text
stringlengths
5
1.04M
// Copyright (C) 2018-2021 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #pragma once #include <cstddef> #include <ostream> #include <vector> #include "ngraph/attribute_adapter.hpp" #include "ngraph/ngraph_visibility.hpp" namespace ngraph { /// \brief A vector of axes. class AxisVector : public std::vector<size_t> { public: NGRAPH_API AxisVector(const std::initializer_list<size_t>& axes); NGRAPH_API AxisVector(const std::vector<size_t>& axes); NGRAPH_API AxisVector(const AxisVector& axes); NGRAPH_API explicit AxisVector(size_t n); template <class InputIterator> AxisVector(InputIterator first, InputIterator last) : std::vector<size_t>(first, last) {} NGRAPH_API AxisVector(); NGRAPH_API ~AxisVector(); NGRAPH_API AxisVector& operator=(const AxisVector& v); NGRAPH_API AxisVector& operator=(AxisVector&& v) noexcept; }; NGRAPH_API std::ostream& operator<<(std::ostream& s, const AxisVector& axis_vector); } // namespace ngraph namespace ov { template <> class NGRAPH_API AttributeAdapter<ngraph::AxisVector> : public IndirectVectorValueAccessor<ngraph::AxisVector, std::vector<int64_t>> { public: AttributeAdapter(ngraph::AxisVector& value) : IndirectVectorValueAccessor<ngraph::AxisVector, std::vector<int64_t>>(value) {} static constexpr DiscreteTypeInfo type_info{"AttributeAdapter<AxisVector>", 0}; const DiscreteTypeInfo& get_type_info() const override { return type_info; } }; } // namespace ov
/* * Copyright (C) 2007, 2010 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "core/css/CSSFontFaceSrcValue.h" #include "core/FetchInitiatorTypeNames.h" #include "core/css/StyleSheetContents.h" #include "core/dom/Document.h" #include "core/dom/Node.h" #include "core/fetch/FetchRequest.h" #include "core/fetch/FontResource.h" #include "core/fetch/ResourceFetcher.h" #include "platform/fonts/FontCache.h" #include "platform/fonts/FontCustomPlatformData.h" #include "wtf/text/StringBuilder.h" namespace blink { bool CSSFontFaceSrcValue::isSupportedFormat() const { // Normally we would just check the format, but in order to avoid conflicts with the old WinIE style of font-face, // we will also check to see if the URL ends with .eot. If so, we'll go ahead and assume that we shouldn't load it. if (m_format.isEmpty()) return m_resource.startsWith("data:", false) || !m_resource.endsWith(".eot", false); return FontCustomPlatformData::supportsFormat(m_format); } String CSSFontFaceSrcValue::customCSSText() const { StringBuilder result; if (isLocal()) result.appendLiteral("local("); else result.appendLiteral("url("); result.append(m_resource); result.append(')'); if (!m_format.isEmpty()) { result.appendLiteral(" format("); result.append(m_format); result.append(')'); } return result.toString(); } bool CSSFontFaceSrcValue::hasFailedOrCanceledSubresources() const { return m_fetched && m_fetched->loadFailedOrCanceled(); } bool CSSFontFaceSrcValue::shouldSetCrossOriginAccessControl(const KURL& resource, SecurityOrigin* securityOrigin) { if (resource.isLocalFile() || resource.protocolIsData()) return false; return !securityOrigin->canRequest(resource); } FontResource* CSSFontFaceSrcValue::fetch(Document* document) { if (!m_fetched) { FetchRequest request(ResourceRequest(document->completeURL(m_resource)), FetchInitiatorTypeNames::css); request.setContentSecurityCheck(m_shouldCheckContentSecurityPolicy); SecurityOrigin* securityOrigin = document->securityOrigin(); if (shouldSetCrossOriginAccessControl(request.url(), securityOrigin)) { request.setCrossOriginAccessControl(securityOrigin, DoNotAllowStoredCredentials); } request.mutableResourceRequest().setHTTPReferrer(m_referrer); m_fetched = document->fetcher()->fetchFont(request); } else { // FIXME: CSSFontFaceSrcValue::fetch is invoked when @font-face rule // is processed by StyleResolver / StyleEngine. restoreCachedResourceIfNeeded(document); } return m_fetched.get(); } void CSSFontFaceSrcValue::restoreCachedResourceIfNeeded(Document* document) { ASSERT(m_fetched); ASSERT(document && document->fetcher()); const String resourceURL = document->completeURL(m_resource); if (document->fetcher()->cachedResource(KURL(ParsedURLString, resourceURL))) return; FetchRequest request(ResourceRequest(resourceURL), FetchInitiatorTypeNames::css); request.setContentSecurityCheck(m_shouldCheckContentSecurityPolicy); document->fetcher()->maybeNotifyInsecureContent(m_fetched.get()); document->fetcher()->requestLoadStarted(m_fetched.get(), request, ResourceFetcher::ResourceLoadingFromCache); } bool CSSFontFaceSrcValue::equals(const CSSFontFaceSrcValue& other) const { return m_isLocal == other.m_isLocal && m_format == other.m_format && m_resource == other.m_resource; } }
/* SUBMITTED BY: Deadeye001 THIS CODE CHECKS IF AN ENTERED NUMBER IS PALINDROME NUMBER OR NOT DATE:01/10/2021 */ #include <bits/stdc++.h> using namespace std; int checkpal(int n) { //function to check if no. is palindrome or not int a=n; int sum=0; while(a!=0) { int d=a%10; sum=(sum*10)+d; a=a/10; } if(sum==n) return 1; else return 0; } int main() { //driver function int n; cin>>n; if(checkpal(n)) cout<<n<<" is a Palindrome number"; else cout<<n<<" is NOT a Palindrome number"; return 0; }
#include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> #include <functional> #include <bits/stdc++.h> using namespace __gnu_pbds; using namespace std; typedef vector<int> vi; typedef vector<long> vl; typedef pair<int,int> pi; typedef pair<long,long> pl; typedef set<int> si; typedef set<long> sl; typedef multiset<int> msi; typedef multiset<long> msl; template <typename T> using indexed_set = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>; // order_of_key: The number of items in a set that are strictly smaller than k // find_by_order: It returns an iterator to the ith largest element //Anubhaw Bhalotia https://github.com/anubhawbhalotia #define fi first #define se second #define mp make_pair #define pb push_back #define lb lower_bound #define ub upper_bound #define beg(x) x.begin() #define en(x) x.end() #define all(v) beg(v), en(v) #define f(i,s,n) for(long i=s;i<n;i++) #define fe(i,s,n) for(long i=s;i<=n;i++) #define fr(i,s,n) for(long i=s;i>n;i--) #define fre(i,s,n) for(long i=s;i>=n;i--) const long MOD = 998244353; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int n; string s; cin>>n; cin>>s; int a = 0, d = 0; f(i, 0, n) { if(s[i] == 'A') a++; else d++; } if(a>d) cout<<"Anton"<<endl; else if(d>a) cout<<"Danik"<<endl; else cout<<"Friendship"<<endl; }
/* * Copyright 2019 Carnegie Technologies * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "sys/CalendarTime.hpp" #include "PrometheusManager.hpp" #include "PrometheusMetric.hpp" #include "PacketDataStoreMetrics.hpp" using namespace Pravala; TextLog PrometheusManager::_log ( "prometheus_manager" ); static PacketDataStoreBlocksGauge gaugePacketDataStoreFreeBlocks ( PacketDataStoreBlocksGauge::TypeFree ); static PacketDataStoreBlocksGauge gaugePacketDataStoreAllocatedBlocks ( PacketDataStoreBlocksGauge::TypeAllocated ); static PacketDataStoreMissesCounter counterPacketDataStoreMisses; PrometheusManager::PrometheusManager(): _maxAllocatedBufSize ( 0 ) { } PrometheusManager & PrometheusManager::get() { static PrometheusManager * global = 0; if ( !global ) { global = new PrometheusManager(); } return *global; } void PrometheusManager::registerMetric ( PrometheusMetric & metricToRegister ) { if ( metricToRegister.Name.isEmpty() ) return; if ( _metrics.contains ( metricToRegister.Name ) ) { LOG ( L_FATAL_ERROR, "Prometheus metric already registered under the same name: '" << metricToRegister.Name << "'" ); assert ( false ); } else { _metrics.insert ( metricToRegister.Name, &metricToRegister ); } } void PrometheusManager::unregisterMetric ( PrometheusMetric & metricToRemove ) { if ( _metrics.remove ( metricToRemove.Name ) < 1 ) { LOG ( L_WARN, "Prometheus metric '" << metricToRemove.Name << "' was not registered" ); } } MemHandle PrometheusManager::getData() { Buffer buf ( _maxAllocatedBufSize ); const uint64_t curTime = CalendarTime::getUTCEpochTimeMs(); for ( HashMap<String, PrometheusMetric *>::Iterator it ( _metrics ); it.isValid(); it.next() ) { it.value()->appendData ( buf, curTime ); } // Save the maximum allocated buffer size for the text exposition internally, so that we can pre-allocate the next // buffer with a size that should be sufficient for what is required. if ( buf.size() > _maxAllocatedBufSize ) { _maxAllocatedBufSize = buf.size(); } return buf.getHandle(); }
// // FunctionCodeGenerator.cpp // Emojicode // // Created by Theo Weidmann on 29/07/2017. // Copyright © 2017 Theo Weidmann. All rights reserved. // #include "FunctionCodeGenerator.hpp" #include "AST/ASTStatements.hpp" #include "Compiler.hpp" #include "RunTimeHelper.hpp" #include "Functions/Function.hpp" #include "Generation/CallCodeGenerator.hpp" #include "Package/Package.hpp" #include "Types/Class.hpp" #include "Types/ValueType.hpp" #include "Types/TypeContext.hpp" #include <llvm/IR/BasicBlock.h> #include <llvm/IR/DerivedTypes.h> #include <llvm/IR/Function.h> #include <llvm/IR/Verifier.h> namespace EmojicodeCompiler { FunctionCodeGenerator::FunctionCodeGenerator(Function *function, llvm::Function *llvmFunc, CodeGenerator *generator) : fn_(function), function_(llvmFunc), scoper_(function->variableCount()), generator_(generator), builder_(generator->context()), typeContext_(std::make_unique<TypeContext>(fn_->typeContext())) {} FunctionCodeGenerator::FunctionCodeGenerator(llvm::Function *llvmFunc, CodeGenerator *generator, std::unique_ptr<TypeContext> tc) : fn_(nullptr), function_(llvmFunc), scoper_(0), generator_(generator), builder_(generator->context()), typeContext_(std::move(tc)) {} void FunctionCodeGenerator::generate() { createEntry(); declareArguments(function_); fn_->ast()->generate(this); if (llvm::verifyFunction(*function_, &llvm::outs())) { auto ows = function()->owner() != nullptr ? function()->owner()->type().toString(fn_->typeContext()) : ""; printf("\nDetected in: %s%s (%s)\n=============\n", ows.c_str(), utf8(fn_->name()).c_str(), function_->getName().str().c_str()); } } void FunctionCodeGenerator::createEntry() { auto basicBlock = llvm::BasicBlock::Create(ctx(), "entry", function_); builder_.SetInsertPoint(basicBlock); } Compiler* FunctionCodeGenerator::compiler() const { return generator()->compiler(); } void FunctionCodeGenerator::declareArguments(llvm::Function *function) { unsigned int i = 0; auto it = function->args().begin(); if (hasThisArgument(fn_)) { (it++)->setName("this"); } for (auto &arg : fn_->parameters()) { auto &llvmArg = *(it++); setVariable(i++, &llvmArg); llvmArg.setName(utf8(arg.name)); } if ((fn_->functionType() == FunctionType::ValueTypeInitializer || fn_->functionType() == FunctionType::ObjectInitializer) && fn_->owner()->storesGenericArgs()) { auto llvmArg = (it++); llvmArg->setName("genericArgs"); builder().CreateStore(llvmArg, genericArgsPtr()); } if (isTypeMethod(fn_) && fn_->owner()->storesGenericArgs()) { auto llvmArg = (it++); llvmArg->setName("genericArgs"); typeMethodGenericArgs_ = llvmArg; } if (!fn_->genericParameters().empty()) { auto llvmArg = (it++); llvmArg->setName("fnGenericArgs"); functionGenericArgs_ = llvmArg; } if (fn_->errorProne()) { it->setName("error"); } } const Type& FunctionCodeGenerator::calleeType() const { return typeContext_->calleeType(); } const SourcePosition& FunctionCodeGenerator::position() const { return fn_->position(); } void FunctionCodeGenerator::setVariable(size_t id, llvm::Value *value, const llvm::Twine &name) { auto alloca = createEntryAlloca(value->getType(), name); builder().CreateStore(value, alloca); scoper_.getVariable(id) = alloca; } void FunctionCodeGenerator::buildErrorReturn() { if (llvmReturnType()->isVoidTy()) { builder().CreateRetVoid(); } else { builder().CreateRet(llvm::UndefValue::get(llvmReturnType())); } } llvm::Value* FunctionCodeGenerator::sizeOfReferencedType(llvm::PointerType *ptrType) { auto one = llvm::ConstantInt::get(llvm::Type::getInt32Ty(ctx()), 1); auto sizeg = builder().CreateGEP(llvm::ConstantPointerNull::getNullValue(ptrType), one); return builder().CreatePtrToInt(sizeg, llvm::Type::getInt64Ty(ctx())); } llvm::Value* FunctionCodeGenerator::sizeOf(llvm::Type *type) { return sizeOfReferencedType(type->getPointerTo()); } Value* FunctionCodeGenerator::buildGetBoxInfoPtr(Value *box) { return builder().CreateConstInBoundsGEP2_32(typeHelper().box(), box, 0, 0); } llvm::Value* FunctionCodeGenerator::buildGetClassInfoPtrFromObject(Value *object) { return builder().CreateConstInBoundsGEP2_32(llvm::cast<llvm::PointerType>(object->getType())->getElementType(), object, 0, 1); // classInfo* } llvm::Value* FunctionCodeGenerator::buildGetClassInfoFromObject(llvm::Value *object) { return builder().CreateLoad(buildGetClassInfoPtrFromObject(object), "info"); } llvm::Value* FunctionCodeGenerator::buildHasNoValueBoxPtr(llvm::Value *box) { return builder().CreateIsNull(builder().CreateLoad(buildGetBoxInfoPtr(box))); } llvm::Value* FunctionCodeGenerator::buildHasNoValueBox(llvm::Value *box) { return builder().CreateIsNull(builder().CreateExtractValue(box, 0)); } Value* FunctionCodeGenerator::buildOptionalHasNoValue(llvm::Value *simpleOptional, const Type &type) { if (type.storageType() == StorageType::PointerOptional) { return builder().CreateIsNull(simpleOptional); } auto vf = builder().CreateExtractValue(simpleOptional, 0); return builder().CreateICmpEQ(vf, llvm::ConstantInt::getFalse(ctx())); } Value* FunctionCodeGenerator::buildOptionalHasValue(llvm::Value *simpleOptional, const Type &type) { if (type.storageType() == StorageType::PointerOptional) { return builder().CreateIsNotNull(simpleOptional); } return builder().CreateExtractValue(simpleOptional, 0); } Value* FunctionCodeGenerator::buildOptionalHasValuePtr(llvm::Value *simpleOptional, const Type &type) { if (type.storageType() == StorageType::PointerOptional) { return builder().CreateIsNotNull(simpleOptional); } auto ptype = llvm::cast<llvm::PointerType>(simpleOptional->getType())->getElementType(); return builder().CreateLoad(builder().CreateConstInBoundsGEP2_32(ptype, simpleOptional, 0, 0)); } Value* FunctionCodeGenerator::buildGetOptionalValuePtr(llvm::Value *simpleOptional, const Type &type) { if (type.storageType() == StorageType::PointerOptional) { return builder().CreateLoad(simpleOptional); } auto ptype = llvm::cast<llvm::PointerType>(simpleOptional->getType())->getElementType(); return builder().CreateConstInBoundsGEP2_32(ptype, simpleOptional, 0, 1); } Value* FunctionCodeGenerator::buildSimpleOptionalWithoutValue(const Type &type) { if (type.storageType() == StorageType::PointerOptional) { return llvm::Constant::getNullValue(typeHelper().llvmTypeFor(type.optionalType())); } auto structType = typeHelper().llvmTypeFor(type); auto undef = llvm::UndefValue::get(structType); return builder().CreateInsertValue(undef, llvm::ConstantInt::getFalse(ctx()), 0); } Value* FunctionCodeGenerator::buildBoxWithoutValue() { auto undef = llvm::UndefValue::get(typeHelper().box()); return builder().CreateInsertValue(undef, llvm::Constant::getNullValue(typeHelper().boxInfo()->getPointerTo()), 0); } Value* FunctionCodeGenerator::buildSimpleOptionalWithValue(llvm::Value *value, const Type &type) { if (type.storageType() == StorageType::PointerOptional) { return value; } auto structType = typeHelper().llvmTypeFor(type); auto undef = llvm::UndefValue::get(structType); auto simpleOptional = builder().CreateInsertValue(undef, value, 1); return builder().CreateInsertValue(simpleOptional, llvm::ConstantInt::getTrue(ctx()), 0); } Value* FunctionCodeGenerator::buildGetOptionalValue(llvm::Value *value, const Type &type) { if (type.storageType() == StorageType::PointerOptional) { return value; } return builder().CreateExtractValue(value, 1); } Value* FunctionCodeGenerator::buildGetBoxValuePtr(Value *box, const Type &type) { auto llvmType = typeHelper().llvmTypeFor(type)->getPointerTo(); return buildGetBoxValuePtr(box, llvmType); } Value* FunctionCodeGenerator::buildGetBoxValuePtr(Value *box, llvm::Type *llvmType) { return builder().CreateBitCast(builder().CreateConstInBoundsGEP2_32(typeHelper().box(), box, 0, 1), llvmType); } llvm::Value* FunctionCodeGenerator::buildGetBoxValuePtrAfter(llvm::Value *box, llvm::Type *llvmType, llvm::Type *after) { auto val = builder().CreateConstInBoundsGEP2_32(typeHelper().box(), box, 0, 1); auto strType = llvm::StructType::get(after, llvmType); auto strPtr = builder().CreateBitCast(val, strType->getPointerTo()); return builder().CreateConstInBoundsGEP2_32(strType, strPtr, 0, 1); } void FunctionCodeGenerator::createIfElseBranchCond(llvm::Value *cond, const std::function<bool()> &then, const std::function<bool()> &otherwise) { auto function = builder().GetInsertBlock()->getParent(); auto success = llvm::BasicBlock::Create(ctx(), "then", function); auto fail = llvm::BasicBlock::Create(ctx(), "else", function); auto mergeBlock = llvm::BasicBlock::Create(ctx(), "cont", function); builder().CreateCondBr(cond, success, fail); builder().SetInsertPoint(success); if (then()) { builder().CreateBr(mergeBlock); } builder().SetInsertPoint(fail); if (otherwise()) { builder().CreateBr(mergeBlock); } builder().SetInsertPoint(mergeBlock); } void FunctionCodeGenerator::createIf(llvm::Value *cond, const std::function<void()> &then) { auto function = builder().GetInsertBlock()->getParent(); auto thenBlock = llvm::BasicBlock::Create(ctx(), "then", function); auto cont = llvm::BasicBlock::Create(ctx(), "cont", function); builder().CreateCondBr(cond, thenBlock, cont); builder().SetInsertPoint(thenBlock); then(); builder().CreateBr(cont); builder().SetInsertPoint(cont); } llvm::BasicBlock* FunctionCodeGenerator::createBlock(const llvm::Twine &name) { auto function = builder().GetInsertBlock()->getParent(); return llvm::BasicBlock::Create(ctx(), name, function); } void FunctionCodeGenerator::createIfElse(llvm::Value *cond, const std::function<void()> &then, const std::function<void()> &otherwise) { createIfElseBranchCond(cond, [then]() { then(); return true; }, [otherwise]() { otherwise(); return true; }); } llvm::Value* FunctionCodeGenerator::createIfElsePhi(llvm::Value* cond, const std::function<llvm::Value* ()> &then, const std::function<llvm::Value *()> &otherwise) { auto function = builder().GetInsertBlock()->getParent(); auto thenBlock = llvm::BasicBlock::Create(ctx(), "then", function); auto otherwiseBlock = llvm::BasicBlock::Create(ctx(), "else", function); auto mergeBlock = llvm::BasicBlock::Create(ctx(), "cont", function); builder().CreateCondBr(cond, thenBlock, otherwiseBlock); builder().SetInsertPoint(thenBlock); auto thenValue = then(); auto thenIncoming = builder().GetInsertBlock(); builder().CreateBr(mergeBlock); builder().SetInsertPoint(otherwiseBlock); auto otherwiseValue = otherwise(); auto otherwiseIncoming = builder().GetInsertBlock(); builder().CreateBr(mergeBlock); builder().SetInsertPoint(mergeBlock); auto phi = builder().CreatePHI(thenValue->getType(), 2); phi->addIncoming(thenValue, thenIncoming); phi->addIncoming(otherwiseValue, otherwiseIncoming); return phi; } std::pair<llvm::Value*, llvm::Value*> FunctionCodeGenerator::createIfElsePhi(llvm::Value* cond, const FunctionCodeGenerator::PairIfElseCallback &then, const FunctionCodeGenerator::PairIfElseCallback &otherwise) { auto function = builder().GetInsertBlock()->getParent(); auto thenBlock = llvm::BasicBlock::Create(ctx(), "then", function); auto otherwiseBlock = llvm::BasicBlock::Create(ctx(), "else", function); auto mergeBlock = llvm::BasicBlock::Create(ctx(), "cont", function); builder().CreateCondBr(cond, thenBlock, otherwiseBlock); builder().SetInsertPoint(thenBlock); auto thenValue = then(); auto thenIncoming = builder().GetInsertBlock(); builder().CreateBr(mergeBlock); builder().SetInsertPoint(otherwiseBlock); auto otherwiseValue = otherwise(); auto otherwiseIncoming = builder().GetInsertBlock(); builder().CreateBr(mergeBlock); builder().SetInsertPoint(mergeBlock); auto phi1 = builder().CreatePHI(thenValue.first->getType(), 2); phi1->addIncoming(thenValue.first, thenIncoming); phi1->addIncoming(otherwiseValue.first, otherwiseIncoming); auto phi2 = builder().CreatePHI(thenValue.second->getType(), 2); phi2->addIncoming(thenValue.second, thenIncoming); phi2->addIncoming(otherwiseValue.second, otherwiseIncoming); return std::make_pair(phi1, phi2); } llvm::ConstantInt* FunctionCodeGenerator::int8(int8_t value) { return llvm::ConstantInt::get(llvm::Type::getInt8Ty(ctx()), value); } llvm::ConstantInt* FunctionCodeGenerator::int16(int16_t value) { return llvm::ConstantInt::get(llvm::Type::getInt16Ty(ctx()), value); } llvm::ConstantInt* FunctionCodeGenerator::int32(int32_t value) { return llvm::ConstantInt::get(llvm::Type::getInt32Ty(ctx()), value); } llvm::ConstantInt* FunctionCodeGenerator::int64(int64_t value) { return llvm::ConstantInt::get(llvm::Type::getInt64Ty(ctx()), value); } llvm::Value* FunctionCodeGenerator::alloc(llvm::PointerType *type) { auto alloc = builder().CreateCall(generator()->runTime().alloc(), sizeOfReferencedType(type), "alloc"); return builder().CreateBitCast(alloc, type); } llvm::Value* FunctionCodeGenerator::stackAlloc(llvm::PointerType *type) { auto structType = llvm::StructType::get(llvm::Type::getInt64Ty(ctx()), type->getElementType()); auto ptr = createEntryAlloca(structType); builder().CreateStore(int64(1), builder().CreateConstInBoundsGEP2_32(structType, ptr, 0, 0)); auto object = builder().CreateConstInBoundsGEP2_32(structType, ptr, 0, 1); auto controlBlockField = builder().CreateConstInBoundsGEP2_32(type->getElementType(), object, 0, 0); builder().CreateStore(llvm::ConstantPointerNull::get(llvm::Type::getInt8PtrTy(ctx())), controlBlockField); return object; } llvm::Value* FunctionCodeGenerator::managableGetValuePtr(llvm::Value *managablePtr) { auto elementType = llvm::dyn_cast<llvm::PointerType>(managablePtr->getType())->getElementType(); return builder().CreateConstInBoundsGEP2_32(elementType, managablePtr, 0, 1); } llvm::Value* FunctionCodeGenerator::createEntryAlloca(llvm::Type *type, const llvm::Twine &name) { llvm::IRBuilder<> builder(&function_->getEntryBlock(), function_->getEntryBlock().begin()); return builder.CreateAlloca(type, nullptr, name); } llvm::Constant* FunctionCodeGenerator::boxInfoFor(const Type &type) { return generator()->boxInfoFor(type); } void TemporaryObjectsManager::releaseTemporaryObjects(FunctionCodeGenerator *fg, bool clearQueue, bool skipLast) { if (temporaryObjects_.empty()) return; auto end = skipLast ? temporaryObjects_.end() - 1 : temporaryObjects_.end(); for (auto it = temporaryObjects_.begin(); it < end; it++) { fg->release(it->value, it->type); } if (clearQueue) { temporaryObjects_.clear(); } } void FunctionCodeGenerator::release(llvm::Value *value, const Type &otype) { auto type = otype.resolveOnSuperArgumentsAndConstraints(*typeContext_); if (type.type() == TypeType::Class || type.type() == TypeType::Someobject) { auto opc = builder().CreateBitCast(value, llvm::Type::getInt8PtrTy(ctx())); builder().CreateCall(generator()->runTime().release(), opc); } else if (type.type() == TypeType::ValueType && type.valueType() == compiler()->sMemory) { builder().CreateCall(generator()->runTime().releaseMemory(), value); } else if (type.type() == TypeType::ValueType) { builder().CreateCall(type.valueType()->destructor(), value); } else if (type.type() == TypeType::Optional) { if (isManagedByReference(type)) { createIf(buildOptionalHasValuePtr(value, type), [&] { release(buildGetOptionalValuePtr(value, type), type.optionalType()); }); } else { createIf(buildOptionalHasValue(value, type), [&] { release(buildGetOptionalValue(value, type), type.optionalType()); }); } } else if (type.type() == TypeType::Box) { auto boxInfo = builder().CreateLoad(buildGetBoxInfoPtr(value)); if (type.unboxed().type() == TypeType::Optional || type.unboxed().type() == TypeType::Something) { auto null = llvm::ConstantPointerNull::get(typeHelper().boxInfo()->getPointerTo()); createIf(builder().CreateICmpNE(boxInfo, null), [&] { manageBox(false, boxInfo, value, type); }); } else { manageBox(false, boxInfo, value, type); } } else if (type.type() == TypeType::Callable) { builder().CreateCall(generator()->runTime().releaseCapture(), builder().CreateExtractValue(value, 1)); } } void FunctionCodeGenerator::retain(llvm::Value *value, const Type &otype) { auto type = otype.resolveOnSuperArgumentsAndConstraints(*typeContext_); if (type.type() == TypeType::Class || type.type() == TypeType::Someobject) { auto opc = builder().CreateBitCast(value, llvm::Type::getInt8PtrTy(ctx())); builder().CreateCall(generator()->runTime().retain(), { opc }); } else if (type.type() == TypeType::ValueType && type.valueType() == compiler()->sMemory) { builder().CreateCall(generator()->runTime().retainMemory(), value); } else if (type.type() == TypeType::Callable) { builder().CreateCall(generator()->runTime().retain(), builder().CreateExtractValue(value, 1)); } else if (type.type() == TypeType::ValueType) { builder().CreateCall(type.valueType()->copyRetain(), value); } else if (type.type() == TypeType::Optional) { if (isManagedByReference(type)) { createIf(buildOptionalHasValuePtr(value, type), [&] { retain(buildGetOptionalValuePtr(value, type), type.optionalType()); }); } else { createIf(buildOptionalHasValue(value, type), [&] { retain(buildGetOptionalValue(value, type), type.optionalType()); }); } } else if (type.type() == TypeType::Box) { auto boxInfo = builder().CreateLoad(buildGetBoxInfoPtr(value)); if (type.unboxed().type() == TypeType::Optional || type.unboxed().type() == TypeType::Something) { auto null = llvm::ConstantPointerNull::get(typeHelper().boxInfo()->getPointerTo()); createIf(builder().CreateICmpNE(boxInfo, null), [&] { manageBox(true, boxInfo, value, type); }); } else { manageBox(true, boxInfo, value, type); } } } void FunctionCodeGenerator::manageBox(bool retain, llvm::Value *boxInfo, llvm::Value *value, const Type &type) { llvm::Value *fnPtr; if (type.boxedFor().type() == TypeType::Protocol) { auto conf = builder().CreateBitCast(boxInfo, typeHelper().protocolConformance()->getPointerTo()); fnPtr = builder().CreateConstInBoundsGEP2_32(typeHelper().protocolConformance(), conf, 0, retain ? 3 : 4); } else { fnPtr = builder().CreateConstInBoundsGEP2_32(typeHelper().boxInfo(), boxInfo, 0, retain ? 1 : 2); } auto call = builder().CreateCall(builder().CreateLoad(fnPtr, retain ? "retain" : "release"), value); call->addParamAttr(0, llvm::Attribute::NoCapture); call->addParamAttr(0, llvm::Attribute::ReadOnly); call->addAttribute(llvm::AttributeList::FunctionIndex, llvm::Attribute::NoUnwind); } bool FunctionCodeGenerator::isManagedByReference(const Type &type) const { return (type.type() == TypeType::ValueType && !type.valueType()->isPrimitive()) || type.type() == TypeType::Box || (type.type() == TypeType::Optional && isManagedByReference(type.optionalType())); } void FunctionCodeGenerator::releaseByReference(llvm::Value *ptr, const Type &type) { release(isManagedByReference(type) ? ptr : builder().CreateLoad(ptr), type); } llvm::Value* FunctionCodeGenerator::buildFindProtocolConformance(llvm::Value *box, llvm::Value *boxInfo, llvm::Value *protocolRTTI) { auto objBoxInfo = builder().CreateBitCast(generator()->runTime().boxInfoForObjects(), typeHelper().boxInfo()->getPointerTo()); auto conformanceEntries = createIfElsePhi(builder().CreateICmpEQ(boxInfo, objBoxInfo), [&]() { auto obj = builder().CreateLoad(buildGetBoxValuePtr(box, typeHelper().someobject()->getPointerTo())); auto classInfo = buildGetClassInfoFromObject(obj); return builder().CreateLoad(builder().CreateConstInBoundsGEP2_32(typeHelper().classInfo(), classInfo, 0, 2)); }, [&] { auto conformanceEntriesPtr = builder().CreateConstInBoundsGEP2_32(typeHelper().boxInfo(), boxInfo, 0, 3); return builder().CreateLoad(conformanceEntriesPtr); }); return builder().CreateCall(generator()->runTime().findProtocolConformance(), { conformanceEntries, protocolRTTI }); } llvm::Value* FunctionCodeGenerator::instanceVariablePointer(size_t id) { auto callee = typeContext_->calleeType(); auto offset = callee.type() != TypeType::NoReturn ? (callee.type() == TypeType::Class ? 2 : 0) + (callee.typeDefinition()->storesGenericArgs() ? 1 : 0) : 0; auto type = llvm::cast<llvm::PointerType>(thisValue()->getType())->getElementType(); return builder().CreateConstInBoundsGEP2_32(type, thisValue(), 0, offset + id); } llvm::Value* FunctionCodeGenerator::genericArgsPtr() { if (fn_ != nullptr && isTypeMethod(fn_)) { return typeMethodGenericArgs_; } auto callee = typeContext_->calleeType(); assert(callee.typeDefinition()->storesGenericArgs()); auto type = llvm::cast<llvm::PointerType>(thisValue()->getType())->getElementType(); return builder().CreateConstInBoundsGEP2_32(type, thisValue(), 0, callee.type() == TypeType::Class ? 2 : 0); } FunctionCodeGenerator::~FunctionCodeGenerator() = default; } // namespace EmojicodeCompiler
/* Code generated by IfcQuery EXPRESS generator, www.ifcquery.com */ #include <sstream> #include <limits> #include "ifcpp/model/AttributeObject.h" #include "ifcpp/model/BuildingException.h" #include "ifcpp/model/BuildingGuid.h" #include "ifcpp/reader/ReaderUtil.h" #include "ifcpp/writer/WriterUtil.h" #include "ifcpp/IFC4/include/IfcGlobalOrLocalEnum.h" #include "ifcpp/IFC4/include/IfcGloballyUniqueId.h" #include "ifcpp/IFC4/include/IfcLabel.h" #include "ifcpp/IFC4/include/IfcObjectPlacement.h" #include "ifcpp/IFC4/include/IfcOwnerHistory.h" #include "ifcpp/IFC4/include/IfcProductRepresentation.h" #include "ifcpp/IFC4/include/IfcRelAggregates.h" #include "ifcpp/IFC4/include/IfcRelAssigns.h" #include "ifcpp/IFC4/include/IfcRelAssignsToProduct.h" #include "ifcpp/IFC4/include/IfcRelAssociates.h" #include "ifcpp/IFC4/include/IfcRelConnectsStructuralActivity.h" #include "ifcpp/IFC4/include/IfcRelDeclares.h" #include "ifcpp/IFC4/include/IfcRelDefinesByObject.h" #include "ifcpp/IFC4/include/IfcRelDefinesByProperties.h" #include "ifcpp/IFC4/include/IfcRelDefinesByType.h" #include "ifcpp/IFC4/include/IfcRelNests.h" #include "ifcpp/IFC4/include/IfcStructuralLoad.h" #include "ifcpp/IFC4/include/IfcStructuralSurfaceActivityTypeEnum.h" #include "ifcpp/IFC4/include/IfcStructuralSurfaceReaction.h" #include "ifcpp/IFC4/include/IfcText.h" // ENTITY IfcStructuralSurfaceReaction IfcStructuralSurfaceReaction::IfcStructuralSurfaceReaction( int id ) { m_entity_id = id; } shared_ptr<BuildingObject> IfcStructuralSurfaceReaction::getDeepCopy( BuildingCopyOptions& options ) { shared_ptr<IfcStructuralSurfaceReaction> copy_self( new IfcStructuralSurfaceReaction() ); if( m_GlobalId ) { if( options.create_new_IfcGloballyUniqueId ) { copy_self->m_GlobalId = make_shared<IfcGloballyUniqueId>( createBase64Uuid<wchar_t>().data() ); } else { copy_self->m_GlobalId = dynamic_pointer_cast<IfcGloballyUniqueId>( m_GlobalId->getDeepCopy(options) ); } } if( m_OwnerHistory ) { if( options.shallow_copy_IfcOwnerHistory ) { copy_self->m_OwnerHistory = m_OwnerHistory; } else { copy_self->m_OwnerHistory = dynamic_pointer_cast<IfcOwnerHistory>( m_OwnerHistory->getDeepCopy(options) ); } } if( m_Name ) { copy_self->m_Name = dynamic_pointer_cast<IfcLabel>( m_Name->getDeepCopy(options) ); } if( m_Description ) { copy_self->m_Description = dynamic_pointer_cast<IfcText>( m_Description->getDeepCopy(options) ); } if( m_ObjectType ) { copy_self->m_ObjectType = dynamic_pointer_cast<IfcLabel>( m_ObjectType->getDeepCopy(options) ); } if( m_ObjectPlacement ) { copy_self->m_ObjectPlacement = dynamic_pointer_cast<IfcObjectPlacement>( m_ObjectPlacement->getDeepCopy(options) ); } if( m_Representation ) { copy_self->m_Representation = dynamic_pointer_cast<IfcProductRepresentation>( m_Representation->getDeepCopy(options) ); } if( m_AppliedLoad ) { copy_self->m_AppliedLoad = dynamic_pointer_cast<IfcStructuralLoad>( m_AppliedLoad->getDeepCopy(options) ); } if( m_GlobalOrLocal ) { copy_self->m_GlobalOrLocal = dynamic_pointer_cast<IfcGlobalOrLocalEnum>( m_GlobalOrLocal->getDeepCopy(options) ); } if( m_PredefinedType ) { copy_self->m_PredefinedType = dynamic_pointer_cast<IfcStructuralSurfaceActivityTypeEnum>( m_PredefinedType->getDeepCopy(options) ); } return copy_self; } void IfcStructuralSurfaceReaction::getStepLine( std::stringstream& stream ) const { stream << "#" << m_entity_id << "= IFCSTRUCTURALSURFACEREACTION" << "("; if( m_GlobalId ) { m_GlobalId->getStepParameter( stream ); } else { stream << "$"; } stream << ","; if( m_OwnerHistory ) { stream << "#" << m_OwnerHistory->m_entity_id; } else { stream << "$"; } stream << ","; if( m_Name ) { m_Name->getStepParameter( stream ); } else { stream << "$"; } stream << ","; if( m_Description ) { m_Description->getStepParameter( stream ); } else { stream << "$"; } stream << ","; if( m_ObjectType ) { m_ObjectType->getStepParameter( stream ); } else { stream << "$"; } stream << ","; if( m_ObjectPlacement ) { stream << "#" << m_ObjectPlacement->m_entity_id; } else { stream << "$"; } stream << ","; if( m_Representation ) { stream << "#" << m_Representation->m_entity_id; } else { stream << "$"; } stream << ","; if( m_AppliedLoad ) { stream << "#" << m_AppliedLoad->m_entity_id; } else { stream << "$"; } stream << ","; if( m_GlobalOrLocal ) { m_GlobalOrLocal->getStepParameter( stream ); } else { stream << "$"; } stream << ","; if( m_PredefinedType ) { m_PredefinedType->getStepParameter( stream ); } else { stream << "$"; } stream << ");"; } void IfcStructuralSurfaceReaction::getStepParameter( std::stringstream& stream, bool /*is_select_type*/ ) const { stream << "#" << m_entity_id; } const std::wstring IfcStructuralSurfaceReaction::toString() const { return L"IfcStructuralSurfaceReaction"; } void IfcStructuralSurfaceReaction::readStepArguments( const std::vector<std::wstring>& args, const std::map<int,shared_ptr<BuildingEntity> >& map ) { const size_t num_args = args.size(); if( num_args != 10 ){ std::stringstream err; err << "Wrong parameter count for entity IfcStructuralSurfaceReaction, expecting 10, having " << num_args << ". Entity ID: " << m_entity_id << std::endl; throw BuildingException( err.str().c_str() ); } m_GlobalId = IfcGloballyUniqueId::createObjectFromSTEP( args[0], map ); readEntityReference( args[1], m_OwnerHistory, map ); m_Name = IfcLabel::createObjectFromSTEP( args[2], map ); m_Description = IfcText::createObjectFromSTEP( args[3], map ); m_ObjectType = IfcLabel::createObjectFromSTEP( args[4], map ); readEntityReference( args[5], m_ObjectPlacement, map ); readEntityReference( args[6], m_Representation, map ); readEntityReference( args[7], m_AppliedLoad, map ); m_GlobalOrLocal = IfcGlobalOrLocalEnum::createObjectFromSTEP( args[8], map ); m_PredefinedType = IfcStructuralSurfaceActivityTypeEnum::createObjectFromSTEP( args[9], map ); } void IfcStructuralSurfaceReaction::getAttributes( std::vector<std::pair<std::string, shared_ptr<BuildingObject> > >& vec_attributes ) const { IfcStructuralReaction::getAttributes( vec_attributes ); vec_attributes.emplace_back( std::make_pair( "PredefinedType", m_PredefinedType ) ); } void IfcStructuralSurfaceReaction::getAttributesInverse( std::vector<std::pair<std::string, shared_ptr<BuildingObject> > >& vec_attributes_inverse ) const { IfcStructuralReaction::getAttributesInverse( vec_attributes_inverse ); } void IfcStructuralSurfaceReaction::setInverseCounterparts( shared_ptr<BuildingEntity> ptr_self_entity ) { IfcStructuralReaction::setInverseCounterparts( ptr_self_entity ); } void IfcStructuralSurfaceReaction::unlinkFromInverseCounterparts() { IfcStructuralReaction::unlinkFromInverseCounterparts(); }
/******************************************************************************* * Copyright (C) 2022 Intel Corporation * * SPDX-License-Identifier: MIT ******************************************************************************/ #include "qpl/qpl.h" #include "../c_api/own_defs.h" qpl_status qpl_get_index_table_size(uint32_t mini_block_count, uint32_t mini_blocks_per_block, size_t *size_ptr) { QPL_BAD_PTR_RET(size_ptr); uint32_t block_count = (mini_block_count + mini_blocks_per_block - 1u) / mini_blocks_per_block; *size_ptr = block_count * 2u + mini_block_count + 1u; return QPL_STS_OK; } qpl_status qpl_set_mini_block_location(uint32_t start_bit, uint32_t last_bit, uint8_t **source_pptr, uint32_t *first_bit_offset_ptr, uint32_t *last_bit_offset_ptr, uint32_t *compressed_size_ptr) { QPL_BAD_PTR2_RET(source_pptr, *source_pptr); QPL_BAD_PTR_RET(first_bit_offset_ptr); QPL_BAD_PTR_RET(last_bit_offset_ptr); QPL_BAD_PTR_RET(compressed_size_ptr); *first_bit_offset_ptr = start_bit & 7; *last_bit_offset_ptr = 7 & (0 - last_bit); *compressed_size_ptr = ((last_bit + 7) / 8) - (start_bit / 8); *source_pptr += start_bit / 8; return QPL_STS_OK; } qpl_status qpl_find_header_block_index(qpl_index_table *table_ptr, uint32_t mini_block_number, uint32_t *block_index_ptr) { QPL_BAD_PTR_RET(table_ptr); QPL_BAD_PTR_RET(block_index_ptr); OWN_RETURN_ERROR(mini_block_number >= table_ptr->mini_block_count, QPL_STS_SIZE_ERR); uint32_t blockNumber = mini_block_number / table_ptr->mini_blocks_per_block; *block_index_ptr = blockNumber * (table_ptr->mini_blocks_per_block + 2u); return QPL_STS_OK; } qpl_status qpl_find_mini_block_index(qpl_index_table *table_ptr, uint32_t mini_block_number, uint32_t *block_index_ptr) { QPL_BAD_PTR_RET(table_ptr); QPL_BAD_PTR_RET(block_index_ptr); OWN_RETURN_ERROR(mini_block_number >= table_ptr->mini_block_count, QPL_STS_SIZE_ERR); uint32_t currentHeaderIndex = 0u; qpl_status status = qpl_find_header_block_index(table_ptr, mini_block_number, &currentHeaderIndex); if (status) { return status; } uint32_t blockNumber = mini_block_number / table_ptr->mini_blocks_per_block; uint32_t miniBlockNumberInBlock = mini_block_number - blockNumber * table_ptr->mini_blocks_per_block; *block_index_ptr = currentHeaderIndex + 1u + miniBlockNumberInBlock; return QPL_STS_OK; }
//***************************************************************************** // Copyright 2017-2018 Intel Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //***************************************************************************** #include "ngraph/op/function_call.hpp" #include <pybind11/pybind11.h> #include <pybind11/stl.h> #include "ngraph/function.hpp" #include "pyngraph/ops/function_call.hpp" namespace py = pybind11; void regclass_pyngraph_op_FunctionCall(py::module m) { py::class_<ngraph::op::FunctionCall, std::shared_ptr<ngraph::op::FunctionCall>, ngraph::Node> function_call(m, "FunctionCall"); function_call.doc() = "ngraph.impl.op.FunctionCall wraps ngraph::op::FunctionCall"; function_call.def(py::init<std::shared_ptr<ngraph::Function>, const ngraph::NodeVector&>()); }
//============================================================================ // Copyright (c) Kitware, Inc. // All rights reserved. // See LICENSE.txt for details. // // This software is distributed WITHOUT ANY WARRANTY; without even // the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR // PURPOSE. See the above copyright notice for more information. //============================================================================ #include <vtkm/cont/tbb/DeviceAdapterTBB.h> #include <vtkm/cont/testing/TestingColorTable.h> int UnitTestTBBColorTable(int argc, char* argv[]) { auto& tracker = vtkm::cont::GetRuntimeDeviceTracker(); tracker.ForceDevice(vtkm::cont::DeviceAdapterTagTBB{}); return vtkm::cont::testing::TestingColorTable<vtkm::cont::DeviceAdapterTagTBB>::Run(argc, argv); }
/**************************************************************************** ** Meta object code from reading C++ file 'ActionEditor.h' ** ** Created by: The Qt Meta Object Compiler version 68 (Qt 6.2.2) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include <memory> #include "../../../ActionEditor.h" #include <QtCore/qbytearray.h> #include <QtCore/qmetatype.h> #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'ActionEditor.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 68 #error "This file was generated using the moc from 6.2.2. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE QT_WARNING_PUSH QT_WARNING_DISABLE_DEPRECATED struct qt_meta_stringdata_ActionEditor_t { const uint offsetsAndSize[16]; char stringdata0[102]; }; #define QT_MOC_LITERAL(ofs, len) \ uint(offsetof(qt_meta_stringdata_ActionEditor_t, stringdata0) + ofs), len static const qt_meta_stringdata_ActionEditor_t qt_meta_stringdata_ActionEditor = { { QT_MOC_LITERAL(0, 12), // "ActionEditor" QT_MOC_LITERAL(13, 12), // "addKeyAction" QT_MOC_LITERAL(26, 0), // "" QT_MOC_LITERAL(27, 15), // "deleteKeyAction" QT_MOC_LITERAL(43, 21), // "listContextMenuAction" QT_MOC_LITERAL(65, 3), // "pos" QT_MOC_LITERAL(69, 16), // "saveActionAction" QT_MOC_LITERAL(86, 15) // "openFileChooser" }, "ActionEditor\0addKeyAction\0\0deleteKeyAction\0" "listContextMenuAction\0pos\0saveActionAction\0" "openFileChooser" }; #undef QT_MOC_LITERAL static const uint qt_meta_data_ActionEditor[] = { // content: 10, // revision 0, // classname 0, 0, // classinfo 5, 14, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 0, // signalCount // slots: name, argc, parameters, tag, flags, initial metatype offsets 1, 0, 44, 2, 0x08, 1 /* Private */, 3, 0, 45, 2, 0x08, 2 /* Private */, 4, 1, 46, 2, 0x08, 3 /* Private */, 6, 0, 49, 2, 0x08, 5 /* Private */, 7, 0, 50, 2, 0x08, 6 /* Private */, // slots: parameters QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::QPoint, 5, QMetaType::Void, QMetaType::Void, 0 // eod }; void ActionEditor::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) { if (_c == QMetaObject::InvokeMetaMethod) { auto *_t = static_cast<ActionEditor *>(_o); (void)_t; switch (_id) { case 0: _t->addKeyAction(); break; case 1: _t->deleteKeyAction(); break; case 2: _t->listContextMenuAction((*reinterpret_cast< const QPoint(*)>(_a[1]))); break; case 3: _t->saveActionAction(); break; case 4: _t->openFileChooser(); break; default: ; } } } const QMetaObject ActionEditor::staticMetaObject = { { QMetaObject::SuperData::link<QWidget::staticMetaObject>(), qt_meta_stringdata_ActionEditor.offsetsAndSize, qt_meta_data_ActionEditor, qt_static_metacall, nullptr, qt_incomplete_metaTypeArray<qt_meta_stringdata_ActionEditor_t , QtPrivate::TypeAndForceComplete<ActionEditor, std::true_type> , QtPrivate::TypeAndForceComplete<void, std::false_type>, QtPrivate::TypeAndForceComplete<void, std::false_type>, QtPrivate::TypeAndForceComplete<void, std::false_type>, QtPrivate::TypeAndForceComplete<const QPoint &, std::false_type>, QtPrivate::TypeAndForceComplete<void, std::false_type>, QtPrivate::TypeAndForceComplete<void, std::false_type> >, nullptr } }; const QMetaObject *ActionEditor::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; } void *ActionEditor::qt_metacast(const char *_clname) { if (!_clname) return nullptr; if (!strcmp(_clname, qt_meta_stringdata_ActionEditor.stringdata0)) return static_cast<void*>(this); return QWidget::qt_metacast(_clname); } int ActionEditor::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QWidget::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { if (_id < 5) qt_static_metacall(this, _c, _id, _a); _id -= 5; } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { if (_id < 5) *reinterpret_cast<QMetaType *>(_a[0]) = QMetaType(); _id -= 5; } return _id; } QT_WARNING_POP QT_END_MOC_NAMESPACE
////////////////////////////////////////////////////////////////////////////// // // (C) Copyright Ion Gaztanaga 2006. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // // See http://www.boost.org/libs/interprocess for documentation. // ////////////////////////////////////////////////////////////////////////////// #ifndef BOOST_INTERPROCESS_TEST_MEMORY_ALGORITHM_TEST_TEMPLATE_HEADER #define BOOST_INTERPROCESS_TEST_MEMORY_ALGORITHM_TEST_TEMPLATE_HEADER #include <boost/interprocess/detail/config_begin.hpp> #include <vector> #include <iostream> #include <new> #include <utility> #include <cstring> //std::memset #include <cstdio> //std::remove namespace boost { namespace interprocess { namespace test { enum deallocation_type { DirectDeallocation, InverseDeallocation, MixedDeallocation, EndDeallocationType }; //This test allocates until there is no more memory //and after that deallocates all in the inverse order template<class Allocator> bool test_allocation(Allocator &a) { for( deallocation_type t = DirectDeallocation ; t != EndDeallocationType ; t = (deallocation_type)((int)t + 1)){ std::vector<void*> buffers; std::size_t free_memory = a.get_free_memory(); for(int i = 0; true; ++i){ void *ptr = a.allocate(i, std::nothrow); if(!ptr) break; std::size_t size = a.size(ptr); std::memset(ptr, 0, size); buffers.push_back(ptr); } switch(t){ case DirectDeallocation: { for(int j = 0, max = (int)buffers.size() ;j < max ;++j){ a.deallocate(buffers[j]); } } break; case InverseDeallocation: { for(int j = (int)buffers.size() ;j-- ;){ a.deallocate(buffers[j]); } } break; case MixedDeallocation: { for(int j = 0, max = (int)buffers.size() ;j < max ;++j){ int pos = (j%4)*((int)buffers.size())/4; a.deallocate(buffers[pos]); buffers.erase(buffers.begin()+pos); } } break; default: break; } bool ok = free_memory == a.get_free_memory() && a.all_memory_deallocated() && a.check_sanity(); if(!ok) return ok; } return true; } //This test allocates until there is no more memory //and after that tries to shrink all the buffers to the //half of the original size template<class Allocator> bool test_allocation_shrink(Allocator &a) { std::vector<void*> buffers; //Allocate buffers with extra memory for(int i = 0; true; ++i){ void *ptr = a.allocate(i*2, std::nothrow); if(!ptr) break; std::size_t size = a.size(ptr); std::memset(ptr, 0, size); buffers.push_back(ptr); } //Now shrink to half for(int i = 0, max = (int)buffers.size() ;i < max ; ++i){ std::size_t received_size; if(a.template allocation_command<char> ( shrink_in_place | nothrow_allocation, i*2 , i, received_size, static_cast<char*>(buffers[i])).first){ if(received_size > std::size_t(i*2)){ return false; } if(received_size < std::size_t(i)){ return false; } std::memset(buffers[i], 0, a.size(buffers[i])); } } //Deallocate it in non sequential order for(int j = 0, max = (int)buffers.size() ;j < max ;++j){ int pos = (j%4)*((int)buffers.size())/4; a.deallocate(buffers[pos]); buffers.erase(buffers.begin()+pos); } return a.all_memory_deallocated() && a.check_sanity(); } //This test allocates until there is no more memory //and after that tries to expand all the buffers to //avoid the wasted internal fragmentation template<class Allocator> bool test_allocation_expand(Allocator &a) { std::vector<void*> buffers; //Allocate buffers with extra memory for(int i = 0; true; ++i){ void *ptr = a.allocate(i, std::nothrow); if(!ptr) break; std::size_t size = a.size(ptr); std::memset(ptr, 0, size); buffers.push_back(ptr); } //Now try to expand to the double of the size for(int i = 0, max = (int)buffers.size() ;i < max ;++i){ std::size_t received_size; std::size_t min_size = i+1; std::size_t preferred_size = i*2; preferred_size = min_size > preferred_size ? min_size : preferred_size; while(a.template allocation_command<char> ( expand_fwd | nothrow_allocation, min_size , preferred_size, received_size, static_cast<char*>(buffers[i])).first){ //Check received size is bigger than minimum if(received_size < min_size){ return false; } //Now, try to expand further min_size = received_size+1; preferred_size = min_size*2; } } //Deallocate it in non sequential order for(int j = 0, max = (int)buffers.size() ;j < max ;++j){ int pos = (j%4)*((int)buffers.size())/4; a.deallocate(buffers[pos]); buffers.erase(buffers.begin()+pos); } return a.all_memory_deallocated() && a.check_sanity(); } //This test allocates until there is no more memory //and after that tries to expand all the buffers to //avoid the wasted internal fragmentation template<class Allocator> bool test_allocation_shrink_and_expand(Allocator &a) { std::vector<void*> buffers; std::vector<std::size_t> received_sizes; std::vector<bool> size_reduced; //Allocate buffers wand store received sizes for(int i = 0; true; ++i){ std::size_t received_size; void *ptr = a.template allocation_command<char> ( allocate_new | nothrow_allocation, i, i*2, received_size).first; if(!ptr){ ptr = a.template allocation_command<char> ( allocate_new | nothrow_allocation, 1, i*2, received_size).first; if(!ptr) break; } buffers.push_back(ptr); received_sizes.push_back(received_size); } //Now shrink to half for(int i = 0, max = (int)buffers.size() ; i < max ; ++i){ std::size_t received_size; if(a.template allocation_command<char> ( shrink_in_place | nothrow_allocation, received_sizes[i] , i, received_size, static_cast<char*>(buffers[i])).first){ if(received_size > std::size_t(received_sizes[i])){ return false; } if(received_size < std::size_t(i)){ return false; } size_reduced.push_back(received_size != received_sizes[i]); } } //Now try to expand to the original size for(int i = 0, max = (int)buffers.size() ;i < max ;++i){ std::size_t received_size; std::size_t request_size = received_sizes[i]; if(a.template allocation_command<char> ( expand_fwd | nothrow_allocation, request_size , request_size, received_size, static_cast<char*>(buffers[i])).first){ if(received_size != received_sizes[i]){ return false; } } else{ return false; } } //Deallocate it in non sequential order for(int j = 0, max = (int)buffers.size() ;j < max ;++j){ int pos = (j%4)*((int)buffers.size())/4; a.deallocate(buffers[pos]); buffers.erase(buffers.begin()+pos); } return a.all_memory_deallocated() && a.check_sanity(); } //This test allocates until there is no more memory //and after that deallocates the odd buffers to //make room for expansions. The expansion will probably //success since the deallocation left room for that. template<class Allocator> bool test_allocation_deallocation_expand(Allocator &a) { std::vector<void*> buffers; //Allocate buffers with extra memory for(int i = 0; true; ++i){ void *ptr = a.allocate(i, std::nothrow); if(!ptr) break; std::size_t size = a.size(ptr); std::memset(ptr, 0, size); buffers.push_back(ptr); } //Now deallocate the half of the blocks //so expand maybe can merge new free blocks for(int i = 0, max = (int)buffers.size() ;i < max ;++i){ if(i%2){ a.deallocate(buffers[i]); buffers[i] = 0; } } //Now try to expand to the double of the size for(int i = 0, max = (int)buffers.size() ;i < max ;++i){ // if(buffers[i]){ std::size_t received_size; std::size_t min_size = i+1; std::size_t preferred_size = i*2; preferred_size = min_size > preferred_size ? min_size : preferred_size; while(a.template allocation_command<char> ( expand_fwd | nothrow_allocation, min_size , preferred_size, received_size, static_cast<char*>(buffers[i])).first){ //Check received size is bigger than minimum if(received_size < min_size){ return false; } //Now, try to expand further min_size = received_size+1; preferred_size = min_size*2; } } } //Now erase null values from the vector buffers.erase( std::remove(buffers.begin(), buffers.end(), static_cast<void*>(0)) , buffers.end()); //Deallocate it in non sequential order for(int j = 0, max = (int)buffers.size() ;j < max ;++j){ int pos = (j%4)*((int)buffers.size())/4; a.deallocate(buffers[pos]); buffers.erase(buffers.begin()+pos); } return a.all_memory_deallocated() && a.check_sanity(); } //This test allocates until there is no more memory //and after that deallocates all except the last. //If the allocation algorithm is a bottom-up algorithm //the last buffer will be in the end of the segment. //Then the test will start expanding backwards, until //the buffer fills all the memory template<class Allocator> bool test_allocation_with_reuse(Allocator &a) { //We will repeat this test for different sized elements for(int sizeof_object = 1; sizeof_object < 20; ++sizeof_object){ std::vector<void*> buffers; //Allocate buffers with extra memory for(int i = 0; true; ++i){ void *ptr = a.allocate(i*sizeof_object, std::nothrow); if(!ptr) break; std::size_t size = a.size(ptr); std::memset(ptr, 0, size); buffers.push_back(ptr); } //Now deallocate all except the latest //Now try to expand to the double of the sizeof_object for(int i = 0, max = (int)buffers.size() - 1 ;i < max ;++i){ a.deallocate(buffers[i]); } //Save the unique buffer and clear vector void *ptr = buffers.back(); buffers.clear(); //Now allocate with reuse std::size_t received_size = 0; for(int i = 0; true; ++i){ std::size_t min_size = (received_size + 1); std::size_t prf_size = (received_size + (i+1)*2); std::pair<void*, bool> ret = a.raw_allocation_command ( expand_bwd | nothrow_allocation, min_size , prf_size, received_size, static_cast<char*>(ptr), sizeof_object); if(!ret.first) break; //If we have memory, this must be a buffer reuse if(!ret.second) return 1; if(received_size < min_size) return 1; ptr = ret.first; } //There is only a single block so deallocate it a.deallocate(ptr); if(!a.all_memory_deallocated() || !a.check_sanity()) return false; } return true; } //This test allocates memory with different alignments //and checks returned memory is aligned. template<class Allocator> bool test_aligned_allocation(Allocator &a) { //Allocate aligned buffers in a loop //and then deallocate it bool continue_loop = true; for(unsigned int i = 1; continue_loop; i <<= 1){ for(unsigned int j = 1; true; j <<= 1){ void *ptr = a.allocate_aligned(i-1, j, std::nothrow); if(!ptr){ if(j == 1) continue_loop = false; break; } if(((std::size_t)ptr & (j - 1)) != 0) return false; a.deallocate(ptr); if(!a.all_memory_deallocated() || !a.check_sanity()){ return false; } } } return a.all_memory_deallocated() && a.check_sanity(); } //This test allocates memory with different alignments //and checks returned memory is aligned. template<class Allocator> bool test_continuous_aligned_allocation(Allocator &a) { std::vector<void*> buffers; //Allocate aligned buffers in a loop //and then deallocate it bool continue_loop = true; for(unsigned i = 1; continue_loop && i; i <<= 1){ for(unsigned int j = 1; j; j <<= 1){ for(bool any_allocated = false; 1;){ void *ptr = a.allocate_aligned(i-1, j, std::nothrow); buffers.push_back(ptr); if(!ptr){ if(j == 1 && !any_allocated){ continue_loop = false; } break; } else{ any_allocated = true; } if(((std::size_t)ptr & (j - 1)) != 0) return false; } //Deallocate all for(unsigned int k = (int)buffers.size(); k--;){ a.deallocate(buffers[k]); } buffers.clear(); if(!a.all_memory_deallocated() && a.check_sanity()) return false; if(!continue_loop) break; } } return a.all_memory_deallocated() && a.check_sanity(); } //This test allocates memory, writes it with a non-zero value and //tests zero_free_memory initializes to zero for the next allocation template<class Allocator> bool test_clear_free_memory(Allocator &a) { std::vector<void*> buffers; //Allocate memory for(int i = 0; true; ++i){ void *ptr = a.allocate(i, std::nothrow); if(!ptr) break; std::size_t size = a.size(ptr); std::memset(ptr, 1, size); buffers.push_back(ptr); } //Mark it for(int i = 0, max = buffers.size(); i < max; ++i){ std::memset(buffers[i], 1, i); } //Deallocate all for(int j = (int)buffers.size() ;j-- ;){ a.deallocate(buffers[j]); } buffers.clear(); if(!a.all_memory_deallocated() && a.check_sanity()) return false; //Now clear all free memory a.zero_free_memory(); if(!a.all_memory_deallocated() && a.check_sanity()) return false; //Now test all allocated memory is zero //Allocate memory for(int i = 0; true; ++i){ void *ptr = a.allocate(i, std::nothrow); if(!ptr) break; buffers.push_back(ptr); } //Test allocated memory is zero for(int i = 0, max = buffers.size(); i < max; ++i){ for(int j = 0; j < i; ++j){ if(static_cast<char*>(buffers[i])[j]) return false; } } //Deallocate all for(int j = (int)buffers.size() ;j-- ;){ a.deallocate(buffers[j]); } if(!a.all_memory_deallocated() && a.check_sanity()) return false; return true; } //This test uses tests grow and shrink_to_fit functions template<class Allocator> bool test_grow_shrink_to_fit(Allocator &a) { std::vector<void*> buffers; std::size_t original_size = a.get_size(); std::size_t original_free = a.get_free_memory(); a.shrink_to_fit(); if(!a.all_memory_deallocated() && a.check_sanity()) return false; std::size_t shrunk_size = a.get_size(); std::size_t shrunk_free_memory = a.get_free_memory(); if(shrunk_size != a.get_min_size()) return 1; a.grow(original_size - shrunk_size); if(!a.all_memory_deallocated() && a.check_sanity()) return false; if(original_size != a.get_size()) return false; if(original_free != a.get_free_memory()) return false; //Allocate memory for(int i = 0; true; ++i){ void *ptr = a.allocate(i, std::nothrow); if(!ptr) break; std::size_t size = a.size(ptr); std::memset(ptr, 0, size); buffers.push_back(ptr); } //Now deallocate the half of the blocks //so expand maybe can merge new free blocks for(int i = 0, max = (int)buffers.size() ;i < max ;++i){ if(i%2){ a.deallocate(buffers[i]); buffers[i] = 0; } } //Deallocate the rest of the blocks //Deallocate it in non sequential order for(int j = 0, max = (int)buffers.size() ;j < max ;++j){ int pos = (j%5)*((int)buffers.size())/4; if(pos == int(buffers.size())) --pos; a.deallocate(buffers[pos]); buffers.erase(buffers.begin()+pos); std::size_t old_free = a.get_free_memory(); a.shrink_to_fit(); if(!a.check_sanity()) return false; if(original_size < a.get_size()) return false; if(old_free < a.get_free_memory()) return false; a.grow(original_size - a.get_size()); if(!a.check_sanity()) return false; if(original_size != a.get_size()) return false; if(old_free != a.get_free_memory()) return false; } //Now shrink it to the maximum a.shrink_to_fit(); if(a.get_size() != a.get_min_size()) return 1; if(shrunk_free_memory != a.get_free_memory()) return 1; if(!a.all_memory_deallocated() && a.check_sanity()) return false; a.grow(original_size - shrunk_size); if(original_size != a.get_size()) return false; if(original_free != a.get_free_memory()) return false; if(!a.all_memory_deallocated() && a.check_sanity()) return false; return true; } //This test allocates multiple values until there is no more memory //and after that deallocates all in the inverse order template<class Allocator> bool test_many_equal_allocation(Allocator &a) { typedef typename Allocator::multiallocation_iterator multiallocation_iterator; for( deallocation_type t = DirectDeallocation ; t != EndDeallocationType ; t = (deallocation_type)((int)t + 1)){ std::size_t free_memory = a.get_free_memory(); std::vector<void*> buffers2; //Allocate buffers with extra memory for(int i = 0; true; ++i){ void *ptr = a.allocate(i, std::nothrow); if(!ptr) break; std::size_t size = a.size(ptr); std::memset(ptr, 0, size); if(!a.check_sanity()) return false; buffers2.push_back(ptr); } //Now deallocate the half of the blocks //so expand maybe can merge new free blocks for(int i = 0, max = (int)buffers2.size() ;i < max ;++i){ if(i%2){ a.deallocate(buffers2[i]); buffers2[i] = 0; } } if(!a.check_sanity()) return false; std::vector<void*> buffers; for(int i = 0; true; ++i){ multiallocation_iterator it = a.allocate_many(i+1, (i+1)*2, std::nothrow); if(!it) break; multiallocation_iterator itend; std::size_t n = 0; for(; it != itend; ++n){ buffers.push_back(&*it++); } if(n != std::size_t((i+1)*2)) return false; } if(!a.check_sanity()) return false; switch(t){ case DirectDeallocation: { for(int j = 0, max = (int)buffers.size() ;j < max ;++j){ a.deallocate(buffers[j]); } } break; case InverseDeallocation: { for(int j = (int)buffers.size() ;j-- ;){ a.deallocate(buffers[j]); } } break; case MixedDeallocation: { for(int j = 0, max = (int)buffers.size() ;j < max ;++j){ int pos = (j%4)*((int)buffers.size())/4; a.deallocate(buffers[pos]); buffers.erase(buffers.begin()+pos); } } break; default: break; } //Deallocate the rest of the blocks //Deallocate it in non sequential order for(int j = 0, max = (int)buffers2.size() ;j < max ;++j){ int pos = (j%4)*((int)buffers2.size())/4; a.deallocate(buffers2[pos]); buffers2.erase(buffers2.begin()+pos); } bool ok = free_memory == a.get_free_memory() && a.all_memory_deallocated() && a.check_sanity(); if(!ok) return ok; } return true; } //This test allocates multiple values until there is no more memory //and after that deallocates all in the inverse order template<class Allocator> bool test_many_different_allocation(Allocator &a) { typedef typename Allocator::multiallocation_iterator multiallocation_iterator; const std::size_t ArraySize = 11; std::size_t requested_sizes[ArraySize]; for(std::size_t i = 0; i < ArraySize; ++i){ requested_sizes[i] = 4*i; } for( deallocation_type t = DirectDeallocation ; t != EndDeallocationType ; t = (deallocation_type)((int)t + 1)){ std::size_t free_memory = a.get_free_memory(); std::vector<void*> buffers2; //Allocate buffers with extra memory for(int i = 0; true; ++i){ void *ptr = a.allocate(i, std::nothrow); if(!ptr) break; std::size_t size = a.size(ptr); std::memset(ptr, 0, size); buffers2.push_back(ptr); } //Now deallocate the half of the blocks //so expand maybe can merge new free blocks for(int i = 0, max = (int)buffers2.size() ;i < max ;++i){ if(i%2){ a.deallocate(buffers2[i]); buffers2[i] = 0; } } std::vector<void*> buffers; for(int i = 0; true; ++i){ multiallocation_iterator it = a.allocate_many(requested_sizes, ArraySize, 1, std::nothrow); if(!it) break; multiallocation_iterator itend; std::size_t n = 0; for(; it != itend; ++n){ buffers.push_back(&*it++); } if(n != ArraySize) return false; } switch(t){ case DirectDeallocation: { for(int j = 0, max = (int)buffers.size() ;j < max ;++j){ a.deallocate(buffers[j]); } } break; case InverseDeallocation: { for(int j = (int)buffers.size() ;j-- ;){ a.deallocate(buffers[j]); } } break; case MixedDeallocation: { for(int j = 0, max = (int)buffers.size() ;j < max ;++j){ int pos = (j%4)*((int)buffers.size())/4; a.deallocate(buffers[pos]); buffers.erase(buffers.begin()+pos); } } break; default: break; } //Deallocate the rest of the blocks //Deallocate it in non sequential order for(int j = 0, max = (int)buffers2.size() ;j < max ;++j){ int pos = (j%4)*((int)buffers2.size())/4; a.deallocate(buffers2[pos]); buffers2.erase(buffers2.begin()+pos); } bool ok = free_memory == a.get_free_memory() && a.all_memory_deallocated() && a.check_sanity(); if(!ok) return ok; } return true; } //This test allocates multiple values until there is no more memory //and after that deallocates all in the inverse order template<class Allocator> bool test_many_deallocation(Allocator &a) { typedef typename Allocator::multiallocation_iterator multiallocation_iterator; const std::size_t ArraySize = 11; std::vector<multiallocation_iterator> buffers; std::size_t requested_sizes[ArraySize]; for(std::size_t i = 0; i < ArraySize; ++i){ requested_sizes[i] = 4*i; } std::size_t free_memory = a.get_free_memory(); { for(int i = 0; true; ++i){ multiallocation_iterator it = a.allocate_many(requested_sizes, ArraySize, 1, std::nothrow); if(!it) break; buffers.push_back(it); } for(int i = 0, max = (int)buffers.size(); i != max; ++i){ a.deallocate_many(buffers[i]); } buffers.clear(); bool ok = free_memory == a.get_free_memory() && a.all_memory_deallocated() && a.check_sanity(); if(!ok) return ok; } { for(int i = 0; true; ++i){ multiallocation_iterator it = a.allocate_many(i*4, ArraySize, std::nothrow); if(!it) break; buffers.push_back(it); } for(int i = 0, max = (int)buffers.size(); i != max; ++i){ a.deallocate_many(buffers[i]); } buffers.clear(); bool ok = free_memory == a.get_free_memory() && a.all_memory_deallocated() && a.check_sanity(); if(!ok) return ok; } return true; } //This function calls all tests template<class Allocator> bool test_all_allocation(Allocator &a) { std::cout << "Starting test_allocation. Class: " << typeid(a).name() << std::endl; if(!test_allocation(a)){ std::cout << "test_allocation_direct_deallocation failed. Class: " << typeid(a).name() << std::endl; return false; } std::cout << "Starting test_many_equal_allocation. Class: " << typeid(a).name() << std::endl; if(!test_many_equal_allocation(a)){ std::cout << "test_many_equal_allocation failed. Class: " << typeid(a).name() << std::endl; return false; } std::cout << "Starting test_many_different_allocation. Class: " << typeid(a).name() << std::endl; if(!test_many_different_allocation(a)){ std::cout << "test_many_different_allocation failed. Class: " << typeid(a).name() << std::endl; return false; } if(!test_many_deallocation(a)){ std::cout << "test_many_deallocation failed. Class: " << typeid(a).name() << std::endl; return false; } std::cout << "Starting test_allocation_shrink. Class: " << typeid(a).name() << std::endl; if(!test_allocation_shrink(a)){ std::cout << "test_allocation_shrink failed. Class: " << typeid(a).name() << std::endl; return false; } if(!test_allocation_shrink_and_expand(a)){ std::cout << "test_allocation_shrink_and_expand failed. Class: " << typeid(a).name() << std::endl; return false; } std::cout << "Starting test_allocation_expand. Class: " << typeid(a).name() << std::endl; if(!test_allocation_expand(a)){ std::cout << "test_allocation_expand failed. Class: " << typeid(a).name() << std::endl; return false; } std::cout << "Starting test_allocation_deallocation_expand. Class: " << typeid(a).name() << std::endl; if(!test_allocation_deallocation_expand(a)){ std::cout << "test_allocation_deallocation_expand failed. Class: " << typeid(a).name() << std::endl; return false; } std::cout << "Starting test_allocation_with_reuse. Class: " << typeid(a).name() << std::endl; if(!test_allocation_with_reuse(a)){ std::cout << "test_allocation_with_reuse failed. Class: " << typeid(a).name() << std::endl; return false; } std::cout << "Starting test_aligned_allocation. Class: " << typeid(a).name() << std::endl; if(!test_aligned_allocation(a)){ std::cout << "test_aligned_allocation failed. Class: " << typeid(a).name() << std::endl; return false; } std::cout << "Starting test_continuous_aligned_allocation. Class: " << typeid(a).name() << std::endl; if(!test_continuous_aligned_allocation(a)){ std::cout << "test_continuous_aligned_allocation failed. Class: " << typeid(a).name() << std::endl; return false; } std::cout << "Starting test_clear_free_memory. Class: " << typeid(a).name() << std::endl; if(!test_clear_free_memory(a)){ std::cout << "test_clear_free_memory failed. Class: " << typeid(a).name() << std::endl; return false; } std::cout << "Starting test_grow_shrink_to_fit. Class: " << typeid(a).name() << std::endl; if(!test_grow_shrink_to_fit(a)){ std::cout << "test_grow_shrink_to_fit failed. Class: " << typeid(a).name() << std::endl; return false; } return true; } }}} //namespace boost { namespace interprocess { namespace test { #include <boost/interprocess/detail/config_end.hpp> #endif //BOOST_INTERPROCESS_TEST_MEMORY_ALGORITHM_TEST_TEMPLATE_HEADER
//////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2014-2019, Lawrence Livermore National Security, LLC. // Produced at the Lawrence Livermore National Laboratory. // Written by the LBANN Research Team (B. Van Essen, et al.) listed in // the CONTRIBUTORS file. <lbann-dev@llnl.gov> // // LLNL-CODE-697807. // All rights reserved. // // This file is part of LBANN: Livermore Big Artificial Neural Network // Toolkit. For details, see http://software.llnl.gov/LBANN or // https://github.com/LLNL/LBANN. // // Licensed under the Apache License, Version 2.0 (the "Licensee"); you // may not use this file except in compliance with the License. You may // obtain a copy of the License at: // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or // implied. See the License for the specific language governing // permissions and limitations under the license. //////////////////////////////////////////////////////////////////////////////// #ifndef LBANN_LAYER_BERNOULLI_HPP_INCLUDED #define LBANN_LAYER_BERNOULLI_HPP_INCLUDED #include "lbann/layers/transform/transform.hpp" #include "lbann/utils/random.hpp" namespace lbann { /** @brief Random values with Bernoulli distribution. * * During validation and testing, outputs are all zero. */ template <data_layout T_layout = data_layout::DATA_PARALLEL, El::Device Dev = El::Device::CPU> class bernoulli_layer : public transform_layer { private: /** Probability of outputting 1. */ DataType m_prob; public: bernoulli_layer(lbann_comm *comm, std::vector<int> dims, DataType prob = DataType(0.5)) : transform_layer(comm), m_prob(prob) { set_output_dims(dims); this->m_expected_num_parent_layers = 0; } bernoulli_layer* copy() const override { return new bernoulli_layer(*this); } std::string get_type() const override { return "Bernoulli"; } data_layout get_data_layout() const override { return T_layout; } El::Device get_device_allocation() const override { return Dev; } description get_description() const override { auto desc = transform_layer::get_description(); desc.add("Probability", m_prob); return desc; } protected: void fp_compute() override { auto& output = get_activations(); if (this->m_model->get_execution_context().get_execution_mode() == execution_mode::training) { bernoulli_fill(output, output.Height(), output.Width(), m_prob); } else { El::Zero(output); } } }; } // namespace lbann #endif // LBANN_LAYER_BERNOULLI_HPP_INCLUDED
// Copyright (c) 2018-2019, NVIDIA CORPORATION. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include <unistd.h> #include <iostream> #include <string> #include <vector> #include "request_grpc.h" #include "request_http.h" #include "cidmgr_client.h" namespace ni = nvidia::inferenceserver; namespace nic = nvidia::inferenceserver::client; namespace dicc = dnapoleone::inferenceserver::correlation_id_mgr::client; #define FAIL_IF_ERR(X, MSG) \ { \ nic::Error err = (X); \ if (!err.IsOk()) { \ std::cerr << "error: " << (MSG) << ": " << err << std::endl; \ exit(1); \ } \ } namespace { void Usage(char** argv, const std::string& msg = std::string()) { if (!msg.empty()) { std::cerr << "error: " << msg << std::endl; } std::cerr << "Usage: " << argv[0] << " [options]" << std::endl; std::cerr << "\t-v" << std::endl; std::cerr << "\t-r" << std::endl; std::cerr << "\t-a" << std::endl; std::cerr << "\t-u <URL for inference service and its gRPC port>" << std::endl; std::cerr << std::endl; std::cerr << "For -r, the client will run non-streaming context first." << std::endl; std::cerr << "For -a, the client will send asynchronous requests." << std::endl; exit(1); } int32_t Send( const std::unique_ptr<nic::InferContext>& ctx, int32_t value, bool start_of_sequence = false, bool end_of_sequence = false) { // Set the context options to do batch-size 1 requests. Also request // that all output tensors be returned. std::unique_ptr<nic::InferContext::Options> options; FAIL_IF_ERR( nic::InferContext::Options::Create(&options), "unable to create inference options"); options->SetFlags(0); if (start_of_sequence) { options->SetFlag(ni::InferRequestHeader::FLAG_SEQUENCE_START, true); } if (end_of_sequence) { options->SetFlag(ni::InferRequestHeader::FLAG_SEQUENCE_END, true); } options->SetBatchSize(1); for (const auto& output : ctx->Outputs()) { options->AddRawResult(output); } FAIL_IF_ERR(ctx->SetRunOptions(*options), "unable to set context 0 options"); // Initialize the inputs with the data. std::shared_ptr<nic::InferContext::Input> ivalue; FAIL_IF_ERR(ctx->GetInput("INPUT", &ivalue), "unable to get INPUT"); FAIL_IF_ERR(ivalue->Reset(), "unable to reset INPUT"); FAIL_IF_ERR( ivalue->SetRaw(reinterpret_cast<uint8_t*>(&value), sizeof(int32_t)), "unable to set data for INPUT"); // Send inference request to the inference server. std::map<std::string, std::unique_ptr<nic::InferContext::Result>> results; FAIL_IF_ERR(ctx->Run(&results), "unable to run model"); // We expect there to be 1 result value, return it... if (results.size() != 1) { std::cerr << "error: expected 1 result, got " << results.size() << std::endl; } int32_t r = 0; FAIL_IF_ERR( results["OUTPUT"]->GetRawAtCursor(0 /* batch idx */, &r), "unable to get OUTPUT result"); return r; } std::shared_ptr<nic::InferContext::Request> AsyncSend( const std::unique_ptr<nic::InferContext>& ctx, int32_t value, bool start_of_sequence = false, bool end_of_sequence = false) { std::shared_ptr<nic::InferContext::Request> request; // Set the context options to do batch-size 1 requests. Also request // that all output tensors be returned. std::unique_ptr<nic::InferContext::Options> options; FAIL_IF_ERR( nic::InferContext::Options::Create(&options), "unable to create inference options"); options->SetFlags(0); if (start_of_sequence) { options->SetFlag(ni::InferRequestHeader::FLAG_SEQUENCE_START, true); } if (end_of_sequence) { options->SetFlag(ni::InferRequestHeader::FLAG_SEQUENCE_END, true); } options->SetBatchSize(1); for (const auto& output : ctx->Outputs()) { options->AddRawResult(output); } FAIL_IF_ERR(ctx->SetRunOptions(*options), "unable to set context 0 options"); // Initialize the inputs with the data. std::shared_ptr<nic::InferContext::Input> ivalue; FAIL_IF_ERR(ctx->GetInput("INPUT", &ivalue), "unable to get INPUT"); FAIL_IF_ERR(ivalue->Reset(), "unable to reset INPUT"); FAIL_IF_ERR( ivalue->SetRaw(reinterpret_cast<uint8_t*>(&value), sizeof(int32_t)), "unable to set data for INPUT"); // Send inference request to the inference server. FAIL_IF_ERR(ctx->AsyncRun(&request), "unable to run model"); return request; } int32_t AsyncReceive( const std::unique_ptr<nic::InferContext>& ctx, std::shared_ptr<nic::InferContext::Request> request) { // Retrieve result of the inference request from the inference server. std::map<std::string, std::unique_ptr<nic::InferContext::Result>> results; bool is_ready; FAIL_IF_ERR( ctx->GetAsyncRunResults(&results, &is_ready, request, true), "unable to get results"); // We expect there to be 1 result value, return it... if (results.size() != 1) { std::cerr << "error: expected 1 result, got " << results.size() << std::endl; } int32_t r = 0; FAIL_IF_ERR( results["OUTPUT"]->GetRawAtCursor(0 /* batch idx */, &r), "unable to get OUTPUT result"); return r; } } int main(int argc, char** argv) { bool verbose = false; bool async = false; bool reverse = false; std::string url("localhost:8001"); // Parse commandline... int opt; while ((opt = getopt(argc, argv, "vrau:")) != -1) { switch (opt) { case 'v': verbose = true; break; case 'r': reverse = true; break; case 'a': async = true; break; case 'u': url = optarg; break; case '?': Usage(argv); break; } } nic::Error err; // We use the custom "sequence" model which takes 1 input value. The // output is the accumulated value of the inputs. See // src/custom/sequence. std::string model_name = "simple_sequence"; // Create 2 inference context with different correlation ID. We will // use these to send to sequences of inference requests. Must use a // non-zero correlation ID since zero indicates no correlation ID. std::unique_ptr<dicc::CIDMgr> cidmgr; std::unique_ptr<nic::InferContext> ctx0, ctx1; // Create two different contexts, one is using streaming while the other // isn't. Then we can compare their difference in sync/async runs err = dicc::CIDMgr::Create(&cidmgr, url, "cidmgr", -1, verbose); if (err.IsOk()) { err = cidmgr->Create( &ctx0, url, model_name, -1 /* model_version */, verbose, true /* streaming */); } if (err.IsOk()) { err = cidmgr->Create( &ctx1, url, model_name, -1 /* model_version */, verbose, false /* streaming */); } if (!err.IsOk()) { std::cerr << "error: unable to create inference contexts: " << err << std::endl; exit(1); } // Now send the inference sequences.. // std::vector<int32_t> values{11, 7, 5, 3, 2, 0, 1}; std::vector<int32_t> result0_list; std::vector<int32_t> result1_list; std::vector<std::unique_ptr<nic::InferContext>> ctxs; if (!reverse) { ctxs.emplace_back(std::move(ctx0)); ctxs.emplace_back(std::move(ctx1)); } else { ctxs.emplace_back(std::move(ctx1)); ctxs.emplace_back(std::move(ctx0)); } if (async) { std::vector<std::shared_ptr<nic::InferContext::Request>> request0_list; std::vector<std::shared_ptr<nic::InferContext::Request>> request1_list; // Send requests, first reset accumulator for the sequence. request0_list.emplace_back( AsyncSend(ctxs[0], 0, true /* start-of-sequence */)); request1_list.emplace_back( AsyncSend(ctxs[1], 100, true /* start-of-sequence */)); // Now send a sequence of values... for (int32_t v : values) { request0_list.emplace_back(AsyncSend( ctxs[0], v, false /* start-of-sequence */, (v == 1) /* end-of-sequence */)); request1_list.emplace_back(AsyncSend( ctxs[1], -v, false /* start-of-sequence */, (v == 1) /* end-of-sequence */)); } // Get results for (size_t i = 0; i < request0_list.size(); i++) { result0_list.push_back(AsyncReceive(ctxs[0], request0_list[i])); } for (size_t i = 0; i < request1_list.size(); i++) { result1_list.push_back(AsyncReceive(ctxs[1], request1_list[i])); } } else { // Send requests, first reset accumulator for the sequence. result0_list.push_back(Send(ctxs[0], 0, true /* start-of-sequence */)); result1_list.push_back(Send(ctxs[1], 100, true /* start-of-sequence */)); // Now send a sequence of values... for (int32_t v : values) { result0_list.push_back(Send( ctxs[0], v, false /* start-of-sequence */, (v == 1) /* end-of-sequence */)); result1_list.push_back(Send( ctxs[1], -v, false /* start-of-sequence */, (v == 1) /* end-of-sequence */)); } } if (!reverse) { std::cout << "streaming : non-streaming" << std::endl; } else { std::cout << "non-streaming : streaming" << std::endl; } int32_t seq0_expected = 0; int32_t seq1_expected = 100; for (size_t i = 0; i < result0_list.size(); i++) { std::cout << "[" << i << "] " << result0_list[i] << " : " << result1_list[i] << std::endl; if ((seq0_expected != result0_list[i]) || (seq1_expected != result1_list[i])) { std::cout << "[ expected ] " << seq0_expected << " : " << seq1_expected << std::endl; return 1; } if (i < values.size()) { seq0_expected += values[i]; seq1_expected -= values[i]; } } return 0; }
/////////////////////////////////////////////////////////////////////////////// // This source file is part of the LuaPlus source distribution and is Copyright // 2001-2005 by Joshua C. Jensen (jjensen@workspacewhiz.com). // // The latest version may be obtained from http://wwhiz.com/LuaPlus/. // // The code presented in this file may be used in any environment it is // acceptable to use Lua. /////////////////////////////////////////////////////////////////////////////// #ifndef BUILDING_LUAPLUS #define BUILDING_LUAPLUS #endif #include "LuaLink.h" LUA_EXTERN_C_BEGIN #include "src/lobject.h" LUA_EXTERN_C_END #include "LuaPlus.h" #include "LuaCall.h" #include <string.h> #ifdef WIN32 #if defined(WIN32) && !defined(_XBOX) && !defined(_XBOX_VER) && !defined(_WIN32_WCE) #include <windows.h> #elif defined(_XBOX) || defined(_XBOX_VER) #include <xtl.h> #endif // WIN32 #undef GetObject #endif // WIN32 #if defined(__GNUC__) #include <new> #else #include <new.h> #endif #include <stdlib.h> #include <wchar.h> #include <assert.h> #ifdef _MSC_VER #pragma warning(disable: 4100) #endif // _MSC_VER //----------------------------------------------------------------------------- LUA_EXTERN_C_BEGIN #include "src/ltable.h" #include "src/lstate.h" NAMESPACE_LUA_BEGIN LUA_EXTERN_C int luaH_findindex (lua_State *L, Table *t, StkId key); NAMESPACE_LUA_END LUA_EXTERN_C_END namespace LuaPlus { LUAPLUS_API bool LuaPlusH_next(LuaState* state, LuaObject* table, LuaObject* key, LuaObject* value) { Table* t = hvalue(table->GetTObject()); int i = luaH_findindex(*state, t, key->GetTObject()); /* find original element */ for (i++; i < t->sizearray; i++) { /* try first array part */ if (!ttisnil(&t->array[i])) { /* a non-nil value? */ key->AssignInteger(state, i + 1); value->AssignTObject(state, &t->array[i]); return true; } } for (i -= t->sizearray; i < sizenode(t); i++) { /* then hash part */ if (!ttisnil(gval(gnode(t, i)))) { /* a non-nil value? */ key->AssignTObject(state, key2tval(gnode(t, i))); value->AssignTObject(state, gval(gnode(t, i))); return true; } } return false; /* no more elements */ } /** \param tableObj The table to iterate the contents of. \param doReset If true, the Reset() function is called at constructor initialization time, allowing the iterator to be used immediately. If false, then Reset() must be called before iterating. **/ LuaTableIterator::LuaTableIterator( LuaObject& tableObj, bool doReset ) : m_keyObj(tableObj.GetState()), m_valueObj(tableObj.GetState()), m_tableObj(tableObj), m_isDone(false) { luaplus_assert(tableObj.IsTable()); // If the user requested it, perform the automatic reset. if ( doReset ) Reset(); } /** The destructor does nothing. **/ LuaTableIterator::~LuaTableIterator() { }; /** Start iteration at the beginning of the table. **/ void LuaTableIterator::Reset() { // Start afresh... LuaState* state = m_tableObj.GetState(); // Start at the beginning. m_keyObj.AssignNil(state); // Start the iteration. If the return value is 0, then the iterator // will be invalid. if ( !LuaPlusH_next(state, &m_tableObj, &m_keyObj, &m_valueObj) ) m_isDone = true; else m_isDone = false; } /** Invalidates the iterator. Call this function if you early abort from an iteration loop (such as before it hits the end). **/ void LuaTableIterator::Invalidate() { // This is a local helper variable so we don't waste space in the class // definition. LuaState* state = m_tableObj.GetState(); m_keyObj.AssignNil(state); m_valueObj.AssignNil(state); } /** Go to the next entry in the table. \return Returns true if the iteration is done. **/ bool LuaTableIterator::Next() { // This function is only active if Reset() has been called head. luaplus_assert( IsValid() ); // This is a local helper variable so we don't waste space in the class // definition. LuaState* state = m_tableObj.GetState(); // Do the Lua table iteration. if ( !LuaPlusH_next(state, &m_tableObj, &m_keyObj, &m_valueObj) ) { m_isDone = true; return false; } // The iterator is still valid. return true; } /** \return Returns true if the iterator is valid (there is a current element). **/ bool LuaTableIterator::IsValid() const { return !m_isDone; } /** We can easily allow a prefix operator++. Postfix would be a stack management nightmare. **/ LuaTableIterator& LuaTableIterator::operator++() { Next(); return *this; } /** \return Returns true if the iterator is valid (there is a current element). **/ LuaTableIterator::operator bool() const { // If the iterator is valid, then we're good. return IsValid(); } /** \return Returns a LuaObject describing the current key. **/ LuaObject& LuaTableIterator::GetKey() { // This function is only active if Reset() has been called head. luaplus_assert( IsValid() ); return m_keyObj; } /** \return Returns a LuaObject describing the current value. **/ LuaObject& LuaTableIterator::GetValue() { // This function is only active if Reset() has been called head. luaplus_assert( IsValid() ); return m_valueObj; } } // namespace LuaPlus
/* * Copyright 2015 WebAssembly Community Group * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "ThreadMultiPatch.h" #include "InterpreterThread.h" void wasmint::ThreadMultiPatch::update() { if (functionStatesOffset_ < thread_->functionStackSize()) { } if (instructionStatesOffset_ < thread_->instructionStackSize()) { } } void wasmint::ThreadMultiPatch::applyPatch() { }
#pragma once #include "NVMeSensor.hpp" #include <boost/asio/deadline_timer.hpp> #include <boost/asio/io_service.hpp> #include <memory> class NVMeContext : public std::enable_shared_from_this<NVMeContext> { public: NVMeContext(boost::asio::io_service& io, int rootBus) : scanTimer(io), rootBus(rootBus) {} virtual ~NVMeContext() { close(); } void addSensor(std::shared_ptr<NVMeSensor> sensor) { sensors.emplace_back(sensor); } virtual void pollNVMeDevices() {} virtual void close() { scanTimer.cancel(); } virtual void readAndProcessNVMeSensor() {} virtual void processResponse(void* msg, size_t len) { (void)msg; (void)len; } protected: boost::asio::deadline_timer scanTimer; int rootBus; // Root bus for this drive std::list<std::shared_ptr<NVMeSensor>> sensors; // used as a poll queue }; using NVMEMap = boost::container::flat_map<int, std::shared_ptr<NVMeContext>>; NVMEMap& getNVMEMap(void);
#include "util/fmt/format.h" #include "util/fmt/ostream.h" #include <memory> #include <ostream> #include <stack> #include <string> #include <tuple> #include <unordered_map> #include <unordered_set> #include <vector> #include "parser/ast/expr.h" #include "parser/ast/stmt.h" #include "parser/ast/transform/expr.h" #include "parser/ast/transform/pattern.h" #include "parser/ast/visitor.h" #include "parser/common.h" #include "parser/context.h" #include "parser/ocaml.h" using fmt::format; using std::get; using std::make_unique; using std::move; using std::ostream; using std::stack; using std::string; using std::unique_ptr; using std::unordered_map; using std::unordered_set; using std::vector; #define RETURN(T, ...) \ (this->result = fwdSrcInfo(make_unique<T>(__VA_ARGS__), pat->getSrcInfo())) namespace seq { namespace ast { TransformPatternVisitor::TransformPatternVisitor( TransformStmtVisitor &stmtVisitor) : stmtVisitor(stmtVisitor) {} PatternPtr TransformPatternVisitor::transform(const Pattern *ptr) { TransformPatternVisitor v(stmtVisitor); ptr->accept(v); return move(v.result); } vector<PatternPtr> TransformPatternVisitor::transform(const vector<PatternPtr> &pats) { vector<PatternPtr> r; for (auto &e : pats) { r.push_back(transform(e)); } return r; } void TransformPatternVisitor::visit(const StarPattern *pat) { RETURN(StarPattern, ); } void TransformPatternVisitor::visit(const IntPattern *pat) { RETURN(IntPattern, pat->value); } void TransformPatternVisitor::visit(const BoolPattern *pat) { RETURN(BoolPattern, pat->value); } void TransformPatternVisitor::visit(const StrPattern *pat) { RETURN(StrPattern, pat->value); } void TransformPatternVisitor::visit(const SeqPattern *pat) { RETURN(SeqPattern, pat->value); } void TransformPatternVisitor::visit(const RangePattern *pat) { RETURN(RangePattern, pat->start, pat->end); } void TransformPatternVisitor::visit(const TuplePattern *pat) { RETURN(TuplePattern, transform(pat->patterns)); } void TransformPatternVisitor::visit(const ListPattern *pat) { RETURN(ListPattern, transform(pat->patterns)); } void TransformPatternVisitor::visit(const OrPattern *pat) { RETURN(OrPattern, transform(pat->patterns)); } void TransformPatternVisitor::visit(const WildcardPattern *pat) { RETURN(WildcardPattern, pat->var); } void TransformPatternVisitor::visit(const GuardedPattern *pat) { RETURN(GuardedPattern, transform(pat->pattern), stmtVisitor.transform(pat->cond)); } void TransformPatternVisitor::visit(const BoundPattern *pat) { RETURN(BoundPattern, pat->var, transform(pat->pattern)); } } // namespace ast } // namespace seq
#include <stdio.h> #include <stdlib.h> #include <sys/stat.h> #include <sys/types.h> #include <phosg/Filesystem.hh> #include <phosg/Strings.hh> #include <unordered_map> #include <vector> #include "RealmzLib.hh" using namespace std; static string first_file_that_exists(const vector<string>& names) { for (const auto& it : names) { struct stat st; if (stat(it.c_str(), &st) == 0) { return it; } } return ""; } static unordered_map<string, TileSetDefinition> load_default_tilesets( const string& data_dir) { static const unordered_map<string, vector<string>> land_type_to_filenames({ {"indoor", {"data_castle_bd", "Data Castle BD", "DATA CASTLE BD"}}, {"desert", {"data_desert_bd", "Data Desert BD", "DATA DESERT BD"}}, {"outdoor", {"data_p_bd", "Data P BD", "DATA P BD"}}, {"snow", {"data_snow_bd", "Data Snow BD", "DATA SNOW BD"}}, {"cave", {"data_sub_bd", "Data SUB BD", "DATA SUB BD"}}, {"abyss", {"data_swamp_bd", "Data Swamp BD", "DATA SWAMP BD"}}, }); unordered_map<string, TileSetDefinition> tilesets; for (const auto& it : land_type_to_filenames) { vector<string> filenames; for (const auto& filename : it.second) filenames.emplace_back(string_printf("%s/%s", data_dir.c_str(), filename.c_str())); string filename = first_file_that_exists(filenames); if (!filename.empty()) { printf("loading tileset %s definition\n", it.first.c_str()); tilesets.emplace(it.first, load_tileset_definition(filename)); populate_custom_tileset_configuration(it.first, tilesets[it.first]); } else { printf("warning: tileset definition for %s is missing\n", it.first.c_str()); } } return tilesets; } int disassemble_scenario(const string& data_dir, const string& scenario_dir, const string& out_dir) { string scenario_name; { size_t where = scenario_dir.rfind('/'); if (where == string::npos) { scenario_name = scenario_dir; } else { scenario_name = scenario_dir.substr(where + 1); } } printf("scenario directory: %s\n", scenario_dir.c_str()); printf("disassembly directory: %s\n", out_dir.c_str()); // find all the files string scenario_metadata_name = scenario_dir + "/" + scenario_name; string global_metadata_name = first_file_that_exists({ (scenario_dir + "/global"), (scenario_dir + "/Global")}); string dungeon_map_index_name = first_file_that_exists({ (scenario_dir + "/data_dl"), (scenario_dir + "/Data DL"), (scenario_dir + "/DATA DL")}); string land_map_index_name = first_file_that_exists({ (scenario_dir + "/data_ld"), (scenario_dir + "/Data LD"), (scenario_dir + "/DATA LD")}); string string_index_name = first_file_that_exists({ (scenario_dir + "/data_sd2"), (scenario_dir + "/Data SD2"), (scenario_dir + "/DATA SD2")}); string ecodes_index_name = first_file_that_exists({ (scenario_dir + "/data_edcd"), (scenario_dir + "/Data EDCD"), (scenario_dir + "/DATA EDCD")}); string land_ap_index_name = first_file_that_exists({ (scenario_dir + "/data_dd"), (scenario_dir + "/Data DD"), (scenario_dir + "/DATA DD")}); string dungeon_ap_index_name = first_file_that_exists({ (scenario_dir + "/data_ddd"), (scenario_dir + "/Data DDD"), (scenario_dir + "/DATA DDD")}); string extra_ap_index_name = first_file_that_exists({ (scenario_dir + "/data_ed3"), (scenario_dir + "/Data ED3"), (scenario_dir + "/DATA ED3")}); string land_metadata_index_name = first_file_that_exists({ (scenario_dir + "/data_rd"), (scenario_dir + "/Data RD"), (scenario_dir + "/DATA RD")}); string dungeon_metadata_index_name = first_file_that_exists({ (scenario_dir + "/data_rdd"), (scenario_dir + "/Data RDD"), (scenario_dir + "/DATA RDD")}); string simple_encounter_index_name = first_file_that_exists({ (scenario_dir + "/data_ed"), (scenario_dir + "/Data ED"), (scenario_dir + "/DATA ED")}); string complex_encounter_index_name = first_file_that_exists({ (scenario_dir + "/data_ed2"), (scenario_dir + "/Data ED2"), (scenario_dir + "/DATA ED2")}); string party_map_index_name = first_file_that_exists({ (scenario_dir + "/data_md2"), (scenario_dir + "/Data MD2"), (scenario_dir + "/DATA MD2")}); string treasure_index_name = first_file_that_exists({ (scenario_dir + "/data_td"), (scenario_dir + "/Data TD"), (scenario_dir + "/DATA TD")}); string rogue_encounter_index_name = first_file_that_exists({ (scenario_dir + "/data_td2"), (scenario_dir + "/Data TD2"), (scenario_dir + "/DATA TD2")}); string time_encounter_index_name = first_file_that_exists({ (scenario_dir + "/data_td3"), (scenario_dir + "/Data TD3"), (scenario_dir + "/DATA TD3")}); string scenario_resources_name = first_file_that_exists({ (scenario_dir + "/scenario.rsf"), (scenario_dir + "/Scenario.rsf"), (scenario_dir + "/SCENARIO.RSF"), (scenario_dir + "/scenario/rsrc"), (scenario_dir + "/Scenario/rsrc"), (scenario_dir + "/SCENARIO/rsrc"), (scenario_dir + "/scenario/..namedfork/rsrc"), (scenario_dir + "/Scenario/..namedfork/rsrc"), (scenario_dir + "/SCENARIO/..namedfork/rsrc")}); string the_family_jewels_name = first_file_that_exists({ (data_dir + "/the_family_jewels.rsf"), (data_dir + "/The Family Jewels.rsf"), (data_dir + "/THE FAMILY JEWELS.RSF"), (data_dir + "/the_family_jewels/rsrc"), (data_dir + "/The Family Jewels/rsrc"), (data_dir + "/THE FAMILY JEWELS/rsrc"), (data_dir + "/the_family_jewels/..namedfork/rsrc"), (data_dir + "/The Family Jewels/..namedfork/rsrc"), (data_dir + "/THE FAMILY JEWELS/..namedfork/rsrc")}); // load images populate_image_caches(the_family_jewels_name); // load everything else printf("loading dungeon map index\n"); auto dungeon_maps = load_dungeon_map_index(dungeon_map_index_name); printf("loading land map index\n"); auto land_maps = load_land_map_index(land_map_index_name); printf("loading string index\n"); auto strings = load_string_index(string_index_name); printf("loading ecodes index\n"); auto ecodes = load_ecodes_index(ecodes_index_name); printf("loading dungeon action point index\n"); auto dungeon_aps = load_ap_index(dungeon_ap_index_name); printf("loading land action point index\n"); auto land_aps = load_ap_index(land_ap_index_name); printf("loading extra action point index\n"); auto xaps = load_xap_index(extra_ap_index_name); printf("loading dungeon map metadata index\n"); auto dungeon_metadata = load_map_metadata_index(dungeon_metadata_index_name); printf("loading land map metadata index\n"); auto land_metadata = load_map_metadata_index(land_metadata_index_name); printf("loading simple encounter index\n"); auto simple_encs = load_simple_encounter_index(simple_encounter_index_name); printf("loading complex encounter index\n"); auto complex_encs = load_complex_encounter_index(complex_encounter_index_name); printf("loading party map index\n"); auto party_maps = load_party_map_index(party_map_index_name); printf("loading treasure index\n"); auto treasures = load_treasure_index(treasure_index_name); printf("loading rogue encounter index\n"); auto rogue_encs = load_rogue_encounter_index(rogue_encounter_index_name); printf("loading time encounter index\n"); auto time_encs = load_time_encounter_index(time_encounter_index_name); printf("loading global metadata\n"); GlobalMetadata global; try { global = load_global_metadata(global_metadata_name); } catch (const exception& e) { printf("warning: global metadata appears to be missing\n"); } printf("loading scenario metadata\n"); auto scen_metadata = load_scenario_metadata(scenario_metadata_name); printf("loading picture resources\n"); unordered_map<int16_t, Image> picts = get_picts(scenario_resources_name); printf("loading icon resources\n"); unordered_map<int16_t, ResourceFile::DecodedColorIconResource> cicns = get_cicns(scenario_resources_name); printf("loading sound resources\n"); unordered_map<int16_t, string> snds = get_snds(scenario_resources_name); printf("loading text resources\n"); unordered_map<int16_t, pair<string, bool>> texts = get_texts(scenario_resources_name); // load layout separately because it doesn't have to exist LandLayout layout; { string fname = first_file_that_exists({ (scenario_dir + "/layout"), (scenario_dir + "/Layout")}); if (!fname.empty()) { layout = load_land_layout(fname); } else { printf("note: this scenario has no land layout information\n"); } } // load default tilesets unordered_map<string, TileSetDefinition> tilesets = load_default_tilesets( data_dir); // if custom tilesets exist for this scenario, load them unordered_map<int, TileSetDefinition> custom_tilesets; for (int x = 1; x < 4; x++) { string fname = first_file_that_exists({ string_printf("%s/data_custom_%d_bd", scenario_dir.c_str(), x), string_printf("%s/Data Custom %d BD", scenario_dir.c_str(), x), string_printf("%s/DATA CUSTOM %d BD", scenario_dir.c_str(), x)}); if (!fname.empty()) { printf("loading custom tileset %d definition\n", x); custom_tilesets.emplace(x, load_tileset_definition(fname)); populate_custom_tileset_configuration(string_printf("custom_%d", x), custom_tilesets[x]); } } // make necessary directories for output { mkdir(out_dir.c_str(), 0755); string filename = string_printf("%s/media", out_dir.c_str()); mkdir(filename.c_str(), 0755); } // disassemble scenario text { string filename = string_printf("%s/script.txt", out_dir.c_str()); auto f = fopen_unique(filename.c_str(), "wt"); // global metadata printf("... %s (global metadata)\n", filename.c_str()); string data = disassemble_globals(global); fwrite(data.data(), data.size(), 1, f.get()); // treasures printf("... %s (treasures)\n", filename.c_str()); data = disassemble_all_treasures(treasures); fwrite(data.data(), data.size(), 1, f.get()); // party maps printf("... %s (party_maps)\n", filename.c_str()); data = disassemble_all_party_maps(party_maps); fwrite(data.data(), data.size(), 1, f.get()); // simple encounters printf("... %s (simple encounters)\n", filename.c_str()); data = disassemble_all_simple_encounters(simple_encs, ecodes, strings); fwrite(data.data(), data.size(), 1, f.get()); // complex encounters printf("... %s (complex encounters)\n", filename.c_str()); data = disassemble_all_complex_encounters(complex_encs, ecodes, strings); fwrite(data.data(), data.size(), 1, f.get()); // rogue encounters printf("... %s (rogue encounters)\n", filename.c_str()); data = disassemble_all_rogue_encounters(rogue_encs, ecodes, strings); fwrite(data.data(), data.size(), 1, f.get()); // time encounters printf("... %s (time encounters)\n", filename.c_str()); data = disassemble_all_time_encounters(time_encs); fwrite(data.data(), data.size(), 1, f.get()); // dungeon APs printf("... %s (dungeon APs)\n", filename.c_str()); data = disassemble_all_aps(dungeon_aps, ecodes, strings, 1); fwrite(data.data(), data.size(), 1, f.get()); // land APs printf("... %s (land APs)\n", filename.c_str()); data = disassemble_all_aps(land_aps, ecodes, strings, 0); fwrite(data.data(), data.size(), 1, f.get()); // extra APs printf("... %s (extra APs)\n", filename.c_str()); data = disassemble_xaps(xaps, ecodes, strings, land_metadata, dungeon_metadata); fwrite(data.data(), data.size(), 1, f.get()); } // save media for (const auto& it : picts) { string filename = string_printf("%s/media/picture_%d.bmp", out_dir.c_str(), it.first); printf("... %s\n", filename.c_str()); it.second.save(filename.c_str(), Image::WindowsBitmap); } for (const auto& it : cicns) { string filename = string_printf("%s/media/icon_%d.bmp", out_dir.c_str(), it.first); printf("... %s\n", filename.c_str()); it.second.image.save(filename.c_str(), Image::WindowsBitmap); } for (const auto& it : snds) { string filename = string_printf("%s/media/snd_%d.wav", out_dir.c_str(), it.first); printf("... %s\n", filename.c_str()); FILE* f = fopen(filename.c_str(), "wb"); fwrite(it.second.data(), it.second.size(), 1, f); fclose(f); } for (const auto& it : texts) { string filename = string_printf("%s/media/text_%d.%s", out_dir.c_str(), it.first, it.second.second ? "rtf" : "txt"); printf("... %s\n", filename.c_str()); FILE* f = fopen(filename.c_str(), "wb"); fwrite(it.second.first.data(), it.second.first.size(), 1, f); fclose(f); } // generate custom tileset legends for (auto it : custom_tilesets) { try { string filename = string_printf("%s/tileset_custom_%d_legend.bmp", out_dir.c_str(), it.first); printf("... %s\n", filename.c_str()); Image legend = generate_tileset_definition_legend(it.second, string_printf("custom_%d", it.first), scenario_resources_name); legend.save(filename.c_str(), Image::WindowsBitmap); } catch (const out_of_range&) { // scenario doesn't contain this land type } catch (const runtime_error& e) { printf("warning: can\'t generate legend for custom tileset %d (%s)\n", it.first, e.what()); } } // generate dungeon maps for (size_t x = 0; x < dungeon_maps.size(); x++) { string filename = string_printf("%s/dungeon_%d.bmp", out_dir.c_str(), x); printf("... %s\n", filename.c_str()); Image map = generate_dungeon_map(dungeon_maps[x], dungeon_metadata[x], dungeon_aps[x], x); map.save(filename.c_str(), Image::WindowsBitmap); } // generate land maps unordered_map<int16_t, string> level_id_to_filename; for (size_t x = 0; x < land_maps.size(); x++) { LevelNeighbors n; try { n = get_level_neighbors(layout, x); } catch (const runtime_error& e) { printf("warning: can\'t get neighbors for level! (%s)\n", e.what()); } int16_t start_x = -1, start_y = -1; if (x == (size_t)scen_metadata.start_level) { start_x = scen_metadata.start_x; start_y = scen_metadata.start_y; } try { string filename = string_printf("%s/land_%d.bmp", out_dir.c_str(), x); printf("... %s\n", filename.c_str()); Image map = generate_land_map(land_maps[x], land_metadata[x], land_aps[x], x, n, start_x, start_y, scenario_resources_name); map.save(filename.c_str(), Image::WindowsBitmap); level_id_to_filename[x] = filename; } catch (const out_of_range& e) { printf("error: can\'t render with selected tileset (%s)\n", e.what()); } catch (const runtime_error& e) { printf("error: can\'t render with selected tileset (%s)\n", e.what()); } } // generate connected land map for (auto layout_component : get_connected_components(layout)) { if (layout_component.num_valid_levels() < 2) { continue; } try { string filename = string_printf("%s/land_connected", out_dir.c_str()); for (int y = 0; y < 8; y++) { for (int x = 0; x < 16; x++) { if (layout_component.layout[y][x] != -1) { filename += string_printf("_%d", layout_component.layout[y][x]); } } } filename += ".bmp"; printf("... %s\n", filename.c_str()); Image connected_map = generate_layout_map(layout_component, level_id_to_filename); connected_map.save(filename.c_str(), Image::WindowsBitmap); } catch (const runtime_error& e) { printf("warning: can\'t generate connected land map: %s\n", e.what()); } } return 0; } int disassemble_global_data(const string& data_dir, const string& out_dir) { printf("global data directory: %s\n", data_dir.c_str()); printf("disassembly directory: %s\n", out_dir.c_str()); // find all the files string the_family_jewels_name = first_file_that_exists({ (data_dir + "/the_family_jewels.rsf"), (data_dir + "/The Family Jewels.rsf"), (data_dir + "/THE FAMILY JEWELS.RSF"), (data_dir + "/the_family_jewels/rsrc"), (data_dir + "/The Family Jewels/rsrc"), (data_dir + "/THE FAMILY JEWELS/rsrc"), (data_dir + "/the_family_jewels/..namedfork/rsrc"), (data_dir + "/The Family Jewels/..namedfork/rsrc"), (data_dir + "/THE FAMILY JEWELS/..namedfork/rsrc")}); string portraits_name = first_file_that_exists({ (data_dir + "/portraits.rsf"), (data_dir + "/Portraits.rsf"), (data_dir + "/PORTRAITS.RSF"), (data_dir + "/portraits/rsrc"), (data_dir + "/Portraits/rsrc"), (data_dir + "/PORTRAITS/rsrc"), (data_dir + "/portraits/..namedfork/rsrc"), (data_dir + "/Portraits/..namedfork/rsrc"), (data_dir + "/PORTRAITS/..namedfork/rsrc")}); printf("found data file: %s\n", the_family_jewels_name.c_str()); printf("found data file: %s\n", portraits_name.c_str()); // load resources printf("loading picture resources\n"); unordered_map<int16_t, Image> picts = get_picts(the_family_jewels_name); printf("loading icon resources\n"); unordered_map<int16_t, ResourceFile::DecodedColorIconResource> cicns = get_cicns(the_family_jewels_name); printf("loading sound resources\n"); unordered_map<int16_t, string> snds = get_snds(the_family_jewels_name); printf("loading text resources\n"); unordered_map<int16_t, pair<string, bool>> texts = get_texts(the_family_jewels_name); printf("loading portraits\n"); unordered_map<int16_t, ResourceFile::DecodedColorIconResource> portrait_cicns = get_cicns(portraits_name); // load images populate_image_caches(the_family_jewels_name); // load default tilesets unordered_map<string, TileSetDefinition> tilesets = load_default_tilesets( data_dir); // make necessary directories for output { mkdir(out_dir.c_str(), 0755); string filename = string_printf("%s/media", out_dir.c_str()); mkdir(filename.c_str(), 0755); } // save media for (const auto& it : picts) { string filename = string_printf("%s/media/picture_%d.bmp", out_dir.c_str(), it.first); printf("... %s\n", filename.c_str()); it.second.save(filename.c_str(), Image::WindowsBitmap); } for (const auto& it : cicns) { string filename = string_printf("%s/media/icon_%d.bmp", out_dir.c_str(), it.first); printf("... %s\n", filename.c_str()); it.second.image.save(filename.c_str(), Image::WindowsBitmap); } for (const auto& it : portrait_cicns) { string filename = string_printf("%s/media/portrait_icon_%d.bmp", out_dir.c_str(), it.first); printf("... %s\n", filename.c_str()); it.second.image.save(filename.c_str(), Image::WindowsBitmap); } for (const auto& it : snds) { string filename = string_printf("%s/media/snd_%d.wav", out_dir.c_str(), it.first); printf("... %s\n", filename.c_str()); FILE* f = fopen(filename.c_str(), "wb"); fwrite(it.second.data(), it.second.size(), 1, f); fclose(f); } for (const auto& it : texts) { string filename = string_printf("%s/media/text_%d.%s", out_dir.c_str(), it.first, it.second.second ? "rtf" : "txt"); printf("... %s\n", filename.c_str()); FILE* f = fopen(filename.c_str(), "wb"); fwrite(it.second.first.data(), it.second.first.size(), 1, f); fclose(f); } // generate custom tileset legends for (auto it : tilesets) { try { string filename = string_printf("%s/tileset_%s_legend.bmp", out_dir.c_str(), it.first.c_str()); printf("... %s\n", filename.c_str()); Image legend = generate_tileset_definition_legend(it.second, it.first, the_family_jewels_name); legend.save(filename.c_str(), Image::WindowsBitmap); } catch (const runtime_error& e) { printf("warning: can\'t generate legend for tileset %s (%s)\n", it.first.c_str(), e.what()); } } return 0; } int main(int argc, char* argv[]) { printf("fuzziqer software realmz scenario disassembler\n\n"); if (argc < 3 || argc > 4) { printf("usage: %s data_dir [scenario_dir] out_dir\n", argv[0]); return 1; } if (argc == 4) { return disassemble_scenario(argv[1], argv[2], argv[3]); } else { return disassemble_global_data(argv[1], argv[2]); } }
// Copyright (c) 2011-2019 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #if defined(HAVE_CONFIG_H) #include <config/bitcoin-config.h> #endif #include <qt/bitcoin.h> #include <qt/bitcoingui.h> #include <chainparams.h> #include <qt/clientmodel.h> #include <fs.h> #include <qt/guiconstants.h> #include <qt/guiutil.h> #include <qt/intro.h> #include <qt/networkstyle.h> #include <qt/optionsmodel.h> #include <qt/platformstyle.h> #include <qt/splashscreen.h> #include <qt/utilitydialog.h> #include <qt/winshutdownmonitor.h> #ifdef ENABLE_WALLET #include <qt/paymentserver.h> #include <qt/walletcontroller.h> #endif #include <interfaces/handler.h> #include <interfaces/node.h> #include <noui.h> #include <rpc/server.h> #include <ui_interface.h> #include <uint256.h> #include <util/system.h> #include <warnings.h> #include <walletinitinterface.h> #include <memory> #include <stdint.h> #include <boost/thread.hpp> #include <QApplication> #include <QDebug> #include <QLibraryInfo> #include <QLocale> #include <QMessageBox> #include <QSettings> #include <QThread> #include <QTimer> #include <QTranslator> #if defined(QT_STATICPLUGIN) #include <QtPlugin> #if defined(QT_QPA_PLATFORM_XCB) Q_IMPORT_PLUGIN(QXcbIntegrationPlugin); #elif defined(QT_QPA_PLATFORM_WINDOWS) Q_IMPORT_PLUGIN(QWindowsIntegrationPlugin); #elif defined(QT_QPA_PLATFORM_COCOA) Q_IMPORT_PLUGIN(QCocoaIntegrationPlugin); #endif #endif // Declare meta types used for QMetaObject::invokeMethod Q_DECLARE_METATYPE(bool*) Q_DECLARE_METATYPE(CAmount) Q_DECLARE_METATYPE(uint256) static QString GetLangTerritory() { QSettings settings; // Get desired locale (e.g. "de_DE") // 1) System default language QString lang_territory = QLocale::system().name(); // 2) Language from QSettings QString lang_territory_qsettings = settings.value("language", "").toString(); if(!lang_territory_qsettings.isEmpty()) lang_territory = lang_territory_qsettings; // 3) -lang command line argument lang_territory = QString::fromStdString(gArgs.GetArg("-lang", lang_territory.toStdString())); return lang_territory; } /** Set up translations */ static void initTranslations(QTranslator &qtTranslatorBase, QTranslator &qtTranslator, QTranslator &translatorBase, QTranslator &translator) { // Remove old translators QApplication::removeTranslator(&qtTranslatorBase); QApplication::removeTranslator(&qtTranslator); QApplication::removeTranslator(&translatorBase); QApplication::removeTranslator(&translator); // Get desired locale (e.g. "de_DE") // 1) System default language QString lang_territory = GetLangTerritory(); // Convert to "de" only by truncating "_DE" QString lang = lang_territory; lang.truncate(lang_territory.lastIndexOf('_')); // Load language files for configured locale: // - First load the translator for the base language, without territory // - Then load the more specific locale translator // Load e.g. qt_de.qm if (qtTranslatorBase.load("qt_" + lang, QLibraryInfo::location(QLibraryInfo::TranslationsPath))) QApplication::installTranslator(&qtTranslatorBase); // Load e.g. qt_de_DE.qm if (qtTranslator.load("qt_" + lang_territory, QLibraryInfo::location(QLibraryInfo::TranslationsPath))) QApplication::installTranslator(&qtTranslator); // Load e.g. bitcoin_de.qm (shortcut "de" needs to be defined in bitcoin.qrc) if (translatorBase.load(lang, ":/translations/")) QApplication::installTranslator(&translatorBase); // Load e.g. bitcoin_de_DE.qm (shortcut "de_DE" needs to be defined in bitcoin.qrc) if (translator.load(lang_territory, ":/translations/")) QApplication::installTranslator(&translator); } /* qDebug() message handler --> debug.log */ void DebugMessageHandler(QtMsgType type, const QMessageLogContext& context, const QString &msg) { Q_UNUSED(context); if (type == QtDebugMsg) { LogPrint(BCLog::QT, "GUI: %s\n", msg.toStdString()); } else { LogPrintf("GUI: %s\n", msg.toStdString()); } } BitcoinCore::BitcoinCore(interfaces::Node& node) : QObject(), m_node(node) { } void BitcoinCore::handleRunawayException(const std::exception *e) { PrintExceptionContinue(e, "Runaway exception"); Q_EMIT runawayException(QString::fromStdString(m_node.getWarnings("gui"))); } void BitcoinCore::initialize() { try { qDebug() << __func__ << ": Running initialization in thread"; bool rv = m_node.appInitMain(); Q_EMIT initializeResult(rv); } catch (const std::exception& e) { handleRunawayException(&e); } catch (...) { handleRunawayException(nullptr); } } void BitcoinCore::shutdown() { try { qDebug() << __func__ << ": Running Shutdown in thread"; m_node.appShutdown(); qDebug() << __func__ << ": Shutdown finished"; Q_EMIT shutdownResult(); } catch (const std::exception& e) { handleRunawayException(&e); } catch (...) { handleRunawayException(nullptr); } } BitcoinApplication::BitcoinApplication(interfaces::Node& node, int &argc, char **argv): QApplication(argc, argv), coreThread(nullptr), m_node(node), optionsModel(nullptr), clientModel(nullptr), window(nullptr), pollShutdownTimer(nullptr), returnValue(0), platformStyle(nullptr) { setQuitOnLastWindowClosed(false); } void BitcoinApplication::setupPlatformStyle() { // UI per-platform customization // This must be done inside the BitcoinApplication constructor, or after it, because // PlatformStyle::instantiate requires a QApplication std::string platformName; platformName = gArgs.GetArg("-uiplatform", BitcoinGUI::DEFAULT_UIPLATFORM); platformStyle = PlatformStyle::instantiate(QString::fromStdString(platformName)); if (!platformStyle) // Fall back to "other" if specified name not found platformStyle = PlatformStyle::instantiate("other"); assert(platformStyle); } BitcoinApplication::~BitcoinApplication() { if(coreThread) { qDebug() << __func__ << ": Stopping thread"; coreThread->quit(); coreThread->wait(); qDebug() << __func__ << ": Stopped thread"; } delete window; window = nullptr; #ifdef ENABLE_WALLET delete paymentServer; paymentServer = nullptr; delete m_wallet_controller; m_wallet_controller = nullptr; #endif delete optionsModel; optionsModel = nullptr; delete platformStyle; platformStyle = nullptr; } #ifdef ENABLE_WALLET void BitcoinApplication::createPaymentServer() { paymentServer = new PaymentServer(this); } #endif void BitcoinApplication::createOptionsModel(bool resetSettings) { optionsModel = new OptionsModel(m_node, nullptr, resetSettings); } void BitcoinApplication::createWindow(const NetworkStyle *networkStyle) { window = new BitcoinGUI(m_node, platformStyle, networkStyle, nullptr); pollShutdownTimer = new QTimer(window); connect(pollShutdownTimer, &QTimer::timeout, window, &BitcoinGUI::detectShutdown); } void BitcoinApplication::createSplashScreen(const NetworkStyle *networkStyle) { SplashScreen *splash = new SplashScreen(m_node, nullptr, networkStyle); // We don't hold a direct pointer to the splash screen after creation, but the splash // screen will take care of deleting itself when finish() happens. splash->show(); connect(this, &BitcoinApplication::splashFinished, splash, &SplashScreen::finish); connect(this, &BitcoinApplication::requestedShutdown, splash, &QWidget::close); } bool BitcoinApplication::baseInitialize() { return m_node.baseInitialize(); } void BitcoinApplication::startThread() { if(coreThread) return; coreThread = new QThread(this); BitcoinCore *executor = new BitcoinCore(m_node); executor->moveToThread(coreThread); /* communication to and from thread */ connect(executor, &BitcoinCore::initializeResult, this, &BitcoinApplication::initializeResult); connect(executor, &BitcoinCore::shutdownResult, this, &BitcoinApplication::shutdownResult); connect(executor, &BitcoinCore::runawayException, this, &BitcoinApplication::handleRunawayException); connect(this, &BitcoinApplication::requestedInitialize, executor, &BitcoinCore::initialize); connect(this, &BitcoinApplication::requestedShutdown, executor, &BitcoinCore::shutdown); /* make sure executor object is deleted in its own thread */ connect(coreThread, &QThread::finished, executor, &QObject::deleteLater); coreThread->start(); } void BitcoinApplication::parameterSetup() { // Default printtoconsole to false for the GUI. GUI programs should not // print to the console unnecessarily. gArgs.SoftSetBoolArg("-printtoconsole", false); m_node.initLogging(); m_node.initParameterInteraction(); } void BitcoinApplication::requestInitialize() { qDebug() << __func__ << ": Requesting initialize"; startThread(); Q_EMIT requestedInitialize(); } void BitcoinApplication::requestShutdown() { // Show a simple window indicating shutdown status // Do this first as some of the steps may take some time below, // for example the RPC console may still be executing a command. shutdownWindow.reset(ShutdownWindow::showShutdownWindow(window)); qDebug() << __func__ << ": Requesting shutdown"; startThread(); window->hide(); // Must disconnect node signals otherwise current thread can deadlock since // no event loop is running. window->unsubscribeFromCoreSignals(); // Request node shutdown, which can interrupt long operations, like // rescanning a wallet. m_node.startShutdown(); // Unsetting the client model can cause the current thread to wait for node // to complete an operation, like wait for a RPC execution to complate. window->setClientModel(nullptr); pollShutdownTimer->stop(); delete clientModel; clientModel = nullptr; // Request shutdown from core thread Q_EMIT requestedShutdown(); } void BitcoinApplication::initializeResult(bool success) { qDebug() << __func__ << ": Initialization result: " << success; // Set exit result. returnValue = success ? EXIT_SUCCESS : EXIT_FAILURE; if(success) { // Log this only after AppInitMain finishes, as then logging setup is guaranteed complete qWarning() << "Platform customization:" << platformStyle->getName(); #ifdef ENABLE_WALLET m_wallet_controller = new WalletController(m_node, platformStyle, optionsModel, this); #ifdef ENABLE_BIP70 PaymentServer::LoadRootCAs(); #endif if (paymentServer) { paymentServer->setOptionsModel(optionsModel); #ifdef ENABLE_BIP70 connect(m_wallet_controller, &WalletController::coinsSent, paymentServer, &PaymentServer::fetchPaymentACK); #endif } #endif clientModel = new ClientModel(m_node, optionsModel); window->setClientModel(clientModel); #ifdef ENABLE_WALLET window->setWalletController(m_wallet_controller); #endif // If -min option passed, start window minimized (iconified) or minimized to tray if (!gArgs.GetBoolArg("-min", false)) { window->show(); } else if (clientModel->getOptionsModel()->getMinimizeToTray() && window->hasTrayIcon()) { // do nothing as the window is managed by the tray icon } else { window->showMinimized(); } Q_EMIT splashFinished(); Q_EMIT windowShown(window); #ifdef ENABLE_WALLET // Now that initialization/startup is done, process any command-line // bitcoin: URIs or payment requests: if (paymentServer) { connect(paymentServer, &PaymentServer::receivedPaymentRequest, window, &BitcoinGUI::handlePaymentRequest); connect(window, &BitcoinGUI::receivedURI, paymentServer, &PaymentServer::handleURIOrFile); connect(paymentServer, &PaymentServer::message, [this](const QString& title, const QString& message, unsigned int style) { window->message(title, message, style); }); QTimer::singleShot(100, paymentServer, &PaymentServer::uiReady); } #endif pollShutdownTimer->start(200); } else { Q_EMIT splashFinished(); // Make sure splash screen doesn't stick around during shutdown quit(); // Exit first main loop invocation } } void BitcoinApplication::shutdownResult() { quit(); // Exit second main loop invocation after shutdown finished } void BitcoinApplication::handleRunawayException(const QString &message) { QMessageBox::critical(nullptr, "Runaway exception", BitcoinGUI::tr("A fatal error occurred. Faxtcoin can no longer continue safely and will quit.") + QString("\n\n") + message); ::exit(EXIT_FAILURE); } WId BitcoinApplication::getMainWinId() const { if (!window) return 0; return window->winId(); } static void SetupUIArgs() { #if defined(ENABLE_WALLET) && defined(ENABLE_BIP70) gArgs.AddArg("-allowselfsignedrootcertificates", strprintf("Allow self signed root certificates (default: %u)", DEFAULT_SELFSIGNED_ROOTCERTS), true, OptionsCategory::GUI); #endif gArgs.AddArg("-choosedatadir", strprintf("Choose data directory on startup (default: %u)", DEFAULT_CHOOSE_DATADIR), false, OptionsCategory::GUI); gArgs.AddArg("-lang=<lang>", "Set language, for example \"de_DE\" (default: system locale)", false, OptionsCategory::GUI); gArgs.AddArg("-min", "Start minimized", false, OptionsCategory::GUI); gArgs.AddArg("-resetguisettings", "Reset all settings changed in the GUI", false, OptionsCategory::GUI); gArgs.AddArg("-rootcertificates=<file>", "Set SSL root certificates for payment request (default: -system-)", false, OptionsCategory::GUI); gArgs.AddArg("-splash", strprintf("Show splash screen on startup (default: %u)", DEFAULT_SPLASHSCREEN), false, OptionsCategory::GUI); gArgs.AddArg("-uiplatform", strprintf("Select platform to customize UI for (one of windows, macosx, other; default: %s)", BitcoinGUI::DEFAULT_UIPLATFORM), true, OptionsCategory::GUI); } #ifndef BITCOIN_QT_TEST int GuiMain(int argc, char* argv[]) { #ifdef WIN32 util::WinCmdLineArgs winArgs; std::tie(argc, argv) = winArgs.get(); #endif SetupEnvironment(); std::unique_ptr<interfaces::Node> node = interfaces::MakeNode(); // Subscribe to global signals from core std::unique_ptr<interfaces::Handler> handler_message_box = node->handleMessageBox(noui_ThreadSafeMessageBox); std::unique_ptr<interfaces::Handler> handler_question = node->handleQuestion(noui_ThreadSafeQuestion); std::unique_ptr<interfaces::Handler> handler_init_message = node->handleInitMessage(noui_InitMessage); // Do not refer to data directory yet, this can be overridden by Intro::pickDataDirectory /// 1. Basic Qt initialization (not dependent on parameters or configuration) Q_INIT_RESOURCE(bitcoin); Q_INIT_RESOURCE(bitcoin_locale); // Generate high-dpi pixmaps QApplication::setAttribute(Qt::AA_UseHighDpiPixmaps); #if QT_VERSION >= 0x050600 QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling); #endif #ifdef Q_OS_MAC QApplication::setAttribute(Qt::AA_DontShowIconsInMenus); #endif BitcoinApplication app(*node, argc, argv); // Register meta types used for QMetaObject::invokeMethod qRegisterMetaType< bool* >(); #ifdef ENABLE_WALLET qRegisterMetaType<WalletModel*>(); #endif // Need to pass name here as CAmount is a typedef (see http://qt-project.org/doc/qt-5/qmetatype.html#qRegisterMetaType) // IMPORTANT if it is no longer a typedef use the normal variant above qRegisterMetaType< CAmount >("CAmount"); qRegisterMetaType< std::function<void()> >("std::function<void()>"); qRegisterMetaType<QMessageBox::Icon>("QMessageBox::Icon"); /// 2. Parse command-line options. We do this after qt in order to show an error if there are problems parsing these // Command-line options take precedence: node->setupServerArgs(); SetupUIArgs(); std::string error; if (!node->parseParameters(argc, argv, error)) { QMessageBox::critical(nullptr, QObject::tr(PACKAGE_NAME), QObject::tr("Error parsing command line arguments: %1.").arg(QString::fromStdString(error))); return EXIT_FAILURE; } // Now that the QApplication is setup and we have parsed our parameters, we can set the platform style app.setupPlatformStyle(); /// 3. Application identification // must be set before OptionsModel is initialized or translations are loaded, // as it is used to locate QSettings QApplication::setOrganizationName(QAPP_ORG_NAME); QApplication::setOrganizationDomain(QAPP_ORG_DOMAIN); QApplication::setApplicationName(QAPP_APP_NAME_DEFAULT); /// 4. Initialization of translations, so that intro dialog is in user's language // Now that QSettings are accessible, initialize translations QTranslator qtTranslatorBase, qtTranslator, translatorBase, translator; initTranslations(qtTranslatorBase, qtTranslator, translatorBase, translator); // Show help message immediately after parsing command-line options (for "-lang") and setting locale, // but before showing splash screen. if (HelpRequested(gArgs) || gArgs.IsArgSet("-version")) { HelpMessageDialog help(*node, nullptr, gArgs.IsArgSet("-version")); help.showOrPrint(); return EXIT_SUCCESS; } /// 5. Now that settings and translations are available, ask user for data directory // User language is set up: pick a data directory if (!Intro::pickDataDirectory(*node)) return EXIT_SUCCESS; /// 6. Determine availability of data and blocks directory and parse bitcoin.conf /// - Do not call GetDataDir(true) before this step finishes if (!fs::is_directory(GetDataDir(false))) { QMessageBox::critical(nullptr, QObject::tr(PACKAGE_NAME), QObject::tr("Error: Specified data directory \"%1\" does not exist.").arg(QString::fromStdString(gArgs.GetArg("-datadir", "")))); return EXIT_FAILURE; } if (!node->readConfigFiles(error)) { QMessageBox::critical(nullptr, QObject::tr(PACKAGE_NAME), QObject::tr("Error: Cannot parse configuration file: %1.").arg(QString::fromStdString(error))); return EXIT_FAILURE; } /// 7. Determine network (and switch to network specific options) // - Do not call Params() before this step // - Do this after parsing the configuration file, as the network can be switched there // - QSettings() will use the new application name after this, resulting in network-specific settings // - Needs to be done before createOptionsModel // Check for -testnet or -regtest parameter (Params() calls are only valid after this clause) try { node->selectParams(gArgs.GetChainName()); } catch(std::exception &e) { QMessageBox::critical(nullptr, QObject::tr(PACKAGE_NAME), QObject::tr("Error: %1").arg(e.what())); return EXIT_FAILURE; } #ifdef ENABLE_WALLET // Parse URIs on command line -- this can affect Params() PaymentServer::ipcParseCommandLine(*node, argc, argv); #endif QScopedPointer<const NetworkStyle> networkStyle(NetworkStyle::instantiate(QString::fromStdString(Params().NetworkIDString()))); assert(!networkStyle.isNull()); // Allow for separate UI settings for testnets QApplication::setApplicationName(networkStyle->getAppName()); // Re-initialize translations after changing application name (language in network-specific settings can be different) initTranslations(qtTranslatorBase, qtTranslator, translatorBase, translator); #ifdef ENABLE_WALLET /// 8. URI IPC sending // - Do this early as we don't want to bother initializing if we are just calling IPC // - Do this *after* setting up the data directory, as the data directory hash is used in the name // of the server. // - Do this after creating app and setting up translations, so errors are // translated properly. if (PaymentServer::ipcSendCommandLine()) exit(EXIT_SUCCESS); // Start up the payment server early, too, so impatient users that click on // bitcoin: links repeatedly have their payment requests routed to this process: app.createPaymentServer(); #endif /// 9. Main GUI initialization // Install global event filter that makes sure that long tooltips can be word-wrapped app.installEventFilter(new GUIUtil::ToolTipToRichTextFilter(TOOLTIP_WRAP_THRESHOLD, &app)); #if defined(Q_OS_WIN) // Install global event filter for processing Windows session related Windows messages (WM_QUERYENDSESSION and WM_ENDSESSION) qApp->installNativeEventFilter(new WinShutdownMonitor()); #endif // Install qDebug() message handler to route to debug.log qInstallMessageHandler(DebugMessageHandler); // Allow parameter interaction before we create the options model app.parameterSetup(); // Load GUI settings from QSettings app.createOptionsModel(gArgs.GetBoolArg("-resetguisettings", false)); if (gArgs.GetBoolArg("-splash", DEFAULT_SPLASHSCREEN) && !gArgs.GetBoolArg("-min", false)) app.createSplashScreen(networkStyle.data()); int rv = EXIT_SUCCESS; try { app.createWindow(networkStyle.data()); // Perform base initialization before spinning up initialization/shutdown thread // This is acceptable because this function only contains steps that are quick to execute, // so the GUI thread won't be held up. if (app.baseInitialize()) { app.requestInitialize(); #if defined(Q_OS_WIN) WinShutdownMonitor::registerShutdownBlockReason(QObject::tr("%1 didn't yet exit safely...").arg(QObject::tr(PACKAGE_NAME)), (HWND)app.getMainWinId()); #endif app.exec(); app.requestShutdown(); app.exec(); rv = app.getReturnValue(); } else { // A dialog with detailed error will have been shown by InitError() rv = EXIT_FAILURE; } } catch (const std::exception& e) { PrintExceptionContinue(&e, "Runaway exception"); app.handleRunawayException(QString::fromStdString(node->getWarnings("gui"))); } catch (...) { PrintExceptionContinue(nullptr, "Runaway exception"); app.handleRunawayException(QString::fromStdString(node->getWarnings("gui"))); } return rv; } #endif // BITCOIN_QT_TEST
#include "TOBRodBuilder.h" #include "FWCore/MessageLogger/interface/MessageLogger.h" using namespace edm; using namespace std; TOBRod* TOBRodBuilder::build(const GeometricDet* negTOBRod, const GeometricDet* posTOBRod, const TrackerGeometry* theGeomDetGeometry) { vector<const GeometricDet*> theNegativeGeometricDets; if (negTOBRod != 0) theNegativeGeometricDets = negTOBRod->components(); vector<const GeometricDet*> thePositiveGeometricDets; if (posTOBRod != 0) thePositiveGeometricDets = posTOBRod->components(); vector<const GeometricDet*> allGeometricDets = theNegativeGeometricDets; allGeometricDets.insert(allGeometricDets.end(),thePositiveGeometricDets.begin(), thePositiveGeometricDets.end()); vector<const GeomDet*> innerGeomDets; vector<const GeomDet*> outerGeomDets; double meanR = (allGeometricDets[0]->positionBounds().perp()+allGeometricDets[1]->positionBounds().perp())/2; for(vector<const GeometricDet*>::iterator it=allGeometricDets.begin(); it!=allGeometricDets.end(); it++){ const GeomDet* theGeomDet = theGeomDetGeometry->idToDet( (*it)->geographicalID() ); if( (*it)->positionBounds().perp() < meanR) innerGeomDets.push_back(theGeomDet); if( (*it)->positionBounds().perp() > meanR) outerGeomDets.push_back(theGeomDet); } //LogDebug("TkDetLayers") << "innerGeomDets.size(): " << innerGeomDets.size() ; //LogDebug("TkDetLayers") << "outerGeomDets.size(): " << outerGeomDets.size() ; return new TOBRod(innerGeomDets,outerGeomDets); }
#include <catch2/catch_test_macros.hpp> #include <catch2/matchers/catch_matchers_floating.hpp> #include <cornelis/Color.hpp> using namespace cornelis; TEST_CASE("RGB: operator+") { RGB rgb(1.0f, -2.0f, 3.0f); RGB result = rgb + rgb; CHECK(result(0) == 2.0f); CHECK(result(1) == -4.0f); CHECK(result(2) == 6.0f); result = rgb + RGB(-1.0f, 2.0f, -3.0f); CHECK(result(0) == 0.0f); CHECK(result(1) == 0.0f); CHECK(result(2) == 0.0f); } TEST_CASE("RGB: operator-") { RGB rgb(1.0f, -2.0f, 3.0f); RGB result = rgb - rgb; CHECK(result(0) == 0.0f); CHECK(result(1) == 0.0f); CHECK(result(2) == 0.0f); result = rgb - RGB(-1.0f, 2.0f, -3.0f); CHECK(result(0) == 2.0f); CHECK(result(1) == -4.0f); CHECK(result(2) == 6.0f); } TEST_CASE("RGB: operator* scalar") { RGB rgb(1.0f, -2.0f, 4.0f); RGB result = rgb * 0.5f; CHECK(result(0) == 0.5f); CHECK(result(1) == -1.0f); CHECK(result(2) == 2.0f); } TEST_CASE("toSRGB(RGB)") { RGB c = RGB::black(); SRGB s = toSRGB(c); CHECK(s(0) == 0.0); CHECK(s(1) == 0.0); CHECK(s(2) == 0.0); c = RGB{0.5, 0.5, 0.5}; s = toSRGB(c); CHECK_THAT(s(0), Catch::Matchers::WithinAbs(0.7353, 0.01)); CHECK_THAT(s(1), Catch::Matchers::WithinAbs(0.7353, 0.01)); CHECK_THAT(s(2), Catch::Matchers::WithinAbs(0.7353, 0.01)); c = RGB{1.0, 1.0, 1.0}; s = toSRGB(c); CHECK_THAT(s(0), Catch::Matchers::WithinAbs(1.0, 0.01)); CHECK_THAT(s(1), Catch::Matchers::WithinAbs(1.0, 0.01)); CHECK_THAT(s(2), Catch::Matchers::WithinAbs(1.0, 0.01)); }
#include "cxxopts.hpp" #include "hyrise.hpp" #include "scheduler/node_queue_scheduler.hpp" #include "server/server.hpp" cxxopts::Options get_server_cli_options() { cxxopts::Options cli_options("./hyriseServer", "Starts Hyrise server in order to accept network requests."); // clang-format off cli_options.add_options() ("help", "Display this help and exit") // NOLINT ("address", "Specify the address to run on", cxxopts::value<std::string>()->default_value("0.0.0.0")) // NOLINT ("p,port", "Specify the port number. 0 means randomly select an available one. If no port is specified, the the server will start on PostgreSQL's official port", cxxopts::value<uint16_t>()->default_value("5432")) // NOLINT ("execution_info", "Send execution information after statement execution", cxxopts::value<bool>()->default_value("false")) // NOLINT ; // NOLINT // clang-format on return cli_options; } int main(int argc, char* argv[]) { auto cli_options = get_server_cli_options(); const auto parsed_options = cli_options.parse(argc, argv); // Print help and exit if (parsed_options.count("help")) { std::cout << cli_options.help() << std::endl; return 0; } const auto execution_info = parsed_options["execution_info"].as<bool>(); const auto port = parsed_options["port"].as<uint16_t>(); boost::system::error_code error; const auto address = boost::asio::ip::make_address(parsed_options["address"].as<std::string>(), error); Assert(!error, "Not a valid IPv4 address: " + parsed_options["address"].as<std::string>() + ", terminating..."); // Set scheduler so that the server can execute the tasks on separate threads. opossum::Hyrise::get().set_scheduler(std::make_shared<opossum::NodeQueueScheduler>()); auto server = opossum::Server{address, port, static_cast<opossum::SendExecutionInfo>(execution_info)}; server.run(); return 0; }
/* * Copyright (C) 2013 Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "core/dom/PresentationAttributeStyle.h" #include "core/css/StylePropertySet.h" #include "core/dom/Attribute.h" #include "core/dom/Element.h" #include "core/html/HTMLInputElement.h" #include "platform/Timer.h" #include "wtf/HashFunctions.h" #include "wtf/HashMap.h" #include "wtf/text/CString.h" #include <algorithm> namespace blink { using namespace HTMLNames; struct PresentationAttributeCacheKey { PresentationAttributeCacheKey() : tagName(nullptr) { } StringImpl* tagName; Vector<std::pair<StringImpl*, AtomicString>, 3> attributesAndValues; }; static bool operator!=(const PresentationAttributeCacheKey& a, const PresentationAttributeCacheKey& b) { if (a.tagName != b.tagName) return true; return a.attributesAndValues != b.attributesAndValues; } struct PresentationAttributeCacheEntry final : public NoBaseWillBeGarbageCollectedFinalized<PresentationAttributeCacheEntry> { USING_FAST_MALLOC_WILL_BE_REMOVED(PresentationAttributeCacheEntry); public: DEFINE_INLINE_TRACE() { visitor->trace(value); } PresentationAttributeCacheKey key; RefPtrWillBeMember<StylePropertySet> value; }; using PresentationAttributeCache = WillBeHeapHashMap<unsigned, OwnPtrWillBeMember<PresentationAttributeCacheEntry>, AlreadyHashed>; static PresentationAttributeCache& presentationAttributeCache() { DEFINE_STATIC_LOCAL(OwnPtrWillBePersistent<PresentationAttributeCache>, cache, (adoptPtrWillBeNoop(new PresentationAttributeCache()))); return *cache; } class PresentationAttributeCacheCleaner { WTF_MAKE_NONCOPYABLE(PresentationAttributeCacheCleaner); USING_FAST_MALLOC(PresentationAttributeCacheCleaner); public: PresentationAttributeCacheCleaner() : m_hitCount(0) , m_cleanTimer(this, &PresentationAttributeCacheCleaner::cleanCache) { } void didHitPresentationAttributeCache() { if (presentationAttributeCache().size() < minimumPresentationAttributeCacheSizeForCleaning) return; m_hitCount++; if (!m_cleanTimer.isActive()) m_cleanTimer.startOneShot(presentationAttributeCacheCleanTimeInSeconds, BLINK_FROM_HERE); } private: static const unsigned presentationAttributeCacheCleanTimeInSeconds = 60; static const unsigned minimumPresentationAttributeCacheSizeForCleaning = 100; static const unsigned minimumPresentationAttributeCacheHitCountPerMinute = (100 * presentationAttributeCacheCleanTimeInSeconds) / 60; void cleanCache(Timer<PresentationAttributeCacheCleaner>* timer) { ASSERT_UNUSED(timer, timer == &m_cleanTimer); unsigned hitCount = m_hitCount; m_hitCount = 0; if (hitCount > minimumPresentationAttributeCacheHitCountPerMinute) return; presentationAttributeCache().clear(); } unsigned m_hitCount; Timer<PresentationAttributeCacheCleaner> m_cleanTimer; }; static bool attributeNameSort(const std::pair<StringImpl*, AtomicString>& p1, const std::pair<StringImpl*, AtomicString>& p2) { // Sort based on the attribute name pointers. It doesn't matter what the order is as long as it is always the same. return p1.first < p2.first; } static void makePresentationAttributeCacheKey(Element& element, PresentationAttributeCacheKey& result) { // FIXME: Enable for SVG. if (!element.isHTMLElement()) return; // Interpretation of the size attributes on <input> depends on the type attribute. if (isHTMLInputElement(element)) return; AttributeCollection attributes = element.attributesWithoutUpdate(); for (const Attribute& attr : attributes) { if (!element.isPresentationAttribute(attr.name())) continue; if (!attr.namespaceURI().isNull()) return; // FIXME: Background URL may depend on the base URL and can't be shared. Disallow caching. if (attr.name() == backgroundAttr) return; result.attributesAndValues.append(std::make_pair(attr.localName().impl(), attr.value())); } if (result.attributesAndValues.isEmpty()) return; // Attribute order doesn't matter. Sort for easy equality comparison. std::sort(result.attributesAndValues.begin(), result.attributesAndValues.end(), attributeNameSort); // The cache key is non-null when the tagName is set. result.tagName = element.localName().impl(); } static unsigned computePresentationAttributeCacheHash(const PresentationAttributeCacheKey& key) { if (!key.tagName) return 0; ASSERT(key.attributesAndValues.size()); unsigned attributeHash = StringHasher::hashMemory(key.attributesAndValues.data(), key.attributesAndValues.size() * sizeof(key.attributesAndValues[0])); return WTF::pairIntHash(key.tagName->existingHash(), attributeHash); } PassRefPtrWillBeRawPtr<StylePropertySet> computePresentationAttributeStyle(Element& element) { DEFINE_STATIC_LOCAL(PresentationAttributeCacheCleaner, cacheCleaner, ()); ASSERT(element.isStyledElement()); PresentationAttributeCacheKey cacheKey; makePresentationAttributeCacheKey(element, cacheKey); unsigned cacheHash = computePresentationAttributeCacheHash(cacheKey); PresentationAttributeCache::ValueType* cacheValue; if (cacheHash) { cacheValue = presentationAttributeCache().add(cacheHash, nullptr).storedValue; if (cacheValue->value && cacheValue->value->key != cacheKey) cacheHash = 0; } else { cacheValue = nullptr; } RefPtrWillBeRawPtr<StylePropertySet> style = nullptr; if (cacheHash && cacheValue->value) { style = cacheValue->value->value; cacheCleaner.didHitPresentationAttributeCache(); } else { style = MutableStylePropertySet::create(element.isSVGElement() ? SVGAttributeMode : HTMLAttributeMode); AttributeCollection attributes = element.attributesWithoutUpdate(); for (const Attribute& attr : attributes) element.collectStyleForPresentationAttribute(attr.name(), attr.value(), toMutableStylePropertySet(style)); } if (!cacheHash || cacheValue->value) return style.release(); OwnPtrWillBeRawPtr<PresentationAttributeCacheEntry> newEntry = adoptPtrWillBeNoop(new PresentationAttributeCacheEntry); newEntry->key = cacheKey; newEntry->value = style; static const unsigned presentationAttributeCacheMaximumSize = 4096; if (presentationAttributeCache().size() > presentationAttributeCacheMaximumSize) { // FIXME: Discarding the entire cache when it gets too big is probably bad // since it creates a perf "cliff". Perhaps we should use an LRU? presentationAttributeCache().clear(); presentationAttributeCache().set(cacheHash, newEntry.release()); } else { cacheValue->value = newEntry.release(); } return style.release(); } } // namespace blink
#include "reinas.h" /*Constructor de la clase*/ reinas::reinas(int t) { tam = t; enter.open("ReinasSolucion.txt", fstream::out); enter << "Soluciones en tablero de " << t << "*"<< t <<endl<<endl; } /*Este metodo generara la matriz llena con espacios vacios*/ void reinas::GenerarMatrizA() { matrizA = (char**) malloc(tam * sizeof (char*)); for (int i = 0; i < tam; i++) { matrizA[i] = (char *) malloc(tam * sizeof (char)); } for (int i = 0; i < tam; i++) { for (int j = 0; j < tam; j++) { matrizA[i][j] = ' '; } } } /*Este metodo generara la matriz llena de falsos que se mostraran como 0*/ void reinas::GenerarMatrizB() { matrizB = (bool**) malloc(tam * sizeof (bool*)); for (int i = 0; i < tam; i++) { matrizB[i] = (bool *) malloc(tam * sizeof (bool)); } for (int i = 0; i < tam; i++) { for (int j = 0; j < tam; j++) { matrizB[i][j] = false; } } } /*Este metodo pondra true horizontal, vertical y en la diagonales cada vez que se ingrese una reina*/ void reinas::Reglas(int filas, int columnas) { x = columnas; y = filas; /*VERTICAL*/ int aux1 = x; int aux2 = 0; while (aux2 < tam) { matrizB[aux2][aux1] = true; aux2++; } /*HORIZONTAL*/ aux1 = 0; aux2 = y; while (aux1 < tam) { matrizB[aux2][aux1] = true; aux1++; } /*DIAGONAL "\" */ aux1 = x; aux2 = y; while (aux1 > 0 && aux2 > 0) { aux1--; aux2--; } while (aux1 < tam && aux2 < tam) { matrizB[aux2][aux1] = true; aux1++; aux2++; } /*DIAGONAL "/" */ aux1 = x; aux2 = y; if (aux1 == tam - 1 && aux2 == tam - 1) { } else { while (aux1 < tam && aux2 > 0) { aux1++; aux2--; } if (x + y >= tam) { aux1--; aux2++; } while (aux1 >= 0 && aux2 < tam) { matrizB[aux1][aux2] = true; aux1--; aux2++; } } } /*Este metodo quita un reina en el caso que este mal ubicada y restablece la matrizB*/ void reinas::Llenar(int filas, int columnas) { matrizA[filas][columnas] = ' '; for (int i = 0; i < tam; i++) { for (int j = 0; j < tam; j++) { matrizB[i][j] = false; } } for (int i = 0; i < tam; i++) { for (int j = 0; j < tam; j++) { if (matrizA[i][j] == 'R') { Reglas(i, j); } } } } /*Este metodo guarda e imprime en consola las matrices si se le envia como parametro true imprimira la matrizA caso contrariola matrizB*/ void reinas::Imprimir(bool opcion) { if (opcion) { for (int i = 0; i < tam; i++) { //cout << "|"; enter << "|"; for (int j = 0; j < tam; j++) { //cout << matrizA[i][j] << "|"; enter << matrizA[i][j] << "|"; } //cout << endl; enter << endl; } } else { for (int i = 0; i < tam; i++) { //cout << "|"; enter << "|"; for (int j = 0; j < tam; j++) { //cout << matrizB[i][j] << "|"; enter << matrizB[i][j] << "|"; } //cout << endl; enter << endl; } } //cout << endl; enter << endl; } void reinas::PonerReina(int filas, int columnas) { matrizA[filas][columnas] = 'R'; } /*Este metodo realiza la busqueda por profundidad con recursividad*/ void reinas::Respuesta(int filas, int columnas, int n) { PonerReina(filas, columnas); Reglas(filas, columnas); if (n == tam) { Imprimir(true); } else { for (int i = 0; i < tam; i++) { if (matrizB[i][columnas + 1] == false) { Respuesta(i, columnas + 1, n + 1); } } Llenar(filas, columnas); } }
// #include "p2i_kernel.hpp" // /** // * Parses the next point cloud from the input stream. // */ // void parsePointCloud(std::ifstream& input_file, PointCloud2* pointcloud2) { // try { // input_file.read((char*)&(pointcloud2->height), sizeof(int32_t)); // input_file.read((char*)&(pointcloud2->width), sizeof(int32_t)); // input_file.read((char*)&(pointcloud2->point_step), sizeof(uint32_t)); // pointcloud2->data = // (float*) omp_target_alloc(pointcloud2->height * pointcloud2->width * pointcloud2->point_step * sizeof(float), 0); // input_file.read((char*)pointcloud2->data, pointcloud2->height * pointcloud2->width * pointcloud2->point_step); // } catch (std::ifstream::failure) { // throw std::ios_base::failure("Error reading the next point cloud."); // } // } // /** // * Parses the next camera extrinsic matrix. // */ // void parseCameraExtrinsicMat(std::ifstream& input_file, Mat44* cameraExtrinsicMat) { // try { // for (int h = 0; h < 4; h++) // for (int w = 0; w < 4; w++) // input_file.read((char*)&(cameraExtrinsicMat->data[h][w]),sizeof(double)); // } catch (std::ifstream::failure) { // throw std::ios_base::failure("Error reading the next extrinsic matrix."); // } // } // /** // * Parses the next camera matrix. // */ // void parseCameraMat(std::ifstream& input_file, Mat33* cameraMat ) { // try { // for (int h = 0; h < 3; h++) // for (int w = 0; w < 3; w++) // input_file.read((char*)&(cameraMat->data[h][w]), sizeof(double)); // } catch (std::ifstream::failure) { // throw std::ios_base::failure("Error reading the next camera matrix."); // } // } // /** // * Parses the next distance coefficients. // */ // void parseDistCoeff(std::ifstream& input_file, Vec5* distCoeff) { // try { // for (int w = 0; w < 5; w++) // input_file.read((char*)&(distCoeff->data[w]), sizeof(double)); // } catch (std::ifstream::failure) { // throw std::ios_base::failure("Error reading the next set of distance coefficients."); // } // } // /** // * Parses the next image sizes. // */ // void parseImageSize(std::ifstream& input_file, ImageSize* imageSize) { // try { // input_file.read((char*)&(imageSize->width), sizeof(int32_t)); // input_file.read((char*)&(imageSize->height), sizeof(int32_t)); // } catch (std::ifstream::failure) { // throw std::ios_base::failure("Error reading the next image size."); // } // } // /** // * Parses the next reference image. // */ // void parsePointsImage(std::ifstream& output_file, PointsImage* goldenResult) { // try { // // read data of static size // output_file.read((char*)&(goldenResult->image_width), sizeof(int32_t)); // output_file.read((char*)&(goldenResult->image_height), sizeof(int32_t)); // output_file.read((char*)&(goldenResult->max_y), sizeof(int32_t)); // output_file.read((char*)&(goldenResult->min_y), sizeof(int32_t)); // int pos = 0; // int elements = goldenResult->image_height * goldenResult->image_width; // goldenResult->intensity = new float[elements]; // goldenResult->distance = new float[elements]; // goldenResult->min_height = new float[elements]; // goldenResult->max_height = new float[elements]; // // read data of variable size // for (int h = 0; h < goldenResult->image_height; h++) // for (int w = 0; w < goldenResult->image_width; w++) // { // output_file.read((char*)&(goldenResult->intensity[pos]), sizeof(float)); // output_file.read((char*)&(goldenResult->distance[pos]), sizeof(float)); // output_file.read((char*)&(goldenResult->min_height[pos]), sizeof(float)); // output_file.read((char*)&(goldenResult->max_height[pos]), sizeof(float)); // pos++; // } // } catch (std::ios_base::failure) { // throw std::ios_base::failure("Error reading the next reference image."); // } // } // int points2image::read_next_testcases(int count) // { // // free the memory that has been allocated in the previous iteration // // and allocate new for the currently required data sizes // if (pointcloud2) // for (int m = 0; m < count; ++m) // omp_target_free(pointcloud2[m].data, 0); // delete [] pointcloud2; // pointcloud2 = new PointCloud2[count]; // delete [] cameraExtrinsicMat; // cameraExtrinsicMat = new Mat44[count]; // delete [] cameraMat; // cameraMat = new Mat33[count]; // delete [] distCoeff; // distCoeff = new Vec5[count]; // delete [] imageSize; // imageSize = new ImageSize[count]; // if (results) // for (int m = 0; m < count; ++m) // { // delete [] results[m].intensity; // delete [] results[m].distance; // delete [] results[m].min_height; // delete [] results[m].max_height; // } // delete [] results; // results = new PointsImage[count]; // // iteratively read the data for the test cases // int i; // for (i = 0; (i < count) && (read_testcases < testcases); i++,read_testcases++) // { // try { // parsePointCloud(input_file, pointcloud2 + i); // parseCameraExtrinsicMat(input_file, cameraExtrinsicMat + i); // parseCameraMat(input_file, cameraMat + i); // parseDistCoeff(input_file, distCoeff + i); // parseImageSize(input_file, imageSize + i); // } catch (std::ios_base::failure& e) { // std::cerr << e.what() << std::endl; // exit(-3); // } // } // return i; // } // int points2image::read_number_testcases(std::ifstream& input_file) // { // // reads the number of testcases in the data stream // int32_t number; // try { // input_file.read((char*)&(number), sizeof(int32_t)); // } catch (std::ifstream::failure) { // throw std::ios_base::failure("Error reading the number of testcases."); // } // return number; // } // void points2image::init() { // std::cout << "init\n"; // // open testcase and reference data streams // input_file.exceptions ( std::ifstream::failbit | std::ifstream::badbit ); // output_file.exceptions ( std::ifstream::failbit | std::ifstream::badbit ); // try { // input_file.open("../../../data/p2i_input.dat", std::ios::binary); // } catch (std::ifstream::failure) { // std::cerr << "Error opening the input data file" << std::endl; // exit(-2); // } // try { // output_file.open("../../../data/p2i_output.dat", std::ios::binary); // } catch (std::ifstream::failure) { // std::cerr << "Error opening the output data file" << std::endl; // exit(-2); // } // try { // // consume the total number of testcases // testcases = read_number_testcases(input_file); // } catch (std::ios_base::failure& e) { // std::cerr << e.what() << std::endl; // exit(-3); // } // // device selection // int deviceNo = omp_get_num_devices(); // deviceId = std::max(0, deviceNo -1); // std::cout << "Selected device " << deviceId; // std::cout << " out of " << deviceNo << std::endl; // // prepare the first iteration // error_so_far = false; // max_delta = 0.0; // pointcloud2 = nullptr; // cameraExtrinsicMat = nullptr; // cameraMat = nullptr; // distCoeff = nullptr; // imageSize = nullptr; // results = nullptr; // std::cout << "done\n" << std::endl; // } // /** // * This code is extracted from Autoware, file: // * ~/Autoware/ros/src/sensing/fusion/packages/points2image/lib/points_image/points_image.cpp // * It uses the test data that has been read before and applies the linked algorithm. // * pointcloud2: cloud of points to transform // * cameraExtrinsicMat: camera matrix used for transformation // * cameraMat: camera matrix used for transformation // * distCoeff: distance coefficients for cloud transformation // * imageSize: the size of the resulting image // * returns: the two dimensional image of transformed points // */ // PointsImage pointcloud2_to_image( // const PointCloud2& pointcloud2, // const Mat44& cameraExtrinsicMat, // const Mat33& cameraMat, const Vec5& distCoeff, // const ImageSize& imageSize) // { // // initialize the resulting image data structure // int w = imageSize.width; // int h = imageSize.height; // PointsImage msg; // msg.intensity = new float[w*h]; // std::memset(msg.intensity, 0, sizeof(float)*w*h); // msg.distance = new float[w*h]; // std::memset(msg.distance, 0, sizeof(float)*w*h); // msg.min_height = new float[w*h]; // std::memset(msg.min_height, 0, sizeof(float)*w*h); // msg.max_height = new float[w*h]; // std::memset(msg.max_height, 0, sizeof(float)*w*h); // msg.max_y = -1; // msg.min_y = h; // msg.image_height = imageSize.height; // msg.image_width = imageSize.width; // int32_t max_y = -1; // int32_t min_y = h; // float* cloud = (float *)pointcloud2.data; // // preprocess the given matrices // // transposed 3x3 camera extrinsic matrix // Mat33 invR; // for (int row = 0; row < 3; row++) // for (int col = 0; col < 3; col++) // invR.data[row][col] = cameraExtrinsicMat.data[col][row]; // // translation vector: (transposed camera extrinsic matrix)*(fourth column of camera extrinsic matrix) // Mat13 invT; // for (int row = 0; row < 3; row++) { // invT.data[row] = 0.0; // for (int col = 0; col < 3; col++) // invT.data[row] -= invR.data[row][col] * cameraExtrinsicMat.data[col][3]; // } // // various data sizes in bytes // int sizeMat = pointcloud2.width * pointcloud2.height; // int sizeMaxCp = pointcloud2.height * pointcloud2.width * pointcloud2.point_step; // double* distanceArr = (double*) omp_target_alloc(sizeMat * sizeof(double), 0); // Point2d* imagePointArr = (Point2d*) omp_target_alloc(sizeMat * sizeof(Point2d), 0); // int cloudHeight = pointcloud2.height; // int cloudWidth = pointcloud2.width; // int cloudStepSize = pointcloud2.point_step; // // point transformation // #pragma omp target \ // is_device_ptr(distanceArr, imagePointArr, cloud) \ // map(to:distCoeff,cameraMat,invT,invR,cloudHeight,cloudWidth,cloudStepSize) // { // #pragma omp teams distribute parallel for collapse(2) // for (uint32_t x = 0; x < cloudWidth; ++x) { // for (uint32_t y = 0; y < cloudHeight; ++y) { // int iPoint =x + y * cloudWidth; // float* fp = (float *)(((uintptr_t)cloud) + (x + y*cloudWidth) * cloudStepSize); // double intensity = fp[4]; // Mat13 point, point2; // point2.data[0] = double(fp[0]); // point2.data[1] = double(fp[1]); // point2.data[2] = double(fp[2]); // // apply matrices // for (int row = 0; row < 3; row++) { // point.data[row] = invT.data[row]; // for (int col = 0; col < 3; col++) // point.data[row] += point2.data[col] * invR.data[row][col]; // } // distanceArr[iPoint] = point.data[2] * 100.0; // // discard points that are too near // if (point.data[2] <= 2.5) { // Point2d imagepointError; // imagepointError.x = -1; // imagepointError.y = -1; // imagePointArr[iPoint] = imagepointError; // continue; // } // // determine image coordinates // double tmpx = point.data[0] / point.data[2]; // double tmpy = point.data[1] / point.data[2]; // double r2 = tmpx * tmpx + tmpy * tmpy; // double tmpdist = 1 + distCoeff.data[0] * r2 // + distCoeff.data[1] * r2 * r2 // + distCoeff.data[4] * r2 * r2 * r2; // Point2d imagepoint; // imagepoint.x = tmpx * tmpdist // + 2 * distCoeff.data[2] * tmpx * tmpy // + distCoeff.data[3] * (r2 + 2 * tmpx * tmpx); // imagepoint.y = tmpy * tmpdist // + distCoeff.data[2] * (r2 + 2 * tmpy * tmpy) // + 2 * distCoeff.data[3] * tmpx * tmpy; // imagepoint.x = cameraMat.data[0][0] * imagepoint.x + cameraMat.data[0][2]; // imagepoint.y = cameraMat.data[1][1] * imagepoint.y + cameraMat.data[1][2]; // imagePointArr[iPoint] = imagepoint; // } // } // } // // image formation // for (uint32_t x = 0; x < cloudWidth; ++x) { // for (uint32_t y = 0; y < cloudHeight; ++y) { // int iPoint =x + y * cloudWidth; // // restore values // double distance = distanceArr[iPoint]; // // discard near points again // if (distance <= (2.5 * 100.0)) { // continue; // } // float* fp = (float *)(((uintptr_t)cloud) + (x + y*cloudWidth) * cloudStepSize); // double intensity = fp[4]; // Point2d imagepoint = imagePointArr[iPoint]; // int px = int(imagepoint.x + 0.5); // int py = int(imagepoint.y + 0.5); // if(0 <= px && px < w && 0 <= py && py < h) // { // // write to image and update vertical extends // int pid = py * w + px; // if(msg.distance[pid] == 0 || msg.distance[pid] > distance) // { // msg.distance[pid] = float(distance); //msg is das problem beim paralelisieren // msg.intensity[pid] = float(intensity); // msg.max_y = py > msg.max_y ? py : msg.max_y; // msg.min_y = py < msg.min_y ? py : msg.min_y; // } // msg.min_height[pid] = -1.25; // msg.max_height[pid] = 0; // } // } // } // omp_target_free(distanceArr, 0); // omp_target_free(imagePointArr, 0); // return msg; // } // void points2image::run(int p) { // pause_func(); // while (read_testcases < testcases) // { // int count = read_next_testcases(p); // unpause_func(); // for (int i = 0; i < count; i++) // { // // actual kernel invocation // results[i] = pointcloud2_to_image(pointcloud2[i], // cameraExtrinsicMat[i], // cameraMat[i], distCoeff[i], // imageSize[i]); // } // pause_func(); // check_next_outputs(count); // } // } // void points2image::check_next_outputs(int count) // { // PointsImage reference; // for (int i = 0; i < count; i++) // { // parsePointsImage(output_file, &reference); // if ((results[i].image_height != reference.image_height) // || (results[i].image_width != reference.image_width)) // { // error_so_far = true; // } // if ((results[i].min_y != reference.min_y) // || (results[i].max_y != reference.max_y)) // { // error_so_far = true; // } // int pos = 0; // for (int h = 0; h < reference.image_height; h++) // for (int w = 0; w < reference.image_width; w++) // { // if (fabs(reference.intensity[pos] - results[i].intensity[pos]) > max_delta) // max_delta = fabs(reference.intensity[pos] - results[i].intensity[pos]); // if (fabs(reference.distance[pos] - results[i].distance[pos]) > max_delta) // max_delta = fabs(reference.distance[pos] - results[i].distance[pos]); // if (fabs(reference.min_height[pos] - results[i].min_height[pos]) > max_delta) // max_delta = fabs(reference.min_height[pos] - results[i].min_height[pos]); // if (fabs(reference.max_height[pos] - results[i].max_height[pos]) > max_delta) // max_delta = fabs(reference.max_height[pos] - results[i].max_height[pos]); // pos++; // } // // complement to read_next_testcases() // delete [] reference.intensity; // delete [] reference.distance; // delete [] reference.min_height; // delete [] reference.max_height; // } // } // bool points2image::check_output() { // std::cout << "checking output \n"; // // complement to init() // input_file.close(); // output_file.close(); // std::cout << "max delta: " << max_delta << "\n"; // if ((max_delta > MAX_EPS) || error_so_far) // return false; // return true; // } // points2image P2I = points2image(); // kernel& P2IKernel = P2I;
/* * Copyright (c) 2021 Samsung Electronics Co., Ltd. All Rights Reserved * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // This is to validate CircleNodeMixins.h #include "luci/IR/CircleNodeMixins.h"
// Copyright (c) 2021 by Apex.AI Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // SPDX-License-Identifier: Apache-2.0 #ifndef IOX_POSH_POPO_LISTENER_HPP #define IOX_POSH_POPO_LISTENER_HPP #include "iceoryx_hoofs/cxx/expected.hpp" #include "iceoryx_hoofs/cxx/method_callback.hpp" #include "iceoryx_hoofs/cxx/type_traits.hpp" #include "iceoryx_hoofs/internal/concurrent/loffli.hpp" #include "iceoryx_hoofs/internal/concurrent/smart_lock.hpp" #include "iceoryx_posh/internal/popo/building_blocks/condition_listener.hpp" #include "iceoryx_posh/popo/enum_trigger_type.hpp" #include "iceoryx_posh/popo/notification_attorney.hpp" #include "iceoryx_posh/popo/notification_callback.hpp" #include "iceoryx_posh/popo/trigger_handle.hpp" #include <thread> namespace iox { namespace popo { enum class ListenerError { LISTENER_FULL, EVENT_ALREADY_ATTACHED, EMPTY_EVENT_CALLBACK, EMPTY_INVALIDATION_CALLBACK }; /// @brief The Listener is a class which reacts to registered events by /// executing a corresponding callback concurrently. This is achieved via /// an encapsulated thread inside this class. /// @note The Listener is threadsafe and can be used without any restrictions concurrently. /// @attention Calling detachEvent for the same event from multiple threads is supported but /// can cause a race condition if you attach the same event again concurrently from /// another thread. /// Example: /// 1. One calls detachEvent [1] from thread A, B and C /// 2. thread B wins and detaches event [1] /// 3. A new thread D spawns and would like to attach event [1] again while thread A and C are /// still waiting to detach [1]. /// 4. Thread A wins but cannot detach event [1] since it is not attached. /// 5. Thread D wins and attaches event [1]. /// 6. Finally thread C can continue and detaches event [1] again. /// /// If thread D is executed last then the event is attached. So depending on the operating /// system defined execution order the event is either attached or detached. /// /// Best practice: Detach a specific event only from one specific thread and not /// from multiple contexts. class Listener { public: Listener() noexcept; Listener(const Listener&) = delete; Listener(Listener&&) = delete; ~Listener() noexcept; Listener& operator=(const Listener&) = delete; Listener& operator=(Listener&&) = delete; /// @brief Attaches an event. Hereby the event is defined as a class T, the eventOrigin, an enum which further /// defines the event inside the class and the corresponding callback which will be called when the event /// occurs. /// @note This method can be called from any thread concurrently without any restrictions! /// Furthermore, attachEvent does not take ownership of callback in the underlying eventCallback or the /// optional contextData. The user has to ensure that both will live as long as the event is attached. /// @tparam[in] T type of the class which will signal the event /// @param[in] eventOrigin the object which will signal the event (the origin) /// @param[in] eventType enum required to specify the type of event inside of eventOrigin /// @param[in] eventCallback callback which will be executed concurrently when the event occurs. has to be created /// with iox::popo::createNotificationCallback /// @return If an error occurs the enum packed inside an expected which describes the error. template <typename T, typename EventType, typename ContextDataType, typename = std::enable_if_t<std::is_enum<EventType>::value>> cxx::expected<ListenerError> attachEvent(T& eventOrigin, const EventType eventType, const NotificationCallback<T, ContextDataType>& eventCallback) noexcept; /// @brief Attaches an event. Hereby the event is defined as a class T, the eventOrigin and /// the corresponding callback which will be called when the event occurs. /// @note This method can be called from any thread concurrently without any restrictions! /// Furthermore, attachEvent does not take ownership of callback in the underlying eventCallback or the /// optional contextData. The user has to ensure that both will live as long as the event is attached. /// @tparam[in] T type of the class which will signal the event /// @param[in] eventOrigin the object which will signal the event (the origin) /// @param[in] eventCallback callback which will be executed concurrently when the event occurs. Has to be created /// with iox::popo::createNotificationCallback /// @return If an error occurs the enum packed inside an expected which describes the error. template <typename T, typename ContextDataType> cxx::expected<ListenerError> attachEvent(T& eventOrigin, const NotificationCallback<T, ContextDataType>& eventCallback) noexcept; /// @brief Detaches an event. Hereby, the event is defined as a class T, the eventOrigin and /// the eventType with further specifies the event inside of eventOrigin /// @note This method can be called from any thread concurrently without any restrictions! /// @tparam[in] T type of the class which will signal the event /// @param[in] eventOrigin the object which will signal the event (the origin) /// @param[in] eventType enum required to specify the type of event inside of eventOrigin template <typename T, typename EventType, typename = std::enable_if_t<std::is_enum<EventType>::value>> void detachEvent(T& eventOrigin, const EventType eventType) noexcept; /// @brief Detaches an event. Hereby, the event is defined as a class T, the eventOrigin. /// @note This method can be called from any thread concurrently without any restrictions! /// @tparam[in] T type of the class which will signal the event template <typename T> void detachEvent(T& eventOrigin) noexcept; /// @brief Returns the capacity of the Listener /// @return capacity of the Listener static constexpr uint64_t capacity() noexcept; /// @brief Returns the size of the Listener /// @return size of the Listener uint64_t size() const noexcept; protected: Listener(ConditionVariableData& conditionVariableData) noexcept; private: class Event_t; void threadLoop() noexcept; cxx::expected<uint32_t, ListenerError> addEvent(void* const origin, void* const userType, const uint64_t eventType, const uint64_t eventTypeHash, internal::GenericCallbackRef_t callback, internal::TranslationCallbackRef_t translationCallback, const cxx::MethodCallback<void, uint64_t> invalidationCallback) noexcept; void removeTrigger(const uint64_t index) noexcept; private: enum class NoEnumUsed : EventEnumIdentifier { PLACEHOLDER = 0 }; class Event_t { public: ~Event_t() noexcept; bool isEqualTo(const void* const origin, const uint64_t eventType, const uint64_t eventTypeHash) const noexcept; bool reset() noexcept; bool init(const uint64_t eventId, void* const origin, void* const userType, const uint64_t eventType, const uint64_t eventTypeHash, internal::GenericCallbackRef_t callback, internal::TranslationCallbackRef_t translationCallback, const cxx::MethodCallback<void, uint64_t> invalidationCallback) noexcept; void executeCallback() noexcept; bool isInitialized() const noexcept; private: static constexpr uint64_t INVALID_ID = std::numeric_limits<uint64_t>::max(); void* m_origin = nullptr; uint64_t m_eventType = INVALID_ID; uint64_t m_eventTypeHash = INVALID_ID; internal::GenericCallbackPtr_t m_callback = nullptr; internal::TranslationCallbackPtr_t m_translationCallback = nullptr; void* m_userType = nullptr; uint64_t m_eventId = INVALID_ID; cxx::MethodCallback<void, uint64_t> m_invalidationCallback; }; class IndexManager_t { public: IndexManager_t() noexcept; bool pop(uint32_t& index) noexcept; void push(const uint32_t index) noexcept; uint64_t indicesInUse() const noexcept; using LoFFLi = concurrent::LoFFLi; LoFFLi::Index_t m_loffliStorage[LoFFLi::requiredIndexMemorySize(MAX_NUMBER_OF_EVENTS_PER_LISTENER) / sizeof(uint32_t)]; LoFFLi m_loffli; std::atomic<uint64_t> m_indicesInUse{0U}; } m_indexManager; std::thread m_thread; concurrent::smart_lock<Event_t, std::recursive_mutex> m_events[MAX_NUMBER_OF_EVENTS_PER_LISTENER]; std::mutex m_addEventMutex; std::atomic_bool m_wasDtorCalled{false}; ConditionVariableData* m_conditionVariableData = nullptr; ConditionListener m_conditionListener; }; } // namespace popo } // namespace iox #include "iceoryx_posh/internal/popo/listener.inl" #endif
//===-test_quantizelinear_xnnpack.cc-----------------------------------------------------------===// // // Copyright (C) 2019-2020 Alibaba Group Holding Limited. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ============================================================================= // clang-format off // Testing CXX Code Gen using ODLA API on xnnpack // RUN: %halo_compiler -target cxx -o %data_path/test_quantizelinear/test_data_set_0/input_0.cc -x onnx -emit-data-as-c %data_path/test_quantizelinear/test_data_set_0/input_0.pb // RUN: %halo_compiler -target cxx -o %data_path/test_quantizelinear/test_data_set_0/output_0.cc -x onnx -emit-data-as-c %data_path/test_quantizelinear/test_data_set_0/output_0.pb // RUN: %halo_compiler -target cxx -o %data_path/test_quantizelinear/test_data_set_0/input_1.cc -x onnx -emit-data-as-c %data_path/test_quantizelinear/test_data_set_0/input_1.pb // RUN: %halo_compiler -target cxx -o %data_path/test_quantizelinear/test_data_set_0/input_2.cc -x onnx -emit-data-as-c %data_path/test_quantizelinear/test_data_set_0/input_2.pb // RUN: %halo_compiler -target cxx -batch-size 1 %halo_compile_flags %data_path/test_quantizelinear/model.onnx -o %t.cc // RUN: %cxx -c -fPIC -o %t.o %t.cc -I%odla_path/include // RUN: %cxx -g %s %t.o %t.bin -I%T -I%odla_path/include -I%unittests_path -I%data_path/test_quantizelinear/test_data_set_0 %odla_link %device_link -lodla_xnnpack -o %t_xnnpack.exe -Wno-deprecated-declarations // RUN: %t_xnnpack.exe 0.0001 0 xnnpack %data_path/test_quantizelinear | FileCheck %s // CHECK: Result Pass // clang-format on // XFAIL: * #include "test_quantizelinear_xnnpack.cc.tmp.main.cc.in"
// Copyright Yamaha 2021 // MIT License // https://github.com/yamaha-bps/cbr_utils/blob/master/LICENSE #ifndef CBR_UTILS__CLOCK_TRAITS_HPP_ #define CBR_UTILS__CLOCK_TRAITS_HPP_ #include <chrono> namespace cbr::detail { /** * @brief clock traits wrapper * */ template<typename clock_t> struct ClockTraits { using time_point = typename clock_t::time_point; using duration = typename clock_t::duration; template<typename duration_t> static duration_t duration_cast(const duration & d) { return std::chrono::duration_cast<duration_t>(d); } }; } // namespace cbr::detail #endif // CBR_UTILS__CLOCK_TRAITS_HPP_
/* * Copyright (c) 2018 Abit More, and contributors. * * The MIT License * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include <graphene/protocol/custom_authority.hpp> #include <graphene/protocol/operations.hpp> #include <graphene/protocol/restriction_predicate.hpp> #include <fc/io/raw.hpp> namespace graphene { namespace protocol { share_type custom_authority_create_operation::calculate_fee(const fee_parameters_type& k)const { share_type core_fee_required = k.basic_fee; // Note: practically the `*` won't cause an integer overflow, because k.price_per_byte is 32 bit // and the results of pack_size() won't be too big core_fee_required += k.price_per_byte * (fc::raw::pack_size(restrictions) + fc::raw::pack_size(auth)); return core_fee_required; } void custom_authority_create_operation::validate()const { FC_ASSERT(fee.amount >= 0, "Fee amount can not be negative"); FC_ASSERT(account != GRAPHENE_TEMP_ACCOUNT && account != GRAPHENE_COMMITTEE_ACCOUNT && account != GRAPHENE_WITNESS_ACCOUNT && account != GRAPHENE_RELAXED_COMMITTEE_ACCOUNT, "Can not create custom authority for special accounts"); FC_ASSERT(valid_from < valid_to, "valid_from must be earlier than valid_to"); // Note: The authentication authority can be empty, but it cannot be impossible to satisify. Disable the authority // using the `enabled` boolean rather than setting an impossible authority. FC_ASSERT(auth.address_auths.size() == 0, "Address authorities are not supported"); FC_ASSERT(!auth.is_impossible(), "Cannot use an imposible authority threshold"); // Validate restrictions by constructing a predicate for them; this throws if restrictions aren't valid get_restriction_predicate(restrictions, operation_type); } share_type custom_authority_update_operation::calculate_fee(const fee_parameters_type& k)const { share_type core_fee_required = k.basic_fee; // Note: practically the `*` won't cause an integer overflow, because k.price_per_byte is 32 bit // and the results of pack_size() won't be too big core_fee_required += k.price_per_byte * fc::raw::pack_size(restrictions_to_add); if (new_auth) core_fee_required += k.price_per_byte * fc::raw::pack_size(*new_auth); return core_fee_required; } void custom_authority_update_operation::validate()const { FC_ASSERT(fee.amount >= 0, "Fee amount can not be negative"); FC_ASSERT(account != GRAPHENE_TEMP_ACCOUNT && account != GRAPHENE_COMMITTEE_ACCOUNT && account != GRAPHENE_WITNESS_ACCOUNT && account != GRAPHENE_RELAXED_COMMITTEE_ACCOUNT, "Can not create custom authority for special accounts"); if (new_valid_from && new_valid_to) FC_ASSERT(*new_valid_from < *new_valid_to, "valid_from must be earlier than valid_to"); if (new_auth) { FC_ASSERT(!new_auth->is_impossible(), "Cannot use an impossible authority threshold"); FC_ASSERT(new_auth->address_auths.size() == 0, "Address auth is not supported"); } FC_ASSERT( new_enabled.valid() || new_valid_from.valid() || new_valid_to.valid() || new_auth.valid() || !restrictions_to_remove.empty() || !restrictions_to_add.empty(), "Must update something" ); } void custom_authority_delete_operation::validate()const { FC_ASSERT(fee.amount >= 0, "Fee amount can not be negative"); FC_ASSERT(account != GRAPHENE_TEMP_ACCOUNT && account != GRAPHENE_COMMITTEE_ACCOUNT && account != GRAPHENE_WITNESS_ACCOUNT && account != GRAPHENE_RELAXED_COMMITTEE_ACCOUNT, "Can not delete custom authority for special accounts"); } } } // graphene::protocol
#include "PMurHash.hpp" std::hash<long> long_hasher; std::hash<double> double_hasher; std::hash<std::string> string_hasher; FORCE_INLINE void hash_combine(std::size_t& seed, const long& v) { seed ^= long_hasher(v) + 0x9e3779b9 + (seed<<6) + (seed>>2); } FORCE_INLINE void hash_combine(std::size_t& seed, const double& v) { seed ^= double_hasher(v) + 0x9e3779b9 + (seed<<6) + (seed>>2); } FORCE_INLINE void hash_combine(std::size_t& seed, const std::string& v) { seed ^= string_hasher(v) + 0x9e3779b9 + (seed<<6) + (seed>>2); }
/// \file ParamGeneration.cpp /// /// \brief Parameter manipulation routines for the Zerocoin cryptographic /// components. /// /// \author Ian Miers, Christina Garman and Matthew Green /// \date June 2013 /// /// \copyright Copyright 2013 Ian Miers, Christina Garman and Matthew Green /// \license This project is released under the MIT license. // Copyright (c) 2017 The DONATE developers #include "ParamGeneration.h" #include <string> #include <cmath> #include "hash.h" #include "uint256.h" using namespace std; namespace libzerocoin { /// \brief Fill in a set of Zerocoin parameters from a modulus "N". /// \param N A trusted RSA modulus /// \param aux An optional auxiliary string used in derivation /// \param securityLevel A security level /// /// \throws std::runtime_error if the process fails /// /// Fills in a ZC_Params data structure deterministically from /// a trustworthy RSA modulus "N", which is provided as a CBigNum. /// /// Note: this routine makes the fundamental assumption that "N" /// encodes a valid RSA-style modulus of the form "e1*e2" for some /// unknown safe primes "e1" and "e2". These factors must not /// be known to any party, or the security of Zerocoin is /// compromised. The integer "N" must be a MINIMUM of 1023 /// in length, and 3072 bits is strongly recommended. /// void CalculateParams(ZerocoinParams &params, CBigNum N, string aux, uint32_t securityLevel) { params.initialized = false; params.accumulatorParams.initialized = false; // Verify that |N| is > 1023 bits. uint32_t NLen = N.bitSize(); if (NLen < 1023) { throw std::runtime_error("Modulus must be at least 1023 bits"); } // Verify that "securityLevel" is at least 80 bits (minimum). if (securityLevel < 80) { throw std::runtime_error("Security level must be at least 80 bits."); } // Set the accumulator modulus to "N". params.accumulatorParams.accumulatorModulus = N; // Calculate the required size of the field "F_p" into which // we're embedding the coin commitment group. This may throw an // exception if the securityLevel is too large to be supported // by the current modulus. uint32_t pLen = 0; uint32_t qLen = 0; calculateGroupParamLengths(NLen - 2, securityLevel, &pLen, &qLen); // Calculate candidate parameters ("p", "q") for the coin commitment group // using a deterministic process based on "N", the "aux" string, and // the dedicated string "COMMITMENTGROUP". params.coinCommitmentGroup = deriveIntegerGroupParams(calculateSeed(N, aux, securityLevel, STRING_COMMIT_GROUP), pLen, qLen); // Next, we derive parameters for a second Accumulated Value commitment group. // This is a Schnorr group with the specific property that the order of the group // must be exactly equal to "q" from the commitment group. We set // the modulus of the new group equal to "2q+1" and test to see if this is prime. params.serialNumberSoKCommitmentGroup = deriveIntegerGroupFromOrder(params.coinCommitmentGroup.modulus); // Calculate the parameters for the internal commitment // using the same process. params.accumulatorParams.accumulatorPoKCommitmentGroup = deriveIntegerGroupParams(calculateSeed(N, aux, securityLevel, STRING_AIC_GROUP), qLen + 300, qLen + 1); // Calculate the parameters for the accumulator QRN commitment generators. This isn't really // a whole group, just a pair of random generators in QR_N. uint32_t resultCtr; params.accumulatorParams.accumulatorQRNCommitmentGroup.g = generateIntegerFromSeed(NLen - 1, calculateSeed(N, aux, securityLevel, STRING_QRNCOMMIT_GROUPG), &resultCtr).pow_mod(CBigNum(2),N); params.accumulatorParams.accumulatorQRNCommitmentGroup.h = generateIntegerFromSeed(NLen - 1, calculateSeed(N, aux, securityLevel, STRING_QRNCOMMIT_GROUPH), &resultCtr).pow_mod(CBigNum(2), N); // Calculate the accumulator base, which we calculate as "u = C**2 mod N" // where C is an arbitrary value. In the unlikely case that "u = 1" we increment // "C" and repeat. CBigNum constant(ACCUMULATOR_BASE_CONSTANT); params.accumulatorParams.accumulatorBase = CBigNum(1); for (uint32_t count = 0; count < MAX_ACCUMGEN_ATTEMPTS && params.accumulatorParams.accumulatorBase.isOne(); count++) { params.accumulatorParams.accumulatorBase = constant.pow_mod(CBigNum(2), params.accumulatorParams.accumulatorModulus); } // Compute the accumulator range. The upper range is the largest possible coin commitment value. // The lower range is sqrt(upper range) + 1. Since OpenSSL doesn't have // a square root function we use a slightly higher approximation. params.accumulatorParams.maxCoinValue = params.coinCommitmentGroup.modulus; params.accumulatorParams.minCoinValue = CBigNum(2).pow((params.coinCommitmentGroup.modulus.bitSize() / 2) + 3); // If all went well, mark params as successfully initialized. params.accumulatorParams.initialized = true; // If all went well, mark params as successfully initialized. params.initialized = true; } /// \brief Format a seed string by hashing several values. /// \param N A CBigNum /// \param aux An auxiliary string /// \param securityLevel The security level in bits /// \param groupName A group description string /// \throws std::runtime_error if the process fails /// /// Returns the hash of the value. uint256 calculateGeneratorSeed(uint256 seed, uint256 pSeed, uint256 qSeed, string label, uint32_t index, uint32_t count) { CHashWriter hasher(0,0); uint256 hash; // Compute the hash of: // <modulus>||<securitylevel>||<auxString>||groupName hasher << seed; hasher << string("||"); hasher << pSeed; hasher << string("||"); hasher << qSeed; hasher << string("||"); hasher << label; hasher << string("||"); hasher << index; hasher << string("||"); hasher << count; return hasher.GetHash(); } /// \brief Format a seed string by hashing several values. /// \param N A CBigNum /// \param aux An auxiliary string /// \param securityLevel The security level in bits /// \param groupName A group description string /// \throws std::runtime_error if the process fails /// /// Returns the hash of the value. uint256 calculateSeed(CBigNum modulus, string auxString, uint32_t securityLevel, string groupName) { CHashWriter hasher(0,0); uint256 hash; // Compute the hash of: // <modulus>||<securitylevel>||<auxString>||groupName hasher << modulus; hasher << string("||"); hasher << securityLevel; hasher << string("||"); hasher << auxString; hasher << string("||"); hasher << groupName; return hasher.GetHash(); } uint256 calculateHash(uint256 input) { CHashWriter hasher(0,0); // Compute the hash of "input" hasher << input; return hasher.GetHash(); } /// \brief Calculate field/group parameter sizes based on a security level. /// \param maxPLen Maximum size of the field (modulus "p") in bits. /// \param securityLevel Required security level in bits (at least 80) /// \param pLen Result: length of "p" in bits /// \param qLen Result: length of "q" in bits /// \throws std::runtime_error if the process fails /// /// Calculates the appropriate sizes of "p" and "q" for a prime-order /// subgroup of order "q" embedded within a field "F_p". The sizes /// are based on a 'securityLevel' provided in symmetric-equivalent /// bits. Our choices slightly exceed the specs in FIPS 186-3: /// /// securityLevel = 80: pLen = 1024, qLen = 256 /// securityLevel = 112: pLen = 2048, qLen = 256 /// securityLevel = 128: qLen = 3072, qLen = 320 /// /// If the length of "p" exceeds the length provided in "maxPLen", or /// if "securityLevel < 80" this routine throws an exception. void calculateGroupParamLengths(uint32_t maxPLen, uint32_t securityLevel, uint32_t *pLen, uint32_t *qLen) { *pLen = *qLen = 0; if (securityLevel < 80) { throw std::runtime_error("Security level must be at least 80 bits."); } else if (securityLevel == 80) { *qLen = 256; *pLen = 1024; } else if (securityLevel <= 112) { *qLen = 256; *pLen = 2048; } else if (securityLevel <= 128) { *qLen = 320; *pLen = 3072; } else { throw std::runtime_error("Security level not supported."); } if (*pLen > maxPLen) { throw std::runtime_error("Modulus size is too small for this security level."); } } /// \brief Deterministically compute a set of group parameters using NIST procedures. /// \param seedStr A byte string seeding the process. /// \param pLen The desired length of the modulus "p" in bits /// \param qLen The desired length of the order "q" in bits /// \return An IntegerGroupParams object /// /// Calculates the description of a group G of prime order "q" embedded within /// a field "F_p". The input to this routine is in arbitrary seed. It uses the /// algorithms described in FIPS 186-3 Appendix A.1.2 to calculate /// primes "p" and "q". It uses the procedure in Appendix A.2.3 to /// derive two generators "g", "h". IntegerGroupParams deriveIntegerGroupParams(uint256 seed, uint32_t pLen, uint32_t qLen) { IntegerGroupParams result; CBigNum p; CBigNum q; uint256 pSeed, qSeed; // Calculate "p" and "q" and "domain_parameter_seed" from the // "seed" buffer above, using the procedure described in NIST // FIPS 186-3, Appendix A.1.2. calculateGroupModulusAndOrder(seed, pLen, qLen, &(result.modulus), &(result.groupOrder), &pSeed, &qSeed); // Calculate the generators "g", "h" using the process described in // NIST FIPS 186-3, Appendix A.2.3. This algorithm takes ("p", "q", // "domain_parameter_seed", "index"). We use "index" value 1 // to generate "g" and "index" value 2 to generate "h". result.g = calculateGroupGenerator(seed, pSeed, qSeed, result.modulus, result.groupOrder, 1); result.h = calculateGroupGenerator(seed, pSeed, qSeed, result.modulus, result.groupOrder, 2); // Perform some basic tests to make sure we have good parameters if ((uint32_t)(result.modulus.bitSize()) < pLen || // modulus is pLen bits long (uint32_t)(result.groupOrder.bitSize()) < qLen || // order is qLen bits long !(result.modulus.isPrime()) || // modulus is prime !(result.groupOrder.isPrime()) || // order is prime !((result.g.pow_mod(result.groupOrder, result.modulus)).isOne()) || // g^order mod modulus = 1 !((result.h.pow_mod(result.groupOrder, result.modulus)).isOne()) || // h^order mod modulus = 1 ((result.g.pow_mod(CBigNum(100), result.modulus)).isOne()) || // g^100 mod modulus != 1 ((result.h.pow_mod(CBigNum(100), result.modulus)).isOne()) || // h^100 mod modulus != 1 result.g == result.h || // g != h result.g.isOne()) { // g != 1 // If any of the above tests fail, throw an exception throw std::runtime_error("Group parameters are not valid"); } return result; } /// \brief Deterministically compute a set of group parameters with a specified order. /// \param groupOrder The order of the group /// \return An IntegerGroupParams object /// /// Given "q" calculates the description of a group G of prime order "q" embedded within /// a field "F_p". IntegerGroupParams deriveIntegerGroupFromOrder(CBigNum &groupOrder) { IntegerGroupParams result; // Set the order to "groupOrder" result.groupOrder = groupOrder; // Try possible values for "modulus" of the form "groupOrder * 2 * i" where // "p" is prime and i is a counter starting at 1. for (uint32_t i = 1; i < NUM_SCHNORRGEN_ATTEMPTS; i++) { // Set modulus equal to "groupOrder * 2 * i" result.modulus = (result.groupOrder * CBigNum(i*2)) + CBigNum(1); // Test the result for primality // TODO: This is a probabilistic routine and thus not the right choice if (result.modulus.isPrime(256)) { // Success. // // Calculate the generators "g", "h" using the process described in // NIST FIPS 186-3, Appendix A.2.3. This algorithm takes ("p", "q", // "domain_parameter_seed", "index"). We use "index" value 1 // to generate "g" and "index" value 2 to generate "h". uint256 seed = calculateSeed(groupOrder, "", 128, ""); uint256 pSeed = calculateHash(seed); uint256 qSeed = calculateHash(pSeed); result.g = calculateGroupGenerator(seed, pSeed, qSeed, result.modulus, result.groupOrder, 1); result.h = calculateGroupGenerator(seed, pSeed, qSeed, result.modulus, result.groupOrder, 2); // Perform some basic tests to make sure we have good parameters if (!(result.modulus.isPrime()) || // modulus is prime !(result.groupOrder.isPrime()) || // order is prime !((result.g.pow_mod(result.groupOrder, result.modulus)).isOne()) || // g^order mod modulus = 1 !((result.h.pow_mod(result.groupOrder, result.modulus)).isOne()) || // h^order mod modulus = 1 ((result.g.pow_mod(CBigNum(100), result.modulus)).isOne()) || // g^100 mod modulus != 1 ((result.h.pow_mod(CBigNum(100), result.modulus)).isOne()) || // h^100 mod modulus != 1 result.g == result.h || // g != h result.g.isOne()) { // g != 1 // If any of the above tests fail, throw an exception throw std::runtime_error("Group parameters are not valid"); } return result; } } // If we reached this point group generation has failed. Throw an exception. throw std::runtime_error("Too many attempts to generate Schnorr group."); } /// \brief Deterministically compute a group description using NIST procedures. /// \param seed A byte string seeding the process. /// \param pLen The desired length of the modulus "p" in bits /// \param qLen The desired length of the order "q" in bits /// \param resultModulus A value "p" describing a finite field "F_p" /// \param resultGroupOrder A value "q" describing the order of a subgroup /// \param resultDomainParameterSeed A resulting seed for use in later calculations. /// /// Calculates the description of a group G of prime order "q" embedded within /// a field "F_p". The input to this routine is in arbitrary seed. It uses the /// algorithms described in FIPS 186-3 Appendix A.1.2 to calculate /// primes "p" and "q". void calculateGroupModulusAndOrder(uint256 seed, uint32_t pLen, uint32_t qLen, CBigNum *resultModulus, CBigNum *resultGroupOrder, uint256 *resultPseed, uint256 *resultQseed) { // Verify that the seed length is >= qLen if (qLen > (sizeof(seed)) * 8) { // TODO: The use of 256-bit seeds limits us to 256-bit group orders. We should probably change this. // throw std::runtime_error("Seed is too short to support the required security level."); } #ifdef ZEROCOIN_DEBUG cout << "calculateGroupModulusAndOrder: pLen = " << pLen << endl; #endif // Generate a random prime for the group order. // This may throw an exception, which we'll pass upwards. // Result is the value "resultGroupOrder", "qseed" and "qgen_counter". uint256 qseed; uint32_t qgen_counter; *resultGroupOrder = generateRandomPrime(qLen, seed, &qseed, &qgen_counter); // Using ⎡pLen / 2 + 1⎤ as the length and qseed as the input_seed, use the random prime // routine to obtain p0 , pseed, and pgen_counter. We pass exceptions upward. uint32_t p0len = ceil((pLen / 2.0) + 1); uint256 pseed; uint32_t pgen_counter; CBigNum p0 = generateRandomPrime(p0len, qseed, &pseed, &pgen_counter); // Set x = 0, old_counter = pgen_counter uint32_t old_counter = pgen_counter; // Generate a random integer "x" of pLen bits uint32_t iterations; CBigNum x = generateIntegerFromSeed(pLen, pseed, &iterations); pseed += (iterations + 1); // Set x = 2^{pLen−1} + (x mod 2^{pLen–1}). CBigNum powerOfTwo = CBigNum(2).pow(pLen-1); x = powerOfTwo + (x % powerOfTwo); // t = ⎡x / (2 * resultGroupOrder * p0)⎤. // TODO: we don't have a ceiling function CBigNum t = x / (CBigNum(2) * (*resultGroupOrder) * p0); // Now loop until we find a valid prime "p" or we fail due to // pgen_counter exceeding ((4*pLen) + old_counter). for ( ; pgen_counter <= ((4*pLen) + old_counter) ; pgen_counter++) { // If (2 * t * resultGroupOrder * p0 + 1) > 2^{pLen}, then // t = ⎡2^{pLen−1} / (2 * resultGroupOrder * p0)⎤. powerOfTwo = CBigNum(2).pow(pLen); CBigNum prod = (CBigNum(2) * t * (*resultGroupOrder) * p0) + CBigNum(1); if (prod > powerOfTwo) { // TODO: implement a ceil function t = CBigNum(2).pow(pLen-1) / (CBigNum(2) * (*resultGroupOrder) * p0); } // Compute a candidate prime resultModulus = 2tqp0 + 1. *resultModulus = (CBigNum(2) * t * (*resultGroupOrder) * p0) + CBigNum(1); // Verify that resultModulus is prime. First generate a pseudorandom integer "a". CBigNum a = generateIntegerFromSeed(pLen, pseed, &iterations); pseed += iterations + 1; // Set a = 2 + (a mod (resultModulus–3)). a = CBigNum(2) + (a % ((*resultModulus) - CBigNum(3))); // Set z = a^{2 * t * resultGroupOrder} mod resultModulus CBigNum z = a.pow_mod(CBigNum(2) * t * (*resultGroupOrder), (*resultModulus)); // If GCD(z–1, resultModulus) == 1 AND (z^{p0} mod resultModulus == 1) // then we have found our result. Return. if ((resultModulus->gcd(z - CBigNum(1))).isOne() && (z.pow_mod(p0, (*resultModulus))).isOne()) { // Success! Return the seeds and primes. *resultPseed = pseed; *resultQseed = qseed; return; } // This prime did not work out. Increment "t" and try again. t = t + CBigNum(1); } // loop continues until pgen_counter exceeds a limit // We reach this point only if we exceeded our maximum iteration count. // Throw an exception. throw std::runtime_error("Unable to generate a prime modulus for the group"); } /// \brief Deterministically compute a generator for a given group. /// \param seed A first seed for the process. /// \param pSeed A second seed for the process. /// \param qSeed A third seed for the process. /// \param modulus Proposed prime modulus for the field. /// \param groupOrder Proposed order of the group. /// \param index Index value, selects which generator you're building. /// \return The resulting generator. /// \throws A std::runtime_error if error. /// /// Generates a random group generator deterministically as a function of (seed,pSeed,qSeed) /// Uses the algorithm described in FIPS 186-3 Appendix A.2.3. CBigNum calculateGroupGenerator(uint256 seed, uint256 pSeed, uint256 qSeed, CBigNum modulus, CBigNum groupOrder, uint32_t index) { CBigNum result; // Verify that 0 <= index < 256 if (index > 255) { throw std::runtime_error("Invalid index for group generation"); } // Compute e = (modulus - 1) / groupOrder CBigNum e = (modulus - CBigNum(1)) / groupOrder; // Loop until we find a generator for (uint32_t count = 1; count < MAX_GENERATOR_ATTEMPTS; count++) { // hash = Hash(seed || pSeed || qSeed || “ggen” || index || count uint256 hash = calculateGeneratorSeed(seed, pSeed, qSeed, "ggen", index, count); CBigNum W(hash); // Compute result = W^e mod p result = W.pow_mod(e, modulus); // If result > 1, we have a generator if (result > 1) { return result; } } // We only get here if we failed to find a generator throw std::runtime_error("Unable to find a generator, too many attempts"); } /// \brief Deterministically compute a random prime number. /// \param primeBitLen Desired bit length of the prime. /// \param in_seed Input seed for the process. /// \param out_seed Result: output seed from the process. /// \param prime_gen_counter Result: number of iterations required. /// \return The resulting prime number. /// \throws A std::runtime_error if error. /// /// Generates a random prime number of primeBitLen bits from a given input /// seed. Uses the Shawe-Taylor algorithm as described in FIPS 186-3 /// Appendix C.6. This is a recursive function. CBigNum generateRandomPrime(uint32_t primeBitLen, uint256 in_seed, uint256 *out_seed, uint32_t *prime_gen_counter) { // Verify that primeBitLen is not too small if (primeBitLen < 2) { throw std::runtime_error("Prime length is too short"); } // If primeBitLen < 33 bits, perform the base case. if (primeBitLen < 33) { CBigNum result(0); // Set prime_seed = in_seed, prime_gen_counter = 0. uint256 prime_seed = in_seed; (*prime_gen_counter) = 0; // Loop up to "4 * primeBitLen" iterations. while ((*prime_gen_counter) < (4 * primeBitLen)) { // Generate a pseudorandom integer "c" of length primeBitLength bits uint32_t iteration_count; CBigNum c = generateIntegerFromSeed(primeBitLen, prime_seed, &iteration_count); #ifdef ZEROCOIN_DEBUG cout << "generateRandomPrime: primeBitLen = " << primeBitLen << endl; cout << "Generated c = " << c << endl; #endif prime_seed += (iteration_count + 1); (*prime_gen_counter)++; // Set "intc" to be the least odd integer >= "c" we just generated uint32_t intc = c.getulong(); intc = (2 * floor(intc / 2.0)) + 1; #ifdef ZEROCOIN_DEBUG cout << "Should be odd. c = " << intc << endl; cout << "The big num is: c = " << c << endl; #endif // Perform trial division on this (relatively small) integer to determine if "intc" // is prime. If so, return success. if (primalityTestByTrialDivision(intc)) { // Return "intc" converted back into a CBigNum and "prime_seed". We also updated // the variable "prime_gen_counter" in previous statements. result = intc; *out_seed = prime_seed; // Success return result; } } // while() // If we reached this point there was an error finding a candidate prime // so throw an exception. throw std::runtime_error("Unable to find prime in Shawe-Taylor algorithm"); // END OF BASE CASE } // If primeBitLen >= 33 bits, perform the recursive case. else { // Recurse to find a new random prime of roughly half the size uint32_t newLength = ceil((double)primeBitLen / 2.0) + 1; CBigNum c0 = generateRandomPrime(newLength, in_seed, out_seed, prime_gen_counter); // Generate a random integer "x" of primeBitLen bits using the output // of the previous call. uint32_t numIterations; CBigNum x = generateIntegerFromSeed(primeBitLen, *out_seed, &numIterations); (*out_seed) += numIterations + 1; // Compute "t" = ⎡x / (2 * c0⎤ // TODO no Ceiling call CBigNum t = x / (CBigNum(2) * c0); // Repeat the following procedure until we find a prime (or time out) for (uint32_t testNum = 0; testNum < MAX_PRIMEGEN_ATTEMPTS; testNum++) { // If ((2 * t * c0) + 1 > 2^{primeBitLen}), // then t = ⎡2^{primeBitLen} – 1 / (2 * c0)⎤. if ((CBigNum(2) * t * c0) > (CBigNum(2).pow(CBigNum(primeBitLen)))) { t = ((CBigNum(2).pow(CBigNum(primeBitLen))) - CBigNum(1)) / (CBigNum(2) * c0); } // Set c = (2 * t * c0) + 1 CBigNum c = (CBigNum(2) * t * c0) + CBigNum(1); // Increment prime_gen_counter (*prime_gen_counter)++; // Test "c" for primality as follows: // 1. First pick an integer "a" in between 2 and (c - 2) CBigNum a = generateIntegerFromSeed(c.bitSize(), (*out_seed), &numIterations); a = CBigNum(2) + (a % (c - CBigNum(3))); (*out_seed) += (numIterations + 1); // 2. Compute "z" = a^{2*t} mod c CBigNum z = a.pow_mod(CBigNum(2) * t, c); // 3. Check if "c" is prime. // Specifically, verify that gcd((z-1), c) == 1 AND (z^c0 mod c) == 1 // If so we return "c" as our result. if (c.gcd(z - CBigNum(1)).isOne() && z.pow_mod(c0, c).isOne()) { // Return "c", out_seed and prime_gen_counter // (the latter two of which were already updated) return c; } // 4. If the test did not succeed, increment "t" and loop t = t + CBigNum(1); } // end of test loop } // We only reach this point if the test loop has iterated MAX_PRIMEGEN_ATTEMPTS // and failed to identify a valid prime. Throw an exception. throw std::runtime_error("Unable to generate random prime (too many tests)"); } CBigNum generateIntegerFromSeed(uint32_t numBits, uint256 seed, uint32_t *numIterations) { CBigNum result(0); uint32_t iterations = ceil((double)numBits / (double)HASH_OUTPUT_BITS); #ifdef ZEROCOIN_DEBUG cout << "numBits = " << numBits << endl; cout << "iterations = " << iterations << endl; #endif // Loop "iterations" times filling up the value "result" with random bits for (uint32_t count = 0; count < iterations; count++) { // result += ( H(pseed + count) * 2^{count * p0len} ) result += CBigNum(calculateHash(seed + count)) * CBigNum(2).pow(count * HASH_OUTPUT_BITS); } result = CBigNum(2).pow(numBits - 1) + (result % (CBigNum(2).pow(numBits - 1))); // Return the number of iterations and the result *numIterations = iterations; return result; } /// \brief Determines whether a uint32_t is a prime through trial division. /// \param candidate Candidate to test. /// \return true if the value is prime, false otherwise /// /// Performs trial division to determine whether a uint32_t is prime. bool primalityTestByTrialDivision(uint32_t candidate) { // TODO: HACK HACK WRONG WRONG CBigNum canBignum(candidate); return canBignum.isPrime(); } } // namespace libzerocoin
#include <occa/internal/lang/type/class.hpp> namespace occa { namespace lang { class_t::class_t() : structure_t("") {} int class_t::type() const { return typeType::class_; } type_t& class_t::clone() const { return *(new class_t()); } dtype_t class_t::dtype() const { return dtype::byte; } void class_t::printDeclaration(printer &pout) const { } } }
//////////////////////////////////////////////////////////////////////////////// /// DISCLAIMER /// /// Copyright 2019 ArangoDB GmbH, Cologne, Germany /// /// Licensed under the Apache License, Version 2.0 (the "License"); /// you may not use this file except in compliance with the License. /// You may obtain a copy of the License at /// /// http://www.apache.org/licenses/LICENSE-2.0 /// /// Unless required by applicable law or agreed to in writing, software /// distributed under the License is distributed on an "AS IS" BASIS, /// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. /// See the License for the specific language governing permissions and /// limitations under the License. /// /// Copyright holder is ArangoDB GmbH, Cologne, Germany /// /// @author Dan Larkin-York //////////////////////////////////////////////////////////////////////////////// #include "RocksDBBackgroundErrorListener.h" #include "Logger/Logger.h" namespace arangodb { RocksDBBackgroundErrorListener::~RocksDBBackgroundErrorListener() {} void RocksDBBackgroundErrorListener::OnBackgroundError(rocksdb::BackgroundErrorReason reason, rocksdb::Status*) { if (!_called) { _called = true; std::string operation = "unknown"; switch (reason) { case rocksdb::BackgroundErrorReason::kFlush: { operation = "flush"; break; } case rocksdb::BackgroundErrorReason::kCompaction: { operation = "compaction"; break; } case rocksdb::BackgroundErrorReason::kWriteCallback: { operation = "write callback"; break; } case rocksdb::BackgroundErrorReason::kMemTable: { operation = "memtable"; break; } } LOG_TOPIC("fae2c", ERR, Logger::ROCKSDB) << "RocksDB encountered a background error during a " << operation << " operation; The database will be put in read-only " "mode, and subsequent write errors are likely"; } } } // namespace arangodb
/* * Copyright (C) 2010 The Android Open Source Project * Copyright (C) 2012-2014, The Linux Foundation. All rights reserved. * * Not a Contribution, Apache license notifications and license are * retained for attribution purposes only. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <cutils/properties.h> #include <utils/Log.h> #include <fcntl.h> #include <sys/ioctl.h> #include <linux/msm_mdp.h> #include <sys/resource.h> #include <sys/prctl.h> #include <poll.h> #include "hwc_utils.h" #include "hdmi.h" #include "qd_utils.h" #include "string.h" #include "overlay.h" #include <inttypes.h> using namespace qdutils; namespace qhwc { #define HWC_VSYNC_THREAD_NAME "hwcVsyncThread" #define PANEL_ON_STR "panel_power_on =" #define ARRAY_LENGTH(array) (sizeof((array))/sizeof((array)[0])) #define MAX_THERMAL_LEVEL 3 const int MAX_DATA = 64; int hwc_vsync_control(hwc_context_t* ctx, int dpy, int enable) { int ret = 0; if(!ctx->vstate.fakevsync && ioctl(ctx->dpyAttr[dpy].fd, MSMFB_OVERLAY_VSYNC_CTRL, &enable) < 0) { ALOGE("%s: vsync control failed. Dpy=%d, enable=%d : %s", __FUNCTION__, dpy, enable, strerror(errno)); ret = -errno; } return ret; } static void handle_vsync_event(hwc_context_t* ctx, int dpy, char *data) { // extract timestamp uint64_t timestamp = 0; if (!strncmp(data, "VSYNC=", strlen("VSYNC="))) { timestamp = strtoull(data + strlen("VSYNC="), NULL, 0); } // send timestamp to SurfaceFlinger ALOGD_IF (ctx->vstate.debug, "%s: timestamp %" PRIu64" sent to SF for dpy=%d", __FUNCTION__, timestamp, dpy); ctx->proc->vsync(ctx->proc, dpy, timestamp); } static void handle_blank_event(hwc_context_t* ctx, int dpy, char *data) { if (!strncmp(data, PANEL_ON_STR, strlen(PANEL_ON_STR))) { unsigned long int poweron = strtoul(data + strlen(PANEL_ON_STR), NULL, 0); ALOGI("%s: dpy:%d panel power state: %ld", __FUNCTION__, dpy, poweron); if (!ctx->mHDMIDisplay->isHDMIPrimaryDisplay()) { ctx->dpyAttr[dpy].isActive = poweron ? true: false; } } } static void handle_thermal_event(hwc_context_t* ctx, int dpy, char *data) { // extract thermal level uint64_t thermalLevel = 0; if (!strncmp(data, "thermal_level=", strlen("thermal_level="))) { thermalLevel = strtoull(data + strlen("thermal_level="), NULL, 0); } if (thermalLevel >= MAX_THERMAL_LEVEL) { ALOGD("%s: dpy:%d thermal_level=%" PRIu64"",__FUNCTION__,dpy,thermalLevel); ctx->mThermalBurstMode = true; } else ctx->mThermalBurstMode = false; } struct event { const char* name; void (*callback)(hwc_context_t* ctx, int dpy, char *data); }; struct event event_list[] = { { "vsync_event", handle_vsync_event }, { "show_blank_event", handle_blank_event }, { "msm_fb_thermal_level", handle_thermal_event }, }; #define num_events ARRAY_LENGTH(event_list) static void *vsync_loop(void *param) { hwc_context_t * ctx = reinterpret_cast<hwc_context_t *>(param); char thread_name[64] = HWC_VSYNC_THREAD_NAME; prctl(PR_SET_NAME, (unsigned long) &thread_name, 0, 0, 0); setpriority(PRIO_PROCESS, 0, HAL_PRIORITY_URGENT_DISPLAY + android::PRIORITY_MORE_FAVORABLE); char vdata[MAX_DATA]; //Number of physical displays //We poll on all the nodes. int num_displays = HWC_NUM_DISPLAY_TYPES - 1; struct pollfd pfd[num_displays][num_events]; char property[PROPERTY_VALUE_MAX]; if(property_get("debug.hwc.fakevsync", property, NULL) > 0) { if(atoi(property) == 1) ctx->vstate.fakevsync = true; } char node_path[MAX_SYSFS_FILE_PATH]; for (int dpy = HWC_DISPLAY_PRIMARY; dpy < num_displays; dpy++) { for(size_t ev = 0; ev < num_events; ev++) { snprintf(node_path, sizeof(node_path), "/sys/class/graphics/fb%d/%s", dpy == HWC_DISPLAY_PRIMARY ? 0 : overlay::Overlay::getInstance()-> getFbForDpy(HWC_DISPLAY_EXTERNAL), event_list[ev].name); ALOGI("%s: Reading event %zu for dpy %d from %s", __FUNCTION__, ev, dpy, node_path); pfd[dpy][ev].fd = open(node_path, O_RDONLY); if (dpy == HWC_DISPLAY_PRIMARY && pfd[dpy][ev].fd < 0) { // Make sure fb device is opened before starting // this thread so this never happens. ALOGE ("%s:unable to open event node for dpy=%d event=%zu, %s", __FUNCTION__, dpy, ev, strerror(errno)); if (ev == 0) { ctx->vstate.fakevsync = true; //XXX: Blank events don't work with fake vsync, //but we shouldn't be running on fake vsync anyway. break; } } pread(pfd[dpy][ev].fd, vdata , MAX_DATA, 0); if (pfd[dpy][ev].fd >= 0) pfd[dpy][ev].events = POLLPRI | POLLERR; } } if (LIKELY(!ctx->vstate.fakevsync)) { do { int err = poll(*pfd, (int)(num_displays * num_events), -1); if(err > 0) { for (int dpy = HWC_DISPLAY_PRIMARY; dpy < num_displays; dpy++) { for(size_t ev = 0; ev < num_events; ev++) { if (pfd[dpy][ev].revents & POLLPRI) { ssize_t len = pread(pfd[dpy][ev].fd, vdata, MAX_DATA, 0); if (UNLIKELY(len < 0)) { // If the read was just interrupted - it is not // a fatal error. Just continue in this case ALOGE ("%s: Unable to read event:%zu for \ dpy=%d : %s", __FUNCTION__, ev, dpy, strerror(errno)); continue; } event_list[ev].callback(ctx, dpy, vdata); } } } } else { ALOGE("%s: poll failed errno: %s", __FUNCTION__, strerror(errno)); continue; } } while (true); } else { //Fake vsync is used only when set explicitly through a property or when //the vsync timestamp node cannot be opened at bootup. There is no //fallback to fake vsync from the true vsync loop, ever, as the //condition can easily escape detection. //Also, fake vsync is delivered only for the primary display. do { usleep(16666); uint64_t timestamp = systemTime(); ctx->proc->vsync(ctx->proc, HWC_DISPLAY_PRIMARY, timestamp); } while (true); } for (int dpy = HWC_DISPLAY_PRIMARY; dpy <= HWC_DISPLAY_EXTERNAL; dpy++ ) { for( size_t event = 0; event < num_events; event++) { if(pfd[dpy][event].fd >= 0) close (pfd[dpy][event].fd); } } return NULL; } void init_vsync_thread(hwc_context_t* ctx) { int ret; pthread_t vsync_thread; ALOGI("Initializing VSYNC Thread"); ret = pthread_create(&vsync_thread, NULL, vsync_loop, (void*) ctx); if (ret) { ALOGE("%s: failed to create %s: %s", __FUNCTION__, HWC_VSYNC_THREAD_NAME, strerror(ret)); } } }; //namespace
// Copyright (c) 2017-2018, uPlexa Team // Copyright (c) 2014-2019, The Monero Project // // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, are // permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this list of // conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, this list // of conditions and the following disclaimer in the documentation and/or other // materials provided with the distribution. // // 3. Neither the name of the copyright holder nor the names of its contributors may be // used to endorse or promote products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL // THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF // THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // #include "device_default.hpp" #include "common/int-util.h" #include "cryptonote_basic/account.h" #include "cryptonote_basic/subaddress_index.h" #include "ringct/rctOps.h" #define ENCRYPTED_PAYMENT_ID_TAIL 0x8d #define CHACHA8_KEY_TAIL 0x8c namespace hw { namespace core { device_default::device_default() { } device_default::~device_default() { } /* ===================================================================== */ /* === Misc ==== */ /* ===================================================================== */ static inline unsigned char *operator &(crypto::ec_scalar &scalar) { return &reinterpret_cast<unsigned char &>(scalar); } static inline const unsigned char *operator &(const crypto::ec_scalar &scalar) { return &reinterpret_cast<const unsigned char &>(scalar); } /* ======================================================================= */ /* SETUP/TEARDOWN */ /* ======================================================================= */ bool device_default::set_name(const std::string &name) { this->name = name; return true; } const std::string device_default::get_name() const { return this->name; } bool device_default::init(void) { return true; } bool device_default::release() { return true; } bool device_default::connect(void) { return true; } bool device_default::disconnect() { return true; } bool device_default::set_mode(device_mode mode) { return device::set_mode(mode); } /* ======================================================================= */ /* LOCKER */ /* ======================================================================= */ void device_default::lock() { } bool device_default::try_lock() { return true; } void device_default::unlock() { } /* ======================================================================= */ /* WALLET & ADDRESS */ /* ======================================================================= */ bool device_default::generate_chacha_key(const cryptonote::account_keys &keys, crypto::chacha_key &key, uint64_t kdf_rounds) { const crypto::secret_key &view_key = keys.m_view_secret_key; const crypto::secret_key &spend_key = keys.m_spend_secret_key; epee::mlocked<tools::scrubbed_arr<char, sizeof(view_key) + sizeof(spend_key) + 1>> data; memcpy(data.data(), &view_key, sizeof(view_key)); memcpy(data.data() + sizeof(view_key), &spend_key, sizeof(spend_key)); data[sizeof(data) - 1] = CHACHA8_KEY_TAIL; crypto::generate_chacha_key(data.data(), sizeof(data), key, kdf_rounds); return true; } bool device_default::get_public_address(cryptonote::account_public_address &pubkey) { dfns(); } bool device_default::get_secret_keys(crypto::secret_key &viewkey , crypto::secret_key &spendkey) { dfns(); } /* ======================================================================= */ /* SUB ADDRESS */ /* ======================================================================= */ bool device_default::derive_subaddress_public_key(const crypto::public_key &out_key, const crypto::key_derivation &derivation, const std::size_t output_index, crypto::public_key &derived_key) { return crypto::derive_subaddress_public_key(out_key, derivation, output_index,derived_key); } crypto::public_key device_default::get_subaddress_spend_public_key(const cryptonote::account_keys& keys, const cryptonote::subaddress_index &index) { if (index.is_zero()) return keys.m_account_address.m_spend_public_key; // m = Hs(a || index_major || index_minor) crypto::secret_key m = get_subaddress_secret_key(keys.m_view_secret_key, index); // M = m*G crypto::public_key M; crypto::secret_key_to_public_key(m, M); // D = B + M crypto::public_key D = rct::rct2pk(rct::addKeys(rct::pk2rct(keys.m_account_address.m_spend_public_key), rct::pk2rct(M))); return D; } std::vector<crypto::public_key> device_default::get_subaddress_spend_public_keys(const cryptonote::account_keys &keys, uint32_t account, uint32_t begin, uint32_t end) { CHECK_AND_ASSERT_THROW_MES(begin <= end, "begin > end"); std::vector<crypto::public_key> pkeys; pkeys.reserve(end - begin); cryptonote::subaddress_index index = {account, begin}; ge_p3 p3; ge_cached cached; CHECK_AND_ASSERT_THROW_MES(ge_frombytes_vartime(&p3, (const unsigned char*)keys.m_account_address.m_spend_public_key.data) == 0, "ge_frombytes_vartime failed to convert spend public key"); ge_p3_to_cached(&cached, &p3); for (uint32_t idx = begin; idx < end; ++idx) { index.minor = idx; if (index.is_zero()) { pkeys.push_back(keys.m_account_address.m_spend_public_key); continue; } crypto::secret_key m = get_subaddress_secret_key(keys.m_view_secret_key, index); // M = m*G ge_scalarmult_base(&p3, (const unsigned char*)m.data); // D = B + M crypto::public_key D; ge_p1p1 p1p1; ge_add(&p1p1, &p3, &cached); ge_p1p1_to_p3(&p3, &p1p1); ge_p3_tobytes((unsigned char*)D.data, &p3); pkeys.push_back(D); } return pkeys; } cryptonote::account_public_address device_default::get_subaddress(const cryptonote::account_keys& keys, const cryptonote::subaddress_index &index) { if (index.is_zero()) return keys.m_account_address; crypto::public_key D = get_subaddress_spend_public_key(keys, index); // C = a*D crypto::public_key C = rct::rct2pk(rct::scalarmultKey(rct::pk2rct(D), rct::sk2rct(keys.m_view_secret_key))); // result: (C, D) cryptonote::account_public_address address; address.m_view_public_key = C; address.m_spend_public_key = D; return address; } crypto::secret_key device_default::get_subaddress_secret_key(const crypto::secret_key &a, const cryptonote::subaddress_index &index) { const char prefix[] = "SubAddr"; char data[sizeof(prefix) + sizeof(crypto::secret_key) + 2 * sizeof(uint32_t)]; memcpy(data, prefix, sizeof(prefix)); memcpy(data + sizeof(prefix), &a, sizeof(crypto::secret_key)); uint32_t idx = SWAP32LE(index.major); memcpy(data + sizeof(prefix) + sizeof(crypto::secret_key), &idx, sizeof(uint32_t)); idx = SWAP32LE(index.minor); memcpy(data + sizeof(prefix) + sizeof(crypto::secret_key) + sizeof(uint32_t), &idx, sizeof(uint32_t)); crypto::secret_key m; crypto::hash_to_scalar(data, sizeof(data), m); return m; } /* ======================================================================= */ /* DERIVATION & KEY */ /* ======================================================================= */ bool device_default::verify_keys(const crypto::secret_key &secret_key, const crypto::public_key &public_key) { crypto::public_key calculated_pub; bool r = crypto::secret_key_to_public_key(secret_key, calculated_pub); return r && public_key == calculated_pub; } bool device_default::scalarmultKey(rct::key & aP, const rct::key &P, const rct::key &a) { rct::scalarmultKey(aP, P,a); return true; } bool device_default::scalarmultBase(rct::key &aG, const rct::key &a) { rct::scalarmultBase(aG,a); return true; } bool device_default::sc_secret_add(crypto::secret_key &r, const crypto::secret_key &a, const crypto::secret_key &b) { sc_add(&r, &a, &b); return true; } crypto::secret_key device_default::generate_keys(crypto::public_key &pub, crypto::secret_key &sec, const crypto::secret_key& recovery_key, bool recover) { return crypto::generate_keys(pub, sec, recovery_key, recover); } bool device_default::generate_key_derivation(const crypto::public_key &key1, const crypto::secret_key &key2, crypto::key_derivation &derivation) { return crypto::generate_key_derivation(key1, key2, derivation); } bool device_default::derivation_to_scalar(const crypto::key_derivation &derivation, const size_t output_index, crypto::ec_scalar &res){ crypto::derivation_to_scalar(derivation,output_index, res); return true; } bool device_default::derive_secret_key(const crypto::key_derivation &derivation, const std::size_t output_index, const crypto::secret_key &base, crypto::secret_key &derived_key){ crypto::derive_secret_key(derivation, output_index, base, derived_key); return true; } bool device_default::derive_public_key(const crypto::key_derivation &derivation, const std::size_t output_index, const crypto::public_key &base, crypto::public_key &derived_key){ return crypto::derive_public_key(derivation, output_index, base, derived_key); } bool device_default::secret_key_to_public_key(const crypto::secret_key &sec, crypto::public_key &pub) { return crypto::secret_key_to_public_key(sec,pub); } bool device_default::generate_key_image(const crypto::public_key &pub, const crypto::secret_key &sec, crypto::key_image &image){ crypto::generate_key_image(pub, sec,image); return true; } bool device_default::conceal_derivation(crypto::key_derivation &derivation, const crypto::public_key &tx_pub_key, const std::vector<crypto::public_key> &additional_tx_pub_keys, const crypto::key_derivation &main_derivation, const std::vector<crypto::key_derivation> &additional_derivations){ return true; } /* ======================================================================= */ /* TRANSACTION */ /* ======================================================================= */ bool device_default::open_tx(crypto::secret_key &tx_key) { cryptonote::keypair txkey = cryptonote::keypair::generate(*this); tx_key = txkey.sec; return true; } bool device_default::add_output_key_mapping(const crypto::public_key &Aout, const crypto::public_key &Bout, const bool is_subaddress, const size_t real_output_index, const rct::key &amount_key, const crypto::public_key &out_eph_public_key) { return true; } bool device_default::encrypt_payment_id(crypto::hash8 &payment_id, const crypto::public_key &public_key, const crypto::secret_key &secret_key) { crypto::key_derivation derivation; crypto::hash hash; char data[33]; /* A hash, and an extra byte */ if (!generate_key_derivation(public_key, secret_key, derivation)) return false; memcpy(data, &derivation, 32); data[32] = ENCRYPTED_PAYMENT_ID_TAIL; cn_fast_hash(data, 33, hash); for (size_t b = 0; b < 8; ++b) payment_id.data[b] ^= hash.data[b]; return true; } bool device_default::ecdhEncode(rct::ecdhTuple & unmasked, const rct::key & sharedSec) { rct::ecdhEncode(unmasked, sharedSec); return true; } bool device_default::ecdhDecode(rct::ecdhTuple & masked, const rct::key & sharedSec) { rct::ecdhDecode(masked, sharedSec); return true; } bool device_default::mlsag_prepare(const rct::key &H, const rct::key &xx, rct::key &a, rct::key &aG, rct::key &aHP, rct::key &II) { rct::skpkGen(a, aG); rct::scalarmultKey(aHP, H, a); rct::scalarmultKey(II, H, xx); return true; } bool device_default::mlsag_prepare(rct::key &a, rct::key &aG) { rct::skpkGen(a, aG); return true; } bool device_default::mlsag_prehash(const std::string &blob, size_t inputs_size, size_t outputs_size, const rct::keyV &hashes, const rct::ctkeyV &outPk, rct::key &prehash) { prehash = rct::cn_fast_hash(hashes); return true; } bool device_default::mlsag_hash(const rct::keyV &toHash, rct::key &c_old) { c_old = rct::hash_to_scalar(toHash); return true; } bool device_default::mlsag_sign(const rct::key &c, const rct::keyV &xx, const rct::keyV &alpha, const size_t rows, const size_t dsRows, rct::keyV &ss ) { CHECK_AND_ASSERT_THROW_MES(dsRows<=rows, "dsRows greater than rows"); CHECK_AND_ASSERT_THROW_MES(xx.size() == rows, "xx size does not match rows"); CHECK_AND_ASSERT_THROW_MES(alpha.size() == rows, "alpha size does not match rows"); CHECK_AND_ASSERT_THROW_MES(ss.size() == rows, "ss size does not match rows"); for (size_t j = 0; j < rows; j++) { sc_mulsub(ss[j].bytes, c.bytes, xx[j].bytes, alpha[j].bytes); } return true; } bool device_default::close_tx() { return true; } /* ---------------------------------------------------------- */ static device_default *default_core_device = NULL; void register_all(std::map<std::string, std::unique_ptr<device>> &registry) { if (!default_core_device) { default_core_device = new device_default(); default_core_device->set_name("default_core_device"); } registry.insert(std::make_pair("default", std::unique_ptr<device>(default_core_device))); } } }
// Copyright 2007, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Author: wan@google.com (Zhanyong Wan) // Google Mock - a framework for writing C++ mock classes. // // This file tests the built-in actions. #include "gmock/gmock-actions.h" #include <algorithm> #include <iterator> #include <memory> #include <string> #include "gmock/gmock.h" #include "gmock/internal/gmock-port.h" #include "gtest/gtest.h" #include "gtest/gtest-spi.h" namespace { // This list should be kept sorted. using testing::Action; using testing::ActionInterface; using testing::Assign; using testing::ByMove; using testing::ByRef; using testing::DefaultValue; using testing::DoDefault; using testing::IgnoreResult; using testing::Invoke; using testing::InvokeWithoutArgs; using testing::MakePolymorphicAction; using testing::Ne; using testing::PolymorphicAction; using testing::Return; using testing::ReturnNull; using testing::ReturnRef; using testing::ReturnRefOfCopy; using testing::SetArgPointee; using testing::SetArgumentPointee; using testing::_; using testing::get; using testing::internal::BuiltInDefaultValue; using testing::internal::Int64; using testing::internal::UInt64; using testing::make_tuple; using testing::tuple; using testing::tuple_element; #if !GTEST_OS_WINDOWS_MOBILE using testing::SetErrnoAndReturn; #endif #if GTEST_HAS_PROTOBUF_ using testing::internal::TestMessage; #endif // GTEST_HAS_PROTOBUF_ // Tests that BuiltInDefaultValue<T*>::Get() returns NULL. TEST(BuiltInDefaultValueTest, IsNullForPointerTypes) { EXPECT_TRUE(BuiltInDefaultValue<int*>::Get() == NULL); EXPECT_TRUE(BuiltInDefaultValue<const char*>::Get() == NULL); EXPECT_TRUE(BuiltInDefaultValue<void*>::Get() == NULL); } // Tests that BuiltInDefaultValue<T*>::Exists() return true. TEST(BuiltInDefaultValueTest, ExistsForPointerTypes) { EXPECT_TRUE(BuiltInDefaultValue<int*>::Exists()); EXPECT_TRUE(BuiltInDefaultValue<const char*>::Exists()); EXPECT_TRUE(BuiltInDefaultValue<void*>::Exists()); } // Tests that BuiltInDefaultValue<T>::Get() returns 0 when T is a // built-in numeric type. TEST(BuiltInDefaultValueTest, IsZeroForNumericTypes) { EXPECT_EQ(0U, BuiltInDefaultValue<unsigned char>::Get()); EXPECT_EQ(0, BuiltInDefaultValue<signed char>::Get()); EXPECT_EQ(0, BuiltInDefaultValue<char>::Get()); #if GMOCK_HAS_SIGNED_WCHAR_T_ EXPECT_EQ(0U, BuiltInDefaultValue<unsigned wchar_t>::Get()); EXPECT_EQ(0, BuiltInDefaultValue<signed wchar_t>::Get()); #endif #if GMOCK_WCHAR_T_IS_NATIVE_ EXPECT_EQ(0, BuiltInDefaultValue<wchar_t>::Get()); #endif EXPECT_EQ(0U, BuiltInDefaultValue<unsigned short>::Get()); // NOLINT EXPECT_EQ(0, BuiltInDefaultValue<signed short>::Get()); // NOLINT EXPECT_EQ(0, BuiltInDefaultValue<short>::Get()); // NOLINT EXPECT_EQ(0U, BuiltInDefaultValue<unsigned int>::Get()); EXPECT_EQ(0, BuiltInDefaultValue<signed int>::Get()); EXPECT_EQ(0, BuiltInDefaultValue<int>::Get()); EXPECT_EQ(0U, BuiltInDefaultValue<unsigned long>::Get()); // NOLINT EXPECT_EQ(0, BuiltInDefaultValue<signed long>::Get()); // NOLINT EXPECT_EQ(0, BuiltInDefaultValue<long>::Get()); // NOLINT EXPECT_EQ(0U, BuiltInDefaultValue<UInt64>::Get()); EXPECT_EQ(0, BuiltInDefaultValue<Int64>::Get()); EXPECT_EQ(0, BuiltInDefaultValue<float>::Get()); EXPECT_EQ(0, BuiltInDefaultValue<double>::Get()); } // Tests that BuiltInDefaultValue<T>::Exists() returns true when T is a // built-in numeric type. TEST(BuiltInDefaultValueTest, ExistsForNumericTypes) { EXPECT_TRUE(BuiltInDefaultValue<unsigned char>::Exists()); EXPECT_TRUE(BuiltInDefaultValue<signed char>::Exists()); EXPECT_TRUE(BuiltInDefaultValue<char>::Exists()); #if GMOCK_HAS_SIGNED_WCHAR_T_ EXPECT_TRUE(BuiltInDefaultValue<unsigned wchar_t>::Exists()); EXPECT_TRUE(BuiltInDefaultValue<signed wchar_t>::Exists()); #endif #if GMOCK_WCHAR_T_IS_NATIVE_ EXPECT_TRUE(BuiltInDefaultValue<wchar_t>::Exists()); #endif EXPECT_TRUE(BuiltInDefaultValue<unsigned short>::Exists()); // NOLINT EXPECT_TRUE(BuiltInDefaultValue<signed short>::Exists()); // NOLINT EXPECT_TRUE(BuiltInDefaultValue<short>::Exists()); // NOLINT EXPECT_TRUE(BuiltInDefaultValue<unsigned int>::Exists()); EXPECT_TRUE(BuiltInDefaultValue<signed int>::Exists()); EXPECT_TRUE(BuiltInDefaultValue<int>::Exists()); EXPECT_TRUE(BuiltInDefaultValue<unsigned long>::Exists()); // NOLINT EXPECT_TRUE(BuiltInDefaultValue<signed long>::Exists()); // NOLINT EXPECT_TRUE(BuiltInDefaultValue<long>::Exists()); // NOLINT EXPECT_TRUE(BuiltInDefaultValue<UInt64>::Exists()); EXPECT_TRUE(BuiltInDefaultValue<Int64>::Exists()); EXPECT_TRUE(BuiltInDefaultValue<float>::Exists()); EXPECT_TRUE(BuiltInDefaultValue<double>::Exists()); } // Tests that BuiltInDefaultValue<bool>::Get() returns false. TEST(BuiltInDefaultValueTest, IsFalseForBool) { EXPECT_FALSE(BuiltInDefaultValue<bool>::Get()); } // Tests that BuiltInDefaultValue<bool>::Exists() returns true. TEST(BuiltInDefaultValueTest, BoolExists) { EXPECT_TRUE(BuiltInDefaultValue<bool>::Exists()); } // Tests that BuiltInDefaultValue<T>::Get() returns "" when T is a // string type. TEST(BuiltInDefaultValueTest, IsEmptyStringForString) { #if GTEST_HAS_GLOBAL_STRING EXPECT_EQ("", BuiltInDefaultValue< ::string>::Get()); #endif // GTEST_HAS_GLOBAL_STRING EXPECT_EQ("", BuiltInDefaultValue< ::std::string>::Get()); } // Tests that BuiltInDefaultValue<T>::Exists() returns true when T is a // string type. TEST(BuiltInDefaultValueTest, ExistsForString) { #if GTEST_HAS_GLOBAL_STRING EXPECT_TRUE(BuiltInDefaultValue< ::string>::Exists()); #endif // GTEST_HAS_GLOBAL_STRING EXPECT_TRUE(BuiltInDefaultValue< ::std::string>::Exists()); } // Tests that BuiltInDefaultValue<const T>::Get() returns the same // value as BuiltInDefaultValue<T>::Get() does. TEST(BuiltInDefaultValueTest, WorksForConstTypes) { EXPECT_EQ("", BuiltInDefaultValue<const std::string>::Get()); EXPECT_EQ(0, BuiltInDefaultValue<const int>::Get()); EXPECT_TRUE(BuiltInDefaultValue<char* const>::Get() == NULL); EXPECT_FALSE(BuiltInDefaultValue<const bool>::Get()); } // A type that's default constructible. class MyDefaultConstructible { public: MyDefaultConstructible() : value_(42) {} int value() const { return value_; } private: int value_; }; // A type that's not default constructible. class MyNonDefaultConstructible { public: // Does not have a default ctor. explicit MyNonDefaultConstructible(int a_value) : value_(a_value) {} int value() const { return value_; } private: int value_; }; #if GTEST_HAS_STD_TYPE_TRAITS_ TEST(BuiltInDefaultValueTest, ExistsForDefaultConstructibleType) { EXPECT_TRUE(BuiltInDefaultValue<MyDefaultConstructible>::Exists()); } TEST(BuiltInDefaultValueTest, IsDefaultConstructedForDefaultConstructibleType) { EXPECT_EQ(42, BuiltInDefaultValue<MyDefaultConstructible>::Get().value()); } #endif // GTEST_HAS_STD_TYPE_TRAITS_ TEST(BuiltInDefaultValueTest, DoesNotExistForNonDefaultConstructibleType) { EXPECT_FALSE(BuiltInDefaultValue<MyNonDefaultConstructible>::Exists()); } // Tests that BuiltInDefaultValue<T&>::Get() aborts the program. TEST(BuiltInDefaultValueDeathTest, IsUndefinedForReferences) { EXPECT_DEATH_IF_SUPPORTED({ BuiltInDefaultValue<int&>::Get(); }, ""); EXPECT_DEATH_IF_SUPPORTED({ BuiltInDefaultValue<const char&>::Get(); }, ""); } TEST(BuiltInDefaultValueDeathTest, IsUndefinedForNonDefaultConstructibleType) { EXPECT_DEATH_IF_SUPPORTED({ BuiltInDefaultValue<MyNonDefaultConstructible>::Get(); }, ""); } // Tests that DefaultValue<T>::IsSet() is false initially. TEST(DefaultValueTest, IsInitiallyUnset) { EXPECT_FALSE(DefaultValue<int>::IsSet()); EXPECT_FALSE(DefaultValue<MyDefaultConstructible>::IsSet()); EXPECT_FALSE(DefaultValue<const MyNonDefaultConstructible>::IsSet()); } // Tests that DefaultValue<T> can be set and then unset. TEST(DefaultValueTest, CanBeSetAndUnset) { EXPECT_TRUE(DefaultValue<int>::Exists()); EXPECT_FALSE(DefaultValue<const MyNonDefaultConstructible>::Exists()); DefaultValue<int>::Set(1); DefaultValue<const MyNonDefaultConstructible>::Set( MyNonDefaultConstructible(42)); EXPECT_EQ(1, DefaultValue<int>::Get()); EXPECT_EQ(42, DefaultValue<const MyNonDefaultConstructible>::Get().value()); EXPECT_TRUE(DefaultValue<int>::Exists()); EXPECT_TRUE(DefaultValue<const MyNonDefaultConstructible>::Exists()); DefaultValue<int>::Clear(); DefaultValue<const MyNonDefaultConstructible>::Clear(); EXPECT_FALSE(DefaultValue<int>::IsSet()); EXPECT_FALSE(DefaultValue<const MyNonDefaultConstructible>::IsSet()); EXPECT_TRUE(DefaultValue<int>::Exists()); EXPECT_FALSE(DefaultValue<const MyNonDefaultConstructible>::Exists()); } // Tests that DefaultValue<T>::Get() returns the // BuiltInDefaultValue<T>::Get() when DefaultValue<T>::IsSet() is // false. TEST(DefaultValueDeathTest, GetReturnsBuiltInDefaultValueWhenUnset) { EXPECT_FALSE(DefaultValue<int>::IsSet()); EXPECT_TRUE(DefaultValue<int>::Exists()); EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible>::IsSet()); EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible>::Exists()); EXPECT_EQ(0, DefaultValue<int>::Get()); EXPECT_DEATH_IF_SUPPORTED({ DefaultValue<MyNonDefaultConstructible>::Get(); }, ""); } #if GTEST_HAS_STD_UNIQUE_PTR_ TEST(DefaultValueTest, GetWorksForMoveOnlyIfSet) { EXPECT_TRUE(DefaultValue<std::unique_ptr<int>>::Exists()); EXPECT_TRUE(DefaultValue<std::unique_ptr<int>>::Get() == NULL); DefaultValue<std::unique_ptr<int>>::SetFactory([] { return std::unique_ptr<int>(new int(42)); }); EXPECT_TRUE(DefaultValue<std::unique_ptr<int>>::Exists()); std::unique_ptr<int> i = DefaultValue<std::unique_ptr<int>>::Get(); EXPECT_EQ(42, *i); } #endif // GTEST_HAS_STD_UNIQUE_PTR_ // Tests that DefaultValue<void>::Get() returns void. TEST(DefaultValueTest, GetWorksForVoid) { return DefaultValue<void>::Get(); } // Tests using DefaultValue with a reference type. // Tests that DefaultValue<T&>::IsSet() is false initially. TEST(DefaultValueOfReferenceTest, IsInitiallyUnset) { EXPECT_FALSE(DefaultValue<int&>::IsSet()); EXPECT_FALSE(DefaultValue<MyDefaultConstructible&>::IsSet()); EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible&>::IsSet()); } // Tests that DefaultValue<T&>::Exists is false initiallly. TEST(DefaultValueOfReferenceTest, IsInitiallyNotExisting) { EXPECT_FALSE(DefaultValue<int&>::Exists()); EXPECT_FALSE(DefaultValue<MyDefaultConstructible&>::Exists()); EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible&>::Exists()); } // Tests that DefaultValue<T&> can be set and then unset. TEST(DefaultValueOfReferenceTest, CanBeSetAndUnset) { int n = 1; DefaultValue<const int&>::Set(n); MyNonDefaultConstructible x(42); DefaultValue<MyNonDefaultConstructible&>::Set(x); EXPECT_TRUE(DefaultValue<const int&>::Exists()); EXPECT_TRUE(DefaultValue<MyNonDefaultConstructible&>::Exists()); EXPECT_EQ(&n, &(DefaultValue<const int&>::Get())); EXPECT_EQ(&x, &(DefaultValue<MyNonDefaultConstructible&>::Get())); DefaultValue<const int&>::Clear(); DefaultValue<MyNonDefaultConstructible&>::Clear(); EXPECT_FALSE(DefaultValue<const int&>::Exists()); EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible&>::Exists()); EXPECT_FALSE(DefaultValue<const int&>::IsSet()); EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible&>::IsSet()); } // Tests that DefaultValue<T&>::Get() returns the // BuiltInDefaultValue<T&>::Get() when DefaultValue<T&>::IsSet() is // false. TEST(DefaultValueOfReferenceDeathTest, GetReturnsBuiltInDefaultValueWhenUnset) { EXPECT_FALSE(DefaultValue<int&>::IsSet()); EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible&>::IsSet()); EXPECT_DEATH_IF_SUPPORTED({ DefaultValue<int&>::Get(); }, ""); EXPECT_DEATH_IF_SUPPORTED({ DefaultValue<MyNonDefaultConstructible>::Get(); }, ""); } // Tests that ActionInterface can be implemented by defining the // Perform method. typedef int MyGlobalFunction(bool, int); class MyActionImpl : public ActionInterface<MyGlobalFunction> { public: virtual int Perform(const tuple<bool, int>& args) { return get<0>(args) ? get<1>(args) : 0; } }; TEST(ActionInterfaceTest, CanBeImplementedByDefiningPerform) { MyActionImpl my_action_impl; (void)my_action_impl; } TEST(ActionInterfaceTest, MakeAction) { Action<MyGlobalFunction> action = MakeAction(new MyActionImpl); // When exercising the Perform() method of Action<F>, we must pass // it a tuple whose size and type are compatible with F's argument // types. For example, if F is int(), then Perform() takes a // 0-tuple; if F is void(bool, int), then Perform() takes a // tuple<bool, int>, and so on. EXPECT_EQ(5, action.Perform(make_tuple(true, 5))); } // Tests that Action<F> can be contructed from a pointer to // ActionInterface<F>. TEST(ActionTest, CanBeConstructedFromActionInterface) { Action<MyGlobalFunction> action(new MyActionImpl); } // Tests that Action<F> delegates actual work to ActionInterface<F>. TEST(ActionTest, DelegatesWorkToActionInterface) { const Action<MyGlobalFunction> action(new MyActionImpl); EXPECT_EQ(5, action.Perform(make_tuple(true, 5))); EXPECT_EQ(0, action.Perform(make_tuple(false, 1))); } // Tests that Action<F> can be copied. TEST(ActionTest, IsCopyable) { Action<MyGlobalFunction> a1(new MyActionImpl); Action<MyGlobalFunction> a2(a1); // Tests the copy constructor. // a1 should continue to work after being copied from. EXPECT_EQ(5, a1.Perform(make_tuple(true, 5))); EXPECT_EQ(0, a1.Perform(make_tuple(false, 1))); // a2 should work like the action it was copied from. EXPECT_EQ(5, a2.Perform(make_tuple(true, 5))); EXPECT_EQ(0, a2.Perform(make_tuple(false, 1))); a2 = a1; // Tests the assignment operator. // a1 should continue to work after being copied from. EXPECT_EQ(5, a1.Perform(make_tuple(true, 5))); EXPECT_EQ(0, a1.Perform(make_tuple(false, 1))); // a2 should work like the action it was copied from. EXPECT_EQ(5, a2.Perform(make_tuple(true, 5))); EXPECT_EQ(0, a2.Perform(make_tuple(false, 1))); } // Tests that an Action<From> object can be converted to a // compatible Action<To> object. class IsNotZero : public ActionInterface<bool(int)> { // NOLINT public: virtual bool Perform(const tuple<int>& arg) { return get<0>(arg) != 0; } }; #if !GTEST_OS_SYMBIAN // Compiling this test on Nokia's Symbian compiler fails with: // 'Result' is not a member of class 'testing::internal::Function<int>' // (point of instantiation: '@unnamed@gmock_actions_test_cc@:: // ActionTest_CanBeConvertedToOtherActionType_Test::TestBody()') // with no obvious fix. TEST(ActionTest, CanBeConvertedToOtherActionType) { const Action<bool(int)> a1(new IsNotZero); // NOLINT const Action<int(char)> a2 = Action<int(char)>(a1); // NOLINT EXPECT_EQ(1, a2.Perform(make_tuple('a'))); EXPECT_EQ(0, a2.Perform(make_tuple('\0'))); } #endif // !GTEST_OS_SYMBIAN // The following two classes are for testing MakePolymorphicAction(). // Implements a polymorphic action that returns the second of the // arguments it receives. class ReturnSecondArgumentAction { public: // We want to verify that MakePolymorphicAction() can work with a // polymorphic action whose Perform() method template is either // const or not. This lets us verify the non-const case. template <typename Result, typename ArgumentTuple> Result Perform(const ArgumentTuple& args) { return get<1>(args); } }; // Implements a polymorphic action that can be used in a nullary // function to return 0. class ReturnZeroFromNullaryFunctionAction { public: // For testing that MakePolymorphicAction() works when the // implementation class' Perform() method template takes only one // template parameter. // // We want to verify that MakePolymorphicAction() can work with a // polymorphic action whose Perform() method template is either // const or not. This lets us verify the const case. template <typename Result> Result Perform(const tuple<>&) const { return 0; } }; // These functions verify that MakePolymorphicAction() returns a // PolymorphicAction<T> where T is the argument's type. PolymorphicAction<ReturnSecondArgumentAction> ReturnSecondArgument() { return MakePolymorphicAction(ReturnSecondArgumentAction()); } PolymorphicAction<ReturnZeroFromNullaryFunctionAction> ReturnZeroFromNullaryFunction() { return MakePolymorphicAction(ReturnZeroFromNullaryFunctionAction()); } // Tests that MakePolymorphicAction() turns a polymorphic action // implementation class into a polymorphic action. TEST(MakePolymorphicActionTest, ConstructsActionFromImpl) { Action<int(bool, int, double)> a1 = ReturnSecondArgument(); // NOLINT EXPECT_EQ(5, a1.Perform(make_tuple(false, 5, 2.0))); } // Tests that MakePolymorphicAction() works when the implementation // class' Perform() method template has only one template parameter. TEST(MakePolymorphicActionTest, WorksWhenPerformHasOneTemplateParameter) { Action<int()> a1 = ReturnZeroFromNullaryFunction(); EXPECT_EQ(0, a1.Perform(make_tuple())); Action<void*()> a2 = ReturnZeroFromNullaryFunction(); EXPECT_TRUE(a2.Perform(make_tuple()) == NULL); } // Tests that Return() works as an action for void-returning // functions. TEST(ReturnTest, WorksForVoid) { const Action<void(int)> ret = Return(); // NOLINT return ret.Perform(make_tuple(1)); } // Tests that Return(v) returns v. TEST(ReturnTest, ReturnsGivenValue) { Action<int()> ret = Return(1); // NOLINT EXPECT_EQ(1, ret.Perform(make_tuple())); ret = Return(-5); EXPECT_EQ(-5, ret.Perform(make_tuple())); } // Tests that Return("string literal") works. TEST(ReturnTest, AcceptsStringLiteral) { Action<const char*()> a1 = Return("Hello"); EXPECT_STREQ("Hello", a1.Perform(make_tuple())); Action<std::string()> a2 = Return("world"); EXPECT_EQ("world", a2.Perform(make_tuple())); } // Test struct which wraps a vector of integers. Used in // 'SupportsWrapperReturnType' test. struct IntegerVectorWrapper { std::vector<int> * v; IntegerVectorWrapper(std::vector<int>& _v) : v(&_v) {} // NOLINT }; // Tests that Return() works when return type is a wrapper type. TEST(ReturnTest, SupportsWrapperReturnType) { // Initialize vector of integers. std::vector<int> v; for (int i = 0; i < 5; ++i) v.push_back(i); // Return() called with 'v' as argument. The Action will return the same data // as 'v' (copy) but it will be wrapped in an IntegerVectorWrapper. Action<IntegerVectorWrapper()> a = Return(v); const std::vector<int>& result = *(a.Perform(make_tuple()).v); EXPECT_THAT(result, ::testing::ElementsAre(0, 1, 2, 3, 4)); } // Tests that Return(v) is covaraint. struct Base { bool operator==(const Base&) { return true; } }; struct Derived : public Base { bool operator==(const Derived&) { return true; } }; TEST(ReturnTest, IsCovariant) { Base base; Derived derived; Action<Base*()> ret = Return(&base); EXPECT_EQ(&base, ret.Perform(make_tuple())); ret = Return(&derived); EXPECT_EQ(&derived, ret.Perform(make_tuple())); } // Tests that the type of the value passed into Return is converted into T // when the action is cast to Action<T(...)> rather than when the action is // performed. See comments on testing::internal::ReturnAction in // gmock-actions.h for more information. class FromType { public: explicit FromType(bool* is_converted) : converted_(is_converted) {} bool* converted() const { return converted_; } private: bool* const converted_; GTEST_DISALLOW_ASSIGN_(FromType); }; class ToType { public: // Must allow implicit conversion due to use in ImplicitCast_<T>. ToType(const FromType& x) { *x.converted() = true; } // NOLINT }; TEST(ReturnTest, ConvertsArgumentWhenConverted) { bool converted = false; FromType x(&converted); Action<ToType()> action(Return(x)); EXPECT_TRUE(converted) << "Return must convert its argument in its own " << "conversion operator."; converted = false; action.Perform(tuple<>()); EXPECT_FALSE(converted) << "Action must NOT convert its argument " << "when performed."; } class DestinationType {}; class SourceType { public: // Note: a non-const typecast operator. operator DestinationType() { return DestinationType(); } }; TEST(ReturnTest, CanConvertArgumentUsingNonConstTypeCastOperator) { SourceType s; Action<DestinationType()> action(Return(s)); } // Tests that ReturnNull() returns NULL in a pointer-returning function. TEST(ReturnNullTest, WorksInPointerReturningFunction) { const Action<int*()> a1 = ReturnNull(); EXPECT_TRUE(a1.Perform(make_tuple()) == NULL); const Action<const char*(bool)> a2 = ReturnNull(); // NOLINT EXPECT_TRUE(a2.Perform(make_tuple(true)) == NULL); } #if GTEST_HAS_STD_UNIQUE_PTR_ // Tests that ReturnNull() returns NULL for shared_ptr and unique_ptr returning // functions. TEST(ReturnNullTest, WorksInSmartPointerReturningFunction) { const Action<std::unique_ptr<const int>()> a1 = ReturnNull(); EXPECT_TRUE(a1.Perform(make_tuple()) == nullptr); const Action<std::shared_ptr<int>(std::string)> a2 = ReturnNull(); EXPECT_TRUE(a2.Perform(make_tuple("foo")) == nullptr); } #endif // GTEST_HAS_STD_UNIQUE_PTR_ // Tests that ReturnRef(v) works for reference types. TEST(ReturnRefTest, WorksForReference) { const int n = 0; const Action<const int&(bool)> ret = ReturnRef(n); // NOLINT EXPECT_EQ(&n, &ret.Perform(make_tuple(true))); } // Tests that ReturnRef(v) is covariant. TEST(ReturnRefTest, IsCovariant) { Base base; Derived derived; Action<Base&()> a = ReturnRef(base); EXPECT_EQ(&base, &a.Perform(make_tuple())); a = ReturnRef(derived); EXPECT_EQ(&derived, &a.Perform(make_tuple())); } // Tests that ReturnRefOfCopy(v) works for reference types. TEST(ReturnRefOfCopyTest, WorksForReference) { int n = 42; const Action<const int&()> ret = ReturnRefOfCopy(n); EXPECT_NE(&n, &ret.Perform(make_tuple())); EXPECT_EQ(42, ret.Perform(make_tuple())); n = 43; EXPECT_NE(&n, &ret.Perform(make_tuple())); EXPECT_EQ(42, ret.Perform(make_tuple())); } // Tests that ReturnRefOfCopy(v) is covariant. TEST(ReturnRefOfCopyTest, IsCovariant) { Base base; Derived derived; Action<Base&()> a = ReturnRefOfCopy(base); EXPECT_NE(&base, &a.Perform(make_tuple())); a = ReturnRefOfCopy(derived); EXPECT_NE(&derived, &a.Perform(make_tuple())); } // Tests that DoDefault() does the default action for the mock method. class MockClass { public: MockClass() {} MOCK_METHOD1(IntFunc, int(bool flag)); // NOLINT MOCK_METHOD0(Foo, MyNonDefaultConstructible()); #if GTEST_HAS_STD_UNIQUE_PTR_ MOCK_METHOD0(MakeUnique, std::unique_ptr<int>()); MOCK_METHOD0(MakeUniqueBase, std::unique_ptr<Base>()); MOCK_METHOD0(MakeVectorUnique, std::vector<std::unique_ptr<int>>()); #endif private: GTEST_DISALLOW_COPY_AND_ASSIGN_(MockClass); }; // Tests that DoDefault() returns the built-in default value for the // return type by default. TEST(DoDefaultTest, ReturnsBuiltInDefaultValueByDefault) { MockClass mock; EXPECT_CALL(mock, IntFunc(_)) .WillOnce(DoDefault()); EXPECT_EQ(0, mock.IntFunc(true)); } // Tests that DoDefault() throws (when exceptions are enabled) or aborts // the process when there is no built-in default value for the return type. TEST(DoDefaultDeathTest, DiesForUnknowType) { MockClass mock; EXPECT_CALL(mock, Foo()) .WillRepeatedly(DoDefault()); #if GTEST_HAS_EXCEPTIONS EXPECT_ANY_THROW(mock.Foo()); #else EXPECT_DEATH_IF_SUPPORTED({ mock.Foo(); }, ""); #endif } // Tests that using DoDefault() inside a composite action leads to a // run-time error. void VoidFunc(bool /* flag */) {} TEST(DoDefaultDeathTest, DiesIfUsedInCompositeAction) { MockClass mock; EXPECT_CALL(mock, IntFunc(_)) .WillRepeatedly(DoAll(Invoke(VoidFunc), DoDefault())); // Ideally we should verify the error message as well. Sadly, // EXPECT_DEATH() can only capture stderr, while Google Mock's // errors are printed on stdout. Therefore we have to settle for // not verifying the message. EXPECT_DEATH_IF_SUPPORTED({ mock.IntFunc(true); }, ""); } // Tests that DoDefault() returns the default value set by // DefaultValue<T>::Set() when it's not overridden by an ON_CALL(). TEST(DoDefaultTest, ReturnsUserSpecifiedPerTypeDefaultValueWhenThereIsOne) { DefaultValue<int>::Set(1); MockClass mock; EXPECT_CALL(mock, IntFunc(_)) .WillOnce(DoDefault()); EXPECT_EQ(1, mock.IntFunc(false)); DefaultValue<int>::Clear(); } // Tests that DoDefault() does the action specified by ON_CALL(). TEST(DoDefaultTest, DoesWhatOnCallSpecifies) { MockClass mock; ON_CALL(mock, IntFunc(_)) .WillByDefault(Return(2)); EXPECT_CALL(mock, IntFunc(_)) .WillOnce(DoDefault()); EXPECT_EQ(2, mock.IntFunc(false)); } // Tests that using DoDefault() in ON_CALL() leads to a run-time failure. TEST(DoDefaultTest, CannotBeUsedInOnCall) { MockClass mock; EXPECT_NONFATAL_FAILURE({ // NOLINT ON_CALL(mock, IntFunc(_)) .WillByDefault(DoDefault()); }, "DoDefault() cannot be used in ON_CALL()"); } // Tests that SetArgPointee<N>(v) sets the variable pointed to by // the N-th (0-based) argument to v. TEST(SetArgPointeeTest, SetsTheNthPointee) { typedef void MyFunction(bool, int*, char*); Action<MyFunction> a = SetArgPointee<1>(2); int n = 0; char ch = '\0'; a.Perform(make_tuple(true, &n, &ch)); EXPECT_EQ(2, n); EXPECT_EQ('\0', ch); a = SetArgPointee<2>('a'); n = 0; ch = '\0'; a.Perform(make_tuple(true, &n, &ch)); EXPECT_EQ(0, n); EXPECT_EQ('a', ch); } #if !((GTEST_GCC_VER_ && GTEST_GCC_VER_ < 40000) || GTEST_OS_SYMBIAN) // Tests that SetArgPointee<N>() accepts a string literal. // GCC prior to v4.0 and the Symbian compiler do not support this. TEST(SetArgPointeeTest, AcceptsStringLiteral) { typedef void MyFunction(std::string*, const char**); Action<MyFunction> a = SetArgPointee<0>("hi"); std::string str; const char* ptr = NULL; a.Perform(make_tuple(&str, &ptr)); EXPECT_EQ("hi", str); EXPECT_TRUE(ptr == NULL); a = SetArgPointee<1>("world"); str = ""; a.Perform(make_tuple(&str, &ptr)); EXPECT_EQ("", str); EXPECT_STREQ("world", ptr); } TEST(SetArgPointeeTest, AcceptsWideStringLiteral) { typedef void MyFunction(const wchar_t**); Action<MyFunction> a = SetArgPointee<0>(L"world"); const wchar_t* ptr = NULL; a.Perform(make_tuple(&ptr)); EXPECT_STREQ(L"world", ptr); # if GTEST_HAS_STD_WSTRING typedef void MyStringFunction(std::wstring*); Action<MyStringFunction> a2 = SetArgPointee<0>(L"world"); std::wstring str = L""; a2.Perform(make_tuple(&str)); EXPECT_EQ(L"world", str); # endif } #endif // Tests that SetArgPointee<N>() accepts a char pointer. TEST(SetArgPointeeTest, AcceptsCharPointer) { typedef void MyFunction(bool, std::string*, const char**); const char* const hi = "hi"; Action<MyFunction> a = SetArgPointee<1>(hi); std::string str; const char* ptr = NULL; a.Perform(make_tuple(true, &str, &ptr)); EXPECT_EQ("hi", str); EXPECT_TRUE(ptr == NULL); char world_array[] = "world"; char* const world = world_array; a = SetArgPointee<2>(world); str = ""; a.Perform(make_tuple(true, &str, &ptr)); EXPECT_EQ("", str); EXPECT_EQ(world, ptr); } TEST(SetArgPointeeTest, AcceptsWideCharPointer) { typedef void MyFunction(bool, const wchar_t**); const wchar_t* const hi = L"hi"; Action<MyFunction> a = SetArgPointee<1>(hi); const wchar_t* ptr = NULL; a.Perform(make_tuple(true, &ptr)); EXPECT_EQ(hi, ptr); # if GTEST_HAS_STD_WSTRING typedef void MyStringFunction(bool, std::wstring*); wchar_t world_array[] = L"world"; wchar_t* const world = world_array; Action<MyStringFunction> a2 = SetArgPointee<1>(world); std::wstring str; a2.Perform(make_tuple(true, &str)); EXPECT_EQ(world_array, str); # endif } #if GTEST_HAS_PROTOBUF_ // Tests that SetArgPointee<N>(proto_buffer) sets the v1 protobuf // variable pointed to by the N-th (0-based) argument to proto_buffer. TEST(SetArgPointeeTest, SetsTheNthPointeeOfProtoBufferType) { TestMessage* const msg = new TestMessage; msg->set_member("yes"); TestMessage orig_msg; orig_msg.CopyFrom(*msg); Action<void(bool, TestMessage*)> a = SetArgPointee<1>(*msg); // SetArgPointee<N>(proto_buffer) makes a copy of proto_buffer // s.t. the action works even when the original proto_buffer has // died. We ensure this behavior by deleting msg before using the // action. delete msg; TestMessage dest; EXPECT_FALSE(orig_msg.Equals(dest)); a.Perform(make_tuple(true, &dest)); EXPECT_TRUE(orig_msg.Equals(dest)); } // Tests that SetArgPointee<N>(proto_buffer) sets the // ::ProtocolMessage variable pointed to by the N-th (0-based) // argument to proto_buffer. TEST(SetArgPointeeTest, SetsTheNthPointeeOfProtoBufferBaseType) { TestMessage* const msg = new TestMessage; msg->set_member("yes"); TestMessage orig_msg; orig_msg.CopyFrom(*msg); Action<void(bool, ::ProtocolMessage*)> a = SetArgPointee<1>(*msg); // SetArgPointee<N>(proto_buffer) makes a copy of proto_buffer // s.t. the action works even when the original proto_buffer has // died. We ensure this behavior by deleting msg before using the // action. delete msg; TestMessage dest; ::ProtocolMessage* const dest_base = &dest; EXPECT_FALSE(orig_msg.Equals(dest)); a.Perform(make_tuple(true, dest_base)); EXPECT_TRUE(orig_msg.Equals(dest)); } // Tests that SetArgPointee<N>(proto2_buffer) sets the v2 // protobuf variable pointed to by the N-th (0-based) argument to // proto2_buffer. TEST(SetArgPointeeTest, SetsTheNthPointeeOfProto2BufferType) { using testing::internal::FooMessage; FooMessage* const msg = new FooMessage; msg->set_int_field(2); msg->set_string_field("hi"); FooMessage orig_msg; orig_msg.CopyFrom(*msg); Action<void(bool, FooMessage*)> a = SetArgPointee<1>(*msg); // SetArgPointee<N>(proto2_buffer) makes a copy of // proto2_buffer s.t. the action works even when the original // proto2_buffer has died. We ensure this behavior by deleting msg // before using the action. delete msg; FooMessage dest; dest.set_int_field(0); a.Perform(make_tuple(true, &dest)); EXPECT_EQ(2, dest.int_field()); EXPECT_EQ("hi", dest.string_field()); } // Tests that SetArgPointee<N>(proto2_buffer) sets the // proto2::Message variable pointed to by the N-th (0-based) argument // to proto2_buffer. TEST(SetArgPointeeTest, SetsTheNthPointeeOfProto2BufferBaseType) { using testing::internal::FooMessage; FooMessage* const msg = new FooMessage; msg->set_int_field(2); msg->set_string_field("hi"); FooMessage orig_msg; orig_msg.CopyFrom(*msg); Action<void(bool, ::proto2::Message*)> a = SetArgPointee<1>(*msg); // SetArgPointee<N>(proto2_buffer) makes a copy of // proto2_buffer s.t. the action works even when the original // proto2_buffer has died. We ensure this behavior by deleting msg // before using the action. delete msg; FooMessage dest; dest.set_int_field(0); ::proto2::Message* const dest_base = &dest; a.Perform(make_tuple(true, dest_base)); EXPECT_EQ(2, dest.int_field()); EXPECT_EQ("hi", dest.string_field()); } #endif // GTEST_HAS_PROTOBUF_ // Tests that SetArgumentPointee<N>(v) sets the variable pointed to by // the N-th (0-based) argument to v. TEST(SetArgumentPointeeTest, SetsTheNthPointee) { typedef void MyFunction(bool, int*, char*); Action<MyFunction> a = SetArgumentPointee<1>(2); int n = 0; char ch = '\0'; a.Perform(make_tuple(true, &n, &ch)); EXPECT_EQ(2, n); EXPECT_EQ('\0', ch); a = SetArgumentPointee<2>('a'); n = 0; ch = '\0'; a.Perform(make_tuple(true, &n, &ch)); EXPECT_EQ(0, n); EXPECT_EQ('a', ch); } #if GTEST_HAS_PROTOBUF_ // Tests that SetArgumentPointee<N>(proto_buffer) sets the v1 protobuf // variable pointed to by the N-th (0-based) argument to proto_buffer. TEST(SetArgumentPointeeTest, SetsTheNthPointeeOfProtoBufferType) { TestMessage* const msg = new TestMessage; msg->set_member("yes"); TestMessage orig_msg; orig_msg.CopyFrom(*msg); Action<void(bool, TestMessage*)> a = SetArgumentPointee<1>(*msg); // SetArgumentPointee<N>(proto_buffer) makes a copy of proto_buffer // s.t. the action works even when the original proto_buffer has // died. We ensure this behavior by deleting msg before using the // action. delete msg; TestMessage dest; EXPECT_FALSE(orig_msg.Equals(dest)); a.Perform(make_tuple(true, &dest)); EXPECT_TRUE(orig_msg.Equals(dest)); } // Tests that SetArgumentPointee<N>(proto_buffer) sets the // ::ProtocolMessage variable pointed to by the N-th (0-based) // argument to proto_buffer. TEST(SetArgumentPointeeTest, SetsTheNthPointeeOfProtoBufferBaseType) { TestMessage* const msg = new TestMessage; msg->set_member("yes"); TestMessage orig_msg; orig_msg.CopyFrom(*msg); Action<void(bool, ::ProtocolMessage*)> a = SetArgumentPointee<1>(*msg); // SetArgumentPointee<N>(proto_buffer) makes a copy of proto_buffer // s.t. the action works even when the original proto_buffer has // died. We ensure this behavior by deleting msg before using the // action. delete msg; TestMessage dest; ::ProtocolMessage* const dest_base = &dest; EXPECT_FALSE(orig_msg.Equals(dest)); a.Perform(make_tuple(true, dest_base)); EXPECT_TRUE(orig_msg.Equals(dest)); } // Tests that SetArgumentPointee<N>(proto2_buffer) sets the v2 // protobuf variable pointed to by the N-th (0-based) argument to // proto2_buffer. TEST(SetArgumentPointeeTest, SetsTheNthPointeeOfProto2BufferType) { using testing::internal::FooMessage; FooMessage* const msg = new FooMessage; msg->set_int_field(2); msg->set_string_field("hi"); FooMessage orig_msg; orig_msg.CopyFrom(*msg); Action<void(bool, FooMessage*)> a = SetArgumentPointee<1>(*msg); // SetArgumentPointee<N>(proto2_buffer) makes a copy of // proto2_buffer s.t. the action works even when the original // proto2_buffer has died. We ensure this behavior by deleting msg // before using the action. delete msg; FooMessage dest; dest.set_int_field(0); a.Perform(make_tuple(true, &dest)); EXPECT_EQ(2, dest.int_field()); EXPECT_EQ("hi", dest.string_field()); } // Tests that SetArgumentPointee<N>(proto2_buffer) sets the // proto2::Message variable pointed to by the N-th (0-based) argument // to proto2_buffer. TEST(SetArgumentPointeeTest, SetsTheNthPointeeOfProto2BufferBaseType) { using testing::internal::FooMessage; FooMessage* const msg = new FooMessage; msg->set_int_field(2); msg->set_string_field("hi"); FooMessage orig_msg; orig_msg.CopyFrom(*msg); Action<void(bool, ::proto2::Message*)> a = SetArgumentPointee<1>(*msg); // SetArgumentPointee<N>(proto2_buffer) makes a copy of // proto2_buffer s.t. the action works even when the original // proto2_buffer has died. We ensure this behavior by deleting msg // before using the action. delete msg; FooMessage dest; dest.set_int_field(0); ::proto2::Message* const dest_base = &dest; a.Perform(make_tuple(true, dest_base)); EXPECT_EQ(2, dest.int_field()); EXPECT_EQ("hi", dest.string_field()); } #endif // GTEST_HAS_PROTOBUF_ // Sample functions and functors for testing Invoke() and etc. int Nullary() { return 1; } class NullaryFunctor { public: int operator()() { return 2; } }; bool g_done = false; void VoidNullary() { g_done = true; } class VoidNullaryFunctor { public: void operator()() { g_done = true; } }; class Foo { public: Foo() : value_(123) {} int Nullary() const { return value_; } private: int value_; }; // Tests InvokeWithoutArgs(function). TEST(InvokeWithoutArgsTest, Function) { // As an action that takes one argument. Action<int(int)> a = InvokeWithoutArgs(Nullary); // NOLINT EXPECT_EQ(1, a.Perform(make_tuple(2))); // As an action that takes two arguments. Action<int(int, double)> a2 = InvokeWithoutArgs(Nullary); // NOLINT EXPECT_EQ(1, a2.Perform(make_tuple(2, 3.5))); // As an action that returns void. Action<void(int)> a3 = InvokeWithoutArgs(VoidNullary); // NOLINT g_done = false; a3.Perform(make_tuple(1)); EXPECT_TRUE(g_done); } // Tests InvokeWithoutArgs(functor). TEST(InvokeWithoutArgsTest, Functor) { // As an action that takes no argument. Action<int()> a = InvokeWithoutArgs(NullaryFunctor()); // NOLINT EXPECT_EQ(2, a.Perform(make_tuple())); // As an action that takes three arguments. Action<int(int, double, char)> a2 = // NOLINT InvokeWithoutArgs(NullaryFunctor()); EXPECT_EQ(2, a2.Perform(make_tuple(3, 3.5, 'a'))); // As an action that returns void. Action<void()> a3 = InvokeWithoutArgs(VoidNullaryFunctor()); g_done = false; a3.Perform(make_tuple()); EXPECT_TRUE(g_done); } // Tests InvokeWithoutArgs(obj_ptr, method). TEST(InvokeWithoutArgsTest, Method) { Foo foo; Action<int(bool, char)> a = // NOLINT InvokeWithoutArgs(&foo, &Foo::Nullary); EXPECT_EQ(123, a.Perform(make_tuple(true, 'a'))); } // Tests using IgnoreResult() on a polymorphic action. TEST(IgnoreResultTest, PolymorphicAction) { Action<void(int)> a = IgnoreResult(Return(5)); // NOLINT a.Perform(make_tuple(1)); } // Tests using IgnoreResult() on a monomorphic action. int ReturnOne() { g_done = true; return 1; } TEST(IgnoreResultTest, MonomorphicAction) { g_done = false; Action<void()> a = IgnoreResult(Invoke(ReturnOne)); a.Perform(make_tuple()); EXPECT_TRUE(g_done); } // Tests using IgnoreResult() on an action that returns a class type. MyNonDefaultConstructible ReturnMyNonDefaultConstructible(double /* x */) { g_done = true; return MyNonDefaultConstructible(42); } TEST(IgnoreResultTest, ActionReturningClass) { g_done = false; Action<void(int)> a = IgnoreResult(Invoke(ReturnMyNonDefaultConstructible)); // NOLINT a.Perform(make_tuple(2)); EXPECT_TRUE(g_done); } TEST(AssignTest, Int) { int x = 0; Action<void(int)> a = Assign(&x, 5); a.Perform(make_tuple(0)); EXPECT_EQ(5, x); } TEST(AssignTest, String) { ::std::string x; Action<void(void)> a = Assign(&x, "Hello, world"); a.Perform(make_tuple()); EXPECT_EQ("Hello, world", x); } TEST(AssignTest, CompatibleTypes) { double x = 0; Action<void(int)> a = Assign(&x, 5); a.Perform(make_tuple(0)); EXPECT_DOUBLE_EQ(5, x); } #if !GTEST_OS_WINDOWS_MOBILE class SetErrnoAndReturnTest : public testing::Test { protected: virtual void SetUp() { errno = 0; } virtual void TearDown() { errno = 0; } }; TEST_F(SetErrnoAndReturnTest, Int) { Action<int(void)> a = SetErrnoAndReturn(ENOTTY, -5); EXPECT_EQ(-5, a.Perform(make_tuple())); EXPECT_EQ(ENOTTY, errno); } TEST_F(SetErrnoAndReturnTest, Ptr) { int x; Action<int*(void)> a = SetErrnoAndReturn(ENOTTY, &x); EXPECT_EQ(&x, a.Perform(make_tuple())); EXPECT_EQ(ENOTTY, errno); } TEST_F(SetErrnoAndReturnTest, CompatibleTypes) { Action<double()> a = SetErrnoAndReturn(EINVAL, 5); EXPECT_DOUBLE_EQ(5.0, a.Perform(make_tuple())); EXPECT_EQ(EINVAL, errno); } #endif // !GTEST_OS_WINDOWS_MOBILE // Tests ByRef(). // Tests that ReferenceWrapper<T> is copyable. TEST(ByRefTest, IsCopyable) { const std::string s1 = "Hi"; const std::string s2 = "Hello"; ::testing::internal::ReferenceWrapper<const std::string> ref_wrapper = ByRef(s1); const std::string& r1 = ref_wrapper; EXPECT_EQ(&s1, &r1); // Assigns a new value to ref_wrapper. ref_wrapper = ByRef(s2); const std::string& r2 = ref_wrapper; EXPECT_EQ(&s2, &r2); ::testing::internal::ReferenceWrapper<const std::string> ref_wrapper1 = ByRef(s1); // Copies ref_wrapper1 to ref_wrapper. ref_wrapper = ref_wrapper1; const std::string& r3 = ref_wrapper; EXPECT_EQ(&s1, &r3); } // Tests using ByRef() on a const value. TEST(ByRefTest, ConstValue) { const int n = 0; // int& ref = ByRef(n); // This shouldn't compile - we have a // negative compilation test to catch it. const int& const_ref = ByRef(n); EXPECT_EQ(&n, &const_ref); } // Tests using ByRef() on a non-const value. TEST(ByRefTest, NonConstValue) { int n = 0; // ByRef(n) can be used as either an int&, int& ref = ByRef(n); EXPECT_EQ(&n, &ref); // or a const int&. const int& const_ref = ByRef(n); EXPECT_EQ(&n, &const_ref); } // Tests explicitly specifying the type when using ByRef(). TEST(ByRefTest, ExplicitType) { int n = 0; const int& r1 = ByRef<const int>(n); EXPECT_EQ(&n, &r1); // ByRef<char>(n); // This shouldn't compile - we have a negative // compilation test to catch it. Derived d; Derived& r2 = ByRef<Derived>(d); EXPECT_EQ(&d, &r2); const Derived& r3 = ByRef<const Derived>(d); EXPECT_EQ(&d, &r3); Base& r4 = ByRef<Base>(d); EXPECT_EQ(&d, &r4); const Base& r5 = ByRef<const Base>(d); EXPECT_EQ(&d, &r5); // The following shouldn't compile - we have a negative compilation // test for it. // // Base b; // ByRef<Derived>(b); } // Tests that Google Mock prints expression ByRef(x) as a reference to x. TEST(ByRefTest, PrintsCorrectly) { int n = 42; ::std::stringstream expected, actual; testing::internal::UniversalPrinter<const int&>::Print(n, &expected); testing::internal::UniversalPrint(ByRef(n), &actual); EXPECT_EQ(expected.str(), actual.str()); } #if GTEST_HAS_STD_UNIQUE_PTR_ std::unique_ptr<int> UniquePtrSource() { return std::unique_ptr<int>(new int(19)); } std::vector<std::unique_ptr<int>> VectorUniquePtrSource() { std::vector<std::unique_ptr<int>> out; out.emplace_back(new int(7)); return out; } TEST(MockMethodTest, CanReturnMoveOnlyValue_Return) { MockClass mock; std::unique_ptr<int> i(new int(19)); EXPECT_CALL(mock, MakeUnique()).WillOnce(Return(ByMove(std::move(i)))); EXPECT_CALL(mock, MakeVectorUnique()) .WillOnce(Return(ByMove(VectorUniquePtrSource()))); Derived* d = new Derived; EXPECT_CALL(mock, MakeUniqueBase()) .WillOnce(Return(ByMove(std::unique_ptr<Derived>(d)))); std::unique_ptr<int> result1 = mock.MakeUnique(); EXPECT_EQ(19, *result1); std::vector<std::unique_ptr<int>> vresult = mock.MakeVectorUnique(); EXPECT_EQ(1u, vresult.size()); EXPECT_NE(nullptr, vresult[0]); EXPECT_EQ(7, *vresult[0]); std::unique_ptr<Base> result2 = mock.MakeUniqueBase(); EXPECT_EQ(d, result2.get()); } TEST(MockMethodTest, CanReturnMoveOnlyValue_DoAllReturn) { testing::MockFunction<void()> mock_function; MockClass mock; std::unique_ptr<int> i(new int(19)); EXPECT_CALL(mock_function, Call()); EXPECT_CALL(mock, MakeUnique()).WillOnce(DoAll( InvokeWithoutArgs(&mock_function, &testing::MockFunction<void()>::Call), Return(ByMove(std::move(i))))); std::unique_ptr<int> result1 = mock.MakeUnique(); EXPECT_EQ(19, *result1); } TEST(MockMethodTest, CanReturnMoveOnlyValue_Invoke) { MockClass mock; // Check default value DefaultValue<std::unique_ptr<int>>::SetFactory([] { return std::unique_ptr<int>(new int(42)); }); EXPECT_EQ(42, *mock.MakeUnique()); EXPECT_CALL(mock, MakeUnique()).WillRepeatedly(Invoke(UniquePtrSource)); EXPECT_CALL(mock, MakeVectorUnique()) .WillRepeatedly(Invoke(VectorUniquePtrSource)); std::unique_ptr<int> result1 = mock.MakeUnique(); EXPECT_EQ(19, *result1); std::unique_ptr<int> result2 = mock.MakeUnique(); EXPECT_EQ(19, *result2); EXPECT_NE(result1, result2); std::vector<std::unique_ptr<int>> vresult = mock.MakeVectorUnique(); EXPECT_EQ(1u, vresult.size()); EXPECT_NE(nullptr, vresult[0]); EXPECT_EQ(7, *vresult[0]); } #endif // GTEST_HAS_STD_UNIQUE_PTR_ } // Unnamed namespace
program find_test; vars i, max, qty : int; vars array[100] : int; void function readArray(length : int); vars i : int; { for(i = 0; i < length; i = i + 1) { read(array[i]); } } void function printArray(length : int); vars i : int; { for(i = 0; i < length; i = i + 1) { write(array[i]); } } void function swap(x : int, y : int); vars tmp1, tmp2 : int; { tmp1 = array[x]; tmp2 = array[y]; array[y] = tmp1; array[x] = tmp2; } void function bubbleSort(size : int); vars i, j, a, b, c, tmp : int; { for(i = -1; i < size - 1; i = i + 1){ for(j = -1; j < size - i - 1; j = j + 1){ c = j + 1; a = array[j]; b = array[c]; if(a > b){ swap(j, c); } } } } main(){ max = 100; write("¿Cuántos números quieres?: "); read(qty); if(qty > max) { write("Error: El número máximo de números es:"); write(max); } else { readArray(qty); bubbleSort(qty); write("Resultado: "); printArray(qty); } }
//===--- GenDecl.cpp - IR Generation for Declarations ---------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // This file implements IR generation for local and global // declarations in Swift. // //===----------------------------------------------------------------------===// #include "swift/AST/ASTContext.h" #include "swift/AST/Decl.h" #include "swift/AST/DiagnosticEngine.h" #include "swift/AST/GenericEnvironment.h" #include "swift/AST/GenericSignature.h" #include "swift/AST/IRGenOptions.h" #include "swift/AST/Module.h" #include "swift/AST/NameLookup.h" #include "swift/AST/Pattern.h" #include "swift/AST/ProtocolConformance.h" #include "swift/AST/TypeMemberVisitor.h" #include "swift/AST/Types.h" #include "swift/ClangImporter/ClangModule.h" #include "swift/Demangling/ManglingMacros.h" #include "swift/IRGen/Linking.h" #include "swift/Runtime/HeapObject.h" #include "swift/SIL/FormalLinkage.h" #include "swift/SIL/SILDebugScope.h" #include "swift/SIL/SILModule.h" #include "swift/Subsystems.h" #include "clang/AST/ASTContext.h" #include "clang/AST/DeclCXX.h" #include "clang/AST/GlobalDecl.h" #include "clang/CodeGen/CodeGenABITypes.h" #include "clang/CodeGen/ModuleBuilder.h" #include "llvm/ADT/SmallString.h" #include "llvm/IR/DerivedTypes.h" #include "llvm/IR/GlobalAlias.h" #include "llvm/IR/InlineAsm.h" #include "llvm/IR/Module.h" #include "llvm/IR/Value.h" #include "llvm/Support/Compiler.h" #include "llvm/Support/ConvertUTF.h" #include "llvm/Support/Path.h" #include "llvm/Support/SaveAndRestore.h" #include "llvm/Target/TargetMachine.h" #include "llvm/Transforms/Utils/ModuleUtils.h" #include "Callee.h" #include "ConformanceDescription.h" #include "ConstantBuilder.h" #include "Explosion.h" #include "FixedTypeInfo.h" #include "GenCall.h" #include "GenClass.h" #include "GenDecl.h" #include "GenMeta.h" #include "GenObjC.h" #include "GenOpaque.h" #include "GenPointerAuth.h" #include "GenProto.h" #include "GenType.h" #include "IRGenDebugInfo.h" #include "IRGenFunction.h" #include "IRGenMangler.h" #include "IRGenModule.h" #include "LoadableTypeInfo.h" #include "MetadataRequest.h" #include "ProtocolInfo.h" #include "Signature.h" #include "StructLayout.h" using namespace swift; using namespace irgen; llvm::cl::opt<bool> UseBasicDynamicReplacement( "basic-dynamic-replacement", llvm::cl::init(false), llvm::cl::desc("Basic implementation of dynamic replacement")); namespace { /// Add methods, properties, and protocol conformances from a JITed extension /// to an ObjC class using the ObjC runtime. /// /// This must happen after ObjCProtocolInitializerVisitor if any @objc protocols /// were defined in the TU. class CategoryInitializerVisitor : public ClassMemberVisitor<CategoryInitializerVisitor> { IRGenFunction &IGF; IRGenModule &IGM = IGF.IGM; IRBuilder &Builder = IGF.Builder; llvm::Constant *class_replaceMethod; llvm::Constant *class_addProtocol; llvm::Value *classMetadata; llvm::Constant *metaclassMetadata; public: CategoryInitializerVisitor(IRGenFunction &IGF, ExtensionDecl *ext) : IGF(IGF) { class_replaceMethod = IGM.getClassReplaceMethodFn(); class_addProtocol = IGM.getClassAddProtocolFn(); CanType origTy = ext->getSelfNominalTypeDecl() ->getDeclaredType()->getCanonicalType(); classMetadata = emitClassHeapMetadataRef(IGF, origTy, MetadataValueType::ObjCClass, MetadataState::Complete, /*allow uninitialized*/ false); classMetadata = Builder.CreateBitCast(classMetadata, IGM.ObjCClassPtrTy); metaclassMetadata = IGM.getAddrOfMetaclassObject( dyn_cast_or_null<ClassDecl>(origTy->getAnyNominal()), NotForDefinition); metaclassMetadata = llvm::ConstantExpr::getBitCast(metaclassMetadata, IGM.ObjCClassPtrTy); // Register ObjC protocol conformances. for (auto *p : ext->getLocalProtocols()) { if (!p->isObjC()) continue; llvm::Value *protoRef = IGM.getAddrOfObjCProtocolRef(p, NotForDefinition); auto proto = Builder.CreateLoad(protoRef, IGM.getPointerAlignment()); Builder.CreateCall(class_addProtocol, {classMetadata, proto}); } } void visitMembers(ExtensionDecl *ext) { for (Decl *member : ext->getMembers()) visit(member); } void visitTypeDecl(TypeDecl *type) { // We'll visit nested types separately if necessary. } void visitMissingMemberDecl(MissingMemberDecl *placeholder) {} void visitFuncDecl(FuncDecl *method) { if (!requiresObjCMethodDescriptor(method)) return; // Don't emit getters/setters for @NSManaged methods. if (method->getAttrs().hasAttribute<NSManagedAttr>()) return; auto descriptor = emitObjCMethodDescriptorParts(IGM, method, /*concrete*/true); // When generating JIT'd code, we need to call sel_registerName() to force // the runtime to unique the selector. llvm::Value *sel = Builder.CreateCall(IGM.getObjCSelRegisterNameFn(), descriptor.selectorRef); llvm::Value *args[] = { method->isStatic() ? metaclassMetadata : classMetadata, sel, descriptor.impl, descriptor.typeEncoding }; Builder.CreateCall(class_replaceMethod, args); } // Can't be added in an extension. void visitDestructorDecl(DestructorDecl *dtor) {} void visitConstructorDecl(ConstructorDecl *constructor) { if (!requiresObjCMethodDescriptor(constructor)) return; auto descriptor = emitObjCMethodDescriptorParts(IGM, constructor, /*concrete*/true); // When generating JIT'd code, we need to call sel_registerName() to force // the runtime to unique the selector. llvm::Value *sel = Builder.CreateCall(IGM.getObjCSelRegisterNameFn(), descriptor.selectorRef); llvm::Value *args[] = { classMetadata, sel, descriptor.impl, descriptor.typeEncoding }; Builder.CreateCall(class_replaceMethod, args); } void visitPatternBindingDecl(PatternBindingDecl *binding) { // Ignore the PBD and just handle the individual vars. } void visitVarDecl(VarDecl *prop) { if (!requiresObjCPropertyDescriptor(IGM, prop)) return; // FIXME: register property metadata in addition to the methods. // ObjC doesn't have a notion of class properties, so we'd only do this // for instance properties. // Don't emit getters/setters for @NSManaged properties. if (prop->getAttrs().hasAttribute<NSManagedAttr>()) return; auto descriptor = emitObjCGetterDescriptorParts(IGM, prop); // When generating JIT'd code, we need to call sel_registerName() to force // the runtime to unique the selector. llvm::Value *sel = Builder.CreateCall(IGM.getObjCSelRegisterNameFn(), descriptor.selectorRef); auto theClass = prop->isStatic() ? metaclassMetadata : classMetadata; llvm::Value *getterArgs[] = {theClass, sel, descriptor.impl, descriptor.typeEncoding}; Builder.CreateCall(class_replaceMethod, getterArgs); if (prop->isSettable(prop->getDeclContext())) { auto descriptor = emitObjCSetterDescriptorParts(IGM, prop); sel = Builder.CreateCall(IGM.getObjCSelRegisterNameFn(), descriptor.selectorRef); llvm::Value *setterArgs[] = {theClass, sel, descriptor.impl, descriptor.typeEncoding}; Builder.CreateCall(class_replaceMethod, setterArgs); } } void visitSubscriptDecl(SubscriptDecl *subscript) { assert(!subscript->isStatic() && "objc doesn't support class subscripts"); if (!requiresObjCSubscriptDescriptor(IGM, subscript)) return; auto descriptor = emitObjCGetterDescriptorParts(IGM, subscript); // When generating JIT'd code, we need to call sel_registerName() to force // the runtime to unique the selector. llvm::Value *sel = Builder.CreateCall(IGM.getObjCSelRegisterNameFn(), descriptor.selectorRef); llvm::Value *getterArgs[] = {classMetadata, sel, descriptor.impl, descriptor.typeEncoding}; Builder.CreateCall(class_replaceMethod, getterArgs); if (subscript->supportsMutation()) { auto descriptor = emitObjCSetterDescriptorParts(IGM, subscript); sel = Builder.CreateCall(IGM.getObjCSelRegisterNameFn(), descriptor.selectorRef); llvm::Value *setterArgs[] = {classMetadata, sel, descriptor.impl, descriptor.typeEncoding}; Builder.CreateCall(class_replaceMethod, setterArgs); } } }; /// Create a descriptor for JITed @objc protocol using the ObjC runtime. class ObjCProtocolInitializerVisitor : public ClassMemberVisitor<ObjCProtocolInitializerVisitor> { IRGenFunction &IGF; IRGenModule &IGM = IGF.IGM; IRBuilder &Builder = IGF.Builder; llvm::Constant *objc_getProtocol, *objc_allocateProtocol, *objc_registerProtocol, *protocol_addMethodDescription, *protocol_addProtocol; llvm::Value *NewProto = nullptr; public: ObjCProtocolInitializerVisitor(IRGenFunction &IGF) : IGF(IGF) { objc_getProtocol = IGM.getGetObjCProtocolFn(); objc_allocateProtocol = IGM.getAllocateObjCProtocolFn(); objc_registerProtocol = IGM.getRegisterObjCProtocolFn(); protocol_addMethodDescription = IGM.getProtocolAddMethodDescriptionFn(); protocol_addProtocol = IGM.getProtocolAddProtocolFn(); } void visitMembers(ProtocolDecl *proto) { // Check if the ObjC runtime already has a descriptor for this // protocol. If so, use it. SmallString<32> buf; auto protocolName = IGM.getAddrOfGlobalString(proto->getObjCRuntimeName(buf)); auto existing = Builder.CreateCall(objc_getProtocol, protocolName); auto isNull = Builder.CreateICmpEQ(existing, llvm::ConstantPointerNull::get(IGM.ProtocolDescriptorPtrTy)); auto existingBB = IGF.createBasicBlock("existing_protocol"); auto newBB = IGF.createBasicBlock("new_protocol"); auto contBB = IGF.createBasicBlock("cont"); Builder.CreateCondBr(isNull, newBB, existingBB); // Nothing to do if there's already a descriptor. Builder.emitBlock(existingBB); Builder.CreateBr(contBB); Builder.emitBlock(newBB); // Allocate the protocol descriptor. NewProto = Builder.CreateCall(objc_allocateProtocol, protocolName); // Add the parent protocols. for (auto parentProto : proto->getInheritedProtocols()) { if (!parentProto->isObjC()) continue; llvm::Value *parentRef = IGM.getAddrOfObjCProtocolRef(parentProto, NotForDefinition); parentRef = IGF.Builder.CreateBitCast(parentRef, IGM.ProtocolDescriptorPtrTy ->getPointerTo()); auto parent = Builder.CreateLoad(parentRef, IGM.getPointerAlignment()); Builder.CreateCall(protocol_addProtocol, {NewProto, parent}); } // Add the members. for (Decl *member : proto->getMembers()) visit(member); // Register it. Builder.CreateCall(objc_registerProtocol, NewProto); Builder.CreateBr(contBB); // Store the reference to the runtime's idea of the protocol descriptor. Builder.emitBlock(contBB); auto result = Builder.CreatePHI(IGM.ProtocolDescriptorPtrTy, 2); result->addIncoming(existing, existingBB); result->addIncoming(NewProto, newBB); llvm::Value *ref = IGM.getAddrOfObjCProtocolRef(proto, NotForDefinition); ref = IGF.Builder.CreateBitCast(ref, IGM.ProtocolDescriptorPtrTy->getPointerTo()); Builder.CreateStore(result, ref, IGM.getPointerAlignment()); } void visitTypeDecl(TypeDecl *type) { // We'll visit nested types separately if necessary. } void visitMissingMemberDecl(MissingMemberDecl *placeholder) {} void visitAbstractFunctionDecl(AbstractFunctionDecl *method) { if (isa<AccessorDecl>(method)) { // Accessors are handled as part of their AbstractStorageDecls. return; } auto descriptor = emitObjCMethodDescriptorParts(IGM, method, /*concrete*/false); // When generating JIT'd code, we need to call sel_registerName() to force // the runtime to unique the selector. llvm::Value *sel = Builder.CreateCall(IGM.getObjCSelRegisterNameFn(), descriptor.selectorRef); llvm::Value *args[] = { NewProto, sel, descriptor.typeEncoding, // required? llvm::ConstantInt::get(IGM.ObjCBoolTy, !method->getAttrs().hasAttribute<OptionalAttr>()), // instance? llvm::ConstantInt::get(IGM.ObjCBoolTy, isa<ConstructorDecl>(method) || method->isInstanceMember()), }; Builder.CreateCall(protocol_addMethodDescription, args); } void visitPatternBindingDecl(PatternBindingDecl *binding) { // Ignore the PBD and just handle the individual vars. } void visitAbstractStorageDecl(AbstractStorageDecl *prop) { // TODO: Add properties to protocol. auto descriptor = emitObjCGetterDescriptorParts(IGM, prop); // When generating JIT'd code, we need to call sel_registerName() to force // the runtime to unique the selector. llvm::Value *sel = Builder.CreateCall(IGM.getObjCSelRegisterNameFn(), descriptor.selectorRef); llvm::Value *getterArgs[] = { NewProto, sel, descriptor.typeEncoding, // required? llvm::ConstantInt::get(IGM.ObjCBoolTy, !prop->getAttrs().hasAttribute<OptionalAttr>()), // instance? llvm::ConstantInt::get(IGM.ObjCBoolTy, prop->isInstanceMember()), }; Builder.CreateCall(protocol_addMethodDescription, getterArgs); if (prop->isSettable(nullptr)) { auto descriptor = emitObjCSetterDescriptorParts(IGM, prop); sel = Builder.CreateCall(IGM.getObjCSelRegisterNameFn(), descriptor.selectorRef); llvm::Value *setterArgs[] = { NewProto, sel, descriptor.typeEncoding, // required? llvm::ConstantInt::get(IGM.ObjCBoolTy, !prop->getAttrs().hasAttribute<OptionalAttr>()), // instance? llvm::ConstantInt::get(IGM.ObjCBoolTy, prop->isInstanceMember()), }; Builder.CreateCall(protocol_addMethodDescription, setterArgs); } } }; } // end anonymous namespace namespace { class PrettySourceFileEmission : public llvm::PrettyStackTraceEntry { const SourceFile &SF; public: explicit PrettySourceFileEmission(const SourceFile &SF) : SF(SF) {} void print(raw_ostream &os) const override { os << "While emitting IR for source file " << SF.getFilename() << '\n'; } }; class PrettySynthesizedFileUnitEmission : public llvm::PrettyStackTraceEntry { const SynthesizedFileUnit &SFU; public: explicit PrettySynthesizedFileUnitEmission(const SynthesizedFileUnit &SFU) : SFU(SFU) {} void print(raw_ostream &os) const override { os << "While emitting IR for synthesized file" << &SFU << "\n"; } }; } // end anonymous namespace /// Emit all the top-level code in the source file. void IRGenModule::emitSourceFile(SourceFile &SF) { // Type-check the file if we haven't already (this may be necessary for .sil // files, which don't get fully type-checked by parsing). performTypeChecking(SF); PrettySourceFileEmission StackEntry(SF); // Emit types and other global decls. for (auto *decl : SF.getTopLevelDecls()) emitGlobalDecl(decl); for (auto *decl : SF.getHoistedDecls()) emitGlobalDecl(decl); for (auto *localDecl : SF.LocalTypeDecls) emitGlobalDecl(localDecl); for (auto *opaqueDecl : SF.getOpaqueReturnTypeDecls()) maybeEmitOpaqueTypeDecl(opaqueDecl); SF.collectLinkLibraries([this](LinkLibrary linkLib) { this->addLinkLibrary(linkLib); }); if (ObjCInterop) this->addLinkLibrary(LinkLibrary("objc", LibraryKind::Library)); // FIXME: It'd be better to have the driver invocation or build system that // executes the linker introduce these compatibility libraries, since at // that point we know whether we're building an executable, which is the only // place where the compatibility libraries take effect. For the benefit of // build systems that build Swift code, but don't use Swift to drive // the linker, we can also use autolinking to pull in the compatibility // libraries. This may however cause the library to get pulled in in // situations where it isn't useful, such as for dylibs, though this is // harmless aside from code size. if (!IRGen.Opts.UseJIT) { auto addBackDeployLib = [&](llvm::VersionTuple version, StringRef libraryName) { Optional<llvm::VersionTuple> compatibilityVersion; if (libraryName == "swiftCompatibilityDynamicReplacements") { compatibilityVersion = IRGen.Opts. AutolinkRuntimeCompatibilityDynamicReplacementLibraryVersion; } else if (libraryName == "swiftCompatibilityConcurrency") { compatibilityVersion = IRGen.Opts.AutolinkRuntimeCompatibilityConcurrencyLibraryVersion; } else { compatibilityVersion = IRGen.Opts. AutolinkRuntimeCompatibilityLibraryVersion; } if (!compatibilityVersion) return; if (*compatibilityVersion > version) return; this->addLinkLibrary(LinkLibrary(libraryName, LibraryKind::Library, /*forceLoad*/ true)); }; #define BACK_DEPLOYMENT_LIB(Version, Filter, LibraryName) \ addBackDeployLib(llvm::VersionTuple Version, LibraryName); #include "swift/Frontend/BackDeploymentLibs.def" } } /// Emit all the top-level code in the synthesized file unit. void IRGenModule::emitSynthesizedFileUnit(SynthesizedFileUnit &SFU) { PrettySynthesizedFileUnitEmission StackEntry(SFU); for (auto *decl : SFU.getTopLevelDecls()) emitGlobalDecl(decl); } /// Collect elements of an already-existing global list with the given /// \c name into \c list. /// /// We use this when Clang code generation might populate the list. static void collectGlobalList(IRGenModule &IGM, SmallVectorImpl<llvm::WeakTrackingVH> &list, StringRef name) { if (auto *existing = IGM.Module.getGlobalVariable(name)) { auto *globals = cast<llvm::ConstantArray>(existing->getInitializer()); for (auto &use : globals->operands()) { auto *global = use.get(); list.push_back(global); } existing->eraseFromParent(); } std::for_each(list.begin(), list.end(), [](const llvm::WeakTrackingVH &global) { assert(!isa<llvm::GlobalValue>(global) || !cast<llvm::GlobalValue>(global)->isDeclaration() && "all globals in the 'used' list must be definitions"); }); } /// Emit a global list, i.e. a global constant array holding all of a /// list of values. Generally these lists are for various LLVM /// metadata or runtime purposes. static llvm::GlobalVariable * emitGlobalList(IRGenModule &IGM, ArrayRef<llvm::WeakTrackingVH> handles, StringRef name, StringRef section, llvm::GlobalValue::LinkageTypes linkage, llvm::Type *eltTy, bool isConstant, bool asContiguousArray) { // Do nothing if the list is empty. if (handles.empty()) return nullptr; // For global lists that actually get linked (as opposed to notional // ones like @llvm.used), it's important to set an explicit alignment // so that the linker doesn't accidentally put padding in the list. Alignment alignment = IGM.getPointerAlignment(); if (!asContiguousArray) { // Emit as individual globals, which is required for conditional runtime // records to work. for (auto &handle : handles) { llvm::Constant *elt = cast<llvm::Constant>(&*handle); std::string eltName = name.str() + "_" + elt->getName().str(); if (elt->getType() != eltTy) elt = llvm::ConstantExpr::getBitCast(elt, eltTy); auto var = new llvm::GlobalVariable(IGM.Module, eltTy, isConstant, linkage, elt, eltName); var->setSection(section); var->setAlignment(llvm::MaybeAlign(alignment.getValue())); disableAddressSanitizer(IGM, var); if (llvm::GlobalValue::isLocalLinkage(linkage)) IGM.addUsedGlobal(var); if (IGM.IRGen.Opts.ConditionalRuntimeRecords) { // Allow dead-stripping `var` (the runtime record from the global list) // when `handle` / `elt` (the underlaying entity) is not referenced. IGM.appendLLVMUsedConditionalEntry(var, elt->stripPointerCasts()); } } return nullptr; } // We have an array of value handles, but we need an array of constants. SmallVector<llvm::Constant*, 8> elts; elts.reserve(handles.size()); for (auto &handle : handles) { auto elt = cast<llvm::Constant>(&*handle); if (elt->getType() != eltTy) elt = llvm::ConstantExpr::getBitCast(elt, eltTy); elts.push_back(elt); } auto varTy = llvm::ArrayType::get(eltTy, elts.size()); auto init = llvm::ConstantArray::get(varTy, elts); auto var = new llvm::GlobalVariable(IGM.Module, varTy, isConstant, linkage, init, name); var->setSection(section); // Do not set alignment and don't set disableAddressSanitizer on @llvm.used // and @llvm.compiler.used. Doing so confuses LTO (merging) and they're not // going to end up as real global symbols in the binary anyways. if (name != "llvm.used" && name != "llvm.compiler.used") { var->setAlignment(llvm::MaybeAlign(alignment.getValue())); disableAddressSanitizer(IGM, var); } // Mark the variable as used if doesn't have external linkage. // (Note that we'd specifically like to not put @llvm.used in itself.) if (llvm::GlobalValue::isLocalLinkage(linkage)) IGM.addUsedGlobal(var); return var; } void IRGenModule::emitRuntimeRegistration() { // Duck out early if we have nothing to register. if (SwiftProtocols.empty() && ProtocolConformances.empty() && RuntimeResolvableTypes.empty() && (!ObjCInterop || (ObjCProtocols.empty() && ObjCClasses.empty() && ObjCCategoryDecls.empty()))) return; // Find the entry point. SILFunction *EntryPoint = getSILModule().lookUpFunction( getSILModule().getASTContext().getEntryPointFunctionName()); // If we're debugging (and not in the REPL), we don't have a // main. Find a function marked with the LLDBDebuggerFunction // attribute instead. if (!EntryPoint && Context.LangOpts.DebuggerSupport) { for (SILFunction &SF : getSILModule()) { if (SF.hasLocation()) { if (Decl* D = SF.getLocation().getAsASTNode<Decl>()) { if (auto *FD = dyn_cast<FuncDecl>(D)) { if (FD->getAttrs().hasAttribute<LLDBDebuggerFunctionAttr>()) { EntryPoint = &SF; break; } } } } } } if (!EntryPoint) return; llvm::Function *EntryFunction = Module.getFunction(EntryPoint->getName()); if (!EntryFunction) return; // Create a new function to contain our logic. auto fnTy = llvm::FunctionType::get(VoidTy, /*varArg*/ false); auto RegistrationFunction = llvm::Function::Create(fnTy, llvm::GlobalValue::PrivateLinkage, "runtime_registration", getModule()); RegistrationFunction->setAttributes(constructInitialAttributes()); // Insert a call into the entry function. { llvm::BasicBlock *EntryBB = &EntryFunction->getEntryBlock(); llvm::BasicBlock::iterator IP = EntryBB->getFirstInsertionPt(); IRBuilder Builder(getLLVMContext(), DebugInfo && !Context.LangOpts.DebuggerSupport); Builder.llvm::IRBuilderBase::SetInsertPoint(EntryBB, IP); if (DebugInfo && !Context.LangOpts.DebuggerSupport) DebugInfo->setEntryPointLoc(Builder); Builder.CreateCall(RegistrationFunction, {}); } IRGenFunction RegIGF(*this, RegistrationFunction); if (DebugInfo && !Context.LangOpts.DebuggerSupport) DebugInfo->emitArtificialFunction(RegIGF, RegistrationFunction); // Register ObjC protocols we added. if (ObjCInterop) { if (!ObjCProtocols.empty()) { // We need to initialize ObjC protocols in inheritance order, parents // first. llvm::DenseSet<ProtocolDecl*> protos; for (auto &proto : ObjCProtocols) protos.insert(proto.first); llvm::SmallVector<ProtocolDecl*, 4> protoInitOrder; std::function<void(ProtocolDecl*)> orderProtocol = [&](ProtocolDecl *proto) { // Recursively put parents first. for (auto parent : proto->getInheritedProtocols()) orderProtocol(parent); // Skip if we don't need to reify this protocol. auto found = protos.find(proto); if (found == protos.end()) return; protos.erase(found); protoInitOrder.push_back(proto); }; while (!protos.empty()) { orderProtocol(*protos.begin()); } // Visit the protocols in the order we established. for (auto *proto : protoInitOrder) { ObjCProtocolInitializerVisitor(RegIGF) .visitMembers(proto); } } } // Register Swift protocols if we added any. if (!SwiftProtocols.empty()) { llvm::Constant *protocols = emitSwiftProtocols(/*asContiguousArray*/ true); llvm::Constant *beginIndices[] = { llvm::ConstantInt::get(Int32Ty, 0), llvm::ConstantInt::get(Int32Ty, 0), }; auto begin = llvm::ConstantExpr::getGetElementPtr( protocols->getType()->getPointerElementType(), protocols, beginIndices); llvm::Constant *endIndices[] = { llvm::ConstantInt::get(Int32Ty, 0), llvm::ConstantInt::get(Int32Ty, SwiftProtocols.size()), }; auto end = llvm::ConstantExpr::getGetElementPtr( protocols->getType()->getPointerElementType() , protocols, endIndices); RegIGF.Builder.CreateCall(getRegisterProtocolsFn(), {begin, end}); } // Register Swift protocol conformances if we added any. if (llvm::Constant *conformances = emitProtocolConformances(/*asContiguousArray*/ true)) { llvm::Constant *beginIndices[] = { llvm::ConstantInt::get(Int32Ty, 0), llvm::ConstantInt::get(Int32Ty, 0), }; auto begin = llvm::ConstantExpr::getGetElementPtr( conformances->getType()->getPointerElementType(), conformances, beginIndices); llvm::Constant *endIndices[] = { llvm::ConstantInt::get(Int32Ty, 0), llvm::ConstantInt::get(Int32Ty, ProtocolConformances.size()), }; auto end = llvm::ConstantExpr::getGetElementPtr( conformances->getType()->getPointerElementType(), conformances, endIndices); RegIGF.Builder.CreateCall(getRegisterProtocolConformancesFn(), {begin, end}); } if (!RuntimeResolvableTypes.empty()) { llvm::Constant *records = emitTypeMetadataRecords(/*asContiguousArray*/ true); llvm::Constant *beginIndices[] = { llvm::ConstantInt::get(Int32Ty, 0), llvm::ConstantInt::get(Int32Ty, 0), }; auto begin = llvm::ConstantExpr::getGetElementPtr( records->getType()->getPointerElementType(), records, beginIndices); llvm::Constant *endIndices[] = { llvm::ConstantInt::get(Int32Ty, 0), llvm::ConstantInt::get(Int32Ty, RuntimeResolvableTypes.size()), }; auto end = llvm::ConstantExpr::getGetElementPtr( records->getType()->getPointerElementType(), records, endIndices); RegIGF.Builder.CreateCall(getRegisterTypeMetadataRecordsFn(), {begin, end}); } // Register Objective-C classes and extensions we added. if (ObjCInterop) { for (llvm::WeakTrackingVH &ObjCClass : ObjCClasses) { RegIGF.Builder.CreateCall(getInstantiateObjCClassFn(), {ObjCClass}); } for (ExtensionDecl *ext : ObjCCategoryDecls) { CategoryInitializerVisitor(RegIGF, ext).visitMembers(ext); } } RegIGF.Builder.CreateRetVoid(); } /// Return the address of the context descriptor representing the given /// decl context, used as a parent reference for another decl. /// /// For a nominal type context, this returns the address of the nominal type /// descriptor. /// For an extension context, this returns the address of the extension /// context descriptor. /// For a module or file unit context, this returns the address of the module /// context descriptor. /// For any other kind of context, this returns an anonymous context descriptor /// for the context. ConstantReference IRGenModule::getAddrOfContextDescriptorForParent(DeclContext *parent, DeclContext *ofChild, bool fromAnonymousContext) { switch (parent->getContextKind()) { case DeclContextKind::AbstractClosureExpr: case DeclContextKind::AbstractFunctionDecl: case DeclContextKind::SubscriptDecl: case DeclContextKind::EnumElementDecl: case DeclContextKind::TopLevelCodeDecl: case DeclContextKind::Initializer: case DeclContextKind::SerializedLocal: return {getAddrOfAnonymousContextDescriptor( fromAnonymousContext ? parent : ofChild), ConstantReference::Direct}; case DeclContextKind::GenericTypeDecl: if (auto nomTy = dyn_cast<NominalTypeDecl>(parent)) { return {getAddrOfTypeContextDescriptor(nomTy, DontRequireMetadata), ConstantReference::Direct}; } return {getAddrOfAnonymousContextDescriptor( fromAnonymousContext ? parent : ofChild), ConstantReference::Direct}; case DeclContextKind::ExtensionDecl: { auto ext = cast<ExtensionDecl>(parent); // If the extension is equivalent to its extended context (that is, it's // in the same module as the original non-protocol type and // has no constraints), then we can use the original nominal type context // (assuming there is one). if (ext->isEquivalentToExtendedContext()) { auto nominal = ext->getExtendedNominal(); // If the extended type is an ObjC class, it won't have a nominal type // descriptor, so we'll just emit an extension context. auto clas = dyn_cast<ClassDecl>(nominal); if (!clas || clas->isForeign() || hasKnownSwiftMetadata(*this, clas)) { IRGen.noteUseOfTypeContextDescriptor(nominal, DontRequireMetadata); return getAddrOfLLVMVariableOrGOTEquivalent( LinkEntity::forNominalTypeDescriptor(nominal)); } } return {getAddrOfExtensionContextDescriptor(ext), ConstantReference::Direct}; } case DeclContextKind::FileUnit: parent = parent->getParentModule(); LLVM_FALLTHROUGH; case DeclContextKind::Module: if (auto *D = ofChild->getAsDecl()) { // If the top-level decl has been marked as moved from another module, // using @_originallyDefinedIn, we should emit the original module as // the context because all run-time names of this decl are based on the // original module name. auto OriginalModule = D->getAlternateModuleName(); if (!OriginalModule.empty()) { return {getAddrOfOriginalModuleContextDescriptor(OriginalModule), ConstantReference::Direct}; } } return {getAddrOfModuleContextDescriptor(cast<ModuleDecl>(parent)), ConstantReference::Direct}; } llvm_unreachable("unhandled kind"); } /// Return the address of the context descriptor representing the parent of /// the given decl context. /// /// For a nominal type context, this returns the address of the nominal type /// descriptor. /// For an extension context, this returns the address of the extension /// context descriptor. /// For a module or file unit context, this returns the address of the module /// context descriptor. /// For any other kind of context, this returns an anonymous context descriptor /// for the context. ConstantReference IRGenModule::getAddrOfParentContextDescriptor(DeclContext *from, bool fromAnonymousContext) { // Some types get special treatment. if (auto Type = dyn_cast<NominalTypeDecl>(from)) { // Use a special module context if we have one. if (auto context = Mangle::ASTMangler::getSpecialManglingContext( Type, /*UseObjCProtocolNames=*/false)) { switch (*context) { case Mangle::ASTMangler::ObjCContext: return {getAddrOfObjCModuleContextDescriptor(), ConstantReference::Direct}; case Mangle::ASTMangler::ClangImporterContext: return {getAddrOfClangImporterModuleContextDescriptor(), ConstantReference::Direct}; } } // Wrap up private types in an anonymous context for the containing file // unit so that the runtime knows they have unstable identity. if (!fromAnonymousContext && Type->isOutermostPrivateOrFilePrivateScope() && !Type->isUsableFromInline()) return {getAddrOfAnonymousContextDescriptor(Type), ConstantReference::Direct}; } return getAddrOfContextDescriptorForParent(from->getParent(), from, fromAnonymousContext); } static void markGlobalAsUsedBasedOnLinkage(IRGenModule &IGM, LinkInfo &link, llvm::GlobalValue *global) { // If we're internalizing public symbols at link time, don't make globals // unconditionally externally visible. if (IGM.getOptions().InternalizeAtLink) return; // Everything externally visible is considered used in Swift. // That mostly means we need to be good at not marking things external. if (link.isUsed()) IGM.addUsedGlobal(global); } bool LinkInfo::isUsed(IRLinkage IRL) { // Everything externally visible is considered used in Swift. // That mostly means we need to be good at not marking things external. return IRL.Linkage == llvm::GlobalValue::ExternalLinkage && (IRL.Visibility == llvm::GlobalValue::DefaultVisibility || IRL.Visibility == llvm::GlobalValue::ProtectedVisibility) && (IRL.DLLStorage == llvm::GlobalValue::DefaultStorageClass || IRL.DLLStorage == llvm::GlobalValue::DLLExportStorageClass); } /// Add the given global value to @llvm.used. /// /// This value must have a definition by the time the module is finalized. void IRGenModule::addUsedGlobal(llvm::GlobalValue *global) { // As of reviews.llvm.org/D97448 "ELF: Create unique SHF_GNU_RETAIN sections // for llvm.used global objects" LLVM creates separate sections for globals in // llvm.used on ELF. Therefore we use llvm.compiler.used on ELF instead. if (TargetInfo.OutputObjectFormat == llvm::Triple::ELF) { addCompilerUsedGlobal(global); return; } LLVMUsed.push_back(global); } /// Add the given global value to @llvm.compiler.used. /// /// This value must have a definition by the time the module is finalized. void IRGenModule::addCompilerUsedGlobal(llvm::GlobalValue *global) { LLVMCompilerUsed.push_back(global); } /// Add the given global value to the Objective-C class list. void IRGenModule::addObjCClass(llvm::Constant *classPtr, bool nonlazy) { ObjCClasses.push_back(classPtr); if (nonlazy) ObjCNonLazyClasses.push_back(classPtr); } /// Add the given global value to the Objective-C resilient class stub list. void IRGenModule::addObjCClassStub(llvm::Constant *classPtr) { ObjCClassStubs.push_back(classPtr); } void IRGenModule::addRuntimeResolvableType(GenericTypeDecl *type) { // Collect the nominal type records we emit into a special section. RuntimeResolvableTypes.push_back(type); if (auto nominal = dyn_cast<NominalTypeDecl>(type)) { // As soon as the type metadata is available, all the type's conformances // must be available, too. The reason is that a type (with the help of its // metadata) can be checked at runtime if it conforms to a protocol. addLazyConformances(nominal); } } ConstantReference IRGenModule::getConstantReferenceForProtocolDescriptor(ProtocolDecl *proto) { if (proto->isObjC()) { // ObjC protocol descriptors don't have a unique address, but get uniqued // by the Objective-C runtime at load time. // Get the indirected address of the protocol descriptor reference variable // that the ObjC runtime uniques. auto refVar = getAddrOfObjCProtocolRef(proto, NotForDefinition); return ConstantReference(refVar, ConstantReference::Indirect); } // Try to form a direct reference to the nominal type descriptor if it's in // the same binary, or use the GOT entry if it's from another binary. return getAddrOfLLVMVariableOrGOTEquivalent( LinkEntity::forProtocolDescriptor(proto)); } void IRGenModule::addLazyConformances(const IterableDeclContext *idc) { for (const ProtocolConformance *conf : idc->getLocalConformances(ConformanceLookupKind::All)) { IRGen.addLazyWitnessTable(conf); } } std::string IRGenModule::GetObjCSectionName(StringRef Section, StringRef MachOAttributes) { assert(Section.substr(0, 2) == "__" && "expected the name to begin with __"); switch (TargetInfo.OutputObjectFormat) { case llvm::Triple::GOFF: case llvm::Triple::UnknownObjectFormat: llvm_unreachable("must know the object file format"); case llvm::Triple::MachO: return MachOAttributes.empty() ? ("__DATA," + Section).str() : ("__DATA," + Section + "," + MachOAttributes).str(); case llvm::Triple::ELF: case llvm::Triple::Wasm: return Section.substr(2).str(); case llvm::Triple::XCOFF: case llvm::Triple::COFF: return ("." + Section.substr(2) + "$B").str(); } llvm_unreachable("unexpected object file format"); } void IRGenModule::SetCStringLiteralSection(llvm::GlobalVariable *GV, ObjCLabelType Type) { switch (TargetInfo.OutputObjectFormat) { case llvm::Triple::GOFF: case llvm::Triple::UnknownObjectFormat: llvm_unreachable("must know the object file format"); case llvm::Triple::MachO: switch (Type) { case ObjCLabelType::ClassName: GV->setSection("__TEXT,__objc_classname,cstring_literals"); return; case ObjCLabelType::MethodVarName: GV->setSection("__TEXT,__objc_methname,cstring_literals"); return; case ObjCLabelType::MethodVarType: GV->setSection("__TEXT,__objc_methtype,cstring_literals"); return; case ObjCLabelType::PropertyName: GV->setSection("__TEXT,__cstring,cstring_literals"); return; } case llvm::Triple::ELF: case llvm::Triple::Wasm: return; case llvm::Triple::XCOFF: case llvm::Triple::COFF: return; } llvm_unreachable("unexpected object file format"); } void IRGenModule::emitGlobalLists() { if (ObjCInterop) { // Objective-C class references go in a variable with a meaningless // name but a magic section. emitGlobalList( *this, ObjCClasses, "objc_classes", GetObjCSectionName("__objc_classlist", "regular,no_dead_strip"), llvm::GlobalValue::InternalLinkage, Int8PtrTy, /*isConstant*/ false, /*asContiguousArray*/ false); // So do resilient class stubs. emitGlobalList( *this, ObjCClassStubs, "objc_class_stubs", GetObjCSectionName("__objc_stublist", "regular,no_dead_strip"), llvm::GlobalValue::InternalLinkage, Int8PtrTy, /*isConstant*/ false, /*asContiguousArray*/ true); // So do categories. emitGlobalList( *this, ObjCCategories, "objc_categories", GetObjCSectionName("__objc_catlist", "regular,no_dead_strip"), llvm::GlobalValue::InternalLinkage, Int8PtrTy, /*isConstant*/ false, /*asContiguousArray*/ true); // And categories on class stubs. emitGlobalList( *this, ObjCCategoriesOnStubs, "objc_categories_stubs", GetObjCSectionName("__objc_catlist2", "regular,no_dead_strip"), llvm::GlobalValue::InternalLinkage, Int8PtrTy, /*isConstant*/ false, /*asContiguousArray*/ true); // Emit nonlazily realized class references in a second magic section to // make sure they are realized by the Objective-C runtime before any // instances are allocated. emitGlobalList( *this, ObjCNonLazyClasses, "objc_non_lazy_classes", GetObjCSectionName("__objc_nlclslist", "regular,no_dead_strip"), llvm::GlobalValue::InternalLinkage, Int8PtrTy, /*isConstant*/ false, /*asContiguousArray*/ true); } // @llvm.used // Collect llvm.used globals already in the module (coming from ClangCodeGen). collectGlobalList(*this, LLVMUsed, "llvm.used"); emitGlobalList(*this, LLVMUsed, "llvm.used", "llvm.metadata", llvm::GlobalValue::AppendingLinkage, Int8PtrTy, /*isConstant*/false, /*asContiguousArray*/true); // Collect llvm.compiler.used globals already in the module (coming // from ClangCodeGen). collectGlobalList(*this, LLVMCompilerUsed, "llvm.compiler.used"); emitGlobalList(*this, LLVMCompilerUsed, "llvm.compiler.used", "llvm.metadata", llvm::GlobalValue::AppendingLinkage, Int8PtrTy, /*isConstant*/false, /*asContiguousArray*/true); } static bool hasCodeCoverageInstrumentation(SILFunction &f, SILModule &m) { return f.getProfiler() && m.getOptions().EmitProfileCoverageMapping; } // Eagerly emit functions that are externally visible. Functions with code // coverage instrumentation must also be eagerly emitted. So must functions // that are a dynamic replacement for another. static bool isLazilyEmittedFunction(SILFunction &f, SILModule &m) { if (f.isPossiblyUsedExternally()) return false; if (f.getDynamicallyReplacedFunction()) return false; if (hasCodeCoverageInstrumentation(f, m)) return false; // Needed by lldb to print global variables which are propagated by the // mandatory GlobalOpt. if (m.getOptions().OptMode == OptimizationMode::NoOptimization && f.isGlobalInit()) return false; return true; } void IRGenerator::emitGlobalTopLevel( const std::vector<std::string> &linkerDirectives) { // Generate order numbers for the functions in the SIL module that // correspond to definitions in the LLVM module. unsigned nextOrderNumber = 0; for (auto &silFn : PrimaryIGM->getSILModule().getFunctions()) { // Don't bother adding external declarations to the function order. if (!silFn.isDefinition()) continue; FunctionOrder.insert(std::make_pair(&silFn, nextOrderNumber++)); } // Ensure that relative symbols are collocated in the same LLVM module. for (auto &wt : PrimaryIGM->getSILModule().getWitnessTableList()) { CurrentIGMPtr IGM = getGenModule(wt.getDeclContext()); ensureRelativeSymbolCollocation(wt); } for (auto &wt : PrimaryIGM->getSILModule().getDefaultWitnessTableList()) { CurrentIGMPtr IGM = getGenModule(wt.getProtocol()->getDeclContext()); ensureRelativeSymbolCollocation(wt); } for (auto &directive: linkerDirectives) { createLinkerDirectiveVariable(*PrimaryIGM, directive); } for (SILGlobalVariable &v : PrimaryIGM->getSILModule().getSILGlobals()) { Decl *decl = v.getDecl(); CurrentIGMPtr IGM = getGenModule(decl ? decl->getDeclContext() : nullptr); IGM->emitSILGlobalVariable(&v); } // Emit SIL functions. auto &m = PrimaryIGM->getSILModule(); for (SILFunction &f : m) { if (isLazilyEmittedFunction(f, m)) continue; CurrentIGMPtr IGM = getGenModule(&f); IGM->emitSILFunction(&f); } // Emit static initializers. for (auto Iter : *this) { IRGenModule *IGM = Iter.second; IGM->emitSILStaticInitializers(); } // Emit witness tables. for (SILWitnessTable &wt : PrimaryIGM->getSILModule().getWitnessTableList()) { CurrentIGMPtr IGM = getGenModule(wt.getDeclContext()); if (!canEmitWitnessTableLazily(&wt)) { IGM->emitSILWitnessTable(&wt); } } // Emit property descriptors. for (auto &prop : PrimaryIGM->getSILModule().getPropertyList()) { CurrentIGMPtr IGM = getGenModule(prop.getDecl()->getInnermostDeclContext()); IGM->emitSILProperty(&prop); } // Emit differentiability witnesses. for (auto &dw : PrimaryIGM->getSILModule().getDifferentiabilityWitnessList()) { // Emit into same IRGenModule as the original function. // NOTE(TF-894): Investigate whether `getGenModule(dw.getVJP())` is // significant/desirable; `getGenModule` seems relevant for multi-threaded // compilation. When the differentiation transform canonicalizes all // differentiability witnesses to have JVP/VJP functions, we can assert // that JVP/VJP functions exist and use `getGenModule(dw.getVJP())`. CurrentIGMPtr IGM = getGenModule(dw.getOriginalFunction()); IGM->emitSILDifferentiabilityWitness(&dw); } // Emit code coverage mapping data for all modules for (auto Iter : *this) { IRGenModule *IGM = Iter.second; IGM->emitCoverageMapping(); } for (auto Iter : *this) { IRGenModule *IGM = Iter.second; IGM->finishEmitAfterTopLevel(); } emitEntryPointInfo(); } void IRGenModule::finishEmitAfterTopLevel() { // Emit the implicit import of the swift standard library. // FIXME: We'd get the exact set of implicit imports if we went through the // SourceFile's getImportedModules instead, but then we'd lose location info // for the explicit imports. if (DebugInfo) { if (ModuleDecl *TheStdlib = Context.getStdlibModule()) { if (TheStdlib != getSwiftModule()) { Located<swift::Identifier> moduleName[] = { { Context.StdlibModuleName, swift::SourceLoc() } }; auto Imp = ImportDecl::create(Context, getSwiftModule(), SourceLoc(), ImportKind::Module, SourceLoc(), llvm::makeArrayRef(moduleName)); Imp->setModule(TheStdlib); DebugInfo->emitImport(Imp); } } } } void IRGenerator::emitSwiftProtocols() { for (auto &m : *this) { m.second->emitSwiftProtocols(/*asContiguousArray*/ false); } } void IRGenerator::emitProtocolConformances() { for (auto &m : *this) { m.second->emitProtocolConformances(/*asContiguousArray*/ false); } } void IRGenerator::emitTypeMetadataRecords() { for (auto &m : *this) { m.second->emitTypeMetadataRecords(/*asContiguousArray*/ false); } } static void deleteAndReenqueueForEmissionValuesDependentOnCanonicalPrespecializedMetadataRecords( IRGenModule &IGM, CanType typeWithCanonicalMetadataPrespecialization, NominalTypeDecl &decl) { // The accessor depends on the existence of canonical metadata records // because their presence determine which runtime function is called. auto *accessor = IGM.getAddrOfTypeMetadataAccessFunction( decl.getDeclaredType()->getCanonicalType(), NotForDefinition); accessor->deleteBody(); IGM.IRGen.noteUseOfMetadataAccessor(&decl); IGM.IRGen.noteLazyReemissionOfNominalTypeDescriptor(&decl); // The type context descriptor depends on canonical metadata records because // pointers to them are attached as trailing objects to it. // // Don't call // // noteUseOfTypeContextDescriptor // // here because we don't want to reemit metadata. emitLazyTypeContextDescriptor(IGM, &decl, RequireMetadata); } /// Emit any lazy definitions (of globals or functions or whatever /// else) that we require. void IRGenerator::emitLazyDefinitions() { while (!LazyTypeMetadata.empty() || !LazySpecializedTypeMetadataRecords.empty() || !LazyTypeContextDescriptors.empty() || !LazyOpaqueTypeDescriptors.empty() || !LazyFieldDescriptors.empty() || !LazyFunctionDefinitions.empty() || !LazyWitnessTables.empty() || !LazyCanonicalSpecializedMetadataAccessors.empty() || !LazyMetadataAccessors.empty()) { // Emit any lazy type metadata we require. while (!LazyTypeMetadata.empty()) { NominalTypeDecl *type = LazyTypeMetadata.pop_back_val(); auto &entry = LazyTypeGlobals.find(type)->second; assert(hasLazyMetadata(type)); assert(entry.IsMetadataUsed && !entry.IsMetadataEmitted); entry.IsMetadataEmitted = true; CurrentIGMPtr IGM = getGenModule(type->getDeclContext()); emitLazyTypeMetadata(*IGM.get(), type); } while (!LazySpecializedTypeMetadataRecords.empty()) { CanType theType; TypeMetadataCanonicality canonicality; std::tie(theType, canonicality) = LazySpecializedTypeMetadataRecords.pop_back_val(); auto *nominal = theType->getNominalOrBoundGenericNominal(); CurrentIGMPtr IGMPtr = getGenModule(nominal->getDeclContext()); auto &IGM = *IGMPtr.get(); // A new canonical prespecialized metadata changes both the type // descriptor (adding a new entry to the trailing list of metadata) and // the metadata accessor (calling the appropriate getGenericMetadata // variant depending on whether there are any canonical prespecialized // metadata records to add to the metadata cache). Consequently, it is // necessary to force these to be reemitted. if (canonicality == TypeMetadataCanonicality::Canonical) { deleteAndReenqueueForEmissionValuesDependentOnCanonicalPrespecializedMetadataRecords( IGM, theType, *nominal); } emitLazySpecializedGenericTypeMetadata(IGM, theType); } while (!LazyTypeContextDescriptors.empty()) { NominalTypeDecl *type = LazyTypeContextDescriptors.pop_back_val(); auto &entry = LazyTypeGlobals.find(type)->second; assert(hasLazyMetadata(type)); assert(entry.IsDescriptorUsed && !entry.IsDescriptorEmitted); entry.IsDescriptorEmitted = true; CurrentIGMPtr IGM = getGenModule(type->getDeclContext()); emitLazyTypeContextDescriptor(*IGM.get(), type, RequireMetadata_t(entry.IsMetadataUsed)); } while (!LazyOpaqueTypeDescriptors.empty()) { OpaqueTypeDecl *type = LazyOpaqueTypeDescriptors.pop_back_val(); auto &entry = LazyOpaqueTypes.find(type)->second; assert(hasLazyMetadata(type)); assert(entry.IsDescriptorUsed && !entry.IsDescriptorEmitted); entry.IsDescriptorEmitted = true; CurrentIGMPtr IGM = getGenModule(type->getDeclContext()); IGM->emitOpaqueTypeDecl(type); } while (!LazyFieldDescriptors.empty()) { NominalTypeDecl *type = LazyFieldDescriptors.pop_back_val(); CurrentIGMPtr IGM = getGenModule(type->getDeclContext()); IGM->emitFieldDescriptor(type); } while (!LazyWitnessTables.empty()) { SILWitnessTable *wt = LazyWitnessTables.pop_back_val(); CurrentIGMPtr IGM = getGenModule(wt->getDeclContext()); IGM->emitSILWitnessTable(wt); } // Emit any lazy function definitions we require. while (!LazyFunctionDefinitions.empty()) { SILFunction *f = LazyFunctionDefinitions.pop_back_val(); CurrentIGMPtr IGM = getGenModule(f); assert(!f->isPossiblyUsedExternally() && "function with externally-visible linkage emitted lazily?"); IGM->emitSILFunction(f); } while (!LazyCanonicalSpecializedMetadataAccessors.empty()) { CanType theType = LazyCanonicalSpecializedMetadataAccessors.pop_back_val(); auto *nominal = theType->getAnyNominal(); assert(nominal); CurrentIGMPtr IGMPtr = getGenModule(nominal->getDeclContext()); auto &IGM = *IGMPtr.get(); // TODO: Once non-canonical accessors are available, this variable should // reflect the canonicality of the accessor rather than always being // canonical. auto canonicality = TypeMetadataCanonicality::Canonical; if (canonicality == TypeMetadataCanonicality::Canonical) { deleteAndReenqueueForEmissionValuesDependentOnCanonicalPrespecializedMetadataRecords( IGM, theType, *nominal); } emitLazyCanonicalSpecializedMetadataAccessor(IGM, theType); } while (!LazyMetadataAccessors.empty()) { NominalTypeDecl *nominal = LazyMetadataAccessors.pop_back_val(); CurrentIGMPtr IGM = getGenModule(nominal->getDeclContext()); emitLazyMetadataAccessor(*IGM.get(), nominal); } } FinishedEmittingLazyDefinitions = true; } void IRGenerator::addLazyFunction(SILFunction *f) { // Add it to the queue if it hasn't already been put there. if (!LazilyEmittedFunctions.insert(f).second) return; assert(!FinishedEmittingLazyDefinitions); LazyFunctionDefinitions.push_back(f); if (const SILFunction *orig = f->getOriginOfSpecialization()) { // f is a specialization. Try to emit all specializations of the same // original function into the same IGM. This increases the chances that // specializations are merged by LLVM's function merging. IRGenModule *IGM = CurrentIGM ? CurrentIGM : getPrimaryIGM(); auto iter = IGMForSpecializations.insert(std::make_pair(orig, IGM)).first; DefaultIGMForFunction.insert(std::make_pair(f, iter->second)); return; } if (auto *dc = f->getDeclContext()) if (dc->getParentSourceFile()) return; if (CurrentIGM == nullptr) return; // Don't update the map if we already have an entry. DefaultIGMForFunction.insert(std::make_pair(f, CurrentIGM)); } bool IRGenerator::hasLazyMetadata(TypeDecl *type) { assert(isa<NominalTypeDecl>(type) || isa<OpaqueTypeDecl>(type)); auto found = HasLazyMetadata.find(type); if (found != HasLazyMetadata.end()) return found->second; auto canBeLazy = [&]() -> bool { auto *dc = type->getDeclContext(); if (isa<ClangModuleUnit>(dc->getModuleScopeContext())) { if (auto nominal = dyn_cast<NominalTypeDecl>(type)) { return requiresForeignTypeMetadata(nominal); } } else if (dc->getParentModule() == SIL.getSwiftModule()) { // When compiling with -Onone keep all metadata for the debugger. Even if // it is not used by the program itself. if (!Opts.shouldOptimize()) return false; if (Opts.UseJIT) return false; if (isa<ClassDecl>(type) || isa<ProtocolDecl>(type)) return false; switch (type->getEffectiveAccess()) { case AccessLevel::Open: case AccessLevel::Public: // We can't remove metadata for externally visible types. return false; case AccessLevel::Internal: // In non-whole-module mode, internal types are also visible externally. return SIL.isWholeModule(); case AccessLevel::FilePrivate: case AccessLevel::Private: return true; } } return false; }; bool isLazy = canBeLazy(); HasLazyMetadata[type] = isLazy; return isLazy; } void IRGenerator::noteUseOfTypeGlobals(NominalTypeDecl *type, bool isUseOfMetadata, RequireMetadata_t requireMetadata) { if (!type) return; // Force emission of ObjC protocol descriptors used by type refs. if (auto proto = dyn_cast<ProtocolDecl>(type)) { if (proto->isObjC()) { PrimaryIGM->getAddrOfObjCProtocolRecord(proto, NotForDefinition); return; } } if (!hasLazyMetadata(type)) return; // If the type can be generated in several TU with weak linkage we don't know // which one will be picked up so we have to require the metadata. Otherwise, // the situation can arise where one TU contains a type descriptor with a null // metadata access function and the other TU which requires metadata has a // type descriptor with a valid metadata access function but the linker picks // the first one. if (isAccessorLazilyGenerated(getTypeMetadataAccessStrategy( type->getDeclaredType()->getCanonicalType()))) { requireMetadata = RequireMetadata; } // Try to create a new record of the fact that we used this type. auto insertResult = LazyTypeGlobals.try_emplace(type); auto &entry = insertResult.first->second; bool metadataWasUsed = entry.IsMetadataUsed; bool descriptorWasUsed = entry.IsDescriptorUsed; bool isNovelUseOfMetadata = false; bool isNovelUseOfDescriptor = false; // Flag that we have a use of the metadata if // - the reference was directly to the metadata // - the reference was to the descriptor, but it requested the emission // of metadata if (!metadataWasUsed && (isUseOfMetadata || requireMetadata)) { if (metadataWasUsed) return; entry.IsMetadataUsed = true; isNovelUseOfMetadata = true; } if (!descriptorWasUsed && !isUseOfMetadata) { if (descriptorWasUsed) return; entry.IsDescriptorUsed = true; isNovelUseOfDescriptor = true; } // Enqueue metadata emission if we have a novel use of it. if (isNovelUseOfMetadata) { assert(!FinishedEmittingLazyDefinitions); LazyTypeMetadata.push_back(type); } // Enqueue descriptor emission if we have a novel use of it or if we // need to re-emit it because we're suddenly using metadata for it. if (isNovelUseOfDescriptor || (isNovelUseOfMetadata && entry.IsDescriptorEmitted)) { entry.IsDescriptorEmitted = false; // clear this in case it was true assert(!FinishedEmittingLazyDefinitions); LazyTypeContextDescriptors.push_back(type); } } void IRGenerator::noteUseOfFieldDescriptor(NominalTypeDecl *type) { if (!hasLazyMetadata(type)) return; // Imported classes and protocols do not need field descriptors. if (type->hasClangNode() && (isa<ClassDecl>(type) || isa<ProtocolDecl>(type))) return; if (!LazilyEmittedFieldMetadata.insert(type).second) return; assert(!FinishedEmittingLazyDefinitions); LazyFieldDescriptors.push_back(type); } void IRGenerator::noteUseOfCanonicalSpecializedMetadataAccessor( CanType forType) { auto key = forType->getAnyNominal(); assert(key); assert(key->isGenericContext()); auto &enqueuedSpecializedAccessors = CanonicalSpecializedAccessorsForGenericTypes[key]; if (llvm::all_of(enqueuedSpecializedAccessors, [&](CanType enqueued) { return enqueued != forType; })) { assert(!FinishedEmittingLazyDefinitions); LazyCanonicalSpecializedMetadataAccessors.insert(forType); enqueuedSpecializedAccessors.push_back(forType); } } static bool typeKindCanBePrespecialized(TypeKind theKind) { switch (theKind) { case TypeKind::Struct: case TypeKind::BoundGenericStruct: case TypeKind::Enum: case TypeKind::BoundGenericEnum: case TypeKind::Class: case TypeKind::BoundGenericClass: return true; default: return false; } } void IRGenerator::noteUseOfSpecializedGenericTypeMetadata( IRGenModule &IGM, CanType theType, TypeMetadataCanonicality canonicality) { assert(typeKindCanBePrespecialized(theType->getKind())); auto key = theType->getAnyNominal(); assert(key); assert(key->isGenericContext()); auto &enqueuedSpecializedTypes = MetadataPrespecializationsForGenericTypes[key]; if (llvm::all_of(enqueuedSpecializedTypes, [&](auto enqueued) { return enqueued.first != theType; })) { assert(!FinishedEmittingLazyDefinitions); LazySpecializedTypeMetadataRecords.push_back({theType, canonicality}); enqueuedSpecializedTypes.push_back({theType, canonicality}); } } void IRGenerator::noteUseOfOpaqueTypeDescriptor(OpaqueTypeDecl *opaque) { if (!opaque) return; if (!hasLazyMetadata(opaque)) return; auto insertResult = LazyOpaqueTypes.try_emplace(opaque); auto &entry = insertResult.first->second; bool isNovelUseOfDescriptor = !entry.IsDescriptorUsed; entry.IsDescriptorUsed = true; if (isNovelUseOfDescriptor) { LazyOpaqueTypeDescriptors.push_back(opaque); } } static std::string getDynamicReplacementSection(IRGenModule &IGM) { std::string sectionName; switch (IGM.TargetInfo.OutputObjectFormat) { case llvm::Triple::GOFF: case llvm::Triple::UnknownObjectFormat: llvm_unreachable("Don't know how to emit field records table for " "the selected object format."); case llvm::Triple::MachO: sectionName = "__TEXT, __swift5_replace, regular, no_dead_strip"; break; case llvm::Triple::ELF: case llvm::Triple::Wasm: sectionName = "swift5_replace"; break; case llvm::Triple::XCOFF: case llvm::Triple::COFF: sectionName = ".sw5repl$B"; break; } return sectionName; } static std::string getDynamicReplacementSomeSection(IRGenModule &IGM) { std::string sectionName; switch (IGM.TargetInfo.OutputObjectFormat) { case llvm::Triple::GOFF: case llvm::Triple::UnknownObjectFormat: llvm_unreachable("Don't know how to emit field records table for " "the selected object format."); case llvm::Triple::MachO: sectionName = "__TEXT, __swift5_replac2, regular, no_dead_strip"; break; case llvm::Triple::ELF: case llvm::Triple::Wasm: sectionName = "swift5_replac2"; break; case llvm::Triple::XCOFF: case llvm::Triple::COFF: sectionName = ".sw5reps$B"; break; } return sectionName; } llvm::GlobalVariable *IRGenModule::getGlobalForDynamicallyReplaceableThunk( LinkEntity &entity, llvm::Type *type, ForDefinition_t forDefinition) { return cast<llvm::GlobalVariable>( getAddrOfLLVMVariable(entity, forDefinition, DebugTypeInfo())); } /// Creates a dynamic replacement chain entry for \p SILFn that contains either /// the implementation function pointer \p or a nullptr, the next pointer of the /// chain entry is set to nullptr. /// struct ChainEntry { /// void *funPtr; /// struct ChainEntry *next; /// } static llvm::GlobalVariable *getChainEntryForDynamicReplacement( IRGenModule &IGM, LinkEntity entity, llvm::Constant *implFunction = nullptr, ForDefinition_t forDefinition = ForDefinition) { auto linkEntry = IGM.getGlobalForDynamicallyReplaceableThunk( entity, IGM.DynamicReplacementLinkEntryTy, forDefinition); if (!forDefinition) return linkEntry; auto *funPtr = implFunction ? llvm::ConstantExpr::getBitCast(implFunction, IGM.Int8PtrTy) : llvm::ConstantExpr::getNullValue(IGM.Int8PtrTy); if (implFunction) { llvm::Constant *indices[] = {llvm::ConstantInt::get(IGM.Int32Ty, 0), llvm::ConstantInt::get(IGM.Int32Ty, 0)}; auto *storageAddr = llvm::ConstantExpr::getInBoundsGetElementPtr( linkEntry->getType()->getPointerElementType(), linkEntry, indices); bool isAsyncFunction = entity.hasSILFunction() && entity.getSILFunction()->isAsync(); auto &schema = isAsyncFunction ? IGM.getOptions().PointerAuth.AsyncSwiftDynamicReplacements : IGM.getOptions().PointerAuth.SwiftDynamicReplacements; assert(entity.hasSILFunction() || entity.isOpaqueTypeDescriptorAccessor()); auto authEntity = entity.hasSILFunction() ? PointerAuthEntity(entity.getSILFunction()) : PointerAuthEntity::Special::TypeDescriptor; funPtr = IGM.getConstantSignedPointer(funPtr, schema, authEntity, storageAddr); } auto *nextEntry = llvm::ConstantExpr::getNullValue(IGM.DynamicReplacementLinkEntryPtrTy); llvm::Constant *fields[] = {funPtr, nextEntry}; auto *entry = llvm::ConstantStruct::get(IGM.DynamicReplacementLinkEntryTy, fields); linkEntry->setInitializer(entry); return linkEntry; } void IRGenerator::emitDynamicReplacements() { if (DynamicReplacements.empty()) return; auto &IGM = *getPrimaryIGM(); // Collect all the type metadata accessor replacements. SmallVector<OpaqueTypeArchetypeType *, 8> newFuncTypes; SmallVector<OpaqueTypeArchetypeType *, 8> origFuncTypes; llvm::SmallSet<OpaqueTypeArchetypeType *, 8> newUniqueOpaqueTypes; llvm::SmallSet<OpaqueTypeArchetypeType *, 8> origUniqueOpaqueTypes; for (auto *newFunc : DynamicReplacements) { auto newResultTy = newFunc->getLoweredFunctionType() ->getAllResultsInterfaceType() .getASTType(); if (!newResultTy->hasOpaqueArchetype()) continue; newResultTy.visit([&](CanType ty) { if (auto opaque = ty->getAs<OpaqueTypeArchetypeType>()) if (newUniqueOpaqueTypes.insert(opaque).second) newFuncTypes.push_back(opaque); }); auto *origFunc = newFunc->getDynamicallyReplacedFunction(); assert(origFunc); auto origResultTy = origFunc->getLoweredFunctionType() ->getAllResultsInterfaceType() .getASTType(); assert(origResultTy->hasOpaqueArchetype()); origResultTy.visit([&](CanType ty) { if (auto opaque = ty->getAs<OpaqueTypeArchetypeType>()) if (origUniqueOpaqueTypes.insert(opaque).second) origFuncTypes.push_back(opaque); }); assert(origFuncTypes.size() == newFuncTypes.size()); } // struct ReplacementScope { // uint32t flags; // unused // uint32t numReplacements; // struct Entry { // RelativeIndirectablePointer<KeyEntry, false> replacedFunctionKey; // RelativeDirectPointer<void> newFunction; // RelativeDirectPointer<LinkEntry> replacement; // uint32_t flags; // shouldChain. // }[0] // }; ConstantInitBuilder builder(IGM); auto replacementScope = builder.beginStruct(); replacementScope.addInt32(0); // unused flags. replacementScope.addInt32(DynamicReplacements.size() + newFuncTypes.size()); auto replacementsArray = replacementScope.beginArray(); for (auto *newFunc : DynamicReplacements) { LinkEntity entity = LinkEntity::forDynamicallyReplaceableFunctionVariable(newFunc); auto replacementLinkEntry = getChainEntryForDynamicReplacement(IGM, entity); // TODO: replacementLinkEntry->setZeroSection() auto *origFunc = newFunc->getDynamicallyReplacedFunction(); assert(origFunc); auto keyRef = IGM.getAddrOfLLVMVariableOrGOTEquivalent( LinkEntity::forDynamicallyReplaceableFunctionKey(origFunc)); llvm::Constant *newFnPtr = llvm::ConstantExpr::getBitCast( newFunc->isAsync() ? IGM.getAddrOfAsyncFunctionPointer( LinkEntity::forSILFunction(newFunc)) : IGM.getAddrOfSILFunction(newFunc, NotForDefinition), IGM.Int8PtrTy); auto replacement = replacementsArray.beginStruct(); replacement.addRelativeAddress(keyRef); // tagged relative reference. replacement.addRelativeAddress(newFnPtr); // direct relative reference. replacement.addRelativeAddress( replacementLinkEntry); // direct relative reference. replacement.addInt32( Opts.EnableDynamicReplacementChaining ? 1 : 0); replacement.finishAndAddTo(replacementsArray); } // Emit replacements of the opaque type descriptor accessor. for (auto i : indices(origFuncTypes)) { LinkEntity entity = LinkEntity::forOpaqueTypeDescriptorAccessorVar( newFuncTypes[i]->getDecl()); auto replacementLinkEntry = getChainEntryForDynamicReplacement(IGM, entity); auto keyRef = IGM.getAddrOfLLVMVariableOrGOTEquivalent( LinkEntity::forOpaqueTypeDescriptorAccessorKey( origFuncTypes[i]->getDecl())); llvm::Constant *newFnPtr = llvm::ConstantExpr::getBitCast( IGM.getAddrOfOpaqueTypeDescriptorAccessFunction( newFuncTypes[i]->getDecl(), NotForDefinition, false), IGM.Int8PtrTy); auto replacement = replacementsArray.beginStruct(); replacement.addRelativeAddress(keyRef); // tagged relative reference. replacement.addRelativeAddress(newFnPtr); // direct relative reference. replacement.addRelativeAddress( replacementLinkEntry); // direct relative reference. replacement.addInt32(0); replacement.finishAndAddTo(replacementsArray); } replacementsArray.finishAndAddTo(replacementScope); auto var = replacementScope.finishAndCreateGlobal( "\x01l_unnamed_dynamic_replacements", IGM.getPointerAlignment(), /*isConstant*/ true, llvm::GlobalValue::PrivateLinkage); IGM.setTrueConstGlobal(var); IGM.addUsedGlobal(var); // Emit the data for automatic replacement to happen on load. // struct AutomaticReplacements { // uint32t flags; // unused // uint32t numReplacements; // struct Entry { // RelativeDirectPointer<ReplacementScope> replacements; // uint32_t flags; // unused. // }[0] // }; auto autoReplacements = builder.beginStruct(); autoReplacements.addInt32(0); // unused flags. autoReplacements.addInt32(1); // number of replacement entries. auto autoReplacementsArray = autoReplacements.beginArray(); autoReplacementsArray.addRelativeAddress(var); autoReplacementsArray.addInt32(0); // unused flags. autoReplacementsArray.finishAndAddTo(autoReplacements); auto autoReplVar = autoReplacements.finishAndCreateGlobal( "\x01l_auto_dynamic_replacements", IGM.getPointerAlignment(), /*isConstant*/ true, llvm::GlobalValue::PrivateLinkage); autoReplVar->setSection(getDynamicReplacementSection(IGM)); IGM.addUsedGlobal(autoReplVar); if (origFuncTypes.empty()) return; // Emit records for replacing opaque type descriptor for some types. // struct AutomaticReplacementsSome { // uint32t flags; // unused // uint32t numReplacements; // struct Entry { // RelativeIndirectablePointer<OpaqueTypeDescriptor*> orig; // RelativeDirectPointer<OpaqueTypeDescriptor*> replacement; // uint32_t flags; // unused. // }[numEntries] // }; auto autoReplacementsSome = builder.beginStruct(); autoReplacementsSome.addInt32(0); // unused flags. autoReplacementsSome.addInt32( origFuncTypes.size()); // number of replacement entries. auto someReplacementsArray = autoReplacementsSome.beginArray(); for (auto i : indices(origFuncTypes)) { auto origDesc = LinkEntity::forOpaqueTypeDescriptor(origFuncTypes[i]->getDecl()); auto replDesc = LinkEntity::forOpaqueTypeDescriptor(newFuncTypes[i]->getDecl()); auto replacement = someReplacementsArray.beginStruct(); replacement.addRelativeAddress( IGM.getAddrOfLLVMVariableOrGOTEquivalent(origDesc)); replacement.addRelativeAddress( IGM.getAddrOfLLVMVariableOrGOTEquivalent(replDesc)); replacement.finishAndAddTo(someReplacementsArray); } someReplacementsArray.finishAndAddTo(autoReplacementsSome); auto autoReplVar2 = autoReplacementsSome.finishAndCreateGlobal( "\x01l_auto_dynamic_replacements_some", IGM.getPointerAlignment(), /*isConstant*/ true, llvm::GlobalValue::PrivateLinkage); autoReplVar2->setSection(getDynamicReplacementSomeSection(IGM)); } void IRGenerator::emitEagerClassInitialization() { if (ClassesForEagerInitialization.empty()) return; // Emit the register function in the primary module. IRGenModule *IGM = getPrimaryIGM(); llvm::Function *RegisterFn = llvm::Function::Create( llvm::FunctionType::get(IGM->VoidTy, false), llvm::GlobalValue::PrivateLinkage, "_swift_eager_class_initialization"); IGM->Module.getFunctionList().push_back(RegisterFn); IRGenFunction RegisterIGF(*IGM, RegisterFn); RegisterFn->setAttributes(IGM->constructInitialAttributes()); RegisterFn->setCallingConv(IGM->DefaultCC); for (ClassDecl *CD : ClassesForEagerInitialization) { auto Ty = CD->getDeclaredType()->getCanonicalType(); llvm::Value *MetaData = RegisterIGF.emitTypeMetadataRef(Ty); assert(CD->getAttrs().hasAttribute<StaticInitializeObjCMetadataAttr>()); // Get the metadata to make sure that the class is registered. We need to // add a use (empty inline asm instruction) for the metadata. Otherwise // llvm would optimize the metadata accessor call away because it's // defined as "readnone". llvm::FunctionType *asmFnTy = llvm::FunctionType::get(IGM->VoidTy, {MetaData->getType()}, false /* = isVarArg */); llvm::InlineAsm *inlineAsm = llvm::InlineAsm::get(asmFnTy, "", "r", true /* = SideEffects */); RegisterIGF.Builder.CreateAsmCall(inlineAsm, MetaData); } RegisterIGF.Builder.CreateRetVoid(); // Add the registration function as a static initializer. We use a priority // slightly lower than used for C++ global constructors, so that the code is // executed before C++ global constructors (in case someone uses archives // from a C++ global constructor). llvm::appendToGlobalCtors(IGM->Module, RegisterFn, 60000, nullptr); } void IRGenerator::emitObjCActorsNeedingSuperclassSwizzle() { if (ObjCActorsNeedingSuperclassSwizzle.empty()) return; // Emit the register function in the primary module. IRGenModule *IGM = getPrimaryIGM(); llvm::Function *RegisterFn = llvm::Function::Create( llvm::FunctionType::get(IGM->VoidTy, false), llvm::GlobalValue::PrivateLinkage, "_swift_objc_actor_initialization"); IGM->Module.getFunctionList().push_back(RegisterFn); IRGenFunction RegisterIGF(*IGM, RegisterFn); RegisterFn->setAttributes(IGM->constructInitialAttributes()); RegisterFn->setCallingConv(IGM->DefaultCC); // Look up the SwiftNativeNSObject class. auto swiftNativeNSObjectName = IGM->getAddrOfGlobalString("SwiftNativeNSObject"); auto swiftNativeNSObjectClass = RegisterIGF.Builder.CreateCall( RegisterIGF.IGM.getObjCGetRequiredClassFn(), swiftNativeNSObjectName); for (ClassDecl *CD : ObjCActorsNeedingSuperclassSwizzle) { // The @objc actor class. llvm::Value *classRef = RegisterIGF.emitTypeMetadataRef( CD->getDeclaredInterfaceType()->getCanonicalType()); classRef = RegisterIGF.Builder.CreateBitCast(classRef, IGM->ObjCClassPtrTy); // Set its superclass to SwiftNativeNSObject. RegisterIGF.Builder.CreateCall( RegisterIGF.IGM.getSetSuperclassFn(), { classRef, swiftNativeNSObjectClass}); } RegisterIGF.Builder.CreateRetVoid(); // Add the registration function as a static initializer. We use a priority // slightly lower than used for C++ global constructors, so that the code is // executed before C++ global constructors (in case someone manages to access // an @objc actor from a global constructor). llvm::appendToGlobalCtors(IGM->Module, RegisterFn, 60000, nullptr); } /// Emit symbols for eliminated dead methods, which can still be referenced /// from other modules. This happens e.g. if a public class contains a (dead) /// private method. void IRGenModule::emitVTableStubs() { llvm::Function *stub = nullptr; for (auto I = getSILModule().zombies_begin(); I != getSILModule().zombies_end(); ++I) { const SILFunction &F = *I; if (! F.isExternallyUsedSymbol()) continue; if (!stub) { // Create a single stub function which calls swift_deletedMethodError(). stub = llvm::Function::Create(llvm::FunctionType::get(VoidTy, false), llvm::GlobalValue::InternalLinkage, "_swift_dead_method_stub"); stub->setAttributes(constructInitialAttributes()); Module.getFunctionList().push_back(stub); stub->setCallingConv(DefaultCC); auto *entry = llvm::BasicBlock::Create(getLLVMContext(), "entry", stub); auto *errorFunc = getDeletedMethodErrorFn(); llvm::CallInst::Create(cast<llvm::FunctionType>( errorFunc->getType()->getPointerElementType()), errorFunc, ArrayRef<llvm::Value *>(), "", entry); new llvm::UnreachableInst(getLLVMContext(), entry); } // For each eliminated method symbol create an alias to the stub. auto *alias = llvm::GlobalAlias::create(llvm::GlobalValue::ExternalLinkage, F.getName(), stub); if (F.getEffectiveSymbolLinkage() == SILLinkage::Hidden) alias->setVisibility(llvm::GlobalValue::HiddenVisibility); else ApplyIRLinkage(IRLinkage::ExternalExport).to(alias); } } static std::string getEntryPointSection(IRGenModule &IGM) { std::string sectionName; switch (IGM.TargetInfo.OutputObjectFormat) { case llvm::Triple::GOFF: case llvm::Triple::UnknownObjectFormat: llvm_unreachable("Don't know how to emit field records table for " "the selected object format."); case llvm::Triple::MachO: sectionName = "__TEXT, __swift5_entry, regular, no_dead_strip"; break; case llvm::Triple::ELF: case llvm::Triple::Wasm: sectionName = "swift5_entry"; break; case llvm::Triple::XCOFF: case llvm::Triple::COFF: sectionName = ".sw5entr$B"; break; } return sectionName; } void IRGenerator::emitEntryPointInfo() { SILFunction *entrypoint = nullptr; if (!(entrypoint = SIL.lookUpFunction( SIL.getASTContext().getEntryPointFunctionName()))) { return; } auto &IGM = *getGenModule(entrypoint); ConstantInitBuilder builder(IGM); auto entrypointInfo = builder.beginStruct(); entrypointInfo.addRelativeAddress( IGM.getAddrOfSILFunction(entrypoint, NotForDefinition)); auto var = entrypointInfo.finishAndCreateGlobal( "\x01l_entry_point", Alignment(4), /*isConstant*/ true, llvm::GlobalValue::PrivateLinkage); var->setSection(getEntryPointSection(IGM)); IGM.addUsedGlobal(var); } static IRLinkage getIRLinkage(const UniversalLinkageInfo &info, SILLinkage linkage, ForDefinition_t isDefinition, bool isWeakImported, bool isKnownLocal = false) { #define RESULT(LINKAGE, VISIBILITY, DLL_STORAGE) \ IRLinkage{llvm::GlobalValue::LINKAGE##Linkage, \ llvm::GlobalValue::VISIBILITY##Visibility, \ llvm::GlobalValue::DLL_STORAGE##StorageClass} // Use protected visibility for public symbols we define on ELF. ld.so // doesn't support relative relocations at load time, which interferes with // our metadata formats. Default visibility should suffice for other object // formats. llvm::GlobalValue::VisibilityTypes PublicDefinitionVisibility = info.IsELFObject ? llvm::GlobalValue::ProtectedVisibility : llvm::GlobalValue::DefaultVisibility; llvm::GlobalValue::DLLStorageClassTypes ExportedStorage = info.UseDLLStorage ? llvm::GlobalValue::DLLExportStorageClass : llvm::GlobalValue::DefaultStorageClass; llvm::GlobalValue::DLLStorageClassTypes ImportedStorage = info.UseDLLStorage ? llvm::GlobalValue::DLLImportStorageClass : llvm::GlobalValue::DefaultStorageClass; switch (linkage) { case SILLinkage::Public: return {llvm::GlobalValue::ExternalLinkage, PublicDefinitionVisibility, ExportedStorage}; case SILLinkage::PublicNonABI: return isDefinition ? RESULT(WeakODR, Hidden, Default) : RESULT(External, Hidden, Default); case SILLinkage::Shared: case SILLinkage::SharedExternal: return isDefinition ? RESULT(LinkOnceODR, Hidden, Default) : RESULT(External, Hidden, Default); case SILLinkage::Hidden: return RESULT(External, Hidden, Default); case SILLinkage::Private: { if (info.forcePublicDecls() && !isDefinition) return getIRLinkage(info, SILLinkage::PublicExternal, isDefinition, isWeakImported, isKnownLocal); auto linkage = info.needLinkerToMergeDuplicateSymbols() ? llvm::GlobalValue::LinkOnceODRLinkage : llvm::GlobalValue::InternalLinkage; auto visibility = info.shouldAllPrivateDeclsBeVisibleFromOtherFiles() ? llvm::GlobalValue::HiddenVisibility : llvm::GlobalValue::DefaultVisibility; return {linkage, visibility, llvm::GlobalValue::DefaultStorageClass}; } case SILLinkage::PublicExternal: { if (isDefinition) return RESULT(AvailableExternally, Default, Default); auto linkage = isWeakImported ? llvm::GlobalValue::ExternalWeakLinkage : llvm::GlobalValue::ExternalLinkage; return {linkage, llvm::GlobalValue::DefaultVisibility, isKnownLocal ? llvm::GlobalValue::DefaultStorageClass : ImportedStorage}; } case SILLinkage::HiddenExternal: if (isDefinition) return RESULT(AvailableExternally, Hidden, Default); return {llvm::GlobalValue::ExternalLinkage, llvm::GlobalValue::DefaultVisibility, isKnownLocal ? llvm::GlobalValue::DefaultStorageClass : ImportedStorage}; } llvm_unreachable("bad SIL linkage"); } /// Given that we're going to define a global value but already have a /// forward-declaration of it, update its linkage. void irgen::updateLinkageForDefinition(IRGenModule &IGM, llvm::GlobalValue *global, const LinkEntity &entity) { // TODO: there are probably cases where we can avoid redoing the // entire linkage computation. UniversalLinkageInfo linkInfo(IGM); bool weakImported = entity.isWeakImported(IGM.getSwiftModule()); bool isKnownLocal = entity.isAlwaysSharedLinkage(); if (const auto *DC = entity.getDeclContextForEmission()) if (const auto *MD = DC->getParentModule()) isKnownLocal = IGM.getSwiftModule() == MD || MD->isStaticLibrary(); auto IRL = getIRLinkage(linkInfo, entity.getLinkage(ForDefinition), ForDefinition, weakImported, isKnownLocal); ApplyIRLinkage(IRL).to(global); LinkInfo link = LinkInfo::get(IGM, entity, ForDefinition); markGlobalAsUsedBasedOnLinkage(IGM, link, global); } LinkInfo LinkInfo::get(IRGenModule &IGM, const LinkEntity &entity, ForDefinition_t isDefinition) { return LinkInfo::get(UniversalLinkageInfo(IGM), IGM.getSwiftModule(), entity, isDefinition); } LinkInfo LinkInfo::get(const UniversalLinkageInfo &linkInfo, ModuleDecl *swiftModule, const LinkEntity &entity, ForDefinition_t isDefinition) { LinkInfo result; entity.mangle(result.Name); bool isKnownLocal = entity.isAlwaysSharedLinkage(); if (const auto *DC = entity.getDeclContextForEmission()) { if (const auto *MD = DC->getParentModule()) isKnownLocal = MD == swiftModule || MD->isStaticLibrary(); } else if (entity.hasSILFunction()) { // SIL serialized entitites (functions, witness tables, vtables) do not have // an associated DeclContext and are serialized into the current module. As // a result, we explicitly handle SIL Functions here. We do not expect other // types to be referenced directly. isKnownLocal = entity.getSILFunction()->isStaticallyLinked(); } bool weakImported = entity.isWeakImported(swiftModule); result.IRL = getIRLinkage(linkInfo, entity.getLinkage(isDefinition), isDefinition, weakImported, isKnownLocal); result.ForDefinition = isDefinition; return result; } LinkInfo LinkInfo::get(const UniversalLinkageInfo &linkInfo, StringRef name, SILLinkage linkage, ForDefinition_t isDefinition, bool isWeakImported) { LinkInfo result; // TODO(compnerd) handle this properly result.Name += name; result.IRL = getIRLinkage(linkInfo, linkage, isDefinition, isWeakImported); result.ForDefinition = isDefinition; return result; } static bool isPointerTo(llvm::Type *ptrTy, llvm::Type *objTy) { return cast<llvm::PointerType>(ptrTy)->getElementType() == objTy; } /// Get or create an LLVM function with these linkage rules. llvm::Function *irgen::createFunction(IRGenModule &IGM, LinkInfo &linkInfo, const Signature &signature, llvm::Function *insertBefore, OptimizationMode FuncOptMode) { auto name = linkInfo.getName(); llvm::Function *existing = IGM.Module.getFunction(name); if (existing) { if (isPointerTo(existing->getType(), signature.getType())) return cast<llvm::Function>(existing); IGM.error(SourceLoc(), "program too clever: function collides with existing symbol " + name); // Note that this will implicitly unique if the .unique name is also taken. existing->setName(name + ".unique"); } llvm::Function *fn = llvm::Function::Create(signature.getType(), linkInfo.getLinkage(), name); fn->setCallingConv(signature.getCallingConv()); if (insertBefore) { IGM.Module.getFunctionList().insert(insertBefore->getIterator(), fn); } else { IGM.Module.getFunctionList().push_back(fn); } ApplyIRLinkage({linkInfo.getLinkage(), linkInfo.getVisibility(), linkInfo.getDLLStorage()}) .to(fn, linkInfo.isForDefinition()); llvm::AttrBuilder initialAttrs; IGM.constructInitialFnAttributes(initialAttrs, FuncOptMode); // Merge initialAttrs with attrs. auto updatedAttrs = signature.getAttributes().addAttributes(IGM.getLLVMContext(), llvm::AttributeList::FunctionIndex, initialAttrs); if (!updatedAttrs.isEmpty()) fn->setAttributes(updatedAttrs); markGlobalAsUsedBasedOnLinkage(IGM, linkInfo, fn); return fn; } /// Get or create an LLVM global variable with these linkage rules. llvm::GlobalVariable *swift::irgen::createVariable( IRGenModule &IGM, LinkInfo &linkInfo, llvm::Type *storageType, Alignment alignment, DebugTypeInfo DbgTy, Optional<SILLocation> DebugLoc, StringRef DebugName, bool inFixedBuffer) { auto name = linkInfo.getName(); llvm::GlobalValue *existingValue = IGM.Module.getNamedGlobal(name); if (existingValue) { auto existingVar = dyn_cast<llvm::GlobalVariable>(existingValue); if (existingVar && isPointerTo(existingVar->getType(), storageType)) return existingVar; IGM.error(SourceLoc(), "program too clever: variable collides with existing symbol " + name); // Note that this will implicitly unique if the .unique name is also taken. existingValue->setName(name + ".unique"); } auto var = new llvm::GlobalVariable(IGM.Module, storageType, /*constant*/ false, linkInfo.getLinkage(), /*initializer*/ nullptr, name); ApplyIRLinkage({linkInfo.getLinkage(), linkInfo.getVisibility(), linkInfo.getDLLStorage()}) .to(var, linkInfo.isForDefinition()); var->setAlignment(llvm::MaybeAlign(alignment.getValue())); markGlobalAsUsedBasedOnLinkage(IGM, linkInfo, var); if (IGM.DebugInfo && !DbgTy.isNull() && linkInfo.isForDefinition()) IGM.DebugInfo->emitGlobalVariableDeclaration( var, DebugName.empty() ? name : DebugName, name, DbgTy, var->hasInternalLinkage(), inFixedBuffer, DebugLoc); return var; } llvm::GlobalVariable * swift::irgen::createLinkerDirectiveVariable(IRGenModule &IGM, StringRef name) { // A prefix of \1 can avoid further mangling of the symbol (prefixing _). llvm::SmallString<32> NameWithFlag; NameWithFlag.push_back('\1'); NameWithFlag.append(name); name = NameWithFlag.str(); static const uint8_t Size = 8; static const uint8_t Alignment = 8; // Use a char type as the type for this linker directive. auto ProperlySizedIntTy = SILType::getBuiltinIntegerType( Size, IGM.getSwiftModule()->getASTContext()); auto storageType = IGM.getStorageType(ProperlySizedIntTy); llvm::GlobalValue *existingValue = IGM.Module.getNamedGlobal(name); if (existingValue) { auto existingVar = dyn_cast<llvm::GlobalVariable>(existingValue); if (existingVar && isPointerTo(existingVar->getType(), storageType)) return existingVar; IGM.error(SourceLoc(), "program too clever: variable collides with existing symbol " + name); // Note that this will implicitly unique if the .unique name is also taken. existingValue->setName(name + ".unique"); } llvm::GlobalValue::LinkageTypes Linkage = llvm::GlobalValue::LinkageTypes::ExternalLinkage; auto var = new llvm::GlobalVariable(IGM.Module, storageType, /*constant*/true, Linkage, /*Init to zero*/llvm::Constant::getNullValue(storageType), name); ApplyIRLinkage({Linkage, llvm::GlobalValue::VisibilityTypes::DefaultVisibility, llvm::GlobalValue::DLLStorageClassTypes::DefaultStorageClass}).to(var); var->setAlignment(llvm::MaybeAlign(Alignment)); disableAddressSanitizer(IGM, var); IGM.addUsedGlobal(var); return var; } void swift::irgen::disableAddressSanitizer(IRGenModule &IGM, llvm::GlobalVariable *var) { // Add an operand to llvm.asan.globals denylisting this global variable. llvm::Metadata *metadata[] = { // The global variable to denylist. llvm::ConstantAsMetadata::get(var), // Source location. Optional, unnecessary here. nullptr, // Name. Optional, unnecessary here. nullptr, // Whether the global is dynamically initialized. llvm::ConstantAsMetadata::get(llvm::ConstantInt::get( llvm::Type::getInt1Ty(IGM.Module.getContext()), false)), // Whether the global is denylisted. llvm::ConstantAsMetadata::get(llvm::ConstantInt::get( llvm::Type::getInt1Ty(IGM.Module.getContext()), true))}; auto *globalNode = llvm::MDNode::get(IGM.Module.getContext(), metadata); auto *asanMetadata = IGM.Module.getOrInsertNamedMetadata("llvm.asan.globals"); asanMetadata->addOperand(globalNode); } /// Emit a global declaration. void IRGenModule::emitGlobalDecl(Decl *D) { switch (D->getKind()) { case DeclKind::Extension: return emitExtension(cast<ExtensionDecl>(D)); case DeclKind::Protocol: return emitProtocolDecl(cast<ProtocolDecl>(D)); case DeclKind::PatternBinding: // The global initializations are in SIL. return; case DeclKind::Param: llvm_unreachable("there are no global function parameters"); case DeclKind::Subscript: llvm_unreachable("there are no global subscript operations"); case DeclKind::EnumCase: case DeclKind::EnumElement: llvm_unreachable("there are no global enum elements"); case DeclKind::Constructor: llvm_unreachable("there are no global constructor"); case DeclKind::Destructor: llvm_unreachable("there are no global destructor"); case DeclKind::MissingMember: llvm_unreachable("there are no global member placeholders"); case DeclKind::TypeAlias: case DeclKind::GenericTypeParam: case DeclKind::AssociatedType: case DeclKind::IfConfig: case DeclKind::PoundDiagnostic: return; case DeclKind::Enum: return emitEnumDecl(cast<EnumDecl>(D)); case DeclKind::Struct: return emitStructDecl(cast<StructDecl>(D)); case DeclKind::Class: return emitClassDecl(cast<ClassDecl>(D)); // These declarations are only included in the debug info. case DeclKind::Import: if (DebugInfo) DebugInfo->emitImport(cast<ImportDecl>(D)); return; case DeclKind::Var: case DeclKind::Accessor: case DeclKind::Func: // Handled in SIL. return; case DeclKind::TopLevelCode: // All the top-level code will be lowered separately. return; // Operator decls aren't needed for IRGen. case DeclKind::InfixOperator: case DeclKind::PrefixOperator: case DeclKind::PostfixOperator: case DeclKind::PrecedenceGroup: return; case DeclKind::Module: return; case DeclKind::OpaqueType: // TODO: Eventually we'll need to emit descriptors to access the opaque // type's metadata. return; } llvm_unreachable("bad decl kind!"); } Address IRGenModule::getAddrOfSILGlobalVariable(SILGlobalVariable *var, const TypeInfo &ti, ForDefinition_t forDefinition) { if (auto clangDecl = var->getClangDecl()) { auto addr = getAddrOfClangGlobalDecl(cast<clang::VarDecl>(clangDecl), forDefinition); // If we're not emitting this to define it, make sure we cast it to the // right type. if (!forDefinition) { auto ptrTy = ti.getStorageType()->getPointerTo(); addr = llvm::ConstantExpr::getBitCast(addr, ptrTy); } auto alignment = Alignment(getClangASTContext().getDeclAlign(clangDecl).getQuantity()); return Address(addr, alignment); } LinkEntity entity = LinkEntity::forSILGlobalVariable(var); ResilienceExpansion expansion = getResilienceExpansionForLayout(var); llvm::Type *storageType; llvm::Type *castStorageToType = nullptr; Size fixedSize; Alignment fixedAlignment; bool inFixedBuffer = false; if (var->isInitializedObject()) { assert(ti.isFixedSize(expansion)); StructLayout *Layout = StaticObjectLayouts[var].get(); if (!Layout) { // Create the layout (includes the llvm type) for the statically // initialized object and store it for later. ObjectInst *OI = cast<ObjectInst>(var->getStaticInitializerValue()); llvm::SmallVector<SILType, 16> TailTypes; for (SILValue TailOp : OI->getTailElements()) { TailTypes.push_back(TailOp->getType()); } Layout = getClassLayoutWithTailElems(*this, var->getLoweredType(), TailTypes); StaticObjectLayouts[var] = std::unique_ptr<StructLayout>(Layout); } storageType = Layout->getType(); fixedSize = Layout->getSize(); fixedAlignment = Layout->getAlignment(); castStorageToType = cast<FixedTypeInfo>(ti).getStorageType(); assert(fixedAlignment >= TargetInfo.HeapObjectAlignment); } else if (ti.isFixedSize(expansion)) { // Allocate static storage. auto &fixedTI = cast<FixedTypeInfo>(ti); storageType = fixedTI.getStorageType(); fixedSize = fixedTI.getFixedSize(); fixedAlignment = fixedTI.getFixedAlignment(); } else { // Allocate a fixed-size buffer and possibly heap-allocate a payload at // runtime if the runtime size of the type does not fit in the buffer. inFixedBuffer = true; storageType = getFixedBufferTy(); fixedSize = Size(DataLayout.getTypeAllocSize(storageType)); fixedAlignment = getFixedBufferAlignment(*this); } // Check whether we've created the global variable already. // FIXME: We should integrate this into the LinkEntity cache more cleanly. auto gvar = Module.getGlobalVariable(var->getName(), /*allowInternal*/ true); if (gvar) { if (forDefinition) updateLinkageForDefinition(*this, gvar, entity); } else { LinkInfo link = LinkInfo::get(*this, entity, forDefinition); llvm::Type *storageTypeWithContainer = storageType; if (var->isInitializedObject()) { // A statically initialized object must be placed into a container struct // because the swift_initStaticObject needs a swift_once_t at offset -1: // struct Container { // swift_once_t token[fixedAlignment / sizeof(swift_once_t)]; // HeapObject object; // }; std::string typeName = storageType->getStructName().str() + 'c'; assert(fixedAlignment >= getPointerAlignment()); unsigned numTokens = fixedAlignment.getValue() / getPointerAlignment().getValue(); storageTypeWithContainer = llvm::StructType::create(getLLVMContext(), {llvm::ArrayType::get(OnceTy, numTokens), storageType}, typeName); gvar = createVariable(*this, link, storageTypeWithContainer, fixedAlignment); } else { StringRef name; Optional<SILLocation> loc; if (var->getDecl()) { // Use the VarDecl for more accurate debugging information. loc = var->getDecl(); name = var->getDecl()->getName().str(); } else { if (var->hasLocation()) loc = var->getLocation(); name = var->getName(); } auto DbgTy = DebugTypeInfo::getGlobal(var, storageTypeWithContainer, fixedSize, fixedAlignment); gvar = createVariable(*this, link, storageTypeWithContainer, fixedAlignment, DbgTy, loc, name, inFixedBuffer); } /// Add a zero initializer. if (forDefinition) gvar->setInitializer(llvm::Constant::getNullValue(storageTypeWithContainer)); else gvar->setComdat(nullptr); } llvm::Constant *addr = gvar; if (var->isInitializedObject()) { // Project out the object from the container. llvm::Constant *Indices[2] = { llvm::ConstantExpr::getIntegerValue(Int32Ty, APInt(32, 0)), llvm::ConstantExpr::getIntegerValue(Int32Ty, APInt(32, 1)) }; // Return the address of the initialized object itself (and not the address // to a reference to it). addr = llvm::ConstantExpr::getGetElementPtr( gvar->getType()->getPointerElementType(), gvar, Indices); } addr = llvm::ConstantExpr::getBitCast( addr, castStorageToType ? castStorageToType : storageType->getPointerTo()); return Address(addr, Alignment(gvar->getAlignment())); } /// Return True if the function \p f is a 'readonly' function. Checking /// for the SIL @_effects(readonly) attribute is not enough because this /// definition does not match the definition of the LLVM readonly function /// attribute. In this function we do the actual check. static bool isReadOnlyFunction(SILFunction *f) { // Check if the function has any 'owned' parameters. Owned parameters may // call the destructor of the object which could violate the readonly-ness // of the function. if (f->hasOwnedParameters() || f->hasIndirectFormalResults()) return false; auto Eff = f->getEffectsKind(); // Swift's readonly does not automatically match LLVM's readonly. // Swift SIL optimizer relies on @_effects(readonly) to remove e.g. // dead code remaining from initializers of strings or dictionaries // of variables that are not used. But those initializers are often // not really readonly in terms of LLVM IR. For example, the // Dictionary.init() is marked as @_effects(readonly) in Swift, but // it does invoke reference-counting operations. if (Eff == EffectsKind::ReadOnly || Eff == EffectsKind::ReadNone) { // TODO: Analyze the body of function f and return true if it is // really readonly. return false; } return false; } static clang::GlobalDecl getClangGlobalDeclForFunction(const clang::Decl *decl) { if (auto ctor = dyn_cast<clang::CXXConstructorDecl>(decl)) return clang::GlobalDecl(ctor, clang::Ctor_Complete); if (auto dtor = dyn_cast<clang::CXXDestructorDecl>(decl)) return clang::GlobalDecl(dtor, clang::Dtor_Complete); return clang::GlobalDecl(cast<clang::FunctionDecl>(decl)); } static void addLLVMFunctionAttributes(SILFunction *f, Signature &signature) { auto &attrs = signature.getMutableAttributes(); switch (f->getInlineStrategy()) { case NoInline: attrs = attrs.addAttribute(signature.getType()->getContext(), llvm::AttributeList::FunctionIndex, llvm::Attribute::NoInline); break; case AlwaysInline: // FIXME: We do not currently transfer AlwaysInline since doing so results // in test failures, which must be investigated first. case InlineDefault: break; } if (isReadOnlyFunction(f)) { attrs = attrs.addAttribute(signature.getType()->getContext(), llvm::AttributeList::FunctionIndex, llvm::Attribute::ReadOnly); } } /// Create a key entry for a dynamic function replacement. A key entry refers to /// the link entry for the dynamic replaceable function. /// struct KeyEntry { /// RelativeDirectPointer<LinkEntry> linkEntry; /// int32_t flags; /// } static llvm::GlobalVariable *createGlobalForDynamicReplacementFunctionKey( IRGenModule &IGM, LinkEntity keyEntity, llvm::GlobalVariable *linkEntry) { auto key = IGM.getGlobalForDynamicallyReplaceableThunk( keyEntity, IGM.DynamicReplacementKeyTy, ForDefinition); ConstantInitBuilder builder(IGM); auto B = builder.beginStruct(IGM.DynamicReplacementKeyTy); B.addRelativeAddress(linkEntry); bool isAsyncFunction = keyEntity.hasSILFunction() && keyEntity.getSILFunction()->isAsync(); auto schema = isAsyncFunction ? IGM.getOptions().PointerAuth.AsyncSwiftDynamicReplacements : IGM.getOptions().PointerAuth.SwiftDynamicReplacements; if (schema) { assert(keyEntity.hasSILFunction() || keyEntity.isOpaqueTypeDescriptorAccessor()); auto authEntity = keyEntity.hasSILFunction() ? PointerAuthEntity(keyEntity.getSILFunction()) : PointerAuthEntity::Special::TypeDescriptor; B.addInt32((uint32_t)PointerAuthInfo::getOtherDiscriminator(IGM, schema, authEntity) ->getZExtValue() | ((uint32_t)isAsyncFunction ? 0x10000 : 0x0)); } else B.addInt32(0); B.finishAndSetAsInitializer(key); key->setConstant(true); IGM.setTrueConstGlobal(key); return key; } /// Creates the prolog for a dynamically replaceable function. /// It checks if the replaced function or the original function should be called /// (by calling the swift_getFunctionReplacement runtime function). In case of /// the original function, it just jumps to the "real" code of the function, /// otherwise it tail calls the replacement. void IRGenModule::createReplaceableProlog(IRGenFunction &IGF, SILFunction *f) { LinkEntity varEntity = LinkEntity::forDynamicallyReplaceableFunctionVariable(f); LinkEntity keyEntity = LinkEntity::forDynamicallyReplaceableFunctionKey(f); auto silFunctionType = f->getLoweredFunctionType(); Signature signature = getSignature(silFunctionType); // Create and initialize the first link entry for the chain of replacements. // The first implementation is initialized with 'implFn'. auto *funPtr = f->isAsync() ? IGF.IGM.getAddrOfAsyncFunctionPointer(LinkEntity::forSILFunction(f)) : IGF.CurFn; auto linkEntry = getChainEntryForDynamicReplacement(*this, varEntity, funPtr); // Create the key data structure. This is used from other modules to refer to // the chain of replacements. createGlobalForDynamicReplacementFunctionKey(*this, keyEntity, linkEntry); llvm::Constant *indices[] = {llvm::ConstantInt::get(Int32Ty, 0), llvm::ConstantInt::get(Int32Ty, 0)}; auto *fnPtrAddr = llvm::ConstantExpr::getInBoundsGetElementPtr( linkEntry->getType()->getPointerElementType(), linkEntry, indices); auto *ReplAddr = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(fnPtrAddr, FunctionPtrTy->getPointerTo()); auto *FnAddr = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast( funPtr, FunctionPtrTy); auto &schema = f->isAsync() ? getOptions().PointerAuth.AsyncSwiftDynamicReplacements : getOptions().PointerAuth.SwiftDynamicReplacements; llvm::Value *ReplFn = nullptr, *hasReplFn = nullptr; if (UseBasicDynamicReplacement) { ReplFn = IGF.Builder.CreateLoad(fnPtrAddr, getPointerAlignment()); llvm::Value *lhs = ReplFn; if (schema.isEnabled()) { lhs = emitPointerAuthStrip(IGF, lhs, schema.getKey()); } hasReplFn = IGF.Builder.CreateICmpEQ(lhs, FnAddr); } else { // Call swift_getFunctionReplacement to check which function to call. auto *callRTFunc = IGF.Builder.CreateCall(getGetReplacementFn(), {ReplAddr, FnAddr}); callRTFunc->setDoesNotThrow(); ReplFn = callRTFunc; hasReplFn = IGF.Builder.CreateICmpEQ(ReplFn, llvm::ConstantExpr::getNullValue(ReplFn->getType())); } auto *replacedBB = IGF.createBasicBlock("forward_to_replaced"); auto *origEntryBB = IGF.createBasicBlock("original_entry"); IGF.Builder.CreateCondBr(hasReplFn, origEntryBB, replacedBB); IGF.Builder.emitBlock(replacedBB); if (f->isAsync()) { auto &IGM = IGF.IGM; auto &Builder = IGF.Builder; PrologueLocation AutoRestore(IGM.DebugInfo.get(), Builder); auto authEntity = PointerAuthEntity(f); auto authInfo = PointerAuthInfo::emit(IGF, schema, fnPtrAddr, authEntity); auto *fnType = signature.getType()->getPointerTo(); auto *realReplFn = Builder.CreateBitCast(ReplFn, fnType); auto asyncFnPtr = FunctionPointer(silFunctionType, realReplFn, authInfo, signature); PointerAuthInfo codeAuthInfo = asyncFnPtr.getAuthInfo().getCorrespondingCodeAuthInfo(); auto newFnPtr = FunctionPointer( FunctionPointer::Kind::Function, asyncFnPtr.getPointer(IGF), codeAuthInfo, Signature::forAsyncAwait(IGM, silFunctionType, /*useSpecialConvention*/ false)); SmallVector<llvm::Value *, 16> forwardedArgs; for (auto &arg : IGF.CurFn->args()) forwardedArgs.push_back(&arg); auto layout = getAsyncContextLayout( IGM, silFunctionType, silFunctionType, f->getForwardingSubstitutionMap(), false, FunctionPointer::Kind( FunctionPointer::BasicKind::AsyncFunctionPointer)); llvm::Value *dynamicContextSize32; llvm::Value *calleeFunction; auto initialContextSize = Size(0); std::tie(calleeFunction, dynamicContextSize32) = getAsyncFunctionAndSize( IGF, silFunctionType->getRepresentation(), asyncFnPtr, nullptr, std::make_pair(false, true), initialContextSize); auto *dynamicContextSize = Builder.CreateZExt(dynamicContextSize32, IGM.SizeTy); auto calleeContextBuffer = emitAllocAsyncContext(IGF, dynamicContextSize); auto calleeContext = layout.emitCastTo(IGF, calleeContextBuffer.getAddress()); auto saveValue = [&](ElementLayout layout, Explosion &explosion) -> void { Address addr = layout.project(IGF, calleeContext, /*offsets*/ llvm::None); auto &ti = cast<LoadableTypeInfo>(layout.getType()); ti.initialize(IGF, explosion, addr, /*isOutlined*/ false); }; // Set caller info into the context. { // caller context Explosion explosion; auto fieldLayout = layout.getParentLayout(); auto *context = IGF.getAsyncContext(); if (auto schema = IGM.getOptions().PointerAuth.AsyncContextParent) { Address fieldAddr = fieldLayout.project(IGF, calleeContext, /*offsets*/ llvm::None); auto authInfo = PointerAuthInfo::emit( IGF, schema, fieldAddr.getAddress(), PointerAuthEntity()); context = emitPointerAuthSign(IGF, context, authInfo); } explosion.add(context); saveValue(fieldLayout, explosion); } auto currentResumeFn = Builder.CreateIntrinsicCall(llvm::Intrinsic::coro_async_resume, {}); { // Return to caller function. auto fieldLayout = layout.getResumeParentLayout(); llvm::Value *fnVal = currentResumeFn; // Sign the pointer. if (auto schema = IGM.getOptions().PointerAuth.AsyncContextResume) { Address fieldAddr = fieldLayout.project(IGF, calleeContext, /*offsets*/ llvm::None); auto authInfo = PointerAuthInfo::emit( IGF, schema, fieldAddr.getAddress(), PointerAuthEntity()); fnVal = emitPointerAuthSign(IGF, fnVal, authInfo); } fnVal = Builder.CreateBitCast(fnVal, IGM.TaskContinuationFunctionPtrTy); Explosion explosion; explosion.add(fnVal); saveValue(fieldLayout, explosion); } // Setup the suspend point. SmallVector<llvm::Value *, 8> arguments; auto signature = newFnPtr.getSignature(); auto asyncContextIndex = signature.getAsyncContextIndex(); auto paramAttributeFlags = asyncContextIndex | (signature.getAsyncResumeFunctionSwiftSelfIndex() << 8); // Index of swiftasync context | ((index of swiftself) << 8). arguments.push_back(IGM.getInt32(paramAttributeFlags)); arguments.push_back(currentResumeFn); auto resumeProjFn = IGF.getOrCreateResumePrjFn(true /*forProlog*/); arguments.push_back( Builder.CreateBitOrPointerCast(resumeProjFn, IGM.Int8PtrTy)); auto dispatchFn = IGF.createAsyncDispatchFn( getFunctionPointerForDispatchCall(IGM, newFnPtr), forwardedArgs); arguments.push_back( Builder.CreateBitOrPointerCast(dispatchFn, IGM.Int8PtrTy)); arguments.push_back(Builder.CreateBitOrPointerCast(newFnPtr.getRawPointer(), IGM.Int8PtrTy)); if (auto authInfo = newFnPtr.getAuthInfo()) { arguments.push_back(newFnPtr.getAuthInfo().getDiscriminator()); } unsigned argIdx = 0; for (auto arg : forwardedArgs) { // Replace the context argument. if (argIdx == asyncContextIndex) arguments.push_back(Builder.CreateBitOrPointerCast( calleeContextBuffer.getAddress(), IGM.SwiftContextPtrTy)); else arguments.push_back(arg); argIdx++; } auto resultTy = cast<llvm::StructType>(signature.getType()->getReturnType()); auto suspend = IGF.emitSuspendAsyncCall( asyncContextIndex, resultTy, arguments, false /*restore context*/); { // Restore the context. llvm::Value *calleeContext = Builder.CreateExtractValue(suspend, asyncContextIndex); auto context = IGF.emitAsyncResumeProjectContext(calleeContext); IGF.storeCurrentAsyncContext(context); } emitDeallocAsyncContext(IGF, calleeContextBuffer); forwardAsyncCallResult(IGF, silFunctionType, layout, suspend); } else { // Call the replacement function. SmallVector<llvm::Value *, 16> forwardedArgs; for (auto &arg : IGF.CurFn->args()) forwardedArgs.push_back(&arg); auto *fnType = signature.getType()->getPointerTo(); auto *realReplFn = IGF.Builder.CreateBitCast(ReplFn, fnType); auto authEntity = PointerAuthEntity(f); auto authInfo = PointerAuthInfo::emit(IGF, schema, fnPtrAddr, authEntity); auto *Res = IGF.Builder.CreateCall( FunctionPointer(silFunctionType, realReplFn, authInfo, signature) .getAsFunction(IGF), forwardedArgs); if (Res->getCallingConv() == llvm::CallingConv::SwiftTail && Res->getCaller()->getCallingConv() == llvm::CallingConv::SwiftTail) { Res->setTailCallKind(IGF.IGM.AsyncTailCallKind); } else { Res->setTailCall(); } if (IGF.CurFn->getReturnType()->isVoidTy()) IGF.Builder.CreateRetVoid(); else IGF.Builder.CreateRet(Res); } IGF.Builder.emitBlock(origEntryBB); } /// Emit the thunk that dispatches to the dynamically replaceable function. static void emitDynamicallyReplaceableThunk(IRGenModule &IGM, LinkEntity varEntity, LinkEntity keyEntity, llvm::Function *dispatchFn, llvm::Function *implFn, Signature &signature) { // Create and initialize the first link entry for the chain of replacements. // The first implementation is initialized with 'implFn'. auto linkEntry = getChainEntryForDynamicReplacement(IGM, varEntity, implFn); // Create the key data structure. This is used from other modules to refer to // the chain of replacements. createGlobalForDynamicReplacementFunctionKey(IGM, keyEntity, linkEntry); // We should never inline the implementation function. implFn->addFnAttr(llvm::Attribute::NoInline); // Load the function and dispatch to it forwarding our arguments. IRGenFunction IGF(IGM, dispatchFn); if (IGM.DebugInfo) IGM.DebugInfo->emitArtificialFunction(IGF, dispatchFn); llvm::Constant *indices[] = {llvm::ConstantInt::get(IGM.Int32Ty, 0), llvm::ConstantInt::get(IGM.Int32Ty, 0)}; auto *fnPtrAddr = llvm::ConstantExpr::getInBoundsGetElementPtr( linkEntry->getType()->getPointerElementType(), linkEntry, indices); auto *fnPtr = IGF.Builder.CreateLoad(fnPtrAddr, IGM.getPointerAlignment()); auto *typeFnPtr = IGF.Builder.CreateBitOrPointerCast(fnPtr, implFn->getType()); SmallVector<llvm::Value *, 16> forwardedArgs; for (auto &arg : dispatchFn->args()) forwardedArgs.push_back(&arg); bool isAsyncFunction = keyEntity.hasSILFunction() && keyEntity.getSILFunction()->isAsync(); auto &schema = isAsyncFunction ? IGM.getOptions().PointerAuth.AsyncSwiftDynamicReplacements : IGM.getOptions().PointerAuth.SwiftDynamicReplacements; assert(keyEntity.hasSILFunction() || keyEntity.isOpaqueTypeDescriptorAccessor()); auto authEntity = keyEntity.hasSILFunction() ? PointerAuthEntity(keyEntity.getSILFunction()) : PointerAuthEntity::Special::TypeDescriptor; auto authInfo = PointerAuthInfo::emit(IGF, schema, fnPtrAddr, authEntity); auto *Res = IGF.Builder.CreateCall(FunctionPointer(FunctionPointer::Kind::Function, typeFnPtr, authInfo, signature), forwardedArgs); Res->setTailCall(); if (implFn->getReturnType()->isVoidTy()) IGF.Builder.CreateRetVoid(); else IGF.Builder.CreateRet(Res); } void IRGenModule::emitOpaqueTypeDescriptorAccessor(OpaqueTypeDecl *opaque) { auto *namingDecl = opaque->getNamingDecl(); auto *abstractStorage = dyn_cast<AbstractStorageDecl>(namingDecl); bool isNativeDynamic = false; const bool isDynamicReplacement = namingDecl->getDynamicallyReplacedDecl(); // Don't emit accessors for abstract storage that is not dynamic or a dynamic // replacement. if (abstractStorage) { isNativeDynamic = abstractStorage->hasAnyNativeDynamicAccessors(); if (!isNativeDynamic && !isDynamicReplacement) return; } // Don't emit accessors for functions that are not dynamic or dynamic // replacements. if (!abstractStorage) { isNativeDynamic = namingDecl->shouldUseNativeDynamicDispatch(); if (!isNativeDynamic && !isDynamicReplacement) return; } auto accessor = getAddrOfOpaqueTypeDescriptorAccessFunction(opaque, ForDefinition, false); if (isNativeDynamic) { auto thunk = accessor; auto impl = getAddrOfOpaqueTypeDescriptorAccessFunction( opaque, ForDefinition, true); auto varEntity = LinkEntity::forOpaqueTypeDescriptorAccessorVar(opaque); auto keyEntity = LinkEntity::forOpaqueTypeDescriptorAccessorKey(opaque); auto fnType = llvm::FunctionType::get(OpaqueTypeDescriptorPtrTy, {}, false); Signature signature(fnType, llvm::AttributeList(), SwiftCC); emitDynamicallyReplaceableThunk(*this, varEntity, keyEntity, thunk, impl, signature); // We should never inline the thunk function. thunk->addFnAttr(llvm::Attribute::NoInline); accessor = impl; } // The implementation just returns the opaque type descriptor. llvm::BasicBlock *entryBB = llvm::BasicBlock::Create(getLLVMContext(), "entry", accessor); IRBuilder B(getLLVMContext(), false); B.SetInsertPoint(entryBB); if (DebugInfo) DebugInfo->emitArtificialFunction(B, accessor); auto *desc = getAddrOfOpaqueTypeDescriptor(opaque, ConstantInit()); B.CreateRet(desc); } /// Calls the previous implementation before this dynamic replacement became /// active. void IRGenModule::emitDynamicReplacementOriginalFunctionThunk(SILFunction *f) { assert(f->getDynamicallyReplacedFunction()); if (UseBasicDynamicReplacement) return; auto entity = LinkEntity::forSILFunction(f, true); auto fnType = f->getLoweredFunctionType(); Signature signature = getSignature(fnType); addLLVMFunctionAttributes(f, signature); LinkInfo implLink = LinkInfo::get(*this, entity, ForDefinition); auto implFn = createFunction(*this, implLink, signature, nullptr /*insertBefore*/, f->getOptimizationMode()); implFn->addFnAttr(llvm::Attribute::NoInline); IRGenFunction IGF(*this, implFn); if (DebugInfo) DebugInfo->emitArtificialFunction(IGF, implFn); LinkEntity varEntity = LinkEntity::forDynamicallyReplaceableFunctionVariable(f); auto linkEntry = getChainEntryForDynamicReplacement(*this, varEntity, nullptr, NotForDefinition); // Load the function and dispatch to it forwarding our arguments. llvm::Constant *indices[] = {llvm::ConstantInt::get(Int32Ty, 0), llvm::ConstantInt::get(Int32Ty, 0)}; auto *fnPtrAddr = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast( llvm::ConstantExpr::getInBoundsGetElementPtr( linkEntry->getType()->getPointerElementType(), linkEntry, indices), FunctionPtrTy->getPointerTo()); auto *OrigFn = IGF.Builder.CreateCall(getGetOrigOfReplaceableFn(), {fnPtrAddr}); OrigFn->setDoesNotThrow(); auto *typeFnPtr = IGF.Builder.CreateBitOrPointerCast(OrigFn, implFn->getType()); SmallVector<llvm::Value *, 16> forwardedArgs; for (auto &arg : implFn->args()) forwardedArgs.push_back(&arg); auto &schema = f->isAsync() ? getOptions().PointerAuth.AsyncSwiftDynamicReplacements : getOptions().PointerAuth.SwiftDynamicReplacements; auto authInfo = PointerAuthInfo::emit( IGF, schema, fnPtrAddr, PointerAuthEntity(f->getDynamicallyReplacedFunction())); auto *Res = IGF.Builder.CreateCall( FunctionPointer(fnType, typeFnPtr, authInfo, signature) .getAsFunction(IGF), forwardedArgs); Res->setTailCall(); if (f->isAsync()) { Res->setTailCallKind(IGF.IGM.AsyncTailCallKind); } if (implFn->getReturnType()->isVoidTy()) IGF.Builder.CreateRetVoid(); else IGF.Builder.CreateRet(Res); } llvm::Constant *swift::irgen::emitCXXConstructorThunkIfNeeded( IRGenModule &IGM, Signature signature, const clang::CXXConstructorDecl *ctor, StringRef name, llvm::Constant *ctorAddress) { llvm::FunctionType *assumedFnType = signature.getType(); llvm::FunctionType *ctorFnType = cast<llvm::FunctionType>(ctorAddress->getType()->getPointerElementType()); if (assumedFnType == ctorFnType) { return ctorAddress; } llvm::Function *thunk = llvm::Function::Create( assumedFnType, llvm::Function::PrivateLinkage, name, &IGM.Module); thunk->setCallingConv(llvm::CallingConv::C); llvm::AttrBuilder attrBuilder; IGM.constructInitialFnAttributes(attrBuilder); attrBuilder.addAttribute(llvm::Attribute::AlwaysInline); llvm::AttributeList attr = signature.getAttributes().addAttributes( IGM.getLLVMContext(), llvm::AttributeList::FunctionIndex, attrBuilder); thunk->setAttributes(attr); IRGenFunction subIGF(IGM, thunk); if (IGM.DebugInfo) IGM.DebugInfo->emitArtificialFunction(subIGF, thunk); SmallVector<llvm::Value *, 8> Args; for (auto i = thunk->arg_begin(), e = thunk->arg_end(); i != e; ++i) { auto *argTy = i->getType(); auto *paramTy = ctorFnType->getParamType(i - thunk->arg_begin()); if (paramTy != argTy) Args.push_back(subIGF.coerceValue(i, paramTy, IGM.DataLayout)); else Args.push_back(i); } clang::CodeGen::ImplicitCXXConstructorArgs implicitArgs = clang::CodeGen::getImplicitCXXConstructorArgs(IGM.ClangCodeGen->CGM(), ctor); for (size_t i = 0; i < implicitArgs.Prefix.size(); ++i) { Args.insert(Args.begin() + 1 + i, implicitArgs.Prefix[i]); } for (const auto &arg : implicitArgs.Suffix) { Args.push_back(arg); } subIGF.Builder.CreateCall(ctorFnType, ctorAddress, Args); subIGF.Builder.CreateRetVoid(); return thunk; } /// Find the entry point for a SIL function. llvm::Function *IRGenModule::getAddrOfSILFunction( SILFunction *f, ForDefinition_t forDefinition, bool isDynamicallyReplaceableImplementation, bool shouldCallPreviousImplementation) { assert(forDefinition || !isDynamicallyReplaceableImplementation); assert(!forDefinition || !shouldCallPreviousImplementation); LinkEntity entity = LinkEntity::forSILFunction(f, shouldCallPreviousImplementation); // Check whether we've created the function already. // FIXME: We should integrate this into the LinkEntity cache more cleanly. llvm::Function *fn = Module.getFunction(entity.mangleAsString()); if (fn) { if (forDefinition) { updateLinkageForDefinition(*this, fn, entity); } return fn; } // If it's a Clang declaration, ask Clang to generate the IR declaration. // This might generate new functions, so we should do it before computing // the insert-before point. llvm::Constant *clangAddr = nullptr; if (auto clangDecl = f->getClangDecl()) { // If we have an Objective-C Clang declaration, it must be a direct // method and we want to generate the IR declaration ourselves. if (auto objcDecl = dyn_cast<clang::ObjCMethodDecl>(clangDecl)) { assert(objcDecl->isDirectMethod()); } else { auto globalDecl = getClangGlobalDeclForFunction(clangDecl); clangAddr = getAddrOfClangGlobalDecl(globalDecl, forDefinition); } if (auto ctor = dyn_cast<clang::CXXConstructorDecl>(clangDecl)) { Signature signature = getSignature(f->getLoweredFunctionType()); // The thunk has private linkage, so it doesn't need to have a predictable // mangled name -- we just need to make sure the name is unique. llvm::SmallString<32> name; llvm::raw_svector_ostream stream(name); stream << "__swift_cxx_ctor"; entity.mangle(stream); clangAddr = emitCXXConstructorThunkIfNeeded(*this, signature, ctor, name, clangAddr); } } bool isDefinition = f->isDefinition(); bool hasOrderNumber = isDefinition && !shouldCallPreviousImplementation; unsigned orderNumber = ~0U; llvm::Function *insertBefore = nullptr; // If the SIL function has a definition, we should have an order // number for it; make sure to insert it in that position relative // to other ordered functions. if (hasOrderNumber) { orderNumber = IRGen.getFunctionOrder(f); if (auto emittedFunctionIterator = EmittedFunctionsByOrder.findLeastUpperBound(orderNumber)) insertBefore = *emittedFunctionIterator; } // If it's a Clang declaration, check whether Clang gave us a declaration. if (clangAddr) { fn = dyn_cast<llvm::Function>(clangAddr->stripPointerCasts()); // If we have a function, move it to the appropriate position. if (fn) { if (hasOrderNumber) { auto &fnList = Module.getFunctionList(); fnList.remove(fn); fnList.insert(llvm::Module::iterator(insertBefore), fn); EmittedFunctionsByOrder.insert(orderNumber, fn); } return fn; } // Otherwise, if we have a lazy definition for it, be sure to queue that up. } else if (isDefinition && !forDefinition && isLazilyEmittedFunction(*f, getSILModule())) { IRGen.addLazyFunction(f); } auto fpKind = irgen::classifyFunctionPointerKind(f); Signature signature = getSignature(f->getLoweredFunctionType(), fpKind.useSpecialConvention()); addLLVMFunctionAttributes(f, signature); LinkInfo link = LinkInfo::get(*this, entity, forDefinition); fn = createFunction(*this, link, signature, insertBefore, f->getOptimizationMode()); // If `hasCReferences` is true, then the function is either marked with // @_silgen_name OR @_cdecl. If it is the latter, it must have a definition // associated with it. The combination of the two allows us to identify the // @_silgen_name functions. These are locally defined function thunks used in // the standard library. Do not give them DLLImport DLL Storage. if (!forDefinition) { fn->setComdat(nullptr); if (f->hasCReferences()) fn->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass); } // If we have an order number for this function, set it up as appropriate. if (hasOrderNumber) { EmittedFunctionsByOrder.insert(orderNumber, fn); } return fn; } static llvm::GlobalVariable *createGOTEquivalent(IRGenModule &IGM, llvm::Constant *global, LinkEntity entity) { // Determine the name of this entity. llvm::SmallString<64> globalName; entity.mangle(globalName); if (IGM.Triple.getObjectFormat() == llvm::Triple::COFF) { if (cast<llvm::GlobalValue>(global)->hasDLLImportStorageClass()) { // Add the user label prefix *prior* to the introduction of the linker // synthetic marker `__imp_`. // Failure to do so will re-decorate the generated symbol and miss the // user label prefix, generating e.g. `___imp_$sBoW` instead of // `__imp__$sBoW`. if (auto prefix = IGM.DataLayout.getGlobalPrefix()) globalName = (llvm::Twine(prefix) + globalName).str(); // Indicate to LLVM that the symbol should not be re-decorated. llvm::GlobalVariable *GV = new llvm::GlobalVariable(IGM.Module, global->getType(), /*Constant=*/true, llvm::GlobalValue::ExternalLinkage, nullptr, "\01__imp_" + globalName); GV->setExternallyInitialized(true); return GV; } } auto gotEquivalent = new llvm::GlobalVariable(IGM.Module, global->getType(), /*constant*/ true, llvm::GlobalValue::PrivateLinkage, global, llvm::Twine("got.") + globalName); // rdar://problem/53836960: i386 ld64 also mis-links relative references // to GOT entries. // rdar://problem/59782487: issue with on-device JITd expressions. // The JIT gets confused by private vars accessed accross object files. if (!IGM.getOptions().UseJIT && (!IGM.Triple.isOSDarwin() || IGM.Triple.getArch() != llvm::Triple::x86)) { gotEquivalent->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); } else { ApplyIRLinkage(IRLinkage::InternalLinkOnceODR) .to(gotEquivalent); } // Context descriptor pointers need to be signed. // TODO: We should really sign a pointer to *any* code entity or true-const // metadata structure that may reference data structures with function // pointers inside them. if (entity.isContextDescriptor()) { auto schema = IGM.getOptions().PointerAuth.TypeDescriptors; if (schema) { auto signedValue = IGM.getConstantSignedPointer( global, schema, PointerAuthEntity::Special::TypeDescriptor, /*storageAddress*/ gotEquivalent); gotEquivalent->setInitializer(signedValue); } } else if (entity.isDynamicallyReplaceableKey()) { auto schema = IGM.getOptions().PointerAuth.SwiftDynamicReplacementKeys; if (schema) { auto signedValue = IGM.getConstantSignedPointer( global, schema, PointerAuthEntity::Special::DynamicReplacementKey, /*storageAddress*/ gotEquivalent); gotEquivalent->setInitializer(signedValue); } } return gotEquivalent; } llvm::Constant *IRGenModule::getOrCreateGOTEquivalent(llvm::Constant *global, LinkEntity entity) { auto &gotEntry = GlobalGOTEquivalents[entity]; if (gotEntry) { return gotEntry; } if (auto *Stats = Context.Stats) ++Stats->getFrontendCounters().NumGOTEntries; // Use the global as the initializer for an anonymous constant. LLVM can treat // this as equivalent to the global's GOT entry. auto gotEquivalent = createGOTEquivalent(*this, global, entity); gotEntry = gotEquivalent; return gotEquivalent; } static llvm::Constant *getElementBitCast(llvm::Constant *ptr, llvm::Type *newEltType) { auto ptrType = cast<llvm::PointerType>(ptr->getType()); if (ptrType->getElementType() == newEltType) { return ptr; } else { auto newPtrType = newEltType->getPointerTo(ptrType->getAddressSpace()); return llvm::ConstantExpr::getBitCast(ptr, newPtrType); } } /// Return a reference to an object that's suitable for being used for /// the given kind of reference. /// /// Note that, if the requested reference kind is a relative reference. /// the returned constant will not actually be a relative reference. /// To form the actual relative reference, you must pass the returned /// result to emitRelativeReference, passing the correct base-address /// information. ConstantReference IRGenModule::getAddrOfLLVMVariable(LinkEntity entity, ConstantInit definition, DebugTypeInfo debugType, SymbolReferenceKind refKind, llvm::Type *overrideDeclType) { switch (refKind) { case SymbolReferenceKind::Relative_Direct: case SymbolReferenceKind::Far_Relative_Direct: assert(!definition); // FIXME: don't just fall through; force the creation of a weak // definition so that we can emit a relative reference. LLVM_FALLTHROUGH; case SymbolReferenceKind::Absolute: return { getAddrOfLLVMVariable(entity, definition, debugType, overrideDeclType), ConstantReference::Direct }; case SymbolReferenceKind::Relative_Indirectable: case SymbolReferenceKind::Far_Relative_Indirectable: assert(!definition); return getAddrOfLLVMVariableOrGOTEquivalent(entity); } llvm_unreachable("bad reference kind"); } /// A convenient wrapper around getAddrOfLLVMVariable which uses the /// default type as the definition type. llvm::Constant * IRGenModule::getAddrOfLLVMVariable(LinkEntity entity, ForDefinition_t forDefinition, DebugTypeInfo debugType) { auto definition = forDefinition ? ConstantInit::getDelayed(entity.getDefaultDeclarationType(*this)) : ConstantInit(); return getAddrOfLLVMVariable(entity, definition, debugType); } /// Get or create an llvm::GlobalVariable. /// /// If a definition type is given, the result will always be an /// llvm::GlobalVariable of that type. Otherwise, the result will /// have type pointerToDefaultType and may involve bitcasts. llvm::Constant * IRGenModule::getAddrOfLLVMVariable(LinkEntity entity, ConstantInit definition, DebugTypeInfo DbgTy, llvm::Type *overrideDeclType) { // This function assumes that 'globals' only contains GlobalValue // values for the entities that it will look up. llvm::Type *definitionType = (definition ? definition.getType() : nullptr); auto defaultType = overrideDeclType ? overrideDeclType : entity.getDefaultDeclarationType(*this); auto &entry = GlobalVars[entity]; if (entry) { auto existing = cast<llvm::GlobalValue>(entry); // If we're looking to define something, we may need to replace a // forward declaration. if (definitionType) { assert(existing->isDeclaration() && "already defined"); updateLinkageForDefinition(*this, existing, entity); // If the existing entry is a variable of the right type, // set the initializer on it and return. if (auto var = dyn_cast<llvm::GlobalVariable>(existing)) { if (definitionType == var->getValueType()) { if (definition.hasInit()) definition.getInit().installInGlobal(var); return var; } } // Fall out to the case below, clearing the name so that // createVariable doesn't detect a collision. entry->setName(""); // Otherwise, we have a previous declaration or definition which // we need to ensure has the right type. } else { return getElementBitCast(entry, defaultType); } } ForDefinition_t forDefinition = (ForDefinition_t) (definitionType != nullptr); LinkInfo link = LinkInfo::get(*this, entity, forDefinition); // Clang may have defined the variable already. if (auto existing = Module.getNamedGlobal(link.getName())) return getElementBitCast(existing, defaultType); // If we're not defining the object now, forward declare it with the default // type. if (!definitionType) definitionType = defaultType; // Create the variable. auto var = createVariable(*this, link, definitionType, entity.getAlignment(*this), DbgTy); // Install the concrete definition if we have one. if (definition && definition.hasInit()) { definition.getInit().installInGlobal(var); } // If we have an existing entry, destroy it, replacing it with the // new variable. if (entry) { auto existing = cast<llvm::GlobalValue>(entry); auto castVar = llvm::ConstantExpr::getBitCast(var, entry->getType()); existing->replaceAllUsesWith(castVar); existing->eraseFromParent(); } // If there's also an existing GOT-equivalent entry, rewrite it too, since // LLVM won't recognize a global with bitcasts in its initializers as GOT- // equivalent. rdar://problem/22388190 auto foundGOTEntry = GlobalGOTEquivalents.find(entity); if (foundGOTEntry != GlobalGOTEquivalents.end() && foundGOTEntry->second) { auto existingGOTEquiv = cast<llvm::GlobalVariable>(foundGOTEntry->second); // Make a new GOT equivalent referring to the new variable with its // definition type. auto newGOTEquiv = createGOTEquivalent(*this, var, entity); auto castGOTEquiv = llvm::ConstantExpr::getBitCast(newGOTEquiv, existingGOTEquiv->getType()); existingGOTEquiv->replaceAllUsesWith(castGOTEquiv); existingGOTEquiv->eraseFromParent(); GlobalGOTEquivalents[entity] = newGOTEquiv; } // Cache and return. entry = var; return var; } /// Get or create a "GOT equivalent" llvm::GlobalVariable, if applicable. /// /// Creates a private, unnamed constant containing the address of another /// global variable. LLVM can replace relative references to this variable with /// relative references to the GOT entry for the variable in the object file. ConstantReference IRGenModule::getAddrOfLLVMVariableOrGOTEquivalent(LinkEntity entity) { auto canDirectlyReferenceSILFunction = [&](SILFunction *silFn) { return (silFn->isDefinition() && !isAvailableExternally(silFn->getLinkage()) && this == IRGen.getGenModule(silFn)); }; // Handle SILFunctions specially, because unlike other entities they aren't // variables and aren't kept in the GlobalVars table. if (entity.isSILFunction()) { auto *silFn = entity.getSILFunction(); auto fn = getAddrOfSILFunction(silFn, NotForDefinition); if (canDirectlyReferenceSILFunction(silFn)) { return {fn, ConstantReference::Direct}; } auto gotEquivalent = getOrCreateGOTEquivalent(fn, entity); return {gotEquivalent, ConstantReference::Indirect}; } // ObjC class references can always be directly referenced, even in // the weird cases where we don't see a definition. if (entity.isObjCClassRef()) { auto value = getAddrOfObjCClassRef( const_cast<ClassDecl *>(cast<ClassDecl>(entity.getDecl()))); return { cast<llvm::Constant>(value.getAddress()), ConstantReference::Direct }; } // Ensure the variable is at least forward-declared. getAddrOfLLVMVariable(entity, ConstantInit(), DebugTypeInfo()); auto entry = GlobalVars[entity]; /// Returns a direct reference. auto direct = [&]() -> ConstantReference { // FIXME: Relative references to aliases break MC on 32-bit Mach-O // platforms (rdar://problem/22450593 ), so substitute an alias with its // aliasee to work around that. if (auto alias = dyn_cast<llvm::GlobalAlias>(entry)) return {alias->getAliasee(), ConstantReference::Direct}; return {entry, ConstantReference::Direct}; }; /// Returns an indirect reference. auto indirect = [&]() -> ConstantReference { auto gotEquivalent = getOrCreateGOTEquivalent( cast<llvm::GlobalValue>(entry), entity); return {gotEquivalent, ConstantReference::Indirect}; }; // Dynamically replaceable function keys are stored in the GlobalVars // table, but they don't have an associated Decl, so they require // special treatment here. if (entity.isDynamicallyReplaceableFunctionKey()) { auto *silFn = entity.getSILFunction(); if (canDirectlyReferenceSILFunction(silFn)) return direct(); return indirect(); } if (auto *entityDC = entity.getDeclContextForEmission()) { auto *entitySF = entityDC->getModuleScopeContext(); bool clangImportedEntity = isa<ClangModuleUnit>(entitySF); auto &mod = getSILModule(); if (!mod.isWholeModule()) { // In non-WMO builds, the associated context of the SILModule must // be a source file. Every source file is its own translation unit. auto *modDC = mod.getAssociatedContext(); auto *modSF = modDC->getModuleScopeContext(); assert(modSF != nullptr); // Imported entities are in a different Swift module, but are emitted // on demand and can be referenced directly. Entities in the same // source file can also be referenced directly. if (clangImportedEntity || modSF == entitySF) return direct(); // Everything else must be referenced indirectly. return indirect(); } // We're performing a WMO build. // // The associated context of the SILModule is the entire AST ModuleDecl, // but we might be doing a multi-threaded IRGen build, in which case // there is one translation unit per source file. // Imported entities are in a different Swift module and are emitted // on demand. In multi-threaded builds, they will be emitted into one // translation unit only. if (clangImportedEntity || entitySF->getParentModule() == mod.getSwiftModule()) { // If we're doing a single-threaded WMO build, or if the entity is // scheduled to be emitted in the same translation unit, reference // it directly. if (this == IRGen.getGenModule(entitySF)) return direct(); } } // Fall back to an indirect reference if we can't establish that a direct // reference is OK. return indirect(); } static TypeEntityReference getContextDescriptorEntityReference(IRGenModule &IGM, const LinkEntity &entity){ // TODO: consider using a symbolic reference (i.e. a symbol string // to be looked up dynamically) for types defined outside the module. auto ref = IGM.getAddrOfLLVMVariableOrGOTEquivalent(entity); auto kind = ref.isIndirect() ? TypeReferenceKind::IndirectTypeDescriptor : TypeReferenceKind::DirectTypeDescriptor; return TypeEntityReference(kind, ref.getValue()); } static TypeEntityReference getTypeContextDescriptorEntityReference(IRGenModule &IGM, NominalTypeDecl *decl) { auto entity = LinkEntity::forNominalTypeDescriptor(decl); IGM.IRGen.noteUseOfTypeContextDescriptor(decl, DontRequireMetadata); return getContextDescriptorEntityReference(IGM, entity); } static TypeEntityReference getProtocolDescriptorEntityReference(IRGenModule &IGM, ProtocolDecl *protocol) { assert(!protocol->isObjC() && "objc protocols don't have swift protocol descriptors"); auto entity = LinkEntity::forProtocolDescriptor(protocol); return getContextDescriptorEntityReference(IGM, entity); } static TypeEntityReference getObjCClassByNameReference(IRGenModule &IGM, ClassDecl *cls) { auto kind = TypeReferenceKind::DirectObjCClassName; SmallString<64> objcRuntimeNameBuffer; auto ref = IGM.getAddrOfGlobalString( cls->getObjCRuntimeName(objcRuntimeNameBuffer), /*willBeRelativelyAddressed=*/true); return TypeEntityReference(kind, ref); } TypeEntityReference IRGenModule::getTypeEntityReference(GenericTypeDecl *decl) { if (auto protocol = dyn_cast<ProtocolDecl>(decl)) { assert(!protocol->isObjC() && "imported protocols not handled here"); return getProtocolDescriptorEntityReference(*this, protocol); } if (auto opaque = dyn_cast<OpaqueTypeDecl>(decl)) { auto entity = LinkEntity::forOpaqueTypeDescriptor(opaque); IRGen.noteUseOfOpaqueTypeDescriptor(opaque); return getContextDescriptorEntityReference(*this, entity); } if (auto nominal = dyn_cast<NominalTypeDecl>(decl)) { auto clas = dyn_cast<ClassDecl>(decl); if (!clas) { return getTypeContextDescriptorEntityReference(*this, nominal); } switch (clas->getForeignClassKind()) { case ClassDecl::ForeignKind::RuntimeOnly: return getObjCClassByNameReference(*this, clas); case ClassDecl::ForeignKind::CFType: return getTypeContextDescriptorEntityReference(*this, clas); case ClassDecl::ForeignKind::Normal: if (hasKnownSwiftMetadata(*this, clas)) { return getTypeContextDescriptorEntityReference(*this, clas); } // Note: we would like to use an Objective-C class reference, but the // Darwin linker currently has a bug where it will coalesce these symbols // *after* computing a relative offset, causing incorrect relative // offsets in the metadata. Therefore, reference Objective-C classes by // their runtime names. return getObjCClassByNameReference(*this, clas); } } llvm_unreachable("bad foreign type kind"); } /// Form an LLVM constant for the relative distance between a reference /// (appearing at gep (0, indices) of `base`) and `target`. llvm::Constant * IRGenModule::emitRelativeReference(ConstantReference target, llvm::Constant *base, ArrayRef<unsigned> baseIndices) { llvm::Constant *relativeAddr = emitDirectRelativeReference(target.getValue(), base, baseIndices); // If the reference is indirect, flag it by setting the low bit. // (All of the base, direct target, and GOT entry need to be pointer-aligned // for this to be OK.) if (target.isIndirect()) { relativeAddr = llvm::ConstantExpr::getAdd(relativeAddr, llvm::ConstantInt::get(RelativeAddressTy, 1)); } return relativeAddr; } /// Form an LLVM constant for the relative distance between a reference /// (appearing at gep (0, indices...) of `base`) and `target`. For now, /// for this to succeed portably, both need to be globals defined in the /// current translation unit. llvm::Constant * IRGenModule::emitDirectRelativeReference(llvm::Constant *target, llvm::Constant *base, ArrayRef<unsigned> baseIndices) { // Convert the target to an integer. auto targetAddr = llvm::ConstantExpr::getPtrToInt(target, SizeTy); SmallVector<llvm::Constant*, 4> indices; indices.push_back(llvm::ConstantInt::get(Int32Ty, 0)); for (unsigned baseIndex : baseIndices) { indices.push_back(llvm::ConstantInt::get(Int32Ty, baseIndex)); }; // Drill down to the appropriate address in the base, then convert // that to an integer. auto baseElt = llvm::ConstantExpr::getInBoundsGetElementPtr( base->getType()->getPointerElementType(), base, indices); auto baseAddr = llvm::ConstantExpr::getPtrToInt(baseElt, SizeTy); // The relative address is the difference between those. auto relativeAddr = llvm::ConstantExpr::getSub(targetAddr, baseAddr); // Relative addresses can be 32-bit even on 64-bit platforms. if (SizeTy != RelativeAddressTy) relativeAddr = llvm::ConstantExpr::getTrunc(relativeAddr, RelativeAddressTy); return relativeAddr; } /// Expresses that `var` is removable (dead-strippable) when `dependsOn` is not /// referenced. void IRGenModule::appendLLVMUsedConditionalEntry(llvm::GlobalVariable *var, llvm::Constant *dependsOn) { llvm::Metadata *metadata[] = { // (1) which variable is being conditionalized, "target" llvm::ConstantAsMetadata::get(var), // (2) type, not relevant for a single-edge condition llvm::ConstantAsMetadata::get(llvm::ConstantInt::get( llvm::Type::getInt32Ty(Module.getContext()), 0)), // (3) the "edge" that holds the target alive, if it's missing the target // is allowed to be removed llvm::MDNode::get(Module.getContext(), { llvm::ConstantAsMetadata::get(dependsOn), }), }; auto *usedConditional = Module.getOrInsertNamedMetadata("llvm.used.conditional"); usedConditional->addOperand(llvm::MDNode::get(Module.getContext(), metadata)); } /// Expresses that `var` is removable (dead-strippable) when either the protocol /// from `record` is not referenced or the type from `record` is not referenced. void IRGenModule::appendLLVMUsedConditionalEntry( llvm::GlobalVariable *var, const ProtocolConformance *conformance) { auto *protocol = getAddrOfProtocolDescriptor(conformance->getProtocol()) ->stripPointerCasts(); auto *type = getAddrOfTypeContextDescriptor( conformance->getType()->getAnyNominal(), DontRequireMetadata) ->stripPointerCasts(); llvm::Metadata *metadata[] = { // (1) which variable is being conditionalized, "target" llvm::ConstantAsMetadata::get(var), // (2) type, "1" = if either edge is missing, the target is allowed to be // removed. llvm::ConstantAsMetadata::get(llvm::ConstantInt::get( llvm::Type::getInt32Ty(Module.getContext()), 1)), // (3) list of edges llvm::MDNode::get(Module.getContext(), { llvm::ConstantAsMetadata::get(protocol), llvm::ConstantAsMetadata::get(type), }), }; auto *usedConditional = Module.getOrInsertNamedMetadata("llvm.used.conditional"); usedConditional->addOperand(llvm::MDNode::get(Module.getContext(), metadata)); } /// Emit the protocol descriptors list and return it (if asContiguousArray is /// true, otherwise the descriptors are emitted as individual globals and /// nullptr is returned). llvm::Constant *IRGenModule::emitSwiftProtocols(bool asContiguousArray) { if (SwiftProtocols.empty()) return nullptr; StringRef sectionName; switch (TargetInfo.OutputObjectFormat) { case llvm::Triple::GOFF: case llvm::Triple::UnknownObjectFormat: llvm_unreachable("Don't know how to emit protocols for " "the selected object format."); case llvm::Triple::MachO: sectionName = "__TEXT, __swift5_protos, regular"; break; case llvm::Triple::ELF: case llvm::Triple::Wasm: sectionName = "swift5_protocols"; break; case llvm::Triple::XCOFF: case llvm::Triple::COFF: sectionName = ".sw5prt$B"; break; } // For JIT, emit the protocol list as a single global array, and return it. if (asContiguousArray) { ConstantInitBuilder builder(*this); auto recordsArray = builder.beginArray(ProtocolRecordTy); for (auto *protocol : SwiftProtocols) { auto record = recordsArray.beginStruct(ProtocolRecordTy); // Relative reference to the protocol descriptor. auto descriptorRef = getAddrOfLLVMVariableOrGOTEquivalent( LinkEntity::forProtocolDescriptor(protocol)); record.addRelativeAddress(descriptorRef); record.finishAndAddTo(recordsArray); } // Define the global variable for the protocol list. // FIXME: This needs to be a linker-local symbol in order for Darwin ld to // resolve relocations relative to it. auto var = recordsArray.finishAndCreateGlobal( "\x01l_protocols", Alignment(4), /*isConstant*/ true, llvm::GlobalValue::PrivateLinkage); var->setSection(sectionName); disableAddressSanitizer(*this, var); addUsedGlobal(var); return var; } // In non-JIT mode, emit the protocol records as individual globals. for (auto *protocol : SwiftProtocols) { auto entity = LinkEntity::forProtocolDescriptor(protocol); auto link = LinkInfo::get(*this, entity, NotForDefinition); auto recordMangledName = LinkEntity::forProtocolDescriptorRecord(protocol).mangleAsString(); auto var = new llvm::GlobalVariable(Module, ProtocolRecordTy, /*isConstant*/ true, llvm::GlobalValue::PrivateLinkage, /*initializer*/ nullptr, recordMangledName); auto descriptorRef = getAddrOfLLVMVariableOrGOTEquivalent(entity); llvm::Constant *relativeAddr = emitDirectRelativeReference(descriptorRef.getValue(), var, {0}); llvm::Constant *recordFields[] = {relativeAddr}; auto record = llvm::ConstantStruct::get(ProtocolRecordTy, recordFields); var->setInitializer(record); var->setSection(sectionName); var->setAlignment(llvm::MaybeAlign(4)); disableAddressSanitizer(*this, var); addUsedGlobal(var); if (IRGen.Opts.ConditionalRuntimeRecords) { // Allow dead-stripping `var` (the protocol record) when the protocol // (descriptorRef) is not referenced. appendLLVMUsedConditionalEntry(var, descriptorRef.getValue()); } } return nullptr; } void IRGenModule::addProtocolConformance(ConformanceDescription &&record) { emitProtocolConformance(record); // Add this conformance to the conformance list. ProtocolConformances.push_back(std::move(record)); } /// Emit the protocol conformance list and return it (if asContiguousArray is /// true, otherwise the records are emitted as individual globals and /// nullptr is returned). llvm::Constant *IRGenModule::emitProtocolConformances(bool asContiguousArray) { if (ProtocolConformances.empty()) return nullptr; StringRef sectionName; switch (TargetInfo.OutputObjectFormat) { case llvm::Triple::GOFF: case llvm::Triple::UnknownObjectFormat: llvm_unreachable("Don't know how to emit protocol conformances for " "the selected object format."); case llvm::Triple::MachO: sectionName = "__TEXT, __swift5_proto, regular"; break; case llvm::Triple::ELF: case llvm::Triple::Wasm: sectionName = "swift5_protocol_conformances"; break; case llvm::Triple::XCOFF: case llvm::Triple::COFF: sectionName = ".sw5prtc$B"; break; } // For JIT, emit the protocol conformance list as a single global array, and // return it. if (asContiguousArray) { ConstantInitBuilder builder(*this); auto descriptorArray = builder.beginArray(RelativeAddressTy); for (const auto &record : ProtocolConformances) { auto conformance = record.conformance; auto entity = LinkEntity::forProtocolConformanceDescriptor(conformance); auto descriptor = getAddrOfLLVMVariable(entity, ConstantInit(), DebugTypeInfo()); descriptorArray.addRelativeAddress(descriptor); } // Define the global variable for the conformance list. // FIXME: This needs to be a linker-local symbol in order for Darwin ld to // resolve relocations relative to it. auto var = descriptorArray.finishAndCreateGlobal( "\x01l_protocol_conformances", Alignment(4), /*isConstant*/ true, llvm::GlobalValue::PrivateLinkage); var->setSection(sectionName); disableAddressSanitizer(*this, var); addUsedGlobal(var); return var; } // In non-JIT mode, emit the protocol conformance records as individual // globals. for (const auto &record : ProtocolConformances) { auto entity = LinkEntity::forProtocolConformanceDescriptor(record.conformance); auto link = LinkInfo::get(*this, entity, NotForDefinition); auto recordMangledName = LinkEntity::forProtocolConformanceDescriptorRecord(record.conformance) .mangleAsString(); auto var = new llvm::GlobalVariable( Module, RelativeAddressTy, /*isConstant*/ true, llvm::GlobalValue::PrivateLinkage, /*initializer*/ nullptr, recordMangledName); auto descriptorRef = getAddrOfLLVMVariableOrGOTEquivalent(entity); llvm::Constant *relativeAddr = emitDirectRelativeReference(descriptorRef.getValue(), var, {}); var->setInitializer(relativeAddr); var->setSection(sectionName); var->setAlignment(llvm::MaybeAlign(4)); disableAddressSanitizer(*this, var); addUsedGlobal(var); if (IRGen.Opts.ConditionalRuntimeRecords) { // Allow dead-stripping `var` (the conformance record) when the protocol // or type (from the conformance) is not referenced. appendLLVMUsedConditionalEntry(var, record.conformance); } } return nullptr; } /// Emit list of type metadata records for types that might not have explicit /// protocol conformances, and return it (if asContiguousArray is true, /// otherwise the descriptors are emitted as individual globals and nullptr is /// returned). llvm::Constant *IRGenModule::emitTypeMetadataRecords(bool asContiguousArray) { if (RuntimeResolvableTypes.empty()) return nullptr; std::string sectionName; switch (TargetInfo.OutputObjectFormat) { case llvm::Triple::MachO: sectionName = "__TEXT, __swift5_types, regular"; break; case llvm::Triple::ELF: case llvm::Triple::Wasm: sectionName = "swift5_type_metadata"; break; case llvm::Triple::XCOFF: case llvm::Triple::COFF: sectionName = ".sw5tymd$B"; break; case llvm::Triple::GOFF: case llvm::Triple::UnknownObjectFormat: llvm_unreachable("Don't know how to emit type metadata table for " "the selected object format."); } auto generateRecord = [this](TypeEntityReference ref, llvm::GlobalVariable *var, ArrayRef<unsigned> baseIndices) { // Form the relative address, with the type reference kind in the low bits. llvm::Constant *relativeAddr = emitDirectRelativeReference(ref.getValue(), var, baseIndices); unsigned lowBits = static_cast<unsigned>(ref.getKind()); if (lowBits != 0) { relativeAddr = llvm::ConstantExpr::getAdd( relativeAddr, llvm::ConstantInt::get(RelativeAddressTy, lowBits)); } llvm::Constant *recordFields[] = {relativeAddr}; auto record = llvm::ConstantStruct::get(TypeMetadataRecordTy, recordFields); return record; }; // For JIT, emit the type list as a single global array, and return it. if (asContiguousArray) { // Define the global variable for the list of types. // We have to do this before defining the initializer since the entries will // contain offsets relative to themselves. // FIXME: This needs to be a linker-local symbol in order for Darwin ld to // resolve relocations relative to it. auto arrayTy = llvm::ArrayType::get(TypeMetadataRecordTy, RuntimeResolvableTypes.size()); auto var = new llvm::GlobalVariable( Module, arrayTy, /*isConstant*/ true, llvm::GlobalValue::PrivateLinkage, /*initializer*/ nullptr, "\x01l_type_metadata_table"); SmallVector<llvm::Constant *, 8> elts; for (auto type : RuntimeResolvableTypes) { auto ref = getTypeEntityReference(type); unsigned arrayIdx = elts.size(); auto record = generateRecord(ref, var, { arrayIdx, 0 }); elts.push_back(record); } auto initializer = llvm::ConstantArray::get(arrayTy, elts); var->setInitializer(initializer); var->setSection(sectionName); var->setAlignment(llvm::MaybeAlign(4)); disableAddressSanitizer(*this, var); addUsedGlobal(var); return var; } // In non-JIT mode, emit the type records as individual globals. for (auto type : RuntimeResolvableTypes) { auto ref = getTypeEntityReference(type); std::string recordMangledName; if (auto opaque = dyn_cast<OpaqueTypeDecl>(type)) { recordMangledName = LinkEntity::forOpaqueTypeDescriptorRecord(opaque).mangleAsString(); } else if (auto nominal = dyn_cast<NominalTypeDecl>(type)) { recordMangledName = LinkEntity::forNominalTypeDescriptorRecord(nominal).mangleAsString(); } else { llvm_unreachable("bad type in RuntimeResolvableTypes"); } auto var = new llvm::GlobalVariable( Module, TypeMetadataRecordTy, /*isConstant*/ true, llvm::GlobalValue::PrivateLinkage, /*initializer*/ nullptr, recordMangledName); auto record = generateRecord(ref, var, {0}); var->setInitializer(record); var->setSection(sectionName); var->setAlignment(llvm::MaybeAlign(4)); disableAddressSanitizer(*this, var); addUsedGlobal(var); if (IRGen.Opts.ConditionalRuntimeRecords) { // Allow dead-stripping `var` (the type record) when the type (`ref`) is // not referenced. appendLLVMUsedConditionalEntry(var, ref.getValue()); } } return nullptr; } /// Fetch a global reference to a reference to the given Objective-C class. /// The result is of type ObjCClassPtrTy->getPointerTo(). Address IRGenModule::getAddrOfObjCClassRef(ClassDecl *theClass) { assert(ObjCInterop && "getting address of ObjC class ref in no-interop mode"); LinkEntity entity = LinkEntity::forObjCClassRef(theClass); auto DbgTy = DebugTypeInfo::getObjCClass( theClass, ObjCClassPtrTy, getPointerSize(), getPointerAlignment()); auto addr = getAddrOfLLVMVariable(entity, ConstantInit(), DbgTy); // Define it lazily. if (auto global = dyn_cast<llvm::GlobalVariable>(addr)) { if (global->isDeclaration()) { global->setSection(GetObjCSectionName("__objc_classrefs", "regular,no_dead_strip")); global->setLinkage(llvm::GlobalVariable::PrivateLinkage); global->setExternallyInitialized(true); global->setInitializer(getAddrOfObjCClass(theClass, NotForDefinition)); addCompilerUsedGlobal(global); } } return Address(addr, entity.getAlignment(*this)); } /// Fetch a global reference to the given Objective-C class. The /// result is of type ObjCClassPtrTy. llvm::Constant *IRGenModule::getAddrOfObjCClass(ClassDecl *theClass, ForDefinition_t forDefinition) { assert(ObjCInterop && "getting address of ObjC class in no-interop mode"); assert(!theClass->isForeign()); LinkEntity entity = LinkEntity::forObjCClass(theClass); auto DbgTy = DebugTypeInfo::getObjCClass( theClass, ObjCClassPtrTy, getPointerSize(), getPointerAlignment()); auto addr = getAddrOfLLVMVariable(entity, forDefinition, DbgTy); return addr; } /// Fetch the declaration of a metaclass object. The result is always a /// GlobalValue of ObjCClassPtrTy, and is either the Objective-C metaclass or /// the Swift metaclass stub, depending on whether the class is published as an /// ObjC class. llvm::Constant * IRGenModule::getAddrOfMetaclassObject(ClassDecl *decl, ForDefinition_t forDefinition) { assert((!decl->isGenericContext() || decl->hasClangNode()) && "generic classes do not have a static metaclass object"); auto entity = decl->getMetaclassKind() == ClassDecl::MetaclassKind::ObjC ? LinkEntity::forObjCMetaclass(decl) : LinkEntity::forSwiftMetaclassStub(decl); auto DbgTy = DebugTypeInfo::getObjCClass( decl, ObjCClassPtrTy, getPointerSize(), getPointerAlignment()); auto addr = getAddrOfLLVMVariable(entity, forDefinition, DbgTy); return addr; } llvm::Constant * IRGenModule::getAddrOfCanonicalSpecializedGenericMetaclassObject( CanType concreteType, ForDefinition_t forDefinition) { auto *theClass = concreteType->getClassOrBoundGenericClass(); assert(theClass && "only classes have metaclasses"); assert(concreteType->getClassOrBoundGenericClass()->isGenericContext()); auto entity = LinkEntity::forSpecializedGenericSwiftMetaclassStub(concreteType); auto DbgTy = DebugTypeInfo::getObjCClass( theClass, ObjCClassPtrTy, getPointerSize(), getPointerAlignment()); auto addr = getAddrOfLLVMVariable(entity, forDefinition, DbgTy); return addr; } /// Fetch the declaration of an Objective-C metadata update callback. llvm::Function * IRGenModule::getAddrOfObjCMetadataUpdateFunction(ClassDecl *classDecl, ForDefinition_t forDefinition) { assert(ObjCInterop); LinkEntity entity = LinkEntity::forObjCMetadataUpdateFunction(classDecl); llvm::Function *&entry = GlobalFuncs[entity]; if (entry) { if (forDefinition) updateLinkageForDefinition(*this, entry, entity); return entry; } // Class _Nullable callback(Class _Nonnull cls, void * _Nullable arg); Signature signature(ObjCUpdateCallbackTy, llvm::AttributeList(), DefaultCC); LinkInfo link = LinkInfo::get(*this, entity, forDefinition); entry = createFunction(*this, link, signature); return entry; } /// Fetch the declaration of an Objective-C resilient class stub. llvm::Constant * IRGenModule::getAddrOfObjCResilientClassStub(ClassDecl *classDecl, ForDefinition_t forDefinition, TypeMetadataAddress addr) { assert(ObjCInterop); assert(getClassMetadataStrategy(classDecl) == ClassMetadataStrategy::Resilient); LinkEntity entity = LinkEntity::forObjCResilientClassStub(classDecl, addr); return getAddrOfLLVMVariable(entity, forDefinition, DebugTypeInfo()); } /// Fetch the type metadata access function for a non-generic type. llvm::Function * IRGenModule::getAddrOfTypeMetadataAccessFunction(CanType type, ForDefinition_t forDefinition) { assert(!type->hasArchetype() && !type->hasTypeParameter()); NominalTypeDecl *Nominal = type->getNominalOrBoundGenericNominal(); IRGen.noteUseOfTypeMetadata(Nominal); LinkEntity entity = LinkEntity::forTypeMetadataAccessFunction(type); llvm::Function *&entry = GlobalFuncs[entity]; if (entry) { if (forDefinition) updateLinkageForDefinition(*this, entry, entity); return entry; } llvm::Type *params[] = { SizeTy }; // MetadataRequest auto fnType = llvm::FunctionType::get(TypeMetadataResponseTy, params, false); Signature signature(fnType, llvm::AttributeList(), SwiftCC); LinkInfo link = LinkInfo::get(*this, entity, forDefinition); entry = createFunction(*this, link, signature); return entry; } /// Fetch the opaque type descriptor access function. llvm::Function *IRGenModule::getAddrOfOpaqueTypeDescriptorAccessFunction( OpaqueTypeDecl *decl, ForDefinition_t forDefinition, bool implementation) { IRGen.noteUseOfOpaqueTypeDescriptor(decl); LinkEntity entity = implementation ? LinkEntity::forOpaqueTypeDescriptorAccessorImpl(decl) : LinkEntity::forOpaqueTypeDescriptorAccessor(decl); llvm::Function *&entry = GlobalFuncs[entity]; if (entry) { if (forDefinition) updateLinkageForDefinition(*this, entry, entity); return entry; } auto fnType = llvm::FunctionType::get(OpaqueTypeDescriptorPtrTy, {}, false); Signature signature(fnType, llvm::AttributeList(), SwiftCC); LinkInfo link = LinkInfo::get(*this, entity, forDefinition); entry = createFunction(*this, link, signature); return entry; } /// Fetch the type metadata access function for the given generic type. llvm::Function * IRGenModule::getAddrOfGenericTypeMetadataAccessFunction( NominalTypeDecl *nominal, ArrayRef<llvm::Type *> genericArgs, ForDefinition_t forDefinition) { assert(nominal->isGenericContext()); assert(!genericArgs.empty() || nominal->getGenericSignature()->areAllParamsConcrete()); IRGen.noteUseOfTypeMetadata(nominal); auto type = nominal->getDeclaredType()->getCanonicalType(); assert(type->hasUnboundGenericType()); LinkEntity entity = LinkEntity::forTypeMetadataAccessFunction(type); llvm::Function *&entry = GlobalFuncs[entity]; if (entry) { if (forDefinition) updateLinkageForDefinition(*this, entry, entity); return entry; } // If we have more arguments than can be passed directly, all of the // generic arguments are passed as an array. llvm::Type *paramTypesArray[NumDirectGenericTypeMetadataAccessFunctionArgs+1]; paramTypesArray[0] = SizeTy; // MetadataRequest size_t numParams = 1; size_t numGenericArgs = genericArgs.size(); if (numGenericArgs > NumDirectGenericTypeMetadataAccessFunctionArgs) { paramTypesArray[1] = Int8PtrPtrTy; ++numParams; } else { for (size_t i : indices(genericArgs)) paramTypesArray[i + 1] = genericArgs[i]; numParams += numGenericArgs; } auto paramTypes = llvm::makeArrayRef(paramTypesArray, numParams); auto fnType = llvm::FunctionType::get(TypeMetadataResponseTy, paramTypes, false); Signature signature(fnType, llvm::AttributeList(), SwiftCC); LinkInfo link = LinkInfo::get(*this, entity, forDefinition); entry = createFunction(*this, link, signature); return entry; } llvm::Function * IRGenModule::getAddrOfCanonicalSpecializedGenericTypeMetadataAccessFunction( CanType theType, ForDefinition_t forDefinition) { assert(shouldPrespecializeGenericMetadata()); assert(!theType->hasUnboundGenericType()); auto *nominal = theType->getAnyNominal(); assert(nominal); assert(nominal->isGenericContext()); IRGen.noteUseOfCanonicalSpecializedMetadataAccessor(theType); LinkEntity entity = LinkEntity::forPrespecializedTypeMetadataAccessFunction(theType); llvm::Function *&entry = GlobalFuncs[entity]; if (entry) { if (forDefinition) updateLinkageForDefinition(*this, entry, entity); return entry; } llvm::Type *paramTypesArray[1]; paramTypesArray[0] = SizeTy; // MetadataRequest auto paramTypes = llvm::makeArrayRef(paramTypesArray, 1); auto functionType = llvm::FunctionType::get(TypeMetadataResponseTy, paramTypes, false); Signature signature(functionType, llvm::AttributeList(), SwiftCC); LinkInfo link = LinkInfo::get(*this, entity, forDefinition); entry = createFunction(*this, link, signature); return entry; } /// Get or create a type metadata cache variable. These are an /// implementation detail of type metadata access functions. llvm::Constant * IRGenModule::getAddrOfTypeMetadataLazyCacheVariable(CanType type) { assert(!type->hasArchetype() && !type->hasTypeParameter()); LinkEntity entity = LinkEntity::forTypeMetadataLazyCacheVariable(type); auto variable = getAddrOfLLVMVariable(entity, ForDefinition, DebugTypeInfo()); // Zero-initialize if we're asking for a definition. cast<llvm::GlobalVariable>(variable)->setInitializer( llvm::ConstantPointerNull::get(TypeMetadataPtrTy)); return variable; } llvm::Constant * IRGenModule::getAddrOfCanonicalPrespecializedGenericTypeCachingOnceToken( NominalTypeDecl *decl) { assert(decl->isGenericContext()); LinkEntity entity = LinkEntity::forCanonicalPrespecializedGenericTypeCachingOnceToken(decl); if (auto &entry = GlobalVars[entity]) { return entry; } auto variable = getAddrOfLLVMVariable(entity, ForDefinition, DebugTypeInfo()); // Zero-initialize if we're asking for a definition. cast<llvm::GlobalVariable>(variable)->setInitializer( llvm::ConstantInt::get(OnceTy, 0)); return variable; } llvm::Constant * IRGenModule::getAddrOfNoncanonicalSpecializedGenericTypeMetadataCacheVariable(CanType type) { assert(!type->hasArchetype() && !type->hasTypeParameter()); LinkEntity entity = LinkEntity::forNoncanonicalSpecializedGenericTypeMetadataCacheVariable(type); if (auto &entry = GlobalVars[entity]) { return entry; } auto variable = getAddrOfLLVMVariable(entity, ForDefinition, DebugTypeInfo()); cast<llvm::GlobalVariable>(variable)->setInitializer( llvm::ConstantPointerNull::get(TypeMetadataPtrTy)); return variable; } /// Get or create a type metadata cache variable. These are an /// implementation detail of type metadata access functions. llvm::Constant * IRGenModule::getAddrOfTypeMetadataDemanglingCacheVariable(CanType type, ConstantInit definition) { assert(!type->hasArchetype() && !type->hasTypeParameter()); LinkEntity entity = LinkEntity::forTypeMetadataDemanglingCacheVariable(type); return getAddrOfLLVMVariable(entity, definition, DebugTypeInfo()); } llvm::Constant * IRGenModule::getAddrOfTypeMetadataSingletonInitializationCache( NominalTypeDecl *D, ForDefinition_t forDefinition) { auto entity = LinkEntity::forTypeMetadataSingletonInitializationCache(D); auto variable = getAddrOfLLVMVariable(entity, forDefinition, DebugTypeInfo()); // Zero-initialize if we're asking for a definition. if (forDefinition) { cast<llvm::GlobalVariable>(variable)->setInitializer( llvm::Constant::getNullValue(variable->getType()->getPointerElementType())); } return variable; } llvm::GlobalValue *IRGenModule::defineAlias(LinkEntity entity, llvm::Constant *definition) { // Check for an existing forward declaration of the alias. auto &entry = GlobalVars[entity]; llvm::GlobalValue *existingVal = nullptr; if (entry) { existingVal = cast<llvm::GlobalValue>(entry); // Clear the existing value's name so we can steal it. existingVal->setName(""); } LinkInfo link = LinkInfo::get(*this, entity, ForDefinition); auto *ptrTy = cast<llvm::PointerType>(definition->getType()); auto *alias = llvm::GlobalAlias::create( ptrTy->getElementType(), ptrTy->getAddressSpace(), link.getLinkage(), link.getName(), definition, &Module); ApplyIRLinkage({link.getLinkage(), link.getVisibility(), link.getDLLStorage()}) .to(alias); markGlobalAsUsedBasedOnLinkage(*this, link, alias); // Replace an existing external declaration for the address point. if (entry) { auto existingVal = cast<llvm::GlobalValue>(entry); for (auto iterator = std::begin(LLVMUsed); iterator < std::end(LLVMUsed); ++iterator) { llvm::Value *thisValue = *iterator; if (thisValue == existingVal) { LLVMUsed.erase(iterator); } } for (auto iterator = std::begin(LLVMCompilerUsed); iterator < std::end(LLVMCompilerUsed); ++iterator) { llvm::Value *thisValue = *iterator; if (thisValue == existingVal) { LLVMCompilerUsed.erase(iterator); } } // FIXME: MC breaks when emitting alias references on some platforms // (rdar://problem/22450593 ). Work around this by referring to the aliasee // instead. llvm::Constant *aliasCast = alias->getAliasee(); aliasCast = llvm::ConstantExpr::getBitCast(aliasCast, entry->getType()); existingVal->replaceAllUsesWith(aliasCast); existingVal->eraseFromParent(); } entry = alias; return alias; } /// Define the metadata for a type. /// /// Some type metadata has information before the address point that the /// public symbol for the metadata references. This function will rewrite any /// existing external declaration to the address point as an alias into the /// full metadata object. llvm::GlobalValue *IRGenModule::defineTypeMetadata( CanType concreteType, bool isPattern, bool isConstant, ConstantInitFuture init, llvm::StringRef section, SmallVector<std::pair<Size, SILDeclRef>, 8> vtableEntries) { assert(init); auto isPrespecialized = concreteType->getAnyGeneric() && concreteType->getAnyGeneric()->isGenericContext(); if (isPattern) { assert(isConstant && "Type metadata patterns must be constant"); auto addr = getAddrOfTypeMetadataPattern(concreteType->getAnyNominal(), init, section); return cast<llvm::GlobalValue>(addr); } auto entity = (isPrespecialized && !irgen::isCanonicalInitializableTypeMetadataStaticallyAddressable( *this, concreteType)) ? LinkEntity::forNoncanonicalSpecializedGenericTypeMetadata( concreteType) : LinkEntity::forTypeMetadata(concreteType, TypeMetadataAddress::FullMetadata); auto DbgTy = DebugTypeInfo::getMetadata(MetatypeType::get(concreteType), entity.getDefaultDeclarationType(*this)->getPointerTo(), Size(0), Alignment(1)); // Define the variable. llvm::GlobalVariable *var = cast<llvm::GlobalVariable>( getAddrOfLLVMVariable(entity, init, DbgTy)); var->setConstant(isConstant); if (!section.empty()) var->setSection(section); if (getOptions().VirtualFunctionElimination) { if (auto classDecl = concreteType->getClassOrBoundGenericClass()) { addVTableTypeMetadata(classDecl, var, vtableEntries); } } LinkInfo link = LinkInfo::get(*this, entity, ForDefinition); markGlobalAsUsedBasedOnLinkage(*this, link, var); /// For concrete metadata, we want to use the initializer on the /// "full metadata", and define the "direct" address point as an alias. unsigned adjustmentIndex = MetadataAdjustmentIndex::ValueType; if (auto nominal = concreteType->getAnyNominal()) { // Keep type metadata around for all types. addRuntimeResolvableType(nominal); // Don't define the alias for foreign type metadata or prespecialized // generic metadata, since neither is ABI. if (requiresForeignTypeMetadata(nominal) || isPrespecialized) return var; // Native Swift class metadata has a destructor before the address point. if (isa<ClassDecl>(nominal)) { adjustmentIndex = MetadataAdjustmentIndex::Class; } } llvm::Constant *indices[] = { llvm::ConstantInt::get(Int32Ty, 0), llvm::ConstantInt::get(Int32Ty, adjustmentIndex)}; auto addr = llvm::ConstantExpr::getInBoundsGetElementPtr( var->getType()->getPointerElementType(), var, indices); addr = llvm::ConstantExpr::getBitCast(addr, TypeMetadataPtrTy); // For concrete metadata, declare the alias to its address point. auto directEntity = LinkEntity::forTypeMetadata( concreteType, TypeMetadataAddress::AddressPoint); return defineAlias(directEntity, addr); } /// Fetch the declaration of the (possibly uninitialized) metadata for a type. llvm::Constant * IRGenModule::getAddrOfTypeMetadata(CanType concreteType, TypeMetadataCanonicality canonicality) { return getAddrOfTypeMetadata(concreteType, SymbolReferenceKind::Absolute, canonicality) .getDirectValue(); } ConstantReference IRGenModule::getAddrOfTypeMetadata(CanType concreteType, SymbolReferenceKind refKind, TypeMetadataCanonicality canonicality) { assert(!isa<UnboundGenericType>(concreteType)); auto nominal = concreteType->getAnyNominal(); bool foreign = nominal && requiresForeignTypeMetadata(nominal); // Foreign classes and prespecialized generic types do not use an alias into // the full metadata and therefore require a GEP. bool fullMetadata = foreign || (concreteType->getAnyGeneric() && concreteType->getAnyGeneric()->isGenericContext()); llvm::Type *defaultVarTy; unsigned adjustmentIndex; if (fullMetadata) { defaultVarTy = FullTypeMetadataStructTy; if (concreteType->getClassOrBoundGenericClass() && !foreign) { adjustmentIndex = MetadataAdjustmentIndex::Class; } else { adjustmentIndex = MetadataAdjustmentIndex::ValueType; } } else if (nominal) { // The symbol for native non-generic nominal type metadata is generated at // the aliased address point (see defineTypeMetadata() above). assert(!nominal->hasClangNode()); defaultVarTy = TypeMetadataStructTy; adjustmentIndex = 0; } else { // FIXME: Non-nominal metadata provided by the C++ runtime is exported // with the address of the start of the full metadata object, since // Clang doesn't provide an easy way to emit symbols aliasing into the // middle of an object. defaultVarTy = FullTypeMetadataStructTy; adjustmentIndex = MetadataAdjustmentIndex::ValueType; } // If this is a use, and the type metadata is emitted lazily, // trigger lazy emission of the metadata. if (NominalTypeDecl *nominal = concreteType->getAnyNominal()) { IRGen.noteUseOfTypeMetadata(nominal); } if (shouldPrespecializeGenericMetadata()) { if (auto nominal = concreteType->getAnyNominal()) { if (nominal->isGenericContext()) { IRGen.noteUseOfSpecializedGenericTypeMetadata(*this, concreteType, canonicality); } } } Optional<LinkEntity> entity; DebugTypeInfo DbgTy; switch (canonicality) { case TypeMetadataCanonicality::Canonical: entity = LinkEntity::forTypeMetadata( concreteType, fullMetadata ? TypeMetadataAddress::FullMetadata : TypeMetadataAddress::AddressPoint); break; case TypeMetadataCanonicality::Noncanonical: entity = LinkEntity::forNoncanonicalSpecializedGenericTypeMetadata(concreteType); break; } DbgTy = DebugTypeInfo::getMetadata(MetatypeType::get(concreteType), defaultVarTy->getPointerTo(), Size(0), Alignment(1)); ConstantReference addr; if (fullMetadata && !foreign) { addr = getAddrOfLLVMVariable(*entity, ConstantInit(), DbgTy, refKind, /*overrideDeclType=*/nullptr); } else { addr = getAddrOfLLVMVariable(*entity, ConstantInit(), DbgTy, refKind, /*overrideDeclType=*/defaultVarTy); } if (auto *GV = dyn_cast<llvm::GlobalVariable>(addr.getValue())) GV->setComdat(nullptr); // FIXME: MC breaks when emitting alias references on some platforms // (rdar://problem/22450593 ). Work around this by referring to the aliasee // instead. if (auto alias = dyn_cast<llvm::GlobalAlias>(addr.getValue())) addr = ConstantReference(alias->getAliasee(), addr.isIndirect()); // Adjust if necessary. if (adjustmentIndex) { llvm::Constant *indices[] = { llvm::ConstantInt::get(Int32Ty, 0), llvm::ConstantInt::get(Int32Ty, adjustmentIndex) }; addr = ConstantReference( llvm::ConstantExpr::getInBoundsGetElementPtr( addr.getValue()->getType()->getPointerElementType(), addr.getValue(), indices), addr.isIndirect()); } return addr; } llvm::Constant * IRGenModule::getAddrOfTypeMetadataPattern(NominalTypeDecl *D) { return getAddrOfTypeMetadataPattern(D, ConstantInit(), ""); } llvm::Constant * IRGenModule::getAddrOfTypeMetadataPattern(NominalTypeDecl *D, ConstantInit init, StringRef section) { if (!init) IRGen.noteUseOfTypeMetadata(D); LinkEntity entity = LinkEntity::forTypeMetadataPattern(D); auto addr = getAddrOfLLVMVariable(entity, init, DebugTypeInfo()); if (init) { auto var = cast<llvm::GlobalVariable>(addr); var->setConstant(true); if (!section.empty()) var->setSection(section); // Keep type metadata around for all types. addRuntimeResolvableType(D); } return addr; } /// Returns the address of a class metadata base offset. llvm::Constant * IRGenModule::getAddrOfClassMetadataBounds(ClassDecl *D, ForDefinition_t forDefinition) { LinkEntity entity = LinkEntity::forClassMetadataBaseOffset(D); return getAddrOfLLVMVariable(entity, forDefinition, DebugTypeInfo()); } /// Return the address of a generic type's metadata instantiation cache. llvm::Constant * IRGenModule::getAddrOfTypeMetadataInstantiationCache(NominalTypeDecl *D, ForDefinition_t forDefinition) { auto entity = LinkEntity::forTypeMetadataInstantiationCache(D); return getAddrOfLLVMVariable(entity, forDefinition, DebugTypeInfo()); } llvm::Function * IRGenModule::getAddrOfTypeMetadataInstantiationFunction(NominalTypeDecl *D, ForDefinition_t forDefinition) { LinkEntity entity = LinkEntity::forTypeMetadataInstantiationFunction(D); llvm::Function *&entry = GlobalFuncs[entity]; if (entry) { if (forDefinition) updateLinkageForDefinition(*this, entry, entity); return entry; } // This function is used in two cases -- allocating generic type metadata, // and relocating non-generic resilient class metadata. llvm::FunctionType *fnType; if (D->isGenericContext()) { // MetadataInstantiator in ABI/Metadata.h llvm::Type *argTys[] = { /// Type descriptor. TypeContextDescriptorPtrTy, /// Generic arguments. Int8PtrPtrTy, /// Generic metadata pattern. Int8PtrTy }; fnType = llvm::FunctionType::get(TypeMetadataPtrTy, argTys, /*isVarArg*/ false); } else { assert(isa<ClassDecl>(D)); // MetadataRelocator in ABI/Metadata.h llvm::Type *argTys[] = { /// Type descriptor. TypeContextDescriptorPtrTy, /// Resilient metadata pattern. Int8PtrTy }; fnType = llvm::FunctionType::get(TypeMetadataPtrTy, argTys, /*isVarArg*/ false); } Signature signature(fnType, llvm::AttributeList(), DefaultCC); LinkInfo link = LinkInfo::get(*this, entity, forDefinition); entry = createFunction(*this, link, signature); return entry; } llvm::Function * IRGenModule::getAddrOfTypeMetadataCompletionFunction(NominalTypeDecl *D, ForDefinition_t forDefinition) { LinkEntity entity = LinkEntity::forTypeMetadataCompletionFunction(D); llvm::Function *&entry = GlobalFuncs[entity]; if (entry) { if (forDefinition) updateLinkageForDefinition(*this, entry, entity); return entry; } llvm::Type *argTys[] = { /// Type metadata. TypeMetadataPtrTy, /// Metadata completion context. Int8PtrTy, /// Generic metadata pattern. Int8PtrPtrTy }; auto fnType = llvm::FunctionType::get(TypeMetadataResponseTy, argTys, /*isVarArg*/ false); Signature signature(fnType, llvm::AttributeList(), SwiftCC); LinkInfo link = LinkInfo::get(*this, entity, forDefinition); entry = createFunction(*this, link, signature); return entry; } /// Return the address of a nominal type descriptor. llvm::Constant *IRGenModule::getAddrOfTypeContextDescriptor(NominalTypeDecl *D, RequireMetadata_t requireMetadata, ConstantInit definition) { IRGen.noteUseOfTypeContextDescriptor(D, requireMetadata); auto entity = LinkEntity::forNominalTypeDescriptor(D); return getAddrOfLLVMVariable(entity, definition, DebugTypeInfo()); } llvm::Constant *IRGenModule::getAddrOfOpaqueTypeDescriptor( OpaqueTypeDecl *opaqueType, ConstantInit definition) { IRGen.noteUseOfOpaqueTypeDescriptor(opaqueType); auto entity = LinkEntity::forOpaqueTypeDescriptor(opaqueType); return getAddrOfLLVMVariable(entity, definition, DebugTypeInfo()); } llvm::Constant *IRGenModule:: getAddrOfReflectionBuiltinDescriptor(CanType type, ConstantInit definition) { auto entity = LinkEntity::forReflectionBuiltinDescriptor(type); return getAddrOfLLVMVariable(entity, definition, DebugTypeInfo()); } llvm::Constant *IRGenModule:: getAddrOfReflectionFieldDescriptor(CanType type, ConstantInit definition) { auto entity = LinkEntity::forReflectionFieldDescriptor(type); return getAddrOfLLVMVariable(entity, definition, DebugTypeInfo()); } llvm::Constant *IRGenModule:: getAddrOfReflectionAssociatedTypeDescriptor(const ProtocolConformance *c, ConstantInit definition) { auto entity = LinkEntity::forReflectionAssociatedTypeDescriptor(c); return getAddrOfLLVMVariable(entity, definition, DebugTypeInfo()); } /// Return the address of a property descriptor. llvm::Constant *IRGenModule::getAddrOfPropertyDescriptor(AbstractStorageDecl *D, ConstantInit definition) { auto entity = LinkEntity::forPropertyDescriptor(D); return getAddrOfLLVMVariable(entity, definition, DebugTypeInfo()); } llvm::Constant *IRGenModule::getAddrOfProtocolDescriptor(ProtocolDecl *D, ConstantInit definition) { if (D->isObjC()) { assert(!definition && "cannot define an @objc protocol descriptor this way"); return getAddrOfObjCProtocolRecord(D, NotForDefinition); } auto entity = LinkEntity::forProtocolDescriptor(D); return getAddrOfLLVMVariable(entity, definition, DebugTypeInfo()); } llvm::Constant *IRGenModule::getAddrOfProtocolRequirementsBaseDescriptor( ProtocolDecl *proto) { auto entity = LinkEntity::forProtocolRequirementsBaseDescriptor(proto); return getAddrOfLLVMVariable(entity, ConstantInit(), DebugTypeInfo()); } llvm::GlobalValue *IRGenModule::defineProtocolRequirementsBaseDescriptor( ProtocolDecl *proto, llvm::Constant *definition) { auto entity = LinkEntity::forProtocolRequirementsBaseDescriptor(proto); return defineAlias(entity, definition); } llvm::Constant *IRGenModule::getAddrOfAssociatedTypeDescriptor( AssociatedTypeDecl *assocType) { auto entity = LinkEntity::forAssociatedTypeDescriptor(assocType); return getAddrOfLLVMVariable(entity, ConstantInit(), DebugTypeInfo()); } llvm::GlobalValue *IRGenModule::defineAssociatedTypeDescriptor( AssociatedTypeDecl *assocType, llvm::Constant *definition) { auto entity = LinkEntity::forAssociatedTypeDescriptor(assocType); return defineAlias(entity, definition); } llvm::Constant *IRGenModule::getAddrOfAssociatedConformanceDescriptor( AssociatedConformance conformance) { auto entity = LinkEntity::forAssociatedConformanceDescriptor(conformance); return getAddrOfLLVMVariable(entity, ConstantInit(), DebugTypeInfo()); } llvm::GlobalValue *IRGenModule::defineAssociatedConformanceDescriptor( AssociatedConformance conformance, llvm::Constant *definition) { auto entity = LinkEntity::forAssociatedConformanceDescriptor(conformance); return defineAlias(entity, definition); } llvm::Constant *IRGenModule::getAddrOfBaseConformanceDescriptor( BaseConformance conformance) { auto entity = LinkEntity::forBaseConformanceDescriptor(conformance); return getAddrOfLLVMVariable(entity, ConstantInit(), DebugTypeInfo()); } llvm::GlobalValue *IRGenModule::defineBaseConformanceDescriptor( BaseConformance conformance, llvm::Constant *definition) { auto entity = LinkEntity::forBaseConformanceDescriptor(conformance); return defineAlias(entity, definition); } llvm::Constant *IRGenModule::getAddrOfProtocolConformanceDescriptor( const RootProtocolConformance *conformance, ConstantInit definition) { IRGen.addLazyWitnessTable(conformance); auto entity = LinkEntity::forProtocolConformanceDescriptor(conformance); return getAddrOfLLVMVariable(entity, definition, DebugTypeInfo()); } /// Fetch the declaration of the ivar initializer for the given class. Optional<llvm::Function*> IRGenModule::getAddrOfIVarInitDestroy( ClassDecl *cd, bool isDestroyer, bool isForeign, ForDefinition_t forDefinition) { auto silRef = SILDeclRef(cd, isDestroyer ? SILDeclRef::Kind::IVarDestroyer : SILDeclRef::Kind::IVarInitializer) .asForeign(isForeign); // Find the SILFunction for the ivar initializer or destroyer. if (auto silFn = getSILModule().lookUpFunction(silRef)) { return getAddrOfSILFunction(silFn, forDefinition); } return None; } /// Returns the address of a value-witness function. llvm::Function *IRGenModule::getAddrOfValueWitness(CanType abstractType, ValueWitness index, ForDefinition_t forDefinition) { LinkEntity entity = LinkEntity::forValueWitness(abstractType, index); llvm::Function *&entry = GlobalFuncs[entity]; if (entry) { if (forDefinition) updateLinkageForDefinition(*this, entry, entity); return entry; } auto signature = getValueWitnessSignature(index); LinkInfo link = LinkInfo::get(*this, entity, forDefinition); entry = createFunction(*this, link, signature); return entry; } /// Returns the address of a value-witness table. If a definition /// type is provided, the table is created with that type; the return /// value will be an llvm::GlobalValue. Otherwise, the result will /// have type WitnessTablePtrTy. llvm::Constant * IRGenModule::getAddrOfValueWitnessTable(CanType concreteType, ConstantInit definition) { LinkEntity entity = LinkEntity::forValueWitnessTable(concreteType); return getAddrOfLLVMVariable(entity, definition, DebugTypeInfo()); } static Address getAddrOfSimpleVariable(IRGenModule &IGM, llvm::DenseMap<LinkEntity, llvm::Constant*> &cache, LinkEntity entity, ForDefinition_t forDefinition) { auto alignment = entity.getAlignment(IGM); auto type = entity.getDefaultDeclarationType(IGM); // Check whether it's already cached. llvm::Constant *&entry = cache[entity]; if (entry) { auto existing = cast<llvm::GlobalVariable>(entry); assert(alignment == Alignment(existing->getAlignment())); if (forDefinition) updateLinkageForDefinition(IGM, existing, entity); return Address(entry, alignment); } // Otherwise, we need to create it. LinkInfo link = LinkInfo::get(IGM, entity, forDefinition); auto addr = createVariable(IGM, link, type, alignment); entry = addr; return Address(addr, alignment); } /// getAddrOfFieldOffset - Get the address of the global variable /// which contains an offset to apply to either an object (if direct) /// or a metadata object in order to find an offset to apply to an /// object (if indirect). /// /// The result is always a GlobalValue. Address IRGenModule::getAddrOfFieldOffset(VarDecl *var, ForDefinition_t forDefinition) { LinkEntity entity = LinkEntity::forFieldOffset(var); return getAddrOfSimpleVariable(*this, GlobalVars, entity, forDefinition); } Address IRGenModule::getAddrOfEnumCase(EnumElementDecl *Case, ForDefinition_t forDefinition) { LinkEntity entity = LinkEntity::forEnumCase(Case); auto addr = getAddrOfSimpleVariable(*this, GlobalVars, entity, forDefinition); auto *global = cast<llvm::GlobalVariable>(addr.getAddress()); global->setConstant(true); return addr; } void IRGenModule::emitNestedTypeDecls(DeclRange members) { for (Decl *member : members) { switch (member->getKind()) { case DeclKind::Import: case DeclKind::TopLevelCode: case DeclKind::Protocol: case DeclKind::Extension: case DeclKind::InfixOperator: case DeclKind::PrefixOperator: case DeclKind::PostfixOperator: case DeclKind::Param: case DeclKind::Module: case DeclKind::PrecedenceGroup: llvm_unreachable("decl not allowed in type context"); case DeclKind::IfConfig: case DeclKind::PoundDiagnostic: continue; case DeclKind::Func: case DeclKind::Var: case DeclKind::Subscript: // Handled in SIL. continue; case DeclKind::PatternBinding: case DeclKind::Accessor: case DeclKind::Constructor: case DeclKind::Destructor: case DeclKind::EnumCase: case DeclKind::EnumElement: case DeclKind::MissingMember: // Skip non-type members. continue; case DeclKind::AssociatedType: case DeclKind::GenericTypeParam: // Do nothing. continue; case DeclKind::TypeAlias: case DeclKind::OpaqueType: // Do nothing. continue; case DeclKind::Enum: emitEnumDecl(cast<EnumDecl>(member)); continue; case DeclKind::Struct: emitStructDecl(cast<StructDecl>(member)); continue; case DeclKind::Class: emitClassDecl(cast<ClassDecl>(member)); continue; } } } static bool shouldEmitCategory(IRGenModule &IGM, ExtensionDecl *ext) { for (auto conformance : ext->getLocalConformances()) { if (conformance->getProtocol()->isObjC()) return true; } for (auto member : ext->getMembers()) { if (auto func = dyn_cast<FuncDecl>(member)) { if (requiresObjCMethodDescriptor(func)) return true; } else if (auto constructor = dyn_cast<ConstructorDecl>(member)) { if (requiresObjCMethodDescriptor(constructor)) return true; } else if (auto var = dyn_cast<VarDecl>(member)) { if (requiresObjCPropertyDescriptor(IGM, var)) return true; } else if (auto subscript = dyn_cast<SubscriptDecl>(member)) { if (requiresObjCSubscriptDescriptor(IGM, subscript)) return true; } } return false; } void IRGenModule::emitExtension(ExtensionDecl *ext) { emitNestedTypeDecls(ext->getMembers()); addLazyConformances(ext); // Generate a category if the extension either introduces a // conformance to an ObjC protocol or introduces a method // that requires an Objective-C entry point. ClassDecl *origClass = ext->getSelfClassDecl(); if (!origClass) return; if (shouldEmitCategory(*this, ext)) { assert(origClass && !origClass->isForeign() && "foreign types cannot have categories emitted"); llvm::Constant *category = emitCategoryData(*this, ext); category = llvm::ConstantExpr::getBitCast(category, Int8PtrTy); auto *theClass = ext->getSelfClassDecl(); // Categories on class stubs are added to a separate list. if (theClass->checkAncestry(AncestryFlags::ResilientOther)) ObjCCategoriesOnStubs.push_back(category); else ObjCCategories.push_back(category); ObjCCategoryDecls.push_back(ext); } } /// Create an allocation on the stack. Address IRGenFunction::createAlloca(llvm::Type *type, Alignment alignment, const llvm::Twine &name) { llvm::AllocaInst *alloca = new llvm::AllocaInst(type, IGM.DataLayout.getAllocaAddrSpace(), name, AllocaIP); alloca->setAlignment(llvm::MaybeAlign(alignment.getValue()).valueOrOne()); return Address(alloca, alignment); } /// Create an allocation of an array on the stack. Address IRGenFunction::createAlloca(llvm::Type *type, llvm::Value *ArraySize, Alignment alignment, const llvm::Twine &name) { llvm::AllocaInst *alloca = new llvm::AllocaInst( type, IGM.DataLayout.getAllocaAddrSpace(), ArraySize, llvm::MaybeAlign(alignment.getValue()).valueOrOne(), name, AllocaIP); return Address(alloca, alignment); } /// Allocate a fixed-size buffer on the stack. Address IRGenFunction::createFixedSizeBufferAlloca(const llvm::Twine &name) { return createAlloca(IGM.getFixedBufferTy(), getFixedBufferAlignment(IGM), name); } /// Get or create a global string constant. /// /// \returns an i8* with a null terminator; note that embedded nulls /// are okay /// /// FIXME: willBeRelativelyAddressed is only needed to work around an ld64 bug /// resolving relative references to coalesceable symbols. /// It should be removed when fixed. rdar://problem/22674524 llvm::Constant *IRGenModule::getAddrOfGlobalString(StringRef data, bool willBeRelativelyAddressed) { // Check whether this string already exists. auto &entry = GlobalStrings[data]; if (entry.second) { // FIXME: Clear unnamed_addr if the global will be relative referenced // to work around an ld64 bug. rdar://problem/22674524 if (willBeRelativelyAddressed) entry.first->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::None); return entry.second; } entry = createStringConstant(data, willBeRelativelyAddressed); return entry.second; } /// Get or create a global UTF-16 string constant. /// /// \returns an i16* with a null terminator; note that embedded nulls /// are okay llvm::Constant *IRGenModule::getAddrOfGlobalUTF16String(StringRef utf8) { // Check whether this string already exists. auto &entry = GlobalUTF16Strings[utf8]; if (entry) return entry; // If not, first transcode it to UTF16. SmallVector<llvm::UTF16, 128> buffer(utf8.size() + 1); // +1 for ending nulls. const llvm::UTF8 *fromPtr = (const llvm::UTF8 *) utf8.data(); llvm::UTF16 *toPtr = &buffer[0]; (void) ConvertUTF8toUTF16(&fromPtr, fromPtr + utf8.size(), &toPtr, toPtr + utf8.size(), llvm::strictConversion); // The length of the transcoded string in UTF-8 code points. size_t utf16Length = toPtr - &buffer[0]; // Null-terminate the UTF-16 string. *toPtr = 0; ArrayRef<llvm::UTF16> utf16(&buffer[0], utf16Length + 1); auto init = llvm::ConstantDataArray::get(getLLVMContext(), utf16); auto global = new llvm::GlobalVariable(Module, init->getType(), true, llvm::GlobalValue::PrivateLinkage, init); global->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); // Drill down to make an i16*. auto zero = llvm::ConstantInt::get(SizeTy, 0); llvm::Constant *indices[] = { zero, zero }; auto address = llvm::ConstantExpr::getInBoundsGetElementPtr( global->getValueType(), global, indices); // Cache and return. entry = address; return address; } /// Do we have to use resilient access patterns when working with this /// declaration? /// /// IRGen is primarily concerned with resilient handling of the following: /// - For structs, a struct's size might change /// - For enums, new cases can be added /// - For classes, the superclass might change the size or number /// of stored properties bool IRGenModule::isResilient(NominalTypeDecl *D, ResilienceExpansion expansion) { if (D->getModuleContext()->getBypassResilience()) return false; if (expansion == ResilienceExpansion::Maximal && Types.getLoweringMode() == TypeConverter::Mode::CompletelyFragile) { return false; } return D->isResilient(getSwiftModule(), expansion); } /// Do we have to use resilient access patterns when working with this /// class? /// /// For classes, this means that virtual method calls use dispatch thunks /// rather than accessing metadata members directly. bool IRGenModule::hasResilientMetadata(ClassDecl *D, ResilienceExpansion expansion) { if (expansion == ResilienceExpansion::Maximal && Types.getLoweringMode() == TypeConverter::Mode::CompletelyFragile) { return false; } return D->hasResilientMetadata(getSwiftModule(), expansion); } // The most general resilience expansion where the given declaration is visible. ResilienceExpansion IRGenModule::getResilienceExpansionForAccess(NominalTypeDecl *decl) { if (decl->getModuleContext() == getSwiftModule() && decl->getEffectiveAccess() < AccessLevel::Public) return ResilienceExpansion::Maximal; return ResilienceExpansion::Minimal; } // The most general resilience expansion which has knowledge of the declaration's // layout. Calling isResilient() with this scope will always return false. ResilienceExpansion IRGenModule::getResilienceExpansionForLayout(NominalTypeDecl *decl) { if (Types.getLoweringMode() == TypeConverter::Mode::CompletelyFragile) return ResilienceExpansion::Minimal; if (isResilient(decl, ResilienceExpansion::Minimal)) return ResilienceExpansion::Maximal; return getResilienceExpansionForAccess(decl); } // The most general resilience expansion which has knowledge of the global // variable's layout. ResilienceExpansion IRGenModule::getResilienceExpansionForLayout(SILGlobalVariable *global) { if (hasPublicVisibility(global->getLinkage())) return ResilienceExpansion::Minimal; return ResilienceExpansion::Maximal; } llvm::Function * IRGenModule::getAddrOfGenericWitnessTableInstantiationFunction( const NormalProtocolConformance *conf) { auto forDefinition = ForDefinition; LinkEntity entity = LinkEntity::forGenericProtocolWitnessTableInstantiationFunction(conf); llvm::Function *&entry = GlobalFuncs[entity]; if (entry) { if (forDefinition) updateLinkageForDefinition(*this, entry, entity); return entry; } auto fnType = llvm::FunctionType::get( VoidTy, {WitnessTablePtrTy, TypeMetadataPtrTy, Int8PtrPtrTy}, /*varargs*/ false); Signature signature(fnType, llvm::AttributeList(), DefaultCC); LinkInfo link = LinkInfo::get(*this, entity, forDefinition); entry = createFunction(*this, link, signature); return entry; } /// Fetch the lazy witness table access function for a protocol conformance. llvm::Function * IRGenModule::getAddrOfWitnessTableLazyAccessFunction( const NormalProtocolConformance *conf, CanType conformingType, ForDefinition_t forDefinition) { LinkEntity entity = LinkEntity::forProtocolWitnessTableLazyAccessFunction(conf, conformingType); llvm::Function *&entry = GlobalFuncs[entity]; if (entry) { if (forDefinition) updateLinkageForDefinition(*this, entry, entity); return entry; } llvm::FunctionType *fnType = llvm::FunctionType::get(WitnessTablePtrTy, false); Signature signature(fnType, llvm::AttributeList(), DefaultCC); LinkInfo link = LinkInfo::get(*this, entity, forDefinition); entry = createFunction(*this, link, signature); ApplyIRLinkage({link.getLinkage(), link.getVisibility(), link.getDLLStorage()}) .to(entry, link.isForDefinition()); return entry; } /// Get or create a witness table cache variable. These are an /// implementation detail of witness table lazy access functions. llvm::Constant * IRGenModule::getAddrOfWitnessTableLazyCacheVariable( const NormalProtocolConformance *conf, CanType conformingType, ForDefinition_t forDefinition) { assert(!conformingType->hasArchetype()); LinkEntity entity = LinkEntity::forProtocolWitnessTableLazyCacheVariable(conf, conformingType); auto variable = getAddrOfLLVMVariable(entity, forDefinition, DebugTypeInfo()); // Zero-initialize if we're asking for a definition. if (forDefinition) { cast<llvm::GlobalVariable>(variable)->setInitializer( llvm::ConstantPointerNull::get(WitnessTablePtrTy)); } return variable; } /// Look up the address of a witness table. /// /// This can only be used with non-dependent conformances. llvm::Constant* IRGenModule::getAddrOfWitnessTable(const RootProtocolConformance *conf, ConstantInit definition) { IRGen.addLazyWitnessTable(conf); auto entity = LinkEntity::forProtocolWitnessTable(conf); return getAddrOfLLVMVariable(entity, definition, DebugTypeInfo()); } /// Look up the address of a witness table pattern. /// /// This can only be used with dependent conformances from inside the /// defining module. llvm::Constant* IRGenModule::getAddrOfWitnessTablePattern(const NormalProtocolConformance *conf, ConstantInit definition) { IRGen.addLazyWitnessTable(conf); auto entity = LinkEntity::forProtocolWitnessTablePattern(conf); return getAddrOfLLVMVariable(entity, definition, DebugTypeInfo()); } /// Look up the address of a differentiability witness. llvm::Constant *IRGenModule::getAddrOfDifferentiabilityWitness( const SILDifferentiabilityWitness *witness, ConstantInit definition) { auto entity = LinkEntity::forDifferentiabilityWitness(witness); return getAddrOfLLVMVariable(entity, definition, DebugTypeInfo()); } llvm::Function * IRGenModule::getAddrOfAssociatedTypeWitnessTableAccessFunction( const NormalProtocolConformance *conformance, const AssociatedConformance &association) { auto forDefinition = ForDefinition; LinkEntity entity = LinkEntity::forAssociatedTypeWitnessTableAccessFunction(conformance, association); llvm::Function *&entry = GlobalFuncs[entity]; if (entry) { if (forDefinition) updateLinkageForDefinition(*this, entry, entity); return entry; } auto signature = getAssociatedTypeWitnessTableAccessFunctionSignature(); LinkInfo link = LinkInfo::get(*this, entity, forDefinition); entry = createFunction(*this, link, signature); return entry; } llvm::Function * IRGenModule::getAddrOfDefaultAssociatedConformanceAccessor( AssociatedConformance requirement) { auto forDefinition = ForDefinition; LinkEntity entity = LinkEntity::forDefaultAssociatedConformanceAccessor(requirement); llvm::Function *&entry = GlobalFuncs[entity]; if (entry) { if (forDefinition) updateLinkageForDefinition(*this, entry, entity); return entry; } auto signature = getAssociatedTypeWitnessTableAccessFunctionSignature(); LinkInfo link = LinkInfo::get(*this, entity, forDefinition); entry = createFunction(*this, link, signature); return entry; } llvm::Function * IRGenModule::getAddrOfContinuationPrototype(CanSILFunctionType fnType) { LinkEntity entity = LinkEntity::forCoroutineContinuationPrototype(fnType); llvm::Function *&entry = GlobalFuncs[entity]; if (entry) return entry; auto signature = Signature::forCoroutineContinuation(*this, fnType); LinkInfo link = LinkInfo::get(*this, entity, NotForDefinition); entry = createFunction(*this, link, signature); return entry; } /// Should we be defining the given helper function? static llvm::Function *shouldDefineHelper(IRGenModule &IGM, llvm::Constant *fn, bool setIsNoInline) { auto *def = dyn_cast<llvm::Function>(fn); if (!def) return nullptr; if (!def->empty()) return nullptr; def->setAttributes(IGM.constructInitialAttributes()); ApplyIRLinkage(IRLinkage::InternalLinkOnceODR).to(def); def->setDoesNotThrow(); def->setCallingConv(IGM.DefaultCC); if (setIsNoInline) def->addFnAttr(llvm::Attribute::NoInline); return def; } /// Get or create a helper function with the given name and type, lazily /// using the given generation function to fill in its body. /// /// The helper function will be shared between translation units within the /// current linkage unit, so choose the name carefully to ensure that it /// does not collide with any other helper function. In general, it should /// be a Swift-specific C reserved name; that is, it should start with // "__swift". llvm::Constant * IRGenModule::getOrCreateHelperFunction(StringRef fnName, llvm::Type *resultTy, ArrayRef<llvm::Type*> paramTys, llvm::function_ref<void(IRGenFunction &IGF)> generate, bool setIsNoInline, bool forPrologue) { llvm::FunctionType *fnTy = llvm::FunctionType::get(resultTy, paramTys, false); llvm::Constant *fn = cast<llvm::Constant>( Module.getOrInsertFunction(fnName, fnTy).getCallee()); if (llvm::Function *def = shouldDefineHelper(*this, fn, setIsNoInline)) { IRGenFunction IGF(*this, def); if (DebugInfo && !forPrologue) DebugInfo->emitArtificialFunction(IGF, def); generate(IGF); } return fn; }
/* * Copyright 2011-2022 Branimir Karadzic. All rights reserved. * License: https://github.com/bkaradzic/bgfx/blob/master/LICENSE */ #include "common.h" #include "bgfx_utils.h" #include "imgui/imgui.h" namespace { struct PosColorVertex { float m_x; float m_y; float m_z; uint32_t m_abgr; static void init() { ms_layout .begin() .add(bgfx::Attrib::Position, 3, bgfx::AttribType::Float) .add(bgfx::Attrib::Color0, 4, bgfx::AttribType::Uint8, true) .end(); } static bgfx::VertexLayout ms_layout; }; bgfx::VertexLayout PosColorVertex::ms_layout; struct PosColorTexCoord0Vertex { float m_x; float m_y; float m_z; uint32_t m_rgba; float m_u; float m_v; static void init() { ms_layout .begin() .add(bgfx::Attrib::Position, 3, bgfx::AttribType::Float) .add(bgfx::Attrib::Color0, 4, bgfx::AttribType::Uint8, true) .add(bgfx::Attrib::TexCoord0, 2, bgfx::AttribType::Float) .end(); } static bgfx::VertexLayout ms_layout; }; bgfx::VertexLayout PosColorTexCoord0Vertex::ms_layout; static PosColorVertex s_cubeVertices[8] = { {-1.0f, 1.0f, 1.0f, 0xff000000 }, { 1.0f, 1.0f, 1.0f, 0xff0000ff }, {-1.0f, -1.0f, 1.0f, 0xff00ff00 }, { 1.0f, -1.0f, 1.0f, 0xff00ffff }, {-1.0f, 1.0f, -1.0f, 0xffff0000 }, { 1.0f, 1.0f, -1.0f, 0xffff00ff }, {-1.0f, -1.0f, -1.0f, 0xffffff00 }, { 1.0f, -1.0f, -1.0f, 0xffffffff }, }; static const uint16_t s_cubeIndices[36] = { 0, 1, 2, // 0 1, 3, 2, 4, 6, 5, // 2 5, 6, 7, 0, 2, 4, // 4 4, 2, 6, 1, 5, 3, // 6 5, 7, 3, 0, 4, 1, // 8 4, 5, 1, 2, 3, 6, // 10 6, 3, 7, }; static float s_texelHalf = 0.0f; static bool s_flipV = false; inline void mtxProj(float* _result, float _fovy, float _aspect, float _near, float _far) { bx::mtxProj(_result, _fovy, _aspect, _near, _far, s_flipV); } void screenSpaceQuad(float _textureWidth, float _textureHeight, bool _originBottomLeft = false, float _width = 1.0f, float _height = 1.0f) { if (3 == bgfx::getAvailTransientVertexBuffer(3, PosColorTexCoord0Vertex::ms_layout) ) { bgfx::TransientVertexBuffer vb; bgfx::allocTransientVertexBuffer(&vb, 3, PosColorTexCoord0Vertex::ms_layout); PosColorTexCoord0Vertex* vertex = (PosColorTexCoord0Vertex*)vb.data; const float zz = 0.0f; const float minx = -_width; const float maxx = _width; const float miny = 0.0f; const float maxy = _height*2.0f; const float texelHalfW = s_texelHalf/_textureWidth; const float texelHalfH = s_texelHalf/_textureHeight; const float minu = -1.0f + texelHalfW; const float maxu = 1.0f + texelHalfW; float minv = texelHalfH; float maxv = 2.0f + texelHalfH; if (_originBottomLeft) { float tmp = minv; minv = maxv; maxv = tmp; minv -= 1.0f; maxv -= 1.0f; } vertex[0].m_x = minx; vertex[0].m_y = miny; vertex[0].m_z = zz; vertex[0].m_rgba = 0xffffffff; vertex[0].m_u = minu; vertex[0].m_v = minv; vertex[1].m_x = maxx; vertex[1].m_y = miny; vertex[1].m_z = zz; vertex[1].m_rgba = 0xffffffff; vertex[1].m_u = maxu; vertex[1].m_v = minv; vertex[2].m_x = maxx; vertex[2].m_y = maxy; vertex[2].m_z = zz; vertex[2].m_rgba = 0xffffffff; vertex[2].m_u = maxu; vertex[2].m_v = maxv; bgfx::setVertexBuffer(0, &vb); } } class ExampleOIT : public entry::AppI { public: ExampleOIT(const char* _name, const char* _description, const char* _url) : entry::AppI(_name, _description, _url) { } void init(int32_t _argc, const char* const* _argv, uint32_t _width, uint32_t _height) override { Args args(_argc, _argv); m_width = _width; m_height = _height; m_debug = BGFX_DEBUG_NONE; m_reset = BGFX_RESET_VSYNC; bgfx::Init init; init.type = args.m_type; init.vendorId = args.m_pciId; init.resolution.width = m_width; init.resolution.height = m_height; init.resolution.reset = m_reset; bgfx::init(init); // Enable debug text. bgfx::setDebug(m_debug); // Create vertex stream declaration. PosColorVertex::init(); PosColorTexCoord0Vertex::init(); // Get renderer capabilities info. const bgfx::Caps* caps = bgfx::getCaps(); // Setup root path for binary shaders. Shader binaries are different // for each renderer. switch (caps->rendererType) { default: break; case bgfx::RendererType::OpenGL: case bgfx::RendererType::OpenGLES: s_flipV = true; break; } // Imgui. imguiCreate(); // Create static vertex buffer. m_vbh = bgfx::createVertexBuffer( bgfx::makeRef(s_cubeVertices, sizeof(s_cubeVertices) ) , PosColorVertex::ms_layout ); // Create static index buffer. m_ibh = bgfx::createIndexBuffer(bgfx::makeRef(s_cubeIndices, sizeof(s_cubeIndices) ) ); // Create texture sampler uniforms. s_texColor0 = bgfx::createUniform("s_texColor0", bgfx::UniformType::Sampler); s_texColor1 = bgfx::createUniform("s_texColor1", bgfx::UniformType::Sampler); u_color = bgfx::createUniform("u_color", bgfx::UniformType::Vec4); m_blend = loadProgram("vs_oit", "fs_oit" ); m_wbSeparatePass = loadProgram("vs_oit", "fs_oit_wb_separate" ); m_wbSeparateBlit = loadProgram("vs_oit_blit", "fs_oit_wb_separate_blit" ); m_wbPass = loadProgram("vs_oit", "fs_oit_wb" ); m_wbBlit = loadProgram("vs_oit_blit", "fs_oit_wb_blit" ); m_fbtextures[0].idx = bgfx::kInvalidHandle; m_fbtextures[1].idx = bgfx::kInvalidHandle; m_fbh.idx = bgfx::kInvalidHandle; m_mode = 1; m_frontToBack = true; m_fadeInOut = false; m_oldWidth = 0; m_oldHeight = 0; m_oldReset = m_reset; m_mrtSupported = true && 2 <= caps->limits.maxFBAttachments && bgfx::isTextureValid(0, false, 1, bgfx::TextureFormat::RGBA16F, BGFX_TEXTURE_RT) && bgfx::isTextureValid(0, false, 1, bgfx::TextureFormat::R16F, BGFX_TEXTURE_RT) ; m_timeOffset = bx::getHPCounter(); } int shutdown() override { // Cleanup. imguiDestroy(); if (bgfx::isValid(m_fbh) ) { bgfx::destroy(m_fbh); } bgfx::destroy(m_ibh); bgfx::destroy(m_vbh); bgfx::destroy(m_blend); bgfx::destroy(m_wbSeparatePass); bgfx::destroy(m_wbSeparateBlit); bgfx::destroy(m_wbPass); bgfx::destroy(m_wbBlit); bgfx::destroy(s_texColor0); bgfx::destroy(s_texColor1); bgfx::destroy(u_color); // Shutdown bgfx. bgfx::shutdown(); return 0; } bool update() override { if (!entry::processEvents(m_width, m_height, m_debug, m_reset, &m_mouseState) ) { imguiBeginFrame(m_mouseState.m_mx , m_mouseState.m_my , (m_mouseState.m_buttons[entry::MouseButton::Left ] ? IMGUI_MBUT_LEFT : 0) | (m_mouseState.m_buttons[entry::MouseButton::Right ] ? IMGUI_MBUT_RIGHT : 0) | (m_mouseState.m_buttons[entry::MouseButton::Middle] ? IMGUI_MBUT_MIDDLE : 0) , m_mouseState.m_mz , uint16_t(m_width) , uint16_t(m_height) ); showExampleDialog(this , !m_mrtSupported ? "MRT or frame buffer texture format are not supported." : NULL ); if (m_mrtSupported) { if (m_oldWidth != m_width || m_oldHeight != m_height || m_oldReset != m_reset || !bgfx::isValid(m_fbh) ) { // Recreate variable size render targets when resolution changes. m_oldWidth = m_width; m_oldHeight = m_height; m_oldReset = m_reset; if (bgfx::isValid(m_fbh) ) { bgfx::destroy(m_fbh); } m_fbtextures[0] = bgfx::createTexture2D(uint16_t(m_width), uint16_t(m_height), false, 1, bgfx::TextureFormat::RGBA16F, BGFX_TEXTURE_RT); m_fbtextures[1] = bgfx::createTexture2D(uint16_t(m_width), uint16_t(m_height), false, 1, bgfx::TextureFormat::R16F, BGFX_TEXTURE_RT); m_fbh = bgfx::createFrameBuffer(BX_COUNTOF(m_fbtextures), m_fbtextures, true); } ImGui::SetNextWindowPos( ImVec2(m_width - m_width / 5.0f - 10.0f, 10.0f) , ImGuiCond_FirstUseEver ); ImGui::SetNextWindowSize( ImVec2(m_width / 5.0f, m_height / 3.0f) , ImGuiCond_FirstUseEver ); ImGui::Begin("Settings" , NULL , 0 ); ImGui::Separator(); ImGui::Text("Blend mode:"); ImGui::RadioButton("None", &m_mode, 0); ImGui::RadioButton("Separate", &m_mode, 1); ImGui::RadioButton("MRT Independent", &m_mode, 2); ImGui::Separator(); ImGui::Checkbox("Front to back", &m_frontToBack); ImGui::Checkbox("Fade in/out", &m_fadeInOut); ImGui::End(); // Set view 0 default viewport. bgfx::setViewRect(0, 0, 0, uint16_t(m_width), uint16_t(m_height) ); bgfx::setViewRect(1, 0, 0, uint16_t(m_width), uint16_t(m_height) ); int64_t now = bx::getHPCounter(); const double freq = double(bx::getHPFrequency() ); float time = (float)( (now-m_timeOffset)/freq); // Reference(s): // - Weighted, Blended Order-Independent Transparency // https://web.archive.org/save/http://jcgt.org/published/0002/02/09/ // https://web.archive.org/web/20181126040455/http://casual-effects.blogspot.com/2014/03/weighted-blended-order-independent.html // const bx::Vec3 at = { 0.0f, 0.0f, 0.0f }; const bx::Vec3 eye = { 0.0f, 0.0f, -7.0f }; float view[16]; float proj[16]; // Set view and projection matrix for view 0. bx::mtxLookAt(view, eye, at); mtxProj(proj, 60.0f, float(m_width)/float(m_height), 0.1f, 100.0f); bgfx::setViewTransform(0, view, proj); // Set palette color for index 0 bgfx::setPaletteColor(0, 0.0f, 0.0f, 0.0f, 0.0f); // Set palette color for index 1 bgfx::setPaletteColor(1, 1.0f, 1.0f, 1.0f, 1.0f); bgfx::setViewClear(0 , BGFX_CLEAR_COLOR|BGFX_CLEAR_DEPTH , 1.0f // Depth , 0 // Stencil , 0 // FB texture 0, color palette 0 , 1 == m_mode ? 1 : 0 // FB texture 1, color palette 1 ); bgfx::setViewClear(1 , BGFX_CLEAR_COLOR|BGFX_CLEAR_DEPTH , 1.0f // Depth , 0 // Stencil , 0 // Color palette 0 ); bgfx::FrameBufferHandle invalid = BGFX_INVALID_HANDLE; bgfx::setViewFrameBuffer(0, 0 == m_mode ? invalid : m_fbh); // Set view and projection matrix for view 1. bx::mtxIdentity(view); const bgfx::Caps* caps = bgfx::getCaps(); bx::mtxOrtho(proj, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 100.0f, 0.0f, caps->homogeneousDepth); bgfx::setViewTransform(1, view, proj); for (uint32_t depth = 0; depth < 3; ++depth) { uint32_t zz = m_frontToBack ? 2-depth : depth; for (uint32_t yy = 0; yy < 3; ++yy) { for (uint32_t xx = 0; xx < 3; ++xx) { float color[4] = { xx*1.0f/3.0f, zz*1.0f/3.0f, yy*1.0f/3.0f, 0.5f }; if (m_fadeInOut && zz == 1) { color[3] = bx::sin(time*3.0f)*0.49f+0.5f; } bgfx::setUniform(u_color, color); BX_UNUSED(time); float mtx[16]; bx::mtxRotateXY(mtx, time*0.023f + xx*0.21f, time*0.03f + yy*0.37f); //mtxIdentity(mtx); mtx[12] = -2.5f + float(xx)*2.5f; mtx[13] = -2.5f + float(yy)*2.5f; mtx[14] = -2.5f + float(zz)*2.5f; // Set transform for draw call. bgfx::setTransform(mtx); // Set vertex and index buffer. bgfx::setVertexBuffer(0, m_vbh); bgfx::setIndexBuffer(m_ibh); const uint64_t state = 0 | BGFX_STATE_CULL_CW | BGFX_STATE_WRITE_RGB | BGFX_STATE_WRITE_A | BGFX_STATE_DEPTH_TEST_LESS | BGFX_STATE_MSAA ; const uint64_t stateNoDepth = 0 | BGFX_STATE_CULL_CW | BGFX_STATE_WRITE_RGB | BGFX_STATE_WRITE_A | BGFX_STATE_DEPTH_TEST_ALWAYS | BGFX_STATE_MSAA ; bgfx::ProgramHandle program = BGFX_INVALID_HANDLE; switch (m_mode) { case 0: // Set vertex and fragment shaders. program = m_blend; // Set render states. bgfx::setState(state | BGFX_STATE_BLEND_ALPHA ); break; case 1: // Set vertex and fragment shaders. program = m_wbSeparatePass; // Set render states. bgfx::setState(stateNoDepth | BGFX_STATE_BLEND_FUNC_SEPARATE(BGFX_STATE_BLEND_ONE, BGFX_STATE_BLEND_ONE, BGFX_STATE_BLEND_ZERO, BGFX_STATE_BLEND_INV_SRC_ALPHA) ); break; default: // Set vertex and fragment shaders. program = m_wbPass; // Set render states. bgfx::setState(stateNoDepth | BGFX_STATE_BLEND_FUNC(BGFX_STATE_BLEND_ONE, BGFX_STATE_BLEND_ONE) | BGFX_STATE_BLEND_INDEPENDENT , 0 | BGFX_STATE_BLEND_FUNC_RT_1(BGFX_STATE_BLEND_ZERO, BGFX_STATE_BLEND_SRC_COLOR) ); break; } // Submit primitive for rendering to view 0. bgfx::submit(0, program); } } } if (0 != m_mode) { bgfx::setTexture(0, s_texColor0, m_fbtextures[0]); bgfx::setTexture(1, s_texColor1, m_fbtextures[1]); bgfx::setState(0 | BGFX_STATE_WRITE_RGB | BGFX_STATE_BLEND_FUNC(BGFX_STATE_BLEND_INV_SRC_ALPHA, BGFX_STATE_BLEND_SRC_ALPHA) ); screenSpaceQuad( (float)m_width, (float)m_height, s_flipV); bgfx::submit(1 , 1 == m_mode ? m_wbSeparateBlit : m_wbBlit ); } } imguiEndFrame(); // Advance to next frame. Rendering thread will be kicked to // process submitted rendering primitives. bgfx::frame(); return true; } return false; } uint32_t m_width; uint32_t m_height; uint32_t m_debug; uint32_t m_reset; int32_t m_mode; bool m_frontToBack; bool m_fadeInOut; bool m_mrtSupported; uint32_t m_oldWidth; uint32_t m_oldHeight; uint32_t m_oldReset; entry::MouseState m_mouseState; int64_t m_timeOffset; bgfx::VertexBufferHandle m_vbh; bgfx::IndexBufferHandle m_ibh; bgfx::UniformHandle s_texColor0; bgfx::UniformHandle s_texColor1; bgfx::UniformHandle u_color; bgfx::ProgramHandle m_blend; bgfx::ProgramHandle m_wbSeparatePass; bgfx::ProgramHandle m_wbSeparateBlit; bgfx::ProgramHandle m_wbPass; bgfx::ProgramHandle m_wbBlit; bgfx::TextureHandle m_fbtextures[2]; bgfx::FrameBufferHandle m_fbh; }; } // namespace ENTRY_IMPLEMENT_MAIN( ExampleOIT , "19-oit" , "Weighted, Blended Order Independent Transparency." , "https://bkaradzic.github.io/bgfx/examples.html#oit" );
// This file is licensed under the Elastic License 2.0. Copyright 2021 StarRocks Limited. #include "exprs/vectorized/like_predicate.h" #include <memory> #include "column/column_builder.h" #include "column/column_helper.h" #include "column/column_viewer.h" #include "exprs/vectorized/binary_function.h" #include "glog/logging.h" #include "gutil/strings/substitute.h" #include "runtime/vectorized/Volnitsky.h" namespace starrocks::vectorized { // A regex to match any regex pattern is equivalent to a substring search. static const RE2 SUBSTRING_RE(R"((?:\.\*)*([^\.\^\{\[\(\|\)\]\}\+\*\?\$\\]*)(?:\.\*)*)"); // A regex to match any regex pattern which is equivalent to matching a constant string // at the end of the string values. static const RE2 ENDS_WITH_RE(R"((?:\.\*)*([^\.\^\{\[\(\|\)\]\}\+\*\?\$\\]*)\$)"); // A regex to match any regex pattern which is equivalent to matching a constant string // at the end of the string values. static const RE2 STARTS_WITH_RE(R"(\^([^\.\^\{\[\(\|\)\]\}\+\*\?\$\\]*)(?:\.\*)*)"); // A regex to match any regex pattern which is equivalent to a constant string match. static const RE2 EQUALS_RE(R"(\^([^\.\^\{\[\(\|\)\]\}\+\*\?\$\\]*)\$)"); static const re2::RE2 LIKE_SUBSTRING_RE(R"((?:%+)(((\\%)|(\\_)|([^%_]))+)(?:%+))"); static const re2::RE2 LIKE_ENDS_WITH_RE(R"((?:%+)(((\\%)|(\\_)|([^%_]))+))"); static const re2::RE2 LIKE_STARTS_WITH_RE(R"((((\\%)|(\\_)|([^%_]))+)(?:%+))"); static const re2::RE2 LIKE_EQUALS_RE(R"((((\\%)|(\\_)|([^%_]))+))"); Status LikePredicate::hs_compile_and_alloc_scratch(const std::string& pattern, LikePredicateState* state, starrocks_udf::FunctionContext* context, const Slice& slice) { if (hs_compile(pattern.c_str(), HS_FLAG_ALLOWEMPTY | HS_FLAG_DOTALL | HS_FLAG_UTF8 | HS_FLAG_SINGLEMATCH, HS_MODE_BLOCK, nullptr, &state->database, &state->compile_err) != HS_SUCCESS) { std::stringstream error; error << "Invalid regex expression: " << slice.data << ": " << state->compile_err->message; context->set_error(error.str().c_str()); hs_free_compile_error(state->compile_err); return Status::InvalidArgument(error.str()); } if (hs_alloc_scratch(state->database, &state->scratch) != HS_SUCCESS) { std::stringstream error; error << "ERROR: Unable to allocate scratch space."; context->set_error(error.str().c_str()); hs_free_database(state->database); return Status::InvalidArgument(error.str()); } return Status::OK(); } // when pattern is one of (EQUALS | SUBSTRING | STARTS_WITH | ENDS_WITH) or variable value // we use Re2. // when pattern is a constant value except ((EQUALS | SUBSTRING | STARTS_WITH | ENDS_WITH) variable value) // we use hyperscan. // like predicate Status LikePredicate::like_prepare(starrocks_udf::FunctionContext* context, starrocks_udf::FunctionContext::FunctionStateScope scope) { if (scope != FunctionContext::THREAD_LOCAL) { return Status::OK(); } // @todo: should replace to mem pool auto state = new LikePredicateState(); state->function = &like_fn; context->set_function_state(scope, state); // go row regex if (!context->is_constant_column(1)) { return Status::OK(); } auto column = context->get_constant_column(1); if (column->only_null() || column->is_null(0)) { return Status::OK(); } auto pattern = ColumnHelper::get_const_value<TYPE_VARCHAR>(column); std::string pattern_str = pattern.to_string(); std::string search_string; if (RE2::FullMatch(pattern_str, LIKE_ENDS_WITH_RE, &search_string)) { remove_escape_character(&search_string); state->set_search_string(search_string); state->function = &constant_ends_with_fn; } else if (RE2::FullMatch(pattern_str, LIKE_STARTS_WITH_RE, &search_string)) { remove_escape_character(&search_string); state->set_search_string(search_string); state->function = &constant_starts_with_fn; } else if (RE2::FullMatch(pattern_str, LIKE_EQUALS_RE, &search_string)) { remove_escape_character(&search_string); state->set_search_string(search_string); state->function = &constant_equals_fn; } else if (RE2::FullMatch(pattern_str, LIKE_SUBSTRING_RE, &search_string)) { remove_escape_character(&search_string); state->set_search_string(search_string); state->function = &constant_substring_fn; } else { auto re_pattern = LikePredicate::template convert_like_pattern<true>(context, pattern); RETURN_IF_ERROR(hs_compile_and_alloc_scratch(re_pattern, state, context, pattern)); } return Status::OK(); } Status LikePredicate::like_close(starrocks_udf::FunctionContext* context, starrocks_udf::FunctionContext::FunctionStateScope scope) { if (scope == FunctionContext::THREAD_LOCAL) { auto state = reinterpret_cast<LikePredicateState*>(context->get_function_state(FunctionContext::THREAD_LOCAL)); delete state; } return Status::OK(); } ColumnPtr LikePredicate::like(FunctionContext* context, const starrocks::vectorized::Columns& columns) { auto state = reinterpret_cast<LikePredicateState*>(context->get_function_state(FunctionContext::THREAD_LOCAL)); return (state->function)(context, columns); } // regex predicate Status LikePredicate::regex_prepare(starrocks_udf::FunctionContext* context, starrocks_udf::FunctionContext::FunctionStateScope scope) { if (scope != FunctionContext::THREAD_LOCAL) { return Status::OK(); } // @todo: should replace to mem pool LikePredicateState* state = new LikePredicateState(); context->set_function_state(scope, state); state->function = &regex_fn; // go row regex if (!context->is_constant_column(1)) { return Status::OK(); } auto column = context->get_constant_column(1); if (column->only_null() || column->is_null(0)) { return Status::OK(); } auto pattern = ColumnHelper::get_const_value<TYPE_VARCHAR>(column); std::string pattern_str = pattern.to_string(); std::string search_string; // The following four conditionals check if the pattern is a constant string, // starts with a constant string and is followed by any number of wildcard characters, // ends with a constant string and is preceded by any number of wildcard characters or // has a constant substring surrounded on both sides by any number of wildcard // characters. In any of these conditions, we can search for the pattern more // efficiently by using our own string match functions rather than regex matching. if (RE2::FullMatch(pattern_str, EQUALS_RE, &search_string)) { state->set_search_string(search_string); state->function = &constant_equals_fn; } else if (RE2::FullMatch(pattern_str, STARTS_WITH_RE, &search_string)) { state->set_search_string(search_string); state->function = &constant_starts_with_fn; } else if (RE2::FullMatch(pattern_str, ENDS_WITH_RE, &search_string)) { state->set_search_string(search_string); state->function = &constant_ends_with_fn; } else if (RE2::FullMatch(pattern_str, SUBSTRING_RE, &search_string)) { state->set_search_string(search_string); state->function = &constant_substring_fn; } else { std::string re_pattern(pattern.data, pattern.size); RETURN_IF_ERROR(hs_compile_and_alloc_scratch(re_pattern, state, context, pattern)); } return Status::OK(); } Status LikePredicate::regex_close(starrocks_udf::FunctionContext* context, starrocks_udf::FunctionContext::FunctionStateScope scope) { if (scope == FunctionContext::THREAD_LOCAL) { LikePredicateState* state = reinterpret_cast<LikePredicateState*>(context->get_function_state(FunctionContext::THREAD_LOCAL)); delete state; } return Status::OK(); } ColumnPtr LikePredicate::regex(FunctionContext* context, const Columns& columns) { auto state = reinterpret_cast<LikePredicateState*>(context->get_function_state(FunctionContext::THREAD_LOCAL)); return (state->function)(context, columns); } // like_fn ColumnPtr LikePredicate::like_fn(FunctionContext* context, const starrocks::vectorized::Columns& columns) { return regex_match(context, columns, true); } ColumnPtr LikePredicate::regex_fn(FunctionContext* context, const Columns& columns) { return regex_match(context, columns, false); } // constant_ends DEFINE_BINARY_FUNCTION_WITH_IMPL(ConstantEndsImpl, value, pattern) { return (value.size >= pattern.size) && (pattern == Slice(value.data + value.size - pattern.size, pattern.size)); } ColumnPtr LikePredicate::constant_ends_with_fn(FunctionContext* context, const starrocks::vectorized::Columns& columns) { auto state = reinterpret_cast<LikePredicateState*>(context->get_function_state(FunctionContext::THREAD_LOCAL)); auto value = VECTORIZED_FN_ARGS(0); auto pattern = state->_search_string_column; return VectorizedStrictBinaryFunction<ConstantEndsImpl>::evaluate<TYPE_VARCHAR, TYPE_BOOLEAN>(value, pattern); } // constant_starts DEFINE_BINARY_FUNCTION_WITH_IMPL(ConstantStartsImpl, value, pattern) { return (value.size >= pattern.size) && (pattern == Slice(value.data, pattern.size)); } ColumnPtr LikePredicate::constant_starts_with_fn(FunctionContext* context, const starrocks::vectorized::Columns& columns) { auto state = reinterpret_cast<LikePredicateState*>(context->get_function_state(FunctionContext::THREAD_LOCAL)); auto value = VECTORIZED_FN_ARGS(0); auto pattern = state->_search_string_column; return VectorizedStrictBinaryFunction<ConstantStartsImpl>::evaluate<TYPE_VARCHAR, TYPE_BOOLEAN>(value, pattern); } // constant_equals DEFINE_BINARY_FUNCTION_WITH_IMPL(ConstantEqualsImpl, value, pattern) { return value == pattern; } ColumnPtr LikePredicate::constant_equals_fn(FunctionContext* context, const starrocks::vectorized::Columns& columns) { auto state = reinterpret_cast<LikePredicateState*>(context->get_function_state(FunctionContext::THREAD_LOCAL)); auto value = VECTORIZED_FN_ARGS(0); auto pattern = state->_search_string_column; return VectorizedStrictBinaryFunction<ConstantEqualsImpl>::evaluate<TYPE_VARCHAR, TYPE_BOOLEAN>(value, pattern); } ColumnPtr LikePredicate::constant_substring_fn(FunctionContext* context, const starrocks::vectorized::Columns& columns) { RETURN_IF_COLUMNS_ONLY_NULL(columns); auto state = reinterpret_cast<LikePredicateState*>(context->get_function_state(FunctionContext::THREAD_LOCAL)); Slice needle = ColumnHelper::get_const_value<TYPE_VARCHAR>(state->_search_string_column); auto res = RunTimeColumnType<TYPE_BOOLEAN>::create(); if (columns[0]->is_constant()) { Slice haystack = ColumnHelper::get_const_value<TYPE_VARCHAR>(columns[0]); /// It is assumed that the StringSearcher is not very difficult to initialize. auto searcher = LibcASCIICaseSensitiveStringSearcher(needle.data, needle.size); /// searcher returns a pointer to the found substring or to the end of `haystack`. const char* res_pointer = searcher.search(haystack.data, haystack.size); if (!res_pointer) { res->append(false); } else { res->append(true); } return ConstColumn::create(res, columns[0]->size()); } BinaryColumn* haystack = nullptr; NullColumnPtr res_null = nullptr; if (columns[0]->is_nullable()) { auto haystack_null = ColumnHelper::as_column<NullableColumn>(columns[0]); haystack = ColumnHelper::as_raw_column<BinaryColumn>(haystack_null->data_column()); res_null = haystack_null->null_column(); } else { haystack = ColumnHelper::as_raw_column<BinaryColumn>(columns[0]); } if (needle.size == 0) { // if needle is empty string, every haystack can be matched. res->resize(haystack->size()); size_t type_size = res->type_size(); memset(res->mutable_raw_data(), 1, res->size() * type_size); } else { const std::vector<uint32_t>& offsets = haystack->get_offset(); res->resize(haystack->size()); const char* begin = haystack->get_slice(0).data; const char* pos = begin; const char* end = pos + haystack->get_bytes().size(); /// Current index in the array of strings. size_t i = 0; auto searcher = VolnitskyUTF8(needle.data, needle.size, end - pos); /// We will search for the next occurrence in all strings at once. while (pos < end && end != (pos = searcher.search(pos, end - pos))) { /// Determine which index it refers to. while (begin + offsets[i + 1] <= pos) { res->get_data()[i] = false; ++i; } /// We check that the entry does not pass through the boundaries of strings. if (pos + needle.size > begin + offsets[i + 1]) { res->get_data()[i] = false; } else { res->get_data()[i] = true; } pos = begin + offsets[i + 1]; ++i; } if (i < res->size()) { size_t type_size = res->type_size(); memset(res->mutable_raw_data() + i * type_size, 0, (res->size() - i) * type_size); } } if (columns[0]->has_null()) { return NullableColumn::create(res, res_null); } return res; } // regex_match ColumnPtr LikePredicate::regex_match(FunctionContext* context, const starrocks::vectorized::Columns& columns, bool is_like_pattern) { RETURN_IF_COLUMNS_ONLY_NULL(columns); if (is_like_pattern) { return regex_match_full(context, columns); } else { return regex_match_partial(context, columns); } } ColumnPtr LikePredicate::regex_match_full(FunctionContext* context, const starrocks::vectorized::Columns& columns) { auto value_column = VECTORIZED_FN_ARGS(0); ColumnViewer<TYPE_VARCHAR> value_viewer(value_column); ColumnBuilder<TYPE_BOOLEAN> result; // pattern is constant value, use context's regex if (context->is_constant_column(1)) { auto state = reinterpret_cast<LikePredicateState*>(context->get_function_state(FunctionContext::THREAD_LOCAL)); hs_scratch_t* scratch = nullptr; if (hs_clone_scratch(state->scratch, &scratch) != HS_SUCCESS) { CHECK(false) << "ERROR: Unable to clone scratch space."; } for (int row = 0; row < value_viewer.size(); ++row) { bool v = false; auto status = hs_scan( state->database, value_viewer.value(row).data, value_viewer.value(row).size, 0, scratch, [](unsigned int id, unsigned long long from, unsigned long long to, unsigned int flags, void* ctx) -> int { *((bool*)ctx) = true; return 1; }, &v); DCHECK(status == HS_SUCCESS || status == HS_SCAN_TERMINATED); result.append(v, value_viewer.is_null(row)); } if (hs_free_scratch(scratch) != HS_SUCCESS) { CHECK(false) << "ERROR: free scratch space failure"; } return result.build(value_column->is_constant()); } // pattern is variables row, build by rows auto pattern_column = VECTORIZED_FN_ARGS(1); ColumnViewer<TYPE_VARCHAR> pattern_viewer(pattern_column); RE2::Options opts; opts.set_never_nl(false); opts.set_dot_nl(true); for (int row = 0; row < value_viewer.size(); ++row) { if (value_viewer.is_null(row) || pattern_viewer.is_null(row)) { result.append_null(); continue; } auto re_pattern = LikePredicate::template convert_like_pattern<false>(context, pattern_viewer.value(row)); re2::RE2 re(re_pattern, opts); if (!re.ok()) { context->set_error(strings::Substitute("Invalid regex: $0", re_pattern).c_str()); result.append_null(); continue; } auto v = RE2::FullMatch(re2::StringPiece(value_viewer.value(row).data, value_viewer.value(row).size), re); result.append(v); } return result.build(ColumnHelper::is_all_const(columns)); } ColumnPtr LikePredicate::regex_match_partial(FunctionContext* context, const starrocks::vectorized::Columns& columns) { auto value_column = VECTORIZED_FN_ARGS(0); ColumnViewer<TYPE_VARCHAR> value_viewer(value_column); ColumnBuilder<TYPE_BOOLEAN> result; // pattern is constant value, use context's regex if (context->is_constant_column(1)) { auto state = reinterpret_cast<LikePredicateState*>(context->get_function_state(FunctionContext::THREAD_LOCAL)); hs_scratch_t* scratch = nullptr; if (hs_clone_scratch(state->scratch, &scratch) != HS_SUCCESS) { CHECK(false) << "ERROR: Unable to clone scratch space."; } for (int row = 0; row < value_viewer.size(); ++row) { bool v = false; auto status = hs_scan( state->database, value_viewer.value(row).data, value_viewer.value(row).size, 0, scratch, [](unsigned int id, unsigned long long from, unsigned long long to, unsigned int flags, void* ctx) -> int { *((bool*)ctx) = true; return 1; }, &v); DCHECK(status == HS_SUCCESS || status == HS_SCAN_TERMINATED); result.append(v, value_viewer.is_null(row)); } if (hs_free_scratch(scratch) != HS_SUCCESS) { CHECK(false) << "ERROR: free scratch space failure"; } return result.build(value_column->is_constant()); } // pattern is variables row, build by rows auto pattern_column = VECTORIZED_FN_ARGS(1); ColumnViewer<TYPE_VARCHAR> pattern_viewer(pattern_column); RE2::Options opts; opts.set_never_nl(false); opts.set_dot_nl(true); for (int row = 0; row < value_viewer.size(); ++row) { if (value_viewer.is_null(row) || pattern_viewer.is_null(row)) { result.append_null(); continue; } auto re_pattern = pattern_viewer.value(row).to_string(); re2::RE2 re(re_pattern, opts); if (!re.ok()) { context->set_error(strings::Substitute("Invalid regex: $0", re_pattern).c_str()); result.append_null(); continue; } auto v = RE2::PartialMatch(re2::StringPiece(value_viewer.value(row).data, value_viewer.value(row).size), re); result.append(v); } return result.build(ColumnHelper::is_all_const(columns)); } template <bool fullMatch> std::string LikePredicate::convert_like_pattern(FunctionContext* context, const Slice& pattern) { std::string re_pattern; re_pattern.clear(); auto state = reinterpret_cast<LikePredicateState*>(context->get_function_state(FunctionContext::THREAD_LOCAL)); bool is_escaped = false; if constexpr (fullMatch) { re_pattern.append("^"); } for (int i = 0; i < pattern.size; ++i) { if (!is_escaped && pattern.data[i] == '%') { re_pattern.append(".*"); } else if (!is_escaped && pattern.data[i] == '_') { re_pattern.append("."); // check for escape char before checking for regex special chars, they might overlap } else if (!is_escaped && pattern.data[i] == state->escape_char) { is_escaped = true; } else if (pattern.data[i] == '.' || pattern.data[i] == '[' || pattern.data[i] == ']' || pattern.data[i] == '{' || pattern.data[i] == '}' || pattern.data[i] == '(' || pattern.data[i] == ')' || pattern.data[i] == '\\' || pattern.data[i] == '*' || pattern.data[i] == '+' || pattern.data[i] == '?' || pattern.data[i] == '|' || pattern.data[i] == '^' || pattern.data[i] == '$') { // escape all regex special characters; see list at re_pattern.append("\\"); re_pattern.append(1, pattern.data[i]); is_escaped = false; } else { // regular character or escaped special character re_pattern.append(1, pattern.data[i]); is_escaped = false; } } if constexpr (fullMatch) { re_pattern.append("$"); } return re_pattern; } void LikePredicate::remove_escape_character(std::string* search_string) { std::string tmp_search_string; tmp_search_string.swap(*search_string); int len = tmp_search_string.length(); for (int i = 0; i < len;) { if (tmp_search_string[i] == '\\' && i + 1 < len && (tmp_search_string[i + 1] == '%' || tmp_search_string[i + 1] == '_')) { search_string->append(1, tmp_search_string[i + 1]); i += 2; } else { search_string->append(1, tmp_search_string[i]); i++; } } } } // namespace starrocks::vectorized
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/browser/service_worker/service_worker_job_coordinator.h" #include "base/stl_util.h" #include "content/browser/service_worker/embedded_worker_registry.h" #include "content/browser/service_worker/service_worker_registration.h" namespace content { ServiceWorkerJobCoordinator::JobQueue::JobQueue() {} ServiceWorkerJobCoordinator::JobQueue::~JobQueue() { DCHECK(jobs_.empty()) << "Destroying JobQueue with " << jobs_.size() << " unfinished jobs"; STLDeleteElements(&jobs_); } void ServiceWorkerJobCoordinator::JobQueue::Push( scoped_ptr<ServiceWorkerRegisterJob> job, int source_process_id, const ServiceWorkerRegisterJob::RegistrationCallback& callback) { if (jobs_.empty()) { job->Start(); jobs_.push_back(job.release()); } else if (!job->Equals(jobs_.back())) { jobs_.push_back(job.release()); } // Note we are releasing 'job' here. DCHECK(!jobs_.empty()); jobs_.back()->AddCallback(callback, source_process_id); } void ServiceWorkerJobCoordinator::JobQueue::Pop(ServiceWorkerRegisterJob* job) { DCHECK(job == jobs_.front()); jobs_.pop_front(); delete job; if (!jobs_.empty()) jobs_.front()->Start(); } ServiceWorkerJobCoordinator::ServiceWorkerJobCoordinator( ServiceWorkerStorage* storage, EmbeddedWorkerRegistry* worker_registry) : storage_(storage), worker_registry_(worker_registry), weak_factory_(this) {} ServiceWorkerJobCoordinator::~ServiceWorkerJobCoordinator() { DCHECK(jobs_.empty()) << "Destroying ServiceWorkerJobCoordinator with " << jobs_.size() << " job queues"; } void ServiceWorkerJobCoordinator::Register( const GURL& pattern, const GURL& script_url, int source_process_id, const ServiceWorkerRegisterJob::RegistrationCallback& callback) { scoped_ptr<ServiceWorkerRegisterJob> job = make_scoped_ptr( new ServiceWorkerRegisterJob(storage_, worker_registry_, this, pattern, script_url, ServiceWorkerRegisterJob::REGISTER)); jobs_[pattern].Push(job.Pass(), source_process_id, callback); } void ServiceWorkerJobCoordinator::Unregister( const GURL& pattern, int source_process_id, const ServiceWorkerRegisterJob::UnregistrationCallback& callback) { scoped_ptr<ServiceWorkerRegisterJob> job = make_scoped_ptr( new ServiceWorkerRegisterJob(storage_, worker_registry_, this, pattern, GURL(), ServiceWorkerRegisterJob::UNREGISTER)); jobs_[pattern] .Push(job.Pass(), source_process_id, base::Bind(&ServiceWorkerJobCoordinator::UnregisterComplete, weak_factory_.GetWeakPtr(), callback)); } void ServiceWorkerJobCoordinator::FinishJob(const GURL& pattern, ServiceWorkerRegisterJob* job) { RegistrationJobMap::iterator pending_jobs = jobs_.find(pattern); DCHECK(pending_jobs != jobs_.end()) << "Deleting non-existent job."; pending_jobs->second.Pop(job); if (pending_jobs->second.empty()) jobs_.erase(pending_jobs); } void ServiceWorkerJobCoordinator::UnregisterComplete( const ServiceWorkerRegisterJob::UnregistrationCallback& callback, ServiceWorkerStatusCode status, const scoped_refptr<ServiceWorkerRegistration>& previous_registration) { callback.Run(status); } } // namespace content
#include <iostream> extern "C" { __attribute__((weak)) int saveCheckpoint() { return 0; } __attribute__((weak)) int restoreCheckpoint() { return 0; } int fakeFunction(int x) { return (x) * 2; } }
// Begin CVS Header // $Source: /fs/turing/cvs/copasi_dev/copasi/function/CMassAction.cpp,v $ // $Revision: 1.41 $ // $Name: Build-33 $ // $Author: shoops $ // $Date: 2009/07/30 00:51:57 $ // End CVS Header // Copyright (C) 2008 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., EML Research, gGmbH, University of Heidelberg, // and The University of Manchester. // All rights reserved. // Copyright (C) 2001 - 2007 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc. and EML Research, gGmbH. // All rights reserved. /** * CMassAction * * Created for Copasi by Stefan Hoops * (C) Stefan Hoops 2001 */ #include "copasi.h" #include "CMassAction.h" #include "utilities/utility.h" CMassAction::CMassAction(const std::string & name, const CCopasiContainer * pParent): CFunction(name, pParent, CEvaluationTree::MassAction) {} CMassAction::CMassAction(const CFunction & src, const CCopasiContainer * pParent): CFunction(src, pParent) {} CMassAction::CMassAction(const TriLogic & reversible, const CCopasiContainer * pParent): CFunction((reversible == TriTrue) ? "Mass action (reversible)" : "Mass action (irreversible)", pParent, CFunction::MassAction) { CONSTRUCTOR_TRACE; if (reversible != TriFalse && reversible != TriTrue) CCopasiMessage(CCopasiMessage::ERROR, MCMassAction + 1); if (reversible == TriTrue) setInfix("k1*PRODUCT<substrate_i>-k2*PRODUCT<product_j>"); else setInfix("k1*PRODUCT<substrate_i>"); } CMassAction::~CMassAction() {DESTRUCTOR_TRACE;} const C_FLOAT64 & CMassAction::calcValue(const CCallParameters<C_FLOAT64> & callParameters) { CCallParameters<C_FLOAT64>::const_iterator Factor; CCallParameters<C_FLOAT64>::const_iterator End; mValue = 0.0; Factor = callParameters[1].vector->begin(); End = callParameters[1].vector->end(); if (Factor != End) { mValue = *callParameters[0].value // k1 * *(Factor++)->value; // first substrate. while (Factor != End) mValue *= *(Factor++)->value; } if (isReversible() == TriFalse) return mValue; C_FLOAT64 Products = 0.0; Factor = callParameters[3].vector->begin(); End = callParameters[3].vector->end(); if (Factor != End) { Products = *callParameters[2].value // k2 * *(Factor++)->value; // first product. while (Factor != End) Products *= *(Factor++)->value; } return mValue -= Products; } bool CMassAction::dependsOn(const C_FLOAT64 * parameter, const CCallParameters<C_FLOAT64> & callParameters) const { if (parameter == callParameters[0].value) return true; CCallParameters<C_FLOAT64>::const_iterator it; CCallParameters<C_FLOAT64>::const_iterator end; it = callParameters[1].vector->begin(); end = callParameters[1].vector->end(); for (; it != end; it++) if (parameter == it->value) return true; if (isReversible() != TriTrue) return false; if (parameter == callParameters[2].value) return true; it = callParameters[3].vector->begin(); end = callParameters[3].vector->end(); for (; it != end; it++) if (parameter == it->value) return true; return false; } bool CMassAction::setInfix(const std::string & infix) { if (infix == "k1*PRODUCT<substrate_i>-k2*PRODUCT<product_j>") setReversible(TriTrue); else if (infix == "k1*PRODUCT<substrate_i>") setReversible(TriFalse); else return false; CFunction::setInfix(infix); getVariables().cleanup(); getVariables().add("k1", CFunctionParameter::FLOAT64, CFunctionParameter::PARAMETER); getVariables().add("substrate", CFunctionParameter::VFLOAT64, CFunctionParameter::SUBSTRATE); if (isReversible() == TriTrue) { getVariables().add("k2", CFunctionParameter::FLOAT64, CFunctionParameter::PARAMETER); getVariables().add("product", CFunctionParameter::VFLOAT64, CFunctionParameter::PRODUCT); } return true; } bool CMassAction::compile() { mUsable = true; return true; } #include "utilities/copasimathml.h" void CMassAction::writeMathML(std::ostream & out, const std::vector<std::vector<std::string> > & env, bool /* expand */, bool /* fullExpand */, unsigned C_INT32 l) const { bool rev = (isReversible() == TriTrue); if (rev) out << SPC(l) << "<mfenced>" << std::endl; out << SPC(l) << "<mrow>" << std::endl; out << SPC(l + 1) << env[0][0] << std::endl; unsigned i, imax = env[1].size(); for (i = 0; i < imax; ++i) { out << SPC(l + 1) << "<mo>&CenterDot;</mo>" << std::endl; out << SPC(l + 1) << env[1][i] << std::endl; } if (rev) { out << SPC(l + 1) << "<mo>-</mo>" << std::endl; out << SPC(l + 1) << env[2][0] << std::endl; unsigned i, imax = env[3].size(); for (i = 0; i < imax; ++i) { out << SPC(l + 1) << "<mo>&CenterDot;</mo>" << std::endl; out << SPC(l + 1) << env[3][i] << std::endl; } } out << SPC(l) << "</mrow>" << std::endl; if (rev) out << SPC(l) << "</mfenced>" << std::endl; }
#include <bits/stdc++.h> using namespace std; typedef long long ll; typedef vector <int> vi; vector <vi> a; int n; map <vi, int> map1; int main(){ ios_base::sync_with_stdio(false); cin.tie(nullptr); freopen("in.txt", "r", stdin); freopen("out.txt", "w", stdout); while(cin >> n, n){ a.resize(n); map1.clear(); for(int i=0; i<n; i++){ a[i].resize(5); for(int j=0; j<5; j++) cin >> a[i][j]; sort(a[i].begin(), a[i].end()); if(map1.count(a[i])) map1[a[i]]++; else map1[a[i]] = 1; } int max1 = -1; for(auto el:map1){ max1 = max(max1, el.second); } int cnt = 0; for(auto el:map1){ if(el.second == max1) cnt += el.second; } cout << cnt << "\n"; } return 0; }
/* * Copyright (c) 2021, NVIDIA CORPORATION. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <rapids_triton/triton/api/instance_finalize.hpp>
/* * Copyright 2018-2021 The urg_stamped Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <gtest/gtest.h> #include <cmath> #include <urg_stamped/first_order_filter.h> namespace urg_stamped { TEST(FirstOrderFilter, PassThrough) { FirstOrderFilter<double> flt; ASSERT_EQ(flt.update(0.0), 0.0); ASSERT_EQ(flt.update(1.0), 1.0); ASSERT_EQ(flt.update(2.0), 2.0); } TEST(FirstOrderFilter, LPF) { FirstOrderLPF<double> flt(100); ASSERT_EQ(flt.update(0.0), 0.0); for (size_t i = 0; i < 100 - 1; ++i) flt.update(1.0); ASSERT_NEAR(flt.update(1.0), 1.0 - 1.0 / std::exp(1), 1e-2); } TEST(FirstOrderFilter, HPF) { FirstOrderHPF<double> flt(100); ASSERT_EQ(flt.update(0.0), 0.0); for (size_t i = 0; i < 100 - 2; ++i) flt.update(1.0); ASSERT_NEAR(flt.update(1.0), 1.0 / std::exp(1), 1e-2); } } // namespace urg_stamped int main(int argc, char** argv) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin developers // Copyright (c) 2014-2015 The Dash developers // Copyright (c) 2015-2017 The kaishen developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "base58.h" #include "core_io.h" #include "init.h" #include "keystore.h" #include "main.h" #include "net.h" #include "primitives/transaction.h" #include "rpcserver.h" #include "script/script.h" #include "script/sign.h" #include "script/standard.h" #include "uint256.h" #ifdef ENABLE_WALLET #include "wallet.h" #endif #include <stdint.h> #include "json/json_spirit_utils.h" #include "json/json_spirit_value.h" #include <boost/assign/list_of.hpp> using namespace boost; using namespace boost::assign; using namespace json_spirit; using namespace std; void ScriptPubKeyToJSON(const CScript& scriptPubKey, Object& out, bool fIncludeHex) { txnouttype type; vector<CTxDestination> addresses; int nRequired; out.push_back(Pair("asm", scriptPubKey.ToString())); if (fIncludeHex) out.push_back(Pair("hex", HexStr(scriptPubKey.begin(), scriptPubKey.end()))); if (!ExtractDestinations(scriptPubKey, type, addresses, nRequired)) { out.push_back(Pair("type", GetTxnOutputType(type))); return; } out.push_back(Pair("reqSigs", nRequired)); out.push_back(Pair("type", GetTxnOutputType(type))); Array a; BOOST_FOREACH (const CTxDestination& addr, addresses) a.push_back(CBitcoinAddress(addr).ToString()); out.push_back(Pair("addresses", a)); } void TxToJSON(const CTransaction& tx, const uint256 hashBlock, Object& entry) { entry.push_back(Pair("txid", tx.GetHash().GetHex())); entry.push_back(Pair("version", tx.nVersion)); entry.push_back(Pair("locktime", (int64_t)tx.nLockTime)); Array vin; BOOST_FOREACH (const CTxIn& txin, tx.vin) { Object in; if (tx.IsCoinBase()) in.push_back(Pair("coinbase", HexStr(txin.scriptSig.begin(), txin.scriptSig.end()))); else { in.push_back(Pair("txid", txin.prevout.hash.GetHex())); in.push_back(Pair("vout", (int64_t)txin.prevout.n)); Object o; o.push_back(Pair("asm", txin.scriptSig.ToString())); o.push_back(Pair("hex", HexStr(txin.scriptSig.begin(), txin.scriptSig.end()))); in.push_back(Pair("scriptSig", o)); } in.push_back(Pair("sequence", (int64_t)txin.nSequence)); vin.push_back(in); } entry.push_back(Pair("vin", vin)); Array vout; for (unsigned int i = 0; i < tx.vout.size(); i++) { const CTxOut& txout = tx.vout[i]; Object out; out.push_back(Pair("value", ValueFromAmount(txout.nValue))); out.push_back(Pair("n", (int64_t)i)); Object o; ScriptPubKeyToJSON(txout.scriptPubKey, o, true); out.push_back(Pair("scriptPubKey", o)); vout.push_back(out); } entry.push_back(Pair("vout", vout)); if (hashBlock != 0) { entry.push_back(Pair("blockhash", hashBlock.GetHex())); BlockMap::iterator mi = mapBlockIndex.find(hashBlock); if (mi != mapBlockIndex.end() && (*mi).second) { CBlockIndex* pindex = (*mi).second; if (chainActive.Contains(pindex)) { entry.push_back(Pair("confirmations", 1 + chainActive.Height() - pindex->nHeight)); entry.push_back(Pair("time", pindex->GetBlockTime())); entry.push_back(Pair("blocktime", pindex->GetBlockTime())); } else entry.push_back(Pair("confirmations", 0)); } } } Value getrawtransaction(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) throw runtime_error( "getrawtransaction \"txid\" ( verbose )\n" "\nNOTE: By default this function only works sometimes. This is when the tx is in the mempool\n" "or there is an unspent output in the utxo for this transaction. To make it always work,\n" "you need to maintain a transaction index, using the -txindex command line option.\n" "\nReturn the raw transaction data.\n" "\nIf verbose=0, returns a string that is serialized, hex-encoded data for 'txid'.\n" "If verbose is non-zero, returns an Object with information about 'txid'.\n" "\nArguments:\n" "1. \"txid\" (string, required) The transaction id\n" "2. verbose (numeric, optional, default=0) If 0, return a string, other return a json object\n" "\nResult (if verbose is not set or set to 0):\n" "\"data\" (string) The serialized, hex-encoded data for 'txid'\n" "\nResult (if verbose > 0):\n" "{\n" " \"hex\" : \"data\", (string) The serialized, hex-encoded data for 'txid'\n" " \"txid\" : \"id\", (string) The transaction id (same as provided)\n" " \"version\" : n, (numeric) The version\n" " \"locktime\" : ttt, (numeric) The lock time\n" " \"vin\" : [ (array of json objects)\n" " {\n" " \"txid\": \"id\", (string) The transaction id\n" " \"vout\": n, (numeric) \n" " \"scriptSig\": { (json object) The script\n" " \"asm\": \"asm\", (string) asm\n" " \"hex\": \"hex\" (string) hex\n" " },\n" " \"sequence\": n (numeric) The script sequence number\n" " }\n" " ,...\n" " ],\n" " \"vout\" : [ (array of json objects)\n" " {\n" " \"value\" : x.xxx, (numeric) The value in btc\n" " \"n\" : n, (numeric) index\n" " \"scriptPubKey\" : { (json object)\n" " \"asm\" : \"asm\", (string) the asm\n" " \"hex\" : \"hex\", (string) the hex\n" " \"reqSigs\" : n, (numeric) The required sigs\n" " \"type\" : \"pubkeyhash\", (string) The type, eg 'pubkeyhash'\n" " \"addresses\" : [ (json array of string)\n" " \"kaishenaddress\" (string) kaishen address\n" " ,...\n" " ]\n" " }\n" " }\n" " ,...\n" " ],\n" " \"blockhash\" : \"hash\", (string) the block hash\n" " \"confirmations\" : n, (numeric) The confirmations\n" " \"time\" : ttt, (numeric) The transaction time in seconds since epoch (Jan 1 1970 GMT)\n" " \"blocktime\" : ttt (numeric) The block time in seconds since epoch (Jan 1 1970 GMT)\n" "}\n" "\nExamples:\n" + HelpExampleCli("getrawtransaction", "\"mytxid\"") + HelpExampleCli("getrawtransaction", "\"mytxid\" 1") + HelpExampleRpc("getrawtransaction", "\"mytxid\", 1")); uint256 hash = ParseHashV(params[0], "parameter 1"); bool fVerbose = false; if (params.size() > 1) fVerbose = (params[1].get_int() != 0); CTransaction tx; uint256 hashBlock = 0; if (!GetTransaction(hash, tx, hashBlock, true)) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "No information available about transaction"); string strHex = EncodeHexTx(tx); if (!fVerbose) return strHex; Object result; result.push_back(Pair("hex", strHex)); TxToJSON(tx, hashBlock, result); return result; } #ifdef ENABLE_WALLET Value listunspent(const Array& params, bool fHelp) { if (fHelp || params.size() > 3) throw runtime_error( "listunspent ( minconf maxconf [\"address\",...] )\n" "\nReturns array of unspent transaction outputs\n" "with between minconf and maxconf (inclusive) confirmations.\n" "Optionally filter to only include txouts paid to specified addresses.\n" "Results are an array of Objects, each of which has:\n" "{txid, vout, scriptPubKey, amount, confirmations}\n" "\nArguments:\n" "1. minconf (numeric, optional, default=1) The minimum confirmations to filter\n" "2. maxconf (numeric, optional, default=9999999) The maximum confirmations to filter\n" "3. \"addresses\" (string) A json array of kaishen addresses to filter\n" " [\n" " \"address\" (string) kaishen address\n" " ,...\n" " ]\n" "\nResult\n" "[ (array of json object)\n" " {\n" " \"txid\" : \"txid\", (string) the transaction id \n" " \"vout\" : n, (numeric) the vout value\n" " \"address\" : \"address\", (string) the kaishen address\n" " \"account\" : \"account\", (string) The associated account, or \"\" for the default account\n" " \"scriptPubKey\" : \"key\", (string) the script key\n" " \"amount\" : x.xxx, (numeric) the transaction amount in btc\n" " \"confirmations\" : n (numeric) The number of confirmations\n" " }\n" " ,...\n" "]\n" "\nExamples\n" + HelpExampleCli("listunspent", "") + HelpExampleCli("listunspent", "6 9999999 \"[\\\"1PGFqEzfmQch1gKD3ra4k18PNj3tTUUSqg\\\",\\\"1LtvqCaApEdUGFkpKMM4MstjcaL4dKg8SP\\\"]\"") + HelpExampleRpc("listunspent", "6, 9999999 \"[\\\"1PGFqEzfmQch1gKD3ra4k18PNj3tTUUSqg\\\",\\\"1LtvqCaApEdUGFkpKMM4MstjcaL4dKg8SP\\\"]\"")); RPCTypeCheck(params, list_of(int_type)(int_type)(array_type)); int nMinDepth = 1; if (params.size() > 0) nMinDepth = params[0].get_int(); int nMaxDepth = 9999999; if (params.size() > 1) nMaxDepth = params[1].get_int(); set<CBitcoinAddress> setAddress; if (params.size() > 2) { Array inputs = params[2].get_array(); BOOST_FOREACH (Value& input, inputs) { CBitcoinAddress address(input.get_str()); if (!address.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, string("Invalid kaishen address: ") + input.get_str()); if (setAddress.count(address)) throw JSONRPCError(RPC_INVALID_PARAMETER, string("Invalid parameter, duplicated address: ") + input.get_str()); setAddress.insert(address); } } Array results; vector<COutput> vecOutputs; assert(pwalletMain != NULL); pwalletMain->AvailableCoins(vecOutputs, false); BOOST_FOREACH (const COutput& out, vecOutputs) { if (out.nDepth < nMinDepth || out.nDepth > nMaxDepth) continue; if (setAddress.size()) { CTxDestination address; if (!ExtractDestination(out.tx->vout[out.i].scriptPubKey, address)) continue; if (!setAddress.count(address)) continue; } CAmount nValue = out.tx->vout[out.i].nValue; const CScript& pk = out.tx->vout[out.i].scriptPubKey; Object entry; entry.push_back(Pair("txid", out.tx->GetHash().GetHex())); entry.push_back(Pair("vout", out.i)); CTxDestination address; if (ExtractDestination(out.tx->vout[out.i].scriptPubKey, address)) { entry.push_back(Pair("address", CBitcoinAddress(address).ToString())); if (pwalletMain->mapAddressBook.count(address)) entry.push_back(Pair("account", pwalletMain->mapAddressBook[address].name)); } entry.push_back(Pair("scriptPubKey", HexStr(pk.begin(), pk.end()))); if (pk.IsPayToScriptHash()) { CTxDestination address; if (ExtractDestination(pk, address)) { const CScriptID& hash = boost::get<CScriptID>(address); CScript redeemScript; if (pwalletMain->GetCScript(hash, redeemScript)) entry.push_back(Pair("redeemScript", HexStr(redeemScript.begin(), redeemScript.end()))); } } entry.push_back(Pair("amount", ValueFromAmount(nValue))); entry.push_back(Pair("confirmations", out.nDepth)); entry.push_back(Pair("spendable", out.fSpendable)); results.push_back(entry); } return results; } #endif Value createrawtransaction(const Array& params, bool fHelp) { if (fHelp || params.size() != 2) throw runtime_error( "createrawtransaction [{\"txid\":\"id\",\"vout\":n},...] {\"address\":amount,...}\n" "\nCreate a transaction spending the given inputs and sending to the given addresses.\n" "Returns hex-encoded raw transaction.\n" "Note that the transaction's inputs are not signed, and\n" "it is not stored in the wallet or transmitted to the network.\n" "\nArguments:\n" "1. \"transactions\" (string, required) A json array of json objects\n" " [\n" " {\n" " \"txid\":\"id\", (string, required) The transaction id\n" " \"vout\":n (numeric, required) The output number\n" " }\n" " ,...\n" " ]\n" "2. \"addresses\" (string, required) a json object with addresses as keys and amounts as values\n" " {\n" " \"address\": x.xxx (numeric, required) The key is the kaishen address, the value is the btc amount\n" " ,...\n" " }\n" "\nResult:\n" "\"transaction\" (string) hex string of the transaction\n" "\nExamples\n" + HelpExampleCli("createrawtransaction", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\" \"{\\\"address\\\":0.01}\"") + HelpExampleRpc("createrawtransaction", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\", \"{\\\"address\\\":0.01}\"")); RPCTypeCheck(params, list_of(array_type)(obj_type)); Array inputs = params[0].get_array(); Object sendTo = params[1].get_obj(); CMutableTransaction rawTx; BOOST_FOREACH (const Value& input, inputs) { const Object& o = input.get_obj(); uint256 txid = ParseHashO(o, "txid"); const Value& vout_v = find_value(o, "vout"); if (vout_v.type() != int_type) throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, missing vout key"); int nOutput = vout_v.get_int(); if (nOutput < 0) throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, vout must be positive"); CTxIn in(COutPoint(txid, nOutput)); rawTx.vin.push_back(in); } set<CBitcoinAddress> setAddress; BOOST_FOREACH (const Pair& s, sendTo) { CBitcoinAddress address(s.name_); if (!address.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, string("Invalid kaishen address: ") + s.name_); if (setAddress.count(address)) throw JSONRPCError(RPC_INVALID_PARAMETER, string("Invalid parameter, duplicated address: ") + s.name_); setAddress.insert(address); CScript scriptPubKey = GetScriptForDestination(address.Get()); CAmount nAmount = AmountFromValue(s.value_); CTxOut out(nAmount, scriptPubKey); rawTx.vout.push_back(out); } return EncodeHexTx(rawTx); } Value decoderawtransaction(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "decoderawtransaction \"hexstring\"\n" "\nReturn a JSON object representing the serialized, hex-encoded transaction.\n" "\nArguments:\n" "1. \"hex\" (string, required) The transaction hex string\n" "\nResult:\n" "{\n" " \"txid\" : \"id\", (string) The transaction id\n" " \"version\" : n, (numeric) The version\n" " \"locktime\" : ttt, (numeric) The lock time\n" " \"vin\" : [ (array of json objects)\n" " {\n" " \"txid\": \"id\", (string) The transaction id\n" " \"vout\": n, (numeric) The output number\n" " \"scriptSig\": { (json object) The script\n" " \"asm\": \"asm\", (string) asm\n" " \"hex\": \"hex\" (string) hex\n" " },\n" " \"sequence\": n (numeric) The script sequence number\n" " }\n" " ,...\n" " ],\n" " \"vout\" : [ (array of json objects)\n" " {\n" " \"value\" : x.xxx, (numeric) The value in btc\n" " \"n\" : n, (numeric) index\n" " \"scriptPubKey\" : { (json object)\n" " \"asm\" : \"asm\", (string) the asm\n" " \"hex\" : \"hex\", (string) the hex\n" " \"reqSigs\" : n, (numeric) The required sigs\n" " \"type\" : \"pubkeyhash\", (string) The type, eg 'pubkeyhash'\n" " \"addresses\" : [ (json array of string)\n" " \"12tvKAXCxZjSmdNbao16dKXC8tRWfcF5oc\" (string) kaishen address\n" " ,...\n" " ]\n" " }\n" " }\n" " ,...\n" " ],\n" "}\n" "\nExamples:\n" + HelpExampleCli("decoderawtransaction", "\"hexstring\"") + HelpExampleRpc("decoderawtransaction", "\"hexstring\"")); RPCTypeCheck(params, list_of(str_type)); CTransaction tx; if (!DecodeHexTx(tx, params[0].get_str())) throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed"); Object result; TxToJSON(tx, 0, result); return result; } Value decodescript(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "decodescript \"hex\"\n" "\nDecode a hex-encoded script.\n" "\nArguments:\n" "1. \"hex\" (string) the hex encoded script\n" "\nResult:\n" "{\n" " \"asm\":\"asm\", (string) Script public key\n" " \"hex\":\"hex\", (string) hex encoded public key\n" " \"type\":\"type\", (string) The output type\n" " \"reqSigs\": n, (numeric) The required signatures\n" " \"addresses\": [ (json array of string)\n" " \"address\" (string) kaishen address\n" " ,...\n" " ],\n" " \"p2sh\",\"address\" (string) script address\n" "}\n" "\nExamples:\n" + HelpExampleCli("decodescript", "\"hexstring\"") + HelpExampleRpc("decodescript", "\"hexstring\"")); RPCTypeCheck(params, list_of(str_type)); Object r; CScript script; if (params[0].get_str().size() > 0) { vector<unsigned char> scriptData(ParseHexV(params[0], "argument")); script = CScript(scriptData.begin(), scriptData.end()); } else { // Empty scripts are valid } ScriptPubKeyToJSON(script, r, false); r.push_back(Pair("p2sh", CBitcoinAddress(CScriptID(script)).ToString())); return r; } Value signrawtransaction(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 4) throw runtime_error( "signrawtransaction \"hexstring\" ( [{\"txid\":\"id\",\"vout\":n,\"scriptPubKey\":\"hex\",\"redeemScript\":\"hex\"},...] [\"privatekey1\",...] sighashtype )\n" "\nSign inputs for raw transaction (serialized, hex-encoded).\n" "The second optional argument (may be null) is an array of previous transaction outputs that\n" "this transaction depends on but may not yet be in the block chain.\n" "The third optional argument (may be null) is an array of base58-encoded private\n" "keys that, if given, will be the only keys used to sign the transaction.\n" #ifdef ENABLE_WALLET + HelpRequiringPassphrase() + "\n" #endif "\nArguments:\n" "1. \"hexstring\" (string, required) The transaction hex string\n" "2. \"prevtxs\" (string, optional) An json array of previous dependent transaction outputs\n" " [ (json array of json objects, or 'null' if none provided)\n" " {\n" " \"txid\":\"id\", (string, required) The transaction id\n" " \"vout\":n, (numeric, required) The output number\n" " \"scriptPubKey\": \"hex\", (string, required) script key\n" " \"redeemScript\": \"hex\" (string, required for P2SH) redeem script\n" " }\n" " ,...\n" " ]\n" "3. \"privatekeys\" (string, optional) A json array of base58-encoded private keys for signing\n" " [ (json array of strings, or 'null' if none provided)\n" " \"privatekey\" (string) private key in base58-encoding\n" " ,...\n" " ]\n" "4. \"sighashtype\" (string, optional, default=ALL) The signature hash type. Must be one of\n" " \"ALL\"\n" " \"NONE\"\n" " \"SINGLE\"\n" " \"ALL|ANYONECANPAY\"\n" " \"NONE|ANYONECANPAY\"\n" " \"SINGLE|ANYONECANPAY\"\n" "\nResult:\n" "{\n" " \"hex\": \"value\", (string) The raw transaction with signature(s) (hex-encoded string)\n" " \"complete\": n (numeric) if transaction has a complete set of signature (0 if not)\n" "}\n" "\nExamples:\n" + HelpExampleCli("signrawtransaction", "\"myhex\"") + HelpExampleRpc("signrawtransaction", "\"myhex\"")); RPCTypeCheck(params, list_of(str_type)(array_type)(array_type)(str_type), true); vector<unsigned char> txData(ParseHexV(params[0], "argument 1")); CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION); vector<CMutableTransaction> txVariants; while (!ssData.empty()) { try { CMutableTransaction tx; ssData >> tx; txVariants.push_back(tx); } catch (const std::exception&) { throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed"); } } if (txVariants.empty()) throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Missing transaction"); // mergedTx will end up with all the signatures; it // starts as a clone of the rawtx: CMutableTransaction mergedTx(txVariants[0]); bool fComplete = true; // Fetch previous transactions (inputs): CCoinsView viewDummy; CCoinsViewCache view(&viewDummy); { LOCK(mempool.cs); CCoinsViewCache& viewChain = *pcoinsTip; CCoinsViewMemPool viewMempool(&viewChain, mempool); view.SetBackend(viewMempool); // temporarily switch cache backend to db+mempool view BOOST_FOREACH (const CTxIn& txin, mergedTx.vin) { const uint256& prevHash = txin.prevout.hash; CCoins coins; view.AccessCoins(prevHash); // this is certainly allowed to fail } view.SetBackend(viewDummy); // switch back to avoid locking mempool for too long } bool fGivenKeys = false; CBasicKeyStore tempKeystore; if (params.size() > 2 && params[2].type() != null_type) { fGivenKeys = true; Array keys = params[2].get_array(); BOOST_FOREACH (Value k, keys) { CBitcoinSecret vchSecret; bool fGood = vchSecret.SetString(k.get_str()); if (!fGood) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid private key"); CKey key = vchSecret.GetKey(); if (!key.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Private key outside allowed range"); tempKeystore.AddKey(key); } } #ifdef ENABLE_WALLET else EnsureWalletIsUnlocked(); #endif // Add previous txouts given in the RPC call: if (params.size() > 1 && params[1].type() != null_type) { Array prevTxs = params[1].get_array(); BOOST_FOREACH (Value& p, prevTxs) { if (p.type() != obj_type) throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "expected object with {\"txid'\",\"vout\",\"scriptPubKey\"}"); Object prevOut = p.get_obj(); RPCTypeCheck(prevOut, map_list_of("txid", str_type)("vout", int_type)("scriptPubKey", str_type)); uint256 txid = ParseHashO(prevOut, "txid"); int nOut = find_value(prevOut, "vout").get_int(); if (nOut < 0) throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "vout must be positive"); vector<unsigned char> pkData(ParseHexO(prevOut, "scriptPubKey")); CScript scriptPubKey(pkData.begin(), pkData.end()); { CCoinsModifier coins = view.ModifyCoins(txid); if (coins->IsAvailable(nOut) && coins->vout[nOut].scriptPubKey != scriptPubKey) { string err("Previous output scriptPubKey mismatch:\n"); err = err + coins->vout[nOut].scriptPubKey.ToString() + "\nvs:\n" + scriptPubKey.ToString(); throw JSONRPCError(RPC_DESERIALIZATION_ERROR, err); } if ((unsigned int)nOut >= coins->vout.size()) coins->vout.resize(nOut + 1); coins->vout[nOut].scriptPubKey = scriptPubKey; coins->vout[nOut].nValue = 0; // we don't know the actual output value } // if redeemScript given and not using the local wallet (private keys // given), add redeemScript to the tempKeystore so it can be signed: if (fGivenKeys && scriptPubKey.IsPayToScriptHash()) { RPCTypeCheck(prevOut, map_list_of("txid", str_type)("vout", int_type)("scriptPubKey", str_type)("redeemScript", str_type)); Value v = find_value(prevOut, "redeemScript"); if (!(v == Value::null)) { vector<unsigned char> rsData(ParseHexV(v, "redeemScript")); CScript redeemScript(rsData.begin(), rsData.end()); tempKeystore.AddCScript(redeemScript); } } } } #ifdef ENABLE_WALLET const CKeyStore& keystore = ((fGivenKeys || !pwalletMain) ? tempKeystore : *pwalletMain); #else const CKeyStore& keystore = tempKeystore; #endif int nHashType = SIGHASH_ALL; if (params.size() > 3 && params[3].type() != null_type) { static map<string, int> mapSigHashValues = boost::assign::map_list_of(string("ALL"), int(SIGHASH_ALL))(string("ALL|ANYONECANPAY"), int(SIGHASH_ALL | SIGHASH_ANYONECANPAY))(string("NONE"), int(SIGHASH_NONE))(string("NONE|ANYONECANPAY"), int(SIGHASH_NONE | SIGHASH_ANYONECANPAY))(string("SINGLE"), int(SIGHASH_SINGLE))(string("SINGLE|ANYONECANPAY"), int(SIGHASH_SINGLE | SIGHASH_ANYONECANPAY)); string strHashType = params[3].get_str(); if (mapSigHashValues.count(strHashType)) nHashType = mapSigHashValues[strHashType]; else throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid sighash param"); } bool fHashSingle = ((nHashType & ~SIGHASH_ANYONECANPAY) == SIGHASH_SINGLE); // Sign what we can: for (unsigned int i = 0; i < mergedTx.vin.size(); i++) { CTxIn& txin = mergedTx.vin[i]; const CCoins* coins = view.AccessCoins(txin.prevout.hash); if (coins == NULL || !coins->IsAvailable(txin.prevout.n)) { fComplete = false; continue; } const CScript& prevPubKey = coins->vout[txin.prevout.n].scriptPubKey; txin.scriptSig.clear(); // Only sign SIGHASH_SINGLE if there's a corresponding output: if (!fHashSingle || (i < mergedTx.vout.size())) SignSignature(keystore, prevPubKey, mergedTx, i, nHashType); // ... and merge in other signatures: BOOST_FOREACH (const CMutableTransaction& txv, txVariants) { txin.scriptSig = CombineSignatures(prevPubKey, mergedTx, i, txin.scriptSig, txv.vin[i].scriptSig); } if (!VerifyScript(txin.scriptSig, prevPubKey, STANDARD_SCRIPT_VERIFY_FLAGS, MutableTransactionSignatureChecker(&mergedTx, i))) fComplete = false; } Object result; result.push_back(Pair("hex", EncodeHexTx(mergedTx))); result.push_back(Pair("complete", fComplete)); return result; } Value sendrawtransaction(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) throw runtime_error( "sendrawtransaction \"hexstring\" ( allowhighfees )\n" "\nSubmits raw transaction (serialized, hex-encoded) to local node and network.\n" "\nAlso see createrawtransaction and signrawtransaction calls.\n" "\nArguments:\n" "1. \"hexstring\" (string, required) The hex string of the raw transaction)\n" "2. allowhighfees (boolean, optional, default=false) Allow high fees\n" "\nResult:\n" "\"hex\" (string) The transaction hash in hex\n" "\nExamples:\n" "\nCreate a transaction\n" + HelpExampleCli("createrawtransaction", "\"[{\\\"txid\\\" : \\\"mytxid\\\",\\\"vout\\\":0}]\" \"{\\\"myaddress\\\":0.01}\"") + "Sign the transaction, and get back the hex\n" + HelpExampleCli("signrawtransaction", "\"myhex\"") + "\nSend the transaction (signed hex)\n" + HelpExampleCli("sendrawtransaction", "\"signedhex\"") + "\nAs a json rpc call\n" + HelpExampleRpc("sendrawtransaction", "\"signedhex\"")); RPCTypeCheck(params, list_of(str_type)(bool_type)); // parse hex string from parameter CTransaction tx; if (!DecodeHexTx(tx, params[0].get_str())) throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed"); uint256 hashTx = tx.GetHash(); bool fOverrideFees = false; if (params.size() > 1) fOverrideFees = params[1].get_bool(); CCoinsViewCache& view = *pcoinsTip; const CCoins* existinkaishens = view.AccessCoins(hashTx); bool fHaveMempool = mempool.exists(hashTx); bool fHaveChain = existinkaishens && existinkaishens->nHeight < 1000000000; if (!fHaveMempool && !fHaveChain) { // push to local node and sync with wallets CValidationState state; if (!AcceptToMemoryPool(mempool, state, tx, false, NULL, !fOverrideFees)) { if (state.IsInvalid()) throw JSONRPCError(RPC_TRANSACTION_REJECTED, strprintf("%i: %s", state.GetRejectCode(), state.GetRejectReason())); else throw JSONRPCError(RPC_TRANSACTION_ERROR, state.GetRejectReason()); } } else if (fHaveChain) { throw JSONRPCError(RPC_TRANSACTION_ALREADY_IN_CHAIN, "transaction already in block chain"); } RelayTransaction(tx); return hashTx.GetHex(); }
//===--- Expr.cpp - Swift Language Expression ASTs ------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // This file implements the Expr class and subclasses. // //===----------------------------------------------------------------------===// #include "swift/AST/Expr.h" #include "swift/Basic/Statistic.h" #include "swift/Basic/Unicode.h" #include "swift/AST/ASTContext.h" #include "swift/AST/ASTVisitor.h" #include "swift/AST/Decl.h" // FIXME: Bad dependency #include "swift/AST/ParameterList.h" #include "swift/AST/Stmt.h" #include "swift/AST/ASTWalker.h" #include "swift/AST/AvailabilitySpec.h" #include "swift/AST/PrettyStackTrace.h" #include "swift/AST/TypeCheckRequests.h" #include "swift/AST/TypeLoc.h" #include "llvm/ADT/APFloat.h" #include "llvm/ADT/PointerUnion.h" #include "llvm/ADT/SetVector.h" #include "llvm/ADT/Twine.h" using namespace swift; #define EXPR(Id, _) \ static_assert(IsTriviallyDestructible<Id##Expr>::value, \ "Exprs are BumpPtrAllocated; the destructor is never called"); #include "swift/AST/ExprNodes.def" StringRef swift::getFunctionRefKindStr(FunctionRefKind refKind) { switch (refKind) { case FunctionRefKind::Unapplied: return "unapplied"; case FunctionRefKind::SingleApply: return "single"; case FunctionRefKind::DoubleApply: return "double"; case FunctionRefKind::Compound: return "compound"; } llvm_unreachable("Unhandled FunctionRefKind in switch."); } //===----------------------------------------------------------------------===// // Expr methods. //===----------------------------------------------------------------------===// // Only allow allocation of Stmts using the allocator in ASTContext. void *Expr::operator new(size_t Bytes, ASTContext &C, unsigned Alignment) { return C.Allocate(Bytes, Alignment); } StringRef Expr::getKindName(ExprKind K) { switch (K) { #define EXPR(Id, Parent) case ExprKind::Id: return #Id; #include "swift/AST/ExprNodes.def" } llvm_unreachable("bad ExprKind"); } template <class T> static SourceLoc getStartLocImpl(const T *E); template <class T> static SourceLoc getEndLocImpl(const T *E); template <class T> static SourceLoc getLocImpl(const T *E); // Helper functions to check statically whether a method has been // overridden from its implementation in Expr. The sort of thing you // need when you're avoiding v-tables. namespace { template <typename ReturnType, typename Class> constexpr bool isOverriddenFromExpr(ReturnType (Class::*)() const) { return true; } template <typename ReturnType> constexpr bool isOverriddenFromExpr(ReturnType (Expr::*)() const) { return false; } template <bool IsOverridden> struct Dispatch; /// Dispatch down to a concrete override. template <> struct Dispatch<true> { template <class T> static SourceLoc getStartLoc(const T *E) { return E->getStartLoc(); } template <class T> static SourceLoc getEndLoc(const T *E) { return E->getEndLoc(); } template <class T> static SourceLoc getLoc(const T *E) { return E->getLoc(); } template <class T> static SourceRange getSourceRange(const T *E) { return E->getSourceRange(); } }; /// Default implementations for when a method isn't overridden. template <> struct Dispatch<false> { template <class T> static SourceLoc getStartLoc(const T *E) { return E->getSourceRange().Start; } template <class T> static SourceLoc getEndLoc(const T *E) { return E->getSourceRange().End; } template <class T> static SourceLoc getLoc(const T *E) { return getStartLocImpl(E); } template <class T> static SourceRange getSourceRange(const T *E) { if (E->getStartLoc().isInvalid() != E->getEndLoc().isInvalid()) return SourceRange(); return { E->getStartLoc(), E->getEndLoc() }; } }; } // end anonymous namespace void Expr::setType(Type T) { assert(!T || !T->hasTypeVariable() || !T->hasHole()); Ty = T; } void Expr::setImplicit(bool Implicit) { assert(!isa<TypeExpr>(this) || getType() && "Cannot make a TypeExpr implicit without a contextual type."); Bits.Expr.Implicit = Implicit; } template <class T> static SourceRange getSourceRangeImpl(const T *E) { static_assert(isOverriddenFromExpr(&T::getSourceRange) || (isOverriddenFromExpr(&T::getStartLoc) && isOverriddenFromExpr(&T::getEndLoc)), "Expr subclass must implement either getSourceRange() " "or getStartLoc()/getEndLoc()"); return Dispatch<isOverriddenFromExpr(&T::getSourceRange)>::getSourceRange(E); } SourceRange Expr::getSourceRange() const { switch (getKind()) { #define EXPR(ID, PARENT) \ case ExprKind::ID: return getSourceRangeImpl(cast<ID##Expr>(this)); #include "swift/AST/ExprNodes.def" } llvm_unreachable("expression type not handled!"); } template <class T> static SourceLoc getStartLocImpl(const T *E) { return Dispatch<isOverriddenFromExpr(&T::getStartLoc)>::getStartLoc(E); } SourceLoc Expr::getStartLoc() const { switch (getKind()) { #define EXPR(ID, PARENT) \ case ExprKind::ID: return getStartLocImpl(cast<ID##Expr>(this)); #include "swift/AST/ExprNodes.def" } llvm_unreachable("expression type not handled!"); } template <class T> static SourceLoc getEndLocImpl(const T *E) { return Dispatch<isOverriddenFromExpr(&T::getEndLoc)>::getEndLoc(E); } SourceLoc Expr::getEndLoc() const { switch (getKind()) { #define EXPR(ID, PARENT) \ case ExprKind::ID: return getEndLocImpl(cast<ID##Expr>(this)); #include "swift/AST/ExprNodes.def" } llvm_unreachable("expression type not handled!"); } template <class T> static SourceLoc getLocImpl(const T *E) { return Dispatch<isOverriddenFromExpr(&T::getLoc)>::getLoc(E); } SourceLoc Expr::getLoc() const { switch (getKind()) { #define EXPR(ID, PARENT) \ case ExprKind::ID: return getLocImpl(cast<ID##Expr>(this)); #include "swift/AST/ExprNodes.def" } llvm_unreachable("expression type not handled!"); } Expr *Expr::getSemanticsProvidingExpr() { if (auto *IE = dyn_cast<IdentityExpr>(this)) return IE->getSubExpr()->getSemanticsProvidingExpr(); if (auto *TE = dyn_cast<TryExpr>(this)) return TE->getSubExpr()->getSemanticsProvidingExpr(); return this; } Expr *Expr::getValueProvidingExpr() { Expr *E = getSemanticsProvidingExpr(); if (auto TE = dyn_cast<ForceTryExpr>(E)) return TE->getSubExpr()->getValueProvidingExpr(); // TODO: // - tuple literal projection, which may become interestingly idiomatic return E; } DeclRefExpr *Expr::getMemberOperatorRef() { auto expr = this; if (!expr->isImplicit()) return nullptr; auto dotSyntax = dyn_cast<DotSyntaxCallExpr>(expr); if (!dotSyntax) return nullptr; auto operatorRef = dyn_cast<DeclRefExpr>(dotSyntax->getFn()); if (!operatorRef) return nullptr; auto func = dyn_cast<FuncDecl>(operatorRef->getDecl()); if (!func) return nullptr; if (!func->isOperator()) return nullptr; return operatorRef; } ConcreteDeclRef Expr::getReferencedDecl(bool stopAtParenExpr) const { switch (getKind()) { // No declaration reference. #define NO_REFERENCE(Id) case ExprKind::Id: return ConcreteDeclRef() #define SIMPLE_REFERENCE(Id, Getter) \ case ExprKind::Id: \ return cast<Id##Expr>(this)->Getter() #define PASS_THROUGH_REFERENCE(Id, GetSubExpr) \ case ExprKind::Id: \ return cast<Id##Expr>(this) \ ->GetSubExpr()->getReferencedDecl(stopAtParenExpr) NO_REFERENCE(Error); NO_REFERENCE(NilLiteral); NO_REFERENCE(IntegerLiteral); NO_REFERENCE(FloatLiteral); NO_REFERENCE(BooleanLiteral); NO_REFERENCE(StringLiteral); NO_REFERENCE(InterpolatedStringLiteral); NO_REFERENCE(ObjectLiteral); NO_REFERENCE(MagicIdentifierLiteral); NO_REFERENCE(DiscardAssignment); NO_REFERENCE(LazyInitializer); SIMPLE_REFERENCE(DeclRef, getDeclRef); SIMPLE_REFERENCE(SuperRef, getSelf); NO_REFERENCE(Type); SIMPLE_REFERENCE(OtherConstructorDeclRef, getDeclRef); PASS_THROUGH_REFERENCE(DotSyntaxBaseIgnored, getRHS); // FIXME: Return multiple results? case ExprKind::OverloadedDeclRef: return ConcreteDeclRef(); NO_REFERENCE(UnresolvedDeclRef); SIMPLE_REFERENCE(MemberRef, getMember); SIMPLE_REFERENCE(DynamicMemberRef, getMember); SIMPLE_REFERENCE(DynamicSubscript, getMember); PASS_THROUGH_REFERENCE(UnresolvedSpecialize, getSubExpr); NO_REFERENCE(UnresolvedMember); NO_REFERENCE(UnresolvedDot); NO_REFERENCE(Sequence); case ExprKind::Paren: if (stopAtParenExpr) return ConcreteDeclRef(); return cast<ParenExpr>(this) ->getSubExpr()->getReferencedDecl(stopAtParenExpr); PASS_THROUGH_REFERENCE(UnresolvedMemberChainResult, getSubExpr); PASS_THROUGH_REFERENCE(DotSelf, getSubExpr); PASS_THROUGH_REFERENCE(Await, getSubExpr); PASS_THROUGH_REFERENCE(Try, getSubExpr); PASS_THROUGH_REFERENCE(ForceTry, getSubExpr); PASS_THROUGH_REFERENCE(OptionalTry, getSubExpr); NO_REFERENCE(Tuple); NO_REFERENCE(Array); NO_REFERENCE(Dictionary); case ExprKind::Subscript: { auto subscript = cast<SubscriptExpr>(this); if (subscript->hasDecl()) return subscript->getDecl(); return ConcreteDeclRef(); } NO_REFERENCE(KeyPathApplication); NO_REFERENCE(TupleElement); NO_REFERENCE(CaptureList); NO_REFERENCE(Closure); PASS_THROUGH_REFERENCE(AutoClosure, getSingleExpressionBody); PASS_THROUGH_REFERENCE(InOut, getSubExpr); NO_REFERENCE(VarargExpansion); NO_REFERENCE(DynamicType); PASS_THROUGH_REFERENCE(RebindSelfInConstructor, getSubExpr); NO_REFERENCE(OpaqueValue); NO_REFERENCE(PropertyWrapperValuePlaceholder); NO_REFERENCE(DefaultArgument); PASS_THROUGH_REFERENCE(BindOptional, getSubExpr); PASS_THROUGH_REFERENCE(OptionalEvaluation, getSubExpr); PASS_THROUGH_REFERENCE(ForceValue, getSubExpr); PASS_THROUGH_REFERENCE(OpenExistential, getSubExpr); NO_REFERENCE(Call); NO_REFERENCE(PrefixUnary); NO_REFERENCE(PostfixUnary); NO_REFERENCE(Binary); NO_REFERENCE(DotSyntaxCall); NO_REFERENCE(MakeTemporarilyEscapable); NO_REFERENCE(ConstructorRefCall); PASS_THROUGH_REFERENCE(Load, getSubExpr); NO_REFERENCE(DestructureTuple); NO_REFERENCE(UnresolvedTypeConversion); PASS_THROUGH_REFERENCE(FunctionConversion, getSubExpr); PASS_THROUGH_REFERENCE(CovariantFunctionConversion, getSubExpr); PASS_THROUGH_REFERENCE(CovariantReturnConversion, getSubExpr); PASS_THROUGH_REFERENCE(ImplicitlyUnwrappedFunctionConversion, getSubExpr); PASS_THROUGH_REFERENCE(MetatypeConversion, getSubExpr); PASS_THROUGH_REFERENCE(CollectionUpcastConversion, getSubExpr); PASS_THROUGH_REFERENCE(Erasure, getSubExpr); PASS_THROUGH_REFERENCE(AnyHashableErasure, getSubExpr); PASS_THROUGH_REFERENCE(DerivedToBase, getSubExpr); PASS_THROUGH_REFERENCE(ArchetypeToSuper, getSubExpr); PASS_THROUGH_REFERENCE(InjectIntoOptional, getSubExpr); PASS_THROUGH_REFERENCE(ClassMetatypeToObject, getSubExpr); PASS_THROUGH_REFERENCE(ExistentialMetatypeToObject, getSubExpr); PASS_THROUGH_REFERENCE(ProtocolMetatypeToObject, getSubExpr); PASS_THROUGH_REFERENCE(InOutToPointer, getSubExpr); PASS_THROUGH_REFERENCE(ArrayToPointer, getSubExpr); PASS_THROUGH_REFERENCE(StringToPointer, getSubExpr); PASS_THROUGH_REFERENCE(PointerToPointer, getSubExpr); PASS_THROUGH_REFERENCE(ForeignObjectConversion, getSubExpr); PASS_THROUGH_REFERENCE(UnevaluatedInstance, getSubExpr); PASS_THROUGH_REFERENCE(DifferentiableFunction, getSubExpr); PASS_THROUGH_REFERENCE(LinearFunction, getSubExpr); PASS_THROUGH_REFERENCE(DifferentiableFunctionExtractOriginal, getSubExpr); PASS_THROUGH_REFERENCE(LinearFunctionExtractOriginal, getSubExpr); PASS_THROUGH_REFERENCE(LinearToDifferentiableFunction, getSubExpr); PASS_THROUGH_REFERENCE(BridgeToObjC, getSubExpr); PASS_THROUGH_REFERENCE(BridgeFromObjC, getSubExpr); PASS_THROUGH_REFERENCE(ConditionalBridgeFromObjC, getSubExpr); PASS_THROUGH_REFERENCE(UnderlyingToOpaque, getSubExpr); NO_REFERENCE(Coerce); NO_REFERENCE(ForcedCheckedCast); NO_REFERENCE(ConditionalCheckedCast); NO_REFERENCE(Is); NO_REFERENCE(Arrow); NO_REFERENCE(If); NO_REFERENCE(EnumIsCase); NO_REFERENCE(Assign); NO_REFERENCE(CodeCompletion); NO_REFERENCE(UnresolvedPattern); NO_REFERENCE(EditorPlaceholder); NO_REFERENCE(ObjCSelector); NO_REFERENCE(KeyPath); NO_REFERENCE(KeyPathDot); PASS_THROUGH_REFERENCE(OneWay, getSubExpr); NO_REFERENCE(Tap); #undef SIMPLE_REFERENCE #undef NO_REFERENCE #undef PASS_THROUGH_REFERENCE } return ConcreteDeclRef(); } /// Enumerate each immediate child expression of this node, invoking the /// specific functor on it. This ignores statements and other non-expression /// children. void Expr:: forEachImmediateChildExpr(llvm::function_ref<Expr *(Expr *)> callback) { struct ChildWalker : ASTWalker { llvm::function_ref<Expr *(Expr *)> callback; Expr *ThisNode; ChildWalker(llvm::function_ref<Expr *(Expr *)> callback, Expr *ThisNode) : callback(callback), ThisNode(ThisNode) {} std::pair<bool, Expr *> walkToExprPre(Expr *E) override { // When looking at the current node, of course we want to enter it. We // also don't want to enumerate it. if (E == ThisNode) return { true, E }; // Otherwise we must be a child of our expression, enumerate it! return { false, callback(E) }; } std::pair<bool, Stmt *> walkToStmtPre(Stmt *S) override { return { false, S }; } std::pair<bool, Pattern*> walkToPatternPre(Pattern *P) override { return { false, P }; } bool walkToDeclPre(Decl *D) override { return false; } bool walkToTypeReprPre(TypeRepr *T) override { return false; } }; this->walk(ChildWalker(callback, this)); } /// Enumerate each immediate child expression of this node, invoking the /// specific functor on it. This ignores statements and other non-expression /// children. void Expr::forEachChildExpr(llvm::function_ref<Expr *(Expr *)> callback) { struct ChildWalker : ASTWalker { llvm::function_ref<Expr *(Expr *)> callback; ChildWalker(llvm::function_ref<Expr *(Expr *)> callback) : callback(callback) {} std::pair<bool, Expr *> walkToExprPre(Expr *E) override { // Enumerate the node! return { true, callback(E) }; } std::pair<bool, Stmt *> walkToStmtPre(Stmt *S) override { return { false, S }; } std::pair<bool, Pattern*> walkToPatternPre(Pattern *P) override { return { false, P }; } bool walkToDeclPre(Decl *D) override { return false; } bool walkToTypeReprPre(TypeRepr *T) override { return false; } }; this->walk(ChildWalker(callback)); } bool Expr::isTypeReference(llvm::function_ref<Type(Expr *)> getType, llvm::function_ref<Decl *(Expr *)> getDecl) const { Expr *expr = const_cast<Expr *>(this); // If the result isn't a metatype, there's nothing else to do. if (!getType(expr)->is<AnyMetatypeType>()) return false; do { // Skip syntax. expr = expr->getSemanticsProvidingExpr(); // Direct reference to a type. if (auto declRef = dyn_cast<DeclRefExpr>(expr)) if (isa<TypeDecl>(declRef->getDecl())) return true; if (isa<TypeExpr>(expr)) return true; // A "." expression that refers to a member. if (auto memberRef = dyn_cast<MemberRefExpr>(expr)) return isa<TypeDecl>(memberRef->getMember().getDecl()); // Any other expressions which might be referencing // a declaration e.g. not yet type-checked ones like // `UnresolvedDotExpr`. if (auto *decl = getDecl(expr)) return isa<TypeDecl>(decl); // When the base of a "." expression is ignored, look at the member. if (auto ignoredDot = dyn_cast<DotSyntaxBaseIgnoredExpr>(expr)) { expr = ignoredDot->getRHS(); continue; } if (auto *USE = dyn_cast<UnresolvedSpecializeExpr>(expr)) { expr = USE->getSubExpr(); continue; } // Anything else is not statically derived. return false; } while (true); } bool Expr::isStaticallyDerivedMetatype( llvm::function_ref<Type(Expr *)> getType, llvm::function_ref<bool(Expr *)> isTypeReference) const { // The expression must first be a type reference. if (!isTypeReference(const_cast<Expr *>(this))) return false; auto type = getType(const_cast<Expr *>(this)) ->castTo<AnyMetatypeType>() ->getInstanceType(); // Archetypes are never statically derived. if (type->is<ArchetypeType>()) return false; // Dynamic Self is never statically derived. if (type->is<DynamicSelfType>()) return false; // Everything else is statically derived. return true; } bool Expr::isSuperExpr() const { const Expr *expr = this; do { expr = expr->getSemanticsProvidingExpr(); if (isa<SuperRefExpr>(expr)) return true; if (auto derivedToBase = dyn_cast<DerivedToBaseExpr>(expr)) { expr = derivedToBase->getSubExpr(); continue; } if (auto metatypeConversion = dyn_cast<MetatypeConversionExpr>(expr)) { expr = metatypeConversion->getSubExpr(); continue; } return false; } while (true); } bool Expr::canAppendPostfixExpression(bool appendingPostfixOperator) const { switch (getKind()) { case ExprKind::Error: case ExprKind::CodeCompletion: case ExprKind::LazyInitializer: case ExprKind::OneWay: return false; case ExprKind::NilLiteral: case ExprKind::IntegerLiteral: case ExprKind::FloatLiteral: case ExprKind::BooleanLiteral: case ExprKind::StringLiteral: case ExprKind::InterpolatedStringLiteral: case ExprKind::MagicIdentifierLiteral: case ExprKind::ObjCSelector: case ExprKind::KeyPath: return true; case ExprKind::ObjectLiteral: return true; case ExprKind::DiscardAssignment: // Legal but pointless. return true; case ExprKind::DeclRef: return !cast<DeclRefExpr>(this)->getDecl()->isOperator(); case ExprKind::SuperRef: case ExprKind::OtherConstructorDeclRef: case ExprKind::DotSyntaxBaseIgnored: return true; case ExprKind::Type: return cast<TypeExpr>(this)->getTypeRepr()->isSimple(); case ExprKind::OverloadedDeclRef: { auto *overloadedExpr = cast<OverloadedDeclRefExpr>(this); if (overloadedExpr->getDecls().empty()) return false; return !overloadedExpr->getDecls().front()->isOperator(); } case ExprKind::UnresolvedDeclRef: return cast<UnresolvedDeclRefExpr>(this)->getName().isOperator(); case ExprKind::MemberRef: case ExprKind::DynamicMemberRef: case ExprKind::DynamicSubscript: case ExprKind::UnresolvedSpecialize: case ExprKind::UnresolvedMember: case ExprKind::UnresolvedDot: return true; case ExprKind::Sequence: return false; case ExprKind::Paren: case ExprKind::DotSelf: case ExprKind::UnresolvedMemberChainResult: case ExprKind::Tuple: case ExprKind::Array: case ExprKind::Dictionary: case ExprKind::Subscript: case ExprKind::KeyPathApplication: case ExprKind::TupleElement: return true; case ExprKind::CaptureList: case ExprKind::Closure: case ExprKind::AutoClosure: return false; case ExprKind::DynamicType: return true; case ExprKind::Await: case ExprKind::Try: case ExprKind::ForceTry: case ExprKind::OptionalTry: case ExprKind::InOut: return false; case ExprKind::RebindSelfInConstructor: case ExprKind::OpaqueValue: case ExprKind::PropertyWrapperValuePlaceholder: case ExprKind::DefaultArgument: case ExprKind::BindOptional: case ExprKind::OptionalEvaluation: return false; case ExprKind::ForceValue: return true; case ExprKind::OpenExistential: case ExprKind::MakeTemporarilyEscapable: case ExprKind::VarargExpansion: return false; case ExprKind::Call: case ExprKind::DotSyntaxCall: case ExprKind::ConstructorRefCall: return true; case ExprKind::PostfixUnary: return !appendingPostfixOperator; case ExprKind::PrefixUnary: case ExprKind::Binary: return false; case ExprKind::Load: case ExprKind::DestructureTuple: case ExprKind::UnresolvedTypeConversion: case ExprKind::FunctionConversion: case ExprKind::CovariantFunctionConversion: case ExprKind::CovariantReturnConversion: case ExprKind::ImplicitlyUnwrappedFunctionConversion: case ExprKind::MetatypeConversion: case ExprKind::CollectionUpcastConversion: case ExprKind::Erasure: case ExprKind::AnyHashableErasure: case ExprKind::DerivedToBase: case ExprKind::ArchetypeToSuper: case ExprKind::InjectIntoOptional: case ExprKind::ClassMetatypeToObject: case ExprKind::ExistentialMetatypeToObject: case ExprKind::ProtocolMetatypeToObject: case ExprKind::InOutToPointer: case ExprKind::ArrayToPointer: case ExprKind::StringToPointer: case ExprKind::PointerToPointer: case ExprKind::ForeignObjectConversion: case ExprKind::UnevaluatedInstance: case ExprKind::DifferentiableFunction: case ExprKind::LinearFunction: case ExprKind::DifferentiableFunctionExtractOriginal: case ExprKind::LinearFunctionExtractOriginal: case ExprKind::LinearToDifferentiableFunction: case ExprKind::EnumIsCase: case ExprKind::ConditionalBridgeFromObjC: case ExprKind::BridgeFromObjC: case ExprKind::BridgeToObjC: case ExprKind::UnderlyingToOpaque: // Implicit conversion nodes have no syntax of their own; defer to the // subexpression. return cast<ImplicitConversionExpr>(this)->getSubExpr() ->canAppendPostfixExpression(appendingPostfixOperator); case ExprKind::ForcedCheckedCast: case ExprKind::ConditionalCheckedCast: case ExprKind::Is: case ExprKind::Coerce: return false; case ExprKind::Arrow: case ExprKind::If: case ExprKind::Assign: case ExprKind::UnresolvedPattern: case ExprKind::EditorPlaceholder: case ExprKind::KeyPathDot: return false; case ExprKind::Tap: return true; } llvm_unreachable("Unhandled ExprKind in switch."); } llvm::DenseMap<Expr *, Expr *> Expr::getParentMap() { class RecordingTraversal : public ASTWalker { public: llvm::DenseMap<Expr *, Expr *> &ParentMap; explicit RecordingTraversal(llvm::DenseMap<Expr *, Expr *> &parentMap) : ParentMap(parentMap) { } std::pair<bool, Expr *> walkToExprPre(Expr *E) override { if (auto parent = Parent.getAsExpr()) ParentMap[E] = parent; return { true, E }; } }; llvm::DenseMap<Expr *, Expr *> parentMap; RecordingTraversal traversal(parentMap); walk(traversal); return parentMap; } //===----------------------------------------------------------------------===// // Support methods for Exprs. //===----------------------------------------------------------------------===// IntegerLiteralExpr * IntegerLiteralExpr::createFromUnsigned(ASTContext &C, unsigned value) { llvm::SmallString<8> Scratch; llvm::APInt(sizeof(unsigned)*8, value).toString(Scratch, 10, /*signed*/ false); auto Text = C.AllocateCopy(StringRef(Scratch)); return new (C) IntegerLiteralExpr(Text, SourceLoc(), /*implicit*/ true); } APInt IntegerLiteralExpr::getRawValue() const { return BuiltinIntegerWidth::arbitrary().parse(getDigitsText(), /*radix*/0, isNegative()); } APInt IntegerLiteralExpr::getValue() const { assert(!getType().isNull() && "Semantic analysis has not completed"); assert(!getType()->hasError() && "Should have a valid type"); if (!getType()->is<AnyBuiltinIntegerType>()) return getRawValue(); auto width = getType()->castTo<AnyBuiltinIntegerType>()->getWidth(); return width.parse(getDigitsText(), /*radix*/ 0, isNegative()); } APInt BuiltinIntegerWidth::parse(StringRef text, unsigned radix, bool negate, bool *hadError) const { if (hadError) *hadError = false; // Parse an unsigned value from the string. APInt value; // Swift doesn't treat a leading zero as signifying octal, but // StringRef::getAsInteger does. Force decimal parsing in this case. if (radix == 0 && text.size() >= 2 && text[0] == '0' && isdigit(text[1])) radix = 10; bool error = text.getAsInteger(radix, value); if (error) { if (hadError) *hadError = true; return value; } // If we're producing an arbitrary-precision value, we don't need to do // much additional processing. if (isArbitraryWidth()) { // The parser above always produces a non-negative value, so if the sign // bit is set we need to give it some breathing room. if (value.isNegative()) value = value.zext(value.getBitWidth() + 1); assert(!value.isNegative()); // Now we can safely negate. if (negate) { value = -value; assert(value.isNegative() || value.isNullValue()); } // Truncate down to the minimum number of bits required to express // this value exactly. auto requiredBits = value.getMinSignedBits(); if (value.getBitWidth() > requiredBits) value = value.trunc(requiredBits); // If we have a fixed-width type (including abstract ones), we need to do // fixed-width transformations, which can overflow. } else { unsigned width = getGreatestWidth(); // The overflow diagnostics in this case can't be fully correct because // we don't know whether we're supposed to be producing a signed number // or an unsigned one. if (hadError && value.getActiveBits() > width) *hadError = true; value = value.zextOrTrunc(width); if (negate) { value = -value; if (hadError && !value.isNegative()) *hadError = true; } assert(value.getBitWidth() == width); } return value; } static APFloat getFloatLiteralValue(bool IsNegative, StringRef Text, const llvm::fltSemantics &Semantics) { APFloat Val(Semantics); auto Res = Val.convertFromString(Text, llvm::APFloat::rmNearestTiesToEven); assert(Res && "Sema didn't reject invalid number"); consumeError(Res.takeError()); if (IsNegative) { auto NegVal = APFloat::getZero(Semantics, /*negative*/ true); Res = NegVal.subtract(Val, llvm::APFloat::rmNearestTiesToEven); assert(Res && "Sema didn't reject invalid number"); consumeError(Res.takeError()); return NegVal; } return Val; } APFloat FloatLiteralExpr::getValue(StringRef Text, const llvm::fltSemantics &Semantics, bool Negative) { return getFloatLiteralValue(Negative, Text, Semantics); } llvm::APFloat FloatLiteralExpr::getValue() const { assert(!getType().isNull() && "Semantic analysis has not completed"); assert(!getType()->hasError() && "Should have a valid type"); Type ty = getType(); if (!ty->is<BuiltinFloatType>()) { assert(!getBuiltinType().isNull() && "Semantic analysis has not completed"); assert(!getBuiltinType()->hasError() && "Should have a valid type"); ty = getBuiltinType(); } return getFloatLiteralValue( isNegative(), getDigitsText(), ty->castTo<BuiltinFloatType>()->getAPFloatSemantics()); } StringLiteralExpr::StringLiteralExpr(StringRef Val, SourceRange Range, bool Implicit) : BuiltinLiteralExpr(ExprKind::StringLiteral, Implicit), Val(Val), Range(Range) { Bits.StringLiteralExpr.Encoding = static_cast<unsigned>(UTF8); Bits.StringLiteralExpr.IsSingleUnicodeScalar = unicode::isSingleUnicodeScalar(Val); Bits.StringLiteralExpr.IsSingleExtendedGraphemeCluster = unicode::isSingleExtendedGraphemeCluster(Val); } static ArrayRef<Identifier> getArgumentLabelsFromArgument( Expr *arg, SmallVectorImpl<Identifier> &scratch, SmallVectorImpl<SourceLoc> *sourceLocs = nullptr, bool *hasTrailingClosure = nullptr, llvm::function_ref<Type(Expr *)> getType = [](Expr *E) -> Type { return E->getType(); }) { if (sourceLocs) sourceLocs->clear(); if (hasTrailingClosure) *hasTrailingClosure = false; // A parenthesized expression is a single, unlabeled argument. if (auto paren = dyn_cast<ParenExpr>(arg)) { scratch.clear(); scratch.push_back(Identifier()); if (hasTrailingClosure) *hasTrailingClosure = paren->hasTrailingClosure(); return scratch; } // A tuple expression stores its element names, if they exist. if (auto tuple = dyn_cast<TupleExpr>(arg)) { if (sourceLocs && tuple->hasElementNameLocs()) { sourceLocs->append(tuple->getElementNameLocs().begin(), tuple->getElementNameLocs().end()); } if (hasTrailingClosure) *hasTrailingClosure = tuple->hasTrailingClosure(); if (tuple->hasElementNames()) { assert(tuple->getElementNames().size() == tuple->getNumElements()); return tuple->getElementNames(); } scratch.assign(tuple->getNumElements(), Identifier()); return scratch; } // Otherwise, use the type information. auto type = getType(arg); if (type->hasParenSugar()) { scratch.clear(); scratch.push_back(Identifier()); return scratch; } // FIXME: Should be a dyn_cast. if (auto tupleTy = type->getAs<TupleType>()) { scratch.clear(); for (const auto &elt : tupleTy->getElements()) scratch.push_back(elt.getName()); return scratch; } // FIXME: Shouldn't get here. scratch.clear(); scratch.push_back(Identifier()); return scratch; } /// Compute the type of an argument to a call (or call-like) AST static void computeSingleArgumentType(ASTContext &ctx, Expr *arg, bool implicit, llvm::function_ref<Type(Expr *)> getType) { // Propagate 'implicit' to the argument. if (implicit) { arg->setImplicit(true); } // Handle parenthesized expressions. if (auto paren = dyn_cast<ParenExpr>(arg)) { if (auto type = getType(paren->getSubExpr())) { auto parenFlags = ParameterTypeFlags().withInOut(type->is<InOutType>()); arg->setType(ParenType::get(ctx, type->getInOutObjectType(), parenFlags)); } return; } // Handle tuples. auto tuple = dyn_cast<TupleExpr>(arg); SmallVector<TupleTypeElt, 4> typeElements; for (unsigned i = 0, n = tuple->getNumElements(); i != n; ++i) { auto type = getType(tuple->getElement(i)); if (!type) return; bool isInOut = tuple->getElement(i)->isSemanticallyInOutExpr(); typeElements.push_back(TupleTypeElt(type->getInOutObjectType(), tuple->getElementName(i), ParameterTypeFlags().withInOut(isInOut))); } arg->setType(TupleType::get(typeElements, ctx)); } Expr *swift::packSingleArgument(ASTContext &ctx, SourceLoc lParenLoc, ArrayRef<Expr *> args, ArrayRef<Identifier> &argLabels, ArrayRef<SourceLoc> &argLabelLocs, SourceLoc rParenLoc, ArrayRef<TrailingClosure> trailingClosures, bool implicit, SmallVectorImpl<Identifier> &argLabelsScratch, SmallVectorImpl<SourceLoc> &argLabelLocsScratch, llvm::function_ref<Type(Expr *)> getType) { // Clear out our scratch space. argLabelsScratch.clear(); argLabelLocsScratch.clear(); // Construct a TupleExpr or ParenExpr, as appropriate, for the argument. if (trailingClosures.empty()) { // Do we have a single, unlabeled argument? if (args.size() == 1 && (argLabels.empty() || argLabels[0].empty())) { auto arg = new (ctx) ParenExpr(lParenLoc, args[0], rParenLoc, /*hasTrailingClosure=*/false); computeSingleArgumentType(ctx, arg, implicit, getType); argLabelsScratch.push_back(Identifier()); argLabels = argLabelsScratch; argLabelLocs = { }; return arg; } // Make sure we have argument labels. if (argLabels.empty()) { argLabelsScratch.assign(args.size(), Identifier()); argLabels = argLabelsScratch; } // Construct the argument tuple. if (argLabels.empty() && !args.empty()) { argLabelsScratch.assign(args.size(), Identifier()); argLabels = argLabelsScratch; } auto arg = TupleExpr::create(ctx, lParenLoc, args, argLabels, argLabelLocs, rParenLoc, /*HasTrailingClosure=*/false, implicit); computeSingleArgumentType(ctx, arg, implicit, getType); return arg; } // If we have no other arguments, represent the a single trailing closure as a // parenthesized expression. if (args.empty() && trailingClosures.size() == 1 && trailingClosures.front().LabelLoc.isInvalid()) { auto &trailingClosure = trailingClosures.front(); auto arg = new (ctx) ParenExpr(lParenLoc, trailingClosure.ClosureExpr, rParenLoc, /*hasTrailingClosure=*/true); computeSingleArgumentType(ctx, arg, implicit, getType); argLabelsScratch.push_back(Identifier()); argLabels = argLabelsScratch; argLabelLocs = { }; return arg; } assert(argLabels.empty() || args.size() == argLabels.size()); unsigned numRegularArgs = args.size(); // Form a tuple, including the trailing closure. SmallVector<Expr *, 4> argsScratch; argsScratch.reserve(numRegularArgs + trailingClosures.size()); argsScratch.append(args.begin(), args.end()); for (const auto &closure : trailingClosures) argsScratch.push_back(closure.ClosureExpr); args = argsScratch; { if (argLabels.empty()) { argLabelsScratch.resize(numRegularArgs); } else { argLabelsScratch.append(argLabels.begin(), argLabels.end()); } for (const auto &closure : trailingClosures) argLabelsScratch.push_back(closure.Label); argLabels = argLabelsScratch; } { if (argLabelLocs.empty()) { argLabelLocsScratch.resize(numRegularArgs); } else { argLabelLocsScratch.append(argLabelLocs.begin(), argLabelLocs.end()); } for (const auto &closure : trailingClosures) argLabelLocsScratch.push_back(closure.LabelLoc); argLabelLocs = argLabelLocsScratch; } Optional<unsigned> unlabeledTrailingClosureIndex; if (!trailingClosures.empty() && trailingClosures[0].Label.empty()) unlabeledTrailingClosureIndex = args.size() - trailingClosures.size(); auto arg = TupleExpr::create(ctx, lParenLoc, rParenLoc, args, argLabels, argLabelLocs, unlabeledTrailingClosureIndex, /*Implicit=*/false); computeSingleArgumentType(ctx, arg, implicit, getType); return arg; } Optional<unsigned> Expr::getUnlabeledTrailingClosureIndexOfPackedArgument() const { if (auto PE = dyn_cast<ParenExpr>(this)) return PE->getUnlabeledTrailingClosureIndexOfPackedArgument(); if (auto TE = dyn_cast<TupleExpr>(this)) return TE->getUnlabeledTrailingClosureIndexOfPackedArgument(); return None; } ObjectLiteralExpr::ObjectLiteralExpr(SourceLoc PoundLoc, LiteralKind LitKind, Expr *Arg, ArrayRef<Identifier> argLabels, ArrayRef<SourceLoc> argLabelLocs, bool hasTrailingClosure, bool implicit) : LiteralExpr(ExprKind::ObjectLiteral, implicit), Arg(Arg), PoundLoc(PoundLoc) { Bits.ObjectLiteralExpr.LitKind = static_cast<unsigned>(LitKind); assert(getLiteralKind() == LitKind); Bits.ObjectLiteralExpr.NumArgLabels = argLabels.size(); Bits.ObjectLiteralExpr.HasArgLabelLocs = !argLabelLocs.empty(); Bits.ObjectLiteralExpr.HasTrailingClosure = hasTrailingClosure; initializeCallArguments(argLabels, argLabelLocs); } ObjectLiteralExpr * ObjectLiteralExpr::create(ASTContext &ctx, SourceLoc poundLoc, LiteralKind kind, Expr *arg, bool implicit, llvm::function_ref<Type(Expr *)> getType) { // Inspect the argument to dig out the argument labels, their location, and // whether there is a trailing closure. SmallVector<Identifier, 4> argLabelsScratch; SmallVector<SourceLoc, 4> argLabelLocs; bool hasTrailingClosure = false; auto argLabels = getArgumentLabelsFromArgument(arg, argLabelsScratch, &argLabelLocs, &hasTrailingClosure, getType); size_t size = totalSizeToAlloc(argLabels, argLabelLocs); void *memory = ctx.Allocate(size, alignof(ObjectLiteralExpr)); return new (memory) ObjectLiteralExpr(poundLoc, kind, arg, argLabels, argLabelLocs, hasTrailingClosure, implicit); } ObjectLiteralExpr *ObjectLiteralExpr::create(ASTContext &ctx, SourceLoc poundLoc, LiteralKind kind, SourceLoc lParenLoc, ArrayRef<Expr *> args, ArrayRef<Identifier> argLabels, ArrayRef<SourceLoc> argLabelLocs, SourceLoc rParenLoc, ArrayRef<TrailingClosure> trailingClosures, bool implicit) { SmallVector<Identifier, 4> argLabelsScratch; SmallVector<SourceLoc, 4> argLabelLocsScratch; Expr *arg = packSingleArgument(ctx, lParenLoc, args, argLabels, argLabelLocs, rParenLoc, trailingClosures, implicit, argLabelsScratch, argLabelLocsScratch); size_t size = totalSizeToAlloc(argLabels, argLabelLocs); void *memory = ctx.Allocate(size, alignof(ObjectLiteralExpr)); return new (memory) ObjectLiteralExpr(poundLoc, kind, arg, argLabels, argLabelLocs, trailingClosures.size() == 1, implicit); } StringRef ObjectLiteralExpr::getLiteralKindRawName() const { switch (getLiteralKind()) { #define POUND_OBJECT_LITERAL(Name, Desc, Proto) case Name: return #Name; #include "swift/Syntax/TokenKinds.def" } llvm_unreachable("unspecified literal"); } StringRef ObjectLiteralExpr::getLiteralKindPlainName() const { switch (getLiteralKind()) { #define POUND_OBJECT_LITERAL(Name, Desc, Proto) case Name: return Desc; #include "swift/Syntax/TokenKinds.def" } llvm_unreachable("unspecified literal"); } ConstructorDecl *OtherConstructorDeclRefExpr::getDecl() const { return cast_or_null<ConstructorDecl>(Ctor.getDecl()); } MemberRefExpr::MemberRefExpr(Expr *base, SourceLoc dotLoc, ConcreteDeclRef member, DeclNameLoc nameLoc, bool Implicit, AccessSemantics semantics) : LookupExpr(ExprKind::MemberRef, base, member, Implicit), DotLoc(dotLoc), NameLoc(nameLoc) { Bits.MemberRefExpr.Semantics = (unsigned) semantics; } Type OverloadSetRefExpr::getBaseType() const { if (isa<OverloadedDeclRefExpr>(this)) return Type(); llvm_unreachable("Unhandled overloaded set reference expression"); } bool OverloadSetRefExpr::hasBaseObject() const { if (Type BaseTy = getBaseType()) return !BaseTy->is<AnyMetatypeType>(); return false; } InOutExpr::InOutExpr(SourceLoc operLoc, Expr *subExpr, Type baseType, bool isImplicit) : Expr(ExprKind::InOut, isImplicit, baseType.isNull() ? baseType : InOutType::get(baseType)), SubExpr(subExpr), OperLoc(operLoc) {} SequenceExpr *SequenceExpr::create(ASTContext &ctx, ArrayRef<Expr*> elements) { assert(elements.size() & 1 && "even number of elements in sequence"); size_t bytes = totalSizeToAlloc<Expr *>(elements.size()); void *Buffer = ctx.Allocate(bytes, alignof(SequenceExpr)); return ::new(Buffer) SequenceExpr(elements); } ErasureExpr *ErasureExpr::create(ASTContext &ctx, Expr *subExpr, Type type, ArrayRef<ProtocolConformanceRef> conformances){ auto size = totalSizeToAlloc<ProtocolConformanceRef>(conformances.size()); auto mem = ctx.Allocate(size, alignof(ErasureExpr)); return ::new(mem) ErasureExpr(subExpr, type, conformances); } UnresolvedSpecializeExpr *UnresolvedSpecializeExpr::create(ASTContext &ctx, Expr *SubExpr, SourceLoc LAngleLoc, ArrayRef<TypeRepr *> UnresolvedParams, SourceLoc RAngleLoc) { auto size = totalSizeToAlloc<TypeRepr *>(UnresolvedParams.size()); auto mem = ctx.Allocate(size, alignof(UnresolvedSpecializeExpr)); return ::new(mem) UnresolvedSpecializeExpr(SubExpr, LAngleLoc, UnresolvedParams, RAngleLoc); } bool CaptureListEntry::isSimpleSelfCapture() const { auto &ctx = Var->getASTContext(); if (Var->getName() != ctx.Id_self) return false; if (auto *attr = Var->getAttrs().getAttribute<ReferenceOwnershipAttr>()) if (attr->get() == ReferenceOwnership::Weak) return false; if (Init->getPatternList().size() != 1) return false; auto *expr = Init->getInit(0); if (auto *DRE = dyn_cast<DeclRefExpr>(expr)) { if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) { return VD->getName() == ctx.Id_self; } } if (auto *UDRE = dyn_cast<UnresolvedDeclRefExpr>(expr)) { return UDRE->getName().isSimpleName(ctx.Id_self); } return false; } CaptureListExpr *CaptureListExpr::create(ASTContext &ctx, ArrayRef<CaptureListEntry> captureList, ClosureExpr *closureBody) { auto size = totalSizeToAlloc<CaptureListEntry>(captureList.size()); auto mem = ctx.Allocate(size, alignof(CaptureListExpr)); auto *expr = ::new(mem) CaptureListExpr(captureList, closureBody); for (auto capture : captureList) capture.Var->setParentCaptureList(expr); return expr; } DestructureTupleExpr * DestructureTupleExpr::create(ASTContext &ctx, ArrayRef<OpaqueValueExpr *> destructuredElements, Expr *srcExpr, Expr *dstExpr, Type ty) { auto size = totalSizeToAlloc<OpaqueValueExpr *>(destructuredElements.size()); auto mem = ctx.Allocate(size, alignof(DestructureTupleExpr)); return ::new(mem) DestructureTupleExpr(destructuredElements, srcExpr, dstExpr, ty); } SourceRange TupleExpr::getSourceRange() const { SourceLoc start = SourceLoc(); SourceLoc end = SourceLoc(); if (LParenLoc.isValid()) { start = LParenLoc; } else if (getNumElements() == 0) { return { SourceLoc(), SourceLoc() }; } else { // Scan forward for the first valid source loc. for (Expr *expr : getElements()) { start = expr->getStartLoc(); if (start.isValid()) { break; } } } if (hasAnyTrailingClosures() || RParenLoc.isInvalid()) { if (getNumElements() == 0) { return { SourceLoc(), SourceLoc() }; } else { // Scan backwards for a valid source loc. bool hasSingleTrailingClosure = hasTrailingClosure(); for (Expr *expr : llvm::reverse(getElements())) { // Default arguments are located at the start of their parent tuple, so // skip over them. if (isa<DefaultArgumentExpr>(expr)) continue; SourceLoc newEnd = expr->getEndLoc(); if (newEnd.isInvalid()) continue; // There is a quirk with the backward scan logic for trailing // closures that can cause arguments to be flipped. If there is a // single trailing closure, only stop when the "end" point we hit comes // after the close parenthesis (if there is one). if (end.isInvalid() || end.getOpaquePointerValue() < newEnd.getOpaquePointerValue()) { end = newEnd; } if (!hasSingleTrailingClosure || RParenLoc.isInvalid() || RParenLoc.getOpaquePointerValue() < end.getOpaquePointerValue()) break; } } } else { end = RParenLoc; } if (start.isValid() && end.isValid()) { return { start, end }; } else { return { SourceLoc(), SourceLoc() }; } } TupleExpr::TupleExpr(SourceLoc LParenLoc, SourceLoc RParenLoc, ArrayRef<Expr *> SubExprs, ArrayRef<Identifier> ElementNames, ArrayRef<SourceLoc> ElementNameLocs, Optional<unsigned> FirstTrailingArgumentAt, bool Implicit, Type Ty) : Expr(ExprKind::Tuple, Implicit, Ty), LParenLoc(LParenLoc), RParenLoc(RParenLoc), FirstTrailingArgumentAt(FirstTrailingArgumentAt) { Bits.TupleExpr.HasElementNames = !ElementNames.empty(); Bits.TupleExpr.HasElementNameLocations = !ElementNameLocs.empty(); Bits.TupleExpr.NumElements = SubExprs.size(); assert(LParenLoc.isValid() == RParenLoc.isValid() && "Mismatched parenthesis location information validity"); assert(ElementNames.empty() || ElementNames.size() == SubExprs.size()); assert(ElementNameLocs.empty() || ElementNames.size() == ElementNameLocs.size()); // Copy elements. std::uninitialized_copy(SubExprs.begin(), SubExprs.end(), getTrailingObjects<Expr *>()); // Copy element names, if provided. if (hasElementNames()) { std::uninitialized_copy(ElementNames.begin(), ElementNames.end(), getTrailingObjects<Identifier>()); } // Copy element name locations, if provided. if (hasElementNameLocs()) { std::uninitialized_copy(ElementNameLocs.begin(), ElementNameLocs.end(), getTrailingObjects<SourceLoc>()); } } TupleExpr *TupleExpr::create(ASTContext &ctx, SourceLoc LParenLoc, ArrayRef<Expr *> SubExprs, ArrayRef<Identifier> ElementNames, ArrayRef<SourceLoc> ElementNameLocs, SourceLoc RParenLoc, bool HasTrailingClosure, bool Implicit, Type Ty) { Optional<unsigned> FirstTrailingArgumentAt = HasTrailingClosure ? SubExprs.size() - 1 : Optional<unsigned>(); return create(ctx, LParenLoc, RParenLoc, SubExprs, ElementNames, ElementNameLocs, FirstTrailingArgumentAt, Implicit, Ty); } TupleExpr *TupleExpr::create(ASTContext &ctx, SourceLoc LParenLoc, SourceLoc RParenLoc, ArrayRef<Expr *> SubExprs, ArrayRef<Identifier> ElementNames, ArrayRef<SourceLoc> ElementNameLocs, Optional<unsigned> FirstTrailingArgumentAt, bool Implicit, Type Ty) { assert(!Ty || isa<TupleType>(Ty.getPointer())); auto hasNonEmptyIdentifier = [](ArrayRef<Identifier> Ids) -> bool { for (auto ident : Ids) { if (!ident.empty()) return true; } return false; }; assert((Implicit || ElementNames.size() == ElementNameLocs.size() || (!hasNonEmptyIdentifier(ElementNames) && ElementNameLocs.empty())) && "trying to create non-implicit tuple-expr without name locations"); (void)hasNonEmptyIdentifier; size_t size = totalSizeToAlloc<Expr *, Identifier, SourceLoc>(SubExprs.size(), ElementNames.size(), ElementNameLocs.size()); void *mem = ctx.Allocate(size, alignof(TupleExpr)); return new (mem) TupleExpr(LParenLoc, RParenLoc, SubExprs, ElementNames, ElementNameLocs, FirstTrailingArgumentAt, Implicit, Ty); } TupleExpr *TupleExpr::createEmpty(ASTContext &ctx, SourceLoc LParenLoc, SourceLoc RParenLoc, bool Implicit) { return create(ctx, LParenLoc, RParenLoc, {}, {}, {}, /*FirstTrailingArgumentAt=*/None, Implicit, TupleType::getEmpty(ctx)); } TupleExpr *TupleExpr::createImplicit(ASTContext &ctx, ArrayRef<Expr *> SubExprs, ArrayRef<Identifier> ElementNames) { return create(ctx, SourceLoc(), SourceLoc(), SubExprs, ElementNames, {}, /*FirstTrailingArgumentAt=*/None, /*Implicit=*/true, Type()); } ArrayExpr *ArrayExpr::create(ASTContext &C, SourceLoc LBracketLoc, ArrayRef<Expr*> Elements, ArrayRef<SourceLoc> CommaLocs, SourceLoc RBracketLoc, Type Ty) { auto Size = totalSizeToAlloc<Expr *, SourceLoc>(Elements.size(), CommaLocs.size()); auto Mem = C.Allocate(Size, alignof(ArrayExpr)); return new (Mem) ArrayExpr(LBracketLoc, Elements, CommaLocs, RBracketLoc, Ty); } Type ArrayExpr::getElementType() { auto init = getInitializer(); if (!init) return Type(); auto *decl = cast<ConstructorDecl>(init.getDecl()); return decl->getMethodInterfaceType() ->getAs<AnyFunctionType>() ->getParams()[0] .getPlainType() .subst(init.getSubstitutions()); } Type DictionaryExpr::getElementType() { auto init = getInitializer(); if (!init) return Type(); auto *decl = cast<ConstructorDecl>(init.getDecl()); return decl->getMethodInterfaceType() ->getAs<AnyFunctionType>() ->getParams()[0] .getPlainType() .subst(init.getSubstitutions()); } DictionaryExpr *DictionaryExpr::create(ASTContext &C, SourceLoc LBracketLoc, ArrayRef<Expr*> Elements, ArrayRef<SourceLoc> CommaLocs, SourceLoc RBracketLoc, Type Ty) { auto Size = totalSizeToAlloc<Expr *, SourceLoc>(Elements.size(), CommaLocs.size()); auto Mem = C.Allocate(Size, alignof(DictionaryExpr)); return new (Mem) DictionaryExpr(LBracketLoc, Elements, CommaLocs, RBracketLoc, Ty); } static ValueDecl *getCalledValue(Expr *E) { if (auto *DRE = dyn_cast<DeclRefExpr>(E)) return DRE->getDecl(); if (auto *OCRE = dyn_cast<OtherConstructorDeclRefExpr>(E)) return OCRE->getDecl(); // Look through SelfApplyExpr. if (auto *SAE = dyn_cast<SelfApplyExpr>(E)) return SAE->getCalledValue(); Expr *E2 = E->getValueProvidingExpr(); if (E != E2) return getCalledValue(E2); return nullptr; } PropertyWrapperValuePlaceholderExpr * PropertyWrapperValuePlaceholderExpr::create(ASTContext &ctx, SourceRange range, Type ty, Expr *wrappedValue, bool isAutoClosure) { auto *placeholder = new (ctx) OpaqueValueExpr(range, ty, /*isPlaceholder=*/true); return new (ctx) PropertyWrapperValuePlaceholderExpr( range, ty, placeholder, wrappedValue, isAutoClosure); } const ParamDecl *DefaultArgumentExpr::getParamDecl() const { return getParameterAt(DefaultArgsOwner.getDecl(), ParamIndex); } bool DefaultArgumentExpr::isCallerSide() const { return getParamDecl()->hasCallerSideDefaultExpr(); } Expr *DefaultArgumentExpr::getCallerSideDefaultExpr() const { assert(isCallerSide()); auto &ctx = DefaultArgsOwner.getDecl()->getASTContext(); auto *mutableThis = const_cast<DefaultArgumentExpr *>(this); return evaluateOrDefault(ctx.evaluator, CallerSideDefaultArgExprRequest{mutableThis}, new (ctx) ErrorExpr(getSourceRange(), getType())); } ValueDecl *ApplyExpr::getCalledValue() const { return ::getCalledValue(Fn); } SubscriptExpr::SubscriptExpr(Expr *base, Expr *index, ArrayRef<Identifier> argLabels, ArrayRef<SourceLoc> argLabelLocs, bool hasTrailingClosure, ConcreteDeclRef decl, bool implicit, AccessSemantics semantics) : LookupExpr(ExprKind::Subscript, base, decl, implicit), Index(index) { Bits.SubscriptExpr.Semantics = (unsigned) semantics; Bits.SubscriptExpr.NumArgLabels = argLabels.size(); Bits.SubscriptExpr.HasArgLabelLocs = !argLabelLocs.empty(); Bits.SubscriptExpr.HasTrailingClosure = hasTrailingClosure; initializeCallArguments(argLabels, argLabelLocs); } SubscriptExpr *SubscriptExpr::create(ASTContext &ctx, Expr *base, Expr *index, ConcreteDeclRef decl, bool implicit, AccessSemantics semantics, llvm::function_ref<Type(Expr *)> getType) { // Inspect the argument to dig out the argument labels, their location, and // whether there is a trailing closure. SmallVector<Identifier, 4> argLabelsScratch; SmallVector<SourceLoc, 4> argLabelLocs; bool hasTrailingClosure = false; auto argLabels = getArgumentLabelsFromArgument(index, argLabelsScratch, &argLabelLocs, &hasTrailingClosure, getType); size_t size = totalSizeToAlloc(argLabels, argLabelLocs); void *memory = ctx.Allocate(size, alignof(SubscriptExpr)); return new (memory) SubscriptExpr(base, index, argLabels, argLabelLocs, hasTrailingClosure, decl, implicit, semantics); } SubscriptExpr *SubscriptExpr::create(ASTContext &ctx, Expr *base, SourceLoc lSquareLoc, ArrayRef<Expr *> indexArgs, ArrayRef<Identifier> indexArgLabels, ArrayRef<SourceLoc> indexArgLabelLocs, SourceLoc rSquareLoc, ArrayRef<TrailingClosure> trailingClosures, ConcreteDeclRef decl, bool implicit, AccessSemantics semantics) { SmallVector<Identifier, 4> indexArgLabelsScratch; SmallVector<SourceLoc, 4> indexArgLabelLocsScratch; Expr *index = packSingleArgument(ctx, lSquareLoc, indexArgs, indexArgLabels, indexArgLabelLocs, rSquareLoc, trailingClosures, implicit, indexArgLabelsScratch, indexArgLabelLocsScratch); size_t size = totalSizeToAlloc(indexArgLabels, indexArgLabelLocs); void *memory = ctx.Allocate(size, alignof(SubscriptExpr)); return new (memory) SubscriptExpr(base, index, indexArgLabels, indexArgLabelLocs, trailingClosures.size() == 1, decl, implicit, semantics); } DynamicSubscriptExpr::DynamicSubscriptExpr(Expr *base, Expr *index, ArrayRef<Identifier> argLabels, ArrayRef<SourceLoc> argLabelLocs, bool hasTrailingClosure, ConcreteDeclRef member, bool implicit) : DynamicLookupExpr(ExprKind::DynamicSubscript, member, base), Index(index) { Bits.DynamicSubscriptExpr.NumArgLabels = argLabels.size(); Bits.DynamicSubscriptExpr.HasArgLabelLocs = !argLabelLocs.empty(); Bits.DynamicSubscriptExpr.HasTrailingClosure = hasTrailingClosure; initializeCallArguments(argLabels, argLabelLocs); if (implicit) setImplicit(implicit); } DynamicSubscriptExpr * DynamicSubscriptExpr::create(ASTContext &ctx, Expr *base, Expr *index, ConcreteDeclRef decl, bool implicit, llvm::function_ref<Type(Expr *)> getType) { // Inspect the argument to dig out the argument labels, their location, and // whether there is a trailing closure. SmallVector<Identifier, 4> argLabelsScratch; SmallVector<SourceLoc, 4> argLabelLocs; bool hasTrailingClosure = false; auto argLabels = getArgumentLabelsFromArgument(index, argLabelsScratch, &argLabelLocs, &hasTrailingClosure, getType); size_t size = totalSizeToAlloc(argLabels, argLabelLocs); void *memory = ctx.Allocate(size, alignof(DynamicSubscriptExpr)); return new (memory) DynamicSubscriptExpr(base, index, argLabels, argLabelLocs, hasTrailingClosure, decl, implicit); } ArrayRef<Identifier> ApplyExpr::getArgumentLabels( SmallVectorImpl<Identifier> &scratch) const { // Unary operators and 'self' applications have a single, unlabeled argument. if (isa<PrefixUnaryExpr>(this) || isa<PostfixUnaryExpr>(this) || isa<SelfApplyExpr>(this)) { scratch.clear(); scratch.push_back(Identifier()); return scratch; } // Binary operators have two unlabeled arguments. if (isa<BinaryExpr>(this)) { scratch.clear(); scratch.reserve(2); scratch.push_back(Identifier()); scratch.push_back(Identifier()); return scratch; } // For calls, get the argument labels directly. auto call = cast<CallExpr>(this); return call->getArgumentLabels(); } bool ApplyExpr::hasTrailingClosure() const { if (auto call = dyn_cast<CallExpr>(this)) return call->hasTrailingClosure(); return false; } Optional<unsigned> ApplyExpr::getUnlabeledTrailingClosureIndex() const { if (auto call = dyn_cast<CallExpr>(this)) return call->getUnlabeledTrailingClosureIndex(); return None; } CallExpr::CallExpr(Expr *fn, Expr *arg, bool Implicit, ArrayRef<Identifier> argLabels, ArrayRef<SourceLoc> argLabelLocs, bool hasTrailingClosure, Type ty) : ApplyExpr(ExprKind::Call, fn, arg, Implicit, ty) { Bits.CallExpr.NumArgLabels = argLabels.size(); Bits.CallExpr.HasArgLabelLocs = !argLabelLocs.empty(); Bits.CallExpr.HasTrailingClosure = hasTrailingClosure; initializeCallArguments(argLabels, argLabelLocs); #ifndef NDEBUG Expr *calleeFn = fn->getSemanticsProvidingExpr(); if (auto *calleeDRE = dyn_cast<DeclRefExpr>(calleeFn)) assert(!calleeDRE->getDecl()->isInstanceMember()); #endif } CallExpr *CallExpr::create(ASTContext &ctx, Expr *fn, Expr *arg, ArrayRef<Identifier> argLabels, ArrayRef<SourceLoc> argLabelLocs, bool hasTrailingClosure, bool implicit, Type type, llvm::function_ref<Type(Expr *)> getType) { SmallVector<Identifier, 4> argLabelsScratch; SmallVector<SourceLoc, 4> argLabelLocsScratch; if (argLabels.empty()) { // Inspect the argument to dig out the argument labels, their location, and // whether there is a trailing closure. argLabels = getArgumentLabelsFromArgument(arg, argLabelsScratch, &argLabelLocsScratch, &hasTrailingClosure, getType); argLabelLocs = argLabelLocsScratch; } size_t size = totalSizeToAlloc(argLabels, argLabelLocs); void *memory = ctx.Allocate(size, alignof(CallExpr)); return new (memory) CallExpr(fn, arg, implicit, argLabels, argLabelLocs, hasTrailingClosure, type); } CallExpr *CallExpr::create(ASTContext &ctx, Expr *fn, SourceLoc lParenLoc, ArrayRef<Expr *> args, ArrayRef<Identifier> argLabels, ArrayRef<SourceLoc> argLabelLocs, SourceLoc rParenLoc, ArrayRef<TrailingClosure> trailingClosures, bool implicit, llvm::function_ref<Type(Expr *)> getType) { SmallVector<Identifier, 4> argLabelsScratch; SmallVector<SourceLoc, 4> argLabelLocsScratch; Expr *arg = packSingleArgument(ctx, lParenLoc, args, argLabels, argLabelLocs, rParenLoc, trailingClosures, implicit, argLabelsScratch, argLabelLocsScratch, getType); size_t size = totalSizeToAlloc(argLabels, argLabelLocs); void *memory = ctx.Allocate(size, alignof(CallExpr)); return new (memory) CallExpr(fn, arg, implicit, argLabels, argLabelLocs, trailingClosures.size() == 1, Type()); } Expr *CallExpr::getDirectCallee() const { auto fn = getFn(); while (true) { fn = fn->getSemanticsProvidingExpr(); if (auto force = dyn_cast<ForceValueExpr>(fn)) { fn = force->getSubExpr(); continue; } if (auto bind = dyn_cast<BindOptionalExpr>(fn)) { fn = bind->getSubExpr(); continue; } if (auto ctorCall = dyn_cast<ConstructorRefCallExpr>(fn)) { fn = ctorCall->getFn(); continue; } return fn; } } SourceLoc DotSyntaxCallExpr::getLoc() const { if (isImplicit()) { SourceLoc baseLoc = getBase()->getLoc(); return baseLoc.isValid() ? baseLoc : getFn()->getLoc(); } return getFn()->getLoc(); } SourceLoc DotSyntaxCallExpr::getStartLoc() const { if (isImplicit()) { SourceLoc baseLoc = getBase()->getStartLoc(); return baseLoc.isValid() ? baseLoc : getFn()->getStartLoc(); } return getBase()->getStartLoc(); } SourceLoc DotSyntaxCallExpr::getEndLoc() const { if (isImplicit()) { SourceLoc fnLoc = getFn()->getEndLoc(); return fnLoc.isValid() ? fnLoc : getBase()->getEndLoc(); } return getFn()->getEndLoc(); } void ExplicitCastExpr::setCastType(Type type) { CastTy->setType(MetatypeType::get(type)); } ForcedCheckedCastExpr *ForcedCheckedCastExpr::create(ASTContext &ctx, SourceLoc asLoc, SourceLoc exclaimLoc, TypeRepr *tyRepr) { return new (ctx) ForcedCheckedCastExpr(nullptr, asLoc, exclaimLoc, new (ctx) TypeExpr(tyRepr)); } ForcedCheckedCastExpr * ForcedCheckedCastExpr::createImplicit(ASTContext &ctx, Expr *sub, Type castTy) { auto *const expr = new (ctx) ForcedCheckedCastExpr( sub, SourceLoc(), SourceLoc(), TypeExpr::createImplicit(castTy, ctx)); expr->setType(castTy); expr->setImplicit(); return expr; } ConditionalCheckedCastExpr * ConditionalCheckedCastExpr::create(ASTContext &ctx, SourceLoc asLoc, SourceLoc questionLoc, TypeRepr *tyRepr) { return new (ctx) ConditionalCheckedCastExpr(nullptr, asLoc, questionLoc, new (ctx) TypeExpr(tyRepr)); } ConditionalCheckedCastExpr * ConditionalCheckedCastExpr::createImplicit(ASTContext &ctx, Expr *sub, Type castTy) { auto *const expr = new (ctx) ConditionalCheckedCastExpr( sub, SourceLoc(), SourceLoc(), TypeExpr::createImplicit(castTy, ctx)); expr->setType(OptionalType::get(castTy)); expr->setImplicit(); return expr; } IsExpr *IsExpr::create(ASTContext &ctx, SourceLoc isLoc, TypeRepr *tyRepr) { return new (ctx) IsExpr(nullptr, isLoc, new (ctx) TypeExpr(tyRepr)); } CoerceExpr *CoerceExpr::create(ASTContext &ctx, SourceLoc asLoc, TypeRepr *tyRepr) { return new (ctx) CoerceExpr(nullptr, asLoc, new (ctx) TypeExpr(tyRepr)); } CoerceExpr *CoerceExpr::createImplicit(ASTContext &ctx, Expr *sub, Type castTy) { auto *const expr = new (ctx) CoerceExpr(sub, SourceLoc(), TypeExpr::createImplicit(castTy, ctx)); expr->setType(castTy); expr->setImplicit(); return expr; } CoerceExpr *CoerceExpr::forLiteralInit(ASTContext &ctx, Expr *literal, SourceRange range, TypeRepr *literalTyRepr) { auto *const expr = new (ctx) CoerceExpr(range, literal, new (ctx) TypeExpr(literalTyRepr)); expr->setImplicit(); return expr; } RebindSelfInConstructorExpr::RebindSelfInConstructorExpr(Expr *SubExpr, VarDecl *Self) : Expr(ExprKind::RebindSelfInConstructor, /*Implicit=*/true, TupleType::getEmpty(Self->getASTContext())), SubExpr(SubExpr), Self(Self) {} OtherConstructorDeclRefExpr * RebindSelfInConstructorExpr::getCalledConstructor(bool &isChainToSuper) const { // Dig out the OtherConstructorDeclRefExpr. Note that this is the reverse // of what we do in pre-checking. Expr *candidate = getSubExpr(); while (true) { // Look through identity expressions. if (auto identity = dyn_cast<IdentityExpr>(candidate)) { candidate = identity->getSubExpr(); continue; } // Look through force-value expressions. if (auto force = dyn_cast<ForceValueExpr>(candidate)) { candidate = force->getSubExpr(); continue; } // Look through all try expressions. if (auto tryExpr = dyn_cast<AnyTryExpr>(candidate)) { candidate = tryExpr->getSubExpr(); continue; } // Look through covariant return expressions. if (auto covariantExpr = dyn_cast<CovariantReturnConversionExpr>(candidate)) { candidate = covariantExpr->getSubExpr(); continue; } // Look through inject into optional expressions if (auto injectIntoOptionalExpr = dyn_cast<InjectIntoOptionalExpr>(candidate)) { candidate = injectIntoOptionalExpr->getSubExpr(); continue; } break; } // We hit an application, find the constructor reference. OtherConstructorDeclRefExpr *otherCtorRef; const ApplyExpr *apply; do { apply = cast<ApplyExpr>(candidate); candidate = apply->getFn(); auto candidateUnwrapped = candidate->getSemanticsProvidingExpr(); otherCtorRef = dyn_cast<OtherConstructorDeclRefExpr>(candidateUnwrapped); } while (!otherCtorRef); isChainToSuper = apply->getArg()->isSuperExpr(); return otherCtorRef; } void AbstractClosureExpr::setParameterList(ParameterList *P) { parameterList = P; // Change the DeclContext of any parameters to be this closure. if (P) P->setDeclContextOfParamDecls(this); } Type AbstractClosureExpr::getResultType( llvm::function_ref<Type(Expr *)> getType) const { auto *E = const_cast<AbstractClosureExpr *>(this); if (getType(E)->hasError()) return getType(E); return getType(E)->castTo<FunctionType>()->getResult(); } bool AbstractClosureExpr::isBodyThrowing() const { if (getType()->hasError()) return false; return getType()->castTo<FunctionType>()->getExtInfo().isThrowing(); } bool AbstractClosureExpr::isBodyAsync() const { if (getType()->hasError()) return false; return getType()->castTo<FunctionType>()->getExtInfo().isAsync(); } bool AbstractClosureExpr::hasSingleExpressionBody() const { if (auto closure = dyn_cast<ClosureExpr>(this)) return closure->hasSingleExpressionBody(); return true; } Expr *AbstractClosureExpr::getSingleExpressionBody() const { if (auto closure = dyn_cast<ClosureExpr>(this)) return closure->getSingleExpressionBody(); else if (auto autoclosure = dyn_cast<AutoClosureExpr>(this)) return autoclosure->getSingleExpressionBody(); return nullptr; } #define FORWARD_SOURCE_LOCS_TO(CLASS, NODE) \ SourceRange CLASS::getSourceRange() const { \ return (NODE)->getSourceRange(); \ } \ SourceLoc CLASS::getStartLoc() const { \ return (NODE)->getStartLoc(); \ } \ SourceLoc CLASS::getEndLoc() const { \ return (NODE)->getEndLoc(); \ } \ SourceLoc CLASS::getLoc() const { \ return (NODE)->getStartLoc(); \ } FORWARD_SOURCE_LOCS_TO(ClosureExpr, Body.getPointer()) Expr *ClosureExpr::getSingleExpressionBody() const { assert(hasSingleExpressionBody() && "Not a single-expression body"); auto body = getBody()->getFirstElement(); if (auto stmt = body.dyn_cast<Stmt *>()) { if (auto braceStmt = dyn_cast<BraceStmt>(stmt)) return braceStmt->getFirstElement().get<Expr *>(); return cast<ReturnStmt>(stmt)->getResult(); } return body.get<Expr *>(); } bool ClosureExpr::hasEmptyBody() const { return getBody()->empty(); } void ClosureExpr::setExplicitResultType(Type ty) { assert(ty && !ty->hasTypeVariable() && !ty->hasHole()); ExplicitResultTypeAndBodyState.getPointer() ->setType(MetatypeType::get(ty)); } FORWARD_SOURCE_LOCS_TO(AutoClosureExpr, Body) void AutoClosureExpr::setBody(Expr *E) { auto &Context = getASTContext(); auto *RS = new (Context) ReturnStmt(SourceLoc(), E); Body = BraceStmt::create(Context, E->getStartLoc(), { RS }, E->getEndLoc()); } Expr *AutoClosureExpr::getSingleExpressionBody() const { return cast<ReturnStmt>(Body->getFirstElement().get<Stmt *>())->getResult(); } Expr *AutoClosureExpr::getUnwrappedCurryThunkExpr() const { auto maybeUnwrapOpenExistential = [](Expr *expr) { if (auto *openExistential = dyn_cast<OpenExistentialExpr>(expr)) { expr = openExistential->getSubExpr()->getSemanticsProvidingExpr(); if (auto *ICE = dyn_cast<ImplicitConversionExpr>(expr)) expr = ICE->getSyntacticSubExpr(); } return expr; }; auto maybeUnwrapOptionalEval = [](Expr *expr) { if (auto optEval = dyn_cast<OptionalEvaluationExpr>(expr)) expr = optEval->getSubExpr(); if (auto inject = dyn_cast<InjectIntoOptionalExpr>(expr)) expr = inject->getSubExpr(); if (auto erasure = dyn_cast<ErasureExpr>(expr)) expr = erasure->getSubExpr(); if (auto bind = dyn_cast<BindOptionalExpr>(expr)) expr = bind->getSubExpr(); return expr; }; switch (getThunkKind()) { case AutoClosureExpr::Kind::None: break; case AutoClosureExpr::Kind::SingleCurryThunk: { auto *body = getSingleExpressionBody(); body = body->getSemanticsProvidingExpr(); body = maybeUnwrapOpenExistential(body); body = maybeUnwrapOptionalEval(body); if (auto *outerCall = dyn_cast<ApplyExpr>(body)) { return outerCall->getFn(); } assert(false && "Malformed curry thunk?"); break; } case AutoClosureExpr::Kind::DoubleCurryThunk: { auto *body = getSingleExpressionBody(); if (auto *innerClosure = dyn_cast<AutoClosureExpr>(body)) { assert(innerClosure->getThunkKind() == AutoClosureExpr::Kind::SingleCurryThunk); auto *innerBody = innerClosure->getSingleExpressionBody(); innerBody = innerBody->getSemanticsProvidingExpr(); innerBody = maybeUnwrapOpenExistential(innerBody); innerBody = maybeUnwrapOptionalEval(innerBody); if (auto *outerCall = dyn_cast<ApplyExpr>(innerBody)) { if (auto *innerCall = dyn_cast<ApplyExpr>(outerCall->getFn())) { return innerCall->getFn(); } } } assert(false && "Malformed curry thunk?"); break; } } return nullptr; } FORWARD_SOURCE_LOCS_TO(UnresolvedPatternExpr, subPattern) TypeExpr::TypeExpr(TypeRepr *Repr) : Expr(ExprKind::Type, /*implicit*/false), Repr(Repr) {} TypeExpr *TypeExpr::createImplicit(Type Ty, ASTContext &C) { assert(Ty); auto *result = new (C) TypeExpr(nullptr); result->setType(MetatypeType::get(Ty, Ty->getASTContext())); result->setImplicit(); return result; } // The type of a TypeExpr is always a metatype type. Return the instance // type or null if not set yet. Type TypeExpr::getInstanceType() const { auto ty = getType(); if (!ty) return Type(); if (auto metaType = ty->getAs<MetatypeType>()) return metaType->getInstanceType(); return ErrorType::get(ty->getASTContext()); } TypeExpr *TypeExpr::createForDecl(DeclNameLoc Loc, TypeDecl *Decl, DeclContext *DC) { ASTContext &C = Decl->getASTContext(); assert(Loc.isValid()); auto *Repr = new (C) SimpleIdentTypeRepr(Loc, Decl->createNameRef()); Repr->setValue(Decl, DC); return new (C) TypeExpr(Repr); } TypeExpr *TypeExpr::createImplicitForDecl(DeclNameLoc Loc, TypeDecl *Decl, DeclContext *DC, Type ty) { ASTContext &C = Decl->getASTContext(); auto *Repr = new (C) SimpleIdentTypeRepr(Loc, Decl->createNameRef()); Repr->setValue(Decl, DC); auto result = new (C) TypeExpr(Repr); assert(ty && !ty->hasTypeParameter()); result->setType(ty); result->setImplicit(); return result; } TypeExpr *TypeExpr::createForMemberDecl(DeclNameLoc ParentNameLoc, TypeDecl *Parent, DeclNameLoc NameLoc, TypeDecl *Decl) { ASTContext &C = Decl->getASTContext(); assert(ParentNameLoc.isValid()); assert(NameLoc.isValid()); // Create a new list of components. SmallVector<ComponentIdentTypeRepr *, 2> Components; // The first component is the parent type. auto *ParentComp = new (C) SimpleIdentTypeRepr(ParentNameLoc, Parent->createNameRef()); ParentComp->setValue(Parent, nullptr); Components.push_back(ParentComp); // The second component is the member we just found. auto *NewComp = new (C) SimpleIdentTypeRepr(NameLoc, Decl->createNameRef()); NewComp->setValue(Decl, nullptr); Components.push_back(NewComp); auto *NewTypeRepr = IdentTypeRepr::create(C, Components); return new (C) TypeExpr(NewTypeRepr); } TypeExpr *TypeExpr::createForMemberDecl(IdentTypeRepr *ParentTR, DeclNameLoc NameLoc, TypeDecl *Decl) { ASTContext &C = Decl->getASTContext(); // Create a new list of components. SmallVector<ComponentIdentTypeRepr *, 2> Components; for (auto *Component : ParentTR->getComponentRange()) Components.push_back(Component); assert(!Components.empty()); // Add a new component for the member we just found. auto *NewComp = new (C) SimpleIdentTypeRepr(NameLoc, Decl->createNameRef()); NewComp->setValue(Decl, nullptr); Components.push_back(NewComp); auto *NewTypeRepr = IdentTypeRepr::create(C, Components); return new (C) TypeExpr(NewTypeRepr); } TypeExpr *TypeExpr::createForSpecializedDecl(IdentTypeRepr *ParentTR, ArrayRef<TypeRepr*> Args, SourceRange AngleLocs, ASTContext &C) { // Create a new list of components. SmallVector<ComponentIdentTypeRepr *, 2> components; for (auto *component : ParentTR->getComponentRange()) { components.push_back(component); } auto *last = components.back(); components.pop_back(); if (isa<SimpleIdentTypeRepr>(last) && last->getBoundDecl()) { if (isa<TypeAliasDecl>(last->getBoundDecl())) { // If any of our parent types are unbound, bail out and let // the constraint solver can infer generic parameters for them. // // This is because a type like GenericClass.GenericAlias<Int> // cannot be represented directly. // // This also means that [GenericClass.GenericAlias<Int>]() // won't parse correctly, whereas if we fully specialize // GenericClass, it does. // // FIXME: Once we can model generic typealiases properly, rip // this out. for (auto *component : components) { auto *componentDecl = dyn_cast_or_null<GenericTypeDecl>( component->getBoundDecl()); if (isa<SimpleIdentTypeRepr>(component) && componentDecl && componentDecl->isGeneric()) return nullptr; } } auto *genericComp = GenericIdentTypeRepr::create(C, last->getNameLoc(), last->getNameRef(), Args, AngleLocs); genericComp->setValue(last->getBoundDecl(), last->getDeclContext()); components.push_back(genericComp); auto *genericRepr = IdentTypeRepr::create(C, components); return new (C) TypeExpr(genericRepr); } return nullptr; } // Create an implicit TypeExpr, with location information even though it // shouldn't have one. This is presently used to work around other location // processing bugs. If you have an implicit location, use createImplicit. TypeExpr *TypeExpr::createImplicitHack(SourceLoc Loc, Type Ty, ASTContext &C) { // FIXME: This is horrible. assert(Ty); if (Loc.isInvalid()) return createImplicit(Ty, C); auto *Repr = new (C) FixedTypeRepr(Ty, Loc); auto *Res = new (C) TypeExpr(Repr); Res->setType(MetatypeType::get(Ty, C)); Res->setImplicit(); return Res; } SourceRange TypeExpr::getSourceRange() const { if (!getTypeRepr()) return SourceRange(); return getTypeRepr()->getSourceRange(); } bool Expr::isSelfExprOf(const AbstractFunctionDecl *AFD, bool sameBase) const { auto *E = getSemanticsProvidingExpr(); if (auto IOE = dyn_cast<InOutExpr>(E)) E = IOE->getSubExpr(); while (auto ICE = dyn_cast<ImplicitConversionExpr>(E)) { if (sameBase && isa<DerivedToBaseExpr>(ICE)) return false; E = ICE->getSubExpr(); } if (auto DRE = dyn_cast<DeclRefExpr>(E)) return DRE->getDecl() == AFD->getImplicitSelfDecl(); return false; } OpenedArchetypeType *OpenExistentialExpr::getOpenedArchetype() const { auto type = getOpaqueValue()->getType()->getRValueType(); while (auto metaTy = type->getAs<MetatypeType>()) type = metaTy->getInstanceType(); return type->castTo<OpenedArchetypeType>(); } KeyPathExpr::KeyPathExpr(ASTContext &C, SourceLoc keywordLoc, SourceLoc lParenLoc, ArrayRef<Component> components, SourceLoc rParenLoc, bool isImplicit) : Expr(ExprKind::KeyPath, isImplicit), StartLoc(keywordLoc), LParenLoc(lParenLoc), EndLoc(rParenLoc), Components(C.AllocateUninitialized<Component>(components.size())) { // Copy components into the AST context. std::uninitialized_copy(components.begin(), components.end(), Components.begin()); Bits.KeyPathExpr.IsObjC = true; } void KeyPathExpr::resolveComponents(ASTContext &C, ArrayRef<KeyPathExpr::Component> resolvedComponents) { // Reallocate the components array if it needs to be. if (Components.size() < resolvedComponents.size()) { Components = C.Allocate<Component>(resolvedComponents.size()); for (unsigned i : indices(Components)) { ::new ((void*)&Components[i]) Component{}; } } for (unsigned i : indices(resolvedComponents)) { Components[i] = resolvedComponents[i]; } Components = Components.slice(0, resolvedComponents.size()); } KeyPathExpr::Component KeyPathExpr::Component::forSubscript(ASTContext &ctx, ConcreteDeclRef subscript, SourceLoc lSquareLoc, ArrayRef<Expr *> indexArgs, ArrayRef<Identifier> indexArgLabels, ArrayRef<SourceLoc> indexArgLabelLocs, SourceLoc rSquareLoc, ArrayRef<TrailingClosure> trailingClosures, Type elementType, ArrayRef<ProtocolConformanceRef> indexHashables) { SmallVector<Identifier, 4> indexArgLabelsScratch; SmallVector<SourceLoc, 4> indexArgLabelLocsScratch; Expr *index = packSingleArgument(ctx, lSquareLoc, indexArgs, indexArgLabels, indexArgLabelLocs, rSquareLoc, trailingClosures, /*implicit*/ false, indexArgLabelsScratch, indexArgLabelLocsScratch); return forSubscriptWithPrebuiltIndexExpr(subscript, index, indexArgLabels, elementType, lSquareLoc, indexHashables); } KeyPathExpr::Component KeyPathExpr::Component::forUnresolvedSubscript(ASTContext &ctx, SourceLoc lSquareLoc, ArrayRef<Expr *> indexArgs, ArrayRef<Identifier> indexArgLabels, ArrayRef<SourceLoc> indexArgLabelLocs, SourceLoc rSquareLoc, ArrayRef<TrailingClosure> trailingClosures) { SmallVector<Identifier, 4> indexArgLabelsScratch; SmallVector<SourceLoc, 4> indexArgLabelLocsScratch; Expr *index = packSingleArgument( ctx, lSquareLoc, indexArgs, indexArgLabels, indexArgLabelLocs, rSquareLoc, trailingClosures, /*implicit*/ false, indexArgLabelsScratch, indexArgLabelLocsScratch); return forUnresolvedSubscriptWithPrebuiltIndexExpr(ctx, index, indexArgLabels, lSquareLoc); } KeyPathExpr::Component::Component(ASTContext *ctxForCopyingLabels, DeclNameOrRef decl, Expr *indexExpr, ArrayRef<Identifier> subscriptLabels, ArrayRef<ProtocolConformanceRef> indexHashables, Kind kind, Type type, SourceLoc loc) : Decl(decl), SubscriptIndexExpr(indexExpr), KindValue(kind), ComponentType(type), Loc(loc) { assert(kind != Kind::TupleElement || subscriptLabels.empty()); assert(subscriptLabels.size() == indexHashables.size() || indexHashables.empty()); SubscriptLabelsData = subscriptLabels.data(); SubscriptHashableConformancesData = indexHashables.empty() ? nullptr : indexHashables.data(); SubscriptSize = subscriptLabels.size(); } KeyPathExpr::Component KeyPathExpr::Component::forSubscriptWithPrebuiltIndexExpr( ConcreteDeclRef subscript, Expr *index, ArrayRef<Identifier> labels, Type elementType, SourceLoc loc, ArrayRef<ProtocolConformanceRef> indexHashables) { return Component(&elementType->getASTContext(), subscript, index, labels, indexHashables, Kind::Subscript, elementType, loc); } void KeyPathExpr::Component::setSubscriptIndexHashableConformances( ArrayRef<ProtocolConformanceRef> hashables) { switch (getKind()) { case Kind::Subscript: assert(hashables.size() == SubscriptSize); SubscriptHashableConformancesData = getComponentType()->getASTContext() .AllocateCopy(hashables) .data(); return; case Kind::UnresolvedSubscript: case Kind::Invalid: case Kind::OptionalChain: case Kind::OptionalWrap: case Kind::OptionalForce: case Kind::UnresolvedProperty: case Kind::Property: case Kind::Identity: case Kind::TupleElement: case Kind::DictionaryKey: llvm_unreachable("no hashable conformances for this kind"); } } void InterpolatedStringLiteralExpr::forEachSegment(ASTContext &Ctx, llvm::function_ref<void(bool, CallExpr *)> callback) { auto appendingExpr = getAppendingExpr(); for (auto stmt : appendingExpr->getBody()->getElements()) { if (auto expr = stmt.dyn_cast<Expr*>()) { if (auto call = dyn_cast<CallExpr>(expr)) { DeclName name; if (auto fn = call->getCalledValue()) { name = fn->getName(); } else if (auto unresolvedDot = dyn_cast<UnresolvedDotExpr>(call->getFn())) { name = unresolvedDot->getName().getFullName(); } bool isInterpolation = (name.getBaseName() == Ctx.Id_appendInterpolation); callback(isInterpolation, call); } } } } TapExpr::TapExpr(Expr * SubExpr, BraceStmt *Body) : Expr(ExprKind::Tap, /*Implicit=*/true), SubExpr(SubExpr), Body(Body) { if (Body) { assert(!Body->empty() && Body->getFirstElement().isDecl(DeclKind::Var) && "First element of Body should be a variable to init with the subExpr"); } } VarDecl * TapExpr::getVar() const { return dyn_cast<VarDecl>(Body->getFirstElement().dyn_cast<Decl *>()); } SourceLoc TapExpr::getEndLoc() const { // Include the body in the range, assuming the body follows the SubExpr. // Also, be (perhaps overly) defensive about null pointers & invalid // locations. if (auto *const b = getBody()) { const auto be = b->getEndLoc(); if (be.isValid()) return be; } if (auto *const se = getSubExpr()) return se->getEndLoc(); return SourceLoc(); } void swift::simple_display(llvm::raw_ostream &out, const ClosureExpr *CE) { if (!CE) { out << "(null)"; return; } out << "closure"; } void swift::simple_display(llvm::raw_ostream &out, const DefaultArgumentExpr *expr) { if (!expr) { out << "(null)"; return; } out << "default arg for param "; out << "#" << expr->getParamIndex() + 1 << " "; out << "of "; simple_display(out, expr->getDefaultArgsOwner().getDecl()); } void swift::simple_display(llvm::raw_ostream &out, const Expr *expr) { out << "expression"; } SourceLoc swift::extractNearestSourceLoc(const DefaultArgumentExpr *expr) { return expr->getLoc(); } // See swift/Basic/Statistic.h for declaration: this enables tracing Exprs, is // defined here to avoid too much layering violation / circular linkage // dependency. struct ExprTraceFormatter : public UnifiedStatsReporter::TraceFormatter { void traceName(const void *Entity, raw_ostream &OS) const override { if (!Entity) return; const Expr *E = static_cast<const Expr *>(Entity); OS << Expr::getKindName(E->getKind()); } void traceLoc(const void *Entity, SourceManager *SM, clang::SourceManager *CSM, raw_ostream &OS) const override { if (!Entity) return; const Expr *E = static_cast<const Expr *>(Entity); E->getSourceRange().print(OS, *SM, false); } }; static ExprTraceFormatter TF; template<> const UnifiedStatsReporter::TraceFormatter* FrontendStatsTracer::getTraceFormatter<const Expr *>() { return &TF; }
/** * @addtogroup DFNs * @{ */ #include "PrimitiveFinderInterface.hpp" namespace CDFF { namespace DFN { PrimitiveFinderInterface::PrimitiveFinderInterface() { asn1SccFrame_Initialize(& inImage); asn1SccT_String_Initialize(& inPrimitive); asn1SccVectorXdSequence_Initialize(& outPrimitives); } PrimitiveFinderInterface::~PrimitiveFinderInterface() { } void PrimitiveFinderInterface::imageInput(const asn1SccFrame& data) { inImage = data; } void PrimitiveFinderInterface::primitiveInput(const asn1SccT_String& data) { inPrimitive = data; } const asn1SccVectorXdSequence& PrimitiveFinderInterface::primitivesOutput() const { return outPrimitives; } } } /** @} */
/************************************************************************************ * * D++, A Lightweight C++ library for Discord * * Copyright 2021 Craig Edwards and D++ contributors * (https://github.com/brainboxdotcc/DPP/graphs/contributors) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ************************************************************************************/ #include <dpp/discordevents.h> #include <dpp/cluster.h> #include <dpp/integration.h> #include <dpp/stringops.h> #include <dpp/nlohmann/json.hpp> using json = nlohmann::json; namespace dpp { namespace events { using namespace dpp; /** * @brief Handle event * * @param client Websocket client (current shard) * @param j JSON data for the event * @param raw Raw JSON string */ void integration_create::handle(discord_client* client, json &j, const std::string &raw) { if (!client->creator->on_integration_create.empty()) { json& d = j["d"]; dpp::integration_create_t ic(client, raw); ic.created_integration = dpp::integration().fill_from_json(&d); client->creator->on_integration_create.call(ic); } } }};
/* * Copyright 2018 The Project Oak Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "oak_manager.h" #include "absl/memory/memory.h" #include "asylo/identity/descriptions.h" #include "asylo/identity/enclave_assertion_authority_config.pb.h" #include "asylo/util/logging.h" #include "asylo/util/statusor.h" namespace oak { OakManager::OakManager(absl::string_view enclave_path) : Service(), enclave_path_(enclave_path), node_id_(0) { InitializeEnclaveManager(); } grpc::Status OakManager::CreateNode(grpc::ServerContext* context, const oak::CreateNodeRequest* request, oak::CreateNodeResponse* response) { std::string node_id = NewNodeId(); grpc::Status status = CreateEnclave(node_id, request->module()); if (!status.ok()) { return status; } asylo::StatusOr<oak::InitializeOutput> result = GetEnclaveOutput(node_id); if (!result.ok()) { return result.status().ToOtherStatus<grpc::Status>(); } oak::InitializeOutput out = result.ValueOrDie(); response->set_port(out.port()); response->set_node_id(node_id); return grpc::Status::OK; } void OakManager::InitializeEnclaveManager() { LOG(INFO) << "Initializing enclave manager"; asylo::EnclaveManager::Configure(asylo::EnclaveManagerOptions()); auto manager_result = asylo::EnclaveManager::Instance(); if (!manager_result.ok()) { LOG(QFATAL) << "Could not initialize enclave manager: " << manager_result.status(); } enclave_manager_ = manager_result.ValueOrDie(); LOG(INFO) << "Enclave manager initialized"; LOG(INFO) << "Loading enclave code from " << enclave_path_; enclave_loader_ = absl::make_unique<asylo::SimLoader>(enclave_path_, /*debug=*/true); } grpc::Status OakManager::CreateEnclave(const std::string& node_id, const std::string& module) { LOG(INFO) << "Creating enclave"; asylo::EnclaveConfig config; // Explicitly initialize the null assertion authority in the enclave. asylo::EnclaveAssertionAuthorityConfig* authority_config = config.add_enclave_assertion_authority_configs(); asylo::SetNullAssertionDescription(authority_config->mutable_description()); oak::InitializeInput* initialize_input = config.MutableExtension(oak::initialize_input); initialize_input->set_node_id(node_id); initialize_input->set_module(module); asylo::Status status = enclave_manager_->LoadEnclave(node_id, *enclave_loader_, config); if (!status.ok()) { LOG(ERROR) << "Could not load enclave " << enclave_path_ << ": " << status; return status.ToOtherStatus<grpc::Status>(); } LOG(INFO) << "Enclave created"; return grpc::Status::OK; } asylo::StatusOr<oak::InitializeOutput> OakManager::GetEnclaveOutput(const std::string& node_id) { LOG(INFO) << "Initializing enclave"; asylo::EnclaveClient* client = enclave_manager_->GetClient(node_id); asylo::EnclaveInput input; asylo::EnclaveOutput output; asylo::Status status = client->EnterAndRun(input, &output); if (!status.ok()) { LOG(ERROR) << "EnterAndRun failed: " << status; return status; } LOG(INFO) << "Enclave initialized"; return output.GetExtension(oak::initialize_output); } std::string OakManager::NewNodeId() { // TODO: Generate UUID. std::stringstream id_str; id_str << node_id_; node_id_ += 1; return id_str.str(); } void OakManager::DestroyEnclave(const std::string& node_id) { LOG(INFO) << "Destroying enclave"; asylo::EnclaveClient* client = enclave_manager_->GetClient(node_id); asylo::EnclaveFinal final_input; asylo::Status status = enclave_manager_->DestroyEnclave(client, final_input); if (!status.ok()) { LOG(QFATAL) << "Destroy " << enclave_path_ << " failed: " << status; } LOG(INFO) << "Enclave destroyed"; } } // namespace oak
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/login/login_handler.h" #include <string> #include <vector> #include "base/bind.h" #include "base/command_line.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" #include "base/synchronization/lock.h" #include "chrome/browser/chrome_notification_types.h" #include "chrome/browser/password_manager/chrome_password_manager_client.h" #include "chrome/browser/prerender/prerender_contents.h" #include "chrome/browser/tab_contents/tab_util.h" #include "chrome/browser/ui/login/login_interstitial_delegate.h" #include "chrome/grit/generated_resources.h" #include "components/password_manager/core/browser/browser_save_password_progress_logger.h" #include "components/password_manager/core/browser/log_manager.h" #include "components/password_manager/core/browser/password_manager.h" #include "components/strings/grit/components_strings.h" #include "components/url_formatter/elide_url.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/notification_registrar.h" #include "content/public/browser/notification_service.h" #include "content/public/browser/render_frame_host.h" #include "content/public/browser/resource_dispatcher_host.h" #include "content/public/browser/resource_request_info.h" #include "content/public/browser/web_contents.h" #include "content/public/common/origin_util.h" #include "net/base/auth.h" #include "net/base/host_port_pair.h" #include "net/base/load_flags.h" #include "net/http/http_auth_scheme.h" #include "net/http/http_transaction_factory.h" #include "net/url_request/url_request.h" #include "net/url_request/url_request_context.h" #include "ui/base/l10n/l10n_util.h" #include "ui/gfx/text_elider.h" #if defined(ENABLE_EXTENSIONS) #include "components/guest_view/browser/guest_view_base.h" #include "extensions/browser/view_type_utils.h" #endif using autofill::PasswordForm; using content::BrowserThread; using content::NavigationController; using content::RenderViewHost; using content::RenderViewHostDelegate; using content::ResourceDispatcherHost; using content::ResourceRequestInfo; using content::WebContents; class LoginHandlerImpl; namespace { // Helper to remove the ref from an net::URLRequest to the LoginHandler. // Should only be called from the IO thread, since it accesses an // net::URLRequest. void ResetLoginHandlerForRequest(net::URLRequest* request) { ResourceDispatcherHost::Get()->ClearLoginDelegateForRequest(request); } } // namespace // ---------------------------------------------------------------------------- // LoginHandler LoginHandler::LoginModelData::LoginModelData( password_manager::LoginModel* login_model, const autofill::PasswordForm& observed_form) : model(login_model), form(observed_form) { DCHECK(model); } LoginHandler::LoginHandler(net::AuthChallengeInfo* auth_info, net::URLRequest* request) : handled_auth_(false), auth_info_(auth_info), request_(request), http_network_session_( request_->context()->http_transaction_factory()->GetSession()), password_manager_(NULL), login_model_(NULL) { // This constructor is called on the I/O thread, so we cannot load the nib // here. BuildViewImpl() will be invoked on the UI thread later, so wait with // loading the nib until then. DCHECK(request_) << "LoginHandler constructed with NULL request"; DCHECK(auth_info_.get()) << "LoginHandler constructed with NULL auth info"; AddRef(); // matched by LoginHandler::ReleaseSoon(). BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::Bind(&LoginHandler::AddObservers, this)); const content::ResourceRequestInfo* info = ResourceRequestInfo::ForRequest(request); DCHECK(info); web_contents_getter_ = info->GetWebContentsGetterForRequest(); } void LoginHandler::OnRequestCancelled() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)) << "Why is OnRequestCancelled called from the UI thread?"; // Reference is no longer valid. request_ = NULL; // Give up on auth if the request was cancelled. Since the dialog was canceled // by the ResourceLoader and not the user, we should cancel the navigation as // well. This can happen when a new navigation interrupts the current one. DoCancelAuth(true); } void LoginHandler::BuildViewWithPasswordManager( const base::string16& authority, const base::string16& explanation, password_manager::PasswordManager* password_manager, const autofill::PasswordForm& observed_form) { password_manager_ = password_manager; password_form_ = observed_form; LoginHandler::LoginModelData model_data(password_manager, observed_form); BuildViewImpl(authority, explanation, &model_data); } void LoginHandler::BuildViewWithoutPasswordManager( const base::string16& authority, const base::string16& explanation) { BuildViewImpl(authority, explanation, nullptr); } WebContents* LoginHandler::GetWebContentsForLogin() const { DCHECK_CURRENTLY_ON(BrowserThread::UI); return web_contents_getter_.Run(); } password_manager::PasswordManager* LoginHandler::GetPasswordManagerForLogin() { password_manager::PasswordManagerClient* client = ChromePasswordManagerClient::FromWebContents(GetWebContentsForLogin()); return client ? client->GetPasswordManager() : nullptr; } void LoginHandler::SetAuth(const base::string16& username, const base::string16& password) { DCHECK_CURRENTLY_ON(BrowserThread::UI); std::unique_ptr<password_manager::BrowserSavePasswordProgressLogger> logger; if (password_manager_ && password_manager_->client()->GetLogManager()->IsLoggingActive()) { logger.reset(new password_manager::BrowserSavePasswordProgressLogger( password_manager_->client()->GetLogManager())); logger->LogMessage( autofill::SavePasswordProgressLogger::STRING_SET_AUTH_METHOD); } bool already_handled = TestAndSetAuthHandled(); if (logger) { logger->LogBoolean( autofill::SavePasswordProgressLogger::STRING_AUTHENTICATION_HANDLED, already_handled); } if (already_handled) return; // Tell the password manager the credentials were submitted / accepted. if (password_manager_) { password_form_.username_value = username; password_form_.password_value = password; password_manager_->ProvisionallySavePassword(password_form_); if (logger) { logger->LogPasswordForm( autofill::SavePasswordProgressLogger::STRING_LOGINHANDLER_FORM, password_form_); } } // Calling NotifyAuthSupplied() directly instead of posting a task // allows other LoginHandler instances to queue their // CloseContentsDeferred() before ours. Closing dialogs in the // opposite order as they were created avoids races where remaining // dialogs in the same tab may be briefly displayed to the user // before they are removed. NotifyAuthSupplied(username, password); BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::Bind(&LoginHandler::CloseContentsDeferred, this)); BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, base::Bind(&LoginHandler::SetAuthDeferred, this, username, password)); } void LoginHandler::CancelAuth() { // Cancel the auth without canceling the navigation, so that the auth error // page commits. DoCancelAuth(false); } void LoginHandler::Observe(int type, const content::NotificationSource& source, const content::NotificationDetails& details) { DCHECK_CURRENTLY_ON(BrowserThread::UI); DCHECK(type == chrome::NOTIFICATION_AUTH_SUPPLIED || type == chrome::NOTIFICATION_AUTH_CANCELLED); WebContents* requesting_contents = GetWebContentsForLogin(); if (!requesting_contents) return; // Break out early if we aren't interested in the notification. if (WasAuthHandled()) return; LoginNotificationDetails* login_details = content::Details<LoginNotificationDetails>(details).ptr(); // WasAuthHandled() should always test positive before we publish // AUTH_SUPPLIED or AUTH_CANCELLED notifications. DCHECK(login_details->handler() != this); // Only handle notification for the identical auth info. if (!login_details->handler()->auth_info()->Equals(*auth_info())) return; // Ignore login notification events from other profiles. if (login_details->handler()->http_network_session_ != http_network_session_) return; // Set or cancel the auth in this handler. if (type == chrome::NOTIFICATION_AUTH_SUPPLIED) { AuthSuppliedLoginNotificationDetails* supplied_details = content::Details<AuthSuppliedLoginNotificationDetails>(details).ptr(); SetAuth(supplied_details->username(), supplied_details->password()); } else { DCHECK(type == chrome::NOTIFICATION_AUTH_CANCELLED); CancelAuth(); } } // Returns whether authentication had been handled (SetAuth or CancelAuth). bool LoginHandler::WasAuthHandled() const { base::AutoLock lock(handled_auth_lock_); bool was_handled = handled_auth_; return was_handled; } LoginHandler::~LoginHandler() { ResetModel(); } void LoginHandler::SetModel(LoginModelData model_data) { ResetModel(); login_model_ = model_data.model; login_model_->AddObserverAndDeliverCredentials(this, model_data.form); } void LoginHandler::ResetModel() { if (login_model_) login_model_->RemoveObserver(this); login_model_ = nullptr; } void LoginHandler::NotifyAuthNeeded() { DCHECK_CURRENTLY_ON(BrowserThread::UI); if (WasAuthHandled()) return; content::NotificationService* service = content::NotificationService::current(); NavigationController* controller = NULL; WebContents* requesting_contents = GetWebContentsForLogin(); if (requesting_contents) controller = &requesting_contents->GetController(); LoginNotificationDetails details(this); service->Notify(chrome::NOTIFICATION_AUTH_NEEDED, content::Source<NavigationController>(controller), content::Details<LoginNotificationDetails>(&details)); } void LoginHandler::ReleaseSoon() { if (!TestAndSetAuthHandled()) { BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, base::Bind(&LoginHandler::CancelAuthDeferred, this)); BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::Bind(&LoginHandler::NotifyAuthCancelled, this, false)); } BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::Bind(&LoginHandler::RemoveObservers, this)); // Delete this object once all InvokeLaters have been called. BrowserThread::ReleaseSoon(BrowserThread::IO, FROM_HERE, this); } void LoginHandler::AddObservers() { DCHECK_CURRENTLY_ON(BrowserThread::UI); // This is probably OK; we need to listen to everything and we break out of // the Observe() if we aren't handling the same auth_info(). registrar_.reset(new content::NotificationRegistrar); registrar_->Add(this, chrome::NOTIFICATION_AUTH_SUPPLIED, content::NotificationService::AllBrowserContextsAndSources()); registrar_->Add(this, chrome::NOTIFICATION_AUTH_CANCELLED, content::NotificationService::AllBrowserContextsAndSources()); } void LoginHandler::RemoveObservers() { DCHECK_CURRENTLY_ON(BrowserThread::UI); registrar_.reset(); } void LoginHandler::NotifyAuthSupplied(const base::string16& username, const base::string16& password) { DCHECK_CURRENTLY_ON(BrowserThread::UI); DCHECK(WasAuthHandled()); WebContents* requesting_contents = GetWebContentsForLogin(); if (!requesting_contents) return; content::NotificationService* service = content::NotificationService::current(); NavigationController* controller = &requesting_contents->GetController(); AuthSuppliedLoginNotificationDetails details(this, username, password); service->Notify( chrome::NOTIFICATION_AUTH_SUPPLIED, content::Source<NavigationController>(controller), content::Details<AuthSuppliedLoginNotificationDetails>(&details)); } void LoginHandler::NotifyAuthCancelled(bool dismiss_navigation) { DCHECK_CURRENTLY_ON(BrowserThread::UI); DCHECK(WasAuthHandled()); content::NotificationService* service = content::NotificationService::current(); NavigationController* controller = NULL; WebContents* requesting_contents = GetWebContentsForLogin(); if (requesting_contents) controller = &requesting_contents->GetController(); if (dismiss_navigation && interstitial_delegate_) interstitial_delegate_->DontProceed(); LoginNotificationDetails details(this); service->Notify(chrome::NOTIFICATION_AUTH_CANCELLED, content::Source<NavigationController>(controller), content::Details<LoginNotificationDetails>(&details)); } // Marks authentication as handled and returns the previous handled state. bool LoginHandler::TestAndSetAuthHandled() { base::AutoLock lock(handled_auth_lock_); bool was_handled = handled_auth_; handled_auth_ = true; return was_handled; } // Calls SetAuth from the IO loop. void LoginHandler::SetAuthDeferred(const base::string16& username, const base::string16& password) { DCHECK_CURRENTLY_ON(BrowserThread::IO); if (request_) { request_->SetAuth(net::AuthCredentials(username, password)); ResetLoginHandlerForRequest(request_); } } void LoginHandler::DoCancelAuth(bool dismiss_navigation) { if (TestAndSetAuthHandled()) return; // Similar to how we deal with notifications above in SetAuth(). if (BrowserThread::CurrentlyOn(BrowserThread::UI)) { NotifyAuthCancelled(dismiss_navigation); } else { BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, base::Bind(&LoginHandler::NotifyAuthCancelled, this, dismiss_navigation)); } BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::Bind(&LoginHandler::CloseContentsDeferred, this)); BrowserThread::PostTask(BrowserThread::IO, FROM_HERE, base::Bind(&LoginHandler::CancelAuthDeferred, this)); } // Calls CancelAuth from the IO loop. void LoginHandler::CancelAuthDeferred() { DCHECK_CURRENTLY_ON(BrowserThread::IO); if (request_) { request_->CancelAuth(); // Verify that CancelAuth doesn't destroy the request via our delegate. DCHECK(request_ != NULL); ResetLoginHandlerForRequest(request_); } } // Closes the view_contents from the UI loop. void LoginHandler::CloseContentsDeferred() { DCHECK_CURRENTLY_ON(BrowserThread::UI); CloseDialog(); if (interstitial_delegate_) interstitial_delegate_->Proceed(); } // static std::string LoginHandler::GetSignonRealm( const GURL& url, const net::AuthChallengeInfo& auth_info) { std::string signon_realm; if (auth_info.is_proxy) { // Historically we've been storing the signon realm for proxies using // net::HostPortPair::ToString(). net::HostPortPair host_port_pair = net::HostPortPair::FromURL(GURL(auth_info.challenger.Serialize())); signon_realm = host_port_pair.ToString(); signon_realm.append("/"); } else { // Take scheme, host, and port from the url. signon_realm = url.GetOrigin().spec(); // This ends with a "/". } signon_realm.append(auth_info.realm); return signon_realm; } // static PasswordForm LoginHandler::MakeInputForPasswordManager( const GURL& request_url, const net::AuthChallengeInfo& auth_info) { PasswordForm dialog_form; if (base::LowerCaseEqualsASCII(auth_info.scheme, net::kBasicAuthScheme)) { dialog_form.scheme = PasswordForm::SCHEME_BASIC; } else if (base::LowerCaseEqualsASCII(auth_info.scheme, net::kDigestAuthScheme)) { dialog_form.scheme = PasswordForm::SCHEME_DIGEST; } else { dialog_form.scheme = PasswordForm::SCHEME_OTHER; } if (auth_info.is_proxy) { dialog_form.origin = GURL(auth_info.challenger.Serialize()); } else if (!auth_info.challenger.IsSameOriginWith(url::Origin(request_url))) { dialog_form.origin = GURL(); NOTREACHED(); // crbug.com/32718 } else { dialog_form.origin = GURL(auth_info.challenger.Serialize()); } dialog_form.signon_realm = GetSignonRealm(dialog_form.origin, auth_info); return dialog_form; } // static void LoginHandler::GetDialogStrings(const GURL& request_url, const net::AuthChallengeInfo& auth_info, base::string16* authority, base::string16* explanation) { GURL authority_url; if (auth_info.is_proxy) { *authority = l10n_util::GetStringFUTF16( IDS_LOGIN_DIALOG_PROXY_AUTHORITY, url_formatter::FormatOriginForSecurityDisplay( auth_info.challenger, url_formatter::SchemeDisplay::SHOW)); authority_url = GURL(auth_info.challenger.Serialize()); } else { *authority = l10n_util::GetStringFUTF16( IDS_LOGIN_DIALOG_AUTHORITY, url_formatter::FormatUrlForSecurityDisplay(request_url)); authority_url = request_url; } if (!content::IsOriginSecure(authority_url)) { // TODO(asanka): The string should be different for proxies and servers. // http://crbug.com/620756 *explanation = l10n_util::GetStringUTF16(IDS_WEBSITE_SETTINGS_NON_SECURE_TRANSPORT); } else { explanation->clear(); } } // static void LoginHandler::ShowLoginPrompt(const GURL& request_url, net::AuthChallengeInfo* auth_info, LoginHandler* handler) { DCHECK_CURRENTLY_ON(BrowserThread::UI); WebContents* parent_contents = handler->GetWebContentsForLogin(); if (!parent_contents) return; prerender::PrerenderContents* prerender_contents = prerender::PrerenderContents::FromWebContents(parent_contents); if (prerender_contents) { prerender_contents->Destroy(prerender::FINAL_STATUS_AUTH_NEEDED); return; } base::string16 authority; base::string16 explanation; GetDialogStrings(request_url, *auth_info, &authority, &explanation); password_manager::PasswordManager* password_manager = handler->GetPasswordManagerForLogin(); if (!password_manager) { #if defined(ENABLE_EXTENSIONS) // A WebContents in a <webview> (a GuestView type) does not have a password // manager, but still needs to be able to show login prompts. const auto* guest = guest_view::GuestViewBase::FromWebContents(parent_contents); if (guest && extensions::GetViewType(guest->owner_web_contents()) != extensions::VIEW_TYPE_EXTENSION_BACKGROUND_PAGE) { handler->BuildViewWithoutPasswordManager(authority, explanation); return; } #endif handler->CancelAuth(); return; } if (password_manager && password_manager->client()->GetLogManager()->IsLoggingActive()) { password_manager::BrowserSavePasswordProgressLogger logger( password_manager->client()->GetLogManager()); logger.LogMessage( autofill::SavePasswordProgressLogger::STRING_SHOW_LOGIN_PROMPT_METHOD); } PasswordForm observed_form( LoginHandler::MakeInputForPasswordManager(request_url, *auth_info)); handler->BuildViewWithPasswordManager(authority, explanation, password_manager, observed_form); } // static void LoginHandler::LoginDialogCallback(const GURL& request_url, net::AuthChallengeInfo* auth_info, LoginHandler* handler, bool is_main_frame) { DCHECK_CURRENTLY_ON(BrowserThread::UI); WebContents* parent_contents = handler->GetWebContentsForLogin(); if (!parent_contents || handler->WasAuthHandled()) { // The request may have been canceled, or it may be for a renderer not // hosted by a tab (e.g. an extension). Cancel just in case (canceling twice // is a no-op). handler->CancelAuth(); return; } // Check if this is a main frame navigation and // (a) if the request is cross origin or // (b) if an interstitial is already being shown or // (c) the prompt is for proxy authentication // // For (a), there are two different ways the navigation can occur: // 1- The user enters the resource URL in the omnibox. // 2- The page redirects to the resource. // In both cases, the last committed URL is different than the resource URL, // so checking it is sufficient. // Note that (1) will not be true once site isolation is enabled, as any // navigation could cause a cross-process swap, including link clicks. // // For (b), the login interstitial should always replace an existing // interstitial. This is because |LoginHandler::CloseContentsDeferred| tries // to proceed whatever interstitial is being shown when the login dialog is // closed, so that interstitial should only be a login interstitial. // // For (c), the authority information in the omnibox will be (and should be) // different from the authority information in the authentication prompt. An // interstitial with an empty URL clears the omnibox and reduces the possible // user confusion that may result from the different authority information // being displayed simultaneously. This is specially important when the proxy // is accessed via an open connection while the target server is considered // secure. if (is_main_frame && (parent_contents->ShowingInterstitialPage() || auth_info->is_proxy || parent_contents->GetLastCommittedURL().GetOrigin() != request_url.GetOrigin())) { // Show a blank interstitial for main-frame, cross origin requests // so that the correct URL is shown in the omnibox. base::Closure callback = base::Bind(&LoginHandler::ShowLoginPrompt, request_url, base::RetainedRef(auth_info), base::RetainedRef(handler)); // The interstitial delegate is owned by the interstitial that it creates. // This cancels any existing interstitial. handler->SetInterstitialDelegate( (new LoginInterstitialDelegate( parent_contents, auth_info->is_proxy ? GURL() : request_url, callback)) ->GetWeakPtr()); } else { ShowLoginPrompt(request_url, auth_info, handler); } } // ---------------------------------------------------------------------------- // Public API LoginHandler* CreateLoginPrompt(net::AuthChallengeInfo* auth_info, net::URLRequest* request) { bool is_main_frame = (request->load_flags() & net::LOAD_MAIN_FRAME) != 0; LoginHandler* handler = LoginHandler::Create(auth_info, request); BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::Bind(&LoginHandler::LoginDialogCallback, request->url(), base::RetainedRef(auth_info), base::RetainedRef(handler), is_main_frame)); return handler; }
#include <stack> #include "../util/scope_guard.hpp" #include "activity.hpp" #include "animation.hpp" #include "area.hpp" #include "attack.hpp" #include "audio.hpp" #include "buff.hpp" #include "buff_utils.hpp" #include "calc.hpp" #include "character.hpp" #include "character_status.hpp" #include "command.hpp" #include "config.hpp" #include "crafting.hpp" #include "crafting_material.hpp" #include "data/types/type_asset.hpp" #include "data/types/type_buff.hpp" #include "data/types/type_item.hpp" #include "data/types/type_item_material.hpp" #include "data/types/type_skill.hpp" #include "debug.hpp" #include "dmgheal.hpp" #include "draw.hpp" #include "element.hpp" #include "elona.hpp" #include "enchantment.hpp" #include "food.hpp" #include "fov.hpp" #include "game.hpp" #include "globals.hpp" #include "god.hpp" #include "i18n.hpp" #include "input.hpp" #include "inventory.hpp" #include "item.hpp" #include "itemgen.hpp" #include "lua_env/interface.hpp" #include "map.hpp" #include "map_cell.hpp" #include "mef.hpp" #include "menu.hpp" #include "message.hpp" #include "quest.hpp" #include "random.hpp" #include "save.hpp" #include "save_fs.hpp" #include "skill.hpp" #include "status_ailment.hpp" #include "text.hpp" #include "trait.hpp" #include "ui.hpp" #include "variables.hpp" #include "wish.hpp" namespace { // Eye of Insanity bool _magic_636(Character& subject, Character& target) { txt(i18n::s.get("core.magic.insanity", subject, target), Message::color{ColorIndex::purple}); damage_insanity(target, rnd_capped(roll(dice1, dice2, bonus) + 1)); return true; } // Item: treasure map bool _magic_1136(const ItemRef& treasure_map) { if (map_data.type != mdata_t::MapType::world_map) { txt(i18n::s.get("core.magic.map.need_global_map")); return true; } if (is_cursed(efstatus)) { if (rnd(5) == 0) { txt(i18n::s.get("core.magic.map.cursed")); treasure_map->modify_number(-1); return true; } } if (treasure_map->param1 == 0) { item_separate(treasure_map); for (int cnt = 0; cnt < 1000; ++cnt) { dx = 4 + rnd(map_data.width - 8); dy = 3 + rnd(map_data.height - 6); if (dx >= 50 && dy >= 39 && dx <= 73 && dy <= 54) { continue; } x(0) = 1; x(1) = -1; x(2) = 0; x(3) = 0; y(0) = 0; y(1) = 0; y(2) = 1; y(3) = -1; for (int cnt = 0; cnt < 4; ++cnt) { f = 1; int cnt2 = cnt; for (int cnt = 0; cnt < 3; ++cnt) { p = cell_data.at(dx + x(cnt2) * cnt, dy + y(cnt2) * cnt) .chip_id_actual; if ((264 <= p && p < 363) || chip_data[p].effect & 4) { f = 0; break; } } if (f == 1) { break; } } if (f == 1) { break; } } treasure_map->param1 = dx; treasure_map->param2 = dy; } txt(i18n::s.get("core.magic.map.apply")); snd("core.book1"); const auto& info = asset_load("core.paper"); gsel(0); ww = info.width; wh = info.height; wx = (windoww - ww) / 2 + inf_screenx; wy = winposy(wh); gmode(2); gcopy(4, 0, 0, ww, wh, wx, wy); gmode(0); for (int cnt = 0; cnt < 5; ++cnt) { y = cnt + treasure_map->param2 - 2; sy = cnt * inf_tiles + wy + 26; for (int cnt = 0; cnt < 7; ++cnt) { x = cnt + treasure_map->param1 - 3; sx = cnt * inf_tiles + wx + 46; draw_map_tile(cell_data.at(x, y).chip_id_actual, sx + 1, sy + 1); if (x == treasure_map->param1) { if (y == treasure_map->param2) { font(40 - en * 2, snail::Font::Style::italic); mes(sx, sy, i18n::s.get("core.magic.map.mark"), {255, 20, 20}); } } } } gmode(2); gcopy(4, 400, 0, ww, wh, wx, wy); redraw(); wait_key_pressed(); snd("core.card1"); return true; } // Item: love potion bool _magic_1135(Character& target) { if (is_cursed(efstatus)) { if (target.is_player()) { food_apply_curse_state(target, efstatus); } else { txt(i18n::s.get("core.magic.love_potion.cursed", target)); chara_modify_impression(target, -15); } obvious = 0; return true; } target.emotion_icon = 317; if (potionspill || potionthrow) { txt(i18n::s.get("core.magic.love_potion.spill", target)); chara_modify_impression(target, clamp(efp / 15, 0, 15)); status_ailment_damage(target, StatusAilment::dimmed, 100); lovemiracle(target); return true; } if (target.is_player()) { txt(i18n::s.get("core.magic.love_potion.self", target)); } else { txt(i18n::s.get("core.magic.love_potion.other", target)); lovemiracle(target); chara_modify_impression(target, clamp(efp / 4, 0, 25)); } status_ailment_damage(target, StatusAilment::dimmed, 500); return true; } // Pregnant bool _magic_654(Character& subject, Character& target) { if (is_in_fov(target)) { txt(i18n::s.get("core.magic.pregnant", subject, target)); } get_pregnant(target); return true; } // Mirror bool _magic_626(Character& target) { txt(i18n::s.get("core.magic.mirror")); animeload(10, target); screen_analyze_self(); return true; } // Item: milk bool _magic_1101(Character& subject, Character& target) { if (is_in_fov(target)) { snd("core.atk_elec"); if (is_cursed(efstatus)) { if (target.is_player()) { txt(i18n::s.get("core.magic.milk.cursed.self")); } else { txt(i18n::s.get("core.magic.milk.cursed.other"), Message::color{ColorIndex::cyan}); } } else if (target.is_player()) { txt(i18n::s.get("core.magic.milk.self")); } else { txt(i18n::s.get("core.magic.milk.other"), Message::color{ColorIndex::cyan}); } } if (efstatus == CurseState::blessed) { modify_height(target, rnd(5) + 1); } if (is_cursed(efstatus)) { modify_height(target, (rnd(5) + 1) * -1); } target.nutrition += 1000 * (efp / 100); if (target.is_player()) { show_eating_message(subject); } food_apply_curse_state(target, efstatus); animeload(15, target); return true; } // Item: alcohol bool _magic_1102(Character& target) { if (is_in_fov(target)) { if (is_cursed(efstatus)) { txt(i18n::s.get("core.magic.alcohol.cursed"), Message::color{ColorIndex::cyan}); } else { txt(i18n::s.get("core.magic.alcohol.normal"), Message::color{ColorIndex::cyan}); } } status_ailment_damage(target, StatusAilment::drunk, efp); food_apply_curse_state(target, efstatus); return true; } // Item: acid bool _magic_1116(Character& target) { if (is_in_fov(target)) { if (target.is_player()) { txt(i18n::s.get("core.magic.acid.self")); } txt(i18n::s.get("core.magic.acid.apply", target)); } if (target.is_pregnant()) { target.is_pregnant() = false; if (is_in_fov(target)) { txt(i18n::s.get("core.magic.common.melts_alien_children", target)); } } damage_hp( target, efp * efstatusfix(500, 400, 100, 50) / 1000, -15, 63, efp); return true; } // Item: water bool _magic_1103(Character& target) { if (is_in_fov(target)) { if (target.is_player()) { txt(i18n::s.get("core.magic.water.self")); } else { txt(i18n::s.get("core.magic.water.other")); } } get_sick_if_cursed(efstatus, target); return true; } // Item: soda bool _magic_1146(Character& target) { if (is_in_fov(target)) { txt(i18n::s.get("core.magic.restore_stamina.dialog")); txt(i18n::s.get("core.magic.restore_stamina.apply", target)); } heal_sp(target, 25); get_sick_if_cursed(efstatus, target); return true; } // Item: blue capsule drug bool _magic_1147(Character& target) { if (is_in_fov(target)) { txt(i18n::s.get("core.magic.restore_stamina_greater.dialog")); txt(i18n::s.get("core.magic.restore_stamina_greater.apply", target)); } heal_sp(target, 100); get_sick_if_cursed(efstatus, target); return true; } // Item: salt solution bool _magic_1142(Character& target) { if (target.race == "core.snail") { if (is_in_fov(target)) { txt(i18n::s.get("core.magic.salt.snail", target), Message::color{ColorIndex::red}); } if (target.hp > 10) { damage_hp(target, target.hp - rnd(10), -15); } else { damage_hp(target, rnd(20000), -15); } } else if (is_in_fov(target)) { txt(i18n::s.get("core.magic.salt.apply"), Message::color{ColorIndex::cyan}); } return true; } // Item: dirty water bool _magic_1130(Character& target) { if (is_in_fov(target)) { if (target.is_player()) { txt(i18n::s.get("core.magic.dirty_water.self")); } else { txt(i18n::s.get("core.magic.dirty_water.other")); } } get_sick_if_cursed(efstatus, target); return true; } // Pickpocket bool _magic_300(Character& subject, Character& target) { if (game()->executing_immediate_quest_type == 1008 || game()->executing_immediate_quest_type == 1010) { txt(i18n::s.get("core.magic.steal.in_quest")); return false; } if (subject.is_player()) { if (cdata.player().sp < 50) { if (cdata.player().sp < rnd(75)) { txt(i18n::s.get("core.magic.common.too_exhausted")); damage_sp(cdata.player(), the_skill_db[efid]->cost / 2 + 1); return true; } } damage_sp( cdata.player(), rnd(the_skill_db[efid]->cost / 2 + 1) + the_skill_db[efid]->cost / 2 + 1); } invsubroutine = 1; invctrl(0) = 27; invctrl(1) = 0; snd("core.inv"); // In Pickpocket spact, target == player means that you attempts to steal // items on the ground, not in someone's inventory. CtrlInventoryOptions opts; if (!target.is_player()) { opts.inventory_owner = target; } ctrl_inventory(opts); return true; } // Riding bool _magic_301(Character& subject, Character& target) { if (subject.is_player()) { if (cdata.player().sp < 50) { if (cdata.player().sp < rnd(75)) { txt(i18n::s.get("core.magic.common.too_exhausted")); damage_sp(cdata.player(), the_skill_db[efid]->cost / 2 + 1); return true; } } damage_sp( cdata.player(), rnd(the_skill_db[efid]->cost / 2 + 1) + the_skill_db[efid]->cost / 2 + 1); } if (game()->mount != 0) { if (target == subject) { int stat = cell_findspace( cdata.player().position.x, cdata.player().position.y, 1); if (stat == 0) { txt(i18n::s.get("core.magic.mount.no_place_to_get_off")); return true; } cell_setchara(cdata[game()->mount], rtval, rtval(1)); txt(i18n::s.get("core.magic.mount.dismount", cdata[game()->mount])); txt(name(game()->mount) + i18n::s.get("core.magic.mount.dismount_dialog"), Message::color{ColorIndex::cyan}); ride_end(); return true; } } if (!target.is_player_or_ally()) { txt(i18n::s.get("core.magic.mount.only_ally")); return true; } if (target.is_escorted() == 1 || target.is_escorted_in_sub_quest() == 1) { txt(i18n::s.get("core.magic.mount.not_client")); return true; } if (target == subject) { if (game()->mount == 0) { txt(i18n::s.get("core.magic.mount.ride_self", subject)); } return true; } if (target.current_map != 0) { txt(i18n::s.get("core.magic.mount.stays_in_area")); return true; } if (game()->mount != 0) { txt(i18n::s.get( "core.magic.mount.currently_riding", subject, cdata[game()->mount])); } else { ride_begin(target.index); txt(name(game()->mount) + i18n::space_if_needed() + i18n::s.get("core.magic.mount.mount.dialog"), Message::color{ColorIndex::cyan}); } return true; } // Performance bool _magic_183(Character& subject, OptionalItemRef instrument) { assert(!subject.is_player() || instrument); if (!subject.is_player()) { for (const auto& item : *subject.inventory()) { if (item->skill == 183) { instrument = item; break; } } if (!instrument) { return false; } } if (subject.skills().level("core.performer") == 0) { if (is_in_fov(subject)) { txt(i18n::s.get("core.magic.perform.do_not_know", subject)); return false; } } if (subject.is_player()) { if (cdata.player().sp < 50) { if (cdata.player().sp < rnd(75)) { txt(i18n::s.get("core.magic.common.too_exhausted")); damage_sp(cdata.player(), the_skill_db[efid]->cost / 2 + 1); return true; } } damage_sp( cdata.player(), rnd(the_skill_db[efid]->cost / 2 + 1) + the_skill_db[efid]->cost / 2 + 1); } activity_perform(subject, instrument.unwrap()); return true; } // Cooking bool _magic_184(Character& subject, const ItemRef& cook_tool) { if (cdata.player().skills().level("core.cooking") == 0) { txt(i18n::s.get("core.magic.cook.do_not_know")); return false; } invsubroutine = 1; invctrl = 16; snd("core.inv"); const auto& [menu_result, food_opt] = ctrl_inventory(); if (!menu_result.succeeded) { return false; } assert(food_opt); const auto food = food_opt.unwrap(); if (subject.is_player()) { if (cdata.player().sp < 50) { if (cdata.player().sp < rnd(75)) { txt(i18n::s.get("core.magic.common.too_exhausted")); damage_sp(cdata.player(), the_skill_db[efid]->cost / 2 + 1); return true; } } damage_sp( cdata.player(), rnd(the_skill_db[efid]->cost / 2 + 1) + the_skill_db[efid]->cost / 2 + 1); } food_cook(subject, cook_tool, food); return true; } // Fishing bool _magic_185(Character& subject, const ItemRef& rod) { if (cdata.player().skills().level("core.fishing") == 0) { txt(i18n::s.get("core.magic.fish.do_not_know")); return false; } if (!inv_player()->has_free_slot()) { txt(i18n::s.get("core.ui.inv.common.inventory_is_full")); return false; } if (rod->charges == 0) { txt(i18n::s.get("core.magic.fish.need_bait")); return false; } f = 0; for (int cnt = 0; cnt < 3; ++cnt) { y = subject.position.y + cnt - 1; x = subject.position.x; if (x < 0 || y < 0 || x >= map_data.width || y >= map_data.height) { continue; } if (chip_data.for_cell(x, y).kind == 3) { f = 1; break; } } if (f == 0) { for (int cnt = 0; cnt < 3; ++cnt) { y = subject.position.y; x = subject.position.x + cnt - 1; if (x < 0 || y < 0 || x >= map_data.width || y >= map_data.height) { continue; } if (chip_data.for_cell(x, y).kind == 3) { f = 1; break; } } } if (f == 0) { txt(i18n::s.get("core.magic.fish.not_good_place"), Message::only_once{true}); update_screen(); return false; } if (chip_data.for_cell(cdata.player().position.x, cdata.player().position.y) .kind == 3) { txt(i18n::s.get("core.magic.fish.cannot_during_swim")); update_screen(); return false; } if (cdata.player().position.x - x > 0) { cdata.player().direction = 1; } if (cdata.player().position.x - x < 0) { cdata.player().direction = 2; } if (cdata.player().position.y - y > 0) { cdata.player().direction = 3; } if (cdata.player().position.y - y < 0) { cdata.player().direction = 0; } game()->player_next_move_direction = cdata.player().direction; fishx = x; fishy = y; addefmap(fishx, fishy, 1, 3); if (subject.is_player()) { if (cdata.player().sp < 50) { if (cdata.player().sp < rnd(75)) { txt(i18n::s.get("core.magic.common.too_exhausted")); damage_sp(cdata.player(), the_skill_db[efid]->cost / 2 + 1); return true; } } damage_sp( cdata.player(), rnd(the_skill_db[efid]->cost / 2 + 1) + the_skill_db[efid]->cost / 2 + 1); } item_separate(rod); --rod->charges; rowactre = 0; spot_fishing(subject, rod); return true; } bool _magic_645_1114(Character&, Character&); // Holy Light / Vanquish Hex bool _magic_406_407(Character& subject, Character& target) { if (is_cursed(efstatus)) { if (is_in_fov(target)) { txt(i18n::s.get("core.magic.common.cursed", target)); } return _magic_645_1114(subject, target); } int cnt = 0; buff_remove_if_reverse(target, [&cnt](const auto& buff) { if (efid == 406 && 1 <= cnt) return false; if (buff.id == "core.punishment") return false; if (the_buff_db[buff.id]->type != BuffType::hex) return false; if (rnd_capped(efp * 2 + 1) > rnd_capped(buff.power + 1)) { cnt += 1; return true; } else { return false; } }); buff_add(target, "core.holy_veil", efp, 5 + efp / 30, subject); animeload(11, target); return true; } // Prayer bool _magic_1120(Character& target) { txt(i18n::s.get("core.magic.prayer", target), Message::color{ColorIndex::orange}); heal_completely(target); BrightAuraAnimation(target.position, BrightAuraAnimation::Type::healing) .play(); return true; } // Random craft material bool _magic_1117(Character& target) { if (!target.is_player_or_ally()) { txt(i18n::s.get("core.common.nothing_happens")); obvious = 0; return true; } if (!is_cursed(efstatus)) { s = i18n::s.get("core.magic.create_material.materials"); } else { s = i18n::s.get("core.magic.create_material.junks"); } snd("core.ding2"); txt(i18n::s.get("core.magic.create_material.apply", s(0))); save_trigger_autosaving(); for (int cnt = 0, cnt_end = (rnd(3) + 3 + (efstatus == CurseState::blessed) * 6); cnt < cnt_end; ++cnt) { data::InstanceId crafting_material_id; if (!is_cursed(efstatus)) { crafting_material_id = crafting_material_select_random_id(efp / 10, efp / 50, 19); } else { crafting_material_id = "core.garbage"; } crafting_material_gain(crafting_material_id, 1); } return true; } bool _magic_628(Character& subject, Character& target); // Eye of Mutation / Mutation bool _magic_632_454_1144( Character& subject, Character& target, bool is_cursed_potion_of_cure_mutation = false) { if (!is_cursed_potion_of_cure_mutation) { if (!target.is_player()) { return _magic_628(subject, target); } if (efid == 632) { txt(i18n::s.get("core.magic.mutation.spell", subject, target)); if (rnd(3)) { return true; } } if (!target.is_player()) { txt(i18n::s.get("core.common.nothing_happens")); return true; } if (enchantment_find(target, 33)) { if (rnd(5)) { txt(i18n::s.get("core.magic.mutation.resist")); return true; } } } f = 0; p = 1; if (efid == 1144) { p = 2 + rnd(3); } for (int cnt = 0, cnt_end = (p); cnt < cnt_end; ++cnt) { for (int cnt = 0; cnt < 100; ++cnt) { int tid = rnd(45); int stat = trait_get_info(0, tid); if (stat == 0 || traitref != 1) { continue; } if (rnd(2)) { p = 1; } else { p = -1; } if (cdata.player().traits().level( *the_trait_db.get_id_from_integer(tid)) >= traitref(2)) { p = -1; } if (cdata.player().traits().level( *the_trait_db.get_id_from_integer(tid)) <= traitref(1)) { p = 1; } if (is_cursed(efstatus)) { if (p == 1) { continue; } } else if (p == -1) { if (efstatus == CurseState::blessed) { if (rnd(3) == 0) { continue; } } if (efid == 1144) { continue; } } cdata.player().traits().add( *the_trait_db.get_id_from_integer(tid), p); txt(i18n::s.get("core.magic.mutation.apply")); if (p > 0) { txt(traitrefn(0), Message::color{ColorIndex::green}); } else { txt(traitrefn(1), Message::color{ColorIndex::red}); } animeload(8, cdata.player()); f = 1; break; } } if (f == 0) { txt(i18n::s.get("core.common.nothing_happens")); obvious = 0; } chara_refresh(cdata.player()); return true; } // Item: potion of cure mutation bool _magic_1121(Character& subject, Character& target) { if (!target.is_player()) { txt(i18n::s.get("core.common.nothing_happens")); return true; } if (is_cursed(efstatus)) { if (is_in_fov(target)) { txt(i18n::s.get("core.magic.common.it_is_cursed")); } return _magic_632_454_1144(subject, target, true); } f = 0; for (int cnt = 0, cnt_end = cnt + (1 + (efstatus == CurseState::blessed) + (!is_cursed(efstatus)) + rnd(2)); cnt < cnt_end; ++cnt) { for (int cnt = 0; cnt < 100; ++cnt) { int tid = rnd(217); int stat = trait_get_info(0, tid); if (stat == 0 || traitref != 1) { continue; } if (cdata.player().traits().level( *the_trait_db.get_id_from_integer(tid)) == 0) { continue; } if (cdata.player().traits().level( *the_trait_db.get_id_from_integer(tid)) > 0) { p = -1; } if (cdata.player().traits().level( *the_trait_db.get_id_from_integer(tid)) < 0) { p = 1; } cdata.player().traits().set_level( *the_trait_db.get_id_from_integer(tid), 0); txt(i18n::s.get("core.magic.cure_mutation")); if (p > 0) { txt(traitrefn(0), Message::color{ColorIndex::green}); } else { txt(traitrefn(1), Message::color{ColorIndex::red}); } f = 1; break; } } if (f == 0) { txt(i18n::s.get("core.common.nothing_happens")); obvious = 0; } chara_refresh(cdata.player()); return true; } // Identify bool _magic_411(Character& subject) { if (!subject.is_player()) { txt(i18n::s.get("core.common.nothing_happens")); obvious = 0; return true; } invsubroutine = 1; invctrl = 13; snd("core.inv"); ctrl_inventory(); return true; } // Resurrection bool _magic_461(Character& subject) { if (map_data.type == mdata_t::MapType::world_map) { txt(i18n::s.get("core.common.nothing_happens")); obvious = 0; return true; } if (is_cursed(efstatus)) { txt(i18n::s.get("core.magic.resurrection.cursed")); for (int cnt = 0, cnt_end = (4 + rnd(4)); cnt < cnt_end; ++cnt) { flt(calcobjlv(cdata.player().level), calcfixlv(Quality::good)); fltn("undead"s); chara_create( -1, "", cdata.player().position.x, cdata.player().position.y); } obvious = 0; return true; } int stat = show_hire_menu(HireOperation::revive); if (stat == -1) { txt(i18n::s.get("core.common.nothing_happens")); obvious = 0; return true; } if (bonus < rnd(100)) { if (is_in_fov(subject)) { txt(i18n::s.get("core.magic.resurrection.fail", subject)); } return true; } do_chara_revival(cdata[stat]); cxinit = subject.position.x; cyinit = subject.position.y; chara_place(cdata[stat]); cdata[stat].current_map = 0; txt(i18n::s.get( "core.magic.resurrection.apply", cnven(cdata[stat].name), cdata[stat]), Message::color{ColorIndex::orange}); txt(i18n::s.get("core.magic.resurrection.dialog")); MiracleAnimation(MiracleAnimation::Mode::target_one, cdata[stat]).play(); snd("core.pray2"); cdata[stat].emotion_icon = 317; if (subject.is_player()) { chara_modify_impression(cdata[stat], 15); if (stat >= 16) { modify_karma(cdata.player(), 2); } } return true; } bool _magic_645_1114(Character&, Character&); // Uncurse bool _magic_412(Character& subject, Character& target) { if (efstatus == CurseState::none) { if (is_in_fov(target)) { txt(i18n::s.get("core.magic.uncurse.apply", target)); } } if (efstatus == CurseState::blessed) { if (is_in_fov(target)) { txt(i18n::s.get("core.magic.uncurse.blessed", target)); } } if (is_cursed(efstatus)) { if (is_in_fov(target)) { txt(i18n::s.get("core.magic.common.cursed", target)); } return _magic_645_1114(subject, target); } p(1) = 0; p(2) = 0; for (const auto& item : *target.inventory()) { if (!is_cursed(item->curse_state)) { continue; } p = 0; if (item->curse_state == CurseState::cursed) { p = rnd(200) + 1; } if (item->curse_state == CurseState::doomed) { p = rnd(1000) + 1; } if (efstatus == CurseState::blessed) { p = p / 2 + 1; } else if (!item->is_equipped()) { continue; } if (p != 0) { if (efp >= p) { ++p(1); item->curse_state = CurseState::none; inv_stack(target.inventory(), item, true); } else { ++p(2); } } } if (efstatus == CurseState::blessed) { if (p(1) != 0) { if (is_in_fov(target)) { txt(i18n::s.get("core.magic.uncurse.item", target)); } } } else if (p(1) != 0) { if (is_in_fov(target)) { txt(i18n::s.get("core.magic.uncurse.equipment", target)); } } if (p(2) != 0) { if (is_in_fov(target)) { txt(i18n::s.get("core.magic.uncurse.resist")); } } if (p(1) == 0 && p(2) == 0) { txt(i18n::s.get("core.common.nothing_happens")); obvious = 0; } else { animeload(10, target); } chara_refresh(target); return true; } // Oracle bool _magic_413(Character& target) { if (!target.is_player_or_ally()) { txt(i18n::s.get("core.common.nothing_happens")); return true; } if (is_cursed(efstatus)) { game()->artifact_logs.clear(); txt(i18n::s.get("core.magic.oracle.cursed")); return true; } if (game()->artifact_logs.empty()) { txt(i18n::s.get("core.magic.oracle.no_artifacts")); } else { for (const auto& log : game()->artifact_logs) { txt(cnven(log.content)); } game()->artifact_logs.clear(); } return true; } // Gain spell stock bool _magic_1104(Character& target) { if (!target.is_player()) { txt(i18n::s.get("core.common.nothing_happens")); obvious = 0; return true; } f = 0; for (int cnt = 0, cnt_end = (1 + (efstatus == CurseState::blessed)); cnt < cnt_end; ++cnt) { int cnt2 = cnt; for (int cnt = 0; cnt < 2000; ++cnt) { p = rnd(67) + 400; if (p == 441) { if (rnd(10)) { continue; } } if (!the_skill_db[p]) { continue; } if (!is_cursed(efstatus)) { if (cnt2 == 0) { s = i18n::s.get("core.magic.gain_knowledge.suddenly"); } else { s = i18n::s.get("core.magic.gain_knowledge.furthermore"); } chara_gain_skill(cdata.player(), p, 1, 200); txt(s + i18n::s.get( "core.magic.gain_knowledge.gain", the_skill_db.get_text(p, "name")), Message::color{ColorIndex::green}); snd("core.ding2"); f = 1; break; } else { if (target.spell_stocks().amount( *the_skill_db.get_id_from_integer(p)) > 0) { target.spell_stocks().set_amount( *the_skill_db.get_id_from_integer(p), 0); txt(i18n::s.get("core.magic.common.it_is_cursed")); txt(i18n::s.get( "core.magic.gain_knowledge.lose", the_skill_db.get_text(p, "name")), Message::color{ColorIndex::red}); snd("core.curse3"); animeload(14, cdata.player()); f = 1; break; } } } } if (f == 0) { txt(i18n::s.get("core.common.nothing_happens")); obvious = 0; return true; } save_trigger_autosaving(); return true; } // Item: potion of descent bool _magic_1143(Character& target) { if (efstatus == CurseState::blessed) { target.experience = target.required_experience; r2 = 0; gain_level(target); if (is_in_fov(target)) { snd("core.ding1"); } } else { if (target.level <= 1) { txt(i18n::s.get("core.common.nothing_happens")); obvious = 0; return true; } --target.level; target.experience = 0; update_required_experience(target); txt(i18n::s.get("core.magic.descent", target), Message::color{ColorIndex::purple}); } if (is_cursed(efstatus)) { txt(i18n::s.get("core.magic.common.it_is_cursed")); for (int cnt = 10; cnt < 50; ++cnt) { if (rnd(3) == 0) { if (cnt <= 17) { if (target.skills().level( *the_skill_db.get_id_from_integer(cnt)) != 0) { chara_gain_skill_exp(target, cnt, -1000); } } } } animeload(8, target); } chara_refresh(target); return true; } // Item: scroll of gain attribute bool _magic_1105(Character& target) { for (int cnt = 0;; ++cnt) { p = rnd(300) + 100; if (the_skill_db[p]) { if (!is_cursed(efstatus)) { if (cnt < efstatusfix(0, 0, 100, 2000)) { if (target.skills().level( *the_skill_db.get_id_from_integer(p)) != 0) { continue; } } chara_gain_skill(target, p, 1); if (is_in_fov(target)) { snd("core.ding2"); txt(i18n::s.get( "core.magic.gain_skill", target, the_skill_db.get_text(p, "name")), Message::color{ColorIndex::green}); } break; } else { if (target.skills().level( *the_skill_db.get_id_from_integer(p)) == 0) { continue; } if (is_in_fov(target)) { snd("core.curse1"); txt(i18n::s.get("core.magic.common.it_is_cursed")); } chara_gain_skill_exp(target, p, -1000); break; } } } chara_refresh(target); save_trigger_autosaving(); return true; } // Item: scroll of faith bool _magic_1107(Character& target) { if (!target.is_player()) { txt(i18n::s.get("core.common.nothing_happens")); obvious = 0; return true; } if (cdata.player().religion == "") { txt(i18n::s.get("core.common.nothing_happens")); obvious = 0; return true; } if (is_cursed(efstatus)) { txt(i18n::s.get("core.magic.faith.doubt")); snd("core.curse3"); animeload(14, cdata.player()); chara_gain_skill_exp(cdata.player(), 181, -1000); return true; } txt(i18n::s.get( "core.magic.faith.apply", god_get_name(cdata.player().religion)), Message::color{ColorIndex::green}); if (efstatus == CurseState::blessed) { txt(i18n::s.get("core.magic.faith.blessed")); } MiracleAnimation(MiracleAnimation::Mode::target_one, target).play(); snd("core.pray2"); cdata.player().prayer_point += 500; god_add_piety(cdata.player(), 75); chara_gain_skill_exp( cdata.player(), 181, 1000 + (efstatus == CurseState::blessed) * 750, 6, 1000); chara_refresh(target); return true; } // Item: scroll of growth bool _magic_1119(Character& target) { for (int cnt = 0, cnt_end = (1 + (efstatus == CurseState::blessed)); cnt < cnt_end; ++cnt) { int cnt2 = cnt; while (1) { p = rnd(300) + 100; if (the_skill_db[p]) { if (target.skills().base_level( *the_skill_db.get_id_from_integer(p)) == 0) { continue; } skill_add_potential( target, *the_skill_db.get_id_from_integer(p), efp * efstatusfix(-4, -2, 5, 5) / 100); if (cnt2 == 0) { s = i18n::s.get("core.magic.gain_skill_potential.the"); } else { s = i18n::s.get( "core.magic.gain_skill_potential.furthermore_the"); } if (!is_cursed(efstatus)) { if (is_in_fov(target)) { snd("core.ding2"); txt(s + i18n::s.get( "core.magic.gain_skill_potential.increases", target, the_skill_db.get_text(p, "name")), Message::color{ColorIndex::green}); } } else if (is_in_fov(target)) { snd("core.curse3"); txt(i18n::s.get( "core.magic.gain_skill_potential.decreases", target, the_skill_db.get_text(p, "name")), Message::color{ColorIndex::red}); } break; } } } chara_refresh(target); save_trigger_autosaving(); return true; } // Lose stats' experience bool _magic_1106(Character& target) { i = rnd(10) + 10; chara_gain_skill_exp(target, i, efstatusfix(-2000, -2000, -1000, -250)); BrightAuraAnimation(target.position, BrightAuraAnimation::Type::debuff) .play(); chara_refresh(target); return true; } // Item: troll blood bool _magic_1139(Character& target) { txt(i18n::s.get("core.magic.troll_blood.apply", target)); chara_gain_skill_exp(target, 18, efstatusfix(-4000, -1000, 8000, 12000)); if (efstatus == CurseState::blessed) { skill_add_potential(target, "core.stat_speed", 15); txt(i18n::s.get("core.magic.troll_blood.blessed"), Message::color{ColorIndex::green}); } chara_refresh(target); return true; } // Gain stats' potential bool _magic_1113(Character& target) { if (efstatus == CurseState::blessed) { for (int cnt = 10; cnt < 18; ++cnt) { skill_add_potential( target, *the_skill_db.get_id_from_integer(cnt), rnd(target.skills().potential( *the_skill_db.get_id_from_integer(cnt)) / 20 + 3) + 1); } txt(i18n::s.get("core.magic.gain_potential.blessed", target)); MiracleAnimation(MiracleAnimation::Mode::target_one, target).play(); snd("core.ding3"); } else { i = rnd(8) + 10; const auto valn = the_skill_db.get_text(i, "name"); if (efstatus == CurseState::none) { txt(i18n::s.get( "core.magic.gain_potential.increases", target, valn)); skill_add_potential( target, *the_skill_db.get_id_from_integer(i), rnd(target.skills().potential( *the_skill_db.get_id_from_integer(i)) / 10 + 10) + 1); snd("core.ding2"); } else { txt(i18n::s.get( "core.magic.gain_potential.decreases", target, valn)); skill_add_potential( target, *the_skill_db.get_id_from_integer(i), (rnd(target.skills().potential( *the_skill_db.get_id_from_integer(i)) / 10 + 10) + 1) * -1); snd("core.curse3"); } } if (target.is_player()) { save_trigger_autosaving(); } return true; } // Vanish bool _magic_653(Character& target) { if (target.is_global()) { return true; } if (target.quality >= Quality::miracle) { return true; } txt(i18n::s.get("core.magic.vanish", target)); chara_vanquish(target); quest_check(); return true; } // Sense Object / Magic Map bool _magic_430_429(Character& target) { if (!target.is_player_or_ally()) { txt(i18n::s.get("core.common.nothing_happens")); obvious = 0; return true; } p = 1; if (efid == 430) { p = 2; } for (int cnt = 0, cnt_end = (p); cnt < cnt_end; ++cnt) { for (int cnt = 0, cnt_end = (map_data.height); cnt < cnt_end; ++cnt) { y = cnt; for (int cnt = 0, cnt_end = (map_data.width); cnt < cnt_end; ++cnt) { x = cnt; p = dist(target.position, x, y); if (is_cursed(efstatus)) { if (efid == 429) { cell_data.at(x, y).chip_id_memory = tile_default; } if (efid == 430) { cell_data.at(x, y).item_info_memory.clear(); } continue; } if (p < 7 || rnd_capped(efp + 1) > rnd(p * 8 + 1) || efstatus == CurseState::blessed) { if (efid == 429) { cell_data.at(x, y).chip_id_memory = cell_data.at(x, y).chip_id_actual; } if (efid == 430) { if (cell_data.at(x, y).feats != 0 || !cell_data.at(x, y).item_info_memory.is_empty()) { cell_data.at(x, y).chip_id_memory = cell_data.at(x, y).chip_id_actual; } } } } } } if (is_cursed(efstatus)) { txt(i18n::s.get("core.magic.sense.cursed")); } else { if (efid == 429) { txt(i18n::s.get("core.magic.sense.magic_mapping", target)); } if (efid == 430) { txt(i18n::s.get("core.magic.sense.sense_object", target)); } } animeload(10, target); update_minimap(); update_screen(); return true; } // Decapitation bool _magic_658(Character& subject, Character& target) { if (target.hp > target.max_hp / 8) { return true; } if (is_in_fov(target)) { snd("core.atksword"); txt(i18n::s.get("core.magic.vorpal.sound"), Message::color{ColorIndex::red}); if (!target.is_player_or_ally()) { g_proc_damage_events_flag = 2; txt3rd = 1; txt(i18n::s.get("core.magic.vorpal.other", subject, target)); } else { txt(i18n::s.get("core.magic.vorpal.ally", subject, target)); } } damage_hp(target, target.max_hp, subject.index, 658); return true; } // Restore Spirit / Restore Body bool _magic_440_439(Character& target) { if (efid == 439) { if (is_in_fov(target)) { if (is_cursed(efstatus)) { snd("core.curse3"); txt(i18n::s.get("core.magic.restore.body.cursed", target)); } else { txt(i18n::s.get("core.magic.restore.body.apply", target)); animeload(10, target); } if (efstatus == CurseState::blessed) { txt(i18n::s.get("core.magic.restore.body.blessed", target)); animeload(10, target); } } p(0) = 10; p(1) = 11; p(2) = 12; p(3) = 17; p(4) = 18; p(5) = -1; } if (efid == 440) { if (is_in_fov(target)) { if (is_cursed(efstatus)) { snd("core.curse3"); txt(i18n::s.get("core.magic.restore.mind.cursed", target)); } else { txt(i18n::s.get("core.magic.restore.mind.apply", target)); animeload(10, target); } if (efstatus == CurseState::blessed) { txt(i18n::s.get("core.magic.restore.mind.blessed", target)); animeload(10, target); } } p(0) = 14; p(1) = 13; p(2) = 16; p(3) = 15; p(4) = 19; p(5) = -1; } for (int cnt = 0;; ++cnt) { if (p(cnt) == -1) { break; } const auto attr = p(cnt) - 10; if (is_cursed(efstatus)) { if (target.quality <= Quality::great) { target.attr_adjs[attr] -= rnd(target.skills().base_level( *the_skill_db.get_id_from_integer(p(cnt)))) / 5 + rnd(5); continue; } } if (target.attr_adjs[attr] < 0) { target.attr_adjs[attr] = 0; } if (efstatus == CurseState::blessed) { target.attr_adjs[attr] = target.skills().base_level( *the_skill_db.get_id_from_integer(p(cnt))) / 10 + 5; } } chara_refresh(target); return true; } // Wish bool _magic_441(Character& subject) { what_do_you_wish_for(subject); screenupdate = -1; gmode(2); update_screen(); return true; } // Item: scroll of escape bool _magic_1141(Character& target) { if (!target.is_player()) { txt(i18n::s.get("core.common.nothing_happens")); obvious = 0; return true; } if (game()->is_returning_or_escaping != 0) { txt(i18n::s.get("core.magic.escape.cancel")); game()->is_returning_or_escaping = 0; } else { if (quest_is_return_forbidden()) { txt(i18n::s.get("core.magic.escape.during_quest")); if (!yes_no()) { return true; } } txt(i18n::s.get("core.magic.escape.begin")); if (area_data[game()->current_map].id == mdata_t::MapId::random_dungeon) { if (game()->current_dungeon_level == area_data[game()->current_map].deepest_level) { if (area_data[game()->current_map].has_been_conquered != -1) { txt(i18n::s.get("core.magic.escape.lord_may_disappear")); } } } game()->destination_map = game()->destination_outer_map; game()->destination_dungeon_level = 1; if (is_cursed(efstatus)) { if (rnd(3) == 0) { game()->destination_map = 41; game()->destination_dungeon_level = 1; } } game()->is_returning_or_escaping = 5 + rnd(10); } return true; } // Return bool _magic_428(Character& target) { if (!target.is_player()) { txt(i18n::s.get("core.common.nothing_happens")); obvious = 0; return true; } if (game()->is_returning_or_escaping != 0) { txt(i18n::s.get("core.magic.return.cancel")); game()->is_returning_or_escaping = 0; } else { try_to_return(); if (is_cursed(efstatus)) { if (rnd(3) == 0) { game()->destination_map = 41; game()->destination_dungeon_level = 1; } } } return true; } // Harvest Mana bool _magic_621(Character& target) { heal_mp(target, efp / 2 + rnd_capped(efp / 2 + 1)); if (is_in_fov(target)) { txt(i18n::s.get("core.magic.harvest_mana", target)); BrightAuraAnimation(target.position, BrightAuraAnimation::Type::healing) .play(); } return true; } // Absorb Magic bool _magic_624(Character& target) { heal_mp(target, roll(dice1, dice2, bonus)); if (is_in_fov(target)) { txt(i18n::s.get("core.magic.absorb_magic", target)); BrightAuraAnimation(target.position, BrightAuraAnimation::Type::healing) .play(); } return true; } // Item: poison bool _magic_1108(Character& target) { if (is_in_fov(target)) { txt(i18n::s.get("core.magic.poison_attack", target)); } if (target.is_pregnant()) { target.is_pregnant() = false; if (is_in_fov(target)) { txt(i18n::s.get("core.magic.common.melts_alien_children", target)); } } status_ailment_damage(target, StatusAilment::poisoned, efp); return true; } // Item: potion of blindness bool _magic_1111(Character& target) { if (is_in_fov(target)) { txt(i18n::s.get("core.magic.ink_attack", target)); } status_ailment_damage(target, StatusAilment::blinded, efp); return true; } // Item: potion of confusion bool _magic_1109(Character& target) { if (is_in_fov(target)) { txt(i18n::s.get("core.magic.confusion", target)); } status_ailment_damage(target, StatusAilment::confused, efp); return true; } // Item: potion of paralysis bool _magic_1110(Character& target) { if (is_in_fov(target)) { txt(i18n::s.get("core.magic.paralysis", target)); } status_ailment_damage(target, StatusAilment::paralyzed, efp); return true; } // Item: sleeping drug bool _magic_1112(Character& target) { if (is_in_fov(target)) { txt(i18n::s.get("core.magic.sleep", target)); } status_ailment_damage(target, StatusAilment::sleep, efp); return true; } // Curse / Item: scroll of curse bool _magic_645_1114(Character& subject, Character& target) { if (efid == 645) { if (is_in_fov(target)) { txt(i18n::s.get("core.magic.curse.spell", subject, target)); } } int p = 75 + target.skills().level("core.stat_luck"); if (const auto anticurse = enchantment_find(target, 43)) { p += *anticurse / 2; } if (rnd_capped(p) > efp / 2 + (is_cursed(efstatus)) * 100) { return true; } if (target.is_player_or_ally()) { if (rnd(3)) { if (cdata.player().traits().level("core.exorcist")) { txt(i18n::s.get("core.magic.curse.no_effect")); return true; } } } std::vector<ItemRef> candidates; for (const auto& body_part : target.body_parts) { if (!body_part.is_equip()) { continue; } if (body_part.equipment()->curse_state == CurseState::blessed) { if (rnd(10)) { continue; } } candidates.emplace_back(body_part.equipment().unwrap()); } if (candidates.empty()) { for (int _i = 0; _i < 200; ++_i) { const auto inv = target.inventory(); const auto item = inv->at(inv_get_random_slot(inv)); if (!item) { continue; } if (item->curse_state == CurseState::blessed) { if (rnd(10)) { continue; } } candidates.emplace_back(item.unwrap()); break; } } if (!candidates.empty()) { const auto cursed_item = choice(candidates); const auto original_item_name = itemname(cursed_item, 1, false); if (cursed_item->curse_state == CurseState::cursed) { cursed_item->curse_state = CurseState::doomed; } else { cursed_item->curse_state = CurseState::cursed; } if (is_in_fov(target)) { txt(i18n::s.get( "core.magic.curse.apply", target, original_item_name)); } chara_refresh(target); snd("core.curse3"); animeload(14, target); inv_stack(target.inventory(), cursed_item, true); } else { txt(i18n::s.get("core.common.nothing_happens")); obvious = 0; } return true; } // Weaken resistance bool _magic_1118(Character& target) { f = 0; for (int cnt = 0; cnt < 10; ++cnt) { p = rnd(11) + 50; if (target.skills().base_level(*the_skill_db.get_id_from_integer(p)) >= 150) { ++f; chara_gain_registance(target, p, 50 * -1); if (f >= efp / 100) { break; } } } if (f == 0) { txt(i18n::s.get("core.magic.weaken_resistance.nothing_happens")); obvious = 0; } else { snd("core.curse1"); } chara_refresh(target); return true; } // Item: diary of cat sister / diary of younger sister / scroll of ally / diary // of young lady bool _magic_1138_1123_1122_1137(Character& subject) { if (subject.is_ally()) { txt(i18n::s.get("core.common.nothing_happens")); return true; } flt(cdata.player().level / 2 + 5, Quality::great); data::InstanceId chara_id = ""; if (rnd(3) == 0) { fltn("man"s); } if (efid == 1138) { txt(i18n::s.get("core.magic.diary.cat_sister")); chara_id = "core.younger_cat_sister"; } else if (efid == 1123) { txt(i18n::s.get("core.magic.diary.younger_sister")); chara_id = "core.younger_sister"; } else if (efid == 1137) { txt(i18n::s.get("core.magic.diary.young_lady")); chara_id = "core.young_lady"; } novoidlv = 1; chara_create(56, chara_id, -3, 0); new_ally_joins(cdata.tmp()); return true; } // Dominate bool _magic_435(Character& subject, Character& target) { if (!subject.is_player() || target.is_player() || target.relationship == Relationship::ally) { txt(i18n::s.get("core.common.nothing_happens")); obvious = 0; return true; } if (map_prevents_domination()) { obvious = 0; txt(i18n::s.get("core.magic.domination.does_not_work_in_area")); return true; } f = 1; { if (itemfind(subject.inventory(), "core.monster_heart")) { efp = efp * 3 / 2; } } if (rnd_capped(efp / 15 + 5) < target.level) { f = 0; } if (target.quality >= Quality::miracle || target.role != Role::none || target.is_lord_of_dungeon() == 1) { f = -1; } if (f == 1) { new_ally_joins(target); quest_check(); } else if (f == 0) { txt(i18n::s.get("core.magic.common.resists", target)); } else { txt(i18n::s.get("core.magic.domination.cannot_be_charmed", target)); } return true; } // Web / Mist of Darkness / Acid Ground / Ether Ground / Fire Wall bool _magic_436_437_455_634_456(Character& subject) { if (efid == 436) { p(0) = 3; p(1) = 2 + rnd_capped(efp / 50 + 1); txt(i18n::s.get("core.magic.map_effect.web")); } if (efid == 437) { txt(i18n::s.get("core.magic.map_effect.fog")); p(0) = 3; p(1) = 2 + rnd_capped(efp / 50 + 1); } if (efid == 455) { txt(i18n::s.get("core.magic.map_effect.acid")); p(0) = 2; p(1) = 2 + rnd_capped(efp / 50 + 1); } if (efid == 456) { txt(i18n::s.get("core.magic.map_effect.fire")); p(0) = 2; p(1) = 2 + rnd_capped(efp / 50 + 1); } if (efid == 634) { txt(i18n::s.get("core.magic.map_effect.ether_mist")); p(0) = 2; p(1) = 1 + rnd_capped(efp / 100 + 2); } snd("core.web"); for (int cnt = 0, cnt_end = (p(1)); cnt < cnt_end; ++cnt) { x = rnd(p(0)) + tlocx - rnd(p(0)); y = rnd(p(0)) + tlocy - rnd(p(0)); f = 1; if (x < 0 || y < 0 || x >= map_data.width || y >= map_data.height) { f = 0; } else if (chip_data.for_cell(x, y).effect & 4) { f = 0; } if (dist(tlocx, tlocy, x, y) >= p) { f = 0; } if (f == 0) { if (rnd(2) == 0) { continue; } else { --cnt; continue; } } if (efid == 634) { mef_add(x, y, 4, 20, rnd(4) + 2, efp, subject.index); } if (efid == 455) { mef_add(x, y, 3, 19, rnd(10) + 5, efp, subject.index); } if (efid == 456) { mef_add(x, y, 5, 24, rnd(10) + 5, efp, subject.index); mapitem_fire(subject, x, y); } if (efid == 436) { mef_add(x, y, 1, 11, -1, efp * 2); } if (efid == 437) { mef_add(x, y, 2, 30, 8 + rnd_capped(15 + efp / 25), efp); } } return true; } // Item: scroll of name bool _magic_1145(Character& subject) { if (!subject.is_player()) { txt(i18n::s.get("core.common.nothing_happens")); obvious = 0; return true; } invsubroutine = 1; invctrl(0) = 23; invctrl(1) = 0; snd("core.inv"); const auto& [menu_result, target_item_opt] = ctrl_inventory(); if (!menu_result.succeeded || target_item_opt->quality < Quality::miracle || target_item_opt->quality == Quality::special) { txt(i18n::s.get("core.common.it_is_impossible")); obvious = 0; return true; } assert(target_item_opt); const auto target_item = target_item_opt.unwrap(); txt(i18n::s.get("core.magic.name.prompt")); const auto result = select_alias(RandomTitleType::living_weapon); if (!result) { obvious = 0; randomize(); return true; } target_item->subname = result->seed + 40000; randomize(); txt(i18n::s.get("core.magic.name.apply", result->alias)); return true; } // Item: Garok's hammer bool _magic_49(Character& subject, const ItemRef& hammer) { if (!subject.is_player()) { txt(i18n::s.get("core.common.nothing_happens")); obvious = 0; return true; } invsubroutine = 1; invctrl(0) = 23; invctrl(1) = 7; snd("core.inv"); const auto& [menu_result, target_item_opt] = ctrl_inventory(); if (!menu_result.succeeded) { return true; } assert(target_item_opt); const auto target_item = target_item_opt.unwrap(); if (target_item->quality >= Quality::miracle || target_item->is_alive) { txt(i18n::s.get("core.magic.garoks_hammer.no_effect")); fixmaterial = 0; objfix = 0; return true; } randomize(hammer->param1); animeload(8, subject); target_item->quality = Quality::miracle; change_item_material(target_item, target_item->material); randomize(hammer->param1); target_item->subname = 40000 + rnd(30000); p = rnd(rnd(rnd(10) + 1) + 3) + 3; egolv = rnd(clamp(rnd(6), 0, 4) + 1); for (int cnt = 0, cnt_end = (p); cnt < cnt_end; ++cnt) { randomize(hammer->param1); enchantment_add( target_item, enchantment_generate(enchantment_gen_level(egolv)), enchantment_gen_p() + (fixlv == Quality::godly) * 100 + (target_item->is_eternal_force) * 100, 20 - (fixlv == Quality::godly) * 10 - (target_item->is_eternal_force) * 20); } randomize(); txt(i18n::s.get("core.magic.garoks_hammer.apply", target_item)); chara_refresh(subject); fixmaterial = 0; objfix = 0; hammer->modify_number(-1); save_trigger_autosaving(); return true; } // Item: scroll of change material bool _magic_21_1127(Character& subject) { if (!subject.is_player()) { txt(i18n::s.get("core.common.nothing_happens")); obvious = 0; return true; } invsubroutine = 1; invctrl(0) = 23; invctrl(1) = 0; snd("core.inv"); const auto& [menu_result, target_item_opt] = ctrl_inventory(); f = menu_result.succeeded ? 1 : 0; if (f) { if (target_item_opt->quality == Quality::godly || target_item_opt->is_alive) { if (efid == 1127) { f = 0; } } } if (f == 1) { assert(target_item_opt); const auto target_item = target_item_opt.unwrap(); if (target_item->quality == Quality::special) { const auto equipped_slot_save = target_item->_equipped_slot; if (efp < 350) { txt(i18n::s.get( "core.magic.change_material.more_power_needed")); return true; } animeload(8, subject); txt(i18n::s.get( "core.magic.change_material.artifact_reconstructed", subject, target_item)); target_item->modify_number(-1); flt(); const auto reconstructed_artifact = itemcreate_player_inv( the_item_db[target_item->id]->integer_id, 0); assert(reconstructed_artifact); if (!equipped_slot_save.is_nil()) { subject.body_parts[equipped_slot_save].equip( reconstructed_artifact.unwrap()); reconstructed_artifact->_equipped_slot = equipped_slot_save; } } else { int material = fixmaterial; animeload(8, subject); if (efp <= 50) { if (rnd(3) == 0) { material = 35; } } s = itemname(target_item, 1, false); objlv = efp / 10; objfix = efp / 100; randomize(); change_item_material( target_item, material == 0 ? data::InstanceId{} : *the_item_material_db.get_id_from_integer(material)); txt(i18n::s.get( "core.magic.change_material.apply", subject, s(0), target_item)); } } else { txt(i18n::s.get("core.common.nothing_happens")); obvious = 0; } chara_refresh(subject); fixmaterial = 0; objfix = 0; return true; } // Item: deed of inheritance bool _magic_1128(Character& subject) { if (!subject.is_player()) { txt(i18n::s.get("core.common.nothing_happens")); obvious = 0; return true; } snd("core.ding2"); p = rnd_capped(efp + 1) / 100 + 1; game()->inheritance_rights += p; txt(i18n::s.get("core.magic.deed_of_inheritance.claim", p(0)), Message::color{ColorIndex::orange}); txt(i18n::s.get( "core.magic.deed_of_inheritance.can_now_inherit", game()->inheritance_rights)); return true; } // Item: scroll of enchant weapon / armor bool _magic_1124_1125(Character& subject) { if (!subject.is_player()) { txt(i18n::s.get("core.common.nothing_happens")); return true; } invsubroutine = 1; if (efid == 1124) { invctrl(0) = 23; invctrl(1) = 1; } else { invctrl(0) = 23; invctrl(1) = 2; } snd("core.inv"); const auto& [menu_result, target_item_opt] = ctrl_inventory(); if (menu_result.succeeded) { assert(target_item_opt); const auto target_item = target_item_opt.unwrap(); if (target_item->bonus_value < efp / 100) { snd("core.ding2"); txt(i18n::s.get("core.magic.enchant.apply", target_item)); ++target_item->bonus_value; } else { txt(i18n::s.get("core.magic.enchant.resist", target_item)); } chara_refresh(subject); } else { obvious = 0; } return true; } // Fill Charge / Item: scroll of charge bool _magic_630_1129(Character& subject) { if (!subject.is_player()) { txt(i18n::s.get("core.common.nothing_happens")); obvious = 0; return true; } if (efid == 630) { if (game()->charge_power < 10) { txt(i18n::s.get("core.magic.fill_charge.more_power_needed")); return true; } game()->charge_power -= 10; txt(i18n::s.get("core.magic.fill_charge.spend", game()->charge_power)); } invsubroutine = 1; invctrl(0) = 23; invctrl(1) = 3; snd("core.inv"); const auto& [menu_result, target_item_opt] = ctrl_inventory(); if (menu_result.succeeded) { assert(target_item_opt); const auto target_item = target_item_opt.unwrap(); const auto max_charges = lua::get_data("core.item", target_item->id) ->optional_or<lua_int>("max_charges", 0); if (max_charges < 1 || target_item->id == "core.rod_of_wishing" || target_item->id == "core.rod_of_domination" || target_item->id == "core.spellbook_of_wishing" || target_item->id == "core.spellbook_of_harvest" || (target_item->id == "core.ancient_book" && target_item->param2 != 0)) { txt(i18n::s.get("core.magic.fill_charge.cannot_recharge")); return true; } f = 1; if (target_item->charges > max_charges) { f = -1; } if (f == -1) { txt(i18n::s.get( "core.magic.fill_charge.cannot_recharge_anymore", target_item)); return true; } if (rnd_capped(efp / 25 + 1) == 0) { f = 0; } if (the_item_db[target_item->id]->category == ItemCategory::spellbook) { if (rnd(4) == 0) { f = 0; } } if (rnd(max_charges * max_charges + 1) == 0) { f = 0; } if (f == 1) { p = 1 + rnd(max_charges / 2 + 1); if (p + target_item->charges > max_charges) { p = max_charges - target_item->charges + 1; } if (the_item_db[target_item->id]->category == ItemCategory::spellbook) { p = 1; } txt(i18n::s.get("core.magic.fill_charge.apply", target_item, p(0))); target_item->charges += p; animeload(8, subject); } else { if (rnd(4) == 0) { txt(i18n::s.get( "core.magic.fill_charge.explodes", target_item)); target_item->modify_number(-1); refresh_burden_state(); return true; } txt(i18n::s.get("core.magic.fill_charge.fail", target_item)); } } else { obvious = 0; } return true; } // Draw Charge bool _magic_629(Character& subject) { if (!subject.is_player()) { txt(i18n::s.get("core.common.nothing_happens")); obvious = 0; return true; } invsubroutine = 1; invctrl(0) = 23; invctrl(1) = 5; snd("core.inv"); const auto& [menu_result, target_item_opt] = ctrl_inventory(); if (menu_result.succeeded) { assert(target_item_opt); const auto target_item = target_item_opt.unwrap(); const auto max_charges = lua::get_data("core.item", target_item->id) ->optional_or<lua_int>("max_charges", 0); if (max_charges == 1) { p = 100; } else if (max_charges == 2) { p = 25; } else if (max_charges <= 4) { p = 5; } else if (max_charges <= 6) { p = 3; } else { p = 1; } animeload(8, subject); p = p * target_item->charges; game()->charge_power += p; txt(i18n::s.get( "core.magic.draw_charge", target_item, p(0), game()->charge_power)); target_item->remove(); refresh_burden_state(); } return true; } // Change bool _magic_628(Character& subject, Character& target) { if (target.is_player()) { txt(i18n::s.get("core.common.nothing_happens")); obvious = 0; return true; } f = 1; if (efp / 10 + 10 < target.level) { f = 0; } if (target.quality >= Quality::miracle || target.role != Role::none || target.is_escorted() == 1 || target.is_lord_of_dungeon() == 1) { f = -1; } if (target.is_global()) { f = 0; } if (f == 1) { animeload(8, target); txt(i18n::s.get("core.magic.change.apply", target)); flt(calcobjlv(target.level + 3), Quality::good); chara_create(56, "", -3, 0); chara_relocate(cdata.tmp(), target, CharaRelocationMode::change); target.enemy_id = subject.index; target.is_quest_target() = false; quest_check(); } else if (f == 0) { txt(i18n::s.get("core.magic.common.resists", target)); } else { txt(i18n::s.get("core.magic.change.cannot_be_changed", target)); } return true; } // Item: scroll of flying bool _magic_1140(Character& subject) { if (!subject.is_player()) { txt(i18n::s.get("core.common.nothing_happens")); obvious = 0; return true; } invsubroutine = 1; invctrl(0) = 23; invctrl(1) = 6; snd("core.inv"); const auto& [menu_result, target_item_opt] = ctrl_inventory(); if (menu_result.succeeded) { assert(target_item_opt); const auto target_item = target_item_opt.unwrap(); save_trigger_autosaving(); animeload(8, subject); if (!is_cursed(efstatus)) { if (target_item->weight > 0) { target_item->weight = clamp( target_item->weight * (100 - efp / 10) / 100, 1, target_item->weight); if (target_item->pv > 0) { target_item->pv -= target_item->pv / 10 + 1 + (efstatus != CurseState::blessed); } if (target_item->dice.bonus > 0) { target_item->dice.bonus -= target_item->dice.bonus / 10 + 1 + (efstatus != CurseState::blessed); } } txt(i18n::s.get("core.magic.flying.apply", target_item)); } else { target_item->weight = target_item->weight * 150 / 100 + 1000; if (target_item->pv > 0) { target_item->pv += clamp(target_item->pv / 10, 1, 5); } if (target_item->dice.bonus > 0) { target_item->dice.bonus += clamp(target_item->dice.bonus / 10, 1, 5); } txt(i18n::s.get("core.magic.flying.cursed", target_item)); } refresh_burden_state(); } else { txt(i18n::s.get("core.common.nothing_happens")); obvious = 0; } chara_refresh(subject); return true; } // Item: rod of alchemy bool _magic_1132(Character& subject, int& fltbk, int& valuebk) { if (!subject.is_player()) { txt(i18n::s.get("core.common.nothing_happens")); obvious = 0; return true; } invsubroutine = 1; invctrl(0) = 23; invctrl(1) = 4; snd("core.inv"); const auto& [menu_result, target_item_opt] = ctrl_inventory(); f = menu_result.succeeded ? 1 : 0; if (f) { assert(target_item_opt); if (target_item_opt->quality > Quality::miracle || target_item_opt->is_precious) { f = 0; } } if (f == 1) { assert(target_item_opt); const auto target_item = target_item_opt.unwrap(); save_trigger_autosaving(); animeload(8, subject); fltbk = (int)the_item_db[target_item->id]->category; valuebk = calcitemvalue(target_item, 0); target_item->remove(); for (int cnt = 0;; ++cnt) { flt(calcobjlv(efp / 10) + 5, calcfixlv(Quality::good)); if (cnt < 10) { flttypemajor = fltbk; } if (const auto item = itemcreate_player_inv(0, 0)) { if (item->value > valuebk * 3 / 2 + 1000) { item->remove(); continue; } else { txt(i18n::s.get("core.magic.alchemy", item.unwrap())); break; } } else { continue; } } refresh_burden_state(); } else { txt(i18n::s.get("core.common.nothing_happens")); obvious = 0; } return true; } // Door Creation / Wall Creation bool _magic_457_438() { x = tlocx; y = tlocy; f = 1; if (x < 0 || y < 0 || x >= map_data.width || y >= map_data.height) { f = 0; } else { if (chip_data.for_cell(x, y).effect & 4) { if (homemapmode == 0) { if (efid != 457) { f = 0; } else if (chip_data.for_cell(x, y).kind == 3) { f = 0; } } } if (cell_data.at(x, y).chara_index_plus_one != 0 || cell_data.at(x, y).feats != 0) { f = 0; } } if (f == 1) { if (efid == 438) { if (homemapmode == 0) { txt(i18n::s.get("core.magic.create.wall")); p = tile_wall; } else { p = tile; } if (cell_data.at(x, y).chip_id_actual != p) { snd("core.offer1"); } cell_data.at(x, y).chip_id_actual = p; cell_data.at(x, y).chip_id_memory = p; } if (efid == 457) { snd("core.offer1"); if (chip_data.for_cell(x, y).kind == 6) { txt(i18n::s.get("core.magic.create.door.resist")); return true; } txt(i18n::s.get("core.magic.create.door.apply")); cell_featset(x, y, tile_doorclosed, 21, rnd_capped(efp / 10 + 1)); if (chip_data.for_cell(x, y).effect & 4) { cell_data.at(x, y).chip_id_actual = tile_tunnel; } } } else { if (homemapmode == 0) { txt(i18n::s.get("core.common.nothing_happens")); } obvious = 0; } return true; } // Swarm bool _magic_631(Character& subject) { txt(i18n::s.get("core.magic.swarm"), Message::color{ColorIndex::blue}); for (auto&& cnt : cdata.all()) { if (subject.state() != Character::State::alive) { continue; } if (cnt.state() != Character::State::alive) { continue; } if (subject == cnt) { continue; } if (belong_to_same_team(subject, cnt)) { continue; } dx = cnt.position.x; dy = cnt.position.y; if (dist(subject.position, dx, dy) > the_skill_db[631]->range % 1000 + 1) { continue; } if (!fov_los(subject.position, {dx, dy})) { continue; } SwarmAnimation(cnt.position).play(); try_to_melee_attack(subject, cnt); } return true; } // Drop Mine bool _magic_659(Character& subject) { if (map_data.type == mdata_t::MapType::world_map) { return true; } if (cell_data.at(subject.position.x, subject.position.y).feats != 0) { return true; } cell_featset( subject.position.x, subject.position.y, 0, 14, 7, subject.index); if (is_in_fov(subject)) { txt(i18n::s.get("core.magic.drop_mine", subject)); } return true; } // Gravity bool _magic_466(Character& subject) { for (auto&& cnt : cdata.all()) { if (cnt.state() != Character::State::alive) { continue; } if (subject == cnt) { continue; } if (cnt.is_immune_to_mine()) { continue; } dx = cnt.position.x; dy = cnt.position.y; if (dist(subject.position, dx, dy) > 4) { continue; } if (is_in_fov(cnt)) { txt(i18n::s.get("core.magic.gravity", cnt)); } cnt.gravity += 100 + rnd(100); } return true; } // Mewmewmew! bool _magic_657(Character& subject) { txt(i18n::s.get("core.magic.mewmewmew"), Message::color{ColorIndex::blue}); MiracleAnimation(MiracleAnimation::Mode::target_all, subject).play(); for (auto&& cnt : cdata.all()) { if (subject.state() != Character::State::alive) { continue; } if (cnt.state() != Character::State::alive) { continue; } if (subject == cnt) { continue; } damage_hp(cnt, 9999999, subject.index); } return true; } // Meteor bool _magic_465(Character& subject) { txt(i18n::s.get("core.magic.meteor"), Message::color{ColorIndex::blue}); MeteorAnimation().play(); for (int cnt = 0, cnt_end = (map_data.height); cnt < cnt_end; ++cnt) { dy = cnt; for (int cnt = 0, cnt_end = (map_data.width); cnt < cnt_end; ++cnt) { dx = cnt; if (rnd(3) == 0) { cell_data.at(dx, dy).chip_id_actual = 12 + rnd(2); } if (rnd(40) == 0) { mef_add(dx, dy, 5, 24, rnd(4) + 3, 50); } if (cell_data.at(dx, dy).chara_index_plus_one != 0) { dmg = subject.skills().level("core.stat_magic") * efp / 10; damage_hp( cdata[cell_data.at(dx, dy).chara_index_plus_one - 1], dmg, subject.index, 50, 1000); } } } return true; } // Cheer bool _magic_656(Character& subject) { if (is_in_fov(subject)) { txt(i18n::s.get("core.magic.cheer.apply", subject)); } for (auto&& cnt : cdata.all()) { if (cnt.state() != Character::State::alive) { continue; } if (subject == cnt) { continue; } if (subject.is_player_or_ally()) { if (!cnt.is_player_or_ally()) { continue; } else if (subject.relationship != cnt.relationship) { continue; } } dx = cnt.position.x; dy = cnt.position.y; if (dist(subject.position, dx, dy) > the_skill_db[656]->range % 1000 + 1) { continue; } if (!fov_los(subject.position, {dx, dy})) { continue; } if (is_in_fov(cnt)) { txt(i18n::s.get("core.magic.cheer.is_excited", cnt), Message::color{ColorIndex::blue}); } buff_add( cnt, "core.speed", subject.skills().level("core.stat_charisma") * 5 + 50, 15, subject); buff_add( cnt, "core.hero", subject.skills().level("core.stat_charisma") * 5 + 100, 60, subject); buff_add(cnt, "core.contingency", 1500, 30, subject); } return true; } // Item: potion of cure corruption bool _magic_1131(Character& target) { if (!target.is_player()) { txt(i18n::s.get("core.common.nothing_happens")); return true; } snd("core.pray1"); if (!is_cursed(efstatus)) { txt(i18n::s.get("core.magic.cure_corruption.apply"), Message::color{ColorIndex::green}); trait_progress_ether_disease_stage(target, efp * -10); } else { txt(i18n::s.get("core.magic.cure_corruption.cursed"), Message::color{ColorIndex::purple}); trait_progress_ether_disease_stage(target, 200); } return true; } // Eye of Ether bool _magic_633(Character& subject, Character& target) { if (!target.is_player()) { return true; } txt(i18n::s.get("core.magic.eye_of_ether", subject), Message::color{ColorIndex::purple}); trait_progress_ether_disease_stage(target, 100); return true; } // Eye of Dimness bool _magic_638_648(Character& subject, Character& target) { if (efid == 648) { if (is_in_fov(target)) { txt(i18n::s.get("core.magic.insult.apply", subject, target)); if (subject.sex == 0) { txt(i18n::s.get("core.magic.insult.man"), Message::color{ColorIndex::cyan}); } else { txt(i18n::s.get("core.magic.insult.woman"), Message::color{ColorIndex::cyan}); } } } if (efid == 638) { if (is_in_fov(target)) { txt(i18n::s.get("core.magic.gaze", subject, target)); } } status_ailment_damage(target, StatusAilment::dimmed, 200); return true; } // Insult bool _magic_652(Character& subject, Character& target) { if (is_in_fov(target)) { txt(i18n::s.get("core.magic.gaze", subject, target)); } damage_mp(target, rnd(20) + 1); return true; } // Item: molotov bool _magic_1133(Character& subject, Character& target) { if (is_in_fov(target)) { txt(i18n::s.get("core.magic.molotov", target)); } mef_add( target.position.x, target.position.y, 5, 24, rnd(15) + 25, efp, subject.index); mapitem_fire(subject, target.position.x, target.position.y); return true; } // Scavenge bool _magic_651(Character& subject, Character& target) { if (is_in_fov(target)) { txt(i18n::s.get("core.magic.scavenge.apply", subject, target)); } OptionalItemRef eat_item_opt; for (const auto& item : *target.inventory()) { if (item->id == "core.fish_a") { eat_item_opt = item; break; } } if (!eat_item_opt) { for (const auto& item : *target.inventory()) { if (item->is_precious) { continue; } if (the_item_db[item->id]->category != ItemCategory::food) { continue; } eat_item_opt = item; break; } } if (!eat_item_opt) { return true; } const auto eat_item = eat_item_opt.unwrap(); if (eat_item->is_aphrodisiac) { if (is_in_fov(target)) { txt(i18n::s.get("core.magic.scavenge.rotten", subject, eat_item)); } return true; } rowact_item(eat_item); if (is_in_fov(target)) { snd("core.eat1"); txt(i18n::s.get("core.magic.scavenge.eats", subject, eat_item)); } heal_hp(subject, subject.max_hp / 3); activity_eating_finish(subject, eat_item); refresh_burden_state(); return true; } // Wizard's Harvest bool _magic_464(Character& subject, Character& target) { bool fastest = g_config.animation_wait() == 0; std::string messages; animeload(10, target); for (int i = 0, n = clamp(4 + rnd_capped(efp / 50 + 1), 1, 15); i < n; ++i) { snd("core.pray1"); flt(calcobjlv(efp / 10), calcfixlv(Quality::good)); int item_id = 54; int number = 400 + rnd_capped(efp); if (rnd(30) == 0) { item_id = 55; number = 1; } if (rnd(80) == 0) { item_id = 622; number = 1; } if (rnd(2000) == 0) { item_id = 290; number = 1; } nostack = 1; if (const auto item = itemcreate_map_inv(item_id, subject.position, number)) { const auto message = i18n::s.get("core.magic.wizards_harvest", item.unwrap()); if (fastest) { messages += message; } else { txt(message); await(g_config.animation_wait() * 4); redraw(); } } } if (fastest) { txt(messages); redraw(); } return true; } // 4-Dimentional Pocket bool _magic_463() { const auto pocket_file_name = fs::u8path("shop8.s2"); snd("core.teleport1"); txt(i18n::s.get("core.magic.four_dimensional_pocket")); inv_open_tmp_inv(pocket_file_name); shoptrade = 0; menucycle = 1; invsubroutine = 1; invctrl(0) = 22; invctrl(1) = 5; invcontainer = clamp(efp / 10 + 10, 10, 300); g_mode = 6; snd("core.inv"); ctrl_inventory(); invcontainer = 0; inv_close_tmp_inv(pocket_file_name); g_mode = 0; return true; } int _calc_ball_spell_range(Character& subject) { (void)subject; int ret = the_skill_db[efid]->range % 1000 + 1; if (efid == 644) { ret = 2; } return ret; } optional_ref<Character> _ball_spell_internal( Character& subject, std::stack<Character*>& bomb_chain) { subject.will_explode_soon() = false; range_ = _calc_ball_spell_range(subject); if (efid != 404 && efid != 637) { BallAnimation({tlocx, tlocy}, range_, BallAnimation::Type::ball, ele) .play(); } for (int dy_ = 0; dy_ < range_ * 2 + 1; ++dy_) { dy = tlocy - range_ + dy_; if (dy < 0 || map_data.height <= dy) { continue; } for (int dx_ = 0; dx_ < range_ * 2 + 1; ++dx_) { dx = tlocx - range_ + dx_; if (dx < 0 || map_data.width <= dx) { continue; } if (dist(tlocx, tlocy, dx, dy) > range_) { continue; } if (!fov_los({tlocx, tlocy}, {dx, dy})) { continue; } if (cell_data.at(dx, dy).chara_index_plus_one == 0) { continue; } const auto target_index = cell_data.at(dx, dy).chara_index_plus_one - 1; if (efid == 404) { f = 0; if (subject.is_player() || subject.relationship >= Relationship::friendly) { if (cdata[target_index].relationship >= Relationship::friendly) { f = 1; } } else if ( cdata[target_index].relationship <= Relationship::neutral) { f = 1; } if (f) { BrightAuraAnimation( cdata[target_index].position, BrightAuraAnimation::Type::healing_rain) .play(); if (is_in_fov(cdata[target_index])) { txt(i18n::s.get( "core.magic.healed.normal", cdata[target_index])); } heal_both_rider_and_mount(cdata[target_index]); } continue; } if (efid == 637) { f = 0; if (subject.is_player() || subject.relationship >= Relationship::friendly) { if (cdata[target_index].relationship >= Relationship::friendly) { f = 1; } } else if ( cdata[target_index].relationship <= Relationship::neutral) { f = 1; } if (f) { BrightAuraAnimation( cdata[target_index].position, BrightAuraAnimation::Type::healing_rain) .play(); txt(i18n::s.get( "core.magic.rain_of_sanity", cdata[target_index])); heal_insanity(cdata[target_index], efp / 10); status_ailment_heal( cdata[target_index], StatusAilment::insane, 9999); } continue; } if (dx == subject.position.x && dy == subject.position.y) { continue; } if (game()->mount != 0) { if (game()->mount == subject.index) { if (target_index == 0) { continue; } } } if (ele == 50) { mapitem_fire(subject, dx, dy); } if (ele == 51) { mapitem_cold(dx, dy); } if (subject.index == target_index) { continue; } dmg = roll(dice1, dice2, bonus) * 100 / (75 + dist(tlocx, tlocy, dx, dy) * 25); if (calc_magic_control(subject, cdata[target_index])) { continue; } if (efid == 644) { if (is_in_fov(cdata[target_index])) { if (target_index >= 16) { g_proc_damage_events_flag = 2; txt3rd = 1; txt(i18n::s.get( "core.magic.explosion.other", cdata[target_index])); } else { txt(i18n::s.get( "core.magic.explosion.ally", cdata[target_index])); } } if (cdata[target_index].explodes()) { bomb_chain.push(&cdata[target_index]); continue; } } else if (is_in_fov(cdata[target_index])) { if (target_index >= 16) { g_proc_damage_events_flag = 2; txt3rd = 1; txt(i18n::s.get( "core.magic.ball.other", cdata[target_index])); } else { txt(i18n::s.get( "core.magic.ball.ally", cdata[target_index])); } } damage_hp(cdata[target_index], dmg, subject.index, ele, elep); } } if (efid == 644) { damage_hp(subject, 99999, -16); } if (!bomb_chain.empty()) { auto& next_subject = *bomb_chain.top(); bomb_chain.pop(); tlocx = next_subject.position.x; tlocy = next_subject.position.y; if (next_subject.state() == Character::State::alive) { const auto damage = calc_skill_damage(next_subject, efid, efp); dice1 = damage->dice_x; dice2 = damage->dice_y; bonus = damage->damage_bonus; ele = damage->element; elep = damage->element_power; if (is_in_fov(next_subject)) { txt(i18n::s.get("core.magic.explosion.chain", next_subject)); } return next_subject; } } return none; } void _ball_spell(Character& subject) { std::stack<Character*> bomb_chain; if (efid == 644) { if (is_in_fov(subject)) { txt(i18n::s.get("core.magic.explosion.begins", subject)); } } optional_ref<Character> subject_ = subject; while (subject_) { subject_ = _ball_spell_internal(*subject_, bomb_chain); } } void proc_bolt(Character& subject, Character& target) { (void)target; const auto route = fov_get_route(subject.position, Position{tlocx, tlocy}); if (route.empty()) { return; } { int distance = the_skill_db[efid]->range % 1000 + 1; BoltAnimation(subject.position, {tlocx, tlocy}, ele, distance, route) .play(); } dx = subject.position.x; dy = subject.position.y; for (int cnt = 0; cnt < 20; ++cnt) { const auto route_result = route_info(dx, dy, cnt, route); if (route_result == RouteInfo::stop) { break; } else if (route_result == RouteInfo::skip) { continue; } if (dist(dx, dy, subject.position) > the_skill_db[efid]->range % 1000 + 1) { break; } if (dx == subject.position.x && dy == subject.position.y) { continue; } if (ele == 50) { mapitem_fire(subject, dx, dy); } if (ele == 51) { mapitem_cold(dx, dy); } if (cell_data.at(dx, dy).chara_index_plus_one != 0) { const auto target_index = cell_data.at(dx, dy).chara_index_plus_one - 1; if (subject.index != target_index) { if (game()->mount != 0) { if (game()->mount == subject.index) { if (target_index == 0) { continue; } } } dmg = roll(dice1, dice2, bonus); if (calc_magic_control(subject, cdata[target_index])) { continue; } if (is_in_fov(cdata[target_index])) { if (target_index >= 16) { g_proc_damage_events_flag = 2; txt3rd = 1; txt(i18n::s.get( "core.magic.bolt.other", cdata[target_index])); } else { txt(i18n::s.get( "core.magic.bolt.ally", cdata[target_index])); } } damage_hp(cdata[target_index], dmg, subject.index, ele, elep); } } } } void proc_breath(Character& subject, Character& target) { (void)target; const auto route = fov_get_route(subject.position, Position{tlocx, tlocy}); if (route.empty()) { return; } std::string valn; if (ele) { valn = i18n::s.get( "core.magic.breath.named", the_skill_db.get_text(ele, "name")); } else { valn = i18n::s.get("core.magic.breath.no_element"); } if (is_in_fov(subject)) { txt(i18n::s.get("core.magic.breath.bellows", subject, valn)); } const auto breath_route = fov_get_breath_route( subject.position, the_skill_db[efid]->range % 1000 + 1, route); BreathAnimation(subject.position, {tlocx, tlocy}, breath_route, ele).play(); for (const auto pos : breath_route) { const auto [dx, dy] = pos; if (!fov_los(subject.position, pos)) { continue; } if (pos == subject.position) { continue; } if (ele == 50) { mapitem_fire(subject, dx, dy); } if (ele == 51) { mapitem_cold(dx, dy); } if (cell_data.at(dx, dy).chara_index_plus_one != 0) { const auto target_index = cell_data.at(dx, dy).chara_index_plus_one - 1; if (subject.index != target_index) { dmg = roll(dice1, dice2, bonus); if (is_in_fov(cdata[target_index])) { if (target_index >= 16) { g_proc_damage_events_flag = 2; txt3rd = 1; txt(i18n::s.get( "core.magic.breath.other", cdata[target_index])); } else { txt(i18n::s.get( "core.magic.breath.ally", cdata[target_index])); } } damage_hp(cdata[target_index], dmg, subject.index, ele, elep); } } } } optional<bool> _proc_general_magic(Character& subject, Character& target) { int efbad = 0; int telex = 0; int teley = 0; int efidprev = 0; f = 0; if (the_skill_db[efid]->ability_type / 1000 == 1) { f = 1; p = the_skill_db[efid]->ability_type % 1000; if (the_buff_db[p]->type == BuffType::hex) { efbad = 1; } } if (the_skill_db[efid]->ability_type == 7) { efbad = 1; } if (efbad == 0) { if (efstatus == CurseState::blessed) { efp = efp * 150 / 100; } if (is_cursed(efstatus)) { efp = 50; } } else { if (efstatus == CurseState::blessed) { efp = 50; } if (is_cursed(efstatus)) { efp = efp * 150 / 100; } } if (f) { const auto& buff_data = the_buff_db.ensure(p); if (buff_data.type == BuffType::buff) { animeload(11, target); } else if (buff_data.type == BuffType::hex) { BrightAuraAnimation( target.position, BrightAuraAnimation::Type::debuff) .play(); } std::reference_wrapper<Character> target_ref = target; if (efid == 625 || efid == 446) { if ((target.is_player() && subject.is_player()) || subject.index == game()->mount) { if (game()->mount != 0) { target_ref = cdata[game()->mount]; } } } Character& target_ = target_ref.get(); buff_add( target_, buff_data.id, efp, buff_calc_duration(buff_data.id, efp), subject); if (efid == 447) { if (efstatus == CurseState::blessed) { { const auto this_year = game_date().year(); const auto youngest_age = 12; const auto y = target_.birthday.year(); const auto m = target_.birthday.month(); const auto d = target_.birthday.day(); const auto new_y = std::min(y + rnd(3) + 1, this_year - youngest_age); target_.birthday = time::Date{new_y, m, d}; } if (is_in_fov(target_)) { txt(i18n::s.get("core.magic.slow", target_), Message::color{ColorIndex::green}); } } } if (efid == 446) { if (is_cursed(efstatus)) { { const auto y = target_.birthday.year(); const auto m = target_.birthday.month(); const auto d = target_.birthday.day(); const auto new_y = y - (rnd(3) + 1); target_.birthday = time::Date{new_y, m, d}; } if (is_in_fov(target_)) { txt(i18n::s.get("core.magic.speed", target_), Message::color{ColorIndex::purple}); } } } if (efid == 458) { if (target_.is_player()) { incognitobegin(); } } return true; } if (const auto damage = calc_skill_damage(subject, efid, efp)) { dice1 = damage->dice_x; dice2 = damage->dice_y; bonus = damage->damage_bonus; ele = damage->element; elep = damage->element_power; } if (subject.is_player()) { if (cdata.player().traits().level("core.itzpalt_blessing")) { if (ele == 50 || ele == 51 || ele == 52) { dice2 = dice2 * 125 / 100; } } } if (rapidmagic) { elep = elep * 4 / 5 + 1; dice1 = dice1 * 4 / 5 + 1; dice2 = dice2 * 4 / 5 + 1; bonus = bonus * 4 / 5 + 1; } switch (the_skill_db[efid]->ability_type) { default: return none; case 10: RangedAttackAnimation( subject.position, target.position, RangedAttackAnimation::Type::distant_attack) .play(); try_to_melee_attack(subject, target); return true; case 1: proc_bolt(subject, target); return true; case 3: _ball_spell(subject); return true; case 2: RangedAttackAnimation( subject.position, target.position, RangedAttackAnimation::Type::magic_arrow) .play(); dmg = roll(dice1, dice2, bonus); if (is_in_fov(target)) { if (!target.is_player_or_ally()) { g_proc_damage_events_flag = 2; txt3rd = 1; txt(i18n::s.get("core.magic.arrow.other", target)); } else { txt(i18n::s.get("core.magic.arrow.ally", target)); } } damage_hp(target, dmg, subject.index, ele, elep); return true; case 4: if (efid == 400) { if (is_in_fov(target)) { txt(i18n::s.get("core.magic.healed.slightly", target)); } } if (efid == 401 || efid == 405) { if (is_in_fov(target)) { txt(i18n::s.get("core.magic.healed.normal", target)); } } if (efid == 402) { if (is_in_fov(target)) { txt(i18n::s.get("core.magic.healed.greatly", target)); } } if (efid == 403) { if (is_in_fov(target)) { txt(i18n::s.get("core.magic.healed.completely", target)); } } heal_both_rider_and_mount(target); if (efstatus == CurseState::blessed) { status_ailment_heal(target, StatusAilment::sick, 5 + rnd(5)); } if (rnd(3) == 0) { get_sick_if_cursed(efstatus, target); } BrightAuraAnimation(target.position, BrightAuraAnimation::Type::healing) .play(); return true; case 6: if (subject.special_attack_type != 0) { if (is_in_fov(subject)) { if (subject.is_player()) { txt(i18n::s.get( "core.magic.special_attack.self", subject, the_skill_db.get_text(efid, "name"), i18n::s.get_enum( "core.ui.cast_style", subject.special_attack_type))); } else { txt(i18n::s.get( "core.magic.special_attack.other", subject, i18n::s.get_enum( "core.ui.cast_style", subject.special_attack_type))); } } } else if (efid == 601) { if (is_in_fov(subject)) { if (!target.is_player_or_ally()) { g_proc_damage_events_flag = 2; txt(i18n::s.get( "core.magic.sucks_blood.other", subject, target)); } else { txt(i18n::s.get( "core.magic.sucks_blood.ally", subject, target)); } } } else if (efid == 660) { if (is_in_fov(subject)) { txt(i18n::s.get("core.magic.disassembly")); } } else if (is_in_fov(subject)) { if (!target.is_player_or_ally()) { g_proc_damage_events_flag = 2; txt(i18n::s.get( "core.magic.touch.other", subject, target, elename(ele), _melee(2, subject.melee_attack_type), _melee(0, subject.melee_attack_type))); } else { txt(i18n::s.get( "core.magic.touch.ally", subject, target, elename(ele), _melee(2, subject.melee_attack_type), _melee(1, subject.melee_attack_type))); } } if (efid == 660) { target.hp = target.max_hp / 12 + 1; return true; } damage_hp(target, roll(dice1, dice2, bonus), subject.index, ele, elep); if (efid == 617) { status_ailment_damage(target, StatusAilment::fear, elep); } if (efid == 618) { status_ailment_damage(target, StatusAilment::sleep, elep); } if (efid == 614) { target.nutrition -= 800; if (is_in_fov(target)) { txt(i18n::s.get("core.magic.hunger", target), Message::color{ColorIndex::purple}); } get_hungry(target); } if (efid == 613) { p = rnd(10); if ((target.quality >= Quality::miracle && rnd(4)) || enchantment_find(target, 60010 + p)) { p = -1; } if (p != -1) { i = target.skills().base_level( *the_skill_db.get_id_from_integer(10 + p)) + target.attr_adjs[p]; if (i > 0) { i = i * efp / 2000 + 1; target.attr_adjs[p] -= i; } if (is_in_fov(target)) { txt(i18n::s.get("core.magic.weaken", target), Message::color{ColorIndex::purple}); } chara_refresh(target); } } return true; case 7: if (subject.is_player()) { if (game()->crowd_density + 100 >= ELONA_MAX_OTHER_CHARACTERS) { txt(i18n::s.get("core.common.nothing_happens")); obvious = 0; return true; } } p = 3; efp = (efp / 25 + efp * efp / 10000 + subject.level) / 2; if (efp < 1) { efp = 1; } if (efid == 641) { efp = 15 + rnd(8); } if (efid == 639) { efp = 2 + rnd(18); } if (efid == 642) { efp = 15 + rnd(15); } if (efid == 640) { efp = 5 + rnd(12); } if (efid == 643) { p = 10; } for (int cnt = 0, cnt_end = (1 + rnd(p(0))); cnt < cnt_end; ++cnt) { flt(calcobjlv(efp), Quality::good); data::InstanceId chara_id = ""; if (efid == 425) { fltn("wild"s); } if (efid == 642) { fltn("fire"s); } if (efid == 641) { fltn("pawn"s); } if (efid == 639) { fltn("cat"s); } if (efid == 640) { fltn("yeek"s); } if (efid == 643) { chara_id = "core.younger_sister"; } if (const auto chara = chara_create( -1, chara_id, target.position.x, target.position.y)) { if (efid != 643) { if (chara->id == subject.id) { chara_vanquish(*chara); --cnt; continue; } } } } if (is_in_fov(subject)) { txt(i18n::s.get("core.magic.summon")); } return true; case 5: { if (game()->mount != 0) { if (game()->mount == target.index) { return true; } } auto target_index = target.index; if (efid == 408) { target_index = subject.index; } if (efid == 619) { telex = cdata[target_index].position.x; teley = cdata[target_index].position.y; target_index = subject.index; if (game()->mount != 0 && game()->mount == target_index) { return true; } } if (efid == 620) { telex = subject.position.x; teley = subject.position.y; } if (efid == 409 || efid == 635) { if (cell_data.at(tlocx, tlocy).chara_index_plus_one == 0) { txt(i18n::s.get("core.common.nothing_happens")); obvious = 0; return true; } target_index = cell_data.at(tlocx, tlocy).chara_index_plus_one - 1; } if (map_prevents_teleport()) { if (is_in_fov(cdata[target_index])) { txt(i18n::s.get("core.magic.teleport.prevented")); } return true; } if (efid != 619 && efid != 635 && enchantment_find(cdata[target_index], 22)) { if (is_in_fov(cdata[target_index])) { txt(i18n::s.get("core.magic.teleport.prevented")); } return true; } if (efid == 635) { if (enchantment_find(subject, 22)) { if (is_in_fov(cdata[target_index])) { txt(i18n::s.get("core.magic.teleport.prevented")); } return true; } p = rnd_capped(cdata[target_index].gold / 10 + 1); if (rnd_capped(cdata[target_index].skills().level( "core.stat_perception")) > rnd_capped( subject.skills().level("core.stat_dexterity") * 4) || cdata[target_index].is_protected_from_thieves() == 1) { txt(i18n::s.get( "core.magic.teleport.suspicious_hand.prevented", cdata[target_index])); p = 0; } if (p != 0) { snd("core.paygold1"); cdata[target_index].gold -= p; txt(i18n::s.get( "core.magic.teleport.suspicious_hand.succeeded", subject, cdata[target_index], p(0))); earn_gold(subject, p); } target_index = subject.index; if (game()->mount != 0) { if (game()->mount == target_index) { return true; } } } if (is_in_fov(cdata[target_index])) { snd_at("core.teleport1", cdata[target_index].position); } tx = cdata[target_index].position.x; ty = cdata[target_index].position.y; efidprev = efid; for (int cnt = 0; cnt < 200; ++cnt) { if (efidprev == 410 || efidprev == 627) { p(0) = -1; p(1) = 1; cdata[target_index].next_position.x = cdata[target_index].position.x + (3 - cnt / 70 + rnd(5)) * p(rnd(2)); cdata[target_index].next_position.y = cdata[target_index].position.y + (3 - cnt / 70 + rnd(5)) * p(rnd(2)); } else if (efidprev == 619) { cdata[target_index].next_position.x = telex + rnd((cnt / 8 + 2)) - rnd((cnt / 8 + 2)); cdata[target_index].next_position.y = teley + rnd((cnt / 8 + 2)) - rnd((cnt / 8 + 2)); } else if (efidprev == 620) { cdata[target_index].next_position.x = telex + rnd((cnt / 8 + 2)) - rnd((cnt / 8 + 2)); cdata[target_index].next_position.y = teley + rnd((cnt / 8 + 2)) - rnd((cnt / 8 + 2)); } else { cdata[target_index].next_position.x = rnd(map_data.width - 2) + 1; cdata[target_index].next_position.y = rnd(map_data.height - 2) + 1; } cell_check( cdata[target_index].next_position.x, cdata[target_index].next_position.y); if (cellaccess == 1) { if (efidprev == 619) { if (is_in_fov(subject)) { txt(i18n::s.get( "core.magic.teleport.shadow_step", subject, target)); } } else if (efidprev == 620) { if (is_in_fov(subject)) { txt(i18n::s.get( "core.magic.teleport.draw_shadow", cdata[target_index])); } } else if (is_in_fov(subject)) { if (efidprev == 635) { txt(i18n::s.get( "core.magic.teleport.suspicious_hand.after")); } else { txt(i18n::s.get( "core.magic.teleport.disappears", cdata[target_index])); } } subject.activity.finish(); move_character(cdata[target_index]); if (target_index == 0) { update_screen(); } break; } } return true; } case 8: proc_breath(subject, target); return true; } } bool _proc_magic( Character& subject, Character& target, const OptionalItemRef& efitem, int efid, int& fltbk, int& valuebk) { switch (efid) { case 636: return _magic_636(subject, target); case 1136: assert(efitem); return _magic_1136(efitem.unwrap()); case 1135: return _magic_1135(target); case 654: return _magic_654(subject, target); case 626: return _magic_626(target); case 1101: return _magic_1101(subject, target); case 1102: return _magic_1102(target); case 1116: return _magic_1116(target); case 1103: return _magic_1103(target); case 1146: return _magic_1146(target); case 1147: return _magic_1147(target); case 1142: return _magic_1142(target); case 1130: return _magic_1130(target); case 300: return _magic_300(subject, target); case 301: return _magic_301(subject, target); case 183: return _magic_183(subject, efitem); case 184: assert(efitem); return _magic_184(subject, efitem.unwrap()); case 185: assert(efitem); return _magic_185(subject, efitem.unwrap()); case 406: case 407: return _magic_406_407(subject, target); case 1120: return _magic_1120(target); case 1117: return _magic_1117(target); case 632: case 454: case 1144: return _magic_632_454_1144(subject, target); case 1121: return _magic_1121(subject, target); case 411: return _magic_411(subject); case 461: return _magic_461(subject); case 412: return _magic_412(subject, target); case 413: return _magic_413(target); case 1104: return _magic_1104(target); case 1143: return _magic_1143(target); case 1105: return _magic_1105(target); case 1107: return _magic_1107(target); case 1119: return _magic_1119(target); case 1106: return _magic_1106(target); case 1139: return _magic_1139(target); case 1113: return _magic_1113(target); case 653: return _magic_653(target); case 430: case 429: return _magic_430_429(target); case 658: return _magic_658(subject, target); case 440: case 439: return _magic_440_439(target); case 441: return _magic_441(subject); case 1141: return _magic_1141(target); case 428: return _magic_428(target); case 621: return _magic_621(target); case 624: return _magic_624(target); case 1108: return _magic_1108(target); case 1111: return _magic_1111(target); case 1109: return _magic_1109(target); case 1110: return _magic_1110(target); case 1112: return _magic_1112(target); case 645: case 1114: return _magic_645_1114(subject, target); case 1118: return _magic_1118(target); case 1138: case 1123: case 1122: case 1137: return _magic_1138_1123_1122_1137(subject); case 435: return _magic_435(subject, target); case 436: case 437: case 455: case 634: case 456: return _magic_436_437_455_634_456(subject); case 1145: return _magic_1145(subject); case 49: assert(efitem); return _magic_49(subject, efitem.unwrap()); case 21: case 1127: return _magic_21_1127(subject); case 1128: return _magic_1128(subject); case 1124: case 1125: return _magic_1124_1125(subject); case 630: case 1129: return _magic_630_1129(subject); case 629: return _magic_629(subject); case 628: return _magic_628(subject, target); case 1140: return _magic_1140(subject); case 1132: return _magic_1132(subject, fltbk, valuebk); case 457: case 438: return _magic_457_438(); case 631: return _magic_631(subject); case 659: return _magic_659(subject); case 466: return _magic_466(subject); case 657: return _magic_657(subject); case 465: return _magic_465(subject); case 656: return _magic_656(subject); case 1131: return _magic_1131(target); case 633: return _magic_633(subject, target); case 638: case 648: return _magic_638_648(subject, target); case 652: return _magic_652(subject, target); case 1133: return _magic_1133(subject, target); case 651: return _magic_651(subject, target); case 464: return _magic_464(subject, target); case 463: return _magic_463(); default: return true; } } } // namespace namespace elona { bool magic(Character& subject, Character& target, const OptionalItemRef& efitem) { int fltbk = 0; int valuebk = 0; efcancel = 0; obvious = 1; if (efsource != 4 && efsource != 1 && efsource != 2) { efstatus = CurseState::none; } efsource = 0; lib::scope_guard restore([&]() { efstatus = CurseState::none; efsource = 0; }); if (efid >= 300) { if (efid < 661) { if (const auto ret = _proc_general_magic(subject, target)) { return *ret; } } else { if (efstatus == CurseState::blessed) { efp = efp * 150 / 100; } if (is_cursed(efstatus)) { efp = 50; } } } return _proc_magic(subject, target, efitem, efid, fltbk, valuebk); } } // namespace elona
/*************************************************************************** ** Sun Aug 27 2006 ** (C) 2006 by Sanjay Nair ** sanjaysn <at> usc <dot> edu ****************************************************************************/ #include "cglobal.h" #include <openssl/sha.h> #include "cevent.h" /*! C'tor */ CEvent::CEvent() {} /*! D'tor */ CEvent::~CEvent() {} /*! Private copy constructor and assignment operator */ CEvent::CEvent(const CEvent &rhs) {} CEvent& CEvent::operator=(const CEvent &rhs) { return *this; } //----------------------------------------------------------------------------- /*! Constructs an event with a message for flooding */ CMsgEvent::CMsgEvent( CMessage *m, const string &srcNodeId, CLog::MsgType logType) { assert(m); _message = m; _srcNodeId = srcNodeId; _logType = logType; _probabilistic = false; } /*! Constructs an event with a message for routing */ CMsgEvent::CMsgEvent( CMessage *m, const string &srcNodeId, const UCharBuffer &uoid, CLog::MsgType logType) { assert(m); assert(uoid.size() == SHA_DIGEST_LENGTH); _message = m; _srcNodeId = srcNodeId; _uoid = uoid; _logType = logType; _probabilistic = false; } /* Deletes the event */ CMsgEvent::~CMsgEvent() { if (_message) { delete _message; _message = NULL; } } /*! Returns the event type */ EventType CMsgEvent::getType() { return EventMsg; } /*! Returns the message */ CMessage* CMsgEvent::getMessage() { return _message; } /*! Returns the source node id */ string CMsgEvent::getSrcNodeId() const { return _srcNodeId; } /*! Return the log Msg */ CLog::MsgType CMsgEvent::getLogType() const { return _logType; } /*! Returns true if the message needs to be flooded. */ bool CMsgEvent::isFlood() const { return (_uoid.size() != SHA_DIGEST_LENGTH); } /*! Returns true if the message needs to be flooded. */ UCharBuffer CMsgEvent::getUoid() const { return _uoid; } /*! Sets the probabilistic flooding enabled */ void CMsgEvent::setProbEnabled(bool flag) { _probabilistic = flag; } /*! Returns true if the probabilistic flooding is enabled */ bool CMsgEvent::isProbEnabled() const { return _probabilistic; } //----------------------------------------------------------------------------- /*! C'tor */ CStatusMsgEvent::CStatusMsgEvent( CMessageStatusRes *m, const string &srcNodeId, const UCharBuffer &uoid, CLog::MsgType logType) : CMsgEvent(m, srcNodeId, uoid, logType) {} /*! D'tor */ CStatusMsgEvent::~CStatusMsgEvent() {} /*! Returns the event type */ EventType CStatusMsgEvent::getType() { return EventStatusMsg; } /*! Returns the status response message */ CMessageStatusRes* CStatusMsgEvent::getMessage() { return dynamic_cast<CMessageStatusRes*>(_message); }
/* * Copyright 2017-2018 Tom van Dijk, Johannes Kepler University Linz * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <csignal> #include <iomanip> #include <iostream> #include <fstream> #include <sys/time.h> #include <boost/algorithm/string/predicate.hpp> #include <boost/iostreams/categories.hpp> #include <boost/iostreams/filtering_stream.hpp> #include <boost/iostreams/filter/bzip2.hpp> #include <boost/iostreams/filter/gzip.hpp> #include "cxxopts.hpp" #include "game.hpp" #include "oink.hpp" #include "solvers.hpp" #include "verifier.hpp" #include "tools/getrss.h" using namespace pg; /*------------------------------------------------------------------------*/ static double wctime() { struct timeval time; gettimeofday(&time, NULL); return time.tv_sec + 1E-6 * time.tv_usec; } static double t_start; /*------------------------------------------------------------------------*/ // timestamp_filter adds a timestamp at the beginning of every line. namespace io = boost::iostreams; class timestamp_filter : public io::output_filter { public: timestamp_filter() {} struct category : io::output_filter::category, io::flushable_tag { }; template<typename Sink> bool put(Sink& snk, char c); template<typename Device> void close(Device&); template<typename Sink> bool flush(Sink& snk); private: bool is_start = true; char sz[16]; const char* pos = NULL; const char* end = NULL; }; template<typename Sink> bool timestamp_filter::put(Sink& dest, char c) { if (is_start) { if (c == '\n') return true; // ignore consecutive endl is_start = false; pos = sz; end = sz + snprintf(sz, 16, "[% 8.2f] ", wctime() - t_start); } while (pos != end) { if (!io::put(dest, *pos)) return false; pos++; } if (!io::put(dest, c)) return false; if (c == '\n') is_start = true; return true; } template<typename Sink> bool timestamp_filter::flush(Sink& dest) { while (pos != end) { if (!io::put(dest, *pos)) return false; pos++; } return io::flush(dest); } template<typename Device> void timestamp_filter::close(Device&) { is_start = true; pos = end = NULL; } // global variable so signal handlers can work with it io::filtering_ostream out; /*------------------------------------------------------------------------*/ static void (*sig_int_handler)(int); static void (*sig_segv_handler)(int); static void (*sig_abrt_handler)(int); static void (*sig_term_handler)(int); static void (*sig_alrm_handler)(int); static void resetsighandlers(void) { (void)signal(SIGINT, sig_int_handler); (void)signal(SIGSEGV, sig_segv_handler); (void)signal(SIGABRT, sig_abrt_handler); (void)signal(SIGTERM, sig_term_handler); (void)signal(SIGALRM, sig_alrm_handler); } static void catchsig(int sig) { // note: this can actually deadlock because we are writing to stdout... if (sig == SIGALRM) { resetsighandlers(); out << std::endl << "terminated due to timeout" << std::endl; out.flush(); exit(-1); } else if (sig == SIGINT) { // CTRL-C resetsighandlers(); out << std::endl << "received INT signal" << std::endl; out.flush(); exit(-SIGINT); } else if (sig == SIGABRT) { // really bad resetsighandlers(); out << std::endl << "terminated due to ABORT signal" << std::endl; out.flush(); exit(-SIGABRT); raise(sig); } else { resetsighandlers(); out << std::endl << "terminated due to signal " << sig << std::endl; out.flush(); exit(-sig); } } static void setsighandlers(void) { sig_int_handler = signal(SIGINT, catchsig); sig_segv_handler = signal(SIGSEGV, catchsig); sig_abrt_handler = signal(SIGABRT, catchsig); sig_term_handler = signal(SIGTERM, catchsig); sig_alrm_handler = signal(SIGALRM, catchsig); } /*------------------------------------------------------------------------*/ static char* to_h(double size, char *buf) { const char* units[] = {"B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"}; int i = 0; for (;size>1024;size/=1024) i++; sprintf(buf, "%.*f %s", i, size, units[i]); return buf; } /*------------------------------------------------------------------------*/ int main(int argc, char **argv) { t_start = wctime(); setsighandlers(); cxxopts::Options opts(argv[0], "Parity game solver"); opts.add_options() ("help", "Print help") ("t,trace", "Generate trace (with increasing verbosity)") ("v,verify", "Verify solution") ("p,print", "Print solution to stdout") ("i,input", "Input parity game", cxxopts::value<std::string>()) ("sol", "Input (partial) solution", cxxopts::value<std::string>()) ("o,output", "Output game or solution", cxxopts::value<std::string>()) ("dot", "Write .dot file (before preprocessing)", cxxopts::value<std::string>()) /* Preprocessing */ ("inflate", "Inflate game") ("compress", "Compress game") ("no-single", "Do not solve single-parity games during preprocessing") ("no-loops", "Do not remove self-loops during preprocessing (default behavior)") ("no-wcwc", "Do not solve winner-controlled winning cycles during preprocessing") ("no", "Do not touch the game at all") /* Solving */ ("scc", "Iteratively solve bottom SCCs") ("s,solver", "Use given solver (--solvers for info)", cxxopts::value<std::string>()) ("solvers", "List available solvers") ("w,workers", "Number of workers for parallel code", cxxopts::value<int>()) ("z,timeout", "Number of seconds for timeout", cxxopts::value<int>()) ; /* Add solvers */ Solvers solvers; for (unsigned id=0; id<solvers.count(); id++) { opts.add_options()(solvers.label(id), solvers.desc(id)); } /* Parse command line */ opts.parse_positional(std::vector<std::string>({"input", "output"})); auto options = opts.parse(argc, argv); if (options.count("help")) { std::cout << opts.help() << std::endl; return 0; } if (options.count("solvers")) { solvers.list(std::cout); return 0; } /* Setup timestamp filter */ out.push(timestamp_filter()); out.push(std::cout); /** * STEP 1 * Read the game that must be solved. * (Supports bz2 and gz compression.) */ Game pg; try { if (options.count("input")) { std::string filename = options["input"].as<std::string>(); io::filtering_istream in; if (boost::algorithm::ends_with(filename, ".bz2")) in.push(io::bzip2_decompressor()); if (boost::algorithm::ends_with(filename, ".gz")) in.push(io::gzip_decompressor()); std::ifstream file(filename, std::ios_base::binary); in.push(file); pg.parse_pgsolver(in, options.count("no-loops") == 0 and options.count("no") == 0); file.close(); } else { pg.parse_pgsolver(std::cin, options.count("no-loops") == 0 and options.count("no") == 0); } out << "parity game with " << pg.nodecount() << " nodes and " << pg.edgecount() << " edges." << std::endl; } catch (const char *err) { out << "parsing error: " << err << std::endl; return -1; } /** * STEP 2 * Parse the (partial) solution. */ try { if (options.count("sol")) { std::ifstream file(options["sol"].as<std::string>()); pg.parse_solution(file); file.close(); out << "solution parsed." << std::endl; } } catch (const char *err) { out << "parsing error: " << err << std::endl; return -1; } /** * STEP 3 * If requested, write .dot file */ if (options.count("dot")) { std::ofstream file(options["dot"].as<std::string>()); pg.write_dot(file); file.close(); out << "dot file written." << std::endl; } /** * STEP 4 * Reindex the game so all nodes are in order of priority. * (Remember the mapping to reverse the reindex later.) */ int *mapping = new int[pg.nodecount()]; pg.sort(mapping); out << "parity game reindexed" << std::endl; /** * STEP 5 * Configure the solver. */ Oink en(pg, out); en.setTrace(options.count("t")); // preprocessing options bool no = options.count("no"); if (options.count("inflate")) en.setInflate(); else if (options.count("compress")) en.setCompress(); else if (!no) en.setRenumber(); if (no or options.count("no-single")) en.setSolveSingle(false); if (no or options.count("no-loops")) en.setRemoveLoops(false); if (no or options.count("no-wcwc")) en.setRemoveWCWC(false); // solver if (options.count("solver")) { en.setSolver(solvers.id(options["solver"].as<std::string>())); } else { en.setSolver("tl"); // default solver for (unsigned id=0; id<solvers.count(); id++) { if (options.count(solvers.label(id))) en.setSolver(id); } } // solving options if (options.count("scc")) en.setBottomSCC(true); if (options.count("workers")) en.setWorkers(options["workers"].as<int>()); /** * STEP 6 * Run the solver and report the time. */ if (options.count("timeout")) alarm(options["timeout"].as<int>()); try { double begin = wctime(); en.run(); double end = wctime(); out << "total solving time: " << std::fixed << (end-begin) << " sec." << std::endl; } catch (pg::Error &err) { out << "solving error: " << err.what() << std::endl; return -1; } /** * STEP 7 * Verify the solution. */ if (options.count("v")) { try { out << "verifying solution..." << std::endl; Verifier v(&pg, out); double vbegin = wctime(); v.verify(true, true, true); double vend = wctime(); out << "solution verified (" << v.n_strategies << " strategies)." << std::endl; out << "verification took " << std::fixed << (vend - vbegin) << " sec." << std::endl; } catch (const char *err) { out << "verification error: " << err << std::endl; return -1; } } char buf[32]; to_h(getCurrentRSS(), buf); out << "current memory usage: " << buf << std::endl; to_h(getPeakRSS(), buf); out << "peak memory usage: " << buf << std::endl; /** * STEP 8 * Revert reindex if we need to output. */ if (options.count("output") or options.count("p")) pg.permute(mapping); if (options.count("output")) { // write solution to file if (options.count("output")) { std::ofstream file(options["output"].as<std::string>()); pg.write_sol(file); } } if (options.count("p")) { // print winning nodes bool banner = false; for (int i=0; i<pg.nodecount(); i++) { if (pg.solved[i] and pg.winner[i] == 0) { if (!banner) out << "won by even:"; banner = true; // out << " " << i; // << "(" << pg.priority(i) << ")"; out << " " << pg.label_vertex(i); } } if (banner) out << std::endl; banner = false; for (int i=0; i<pg.nodecount(); i++) { if (pg.solved[i] and pg.winner[i] == 1) { if (!banner) out << "won by odd:"; banner = true; out << " " << pg.label_vertex(i); } } if (banner) out << std::endl; } delete[] mapping; resetsighandlers(); return 0; }
/* Copyright (C) 2005-2007 Feeling Software Inc. Portions of the code are: Copyright (C) 2005-2007 Sony Computer Entertainment America MIT License: http://www.opensource.org/licenses/mit-license.php */ #include "StdAfx.h" #include "FCDocument.h" #include "FCDEntity.h" #include "FCDEntityInstance.h" #include "FCDExtra.h" #include "FCDSceneNode.h" #include "FCDControllerInstance.h" #include "FCDEmitterInstance.h" #include "FCDGeometryInstance.h" #include "FCDPhysicsForceFieldInstance.h" #include "FCDEntityReference.h" #include <FUtils/FUFileManager.h> #include <FUtils/FUUniqueStringMap.h> // // FCDEntityInstance // ImplementObjectType(FCDEntityInstance); ImplementParameterObject(FCDEntityInstance, FCDEntityReference, entityReference, new FCDEntityReference(parent->GetDocument(), parent->GetParent())); ImplementParameterObject(FCDEntityInstance, FCDExtra, extra, new FCDExtra(parent->GetDocument(), parent)); FCDEntityInstance::FCDEntityInstance(FCDocument* document, FCDSceneNode* _parent, FCDEntity::Type type) : FCDObject(document), parent(_parent) , entityType(type) , InitializeParameterNoArg(entityReference) , InitializeParameterNoArg(wantedSubId) , InitializeParameterNoArg(extra) { // Always create this entityReference = new FCDEntityReference(document, _parent); TrackObject(entityReference); } FCDEntityInstance::~FCDEntityInstance() { if (entityReference != NULL) { UntrackObject(entityReference); SAFE_RELEASE(entityReference); } } FCDEntity* FCDEntityInstance::GetEntity() { return entityReference->GetEntity(); } void FCDEntityInstance::SetEntity(FCDEntity* entity) { entityReference->SetEntity(entity); } const FUUri FCDEntityInstance::GetEntityUri() const { return entityReference->GetUri(); } void FCDEntityInstance::SetEntityUri(const FUUri& uri) { entityReference->SetUri(uri); } void FCDEntityInstance::SetName(const fstring& _name) { name = FCDEntity::CleanName(_name.c_str()); SetDirtyFlag(); } FCDExtra* FCDEntityInstance::GetExtra() { return (extra != NULL) ? extra : (extra = new FCDExtra(GetDocument(), this)); } bool FCDEntityInstance::IsExternalReference() const { return entityReference->GetPlaceHolder() != NULL; } /* void FCDEntityInstance::LoadExternalEntity(FCDocument* externalDocument, const fm::string& daeId) { if (externalDocument == NULL || entity != NULL) return; FCDEntity* instancedEntity = NULL; switch (entityType) { case FCDEntity::ANIMATION: instancedEntity = (FCDEntity*) externalDocument->FindAnimation(daeId); break; case FCDEntity::CAMERA: instancedEntity = (FCDEntity*) externalDocument->FindCamera(daeId); break; case FCDEntity::EMITTER: instancedEntity = (FCDEntity*) externalDocument->FindEmitter(daeId); break; case FCDEntity::LIGHT: instancedEntity = (FCDEntity*) externalDocument->FindLight(daeId); break; case FCDEntity::GEOMETRY: instancedEntity = (FCDEntity*) externalDocument->FindGeometry(daeId); break; case FCDEntity::CONTROLLER: instancedEntity = (FCDEntity*) externalDocument->FindController(daeId); break; case FCDEntity::MATERIAL: instancedEntity = (FCDEntity*) externalDocument->FindMaterial(daeId); break; case FCDEntity::EFFECT: instancedEntity = (FCDEntity*) externalDocument->FindEffect(daeId); break; case FCDEntity::SCENE_NODE: instancedEntity = (FCDEntity*) externalDocument->FindSceneNode(daeId); break; case FCDEntity::FORCE_FIELD: instancedEntity = (FCDEntity*) externalDocument->FindForceField(daeId); break; case FCDEntity::PHYSICS_MATERIAL: instancedEntity = (FCDEntity*) externalDocument->FindPhysicsMaterial(daeId); break; case FCDEntity::PHYSICS_MODEL: instancedEntity = (FCDEntity*) externalDocument->FindPhysicsModel(daeId); break; default: break; } if (instancedEntity != NULL) { SetEntity(instancedEntity); } } */ bool FCDEntityInstance::HasForParent(FCDSceneNode* node) const { if (node == NULL) return false; if (parent == NULL) return false; FCDSceneNodeList parentStack; parentStack.push_back(parent); while (!parentStack.empty()) { FCDSceneNode* p = parentStack.front(); if (p == node) return true; for (size_t i = 0; i < p->GetParentCount(); ++i) { parentStack.push_back(p->GetParent(i)); } parentStack.pop_front(); } return false; } void FCDEntityInstance::CleanSubId(FUSUniqueStringMap* parentStringMap) { if (!wantedSubId->empty() && (parentStringMap != NULL)) { parentStringMap->insert(wantedSubId); } } FCDEntityInstance* FCDEntityInstance::Clone(FCDEntityInstance* clone) const { if (clone == NULL) { clone = new FCDEntityInstance(const_cast<FCDocument*>(GetDocument()), const_cast<FCDSceneNode*>(parent), entityType); } clone->SetEntity(const_cast<FCDEntity*>(entityReference->GetEntity())); return clone; } void FCDEntityInstance::OnObjectReleased(FUTrackable* object) { FUAssert(object == entityReference, return); entityReference = NULL; Release(); } /******************* FCDEntityInstanceFactory implementation ***********************/ FCDEntityInstance* FCDEntityInstanceFactory::CreateInstance(FCDocument* document, FCDSceneNode* parent, FCDEntity::Type type) { switch (type) { case FCDEntity::CONTROLLER: return new FCDControllerInstance(document, parent, type); break; case FCDEntity::EMITTER: return new FCDEmitterInstance(document, parent, type); break; case FCDEntity::GEOMETRY: return new FCDGeometryInstance(document, parent, type); break; case FCDEntity::FORCE_FIELD: return new FCDPhysicsForceFieldInstance(document, parent, type); break; case FCDEntity::PHYSICS_MATERIAL: case FCDEntity::CAMERA: case FCDEntity::LIGHT: case FCDEntity::ANIMATION: case FCDEntity::SCENE_NODE: return new FCDEntityInstance(document, parent, type); break; default: FUFail(;); // Default to always return something. return new FCDEntityInstance(document, parent, type); break; } } FCDEntityInstance* FCDEntityInstanceFactory::CreateInstance(FCDocument* document, FCDSceneNode* parent, FCDEntity* entity) { FUAssert(entity != NULL, return NULL); FCDEntityInstance* instance = CreateInstance(document, parent, entity->GetType()); instance->SetEntity(entity); return instance; }
// // EventCollision.cpp // Joseph Petitti // #include "EventCollision.h" namespace df { EventCollision::EventCollision() { Vector m_pos(0, 0); m_p_obj1 = NULL; m_p_obj2 = NULL; setType(COLLISION_EVENT); } EventCollision::EventCollision(Object *p_o1, Object *p_o2, Vector p) { m_pos = p; m_p_obj1 = p_o1; m_p_obj2 = p_o2; setType(COLLISION_EVENT); } void EventCollision::setObject1(Object *p_new_o1) { m_p_obj1 = p_new_o1; } Object *EventCollision::getObject1() const { return m_p_obj1; } void EventCollision::setObject2(Object *p_new_o2) { m_p_obj2 = p_new_o2; } Object *EventCollision::getObject2() const { return m_p_obj2; } void EventCollision::setPosition(Vector new_pos) { m_pos = new_pos; } Vector EventCollision::getPosition() const { return m_pos; } } // end namespace df
#ifndef REMOTE_SLAVE_CLIENT_HPP_INCLUDED #define REMOTE_SLAVE_CLIENT_HPP_INCLUDED #include <network/remote_client_base.hpp> #include <network/tcp_socket.hpp> class MasterToSlaveServer; class RemoteSlaveClient: public RemoteClientBase<TCPSocket> { public: RemoteSlaveClient() = default; ~RemoteSlaveClient() = default; void on_connection_closed() override final; void set_server(MasterToSlaveServer* server); private: MasterToSlaveServer* server; void install_callbacks() override final; RemoteSlaveClient(const RemoteSlaveClient&) = delete; RemoteSlaveClient(RemoteSlaveClient&&) = delete; RemoteSlaveClient& operator=(const RemoteSlaveClient&) = delete; RemoteSlaveClient& operator=(RemoteSlaveClient&&) = delete; }; #endif /* REMOTE_SLAVE_CLIENT_HPP_INCLUDED */
/*! * WTEngine | File: renderer.hpp * * \author Matthew Evans * \version 0.7 * \copyright See LICENSE.md for copyright information. * \date 2019-2021 */ #ifndef WTE_MGR_RENDERER_HPP #define WTE_MGR_RENDERER_HPP #include <string> #include <utility> #include <set> #include <iterator> #include <memory> #include <chrono> #include <stdexcept> #include <cassert> #include <allegro5/allegro.h> #include <allegro5/allegro_image.h> #include <allegro5/allegro_font.h> #include "wtengine/mgr/manager.hpp" #include "wtengine/_globals/_defines.hpp" #include "wtengine/_globals/alert.hpp" #include "wtengine/_globals/engine_time.hpp" #include "wtengine/_globals/notice.hpp" #include "wtengine/_globals/wrappers.hpp" #include "wtengine/_globals/wte_asset.hpp" #include "wtengine/_globals/wte_exception.hpp" #include "wtengine/cmp/_components.hpp" #include "wtengine/mgr/menus.hpp" #include "wtengine/mgr/world.hpp" #include "wtengine/config.hpp" #include "wtengine/display.hpp" namespace wte { class display; class engine; template <typename T> using time_point = std::chrono::time_point<T>; typedef std::chrono::system_clock system_clock; typedef std::chrono::system_clock::duration duration; } namespace wte::mgr { /*! * Container for an entity and component pair. Used for sorting. * \tparam Component type */ template <typename T> using entity_component_pair = std::pair<const entity_id, std::shared_ptr<const T>>; /*! * \class renderer * \brief An object that handles drawing the world to the screen. */ class renderer final : private manager<renderer> { friend class wte::display; friend class wte::engine; public: /*! * \brief Set the arena size. * * Once the renderer has been initialized it can not be changed. * This should be called during engine initialization before the main object is created. * * \param w Arena width in pixels. * \param h Arena height in pixels. */ static void set_arena_size( const int& w, const int& h ); /*! * \brief Set the title screen. * * This should be called during engine initialization before the main object is created. * * \param fname Filename of the title screen. */ static void set_title_screen( const std::string& fname ); /*! * \brief Set the font to be used by the renderer. * * If not called, Allegro's default font will be used. * This should be called during engine initialization before the main object is created. * See the Allegro docs for more information on al_load_font and the parameters used. * * \param fone Font asset to use. */ static void set_font( wte_asset<al_font> font ); static const std::size_t& fps; //!< Frames per second static const time_point<system_clock>& last_render; //!< Time of last render static const time_point<system_clock>& start_time; //!< Start time of renderer static const duration& delta_time; //!< Duration of last frame render private: renderer() = default; ~renderer() = default; /* * Configures the internal objects for the render manager to use. */ static void initialize(void); /* * Destories the internal objects. */ static void de_init(void); /* * Draw the game screen. */ static void render(void); template <typename T> struct comparator { const bool operator() (const T& a, const T& b) const { return *a.second < *b.second; } }; static ALLEGRO_TIMER* fps_timer; static ALLEGRO_EVENT_QUEUE* fps_event_queue; static ALLEGRO_EVENT fps_event; static wte_asset<al_bitmap> arena_bitmap; static wte_asset<al_bitmap> title_bitmap; static wte_asset<al_bitmap> menu_bitmap; static wte_asset<al_font> renderer_font; static std::size_t fps_counter, _fps; static time_point<system_clock> _last_render, _start_time; static duration _delta_time; static bool arena_created; static std::string title_screen_file; static std::string background_file; }; } // end namespace wte::mgr #endif
// Copyright (c) 2014-2015 Dropbox, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "gc/collector.h" #include <cassert> #include <cstdio> #include <cstdlib> #include "codegen/ast_interpreter.h" #include "codegen/codegen.h" #include "core/common.h" #include "core/threading.h" #include "core/types.h" #include "core/util.h" #include "gc/heap.h" #include "runtime/hiddenclass.h" #include "runtime/objmodel.h" #include "runtime/types.h" #ifndef NVALGRIND #include "valgrind.h" #endif namespace pyston { namespace gc { #if TRACE_GC_MARKING FILE* trace_fp; #endif std::deque<Box*> pending_finalization_list; std::deque<PyWeakReference*> weakrefs_needing_callback_list; std::list<Box*> objects_with_ordered_finalizers; static std::unordered_set<void*> roots; static std::vector<std::pair<void*, void*>> potential_root_ranges; // BoxedClasses in the program that are still needed. static std::unordered_set<BoxedClass*> class_objects; static std::unordered_set<void*> nonheap_roots; // Track the highest-addressed nonheap root; the assumption is that the nonheap roots will // typically all have lower addresses than the heap roots, so this can serve as a cheap // way to verify it's not a nonheap root (the full check requires a hashtable lookup). static void* max_nonheap_root = 0; static void* min_nonheap_root = (void*)~0; static std::unordered_set<GCRootHandle*>* getRootHandles() { static std::unordered_set<GCRootHandle*> root_handles; return &root_handles; } static int ncollections = 0; static bool gc_enabled = true; static bool should_not_reenter_gc = false; enum TraceStackType { MarkPhase, FinalizationOrderingFindReachable, FinalizationOrderingRemoveTemporaries, }; class TraceStack { private: const int CHUNK_SIZE = 256; const int MAX_FREE_CHUNKS = 50; std::vector<void**> chunks; static std::vector<void**> free_chunks; void** cur; void** start; void** end; TraceStackType visit_type; void get_chunk() { if (free_chunks.size()) { start = free_chunks.back(); free_chunks.pop_back(); } else { start = (void**)malloc(sizeof(void*) * CHUNK_SIZE); } cur = start; end = start + CHUNK_SIZE; } void release_chunk(void** chunk) { if (free_chunks.size() == MAX_FREE_CHUNKS) free(chunk); else free_chunks.push_back(chunk); } void pop_chunk() { start = chunks.back(); chunks.pop_back(); end = start + CHUNK_SIZE; cur = end; } public: TraceStack(TraceStackType type) : visit_type(type) { get_chunk(); } TraceStack(TraceStackType type, const std::unordered_set<void*>& roots) : visit_type(type) { get_chunk(); for (void* p : roots) { ASSERT(!isMarked(GCAllocation::fromUserData(p)), ""); push(p); } } ~TraceStack() { RELEASE_ASSERT(end - cur == CHUNK_SIZE, "destroying non-empty TraceStack"); // We always have a block available in case we want to push items onto the TraceStack, // but that chunk needs to be released after use to avoid a memory leak. release_chunk(start); } void push(void* p) { GC_TRACE_LOG("Pushing %p\n", p); GCAllocation* al = GCAllocation::fromUserData(p); switch (visit_type) { case TraceStackType::MarkPhase: // Use this to print the directed edges of the GC graph traversal. // i.e. print every a -> b where a is a pointer and b is something a references #if 0 if (previous_pop) { GCAllocation* source_allocation = GCAllocation::fromUserData(previous_pop); if (source_allocation->kind_id == GCKind::PYTHON) { printf("(%s) ", ((Box*)previous_pop)->cls->tp_name); } printf("%p > %p", previous_pop, al->user_data); } else { printf("source %p", al->user_data); } if (al->kind_id == GCKind::PYTHON) { printf(" (%s)", ((Box*)al->user_data)->cls->tp_name); } printf("\n"); #endif if (isMarked(al)) { return; } else { setMark(al); } break; // See PyPy's finalization ordering algorithm: // http://pypy.readthedocs.org/en/latest/discussion/finalizer-order.html case TraceStackType::FinalizationOrderingFindReachable: if (orderingState(al) == FinalizationState::UNREACHABLE) { setOrderingState(al, FinalizationState::TEMPORARY); } else if (orderingState(al) == FinalizationState::REACHABLE_FROM_FINALIZER) { setOrderingState(al, FinalizationState::ALIVE); } else { return; } break; case TraceStackType::FinalizationOrderingRemoveTemporaries: if (orderingState(al) == FinalizationState::TEMPORARY) { setOrderingState(al, FinalizationState::REACHABLE_FROM_FINALIZER); } else { return; } break; default: assert(false); } *cur++ = p; if (cur == end) { chunks.push_back(start); get_chunk(); } } void* pop_chunk_and_item() { release_chunk(start); if (chunks.size()) { pop_chunk(); assert(cur == end); return *--cur; // no need for any bounds checks here since we're guaranteed we're CHUNK_SIZE from the start } else { // We emptied the stack, but we should prepare a new chunk in case another item // gets added onto the stack. get_chunk(); return NULL; } } void* pop() { if (cur > start) return *--cur; return pop_chunk_and_item(); } }; std::vector<void**> TraceStack::free_chunks; void registerPermanentRoot(void* obj, bool allow_duplicates) { assert(global_heap.getAllocationFromInteriorPointer(obj)); // Check for double-registers. Wouldn't cause any problems, but we probably shouldn't be doing them. if (!allow_duplicates) ASSERT(roots.count(obj) == 0, "Please only register roots once"); roots.insert(obj); } void deregisterPermanentRoot(void* obj) { assert(global_heap.getAllocationFromInteriorPointer(obj)); ASSERT(roots.count(obj), ""); roots.erase(obj); } void registerPotentialRootRange(void* start, void* end) { potential_root_ranges.push_back(std::make_pair(start, end)); } extern "C" PyObject* PyGC_AddRoot(PyObject* obj) noexcept { if (obj) { // Allow duplicates from CAPI code since they shouldn't have to know // which objects we already registered as roots: registerPermanentRoot(obj, /* allow_duplicates */ true); } return obj; } extern "C" PyObject* PyGC_AddNonHeapRoot(PyObject* obj, int size) noexcept { if (obj) { registerNonheapRootObject(obj, size); } return obj; } void registerNonheapRootObject(void* obj, int size) { // I suppose that things could work fine even if this were true, but why would it happen? assert(global_heap.getAllocationFromInteriorPointer(obj) == NULL); assert(nonheap_roots.count(obj) == 0); nonheap_roots.insert(obj); registerPotentialRootRange(obj, ((uint8_t*)obj) + size); max_nonheap_root = std::max(obj, max_nonheap_root); min_nonheap_root = std::min(obj, min_nonheap_root); } bool isNonheapRoot(void* p) { if (p > max_nonheap_root || p < min_nonheap_root) return false; return nonheap_roots.count(p) != 0; } bool isValidGCMemory(void* p) { return isNonheapRoot(p) || (global_heap.getAllocationFromInteriorPointer(p)->user_data == p); } bool isValidGCObject(void* p) { if (isNonheapRoot(p)) return true; GCAllocation* al = global_heap.getAllocationFromInteriorPointer(p); if (!al) return false; return al->user_data == p && al->kind_id == GCKind::PYTHON; } void registerPythonObject(Box* b) { assert(isValidGCMemory(b)); auto al = GCAllocation::fromUserData(b); assert(al->kind_id == GCKind::CONSERVATIVE || al->kind_id == GCKind::PYTHON); al->kind_id = GCKind::PYTHON; assert(b->cls); if (hasOrderedFinalizer(b->cls)) { objects_with_ordered_finalizers.push_back(b); } if (PyType_Check(b)) { class_objects.insert((BoxedClass*)b); } } void invalidateOrderedFinalizerList() { static StatCounter sc_us("us_gc_invalidate_ordered_finalizer_list"); Timer _t("invalidateOrderedFinalizerList", /*min_usec=*/10000); for (auto iter = objects_with_ordered_finalizers.begin(); iter != objects_with_ordered_finalizers.end();) { Box* box = *iter; GCAllocation* al = GCAllocation::fromUserData(box); if (!hasOrderedFinalizer(box->cls) || hasFinalized(al)) { // Cleanup. iter = objects_with_ordered_finalizers.erase(iter); } else { ++iter; } } long us = _t.end(); sc_us.log(us); } GCRootHandle::GCRootHandle() { getRootHandles()->insert(this); } GCRootHandle::~GCRootHandle() { getRootHandles()->erase(this); } bool GCVisitor::isValid(void* p) { return global_heap.getAllocationFromInteriorPointer(p) != NULL; } void GCVisitor::visit(void* p) { if ((uintptr_t)p < SMALL_ARENA_START || (uintptr_t)p >= HUGE_ARENA_START + ARENA_SIZE) { ASSERT(!p || isNonheapRoot(p), "%p", p); return; } ASSERT(global_heap.getAllocationFromInteriorPointer(p)->user_data == p, "%p", p); stack->push(p); } void GCVisitor::visitRange(void* const* start, void* const* end) { ASSERT((const char*)end - (const char*)start <= 1000000000, "Asked to scan %.1fGB -- a bug?", ((const char*)end - (const char*)start) * 1.0 / (1 << 30)); assert((uintptr_t)start % sizeof(void*) == 0); assert((uintptr_t)end % sizeof(void*) == 0); while (start < end) { visit(*start); start++; } } void GCVisitor::visitPotential(void* p) { GCAllocation* a = global_heap.getAllocationFromInteriorPointer(p); if (a) { visit(a->user_data); } } void GCVisitor::visitPotentialRange(void* const* start, void* const* end) { ASSERT((const char*)end - (const char*)start <= 1000000000, "Asked to scan %.1fGB -- a bug?", ((const char*)end - (const char*)start) * 1.0 / (1 << 30)); assert((uintptr_t)start % sizeof(void*) == 0); assert((uintptr_t)end % sizeof(void*) == 0); while (start < end) { #if TRACE_GC_MARKING if (global_heap.getAllocationFromInteriorPointer(*start)) { if (*start >= (void*)HUGE_ARENA_START) GC_TRACE_LOG("Found conservative reference to huge object %p from %p\n", *start, start); else if (*start >= (void*)LARGE_ARENA_START && *start < (void*)HUGE_ARENA_START) GC_TRACE_LOG("Found conservative reference to large object %p from %p\n", *start, start); else GC_TRACE_LOG("Found conservative reference to %p from %p\n", *start, start); } #endif visitPotential(*start); start++; } } static __attribute__((always_inline)) void visitByGCKind(void* p, GCVisitor& visitor) { assert(((intptr_t)p) % 8 == 0); GCAllocation* al = GCAllocation::fromUserData(p); GCKind kind_id = al->kind_id; if (kind_id == GCKind::UNTRACKED) { // Nothing to do here. } else if (kind_id == GCKind::CONSERVATIVE) { uint32_t bytes = al->kind_data; visitor.visitPotentialRange((void**)p, (void**)((char*)p + bytes)); } else if (kind_id == GCKind::PRECISE) { uint32_t bytes = al->kind_data; visitor.visitRange((void**)p, (void**)((char*)p + bytes)); } else if (kind_id == GCKind::PYTHON) { Box* b = reinterpret_cast<Box*>(p); BoxedClass* cls = b->cls; if (cls) { // The cls can be NULL since we use 'new' to construct them. // An arbitrary amount of stuff can happen between the 'new' and // the call to the constructor (ie the args get evaluated), which // can trigger a collection. ASSERT(cls->gc_visit, "%s", getTypeName(b)); cls->gc_visit(&visitor, b); } } else if (kind_id == GCKind::RUNTIME) { GCAllocatedRuntime* runtime_obj = reinterpret_cast<GCAllocatedRuntime*>(p); runtime_obj->gc_visit(&visitor); } else { RELEASE_ASSERT(0, "Unhandled kind: %d", (int)kind_id); } } static void markRoots(GCVisitor& visitor) { GC_TRACE_LOG("Looking at the stack\n"); threading::visitAllStacks(&visitor); GC_TRACE_LOG("Looking at root handles\n"); for (auto h : *getRootHandles()) { visitor.visit(h->value); } GC_TRACE_LOG("Looking at potential root ranges\n"); for (auto& e : potential_root_ranges) { visitor.visitPotentialRange((void* const*)e.first, (void* const*)e.second); } GC_TRACE_LOG("Looking at pending finalization list\n"); for (auto box : pending_finalization_list) { visitor.visit(box); } GC_TRACE_LOG("Looking at weakrefs needing callbacks list\n"); for (auto weakref : weakrefs_needing_callback_list) { visitor.visit(weakref); } } static void finalizationOrderingFindReachable(Box* obj) { static StatCounter sc_marked_objs("gc_marked_object_count_finalizer_ordering"); static StatCounter sc_us("us_gc_mark_finalizer_ordering_1"); Timer _t("finalizationOrderingFindReachable", /*min_usec=*/10000); TraceStack stack(TraceStackType::FinalizationOrderingFindReachable); GCVisitor visitor(&stack); stack.push(obj); while (void* p = stack.pop()) { sc_marked_objs.log(); visitByGCKind(p, visitor); } long us = _t.end(); sc_us.log(us); } static void finalizationOrderingRemoveTemporaries(Box* obj) { static StatCounter sc_us("us_gc_mark_finalizer_ordering_2"); Timer _t("finalizationOrderingRemoveTemporaries", /*min_usec=*/10000); TraceStack stack(TraceStackType::FinalizationOrderingRemoveTemporaries); GCVisitor visitor(&stack); stack.push(obj); while (void* p = stack.pop()) { GCAllocation* al = GCAllocation::fromUserData(p); assert(orderingState(al) != FinalizationState::UNREACHABLE); visitByGCKind(p, visitor); } long us = _t.end(); sc_us.log(us); } // Implementation of PyPy's finalization ordering algorithm: // http://pypy.readthedocs.org/en/latest/discussion/finalizer-order.html static void orderFinalizers() { static StatCounter sc_us("us_gc_finalization_ordering"); Timer _t("finalizationOrdering", /*min_usec=*/10000); std::vector<Box*> finalizer_marked; for (Box* obj : objects_with_ordered_finalizers) { GCAllocation* al = GCAllocation::fromUserData(obj); // We are only interested in object with finalizers that need to be garbage-collected. if (orderingState(al) == FinalizationState::UNREACHABLE) { assert(hasOrderedFinalizer(obj->cls)); finalizer_marked.push_back(obj); finalizationOrderingFindReachable(obj); finalizationOrderingRemoveTemporaries(obj); } } for (Box* marked : finalizer_marked) { GCAllocation* al = GCAllocation::fromUserData(marked); FinalizationState state = orderingState(al); assert(state == FinalizationState::REACHABLE_FROM_FINALIZER || state == FinalizationState::ALIVE); if (state == FinalizationState::REACHABLE_FROM_FINALIZER) { pending_finalization_list.push_back(marked); } } long us = _t.end(); sc_us.log(us); } static void graphTraversalMarking(TraceStack& stack, GCVisitor& visitor) { static StatCounter sc_us("us_gc_mark_phase_graph_traversal"); static StatCounter sc_marked_objs("gc_marked_object_count"); Timer _t("traversing", /*min_usec=*/10000); while (void* p = stack.pop()) { sc_marked_objs.log(); GCAllocation* al = GCAllocation::fromUserData(p); #if TRACE_GC_MARKING if (al->kind_id == GCKind::PYTHON) GC_TRACE_LOG("Looking at %s object %p\n", static_cast<Box*>(p)->cls->tp_name, p); else GC_TRACE_LOG("Looking at non-python allocation %p\n", p); #endif assert(isMarked(al)); visitByGCKind(p, visitor); } long us = _t.end(); sc_us.log(us); } static void callWeakrefCallback(PyWeakReference* head) { if (head->wr_callback) { runtimeCall(head->wr_callback, ArgPassSpec(1), reinterpret_cast<Box*>(head), NULL, NULL, NULL, NULL); head->wr_callback = NULL; } } static void callPendingFinalizers() { static StatCounter sc_us_finalizer("us_gc_finalizercalls"); Timer _timer_finalizer("calling finalizers", /*min_usec=*/10000); bool initially_empty = pending_finalization_list.empty(); // An object can be resurrected in the finalizer code. So when we call a finalizer, we // mark the finalizer as having been called, but the object is only freed in another // GC pass (objects whose finalizers have been called are treated the same as objects // without finalizers). while (!pending_finalization_list.empty()) { Box* box = pending_finalization_list.front(); pending_finalization_list.pop_front(); ASSERT(isValidGCObject(box), "objects to be finalized should still be alive"); if (isWeaklyReferenced(box)) { // Callbacks for weakly-referenced objects with finalizers (if any), followed by call to finalizers. PyWeakReference** list = (PyWeakReference**)PyObject_GET_WEAKREFS_LISTPTR(box); while (PyWeakReference* head = *list) { assert(isValidGCObject(head)); if (head->wr_object != Py_None) { assert(head->wr_object == box); _PyWeakref_ClearRef(head); callWeakrefCallback(head); } } } finalize(box); ASSERT(isValidGCObject(box), "finalizing an object should not free the object"); } if (!initially_empty) { invalidateOrderedFinalizerList(); } sc_us_finalizer.log(_timer_finalizer.end()); } static void callPendingWeakrefCallbacks() { static StatCounter sc_us_weakref("us_gc_weakrefcalls"); Timer _timer_weakref("calling weakref callbacks", /*min_usec=*/10000); // Callbacks for weakly-referenced objects without finalizers. while (!weakrefs_needing_callback_list.empty()) { PyWeakReference* head = weakrefs_needing_callback_list.front(); weakrefs_needing_callback_list.pop_front(); callWeakrefCallback(head); } sc_us_weakref.log(_timer_weakref.end()); } void callPendingDestructionLogic() { static bool callingPending = false; // Calling finalizers is likely going to lead to another call to allowGLReadPreemption // and reenter callPendingDestructionLogic, so we'd really only be calling // one finalizer per function call to callPendingFinalizers/WeakrefCallbacks. The purpose // of this boolean is to avoid that. if (!callingPending) { callingPending = true; callPendingFinalizers(); callPendingWeakrefCallbacks(); callingPending = false; } } static void prepareWeakrefCallbacks(Box* box) { PyWeakReference** list = (PyWeakReference**)PyObject_GET_WEAKREFS_LISTPTR(box); while (PyWeakReference* head = *list) { assert(isValidGCObject(head)); if (head->wr_object != Py_None) { assert(head->wr_object == box); _PyWeakref_ClearRef(head); if (head->wr_callback) { weakrefs_needing_callback_list.push_back(head); } } } } static void markPhase() { static StatCounter sc_us("us_gc_mark_phase"); Timer _t("markPhase", /*min_usec=*/10000); #ifndef NVALGRIND // Have valgrind close its eyes while we do the conservative stack and data scanning, // since we'll be looking at potentially-uninitialized values: VALGRIND_DISABLE_ERROR_REPORTING; #endif GC_TRACE_LOG("Starting collection %d\n", ncollections); GC_TRACE_LOG("Looking at roots\n"); TraceStack stack(TraceStackType::MarkPhase, roots); GCVisitor visitor(&stack); markRoots(visitor); graphTraversalMarking(stack, visitor); // Some classes might be unreachable. Unfortunately, we have to keep them around for // one more collection, because during the sweep phase, instances of unreachable // classes might still end up looking at the class. So we visit those unreachable // classes remove them from the list of class objects so that it can be freed // in the next collection. std::vector<BoxedClass*> classes_to_remove; for (BoxedClass* cls : class_objects) { GCAllocation* al = GCAllocation::fromUserData(cls); if (!isMarked(al)) { visitor.visit(cls); classes_to_remove.push_back(cls); } } // We added new objects to the stack again from visiting classes so we nee to do // another (mini) traversal. graphTraversalMarking(stack, visitor); for (BoxedClass* cls : classes_to_remove) { class_objects.erase(cls); } // The above algorithm could fail if we have a class and a metaclass -- they might // both have been added to the classes to remove. In case that happens, make sure // that the metaclass is retained for at least another collection. for (BoxedClass* cls : classes_to_remove) { class_objects.insert(cls->cls); } // Objects with finalizers cannot be freed in any order. During the call to a finalizer // of an object, the finalizer expects the object's references to still point to valid // memory. So we root objects whose finalizers need to be called by placing them in a // pending finalization list. orderFinalizers(); #ifndef NVALGRIND VALGRIND_ENABLE_ERROR_REPORTING; #endif long us = _t.end(); sc_us.log(us); } static void sweepPhase(std::vector<Box*>& weakly_referenced) { static StatCounter sc_us("us_gc_sweep_phase"); Timer _t("sweepPhase", /*min_usec=*/10000); // we need to use the allocator here because these objects are referenced only here, and calling the weakref // callbacks could start another gc global_heap.freeUnmarked(weakly_referenced); long us = _t.end(); sc_us.log(us); } bool gcIsEnabled() { return gc_enabled; } void enableGC() { gc_enabled = true; } void disableGC() { gc_enabled = false; } void startGCUnexpectedRegion() { RELEASE_ASSERT(!should_not_reenter_gc, ""); should_not_reenter_gc = true; } void endGCUnexpectedRegion() { RELEASE_ASSERT(should_not_reenter_gc, ""); should_not_reenter_gc = false; } void runCollection() { static StatCounter sc_us("us_gc_collections"); static StatCounter sc("gc_collections"); sc.log(); UNAVOIDABLE_STAT_TIMER(t0, "us_timer_gc_collection"); ncollections++; if (VERBOSITY("gc") >= 2) printf("Collection #%d\n", ncollections); // The bulk of the GC work is not reentrant-safe. // In theory we should never try to reenter that section, but it's happened due to bugs, // which show up as very-hard-to-understand gc issues. // So keep track if we're in the non-reentrant section and abort if we try to go back in. // We could also just skip the collection if we're currently in the gc, but I think if we // run into this case it's way more likely that it's a bug than something we should ignore. RELEASE_ASSERT(!should_not_reenter_gc, ""); should_not_reenter_gc = true; // begin non-reentrant section Timer _t("collecting", /*min_usec=*/10000); #if TRACE_GC_MARKING #if 1 // separate log file per collection char tracefn_buf[80]; snprintf(tracefn_buf, sizeof(tracefn_buf), "gc_trace_%d.%03d.txt", getpid(), ncollections); trace_fp = fopen(tracefn_buf, "w"); #else // overwrite previous log file with each collection trace_fp = fopen("gc_trace.txt", "w"); #endif #endif global_heap.prepareForCollection(); // Finalizers might have been called since the last GC. // Normally we invalidate the list everytime we call a batch of objects with finalizers. // However, there are some edge cases where that isn't sufficient, such as a GC being triggered // inside a finalizer call. To be safe, it's better to invalidate the list again. invalidateOrderedFinalizerList(); markPhase(); // The sweep phase will not free weakly-referenced objects, so that we can inspect their // weakrefs_list. We want to defer looking at those lists until the end of the sweep phase, // since the deallocation of other objects (namely, the weakref objects themselves) can affect // those lists, and we want to see the final versions. std::vector<Box*> weakly_referenced; sweepPhase(weakly_referenced); // Handle weakrefs in two passes: // - first, find all of the weakref objects whose callbacks we need to call. we need to iterate // over the garbage-and-corrupt-but-still-alive weakly_referenced list in order to find these objects, // so the gc is not reentrant during this section. after this we discard that list. // - the callbacks are called later, along with the finalizers for (auto o : weakly_referenced) { assert(isValidGCObject(o)); prepareWeakrefCallbacks(o); global_heap.free(GCAllocation::fromUserData(o)); } #if TRACE_GC_MARKING fclose(trace_fp); trace_fp = NULL; #endif should_not_reenter_gc = false; // end non-reentrant section global_heap.cleanupAfterCollection(); if (VERBOSITY("gc") >= 2) printf("Collection #%d done\n\n", ncollections); long us = _t.end(); sc_us.log(us); // dumpHeapStatistics(); } } // namespace gc } // namespace pyston
// Copyright (c) 2014-2017 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <qt/networkstyle.h> #include <qt/guiconstants.h> #include <QApplication> static const struct { const char *networkId; const char *appName; const int iconColorHueShift; const int iconColorSaturationReduction; const char *titleAddText; } network_styles[] = { {"main", QAPP_APP_NAME_DEFAULT, 0, 0, ""}, {"test", QAPP_APP_NAME_TESTNET, 0, 0, QT_TRANSLATE_NOOP("SplashScreen", "[testnet]")}, {"regtest", QAPP_APP_NAME_TESTNET, 60, 1, "[regtest]"} }; static const unsigned network_styles_count = sizeof(network_styles)/sizeof(*network_styles); // titleAddText needs to be const char* for tr() NetworkStyle::NetworkStyle(const QString &_appName, const int iconColorHueShift, const int iconColorSaturationReduction, const char *_titleAddText): appName(_appName), titleAddText(qApp->translate("SplashScreen", _titleAddText)) { // load pixmap QPixmap pixmap; if (std::char_traits<char>::length(_titleAddText) == 0) { pixmap.load(":/icons/bitcoin"); } else { pixmap.load(":/icons/bitmoney_splash"); } if(iconColorHueShift != 0 && iconColorSaturationReduction != 0) { // generate QImage from QPixmap QImage img = pixmap.toImage(); int h,s,l,a; // traverse though lines for(int y=0;y<img.height();y++) { QRgb *scL = reinterpret_cast< QRgb *>( img.scanLine( y ) ); // loop through pixels for(int x=0;x<img.width();x++) { // preserve alpha because QColor::getHsl doesn't return the alpha value a = qAlpha(scL[x]); QColor col(scL[x]); // get hue value col.getHsl(&h,&s,&l); // rotate color on RGB color circle // 70° should end up with the typical "testnet" green h+=iconColorHueShift; // change saturation value if(s>iconColorSaturationReduction) { s -= iconColorSaturationReduction; } col.setHsl(h,s,l,a); // set the pixel scL[x] = col.rgba(); } } //convert back to QPixmap #if QT_VERSION >= 0x040700 pixmap.convertFromImage(img); #else pixmap = QPixmap::fromImage(img); #endif } appIcon = QIcon(pixmap); trayAndWindowIcon = QIcon(pixmap.scaled(QSize(256,256))); } const NetworkStyle *NetworkStyle::instantiate(const QString &networkId) { for (unsigned x=0; x<network_styles_count; ++x) { if (networkId == network_styles[x].networkId) { return new NetworkStyle( network_styles[x].appName, network_styles[x].iconColorHueShift, network_styles[x].iconColorSaturationReduction, network_styles[x].titleAddText); } } return 0; }
/********************* */ /*! \file lazy_bitblaster.cpp ** \verbatim ** Original author: Liana Hadarean ** Major contributors: none ** Minor contributors (to current version): Morgan Deters ** This file is part of the CVC4 project. ** Copyright (c) 2009-2014 New York University and The University of Iowa ** See the file COPYING in the top-level source directory for licensing ** information.\endverbatim ** ** \brief Bitblaster for the lazy bv solver. ** ** Bitblaster for the lazy bv solver. **/ #include "cvc4_private.h" #include "bitblaster_template.h" #include "theory_bv_utils.h" #include "theory/rewriter.h" #include "prop/cnf_stream.h" #include "prop/sat_solver.h" #include "prop/sat_solver_factory.h" #include "theory/bv/theory_bv.h" #include "theory/bv/options.h" #include "theory/theory_model.h" #include "theory/bv/abstraction.h" using namespace CVC4; using namespace CVC4::theory; using namespace CVC4::theory::bv; TLazyBitblaster::TLazyBitblaster(context::Context* c, bv::TheoryBV* bv, const std::string name, bool emptyNotify) : TBitblaster<Node>() , d_bv(bv) , d_ctx(c) , d_assertedAtoms(new(true) context::CDList<prop::SatLiteral>(c)) , d_explanations(new(true) ExplanationMap(c)) , d_variables() , d_bbAtoms() , d_abstraction(NULL) , d_emptyNotify(emptyNotify) , d_name(name) , d_statistics(name) { d_satSolver = prop::SatSolverFactory::createMinisat(c, name); d_nullRegistrar = new prop::NullRegistrar(); d_nullContext = new context::Context(); d_cnfStream = new prop::TseitinCnfStream(d_satSolver, d_nullRegistrar, d_nullContext); prop::BVSatSolverInterface::Notify* notify = d_emptyNotify ? (prop::BVSatSolverInterface::Notify*) new MinisatEmptyNotify() : (prop::BVSatSolverInterface::Notify*) new MinisatNotify(d_cnfStream, bv, this); d_satSolver->setNotify(notify); } void TLazyBitblaster::setAbstraction(AbstractionModule* abs) { d_abstraction = abs; } TLazyBitblaster::~TLazyBitblaster() { delete d_cnfStream; delete d_nullRegistrar; delete d_nullContext; delete d_satSolver; } /** * Bitblasts the atom, assigns it a marker literal, adding it to the SAT solver * NOTE: duplicate clauses are not detected because of marker literal * @param node the atom to be bitblasted * */ void TLazyBitblaster::bbAtom(TNode node) { node = node.getKind() == kind::NOT? node[0] : node; if (hasBBAtom(node)) { return; } // make sure it is marked as an atom addAtom(node); Debug("bitvector-bitblast") << "Bitblasting node " << node <<"\n"; ++d_statistics.d_numAtoms; /// if we are using bit-vector abstraction bit-blast the original interpretation if (options::bvAbstraction() && d_abstraction != NULL && d_abstraction->isAbstraction(node)) { // node must be of the form P(args) = bv1 Node expansion = Rewriter::rewrite(d_abstraction->getInterpretation(node)); Node atom_bb; if (expansion.getKind() == kind::CONST_BOOLEAN) { atom_bb = expansion; } else { Assert (expansion.getKind() == kind::AND); std::vector<Node> atoms; for (unsigned i = 0; i < expansion.getNumChildren(); ++i) { Node normalized_i = Rewriter::rewrite(expansion[i]); Node atom_i = normalized_i.getKind() != kind::CONST_BOOLEAN ? Rewriter::rewrite(d_atomBBStrategies[normalized_i.getKind()](normalized_i, this)) : normalized_i; atoms.push_back(atom_i); } atom_bb = utils::mkAnd(atoms); } Assert (!atom_bb.isNull()); Node atom_definition = utils::mkNode(kind::IFF, node, atom_bb); storeBBAtom(node, atom_bb); d_cnfStream->convertAndAssert(atom_definition, false, false); return; } // the bitblasted definition of the atom Node normalized = Rewriter::rewrite(node); Node atom_bb = normalized.getKind() != kind::CONST_BOOLEAN ? Rewriter::rewrite(d_atomBBStrategies[normalized.getKind()](normalized, this)) : normalized; // asserting that the atom is true iff the definition holds Node atom_definition = utils::mkNode(kind::IFF, node, atom_bb); storeBBAtom(node, atom_bb); d_cnfStream->convertAndAssert(atom_definition, false, false); } void TLazyBitblaster::storeBBAtom(TNode atom, Node atom_bb) { // no need to store the definition for the lazy bit-blaster d_bbAtoms.insert(atom); } bool TLazyBitblaster::hasBBAtom(TNode atom) const { return d_bbAtoms.find(atom) != d_bbAtoms.end(); } void TLazyBitblaster::makeVariable(TNode var, Bits& bits) { Assert(bits.size() == 0); for (unsigned i = 0; i < utils::getSize(var); ++i) { bits.push_back(utils::mkBitOf(var, i)); } d_variables.insert(var); } uint64_t TLazyBitblaster::computeAtomWeight(TNode node, NodeSet& seen) { node = node.getKind() == kind::NOT? node[0] : node; Node atom_bb = Rewriter::rewrite(d_atomBBStrategies[node.getKind()](node, this)); uint64_t size = utils::numNodes(atom_bb, seen); return size; } // cnf conversion ensures the atom represents itself Node TLazyBitblaster::getBBAtom(TNode node) const { return node; } void TLazyBitblaster::bbTerm(TNode node, Bits& bits) { if (hasBBTerm(node)) { getBBTerm(node, bits); return; } Debug("bitvector-bitblast") << "Bitblasting node " << node <<"\n"; ++d_statistics.d_numTerms; d_termBBStrategies[node.getKind()] (node, bits,this); Assert (bits.size() == utils::getSize(node)); storeBBTerm(node, bits); } /// Public methods void TLazyBitblaster::addAtom(TNode atom) { d_cnfStream->ensureLiteral(atom); prop::SatLiteral lit = d_cnfStream->getLiteral(atom); d_satSolver->addMarkerLiteral(lit); } void TLazyBitblaster::explain(TNode atom, std::vector<TNode>& explanation) { prop::SatLiteral lit = d_cnfStream->getLiteral(atom); ++(d_statistics.d_numExplainedPropagations); if (options::bvEagerExplanations()) { Assert (d_explanations->find(lit) != d_explanations->end()); const std::vector<prop::SatLiteral>& literal_explanation = (*d_explanations)[lit].get(); for (unsigned i = 0; i < literal_explanation.size(); ++i) { explanation.push_back(d_cnfStream->getNode(literal_explanation[i])); } return; } std::vector<prop::SatLiteral> literal_explanation; d_satSolver->explain(lit, literal_explanation); for (unsigned i = 0; i < literal_explanation.size(); ++i) { explanation.push_back(d_cnfStream->getNode(literal_explanation[i])); } } /* * Asserts the clauses corresponding to the atom to the Sat Solver * by turning on the marker literal (i.e. setting it to false) * @param node the atom to be asserted * */ bool TLazyBitblaster::propagate() { return d_satSolver->propagate() == prop::SAT_VALUE_TRUE; } bool TLazyBitblaster::assertToSat(TNode lit, bool propagate) { // strip the not TNode atom; if (lit.getKind() == kind::NOT) { atom = lit[0]; } else { atom = lit; } Assert (hasBBAtom(atom)); prop::SatLiteral markerLit = d_cnfStream->getLiteral(atom); if(lit.getKind() == kind::NOT) { markerLit = ~markerLit; } Debug("bitvector-bb") << "TheoryBV::TLazyBitblaster::assertToSat asserting node: " << atom <<"\n"; Debug("bitvector-bb") << "TheoryBV::TLazyBitblaster::assertToSat with literal: " << markerLit << "\n"; prop::SatValue ret = d_satSolver->assertAssumption(markerLit, propagate); d_assertedAtoms->push_back(markerLit); return ret == prop::SAT_VALUE_TRUE || ret == prop::SAT_VALUE_UNKNOWN; } /** * Calls the solve method for the Sat Solver. * passing it the marker literals to be asserted * * @return true for sat, and false for unsat */ bool TLazyBitblaster::solve() { if (Trace.isOn("bitvector")) { Trace("bitvector") << "TLazyBitblaster::solve() asserted atoms "; context::CDList<prop::SatLiteral>::const_iterator it = d_assertedAtoms->begin(); for (; it != d_assertedAtoms->end(); ++it) { Trace("bitvector") << " " << d_cnfStream->getNode(*it) << "\n"; } } Debug("bitvector") << "TLazyBitblaster::solve() asserted atoms " << d_assertedAtoms->size() <<"\n"; return prop::SAT_VALUE_TRUE == d_satSolver->solve(); } prop::SatValue TLazyBitblaster::solveWithBudget(unsigned long budget) { if (Trace.isOn("bitvector")) { Trace("bitvector") << "TLazyBitblaster::solveWithBudget() asserted atoms "; context::CDList<prop::SatLiteral>::const_iterator it = d_assertedAtoms->begin(); for (; it != d_assertedAtoms->end(); ++it) { Trace("bitvector") << " " << d_cnfStream->getNode(*it) << "\n"; } } Debug("bitvector") << "TLazyBitblaster::solveWithBudget() asserted atoms " << d_assertedAtoms->size() <<"\n"; return d_satSolver->solve(budget); } void TLazyBitblaster::getConflict(std::vector<TNode>& conflict) { prop::SatClause conflictClause; d_satSolver->getUnsatCore(conflictClause); for (unsigned i = 0; i < conflictClause.size(); i++) { prop::SatLiteral lit = conflictClause[i]; TNode atom = d_cnfStream->getNode(lit); Node not_atom; if (atom.getKind() == kind::NOT) { not_atom = atom[0]; } else { not_atom = NodeManager::currentNM()->mkNode(kind::NOT, atom); } conflict.push_back(not_atom); } } TLazyBitblaster::Statistics::Statistics(const std::string& prefix) : d_numTermClauses("theory::bv::"+prefix+"::NumberOfTermSatClauses", 0), d_numAtomClauses("theory::bv::"+prefix+"::NumberOfAtomSatClauses", 0), d_numTerms("theory::bv::"+prefix+"::NumberOfBitblastedTerms", 0), d_numAtoms("theory::bv::"+prefix+"::NumberOfBitblastedAtoms", 0), d_numExplainedPropagations("theory::bv::"+prefix+"::NumberOfExplainedPropagations", 0), d_numBitblastingPropagations("theory::bv::"+prefix+"::NumberOfBitblastingPropagations", 0), d_bitblastTimer("theory::bv::"+prefix+"::BitblastTimer") { StatisticsRegistry::registerStat(&d_numTermClauses); StatisticsRegistry::registerStat(&d_numAtomClauses); StatisticsRegistry::registerStat(&d_numTerms); StatisticsRegistry::registerStat(&d_numAtoms); StatisticsRegistry::registerStat(&d_numExplainedPropagations); StatisticsRegistry::registerStat(&d_numBitblastingPropagations); StatisticsRegistry::registerStat(&d_bitblastTimer); } TLazyBitblaster::Statistics::~Statistics() { StatisticsRegistry::unregisterStat(&d_numTermClauses); StatisticsRegistry::unregisterStat(&d_numAtomClauses); StatisticsRegistry::unregisterStat(&d_numTerms); StatisticsRegistry::unregisterStat(&d_numAtoms); StatisticsRegistry::unregisterStat(&d_numExplainedPropagations); StatisticsRegistry::unregisterStat(&d_numBitblastingPropagations); StatisticsRegistry::unregisterStat(&d_bitblastTimer); } bool TLazyBitblaster::MinisatNotify::notify(prop::SatLiteral lit) { if(options::bvEagerExplanations()) { // compute explanation if (d_lazyBB->d_explanations->find(lit) == d_lazyBB->d_explanations->end()) { std::vector<prop::SatLiteral> literal_explanation; d_lazyBB->d_satSolver->explain(lit, literal_explanation); d_lazyBB->d_explanations->insert(lit, literal_explanation); } else { // we propagated it at a lower level return true; } } ++(d_lazyBB->d_statistics.d_numBitblastingPropagations); TNode atom = d_cnf->getNode(lit); return d_bv->storePropagation(atom, SUB_BITBLAST); } void TLazyBitblaster::MinisatNotify::notify(prop::SatClause& clause) { if (clause.size() > 1) { NodeBuilder<> lemmab(kind::OR); for (unsigned i = 0; i < clause.size(); ++ i) { lemmab << d_cnf->getNode(clause[i]); } Node lemma = lemmab; d_bv->d_out->lemma(lemma); } else { d_bv->d_out->lemma(d_cnf->getNode(clause[0])); } } void TLazyBitblaster::MinisatNotify::safePoint() { d_bv->d_out->safePoint(); } EqualityStatus TLazyBitblaster::getEqualityStatus(TNode a, TNode b) { // We don't want to bit-blast every possibly expensive term for the sake of equality checking if (hasBBTerm(a) && hasBBTerm(b)) { Bits a_bits, b_bits; getBBTerm(a, a_bits); getBBTerm(b, b_bits); theory::EqualityStatus status = theory::EQUALITY_TRUE_IN_MODEL; for (unsigned i = 0; i < a_bits.size(); ++ i) { if (d_cnfStream->hasLiteral(a_bits[i]) && d_cnfStream->hasLiteral(b_bits[i])) { prop::SatLiteral a_lit = d_cnfStream->getLiteral(a_bits[i]); prop::SatValue a_lit_value = d_satSolver->value(a_lit); if (a_lit_value != prop::SAT_VALUE_UNKNOWN) { prop::SatLiteral b_lit = d_cnfStream->getLiteral(b_bits[i]); prop::SatValue b_lit_value = d_satSolver->value(b_lit); if (b_lit_value != prop::SAT_VALUE_UNKNOWN) { if (a_lit_value != b_lit_value) { return theory::EQUALITY_FALSE_IN_MODEL; } } else { status = theory::EQUALITY_UNKNOWN; } } { status = theory::EQUALITY_UNKNOWN; } } else { status = theory::EQUALITY_UNKNOWN; } } return status; } else { return theory::EQUALITY_UNKNOWN; } } bool TLazyBitblaster::isSharedTerm(TNode node) { return d_bv->d_sharedTermsSet.find(node) != d_bv->d_sharedTermsSet.end(); } bool TLazyBitblaster::hasValue(TNode a) { Assert (hasBBTerm(a)); Bits bits; getBBTerm(a, bits); for (int i = bits.size() -1; i >= 0; --i) { prop::SatValue bit_value; if (d_cnfStream->hasLiteral(bits[i])) { prop::SatLiteral bit = d_cnfStream->getLiteral(bits[i]); bit_value = d_satSolver->value(bit); if (bit_value == prop::SAT_VALUE_UNKNOWN) return false; } else { return false; } } return true; } /** * Returns the value a is currently assigned to in the SAT solver * or null if the value is completely unassigned. * * @param a * @param fullModel whether to create a "full model," i.e., add * constants to equivalence classes that don't already have them * * @return */ Node TLazyBitblaster::getVarValue(TNode a, bool fullModel) { if (!hasBBTerm(a)) { Assert(isSharedTerm(a)); return Node(); } Bits bits; getBBTerm(a, bits); Integer value(0); for (int i = bits.size() -1; i >= 0; --i) { prop::SatValue bit_value; if (d_cnfStream->hasLiteral(bits[i])) { prop::SatLiteral bit = d_cnfStream->getLiteral(bits[i]); bit_value = d_satSolver->value(bit); Assert (bit_value != prop::SAT_VALUE_UNKNOWN); } else { // the bit is unconstrainted so we can give it an arbitrary value bit_value = prop::SAT_VALUE_FALSE; } Integer bit_int = bit_value == prop::SAT_VALUE_TRUE ? Integer(1) : Integer(0); value = value * 2 + bit_int; } return utils::mkConst(BitVector(bits.size(), value)); } void TLazyBitblaster::collectModelInfo(TheoryModel* m, bool fullModel) { TNodeSet::iterator it = d_variables.begin(); for (; it!= d_variables.end(); ++it) { TNode var = *it; if (Theory::theoryOf(var) == theory::THEORY_BV || isSharedTerm(var)) { Node const_value = getVarValue(var, fullModel); if(const_value == Node()) { if( fullModel ){ // if the value is unassigned just set it to zero const_value = utils::mkConst(BitVector(utils::getSize(var), 0u)); } } if(const_value != Node()) { Debug("bitvector-model") << "TLazyBitblaster::collectModelInfo (assert (= " << var << " " << const_value << "))\n"; m->assertEquality(var, const_value, true); } } } } void TLazyBitblaster::clearSolver() { Assert (d_ctx->getLevel() == 0); delete d_satSolver; delete d_cnfStream; d_assertedAtoms->deleteSelf(); d_assertedAtoms = new(true) context::CDList<prop::SatLiteral>(d_ctx); d_explanations->deleteSelf(); d_explanations = new(true) ExplanationMap(d_ctx); d_bbAtoms.clear(); d_variables.clear(); d_termCache.clear(); // recreate sat solver d_satSolver = prop::SatSolverFactory::createMinisat(d_ctx); d_cnfStream = new prop::TseitinCnfStream(d_satSolver, new prop::NullRegistrar(), new context::Context()); prop::BVSatSolverInterface::Notify* notify = d_emptyNotify ? (prop::BVSatSolverInterface::Notify*) new MinisatEmptyNotify() : (prop::BVSatSolverInterface::Notify*) new MinisatNotify(d_cnfStream, d_bv, this); d_satSolver->setNotify(notify); }
//=---------------------------------------------------------------------= // // $Id$ $Name$ // // The contents of this file are subject to the AAF SDK Public Source // License Agreement Version 2.0 (the "License"); You may not use this // file except in compliance with the License. The License is available // in AAFSDKPSL.TXT, or you may obtain a copy of the License from the // Advanced Media Workflow Association, Inc., or its successor. // // Software distributed under the License is distributed on an "AS IS" // basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See // the License for the specific language governing rights and limitations // under the License. Refer to Section 3.3 of the License for proper use // of this Exhibit. // // WARNING: Please contact the Advanced Media Workflow Association, // Inc., for more information about any additional licenses to // intellectual property covering the AAF Standard that may be required // to create and distribute AAF compliant products. // (http://www.amwa.tv/policies). // // Copyright Notices: // The Original Code of this file is Copyright 1998-2009, licensor of the // Advanced Media Workflow Association. All rights reserved. // // //=---------------------------------------------------------------------= #ifndef OM_NO_STRUCTURED_STORAGE #if defined(OM_USE_GSF_SS) #include "OMAssertions.h" #include "OMGSFStructuredStorage.h" #include "OMUtilities.h" #ifdef __cplusplus extern "C" { #endif #include <gsf/gsf-utils.h> #include <gsf/gsf-input-stdio.h> #include <gsf/gsf-infile.h> #include <gsf/gsf-input-impl.h> #include <gsf/gsf-infile-msole.h> #include <gsf/gsf-output-stdio.h> #include <gsf/gsf-outfile.h> #include <gsf/gsf-outfile-msole.h> #ifdef __cplusplus } #endif typedef struct tag_GSF_GUID { unsigned int Data1; unsigned short Data2; unsigned short Data3; unsigned char Data4[8]; } GSF_GUID; typedef GSF_GUID GSF_CLSID; static inline HRESULT makeStatus(int status) { TRACE("makeStatus"); if (GSTG_OK!=status) { return (status | 0x80000000L); } return GSTG_OK; } static int _GSFIsInitialized; // automatically initialized to 0 void OMGSFInitialize(void) { if (!_GSFIsInitialized) { gsf_init(); _GSFIsInitialized = 1; } } void OMGSFFinalize(void) { if (_GSFIsInitialized) { gsf_shutdown (); _GSFIsInitialized = 0; } } // GSF Storage OMGSFIStorage::OMGSFIStorage(GsfStorage *in_storage, GsfAccessMode mode, const char *sname) : _storage(in_storage), _mode(mode), _referenceCount(1) { strcpy(_storageName, sname); TRACE("OMGSFIStorage::OMGSFIStorage"); PRECONDITION("Valid reference count", _referenceCount == 1); }; OMGSFIStorage::~OMGSFIStorage() { TRACE("OMGSFIStorage::~OMGSFIStorage"); PRECONDITION("Valid reference count", _referenceCount == 0); PRECONDITION("Non-Root storage closed", _storage == 0); } HRESULT STDMETHODCALLTYPE OMGSFIStorage::QueryInterface(REFIID /* riid */, void** ppvObject) { TRACE("OMGSFIStorage::QueryInterface"); *ppvObject = 0; return E_NOINTERFACE; } ULONG STDMETHODCALLTYPE OMGSFIStorage::AddRef(void) { TRACE("OMGSFIStorage::AddRef"); ++_referenceCount; return _referenceCount; } ULONG STDMETHODCALLTYPE OMGSFIStorage::Release(void) { TRACE("OMGSFIStorage::Release"); ULONG result = --_referenceCount; if (_referenceCount == 0) { if (_storage != 0) { if (GSF_IS_OUTPUT(_storage)) { gsf_output_close (GSF_OUTPUT(_storage)); } g_object_unref (G_OBJECT(_storage)); _storage = 0; } delete this; } return result; } HRESULT STDMETHODCALLTYPE OMGSFIStorage::StgCreateStorageEx( const TCHAR FAR* in_filename, OMFile::OMAccessMode in_accessMode, void **out_storage, ULONG in_sectorSize) { TRACE("OMGSFIStorage::StgCreateStorageEx"); PRECONDITION("Valid access mode", in_accessMode == OMFile::writeOnlyMode); GsfStorage *storage = 0; *out_storage = 0; char storageName[FILENAME_MAX]; #ifndef OM_UNICODE_APIS strncpy (storageName, in_filename, sizeof(storageName) -1); storageName[sizeof(storageName) -1] = '\0'; #else convertWideStringToString (storageName, in_filename, FILENAME_MAX); #endif int status = GSTG_OK; GError *err; GsfOutput *output = GSF_OUTPUT (gsf_output_stdio_new (storageName, &err)); if (output != NULL) { storage = GSF_OUTFILE (gsf_outfile_msole_new_full ( output, in_sectorSize, // sector size - 512 or 4096 bytes 64)); // mini-sector size always 64 bytes g_object_unref (G_OBJECT (output)); } else status = GSTG_ERROR; if (status == GSTG_OK) { OMGSFIStorage *newStorage = new OMGSFIStorage (storage, GSF_WRITE, storageName); *out_storage = newStorage; } return makeStatus(status); } HRESULT STDMETHODCALLTYPE OMGSFIStorage::StgOpenStorageEx( const TCHAR FAR* in_filename, OMFile::OMAccessMode in_accessMode, void **out_storage) { TRACE("OMGSFIStorage::StgOpenStorageEx"); PRECONDITION("Valid access mode", in_accessMode == OMFile::readOnlyMode); GsfStorage *storage = 0; *out_storage = 0; char storageName[FILENAME_MAX]; #ifndef OM_UNICODE_APIS strncpy (storageName, in_filename, sizeof(storageName) -1); storageName[sizeof(storageName) -1] = '\0'; #else convertWideStringToString (storageName, in_filename, FILENAME_MAX); #endif GError *err; int status = GSTG_OK; GsfInput *input = GSF_INPUT (gsf_input_stdio_new (storageName, &err)); if (input != NULL) { input = gsf_input_uncompress (input); storage = GSF_INFILE (gsf_infile_msole_new (input, &err)); g_object_unref (G_OBJECT (input)); } else status = GSTG_ERROR; if (status == GSTG_OK) { OMGSFIStorage *newStorage = new OMGSFIStorage (storage, GSF_READ, storageName); *out_storage = newStorage; } return makeStatus(status); } HRESULT STDMETHODCALLTYPE OMGSFIStorage::StgCreateStorageInOMRawStorage( const OMRawStorage* in_pRaw, OMFile::OMAccessMode in_accessMode, void** out_storage, ULONG in_sectorSize) { TRACE("OMGSFIStorage::StgCreateStorageInOMRawStorage"); return STG_E_UNIMPLEMENTEDFUNCTION; } HRESULT STDMETHODCALLTYPE OMGSFIStorage::StgOpenStorageInOMRawStorage( const OMRawStorage* in_pRaw, OMFile::OMAccessMode in_accessMode, void** out_storage) { TRACE("OMGSFIStorage::StgOpenStorageInOMRawStorage"); return STG_E_UNIMPLEMENTEDFUNCTION; } HRESULT STDMETHODCALLTYPE OMGSFIStorage::CreateStream( const TCHAR FAR* pwcsName, DWORD grfMode, DWORD reserved1, DWORD reserved2, IStream FAR *FAR *ppstm) { TRACE("OMGSFIStorage::CreateStream"); // TODO: not interpreting grfMode GsfStream *stream; int status = GSTG_OK; char streamName[FILENAME_MAX]; #ifndef OM_UNICODE_APIS strncpy (streamName, pwcsName, sizeof(streamName) -1); streamName[sizeof(streamName) -1] = '\0'; #else convertWideStringToString (streamName, pwcsName, FILENAME_MAX); #endif ASSERT ("Creating a stream in a WriteOnly GSF Storage", _mode == GSF_WRITE); if ((stream = gsf_outfile_new_child (GSF_OUTFILE(_storage), streamName, false))) { OMGSFIStream *newStream = new OMGSFIStream (stream, _mode, streamName); *ppstm = newStream; } else status = GSTG_ERROR; return makeStatus(status); } HRESULT STDMETHODCALLTYPE OMGSFIStorage::OpenStream( const TCHAR FAR* pwcsName, void FAR *reserved1, DWORD grfMode, DWORD reserved2, IStream FAR *FAR *ppstm) { TRACE("OMGSFIStorage::OpenStream"); // TODO: not interpreting grfMode GsfStream *stream; int status = GSTG_OK; char streamName[FILENAME_MAX]; #ifndef OM_UNICODE_APIS strncpy (streamName, pwcsName, sizeof(streamName) -1); streamName[sizeof(streamName) -1] = '\0'; #else convertWideStringToString (streamName, pwcsName, FILENAME_MAX); #endif ASSERT ("Opening a stream in a ReadOnly GSF Storage", _mode == GSF_READ); if ((stream = gsf_infile_child_by_name (GSF_INFILE(_storage), streamName))) { OMGSFIStream *newStream = new OMGSFIStream (stream, _mode, streamName); *ppstm = newStream; } else status = GSTG_ERROR; return makeStatus(status); } HRESULT STDMETHODCALLTYPE OMGSFIStorage::CreateStorage( const TCHAR FAR* pwcsName, DWORD grfMode, DWORD reserved1, DWORD reserved2, IStorage FAR *FAR *ppstg) { TRACE("OMGSFIStorage::CreateStorage"); // TODO: not interpreting grfMode int status = GSTG_OK; GsfStorage *storage = 0; *ppstg = 0; char storageName[FILENAME_MAX]; #ifndef OM_UNICODE_APIS strncpy (storageName, pwcsName, sizeof(storageName) -1); storageName[sizeof(storageName) -1] = '\0'; #else convertWideStringToString (storageName, pwcsName, FILENAME_MAX); #endif ASSERT ("Creating Storage in WriteOnly GSF Storage", _mode == GSF_WRITE); if ((storage = gsf_outfile_new_child (GSF_OUTFILE(_storage), storageName, true))) { OMGSFIStorage *newStorage = new OMGSFIStorage (storage, _mode, storageName); *ppstg = newStorage; } else status = GSTG_ERROR; return makeStatus(status); } HRESULT STDMETHODCALLTYPE OMGSFIStorage::OpenStorage( const TCHAR FAR* pwcsName, IStorage FAR *pstgPriority, DWORD grfMode, SNB snbExclude, DWORD reserved, IStorage FAR *FAR *ppstg) { TRACE("OMGSFIStorage::OpenStorage"); // TODO: not interpreting grfMode int status = GSTG_OK; GsfStorage *storage = 0; *ppstg = 0; char storageName[FILENAME_MAX]; #ifndef OM_UNICODE_APIS strncpy (storageName, pwcsName, sizeof(storageName) -1); storageName[sizeof(storageName) -1] = '\0'; #else convertWideStringToString (storageName, pwcsName, FILENAME_MAX); #endif ASSERT ("Opening Storage in ReadOnly GSF Storage", _mode == GSF_READ); if ((storage = gsf_infile_child_by_name (GSF_INFILE(_storage), storageName))) { OMGSFIStorage *newStorage = new OMGSFIStorage (storage, _mode, storageName); *ppstg = newStorage; } else status = GSTG_ERROR; return makeStatus(status); } HRESULT STDMETHODCALLTYPE OMGSFIStorage::CopyTo( DWORD ciidExclude, IID const FAR *rgiidExclude, SNB snbExclude, IStorage FAR *pstgDest) { TRACE("OMGSFIStorage::CopyTo"); return STG_E_UNIMPLEMENTEDFUNCTION; } HRESULT STDMETHODCALLTYPE OMGSFIStorage::MoveElementTo( TCHAR const FAR* lpszName, IStorage FAR *pstgDest, TCHAR const FAR* lpszNewName, DWORD grfFlags) { TRACE("OMGSFIStorage::MoveElementTo"); return STG_E_UNIMPLEMENTEDFUNCTION; } HRESULT STDMETHODCALLTYPE OMGSFIStorage::Commit (DWORD grfCommitFlags) { TRACE("OMGSFIStorage::Commit"); return STG_E_UNIMPLEMENTEDFUNCTION; } HRESULT STDMETHODCALLTYPE OMGSFIStorage::Revert (void) { TRACE("OMGSFIStorage::Revert"); return STG_E_UNIMPLEMENTEDFUNCTION; } HRESULT STDMETHODCALLTYPE OMGSFIStorage::EnumElements( DWORD reserved1, void FAR *reserved2, DWORD reserved3, IEnumSTATSTG FAR *FAR *ppenm) { TRACE("OMGSFIStorage::EnumElements"); return STG_E_UNIMPLEMENTEDFUNCTION; } HRESULT STDMETHODCALLTYPE OMGSFIStorage::DestroyElement(const TCHAR FAR* pwcsName) { TRACE("OMGSFIStorage::DestroyElement"); return STG_E_UNIMPLEMENTEDFUNCTION; } HRESULT STDMETHODCALLTYPE OMGSFIStorage::RenameElement( const TCHAR FAR* pwcsOldName, const TCHAR FAR* pwcsNewName ) { TRACE("OMGSFIStorage::RenameElement"); return STG_E_UNIMPLEMENTEDFUNCTION; } HRESULT STDMETHODCALLTYPE OMGSFIStorage::SetElementTimes( const TCHAR FAR *lpszName, FILETIME const FAR *pctime, FILETIME const FAR *patime, FILETIME const FAR *pmtime ) { TRACE("OMGSFIStorage::SetElementTimes"); return STG_E_UNIMPLEMENTEDFUNCTION; } // libgsf treats clsid as an array of 16 bytes storing it unchanged on disk. // The container spec requires a little-endian ordering of clsid on disk // so on bigendian machines we must reorder the class id. static inline void reorder_clsid(unsigned char *id) { if (hostByteOrder() == littleEndian) return; unsigned char t[8]; memmove(t, &id[0], 8); id[0] = t[3]; // reorder Data1 int32_t id[1] = t[2]; id[2] = t[1]; id[3] = t[0]; id[4] = t[5]; // reorder Data2 int16_t id[5] = t[4]; id[6] = t[7]; // reorder Data3 int16_t id[7] = t[6]; // Data4 is an array of char so remains unchanged } HRESULT STDMETHODCALLTYPE OMGSFIStorage::SetClass (REFCLSID clsid) { TRACE("OMGSFIStorage::SetClass"); ASSERT ("Calling SetClass in a WriteOnly GSF Storage", _mode == GSF_WRITE); unsigned char tmp_clsid[16]; memmove(&tmp_clsid, &clsid, sizeof(tmp_clsid)); reorder_clsid(tmp_clsid); int status = GSTG_OK; if (!gsf_outfile_msole_set_class_id (GSF_OUTFILE_MSOLE(_storage), tmp_clsid)) status = GSTG_ERROR; return makeStatus(status); } HRESULT STDMETHODCALLTYPE OMGSFIStorage::SetStateBits( DWORD grfStateBits, DWORD grfMask ) { TRACE("OMGSFIStorage::SetStateBits"); return STG_E_UNIMPLEMENTEDFUNCTION; } HRESULT STDMETHODCALLTYPE OMGSFIStorage::Stat( STATSTG FAR *pstatstg, DWORD grfStatFlag ) { TRACE("OMGSFIStorage::DestroyElement"); int status = GSTG_OK; memset(pstatstg, 0, sizeof(STATSTG)); // TODO: ignoring several fields currently not required by SDK if (!(grfStatFlag & STATFLAG_NONAME)) { #ifdef OM_UNICODE_APIS pstatstg->pwcsName = convertString(_storageName); #else pstatstg->pwcsName = saveString(_storageName); #endif } //pstatstg->type //pstatstg->cbSize //pstatstg->mtime //pstatstg->ctime //pstatstg->atime switch (_mode) { case GSF_READ: pstatstg->grfMode |= STGM_READ; break; case GSF_READWRITE: pstatstg->grfMode |= STGM_READWRITE; break; case GSF_WRITE: pstatstg->grfMode |= STGM_WRITE; break; default: ASSERT ("Known SS access mode", false); break; } //pstatstg->grfLocksSupported unsigned char clsid[16]; if ( _mode == GSF_READ) { if (gsf_infile_msole_get_class_id (GSF_INFILE_MSOLE(_storage), clsid)) { reorder_clsid(clsid); memmove (&pstatstg->clsid, clsid, sizeof(pstatstg->clsid)); } else status = GSTG_ERROR; } //pstatstg->grfStateBits //pstatstg->reserved return makeStatus(status); } // GSF streams OMGSFIStream::OMGSFIStream (GsfStream *in_stream, GsfAccessMode mode, const char *sname) : _stream(in_stream), _mode(mode), _referenceCount(1) { strcpy(_streamName, sname); TRACE("OMGSFIStream::OMGSFIStream"); PRECONDITION("Valid reference count", _referenceCount == 1); } OMGSFIStream::~OMGSFIStream () { TRACE("OMGSFIStream::~OMGSFIStream"); PRECONDITION("Valid reference count", _referenceCount == 0); PRECONDITION("Stream has been closed", _stream == 0); } HRESULT STDMETHODCALLTYPE OMGSFIStream::QueryInterface(REFIID /* riid */, void** ppvObject) { TRACE("OMGSFIStream::QueryInterface"); *ppvObject = 0; return E_NOINTERFACE; } ULONG STDMETHODCALLTYPE OMGSFIStream::AddRef(void) { TRACE("OMGSFIStream::AddRef"); ++_referenceCount; return _referenceCount; } ULONG STDMETHODCALLTYPE OMGSFIStream::Release(void) { TRACE("OMGSFIStream::Release"); ULONG result = --_referenceCount; if (_referenceCount == 0) { if (_stream != 0) { if (GSF_IS_OUTPUT(_stream)) gsf_output_close (GSF_OUTPUT(_stream)); g_object_unref (G_OBJECT (_stream)); _stream = 0; } delete this; } return result; } HRESULT STDMETHODCALLTYPE OMGSFIStream::Read( VOID HUGEP *pv, ULONG cb, ULONG FAR *pcbRead ) { TRACE("OMGSFIStream::Read"); ASSERT ("Reading a ReadOnly GSF Stream", _mode == GSF_READ); int result = GSTG_OK; OMUInt64 bytesToRead = gsf_input_remaining (GSF_INPUT(_stream)); if (bytesToRead > cb) bytesToRead = cb; if (bytesToRead > 0) { if (gsf_input_read(GSF_INPUT(_stream), bytesToRead, (guint8*)pv) == NULL) result = GSTG_ERROR; } *pcbRead = bytesToRead; return makeStatus(result); } HRESULT STDMETHODCALLTYPE OMGSFIStream::Write( VOID const HUGEP *pv, ULONG cb, ULONG FAR *pcbWritten ) { TRACE("OMGSFIStream::Write"); ASSERT ("Writing to a WriteOnly GSF stream", _mode == GSF_WRITE); int result = GSTG_OK; if (!gsf_output_write (GSF_OUTPUT(_stream), cb, (const guint8 *)pv)) result = GSTG_ERROR; *pcbWritten = cb; return makeStatus(result); } int OMGSFIStream::Seek (OMInt64 offset, DWORD whence) { TRACE("OMGSFIStream::Seek"); int status = GSTG_OK; GSeekType pos; switch (whence) { case STREAM_SEEK_CUR: pos = G_SEEK_CUR; break; case STREAM_SEEK_END: pos = G_SEEK_END; break; case STREAM_SEEK_SET: default: pos = G_SEEK_SET; break; } if ( GSF_IS_INPUT(_stream)) { if (gsf_input_seek (GSF_INPUT(_stream), offset, pos) < 0) status = GSTG_ERROR; } else if (GSF_IS_OUTPUT(_stream)) { if (!gsf_output_seek (GSF_OUTPUT(_stream), offset, pos)) status = GSTG_ERROR; } else { ASSERT ("Known GSF stream type", false); status = GSTG_ERROR; } return status; } HRESULT STDMETHODCALLTYPE OMGSFIStream::Seek( LARGE_INTEGER dlibMove, DWORD dwOrigin, ULARGE_INTEGER FAR *plibNewPosition ) { TRACE("OMGSFIStream::Seek"); int status = GSTG_OK; ULARGE_INTEGER offset; memcpy (&offset, &dlibMove, sizeof(LARGE_INTEGER)); status = this->Seek(toOMUInt64(offset), dwOrigin); if (status == GSTG_OK && plibNewPosition != 0) { OMUInt64 newPos = 0; if((status = this->Tell(&newPos)) == GSTG_OK) *plibNewPosition = fromOMUInt64(newPos); } return makeStatus(status); } HRESULT STDMETHODCALLTYPE OMGSFIStream::SetSize( ULARGE_INTEGER libNewSize) { TRACE("OMGSFIStream::SetSize"); ASSERT ("Calling SetSize for ReadOnly GSF Streams", _mode == GSF_READ); OMUInt64 newSize = toOMUInt64(libNewSize); int status = GSTG_OK; if (!gsf_input_set_size (GSF_INPUT(_stream), newSize)) status = GSTG_ERROR; return makeStatus(status); } HRESULT STDMETHODCALLTYPE OMGSFIStream::CopyTo( IStream FAR *pstm, ULARGE_INTEGER cb, ULARGE_INTEGER FAR *pcbRead, ULARGE_INTEGER FAR *pcbWritten) { TRACE("OMGSFIStream::SetSize"); return STG_E_UNIMPLEMENTEDFUNCTION; } HRESULT STDMETHODCALLTYPE OMGSFIStream::Commit(DWORD grfCommitFlags) { TRACE("OMGSFIStream::Commit"); return STG_E_UNIMPLEMENTEDFUNCTION; } HRESULT STDMETHODCALLTYPE OMGSFIStream::Revert(void) { TRACE("OMGSFIStream::Revert"); return STG_E_UNIMPLEMENTEDFUNCTION; } HRESULT STDMETHODCALLTYPE OMGSFIStream::LockRegion( ULARGE_INTEGER libOffset, ULARGE_INTEGER cb, DWORD dwLockType) { TRACE("OMGSFIStream::LockRegion"); return STG_E_UNIMPLEMENTEDFUNCTION; } HRESULT STDMETHODCALLTYPE OMGSFIStream::UnlockRegion( ULARGE_INTEGER libOffset, ULARGE_INTEGER cb, DWORD dwLockType) { TRACE("OMGSFIStream::LockRegion"); return STG_E_UNIMPLEMENTEDFUNCTION; } int OMGSFIStream::Tell (OMUInt64 *position) const { TRACE("OMGSFIStream::Tell"); int status = GSTG_OK; *position = 0; if (GSF_IS_INPUT(_stream)) *position = gsf_input_tell (GSF_INPUT(_stream)); else if (GSF_IS_OUTPUT(_stream)) *position = gsf_output_tell (GSF_OUTPUT(_stream)); else { ASSERT ("Known GSF stream type", false); } return status; } int OMGSFIStream::Size (OMUInt64 *ssize) const { TRACE("OMGSFIStream::Size"); *ssize = 0; if (GSF_IS_INPUT(_stream)) *ssize = gsf_input_size (GSF_INPUT(_stream)); else if (GSF_IS_OUTPUT(_stream)) *ssize = gsf_output_size (GSF_OUTPUT(_stream)); else { ASSERT ("Known GSF stream type", false); return GSTG_ERROR; } return GSTG_OK; } HRESULT STDMETHODCALLTYPE OMGSFIStream::Stat( STATSTG FAR *pstatstg, DWORD grfStatFlag) { TRACE("OMGSFIStream::Stat"); OMUInt64 curSize; memset (pstatstg, 0, sizeof(*pstatstg)); // TODO: ignoring several fields currently not required by SDK if (!(grfStatFlag & STATFLAG_NONAME)) { #ifdef OM_UNICODE_APIS pstatstg->pwcsName = convertString(_streamName); #else pstatstg->pwcsName = saveString(_streamName); #endif } //pstatstg->type int status = this->Size (&curSize); pstatstg->cbSize = fromOMUInt64(curSize); //pstatstg->mtime //pstatstg->ctime //pstatstg->atime switch (_mode) { case GSF_READ: pstatstg->grfMode |= STGM_READ; break; case GSF_READWRITE: pstatstg->grfMode |= STGM_READWRITE; break; case GSF_WRITE: pstatstg->grfMode |= STGM_WRITE; break; default: ASSERT ("Known SS access mode", false); break; } //pstatstg->grfLocksSupported //pstatstg->clsid //pstatstg->grfStateBits //pstatstg->reserved return makeStatus(status); } HRESULT STDMETHODCALLTYPE OMGSFIStream::Clone(IStream FAR * FAR *ppstm) { TRACE("OMGSFIStream::Clone"); return STG_E_UNIMPLEMENTEDFUNCTION; } #endif // OM_USE_GSF_SS #endif // !OM_NO_STRUCTURED_STORAGE
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "flutter/flow/layers/color_filter_layer.h" #include "flutter/flow/testing/layer_test.h" #include "flutter/flow/testing/mock_layer.h" #include "flutter/fml/macros.h" #include "flutter/testing/mock_canvas.h" #include "third_party/skia/include/core/SkColorFilter.h" #include "third_party/skia/include/effects/SkColorMatrixFilter.h" namespace flutter { namespace testing { using ColorFilterLayerTest = LayerTest; #ifndef NDEBUG TEST_F(ColorFilterLayerTest, PaintingEmptyLayerDies) { auto layer = std::make_shared<ColorFilterLayer>(sk_sp<SkColorFilter>()); layer->Preroll(preroll_context(), SkMatrix()); EXPECT_EQ(layer->paint_bounds(), kEmptyRect); EXPECT_EQ(layer->child_paint_bounds(), kEmptyRect); EXPECT_FALSE(layer->needs_painting(paint_context())); EXPECT_DEATH_IF_SUPPORTED(layer->Paint(paint_context()), "needs_painting\\(context\\)"); } TEST_F(ColorFilterLayerTest, PaintBeforePrerollDies) { const SkRect child_bounds = SkRect::MakeLTRB(5.0f, 6.0f, 20.5f, 21.5f); const SkPath child_path = SkPath().addRect(child_bounds); auto mock_layer = std::make_shared<MockLayer>(child_path); auto layer = std::make_shared<ColorFilterLayer>(sk_sp<SkColorFilter>()); layer->Add(mock_layer); EXPECT_EQ(layer->paint_bounds(), kEmptyRect); EXPECT_EQ(layer->child_paint_bounds(), kEmptyRect); EXPECT_DEATH_IF_SUPPORTED(layer->Paint(paint_context()), "needs_painting\\(context\\)"); } #endif TEST_F(ColorFilterLayerTest, EmptyFilter) { const SkMatrix initial_transform = SkMatrix::Translate(0.5f, 1.0f); const SkRect child_bounds = SkRect::MakeLTRB(5.0f, 6.0f, 20.5f, 21.5f); const SkPath child_path = SkPath().addRect(child_bounds); const SkPaint child_paint = SkPaint(SkColors::kYellow); auto mock_layer = std::make_shared<MockLayer>(child_path, child_paint); auto layer = std::make_shared<ColorFilterLayer>(nullptr); layer->Add(mock_layer); layer->Preroll(preroll_context(), initial_transform); EXPECT_EQ(layer->paint_bounds(), child_bounds); EXPECT_EQ(layer->child_paint_bounds(), child_bounds); EXPECT_TRUE(layer->needs_painting(paint_context())); EXPECT_EQ(mock_layer->parent_matrix(), initial_transform); SkPaint filter_paint; filter_paint.setColorFilter(nullptr); layer->Paint(paint_context()); EXPECT_EQ( mock_canvas().draw_calls(), std::vector({MockCanvas::DrawCall{ 0, MockCanvas::SaveLayerData{child_bounds, filter_paint, nullptr, 1}}, MockCanvas::DrawCall{ 1, MockCanvas::DrawPathData{child_path, child_paint}}, MockCanvas::DrawCall{1, MockCanvas::RestoreData{0}}})); } TEST_F(ColorFilterLayerTest, SimpleFilter) { const SkMatrix initial_transform = SkMatrix::Translate(0.5f, 1.0f); const SkRect child_bounds = SkRect::MakeLTRB(5.0f, 6.0f, 20.5f, 21.5f); const SkPath child_path = SkPath().addRect(child_bounds); const SkPaint child_paint = SkPaint(SkColors::kYellow); auto layer_filter = SkColorMatrixFilter::MakeLightingFilter(SK_ColorGREEN, SK_ColorYELLOW); auto mock_layer = std::make_shared<MockLayer>(child_path, child_paint); auto layer = std::make_shared<ColorFilterLayer>(layer_filter); layer->Add(mock_layer); layer->Preroll(preroll_context(), initial_transform); EXPECT_EQ(layer->paint_bounds(), child_bounds); EXPECT_EQ(layer->child_paint_bounds(), child_bounds); EXPECT_TRUE(layer->needs_painting(paint_context())); EXPECT_EQ(mock_layer->parent_matrix(), initial_transform); SkPaint filter_paint; filter_paint.setColorFilter(layer_filter); layer->Paint(paint_context()); EXPECT_EQ( mock_canvas().draw_calls(), std::vector({MockCanvas::DrawCall{ 0, MockCanvas::SaveLayerData{child_bounds, filter_paint, nullptr, 1}}, MockCanvas::DrawCall{ 1, MockCanvas::DrawPathData{child_path, child_paint}}, MockCanvas::DrawCall{1, MockCanvas::RestoreData{0}}})); } TEST_F(ColorFilterLayerTest, MultipleChildren) { const SkMatrix initial_transform = SkMatrix::Translate(0.5f, 1.0f); const SkRect child_bounds = SkRect::MakeLTRB(5.0f, 6.0f, 2.5f, 3.5f); const SkPath child_path1 = SkPath().addRect(child_bounds); const SkPath child_path2 = SkPath().addRect(child_bounds.makeOffset(3.0f, 0.0f)); const SkPaint child_paint1 = SkPaint(SkColors::kYellow); const SkPaint child_paint2 = SkPaint(SkColors::kCyan); auto layer_filter = SkColorMatrixFilter::MakeLightingFilter(SK_ColorGREEN, SK_ColorYELLOW); auto mock_layer1 = std::make_shared<MockLayer>(child_path1, child_paint1); auto mock_layer2 = std::make_shared<MockLayer>(child_path2, child_paint2); auto layer = std::make_shared<ColorFilterLayer>(layer_filter); layer->Add(mock_layer1); layer->Add(mock_layer2); SkRect children_bounds = child_path1.getBounds(); children_bounds.join(child_path2.getBounds()); layer->Preroll(preroll_context(), initial_transform); EXPECT_EQ(mock_layer1->paint_bounds(), child_path1.getBounds()); EXPECT_EQ(mock_layer2->paint_bounds(), child_path2.getBounds()); EXPECT_EQ(layer->paint_bounds(), children_bounds); EXPECT_EQ(layer->child_paint_bounds(), children_bounds); EXPECT_TRUE(mock_layer1->needs_painting(paint_context())); EXPECT_TRUE(mock_layer2->needs_painting(paint_context())); EXPECT_TRUE(layer->needs_painting(paint_context())); EXPECT_EQ(mock_layer1->parent_matrix(), initial_transform); EXPECT_EQ(mock_layer2->parent_matrix(), initial_transform); SkPaint filter_paint; filter_paint.setColorFilter(layer_filter); layer->Paint(paint_context()); EXPECT_EQ( mock_canvas().draw_calls(), std::vector({MockCanvas::DrawCall{ 0, MockCanvas::SaveLayerData{children_bounds, filter_paint, nullptr, 1}}, MockCanvas::DrawCall{ 1, MockCanvas::DrawPathData{child_path1, child_paint1}}, MockCanvas::DrawCall{ 1, MockCanvas::DrawPathData{child_path2, child_paint2}}, MockCanvas::DrawCall{1, MockCanvas::RestoreData{0}}})); } TEST_F(ColorFilterLayerTest, Nested) { const SkMatrix initial_transform = SkMatrix::Translate(0.5f, 1.0f); const SkRect child_bounds = SkRect::MakeLTRB(5.0f, 6.0f, 2.5f, 3.5f); const SkPath child_path1 = SkPath().addRect(child_bounds); const SkPath child_path2 = SkPath().addRect(child_bounds.makeOffset(3.0f, 0.0f)); const SkPaint child_paint1 = SkPaint(SkColors::kYellow); const SkPaint child_paint2 = SkPaint(SkColors::kCyan); auto layer_filter1 = SkColorMatrixFilter::MakeLightingFilter(SK_ColorGREEN, SK_ColorYELLOW); auto layer_filter2 = SkColorMatrixFilter::MakeLightingFilter(SK_ColorMAGENTA, SK_ColorBLUE); auto mock_layer1 = std::make_shared<MockLayer>(child_path1, child_paint1); auto mock_layer2 = std::make_shared<MockLayer>(child_path2, child_paint2); auto layer1 = std::make_shared<ColorFilterLayer>(layer_filter1); auto layer2 = std::make_shared<ColorFilterLayer>(layer_filter2); layer2->Add(mock_layer2); layer1->Add(mock_layer1); layer1->Add(layer2); SkRect children_bounds = child_path1.getBounds(); children_bounds.join(child_path2.getBounds()); layer1->Preroll(preroll_context(), initial_transform); EXPECT_EQ(mock_layer1->paint_bounds(), child_path1.getBounds()); EXPECT_EQ(mock_layer2->paint_bounds(), child_path2.getBounds()); EXPECT_EQ(layer1->paint_bounds(), children_bounds); EXPECT_EQ(layer1->child_paint_bounds(), children_bounds); EXPECT_EQ(layer2->paint_bounds(), mock_layer2->paint_bounds()); EXPECT_EQ(layer2->child_paint_bounds(), mock_layer2->paint_bounds()); EXPECT_TRUE(mock_layer1->needs_painting(paint_context())); EXPECT_TRUE(mock_layer2->needs_painting(paint_context())); EXPECT_TRUE(layer1->needs_painting(paint_context())); EXPECT_TRUE(layer2->needs_painting(paint_context())); EXPECT_EQ(mock_layer1->parent_matrix(), initial_transform); EXPECT_EQ(mock_layer2->parent_matrix(), initial_transform); SkPaint filter_paint1, filter_paint2; filter_paint1.setColorFilter(layer_filter1); filter_paint2.setColorFilter(layer_filter2); layer1->Paint(paint_context()); EXPECT_EQ( mock_canvas().draw_calls(), std::vector({MockCanvas::DrawCall{ 0, MockCanvas::SaveLayerData{children_bounds, filter_paint1, nullptr, 1}}, MockCanvas::DrawCall{ 1, MockCanvas::DrawPathData{child_path1, child_paint1}}, MockCanvas::DrawCall{ 1, MockCanvas::SaveLayerData{child_path2.getBounds(), filter_paint2, nullptr, 2}}, MockCanvas::DrawCall{ 2, MockCanvas::DrawPathData{child_path2, child_paint2}}, MockCanvas::DrawCall{2, MockCanvas::RestoreData{1}}, MockCanvas::DrawCall{1, MockCanvas::RestoreData{0}}})); } TEST_F(ColorFilterLayerTest, Readback) { auto layer_filter = SkColorFilters::LinearToSRGBGamma(); auto initial_transform = SkMatrix(); // ColorFilterLayer does not read from surface auto layer = std::make_shared<ColorFilterLayer>(layer_filter); preroll_context()->surface_needs_readback = false; layer->Preroll(preroll_context(), initial_transform); EXPECT_FALSE(preroll_context()->surface_needs_readback); // ColorFilterLayer blocks child with readback auto mock_layer = std::make_shared<MockLayer>(SkPath(), SkPaint(), false, true); layer->Add(mock_layer); preroll_context()->surface_needs_readback = false; layer->Preroll(preroll_context(), initial_transform); EXPECT_FALSE(preroll_context()->surface_needs_readback); } TEST_F(ColorFilterLayerTest, CacheChild) { auto layer_filter = SkColorMatrixFilter::MakeLightingFilter(SK_ColorGREEN, SK_ColorYELLOW); auto initial_transform = SkMatrix::Translate(50.0, 25.5); auto other_transform = SkMatrix::Scale(1.0, 2.0); const SkPath child_path = SkPath().addRect(SkRect::MakeWH(5.0f, 5.0f)); auto mock_layer = std::make_shared<MockLayer>(child_path); auto layer = std::make_shared<ColorFilterLayer>(layer_filter); layer->Add(mock_layer); SkMatrix cache_ctm = initial_transform; SkCanvas cache_canvas; cache_canvas.setMatrix(cache_ctm); SkCanvas other_canvas; other_canvas.setMatrix(other_transform); use_mock_raster_cache(); EXPECT_EQ(raster_cache()->GetLayerCachedEntriesCount(), (size_t)0); EXPECT_FALSE(raster_cache()->Draw(mock_layer.get(), other_canvas)); EXPECT_FALSE(raster_cache()->Draw(mock_layer.get(), cache_canvas)); EXPECT_FALSE(raster_cache()->Draw(layer.get(), other_canvas, RasterCacheLayerStrategy::kLayer)); EXPECT_FALSE(raster_cache()->Draw(layer.get(), cache_canvas, RasterCacheLayerStrategy::kLayer)); EXPECT_FALSE(raster_cache()->Draw(layer.get(), other_canvas, RasterCacheLayerStrategy::kLayerChildren)); EXPECT_FALSE(raster_cache()->Draw(layer.get(), cache_canvas, RasterCacheLayerStrategy::kLayerChildren)); layer->Preroll(preroll_context(), initial_transform); EXPECT_EQ(raster_cache()->GetLayerCachedEntriesCount(), (size_t)1); EXPECT_FALSE(raster_cache()->Draw(mock_layer.get(), other_canvas)); EXPECT_FALSE(raster_cache()->Draw(mock_layer.get(), cache_canvas)); EXPECT_FALSE(raster_cache()->Draw(layer.get(), other_canvas, RasterCacheLayerStrategy::kLayer)); EXPECT_FALSE(raster_cache()->Draw(layer.get(), cache_canvas, RasterCacheLayerStrategy::kLayer)); EXPECT_FALSE(raster_cache()->Draw(layer.get(), other_canvas, RasterCacheLayerStrategy::kLayerChildren)); EXPECT_TRUE(raster_cache()->Draw(layer.get(), cache_canvas, RasterCacheLayerStrategy::kLayerChildren)); } TEST_F(ColorFilterLayerTest, CacheChildren) { auto layer_filter = SkColorMatrixFilter::MakeLightingFilter(SK_ColorGREEN, SK_ColorYELLOW); auto initial_transform = SkMatrix::Translate(50.0, 25.5); auto other_transform = SkMatrix::Scale(1.0, 2.0); const SkPath child_path1 = SkPath().addRect(SkRect::MakeWH(5.0f, 5.0f)); const SkPath child_path2 = SkPath().addRect(SkRect::MakeWH(5.0f, 5.0f)); auto mock_layer1 = std::make_shared<MockLayer>(child_path1); auto mock_layer2 = std::make_shared<MockLayer>(child_path2); auto layer = std::make_shared<ColorFilterLayer>(layer_filter); layer->Add(mock_layer1); layer->Add(mock_layer2); SkMatrix cache_ctm = initial_transform; SkCanvas cache_canvas; cache_canvas.setMatrix(cache_ctm); SkCanvas other_canvas; other_canvas.setMatrix(other_transform); use_mock_raster_cache(); EXPECT_EQ(raster_cache()->GetLayerCachedEntriesCount(), (size_t)0); EXPECT_FALSE(raster_cache()->Draw(mock_layer1.get(), other_canvas)); EXPECT_FALSE(raster_cache()->Draw(mock_layer1.get(), cache_canvas)); EXPECT_FALSE(raster_cache()->Draw(mock_layer2.get(), other_canvas)); EXPECT_FALSE(raster_cache()->Draw(mock_layer2.get(), cache_canvas)); EXPECT_FALSE(raster_cache()->Draw(layer.get(), other_canvas, RasterCacheLayerStrategy::kLayer)); EXPECT_FALSE(raster_cache()->Draw(layer.get(), cache_canvas, RasterCacheLayerStrategy::kLayer)); EXPECT_FALSE(raster_cache()->Draw(layer.get(), other_canvas, RasterCacheLayerStrategy::kLayerChildren)); EXPECT_FALSE(raster_cache()->Draw(layer.get(), cache_canvas, RasterCacheLayerStrategy::kLayerChildren)); layer->Preroll(preroll_context(), initial_transform); EXPECT_EQ(raster_cache()->GetLayerCachedEntriesCount(), (size_t)1); EXPECT_FALSE(raster_cache()->Draw(mock_layer1.get(), other_canvas)); EXPECT_FALSE(raster_cache()->Draw(mock_layer1.get(), cache_canvas)); EXPECT_FALSE(raster_cache()->Draw(mock_layer2.get(), other_canvas)); EXPECT_FALSE(raster_cache()->Draw(mock_layer2.get(), cache_canvas)); EXPECT_FALSE(raster_cache()->Draw(layer.get(), other_canvas, RasterCacheLayerStrategy::kLayer)); EXPECT_FALSE(raster_cache()->Draw(layer.get(), cache_canvas, RasterCacheLayerStrategy::kLayer)); EXPECT_FALSE(raster_cache()->Draw(layer.get(), other_canvas, RasterCacheLayerStrategy::kLayerChildren)); EXPECT_TRUE(raster_cache()->Draw(layer.get(), cache_canvas, RasterCacheLayerStrategy::kLayerChildren)); } } // namespace testing } // namespace flutter
/* Copyright 2016 Ahnaf Siddiqui Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "Q_DynamicWorld2D.h" #include "Q_PolyCollider.h" #include "gtest/gtest.h" using namespace Diamond; using namespace Quantum2D; void colFunc(void *ptr) { // } // TEST(LayerTest, MaxLayers) { // EXPECT_EQ(Quantum2D::MAX_LAYERS, 256); // } TEST(LayerTest, LayerSet) { DynamicWorld2D world; ASSERT_TRUE(world.init(false)); world.setLayersCollide(0, 0, 1); EXPECT_TRUE(world.doLayersCollide(0, 0)); world.setLayersCollide(0, 0, 0); EXPECT_FALSE(world.doLayersCollide(0, 0)); world.setLayersCollide(4, 6, 1); EXPECT_TRUE(world.doLayersCollide(4, 6)); EXPECT_TRUE(world.doLayersCollide(6, 4)); world.setLayersCollide(4, 6, 0); EXPECT_FALSE(world.doLayersCollide(4, 6)); EXPECT_FALSE(world.doLayersCollide(6, 4)); } TEST(PolyColliderTest, PersistsCWPoints) { DynamicWorld2D world; ASSERT_TRUE(world.init()); PointList2D points; // Clockwise order points.emplace_back(9, 10); points.emplace_back(7, 8); points.emplace_back(5, 6); points.emplace_back(4, 7); points.emplace_back(6, 12); collider2_id colID = world.genCollider<PolyCollider>( world.genRigidbody(), nullptr, colFunc, points); PolyCollider *collider = (PolyCollider *)world.getCollider(colID); EXPECT_FLOAT_EQ(collider->points()[0].x, 9); EXPECT_FLOAT_EQ(collider->points()[0].y, 10); EXPECT_FLOAT_EQ(collider->points()[1].x, 7); EXPECT_FLOAT_EQ(collider->points()[1].y, 8); EXPECT_FLOAT_EQ(collider->points()[2].x, 5); EXPECT_FLOAT_EQ(collider->points()[2].y, 6); EXPECT_FLOAT_EQ(collider->points()[3].x, 4); EXPECT_FLOAT_EQ(collider->points()[3].y, 7); EXPECT_FLOAT_EQ(collider->points()[4].x, 6); EXPECT_FLOAT_EQ(collider->points()[4].y, 12); } TEST(PolyColliderTest, PersistsThreeCWPoints) { DynamicWorld2D world; ASSERT_TRUE(world.init()); PointList2D points; // Clockwise order points.emplace_back(25, 50); points.emplace_back(50, 0); points.emplace_back(0, 0); collider2_id colID = world.genCollider<PolyCollider>( world.genRigidbody(), nullptr, colFunc, points); PolyCollider *collider = (PolyCollider *)world.getCollider(colID); EXPECT_FLOAT_EQ(collider->points()[0].x, 25); EXPECT_FLOAT_EQ(collider->points()[0].y, 50); EXPECT_FLOAT_EQ(collider->points()[1].x, 50); EXPECT_FLOAT_EQ(collider->points()[1].y, 0); EXPECT_FLOAT_EQ(collider->points()[2].x, 0); EXPECT_FLOAT_EQ(collider->points()[2].y, 0); } TEST(PolyColliderTest, PersistsCCWPoints) { DynamicWorld2D world; ASSERT_TRUE(world.init()); PointList2D points; // Counterclockwise order points.emplace_back(6, 4); points.emplace_back(8, 5); points.emplace_back(9, 7); points.emplace_back(4, 12); points.emplace_back(2, 7); collider2_id colID = world.genCollider<PolyCollider>( world.genRigidbody(), nullptr, colFunc, points); PolyCollider *collider = (PolyCollider *)world.getCollider(colID); // Points should be reversed into clockwise order EXPECT_FLOAT_EQ(collider->points()[0].x, 2); EXPECT_FLOAT_EQ(collider->points()[0].y, 7); EXPECT_FLOAT_EQ(collider->points()[1].x, 4); EXPECT_FLOAT_EQ(collider->points()[1].y, 12); EXPECT_FLOAT_EQ(collider->points()[2].x, 9); EXPECT_FLOAT_EQ(collider->points()[2].y, 7); EXPECT_FLOAT_EQ(collider->points()[3].x, 8); EXPECT_FLOAT_EQ(collider->points()[3].y, 5); EXPECT_FLOAT_EQ(collider->points()[4].x, 6); EXPECT_FLOAT_EQ(collider->points()[4].y, 4); }
/* * Copyright 2012 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "gm/gm.h" #include "include/core/SkBitmap.h" #include "include/core/SkCanvas.h" #include "include/core/SkColor.h" #include "include/core/SkFont.h" #include "include/core/SkImageFilter.h" #include "include/core/SkPaint.h" #include "include/core/SkPoint.h" #include "include/core/SkRect.h" #include "include/core/SkScalar.h" #include "include/core/SkShader.h" #include "include/core/SkSize.h" #include "include/core/SkString.h" #include "include/core/SkTileMode.h" #include "include/core/SkTypeface.h" #include "include/effects/SkGradientShader.h" #include "include/effects/SkImageFilters.h" #include "src/gpu/ganesh/effects/GrMatrixConvolutionEffect.h" #include "tools/ToolUtils.h" #include <vector> namespace skiagm { enum KernelFixture { kBasic_KernelFixture, kLarge_KernelFixture }; class MatrixConvolutionGM : public GM { public: MatrixConvolutionGM(SkColor colorOne, SkColor colorTwo, KernelFixture kernelFixture, const char* nameSuffix) : fNameSuffix(nameSuffix), fKernelFixture(kernelFixture) { this->setBGColor(0x00000000); fColors[0] = colorOne; fColors[1] = colorTwo; } protected: SkString onShortName() override { return SkStringPrintf("matrixconvolution%s", fNameSuffix); } void makeBitmap() { // Draw our bitmap in N32, so legacy devices get "premul" values they understand auto surf = SkSurface::MakeRasterN32Premul(80, 80); SkPaint paint; paint.setColor(0xFFFFFFFF); SkPoint pts[2] = { {0, 0}, {0, 80.0f} }; SkScalar pos[2] = { 0, 80.0f }; paint.setShader(SkGradientShader::MakeLinear( pts, fColors, pos, 2, SkTileMode::kClamp)); SkFont font(ToolUtils::create_portable_typeface(), 180.0f); surf->getCanvas()->drawString("e", -10.0f, 80.0f, font, paint); fImage = surf->makeImageSnapshot(); } SkISize onISize() override { return SkISize::Make(500, 300); } sk_sp<SkImageFilter> makeFilter(const SkIPoint &kernelOffset, SkTileMode tileMode, bool convolveAlpha, const SkIRect *cropRect = nullptr) { switch (fKernelFixture) { case kBasic_KernelFixture: { // All 1s except center value, which is -7 (sum of 1). std::vector<SkScalar> kernel(9, SkIntToScalar(1)); kernel[4] = SkIntToScalar(-7); return SkImageFilters::MatrixConvolution({3,3}, kernel.data(), /* gain */ 0.3f, /* bias */ SkIntToScalar(100), kernelOffset, tileMode, convolveAlpha, nullptr, cropRect); } case kLarge_KernelFixture: { static_assert(49 > GrMatrixConvolutionEffect::kMaxUniformSize); // All 1s except center value, which is -47 (sum of 1). std::vector<SkScalar> kernel(49, SkIntToScalar(1)); kernel[24] = SkIntToScalar(-47); return SkImageFilters::MatrixConvolution({7,7}, kernel.data(), /* gain */ 0.3f, /* bias */ SkIntToScalar(100), kernelOffset, tileMode, convolveAlpha, nullptr, cropRect); } default: return nullptr; } } void draw(SkCanvas* canvas, int x, int y, const SkIPoint& kernelOffset, SkTileMode tileMode, bool convolveAlpha, const SkIRect* cropRect = nullptr) { SkPaint paint; paint.setImageFilter(this->makeFilter(kernelOffset, tileMode, convolveAlpha, cropRect)); canvas->save(); canvas->translate(SkIntToScalar(x), SkIntToScalar(y)); const SkRect layerBounds = SkRect::Make(fImage->bounds()); canvas->clipRect(layerBounds); // This GM is, in part, intended to display the wrapping behavior of the // matrix image filter. The only (rational) way to achieve that for repeat mode // is to create a tight layer. canvas->saveLayer(layerBounds, &paint); canvas->drawImage(fImage, 0, 0); canvas->restore(); canvas->restore(); } void onOnceBeforeDraw() override { this->makeBitmap(); } void onDraw(SkCanvas* canvas) override { canvas->clear(SK_ColorBLACK); SkIPoint kernelOffset = SkIPoint::Make(1, 0); SkIRect rect = fImage->bounds(); for (int x = 10; x < 310; x += 100) { this->draw(canvas, x, 10, kernelOffset, SkTileMode::kClamp, true, &rect); this->draw(canvas, x, 110, kernelOffset, SkTileMode::kDecal, true, &rect); this->draw(canvas, x, 210, kernelOffset, SkTileMode::kRepeat, true, &rect); kernelOffset.fY++; } kernelOffset.fY = 1; SkIRect smallRect = SkIRect::MakeXYWH(10, 5, 60, 60); this->draw(canvas, 310, 10, kernelOffset, SkTileMode::kClamp, true, &smallRect); this->draw(canvas, 310, 110, kernelOffset, SkTileMode::kDecal, true, &smallRect); this->draw(canvas, 310, 210, kernelOffset, SkTileMode::kRepeat, true, &smallRect); this->draw(canvas, 410, 10, kernelOffset, SkTileMode::kClamp, false, &rect); this->draw(canvas, 410, 110, kernelOffset, SkTileMode::kDecal, false, &rect); this->draw(canvas, 410, 210, kernelOffset, SkTileMode::kRepeat, false, &rect); } private: sk_sp<SkImage> fImage; SkColor fColors[2]; const char* fNameSuffix; KernelFixture fKernelFixture; using INHERITED = GM; }; ////////////////////////////////////////////////////////////////////////////// DEF_GM(return new MatrixConvolutionGM(0xFFFFFFFF, 0x40404040, KernelFixture::kBasic_KernelFixture, "");) DEF_GM(return new MatrixConvolutionGM(0xFFFF0000, 0xFF00FF00, KernelFixture::kBasic_KernelFixture, "_color");) DEF_GM(return new MatrixConvolutionGM(0xFFFFFFFF, 0x40404040, KernelFixture::kLarge_KernelFixture, "_big");) DEF_GM(return new MatrixConvolutionGM(0xFFFF0000, 0xFF00FF00, KernelFixture::kLarge_KernelFixture, "_big_color");) } // namespace skiagm
#pragma once #include "cApp.hpp" #include <iostream> wxIMPLEMENT_APP(cApp); cApp::cApp() { } cApp::~cApp() { } bool cApp::OnInit() { _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF); m_frame = new Main(); m_frame->Show(); return true; }
#ifndef STAN_MATH_PRIM_SCAL_FUN_LOG1P_HPP #define STAN_MATH_PRIM_SCAL_FUN_LOG1P_HPP #include <stan/math/prim/scal/fun/boost_policy.hpp> #include <boost/math/special_functions/log1p.hpp> namespace stan { namespace math { /** * Return the natural logarithm of one plus the specified value. * * \f[ * \mbox{log1p}(x) = \log(1 + x) * \f] * * This version is more stable for arguments near zero than * the direct definition. If <code>log1p(x)</code> is defined to * be negative infinity. * * @param[in] x Argument. * @return Natural log of one plus the argument. * @throw std::domain_error If argument is less than -1. */ inline double log1p(double x) { return boost::math::log1p(x, boost_policy_t()); } /** * Return the natural logarithm of one plus the specified * argument. This version is required to disambiguate * <code>log1p(int)</code>. * * @param[in] x Argument. * @return Natural logarithm of one plus the argument. * @throw std::domain_error If argument is less than -1. */ inline double log1p(int x) { return log1p(static_cast<double>(x)); } } // namespace math } // namespace stan #endif
/*========================================================================= * * Copyright Insight Software Consortium * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #include "sitkEvent.h" #define sitkEventToStringCaseMacro(n) case sitk##n##Event: return ( os << #n << "Event" ) namespace itk { namespace simple { std::ostream& operator<<(std::ostream& os, const EventEnum k) { switch (k) { sitkEventToStringCaseMacro(Any); sitkEventToStringCaseMacro(Abort); sitkEventToStringCaseMacro(Delete); sitkEventToStringCaseMacro(End); sitkEventToStringCaseMacro(Iteration); sitkEventToStringCaseMacro(Progress); sitkEventToStringCaseMacro(Start); sitkEventToStringCaseMacro(User); sitkEventToStringCaseMacro(MultiResolutionIteration); } return os; } } // end namespace simple } // end namespace itk
// Copyright 2018 POGchain Development Foundation and contributors. Licensed // under the Apache License, Version 2.0. See the COPYING file at the root // of this distribution or at http://www.apache.org/licenses/LICENSE-2.0 #include "work/BasicWork.h" #include "util/GlobalChecks.h" #include "util/Logging.h" #include "util/Math.h" #include <Tracy.hpp> #include <fmt/format.h> namespace POGchain { size_t const BasicWork::RETRY_NEVER = 0; size_t const BasicWork::RETRY_ONCE = 1; size_t const BasicWork::RETRY_A_FEW = 5; size_t const BasicWork::RETRY_A_LOT = 32; std::set<BasicWork::Transition> const BasicWork::ALLOWED_TRANSITIONS = { Transition(InternalState::PENDING, InternalState::RUNNING), Transition(InternalState::PENDING, InternalState::ABORTING), Transition(InternalState::RUNNING, InternalState::RUNNING), Transition(InternalState::RUNNING, InternalState::WAITING), Transition(InternalState::RUNNING, InternalState::SUCCESS), Transition(InternalState::RUNNING, InternalState::FAILURE), Transition(InternalState::RUNNING, InternalState::RETRYING), Transition(InternalState::RUNNING, InternalState::ABORTING), Transition(InternalState::WAITING, InternalState::RUNNING), Transition(InternalState::WAITING, InternalState::ABORTING), Transition(InternalState::RETRYING, InternalState::WAITING), Transition(InternalState::SUCCESS, InternalState::PENDING), Transition(InternalState::FAILURE, InternalState::PENDING), Transition(InternalState::ABORTING, InternalState::ABORTING), Transition(InternalState::ABORTING, InternalState::ABORTED), Transition(InternalState::ABORTED, InternalState::PENDING), }; BasicWork::BasicWork(Application& app, std::string name, size_t maxRetries) : mApp(app), mName(std::move(name)), mMaxRetries(maxRetries) { } BasicWork::~BasicWork() { // Work completed or has not started yet releaseAssert(isDone() || mState == InternalState::PENDING); } void BasicWork::resetWaitingTimer() { if (mWaitingTimer) { mWaitingTimer->cancel(); mWaitingTimer.reset(); } } void BasicWork::shutdown() { CLOG_TRACE(Work, "Shutting down: {}", getName()); if (!isDone()) { // We're transitioning into "ABORTING" state, so cancel // the waiting timer resetWaitingTimer(); setState(InternalState::ABORTING); } } std::string const& BasicWork::getName() const { return mName; } std::string BasicWork::getStatus() const { // Work is in `WAITING` state when retrying auto state = mRetryTimer ? InternalState::RETRYING : mState; switch (state) { case InternalState::PENDING: return fmt::format(FMT_STRING("Ready to run: {}"), getName()); case InternalState::RUNNING: return fmt::format(FMT_STRING("Running: {}"), getName()); case InternalState::WAITING: return fmt::format(FMT_STRING("Waiting: {}"), getName()); case InternalState::SUCCESS: return fmt::format(FMT_STRING("Succeeded: {}"), getName()); case InternalState::RETRYING: { auto eta = getRetryETA(); return fmt::format(FMT_STRING("Retrying in {:d} sec: {}"), eta, getName()); } case InternalState::FAILURE: return fmt::format(FMT_STRING("Failed: {}"), getName()); case InternalState::ABORTING: return fmt::format(FMT_STRING("Aborting: {}"), getName()); case InternalState::ABORTED: return fmt::format(FMT_STRING("Aborted: {}"), getName()); default: abort(); } } bool BasicWork::isDone() const { return mState == InternalState::SUCCESS || mState == InternalState::FAILURE || mState == InternalState::ABORTED; } std::string BasicWork::stateName(InternalState st) { switch (st) { case InternalState::WAITING: return "WORK_WAITING"; case InternalState::RUNNING: return "WORK_RUNNING"; case InternalState::SUCCESS: return "WORK_SUCCESS"; case InternalState::FAILURE: return "WORK_FAILURE"; case InternalState::PENDING: return "WORK_PENDING"; case InternalState::ABORTING: return "WORK_ABORTING"; case InternalState::ABORTED: return "WORK_ABORTED"; case InternalState::RETRYING: return "WORK_RETRYING"; default: abort(); } } void BasicWork::reset() { CLOG_TRACE(Work, "resetting {}", getName()); if (mRetryTimer) { mRetryTimer->cancel(); mRetryTimer.reset(); } onReset(); } void BasicWork::startWork(std::function<void()> notificationCallback) { CLOG_TRACE(Work, "Starting {}", getName()); if (mState != InternalState::PENDING) { // Only restart if work is in terminal state setState(InternalState::PENDING); } mNotifyCallback = notificationCallback; setState(InternalState::RUNNING); releaseAssert(mRetries == 0); } void BasicWork::waitForRetry() { if (mRetryTimer) { throw std::runtime_error(fmt::format( FMT_STRING("Retry timer for {} already exists!"), getName())); } mRetryTimer = std::make_unique<VirtualTimer>(mApp.getClock()); std::weak_ptr<BasicWork> weak = shared_from_this(); auto t = getRetryDelay(); mRetryTimer->expires_from_now(t); CLOG_DEBUG(Work, "Scheduling retry #{}/{} in {} sec, for {}", (mRetries + 1), mMaxRetries, std::chrono::duration_cast<std::chrono::seconds>(t).count(), getName()); setState(InternalState::WAITING); mRetryTimer->async_wait([weak](asio::error_code const& ec) { auto self = weak.lock(); if (!self) { return; } releaseAssert(self->mState == InternalState::WAITING || self->mState == InternalState::ABORTED || self->mState == InternalState::ABORTING); if (self->mState == InternalState::WAITING) { self->mRetries++; self->mRetryTimer.reset(); self->wakeUp(); } }); } void BasicWork::onReset() { } void BasicWork::onSuccess() { } void BasicWork::onFailureRetry() { } void BasicWork::onFailureRaise() { } BasicWork::State BasicWork::getState() const { switch (mState) { case InternalState::RUNNING: case InternalState::PENDING: case InternalState::ABORTING: return State::WORK_RUNNING; case InternalState::WAITING: case InternalState::RETRYING: return State::WORK_WAITING; case InternalState::SUCCESS: return State::WORK_SUCCESS; case InternalState::FAILURE: return State::WORK_FAILURE; case InternalState::ABORTED: return State::WORK_ABORTED; default: abort(); } } void BasicWork::setState(InternalState st) { if (st == InternalState::FAILURE && (mRetries < mMaxRetries)) { st = InternalState::RETRYING; } assertValidTransition(Transition(mState, st)); if (mState == InternalState::PENDING && st == InternalState::RUNNING) { reset(); mRetries = 0; } // Perform necessary action *before* changing state (in case shutdown was // issued in between) switch (st) { case InternalState::SUCCESS: onSuccess(); break; case InternalState::FAILURE: onFailureRaise(); reset(); break; case InternalState::RETRYING: onFailureRetry(); reset(); break; case InternalState::ABORTED: reset(); break; default: break; } if (mState != st) { CLOG_DEBUG(Work, "work {} : {} -> {}", getName(), stateName(mState), stateName(st)); mState = st; } if (mState == InternalState::RETRYING) { waitForRetry(); } } void BasicWork::wakeUp(std::function<void()> innerCallback) { // Work should not be waking up in terminal state // Work should not be interrupted when retrying or destructing if (mState != InternalState::WAITING) { return; } CLOG_TRACE(Work, "Waking up: {}", getName()); setState(InternalState::RUNNING); // If we woke up because of the waiting timer firing, reset it resetWaitingTimer(); if (innerCallback) { CLOG_TRACE(Work, "{} woke up and is executing its callback", getName()); innerCallback(); } if (mNotifyCallback) { mNotifyCallback(); } } std::function<void()> BasicWork::wakeSelfUpCallback(std::function<void()> innerCallback) { std::weak_ptr<BasicWork> weak = shared_from_this(); auto callback = [weak, innerCallback]() { auto self = weak.lock(); if (!self) { return; } self->wakeUp(innerCallback); }; return callback; } void BasicWork::setupWaitingCallback(std::chrono::milliseconds wakeUpIn) { // Work must be running to schedule a timer releaseAssert(mState == BasicWork::InternalState::RUNNING); // No-op if timer is already set if (mWaitingTimer) { CLOG_WARNING(Work, "{}: waiting timer is already set (no-op)", getName()); return; } // Otherwise, setup the timer that no-ops on failure (if work is shutdown or // destroyed, for example) mWaitingTimer = std::make_unique<VirtualTimer>(mApp.getClock()); mWaitingTimer->expires_from_now(wakeUpIn); mWaitingTimer->async_wait(wakeSelfUpCallback(), &VirtualTimer::onFailureNoop); } void BasicWork::crankWork() { ZoneScoped; releaseAssert(!isDone() && mState != InternalState::WAITING); InternalState nextState; if (mState == InternalState::ABORTING) { auto doneAborting = onAbort(); nextState = doneAborting ? InternalState::ABORTED : InternalState::ABORTING; CLOG_TRACE(Work, "Abort progress for {}{}", getName(), (doneAborting ? ": done" : ": still aborting")); } else { nextState = getInternalState(onRun()); } setState(nextState); } VirtualClock::duration BasicWork::getRetryDelay() const { // Cap to 512 sec or ~8 minutes uint64_t m = 2ULL << std::min(uint64_t(8), uint64_t(mRetries)); return std::chrono::seconds(rand_uniform<uint64_t>(1ULL, m)); } uint64_t BasicWork::getRetryETA() const { if (!mRetryTimer) { return 0; } auto now = mApp.getClock().now(); auto retry = mRetryTimer->expiry_time(); if (now > retry) { return 0; } auto secs = std::chrono::duration_cast<std::chrono::seconds>(retry - now); return secs.count(); } void BasicWork::assertValidTransition(Transition const& t) const { if (ALLOWED_TRANSITIONS.find(t) == ALLOWED_TRANSITIONS.end()) { throw std::runtime_error(fmt::format( FMT_STRING("BasicWork error: illegal state transition {} -> {}"), stateName(t.first), stateName(t.second))); } } BasicWork::InternalState BasicWork::getInternalState(State s) const { switch (s) { case State::WORK_SUCCESS: return InternalState::SUCCESS; case State::WORK_FAILURE: return InternalState::FAILURE; case State::WORK_WAITING: return InternalState::WAITING; case State::WORK_RUNNING: return InternalState::RUNNING; case State::WORK_ABORTED: return InternalState::ABORTED; default: abort(); } } }
//********************************************************* // AboutCommand.cpp // // Copyright (C) 2007-2021 Skeletal Studios // All rights reserved. // //********************************************************* //********************************************************* #include "AboutCommand.h" #include "ErrorReporting.h" //********************************************************* //********************************************************* // Constants //********************************************************* const char* AboutCommand::nameFlag = "-n"; const char* AboutCommand::nameLongFlag = "-name"; const char* AboutCommand::versionFlag = "-v"; const char* AboutCommand::versionLongFlag = "-version"; const char* AboutCommand::copyrightFlag = "-c"; const char* AboutCommand::copyrightLongFlag = "-copyright"; const char* AboutCommand::name = "tradigitools"; const char* AboutCommand::version = "1.5"; const char* AboutCommand::copyright = "Copyright 2007-2021 Skeletal Studios"; //********************************************************* // Name: AboutCommand // Desc: Constructor //********************************************************* AboutCommand::AboutCommand() { } //********************************************************* // Name: ~AboutCommand // Desc: Destructor //********************************************************* AboutCommand::~AboutCommand() { } //********************************************************* // Name: doIt // Desc: All of the one-time setup and initialization // code for the set key command. doIt is called // by Maya when any command is executed in MEL. //********************************************************* MStatus AboutCommand::doIt( const MArgList &args ) { parseCommandFlags( args ); return MS::kSuccess; } //********************************************************* // Name: newSyntax // Desc: Method for registering the command flags // with Maya //********************************************************* MSyntax AboutCommand::newSyntax() { // Use MSyntax for a more robust solution to the // parsing the command flags MSyntax syntax; syntax.addFlag( nameFlag, nameLongFlag, MSyntax::kNoArg ); syntax.addFlag( versionFlag, versionLongFlag, MSyntax::kNoArg ); syntax.addFlag( copyrightFlag, copyrightLongFlag, MSyntax::kNoArg ); return syntax; } //********************************************************* // Name: parseCommandFlags // Desc: Parse the command flags and stores the values // in the appropriate variables //********************************************************* MStatus AboutCommand::parseCommandFlags( const MArgList &args ) { MArgDatabase argData( syntax(), args ); // No flags set returns the name if( argData.isFlagSet( versionFlag )) setResult( version ); else if( argData.isFlagSet( copyrightFlag )) setResult( copyright ); else setResult( name ); return MS::kSuccess; }
/* * Copyright (C) Volition, Inc. 1999. All rights reserved. * * All source code herein is the property of Volition, Inc. You may not sell * or otherwise commercially exploit the source or things you created based on the * source. * */ #include <cstdio> #include <cstdlib> #include <cstring> #include <cassert> #include <cstdarg> #include <csetjmp> #include "ai/aigoals.h" #include "asteroid/asteroid.h" #include "bmpman/bmpman.h" #include "cfile/cfile.h" #include "cmdline/cmdline.h" #include "debris/debris.h" #include "gamesnd/eventmusic.h" #include "globalincs/alphacolors.h" #include "globalincs/linklist.h" #include "hud/hudescort.h" #include "hud/hudets.h" #include "hud/hudwingmanstatus.h" #include "iff_defs/iff_defs.h" #include "io/timer.h" #include "jumpnode/jumpnode.h" #include "lighting/lighting.h" #include "localization/localize.h" #include "math/fvi.h" #include "math/staticrand.h" #include "mission/missionbriefcommon.h" #include "mission/missioncampaign.h" #include "mission/missiongoals.h" #include "mission/missionhotkey.h" #include "mission/missionlog.h" #include "mission/missionmessage.h" #include "mission/missionparse.h" #include "missionui/fictionviewer.h" #include "missionui/missioncmdbrief.h" #include "missionui/redalert.h" #include "mod_table/mod_table.h" #include "nebula/neb.h" #include "nebula/neblightning.h" #include "network/multi.h" #include "network/multi_endgame.h" #include "network/multi_respawn.h" #include "network/multimsgs.h" #include "network/multiutil.h" #include "object/objectdock.h" #include "object/parseobjectdock.h" #include "object/objectshield.h" #include "object/waypoint.h" #include "parse/generic_log.h" #include "parse/parselo.h" #include "scripting/hook_api.h" #include "scripting/scripting.h" #include "playerman/player.h" #include "popup/popup.h" #include "popup/popupdead.h" #include "ship/ship.h" #include "ship/shipfx.h" #include "ship/shiphit.h" #include "sound/ds.h" #include "starfield/nebula.h" #include "starfield/starfield.h" #include "weapon/weapon.h" #include "tracing/Monitor.h" #include "missionparse.h" LOCAL struct { char docker[NAME_LENGTH]; char dockee[NAME_LENGTH]; char docker_point[NAME_LENGTH]; char dockee_point[NAME_LENGTH]; } Initially_docked[MAX_SHIPS]; int Total_initially_docked; mission The_mission; char Mission_filename[80]; int Mission_palette; // index into Nebula_palette_filenames[] of palette file to use for mission int Nebula_index; // index into Nebula_filenames[] of nebula to use in mission. int Num_ai_behaviors = MAX_AI_BEHAVIORS; int Num_cargo = 0; int Num_status_names = MAX_STATUS_NAMES; int Num_arrival_names = MAX_ARRIVAL_NAMES; int Num_goal_type_names = MAX_GOAL_TYPE_NAMES; int Num_parse_goals; int Player_starts = 1; int Num_teams; fix Entry_delay_time = 0; int Num_unknown_ship_classes; int Num_unknown_weapon_classes; int Num_unknown_loadout_classes; ushort Current_file_checksum = 0; ushort Last_file_checksum = 0; int Current_file_length = 0; // alternate ship type names char Mission_alt_types[MAX_ALT_TYPE_NAMES][NAME_LENGTH]; int Mission_alt_type_count = 0; // callsigns char Mission_callsigns[MAX_CALLSIGNS][NAME_LENGTH]; int Mission_callsign_count = 0; #define SHIP_WARP_TIME 5.0f // how many seconds it takes for ship to warp in // the ship arrival list will contain a list of ships that are yet to arrive. This // list could also include ships that are part of wings! p_object Ship_arrival_list; // for linked list of ships to arrive later // all the ships that we parse SCP_vector<p_object> Parse_objects; // list for arriving support ship p_object Support_ship_pobj; p_object *Arriving_support_ship; char Arriving_repair_targets[MAX_AI_GOALS][NAME_LENGTH]; int Num_arriving_repair_targets; #define MIN_SUBSYS_STATUS_SIZE 25 subsys_status *Subsys_status = NULL; int Subsys_index; int Subsys_status_size; char Mission_parse_storm_name[NAME_LENGTH] = "none"; team_data Team_data[MAX_TVT_TEAMS]; // variables for player start in single player char Player_start_shipname[NAME_LENGTH]; int Player_start_shipnum; p_object *Player_start_pobject; // name of all ships to use while parsing a mission (since a ship might be referenced by // something before that ship has even been loaded yet) char Parse_names[MAX_SHIPS + MAX_WINGS][NAME_LENGTH]; int Num_parse_names; SCP_vector<texture_replace> Fred_texture_replacements; int Num_path_restrictions; path_restriction_t Path_restrictions[MAX_PATH_RESTRICTIONS]; //XSTR:OFF const char *Nebula_filenames[NUM_NEBULAS] = { "Nebula01", "Nebula02", "Nebula03" }; const char *Neb2_filenames[NUM_NEBULAS] = { "Nebfull01", "Nebfull02", "Nebfull03" }; // Note: Nebula_colors[] and Nebula_palette_filenames are linked via index numbers const char *Nebula_colors[NUM_NEBULA_COLORS] = { "Red", "Blue", "Gold", "Purple", "Maroon", "Green", "Grey blue", "Violet", "Grey Green", }; const char *Ai_behavior_names[MAX_AI_BEHAVIORS] = { "Chase", "Evade", "Get behind", "Stay Near", "Still", "Guard", "Avoid", "Waypoints", "Dock", "None", "Big Ship", "Path", "Be Rearmed", "Safety", "Evade Weapon", "Strafe", "Play Dead", "Bay Emerge", "Bay Depart", "Sentry Gun", "Warp Out", }; char *Cargo_names[MAX_CARGO]; char Cargo_names_buf[MAX_CARGO][NAME_LENGTH]; const char *Ship_class_names[MAX_SHIP_CLASSES]; // to be filled in from Ship_info array const char *Icon_names[MIN_BRIEF_ICONS] = { "Fighter", "Fighter Wing", "Cargo", "Cargo Wing", "Largeship", "Largeship Wing", "Capital", "Planet", "Asteroid Field", "Waypoint", "Support Ship", "Freighter(no cargo)", "Freighter(has cargo)", "Freighter Wing(no cargo)", "Freighter Wing(has cargo)", "Installation", "Bomber", "Bomber Wing", "Cruiser", "Cruiser Wing", "Unknown", "Unknown Wing", "Player Fighter", "Player Fighter Wing", "Player Bomber", "Player Bomber Wing", "Knossos Device", "Transport Wing", "Corvette", "Gas Miner", "Awacs", "Supercap", "Sentry Gun", "Jump Node", "Transport" }; const char *Status_desc_names[MAX_STATUS_NAMES] = { "Shields Critical", "Engines Damaged", "Fully Operational", }; const char *Status_type_names[MAX_STATUS_NAMES] = { "Damaged", "Disabled", "Corroded", }; const char *Status_target_names[MAX_STATUS_NAMES] = { "Weapons", "Engines", "Cable TV", }; // definitions for arrival locations for ships/wings const char *Arrival_location_names[MAX_ARRIVAL_NAMES] = { "Hyperspace", "Near Ship", "In front of ship", "Docking Bay", }; const char *Departure_location_names[MAX_DEPARTURE_NAMES] = { "Hyperspace", "Docking Bay", }; const char *Goal_type_names[MAX_GOAL_TYPE_NAMES] = { "Primary", "Secondary", "Bonus", }; const char *Reinforcement_type_names[] = { "Attack/Protect", "Repair/Rearm", }; const char *Old_game_types[OLD_MAX_GAME_TYPES] = { "Single Player Only", "Multiplayer Only", "Single/Multi Player", "Training mission" }; flag_def_list_new<Mission::Parse_Object_Flags> Parse_object_flags[] = { { "cargo-known", Mission::Parse_Object_Flags::SF_Cargo_known, true, false }, { "ignore-count", Mission::Parse_Object_Flags::SF_Ignore_count, true, false }, { "protect-ship", Mission::Parse_Object_Flags::OF_Protected, true, false }, { "reinforcement", Mission::Parse_Object_Flags::SF_Reinforcement, true, false }, { "no-shields", Mission::Parse_Object_Flags::OF_No_shields, true, false }, { "escort", Mission::Parse_Object_Flags::SF_Escort, true, false }, { "player-start", Mission::Parse_Object_Flags::OF_Player_start, true, false }, { "no-arrival-music", Mission::Parse_Object_Flags::SF_No_arrival_music, true, false }, { "no-arrival-warp", Mission::Parse_Object_Flags::SF_No_arrival_warp, true, false }, { "no-departure-warp", Mission::Parse_Object_Flags::SF_No_departure_warp, true, false }, { "locked", Mission::Parse_Object_Flags::SF_Locked, true, false }, { "invulnerable", Mission::Parse_Object_Flags::OF_Invulnerable, true, false }, { "hidden-from-sensors", Mission::Parse_Object_Flags::SF_Hidden_from_sensors, true, false }, { "scannable", Mission::Parse_Object_Flags::SF_Scannable, true, false }, { "kamikaze", Mission::Parse_Object_Flags::AIF_Kamikaze, true, false }, { "no-dynamic", Mission::Parse_Object_Flags::AIF_No_dynamic, true, false }, { "red-alert-carry", Mission::Parse_Object_Flags::SF_Red_alert_store_status, true, false }, { "beam-protect-ship", Mission::Parse_Object_Flags::OF_Beam_protected, true, false }, { "flak-protect-ship", Mission::Parse_Object_Flags::OF_Flak_protected, true, false }, { "laser-protect-ship", Mission::Parse_Object_Flags::OF_Laser_protected, true, false }, { "missile-protect-ship", Mission::Parse_Object_Flags::OF_Missile_protected, true, false }, { "guardian", Mission::Parse_Object_Flags::SF_Guardian, true, false }, { "special-warp", Mission::Parse_Object_Flags::Knossos_warp_in, true, false }, { "vaporize", Mission::Parse_Object_Flags::SF_Vaporize, true, false }, { "stealth", Mission::Parse_Object_Flags::SF_Stealth, true, false }, { "friendly-stealth-invisible", Mission::Parse_Object_Flags::SF_Friendly_stealth_invis, true, false }, { "don't-collide-invisible", Mission::Parse_Object_Flags::SF_Dont_collide_invis, true, false }, { "primitive-sensors", Mission::Parse_Object_Flags::SF_Primitive_sensors, true, false }, { "no-subspace-drive", Mission::Parse_Object_Flags::SF_No_subspace_drive, true, false }, { "nav-carry-status", Mission::Parse_Object_Flags::SF_Nav_carry_status, true, false }, { "affected-by-gravity", Mission::Parse_Object_Flags::SF_Affected_by_gravity, true, false }, { "toggle-subsystem-scanning", Mission::Parse_Object_Flags::SF_Toggle_subsystem_scanning, true, false }, { "targetable-as-bomb", Mission::Parse_Object_Flags::OF_Targetable_as_bomb, true, false }, { "no-builtin-messages", Mission::Parse_Object_Flags::SF_No_builtin_messages, true, false }, { "primaries-locked", Mission::Parse_Object_Flags::SF_Primaries_locked, true, false }, { "secondaries-locked", Mission::Parse_Object_Flags::SF_Secondaries_locked, true, false }, { "no-death-scream", Mission::Parse_Object_Flags::SF_No_death_scream, true, false }, { "always-death-scream", Mission::Parse_Object_Flags::SF_Always_death_scream, true, false }, { "nav-needslink", Mission::Parse_Object_Flags::SF_Nav_needslink, true, false }, { "hide-ship-name", Mission::Parse_Object_Flags::SF_Hide_ship_name, true, false }, { "set-class-dynamically", Mission::Parse_Object_Flags::SF_Set_class_dynamically, true, false }, { "lock-all-turrets", Mission::Parse_Object_Flags::SF_Lock_all_turrets_initially, true, false }, { "afterburners-locked", Mission::Parse_Object_Flags::SF_Afterburner_locked, true, false }, { "force-shields-on", Mission::Parse_Object_Flags::OF_Force_shields_on, true, false }, { "immobile", Mission::Parse_Object_Flags::OF_Immobile, true, false }, { "no-ets", Mission::Parse_Object_Flags::SF_No_ets, true, false }, { "cloaked", Mission::Parse_Object_Flags::SF_Cloaked, true, false }, { "ship-locked", Mission::Parse_Object_Flags::SF_Ship_locked, true, false }, { "weapons-locked", Mission::Parse_Object_Flags::SF_Weapons_locked, true, false }, { "scramble-messages", Mission::Parse_Object_Flags::SF_Scramble_messages, true, false }, { "no_collide", Mission::Parse_Object_Flags::OF_No_collide, true, false }, { "no-disabled-self-destruct", Mission::Parse_Object_Flags::SF_No_disabled_self_destruct, true, false } }; const size_t num_parse_object_flags = sizeof(Parse_object_flags) / sizeof(flag_def_list_new<Mission::Parse_Object_Flags>); // These are only the flags that are saved to the mission file. See the MEF_ #defines. flag_def_list Mission_event_flags[] = { { "interval & delay use msecs", MEF_USE_MSECS, 0 }, }; int Num_mission_event_flags = sizeof(Mission_event_flags) / sizeof(flag_def_list); const char *Mission_event_log_flags[MAX_MISSION_EVENT_LOG_FLAGS] = { "true", "false", "always true", // disabled "always false", "first repeat", "last repeat", "first trigger", "last trigger", "state change", }; //XSTR:ON int Num_reinforcement_type_names = sizeof(Reinforcement_type_names) / sizeof(char *); vec3d Parse_viewer_pos; matrix Parse_viewer_orient; int Loading_screen_bm_index=-1; // definitions for timestamps for eval'ing arrival/departure cues int Mission_arrival_timestamp; int Mission_departure_timestamp; fix Mission_end_time; #define ARRIVAL_TIMESTAMP 2000 // every 2 seconds #define DEPARTURE_TIMESTAMP 2200 // every 2.2 seconds -- just to be a little different // calculates a "unique" file signature as a ushort (checksum) and an int (file length) // the amount of The_mission we're going to checksum // WARNING : do NOT call this function on the server - it will overwrite goals, etc #define MISSION_CHECKSUM_SIZE (NAME_LENGTH + NAME_LENGTH + 4 + DATE_TIME_LENGTH + DATE_TIME_LENGTH) // timers used to limit arrival messages and music #define ARRIVAL_MUSIC_MIN_SEPARATION 60000 #define ARRIVAL_MESSAGE_MIN_SEPARATION 30000 #define ARRIVAL_MESSAGE_DELAY_MIN 2000 #define ARRIVAL_MESSAGE_DELAY_MAX 3000 static int Allow_arrival_music_timestamp; static int Allow_arrival_message_timestamp; static int Arrival_message_delay_timestamp; // multi TvT static int Allow_arrival_music_timestamp_m[2]; static int Allow_arrival_message_timestamp_m[2]; static int Arrival_message_delay_timestamp_m[2]; extern fix game_get_overall_frametime(); // for texture animation // local prototypes void parse_player_info2(mission *pm); bool post_process_mission(); int allocate_subsys_status(); void parse_common_object_data(p_object *objp); void parse_asteroid_fields(mission *pm); int mission_set_arrival_location(int anchor, int location, int distance, int objnum, int path_mask, vec3d *new_pos, matrix *new_orient); int get_anchor(const char *name); void mission_parse_set_up_initial_docks(); void mission_parse_set_arrival_locations(); void mission_set_wing_arrival_location( wing *wingp, int num_to_set ); void parse_init(bool basic = false); void parse_object_set_handled_flag_helper(p_object *pobjp, p_dock_function_info *infop); void parse_object_clear_all_handled_flags(); int parse_object_on_arrival_list(p_object *pobjp); int add_path_restriction(); static bool Warned_about_team_out_of_range; // Goober5000 void mission_parse_mark_non_arrival(p_object *p_objp); void mission_parse_mark_non_arrival(wing *wingp); void mission_parse_mark_non_arrivals(); // Goober5000 - FRED import void convertFSMtoFS2(); MONITOR(NumShipArrivals) MONITOR(NumShipDepartures) const std::shared_ptr<scripting::Hook> OnDepartureStartedHook = scripting::Hook::Factory( "On Departure Started", "Called when a ship starts the departure process.", { {"Ship", "ship", "The ship that has began the depture process."}, }); // Goober5000 void parse_custom_bitmap(const char *expected_string_640, const char *expected_string_1024, char *string_field_640, char *string_field_1024) { int found640 = 0, found1024 = 0; strcpy(string_field_640, ""); strcpy(string_field_1024, ""); // custom mission loading background, or whatever if (optional_string(expected_string_640)) { found640 = 1; stuff_string(string_field_640, F_NAME, MAX_FILENAME_LEN); } if (optional_string(expected_string_1024)) { found1024 = 1; stuff_string(string_field_1024, F_NAME, MAX_FILENAME_LEN); } // error testing if (Fred_running && (found640) && !(found1024)) { mprintf(("Mission: found an entry for %s but not a corresponding entry for %s!\n", expected_string_640, expected_string_1024)); } if (Fred_running && !(found640) && (found1024)) { mprintf(("Mission: found an entry for %s but not a corresponding entry for %s!\n", expected_string_1024, expected_string_640)); } } void parse_mission_info(mission *pm, bool basic = false) { char game_string[NAME_LENGTH]; // Goober5000 skip_to_start_of_string("#Mission Info"); required_string("#Mission Info"); required_string("$Version:"); stuff_float(&pm->version); if (pm->version != MISSION_VERSION) mprintf(("Older mission, should update it (%.2f<-->%.2f)\n", pm->version, MISSION_VERSION)); required_string("$Name:"); stuff_string(pm->name, F_NAME, NAME_LENGTH); required_string("$Author:"); stuff_string(pm->author, F_NAME, NAME_LENGTH); required_string("$Created:"); stuff_string(pm->created, F_DATE, DATE_TIME_LENGTH); required_string("$Modified:"); stuff_string(pm->modified, F_DATE, DATE_TIME_LENGTH); required_string("$Notes:"); stuff_string(pm->notes, F_NOTES, NOTES_LENGTH); if (optional_string("$Mission Desc:")) stuff_string(pm->mission_desc, F_MULTITEXT, MISSION_DESC_LENGTH); else strcpy_s(pm->mission_desc, NOX("No description\n")); pm->game_type = MISSION_TYPE_SINGLE; // default to single player only if ( optional_string("+Game Type:")) { // HACK HACK HACK -- stuff_string was changed to *not* ignore carriage returns. Since the // old style missions may have carriage returns, deal with it here. ignore_white_space(); stuff_string(game_string, F_NAME, NAME_LENGTH); for ( int i = 0; i < OLD_MAX_GAME_TYPES; i++ ) { if ( !stricmp(game_string, Old_game_types[i]) ) { // this block of code is now old mission compatibility code. We specify game // type in a different manner than before. if ( i == OLD_GAME_TYPE_SINGLE_ONLY ) pm->game_type = MISSION_TYPE_SINGLE; else if ( i == OLD_GAME_TYPE_MULTI_ONLY ) pm->game_type = MISSION_TYPE_MULTI; else if ( i == OLD_GAME_TYPE_SINGLE_MULTI ) pm->game_type = (MISSION_TYPE_SINGLE | MISSION_TYPE_MULTI ); else if ( i == OLD_GAME_TYPE_TRAINING ) pm->game_type = MISSION_TYPE_TRAINING; else Int3(); if ( pm->game_type & MISSION_TYPE_MULTI ) pm->game_type |= MISSION_TYPE_MULTI_COOP; break; } } } if ( optional_string("+Game Type Flags:") ) { stuff_int(&pm->game_type); } pm->flags.reset(); if (optional_string("+Flags:")){ stuff_flagset(&pm->flags); } // nebula mission stuff Neb2_awacs = -1.0f; if(optional_string("+NebAwacs:")){ stuff_float(&Neb2_awacs); } if(optional_string("+Storm:")){ stuff_string(Mission_parse_storm_name, F_NAME, NAME_LENGTH); if (!basic) nebl_set_storm(Mission_parse_storm_name); } Neb2_fog_near_mult = 1.0f; Neb2_fog_far_mult = 1.0f; if(optional_string("+Fog Near Mult:")){ stuff_float(&Neb2_fog_near_mult); } if(optional_string("+Fog Far Mult:")){ stuff_float(&Neb2_fog_far_mult); } // Goober5000 - ship contrail speed threshold pm->contrail_threshold = CONTRAIL_THRESHOLD_DEFAULT; if (optional_string("$Contrail Speed Threshold:")){ stuff_int(&pm->contrail_threshold); } // get the number of players if in a multiplayer mission pm->num_players = 1; if ( pm->game_type & MISSION_TYPE_MULTI ) { if ( optional_string("+Num Players:") ) { stuff_int( &(pm->num_players) ); } } // get the number of respawns pm->num_respawns = 0; if ( pm->game_type & MISSION_TYPE_MULTI ) { if ( optional_string("+Num Respawns:") ){ stuff_int( (int*)&(pm->num_respawns) ); } } The_mission.max_respawn_delay = -1; if ( pm->game_type & MISSION_TYPE_MULTI ) { if ( optional_string("+Max Respawn Time:") ){ stuff_int( &The_mission.max_respawn_delay ); } } if ( optional_string("+Red Alert:")) { int temp; stuff_int(&temp); pm->flags.set(Mission::Mission_Flags::Red_alert, temp != 0); } red_alert_invalidate_timestamp(); if ( optional_string("+Scramble:")) { int temp; stuff_int(&temp); pm->flags.set(Mission::Mission_Flags::Scramble, temp != 0); } // if we are just requesting basic info then skip everything else. the reason // for this is to make sure that we don't modify things outside of the mission struct // that might not get reset afterwards (like what can happen in the techroom) - taylor // // NOTE: this can be dangerous so be sure that any get_mission_info() call (defaults to basic info) will // only reference data parsed before this point!! (like current FRED2 and game code does) if (basic) return; // this is part of mission info but derived from the campaign file rather than parsed extern int debrief_find_persona_index(); pm->debriefing_persona = debrief_find_persona_index(); // set up support ships pm->support_ships.arrival_location = ARRIVE_AT_LOCATION; pm->support_ships.arrival_anchor = -1; pm->support_ships.departure_location = DEPART_AT_LOCATION; pm->support_ships.departure_anchor = -1; pm->support_ships.max_hull_repair_val = 0.0f; pm->support_ships.max_subsys_repair_val = 100.0f; //ASSUMPTION: full repair capabilities pm->support_ships.max_support_ships = -1; // infinite pm->support_ships.max_concurrent_ships = 1; pm->support_ships.ship_class = -1; pm->support_ships.tally = 0; pm->support_ships.support_available_for_species = 0; // for each species, store whether support is available for (int species = 0; species < (int)Species_info.size(); species++) { for (auto it = Ship_info.cbegin(); it != Ship_info.cend(); ++it) { if ((it->flags[Ship::Info_Flags::Support]) && (it->species == species)) { pm->support_ships.support_available_for_species |= (1 << species); break; } } } if ( optional_string("+Disallow Support:")) { int temp; stuff_int(&temp); pm->support_ships.max_support_ships = (temp > 0) ? 0 : -1; } if ( optional_string("+Hull Repair Ceiling:")) { float temp; stuff_float(&temp); //ONLY set max_hull_repair_val if the value given is valid -C if (temp <= 100.0f && temp >= 0.0f) { pm->support_ships.max_hull_repair_val = temp; } } if ( optional_string("+Subsystem Repair Ceiling:")) { float temp; stuff_float(&temp); //ONLY set max_subsys_repair_val if the value given is valid -C if (temp <= 100.0f && temp >= 0.0f) { pm->support_ships.max_subsys_repair_val = temp; } } if (optional_string("+All Teams Attack")){ Mission_all_attack = 1; } else { Mission_all_attack = 0; } // Maybe delay the player's entry. if (optional_string("+Player Entry Delay:")) { float temp; stuff_float(&temp); Assert(temp >= 0.0f); Entry_delay_time = fl2f(temp); } else { Entry_delay_time = 0; } if (optional_string("+Viewer pos:")){ stuff_vec3d(&Parse_viewer_pos); } if (optional_string("+Viewer orient:")){ stuff_matrix(&Parse_viewer_orient); } // possible squadron reassignment strcpy_s(pm->squad_name, ""); strcpy_s(pm->squad_filename, ""); if(optional_string("+SquadReassignName:")){ stuff_string(pm->squad_name, F_NAME, NAME_LENGTH); if(optional_string("+SquadReassignLogo:")){ stuff_string(pm->squad_filename, F_NAME, MAX_FILENAME_LEN); } } // always clear out squad reassignments if not single player if(Game_mode & GM_MULTIPLAYER){ strcpy_s(pm->squad_name, ""); strcpy_s(pm->squad_filename, ""); } // reassign the player else { if(!Fred_running && (Player != NULL) && (pm->squad_name[0] != '\0') && (Game_mode & GM_CAMPAIGN_MODE)){ mprintf(("Reassigning player to squadron %s\n", pm->squad_name)); player_set_squad(Player, pm->squad_name); player_set_squad_bitmap(Player, pm->squad_filename, false); } } // wing stuff by Goober5000 ------------------------------------------ // the wing name arrays are initialized in ship_level_init if (optional_string("$Starting wing names:")) { stuff_string_list(Starting_wing_names, MAX_STARTING_WINGS); } if (optional_string("$Squadron wing names:")) { stuff_string_list(Squadron_wing_names, MAX_SQUADRON_WINGS); } if (optional_string("$Team-versus-team wing names:")) { stuff_string_list(TVT_wing_names, MAX_TVT_WINGS); } // end of wing stuff ------------------------------------------------- // set up the Num_teams variable accoriding to the game_type variable' Num_teams = 1; // assume 1 // multiplayer team v. team games have two teams. If we have three teams, we need to use // a new mission mode! if ( (pm->game_type & MISSION_TYPE_MULTI) && (pm->game_type & MISSION_TYPE_MULTI_TEAMS) ){ Num_teams = 2; } // Goober5000 - made this into a function since we use much the same technique for the briefing background parse_custom_bitmap("$Load Screen 640:", "$Load Screen 1024:", pm->loading_screen[GR_640], pm->loading_screen[GR_1024]); strcpy_s(pm->skybox_model, ""); if (optional_string("$Skybox Model:")) { stuff_string(pm->skybox_model, F_NAME, MAX_FILENAME_LEN); } vm_set_identity(&pm->skybox_orientation); if (optional_string("+Skybox Orientation:")) { stuff_matrix(&pm->skybox_orientation); } if (optional_string("+Skybox Flags:")){ pm->skybox_flags = 0; stuff_int(&pm->skybox_flags); }else{ pm->skybox_flags = DEFAULT_NMODEL_FLAGS; } // Goober5000 - AI on a per-mission basis The_mission.ai_profile = &Ai_profiles[Default_ai_profile]; if (optional_string("$AI Profile:")) { int index; char temp[NAME_LENGTH]; stuff_string(temp, F_NAME, NAME_LENGTH); index = ai_profile_lookup(temp); if (index >= 0) The_mission.ai_profile = &Ai_profiles[index]; else WarningEx(LOCATION, "Mission: %s\nUnknown AI profile %s!", pm->name, temp ); } Assert( The_mission.ai_profile != NULL ); // Kazan - player use AI at start? if (pm->flags[Mission::Mission_Flags::Player_start_ai]) Player_use_ai = 1; pm->sound_environment.id = -1; if (optional_string("$Sound Environment:")) { char preset[65] = { '\0' }; stuff_string(preset, F_NAME, sizeof(preset)-1); int preset_id = ds_eax_get_preset_id(preset); if (preset_id >= 0) { sound_env_get(&pm->sound_environment, preset_id); } // NOTE: values will be clamped properly when the effect is actually set if (optional_string("+Volume:")) { stuff_float(&pm->sound_environment.volume); } if (optional_string("+Damping:")) { stuff_float(&pm->sound_environment.damping); } if (optional_string("+Decay Time:")) { stuff_float(&pm->sound_environment.decay); } } } void parse_player_info(mission *pm) { char temp[NAME_LENGTH]; Assert(pm != NULL); // alternate type names begin here mission_parse_reset_alt(); if(optional_string("#Alternate Types:")){ // read them all in while(!optional_string("#end")){ required_string("$Alt:"); stuff_string(temp, F_NAME, NAME_LENGTH); // maybe store it mission_parse_add_alt(temp); } } // callsigns begin here mission_parse_reset_callsign(); if(optional_string("#Callsigns:")){ // read them all in while(!optional_string("#end")){ required_string("$Callsign:"); stuff_string(temp, F_NAME, NAME_LENGTH); // maybe store it mission_parse_add_callsign(temp); } } Player_starts = 0; required_string("#Players"); while (required_string_either("#Objects", "$")){ parse_player_info2(pm); } } void parse_player_info2(mission *pm) { int nt, i; SCP_vector<loadout_row> list, list2; team_data *ptr; // read in a ship/weapon pool for each team. for ( nt = 0; nt < Num_teams; nt++ ) { int num_choices; ptr = &Team_data[nt]; // get the shipname for single player missions // MWA -- make this required later!!!! if ( optional_string("$Starting Shipname:") ) stuff_string( Player_start_shipname, F_NAME, NAME_LENGTH ); required_string("$Ship Choices:"); stuff_loadout_list(list, MISSION_LOADOUT_SHIP_LIST); num_choices = 0; // check ship class loadout entries for (auto &sc : list) { // in a campaign, see if the player is allowed the ships or not. Remove them from the // pool if they are not allowed if (Game_mode & GM_CAMPAIGN_MODE || (MULTIPLAYER_CLIENT)) { if ( !Campaign.ships_allowed[sc.index] ) continue; } if (sc.index < 0 || sc.index >= ship_info_size()) continue; ptr->ship_list[num_choices] = sc.index; // if the list isn't set by a variable leave the variable name empty if (sc.index_sexp_var == NOT_SET_BY_SEXP_VARIABLE) { strcpy_s(ptr->ship_list_variables[num_choices], "") ; } else { strcpy_s(ptr->ship_list_variables[num_choices], Sexp_variables[sc.index_sexp_var].variable_name); } ptr->ship_count[num_choices] = sc.count; ptr->loadout_total += sc.count; // if the list isn't set by a variable leave the variable name empty if (sc.count_sexp_var == NOT_SET_BY_SEXP_VARIABLE) { strcpy_s(ptr->ship_count_variables[num_choices], ""); } else { strcpy_s(ptr->ship_count_variables[num_choices], Sexp_variables[sc.count_sexp_var].variable_name); } num_choices++; } ptr->num_ship_choices = num_choices; ptr->default_ship = -1; if (optional_string("+Default_ship:")) { char str[NAME_LENGTH]; stuff_string(str, F_NAME, NAME_LENGTH); ptr->default_ship = ship_info_lookup(str); if (-1 == ptr->default_ship) { WarningEx(LOCATION, "Mission: %s\nUnknown default ship %s! Defaulting to %s.", pm->name, str, Ship_info[ptr->ship_list[0]].name ); ptr->default_ship = ptr->ship_list[0]; // default to 1st in list } // see if the player's default ship is an allowable ship (campaign only). If not, then what // do we do? choose the first allowable one? if (Game_mode & GM_CAMPAIGN_MODE || (MULTIPLAYER_CLIENT)) { if ( !(Campaign.ships_allowed[ptr->default_ship]) ) { for (i = 0; i < ship_info_size(); i++ ) { if ( Campaign.ships_allowed[i] ) { ptr->default_ship = i; break; } } Assertion( i < ship_info_size(), "Mission: %s: Could not find a valid default ship.\n", pm->name ); } } } if (ptr->default_ship == -1) // invalid or not specified, make first in list ptr->default_ship = ptr->ship_list[0]; required_string("+Weaponry Pool:"); stuff_loadout_list(list2, MISSION_LOADOUT_WEAPON_LIST); num_choices = 0; // check weapon class loadout entries for (auto &wc : list2) { // in a campaign, see if the player is allowed the weapons or not. Remove them from the // pool if they are not allowed if (Game_mode & GM_CAMPAIGN_MODE || (MULTIPLAYER_CLIENT)) { if ( !Campaign.weapons_allowed[wc.index] ) { continue; } } if (wc.index < 0 || wc.index >= weapon_info_size()) continue; // always allow the pool to be added in FRED, it is a verbal warning // to let the mission dev know about the problem if ( !(Weapon_info[wc.index].wi_flags[Weapon::Info_Flags::Player_allowed]) && !Fred_running ) { WarningEx(LOCATION, "Weapon '%s' in weapon pool isn't allowed on player loadout! Ignoring it ...\n", Weapon_info[wc.index].name); continue; } ptr->weaponry_pool[num_choices] = wc.index; ptr->weaponry_count[num_choices] = wc.count; // if the list isn't set by a variable leave the variable name empty if (wc.index_sexp_var == NOT_SET_BY_SEXP_VARIABLE) { strcpy_s(ptr->weaponry_pool_variable[num_choices], ""); } else { strcpy_s(ptr->weaponry_pool_variable[num_choices], Sexp_variables[wc.index_sexp_var].variable_name); } // if the list isn't set by a variable leave the variable name empty if (wc.count_sexp_var == NOT_SET_BY_SEXP_VARIABLE) { strcpy_s(ptr->weaponry_amount_variable[num_choices], ""); } else { strcpy_s(ptr->weaponry_amount_variable[num_choices], Sexp_variables[wc.count_sexp_var].variable_name); } num_choices++; } ptr->num_weapon_choices = num_choices; memset(ptr->weapon_required, 0, MAX_WEAPON_TYPES * sizeof(bool)); if (optional_string("+Required for mission:")) { int num_weapons; int weapon_list_buf[MAX_WEAPON_TYPES]; num_weapons = (int)stuff_int_list(weapon_list_buf, MAX_WEAPON_TYPES, WEAPON_LIST_TYPE); for (i = 0; i < num_weapons; i++) ptr->weapon_required[weapon_list_buf[i]] = true; } } if ( nt != Num_teams ) Error(LOCATION, "Not enough ship/weapon pools for mission. There are %d teams and only %d pools.", Num_teams, nt); } void parse_cutscenes(mission *pm) { pm->cutscenes.clear(); if (optional_string("#Cutscenes")) { mission_cutscene scene; while (!optional_string("#end")) { // this list should correspond to the MOVIE_* #defines scene.type = optional_string_one_of(6, "$Fiction Viewer Cutscene:", "$Command Brief Cutscene:", "$Briefing Cutscene:", "$Pre-game Cutscene:", "$Debriefing Cutscene:", "$Campaign End Cutscene:"); // no more cutscenes specified? if (scene.type < 0) break; // get the cutscene file stuff_string(scene.filename, F_NAME, NAME_LENGTH); // get the sexp if we have one if (optional_string("+formula:")) scene.formula = get_sexp_main(); else scene.formula = Locked_sexp_true; // add it pm->cutscenes.push_back(scene); } } } void parse_plot_info(mission * /*pm*/) { if (optional_string("#Plot Info")) { char dummy_filespec[FILESPEC_LENGTH]; char dummy_name[NAME_LENGTH]; required_string("$Tour:"); stuff_string(dummy_name, F_NAME, NAME_LENGTH); required_string("$Pre-Briefing Cutscene:"); stuff_string(dummy_filespec, F_FILESPEC, FILESPEC_LENGTH); required_string("$Pre-Mission Cutscene:"); stuff_string(dummy_filespec, F_FILESPEC, FILESPEC_LENGTH); required_string("$Next Mission Success:"); stuff_string(dummy_name, F_NAME, NAME_LENGTH); required_string("$Next Mission Partial:"); stuff_string(dummy_name, F_NAME, NAME_LENGTH); required_string("$Next Mission Failure:"); stuff_string(dummy_name, F_NAME, NAME_LENGTH); } } void parse_briefing_info(mission * /*pm*/) { char junk[4096]; if ( !optional_string("#Briefing Info") ) return; required_string("$Briefing Voice 1:"); stuff_string(junk, F_FILESPEC, sizeof(junk)); required_string("$Briefing Text 1:"); stuff_string(junk, F_MULTITEXTOLD, sizeof(junk)); required_string("$Briefing Voice 2:"); stuff_string(junk, F_FILESPEC, sizeof(junk)); required_string("$Briefing Text 2:"); stuff_string(junk, F_MULTITEXTOLD, sizeof(junk)); required_string("$Briefing Voice 3:"); stuff_string(junk, F_FILESPEC, sizeof(junk)); required_string("$Briefing Text 3:"); stuff_string(junk, F_MULTITEXTOLD, sizeof(junk)); required_string("$Debriefing Voice 1:"); stuff_string(junk, F_FILESPEC, sizeof(junk)); required_string("$Debriefing Text 1:"); stuff_string(junk, F_MULTITEXTOLD, sizeof(junk)); required_string("$Debriefing Voice 2:"); stuff_string(junk, F_FILESPEC, sizeof(junk)); required_string("$Debriefing Text 2:"); stuff_string(junk, F_MULTITEXTOLD, sizeof(junk)); required_string("$Debriefing Voice 3:"); stuff_string(junk, F_FILESPEC, sizeof(junk)); required_string("$Debriefing Text 3:"); stuff_string(junk, F_MULTITEXTOLD, sizeof(junk)); } /** * Parse the event music and briefing music for the mission */ void parse_music(mission *pm, int flags) { int i, index, num; char *ch; char temp[NAME_LENGTH]; event_music_reset_choices(); if ( !optional_string("#Music") ) { return; } required_string("$Event Music:"); stuff_string(pm->event_music_name, F_NAME, NAME_LENGTH); // Goober5000 if (optional_string("$Substitute Event Music:")) stuff_string(pm->substitute_event_music_name, F_NAME, NAME_LENGTH); required_string("$Briefing Music:"); stuff_string(pm->briefing_music_name, F_NAME, NAME_LENGTH); // Goober5000 if (optional_string("$Substitute Briefing Music:")) stuff_string(pm->substitute_briefing_music_name, F_NAME, NAME_LENGTH); // old stuff, apparently if (optional_string("$Debriefing Success Music:")) { stuff_string(temp, F_NAME, NAME_LENGTH); index = event_music_get_spooled_music_index(temp); if ((index >= 0) && ((Spooled_music[index].flags & SMF_VALID) || Fred_running)) { event_music_set_score(SCORE_DEBRIEF_SUCCESS, temp); } } // not old, just added since it makes sense if (optional_string("$Debriefing Average Music:")) { stuff_string(temp, F_NAME, NAME_LENGTH); index = event_music_get_spooled_music_index(temp); if ((index >= 0) && ((Spooled_music[index].flags & SMF_VALID) || Fred_running)) { event_music_set_score(SCORE_DEBRIEF_AVERAGE, temp); } } // old stuff if (optional_string("$Debriefing Fail Music:")) { stuff_string(temp, F_NAME, NAME_LENGTH); index = event_music_get_spooled_music_index(temp); if ((index >= 0) && ((Spooled_music[index].flags & SMF_VALID) || Fred_running)) { event_music_set_score(SCORE_DEBRIEF_FAIL, temp); } } // new stuff if (optional_string("$Fiction Viewer Music:")) { stuff_string(temp, F_NAME, NAME_LENGTH); event_music_set_score(SCORE_FICTION_VIEWER, temp); } // Goober5000 - if briefing not specified in import, default to BRIEF1 if (!stricmp(pm->briefing_music_name, "none") && (flags & MPF_IMPORT_FSM)) strcpy_s(pm->briefing_music_name, "BRIEF1"); // Goober5000 - old way of grabbing substitute music, but here for reverse compatibility if (optional_string("$Substitute Music:")) { stuff_string(pm->substitute_event_music_name, F_NAME, NAME_LENGTH, "," ); Mp++; stuff_string(pm->substitute_briefing_music_name, F_NAME, NAME_LENGTH); } // Goober5000 - if the mission is being imported, the substitutes are the specified tracks // (with FS1 prefixes) and we generate new specified tracks if (flags & MPF_IMPORT_FSM) { // no specified music? if (!stricmp(pm->event_music_name, "none")) goto done_event_music; // set the FS1 equivalent as the substitute strcpy_s(pm->substitute_event_music_name, "FS1-"); strcat_s(pm->substitute_event_music_name, pm->event_music_name); // if we have Marauder, it's in FS2 as Deuteronomy, so we're done if (!stricmp(pm->event_music_name, "7: Marauder") && event_music_get_soundtrack_index("5: Deuteronomy") >= 0) { strcpy_s(pm->event_music_name, "5: Deuteronomy"); goto done_event_music; } // search for something with the same track number strcpy_s(temp, pm->event_music_name); ch = strchr(temp, ':'); if (ch != NULL) { *(ch + 1) = '\0'; for (i = 0; i < Num_soundtracks; i++) { if (!strncmp(temp, Soundtracks[i].name, strlen(temp))) { strcpy_s(pm->event_music_name, Soundtracks[i].name); goto done_event_music; } } } // last resort: pick a random track out of the 7 FS2 soundtracks num = (Num_soundtracks < 7) ? Num_soundtracks : 7; strcpy_s(pm->event_music_name, Soundtracks[Random::next(num)].name); done_event_music: // no specified music? if (!stricmp(pm->briefing_music_name, "none")) goto done_briefing_music; // set the FS1 equivalent as the substitute strcpy_s(pm->substitute_briefing_music_name, "FS1-"); strcat_s(pm->substitute_briefing_music_name, pm->briefing_music_name); // Choco Mousse is the FS1 title soundtrack, so use Aquitaine in FS2 if (!stricmp(pm->briefing_music_name, "Choco Mousse") && event_music_get_spooled_music_index("Aquitaine") >= 0) { strcpy_s(pm->briefing_music_name, "Aquitaine"); goto done_briefing_music; } // we might have a match with the same track number if (event_music_get_spooled_music_index(pm->briefing_music_name) >= 0) goto done_briefing_music; // last resort: pick a random track out of the first 7 FS2 briefings (the regular ones)... num = (Num_music_files < 7) ? Num_music_files : 7; strcpy_s(pm->briefing_music_name, Spooled_music[Random::next(num)].name); done_briefing_music: /* NO-OP */ ; } // set the soundtrack, preferring the substitute in FS2 (not FRED!) index = event_music_get_soundtrack_index(pm->substitute_event_music_name); if ((index >= 0) && (Soundtracks[index].flags & EMF_VALID) && !Fred_running) { event_music_set_soundtrack(pm->substitute_event_music_name); } else { event_music_set_soundtrack(pm->event_music_name); } // set the briefing, preferring the substitute in FS2 (not FRED!) index = event_music_get_spooled_music_index(pm->substitute_briefing_music_name); if ((index >= 0) && (Spooled_music[index].flags & SMF_VALID) && !Fred_running) { event_music_set_score(SCORE_BRIEFING, pm->substitute_briefing_music_name); } else { event_music_set_score(SCORE_BRIEFING, pm->briefing_music_name); } } /** * Parse fiction viewer */ void parse_fiction(mission * /*pm*/) { fiction_viewer_reset(); if (optional_string("#Fiction Viewer")) { bool fiction_viewer_loaded = false; while (check_for_string("$File:")) { fiction_viewer_stage stage; memset(&stage, 0, sizeof(fiction_viewer_stage)); stage.formula = Locked_sexp_true; required_string("$File:"); stuff_string(stage.story_filename, F_FILESPEC, MAX_FILENAME_LEN); if (optional_string("$Font:")) stuff_string(stage.font_filename, F_FILESPEC, MAX_FILENAME_LEN); if (optional_string("$Voice:")) stuff_string(stage.voice_filename, F_FILESPEC, MAX_FILENAME_LEN); if (optional_string("$UI:")) stuff_string(stage.ui_name, F_NAME, NAME_LENGTH); parse_custom_bitmap("$Background 640:", "$Background 1024:", stage.background[GR_640], stage.background[GR_1024]); // get the sexp if we have one if (optional_string("$Formula:")) stage.formula = get_sexp_main(); if (strlen(stage.story_filename) > 0) { // now, store this stage Fiction_viewer_stages.push_back(stage); // see if this is the stage we want to display, then display it if (!Fred_running && !fiction_viewer_loaded && is_sexp_true(stage.formula)) { fiction_viewer_load((int)(Fiction_viewer_stages.size() - 1)); fiction_viewer_loaded = true; } } else { error_display(0, "Fiction viewer story filename may not be empty!"); } } } } /** * Parse command briefing */ void parse_cmd_brief(mission * /*pm*/) { int stage; Assert(!Cur_cmd_brief->num_stages); stage = 0; required_string("#Command Briefing"); // Yarn - use the same code as for mission loading screens parse_custom_bitmap("$Background 640:", "$Background 1024:", Cur_cmd_brief->background[GR_640], Cur_cmd_brief->background[GR_1024]); while (optional_string("$Stage Text:")) { Assert(stage < CMD_BRIEF_STAGES_MAX); stuff_string(Cur_cmd_brief->stage[stage].text, F_MULTITEXT, NULL); required_string("$Ani Filename:"); stuff_string(Cur_cmd_brief->stage[stage].ani_filename, F_FILESPEC, MAX_FILENAME_LEN); if (optional_string("+Wave Filename:")) stuff_string(Cur_cmd_brief->stage[stage].wave_filename, F_FILESPEC, MAX_FILENAME_LEN); else Cur_cmd_brief->stage[stage].wave_filename[0] = 0; stage++; } Cur_cmd_brief->num_stages = stage; } void parse_cmd_briefs(mission *pm) { int i; cmd_brief_reset(); // a hack follows because old missions don't have a command briefing if (required_string_either("#Command Briefing", "#Briefing")) return; for (i=0; i<Num_teams; i++) { Cur_cmd_brief = &Cmd_briefs[i]; parse_cmd_brief(pm); } } /** * Parse the data required for the mission briefing * * NOTE: This updates the global Briefing struct with all the data necessary to drive the briefing */ void parse_briefing(mission * /*pm*/, int flags) { int nt, i, j, stage_num = 0, icon_num = 0; brief_stage *bs; brief_icon *bi; briefing *bp; char not_used_text[MAX_ICON_TEXT_LEN]; brief_reset(); // MWA -- 2/3/98. we can now have multiple briefing and debriefings in a mission for ( nt = 0; nt < Num_teams; nt++ ) { if ( !optional_string("#Briefing") ) break; bp = &Briefings[nt]; required_string("$start_briefing"); // Goober5000 - use the same code as for mission loading screens parse_custom_bitmap("$briefing_background_640:", "$briefing_background_1024:", bp->background[GR_640], bp->background[GR_1024]); parse_custom_bitmap("$ship_select_background_640:", "$ship_select_background_1024:", bp->ship_select_background[GR_640], bp->ship_select_background[GR_1024]); parse_custom_bitmap("$weapon_select_background_640:", "$weapon_select_background_1024:", bp->weapon_select_background[GR_640], bp->weapon_select_background[GR_1024]); required_string("$num_stages:"); stuff_int(&bp->num_stages); Assert(bp->num_stages <= MAX_BRIEF_STAGES); stage_num = 0; while (required_string_either("$end_briefing", "$start_stage")) { required_string("$start_stage"); Assert(stage_num < MAX_BRIEF_STAGES); if (stage_num >= bp->num_stages) { error_display(1, "$num_stages did not match the number of specified stages! %d stages were specified but there is at least one more.", bp->num_stages); } bs = &bp->stages[stage_num++]; required_string("$multi_text"); stuff_string(bs->text, F_MULTITEXT, NULL); required_string("$voice:"); stuff_string(bs->voice, F_FILESPEC, MAX_FILENAME_LEN); required_string("$camera_pos:"); stuff_vec3d(&bs->camera_pos); required_string("$camera_orient:"); stuff_matrix(&bs->camera_orient); required_string("$camera_time:"); stuff_int(&bs->camera_time); if ( optional_string("$num_lines:") ) { stuff_int(&bs->num_lines); if ( Fred_running ) { Assert(bs->lines!=NULL); } else { if ( bs->num_lines > 0 ) { bs->lines = (brief_line *)vm_malloc(sizeof(brief_line)*bs->num_lines); Assert(bs->lines!=NULL); } } for (i=0; i<bs->num_lines; i++) { required_string("$line_start:"); stuff_int(&bs->lines[i].start_icon); required_string("$line_end:"); stuff_int(&bs->lines[i].end_icon); } } else { bs->num_lines = 0; } required_string("$num_icons:"); stuff_int(&bs->num_icons); if ( Fred_running ) { Assert(bs->icons!=NULL); } else { if ( bs->num_icons > 0 ) { bs->icons = (brief_icon *)vm_malloc(sizeof(brief_icon)*bs->num_icons); Assert(bs->icons!=NULL); } } if ( optional_string("$flags:") ) stuff_int(&bs->flags); else bs->flags = 0; if ( optional_string("$formula:") ) bs->formula = get_sexp_main(); else bs->formula = Locked_sexp_true; Assert(bs->num_icons <= MAX_STAGE_ICONS ); // static alias stuff - stupid, but it seems to be necessary static const char *temp_team_names[MAX_IFFS]; for (i = 0; i < Num_iffs; i++) temp_team_names[i] = Iff_info[i].iff_name; while (required_string_either("$end_stage", "$start_icon")) { required_string("$start_icon"); Assert(icon_num < MAX_STAGE_ICONS); // Make sure we don't cause a buffer overflow if $num_icons is wrong if (icon_num >= bs->num_icons) { error_display(1, "$num_icons did not match the number of specified icons! %d icons were specified but there is at least one more.", bs->num_icons); } bi = &bs->icons[icon_num++]; required_string("$type:"); stuff_int(&bi->type); // Goober5000 - import if (flags & MPF_IMPORT_FSM) { // someone changed the jump node icon to a Knossos, so change it back if (bi->type == ICON_KNOSSOS_DEVICE) bi->type = ICON_JUMP_NODE; // change largeship to transport else if (bi->type == ICON_LARGESHIP) bi->type = ICON_TRANSPORT; // ditto else if (bi->type == ICON_LARGESHIP_WING) bi->type = ICON_TRANSPORT_WING; } find_and_stuff("$team:", &bi->team, F_NAME, temp_team_names, Num_iffs, "team name"); find_and_stuff("$class:", &bi->ship_class, F_NAME, Ship_class_names, Ship_info.size(), "ship class"); bi->modelnum = -1; bi->model_instance_num = -1; // Goober5000 - import if (flags & MPF_IMPORT_FSM) { // the Faustus is a largeship if (!strnicmp(Ship_info[bi->ship_class].name, "GTSC Faustus", 12)) { if (bi->type == ICON_CRUISER) bi->type = ICON_LARGESHIP; else if (bi->type == ICON_CRUISER_WING) bi->type = ICON_LARGESHIP_WING; } // the Demon is a support ship :p else if (!strnicmp(Ship_info[bi->ship_class].name, "SD Demon", 8)) { bi->type = ICON_SUPPORT_SHIP; } // the Hades is a supercap else if (!strnicmp(Ship_info[bi->ship_class].name, "GTD Hades", 9)) { bi->type = ICON_SUPERCAP; } } required_string("$pos:"); stuff_vec3d(&bi->pos); bi->label[0] = 0; if (optional_string("$label:")) stuff_string(bi->label, F_MESSAGE, MAX_LABEL_LEN); if (optional_string("+id:")) { stuff_int(&bi->id); if (bi->id >= Cur_brief_id) Cur_brief_id = bi->id + 1; } else { bi->id = -1; for (i=0; i<stage_num-1; i++) for (j=0; j < bp->stages[i].num_icons; j++) { if (!stricmp(bp->stages[i].icons[j].label, bi->label)) bi->id = bp->stages[i].icons[j].id; } if (bi->id < 0) bi->id = Cur_brief_id++; } bi->flags=0; int val; required_string("$hlight:"); stuff_int(&val); if ( val>0 ) { bi->flags |= BI_HIGHLIGHT; } if (optional_string("$mirror:")) { stuff_int(&val); if ( val>0 ) { bi->flags |= BI_MIRROR_ICON; } } if (optional_string("$use wing icon:")) { stuff_int(&val); if ( val>0 ) { bi->flags |= BI_USE_WING_ICON; } } required_string("$multi_text"); stuff_string(not_used_text, F_MULTITEXT, MAX_ICON_TEXT_LEN); required_string("$end_icon"); } // end while if (icon_num != bs->num_icons) { error_display(1, "$num_icons did not match the number of specified icons! %d icons were specified but only %d were parsed.", bs->num_icons, icon_num); } icon_num = 0; required_string("$end_stage"); } // end while if (stage_num != bp->num_stages) { error_display(1, "$num_stages did not match the number of specified icons! %d stages were specified but only %d were parsed.", bp->num_stages, stage_num); } required_string("$end_briefing"); } if ( nt != Num_teams ) Error(LOCATION, "Not enough briefings in mission file. There are %d teams and only %d briefings.", Num_teams, nt ); } /** * Parse the data required for the mission debriefings */ void parse_debriefing_new(mission * /*pm*/) { int stage_num, nt; debriefing *db; debrief_stage *dbs; debrief_reset(); // 2/3/98 -- MWA. We can now have multiple briefings and debriefings on a team for ( nt = 0; nt < Num_teams; nt++ ) { if ( !optional_string("#Debriefing_info") ) break; stage_num = 0; db = &Debriefings[nt]; // Yarn - use the same code as for mission loading screens parse_custom_bitmap("$Background 640:", "$Background 1024:", db->background[GR_640], db->background[GR_1024]); required_string("$Num stages:"); stuff_int(&db->num_stages); Assert(db->num_stages <= MAX_DEBRIEF_STAGES); while (required_string_either("#", "$Formula")) { Assert(stage_num < MAX_DEBRIEF_STAGES); dbs = &db->stages[stage_num++]; required_string("$Formula:"); dbs->formula = get_sexp_main(); required_string("$multi text"); stuff_string(dbs->text, F_MULTITEXT, NULL); required_string("$Voice:"); stuff_string(dbs->voice, F_FILESPEC, MAX_FILENAME_LEN); required_string("$Recommendation text:"); stuff_string(dbs->recommendation_text, F_MULTITEXT, NULL); } // end while Assert(db->num_stages == stage_num); } if ( nt != Num_teams ) Error(LOCATION, "Not enough debriefings for mission. There are %d teams and only %d debriefings;\n", Num_teams, nt ); } void position_ship_for_knossos_warpin(object *objp) { ship *shipp = &Ships[objp->instance]; ship_info *sip = &Ship_info[shipp->ship_info_index]; object *knossos_objp = nullptr; float half_length, min_dist = -1.0f; vec3d center_pos, actual_local_center; vec3d new_point, new_center_pos, offset; // Assume no valid knossos device shipp->special_warpin_objnum = -1; // find closest knossos device (allow multiple knossoses) for (ship_obj *so = GET_FIRST(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so)) { object *ship_objp = &Objects[so->objnum]; if (Ship_info[Ships[ship_objp->instance].ship_info_index].flags[Ship::Info_Flags::Knossos_device]) { // is this the closest? (can use dist_squared since we're only comparing) float dist = vm_vec_dist_squared(&ship_objp->pos, &objp->pos); if (min_dist < 0.0f || dist < min_dist) { knossos_objp = ship_objp; min_dist = dist; } } } if (knossos_objp == nullptr) return; // set ship special_warpin_objnum shipp->special_warpin_objnum = OBJ_INDEX(knossos_objp); // determine the correct center of the model (which may not be the model's origin) if (object_is_docked(objp)) dock_calc_docked_actual_center(&actual_local_center, objp); else ship_class_get_actual_center(sip, &actual_local_center); // find world position of the center of the ship assembly vm_vec_unrotate(&center_pos, &actual_local_center, &objp->orient); vm_vec_add2(&center_pos, &objp->pos); // determine the half-length if (object_is_docked(objp)) { // we need to get the longitudinal radius of our ship, so find the semilatus rectum along the Z-axis half_length = dock_calc_max_semilatus_rectum_parallel_to_axis(objp, Z_AXIS); } else half_length = 0.5f * ship_class_get_length(sip); // position self for warp on plane of device float dist = fvi_ray_plane(&new_point, &knossos_objp->pos, &knossos_objp->orient.vec.fvec, &center_pos, &objp->orient.vec.fvec, 0.0f); vm_vec_scale_add(&new_center_pos, &center_pos, &objp->orient.vec.fvec, (dist - half_length)); // now move the actual ship based on how we moved the center vm_vec_sub(&offset, &new_center_pos, &center_pos); vm_vec_add2(&objp->pos, &offset); // if ship is HUGE, make it go through the center of the knossos if (sip->is_huge_ship()) { vm_vec_sub(&offset, &knossos_objp->pos, &new_point); vm_vec_add2(&objp->pos, &offset); } } /** * This is conceptually almost the same as ::obj_move_one_docked_object and is used in the same way. */ void parse_dock_one_docked_object(p_object *pobjp, p_object *parent_pobjp) { int dockpoint, parent_dockpoint; char *dockpoint_name, *parent_dockpoint_name; object *objp, *parent_objp; // get the actual in-game objects that will be docked objp = pobjp->created_object; parent_objp = parent_pobjp->created_object; // check valid if (!objp || !parent_objp) { Int3(); return; } // get dockpoint names dockpoint_name = dock_find_dockpoint_used_by_object(pobjp, parent_pobjp); parent_dockpoint_name = dock_find_dockpoint_used_by_object(parent_pobjp, pobjp); // check valid if (!dockpoint_name || !parent_dockpoint_name) { Int3(); return; } // resolve names to dockpoints dockpoint = model_find_dock_name_index(Ship_info[Ships[objp->instance].ship_info_index].model_num, dockpoint_name); parent_dockpoint = model_find_dock_name_index(Ship_info[Ships[parent_objp->instance].ship_info_index].model_num, parent_dockpoint_name); // check valid if ((dockpoint < 0) || (parent_dockpoint < 0)) { if (dockpoint < 0) ReleaseWarning(LOCATION, "Dockpoint %s could not be found on model %s", dockpoint_name, model_get(Ship_info[Ships[objp->instance].ship_info_index].model_num)->filename); if (parent_dockpoint < 0) ReleaseWarning(LOCATION, "Dockpoint %s could not be found on model %s", parent_dockpoint_name, model_get(Ship_info[Ships[parent_objp->instance].ship_info_index].model_num)->filename); return; } // dock them nprintf(("AI", "Initially docked: %s to parent %s\n", Ships[objp->instance].ship_name, Ships[parent_objp->instance].ship_name)); ai_dock_with_object(objp, dockpoint, parent_objp, parent_dockpoint, AIDO_DOCK_NOW); } int parse_create_object_sub(p_object *objp); // Goober5000 void parse_create_docked_object_helper(p_object *pobjp, p_dock_function_info *infop) { // create the object parse_create_object_sub(pobjp); // remove the object from the arrival list // (don't remove the leader, because he'll be removed the usual way) if (pobjp != infop->parameter_variables.objp_value) { // If an object is present at the beginning of the mission, it may not have been put on the arrival // list. This is totally dependent on the order the objects are parsed in the mission file because // that is the order in which they are created. All the objects in a docked group are created // simultaneously when and only when the leader is created. // if it's on the list, remove it if (parse_object_on_arrival_list(pobjp)) list_remove(&Ship_arrival_list, pobjp); } } /** * This is a bit tricky because of the way initial docking is now handled. * Docking groups require special treatment. */ int parse_create_object(p_object *pobjp) { object *objp; // if this guy is part of a dock group, create the entire group, starting with the leader if (object_is_docked(pobjp)) { p_dock_function_info dfi; // we should only be calling this for dock leaders, because the dock leader // governs the creation of his entire group Assert((pobjp->flags[Mission::Parse_Object_Flags::SF_Dock_leader])); // if the leader will be destroyed before the mission starts, then *only* create the leader; // don't create the rest of the group (this is what retail did) if (pobjp->destroy_before_mission_time >= 0) return parse_create_object_sub(pobjp); // store the leader as a parameter dfi.parameter_variables.objp_value = pobjp; // Just as we couldn't create the parse dock trees until we had parsed them all, // we can't dock the in-game objects until we have created them all. :p // create all the objects dock_evaluate_all_docked_objects(pobjp, &dfi, parse_create_docked_object_helper); // dock all the objects dock_dock_docked_objects(pobjp); // now clear the handled flags parse_object_clear_all_handled_flags(); } // create normally else { parse_create_object_sub(pobjp); } // get the main object objp = pobjp->created_object; // if arriving through knossos, adjust objp->pos to plane of knossos and set object reference // special warp is single player only if ((pobjp->flags[Mission::Parse_Object_Flags::Knossos_warp_in]) && !(Game_mode & GM_MULTIPLAYER)) { if (!Fred_running) position_ship_for_knossos_warpin(objp); } // warp it in (moved from parse_create_object_sub) if ((Game_mode & GM_IN_MISSION) && (!Fred_running) && (!Game_restoring)) { if ((Ships[objp->instance].wingnum < 0) && (pobjp->arrival_location != ARRIVE_FROM_DOCK_BAY)) { shipfx_warpin_start(objp); } } // return the main object's objnum return OBJ_INDEX(objp); } void parse_bring_in_docked_wing(p_object *p_objp, int wingnum, int shipnum); /** * Given a stuffed p_object struct, create an object and fill in the necessary fields. * @return object number. */ int parse_create_object_sub(p_object *p_objp) { int i, j, k, objnum, shipnum; int anchor_objnum = -1; bool brought_in_docked_wing = false; ai_info *aip; ship_subsys *ptr; ship *shipp; ship_info *sip; subsys_status *sssp; ship_weapon *wp; // texture replacements polymodel *pm; MONITOR_INC(NumShipArrivals, 1); // base level creation - need ship name in case of duplicate textures objnum = ship_create(&p_objp->orient, &p_objp->pos, p_objp->ship_class, p_objp->name); Assert(objnum != -1); shipnum = Objects[objnum].instance; shipp = &Ships[shipnum]; sip = &Ship_info[shipp->ship_info_index]; // Goober5000 - make the parse object aware of what it was created as p_objp->created_object = &Objects[objnum]; // Goober5000 - if this object is being created because he's docked to something, // and he's in a wing, then mark the wing as having arrived if (object_is_docked(p_objp) && !(p_objp->flags[Mission::Parse_Object_Flags::SF_Dock_leader]) && (p_objp->wingnum >= 0)) { if (!Fred_running) { parse_bring_in_docked_wing(p_objp, p_objp->wingnum, shipnum); brought_in_docked_wing = true; } } shipp->group = p_objp->group; shipp->team = p_objp->team; shipp->display_name = p_objp->display_name; shipp->escort_priority = p_objp->escort_priority; shipp->use_special_explosion = p_objp->use_special_explosion; shipp->special_exp_damage = p_objp->special_exp_damage; shipp->special_exp_blast = p_objp->special_exp_blast; shipp->special_exp_inner = p_objp->special_exp_inner; shipp->special_exp_outer = p_objp->special_exp_outer; shipp->use_shockwave = p_objp->use_shockwave; shipp->special_exp_shockwave_speed = p_objp->special_exp_shockwave_speed; shipp->special_exp_deathroll_time = p_objp->special_exp_deathroll_time; shipp->special_hitpoints = p_objp->special_hitpoints; shipp->special_shield = p_objp->special_shield; for (i=0;i<MAX_IFFS;i++) { for (j=0;j<MAX_IFFS;j++) { shipp->ship_iff_color[i][j] = p_objp->alt_iff_color[i][j]; } } shipp->ship_max_shield_strength = p_objp->ship_max_shield_strength; shipp->ship_max_hull_strength = p_objp->ship_max_hull_strength; shipp->max_shield_recharge = p_objp->max_shield_recharge; // Goober5000 - ugh, this is really stupid having to do this here; if the // ship creation code was better organized this wouldn't be necessary if (shipp->special_hitpoints > 0) { float hull_factor = shipp->ship_max_hull_strength / sip->max_hull_strength; ship_subsys *ss; for (ss = GET_FIRST(&shipp->subsys_list); ss != END_OF_LIST(&shipp->subsys_list) && ss != NULL; ss = GET_NEXT(ss)) { ss->max_hits *= hull_factor; if (Fred_running) ss->current_hits = 0.0f; else ss->current_hits = ss->max_hits; } ship_recalc_subsys_strength(shipp); } // Goober5000 - this is also stupid; this is in ship_set but it needs to be done here because of the special hitpoints mod Objects[objnum].hull_strength = shipp->ship_max_hull_strength; shipp->respawn_priority = p_objp->respawn_priority; // if this is a multiplayer dogfight game, and its from a player wing, make it team traitor if (MULTI_DOGFIGHT && (p_objp->wingnum >= 0)) { for (i = 0; i < MAX_STARTING_WINGS; i++) { if (!stricmp(Starting_wing_names[i], Wings[p_objp->wingnum].name)) shipp->team = Iff_traitor; } } // alternate stuff shipp->alt_type_index = p_objp->alt_type_index; shipp->callsign_index = p_objp->callsign_index; // AI stuff. Note a lot of the AI was already initialized in ship_create. aip = &(Ai_info[shipp->ai_index]); aip->ai_class = p_objp->ai_class; shipp->weapons.ai_class = p_objp->ai_class; // Fred uses this instead of above. //Fixes a bug where the AI class attributes were not copied if the AI class was set in the mission. if (The_mission.ai_profile->flags[AI::Profile_Flags::Fix_ai_class_bug]) ship_set_new_ai_class(shipp, p_objp->ai_class); aip->behavior = p_objp->behavior; aip->mode = aip->behavior; // make sure aim_safety has its submode defined if (aip->mode == AIM_SAFETY) { aip->submode = AISS_1; } shipp->cargo1 = p_objp->cargo1; shipp->arrival_location = p_objp->arrival_location; shipp->arrival_distance = p_objp->arrival_distance; shipp->arrival_anchor = p_objp->arrival_anchor; shipp->arrival_path_mask = p_objp->arrival_path_mask; shipp->arrival_cue = p_objp->arrival_cue; shipp->arrival_delay = p_objp->arrival_delay; shipp->departure_location = p_objp->departure_location; shipp->departure_anchor = p_objp->departure_anchor; shipp->departure_path_mask = p_objp->departure_path_mask; shipp->departure_cue = p_objp->departure_cue; shipp->departure_delay = p_objp->departure_delay; shipp->wingnum = p_objp->wingnum; shipp->hotkey = p_objp->hotkey; shipp->score = p_objp->score; shipp->assist_score_pct = p_objp->assist_score_pct; shipp->persona_index = p_objp->persona_index; if (Ship_info[shipp->ship_info_index].uses_team_colors && !p_objp->team_color_setting.empty()) shipp->team_name = p_objp->team_color_setting; if (p_objp->warpin_params_index >= 0) shipp->warpin_params_index = p_objp->warpin_params_index; if (p_objp->warpout_params_index >= 0) shipp->warpout_params_index = p_objp->warpout_params_index; // now that we have our correct warpout params, set the warp effects if (!Fred_running) { ship_set_warp_effects(&Objects[objnum]); } // reset texture animations shipp->base_texture_anim_frametime = game_get_overall_frametime(); // handle the replacement textures shipp->apply_replacement_textures(p_objp->replacement_textures); // Copy across the alt classes (if any) for FRED if (Fred_running) { shipp->s_alt_classes = p_objp->alt_classes; } // check the parse object's flags for possible things to set on this newly created ship resolve_parse_flags(&Objects[objnum], p_objp->flags); // other flag checks //////////////////////// // forcing the shields on or off depending on flags -- but only if shield strength supports it // no strength means we can't have shields, period if (p_objp->ship_max_shield_strength == 0.0f) Objects[objnum].flags.set(Object::Object_Flags::No_shields); // force shields on means we have them regardless of other flags; per r5332 this ranks above the next check else if (p_objp->flags[Mission::Parse_Object_Flags::OF_Force_shields_on]) Objects[objnum].flags.remove(Object::Object_Flags::No_shields); // intrinsic no-shields means we have them off in-game else if (!Fred_running && (sip->flags[Ship::Info_Flags::Intrinsic_no_shields])) Objects[objnum].flags.set(Object::Object_Flags::No_shields); // don't set the flag if the mission is ongoing in a multiplayer situation. This will be set by the players in the // game only before the game or during respawning. // MWA -- changed the next line to remove the !(Game_mode & GM_MULTIPLAYER). We shouldn't be setting // this flag in single player mode -- it gets set in post process mission. if ((p_objp->flags[Mission::Parse_Object_Flags::OF_Player_start]) && (Fred_running || ((Game_mode & GM_MULTIPLAYER) && !(Game_mode & GM_IN_MISSION)))) { Objects[objnum].flags.set(Object::Object_Flags::Player_ship); } // a couple of ai_info flags. Also, do a reasonable default for the kamikaze damage regardless of // whether this flag is set or not if (p_objp->flags[Mission::Parse_Object_Flags::AIF_Kamikaze]) { Ai_info[shipp->ai_index].ai_flags.set(AI::AI_Flags::Kamikaze); Ai_info[shipp->ai_index].kamikaze_damage = p_objp->kamikaze_damage; } if (p_objp->flags[Mission::Parse_Object_Flags::AIF_No_dynamic]) Ai_info[shipp->ai_index].ai_flags.set(AI::AI_Flags::No_dynamic); if (p_objp->flags[Mission::Parse_Object_Flags::SF_Red_alert_store_status]) { if (!(Game_mode & GM_MULTIPLAYER)) { shipp->flags.set(Ship::Ship_Flags::Red_alert_store_status); } } if (p_objp->flags[Mission::Parse_Object_Flags::Knossos_warp_in]) { Objects[objnum].flags.set(Object::Object_Flags::Special_warpin); Knossos_warp_ani_used = 1; } // set the orders that this ship will accept. It will have already been set to default from the // ship create code, so only set them if the parse object flags say they are unique if (p_objp->flags[Mission::Parse_Object_Flags::SF_Use_unique_orders]) { shipp->orders_accepted = p_objp->orders_accepted; // MWA 5/15/98 -- Added the following debug code because some orders that ships // will accept were apparently written out incorrectly with Fred. This Int3() should // trap these instances. #ifndef NDEBUG if (Fred_running) { int default_orders, remaining_orders; default_orders = ship_get_default_orders_accepted(&Ship_info[shipp->ship_info_index]); remaining_orders = p_objp->orders_accepted & ~default_orders; if (remaining_orders) { Warning(LOCATION, "Ship %s has orders which it will accept that are\nnot part of default orders accepted.\n\nPlease reedit this ship and change the orders again\n", shipp->ship_name); } } #endif } if (p_objp->flags[Mission::Parse_Object_Flags::SF_Dock_leader]) shipp->flags.set(Ship::Ship_Flags::Dock_leader); if (p_objp->flags[Mission::Parse_Object_Flags::SF_Warp_broken]) shipp->flags.set(Ship::Ship_Flags::Warp_broken); if (p_objp->flags[Mission::Parse_Object_Flags::SF_Warp_never]) shipp->flags.set(Ship::Ship_Flags::Warp_never); if (p_objp->flags[Mission::Parse_Object_Flags::SF_Has_display_name]) shipp->flags.set(Ship::Ship_Flags::Has_display_name); //////////////////////// // if ship is in a wing, and the wing's no_warp_effect flag is set, then set the equivalent // flag for the ship if ((shipp->wingnum != -1) && (Wings[shipp->wingnum].flags[Ship::Wing_Flags::No_arrival_warp])) shipp->flags.set(Ship::Ship_Flags::No_arrival_warp); if ((shipp->wingnum != -1) && (Wings[shipp->wingnum].flags[Ship::Wing_Flags::No_departure_warp])) shipp->flags.set(Ship::Ship_Flags::No_departure_warp); // ditto for Kazan if ((shipp->wingnum != -1) && (Wings[shipp->wingnum].flags[Ship::Wing_Flags::Nav_carry])) { shipp->flags.set(Ship::Ship_Flags::Navpoint_carry); } // if the wing index and wing pos are set for this parse object, set them for the ship. This // is useful in multiplayer when ships respawn shipp->wing_status_wing_index = p_objp->wing_status_wing_index; shipp->wing_status_wing_pos = p_objp->wing_status_wing_pos; // set up the ai_goals for this object -- all ships created here are AI controlled. if (p_objp->ai_goals != -1) { int sexp; // set up the ai goals for this object. for (sexp = CDR(p_objp->ai_goals); sexp != -1; sexp = CDR(sexp)) ai_add_ship_goal_sexp(sexp, AIG_TYPE_EVENT_SHIP, aip); // free the sexpression nodes only for non-wing ships. wing code will handle its own case if (p_objp->wingnum < 0) free_sexp2(p_objp->ai_goals); // free up sexp nodes for reuse, since they aren't needed anymore. } Assert(sip->model_num != -1); // initialize subsystem statii here. The subsystems are given a percentage damaged. So a percent value // of 20% means that the subsystem is 20% damaged (*not* 20% of max hits). This is opposite the way // that the initial velocity/hull strength/shields work i = p_objp->subsys_count; while (i--) { sssp = &Subsys_status[p_objp->subsys_index + i]; if (!stricmp(sssp->name, NOX("Pilot"))) { ptr = nullptr; wp = &shipp->weapons; } else { ptr = ship_get_subsys(shipp, sssp->name); // find the subsystem in the ship list that corresponds to the parsed subsystem if (!ptr) { Warning(LOCATION, "Unable to find '%s' in the ship %s (class %s) subsys_list!", sssp->name, shipp->ship_name, sip->name); continue; } wp = &ptr->weapons; } if (sssp->primary_banks[0] != SUBSYS_STATUS_NO_CHANGE) { for (j = k = 0; j < MAX_SHIP_PRIMARY_BANKS; ++j) { // skip over any empty primary banks unless we are in FRED if ((sssp->primary_banks[j] >= 0) || Fred_running) { wp->primary_bank_weapons[k] = sssp->primary_banks[j]; ++k; } } if (Fred_running) { // only do this for the Pilot subsystem if (!ptr) wp->num_primary_banks = sip->num_primary_banks; } else wp->num_primary_banks = k; } for (j = 0; j < wp->num_primary_banks; ++j) { if (Fred_running) { wp->primary_bank_ammo[j] = sssp->primary_ammo[j]; } else if (wp->primary_bank_weapons[j] >= 0 && Weapon_info[wp->primary_bank_weapons[j]].wi_flags[Weapon::Info_Flags::Ballistic]) { Assertion(Weapon_info[wp->primary_bank_weapons[j]].cargo_size > 0.0f, "Primary weapon cargo size <= 0. Ship (%s) Subsystem (%s) Bank (%i) Weapon (%s)", shipp->ship_name, sssp->name,j,Weapon_info[wp->primary_bank_weapons[j]].name); // Pilot subsystem ammo depends on ship ammo capacity // in contrast non pilot subsystems depend on the bank capacity of the subsystem int ammo_cap; if (!ptr) { ammo_cap = sip->primary_bank_ammo_capacity[j]; } else { ammo_cap = wp->primary_bank_capacity[j]; } int capacity = (int)std::lround(sssp->primary_ammo[j] / 100.0f * ammo_cap); wp->primary_bank_ammo[j] = (int)std::lround(capacity / Weapon_info[wp->primary_bank_weapons[j]].cargo_size); } } if (sssp->secondary_banks[0] != SUBSYS_STATUS_NO_CHANGE) { for (j = k = 0; j < MAX_SHIP_SECONDARY_BANKS; ++j) { // skip over any empty secondary banks unless we are in FRED if ((sssp->secondary_banks[j] >= 0) || Fred_running) { wp->secondary_bank_weapons[k] = sssp->secondary_banks[j]; ++k; } } if (Fred_running) { // only do this for the Pilot subsystem if (!ptr) wp->num_secondary_banks = sip->num_secondary_banks; } else wp->num_secondary_banks = k; } for (j = 0; j < wp->num_secondary_banks; ++j) { if (Fred_running) { wp->secondary_bank_ammo[j] = sssp->secondary_ammo[j]; } else if (wp->secondary_bank_weapons[j] >= 0) { Assertion(Weapon_info[wp->secondary_bank_weapons[j]].cargo_size > 0.0f, "Secondary weapon cargo size <= 0. Ship (%s) Subsystem (%s) Bank (%i) Weapon (%s)", shipp->ship_name, sssp->name, j, Weapon_info[wp->secondary_bank_weapons[j]].name); // Pilot subsystem ammo depends on ship ammo capacity // in contrast non pilot subsystems depend on the bank capacity of the subsystem int ammo_cap; if (!ptr) { ammo_cap = sip->secondary_bank_ammo_capacity[j]; } else { ammo_cap = wp->secondary_bank_capacity[j]; } int capacity = (int)std::lround(sssp->secondary_ammo[j] / 100.0f * ammo_cap); wp->secondary_bank_ammo[j] = (int)std::lround(capacity / Weapon_info[wp->secondary_bank_weapons[j]].cargo_size); } } // if we are parsing a Pilot subsystem, skip the rest if (!ptr) continue; // check the mission flag to possibly free all beam weapons - Goober5000, taken from SEXP.CPP if (The_mission.flags[Mission::Mission_Flags::Beam_free_all_by_default]) { // mark all turrets as beam free if(ptr->system_info->type == SUBSYSTEM_TURRET) { ptr->weapons.flags.set(Ship::Weapon_Flags::Beam_Free); ptr->turret_next_fire_stamp = timestamp((int) frand_range(50.0f, 4000.0f)); } } if (shipp->flags[Ship::Ship_Flags::Lock_all_turrets_initially] || ptr->system_info->flags[Model::Subsystem_Flags::Turret_locked]) { // mark all turrets as locked if(ptr->system_info->type == SUBSYSTEM_TURRET) { ptr->weapons.flags.set(Ship::Weapon_Flags::Turret_Lock); } } if (Fred_running) { ptr->current_hits = sssp->percent; ptr->max_hits = 100.0f; } else { ptr->max_hits = ptr->system_info->max_subsys_strength * (shipp->ship_max_hull_strength / sip->max_hull_strength); float new_hits = ptr->max_hits * (100.0f - sssp->percent) / 100.f; if (!(ptr->flags[Ship::Subsystem_Flags::No_aggregate])) { shipp->subsys_info[ptr->system_info->type].aggregate_current_hits -= (ptr->max_hits - new_hits); } if ((100.0f - sssp->percent) < 0.5) { ptr->current_hits = 0.0f; if (ptr->submodel_instance_1 != nullptr) ptr->submodel_instance_1->blown_off = true; } else { ptr->current_hits = new_hits; } } ptr->subsys_cargo_name = sssp->subsys_cargo_name; if (sssp->ai_class != SUBSYS_STATUS_NO_CHANGE) ptr->weapons.ai_class = sssp->ai_class; ptr->turret_animation_position = MA_POS_NOT_SET; // model animation position is not set ptr->turret_animation_done_time = 0; } // initial hull strength, shields, and velocity are all expressed as a percentage of the max value/ // so a initial_hull value of 90% means 90% of max. This way is opposite of how subsystems are dealt // with if (Fred_running) { Objects[objnum].phys_info.speed = (float) p_objp->initial_velocity; Objects[objnum].hull_strength = (float) p_objp->initial_hull; Objects[objnum].shield_quadrant[0] = (float) p_objp->initial_shields; } else { int max_allowed_sparks, num_sparks, iLoop; Objects[objnum].hull_strength = p_objp->initial_hull * shipp->ship_max_hull_strength / 100.0f; for (iLoop = 0; iLoop<Objects[objnum].n_quadrants; iLoop++) { Objects[objnum].shield_quadrant[iLoop] = (float) (shipp->max_shield_recharge * p_objp->initial_shields * shield_get_max_quad(&Objects[objnum]) / 100.0f); } // initial velocities now do not apply to ships which warp in after mission starts // WMC - Make it apply for ships with IN_PLACE_ANIM type // zookeeper - Also make it apply for hyperspace warps if (!(Game_mode & GM_IN_MISSION) || (Warp_params[shipp->warpin_params_index].warp_type == WT_IN_PLACE_ANIM || Warp_params[shipp->warpin_params_index].warp_type == WT_HYPERSPACE)) { Objects[objnum].phys_info.speed = (float) p_objp->initial_velocity * sip->max_speed / 100.0f; // prev_ramp_vel needs to be in local coordinates // set z of prev_ramp_vel to initial velocity vm_vec_zero(&Objects[objnum].phys_info.prev_ramp_vel); Objects[objnum].phys_info.prev_ramp_vel.xyz.z = Objects[objnum].phys_info.speed; // convert to global coordinates and set to ship velocity and desired velocity vm_vec_unrotate(&Objects[objnum].phys_info.vel, &Objects[objnum].phys_info.prev_ramp_vel, &Objects[objnum].orient); Objects[objnum].phys_info.desired_vel = Objects[objnum].phys_info.vel; } // recalculate damage of subsystems ship_recalc_subsys_strength(&Ships[shipnum]); // create sparks on a ship whose hull is damaged. We will create two sparks for every 20% // of hull damage done. 100 means no sparks. between 80 and 100 do two sparks. 60 and 80 is // four, etc. pm = model_get(sip->model_num); max_allowed_sparks = get_max_sparks(&Objects[objnum]); num_sparks = (int)((100.0f - p_objp->initial_hull) / 5.0f); if (num_sparks > max_allowed_sparks) num_sparks = max_allowed_sparks; for (iLoop = 0; iLoop < num_sparks; iLoop++) { vec3d v1, v2; // DA 10/20/98 - sparks must be chosen on the hull and not any submodel submodel_get_two_random_points_better(sip->model_num, pm->detail[0], &v1, &v2); ship_hit_sparks_no_rotate(&Objects[objnum], &v1); } } // in mission, we add a log entry -- set ship positions for ships not in wings, and then do // warpin effect if ((Game_mode & GM_IN_MISSION) && (!Fred_running)) { mission_log_add_entry(LOG_SHIP_ARRIVED, shipp->ship_name, NULL); if (!Game_restoring) { // if this ship isn't in a wing, determine its arrival location if (shipp->wingnum == -1) { int location; // multiplayer clients set the arrival location of ships to be at location since their // position has already been determined. Don't actually set the variable since we // don't want the warp effect to show if coming from a dock bay. location = p_objp->arrival_location; if (MULTIPLAYER_CLIENT) location = ARRIVE_AT_LOCATION; anchor_objnum = mission_set_arrival_location(p_objp->arrival_anchor, location, p_objp->arrival_distance, objnum, p_objp->arrival_path_mask, NULL, NULL); // Goober5000 - warpin start moved to parse_create_object } } // possibly add this ship to a hotkey set // Ships can now have both a ship-hotkey and a wing-hotkey -- FSF if (shipp->hotkey != -1) mission_hotkey_mf_add(shipp->hotkey, shipp->objnum, HOTKEY_MISSION_FILE_ADDED); if ((shipp->wingnum != -1) && (Wings[shipp->wingnum].hotkey != -1)) mission_hotkey_mf_add(Wings[shipp->wingnum].hotkey, shipp->objnum, HOTKEY_MISSION_FILE_ADDED); // possibly add this ship to the hud escort list if (shipp->flags[Ship::Ship_Flags::Escort]) hud_add_remove_ship_escort(objnum, 1); } // for multiplayer games, make a call to the network code to assign the object signature // of the newly created object. The network host of the netgame will always assign a signature // to a newly created object. The network signature will get to the clients of the game in // different manners depending on whether or not an individual ship or a wing was created. if (Game_mode & GM_MULTIPLAYER) { Objects[objnum].net_signature = p_objp->net_signature; // Goober5000 - for an initially docked group, only send the packet for the dock leader... this is necessary so that the // docked hierarchy of objects can be created in the right order on the client side if (!object_is_docked(p_objp) || (p_objp->flags[Mission::Parse_Object_Flags::SF_Dock_leader])) { if ((Game_mode & GM_IN_MISSION) && MULTIPLAYER_MASTER && (p_objp->wingnum == -1)) send_ship_create_packet(&Objects[objnum], (p_objp == Arriving_support_ship)); } // also add this ship to the multi ship tracking and interpolation struct multi_ship_record_add_ship(objnum); } // If the ship is in a wing, this will be done in mission_set_wing_arrival_location() instead // If the ship is in a wing, but the wing is docked then addition of bool brought_in_docked_wing accounts for that status --wookieejedi if (Game_mode & GM_IN_MISSION && ((shipp->wingnum == -1) || (brought_in_docked_wing))) { object *anchor_objp = (anchor_objnum >= 0) ? &Objects[anchor_objnum] : nullptr; Script_system.SetHookObjects(2, "Ship", &Objects[objnum], "Parent", anchor_objp); Script_system.RunCondition(CHA_ONSHIPARRIVE, &Objects[objnum]); Script_system.RemHookVars({"Ship", "Parent"}); if (Ship_info[shipp->ship_info_index].is_big_or_huge() && !brought_in_docked_wing) { float mission_time = f2fl(Missiontime); int minutes = (int)(mission_time / 60); int seconds = (int)mission_time % 60; mprintf(("%s arrived at %02d:%02d\n", shipp->ship_name, minutes, seconds)); } } return objnum; } /** * There are a bunch of assumptions in the code that, in FS2, the wing will be created first, and * then it will create its component ships. If a wing arrives because all its ships were docked * to something else, these assumptions are turned inside out. So we have to sort of bootstrap * the creation of the wing by running a subset of the code from parse_wing_create_ships(). */ void parse_bring_in_docked_wing(p_object *p_objp, int wingnum, int shipnum) { Assert(!Fred_running); Assert(p_objp != NULL); Assert(wingnum >= 0); Assert(shipnum >= 0); int j, index; wing *wingp = &Wings[wingnum]; // link ship and wing together // (do this first because mission log relies on ship_index) wingp->ship_index[p_objp->pos_in_wing] = shipnum; Ships[shipnum].wingnum = wingnum; // has this wing arrived at all yet? if (wingp->current_wave == 0) { wingp->current_wave++; mission_log_add_entry( LOG_WING_ARRIVED, wingp->name, NULL, wingp->current_wave ); wingp->wave_delay_timestamp = timestamp(-1); } // how did we get more than one wave here? else if (wingp->current_wave > 1) Error(LOCATION, "Wing %s was created from docked ships but somehow has more than one wave!", wingp->name); // increment tallies wingp->total_arrived_count++; wingp->current_count++; // make sure we haven't created too many ships Assert(wingp->current_count <= MAX_SHIPS_PER_WING); // at this point the wing has arrived, so handle the stuff for this particular ship // set up wingman status index hud_wingman_status_set_index(wingp, &Ships[shipnum], p_objp); // copy to parse object p_objp->wing_status_wing_index = Ships[shipnum].wing_status_wing_index; p_objp->wing_status_wing_pos = Ships[shipnum].wing_status_wing_pos; // set flag if necessary for (j = 0; j < MAX_STARTING_WINGS; j++) { if (!stricmp(Starting_wing_names[j], wingp->name)) Ships[shipnum].flags[Ship::Ship_Flags::From_player_wing]; } // handle AI ai_info *aip = &Ai_info[Ships[shipnum].ai_index]; aip->wing = wingnum; if (wingp->flags[Ship::Wing_Flags::No_dynamic]) aip->ai_flags.set(AI::AI_Flags::No_dynamic); // copy any goals from the wing to the newly created ship for (index = 0; index < MAX_AI_GOALS; index++) { if (wingp->ai_goals[index].ai_mode != AI_GOAL_NONE) ai_copy_mission_wing_goal(&wingp->ai_goals[index], aip); } } // Goober5000 void resolve_parse_flags(object *objp, flagset<Mission::Parse_Object_Flags> &parse_flags) { Assert(objp != NULL); ship *shipp = &Ships[objp->instance]; if (parse_flags[Mission::Parse_Object_Flags::SF_Cargo_known]) shipp->flags.set(Ship::Ship_Flags::Cargo_revealed); if (parse_flags[Mission::Parse_Object_Flags::SF_Ignore_count]) shipp->flags.set(Ship::Ship_Flags::Ignore_count); if (parse_flags[Mission::Parse_Object_Flags::OF_Protected]) objp->flags.set(Object::Object_Flags::Protected); if (parse_flags[Mission::Parse_Object_Flags::SF_Reinforcement]) { //Individual ships in wings can't be reinforcements - FUBAR if (shipp->wingnum >= 0) { Warning(LOCATION, "Ship %s is a reinforcement unit but is a member of a wing. Ignoring reinforcement flag.", shipp->ship_name); } else { shipp->flags.set(Ship::Ship_Flags::Reinforcement); } } if ((parse_flags[Mission::Parse_Object_Flags::OF_No_shields]) && (parse_flags[Mission::Parse_Object_Flags::OF_Force_shields_on])) { Warning(LOCATION, "The parser found a ship with both the \"force-shields-on\" and \"no-shields\" flags; this is inconsistent!"); } if (parse_flags[Mission::Parse_Object_Flags::OF_No_shields]) objp->flags.set(Object::Object_Flags::No_shields); if (parse_flags[Mission::Parse_Object_Flags::SF_Escort]) shipp->flags.set(Ship::Ship_Flags::Escort); // P_OF_PLAYER_START is handled in parse_create_object_sub if (parse_flags[Mission::Parse_Object_Flags::SF_No_arrival_music]) shipp->flags.set(Ship::Ship_Flags::No_arrival_music); if (parse_flags[Mission::Parse_Object_Flags::SF_No_arrival_warp]) shipp->flags.set(Ship::Ship_Flags::No_arrival_warp); if (parse_flags[Mission::Parse_Object_Flags::SF_No_departure_warp]) shipp->flags.set(Ship::Ship_Flags::No_departure_warp); if (parse_flags[Mission::Parse_Object_Flags::SF_Locked]) { shipp->flags.set(Ship::Ship_Flags::Ship_locked); shipp->flags.set(Ship::Ship_Flags::Weapons_locked); } if (parse_flags[Mission::Parse_Object_Flags::OF_Invulnerable]) objp->flags.set(Object::Object_Flags::Invulnerable); if (parse_flags[Mission::Parse_Object_Flags::SF_Hidden_from_sensors]) shipp->flags.set(Ship::Ship_Flags::Hidden_from_sensors); if (parse_flags[Mission::Parse_Object_Flags::SF_Scannable]) shipp->flags.set(Ship::Ship_Flags::Scannable); // P_AIF_KAMIKAZE, P_AIF_NO_DYNAMIC, and P_SF_RED_ALERT_CARRY are handled in parse_create_object_sub if (parse_flags[Mission::Parse_Object_Flags::OF_Beam_protected]) objp->flags.set(Object::Object_Flags::Beam_protected); if (parse_flags[Mission::Parse_Object_Flags::OF_Flak_protected]) objp->flags.set(Object::Object_Flags::Flak_protected); if (parse_flags[Mission::Parse_Object_Flags::OF_Laser_protected]) objp->flags.set(Object::Object_Flags::Laser_protected); if (parse_flags[Mission::Parse_Object_Flags::OF_Missile_protected]) objp->flags.set(Object::Object_Flags::Missile_protected); if (parse_flags[Mission::Parse_Object_Flags::SF_Guardian]) shipp->ship_guardian_threshold = SHIP_GUARDIAN_THRESHOLD_DEFAULT; if (parse_flags[Mission::Parse_Object_Flags::SF_Vaporize]) shipp->flags.set(Ship::Ship_Flags::Vaporize); if (parse_flags[Mission::Parse_Object_Flags::SF_Stealth]) shipp->flags.set(Ship::Ship_Flags::Stealth); if (parse_flags[Mission::Parse_Object_Flags::SF_Friendly_stealth_invis]) shipp->flags.set(Ship::Ship_Flags::Friendly_stealth_invis); if (parse_flags[Mission::Parse_Object_Flags::SF_Dont_collide_invis]) shipp->flags.set(Ship::Ship_Flags::Dont_collide_invis); if (parse_flags[Mission::Parse_Object_Flags::SF_Primitive_sensors]) shipp->flags.set(Ship::Ship_Flags::Primitive_sensors); if (parse_flags[Mission::Parse_Object_Flags::SF_No_subspace_drive]) shipp->flags.set(Ship::Ship_Flags::No_subspace_drive); if (parse_flags[Mission::Parse_Object_Flags::SF_Nav_carry_status]) shipp->flags.set(Ship::Ship_Flags::Navpoint_carry); if (parse_flags[Mission::Parse_Object_Flags::SF_Affected_by_gravity]) shipp->flags.set(Ship::Ship_Flags::Affected_by_gravity); if (parse_flags[Mission::Parse_Object_Flags::SF_Toggle_subsystem_scanning]) shipp->flags.set(Ship::Ship_Flags::Toggle_subsystem_scanning); if (parse_flags[Mission::Parse_Object_Flags::OF_Targetable_as_bomb]) objp->flags.set(Object::Object_Flags::Targetable_as_bomb); if (parse_flags[Mission::Parse_Object_Flags::SF_No_builtin_messages]) shipp->flags.set(Ship::Ship_Flags::No_builtin_messages); if (parse_flags[Mission::Parse_Object_Flags::SF_Primaries_locked]) shipp->flags.set(Ship::Ship_Flags::Primaries_locked); if (parse_flags[Mission::Parse_Object_Flags::SF_Secondaries_locked]) shipp->flags.set(Ship::Ship_Flags::Secondaries_locked); if (parse_flags[Mission::Parse_Object_Flags::SF_Set_class_dynamically]) shipp->flags.set(Ship::Ship_Flags::Set_class_dynamically); if (parse_flags[Mission::Parse_Object_Flags::SF_No_death_scream]) shipp->flags.set(Ship::Ship_Flags::No_death_scream); if (parse_flags[Mission::Parse_Object_Flags::SF_Always_death_scream]) shipp->flags.set(Ship::Ship_Flags::Always_death_scream); if (parse_flags[Mission::Parse_Object_Flags::SF_Nav_needslink]) shipp->flags.set(Ship::Ship_Flags::Navpoint_needslink); if (parse_flags[Mission::Parse_Object_Flags::SF_Hide_ship_name]) shipp->flags.set(Ship::Ship_Flags::Hide_ship_name); if (parse_flags[Mission::Parse_Object_Flags::SF_Lock_all_turrets_initially]) shipp->flags.set(Ship::Ship_Flags::Lock_all_turrets_initially); if (parse_flags[Mission::Parse_Object_Flags::SF_Afterburner_locked]) shipp->flags.set(Ship::Ship_Flags::Afterburner_locked); if (parse_flags[Mission::Parse_Object_Flags::OF_Force_shields_on]) shipp->flags.set(Ship::Ship_Flags::Force_shields_on); if (parse_flags[Mission::Parse_Object_Flags::OF_Immobile]) objp->flags.set(Object::Object_Flags::Immobile); if (parse_flags[Mission::Parse_Object_Flags::SF_No_ets]) shipp->flags.set(Ship::Ship_Flags::No_ets); if (parse_flags[Mission::Parse_Object_Flags::SF_Cloaked]) shipp->flags.set(Ship::Ship_Flags::Cloaked); if (parse_flags[Mission::Parse_Object_Flags::SF_Ship_locked]) shipp->flags.set(Ship::Ship_Flags::Ship_locked); if (parse_flags[Mission::Parse_Object_Flags::SF_Weapons_locked]) shipp->flags.set(Ship::Ship_Flags::Weapons_locked); if (parse_flags[Mission::Parse_Object_Flags::SF_Scramble_messages]) shipp->flags.set(Ship::Ship_Flags::Scramble_messages); if (parse_flags[Mission::Parse_Object_Flags::OF_No_collide]) objp->flags.remove(Object::Object_Flags::Collides); if (parse_flags[Mission::Parse_Object_Flags::SF_No_disabled_self_destruct]) shipp->flags.set(Ship::Ship_Flags::No_disabled_self_destruct); } void fix_old_special_explosions(p_object *p_objp, int variable_index) { int i; Assertion(!(p_objp->use_special_explosion), "Mission appears to be using both the new and old method of special explosions for %s. Old method values used", p_objp->name); // check all the variables are valid for ( i = variable_index; i < (variable_index + BLOCK_EXP_SIZE); i++ ) { if (!( Block_variables[i].type & SEXP_VARIABLE_BLOCK )) { Warning (LOCATION, "%s is using the old special explosions method but does not appear to have variables for all the values", p_objp->name); return; } } p_objp->use_special_explosion = true; p_objp->special_exp_damage = atoi(Block_variables[variable_index+DAMAGE].text); p_objp->special_exp_blast = atoi(Block_variables[variable_index+BLAST].text); p_objp->special_exp_inner = atoi(Block_variables[variable_index+INNER_RAD].text); p_objp->special_exp_outer = atoi(Block_variables[variable_index+OUTER_RAD].text); p_objp->use_shockwave = (atoi(Block_variables[variable_index+PROPAGATE].text) ? 1:0); p_objp->special_exp_shockwave_speed = atoi(Block_variables[variable_index+SHOCK_SPEED].text); p_objp->special_exp_deathroll_time = 0; } void fix_old_special_hits(p_object *p_objp, int variable_index) { int i; Assertion( ((p_objp->special_hitpoints == 0) && (p_objp->special_shield == -1)),"Mission appears to be using both the new and old method of special hitpoints for %s", p_objp->name); // check all the variables are valid for ( i = variable_index; i < (variable_index + BLOCK_HIT_SIZE); i++ ) { if (!( Block_variables[i].type & SEXP_VARIABLE_BLOCK )) { Warning (LOCATION, "%s is using the old special hitpoints method but does not appear to have variables for all the values", p_objp->name); return; } } p_objp->special_hitpoints = atoi(Block_variables[variable_index+HULL_STRENGTH].text); p_objp->special_shield = atoi(Block_variables[variable_index+SHIELD_STRENGTH].text); } p_object::p_object() : next(NULL), prev(NULL), dock_list(NULL), created_object(NULL) {} // this will be called when Parse_objects is cleared between missions and upon shutdown p_object::~p_object() { dock_free_dock_list(this); } const char* p_object::get_display_name() { if (has_display_name()) { return display_name.c_str(); } else { return name; } } bool p_object::has_display_name() { return flags[Mission::Parse_Object_Flags::SF_Has_display_name]; } extern int parse_warp_params(const WarpParams *inherit_from, WarpDirection direction, const char *info_type_name, const char *sip_name); /** * Mp points at the text of an object, which begins with the "$Name:" field. * Snags all object information. Creating the ship now only happens after everything has been parsed. * * @param pm Mission * @param flag is parameter that is used to tell what kind information we are retrieving from the mission. * if we are just getting player starts, then don't create the objects * @param p_objp Object */ int parse_object(mission *pm, int /*flag*/, p_object *p_objp) { int i, j, count, delay; char name[NAME_LENGTH]; ship_info *sip; Assert(pm != NULL); // Goober5000 p_objp->created_object = NULL; p_objp->next = NULL; p_objp->prev = NULL; p_objp->flags.reset(); required_string("$Name:"); stuff_string(p_objp->name, F_NAME, NAME_LENGTH); if (mission_parse_get_parse_object(p_objp->name)) error_display(0, NOX("Redundant ship name: %s\n"), p_objp->name); // if this name has a hash, create a default display name if (get_pointer_to_first_hash_symbol(p_objp->name)) { p_objp->display_name = p_objp->name; end_string_at_first_hash_symbol(p_objp->display_name); p_objp->flags.set(Mission::Parse_Object_Flags::SF_Has_display_name); } if (optional_string("$Display Name:")) { stuff_string(p_objp->display_name, F_NAME); p_objp->flags.set(Mission::Parse_Object_Flags::SF_Has_display_name); } find_and_stuff("$Class:", &p_objp->ship_class, F_NAME, Ship_class_names, Ship_info.size(), "ship class"); if (p_objp->ship_class < 0) { if (Fred_running) { Warning(LOCATION, "Ship \"%s\" has an invalid ship type (ships.tbl probably changed). Making it type 0\n", p_objp->name); } else { mprintf(("MISSIONS: Ship \"%s\" has an invalid ship type (ships.tbl probably changed). Making it type 0\n", p_objp->name)); } p_objp->ship_class = 0; Num_unknown_ship_classes++; } sip = &Ship_info[p_objp->ship_class]; // Karajorma - See if there are any alternate classes specified for this ship. p_objp->alt_classes.clear(); // The alt class can either be a variable or a ship class name char alt_ship_class[TOKEN_LENGTH > NAME_LENGTH ? TOKEN_LENGTH : NAME_LENGTH]; int is_variable; while (optional_string("$Alt Ship Class:")) { alt_class new_alt_class; is_variable = get_string_or_variable(alt_ship_class); if (is_variable) { new_alt_class.variable_index = get_index_sexp_variable_name(alt_ship_class); if(new_alt_class.variable_index >= 0) { new_alt_class.ship_class = ship_info_lookup(Sexp_variables[new_alt_class.variable_index].text); } else { new_alt_class.ship_class = -1; } } else { new_alt_class.variable_index = -1; new_alt_class.ship_class = ship_info_lookup(alt_ship_class); } if (new_alt_class.ship_class < 0 ) { if (!Fred_running) { Warning(LOCATION, "Ship \"%s\" has an invalid Alternate Ship Class type (ships.tbl probably changed). Skipping this entry", p_objp->name); continue; } else { // incorrect initial values for a variable can be fixed in FRED if (new_alt_class.variable_index != -1) { Warning(LOCATION, "Ship \"%s\" has an invalid Alternate Ship Class type.", p_objp->name); } // but there is little we can do if someone spelled a ship class incorrectly else { Warning(LOCATION, "Ship \"%s\" has an invalid Alternate Ship Class type. Skipping this entry", p_objp->name); continue; } } } if (optional_string("+Default Class:")) { new_alt_class.default_to_this_class = true; } else { new_alt_class.default_to_this_class = false; } p_objp->alt_classes.push_back(new_alt_class); } // if this is a multiplayer dogfight mission, skip support ships if(MULTI_DOGFIGHT && (sip->flags[Ship::Info_Flags::Support])) return 0; // optional alternate name type p_objp->alt_type_index = -1; if(optional_string("$Alt:")) { // alternate name stuff_string(name, F_NAME, NAME_LENGTH); // try and find the alternate name p_objp->alt_type_index = mission_parse_lookup_alt(name); if(p_objp->alt_type_index < 0) WarningEx(LOCATION, "Mission %s\nError looking up alternate ship type name %s!\n", pm->name, name); else mprintf(("Using alternate ship type name: %s\n", name)); } // optional callsign p_objp->callsign_index = -1; if(optional_string("$Callsign:")) { // alternate callsign stuff_string(name, F_NAME, NAME_LENGTH); // try and find the callsign p_objp->callsign_index = mission_parse_lookup_callsign(name); if(p_objp->callsign_index < 0) WarningEx(LOCATION, "Mission %s\nError looking up callsign %s!\n", pm->name, name); else mprintf(("Using callsign: %s\n", name)); } // static alias stuff - stupid, but it seems to be necessary static const char *temp_team_names[MAX_IFFS]; for (i = 0; i < Num_iffs; i++) temp_team_names[i] = Iff_info[i].iff_name; find_and_stuff("$Team:", &p_objp->team, F_NAME, temp_team_names, Num_iffs, "team name"); // save current team for loadout purposes, so that in multi we always respawn // from the original loadout slot even if the team changes p_objp->loadout_team = p_objp->team; if (optional_string("$Team Color Setting:")) { char temp[NAME_LENGTH]; stuff_string(temp, F_NAME, NAME_LENGTH); p_objp->team_color_setting = temp; if (Team_Colors.find(p_objp->team_color_setting) == Team_Colors.end()) { mprintf(("Invalid team color specified in mission file for ship %s, resetting to default\n", p_objp->name)); p_objp->team_color_setting = sip->default_team_name; } } required_string("$Location:"); stuff_vec3d(&p_objp->pos); required_string("$Orientation:"); stuff_matrix(&p_objp->orient); // legacy code, not even used in FS1 if (optional_string("$IFF:")) { stuff_string(name, F_NAME, NAME_LENGTH); } find_and_stuff("$AI Behavior:", &p_objp->behavior, F_NAME, Ai_behavior_names, Num_ai_behaviors, "AI behavior"); p_objp->ai_goals = -1; if (optional_string("+AI Class:")) { p_objp->ai_class = match_and_stuff(F_NAME, Ai_class_names, Num_ai_classes, "AI class"); if (p_objp->ai_class < 0) { Warning(LOCATION, "AI Class for ship %s does not exist in ai.tbl. Setting to first available class.\n", p_objp->name); p_objp->ai_class = 0; } } else { p_objp->ai_class = sip->ai_class; } if (optional_string("$AI Goals:")) p_objp->ai_goals = get_sexp_main(); if (!required_string_either("$AI Goals:", "$Cargo 1:")) { required_string("$AI Goals:"); p_objp->ai_goals = get_sexp_main(); } p_objp->cargo1 = -1; int temp; find_and_stuff_or_add("$Cargo 1:", &temp, F_NAME, Cargo_names, &Num_cargo, MAX_CARGO, "cargo"); p_objp->cargo1 = char(temp); if (optional_string("$Cargo 2:")) { stuff_string(name, F_NAME, NAME_LENGTH); } parse_common_object_data(p_objp); // get initial conditions and subsys status count = 0; while (required_string_either("$Arrival Location:", "$Status Description:")) { Assert(count < MAX_OBJECT_STATUS); find_and_stuff("$Status Description:", &p_objp->status_type[count], F_NAME, Status_desc_names, Num_status_names, "Status Description"); find_and_stuff("$Status:", &p_objp->status[count], F_NAME, Status_type_names, Num_status_names, "Status Type"); find_and_stuff("$Target:", &p_objp->target[count], F_NAME, Status_target_names, Num_status_names, "Target"); count++; } p_objp->status_count = count; p_objp->arrival_anchor = -1; p_objp->arrival_distance = 0; p_objp->arrival_path_mask = -1; // -1 only until resolved find_and_stuff("$Arrival Location:", &p_objp->arrival_location, F_NAME, Arrival_location_names, Num_arrival_names, "Arrival Location"); if (optional_string("+Arrival Distance:")) { stuff_int(&p_objp->arrival_distance); // Goober5000 if ((p_objp->arrival_distance <= 0) && ((p_objp->arrival_location == ARRIVE_NEAR_SHIP) || (p_objp->arrival_location == ARRIVE_IN_FRONT_OF_SHIP))) { Warning(LOCATION, "Arrival distance for ship %s cannot be %d. Setting to 1.\n", p_objp->name, p_objp->arrival_distance); p_objp->arrival_distance = 1; } } if (p_objp->arrival_location != ARRIVE_AT_LOCATION) { required_string("$Arrival Anchor:"); stuff_string(name, F_NAME, NAME_LENGTH); p_objp->arrival_anchor = get_anchor(name); } if (optional_string("+Arrival Paths:")) { // temporarily use mask to point to the restriction index p_objp->arrival_path_mask = add_path_restriction(); } delay = 0; if (optional_string("+Arrival Delay:")) { stuff_int(&delay); if (delay < 0) Error(LOCATION, "Cannot have arrival delay < 0 (ship %s)", p_objp->name); } if (!Fred_running) p_objp->arrival_delay = -delay; // use negative numbers to mean we haven't set up a timer yet else p_objp->arrival_delay = delay; required_string("$Arrival Cue:"); p_objp->arrival_cue = get_sexp_main(); p_objp->departure_anchor = -1; p_objp->departure_path_mask = -1; // -1 only until resolved find_and_stuff("$Departure Location:", &p_objp->departure_location, F_NAME, Departure_location_names, Num_arrival_names, "Departure Location"); if (p_objp->departure_location != DEPART_AT_LOCATION) { required_string("$Departure Anchor:"); stuff_string(name, F_NAME, NAME_LENGTH); p_objp->departure_anchor = get_anchor(name); } if (optional_string("+Departure Paths:")) { // temporarily use mask to point to the restriction index p_objp->departure_path_mask = add_path_restriction(); } delay = 0; if (optional_string("+Departure Delay:")) { stuff_int(&delay); if (delay < 0) Error(LOCATION, "Cannot have departure delay < 0 (ship %s)", p_objp->name); } if (!Fred_running) p_objp->departure_delay = -delay; else p_objp->departure_delay = delay; required_string("$Departure Cue:"); p_objp->departure_cue = get_sexp_main(); // look for warp parameters p_objp->warpin_params_index = parse_warp_params(&Warp_params[sip->warpin_params_index], WarpDirection::WARP_IN, "Ship", p_objp->name); p_objp->warpout_params_index = parse_warp_params(&Warp_params[sip->warpout_params_index], WarpDirection::WARP_OUT, "Ship", p_objp->name); if (optional_string("$Misc Properties:")) stuff_string(p_objp->misc, F_NAME, NAME_LENGTH); required_string("$Determination:"); int dummy; stuff_int(&dummy); // set flags if (optional_string("+Flags:")) { SCP_vector<SCP_string> unparsed; parse_string_flag_list(p_objp->flags, Parse_object_flags, num_parse_object_flags, &unparsed); if (!unparsed.empty()) { for (size_t k = 0; k < unparsed.size(); ++k) { WarningEx(LOCATION, "Unknown flag in parse object flags: %s", unparsed[k].c_str()); } } } // second set - Goober5000 if (optional_string("+Flags2:")) { SCP_vector<SCP_string> unparsed; parse_string_flag_list(p_objp->flags, Parse_object_flags, num_parse_object_flags, &unparsed); if (!unparsed.empty()) { for (size_t k = 0; k < unparsed.size(); ++k) { // catch typos or deprecations if (!stricmp(unparsed[k].c_str(), "no-collide") || !stricmp(unparsed[k].c_str(), "no_collide")) { p_objp->flags.set(Mission::Parse_Object_Flags::OF_No_collide); } else { WarningEx(LOCATION, "Unknown flag in parse object flags: %s", unparsed[k].c_str()); } } } } // always store respawn priority, just for ease of implementation p_objp->respawn_priority = 0; if(optional_string("+Respawn Priority:")) stuff_int(&p_objp->respawn_priority); p_objp->escort_priority = 0; if (optional_string("+Escort Priority:")) { Assert(p_objp->flags[Mission::Parse_Object_Flags::SF_Escort]); stuff_int(&p_objp->escort_priority); } if (p_objp->flags[Mission::Parse_Object_Flags::OF_Player_start]) { p_objp->flags.set(Mission::Parse_Object_Flags::SF_Cargo_known); // make cargo known for players Player_starts++; } p_objp->use_special_explosion = false; p_objp->special_exp_damage = -1; p_objp->special_exp_blast = -1; p_objp->special_exp_inner = -1; p_objp->special_exp_outer = -1; p_objp->use_shockwave = false; p_objp->special_exp_shockwave_speed = 0; p_objp->special_exp_deathroll_time = 0; p_objp->special_hitpoints = 0; p_objp->special_shield = -1; if (optional_string("$Special Explosion:")) { p_objp->use_special_explosion = true; bool period_detected = false; if (required_string("+Special Exp Damage:")) { stuff_int(&p_objp->special_exp_damage); if (*Mp == '.') { period_detected = true; advance_to_eoln(NULL); } } if (required_string("+Special Exp Blast:")) { stuff_int(&p_objp->special_exp_blast); if (*Mp == '.') { period_detected = true; advance_to_eoln(NULL); } } if (required_string("+Special Exp Inner Radius:")) { stuff_int(&p_objp->special_exp_inner); if (*Mp == '.') { period_detected = true; advance_to_eoln(NULL); } } if (required_string("+Special Exp Outer Radius:")) { stuff_int(&p_objp->special_exp_outer); if (*Mp == '.') { period_detected = true; advance_to_eoln(NULL); } } if (optional_string("+Special Exp Shockwave Speed:")) { stuff_int(&p_objp->special_exp_shockwave_speed); p_objp->use_shockwave = true; if (*Mp == '.') { period_detected = true; advance_to_eoln(NULL); } } if (optional_string("+Special Exp Death Roll Time:")) { stuff_int(&p_objp->special_exp_deathroll_time); } if (period_detected) { nprintf(("Warning", "Special explosion attributes have been returned to integer format\n")); } } if (optional_string("+Special Hitpoints:")) { stuff_int(&p_objp->special_hitpoints); } if (optional_string("+Special Shield Points:")) { stuff_int(&p_objp->special_shield); } if (optional_string("+Special Exp index:")) { int variable_index; stuff_int(&variable_index); fix_old_special_explosions(p_objp, variable_index); } if (optional_string("+Special Hitpoint index:")) { int variable_index; stuff_int(&variable_index); fix_old_special_hits(p_objp, variable_index); } // set custom shield value if (p_objp->special_shield != -1) { p_objp->ship_max_shield_strength = (float) p_objp->special_shield; } else { p_objp->ship_max_shield_strength = sip->max_shield_strength; } // set custom hitpoint value if (p_objp->special_hitpoints > 0) { p_objp->ship_max_hull_strength = (float) p_objp->special_hitpoints; } else { p_objp->ship_max_hull_strength = sip->max_hull_strength; } Assert(p_objp->ship_max_hull_strength > 0.0f); // Goober5000: div-0 check (not shield because we might not have one) p_objp->max_shield_recharge = sip->max_shield_recharge; // if the kamikaze flag is set, we should have the next flag if (optional_string("+Kamikaze Damage:")) { int damage; stuff_int(&damage); p_objp->kamikaze_damage = damage; } p_objp->hotkey = -1; if (optional_string("+Hotkey:")) { stuff_int(&p_objp->hotkey); Assert((p_objp->hotkey >= 0) && (p_objp->hotkey < 10)); } // Goober5000 p_objp->dock_list = NULL; while (optional_string("+Docked With:")) { char docked_with[NAME_LENGTH]; char docker_point[NAME_LENGTH]; char dockee_point[NAME_LENGTH]; // grab docking information // (whoever designed the original docking system // reversed the dockpoints in the mission file) stuff_string(docked_with, F_NAME, NAME_LENGTH); required_string("$Docker Point:"); stuff_string(dockee_point, F_NAME, NAME_LENGTH); required_string("$Dockee Point:"); stuff_string(docker_point, F_NAME, NAME_LENGTH); // make sure we don't overflow the limit if (Total_initially_docked >= MAX_SHIPS) { mprintf(("Too many initially docked instances; skipping...\n")); continue; } // put this information into the Initially_docked array strcpy_s(Initially_docked[Total_initially_docked].docker, p_objp->name); strcpy_s(Initially_docked[Total_initially_docked].dockee, docked_with); strcpy_s(Initially_docked[Total_initially_docked].docker_point, docker_point); strcpy_s(Initially_docked[Total_initially_docked].dockee_point, dockee_point); Total_initially_docked++; } // check the optional parameter for destroying the ship before the mission starts. If this parameter is // here, then we need to destroy the ship N seconds before the mission starts (for debris purposes). // store the time value here. We want to create this object for sure. Set the arrival cue and arrival // delay to bogus values p_objp->destroy_before_mission_time = -1; if (optional_string("+Destroy At:")) { stuff_int(&p_objp->destroy_before_mission_time); Assert (p_objp->destroy_before_mission_time >= 0); p_objp->arrival_cue = Locked_sexp_true; p_objp->arrival_delay = timestamp(0); } // check for the optional "orders accepted" string which contains the orders from the default // set that this ship will actually listen to if (optional_string("+Orders Accepted:")) { stuff_int(&p_objp->orders_accepted); if (p_objp->orders_accepted != -1) p_objp->flags.set(Mission::Parse_Object_Flags::SF_Use_unique_orders); } p_objp->group = 0; if (optional_string("+Group:")) stuff_int(&p_objp->group); bool table_score = false; if (optional_string("+Use Table Score:")) { table_score = true; } if (optional_string("+Score:")) { if (!table_score) { stuff_int(&p_objp->score); } // throw away the value the mission file has and use the table value. else { int temp_score; stuff_int(&temp_score); } } else { table_score = true; } if (table_score) { p_objp->score = sip->score; } if (optional_string("+Assist Score Percentage:")) { stuff_float(&p_objp->assist_score_pct); // value must be a percentage if (p_objp->assist_score_pct < 0) { p_objp->assist_score_pct = 0; } else if (p_objp->assist_score_pct > 1) { p_objp->assist_score_pct = 1; } } else { p_objp->assist_score_pct = 0; } // parse the persona index if present p_objp->persona_index = -1; if (optional_string("+Persona Index:")) stuff_int(&p_objp->persona_index); // texture replacement - Goober5000 p_objp->replacement_textures = sip->replacement_textures; // initialize our set with the ship class set, which may be empty if (optional_string("$Texture Replace:") || optional_string("$Duplicate Model Texture Replace:")) { texture_replace tr; char *p; tr.from_table = false; while (optional_string("+old:")) { strcpy_s(tr.ship_name, p_objp->name); tr.new_texture_id = -1; stuff_string(tr.old_texture, F_NAME, MAX_FILENAME_LEN); required_string("+new:"); stuff_string(tr.new_texture, F_NAME, MAX_FILENAME_LEN); // get rid of extensions p = strchr(tr.old_texture, '.'); if (p) { mprintf(("Extraneous extension found on replacement texture %s!\n", tr.old_texture)); *p = 0; } p = strchr(tr.new_texture, '.'); if (p) { mprintf(("Extraneous extension found on replacement texture %s!\n", tr.new_texture)); *p = 0; } // add it if we aren't over the limit if (p_objp->replacement_textures.size() < MAX_MODEL_TEXTURES) p_objp->replacement_textures.push_back(tr); else mprintf(("Too many replacement textures specified for ship '%s'!\n", p_objp->name)); } } // now load the textures (do this outside the parse loop because we may have ship class replacements too) for (SCP_vector<texture_replace>::iterator tr = p_objp->replacement_textures.begin(); tr != p_objp->replacement_textures.end(); ++tr) { // load the texture if (!stricmp(tr->new_texture, "invisible")) { // invisible is a special case tr->new_texture_id = REPLACE_WITH_INVISIBLE; } else { // try to load texture or anim as normal tr->new_texture_id = bm_load_either(tr->new_texture); } // not found? if (tr->new_texture_id < 0) { mprintf(("Could not load replacement texture %s for ship %s\n", tr->new_texture, p_objp->name)); } // account for FRED if (Fred_running) { Fred_texture_replacements.push_back(*tr); Fred_texture_replacements.back().new_texture_id = -1; } } p_objp->wingnum = -1; // set the wing number to -1 -- possibly to be set later p_objp->pos_in_wing = -1; // Goober5000 for (i=0;i<MAX_IFFS;i++) { for (j=0;j<MAX_IFFS;j++) { p_objp->alt_iff_color[i][j] = -1; } } // for multiplayer, assign a network signature to this parse object. Doing this here will // allow servers to use the signature with clients when creating new ships, instead of having // to pass ship names all the time if (Game_mode & GM_MULTIPLAYER) p_objp->net_signature = multi_assign_network_signature(MULTI_SIG_SHIP); // set the wing_status position to be -1 for all objects. This will get set to an appropriate // value when the wing positions are finally determined. p_objp->wing_status_wing_index = -1; p_objp->wing_status_wing_pos = -1; p_objp->respawn_count = 0; // Goober5000 - preload stuff for certain object flags // (done after parsing object, but before creating it) if (p_objp->flags[Mission::Parse_Object_Flags::Knossos_warp_in]) Knossos_warp_ani_used = 1; // this is a valid/legal ship to create return 1; } void mission_parse_handle_late_arrivals(p_object *p_objp) { ship_info *sip = NULL; model_subsystem *subsystems = NULL; // only for objects which show up after the start of a mission if (p_objp->created_object != NULL) return; Assert( p_objp->ship_class >= 0 ); sip = &Ship_info[p_objp->ship_class]; if (sip->n_subsystems > 0) { subsystems = &sip->subsystems[0]; } // we need the model to process the texture set, so go ahead and load it now sip->model_num = model_load(sip->pof_file, sip->n_subsystems, subsystems); } // Goober5000 - I split this because 1) it's clearer; and 2) initially multiple docked ships would have been // insanely difficult otherwise // // Maybe create the object. // Don't create the new ship blindly. First, check the sexp for the arrival cue // to determine when this ship should arrive. If not right away, stick this ship // onto the ship arrival list to be looked at later. Also check to see if it should use the // wings arrival cue. The ship may get created later depending on whether or not the wing // is created. // Always create ships when FRED is running. void mission_parse_maybe_create_parse_object(p_object *pobjp) { // Bail if it was already created. This should only happen when we previously // created all the objects in a docked group simultaneously. if (pobjp->created_object != NULL) { Assert(object_is_docked(pobjp)); return; } // Goober5000 // shunt this guy to the arrival list if he meets one of the following conditions: // 1) he's docked but not the dock leader // 2) this is FS2 (i.e. not FRED2) AND he meets one of the following conditions: // a) he's not cued to arrive yet // b) his arrival delay hasn't elapsed // c) he's reinforcement if ((object_is_docked(pobjp) && !(pobjp->flags[Mission::Parse_Object_Flags::SF_Dock_leader])) || (!Fred_running && (!eval_sexp(pobjp->arrival_cue) || !timestamp_elapsed(pobjp->arrival_delay) || (pobjp->flags[Mission::Parse_Object_Flags::SF_Reinforcement])))) { // we can't add ships getting destroyed to the arrival list!!! Assert (pobjp->destroy_before_mission_time < 0); // add to arrival list list_append(&Ship_arrival_list, pobjp); // we need to deal with replacement textures now, so that texture page-in will work properly mission_parse_handle_late_arrivals(pobjp); } // ingame joiners bail here. else if((Game_mode & GM_MULTIPLAYER) && (Net_player->flags & NETINFO_FLAG_INGAME_JOIN)) { return; } // the ship is present at the beginning of the mission, so we create it else { int real_objnum = parse_create_object(pobjp); // this object may later get destroyed depending on wing status!!!! // if the ship is supposed to be destroyed before the mission, then blow up the ship and mark the pieces // as last forever. Only call this stuff when you are blowing up the ship if (pobjp->destroy_before_mission_time >= 0) { object *objp = &Objects[real_objnum]; // FreeSpace if (!Fred_running) { shipfx_blow_up_model(objp, 0, 0, &objp->pos); objp->flags.set(Object::Object_Flags::Should_be_dead); // Make sure that the ship is marked as destroyed so the AI doesn't freak out later ship_add_exited_ship(&Ships[objp->instance], Ship::Exit_Flags::Destroyed); // once the ship is exploded, find the debris pieces belonging to this object, mark them // as not to expire, and move them forward in time N seconds for (auto &db: Debris) { if (!(db.flags[Debris_Flags::Used])) // not used, move onto the next one. continue; if (db.source_objnum != real_objnum) // not from this ship, move to next one continue; debris_remove_from_hull_list(&db); db.flags.set(Debris_Flags::DoNotExpire); // mark as don't expire db.lifeleft = -1.0f; // be sure that lifeleft == -1.0 so that it really doesn't expire! // now move the debris along its path for N seconds objp = &Objects[db.objnum]; physics_sim(&objp->pos, &objp->orient, &objp->phys_info, (float) pobjp->destroy_before_mission_time); } } // FRED else { // be sure to set the variable in the ships structure for the final death time!!! Ships[objp->instance].final_death_time = pobjp->destroy_before_mission_time; Ships[objp->instance].flags.set(Ship::Ship_Flags::Kill_before_mission); } } } } void parse_common_object_data(p_object *p_objp) { int i; // Genghis: used later for subsystem checking auto sip = &Ship_info[p_objp->ship_class]; // set some defaults.. p_objp->initial_velocity = 0; p_objp->initial_hull = 100; p_objp->initial_shields = 100; // now change defaults if present if (optional_string("+Initial Velocity:")) { stuff_int(&p_objp->initial_velocity); } if (optional_string("+Initial Hull:")) stuff_int(&p_objp->initial_hull); if (optional_string("+Initial Shields:")) stuff_int(&p_objp->initial_shields); p_objp->subsys_index = Subsys_index; p_objp->subsys_count = 0; while (optional_string("+Subsystem:")) { i = allocate_subsys_status(); p_objp->subsys_count++; stuff_string(Subsys_status[i].name, F_NAME, NAME_LENGTH); // Genghis: check that the subsystem name makes sense for this ship type if (subsystem_stricmp(Subsys_status[i].name, NOX("pilot"))) { int j; for (j=0; j < sip->n_subsystems; ++j) if (!subsystem_stricmp(sip->subsystems[j].subobj_name, Subsys_status[i].name)) break; //if (j == sip->n_subsystems) //Warning(LOCATION, "Ship \"%s\", class \"%s\"\nUnknown subsystem \"%s\" found in mission!", objp->name, sip->name, Subsys_status[i].name); } if (optional_string("$Damage:")) stuff_float(&Subsys_status[i].percent); Subsys_status[i].subsys_cargo_name = 0; if (optional_string("+Cargo Name:")) { char cargo_name[NAME_LENGTH]; stuff_string(cargo_name, F_NAME, NAME_LENGTH); int index = string_lookup(cargo_name, Cargo_names, Num_cargo, "cargo", 0); if (index == -1) { if (Num_cargo < MAX_CARGO) { index = Num_cargo; strcpy(Cargo_names[Num_cargo++], cargo_name); } else { WarningEx(LOCATION, "Maximum number of cargo names (%d) exceeded, defaulting to Nothing!", MAX_CARGO); index = 0; } } Subsys_status[i].subsys_cargo_name = index; } if (optional_string("+AI Class:")) { Subsys_status[i].ai_class = match_and_stuff(F_NAME, Ai_class_names, Num_ai_classes, "AI class"); if (Subsys_status[i].ai_class < 0) { Warning(LOCATION, "AI Class for ship %s and subsystem %s does not exist in ai.tbl. Setting to first available class.\n", p_objp->name, Subsys_status[i].name); Subsys_status[i].ai_class = 0; } } if (optional_string("+Primary Banks:")) stuff_int_list(Subsys_status[i].primary_banks, MAX_SHIP_PRIMARY_BANKS, WEAPON_LIST_TYPE); // Goober5000 if (optional_string("+Pbank Ammo:")) stuff_int_list(Subsys_status[i].primary_ammo, MAX_SHIP_PRIMARY_BANKS, RAW_INTEGER_TYPE); if (optional_string("+Secondary Banks:")) stuff_int_list(Subsys_status[i].secondary_banks, MAX_SHIP_SECONDARY_BANKS, WEAPON_LIST_TYPE); if (optional_string("+Sbank Ammo:")) stuff_int_list(Subsys_status[i].secondary_ammo, MAX_SHIP_SECONDARY_BANKS, RAW_INTEGER_TYPE); } } /** * Checks if any ships of a certain ship class are still available in the team loadout * @return The index of the ship in team_data->ship_list if found or -1 if it isn't */ int get_reassigned_index(team_data *current_team, int ship_class) { // Search through the available ships to see if there is a matching ship class in the loadout for (int i=0; i < current_team->num_ship_choices; i++) { if (ship_class == current_team->ship_list[i]) { if (current_team->ship_count[i] > 0) { return i; } else { return -1; } } } return -1; } /** * Updates the loadout quanities for a ship class. */ void update_loadout_totals(team_data *current_team, int loadout_index) { // Fix the loadout variables to show that the class has less available if there are still ships available if (current_team->ship_count[loadout_index] > 0) { Assert (current_team->loadout_total > 0); current_team->ship_count[loadout_index]--; current_team->loadout_total--; } } /** * Attempts to set the class of this ship based which ship classes still remain unassigned in the ship loadout * The ship class specified by the mission file itself is tested first. Followed by the list of alt classes. * If an alt class flagged as default_to_this_class is reached the ship will be assigned to that class. * If the class can't be assigned because no ships of that class remain the function returns false. */ bool is_ship_assignable(p_object *p_objp) { int loadout_index = -1; team_data *data_for_team = &Team_data[p_objp->team]; // First lets check if the ship specified in the mission file is of an assignable class loadout_index = get_reassigned_index(data_for_team, p_objp->ship_class); if (loadout_index != -1 ) { Assert (data_for_team->loadout_total > 0); update_loadout_totals(data_for_team, loadout_index); // Since the ship in the mission file matched one available in the loadout we need go no further return true; } // Now we check the alt_classes (if there are any) for (SCP_vector<alt_class>::iterator pac = p_objp->alt_classes.begin(); pac != p_objp->alt_classes.end(); ++pac) { // we don't check availability unless we are asked to if (pac->default_to_this_class == false) { loadout_index = pac->ship_class; break; } else { loadout_index = get_reassigned_index(data_for_team, pac->ship_class); if (loadout_index != -1 ) { update_loadout_totals(data_for_team, loadout_index); break; } } } // If we managed to assign a class we'd may need to actually swap to it if (loadout_index != -1 ) { if (p_objp->ship_class != data_for_team->ship_list[loadout_index]) { swap_parse_object(p_objp, data_for_team->ship_list[loadout_index]); } return true; } return false; } /** * Checks the list of Parse_objects to see if any of them should be reassigned based on the * number of ships of that class that were present in the loadout. */ void process_loadout_objects() { SCP_vector<size_t> reassignments; // Loop through all the Parse_objects looking for ships that should be affected by the loadout code. for (size_t i=0; i < Parse_objects.size(); i++) { p_object *p_objp = &Parse_objects[i]; if (p_objp->flags[Mission::Parse_Object_Flags::SF_Set_class_dynamically]) { if (!(is_ship_assignable(p_objp))) { // store the ship so we can come back to it later. reassignments.push_back(i); } } } // Now we go though the ships we were unable to assign earlier and reassign them on a first come first // served basis. for (size_t m=0; m < reassignments.size(); m++) { p_object *p_objp = &Parse_objects[reassignments[m]]; team_data *current_team = &Team_data[p_objp->team]; bool loadout_assigned = false; Assert(p_objp->flags[Mission::Parse_Object_Flags::SF_Set_class_dynamically]); // First thing to check is whether we actually have any ships left to assign if (current_team->loadout_total == 0) { // If there is nothing left to assign we should use the ship in the mission file loadout_assigned = true; } // We do have ships left in the team loadout that we can assign else { // Go through the loadout until we find an unassigned ship for (int j=0; j < current_team->num_ship_choices; j++) { if (current_team->ship_count[j] > 0) { update_loadout_totals(current_team, j); // We will need to assign a new class too (if a p_object the same class was available // it should have been assigned by attempt_loadout_assignation_from_defaults() Assert (p_objp->ship_class != current_team->ship_list[j]); swap_parse_object(p_objp, current_team->ship_list[j]); loadout_assigned = true; break ; } } } // We should never reach here with an unassigned loadout Assert (loadout_assigned); } } extern int Multi_ping_timestamp; void parse_objects(mission *pm, int flag) { Assert(pm != NULL); required_string("#Objects"); // parse in objects Parse_objects.clear(); while (required_string_either("#Wings", "$Name:")) { p_object pobj; // parse a single object int valid = parse_object(pm, flag, &pobj); // not all objects are always valid or legal if (!valid) continue; // add it Parse_objects.push_back(pobj); // send out a ping if we are multi so that psnet2 doesn't kill us off for a long load // NOTE that we can't use the timestamp*() functions here since they won't increment // during this loading process if (Game_mode & GM_MULTIPLAYER) { if ((Multi_ping_timestamp == -1) || (Multi_ping_timestamp <= timer_get_milliseconds())) { multi_ping_send_all(); Multi_ping_timestamp = timer_get_milliseconds() + 10000; // timeout is 10 seconds between pings } } } // Goober5000 - I moved the docking stuff to post_process_ships_wings because of interdependencies // between ships and wings. Neither docking stuff nor ship stuff (for ships present at mission start) // will be valid until after post_process_ships_wings is run. // Karajorma - Now that we've parsed all the objects we can set the class of those which were flagged // to be set based on the number of ships available in the loadout. if (!Fred_running) { process_loadout_objects(); } } /** * Replaces a p_object with a new one based on a Ship_info index. */ void swap_parse_object(p_object *p_obj, int new_ship_class) { ship_info *new_ship_info = &Ship_info[new_ship_class]; ship_info *old_ship_info = &Ship_info[p_obj->ship_class]; int subsys_ind = p_obj->subsys_index; subsys_status *ship_subsystems = &Subsys_status[subsys_ind]; // Class // First things first. Change the class of the p_object p_obj->ship_class = new_ship_class; // Hitpoints // We need to take into account that the ship might have been assigned special hitpoints so we can't // simply swap old for new. Assert (p_obj->ship_max_hull_strength > 0); Assert (old_ship_info->max_hull_strength > 0); float hp_multiplier = p_obj->ship_max_hull_strength / old_ship_info->max_hull_strength; p_obj->ship_max_hull_strength = new_ship_info->max_hull_strength * hp_multiplier; // Shields // Again we have to watch out for special hitpoints but this time we can't assume that there will be a // shield. So first lets see if there is one. if ((p_obj->ship_max_shield_strength != old_ship_info->max_shield_strength) && (p_obj->ship_max_shield_strength > 0) && (new_ship_info->max_shield_strength > 0)) { // This ship is using special hitpoints to alter the shield strength float shield_multiplier = p_obj->ship_max_shield_strength / i2fl(old_ship_info->max_shield_strength); p_obj->ship_max_shield_strength = new_ship_info->max_shield_strength * shield_multiplier; } // Not using special hitpoints or a class which has a shield strength of zero else { p_obj->ship_max_shield_strength = new_ship_info->max_shield_strength; } // Primary weapons // First find out what is the correct number for a ship of this class int num_pbanks = new_ship_info->num_primary_banks; // Now cycle through the primary banks looking for banks that were added or removed for (int i=0; i < MAX_SHIP_PRIMARY_BANKS; i++) { // If we're dealing with a primary bank that actually should exist on this ship if ( i < num_pbanks ) { // We only care if a weapon hasn't been parsed in for this bank if (ship_subsystems->primary_banks[i] == -1) { // Give the ship the default weapon for this bank. ship_subsystems->primary_banks[i] = new_ship_info->primary_bank_weapons[i]; } } // Any primary banks the ship doesn't have should be set to -1 else { ship_subsystems->primary_banks[i] = -1; } } // Secondary weapons // Again we first have to find out how many we should have int num_sbanks = new_ship_info->num_secondary_banks; // Now cycle through the secondary banks looking for banks that were added or removed for (int j=0; j < MAX_SHIP_SECONDARY_BANKS; j++) { // If we're dealing with a primary bank that actually should exist on this ship if ( j < num_sbanks ) { // We only care if a weapon hasn't been parsed in for this bank if (ship_subsystems->secondary_banks[j] == -1){ // Give the ship the default weapon for this bank. ship_subsystems->secondary_banks[j] = new_ship_info->secondary_bank_weapons[j]; } } // Any secondary banks the ship doesn't have should be set to -1 else { ship_subsystems->secondary_banks[j] = -1; } } } p_object *mission_parse_get_parse_object(ushort net_signature) { SCP_vector<p_object>::iterator ii; // look for original ships for (ii = Parse_objects.begin(); ii != Parse_objects.end(); ++ii) if (ii->net_signature == net_signature) return &(*ii); // boo return NULL; } // Goober5000 - also get it by name p_object *mission_parse_get_parse_object(const char *name) { SCP_vector<p_object>::iterator ii; // look for original ships for (ii = Parse_objects.begin(); ii != Parse_objects.end(); ++ii) if (!stricmp(ii->name, name)) return &(*ii); // boo return NULL; } int find_wing_name(char *name) { int i; for (i = 0; i < Num_wings; i++) { if (!stricmp(name, Wings[i].name)) return i; } return -1; } /** * @brief Tries to create a wing of ships * @param[inout] wingp Pointer to the wing structure of the wing to be created * @param[in] num_to_create Number of ships to create * @param[in] force If set to 1, the wing will be created regardless of whether or not the arrival conditions * have been met yet. * @param[in] specific_instance Set this to create a specific ship from this wing * @returns Number of ships created */ int parse_wing_create_ships( wing *wingp, int num_to_create, int force, int specific_instance ) { int wingnum, objnum, num_create_save; int time_to_arrive; int pre_create_count; int i, j; // we need to send this in multiplayer pre_create_count = wingp->total_arrived_count; // force is used to force creation of the wing -- used for multiplayer if ( !force ) { // we only want to evaluate the arrival cue of the wing if: // 1) single player // 2) multiplayer and I am the host of the game // can't create any ships if the arrival cue is false or the timestamp has not elapsed. if ( !eval_sexp(wingp->arrival_cue) ) /* || !timestamp_elapsed(wingp->arrival_delay) ) */ return 0; // once the sexpressions becomes true, then check the arrival delay on the wing. The first time, the // arrival delay will be <= 0 meaning that no timer object has been set yet. Set up the timestamp // which should always give a number >= 0; if ( wingp->arrival_delay <= 0 ) { wingp->arrival_delay = timestamp( -wingp->arrival_delay * 1000 ); Assert ( wingp->arrival_delay >= 0 ); } if ( !timestamp_elapsed( wingp->arrival_delay ) ) return 0; // if wing is coming from docking bay, then be sure that ship we are arriving from actually exists // (or will exist). if ( wingp->arrival_location == ARRIVE_FROM_DOCK_BAY ) { int shipnum; char *name; Assert( wingp->arrival_anchor >= 0 ); name = Parse_names[wingp->arrival_anchor]; // see if ship is in mission. shipnum = ship_name_lookup( name ); if ( shipnum == -1 ) { int num_remaining; // see if ship is yet to arrive. If so, then return 0 so we can evaluate again later. if (mission_check_ship_yet_to_arrive(name)) return 0; // since this wing cannot arrive from this place, we need to mark the wing as destroyed and // set the wing variables appropriately. Good for directives. // set the gone flag wingp->flags.set(Ship::Wing_Flags::Gone); // mark the number of waves and number of ships destroyed equal to the last wave and the number // of ships yet to arrive num_remaining = ( (wingp->num_waves - wingp->current_wave) * wingp->wave_count); wingp->total_arrived_count += num_remaining; wingp->current_wave = wingp->num_waves; if ( mission_log_get_time(LOG_SHIP_DESTROYED, name, NULL, NULL) || mission_log_get_time(LOG_SELF_DESTRUCTED, name, NULL, NULL) ) { wingp->total_destroyed += num_remaining; } else if ( mission_log_get_time(LOG_SHIP_DEPARTED, name, NULL, NULL) ) { wingp->total_departed += num_remaining; } else { wingp->total_vanished += num_remaining; } mission_parse_mark_non_arrival(wingp); // Goober5000 return 0; } // Goober5000 - check status of fighterbays - if they're destroyed, we can't launch - but we want to reeval later if (ship_fighterbays_all_destroyed(&Ships[shipnum])) return 0; } if ( num_to_create == 0 ) return 0; // check the wave_delay_timestamp field. If it is not valid, make it valid (based on wave delay min // and max values). If it is valid, and not elapsed, then return. If it is valid and elasped, then // continue on. if ( !timestamp_valid(wingp->wave_delay_timestamp) ) { // if at least one of these is valid, then reset the timestamp. If they are both zero, we will create the // wave if ( (wingp->wave_delay_min > 0) || (wingp->wave_delay_max > 0) ) { Assert ( wingp->wave_delay_min <= wingp->wave_delay_max ); time_to_arrive = wingp->wave_delay_min + (int)(frand() * (wingp->wave_delay_max - wingp->wave_delay_min)); // MWA -- 5/18/98 // HACK HACK -- in the presense of Mike Comet and Mitri, I have introduced one of the most // serious breaches of coding standards. I'm to lazy to fix this the correct way. Insert // a delay before the next wave of the wing can arrive to that clients in the game have ample // time to kill off any ships in the wing before the next wave arrives. if ( Game_mode & GM_MULTIPLAYER ){ time_to_arrive += 7; } wingp->wave_delay_timestamp = timestamp(time_to_arrive * 1000); return 0; } // if we get here, both min and max values are 0; See comments above for a most serious hack time_to_arrive = 0; if ( Game_mode & GM_MULTIPLAYER ) time_to_arrive += 7; time_to_arrive *= 1000; wingp->wave_delay_timestamp = timestamp(time_to_arrive); } // now check to see if the wave_delay_timestamp is elapsed or not if ( !timestamp_elapsed(wingp->wave_delay_timestamp) ) return 0; } // finally we can create the wing. num_create_save = num_to_create; wingnum = WING_INDEX(wingp); // get the wing number // if there are no ships to create, then all ships must be player start ships -- do nothing in this case. if ( num_to_create == 0 ){ return 0; } wingp->current_wave++; // we are creating new ships // we need to create num_to_create ships. Since the arrival cues for ships in a wing // are ignored, then *all* ships must be in the Ship_arrival_list. objnum = -1; // Goober5000 - we have to do this via the array because we have no guarantee we'll be able to iterate along the list // (since created objects plus anything they're docked to will be removed from it) for (SCP_vector<p_object>::iterator ii = Parse_objects.begin(); ii != Parse_objects.end(); ++ii) { int index; ai_info *aip; p_object *p_objp = &(*ii); // ensure on arrival list if (!parse_object_on_arrival_list(p_objp)) continue; // compare the wingnums. When they are equal, we can create the ship. In the case of // wings that have multiple waves, this code implies that we essentially creating clones // of the ships that were created in Fred for the wing when more ships for a new wave // arrive. The threshold value of a wing can also make one of the ships in a wing be "cloned" // more often than other ships in the wing. I don't think this matters much. if (p_objp->wingnum != wingnum) continue; Assert( (p_objp->pos_in_wing >= 0) && (p_objp->pos_in_wing < MAX_SHIPS_PER_WING) ); // when ingame joining, we need to create a specific ship out of the list of ships for a // wing. specific_instance is a 0 based integer which specified which ship in the wing // to create. So, only create the ship we actually need to. if ((Game_mode & GM_MULTIPLAYER) && (specific_instance > 0)) { specific_instance--; continue; } // when not creating a specific ship, we should skip over any ships that weren't carried along in the red-alert else if (p_objp->flags[Mission::Parse_Object_Flags::Red_alert_deleted]) { num_to_create--; num_create_save--; ship_add_ship_type_count(p_objp->ship_class, -1); wingp->red_alert_skipped_ships++; // clear the flag so that this parse object can be used for the next wave p_objp->flags.remove(Mission::Parse_Object_Flags::Red_alert_deleted); // skip over this parse object if (num_to_create == 0) break; else continue; } Assert(!(p_objp->flags[Mission::Parse_Object_Flags::SF_Cannot_arrive])); // get allender // if we have the maximum number of ships in the wing, we must bail as well if (wingp->current_count >= MAX_SHIPS_PER_WING) { Int3(); // this is bogus -- we should always allow all ships to be created num_to_create = 0; break; } // bash the ship name to be the name of the wing + some number if there is > 1 wave in this wing wingp->total_arrived_count++; if (wingp->num_waves > 1) { bool needs_display_name; wing_bash_ship_name(p_objp->name, wingp->name, wingp->total_arrived_count + wingp->red_alert_skipped_ships, &needs_display_name); // set up display name if we need to // (In the unlikely edge case where the ship already has a display name for some reason, it will be overwritten. // This is unavoidable, because if we didn't overwrite display names, all waves would have the display name from the first wave.) if (needs_display_name) { p_objp->display_name = p_objp->name; end_string_at_first_hash_symbol(p_objp->display_name); p_objp->flags.set(Mission::Parse_Object_Flags::SF_Has_display_name); } // subsequent waves of ships will not be in the ship registry, so add them if (!ship_registry_get(p_objp->name)) { ship_registry_entry entry(p_objp->name); entry.p_objp = p_objp; Ship_registry.push_back(entry); Ship_registry_map[p_objp->name] = static_cast<int>(Ship_registry.size() - 1); } } // also, if multiplayer, set the parse object's net signature to be wing's net signature // base + total_arrived_count (before adding 1) // Cyborg -- The original ships in the wave have their net_signature set at mission parse // so only do this if this is a subsequent wave. if (Game_mode & GM_MULTIPLAYER && wingp->num_waves > 1) { // Cyborg -- Also, then we need to subtract the original wave's number of fighters // and also subtract 1 to use the wing's starting signature p_objp->net_signature = (ushort) (wingp->net_signature + wingp->total_arrived_count - (wingp->wave_count + 1)); } objnum = parse_create_object(p_objp); aip = &Ai_info[Ships[Objects[objnum].instance].ai_index]; // copy any goals from the wing to the newly created ship for (index = 0; index < MAX_AI_GOALS; index++) { if (wingp->ai_goals[index].ai_mode != AI_GOAL_NONE) ai_copy_mission_wing_goal(&wingp->ai_goals[index], aip); } Ai_info[Ships[Objects[objnum].instance].ai_index].wing = wingnum; if (wingp->flags[Ship::Wing_Flags::No_dynamic]) aip->ai_flags.set(AI::AI_Flags::No_dynamic); // update housekeeping variables // NOTE: for the initial wing setup we use actual position to get around // object order isses, but ships in all following waves just get // tacked onto the end of the list if (wingp->current_wave == 1) { wingp->ship_index[p_objp->pos_in_wing] = Objects[objnum].instance; } else { wingp->ship_index[wingp->current_count] = Objects[objnum].instance; } // set up wingman status index hud_wingman_status_set_index(wingp, &Ships[Objects[objnum].instance], p_objp); p_objp->wing_status_wing_index = Ships[Objects[objnum].instance].wing_status_wing_index; p_objp->wing_status_wing_pos = Ships[Objects[objnum].instance].wing_status_wing_pos; wingp->current_count++; // keep any player ship on the parse object list -- used for respawns // 5/8/98 -- MWA -- don't remove ships from the list when you are ingame joining if (!(p_objp->flags[Mission::Parse_Object_Flags::OF_Player_start])) { if ((Game_mode & GM_NORMAL) || !(Net_player->flags & NETINFO_FLAG_INGAME_JOIN)) { // only remove ship if one wave in wing if (wingp->num_waves == wingp->current_wave) { // remove p_objp from the list list_remove(&Ship_arrival_list, p_objp); // free up sexp nodes for reuse if (p_objp->ai_goals != -1) free_sexp2(p_objp->ai_goals); } } } // flag ship with SF_FROM_PLAYER_WING if a member of player starting wings if (MULTI_TEAM) { // different for tvt -- Goober5000 for (j = 0; j < MAX_TVT_WINGS; j++) { if (!stricmp(TVT_wing_names[j], wingp->name)) Ships[Objects[objnum].instance].flags.set(Ship::Ship_Flags::From_player_wing); } } else { for (j = 0; j < MAX_STARTING_WINGS; j++) { if (!stricmp(Starting_wing_names[j], wingp->name)) Ships[Objects[objnum].instance].flags.set(Ship::Ship_Flags::From_player_wing); } } // keep track of how many ships to create. Stop when we have done all that we are supposed to do. num_to_create--; if (num_to_create == 0) break; } // we should always have enough ships in the list!!! Assert (num_to_create == 0); // wing current_count needs to match the end of the ship_index[] list, but there // is a very off chance it could have holes in it (especially if it's a red-alert // wing that arrives late), so make sure to compact the list int length = MAX_SHIPS_PER_WING; for (i = 0; i < length; i++) { if (wingp->ship_index[i] == -1) { // shift actual values downward for (j = i; j < length - 1; j++) { wingp->ship_index[j] = wingp->ship_index[j+1]; // update "special" ship too if (wingp->special_ship == j+1) wingp->special_ship--; } // last value becomes -1 wingp->ship_index[j] = -1; length--; // stay on the current index in case we still have a -1 i--; } } // possibly play some event driven music here. Send a network packet indicating the wing was // created. Only do this stuff if actually in the mission. if ( (objnum != -1) && (Game_mode & GM_IN_MISSION) ) { // if true, we have created at least one new ship. int it, ship_num; // see if this wing is a player starting wing, and if so, call the maybe_add_form_goal // function to possibly make the wing form on the player for (it = 0; it < MAX_STARTING_WINGS; it++ ) { if ( Starting_wings[it] == wingnum ){ break; } } if ( it < MAX_STARTING_WINGS ){ ai_maybe_add_form_goal( wingp ); } mission_log_add_entry( LOG_WING_ARRIVED, wingp->name, NULL, wingp->current_wave ); ship_num = wingp->ship_index[0]; if ( !(Ships[ship_num].flags[Ship::Ship_Flags::No_arrival_music]) && !(wingp->flags[Ship::Wing_Flags::No_arrival_music]) ) { if ( timestamp_elapsed(Allow_arrival_music_timestamp) ) { Allow_arrival_music_timestamp = timestamp(ARRIVAL_MUSIC_MIN_SEPARATION); event_music_arrival(Ships[ship_num].team); } } // possibly change the location where these ships arrive based on the wings arrival location mission_set_wing_arrival_location( wingp, num_create_save ); // if in multiplayer (and I am the host) and in the mission, send a wing create command to all // other players if ( MULTIPLAYER_MASTER ){ send_wing_create_packet( wingp, num_create_save, pre_create_count ); } #ifndef NDEBUG // test code to check to be sure that all ships in the wing are ignoring the same types // of orders from the leader if ( Fred_running ) { Assert( wingp->ship_index[wingp->special_ship] != -1 ); int orders = Ships[wingp->ship_index[0]].orders_accepted; for (it = 0; it < wingp->current_count; it++ ) { if (it == wingp->special_ship) continue; if ( orders != Ships[wingp->ship_index[it]].orders_accepted ) { Warning(LOCATION, "ships in wing %s are ignoring different player orders. Please find Mark A\nto talk to him about this.", wingp->name ); break; } } } #endif } wingp->wave_delay_timestamp = timestamp(-1); // we will need to set this up properly for the next wave return num_create_save; } void parse_wing(mission *pm) { int wingnum, i, wing_goals, delay, saved_arrival_delay; char name[NAME_LENGTH], ship_names[MAX_SHIPS_PER_WING][NAME_LENGTH]; char wing_flag_strings[PARSEABLE_WING_FLAGS][NAME_LENGTH]; wing *wingp; Assert(pm != NULL); wingp = &Wings[Num_wings]; required_string("$Name:"); stuff_string(wingp->name, F_NAME, NAME_LENGTH); // quickly look through the squadron wing names to see if we have to warn the modder about this mission // to avoid them avoid the multi missing wing bug. if (pm->game_type & (MISSION_TYPE_MULTI | MISSION_TYPE_MULTI_COOP)) { for (int j = 0; j < MAX_SQUADRON_WINGS; j++) { if (!strcmp(wingp->name, Squadron_wing_names[j])) { Squadron_wing_names_found[j] = true; } } } wingnum = find_wing_name(wingp->name); if (wingnum != -1) error_display(0, NOX("Redundant wing name: %s\n"), wingp->name); wingnum = Num_wings; wingp->total_arrived_count = 0; wingp->red_alert_skipped_ships = 0; wingp->total_destroyed = 0; wingp->total_departed = 0; // Goober5000 wingp->total_vanished = 0; // Goober5000 wingp->flags.reset(); // squad logo - Goober5000 if (optional_string("+Squad Logo:")) { int flag = -1; stuff_string(wingp->wing_squad_filename, F_NAME, MAX_FILENAME_LEN); // load it only if FRED isn't running if (!Fred_running) { // check all previous wings to see if we already loaded it (we want to save memory) for (i = 0; i < Num_wings; i++) { // do we have a previous texture? if (Wings[i].wing_insignia_texture != -1) { // if we have a match if (!stricmp(Wings[i].wing_squad_filename, wingp->wing_squad_filename)) { flag = i; break; } } } // if we have loaded it already, just use the old bitmap index if (flag != -1) { wingp->wing_insignia_texture = Wings[flag].wing_insignia_texture; } else { wing_load_squad_bitmap(wingp); } } } required_string("$Waves:"); stuff_int(&wingp->num_waves); Assert ( wingp->num_waves >= 1 ); // there must be at least 1 wave wingp->current_wave = 0; required_string("$Wave Threshold:"); stuff_int(&wingp->threshold); required_string("$Special Ship:"); stuff_int(&wingp->special_ship); // Use a custom formation if specified if (optional_string("+Formation:")) { char f[NAME_LENGTH]; stuff_string(f, F_NAME, NAME_LENGTH); wingp->formation = wing_formation_lookup(f); if (wingp->formation < 0) { Warning(LOCATION, "Invalid Formation %s.", f); } } else { wingp->formation = -1; } wingp->arrival_anchor = -1; wingp->arrival_distance = 0; wingp->arrival_path_mask = -1; // -1 only until resolved find_and_stuff("$Arrival Location:", &wingp->arrival_location, F_NAME, Arrival_location_names, Num_arrival_names, "Arrival Location"); if ( optional_string("+Arrival Distance:") ) { stuff_int( &wingp->arrival_distance ); // Goober5000 if ((wingp->arrival_distance <= 0) && ((wingp->arrival_location == ARRIVE_NEAR_SHIP) || (wingp->arrival_location == ARRIVE_IN_FRONT_OF_SHIP))) { Warning(LOCATION, "Arrival distance for wing %s cannot be %d. Setting to 1.\n", wingp->name, wingp->arrival_distance); wingp->arrival_distance = 1; } } if ( wingp->arrival_location != ARRIVE_AT_LOCATION ) { required_string("$Arrival Anchor:"); stuff_string(name, F_NAME, NAME_LENGTH); wingp->arrival_anchor = get_anchor(name); } if (optional_string("+Arrival Paths:")) { // temporarily use mask to point to the restriction index wingp->arrival_path_mask = add_path_restriction(); } if (optional_string("+Arrival delay:")) { stuff_int(&delay); if ( delay < 0 ) Error(LOCATION, "Cannot have arrival delay < 0 on wing %s", wingp->name ); } else delay = 0; saved_arrival_delay = delay; if ( !Fred_running ){ wingp->arrival_delay = -delay; } else { wingp->arrival_delay = delay; } required_string("$Arrival Cue:"); wingp->arrival_cue = get_sexp_main(); wingp->departure_anchor = -1; wingp->departure_path_mask = -1; // -1 only until resolved find_and_stuff("$Departure Location:", &wingp->departure_location, F_NAME, Departure_location_names, Num_arrival_names, "Departure Location"); if ( wingp->departure_location != DEPART_AT_LOCATION ) { required_string("$Departure Anchor:"); stuff_string( name, F_NAME, NAME_LENGTH ); wingp->departure_anchor = get_anchor(name); } if (optional_string("+Departure Paths:")) { // temporarily use mask to point to the restriction index wingp->departure_path_mask = add_path_restriction(); } if (optional_string("+Departure delay:")) { stuff_int(&delay); if ( delay < 0 ) Error(LOCATION, "Cannot have departure delay < 0 on wing %s", wingp->name ); } else delay = 0; if ( !Fred_running ) wingp->departure_delay = -delay; // use negative numbers to mean that delay timer not yet set else wingp->departure_delay = delay; required_string("$Departure Cue:"); wingp->departure_cue = get_sexp_main(); // stores a list of all names of ships in the wing required_string("$Ships:"); wingp->wave_count = (int)stuff_string_list( ship_names, MAX_SHIPS_PER_WING ); wingp->current_count = 0; // get the wings goals, if any wing_goals = -1; if ( optional_string("$AI Goals:") ) wing_goals = get_sexp_main(); wingp->hotkey = -1; if (optional_string("+Hotkey:")) { stuff_int(&wingp->hotkey); Assert((wingp->hotkey >= 0) && (wingp->hotkey < 10)); } if (optional_string("+Flags:")) { auto count = (int)stuff_string_list( wing_flag_strings, PARSEABLE_WING_FLAGS); for (i = 0; i < count; i++) { if (!stricmp(wing_flag_strings[i], NOX("ignore-count"))) wingp->flags.set(Ship::Wing_Flags::Ignore_count); else if (!stricmp(wing_flag_strings[i], NOX("reinforcement"))) wingp->flags.set(Ship::Wing_Flags::Reinforcement); else if (!stricmp(wing_flag_strings[i], NOX("no-arrival-music"))) wingp->flags.set(Ship::Wing_Flags::No_arrival_music); else if (!stricmp(wing_flag_strings[i], NOX("no-arrival-message"))) wingp->flags.set(Ship::Wing_Flags::No_arrival_message); else if (!stricmp(wing_flag_strings[i], NOX("no-arrival-warp"))) wingp->flags.set(Ship::Wing_Flags::No_arrival_warp); else if (!stricmp(wing_flag_strings[i], NOX("no-departure-warp"))) wingp->flags.set(Ship::Wing_Flags::No_departure_warp); else if (!stricmp(wing_flag_strings[i], NOX("no-dynamic"))) wingp->flags.set(Ship::Wing_Flags::No_dynamic); else if (!stricmp(wing_flag_strings[i], NOX("nav-carry-status"))) wingp->flags.set(Ship::Wing_Flags::Nav_carry); else Warning(LOCATION, "unknown wing flag\n%s\n\nSkipping.", wing_flag_strings[i]); } } // get the wave arrival delay bounds (if present). Used as lower and upper bounds (in seconds) // which determine when new waves of a wing should arrive. wingp->wave_delay_min = 0; wingp->wave_delay_max = 0; if ( optional_string("+Wave Delay Min:") ) stuff_int( &(wingp->wave_delay_min) ); if ( optional_string("+Wave Delay Max:") ) stuff_int( &(wingp->wave_delay_max) ); // be sure to set the wave arrival timestamp of this wing to pop right away so that the // wing could be created if it needs to be wingp->wave_delay_timestamp = timestamp(0); // initialize wing goals for (i=0; i<MAX_AI_GOALS; i++) { wingp->ai_goals[i].ai_mode = AI_GOAL_NONE; wingp->ai_goals[i].signature = -1; wingp->ai_goals[i].priority = -1; wingp->ai_goals[i].flags.reset(); } // 7/13/98 -- MWA // error checking against the player ship wings (i.e. starting & tvt) to be sure that wave count doesn't exceed one for // these wings. if ( MULTI_NOT_TEAM ) { for (i = 0; i < MAX_STARTING_WINGS; i++ ) { if ( !stricmp(Starting_wing_names[i], wingp->name) ) { if ( wingp->num_waves > 1 ) { // only end the game if we're the server - clients will eventually find out :) if(Net_player->flags & NETINFO_FLAG_AM_MASTER){ multi_quit_game(PROMPT_NONE, MULTI_END_NOTIFY_NONE, MULTI_END_ERROR_WAVE_COUNT); } } } } } else if (MULTI_TEAM) { for (i = 0; i < MAX_TVT_WINGS; i++ ) { if ( !stricmp(TVT_wing_names[i], wingp->name) ) { if ( wingp->num_waves > 1 ) { // only end the game if we're the server - clients will eventually find out :) if(Net_player->flags & NETINFO_FLAG_AM_MASTER){ multi_quit_game(PROMPT_NONE, MULTI_END_NOTIFY_NONE, MULTI_END_ERROR_WAVE_COUNT); } } } } } // Get the next starting signature for this in this wing. We want to reserve wave_count * num_waves // of signature. These can be used to construct wings for ingame joiners. if ( Game_mode & GM_MULTIPLAYER ) { int next_signature; wingp->net_signature = multi_assign_network_signature( MULTI_SIG_SHIP ); // Cyborg -- Subtract one because the original wave already has its signatures set. next_signature = wingp->net_signature + (wingp->wave_count * (wingp->num_waves - 1)); if ( next_signature > SHIP_SIG_MAX ) Error(LOCATION, "Too many total ships in mission (%d) for network signature assignment", SHIP_SIG_MAX); multi_set_network_signature( (ushort)next_signature, MULTI_SIG_SHIP ); } for (i=0; i<MAX_SHIPS_PER_WING; i++) wingp->ship_index[i] = -1; // set up the ai_goals for this wing -- all ships created from this wing will inherit these goals // goals for the wing are stored slightly differently than for ships. We simply store the index // into the sexpression array of each goal (max 10). When a ship in this wing is created, each // goal in the wings goal array is given to the ship. if ( wing_goals != -1 ) { int sexp; // this will assign the goals to the wings as well as to any ships in the wing that have been // already created. for ( sexp = CDR(wing_goals); sexp != -1; sexp = CDR(sexp) ) ai_add_wing_goal_sexp(sexp, AIG_TYPE_EVENT_WING, wingp); // used by Fred free_sexp2(wing_goals); // free up sexp nodes for reuse, since they aren't needed anymore. } // set the wing number for all ships in the wing for (i = 0; i < wingp->wave_count; i++ ) { char *ship_name = ship_names[i]; int assigned = 0; // Goober5000 - since the ship/wing creation stuff is reordered to accommodate multiple docking, // everything is still only in the parse array at this point (in both FRED and FS2) // find the parse object and assign it the wing number for (SCP_vector<p_object>::iterator p_objp = Parse_objects.begin(); p_objp != Parse_objects.end(); ++p_objp) { if ( !strcmp(ship_name, p_objp->name) ) { // get Allender -- ship appears to be in multiple wings Assert (p_objp->wingnum == -1); // assign wingnum p_objp->wingnum = wingnum; p_objp->pos_in_wing = i; assigned++; // Goober5000 - if this is a player start object, there shouldn't be a wing arrival delay (Mantis #2678) if ((p_objp->flags[Mission::Parse_Object_Flags::OF_Player_start]) && (saved_arrival_delay != 0)) { Warning(LOCATION, "Wing %s specifies an arrival delay of %ds, but it also contains a player. The arrival delay will be reset to 0.", wingp->name, saved_arrival_delay); if (!Fred_running && wingp->arrival_delay > 0) { // timestamp has been set, so set it again wingp->arrival_delay = timestamp(0); } else { // no timestamp, or timestamp invalid wingp->arrival_delay = 0; } // prevent message from reappearing saved_arrival_delay = 0; } } } // error checking if (assigned == 0) { Error(LOCATION, "Cannot load mission -- for wing %s, ship %s is not present in #Objects section.\n", wingp->name, ship_name); } else if (assigned > 1) { Error(LOCATION, "Cannot load mission -- for wing %s, ship %s is specified multiple times in wing.\n", wingp->name, ship_name); } } // Goober5000 - wing creation stuff moved to post_process_ships_wings } void parse_wings(mission* pm) { // reset this for the missing wing bug. for (int i = 0; i < MAX_SQUADRON_WINGS; i++) { Squadron_wing_names_found[i] = false; } required_string("#Wings"); while (required_string_either("#Events", "$Name:")) { Assert(Num_wings < MAX_WINGS); parse_wing(pm); Num_wings++; } bool found = false; static_assert(MAX_TVT_WINGS_PER_TEAM == 1, "Unless you also update the section of code below or redo the loadout code, for TvT, there should be just one player wing, otherwise, wings may start disappearing in game."); // now see if we found the missing wing. We're looking for a wing that is there after a wing that is not. // for now TvT mission do not have enough player wings to be affected by this bug. if (pm->game_type & (MISSION_TYPE_MULTI | MISSION_TYPE_MULTI_COOP)) { do { found = false; // we only search up to the MAX_STARTING_WINGS because non-starting wings should not be in starting wing indices (0-2) for (int i = 1; i < MAX_STARTING_WINGS; i++) { // If there was a wing for this squadron entry, check the last one. If it's empty, we found a mistake, so move the wing names over. if (Squadron_wing_names_found[i] && !Squadron_wing_names_found[i - 1]) { Warning(LOCATION, "Squadron wings are not in the correct order and may cause wings to disappear in multi.\n\nEither wing %s should exist or the %s entry needs to come before it in the list.\n\nPlease go back and fix the mission.", Squadron_wing_names[i - 1], Squadron_wing_names[i]); char temp_chars[NAME_LENGTH]; strcpy_s(temp_chars, Squadron_wing_names[i - 1]); strcpy_s(Squadron_wing_names[i - 1], Squadron_wing_names[i]); strcpy_s(Squadron_wing_names[i], temp_chars); Squadron_wing_names_found[i] = !Squadron_wing_names_found[i]; Squadron_wing_names_found[i - 1] = !Squadron_wing_names_found[i - 1]; found = true; } } } while (found); } } // Goober5000 void resolve_path_masks(int anchor, int *path_mask) { path_restriction_t *prp; // if we have no restrictions, do a quick out if (*path_mask < 0) { *path_mask = 0; return; } // get path restriction info prp = &Path_restrictions[*path_mask]; // uninitialized; compute the mask from scratch if (prp->cached_mask & (1 << MAX_SHIP_BAY_PATHS)) { int j, bay_path, modelnum; p_object *parent_pobjp; // get anchor ship Assert(!(anchor & SPECIAL_ARRIVAL_ANCHOR_FLAG)); parent_pobjp = mission_parse_get_parse_object(Parse_names[anchor]); // Load the anchor ship model with subsystems and all; it'll need to be done for this mission anyway ship_info *sip = &Ship_info[parent_pobjp->ship_class]; modelnum = model_load(sip->pof_file, sip->n_subsystems, &sip->subsystems[0]); // resolve names to indexes *path_mask = 0; for (j = 0; j < prp->num_paths; j++) { bay_path = model_find_bay_path(modelnum, prp->path_names[j]); if (bay_path < 0) continue; *path_mask |= (1 << bay_path); } // cache the result prp->cached_mask = *path_mask; } // already computed; so reuse it else { *path_mask = prp->cached_mask; } } /** * Resolve arrival/departure path masks * NB: between parsing and the time this function is run, the path_mask variables store the index of the path info; * at all other times, they store the masks of the bay paths as expected */ void post_process_path_stuff() { int i; wing *wingp; // take care of parse objects (ships) for (SCP_vector<p_object>::iterator pobjp = Parse_objects.begin(); pobjp != Parse_objects.end(); ++pobjp) { resolve_path_masks(pobjp->arrival_anchor, &pobjp->arrival_path_mask); resolve_path_masks(pobjp->departure_anchor, &pobjp->departure_path_mask); } // take care of wings for (i = 0; i < Num_wings; i++) { wingp = &Wings[i]; resolve_path_masks(wingp->arrival_anchor, &wingp->arrival_path_mask); resolve_path_masks(wingp->departure_anchor, &wingp->departure_path_mask); } } // Goober5000 void post_process_ships_wings() { int i; // Goober5000 - first, resolve the path masks. Needs to be done first because // mission_parse_maybe_create_parse_object relies on it. post_process_path_stuff(); // Goober5000 - now that we've parsed all the objects, resolve the initially docked references. // This must be done before anything that relies on the dock references but can't be done until // both ships and wings have been parsed. mission_parse_set_up_initial_docks(); // Goober5000 - now add all the parse objects to the ship registry. This must be done before // any ships are created from the parse objects. for (auto &p_obj : Parse_objects) { ship_registry_entry entry(p_obj.name); entry.p_objp = &p_obj; Ship_registry.push_back(entry); Ship_registry_map[p_obj.name] = static_cast<int>(Ship_registry.size() - 1); } // Goober5000 - now create all objects that we can. This must be done before any ship stuff // but can't be done until the dock references are resolved. This was originally done // in parse_object(). for (auto &p_obj : Parse_objects) { // Evaluate the arrival cue and maybe set up the arrival delay. This can't be done until the ship registry is populated // (because SEXPs now require a complete ship registry) but must be done before the arrival list check inside // mission_parse_maybe_create_parse_object. That check is, in fact, the only reason this is needed. We don't need to // pre-emptively set up the delay for wings because there is no equivalent wing arrival list check. In any case, the // arrival_delay is always validated in mission_did_ship_arrive (for ships) and parse_wing_create_ships (for wings). // Addendum: Don't mess with any arrival delays which are strictly positive, meaning they have already been set. // (This is the case for ships destroyed before mission. In the retail codebase, the destroy-before-mission chunk was // parsed after the arrival cue and delay were parsed and checked, so it overwrote them.) if (!Fred_running && (p_obj.arrival_cue >= 0) && (p_obj.arrival_delay <= 0)) { // eval the arrival cue. if the cue is true, set up the timestamp for the arrival delay if (eval_sexp(p_obj.arrival_cue)) p_obj.arrival_delay = timestamp(-p_obj.arrival_delay * 1000); } // create as usual mission_parse_maybe_create_parse_object(&p_obj); } // ----------------- at this point the ships have been created ----------------- // Now set up the wings. This must be done after both dock stuff and ship stuff. // error checking for custom wings if (strcmp(Starting_wing_names[0], TVT_wing_names[0]) != 0) { Error(LOCATION, "The first starting wing and the first team-versus-team wing must have the same wing name.\n"); } // Goober5000 - for FRED, the ships are initialized after the wings, so we must now tell the wings // where their ships are if (Fred_running) { // even though the ships are already created, only the parse objects know the wing info for (SCP_vector<p_object>::iterator p_objp = Parse_objects.begin(); p_objp != Parse_objects.end(); ++p_objp) { // link the ship into the wing's array of ship indices (previously done in parse_wing // in a rather less backwards way) if (p_objp->wingnum >= 0) { int shipnum = ship_name_lookup(p_objp->name); Assert(shipnum >= 0 && shipnum < MAX_SHIPS); Assert(p_objp->pos_in_wing >= 0 && p_objp->pos_in_wing < MAX_SHIPS_PER_WING); Wings[p_objp->wingnum].ship_index[p_objp->pos_in_wing] = shipnum; } } } // Goober5000 - for FS2, the wings are initialized first, so all we have to do is create their ships else { for (i = 0; i < Num_wings; i++) { wing *wingp = &Wings[i]; // create the wing if is isn't a reinforcement. if (!(wingp->flags[Ship::Wing_Flags::Reinforcement])) parse_wing_create_ships(wingp, wingp->wave_count); } } } // mission events are sexpressions which cause things to happen based on the outcome // of other events in a mission. Essentially scripting the different things that can happen // in a mission void parse_event(mission * /*pm*/) { char buf[NAME_LENGTH]; mission_event *event; event = &Mission_events[Num_mission_events]; required_string( "$Formula:" ); event->formula = get_sexp_main(); if (optional_string("+Name:")){ stuff_string(event->name, F_NAME, NAME_LENGTH); } else { event->name[0] = 0; } if ( optional_string("+Repeat Count:")){ stuff_int( &(event->repeat_count) ); // sanity check on the repeat count variable // _argv[-1] - negative repeat count is now legal; means repeat indefinitely. if ( event->repeat_count == 0 ){ Warning(LOCATION, "Repeat count for mission event %s is 0.\nMust be >= 1 or negative! Setting to 1.", event->name ); event->repeat_count = 1; } } else { event->repeat_count = 1; } if ( optional_string("+Trigger Count:")){ stuff_int( &(event->trigger_count) ); event->flags |= MEF_USING_TRIGGER_COUNT; // if we have a trigger count but no repeat count, we want the event to loop until it has triggered enough times if (event->repeat_count == 1) { event->repeat_count = -1; } // sanity check on the trigger count variable // negative trigger count is also legal if ( event->trigger_count == 0 ){ Warning(LOCATION, "Trigger count for mission event %s is 0.\nMust be >= 1 or negative! Setting to 1.", event->name ); event->trigger_count = 1; } } else { event->trigger_count = 1; } event->interval = -1; if ( optional_string("+Interval:")){ stuff_int( &(event->interval) ); } event->score = 0; if ( optional_string("+Score:") ){ stuff_int(&event->score); } event->chain_delay = -1; if ( optional_string("+Chained:") ){ stuff_int(&event->chain_delay); } if ( optional_string("+Objective:") ) { stuff_string(buf, F_NAME, NAME_LENGTH); event->objective_text = vm_strdup(buf); } else { event->objective_text = NULL; } if ( optional_string("+Objective key:") ) { stuff_string(buf, F_NAME, NAME_LENGTH); event->objective_key_text = vm_strdup(buf); } else { event->objective_key_text = NULL; } event->team = -1; if( optional_string("+Team:") ) { stuff_int(&event->team); // sanity check if (event->team < -1 || event->team >= MAX_TVT_TEAMS) { if (Fred_running && !Warned_about_team_out_of_range) { Warning(LOCATION, "+Team: value was out of range in the mission file! This was probably caused by a bug in an older version of FRED. Using -1 for now."); Warned_about_team_out_of_range = true; } event->team = -1; } } // Need to set this to zero so that we don't accidentally reuse old data. event->flags = 0; if (optional_string("+Event Flags:")) { parse_string_flag_list(&event->flags, Mission_event_flags, Num_mission_event_flags); } if( optional_string("+Event Log Flags:") ) { SCP_vector<SCP_string> buffer; stuff_string_list(buffer); for (int i = 0; i < (int)buffer.size(); i++) { int add_flag = 1; for (int j = 0; j < MAX_MISSION_EVENT_LOG_FLAGS; j++) { if (!stricmp(buffer[i].c_str(), Mission_event_log_flags[j])) { // bitshift add_flag so that it equals the index of the flag in Mission_event_log_flags[] add_flag = add_flag << j; event->mission_log_flags |= add_flag; } } } } if (optional_string("$Annotations Start")) { // annotations are only used in FRED if (Fred_running) { while (check_for_string("+Comment:") || check_for_string("+Background Color:") || check_for_string("+Path:")) { event_annotation ea; ea.path.push_back(Num_mission_events); if (optional_string("+Comment:")) { stuff_string(ea.comment, F_MULTITEXT); lcl_replace_stuff(ea.comment, true); } if (optional_string("+Background Color:")) { stuff_ubyte(&ea.r); if (*Mp == ',') Mp++; stuff_ubyte(&ea.g); if (*Mp == ',') Mp++; stuff_ubyte(&ea.b); } if (optional_string("+Path:")) { int num; while (true) { ignore_gray_space(); if (stuff_int_optional(&num) != 2) { break; } ea.path.push_back(num); } } Event_annotations.push_back(std::move(ea)); } required_string("$Annotations End"); } else { skip_to_string("$Annotations End"); } } } void parse_events(mission *pm) { required_string("#Events"); while (required_string_either( "#Goals", "$Formula:")) { Assert( Num_mission_events < MAX_MISSION_EVENTS ); parse_event(pm); Num_mission_events++; } } void parse_goal(mission *pm) { int dummy; mission_goal *goalp; goalp = &Mission_goals[Num_goals++]; Assert(Num_goals < MAX_GOALS); Assert(pm != NULL); find_and_stuff("$Type:", &goalp->type, F_NAME, Goal_type_names, Num_goal_type_names, "goal type"); required_string("+Name:"); stuff_string(goalp->name, F_NAME, NAME_LENGTH); // backwards compatibility for old Fred missions - all new missions should use $MessageNew if(optional_string("$Message:")){ stuff_string(goalp->message, F_NAME, MAX_GOAL_TEXT); } else { required_string("$MessageNew:"); stuff_string(goalp->message, F_MULTITEXT, MAX_GOAL_TEXT); } if (optional_string("$Rating:")){ stuff_int(&dummy); // not used } required_string("$Formula:"); goalp->formula = get_sexp_main(); goalp->flags = 0; if ( optional_string("+Invalid:") ) goalp->type |= INVALID_GOAL; if ( optional_string("+Invalid") ) goalp->type |= INVALID_GOAL; if ( optional_string("+No music") ) goalp->flags |= MGF_NO_MUSIC; goalp->score = 0; if ( optional_string("+Score:") ){ stuff_int(&goalp->score); } goalp->team = 0; if ( optional_string("+Team:") ){ stuff_int( &goalp->team ); // sanity check if (goalp->team < -1 || goalp->team >= Num_iffs) { if (Fred_running && !Warned_about_team_out_of_range) { Warning(LOCATION, "+Team: value was out of range in the mission file! This was probably caused by a bug in an older version of FRED. Using -1 for now."); Warned_about_team_out_of_range = true; } goalp->team = -1; } } } void parse_goals(mission *pm) { required_string("#Goals"); while (required_string_either("#Waypoints", "$Type:")){ parse_goal(pm); } } void parse_waypoint_list(mission *pm) { Assert(pm != NULL); char name_buf[NAME_LENGTH]; required_string("$Name:"); stuff_string(name_buf, F_NAME, NAME_LENGTH); SCP_vector<vec3d> vec_list; required_string("$List:"); stuff_vec3d_list(vec_list); waypoint_add_list(name_buf, vec_list); } void parse_waypoints_and_jumpnodes(mission *pm) { vec3d pos; required_string("#Waypoints"); char file_name[MAX_FILENAME_LEN] = { 0 }; char jump_name[NAME_LENGTH] = { 0 }; while (optional_string("$Jump Node:")) { stuff_vec3d(&pos); CJumpNode jnp(&pos); if (optional_string("$Jump Node Name:") || optional_string("+Jump Node Name:")) { stuff_string(jump_name, F_NAME, NAME_LENGTH); jnp.SetName(jump_name); } if(optional_string("+Model File:")){ stuff_string(file_name, F_NAME, MAX_FILENAME_LEN); jnp.SetModel(file_name); } if(optional_string("+Alphacolor:")) { ubyte r,g,b,a; stuff_ubyte(&r); stuff_ubyte(&g); stuff_ubyte(&b); stuff_ubyte(&a); jnp.SetAlphaColor(r, g, b, a); } if(optional_string("+Hidden:")) { int hide; stuff_boolean(&hide); jnp.SetVisibility(!hide); } Jump_nodes.push_back(std::move(jnp)); } while (required_string_either("#Messages", "$Name:")) parse_waypoint_list(pm); } void parse_messages(mission *pm, int flags) { required_string("#Messages"); // command stuff by Goober5000 --------------------------------------- strcpy_s(pm->command_sender, DEFAULT_COMMAND); if (optional_string("$Command Sender:")) { char temp[NAME_LENGTH]; stuff_string(temp, F_NAME, NAME_LENGTH); if (*temp == '#') strcpy_s(pm->command_sender, &temp[1]); else strcpy_s(pm->command_sender, temp); } pm->command_persona = Default_command_persona; if (optional_string("$Command Persona:")) { int idx; char temp[NAME_LENGTH]; stuff_string(temp, F_NAME, NAME_LENGTH); idx = message_persona_name_lookup(temp); if (idx >= 0) pm->command_persona = idx; else Warning(LOCATION, "Supplied Command Persona is invalid! Defaulting to %s.", Personas[Default_command_persona].name); } // end of command stuff ---------------------------------------------- mprintf(("Starting mission message count : %d\n", (int)Message_waves.size())); // the message_parse function can be found in MissionMessage.h. The format in the // mission file takes the same format as the messages in messages,tbl. Make parsing // a whole lot easier!!! while ( required_string_either("#Reinforcements", "$Name")){ message_parse((flags & MPF_IMPORT_FSM) != 0); // call the message parsing system } mprintf(("Ending mission message count : %d\n", (int)Message_waves.size())); } void parse_reinforcement(mission *pm) { reinforcements *ptr; p_object *rforce_obj = NULL; int instance = -1; Assert(Num_reinforcements < MAX_REINFORCEMENTS); Assert(pm != NULL); ptr = &Reinforcements[Num_reinforcements]; required_string("$Name:"); stuff_string(ptr->name, F_NAME, NAME_LENGTH); find_and_stuff("$Type:", &ptr->type, F_NAME, Reinforcement_type_names, Num_reinforcement_type_names, "reinforcement type"); required_string("$Num times:"); stuff_int(&ptr->uses); ptr->num_uses = 0; // reset the flags to 0 ptr->flags = 0; if ( optional_string("+Arrival delay:") ){ stuff_int( &(ptr->arrival_delay) ); } if ( optional_string("+No Messages:") ){ stuff_string_list( ptr->no_messages, MAX_REINFORCEMENT_MESSAGES ); } if ( optional_string("+Yes Messages:") ){ stuff_string_list( ptr->yes_messages, MAX_REINFORCEMENT_MESSAGES ); } // sanity check on the names of reinforcements rforce_obj = mission_parse_get_parse_object(ptr->name); if (rforce_obj == NULL) { if ((instance = wing_name_lookup(ptr->name, 1)) == -1) { Warning(LOCATION, "Reinforcement %s not found as ship or wing", ptr->name); return; } } else { // Individual ships in wings can't be reinforcements - FUBAR if (rforce_obj->wingnum >= 0) { Warning(LOCATION, "Reinforcement %s is part of a wing - Ignoring reinforcement declaration", ptr->name); return; } else { instance = rforce_obj->wingnum; } } // now, if the reinforcement is a wing, then set the number of waves of the wing == number of // uses of the reinforcement if (instance >= 0) { Wings[instance].num_waves = ptr->uses; } Num_reinforcements++; } void parse_reinforcements(mission *pm) { Num_reinforcements = 0; required_string("#Reinforcements"); while (required_string_either("#Background bitmaps", "$Name:")) parse_reinforcement(pm); } void parse_one_background(background_t *background) { // clear here too because this function can be called from more than one place background->suns.clear(); background->bitmaps.clear(); // parse suns while (optional_string("$Sun:")) { starfield_list_entry sle; // filename stuff_string(sle.filename, F_NAME, MAX_FILENAME_LEN); // angles required_string("+Angles:"); stuff_float(&sle.ang.p); stuff_float(&sle.ang.b); stuff_float(&sle.ang.h); // scale required_string("+Scale:"); stuff_float(&sle.scale_x); sle.scale_y = sle.scale_x; sle.div_x = 1; sle.div_y = 1; // add it background->suns.push_back(sle); } // parse starfields while (optional_string("$Starbitmap:")) { starfield_list_entry sle; // filename stuff_string(sle.filename, F_NAME, MAX_FILENAME_LEN); // angles required_string("+Angles:"); stuff_float(&sle.ang.p); stuff_float(&sle.ang.b); stuff_float(&sle.ang.h); // scale if (optional_string("+Scale:")) { stuff_float(&sle.scale_x); sle.scale_y = sle.scale_x; sle.div_x = 1; sle.div_y = 1; } else { required_string("+ScaleX:"); stuff_float(&sle.scale_x); required_string("+ScaleY:"); stuff_float(&sle.scale_y); required_string("+DivX:"); stuff_int(&sle.div_x); required_string("+DivY:"); stuff_int(&sle.div_y); } // add it background->bitmaps.push_back(sle); } } void parse_bitmaps(mission *pm) { char str[MAX_FILENAME_LEN]; int z; required_string("#Background bitmaps"); required_string("$Num stars:"); stuff_int(&Num_stars); if (Num_stars >= MAX_STARS) Num_stars = MAX_STARS; required_string("$Ambient light level:"); stuff_int(&pm->ambient_light_level); if (pm->ambient_light_level == 0) { pm->ambient_light_level = DEFAULT_AMBIENT_LIGHT_LEVEL; } // This should call light_set_ambient() to // set the ambient light Nebula_index = -1; Mission_palette = 1; // neb2 info strcpy_s(Neb2_texture_name, ""); Neb2_poof_flags = ((1<<0) | (1<<1) | (1<<2) | (1<<3) | (1<<4) | (1<<5)); bool nebula = false; if (optional_string("+Neb2:")) { nebula = true; stuff_string(Neb2_texture_name, F_NAME, MAX_FILENAME_LEN); } else if (optional_string("+Neb2Color:")) { nebula = true; int neb_colors[3]; stuff_int_list(neb_colors, 3, RAW_INTEGER_TYPE); Neb2_fog_color[0] = (ubyte)neb_colors[0]; Neb2_fog_color[1] = (ubyte)neb_colors[1]; Neb2_fog_color[2] = (ubyte)neb_colors[2]; } if (nebula) { required_string("+Neb2Flags:"); stuff_int(&Neb2_poof_flags); // initialize neb effect. its gross to do this here, but Fred is dumb so I have no choice ... :( if(Fred_running && (pm->flags[Mission::Mission_Flags::Fullneb])){ neb2_post_level_init(); } } if(pm->flags[Mission::Mission_Flags::Fullneb]){ // no regular nebula stuff nebula_close(); } else { if (optional_string("+Nebula:")) { stuff_string(str, F_NAME, MAX_FILENAME_LEN); // parse the proper nebula type (full or not) for (z=0; z<NUM_NEBULAS; z++){ if(pm->flags[Mission::Mission_Flags::Fullneb]){ if (!stricmp(str, Neb2_filenames[z])) { Nebula_index = z; break; } } else { if (!stricmp(str, Nebula_filenames[z])) { Nebula_index = z; break; } } } if (z == NUM_NEBULAS) WarningEx(LOCATION, "Mission %s\nUnknown nebula %s!", pm->name, str); if (optional_string("+Color:")) { stuff_string(str, F_NAME, MAX_FILENAME_LEN); for (z=0; z<NUM_NEBULA_COLORS; z++){ if (!stricmp(str, Nebula_colors[z])) { Mission_palette = z; break; } } } if (z == NUM_NEBULA_COLORS) WarningEx(LOCATION, "Mission %s\nUnknown nebula color %s!", pm->name, str); if (optional_string("+Pitch:")){ stuff_int(&Nebula_pitch); } else { Nebula_pitch = 0; } if (optional_string("+Bank:")){ stuff_int(&Nebula_bank); } else { Nebula_bank = 0; } if (optional_string("+Heading:")){ stuff_int(&Nebula_heading); } else { Nebula_heading = 0; } } if (Nebula_index >= 0){ nebula_init(Nebula_filenames[Nebula_index], Nebula_pitch, Nebula_bank, Nebula_heading); } else { nebula_close(); } } // Goober5000 while (optional_string("$Bitmap List:") || check_for_string("$Sun:") || check_for_string("$Starbitmap:")) { Backgrounds.emplace_back(); parse_one_background(&Backgrounds.back()); } // Goober5000 stars_load_first_valid_background(); if (optional_string("$Environment Map:")) { stuff_string(pm->envmap_name, F_NAME, MAX_FILENAME_LEN); } // bypass spurious stuff from e.g. FS1 missions skip_to_start_of_string("#"); } void parse_asteroid_fields(mission *pm) { int i, count, subtype; Assert(pm != NULL); for (i=0; i<MAX_ASTEROID_FIELDS; i++) Asteroid_field.num_initial_asteroids = 0; i = 0; count = 0; if (!optional_string("#Asteroid Fields")) return; while (required_string_either("#", "$density:")) { float speed, density; int type; Assert(i < 1); required_string("$Density:"); stuff_float(&density); Asteroid_field.num_initial_asteroids = (int) density; Asteroid_field.field_type = FT_ACTIVE; if (optional_string("+Field Type:")) { stuff_int( &type ); Asteroid_field.field_type = (field_type_t)type; } Asteroid_field.debris_genre = DG_ASTEROID; if (optional_string("+Debris Genre:")) { stuff_int( &type ); Asteroid_field.debris_genre = (debris_genre_t)type; } Asteroid_field.field_debris_type[0] = -1; Asteroid_field.field_debris_type[1] = -1; Asteroid_field.field_debris_type[2] = -1; if (Asteroid_field.debris_genre == DG_SHIP) { if (optional_string("+Field Debris Type:")) { stuff_int(&Asteroid_field.field_debris_type[0]); } if (optional_string("+Field Debris Type:")) { stuff_int(&Asteroid_field.field_debris_type[1]); } if (optional_string("+Field Debris Type:")) { stuff_int(&Asteroid_field.field_debris_type[2]); } } else { // debris asteroid if (optional_string("+Field Debris Type:")) { stuff_int(&subtype); Asteroid_field.field_debris_type[subtype] = 1; count++; } if (optional_string("+Field Debris Type:")) { stuff_int(&subtype); Asteroid_field.field_debris_type[subtype] = 1; count++; } if (optional_string("+Field Debris Type:")) { stuff_int(&subtype); Asteroid_field.field_debris_type[subtype] = 1; count++; } } bool invalid_asteroids = false; for (int& ast_type : Asteroid_field.field_debris_type) { if (ast_type >= (int)Asteroid_info.size()) { invalid_asteroids = true; ast_type = -1; } } if (invalid_asteroids) Warning(LOCATION, "The Asteroid field contains invalid entries!"); // backward compatibility if ( (Asteroid_field.debris_genre == DG_ASTEROID) && (count == 0) ) { Asteroid_field.field_debris_type[0] = 0; } required_string("$Average Speed:"); stuff_float(&speed); vm_vec_rand_vec_quick(&Asteroid_field.vel); vm_vec_scale(&Asteroid_field.vel, speed); Asteroid_field.speed = speed; required_string("$Minimum:"); stuff_vec3d(&Asteroid_field.min_bound); required_string("$Maximum:"); stuff_vec3d(&Asteroid_field.max_bound); vec3d a_rad; vm_vec_sub(&a_rad, &Asteroid_field.max_bound, &Asteroid_field.min_bound); vm_vec_scale(&a_rad, 0.5f); float b_rad = vm_vec_mag(&a_rad); Asteroid_field.bound_rad = MAX(3000.0f, b_rad); if (optional_string("+Inner Bound:")) { Asteroid_field.has_inner_bound = 1; required_string("$Minimum:"); stuff_vec3d(&Asteroid_field.inner_min_bound); required_string("$Maximum:"); stuff_vec3d(&Asteroid_field.inner_max_bound); } else { Asteroid_field.has_inner_bound = 0; } i++; } } void parse_variables() { int i, j, num_variables = 0; if (! optional_string("#Sexp_variables") ) { return; } else { num_variables = stuff_sexp_variable_list(); } // yeesh - none of this should be done in FRED :) // It shouldn't be done for missions in the tecroom either. They should default to whatever FRED set them to if ( Fred_running || !(Game_mode & GM_CAMPAIGN_MODE) ) { return; } // Goober5000 - now set the default value, if it's a variable saved on mission progress // loop through the current mission's variables for (j = 0; j < num_variables; j++) { // check against existing variables for (auto& current_pv : Campaign.persistent_variables) { // if the active mission has a variable with the same name as a variable saved to the campaign file override its initial value with the previous mission's value if ( !stricmp(Sexp_variables[j].variable_name, current_pv.variable_name) ) { // if this is an eternal that shares the same name as a non-eternal warn but do nothing if (Sexp_variables[j].type & SEXP_VARIABLE_SAVE_TO_PLAYER_FILE) { error_display(0, "Variable %s is marked eternal but has the same name as another persistent variable. One of these should be renamed to avoid confusion", Sexp_variables[j].text); } else if (Sexp_variables[j].type & SEXP_VARIABLE_IS_PERSISTENT) { Sexp_variables[j].type = current_pv.type; strcpy_s(Sexp_variables[j].text, current_pv.text); break; } else { error_display(0, "Variable %s has the same name as another persistent variable. One of these should be renamed to avoid confusion", Sexp_variables[j].text); } } } } // next, see if any eternal variables are set loop through the current mission's variables for (j = 0; j < num_variables; j++) { // check against existing variables for (i = 0; i < (int)Player->variables.size(); i++) { // if the active mission has a variable with the same name as a variable saved to the player file override its initial value with the previous mission's value if ( !stricmp(Sexp_variables[j].variable_name, Player->variables[i].variable_name) ) { if (Sexp_variables[j].type & SEXP_VARIABLE_IS_PERSISTENT) { // if the variable in the player file is marked as eternal but the version in the mission file is not, we assume that the player file one is rogue // and use the one in the mission file instead. if ((Player->variables[i].type & SEXP_VARIABLE_SAVE_TO_PLAYER_FILE) && !(Sexp_variables[j].type & SEXP_VARIABLE_SAVE_TO_PLAYER_FILE)) { break; } // replace the default values with the ones saved to the player file Sexp_variables[j].type = Player->variables[i].type; strcpy_s(Sexp_variables[j].text, Player->variables[i].text); /* // check that the eternal flag has been set. Players using a player file from before the eternal flag was added may have old player-persistent variables // these should be converted to non-eternals if (!(Player->variables[i].type & SEXP_VARIABLE_SAVE_TO_PLAYER_FILE)) { Sexp_variables[j].type &= ~SEXP_VARIABLE_SAVE_TO_PLAYER_FILE; } */ break; } else { error_display(0, "Variable %s has the same name as an eternal variable. One of these should be renamed to avoid confusion", Sexp_variables[j].variable_name); } } } } } bool parse_mission(mission *pm, int flags) { int saved_warning_count = Global_warning_count; int saved_error_count = Global_error_count; int i; Warned_about_team_out_of_range = false; waypoint_parse_init(); Player_starts = Num_cargo = Num_goals = Num_wings = 0; Player_start_shipnum = -1; *Player_start_shipname = 0; // make the string 0 length for checking later clear_texture_replacements(); // initialize the initially_docked array. for ( i = 0; i < MAX_SHIPS; i++ ) { Initially_docked[i].docker[0] = '\0'; Initially_docked[i].dockee[0] = '\0'; Initially_docked[i].docker_point[0] = '\0'; Initially_docked[i].dockee_point[0] = '\0'; } Total_initially_docked = 0; list_init(&Ship_arrival_list); // init list for arrival ships parse_init(); Subsys_index = 0; Subsys_status_size = 0; if (Subsys_status != NULL) { vm_free( Subsys_status ); Subsys_status = NULL; } parse_mission_info(pm); Current_file_checksum = netmisc_calc_checksum(pm,MISSION_CHECKSUM_SIZE); if (flags & MPF_ONLY_MISSION_INFO) return true; parse_plot_info(pm); parse_variables(); parse_briefing_info(pm); // TODO: obsolete code, keeping so we don't obsolete existing mission files parse_cutscenes(pm); parse_fiction(pm); parse_cmd_briefs(pm); parse_briefing(pm, flags); parse_debriefing_new(pm); parse_player_info(pm); parse_objects(pm, flags); parse_wings(pm); parse_events(pm); parse_goals(pm); parse_waypoints_and_jumpnodes(pm); parse_messages(pm, flags); parse_reinforcements(pm); parse_bitmaps(pm); parse_asteroid_fields(pm); parse_music(pm, flags); // if we couldn't load some mod data if ((Num_unknown_ship_classes > 0) || ( Num_unknown_loadout_classes > 0 )) { // if running on standalone server, just print to the log if (Game_mode & GM_STANDALONE_SERVER) { mprintf(("Warning! Could not load %d ship classes!\n", Num_unknown_ship_classes)); return false; } // don't do this in FRED; we will display a separate popup else if (!Fred_running) { // build up the prompt... SCP_string text; if (Num_unknown_ship_classes > 0) { sprintf(text, "Warning!\n\nFreeSpace was unable to find %d ship class%s while loading this mission. This can happen if you try to play a %s that is incompatible with the current mod.\n\n", Num_unknown_ship_classes, (Num_unknown_ship_classes > 1) ? "es" : "", (Game_mode & GM_CAMPAIGN_MODE) ? "campaign" : "mission"); } else { sprintf(text, "Warning!\n\nFreeSpace was unable to find %d weapon class%s while loading this mission. This can happen if you try to play a %s that is incompatible with the current mod.\n\n", Num_unknown_loadout_classes, (Num_unknown_loadout_classes > 1) ? "es" : "", (Game_mode & GM_CAMPAIGN_MODE) ? "campaign" : "mission"); } if (Game_mode & GM_CAMPAIGN_MODE) { text += "(The current campaign is \""; text += Campaign.name; } else { text += "(The current mission is \""; text += pm->name; } text += "\", and the current mod is \""; if (Cmdline_mod == NULL || *Cmdline_mod == 0) { text += "<retail default> "; } else { for (char *mod_token = Cmdline_mod; *mod_token != '\0'; mod_token += strlen(mod_token) + 1) { text += mod_token; text += " "; } } text.erase(text.length() - 1); // trim last space text += "\".)\n\n You can continue to load the mission, but it is quite likely that you will encounter a large number of mysterious errors. It is recommended that you either select a "; text += (Game_mode & GM_CAMPAIGN_MODE) ? "campaign" : "mission"; text += " that is compatible with your current mod, or else exit FreeSpace and select a different mod.\n\n"; text += "Do you want to continue to load the mission?"; // now display the popup int popup_rval = popup(PF_TITLE_BIG | PF_TITLE_RED, 2, POPUP_NO, POPUP_YES, text.c_str()); if (popup_rval == 0) { return false; } } } if (!post_process_mission()) { return false; } if ((saved_warning_count - Global_warning_count) > 10 || (saved_error_count - Global_error_count) > 0) { char text[512]; sprintf(text, "Warning!\n\nThe current mission has generated %d warnings and/or errors during load. These are usually caused by corrupted ship models or syntax errors in the mission file. While FreeSpace Open will attempt to compensate for these issues, it cannot guarantee a trouble-free gameplay experience. Source Code Project staff cannot provide assistance or support for these problems, as they are caused by the mission's data files, not FreeSpace Open's source code.", (saved_warning_count - Global_warning_count) + (saved_error_count - Global_error_count)); popup(PF_TITLE_BIG | PF_TITLE_RED | PF_USE_AFFIRMATIVE_ICON | PF_NO_NETWORKING, 1, POPUP_OK, text); } log_printf(LOGFILE_EVENT_LOG, "Mission %s loaded.\n", pm->name); // success return true; } bool post_process_mission() { int i; int indices[MAX_SHIPS], objnum; ship_weapon *swp; ship_obj *so; // Goober5000 - must be done before all other post processing post_process_ships_wings(); // the player_start_shipname had better exist at this point! Player_start_shipnum = ship_name_lookup( Player_start_shipname ); Assert( Player_start_shipnum != -1 ); Player_start_pobject = mission_parse_get_parse_object( Player_start_shipname ); Assert( Player_start_pobject != NULL ); // Assign objnum, shipnum, etc. to the player structure objnum = Ships[Player_start_shipnum].objnum; Player_obj = &Objects[objnum]; if (!Fred_running){ Player->objnum = objnum; } Player_obj->flags.set(Object::Object_Flags::Player_ship); // make this object a player controlled ship. Player_ship = &Ships[Player_start_shipnum]; Player_ai = &Ai_info[Player_ship->ai_index]; Player_ai->targeted_subsys = NULL; Player_ai->targeted_subsys_parent = -1; // determine if player start has initial velocity and set forward cruise percent to relect this // this should check prev_ramp_vel because that is in local coordinates --wookieejedi if ( Player_obj->phys_info.prev_ramp_vel.xyz.z > 0.0f ) Player->ci.forward_cruise_percent = Player_obj->phys_info.prev_ramp_vel.xyz.z / Player_ship->current_max_speed * 100.0f; // set up wing indexes for (i = 0; i < MAX_STARTING_WINGS; i++ ) { Starting_wings[i] = wing_name_lookup(Starting_wing_names[i], 1); } for (i = 0; i < MAX_SQUADRON_WINGS; i++ ) { Squadron_wings[i] = wing_name_lookup(Squadron_wing_names[i], 1); } for (i = 0; i < MAX_TVT_WINGS; i++ ) { TVT_wings[i] = wing_name_lookup(TVT_wing_names[i], 1); } // when TVT, hack starting wings to be team wings if(MULTI_TEAM){ Assert(MAX_TVT_WINGS <= MAX_STARTING_WINGS); for (i=0; i<MAX_STARTING_WINGS; i++) { if (i<MAX_TVT_WINGS) Starting_wings[i] = TVT_wings[i]; else Starting_wings[i] = -1; } } init_ai_system(); waypoint_create_game_objects(); // Goober5000 - this needs to be called only once after parsing of objects and wings is complete // (for individual invalidation, see mission_parse_mark_non_arrival) mission_parse_mark_non_arrivals(); // deal with setting up arrival location for all ships. Must do this now after all ships are created mission_parse_set_arrival_locations(); // clear out information about arriving support ships Arriving_support_ship = NULL; Num_arriving_repair_targets = 0; // convert all ship name indices to ship indices now that mission has been loaded if (Fred_running) { for (i=0; i<Num_parse_names; i++) { indices[i] = ship_name_lookup(Parse_names[i], 1); if (indices[i] < 0) Warning(LOCATION, "Ship name \"%s\" referenced, but this ship doesn't exist", Parse_names[i]); } for (i=0; i<MAX_SHIPS; i++) { if ((Ships[i].objnum >= 0) && (Ships[i].arrival_anchor >= 0) && (Ships[i].arrival_anchor < SPECIAL_ARRIVAL_ANCHOR_FLAG)) Ships[i].arrival_anchor = indices[Ships[i].arrival_anchor]; if ( (Ships[i].objnum >= 0) && (Ships[i].departure_anchor >= 0) ) Ships[i].departure_anchor = indices[Ships[i].departure_anchor]; } for (i=0; i<MAX_WINGS; i++) { if (Wings[i].wave_count && (Wings[i].arrival_anchor >= 0) && (Wings[i].arrival_anchor < SPECIAL_ARRIVAL_ANCHOR_FLAG)) Wings[i].arrival_anchor = indices[Wings[i].arrival_anchor]; if (Wings[i].wave_count && (Wings[i].departure_anchor >= 0) ) Wings[i].departure_anchor = indices[Wings[i].departure_anchor]; } } // before doing anything else, we must validate all of the sexpressions that were loaded into the mission. // Loop through the Sexp_nodes array and send the top level functions to the check_sexp_syntax parser for (i = 0; i < Num_sexp_nodes; i++) { if (is_sexp_top_level(i) && (!Fred_running || (i != Sexp_clipboard))) { int result, bad_node, op; op = get_operator_index(i); Assert(op != -1); // need to make sure it is an operator before we treat it like one.. result = check_sexp_syntax( i, query_operator_return_type(op), 1, &bad_node); // entering this if statement will result in program termination!!!!! // print out an error based on the return value from check_sexp_syntax() // G5K: now entering this statement simply aborts the mission load if ( result ) { SCP_string sexp_str; SCP_string error_msg; convert_sexp_to_string(sexp_str, i, SEXP_ERROR_CHECK_MODE); truncate_message_lines(sexp_str, 30); sprintf(error_msg, "%s.\n\nIn sexpression: %s\n(Error appears to be: %s)", sexp_error_message(result), sexp_str.c_str(), Sexp_nodes[bad_node].text); Warning(LOCATION, "%s", error_msg.c_str()); // syntax errors are recoverable in Fred but not FS if (!Fred_running) { return false; } } } } // multiplayer missions are handled just before mission start if (!(Game_mode & GM_MULTIPLAYER) ){ ai_post_process_mission(); } // first we need to clear out the counts for this mission ship_clear_ship_type_counts(); // we must also count all of the ships of particular types. We count all of the ships that do not have // their SF_IGNORE_COUNT flag set. We don't count ships in wings when the equivalent wing flag is set. // in counting ships in wings, we increment the count by the wing's wave count to account for everyone. for ( so = GET_FIRST(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so) ) { int num, shipnum; shipnum = Objects[so->objnum].instance; // pass over non-ship objects and player ship objects if ( Ships[shipnum].objnum == -1 || (Objects[Ships[shipnum].objnum].flags[Object::Object_Flags::Player_ship]) ) continue; if ( Ships[shipnum].flags[Ship::Ship_Flags::Ignore_count] ) continue; if ( (Ships[shipnum].wingnum != -1) && (Wings[Ships[shipnum].wingnum].flags[Ship::Wing_Flags::Ignore_count]) ) continue; num = 1; ship_add_ship_type_count( Ships[shipnum].ship_info_index, num ); } // now go through the list of ships yet to arrive for (p_object *p_objp = GET_FIRST(&Ship_arrival_list); p_objp != END_OF_LIST(&Ship_arrival_list); p_objp = GET_NEXT(p_objp)) { int num; // go through similar motions as above if ( p_objp->flags[Mission::Parse_Object_Flags::SF_Ignore_count] ) continue; if ( (p_objp->wingnum != -1) && (Wings[p_objp->wingnum].flags[Ship::Wing_Flags::Ignore_count]) ) continue; if ( p_objp->wingnum == -1 ) num = 1; else num = Wings[p_objp->wingnum].num_waves - 1; // subtract one since we already counted the first wave ship_add_ship_type_count( p_objp->ship_class, num ); } // set player weapons that are selected by default // AL 09/17/97: I added this code to select the first primary/secondary weapons, // since I noticed the player ship sometimes doesn't get default weapons selected // DB: modified 4/23/98 to take multiplayer into account. Under certain circumstances, multiplayer netplayer ships // had their current_primary_bank and current_secondary_bank set to -1 (from ship_set()) and left there since // Player_ship is not the only one we need to need about. for ( so = GET_FIRST(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so) ) { ship *shipp = &Ships[Objects[so->objnum].instance]; // don't process non player wing ships if ( !(shipp->flags[Ship::Ship_Flags::From_player_wing] ) ) continue; swp = &shipp->weapons; if ( swp->num_primary_banks > 0 ) { swp->current_primary_bank = 0; // currently selected primary bank } if ( swp->num_secondary_banks > 0 ) { swp->current_secondary_bank = 0; // currently selected secondary bank } } ets_init_ship(Player_obj); // init ETS data for the player // put the timestamp stuff here for now Mission_arrival_timestamp = timestamp( ARRIVAL_TIMESTAMP ); Mission_departure_timestamp = timestamp( DEPARTURE_TIMESTAMP ); Mission_end_time = -1; Allow_arrival_music_timestamp=timestamp(0); Allow_arrival_message_timestamp=timestamp(0); Arrival_message_delay_timestamp = timestamp(-1); int idx; for(idx=0; idx<2; idx++){ Allow_arrival_music_timestamp_m[idx]=timestamp(0); Allow_arrival_message_timestamp_m[idx]=timestamp(0); Arrival_message_delay_timestamp_m[idx] = timestamp(-1); } if(Game_mode & GM_MULTIPLAYER){ multi_respawn_build_points(); } // maybe reset hotkey defaults when loading new mission if ( Last_file_checksum != Current_file_checksum ){ mission_hotkey_reset_saved(); } Last_file_checksum = Current_file_checksum; // success return true; } int get_mission_info(const char *filename, mission *mission_p, bool basic) { char real_fname[MAX_FILENAME_LEN]; strncpy(real_fname, filename, MAX_FILENAME_LEN-1); real_fname[sizeof(real_fname)-1] = '\0'; char *p = strrchr(real_fname, '.'); if (p) *p = 0; // remove any extension strcat_s(real_fname, FS_MISSION_FILE_EXT); // append mission extension int filelength; // if mission_p is NULL, make it point to The_mission if ( mission_p == NULL ) mission_p = &The_mission; CFILE *ftemp = cfopen(real_fname, "rt"); if (!ftemp) { return -1; } // 7/9/98 -- MWA -- check for 0 length file. filelength = cfilelength(ftemp); cfclose(ftemp); if (filelength == 0) { return -1; } try { read_file_text(real_fname, CF_TYPE_MISSIONS); mission_p->Reset(); parse_init(basic); parse_mission_info(mission_p, basic); } catch (const parse::ParseException& e) { mprintf(("MISSIONS: Unable to parse '%s'! Error message = %s.\n", real_fname, e.what())); return -1; } return 0; } /** * Initialize the mission parse process. */ void parse_init(bool basic) { reset_parse(); // if we just want basic info then we don't need some of this initialization if (!basic) { for (int i = 0; i < MAX_CARGO; i++) Cargo_names[i] = Cargo_names_buf[i]; // make a pointer array for compatibility ai_clear_goal_target_names(); // if we are just wanting basic info then we shouldn't need sexps // (prevents memory fragmentation with the now dynamic Sexp_nodes[]) init_sexp(); } } // main parse routine for parsing a mission. The default parameter flags tells us which information // to get when parsing the mission. 0 means get everything (default). Other flags just gets us basic // info such as game type, number of players etc. bool parse_main(const char *mission_name, int flags) { int i; bool rval; // reset parse error stuff Num_unknown_ship_classes = 0; Num_unknown_weapon_classes = 0; Num_unknown_loadout_classes = 0; // fill in Ship_class_names array with the names from the ship_info struct; Num_parse_names = 0; Num_path_restrictions = 0; Assert(Ship_info.size() <= MAX_SHIP_CLASSES); i = 0; for (auto it = Ship_info.begin(); it != Ship_info.end(); i++, ++it) Ship_class_names[i] = it->name; do { // don't do this for imports if (!(flags & MPF_IMPORT_FSM)) { CFILE *ftemp = cfopen(mission_name, "rt", CFILE_NORMAL, CF_TYPE_MISSIONS); // fail situation. if (!ftemp) { if (!Fred_running) Error( LOCATION, "Couldn't open mission '%s'\n", mission_name ); Current_file_length = -1; Current_file_checksum = 0; rval = false; break; } Current_file_length = cfilelength(ftemp); cfclose(ftemp); } try { // import? if (flags & MPF_IMPORT_FSM) { read_file_text(mission_name, CF_TYPE_ANY); convertFSMtoFS2(); } else { read_file_text(mission_name, CF_TYPE_MISSIONS); } The_mission.Reset(); rval = parse_mission(&The_mission, flags); display_parse_diagnostics(); } catch (const parse::ParseException& e) { mprintf(("MISSIONS: Unable to parse '%s'! Error message = %s.\n", mission_name, e.what())); rval = false; break; } } while (0); if (!Fred_running) strcpy_s(Mission_filename, mission_name); return rval; } // Note, this is currently only called from game_shutdown() void mission_parse_close() { // free subsystems if (Subsys_status != NULL) { vm_free(Subsys_status); Subsys_status = NULL; } // the destructor for each p_object will clear its dock list Parse_objects.clear(); } /** * Sets the arrival location of the ships in wingp. * * @param wingp Pointer to wing * @param num_to_set The threshold value for wings may have us create more ships in the wing when there are still some remaining */ void mission_set_wing_arrival_location( wing *wingp, int num_to_set ) { int index; int anchor_objnum = -1; // get the starting index into the ship_index array of the first ship whose location we need set. index = wingp->current_count - num_to_set; if ( (wingp->arrival_location == ARRIVE_FROM_DOCK_BAY) || (wingp->arrival_location == ARRIVE_AT_LOCATION) ) { while ( index < wingp->current_count ) { object *objp; objp = &Objects[Ships[wingp->ship_index[index]].objnum]; anchor_objnum = mission_set_arrival_location(wingp->arrival_anchor, wingp->arrival_location, wingp->arrival_distance, OBJ_INDEX(objp), wingp->arrival_path_mask, NULL, NULL); index++; } } else { object *leader_objp; vec3d pos; matrix orient; int wing_index; // wing is not arriving from a docking bay -- possibly move them based on arriving near // or in front of some other ship. index = wingp->current_count - num_to_set; leader_objp = &Objects[Ships[wingp->ship_index[index]].objnum]; anchor_objnum = mission_set_arrival_location(wingp->arrival_anchor, wingp->arrival_location, wingp->arrival_distance, OBJ_INDEX(leader_objp), wingp->arrival_path_mask, &pos, &orient); if (anchor_objnum != -1) { // modify the remaining ships created index++; wing_index = 1; while ( index < wingp->current_count ) { object *objp; objp = &Objects[Ships[wingp->ship_index[index]].objnum]; // change the position of the next ships in the wing. Use the cool function in AiCode.cpp which // Mike K wrote to give new positions to the wing members. get_absolute_wing_pos( &objp->pos, leader_objp, WING_INDEX(wingp), wing_index++, false); memcpy( &objp->orient, &orient, sizeof(matrix) ); index++; } } } if (Game_mode & GM_IN_MISSION) { for ( index = wingp->current_count - num_to_set; index < wingp->current_count; index ++ ) { object *objp = &Objects[Ships[wingp->ship_index[index]].objnum]; object *anchor_objp = (anchor_objnum >= 0) ? &Objects[anchor_objnum] : nullptr; Script_system.SetHookObjects(2, "Ship", objp, "Parent", anchor_objp); Script_system.RunCondition(CHA_ONSHIPARRIVE, objp); Script_system.RemHookVars({"Ship", "Parent"}); if (wingp->arrival_location != ARRIVE_FROM_DOCK_BAY) { shipfx_warpin_start(objp); } } } } /** * Called after a mission is parsed to set the arrival locations of all ships in the * mission to the apprioriate spot. Mainly needed because ships might be in dock bays to start * the mission, so their AI mode must be set appropriately. */ void mission_parse_set_arrival_locations() { int i; object *objp; if ( Fred_running ) return; obj_merge_created_list(); for ( objp = GET_FIRST(&obj_used_list); objp != END_OF_LIST(&obj_used_list); objp = GET_NEXT(objp) ) { ship *shipp; if ( objp->type != OBJ_SHIP ) continue; shipp = &Ships[objp->instance]; // if the ship is in a wing -- ignore the info and let the wing info handle it if ( shipp->wingnum != -1 ) continue; // call function to set arrival location for this ship. mission_set_arrival_location( shipp->arrival_anchor, shipp->arrival_location, shipp->arrival_distance, OBJ_INDEX(objp), shipp->arrival_path_mask, NULL, NULL); } // do the wings for ( i = 0; i < Num_wings; i++ ) { // if wing has no ships, then don't process it. if ( Wings[i].current_count == 0 ) continue; mission_set_wing_arrival_location( &Wings[i], Wings[i].current_count ); } } // Goober5000 bool sexp_is_locked_false(int node) { // dunno why these are different, but they are if (Fred_running) return (node == Locked_sexp_false); else return (Sexp_nodes[node].value == SEXP_KNOWN_FALSE); } void set_cue_to_false(int *cue) { free_sexp2(*cue); *cue = Locked_sexp_false; } // function to set the arrival cue of a ship to false void reset_arrival_to_false(p_object *pobjp, bool reset_wing) { // falsify the ship cue mprintf(("Setting arrival cue of ship %s to false for initial docking purposes.\n", pobjp->name)); set_cue_to_false(&pobjp->arrival_cue); // falsify the wing cue and all ships in that wing if (reset_wing && pobjp->wingnum >= 0) { wing *wingp = &Wings[pobjp->wingnum]; mprintf(("Setting arrival cue of wing %s to false for initial docking purposes.\n", wingp->name)); set_cue_to_false(&wingp->arrival_cue); for (SCP_vector<p_object>::iterator ii = Parse_objects.begin(); ii != Parse_objects.end(); ++ii) { if ((&(*ii) != pobjp) && (ii->wingnum == pobjp->wingnum)) reset_arrival_to_false(&(*ii), false); } } } /** * In both retail and SCP, the dock "leader" is defined as the only guy in his * group with a non-false arrival cue. * * If we are forcing a leader, that means *none* of the ships in this dock group * have a non-false arrival cue, so we just need to pick one */ void parse_object_mark_dock_leader_sub(p_object *pobjp, p_dock_function_info *infop, bool force_a_leader) { int cue_to_check; // if this guy is part of a wing, he uses his wing's arrival cue if (pobjp->wingnum >= 0) { cue_to_check = Wings[pobjp->wingnum].arrival_cue; } // check the object's arrival cue else { cue_to_check = pobjp->arrival_cue; } // is he a leader (using the definition above)? if (!sexp_is_locked_false(cue_to_check) || force_a_leader) { p_object *existing_leader; // increment number of leaders found infop->maintained_variables.int_value++; // see if we already found a leader existing_leader = infop->maintained_variables.objp_value; if (existing_leader != NULL) { // keep existing leader if he has a higher priority than us if (ship_class_compare(pobjp->ship_class, existing_leader->ship_class) >= 0) { // set my arrival cue to false reset_arrival_to_false(pobjp, true); return; } // otherwise, unmark the existing leader and set his arrival cue to false existing_leader->flags.remove(Mission::Parse_Object_Flags::SF_Dock_leader); reset_arrival_to_false(existing_leader, true); } // mark and save me as the leader pobjp->flags.set(Mission::Parse_Object_Flags::SF_Dock_leader); infop->maintained_variables.objp_value = pobjp; } } void parse_object_mark_dock_leader_helper(p_object *pobjp, p_dock_function_info *infop) { parse_object_mark_dock_leader_sub(pobjp, infop, false); } void parse_object_choose_arbitrary_dock_leader_helper(p_object *pobjp, p_dock_function_info *infop) { parse_object_mark_dock_leader_sub(pobjp, infop, true); } // Goober5000 void parse_object_set_handled_flag_helper(p_object *pobjp, p_dock_function_info * /*infop*/) { pobjp->flags.set(Mission::Parse_Object_Flags::Already_handled); } // Goober5000 void parse_object_clear_handled_flag_helper(p_object *pobjp, p_dock_function_info * /*infop*/) { pobjp->flags.remove(Mission::Parse_Object_Flags::Already_handled); } // Goober5000 void parse_object_clear_all_handled_flags() { // clear flag for all ships for (SCP_vector<p_object>::iterator ii = Parse_objects.begin(); ii != Parse_objects.end(); ++ii) { p_object *pobjp = &(*ii); p_dock_function_info dfi; // since we're going through all objects, this object may not be docked if (!object_is_docked(pobjp)) continue; // has this object (by extension, this group of docked objects) been cleared already? if (!(pobjp->flags[Mission::Parse_Object_Flags::Already_handled])) continue; // clear the handled flag for this group dock_evaluate_all_docked_objects(pobjp, &dfi, parse_object_clear_handled_flag_helper); } } // Goober5000 // This function iterates through the Initially_docked array and builds the dock trees // for each parse object. This can only be done after all objects and wings have been parsed. void mission_parse_set_up_initial_docks() { int i; // build trees for (i = 0; i < Total_initially_docked; i++) { char *docker_point, *dockee_point; p_object *docker, *dockee; // resolve the docker and dockee docker = mission_parse_get_parse_object(Initially_docked[i].docker); if (docker == NULL) { Warning(LOCATION, "Could not resolve initially docked object '%s'!", Initially_docked[i].docker); continue; } dockee = mission_parse_get_parse_object(Initially_docked[i].dockee); if (dockee == NULL) { Warning(LOCATION, "Could not resolve docking target '%s' of initially docked object '%s'!", Initially_docked[i].dockee, Initially_docked[i].docker); continue; } // skip docking if they're already docked // (in FSO, we list all initially docked pairs for all ships, // so we end up with twice as many docking entries as we need) if (dock_check_find_direct_docked_object(docker, dockee)) continue; // resolve the dockpoints docker_point = Initially_docked[i].docker_point; dockee_point = Initially_docked[i].dockee_point; // docker point in use? if (dock_find_object_at_dockpoint(docker, docker_point) != NULL) { Warning(LOCATION, "Trying to initially dock '%s' and '%s', but the former's dockpoint is already in use!", Initially_docked[i].docker, Initially_docked[i].dockee); continue; } // dockee point in use? if (dock_find_object_at_dockpoint(dockee, dockee_point) != NULL) { Warning(LOCATION, "Trying to initially dock '%s' and '%s', but the latter's dockpoint is already in use!", Initially_docked[i].docker, Initially_docked[i].dockee); continue; } dock_dock_objects(docker, docker_point, dockee, dockee_point); } // now resolve the leader of each tree for (SCP_vector<p_object>::iterator ii = Parse_objects.begin(); ii != Parse_objects.end(); ++ii) { p_object *pobjp = &(*ii); p_dock_function_info dfi; // since we're going through all objects, this object may not be docked if (!object_is_docked(pobjp)) continue; // has this object (by extension, this group of docked objects) been handled already? if (pobjp->flags[Mission::Parse_Object_Flags::Already_handled]) continue; // find the dock leader(s) dock_evaluate_all_docked_objects(pobjp, &dfi, parse_object_mark_dock_leader_helper); // display an error if necessary if (dfi.maintained_variables.int_value == 0) { Warning(LOCATION, "In the docking group containing %s, every ship has an arrival cue set to false. The group will not appear in-mission!\n", pobjp->name); // for FRED, we must arbitrarily choose a dock leader, otherwise the entire docked group will not be loaded if (Fred_running) dock_evaluate_all_docked_objects(pobjp, &dfi, parse_object_choose_arbitrary_dock_leader_helper); } else if (dfi.maintained_variables.int_value > 1) { Warning(LOCATION, "In the docking group containing %s, there is more than one ship with a non-false arrival cue! There can only be one such ship. Setting all arrival cues except %s to false...\n", dfi.maintained_variables.objp_value->name, dfi.maintained_variables.objp_value->name); } // clear dfi stuff dfi.maintained_variables.int_value = 0; dfi.maintained_variables.objp_value = NULL; // set the handled flag for this group dock_evaluate_all_docked_objects(pobjp, &dfi, parse_object_set_handled_flag_helper); } // now clear the handled flags parse_object_clear_all_handled_flags(); } /** * Returns true or false if the given mission support multiplayers */ int mission_parse_is_multi(const char *filename, char *mission_name) { int game_type; int filelength; CFILE *ftemp; // new way of getting information. Open the file, and just get the name and the game_type flags. // return the flags if a multiplayer mission ftemp = cfopen(filename, "rt"); if (!ftemp) return 0; // 7/9/98 -- MWA -- check for 0 length file. filelength = cfilelength(ftemp); cfclose(ftemp); if ( filelength == 0 ) return 0; game_type = 0; do { try { read_file_text(filename, CF_TYPE_MISSIONS); reset_parse(); if (skip_to_string("$Name:") != 1) { nprintf(("Network", "Unable to process %s because we couldn't find $Name:", filename)); break; } stuff_string(mission_name, F_NAME, NAME_LENGTH); if (skip_to_string("+Game Type Flags:") != 1) { nprintf(("Network", "Unable to process %s because we couldn't find +Game Type Flags:\n", filename)); break; } stuff_int(&game_type); } catch (const parse::ParseException& e) { mprintf(("MISSIONS: Unable to parse '%s'! Error message = %s.\n", filename, e.what())); break; } } while (0); return (game_type & MISSION_TYPE_MULTI) ? game_type : 0; } /** * Called to retrieve useful information about a mission. * * We will get the name, description, and number of players for a mission. Probably used for multiplayer only? * The calling function can use the information in The_mission to get the name/description of the mission * if needed. */ int mission_parse_get_multi_mission_info( const char *filename ) { if ( get_mission_info(filename, &The_mission) ) return -1; Assert( The_mission.game_type & MISSION_TYPE_MULTI ); // assume multiplayer only for now? // return the number of parse_players. later, we might want to include (optionally?) the number // of other ships in the main players wing (usually wing 'alpha') for inclusion of number of // players allowed. return The_mission.num_players; } /** * @brief Returns the parse object on the ship arrival list associated with the given name. * @param[in] name The name of the object * @returns The parse object, or NULL if no object with the given name is on the arrival list * @remarks This function is used to determine whether a ship has arrived. Ships on the arrival list * are considered to not be in the game; In order to make respawns work in multiplayer, * player ships (those marked with the P_OF_PLAYER_START flag) are never removed from it. */ p_object *mission_parse_get_arrival_ship(const char *name) { p_object *p_objp; if (name == nullptr) return nullptr; for (p_objp = GET_FIRST(&Ship_arrival_list); p_objp != END_OF_LIST(&Ship_arrival_list); p_objp = GET_NEXT(p_objp)) { if (!stricmp(p_objp->name, name)) { return p_objp; // still on the arrival list } } return nullptr; } /** * @brief Returns the parse object on the ship arrival list associated with the given net signature. * @param[in] net_signature The net signature of the object * @returns The parse object, or NULL if no object with the given signature is on the arrival list * @remarks This function is used to determine whether a ship has arrived. Ships on the arrival list * are considered to not be in the game; In order to make respawns work in multiplayer, * player ships (those marked with the P_OF_PLAYER_START flag) are never removed from it. */ p_object *mission_parse_get_arrival_ship(ushort net_signature) { p_object *p_objp; for (p_objp = GET_FIRST(&Ship_arrival_list); p_objp !=END_OF_LIST(&Ship_arrival_list); p_objp = GET_NEXT(p_objp)) { if (p_objp->net_signature == net_signature) { return p_objp; // still on the arrival list } } return NULL; } /** * Because player ships remain on the arrival list (see parse_wing_create_ships), testing for yet-to-arrive by merely * checking the list will produce false positives for player ships. So this function also checks whether the object was created. */ bool mission_check_ship_yet_to_arrive(const char *name) { p_object *p_objp = mission_parse_get_arrival_ship(name); if (p_objp == nullptr) return false; if (p_objp->created_object != nullptr) return false; return true; } /** * Sets the arrival location of a parse object according to the arrival location of the object. * @return objnum of anchor ship if there is one, -1 otherwise. */ int mission_set_arrival_location(int anchor, int location, int dist, int objnum, int path_mask, vec3d *new_pos, matrix *new_orient) { int shipnum, anchor_objnum; vec3d anchor_pos, rand_vec, new_fvec; matrix orient; if ( location == ARRIVE_AT_LOCATION ) return -1; Assert(anchor >= 0); // this ship might possibly arrive at another location. The location is based on the // proximity of some ship (and some other special tokens) if (anchor & SPECIAL_ARRIVAL_ANCHOR_FLAG) { bool get_players = (anchor & SPECIAL_ARRIVAL_ANCHOR_PLAYER_FLAG) > 0; // filter out iff int iff_index = anchor; iff_index &= ~SPECIAL_ARRIVAL_ANCHOR_FLAG; iff_index &= ~SPECIAL_ARRIVAL_ANCHOR_PLAYER_FLAG; // get ship shipnum = ship_get_random_team_ship(iff_get_mask(iff_index), get_players ? SHIP_GET_ONLY_PLAYERS : SHIP_GET_ANY_SHIP); } // if we didn't find the arrival anchor in the list of special nodes, then do a // ship name lookup on the anchor else { shipnum = ship_name_lookup(Parse_names[anchor]); } // if we didn't get an object from one of the above functions, then make the object // arrive at its placed location if (shipnum < 0) { Assert ( location != ARRIVE_FROM_DOCK_BAY ); // bogus data somewhere!!! get mwa nprintf (("allender", "couldn't find ship for arrival anchor -- using location ship created at")); return -1; } // take the shipnum and get the position. once we have positions, we can determine where // to make this ship appear Assert ( shipnum != -1 ); anchor_objnum = Ships[shipnum].objnum; anchor_pos = Objects[anchor_objnum].pos; // if arriving from docking bay, then set ai mode and call function as per AL's instructions. if ( location == ARRIVE_FROM_DOCK_BAY ) { vec3d pos, fvec; // if we get an error, just let the ship arrive(?) if ( ai_acquire_emerge_path(&Objects[objnum], anchor_objnum, path_mask, &pos, &fvec) == -1 ) { // get MWA or AL -- not sure what to do here when we cannot acquire a path mprintf(("Unable to acquire arrival path on anchor ship %s\n", Ships[shipnum].ship_name)); return -1; } Objects[objnum].pos = pos; vm_vector_2_matrix(&Objects[objnum].orient, &fvec, NULL, NULL); } else { // AL: ensure dist > 0 (otherwise get errors in vecmat) // TODO: maybe set distance to 2x ship radius of ship appearing in front of? if ( dist <= 0 ) { // Goober5000 - default to 100 Warning(LOCATION, "Distance of %d is invalid in mission_set_arrival_location. Defaulting to 100.\n", dist); dist = 100; } // get a vector which is the ships arrival position based on the type of arrival // this ship should have. Arriving near a ship we use a random normalized vector // scaled by the distance given by the designer. Arriving in front of a ship means // entering the battle in the view cone. if ( location == ARRIVE_NEAR_SHIP ) { // get a random vector -- use static randvec if in multiplayer if ( Game_mode & GM_NORMAL ) vm_vec_rand_vec_quick(&rand_vec); else static_randvec( Objects[objnum].net_signature, &rand_vec ); } else if ( location == ARRIVE_IN_FRONT_OF_SHIP ) { vec3d t1, t2, t3; int r1, r2; float x; // cool function by MK to give a reasonable random vector "in front" of a ship // rvec and uvec are the right and up vectors. // If these are not available, this would be an expensive method. x = cosf(fl_radians(45.0f)); if ( Game_mode & GM_NORMAL ) { r1 = Random::flip_coin() ? -1 : 1; r2 = Random::flip_coin() ? -1 : 1; } else { // in multiplayer, use the static rand functions so that all clients can get the // same information. r1 = static_rand(Objects[objnum].net_signature) < STATIC_RAND_MAX / 2 ? -1 : 1; r2 = static_rand(Objects[objnum].net_signature+1) < STATIC_RAND_MAX / 2 ? -1 : 1; } vm_vec_copy_scale(&t1, &(Objects[anchor_objnum].orient.vec.fvec), x); vm_vec_copy_scale(&t2, &(Objects[anchor_objnum].orient.vec.rvec), (1.0f - x) * r1); vm_vec_copy_scale(&t3, &(Objects[anchor_objnum].orient.vec.uvec), (1.0f - x) * r2); vm_vec_add(&rand_vec, &t1, &t2); vm_vec_add2(&rand_vec, &t3); vm_vec_normalize(&rand_vec); } // add in the radius of the two ships involved. This will make the ship arrive further than // specified, but will appear more accurate since we are pushing the edge of the model to the // specified distance. large objects appears to be a lot closer without the following line because // the object centers were at the correct distance, but the model itself was much closer to the // target ship. dist += (int)Objects[objnum].radius + (int)Objects[anchor_objnum].radius; vm_vec_scale_add(&Objects[objnum].pos, &anchor_pos, &rand_vec, (float)dist); // I think that we will always want to orient the ship that is arriving to face towards // the ship it is arriving near/in front of. The effect will be cool! // // calculate the new fvec of the ship arriving and use only that to get the matrix. isn't a big // deal not getting bank. vm_vec_sub(&new_fvec, &anchor_pos, &Objects[objnum].pos ); vm_vector_2_matrix( &orient, &new_fvec, NULL, NULL ); Objects[objnum].orient = orient; } // set the new_pos parameter since it might be used outside the function (i.e. when dealing with wings). if ( new_pos ) memcpy(new_pos, &Objects[objnum].pos, sizeof(vec3d) ); if ( new_orient ) memcpy( new_orient, &Objects[objnum].orient, sizeof(matrix) ); return anchor_objnum; } /** * Mark a reinforcement as available */ void mission_parse_mark_reinforcement_available(char *name) { int i; reinforcements *rp; for (i = 0; i < Num_reinforcements; i++) { rp = &Reinforcements[i]; if ( !stricmp(rp->name, name) ) { if ( !(rp->flags & RF_IS_AVAILABLE) ) { rp->flags |= RF_IS_AVAILABLE; // tell all of the clients. if ( MULTIPLAYER_MASTER ) { send_reinforcement_avail( i ); } } return; } } Assert ( i < Num_reinforcements ); } /** * Takes a parse object and checks the arrival cue, delay and destruction of object it is arriving from then creates the object if necessary. * * @return -1 if not created. * @return objnum of created ship otherwise */ int mission_did_ship_arrive(p_object *objp) { int should_arrive; // find out in the arrival cue became true should_arrive = eval_sexp(objp->arrival_cue); // we must first check to see if this ship is a reinforcement or not. If so, then don't // process if ( objp->flags[Mission::Parse_Object_Flags::SF_Reinforcement] ) { // if this ship did arrive, mark the reinforcement as available, and tell clients if in multiplayer // mode if ( should_arrive ) { mission_parse_mark_reinforcement_available(objp->name); } return -1; } if ( should_arrive ) { // has the arrival criteria been met? int object_num; // check to see if the delay field <= 0. if so, then create a timestamp and then maybe // create the object if ( objp->arrival_delay <= 0 ) { objp->arrival_delay = timestamp( -objp->arrival_delay * 1000 ); // make sure we have a valid timestamp Assert( objp->arrival_delay > 0 ); } // if the timestamp hasn't elapsed, move onto the next ship. if ( !timestamp_elapsed(objp->arrival_delay) ) return -1; // check to see if this ship is to arrive via a docking bay. If so, and the ship to arrive from // doesn't exist, don't create. if ( objp->arrival_location == ARRIVE_FROM_DOCK_BAY ) { int shipnum; char *name; Assert( objp->arrival_anchor >= 0 ); name = Parse_names[objp->arrival_anchor]; // see if ship is in mission. shipnum = ship_name_lookup( name ); if ( shipnum == -1 ) { // see if ship is yet to arrive. If so, then return -1 so we can evaluate again later. if (mission_check_ship_yet_to_arrive(name)) return -1; mission_parse_mark_non_arrival(objp); // Goober5000 WarningEx(LOCATION, "Warning: Ship %s cannot arrive from docking bay of destroyed or departed %s.\n", objp->name, name); return -1; } // Goober5000: aha - also don't create if fighterbay is destroyed if (ship_fighterbays_all_destroyed(&Ships[shipnum])) { WarningEx(LOCATION, "Warning: Ship %s cannot arrive from destroyed docking bay of %s.\n", objp->name, name); return -1; } } if ( objp->flags[Mission::Parse_Object_Flags::SF_Cannot_arrive] ) { WarningEx(LOCATION, "Warning: Ship %s cannot arrive. Ship not created.\n", objp->name); return -1; } // create the ship object_num = parse_create_object(objp); // since this ship is not in a wing, create a SHIP_ARRIVE entry //mission_log_add_entry( LOG_SHIP_ARRIVE, objp->name, NULL ); Assert(object_num >= 0 && object_num < MAX_OBJECTS); // Play the music track for an arrival if ( !(Ships[Objects[object_num].instance].flags[Ship::Ship_Flags::No_arrival_music]) ) if ( timestamp_elapsed(Allow_arrival_music_timestamp) ) { Allow_arrival_music_timestamp = timestamp(ARRIVAL_MUSIC_MIN_SEPARATION); event_music_arrival(Ships[Objects[object_num].instance].team); } return object_num; } return -1; } // Goober5000 void mission_maybe_make_ship_arrive(p_object *p_objp) { // try to create ship int objnum = mission_did_ship_arrive(p_objp); if (objnum < 0) return; // remove from arrival list if (p_objp == Arriving_support_ship) mission_parse_support_arrived(objnum); else list_remove(&Ship_arrival_list, p_objp); } // Goober5000 void mission_parse_mark_non_arrival(p_object *p_objp) { // mark the flag p_objp->flags.set(Mission::Parse_Object_Flags::SF_Cannot_arrive); } // Goober5000 void mission_parse_mark_non_arrival(wing *wingp) { int wingnum = WING_INDEX(wingp); // look through all ships yet to arrive... for (p_object *p_objp = GET_FIRST(&Ship_arrival_list); p_objp != END_OF_LIST(&Ship_arrival_list); p_objp = GET_NEXT(p_objp)) { // ...and mark the ones in this wing if (p_objp->wingnum == wingnum) p_objp->flags.set(Mission::Parse_Object_Flags::SF_Cannot_arrive); } } /** * Set a flag on all parse objects on ship arrival list which cannot arrive in the mission */ void mission_parse_mark_non_arrivals() { for (p_object *p_objp = GET_FIRST(&Ship_arrival_list); p_objp != END_OF_LIST(&Ship_arrival_list); p_objp = GET_NEXT(p_objp)) { if (p_objp->wingnum != -1) { if (!object_is_docked(p_objp) && (Sexp_nodes[Wings[p_objp->wingnum].arrival_cue].value == SEXP_KNOWN_FALSE)) p_objp->flags.set(Mission::Parse_Object_Flags::SF_Cannot_arrive); } else { if (Sexp_nodes[p_objp->arrival_cue].value == SEXP_KNOWN_FALSE) p_objp->flags.set(Mission::Parse_Object_Flags::SF_Cannot_arrive); } } } /** * Deal with support ship arrival. This function can get called from either single or multiplayer. Needed to that clients * can know when to abort rearm. * * @param objnum is the object number of the arriving support ship */ void mission_parse_support_arrived( int objnum ) { int i; // when the support ship arrives, the shipname it is supposed to repair is in the 'misc' // field of the parse object. If the ship still exists, call ai function which actually // issues the goal for the repair for ( i = 0; i < Num_arriving_repair_targets; i++ ) { int shipnum; shipnum = ship_name_lookup( Arriving_repair_targets[i] ); if ( shipnum != -1 ) { object *requester_objp, *support_objp; support_objp = &Objects[objnum]; requester_objp = &Objects[Ships[shipnum].objnum]; ai_add_rearm_goal( requester_objp, support_objp ); } } Ships[Objects[objnum].instance].flags.set(Ship::Ship_Flags::Warped_support); Arriving_support_ship = NULL; Num_arriving_repair_targets = 0; } // Goober5000 int parse_object_on_arrival_list(p_object *pobjp) { return (pobjp->next != NULL) && (pobjp->prev != NULL); } /** * Check the lists of arriving ships and wings, creating new ships/wings if the arrival criteria have been met */ void mission_eval_arrivals() { int i; int rship = -1; wing *wingp; // before checking arrivals, check to see if we should play a message concerning arrivals // of other wings. We use the timestamps to delay the arrival message slightly for // better effect if (timestamp_valid(Arrival_message_delay_timestamp) && timestamp_elapsed(Arrival_message_delay_timestamp) && !MULTI_TEAM) { int use_terran_cmd; // use terran command 25% of time use_terran_cmd = ((frand() - 0.75) > 0.0f)?1:0; rship = ship_get_random_player_wing_ship( SHIP_GET_UNSILENCED ); if ((rship < 0) || use_terran_cmd) message_send_builtin_to_player(MESSAGE_ARRIVE_ENEMY, NULL, MESSAGE_PRIORITY_LOW, MESSAGE_TIME_SOON, 0, 0, -1, -1); else if (rship >= 0) message_send_builtin_to_player(MESSAGE_ARRIVE_ENEMY, &Ships[rship], MESSAGE_PRIORITY_LOW, MESSAGE_TIME_SOON, 0, 0, -1, -1); Arrival_message_delay_timestamp = timestamp(-1); // make the stamp invalid } // check the arrival list // Goober5000 - we can't run through the list the usual way because we might // remove a bunch of objects and completely screw up the list linkage for (SCP_vector<p_object>::iterator ii = Parse_objects.begin(); ii != Parse_objects.end(); ++ii) { p_object *pobjp = &(*ii); // make sure we're on the arrival list if (!parse_object_on_arrival_list(pobjp)) continue; // if this object has a wing, don't create it -- let code for wings determine if it should be created if (pobjp->wingnum >= 0) continue; // make it arrive mission_maybe_make_ship_arrive(pobjp); } // check the support ship arrival list if (Arriving_support_ship) { // make it arrive (support ships are not put on the arrival list) mission_maybe_make_ship_arrive(Arriving_support_ship); } // we must also check to see if there are waves of a wing that must // reappear if all the ships of the current wing have been destroyed or // have departed. If this is the case, then create the next wave. for (i = 0; i < Num_wings; i++) { wingp = &Wings[i]; // should we process this wing anymore if (wingp->flags[Ship::Wing_Flags::Gone]) continue; // if we have a reinforcement wing, then don't try to create new ships automatically. if (wingp->flags[Ship::Wing_Flags::Reinforcement]) { // check to see in the wings arrival cue is true, and if so, then mark the reinforcement // as available if (eval_sexp(wingp->arrival_cue)) mission_parse_mark_reinforcement_available(wingp->name); // reinforcement wings skip the rest of the loop continue; } // don't do evaluations for departing wings if (wingp->flags[Ship::Wing_Flags::Departing]) continue; // must check to see if we are at the last wave. Code above to determine when a wing is gone only // gets run when a ship is destroyed (not every N seconds like it used to). Do a quick check here. if (wingp->current_wave == wingp->num_waves) continue; // If the current wave of this wing is 0, then we haven't created the ships in the wing yet. // If the threshold of the wing has been reached, then we need to create more ships. if ((wingp->current_wave == 0) || (wingp->current_count <= wingp->threshold)) { // Call parse_wing_create_ships to try and create it. That function will eval the arrival // cue of the wing and create the ships if necessary. int created = parse_wing_create_ships(wingp, wingp->wave_count); // if we didn't create any ships, nothing more to do for this wing if (created <= 0) continue; // If this wing was a reinforcement wing, then we need to reset the reinforcement flag for the wing // so the user can call in another set if need be. if (wingp->flags[Ship::Wing_Flags::Reset_reinforcement]) { wingp->flags.remove(Ship::Wing_Flags::Reset_reinforcement); wingp->flags.set(Ship::Wing_Flags::Reinforcement); } // probably send a message to the player when this wing arrives. // if no message, nothing more to do for this wing if (wingp->flags[Ship::Wing_Flags::No_arrival_message]) continue; // multiplayer team vs. team if(MULTI_TEAM) { // send a hostile wing arrived message rship = wingp->ship_index[wingp->special_ship]; int multi_team_filter = Ships[rship].team; // there are two timestamps at work here. One to control how often the player receives // messages about incoming hostile waves, and the other to control how long after // the wing arrives does the player actually get the message. if (timestamp_elapsed(Allow_arrival_message_timestamp_m[multi_team_filter])) { if (!timestamp_valid(Arrival_message_delay_timestamp_m[multi_team_filter])) { Arrival_message_delay_timestamp_m[multi_team_filter] = timestamp_rand(ARRIVAL_MESSAGE_DELAY_MIN, ARRIVAL_MESSAGE_DELAY_MAX); } Allow_arrival_message_timestamp_m[multi_team_filter] = timestamp(ARRIVAL_MESSAGE_MIN_SEPARATION); // send to the proper team message_send_builtin_to_player(MESSAGE_ARRIVE_ENEMY, NULL, MESSAGE_PRIORITY_LOW, MESSAGE_TIME_SOON, 0, 0, -1, multi_team_filter); } } // does the player attack this ship? else if (iff_x_attacks_y(Player_ship->team, Ships[wingp->ship_index[0]].team)) { // there are two timestamps at work here. One to control how often the player receives // messages about incoming hostile waves, and the other to control how long after // the wing arrives does the player actually get the message. if (timestamp_elapsed(Allow_arrival_message_timestamp)) { if (!timestamp_valid(Arrival_message_delay_timestamp)) { Arrival_message_delay_timestamp = timestamp_rand(ARRIVAL_MESSAGE_DELAY_MIN, ARRIVAL_MESSAGE_DELAY_MAX); } Allow_arrival_message_timestamp = timestamp(ARRIVAL_MESSAGE_MIN_SEPARATION); } } // everything else else { rship = ship_get_random_ship_in_wing(i, SHIP_GET_UNSILENCED); if (rship >= 0) { int j; SCP_string message_name; sprintf(message_name, "%s Arrived", wingp->name); // see if this wing has an arrival message associated with it for (j = 0; j < MAX_BUILTIN_MESSAGE_TYPES; j++) { if (!stricmp(message_name.c_str(), Builtin_messages[j].name)) { message_send_builtin_to_player(j, &Ships[rship], MESSAGE_PRIORITY_LOW, MESSAGE_TIME_SOON, 0, 0, -1, -1); break; } } } } } } Mission_arrival_timestamp = timestamp(ARRIVAL_TIMESTAMP); } /** * Called to make object objp depart. Rewritten and expanded by Goober5000. */ int mission_do_departure(object *objp, bool goal_is_to_warp) { Assert(objp->type == OBJ_SHIP); int location, anchor, path_mask; ship *shipp = &Ships[objp->instance]; ai_info *aip = &Ai_info[shipp->ai_index]; mprintf(("Entered mission_do_departure() for %s\n", shipp->ship_name)); // add scripting hook for 'On Depature Started' --wookieejedi // hook is placed at the begining of this function to allow the scripter to // actually have access to the ship's departure decisions before they are all executed OnDepartureStartedHook->run(scripting::hook_param_list(scripting::hook_param("Ship", 'o', objp))); // abort rearm, because if we entered this function we're either going to depart via hyperspace, depart via bay, // or revert to our default behavior ai_abort_rearm_request(objp); // if our current goal is to warp, then we won't consider departing to a bay, because the goal explicitly says to warp out // (this sort of goal can be assigned in FRED, either in the ship's initial orders or as the ai-warp-out goal) if (goal_is_to_warp) { // aha, but not if we were ORDERED to depart, because the comms menu ALSO uses the goal code, and yet the comms menu means any departure method! if ((shipp->flags[Ship::Ship_Flags::Departure_ordered]) || ((shipp->wingnum >= 0) && (Wings[shipp->wingnum].flags[Ship::Wing_Flags::Departure_ordered]))) { mprintf(("Looks like we were ordered to depart; initiating the standard departure logic\n")); } // since our goal is to warp, then if we can warp, jump directly to the warping part else if (ship_can_warp_full_check(shipp)) { mprintf(("Our current goal is to warp! Trying to warp...\n")); goto try_to_warp; } // otherwise, since we can't warp, we'll do the standard bay departure check, etc. } // if this ship belongs to a wing, then use the wing departure information if (shipp->wingnum >= 0) { wing *wingp = &Wings[shipp->wingnum]; // copy the wing's departure information to the ship // (needed because the bay departure code will check the ship's information again later on) shipp->departure_location = wingp->departure_location; shipp->departure_anchor = wingp->departure_anchor; shipp->departure_path_mask = wingp->departure_path_mask; } location = shipp->departure_location; anchor = shipp->departure_anchor; path_mask = shipp->departure_path_mask; // if departing to a docking bay, try to find the anchor ship to depart to. If not found, then // just make it warp out like anything else. if (location == DEPART_AT_DOCK_BAY) { int anchor_shipnum; char *name; Assert(anchor >= 0); name = Parse_names[anchor]; // see if ship is yet to arrive. If so, then warp. if (mission_check_ship_yet_to_arrive(name)) { mprintf(("Anchor ship %s hasn't arrived yet! Trying to warp...\n", name)); goto try_to_warp; } // see if ship is in mission. If not, then we can assume it was destroyed or departed since // it is not on the arrival list (as shown by above if statement). anchor_shipnum = ship_name_lookup(name); if (anchor_shipnum < 0) { mprintf(("Anchor ship %s not found! Trying to warp...\n", name)); goto try_to_warp; } // see if we can actually depart to the ship if (!ship_useful_for_departure(anchor_shipnum, shipp->departure_path_mask)) { mprintf(("Anchor ship %s not suitable for departure (dying, departing, bays destroyed, etc.). Trying to warp...\n", name)); goto try_to_warp; } // find a path if (ai_acquire_depart_path(objp, Ships[anchor_shipnum].objnum, path_mask) >= 0) { MONITOR_INC(NumShipDepartures,1); mprintf(("Acquired departure path\n")); return 1; } } try_to_warp: // make sure we can actually warp if (ship_can_warp_full_check(shipp)) { mprintf(("Setting mode to warpout\n")); ai_set_mode_warp_out(objp, aip); MONITOR_INC(NumShipDepartures,1); return 1; } // find something else to do else { // NOTE: this point should no longer be reached in the standard goal code, since the goal or comm order must be achievable // for this function to be called. This point should only be reached if the ship has no subspace drive, AND either has no // mothership assigned (or departs to hyperspace) or the mothership was destroyed, AND falls into one of the following cases: // 1) The ship's departure cue evaluates to true in the mission // 2) A support ship has had its hull fall to 25% when it has no repair targets // 3) A fighter or bomber with an IFF that doesn't allow support ships has its warp_out_timestamp elapse (but this seems to not be a possibility anymore) // 4) An instructor in a training mission has been fired upon mprintf(("Can't warp! Doing something else instead.\n")); shipp->flags.remove(Ship::Ship_Flags::Depart_dockbay); shipp->flags.remove(Ship::Ship_Flags::Depart_warp); ai_do_default_behavior(objp); return 0; } } /** * Put here because mission_eval_arrivals is here. * @todo Might move these to a better location later -- MWA */ void mission_eval_departures() { int i, j; object *objp; wing *wingp; // scan through the active ships an evaluate their departure cues. For those // ships whose time has come, set their departing flag. for ( objp = GET_FIRST(&obj_used_list); objp !=END_OF_LIST(&obj_used_list); objp = GET_NEXT(objp) ) { if (objp->type == OBJ_SHIP) { ship *shipp; Assert((objp->instance >= 0) && (objp->instance < MAX_SHIPS)); shipp = &Ships[objp->instance]; // don't process a ship that is already departing or dying or disabled // AL 12-30-97: Added SF_CANNOT_WARP to check // Goober5000 - fixed so that it WILL eval when SF_CANNOT_WARP if departing to dockbay // wookieejedi - fixed so it accounts for break and never warp too if ( shipp->is_dying_or_departing() || ( !(ship_can_warp_full_check(shipp)) && (shipp->departure_location != DEPART_AT_DOCK_BAY)) || ship_subsys_disrupted(shipp, SUBSYSTEM_ENGINE) ) { continue; } // don't process ships that are part of a wing -- handled in seperate case if ( shipp->wingnum != -1 ) continue; // when the departure cue becomes true, set off the departure delay timer. We store the // timer as -seconds in FreeSpace which indicates that the timer has not been set. If the timer // is not set, then turn it into a valid timer and keep evaluating the timer until it is elapsed if ( eval_sexp(shipp->departure_cue) ) { if ( shipp->departure_delay <= 0 ) shipp->departure_delay = timestamp(-shipp->departure_delay * 1000 ); if ( timestamp_elapsed(shipp->departure_delay) ) mission_do_departure( objp ); } } } // now scan through the list of wings and check their departure cues. For wings with // that cue being true, we must update internal variables to indicate that the wing is // departed and that no further waves of this wing will appear for ( i = 0; i < Num_wings; i++ ) { wingp = &Wings[i]; // should we process this wing anymore if ( wingp->flags[Ship::Wing_Flags::Departing] ) continue; // evaluate the sexpression. If true, mark all the ships in this wing as departing and increment // the num departed in the wing structure. Then add number of remaining waves * ships/wave to // departed count to get total count of ships in the wing which departed. (We are counting ships // that have not yet arrived as departed if they never arrive -- this may be bad, but for some reason // seems like the right thing to do). if ( eval_sexp(wingp->departure_cue) ) { // if we haven't set up the departure timer yet (would be <= 0) setup the timer to pop N seconds // later if ( wingp->departure_delay <= 0 ) wingp->departure_delay = timestamp( -wingp->departure_delay * 1000 ); if ( !timestamp_elapsed(wingp->departure_delay) ) continue; wingp->flags.set(Ship::Wing_Flags::Departing); for ( j = 0; j < wingp->current_count; j++ ) { ship *shipp; shipp = &Ships[wingp->ship_index[j]]; if ( (shipp->is_departing()) || (shipp->flags[Ship::Ship_Flags::Dying]) ) continue; Assert ( shipp->objnum != -1 ); objp = &Objects[shipp->objnum]; mission_do_departure( objp ); // don't add to wingp->total_departed here -- this is taken care of in ship code. } } } Mission_departure_timestamp = timestamp(DEPARTURE_TIMESTAMP); } /** * Called from high level game loop to do mission evaluation stuff */ void mission_parse_eval_stuff() { mission_eval_arrivals(); mission_eval_departures(); } int allocate_subsys_status() { int i; // set primary weapon ammunition here, but does it actually matter? - Goober5000 Assert(Subsys_index >= 0); // we allocate in blocks of MIN_SUBSYS_STATUS_SIZE so if we need more then make more if ( (Subsys_status == NULL) || (Subsys_index >= (Subsys_status_size - 1)) ) { Assert( MIN_SUBSYS_STATUS_SIZE > 0 ); Subsys_status_size += MIN_SUBSYS_STATUS_SIZE; Subsys_status = (subsys_status*)vm_realloc(Subsys_status, sizeof(subsys_status) * Subsys_status_size ); } Verify( Subsys_status != NULL ); // the memset is redundant to the below assignments //memset( &Subsys_status[Subsys_index], 0, sizeof(subsys_status) ); Subsys_status[Subsys_index].name[0] = '\0'; Subsys_status[Subsys_index].percent = 0.0f; Subsys_status[Subsys_index].primary_banks[0] = SUBSYS_STATUS_NO_CHANGE; Subsys_status[Subsys_index].primary_ammo[0] = 100; // * for (i=1; i<MAX_SHIP_PRIMARY_BANKS; i++) { Subsys_status[Subsys_index].primary_banks[i] = -1; // none Subsys_status[Subsys_index].primary_ammo[i] = 100; // * } Subsys_status[Subsys_index].secondary_banks[0] = SUBSYS_STATUS_NO_CHANGE; Subsys_status[Subsys_index].secondary_ammo[0] = 100; for (i=1; i<MAX_SHIP_SECONDARY_BANKS; i++) { Subsys_status[Subsys_index].secondary_banks[i] = -1; Subsys_status[Subsys_index].secondary_ammo[i] = 100; } Subsys_status[Subsys_index].ai_class = SUBSYS_STATUS_NO_CHANGE; Subsys_status[Subsys_index].subsys_cargo_name = 0; // "Nothing" return Subsys_index++; } // Goober5000 int insert_subsys_status(p_object *pobjp) { int i, new_index; // this is not good; we have to allocate another slot, but then bump all the // slots upward so that this particular parse object's subsystems are contiguous new_index = allocate_subsys_status(); // only bump the subsystems if this isn't the very last subsystem if (new_index != pobjp->subsys_index + pobjp->subsys_count) { // copy the new blank entry for future reference subsys_status temp_entry; memcpy(&temp_entry, &Subsys_status[new_index], sizeof(subsys_status)); // shift elements upward for (i = Subsys_index - 1; i > (pobjp->subsys_index + pobjp->subsys_count); i--) { memcpy(&Subsys_status[i], &Subsys_status[i-1], sizeof(subsys_status)); } // correct the index so that the new subsystem belongs to the proper p_object new_index = pobjp->subsys_index + pobjp->subsys_count; // put the blank entry in the p_object memcpy(&Subsys_status[new_index], &temp_entry, sizeof(subsys_status)); } // make the p_object aware of its new subsystem pobjp->subsys_count++; // we also have to adjust all the indexes in existing parse objects // (each p_object's subsys_index points to subsystem 0 in its list) for (SCP_vector<p_object>::iterator ii = Parse_objects.begin(); ii != Parse_objects.end(); ++ii) { // bump up base index to accommodate inserted subsystem if (ii->subsys_index >= new_index) ii->subsys_index++; } return new_index; } // Goober5000 subsys_status *parse_get_subsys_status(p_object *pobjp, const char *subsys_name) { int i; subsys_status *sssp; for (i = 0; i < pobjp->subsys_count; i++) { sssp = &Subsys_status[pobjp->subsys_index + i]; if (!subsystem_stricmp(sssp->name, subsys_name)) return sssp; } return NULL; } // find (or add) the name in the list and return an index to it. int get_parse_name_index(const char *name) { int i; for (i=0; i<Num_parse_names; i++) if (!stricmp(name, Parse_names[i])) return i; Assert(i < MAX_SHIPS + MAX_WINGS); Assert(strlen(name) < NAME_LENGTH); strcpy_s(Parse_names[i], name); return Num_parse_names++; } // Goober5000 int add_path_restriction() { int i, j; // parse it path_restriction_t temp; temp.cached_mask = (1 << MAX_SHIP_BAY_PATHS); // uninitialized value (too high) temp.num_paths = (int)stuff_string_list(temp.path_names, MAX_SHIP_BAY_PATHS); // no restriction? if (temp.num_paths == 0) return -1; // first, see if it's duplicated anywhere for (i = 0; i < Num_path_restrictions; i++) { // must have same number of allowed paths if (temp.num_paths != Path_restrictions[i].num_paths) continue; // see if path names match for (j = 0; j < temp.num_paths; j++) { // no match, so skip this if (stricmp(temp.path_names[j], Path_restrictions[i].path_names[j]) != 0) goto continue_outer_loop; } // match! return i; continue_outer_loop: ; } // no match, so add a new restriction // check limit if (Num_path_restrictions >= MAX_PATH_RESTRICTIONS) { Warning(LOCATION, "Maximum number of path restrictions reached"); return -1; } // add this restriction at the new index int index = Num_path_restrictions++; Path_restrictions[index] = temp; return index; } /** * Look for \<any friendly\>, \<any hostile player\>, etc. */ int get_special_anchor(const char *name) { char tmp[NAME_LENGTH + 15]; const char *iff_name; int iff_index; if (strnicmp(name, "<any ", 5) != 0) return -1; strcpy_s(tmp, name+5); iff_name = strtok(tmp, " >"); // hack substitute "hostile" for "enemy" if (!stricmp(iff_name, "enemy")) iff_name = "hostile"; iff_index = iff_lookup(iff_name); if (iff_index < 0) return -1; // restrict to players? if (stristr(name+5, "player") != NULL) return (iff_index | SPECIAL_ARRIVAL_ANCHOR_FLAG | SPECIAL_ARRIVAL_ANCHOR_PLAYER_FLAG); else return (iff_index | SPECIAL_ARRIVAL_ANCHOR_FLAG); } int get_anchor(const char *name) { int special_anchor = get_special_anchor(name); if (special_anchor >= 0) return special_anchor; return get_parse_name_index(name); } /** * Fixup the goals/ai references for player objects in the mission */ void mission_parse_fixup_players() { object *objp; for ( objp = GET_FIRST(&obj_used_list); objp != END_OF_LIST(&obj_used_list); objp = GET_NEXT(objp) ) { if ( (objp->type == OBJ_SHIP) && (objp->flags[Object::Object_Flags::Player_ship]) ) { game_busy( NOX("** fixing up player/ai stuff **") ); // animate the loading screen, doesn't nothing if the screen is not active ai_clear_ship_goals( &Ai_info[Ships[objp->instance].ai_index] ); init_ai_object( OBJ_INDEX(objp) ); } } } // code to warp in a new support ship. It works by finding the average position of all ships // in the mission, creating a vector from that position to the player, and scaling out behind the // player some distance. Should be sufficient. #define WARP_IN_MIN_DISTANCE 1000.0f #define WARP_IN_TIME_MIN 3000 // warps in min 3 seconds later #define WARP_IN_TIME_MAX 6000 // warps in max 6 seconds later /** * Adds requester_objp onto the queue of ships for the arriving support ship to service */ void mission_add_to_arriving_support( object *requester_objp ) { int i; ship *shipp; Assert ( Arriving_support_ship ); if ( Num_arriving_repair_targets == MAX_AI_GOALS ) { mprintf(("Reached MAX_AI_GOALS trying to add repair request!\n")); return; } shipp = &Ships[requester_objp->instance]; // check for duplicates before adding for (i = 0; i < Num_arriving_repair_targets; i++ ) { if ( !stricmp(Arriving_repair_targets[i], shipp->ship_name) ){ break; } } if ( i != Num_arriving_repair_targets ){ // found the ship before reaching the end -- ignore it! return; } strcpy_s( Arriving_repair_targets[Num_arriving_repair_targets], Ships[requester_objp->instance].ship_name ); Num_arriving_repair_targets++; if ( MULTIPLAYER_MASTER ){ multi_maybe_send_repair_info( requester_objp, NULL, REPAIR_INFO_WARP_ADD ); } } extern int pp_collide_any(vec3d *curpos, vec3d *goalpos, float radius, object *ignore_objp1, object *ignore_objp2, int big_only_flag); /** * Set the warp in position for a support ship relative to an object. * Caller tries several positions, passing vector in x, y, z. */ int get_warp_in_pos(vec3d *pos, object *objp, float x, float y, float z) { float rand_val; if ( Game_mode & GM_NORMAL ) rand_val = frand(); else rand_val = static_randf(objp->net_signature); rand_val = 1.0f + (rand_val - 0.5f)*0.2f; *pos = objp->pos; vm_vec_scale_add2( pos, &objp->orient.vec.rvec, x*rand_val*800.0f); vm_vec_scale_add2( pos, &objp->orient.vec.uvec, y*rand_val*800.0f); vm_vec_scale_add2( pos, &objp->orient.vec.fvec, z*rand_val*800.0f); return pp_collide_any(&objp->pos, pos, objp->radius, objp, NULL, 1); } /** * Modified by Goober5000 to allow more flexibility in support ships */ void mission_bring_in_support_ship( object *requester_objp ) { vec3d center, warp_in_pos; p_object *pobj; ship *requester_shipp; int i, j, requester_species; Assert ( requester_objp->type == OBJ_SHIP ); requester_shipp = &Ships[requester_objp->instance]; // MK, 10/23/97, used to be ->type, bogus, no? // if the support ship is already arriving, add the requester to the list if ( Arriving_support_ship ) { mission_add_to_arriving_support( requester_objp ); return; } // create a parse object, and put it onto the ship arrival list. This whole thing kind of stinks. // I want to put it into a parse object since it needs to arrive just a little later than // this function is called. I have to make some assumptions in the code about values for the parse // object since I'm no longer working with a mission file. These exceptions will be noted with // comments Arriving_support_ship = &Support_ship_pobj; pobj = Arriving_support_ship; // get average position of all ships obj_get_average_ship_pos( &center ); vm_vec_sub( &warp_in_pos, &center, &(requester_objp->pos) ); // Choose position to warp in ship. // Temporary, but changed by MK because it used to be exactly behind the player. // This could cause an Assert if the player immediately targeted it (before moving). // Tend to put in front of the player to aid him in flying towards the ship. if (!get_warp_in_pos(&warp_in_pos, requester_objp, 1.0f, 0.1f, 1.0f)) if (!get_warp_in_pos(&warp_in_pos, requester_objp, 1.0f, 0.2f, -1.0f)) if (!get_warp_in_pos(&warp_in_pos, requester_objp, -1.0f, -0.2f, -1.0f)) if (!get_warp_in_pos(&warp_in_pos, requester_objp, -1.0f, -0.1f, 1.0f)) get_warp_in_pos(&warp_in_pos, requester_objp, 0.1f, 1.0f, 0.2f); // position for ship if it warps in pobj->pos = warp_in_pos; // tally the ship The_mission.support_ships.tally++; // create a name for the ship. use "Support #". look for collisions until one isn't found anymore i = 1; do { sprintf(pobj->name, NOX("Support %d"), i); if ( (ship_name_lookup(pobj->name) == -1) && (ship_find_exited_ship_by_name(pobj->name) == -1) ) break; i++; } while(1); vm_set_identity( &(pobj->orient) ); // *sigh*. Gotta get the ship class. For now, this will amount to finding a ship in the ship_info // array with the same team as the requester of type SIF_SUPPORT. Might need to be changed, but who knows // Goober5000 - who knew of the SCP release? ;) only determine ship class if not set by SEXP pobj->ship_class = The_mission.support_ships.ship_class; if (pobj->ship_class < 0) { requester_species = Ship_info[requester_shipp->ship_info_index].species; // 5/6/98 -- MWA Don't need to do anything for multiplayer. I think that we always want to use // the species of the caller ship. i = -1; // get index of correct species support ship for (auto it = Ship_info.cbegin(); it != Ship_info.cend(); ++it) { if ((it->species == requester_species) && (it->flags[Ship::Info_Flags::Support])) { i = (int)std::distance(Ship_info.cbegin(), it); break; } } if ( i != -1 ) pobj->ship_class = i; else Int3(); // BOGUS!!!! gotta figure something out here } // set support ship hitpoints pobj->ship_max_hull_strength = Ship_info[i].max_hull_strength; pobj->ship_max_shield_strength = Ship_info[i].max_shield_strength; pobj->max_shield_recharge = Ship_info[i].max_shield_recharge; pobj->team = requester_shipp->team; for (i=0;i<MAX_IFFS;i++) { for (j=0;j<MAX_IFFS;j++) { pobj->alt_iff_color[i][j] = -1; } } pobj->behavior = AIM_NONE; // ASSUMPTION: the mission file has the string "None" which maps to AIM_NONE // set the ai_goals to -1. We will put the requester object shipname in repair target array and then take // care of setting up the goal when creating the ship!!!! pobj->ai_goals = -1; Num_arriving_repair_targets = 0; mission_add_to_arriving_support( requester_objp ); // need to set ship's cargo to nothing. scan the cargo_names array looking for the string nothing. // add it if not found for (i = 0; i < Num_cargo; i++ ) if ( !stricmp(Cargo_names[i], NOX("nothing")) ) break; if ( i == Num_cargo ) { strcpy(Cargo_names[i], NOX("Nothing")); Num_cargo++; } pobj->cargo1 = char(i); pobj->status_count = 0; // Goober5000 - take some stuff from mission flags pobj->arrival_location = The_mission.support_ships.arrival_location; pobj->arrival_anchor = The_mission.support_ships.arrival_anchor; pobj->departure_location = The_mission.support_ships.departure_location; pobj->departure_anchor = The_mission.support_ships.departure_anchor; pobj->arrival_path_mask = 0; pobj->departure_path_mask = 0; pobj->arrival_distance = 0; pobj->arrival_cue = Locked_sexp_true; pobj->arrival_delay = timestamp_rand(WARP_IN_TIME_MIN, WARP_IN_TIME_MAX); pobj->subsys_count = 0; // number of elements used in subsys_status array pobj->initial_velocity = 100; // start at 100% velocity pobj->initial_hull = 100; // start at 100% hull pobj->initial_shields = 100; // and 100% shields pobj->departure_cue = Locked_sexp_false; pobj->departure_delay = 0; pobj->warpin_params_index = -1; pobj->warpout_params_index = -1; pobj->wingnum = -1; pobj->flags.reset(); if (Player_obj->flags[Object::Object_Flags::No_shields]) { pobj->flags.set(Mission::Parse_Object_Flags::OF_No_shields); // support ships have no shields when player has not shields } pobj->ai_class = Ship_info[pobj->ship_class].ai_class; pobj->hotkey = -1; pobj->score = 0; pobj->assist_score_pct = 0; pobj->dock_list = NULL; pobj->created_object = NULL; pobj->group = -1; pobj->persona_index = -1; pobj->net_signature = multi_assign_network_signature(MULTI_SIG_SHIP); pobj->wing_status_wing_index = -1; pobj->wing_status_wing_pos = -1; pobj->respawn_count = 0; pobj->alt_type_index = -1; pobj->callsign_index = -1; pobj->replacement_textures.clear(); } /** * Returns true if a support ship is currently in the process of warping in. */ int mission_is_support_ship_arriving() { if ( Arriving_support_ship ) return 1; else return 0; } /** * Returns true if the given ship is scheduled to be repaired by the arriving support ship */ int mission_is_repair_scheduled( object *objp ) { char *name; int i; if ( !Arriving_support_ship ) return 0; Assert ( objp->type == OBJ_SHIP ); name = Ships[objp->instance].ship_name; for (i = 0; i < Num_arriving_repair_targets; i++ ) { if ( !strcmp( name, Arriving_repair_targets[i]) ) return 1; } return 0; } /** * Removed the given ship from the list of ships that are to get repair by arriving support ship */ int mission_remove_scheduled_repair( object *objp ) { char *name; int i, index; if ( !Arriving_support_ship ) return 0; // itereate through the target list looking for this ship name. If not found, we // can simply return. Assert ( objp->type == OBJ_SHIP ); name = Ships[objp->instance].ship_name; for (index = 0; index < Num_arriving_repair_targets; index++ ) { if ( !strcmp( name, Arriving_repair_targets[index]) ) break; } if ( index == Num_arriving_repair_targets ) return 0; // ship is found -- compress the array for ( i = index; i < Num_arriving_repair_targets - 1; i++ ) strcpy_s( Arriving_repair_targets[i], Arriving_repair_targets[i+1] ); Num_arriving_repair_targets--; if ( MULTIPLAYER_MASTER ) multi_maybe_send_repair_info( objp, NULL, REPAIR_INFO_WARP_REMOVE ); return 1; } /** * Alternate name stuff */ int mission_parse_lookup_alt(const char *name) { int idx; // sanity if(name == NULL) return -1; // lookup for(idx=0; idx<Mission_alt_type_count; idx++) { if(!strcmp(Mission_alt_types[idx], name)) return idx; } // could not find return -1; } static int mission_parse_lookup_alt_index_warn = 1; const char *mission_parse_lookup_alt_index(int index) { if((index < 0) || (index >= Mission_alt_type_count)) { if (mission_parse_lookup_alt_index_warn) { Warning(LOCATION, "Ship with invalid alt_name. Get a programmer"); mission_parse_lookup_alt_index_warn = 0; } return ""; } // get it return Mission_alt_types[index]; } int mission_parse_add_alt(const char *name) { // sanity if(name == NULL) return -1; // maybe add if(Mission_alt_type_count < MAX_ALT_TYPE_NAMES) { // stuff the name strcpy_s(Mission_alt_types[Mission_alt_type_count++], name); // done return Mission_alt_type_count - 1; } return -1; } void mission_parse_remove_alt(const char *name) { // sanity if(name == NULL) return; // maybe remove for (int i = 0; i < Mission_alt_type_count; ++i) { if (!strcmp(Mission_alt_types[i], name)) { // remove this name by overwriting it with the last name if (i < Mission_alt_type_count - 1) strcpy_s(Mission_alt_types[i], Mission_alt_types[Mission_alt_type_count - 1]); Mission_alt_type_count--; break; } } } void mission_parse_reset_alt() { Mission_alt_type_count = 0; } // For compatibility purposes some mods want alt names to truncate at the hash symbol. But we can't actually do that at mission load, // since we have to save them again in FRED. So this function processes the names just before the mission starts. // To further complicate things, some mods actually want the hash to be displayed. So this function uses the double-hash as an escape sequence for a single hash. void mission_process_alt_types() { for (int i = 0; i < Mission_alt_type_count; ++i) { // truncate at a single hash end_string_at_first_hash_symbol(Mission_alt_types[i], true); // ## -> # consolidate_double_characters(Mission_alt_types[i], '#'); } } /** * Callsign stuff */ int mission_parse_lookup_callsign(const char *name) { int idx; // sanity if(name == NULL) return -1; // lookup for(idx=0; idx<Mission_callsign_count; idx++) { if(!strcmp(Mission_callsigns[idx], name)) return idx; } // could not find return -1; } static int mission_parse_lookup_callsign_index_warn = 1; const char *mission_parse_lookup_callsign_index(int index) { if((index < 0) || (index >= Mission_callsign_count)) { if (mission_parse_lookup_callsign_index_warn) { Warning(LOCATION, "Ship with invalid callsign. Get a programmer"); mission_parse_lookup_callsign_index_warn = 0; } return ""; } // get it return Mission_callsigns[index]; } int mission_parse_add_callsign(const char *name) { // sanity if(name == NULL) return -1; // maybe add if(Mission_callsign_count < MAX_CALLSIGNS) { // stuff the name strcpy_s(Mission_callsigns[Mission_callsign_count++], name); // done return Mission_callsign_count - 1; } return -1; } void mission_parse_remove_callsign(const char *name) { // sanity if(name == NULL) return; // maybe remove for (int i = 0; i < Mission_callsign_count; ++i) { if (!strcmp(Mission_callsigns[i], name)) { // remove this callsign by overwriting it with the last callsign if (i < Mission_callsign_count - 1) strcpy_s(Mission_callsigns[i], Mission_callsigns[Mission_callsign_count - 1]); Mission_callsign_count--; break; } } } void mission_parse_reset_callsign() { Mission_callsign_count = 0; } int is_training_mission() { return (The_mission.game_type & MISSION_TYPE_TRAINING); } /** * Go through all the displayed text in one section and fix the section and text delimiters should all be different */ void conv_fix_punctuation_section(char *str, const char *section_start, const char *section_end, const char *text_start, const char *text_end) { char *s1, *s2, *t1, *t2; s1 = strstr(str, section_start); s2 = strstr(s1, section_end); t1 = s1; while (1) { t1 = strstr(t1+1, text_start); if (!t1 || t1 > s2) return; t2 = strstr(t1, text_end); if (!t2 || t2 > s2) return; replace_all(t1, "\"", "$quote", PARSE_TEXT_SIZE - (str - Parse_text), (t2 - t1)); } } // Goober5000 void conv_fix_punctuation() { // command briefings conv_fix_punctuation_section(Parse_text, "#Command Briefing", "#Briefing", "$Stage Text:", "$end_multi_text"); // briefings conv_fix_punctuation_section(Parse_text, "#Briefing", "#Debriefing_info", "$multi_text", "$end_multi_text"); // debriefings conv_fix_punctuation_section(Parse_text, "#Debriefing_info", "#Players", "$Multi text", "$end_multi_text"); // messages conv_fix_punctuation_section(Parse_text, "#Messages", "#Reinforcements", "$Message:", "\n"); } // Goober5000 void convertFSMtoFS2() { // fix punctuation conv_fix_punctuation(); } void clear_texture_replacements() { Fred_texture_replacements.clear(); }
/*============================================================================= Copyright (c) 2006 Eric Niebler Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) ==============================================================================*/ #if !defined(BOOST_FUSION_SEGMENTS_04052005_1141) #define BOOST_FUSION_SEGMENTS_04052005_1141 #include "Utilogeny/lib/boost/fusion/support/config.hpp" #include "Utilogeny/lib/boost/type_traits/is_const.hpp" #include "Utilogeny/lib/boost/utility/enable_if.hpp" #include "Utilogeny/lib/boost/fusion/sequence/intrinsic_fwd.hpp" #include "Utilogeny/lib/boost/fusion/support/tag_of.hpp" namespace boost { namespace fusion { // Special tags: struct sequence_facade_tag; struct iterator_range_tag; // segments: returns a sequence of sequences namespace extension { template <typename Tag> struct segments_impl { template <typename Sequence> struct apply {}; }; template <> struct segments_impl<sequence_facade_tag> { template <typename Sequence> struct apply : Sequence::template segments<Sequence> {}; }; template <> struct segments_impl<iterator_range_tag>; } namespace result_of { template <typename Sequence> struct segments { typedef typename traits::tag_of<Sequence>::type tag_type; typedef typename extension::segments_impl<tag_type>::template apply<Sequence>::type type; }; } template <typename Sequence> BOOST_CONSTEXPR BOOST_FUSION_GPU_ENABLED inline typename lazy_disable_if< is_const<Sequence> , result_of::segments<Sequence> >::type segments(Sequence& seq) { typedef typename traits::tag_of<Sequence>::type tag_type; return extension::segments_impl<tag_type>::template apply<Sequence>::call(seq); } template <typename Sequence> BOOST_CONSTEXPR BOOST_FUSION_GPU_ENABLED inline typename result_of::segments<Sequence const>::type segments(Sequence const& seq) { typedef typename traits::tag_of<Sequence const>::type tag_type; return extension::segments_impl<tag_type>::template apply<Sequence const>::call(seq); } }} #endif
// Copyright 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "cc/scheduler/delay_based_time_source.h" #include "base/basictypes.h" #include "base/test/test_simple_task_runner.h" #include "cc/test/scheduler_test_common.h" #include "testing/gtest/include/gtest/gtest.h" namespace cc { namespace { base::TimeDelta Interval() { return base::TimeDelta::FromMicroseconds(base::Time::kMicrosecondsPerSecond / 60); } TEST(DelayBasedTimeSourceTest, TaskPostedAndTickCalled) { scoped_refptr<base::TestSimpleTaskRunner> task_runner = new base::TestSimpleTaskRunner; FakeTimeSourceClient client; scoped_refptr<FakeDelayBasedTimeSource> timer = FakeDelayBasedTimeSource::Create(Interval(), task_runner.get()); timer->SetClient(&client); timer->SetActive(true); EXPECT_TRUE(timer->Active()); EXPECT_TRUE(task_runner->HasPendingTask()); timer->SetNow(timer->Now() + base::TimeDelta::FromMilliseconds(16)); task_runner->RunPendingTasks(); EXPECT_TRUE(timer->Active()); EXPECT_TRUE(client.TickCalled()); } TEST(DelayBasedTimeSourceTest, TickNotCalledWithTaskPosted) { scoped_refptr<base::TestSimpleTaskRunner> task_runner = new base::TestSimpleTaskRunner; FakeTimeSourceClient client; scoped_refptr<FakeDelayBasedTimeSource> timer = FakeDelayBasedTimeSource::Create(Interval(), task_runner.get()); timer->SetClient(&client); timer->SetActive(true); EXPECT_TRUE(task_runner->HasPendingTask()); timer->SetActive(false); task_runner->RunPendingTasks(); EXPECT_FALSE(client.TickCalled()); } TEST(DelayBasedTimeSourceTest, StartTwiceEnqueuesOneTask) { scoped_refptr<base::TestSimpleTaskRunner> task_runner = new base::TestSimpleTaskRunner; FakeTimeSourceClient client; scoped_refptr<FakeDelayBasedTimeSource> timer = FakeDelayBasedTimeSource::Create(Interval(), task_runner.get()); timer->SetClient(&client); timer->SetActive(true); EXPECT_TRUE(task_runner->HasPendingTask()); task_runner->ClearPendingTasks(); timer->SetActive(true); EXPECT_FALSE(task_runner->HasPendingTask()); } TEST(DelayBasedTimeSourceTest, StartWhenRunningDoesntTick) { scoped_refptr<base::TestSimpleTaskRunner> task_runner = new base::TestSimpleTaskRunner; FakeTimeSourceClient client; scoped_refptr<FakeDelayBasedTimeSource> timer = FakeDelayBasedTimeSource::Create(Interval(), task_runner.get()); timer->SetClient(&client); timer->SetActive(true); EXPECT_TRUE(task_runner->HasPendingTask()); task_runner->RunPendingTasks(); task_runner->ClearPendingTasks(); timer->SetActive(true); EXPECT_FALSE(task_runner->HasPendingTask()); } // At 60Hz, when the tick returns at exactly the requested next time, make sure // a 16ms next delay is posted. TEST(DelayBasedTimeSourceTest, NextDelaySaneWhenExactlyOnRequestedTime) { scoped_refptr<base::TestSimpleTaskRunner> task_runner = new base::TestSimpleTaskRunner; FakeTimeSourceClient client; scoped_refptr<FakeDelayBasedTimeSource> timer = FakeDelayBasedTimeSource::Create(Interval(), task_runner.get()); timer->SetClient(&client); timer->SetActive(true); // Run the first tick. task_runner->RunPendingTasks(); EXPECT_EQ(16, task_runner->NextPendingTaskDelay().InMilliseconds()); timer->SetNow(timer->Now() + Interval()); task_runner->RunPendingTasks(); EXPECT_EQ(16, task_runner->NextPendingTaskDelay().InMilliseconds()); } // At 60Hz, when the tick returns at slightly after the requested next time, // make sure a 16ms next delay is posted. TEST(DelayBasedTimeSourceTest, NextDelaySaneWhenSlightlyAfterRequestedTime) { scoped_refptr<base::TestSimpleTaskRunner> task_runner = new base::TestSimpleTaskRunner; FakeTimeSourceClient client; scoped_refptr<FakeDelayBasedTimeSource> timer = FakeDelayBasedTimeSource::Create(Interval(), task_runner.get()); timer->SetClient(&client); timer->SetActive(true); // Run the first tick. task_runner->RunPendingTasks(); EXPECT_EQ(16, task_runner->NextPendingTaskDelay().InMilliseconds()); timer->SetNow(timer->Now() + Interval() + base::TimeDelta::FromMicroseconds(1)); task_runner->RunPendingTasks(); EXPECT_EQ(16, task_runner->NextPendingTaskDelay().InMilliseconds()); } // At 60Hz, when the tick returns at exactly 2*interval after the requested next // time, make sure a 0ms next delay is posted. TEST(DelayBasedTimeSourceTest, NextDelaySaneWhenExactlyTwiceAfterRequestedTime) { scoped_refptr<base::TestSimpleTaskRunner> task_runner = new base::TestSimpleTaskRunner; FakeTimeSourceClient client; scoped_refptr<FakeDelayBasedTimeSource> timer = FakeDelayBasedTimeSource::Create(Interval(), task_runner.get()); timer->SetClient(&client); timer->SetActive(true); // Run the first tick. task_runner->RunPendingTasks(); EXPECT_EQ(16, task_runner->NextPendingTaskDelay().InMilliseconds()); timer->SetNow(timer->Now() + 2 * Interval()); task_runner->RunPendingTasks(); EXPECT_EQ(0, task_runner->NextPendingTaskDelay().InMilliseconds()); } // At 60Hz, when the tick returns at 2*interval and a bit after the requested // next time, make sure a 16ms next delay is posted. TEST(DelayBasedTimeSourceTest, NextDelaySaneWhenSlightlyAfterTwiceRequestedTime) { scoped_refptr<base::TestSimpleTaskRunner> task_runner = new base::TestSimpleTaskRunner; FakeTimeSourceClient client; scoped_refptr<FakeDelayBasedTimeSource> timer = FakeDelayBasedTimeSource::Create(Interval(), task_runner.get()); timer->SetClient(&client); timer->SetActive(true); // Run the first tick. task_runner->RunPendingTasks(); EXPECT_EQ(16, task_runner->NextPendingTaskDelay().InMilliseconds()); timer->SetNow(timer->Now() + 2 * Interval() + base::TimeDelta::FromMicroseconds(1)); task_runner->RunPendingTasks(); EXPECT_EQ(16, task_runner->NextPendingTaskDelay().InMilliseconds()); } // At 60Hz, when the tick returns halfway to the next frame time, make sure // a correct next delay value is posted. TEST(DelayBasedTimeSourceTest, NextDelaySaneWhenHalfAfterRequestedTime) { scoped_refptr<base::TestSimpleTaskRunner> task_runner = new base::TestSimpleTaskRunner; FakeTimeSourceClient client; scoped_refptr<FakeDelayBasedTimeSource> timer = FakeDelayBasedTimeSource::Create(Interval(), task_runner.get()); timer->SetClient(&client); timer->SetActive(true); // Run the first tick. task_runner->RunPendingTasks(); EXPECT_EQ(16, task_runner->NextPendingTaskDelay().InMilliseconds()); timer->SetNow(timer->Now() + Interval() + base::TimeDelta::FromMilliseconds(8)); task_runner->RunPendingTasks(); EXPECT_EQ(8, task_runner->NextPendingTaskDelay().InMilliseconds()); } // If the timebase and interval are updated with a jittery source, we want to // make sure we do not double tick. TEST(DelayBasedTimeSourceTest, SaneHandlingOfJitteryTimebase) { scoped_refptr<base::TestSimpleTaskRunner> task_runner = new base::TestSimpleTaskRunner; FakeTimeSourceClient client; scoped_refptr<FakeDelayBasedTimeSource> timer = FakeDelayBasedTimeSource::Create(Interval(), task_runner.get()); timer->SetClient(&client); timer->SetActive(true); // Run the first tick. task_runner->RunPendingTasks(); EXPECT_EQ(16, task_runner->NextPendingTaskDelay().InMilliseconds()); // Jitter timebase ~1ms late timer->SetNow(timer->Now() + Interval()); timer->SetTimebaseAndInterval( timer->Now() + base::TimeDelta::FromMilliseconds(1), Interval()); task_runner->RunPendingTasks(); // Without double tick prevention, NextPendingTaskDelay would be 1. EXPECT_EQ(17, task_runner->NextPendingTaskDelay().InMilliseconds()); // Jitter timebase ~1ms early timer->SetNow(timer->Now() + Interval()); timer->SetTimebaseAndInterval( timer->Now() - base::TimeDelta::FromMilliseconds(1), Interval()); task_runner->RunPendingTasks(); EXPECT_EQ(15, task_runner->NextPendingTaskDelay().InMilliseconds()); } TEST(DelayBasedTimeSourceTest, HandlesSignificantTimebaseChangesImmediately) { scoped_refptr<base::TestSimpleTaskRunner> task_runner = new base::TestSimpleTaskRunner; FakeTimeSourceClient client; scoped_refptr<FakeDelayBasedTimeSource> timer = FakeDelayBasedTimeSource::Create(Interval(), task_runner.get()); timer->SetClient(&client); timer->SetActive(true); // Run the first tick. task_runner->RunPendingTasks(); EXPECT_EQ(16, task_runner->NextPendingTaskDelay().InMilliseconds()); // Tick, then shift timebase by +7ms. timer->SetNow(timer->Now() + Interval()); task_runner->RunPendingTasks(); EXPECT_EQ(16, task_runner->NextPendingTaskDelay().InMilliseconds()); client.Reset(); task_runner->ClearPendingTasks(); task_runner->RunPendingTasks(); base::TimeDelta jitter = base::TimeDelta::FromMilliseconds(7) + base::TimeDelta::FromMicroseconds(1); timer->SetTimebaseAndInterval(timer->Now() + jitter, Interval()); EXPECT_FALSE(client.TickCalled()); // Make sure pending tasks were canceled. EXPECT_EQ(16 + 7, task_runner->NextPendingTaskDelay().InMilliseconds()); // Tick, then shift timebase by -7ms. timer->SetNow(timer->Now() + Interval() + jitter); task_runner->RunPendingTasks(); EXPECT_EQ(16, task_runner->NextPendingTaskDelay().InMilliseconds()); client.Reset(); task_runner->ClearPendingTasks(); task_runner->RunPendingTasks(); timer->SetTimebaseAndInterval(base::TimeTicks() + Interval(), Interval()); EXPECT_FALSE(client.TickCalled()); // Make sure pending tasks were canceled. EXPECT_EQ(16 - 7, task_runner->NextPendingTaskDelay().InMilliseconds()); } TEST(DelayBasedTimeSourceTest, HanldlesSignificantIntervalChangesImmediately) { scoped_refptr<base::TestSimpleTaskRunner> task_runner = new base::TestSimpleTaskRunner; FakeTimeSourceClient client; scoped_refptr<FakeDelayBasedTimeSource> timer = FakeDelayBasedTimeSource::Create(Interval(), task_runner.get()); timer->SetClient(&client); timer->SetActive(true); // Run the first tick. task_runner->RunPendingTasks(); EXPECT_EQ(16, task_runner->NextPendingTaskDelay().InMilliseconds()); // Tick, then double the interval. timer->SetNow(timer->Now() + Interval()); task_runner->RunPendingTasks(); EXPECT_EQ(16, task_runner->NextPendingTaskDelay().InMilliseconds()); client.Reset(); task_runner->ClearPendingTasks(); task_runner->RunPendingTasks(); timer->SetTimebaseAndInterval(base::TimeTicks() + Interval(), Interval() * 2); EXPECT_FALSE(client.TickCalled()); // Make sure pending tasks were canceled. EXPECT_EQ(33, task_runner->NextPendingTaskDelay().InMilliseconds()); // Tick, then halve the interval. timer->SetNow(timer->Now() + Interval() * 2); task_runner->RunPendingTasks(); EXPECT_EQ(33, task_runner->NextPendingTaskDelay().InMilliseconds()); client.Reset(); task_runner->ClearPendingTasks(); task_runner->RunPendingTasks(); timer->SetTimebaseAndInterval(base::TimeTicks() + Interval() * 3, Interval()); EXPECT_FALSE(client.TickCalled()); // Make sure pending tasks were canceled. EXPECT_EQ(16, task_runner->NextPendingTaskDelay().InMilliseconds()); } TEST(DelayBasedTimeSourceTest, JitteryRuntimeWithFutureTimebases) { scoped_refptr<base::TestSimpleTaskRunner> task_runner = new base::TestSimpleTaskRunner; FakeTimeSourceClient client; scoped_refptr<FakeDelayBasedTimeSource> timer = FakeDelayBasedTimeSource::Create(Interval(), task_runner.get()); timer->SetClient(&client); timer->SetActive(true); // Run the first tick. task_runner->RunPendingTasks(); EXPECT_EQ(16, task_runner->NextPendingTaskDelay().InMilliseconds()); base::TimeTicks future_timebase = timer->Now() + Interval() * 10; // 1ms jitter base::TimeDelta jitter1 = base::TimeDelta::FromMilliseconds(1); // Tick with +1ms of jitter future_timebase += Interval(); timer->SetTimebaseAndInterval(future_timebase, Interval()); timer->SetNow(timer->Now() + Interval() + jitter1); task_runner->RunPendingTasks(); EXPECT_EQ(15, task_runner->NextPendingTaskDelay().InMilliseconds()); // Tick with 0ms of jitter future_timebase += Interval(); timer->SetTimebaseAndInterval(future_timebase, Interval()); timer->SetNow(timer->Now() + Interval() - jitter1); task_runner->RunPendingTasks(); EXPECT_EQ(16, task_runner->NextPendingTaskDelay().InMilliseconds()); // Tick with -1ms of jitter future_timebase += Interval(); timer->SetTimebaseAndInterval(future_timebase, Interval()); timer->SetNow(timer->Now() + Interval() - jitter1); task_runner->RunPendingTasks(); EXPECT_EQ(17, task_runner->NextPendingTaskDelay().InMilliseconds()); // Tick with 0ms of jitter future_timebase += Interval(); timer->SetTimebaseAndInterval(future_timebase, Interval()); timer->SetNow(timer->Now() + Interval() + jitter1); task_runner->RunPendingTasks(); EXPECT_EQ(16, task_runner->NextPendingTaskDelay().InMilliseconds()); // 8 ms jitter base::TimeDelta jitter8 = base::TimeDelta::FromMilliseconds(8); // Tick with +8ms of jitter future_timebase += Interval(); timer->SetTimebaseAndInterval(future_timebase, Interval()); timer->SetNow(timer->Now() + Interval() + jitter8); task_runner->RunPendingTasks(); EXPECT_EQ(8, task_runner->NextPendingTaskDelay().InMilliseconds()); // Tick with 0ms of jitter future_timebase += Interval(); timer->SetTimebaseAndInterval(future_timebase, Interval()); timer->SetNow(timer->Now() + Interval() - jitter8); task_runner->RunPendingTasks(); EXPECT_EQ(16, task_runner->NextPendingTaskDelay().InMilliseconds()); // Tick with -8ms of jitter future_timebase += Interval(); timer->SetTimebaseAndInterval(future_timebase, Interval()); timer->SetNow(timer->Now() + Interval() - jitter8); task_runner->RunPendingTasks(); EXPECT_EQ(24, task_runner->NextPendingTaskDelay().InMilliseconds()); // Tick with 0ms of jitter future_timebase += Interval(); timer->SetTimebaseAndInterval(future_timebase, Interval()); timer->SetNow(timer->Now() + Interval() + jitter8); task_runner->RunPendingTasks(); EXPECT_EQ(16, task_runner->NextPendingTaskDelay().InMilliseconds()); // 15 ms jitter base::TimeDelta jitter15 = base::TimeDelta::FromMilliseconds(15); // Tick with +15ms jitter future_timebase += Interval(); timer->SetTimebaseAndInterval(future_timebase, Interval()); timer->SetNow(timer->Now() + Interval() + jitter15); task_runner->RunPendingTasks(); EXPECT_EQ(1, task_runner->NextPendingTaskDelay().InMilliseconds()); // Tick with 0ms of jitter future_timebase += Interval(); timer->SetTimebaseAndInterval(future_timebase, Interval()); timer->SetNow(timer->Now() + Interval() - jitter15); task_runner->RunPendingTasks(); EXPECT_EQ(16, task_runner->NextPendingTaskDelay().InMilliseconds()); // Tick with -15ms of jitter future_timebase += Interval(); timer->SetTimebaseAndInterval(future_timebase, Interval()); timer->SetNow(timer->Now() + Interval() - jitter15); task_runner->RunPendingTasks(); EXPECT_EQ(31, task_runner->NextPendingTaskDelay().InMilliseconds()); // Tick with 0ms of jitter future_timebase += Interval(); timer->SetTimebaseAndInterval(future_timebase, Interval()); timer->SetNow(timer->Now() + Interval() + jitter15); task_runner->RunPendingTasks(); EXPECT_EQ(16, task_runner->NextPendingTaskDelay().InMilliseconds()); } TEST(DelayBasedTimeSourceTest, AchievesTargetRateWithNoNoise) { int num_iterations = 10; scoped_refptr<base::TestSimpleTaskRunner> task_runner = new base::TestSimpleTaskRunner; FakeTimeSourceClient client; scoped_refptr<FakeDelayBasedTimeSource> timer = FakeDelayBasedTimeSource::Create(Interval(), task_runner.get()); timer->SetClient(&client); timer->SetActive(true); double total_frame_time = 0.0; for (int i = 0; i < num_iterations; ++i) { int64 delay_ms = task_runner->NextPendingTaskDelay().InMilliseconds(); // accumulate the "delay" total_frame_time += delay_ms / 1000.0; // Run the callback exactly when asked timer->SetNow(timer->Now() + base::TimeDelta::FromMilliseconds(delay_ms)); task_runner->RunPendingTasks(); } double average_interval = total_frame_time / static_cast<double>(num_iterations); EXPECT_NEAR(1.0 / 60.0, average_interval, 0.1); } TEST(DelayBasedTimeSourceTest, TestDeactivateWhilePending) { scoped_refptr<base::TestSimpleTaskRunner> task_runner = new base::TestSimpleTaskRunner; FakeTimeSourceClient client; scoped_refptr<FakeDelayBasedTimeSource> timer = FakeDelayBasedTimeSource::Create(Interval(), task_runner.get()); timer->SetClient(&client); timer->SetActive(true); // Should post a task. timer->SetActive(false); timer = NULL; // Should run the posted task without crashing. EXPECT_TRUE(task_runner->HasPendingTask()); task_runner->RunPendingTasks(); } TEST(DelayBasedTimeSourceTest, TestDeactivateAndReactivateBeforeNextTickTime) { scoped_refptr<base::TestSimpleTaskRunner> task_runner = new base::TestSimpleTaskRunner; FakeTimeSourceClient client; scoped_refptr<FakeDelayBasedTimeSource> timer = FakeDelayBasedTimeSource::Create(Interval(), task_runner.get()); timer->SetClient(&client); // Should run the activate task, and pick up a new timebase. timer->SetActive(true); task_runner->RunPendingTasks(); // Stop the timer timer->SetActive(false); // Task will be pending anyway, run it task_runner->RunPendingTasks(); // Start the timer again, but before the next tick time the timer previously // planned on using. That same tick time should still be targeted. timer->SetNow(timer->Now() + base::TimeDelta::FromMilliseconds(4)); timer->SetActive(true); EXPECT_EQ(12, task_runner->NextPendingTaskDelay().InMilliseconds()); } TEST(DelayBasedTimeSourceTest, TestDeactivateAndReactivateAfterNextTickTime) { scoped_refptr<base::TestSimpleTaskRunner> task_runner = new base::TestSimpleTaskRunner; FakeTimeSourceClient client; scoped_refptr<FakeDelayBasedTimeSource> timer = FakeDelayBasedTimeSource::Create(Interval(), task_runner.get()); timer->SetClient(&client); // Should run the activate task, and pick up a new timebase. timer->SetActive(true); task_runner->RunPendingTasks(); // Stop the timer. timer->SetActive(false); // Task will be pending anyway, run it. task_runner->RunPendingTasks(); // Start the timer again, but before the next tick time the timer previously // planned on using. That same tick time should still be targeted. timer->SetNow(timer->Now() + base::TimeDelta::FromMilliseconds(20)); timer->SetActive(true); EXPECT_EQ(13, task_runner->NextPendingTaskDelay().InMilliseconds()); } TEST(DelayBasedTimeSourceTest, TestReturnValueWhenTimerIsDeActivated) { scoped_refptr<base::TestSimpleTaskRunner> task_runner = new base::TestSimpleTaskRunner; FakeTimeSourceClient client; scoped_refptr<FakeDelayBasedTimeSource> timer = FakeDelayBasedTimeSource::Create(Interval(), task_runner.get()); timer->SetClient(&client); timer->SetActive(true); task_runner->RunPendingTasks(); // SetActive should return empty TimeTicks when the timer is deactivated. base::TimeTicks missed_tick_time = timer->SetActive(false); EXPECT_TRUE(missed_tick_time.is_null()); } } // namespace } // namespace cc
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. */ #include <cassert> #include <sstream> #include <stdexcept> #include <vector> #include "inference/module/ModuleParameter.h" namespace w2l { namespace streaming { ModuleParameter::ModuleParameter( DataType type, const void* buffer, int nElements) : type_(type), buffer_(buffer, nElements * dataTypeNumberOfBytes(type)) { if (nElements < 0) { std::stringstream ss; ss << "Invalid nElements at ModuleParameter::ModuleParameter(type=" << dataTypeString(type) << " nElements=" << nElements << ")"; throw std::invalid_argument(ss.str()); } } ModuleParameter::ModuleParameter() : ModuleParameter(DataType::UNINITIALIZED, nullptr, 0) {} std::string ModuleParameter::debugString() const { std::stringstream ss; ss << "ModuleParameter:{type_=" << dataTypeString(type_) << " buffer_=" << buffer_.debugString() << "}"; return ss.str(); } } // namespace streaming } // namespace w2l
// MadronaLib: a C++ framework for DSP applications. // Copyright (c) 2013 Madrona Labs LLC. http://www.madronalabs.com // Distributed under the MIT license: http://madrona-labs.mit-license.org/ #include "MLProc.h" // ---------------------------------------------------------------- // class definition class MLProcGlide : public MLProc { public: MLProcGlide(); ~MLProcGlide(); void clear(); void process(const int n); MLProcInfoBase& procInfo() { return mInfo; } private: MLProcInfo<MLProcGlide> mInfo; void calcCoeffs(void); // coeffs MLSample mY1; MLSample mEndValue; int mRampTimeInSamples; MLSample mInvRampTimeInSamples; MLSample mStep; bool mActive; }; // ---------------------------------------------------------------- // registry section namespace { MLProcRegistryEntry<MLProcGlide> classReg("glide"); ML_UNUSED MLProcParam<MLProcGlide> params[1] = { "time" }; ML_UNUSED MLProcInput<MLProcGlide> inputs[] = { "in" }; ML_UNUSED MLProcOutput<MLProcGlide> outputs[] = { "out" }; } // ---------------------------------------------------------------- // implementation MLProcGlide::MLProcGlide() { setParam("time", 1.f); } MLProcGlide::~MLProcGlide() { } void MLProcGlide::calcCoeffs(void) { const float t = getParam("time") + 0.001f; const float sr = getContextSampleRate(); mRampTimeInSamples = (int)(sr*t); mInvRampTimeInSamples = 1.f / (float)mRampTimeInSamples; mParamsChanged = false; } void MLProcGlide::clear() { mY1 = 0.f; mStep = 0.f; mEndValue = 0.f; mActive= false; } void MLProcGlide::process(const int samples) { const MLSignal& x = getInput(1); MLSignal& y = getOutput(); float in; float signBeforeAdd, signAfterAdd; if (mParamsChanged) calcCoeffs(); for (int n=0; n<samples; ++n) { in = x[n]; // TODO constant input if (in != mEndValue) { mEndValue = in; mStep = (mEndValue - mY1) * mInvRampTimeInSamples; mActive = true; } if(mActive) { signBeforeAdd = sign(mY1 - mEndValue); mY1 += mStep; signAfterAdd = sign(mY1 - mEndValue); if (signAfterAdd != signBeforeAdd) { mY1 = mEndValue; mActive = false; } } y[n] = mY1; } }
/****************************************************************************** * The MIT License (MIT) * * Copyright (c) 2017-2019 Baldur Karlsson * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. ******************************************************************************/ #include "core/plugins.h" #include "os/os_specific.h" #include "strings/string_utils.h" std::string LocatePluginFile(const std::string &path, const std::string &fileName) { std::string ret; std::string libpath; FileIO::GetLibraryFilename(libpath); libpath = get_dirname(libpath); std::vector<std::string> paths; #if defined(RENDERDOC_PLUGINS_PATH) string customPath(RENDERDOC_PLUGINS_PATH); if(FileIO::IsRelativePath(customPath)) customPath = libpath + "/" + customPath; paths.push_back(customPath); #endif // windows installation paths.push_back(libpath + "/plugins"); // linux installation paths.push_back(libpath + "/../share/renderdoc/plugins"); // also search the appropriate OS-specific location in the root #if ENABLED(RDOC_WIN32) && ENABLED(RDOC_X64) paths.push_back(libpath + "/../../plugins-win64"); #endif #if ENABLED(RDOC_WIN32) && DISABLED(RDOC_X64) paths.push_back(libpath + "/../../plugins-win32"); #endif #if ENABLED(RDOC_LINUX) paths.push_back(libpath + "/../../plugins-linux64"); #endif // there is no standard path for local builds as we don't provide these plugins in the repository // directly. As a courtesy we search the root of the build, from the executable. The user can // always put the plugins folder relative to the exe where it would be in an installation too. paths.push_back(libpath + "/../../plugins"); // in future maybe we want to search a user-specific plugins folder? Like ~/.renderdoc/ on linux // or %APPDATA%/renderdoc on windows? for(uint32_t i = 0; i < paths.size(); i++) { std::string check = paths[i] + "/" + path + "/" + fileName; if(FileIO::exists(check.c_str())) { ret = check; break; } } // if we didn't find it anywhere, just try running it directly in case it's in the PATH if(ret.empty()) ret = fileName; return ret; }
//#include <iostream> // //using namespace std; // //int main() { // int x, y[1000]; // cin >> x; // // for (int i = 0, j = 0; i < 1000; i++, j++) { // if (j == x) j = 0; // cout << "N[" << i << "] = " << j << endl; // } // // return 0; //}
/* * ModSecurity, http://www.modsecurity.org/ * Copyright (c) 2015 - 2020 Trustwave Holdings, Inc. (http://www.trustwave.com/) * * You may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * If any of the files related to licensing are missing or if you have any * other questions related to licensing please contact Trustwave Holdings, Inc. * directly using the email address security@modsecurity.org. * */ #include "src/actions/transformations/url_decode.h" #include <iostream> #include <string> #include <algorithm> #include <functional> #include <cctype> #include <locale> #include <cstring> #include "modsecurity/transaction.h" #include "src/actions/transformations/transformation.h" #include "src/utils/decode.h" namespace modsecurity { namespace actions { namespace transformations { UrlDecode::UrlDecode(const std::string &action) : Transformation(action) { this->action_kind = 1; } std::string UrlDecode::evaluate(std::string value, Transaction *transaction) { unsigned char *val = NULL; int invalid_count = 0; int changed; val = (unsigned char *) malloc(sizeof(char) * value.size() + 1); memcpy(val, value.c_str(), value.size() + 1); val[value.size()] = '\0'; int size = utils::urldecode_nonstrict_inplace(val, value.size(), &invalid_count, &changed); std::string out; out.append((const char *)val, size); free(val); return out; } } // namespace transformations } // namespace actions } // namespace modsecurity
#include <iostream> #include <unistd.h> #include "option_parse.h" void Options::initialize(Algo algo, int argc, char** argv) { switch(algo) { case Algo::dynamique: case Algo::vorace: { int opt; while((opt = getopt(argc, argv, "pf:")) != -1) { switch(opt) { case 'p': verbose_p = true; break; case 'f': filename = optarg; break; } } if(filename == nullptr) { std::cerr << "Usage: \n" << " -p Affiche les resultats\n" << " -f <filename> Examplaire" << std::endl; exit(1); } } break; case Algo::recuit_simule: initialize_recuit(argc, argv); break; } } Options::~Options() { delete exemplaire; } void Options::initialize_recuit(int argc, char ** argv){ int opt; k_max = 1000; t = 1.0; p = 100; a = 0.9; while((opt = getopt(argc, argv, "k:t:l:a:pf:")) != -1) { switch(opt) { case 'p': verbose_p = true; break; case 'f': filename = optarg; break; case 'k': k_max = std::stoi(optarg); break; case 't': t = std::stof(optarg); break; case 'l': p = std::stoi(optarg); break; case 'a': a = std::stof(optarg); break; } } // TODO assert for given value if(filename == nullptr) { std::cerr << "Usage: \n" << " -k <int> nombre de pas maximums, valeur par default 1000\n" << " -t <float> temperature initial, valeur par defaut 1.0\n" << " -l <int> palier de refroidissement, valeur par default 100\n" << " -a <float> coeficient de refroidissement, valeur par default 0.9\n" << " -p Affiche les resultats\n" << " -f <filename> Examplaire" << std::endl; exit(1); } }
#include "tests.h" #pragma warning(disable: 4474) bool gbVerifyFailed = false; bool gbVerifyStepFailed = false; bool gbVerifyVerbose = false; bool gbVerifyIgnoreAsserts = false; bool FileExistsMock(const wchar_t* asFilePath, uint64_t * pnSize, bool& result) { return false; } bool SearchPathMock(LPCWSTR path, LPCWSTR fileName, LPCWSTR extension, CEStr& resultPath, int& rc) { return false; } int main(int argc, char** argv) { HeapInitialize(); for (int i=0; i<argc; i++) { if (strcmp(argv[i], "-verbose")==0 || strcmp(argv[i], "--verbose")==0) gbVerifyVerbose = true; } // Tests { Verify_Step("CEStr condition checks"); CEStr lsVal; Verify0((!lsVal),"{NULL} (!ls_Val)"); Verify0((lsVal.IsEmpty()),"{NULL} (ls_Val.IsEmpty())"); lsVal = L""; Verify0((!lsVal),"{\"\"} (!ls_Val)"); Verify0((lsVal.IsEmpty()),"{\"\"} (ls_Val.IsEmpty())"); lsVal = L"abc"; Verify0((lsVal),"{\"abc\"} (ls_Val)"); Verify0((!lsVal.IsEmpty()),"{\"abc\"} (!ls_Val.IsEmpty()) "); } { Verify_Step("CEStr ctor_1"); CEStr ls1; ls1.Set(L"Test"); CEStr ls2(ls1); Verify0((ls1.ms_Val && ls2.ms_Val && ls1.ms_Val!=ls2.ms_Val),"ls1.ms_Val!=ls2.ms_Val)"); } { Verify_Step("CEStr ctor_2"); CEStr ls1; ls1.Set(L"Test"); CEStr ls2 = ls1; Verify0((ls1.ms_Val && ls2.ms_Val && ls1.ms_Val!=ls2.ms_Val),"ls1.ms_Val!=ls2.ms_Val)"); } { Verify_Step("CEStr assign_1"); CEStr ls1; ls1.Set(L"Test"); CEStr ls2(ls1.ms_Val); Verify0((ls1.ms_Val && ls2.ms_Val && ls1.ms_Val!=ls2.ms_Val),"ls1.ms_Val!=ls2.ms_Val)"); } { Verify_Step("CEStr assign_2"); CEStr ls1; ls1.Set(L"Test"); CEStr ls2 = ls1.ms_Val; Verify0((ls1.ms_Val && ls2.ms_Val && ls1.ms_Val!=ls2.ms_Val),"ls1.ms_Val!=ls2.ms_Val)"); } { Verify_Step("ls1(`Test`)"); CEStr ls1(L"Test"); Verify0((ls1.ms_Val && 0==wcscmp(ls1.ms_Val,L"Test")),"ls1==`Test`"); Verify_Step("ls12 = ls1.Detach()"); /* Store ptr for Verify test result */ LPCWSTR pszPtr = ls1.ms_Val; CEStr ls2 = ls1.Detach(); Verify2((ls2.ms_Val && !ls1.ms_Val && ls2.ms_Val==pszPtr),"ls2.ms_Val{x%p}==pszPtr{x%p}",ls2.ms_Val,pszPtr); } { Verify_Step("ls3 = `Test3`"); CEStr ls3 = L"Test3"; Verify0((ls3.ms_Val && 0==wcscmp(ls3.ms_Val,L"Test3")),"ls3==`Test3`"); Verify_Step("ls4 = (LPCWSTR)ls3.ms_Val"); CEStr ls4 = static_cast<LPCWSTR>(ls3.ms_Val); Verify2((ls4.ms_Val && ls4.ms_Val != ls3.ms_Val),"ls4.ms_Val{x%p}!=ls3.ms_Val{x%p}",ls4.ms_Val,ls3.ms_Val); Verify_Step("ls5 = lstrdup(ls3)"); CEStr ls5 = lstrdup(ls3); Verify0((ls5.ms_Val && 0==wcscmp(ls5.ms_Val,L"Test3")),"ls5==`Test3`"); Verify_Step("ls6(lstrdup(ls3))"); CEStr ls6(lstrdup(ls3)); Verify0((ls6.ms_Val && 0==wcscmp(ls6.ms_Val,L"Test3")),"ls6==`Test3`"); } { Verify_Step("NextArg and Switch comparison"); LPCWSTR pszCmd = L"conemu.exe /c/dir -run -inside=0x800 /cmdlist \"-inside=\\eCD /d %1\" -bad|switch "; CmdArg ls; Verify0(((pszCmd=NextArg(pszCmd,ls))),"NextArg conemu.exe"); Verify0((!ls.IsPossibleSwitch()),"!IsPossibleSwitch()"); Verify0(((pszCmd=NextArg(pszCmd,ls))),"NextArg /c/dir"); Verify0((!ls.IsPossibleSwitch()),"!IsPossibleSwitch()"); Verify0(((pszCmd=NextArg(pszCmd,ls))),"NextArg -run"); Verify0((ls.OneOfSwitches(L"/cmd",L"/run")),"OneOfSwitches(/cmd,/run)"); Verify0((!ls.OneOfSwitches(L"/cmd",L"/cmdlist")),"!OneOfSwitches(/cmd,/cmdlist)"); Verify0((ls.IsSwitch(L"-run")),"IsSwitch(-run)"); Verify0(((pszCmd=NextArg(pszCmd,ls))),"NextArg -inside=0x800"); Verify0((ls.IsSwitch(L"-inside=")),"IsSwitch(-inside=)"); Verify0((ls.OneOfSwitches(L"-inside",L"-inside=")),"OneOfSwitches(-inside,-inside=)"); Verify0((!ls.IsSwitch(L"-inside")),"!IsSwitch(-inside)"); Verify0(((pszCmd=NextArg(pszCmd,ls))),"NextArg /cmdlist"); Verify0((ls.IsSwitch(L"-cmdlist")),"IsSwitch(-cmdlist)"); Verify0(((pszCmd=NextArg(pszCmd,ls))),"NextArg \"-inside=\\eCD /d %%1\""); Verify0((ls.IsSwitch(L"-inside:")),"IsSwitch(-inside=)"); Verify0(((pszCmd=NextArg(pszCmd,ls))),"NextArg -bad|switch"); Verify0((ls.Compare(L"-bad|switch")==0),"Compare(-bad|switch)"); Verify0((!ls.IsPossibleSwitch()),"!IsPossibleSwitch"); } { Verify_Step("-new_console parser tests"); LPCWSTR pszTest = L"-new_console:a \\\"-new_console:c\\\" `-new_console:d:C:\\` -cur_console:b"; LPCWSTR pszCmp = L"\\\"-new_console:c\\\" `-new_console:d:C:\\`"; RConStartArgsEx arg; arg.pszSpecialCmd = lstrdup(pszTest); arg.ProcessNewConArg(); int iCmp = lstrcmp(arg.pszSpecialCmd, pszCmp); Verify0((iCmp==0),"arg.pszSpecialCmd==\\\"-new_console:c\\\" `-new_console:d:C:\\`"); Verify_Step("RConStartArgsEx::RunArgTests()"); //RConStartArgsEx::RunArgTests(); Verify0(!gbVerifyStepFailed,"RConStartArgsEx tests passed"); } { Verify_Step("msprintf tests"); wchar_t szBuffer[200]; msprintf(szBuffer, countof(szBuffer), L"%u %03u %03u %i %x %02X %02X %04x %08X", 123, 98, 4567, -234, 0x12AB, 0x0A, 0xABC, 0x01A0, 0x0765ABCD); const wchar_t szStd[] = L"123 098 4567 -234 12ab 0A ABC 01a0 0765ABCD"; int iCmp = lstrcmp(szBuffer, szStd); WVerify2((iCmp==0),L"`%s` (msprintf[W])\n `%s` (standard)", szBuffer, szStd); char szBufA[200]; msprintf(szBufA, countof(szBufA), "%u %i %x %02X %02X %04x %08X", 123, -234, 0x12AB, 0x0A, 0xABC, 0x01A0, 0x0765ABCD); const char szStdA[] = "123 -234 12ab 0A ABC 01a0 0765ABCD"; iCmp = lstrcmpA(szBufA, szStdA); Verify2((iCmp==0),"`%s` (msprintf[A])\n `%s` (standard)", szBufA, szStdA); } if (gbVerifyFailed) Verify_MsgFail("Some tests failed!"); else Verify_MsgOk("All done"); return gbVerifyFailed ? 99 : 0; }
//===- PreprocessorLexer.cpp - C Language Family Lexer --------------------===// // // 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 // //===----------------------------------------------------------------------===// // // This file implements the PreprocessorLexer and Token interfaces. // //===----------------------------------------------------------------------===// #include "clang/Lex/PreprocessorLexer.h" #include "clang/Basic/SourceManager.h" #include "clang/Lex/LexDiagnostic.h" #include "clang/Lex/Preprocessor.h" #include "clang/Lex/Token.h" #include <cassert> using namespace clang; void PreprocessorLexer::anchor() {} PreprocessorLexer::PreprocessorLexer(Preprocessor *pp, FileID fid) : PP(pp), FID(fid) { if (pp) InitialNumSLocEntries = pp->getSourceManager().local_sloc_entry_size(); } /// After the preprocessor has parsed a \#include, lex and /// (potentially) macro expand the filename. void PreprocessorLexer::LexIncludeFilename(Token &FilenameTok) { assert(ParsingPreprocessorDirective && ParsingFilename == false && "Must be in a preprocessing directive!"); // We are now parsing a filename! ParsingFilename = true; // Lex the filename. if (LexingRawMode) IndirectLex(FilenameTok); else PP->Lex(FilenameTok); // We should have obtained the filename now. ParsingFilename = false; // No filename? if (FilenameTok.is(tok::eod)) PP->Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename); } /// getFileEntry - Return the FileEntry corresponding to this FileID. Like /// getFileID(), this only works for lexers with attached preprocessors. const FileEntry *PreprocessorLexer::getFileEntry() const { return PP->getSourceManager().getFileEntryForID(getFileID()); }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /*! * \file src/ir/function.cc * \brief The function data structure. */ #include <tvm/ir/function.h> #include <tvm/runtime/registry.h> // NOTE: reverse dependency on relay, tir/ // These dependencies do not happen at the interface-level, // and are only used in minimum cases where they are clearly marked. // // Rationale: We calls into the type specific WithAttr function #include <tvm/relax/expr.h> #include <tvm/relay/function.h> #include <tvm/tir/function.h> namespace tvm { TVM_REGISTER_GLOBAL("ir.BaseFunc_Attrs").set_body_typed([](BaseFunc func) { return func->attrs; }); TVM_REGISTER_GLOBAL("ir.BaseFuncCopy").set_body_typed([](BaseFunc func) { return func; }); TVM_REGISTER_GLOBAL("ir.BaseFuncWithAttr") .set_body_typed([](BaseFunc func, String key, ObjectRef value) -> BaseFunc { if (func->IsInstance<tir::PrimFuncNode>()) { return WithAttr(Downcast<tir::PrimFunc>(std::move(func)), key, value); } else if (func->IsInstance<relay::FunctionNode>()) { return WithAttr(Downcast<relay::Function>(std::move(func)), key, value); } else if (func->IsInstance<relax::FunctionNode>()) { return WithAttr(Downcast<relax::Function>(std::move(func)), key, value); } else { LOG(FATAL) << "Do not support function type " << func->GetTypeKey(); return func; } }); } // namespace tvm
// $Id$ /* Copyright (c) 2007-2015, Trustees of The Leland Stanford Junior University All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "booksim.hpp" #include <iostream> #include "selalloc.hpp" #include "random_utils.hpp" //#define DEBUG_SELALLOC SelAlloc::SelAlloc( Module *parent, const string& name, int inputs, int outputs, int iters, Module *clock ) : SparseAllocator( parent, name, inputs, outputs, clock ) { _iter = iters; _gptrs.resize(outputs, 0); _aptrs.resize(inputs, 0); _outmask.resize(outputs, 0); } void SelAlloc::Allocate( ) { int input; int output; int input_offset; int output_offset; map<int, sRequest>::iterator p; set<int>::iterator outer_iter; bool wrapped; int max_index; int max_pri; vector<int> grants(_outputs, -1); for ( int iter = 0; iter < _iter; ++iter ) { // Grant phase for( outer_iter = _out_occ.begin( ); outer_iter != _out_occ.end( ); ++outer_iter ) { output = *outer_iter; // Skip loop if there are no requests // or the output is already matched or // the output is masked if ( ( _out_req[output].empty( ) ) || ( _outmatch[output] != -1 ) || ( _outmask[output] != 0 ) ) { continue; } // A round-robin arbiter between input requests input_offset = _gptrs[output]; p = _out_req[output].begin( ); while( ( p != _out_req[output].end( ) ) && ( p->second.port < input_offset ) ) { p++; } max_index = -1; max_pri = 0; wrapped = false; while( (!wrapped) || ( ( p != _out_req[output].end() ) && ( p->second.port < input_offset ) ) ) { if ( p == _out_req[output].end( ) ) { if ( wrapped ) { break; } // p is valid here because empty lists // are skipped (above) p = _out_req[output].begin( ); wrapped = true; } input = p->second.port; // we know the output is free (above) and // if the input is free, check if request is the // highest priority so far if ( ( _inmatch[input] == -1 ) && ( ( p->second.out_pri > max_pri ) || ( max_index == -1 ) ) ) { max_pri = p->second.out_pri; max_index = input; } p++; } if ( max_index != -1 ) { // grant grants[output] = max_index; } } #ifdef DEBUG_SELALLOC cout << "grants: "; for ( int i = 0; i < _outputs; ++i ) { cout << grants[i] << " "; } cout << endl; cout << "aptrs: "; for ( int i = 0; i < _inputs; ++i ) { cout << _aptrs[i] << " "; } cout << endl; #endif // Accept phase for ( outer_iter = _in_occ.begin( ); outer_iter != _in_occ.end( ); ++outer_iter ) { input = *outer_iter; if ( _in_req[input].empty( ) ) { continue; } // A round-robin arbiter between output grants output_offset = _aptrs[input]; p = _in_req[input].begin( ); while( ( p != _in_req[input].end( ) ) && ( p->second.port < output_offset ) ) { p++; } max_index = -1; max_pri = 0; wrapped = false; while( (!wrapped) || ( ( p != _in_req[input].end() ) && ( p->second.port < output_offset ) ) ) { if ( p == _in_req[input].end( ) ) { if ( wrapped ) { break; } // p is valid here because empty lists // are skipped (above) p = _in_req[input].begin( ); wrapped = true; } output = p->second.port; // we know the output is free (above) and // if the input is free, check if the highest // priroity if ( ( grants[output] == input ) && ( !_out_req[output].empty( ) ) && ( ( p->second.in_pri > max_pri ) || ( max_index == -1 ) ) ) { max_pri = p->second.in_pri; max_index = output; } p++; } if ( max_index != -1 ) { // Accept output = max_index; _inmatch[input] = output; _outmatch[output] = input; // Only update pointers if accepted during the 1st iteration if ( iter == 0 ) { _gptrs[output] = ( input + 1 ) % _inputs; _aptrs[input] = ( output + 1 ) % _outputs; } } } } #ifdef DEBUG_SELALLOC cout << "input match: "; for ( int i = 0; i < _inputs; ++i ) { cout << _inmatch[i] << " "; } cout << endl; cout << "output match: "; for ( int j = 0; j < _outputs; ++j ) { cout << _outmatch[j] << " "; } cout << endl; #endif } void SelAlloc::MaskOutput( int out, int mask ) { assert( ( out >= 0 ) && ( out < _outputs ) ); _outmask[out] = mask; } void SelAlloc::PrintRequests( ostream * os ) const { map<int, sRequest>::const_iterator iter; if(!os) os = &cout; *os << "Input requests = [ "; for ( int input = 0; input < _inputs; ++input ) { *os << input << " -> [ "; for ( iter = _in_req[input].begin( ); iter != _in_req[input].end( ); iter++ ) { *os << iter->second.port << " "; } *os << "] "; } *os << "], output requests = [ "; for ( int output = 0; output < _outputs; ++output ) { *os << output << " -> "; if ( _outmask[output] == 0 ) { *os << "[ "; for ( iter = _out_req[output].begin( ); iter != _out_req[output].end( ); iter++ ) { *os << iter->second.port << " "; } *os << "] "; } else { *os << "masked "; } } *os << "]." << endl; }
/** * Licensed to Green Energy Corp (www.greenenergycorp.com) under one or * more contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright ownership. * Green Energy Corp licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * This project was forked on 01/01/2013 by Automatak, LLC and modifications * may have been made to this file. Automatak, LLC licenses these modifications * to you under the terms of the License. */ #include "ReadHandler.h" namespace opendnp3 { ReadHandler::ReadHandler(openpal::Logger logger, IStaticSelector& staticSelector, IEventSelector& eventSelector) : APDUHandlerBase(logger), pStaticSelector(&staticSelector), pEventSelector(&eventSelector) { } IINField ReadHandler::ProcessAllObjects(const HeaderRecord& record) { switch (record.type) { case(GroupVariationType::STATIC) : return pStaticSelector->SelectAll(record.enumeration); case(GroupVariationType::EVENT) : return pEventSelector->SelectAll(record.enumeration); default: return IINField(IINBit::FUNC_NOT_SUPPORTED); } } IINField ReadHandler::ProcessRangeRequest(const HeaderRecord& record, const Range& range) { return pStaticSelector->SelectRange(record.enumeration, range); } IINField ReadHandler::ProcessCountRequest(const HeaderRecord& record, uint16_t count) { return pEventSelector->SelectCount(record.enumeration, count); } }
/******************************************************************************* * Copyright (c) 2015-2018 Skymind, Inc. * * This program and the accompanying materials are made available under the * terms of the Apache License, Version 2.0 which is available at * https://www.apache.org/licenses/LICENSE-2.0. * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. * * SPDX-License-Identifier: Apache-2.0 ******************************************************************************/ // // @author raver119@gmail.com // #include <helpers/Loops.h> #include <system/pointercast.h> #include <types/types.h> using namespace simdOps; namespace sd { template<typename X, typename Z> template <typename OpType> void Reduction3Loops<X,Z>::innerloopReduce3(X* x, Nd4jLong* xShapeInfo, X* y, Nd4jLong* yShapeInfo, Z* z, Nd4jLong* zShapeInfo, int* dims, int dimsLen, Z* extraParams, int64_t start, int64_t stop) { #ifndef INLINE_LOOPS Reduction3Loops<X,Z>::template loopReduce3<OpType>(x, xShapeInfo, y, yShapeInfo, z, zShapeInfo, dims, dimsLen, extraParams, start, stop); #endif } template<typename X, typename Z> template <typename OpType> void Reduction3Loops<X,Z>::innerloopReduce3All(X* x, Nd4jLong* xShapeInfo, X* y, Nd4jLong* yShapeInfo, Z* z, Nd4jLong* zShapeInfo, Nd4jLong* xTadShapeInfo, Nd4jLong* xTadOffsets, Nd4jLong* yTadShapeInfo, Nd4jLong* yTadOffsets, Z* extraParams, int64_t start, int64_t stop) { #ifndef INLINE_LOOPS Reduction3Loops<X,Z>::template loopReduce3All<OpType>(x, xShapeInfo, y, yShapeInfo, z, zShapeInfo, xTadShapeInfo, xTadOffsets, yTadShapeInfo, yTadOffsets, extraParams, start, stop); #endif } template<typename X, typename Y> void Reduction3Loops<X, Y>::wrapper(const int opNum, X *x, Nd4jLong *xShapeInfo, X *y, Nd4jLong *yShapeInfo, Y *z, Nd4jLong *zShapeInfo, int* dims, int dimsLen, Y *extraParams, int64_t start, int64_t stop) { #ifndef INLINE_LOOPS DISPATCH_BY_OPNUM_TT(innerloopReduce3, PARAMS(x, xShapeInfo, y, yShapeInfo, z, zShapeInfo, dims, dimsLen, extraParams, start, stop), REDUCE3_OPS); #endif } template<typename X, typename Y> void Reduction3Loops<X, Y>::wrapperAll(const int opNum, X *x, Nd4jLong *xShapeInfo, X *y, Nd4jLong *yShapeInfo, Y *z, Nd4jLong *zShapeInfo, Nd4jLong* xTadShapeInfo, Nd4jLong* xTadOffsets, Nd4jLong* yTadShapeInfo, Nd4jLong* yTadOffsets, Y* extraParams, int64_t start, int64_t stop) { #ifndef INLINE_LOOPS DISPATCH_BY_OPNUM_TT(innerloopReduce3All, PARAMS(x, xShapeInfo, y, yShapeInfo, z, zShapeInfo, xTadShapeInfo, xTadOffsets, yTadShapeInfo, yTadOffsets, extraParams, start, stop), REDUCE3_OPS); #endif } BUILD_DOUBLE_TEMPLATE(template class ND4J_EXPORT Reduction3Loops, , LIBND4J_TYPES, FLOAT_TYPES_0); }
/* Author: Jason Williams <jdw@cromulence.com> Copyright (c) 2014 Cromulence LLC Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "cgc_common.h" DLQueue::DLQueue( ) : m_pFirst( NULL ), m_pLast( NULL ), m_count( 0 ) { } DLQueue::~DLQueue( ) { DeleteAll(); } void DLQueue::AddFirst( DLItem *pItem ) { if ( pItem == NULL ) return; if ( m_pFirst == NULL ) { pItem->m_pNext = NULL; pItem->m_pPrev = NULL; m_pFirst = pItem; m_pLast = pItem; } else { pItem->m_pNext = m_pFirst; pItem->m_pPrev = NULL; m_pFirst->m_pPrev = pItem; m_pFirst = pItem; } // Increment count m_count++; } void DLQueue::AddLast( DLItem *pItem ) { if ( pItem == NULL ) return; if ( m_pLast == NULL ) { pItem->m_pNext = NULL; pItem->m_pPrev = NULL; m_pFirst = pItem; m_pLast = pItem; } else { pItem->m_pNext = NULL; pItem->m_pPrev = m_pLast; m_pLast->m_pNext = pItem; m_pLast = pItem; } // Increment count m_count++; } void DLQueue::AddAfter( DLItem *pPrev, DLItem *pItem ) { if ( pPrev == NULL || pItem == NULL ) return; pItem->m_pNext = pPrev->m_pNext; pItem->m_pPrev = pPrev; if ( pPrev->m_pNext ) pPrev->m_pNext->m_pPrev = pItem; pPrev->m_pNext = pItem; if ( m_pLast == pPrev ) m_pLast = pItem; // Increment count m_count++; } void DLQueue::Unlink( DLItem *pItem ) { if ( pItem->m_pNext ) pItem->m_pNext->m_pPrev = pItem->m_pPrev; if ( pItem->m_pPrev ) pItem->m_pPrev->m_pNext = pItem->m_pNext; if ( m_pFirst == pItem ) m_pFirst = pItem->m_pNext; if ( m_pLast == pItem ) m_pLast = pItem->m_pPrev; m_count--; } void DLQueue::DeleteItem( DLItem *pItem ) { Unlink( pItem ); delete pItem; } void DLQueue::RemoveItem( DLItem *pItem ) { Unlink( pItem ); } DLItem *DLQueue::RemoveFirst( void ) { DLItem *pItem = m_pFirst; Unlink( pItem ); return (pItem); } DLItem *DLQueue::RemoveLast( void ) { DLItem *pItem = m_pLast; Unlink( pItem ); return (pItem); } void DLQueue::DeleteAll( void ) { // Fast delete all items DLItem *pCur = m_pFirst; DLItem *pNext = NULL; for ( ; pCur; pCur = pNext ) { pNext = pCur->m_pNext; delete pCur; } m_count = 0; m_pFirst = m_pLast = NULL; }
// Copyright (c) 2005-2014 Code Synthesis Tools CC // // This program was generated by CodeSynthesis XSD, an XML Schema to // C++ data binding compiler. // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License version 2 as // published by the Free Software Foundation. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA // // In addition, as a special exception, Code Synthesis Tools CC gives // permission to link this program with the Xerces-C++ library (or with // modified versions of Xerces-C++ that use the same license as Xerces-C++), // and distribute linked combinations including the two. You must obey // the GNU General Public License version 2 in all respects for all of // the code used other than Xerces-C++. If you modify this copy of the // program, you may extend this exception to your version of the program, // but you are not obligated to do so. If you do not wish to do so, delete // this exception statement from your version. // // Furthermore, Code Synthesis Tools CC makes a special exception for // the Free/Libre and Open Source Software (FLOSS) which is described // in the accompanying FLOSSE file. // // Begin prologue. // // // End prologue. #include <xsd/cxx/pre.hxx> #include "SimDistributionPort_SteamFlowPort_Steam_InOrOut.hxx" namespace schema { namespace simxml { namespace ResourcesGeneral { // SimDistributionPort_SteamFlowPort_Steam_InOrOut // } } } #include <xsd/cxx/xml/dom/parsing-source.hxx> #include <xsd/cxx/tree/type-factory-map.hxx> namespace _xsd { static const ::xsd::cxx::tree::type_factory_plate< 0, char > type_factory_plate_init; } namespace schema { namespace simxml { namespace ResourcesGeneral { // SimDistributionPort_SteamFlowPort_Steam_InOrOut // SimDistributionPort_SteamFlowPort_Steam_InOrOut:: SimDistributionPort_SteamFlowPort_Steam_InOrOut () : ::schema::simxml::ResourcesGeneral::SimDistributionPort_SteamFlowPort () { } SimDistributionPort_SteamFlowPort_Steam_InOrOut:: SimDistributionPort_SteamFlowPort_Steam_InOrOut (const RefId_type& RefId) : ::schema::simxml::ResourcesGeneral::SimDistributionPort_SteamFlowPort (RefId) { } SimDistributionPort_SteamFlowPort_Steam_InOrOut:: SimDistributionPort_SteamFlowPort_Steam_InOrOut (const SimDistributionPort_SteamFlowPort_Steam_InOrOut& x, ::xml_schema::flags f, ::xml_schema::container* c) : ::schema::simxml::ResourcesGeneral::SimDistributionPort_SteamFlowPort (x, f, c) { } SimDistributionPort_SteamFlowPort_Steam_InOrOut:: SimDistributionPort_SteamFlowPort_Steam_InOrOut (const ::xercesc::DOMElement& e, ::xml_schema::flags f, ::xml_schema::container* c) : ::schema::simxml::ResourcesGeneral::SimDistributionPort_SteamFlowPort (e, f, c) { } SimDistributionPort_SteamFlowPort_Steam_InOrOut* SimDistributionPort_SteamFlowPort_Steam_InOrOut:: _clone (::xml_schema::flags f, ::xml_schema::container* c) const { return new class SimDistributionPort_SteamFlowPort_Steam_InOrOut (*this, f, c); } SimDistributionPort_SteamFlowPort_Steam_InOrOut:: ~SimDistributionPort_SteamFlowPort_Steam_InOrOut () { } } } } #include <istream> #include <xsd/cxx/xml/sax/std-input-source.hxx> #include <xsd/cxx/tree/error-handler.hxx> namespace schema { namespace simxml { namespace ResourcesGeneral { } } } #include <xsd/cxx/post.hxx> // Begin epilogue. // // // End epilogue.
//%LICENSE//////////////////////////////////////////////////////////////// // // Licensed to The Open Group (TOG) under one or more contributor license // agreements. Refer to the OpenPegasusNOTICE.txt file distributed with // this work for additional information regarding copyright ownership. // Each contributor licenses this file to you under the OpenPegasus Open // Source License; you may not use this file except in compliance with the // License. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. // IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY // CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, // TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE // SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // ////////////////////////////////////////////////////////////////////////// // //%///////////////////////////////////////////////////////////////////////// #include "UNIX_InstDeletionProvider.h" UNIX_InstDeletionProvider::UNIX_InstDeletionProvider() { } UNIX_InstDeletionProvider::~UNIX_InstDeletionProvider() { } CIMInstance UNIX_InstDeletionProvider::constructInstance( const CIMName &className, const CIMNamespaceName &nameSpace, const UNIX_InstDeletion &_p) { CIMProperty p; CIMInstance inst(className); // Set path inst.setPath(CIMObjectPath(String(""), // hostname nameSpace, CIMName("UNIX_InstDeletion"), constructKeyBindings(_p))); //CIM_Indication Properties if (_p.getIndicationIdentifier(p)) inst.addProperty(p); if (_p.getCorrelatedIndications(p)) inst.addProperty(p); if (_p.getIndicationTime(p)) inst.addProperty(p); if (_p.getPerceivedSeverity(p)) inst.addProperty(p); if (_p.getOtherSeverity(p)) inst.addProperty(p); if (_p.getIndicationFilterName(p)) inst.addProperty(p); if (_p.getSequenceContext(p)) inst.addProperty(p); if (_p.getSequenceNumber(p)) inst.addProperty(p); //CIM_InstIndication Properties if (_p.getSourceInstance(p)) inst.addProperty(p); if (_p.getSourceInstanceModelPath(p)) inst.addProperty(p); if (_p.getSourceInstanceHost(p)) inst.addProperty(p); //CIM_InstDeletion Properties return inst; } Array<CIMKeyBinding> UNIX_InstDeletionProvider::constructKeyBindings(const UNIX_InstDeletion& _p) { Array<CIMKeyBinding> keys; return keys; } #define UNIX_PROVIDER UNIX_InstDeletionProvider #define UNIX_PROVIDER_NAME "UNIX_InstDeletionProvider" #define CLASS_IMPLEMENTATION UNIX_InstDeletion #define CLASS_IMPLEMENTATION_NAME "UNIX_InstDeletion" #define BASE_CLASS_NAME "CIM_InstDeletion" #define NUMKEYS_CLASS_IMPLEMENTATION 0 #include "UNIXProviderBase.hpp"
/* * Copyright (c) 2020, Nico Weber <thakis@chromium.org> * * SPDX-License-Identifier: BSD-2-Clause */ #include <LibCore/ArgsParser.h> #include <math.h> #include <sys/time.h> #include <unistd.h> int main(int argc, char** argv) { #ifdef __serenity__ if (pledge("stdio settime", nullptr) < 0) { perror("pledge"); return 1; } #endif Core::ArgsParser args_parser; double delta = __builtin_nan(""); args_parser.add_option(delta, "Adjust system time by this many seconds", "set", 's', "delta_seconds"); args_parser.parse(argc, argv); if (__builtin_isnan(delta)) { #ifdef __serenity__ if (pledge("stdio", nullptr) < 0) { perror("pledge"); return 1; } #endif } else { long delta_us = static_cast<long>(round(delta * 1'000'000)); timeval delta_timeval; delta_timeval.tv_sec = delta_us / 1'000'000; delta_timeval.tv_usec = delta_us % 1'000'000; if (delta_timeval.tv_usec < 0) { delta_timeval.tv_sec--; delta_timeval.tv_usec += 1'000'000; } if (adjtime(&delta_timeval, nullptr) < 0) { perror("adjtime set"); return 1; } } timeval remaining_delta_timeval; if (adjtime(nullptr, &remaining_delta_timeval) < 0) { perror("adjtime get"); return 1; } double remaining_delta = remaining_delta_timeval.tv_sec + remaining_delta_timeval.tv_usec / 1'000'000.0; outln("{}", remaining_delta); return 0; }
#include "quit_action.hpp" #include "quit_event.hpp" namespace wanderer { void quit_action::execute(entt::dispatcher& dispatcher) { dispatcher.enqueue<event::quit_event>(); } } // namespace wanderer
#include <bits/stdc++.h> #define IOS std::ios::sync_with_stdio(false); std::cin.tie(nullptr); std::cout.tie(nullptr); // #define __DEBUG__ #ifdef __DEBUG__ #define DEBUG(...) printf(__VA_ARGS__) #else #define DEBUG(...) #endif #define filename "" #define setfile() freopen(filename".in", "r", stdin); freopen(filename".ans", "w", stdout); #define resetfile() freopen("/dev/tty", "r", stdin); freopen("/dev/tty", "w", stdout); system("more " filename".ans"); using namespace std; template <typename T> inline T sqr(T a) { return a * a;}; typedef long long ll; typedef unsigned long long ull; typedef long double ld; typedef pair<int, int > Pii; const double pi = acos(-1.0); const int INF = INT_MAX; const int MAX_N = 2e5 + 10; int N, A[MAX_N], B[MAX_N], C[MAX_N], bit[MAX_N], mp[MAX_N]; void add(int i, int x) { while (i <= N) { bit[i] += x; i += i & -i; } } int sum(int i) { int res = 0; while (i) { res += bit[i]; i -= i & -i; } return res; } ll diff(int A[], int B[]) { ll res = 0; for (int i = 1; i <= N; ++i) mp[A[i]] = i; memset(bit, 0, sizeof bit); for (int i = N; i >= 1; --i) { res += sum(mp[B[i]]); add(mp[B[i]], 1); } return res; } int main(int argc, char const *argv[]) { while (~scanf("%d", &N)) { for (int i = 1; i <= N; ++i) scanf("%d", A + i); for (int i = 1; i <= N; ++i) scanf("%d", B + i); for (int i = 1; i <= N; ++i) scanf("%d", C + i); ll ans = (ll) N * (N - 1) / 2; ans -= (diff(A, B) + diff(A, C) + diff(B, C)) / 2; printf("%lld\n", ans); } return 0; }
/////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2007, Industrial Light & Magic, a division of Lucas // Digital Ltd. LLC // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Industrial Light & Magic nor the names of // its contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // /////////////////////////////////////////////////////////////////////////// //----------------------------------------------------------------------------- // // ACES image file I/O. // //----------------------------------------------------------------------------- #include <ImfAcesFile.h> #include <ImfRgbaFile.h> #include <ImfStandardAttributes.h> #include <Iex.h> #include <algorithm> using namespace std; using namespace Imath; using namespace Iex; namespace Imf { const Chromaticities & acesChromaticities () { static const Chromaticities acesChr (V2f (0.73470, 0.26530), // red V2f (0.00000, 1.00000), // green V2f (0.00010, -0.07700), // blue V2f (0.32168, 0.33767)); // white return acesChr; } class AcesOutputFile::Data { public: Data(); ~Data(); RgbaOutputFile * rgbaFile; }; AcesOutputFile::Data::Data (): rgbaFile (0) { // empty } AcesOutputFile::Data::~Data () { delete rgbaFile; } namespace { void checkCompression (Compression compression) { // // Not all compression methods are allowed in ACES files. // switch (compression) { case NO_COMPRESSION: case PIZ_COMPRESSION: case B44A_COMPRESSION: break; default: throw ArgExc ("Invalid compression type for ACES file."); } } } // namespace AcesOutputFile::AcesOutputFile (const std::string &name, const Header &header, RgbaChannels rgbaChannels, int numThreads) : _data (new Data) { checkCompression (header.compression()); Header newHeader = header; addChromaticities (newHeader, acesChromaticities()); addAdoptedNeutral (newHeader, acesChromaticities().white); _data->rgbaFile = new RgbaOutputFile (name.c_str(), newHeader, rgbaChannels, numThreads); _data->rgbaFile->setYCRounding (7, 6); } AcesOutputFile::AcesOutputFile (OStream &os, const Header &header, RgbaChannels rgbaChannels, int numThreads) : _data (new Data) { checkCompression (header.compression()); Header newHeader = header; addChromaticities (newHeader, acesChromaticities()); addAdoptedNeutral (newHeader, acesChromaticities().white); _data->rgbaFile = new RgbaOutputFile (os, header, rgbaChannels, numThreads); _data->rgbaFile->setYCRounding (7, 6); } AcesOutputFile::AcesOutputFile (const std::string &name, const Imath::Box2i &displayWindow, const Imath::Box2i &dataWindow, RgbaChannels rgbaChannels, float pixelAspectRatio, const Imath::V2f screenWindowCenter, float screenWindowWidth, LineOrder lineOrder, Compression compression, int numThreads) : _data (new Data) { checkCompression (compression); Header newHeader (displayWindow, dataWindow.isEmpty()? displayWindow: dataWindow, pixelAspectRatio, screenWindowCenter, screenWindowWidth, lineOrder, compression); addChromaticities (newHeader, acesChromaticities()); addAdoptedNeutral (newHeader, acesChromaticities().white); _data->rgbaFile = new RgbaOutputFile (name.c_str(), newHeader, rgbaChannels, numThreads); _data->rgbaFile->setYCRounding (7, 6); } AcesOutputFile::AcesOutputFile (const std::string &name, int width, int height, RgbaChannels rgbaChannels, float pixelAspectRatio, const Imath::V2f screenWindowCenter, float screenWindowWidth, LineOrder lineOrder, Compression compression, int numThreads) : _data (new Data) { checkCompression (compression); Header newHeader (width, height, pixelAspectRatio, screenWindowCenter, screenWindowWidth, lineOrder, compression); addChromaticities (newHeader, acesChromaticities()); addAdoptedNeutral (newHeader, acesChromaticities().white); _data->rgbaFile = new RgbaOutputFile (name.c_str(), newHeader, rgbaChannels, numThreads); _data->rgbaFile->setYCRounding (7, 6); } AcesOutputFile::~AcesOutputFile () { delete _data; } void AcesOutputFile::setFrameBuffer (const Rgba *base, size_t xStride, size_t yStride) { _data->rgbaFile->setFrameBuffer (base, xStride, yStride); } void AcesOutputFile::writePixels (int numScanLines) { _data->rgbaFile->writePixels (numScanLines); } int AcesOutputFile::currentScanLine () const { return _data->rgbaFile->currentScanLine(); } const Header & AcesOutputFile::header () const { return _data->rgbaFile->header(); } const Imath::Box2i & AcesOutputFile::displayWindow () const { return _data->rgbaFile->displayWindow(); } const Imath::Box2i & AcesOutputFile::dataWindow () const { return _data->rgbaFile->dataWindow(); } float AcesOutputFile::pixelAspectRatio () const { return _data->rgbaFile->pixelAspectRatio(); } const Imath::V2f AcesOutputFile::screenWindowCenter () const { return _data->rgbaFile->screenWindowCenter(); } float AcesOutputFile::screenWindowWidth () const { return _data->rgbaFile->screenWindowWidth(); } LineOrder AcesOutputFile::lineOrder () const { return _data->rgbaFile->lineOrder(); } Compression AcesOutputFile::compression () const { return _data->rgbaFile->compression(); } RgbaChannels AcesOutputFile::channels () const { return _data->rgbaFile->channels(); } void AcesOutputFile::updatePreviewImage (const PreviewRgba pixels[]) { _data->rgbaFile->updatePreviewImage (pixels); } class AcesInputFile::Data { public: Data(); ~Data(); void initColorConversion (); RgbaInputFile * rgbaFile; Rgba * fbBase; size_t fbXStride; size_t fbYStride; int minX; int maxX; bool mustConvertColor; M44f fileToAces; }; AcesInputFile::Data::Data (): rgbaFile (0), fbBase (0), fbXStride (0), fbYStride (0), minX (0), maxX (0), mustConvertColor (false) { // empty } AcesInputFile::Data::~Data () { delete rgbaFile; } void AcesInputFile::Data::initColorConversion () { const Header &header = rgbaFile->header(); Chromaticities fileChr; if (hasChromaticities (header)) fileChr = chromaticities (header); V2f fileNeutral = fileChr.white; if (hasAdoptedNeutral (header)) fileNeutral = adoptedNeutral (header); const Chromaticities acesChr = acesChromaticities(); V2f acesNeutral = acesChr.white; if (fileChr.red == acesChr.red && fileChr.green == acesChr.green && fileChr.blue == acesChr.blue && fileChr.white == acesChr.white && fileNeutral == acesNeutral) { // // The file already contains ACES data, // color conversion is not necessary. return; } mustConvertColor = true; minX = header.dataWindow().min.x; maxX = header.dataWindow().max.x; // // Create a matrix that transforms colors from the // RGB space of the input file into the ACES space // using a color adaptation transform to move the // white point. // // // We'll need the Bradford cone primary matrix and its inverse // static const M44f bradfordCPM (0.895100, -0.750200, 0.038900, 0.000000, 0.266400, 1.713500, -0.068500, 0.000000, -0.161400, 0.036700, 1.029600, 0.000000, 0.000000, 0.000000, 0.000000, 1.000000); const static M44f inverseBradfordCPM (0.986993, 0.432305, -0.008529, 0.000000, -0.147054, 0.518360, 0.040043, 0.000000, 0.159963, 0.049291, 0.968487, 0.000000, 0.000000, 0.000000, 0.000000, 1.000000); // // Convert the white points of the two RGB spaces to XYZ // float fx = fileNeutral.x; float fy = fileNeutral.y; V3f fileNeutralXYZ (fx / fy, 1, (1 - fx - fy) / fy); float ax = acesNeutral.x; float ay = acesNeutral.y; V3f acesNeutralXYZ (ax / ay, 1, (1 - ax - ay) / ay); // // Compute the Bradford transformation matrix // V3f ratio ((acesNeutralXYZ * bradfordCPM) / (fileNeutralXYZ * bradfordCPM)); M44f ratioMat (ratio[0], 0, 0, 0, 0, ratio[1], 0, 0, 0, 0, ratio[2], 0, 0, 0, 0, 1); M44f bradfordTrans = bradfordCPM * ratioMat * inverseBradfordCPM; // // Build a combined file-RGB-to-ACES-RGB conversion matrix // fileToAces = RGBtoXYZ (fileChr, 1) * bradfordTrans * XYZtoRGB (acesChr, 1); } AcesInputFile::AcesInputFile (const std::string &name, int numThreads): _data (new Data) { _data->rgbaFile = new RgbaInputFile (name.c_str(), numThreads); _data->initColorConversion(); } AcesInputFile::AcesInputFile (IStream &is, int numThreads): _data (new Data) { _data->rgbaFile = new RgbaInputFile (is, numThreads); _data->initColorConversion(); } AcesInputFile::~AcesInputFile () { delete _data; } void AcesInputFile::setFrameBuffer (Rgba *base, size_t xStride, size_t yStride) { _data->rgbaFile->setFrameBuffer (base, xStride, yStride); _data->fbBase = base; _data->fbXStride = xStride; _data->fbYStride = yStride; } void AcesInputFile::readPixels (int scanLine1, int scanLine2) { // // Copy the pixels from the RgbaInputFile into the frame buffer. // _data->rgbaFile->readPixels (scanLine1, scanLine2); // // If the RGB space of the input file is not the same as the ACES // RGB space, then the pixels in the frame buffer must be transformed // into the ACES RGB space. // if (!_data->mustConvertColor) return; int minY = min (scanLine1, scanLine2); int maxY = max (scanLine1, scanLine2); for (int y = minY; y <= maxY; ++y) { Rgba *base = _data->fbBase + _data->fbXStride * _data->minX + _data->fbYStride * y; for (int x = _data->minX; x <= _data->maxX; ++x) { V3f aces = V3f (base->r, base->g, base->b) * _data->fileToAces; base->r = aces[0]; base->g = aces[1]; base->b = aces[2]; base += _data->fbXStride; } } } void AcesInputFile::readPixels (int scanLine) { readPixels (scanLine, scanLine); } const Header & AcesInputFile::header () const { return _data->rgbaFile->header(); } const Imath::Box2i & AcesInputFile::displayWindow () const { return _data->rgbaFile->displayWindow(); } const Imath::Box2i & AcesInputFile::dataWindow () const { return _data->rgbaFile->dataWindow(); } float AcesInputFile::pixelAspectRatio () const { return _data->rgbaFile->pixelAspectRatio(); } const Imath::V2f AcesInputFile::screenWindowCenter () const { return _data->rgbaFile->screenWindowCenter(); } float AcesInputFile::screenWindowWidth () const { return _data->rgbaFile->screenWindowWidth(); } LineOrder AcesInputFile::lineOrder () const { return _data->rgbaFile->lineOrder(); } Compression AcesInputFile::compression () const { return _data->rgbaFile->compression(); } RgbaChannels AcesInputFile::channels () const { return _data->rgbaFile->channels(); } const char * AcesInputFile::fileName () const { return _data->rgbaFile->fileName(); } bool AcesInputFile::isComplete () const { return _data->rgbaFile->isComplete(); } int AcesInputFile::version () const { return _data->rgbaFile->version(); } } // namespace Imf
//***************************************************************************** // Copyright 2017-2020 Intel Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //***************************************************************************** #pragma once #include <string> #include "core/node.hpp" #include "ngraph/assertion.hpp" #include "ngraph/check.hpp" #include "ngraph/except.hpp" namespace ngraph { namespace onnx_import { namespace error { namespace detail { std::string get_error_msg_prefix(const Node& node); } struct NotSupported : AssertionFailure { explicit NotSupported(const std::string& what_arg) : AssertionFailure(what_arg) { } }; struct InvalidArgument : AssertionFailure { explicit InvalidArgument(const std::string& what_arg) : AssertionFailure(what_arg) { } }; class OnnxNodeValidationFailure : public CheckFailure { public: OnnxNodeValidationFailure(const CheckLocInfo& check_loc_info, const Node& node, const std::string& explanation) : CheckFailure(check_loc_info, detail::get_error_msg_prefix(node), explanation) { } }; } } } #define ASSERT_IS_SUPPORTED(node_, cond_) \ NGRAPH_ASSERT_STREAM_DO_NOT_USE_IN_NEW_CODE(ngraph::onnx_import::error::NotSupported, cond_) \ << (node_) << " " #define ASSERT_VALID_ARGUMENT(node_, cond_) \ NGRAPH_ASSERT_STREAM_DO_NOT_USE_IN_NEW_CODE(ngraph::onnx_import::error::InvalidArgument, \ cond_) \ << (node_) << " " #define CHECK_VALID_NODE(node_, cond_, ...) \ NGRAPH_CHECK_HELPER( \ ::ngraph::onnx_import::error::OnnxNodeValidationFailure, (node_), (cond_), ##__VA_ARGS__)
/* -*- mode:C++; c-basic-offset:4 -*- Shore-kits -- Benchmark implementations for Shore-MT Copyright (c) 2007-2009 Data Intensive Applications and Systems Labaratory (DIAS) Ecole Polytechnique Federale de Lausanne All Rights Reserved. Permission to use, copy, modify and distribute this software and its documentation is hereby granted, provided that both the copyright notice and this permission notice appear in all copies of the software, derivative works or modified versions, and any portions thereof, and that both notices appear in supporting documentation. This code is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. THE AUTHORS DISCLAIM ANY LIABILITY OF ANY KIND FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE. */ /** @file: shore_tpce_xct_trade_cleanup.cpp * * @brief: Implementation of the Baseline Shore TPC-E TRADE CLEANUP transaction * * @author: Cansu Kaynak * @author: Djordje Jevdjic */ #include "workload/tpce/shore_tpce_env.h" #include "workload/tpce/tpce_const.h" #include "workload/tpce/tpce_input.h" #include <vector> #include <numeric> #include <algorithm> #include <stdio.h> #include <stdlib.h> #include "workload/tpce/egen/CE.h" #include "workload/tpce/egen/TxnHarnessStructs.h" #include "workload/tpce/shore_tpce_egen.h" using namespace shore; using namespace TPCE; ENTER_NAMESPACE(tpce); /******************************************************************** * * TPC-E TRADE CLEANUP * ********************************************************************/ w_rc_t ShoreTPCEEnv::xct_trade_cleanup(const int xct_id, trade_cleanup_input_t& ptcin) { // ensure a valid environment assert (_pssm); assert (_initialized); assert (_loaded); table_row_t* prtrade = _ptrade_man->get_tuple(); assert (prtrade); table_row_t* prtradehist = _ptrade_history_man->get_tuple(); assert (prtradehist); table_row_t* prtradereq = _ptrade_request_man->get_tuple(); assert (prtradereq); w_rc_t e = RCOK; rep_row_t areprow(_ptrade_man->ts()); areprow.set(_ptrade_desc->maxsize()); prtradereq->_rep = &areprow; prtrade->_rep = &areprow; prtradehist->_rep = &areprow; rep_row_t lowrep( _ptrade_man->ts()); rep_row_t highrep( _ptrade_man->ts()); // allocate space for the biggest of the table representations lowrep.set(_ptrade_desc->maxsize()); highrep.set(_ptrade_desc->maxsize()); { TIdent t_id; TIdent tr_t_id; myTime now_dts; /** select TR_T_ID from TRADE_REQUEST order by TR_T_ID */ /* PIN: To get rid of the primary index TRADE_REQUEST, since TRADE_CLEANUP is not performance critical and since we have to touch all the TRADE_REQUEST tuples anyway here, I think this won't hurt Also I'm going to do the deleting of TRADE_REQUEST tuples here as well */ guard<table_scan_iter_impl<trade_request_t> > tr_iter; { table_scan_iter_impl<trade_request_t>* tmp_tr_iter; TRACE( TRACE_TRX_FLOW, "App: %d TC:tr-get-table-iter \n", xct_id); e = _ptrade_request_man->get_iter_for_file_scan(_pssm, tmp_tr_iter); if (e.is_error()) { goto done; } tr_iter = tmp_tr_iter; } //ascending order rep_row_t sortrep(_ptrade_man->ts()); sortrep.set(_ptrade_desc->maxsize()); asc_sort_buffer_t tr_list(1); tr_list.setup(0, SQL_LONG); table_row_t rsb(&tr_list); asc_sort_man_impl tr_sorter(&tr_list, &sortrep); bool eof; e = tr_iter->next(_pssm, eof, *prtradereq); if (e.is_error()) { goto done; } while(!eof){ prtradereq->get_value(0, tr_t_id); rsb.set_value(0, tr_t_id); tr_sorter.add_tuple(rsb); TRACE( TRACE_TRX_FLOW, "App: %d TC:tr-delete- \n", xct_id); e = _ptrade_request_man->delete_tuple(_pssm, prtradereq); if (e.is_error()) { goto done; } e = tr_iter->next(_pssm, eof, *prtradereq); if (e.is_error()) { goto done; } } asc_sort_iter_impl tr_list_sort_iter(_pssm, &tr_list, &tr_sorter); /* guard< index_scan_iter_impl<trade_request_t> > tr_iter; { index_scan_iter_impl<trade_request_t>* tmp_tr_iter; TRACE( TRACE_TRX_FLOW, "App: %d TC:tr-get-iter-by-idx \n", xct_id); e = _ptrade_request_man->tr_get_iter_by_index(_pssm, tmp_tr_iter, prtradereq, lowrep, highrep); if (e.is_error()) { goto done; } tr_iter = tmp_tr_iter; } //already ordered TRACE( TRACE_TRX_FLOW, "App: %d TC:tr-iter-next \n", xct_id); e = tr_iter->next(_pssm, eof, *prtradereq); */ TRACE( TRACE_TRX_FLOW, "App: %d TC:tr-sort-iter-next \n", xct_id); e = tr_list_sort_iter.next(_pssm, eof, rsb); if (e.is_error()) { goto done; } while(!eof){ //prtradereq->get_value(0, tr_t_id); // PIN: read above PIN rsb.get_value(0, tr_t_id); now_dts = time(NULL); /** insert into TRADE_HISTORY ( TH_T_ID, TH_DTS, TH_ST_ID ) values ( tr_t_id, // TH_T_ID now_dts, // TH_DTS st_submitted_id // TH_ST_ID ) */ prtradehist->set_value(0, tr_t_id); prtradehist->set_value(1, now_dts); prtradehist->set_value(2, ptcin._st_submitted_id); TRACE( TRACE_TRX_FLOW, "App: %d TC:th-add-tuple (%ld) (%ld) (%s) \n", xct_id, tr_t_id, now_dts, ptcin._st_submitted_id); e = _ptrade_history_man->add_tuple(_pssm, prtradehist); if (e.is_error()) { goto done; } /** update TRADE set T_ST_ID = st_canceled_id, T_DTS = now_dts where T_ID = tr_t_id */ TRACE( TRACE_TRX_FLOW, "App: %d TC:t-update (%ld) (%ld) (%s) \n", xct_id, tr_t_id, now_dts, ptcin._st_canceled_id); e = _ptrade_man->t_update_dts_stdid_by_index(_pssm, prtrade, tr_t_id, now_dts, ptcin._st_canceled_id); if (e.is_error()) { goto done; } /** insert into TRADE_HISTORY ( TH_T_ID, TH_DTS, TH_ST_ID ) values ( tr_t_id, // TH_T_ID now_dts, // TH_DTS st_canceled_id // TH_ST_ID ) */ prtradehist->set_value(0, tr_t_id); prtradehist->set_value(1, now_dts); prtradehist->set_value(2, ptcin._st_canceled_id); TRACE( TRACE_TRX_FLOW, "App: %d TC:th-add-tuple (%ld) (%ld) (%s) \n", xct_id, tr_t_id, now_dts, ptcin._st_canceled_id); e = _ptrade_history_man->add_tuple(_pssm, prtradehist); if (e.is_error()) { goto done; } /* PIN: read above PIN TRACE( TRACE_TRX_FLOW, "App: %d TC:tr-iter-next \n", xct_id); e = tr_iter->next(_pssm, eof, *prtradereq); */ TRACE( TRACE_TRX_FLOW, "App: %d TC:tr-sort-iter-next \n", xct_id); e = tr_list_sort_iter.next(_pssm, eof, rsb); if (e.is_error()) { goto done; } } /** delete from TRADE_REQUEST */ /* PIN: read above PIN index_scan_iter_impl<trade_request_t>* tmp_tr_iter; { TRACE( TRACE_TRX_FLOW, "App: %d TC:tr-get-iter-by-idx \n", xct_id); e = _ptrade_request_man->tr_get_iter_by_index(_pssm, tmp_tr_iter, prtradereq, lowrep, highrep); if (e.is_error()) { goto done; } tr_iter = tmp_tr_iter; } TRACE( TRACE_TRX_FLOW, "App: %d TC:tr-iter-next \n", xct_id); e = tr_iter->next(_pssm, eof, *prtradereq); if (e.is_error()) { goto done; } while(!eof){ TRACE( TRACE_TRX_FLOW, "App: %d TC:tr-delete- \n", xct_id); e = _ptrade_request_man->delete_tuple(_pssm, prtradereq); if (e.is_error()) { goto done; } TRACE( TRACE_TRX_FLOW, "App: %d TC:tr-iter-next \n", xct_id); e = tr_iter->next(_pssm, eof, *prtradereq); if (e.is_error()) { goto done; } } */ /** select T_ID from TRADE where T_ID >= trade_id and T_ST_ID = st_submitted_id */ guard<index_scan_iter_impl<trade_t> > t_iter; { index_scan_iter_impl<trade_t>* tmp_t_iter; TRACE( TRACE_TRX_FLOW, "App: %d TC:t-iter-by-idx \n", xct_id); e = _ptrade_man->t_get_iter_by_index(_pssm, tmp_t_iter, prtrade, lowrep, highrep, ptcin._trade_id); if (e.is_error()) { goto done; } t_iter = tmp_t_iter; } TRACE( TRACE_TRX_FLOW, "App: %d TC:t-iter-next \n", xct_id); e = t_iter->next(_pssm, eof, *prtrade); if (e.is_error()) { goto done; } while(!eof){ char t_st_id[5]; //4 prtrade->get_value(2, t_st_id, 5); if(strcmp(t_st_id, ptcin._st_submitted_id) == 0){ now_dts = time(NULL); /** update TRADE set T_ST_ID = st_canceled_id T_DTS = now_dts where T_ID = t_id */ TRACE( TRACE_TRX_FLOW, "App: %d TC:t-update (%ld) (%ld) (%s) \n", xct_id, t_id, now_dts, ptcin._st_canceled_id); e = _ptrade_man->t_update_dts_stdid_by_index(_pssm, prtrade, t_id, now_dts, ptcin._st_canceled_id); if (e.is_error()) { goto done; } /** insert into TRADE_HISTORY ( TH_T_ID, TH_DTS, TH_ST_ID ) values ( t_id, // TH_T_ID now_dts, // TH_DTS st_canceled_id // TH_ST_ID ) */ prtradehist->set_value(0, t_id); prtradehist->set_value(1, now_dts); prtradehist->set_value(2, ptcin._st_canceled_id); TRACE( TRACE_TRX_FLOW, "App: %d TC:th-add-tuple (%ld) (%ld) (%s) \n", xct_id, t_id, now_dts, ptcin._st_canceled_id); e = _ptrade_history_man->add_tuple(_pssm, prtradehist); if (e.is_error()) { goto done; } } TRACE( TRACE_TRX_FLOW, "App: %d TC:t-iter-next \n", xct_id); e = t_iter->next(_pssm, eof, *prtrade); if (e.is_error()) { goto done; } } } #ifdef PRINT_TRX_RESULTS // at the end of the transaction // dumps the status of all the table rows used rtradereq.print_tuple(); rtrade.print_tuple(); rtradehist.print_tuple(); #endif done: // return the tuples to the cache _ptrade_request_man->give_tuple(prtradereq); _ptrade_man->give_tuple(prtrade); _ptrade_history_man->give_tuple(prtradehist); return (e); } EXIT_NAMESPACE(tpce);
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2016 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "feerate.h" #include "tinyformat.h" const std::string CURRENCY_UNIT = "RWC"; CFeeRate::CFeeRate(const CAmount& nFeePaid, size_t nBytes_) { assert(nBytes_ <= uint64_t(std::numeric_limits<int64_t>::max())); int64_t nSize = int64_t(nBytes_); if (nSize > 0) nSatoshisPerK = nFeePaid * 1000 / nSize; else nSatoshisPerK = 0; } CAmount CFeeRate::GetFee(size_t nBytes_) const { assert(nBytes_ <= uint64_t(std::numeric_limits<int64_t>::max())); int64_t nSize = int64_t(nBytes_); CAmount nFee = nSatoshisPerK * nSize / 1000; if (nFee == 0 && nSize != 0) { if (nSatoshisPerK > 0) nFee = CAmount(1); if (nSatoshisPerK < 0) nFee = CAmount(-1); } return nFee; } std::string CFeeRate::ToString() const { return strprintf("%d.%08d %s/kB", nSatoshisPerK / COIN, nSatoshisPerK % COIN, CURRENCY_UNIT); }
#include "stdafx.h" #include "CUnitSurface.h" #include "..\Common\Colors.h" #include <math.h> // Constructor CCUnitSurface::CCUnitSurface() { m_pColoringParams = NULL; m_nRefCount = 0; m_nXOffset = 0; m_nYOffset = 0; m_dwFrameDelay = 0; } // Destructor CCUnitSurface::~CCUnitSurface() { } // Debug functions #ifdef _DEBUG void CCUnitSurface::AssertValid() const { CImageSurface::AssertValid(); ASSERT(m_pColoringParams != NULL); } void CCUnitSurface::Dump(CDumpContext &dc) const { CImageSurface::Dump(dc); } #endif // Implementation ---------------------------------------------- // Creates the object - loads it from the disk void CCUnitSurface::Create(CArchiveFile file, CCUnitSurface::tagSColoringParams *pColoringParams, int nXOffset, int nYOffset, DWORD dwFrameDelay ) { ASSERT(pColoringParams != NULL); m_pColoringParams = pColoringParams; m_nXOffset = nXOffset; m_nYOffset = nYOffset; m_dwFrameDelay = dwFrameDelay; CImageSurface::SetFinishRGBProc(ColorImage, pColoringParams); // create the surface (load the image) CImageSurface::Create(file); } // Deletes the object void CCUnitSurface::Delete() { // just call the base class CImageSurface::Delete(); // clear coloring params m_pColoringParams = NULL; } void CCUnitSurface::Restore() { // first restore the image CImageSurface::Restore(); } void CCUnitSurface::ColorImage(CDDrawSurface *pDDSurface, LPBYTE pSurface, DWORD dwPitch, LPVOID pParam) { int nSrcH, nSrcS, nSrcV; int nDstH, nDstS, nDstV; SColoringParams *pColoringParams = (SColoringParams *)pParam; // if 0 tolerance -> do nothing if(pColoringParams->m_dbHTolerance == 0) return; // convert our source and destination colors to HSV Color_RGB2HSV_int(R32(pColoringParams->m_dwSourceColor), G32(pColoringParams->m_dwSourceColor), B32(pColoringParams->m_dwSourceColor), nSrcH, nSrcS, nSrcV); Color_RGB2HSV_int(R32(pColoringParams->m_dwDestColor), G32(pColoringParams->m_dwDestColor), B32(pColoringParams->m_dwDestColor), nDstH, nDstS, nDstV); // now go through all pixels in image and color them // lock the surface LPBYTE pData = pSurface; DWORD dwX, dwY, dwWidth, dwHeight, dwOff; dwWidth = pDDSurface->GetWidth(); dwHeight = pDDSurface->GetHeight(); int nH, nS, nV; int nHTolerance=(int)pColoringParams->m_dbHTolerance; int nSTolerance=(int)(pColoringParams->m_dbSTolerance*255.0); int nVTolerance=(int)(pColoringParams->m_dbVTolerance*255.0); int nHDif, nSDif, nVDif; int R, G, B; if(g_pDirectDraw->Is32BitMode()){ for(dwY = 0; dwY < dwHeight; dwY++){ dwOff = dwY * dwPitch; for(dwX = 0; dwX < dwWidth; dwX++, dwOff+=4){ // get the RGB value R = pData[dwOff + 2]; G = pData[dwOff + 1]; B = pData[dwOff]; // convert to HSV Color_RGB2HSV_int(R, G, B, nH, nS, nV); // compute differences nHDif = nH - nSrcH; nSDif = nS - nSrcS; nVDif = nV - nSrcV; // test if we are inside tolerance -> if no do nothing if(abs(nHDif) > nHTolerance) continue; if(abs(nSDif) > nSTolerance) continue; if(abs(nVDif) > nVTolerance) continue; // we are in the tolerance -> color it // just use the dest color as the base nH = nDstH + nHDif; if(nH > 360) nH -= 360; if(nH < 0) nH += 360; nS = nDstS + nSDif; nV = nDstV + nVDif; if(nV > 255){ nS -= nV - 255; nV = 255; } if(nV < 0) nV = 0; if(nS > 255){ if(nV > (nS - 255)) nV -= nS - 255; else nV = 0; nS = 255; } if(nS < 0) nS = 0; // convert the color back to RGB Color_HSV2RGB_int(nH, nS, nV, R, G, B); pData[dwOff + 2] = (BYTE)R; pData[dwOff + 1] = (BYTE)G; pData[dwOff] = (BYTE)B; } } } else{ for(dwY = 0; dwY < dwHeight; dwY++){ dwOff = dwY * dwPitch; for(dwX = 0; dwX < dwWidth; dwX++, dwOff+=3){ // get the RGB value R = pData[dwOff + 2]; G = pData[dwOff + 1]; B = pData[dwOff]; // convert to HSV Color_RGB2HSV_int(R, G, B, nH, nS, nV); // compute differences nHDif = nH - nSrcH; nSDif = nS - nSrcS; nVDif = nV - nSrcV; // test if we are inside tolerance -> if no do nothing if(abs(nHDif) > nHTolerance) continue; if(abs(nSDif) > nSTolerance) continue; if(abs(nVDif) > nVTolerance) continue; // we are in the tolerance -> color it // just use the dest color as the base nH = nDstH + nHDif; if(nH > 360) nH -= 360; if(nH < 0) nH += 360; nS = nDstS + nSDif; nV = nDstV + nVDif; if(nV > 255){ nS -= nV - 255; nV = 255; } if(nV < 0) nV = 0; if(nS > 255){ if(nV > (nS - 255)) nV -= nS - 255; else nV = 0; nS = 255; } if(nS < 0) nS = 0; // convert the color back to RGB Color_HSV2RGB_int(nH, nS, nV, R, G, B); pData[dwOff + 2] = (BYTE)R; pData[dwOff + 1] = (BYTE)G; pData[dwOff] = (BYTE)B; } } } }
#include <PCU.h> #include "parma_sides.h" #include "parma_weights.h" #include "parma_targets.h" namespace parma { class WeightSideTargets : public Targets { public: WeightSideTargets(Sides* s, Weights* w, int sideTol, double alpha) { init(s, w, sideTol, alpha); } double total() { return totW; } private: WeightSideTargets(); double totW; void init(Sides* s, Weights* w, int sideTol, double alpha) { const double selfW = w->self(); totW = 0; const Sides::Item* side; s->begin(); while( (side = s->iterate()) ) { const int peer = side->first; const double peerW = w->get(peer); const int peerSides = s->get(peer); if( selfW > peerW && peerSides < sideTol ) { const double difference = selfW - peerW; double sideFraction = side->second; sideFraction /= s->total(); double scaledW = difference * sideFraction * alpha; set(peer, scaledW); totW+=scaledW; } } s->end(); } }; Targets* makeWeightSideTargets(Sides* s, Weights* w, int sideTol, double alpha) { return new WeightSideTargets(s, w, sideTol, alpha); } }