text
stringlengths
5
1.04M
/* * Copyright (C) 2012 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 INC. AND ITS 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 APPLE INC. OR ITS 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 "PlatformUtilities.h" #include "test.h" namespace TestWebKitAPI { static bool done; // Callback for WKContextGetStatistics. static void wkContextGetStatisticsCallback(WKDictionaryRef statistics, WKErrorRef error, void* functionContext) { EXPECT_NOT_NULL(error); done = true; } TEST(WebKit2, WebCoreStatisticsWithNoWebProcess) { WKRetainPtr<WKContextRef> context = adoptWK(WKContextCreate()); WKContextGetStatistics(context.get(), 0, wkContextGetStatisticsCallback); Util::run(&done); } } // namespace TestWebKitAPI
#include "../Collect/Array.h" #include "../Sys/Platform.h" #include "../Sys/Path.h" #include "../Sys/Endian.h" #include "../Memory/Memory.h" #include "../Io/Stream.h" #include "StringRef.h" #include <stdlib.h> #include <stdarg.h> #include <stdio.h> #include <string.h> // this is my older code. may need review #if LETHE_OS_WINDOWS # include <windows.h> #endif namespace lethe { // static helpers namespace { // maximum format string buffer size in chars const int maxFmtSize = 64000; int wlen(const wchar_t *str) { LETHE_ASSERT(str); if (!str) return 0; const wchar_t *start = str; while (*str) str++; return static_cast<int>(str - start); } bool isWhiteSpc(wchar_t ch) { // FIXME: better switch(ch) { case '\t': case '\v': case '\b': case '\n': case '\r': case 32: return 1; } return 0; } } // String::CharIterator String::CharIterator &String::CharIterator::operator ++() { ptr += byteSize; bytePos += byteSize; charPos++; if (ptr >= top) { *this = endIterator; return *this; } LETHE_ASSERT(ptr); auto optr = ptr; ch = CharConv::DecodeUTF8(ptr, top); if (ch < 0) ch = '?'; byteSize = int(ptr - optr); byteSize = Max<int>(byteSize, 1); ptr = optr; return *this; } // StringData StringData *StringData::Alloc(int n) { LETHE_ASSERT(n >= 0); StringData *res = reinterpret_cast<StringData *>( StringAllocator.CallAlloc(sizeof(StringData) + n*sizeof(char), Max<size_t>(8, alignof(StringData))) ); LETHE_ASSERT(!((uintptr_t)res & 7)); res->length = 0; res->charLength = 0; res->capacity = n; res->refCount = 1; // pre-incremented -- no need to call addRef after alloc res->hash = 0; res->data[0] = 0; return res; } StringData *StringData::Clone() { LETHE_ASSERT(refCount); StringData *res = Alloc(length); LETHE_ASSERT(res); for (int i=0; i<=length; i++) res->data[i] = data[i]; res->length = length; // note: we don't copy derived information here (like hash and widelength) return res; } // String String::CharIterator String::endIterator = { nullptr, nullptr, -1, 0, 0, 0 }; String::CharIterator String::Begin() const { CharIterator res; res.ptr = reinterpret_cast<const Byte *>(Ansi()); res.top = res.ptr + GetLength(); if (res.ptr >= res.top) return endIterator; res.ch = -1; res.charPos = res.bytePos = res.byteSize = 0; auto optr = res.ptr; res.ch = CharConv::DecodeUTF8(res.ptr, res.top); res.byteSize = int(res.ptr - optr); res.ptr = optr; return res; } String::String(const StringRef &sr) : data(nullptr) { Init(sr.GetData(), sr.GetData() + sr.GetLength()); } String::String(const char *str) : data(0) { *this = str; } String::String(const wchar_t *str) : data(0) { *this = str; } String::String(const String &str) : data(0) { *this = str; } // allow construction from path! String::String(const Path &pth) : data(0) { *this = pth.Get(); } String::String(const char *str, int len) : data(0) { Init(str, len < 0 ? static_cast<const char *>(0) : str + len); } String::String(const wchar_t *str, int len) : data(0) { Init(str, len < 0 ? static_cast<const wchar_t *>(0) : str + len); } String::String(const char *str, const char *strEnd) : data(0) { Init(str, strEnd); } String::String(const wchar_t *str, const wchar_t *strEnd) : data(0) { Init(str, strEnd); } String String::operator +(int w) const { String res(*this); return res += w; } String String::operator +(const char *str) const { String res(*this); return res += str; } String String::operator +(const String &str) const { String res(*this); return res += str; } // friends String operator +(wchar_t w, const String &str1) { wchar_t wa[2] = {w, 0}; return String(wa) + str1; } String operator +(const char *str0, const String &str1) { return String(str0) + str1; } String operator +(const wchar_t *str0, const String &str1) { return String(str0) + str1; } void String::Init(const char *str, const char *strEnd, CharConv::Encoding encoding) { Clear(); if (str && !strEnd) strEnd = str + strlen(str); LETHE_ASSERT(str && strEnd); if (!str || strEnd == str) return; if (encoding == CharConv::encDefault) encoding = CharConv::defaultEncoding; // convert to utf8 representation int req = int(strEnd - str); StringData *ndata; if (encoding != CharConv::encUtf8) { int slen = req; req = CharConv::AnsiToUTF8(str, req, nullptr, 0, encoding); LETHE_ASSERT(req != (int)-1); ndata = StringData::Alloc(req); CharConv::AnsiToUTF8(str, slen, ndata->data, req, encoding); } else { ndata = StringData::Alloc(req); MemCpy(ndata->data, str, req); } LETHE_ASSERT(ndata); ndata->data[ndata->length = req] = 0; data = ndata; } void String::Init(const wchar_t *str, const wchar_t *strEnd) { Clear(); if (str && !strEnd) strEnd = str + wlen(str); LETHE_ASSERT(str && strEnd); if (!str || strEnd == str) return; int wlen = int(strEnd - str); int len = CharConv::WideToAnsi(str, wlen, nullptr, 0, CharConv::encUtf8); LETHE_ASSERT(len >= 0); if (!len) return; StringData *ndata = StringData::Alloc(len); LETHE_ASSERT(ndata); ndata->length = CharConv::WideToAnsi(str, wlen, ndata->data, len, CharConv::encUtf8); ndata->data[ndata->length] = 0; data = ndata; } String::~String() { Reset(); #if LETHE_DEBUG memset(this, 0xfe, sizeof(*this)); #endif } String &String::ContChange() { if (data) { data->hash = 0; data->charLength = 0; } return *this; } String &String::Clear() { #ifndef __clang_analyzer__ if (data) { StringData *dt = data; data = nullptr; dt->Release(); } #endif return *this; } String &String::Reset() { // at the moment, this is the same as Clear return Clear(); } String &String::operator =(int w) { // FIXME: better wchar_t wa[] = {(wchar_t)w, 0}; return *this = wa; } String &String::operator =(const char *c) { if (!c || !*c) { Clear(); return *this; } const char *ce = c; while (*ce) ce++; Init(c, ce); return *this; } String &String::operator =(const wchar_t *c) { if (!c || !*c) { Clear(); return *this; } const wchar_t *ce = c; while (*ce) ce++; Init(c, ce); return *this; } String &String::operator =(const String &str) { if (str.data == data) return *this; Clear(); if (str.data) { #ifndef __clang_analyzer__ str.data->AddRef(); #endif data = str.data; } return *this; } String &String::operator =(const StringRef &str) { Init(str.GetData(), str.GetData() + str.GetLength()); return *this; } String &String::AppendData(int l, int sl, const char *str) { LETHE_ASSERT(str); if (LETHE_UNLIKELY(!str || !sl)) return *this; CloneData(); LETHE_ASSERT(data); if (l + sl > data->capacity) { // must resize int cap = Max<int>(data->capacity*3 / 2, l + sl); StringData *nd = StringData::Alloc(cap); LETHE_ASSERT(nd); // full add MemCpy(nd->data, data->data, l * sizeof(char)); MemCpy(nd->data + l, str, sl * sizeof(char)); StringData *dt = data; data = nd; dt->Release(); } else { // fast add MemCpy(data->data + l, str, sl * sizeof(char)); } data->data[data->length = l+sl] = 0; return ContChange(); } String &String::operator +=(int w) { int l = GetLength(); if (!l) return *this = w; Byte buf[7]; int sl = CharConv::EncodeUTF8(w, buf, buf+6); buf[sl] = 0; return AppendData(l, sl, reinterpret_cast<const char *>(buf)); } String &String::Append(const char *c, const char *cend) { LETHE_ASSERT(c && cend); return AppendData(GetLength(), (int)(cend - c), c); } String &String::operator +=(const char *c) { if (!c || !*c) return *this; int l = GetLength(); if (!l) return *this = c; int sl = (int)StrLen(c); if (!sl) return *this; return AppendData(l, sl, c); } String &String::operator +=(const String &str) { int s = GetLength(); if (!s) return *this = str; int sl = str.GetLength(); if (!sl) return *this; return AppendData(s, sl, str.Ansi()); } int String::Comp(const char *str, const char *strEnd) const { LETHE_ASSERT(str); if (!str) return -2; if (!strEnd) strEnd = str + strlen(str); const char *c = Ansi(); const char *cEnd = c + GetLength(); while (c != cEnd && str != strEnd) { if (*c != *str) return *reinterpret_cast<const Byte *>(c) < *reinterpret_cast<const Byte *>(str) ? -1 : 1; c++; str++; } // now, strings match only if both are at the end if (c == cEnd) return str == strEnd ? 0 : -1; LETHE_ASSERT(str == strEnd); return 1; } int String::Comp(const String &str) const { if (data == str.data) return 0; const char *c = str.Ansi(); return Comp(c, c + str.GetLength()); } int String::CompNC(const char *str, const char *strEnd) const { // FIXME: use locale? LETHE_ASSERT(str); if (!str) return -2; const char *c = Ansi(); const char *cEnd = c + GetLength(); if (!strEnd) strEnd = str + StrLen(str); while (c != cEnd && str != strEnd) { int wc0, wc1; wc0 = *reinterpret_cast<const Byte *>(c); wc1 = *reinterpret_cast<const Byte *>(str); // fast tolower if (wc0 >= 'A' && wc0 <= 'Z') wc0 |= 32; if (wc1 >= 'A' && wc1 <= 'Z') wc1 |= 32; if (wc0 != wc1) return wc0 < wc1 ? -1 : 1; c++; str++; } if (c == cEnd) return str == strEnd ? 0 : -1; return str == strEnd ? 1 : 0; } int String::CompNC(const String &str) const { if (data == str.data) return 0; const char *c = str.Ansi(); return CompNC(c, c + str.GetLength()); } int String::Find(const char *str, const char *strEnd, int pos) const { int l = GetLength(); if (!l) return -1; LETHE_ASSERT(str); if (!str) return -1; if (!strEnd) strEnd = str + StrLen(str); if (str == strEnd || (int)pos >= l) return -1; const char *c = Ansi(); const char *ce = c + GetLength(); c += pos; while (c < ce) { const char *tmp = str; const char *src = c; while (tmp < strEnd && src < ce) { if (*src != *tmp) break; tmp++; src++; } if (tmp == strEnd) return pos; // match c++; pos++; } return -1; } int String::FindSet(const char *str, const char *strEnd, int pos) const { int l = GetLength(); if (!l) return -1; LETHE_ASSERT(str); if (!str) return -1; if (!strEnd) strEnd = str + StrLen(str); if (str == strEnd || (int)pos >= l) return -1; const char *c = Ansi(); const char *ce = c + GetLength(); c += pos; while (c < ce) { const char *tmp = str; while (tmp < strEnd) { if (*c == *tmp) return pos; tmp++; } c++; pos++; } return -1; } String String::Tokenize(const char *str, const char *strEnd, int &pos) const { // FIXME: this could be better String res; LETHE_ASSERT(str); if (pos < 0 || !str) return res; if (!strEnd) strEnd = str + StrLen(str); const char *c = Ansi(); const char *ce = c + GetLength(); c += (int)pos; if (c < Ansi()) return res; // if tokStart is initially null, skips empty tokens (FIXME: change later to accept keepEmpty flag as well?) const char *tokStart = c; while (c < ce) { const char *tmp = str; while (tmp < strEnd) { if (*c == *tmp) break; tmp++; } if (tmp >= strEnd) { // not a separator if (!tokStart) tokStart = c; } else if (tokStart) { res = String(tokStart, c); pos = (int)(c - Ansi() + 1); // keep this if tokStart is initially null (=we want to skip empty strings) /*if ((int)pos >= GetLength()) { pos = -1; }*/ break; } c++; } if (tokStart && c >= ce) { res = String(tokStart, ce); pos = -1; } return res; } String &String::Insert(const char *str, const char *strEnd, int pos) { LETHE_ASSERT(str); if (!str) return *this; if (!strEnd) strEnd = str + StrLen(str); if (str == strEnd) return *this; int l = GetLength(); int epos = (int)pos; if (epos >= l) { if (!l) Init(str, strEnd); else AppendData(l, static_cast<int>(strEnd - str), str); return *this; } CloneData(); LETHE_ASSERT(data); int sl = static_cast<int>(strEnd - str); if (l + sl > data->capacity) { int cap = Max<int>(data->capacity*3/2, l + sl); StringData *nd = StringData::Alloc(cap); LETHE_ASSERT(nd); MemCpy(nd->data, data->data, epos * sizeof(char)); MemCpy(nd->data + epos, str, sl * sizeof(char)); MemCpy(nd->data + epos + sl, data->data + epos, (data->length - epos) * sizeof(char)); StringData *dt = data; data = nd; dt->Release(); } else { // first make space for (int i=l - epos; i>0; i--) data->data[epos + sl + i - 1] = data->data[epos + i - 1]; // then copy MemCpy(data->data + epos, str, sl * sizeof(char)); } data->data[data->length = l+sl] = 0; return ContChange(); } int String::Replace( const char *ostr, const char *ostrend, const char *nstr, const char *nstrend ) { LETHE_ASSERT(ostr && nstr); if (!ostr || !nstr) return 0; if (!ostrend) ostrend = ostr + StrLen(ostr); if (!nstrend) nstrend = nstr + StrLen(nstr); if (ostrend == ostr) return 0; String res(*this); int pos = 0; int reps = 0; int osz = (int)(ostrend - ostr); while ((pos = res.Find(ostr, ostrend, pos)) >= 0) { res.Erase(pos, osz); res.Insert(nstr, nstrend, pos); pos += (int)(nstrend - nstr); reps++; } *this = res; return reps; } bool String::operator <(const char *str) const { return Comp(str) < 0; } bool String::operator <(const String &str) const { return Comp(str) < 0; } bool String::operator <=(const char *str) const { return Comp(str) <= 0; } bool String::operator <=(const String &str) const { return Comp(str) <= 0; } bool String::operator >(const char *str) const { return Comp(str) > 0; } bool String::operator >(const String &str) const { return Comp(str) > 0; } bool String::operator >=(const char *str) const { return Comp(str) >= 0; } bool String::operator >=(const String &str) const { return Comp(str) >= 0; } bool String::operator ==(const char *str) const { return Comp(str) == 0; } bool String::operator ==(const StringRef &sr) const { const auto len = GetLength(); if (len != sr.GetLength()) return false; return len == 0 || MemCmp(data->data, sr.GetData(), len) == 0; } bool String::operator ==(const String &str) const { const auto len = GetLength(); if (len != str.GetLength()) return false; return len == 0 || MemCmp(data->data, str.data->data, len) == 0; } bool String::operator !=(const char *str) const { return Comp(str) != 0; } bool String::operator !=(const String &str) const { return !(*this == str); } bool String::operator !=(const StringRef &sr) const { return !(*this == sr); } // conversions const char *String::Ansi() const { return !data ? "" : data->data; } // index operator (read only) char String::operator[](int index) const { LETHE_ASSERT(index >= 0 && index < GetLength()); return data->data[index]; } bool String::IsUnique() const { return !data || Atomic::Load(data->refCount) == 1; } String &String::CloneData() { // note: this is not thread-safe! if (IsUnique()) return *this; StringData *ndata = data->Clone(); StringData *odata = data; data = ndata; odata->Release(); return *this; } String &String::Shrink() { if (data && data->capacity != data->length) { StringData *ndata = data->Clone(); StringData *odata = data; data = ndata; odata->Release(); } return *this; } // string length in bytes int String::GetLength() const { #if defined(__clang_analyzer__) return 0; #else return !data ? 0 : data->length; #endif } bool String::IsEmpty() const { return !GetLength(); } String &String::Format(const char *fmt, ...) { va_list ap; va_start(ap, fmt); char buf[maxFmtSize]; #ifdef LETHE_COMPILER_MSC vsnprintf_s(buf, sizeof(buf), _TRUNCATE, fmt, ap); #else vsnprintf(buf, sizeof(buf), fmt, ap); #endif va_end(ap); buf[maxFmtSize - 1] = 0; return *this = buf; } String String::Printf(const char *fmt, ...) { va_list ap; va_start(ap, fmt); char buf[maxFmtSize]; #ifdef LETHE_COMPILER_MSC vsnprintf_s(buf, sizeof(buf), _TRUNCATE, fmt, ap); #else vsnprintf(buf, sizeof(buf), fmt, ap); #endif va_end(ap); buf[maxFmtSize - 1] = 0; return buf; } int String::Find(wchar_t ch, int pos) const { char buf[7]; int sl = CharConv::EncodeUTF8(ch, buf, buf+6); buf[sl] = 0; return Find(buf, buf+sl, pos); } int String::Find(const char *str, int pos) const { // FIXME: better? return Find(String(str), pos); } int String::Find(const String &str, int pos) const { const char *c = str.Ansi(); return Find(c, c + str.GetLength(), pos); } int String::FindOneOf(wchar_t ch, int pos) const { return Find(ch, pos); } int String::FindOneOf(const char *str, int pos) const { return FindSet(str, 0, pos); } int String::FindOneOf(const String &str, int pos) const { const char *c = str.Ansi(); return FindSet(c, c + str.GetLength(), pos); } int String::ReverseFind(wchar_t ch) const { LETHE_ASSERT(ch >= 0 && ch <= 127); const char *c = Ansi(); const char *ce = c + GetLength(); while (--ce >= c) { if (*ce == ch) return (int)(ce - c); } return -1; } int String::ReverseFind(const String &str, int pos) const { int best = -1; int found = -1; for (;;) { found = Find(str, found + 1); if (found < 0 || (found + str.GetLength() >= pos)) break; best = found; } return best; } String &String::Reverse() { if (IsEmpty()) return *this; CloneData(); int req = 0; for (auto ci : *this) req += ci.byteSize; StringData *tmp = StringData::Alloc(req); tmp->length = req; char *c = tmp->data + req; for (auto ci : *this) { c -= ci.byteSize; CharConv::EncodeUTF8(ci.ch, c, c+ci.byteSize); } auto odata = data; data = tmp; odata->Release(); return ContChange(); } String &String::ToUpper() { if (IsEmpty()) return *this; CloneData(); LETHE_ASSERT(data); for (int i=0; i<data->length; i++) { char &c = data->data[i]; if (c >= 'a' && c <= 'z') c ^= 32; } return ContChange(); } String &String::ToLower() { if (IsEmpty()) return *this; CloneData(); LETHE_ASSERT(data); for (int i=0; i<data->length; i++) { char &c = data->data[i]; if (c >= 'A' && c <= 'Z') c |= 32; } return ContChange(); } String &String::ToCapital() { if (IsEmpty()) return *this; CloneData(); LETHE_ASSERT(data); char &c = data->data[0]; if (c >= 'a' && c <= 'z') c ^= 32; return ContChange(); } // returns new length int String::Erase(int pos, int count) { int l = GetLength(); pos = Max<Int>(pos, 0); if (pos >= l) return l; CloneData(); // erase... int index = pos; int ecount = count < 0 ? l : count; if (index + ecount > l) ecount = l-index; int cpy = l - (index + ecount); for (int i=0; i<cpy; i++) data->data[index + i] = data->data[index + ecount + i]; data->data[data->length -= ecount] = 0; ContChange(); return GetLength(); } String String::Left(int count) const { int l = GetLength(); if (!l || count <= 0) return String(); int ecount = count; if (ecount > l) ecount = l; return String(Ansi(), ecount); } String String::Right(int count) const { int l = GetLength(); if (!l || count <= 0) return String(); int ecount = count; if (ecount > l) ecount = l; return String(Ansi() + l - ecount, ecount); } // if count is -1, returns all chars to the right of pos String String::Mid(int pos, int count) const { int l = GetLength(); int epos = pos; if (!l || epos >= l) return String(); int ecount = count < 0 ? l : count; if (epos + ecount > l) ecount = l - epos; return String(Ansi() + epos, ecount); } // remove char from string // returns number of characters removed int String::Remove(wchar_t ch) { int l = GetLength(); if (!l) return 0; LETHE_ASSERT(ch >= 0 && ch <= 127); CloneData(); LETHE_ASSERT(data); char *c = data->data; int res = 0; for (int i=0; i<l; i++) { if (c[i] == ch) { for (int j=i; j+1<l; j++) c[j] = c[j+1]; l--; i--; res++; } } c[data->length = l] = 0; ContChange(); return res; } int String::Insert(int pos, wchar_t ch) { char buf[7]; int sl = CharConv::EncodeUTF8(ch, buf, buf+6); buf[sl] = 0; Insert(buf, buf+sl, pos); return GetLength(); } int String::Insert(int pos, const char *str) { LETHE_ASSERT(str); Insert(str, nullptr, pos); return GetLength(); } int String::Insert(int pos, const String &str) { const char *c = str.Ansi(); Insert(c, c + str.GetLength(), pos); return GetLength(); } int String::Replace(wchar_t oldc, wchar_t newc) { char buf[7]; int sl = CharConv::EncodeUTF8(oldc, buf, buf+6); buf[sl] = 0; char buf2[7]; int sl2 = CharConv::EncodeUTF8(newc, buf2, buf2+6); buf2[sl2] = 0; return Replace(buf, buf2); } // performance warning: string versions are slow int String::Replace(const char *oldstr, const char *newstr) { return Replace(oldstr, nullptr, newstr, nullptr); } int String::Replace(const String &oldstr, const String &newstr) { const char *oc = oldstr.Ansi(); const char *nc = newstr.Ansi(); return Replace(oc, oc + oldstr.GetLength(), nc, nc + newstr.GetLength()); } String &String::TrimLeft(void) { if (IsEmpty()) return *this; CloneData(); LETHE_ASSERT(data); char *c = data->data; const char *ce = c + data->length; while (c < ce && isWhiteSpc(*c)) c++; IntPtr delta = (IntPtr)(c - data->data); while (c < ce) { c[-delta] = *c; c++; } data->data[data->length -= (int)delta] = 0; return ContChange(); } String &String::TrimRight(void) { if (IsEmpty()) return *this; CloneData(); LETHE_ASSERT(data); const char *ce = data->data + data->length; char *c = const_cast<char *>(ce)-1; while (c >= data->data && isWhiteSpc(*c)) c--; c++; data->data[data->length = static_cast<int>(c - data->data)] = 0; return ContChange(); } String &String::Trim(void) { TrimRight(); return TrimLeft(); } bool String::StartsWith(const wchar_t ch) const { char buf[7]; int sl = CharConv::EncodeUTF8(ch, buf, buf+6); return StartsWith(buf, sl); } bool String::StartsWith(const char *str) const { return StartsWith(str, (int)StrLen(str)); } bool String::StartsWith(const char *str, int len) const { return StartsWith(str, str + len); } bool String::StartsWith(const char *str, const char *strEnd) const { // main work is done here if (LETHE_UNLIKELY(!str || IsEmpty() || str >= strEnd)) return 0; if (LETHE_UNLIKELY(strEnd - str > data->length)) return 0; int ind = 0; while (str < strEnd) { if (data->data[ind++] != *str++) return 0; } return 1; } bool String::StartsWith(const String &str) const { return StartsWith(str.Ansi(), str.GetLength()); } bool String::EndsWith(const wchar_t ch) const { char buf[7]; int sl = CharConv::EncodeUTF8(ch, buf, buf+6); buf[sl] = 0; return EndsWith(buf, sl); } bool String::EndsWith(const char *str) const { return EndsWith(str, str + StrLen(str)); } bool String::EndsWith(const char *str, int len) const { return EndsWith(str, str+len); } bool String::EndsWith(const char *str, const char *strEnd) const { // main work is done here if (LETHE_UNLIKELY(!str || IsEmpty() || str >= strEnd)) return 0; if (LETHE_UNLIKELY((strEnd - str) > data->length)) return 0; int ind = data->length; while (str < strEnd) { if (data->data[--ind] != *--strEnd) return 0; } return 1; } bool String::EndsWith(const String &str) const { return EndsWith(str.Ansi(), str.GetLength()); } String String::Tokenize(wchar_t ch, int &pos) const { char buf[7]; int sl = CharConv::EncodeUTF8(ch, buf, buf+6); buf[sl] = 0; return Tokenize(buf, buf+sl, pos); } String String::Tokenize(const char *chset, int &pos) const { return Tokenize(chset, nullptr, pos); } String String::Tokenize(const String &chset, int &pos) const { if (IsEmpty()) return String(); LETHE_ASSERT(data); const char *c = chset.Ansi(); return Tokenize(c, c + chset.GetLength(), pos); } Array<String> String::Split(const int ch, bool keepEmpty) const { char buf[7]; int sl = CharConv::EncodeUTF8(ch, buf, buf+6); buf[sl] = 0; return Split(String(buf, sl), keepEmpty); } Array<String> String::Split(const char *chset, bool keepEmpty) const { return Split(String(chset), keepEmpty); } Array<String> String::Split(const String &chset, bool keepEmpty) const { Array< String > res; if (IsEmpty()) return res; int pos = 0; String tmp; while (pos >= 0) { tmp = Tokenize(chset, pos); if (keepEmpty || !tmp.IsEmpty()) res.Add(tmp); } return res; } String String::Escape() const { String res; bool changed = 0; for (Int i=0; i<GetLength(); i++) { wchar_t ch = Ansi()[i]; // try to escape char... if (ch == '\\' || ch == '\'' || ch == '"') { changed = 1; break; } if (ch < 32 || ch > 127) { changed = 1; break; } } if (!changed) return *this; // pass 2: escaping... const char *HEX_CHARS = "0123456789abcdef"; for (Int i=0; i<GetLength(); i++) { wchar_t ch = (wchar_t)(Ansi()[i] & 255u); if (ch == '\\' || ch == '\'' || ch == '"') { res += '\\'; res += ch; continue; } if (ch >= 32 && ch <= 127) { res += ch; continue; } // handle special chars here... switch(ch) { case '\a': res += "\\a"; continue; case '\b': res += "\\b"; continue; case '\n': res += "\\n"; continue; case '\r': res += "\\r"; continue; case '\t': res += "\\t"; continue; case '\v': res += "\\v"; continue; }; res += "\\x"; char tmp[3] = { HEX_CHARS[(ch >> 4) & 15], HEX_CHARS[ch & 15], 0 }; res += tmp; } return res; } String String::Unescape() const { // TODO: implement return *this; } // load/save from binary stream bool String::Load(Stream &s) { Int len; LETHE_RET_FALSE(s.Read(&len, sizeof(len))); Endian::FromLittle(len); if (!len) { Reset(); return 1; } if (len < 4096) { char buf[4096]; LETHE_RET_FALSE(s.Read(buf, len)); buf[len] = 0; *this = buf; return 1; } Array<char> tmp(len + 1); LETHE_RET_FALSE(s.Read(tmp.GetData(), len)); tmp[len] = 0; *this = tmp.GetData(); return 1; } bool String::Save(Stream &s) const { Int len = GetLength(); Endian::ToLittle(len); LETHE_RET_FALSE(s.Write(&len, sizeof(len))); if (!len) return 1; return s.Write(Ansi(), len); } bool String::Serialize(Stream &s) { return s.IsWritable() ? Save(s) : Load(s); } // load/save from text stream bool String::LoadText(Stream &s) { Int ch = s.GetByte(); LETHE_RET_FALSE(ch == '"'); String tmp; for (;;) { ch = s.GetByte(); if (ch < 0) return 0; if (ch == '"') break; if (ch != '\\') { tmp += (wchar_t)ch; continue; } tmp += (wchar_t)ch; ch = s.GetByte(); if (ch < 0) return 0; tmp += (wchar_t)ch; } *this = tmp.Unescape(); return 1; } bool String::SaveText(Stream &s) const { String tmp = Escape(); return s.Write("\"", 1) && (tmp.IsEmpty() ? true : s.Write(tmp.Ansi(), tmp.GetLength())) && s.Write("\"", 1); } // init from specific multibyte encoded string String &String::FromEncoding(CharConv::Encoding enc, const char *str, const char *strEnd) { if (!strEnd) strEnd = str+StrLen(str); Init(str, strEnd, enc); return *this; } // convert ansi representation to encoding // note: reset when string gets modified! String &String::ToEncoding(CharConv::Encoding enc) { if (IsEmpty()) return *this; if (enc == CharConv::encDefault) enc = CharConv::defaultEncoding; if (enc == CharConv::encUtf8) return *this; const char *c = data->data; int req = CharConv::UTF8ToAnsi(c, data->length, nullptr, 0, enc); LETHE_ASSERT(req != (int)-1); StringData *tmp = StringData::Alloc(req); LETHE_ASSERT(tmp); CharConv::UTF8ToAnsi(c, data->length, tmp->data, req, enc); tmp->data[tmp->length = req] = 0; auto odata = data; data = tmp; odata->Release(); return *this; } UInt String::GetStoredHash() const { return data ? Atomic::Load(data->hash) : 0; } const wchar_t *String::ToWide(Array<wchar_t> &wbuf) const { if (IsEmpty()) { wbuf.Resize(1); wbuf[0] = 0; return L""; } int req = CharConv::AnsiToWide(Ansi(), GetLength(), nullptr, 0); wbuf.Resize(req+1); CharConv::AnsiToWide(Ansi(), GetLength(), wbuf.GetData(), wbuf.GetSize()); wbuf[req] = 0; return wbuf.GetData(); } int String::GetByteIndex(int charIndex) const { int res = -1; int maxRes = 0; for (auto ci : *this) { maxRes = ci.bytePos + ci.byteSize; if (ci.charPos >= charIndex) { res = ci.bytePos; break; } } return res < 0 ? maxRes : res; } int String::GetCharIndex(int byteIndex) const { int res = -1; int maxRes = 0; for (auto ci : *this) { maxRes = ci.charPos+1; if (ci.bytePos >= byteIndex) { res = ci.charPos; break; } } return res < 0 ? maxRes : res; } int String::DecodeCharAt(int byteIndex) const { if ((UInt)byteIndex >= (UInt)GetLength()) return -1; const Byte *tmp = reinterpret_cast<const Byte *>(Ansi()); const Byte *te = tmp + GetLength(); tmp += byteIndex; return CharConv::DecodeUTF8(tmp, te); } int String::GetCharSizeAt(int byteIndex) const { if ((UInt)byteIndex >= (UInt)GetLength()) return 0; const Byte *tmp = reinterpret_cast<const Byte *>(Ansi()); const Byte *te = tmp + GetLength(); tmp += byteIndex; auto otmp = tmp; CharConv::DecodeUTF8(tmp, te); return int(tmp - otmp); } bool String::IsMultiByte() const { return GetLength() != GetWideLength(); } int String::GetWideLength() const { if (data && data->charLength) return data->charLength; auto res = GetCharIndex(GetLength()); if (data) data->charLength = res; return res; } UInt Hash(const String &s) { if (LETHE_UNLIKELY(!s.data)) { // equals to HashBuffer(0, 0); return 0x424c5fbfu; } LETHE_ASSERT(s.data); UInt res = Atomic::Load(s.data->hash); if (LETHE_UNLIKELY(!res)) { // we don't care about the result here res = HashBuffer(s.data->data, (size_t)s.data->length*sizeof(char)); Atomic::Store(s.data->hash, res); } return res; } Int String::AsInt() const { return (Int)strtol(Ansi(), nullptr, 10); } }
/*! * Copyright 2014-2022 by XGBoost Contributors * \file updater_prune.cc * \brief prune a tree given the statistics * \author Tianqi Chen */ #include <rabit/rabit.h> #include <xgboost/tree_updater.h> #include <string> #include <memory> #include "xgboost/base.h" #include "xgboost/json.h" #include "./param.h" #include "../common/io.h" #include "../common/timer.h" namespace xgboost { namespace tree { DMLC_REGISTRY_FILE_TAG(updater_prune); /*! \brief pruner that prunes a tree after growing finishes */ class TreePruner: public TreeUpdater { public: explicit TreePruner(ObjInfo task) { syncher_.reset(TreeUpdater::Create("sync", ctx_, task)); pruner_monitor_.Init("TreePruner"); } char const* Name() const override { return "prune"; } // set training parameter void Configure(const Args& args) override { param_.UpdateAllowUnknown(args); syncher_->Configure(args); } void LoadConfig(Json const& in) override { auto const& config = get<Object const>(in); FromJson(config.at("train_param"), &this->param_); } void SaveConfig(Json* p_out) const override { auto& out = *p_out; out["train_param"] = ToJson(param_); } bool CanModifyTree() const override { return true; } // update the tree, do pruning void Update(HostDeviceVector<GradientPair> *gpair, DMatrix *p_fmat, const std::vector<RegTree*> &trees) override { pruner_monitor_.Start("PrunerUpdate"); // rescale learning rate according to size of trees float lr = param_.learning_rate; param_.learning_rate = lr / trees.size(); for (auto tree : trees) { this->DoPrune(tree); } param_.learning_rate = lr; syncher_->Update(gpair, p_fmat, trees); pruner_monitor_.Stop("PrunerUpdate"); } private: // try to prune off current leaf bst_node_t TryPruneLeaf(RegTree &tree, int nid, int depth, int npruned) { // NOLINT(*) CHECK(tree[nid].IsLeaf()); if (tree[nid].IsRoot()) { return npruned; } bst_node_t pid = tree[nid].Parent(); CHECK(!tree[pid].IsLeaf()); RTreeNodeStat const &s = tree.Stat(pid); // Only prune when both child are leaf. auto left = tree[pid].LeftChild(); auto right = tree[pid].RightChild(); bool balanced = tree[left].IsLeaf() && right != RegTree::kInvalidNodeId && tree[right].IsLeaf(); if (balanced && param_.NeedPrune(s.loss_chg, depth)) { // need to be pruned tree.ChangeToLeaf(pid, param_.learning_rate * s.base_weight); // tail recursion return this->TryPruneLeaf(tree, pid, depth - 1, npruned + 2); } else { return npruned; } } /*! \brief do pruning of a tree */ void DoPrune(RegTree* p_tree) { auto& tree = *p_tree; bst_node_t npruned = 0; for (int nid = 0; nid < tree.param.num_nodes; ++nid) { if (tree[nid].IsLeaf() && !tree[nid].IsDeleted()) { npruned = this->TryPruneLeaf(tree, nid, tree.GetDepth(nid), npruned); } } LOG(INFO) << "tree pruning end, " << tree.NumExtraNodes() << " extra nodes, " << npruned << " pruned nodes, max_depth=" << tree.MaxDepth(); } private: // synchronizer std::unique_ptr<TreeUpdater> syncher_; // training parameter TrainParam param_; common::Monitor pruner_monitor_; }; XGBOOST_REGISTER_TREE_UPDATER(TreePruner, "prune") .describe("Pruner that prune the tree according to statistics.") .set_body([](ObjInfo task) { return new TreePruner(task); }); } // namespace tree } // namespace xgboost
/** @file * @author Grigorios Megariotis (<gmegariotis@yahoo.gr>) * @author Georgios G. Vogiatzis (<gvog@chemeng.ntua.gr>) * @brief C++ source file containing the implementation of bonded interactions. * * @section LICENSE * * Copyright (c) 2013 Grigorios Megariotis and Georgios Vogiatzis. All rights reserved. * * This work is licensed under the terms of the MIT license. * For a copy, see <https://opensource.org/licenses/MIT>. */ #include <cmath> #include <iostream> #include "distributions.h" using namespace std; /** @param[in] rij the separation vector between beads i and j, i.e. @f$ \mathbf{R}_{ij} @f$. * @param[in] coeff the strength of the entropic springs * @f$ \epsilon_{\rm b} = 3/2 \:k_{\rm B} @f$, measured in kJ/mol/K. * @param[in] sq_ete the equilibrium mean-squared end-to-end length of the strand, * i.e. @f$\sigma_{\rm b} = n_{\rm Kuhns/bead}b^2@f$, measured * in @f$ \text{\AA}^2 @f$. * @param[in] temp the temperature of the simulation, @f$ T@f$, in K. * @param[out] gradi the force acted on the bead i, due to its bond with bead j * @param[out] gradj the force acted on the bead j, due to its bond with bead i */ double f_gaussian(const double *rij, const double & coeff, const double & sq_ete, const double & temp, double *gradi, double *gradj) { /** This routine applies a Gaussian free energy potential of the form: * @f[ \mathcal{V}_{\rm b} \left(r^2_{ij} \right) = \epsilon_{\rm b} T * \frac{r^2_{ij}}{\sigma^2_{\rm b}} * = \frac{3}{2}k_{\rm B}T\frac{\mathbf{R}_{ij} \cdot \mathbf{R}_{ij}} * {n_{\rm Kuhns/bead} b^2} @f] * with the parameters @f$ \epsilon_{\rm b} @f$ and @f$ \sigma_{\rm b} @f$ read from the * data file. In our approach @f$ \epsilon_{\rm b} = 0.012471 @f$ kJ/mol/K and * @f$ \sigma_{\rm b} = 810 \; \text{\AA}^2 @f$ for polyisoprene melt. */ // Compute the distance between positional vectors ri and rj double rsq = rij[0]*rij[0] + rij[1]*rij[1] + rij[2]*rij[2]; // Compute the free energy of the Gaussian spring. double p = coeff * temp / sq_ete; // Compute the forces as gradients of the Gaussian distribution along ri and rj direction. gradi[0] = 2.0 * p * rij[0]; gradi[1] = 2.0 * p * rij[1]; gradi[2] = 2.0 * p * rij[2]; gradj[0] = -gradi[0]; gradj[1] = -gradi[1]; gradj[2] = -gradi[2]; return (p*rsq); } /** @param[in] rij the separation vector between beads i and j, i.e. @f$ \mathbf{R}_{ij} @f$. * @param[in] coeff the strength of the entropic springs * @f$ \epsilon_{\rm b} = 3/2 \:k_{\rm B} @f$, measured in kJ/mol/K. * @param[in] sq_ete the equilibrium mean-squared end-to-end length of the strand, * i.e. @f$\sigma_{\rm b} = n_{\rm Kuhns/bead}b^2@f$, measured in * @f$ \text{\AA}^2 @f$. * @param[in] temp the temperature of the simulation, @f$ T@f$, in K. */ double e_gaussian(const double *rij, const double & coeff, const double & sq_ete, const double & temp) { //compute the distance between positional vectors ri and rj double rsq = rij[0]*rij[0] + rij[1]*rij[1] + rij[2]*rij[2]; // Compute only the free energy of the Gaussian spring. return (coeff * temp * rsq / sq_ete); }
// Copyright (c) 2021 CINN Authors. 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. #include "cinn/ir/tensor.h" #include <gtest/gtest.h> #include "cinn/backends/codegen_c.h" #include "cinn/backends/llvm/execution_engine.h" #include "cinn/cinn.h" #include "cinn/common/test_helper.h" #include "cinn/ir/ir_operators.h" #include "cinn/ir/ir_printer.h" #include "cinn/lang/builtin.h" #include "cinn/lang/compute.h" #include "cinn/lang/lower.h" #include "cinn/lang/packed_func.h" #include "cinn/lang/placeholder.h" namespace cinn { namespace ir { using utils::GetStreamCnt; using utils::Trim; TEST(Tensor, inlined) { Expr M(100), N(20); Placeholder<float> A("A", {M, N}); Placeholder<float> B("B", {M, N}); // C is inlined Tensor C = lang::Compute( {M, N}, [=](Var i, Var j) { return A(i, j) + B(i, j); }, "C"); Tensor D = lang::Compute( {M, N}, [=](Var i, Var j) -> Expr { return C(i, j) * 2.f + 1.f; }, "D"); auto stages = CreateStages({D}); stages[C]->ComputeInline(); auto func = lang::Lower("func_C", stages, {A, B, D}); std::cout << "output: \n" << func << std::endl; auto out = GetStreamCnt(func); EXPECT_EQ(Trim(out), Trim(R"ROC( function func_C (_A, _B, _D) { for (i, 0, 100) { for (j, 0, 20) { D[i, j] = (1 + ((2 * A[i, j]) + (2 * B[i, j]))) } } } )ROC")); } TEST(Tensor, IsDependOnStatement) { Expr N(100); Placeholder<float> X("X", {N}); auto t = Compute({N}, [&](Var i) -> Expr { return X(i); }); ASSERT_TRUE(t->IsDependOnStatement("X")); ASSERT_FALSE(t->IsDependOnStatement("XXX")); } TEST(Tensor, Reshape) { Context::Global().ResetNameId(); Expr M(100); Expr N(100); Placeholder<float> A("A", {M, N}); auto stages = CreateStages({A}); auto A1 = A->Reshape({Expr(10), Expr(10), Expr(100)}, stages); auto B = Compute(A1->shape, [=](Expr i, Expr j, Expr k) { return A1(i, j, k) * 2.f; }); stages->InsertLazily(B); auto func = lang::Lower("fn", stages, {A, B}); ir::Module::Builder builder("some_modue", common::DefaultHostTarget()); builder.AddFunction(func); backends::CodeGenC codegenc(common::DefaultHostTarget()); codegenc.SetInlineBuiltinCodes(false); auto source = codegenc.Compile(builder.Build(), CodeGenC::OutputKind::CImpl); LOG(INFO) << "source:\n" << source; auto target_source = R"ROC( #include <cinn_runtime.h> #include <stdio.h> void fn(void* _args, int32_t num_args) { const cinn_buffer_t* _A = cinn_pod_value_to_buffer_p(&(((cinn_pod_value_t*)(_args))[0])); cinn_buffer_t* _tensor = cinn_pod_value_to_buffer_p(&(((cinn_pod_value_t*)(_args))[1])); cinn_buffer_malloc((void*)(0), _tensor); const float* A_reshape = ((const float*)(_A->memory)); float* tensor = ((float*)(_tensor->memory)); for (int32_t i = 0; i < 10; i += 1) { for (int32_t j = 0; j < 10; j += 1) { for (int32_t k = 0; k < 100; k += 1) { tensor[((1000 * i) + ((100 * j) + k))] = (2 * A_reshape[((1000 * i) + ((100 * j) + k))]); }; }; }; cinn_buffer_free((void*)(0), _tensor); } )ROC"; ASSERT_EQ(Trim(target_source), Trim(source)); } TEST(Tensor, ReshapeCopied) { Context::Global().ResetNameId(); Expr M(100); Expr N(100); Placeholder<float> A("A", {M, N}); auto stages = CreateStages({A}); auto A1 = A->ReshapeCopied({Expr(10), Expr(10), Expr(100)}, stages); auto B = Compute(A1->shape, [=](Expr i, Expr j, Expr k) { return A1(i, j, k) * 2.f; }); stages->InsertLazily(B); ir::Module::Builder builder("some_modue", common::DefaultHostTarget()); auto func = lang::Lower("fn", stages, {A, B}, {}, {}, &builder); backends::CodeGenC codegenc(common::DefaultHostTarget()); codegenc.SetInlineBuiltinCodes(false); auto source = codegenc.Compile(builder.Build(), CodeGenC::OutputKind::CImpl); LOG(INFO) << "source:\n" << source; auto target_source = R"ROC( #include <cinn_runtime.h> #include <stdio.h> void fn(void* _args, int32_t num_args) { const cinn_buffer_t* _A = cinn_pod_value_to_buffer_p(&(((cinn_pod_value_t*)(_args))[0])); cinn_buffer_t* _tensor = cinn_pod_value_to_buffer_p(&(((cinn_pod_value_t*)(_args))[1])); cinn_buffer_t* _A_copied_reshape = cinn_buffer_t::new_((cinn_device_kind_t)(0)/*target*/, cinn_float32_t(), { 10, 10, 100 }, 32/*align*/); cinn_buffer_malloc((void*)(0), _tensor); cinn_buffer_malloc((void*)(0), _A_copied_reshape); const float* A = ((const float*)(_A->memory)); float* A_copied = ((float*)(_A_copied_reshape->memory)); const float* A_copied_reshape = ((const float*)(_A_copied_reshape->memory)); float* tensor = ((float*)(_tensor->memory)); for (int32_t i = 0; i < 100; i += 1) { for (int32_t j = 0; j < 100; j += 1) { A_copied[((100 * i) + j)] = A[((100 * i) + j)]; }; }; for (int32_t i = 0; i < 10; i += 1) { for (int32_t j = 0; j < 10; j += 1) { for (int32_t k = 0; k < 100; k += 1) { tensor[((1000 * i) + ((100 * j) + k))] = (2 * A_copied_reshape[((1000 * i) + ((100 * j) + k))]); }; }; }; cinn_buffer_free((void*)(0), _A_copied_reshape); cinn_buffer_free((void*)(0), _tensor); } )ROC"; ASSERT_EQ(Trim(target_source), Trim(source)); } TEST(Tensor, reduce) { Placeholder<float> A("A", {Expr(10)}); Var reduce_axis(Expr(10), "ii"); { auto C = Compute( A->shape, [=](const std::vector<Expr>& axis) { return lang::ReduceSum(A(reduce_axis) + 1.f, {reduce_axis}); }, "C"); ASSERT_TRUE(C->has_expression()); ASSERT_TRUE(C->is_reduce_sum()); ASSERT_FALSE(C->is_reduce_mul()); } { auto C = Compute( A->shape, [=](const std::vector<Expr>& axis) { return lang::ReduceMul(A(reduce_axis) + 1.f, {reduce_axis}); }, "C"); ASSERT_TRUE(C->has_expression()); ASSERT_TRUE(C->is_reduce_mul()); ASSERT_FALSE(C->is_reduce_sum()); } } } // namespace ir } // namespace cinn
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "irc.h" #include "net.h" #include "strlcpy.h" #include "base58.h" using namespace std; using namespace boost; int nGotIRCAddresses = 0; void ThreadIRCSeed2(void* parg); #pragma pack(push, 1) struct ircaddr { struct in_addr ip; short port; }; #pragma pack(pop) string EncodeAddress(const CService& addr) { struct ircaddr tmp; if (addr.GetInAddr(&tmp.ip)) { tmp.port = htons(addr.GetPort()); vector<unsigned char> vch(UBEGIN(tmp), UEND(tmp)); return string("u") + EncodeBase58Check(vch); } return ""; } bool DecodeAddress(string str, CService& addr) { vector<unsigned char> vch; if (!DecodeBase58Check(str.substr(1), vch)) return false; struct ircaddr tmp; if (vch.size() != sizeof(tmp)) return false; memcpy(&tmp, &vch[0], sizeof(tmp)); addr = CService(tmp.ip, ntohs(tmp.port)); return true; } static bool Send(SOCKET hSocket, const char* pszSend) { if (strstr(pszSend, "PONG") != pszSend) printf("IRC SENDING: %s\n", pszSend); const char* psz = pszSend; const char* pszEnd = psz + strlen(psz); while (psz < pszEnd) { int ret = send(hSocket, psz, pszEnd - psz, MSG_NOSIGNAL); if (ret < 0) return false; psz += ret; } return true; } bool RecvLineIRC(SOCKET hSocket, string& strLine) { while (true) { bool fRet = RecvLine(hSocket, strLine); if (fRet) { if (fShutdown) return false; vector<string> vWords; ParseString(strLine, ' ', vWords); if (vWords.size() >= 1 && vWords[0] == "PING") { strLine[1] = 'O'; strLine += '\r'; Send(hSocket, strLine.c_str()); continue; } } return fRet; } } int RecvUntil(SOCKET hSocket, const char* psz1, const char* psz2=NULL, const char* psz3=NULL, const char* psz4=NULL) { while (true) { string strLine; strLine.reserve(10000); if (!RecvLineIRC(hSocket, strLine)) return 0; printf("IRC %s\n", strLine.c_str()); if (psz1 && strLine.find(psz1) != string::npos) return 1; if (psz2 && strLine.find(psz2) != string::npos) return 2; if (psz3 && strLine.find(psz3) != string::npos) return 3; if (psz4 && strLine.find(psz4) != string::npos) return 4; } } bool Wait(int nSeconds) { if (fShutdown) return false; printf("IRC waiting %d seconds to reconnect\n", nSeconds); for (int i = 0; i < nSeconds; i++) { if (fShutdown) return false; MilliSleep(1000); } return true; } bool RecvCodeLine(SOCKET hSocket, const char* psz1, string& strRet) { strRet.clear(); while (true) { string strLine; if (!RecvLineIRC(hSocket, strLine)) return false; vector<string> vWords; ParseString(strLine, ' ', vWords); if (vWords.size() < 2) continue; if (vWords[1] == psz1) { printf("IRC %s\n", strLine.c_str()); strRet = strLine; return true; } } } bool GetIPFromIRC(SOCKET hSocket, string strMyName, CNetAddr& ipRet) { Send(hSocket, strprintf("USERHOST %s\r", strMyName.c_str()).c_str()); string strLine; if (!RecvCodeLine(hSocket, "302", strLine)) return false; vector<string> vWords; ParseString(strLine, ' ', vWords); if (vWords.size() < 4) return false; string str = vWords[3]; if (str.rfind("@") == string::npos) return false; string strHost = str.substr(str.rfind("@")+1); // Hybrid IRC used by lfnet always returns IP when you userhost yourself, // but in case another IRC is ever used this should work. printf("GetIPFromIRC() got userhost %s\n", strHost.c_str()); CNetAddr addr(strHost, true); if (!addr.IsValid()) return false; ipRet = addr; return true; } void ThreadIRCSeed(void* parg) { // Make this thread recognisable as the IRC seeding thread RenameThread("PostCoin-ircseed"); try { ThreadIRCSeed2(parg); } catch (std::exception& e) { PrintExceptionContinue(&e, "ThreadIRCSeed()"); } catch (...) { PrintExceptionContinue(NULL, "ThreadIRCSeed()"); } printf("ThreadIRCSeed exited\n"); } void ThreadIRCSeed2(void* parg) { // Don't connect to IRC if we won't use IPv4 connections. if (IsLimited(NET_IPV4)) return; // ... or if we won't make outbound connections and won't accept inbound ones. if (mapArgs.count("-connect") && fNoListen) return; // ... or if IRC is not enabled. if (!GetBoolArg("-irc", false)) return; printf("ThreadIRCSeed started\n"); int nErrorWait = 10; int nRetryWait = 10; int nNameRetry = 0; while (!fShutdown) { CService addrConnect("92.243.23.21", 6667); // irc.lfnet.org CService addrIRC("irc.lfnet.org", 6667, true); if (addrIRC.IsValid()) addrConnect = addrIRC; SOCKET hSocket; if (!ConnectSocket(addrConnect, hSocket)) { printf("IRC connect failed\n"); nErrorWait = nErrorWait * 11 / 10; if (Wait(nErrorWait += 60)) continue; else return; } if (!RecvUntil(hSocket, "Found your hostname", "using your IP address instead", "Couldn't look up your hostname", "ignoring hostname")) { closesocket(hSocket); hSocket = INVALID_SOCKET; nErrorWait = nErrorWait * 11 / 10; if (Wait(nErrorWait += 60)) continue; else return; } CNetAddr addrIPv4("1.2.3.4"); // arbitrary IPv4 address to make GetLocal prefer IPv4 addresses CService addrLocal; string strMyName; // Don't use our IP as our nick if we're not listening // or if it keeps failing because the nick is already in use. if (!fNoListen && GetLocal(addrLocal, &addrIPv4) && nNameRetry<3) strMyName = EncodeAddress(GetLocalAddress(&addrConnect)); if (strMyName == "") strMyName = strprintf("x%"PRIu64"", GetRand(1000000000)); Send(hSocket, strprintf("NICK %s\r", strMyName.c_str()).c_str()); Send(hSocket, strprintf("USER %s 8 * : %s\r", strMyName.c_str(), strMyName.c_str()).c_str()); int nRet = RecvUntil(hSocket, " 004 ", " 433 "); if (nRet != 1) { closesocket(hSocket); hSocket = INVALID_SOCKET; if (nRet == 2) { printf("IRC name already in use\n"); nNameRetry++; Wait(10); continue; } nErrorWait = nErrorWait * 11 / 10; if (Wait(nErrorWait += 60)) continue; else return; } nNameRetry = 0; MilliSleep(500); // Get our external IP from the IRC server and re-nick before joining the channel CNetAddr addrFromIRC; if (GetIPFromIRC(hSocket, strMyName, addrFromIRC)) { printf("GetIPFromIRC() returned %s\n", addrFromIRC.ToString().c_str()); // Don't use our IP as our nick if we're not listening if (!fNoListen && addrFromIRC.IsRoutable()) { // IRC lets you to re-nick AddLocal(addrFromIRC, LOCAL_IRC); strMyName = EncodeAddress(GetLocalAddress(&addrConnect)); Send(hSocket, strprintf("NICK %s\r", strMyName.c_str()).c_str()); } } if (fTestNet) { Send(hSocket, "JOIN #PostCoinTEST\r"); Send(hSocket, "WHO #PostCoinTEST\r"); } else { // randomly join #PostCoin00-#PostCoin05 //int channel_number = GetRandInt(5); int channel_number = 0; // Channel number is always 0 for initial release //int channel_number = 0; Send(hSocket, strprintf("JOIN #PostCoin%02d\r", channel_number).c_str()); Send(hSocket, strprintf("WHO #PostCoin%02d\r", channel_number).c_str()); } int64_t nStart = GetTime(); string strLine; strLine.reserve(10000); while (!fShutdown && RecvLineIRC(hSocket, strLine)) { if (strLine.empty() || strLine.size() > 900 || strLine[0] != ':') continue; vector<string> vWords; ParseString(strLine, ' ', vWords); if (vWords.size() < 2) continue; char pszName[10000]; pszName[0] = '\0'; if (vWords[1] == "352" && vWords.size() >= 8) { // index 7 is limited to 16 characters // could get full length name at index 10, but would be different from join messages strlcpy(pszName, vWords[7].c_str(), sizeof(pszName)); printf("IRC got who\n"); } if (vWords[1] == "JOIN" && vWords[0].size() > 1) { // :username!username@50000007.F000000B.90000002.IP JOIN :#channelname strlcpy(pszName, vWords[0].c_str() + 1, sizeof(pszName)); if (strchr(pszName, '!')) *strchr(pszName, '!') = '\0'; printf("IRC got join\n"); } if (pszName[0] == 'u') { CAddress addr; if (DecodeAddress(pszName, addr)) { addr.nTime = GetAdjustedTime(); if (addrman.Add(addr, addrConnect, 51 * 60)) printf("IRC got new address: %s\n", addr.ToString().c_str()); nGotIRCAddresses++; } else { printf("IRC decode failed\n"); } } } closesocket(hSocket); hSocket = INVALID_SOCKET; if (GetTime() - nStart > 20 * 60) { nErrorWait /= 3; nRetryWait /= 3; } nRetryWait = nRetryWait * 11 / 10; if (!Wait(nRetryWait += 60)) return; } } #ifdef TEST int main(int argc, char *argv[]) { WSADATA wsadata; if (WSAStartup(MAKEWORD(2,2), &wsadata) != NO_ERROR) { printf("Error at WSAStartup()\n"); return false; } ThreadIRCSeed(NULL); WSACleanup(); return 0; } #endif
// sass.hpp must go before all system headers to get the // __EXTENSIONS__ fix on Solaris. #include "sass.hpp" #include <cstdint> #include <cstdlib> #include <cmath> #include <random> #include <sstream> #include <iomanip> #include <algorithm> #include "ast.hpp" #include "units.hpp" #include "fn_utils.hpp" #include "fn_numbers.hpp" #ifdef __MINGW32__ #include "windows.h" #include "wincrypt.h" #endif namespace Sass { namespace Functions { #ifdef __MINGW32__ uint64_t GetSeed() { HCRYPTPROV hp = 0; BYTE rb[8]; CryptAcquireContext(&hp, 0, 0, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT); CryptGenRandom(hp, sizeof(rb), rb); CryptReleaseContext(hp, 0); uint64_t seed; memcpy(&seed, &rb[0], sizeof(seed)); return seed; } #else uint64_t GetSeed() { std::random_device rd; return rd(); } #endif // note: the performance of many implementations of // random_device degrades sharply once the entropy pool // is exhausted. For practical use, random_device is // generally only used to seed a PRNG such as mt19937. static std::mt19937 rand(static_cast<unsigned int>(GetSeed())); /////////////////// // NUMBER FUNCTIONS /////////////////// Signature percentage_sig = "percentage($number)"; BUILT_IN(percentage) { Number_Obj n = ARGN("$number"); if (!n->is_unitless()) error("argument $number of `" + sass::string(sig) + "` must be unitless", pstate, traces); return SASS_MEMORY_NEW(Number, pstate, n->value() * 100, "%"); } Signature round_sig = "round($number)"; BUILT_IN(round) { Number_Obj r = ARGN("$number"); r->value(Sass::round(r->value(), ctx.c_options.precision)); r->pstate(pstate); return r.detach(); } Signature ceil_sig = "ceil($number)"; BUILT_IN(ceil) { Number_Obj r = ARGN("$number"); r->value(std::ceil(r->value())); r->pstate(pstate); return r.detach(); } Signature floor_sig = "floor($number)"; BUILT_IN(floor) { Number_Obj r = ARGN("$number"); r->value(std::floor(r->value())); r->pstate(pstate); return r.detach(); } Signature abs_sig = "abs($number)"; BUILT_IN(abs) { Number_Obj r = ARGN("$number"); r->value(std::abs(r->value())); r->pstate(pstate); return r.detach(); } Signature min_sig = "min($numbers...)"; BUILT_IN(min) { List* arglist = ARG("$numbers", List); Number_Obj least; size_t L = arglist->length(); if (L == 0) { error("At least one argument must be passed.", pstate, traces); } for (size_t i = 0; i < L; ++i) { ExpressionObj val = arglist->value_at_index(i); Number_Obj xi = Cast<Number>(val); if (!xi) { error("\"" + val->to_string(ctx.c_options) + "\" is not a number for `min'", pstate, traces); } if (least) { if (*xi < *least) least = xi; } else least = xi; } return least.detach(); } Signature max_sig = "max($numbers...)"; BUILT_IN(max) { List* arglist = ARG("$numbers", List); Number_Obj greatest; size_t L = arglist->length(); if (L == 0) { error("At least one argument must be passed.", pstate, traces); } for (size_t i = 0; i < L; ++i) { ExpressionObj val = arglist->value_at_index(i); Number_Obj xi = Cast<Number>(val); if (!xi) { error("\"" + val->to_string(ctx.c_options) + "\" is not a number for `max'", pstate, traces); } if (greatest) { if (*greatest < *xi) greatest = xi; } else greatest = xi; } return greatest.detach(); } Signature random_sig = "random($limit:false)"; BUILT_IN(random) { AST_Node_Obj arg = env["$limit"]; Value* v = Cast<Value>(arg); Number* l = Cast<Number>(arg); Boolean* b = Cast<Boolean>(arg); if (l) { double lv = l->value(); if (lv < 1) { sass::sstream err; err << "$limit " << lv << " must be greater than or equal to 1 for `random'"; error(err.str(), pstate, traces); } bool eq_int = std::fabs(trunc(lv) - lv) < NUMBER_EPSILON; if (!eq_int) { sass::sstream err; err << "Expected $limit to be an integer but got " << lv << " for `random'"; error(err.str(), pstate, traces); } std::uniform_real_distribution<> distributor(1, lv + 1); uint_fast32_t distributed = static_cast<uint_fast32_t>(distributor(rand)); return SASS_MEMORY_NEW(Number, pstate, (double)distributed); } else if (b) { std::uniform_real_distribution<> distributor(0, 1); double distributed = static_cast<double>(distributor(rand)); return SASS_MEMORY_NEW(Number, pstate, distributed); } else if (v) { traces.push_back(Backtrace(pstate)); throw Exception::InvalidArgumentType(pstate, traces, "random", "$limit", "number", v); } else { traces.push_back(Backtrace(pstate)); throw Exception::InvalidArgumentType(pstate, traces, "random", "$limit", "number"); } } Signature unique_id_sig = "unique-id()"; BUILT_IN(unique_id) { sass::sstream ss; std::uniform_real_distribution<> distributor(0, 4294967296); // 16^8 uint_fast32_t distributed = static_cast<uint_fast32_t>(distributor(rand)); ss << "u" << std::setfill('0') << std::setw(8) << std::hex << distributed; return SASS_MEMORY_NEW(String_Quoted, pstate, ss.str()); } Signature unit_sig = "unit($number)"; BUILT_IN(unit) { Number_Obj arg = ARGN("$number"); sass::string str(quote(arg->unit(), '"')); return SASS_MEMORY_NEW(String_Quoted, pstate, str); } Signature unitless_sig = "unitless($number)"; BUILT_IN(unitless) { Number_Obj arg = ARGN("$number"); bool unitless = arg->is_unitless(); return SASS_MEMORY_NEW(Boolean, pstate, unitless); } Signature comparable_sig = "comparable($number1, $number2)"; BUILT_IN(comparable) { Number_Obj n1 = ARGN("$number1"); Number_Obj n2 = ARGN("$number2"); if (n1->is_unitless() || n2->is_unitless()) { return SASS_MEMORY_NEW(Boolean, pstate, true); } // normalize into main units n1->normalize(); n2->normalize(); Units &lhs_unit = *n1, &rhs_unit = *n2; bool is_comparable = (lhs_unit == rhs_unit); return SASS_MEMORY_NEW(Boolean, pstate, is_comparable); } } }
// Copyright (C) 2002-2009 Nikolaus Gebhardt // This file is part of the "Irrlicht Engine". // For conditions of distribution and use, see copyright notice in irrlicht.h #include "IrrCompileConfig.h" #ifdef _IRR_COMPILE_WITH_WINDOWS_CE_DEVICE_ #include "CIrrDeviceWinCE.h" #include "IEventReceiver.h" #include "irrList.h" #include "os.h" #include "CTimer.h" #include "irrString.h" #include "COSOperator.h" #include "dimension2d.h" #include <winuser.h> #include "irrlicht.h" #ifdef _MSC_VER #pragma comment (lib, "aygshell.lib") #endif namespace irr { namespace video { #ifdef _IRR_COMPILE_WITH_DIRECT3D_8_ IVideoDriver* createDirectX8Driver(const core::dimension2d<s32>& screenSize, HWND window, u32 bits, bool fullscreen, bool stencilbuffer, io::IFileSystem* io, bool pureSoftware, bool highPrecisionFPU, bool vsync, bool antiAlias); #endif #ifdef _IRR_COMPILE_WITH_DIRECT3D_9_ IVideoDriver* createDirectX9Driver(const core::dimension2d<s32>& screenSize, HWND window, u32 bits, bool fullscreen, bool stencilbuffer, io::IFileSystem* io, bool pureSoftware, bool highPrecisionFPU, bool vsync, bool antiAlias); #endif #ifdef _IRR_COMPILE_WITH_OPENGL_ IVideoDriver* createOpenGLDriver(const irr::SIrrlichtCreationParameters& params, io::IFileSystem* io, this); #endif } } // end namespace irr struct SEnvMapper { HWND hWnd; irr::CIrrDeviceWinCE* irrDev; }; irr::core::list<SEnvMapper> EnvMap; SEnvMapper* getEnvMapperFromHWnd(HWND hWnd) { irr::core::list<SEnvMapper>::Iterator it = EnvMap.begin(); for (; it!= EnvMap.end(); ++it) if ((*it).hWnd == hWnd) return &(*it); return 0; } irr::CIrrDeviceWinCE* getDeviceFromHWnd(HWND hWnd) { irr::core::list<SEnvMapper>::Iterator it = EnvMap.begin(); for (; it!= EnvMap.end(); ++it) if ((*it).hWnd == hWnd) return (*it).irrDev; return 0; } LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { #ifndef WM_MOUSEWHEEL #define WM_MOUSEWHEEL 0x020A #endif #ifndef WHEEL_DELTA #define WHEEL_DELTA 120 #endif irr::CIrrDeviceWinCE* dev = 0; irr::SEvent event; SEnvMapper* envm = 0; //BYTE allKeys[256]; static irr::s32 ClickCount=0; if (GetCapture() != hWnd && ClickCount > 0) ClickCount = 0; switch (message) { case WM_PAINT: { PAINTSTRUCT ps; BeginPaint(hWnd, &ps); EndPaint(hWnd, &ps); } return 0; case WM_ERASEBKGND: return 0; case WM_SETCURSOR: envm = getEnvMapperFromHWnd(hWnd); if (envm && !envm->irrDev->getWin32CursorControl()->isVisible()) { SetCursor(NULL); return 0; } break; case WM_MOUSEWHEEL: event.EventType = irr::EET_MOUSE_INPUT_EVENT; event.MouseInput.Wheel = ((irr::f32)((short)HIWORD(wParam))) / (irr::f32)WHEEL_DELTA; event.MouseInput.Event = irr::EMIE_MOUSE_WHEEL; POINT p; // fixed by jox p.x = 0; p.y = 0; ClientToScreen(hWnd, &p); event.MouseInput.X = LOWORD(lParam) - p.x; event.MouseInput.Y = HIWORD(lParam) - p.y; event.MouseInput.Shift = ((LOWORD(wParam) & MK_SHIFT) != 0); event.MouseInput.Control = ((LOWORD(wParam) & MK_CONTROL) != 0); // left and right mouse buttons event.MouseInput.ButtonStates = wParam & ( MK_LBUTTON | MK_RBUTTON); // middle and extra buttons if (wParam & MK_MBUTTON) event.MouseInput.ButtonStates |= irr::EMBSM_MIDDLE; dev = getDeviceFromHWnd(hWnd); if (dev) dev->postEventFromUser(event); break; case WM_LBUTTONDOWN: ClickCount++; SetCapture(hWnd); event.EventType = irr::EET_MOUSE_INPUT_EVENT; event.MouseInput.Event = irr::EMIE_LMOUSE_PRESSED_DOWN; event.MouseInput.X = (short)LOWORD(lParam); event.MouseInput.Y = (short)HIWORD(lParam); event.MouseInput.Shift = ((LOWORD(wParam) & MK_SHIFT) != 0); event.MouseInput.Control = ((LOWORD(wParam) & MK_CONTROL) != 0); // left and right mouse buttons event.MouseInput.ButtonStates = wParam & ( MK_LBUTTON | MK_RBUTTON); // middle and extra buttons if (wParam & MK_MBUTTON) event.MouseInput.ButtonStates |= irr::EMBSM_MIDDLE; dev = getDeviceFromHWnd(hWnd); if (dev) dev->postEventFromUser(event); return 0; case WM_LBUTTONUP: ClickCount--; if (ClickCount<1) { ClickCount=0; ReleaseCapture(); } event.EventType = irr::EET_MOUSE_INPUT_EVENT; event.MouseInput.Event = irr::EMIE_LMOUSE_LEFT_UP; event.MouseInput.X = (short)LOWORD(lParam); event.MouseInput.Y = (short)HIWORD(lParam); event.MouseInput.Shift = ((LOWORD(wParam) & MK_SHIFT) != 0); event.MouseInput.Control = ((LOWORD(wParam) & MK_CONTROL) != 0); // left and right mouse buttons event.MouseInput.ButtonStates = wParam & ( MK_LBUTTON | MK_RBUTTON); // middle and extra buttons if (wParam & MK_MBUTTON) event.MouseInput.ButtonStates |= irr::EMBSM_MIDDLE; dev = getDeviceFromHWnd(hWnd); if (dev) dev->postEventFromUser(event); return 0; case WM_RBUTTONDOWN: ClickCount++; SetCapture(hWnd); event.EventType = irr::EET_MOUSE_INPUT_EVENT; event.MouseInput.Event = irr::EMIE_RMOUSE_PRESSED_DOWN; event.MouseInput.X = (short)LOWORD(lParam); event.MouseInput.Y = (short)HIWORD(lParam); event.MouseInput.Shift = ((LOWORD(wParam) & MK_SHIFT) != 0); event.MouseInput.Control = ((LOWORD(wParam) & MK_CONTROL) != 0); // left and right mouse buttons event.MouseInput.ButtonStates = wParam & ( MK_LBUTTON | MK_RBUTTON); // middle and extra buttons if (wParam & MK_MBUTTON) event.MouseInput.ButtonStates |= irr::EMBSM_MIDDLE; dev = getDeviceFromHWnd(hWnd); if (dev) dev->postEventFromUser(event); return 0; case WM_RBUTTONUP: ClickCount--; if (ClickCount<1) { ClickCount=0; ReleaseCapture(); } event.EventType = irr::EET_MOUSE_INPUT_EVENT; event.MouseInput.Event = irr::EMIE_RMOUSE_LEFT_UP; event.MouseInput.X = (short)LOWORD(lParam); event.MouseInput.Y = (short)HIWORD(lParam); event.MouseInput.Shift = ((LOWORD(wParam) & MK_SHIFT) != 0); event.MouseInput.Control = ((LOWORD(wParam) & MK_CONTROL) != 0); // left and right mouse buttons event.MouseInput.ButtonStates = wParam & ( MK_LBUTTON | MK_RBUTTON); // middle and extra buttons if (wParam & MK_MBUTTON) event.MouseInput.ButtonStates |= irr::EMBSM_MIDDLE; dev = getDeviceFromHWnd(hWnd); if (dev) dev->postEventFromUser(event); return 0; case WM_MBUTTONDOWN: ClickCount++; SetCapture(hWnd); event.EventType = irr::EET_MOUSE_INPUT_EVENT; event.MouseInput.Event = irr::EMIE_MMOUSE_PRESSED_DOWN; event.MouseInput.X = (short)LOWORD(lParam); event.MouseInput.Y = (short)HIWORD(lParam); event.MouseInput.Shift = ((LOWORD(wParam) & MK_SHIFT) != 0); event.MouseInput.Control = ((LOWORD(wParam) & MK_CONTROL) != 0); // left and right mouse buttons event.MouseInput.ButtonStates = wParam & ( MK_LBUTTON | MK_RBUTTON); // middle and extra buttons if (wParam & MK_MBUTTON) event.MouseInput.ButtonStates |= irr::EMBSM_MIDDLE; dev = getDeviceFromHWnd(hWnd); if (dev) dev->postEventFromUser(event); return 0; case WM_MBUTTONUP: ClickCount--; if (ClickCount<1) { ClickCount=0; ReleaseCapture(); } event.EventType = irr::EET_MOUSE_INPUT_EVENT; event.MouseInput.Event = irr::EMIE_MMOUSE_LEFT_UP; event.MouseInput.X = (short)LOWORD(lParam); event.MouseInput.Y = (short)HIWORD(lParam); event.MouseInput.Shift = ((LOWORD(wParam) & MK_SHIFT) != 0); event.MouseInput.Control = ((LOWORD(wParam) & MK_CONTROL) != 0); // left and right mouse buttons event.MouseInput.ButtonStates = wParam & ( MK_LBUTTON | MK_RBUTTON); // middle and extra buttons if (wParam & MK_MBUTTON) event.MouseInput.ButtonStates |= irr::EMBSM_MIDDLE; dev = getDeviceFromHWnd(hWnd); if (dev) dev->postEventFromUser(event); return 0; case WM_MOUSEMOVE: event.EventType = irr::EET_MOUSE_INPUT_EVENT; event.MouseInput.Event = irr::EMIE_MOUSE_MOVED; event.MouseInput.X = (short)LOWORD(lParam); event.MouseInput.Y = (short)HIWORD(lParam); event.MouseInput.Shift = ((LOWORD(wParam) & MK_SHIFT) != 0); event.MouseInput.Control = ((LOWORD(wParam) & MK_CONTROL) != 0); // left and right mouse buttons event.MouseInput.ButtonStates = wParam & ( MK_LBUTTON | MK_RBUTTON); // middle and extra buttons if (wParam & MK_MBUTTON) event.MouseInput.ButtonStates |= irr::EMBSM_MIDDLE; dev = getDeviceFromHWnd(hWnd); if (dev) dev->postEventFromUser(event); return 0; case WM_SYSKEYDOWN: case WM_SYSKEYUP: case WM_KEYDOWN: case WM_KEYUP: { event.EventType = irr::EET_KEY_INPUT_EVENT; event.KeyInput.Key = (irr::EKEY_CODE)wParam; event.KeyInput.PressedDown = (message==WM_KEYDOWN || message == WM_SYSKEYDOWN); dev = getDeviceFromHWnd(hWnd); /* WORD KeyAsc=0; GetKeyboardState(allKeys); ToAscii(wParam,lParam,allKeys,&KeyAsc,0); */ // event.KeyInput.Shift = ((allKeys[VK_SHIFT] & 0x80)!=0); // event.KeyInput.Control = ((allKeys[VK_CONTROL] & 0x80)!=0); // event.KeyInput.Char = (KeyAsc & 0x00ff); //KeyAsc >= 0 ? KeyAsc : 0; if (dev) dev->postEventFromUser(event); return 0; } case WM_SIZE: { // resize dev = getDeviceFromHWnd(hWnd); if (dev) dev->OnResized(); } return 0; case WM_DESTROY: PostQuitMessage(0); return 0; } return DefWindowProc(hWnd, message, wParam, lParam); } namespace irr { //! constructor CIrrDeviceWinCE::CIrrDeviceWinCE(const SIrrlichtCreationParameters& params) : CIrrDeviceStub(params), HWnd(0), Win32CursorControl(0), ChangedToFullScreen(false), Resized(false), ExternalWindow(false) { #ifdef _DEBUG setDebugName("CIrrDeviceWinCE"); #endif core::stringc winversion; getWindowsVersion(winversion); Operator = new COSOperator(winversion.c_str()); os::Printer::log(winversion.c_str(), ELL_INFORMATION); HINSTANCE hInstance = GetModuleHandle(0); // create the window only if we do not use the null device if (!CreationParams.WindowId && (CreationParams.DriverType != video::EDT_NULL)) { const wchar_t* ClassName = L"CIrrDeviceWinCE"; // Register Class WNDCLASS wc; wc.style = CS_HREDRAW | CS_VREDRAW; wc.lpfnWndProc = WndProc; wc.cbClsExtra = 0; wc.cbWndExtra = 0; wc.hInstance = hInstance; wc.hIcon = NULL; wc.hCursor = LoadCursor(NULL, IDC_ARROW); wc.hbrBackground = (HBRUSH)(COLOR_WINDOW+1); wc.lpszMenuName = 0; wc.lpszClassName = ClassName; // if there is an icon, load it wc.hIcon = (HICON)LoadImageW(hInstance, L"irrlicht.ico", IMAGE_ICON, 0,0, 0); RegisterClass(&wc); // calculate client size RECT clientSize; clientSize.top = 0; clientSize.left = 0; clientSize.right = CreationParams.WindowSize.Width; clientSize.bottom = CreationParams.WindowSize.Height; DWORD style = WS_POPUP; if (!CreationParams.Fullscreen) style = WS_SYSMENU | WS_BORDER | WS_CAPTION | WS_CLIPCHILDREN | WS_CLIPSIBLINGS; AdjustWindowRectEx(&clientSize, style, FALSE, 0); const s32 realWidth = clientSize.right - clientSize.left; const s32 realHeight = clientSize.bottom - clientSize.top; const s32 windowLeft = core::s32_max ( 0, (GetSystemMetrics(SM_CXSCREEN) - realWidth) >> 1 ); const s32 windowTop = core::s32_max ( 0, (GetSystemMetrics(SM_CYSCREEN) - realHeight) >> 1 ); // create window HWnd = CreateWindowW( ClassName, L"", style, windowLeft, windowTop, realWidth, realHeight, NULL, NULL, hInstance, NULL); ShowWindow(HWnd , SW_SHOW); UpdateWindow(HWnd); // fix ugly ATI driver bugs. Thanks to ariaci MoveWindow(HWnd, windowLeft, windowTop, realWidth, realHeight, TRUE); } else if (CreationParams.WindowId) { // attach external window HWnd = static_cast<HWND>(CreationParams.WindowId); RECT r; GetWindowRect(HWnd, &r); CreationParams.WindowSize.Width = r.right - r.left; CreationParams.WindowSize.Height = r.bottom - r.top; CreationParams.Fullscreen = false; ExternalWindow = true; } // create cursor control Win32CursorControl = new CCursorControl(CreationParams.WindowSize, HWnd, CreationParams.Fullscreen); CursorControl = Win32CursorControl; // create driver createDriver(); if (VideoDriver) createGUIAndScene(); // register environment SEnvMapper em; em.irrDev = this; em.hWnd = HWnd; EnvMap.push_back(em); // set this as active window SetActiveWindow(HWnd); SetForegroundWindow(HWnd); } //! destructor CIrrDeviceWinCE::~CIrrDeviceWinCE() { // unregister environment if (ChangedToFullScreen) SHFullScreen(HWnd, SHFS_SHOWTASKBAR | SHFS_SHOWSTARTICON | SHFS_SHOWSIPBUTTON); irr::core::list<SEnvMapper>::Iterator it = EnvMap.begin(); for (; it!= EnvMap.end(); ++it) if ((*it).hWnd == HWnd) { EnvMap.erase(it); break; } } //! create the driver void CIrrDeviceWinCE::createDriver() { switch(CreationParams.DriverType) { case video::EDT_DIRECT3D8: #ifdef _IRR_COMPILE_WITH_DIRECT3D_8_ VideoDriver = video::createDirectX8Driver(CreationParams.WindowSize, HWnd, CreationParams.Bits, CreationParams.Fullscreen, CreationParams.Stencilbuffer, FileSystem, false, CreationParams.HighPrecisionFPU, CreationParams.Vsync, CreationParams.AntiAlias); if (!VideoDriver) { os::Printer::log("Could not create DIRECT3D8 Driver.", ELL_ERROR); } #else os::Printer::log("DIRECT3D8 Driver was not compiled into this dll. Try another one.", ELL_ERROR); #endif // _IRR_COMPILE_WITH_DIRECT3D_8_ break; case video::EDT_DIRECT3D9: #ifdef _IRR_COMPILE_WITH_DIRECT3D_9_ VideoDriver = video::createDirectX9Driver(CreationParams.WindowSize, HWnd, CreationParams.Bits, CreationParams.Fullscreen, CreationParams.Stencilbuffer, FileSystem, false, CreationParams.HighPrecisionFPU, CreationParams.Vsync, CreationParams.AntiAlias); if (!VideoDriver) { os::Printer::log("Could not create DIRECT3D9 Driver.", ELL_ERROR); } #else os::Printer::log("DIRECT3D9 Driver was not compiled into this dll. Try another one.", ELL_ERROR); #endif // _IRR_COMPILE_WITH_DIRECT3D_9_ break; case video::EDT_OPENGL: #ifdef _IRR_COMPILE_WITH_OPENGL_ if (CreationParams.Fullscreen) switchToFullScreen(); VideoDriver = video::createOpenGLDriver(CreationParams, FileSystem); if (!VideoDriver) { os::Printer::log("Could not create OpenGL driver.", ELL_ERROR); } #else os::Printer::log("OpenGL driver was not compiled in.", ELL_ERROR); #endif break; case video::EDT_SOFTWARE: #ifdef _IRR_COMPILE_WITH_SOFTWARE_ if (CreationParams.Fullscreen) switchToFullScreen(); VideoDriver = video::createSoftwareDriver(CreationParams.WindowSize, CreationParams.Fullscreen, FileSystem, this); #else os::Printer::log("Software driver was not compiled in.", ELL_ERROR); #endif break; case video::EDT_BURNINGSVIDEO: #ifdef _IRR_COMPILE_WITH_BURNINGSVIDEO_ if (CreationParams.Fullscreen) switchToFullScreen(); VideoDriver = video::createSoftwareDriver2(CreationParams.WindowSize, CreationParams.Fullscreen, FileSystem, this); #else os::Printer::log("Burning's Video driver was not compiled in.", ELL_ERROR); #endif break; case video::EDT_NULL: // create null driver VideoDriver = video::createNullDriver(FileSystem, CreationParams.WindowSize); break; default: os::Printer::log("Unable to create video driver of unknown type.", ELL_ERROR); break; } } //! runs the device. Returns false if device wants to be deleted bool CIrrDeviceWinCE::run() { os::Timer::tick(); MSG msg; while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) { TranslateMessage(&msg); if (ExternalWindow && msg.hwnd == HWnd) WndProc(HWnd, msg.message, msg.wParam, msg.lParam); else DispatchMessage(&msg); if (msg.message == WM_QUIT) Close = true; } if (!Close) resizeIfNecessary(); _IRR_IMPLEMENT_MANAGED_MARSHALLING_BUGFIX; return !Close; } //! Pause the current process for the minimum time allowed only to allow other processes to execute void CIrrDeviceWinCE::yield() { Sleep(1); } //! Pause execution and let other processes to run for a specified amount of time. void CIrrDeviceWinCE::sleep(u32 timeMs, bool pauseTimer) { const bool wasStopped = Timer ? Timer->isStopped() : true; if (pauseTimer && !wasStopped) Timer->stop(); Sleep(timeMs); if (pauseTimer && !wasStopped) Timer->start(); } void CIrrDeviceWinCE::resizeIfNecessary() { if (!Resized) return; RECT r; GetClientRect(HWnd, &r); char tmp[255]; if (r.right < 2 || r.bottom < 2) { sprintf(tmp, "Ignoring resize operation to (%ld %ld)", r.right, r.bottom); os::Printer::log(tmp); } else { sprintf(tmp, "Resizing window (%ld %ld)", r.right, r.bottom); os::Printer::log(tmp); getVideoDriver()->OnResize(irr::core::dimension2d<irr::u32>(r.right, r.bottom)); getWin32CursorControl()->OnResize(getVideoDriver()->getScreenSize()); } Resized = false; } //! sets the caption of the window void CIrrDeviceWinCE::setWindowCaption(const wchar_t* text) { SetWindowTextW(HWnd, text); } #if !defined(BITMAPV4HEADER) typedef struct { DWORD bV4Size; LONG bV4Width; LONG bV4Height; WORD bV4Planes; WORD bV4BitCount; DWORD bV4V4Compression; DWORD bV4SizeImage; LONG bV4XPelsPerMeter; LONG bV4YPelsPerMeter; DWORD bV4ClrUsed; DWORD bV4ClrImportant; DWORD bV4RedMask; DWORD bV4GreenMask; DWORD bV4BlueMask; DWORD bV4AlphaMask; DWORD bV4CSType; DWORD un[9]; } BITMAPV4HEADER, *PBITMAPV4HEADER; #endif //! presents a surface in the client area bool CIrrDeviceWinCE::present(video::IImage* image, void* windowId, core::rect<s32>* src) { HWND hwnd = HWnd; if ( windowId ) hwnd = (HWND)windowId; HDC dc = GetDC(hwnd); if ( dc ) { RECT rect; GetClientRect(hwnd, &rect); const void* memory = (const void *)image->lock(); BITMAPV4HEADER bi; memset (&bi, 0, sizeof(bi)); bi.bV4Size = sizeof(BITMAPINFOHEADER); bi.bV4BitCount = image->getBitsPerPixel(); bi.bV4Planes = 1; bi.bV4Width = image->getDimension().Width; bi.bV4Height = 0 - image->getDimension().Height; bi.bV4V4Compression = BI_BITFIELDS; bi.bV4AlphaMask = image->getAlphaMask (); bi.bV4RedMask = image->getRedMask (); bi.bV4GreenMask = image->getGreenMask(); bi.bV4BlueMask = image->getBlueMask(); int r = 0; if ( src ) { r = StretchDIBits(dc, 0,0, rect.right, rect.bottom, src->UpperLeftCorner.X, src->UpperLeftCorner.Y, src->getWidth(), src->getHeight(), memory, (const BITMAPINFO*)(&bi), DIB_RGB_COLORS, SRCCOPY); } else { r = StretchDIBits(dc, 0,0, rect.right, rect.bottom, 0, 0, image->getDimension().Width, image->getDimension().Height, memory, (const BITMAPINFO*)(&bi), DIB_RGB_COLORS, SRCCOPY); } image->unlock(); ReleaseDC(hwnd, dc); } return true; } //! notifies the device that it should close itself void CIrrDeviceWinCE::closeDevice() { MSG msg; PeekMessage(&msg, NULL, WM_QUIT, WM_QUIT, PM_REMOVE); PostQuitMessage(0); PeekMessage(&msg, NULL, WM_QUIT, WM_QUIT, PM_REMOVE); DestroyWindow(HWnd); Close=true; } //! returns if window is active. if not, nothing need to be drawn bool CIrrDeviceWinCE::isWindowActive() const { bool ret = (GetActiveWindow() == HWnd); _IRR_IMPLEMENT_MANAGED_MARSHALLING_BUGFIX; return ret; } //! returns if window has focus bool CIrrDeviceWinCE::isWindowFocused() const { bool ret = (GetFocus() == HWnd); _IRR_IMPLEMENT_MANAGED_MARSHALLING_BUGFIX; return ret; } //! returns if window is minimized bool CIrrDeviceWinCE::isWindowMinimized() const { #if 0 WINDOWPLACEMENT plc; plc.length=sizeof(WINDOWPLACEMENT); bool ret=false; if (GetWindowPlacement(HWnd,&plc)) ret=(plc.showCmd & SW_SHOWMINIMIZED); _IRR_IMPLEMENT_MANAGED_MARSHALLING_BUGFIX; return ret; #endif return false; } //! switches to fullscreen bool CIrrDeviceWinCE::switchToFullScreen() { ChangedToFullScreen = SHFullScreen(HWnd, SHFS_HIDESIPBUTTON | SHFS_HIDETASKBAR) != 0; return ChangedToFullScreen; } //! returns the win32 cursor control CIrrDeviceWinCE::CCursorControl* CIrrDeviceWinCE::getWin32CursorControl() { return Win32CursorControl; } //! Return pointer to a list with all video modes supported by the gfx adapter. /** \return Pointer to video modes list */ video::IVideoModeList* CIrrDeviceWinCE::getVideoModeList() { if (!VideoModeList.getVideoModeCount()) { // enumerate video modes. DWORD i=0; DEVMODE mode; memset(&mode, 0, sizeof(mode)); mode.dmSize = sizeof(mode); while (EnumDisplaySettings(NULL, i, &mode)) { VideoModeList.addMode(core::dimension2d<u32>(mode.dmPelsWidth, mode.dmPelsHeight), mode.dmBitsPerPel); ++i; } if (EnumDisplaySettings(NULL, ENUM_CURRENT_SETTINGS, &mode)) VideoModeList.setDesktop(mode.dmBitsPerPel, core::dimension2d<u32>(mode.dmPelsWidth, mode.dmPelsHeight)); } return &VideoModeList; } void CIrrDeviceWinCE::getWindowsVersion(core::stringc& out) { out = "WinCE"; } //! Notifies the device, that it has been resized void CIrrDeviceWinCE::OnResized() { Resized = true; } //! Sets if the window should be resizable in windowed mode. void CIrrDeviceWinCE::setResizable(bool resize) { if (ExternalWindow || !getVideoDriver() || CreationParams.Fullscreen) return; LONG style = WS_POPUP; if (!resize) style = WS_SYSMENU | WS_BORDER | WS_CAPTION | WS_CLIPCHILDREN | WS_CLIPSIBLINGS; else style = WS_THICKFRAME | WS_SYSMENU | WS_CAPTION | WS_CLIPCHILDREN | WS_CLIPSIBLINGS | WS_MAXIMIZEBOX; if (!SetWindowLong(HWnd, GWL_STYLE, style)) os::Printer::log("Could not change window style."); RECT clientSize; clientSize.top = 0; clientSize.left = 0; clientSize.right = getVideoDriver()->getScreenSize().Width; clientSize.bottom = getVideoDriver()->getScreenSize().Height; AdjustWindowRectEx(&clientSize, style, FALSE, 0); const s32 realWidth = clientSize.right - clientSize.left; const s32 realHeight = clientSize.bottom - clientSize.top; const s32 windowLeft = (GetSystemMetrics(SM_CXSCREEN) - realWidth) / 2; const s32 windowTop = (GetSystemMetrics(SM_CYSCREEN) - realHeight) / 2; SetWindowPos(HWnd, HWND_TOP, windowLeft, windowTop, realWidth, realHeight, SWP_FRAMECHANGED | SWP_NOMOVE | SWP_SHOWWINDOW); } //! Minimizes the window. void CIrrDeviceWinCE::minimizeWindow() { // do nothing } //! Maximize window void CIrrDeviceWinCE::maximizeWindow() { // do nothing } //! Restore original window size void CIrrDeviceWinCE::restoreWindow() { // do nothing } } // end namespace #endif // _IRR_COMPILE_WITH_WINDOWS_CE_DEVICE_
#include <easy/profiler.h> #include <easy/reader.h> #include <fstream> #include <list> #include <iostream> #include <map> #include <stack> #include <vector> #include <iterator> #include <algorithm> #include <ctime> #include <chrono> #include <iostream> #include <string> #include <sstream> class TreePrinter { struct Info{ std::string name; std::string info; }; std::vector<Info> m_rows; public: TreePrinter(){ } void addNewRow(int level) { } void printTree() { for (auto& row : m_rows){ std::cout << row.name << " " << row.info << std::endl; } } }; void printTree(TreePrinter& printer, const profiler::BlocksTree& tree, int level = 0, profiler::timestamp_t parent_dur = 0, profiler::timestamp_t root_dur = 0) { // //if (tree.node){ // auto duration = tree.node->block()->duration(); // float duration_ms = duration / 1e6f; // float percent = parent_dur ? float(duration) / float(parent_dur)*100.0f : 100.0f; // float rpercent = root_dur ? float(duration) / float(root_dur)*100.0f : 100.0f; // std::cout << std::string(level, '\t') << tree.node->getName() // << std::string(5 - level, '\t') // /*<< std::string(level, ' ')*/ << percent << "%| " // << rpercent << "%| " // << duration_ms << " ms" // << std::endl; // if (root_dur == 0){ // root_dur = tree.node->block()->duration(); // } //} //else{ // root_dur = 0; //} // //for (const auto& i : tree.children){ // printTree(printer, i, level + 1, tree.node ? tree.node->block()->duration() : 0, root_dur); //} } int main(int argc, char* argv[]) { profiler::thread_blocks_tree_t threaded_trees; ::std::string filename;// = "test.prof"; if (argc > 1 && argv[1]) { filename = argv[1]; } else { std::cout << "Specify prof file: "; std::getline(std::cin, filename); //return 255; } ::std::string dump_filename; if (argc > 2 && argv[2]) { dump_filename = argv[2]; } else { std::cout << "Specify output prof file: "; std::getline(std::cin, dump_filename); } if (dump_filename.size() > 2) { EASY_PROFILER_ENABLE; std::cout << "Will dump reader prof file to " << dump_filename << std::endl; } else { dump_filename.clear(); } auto start = std::chrono::system_clock::now(); profiler::SerializedData serialized_blocks, serialized_descriptors; profiler::descriptors_list_t descriptors; profiler::blocks_t blocks; profiler::bookmarks_t bookmarks; profiler::BeginEndTime beginEndTime; std::stringstream errorMessage; uint32_t descriptorsNumberInFile = 0; uint32_t version = 0; profiler::processid_t pid = 0; auto blocks_counter = fillTreesFromFile(filename.c_str(), beginEndTime, serialized_blocks, serialized_descriptors, descriptors, blocks, threaded_trees, bookmarks, descriptorsNumberInFile, version, pid, true, errorMessage); if (blocks_counter == 0) std::cout << "Can not read blocks from file " << filename.c_str() << "\nReason: " << errorMessage.str(); auto end = std::chrono::system_clock::now(); std::cout << "Blocks count: " << blocks_counter << std::endl; std::cout << "dT = " << std::chrono::duration_cast<std::chrono::microseconds>(end - start).count() << " usec" << std::endl; //for (const auto & i : threaded_trees){ // TreePrinter p; // std::cout << std::string(20, '=') << " thread "<< i.first << " "<< std::string(20, '=') << std::endl; // printTree(p, i.second.tree,-1); //} if (!dump_filename.empty()) { auto bcount = profiler::dumpBlocksToFile(dump_filename.c_str()); std::cout << "Blocks count for reader: " << bcount << std::endl; } //char c; //::std::cin >> c; return 0; }
// *************************************************************** // Copyright (c) 2021 Jittor. All Rights Reserved. // Maintainers: Dun Liang <randonlang@gmail.com>. // This file is subject to the terms and conditions defined in // file 'LICENSE.txt', which is part of this source code package. // *************************************************************** #include "utils/str_utils.h" namespace jittor { bool startswith(const string& a, const string& b, uint start, bool equal, uint end) { if (!end) end = a.size(); if (b.size()+start > end) return false; if (equal && b.size()+start != end) return false; for (uint i=0; i<b.size(); i++) if (a[i+start] != b[i]) return false; return true; } bool endswith(const string& a, const string& b) { if (a.size() < b.size()) return false; return startswith(a, b, a.size()-b.size()); } vector<string> split(const string& s, const string& sep, int max_split) { vector<string> ret; int pos = -1, pos_next; while (1) { pos_next = s.find(sep, pos+1); if (pos_next == (int)string::npos || (int)ret.size() == max_split-1) { ret.push_back(s.substr(pos+sep.size())); return ret; } ret.push_back(s.substr(pos+sep.size(), pos_next-pos-sep.size())); pos = pos_next; } ASSERT(max_split==0); return ret; } string strip(const string& s) { int i=0; while (i<s.size() && (s[i]==' ' || s[i]=='\t' || s[i]=='\n')) i++; int j = s.size(); while (j>i && (s[j]==' ' || s[j]=='\t' || s[j]=='\n')) j--; return s.substr(i,j-i); } } // jittor
/* * bits-fun.cpp * * Created on: Dec 14, 2015 * Author: zmij */ #include <iostream> #include <iomanip> #include <bitset> #include <cstdlib> const int FIRST_COL = 30; int main(int argc, char* argv[]) { typedef int32_t signed_type; typedef std::make_unsigned<signed_type>::type unsigned_type; const uint32_t bits_count = sizeof(unsigned_type) * 8 - 1; typedef std::bitset< bits_count + 1 > bits_type; try { if (argc < 2) return 1; for (int i = 1; i < argc; ++i) { signed_type v = std::atoi(argv[i]); unsigned_type e = static_cast< unsigned_type >((v << 1) ^ (v >> bits_count)); std::cout << std::setfill(' ') << v << "\n" << std::setw(FIRST_COL) << std::left << "v =" << bits_type(v) << "\n" << std::setw(FIRST_COL) << std::left << "v << 1 =" << bits_type(v << 1) << "\n" << std::setw(FIRST_COL) << std::left << "v >> " << bits_count << " =" << bits_type(v >> bits_count) << "\n" << std::setw(FIRST_COL) << std::left << "(v << 1) ^ (v >> " << bits_count << ") =" << bits_type((v << 1) ^ (v >> bits_count)) << "\n" ; //std::cout << std::setw(FIRST_COL) << std::setfill('*') << '*' << "\n"; std::cout << std::setfill(' ') << std::setw(FIRST_COL) << std::left << "e << " << bits_count << " =" << bits_type(e << bits_count) << "\n" << std::setw(FIRST_COL) << std::left << "e << " << bits_count << " >> " << bits_count << " =" << bits_type(e << bits_count >> bits_count) << "\n" << std::setw(FIRST_COL) << std::left << "(e >> 1) ^ (e << " << bits_count << " >> " << bits_count << ") =" << bits_type((e >> 1) ^ (e << bits_count >> bits_count)) << "\n" ; std::cout << ((static_cast< signed_type >((e >> 1) ^ (static_cast<signed_type>(e) << bits_count >> bits_count)) == v) ? "OK" : "FAIL") << "\n"; std::cout << std::setw(80) << std::setfill('=') << '=' << "\n"; } } catch (std::exception const& e) { std::cerr << "Exception: " << e.what() << "\n"; return 1; } return 0; }
/* kitty: C++ truth table library * Copyright (C) 2017-2021 EPFL * * 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. */ /*! \file spp.hpp \brief Implements methods to compute SPP representations \author Mathias Soeken */ #pragma once #include <cstdint> #include <utility> #include <vector> #include "cube.hpp" #include "traits.hpp" namespace kitty { /*! \brief Merges products in an ESOP into pseudo products Given, e.g., the two cubes `abc` and `abd`, this algorithm will combine them into a single cube `ab(c+d)`. The term `(c+d)` is stored as a literal in the first argument of the result pair, starting free indexes after `num_vars`. Which literals are used is stored in the second argument of the result pair, as bitpattern over the original inputs. \param esop ESOP form \param num_vars Number of variables in ESOP form */ std::pair<std::vector<cube>, std::vector<uint64_t>> simple_spp( const std::vector<cube>& esop, uint32_t num_vars ) { auto next_free = num_vars; std::vector<uint64_t> sums; auto e = esop.size(); auto copy = esop; const auto var_mask = ( 1u << num_vars ) - 1; for ( auto i = 0u; i < e; ++i ) { auto& c = copy[i]; if ( ( c._mask & 0b1111 ) != c._mask ) { continue; } const auto it = std::find_if( copy.begin() + i, copy.begin() + e, [&]( auto const& c2 ) { bool cnd1 = ( c2._mask & var_mask ) == c2._mask; const auto same_mask = c._mask & c2._mask; bool cnd2 = ( c._bits & same_mask ) == ( c2._bits & same_mask ); bool cnd3 = __builtin_popcount( c._mask & ~c2._mask ) == 1; bool cnd4 = __builtin_popcount( ~c._mask & c2._mask ) == 1; return cnd1 && cnd2 && cnd3 && cnd4; } ); if ( it != copy.begin() + e ) { auto to_delete = c._mask ^ it->_mask; c._mask &= ~to_delete; c.add_literal( next_free++, __builtin_popcount( ( c._bits | it->_bits ) & to_delete ) % 2 == 0 ); c._bits &= ~to_delete; sums.push_back( to_delete ); --e; std::swap( *it, copy[e] ); } } copy.resize( e ); return {copy, sums}; } /*! \brief Creates truth table from SPP This method is helpful to check which truth table is computed by an SPP form. */ template<typename TT> void create_from_spp( TT& tt, const std::vector<cube>& cubes, const std::vector<uint64_t>& sums ) { static_assert( is_complete_truth_table<TT>::value, "Can only be applied on complete truth tables." ); clear( tt ); for ( auto cube : cubes ) { auto product = ~tt.construct(); /* const1 of same size */ auto bits = cube._bits; auto mask = cube._mask; for ( auto i = 0u; i < tt.num_vars(); ++i ) { if ( mask & 1 ) { auto var = tt.construct(); create_nth_var( var, i, !( bits & 1 ) ); product &= var; } bits >>= 1; mask >>= 1; } for ( auto i = 0u; i < sums.size(); ++i ) { if ( mask & 1 ) { auto ssum = tt.construct(); for ( auto j = 0u; j < tt.num_vars(); ++j ) { if ( ( sums[i] >> j ) & 1 ) { auto var = tt.construct(); create_nth_var( var, j ); ssum ^= var; } } if ( !( bits & 1 ) ) { ssum = ~ssum; } product &= ssum; } bits >>= 1; mask >>= 1; } tt ^= product; } } } // namespace kitty
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #include "pch.h" #include "SandboxBridge.h" #include "SandboxJSExecutor.h" #include <cxxreact/JSBigString.h> #include <cxxreact/ModuleRegistry.h> #include <cxxreact/RAMBundleRegistry.h> #include <agents.h> #include <folly/dynamic.h> #include <folly/json.h> #include <chrono> using namespace std; using namespace Concurrency; // OFFICEDEV: Ignore warnings #pragma warning(push) #pragma warning(disable : 4100 4101 4244 4290 4456) namespace facebook { namespace react { #if !defined(OSS_RN) std::unique_ptr<ExecutorDelegate> SandboxDelegateFactory::createExecutorDelegate( std::shared_ptr<ModuleRegistry> registry, std::shared_ptr<InstanceCallback> callback) { return std::unique_ptr<ExecutorDelegate>( new SandboxJsToNativeBridge(registry, callback, m_sendNativeModuleCall)); } std::unique_ptr<ExecutorDelegate> SandboxExecutorDelegateFactory::createExecutorDelegate( std::shared_ptr<ModuleRegistry> registry, std::shared_ptr<InstanceCallback> callback) { return std::unique_ptr<ExecutorDelegate>( new SandboxHostNativeBridge(registry, callback)); } SandboxJSExecutorFactory::SandboxJSExecutorFactory( JSECreator &&jsExecutorFactory) : m_jseCreater(std::move(jsExecutorFactory)) {} std::unique_ptr<JSExecutor> SandboxJSExecutorFactory::createJSExecutor( std::shared_ptr<ExecutorDelegate> delegate, std::shared_ptr<MessageQueueThread> jsQueue) { if (m_jseCreater) { return m_jseCreater(delegate, jsQueue); } else { return std::unique_ptr<JSExecutor>( new SandboxJSExecutor(delegate, jsQueue)); } } template <typename Func> auto create_delayed_task( std::chrono::milliseconds delay, Func func, concurrency::cancellation_token token = concurrency::cancellation_token::none()) -> decltype(create_task(func)) { concurrency::task_completion_event<void> tce; auto pTimer = new concurrency::timer<int>( static_cast<int>(delay.count()), 0, NULL, false); auto pCallback = new concurrency::call<int>([tce](int) { tce.set(); }); pTimer->link_target(pCallback); pTimer->start(); token.register_callback([tce]() { tce.set(); }); return create_task(tce) .then([pCallback, pTimer]() { delete pCallback; delete pTimer; }) .then(func, token); } SandboxJSExecutor::SandboxJSExecutor( std::shared_ptr<ExecutorDelegate> delegate, std::shared_ptr<MessageQueueThread> messageQueueThread) : m_delegate(delegate), m_messageQueueThread(messageQueueThread) {} SandboxJSExecutor::~SandboxJSExecutor() {} void SandboxJSExecutor::loadApplicationScript( std::unique_ptr<const JSBigString> script, uint64_t /*scriptVersion*/, std::string sourceURL, std::string && /*bytecodeFileName*/) { auto requestId = GetNextRequestId(); task_completion_event<void> callback; m_callbacks.emplace(requestId, callback); folly::dynamic request = folly::dynamic::object("script", script->c_str())( "inject", m_injectedObjects)("url", sourceURL); try { SendMessageAsync(requestId, "executeApplicationScript", request) .then([callback](bool success) { if (success) { // Return task to wait for reply. return task<void>(callback); } else { throw new exception("Failed to send"); } }) .get(); } // TODO: handle exceptions in a better way catch (exception &e) { m_errorCallback(e.what()); SetState(State::Error); } } void SandboxJSExecutor::registerBundle( uint32_t /*bundleId*/, const std::string & /*bundlePath*/) { // NYI std::terminate(); } void SandboxJSExecutor::setBundleRegistry( std::unique_ptr<RAMBundleRegistry> bundleRegistry) {} void SandboxJSExecutor::callFunction( const std::string &moduleId, const std::string &methodId, const folly::dynamic &arguments) { if (IsInError()) { return; } folly::dynamic jarray = folly::dynamic::array(moduleId, methodId, arguments); Call("callFunction", jarray); } void SandboxJSExecutor::invokeCallback( const double callbackId, const folly::dynamic &arguments) { if (IsInError()) { return; } folly::dynamic jarray = folly::dynamic::array(callbackId, arguments); Call("invokeCallback", jarray); } void SandboxJSExecutor::setGlobalVariable( std::string propName, std::unique_ptr<const JSBigString> jsonValue) { m_injectedObjects[propName] = std::string(jsonValue->c_str()); } void *SandboxJSExecutor::getJavaScriptContext() { return nullptr; } std::string SandboxJSExecutor::getDescription() { return "SandboxJSExecutor"; } #ifdef WITH_JSC_MEMORY_PRESSURE void SandboxJSExecutor::handleMemoryPressure(int pressureLevel) {} #endif void SandboxJSExecutor::destroy() { SetState(State::Disposed); if (m_sandboxEndpoint) { m_sandboxEndpoint->Shutdown(); } } // NOTE: This function synchronously waiting until get reply back from the // sandbox. // TODO: Indefinite waiting can cause SDX to become unresponsive. We need to // implement timeout mechanism. void SandboxJSExecutor::Call( const std::string &methodName, folly::dynamic &arguments) { auto requestId = GetNextRequestId(); task_completion_event<void> callback; m_callbacks.emplace(requestId, callback); try { std::chrono::high_resolution_clock::time_point t1 = std::chrono::high_resolution_clock::now(); SendMessageAsync(requestId, methodName, arguments) .then([callback](bool sent) { if (sent) { // Return task to wait for reply. return task<void>(callback); } else { throw new exception("Failed to send"); } }) .get(); // wait until get reply std::chrono::high_resolution_clock::time_point t2 = std::chrono::high_resolution_clock::now(); auto duration = std::chrono::duration_cast<std::chrono::microseconds>(t2 - t1).count(); char buffer[256]; sprintf_s( buffer, "(%03I64d) CallFunction, elapsed time = %d us\n", requestId, (int)duration); OutputDebugStringA(buffer); } // TODO: handle exceptions in a better way catch (exception &e) { m_errorCallback(e.what()); SetState(State::Error); } } void SandboxJSExecutor::SetState(State state) noexcept { m_state = state; } bool SandboxJSExecutor::IsListening() const noexcept { return m_state == State::Listening; } bool SandboxJSExecutor::IsConnected() const noexcept { return m_state == State::Connected; } bool SandboxJSExecutor::IsDisposed() const noexcept { return m_state == State::Disposed; } bool SandboxJSExecutor::IsInError() const noexcept { return m_state == State::Error; } inline int64_t SandboxJSExecutor::GetNextRequestId() { return ++m_requestId; } bool SandboxJSExecutor::IsRunning() const noexcept { return m_state == State::Running; } task<bool> SandboxJSExecutor::ConnectAsync( std::shared_ptr<SandboxEndpoint> endpoint, const std::function<void(std::string)> &errorCallback) { m_errorCallback = std::move(errorCallback); auto t = task_from_result(); return t.then([=]() -> bool { int retryCount = ConnectRetryCount; while (true) { try { cancellation_token_source timer_cts; auto timeoutT = create_delayed_task( std::chrono::milliseconds(ConnectTimeoutMilliseconds), [=]() -> string { throw std::runtime_error("timeout"); }, timer_cts.get_token()); if (!IsConnected()) { try { m_sandboxEndpoint = nullptr; } catch (std::exception & /*e*/) { // Don't care what happens with the old client at this point } // TODO: Pass as param m_sandboxEndpoint = endpoint; m_sandboxEndpoint->RegisterReplyHandler( [this](int64_t replyId) { OnReplyMessage(replyId); }); m_sandboxEndpoint->RegisterNativeModuleCallHandler( [this](folly::dynamic &&calls) { OnNativeModuleCallMessage(std::move(calls)); }); if (m_sandboxEndpoint->Start(EndpointType::Host)) { SetState(State::Connected); timer_cts.cancel(); } } else { PrepareJavaScriptRuntimeAsync().then([=](bool success) { if (success) { SetState(State::Running); timer_cts.cancel(); } else { SetState(State::Error); } }); } auto status = timeoutT.wait(); if (status != canceled) { throw new std::exception("Timeout"); } if (IsRunning()) { return true; } } catch (std::exception & /*e*/) { retryCount--; if (retryCount == 0) { m_errorCallback( IsConnected() ? "Timeout: preparing JS runtime" : "Timeout: Failed to connect to dev server"); SetState(State::Error); return false; } } } }); } task<bool> SandboxJSExecutor::PrepareJavaScriptRuntimeAsync() { task_completion_event<void> callback; auto requestId = GetNextRequestId(); m_callbacks.emplace(requestId, callback); folly::dynamic argument; return SendMessageAsync(requestId, "prepareJSRuntime", argument); } task<bool> SandboxJSExecutor::SendMessageAsync( int64_t requestId, const std::string &methodName, folly::dynamic &arguments) { if (!IsDisposed()) { task_completion_event<bool> tce; m_sandboxEndpoint->SendRequest( requestId, methodName, arguments, [tce](bool sent) { tce.set(sent); }); return create_task(tce); } else { CompleteRequest(requestId); return task_from_result(false); } } void SandboxJSExecutor::CompleteRequest(int64_t requestId) { auto it = m_callbacks.find(requestId); if (it != m_callbacks.end()) { it->second.set(); m_callbacks.erase(it); } } void SandboxJSExecutor::OnReplyMessage(int64_t replyId) { // Find callback by replyId and set signal. CompleteRequest(replyId); } void SandboxJSExecutor::OnNativeModuleCallMessage(folly::dynamic &&calls) { m_delegate->callNativeModules(*this, std::move(calls), false); } #endif // OSS_RN } // namespace react } // namespace facebook #pragma warning(pop)
// { dg-do compile { target c++11 } } // 2011-06-14 Paolo Carlini <paolo.carlini@oracle.com> // // Copyright (C) 2011-2017 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // // This library 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 library; see the file COPYING3. If not see // <http://www.gnu.org/licenses/>. #include <memory> typedef std::shared_ptr<int> sptype; static_assert(std::is_nothrow_move_constructible<sptype>::value, "Error");
/** * @file location_api_node.cpp * @author Fujii Naomichi * @copyright (c) 2022 Fujii Naomichi * SPDX-License-Identifier: MIT */ #include "location_api_node.hpp" #include <rclcpp/clock.hpp> #include <rcutils/logging.h> class CInitializeATL : public CAtlExeModuleT<CInitializeATL> {}; static CInitializeATL g_initialize_atl; LocationApiNode::LocationApiNode(const rclcpp::NodeOptions &options) : Node("location_api") { // Acquire parameters int interval_in_ms = (int)declare_parameter<int>("interval_in_ms", 0); std::string frame_id = declare_parameter<std::string>("frame_id", ""); std::string topic_name = declare_parameter<std::string>("topic_name", "gnss"); RCUTILS_LOG_INFO("interval_in_ms = %d", interval_in_ms); RCUTILS_LOG_INFO("frame_id = %s", frame_id.c_str()); RCUTILS_LOG_INFO("topic_name = %s", topic_name.c_str()); // Initialize Location API RCUTILS_LOG_INFO("Initializing Location API."); if (FAILED(CoInitializeEx(nullptr, COINIT_MULTITHREADED | COINIT_DISABLE_OLE1DDE))) { RCUTILS_LOG_ERROR("Failed to initialize COM."); return; } if (FAILED(_location.CoCreateInstance(CLSID_Location))) { RCUTILS_LOG_ERROR("Failed to create ILocation instance."); return; } IID REPORT_TYPES[] = {IID_ILatLongReport}; if (FAILED(_location->RequestPermissions(nullptr, REPORT_TYPES, ARRAYSIZE(REPORT_TYPES), TRUE))) { _location.Release(); RCUTILS_LOG_ERROR("Failed to acquire permission."); return; } if (FAILED(_location->SetReportInterval(IID_ILatLongReport, interval_in_ms))) { RCUTILS_LOG_WARN("Failed to set interval to %d ms.", interval_in_ms); } if (FAILED(CComObject<CLocationEvents>::CreateInstance(&_Location_events))) { RCUTILS_LOG_ERROR("Failed to create event object."); _location.Release(); return; } _Location_events->AddRef(); _Location_events->setFrameId(frame_id); // Get interval DWORD actual_interval; if (SUCCEEDED(_location->GetReportInterval(IID_ILatLongReport, &actual_interval))){ RCUTILS_LOG_INFO("Actual interval is %u ms", actual_interval); } // Create publisher static constexpr int QOS_DEPTH = 10; _Location_events->setPublishers(create_publisher<sensor_msgs::msg::NavSatFix>(topic_name, QOS_DEPTH)); // Register event class if (FAILED(_location->RegisterForReport(_Location_events, IID_ILatLongReport, interval_in_ms))) { RCUTILS_LOG_ERROR("Failed to regitser event object."); _location.Release(); return; } RCUTILS_LOG_INFO("Location API was successfully initialized."); } LocationApiNode::~LocationApiNode() { if (_Location_events) { _location->UnregisterForReport(IID_ILatLongReport); _Location_events->Release(); _Location_events = nullptr; } } STDMETHODIMP LocationApiNode::CLocationEvents::OnLocationChanged(REFIID report_type, ILocationReport *location_report) { if (report_type == IID_ILatLongReport) { CComPtr<ILatLongReport> report; if ((SUCCEEDED(location_report->QueryInterface(IID_PPV_ARGS(&report)))) && (NULL != report.p)) { _msg.header.stamp = rclcpp::Clock().now(); do { // Get location if (FAILED(report->GetLatitude(&_msg.latitude))) { break; } if (FAILED(report->GetLongitude(&_msg.longitude))) { break; } if (FAILED(report->GetAltitude(&_msg.altitude))) { _msg.altitude = std::numeric_limits<double>::quiet_NaN(); } // Get errors double error_radius, altitude_error; if (FAILED(report->GetErrorRadius(&error_radius))) { break; } _msg.position_covariance[0] = error_radius * error_radius; _msg.position_covariance[4] = error_radius * error_radius; if (SUCCEEDED(report->GetAltitudeError(&altitude_error))) { _msg.position_covariance[8] = altitude_error * altitude_error; } else { _msg.position_covariance[8] = 0.0; } _msg.position_covariance_type = sensor_msgs::msg::NavSatFix::COVARIANCE_TYPE_DIAGONAL_KNOWN; // Publish message _publisher->publish(_msg); } while (false); } } return S_OK; } STDMETHODIMP LocationApiNode::CLocationEvents::OnStatusChanged(REFIID report_type, LOCATION_REPORT_STATUS status) { if (report_type == IID_ILatLongReport) { switch (status) { case REPORT_NOT_SUPPORTED: RCUTILS_LOG_WARN("No devices detected."); break; case REPORT_ERROR: RCUTILS_LOG_ERROR("Report error."); break; case REPORT_ACCESS_DENIED: RCUTILS_LOG_ERROR("Access denied to reports."); break; case REPORT_INITIALIZING: RCUTILS_LOG_INFO("Report is initializing."); break; case REPORT_RUNNING: RCUTILS_LOG_INFO("Running."); break; } } return S_OK; } int main(int argc, char *argv[]) { rclcpp::init(argc, argv); auto node = std::make_shared<LocationApiNode>(); if (node->isOpen()) { rclcpp::spin(node); } rclcpp::shutdown(); return 0; }
// Install PrintRun onto Ubunbu // pip install --user wxpython // https://zoomadmin.com/HowToInstall/UbuntuPackage/printrun #include "../gcode.h" #include "../../module/motion.h" #include "../../module/planner.h" #include "../../MarlinCore.h" #define JOINT5_ENDSTOP_PIN 53 //Home Joint5 as axis E0 in Marlin void GcodeSuite::G83(){ while (false){ //next version //Wait queue to be empty } destination.x = current_position.x; destination.y = current_position.y; destination.z = current_position.z; // SERIAL_ERROR_MSG("G83 homing...\n"); pinMode(JOINT5_ENDSTOP_PIN, INPUT_PULLUP); delay(200); bool triggered = false; bool last_triggered_1 = false; bool last_triggered_2 = false; while (!triggered || !last_triggered_1 || !last_triggered_2){ prepare_line_to_destination(); current_position.e = 0; destination.e = -0.1 ; sync_plan_position_e(); last_triggered_2 = last_triggered_1; // planner.synchronize(); last_triggered_1 = triggered; triggered = digitalRead(JOINT5_ENDSTOP_PIN); } SERIAL_ECHO_MSG("G83 home-Joint5 is triggered ...\n"); prepare_line_to_destination(); current_position.e = E1_MIN_POS; // For joint5 PFT-1901 destination.e = E1_MIN_POS; sync_plan_position_e(); } void GcodeSuite::G84(){ }
// MIT License // // Copyright (c) 2020 Mechatronics and Haptic Interfaces Lab - Rice University // // 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. // // Author(s): Evan Pezent (epezent@rice.edu) #pragma once #include <Mahi/Util/Logging/Detail/StreamMeta.hpp> #include <Mahi/Util/StlStreams.hpp> #include <Mahi/Util/Console.hpp> #include <Mahi/Util/System.hpp> #include <Mahi/Util/Timing/Timestamp.hpp> #include <sys/stat.h> namespace mahi { namespace util { /// Represents a logging severity level enum Severity { None = 0, ///< always written Fatal = 1, ///< error that forces application abort Error = 2, ///< error that is fatal to operation, but not application Warning = 3, ///< error that may cause issues, but has been accounted for Info = 4, ///< useful information needed during normal operation Verbose = 5, ///< useful information not needed during normal operation Debug = 6, ///< useful information needed for diagnostics }; inline const char* severity_to_string(Severity severity) { switch (severity) { case Fatal: return "FATAL"; case Error: return "ERROR"; case Warning: return "WARN"; case Info: return "INFO"; case Verbose: return "VERB"; case Debug: return "DEBUG"; default: return "NONE"; } } inline Severity string_to_severity(const char* str) { for (Severity severity = Fatal; severity <= Debug; severity = static_cast<Severity>(severity + 1)) { if (severity_to_string(severity)[0] == str[0]) { return severity; } } return None; } /// Encapsulates a Log record class LogRecord { public: /// Constructor LogRecord(Severity severity, const char* func, size_t line, const char* file, Timestamp timestamp = Timestamp()); /// Destructor virtual ~LogRecord(); // Stream operator overloads LogRecord &operator<<(char data); LogRecord &operator<<(std::ostream &(*data)(std::ostream &)); template <typename T> LogRecord& operator<<(const T& data) { using namespace detail; message_ << data; return *this; } /// Gets the message contained by a Record virtual const char* get_message() const; /// Returns timestamp at which Record was constructed virtual const Timestamp& get_timestamp() const; /// Gets the severity of a record virtual Severity get_severity() const; /// Gets ID of thread a Record was made on virtual unsigned int get_tid_() const; /// Gets the line number where the Record was made virtual size_t get_line() const; /// Gets the name of the function in which the Record was made virtual const char* get_func() const; /// Gets the name of the file in which the Record was made virtual const char* get_file() const; private: Timestamp timestamp_; ///< timestamp const Severity severity_; ///< Record severity const unsigned int tid_; ///< thread ID const size_t line_; ///< line number std::ostringstream message_; ///< string stream for message const char* const func_; ///< function name string const char* const file_; ///< file name string mutable std::string func_str_; ///< function name string mutable std::string message_str_; ///< message string }; inline std::string process_function_name(const char* func); } // namespace util } // namespace mahi
#include <sstream> #include <spdlog/spdlog.h> #include "publisher.h" #include "socket.h" #include "message_helpers.h" #include "smart_capnp_builder.h" #include "smart_capnp_reader.h" #include "smart_message_reader.h" namespace a17 { namespace dispatch { Socket::Socket(boost::asio::io_service &ios, int type, const std::string &class_name) : azmqsocket_(ios, type, true), receive_handler_(bind3(&Socket::onReceive)), log_name_(class_name) { logger_ = spdlog::get("Socket"); if (!logger_) { try { logger_ = spdlog::stdout_color_mt("Socket"); } catch (...) { logger_ = spdlog::get("Socket"); if (!logger_) { throw std::runtime_error("Socket logger get() failed twice."); } } } received_message_.reserve(32); sendHighWaterMark(10); if(logger_) logger_->set_pattern("[%Y-%m-%d %T.%e] [%n](%l) %v"); } // Start the process of receiving a multipart message. void Socket::receive(SmartMessageHandler handler, ErrorHandler error_handler) { smart_message_handler_ = std::move(handler); error_handler_ = std::move(error_handler); // TODO(pickledgator): handle timeout logic here azmqsocket_.async_receive(receive_handler_); } // Accumulates a complete multipart message over possibly several events. When the message is // complete, calls the handler with the message. void Socket::onReceive(boost::system::error_code &ec, azmq::message &msg, size_t bytes) { if (ec) { if (logger_) logger_->error("{0} receive error: {1}", log_name_, strerror(ec.value())); if (error_handler_) error_handler_(ec); return; } bool more = msg.more(); if (msg.size() > 0) { received_message_.push_back(std::move(msg)); } if (more) { azmqsocket_.async_receive(receive_handler_); } else { if (logger_) { std::ostringstream message_ostream; message_ostream << received_message_; logger_->trace("{} received {}", log_name_, message_ostream.str()); } smart_message_handler_(received_message_); // TODO(pickledgator): this may be dangerous if the handler doesn't make a copy! received_message_.clear(); } } size_t Socket::send(const azmq::message_vector &message_vector, boost::system::error_code &ec) { if (logger_) { std::ostringstream message_ostream; message_ostream << message_vector; logger_->trace("{} sending {}", log_name_, message_ostream.str()); } size_t size = 0; if (message_vector.empty()) { size = azmqsocket_.send(azmq::message(), ZMQ_DONTWAIT, ec); } else { for (unsigned long i = 0; i < message_vector.size() - 1 && !ec; i++) { size += azmqsocket_.send(message_vector[i], ZMQ_SNDMORE | ZMQ_DONTWAIT, ec); } if (!ec) size += azmqsocket_.send(message_vector[message_vector.size() - 1], ZMQ_DONTWAIT, ec); } if (ec) { if (logger_) logger_->error("{0} send error: {1}", log_name_, strerror(ec.value())); } return size; } boost::system::error_code Socket::send(const azmq::message_vector &message_vector) { boost::system::error_code ec; send(message_vector, ec); return ec; } } // namespace dispatch } // namespace a17
// Copyright 2010-2014 Google // 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 <algorithm> #include <cmath> #include "base/hash.h" #include <stack> #include <string> #include <utility> #include "base/commandlineflags.h" #include "base/integral_types.h" #include "base/logging.h" #include "base/stringprintf.h" #include "base/join.h" #include "base/map_util.h" #include "constraint_solver/constraint_solver.h" #include "constraint_solver/constraint_solveri.h" DEFINE_bool( cp_full_trace, false, "Display all trace information, even if the modifiers has no effect"); namespace operations_research { namespace { // ---------- Code Instrumentation ---------- class TraceIntVar : public IntVar { public: TraceIntVar(Solver* const solver, IntVar* const inner) : IntVar(solver), inner_(inner) { if (inner->HasName()) { set_name(inner->name()); } CHECK_NE(inner->VarType(), TRACE_VAR); } ~TraceIntVar() override {} int64 Min() const override { return inner_->Min(); } void SetMin(int64 m) override { if (m > inner_->Min()) { solver()->GetPropagationMonitor()->SetMin(inner_, m); inner_->SetMin(m); } } int64 Max() const override { return inner_->Max(); } void SetMax(int64 m) override { if (m < inner_->Max()) { solver()->GetPropagationMonitor()->SetMax(inner_, m); inner_->SetMax(m); } } void Range(int64* l, int64* u) override { inner_->Range(l, u); } void SetRange(int64 l, int64 u) override { if (l > inner_->Min() || u < inner_->Max()) { if (l == u) { solver()->GetPropagationMonitor()->SetValue(inner_, l); inner_->SetValue(l); } else { solver()->GetPropagationMonitor()->SetRange(inner_, l, u); inner_->SetRange(l, u); } } } bool Bound() const override { return inner_->Bound(); } bool IsVar() const override { return true; } IntVar* Var() override { return this; } int64 Value() const override { return inner_->Value(); } void RemoveValue(int64 v) override { if (inner_->Contains(v)) { solver()->GetPropagationMonitor()->RemoveValue(inner_, v); inner_->RemoveValue(v); } } void SetValue(int64 v) override { solver()->GetPropagationMonitor()->SetValue(inner_, v); inner_->SetValue(v); } void RemoveInterval(int64 l, int64 u) override { solver()->GetPropagationMonitor()->RemoveInterval(inner_, l, u); inner_->RemoveInterval(l, u); } void RemoveValues(const std::vector<int64>& values) override { solver()->GetPropagationMonitor()->RemoveValues(inner_, values); inner_->RemoveValues(values); } void SetValues(const std::vector<int64>& values) override { solver()->GetPropagationMonitor()->SetValues(inner_, values); inner_->SetValues(values); } void WhenRange(Demon* d) override { inner_->WhenRange(d); } void WhenBound(Demon* d) override { inner_->WhenBound(d); } void WhenDomain(Demon* d) override { inner_->WhenDomain(d); } uint64 Size() const override { return inner_->Size(); } bool Contains(int64 v) const override { return inner_->Contains(v); } IntVarIterator* MakeHoleIterator(bool reversible) const override { return inner_->MakeHoleIterator(reversible); } IntVarIterator* MakeDomainIterator(bool reversible) const override { return inner_->MakeDomainIterator(reversible); } int64 OldMin() const override { return inner_->OldMin(); } int64 OldMax() const override { return inner_->OldMax(); } int VarType() const override { return TRACE_VAR; } void Accept(ModelVisitor* const visitor) const override { IntExpr* const cast_expr = solver()->CastExpression(const_cast<TraceIntVar*>(this)); if (cast_expr != nullptr) { visitor->VisitIntegerVariable(this, cast_expr); } else { visitor->VisitIntegerVariable(this, ModelVisitor::kTraceOperation, 0, inner_); } } std::string DebugString() const override { return inner_->DebugString(); } IntVar* IsEqual(int64 constant) override { return inner_->IsEqual(constant); } IntVar* IsDifferent(int64 constant) override { return inner_->IsDifferent(constant); } IntVar* IsGreaterOrEqual(int64 constant) override { return inner_->IsGreaterOrEqual(constant); } IntVar* IsLessOrEqual(int64 constant) override { return inner_->IsLessOrEqual(constant); } private: IntVar* const inner_; }; class TraceIntExpr : public IntExpr { public: TraceIntExpr(Solver* const solver, IntExpr* const inner) : IntExpr(solver), inner_(inner) { CHECK(!inner->IsVar()); if (inner->HasName()) { set_name(inner->name()); } } ~TraceIntExpr() override {} int64 Min() const override { return inner_->Min(); } void SetMin(int64 m) override { solver()->GetPropagationMonitor()->SetMin(inner_, m); inner_->SetMin(m); } int64 Max() const override { return inner_->Max(); } void SetMax(int64 m) override { solver()->GetPropagationMonitor()->SetMax(inner_, m); inner_->SetMax(m); } void Range(int64* l, int64* u) override { inner_->Range(l, u); } void SetRange(int64 l, int64 u) override { if (l > inner_->Min() || u < inner_->Max()) { solver()->GetPropagationMonitor()->SetRange(inner_, l, u); inner_->SetRange(l, u); } } bool Bound() const override { return inner_->Bound(); } bool IsVar() const override { DCHECK(!inner_->IsVar()); return false; } IntVar* Var() override { return solver()->RegisterIntVar(inner_->Var()); } void WhenRange(Demon* d) override { inner_->WhenRange(d); } void Accept(ModelVisitor* const visitor) const override { visitor->BeginVisitIntegerExpression(ModelVisitor::kTrace, this); visitor->VisitIntegerExpressionArgument(ModelVisitor::kExpressionArgument, inner_); visitor->EndVisitIntegerExpression(ModelVisitor::kTrace, this); } std::string DebugString() const override { return inner_->DebugString(); } private: IntExpr* const inner_; }; class TraceIntervalVar : public IntervalVar { public: TraceIntervalVar(Solver* const solver, IntervalVar* const inner) : IntervalVar(solver, ""), inner_(inner) { if (inner->HasName()) { set_name(inner->name()); } } ~TraceIntervalVar() override {} int64 StartMin() const override { return inner_->StartMin(); } int64 StartMax() const override { return inner_->StartMax(); } void SetStartMin(int64 m) override { if (inner_->MayBePerformed() && (m > inner_->StartMin())) { solver()->GetPropagationMonitor()->SetStartMin(inner_, m); inner_->SetStartMin(m); } } void SetStartMax(int64 m) override { if (inner_->MayBePerformed() && (m < inner_->StartMax())) { solver()->GetPropagationMonitor()->SetStartMax(inner_, m); inner_->SetStartMax(m); } } void SetStartRange(int64 mi, int64 ma) override { if (inner_->MayBePerformed() && (mi > inner_->StartMin() || ma < inner_->StartMax())) { solver()->GetPropagationMonitor()->SetStartRange(inner_, mi, ma); inner_->SetStartRange(mi, ma); } } int64 OldStartMin() const override { return inner_->OldStartMin(); } int64 OldStartMax() const override { return inner_->OldStartMax(); } void WhenStartRange(Demon* const d) override { inner_->WhenStartRange(d); } void WhenStartBound(Demon* const d) override { inner_->WhenStartBound(d); } int64 EndMin() const override { return inner_->EndMin(); } int64 EndMax() const override { return inner_->EndMax(); } void SetEndMin(int64 m) override { if (inner_->MayBePerformed() && (m > inner_->EndMin())) { solver()->GetPropagationMonitor()->SetEndMin(inner_, m); inner_->SetEndMin(m); } } void SetEndMax(int64 m) override { if (inner_->MayBePerformed() && (m < inner_->EndMax())) { solver()->GetPropagationMonitor()->SetEndMax(inner_, m); inner_->SetEndMax(m); } } void SetEndRange(int64 mi, int64 ma) override { if (inner_->MayBePerformed() && (mi > inner_->EndMin() || ma < inner_->EndMax())) { solver()->GetPropagationMonitor()->SetEndRange(inner_, mi, ma); inner_->SetEndRange(mi, ma); } } int64 OldEndMin() const override { return inner_->OldEndMin(); } int64 OldEndMax() const override { return inner_->OldEndMax(); } void WhenEndRange(Demon* const d) override { inner_->WhenEndRange(d); } void WhenEndBound(Demon* const d) override { inner_->WhenStartBound(d); } int64 DurationMin() const override { return inner_->DurationMin(); } int64 DurationMax() const override { return inner_->DurationMax(); } void SetDurationMin(int64 m) override { if (inner_->MayBePerformed() && (m > inner_->DurationMin())) { solver()->GetPropagationMonitor()->SetDurationMin(inner_, m); inner_->SetDurationMin(m); } } void SetDurationMax(int64 m) override { if (inner_->MayBePerformed() && (m < inner_->DurationMax())) { solver()->GetPropagationMonitor()->SetDurationMax(inner_, m); inner_->SetDurationMax(m); } } void SetDurationRange(int64 mi, int64 ma) override { if (inner_->MayBePerformed() && (mi > inner_->DurationMin() || ma < inner_->DurationMax())) { solver()->GetPropagationMonitor()->SetDurationRange(inner_, mi, ma); inner_->SetDurationRange(mi, ma); } } int64 OldDurationMin() const override { return inner_->OldDurationMin(); } int64 OldDurationMax() const override { return inner_->OldDurationMax(); } void WhenDurationRange(Demon* const d) override { inner_->WhenDurationRange(d); } void WhenDurationBound(Demon* const d) override { inner_->WhenDurationBound(d); } bool MustBePerformed() const override { return inner_->MustBePerformed(); } bool MayBePerformed() const override { return inner_->MayBePerformed(); } void SetPerformed(bool value) override { if ((value && !inner_->MustBePerformed()) || (!value && inner_->MayBePerformed())) { solver()->GetPropagationMonitor()->SetPerformed(inner_, value); inner_->SetPerformed(value); } } bool WasPerformedBound() const override { return inner_->WasPerformedBound(); } void WhenPerformedBound(Demon* const d) override { inner_->WhenPerformedBound(d); } IntExpr* StartExpr() override { return inner_->StartExpr(); } IntExpr* DurationExpr() override { return inner_->DurationExpr(); } IntExpr* EndExpr() override { return inner_->EndExpr(); } IntExpr* PerformedExpr() override { return inner_->PerformedExpr(); } IntExpr* SafeStartExpr(int64 unperformed_value) override { return inner_->SafeStartExpr(unperformed_value); } IntExpr* SafeDurationExpr(int64 unperformed_value) override { return inner_->SafeDurationExpr(unperformed_value); } IntExpr* SafeEndExpr(int64 unperformed_value) override { return inner_->SafeEndExpr(unperformed_value); } void Accept(ModelVisitor* const visitor) const override { inner_->Accept(visitor); } std::string DebugString() const override { return inner_->DebugString(); } private: IntervalVar* const inner_; }; // ---------- PrintTrace ---------- class PrintTrace : public PropagationMonitor { public: struct Info { explicit Info(const std::string& m) : message(m), displayed(false) {} std::string message; bool displayed; }; struct Context { Context() : initial_indent(0), indent(0), in_demon(false), in_constraint(false), in_decision_builder(false), in_decision(false), in_objective(false) {} explicit Context(int start_indent) : initial_indent(start_indent), indent(start_indent), in_demon(false), in_constraint(false), in_decision_builder(false), in_decision(false), in_objective(false) {} bool TopLevel() const { return initial_indent == indent; } void Clear() { indent = initial_indent; in_demon = false; in_constraint = false; in_decision_builder = false; in_decision = false; in_objective = false; delayed_info.clear(); } int initial_indent; int indent; bool in_demon; bool in_constraint; bool in_decision_builder; bool in_decision; bool in_objective; std::vector<Info> delayed_info; }; explicit PrintTrace(Solver* const s) : PropagationMonitor(s) { contexes_.push(Context()); } ~PrintTrace() override {} // ----- Search events ----- void BeginInitialPropagation() override { CheckNoDelayed(); DisplaySearch("Root Node Propagation"); IncreaseIndent(); } void EndInitialPropagation() override { DecreaseIndent(); DisplaySearch("Starting Tree Search"); } void BeginNextDecision(DecisionBuilder* const b) override { DisplaySearch( StringPrintf("DecisionBuilder(%s)", b->DebugString().c_str())); IncreaseIndent(); contexes_.top().in_decision_builder = true; } // After calling DecisionBuilder::Next, along with the returned decision. void EndNextDecision(DecisionBuilder* const b, Decision* const d) override { contexes_.top().in_decision_builder = false; DecreaseIndent(); } void BeginFail() override { contexes_.top().Clear(); while (!contexes_.top().TopLevel()) { DecreaseIndent(); LOG(INFO) << Indent() << "}"; } DisplaySearch(StringPrintf("Failure at depth %d", solver()->SearchDepth())); } bool AtSolution() override { DisplaySearch( StringPrintf("Solution found at depth %d", solver()->SearchDepth())); return false; } void ApplyDecision(Decision* const decision) override { DisplaySearch( StringPrintf("ApplyDecision(%s)", decision->DebugString().c_str())); IncreaseIndent(); contexes_.top().in_decision = true; } void RefuteDecision(Decision* const decision) override { if (contexes_.top().in_objective) { DecreaseIndent(); contexes_.top().in_objective = false; } DisplaySearch( StringPrintf("RefuteDecision(%s)", decision->DebugString().c_str())); IncreaseIndent(); contexes_.top().in_decision = true; } void AfterDecision(Decision* const decision, bool direction) override { DecreaseIndent(); contexes_.top().in_decision = false; } void EnterSearch() override { if (solver()->SolveDepth() == 0) { CHECK_EQ(1, contexes_.size()); contexes_.top().Clear(); } else { PrintDelayedString(); PushNestedContext(); } DisplaySearch("Enter Search"); } void ExitSearch() override { DisplaySearch("Exit Search"); CHECK(contexes_.top().TopLevel()); if (solver()->SolveDepth() > 1) { contexes_.pop(); } } void RestartSearch() override { CHECK(contexes_.top().TopLevel()); } // ----- Propagation events ----- void BeginConstraintInitialPropagation( Constraint* const constraint) override { PushDelayedInfo( StringPrintf("Constraint(%s)", constraint->DebugString().c_str())); contexes_.top().in_constraint = true; } void EndConstraintInitialPropagation(Constraint* const constraint) override { PopDelayedInfo(); contexes_.top().in_constraint = false; } void BeginNestedConstraintInitialPropagation( Constraint* const parent, Constraint* const nested) override { PushDelayedInfo( StringPrintf("Constraint(%s)", nested->DebugString().c_str())); contexes_.top().in_constraint = true; } void EndNestedConstraintInitialPropagation(Constraint* const, Constraint* const) override { PopDelayedInfo(); contexes_.top().in_constraint = false; } void RegisterDemon(Demon* const demon) override {} void BeginDemonRun(Demon* const demon) override { if (demon->priority() != Solver::VAR_PRIORITY) { contexes_.top().in_demon = true; PushDelayedInfo(StringPrintf("Demon(%s)", demon->DebugString().c_str())); } } void EndDemonRun(Demon* const demon) override { if (demon->priority() != Solver::VAR_PRIORITY) { contexes_.top().in_demon = false; PopDelayedInfo(); } } void StartProcessingIntegerVariable(IntVar* const var) override { PushDelayedInfo( StringPrintf("StartProcessing(%s)", var->DebugString().c_str())); } void EndProcessingIntegerVariable(IntVar* const var) override { PopDelayedInfo(); } void PushContext(const std::string& context) override { PushDelayedInfo(context); } void PopContext() override { PopDelayedInfo(); } // ----- IntExpr modifiers ----- void SetMin(IntExpr* const expr, int64 new_min) override { DisplayModification( StringPrintf("SetMin(%s, %lld)", expr->DebugString().c_str(), new_min)); } void SetMax(IntExpr* const expr, int64 new_max) override { DisplayModification( StringPrintf("SetMax(%s, %lld)", expr->DebugString().c_str(), new_max)); } void SetRange(IntExpr* const expr, int64 new_min, int64 new_max) override { DisplayModification(StringPrintf("SetRange(%s, [%lld .. %lld])", expr->DebugString().c_str(), new_min, new_max)); } // ----- IntVar modifiers ----- void SetMin(IntVar* const var, int64 new_min) override { DisplayModification( StringPrintf("SetMin(%s, %lld)", var->DebugString().c_str(), new_min)); } void SetMax(IntVar* const var, int64 new_max) override { DisplayModification( StringPrintf("SetMax(%s, %lld)", var->DebugString().c_str(), new_max)); } void SetRange(IntVar* const var, int64 new_min, int64 new_max) override { DisplayModification(StringPrintf("SetRange(%s, [%lld .. %lld])", var->DebugString().c_str(), new_min, new_max)); } void RemoveValue(IntVar* const var, int64 value) override { DisplayModification(StringPrintf("RemoveValue(%s, %lld)", var->DebugString().c_str(), value)); } void SetValue(IntVar* const var, int64 value) override { DisplayModification( StringPrintf("SetValue(%s, %lld)", var->DebugString().c_str(), value)); } void RemoveInterval(IntVar* const var, int64 imin, int64 imax) override { DisplayModification(StringPrintf("RemoveInterval(%s, [%lld .. %lld])", var->DebugString().c_str(), imin, imax)); } void SetValues(IntVar* const var, const std::vector<int64>& values) override { DisplayModification(StringPrintf("SetValues(%s, %s)", var->DebugString().c_str(), strings::Join(values, ", ").c_str())); } void RemoveValues(IntVar* const var, const std::vector<int64>& values) override { DisplayModification(StringPrintf("RemoveValues(%s, %s)", var->DebugString().c_str(), strings::Join(values, ", ").c_str())); } // ----- IntervalVar modifiers ----- void SetStartMin(IntervalVar* const var, int64 new_min) override { DisplayModification(StringPrintf("SetStartMin(%s, %lld)", var->DebugString().c_str(), new_min)); } void SetStartMax(IntervalVar* const var, int64 new_max) override { DisplayModification(StringPrintf("SetStartMax(%s, %lld)", var->DebugString().c_str(), new_max)); } void SetStartRange(IntervalVar* const var, int64 new_min, int64 new_max) override { DisplayModification(StringPrintf("SetStartRange(%s, [%lld .. %lld])", var->DebugString().c_str(), new_min, new_max)); } void SetEndMin(IntervalVar* const var, int64 new_min) override { DisplayModification(StringPrintf("SetEndMin(%s, %lld)", var->DebugString().c_str(), new_min)); } void SetEndMax(IntervalVar* const var, int64 new_max) override { DisplayModification(StringPrintf("SetEndMax(%s, %lld)", var->DebugString().c_str(), new_max)); } void SetEndRange(IntervalVar* const var, int64 new_min, int64 new_max) override { DisplayModification(StringPrintf("SetEndRange(%s, [%lld .. %lld])", var->DebugString().c_str(), new_min, new_max)); } void SetDurationMin(IntervalVar* const var, int64 new_min) override { DisplayModification(StringPrintf("SetDurationMin(%s, %lld)", var->DebugString().c_str(), new_min)); } void SetDurationMax(IntervalVar* const var, int64 new_max) override { DisplayModification(StringPrintf("SetDurationMax(%s, %lld)", var->DebugString().c_str(), new_max)); } void SetDurationRange(IntervalVar* const var, int64 new_min, int64 new_max) override { DisplayModification(StringPrintf("SetDurationRange(%s, [%lld .. %lld])", var->DebugString().c_str(), new_min, new_max)); } void SetPerformed(IntervalVar* const var, bool value) override { DisplayModification(StringPrintf("SetPerformed(%s, %d)", var->DebugString().c_str(), value)); } void RankFirst(SequenceVar* const var, int index) override { DisplayModification( StringPrintf("RankFirst(%s, %d)", var->DebugString().c_str(), index)); } void RankNotFirst(SequenceVar* const var, int index) override { DisplayModification(StringPrintf("RankNotFirst(%s, %d)", var->DebugString().c_str(), index)); } void RankLast(SequenceVar* const var, int index) override { DisplayModification( StringPrintf("RankLast(%s, %d)", var->DebugString().c_str(), index)); } void RankNotLast(SequenceVar* const var, int index) override { DisplayModification( StringPrintf("RankNotLast(%s, %d)", var->DebugString().c_str(), index)); } void RankSequence(SequenceVar* const var, const std::vector<int>& rank_first, const std::vector<int>& rank_last, const std::vector<int>& unperformed) override { DisplayModification(StringPrintf( "RankSequence(%s, forward [%s], backward[%s], unperformed[%s])", var->DebugString().c_str(), strings::Join(rank_first, ", ").c_str(), strings::Join(rank_last, ", ").c_str(), strings::Join(unperformed, ", ").c_str())); } void Install() override { SearchMonitor::Install(); if (solver()->SolveDepth() <= 1) { solver()->AddPropagationMonitor(this); } } std::string DebugString() const override { return "PrintTrace"; } private: void PushDelayedInfo(const std::string& delayed) { if (FLAGS_cp_full_trace) { LOG(INFO) << Indent() << delayed << " {"; IncreaseIndent(); } else { contexes_.top().delayed_info.push_back(Info(delayed)); } } void PopDelayedInfo() { if (FLAGS_cp_full_trace) { DecreaseIndent(); LOG(INFO) << Indent() << "}"; } else { CHECK(!contexes_.top().delayed_info.empty()); if (contexes_.top().delayed_info.back().displayed && !contexes_.top().TopLevel()) { DecreaseIndent(); LOG(INFO) << Indent() << "}"; } else { contexes_.top().delayed_info.pop_back(); } } } void CheckNoDelayed() { CHECK(contexes_.top().delayed_info.empty()); } void PrintDelayedString() { const std::vector<Info>& infos = contexes_.top().delayed_info; for (int i = 0; i < infos.size(); ++i) { const Info& info = infos[i]; if (!info.displayed) { LOG(INFO) << Indent() << info.message << " {"; IncreaseIndent(); // Marks it as displayed. contexes_.top().delayed_info[i].displayed = true; } } } void DisplayModification(const std::string& to_print) { if (FLAGS_cp_full_trace) { LOG(INFO) << Indent() << to_print; } else { PrintDelayedString(); if (contexes_.top().in_demon || contexes_.top().in_constraint || contexes_.top().in_decision_builder || contexes_.top().in_decision || contexes_.top().in_objective) { // Inside a demon, constraint, decision builder -> normal print. LOG(INFO) << Indent() << to_print; } else { // Top level, modification pushed by the objective. This is a // hack. The SetMax or SetMin done by the objective happens in // the RefuteDecision callback of search monitors. We cannot // easily differentiate that from the actual modifications done // by the Refute() call itself. To distinguish that, we force // the print trace to be last in the list of monitors. Thus // modifications that happens at the top level before the // RefuteDecision() callbacks must be from the objective. // In that case, we push the in_objective context. CHECK(contexes_.top().TopLevel()); DisplaySearch(StringPrintf("Objective -> %s", to_print.c_str())); IncreaseIndent(); contexes_.top().in_objective = true; } } } void DisplaySearch(const std::string& to_print) { const int solve_depth = solver()->SolveDepth(); if (solve_depth <= 1) { LOG(INFO) << Indent() << "######## Top Level Search: " << to_print; } else { LOG(INFO) << Indent() << "######## Nested Search(" << solve_depth - 1 << "): " << to_print; } } std::string Indent() { CHECK_GE(contexes_.top().indent, 0); std::string output = " @ "; for (int i = 0; i < contexes_.top().indent; ++i) { output.append(" "); } return output; } void IncreaseIndent() { contexes_.top().indent++; } void DecreaseIndent() { if (contexes_.top().indent > 0) { contexes_.top().indent--; } } void PushNestedContext() { const int initial_indent = contexes_.top().indent; contexes_.push(Context(initial_indent)); } std::stack<Context> contexes_; }; } // namespace IntExpr* Solver::RegisterIntExpr(IntExpr* const expr) { if (InstrumentsVariables()) { if (expr->IsVar()) { return RegisterIntVar(expr->Var()); } else { return RevAlloc(new TraceIntExpr(this, expr)); } } else { return expr; } } IntVar* Solver::RegisterIntVar(IntVar* const var) { if (InstrumentsVariables() && var->VarType() != TRACE_VAR) { // Not already a // trace var. return RevAlloc(new TraceIntVar(this, var)); } else { return var; } } IntervalVar* Solver::RegisterIntervalVar(IntervalVar* const var) { if (InstrumentsVariables()) { return RevAlloc(new TraceIntervalVar(this, var)); } else { return var; } } PropagationMonitor* BuildPrintTrace(Solver* const s) { return s->RevAlloc(new PrintTrace(s)); } } // namespace operations_research
/*******************************************************************\ Module: Read Goto Programs Author: \*******************************************************************/ /// \file /// Read Goto Programs #include "read_goto_binary.h" #include <fstream> #include <unordered_set> #include <util/message.h> #include <util/unicode.h> #include <util/tempfile.h> #include <util/rename_symbol.h> #include <util/config.h> #include "goto_model.h" #include "link_goto_model.h" #include "read_bin_goto_object.h" #include "elf_reader.h" #include "osx_fat_reader.h" static bool read_goto_binary( const std::string &filename, symbol_tablet &, goto_functionst &, message_handlert &); /// \brief Read a goto binary from a file, but do not update \ref config /// \param filename: the file name of the goto binary /// \param message_handler: for diagnostics /// \return goto model on success, {} on failure optionalt<goto_modelt> read_goto_binary(const std::string &filename, message_handlert &message_handler) { goto_modelt dest; if(read_goto_binary( filename, dest.symbol_table, dest.goto_functions, message_handler)) { return {}; } else return std::move(dest); } /// \brief Read a goto binary from a file, but do not update \ref config /// \param filename: the file name of the goto binary /// \param symbol_table: the symbol table from the goto binary /// \param goto_functions: the goto functions from the goto binary /// \param message_handler: for diagnostics /// \return true on failure, false on success static bool read_goto_binary( const std::string &filename, symbol_tablet &symbol_table, goto_functionst &goto_functions, message_handlert &message_handler) { #ifdef _MSC_VER std::ifstream in(widen(filename), std::ios::binary); #else std::ifstream in(filename, std::ios::binary); #endif if(!in) { messaget message(message_handler); message.error() << "Failed to open `" << filename << "'" << messaget::eom; return true; } char hdr[4]; hdr[0]=in.get(); hdr[1]=in.get(); hdr[2]=in.get(); hdr[3]=in.get(); in.seekg(0); if(hdr[0]==0x7f && hdr[1]=='G' && hdr[2]=='B' && hdr[3]=='F') { return read_bin_goto_object( in, filename, symbol_table, goto_functions, message_handler); } else if(hdr[0]==0x7f && hdr[1]=='E' && hdr[2]=='L' && hdr[3]=='F') { // ELF binary. // This _may_ have a goto-cc section. try { elf_readert elf_reader(in); for(unsigned i=0; i<elf_reader.number_of_sections; i++) if(elf_reader.section_name(i)=="goto-cc") { in.seekg(elf_reader.section_offset(i)); return read_bin_goto_object( in, filename, symbol_table, goto_functions, message_handler); } // section not found messaget(message_handler).error() << "failed to find goto-cc section in ELF binary" << messaget::eom; } catch(const char *s) { messaget(message_handler).error() << s << messaget::eom; } } else if(is_osx_fat_magic(hdr)) { messaget message(message_handler); // Mach-O universal binary // This _may_ have a goto binary as hppa7100LC architecture osx_fat_readert osx_fat_reader(in, message_handler); if(osx_fat_reader.has_gb()) { temporary_filet tempname("tmp.goto-binary", ".gb"); if(osx_fat_reader.extract_gb(filename, tempname())) { message.error() << "failed to extract goto binary" << messaget::eom; return true; } std::ifstream temp_in(tempname(), std::ios::binary); if(!temp_in) message.error() << "failed to read temp binary" << messaget::eom; const bool read_err = read_bin_goto_object( temp_in, filename, symbol_table, goto_functions, message_handler); temp_in.close(); return read_err; } // architecture not found message.error() << "failed to find goto binary in Mach-O file" << messaget::eom; } else if(is_osx_mach_object(hdr)) { messaget message(message_handler); // Mach-O object file, may contain a goto-cc section try { osx_mach_o_readert mach_o_reader(in, message_handler); osx_mach_o_readert::sectionst::const_iterator entry = mach_o_reader.sections.find("goto-cc"); if(entry != mach_o_reader.sections.end()) { in.seekg(entry->second.offset); return read_bin_goto_object( in, filename, symbol_table, goto_functions, message_handler); } // section not found messaget(message_handler).error() << "failed to find goto-cc section in Mach-O binary" << messaget::eom; } catch(const deserialization_exceptiont &e) { messaget(message_handler).error() << e.what() << messaget::eom; } } else { messaget(message_handler).error() << "not a goto binary" << messaget::eom; } return true; } bool is_goto_binary( const std::string &filename, message_handlert &message_handler) { #ifdef _MSC_VER std::ifstream in(widen(filename), std::ios::binary); #else std::ifstream in(filename, std::ios::binary); #endif if(!in) return false; // We accept two forms: // 1. goto binaries, marked with 0x7f GBF // 2. ELF binaries, marked with 0x7f ELF char hdr[4]; hdr[0]=in.get(); hdr[1]=in.get(); hdr[2]=in.get(); hdr[3]=in.get(); if(hdr[0]==0x7f && hdr[1]=='G' && hdr[2]=='B' && hdr[3]=='F') { return true; // yes, this is a goto binary } else if(hdr[0]==0x7f && hdr[1]=='E' && hdr[2]=='L' && hdr[3]=='F') { // this _may_ have a goto-cc section try { in.seekg(0); elf_readert elf_reader(in); if(elf_reader.has_section("goto-cc")) return true; } catch(...) { // ignore any errors } } else if(is_osx_fat_magic(hdr)) { // this _may_ have a goto binary as hppa7100LC architecture try { in.seekg(0); osx_fat_readert osx_fat_reader(in, message_handler); if(osx_fat_reader.has_gb()) return true; } catch(...) { // ignore any errors } } else if(is_osx_mach_object(hdr)) { // this _may_ have a goto-cc section try { in.seekg(0); osx_mach_o_readert mach_o_reader(in, message_handler); if(mach_o_reader.has_section("goto-cc")) return true; } catch(...) { // ignore any errors } } return false; } /// \brief reads an object file, and also updates config /// \param file_name: file name of the goto binary /// \param dest: the goto model returned /// \param message_handler: for diagnostics /// \return true on error, false otherwise bool read_object_and_link( const std::string &file_name, goto_modelt &dest, message_handlert &message_handler) { messaget(message_handler).statistics() << "Reading: " << file_name << messaget::eom; // we read into a temporary model auto temp_model = read_goto_binary(file_name, message_handler); if(!temp_model.has_value()) return true; try { link_goto_model(dest, *temp_model, message_handler); } catch(...) { return true; } // reading successful, let's update config config.set_from_symbol_table(dest.symbol_table); return false; } /// \brief reads an object file, and also updates the config /// \param file_name: file name of the goto binary /// \param dest_symbol_table: symbol table to update /// \param dest_functions: collection of goto functions to update /// \param message_handler: for diagnostics /// \return true on error, false otherwise bool read_object_and_link( const std::string &file_name, symbol_tablet &dest_symbol_table, goto_functionst &dest_functions, message_handlert &message_handler) { goto_modelt goto_model; goto_model.symbol_table.swap(dest_symbol_table); goto_model.goto_functions.swap(dest_functions); bool result=read_object_and_link( file_name, goto_model, message_handler); goto_model.symbol_table.swap(dest_symbol_table); goto_model.goto_functions.swap(dest_functions); return result; }
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin developers // Copyright (c) 2014-2015 The Dash developers // Copyright (c) 2015-2019 The OHONETWORK developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "pow.h" #include "chain.h" #include "chainparams.h" #include "main.h" #include "primitives/block.h" #include "uint256.h" #include "util.h" #include <math.h> unsigned int GetNextWorkRequired(const CBlockIndex* pindexLast, const CBlockHeader* pblock) { if (Params().NetworkID() == CBaseChainParams::REGTEST) return pindexLast->nBits; /* current difficulty formula, ohonetwork - DarkGravity v3, written by Evan Duffield - evan@dashpay.io */ const CBlockIndex* BlockLastSolved = pindexLast; const CBlockIndex* BlockReading = pindexLast; int64_t nActualTimespan = 0; int64_t LastBlockTime = 0; int64_t PastBlocksMin = 24; int64_t PastBlocksMax = 24; int64_t CountBlocks = 0; uint256 PastDifficultyAverage; uint256 PastDifficultyAveragePrev; if (BlockLastSolved == NULL || BlockLastSolved->nHeight == 0 || BlockLastSolved->nHeight < PastBlocksMin) { return Params().ProofOfWorkLimit().GetCompact(); } if (pindexLast->nHeight >= Params().LAST_POW_BLOCK()) { const bool fTimeV2 = Params().IsTimeProtocolV2(pindexLast->nHeight+1); const uint256 bnTargetLimit = Params().ProofOfStakeLimit(fTimeV2); const int64_t nTargetSpacing = Params().TargetSpacing(); const int64_t nTargetTimespan = Params().TargetTimespan(fTimeV2); int64_t nActualSpacing = 0; if (pindexLast->nHeight != 0) nActualSpacing = pindexLast->GetBlockTime() - pindexLast->pprev->GetBlockTime(); if (nActualSpacing < 0) nActualSpacing = 1; if (fTimeV2 && nActualSpacing > nTargetSpacing*10) nActualSpacing = nTargetSpacing*10; // ppcoin: target change every block // ppcoin: retarget with exponential moving toward target spacing uint256 bnNew; bnNew.SetCompact(pindexLast->nBits); // on first block with V2 time protocol, reduce the difficulty by a factor 16 if (fTimeV2 && !Params().IsTimeProtocolV2(pindexLast->nHeight)) bnNew <<= 4; int64_t nInterval = nTargetTimespan / nTargetSpacing; bnNew *= ((nInterval - 1) * nTargetSpacing + nActualSpacing + nActualSpacing); bnNew /= ((nInterval + 1) * nTargetSpacing); if (bnNew <= 0 || bnNew > bnTargetLimit) bnNew = bnTargetLimit; return bnNew.GetCompact(); } for (unsigned int i = 1; BlockReading && BlockReading->nHeight > 0; i++) { if (PastBlocksMax > 0 && i > PastBlocksMax) { break; } CountBlocks++; if (CountBlocks <= PastBlocksMin) { if (CountBlocks == 1) { PastDifficultyAverage.SetCompact(BlockReading->nBits); } else { PastDifficultyAverage = ((PastDifficultyAveragePrev * CountBlocks) + (uint256().SetCompact(BlockReading->nBits))) / (CountBlocks + 1); } PastDifficultyAveragePrev = PastDifficultyAverage; } if (LastBlockTime > 0) { int64_t Diff = (LastBlockTime - BlockReading->GetBlockTime()); nActualTimespan += Diff; } LastBlockTime = BlockReading->GetBlockTime(); if (BlockReading->pprev == NULL) { assert(BlockReading); break; } BlockReading = BlockReading->pprev; } uint256 bnNew(PastDifficultyAverage); int64_t _nTargetTimespan = CountBlocks * Params().TargetSpacing(); if (nActualTimespan < _nTargetTimespan / 3) nActualTimespan = _nTargetTimespan / 3; if (nActualTimespan > _nTargetTimespan * 3) nActualTimespan = _nTargetTimespan * 3; // Retarget bnNew *= nActualTimespan; bnNew /= _nTargetTimespan; if (bnNew > Params().ProofOfWorkLimit()) { bnNew = Params().ProofOfWorkLimit(); } return bnNew.GetCompact(); } bool CheckProofOfWork(uint256 hash, unsigned int nBits) { bool fNegative; bool fOverflow; uint256 bnTarget; if (Params().SkipProofOfWorkCheck()) return true; bnTarget.SetCompact(nBits, &fNegative, &fOverflow); // Check range if (fNegative || bnTarget == 0 || fOverflow || bnTarget > Params().ProofOfWorkLimit()) return error("CheckProofOfWork() : nBits below minimum work"); // Check proof of work matches claimed amount if (hash > bnTarget) { if (Params().MineBlocksOnDemand()) return false; else return error("CheckProofOfWork() : hash doesn't match nBits"); } return true; } uint256 GetBlockProof(const CBlockIndex& block) { uint256 bnTarget; bool fNegative; bool fOverflow; bnTarget.SetCompact(block.nBits, &fNegative, &fOverflow); if (fNegative || fOverflow || bnTarget == 0) return 0; // We need to compute 2**256 / (bnTarget+1), but we can't represent 2**256 // as it's too large for a uint256. However, as 2**256 is at least as large // as bnTarget+1, it is equal to ((2**256 - bnTarget - 1) / (bnTarget+1)) + 1, // or ~bnTarget / (nTarget+1) + 1. return (~bnTarget / (bnTarget + 1)) + 1; }
#include<stdio.h> double dp[1005][1005]; int main(){ #ifdef LOCAL_DEBUG freopen("E:/ACM/SRC/1.txt","r",stdin); #endif int w,b;scanf("%d%d",&w,&b); for(int i=1;i<=w;i++)dp[i][0]=1; for(int j=0;j<=b;j++)dp[0][j]=0; for(int i=1;i<=w;i++)for(int j=1;j<=b;j++){ dp[i][j]=(double)i/(i+j);int mul=j*j-j; long long div=(i+j)*(i+j-1LL)*(i+j-2); if(j>=2)dp[i][j]+=dp[i-1][j-2]*mul*(i-0)/div; if(j>=3)dp[i][j]+=dp[i-0][j-3]*mul*(j-2)/div; }printf("%.9lf\n",dp[w][b]); return 0; }
# include "my_viewer.h" # include <sigogl/ui_button.h> # include <sigogl/ui_radio_button.h> # include <sig/sn_primitive.h> # include <sig/sn_transform.h> # include <sig/sn_manipulator.h> # include <sigogl/ws_run.h> # include <vector> # include <math.h> # include <iostream> #define PI 3.141592654f using namespace std; MyViewer::MyViewer ( int x, int y, int w, int h, const char* l ) : WsViewer(x,y,w,h,l) { _nbut=0; _animating=false; add_ui (); //run_evaluation_test(); build_scene (); } void MyViewer::add_ui () { UiPanel *p, *sp; UiManager* uim = WsWindow::uim(); p = uim->add_panel ( "", UiPanel::HorizLeft ); p->add ( new UiButton ( "View", sp=new UiPanel() ) ); { UiPanel* p=sp; p->add ( _nbut=new UiCheckButton ( "Normals", EvNormals ) ); } p->add ( new UiButton ( "Animate", EvAnimate ) ); p->add ( new UiButton ( "Exit", EvExit ) ); p->top()->separate(); } void MyViewer::add_model ( SnShape* s, GsVec p ) { SnManipulator* manip = new SnManipulator; GsMat m; m.translation ( p ); manip->initial_mat ( m ); SnGroup* g = new SnGroup; SnLines* l = new SnLines; l->color(GsColor::orange); g->add(s); g->add(l); manip->child(g); rootg()->add(manip); } void MyViewer::make_custom_gear(GsModel* m, float r1, float d, int nfaces) { m->init(); float r2 = r1 * 0.5f; float r3 = r1 + 0.2f; m->V.size(nfaces * 8); // cos/sin uses radians. Use PI/180 for conversion vector<float> angles; for (int i = 0; i < nfaces; i++) { angles.push_back(i * 2 * PI / nfaces); } // Vertices for (int i = 0; i < nfaces; i++) { m->V[i] = GsPnt(r2*cos(angles[i]), r2*sin(angles[i]), 0.0f); m->V[i + nfaces] = GsPnt(r1*cos(angles[i]), r1*sin(angles[i]), 0.0f); m->V[i + 2*nfaces] = GsPnt(r2*cos(angles[i]), r2*sin(angles[i]), d); m->V[i + 3*nfaces] = GsPnt(r1*cos(angles[i]), r1*sin(angles[i]), d); } angles.push_back(2*PI); for (int i = 0, j = 0; i < 2 * nfaces; i += 2, j++) { m->V[i + 4 * nfaces] = GsPnt(r1*cos(angles[j]), r1*sin(angles[j]), 0.0f); m->V[i + 1 + 4 * nfaces] = GsPnt(r3*cos((angles[j] + angles[j + 1]) / 2), r3*sin((angles[j] + angles[j + 1]) / 2), 0.0f); m->V[i + 6 * nfaces] = GsPnt(r1*cos(angles[j]), r1*sin(angles[j]), d); m->V[i + 1 + 6 * nfaces] = GsPnt(r3*cos((angles[j] + angles[j + 1]) / 2), r3*sin((angles[j] + angles[j + 1]) / 2), d); } // Faces //m->F.size(nfaces * 8); for (int i = 0; i < nfaces - 1; i++) { // Top and Bottom m->F.push().set(i, nfaces + i + 1, nfaces + i); m->F.push().set(i, i + 1, nfaces + i + 1); m->F.push().set(i + 2*nfaces, 3*nfaces + i, 3*nfaces + i + 1); m->F.push().set(i + 2*nfaces, 3*nfaces + i + 1, 2*nfaces + i + 1); // Inside m->F.push().set(i, 2 * nfaces + i, i + 1); m->F.push().set(2 * nfaces + i, 2 * nfaces + i + 1, i + 1); m->F.push().set(i + nfaces, i + 1 + nfaces, 3 * nfaces + i); m->F.push().set(3 * nfaces + i, i + 1 + nfaces, 3 * nfaces + i + 1); } // Last 2 triangles m->F.push().set(nfaces - 1, nfaces, 2*nfaces-1); m->F.push().set(nfaces - 1, 0, nfaces); m->F.push().set(3*nfaces - 1, 4*nfaces - 1, 3*nfaces); m->F.push().set(3*nfaces - 1, 3*nfaces, 2*nfaces); // TODO m->F.push().set(nfaces - 1, 3 * nfaces - 1, 0); m->F.push().set(3 * nfaces - 1, 2 * nfaces, 0); m->F.push().set(2 * nfaces - 1, nfaces, 4 * nfaces - 1); m->F.push().set(4 * nfaces - 1, nfaces, 3 * nfaces); // Edges for (int i = 0; i < nfaces*2-2; i+=2) { m->F.push().set(i + 4*nfaces, i + 4 * nfaces + 2, i + 4 * nfaces + 1); m->F.push().set(i + 6 * nfaces, i + 6 * nfaces + 1, i + 6 * nfaces + 2); m->F.push().set(i + 4 * nfaces, i + 4 * nfaces + 1, i + 6 * nfaces); m->F.push().set(i + 4 * nfaces + 1, i + 6 * nfaces + 1, i + 6 * nfaces); m->F.push().set(i + 4 * nfaces + 1, i + 4 * nfaces + 2, i + 6 * nfaces + 1); m->F.push().set(i + 4 * nfaces + 2, i + 6 * nfaces + 2, i + 6 * nfaces + 1); if (i == nfaces * 2 - 4) { m->F.push().set(i+2 + 4 * nfaces, 0 + 4*nfaces, i + 2 + 4 * nfaces + 1); m->F.push().set(i + 2 + 6 * nfaces, i + 2 + 6 * nfaces + 1, 0 + 6 * nfaces); m->F.push().set(i+2 + 4 * nfaces, i+2 + 4 * nfaces + 1, i + 2 + 6 * nfaces); m->F.push().set(i+2 + 4 * nfaces + 1, i+2 + 6 * nfaces + 1, i+2 + 6 * nfaces); m->F.push().set(i+2 + 4 * nfaces + 1, 0 + 4 * nfaces, i+2 + 6 * nfaces + 1); m->F.push().set(0 + 4 * nfaces, 0 + 6 * nfaces, i+2 + 6 * nfaces + 1); } } // Cross Edges m->compress(); } void MyViewer::make_normal_gear_base(GsModel* m, float r, float d, int nfaces) { GsPnt a(0.0f, 0.0f, d/2); GsPnt b(0.0f, 0.0f, -d/2); m->make_cylinder(a, b, r, r, nfaces, false); } void MyViewer::make_normal_gear_edges(SnGroup* g, float r, float d, GsColor color, int nfaces) { GsPnt a(0.0f, 0.0f, d/2 - 0.0001f); GsPnt b(0.0f, 0.0f, -d/2 + 0.0001f); vector<float> angles; for (int i = 0; i < nfaces; i++) { angles.push_back(i * 2.0f * PI / nfaces); } vector<GsPnt> edgePts; for (int i = 0; i < nfaces; i++) { edgePts.push_back(GsPnt(r*cos(angles[i]), r*sin(angles[i]), 0)); } SnModel* m; SnGroup* tempG; SnTransform* tempT; for (int i = 0; i < nfaces; i++) { m = new SnModel(); m->model()->make_cylinder(a, b, r/10, r/10, nfaces, false); m->color(color); tempG = new SnGroup(); tempG->separator(true); tempT = new SnTransform(); tempG->add(tempT); tempG->add(m); tempT->get().translation(edgePts[i]); g->add(tempG); } } void MyViewer::make_line_gear(SnGroup *g, float length, float d, GsColor color, int nfaces) { SnModel *m; SnTransform *t1; SnTransform *t2; SnTransform *t3; SnGroup *g1; SnGroup *g2; SnGroup *g3; SnGroup *tempG; SnTransform *tempT; GsBox tempBox; tempBox.a = GsPnt(0.0f, 0.0f, 0.0f); tempBox.b = GsPnt(length, length, d); GsPnt a(0.0f, 0.0f, d / 2); GsPnt b(0.0f, 0.0f, -d / 2); for (int i = 0; i < nfaces; i++) { tempG = new SnGroup(); tempG->separator(true); tempT = new SnTransform(); tempG->add(tempT); //Box 1 m = new SnModel(); m->color(color); g1 = new SnGroup(); g1->separator(true); t1 = new SnTransform(); m->model()->make_box(tempBox); g1->add(t1); g1->add(m); t1->get().translation(0.0f, 0.0f, 0.0f); tempG->add(g1); //Box 2 m = new SnModel(); m->color(color); g2 = new SnGroup(); g2->separator(true); t2 = new SnTransform(); m->model()->make_box(tempBox); g2->add(t2); g2->add(m); t2->get().translation(length, 0.0f, 0.0f); tempG->add(g2); //Cylinder 3 m = new SnModel(); m->color(color); g3 = new SnGroup(); g3->separator(true); t3 = new SnTransform(); m->model()->make_cylinder(a, b, length / 2, length / 2, 20, true); g3->add(t3); g3->add(m); t3->get().translation((1.5f)*length, length, d / 2); tempG->add(g3); tempT->get().translation(i * 2 * length, 0.0f, 0.0f); g->add(tempG); } } void MyViewer::run_evaluation_test() { animationEval = true; double startTime; double finishTime; double completionTime; _model = new SnModel(); SnGroup* g1 = new SnGroup(); g1->separator(true); _model->color(GsColor::cyan); _t1 = new SnTransform(); g1->add(_t1); startTime = gs_time(); // Test 1 // make_custom_gear(_model->model(), 0.2f, 0.4f, 100000); // g1->add(_model); // Test 2 // make_custom_gear(_model->model(), 0.2f, 0.4f, 300000); // g1->add(_model); // Test 3 // make_custom_gear(_model->model(), 0.2f, 0.4f, 500000); // g1->add(_model); // Test 4 //make_normal_gear_base(_model->model(), 0.2f, 0.4f, 10); //g1->add(_model); //make_normal_gear_edges(g1, 0.2f, 0.4f, GsColor::red, 10); // Test 5 //make_normal_gear_base(_model->model(), 0.2f, 0.4f, 50); //make_normal_gear_edges(g1, 0.2f, 0.4f, GsColor::red, 50); //g1->add(_model); // Test 6 //make_normal_gear_base(_model->model(), 0.2f, 0.4f, 300); //make_normal_gear_edges(g1, 0.2f, 0.4f, GsColor::red, 300); //g1->add(_model); // Test 7 //make_line_gear(g1, 0.2f, 0.2f, GsColor::red, 1000); // Test 8 //make_line_gear(g1, 0.2f, 0.2f, GsColor::red, 5000); // Test 9 //make_line_gear(g1, 0.2f, 0.2f, GsColor::red, 7500); finishTime = gs_time(); completionTime = finishTime - startTime; cout << completionTime; _t1->get().translation(0.0f, 0.0f, 0.85f); rootg()->add(g1); } void MyViewer::build_scene () { double startTime; double finishTime; double completionTime; startTime = gs_time(); // Create Sharp Gear 1 _model = new SnModel(); SnGroup* g1 = new SnGroup(); g1->separator(true); _model->color(GsColor::cyan); make_custom_gear(_model->model(), 0.2f, 0.4f, 20); _t1 = new SnTransform(); g1->add(_t1); g1->add(_model); _t1->get().translation(0.0f, 0.0f, 0.85f); // Create Normal Gear 2 _model = new SnModel(); SnGroup* g2 = new SnGroup(); g2->separator(true); _model->color(GsColor::blue); make_normal_gear_base(_model->model(), 0.5, 0.4f, 20); _t2 = new SnTransform(); g2->add(_t2); g2->add(_model); make_normal_gear_edges(g2, 0.5, 0.4f, GsColor::blue, 20); _t2->get().translation(0.0f, 0.0f, 0.0f); // Create Normal Gear 3 _model = new SnModel(); SnGroup* g3 = new SnGroup(); g3->separator(true); _model->color(GsColor::red); make_normal_gear_base(_model->model(), 0.5, 0.4f, 20); _t3 = new SnTransform(); g3->add(_t3); g3->add(_model); make_normal_gear_edges(g3, 0.5, 0.4f, GsColor::red, 20); _t3->get().translation(0.90f, 0.53f, 0.0f); // Create Normal Gear 4 _model = new SnModel(); SnGroup* g4 = new SnGroup(); g4->separator(true); _model->color(GsColor::green); make_normal_gear_base(_model->model(), 0.5, 0.4f, 20); _t4 = new SnTransform(); g4->add(_t4); g4->add(_model); make_normal_gear_edges(g4, 0.5, 0.4f, GsColor::green, 20); _t4->get().translation(-0.90f, -0.53f, 0.0f); // Create Pipe 5 _model = new SnModel(); SnGroup* g5 = new SnGroup(); g5->separator(true); _model->color(GsColor::darkgreen); GsPnt a(0.0f, 0.0f, 0.0f); GsPnt b(0.0f, 0.0f, 1.50f); _model->model()->make_cylinder(a, b, 0.1f, 0.1f, 20, false); _t5 = new SnTransform(); g5->add(_t5); g5->add(_model); _t5->get().translation(0.0f, 0.0f, -0.25f); // Create Pipe 6 _model = new SnModel(); SnGroup* g6 = new SnGroup(); g6->separator(true); _model->color(GsColor::darkblue); a = GsPnt (0.0f, 0.0f, 0.0f); b = GsPnt (0.0f, 0.0f, -1.25f); _model->model()->make_cylinder(a, b, 0.1f, 0.1f, 20, false); _t6 = new SnTransform(); g6->add(_t6); g6->add(_model); _t6->get().translation(0.90f, 0.53f, 0.25f); // Create Pipe 7 _model = new SnModel(); SnGroup* g7 = new SnGroup(); g7->separator(true); _model->color(GsColor::darkblue); a = GsPnt(0.0f, 0.0f, 0.0f); b = GsPnt(0.0f, 0.0f, -1.25f); _model->model()->make_cylinder(a, b, 0.1f, 0.1f, 20, false); _t7 = new SnTransform(); g7->add(_t7); g7->add(_model); _t7->get().translation(-0.90f, -0.53f, 0.25f); // Create Power Box 8 _model = new SnModel(); SnGroup* g8 = new SnGroup(); g8->separator(true); _model->color(GsColor::darkgray); GsBox tempBox; tempBox.a = GsPnt(-0.15f, -0.15f, -0.15f); tempBox.b = GsPnt(0.15f, 0.15f, 0.15f); _model->model()->make_box(tempBox); _t8 = new SnTransform(); g8->add(_t8); g8->add(_model); _t8->get().translation(0.90f, 0.53f, -1.16f); // Create Power Box 9 _model = new SnModel(); SnGroup* g9 = new SnGroup(); g9->separator(true); _model->color(GsColor::darkgray); tempBox.a = GsPnt(-0.15f, -0.15f, -0.15f); tempBox.b = GsPnt(0.15f, 0.15f, 0.15f); _model->model()->make_box(tempBox); _t9 = new SnTransform(); g9->add(_t9); g9->add(_model); _t9->get().translation(-0.90f, -0.53f, -1.16f); // Create Pipe 10 _model = new SnModel(); SnGroup* g10 = new SnGroup(); g10->separator(true); _model->color(GsColor::darkred); a = GsPnt(0.0f, 0.15f, 0.0f); b = GsPnt(0.0f, 0.65f, 0.0f); _model->model()->make_cylinder(a, b, 0.1f, 0.1f, 20, false); _t10 = new SnTransform(); g10->add(_t10); g10->add(_model); _t10->get().translation(-0.90f, -0.53f, -1.16f); // Create Pipe 11 _model = new SnModel(); SnGroup* g11 = new SnGroup(); g11->separator(true); _model->color(GsColor::darkred); a = GsPnt(0.0f, 0.15f, 0.0f); b = GsPnt(0.0f, 0.65f, 0.0f); _model->model()->make_cylinder(a, b, 0.1f, 0.1f, 20, false); _t11 = new SnTransform(); g11->add(_t11); g11->add(_model); _t11->get().translation(0.90f, 0.53f, -1.16f); // Create Sharp Gear 12 _model = new SnModel(); _model->color(GsColor::magenta); make_custom_gear(_model->model(), 0.2f, 0.2f, 10); SnGroup* g12a = new SnGroup(); g12a->separator(true); _t12a = new SnTransform(); g12a->add(_t12a); g12a->add(_model); _t12a->get().rotx(PI/2.0); SnGroup* g12b = new SnGroup(); g12b->separator(true); _t12b = new SnTransform(); g12b->add(_t12b); g12b->add(g12a); _t12b->get().translation(0.0f, 0.65f, 0.0f); SnGroup* g12c = new SnGroup(); g12c->separator(true); _t12c = new SnTransform(); g12c->add(_t12c); g12c->add(g12b); _t12c->get().translation(0.90f, 0.53f, -1.16f); // Create Sharp Gear 12 _model = new SnModel(); _model->color(GsColor::orange); make_custom_gear(_model->model(), 0.2f, 0.2f, 15); SnGroup* g13a = new SnGroup(); g13a->separator(true); _t13a = new SnTransform(); g13a->add(_t13a); g13a->add(_model); _t13a->get().rotx(PI / 2.0); SnGroup* g13b = new SnGroup(); g13b->separator(true); _t13b = new SnTransform(); g13b->add(_t13b); g13b->add(g13a); _t13b->get().translation(0.0f, 0.65f, 0.0f); SnGroup* g13c = new SnGroup(); g13c->separator(true); _t13c = new SnTransform(); g13c->add(_t13c); g13c->add(g13b); _t13c->get().translation(-0.90f, -0.53f, -1.16f); // Create Line Gear 14 SnGroup* g14a = new SnGroup(); g14a->separator(true); _t14a = new SnTransform(); g14a->add(_t14a); make_line_gear(g14a, 0.1f, 0.2f, GsColor::brown, 10); _t14a->get().rotz(PI/2); SnGroup* g14b = new SnGroup(); g14b->separator(true); _t14b = new SnTransform(); g14b->add(_t14b); g14b->add(g14a); _t14b->get().translation(1.54f, -1.125f, 0.0f); // Create Line Gear 15 SnGroup* g15a = new SnGroup(); g15a->separator(true); _t15a = new SnTransform(); g15a->add(_t15a); make_line_gear(g15a, 0.1f, 0.2f, GsColor::brown, 10); _t15a->get().rotz(-PI / 2); SnGroup* g15b = new SnGroup(); g15b->separator(true); _t15b = new SnTransform(); g15b->add(_t15b); g15b->add(g15a); _t15b->get().translation(-1.54f, 1.120f, 0.0f); // Roots SnGroup* gFinal = new SnGroup(); gFinal->separator(true); _tFinal = new SnTransform(); gFinal->add(_tFinal); gFinal->add(g2); gFinal->add(g3); gFinal->add(g4); gFinal->add(g5); gFinal->add(g6); gFinal->add(g7); gFinal->add(g8); gFinal->add(g9); gFinal->add(g1); gFinal->add(g10); gFinal->add(g11); gFinal->add(g12c); gFinal->add(g13c); gFinal->add(g14b); gFinal->add(g15b); _tFinal->get().roty(PI/4); rootg()->add(gFinal); finishTime = gs_time(); completionTime = finishTime - startTime; cout << completionTime << endl; } // Below is an example of how to control the main loop of an animation: void MyViewer::run_animation () { if (animationEval) { if (_animating) return; // avoid recursive calls _animating = true; int ind = gs_random(0, rootg()->size() - 1); // pick one child SnManipulator* manip = rootg()->get<SnManipulator>(ind); // access one of the manipulators GsMat m = manip->mat(); _curang1 = 0; double frdt = 1.0 / 30.0; // delta time to reach given number of frames per second double v = 4; // target velocity is 1 unit per second double t = 0, lt = 0, t0 = gs_time(); do // run for a while: { while (t - lt < frdt) t = gs_time() - t0; // wait until it is time for next frame lt = t; GsVec tr; _t1->get().getrans(tr); _t1->get().rotz(GS_TODEG(-_curang1)); _t1->get().setrans(tr); _curang1 += 0.0005f; render(); // notify it needs redraw ws_check(); // redraw now } while (true);// m.e24 > 0 ); _animating = false; } if (!animationEval) { if (_animating) return; // avoid recursive calls _animating = true; int ind = gs_random(0, rootg()->size() - 1); // pick one child SnManipulator* manip = rootg()->get<SnManipulator>(ind); // access one of the manipulators GsMat m = manip->mat(); _curang1 = 0; double frdt = 1.0 / 30.0; // delta time to reach given number of frames per second double v = 4; // target velocity is 1 unit per second double t = 0, lt = 0, t0 = gs_time(); do // run for a while: { while (t - lt < frdt) t = gs_time() - t0; // wait until it is time for next frame lt = t; GsVec tr; _t2->get().getrans(tr); _t2->get().rotz(GS_TODEG(-_curang1)); _t2->get().setrans(tr); _t3->get().getrans(tr); _t3->get().rotz(GS_TODEG(_curang1)); _t3->get().setrans(tr); _t4->get().getrans(tr); _t4->get().rotz(GS_TODEG(_curang1)); _t4->get().setrans(tr); _t8->get().getrans(tr); _t8->get().rotz(GS_TODEG(_curang1)); _t8->get().setrans(tr); _t9->get().getrans(tr); _t9->get().rotz(GS_TODEG(_curang1)); _t9->get().setrans(tr); _t1->get().getrans(tr); _t1->get().rotz(GS_TODEG(-_curang1)); _t1->get().setrans(tr); _t10->get().getrans(tr); _t10->get().rotz(GS_TODEG(_curang1)); _t10->get().setrans(tr); _t11->get().getrans(tr); _t11->get().rotz(GS_TODEG(_curang1)); _t11->get().setrans(tr); _t12b->get().getrans(tr); _t12b->get().roty(GS_TODEG(_curang1)); _t12b->get().setrans(tr); _t12c->get().getrans(tr); _t12c->get().rotz(GS_TODEG(_curang1)); _t12c->get().setrans(tr); _t13b->get().getrans(tr); _t13b->get().roty(GS_TODEG(-_curang1)); _t13b->get().setrans(tr); _t13c->get().getrans(tr); _t13c->get().rotz(GS_TODEG(_curang1)); _t13c->get().setrans(tr); _t14b->get().getrans(tr); tr += GsVec(0.0f, 0.018f, 0.0f); if (tr.y > 0.26) { tr.y = -1.125f; } _t14b->get().setrans(tr); _t15b->get().getrans(tr); tr -= GsVec(0.0f, 0.018f, 0.0f); if (tr.y < -0.26) { tr.y = 1.120f; } _t15b->get().setrans(tr); _curang1 += 0.0005f; render(); // notify it needs redraw ws_check(); // redraw now } while (true);// m.e24 > 0 ); _animating = false; } } void MyViewer::show_normals ( bool b ) { // Note that primitives are only converted to meshes in GsModel // at the first draw call. GsArray<GsVec> fn; SnGroup* r = (SnGroup*)root(); for ( int k=0; k<r->size(); k++ ) { SnManipulator* manip = r->get<SnManipulator>(k); SnShape* s = manip->child<SnGroup>()->get<SnShape>(0); SnLines* l = manip->child<SnGroup>()->get<SnLines>(1); if ( !b ) { l->visible(false); continue; } l->visible ( true ); if ( !l->empty() ) continue; // build only once l->init(); if ( s->instance_name()==SnPrimitive::class_name ) { GsModel& m = *((SnModel*)s)->model(); m.get_normals_per_face ( fn ); const GsVec* n = fn.pt(); float f = 0.33f; for ( int i=0; i<m.F.size(); i++ ) { const GsVec& a=m.V[m.F[i].a]; l->push ( a, a+(*n++)*f ); const GsVec& b=m.V[m.F[i].b]; l->push ( b, b+(*n++)*f ); const GsVec& c=m.V[m.F[i].c]; l->push ( c, c+(*n++)*f ); } } } } int MyViewer::handle_keyboard ( const GsEvent &e ) { int ret = WsViewer::handle_keyboard ( e ); // 1st let system check events if ( ret ) return ret; switch ( e.key ) { case GsEvent::KeyEsc : gs_exit(); return 1; case 'n' : { bool b=!_nbut->value(); _nbut->value(b); show_normals(b); return 1; } default: gsout<<"Key pressed: "<<e.key<<gsnl; } return 0; } int MyViewer::uievent ( int e ) { switch ( e ) { case EvNormals: show_normals(_nbut->value()); return 1; case EvAnimate: run_animation(); return 1; case EvExit: gs_exit(); } return WsViewer::uievent(e); }
#ifndef DECODER_CHASE_STD_HPP_ #define DECODER_CHASE_STD_HPP_ #include <cstdint> #include <vector> #include "Module/Encoder/Encoder.hpp" #include "Module/Decoder/Decoder_SIHO.hpp" namespace aff3ct { namespace module { template <typename B = int, typename R = float> class Decoder_chase_std : public Decoder_SIHO<B,R> { protected: Encoder<B> &encoder; std::vector<B> best_X_N; std::vector<uint32_t> less_reliable_llrs; const uint32_t max_flips; const bool hamming; float min_euclidean_dist; uint32_t min_hamming_dist; uint32_t best_test; public: Decoder_chase_std(const int K, const int N, Encoder<B> &encoder, const uint32_t max_flips = 3, const bool hamming = false, const int n_frames = 1); virtual ~Decoder_chase_std() = default; protected: void _decode_siho (const R *Y_N, B *V_K, const int frame_id); void _decode_siho_cw(const R *Y_N, B *V_N, const int frame_id); void _decode_siho_cw_euclidean(const R *Y_N, B *V_N); void _decode_siho_cw_hamming ( B *V_N); }; } } #endif /* DECODER_CHASE_STD_HPP_ */
// Copyright (c) 2011-2015 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 "bitcoinamountfield.h" #include "bitcoinunits.h" #include "guiconstants.h" #include "qvaluecombobox.h" #include <QApplication> #include <QAbstractSpinBox> #include <QHBoxLayout> #include <QKeyEvent> #include <QLineEdit> /** QSpinBox that uses fixed-point numbers internally and uses our own * formatting/parsing functions. */ class AmountSpinBox: public QAbstractSpinBox { Q_OBJECT public: explicit AmountSpinBox(QWidget *parent): QAbstractSpinBox(parent), currentUnit(BitcoinUnits::PURA), singleStep(100000) // satoshis { setAlignment(Qt::AlignRight); connect(lineEdit(), SIGNAL(textEdited(QString)), this, SIGNAL(valueChanged())); } QValidator::State validate(QString &text, int &pos) const { if(text.isEmpty()) return QValidator::Intermediate; bool valid = false; parse(text, &valid); /* Make sure we return Intermediate so that fixup() is called on defocus */ return valid ? QValidator::Intermediate : QValidator::Invalid; } void fixup(QString &input) const { bool valid = false; CAmount val = parse(input, &valid); if(valid) { input = BitcoinUnits::format(currentUnit, val, false, BitcoinUnits::separatorAlways); lineEdit()->setText(input); } } CAmount value(bool *valid_out=0) const { return parse(text(), valid_out); } void setValue(const CAmount& value) { lineEdit()->setText(BitcoinUnits::format(currentUnit, value, false, BitcoinUnits::separatorAlways)); Q_EMIT valueChanged(); } void stepBy(int steps) { bool valid = false; CAmount val = value(&valid); val = val + steps * singleStep; val = qMin(qMax(val, CAmount(0)), BitcoinUnits::maxMoney()); setValue(val); } void setDisplayUnit(int unit) { bool valid = false; CAmount val = value(&valid); currentUnit = unit; if(valid) setValue(val); else clear(); } void setSingleStep(const CAmount& step) { singleStep = step; } QSize minimumSizeHint() const { if(cachedMinimumSizeHint.isEmpty()) { ensurePolished(); const QFontMetrics fm(fontMetrics()); int h = lineEdit()->minimumSizeHint().height(); int w = fm.width(BitcoinUnits::format(BitcoinUnits::PURA, BitcoinUnits::maxMoney(), false, BitcoinUnits::separatorAlways)); w += 2; // cursor blinking space QStyleOptionSpinBox opt; initStyleOption(&opt); QSize hint(w, h); QSize extra(35, 6); opt.rect.setSize(hint + extra); extra += hint - style()->subControlRect(QStyle::CC_SpinBox, &opt, QStyle::SC_SpinBoxEditField, this).size(); // get closer to final result by repeating the calculation opt.rect.setSize(hint + extra); extra += hint - style()->subControlRect(QStyle::CC_SpinBox, &opt, QStyle::SC_SpinBoxEditField, this).size(); hint += extra; hint.setHeight(h); opt.rect = rect(); cachedMinimumSizeHint = style()->sizeFromContents(QStyle::CT_SpinBox, &opt, hint, this) .expandedTo(QApplication::globalStrut()); } return cachedMinimumSizeHint; } private: int currentUnit; CAmount singleStep; mutable QSize cachedMinimumSizeHint; /** * Parse a string into a number of base monetary units and * return validity. * @note Must return 0 if !valid. */ CAmount parse(const QString &text, bool *valid_out=0) const { CAmount val = 0; bool valid = BitcoinUnits::parse(currentUnit, text, &val); if(valid) { if(val < 0 || val > BitcoinUnits::maxMoney()) valid = false; } if(valid_out) *valid_out = valid; return valid ? val : 0; } protected: bool event(QEvent *event) { if (event->type() == QEvent::KeyPress || event->type() == QEvent::KeyRelease) { QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event); if (keyEvent->key() == Qt::Key_Comma) { // Translate a comma into a period QKeyEvent periodKeyEvent(event->type(), Qt::Key_Period, keyEvent->modifiers(), ".", keyEvent->isAutoRepeat(), keyEvent->count()); return QAbstractSpinBox::event(&periodKeyEvent); } } return QAbstractSpinBox::event(event); } StepEnabled stepEnabled() const { if (isReadOnly()) // Disable steps when AmountSpinBox is read-only return StepNone; if (text().isEmpty()) // Allow step-up with empty field return StepUpEnabled; StepEnabled rv = 0; bool valid = false; CAmount val = value(&valid); if(valid) { if(val > 0) rv |= StepDownEnabled; if(val < BitcoinUnits::maxMoney()) rv |= StepUpEnabled; } return rv; } Q_SIGNALS: void valueChanged(); }; #include "bitcoinamountfield.moc" BitcoinAmountField::BitcoinAmountField(QWidget *parent) : QWidget(parent), amount(0) { amount = new AmountSpinBox(this); amount->setLocale(QLocale::c()); amount->installEventFilter(this); amount->setMaximumWidth(170); QHBoxLayout *layout = new QHBoxLayout(this); layout->addWidget(amount); unit = new QValueComboBox(this); unit->setModel(new BitcoinUnits(this)); layout->addWidget(unit); layout->addStretch(1); layout->setContentsMargins(0,0,0,0); setLayout(layout); setFocusPolicy(Qt::TabFocus); setFocusProxy(amount); // If one if the widgets changes, the combined content changes as well connect(amount, SIGNAL(valueChanged()), this, SIGNAL(valueChanged())); connect(unit, SIGNAL(currentIndexChanged(int)), this, SLOT(unitChanged(int))); // Set default based on configuration unitChanged(unit->currentIndex()); } void BitcoinAmountField::clear() { amount->clear(); unit->setCurrentIndex(0); } void BitcoinAmountField::setEnabled(bool fEnabled) { amount->setEnabled(fEnabled); unit->setEnabled(fEnabled); } bool BitcoinAmountField::validate() { bool valid = false; value(&valid); setValid(valid); return valid; } void BitcoinAmountField::setValid(bool valid) { if (valid) amount->setStyleSheet(""); else amount->setStyleSheet(STYLE_INVALID); } bool BitcoinAmountField::eventFilter(QObject *object, QEvent *event) { if (event->type() == QEvent::FocusIn) { // Clear invalid flag on focus setValid(true); } return QWidget::eventFilter(object, event); } QWidget *BitcoinAmountField::setupTabChain(QWidget *prev) { QWidget::setTabOrder(prev, amount); QWidget::setTabOrder(amount, unit); return unit; } CAmount BitcoinAmountField::value(bool *valid_out) const { return amount->value(valid_out); } void BitcoinAmountField::setValue(const CAmount& value) { amount->setValue(value); } void BitcoinAmountField::setReadOnly(bool fReadOnly) { amount->setReadOnly(fReadOnly); } void BitcoinAmountField::unitChanged(int idx) { // Use description tooltip for current unit for the combobox unit->setToolTip(unit->itemData(idx, Qt::ToolTipRole).toString()); // Determine new unit ID int newUnit = unit->itemData(idx, BitcoinUnits::UnitRole).toInt(); amount->setDisplayUnit(newUnit); } void BitcoinAmountField::setDisplayUnit(int newUnit) { unit->setValue(newUnit); } void BitcoinAmountField::setSingleStep(const CAmount& step) { amount->setSingleStep(step); }
///////////////////////////////////////////////////////////////////////////////////////////////// // // Tencent is pleased to support the open source community by making libpag available. // // Copyright (C) 2021 THL A29 Limited, a Tencent company. 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. // ///////////////////////////////////////////////////////////////////////////////////////////////// #include <emscripten/bind.h> #include <emscripten/val.h> #include "base/utils/TGFXCast.h" #include "core/FontMetrics.h" #include "core/ImageInfo.h" #include "core/PathTypes.h" #include "gpu/opengl/GLDefines.h" #include "pag/pag.h" #include "pag/types.h" #include "platform/web/GPUDrawable.h" #include "platform/web/NativeImage.h" #include "rendering/editing/StillImage.h" using namespace emscripten; using namespace pag; EMSCRIPTEN_BINDINGS(pag) { class_<PAGLayer>("_PAGLayer") .smart_ptr<std::shared_ptr<PAGLayer>>("_PAGLayer") .function("_uniqueID", optional_override([](PAGLayer& pagLayer) { return static_cast<int>(pagLayer.uniqueID()); })) .function("_layerType", optional_override([](PAGLayer& pagLayer) { return static_cast<int>(pagLayer.layerType()); })) .function("_layerName", &PAGLayer::layerName) .function("_matrix", optional_override([](PAGLayer& pagLayer) { return ToTGFX(pagLayer.matrix()); })) .function("_setMatrix", optional_override([](PAGLayer& pagLayer, tgfx::Matrix matrix) { pagLayer.setMatrix(ToPAG(matrix)); })) .function("_resetMatrix", &PAGLayer::resetMatrix) .function("_getTotalMatrix", &PAGLayer::getTotalMatrix) .function("_alpha", &PAGLayer::alpha) .function("_setAlpha", &PAGLayer::setAlpha) .function("_visible", &PAGLayer::visible) .function("_setVisible", &PAGLayer::setVisible) .function("_editableIndex", &PAGLayer::editableIndex) .function("_parent", &PAGLayer::parent) .function("_markers", optional_override([](PAGLayer& pagLayer) { std::vector<Marker> result = {}; for (auto marker_ptr : pagLayer.markers()) { Marker marker; marker.startTime = marker_ptr->startTime; marker.duration = marker_ptr->duration; marker.comment = marker_ptr->comment; result.push_back(marker); } return result; })) .function("_globalToLocalTime", optional_override([](PAGLayer& pagLayer, int globalTime) { return static_cast<int>(pagLayer.globalToLocalTime(globalTime)); })) .function("_localTimeToGlobal", optional_override([](PAGLayer& pagLayer, int localTime) { return static_cast<int>(pagLayer.localTimeToGlobal(localTime)); })) .function("_duration", optional_override([](PAGLayer& pagLayer) { return static_cast<int>(pagLayer.duration()); })) .function("_frameRate", &PAGLayer::frameRate) .function("_startTime", optional_override([](PAGLayer& pagLayer) { return static_cast<int>(pagLayer.startTime()); })) .function("_startTime", optional_override([](PAGLayer& pagLayer) { return static_cast<int>(pagLayer.startTime()); })) .function("_setStartTime", optional_override([](PAGLayer& pagLayer, int time) { return pagLayer.setStartTime(static_cast<int64_t>(time)); })) .function("_currentTime", optional_override([](PAGLayer& pagLayer) { return static_cast<int>(pagLayer.currentTime()); })) .function("_setCurrentTime", optional_override([](PAGLayer& pagLayer, int time) { return pagLayer.setCurrentTime(static_cast<int64_t>(time)); })) .function("_getProgress", &PAGLayer::getProgress) .function("_setProgress", &PAGLayer::setProgress) .function("_preFrame", &PAGLayer::preFrame) .function("_nextFrame", &PAGLayer::nextFrame) .function("_getBounds", optional_override([](PAGLayer& pagLayer) { return ToTGFX(pagLayer.getBounds()); })) .function("_trackMatteLayer", &PAGLayer::trackMatteLayer) .function("_excludedFromTimeline", &PAGLayer::excludedFromTimeline) .function("_setExcludedFromTimeline", &PAGLayer::setExcludedFromTimeline) .function("_isPAGFile", &PAGLayer::isPAGFile); class_<PAGSolidLayer, base<PAGLayer>>("_PAGSolidLayer") .smart_ptr<std::shared_ptr<PAGSolidLayer>>("_PAGSolidLayer") .class_function("_Make", optional_override([](int duration, int width, int height, Color solidColor, int opacity) { return PAGSolidLayer::Make(static_cast<int64_t>(duration), width, height, solidColor, opacity); })) .function("_solidColor", &PAGSolidLayer::solidColor) .function("_setSolidColor", &PAGSolidLayer::setSolidColor); class_<PAGImageLayer, base<PAGLayer>>("_PAGImageLayer") .smart_ptr<std::shared_ptr<PAGImageLayer>>("_PAGImageLayer") .class_function("_Make", optional_override([](int width, int height, int duration) { return PAGImageLayer::Make(width, height, static_cast<int64_t>(duration)); })) .function("_contentDuration", optional_override([](PAGImageLayer& pagImageLayer) { return static_cast<int>(pagImageLayer.contentDuration()); })) .function("_getVideoRanges", &PAGImageLayer::getVideoRanges) .function("_replaceImage", &PAGImageLayer::replaceImage) .function("_layerTimeToContent", optional_override([](PAGImageLayer& pagImageLayer, int layerTime) { return static_cast<int>(pagImageLayer.layerTimeToContent(layerTime)); })) .function("_contentTimeToLayer", optional_override([](PAGImageLayer& pagImageLayer, int contentTime) { return static_cast<int>(pagImageLayer.contentTimeToLayer(contentTime)); })); class_<PAGTextLayer, base<PAGLayer>>("_PAGTextLayer") .smart_ptr<std::shared_ptr<PAGTextLayer>>("_PAGTextLayer") .class_function("_Make", optional_override([](int duration, std::string text, float fontSize, std::string fontFamily, std::string fontStyle) { return PAGTextLayer::Make(static_cast<int64_t>(duration), text, fontSize, fontFamily, fontStyle); })) .class_function( "_Make", optional_override([](int duration, std::shared_ptr<TextDocument> textDocumentHandle) { return PAGTextLayer::Make(static_cast<int64_t>(duration), textDocumentHandle); })) .function("_fillColor", &PAGTextLayer::fillColor) .function("_setFillColor", &PAGTextLayer::setFillColor) .function("_font", &PAGTextLayer::font) .function("_setFont", &PAGTextLayer::setFont) .function("_fontSize", &PAGTextLayer::fontSize) .function("_setFontSize", &PAGTextLayer::setFontSize) .function("_strokeColor", &PAGTextLayer::strokeColor) .function("_setStrokeColor", &PAGTextLayer::setStrokeColor) .function("_text", &PAGTextLayer::text) .function("_setText", &PAGTextLayer::setText) .function("_reset", &PAGTextLayer::reset); class_<PAGComposition, base<PAGLayer>>("_PAGComposition") .smart_ptr<std::shared_ptr<PAGComposition>>("_PAGComposition") .class_function("_Make", PAGComposition::Make) .function("_width", &PAGComposition::width) .function("_height", &PAGComposition::height) .function("_setContentSize", &PAGComposition::setContentSize) .function("_numChildren", &PAGComposition::numChildren) .function("_getLayerAt", &PAGComposition::getLayerAt) .function("_getLayerIndex", &PAGComposition::getLayerIndex) .function("_setLayerIndex", &PAGComposition::setLayerIndex) .function("_addLayer", &PAGComposition::addLayer) .function("_addLayerAt", &PAGComposition::addLayerAt) .function("_contains", &PAGComposition::contains) .function("_removeLayer", &PAGComposition::removeLayer) .function("_removeLayerAt", &PAGComposition::removeLayerAt) .function("_removeAllLayers", &PAGComposition::removeAllLayers) .function("_swapLayer", &PAGComposition::swapLayer) .function("_swapLayerAt", &PAGComposition::swapLayerAt) .function("_audioBytes", optional_override([](PAGComposition& pagComposition) { ByteData* result = pagComposition.audioBytes(); if (result->length() == 0) { uint8_t empty_arr[] = {}; return val(typed_memory_view(0, empty_arr)); } return val(typed_memory_view(result->length(), result->data())); })) .function("_audioMarkers", optional_override([](PAGComposition& pagComposition) { std::vector<Marker> result = {}; for (auto marker_ptr : pagComposition.audioMarkers()) { Marker marker; marker.startTime = marker_ptr->startTime; marker.duration = marker_ptr->duration; marker.comment = marker_ptr->comment; result.push_back(marker); } return result; })) .function("_audioStartTime", optional_override([](PAGComposition& pagComposition) { return static_cast<int>(pagComposition.audioStartTime()); })) .function("_getLayersByName", &PAGComposition::getLayersByName) .function("_getLayersUnderPoint", &PAGComposition::getLayersUnderPoint); class_<PAGFile, base<PAGComposition>>("_PAGFile") .smart_ptr<std::shared_ptr<PAGFile>>("_PAGFile") .class_function("_MaxSupportedTagLevel", PAGFile::MaxSupportedTagLevel) .class_function("_Load", optional_override([](uintptr_t bytes, size_t length) { return PAGFile::Load(reinterpret_cast<void*>(bytes), length); })) .function("_tagLevel", &PAGFile::tagLevel) .function("_numTexts", &PAGFile::numTexts) .function("_numImages", &PAGFile::numImages) .function("_numVideos", &PAGFile::numVideos) .function("_getTextData", &PAGFile::getTextData) .function("_replaceText", &PAGFile::replaceText) .function("_replaceImage", &PAGFile::replaceImage) .function("_getLayersByEditableIndex", optional_override([](PAGFile& pagFile, int editableIndex, int layerType) { return pagFile.getLayersByEditableIndex(editableIndex, static_cast<LayerType>(layerType)); })) .function("_timeStretchMode", &PAGFile::timeStretchMode) .function("_setTimeStretchMode", &PAGFile::setTimeStretchMode) .function("_setDuration", optional_override([](PAGFile& pagFile, int duration) { return pagFile.setDuration(static_cast<int64_t>(duration)); })) .function("_copyOriginal", &PAGFile::copyOriginal); class_<PAGSurface>("_PAGSurface") .smart_ptr<std::shared_ptr<PAGSurface>>("_PAGSurface") .class_function("_FromCanvas", optional_override([](const std::string& canvasID) { return PAGSurface::MakeFrom(GPUDrawable::FromCanvasID(canvasID)); })) .class_function("_FromTexture", optional_override([](int textureID, int width, int height, bool flipY) { GLTextureInfo glInfo = {}; glInfo.target = GL_TEXTURE_2D; glInfo.id = static_cast<unsigned>(textureID); glInfo.format = GL_RGBA8; BackendTexture glTexture(glInfo, width, height); auto origin = flipY ? ImageOrigin::BottomLeft : ImageOrigin::TopLeft; return PAGSurface::MakeFrom(glTexture, origin); })) .class_function("_FromFrameBuffer", optional_override([](int frameBufferID, int width, int height, bool flipY) { GLFrameBufferInfo glFrameBufferInfo = {}; glFrameBufferInfo.id = static_cast<unsigned>(frameBufferID); glFrameBufferInfo.format = GL_RGBA8; BackendRenderTarget glRenderTarget(glFrameBufferInfo, width, height); auto origin = flipY ? ImageOrigin::BottomLeft : ImageOrigin::TopLeft; return PAGSurface::MakeFrom(glRenderTarget, origin); })) .function("_width", &PAGSurface::width) .function("_height", &PAGSurface::height) .function("_updateSize", &PAGSurface::updateSize) .function("_clearAll", &PAGSurface::clearAll) .function("_freeCache", &PAGSurface::freeCache); class_<PAGImage>("_PAGImage") .smart_ptr<std::shared_ptr<PAGImage>>("_PAGImage") .class_function("_FromBytes", optional_override([](uintptr_t bytes, size_t length) { return PAGImage::FromBytes(reinterpret_cast<void*>(bytes), length); })) .class_function("_FromNativeImage", optional_override([](val nativeImage) { return std::static_pointer_cast<PAGImage>( StillImage::FromImage(tgfx::NativeImage::MakeFrom(nativeImage))); })) .function("_width", &PAGImage::width) .function("_height", &PAGImage::height) .function("_scaleMode", &PAGImage::scaleMode) .function("_setScaleMode", &PAGImage::setScaleMode) .function("_matrix", optional_override([](PAGImage& pagImage) { return ToTGFX(pagImage.matrix()); })) .function("_setMatrix", optional_override([](PAGImage& pagImage, tgfx::Matrix matrix) { pagImage.setMatrix(ToPAG(matrix)); })); class_<PAGPlayer>("_PAGPlayer") .smart_ptr_constructor("_PAGPlayer", &std::make_shared<PAGPlayer>) .function("_setProgress", &PAGPlayer::setProgress) .function("_flush", &PAGPlayer::flush) .function("_duration", optional_override([](PAGPlayer& pagPlayer) { return static_cast<int>(pagPlayer.duration()); })) .function("_getProgress", &PAGPlayer::getProgress) .function("_videoEnabled", &PAGPlayer::videoEnabled) .function("_setVideoEnabled", &PAGPlayer::setVideoEnabled) .function("_cacheEnabled", &PAGPlayer::cacheEnabled) .function("_setCacheEnabled", &PAGPlayer::setCacheEnabled) .function("_cacheScale", &PAGPlayer::cacheScale) .function("_setCacheScale", &PAGPlayer::setCacheScale) .function("_maxFrameRate", &PAGPlayer::maxFrameRate) .function("_setMaxFrameRate", &PAGPlayer::setMaxFrameRate) .function("_scaleMode", &PAGPlayer::scaleMode) .function("_setScaleMode", &PAGPlayer::setScaleMode) .function("_setSurface", &PAGPlayer::setSurface) .function("_getComposition", &PAGPlayer::getComposition) .function("_setComposition", &PAGPlayer::setComposition) .function("_getSurface", &PAGPlayer::getSurface) .function("_matrix", optional_override([](PAGPlayer& pagPlayer) { return ToTGFX(pagPlayer.matrix()); })) .function("_setMatrix", optional_override([](PAGPlayer& pagPlayer, tgfx::Matrix matrix) { pagPlayer.setMatrix(ToPAG(matrix)); })) .function("_nextFrame", &PAGPlayer::nextFrame) .function("_preFrame", &PAGPlayer::preFrame) .function("_autoClear", &PAGPlayer::autoClear) .function("_setAutoClear", &PAGPlayer::setAutoClear) .function("_getBounds", optional_override([](PAGPlayer& pagPlayer, std::shared_ptr<PAGLayer> pagLayer) { return ToTGFX(pagPlayer.getBounds(pagLayer)); })) .function("_getLayersUnderPoint", &PAGPlayer::getLayersUnderPoint) .function("_hitTestPoint", &PAGPlayer::hitTestPoint) .function("_renderingTime", optional_override([](PAGPlayer& pagPlayer) { return static_cast<int>(pagPlayer.renderingTime()); })) .function("_imageDecodingTime", optional_override([](PAGPlayer& pagPlayer) { return static_cast<int>(pagPlayer.imageDecodingTime()); })) .function("_presentingTime", optional_override([](PAGPlayer& pagPlayer) { return static_cast<int>(pagPlayer.presentingTime()); })) .function("_graphicsMemory", optional_override([](PAGPlayer& pagPlayer) { return static_cast<int>(pagPlayer.graphicsMemory()); })); class_<PAGFont>("_PAGFont") .smart_ptr<std::shared_ptr<PAGFont>>("_PAGFont") .class_function("_create", optional_override([](std::string fontFamily, std::string fontStyle) { return pag::PAGFont(fontFamily, fontStyle); })) .class_function("_SetFallbackFontNames", PAGFont::SetFallbackFontNames) .property("fontFamily", &PAGFont::fontFamily) .property("fontStyle", &PAGFont::fontStyle); class_<tgfx::ImageInfo>("ImageInfo") .property("width", &tgfx::ImageInfo::width) .property("height", &tgfx::ImageInfo::height) .property("rowBytes", &tgfx::ImageInfo::rowBytes) .property("colorType", &tgfx::ImageInfo::colorType); class_<tgfx::Matrix>("Matrix") .property("a", &tgfx::Matrix::getScaleX) .property("b", &tgfx::Matrix::getSkewY) .property("c", &tgfx::Matrix::getSkewX) .property("d", &tgfx::Matrix::getScaleY) .property("tx", &tgfx::Matrix::getTranslateX) .property("ty", &tgfx::Matrix::getTranslateY) .function("set", &tgfx::Matrix::set) .function("setAffine", &tgfx::Matrix::setAffine); class_<TextDocument>("TextDocument") .smart_ptr<std::shared_ptr<TextDocument>>("TextDocument") .property("applyFill", &TextDocument::applyFill) .property("applyStroke", &TextDocument::applyStroke) .property("baselineShift", &TextDocument::baselineShift) .property("boxText", &TextDocument::boxText) .property("boxTextPos", &TextDocument::boxTextPos) .property("boxTextSize", &TextDocument::boxTextSize) .property("firstBaseLine", &TextDocument::firstBaseLine) .property("fauxBold", &TextDocument::fauxBold) .property("fauxItalic", &TextDocument::fauxItalic) .property("fillColor", &TextDocument::fillColor) .property("fontFamily", &TextDocument::fontFamily) .property("fontStyle", &TextDocument::fontStyle) .property("fontSize", &TextDocument::fontSize) .property("strokeColor", &TextDocument::strokeColor) .property("strokeOverFill", &TextDocument::strokeOverFill) .property("strokeWidth", &TextDocument::strokeWidth) .property("text", &TextDocument::text) .property("justification", &TextDocument::justification) .property("leading", &TextDocument::leading) .property("tracking", &TextDocument::tracking) .property("backgroundColor", &TextDocument::backgroundColor) .property("backgroundAlpha", &TextDocument::backgroundAlpha) .property("direction", &TextDocument::direction); class_<tgfx::Stroke>("Stroke") .property("width", &tgfx::Stroke::width) .property("cap", &tgfx::Stroke::cap) .property("join", &tgfx::Stroke::join) .property("miterLimit", &tgfx::Stroke::miterLimit); class_<PAGVideoRange>("PAGVideoRange") .function("startTime", optional_override([](PAGVideoRange& pagVideoRange) { return static_cast<int>(pagVideoRange.startTime()); })) .function("endTime", optional_override([](PAGVideoRange& pagVideoRange) { return static_cast<int>(pagVideoRange.endTime()); })) .function("playDuration", optional_override([](PAGVideoRange& pagVideoRange) { return static_cast<int>(pagVideoRange.playDuration()); })) .function("reversed", &PAGVideoRange::reversed); value_object<tgfx::FontMetrics>("FontMetrics") .field("ascent", &tgfx::FontMetrics::ascent) .field("descent", &tgfx::FontMetrics::descent) .field("xHeight", &tgfx::FontMetrics::xHeight) .field("capHeight", &tgfx::FontMetrics::capHeight); value_object<tgfx::Rect>("Rect") .field("left", &tgfx::Rect::left) .field("top", &tgfx::Rect::top) .field("right", &tgfx::Rect::right) .field("bottom", &tgfx::Rect::bottom); value_object<tgfx::Point>("Point").field("x", &tgfx::Point::x).field("y", &tgfx::Point::y); value_object<Color>("Color") .field("red", &Color::red) .field("green", &Color::green) .field("blue", &Color::blue); value_object<Marker>("Marker") .field("startTime", optional_override([](const Marker& marker) { return static_cast<int>(marker.startTime); }), optional_override( [](Marker& marker, int value) { marker.startTime = static_cast<int64_t>(value); })) .field("duration", optional_override([](const Marker& marker) { return static_cast<int>(marker.duration); }), optional_override( [](Marker& marker, int value) { marker.duration = static_cast<int64_t>(value); })) .field("comment", &Marker::comment); enum_<tgfx::PathFillType>("PathFillType") .value("Winding", tgfx::PathFillType::Winding) .value("EvenOdd", tgfx::PathFillType::EvenOdd) .value("InverseWinding", tgfx::PathFillType::InverseWinding) .value("InverseEvenOdd", tgfx::PathFillType::InverseEvenOdd); enum_<ColorType>("ColorType") .value("Unknown", ColorType::Unknown) .value("ALPHA_8", ColorType::ALPHA_8) .value("RGBA_8888", ColorType::RGBA_8888) .value("BGRA_8888", ColorType::BGRA_8888); enum_<tgfx::LineCap>("Cap") .value("Miter", tgfx::LineCap::Butt) .value("Round", tgfx::LineCap::Round) .value("Bevel", tgfx::LineCap::Square); enum_<tgfx::LineJoin>("Join") .value("Miter", tgfx::LineJoin::Miter) .value("Round", tgfx::LineJoin::Round) .value("Bevel", tgfx::LineJoin::Bevel); register_vector<std::shared_ptr<PAGLayer>>("VectorPAGLayer"); register_vector<std::string>("VectorString"); register_vector<tgfx::Point>("VectorPoint"); register_vector<Marker>("VectorMarker"); register_vector<PAGVideoRange>("VectorPAGVideoRange"); }
// Copyright (C) 2020 THL A29 Limited, a Tencent company. All rights reserved. // Please refer to the license text that comes with this tendis open source // project for additional information. #include <stdio.h> #include <iostream> #include <string> #include <algorithm> #include "gtest/gtest.h" #include "glog/logging.h" #include "tendisplus/network/network.h" #include "tendisplus/network/blocking_tcp_client.h" #include "tendisplus/utils/test_util.h" #include "tendisplus/utils/time.h" #include "tendisplus/utils/scopeguard.h" #include "tendisplus/utils/sync_point.h" namespace tendisplus { TEST(NetSession, drainReqInvalid) { asio::io_context ioContext; asio::ip::tcp::socket socket(ioContext); auto sess = std::make_shared<NoSchedNetSession>(nullptr, std::move(socket), 1, false, std::make_shared<NetworkMatrix>(), std::make_shared<RequestMatrix>()); const auto guard = MakeGuard([] { SyncPoint::GetInstance()->ClearAllCallBacks(); }); SyncPoint::GetInstance()->EnableProcessing(); bool hasCalled = false; SyncPoint::GetInstance()->SetCallBack( "NetSession::setRspAndClose", [&](void* arg) { hasCalled = true; std::string* v = static_cast<std::string*>(arg); EXPECT_TRUE(v->find("Protocol error") != std::string::npos); }); // const std::string s = "\r\n :1\r\n :2\r\n :3\r\n"; // std::vector<uint32_t> lens = { 2, 4, 4, 4 }; std::vector<std::pair<std::string, NetSession::State>> arr = { {"\r", NetSession::State::DrainReqNet}, {"\r\n", NetSession::State::Process}, {":1\r\n", NetSession::State::Process}, {"ping\r\n", NetSession::State::Process}, {"\"\r\n", NetSession::State::Created}, // error {"*10\r", NetSession::State::DrainReqNet}, {"*2\r\n$1\r\n", NetSession::State::DrainReqNet}, {"*2\r\n$a\r\n", NetSession::State::Created}, // error {"*100000000\r\n", NetSession::State::Created}, // error {"*-10\r\n", NetSession::State::Process}, {"*2\r\n:\r\n", NetSession::State::Created}, // error, should be $ }; sess->_queryBuf.reserve(128); int i = 0; for (auto s : arr) { hasCalled = false; sess->_queryBuf.clear(); sess->_queryBufPos = 0; sess->resetMultiBulkCtx(); std::copy( s.first.begin(), s.first.end(), std::back_inserter(sess->_queryBuf)); #ifdef _WIN32 sess->_queryBuf.resize(s.first.size() + 1); #endif sess->setState(NetSession::State::DrainReqNet); sess->drainReqCallback(std::error_code(), s.first.size()); if (s.second == NetSession::State::Created) { EXPECT_TRUE(sess->_closeAfterRsp && hasCalled); } else { EXPECT_EQ(sess->_state, s.second); } i++; } } TEST(NetSession, Completed) { std::string s = "*2\r\n$3\r\nfoo\r\n$3\r\nbar\r"; asio::io_context ioContext; asio::ip::tcp::socket socket(ioContext); auto sess = std::make_shared<NoSchedNetSession>(nullptr, std::move(socket), 1, false, std::make_shared<NetworkMatrix>(), std::make_shared<RequestMatrix>()); sess->setState(NetSession::State::DrainReqNet); sess->_queryBuf.resize(128, 0); for (auto& c : s) { sess->_queryBuf[sess->_queryBufPos] = c; sess->drainReqCallback(std::error_code(), 1); EXPECT_EQ(sess->_state.load(), NetSession::State::DrainReqNet); EXPECT_EQ(sess->_closeAfterRsp, false); } sess->_queryBuf[sess->_queryBufPos] = '\n'; sess->drainReqCallback(std::error_code(), 1); EXPECT_EQ(sess->_state.load(), NetSession::State::Process); EXPECT_EQ(sess->_closeAfterRsp, false); EXPECT_EQ(sess->_args.size(), size_t(2)); EXPECT_EQ(sess->_args[0], "foo"); EXPECT_EQ(sess->_args[1], "bar"); sess->resetMultiBulkCtx(); s = "FULLSYNC 1\r"; sess->setState(NetSession::State::DrainReqNet); sess->_queryBuf.resize(128, 0); for (auto& c : s) { sess->_queryBuf[sess->_queryBufPos] = c; sess->drainReqCallback(std::error_code(), 1); EXPECT_EQ(sess->_state.load(), NetSession::State::DrainReqNet); EXPECT_EQ(sess->_closeAfterRsp, false); } sess->_queryBuf[sess->_queryBufPos] = '\n'; sess->drainReqCallback(std::error_code(), 1); EXPECT_EQ(sess->_state.load(), NetSession::State::Process); EXPECT_EQ(sess->_closeAfterRsp, false); EXPECT_EQ(sess->_args.size(), size_t(2)); EXPECT_EQ(sess->_args[0], "FULLSYNC"); EXPECT_EQ(sess->_args[1], "1"); } class session : public std::enable_shared_from_this<session> { public: explicit session(asio::ip::tcp::socket socket) : _socket(std::move(socket)) {} void start() { do_read(); } private: void do_read() { auto self(shared_from_this()); using namespace std::chrono_literals; // NOLINT _socket.async_read_some(asio::buffer(_data, max_length), [this, self](std::error_code ec, size_t length) { if (!ec) { std::this_thread::sleep_for(2s); do_write(length); } }); } void do_write(size_t length) { auto self(shared_from_this()); asio::async_write(_socket, asio::buffer(_data, length), [this, self](std::error_code ec, size_t /*length*/) { if (!ec) { do_read(); } }); } asio::ip::tcp::socket _socket; enum { max_length = 1024 }; char _data[max_length]; }; class server { public: server(asio::io_context& io_context, uint16_t port) { try { _acceptor = new asio::ip::tcp::acceptor( io_context, asio::ip::tcp::endpoint(asio::ip::tcp::v4(), port)); } catch (exception e) { #if defined(TENDIS_DEBUG) && !defined(_WIN32) printPortRunningInfo(port); #endif LOG(FATAL) << "_acceptor async_accept catch error:" << e.what(); } _acceptor->set_option(asio::ip::tcp::acceptor::reuse_address(true)); do_accept(); } ~server() { if (_acceptor) { delete _acceptor; } } private: void do_accept() { _acceptor->async_accept( [this](std::error_code ec, asio::ip::tcp::socket socket) { if (!ec) { std::make_shared<session>(std::move(socket))->start(); } do_accept(); }); } asio::ip::tcp::acceptor* _acceptor; }; TEST(BlockingTcpClient, Common) { auto ioCtx = std::make_shared<asio::io_context>(); auto ioCtx1 = std::make_shared<asio::io_context>(); uint32_t port = 54001; /* BlockingTcpClient cli(ioCtx, 128); Status s = cli.connect("127.0.0.1", port, std::chrono::seconds(1)); EXPECT_FALSE(s.ok()); s = cli.connect("127.0.0.1", port, std::chrono::seconds(1)); EXPECT_FALSE(s.ok()); EXPECT_EQ(s.toString(), "already inited sock"); */ server svr(*ioCtx, port); std::thread thd([&ioCtx] { asio::io_context::work work(*ioCtx); ioCtx->run(); }); std::thread thd1([&ioCtx1] { asio::io_context::work work(*ioCtx1); ioCtx1->run(); }); auto cli1 = std::make_shared<BlockingTcpClient>(ioCtx1, 128, 1024 * 1024, 10); Status s = cli1->connect("127.0.0.1", port, std::chrono::seconds(1)); EXPECT_TRUE(s.ok()); s = cli1->connect("127.0.0.1", port, std::chrono::seconds(1)); EXPECT_FALSE(s.ok()); EXPECT_EQ(s.toString(), "-ERR:1,msg:already inited sock\r\n"); s = cli1->writeLine("hello world\r\n hello world1\r\n trailing"); EXPECT_TRUE(s.ok()); Expected<std::string> exps = cli1->readLine(std::chrono::seconds(3)); EXPECT_TRUE(exps.ok()); EXPECT_EQ(exps.value(), "hello world"); exps = cli1->readLine(std::chrono::seconds(3)); EXPECT_TRUE(exps.ok()); EXPECT_EQ(exps.value(), " hello world1"); EXPECT_EQ(cli1->getReadBufSize(), std::string(" trailing\r\n").size()); exps = cli1->read(1, std::chrono::seconds(1)); EXPECT_TRUE(exps.ok()) << exps.status().toString(); EXPECT_EQ(exps.value()[0], ' '); EXPECT_EQ(cli1->getReadBufSize(), std::string("trailing\r\n").size()); exps = cli1->read(10, std::chrono::seconds(1)); EXPECT_TRUE(exps.ok()) << exps.status().toString(); EXPECT_EQ(exps.value(), "trailing\r\n"); EXPECT_EQ(cli1->getReadBufSize(), size_t(0)); s = cli1->writeLine("hello world"); // timeout exps = cli1->readLine(std::chrono::seconds(1)); EXPECT_FALSE(exps.ok()) << exps.value(); // more than max buf size auto cli2 = std::make_shared<BlockingTcpClient>(ioCtx1, 4, 1024 * 1024, 10); s = cli2->connect("127.0.0.1", port, std::chrono::seconds(1)); EXPECT_TRUE(s.ok()); s = cli2->writeLine("hello world"); exps = cli2->readLine(std::chrono::seconds(3)); EXPECT_FALSE(exps.ok()); ioCtx->stop(); ioCtx1->stop(); thd.join(); thd1.join(); } class session2 : public std::enable_shared_from_this<session2> { public: explicit session2(asio::ip::tcp::socket socket) : _socket(std::move(socket)) {} void start() { do_read(); } private: void do_read() { auto self(shared_from_this()); using namespace std::chrono_literals; // NOLINT _socket.async_read_some(asio::buffer(_data, max_length), [this, self](std::error_code ec, size_t length) { if (ec) { // LOG(ERROR) << ec.message(); } do_read(); }); } asio::ip::tcp::socket _socket; enum { max_length = 1024 }; char _data[max_length]; }; class server2 { public: server2(asio::io_context& io_context, uint16_t port) { try { _acceptor = new asio::ip::tcp::acceptor( io_context, asio::ip::tcp::endpoint(asio::ip::tcp::v4(), port)); } catch (exception e) { #if defined(TENDIS_DEBUG) && !defined(_WIN32) printPortRunningInfo(port); #endif LOG(FATAL) << "_acceptor async_accept catch error:" << e.what(); } _acceptor->set_option(asio::ip::tcp::acceptor::reuse_address(true)); do_accept(); } ~server2() { if (_acceptor) { delete _acceptor; } } private: void do_accept() { _acceptor->async_accept( [this](std::error_code ec, asio::ip::tcp::socket socket) { if (!ec) { std::make_shared<session2>(std::move(socket))->start(); } do_accept(); }); } asio::ip::tcp::acceptor* _acceptor; }; void rateLimit(uint64_t ratelimit, std::shared_ptr<asio::io_context> ioCtx, uint32_t port) { uint32_t total = ratelimit * 10; auto cli1 = std::make_shared<BlockingTcpClient>(ioCtx, 128, 1024 * 1024, 10, ratelimit); Status s = cli1->connect("127.0.0.1", port, std::chrono::seconds(1)); EXPECT_TRUE(s.ok()); uint32_t count = 0; auto now = msSinceEpoch(); size_t buffer_size = 1024 * 16; if (buffer_size > total) { buffer_size = ratelimit; } std::string str; str.assign(buffer_size, 'a'); while (count < total) { s = cli1->writeLine(str); EXPECT_TRUE(s.ok()); count += str.size(); } uint32_t use_time = (msSinceEpoch() - now) / 1000; LOG(INFO) << "rate:" << ratelimit << " use " << use_time << " seconds"; EXPECT_TRUE(use_time >= total / ratelimit && use_time < total * 1.3 / ratelimit); } TEST(BlockingTcpClient, RateLimit) { auto ioCtx = std::make_shared<asio::io_context>(); auto ioCtx1 = std::make_shared<asio::io_context>(); uint32_t port = 54011; server2 svr(*ioCtx, port); std::thread thd([&ioCtx] { asio::io_context::work work(*ioCtx); ioCtx->run(); }); std::thread thd1([&ioCtx1] { asio::io_context::work work(*ioCtx1); ioCtx1->run(); }); rateLimit(1024, ioCtx1, port); rateLimit(102400, ioCtx1, port); rateLimit(1024000, ioCtx1, port); rateLimit(10240000, ioCtx1, port); // rateLimit(102400000, ioCtx1, port); ioCtx->stop(); ioCtx1->stop(); thd.join(); thd1.join(); } } // namespace tendisplus
//********************************************************* // // Copyright (c) Microsoft. All rights reserved. // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. // //********************************************************* // // CachedFileUpdaterPage.xaml.cpp // Implementation of the CachedFileUpdaterPage.xaml class. // #include "pch.h" #include "CachedFileUpdaterPage.xaml.h" #include "Constants.h" #include "App.xaml.h" #include <collection.h> using namespace SDKSample; using namespace SDKSample::Common; using namespace SDKSample::FilePickerContracts; using namespace Platform; using namespace Windows::ApplicationModel::Activation; using namespace Windows::Foundation; using namespace Windows::Foundation::Collections; using namespace Windows::Graphics::Display; using namespace Windows::Storage::Provider; using namespace Windows::UI::ViewManagement; using namespace Windows::UI::Xaml; using namespace Windows::UI::Xaml::Controls; using namespace Windows::UI::Xaml::Interop; using namespace Windows::UI::Xaml::Navigation; CachedFileUpdaterPage^ CachedFileUpdaterPage::Current = nullptr; CachedFileUpdaterPage::CachedFileUpdaterPage() { InitializeComponent(); // This frame is hidden, meaning it is never shown. It is simply used to load // each scenario page and then pluck out the input and output sections and // place them into the UserControls on the main page. HiddenFrame = ref new Windows::UI::Xaml::Controls::Frame(); HiddenFrame->Visibility = Windows::UI::Xaml::Visibility::Collapsed; LayoutRoot->Children->Append(HiddenFrame); FeatureName->Text = FEATURE_NAME; this->SizeChanged += ref new SizeChangedEventHandler(this, &CachedFileUpdaterPage::CachedFileUpdaterPage_SizeChanged); Scenarios->SelectionChanged += ref new SelectionChangedEventHandler(this, &CachedFileUpdaterPage::Scenarios_SelectionChanged); CachedFileUpdaterPage::Current = this; } /// <summary> /// We need to handle SizeChanged so that we can make the sample layout property /// in the various layouts. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> void CachedFileUpdaterPage::CachedFileUpdaterPage_SizeChanged(Object^ sender, SizeChangedEventArgs^ e) { InvalidateSize(); PageSizeChangedEventArgs^ args = ref new PageSizeChangedEventArgs(); args->Width = this->ActualWidth; PageResized(this, args); } void CachedFileUpdaterPage::InvalidateSize() { // Get the window width double windowWidth = this->ActualWidth; if (windowWidth != 0.0) { // Get the width of the ListBox. double listBoxWidth = Scenarios->ActualWidth; // Is the ListBox using any margins that we need to consider? double listBoxMarginLeft = Scenarios->Margin.Left; double listBoxMarginRight = Scenarios->Margin.Right; // Figure out how much room is left after considering the list box width double availableWidth = windowWidth - listBoxWidth; // Is the top most child using margins? double layoutRootMarginLeft = ContentRoot->Margin.Left; double layoutRootMarginRight = ContentRoot->Margin.Right; // We have different widths to use depending on the layout if (windowWidth >= 768) { // Make us as big as the the left over space, factoring in the ListBox width, the ListBox margins. // and the LayoutRoot's margins InputSection->Width = availableWidth - (layoutRootMarginLeft + layoutRootMarginRight + listBoxMarginLeft + listBoxMarginRight); } else { // Make us as big as the left over space, factoring in just the LayoutRoot's margins. InputSection->Width = windowWidth - (layoutRootMarginLeft + layoutRootMarginRight); } } InvalidateLayout(); } void CachedFileUpdaterPage::InvalidateLayout() { if (this->ActualWidth < 768) { Grid::SetRow(DescriptionText, 3); Grid::SetColumn(DescriptionText, 0); Grid::SetRow(InputSection, 4); Grid::SetColumn(InputSection, 0); Grid::SetRow(FooterPanel, 2); Grid::SetColumn(FooterPanel, 0); } else { Grid::SetRow(DescriptionText, 1); Grid::SetColumn(DescriptionText, 1); Grid::SetRow(InputSection, 2); Grid::SetColumn(InputSection, 1); Grid::SetRow(FooterPanel, 1); Grid::SetColumn(FooterPanel, 1); } // Since we don't load the scenario page in the traditional manner (we just pluck out the // input and output sections from the page) we need to ensure that any VSM code used // by the scenario's input and output sections is fired. VisualStateManager::GoToState(InputSection, "Input" + LayoutAwarePage::DetermineVisualState(this->ActualWidth), false); VisualStateManager::GoToState(OutputSection, "Output" + LayoutAwarePage::DetermineVisualState(this->ActualWidth), false); } void CachedFileUpdaterPage::PopulateScenarios() { ScenarioList = ref new Platform::Collections::Vector<Object^>(); // Populate the ListBox with the list of scenarios as defined in Constants.cpp. for (unsigned int i = 0; i < scenarios->Length; ++i) { Scenario s = scenarios[i]; ListBoxItem^ item = ref new ListBoxItem(); item->Name = s.ClassName; item->Content = (i + 1).ToString() + ") " + s.Title; ScenarioList->Append(item); } // Bind the ListBox to the scenario list. Scenarios->ItemsSource = ScenarioList; } /// <summary> /// This method is responsible for loading the individual input and output sections for each scenario. This /// is based on navigating a hidden Frame to the ScenarioX.xaml page and then extracting out the input /// and output sections into the respective UserControl on the main page. /// </summary> /// <param name="scenarioName"></param> void CachedFileUpdaterPage::LoadScenario(String^ scenarioName) { // Load the ScenarioX.xaml file into the Frame. TypeName scenarioType = {scenarioName, TypeKind::Custom}; HiddenFrame->Navigate(scenarioType, this); // Get the top element, the Page, so we can look up the elements // that represent the input and output sections of the ScenarioX file. Page^ hiddenPage = safe_cast<Page^>(HiddenFrame->Content); // Get each element. UIElement^ input = safe_cast<UIElement^>(hiddenPage->FindName("Input")); UIElement^ output = safe_cast<UIElement^>(hiddenPage->FindName("Output")); if (input == nullptr) { // Malformed input section. NotifyUser("Cannot load scenario input section for " + scenarioName + " Make sure root of input section markup has x:Name of 'Input'", NotifyType::ErrorMessage); return; } if (output == nullptr) { // Malformed output section. NotifyUser("Cannot load scenario output section for " + scenarioName + " Make sure root of output section markup has x:Name of 'Output'", NotifyType::ErrorMessage); return; } // Find the LayoutRoot which parents the input and output sections in the main page. Panel^ panel = safe_cast<Panel^>(hiddenPage->FindName("LayoutRoot")); if (panel != nullptr) { unsigned int index = 0; UIElementCollection^ collection = panel->Children; // Get rid of the content that is currently in the intput and output sections. collection->IndexOf(input, &index); collection->RemoveAt(index); collection->IndexOf(output, &index); collection->RemoveAt(index); // Populate the input and output sections with the newly loaded content. InputSection->Content = input; OutputSection->Content = output; ScenarioLoaded(this, nullptr); } else { // Malformed Scenario file. NotifyUser("Cannot load scenario: " + scenarioName + ". Make sure root tag in the '" + scenarioName + "' file has an x:Name of 'LayoutRoot'", NotifyType::ErrorMessage); } } void CachedFileUpdaterPage::Scenarios_SelectionChanged(Object^ sender, SelectionChangedEventArgs^ e) { if (Scenarios->SelectedItem != nullptr) { NotifyUser("", NotifyType::StatusMessage); LoadScenario((safe_cast<ListBoxItem^>(Scenarios->SelectedItem))->Name); InvalidateSize(); } } void CachedFileUpdaterPage::NotifyUser(String^ strMessage, NotifyType type) { switch (type) { case NotifyType::StatusMessage: // Use the status message style. StatusBlock->Style = safe_cast<Windows::UI::Xaml::Style^>(this->Resources->Lookup("StatusStyle")); break; case NotifyType::ErrorMessage: // Use the error message style. StatusBlock->Style = safe_cast<Windows::UI::Xaml::Style^>(this->Resources->Lookup("ErrorStyle")); break; default: break; } StatusBlock->Text = strMessage; // Collapsed the StatusBlock if it has no text to conserve real estate. if (StatusBlock->Text != "") { StatusBlock->Visibility = Windows::UI::Xaml::Visibility::Visible; } else { StatusBlock->Visibility = Windows::UI::Xaml::Visibility::Collapsed; } } void CachedFileUpdaterPage::Footer_Click(Object^ sender, RoutedEventArgs^ e) { auto uri = ref new Uri((String^)((HyperlinkButton^)sender)->Tag); Windows::System::Launcher::LaunchUriAsync(uri); } /// <summary> /// Populates the page with content passed during navigation. Any saved state is also /// provided when recreating a page from a prior session. /// </summary> /// <param name="navigationParameter">The parameter value passed to /// <see cref="Frame::Navigate(Type, Object)"/> when this page was initially requested. /// </param> /// <param name="pageState">A map of state preserved by this page during an earlier /// session. This will be null the first time a page is visited.</param> void CachedFileUpdaterPage::LoadState(Object^ navigationParameter, IMap<String^, Object^>^ pageState) { (void) navigationParameter; // Unused parameter PopulateScenarios(); // Starting scenario is the first or based upon a previous state. ListBoxItem^ startingScenario = nullptr; int startingScenarioIndex = -1; if (pageState != nullptr && pageState->HasKey("SelectedScenarioIndex")) { startingScenarioIndex = safe_cast<int>(pageState->Lookup("SelectedScenarioIndex")); } Scenarios->SelectedIndex = startingScenarioIndex != -1 ? startingScenarioIndex : 0; InvalidateLayout(); } /// <summary> /// Preserves state associated with this page in case the application is suspended or the /// page is discarded from the navigation cache. Values must conform to the serialization /// requirements of <see cref="SuspensionManager::SessionState"/>. /// </summary> /// <param name="pageState">An empty map to be populated with serializable state.</param> void CachedFileUpdaterPage::SaveState(IMap<String^, Object^>^ pageState) { int selectedListBoxItemIndex = Scenarios->SelectedIndex; pageState->Insert("SelectedScenarioIndex", selectedListBoxItemIndex); } void CachedFileUpdaterPage::Activate(CachedFileUpdaterActivatedEventArgs^ args) { // cache CachedFileUpdaterUI cachedFileUpdaterUI = args->CachedFileUpdaterUI; cachedFileUpdaterUI->FileUpdateRequested += ref new TypedEventHandler<CachedFileUpdaterUI^, FileUpdateRequestedEventArgs^>(this, &CachedFileUpdaterPage::OnFileUpdateRequested, CallbackContext::Same); cachedFileUpdaterUI->UIRequested += ref new TypedEventHandler<CachedFileUpdaterUI^, Platform::Object^>(this, &CachedFileUpdaterPage::OnUIRequested, CallbackContext::Same); Window::Current->Activate(); } void CachedFileUpdaterPage::OnFileUpdateRequested(CachedFileUpdaterUI^ sender, FileUpdateRequestedEventArgs^ e) { fileUpdateRequest = e->Request; fileUpdateRequestDeferral = fileUpdateRequest->GetDeferral(); switch (cachedFileUpdaterUI->UIStatus) { case UIStatus::Hidden: fileUpdateRequest->Status = FileUpdateStatus::UserInputNeeded; fileUpdateRequestDeferral->Complete(); break; case UIStatus::Visible: break; case UIStatus::Unavailable: fileUpdateRequest->Status = FileUpdateStatus::Failed; fileUpdateRequestDeferral->Complete(); break; } } void CachedFileUpdaterPage::OnUIRequested(Windows::Storage::Provider::CachedFileUpdaterUI^ sender, Platform::Object^ e) { Window::Current->Content = this; LoadState(nullptr, nullptr); }
// Copyright 2015 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/background_sync/background_sync_manager.h" #include <utility> #include "base/barrier_closure.h" #include "base/bind.h" #include "base/location.h" #include "base/memory/ptr_util.h" #include "base/single_thread_task_runner.h" #include "base/threading/thread_task_runner_handle.h" #include "base/time/default_clock.h" #include "base/time/time.h" #include "build/build_config.h" #include "content/browser/background_sync/background_sync_metrics.h" #include "content/browser/background_sync/background_sync_network_observer.h" #include "content/browser/background_sync/background_sync_registration_options.h" #include "content/browser/service_worker/embedded_worker_status.h" #include "content/browser/service_worker/service_worker_context_wrapper.h" #include "content/browser/service_worker/service_worker_storage.h" #include "content/browser/service_worker/service_worker_type_converters.h" #include "content/browser/storage_partition_impl.h" #include "content/common/service_worker/service_worker_event_dispatcher.mojom.h" #include "content/common/service_worker/service_worker_utils.h" #include "content/public/browser/background_sync_controller.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/permission_controller.h" #include "content/public/browser/permission_type.h" #include "third_party/blink/public/mojom/service_worker/service_worker_event_status.mojom.h" #if defined(OS_ANDROID) #include "content/browser/android/background_sync_network_observer_android.h" #endif namespace content { namespace { // The key used to index the background sync data in ServiceWorkerStorage. const char kBackgroundSyncUserDataKey[] = "BackgroundSyncUserData"; void RecordFailureAndPostError( BackgroundSyncStatus status, BackgroundSyncManager::StatusAndRegistrationCallback callback) { BackgroundSyncMetrics::CountRegisterFailure(status); base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce(std::move(callback), status, nullptr)); } // Returns nullptr if the browser context cannot be accessed for any reason. BrowserContext* GetBrowserContextOnUIThread( scoped_refptr<ServiceWorkerContextWrapper> service_worker_context) { DCHECK_CURRENTLY_ON(BrowserThread::UI); if (!service_worker_context) return nullptr; StoragePartitionImpl* storage_partition_impl = service_worker_context->storage_partition(); if (!storage_partition_impl) // may be null in tests return nullptr; return storage_partition_impl->browser_context(); } // Returns nullptr if the controller cannot be accessed for any reason. BackgroundSyncController* GetBackgroundSyncControllerOnUIThread( scoped_refptr<ServiceWorkerContextWrapper> service_worker_context) { DCHECK_CURRENTLY_ON(BrowserThread::UI); BrowserContext* browser_context = GetBrowserContextOnUIThread(std::move(service_worker_context)); if (!browser_context) return nullptr; return browser_context->GetBackgroundSyncController(); } blink::mojom::PermissionStatus GetBackgroundSyncPermissionOnUIThread( scoped_refptr<ServiceWorkerContextWrapper> service_worker_context, const GURL& origin) { DCHECK_CURRENTLY_ON(BrowserThread::UI); BrowserContext* browser_context = GetBrowserContextOnUIThread(std::move(service_worker_context)); if (!browser_context) return blink::mojom::PermissionStatus::DENIED; PermissionController* permission_controller = BrowserContext::GetPermissionController(browser_context); DCHECK(permission_controller); // The requesting origin always matches the embedding origin. return permission_controller->GetPermissionStatus( PermissionType::BACKGROUND_SYNC, origin, origin); } void NotifyBackgroundSyncRegisteredOnUIThread( scoped_refptr<ServiceWorkerContextWrapper> sw_context_wrapper, const GURL& origin) { DCHECK_CURRENTLY_ON(BrowserThread::UI); BackgroundSyncController* background_sync_controller = GetBackgroundSyncControllerOnUIThread(std::move(sw_context_wrapper)); if (!background_sync_controller) return; background_sync_controller->NotifyBackgroundSyncRegistered(origin); } void RunInBackgroundOnUIThread( scoped_refptr<ServiceWorkerContextWrapper> sw_context_wrapper, bool enabled, int64_t min_ms) { DCHECK_CURRENTLY_ON(BrowserThread::UI); BackgroundSyncController* background_sync_controller = GetBackgroundSyncControllerOnUIThread(sw_context_wrapper); if (background_sync_controller) { background_sync_controller->RunInBackground(enabled, min_ms); } } std::unique_ptr<BackgroundSyncParameters> GetControllerParameters( scoped_refptr<ServiceWorkerContextWrapper> sw_context_wrapper, std::unique_ptr<BackgroundSyncParameters> parameters) { DCHECK_CURRENTLY_ON(BrowserThread::UI); BackgroundSyncController* background_sync_controller = GetBackgroundSyncControllerOnUIThread(sw_context_wrapper); if (!background_sync_controller) { // If there is no controller then BackgroundSync can't run in the // background, disable it. parameters->disable = true; return parameters; } background_sync_controller->GetParameterOverrides(parameters.get()); return parameters; } void OnSyncEventFinished(scoped_refptr<ServiceWorkerVersion> active_version, int request_id, ServiceWorkerVersion::StatusCallback callback, blink::mojom::ServiceWorkerEventStatus status, base::Time dispatch_event_time) { if (!active_version->FinishRequest( request_id, status == blink::mojom::ServiceWorkerEventStatus::COMPLETED, dispatch_event_time)) { return; } std::move(callback).Run(mojo::ConvertTo<ServiceWorkerStatusCode>(status)); } void DidStartWorkerForSyncEvent( base::OnceCallback<void(ServiceWorkerVersion::StatusCallback)> task, ServiceWorkerVersion::StatusCallback callback, ServiceWorkerStatusCode start_worker_status) { if (start_worker_status != SERVICE_WORKER_OK) { std::move(callback).Run(start_worker_status); return; } std::move(task).Run(std::move(callback)); } } // namespace BackgroundSyncManager::BackgroundSyncRegistrations:: BackgroundSyncRegistrations() : next_id(BackgroundSyncRegistration::kInitialId) { } BackgroundSyncManager::BackgroundSyncRegistrations::BackgroundSyncRegistrations( const BackgroundSyncRegistrations& other) = default; BackgroundSyncManager::BackgroundSyncRegistrations:: ~BackgroundSyncRegistrations() { } // static std::unique_ptr<BackgroundSyncManager> BackgroundSyncManager::Create( scoped_refptr<ServiceWorkerContextWrapper> service_worker_context) { DCHECK_CURRENTLY_ON(BrowserThread::IO); BackgroundSyncManager* sync_manager = new BackgroundSyncManager(service_worker_context); sync_manager->Init(); return base::WrapUnique(sync_manager); } BackgroundSyncManager::~BackgroundSyncManager() { DCHECK_CURRENTLY_ON(BrowserThread::IO); service_worker_context_->RemoveObserver(this); } void BackgroundSyncManager::Register( int64_t sw_registration_id, const BackgroundSyncRegistrationOptions& options, StatusAndRegistrationCallback callback) { DCHECK_CURRENTLY_ON(BrowserThread::IO); if (disabled_) { RecordFailureAndPostError(BACKGROUND_SYNC_STATUS_STORAGE_ERROR, std::move(callback)); return; } op_scheduler_.ScheduleOperation(base::BindOnce( &BackgroundSyncManager::RegisterCheckIfHasMainFrame, weak_ptr_factory_.GetWeakPtr(), sw_registration_id, options, op_scheduler_.WrapCallbackToRunNext(std::move(callback)))); } void BackgroundSyncManager::GetRegistrations( int64_t sw_registration_id, StatusAndRegistrationsCallback callback) { DCHECK_CURRENTLY_ON(BrowserThread::IO); if (disabled_) { base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce( std::move(callback), BACKGROUND_SYNC_STATUS_STORAGE_ERROR, std::vector<std::unique_ptr<BackgroundSyncRegistration>>())); return; } op_scheduler_.ScheduleOperation( base::BindOnce(&BackgroundSyncManager::GetRegistrationsImpl, weak_ptr_factory_.GetWeakPtr(), sw_registration_id, op_scheduler_.WrapCallbackToRunNext(std::move(callback)))); } void BackgroundSyncManager::OnRegistrationDeleted(int64_t sw_registration_id, const GURL& pattern) { DCHECK_CURRENTLY_ON(BrowserThread::IO); // Operations already in the queue will either fail when they write to storage // or return stale results based on registrations loaded in memory. This is // inconsequential since the service worker is gone. op_scheduler_.ScheduleOperation( base::BindOnce(&BackgroundSyncManager::OnRegistrationDeletedImpl, weak_ptr_factory_.GetWeakPtr(), sw_registration_id, MakeEmptyCompletion())); } void BackgroundSyncManager::OnStorageWiped() { DCHECK_CURRENTLY_ON(BrowserThread::IO); // Operations already in the queue will either fail when they write to storage // or return stale results based on registrations loaded in memory. This is // inconsequential since the service workers are gone. op_scheduler_.ScheduleOperation( base::BindOnce(&BackgroundSyncManager::OnStorageWipedImpl, weak_ptr_factory_.GetWeakPtr(), MakeEmptyCompletion())); } void BackgroundSyncManager::SetMaxSyncAttemptsForTesting(int max_attempts) { DCHECK_CURRENTLY_ON(BrowserThread::IO); op_scheduler_.ScheduleOperation(base::BindOnce( &BackgroundSyncManager::SetMaxSyncAttemptsImpl, weak_ptr_factory_.GetWeakPtr(), max_attempts, MakeEmptyCompletion())); } void BackgroundSyncManager::EmulateDispatchSyncEvent( const std::string& tag, scoped_refptr<ServiceWorkerVersion> active_version, bool last_chance, ServiceWorkerVersion::StatusCallback callback) { DCHECK_CURRENTLY_ON(BrowserThread::IO); ServiceWorkerStatusCode code = CanEmulateSyncEvent(active_version); if (code != SERVICE_WORKER_OK) { std::move(callback).Run(code); return; } DispatchSyncEvent(tag, std::move(active_version), last_chance, std::move(callback)); } void BackgroundSyncManager::EmulateServiceWorkerOffline( int64_t service_worker_id, bool is_offline) { DCHECK_CURRENTLY_ON(BrowserThread::IO); // Multiple DevTools sessions may want to set the same SW offline, which // is supposed to disable the background sync. For consistency with the // network stack, SW remains offline until all DevTools sessions disable // the offline mode. emulated_offline_sw_[service_worker_id] += is_offline ? 1 : -1; if (emulated_offline_sw_[service_worker_id] > 0) return; emulated_offline_sw_.erase(service_worker_id); FireReadyEvents(); } BackgroundSyncManager::BackgroundSyncManager( scoped_refptr<ServiceWorkerContextWrapper> service_worker_context) : op_scheduler_(CacheStorageSchedulerClient::CLIENT_BACKGROUND_SYNC), service_worker_context_(service_worker_context), parameters_(new BackgroundSyncParameters()), disabled_(false), num_firing_registrations_(0), clock_(base::DefaultClock::GetInstance()), weak_ptr_factory_(this) { DCHECK_CURRENTLY_ON(BrowserThread::IO); service_worker_context_->AddObserver(this); #if defined(OS_ANDROID) network_observer_.reset(new BackgroundSyncNetworkObserverAndroid( base::BindRepeating(&BackgroundSyncManager::OnNetworkChanged, weak_ptr_factory_.GetWeakPtr()))); #else network_observer_.reset(new BackgroundSyncNetworkObserver( base::BindRepeating(&BackgroundSyncManager::OnNetworkChanged, weak_ptr_factory_.GetWeakPtr()))); #endif } void BackgroundSyncManager::Init() { DCHECK_CURRENTLY_ON(BrowserThread::IO); DCHECK(!op_scheduler_.ScheduledOperations()); DCHECK(!disabled_); op_scheduler_.ScheduleOperation( base::BindOnce(&BackgroundSyncManager::InitImpl, weak_ptr_factory_.GetWeakPtr(), MakeEmptyCompletion())); } void BackgroundSyncManager::InitImpl(base::OnceClosure callback) { DCHECK_CURRENTLY_ON(BrowserThread::IO); if (disabled_) { base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, std::move(callback)); return; } BrowserThread::PostTaskAndReplyWithResult( BrowserThread::UI, FROM_HERE, base::BindOnce(&GetControllerParameters, service_worker_context_, std::make_unique<BackgroundSyncParameters>(*parameters_)), base::BindOnce(&BackgroundSyncManager::InitDidGetControllerParameters, weak_ptr_factory_.GetWeakPtr(), std::move(callback))); } void BackgroundSyncManager::InitDidGetControllerParameters( base::OnceClosure callback, std::unique_ptr<BackgroundSyncParameters> updated_parameters) { DCHECK_CURRENTLY_ON(BrowserThread::IO); parameters_ = std::move(updated_parameters); if (parameters_->disable) { disabled_ = true; base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, std::move(callback)); return; } GetDataFromBackend(kBackgroundSyncUserDataKey, base::AdaptCallbackForRepeating(base::BindOnce( &BackgroundSyncManager::InitDidGetDataFromBackend, weak_ptr_factory_.GetWeakPtr(), std::move(callback)))); } void BackgroundSyncManager::InitDidGetDataFromBackend( base::OnceClosure callback, const std::vector<std::pair<int64_t, std::string>>& user_data, ServiceWorkerStatusCode status) { DCHECK_CURRENTLY_ON(BrowserThread::IO); if (status != SERVICE_WORKER_OK && status != SERVICE_WORKER_ERROR_NOT_FOUND) { LOG(ERROR) << "BackgroundSync failed to init due to backend failure."; DisableAndClearManager(std::move(callback)); return; } bool corruption_detected = false; for (const std::pair<int64_t, std::string>& data : user_data) { BackgroundSyncRegistrationsProto registrations_proto; if (registrations_proto.ParseFromString(data.second)) { BackgroundSyncRegistrations* registrations = &active_registrations_[data.first]; registrations->next_id = registrations_proto.next_registration_id(); registrations->origin = GURL(registrations_proto.origin()); for (int i = 0, max = registrations_proto.registration_size(); i < max; ++i) { const BackgroundSyncRegistrationProto& registration_proto = registrations_proto.registration(i); if (registration_proto.id() >= registrations->next_id) { corruption_detected = true; break; } BackgroundSyncRegistration* registration = &registrations->registration_map[registration_proto.tag()]; BackgroundSyncRegistrationOptions* options = registration->options(); options->tag = registration_proto.tag(); options->network_state = registration_proto.network_state(); registration->set_id(registration_proto.id()); registration->set_num_attempts(registration_proto.num_attempts()); registration->set_delay_until( base::Time::FromInternalValue(registration_proto.delay_until())); } } if (corruption_detected) break; } if (corruption_detected) { LOG(ERROR) << "Corruption detected in background sync backend"; DisableAndClearManager(std::move(callback)); return; } FireReadyEvents(); base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, std::move(callback)); } void BackgroundSyncManager::RegisterCheckIfHasMainFrame( int64_t sw_registration_id, const BackgroundSyncRegistrationOptions& options, StatusAndRegistrationCallback callback) { DCHECK_CURRENTLY_ON(BrowserThread::IO); ServiceWorkerRegistration* sw_registration = service_worker_context_->GetLiveRegistration(sw_registration_id); if (!sw_registration || !sw_registration->active_version()) { RecordFailureAndPostError(BACKGROUND_SYNC_STATUS_NO_SERVICE_WORKER, std::move(callback)); return; } HasMainFrameProviderHost( sw_registration->pattern().GetOrigin(), base::BindOnce(&BackgroundSyncManager::RegisterDidCheckIfMainFrame, weak_ptr_factory_.GetWeakPtr(), sw_registration_id, options, std::move(callback))); } void BackgroundSyncManager::RegisterDidCheckIfMainFrame( int64_t sw_registration_id, const BackgroundSyncRegistrationOptions& options, StatusAndRegistrationCallback callback, bool has_main_frame_client) { DCHECK_CURRENTLY_ON(BrowserThread::IO); if (!has_main_frame_client) { RecordFailureAndPostError(BACKGROUND_SYNC_STATUS_NOT_ALLOWED, std::move(callback)); return; } RegisterImpl(sw_registration_id, options, std::move(callback)); } void BackgroundSyncManager::RegisterImpl( int64_t sw_registration_id, const BackgroundSyncRegistrationOptions& options, StatusAndRegistrationCallback callback) { DCHECK_CURRENTLY_ON(BrowserThread::IO); if (disabled_) { RecordFailureAndPostError(BACKGROUND_SYNC_STATUS_STORAGE_ERROR, std::move(callback)); return; } if (options.tag.length() > kMaxTagLength) { RecordFailureAndPostError(BACKGROUND_SYNC_STATUS_NOT_ALLOWED, std::move(callback)); return; } ServiceWorkerRegistration* sw_registration = service_worker_context_->GetLiveRegistration(sw_registration_id); if (!sw_registration || !sw_registration->active_version()) { RecordFailureAndPostError(BACKGROUND_SYNC_STATUS_NO_SERVICE_WORKER, std::move(callback)); return; } BrowserThread::PostTaskAndReplyWithResult( BrowserThread::UI, FROM_HERE, base::BindOnce(&GetBackgroundSyncPermissionOnUIThread, service_worker_context_, sw_registration->pattern().GetOrigin()), base::BindOnce(&BackgroundSyncManager::RegisterDidAskForPermission, weak_ptr_factory_.GetWeakPtr(), sw_registration_id, options, std::move(callback))); } void BackgroundSyncManager::RegisterDidAskForPermission( int64_t sw_registration_id, const BackgroundSyncRegistrationOptions& options, StatusAndRegistrationCallback callback, blink::mojom::PermissionStatus permission_status) { DCHECK_CURRENTLY_ON(BrowserThread::IO); if (permission_status == blink::mojom::PermissionStatus::DENIED) { RecordFailureAndPostError(BACKGROUND_SYNC_STATUS_PERMISSION_DENIED, std::move(callback)); return; } DCHECK(permission_status == blink::mojom::PermissionStatus::GRANTED); ServiceWorkerRegistration* sw_registration = service_worker_context_->GetLiveRegistration(sw_registration_id); if (!sw_registration || !sw_registration->active_version()) { // The service worker was shut down in the interim. RecordFailureAndPostError(BACKGROUND_SYNC_STATUS_NO_SERVICE_WORKER, std::move(callback)); return; } BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::BindOnce(&NotifyBackgroundSyncRegisteredOnUIThread, service_worker_context_, sw_registration->pattern().GetOrigin())); BackgroundSyncRegistration* existing_registration = LookupActiveRegistration(sw_registration_id, options.tag); if (existing_registration) { DCHECK(existing_registration->options()->Equals(options)); BackgroundSyncMetrics::RegistrationCouldFire registration_could_fire = AreOptionConditionsMet(options) ? BackgroundSyncMetrics::REGISTRATION_COULD_FIRE : BackgroundSyncMetrics::REGISTRATION_COULD_NOT_FIRE; BackgroundSyncMetrics::CountRegisterSuccess( registration_could_fire, BackgroundSyncMetrics::REGISTRATION_IS_DUPLICATE); if (existing_registration->IsFiring()) { existing_registration->set_sync_state( blink::mojom::BackgroundSyncState::REREGISTERED_WHILE_FIRING); } base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce(std::move(callback), BACKGROUND_SYNC_STATUS_OK, std::make_unique<BackgroundSyncRegistration>( *existing_registration))); return; } BackgroundSyncRegistration new_registration; *new_registration.options() = options; BackgroundSyncRegistrations* registrations = &active_registrations_[sw_registration_id]; new_registration.set_id(registrations->next_id++); AddActiveRegistration(sw_registration_id, sw_registration->pattern().GetOrigin(), new_registration); StoreRegistrations( sw_registration_id, base::BindOnce(&BackgroundSyncManager::RegisterDidStore, weak_ptr_factory_.GetWeakPtr(), sw_registration_id, new_registration, std::move(callback))); } void BackgroundSyncManager::DisableAndClearManager(base::OnceClosure callback) { DCHECK_CURRENTLY_ON(BrowserThread::IO); if (disabled_) { base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, std::move(callback)); return; } disabled_ = true; active_registrations_.clear(); // Delete all backend entries. The memory representation of registered syncs // may be out of sync with storage (e.g., due to corruption detection on // loading from storage), so reload the registrations from storage again. GetDataFromBackend( kBackgroundSyncUserDataKey, base::AdaptCallbackForRepeating(base::BindOnce( &BackgroundSyncManager::DisableAndClearDidGetRegistrations, weak_ptr_factory_.GetWeakPtr(), std::move(callback)))); } void BackgroundSyncManager::DisableAndClearDidGetRegistrations( base::OnceClosure callback, const std::vector<std::pair<int64_t, std::string>>& user_data, ServiceWorkerStatusCode status) { DCHECK_CURRENTLY_ON(BrowserThread::IO); if (status != SERVICE_WORKER_OK || user_data.empty()) { base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, std::move(callback)); return; } base::RepeatingClosure barrier_closure = base::BarrierClosure(user_data.size(), std::move(callback)); for (const auto& sw_id_and_regs : user_data) { service_worker_context_->ClearRegistrationUserData( sw_id_and_regs.first, {kBackgroundSyncUserDataKey}, base::AdaptCallbackForRepeating(base::BindOnce( &BackgroundSyncManager::DisableAndClearManagerClearedOne, weak_ptr_factory_.GetWeakPtr(), barrier_closure))); } } void BackgroundSyncManager::DisableAndClearManagerClearedOne( base::OnceClosure barrier_closure, ServiceWorkerStatusCode status) { DCHECK_CURRENTLY_ON(BrowserThread::IO); // The status doesn't matter at this point, there is nothing else to be done. base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, std::move(barrier_closure)); } BackgroundSyncRegistration* BackgroundSyncManager::LookupActiveRegistration( int64_t sw_registration_id, const std::string& tag) { DCHECK_CURRENTLY_ON(BrowserThread::IO); SWIdToRegistrationsMap::iterator it = active_registrations_.find(sw_registration_id); if (it == active_registrations_.end()) return nullptr; BackgroundSyncRegistrations& registrations = it->second; DCHECK_LE(BackgroundSyncRegistration::kInitialId, registrations.next_id); DCHECK(!registrations.origin.is_empty()); auto key_and_registration_iter = registrations.registration_map.find(tag); if (key_and_registration_iter == registrations.registration_map.end()) return nullptr; return &key_and_registration_iter->second; } void BackgroundSyncManager::StoreRegistrations( int64_t sw_registration_id, ServiceWorkerStorage::StatusCallback callback) { DCHECK_CURRENTLY_ON(BrowserThread::IO); // Serialize the data. const BackgroundSyncRegistrations& registrations = active_registrations_[sw_registration_id]; BackgroundSyncRegistrationsProto registrations_proto; registrations_proto.set_next_registration_id(registrations.next_id); registrations_proto.set_origin(registrations.origin.spec()); for (const auto& key_and_registration : registrations.registration_map) { const BackgroundSyncRegistration& registration = key_and_registration.second; BackgroundSyncRegistrationProto* registration_proto = registrations_proto.add_registration(); registration_proto->set_id(registration.id()); registration_proto->set_tag(registration.options()->tag); registration_proto->set_network_state( registration.options()->network_state); registration_proto->set_num_attempts(registration.num_attempts()); registration_proto->set_delay_until( registration.delay_until().ToInternalValue()); } std::string serialized; bool success = registrations_proto.SerializeToString(&serialized); DCHECK(success); StoreDataInBackend(sw_registration_id, registrations.origin, kBackgroundSyncUserDataKey, serialized, std::move(callback)); } void BackgroundSyncManager::RegisterDidStore( int64_t sw_registration_id, const BackgroundSyncRegistration& new_registration, StatusAndRegistrationCallback callback, ServiceWorkerStatusCode status) { DCHECK_CURRENTLY_ON(BrowserThread::IO); if (status == SERVICE_WORKER_ERROR_NOT_FOUND) { // The service worker registration is gone. active_registrations_.erase(sw_registration_id); RecordFailureAndPostError(BACKGROUND_SYNC_STATUS_STORAGE_ERROR, std::move(callback)); return; } if (status != SERVICE_WORKER_OK) { LOG(ERROR) << "BackgroundSync failed to store registration due to backend " "failure."; BackgroundSyncMetrics::CountRegisterFailure( BACKGROUND_SYNC_STATUS_STORAGE_ERROR); DisableAndClearManager(base::BindOnce( std::move(callback), BACKGROUND_SYNC_STATUS_STORAGE_ERROR, nullptr)); return; } BackgroundSyncMetrics::RegistrationCouldFire registration_could_fire = AreOptionConditionsMet(*new_registration.options()) ? BackgroundSyncMetrics::REGISTRATION_COULD_FIRE : BackgroundSyncMetrics::REGISTRATION_COULD_NOT_FIRE; BackgroundSyncMetrics::CountRegisterSuccess( registration_could_fire, BackgroundSyncMetrics::REGISTRATION_IS_NOT_DUPLICATE); FireReadyEvents(); base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce(std::move(callback), BACKGROUND_SYNC_STATUS_OK, std::make_unique<BackgroundSyncRegistration>( new_registration))); } void BackgroundSyncManager::RemoveActiveRegistration(int64_t sw_registration_id, const std::string& tag) { DCHECK_CURRENTLY_ON(BrowserThread::IO); DCHECK(LookupActiveRegistration(sw_registration_id, tag)); BackgroundSyncRegistrations* registrations = &active_registrations_[sw_registration_id]; registrations->registration_map.erase(tag); } void BackgroundSyncManager::AddActiveRegistration( int64_t sw_registration_id, const GURL& origin, const BackgroundSyncRegistration& sync_registration) { DCHECK_CURRENTLY_ON(BrowserThread::IO); DCHECK(sync_registration.IsValid()); BackgroundSyncRegistrations* registrations = &active_registrations_[sw_registration_id]; registrations->origin = origin; registrations->registration_map[sync_registration.options()->tag] = sync_registration; } void BackgroundSyncManager::StoreDataInBackend( int64_t sw_registration_id, const GURL& origin, const std::string& backend_key, const std::string& data, ServiceWorkerStorage::StatusCallback callback) { DCHECK_CURRENTLY_ON(BrowserThread::IO); service_worker_context_->StoreRegistrationUserData( sw_registration_id, origin, {{backend_key, data}}, base::AdaptCallbackForRepeating(std::move(callback))); } void BackgroundSyncManager::GetDataFromBackend( const std::string& backend_key, ServiceWorkerStorage::GetUserDataForAllRegistrationsCallback callback) { DCHECK_CURRENTLY_ON(BrowserThread::IO); service_worker_context_->GetUserDataForAllRegistrations(backend_key, std::move(callback)); } void BackgroundSyncManager::DispatchSyncEvent( const std::string& tag, scoped_refptr<ServiceWorkerVersion> active_version, bool last_chance, ServiceWorkerVersion::StatusCallback callback) { DCHECK_CURRENTLY_ON(BrowserThread::IO); DCHECK(active_version); if (active_version->running_status() != EmbeddedWorkerStatus::RUNNING) { active_version->RunAfterStartWorker( ServiceWorkerMetrics::EventType::SYNC, base::BindOnce(&DidStartWorkerForSyncEvent, base::BindOnce(&BackgroundSyncManager::DispatchSyncEvent, weak_ptr_factory_.GetWeakPtr(), tag, std::move(active_version), last_chance), std::move(callback))); return; } auto repeating_callback = base::AdaptCallbackForRepeating(std::move(callback)); int request_id = active_version->StartRequestWithCustomTimeout( ServiceWorkerMetrics::EventType::SYNC, repeating_callback, parameters_->max_sync_event_duration, ServiceWorkerVersion::CONTINUE_ON_TIMEOUT); active_version->event_dispatcher()->DispatchSyncEvent( tag, last_chance, parameters_->max_sync_event_duration, base::BindOnce(&OnSyncEventFinished, std::move(active_version), request_id, std::move(repeating_callback))); } void BackgroundSyncManager::ScheduleDelayedTask(base::OnceClosure callback, base::TimeDelta delay) { base::ThreadTaskRunnerHandle::Get()->PostDelayedTask( FROM_HERE, std::move(callback), delay); } void BackgroundSyncManager::HasMainFrameProviderHost(const GURL& origin, BoolCallback callback) { service_worker_context_->HasMainFrameProviderHost( origin, base::AdaptCallbackForRepeating(std::move(callback))); } void BackgroundSyncManager::GetRegistrationsImpl( int64_t sw_registration_id, StatusAndRegistrationsCallback callback) { DCHECK_CURRENTLY_ON(BrowserThread::IO); std::vector<std::unique_ptr<BackgroundSyncRegistration>> out_registrations; if (disabled_) { base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce(std::move(callback), BACKGROUND_SYNC_STATUS_STORAGE_ERROR, std::move(out_registrations))); return; } SWIdToRegistrationsMap::iterator it = active_registrations_.find(sw_registration_id); if (it != active_registrations_.end()) { const BackgroundSyncRegistrations& registrations = it->second; for (const auto& tag_and_registration : registrations.registration_map) { const BackgroundSyncRegistration& registration = tag_and_registration.second; out_registrations.push_back( std::make_unique<BackgroundSyncRegistration>(registration)); } } base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce(std::move(callback), BACKGROUND_SYNC_STATUS_OK, std::move(out_registrations))); } bool BackgroundSyncManager::AreOptionConditionsMet( const BackgroundSyncRegistrationOptions& options) { DCHECK_CURRENTLY_ON(BrowserThread::IO); return network_observer_->NetworkSufficient(options.network_state); } bool BackgroundSyncManager::IsRegistrationReadyToFire( const BackgroundSyncRegistration& registration, int64_t service_worker_id) { DCHECK_CURRENTLY_ON(BrowserThread::IO); if (registration.sync_state() != blink::mojom::BackgroundSyncState::PENDING) return false; if (clock_->Now() < registration.delay_until()) return false; if (base::ContainsKey(emulated_offline_sw_, service_worker_id)) return false; return AreOptionConditionsMet(*registration.options()); } void BackgroundSyncManager::RunInBackgroundIfNecessary() { DCHECK_CURRENTLY_ON(BrowserThread::IO); base::TimeDelta soonest_wakeup_delta = base::TimeDelta::Max(); for (const auto& sw_id_and_registrations : active_registrations_) { for (const auto& key_and_registration : sw_id_and_registrations.second.registration_map) { const BackgroundSyncRegistration& registration = key_and_registration.second; if (registration.sync_state() == blink::mojom::BackgroundSyncState::PENDING) { if (clock_->Now() >= registration.delay_until()) { soonest_wakeup_delta = base::TimeDelta(); } else { base::TimeDelta delay_delta = registration.delay_until() - clock_->Now(); if (delay_delta < soonest_wakeup_delta) soonest_wakeup_delta = delay_delta; } } } } // If the browser is closed while firing events, the browser needs a task to // wake it back up and try again. if (num_firing_registrations_ > 0 && soonest_wakeup_delta > parameters_->min_sync_recovery_time) { soonest_wakeup_delta = parameters_->min_sync_recovery_time; } // Try firing again after the wakeup delta. if (!soonest_wakeup_delta.is_max() && !soonest_wakeup_delta.is_zero()) { delayed_sync_task_.Reset(base::Bind(&BackgroundSyncManager::FireReadyEvents, weak_ptr_factory_.GetWeakPtr())); ScheduleDelayedTask(delayed_sync_task_.callback(), soonest_wakeup_delta); } // In case the browser closes (or to prevent it from closing), call // RunInBackground to either wake up the browser at the wakeup delta or to // keep the browser running. BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::BindOnce( RunInBackgroundOnUIThread, service_worker_context_, !soonest_wakeup_delta.is_max() /* should run in background */, soonest_wakeup_delta.InMilliseconds())); } void BackgroundSyncManager::FireReadyEvents() { DCHECK_CURRENTLY_ON(BrowserThread::IO); if (disabled_) return; op_scheduler_.ScheduleOperation( base::BindOnce(&BackgroundSyncManager::FireReadyEventsImpl, weak_ptr_factory_.GetWeakPtr(), MakeEmptyCompletion())); } void BackgroundSyncManager::FireReadyEventsImpl(base::OnceClosure callback) { DCHECK_CURRENTLY_ON(BrowserThread::IO); if (disabled_) { base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, std::move(callback)); return; } // Find the registrations that are ready to run. std::vector<std::pair<int64_t, std::string>> sw_id_and_tags_to_fire; for (auto& sw_id_and_registrations : active_registrations_) { const int64_t service_worker_id = sw_id_and_registrations.first; for (auto& key_and_registration : sw_id_and_registrations.second.registration_map) { BackgroundSyncRegistration* registration = &key_and_registration.second; if (IsRegistrationReadyToFire(*registration, service_worker_id)) { sw_id_and_tags_to_fire.push_back( std::make_pair(service_worker_id, key_and_registration.first)); // The state change is not saved to persistent storage because // if the sync event is killed mid-sync then it should return to // SYNC_STATE_PENDING. registration->set_sync_state(blink::mojom::BackgroundSyncState::FIRING); } } } if (sw_id_and_tags_to_fire.empty()) { RunInBackgroundIfNecessary(); base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, std::move(callback)); return; } base::TimeTicks start_time = base::TimeTicks::Now(); // Fire the sync event of the ready registrations and run |callback| once // they're all done. base::RepeatingClosure events_fired_barrier_closure = base::BarrierClosure( sw_id_and_tags_to_fire.size(), base::BindOnce(&BackgroundSyncManager::FireReadyEventsAllEventsFiring, weak_ptr_factory_.GetWeakPtr(), std::move(callback))); // Record the total time taken after all events have run to completion. base::RepeatingClosure events_completed_barrier_closure = base::BarrierClosure(sw_id_and_tags_to_fire.size(), base::BindOnce(&OnAllSyncEventsCompleted, start_time, sw_id_and_tags_to_fire.size())); for (const auto& sw_id_and_tag : sw_id_and_tags_to_fire) { int64_t service_worker_id = sw_id_and_tag.first; const BackgroundSyncRegistration* registration = LookupActiveRegistration(service_worker_id, sw_id_and_tag.second); DCHECK(registration); service_worker_context_->FindReadyRegistrationForId( service_worker_id, active_registrations_[service_worker_id].origin, base::BindOnce( &BackgroundSyncManager::FireReadyEventsDidFindRegistration, weak_ptr_factory_.GetWeakPtr(), sw_id_and_tag.second, registration->id(), events_fired_barrier_closure, events_completed_barrier_closure)); } } void BackgroundSyncManager::FireReadyEventsDidFindRegistration( const std::string& tag, BackgroundSyncRegistration::RegistrationId registration_id, base::OnceClosure event_fired_callback, base::OnceClosure event_completed_callback, ServiceWorkerStatusCode service_worker_status, scoped_refptr<ServiceWorkerRegistration> service_worker_registration) { DCHECK_CURRENTLY_ON(BrowserThread::IO); if (service_worker_status != SERVICE_WORKER_OK) { base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, std::move(event_fired_callback)); base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, std::move(event_completed_callback)); return; } BackgroundSyncRegistration* registration = LookupActiveRegistration(service_worker_registration->id(), tag); DCHECK(registration); num_firing_registrations_ += 1; const bool last_chance = registration->num_attempts() == parameters_->max_sync_attempts - 1; HasMainFrameProviderHost( service_worker_registration->pattern().GetOrigin(), base::BindOnce(&BackgroundSyncMetrics::RecordEventStarted)); DispatchSyncEvent(registration->options()->tag, service_worker_registration->active_version(), last_chance, base::BindOnce(&BackgroundSyncManager::EventComplete, weak_ptr_factory_.GetWeakPtr(), service_worker_registration, service_worker_registration->id(), tag, std::move(event_completed_callback))); base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, std::move(event_fired_callback)); } void BackgroundSyncManager::FireReadyEventsAllEventsFiring( base::OnceClosure callback) { DCHECK_CURRENTLY_ON(BrowserThread::IO); RunInBackgroundIfNecessary(); base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, std::move(callback)); } // |service_worker_registration| is just to keep the registration alive // while the event is firing. void BackgroundSyncManager::EventComplete( scoped_refptr<ServiceWorkerRegistration> service_worker_registration, int64_t service_worker_id, const std::string& tag, base::OnceClosure callback, ServiceWorkerStatusCode status_code) { DCHECK_CURRENTLY_ON(BrowserThread::IO); if (disabled_) { base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, std::move(callback)); return; } op_scheduler_.ScheduleOperation(base::BindOnce( &BackgroundSyncManager::EventCompleteImpl, weak_ptr_factory_.GetWeakPtr(), service_worker_id, tag, status_code, op_scheduler_.WrapCallbackToRunNext(std::move(callback)))); } void BackgroundSyncManager::EventCompleteImpl( int64_t service_worker_id, const std::string& tag, ServiceWorkerStatusCode status_code, base::OnceClosure callback) { DCHECK_CURRENTLY_ON(BrowserThread::IO); if (disabled_) { base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, std::move(callback)); return; } num_firing_registrations_ -= 1; BackgroundSyncRegistration* registration = LookupActiveRegistration(service_worker_id, tag); if (!registration) { base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, std::move(callback)); return; } DCHECK_NE(blink::mojom::BackgroundSyncState::PENDING, registration->sync_state()); registration->set_num_attempts(registration->num_attempts() + 1); // The event ran to completion, we should count it, no matter what happens // from here. ServiceWorkerRegistration* sw_registration = service_worker_context_->GetLiveRegistration(service_worker_id); if (sw_registration) { HasMainFrameProviderHost( sw_registration->pattern().GetOrigin(), base::BindOnce(&BackgroundSyncMetrics::RecordEventResult, status_code == SERVICE_WORKER_OK)); } bool registration_completed = true; bool can_retry = registration->num_attempts() < parameters_->max_sync_attempts; if (registration->sync_state() == blink::mojom::BackgroundSyncState::REREGISTERED_WHILE_FIRING) { registration->set_sync_state(blink::mojom::BackgroundSyncState::PENDING); registration->set_num_attempts(0); registration_completed = false; } else if (status_code != SERVICE_WORKER_OK && can_retry) { // Sync failed but can retry registration->set_sync_state(blink::mojom::BackgroundSyncState::PENDING); registration->set_delay_until(clock_->Now() + parameters_->initial_retry_delay * pow(parameters_->retry_delay_factor, registration->num_attempts() - 1)); registration_completed = false; } if (registration_completed) { const std::string& registration_tag = registration->options()->tag; BackgroundSyncRegistration* active_registration = LookupActiveRegistration(service_worker_id, registration_tag); if (active_registration && active_registration->id() == registration->id()) { RemoveActiveRegistration(service_worker_id, registration_tag); } } StoreRegistrations( service_worker_id, base::BindOnce(&BackgroundSyncManager::EventCompleteDidStore, weak_ptr_factory_.GetWeakPtr(), service_worker_id, std::move(callback))); } void BackgroundSyncManager::EventCompleteDidStore( int64_t service_worker_id, base::OnceClosure callback, ServiceWorkerStatusCode status_code) { DCHECK_CURRENTLY_ON(BrowserThread::IO); if (status_code == SERVICE_WORKER_ERROR_NOT_FOUND) { // The registration is gone. active_registrations_.erase(service_worker_id); base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, std::move(callback)); return; } if (status_code != SERVICE_WORKER_OK) { LOG(ERROR) << "BackgroundSync failed to store registration due to backend " "failure."; DisableAndClearManager(std::move(callback)); return; } // Fire any ready events and call RunInBackground if anything is waiting. FireReadyEvents(); base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, std::move(callback)); } // static void BackgroundSyncManager::OnAllSyncEventsCompleted( const base::TimeTicks& start_time, int number_of_batched_sync_events) { // Record the combined time taken by all sync events. BackgroundSyncMetrics::RecordBatchSyncEventComplete( base::TimeTicks::Now() - start_time, number_of_batched_sync_events); } void BackgroundSyncManager::OnRegistrationDeletedImpl( int64_t sw_registration_id, base::OnceClosure callback) { DCHECK_CURRENTLY_ON(BrowserThread::IO); // The backend (ServiceWorkerStorage) will delete the data, so just delete the // memory representation here. active_registrations_.erase(sw_registration_id); base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, std::move(callback)); } void BackgroundSyncManager::OnStorageWipedImpl(base::OnceClosure callback) { DCHECK_CURRENTLY_ON(BrowserThread::IO); active_registrations_.clear(); disabled_ = false; InitImpl(std::move(callback)); } void BackgroundSyncManager::OnNetworkChanged() { DCHECK_CURRENTLY_ON(BrowserThread::IO); FireReadyEvents(); } void BackgroundSyncManager::SetMaxSyncAttemptsImpl(int max_attempts, base::OnceClosure callback) { DCHECK_CURRENTLY_ON(BrowserThread::IO); parameters_->max_sync_attempts = max_attempts; base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, std::move(callback)); } base::OnceClosure BackgroundSyncManager::MakeEmptyCompletion() { DCHECK_CURRENTLY_ON(BrowserThread::IO); return op_scheduler_.WrapCallbackToRunNext(base::DoNothing::Once()); } ServiceWorkerStatusCode BackgroundSyncManager::CanEmulateSyncEvent( scoped_refptr<ServiceWorkerVersion> active_version) { if (!active_version) return SERVICE_WORKER_ERROR_FAILED; if (!network_observer_->NetworkSufficient(NETWORK_STATE_ONLINE)) return SERVICE_WORKER_ERROR_NETWORK; int64_t registration_id = active_version->registration_id(); if (base::ContainsKey(emulated_offline_sw_, registration_id)) return SERVICE_WORKER_ERROR_NETWORK; return SERVICE_WORKER_OK; } } // namespace content
// MIT License // Copyright (c) 2021 Daniel Kowalczyk // 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 "PricerSolverArcTimeDP.hpp" #include <limits> // for numeric_limits #include <range/v3/algorithm/find.hpp> // for find #include <range/v3/view/filter.hpp> // for filter #include <range/v3/view/reverse.hpp> // for reverse_fn, revers... #include <range/v3/view/take.hpp> // for take #include <range/v3/view/zip.hpp> // for zip #include <span> // for span #include <string> // for char_traits, opera... #include <vector> // for vector, vector<>::... #include "Column.h" // for Column #include "Instance.h" // for Instance #include "PricerSolverBase.hpp" // for PricerSolverBase #include "gurobi_c++.h" // for GRBLinExpr, GRBModel #include "gurobi_c.h" // for GRB_EQUAL, GRB_BINARY using ranges::to_vector; PricerSolverArcTimeDp::PricerSolverArcTimeDp(const Instance& instance) : PricerSolverBase(instance), Hmax(instance.H_max), n(instance.nb_jobs), size_graph(0U), vector_jobs(instance.jobs | ranges::views::transform([](const auto& tmp) { return tmp.get(); }) | to_vector), nb_edges_removed{}, lp_x((n + 1) * (n + 1) * (Hmax + 1), 0.0), solution_x((n + 1) * (n + 1) * (Hmax + 1), 0.0) { // for (auto i : ranges::views::ints(0UL, n)) {V // vector_jobs.push_back((jobs)[i].get()); // } j0.job = n; vector_jobs.push_back(&j0); init_table(); } void PricerSolverArcTimeDp::init_table() { graph = vector3d_jobs(n + 1); reversed_graph = vector3d_jobs(n + 1); for (auto j = 0UL; j < n + 1; j++) { reversed_graph[j] = vector2d_jobs(Hmax + 1); } forward_F = vector2d_dbl(convex_constr_id + 1); backward_F = vector2d_dbl(convex_constr_id + 1); for (unsigned i = 0; i < convex_constr_id + 1; ++i) { forward_F[i] = vector1d_dbl(Hmax + 1, 0.0); backward_F[i] = vector1d_dbl(Hmax + 1, 0.0); } A = vector2d_jobs(convex_constr_id + 1); for (unsigned i = 0; i < convex_constr_id + 1; ++i) { A[i] = vector1d_jobs(Hmax + 1, nullptr); } B = vector2d_int(convex_constr_id + 1); for (unsigned i = 0; i < convex_constr_id + 1; ++i) { B[i] = vector1d_int(Hmax + 1); } arctime_x = vector_grb_var(convex_constr_id + 1); for (auto i = 0UL; i < n + 1; i++) { arctime_x[i] = vector2d_grb_var(convex_constr_id + 1); for (auto j = 0UL; j < n + 1; j++) { arctime_x[i][j] = vector1d_grb_var(Hmax + 1); } } for (auto j = 0UL; j < n; ++j) { graph[j] = vector2d_jobs(Hmax + 1); Job* tmp = jobs[j].get(); for (auto t : ranges::views::ints(size_t{}, Hmax + 1)) { for (auto& it : vector_jobs) { int p = (it->job != j) ? it->processing_time : 1; if (it != tmp && static_cast<int>(t) >= p && t + tmp->processing_time <= Hmax) { graph[j][t].push_back(it); ++size_graph; } } } } graph[n] = vector2d_jobs(Hmax + 1); for (auto t : ranges::views::ints(size_t{}, Hmax + 1)) { for (auto& it : vector_jobs) { if (static_cast<int>(t) >= it->processing_time) { graph[n][t].push_back(it); ++size_graph; } } } /** * Remove all not needed arcs from the sets */ for (auto i = 0UL; i < n - 1; ++i) { Job* tmp_i = vector_jobs[i]; for (auto j = i + 1; j < n; ++j) { Job* tmp_j = vector_jobs[j]; for (size_t t = tmp_i->processing_time; t <= Hmax - tmp_j->processing_time; ++t) { if (delta1(i, j, static_cast<int>(t)) >= 0) { remove_arc(i, j, t); size_graph--; } else { remove_arc( j, i, t - tmp_i->processing_time + tmp_j->processing_time); size_graph--; } } } } for (auto j = 0UL; j < n; ++j) { Job* tmp_j = vector_jobs[j]; for (auto t : ranges::views::ints( static_cast<size_t>(tmp_j->processing_time), Hmax)) { if (delta2(j, t) <= 0) { remove_arc(n, j, t - tmp_j->processing_time + 1); --size_graph; } else { remove_arc(j, n, t); --size_graph; } } } for (auto j = 0UL; j < n + 1; ++j) { Job* tmp = vector_jobs[j]; for (auto t : ranges::views::ints(size_t{}, Hmax + 1)) { if (graph[j][t].empty()) { forward_F[j][t] = std::numeric_limits<double>::max() / 2; } else { for (auto& it : graph[j][t]) { reversed_graph[it->job][t].push_back(tmp); } } } } for (auto j = 0UL; j < n + 1; j++) { for (auto t : ranges::views::ints(size_t{}, Hmax + 1)) { if (reversed_graph[j][t].empty()) { backward_F[j][t] = std::numeric_limits<double>::max() / 2; } } } fmt::print("Number of arcs in ATI formulation = {}\n", size_graph); } auto PricerSolverArcTimeDp::evaluate_nodes( [[maybe_unused]] std::span<const double>& pi) -> bool { forward_evaluator(pi); backward_evaluator(pi); auto num_edges_removed = 0; for (auto* tmp : vector_jobs | ranges::views::take(n)) { for (auto t = size_t{}; t <= Hmax - tmp->processing_time; t++) { auto it = graph[tmp->job][t].begin(); while (it != graph[tmp->job][t].end()) { double result = forward_F[(*it)->job][t - (*it)->processing_time] + tmp->weighted_tardiness_start(t) - pi[tmp->job] + backward_F[tmp->job][t + tmp->processing_time]; if (result + static_cast<double>(convex_rhs - 1) * (forward_F[n][Hmax]) + constLB > UB - 1.0 + RC_FIXING) { size_graph--; num_edges_removed++; auto pend = ranges::find(reversed_graph[(*it)->job][t], tmp); reversed_graph[(*it)->job][t].erase(pend); it = graph[tmp->job][t].erase(it); } else { it++; } } } } return (num_edges_removed > 0); } void PricerSolverArcTimeDp::build_mip() { fmt::print("Building Mip model for the arcTI formulation\n"); /** Constructing variables */ for (auto j = size_t{}; j < n + 1; j++) { for (auto t = size_t{}; t + vector_jobs[j]->processing_time <= Hmax; t++) { for (auto& it : graph[j][t]) { double cost = vector_jobs[j]->weighted_tardiness_start( static_cast<int>(t)); double tmp = (it->job == vector_jobs[j]->job) ? static_cast<double>(convex_rhs) : 1.0; auto s = (it->job == vector_jobs[j]->job) ? GRB_INTEGER : GRB_BINARY; arctime_x[it->job][j][t] = model.addVar(0.0, tmp, cost, s); } } } model.update(); /** Assignment variables */ std::vector<GRBLinExpr> assignment(convex_constr_id, GRBLinExpr()); std::vector<char> sense(convex_constr_id, GRB_GREATER_EQUAL); std::vector<double> rhs(convex_constr_id, 1.0); for (auto j = size_t{}; j < n; j++) { for (auto t = size_t{}; t <= Hmax - vector_jobs[j]->processing_time; t++) { for (auto& it : graph[j][t]) { assignment[j] += arctime_x[it->job][j][t]; } } } std::unique_ptr<GRBConstr> assignment_constrs( model.addConstrs(assignment.data(), sense.data(), rhs.data(), nullptr, static_cast<int>(convex_constr_id))); for (auto i = 0UL; i < n; i++) { for (auto t = 0UL; t <= Hmax - vector_jobs[i]->processing_time; t++) { GRBLinExpr expr{}; for (auto& it : graph[i][t]) { expr += arctime_x[it->job][i][t]; } for (auto& it : reversed_graph[i][t + vector_jobs[i]->processing_time]) { expr -= arctime_x[i][it->job][t + vector_jobs[i]->processing_time]; } model.addConstr(expr, GRB_EQUAL, 0); } } for (auto t : ranges::views::ints(size_t{}, Hmax)) { GRBLinExpr expr{}; for (auto& it : graph[n][t]) { expr += arctime_x[it->job][n][t]; } for (auto& it : reversed_graph[n][t + 1]) { expr -= arctime_x[n][it->job][t + 1]; } model.addConstr(expr, GRB_EQUAL, 0); } GRBLinExpr expr{}; for (auto& it : reversed_graph[n][0]) { expr += arctime_x[n][it->job][0]; } model.addConstr(expr, GRB_EQUAL, static_cast<double>(convex_rhs)); for (auto j = 0UL; j < n + 1; j++) { for (auto t : ranges::views::ints( size_t{}, Hmax - vector_jobs[j]->processing_time + 1)) { for (auto& it : graph[j][t]) { arctime_x[it->job][j][t].set( GRB_DoubleAttr_Start, solution_x[(it->job) * (Hmax + 1) * (n + 1) + j * (Hmax + 1) + t]); arctime_x[it->job][j][t].set( GRB_DoubleAttr_PStart, lp_x[(it->job) * (Hmax + 1) * (n + 1) + j * (Hmax + 1) + t]); } } } model.write("ati_" + problem_name + "_" + std::to_string(convex_rhs) + ".lp"); model.optimize(); if (model.get(GRB_IntAttr_Status) == GRB_OPTIMAL) { for (auto j = 0UL; j < n; j++) { for (auto t = 0UL; t <= Hmax - vector_jobs[j]->processing_time; t++) { for (auto& it : graph[j][t]) { auto a = arctime_x[it->job][j][t].get(GRB_DoubleAttr_X); if (a > 0) { fmt::print("{} {} {}\n", j, t, jobs[j]->processing_time); } } } } } } PricerSolverArcTimeDp::~PricerSolverArcTimeDp() = default; void PricerSolverArcTimeDp::backward_evaluator(double* _pi) { // backward_F[n][T] = 0; backward_F[n][Hmax] = 0.0; std::span aux_pi{_pi, reformulation_model.size()}; for (auto t : ranges::views::ints(size_t{}, Hmax) | ranges::views::reverse) { for (auto i = 0UL; i <= n; ++i) { // Job* tmp = vector_jobs[i]; backward_F[i][t] = ((i == n) && (t == Hmax)) ? 0.0 : std::numeric_limits<double>::max() / 2; auto it = reversed_graph[i][t].begin(); if (!reversed_graph[i][t].empty() && t <= Hmax) { double reduced_cost = ((*it)->job == n) ? (*it)->weighted_tardiness_start(t) : (*it)->weighted_tardiness_start(t) - aux_pi[(*it)->job]; int tt = ((*it)->job != n) ? (*it)->processing_time : (*it)->job == i ? 1 : 0; backward_F[i][t] = backward_F[(*it)->job][t + tt] + reduced_cost; it++; while (it != reversed_graph[i][t].end()) { reduced_cost = ((*it)->job == n) ? (*it)->weighted_tardiness_start(t) : (*it)->weighted_tardiness_start(t) - aux_pi[(*it)->job]; tt = ((*it)->job != n) ? (*it)->processing_time : (*it)->job == i ? 1 : 0; double result = backward_F[(*it)->job][t + tt] + reduced_cost; if (backward_F[i][t] >= result) { backward_F[i][t] = result; } it++; } } else { backward_F[i][t] = std::numeric_limits<double>::max() / 2; } } } } void PricerSolverArcTimeDp::backward_evaluator(std::span<const double>& _pi) { // backward_F[n][T] = 0; backward_F[n][Hmax] = 0.0; for (auto t : ranges::views::ints(size_t{}, Hmax) | ranges::views::reverse) { for (auto i = 0UL; i <= n; ++i) { // Job* tmp = vector_jobs[i]; backward_F[i][t] = ((i == n) && (t == Hmax)) ? 0.0 : std::numeric_limits<double>::max() / 2; auto it = reversed_graph[i][t].begin(); if (!reversed_graph[i][t].empty() && t <= Hmax) { double reduced_cost = ((*it)->job == n) ? (*it)->weighted_tardiness_start(t) : (*it)->weighted_tardiness_start(t) - _pi[(*it)->job]; int tt = ((*it)->job != n) ? (*it)->processing_time : (*it)->job == i ? 1 : 0; backward_F[i][t] = backward_F[(*it)->job][t + tt] + reduced_cost; it++; while (it != reversed_graph[i][t].end()) { reduced_cost = ((*it)->job == n) ? (*it)->weighted_tardiness_start(t) : (*it)->weighted_tardiness_start(t) - _pi[(*it)->job]; tt = ((*it)->job != n) ? (*it)->processing_time : (*it)->job == i ? 1 : 0; double result = backward_F[(*it)->job][t + tt] + reduced_cost; if (backward_F[i][t] >= result) { backward_F[i][t] = result; } it++; } } else { backward_F[i][t] = std::numeric_limits<double>::max() / 2; } } } } void PricerSolverArcTimeDp::forward_evaluator(double* _pi) { forward_F[n][0] = 0; std::span aux_pi{_pi, reformulation_model.size()}; for (auto t : ranges::views::ints(int{}, static_cast<int>(Hmax) + 1)) { for (auto j = 0UL; j <= n; ++j) { Job* tmp = vector_jobs[j]; A[j][t] = nullptr; B[j][t] = -1; forward_F[j][t] = ((j == n) && (t == 0)) ? 0 : std::numeric_limits<double>::max() / 2; auto it = graph[j][t].begin(); if (!graph[j][t].empty() && t <= Hmax - tmp->processing_time) { double reduced_cost = (j == n) ? tmp->weighted_tardiness_start(t) : tmp->weighted_tardiness_start(t) - aux_pi[j]; forward_F[j][t] = forward_F[(*it)->job][t - (*it)->processing_time] + reduced_cost; A[j][t] = (*it); B[j][t] = t - (*it)->processing_time; it++; while (it != graph[j][t].end()) { reduced_cost = (j == n) ? tmp->weighted_tardiness_start(t) : tmp->weighted_tardiness_start(t) - aux_pi[j]; double result = ((*it)->job != vector_jobs[j]->job) ? forward_F[(*it)->job][t - (*it)->processing_time] : forward_F[(*it)->job][t - 1]; result += reduced_cost; if (forward_F[j][t] >= result) { forward_F[j][t] = result; A[j][t] = (*it); B[j][t] = ((*it)->job != vector_jobs[j]->job) ? t - (*it)->processing_time : t - 1; } it++; } } } } } void PricerSolverArcTimeDp::forward_evaluator(std::span<const double>& _pi) { forward_F[n][0] = 0; for (auto t : ranges::views::ints(int{}, static_cast<int>(Hmax) + 1)) { for (auto j = 0UL; j <= n; ++j) { Job* tmp = vector_jobs[j]; A[j][t] = nullptr; B[j][t] = -1; forward_F[j][t] = ((j == n) && (t == 0)) ? 0 : std::numeric_limits<double>::max() / 2; auto it = graph[j][t].begin(); if (!graph[j][t].empty() && t <= Hmax - tmp->processing_time) { double reduced_cost = (j == n) ? tmp->weighted_tardiness_start(t) : tmp->weighted_tardiness_start(t) - _pi[j]; forward_F[j][t] = forward_F[(*it)->job][t - (*it)->processing_time] + reduced_cost; A[j][t] = (*it); B[j][t] = t - (*it)->processing_time; it++; while (it != graph[j][t].end()) { reduced_cost = (j == n) ? tmp->weighted_tardiness_start(t) : tmp->weighted_tardiness_start(t) - _pi[j]; double result = ((*it)->job != vector_jobs[j]->job) ? forward_F[(*it)->job][t - (*it)->processing_time] : forward_F[(*it)->job][t - 1]; result += reduced_cost; if (forward_F[j][t] >= result) { forward_F[j][t] = result; A[j][t] = (*it); B[j][t] = ((*it)->job != vector_jobs[j]->job) ? t - (*it)->processing_time : t - 1; } it++; } } } } } auto PricerSolverArcTimeDp::pricing_algorithm(std::span<const double>& _pi) -> PricingSolution { PricingSolution sol(_pi[n]); std::vector<Job*> v; forward_evaluator(_pi); auto job = n; auto T = Hmax; while (T > 0) { auto aux_job = A[job][T]->job; int aux_T = B[job][T]; if (aux_job != n) { v.push_back(vector_jobs[aux_job]); sol.C_max += vector_jobs[aux_job]->processing_time; sol.cost += vector_jobs[aux_job]->weighted_tardiness_start(aux_T); sol.obj += vector_jobs[aux_job]->weighted_tardiness_start(aux_T) - _pi[aux_job]; } job = aux_job; T = aux_T; } sol.C_max = 0; for (auto& it : v | ranges::views::reverse) { sol.jobs.push_back(it); } return sol; } auto PricerSolverArcTimeDp::farkas_pricing( [[maybe_unused]] std::span<const double>& _pi) -> PricingSolution { PricingSolution opt_sol; return opt_sol; } void PricerSolverArcTimeDp::construct_lp_sol_from_rmp( const std::span<const double>& lambda, const std::vector<std::shared_ptr<Column>>& columns) { std::fill(lp_x.begin(), lp_x.end(), 0.0); auto positive = [](const auto& tmp) { return (tmp.first > 0.0); }; for (auto&& [x, col] : ranges::views::zip(lambda, columns) | ranges::views::filter(positive)) { auto counter = 0UL; auto i = n; auto t = 0UL; while (t < Hmax + 1) { Job* tmp_j = nullptr; auto j = n; if (counter < col->job_list.size()) { tmp_j = col->job_list[counter]; j = tmp_j->job; } lp_x[i * (n + 1) * (Hmax + 1) + j * (Hmax + 1) + t] += x; if (tmp_j == nullptr) { i = n; t += 1; } else { i = j; t += tmp_j->processing_time; counter++; } } } } auto PricerSolverArcTimeDp::get_nb_edges() -> size_t { auto nb_edges = size_t{}; for (auto& it : graph) { for (auto& it_in : it) { nb_edges += it_in.size(); } } return nb_edges; } auto PricerSolverArcTimeDp::get_nb_vertices() -> size_t { size_t nb_vertices = 0U; for (auto& it : graph) { for (auto& it_in : it) { if (!it_in.empty()) { nb_vertices++; } } } return nb_vertices; } auto PricerSolverArcTimeDp::print_num_paths() -> boost::multiprecision::cpp_int { return 0; } auto PricerSolverArcTimeDp::check_column(Column const* col) -> bool { // std::span aux_set{set->pdata, set->len}; const auto& set = col->job_list; auto counter = set.size() - 1; auto i = n; auto t = 0UL; while (t < Hmax + 1) { Job* tmp_j = nullptr; auto j = n; if (counter < set.size()) { j = set[counter]->job; } if (std::find(graph[j][t].begin(), graph[j][t].end(), vector_jobs[i]) == graph[j][t].end()) { return true; } if (tmp_j == nullptr) { i = n; t += 1; } else { i = j; t += tmp_j->processing_time; counter--; } } return false; }
// Copyright (c) 2011-2014 The Bitcoin developers // Copyright (c) 2014-2015 The Dash developers // Copyright (c) 2015-2017 The DARKCOIN developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "clientmodel.h" #include "guiconstants.h" #include "peertablemodel.h" #include "alert.h" #include "chainparams.h" #include "checkpoints.h" #include "clientversion.h" #include "main.h" #include "masternode-sync.h" #include "masternodeman.h" #include "net.h" #include "ui_interface.h" #include "util.h" #include <stdint.h> #include <QDateTime> #include <QDebug> #include <QTimer> static const int64_t nClientStartupTime = GetTime(); ClientModel::ClientModel(OptionsModel* optionsModel, QObject* parent) : QObject(parent), optionsModel(optionsModel), peerTableModel(0), cachedNumBlocks(0), cachedMasternodeCountString(""), cachedReindexing(0), cachedImporting(0), numBlocksAtStartup(-1), pollTimer(0) { peerTableModel = new PeerTableModel(this); pollTimer = new QTimer(this); connect(pollTimer, SIGNAL(timeout()), this, SLOT(updateTimer())); pollTimer->start(MODEL_UPDATE_DELAY); pollMnTimer = new QTimer(this); connect(pollMnTimer, SIGNAL(timeout()), this, SLOT(updateMnTimer())); // no need to update as frequent as data for balances/txes/blocks pollMnTimer->start(MODEL_UPDATE_DELAY * 4); subscribeToCoreSignals(); } ClientModel::~ClientModel() { unsubscribeFromCoreSignals(); } int ClientModel::getNumConnections(unsigned int flags) const { LOCK(cs_vNodes); if (flags == CONNECTIONS_ALL) // Shortcut if we want total return vNodes.size(); int nNum = 0; BOOST_FOREACH (CNode* pnode, vNodes) if (flags & (pnode->fInbound ? CONNECTIONS_IN : CONNECTIONS_OUT)) nNum++; return nNum; } QString ClientModel::getMasternodeCountString() const { int ipv4 = 0, ipv6 = 0, onion = 0; mnodeman.CountNetworks(ActiveProtocol(), ipv4, ipv6, onion); int nUnknown = mnodeman.size() - ipv4 - ipv6 - onion; if(nUnknown < 0) nUnknown = 0; return tr("Total: %1 (IPv4: %2 / IPv6: %3 / Tor: %4 / Unknown: %5)").arg(QString::number((int)mnodeman.size())).arg(QString::number((int)ipv4)).arg(QString::number((int)ipv6)).arg(QString::number((int)onion)).arg(QString::number((int)nUnknown)); } int ClientModel::getNumBlocks() const { LOCK(cs_main); return chainActive.Height(); } int ClientModel::getNumBlocksAtStartup() { if (numBlocksAtStartup == -1) numBlocksAtStartup = getNumBlocks(); return numBlocksAtStartup; } quint64 ClientModel::getTotalBytesRecv() const { return CNode::GetTotalBytesRecv(); } quint64 ClientModel::getTotalBytesSent() const { return CNode::GetTotalBytesSent(); } QDateTime ClientModel::getLastBlockDate() const { LOCK(cs_main); if (chainActive.Tip()) return QDateTime::fromTime_t(chainActive.Tip()->GetBlockTime()); else return QDateTime::fromTime_t(Params().GenesisBlock().GetBlockTime()); // Genesis block's time of current network } double ClientModel::getVerificationProgress() const { LOCK(cs_main); return Checkpoints::GuessVerificationProgress(chainActive.Tip()); } void ClientModel::updateTimer() { // Get required lock upfront. This avoids the GUI from getting stuck on // periodical polls if the core is holding the locks for a longer time - // for example, during a wallet rescan. TRY_LOCK(cs_main, lockMain); if (!lockMain) return; // Some quantities (such as number of blocks) change so fast that we don't want to be notified for each change. // Periodically check and update with a timer. int newNumBlocks = getNumBlocks(); static int prevAttempt = -1; static int prevAssets = -1; // check for changed number of blocks we have, number of blocks peers claim to have, reindexing state and importing state if (cachedNumBlocks != newNumBlocks || cachedReindexing != fReindex || cachedImporting != fImporting || masternodeSync.RequestedMasternodeAttempt != prevAttempt || masternodeSync.RequestedMasternodeAssets != prevAssets) { cachedNumBlocks = newNumBlocks; cachedReindexing = fReindex; cachedImporting = fImporting; prevAttempt = masternodeSync.RequestedMasternodeAttempt; prevAssets = masternodeSync.RequestedMasternodeAssets; emit numBlocksChanged(newNumBlocks); } emit bytesChanged(getTotalBytesRecv(), getTotalBytesSent()); } void ClientModel::updateMnTimer() { // Get required lock upfront. This avoids the GUI from getting stuck on // periodical polls if the core is holding the locks for a longer time - // for example, during a wallet rescan. TRY_LOCK(cs_main, lockMain); if (!lockMain) return; QString newMasternodeCountString = getMasternodeCountString(); if (cachedMasternodeCountString != newMasternodeCountString) { cachedMasternodeCountString = newMasternodeCountString; emit strMasternodesChanged(cachedMasternodeCountString); } } void ClientModel::updateNumConnections(int numConnections) { emit numConnectionsChanged(numConnections); } void ClientModel::updateAlert(const QString& hash, int status) { // Show error message notification for new alert if (status == CT_NEW) { uint256 hash_256; hash_256.SetHex(hash.toStdString()); CAlert alert = CAlert::getAlertByHash(hash_256); if (!alert.IsNull()) { emit message(tr("Network Alert"), QString::fromStdString(alert.strStatusBar), CClientUIInterface::ICON_ERROR); } } emit alertsChanged(getStatusBarWarnings()); } bool ClientModel::inInitialBlockDownload() const { return IsInitialBlockDownload(); } enum BlockSource ClientModel::getBlockSource() const { if (fReindex) return BLOCK_SOURCE_REINDEX; else if (fImporting) return BLOCK_SOURCE_DISK; else if (getNumConnections() > 0) return BLOCK_SOURCE_NETWORK; return BLOCK_SOURCE_NONE; } QString ClientModel::getStatusBarWarnings() const { return QString::fromStdString(GetWarnings("statusbar")); } OptionsModel* ClientModel::getOptionsModel() { return optionsModel; } PeerTableModel* ClientModel::getPeerTableModel() { return peerTableModel; } QString ClientModel::formatFullVersion() const { return QString::fromStdString(FormatFullVersion()); } QString ClientModel::formatBuildDate() const { return QString::fromStdString(CLIENT_DATE); } bool ClientModel::isReleaseVersion() const { return CLIENT_VERSION_IS_RELEASE; } QString ClientModel::clientName() const { return QString::fromStdString(CLIENT_NAME); } QString ClientModel::formatClientStartupTime() const { return QDateTime::fromTime_t(nClientStartupTime).toString(); } // Handlers for core signals static void ShowProgress(ClientModel* clientmodel, const std::string& title, int nProgress) { // emits signal "showProgress" QMetaObject::invokeMethod(clientmodel, "showProgress", Qt::QueuedConnection, Q_ARG(QString, QString::fromStdString(title)), Q_ARG(int, nProgress)); } static void NotifyNumConnectionsChanged(ClientModel* clientmodel, int newNumConnections) { // Too noisy: qDebug() << "NotifyNumConnectionsChanged : " + QString::number(newNumConnections); QMetaObject::invokeMethod(clientmodel, "updateNumConnections", Qt::QueuedConnection, Q_ARG(int, newNumConnections)); } static void NotifyAlertChanged(ClientModel* clientmodel, const uint256& hash, ChangeType status) { qDebug() << "NotifyAlertChanged : " + QString::fromStdString(hash.GetHex()) + " status=" + QString::number(status); QMetaObject::invokeMethod(clientmodel, "updateAlert", Qt::QueuedConnection, Q_ARG(QString, QString::fromStdString(hash.GetHex())), Q_ARG(int, status)); } void ClientModel::subscribeToCoreSignals() { // Connect signals to client uiInterface.ShowProgress.connect(boost::bind(ShowProgress, this, _1, _2)); uiInterface.NotifyNumConnectionsChanged.connect(boost::bind(NotifyNumConnectionsChanged, this, _1)); uiInterface.NotifyAlertChanged.connect(boost::bind(NotifyAlertChanged, this, _1, _2)); } void ClientModel::unsubscribeFromCoreSignals() { // Disconnect signals from client uiInterface.ShowProgress.disconnect(boost::bind(ShowProgress, this, _1, _2)); uiInterface.NotifyNumConnectionsChanged.disconnect(boost::bind(NotifyNumConnectionsChanged, this, _1)); uiInterface.NotifyAlertChanged.disconnect(boost::bind(NotifyAlertChanged, this, _1, _2)); }
/*================================================================================ code generated by: java2cpp author: Zoran Angelov, mailto://baldzar@gmail.com class: java.util.Date ================================================================================*/ #ifndef J2CPP_INCLUDE_IMPLEMENTATION #ifndef J2CPP_JAVA_UTIL_DATE_HPP_DECL #define J2CPP_JAVA_UTIL_DATE_HPP_DECL namespace j2cpp { namespace java { namespace io { class Serializable; } } } namespace j2cpp { namespace java { namespace lang { class Object; } } } namespace j2cpp { namespace java { namespace lang { class Comparable; } } } namespace j2cpp { namespace java { namespace lang { class Cloneable; } } } namespace j2cpp { namespace java { namespace lang { class String; } } } #include <java/io/Serializable.hpp> #include <java/lang/Cloneable.hpp> #include <java/lang/Comparable.hpp> #include <java/lang/Object.hpp> #include <java/lang/String.hpp> namespace j2cpp { namespace java { namespace util { class Date; class Date : public object<Date> { public: J2CPP_DECLARE_CLASS J2CPP_DECLARE_METHOD(0) J2CPP_DECLARE_METHOD(1) J2CPP_DECLARE_METHOD(2) J2CPP_DECLARE_METHOD(3) J2CPP_DECLARE_METHOD(4) J2CPP_DECLARE_METHOD(5) J2CPP_DECLARE_METHOD(6) J2CPP_DECLARE_METHOD(7) J2CPP_DECLARE_METHOD(8) J2CPP_DECLARE_METHOD(9) J2CPP_DECLARE_METHOD(10) J2CPP_DECLARE_METHOD(11) J2CPP_DECLARE_METHOD(12) J2CPP_DECLARE_METHOD(13) J2CPP_DECLARE_METHOD(14) J2CPP_DECLARE_METHOD(15) J2CPP_DECLARE_METHOD(16) J2CPP_DECLARE_METHOD(17) J2CPP_DECLARE_METHOD(18) J2CPP_DECLARE_METHOD(19) J2CPP_DECLARE_METHOD(20) J2CPP_DECLARE_METHOD(21) J2CPP_DECLARE_METHOD(22) J2CPP_DECLARE_METHOD(23) J2CPP_DECLARE_METHOD(24) J2CPP_DECLARE_METHOD(25) J2CPP_DECLARE_METHOD(26) J2CPP_DECLARE_METHOD(27) J2CPP_DECLARE_METHOD(28) J2CPP_DECLARE_METHOD(29) J2CPP_DECLARE_METHOD(30) J2CPP_DECLARE_METHOD(31) J2CPP_DECLARE_METHOD(32) J2CPP_DECLARE_METHOD(33) explicit Date(jobject jobj) : object<Date>(jobj) { } operator local_ref<java::lang::Object>() const; operator local_ref<java::io::Serializable>() const; operator local_ref<java::lang::Cloneable>() const; operator local_ref<java::lang::Comparable>() const; Date(); Date(jint, jint, jint); Date(jint, jint, jint, jint, jint); Date(jint, jint, jint, jint, jint, jint); Date(jlong); Date(local_ref< java::lang::String > const&); jboolean after(local_ref< java::util::Date > const&); jboolean before(local_ref< java::util::Date > const&); local_ref< java::lang::Object > clone(); jint compareTo(local_ref< java::util::Date > const&); jboolean equals(local_ref< java::lang::Object > const&); jint getDate(); jint getDay(); jint getHours(); jint getMinutes(); jint getMonth(); jint getSeconds(); jlong getTime(); jint getTimezoneOffset(); jint getYear(); jint hashCode(); static jlong parse(local_ref< java::lang::String > const&); void setDate(jint); void setHours(jint); void setMinutes(jint); void setMonth(jint); void setSeconds(jint); void setTime(jlong); void setYear(jint); local_ref< java::lang::String > toGMTString(); local_ref< java::lang::String > toLocaleString(); local_ref< java::lang::String > toString(); static jlong UTC(jint, jint, jint, jint, jint, jint); jint compareTo(local_ref< java::lang::Object > const&); }; //class Date } //namespace util } //namespace java } //namespace j2cpp #endif //J2CPP_JAVA_UTIL_DATE_HPP_DECL #else //J2CPP_INCLUDE_IMPLEMENTATION #ifndef J2CPP_JAVA_UTIL_DATE_HPP_IMPL #define J2CPP_JAVA_UTIL_DATE_HPP_IMPL namespace j2cpp { java::util::Date::operator local_ref<java::lang::Object>() const { return local_ref<java::lang::Object>(get_jobject()); } java::util::Date::operator local_ref<java::io::Serializable>() const { return local_ref<java::io::Serializable>(get_jobject()); } java::util::Date::operator local_ref<java::lang::Cloneable>() const { return local_ref<java::lang::Cloneable>(get_jobject()); } java::util::Date::operator local_ref<java::lang::Comparable>() const { return local_ref<java::lang::Comparable>(get_jobject()); } java::util::Date::Date() : object<java::util::Date>( call_new_object< java::util::Date::J2CPP_CLASS_NAME, java::util::Date::J2CPP_METHOD_NAME(0), java::util::Date::J2CPP_METHOD_SIGNATURE(0) >() ) { } java::util::Date::Date(jint a0, jint a1, jint a2) : object<java::util::Date>( call_new_object< java::util::Date::J2CPP_CLASS_NAME, java::util::Date::J2CPP_METHOD_NAME(1), java::util::Date::J2CPP_METHOD_SIGNATURE(1) >(a0, a1, a2) ) { } java::util::Date::Date(jint a0, jint a1, jint a2, jint a3, jint a4) : object<java::util::Date>( call_new_object< java::util::Date::J2CPP_CLASS_NAME, java::util::Date::J2CPP_METHOD_NAME(2), java::util::Date::J2CPP_METHOD_SIGNATURE(2) >(a0, a1, a2, a3, a4) ) { } java::util::Date::Date(jint a0, jint a1, jint a2, jint a3, jint a4, jint a5) : object<java::util::Date>( call_new_object< java::util::Date::J2CPP_CLASS_NAME, java::util::Date::J2CPP_METHOD_NAME(3), java::util::Date::J2CPP_METHOD_SIGNATURE(3) >(a0, a1, a2, a3, a4, a5) ) { } java::util::Date::Date(jlong a0) : object<java::util::Date>( call_new_object< java::util::Date::J2CPP_CLASS_NAME, java::util::Date::J2CPP_METHOD_NAME(4), java::util::Date::J2CPP_METHOD_SIGNATURE(4) >(a0) ) { } java::util::Date::Date(local_ref< java::lang::String > const &a0) : object<java::util::Date>( call_new_object< java::util::Date::J2CPP_CLASS_NAME, java::util::Date::J2CPP_METHOD_NAME(5), java::util::Date::J2CPP_METHOD_SIGNATURE(5) >(a0) ) { } jboolean java::util::Date::after(local_ref< java::util::Date > const &a0) { return call_method< java::util::Date::J2CPP_CLASS_NAME, java::util::Date::J2CPP_METHOD_NAME(6), java::util::Date::J2CPP_METHOD_SIGNATURE(6), jboolean >(get_jobject(), a0); } jboolean java::util::Date::before(local_ref< java::util::Date > const &a0) { return call_method< java::util::Date::J2CPP_CLASS_NAME, java::util::Date::J2CPP_METHOD_NAME(7), java::util::Date::J2CPP_METHOD_SIGNATURE(7), jboolean >(get_jobject(), a0); } local_ref< java::lang::Object > java::util::Date::clone() { return call_method< java::util::Date::J2CPP_CLASS_NAME, java::util::Date::J2CPP_METHOD_NAME(8), java::util::Date::J2CPP_METHOD_SIGNATURE(8), local_ref< java::lang::Object > >(get_jobject()); } jint java::util::Date::compareTo(local_ref< java::util::Date > const &a0) { return call_method< java::util::Date::J2CPP_CLASS_NAME, java::util::Date::J2CPP_METHOD_NAME(9), java::util::Date::J2CPP_METHOD_SIGNATURE(9), jint >(get_jobject(), a0); } jboolean java::util::Date::equals(local_ref< java::lang::Object > const &a0) { return call_method< java::util::Date::J2CPP_CLASS_NAME, java::util::Date::J2CPP_METHOD_NAME(10), java::util::Date::J2CPP_METHOD_SIGNATURE(10), jboolean >(get_jobject(), a0); } jint java::util::Date::getDate() { return call_method< java::util::Date::J2CPP_CLASS_NAME, java::util::Date::J2CPP_METHOD_NAME(11), java::util::Date::J2CPP_METHOD_SIGNATURE(11), jint >(get_jobject()); } jint java::util::Date::getDay() { return call_method< java::util::Date::J2CPP_CLASS_NAME, java::util::Date::J2CPP_METHOD_NAME(12), java::util::Date::J2CPP_METHOD_SIGNATURE(12), jint >(get_jobject()); } jint java::util::Date::getHours() { return call_method< java::util::Date::J2CPP_CLASS_NAME, java::util::Date::J2CPP_METHOD_NAME(13), java::util::Date::J2CPP_METHOD_SIGNATURE(13), jint >(get_jobject()); } jint java::util::Date::getMinutes() { return call_method< java::util::Date::J2CPP_CLASS_NAME, java::util::Date::J2CPP_METHOD_NAME(14), java::util::Date::J2CPP_METHOD_SIGNATURE(14), jint >(get_jobject()); } jint java::util::Date::getMonth() { return call_method< java::util::Date::J2CPP_CLASS_NAME, java::util::Date::J2CPP_METHOD_NAME(15), java::util::Date::J2CPP_METHOD_SIGNATURE(15), jint >(get_jobject()); } jint java::util::Date::getSeconds() { return call_method< java::util::Date::J2CPP_CLASS_NAME, java::util::Date::J2CPP_METHOD_NAME(16), java::util::Date::J2CPP_METHOD_SIGNATURE(16), jint >(get_jobject()); } jlong java::util::Date::getTime() { return call_method< java::util::Date::J2CPP_CLASS_NAME, java::util::Date::J2CPP_METHOD_NAME(17), java::util::Date::J2CPP_METHOD_SIGNATURE(17), jlong >(get_jobject()); } jint java::util::Date::getTimezoneOffset() { return call_method< java::util::Date::J2CPP_CLASS_NAME, java::util::Date::J2CPP_METHOD_NAME(18), java::util::Date::J2CPP_METHOD_SIGNATURE(18), jint >(get_jobject()); } jint java::util::Date::getYear() { return call_method< java::util::Date::J2CPP_CLASS_NAME, java::util::Date::J2CPP_METHOD_NAME(19), java::util::Date::J2CPP_METHOD_SIGNATURE(19), jint >(get_jobject()); } jint java::util::Date::hashCode() { return call_method< java::util::Date::J2CPP_CLASS_NAME, java::util::Date::J2CPP_METHOD_NAME(20), java::util::Date::J2CPP_METHOD_SIGNATURE(20), jint >(get_jobject()); } jlong java::util::Date::parse(local_ref< java::lang::String > const &a0) { return call_static_method< java::util::Date::J2CPP_CLASS_NAME, java::util::Date::J2CPP_METHOD_NAME(21), java::util::Date::J2CPP_METHOD_SIGNATURE(21), jlong >(a0); } void java::util::Date::setDate(jint a0) { return call_method< java::util::Date::J2CPP_CLASS_NAME, java::util::Date::J2CPP_METHOD_NAME(22), java::util::Date::J2CPP_METHOD_SIGNATURE(22), void >(get_jobject(), a0); } void java::util::Date::setHours(jint a0) { return call_method< java::util::Date::J2CPP_CLASS_NAME, java::util::Date::J2CPP_METHOD_NAME(23), java::util::Date::J2CPP_METHOD_SIGNATURE(23), void >(get_jobject(), a0); } void java::util::Date::setMinutes(jint a0) { return call_method< java::util::Date::J2CPP_CLASS_NAME, java::util::Date::J2CPP_METHOD_NAME(24), java::util::Date::J2CPP_METHOD_SIGNATURE(24), void >(get_jobject(), a0); } void java::util::Date::setMonth(jint a0) { return call_method< java::util::Date::J2CPP_CLASS_NAME, java::util::Date::J2CPP_METHOD_NAME(25), java::util::Date::J2CPP_METHOD_SIGNATURE(25), void >(get_jobject(), a0); } void java::util::Date::setSeconds(jint a0) { return call_method< java::util::Date::J2CPP_CLASS_NAME, java::util::Date::J2CPP_METHOD_NAME(26), java::util::Date::J2CPP_METHOD_SIGNATURE(26), void >(get_jobject(), a0); } void java::util::Date::setTime(jlong a0) { return call_method< java::util::Date::J2CPP_CLASS_NAME, java::util::Date::J2CPP_METHOD_NAME(27), java::util::Date::J2CPP_METHOD_SIGNATURE(27), void >(get_jobject(), a0); } void java::util::Date::setYear(jint a0) { return call_method< java::util::Date::J2CPP_CLASS_NAME, java::util::Date::J2CPP_METHOD_NAME(28), java::util::Date::J2CPP_METHOD_SIGNATURE(28), void >(get_jobject(), a0); } local_ref< java::lang::String > java::util::Date::toGMTString() { return call_method< java::util::Date::J2CPP_CLASS_NAME, java::util::Date::J2CPP_METHOD_NAME(29), java::util::Date::J2CPP_METHOD_SIGNATURE(29), local_ref< java::lang::String > >(get_jobject()); } local_ref< java::lang::String > java::util::Date::toLocaleString() { return call_method< java::util::Date::J2CPP_CLASS_NAME, java::util::Date::J2CPP_METHOD_NAME(30), java::util::Date::J2CPP_METHOD_SIGNATURE(30), local_ref< java::lang::String > >(get_jobject()); } local_ref< java::lang::String > java::util::Date::toString() { return call_method< java::util::Date::J2CPP_CLASS_NAME, java::util::Date::J2CPP_METHOD_NAME(31), java::util::Date::J2CPP_METHOD_SIGNATURE(31), local_ref< java::lang::String > >(get_jobject()); } jlong java::util::Date::UTC(jint a0, jint a1, jint a2, jint a3, jint a4, jint a5) { return call_static_method< java::util::Date::J2CPP_CLASS_NAME, java::util::Date::J2CPP_METHOD_NAME(32), java::util::Date::J2CPP_METHOD_SIGNATURE(32), jlong >(a0, a1, a2, a3, a4, a5); } jint java::util::Date::compareTo(local_ref< java::lang::Object > const &a0) { return call_method< java::util::Date::J2CPP_CLASS_NAME, java::util::Date::J2CPP_METHOD_NAME(33), java::util::Date::J2CPP_METHOD_SIGNATURE(33), jint >(get_jobject(), a0); } J2CPP_DEFINE_CLASS(java::util::Date,"java/util/Date") J2CPP_DEFINE_METHOD(java::util::Date,0,"<init>","()V") J2CPP_DEFINE_METHOD(java::util::Date,1,"<init>","(III)V") J2CPP_DEFINE_METHOD(java::util::Date,2,"<init>","(IIIII)V") J2CPP_DEFINE_METHOD(java::util::Date,3,"<init>","(IIIIII)V") J2CPP_DEFINE_METHOD(java::util::Date,4,"<init>","(J)V") J2CPP_DEFINE_METHOD(java::util::Date,5,"<init>","(Ljava/lang/String;)V") J2CPP_DEFINE_METHOD(java::util::Date,6,"after","(Ljava/util/Date;)Z") J2CPP_DEFINE_METHOD(java::util::Date,7,"before","(Ljava/util/Date;)Z") J2CPP_DEFINE_METHOD(java::util::Date,8,"clone","()Ljava/lang/Object;") J2CPP_DEFINE_METHOD(java::util::Date,9,"compareTo","(Ljava/util/Date;)I") J2CPP_DEFINE_METHOD(java::util::Date,10,"equals","(Ljava/lang/Object;)Z") J2CPP_DEFINE_METHOD(java::util::Date,11,"getDate","()I") J2CPP_DEFINE_METHOD(java::util::Date,12,"getDay","()I") J2CPP_DEFINE_METHOD(java::util::Date,13,"getHours","()I") J2CPP_DEFINE_METHOD(java::util::Date,14,"getMinutes","()I") J2CPP_DEFINE_METHOD(java::util::Date,15,"getMonth","()I") J2CPP_DEFINE_METHOD(java::util::Date,16,"getSeconds","()I") J2CPP_DEFINE_METHOD(java::util::Date,17,"getTime","()J") J2CPP_DEFINE_METHOD(java::util::Date,18,"getTimezoneOffset","()I") J2CPP_DEFINE_METHOD(java::util::Date,19,"getYear","()I") J2CPP_DEFINE_METHOD(java::util::Date,20,"hashCode","()I") J2CPP_DEFINE_METHOD(java::util::Date,21,"parse","(Ljava/lang/String;)J") J2CPP_DEFINE_METHOD(java::util::Date,22,"setDate","(I)V") J2CPP_DEFINE_METHOD(java::util::Date,23,"setHours","(I)V") J2CPP_DEFINE_METHOD(java::util::Date,24,"setMinutes","(I)V") J2CPP_DEFINE_METHOD(java::util::Date,25,"setMonth","(I)V") J2CPP_DEFINE_METHOD(java::util::Date,26,"setSeconds","(I)V") J2CPP_DEFINE_METHOD(java::util::Date,27,"setTime","(J)V") J2CPP_DEFINE_METHOD(java::util::Date,28,"setYear","(I)V") J2CPP_DEFINE_METHOD(java::util::Date,29,"toGMTString","()Ljava/lang/String;") J2CPP_DEFINE_METHOD(java::util::Date,30,"toLocaleString","()Ljava/lang/String;") J2CPP_DEFINE_METHOD(java::util::Date,31,"toString","()Ljava/lang/String;") J2CPP_DEFINE_METHOD(java::util::Date,32,"UTC","(IIIIII)J") J2CPP_DEFINE_METHOD(java::util::Date,33,"compareTo","(Ljava/lang/Object;)I") } //namespace j2cpp #endif //J2CPP_JAVA_UTIL_DATE_HPP_IMPL #endif //J2CPP_INCLUDE_IMPLEMENTATION
/* * Copyright 2014 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkColorCubeFilter.h" #include "SkColorPriv.h" #include "SkOnce.h" #include "SkReadBuffer.h" #include "SkUnPreMultiply.h" #include "SkWriteBuffer.h" #if SK_SUPPORT_GPU #include "GrContext.h" #include "GrCoordTransform.h" #include "GrInvariantOutput.h" #include "GrTexturePriv.h" #include "SkGr.h" #include "gl/GrGLProcessor.h" #include "gl/builders/GrGLProgramBuilder.h" #endif /////////////////////////////////////////////////////////////////////////////// namespace { int32_t SkNextColorCubeUniqueID() { static int32_t gColorCubeUniqueID; // do a loop in case our global wraps around, as we never want to return a 0 int32_t genID; do { genID = sk_atomic_inc(&gColorCubeUniqueID) + 1; } while (0 == genID); return genID; } } // end namespace static const int MIN_CUBE_SIZE = 4; static const int MAX_CUBE_SIZE = 64; static bool is_valid_3D_lut(SkData* cubeData, int cubeDimension) { size_t minMemorySize = sizeof(uint8_t) * 4 * cubeDimension * cubeDimension * cubeDimension; return (cubeDimension >= MIN_CUBE_SIZE) && (cubeDimension <= MAX_CUBE_SIZE) && (NULL != cubeData) && (cubeData->size() >= minMemorySize); } SkColorFilter* SkColorCubeFilter::Create(SkData* cubeData, int cubeDimension) { if (!is_valid_3D_lut(cubeData, cubeDimension)) { return NULL; } return SkNEW_ARGS(SkColorCubeFilter, (cubeData, cubeDimension)); } SkColorCubeFilter::SkColorCubeFilter(SkData* cubeData, int cubeDimension) : fCubeData(SkRef(cubeData)) , fUniqueID(SkNextColorCubeUniqueID()) , fCache(cubeDimension) { } uint32_t SkColorCubeFilter::getFlags() const { return this->INHERITED::getFlags() | kAlphaUnchanged_Flag; } SkColorCubeFilter::ColorCubeProcesingCache::ColorCubeProcesingCache(int cubeDimension) : fCubeDimension(cubeDimension) , fLutsInited(false) { fColorToIndex[0] = fColorToIndex[1] = NULL; fColorToFactors[0] = fColorToFactors[1] = NULL; fColorToScalar = NULL; } void SkColorCubeFilter::ColorCubeProcesingCache::getProcessingLuts( const int* (*colorToIndex)[2], const SkScalar* (*colorToFactors)[2], const SkScalar** colorToScalar) { SkOnce(&fLutsInited, &fLutsMutex, SkColorCubeFilter::ColorCubeProcesingCache::initProcessingLuts, this); SkASSERT((fColorToIndex[0] != NULL) && (fColorToIndex[1] != NULL) && (fColorToFactors[0] != NULL) && (fColorToFactors[1] != NULL) && (fColorToScalar != NULL)); (*colorToIndex)[0] = fColorToIndex[0]; (*colorToIndex)[1] = fColorToIndex[1]; (*colorToFactors)[0] = fColorToFactors[0]; (*colorToFactors)[1] = fColorToFactors[1]; (*colorToScalar) = fColorToScalar; } void SkColorCubeFilter::ColorCubeProcesingCache::initProcessingLuts( SkColorCubeFilter::ColorCubeProcesingCache* cache) { static const SkScalar inv8bit = SkScalarInvert(SkIntToScalar(255)); // We need 256 int * 2 for fColorToIndex, so a total of 512 int. // We need 256 SkScalar * 2 for fColorToFactors and 256 SkScalar // for fColorToScalar, so a total of 768 SkScalar. cache->fLutStorage.reset(512 * sizeof(int) + 768 * sizeof(SkScalar)); uint8_t* storage = (uint8_t*)cache->fLutStorage.get(); cache->fColorToIndex[0] = (int*)storage; cache->fColorToIndex[1] = cache->fColorToIndex[0] + 256; cache->fColorToFactors[0] = (SkScalar*)(storage + (512 * sizeof(int))); cache->fColorToFactors[1] = cache->fColorToFactors[0] + 256; cache->fColorToScalar = cache->fColorToFactors[1] + 256; SkScalar size = SkIntToScalar(cache->fCubeDimension); SkScalar scale = (size - SK_Scalar1) * inv8bit; for (int i = 0; i < 256; ++i) { SkScalar index = scale * i; cache->fColorToIndex[0][i] = SkScalarFloorToInt(index); cache->fColorToIndex[1][i] = cache->fColorToIndex[0][i] + 1; cache->fColorToScalar[i] = inv8bit * i; if (cache->fColorToIndex[1][i] < cache->fCubeDimension) { cache->fColorToFactors[1][i] = index - SkIntToScalar(cache->fColorToIndex[0][i]); cache->fColorToFactors[0][i] = SK_Scalar1 - cache->fColorToFactors[1][i]; } else { cache->fColorToIndex[1][i] = cache->fColorToIndex[0][i]; cache->fColorToFactors[0][i] = SK_Scalar1; cache->fColorToFactors[1][i] = 0; } } } void SkColorCubeFilter::filterSpan(const SkPMColor src[], int count, SkPMColor dst[]) const { const int* colorToIndex[2]; const SkScalar* colorToFactors[2]; const SkScalar* colorToScalar; fCache.getProcessingLuts(&colorToIndex, &colorToFactors, &colorToScalar); const int dim = fCache.cubeDimension(); SkColor* colorCube = (SkColor*)fCubeData->data(); for (int i = 0; i < count; ++i) { SkColor inputColor = SkUnPreMultiply::PMColorToColor(src[i]); uint8_t r = SkColorGetR(inputColor); uint8_t g = SkColorGetG(inputColor); uint8_t b = SkColorGetB(inputColor); uint8_t a = SkColorGetA(inputColor); SkScalar rOut(0), gOut(0), bOut(0); for (int x = 0; x < 2; ++x) { for (int y = 0; y < 2; ++y) { for (int z = 0; z < 2; ++z) { SkColor lutColor = colorCube[colorToIndex[x][r] + (colorToIndex[y][g] + colorToIndex[z][b] * dim) * dim]; SkScalar factor = colorToFactors[x][r] * colorToFactors[y][g] * colorToFactors[z][b]; rOut += colorToScalar[SkColorGetR(lutColor)] * factor; gOut += colorToScalar[SkColorGetG(lutColor)] * factor; bOut += colorToScalar[SkColorGetB(lutColor)] * factor; } } } const SkScalar aOut = SkIntToScalar(a); dst[i] = SkPackARGB32(a, SkScalarRoundToInt(rOut * aOut), SkScalarRoundToInt(gOut * aOut), SkScalarRoundToInt(bOut * aOut)); } } SkFlattenable* SkColorCubeFilter::CreateProc(SkReadBuffer& buffer) { int cubeDimension = buffer.readInt(); SkAutoDataUnref cubeData(buffer.readByteArrayAsData()); if (!buffer.validate(is_valid_3D_lut(cubeData, cubeDimension))) { return NULL; } return Create(cubeData, cubeDimension); } void SkColorCubeFilter::flatten(SkWriteBuffer& buffer) const { this->INHERITED::flatten(buffer); buffer.writeInt(fCache.cubeDimension()); buffer.writeDataAsByteArray(fCubeData); } #ifndef SK_IGNORE_TO_STRING void SkColorCubeFilter::toString(SkString* str) const { str->append("SkColorCubeFilter "); } #endif /////////////////////////////////////////////////////////////////////////////// #if SK_SUPPORT_GPU class GrColorCubeEffect : public GrFragmentProcessor { public: static GrFragmentProcessor* Create(GrTexture* colorCube) { return (NULL != colorCube) ? SkNEW_ARGS(GrColorCubeEffect, (colorCube)) : NULL; } virtual ~GrColorCubeEffect(); const char* name() const SK_OVERRIDE { return "ColorCube"; } virtual void getGLProcessorKey(const GrGLCaps& caps, GrProcessorKeyBuilder* b) const SK_OVERRIDE; GrGLFragmentProcessor* createGLInstance() const SK_OVERRIDE; int colorCubeSize() const { return fColorCubeAccess.getTexture()->width(); } void onComputeInvariantOutput(GrInvariantOutput*) const SK_OVERRIDE; class GLProcessor : public GrGLFragmentProcessor { public: GLProcessor(const GrProcessor&); virtual ~GLProcessor(); virtual void emitCode(GrGLFPBuilder*, const GrFragmentProcessor&, const char* outputColor, const char* inputColor, const TransformedCoordsArray&, const TextureSamplerArray&) SK_OVERRIDE; static inline void GenKey(const GrProcessor&, const GrGLCaps&, GrProcessorKeyBuilder*); void setData(const GrGLProgramDataManager&, const GrProcessor&) SK_OVERRIDE; private: GrGLProgramDataManager::UniformHandle fColorCubeSizeUni; GrGLProgramDataManager::UniformHandle fColorCubeInvSizeUni; typedef GrGLFragmentProcessor INHERITED; }; private: bool onIsEqual(const GrFragmentProcessor&) const SK_OVERRIDE { return true; } GrColorCubeEffect(GrTexture* colorCube); GrTextureAccess fColorCubeAccess; typedef GrFragmentProcessor INHERITED; }; /////////////////////////////////////////////////////////////////////////////// GrColorCubeEffect::GrColorCubeEffect(GrTexture* colorCube) : fColorCubeAccess(colorCube, "bgra", GrTextureParams::kBilerp_FilterMode) { this->initClassID<GrColorCubeEffect>(); this->addTextureAccess(&fColorCubeAccess); } GrColorCubeEffect::~GrColorCubeEffect() { } void GrColorCubeEffect::getGLProcessorKey(const GrGLCaps& caps, GrProcessorKeyBuilder* b) const { GLProcessor::GenKey(*this, caps, b); } GrGLFragmentProcessor* GrColorCubeEffect::createGLInstance() const { return SkNEW_ARGS(GLProcessor, (*this)); } void GrColorCubeEffect::onComputeInvariantOutput(GrInvariantOutput* inout) const { inout->setToUnknown(GrInvariantOutput::kWill_ReadInput); } /////////////////////////////////////////////////////////////////////////////// GrColorCubeEffect::GLProcessor::GLProcessor(const GrProcessor&) { } GrColorCubeEffect::GLProcessor::~GLProcessor() { } void GrColorCubeEffect::GLProcessor::emitCode(GrGLFPBuilder* builder, const GrFragmentProcessor&, const char* outputColor, const char* inputColor, const TransformedCoordsArray& coords, const TextureSamplerArray& samplers) { if (NULL == inputColor) { inputColor = "vec4(1)"; } fColorCubeSizeUni = builder->addUniform(GrGLProgramBuilder::kFragment_Visibility, kFloat_GrSLType, kDefault_GrSLPrecision, "Size"); const char* colorCubeSizeUni = builder->getUniformCStr(fColorCubeSizeUni); fColorCubeInvSizeUni = builder->addUniform(GrGLProgramBuilder::kFragment_Visibility, kFloat_GrSLType, kDefault_GrSLPrecision, "InvSize"); const char* colorCubeInvSizeUni = builder->getUniformCStr(fColorCubeInvSizeUni); const char* nonZeroAlpha = "nonZeroAlpha"; const char* unPMColor = "unPMColor"; const char* cubeIdx = "cubeIdx"; const char* cCoords1 = "cCoords1"; const char* cCoords2 = "cCoords2"; // Note: if implemented using texture3D in OpenGL ES older than OpenGL ES 3.0, // the shader might need "#extension GL_OES_texture_3D : enable". GrGLFPFragmentBuilder* fsBuilder = builder->getFragmentShaderBuilder(); // Unpremultiply color fsBuilder->codeAppendf("\tfloat %s = max(%s.a, 0.00001);\n", nonZeroAlpha, inputColor); fsBuilder->codeAppendf("\tvec4 %s = vec4(%s.rgb / %s, %s);\n", unPMColor, inputColor, nonZeroAlpha, nonZeroAlpha); // Fit input color into the cube. fsBuilder->codeAppendf( "vec3 %s = vec3(%s.rg * vec2((%s - 1.0) * %s) + vec2(0.5 * %s), %s.b * (%s - 1.0));\n", cubeIdx, unPMColor, colorCubeSizeUni, colorCubeInvSizeUni, colorCubeInvSizeUni, unPMColor, colorCubeSizeUni); // Compute y coord for for texture fetches. fsBuilder->codeAppendf("vec2 %s = vec2(%s.r, (floor(%s.b) + %s.g) * %s);\n", cCoords1, cubeIdx, cubeIdx, cubeIdx, colorCubeInvSizeUni); fsBuilder->codeAppendf("vec2 %s = vec2(%s.r, (ceil(%s.b) + %s.g) * %s);\n", cCoords2, cubeIdx, cubeIdx, cubeIdx, colorCubeInvSizeUni); // Apply the cube. fsBuilder->codeAppendf("%s = vec4(mix(", outputColor); fsBuilder->appendTextureLookup(samplers[0], cCoords1); fsBuilder->codeAppend(".rgb, "); fsBuilder->appendTextureLookup(samplers[0], cCoords2); // Premultiply color by alpha. Note that the input alpha is not modified by this shader. fsBuilder->codeAppendf(".rgb, fract(%s.b)) * vec3(%s), %s.a);\n", cubeIdx, nonZeroAlpha, inputColor); } void GrColorCubeEffect::GLProcessor::setData(const GrGLProgramDataManager& pdman, const GrProcessor& proc) { const GrColorCubeEffect& colorCube = proc.cast<GrColorCubeEffect>(); SkScalar size = SkIntToScalar(colorCube.colorCubeSize()); pdman.set1f(fColorCubeSizeUni, SkScalarToFloat(size)); pdman.set1f(fColorCubeInvSizeUni, SkScalarToFloat(SkScalarInvert(size))); } void GrColorCubeEffect::GLProcessor::GenKey(const GrProcessor& proc, const GrGLCaps&, GrProcessorKeyBuilder* b) { } GrFragmentProcessor* SkColorCubeFilter::asFragmentProcessor(GrContext* context) const { static const GrUniqueKey::Domain kDomain = GrUniqueKey::GenerateDomain(); GrUniqueKey key; GrUniqueKey::Builder builder(&key, kDomain, 2); builder[0] = fUniqueID; builder[1] = fCache.cubeDimension(); builder.finish(); GrSurfaceDesc desc; desc.fWidth = fCache.cubeDimension(); desc.fHeight = fCache.cubeDimension() * fCache.cubeDimension(); desc.fConfig = kRGBA_8888_GrPixelConfig; SkAutoTUnref<GrTexture> textureCube(context->findAndRefCachedTexture(key)); if (!textureCube) { textureCube.reset(context->createTexture(desc, true, fCubeData->data(), 0)); if (textureCube) { context->addResourceToCache(key, textureCube); } } return textureCube ? GrColorCubeEffect::Create(textureCube) : NULL; } #endif
// // MacchinaMapGenerator.cpp // CarlaUE4_Index // // Created by Thierry Deruyttere on 26/09/18. // Copyright © 2018 Epic Games, Inc. All rights reserved. // // Copyright (c) 2017 Computer Vision Center (CVC) at the Universitat Autonoma // de Barcelona (UAB). // // This work is licensed under the terms of the MIT license. // For a copy, see <https://opensource.org/licenses/MIT>. #include "Carla.h" #include "MacchinaGenerator.h" #include "MapGen/GraphGenerator.h" #include "MapGen/RoadMap.h" #include "Game/Tagger.h" #include "Components/InstancedStaticMeshComponent.h" #include "Engine/World.h" #include "Paths.h" #include "Async.h" #include <vector> #include "json2.h" #include <algorithm> #include <unordered_set> using json = nlohmann::json; #ifdef CARLA_ROAD_GENERATOR_EXTRA_LOG #include <sstream> #endif // CARLA_ROAD_GENERATOR_EXTRA_LOG // ============================================================================= // -- Constructor and destructor ----------------------------------------------- // ============================================================================= AMacchinaCityMapGenerator::AMacchinaCityMapGenerator(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer) { RoadMap = ObjectInitializer.CreateDefaultSubobject<URoadMap>(this, TEXT("RoadMap")); LoadMeshes(); } AMacchinaCityMapGenerator::~AMacchinaCityMapGenerator() {} // ============================================================================= // -- Overriden from UObject --------------------------------------------------- // ============================================================================= void AMacchinaCityMapGenerator::PreSave(const ITargetPlatform *TargetPlatform) { #if WITH_EDITOR if (bGenerateRoadMapOnSave) { // Generate road map only if we are not cooking. FCoreUObjectDelegates::OnObjectSaved.Broadcast(this); if (!GIsCookerLoadingPackage) { check(RoadMap != nullptr); GenerateRoadMap(); } } #endif // WITH_EDITOR Super::PreSave(TargetPlatform); } // ============================================================================= // -- Overriden from ACityMapMeshHolder ---------------------------------------- // ============================================================================= void AMacchinaCityMapGenerator::UpdateMap() { //UpdateSeeds(); //GenerateGraph(); //GenerateMacchina(); /* if (bGenerateRoads) { GenerateRoads(); } if (bTriggerRoadMapGeneration) { bTriggerRoadMapGeneration = false; GenerateRoadMap(); }*/ } // ============================================================================= // -- Map construction and update related methods ------------------------------ // ============================================================================= void AMacchinaCityMapGenerator::UpdateSeeds() { if (!bUseFixedSeed) { FRandomStream randomStream; randomStream.GenerateNewSeed(); Seed = randomStream.GetCurrentSeed(); } } void AMacchinaCityMapGenerator::GenerateGraph() { if ((MapSizeX < 5u) || (MapSizeY < 5u)) { MapSizeX = 5u; MapSizeY = 5u; UE_LOG(LogCarla, Warning, TEXT("Map size changed, was too small")); } #ifdef CARLA_ROAD_GENERATOR_EXTRA_LOG // Delete the dcel before the new one is created so indices are restored. Dcel.Reset(nullptr); #endif // CARLA_ROAD_GENERATOR_EXTRA_LOG Dcel = MapGen::GraphGenerator::Generate(MapSizeX, MapSizeY, Seed); UE_LOG(LogCarla, Log, TEXT("Generated DCEL with: { %d vertices, %d half-edges, %d faces }"), Dcel->CountNodes(), Dcel->CountHalfEdges(), Dcel->CountFaces()); DcelParser = MakeUnique<MapGen::GraphParser>(*Dcel); #ifdef CARLA_ROAD_GENERATOR_EXTRA_LOG { // print the results of the parser. std::wstringstream sout; sout << "\nGenerated " << DcelParser->CityAreaCount() << " city areas: "; for (auto i = 0u; i < DcelParser->CityAreaCount(); ++i) { sout << "{ "; auto &cityArea = DcelParser->GetCityAreaAt(i); for (size_t j = 0u; j < cityArea.NodeCount(); ++j) { sout << cityArea.GetNodeAt(j) << " "; } sout << "} "; } sout << "\nGenerated " << DcelParser->RoadSegmentCount() << " road segments: "; for (auto i = 0u; i < DcelParser->RoadSegmentCount(); ++i) { sout << "{ "; auto &roadSegment = DcelParser->GetRoadSegmentAt(i); for (size_t j = 0u; j < roadSegment.Size(); ++j) { sout << roadSegment[j] << " "; } sout << "} "; } UE_LOG(LogCarla, Log, TEXT("\n%s"), sout.str().c_str()); } #endif // CARLA_ROAD_GENERATOR_EXTRA_LOG } void AMacchinaCityMapGenerator::LoadMeshes() { #define SET_STATIC_MESH(Tag, Folder, FileName) \ { \ static const ConstructorHelpers::FObjectFinder<UStaticMesh> MeshObj(TEXT("StaticMesh'" Folder "/" FileName "." FileName "'")); \ SetStaticMesh(ECityMapMeshTag:: Tag, MeshObj.Object); \ } #define PREFIX_FOLDER "/Game/Carla/Static/" SET_STATIC_MESH(RoadTwoLanes_LaneLeft, PREFIX_FOLDER "Road", "St_Road_TileRoad_RoadL"); SET_STATIC_MESH(RoadTwoLanes_LaneRight, PREFIX_FOLDER "Road", "St_Road_TileRoad_RoadR"); SET_STATIC_MESH(RoadTwoLanes_SidewalkLeft, PREFIX_FOLDER "SideWalk", "St_Road_TileRoad_SidewalkL"); SET_STATIC_MESH(RoadTwoLanes_SidewalkRight, PREFIX_FOLDER "SideWalk", "St_Road_TileRoad_SidewalkR"); SET_STATIC_MESH(RoadTwoLanes_LaneMarkingSolid, PREFIX_FOLDER "RoadLines", "St_Road_TileRoad_LaneMarkingSolid"); SET_STATIC_MESH(RoadTwoLanes_LaneMarkingBroken, PREFIX_FOLDER "RoadLines", "St_Road_TileRoad_LaneMarkingBroken"); SET_STATIC_MESH(Road90DegTurn_Lane0, PREFIX_FOLDER "Road", "St_Road_Curve_Road0"); SET_STATIC_MESH(Road90DegTurn_Lane1, PREFIX_FOLDER "Road", "St_Road_Curve_Road1"); SET_STATIC_MESH(Road90DegTurn_Lane2, PREFIX_FOLDER "Road", "St_Road_Curve_Road2"); SET_STATIC_MESH(Road90DegTurn_Lane3, PREFIX_FOLDER "Road", "St_Road_Curve_Road3"); SET_STATIC_MESH(Road90DegTurn_Lane4, PREFIX_FOLDER "Road", "St_Road_Curve_Road4"); SET_STATIC_MESH(Road90DegTurn_Lane5, PREFIX_FOLDER "Road", "St_Road_Curve_Road5"); SET_STATIC_MESH(Road90DegTurn_Lane6, PREFIX_FOLDER "Road", "St_Road_Curve_Road6"); SET_STATIC_MESH(Road90DegTurn_Lane7, PREFIX_FOLDER "Road", "St_Road_Curve_Road7"); SET_STATIC_MESH(Road90DegTurn_Lane8, PREFIX_FOLDER "Road", "St_Road_Curve_Road8"); SET_STATIC_MESH(Road90DegTurn_Lane9, PREFIX_FOLDER "Road", "St_Road_Curve_Road9"); SET_STATIC_MESH(Road90DegTurn_Sidewalk0, PREFIX_FOLDER "SideWalk", "St_Road_Curve_Sidewalk1"); SET_STATIC_MESH(Road90DegTurn_Sidewalk1, PREFIX_FOLDER "SideWalk", "St_Road_Curve_Sidewalk2"); SET_STATIC_MESH(Road90DegTurn_Sidewalk2, PREFIX_FOLDER "SideWalk", "St_Road_Curve_Sidewalk3"); SET_STATIC_MESH(Road90DegTurn_Sidewalk3, PREFIX_FOLDER "SideWalk", "St_Road_Curve_Sidewalk4"); SET_STATIC_MESH(Road90DegTurn_LaneMarking, PREFIX_FOLDER "RoadLines", "St_Road_Curve_LaneMarking"); SET_STATIC_MESH(RoadTIntersection_Lane0, PREFIX_FOLDER "Road", "St_Road_TCross_Road0"); SET_STATIC_MESH(RoadTIntersection_Lane1, PREFIX_FOLDER "Road", "St_Road_TCross_Road1"); SET_STATIC_MESH(RoadTIntersection_Lane2, PREFIX_FOLDER "Road", "St_Road_TCross_Road2"); SET_STATIC_MESH(RoadTIntersection_Lane3, PREFIX_FOLDER "Road", "St_Road_TCross_Road3"); SET_STATIC_MESH(RoadTIntersection_Lane4, PREFIX_FOLDER "Road", "St_Road_TCross_Road4"); SET_STATIC_MESH(RoadTIntersection_Lane5, PREFIX_FOLDER "Road", "St_Road_TCross_Road5"); SET_STATIC_MESH(RoadTIntersection_Lane6, PREFIX_FOLDER "Road", "St_Road_TCross_Road6"); SET_STATIC_MESH(RoadTIntersection_Lane7, PREFIX_FOLDER "Road", "St_Road_TCross_Road7"); SET_STATIC_MESH(RoadTIntersection_Lane8, PREFIX_FOLDER "Road", "St_Road_TCross_Road8"); SET_STATIC_MESH(RoadTIntersection_Lane9, PREFIX_FOLDER "Road", "St_Road_TCross_Road9"); SET_STATIC_MESH(RoadTIntersection_Sidewalk0, PREFIX_FOLDER "SideWalk", "St_Road_TCross_Sidewalk1"); SET_STATIC_MESH(RoadTIntersection_Sidewalk1, PREFIX_FOLDER "SideWalk", "St_Road_TCross_Sidewalk2"); SET_STATIC_MESH(RoadTIntersection_Sidewalk2, PREFIX_FOLDER "SideWalk", "St_Road_TCross_Sidewalk3"); SET_STATIC_MESH(RoadTIntersection_Sidewalk3, PREFIX_FOLDER "SideWalk", "St_Road_TCross_Sidewalk4"); SET_STATIC_MESH(RoadTIntersection_LaneMarking, PREFIX_FOLDER "RoadLines", "St_Road_TCross_LaneMarking"); SET_STATIC_MESH(RoadXIntersection_Lane0, PREFIX_FOLDER "Road", "St_Road_XCross_Road0"); SET_STATIC_MESH(RoadXIntersection_Lane1, PREFIX_FOLDER "Road", "St_Road_XCross_Road1"); SET_STATIC_MESH(RoadXIntersection_Lane2, PREFIX_FOLDER "Road", "St_Road_XCross_Road2"); SET_STATIC_MESH(RoadXIntersection_Lane3, PREFIX_FOLDER "Road", "St_Road_XCross_Road3"); SET_STATIC_MESH(RoadXIntersection_Lane4, PREFIX_FOLDER "Road", "St_Road_XCross_Road4"); SET_STATIC_MESH(RoadXIntersection_Lane5, PREFIX_FOLDER "Road", "St_Road_XCross_Road5"); SET_STATIC_MESH(RoadXIntersection_Lane6, PREFIX_FOLDER "Road", "St_Road_XCross_Road6"); SET_STATIC_MESH(RoadXIntersection_Lane7, PREFIX_FOLDER "Road", "St_Road_XCross_Road7"); SET_STATIC_MESH(RoadXIntersection_Lane8, PREFIX_FOLDER "Road", "St_Road_XCross_Road8"); SET_STATIC_MESH(RoadXIntersection_Lane9, PREFIX_FOLDER "Road", "St_Road_XCross_Road9"); SET_STATIC_MESH(RoadXIntersection_Sidewalk0, PREFIX_FOLDER "SideWalk", "St_Road_XCross_Sidewalk1"); SET_STATIC_MESH(RoadXIntersection_Sidewalk1, PREFIX_FOLDER "SideWalk", "St_Road_XCross_Sidewalk2"); SET_STATIC_MESH(RoadXIntersection_Sidewalk2, PREFIX_FOLDER "SideWalk", "St_Road_XCross_Sidewalk3"); SET_STATIC_MESH(RoadXIntersection_Sidewalk3, PREFIX_FOLDER "SideWalk", "St_Road_XCross_Sidewalk4"); SET_STATIC_MESH(RoadXIntersection_LaneMarking, PREFIX_FOLDER "RoadLines", "St_Road_XCross_LaneMarking"); /* * Objects */ SET_STATIC_MESH(House_AmerSuburb002_N2, PREFIX_FOLDER "Buildings/Bl_House_AmerSuburb002_N2", "Bl_House_AmerSuburb002_N2"); SET_STATIC_MESH(House_AmerSuburb003_N2, PREFIX_FOLDER "Buildings/Bl_House_AmerSuburb003_N2", "Bl_House_AmerSuburb003"); SET_STATIC_MESH(House_AmerSuburb004_N2, PREFIX_FOLDER "Buildings/Bl_House_AmerSuburb004_N2", "Bl_House_AmerSuburb004_N2"); SET_STATIC_MESH(House_AmerSuburb005_N5, PREFIX_FOLDER "Buildings/Bl_House_AmerSuburb005_N5", "Bl_House_AmerSuburb005_N5"); SET_STATIC_MESH(House_AmerSuburb006_N2, PREFIX_FOLDER "Buildings/Bl_House_AmerSuburb006_N2", "Bl_House_AmerSuburb006_N2"); SET_STATIC_MESH(Props_Bench, PREFIX_FOLDER "Props/Bench", "prop_bench"); SET_STATIC_MESH(Props_Trashcan, PREFIX_FOLDER "Props/MetallicTrashCan", "prop_Trashcan"); SET_STATIC_MESH(Props_BusStop, PREFIX_FOLDER "Props/BusStop", "prop_bus_stop"); SET_STATIC_MESH(Props_FireHydrant, PREFIX_FOLDER "Pole/FireHydrant", "prop__firehydrant"); /* * Vehicles */ SET_STATIC_MESH(Vehicle_Toyota_prius, PREFIX_FOLDER "Vehicles/4Wheeled/Toyota_Prius", "Vh_Car_ToyotaPrius_NOrig"); SET_STATIC_MESH(Vehicle_mini, PREFIX_FOLDER "Vehicles/4Wheeled/MIni", "Vh_Car_MiniCooperS"); #undef PREFIX_FOLDER #undef SET_STATIC_MESH } void AMacchinaCityMapGenerator::GenerateScene(const std::string& scene) { AsyncTask(ENamedThreads::GameThread, [this, scene]() { /*FString JsonRaw = FString(scene.c_str()); TSharedPtr<FJsonObject> JsonParsed; TSharedRef<TJsonReader<TCHAR>> JsonReader = TJsonReaderFactory<TCHAR>::Create(JsonRaw);*/ json JsonRaw = json::parse(scene); json map = JsonRaw["map"].get<std::vector<json>>(); for(auto &item : map){ int obj = item["obj"].get<int>(); if(obj < CityMapMeshTag::GetNumberOfTags()){ float x = item["x"].get<float>(); float y = item["y"].get<float>(); float angle = item["angle"].get<float>(); ECityMapMeshTag tag = static_cast<ECityMapMeshTag>(obj); AddInstance(tag, x, y, angle); } } //GenerateRoadMap(); // code to execute on game thread here //GenerateMacchina(); //UE_LOG(LogCarla, Log, TEXT("%s"), *FString(map.c_str())); }); //GenerateMacchina(); UE_LOG(LogCarla, Log, TEXT("Generated macchina map")); //UE_LOG(LogCarla, Info, TEXT("Finished creating map")); } void AMacchinaCityMapGenerator::GenerateMacchina(){ //check(Dcel != nullptr); auto x = 0; auto y = 0; auto end = 2; // First road AddInstance(ECityMapMeshTag::RoadTwoLanes_LaneLeft, x, y, HALF_PI); AddInstance(ECityMapMeshTag::RoadTwoLanes_SidewalkLeft, x, y, HALF_PI); AddInstance(ECityMapMeshTag::RoadTwoLanes_SidewalkRight, -400, y, HALF_PI); // second road y = 810.0; AddInstance(ECityMapMeshTag::RoadTwoLanes_LaneLeft, x, y, HALF_PI); AddInstance(ECityMapMeshTag::RoadTwoLanes_SidewalkLeft, x, y, HALF_PI); AddInstance(ECityMapMeshTag::RoadTwoLanes_SidewalkRight, -400, y, HALF_PI); // Horizontal y = 1202.0; AddInstance(ECityMapMeshTag::RoadTwoLanes_LaneLeft, -200, y); AddInstance(ECityMapMeshTag::RoadTwoLanes_LaneLeft, 610, y); AddInstance(ECityMapMeshTag::RoadTwoLanes_LaneLeft, -1010, y); y = 1623.0; AddInstance(ECityMapMeshTag::RoadTwoLanes_SidewalkRight, 430, y); AddInstance(ECityMapMeshTag::RoadTwoLanes_SidewalkRight, -810, y); // second road y = 2031.0; AddInstance(ECityMapMeshTag::RoadTwoLanes_LaneLeft, x, y, HALF_PI); AddInstance(ECityMapMeshTag::RoadTwoLanes_SidewalkLeft, x, y, HALF_PI); AddInstance(ECityMapMeshTag::RoadTwoLanes_SidewalkRight, -410, y, HALF_PI); y = 1213.0; AddInstance(ECityMapMeshTag::RoadTwoLanes_SidewalkLeft, 400, y, 0); AddInstance(ECityMapMeshTag::RoadTwoLanes_SidewalkRight, -830, y, PI); // Road sign //AddInstance(ECityMapMeshTag::, 210, 920, 0); } void AMacchinaCityMapGenerator::GenerateRoads() { check(Dcel != nullptr); using Graph = MapGen::DoublyConnectedEdgeList; const Graph &graph = *Dcel; const uint32 margin = CityMapMeshTag::GetRoadIntersectionSize() / 2u; FHalfEdgeCounter HalfEdgeCounter; // For each edge add road segment. for (auto &edge : graph.GetHalfEdges()) { if (HalfEdgeCounter.Insert(edge)) { auto source = Graph::GetSource(edge).GetPosition(); auto target = Graph::GetTarget(edge).GetPosition(); if (source.x == target.x) { // vertical auto y = 1u + margin + std::min(source.y, target.y); auto end = std::max(source.y, target.y) - margin; for (; y < end; ++y) { AddInstance(ECityMapMeshTag::RoadTwoLanes_LaneLeft, source.x, y, HALF_PI); AddInstance(ECityMapMeshTag::RoadTwoLanes_LaneRight, source.x, y, HALF_PI); AddInstance(ECityMapMeshTag::RoadTwoLanes_SidewalkLeft, source.x, y, HALF_PI); AddInstance(ECityMapMeshTag::RoadTwoLanes_SidewalkRight, source.x, y, HALF_PI); AddInstance(ECityMapMeshTag::RoadTwoLanes_LaneMarkingBroken, source.x, y, HALF_PI); } } else if (source.y == target.y) { // horizontal auto x = 1u + margin + std::min(source.x, target.x); auto end = std::max(source.x, target.x) - margin; for (; x < end; ++x) { AddInstance(ECityMapMeshTag::RoadTwoLanes_LaneLeft, x, source.y); AddInstance(ECityMapMeshTag::RoadTwoLanes_LaneRight, x, source.y); AddInstance(ECityMapMeshTag::RoadTwoLanes_SidewalkLeft, x, source.y); AddInstance(ECityMapMeshTag::RoadTwoLanes_SidewalkRight, x, source.y); AddInstance(ECityMapMeshTag::RoadTwoLanes_LaneMarkingBroken, x, source.y); } } else { UE_LOG(LogCarla, Warning, TEXT("Diagonal edge ignored")); } } } #define ADD_INTERSECTION(tag, x, y, angle) \ AddInstance(tag ##_Lane0, x, y, angle); \ AddInstance(tag ##_Lane1, x, y, angle); \ AddInstance(tag ##_Lane2, x, y, angle); \ AddInstance(tag ##_Lane3, x, y, angle); \ AddInstance(tag ##_Lane4, x, y, angle); \ AddInstance(tag ##_Lane5, x, y, angle); \ AddInstance(tag ##_Lane6, x, y, angle); \ AddInstance(tag ##_Lane7, x, y, angle); \ AddInstance(tag ##_Lane8, x, y, angle); \ AddInstance(tag ##_Lane9, x, y, angle); \ AddInstance(tag ##_Sidewalk0, x, y, angle); \ AddInstance(tag ##_Sidewalk1, x, y, angle); \ AddInstance(tag ##_Sidewalk2, x, y, angle); \ AddInstance(tag ##_Sidewalk3, x, y, angle); \ AddInstance(tag ##_LaneMarking, x, y, angle); // For each node add the intersection. for (auto &node : graph.GetNodes()) { const auto coords = node.GetPosition(); switch (node.IntersectionType) { case MapGen::EIntersectionType::Turn90Deg: ADD_INTERSECTION(ECityMapMeshTag::Road90DegTurn, coords.x, coords.y, node.Rotation); break; case MapGen::EIntersectionType::TIntersection: ADD_INTERSECTION(ECityMapMeshTag::RoadTIntersection, coords.x, coords.y, node.Rotation); break; case MapGen::EIntersectionType::XIntersection: ADD_INTERSECTION(ECityMapMeshTag::RoadXIntersection, coords.x, coords.y, node.Rotation); break; default: UE_LOG(LogCarla, Warning, TEXT("Intersection type not implemented")); } } #undef ADD_INTERSECTION } void AMacchinaCityMapGenerator::GenerateRoadMap() { UE_LOG(LogCarla, Log, TEXT("Generating road map...")); auto World = GetWorld(); check(GetWorld() != nullptr); check(RoadMap != nullptr); ATagger::TagActorsInLevel(*GetWorld(), bTagForSemanticSegmentation); // We need the tags. const float IntersectionSize = CityMapMeshTag::GetRoadIntersectionSize(); const uint32 Margin = IntersectionSize / 2u; const float Offset = GetMapScale() * Margin; const float CmPerPixel = GetMapScale() / static_cast<float>(PixelsPerMapUnit); const uint32 SizeX = PixelsPerMapUnit * (MapSizeX + 2u * Margin); const uint32 SizeY = PixelsPerMapUnit * (MapSizeY + 2u * Margin); const FTransform &ActorTransform = GetActorTransform(); const FVector MapOffset(-Offset, -Offset, 0.0f); RoadMap->Reset(SizeX, SizeY, 1.0f / CmPerPixel, ActorTransform.Inverse(), MapOffset); for (uint32 PixelY = 0u; PixelY < SizeY; ++PixelY) { for (uint32 PixelX = 0u; PixelX < SizeX; ++PixelX) { const float X = static_cast<float>(PixelX) * CmPerPixel - Offset; const float Y = static_cast<float>(PixelY) * CmPerPixel - Offset; const FVector Start = ActorTransform.TransformPosition(FVector(X, Y, 50.0f)); const FVector End = ActorTransform.TransformPosition(FVector(X, Y, -50.0f)); // Do the ray tracing. FHitResult Hit; if (LineTrace(World, Start, End, Hit)) { auto StaticMeshComponent = Cast<UStaticMeshComponent>(Hit.Component.Get()); if (StaticMeshComponent == nullptr) { UE_LOG(LogCarla, Error, TEXT("Road component is not UInstancedStaticMeshComponent")); } else { RoadMap->SetPixelAt( PixelX, PixelY, GetTag(*StaticMeshComponent->GetStaticMesh()), StaticMeshComponent->GetOwner()->GetTransform(), bLeftHandTraffic); } } } } #if WITH_EDITOR RoadMap->Log(); #endif // WITH_EDITOR if (bSaveRoadMapToDisk) { RoadMap->SaveAsPNG(FPaths::ProjectSavedDir(), World->GetMapName()); } #if WITH_EDITOR RoadMap->DrawDebugPixelsToLevel(GetWorld(), !bDrawDebugPixelsToLevel); #endif // WITH_EDITOR }
#include "ActionNode.hpp" #include "ValueNode.hpp" #include "../../Exception.hpp" BEGIN_INANITY_SHADERS ActionNode::ActionNode(Action action) : action(action), argumentsCount(0) {} ActionNode::ActionNode(Action action, ptr<ValueNode> a) : action(action), argumentsCount(1), a(a) {} ActionNode::ActionNode(Action action, ptr<ValueNode> a, ptr<ValueNode> b) : action(action), argumentsCount(2), a(a), b(b) {} Node::Type ActionNode::GetType() const { return typeAction; } ActionNode::Action ActionNode::GetAction() const { return action; } int ActionNode::GetArgumentsCount() const { return argumentsCount; } ptr<ValueNode> ActionNode::GetA() const { if(!a) THROW("Argument A is unavailable"); return a; } ptr<ValueNode> ActionNode::GetB() const { if(!b) THROW("Argument B is unavailable"); return b; } ptr<ValueNode> ActionNode::GetArgument(int number) const { switch(number) { case 0: return GetA(); case 1: return GetB(); default: THROW("Invalid argument number for action node"); } } END_INANITY_SHADERS
/*============================================================================= Boost.Wave: A Standard compliant C++ preprocessor library http://www.boost.org/ Copyright (c) 2001-2009 Hartmut Kaiser. 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) The tests included in this file were initially taken from the mcpp V2.5 preprocessor validation suite and were modified to fit into the Boost.Wave unit test requirements. The original files of the mcpp preprocessor are distributed under the license reproduced at the end of this file. =============================================================================*/ // Tests translation limits. #define ABCDEFGHIJKLMNOPQRSTUVWXYZabcde 0 #define ABCDEFGHIJKLMNOPQRSTUVWXYZabcd_ 1 // 37.1: Number of parameters in macro: at least 31. #define GLUE31(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E) \ a##b##c##d##e##f##g##h##i##j##k##l##m##n##o##p##q##r##s##t##u##v##w##x##y##z##A##B##C##D##E // 37.2: Number of arguments in macro call: at least 31. //R #line 28 "t_5_035.cpp" //R 0 GLUE31( A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z, a, b, c, d, e) // 37.3: Significant initial characters in an internal identifier or // macro name: at least 31. //R #line 34 "t_5_035.cpp" ABCDEFGHIJKLMNOPQRSTUVWXYZabcd_ //R 1 // 37.4: Nested conditional inclusion: at least 8 levels. //R #line 65 "t_5_035.cpp" #define NEST 0 #ifdef A #else # ifdef B # else # ifdef C # else # ifdef D # else # ifdef E # else # ifdef F # else # ifdef G # else # ifdef H # else #undef NEST #define NEST 1 # endif # endif # endif # endif # endif # endif # endif #endif NEST //R 1 // 37.5: Nested source file inclusion: at least 8 levels. //R #line 70 "t_5_035.cpp" #include "t_5_035_01.hpp" NEST //R 8 // 37.6: Parenthesized expression: at least 32 levels. //R #line 81 "t_5_035.cpp" #if 0 + (1 - (2 + (3 - (4 + (5 - (6 + (7 - (8 + (9 - (10 + (11 - (12 + \ (13 - (14 + (15 - (16 + (17 - (18 + (19 - (20 + (21 - (22 + (23 - \ (24 + (25 - (26 + (27 - (28 + (29 - (30 + (31 - (32 + 0)))))))))) \ )))))))))))))))))))))) == 0 #undef NEST #define NEST 32 #endif NEST //R 32 // 37.7: Characters in a string (after concatenation): at least 509. //R #line 86 "t_5_035.cpp" //R "123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567" "123456789012345678901234567890123456789012345678901234567890123456789\ 0123456789012345678901234567890123456789012345678901234567890123456789\ 0123456789012345678901234567890123456789012345678901234567890123456789\ 0123456789012345678901234567890123456789012345678901234567890123456789\ 0123456789012345678901234567890123456789012345678901234567890123456789\ 0123456789012345678901234567890123456789012345678901234567890123456789\ 0123456789012345678901234567890123456789012345678901234567890123456789\ 012345678901234567" // 37.8: Characters in a logical source line: at least 509. //R #line 98 "t_5_035.cpp" //R 123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567 123456789012345678901234567890123456789012345678901234567890123456789\ 0123456789012345678901234567890123456789012345678901234567890123456789\ 0123456789012345678901234567890123456789012345678901234567890123456789\ 0123456789012345678901234567890123456789012345678901234567890123456789\ 0123456789012345678901234567890123456789012345678901234567890123456789\ 0123456789012345678901234567890123456789012345678901234567890123456789\ 0123456789012345678901234567890123456789012345678901234567890123456789\ 012345678901234567 // 37.9: Macro definitions: at least 1024. //R #line 110 "t_5_035.cpp" #include "t_5_035.hpp" ZX //R 1 /*- * Copyright (c) 1998, 2002-2005 Kiyoshi Matsui <kmatsui@t3.rim.or.jp> * 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 THE AUTHOR ``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 AUTHOR 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. */
// The API isBadVersion is defined for you. // bool isBadVersion(int version); class Solution { public: int firstBadVersion(int n) { int low=1; int high=n; while(low<=high){ int mid; mid=low+(high-low)/2; if(isBadVersion(mid)) high=mid-1; else low=mid+1; } return low; } };
#include "plansys2_pddl_parser/Domain.h" namespace parser { namespace pddl { void Exists::PDDLPrint( std::ostream & s, unsigned indent, const TokenStruct< std::string > & ts, const Domain & d ) const { tabindent( s, indent ); s << "( exists\n"; TokenStruct< std::string > fstruct( ts ); tabindent( s, indent + 1 ); printParams( 0, s, fstruct, d ); if ( cond ) cond->PDDLPrint( s, indent + 1, fstruct, d ); else { tabindent( s, indent + 1 ); s << "()"; } s << "\n"; tabindent( s, indent ); s << ")"; } plansys2_msgs::msg::Node::SharedPtr Exists::getTree( plansys2_msgs::msg::Tree & tree, const Domain & d, const std::vector<std::string> & replace ) const { throw UnsupportedConstruct("Exists"); } void Exists::parse( Stringreader & f, TokenStruct< std::string > & ts, Domain & d ) { f.next(); f.assert_token( "(" ); TokenStruct< std::string > es = f.parseTypedList( true, d.types ); params = d.convertTypes( es.types ); TokenStruct< std::string > estruct( ts ); estruct.append( es ); f.next(); f.assert_token( "(" ); if ( f.getChar() != ')' ) { cond = d.createCondition( f ); cond->parse( f, estruct, d ); } else ++f.c; f.next(); f.assert_token( ")" ); } } } // namespaces
/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2012 Torus Knot Software Ltd 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 "OgreStableHeaders.h" #include "OgrePointEmitter.h" #include "OgreParticle.h" namespace Ogre { //----------------------------------------------------------------------- PointEmitter::PointEmitter(ParticleSystem* psys) :ParticleEmitter(psys) { mType = "Point"; // Set up parameters if (createParamDictionary("PointEmitter")) { addBaseParameters(); } // No custom parameters } //----------------------------------------------------------------------- void PointEmitter::_initParticle(Particle* pParticle) { // Very simple emitter, uses default implementations with no modification // Call superclass ParticleEmitter::_initParticle(pParticle); // Point emitter emits from own position pParticle->position = mPosition; // Generate complex data by reference genEmissionColour(pParticle->colour); genEmissionDirection(pParticle->direction); genEmissionVelocity(pParticle->direction); // Generate simpler data pParticle->timeToLive = pParticle->totalTimeToLive = genEmissionTTL(); } //----------------------------------------------------------------------- unsigned short PointEmitter::_getEmissionCount(Real timeElapsed) { // Use basic constant emission return genConstantEmissionCount(timeElapsed); } }
/* Copyright (c) 2009-2016, Jack Poulson All rights reserved. This file is part of Elemental and is under the BSD 2-Clause License, which can be found in the LICENSE file in the root directory, or at http://opensource.org/licenses/BSD-2-Clause */ #ifndef EL_DETERMINANT_CHOLESKY_HPP #define EL_DETERMINANT_CHOLESKY_HPP namespace El { namespace hpd_det { template<typename F> SafeProduct<Base<F>> AfterCholesky ( UpperOrLower uplo, const Matrix<F>& A ) { DEBUG_CSE typedef Base<F> Real; const Int n = A.Height(); Matrix<F> d; GetDiagonal( A, d ); SafeProduct<Real> det( n ); det.rho = Real(1); const Real scale = Real(n)/Real(2); for( Int i=0; i<n; ++i ) { const Real delta = RealPart(d(i)); det.kappa += Log(delta)/scale; } return det; } template<typename F> SafeProduct<Base<F>> Cholesky( UpperOrLower uplo, Matrix<F>& A ) { DEBUG_CSE SafeProduct<Base<F>> det( A.Height() ); try { El::Cholesky( uplo, A ); det = hpd_det::AfterCholesky( uplo, A ); } catch( NonHPDMatrixException& e ) { det.rho = 0; det.kappa = 0; } return det; } template<typename F> SafeProduct<Base<F>> AfterCholesky ( UpperOrLower uplo, const ElementalMatrix<F>& APre ) { DEBUG_CSE DistMatrixReadProxy<F,F,MC,MR> AProx( APre ); auto& A = AProx.GetLocked(); typedef Base<F> Real; const Int n = A.Height(); const Grid& g = A.Grid(); DistMatrix<F,MD,STAR> d(g); GetDiagonal( A, d ); Real localKappa = 0; if( d.Participating() ) { const Real scale = Real(n)/Real(2); const Int nLocalDiag = d.LocalHeight(); for( Int iLoc=0; iLoc<nLocalDiag; ++iLoc ) { const Real delta = RealPart(d.GetLocal(iLoc,0)); localKappa += Log(delta)/scale; } } SafeProduct<Real> det( n ); det.kappa = mpi::AllReduce( localKappa, g.VCComm() ); det.rho = Real(1); return det; } template<typename F> SafeProduct<Base<F>> Cholesky( UpperOrLower uplo, ElementalMatrix<F>& APre ) { DEBUG_CSE DistMatrixReadProxy<F,F,MC,MR> AProx( APre ); auto& A = AProx.Get(); SafeProduct<Base<F>> det( A.Height() ); try { El::Cholesky( uplo, A ); det = hpd_det::AfterCholesky( uplo, A ); } catch( NonHPDMatrixException& e ) { det.rho = 0; det.kappa = 0; } return det; } } // namespace hpd_det } // namespace El #endif // ifndef EL_DETERMINANT_CHOLESKY_HPP
// // This source file is part of appleseed. // Visit https://appleseedhq.net/ for additional information and resources. // // This software is released under the MIT license. // // Copyright (c) 2010-2013 Francois Beaune, Jupiter Jazz Limited // Copyright (c) 2014-2018 Francois Beaune, The appleseedhq Organization // // 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. // // Interface header. #include "latlongmapenvironmentedf.h" // appleseed.renderer headers. #include "renderer/global/globallogger.h" #include "renderer/global/globaltypes.h" #include "renderer/kernel/shading/shadingcontext.h" #include "renderer/kernel/texturing/texturecache.h" #include "renderer/kernel/texturing/texturestore.h" #include "renderer/modeling/color/colorspace.h" #include "renderer/modeling/environmentedf/environmentedf.h" #include "renderer/modeling/environmentedf/sphericalcoordinates.h" #include "renderer/modeling/input/inputarray.h" #include "renderer/modeling/input/source.h" #include "renderer/modeling/input/sourceinputs.h" #include "renderer/modeling/project/project.h" #include "renderer/modeling/scene/scene.h" #include "renderer/utility/paramarray.h" #include "renderer/utility/transformsequence.h" // appleseed.foundation headers. #include "foundation/image/color.h" #include "foundation/image/colorspace.h" #include "foundation/math/fp.h" #include "foundation/math/matrix.h" #include "foundation/math/sampling/imageimportancesampler.h" #include "foundation/math/scalar.h" #include "foundation/math/transform.h" #include "foundation/math/vector.h" #include "foundation/platform/compiler.h" #include "foundation/platform/defaulttimers.h" #include "foundation/platform/types.h" #include "foundation/utility/api/apistring.h" #include "foundation/utility/api/specializedapiarrays.h" #include "foundation/utility/containers/dictionary.h" #include "foundation/utility/job/abortswitch.h" #include "foundation/utility/stopwatch.h" #include "foundation/utility/string.h" // Standard headers. #include <cassert> #include <cmath> #include <cstddef> #include <memory> // Forward declarations. namespace renderer { class OnFrameBeginRecorder; } using namespace foundation; using namespace std; namespace renderer { namespace { // // Latitude-longitude environment map EDF. // // Reference: // // http://www.cs.virginia.edu/~gfx/courses/2007/ImageSynthesis/assignments/envsample.pdf // // Light probes: // // http://gl.ict.usc.edu/Data/HighResProbes/ // http://www.cs.kuleuven.be/~graphics/index.php/environment-maps // typedef ImageImportanceSampler<Color3f, float> ImageImportanceSamplerType; class ImageSampler { public: ImageSampler( TextureCache& texture_cache, const Source* radiance_source, const Source* multiplier_source, const Source* exposure_source, const Source* exposure_multiplier_source, const size_t width, const size_t height) : m_texture_cache(texture_cache) , m_radiance_source(radiance_source) , m_multiplier_source(multiplier_source) , m_exposure_source(exposure_source) , m_exposure_multiplier_source(exposure_multiplier_source) , m_rcp_width(1.0f / width) , m_rcp_height(1.0f / height) { } void sample(const size_t x, const size_t y, Color3f& payload, float& importance) { if (m_radiance_source == nullptr) { payload.set(0.0f); importance = 0.0f; return; } const Vector2f uv( (x + 0.5f) * m_rcp_width, 1.0f - (y + 0.5f) * m_rcp_height); m_radiance_source->evaluate(m_texture_cache, SourceInputs(uv), payload); if (is_finite(payload)) { float multiplier; m_multiplier_source->evaluate(m_texture_cache, SourceInputs(uv), multiplier); float exposure; m_exposure_source->evaluate(m_texture_cache, SourceInputs(uv), exposure); float exposure_multiplier; m_exposure_multiplier_source->evaluate_uniform(exposure_multiplier); payload *= multiplier * pow(2.0f, exposure * exposure_multiplier); importance = luminance(payload); } else { payload.set(0.0f); importance = 0.0f; } } private: TextureCache& m_texture_cache; const Source* m_radiance_source; const Source* m_multiplier_source; const Source* m_exposure_source; const Source* m_exposure_multiplier_source; const float m_rcp_width; const float m_rcp_height; }; const char* Model = "latlong_map_environment_edf"; class LatLongMapEnvironmentEDF : public EnvironmentEDF { public: LatLongMapEnvironmentEDF( const char* name, const ParamArray& params) : EnvironmentEDF(name, params) , m_importance_map_width(0) , m_importance_map_height(0) , m_probability_scale(0.0f) { m_inputs.declare("radiance", InputFormatSpectralIlluminance); m_inputs.declare("radiance_multiplier", InputFormatFloat, "1.0"); m_inputs.declare("exposure", InputFormatFloat, "0.0"); m_inputs.declare("exposure_multiplier", InputFormatFloat, "1.0"); m_phi_shift = deg_to_rad(m_params.get_optional<float>("horizontal_shift", 0.0f)); m_theta_shift = deg_to_rad(m_params.get_optional<float>("vertical_shift", 0.0f)); } void release() override { delete this; } const char* get_model() const override { return Model; } bool on_frame_begin( const Project& project, const BaseGroup* parent, OnFrameBeginRecorder& recorder, IAbortSwitch* abort_switch) override { if (!EnvironmentEDF::on_frame_begin(project, parent, recorder, abort_switch)) return false; // Do not build an importance map if the environment EDF is not the active one. const Environment* environment = project.get_scene()->get_environment(); if (environment->get_uncached_environment_edf() == this) { check_non_zero_emission("radiance", "radiance_multiplier"); if (m_importance_sampler.get() == nullptr) build_importance_map(*project.get_scene(), abort_switch); } return true; } void sample( const ShadingContext& shading_context, const Vector2f& s, Vector3f& outgoing, Spectrum& value, float& probability) const override { if (m_importance_sampler.get() == nullptr) { RENDERER_LOG_WARNING( "cannot sample environment edf \"%s\" because it is not bound to the environment.", get_path().c_str()); value.set(0.0f); probability = 0.0f; return; } // Sample the importance map. size_t x, y; Color3f payload; float prob_xy; m_importance_sampler->sample(s, x, y, payload, prob_xy); // Compute the coordinates in [0,1]^2 of the sample. const float u = (x + 0.5f) * m_rcp_importance_map_width; const float v = (y + 0.5f) * m_rcp_importance_map_height; // Compute the spherical coordinates of the sample. float theta, phi; unit_square_to_angles(u, v, theta, phi); shift_angles(theta, phi, m_theta_shift, m_phi_shift); // Compute the local space emission direction. const float cos_theta = cos(theta); const float sin_theta = sin(theta); const float cos_phi = cos(phi); const float sin_phi = sin(phi); const Vector3f local_outgoing = Vector3f::make_unit_vector(cos_theta, sin_theta, cos_phi, sin_phi); // Transform the emission direction to world space. Transformd scratch; const Transformd& transform = m_transform_sequence.evaluate(0.0f, scratch); outgoing = transform.vector_to_parent(local_outgoing); // Return the emitted radiance. value.set(payload, g_std_lighting_conditions, Spectrum::Illuminance); // Compute the probability density of this direction. probability = prob_xy * m_probability_scale / sin_theta; } void evaluate( const ShadingContext& shading_context, const Vector3f& outgoing, Spectrum& value) const override { assert(is_normalized(outgoing)); // Transform the emission direction to local space. Transformd scratch; const Transformd& transform = m_transform_sequence.evaluate(0.0f, scratch); const Vector3f local_outgoing = transform.vector_to_local(outgoing); // Compute the spherical coordinates of the outgoing direction. float theta, phi; unit_vector_to_angles(local_outgoing, theta, phi); shift_angles(theta, phi, -m_theta_shift, -m_phi_shift); // Convert the spherical coordinates to [0,1]^2. float u, v; angles_to_unit_square(theta, phi, u, v); // Compute and return the environment color. lookup_environment_map(shading_context, u, v, value); } void evaluate( const ShadingContext& shading_context, const Vector3f& outgoing, Spectrum& value, float& probability) const override { assert(is_normalized(outgoing)); if (m_importance_sampler.get() == nullptr) { RENDERER_LOG_WARNING( "cannot compute pdf for environment edf \"%s\" because it is not bound to the environment.", get_path().c_str()); value.set(0.0f); probability = 0.0f; return; } // Transform the emission direction to local space. Transformd scratch; const Transformd& transform = m_transform_sequence.evaluate(0.0f, scratch); const Vector3f local_outgoing = transform.vector_to_local(outgoing); // Compute the spherical coordinates of the outgoing direction. float theta, phi; unit_vector_to_angles(local_outgoing, theta, phi); shift_angles(theta, phi, -m_theta_shift, -m_phi_shift); // Convert the spherical coordinates to [0,1]^2. float u, v; angles_to_unit_square(theta, phi, u, v); // Compute and return the environment color and the PDF value. lookup_environment_map(shading_context, u, v, value); probability = compute_pdf(u, v, theta); } float evaluate_pdf( const Vector3f& outgoing) const override { assert(is_normalized(outgoing)); if (m_importance_sampler.get() == nullptr) { RENDERER_LOG_WARNING( "cannot compute pdf for environment edf \"%s\" because it is not bound to the environment.", get_path().c_str()); return 0.0f; } // Transform the emission direction to local space. Transformd scratch; const Transformd& transform = m_transform_sequence.evaluate(0.0f, scratch); const Vector3f local_outgoing = transform.vector_to_local(outgoing); // Compute the spherical coordinates of the outgoing direction. float theta, phi; unit_vector_to_angles(local_outgoing, theta, phi); shift_angles(theta, phi, -m_theta_shift, -m_phi_shift); // Convert the spherical coordinates to [0,1]^2. float u, v; angles_to_unit_square(theta, phi, u, v); // Compute and return the PDF value. return compute_pdf(u, v, theta); } private: APPLESEED_DECLARE_INPUT_VALUES(InputValues) { Spectrum m_radiance; // emitted radiance in W.m^-2.sr^-1 float m_radiance_multiplier; // emitted radiance multiplier float m_exposure; // emitted radiance multiplier in f-stops float m_exposure_multiplier; // emitted radiance exposure multiplier }; float m_phi_shift; // horizontal shift in radians float m_theta_shift; // vertical shift in radians size_t m_importance_map_width; size_t m_importance_map_height; float m_rcp_importance_map_width; float m_rcp_importance_map_height; float m_probability_scale; unique_ptr<ImageImportanceSamplerType> m_importance_sampler; void build_importance_map(const Scene& scene, IAbortSwitch*abort_switch) { Stopwatch<DefaultWallclockTimer> stopwatch; stopwatch.start(); const Source* radiance_source = m_inputs.source("radiance"); assert(radiance_source); const Source::Hints radiance_source_hints = radiance_source->get_hints(); m_importance_map_width = radiance_source_hints.m_width; m_importance_map_height = radiance_source_hints.m_height; m_rcp_importance_map_width = 1.0f / m_importance_map_width; m_rcp_importance_map_height = 1.0f / m_importance_map_height; const size_t texel_count = m_importance_map_width * m_importance_map_height; m_probability_scale = texel_count / (2.0f * PiSquare<float>()); TextureStore texture_store(scene); TextureCache texture_cache(texture_store); ImageSampler sampler( texture_cache, radiance_source, m_inputs.source("radiance_multiplier"), m_inputs.source("exposure"), m_inputs.source("exposure_multiplier"), m_importance_map_width, m_importance_map_height); m_importance_sampler.reset( new ImageImportanceSamplerType( m_importance_map_width, m_importance_map_height)); RENDERER_LOG_INFO( "building " FMT_SIZE_T "x" FMT_SIZE_T " importance map " "for environment edf \"%s\"...", m_importance_map_width, m_importance_map_height, get_path().c_str()); m_importance_sampler->rebuild(sampler, abort_switch); if (is_aborted(abort_switch)) m_importance_sampler.reset(); else { stopwatch.measure(); RENDERER_LOG_INFO( "built importance map for environment edf \"%s\" in %s.", get_path().c_str(), pretty_time(stopwatch.get_seconds()).c_str()); } } void lookup_environment_map( const ShadingContext& shading_context, const float u, const float v, Spectrum& value) const { assert(u >= 0.0f && u < 1.0f); assert(v >= 0.0f && v < 1.0f); InputValues values; m_inputs.evaluate(shading_context.get_texture_cache(), SourceInputs(Vector2f(u, 1.0f - v)), &values); if (is_finite(values.m_radiance)) { value = values.m_radiance; value *= values.m_radiance_multiplier * pow(2.0f, values.m_exposure * values.m_exposure_multiplier); } else value.set(0.0f); } float compute_pdf( const float u, const float v, const float theta) const { assert(u >= 0.0f && u < 1.0f); assert(v >= 0.0f && v < 1.0f); assert(m_importance_sampler.get()); // Compute the probability density of this sample in the importance map. const size_t x = truncate<size_t>(m_importance_map_width * u); const size_t y = truncate<size_t>(m_importance_map_height * v); const float prob_xy = m_importance_sampler->get_pdf(x, y); // Compute the probability density of the emission direction. return prob_xy * m_probability_scale / sin(theta); } }; } // // LatLongMapEnvironmentEDFFactory class implementation. // void LatLongMapEnvironmentEDFFactory::release() { delete this; } const char* LatLongMapEnvironmentEDFFactory::get_model() const { return Model; } Dictionary LatLongMapEnvironmentEDFFactory::get_model_metadata() const { return Dictionary() .insert("name", Model) .insert("label", "Latitude-Longitude Map Environment EDF") .insert("help", "Sky dome environment"); } DictionaryArray LatLongMapEnvironmentEDFFactory::get_input_metadata() const { DictionaryArray metadata; metadata.push_back( Dictionary() .insert("name", "radiance") .insert("label", "Radiance") .insert("type", "colormap") .insert("entity_types", Dictionary() .insert("texture_instance", "Texture Instances")) .insert("use", "required") .insert("default", "1.0") .insert("help", "Environment texture")); metadata.push_back( Dictionary() .insert("name", "radiance_multiplier") .insert("label", "Radiance Multiplier") .insert("type", "colormap") .insert("entity_types", Dictionary().insert("texture_instance", "Texture Instances")) .insert("use", "optional") .insert("default", "1.0") .insert("help", "Environment texture radiance multiplier")); metadata.push_back( Dictionary() .insert("name", "exposure") .insert("label", "Exposure") .insert("type", "colormap") .insert("entity_types", Dictionary().insert("texture_instance", "Texture Instances")) .insert("use", "optional") .insert("default", "0.0") .insert("help", "Environment exposure")); metadata.push_back( Dictionary() .insert("name", "exposure_multiplier") .insert("label", "Exposure Multiplier") .insert("type", "numeric") .insert("min", Dictionary() .insert("value", "-64.0") .insert("type", "soft")) .insert("max", Dictionary() .insert("value", "64.0") .insert("type", "soft")) .insert("default", "1.0") .insert("use", "optional") .insert("help", "Environment exposure multiplier")); metadata.push_back( Dictionary() .insert("name", "horizontal_shift") .insert("label", "Horizontal Shift") .insert("type", "numeric") .insert("min", Dictionary() .insert("value", "-360.0") .insert("type", "soft")) .insert("max", Dictionary() .insert("value", "360.0") .insert("type", "soft")) .insert("default", "0.0") .insert("use", "optional") .insert("help", "Environment texture horizontal shift in degrees")); metadata.push_back( Dictionary() .insert("name", "vertical_shift") .insert("label", "Vertical Shift") .insert("type", "numeric") .insert("min", Dictionary() .insert("value", "-360.0") .insert("type", "soft")) .insert("max", Dictionary() .insert("value", "360.0") .insert("type", "soft")) .insert("default", "0.0") .insert("use", "optional") .insert("help", "Environment texture vertical shift in degrees")); return metadata; } auto_release_ptr<EnvironmentEDF> LatLongMapEnvironmentEDFFactory::create( const char* name, const ParamArray& params) const { return auto_release_ptr<EnvironmentEDF>( new LatLongMapEnvironmentEDF(name, params)); } } // namespace renderer
#include <bits/stdc++.h> using namespace std; int main() { while(true) { string s; cin >> s; if(s == "*") break; int res = 0; float sum = 0.0; for (int i = 0; i < s.size(); ++i) { if(s[i] == '/') { if(sum == 1.0) res++; sum = 0.0; } switch (s[i]) { case 'W': sum += 1.0; break; case 'H': sum += 1/2.0; break; case 'Q': sum += 1/4.0; break; case 'E': sum += 1/8.0; break; case 'S': sum += 1/16.0; break; case 'T': sum += 1/32.0; break; case 'X': sum += 1/64.0; break; } } cout << res << endl; } return 0; }
#include "stdafx.h" #include <iostream> int x; int y; int sum; int console; #include <time.h> using namespace std; int factorial(int x) { if (x == 1) { return 1; } else { return x * factorial(x - 1); } } int main() { cout << "Calculator rev1.0\n"; cout << "Write command.\nFor help write '5'\nDon't TRY TO WRITE WORDS!!!\nONLY NUMBERS!!!\nLike:help and other...\n\n\nroot@calculator-unstable:~# "; cin >> console; if (console == 1) { cout << "Write number\n"; cin >> x; cout << "Write twice number\n"; cin >> y; sum = x + y; cout << "Sum:" << sum << " \n"; main(); } if (console == 2) { cout << "Write number\n"; cin >> x; cout << "Write twice number\n"; cin >> y; sum = x * y; cout << "Multiplication:" << sum << " \n"; main(); } if (console == 3) { cout << "Write number\n"; cin >> x; cout << "Write twice number\n"; cin >> y; sum = x - y; cout << "Subtraction:" << sum << " \n"; main(); } if (console == 4) { cout << "Write number\n"; cin >> x; cout << "Write twice number\n"; cin >> y; sum = x / y; cout << "Division:" << sum << " \n"; main(); } if (console == 5) { cout << "Commands\n 1 - Sum\n 2 - Multiplication Y\n 3 - Subtraction\n 4 - Division\n 5 - Help\n 6 - Close\n 7 - Factorial\n Ctrl+C - Emergency stop\n"; main(); } if (console == 6) { exit(0); } if (console == 7) { cout << "Write number\n !"; cin >> x; if (factorial(x) == 0) { cout << "Too many numbers...\n"; } else{cout << "Factorial:" << factorial(x) << " \n"; } main(); } else { cout << "Error Command\n"; return 0; } }
/* * Warhammer Age of Sigmar battle simulator. * * Copyright (C) 2019 by Rick Weyrauch - rpweyrauch@gmail.com * * This code is licensed under the MIT license (MIT) (http://opensource.org/licenses/MIT) */ #include <gloomspitegitz/Mollog.h> #include <UnitFactory.h> #include <Board.h> #include "GloomspitePrivate.h" namespace GloomspiteGitz { static const int g_basesize = 50; static const int g_wounds = 8; static const int g_pointsPerUnit = 175; bool Mollog::s_registered = false; Unit *Mollog::Create(const ParameterList &parameters) { auto allegiance = (Allegiance) GetEnumParam("Allegiance", parameters, g_allegiance[0]); auto general = GetBoolParam("General", parameters, false); return new Mollog(allegiance, general); } void Mollog::Init() { if (!s_registered) { static FactoryMethod factoryMethod = { Create, GloomspiteGitzBase::ValueToString, GloomspiteGitzBase::EnumStringToInt, ComputePoints, { BoolParameter("General"), EnumParameter("Allegiance", g_allegiance[0], g_allegiance), }, DESTRUCTION, {GLOOMSPITE_GITZ} }; s_registered = UnitFactory::Register("Mollog", factoryMethod); } } int Mollog::ComputePoints(const ParameterList& /*parameters*/) { return g_pointsPerUnit; } Mollog::Mollog(Allegiance allegiance, bool isGeneral) : GloomspiteGitzBase(allegiance, "Mollog", 6, g_wounds, 7, 4, false, g_pointsPerUnit), m_jabbertoad(Weapon::Type::Missile, "Jabbertoad", 12, 1, 4, 4, 0, 1), m_club(Weapon::Type::Melee, "Puff-fungus Club", 1, 2, 0, 0, 0, 0) { m_keywords = {DESTRUCTION, TROGGOTH, GLOOMSPITE_GITZ, DANKHOLD, HERO, MOLLOG}; m_weapons = {&m_jabbertoad, &m_club}; m_battleFieldRole = Role::Leader; s_globalBraveryMod.connect(this, &Mollog::reassuringPresence, &m_connection); setGeneral(isGeneral); auto model = new Model(g_basesize, wounds()); model->addMissileWeapon(&m_jabbertoad); model->addMeleeWeapon(&m_club); addModel(model); } Mollog::~Mollog() { m_connection.disconnect(); } void Mollog::onStartHero(PlayerId player) { GloomspiteGitzBase::onStartHero(player); if (player == owningPlayer()) { if (remainingWounds() < g_wounds && remainingWounds() > 0) { // Regeneration - heal D3 // Troggoth Renewal if (Dice::RollD6() >= 4 || (inLightOfTheBadMoon() && (Dice::RollD6() >= 4))) { int woundsHealed = Dice::RollD3(); if (inLightOfTheBadMoon()) woundsHealed *= 2; for (auto &m : m_models) { m->applyHealing(woundsHealed); } } } } } int Mollog::reassuringPresence(const Unit *unit) { // Reassuring Presence if (unit->hasKeyword(GLOOMSPITE_GITZ) && isFriendly(unit) && (distanceTo(unit) <= 12.0)) { return 1; } return 0; } Wounds Mollog::applyWoundSave(const Wounds &wounds, Unit *attackingUnit) { // Magical Resistance if (wounds.source == Wounds::Source::Spell) { if (Dice::RollD6() >= 4) { return {0, 0, Wounds::Source::Spell}; } } auto totalWounds = GloomspiteGitzBase::applyWoundSave(wounds, attackingUnit); // Loyal to the End if (m_batSquig) { if (totalWounds.mortal > 0) { totalWounds.mortal--; m_batSquig = false; } else if (totalWounds.normal > 0) { totalWounds.normal--; m_batSquig = false; } } if (m_spiteshroom) { if (totalWounds.mortal > 0) { totalWounds.mortal--; m_spiteshroom = false; } else if (totalWounds.normal > 0) { totalWounds.normal--; m_spiteshroom = false; } } if (m_stalagsquig) { const auto roll = Dice::RollD6(); if (totalWounds.mortal > 0) { totalWounds.mortal--; if (roll < 5) m_stalagsquig = false; } else if (totalWounds.normal > 0) { totalWounds.normal--; if (roll < 5) m_stalagsquig = false; } } return totalWounds; } void Mollog::onRestore() { GloomspiteGitzBase::onRestore(); m_batSquig = true; m_spiteshroom = true; m_stalagsquig = true; } void Mollog::onStartShooting(PlayerId player) { GloomspiteGitzBase::onStartShooting(player); if (owningPlayer() == player) { if (m_batSquig) { auto unit = Board::Instance()->getNearestUnit(this, GetEnemyId(owningPlayer())); if (unit && (distanceTo(unit) <= 18.0)) { if (Dice::RollD6() >= 5) { unit->applyDamage({0, 1}, this); } } } } } void Mollog::onStartCombat(PlayerId player) { GloomspiteGitzBase::onStartCombat(player); if (m_spiteshroom) { auto unit = Board::Instance()->getNearestUnit(this, GetEnemyId(owningPlayer())); if (unit && (distanceTo(unit) <= 3.0)) { if (Dice::RollD6() >= 5) { unit->buffModifier(Attribute::To_Hit_Melee, -1, {GamePhase::Combat, m_battleRound, player}); } } } } } // namespace GloomspiteGitz
// 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. #ifdef HAVE_CONFIG_H #include <config/neon-config.h> #endif #include <qt/walletmodeltransaction.h> #include <policy/policy.h> WalletModelTransaction::WalletModelTransaction(const QList<SendCoinsRecipient> &_recipients) : recipients(_recipients), fee(0) { } QList<SendCoinsRecipient> WalletModelTransaction::getRecipients() const { return recipients; } CTransactionRef& WalletModelTransaction::getWtx() { return wtx; } unsigned int WalletModelTransaction::getTransactionSize() { return wtx ? GetVirtualTransactionSize(*wtx) : 0; } CAmount WalletModelTransaction::getTransactionFee() const { return fee; } void WalletModelTransaction::setTransactionFee(const CAmount& newFee) { fee = newFee; } void WalletModelTransaction::reassignAmounts(int nChangePosRet) { const CTransaction* walletTransaction = wtx.get(); int i = 0; for (QList<SendCoinsRecipient>::iterator it = recipients.begin(); it != recipients.end(); ++it) { SendCoinsRecipient& rcp = (*it); { if (i == nChangePosRet) i++; rcp.amount = walletTransaction->vout[i].nValue; i++; } } } CAmount WalletModelTransaction::getTotalTransactionAmount() const { CAmount totalTransactionAmount = 0; for (const SendCoinsRecipient &rcp : recipients) { totalTransactionAmount += rcp.amount; } return totalTransactionAmount; }
// Delete all of the text. m_myRichEditCtrl.SetSel(0, -1); m_myRichEditCtrl.Clear();
// Copyright (C) 2018 Intel Corporation // // // SPDX-License-Identifier: Apache-2.0 // /// @file check_cycles.hpp #ifndef ADE_CHECK_CYCLES_HPP #define ADE_CHECK_CYCLES_HPP #include <exception> #include <string> #include "ade/passes/pass_base.hpp" namespace ade { namespace passes { class CycleFound : public std::exception { public: virtual const char* what() const noexcept override; }; struct CheckCycles { void operator()(const PassContext& context) const; static std::string name(); }; } } #endif // ADE_CHECK_CYCLES_HPP
#include "GAMER.h" #ifdef STAR_FORMATION static RandomNumber_t *RNG = NULL; //------------------------------------------------------------------------------------------------------- // Function : SF_CreateStar // Description : Interface for invoking various star-formation routines // // Note : 1. Invoked by EvolveLevel() // 2. Allocate NT thread-safe random number generators the first time this function is called, // where NT is the number of OpenMP threads // --> Must be freed by calling SF_FreeRNG() manually // // Parameter : lv : Target refinement level // TimeNew : Current physical time (after advancing solution by dt) // dt : Time interval to advance solution // --> Currently this function does not distinguish dt and the physical time interval (dTime) //------------------------------------------------------------------------------------------------------- void SF_CreateStar( const int lv, const real TimeNew, const real dt ) { // only form stars on levels above the given minimum level if ( lv < SF_CREATE_STAR_MIN_LEVEL ) return; // initialiez the random number generators the first time this function is called static bool FirstTime = true; if ( FirstTime ) { // get the number of OpenMP threads int NT; # ifdef OPENMP # pragma omp parallel # pragma omp master { NT = omp_get_num_threads(); } # else { NT = 1; } # endif // allocate RNG RNG = new RandomNumber_t( NT ); // make sure that different threads in different MPI ranks have different random seeds // --> even when SF_CREATE_STAR_DET_RANDOM is enabled, we still set random seeds here just in case that not all // star formation methods support SF_CREATE_STAR_DET_RANDOM for (int t=0; t<NT; t++) { const long RSeed = SF_CREATE_STAR_RSEED + MPI_Rank*1000 + t; RNG->SetSeed( t, RSeed ); } FirstTime = false; } // determine if metallicity is included const bool UseMetal = ( Idx_Metal != Idx_Undefined ); // invoke the target star-formation method switch ( SF_CREATE_STAR_SCHEME ) { # if ( MODEL == HYDRO ) case SF_CREATE_STAR_SCHEME_AGORA: SF_CreateStar_AGORA( lv, TimeNew, dt, RNG, SF_CREATE_STAR_MIN_GAS_DENS, SF_CREATE_STAR_MASS_EFF, SF_CREATE_STAR_MIN_STAR_MASS, SF_CREATE_STAR_MAX_STAR_MFRAC, SF_CREATE_STAR_DET_RANDOM, UseMetal ); break; # endif case SF_CREATE_STAR_SCHEME_NONE: return; break; default : Aux_Error( ERROR_INFO, "incorrect parameter %s = %d !!\n", "SF_CREATE_STAR_SCHEME", SF_CREATE_STAR_SCHEME ); } // switch ( SF_CREATE_STAR_SCHEME ) } // FUNCTION : SF_CreateStar //------------------------------------------------------------------------------------------------------- // Function : SF_FreeRNG // Description : Free the random number generator allocated by SF_CreateStar() // // Note : 1. Invoked by End_MemFree() // // Parameter : None // // Return : None //------------------------------------------------------------------------------------------------------- void SF_FreeRNG() { delete RNG; RNG = NULL; } // FUNCTION : SF_FreeRNG #endif // #ifdef STAR_FORMATION
// Copyright 2014 John Maddock. 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_ #ifndef BOOST_MP_MATH_SETUP_HPP #define BOOST_MP_MATH_SETUP_HPP #ifdef _MSC_VER # define _SCL_SECURE_NO_WARNINGS #endif #define BOOST_MATH_OVERFLOW_ERROR_POLICY ignore_error #include <boost/cstdfloat.hpp> #include <boost/static_assert.hpp> #define ALL_TESTS test(boost::floatmax_t(0), "boost::floatmax_t"); typedef boost::floatmax_t test_type_1; BOOST_STATIC_ASSERT_MSG(std::numeric_limits<boost::floatmax_t>::digits == 113, "These tests should only be run for 128-bit floating point types."); #ifndef BOOST_MATH_TEST_TYPE #define BOOST_TEST_MAIN #include <boost/test/unit_test.hpp> #include <boost/test/tools/floating_point_comparison.hpp> #endif #endif
// ---------------------------------------------------------------------------- // - Open3D: www.open3d.org - // ---------------------------------------------------------------------------- // The MIT License (MIT) // // Copyright (c) 2018-2021 www.open3d.org // // 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 "open3d/Open3D.h" void PrintHelp() { using namespace open3d; PrintOpen3DVersion(); // clang-format off utility::LogInfo("Usage:"); utility::LogInfo(" > ManuallyCropGeometry [--pointcloud/mesh] geometry_file [options]"); utility::LogInfo(" Manually crop geometry in speficied file."); utility::LogInfo(""); utility::LogInfo("Options:"); utility::LogInfo(" --pointcloud, : Read geometry as point cloud."); utility::LogInfo(" --mesh, : Read geometry as mesh."); utility::LogInfo(" --help, -h : Print help information."); utility::LogInfo(" --verbose n : Set verbose level (0-4)."); utility::LogInfo(" --voxel_size d : Set downsample voxel size."); utility::LogInfo(" --without_dialog : Disable dialogs. Default files will be used."); // clang-format on } int main(int argc, char **argv) { using namespace open3d; if (argc < 2 || utility::ProgramOptionExists(argc, argv, "--help") || utility::ProgramOptionExists(argc, argv, "-h")) { PrintHelp(); return 0; } int verbose = utility::GetProgramOptionAsInt(argc, argv, "--verbose", 2); utility::SetVerbosityLevel((utility::VerbosityLevel)verbose); double voxel_size = utility::GetProgramOptionAsDouble(argc, argv, "--voxel_size", -1.0); bool with_dialog = !utility::ProgramOptionExists(argc, argv, "--without_dialog"); visualization::VisualizerWithEditing vis( voxel_size, with_dialog, utility::filesystem::GetFileParentDirectory(argv[1])); vis.CreateVisualizerWindow("Crop Point Cloud", 1920, 1080, 100, 100); if (utility::ProgramOptionExists(argc, argv, "--pointcloud")) { auto pcd_ptr = io::CreatePointCloudFromFile(argv[2]); if (pcd_ptr == nullptr || pcd_ptr->IsEmpty()) { utility::LogWarning("Failed to read the point cloud."); return 1; } vis.AddGeometry(pcd_ptr); if (pcd_ptr->points_.size() > 5000000) { vis.GetRenderOption().point_size_ = 1.0; } } else if (utility::ProgramOptionExists(argc, argv, "--mesh")) { auto mesh_ptr = io::CreateMeshFromFile(argv[2]); if (mesh_ptr == nullptr || mesh_ptr->IsEmpty()) { utility::LogWarning("Failed to read the mesh."); return 1; } vis.AddGeometry(mesh_ptr); } vis.Run(); vis.DestroyVisualizerWindow(); return 0; }
// Supported with union (c) 2020 Union team // User API for zCGameInfo // Add your methods here
// Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // 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: kenton@google.com (Kenton Varda) // Based on original Protocol Buffers design by // Sanjay Ghemawat, Jeff Dean, and others. #include <google/protobuf/unittest.pb.h> #define MESSAGE_TEST_NAME MessageTest #define MESSAGE_FACTORY_TEST_NAME MessageFactoryTest #define UNITTEST_PACKAGE_NAME "protobuf_unittest" #define UNITTEST ::protobuf_unittest #define UNITTEST_IMPORT ::protobuf_unittest_import // Must include after the above macros. // clang-format off #include <google/protobuf/test_util.inc> #include <google/protobuf/message_unittest.inc> #include <google/protobuf/arena.h> // clang-format on
/** * @file pruHandler.hpp * @brief Process which communicates with the PRU that controlls quadrotor ESCs. This process connects to applications via TCP packets over localhost and relays the data to the PRU. If no program is active, zero throttle is sent. * * @author Mike Sardonini * @date 11/10/2018 */ #ifndef PRU_HANDLER_H_ #define PRU_HANDLER_H_ //System Includes #include <thread> #include <fcntl.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <signal.h> #include <errno.h> #include <string.h> #include <sys/types.h> #include <time.h> #include <fstream> //Package Includes #include <rc/servo.h> #include <rc/pthread.h> #include <rc/time.h> #define PID_FILE_PRU "/var/run/pru_handler.pid" #define LOG_FILE_PRU "/var/log/pru_handler.log" #define PRU_PORT 5000 #define PRU_NUM_CHANNELS 4 enum class PruState { UNINITIALIZED, RUNNING, PAUSED, EXITING }; class pruHandler { public: //Default Constructor pruHandler(); //Default Destructor ~pruHandler(); void shutdownPruHandler(int signo); int init_pru_handler(); private: int pru_set_state(enum PruState new_state); enum PruState pru_get_state(); int checkForCompetingProcess(); int createPIDFile(); int initServer(); int run(); //State of the Program enum PruState pruState; std::thread pruHandlerThread; int listenfd; int connfd; int n = 0; struct sockaddr_in serv_addr; char rcvBuff[16]; std::ofstream logFid; }; #endif // PRU_HANDLER_H_
#include "phm_app.h" #include "simple_render_system.h" #include "time.h" #define GLM_FORCE_RADIANS #define GLM_FORCE_DEPTH_ZERO_TO_ONE #include <glm/glm.hpp> #include <glm/gtc/constants.hpp> #include <stdexcept> #include <array> #include <iostream> // temporary helper function, creates a 1x1x1 cube centered at offset std::unique_ptr<phm::PhmModel> createCubeModel(phm::PhmDevice& device, glm::vec3 offset) { std::vector<phm::PhmModel::Vertex> vertices{ // left face (white) {{-.5f, -.5f, -.5f}, {.9f, .9f, .9f}}, {{-.5f, .5f, .5f}, {.9f, .9f, .9f}}, {{-.5f, -.5f, .5f}, {.9f, .9f, .9f}}, {{-.5f, -.5f, -.5f}, {.9f, .9f, .9f}}, {{-.5f, .5f, -.5f}, {.9f, .9f, .9f}}, {{-.5f, .5f, .5f}, {.9f, .9f, .9f}}, // right face (yellow) {{.5f, -.5f, -.5f}, {.8f, .8f, .1f}}, {{.5f, .5f, .5f}, {.8f, .8f, .1f}}, {{.5f, -.5f, .5f}, {.8f, .8f, .1f}}, {{.5f, -.5f, -.5f}, {.8f, .8f, .1f}}, {{.5f, .5f, -.5f}, {.8f, .8f, .1f}}, {{.5f, .5f, .5f}, {.8f, .8f, .1f}}, // top face (orange, remember y axis points down) {{-.5f, -.5f, -.5f}, {.9f, .6f, .1f}}, {{.5f, -.5f, .5f}, {.9f, .6f, .1f}}, {{-.5f, -.5f, .5f}, {.9f, .6f, .1f}}, {{-.5f, -.5f, -.5f}, {.9f, .6f, .1f}}, {{.5f, -.5f, -.5f}, {.9f, .6f, .1f}}, {{.5f, -.5f, .5f}, {.9f, .6f, .1f}}, // bottom face (red) {{-.5f, .5f, -.5f}, {.8f, .1f, .1f}}, {{.5f, .5f, .5f}, {.8f, .1f, .1f}}, {{-.5f, .5f, .5f}, {.8f, .1f, .1f}}, {{-.5f, .5f, -.5f}, {.8f, .1f, .1f}}, {{.5f, .5f, -.5f}, {.8f, .1f, .1f}}, {{.5f, .5f, .5f}, {.8f, .1f, .1f}}, // nose face (blue) {{-.5f, -.5f, 0.5f}, {.1f, .1f, .8f}}, {{.5f, .5f, 0.5f}, {.1f, .1f, .8f}}, {{-.5f, .5f, 0.5f}, {.1f, .1f, .8f}}, {{-.5f, -.5f, 0.5f}, {.1f, .1f, .8f}}, {{.5f, -.5f, 0.5f}, {.1f, .1f, .8f}}, {{.5f, .5f, 0.5f}, {.1f, .1f, .8f}}, // tail face (green) {{-.5f, -.5f, -0.5f}, {.1f, .8f, .1f}}, {{.5f, .5f, -0.5f}, {.1f, .8f, .1f}}, {{-.5f, .5f, -0.5f}, {.1f, .8f, .1f}}, {{-.5f, -.5f, -0.5f}, {.1f, .8f, .1f}}, {{.5f, -.5f, -0.5f}, {.1f, .8f, .1f}}, {{.5f, .5f, -0.5f}, {.1f, .8f, .1f}}, }; for (auto& v : vertices) { v.position += offset; } return std::make_unique<phm::PhmModel>(device, vertices); } namespace phm { Application::Application() { loadObjects(); } Application::~Application() { } void Application::run() { SimpleRenderSystem simpleRenderSystem{ device_, renderer_.getSwapChainRenderPass() }; while (!window_.shouldClose()) { glfwPollEvents(); Time::updateTime(); // BeginFrame returns a nullptr if the swapchain needs to be recreated. // This skips the frame draw call, if that's the case. auto commandBuffer = renderer_.beginFrame(); if (commandBuffer != nullptr) { renderer_.beginSwapChainRenderPass(commandBuffer); simpleRenderSystem.renderObjects(commandBuffer, objects_); renderer_.endSwapChainRenderPass(commandBuffer); renderer_.endFrame(); } } vkDeviceWaitIdle(device_.device()); } void Application::loadObjects() { std::shared_ptr<PhmModel> model = createCubeModel(device_, { 0.0f,0.0f,0.0f }); PhmObject cube; cube.model = model; cube.transform.translation = { 0.0f, 0.0f, 0.5f }; cube.transform.scale = { 0.5f, 0.5f, 0.5f }; cube.transform.rotation.x = 0.1f * glm::two_pi<float>(); objects_.push_back(std::move(cube)); } }
// Tencent is pleased to support the open source community by making ncnn available. // // Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. // // Licensed under the BSD 3-Clause License (the "License"); you may not use this file except // in compliance with the License. You may obtain a copy of the License at // // https://opensource.org/licenses/BSD-3-Clause // // 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 "tanh_arm.h" #if __ARM_NEON #include <arm_neon.h> #include "neon_mathfun.h" #if __ARM_FEATURE_FP16_VECTOR_ARITHMETIC #include "neon_mathfun_fp16s.h" #endif #endif // __ARM_NEON #include <math.h> namespace ncnn { TanH_arm::TanH_arm() { #if __ARM_NEON support_packing = true; #if __ARM_FEATURE_FP16_VECTOR_ARITHMETIC support_fp16_storage = true; #endif #endif // __ARM_NEON #if NCNN_BF16 support_bf16_storage = true; #endif } int TanH_arm::forward_inplace(Mat& bottom_top_blob, const Option& opt) const { int elembits = bottom_top_blob.elembits(); #if __ARM_FEATURE_FP16_VECTOR_ARITHMETIC if (opt.use_fp16_storage && elembits == 16) { if (opt.use_fp16_arithmetic) return forward_inplace_fp16sa(bottom_top_blob, opt); else return forward_inplace_fp16s(bottom_top_blob, opt); } #endif #if NCNN_BF16 if (opt.use_bf16_storage && elembits == 16) return forward_inplace_bf16s(bottom_top_blob, opt); #endif int w = bottom_top_blob.w; int h = bottom_top_blob.h; int channels = bottom_top_blob.c; int size = w * h; int elempack = bottom_top_blob.elempack; #if __ARM_NEON if (elempack == 4) { #pragma omp parallel for num_threads(opt.num_threads) for (int q = 0; q < channels; q++) { float* ptr = bottom_top_blob.channel(q); for (int i = 0; i < size; i++) { float32x4_t _p = vld1q_f32(ptr); _p = tanh_ps(_p); vst1q_f32(ptr, _p); ptr += 4; } } return 0; } #endif // __ARM_NEON #pragma omp parallel for num_threads(opt.num_threads) for (int q = 0; q < channels; q++) { float* ptr = bottom_top_blob.channel(q); #if __ARM_NEON int nn = size >> 2; int remain = size - (nn << 2); #else int remain = size; #endif // __ARM_NEON #if __ARM_NEON for (; nn > 0; nn--) { float32x4_t _p = vld1q_f32(ptr); _p = tanh_ps(_p); vst1q_f32(ptr, _p); ptr += 4; } #endif // __ARM_NEON for (; remain > 0; remain--) { *ptr = tanh(*ptr); ptr++; } } return 0; } #if __ARM_FEATURE_FP16_VECTOR_ARITHMETIC int TanH_arm::forward_inplace_fp16s(Mat& bottom_top_blob, const Option& opt) const { int w = bottom_top_blob.w; int h = bottom_top_blob.h; int channels = bottom_top_blob.c; int size = w * h; int elempack = bottom_top_blob.elempack; if (elempack == 4) { #pragma omp parallel for num_threads(opt.num_threads) for (int q = 0; q < channels; q++) { __fp16* ptr = bottom_top_blob.channel(q); for (int i = 0; i < size; i++) { float32x4_t _p = vcvt_f32_f16(vld1_f16(ptr)); _p = tanh_ps(_p); vst1_f16(ptr, vcvt_f16_f32(_p)); ptr += 4; } } return 0; } #pragma omp parallel for num_threads(opt.num_threads) for (int q = 0; q < channels; q++) { __fp16* ptr = bottom_top_blob.channel(q); int i = 0; for (; i + 3 < size; i += 4) { float32x4_t _p = vcvt_f32_f16(vld1_f16(ptr)); _p = tanh_ps(_p); vst1_f16(ptr, vcvt_f16_f32(_p)); ptr += 4; } for (; i < size; i++) { float v = (float)*ptr; v = tanh(v); *ptr = (__fp16)v; ptr++; } } return 0; } int TanH_arm::forward_inplace_fp16sa(Mat& bottom_top_blob, const Option& opt) const { int w = bottom_top_blob.w; int h = bottom_top_blob.h; int channels = bottom_top_blob.c; int size = w * h; int elempack = bottom_top_blob.elempack; if (elempack == 8) { #pragma omp parallel for num_threads(opt.num_threads) for (int q = 0; q < channels; q++) { __fp16* ptr = bottom_top_blob.channel(q); for (int i = 0; i < size; i++) { float16x8_t _p = vld1q_f16(ptr); _p = tanh_ps(_p); vst1q_f16(ptr, _p); ptr += 8; } } return 0; } if (elempack == 4) { #pragma omp parallel for num_threads(opt.num_threads) for (int q = 0; q < channels; q++) { __fp16* ptr = bottom_top_blob.channel(q); for (int i = 0; i < size; i++) { float16x4_t _p = vld1_f16(ptr); _p = tanh_ps(_p); vst1_f16(ptr, _p); ptr += 4; } } return 0; } #pragma omp parallel for num_threads(opt.num_threads) for (int q = 0; q < channels; q++) { __fp16* ptr = bottom_top_blob.channel(q); int i = 0; for (; i + 3 < size; i += 4) { float16x4_t _p = vld1_f16(ptr); _p = tanh_ps(_p); vst1_f16(ptr, _p); ptr += 4; } for (; i < size; i++) { __fp16 v = *ptr; v = tanh(v); *ptr = v; ptr++; } } return 0; } #endif // __ARM_FEATURE_FP16_VECTOR_ARITHMETIC #if NCNN_BF16 int TanH_arm::forward_inplace_bf16s(Mat& bottom_top_blob, const Option& opt) const { int w = bottom_top_blob.w; int h = bottom_top_blob.h; int channels = bottom_top_blob.c; int size = w * h; int elempack = bottom_top_blob.elempack; #if __ARM_NEON if (elempack == 4) { #pragma omp parallel for num_threads(opt.num_threads) for (int q = 0; q < channels; q++) { unsigned short* ptr = bottom_top_blob.channel(q); for (int i = 0; i < size; i++) { float32x4_t _p = vcvt_f32_bf16(vld1_u16(ptr)); _p = tanh_ps(_p); vst1_u16(ptr, vcvt_bf16_f32(_p)); ptr += 4; } } return 0; } #endif // __ARM_NEON #pragma omp parallel for num_threads(opt.num_threads) for (int q = 0; q < channels; q++) { unsigned short* ptr = bottom_top_blob.channel(q); #if __ARM_NEON int nn = size >> 2; int remain = size - (nn << 2); #else int remain = size; #endif // __ARM_NEON #if __ARM_NEON for (; nn > 0; nn--) { float32x4_t _p = vcvt_f32_bf16(vld1_u16(ptr)); _p = tanh_ps(_p); vst1_u16(ptr, vcvt_bf16_f32(_p)); ptr += 4; } #endif // __ARM_NEON for (; remain > 0; remain--) { float v = bfloat16_to_float32(*ptr); v = tanh(v); *ptr = float32_to_bfloat16(v); ptr++; } } return 0; } #endif // NCNN_BF16 } // namespace ncnn
// Includes #include <xolotl/core/Constants.h> #include <xolotl/core/network/IPSIReactionNetwork.h> #include <xolotl/core/network/NEReactionNetwork.h> #include <xolotl/solver/handler/PetscSolver2DHandler.h> #include <xolotl/util/MathUtils.h> namespace xolotl { namespace solver { namespace handler { void PetscSolver2DHandler::createSolverContext(DM& da) { PetscErrorCode ierr; // Degrees of freedom is the total number of clusters in the network // + moments const auto dof = network.getDOF(); // Set the position of the surface for (auto j = 0; j < nY; j++) { surfacePosition.push_back(0); if (movingSurface) surfacePosition[j] = (IdType)(nX * portion / 100.0); } // We can update the surface position // if we are using a restart file if (not networkName.empty() and movingSurface) { io::XFile xfile(networkName); auto concGroup = xfile.getGroup<io::XFile::ConcentrationGroup>(); if (concGroup and concGroup->hasTimesteps()) { auto tsGroup = concGroup->getLastTimestepGroup(); assert(tsGroup); auto surfaceIndices = tsGroup->readSurface2D(); // Set the actual surface positions for (auto i = 0; i < surfaceIndices.size(); i++) { surfacePosition[i] = surfaceIndices[i]; } } } // Prints info on one process auto xolotlComm = util::getMPIComm(); int procId; MPI_Comm_rank(xolotlComm, &procId); if (procId == 0) { std::cout << "SolverHandler: 2D simulation with surface BC: "; std::string bcString = "periodic"; if (isMirror) bcString = "mirror"; if (leftOffset == 1) std::cout << "free surface"; else std::cout << bcString; std::cout << ", bulk BC: "; if (rightOffset == 1) std::cout << "free surface"; else std::cout << bcString; std::cout << ", left BC: "; if (topOffset == 1) std::cout << "free surface"; else std::cout << "periodic"; std::cout << ", right BC: "; if (bottomOffset == 1) std::cout << "free surface"; else std::cout << "periodic"; std::cout << ", grid (nm): "; for (auto i = 1; i < grid.size() - 1; i++) { std::cout << grid[i] - grid[surfacePosition[0] + 1] << " "; } std::cout << std::endl; } /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Create distributed array (DMDA) to manage parallel grid and vectors - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ if (isMirror) { ierr = DMDACreate2d(xolotlComm, DM_BOUNDARY_MIRROR, DM_BOUNDARY_PERIODIC, DMDA_STENCIL_STAR, nX, nY, PETSC_DECIDE, PETSC_DECIDE, dof + 1, 1, NULL, NULL, &da); checkPetscError(ierr, "PetscSolver2DHandler::createSolverContext: " "DMDACreate2d failed."); } else { ierr = DMDACreate2d(xolotlComm, DM_BOUNDARY_PERIODIC, DM_BOUNDARY_PERIODIC, DMDA_STENCIL_STAR, nX, nY, PETSC_DECIDE, PETSC_DECIDE, dof + 1, 1, NULL, NULL, &da); checkPetscError(ierr, "PetscSolver2DHandler::createSolverContext: " "DMDACreate2d failed."); } ierr = DMSetFromOptions(da); checkPetscError(ierr, "PetscSolver2DHandler::createSolverContext: DMSetFromOptions failed."); ierr = DMSetUp(da); checkPetscError( ierr, "PetscSolver2DHandler::createSolverContext: DMSetUp failed."); // Initialize the surface of the first advection handler corresponding to // the advection toward the surface advectionHandlers[0]->setLocation(grid[surfacePosition[0] + 1] - grid[1]); /* The ofill (thought of as a dof by dof 2d (row-oriented) array represents * the nonzero coupling between degrees of freedom at one point with * degrees of freedom on the adjacent point. */ core::network::IReactionNetwork::SparseFillMap ofill; // Initialize the temperature handler temperatureHandler->initializeTemperature(dof, ofill, dfill); // Fill ofill, the matrix of "off-diagonal" elements that represents // diffusion diffusionHandler->initializeOFill(network, ofill); // Loop on the advection handlers to account the other "off-diagonal" // elements for (auto i = 0; i < advectionHandlers.size(); i++) { advectionHandlers[i]->initialize(network, ofill); } // Get the local boundaries PetscInt xs, xm, ys, ym; ierr = DMDAGetCorners(da, &xs, &ys, NULL, &xm, &ym, NULL); checkPetscError(ierr, "PetscSolver2DHandler::createSolverContext: " "DMDAGetCorners failed."); // Set it in the handler setLocalCoordinates(xs, xm, ys, ym); // Tell the network the number of grid points on this process with ghosts // TODO: do we need the ghost points? network.setGridSize(localXM + 2); // Get the diagonal fill auto nPartials = network.getDiagonalFill(dfill); // Load up the block fills auto dfillsparse = ConvertToPetscSparseFillMap(dof + 1, dfill); auto ofillsparse = ConvertToPetscSparseFillMap(dof + 1, ofill); ierr = DMDASetBlockFillsSparse(da, dfillsparse.data(), ofillsparse.data()); checkPetscError(ierr, "PetscSolver2DHandler::createSolverContext: " "DMDASetBlockFills failed."); // Initialize the arrays for the reaction partial derivatives vals = Kokkos::View<double*>("solverPartials", nPartials); // Set the size of the partial derivatives vectors reactingPartialsForCluster.resize(dof, 0.0); return; } void PetscSolver2DHandler::initializeConcentration(DM& da, Vec& C) { PetscErrorCode ierr; // Pointer for the concentration vector PetscScalar*** concentrations = nullptr; ierr = DMDAVecGetArrayDOF(da, C, &concentrations); checkPetscError(ierr, "PetscSolver2DHandler::initializeConcentration: " "DMDAVecGetArrayDOF failed."); // Initialize the last temperature at each grid point on this process for (auto i = 0; i < localXM + 2; i++) { temperature.push_back(0.0); } // Get the last time step written in the HDF5 file bool hasConcentrations = false; std::unique_ptr<io::XFile> xfile; std::unique_ptr<io::XFile::ConcentrationGroup> concGroup; if (not networkName.empty()) { xfile = std::make_unique<io::XFile>(networkName); concGroup = xfile->getGroup<io::XFile::ConcentrationGroup>(); hasConcentrations = (concGroup and concGroup->hasTimesteps()); } // Give the surface position to the temperature handler temperatureHandler->updateSurfacePosition(surfacePosition[0]); // Initialize the flux handler fluxHandler->initializeFluxHandler(network, surfacePosition[0], grid); // Initialize the grid for the diffusion diffusionHandler->initializeDiffusionGrid( advectionHandlers, grid, localXM, localXS, localYM, hY, localYS); // Initialize the grid for the advection advectionHandlers[0]->initializeAdvectionGrid( advectionHandlers, grid, localXM, localXS, localYM, hY, localYS); // Pointer for the concentration vector at a specific grid point PetscScalar* concOffset = nullptr; // Degrees of freedom is the total number of clusters in the network // + moments const auto dof = network.getDOF(); // Get the single vacancy ID auto singleVacancyCluster = network.getSingleVacancy(); auto vacancyIndex = NetworkType::invalidIndex(); if (singleVacancyCluster.getId() != NetworkType::invalidIndex()) { vacancyIndex = singleVacancyCluster.getId(); } // Loop on all the grid points for (auto j = localYS; j < localYS + localYM; j++) for (auto i = (PetscInt)localXS - 1; i <= (PetscInt)localXS + (PetscInt)localXM; i++) { // Temperature plsm::SpaceVector<double, 3> gridPosition{0.0, j * hY, 0.0}; if (i < 0) gridPosition[0] = (grid[0] - grid[surfacePosition[j] + 1]) / (grid[grid.size() - 1] - grid[surfacePosition[j] + 1]); else gridPosition[0] = ((grid[i] + grid[i + 1]) / 2.0 - grid[surfacePosition[j] + 1]) / (grid[grid.size() - 1] - grid[surfacePosition[j] + 1]); auto temp = temperatureHandler->getTemperature(gridPosition, 0.0); temperature[i - localXS + 1] = temp; // Boundary conditions if (i < localXS || i >= localXS + localXM) continue; concOffset = concentrations[j][i]; concOffset[dof] = temp; // Loop on all the clusters to initialize at 0.0 for (auto n = 0; n < dof; n++) { concOffset[n] = 0.0; } // Initialize the vacancy concentration if (i >= surfacePosition[j] + leftOffset and vacancyIndex != NetworkType::invalidIndex() and not hasConcentrations and i < nX - rightOffset and j >= bottomOffset and j < nY - topOffset) { concOffset[vacancyIndex] = initialVConc; } } // If the concentration must be set from the HDF5 file if (hasConcentrations) { assert(concGroup); auto tsGroup = concGroup->getLastTimestepGroup(); assert(tsGroup); // Loop on the full grid for (auto j = 0; j < nY; j++) for (auto i = 0; i < nX; i++) { // Read the concentrations from the HDF5 file auto concVector = tsGroup->readGridPoint(i, j); // Change the concentration only if we are on the locally owned // part of the grid if (i >= localXS && i < localXS + localXM && j >= localYS && j < localYS + localYM) { concOffset = concentrations[j][i]; // Loop on the concVector size for (auto l = 0; l < concVector.size(); l++) { concOffset[(IdType)concVector.at(l).at(0)] = concVector.at(l).at(1); } // Get the temperature double temp = concVector.at(concVector.size() - 1).at(1); temperature[i - localXS + 1] = temp; } } } // Update the network with the temperature network.setTemperatures(temperature); network.syncClusterDataOnHost(); /* Restore vectors */ ierr = DMDAVecRestoreArrayDOF(da, C, &concentrations); checkPetscError(ierr, "PetscSolver2DHandler::initializeConcentration: " "DMDAVecRestoreArrayDOF failed."); return; } void PetscSolver2DHandler::initGBLocation(DM& da, Vec& C) { PetscErrorCode ierr; // Pointer for the concentration vector PetscScalar*** concentrations = nullptr; ierr = DMDAVecGetArrayDOF(da, C, &concentrations); checkPetscError(ierr, "PetscSolver2DHandler::initGBLocation: " "DMDAVecGetArrayDOF failed."); // Pointer for the concentration vector at a specific grid point PetscScalar* concOffset = nullptr; // Degrees of freedom is the total number of clusters in the network // + moments const auto dof = network.getDOF(); // Need to use the NE network here using NetworkType = core::network::NEReactionNetwork; using Spec = typename NetworkType::Species; auto& neNetwork = dynamic_cast<NetworkType&>(network); // Loop on the GB for (auto const& pair : gbVector) { // Get the coordinate of the point auto xi = std::get<0>(pair); auto yj = std::get<1>(pair); // Check if we are on the right process if (xi >= localXS && xi < localXS + localXM && yj >= localYS && yj < localYS + localYM) { // Get the local concentration concOffset = concentrations[yj][xi]; using HostUnmanaged = Kokkos::View<double*, Kokkos::HostSpace, Kokkos::MemoryUnmanaged>; auto hConcs = HostUnmanaged(concOffset, dof); auto dConcs = Kokkos::View<double*>("Concentrations", dof); deep_copy(dConcs, hConcs); // Transfer the local amount of Xe clusters setLocalXeRate( neNetwork.getTotalAtomConcentration(dConcs, Spec::Xe, 1), xi - localXS, yj - localYS); // Loop on all the clusters to initialize at 0.0 for (auto n = 0; n < dof; n++) { concOffset[n] = 0.0; } } } /* Restore vectors */ ierr = DMDAVecRestoreArrayDOF(da, C, &concentrations); checkPetscError(ierr, "PetscSolver2DHandler::initGBLocation: " "DMDAVecRestoreArrayDOF failed."); return; } std::vector<std::vector<std::vector<std::vector<std::pair<IdType, double>>>>> PetscSolver2DHandler::getConcVector(DM& da, Vec& C) { // Initial declaration PetscErrorCode ierr; const double* gridPointSolution = nullptr; // Pointer for the concentration vector PetscScalar*** concentrations = nullptr; ierr = DMDAVecGetArrayDOFRead(da, C, &concentrations); checkPetscError(ierr, "PetscSolver2DHandler::getConcVector: " "DMDAVecGetArrayDOFRead failed."); // Get the network and dof auto& network = getNetwork(); const auto dof = network.getDOF(); // Create the vector for the concentrations std::vector< std::vector<std::vector<std::vector<std::pair<IdType, double>>>>> toReturn; std::vector<std::vector<std::vector<std::pair<IdType, double>>>> tempTempTempVector; // Loop on the grid points for (auto j = 0; j < localYM; ++j) { std::vector<std::vector<std::pair<IdType, double>>> tempTempVector; for (auto i = 0; i < localXM; ++i) { gridPointSolution = concentrations[localYS + j][localXS + i]; // Create the temporary vector for this grid point std::vector<std::pair<IdType, double>> tempVector; for (auto l = 0; l < dof + 1; ++l) { if (std::fabs(gridPointSolution[l]) > 1.0e-16) { tempVector.push_back( std::make_pair(l, gridPointSolution[l])); } } tempTempVector.push_back(tempVector); } tempTempTempVector.push_back(tempTempVector); } toReturn.push_back(tempTempTempVector); // Restore the solutionArray ierr = DMDAVecRestoreArrayDOFRead(da, C, &concentrations); checkPetscError(ierr, "PetscSolver2DHandler::getConcVector: " "DMDAVecRestoreArrayDOFRead failed."); return toReturn; } void PetscSolver2DHandler::setConcVector(DM& da, Vec& C, std::vector< std::vector<std::vector<std::vector<std::pair<IdType, double>>>>>& concVector) { PetscErrorCode ierr; // Pointer for the concentration vector PetscScalar* gridPointSolution = nullptr; PetscScalar*** concentrations = nullptr; ierr = DMDAVecGetArrayDOF(da, C, &concentrations); checkPetscError(ierr, "PetscSolver2DHandler::setConcVector: " "DMDAVecGetArrayDOF failed."); // Loop on the grid points for (auto j = 0; j < localYM; ++j) { for (auto i = 0; i < localXM; ++i) { gridPointSolution = concentrations[localYS + j][localXS + i]; // Loop on the given vector for (auto l = 0; l < concVector[0][j][i].size(); l++) { gridPointSolution[concVector[0][j][i][l].first] = concVector[0][j][i][l].second; } } } /* Restore vectors */ ierr = DMDAVecRestoreArrayDOF(da, C, &concentrations); checkPetscError(ierr, "PetscSolver2DHandler::setConcVector: " "DMDAVecRestoreArrayDOF failed."); // Get the complete data array, including ghost cells to set the temperature // at the ghost points Vec localSolution; ierr = DMGetLocalVector(da, &localSolution); checkPetscError(ierr, "PetscSolver2DHandler::setConcVector: " "DMGetLocalVector failed."); ierr = DMGlobalToLocalBegin(da, C, INSERT_VALUES, localSolution); checkPetscError(ierr, "PetscSolver2DHandler::setConcVector: " "DMGlobalToLocalBegin failed."); ierr = DMGlobalToLocalEnd(da, C, INSERT_VALUES, localSolution); checkPetscError(ierr, "PetscSolver2DHandler::setConcVector: " "DMGlobalToLocalEnd failed."); // Get the array of concentration ierr = DMDAVecGetArrayDOFRead(da, localSolution, &concentrations); checkPetscError(ierr, "PetscSolver2DHandler::setConcVector: " "DMDAVecGetArrayDOFRead failed."); // Getthe DOF of the network const auto dof = network.getDOF(); // Loop on the grid points for (auto j = 0; j < localYM; ++j) { for (auto i = -1; i <= localXM; ++i) { gridPointSolution = concentrations[localYS + j][localXS + i]; // Get the temperature temperature[i + 1] = gridPointSolution[dof]; } // Update the network with the temperature network.setTemperatures(temperature); network.syncClusterDataOnHost(); } // Restore the solutionArray ierr = DMDAVecRestoreArrayDOFRead(da, localSolution, &concentrations); checkPetscError(ierr, "PetscSolver2DHandler::setConcVector: " "DMDAVecRestoreArrayDOFRead failed."); ierr = DMRestoreLocalVector(da, &localSolution); checkPetscError(ierr, "PetscSolver2DHandler::setConcVector: " "DMRestoreLocalVector failed."); return; } void PetscSolver2DHandler::updateConcentration( TS& ts, Vec& localC, Vec& F, PetscReal ftime) { PetscErrorCode ierr; // Get the local data vector from PETSc DM da; ierr = TSGetDM(ts, &da); checkPetscError( ierr, "PetscSolver2DHandler::updateConcentration: TSGetDM failed."); // Pointers to the PETSc arrays that start at the beginning (localXS, // localYS) of the local array PetscScalar ***concs = nullptr, ***updatedConcs = nullptr; // Get pointers to vector data ierr = DMDAVecGetArrayDOFRead(da, localC, &concs); checkPetscError(ierr, "PetscSolver2DHandler::updateConcentration: " "DMDAVecGetArrayDOFRead (localC) failed."); ierr = DMDAVecGetArrayDOF(da, F, &updatedConcs); checkPetscError(ierr, "PetscSolver2DHandler::updateConcentration: " "DMDAVecGetArrayDOF (F) failed."); // The following pointers are set to the first position in the conc or // updatedConc arrays that correspond to the beginning of the data for the // current grid point. They are accessed just like regular arrays. PetscScalar *concOffset = nullptr, *updatedConcOffset = nullptr; // Degrees of freedom is the total number of clusters in the network const auto dof = network.getDOF(); // Set some step size variable double sy = 1.0 / (hY * hY); // Declarations for variables used in the loop double* concVector[5]{nullptr}; plsm::SpaceVector<double, 3> gridPosition{0.0, 0.0, 0.0}; std::vector<double> incidentFluxVector; double atomConc = 0.0, totalAtomConc = 0.0; // Loop over grid points first for the temperature, including the ghost // points in X for (auto yj = localYS; yj < localYS + localYM; yj++) { temperatureHandler->updateSurfacePosition(surfacePosition[yj]); bool tempHasChanged = false; for (auto xi = (PetscInt)localXS - 1; xi <= (PetscInt)localXS + (PetscInt)localXM; xi++) { // Heat condition if (xi == surfacePosition[yj] && xi >= localXS && xi < localXS + localXM) { // Compute the old and new array offsets concOffset = concs[yj][xi]; updatedConcOffset = updatedConcs[yj][xi]; // Fill the concVector with the pointer to the middle, left, and // right grid points concVector[0] = concOffset; // middle concVector[1] = concs[yj][(PetscInt)xi - 1]; // left concVector[2] = concs[yj][xi + 1]; // right concVector[3] = concs[(PetscInt)yj - 1][xi]; // bottom concVector[4] = concs[yj + 1][xi]; // top // Compute the left and right hx double hxLeft = 0.0, hxRight = 0.0; if (xi >= 1 && xi < nX) { hxLeft = (grid[xi + 1] - grid[xi - 1]) / 2.0; hxRight = (grid[xi + 2] - grid[xi]) / 2.0; } else if (xi < 1) { hxLeft = grid[xi + 1] - grid[xi]; hxRight = (grid[xi + 2] - grid[xi]) / 2.0; } else { hxLeft = (grid[xi + 1] - grid[xi - 1]) / 2.0; hxRight = grid[xi + 1] - grid[xi]; } temperatureHandler->computeTemperature( concVector, updatedConcOffset, hxLeft, hxRight, xi, sy, yj); } // Boundary conditions // Everything to the left of the surface is empty if (xi < surfacePosition[yj] + leftOffset || xi > nX - 1 - rightOffset) { continue; } // Free surface GB bool skip = false; for (auto& pair : gbVector) { if (xi == std::get<0>(pair) && yj == std::get<1>(pair)) { skip = true; break; } } if (skip) continue; // Compute the old and new array offsets concOffset = concs[yj][xi]; updatedConcOffset = updatedConcs[yj][xi]; // Fill the concVector with the pointer to the middle, left, and // right grid points concVector[0] = concOffset; // middle concVector[1] = concs[yj][(PetscInt)xi - 1]; // left concVector[2] = concs[yj][xi + 1]; // right concVector[3] = concs[(PetscInt)yj - 1][xi]; // bottom concVector[4] = concs[yj + 1][xi]; // top // Compute the left and right hx double hxLeft = 0.0, hxRight = 0.0; if (xi >= 1 && xi < nX) { hxLeft = (grid[xi + 1] - grid[xi - 1]) / 2.0; hxRight = (grid[xi + 2] - grid[xi]) / 2.0; } else if (xi < 1) { hxLeft = grid[xi + 1] - grid[xi]; hxRight = (grid[xi + 2] - grid[xi]) / 2.0; } else { hxLeft = (grid[xi + 1] - grid[xi - 1]) / 2.0; hxRight = grid[xi + 1] - grid[xi]; } // Set the grid fraction gridPosition[0] = ((grid[xi] + grid[xi + 1]) / 2.0 - grid[surfacePosition[yj] + 1]) / (grid[grid.size() - 1] - grid[surfacePosition[yj] + 1]); gridPosition[1] = yj / nY; // Get the temperature from the temperature handler temperatureHandler->setTemperature(concOffset); double temp = temperatureHandler->getTemperature(gridPosition, ftime); // Update the network if the temperature changed if (std::fabs(temperature[xi + 1 - localXS] - temp) > 0.1) { temperature[xi + 1 - localXS] = temp; tempHasChanged = true; } // ---- Compute the temperature over the locally owned part of the // grid ----- if (xi >= localXS && xi < localXS + localXM) { temperatureHandler->computeTemperature( concVector, updatedConcOffset, hxLeft, hxRight, xi, sy, yj); } } // TODO: it is updated T more than once per MPI process in preparation // of T depending on more than X if (tempHasChanged) { // Update the network with the temperature network.setTemperatures(temperature); network.syncClusterDataOnHost(); } } // Loop over grid points for (auto yj = bottomOffset; yj < nY - topOffset; yj++) { // Computing the trapped atom concentration is only needed for the // attenuation if (useAttenuation) { // Compute the total concentration of atoms contained in bubbles atomConc = 0.0; auto& psiNetwork = dynamic_cast<core::network::IPSIReactionNetwork&>(network); // Loop over grid points for (auto xi = surfacePosition[yj] + leftOffset; xi < nX - rightOffset; xi++) { // We are only interested in the helium near the surface if ((grid[xi] + grid[xi + 1]) / 2.0 - grid[surfacePosition[yj] + 1] > 2.0) continue; // Check if we are on the right processor if (xi >= localXS && xi < localXS + localXM && yj >= localYS && yj < localYS + localYM) { // Get the concentrations at this grid point concOffset = concs[yj][xi]; // Sum the total atom concentration using HostUnmanaged = Kokkos::View<double*, Kokkos::HostSpace, Kokkos::MemoryUnmanaged>; auto hConcs = HostUnmanaged(concOffset, dof); auto dConcs = Kokkos::View<double*>("Concentrations", dof); deep_copy(dConcs, hConcs); atomConc += psiNetwork.getTotalTrappedHeliumConcentration( dConcs, 0) * (grid[xi + 1] - grid[xi]); } } // Share the concentration with all the processes totalAtomConc = 0.0; auto xolotlComm = util::getMPIComm(); MPI_Allreduce( &atomConc, &totalAtomConc, 1, MPI_DOUBLE, MPI_SUM, xolotlComm); // Set the disappearing rate in the modified TM handler psiNetwork.updateTrapMutationDisappearingRate(totalAtomConc); } // Skip if we are not on the right process if (yj < localYS || yj >= localYS + localYM) continue; // Set the grid position gridPosition[1] = yj * hY; // Initialize the flux, advection handlers which depend // on the surface position at Y fluxHandler->initializeFluxHandler(network, surfacePosition[yj], grid); advectionHandlers[0]->setLocation( grid[surfacePosition[yj] + 1] - grid[1]); for (auto xi = localXS; xi < localXS + localXM; xi++) { // Compute the old and new array offsets concOffset = concs[yj][xi]; updatedConcOffset = updatedConcs[yj][xi]; // Fill the concVector with the pointer to the middle, left, right, // bottom, and top grid points concVector[0] = concOffset; // middle concVector[1] = concs[yj][(PetscInt)xi - 1]; // left concVector[2] = concs[yj][xi + 1]; // right concVector[3] = concs[(PetscInt)yj - 1][xi]; // bottom concVector[4] = concs[yj + 1][xi]; // top // Compute the left and right hx double hxLeft = 0.0, hxRight = 0.0; if (xi >= 1 && xi < nX) { hxLeft = (grid[xi + 1] - grid[xi - 1]) / 2.0; hxRight = (grid[xi + 2] - grid[xi]) / 2.0; } else if (xi < 1) { hxLeft = grid[xi + 1] - grid[xi]; hxRight = (grid[xi + 2] - grid[xi]) / 2.0; } else { hxLeft = (grid[xi + 1] - grid[xi - 1]) / 2.0; hxRight = grid[xi + 1] - grid[xi]; } // Boundary conditions // Everything to the left of the surface is empty if (xi < surfacePosition[yj] + leftOffset || xi > nX - 1 - rightOffset || yj < bottomOffset || yj > nY - 1 - topOffset) { continue; } // Free surface GB bool skip = false; for (auto& pair : gbVector) { if (xi == std::get<0>(pair) && yj == std::get<1>(pair)) { skip = true; break; } } if (skip) continue; // ----- Account for flux of incoming particles ----- fluxHandler->computeIncidentFlux( ftime, updatedConcOffset, xi, surfacePosition[yj]); // ---- Compute diffusion over the locally owned part of the grid // ----- diffusionHandler->computeDiffusion(network, concVector, updatedConcOffset, hxLeft, hxRight, xi - localXS, sy, yj - localYS); // ---- Compute advection over the locally owned part of the grid // ----- Set the grid position gridPosition[0] = (grid[xi] + grid[xi + 1]) / 2.0 - grid[1]; for (auto i = 0; i < advectionHandlers.size(); i++) { advectionHandlers[i]->computeAdvection(network, gridPosition, concVector, updatedConcOffset, hxLeft, hxRight, xi - localXS, hY, yj - localYS); } auto surfacePos = grid[surfacePosition[yj] + 1]; auto curXPos = (grid[xi] + grid[xi + 1]) / 2.0; auto prevXPos = (grid[xi - 1] + grid[xi]) / 2.0; auto curDepth = curXPos - surfacePos; auto curSpacing = curXPos - prevXPos; // ----- Compute the reaction fluxes over the locally owned part of // the grid ----- using HostUnmanaged = Kokkos::View<double*, Kokkos::HostSpace, Kokkos::MemoryUnmanaged>; auto hConcs = HostUnmanaged(concOffset, dof); auto dConcs = Kokkos::View<double*>("Concentrations", dof); deep_copy(dConcs, hConcs); auto hFlux = HostUnmanaged(updatedConcOffset, dof); auto dFlux = Kokkos::View<double*>("Fluxes", dof); deep_copy(dFlux, hFlux); fluxCounter->increment(); fluxTimer->start(); network.computeAllFluxes( dConcs, dFlux, xi + 1 - localXS, curDepth, curSpacing); fluxTimer->stop(); deep_copy(hFlux, dFlux); } } /* Restore vectors */ ierr = DMDAVecRestoreArrayDOFRead(da, localC, &concs); checkPetscError(ierr, "PetscSolver2DHandler::updateConcentration: " "DMDAVecRestoreArrayDOFRead (localC) failed."); ierr = DMDAVecRestoreArrayDOF(da, F, &updatedConcs); checkPetscError(ierr, "PetscSolver2DHandler::updateConcentration: " "DMDAVecRestoreArrayDOF (F) failed."); return; } void PetscSolver2DHandler::computeJacobian( TS& ts, Vec& localC, Mat& J, PetscReal ftime) { PetscErrorCode ierr; // Get the distributed array DM da; ierr = TSGetDM(ts, &da); checkPetscError(ierr, "PetscSolver2DHandler::computeJacobian: " "TSGetDM failed."); // Get pointers to vector data PetscScalar*** concs = nullptr; ierr = DMDAVecGetArrayDOFRead(da, localC, &concs); checkPetscError(ierr, "PetscSolver2DHandler::computeJacobian: " "DMDAVecGetArrayDOFRead failed."); // The degree of freedom is the size of the network const auto dof = network.getDOF(); // Setup some step size variables double sy = 1.0 / (hY * hY); // Pointer to the concentrations at a given grid point PetscScalar* concOffset = nullptr; // Arguments for MatSetValuesStencil called below MatStencil rowId; MatStencil colIds[dof]; IdType pdColIdsVectorSize = 0; // Declarations for variables used in the loop double atomConc = 0.0, totalAtomConc = 0.0; plsm::SpaceVector<double, 3> gridPosition{0.0, 0.0, 0.0}; // Get the total number of diffusing clusters const auto nDiff = std::max(diffusionHandler->getNumberOfDiffusing(), 0); // Get the total number of advecting clusters int nAdvec = 0; for (auto l = 0; l < advectionHandlers.size(); l++) { auto n = advectionHandlers[l]->getNumberOfAdvecting(); if (n > nAdvec) nAdvec = n; } // Arguments for MatSetValuesStencil called below MatStencil row, cols[5]; PetscScalar tempVals[5]; IdType tempIndices[1]; PetscScalar diffVals[5 * nDiff]; IdType diffIndices[nDiff]; PetscScalar advecVals[2 * nAdvec]; IdType advecIndices[nAdvec]; /* Loop over grid points for the temperature, including ghosts */ for (auto yj = localYS; yj < localYS + localYM; yj++) { temperatureHandler->updateSurfacePosition(surfacePosition[yj]); bool tempHasChanged = false; for (auto xi = (PetscInt)localXS - 1; xi <= (PetscInt)localXS + (PetscInt)localXM; xi++) { // Compute the left and right hx double hxLeft = 0.0, hxRight = 0.0; if (xi >= 1 && xi < nX) { hxLeft = (grid[xi + 1] - grid[xi - 1]) / 2.0; hxRight = (grid[xi + 2] - grid[xi]) / 2.0; } else if (xi == -1) { hxLeft = 0.0; hxRight = (grid[xi + 2] + grid[xi + 1]) / 2.0; } else if (xi < 1) { hxLeft = grid[xi + 1] - grid[xi]; hxRight = (grid[xi + 2] - grid[xi]) / 2.0; } else { hxLeft = (grid[xi + 1] - grid[xi - 1]) / 2.0; hxRight = grid[xi + 1] - grid[xi]; } // Heat condition if (xi == surfacePosition[yj] && xi >= localXS && xi < localXS + localXM) { // Get the partial derivatives for the temperature auto setValues = temperatureHandler->computePartialsForTemperature( tempVals, tempIndices, hxLeft, hxRight, xi, sy, yj); if (setValues) { // Set grid coordinate and component number for the row row.i = xi; row.j = yj; row.c = tempIndices[0]; // Set grid coordinates and component numbers for the // columns corresponding to the middle, left, and right grid // points cols[0].i = xi; // middle cols[0].j = yj; cols[0].c = tempIndices[0]; cols[1].i = (PetscInt)xi - 1; // left cols[1].j = yj; cols[1].c = tempIndices[0]; cols[2].i = xi + 1; // right cols[2].j = yj; cols[2].c = tempIndices[0]; cols[3].i = xi; // bottom cols[3].j = (PetscInt)yj - 1; cols[3].c = tempIndices[0]; cols[4].i = xi; // top cols[4].j = yj + 1; cols[4].c = tempIndices[0]; ierr = MatSetValuesStencil( J, 1, &row, 5, cols, tempVals, ADD_VALUES); checkPetscError(ierr, "PetscSolver2DHandler::computeJacobian: " "MatSetValuesStencil (temperature) failed."); } } // Boundary conditions // Everything to the left of the surface is empty if (xi < surfacePosition[yj] + leftOffset || xi > nX - 1 - rightOffset) continue; // Free surface GB bool skip = false; for (auto& pair : gbVector) { if (xi == std::get<0>(pair) && yj == std::get<1>(pair)) { skip = true; break; } } if (skip) continue; // Get the concentrations at this grid point concOffset = concs[yj][xi]; // Set the grid fraction gridPosition[0] = ((grid[xi] + grid[xi + 1]) / 2.0 - grid[surfacePosition[yj] + 1]) / (grid[grid.size() - 1] - grid[surfacePosition[yj] + 1]); gridPosition[1] = yj / nY; // Get the temperature from the temperature handler temperatureHandler->setTemperature(concOffset); double temp = temperatureHandler->getTemperature(gridPosition, ftime); // Update the network if the temperature changed if (std::fabs(temperature[xi + 1 - localXS] - temp) > 0.1) { temperature[xi + 1 - localXS] = temp; tempHasChanged = true; } // Get the partial derivatives for the temperature if (xi >= localXS && xi < localXS + localXM) { auto setValues = temperatureHandler->computePartialsForTemperature( tempVals, tempIndices, hxLeft, hxRight, xi, sy, yj); if (setValues) { // Set grid coordinate and component number for the row row.i = xi; row.j = yj; row.c = tempIndices[0]; // Set grid coordinates and component numbers for the // columns corresponding to the middle, left, and right grid // points cols[0].i = xi; // middle cols[0].j = yj; cols[0].c = tempIndices[0]; cols[1].i = (PetscInt)xi - 1; // left cols[1].j = yj; cols[1].c = tempIndices[0]; cols[2].i = xi + 1; // right cols[2].j = yj; cols[2].c = tempIndices[0]; cols[3].i = xi; // bottom cols[3].j = (PetscInt)yj - 1; cols[3].c = tempIndices[0]; cols[4].i = xi; // top cols[4].j = yj + 1; cols[4].c = tempIndices[0]; ierr = MatSetValuesStencil( J, 1, &row, 5, cols, tempVals, ADD_VALUES); checkPetscError(ierr, "PetscSolver2DHandler::computeJacobian: " "MatSetValuesStencil (temperature) failed."); } } } if (tempHasChanged) { // Update the network with the temperature network.setTemperatures(temperature); network.syncClusterDataOnHost(); } } // Loop over the grid points for (auto yj = bottomOffset; yj < nY - topOffset; yj++) { // Computing the trapped atom concentration is only needed for the // attenuation if (useAttenuation) { // Compute the total concentration of atoms contained in bubbles atomConc = 0.0; auto& psiNetwork = dynamic_cast<core::network::IPSIReactionNetwork&>(network); // Loop over grid points for (auto xi = surfacePosition[yj] + leftOffset; xi < nX - rightOffset; xi++) { // We are only interested in the helium near the surface if ((grid[xi] + grid[xi + 1]) / 2.0 - grid[surfacePosition[yj] + 1] > 2.0) continue; // Check if we are on the right processor if (xi >= localXS && xi < localXS + localXM && yj >= localYS && yj < localYS + localYM) { // Get the concentrations at this grid point concOffset = concs[yj][xi]; // Sum the total atom concentration using HostUnmanaged = Kokkos::View<double*, Kokkos::HostSpace, Kokkos::MemoryUnmanaged>; auto hConcs = HostUnmanaged(concOffset, dof); auto dConcs = Kokkos::View<double*>("Concentrations", dof); deep_copy(dConcs, hConcs); atomConc += psiNetwork.getTotalTrappedHeliumConcentration( dConcs, 0) * (grid[xi + 1] - grid[xi]); } } // Share the concentration with all the processes totalAtomConc = 0.0; auto xolotlComm = util::getMPIComm(); MPI_Allreduce( &atomConc, &totalAtomConc, 1, MPI_DOUBLE, MPI_SUM, xolotlComm); // Set the disappearing rate in the modified TM handler psiNetwork.updateTrapMutationDisappearingRate(totalAtomConc); } // Skip if we are not on the right process if (yj < localYS || yj >= localYS + localYM) continue; // Set the grid position gridPosition[1] = yj * hY; // Initialize the advection and temperature handlers which depend // on the surface position at Y advectionHandlers[0]->setLocation( grid[surfacePosition[yj] + 1] - grid[1]); for (auto xi = localXS; xi < localXS + localXM; xi++) { // Boundary conditions // Everything to the left of the surface is empty if (xi < surfacePosition[yj] + leftOffset || xi > nX - 1 - rightOffset || yj < bottomOffset || yj > nY - 1 - topOffset) continue; // Free surface GB bool skip = false; for (auto& pair : gbVector) { if (xi == std::get<0>(pair) && yj == std::get<1>(pair)) { skip = true; break; } } if (skip) continue; // Compute the left and right hx double hxLeft = 0.0, hxRight = 0.0; if (xi >= 1 && xi < nX) { hxLeft = (grid[xi + 1] - grid[xi - 1]) / 2.0; hxRight = (grid[xi + 2] - grid[xi]) / 2.0; } else if (xi < 1) { hxLeft = grid[xi + 1] - grid[xi]; hxRight = (grid[xi + 2] - grid[xi]) / 2.0; } else { hxLeft = (grid[xi + 1] - grid[xi - 1]) / 2.0; hxRight = grid[xi + 1] - grid[xi]; } // Get the partial derivatives for the diffusion diffusionHandler->computePartialsForDiffusion(network, diffVals, diffIndices, hxLeft, hxRight, xi - localXS, sy, yj - localYS); // Loop on the number of diffusion cluster to set the values in the // Jacobian for (auto i = 0; i < nDiff; i++) { // Set grid coordinate and component number for the row row.i = xi; row.j = yj; row.c = diffIndices[i]; // Set grid coordinates and component numbers for the columns // corresponding to the middle, left, right, bottom, and top // grid points cols[0].i = xi; // middle cols[0].j = yj; cols[0].c = diffIndices[i]; cols[1].i = (PetscInt)xi - 1; // left cols[1].j = yj; cols[1].c = diffIndices[i]; cols[2].i = xi + 1; // right cols[2].j = yj; cols[2].c = diffIndices[i]; cols[3].i = xi; // bottom cols[3].j = (PetscInt)yj - 1; cols[3].c = diffIndices[i]; cols[4].i = xi; // top cols[4].j = yj + 1; cols[4].c = diffIndices[i]; ierr = MatSetValuesStencil( J, 1, &row, 5, cols, diffVals + (5 * i), ADD_VALUES); checkPetscError(ierr, "PetscSolver2DHandler::computeJacobian: " "MatSetValuesStencil (diffusion) failed."); } // Get the partial derivatives for the advection // Set the grid position gridPosition[0] = (grid[xi] + grid[xi + 1]) / 2.0 - grid[1]; for (auto l = 0; l < advectionHandlers.size(); l++) { advectionHandlers[l]->computePartialsForAdvection(network, advecVals, advecIndices, gridPosition, hxLeft, hxRight, xi - localXS, hY, yj - localYS); // Get the stencil indices to know where to put the partial // derivatives in the Jacobian auto advecStencil = advectionHandlers[l]->getStencilForAdvection(gridPosition); // Get the number of advecting clusters nAdvec = advectionHandlers[l]->getNumberOfAdvecting(); // Loop on the number of advecting cluster to set the values in // the Jacobian for (auto i = 0; i < nAdvec; i++) { // Set grid coordinate and component number for the row row.i = xi; row.j = yj; row.c = advecIndices[i]; // If we are on the sink, the partial derivatives are not // the same Both sides are giving their concentrations to // the center if (advectionHandlers[l]->isPointOnSink(gridPosition)) { cols[0].i = (PetscInt)xi - advecStencil[0]; // left? cols[0].j = yj - advecStencil[1]; // bottom? cols[0].c = advecIndices[i]; cols[1].i = xi + advecStencil[0]; // right? cols[1].j = yj + advecStencil[1]; // top? cols[1].c = advecIndices[i]; } else { // Set grid coordinates and component numbers for the // columns corresponding to the middle and other grid // points cols[0].i = xi; // middle cols[0].j = yj; cols[0].c = advecIndices[i]; cols[1].i = xi + advecStencil[0]; // left or right? cols[1].j = yj + advecStencil[1]; // bottom or top? cols[1].c = advecIndices[i]; } // Update the matrix ierr = MatSetValuesStencil( J, 1, &row, 2, cols, advecVals + (2 * i), ADD_VALUES); checkPetscError(ierr, "PetscSolver2DHandler::computeJacobian: " "MatSetValuesStencil (advection) failed."); } } // Get the concentations concOffset = concs[yj][xi]; // ----- Take care of the reactions for all the reactants ----- auto surfacePos = grid[surfacePosition[yj] + 1]; auto curXPos = (grid[xi] + grid[xi + 1]) / 2.0; auto prevXPos = (grid[xi - 1] + grid[xi]) / 2.0; auto curDepth = curXPos - surfacePos; auto curSpacing = curXPos - prevXPos; // Compute all the partial derivatives for the reactions using HostUnmanaged = Kokkos::View<double*, Kokkos::HostSpace, Kokkos::MemoryUnmanaged>; auto hConcs = HostUnmanaged(concOffset, dof); auto dConcs = Kokkos::View<double*>("Concentrations", dof); deep_copy(dConcs, hConcs); partialDerivativeCounter->increment(); partialDerivativeTimer->start(); network.computeAllPartials( dConcs, vals, xi + 1 - localXS, curDepth, curSpacing); partialDerivativeTimer->stop(); auto hPartials = create_mirror_view(vals); deep_copy(hPartials, vals); // Variable for the loop on reactants IdType startingIdx = 0; // Update the column in the Jacobian that represents each DOF for (auto i = 0; i < dof; i++) { // Set grid coordinate and component number for the row rowId.i = xi; rowId.j = yj; rowId.c = i; // Number of partial derivatives auto rowIter = dfill.find(i); if (rowIter != dfill.end()) { const auto& row = rowIter->second; pdColIdsVectorSize = row.size(); // Loop over the list of column ids for (auto j = 0; j < pdColIdsVectorSize; j++) { // Set grid coordinate and component number for a column // in the list colIds[j].i = xi; colIds[j].j = yj; colIds[j].c = row[j]; // Get the partial derivative from the array of all of // the partials reactingPartialsForCluster[j] = hPartials(startingIdx + j); } // Update the matrix ierr = MatSetValuesStencil(J, 1, &rowId, pdColIdsVectorSize, colIds, reactingPartialsForCluster.data(), ADD_VALUES); checkPetscError(ierr, "PetscSolver2DHandler::computeJacobian: " "MatSetValuesStencil (reactions) failed."); // Increase the starting index startingIdx += pdColIdsVectorSize; } } } } /* Restore vectors */ ierr = DMDAVecRestoreArrayDOFRead(da, localC, &concs); checkPetscError(ierr, "PetscSolver2DHandler::computeJacobian: " "DMDAVecRestoreArrayDOFRead failed."); return; } } /* end namespace handler */ } /* end namespace solver */ } /* end namespace xolotl */
//========================================================================= // Copyright (C) 2012 The Elastos Open Source Project // // 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 "org/apache/harmony/security/x509/CPrivateKeyUsagePeriod.h" #include "CASN1Implicit.h" #include "CASN1GeneralizedTime.h" #include "CBerInputStream.h" using Elastos::Core::IArrayOf; using Org::Apache::Harmony::Security::Asn1::CASN1GeneralizedTime; using Org::Apache::Harmony::Security::Asn1::CASN1Implicit; using Org::Apache::Harmony::Security::Asn1::CBerInputStream; using Org::Apache::Harmony::Security::Asn1::IASN1Implicit; using Org::Apache::Harmony::Security::Asn1::IASN1GeneralizedTime; namespace Org { namespace Apache { namespace Harmony { namespace Security { namespace X509 { CPrivateKeyUsagePeriod::ASN1SequenceWrapper::ASN1SequenceWrapper() {} ECode CPrivateKeyUsagePeriod::ASN1SequenceWrapper::constructor( /* [in] */ ArrayOf<IASN1Type*>* types) { ASN1Sequence::constructor(types); SetOptional(0); SetOptional(1); return NOERROR; } ECode CPrivateKeyUsagePeriod::ASN1SequenceWrapper::GetValues( /* [in] */ IInterface* object, /* [in] */ ArrayOf<IInterface*>* values) { CPrivateKeyUsagePeriod* pkup = (CPrivateKeyUsagePeriod*) IPrivateKeyUsagePeriod::Probe(object); values->Set(0, pkup->mNotBeforeDate); values->Set(1, pkup->mNotAfterDate); return NOERROR; } ECode CPrivateKeyUsagePeriod::ASN1SequenceWrapper::GetDecodedObject( /* [in] */ IBerInputStream* in, /* [out] */ IInterface** result) { AutoPtr<IArrayOf> values = IArrayOf::Probe(((CBerInputStream*)in)->mContent); AutoPtr<IInterface> v0; values->Get(0, (IInterface**)&v0); AutoPtr<IInterface> v1; values->Get(1, (IInterface**)&v1); AutoPtr<ArrayOf<Byte> > bs; in->GetEncoded((ArrayOf<Byte>**)&bs); AutoPtr<IPrivateKeyUsagePeriod> pup; CPrivateKeyUsagePeriod::New(IDate::Probe(v0), IDate::Probe(v1) , bs, (IPrivateKeyUsagePeriod**)&pup); *result = pup; REFCOUNT_ADD(*result); return NOERROR; } AutoPtr<IASN1Sequence> CPrivateKeyUsagePeriod::ASN1 = InitASN1(); CAR_OBJECT_IMPL(CPrivateKeyUsagePeriod) CAR_INTERFACE_IMPL(CPrivateKeyUsagePeriod, Object, IPrivateKeyUsagePeriod) AutoPtr<IASN1Sequence> CPrivateKeyUsagePeriod::InitASN1() { AutoPtr<ASN1SequenceWrapper> aw = new ASN1SequenceWrapper(); AutoPtr<ArrayOf<IASN1Type*> > array = ArrayOf<IASN1Type*>::Alloc(2); AutoPtr<IASN1GeneralizedTime> at; CASN1GeneralizedTime::GetInstance((IASN1GeneralizedTime**)&at); AutoPtr<IASN1Implicit> ai; CASN1Implicit::New(0, IASN1Type::Probe(at), (IASN1Implicit**)&ai); array->Set(0, IASN1Type::Probe(ai)); ai = NULL; CASN1Implicit::New(1, IASN1Type::Probe(at), (IASN1Implicit**)&ai); array->Set(1, IASN1Type::Probe(ai)); aw->constructor(array); return aw; } ECode CPrivateKeyUsagePeriod::GetNotBefore( /* [out] */ IDate** result) { VALIDATE_NOT_NULL(result); *result = mNotBeforeDate; REFCOUNT_ADD(*result); return NOERROR; } ECode CPrivateKeyUsagePeriod::GetNotAfter( /* [out] */ IDate** result) { VALIDATE_NOT_NULL(result); *result = mNotAfterDate; REFCOUNT_ADD(*result); return NOERROR; } ECode CPrivateKeyUsagePeriod::GetEncoded( /* [out, callee] */ ArrayOf<Byte>** result) { VALIDATE_NOT_NULL(result); if (mEncoding == NULL) { IASN1Type::Probe(ASN1)->Encode(this->Probe(EIID_IInterface), (ArrayOf<Byte>**)&mEncoding); } *result = mEncoding; REFCOUNT_ADD(*result); return NOERROR; } ECode CPrivateKeyUsagePeriod::constructor( /* [in] */ IDate* notBeforeDate, /* [in] */ IDate* notAfterDate) { return constructor(notBeforeDate, notAfterDate, NULL); } ECode CPrivateKeyUsagePeriod::constructor( /* [in] */ IDate* notBeforeDate, /* [in] */ IDate* notAfterDate, /* [in] */ ArrayOf<Byte>* encoding) { mNotBeforeDate = notBeforeDate; mNotAfterDate = notAfterDate; mEncoding = encoding; return NOERROR; } } // namespace X509 } // namespace Security } // namespace Harmony } // namespace Apache } // namespace Org
#include <bits/stdc++.h> using namespace std; void init(){ #ifndef ONLINE_JUDGE freopen("in.txt", "r", stdin); freopen("out.txt", "w", stdout); freopen("err.txt", "w", stderr); #endif } int main(){ init(); string s, t; cin>>s>>t; for(int i = 0; i < t.size(); i++){ rotate(t.begin(), t.begin()+1, t.end()); if(~s.find(t)) return cout<<"yes", 0; } cout<<"no"; return 0; }
/* * Copyright (c) 2013 ARM Limited * Copyright (c) 2014-2015 Sven Karlsson * Copyright (c) 2018 TU Dresden * All rights reserved * * The license below extends only to copyright in the software and shall * not be construed as granting a license to any other intellectual * property including but not limited to intellectual property relating * to a hardware implementation of the functionality of the software * licensed hereunder. You may use the software subject to the license * terms below provided that you ensure that this notice is replicated * unmodified and in its entirety in all distributions of the software, * modified or unmodified, in source code or in binary form. * * Copyright (c) 2016-2017 The University of Virginia * 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 the copyright holders 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. */ #ifndef __ARCH_PPU_UTILITY_HH__ #define __ARCH_PPU_UTILITY_HH__ #include <cmath> #include <cstdint> #include <sstream> #include <string> #include "arch/ppu/registers.hh" #include "base/types.hh" #include "ppu/reg_class.hh" #include "ppu/static_inst.hh" #include "ppu/thread_context.hh" namespace PpuISA { template<typename T> inline bool isquietnan(T val) { return false; } template<> inline bool isquietnan<float>(float val) { return std::isnan(val) && (reinterpret_cast<uint32_t&>(val)&0x00400000); } template<> inline bool isquietnan<double>(double val) { return std::isnan(val) && (reinterpret_cast<uint64_t&>(val)&0x0008000000000000ULL); } template<typename T> inline bool issignalingnan(T val) { return false; } template<> inline bool issignalingnan<float>(float val) { return std::isnan(val) && (reinterpret_cast<uint32_t&>(val)&0x00200000); } template<> inline bool issignalingnan<double>(double val) { return std::isnan(val) && (reinterpret_cast<uint64_t&>(val)&0x0004000000000000ULL); } inline PCState buildRetPC(const PCState &curPC, const PCState &callPC) { PCState retPC = callPC; retPC.advance(); retPC.pc(curPC.npc()); return retPC; } inline uint64_t getArgument(ThreadContext *tc, int &number, uint16_t size, bool fp) { panic_if(fp, "getArgument(): Floating point arguments not implemented"); panic_if(size != 8, "getArgument(): Can only handle 64-bit arguments."); panic_if(number >= ArgumentRegs.size(), "getArgument(): Don't know how to handle stack arguments"); // The first 8 integer arguments are passed in registers, the rest // are passed on the stack. return tc->readIntReg(ArgumentRegs[number]); } inline void startupCPU(ThreadContext *tc, int cpuId) { tc->activate(); } inline void copyRegs(ThreadContext *src, ThreadContext *dest) { // First loop through the integer registers. for (int i = 0; i < NumIntRegs; ++i) dest->setIntReg(i, src->readIntReg(i)); // Lastly copy PC/NPC dest->pcState(src->pcState()); } inline std::string registerName(RegId reg) { if (reg.isIntReg()) { if (reg.index() >= NumIntArchRegs) { /* * This should only happen if a instruction is being speculatively * executed along a not-taken branch, and if that instruction's * width was incorrectly predecoded (i.e., it was predecoded as a * full instruction rather than a compressed one or vice versa). * It also should only happen if a debug flag is on that prints * disassembly information, so rather than panic the incorrect * value is printed for debugging help. */ std::stringstream str; str << "?? (x" << reg.index() << ')'; return str.str(); } return IntRegNames[reg.index()]; } else { if (reg.index() >= NumFloatRegs) { std::stringstream str; str << "?? (f" << reg.index() << ')'; return str.str(); } return FloatRegNames[reg.index()]; } } inline void advancePC(PCState &pc, const StaticInstPtr &inst) { inst->advancePC(pc); } static inline bool inUserMode(ThreadContext *tc) { return true; } inline uint64_t getExecutingAsid(ThreadContext *tc) { return 0; } /** * init Cpu function */ void initCPU(ThreadContext *tc, int cpuId); /** * check, whether the architecture is in 32 bit or 64 bit mode */ bool isRv32(ThreadContext *tc); } // namespace PpuISA #endif // __ARCH_PPU_UTILITY_HH__
/********** This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. (See <http://www.gnu.org/copyleft/lesser.html>.) This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA **********/ // "liveMedia" // Copyright (c) 1996-2017 Live Networks, Inc. All rights reserved. // H.261 Video RTP Sources // C++ header #ifndef _H261_VIDEO_RTP_SOURCE_HH #define _H261_VIDEO_RTP_SOURCE_HH #ifndef _MULTI_FRAMED_RTP_SOURCE_HH #include "MultiFramedRTPSource.hh" #endif class H261VideoRTPSource: public MultiFramedRTPSource { public: static H261VideoRTPSource* createNew(UsageEnvironment& env, Groupsock* RTPgs, unsigned char rtpPayloadFormat = 31, unsigned rtpTimestampFrequency = 90000); u_int32_t lastSpecialHeader() const {return fLastSpecialHeader;} protected: virtual ~H261VideoRTPSource(); private: H261VideoRTPSource(UsageEnvironment& env, Groupsock* RTPgs, unsigned char rtpPayloadFormat, unsigned rtpTimestampFrequency); // called only by createNew() private: // redefined virtual functions: virtual Boolean processSpecialHeader(BufferedPacket* packet, unsigned& resultSpecialHeaderSize); virtual char const* MIMEtype() const; private: u_int32_t fLastSpecialHeader; }; #endif
// Copyright 2013 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 "chromeos/dbus/fake_nfc_record_client.h" #include "base/logging.h" // TODO(armansito): For now, this class doesn't do anything. Implement fake // behavior in conjunction with unit tests while implementing the src/device // layer. namespace chromeos { FakeNfcRecordClient::Properties::Properties( const PropertyChangedCallback& callback) : NfcRecordClient::Properties(NULL, callback) { } FakeNfcRecordClient::Properties::~Properties() { } void FakeNfcRecordClient::Properties::Get( dbus::PropertyBase* property, dbus::PropertySet::GetCallback callback) { VLOG(1) << "Get " << property->name(); callback.Run(false); } void FakeNfcRecordClient::Properties::GetAll() { VLOG(1) << "GetAll"; } void FakeNfcRecordClient::Properties::Set( dbus::PropertyBase* property, dbus::PropertySet::SetCallback callback) { VLOG(1) << "Set " << property->name(); callback.Run(false); } FakeNfcRecordClient::FakeNfcRecordClient() { VLOG(1) << "Creating FakeNfcRecordClient"; } FakeNfcRecordClient::~FakeNfcRecordClient() { } void FakeNfcRecordClient::Init(dbus::Bus* bus) { } void FakeNfcRecordClient::AddObserver(Observer* observer) { } void FakeNfcRecordClient::RemoveObserver(Observer* observer) { } FakeNfcRecordClient::Properties* FakeNfcRecordClient::GetProperties(const dbus::ObjectPath& object_path) { return NULL; } } // namespace chromeos
/** * * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) * * The version of the OpenAPI document: 20220523 * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ #include <QJsonArray> #include <QJsonDocument> #include <QJsonObject> #include <QVariantMap> #include <QDebug> #include "OAIHelpers.h" #include "OAIItemAttributeApiRequest.h" namespace OpenAPI { OAIItemAttributeApiRequest::OAIItemAttributeApiRequest(QHttpEngine::Socket *s, QSharedPointer<OAIItemAttributeApiHandler> hdl) : QObject(s), socket(s), handler(hdl) { auto headers = s->headers(); for(auto itr = headers.begin(); itr != headers.end(); itr++) { requestHeaders.insert(QString(itr.key()), QString(itr.value())); } } OAIItemAttributeApiRequest::~OAIItemAttributeApiRequest(){ disconnect(this, nullptr, nullptr, nullptr); qDebug() << "OAIItemAttributeApiRequest::~OAIItemAttributeApiRequest()"; } QMap<QString, QString> OAIItemAttributeApiRequest::getRequestHeaders() const { return requestHeaders; } void OAIItemAttributeApiRequest::setResponseHeaders(const QMultiMap<QString, QString>& headers){ for(auto itr = headers.begin(); itr != headers.end(); ++itr) { responseHeaders.insert(itr.key(), itr.value()); } } QHttpEngine::Socket* OAIItemAttributeApiRequest::getRawSocket(){ return socket; } void OAIItemAttributeApiRequest::itemAttributeListRequest(){ qDebug() << "/api/v2/item-attribute/"; connect(this, &OAIItemAttributeApiRequest::itemAttributeList, handler.data(), &OAIItemAttributeApiHandler::itemAttributeList); qint32 limit; if(socket->queryString().keys().contains("limit")){ fromStringValue(socket->queryString().value("limit"), limit); } qint32 offset; if(socket->queryString().keys().contains("offset")){ fromStringValue(socket->queryString().value("offset"), offset); } emit itemAttributeList(limit, offset); } void OAIItemAttributeApiRequest::itemAttributeReadRequest(const QString& idstr){ qDebug() << "/api/v2/item-attribute/{id}/"; connect(this, &OAIItemAttributeApiRequest::itemAttributeRead, handler.data(), &OAIItemAttributeApiHandler::itemAttributeRead); qint32 id; fromStringValue(idstr, id); emit itemAttributeRead(id); } void OAIItemAttributeApiRequest::itemAttributeListResponse(const QString& res){ setSocketResponseHeaders(); socket->write(::OpenAPI::toStringValue(res).toUtf8()); if(socket->isOpen()){ socket->close(); } } void OAIItemAttributeApiRequest::itemAttributeReadResponse(const QString& res){ setSocketResponseHeaders(); socket->write(::OpenAPI::toStringValue(res).toUtf8()); if(socket->isOpen()){ socket->close(); } } void OAIItemAttributeApiRequest::itemAttributeListError(const QString& res, QNetworkReply::NetworkError error_type, QString& error_str){ Q_UNUSED(error_type); // TODO: Remap error_type to QHttpEngine::Socket errors setSocketResponseHeaders(); Q_UNUSED(error_str); // response will be used instead of error string socket->write(::OpenAPI::toStringValue(res).toUtf8()); if(socket->isOpen()){ socket->close(); } } void OAIItemAttributeApiRequest::itemAttributeReadError(const QString& res, QNetworkReply::NetworkError error_type, QString& error_str){ Q_UNUSED(error_type); // TODO: Remap error_type to QHttpEngine::Socket errors setSocketResponseHeaders(); Q_UNUSED(error_str); // response will be used instead of error string socket->write(::OpenAPI::toStringValue(res).toUtf8()); if(socket->isOpen()){ socket->close(); } } void OAIItemAttributeApiRequest::sendCustomResponse(QByteArray & res, QNetworkReply::NetworkError error_type){ Q_UNUSED(error_type); // TODO socket->write(res); if(socket->isOpen()){ socket->close(); } } void OAIItemAttributeApiRequest::sendCustomResponse(QIODevice *res, QNetworkReply::NetworkError error_type){ Q_UNUSED(error_type); // TODO socket->write(res->readAll()); if(socket->isOpen()){ socket->close(); } } }
// Copyright (c) 2011-2013 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 "key.h" #include "keystore.h" #include "policy/policy.h" #include "script/script.h" #include "script/script_error.h" #include "script/interpreter.h" #include "script/sign.h" #include "uint256.h" #include "test/test_smilecoin.h" #ifdef ENABLE_WALLET #include "wallet/wallet_ismine.h" #endif #include <boost/foreach.hpp> #include <boost/test/unit_test.hpp> using namespace std; typedef vector<unsigned char> valtype; BOOST_FIXTURE_TEST_SUITE(multisig_tests, BasicTestingSetup) CScript sign_multisig(CScript scriptPubKey, vector<CKey> keys, CTransaction transaction, int whichIn) { uint256 hash = SignatureHash(scriptPubKey, transaction, whichIn, SIGHASH_ALL); CScript result; result << OP_0; // CHECKMULTISIG bug workaround BOOST_FOREACH(const CKey &key, keys) { vector<unsigned char> vchSig; BOOST_CHECK(key.Sign(hash, vchSig)); vchSig.push_back((unsigned char)SIGHASH_ALL); result << vchSig; } return result; } BOOST_AUTO_TEST_CASE(multisig_verify) { unsigned int flags = SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_STRICTENC; ScriptError err; CKey key[4]; for (int i = 0; i < 4; i++) key[i].MakeNewKey(true); CScript a_and_b; a_and_b << OP_2 << ToByteVector(key[0].GetPubKey()) << ToByteVector(key[1].GetPubKey()) << OP_2 << OP_CHECKMULTISIG; CScript a_or_b; a_or_b << OP_1 << ToByteVector(key[0].GetPubKey()) << ToByteVector(key[1].GetPubKey()) << OP_2 << OP_CHECKMULTISIG; CScript escrow; escrow << OP_2 << ToByteVector(key[0].GetPubKey()) << ToByteVector(key[1].GetPubKey()) << ToByteVector(key[2].GetPubKey()) << OP_3 << OP_CHECKMULTISIG; CMutableTransaction txFrom; // Funding transaction txFrom.vout.resize(3); txFrom.vout[0].scriptPubKey = a_and_b; txFrom.vout[1].scriptPubKey = a_or_b; txFrom.vout[2].scriptPubKey = escrow; CMutableTransaction txTo[3]; // Spending transaction for (int i = 0; i < 3; i++) { txTo[i].vin.resize(1); txTo[i].vout.resize(1); txTo[i].vin[0].prevout.n = i; txTo[i].vin[0].prevout.hash = txFrom.GetHash(); txTo[i].vout[0].nValue = 1; } vector<CKey> keys; CScript s; // Test a AND b: keys.assign(1,key[0]); keys.push_back(key[1]); s = sign_multisig(a_and_b, keys, txTo[0], 0); BOOST_CHECK(VerifyScript(s, a_and_b, flags, MutableTransactionSignatureChecker(&txTo[0], 0), &err)); BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err)); for (int i = 0; i < 4; i++) { keys.assign(1,key[i]); s = sign_multisig(a_and_b, keys, txTo[0], 0); BOOST_CHECK_MESSAGE(!VerifyScript(s, a_and_b, flags, MutableTransactionSignatureChecker(&txTo[0], 0), &err), strprintf("a&b 1: %d", i)); BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_INVALID_STACK_OPERATION, ScriptErrorString(err)); keys.assign(1,key[1]); keys.push_back(key[i]); s = sign_multisig(a_and_b, keys, txTo[0], 0); BOOST_CHECK_MESSAGE(!VerifyScript(s, a_and_b, flags, MutableTransactionSignatureChecker(&txTo[0], 0), &err), strprintf("a&b 2: %d", i)); BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_EVAL_FALSE, ScriptErrorString(err)); } // Test a OR b: for (int i = 0; i < 4; i++) { keys.assign(1,key[i]); s = sign_multisig(a_or_b, keys, txTo[1], 0); if (i == 0 || i == 1) { BOOST_CHECK_MESSAGE(VerifyScript(s, a_or_b, flags, MutableTransactionSignatureChecker(&txTo[1], 0), &err), strprintf("a|b: %d", i)); BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err)); } else { BOOST_CHECK_MESSAGE(!VerifyScript(s, a_or_b, flags, MutableTransactionSignatureChecker(&txTo[1], 0), &err), strprintf("a|b: %d", i)); BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_EVAL_FALSE, ScriptErrorString(err)); } } s.clear(); s << OP_0 << OP_1; BOOST_CHECK(!VerifyScript(s, a_or_b, flags, MutableTransactionSignatureChecker(&txTo[1], 0), &err)); BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_SIG_DER, ScriptErrorString(err)); for (int i = 0; i < 4; i++) for (int j = 0; j < 4; j++) { keys.assign(1,key[i]); keys.push_back(key[j]); s = sign_multisig(escrow, keys, txTo[2], 0); if (i < j && i < 3 && j < 3) { BOOST_CHECK_MESSAGE(VerifyScript(s, escrow, flags, MutableTransactionSignatureChecker(&txTo[2], 0), &err), strprintf("escrow 1: %d %d", i, j)); BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err)); } else { BOOST_CHECK_MESSAGE(!VerifyScript(s, escrow, flags, MutableTransactionSignatureChecker(&txTo[2], 0), &err), strprintf("escrow 2: %d %d", i, j)); BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_EVAL_FALSE, ScriptErrorString(err)); } } } BOOST_AUTO_TEST_CASE(multisig_IsStandard) { CKey key[4]; for (int i = 0; i < 4; i++) key[i].MakeNewKey(true); txnouttype whichType; CScript a_and_b; a_and_b << OP_2 << ToByteVector(key[0].GetPubKey()) << ToByteVector(key[1].GetPubKey()) << OP_2 << OP_CHECKMULTISIG; BOOST_CHECK(::IsStandard(a_and_b, whichType)); CScript a_or_b; a_or_b << OP_1 << ToByteVector(key[0].GetPubKey()) << ToByteVector(key[1].GetPubKey()) << OP_2 << OP_CHECKMULTISIG; BOOST_CHECK(::IsStandard(a_or_b, whichType)); CScript escrow; escrow << OP_2 << ToByteVector(key[0].GetPubKey()) << ToByteVector(key[1].GetPubKey()) << ToByteVector(key[2].GetPubKey()) << OP_3 << OP_CHECKMULTISIG; BOOST_CHECK(::IsStandard(escrow, whichType)); CScript one_of_four; one_of_four << OP_1 << ToByteVector(key[0].GetPubKey()) << ToByteVector(key[1].GetPubKey()) << ToByteVector(key[2].GetPubKey()) << ToByteVector(key[3].GetPubKey()) << OP_4 << OP_CHECKMULTISIG; BOOST_CHECK(!::IsStandard(one_of_four, whichType)); CScript malformed[6]; malformed[0] << OP_3 << ToByteVector(key[0].GetPubKey()) << ToByteVector(key[1].GetPubKey()) << OP_2 << OP_CHECKMULTISIG; malformed[1] << OP_2 << ToByteVector(key[0].GetPubKey()) << ToByteVector(key[1].GetPubKey()) << OP_3 << OP_CHECKMULTISIG; malformed[2] << OP_0 << ToByteVector(key[0].GetPubKey()) << ToByteVector(key[1].GetPubKey()) << OP_2 << OP_CHECKMULTISIG; malformed[3] << OP_1 << ToByteVector(key[0].GetPubKey()) << ToByteVector(key[1].GetPubKey()) << OP_0 << OP_CHECKMULTISIG; malformed[4] << OP_1 << ToByteVector(key[0].GetPubKey()) << ToByteVector(key[1].GetPubKey()) << OP_CHECKMULTISIG; malformed[5] << OP_1 << ToByteVector(key[0].GetPubKey()) << ToByteVector(key[1].GetPubKey()); for (int i = 0; i < 6; i++) BOOST_CHECK(!::IsStandard(malformed[i], whichType)); } BOOST_AUTO_TEST_CASE(multisig_Solver1) { // Tests Solver() that returns lists of keys that are // required to satisfy a ScriptPubKey // // Also tests IsMine() and ExtractDestination() // // Note: ExtractDestination for the multisignature transactions // always returns false for this release, even if you have // one key that would satisfy an (a|b) or 2-of-3 keys needed // to spend an escrow transaction. // CBasicKeyStore keystore, emptykeystore, partialkeystore; CKey key[3]; CTxDestination keyaddr[3]; for (int i = 0; i < 3; i++) { key[i].MakeNewKey(true); keystore.AddKey(key[i]); keyaddr[i] = key[i].GetPubKey().GetID(); } partialkeystore.AddKey(key[0]); { vector<valtype> solutions; txnouttype whichType; CScript s; s << ToByteVector(key[0].GetPubKey()) << OP_CHECKSIG; BOOST_CHECK(Solver(s, whichType, solutions)); BOOST_CHECK(solutions.size() == 1); CTxDestination addr; BOOST_CHECK(ExtractDestination(s, addr)); BOOST_CHECK(addr == keyaddr[0]); #ifdef ENABLE_WALLET BOOST_CHECK(IsMine(keystore, s)); BOOST_CHECK(!IsMine(emptykeystore, s)); #endif } { vector<valtype> solutions; txnouttype whichType; CScript s; s << OP_DUP << OP_HASH160 << ToByteVector(key[0].GetPubKey().GetID()) << OP_EQUALVERIFY << OP_CHECKSIG; BOOST_CHECK(Solver(s, whichType, solutions)); BOOST_CHECK(solutions.size() == 1); CTxDestination addr; BOOST_CHECK(ExtractDestination(s, addr)); BOOST_CHECK(addr == keyaddr[0]); #ifdef ENABLE_WALLET BOOST_CHECK(IsMine(keystore, s)); BOOST_CHECK(!IsMine(emptykeystore, s)); #endif } { vector<valtype> solutions; txnouttype whichType; CScript s; s << OP_2 << ToByteVector(key[0].GetPubKey()) << ToByteVector(key[1].GetPubKey()) << OP_2 << OP_CHECKMULTISIG; BOOST_CHECK(Solver(s, whichType, solutions)); BOOST_CHECK_EQUAL(solutions.size(), 4U); CTxDestination addr; BOOST_CHECK(!ExtractDestination(s, addr)); #ifdef ENABLE_WALLET BOOST_CHECK(IsMine(keystore, s)); BOOST_CHECK(!IsMine(emptykeystore, s)); BOOST_CHECK(!IsMine(partialkeystore, s)); #endif } { vector<valtype> solutions; txnouttype whichType; CScript s; s << OP_1 << ToByteVector(key[0].GetPubKey()) << ToByteVector(key[1].GetPubKey()) << OP_2 << OP_CHECKMULTISIG; BOOST_CHECK(Solver(s, whichType, solutions)); BOOST_CHECK_EQUAL(solutions.size(), 4U); vector<CTxDestination> addrs; int nRequired; BOOST_CHECK(ExtractDestinations(s, whichType, addrs, nRequired)); BOOST_CHECK(addrs[0] == keyaddr[0]); BOOST_CHECK(addrs[1] == keyaddr[1]); BOOST_CHECK(nRequired == 1); #ifdef ENABLE_WALLET BOOST_CHECK(IsMine(keystore, s)); BOOST_CHECK(!IsMine(emptykeystore, s)); BOOST_CHECK(!IsMine(partialkeystore, s)); #endif } { vector<valtype> solutions; txnouttype whichType; CScript s; s << OP_2 << ToByteVector(key[0].GetPubKey()) << ToByteVector(key[1].GetPubKey()) << ToByteVector(key[2].GetPubKey()) << OP_3 << OP_CHECKMULTISIG; BOOST_CHECK(Solver(s, whichType, solutions)); BOOST_CHECK(solutions.size() == 5); } } BOOST_AUTO_TEST_CASE(multisig_Sign) { // Test SignSignature() (and therefore the version of Solver() that signs transactions) CBasicKeyStore keystore; CKey key[4]; for (int i = 0; i < 4; i++) { key[i].MakeNewKey(true); keystore.AddKey(key[i]); } CScript a_and_b; a_and_b << OP_2 << ToByteVector(key[0].GetPubKey()) << ToByteVector(key[1].GetPubKey()) << OP_2 << OP_CHECKMULTISIG; CScript a_or_b; a_or_b << OP_1 << ToByteVector(key[0].GetPubKey()) << ToByteVector(key[1].GetPubKey()) << OP_2 << OP_CHECKMULTISIG; CScript escrow; escrow << OP_2 << ToByteVector(key[0].GetPubKey()) << ToByteVector(key[1].GetPubKey()) << ToByteVector(key[2].GetPubKey()) << OP_3 << OP_CHECKMULTISIG; CMutableTransaction txFrom; // Funding transaction txFrom.vout.resize(3); txFrom.vout[0].scriptPubKey = a_and_b; txFrom.vout[1].scriptPubKey = a_or_b; txFrom.vout[2].scriptPubKey = escrow; CMutableTransaction txTo[3]; // Spending transaction for (int i = 0; i < 3; i++) { txTo[i].vin.resize(1); txTo[i].vout.resize(1); txTo[i].vin[0].prevout.n = i; txTo[i].vin[0].prevout.hash = txFrom.GetHash(); txTo[i].vout[0].nValue = 1; } for (int i = 0; i < 3; i++) { BOOST_CHECK_MESSAGE(SignSignature(keystore, txFrom, txTo[i], 0), strprintf("SignSignature %d", i)); } } BOOST_AUTO_TEST_SUITE_END()
/* * libjingle * Copyright 2004--2011, Google Inc. * * 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. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 "talk/app/webrtcsessionimpl.h" #include <string> #include <vector> #include "talk/app/pc_transport_impl.h" #include "talk/app/peerconnection.h" #include "talk/app/webrtc_json.h" #include "talk/base/common.h" #include "talk/base/json.h" #include "talk/base/scoped_ptr.h" #include "talk/p2p/base/constants.h" #include "talk/p2p/base/sessiondescription.h" #include "talk/p2p/base/p2ptransport.h" #include "talk/session/phone/channel.h" #include "talk/session/phone/channelmanager.h" #include "talk/session/phone/mediasessionclient.h" #include "talk/session/phone/voicechannel.h" using namespace cricket; namespace webrtc { enum { MSG_RTC_CREATEVIDEOCHANNEL = 1, MSG_RTC_CREATEAUDIOCHANNEL = 2, MSG_RTC_SETSTATE = 3, MSG_RTC_SETVIDEOCAPTURE = 4, MSG_RTC_CANDIDATETIMEOUT = 5, MSG_RTC_SETEXTERNALRENDERER = 6, MSG_RTC_SETCRICKETRENDERER = 7, MSG_RTC_CHANNELENABLE = 8, MSG_RTC_SIGNALONWRITABLESTATE = 9, MSG_RTC_DESTROYVOICECHANNEL = 10, MSG_RTC_DESTROYVIDEOCHANNEL = 11, MSG_RTC_SENDLOCALDESCRIPTION = 12, MSG_RTC_REMOVESTREAM = 13, MSG_RTC_REMOVEALLSTREAMS = 14, MSG_RTC_ENABLEALLSTREAMS = 15, MSG_RTC_SETSESSIONERROR = 16, }; struct CreateChannelParams : public talk_base::MessageData { CreateChannelParams(const std::string& content_name, bool rtcp, cricket::VoiceChannel* voice_channel) : content_name(content_name), rtcp(rtcp), voice_channel(voice_channel), video_channel(NULL) {} std::string content_name; bool rtcp; cricket::VoiceChannel* voice_channel; cricket::VideoChannel* video_channel; }; struct SetStateParams : public talk_base::MessageData { SetStateParams(int state) : state(state) {} int state; bool result; }; struct CaptureParams : public talk_base::MessageData { explicit CaptureParams(bool c) : capture(c), result(CR_FAILURE) {} bool capture; CaptureResult result; }; struct ExternalRenderParams : public talk_base::MessageData { ExternalRenderParams(const std::string& stream_id, ExternalRenderer* external_renderer) : stream_id(stream_id), external_renderer(external_renderer), result(false) {} const std::string stream_id; ExternalRenderer* external_renderer; bool result; }; struct CricketRenderParams : public talk_base::MessageData { CricketRenderParams(const std::string& stream_id, cricket::VideoRenderer* renderer) : stream_id(stream_id), renderer(renderer), result(false) {} const std::string stream_id; cricket::VideoRenderer* renderer; bool result; }; struct ChannelEnableParams : public talk_base::MessageData { ChannelEnableParams(cricket::BaseChannel* channel, bool enable) : channel(channel), enable(enable) {} cricket::BaseChannel* channel; bool enable; }; static const int kAudioMonitorPollFrequency = 100; static const int kMonitorPollFrequency = 1000; // We allow 30 seconds to establish a connection; beyond that we consider // it an error static const int kCallSetupTimeout = 30 * 1000; // A loss of connectivity is probably due to the Internet connection going // down, and it might take a while to come back on wireless networks, so we // use a longer timeout for that. static const int kCallLostTimeout = 60 * 1000; static const uint32 kCandidateTimeoutId = 101; typedef std::vector<StreamInfo*> StreamMap; // not really a map (vector) WebRTCSessionImpl::WebRTCSessionImpl( const std::string& id, const std::string& direction, cricket::PortAllocator* allocator, cricket::ChannelManager* channelmgr, PeerConnection* connection, talk_base::Thread* signaling_thread) : WebRTCSession(id, direction, allocator, connection, signaling_thread), channel_manager_(channelmgr), all_writable_(false), muted_(false), camera_muted_(false), setup_timeout_(kCallSetupTimeout), signal_initiated_(false) { } WebRTCSessionImpl::~WebRTCSessionImpl() { if (state_ != STATE_RECEIVEDTERMINATE) { Terminate(); } } bool WebRTCSessionImpl::CreateP2PTransportChannel(const std::string& stream_id, bool video) { PC_Transport_Impl* transport = new PC_Transport_Impl(this); ASSERT(transport != NULL); const std::string name = ((video) ? "video_rtp" : "rtp"); if (!transport->Init(name)) { delete transport; return false; } ASSERT(transport_channels_.find(name) == transport_channels_.end()); transport_channels_[name] = transport; StreamInfo* stream_info = new StreamInfo(stream_id); stream_info->transport = transport; stream_info->video = video; streams_.push_back(stream_info); return true; } bool WebRTCSessionImpl::CreateVoiceChannel(const std::string& stream_id) { this->SignalVoiceChannel.connect( this, &WebRTCSessionImpl::OnVoiceChannelCreated); signaling_thread_->Post(this, MSG_RTC_CREATEAUDIOCHANNEL, new CreateChannelParams(stream_id, true, NULL)); return true; } cricket::VoiceChannel* WebRTCSessionImpl::CreateVoiceChannel_w( const std::string& content_name, bool rtcp) { cricket::VoiceChannel* voice_channel = channel_manager_->CreateVoiceChannel( this, content_name, rtcp); return voice_channel; } void WebRTCSessionImpl::OnVoiceChannelCreated( cricket::VoiceChannel* voice_channel, std::string& stream_id) { StreamMap::iterator iter; for (iter = streams_.begin(); iter != streams_.end(); ++iter) { StreamInfo* stream_info = (*iter); if (stream_info->stream_id.compare(stream_id) == 0) { ASSERT(stream_info->channel == NULL); stream_info->channel = voice_channel; stream_info->media_channel = voice_channel->media_channel()->GetMediaChannelId(); if (incoming()) { // change stream id to audio-<media_channel> // ^^ - The code that does this has been disabled because // it causes us to not be able to find the stream by name later. // Instead, we could store the channel_id as an int member with // stream_info? streams_.erase(iter); #if 0 stream_info->stream_id.append("-"); stream_info->stream_id.append( talk_base::ToString(stream_info->media_channel)); #endif streams_.push_back(stream_info); connection()->OnAddStream( stream_info->stream_id, stream_info->media_channel, false); } else { connection()->OnRtcMediaChannelCreated( stream_id, stream_info->media_channel, false); } break; } } } bool WebRTCSessionImpl::CreateVideoChannel(const std::string& stream_id) { this->SignalVideoChannel.connect( this, &WebRTCSessionImpl::OnVideoChannelCreated); signaling_thread_->Post(this, MSG_RTC_CREATEVIDEOCHANNEL, new CreateChannelParams(stream_id, true, NULL)); return true; } cricket::VideoChannel* WebRTCSessionImpl::CreateVideoChannel_w( const std::string& content_name, bool rtcp, cricket::VoiceChannel* voice_channel) { cricket::VideoChannel* video_channel = channel_manager_->CreateVideoChannel( this, content_name, rtcp, voice_channel); return video_channel; } void WebRTCSessionImpl::OnVideoChannelCreated( cricket::VideoChannel* video_channel, std::string& stream_id) { StreamMap::iterator iter; for (iter = streams_.begin(); iter != streams_.end(); ++iter) { StreamInfo* stream_info = (*iter); if (stream_info->stream_id.compare(stream_id) == 0) { ASSERT(stream_info->channel == NULL); stream_info->channel = video_channel; stream_info->media_channel = video_channel->media_channel()->GetMediaChannelId(); if (incoming()) { // change stream id to video-<media_channel> // ^^ - The code that does this has been disabled because // it causes us to not be able to find the stream by name later. // Instead, we could store the channel_id as an int member with // stream_info? streams_.erase(iter); #if 0 stream_info->stream_id.append("-"); stream_info->stream_id.append( talk_base::ToString(stream_info->media_channel)); #endif streams_.push_back(stream_info); connection()->OnAddStream( stream_info->stream_id, stream_info->media_channel, true); } else { connection()->OnRtcMediaChannelCreated( stream_id, stream_info->media_channel, true); } break; } } } bool WebRTCSessionImpl::SetVideoRenderer(const std::string& stream_id, cricket::VideoRenderer* renderer) { if(signaling_thread_ != talk_base::Thread::Current()) { signaling_thread_->Post(this, MSG_RTC_SETCRICKETRENDERER, new CricketRenderParams(stream_id, renderer), true); return true; } ASSERT(signaling_thread_ == talk_base::Thread::Current()); bool ret = false; StreamMap::iterator iter; for (iter = streams_.begin(); iter != streams_.end(); ++iter) { StreamInfo* stream_info = (*iter); if (stream_info->stream_id.compare(stream_id) == 0) { ASSERT(stream_info->channel != NULL); ASSERT(stream_info->video); cricket::VideoChannel* channel = static_cast<cricket::VideoChannel*>( stream_info->channel); ret = channel->SetRenderer(0, renderer); break; } } return ret; } bool WebRTCSessionImpl::SetVideoRenderer(const std::string& stream_id, ExternalRenderer* external_renderer) { if(signaling_thread_ != talk_base::Thread::Current()) { signaling_thread_->Post(this, MSG_RTC_SETEXTERNALRENDERER, new ExternalRenderParams(stream_id, external_renderer), true); return true; } ASSERT(signaling_thread_ == talk_base::Thread::Current()); bool ret = false; StreamMap::iterator iter; for (iter = streams_.begin(); iter != streams_.end(); ++iter) { StreamInfo* stream_info = (*iter); if (stream_info->stream_id.compare(stream_id) == 0) { ASSERT(stream_info->channel != NULL); ASSERT(stream_info->video); cricket::VideoChannel* channel = static_cast<cricket::VideoChannel*> ( stream_info->channel); ret = channel->media_channel()->SetExternalRenderer(0, external_renderer); break; } } return ret; } void WebRTCSessionImpl::OnMessage(talk_base::Message* message) { using talk_base::TypedMessageData; talk_base::MessageData* data = message->pdata; switch(message->message_id) { case MSG_RTC_CREATEVIDEOCHANNEL: { CreateChannelParams* p = reinterpret_cast<CreateChannelParams*>(data); p->video_channel = CreateVideoChannel_w(p->content_name, p->rtcp, p->voice_channel); SignalVideoChannel(p->video_channel, p->content_name); delete p; break; } case MSG_RTC_CREATEAUDIOCHANNEL: { CreateChannelParams* p = reinterpret_cast<CreateChannelParams*>(data); p->voice_channel = CreateVoiceChannel_w(p->content_name, p->rtcp); SignalVoiceChannel(p->voice_channel, p->content_name); delete p; break; } case MSG_RTC_DESTROYVOICECHANNEL: { cricket::VoiceChannel* channel = reinterpret_cast<TypedMessageData<cricket::VoiceChannel*>*>(data) ->data(); std::string name(channel->content_name()); DestroyVoiceChannel_w(channel); delete data; break; } case MSG_RTC_SETSESSIONERROR: { int err = reinterpret_cast<TypedMessageData<int>*>(data)->data(); BaseSession::SetError(static_cast<Error>(err)); delete data; break; } case MSG_RTC_DESTROYVIDEOCHANNEL: { cricket::VideoChannel* channel = reinterpret_cast<TypedMessageData<cricket::VideoChannel*>*>(data) ->data(); std::string name(channel->content_name()); DestroyVideoChannel_w(channel); delete data; break; } case MSG_RTC_REMOVESTREAM : { std::string stream_id( reinterpret_cast<TypedMessageData<std::string>*>(data)->data()); RemoveStream_w(stream_id); delete data; break; } case MSG_RTC_REMOVEALLSTREAMS : { RemoveAllStreams_w(); delete data; break; } case MSG_RTC_ENABLEALLSTREAMS: { EnableAllStreams_w(); delete data; break; } case MSG_RTC_SETSTATE : { SetSessionState_w(); break; } case MSG_RTC_SETVIDEOCAPTURE : { CaptureParams* p = reinterpret_cast<CaptureParams*>(data); p->result = SetVideoCapture_w(p->capture); delete p; break; } case MSG_RTC_SETEXTERNALRENDERER : { ExternalRenderParams* p = reinterpret_cast<ExternalRenderParams*>(data); p->result = SetVideoRenderer(p->stream_id, p->external_renderer); delete p; break; } case MSG_RTC_SETCRICKETRENDERER : { CricketRenderParams* p = reinterpret_cast<CricketRenderParams*>(data); p->result = SetVideoRenderer(p->stream_id, p->renderer); delete p; break; } case MSG_RTC_CHANNELENABLE : { ChannelEnableParams* p = reinterpret_cast<ChannelEnableParams*>(data); ChannelEnable_w(p->channel, p->enable); delete p; break; } case MSG_RTC_SIGNALONWRITABLESTATE : { cricket::TransportChannel* channel = reinterpret_cast<TypedMessageData<cricket::TransportChannel*>*>(data) ->data(); SignalOnWritableState_w(channel); delete data; break; } case MSG_RTC_CANDIDATETIMEOUT: { break; } case MSG_RTC_SENDLOCALDESCRIPTION : { SendLocalDescription_w(); break; } default: { WebRTCSession::OnMessage(message); } } } bool WebRTCSessionImpl::Initiate() { if (streams_.empty()) { // nothing to initiate return false; } // Enable all the channels signaling_thread_->Post(this, MSG_RTC_ENABLEALLSTREAMS); SetVideoCapture(true); signal_initiated_ = true; if (local_candidates_.size() == streams_.size()) { SendLocalDescription(); } return true; } void WebRTCSessionImpl::ChannelEnable(cricket::BaseChannel* channel, bool enable) { ASSERT(channel); signaling_thread_->Post(this, MSG_RTC_CHANNELENABLE, new ChannelEnableParams(channel, enable), true); } void WebRTCSessionImpl::ChannelEnable_w(cricket::BaseChannel* channel, bool enable) { if (channel) { channel->Enable(enable); } } void WebRTCSessionImpl::SetSessionState(State state) { session_state_ = state; signaling_thread_->Post(this, MSG_RTC_SETSTATE); } void WebRTCSessionImpl::SetSessionState_w() { SetState(session_state_); } bool WebRTCSessionImpl::SetVideoCapture(bool capture) { signaling_thread_->Post(this, MSG_RTC_SETVIDEOCAPTURE, new CaptureParams(capture), true); return true; } cricket::CaptureResult WebRTCSessionImpl::SetVideoCapture_w(bool capture) { ASSERT(signaling_thread_ == talk_base::Thread::Current()); return channel_manager_->SetVideoCapture(capture); } void WebRTCSessionImpl::OnVoiceChannelError( cricket::VoiceChannel* voice_channel, uint32 ssrc, cricket::VoiceMediaChannel::Error error) { //report error to connection } void WebRTCSessionImpl::OnVideoChannelError( cricket::VideoChannel* video_channel, uint32 ssrc, cricket::VideoMediaChannel::Error error) { //report error to connection } void WebRTCSessionImpl::RemoveStream_w(const std::string& stream_id) { bool found = false; StreamMap::iterator iter; std::string candidate_name; for (iter = streams_.begin(); iter != streams_.end(); ++iter) { StreamInfo* sinfo = (*iter); candidate_name = sinfo->transport->name(); if (sinfo->stream_id.compare(stream_id) == 0) { DisableLocalCandidate(candidate_name); if (!sinfo->video) { cricket::VoiceChannel* channel = static_cast<cricket::VoiceChannel*> ( sinfo->channel); channel_manager_->DestroyVoiceChannel(channel); } else { cricket::VideoChannel* channel = static_cast<cricket::VideoChannel*> ( sinfo->channel); channel_manager_->DestroyVideoChannel(channel); } // channel and transport will be deleted in // DestroyVoiceChannel/DestroyVideoChannel found = true; break; } } if (!found) { LOG(LS_ERROR) << "No streams found for stream id " << stream_id; //TODO - trigger onError callback } } bool WebRTCSessionImpl::RemoveStream(const std::string& stream_id) { bool ret = true; if ((state_ == STATE_RECEIVEDACCEPT) || (state_ == STATE_SENTACCEPT)) { signaling_thread_->Post(this, MSG_RTC_REMOVESTREAM, new talk_base::TypedMessageData<std::string>(stream_id)); } else { LOG(LS_ERROR) << "Invalid session state -" << state_; ret = false; } return ret; } void WebRTCSessionImpl::DisableLocalCandidate(const std::string& name) { for (size_t i = 0; i < local_candidates_.size(); ++i) { if (local_candidates_[i].name().compare(name) == 0) { talk_base::SocketAddress address(local_candidates_[i].address().ip(), 0); local_candidates_[i].set_address(address); } } } void WebRTCSessionImpl::RemoveAllStreams_w() { // First build a list of streams to remove and then remove them. // The reason we do this is that if we remove the streams inside the // loop, a stream might get removed while we're enumerating and the iterator // will become invalid (and we crash). std::vector<std::string> streams_to_remove; StreamMap::iterator iter; for (iter = streams_.begin(); iter != streams_.end(); ++iter) streams_to_remove.push_back((*iter)->stream_id); for (std::vector<std::string>::iterator i = streams_to_remove.begin(); i != streams_to_remove.end(); ++i) RemoveStream_w(*i); SignalOnRemoveStream(this); } void WebRTCSessionImpl::EnableAllStreams_w() { StreamMap::const_iterator i; for (i = streams_.begin(); i != streams_.end(); ++i) { cricket::BaseChannel* channel = (*i)->channel; if (channel) channel->Enable(true); } } void WebRTCSessionImpl::RemoveAllStreams() { signaling_thread_->Post(this, MSG_RTC_REMOVEALLSTREAMS); } bool WebRTCSessionImpl::HasStream(const std::string& stream_id) const { StreamMap::const_iterator iter; for (iter = streams_.begin(); iter != streams_.end(); ++iter) { StreamInfo* sinfo = (*iter); if (stream_id.compare(sinfo->stream_id) == 0) { return true; } } return false; } bool WebRTCSessionImpl::HasStream(bool video) const { StreamMap::const_iterator iter; for (iter = streams_.begin(); iter != streams_.end(); ++iter) { StreamInfo* sinfo = (*iter); if (sinfo->video == video) { return true; } } return false; } bool WebRTCSessionImpl::HasAudioStream() const { return HasStream(false); } bool WebRTCSessionImpl::HasVideoStream() const { return HasStream(true); } void WebRTCSessionImpl::OnRequestSignaling(cricket::Transport* transport) { transport->OnSignalingReady(); } cricket::TransportChannel* WebRTCSessionImpl::CreateChannel( const std::string& content_name, const std::string& name) { // channel must be already present in the vector StreamMap::iterator iter; for (iter = streams_.begin(); iter != streams_.end(); ++iter) { if (content_name.compare((*iter)->stream_id) == 0) { StreamInfo* sinfo = (*iter); // if it's a incoming call, remote candidates are already received // in initial SignalingMessage. apply now if (incoming() && state_ == STATE_RECEIVEDINITIATE) { // process the remote candidates std::vector<cricket::Candidate>::iterator iter; for (iter = remote_candidates_.begin(); iter != remote_candidates_.end(); ++iter) { std::string tname = iter->name(); TransportChannelMap::iterator titer = transport_channels_.find(tname); if (titer != transport_channels_.end()) { titer->second->AddRemoteCandidate(*iter); } } } return sinfo->transport->GetP2PChannel(); } } return NULL; } cricket::TransportChannel* WebRTCSessionImpl::GetChannel( const std::string& content_name, const std::string& name) { StreamMap::iterator iter; for (iter = streams_.begin(); iter != streams_.end(); ++iter) { if (content_name.compare((*iter)->stream_id) == 0) { PC_Transport_Impl* transport = (*iter)->transport; return transport->GetP2PChannel(); } } return NULL; } void WebRTCSessionImpl::DestroyChannel( const std::string& content_name, const std::string& name) { bool found = false; StreamMap::iterator iter; for (iter = streams_.begin(); iter != streams_.end(); ++iter) { if (content_name.compare((*iter)->stream_id) == 0) { PC_Transport_Impl* transport = (*iter)->transport; delete transport; (*iter)->transport = NULL; connection()->OnRemoveStream((*iter)->stream_id, (*iter)->media_channel, (*iter)->video); streams_.erase(iter); found = true; break; } } } void WebRTCSessionImpl::DestroyVoiceChannel_w( cricket::VoiceChannel* channel) { channel_manager_->DestroyVoiceChannel(channel); } void WebRTCSessionImpl::DestroyVideoChannel_w( cricket::VideoChannel* channel) { channel_manager_->DestroyVideoChannel(channel); } void WebRTCSessionImpl::StartTransportTimeout(int timeout) { talk_base::Thread::Current()->PostDelayed(timeout, this, MSG_RTC_CANDIDATETIMEOUT, NULL); } void WebRTCSessionImpl::ClearTransportTimeout() { //LOG(LS_INFO) << "ClearTransportTimeout"; talk_base::Thread::Current()->Clear(this, MSG_RTC_CANDIDATETIMEOUT); } void WebRTCSessionImpl::NotifyTransportState() { } bool WebRTCSessionImpl::OnRemoteDescription(Json::Value& desc) { if ((!incoming() && state() != STATE_SENTINITIATE) || (incoming() && state() != STATE_INIT)) { LOG(LS_WARNING) << "Invalid session state" ; return false; } talk_base::scoped_ptr<cricket::AudioContentDescription> audio( new cricket::AudioContentDescription()); talk_base::scoped_ptr<cricket::VideoContentDescription> video( new cricket::VideoContentDescription()); //TODO- get media description from Json format //set_remote_description(); if (incoming()) { SetState(STATE_RECEIVEDINITIATE); } return true; } bool WebRTCSessionImpl::OnInitiateMessage( const cricket::SessionDescription* offer, std::vector<cricket::Candidate>& candidates) { if (!offer) { LOG(LS_ERROR) << "No SessionDescription from peer"; return false; } set_remote_description(offer); const cricket::SessionDescription* answer = CreateAnswer(offer); const cricket::ContentInfo* audio_content = GetFirstAudioContent(answer); const cricket::ContentInfo* video_content = GetFirstVideoContent(answer); if (!audio_content && !video_content) { // no codec information of audio and video set_remote_description(NULL); delete answer; return false; } SetSessionState(STATE_RECEIVEDINITIATE); bool ret = true; if (audio_content) { ret = !HasAudioStream() && CreateP2PTransportChannel(audio_content->name, false) && CreateVoiceChannel(audio_content->name); } if (video_content) { ret = !HasVideoStream() && CreateP2PTransportChannel(video_content->name, true) && CreateVideoChannel(video_content->name); } delete answer; if (!ret) { LOG(LS_ERROR) << "Failed to create channel for incoming media stream"; return false; } // Candidate processing. ASSERT(candidates.size()); remote_candidates_.clear(); remote_candidates_.insert(remote_candidates_.begin(), candidates.begin(), candidates.end()); return true; } bool WebRTCSessionImpl::OnRemoteDescription( const cricket::SessionDescription* rdesc, std::vector<cricket::Candidate>& candidates) { if (state() == STATE_SENTACCEPT || state() == STATE_RECEIVEDACCEPT) { return OnRemoteDescriptionUpdate(rdesc, candidates); } if ((!incoming()) && (state() != STATE_SENTINITIATE)) { LOG(LS_ERROR) << "invalid session state"; return false; } // cricket::SessionDescription* answer = new cricket::SessionDescription(); // const ContentInfo* audio_content = GetFirstAudioContent(rdesc); // if (audio_content) { // const AudioContentDescription* audio_offer = // static_cast<const AudioContentDescription*>(audio_content->description); // // AudioContentDescription* audio_accept = new AudioContentDescription(); // // // for (AudioCodecs::const_iterator theirs = audio_offer->codecs().begin(); // theirs != audio_offer->codecs().end(); ++theirs) { // audio_accept->AddCodec(*theirs); // } // audio_accept->SortCodecs(); // answer->AddContent(audio_content->name, audio_content->type, audio_accept); // } // // const ContentInfo* video_content = GetFirstVideoContent(rdesc); // if (video_content) { // const VideoContentDescription* video_offer = // static_cast<const VideoContentDescription*>(video_content->description); // // VideoContentDescription* video_accept = new VideoContentDescription(); // // for (VideoCodecs::const_iterator theirs = video_offer->codecs().begin(); // theirs != video_offer->codecs().end(); ++theirs) { // video_accept->AddCodec(*theirs); // } // video_accept->SortCodecs(); // answer->AddContent(video_content->name, video_content->type, video_accept); // } // process the remote candidates remote_candidates_.clear(); std::vector<cricket::Candidate>::iterator iter; for (iter = candidates.begin(); iter != candidates.end(); ++iter) { std::string tname = iter->name(); TransportChannelMap::iterator titer = transport_channels_.find(tname); if (titer != transport_channels_.end()) { remote_candidates_.push_back(*iter); titer->second->AddRemoteCandidate(*iter); } } set_remote_description(rdesc); SetSessionState(STATE_RECEIVEDACCEPT); return true; } bool WebRTCSessionImpl::OnRemoteDescriptionUpdate( const cricket::SessionDescription* desc, std::vector<cricket::Candidate>& candidates) { // This will be called when session is in connected state // In this state session expects signaling message for any removed // streamed by the peer. // check for candidates port, if its equal to 0, remove that stream // and provide callback OnRemoveStream else keep as it is for (size_t i = 0; i < candidates.size(); ++i) { if (candidates[i].address().port() == 0) { RemoveStreamOnRequest(candidates[i]); } } return true; } void WebRTCSessionImpl::RemoveStreamOnRequest(const cricket::Candidate& candidate) { // 1. Get Transport corresponding to candidate name // 2. Get StreamInfo for the transport found in step 1 // 3. call ChannelManager Destroy voice/video method TransportChannelMap::iterator iter = transport_channels_.find(candidate.name()); if (iter == transport_channels_.end()) { return; } PC_Transport_Impl* transport = iter->second; std::vector<StreamInfo*>::iterator siter; for (siter = streams_.begin(); siter != streams_.end(); ++siter) { StreamInfo* stream_info = (*siter); if (stream_info->transport == transport) { if (!stream_info->video) { cricket::VoiceChannel* channel = static_cast<cricket::VoiceChannel*> ( stream_info->channel); signaling_thread_->Post(this, MSG_RTC_DESTROYVOICECHANNEL, new talk_base::TypedMessageData<cricket::VoiceChannel*>(channel)); } else { cricket::VideoChannel* channel = static_cast<cricket::VideoChannel*> ( stream_info->channel); signaling_thread_->Post(this, MSG_RTC_DESTROYVIDEOCHANNEL, new talk_base::TypedMessageData<cricket::VideoChannel*>(channel)); } break; } } } cricket::SessionDescription* WebRTCSessionImpl::CreateOffer() { SessionDescription* offer = new SessionDescription(); StreamMap::iterator iter; for (iter = streams_.begin(); iter != streams_.end(); ++iter) { if ((*iter)->video) { // add video codecs, if there is video stream added VideoContentDescription* video = new VideoContentDescription(); std::vector<cricket::VideoCodec> video_codecs; channel_manager_->GetSupportedVideoCodecs(&video_codecs); for (VideoCodecs::const_iterator codec = video_codecs.begin(); codec != video_codecs.end(); ++codec) { video->AddCodec(*codec); } video->SortCodecs(); offer->AddContent(CN_VIDEO, NS_JINGLE_RTP, video); } else { AudioContentDescription* audio = new AudioContentDescription(); std::vector<cricket::AudioCodec> audio_codecs; channel_manager_->GetSupportedAudioCodecs(&audio_codecs); for (AudioCodecs::const_iterator codec = audio_codecs.begin(); codec != audio_codecs.end(); ++codec) { audio->AddCodec(*codec); } audio->SortCodecs(); offer->AddContent(CN_AUDIO, NS_JINGLE_RTP, audio); } } return offer; } cricket::SessionDescription* WebRTCSessionImpl::CreateAnswer( const cricket::SessionDescription* offer) { cricket::SessionDescription* answer = new cricket::SessionDescription(); const ContentInfo* audio_content = GetFirstAudioContent(offer); if (audio_content) { const AudioContentDescription* audio_offer = static_cast<const AudioContentDescription*>(audio_content->description); AudioContentDescription* audio_accept = new AudioContentDescription(); AudioCodecs audio_codecs; channel_manager_->GetSupportedAudioCodecs(&audio_codecs); for (AudioCodecs::const_iterator ours = audio_codecs.begin(); ours != audio_codecs.end(); ++ours) { for (AudioCodecs::const_iterator theirs = audio_offer->codecs().begin(); theirs != audio_offer->codecs().end(); ++theirs) { if (ours->Matches(*theirs)) { cricket::AudioCodec negotiated(*ours); negotiated.id = theirs->id; audio_accept->AddCodec(negotiated); } } } audio_accept->SortCodecs(); answer->AddContent(audio_content->name, audio_content->type, audio_accept); } const ContentInfo* video_content = GetFirstVideoContent(offer); if (video_content) { const VideoContentDescription* video_offer = static_cast<const VideoContentDescription*>(video_content->description); VideoContentDescription* video_accept = new VideoContentDescription(); VideoCodecs video_codecs; channel_manager_->GetSupportedVideoCodecs(&video_codecs); for (VideoCodecs::const_iterator ours = video_codecs.begin(); ours != video_codecs.end(); ++ours) { for (VideoCodecs::const_iterator theirs = video_offer->codecs().begin(); theirs != video_offer->codecs().end(); ++theirs) { if (ours->Matches(*theirs)) { cricket::VideoCodec negotiated(*ours); negotiated.id = theirs->id; video_accept->AddCodec(negotiated); } } } video_accept->SortCodecs(); answer->AddContent(video_content->name, video_content->type, video_accept); } return answer; } void WebRTCSessionImpl::OnMute(bool mute) { } void WebRTCSessionImpl::OnCameraMute(bool mute) { } void WebRTCSessionImpl::SetError(Error error) { if (signaling_thread_->IsCurrent()) { BaseSession::SetError(error); } else { signaling_thread_->Post(this, MSG_RTC_SETSESSIONERROR, new talk_base::TypedMessageData<int>(error)); } } void WebRTCSessionImpl::OnCandidateReady(const cricket::Candidate& address) { local_candidates_.push_back(address); // for now we are using only one candidate from each connection. // PC_Transport_Impl will discard remaining candidates from // P2PTransportChannel. When this function is called, if // local_candidates_ size is equal to streams_ ( if RTCP is disabled) // then send local session description // TODO(mallinath): Is it correct to check the state variable here for // incoming sessions? if ((signal_initiated_ || state_ == STATE_RECEIVEDINITIATE) && (local_candidates_.size() == streams_.size())) { SendLocalDescription(); // On the receiving end, we haven't yet enabled the channels, so after // sending the local description, let's enable the channels. if (!signal_initiated_) { // Enable all the channels and then send our local description. signaling_thread_->Post(this, MSG_RTC_ENABLEALLSTREAMS); } } } void WebRTCSessionImpl::SendLocalDescription() { signaling_thread_->Post(this, MSG_RTC_SENDLOCALDESCRIPTION); } void WebRTCSessionImpl::SendLocalDescription_w() { cricket::SessionDescription* desc; if (incoming() && state_ == STATE_RECEIVEDINITIATE) { desc = CreateAnswer(remote_description_); } else { desc = CreateOffer(); } if (desc) { set_local_description(desc); session_state_ = (incoming()) ? STATE_SENTACCEPT : STATE_SENTINITIATE; SetState(session_state_); connection()->OnLocalDescription(desc, local_candidates_); } } void WebRTCSessionImpl::SignalOnWritableState_w( cricket::TransportChannel* channel) { ASSERT(connection()->media_thread() == talk_base::Thread::Current()); SignalWritableState(channel); } void WebRTCSessionImpl::OnStateChange(P2PTransportClass::State state, cricket::TransportChannel* channel) { if (P2PTransportClass::STATE_WRITABLE & state) { connection()->media_thread()->Post( this, MSG_RTC_SIGNALONWRITABLESTATE, new talk_base::TypedMessageData<cricket::TransportChannel*>(channel)); } } void WebRTCSessionImpl::OnMessageReceived(const char* data, size_t data_size) { } } /* namespace webrtc */
/* * W.J. van der Laan 2011-2012 */ #include <QApplication> #include "bitcoingui.h" #include "clientmodel.h" #include "walletmodel.h" #include "optionsmodel.h" #include "guiutil.h" #include "guiconstants.h" #include "init.h" #include "util.h" #include "ui_interface.h" #include "paymentserver.h" #include "splashscreen.h" #include <QMessageBox> #if QT_VERSION < 0x050000 #include <QTextCodec> #endif #include <QLocale> #include <QTimer> #include <QTranslator> #include <QLibraryInfo> #ifdef Q_OS_MAC #include "macdockiconhandler.h" #endif #if defined(BITCOIN_NEED_QT_PLUGINS) && !defined(_BITCOIN_QT_PLUGINS_INCLUDED) #define _BITCOIN_QT_PLUGINS_INCLUDED #define __INSURE__ #include <QtPlugin> Q_IMPORT_PLUGIN(qcncodecs) Q_IMPORT_PLUGIN(qjpcodecs) Q_IMPORT_PLUGIN(qtwcodecs) Q_IMPORT_PLUGIN(qkrcodecs) Q_IMPORT_PLUGIN(qtaccessiblewidgets) #endif // Declare meta types used for QMetaObject::invokeMethod Q_DECLARE_METATYPE(bool*) // Need a global reference for the notifications to find the GUI static BitcoinGUI *guiref; static SplashScreen *splashref; static bool ThreadSafeMessageBox(const std::string& message, const std::string& caption, unsigned int style) { // Message from network thread if(guiref) { bool modal = (style & CClientUIInterface::MODAL); bool ret = false; // In case of modal message, use blocking connection to wait for user to click a button QMetaObject::invokeMethod(guiref, "message", modal ? GUIUtil::blockingGUIThreadConnection() : Qt::QueuedConnection, Q_ARG(QString, QString::fromStdString(caption)), Q_ARG(QString, QString::fromStdString(message)), Q_ARG(unsigned int, style), Q_ARG(bool*, &ret)); return ret; } else { printf("%s: %s\n", caption.c_str(), message.c_str()); fprintf(stderr, "%s: %s\n", caption.c_str(), message.c_str()); return false; } } static bool ThreadSafeAskFee(int64 nFeeRequired) { if(!guiref) return false; if(nFeeRequired < CTransaction::nMinTxFee || nFeeRequired <= nTransactionFee || fDaemon) return true; bool payFee = false; QMetaObject::invokeMethod(guiref, "askFee", GUIUtil::blockingGUIThreadConnection(), Q_ARG(qint64, nFeeRequired), Q_ARG(bool*, &payFee)); return payFee; } static void InitMessage(const std::string &message) { if(splashref) { splashref->showMessage(QString::fromStdString(message), Qt::AlignBottom|Qt::AlignHCenter, QColor(55,55,55)); qApp->processEvents(); } printf("init message: %s\n", message.c_str()); } /* Translate string to current locale using Qt. */ static std::string Translate(const char* psz) { return QCoreApplication::translate("bitcoin-core", psz).toStdString(); } /* Handle runaway exceptions. Shows a message box with the problem and quits the program. */ static void handleRunawayException(std::exception *e) { PrintExceptionContinue(e, "Runaway exception"); QMessageBox::critical(0, "Runaway exception", BitcoinGUI::tr("A fatal error occurred. Priv can no longer continue safely and will quit.") + QString("\n\n") + QString::fromStdString(strMiscWarning)); exit(1); } #ifndef BITCOIN_QT_TEST int main(int argc, char *argv[]) { // Command-line options take precedence: ParseParameters(argc, argv); #if QT_VERSION < 0x050000 // Internal string conversion is all UTF-8 QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8")); QTextCodec::setCodecForCStrings(QTextCodec::codecForTr()); #endif Q_INIT_RESOURCE(bitcoin); QApplication app(argc, argv); // Register meta types used for QMetaObject::invokeMethod qRegisterMetaType< bool* >(); // Do this early as we don't want to bother initializing if we are just calling IPC // ... but do it after creating app, so QCoreApplication::arguments is initialized: if (PaymentServer::ipcSendCommandLine()) exit(0); PaymentServer* paymentServer = new PaymentServer(&app); // Install global event filter that makes sure that long tooltips can be word-wrapped app.installEventFilter(new GUIUtil::ToolTipToRichTextFilter(TOOLTIP_WRAP_THRESHOLD, &app)); // ... then bitcoin.conf: if (!boost::filesystem::is_directory(GetDataDir(false))) { // This message can not be translated, as translation is not initialized yet // (which not yet possible because lang=XX can be overridden in bitcoin.conf in the data directory) QMessageBox::critical(0, "Priv", QString("Error: Specified data directory \"%1\" does not exist.").arg(QString::fromStdString(mapArgs["-datadir"]))); return 1; } ReadConfigFile(mapArgs, mapMultiArgs); // Application identification (must be set before OptionsModel is initialized, // as it is used to locate QSettings) QApplication::setOrganizationName("Priv"); QApplication::setOrganizationDomain("priv.org"); if(GetBoolArg("-testnet")) // Separate UI settings for testnet QApplication::setApplicationName("Priv-Qt-testnet"); else QApplication::setApplicationName("Priv-Qt"); // ... then GUI settings: OptionsModel optionsModel; // Get desired locale (e.g. "de_DE") from command line or use system locale QString lang_territory = QString::fromStdString(GetArg("-lang", QLocale::system().name().toStdString())); QString lang = lang_territory; // Convert to "de" only by truncating "_DE" lang.truncate(lang_territory.lastIndexOf('_')); QTranslator qtTranslatorBase, qtTranslator, translatorBase, translator; // 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))) app.installTranslator(&qtTranslatorBase); // Load e.g. qt_de_DE.qm if (qtTranslator.load("qt_" + lang_territory, QLibraryInfo::location(QLibraryInfo::TranslationsPath))) app.installTranslator(&qtTranslator); // Load e.g. bitcoin_de.qm (shortcut "de" needs to be defined in bitcoin.qrc) if (translatorBase.load(lang, ":/translations/")) app.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/")) app.installTranslator(&translator); // Subscribe to global signals from core uiInterface.ThreadSafeMessageBox.connect(ThreadSafeMessageBox); uiInterface.ThreadSafeAskFee.connect(ThreadSafeAskFee); uiInterface.InitMessage.connect(InitMessage); uiInterface.Translate.connect(Translate); // Show help message immediately after parsing command-line options (for "-lang") and setting locale, // but before showing splash screen. if (mapArgs.count("-?") || mapArgs.count("--help")) { GUIUtil::HelpMessageBox help; help.showOrPrint(); return 1; } #ifdef Q_OS_MAC // on mac, also change the icon now because it would look strange to have a testnet splash (green) and a std app icon (orange) if(GetBoolArg("-testnet")) { MacDockIconHandler::instance()->setIcon(QIcon(":icons/bitcoin_testnet")); } #endif SplashScreen splash(QPixmap(), 0); if (GetBoolArg("-splash", true) && !GetBoolArg("-min")) { splash.show(); splash.setAutoFillBackground(true); splashref = &splash; } app.processEvents(); app.setQuitOnLastWindowClosed(false); try { #ifndef Q_OS_MAC // Regenerate startup link, to fix links to old versions // OSX: makes no sense on mac and might also scan/mount external (and sleeping) volumes (can take up some secs) if (GUIUtil::GetStartOnSystemStartup()) GUIUtil::SetStartOnSystemStartup(true); #endif boost::thread_group threadGroup; BitcoinGUI window; guiref = &window; QTimer* pollShutdownTimer = new QTimer(guiref); QObject::connect(pollShutdownTimer, SIGNAL(timeout()), guiref, SLOT(detectShutdown())); pollShutdownTimer->start(200); if(AppInit2(threadGroup)) { { // Put this in a block, so that the Model objects are cleaned up before // calling Shutdown(). optionsModel.Upgrade(); // Must be done after AppInit2 if (splashref) splash.finish(&window); ClientModel clientModel(&optionsModel); WalletModel walletModel(pwalletMain, &optionsModel); window.setClientModel(&clientModel); window.addWallet("~Default", &walletModel); window.setCurrentWallet("~Default"); // If -min option passed, start window minimized. if(GetBoolArg("-min")) { window.showMinimized(); } else { window.show(); } // Now that initialization/startup is done, process any command-line // bitcoin: URIs QObject::connect(paymentServer, SIGNAL(receivedURI(QString)), &window, SLOT(handleURI(QString))); QTimer::singleShot(100, paymentServer, SLOT(uiReady())); app.exec(); window.hide(); window.setClientModel(0); window.removeAllWallets(); guiref = 0; } // Shutdown the core and its threads, but don't exit Bitcoin-Qt here threadGroup.interrupt_all(); threadGroup.join_all(); Shutdown(); } else { threadGroup.interrupt_all(); threadGroup.join_all(); Shutdown(); return 1; } } catch (std::exception& e) { handleRunawayException(&e); } catch (...) { handleRunawayException(NULL); } return 0; } #endif // BITCOIN_QT_TEST
/* Copyright 2017 The TensorFlow Authors. 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. ==============================================================================*/ #include "tensorflow/lite/delegates/nnapi/nnapi_delegate.h" #include <algorithm> #include <cstdarg> #include <cstddef> #include <cstdint> #include <cstdio> #include <cstring> #include <functional> #include <initializer_list> #include <iostream> #include <iterator> #include <map> #include <memory> #include <string> #include <tuple> #include <utility> #include <vector> #include "tensorflow/lite/nnapi/NeuralNetworksTypes.h" #ifdef __ANDROID__ #include <sys/system_properties.h> #endif #if defined __ANDROID__ || defined __unix__ #define TFLITE_NNAPI_ALLOW_MMAP_SHARING #include <sys/mman.h> #include <sys/stat.h> #include <unistd.h> #include <fcntl.h> #endif #include "tensorflow/lite/allocation.h" #include "tensorflow/lite/builtin_op_data.h" #include "tensorflow/lite/builtin_ops.h" #include "tensorflow/lite/c/builtin_op_data.h" #include "tensorflow/lite/c/common.h" #include "tensorflow/lite/context_util.h" #include "tensorflow/lite/delegates/nnapi/nnapi_delegate_kernel.h" #include "tensorflow/lite/delegates/nnapi/quant_lstm_sup.h" #include "tensorflow/lite/delegates/utils.h" #include "tensorflow/lite/kernels/kernel_util.h" #include "tensorflow/lite/minimal_logging.h" #include "tensorflow/lite/nnapi/nnapi_implementation.h" #include "tensorflow/lite/nnapi/nnapi_util.h" #include "tensorflow/lite/util.h" static int graph_index = 0; static int actual_node_num = 0; namespace tflite { namespace { // Returns the enum name corresponding to the given error code if the given // value corresponds to an of the error codes in the enumeration above or // an message with the unknown code. // LINT.IfChange(NnApiErrorDescription) std::string NnApiErrorDescription(int error_code) { switch (error_code) { case ANEURALNETWORKS_NO_ERROR: return "ANEURALNETWORKS_NO_ERROR"; case ANEURALNETWORKS_OUT_OF_MEMORY: return "ANEURALNETWORKS_OUT_OF_MEMORY"; case ANEURALNETWORKS_INCOMPLETE: return "ANEURALNETWORKS_INCOMPLETE"; case ANEURALNETWORKS_UNEXPECTED_NULL: return "ANEURALNETWORKS_UNEXPECTED_NULL"; case ANEURALNETWORKS_BAD_DATA: return "ANEURALNETWORKS_BAD_DATA"; case ANEURALNETWORKS_OP_FAILED: return "ANEURALNETWORKS_OP_FAILED"; case ANEURALNETWORKS_BAD_STATE: return "ANEURALNETWORKS_BAD_STATE"; case ANEURALNETWORKS_UNMAPPABLE: return "ANEURALNETWORKS_UNMAPPABLE"; case ANEURALNETWORKS_OUTPUT_INSUFFICIENT_SIZE: return "ANEURALNETWORKS_OUTPUT_INSUFFICIENT_SIZE"; case ANEURALNETWORKS_UNAVAILABLE_DEVICE: return "ANEURALNETWORKS_UNAVAILABLE_DEVICE"; case ANEURALNETWORKS_MISSED_DEADLINE_TRANSIENT: return "ANEURALNETWORKS_MISSED_DEADLINE_TRANSIENT"; case ANEURALNETWORKS_MISSED_DEADLINE_PERSISTENT: return "ANEURALNETWORKS_MISSED_DEADLINE_PERSISTENT"; case ANEURALNETWORKS_RESOURCE_EXHAUSTED_TRANSIENT: return "ANEURALNETWORKS_RESOURCE_EXHAUSTED_TRANSIENT"; case ANEURALNETWORKS_RESOURCE_EXHAUSTED_PERSISTENT: return "ANEURALNETWORKS_RESOURCE_EXHAUSTED_PERSISTENT"; case ANEURALNETWORKS_DEAD_OBJECT: return "ANEURALNETWORKS_DEAD_OBJECT"; default: return "Unknown NNAPI error code: " + std::to_string(error_code); } } // LINT.ThenChange() #define RETURN_TFLITE_ERROR_IF_NN_ERROR(context, code, call_desc, p_errno) \ do { \ const auto _code = (code); \ const auto _call_desc = (call_desc); \ if (_code != ANEURALNETWORKS_NO_ERROR) { \ const auto error_desc = NnApiErrorDescription(_code); \ context->ReportError(context, \ "NN API returned error %s at line %d while %s.\n", \ error_desc.c_str(), __LINE__, _call_desc); \ *p_errno = _code; \ return kTfLiteError; \ } \ } while (0) bool IsFloat(TfLiteType type) { switch (type) { case kTfLiteFloat32: return true; default: return false; } } bool IsFloatOrUInt8(TfLiteType type) { switch (type) { case kTfLiteFloat32: case kTfLiteUInt8: return true; default: return false; } } bool IsQuantized(TfLiteType type) { switch (type) { case kTfLiteUInt8: case kTfLiteInt8: return true; default: // kTfLiteInt16 isn't supported as quantized type yet. return false; } } bool IsScalarInputSupported(int builtin_code) { switch (builtin_code) { case kTfLiteBuiltinAdd: case kTfLiteBuiltinMul: case kTfLiteBuiltinSub: case kTfLiteBuiltinDiv: case kTfLiteBuiltinEqual: case kTfLiteBuiltinNotEqual: case kTfLiteBuiltinGreater: case kTfLiteBuiltinGreaterEqual: case kTfLiteBuiltinLess: case kTfLiteBuiltinLessEqual: case kTfLiteBuiltinPow: case kTfLiteBuiltinMaximum: case kTfLiteBuiltinMinimum: return true; default: return false; } } // Check if the operation requires explicit conversion from int8 to uint8 // values. bool NeedInt8Conversion(const TfLiteContext* context, int builtin_code, const TfLiteNode* node) { const int input_id = node->inputs->data[0]; const TfLiteType input_type = context->tensors[input_id].type; switch (builtin_code) { case kTfLiteBuiltinConv2d: case kTfLiteBuiltinDepthwiseConv2d: case kTfLiteBuiltinFullyConnected: { if (input_type == kTfLiteInt8) { const int weights_id = node->inputs->data[1]; const auto& weights_tensor = context->tensors[weights_id]; if ((weights_tensor.type == kTfLiteInt8 || weights_tensor.type == kTfLiteUInt8) && weights_tensor.quantization.type == kTfLiteAffineQuantization) { return true; } } return false; } case kTfLiteBuiltinSelect: { const auto value_type = context->tensors[node->inputs->data[1]].type; return value_type == kTfLiteInt8; } case kTfLiteBuiltinAdd: case kTfLiteBuiltinArgMax: case kTfLiteBuiltinArgMin: case kTfLiteBuiltinAveragePool2d: case kTfLiteBuiltinBatchToSpaceNd: case kTfLiteBuiltinConcatenation: case kTfLiteBuiltinEqual: case kTfLiteBuiltinExpandDims: case kTfLiteBuiltinGreater: case kTfLiteBuiltinGreaterEqual: case kTfLiteBuiltinHardSwish: case kTfLiteBuiltinL2Normalization: case kTfLiteBuiltinLess: case kTfLiteBuiltinLessEqual: case kTfLiteBuiltinLogistic: case kTfLiteBuiltinMaximum: case kTfLiteBuiltinMaxPool2d: case kTfLiteBuiltinMean: case kTfLiteBuiltinMinimum: case kTfLiteBuiltinMul: case kTfLiteBuiltinNotEqual: case kTfLiteBuiltinPad: case kTfLiteBuiltinPadv2: case kTfLiteBuiltinReduceMax: case kTfLiteBuiltinReduceMin: case kTfLiteBuiltinRelu: case kTfLiteBuiltinReluN1To1: case kTfLiteBuiltinRelu6: case kTfLiteBuiltinResizeBilinear: case kTfLiteBuiltinResizeNearestNeighbor: case kTfLiteBuiltinReshape: case kTfLiteBuiltinSlice: case kTfLiteBuiltinSoftmax: case kTfLiteBuiltinSpaceToBatchNd: case kTfLiteBuiltinSpaceToDepth: case kTfLiteBuiltinDepthToSpace: case kTfLiteBuiltinStridedSlice: case kTfLiteBuiltinSub: case kTfLiteBuiltinTanh: case kTfLiteBuiltinTile: case kTfLiteBuiltinTopkV2: case kTfLiteBuiltinTranspose: { return input_type == kTfLiteInt8; } default: return false; } } constexpr int kLstmFullKernelInputSize = 24; // The 20 input version is deprecated and kept only to // support old model. The latest version of the LSTM Full Kernel // is the one with 24 inputs constexpr int kLstmFullKernelNoOptionalParamsInputSize = 20; constexpr int kLstmBasicKernelInputSize = 5; inline bool isLstmBasicKernel(const TfLiteNode* node) { return node->inputs->size == kLstmBasicKernelInputSize; } inline bool isLstmFullKernel(const TfLiteNode* node) { return node->inputs->size == kLstmFullKernelInputSize || node->inputs->size == kLstmFullKernelNoOptionalParamsInputSize; } bool IsHybridOperator(const TfLiteContext* context, int builtin_code, const TfLiteNode* node) { switch (builtin_code) { case kTfLiteBuiltinConv2d: case kTfLiteBuiltinFullyConnected: { const int input_id = node->inputs->data[0]; const int filter_id = node->inputs->data[1]; const TfLiteType input_type = context->tensors[input_id].type; const TfLiteType filter_type = context->tensors[filter_id].type; return IsFloat(input_type) && IsQuantized(filter_type); } case kTfLiteBuiltinLstm: { const int input_id = node->inputs->data[0]; // Input #1 is optional so use #2 to determine if hybrid. const int weights_id = node->inputs->data[2]; const TfLiteType input_type = context->tensors[input_id].type; const TfLiteType weights_type = context->tensors[weights_id].type; return isLstmFullKernel(node) && IsFloat(input_type) && IsQuantized(weights_type); } case kTfLiteBuiltinUnidirectionalSequenceLstm: { const int input_id = node->inputs->data[0]; // Input #1 is optional so use #2 to determine if hybrid. const int weights_id = node->inputs->data[2]; const TfLiteType input_type = context->tensors[input_id].type; const TfLiteType weights_type = context->tensors[weights_id].type; return IsFloat(input_type) && IsQuantized(weights_type); } case kTfLiteBuiltinBidirectionalSequenceLstm: { const int input_id = node->inputs->data[0]; // Input #1 is optional so use #2 to determine if hybrid. const int weights_id = node->inputs->data[2]; const TfLiteType input_type = context->tensors[input_id].type; const TfLiteType weights_type = context->tensors[weights_id].type; return IsFloat(input_type) && IsQuantized(weights_type); } case kTfLiteBuiltinUnidirectionalSequenceRnn: { const int input_id = node->inputs->data[0]; const int weights_id = node->inputs->data[1]; const TfLiteType input_type = context->tensors[input_id].type; const TfLiteType weights_type = context->tensors[weights_id].type; return IsFloat(input_type) && IsQuantized(weights_type); } default: return false; } } constexpr size_t kDefaultByteAlignmentForNNAPI = 16; static size_t getNumPaddingBytes(size_t byte_size) { size_t num_padding_bytes = 0; if (byte_size % kDefaultByteAlignmentForNNAPI) { num_padding_bytes = kDefaultByteAlignmentForNNAPI - (byte_size % kDefaultByteAlignmentForNNAPI); } return num_padding_bytes; } // Return NNAPI device handle with the provided null-terminated device name. // Returns kTfLiteError in case of any NNAPI error and if no device with the // given name can be found. TfLiteStatus GetDeviceHandle(const NnApi* nnapi, TfLiteContext* context, const char* device_name_ptr, ANeuralNetworksDevice** result, int* nnapi_errno) { if (!device_name_ptr) return kTfLiteError; *result = nullptr; std::string device_name(device_name_ptr); uint32_t num_devices = 0; nnapi->ANeuralNetworks_getDeviceCount(&num_devices); for (uint32_t i = 0; i < num_devices; i++) { ANeuralNetworksDevice* device = nullptr; const char* buffer = nullptr; RETURN_TFLITE_ERROR_IF_NN_ERROR( context, nnapi->ANeuralNetworks_getDevice(i, &device), "Searching for target device", nnapi_errno); RETURN_TFLITE_ERROR_IF_NN_ERROR( context, nnapi->ANeuralNetworksDevice_getName(device, &buffer), "Searching for target device", nnapi_errno); if (device_name == buffer) { *result = device; return kTfLiteOk; } } context->ReportError(context, "Could not find the specified NNAPI accelerator: %s. " "Must be one of: {%s}.", device_name_ptr, nnapi::GetStringDeviceNamesList().c_str()); return kTfLiteError; } // Compute the hash of a TfLiteIntArray. uint64_t GetHash(const TfLiteIntArray* int_array) { constexpr auto kHashConst = 0x9e3779b97f4a7800ULL; uint64_t result = 0; for (auto i : TfLiteIntArrayView(int_array)) { result = result ^ (i + kHashConst + (result << 10) + (result >> 4)); } return result; } bool HasZeroes(TfLiteIntArrayView array) { for (auto value : array) { if (value == 0) { return true; } } return false; } // Bit mask for tensor flags. enum { NN_TENSOR_FLAG_SCALAR_AS_TENSOR = 1U << 0, NN_TENSOR_FLAG_INT8_CONVERSION = 1U << 1, }; // Returns the SDK level to target when delegating to the given devices. // The SDK level is the max of the ones supported by the devices or // the current Android SDK level if no device is present. TfLiteStatus GetTargetSdkVersion( TfLiteContext* context, const NnApi* nnapi, const std::vector<ANeuralNetworksDevice*>& device_handles, int* target_sdk_version, int* nnapi_errno) { *target_sdk_version = nnapi->android_sdk_version; int64_t devices_sdk_version = -1; for (const auto* device_handle : device_handles) { int64_t curr_device_sdk_version; RETURN_TFLITE_ERROR_IF_NN_ERROR( context, nnapi->ANeuralNetworksDevice_getFeatureLevel(device_handle, &curr_device_sdk_version), "Searching for target device", nnapi_errno); devices_sdk_version = std::max(curr_device_sdk_version, devices_sdk_version); } if ((devices_sdk_version > 0) && // This second check is necessary since if the nnapi-reference device is // in the list of target devices the devices_sdk_version value will be // 1000. (devices_sdk_version < nnapi->android_sdk_version)) { TFLITE_LOG(TFLITE_LOG_INFO, "Changing Android NN SDK version %d to version " "supported by target devices: %d", nnapi->android_sdk_version, devices_sdk_version); *target_sdk_version = devices_sdk_version; } return kTfLiteOk; } // Returns true if this delegate is configured to use a specific set of devices. // This will happen either if: // - accelerator_name option has been specified // - NNAPI CPU implementation has been explicitly disabled. // If exclude_nnapi_reference is true this method will return false if the // accelerator_name in the delegate options is equal to "nnapi-reference" bool ShouldUseTargetDevices(StatefulNnApiDelegate::Options delegate_options, bool exclude_nnapi_reference = false) { const char* device_name_ptr = delegate_options.accelerator_name; std::string nnapi_cpu("nnapi-reference"); bool has_selected_accelerator = device_name_ptr != nullptr; if (exclude_nnapi_reference && has_selected_accelerator) { has_selected_accelerator = nnapi_cpu != device_name_ptr; } return (delegate_options.disallow_nnapi_cpu) || has_selected_accelerator; } // Fills the given result vector with the list of devices the given delegate // is referring to. // There are three possible results: // - an empty array (not the full list of available accelerators, // for efficiency reasons) if no accelerator is chosen and the // disallow_nnapi_cpu delegate option is false. // - A single element array with the target processor, if an accelerator name // is specified in the delegate options. // - The full list of devices available on device less the nnapi reference // implementation if the delegate option disallow_nnapi_cpu has been // specified. TfLiteStatus GetTargetDevices(TfLiteContext* context, TfLiteDelegate* delegate, const NnApi* nnapi, int* nnapi_errno, std::vector<ANeuralNetworksDevice*>* result) { if (nnapi->android_sdk_version < delegate::nnapi::kMinSdkVersionForNNAPI12) { return kTfLiteError; } const auto delegate_options = StatefulNnApiDelegate::GetOptions(delegate); const char* device_name_ptr = delegate_options.accelerator_name; if (device_name_ptr != nullptr) { // User specified an accelerator to use. ANeuralNetworksDevice* nnapi_device = nullptr; TF_LITE_ENSURE_STATUS(GetDeviceHandle(nnapi, context, device_name_ptr, &nnapi_device, nnapi_errno)); result->push_back(nnapi_device); } else if (delegate_options.disallow_nnapi_cpu) { std::string nnapi_cpu("nnapi-reference"); uint32_t num_devices = 0; nnapi->ANeuralNetworks_getDeviceCount(&num_devices); for (uint32_t i = 0; i < num_devices; i++) { ANeuralNetworksDevice* device = nullptr; const char* buffer = nullptr; RETURN_TFLITE_ERROR_IF_NN_ERROR( context, nnapi->ANeuralNetworks_getDevice(i, &device), "Getting list of available devices", nnapi_errno); RETURN_TFLITE_ERROR_IF_NN_ERROR( context, nnapi->ANeuralNetworksDevice_getName(device, &buffer), "Getting list of available devices", nnapi_errno); if (nnapi_cpu != buffer) { result->push_back(device); } } } return kTfLiteOk; } } // namespace namespace delegate { namespace nnapi { #ifdef TFLITE_NNAPI_ALLOW_MMAP_SHARING NNMemory::NNMemory(const NnApi* nnapi, const char* name, size_t size) #ifndef __ANDROID__ : name_(name) #endif { if (name && size > 0) { nnapi_ = nnapi; byte_size_ = size; auto map_flag = MAP_SHARED; #if defined __ANDROID__ fd_ = nnapi_->ASharedMemory_create(name, size); #else fd_ = shm_open(name, O_RDWR|O_CREAT, 0666); ftruncate(fd_, size); #endif data_ptr_ = reinterpret_cast<uint8_t*>( mmap(nullptr, size, PROT_READ | PROT_WRITE, map_flag, fd_, 0)); nnapi_->ANeuralNetworksMemory_createFromFd( size, PROT_READ | PROT_WRITE, fd_, 0, &nn_memory_handle_); } } #else NNMemory::NNMemory(const NnApi* /*nnapi*/, const char* /*name*/, size_t /*size*/) : nnapi_(nullptr) {} #endif NNMemory::~NNMemory() { #ifdef TFLITE_NNAPI_ALLOW_MMAP_SHARING if (data_ptr_) { munmap(data_ptr_, byte_size_); } if (nn_memory_handle_) { nnapi_->ANeuralNetworksMemory_free(nn_memory_handle_); } if (fd_ > 0) close(fd_); #if !defined(__ANDROID__) if (name_) unlink(name_); #endif #endif } class DequantizeMapping { public: int DequantizedAnnIndex(int ann_index, TfLiteType type) const { for (const auto& element : mapping_) { if (ann_index == std::get<0>(element) && type == std::get<1>(element)) { return std::get<2>(element); } } return -1; } void Add(int ann_index, TfLiteType type, int dequantized_ann_index) { // This assumes it is not already mapped. mapping_.emplace_back(ann_index, type, dequantized_ann_index); } private: // Each tuple specifies the ANN (quantized) tensor index, the desired // floating-point type and the matching ANN (dequantized) tensor index. This // could use a map but instead std::vector is used to keep code size lower. std::vector<std::tuple<int, TfLiteType, int>> mapping_; }; // Abstract builder for building an op in the NN API graph. This handles // the disparity between TFLite and NN API operand types. NN API has singular // operands for both tensors and parameters, and TFLite separates the two. class NNAPIOpBuilder { public: NNAPIOpBuilder(const NnApi* nnapi, TfLiteContext* context, OperandMapping* tensor_mapping, DequantizeMapping* dequantize_mapping, std::map<const MMAPAllocation*, ANeuralNetworksMemory*>* allocation_mapping, std::vector<int>* nnapi_to_tflite_op_mapping, ANeuralNetworksModel* nn_model, int* nnapi_errno) : nnapi_(nnapi), context_(context), operand_mapping_(tensor_mapping), dequantize_mapping_(dequantize_mapping), allocation_memory_mapping_(allocation_mapping), nnapi_to_tflite_op_mapping_(nnapi_to_tflite_op_mapping), nn_model_(nn_model), nnapi_errno_(nnapi_errno) {} TfLiteStatus AddScalarBoolOperand(bool value) { return AddScalarOperand<bool>(value, ANEURALNETWORKS_BOOL); } TfLiteStatus AddScalarInt32Operand(int32_t value) { return AddScalarOperand<int32_t>(value, ANEURALNETWORKS_INT32); } TfLiteStatus AddScalarFloat32Operand(float value) { return AddScalarOperand<float>(value, ANEURALNETWORKS_FLOAT32); } TfLiteStatus AddVectorInt32Operand(const int32_t* values, uint32_t num_values) { return AddVectorOperand<int32_t>(values, num_values, ANEURALNETWORKS_TENSOR_INT32, /*scale=*/0.f, /*zero_point=*/0); } TfLiteStatus AddVectorInt32Operand(const int32_t* values, uint32_t num_values, float scale, int32_t zero_point) { return AddVectorOperand<int32_t>( values, num_values, ANEURALNETWORKS_TENSOR_INT32, scale, zero_point); } TfLiteStatus AddVectorFloat32Operand(const float* values, uint32_t num_values) { return AddVectorOperand<float>(values, num_values, ANEURALNETWORKS_TENSOR_FLOAT32); } TfLiteStatus AddPoolingParams(void* data) { auto builtin = reinterpret_cast<TfLitePoolParams*>(data); AddScalarInt32Operand(builtin->padding); AddScalarInt32Operand(builtin->stride_width); AddScalarInt32Operand(builtin->stride_height); AddScalarInt32Operand(builtin->filter_width); AddScalarInt32Operand(builtin->filter_height); AddScalarInt32Operand(builtin->activation); return kTfLiteOk; } TfLiteStatus AddTensorInput(int tensor_index, bool hybrid_op, int tensor_flags = 0) { return AddTensor(tensor_index, hybrid_op, &augmented_inputs_, tensor_flags); } TfLiteStatus AddTensorOutput(int tensor_index, int tensor_flags = 0) { return AddTensor(tensor_index, /*hybrid_op=*/false, &augmented_outputs_, tensor_flags); } TfLiteStatus AddAdditionalFloat32OutputTensor(uint32_t dimension_count) { std::vector<uint32_t> dims(dimension_count, 0); return AddFloat32OutputTensor(dimension_count, dims.data(), nullptr); } TfLiteStatus AddStateFloat32Tensor(int tensor_index, int* ann_tensor_index_out) { TfLiteTensor* tensor = &context_->tensors[tensor_index]; return AddFloat32OutputTensor( tensor->dims->size, reinterpret_cast<uint32_t*>(tensor->dims->data), ann_tensor_index_out); } // Add a constant tensor with a single element, intended for broadcast capable // ops. TfLiteStatus AddSingleValueConstantTensor(float value, bool is_quantized) { if (!is_quantized) { return AddVectorFloat32Operand(&value, 1); } else { // in the case that we need to add a quantized tensor, set the value to // 64, zero_point to be 0 and adjust scale accordingly. const uint8_t quant8_value = 64; return AddVectorOperand<uint8_t>(&quant8_value, 1, ANEURALNETWORKS_TENSOR_QUANT8_ASYMM, value / quant8_value, 0); } } // Calculate the scale and zero_point for 8-bit unsigned tensor, given float // min and max. zero_point is clamped to [0, 255]. TfLiteStatus CalculateQuantizationParams(float min, float max, float* scale, int* zero_point) { if (max < min) return kTfLiteError; *scale = (max - min) / 255.f; if (min > 0.f) { *zero_point = 0; } else if (max < 0.f) { *zero_point = 255; } else { *zero_point = (0.f - min) / (*scale); } return kTfLiteOk; } // Lower hardswish according to the following equation: // hard_swish[x] = x (ReLU6(x + 3)) / 6 == x * (Relu_N1_to_1(x/3) * 3 + 3) / 6 // = 0.5x * Relu_N1_to_1(x/3) + 0.5x TfLiteStatus TransformHardSwishIntoSupportedOps(int lite_input_index, int lite_output_index, bool need_int8_conversion, int lite_node_index) { const TfLiteTensor& tensor = context_->tensors[lite_input_index]; float input_scale = tensor.params.scale; int input_zero_point = tensor.params.zero_point; float input_min = 0.f; float input_max = 0.f; int tensor_flags = 0; if (need_int8_conversion) { tensor_flags = tensor_flags | NN_TENSOR_FLAG_INT8_CONVERSION; input_zero_point += 128; } bool is_quantized = false; int nn_type = ANEURALNETWORKS_TENSOR_FLOAT32; if (tensor.type == kTfLiteInt8 || tensor.type == kTfLiteUInt8) { is_quantized = true; nn_type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM; input_min = (0 - input_zero_point) * input_scale; input_max = (255 - input_zero_point) * input_scale; } // Stage1 : s1 = Relu1(x * 1/3) float s1_output_min = 0.f; float s1_output_max = 0.f; int s1_out_ann_index = 0; { float s1_output_scale = 0.f; int s1_output_zero_point = 0; if (is_quantized) { // clamp the output range to [-1, 1] if needed. s1_output_min = input_min / 3.f < -1.f ? -1.f : input_min / 3.f; s1_output_max = input_max / 3.f > 1.f ? 1.f : input_max / 3.f; CalculateQuantizationParams(s1_output_min, s1_output_max, &s1_output_scale, &s1_output_zero_point); } TF_LITE_ENSURE_OK(context_, AddTensorInput(lite_input_index, false, tensor_flags)); const float value3f = 1.f / 3.f; TF_LITE_ENSURE_OK(context_, AddSingleValueConstantTensor(value3f, is_quantized)); TF_LITE_ENSURE_OK(context_, AddScalarInt32Operand(ANEURALNETWORKS_FUSED_RELU1)); TF_LITE_ENSURE_OK( context_, AddAdditionalOutputTensor( tensor.dims->size, reinterpret_cast<uint32_t*>(tensor.dims->data), nn_type, s1_output_scale, s1_output_zero_point, &s1_out_ann_index)); TF_LITE_ENSURE_OK( context_, FinalizeAddOperation(ANEURALNETWORKS_MUL, lite_node_index)); } // Stage2 : s2 = x / 2 float s2_output_min = input_min / 2.f; float s2_output_max = input_max / 2.f; int s2_out_ann_index = 0; { float s2_output_scale = input_scale / 2.0f; int s2_output_zero_point = input_zero_point; TF_LITE_ENSURE_OK(context_, AddTensorInput(lite_input_index, false, tensor_flags)); const float value2f = 0.5f; TF_LITE_ENSURE_OK(context_, AddSingleValueConstantTensor(value2f, is_quantized)); TF_LITE_ENSURE_OK(context_, AddScalarInt32Operand(ANEURALNETWORKS_FUSED_NONE)); TF_LITE_ENSURE_OK( context_, AddAdditionalOutputTensor( tensor.dims->size, reinterpret_cast<uint32_t*>(tensor.dims->data), nn_type, s2_output_scale, s2_output_zero_point, &s2_out_ann_index)); TF_LITE_ENSURE_OK( context_, FinalizeAddOperation(ANEURALNETWORKS_MUL, lite_node_index)); } // Stage 3 : s3 = s1 * s2 int s3_out_ann_index = 0; { augmented_inputs_.push_back(s1_out_ann_index); augmented_inputs_.push_back(s2_out_ann_index); TF_LITE_ENSURE_OK(context_, AddScalarInt32Operand(ANEURALNETWORKS_FUSED_NONE)); float s3_output_scale = 0.f; int s3_output_zero_point = 0; if (is_quantized) { // the min for stage 3 is always 0.0f. float s3_output_min = 0.f; // the max for stage 3 is max(s1_min * s2_min, s1_max * s3_max). float s3_output_max = s1_output_max * s2_output_max > s1_output_min * s2_output_min ? s1_output_max * s2_output_max : s1_output_min * s2_output_min; CalculateQuantizationParams(s3_output_min, s3_output_max, &s3_output_scale, &s3_output_zero_point); } TF_LITE_ENSURE_OK( context_, AddAdditionalOutputTensor( tensor.dims->size, reinterpret_cast<uint32_t*>(tensor.dims->data), nn_type, s3_output_scale, s3_output_zero_point, &s3_out_ann_index)); TF_LITE_ENSURE_OK( context_, FinalizeAddOperation(ANEURALNETWORKS_MUL, lite_node_index)); } // Stage 4: y = s3 + s2 { augmented_inputs_.push_back(s2_out_ann_index); augmented_inputs_.push_back(s3_out_ann_index); TF_LITE_ENSURE_OK(context_, AddScalarInt32Operand(ANEURALNETWORKS_FUSED_NONE)); TF_LITE_ENSURE_OK(context_, AddTensorOutput(lite_output_index, tensor_flags)); TF_LITE_ENSURE_OK( context_, FinalizeAddOperation(ANEURALNETWORKS_ADD, lite_node_index)); } return kTfLiteOk; } // Adds the operation to the model and maps the operation to the originating // TFLite one. TfLiteStatus AddOperationToModel(ANeuralNetworksOperationType type, uint32_t input_count, const uint32_t* inputs, uint32_t output_count, const uint32_t* outputs, int lite_node_index) { RETURN_TFLITE_ERROR_IF_NN_ERROR( context_, nnapi_->ANeuralNetworksModel_addOperation( nn_model_, type, input_count, inputs, output_count, outputs), "adding operation", nnapi_errno_); nnapi_to_tflite_op_mapping_->push_back(lite_node_index); return kTfLiteOk; } // Adds a Dequantize operator and replaces the input tensor index with the // dequantized version. If the dequantized version of the operator already // exists then it is not added again. TfLiteStatus AddDequantize(int nn_input_index, int lite_tensor_index, TfLiteType dequantized_type, int lite_node_index) { const int ann_index = operand_mapping_->lite_index_to_ann(lite_tensor_index); int dequantized_ann_index = dequantize_mapping_->DequantizedAnnIndex(ann_index, dequantized_type); if (dequantized_ann_index == -1) { // The dequantized version does not exist yet, it has to be added: a new // Dequantize operation is added, yielding a new tensor. const TfLiteTensor& tensor = context_->tensors[lite_tensor_index]; ANeuralNetworksOperandType operand_type{ ANEURALNETWORKS_TENSOR_FLOAT32, static_cast<uint32_t>(tensor.dims->size), reinterpret_cast<uint32_t*>(tensor.dims->data), 0.f, 0}; RETURN_TFLITE_ERROR_IF_NN_ERROR( context_, nnapi_->ANeuralNetworksModel_addOperand(nn_model_, &operand_type), "adding operand", nnapi_errno_); dequantized_ann_index = operand_mapping_->add_new_non_tensor_operand(); // Add Dequantize operation. const uint32_t dequantize_input[1] = {static_cast<uint32_t>(ann_index)}; const uint32_t dequantize_output[1] = { static_cast<uint32_t>(dequantized_ann_index)}; TF_LITE_ENSURE_OK( context_, AddOperationToModel(ANEURALNETWORKS_DEQUANTIZE, /*input_count=*/1, dequantize_input, /*output_count=*/1, dequantize_output, lite_node_index)); dequantize_mapping_->Add(ann_index, dequantized_type, dequantized_ann_index); } // The input for the original operation is modified so that the operation // now uses the dequantized tensor as input. augmented_inputs_[nn_input_index] = dequantized_ann_index; return kTfLiteOk; } // Finish emitting the op (of type `type`) into the NN API. TfLiteStatus FinalizeAddOperation(ANeuralNetworksOperationType type, int lite_node_index) { // Actually add a NN API operation TF_LITE_ENSURE_OK(context_, AddOperationToModel( type, static_cast<uint32_t>(augmented_inputs_.size()), augmented_inputs_.data(), static_cast<uint32_t>(augmented_outputs_.size()), augmented_outputs_.data(), lite_node_index)); augmented_inputs_.clear(); augmented_outputs_.clear(); return kTfLiteOk; } TfLiteStatus AddSingleValueTensorAsScalarOperand(int tensor_index, int nn_type) { const TfLiteTensor* tensor = &context_->tensors[tensor_index]; TF_LITE_ENSURE_EQ(context_, NumElements(tensor), 1); ANeuralNetworksOperandType operand_type{.type = nn_type}; RETURN_TFLITE_ERROR_IF_NN_ERROR( context_, nnapi_->ANeuralNetworksModel_addOperand(nn_model_, &operand_type), "adding operand", nnapi_errno_); int ann_tensor_index = operand_mapping_->lite_index_to_ann(tensor_index); if (ann_tensor_index != -1) { augmented_inputs_.push_back(ann_tensor_index); return kTfLiteOk; } // Allocate a new tensor index ann_tensor_index = operand_mapping_->add_new_ann_tensor_index(tensor_index); augmented_inputs_.push_back(ann_tensor_index); const TfLiteType tensor_type = tensor->type; TfLiteType nn_type_equivalent; TF_LITE_ENSURE_OK(context_, GetEquivalentToANNType(context_, nn_type, &nn_type_equivalent)); if (tensor_type != nn_type_equivalent) { operand_mapping_->add_type_conversion(tensor_index, nn_type_equivalent); } return kTfLiteOk; } template <typename T> TfLiteStatus AddNewInputConstantTensor( int32_t nn_type, TfLiteType type, const TfLiteIntArray* dims, const std::vector<T>& tensor_value, const TfLiteQuantizationParams& quant_params, int* tensor_index) { TF_LITE_ENSURE_OK(context_, context_->AddTensors(context_, 1, tensor_index)); TfLiteTensor* new_tensor = &context_->tensors[*tensor_index]; new_tensor->type = type; new_tensor->allocation_type = kTfLiteDynamic; new_tensor->params = quant_params; // Not removing the new tensor in case of resizing errors since it will // be cleared by the context TF_LITE_ENSURE_OK( context_, context_->ResizeTensor( context_, new_tensor, // Resize Tensor takes ownership of the dims array passed as param TfLiteIntArrayCopy(dims))); memcpy(new_tensor->data.raw, reinterpret_cast<const char*>(tensor_value.data()), tensor_value.size() * sizeof(T)); const uint32_t tensor_rank = static_cast<uint32_t>(dims->size); const uint32_t* tensor_dims = reinterpret_cast<const uint32_t*>(dims->data); ANeuralNetworksOperandType operand_type{nn_type, tensor_rank, tensor_dims, quant_params.scale, quant_params.zero_point}; const int ann_tensor_index = operand_mapping_->add_delegate_generated_input_ann_tensors_operand(); RETURN_TFLITE_ERROR_IF_NN_ERROR( context_, nnapi_->ANeuralNetworksModel_addOperand(nn_model_, &operand_type), "adding operand", nnapi_errno_); augmented_inputs_.push_back(ann_tensor_index); RETURN_TFLITE_ERROR_IF_NN_ERROR( context_, nnapi_->ANeuralNetworksModel_setOperandValue( nn_model_, ann_tensor_index, new_tensor->data.raw, new_tensor->bytes), "setting new operand value", nnapi_errno_); return kTfLiteOk; } template <typename T> TfLiteStatus AddNewInputConstantTensor( int32_t nn_type, TfLiteType type, std::initializer_list<int> dims, const std::vector<T>& tensor_value, const TfLiteQuantizationParams& quant_params, int* tensor_index) { TfLiteIntArray* dim_array = TfLiteIntArrayCreate(dims.size()); dim_array->size = dims.size(); std::copy(dims.begin(), dims.end(), dim_array->data); const auto result = AddNewInputConstantTensor( nn_type, type, dim_array, tensor_value, quant_params, tensor_index); TfLiteIntArrayFree(dim_array); return result; } private: // Returns a TF Lite type which has the same memory representation as a // provided NN API type. TfLiteStatus GetEquivalentToANNType(TfLiteContext* context, int nn_type, TfLiteType* type) { switch (nn_type) { case ANEURALNETWORKS_INT32: *type = kTfLiteInt32; return kTfLiteOk; case ANEURALNETWORKS_FLOAT32: *type = kTfLiteFloat32; return kTfLiteOk; default: context->ReportError(context, "NN API Delegate: Can't get an equivalent TF Lite " "type for provided NN API type: %d.\n", nn_type); return kTfLiteError; } } template <typename T> TfLiteStatus AddScalarOperand(T value, int32_t nn_type) { ANeuralNetworksOperandType operand_type{.type = nn_type}; RETURN_TFLITE_ERROR_IF_NN_ERROR( context_, nnapi_->ANeuralNetworksModel_addOperand(nn_model_, &operand_type), "adding operand", nnapi_errno_); const int ann_index = operand_mapping_->add_new_non_tensor_operand(); RETURN_TFLITE_ERROR_IF_NN_ERROR( context_, nnapi_->ANeuralNetworksModel_setOperandValue(nn_model_, ann_index, &value, sizeof(T)), "setting new operand value", nnapi_errno_); augmented_inputs_.push_back(ann_index); return kTfLiteOk; } template <typename T> TfLiteStatus AddVectorOperand(const T* values, uint32_t num_values, int32_t nn_type, float scale, int32_t zero_point) { ANeuralNetworksOperandType operand_type{.type = nn_type, .dimensionCount = 1, .dimensions = &num_values, .scale = scale, .zeroPoint = zero_point}; RETURN_TFLITE_ERROR_IF_NN_ERROR( context_, nnapi_->ANeuralNetworksModel_addOperand(nn_model_, &operand_type), "adding operand", nnapi_errno_); const int ann_index = operand_mapping_->add_new_non_tensor_operand(); RETURN_TFLITE_ERROR_IF_NN_ERROR( context_, nnapi_->ANeuralNetworksModel_setOperandValue( nn_model_, ann_index, values, sizeof(T) * num_values), "settings new operand value", nnapi_errno_); augmented_inputs_.push_back(ann_index); return kTfLiteOk; } template <typename T> TfLiteStatus AddVectorOperand(const T* values, uint32_t num_values, int32_t nn_type) { return AddVectorOperand(values, num_values, nn_type, /*scale=*/0.f, /*zero_point=*/0); } TfLiteStatus AddFloat32OutputTensor(uint32_t dimension_count, const uint32_t* dimension_data, int* ann_index_out) { return AddAdditionalOutputTensor( dimension_count, dimension_data, ANEURALNETWORKS_TENSOR_FLOAT32, /*scale=*/0.f, /*zero_point=*/0, ann_index_out); } TfLiteStatus AddAdditionalOutputTensor(uint32_t dimension_count, const uint32_t* dimension_data, int32_t nn_type, float scale, int32_t zero_point, int* ann_index_out) { ANeuralNetworksOperandType operand_type{ .type = nn_type, .dimensionCount = dimension_count, .dimensions = dimension_data, .scale = scale, .zeroPoint = zero_point, }; RETURN_TFLITE_ERROR_IF_NN_ERROR( context_, nnapi_->ANeuralNetworksModel_addOperand(nn_model_, &operand_type), "adding operand", nnapi_errno_); const int ann_index = operand_mapping_->add_new_non_tensor_operand(); augmented_outputs_.push_back(ann_index); if (ann_index_out) *ann_index_out = ann_index; return kTfLiteOk; } // Adds a new NN API tensor that shadows the TF Lite tensor `tensor_index`. // This returns the NN API tensor index corresponding to the created tensor. // If another caller previously created a NN API tensor for `tensor_index` // then the existing one is returned. TfLiteStatus AddTensor(int tensor_index, bool hybrid_op, std::vector<uint32_t>* indices, int tensor_flags = 0) { const bool scalar_as_tensor = tensor_flags & NN_TENSOR_FLAG_SCALAR_AS_TENSOR; const bool need_int8_conversion = tensor_flags & NN_TENSOR_FLAG_INT8_CONVERSION; int ann_tensor_index = operand_mapping_->lite_index_to_ann(tensor_index); if (ann_tensor_index != -1) { indices->push_back(ann_tensor_index); return kTfLiteOk; } // Allocate a new tensor index ann_tensor_index = operand_mapping_->add_new_ann_tensor_index(tensor_index); // Parameters needed for new type. int32_t nn_type = 0; float scale = 0.0f; int32_t zeroPoint = 0; ANeuralNetworksSymmPerChannelQuantParams ann_perchannel_params; TfLiteTensor* tensor = &context_->tensors[tensor_index]; TfLiteType tensor_type = tensor->type; if (hybrid_op && (tensor_type == kTfLiteUInt8)) { // For legacy reason, UINT8 weights in hybrid operators are actually INT8 // values and should be interpreted as such. tensor_type = kTfLiteInt8; } switch (tensor_type) { case kTfLiteNoType: // Tensors added during initialization of Ops don't have a type yet and // should not be registered with the NNAPI. indices->push_back(-1); return kTfLiteOk; case kTfLiteFloat32: nn_type = ANEURALNETWORKS_TENSOR_FLOAT32; break; case kTfLiteUInt8: case kTfLiteInt8: // If explicit int8 conversion is needed, we still need // ANEURALNETWORKS_TENSOR_QUANT8_ASYMM type. nn_type = (tensor_type == kTfLiteUInt8 || need_int8_conversion) ? ANEURALNETWORKS_TENSOR_QUANT8_ASYMM : ANEURALNETWORKS_TENSOR_QUANT8_SYMM; scale = tensor->params.scale; zeroPoint = tensor->params.zero_point; if (tensor->quantization.type == kTfLiteAffineQuantization) { TfLiteAffineQuantization* quantization_params = static_cast<TfLiteAffineQuantization*>( tensor->quantization.params); if (quantization_params->scale->size > 1) { bool all_zp_equal_to_zero(true); for (auto i = 0; i < quantization_params->zero_point->size; ++i) { all_zp_equal_to_zero &= (0 == quantization_params->zero_point->data[i]); } if (!(tensor_type == kTfLiteInt8 && all_zp_equal_to_zero)) { TFLITE_LOG(TFLITE_LOG_ERROR, "NNapi Cannot handle int8 asymmetric datatype"); return kTfLiteError; } // Set up per-channel quantization. ann_perchannel_params = { .channelDim = static_cast<uint32_t>( quantization_params->quantized_dimension), .scaleCount = static_cast<uint32_t>(quantization_params->scale->size), .scales = quantization_params->scale->data, }; nn_type = ANEURALNETWORKS_TENSOR_QUANT8_SYMM_PER_CHANNEL; scale = 0.0f; zeroPoint = 0; } else if (quantization_params->scale->size == 1) { scale = quantization_params->scale->data[0]; zeroPoint = quantization_params->zero_point->data[0]; } } if (nn_type != ANEURALNETWORKS_TENSOR_QUANT8_SYMM_PER_CHANNEL) { if (need_int8_conversion) { zeroPoint += 128; operand_mapping_->add_type_conversion(tensor_index, kTfLiteUInt8); } if (scale == 0) { // TENSOR_QUANT8_ASYMM and ANEURALNETWORKS_TENSOR_QUANT8_ASYMM // with zero scale are not valid in NNAPI. scale = 1; } } break; case kTfLiteInt32: nn_type = ANEURALNETWORKS_TENSOR_INT32; scale = tensor->params.scale; zeroPoint = tensor->params.zero_point; break; case kTfLiteBool: nn_type = ANEURALNETWORKS_TENSOR_BOOL8; break; case kTfLiteInt16: nn_type = ANEURALNETWORKS_TENSOR_QUANT16_SYMM; scale = tensor->params.scale; zeroPoint = tensor->params.zero_point; break; default: context_->ReportError( context_, "Failed to add NN API tensor: type %s is not supported.", TfLiteTypeGetName(tensor_type)); return kTfLiteError; } uint32_t tensor_rank = static_cast<uint32_t>(tensor->dims->size); uint32_t* tensor_dims = reinterpret_cast<uint32_t*>(tensor->dims->data); if (scalar_as_tensor && tensor_rank == 0) { // Use rank 1, shape {1} operand for TFLite scalar tensors. tensor_rank = 1; tensor_dims = &tensor_rank; } if (tensor_rank == 0) { // if the tensor_rank is 0, the dimension ptr must be nullptr. tensor_dims = nullptr; } ANeuralNetworksOperandType operand_type{nn_type, tensor_rank, tensor_dims, scale, zeroPoint}; RETURN_TFLITE_ERROR_IF_NN_ERROR( context_, nnapi_->ANeuralNetworksModel_addOperand(nn_model_, &operand_type), "adding operand", nnapi_errno_); if (nn_type == ANEURALNETWORKS_TENSOR_QUANT8_SYMM_PER_CHANNEL) { RETURN_TFLITE_ERROR_IF_NN_ERROR( context_, nnapi_->ANeuralNetworksModel_setOperandSymmPerChannelQuantParams( nn_model_, ann_tensor_index, &ann_perchannel_params), "setting new operand per channel quantization params", nnapi_errno_); } if (tensor->allocation_type == kTfLiteMmapRo) { if (IsQuantized(tensor_type) && need_int8_conversion && nn_type != ANEURALNETWORKS_TENSOR_QUANT8_SYMM_PER_CHANNEL) { // We need to to add a tensor and convert the weights into uint8. // Currently this is only needed for fully_connected. The new_tensor is // needed for lifetime management for the converted weights. int new_tensor_index = -1; TF_LITE_ENSURE_OK(context_, context_->AddTensors(context_, 1, &new_tensor_index)); TfLiteTensor* new_tensor = &context_->tensors[new_tensor_index]; new_tensor->type = kTfLiteUInt8; new_tensor->allocation_type = kTfLiteDynamic; new_tensor->params.scale = scale; new_tensor->params.zero_point = zeroPoint; // Not removing the new tensor in case of resizing errors since it will // be cleared by the context TF_LITE_ENSURE_OK( context_, context_->ResizeTensor(context_, new_tensor, // Resize Tensor takes ownership of // the dims array passed as param TfLiteIntArrayCopy(tensor->dims))); // Convert the int8 value into corresponding uint8 value; const auto num_elements = NumElements(tensor); for (int i = 0; i < num_elements; ++i) { new_tensor->data.uint8[i] = static_cast<const uint8_t>( static_cast<int32_t>(tensor->data.int8[i]) + 128); } RETURN_TFLITE_ERROR_IF_NN_ERROR( context_, nnapi_->ANeuralNetworksModel_setOperandValue( nn_model_, ann_tensor_index, new_tensor->data.raw, new_tensor->bytes), "setting new operand value", nnapi_errno_); #ifdef TFLITE_NNAPI_ALLOW_MMAP_SHARING } else if (tensor->allocation && static_cast<const Allocation*>(tensor->allocation)->type() == Allocation::Type::kMMap) { const MMAPAllocation* mmap_alloc = static_cast<const MMAPAllocation*>(tensor->allocation); if (allocation_memory_mapping_->count(mmap_alloc) == 0) { ANeuralNetworksMemory* ann_memory_handle = nullptr; nnapi_->ANeuralNetworksMemory_createFromFd( mmap_alloc->bytes(), PROT_READ, mmap_alloc->fd(), 0, &ann_memory_handle); allocation_memory_mapping_->insert( std::make_pair(mmap_alloc, ann_memory_handle)); } ANeuralNetworksMemory* ann_memory_handle = allocation_memory_mapping_->at(mmap_alloc); // Compute the offset to the base pointer of the MMAPAllocation. auto offset = reinterpret_cast<const uint8_t*>(tensor->data.raw) - reinterpret_cast<const uint8_t*>(mmap_alloc->base()); RETURN_TFLITE_ERROR_IF_NN_ERROR( context_, nnapi_->ANeuralNetworksModel_setOperandValueFromMemory( nn_model_, ann_tensor_index, ann_memory_handle, offset, tensor->bytes), "setting new operand value from memory", nnapi_errno_); #endif } else { RETURN_TFLITE_ERROR_IF_NN_ERROR( context_, nnapi_->ANeuralNetworksModel_setOperandValue( nn_model_, ann_tensor_index, tensor->data.raw, tensor->bytes), "setting new operand value", nnapi_errno_); } } indices->push_back(ann_tensor_index); return kTfLiteOk; } // Access to NNAPI. const NnApi* const nnapi_; // TfLiteContext for error handling. TfLiteContext* const context_; // Tracks relationship between indices. OperandMapping* const operand_mapping_; // Keeps mapping of ANN quantized tensor and float data type to equivalent // dequantized ANN tensor. For example, tensor #4 (UINT8) + FLOAT32 could map // to tensor #10 (FLOAT32) because a DEQUANTIZE operator was added to convert // tensor #4 to a FLOAT32 tensor. DequantizeMapping* const dequantize_mapping_; std::map<const MMAPAllocation*, ANeuralNetworksMemory*>* const allocation_memory_mapping_; // Tracks for every operation in the NNAPI model the source TfLite model // node index. std::vector<int>* const nnapi_to_tflite_op_mapping_; // The NNAPI model. ANeuralNetworksModel* const nn_model_; // Inputs and outputs for the current op. These are augmented in the sense // that NN API uses operands for all arguments, not just tensors, unlike // TensorFlow Lite. std::vector<uint32_t> augmented_inputs_; std::vector<uint32_t> augmented_outputs_; // Return status code of the latest NNAPI call. int* nnapi_errno_; }; // namespace nnapi namespace { struct OpValidationContext { bool is_valid; std::vector<NNAPIValidationFailure>* validation_failures; }; #define EXPECT_INPUT_TYPE_IN(actual_type, ...) \ ExpectTypeIn(actual_type, {__VA_ARGS__}, \ NNAPIValidationFailureType::kUnsupportedInputType, \ "Input type not in expected list " #__VA_ARGS__, &val_ctx) inline void AddValidationFailure(NNAPIValidationFailureType failure_type, const char* message, OpValidationContext* val_ctx) { val_ctx->is_valid = false; #ifdef NNAPI_VERBOSE_VALIDATION if (val_ctx->validation_failures) { val_ctx->validation_failures->push_back({failure_type, message}); } #endif } template <typename... Args> inline void AddValidationFailureFmt(OpValidationContext* val_ctx, NNAPIValidationFailureType failure_type, const char* message_fmt, Args... args) { val_ctx->is_valid = false; #ifdef NNAPI_VERBOSE_VALIDATION if (val_ctx->validation_failures) { size_t req_buf_size = snprintf(nullptr, 0, message_fmt, args...) + 1; std::unique_ptr<char[]> tmp_buf(new char[req_buf_size]); snprintf(tmp_buf.get(), req_buf_size, message_fmt, args...); val_ctx->validation_failures->push_back({failure_type, tmp_buf.get()}); } #endif } inline bool Expect(bool condition, NNAPIValidationFailureType failure_type, const char* message, OpValidationContext* val_ctx) { if (!condition) { AddValidationFailure(failure_type, message, val_ctx); return false; } return true; } template <typename... Args> inline bool ExpectFmt(bool condition, OpValidationContext* val_ctx, NNAPIValidationFailureType failure_type, const char* message_fmt, Args... args) { if (!condition) { AddValidationFailureFmt(val_ctx, failure_type, message_fmt, args...); return false; } return true; } inline bool ExpectTypeIn(TfLiteType actual_type, std::initializer_list<TfLiteType> allowed_types, NNAPIValidationFailureType failure_type, const char* msg, OpValidationContext* val_ctx) { return Expect(std::find(allowed_types.begin(), allowed_types.end(), actual_type) != allowed_types.end(), failure_type, msg, val_ctx); } inline bool ExpectMinAndroidSdkVersion(int curr_version, int min_version, OpValidationContext* val_ctx) { return ExpectFmt(curr_version >= min_version, val_ctx, NNAPIValidationFailureType::kUnsupportedAndroidVersion, "Android sdk version less than %d", min_version); } inline bool ExpectMaxOpVersion(int curr_version, int max_version, OpValidationContext* val_ctx) { return ExpectFmt(curr_version <= max_version, val_ctx, NNAPIValidationFailureType::kUnsupportedOperatorVersion, "OP Version higher than %d", max_version); } inline bool ExpectOpVersion(int curr_version, int max_version, OpValidationContext* val_ctx) { return ExpectFmt(curr_version <= max_version, val_ctx, NNAPIValidationFailureType::kUnsupportedOperatorVersion, "OP Version different from %d", max_version); } inline bool ExpectIsFloatOperator(const TfLiteContext* context, const TfLiteNode* node, OpValidationContext* val_ctx) { const auto input_type = context->tensors[node->inputs->data[0]].type; return Expect(IsFloat(input_type), NNAPIValidationFailureType::kUnsupportedInputType, "Input should be Float", val_ctx); } bool ExpectIsFloatOrUint8Operator(const TfLiteContext* context, const TfLiteNode* node, OpValidationContext* val_ctx) { const auto input_type = context->tensors[node->inputs->data[0]].type; return Expect(IsFloatOrUInt8(input_type), NNAPIValidationFailureType::kUnsupportedInputType, "Input should be Float or UINT8", val_ctx); } bool ExpectIsFloatOrQuant8Operator(const TfLiteContext* context, const TfLiteNode* node, OpValidationContext* val_ctx) { const auto input_type = context->tensors[node->inputs->data[0]].type; return Expect(IsFloat(input_type) || IsQuantized(input_type), NNAPIValidationFailureType::kUnsupportedInputType, "Input should be Float or Quant8", val_ctx); } // When using NN API version 1.0 or 1.1, the condition below must be true for // quantized versions of the following ops: // * CONV_2D // * DEPTHWISE_CONV_2D // * FULLY_CONNECTED (where filter actually stands for weights) // The condition is relaxed and no longer required since version 1.2. bool ExpectIsRestrictedScalesCompliant(const TfLiteContext* context, const TfLiteNode* node, OpValidationContext* val_ctx) { const int input_id = node->inputs->data[0]; const int filter_id = node->inputs->data[1]; const int output_id = node->outputs->data[0]; const float input_scale = context->tensors[input_id].params.scale; const float filter_scale = context->tensors[filter_id].params.scale; const float output_scale = context->tensors[output_id].params.scale; return Expect(input_scale * filter_scale < output_scale, NNAPIValidationFailureType::kNotRestrictedScaleCompliant, "When using NN API version 1.0 or 1.1, input_scale * " "filter_scale < output_scale:", val_ctx); } } // namespace // Return a function that knows how to translate a node into its operands // when called. You can use this function to see if a node is supported // (i.e. if the returned MappingFn is null, then the node is not supported). bool NNAPIDelegateKernel::Validate( const TfLiteContext* context, int builtin_code, int version, int android_sdk_version, const TfLiteNode* node, bool is_accelerator_specified, std::vector<NNAPIValidationFailure>* map_failures) { OpValidationContext val_ctx{true, map_failures}; switch (builtin_code) { case kTfLiteBuiltinAdd: { ExpectMaxOpVersion(version, 2, &val_ctx); ExpectIsFloatOrQuant8Operator(context, node, &val_ctx); } break; case kTfLiteBuiltinArgMax: case kTfLiteBuiltinArgMin: { ExpectMaxOpVersion(version, 2, &val_ctx); // Those operators were introduced in NNAPI 1.2. ExpectMinAndroidSdkVersion(android_sdk_version, kMinSdkVersionForNNAPI12, &val_ctx); const TfLiteType input_type = context->tensors[node->inputs->data[(0)]].type; EXPECT_INPUT_TYPE_IN(input_type, kTfLiteFloat16, kTfLiteFloat32, kTfLiteInt32, kTfLiteUInt8, kTfLiteInt8); const auto& axis_tensor = context->tensors[node->inputs->data[1]]; if (axis_tensor.type == kTfLiteInt64) { Expect( axis_tensor.allocation_type == kTfLiteMmapRo && *axis_tensor.data.i64 <= std::numeric_limits<int32_t>::max() && *axis_tensor.data.i64 >= std::numeric_limits<int32_t>::min(), NNAPIValidationFailureType::kUnsupportedInputType, "NNAPI only supports axis as int32. If the axis type is int64 and " "constant we can convert it to int32 if the value isn't too " "large.", &val_ctx); } else { Expect(axis_tensor.type == kTfLiteInt32, NNAPIValidationFailureType::kUnsupportedInputType, "Axis should be Int32", &val_ctx); } if (builtin_code == kTfLiteBuiltinArgMax) { auto builtin = reinterpret_cast<TfLiteArgMaxParams*>(node->builtin_data); Expect(builtin->output_type == kTfLiteInt32, NNAPIValidationFailureType::kUnsupportedOutputType, "NNAPI only supports int32 output.", &val_ctx); } else { auto builtin = reinterpret_cast<TfLiteArgMinParams*>(node->builtin_data); Expect(builtin->output_type == kTfLiteInt32, NNAPIValidationFailureType::kUnsupportedOutputType, "NNAPI only supports int32 output.", &val_ctx); } } break; case kTfLiteBuiltinMul: { ExpectMaxOpVersion(version, 2, &val_ctx); ExpectIsFloatOrQuant8Operator(context, node, &val_ctx); } break; case kTfLiteBuiltinAveragePool2d: { ExpectMaxOpVersion(version, 2, &val_ctx); ExpectIsFloatOrQuant8Operator(context, node, &val_ctx); auto builtin = reinterpret_cast<TfLitePoolParams*>(node->builtin_data); // TODO(b/138756912): Large filter window would overflow on the // quantized reference CPU path. if (IsQuantized(context->tensors[node->inputs->data[0]].type)) { Expect(is_accelerator_specified || (builtin->filter_width * builtin->filter_height <= 256), NNAPIValidationFailureType::kUnsupportedOperandSize, "Large filter window would overflow on the reference CPU path", &val_ctx); } } break; case kTfLiteBuiltinMaxPool2d: { ExpectMaxOpVersion(version, 2, &val_ctx); ExpectIsFloatOrQuant8Operator(context, node, &val_ctx); } break; case kTfLiteBuiltinL2Pool2d: { ExpectOpVersion(version, 1, &val_ctx); ExpectIsFloatOperator(context, node, &val_ctx); if (android_sdk_version < kMinSdkVersionForNNAPI12) { auto builtin = reinterpret_cast<TfLitePoolParams*>(node->builtin_data); Expect(builtin->activation == kTfLiteActNone, NNAPIValidationFailureType::kUnsupportedOperandValue, "Before NNAPI 1.2 fused activation for l2_pool may not be " "supported.", &val_ctx); } } break; case kTfLiteBuiltinConv2d: { ExpectMaxOpVersion(version, 3, &val_ctx); if (android_sdk_version < kMinSdkVersionForNNAPI12) { Expect(!IsHybridOperator(context, builtin_code, node), NNAPIValidationFailureType::kUnsupportedHybridOperator, "Hybrid operators not supported before NNAPI 1.2", &val_ctx); ExpectIsFloatOrUint8Operator(context, node, &val_ctx); const auto& filter_tensor = context->tensors[node->inputs->data[1]]; if (filter_tensor.quantization.type == kTfLiteAffineQuantization) { TfLiteAffineQuantization* quantization_params = static_cast<TfLiteAffineQuantization*>( filter_tensor.quantization.params); Expect(quantization_params->scale->size <= 1, NNAPIValidationFailureType::kUnsupportedQuantizationType, "Per-channel quantized convolution not supported before NNAPI " "1.2.", &val_ctx); } } const auto input_type = context->tensors[node->inputs->data[0]].type; if (android_sdk_version < kMinSdkVersionForNNAPI12 && input_type == kTfLiteUInt8) { ExpectIsRestrictedScalesCompliant(context, node, &val_ctx); } auto builtin = reinterpret_cast<TfLiteConvParams*>(node->builtin_data); // TODO(b/132950584): Add support for Conv2D with omitted bias. Expect(node->inputs->size == 3, NNAPIValidationFailureType::kMissingRequiredOperand, "Conv2D with omitted bias not supported", &val_ctx); if (builtin->dilation_width_factor != 1 || builtin->dilation_height_factor != 1) { Expect(android_sdk_version >= kMinSdkVersionForNNAPI12, NNAPIValidationFailureType::kUnsupportedOperandValue, "NNAPI supports dilated Conv2D since NNAPI 1.2.", &val_ctx); } } break; case kTfLiteBuiltinDepthwiseConv2d: { ExpectMaxOpVersion(version, 3, &val_ctx); if (android_sdk_version < kMinSdkVersionForNNAPI12) { ExpectIsFloatOrUint8Operator(context, node, &val_ctx); const auto input_type = context->tensors[node->inputs->data[0]].type; if (input_type == kTfLiteUInt8) { ExpectIsRestrictedScalesCompliant(context, node, &val_ctx); } auto builtin = reinterpret_cast<TfLiteDepthwiseConvParams*>(node->builtin_data); Expect(builtin->dilation_width_factor == 1 && builtin->dilation_height_factor == 1, NNAPIValidationFailureType::kUnsupportedOperandValue, "dilation_width_factor and dilation_height_factor expected to " "be equal to 1", &val_ctx); } } break; case kTfLiteBuiltinFullyConnected: { ExpectMaxOpVersion(version, 4, &val_ctx); // TODO(b/132950584): Add support for FullyConnected with no bias. Expect(node->inputs->size == 3 && node->inputs->data[2] != kTfLiteOptionalTensor, NNAPIValidationFailureType::kMissingRequiredOperand, "FullyConnected with no bias not supported", &val_ctx); const auto output_type = context->tensors[node->outputs->data[0]].type; Expect(output_type != kTfLiteInt16, NNAPIValidationFailureType::kUnsupportedOutputType, "Unsupported output of type kTfLiteInt16", &val_ctx); if (android_sdk_version < kMinSdkVersionForNNAPI12) { Expect(!IsHybridOperator(context, builtin_code, node), NNAPIValidationFailureType::kUnsupportedHybridOperator, "Hybrid operators not supported before NNAPI 1.2", &val_ctx); ExpectIsFloatOrUint8Operator(context, node, &val_ctx); } const auto input_type = context->tensors[node->inputs->data[0]].type; if (android_sdk_version < kMinSdkVersionForNNAPI12 && input_type == kTfLiteUInt8) { ExpectIsRestrictedScalesCompliant(context, node, &val_ctx); } auto builtin = reinterpret_cast<TfLiteFullyConnectedParams*>(node->builtin_data); Expect(!builtin->keep_num_dims, NNAPIValidationFailureType::kUnsupportedOperandValue, "keep_num_dims == true not supported", &val_ctx); } break; case kTfLiteBuiltinHardSwish: { // Add support for hardswish. For Pre-Q devices, deconstructing it into // basic ops. Though for some nnapi accelerators using optimized tflite // kernels might even be faster. ExpectIsFloatOrQuant8Operator(context, node, &val_ctx); } break; case kTfLiteBuiltinSoftmax: { ExpectOpVersion(version, 2, &val_ctx); const auto& input = context->tensors[node->outputs->data[0]]; ExpectIsFloatOrQuant8Operator(context, node, &val_ctx); const int input_rank = input.dims->size; Expect(input_rank <= 4, NNAPIValidationFailureType::kUnsupportedOperandRank, "Input rank should be <= 4", &val_ctx); if (android_sdk_version < kMinSdkVersionForNNAPI12) { Expect( input_rank == 2 || input_rank == 4, NNAPIValidationFailureType::kUnsupportedOperandRank, "Before API level 29 only 2D and 4D input tensors were supported.", &val_ctx); } } break; case kTfLiteBuiltinReshape: { ExpectOpVersion(version, 1, &val_ctx); ExpectIsFloatOrQuant8Operator(context, node, &val_ctx); Expect(node->inputs->size >= 2, NNAPIValidationFailureType::kMissingRequiredOperand, "Expected at least 2 inputs", &val_ctx); #ifdef __ANDROID__ const auto& input = context->tensors[node->inputs->data[0]]; Expect(input.dims->size <= 4, NNAPIValidationFailureType::kUnsupportedOperandRank, "Input rank should be <= 4", &val_ctx); #endif if (node->inputs->size >= 2) { Expect(context->tensors[node->inputs->data[1]].allocation_type == kTfLiteMmapRo, NNAPIValidationFailureType::kInputTensorShouldHaveConstantShape, "The shape input tensor must be constant.", &val_ctx); } } break; case kTfLiteBuiltinResizeBilinear: { ExpectMaxOpVersion(version, 3, &val_ctx); const auto& input = context->tensors[node->inputs->data[0]]; const auto output_dims = context->tensors[node->outputs->data[0]].dims; Expect(input.dims->size == 4, NNAPIValidationFailureType::kUnsupportedOperandRank, "Input should have rank 4", &val_ctx); ExpectIsFloatOrQuant8Operator(context, node, &val_ctx); Expect(node->inputs->size >= 2, NNAPIValidationFailureType::kUnsupportedOperatorVariant, "Expected at least 2 inputs", &val_ctx); if (node->inputs->size >= 2) { Expect(context->tensors[node->inputs->data[1]].allocation_type == kTfLiteMmapRo, NNAPIValidationFailureType::kInputTensorShouldHaveConstantShape, "The size input tensor must be constant.", &val_ctx); } if (android_sdk_version < kMinSdkVersionForNNAPI12) { Expect(output_dims->data[1] == output_dims->data[2], NNAPIValidationFailureType::kUnsupportedOperandValue, "Require width == height due to driver differences in NNAPI " "< 1.2", &val_ctx); } auto builtin = reinterpret_cast<TfLiteResizeBilinearParams*>(node->builtin_data); #if defined __ANDROID__ if (android_sdk_version <= kMinSdkVersionForNNAPI12) { Expect(!builtin->align_corners, NNAPIValidationFailureType::kUnsupportedOperandValue, "NNAPI does not support align_corners == true.", &val_ctx); Expect(!builtin->half_pixel_centers, NNAPIValidationFailureType::kUnsupportedOperandValue, "NNAPI does not support half_pixel_centers == true.", &val_ctx); } #endif if (android_sdk_version < kMinSdkVersionForNNAPI12) { Expect(input.type == kTfLiteFloat32, NNAPIValidationFailureType::kUnsupportedInputType, "NNAPI 1.0 & 1.1 only supports float input.", &val_ctx); } } break; case kTfLiteBuiltinResizeNearestNeighbor: { ExpectMaxOpVersion(version, 3, &val_ctx); ExpectMinAndroidSdkVersion(android_sdk_version, kMinSdkVersionForNNAPI12, &val_ctx); ExpectIsFloatOrQuant8Operator(context, node, &val_ctx); auto builtin = reinterpret_cast<TfLiteResizeNearestNeighborParams*>( node->builtin_data); if (android_sdk_version <= kMinSdkVersionForNNAPI12) { Expect(!builtin->align_corners, NNAPIValidationFailureType::kUnsupportedOperandValue, "NNAPI does not support align_corners == true.", &val_ctx); Expect(!builtin->half_pixel_centers, NNAPIValidationFailureType::kUnsupportedOperandValue, "NNAPI does not support half_pixel_centers == true.", &val_ctx); } } break; case kTfLiteBuiltinSqueeze: { ExpectOpVersion(version, 1, &val_ctx); ExpectMinAndroidSdkVersion(android_sdk_version, kMinSdkVersionForNNAPI11, &val_ctx); auto builtin = reinterpret_cast<TfLiteSqueezeParams*>(node->builtin_data); if (android_sdk_version == kMinSdkVersionForNNAPI11) { Expect(builtin->num_squeeze_dims != 0, NNAPIValidationFailureType::kUnsupportedOperandValue, "NNAPI 1.1 does not support null squeeze_dims properly.", &val_ctx); } } break; case kTfLiteBuiltinUnidirectionalSequenceLstm: { ExpectMaxOpVersion(version, 2, &val_ctx); ExpectMinAndroidSdkVersion(android_sdk_version, kMinSdkVersionForNNAPI12, &val_ctx); Expect(!IsHybridOperator(context, builtin_code, node), NNAPIValidationFailureType::kUnsupportedHybridOperator, "Hybrid version of this op is not supported by NN API.", &val_ctx); Expect(node->inputs->size == 20 || node->inputs->size == 24, NNAPIValidationFailureType::kUnsupportedOperatorVariant, "Supporting only operation with 20 or 24 inputs", &val_ctx); } break; case kTfLiteBuiltinL2Normalization: { ExpectMaxOpVersion(version, 2, &val_ctx); if (android_sdk_version < kMinSdkVersionForNNAPI12) { ExpectIsFloatOperator(context, node, &val_ctx); const auto& input = context->tensors[node->inputs->data[0]]; Expect(input.dims->size == 4, NNAPIValidationFailureType::kUnsupportedOperatorVariant, "Expected 4 inputs", &val_ctx); } auto builtin = reinterpret_cast<TfLiteL2NormParams*>(node->builtin_data); Expect(builtin->activation == kTfLiteActNone, NNAPIValidationFailureType::kNoActivationExpected, "Expected no activation", &val_ctx); } break; case kTfLiteBuiltinLocalResponseNormalization: { ExpectOpVersion(version, 1, &val_ctx); } break; case kTfLiteBuiltinLshProjection: { ExpectOpVersion(version, 1, &val_ctx); if (reinterpret_cast<TfLiteLSHProjectionParams*>(node->builtin_data) ->type == kTfLiteLshProjectionSparse) { // NNAPI does not support sparse projection correctly pre-Q // (b/111751836). Expect(android_sdk_version >= kMinSdkVersionForNNAPI12, NNAPIValidationFailureType::kUnsupportedInputType, "NNAPI does not support sparse projection correctly pre-Q", &val_ctx); Expect(node->inputs->size == 2, NNAPIValidationFailureType::kUnsupportedOperatorVariant, " NNAPI does not support weights for sparse projects.", &val_ctx); } } break; case kTfLiteBuiltinConcatenation: { ExpectMaxOpVersion(version, 2, &val_ctx); Expect(reinterpret_cast<TfLiteConcatenationParams*>(node->builtin_data) ->activation == kTfLiteActNone, NNAPIValidationFailureType::kNoActivationExpected, "No activation function supported", &val_ctx); Expect(context->tensors[node->inputs->data[0]].dims->size <= 4, NNAPIValidationFailureType::kUnsupportedOperandRank, "Input rank should be less than 4", &val_ctx); if (context->tensors[node->inputs->data[0]].type == kTfLiteUInt8 && android_sdk_version < kMinSdkVersionForNNAPI12) { auto first_param = context->tensors[node->inputs->data[0]].params; for (int i = 1; i < node->inputs->size; i++) { auto curr_param = context->tensors[node->inputs->data[i]].params; if (!Expect(curr_param.scale == first_param.scale && curr_param.zero_point == first_param.zero_point, NNAPIValidationFailureType::kUnsupportedOperandValue, "NNAPI 1.0-1 only supported concatenating quantized " "tensor of the same scale and offset.", &val_ctx)) { break; } } } } break; case kTfLiteBuiltinDequantize: { Expect(version == 1 || version == 2, NNAPIValidationFailureType::kUnsupportedOperatorVersion, "Supported op versions are 1 and 2 only", &val_ctx); const auto& input = context->tensors[node->inputs->data[0]]; Expect(input.type != kTfLiteFloat16, NNAPIValidationFailureType::kUnsupportedInputType, "kTfLiteFloat16 not supported as input", &val_ctx); const auto zero_point = input.params.zero_point; Expect(input.type != kTfLiteInt8 || (zero_point == 0 && android_sdk_version >= kMinSdkVersionForNNAPI12), NNAPIValidationFailureType::kUnsupportedInputType, "NN API supports int8 type since version 1.2 but only for " "symmetric quantization.", &val_ctx); } break; case kTfLiteBuiltinFloor: { ExpectOpVersion(version, 1, &val_ctx); } break; case kTfLiteBuiltinRelu: case kTfLiteBuiltinReluN1To1: case kTfLiteBuiltinRelu6: case kTfLiteBuiltinLogistic: { ExpectMaxOpVersion(version, 2, &val_ctx); ExpectIsFloatOrQuant8Operator(context, node, &val_ctx); } break; case kTfLiteBuiltinTanh: { ExpectMaxOpVersion(version, 2, &val_ctx); const TfLiteType input_type = context->tensors[node->inputs->data[0]].type; Expect(IsFloat(input_type) || (IsQuantized(input_type) && android_sdk_version >= kMinSdkVersionForNNAPI12), NNAPIValidationFailureType::kUnsupportedInputType, " NNAPI only support float tanh.", &val_ctx); } break; case kTfLiteBuiltinSub: { ExpectMaxOpVersion(version, 3, &val_ctx); const TfLiteType input_type = context->tensors[node->inputs->data[0]].type; Expect((android_sdk_version >= kMinSdkVersionForNNAPI11 && IsFloat(input_type)) || (android_sdk_version >= kMinSdkVersionForNNAPI12 && IsQuantized(input_type)), NNAPIValidationFailureType::kUnsupportedInputType, "NNAPI only support float sub.", &val_ctx); const int input0_rank = context->tensors[node->inputs->data[0]].dims->size; const int input1_rank = context->tensors[node->inputs->data[1]].dims->size; Expect(input0_rank <= 4 && input1_rank <= 4, NNAPIValidationFailureType::kUnsupportedOperandRank, "Input rank must be <= 4", &val_ctx); } break; case kTfLiteBuiltinDiv: { ExpectOpVersion(version, 1, &val_ctx); ExpectMinAndroidSdkVersion(android_sdk_version, kMinSdkVersionForNNAPI11, &val_ctx); Expect(context->tensors[node->inputs->data[0]].type == kTfLiteFloat32, NNAPIValidationFailureType::kUnsupportedInputType, "NNAPI only support float div.", &val_ctx); } break; case kTfLiteBuiltinPad: case kTfLiteBuiltinPadv2: { ExpectMaxOpVersion(version, 2, &val_ctx); ExpectIsFloatOrQuant8Operator(context, node, &val_ctx); ExpectMinAndroidSdkVersion(android_sdk_version, kMinSdkVersionForNNAPI11, &val_ctx); const TfLiteIntArrayView input_shape( context->tensors[node->inputs->data[0]].dims); Expect(!HasZeroes(input_shape), NNAPIValidationFailureType::kUnsupportedOperandValue, "NN API pad ops do not support input tensors with no elements", &val_ctx); Expect(node->inputs->size >= 2, NNAPIValidationFailureType::kUnsupportedOperatorVariant, "Expecting at least 2 inputs", &val_ctx); if (node->inputs->size == 3) { // This is going to be mapped with a PadV2 Expect( android_sdk_version >= kMinSdkVersionForNNAPI12, NNAPIValidationFailureType::kUnsupportedOperatorVariant, "Specification of the padding value is supported from NNAPI 1.2.", &val_ctx); } else { // this is going to be mapped as Pad if (android_sdk_version < kMinSdkVersionForNNAPI12) { Expect(context->tensors[node->inputs->data[0]].type == kTfLiteFloat32, NNAPIValidationFailureType::kUnsupportedInputType, "Only Float32 inputs are supported before NNAPI 1.2", &val_ctx); } } } break; case kTfLiteBuiltinUnidirectionalSequenceRnn: { ExpectOpVersion(version, 1, &val_ctx); ExpectMinAndroidSdkVersion(android_sdk_version, kMinSdkVersionForNNAPI12, &val_ctx); Expect(!IsHybridOperator(context, builtin_code, node), NNAPIValidationFailureType::kUnsupportedHybridOperator, "Hybrid version of this op is not supported by NN API.", &val_ctx); } break; case kTfLiteBuiltinSpaceToBatchNd: { ExpectMaxOpVersion(version, 2, &val_ctx); ExpectMinAndroidSdkVersion(android_sdk_version, kMinSdkVersionForNNAPI11, &val_ctx); } break; case kTfLiteBuiltinBatchToSpaceNd: { ExpectMaxOpVersion(version, 2, &val_ctx); ExpectMinAndroidSdkVersion(android_sdk_version, kMinSdkVersionForNNAPI11, &val_ctx); auto crops = context->tensors[node->inputs->data[2]]; auto crops_data = crops.data.i32; Expect(crops_data && crops.bytes == 16 && crops_data[0] == 0 && crops_data[1] == 0 && crops_data[2] == 0 && crops_data[3] == 0, NNAPIValidationFailureType::kUnsupportedOperandValue, "All crops should be 0.", &val_ctx); } break; case kTfLiteBuiltinStridedSlice: { ExpectMaxOpVersion(version, 2, &val_ctx); ExpectMinAndroidSdkVersion(android_sdk_version, kMinSdkVersionForNNAPI11, &val_ctx); } break; case kTfLiteBuiltinTranspose: { ExpectMaxOpVersion(version, 2, &val_ctx); ExpectMinAndroidSdkVersion(android_sdk_version, kMinSdkVersionForNNAPI11, &val_ctx); // Note that the permutation input tensor value dictates the output // dimensions. // TODO(b/110888333): Support dynamically-sized tensors in delegates. Expect((node->inputs->size > 1) && (context->tensors[node->inputs->data[1]].allocation_type == kTfLiteMmapRo), NNAPIValidationFailureType::kInputTensorShouldHaveConstantShape, "Dynamically-sized tensors not supported.", &val_ctx); } break; case kTfLiteBuiltinAbs: case kTfLiteBuiltinExp: case kTfLiteBuiltinLog: case kTfLiteBuiltinRsqrt: case kTfLiteBuiltinPow: { ExpectOpVersion(version, 1, &val_ctx); ExpectMinAndroidSdkVersion(android_sdk_version, kMinSdkVersionForNNAPI12, &val_ctx); ExpectIsFloatOperator(context, node, &val_ctx); } break; case kTfLiteBuiltinSlice: { ExpectMaxOpVersion(version, 2, &val_ctx); ExpectMinAndroidSdkVersion(android_sdk_version, kMinSdkVersionForNNAPI12, &val_ctx); const auto input_type = context->tensors[node->inputs->data[0]].type; const auto begin_type = context->tensors[node->inputs->data[1]].type; const auto size_type = context->tensors[node->inputs->data[2]].type; EXPECT_INPUT_TYPE_IN(input_type, kTfLiteFloat32, kTfLiteInt32, kTfLiteUInt8, kTfLiteInt8); Expect(begin_type == kTfLiteInt32, NNAPIValidationFailureType::kUnsupportedInputType, "Begin type should be Int32", &val_ctx); Expect(size_type == kTfLiteInt32, NNAPIValidationFailureType::kUnsupportedInputType, "Size type should be Int32", &val_ctx); } break; case kTfLiteBuiltinSin: { ExpectOpVersion(version, 1, &val_ctx); ExpectMinAndroidSdkVersion(android_sdk_version, kMinSdkVersionForNNAPI12, &val_ctx); ExpectIsFloatOperator(context, node, &val_ctx); } break; case kTfLiteBuiltinTransposeConv: { ExpectOpVersion(version, 1, &val_ctx); ExpectMinAndroidSdkVersion(android_sdk_version, kMinSdkVersionForNNAPI12, &val_ctx); Expect((node->inputs->size > 1) && (context->tensors[node->inputs->data[0]].allocation_type == kTfLiteMmapRo) && (context->tensors[node->inputs->data[1]].allocation_type == kTfLiteMmapRo), NNAPIValidationFailureType::kInputTensorShouldHaveConstantShape, "Dynamically-sized tensors not supported.", &val_ctx); } break; case kTfLiteBuiltinSqrt: { ExpectOpVersion(version, 1, &val_ctx); ExpectMinAndroidSdkVersion(android_sdk_version, kMinSdkVersionForNNAPI12, &val_ctx); ExpectIsFloatOperator(context, node, &val_ctx); } break; case kTfLiteBuiltinRnn: { ExpectOpVersion(version, 1, &val_ctx); Expect(node->inputs->size == 5, NNAPIValidationFailureType::kUnsupportedOperatorVariant, "Expected 5 input", &val_ctx); if (node->inputs->size >= 2) { Expect( context->tensors[node->inputs->data[/*kWeightsTensor*/ 1]].type == kTfLiteFloat32, NNAPIValidationFailureType::kUnsupportedInputType, "NNAPI only support float32 weights.", &val_ctx); } } break; case kTfLiteBuiltinSpaceToDepth: { ExpectMaxOpVersion(version, 2, &val_ctx); const TfLiteType input_type = context->tensors[node->inputs->data[0]].type; EXPECT_INPUT_TYPE_IN(input_type, kTfLiteFloat32, kTfLiteUInt8, kTfLiteInt8); } break; case kTfLiteBuiltinSvdf: { ExpectOpVersion(version, 1, &val_ctx); Expect(node->inputs->size == 5, NNAPIValidationFailureType::kUnsupportedOperandRank, "Expected input of rank 5", &val_ctx); if (node->inputs->size >= 2) { Expect( context->tensors[node->inputs->data[/*kWeightsTensor*/ 1]].type == kTfLiteFloat32, NNAPIValidationFailureType::kUnsupportedInputType, "NNAPI only support float32 weights.", &val_ctx); } Expect(android_sdk_version >= kMinSdkVersionForNNAPI11, NNAPIValidationFailureType::kUnsupportedOperandRank, "SVDF does not support rank > 1 on NNAPI 1.0.", &val_ctx); Expect(context->tensors[node->inputs->data[/*kWeightsFeatureTensor*/ 1]] .type == kTfLiteFloat32, NNAPIValidationFailureType::kUnsupportedInputType, "Weights should be Float32", &val_ctx); } break; case kTfLiteBuiltinLstm: { ExpectMaxOpVersion(version, 3, &val_ctx); Expect( android_sdk_version >= kMinSdkVersionForNNAPI11, NNAPIValidationFailureType::kUnsupportedAndroidVersion, "NNAPI 1.0 has a bug for optional tensors which would affect LSTM.", &val_ctx); Expect(android_sdk_version >= kMinSdkVersionForNNAPI12 || !IsHybridOperator(context, builtin_code, node), NNAPIValidationFailureType::kUnsupportedHybridOperator, "Hybrid operators not supported before NNAPI 1.2.", &val_ctx); const auto weight_input_index = isLstmBasicKernel(node) ? 2 /* basic::kInputWeights */ : 4 /* full::kInputToOutputWeightsTensor */; const TfLiteType weight_type = context->tensors[node->inputs->data[weight_input_index]].type; if (isLstmBasicKernel(node)) { Expect(weight_type == kTfLiteUInt8, NNAPIValidationFailureType::kUnsupportedInputType, "Basic LSTM Kernels support only UINT8 weights", &val_ctx); const auto input_quantization_params = context->tensors[node->inputs->data[0]].params; Expect(input_quantization_params.scale == 1. / 128. && input_quantization_params.zero_point == 128, NNAPIValidationFailureType::kUnsupportedQuantizationParameters, "Invalid input quantization", &val_ctx); const auto output_quantization_params = context->tensors[node->outputs->data[0]].params; Expect(output_quantization_params.scale == 1. / 128. && output_quantization_params.zero_point == 128, NNAPIValidationFailureType::kUnsupportedQuantizationParameters, "Invalid output quantization", &val_ctx); const auto cell_state_quantization_params = context->tensors[node->outputs->data[1]].params; Expect(cell_state_quantization_params.scale == 16. / 32768. || cell_state_quantization_params.zero_point == 0, NNAPIValidationFailureType::kUnsupportedQuantizationParameters, "Invalid cell state quantization", &val_ctx); auto is_const_tensor = [&node, &context](int tensor_idx) { return context->tensors[node->inputs->data[tensor_idx]] .allocation_type == kTfLiteMmapRo; }; Expect(is_const_tensor(2 /* kInputWeights */), NNAPIValidationFailureType::kInputTensorShouldHaveConstantShape, "Weights tensor should be constant", &val_ctx); Expect(is_const_tensor(3 /* kInputBiases */), NNAPIValidationFailureType::kInputTensorShouldHaveConstantShape, "Biases tensor should be constant", &val_ctx); return val_ctx.is_valid; } else { if (node->inputs->size == 24) { ExpectMinAndroidSdkVersion(android_sdk_version, kMinSdkVersionForNNAPI12, &val_ctx); } Expect(weight_type == kTfLiteFloat32 || weight_type == kTfLiteUInt8, NNAPIValidationFailureType::kUnsupportedInputType, "Weight has to be Float32 or UINT8", &val_ctx); } } break; case kTfLiteBuiltinMean: { ExpectMaxOpVersion(version, 2, &val_ctx); ExpectMinAndroidSdkVersion(android_sdk_version, kMinSdkVersionForNNAPI11, &val_ctx); if (android_sdk_version >= kMinSdkVersionForNNAPI12) { Expect(context->tensors[node->inputs->data[0]].type == kTfLiteFloat32 || IsQuantized(context->tensors[node->inputs->data[0]].type), NNAPIValidationFailureType::kUnsupportedInputType, "Expected Float32 or Quantized input", &val_ctx); } else { Expect(context->tensors[node->inputs->data[0]].type == kTfLiteFloat32, NNAPIValidationFailureType::kUnsupportedInputType, "Expected Float32 input", &val_ctx); } Expect(context->tensors[node->outputs->data[0]].dims->size > 0, NNAPIValidationFailureType::kUnsupportedOutputType, "NNAPI does not support generating a scalar as output for MEAN.", &val_ctx); #if defined __ANDROID__ auto input_param = context->tensors[node->inputs->data[0]].params; auto output_param = context->tensors[node->outputs->data[0]].params; Expect(input_param.scale == output_param.scale && input_param.zero_point == output_param.zero_point, NNAPIValidationFailureType::kUnsupportedOutputType, "NNAPI requires that the input and output have the same " "quantization parameters.", &val_ctx); #endif } break; case kTfLiteBuiltinEmbeddingLookup: { ExpectOpVersion(version, 1, &val_ctx); Expect(context->tensors[node->inputs->data[1]].type == kTfLiteFloat32, NNAPIValidationFailureType::kUnsupportedInputType, "NNAPI only support float32 values.", &val_ctx); } break; case kTfLiteBuiltinHashtableLookup: { ExpectOpVersion(version, 1, &val_ctx); Expect(context->tensors[node->outputs->data[0]].type == kTfLiteFloat32, NNAPIValidationFailureType::kUnsupportedOutputType, "NNAPI only support float32 output.", &val_ctx); } break; case kTfLiteBuiltinMaximum: case kTfLiteBuiltinMinimum: { ExpectMaxOpVersion(version, 3, &val_ctx); ExpectMinAndroidSdkVersion(android_sdk_version, kMinSdkVersionForNNAPI12, &val_ctx); const auto input_type = context->tensors[node->inputs->data[0]].type; EXPECT_INPUT_TYPE_IN(input_type, kTfLiteFloat32, kTfLiteUInt8, kTfLiteInt8, kTfLiteInt32); const TfLiteTensor& operand0 = context->tensors[node->inputs->data[0]]; if (operand0.dims->size == 0) { Expect(operand0.allocation_type == kTfLiteMmapRo, NNAPIValidationFailureType::kUnsupportedInputType, "Scalar operand should be constant", &val_ctx); } const TfLiteTensor& operand1 = context->tensors[node->inputs->data[1]]; if (operand1.dims->size == 0) { Expect(operand1.allocation_type == kTfLiteMmapRo, NNAPIValidationFailureType::kUnsupportedInputType, "Scalar operand should be constant", &val_ctx); } } break; case kTfLiteBuiltinCast: { ExpectOpVersion(version, 1, &val_ctx); ExpectMinAndroidSdkVersion(android_sdk_version, kMinSdkVersionForNNAPI12, &val_ctx); const TfLiteType input_type = context->tensors[node->inputs->data[0]].type; EXPECT_INPUT_TYPE_IN(input_type, kTfLiteFloat32, kTfLiteInt32, kTfLiteUInt8); const TfLiteType output_type = context->tensors[node->outputs->data[0]].type; ExpectTypeIn(output_type, {kTfLiteFloat32, kTfLiteInt32, kTfLiteUInt8}, NNAPIValidationFailureType::kUnsupportedOutputType, "Output type should be one of kTfLiteFloat32, kTfLiteInt32, " "kTfLiteUInt8.", &val_ctx); } break; case kTfLiteBuiltinPrelu: { ExpectOpVersion(version, 1, &val_ctx); ExpectMinAndroidSdkVersion(android_sdk_version, kMinSdkVersionForNNAPI12, &val_ctx); ExpectIsFloatOrUint8Operator(context, node, &val_ctx); } break; case kTfLiteBuiltinTile: { ExpectOpVersion(version, 1, &val_ctx); ExpectMinAndroidSdkVersion(android_sdk_version, kMinSdkVersionForNNAPI12, &val_ctx); const auto input_type = context->tensors[node->inputs->data[0]].type; EXPECT_INPUT_TYPE_IN(input_type, kTfLiteFloat32, kTfLiteInt8, kTfLiteUInt8, kTfLiteInt32); const auto multipliers_type = context->tensors[node->inputs->data[1]].type; Expect(multipliers_type == kTfLiteInt32, NNAPIValidationFailureType::kUnsupportedInputType, "Multipliers should be Int32", &val_ctx); } break; case kTfLiteBuiltinLogicalOr: case kTfLiteBuiltinLogicalAnd: case kTfLiteBuiltinLogicalNot: { ExpectOpVersion(version, 1, &val_ctx); ExpectMinAndroidSdkVersion(android_sdk_version, kMinSdkVersionForNNAPI12, &val_ctx); const auto input_type = context->tensors[node->inputs->data[0]].type; Expect(input_type == kTfLiteBool, NNAPIValidationFailureType::kUnsupportedInputType, "Input should be bool", &val_ctx); } break; case kTfLiteBuiltinLess: case kTfLiteBuiltinLessEqual: case kTfLiteBuiltinGreater: case kTfLiteBuiltinGreaterEqual: case kTfLiteBuiltinEqual: case kTfLiteBuiltinNotEqual: { ExpectMaxOpVersion(version, 2, &val_ctx); ExpectMinAndroidSdkVersion(android_sdk_version, kMinSdkVersionForNNAPI11, &val_ctx); const auto input_type = context->tensors[node->inputs->data[0]].type; EXPECT_INPUT_TYPE_IN(input_type, kTfLiteFloat32, kTfLiteUInt8, kTfLiteInt8, kTfLiteBool, kTfLiteInt32); } break; case kTfLiteBuiltinNeg: { ExpectMaxOpVersion(version, 2, &val_ctx); ExpectMinAndroidSdkVersion(android_sdk_version, kMinSdkVersionForNNAPI11, &val_ctx); const auto input_type = context->tensors[node->inputs->data[0]].type; EXPECT_INPUT_TYPE_IN(input_type, kTfLiteFloat32, kTfLiteInt32); } break; case kTfLiteBuiltinTopkV2: { ExpectMaxOpVersion(version, 2, &val_ctx); ExpectMinAndroidSdkVersion(android_sdk_version, kMinSdkVersionForNNAPI12, &val_ctx); const auto& input_type = context->tensors[node->inputs->data[0]].type; EXPECT_INPUT_TYPE_IN(input_type, kTfLiteFloat32, kTfLiteInt32, kTfLiteUInt8, kTfLiteInt8); const auto& k_param = context->tensors[node->inputs->data[1]]; Expect(k_param.type == kTfLiteInt32 && k_param.allocation_type == kTfLiteMmapRo, NNAPIValidationFailureType::kUnsupportedInputType, "K param should be a constant of type Int32", &val_ctx); } break; case kTfLiteBuiltinSelect: { ExpectMaxOpVersion(version, 2, &val_ctx); ExpectMinAndroidSdkVersion(android_sdk_version, kMinSdkVersionForNNAPI11, &val_ctx); const auto value_type = context->tensors[node->inputs->data[1]].type; EXPECT_INPUT_TYPE_IN(value_type, kTfLiteFloat32, kTfLiteInt32, kTfLiteUInt8, kTfLiteInt8); TfLiteIntArray* condition_shape = context->tensors[node->inputs->data[0]].dims; TfLiteIntArray* input_shape = context->tensors[node->inputs->data[1]].dims; Expect(TfLiteIntArrayEqual(condition_shape, input_shape), NNAPIValidationFailureType::kUnsupportedOperandValue, "Condition and inputs tensors shuld have the same shape", &val_ctx); } break; case kTfLiteBuiltinGather: { ExpectOpVersion(version, 1, &val_ctx); ExpectMinAndroidSdkVersion(android_sdk_version, kMinSdkVersionForNNAPI12, &val_ctx); const auto input_type = context->tensors[node->inputs->data[0]].type; const auto& positions = context->tensors[node->inputs->data[1]]; EXPECT_INPUT_TYPE_IN(input_type, kTfLiteFloat32, kTfLiteFloat16, kTfLiteInt32, kTfLiteUInt8); ExpectTypeIn(positions.type, {kTfLiteFloat32, kTfLiteFloat16, kTfLiteInt32, kTfLiteUInt8}, NNAPIValidationFailureType::kUnsupportedInputType, "Positions type should be one of kTfLiteFloat32, " "kTfLiteFloat16, kTfLiteInt32, kTfLiteUInt8", &val_ctx); Expect(positions.dims->size != 0, NNAPIValidationFailureType::kUnsupportedOperandRank, "0-dimension args are not supported by NNAPI.", &val_ctx); } break; case kTfLiteBuiltinBidirectionalSequenceLstm: { ExpectOpVersion(version, 1, &val_ctx); ExpectMinAndroidSdkVersion(android_sdk_version, kMinSdkVersionForNNAPI12, &val_ctx); Expect(!IsHybridOperator(context, builtin_code, node), NNAPIValidationFailureType::kUnsupportedHybridOperator, "Hybrid version of this op is not supported by NN API.", &val_ctx); } break; case kTfLiteBuiltinExpandDims: { ExpectOpVersion(version, 1, &val_ctx); ExpectMinAndroidSdkVersion(android_sdk_version, kMinSdkVersionForNNAPI12, &val_ctx); const auto input_type = context->tensors[node->inputs->data[0]].type; EXPECT_INPUT_TYPE_IN(input_type, kTfLiteFloat32, kTfLiteFloat16, kTfLiteInt32, kTfLiteUInt8, kTfLiteInt8); const auto axis = context->tensors[node->inputs->data[1]]; Expect(axis.type == kTfLiteInt32 && axis.allocation_type == kTfLiteMmapRo, NNAPIValidationFailureType::kUnsupportedInputType, "NNAPI only supports constant int32 axis tensor.", &val_ctx); } break; case kTfLiteBuiltinSplit: { ExpectOpVersion(version, 3, &val_ctx); ExpectMinAndroidSdkVersion(android_sdk_version, kMinSdkVersionForNNAPI12, &val_ctx); // Tensor indices: split_dim: 0, value: 1 const TfLiteTensor& input = context->tensors[node->inputs->data[1]]; EXPECT_INPUT_TYPE_IN(input.type, kTfLiteFloat32, kTfLiteUInt8, kTfLiteInt32); const TfLiteTensor& axis = context->tensors[node->inputs->data[0]]; Expect(axis.type == kTfLiteInt32 && axis.allocation_type == kTfLiteMmapRo, NNAPIValidationFailureType::kUnsupportedInputType, "NNAPI only supports constant int32 axis tensor.", &val_ctx); } break; case kTfLiteBuiltinLogSoftmax: { ExpectOpVersion(version, 1, &val_ctx); ExpectMinAndroidSdkVersion(android_sdk_version, kMinSdkVersionForNNAPI12, &val_ctx); const auto input_type = context->tensors[node->inputs->data[0]].type; Expect(input_type == kTfLiteFloat32, NNAPIValidationFailureType::kUnsupportedInputType, "Input should be Float32.", &val_ctx); } break; case kTfLiteBuiltinQuantize: { ExpectOpVersion(version, 1, &val_ctx); ExpectMinAndroidSdkVersion(android_sdk_version, kMinSdkVersionForNNAPI12, &val_ctx); const auto value_type = context->tensors[node->inputs->data[0]].type; Expect(value_type == kTfLiteFloat32, NNAPIValidationFailureType::kUnsupportedInputType, "Value should be Float32.", &val_ctx); const auto output_type = context->tensors[node->outputs->data[0]].type; Expect(output_type == kTfLiteUInt8, NNAPIValidationFailureType::kUnsupportedOutputType, "Output should be kTfLiteUInt8.", &val_ctx); const auto quantization_params = context->tensors[node->outputs->data[0]].params; Expect(quantization_params.scale > 0.f, NNAPIValidationFailureType::kUnsupportedQuantizationParameters, "Quantization scale should be > 0.", &val_ctx); } break; case kTfLiteBuiltinReduceAny: case kTfLiteBuiltinReduceMin: case kTfLiteBuiltinReduceMax: { ExpectOpVersion(version, 1, &val_ctx); ExpectMinAndroidSdkVersion(android_sdk_version, kMinSdkVersionForNNAPI12, &val_ctx); Expect(context->tensors[node->outputs->data[0]].dims->size != 0, NNAPIValidationFailureType::kUnsupportedOutputType, "NNAPI does not support generating a scalar as output.", &val_ctx); if (builtin_code == kTfLiteBuiltinReduceProd) { const auto input_type = context->tensors[node->inputs->data[0]].type; Expect(input_type == kTfLiteFloat32, NNAPIValidationFailureType::kUnsupportedInputType, "NNAPI only supports floating point REDUCE_PROD.", &val_ctx); } } break; case kTfLiteBuiltinDepthToSpace: { const TfLiteType input_type = context->tensors[node->inputs->data[0]].type; // EXPECT_INPUT_TYPE_IN(input_type, kTfLiteFloat32, kTfLiteUInt8, // kTfLiteInt8); if (version <= 1 && (input_type == kTfLiteFloat32 || input_type == kTfLiteUInt8 || input_type == kTfLiteInt8)) { val_ctx.is_valid = true; } } break; case kTfLiteBuiltinReduceProd: case kTfLiteBuiltinSum: { ExpectOpVersion(version, 1, &val_ctx); ExpectMinAndroidSdkVersion(android_sdk_version, kMinSdkVersionForNNAPI12, &val_ctx); Expect(context->tensors[node->outputs->data[0]].dims->size != 0, NNAPIValidationFailureType::kUnsupportedOutputType, "NNAPI does not support generating a scalar as output", &val_ctx); const auto input_type = context->tensors[node->inputs->data[0]].type; Expect(input_type == kTfLiteFloat32, NNAPIValidationFailureType::kUnsupportedInputType, "NNAPI only supports floating point input.", &val_ctx); } break; case kTfLiteBuiltinElu: { ExpectOpVersion(version, 1, &val_ctx); ExpectMinAndroidSdkVersion(android_sdk_version, kMinSdkVersionForNNAPI13, &val_ctx); } break; case kTfLiteBuiltinFill: { ExpectOpVersion(version, 1, &val_ctx); ExpectMinAndroidSdkVersion(android_sdk_version, kMinSdkVersionForNNAPI13, &val_ctx); const auto& dims_tensor = context->tensors[node->inputs->data[0]]; Expect(IsConstantTensor(&dims_tensor), NNAPIValidationFailureType::kUnsupportedInputType, "NNAPI doesn't support dynamic dimensions tensor.", &val_ctx); EXPECT_INPUT_TYPE_IN(dims_tensor.type, kTfLiteInt32, kTfLiteInt64); if (IsConstantTensor(&dims_tensor)) { Expect(dims_tensor.dims->data[0] != 0, NNAPIValidationFailureType::kUnsupportedOperandValue, "NNAPI doesn't support generating scalars from FILL", &val_ctx); if (dims_tensor.type == kTfLiteInt64) { bool fit_in_int32 = std::all_of(dims_tensor.data.i64, dims_tensor.data.i64 + dims_tensor.dims->data[0], [](int64_t dim) { return std::numeric_limits<int32_t>::min() <= dim && dim <= std::numeric_limits<int32_t>::max(); }); Expect(fit_in_int32, NNAPIValidationFailureType::kUnsupportedOperandValue, "NNAPI only supports int32 dimensions tensor. If the " "dimensions type is int64 and they are constant we can " "convert them to int32 if the value isn't too large.", &val_ctx); } } const auto& value_tensor = context->tensors[node->inputs->data[1]]; EXPECT_INPUT_TYPE_IN(value_tensor.type, kTfLiteFloat32, kTfLiteInt32, kTfLiteInt64); if (value_tensor.type == kTfLiteInt64) { Expect( IsConstantTensor(&value_tensor) && *value_tensor.data.i64 <= std::numeric_limits<int32_t>::max() && *value_tensor.data.i64 >= std::numeric_limits<int32_t>::min(), NNAPIValidationFailureType::kUnsupportedInputType, "NNAPI only supports int32 input. If the input type is int64 and " "constant we can convert it to int32 if the value isn't too " "large.", &val_ctx); } } break; default: // All other operators are not mapped. AddValidationFailure(NNAPIValidationFailureType::kUnsupportedOperator, "Unsupported operation type.", &val_ctx); } return val_ctx.is_valid; } // NOLINT(readability/fn_size) TfLiteStatus NNAPIDelegateKernel::Map( TfLiteContext* context, int builtin_code, int version, int android_sdk_version, const NNAPIOpMappingArgs& mapping_args, ANeuralNetworksOperationType* nn_op_type) { switch (builtin_code) { case kTfLiteBuiltinAdd: { auto builtin = reinterpret_cast<TfLiteAddParams*>(mapping_args.node->builtin_data); mapping_args.builder->AddScalarInt32Operand(builtin->activation); *nn_op_type = ANEURALNETWORKS_ADD; } break; case kTfLiteBuiltinArgMax: { *nn_op_type = ANEURALNETWORKS_ARGMAX; } break; case kTfLiteBuiltinArgMin: { *nn_op_type = ANEURALNETWORKS_ARGMIN; } break; case kTfLiteBuiltinMul: { auto builtin = reinterpret_cast<TfLiteMulParams*>(mapping_args.node->builtin_data); mapping_args.builder->AddScalarInt32Operand(builtin->activation); *nn_op_type = ANEURALNETWORKS_MUL; } break; case kTfLiteBuiltinAveragePool2d: { mapping_args.builder->AddPoolingParams(mapping_args.node->builtin_data); *nn_op_type = ANEURALNETWORKS_AVERAGE_POOL_2D; } break; case kTfLiteBuiltinMaxPool2d: { mapping_args.builder->AddPoolingParams(mapping_args.node->builtin_data); *nn_op_type = ANEURALNETWORKS_MAX_POOL_2D; } break; case kTfLiteBuiltinL2Pool2d: { mapping_args.builder->AddPoolingParams(mapping_args.node->builtin_data); *nn_op_type = ANEURALNETWORKS_L2_POOL_2D; } break; case kTfLiteBuiltinConv2d: { auto builtin = reinterpret_cast<TfLiteConvParams*>(mapping_args.node->builtin_data); mapping_args.builder->AddScalarInt32Operand(builtin->padding); mapping_args.builder->AddScalarInt32Operand(builtin->stride_width); mapping_args.builder->AddScalarInt32Operand(builtin->stride_height); mapping_args.builder->AddScalarInt32Operand(builtin->activation); // NNAPI supports dilated Conv2D since NNAPI 1.2. if (builtin->dilation_width_factor != 1 || builtin->dilation_height_factor != 1) { mapping_args.builder->AddScalarBoolOperand(false); // Use NHWC format mapping_args.builder->AddScalarInt32Operand( builtin->dilation_width_factor); mapping_args.builder->AddScalarInt32Operand( builtin->dilation_height_factor); } *nn_op_type = ANEURALNETWORKS_CONV_2D; } break; case kTfLiteBuiltinDepthwiseConv2d: { auto builtin = reinterpret_cast<TfLiteDepthwiseConvParams*>( mapping_args.node->builtin_data); mapping_args.builder->AddScalarInt32Operand(builtin->padding); mapping_args.builder->AddScalarInt32Operand(builtin->stride_width); mapping_args.builder->AddScalarInt32Operand(builtin->stride_height); mapping_args.builder->AddScalarInt32Operand(builtin->depth_multiplier); mapping_args.builder->AddScalarInt32Operand(builtin->activation); if (builtin->dilation_width_factor != 1 || builtin->dilation_height_factor != 1) { mapping_args.builder->AddScalarBoolOperand(false); // Use NHWC format. mapping_args.builder->AddScalarInt32Operand( builtin->dilation_width_factor); mapping_args.builder->AddScalarInt32Operand( builtin->dilation_height_factor); } *nn_op_type = ANEURALNETWORKS_DEPTHWISE_CONV_2D; } break; case kTfLiteBuiltinFullyConnected: { auto builtin = reinterpret_cast<TfLiteFullyConnectedParams*>( mapping_args.node->builtin_data); mapping_args.builder->AddScalarInt32Operand(builtin->activation); *nn_op_type = ANEURALNETWORKS_FULLY_CONNECTED; } break; case kTfLiteBuiltinHardSwish: { *nn_op_type = ANEURALNETWORKS_HARD_SWISH; } break; case kTfLiteBuiltinSoftmax: { auto builtin = reinterpret_cast<TfLiteSoftmaxParams*>( mapping_args.node->builtin_data); mapping_args.builder->AddScalarFloat32Operand(builtin->beta); // Optional scalar specifying the dimension the activation would be // performed on is not added. Default to -1. *nn_op_type = ANEURALNETWORKS_SOFTMAX; } break; case kTfLiteBuiltinReshape: { *nn_op_type = ANEURALNETWORKS_RESHAPE; } break; case kTfLiteBuiltinResizeBilinear: { const int output_id = mapping_args.node->outputs->data[0]; auto& output = mapping_args.context->tensors[output_id]; const int output_height = output.dims->data[1]; const int output_width = output.dims->data[2]; mapping_args.builder->AddScalarInt32Operand(output_width); mapping_args.builder->AddScalarInt32Operand(output_height); auto builtin = reinterpret_cast<TfLiteResizeBilinearParams*>( mapping_args.node->builtin_data); if (builtin->align_corners == true || builtin->half_pixel_centers == true) { mapping_args.builder->AddScalarBoolOperand(false); // Use NHWC format mapping_args.builder->AddScalarBoolOperand(builtin->align_corners); mapping_args.builder->AddScalarBoolOperand(builtin->half_pixel_centers); } *nn_op_type = ANEURALNETWORKS_RESIZE_BILINEAR; } break; case kTfLiteBuiltinResizeNearestNeighbor: { const TfLiteTensor& new_shape = mapping_args.context->tensors[mapping_args.node->inputs->data[1]]; // NNAPI uses scalar inputs for height and width. mapping_args.builder->AddScalarInt32Operand(new_shape.data.i32[1]); mapping_args.builder->AddScalarInt32Operand(new_shape.data.i32[0]); mapping_args.builder->AddScalarBoolOperand(false); // Use NHWC format auto builtin = reinterpret_cast<TfLiteResizeNearestNeighborParams*>( mapping_args.node->builtin_data); if (builtin->align_corners == true || builtin->half_pixel_centers == true) { mapping_args.builder->AddScalarBoolOperand(builtin->align_corners); mapping_args.builder->AddScalarBoolOperand(builtin->half_pixel_centers); } *nn_op_type = ANEURALNETWORKS_RESIZE_NEAREST_NEIGHBOR; } break; case kTfLiteBuiltinSqueeze: { auto builtin = reinterpret_cast<TfLiteSqueezeParams*>( mapping_args.node->builtin_data); // Note that we add the squeeze dimensions even if the dimensions // were unspecified (empty), as NNAPI requires the operand. mapping_args.builder->AddVectorInt32Operand( builtin->num_squeeze_dims ? builtin->squeeze_dims : nullptr, static_cast<uint32_t>(builtin->num_squeeze_dims)); *nn_op_type = ANEURALNETWORKS_SQUEEZE; } break; case kTfLiteBuiltinUnidirectionalSequenceLstm: { auto builtin = reinterpret_cast<TfLiteUnidirectionalSequenceLSTMParams*>( mapping_args.node->builtin_data); mapping_args.builder->AddScalarInt32Operand(builtin->activation); mapping_args.builder->AddScalarFloat32Operand(builtin->cell_clip); mapping_args.builder->AddScalarFloat32Operand(builtin->proj_clip); mapping_args.builder->AddScalarBoolOperand(builtin->time_major); const bool hybrid_op = IsHybridOperator( mapping_args.context, kTfLiteBuiltinUnidirectionalSequenceLstm, mapping_args.node); if (mapping_args.node->inputs->size == 24) { // Add layer normalization tensors if they are provided. for (int i = 20; i < 24; ++i) { const int input_index = mapping_args.node->inputs->data[i]; if (input_index != kTfLiteOptionalTensor) { mapping_args.builder->AddTensorInput(input_index, hybrid_op); } else { mapping_args.builder->AddVectorFloat32Operand(nullptr, 0); } } } else { for (int i = 0; i < 4; ++i) { mapping_args.builder->AddVectorFloat32Operand(nullptr, 0); } } *nn_op_type = ANEURALNETWORKS_UNIDIRECTIONAL_SEQUENCE_LSTM; } break; case kTfLiteBuiltinL2Normalization: { *nn_op_type = ANEURALNETWORKS_L2_NORMALIZATION; } break; case kTfLiteBuiltinLocalResponseNormalization: { auto builtin = reinterpret_cast<TfLiteLocalResponseNormParams*>( mapping_args.node->builtin_data); mapping_args.builder->AddScalarInt32Operand(builtin->radius); mapping_args.builder->AddScalarFloat32Operand(builtin->bias); mapping_args.builder->AddScalarFloat32Operand(builtin->alpha); mapping_args.builder->AddScalarFloat32Operand(builtin->beta); *nn_op_type = ANEURALNETWORKS_LOCAL_RESPONSE_NORMALIZATION; } break; case kTfLiteBuiltinLshProjection: { auto builtin = reinterpret_cast<TfLiteLSHProjectionParams*>( mapping_args.node->builtin_data); int type = builtin->type; // In Android Q+, NNAPI uses 3 to denote // kTfLiteLshProjectionSparse. const int kNNAPILshProjectionSparse = 3; if (builtin->type == kTfLiteLshProjectionSparse) { type = kNNAPILshProjectionSparse; // Add NNAPI null weight operand. mapping_args.builder->AddVectorFloat32Operand(nullptr, 0); } mapping_args.builder->AddScalarInt32Operand(type); *nn_op_type = ANEURALNETWORKS_LSH_PROJECTION; } break; case kTfLiteBuiltinConcatenation: { auto builtin = reinterpret_cast<TfLiteConcatenationParams*>( mapping_args.node->builtin_data); int axis = builtin->axis < 0 ? mapping_args.context ->tensors[mapping_args.node->inputs->data[0]] .dims->size + builtin->axis : builtin->axis; mapping_args.builder->AddScalarInt32Operand(axis); *nn_op_type = ANEURALNETWORKS_CONCATENATION; } break; case kTfLiteBuiltinDequantize: { *nn_op_type = ANEURALNETWORKS_DEQUANTIZE; } break; case kTfLiteBuiltinFloor: { *nn_op_type = ANEURALNETWORKS_FLOOR; } break; case kTfLiteBuiltinRelu: { *nn_op_type = ANEURALNETWORKS_RELU; } break; case kTfLiteBuiltinReluN1To1: { *nn_op_type = ANEURALNETWORKS_RELU1; } break; case kTfLiteBuiltinRelu6: { *nn_op_type = ANEURALNETWORKS_RELU6; } break; case kTfLiteBuiltinLogistic: { *nn_op_type = ANEURALNETWORKS_LOGISTIC; } break; case kTfLiteBuiltinTanh: { *nn_op_type = ANEURALNETWORKS_TANH; } break; case kTfLiteBuiltinSub: { auto builtin = reinterpret_cast<TfLiteSubParams*>(mapping_args.node->builtin_data); mapping_args.builder->AddScalarInt32Operand(builtin->activation); *nn_op_type = ANEURALNETWORKS_SUB; } break; case kTfLiteBuiltinDiv: { auto builtin = reinterpret_cast<TfLiteDivParams*>(mapping_args.node->builtin_data); mapping_args.builder->AddScalarInt32Operand(builtin->activation); *nn_op_type = ANEURALNETWORKS_DIV; } break; case kTfLiteBuiltinPad: case kTfLiteBuiltinPadv2: { // We want to map to PAD as much as possible since it is more widely // supported. We map to PadV2 only when there is the need to specify // the padding value if (mapping_args.node->inputs->size == 2) { *nn_op_type = ANEURALNETWORKS_PAD; } else { const int constant_value_id = mapping_args.node->inputs->data[2]; if (constant_value_id == kTfLiteOptionalTensor) { *nn_op_type = ANEURALNETWORKS_PAD; } else { *nn_op_type = ANEURALNETWORKS_PAD_V2; } } } break; case kTfLiteBuiltinUnidirectionalSequenceRnn: { auto builtin = reinterpret_cast<TfLiteSequenceRNNParams*>( mapping_args.node->builtin_data); mapping_args.builder->AddScalarInt32Operand(builtin->activation); mapping_args.builder->AddScalarInt32Operand(builtin->time_major); *nn_op_type = ANEURALNETWORKS_UNIDIRECTIONAL_SEQUENCE_RNN; } break; case kTfLiteBuiltinSpaceToBatchNd: { *nn_op_type = ANEURALNETWORKS_SPACE_TO_BATCH_ND; } break; case kTfLiteBuiltinBatchToSpaceNd: { *nn_op_type = ANEURALNETWORKS_BATCH_TO_SPACE_ND; } break; case kTfLiteBuiltinStridedSlice: { auto builtin = reinterpret_cast<TfLiteStridedSliceParams*>( mapping_args.node->builtin_data); mapping_args.builder->AddScalarInt32Operand(builtin->begin_mask); mapping_args.builder->AddScalarInt32Operand(builtin->end_mask); mapping_args.builder->AddScalarInt32Operand(builtin->shrink_axis_mask); *nn_op_type = ANEURALNETWORKS_STRIDED_SLICE; } break; case kTfLiteBuiltinTranspose: { *nn_op_type = ANEURALNETWORKS_TRANSPOSE; } break; case kTfLiteBuiltinAbs: { *nn_op_type = ANEURALNETWORKS_ABS; } break; case kTfLiteBuiltinExp: { *nn_op_type = ANEURALNETWORKS_EXP; } break; case kTfLiteBuiltinLog: { *nn_op_type = ANEURALNETWORKS_LOG; } break; case kTfLiteBuiltinRsqrt: { *nn_op_type = ANEURALNETWORKS_RSQRT; } break; case kTfLiteBuiltinPow: { *nn_op_type = ANEURALNETWORKS_POW; } break; case kTfLiteBuiltinSlice: { *nn_op_type = ANEURALNETWORKS_SLICE; } break; case kTfLiteBuiltinSin: { *nn_op_type = ANEURALNETWORKS_SIN; } break; case kTfLiteBuiltinTransposeConv: { const bool hybrid_op = IsHybridOperator( mapping_args.context, kTfLiteBuiltinTransposeConv, mapping_args.node); int input_tensor_flags = 0; const int input_tensor_id = mapping_args.node->inputs->data[/*kDataInputTensor*/ 2]; const int weight_tensor_id = mapping_args.node->inputs->data[/*kWeightsTensor*/ 1]; if (context->tensors[input_tensor_id].type == kTfLiteInt8) { const auto& weights_tensor = context->tensors[weight_tensor_id]; if ((weights_tensor.type == kTfLiteInt8 || weights_tensor.type == kTfLiteUInt8) && weights_tensor.quantization.type == kTfLiteAffineQuantization) { input_tensor_flags |= NN_TENSOR_FLAG_SCALAR_AS_TENSOR; } } mapping_args.builder->AddTensorInput(input_tensor_id, hybrid_op, input_tensor_flags); mapping_args.builder->AddTensorInput(weight_tensor_id, hybrid_op, input_tensor_flags); // NNAPI requires a bias tensor, so we allocate a new tensor to fill // it with zeroes. It is deleted with other tensors in the context // during subgraph destructor call. int bias_index = -1; mapping_args.context->AddTensors(mapping_args.context, 1, &bias_index); TfLiteTensor* bias_tensor = &mapping_args.context->tensors[bias_index]; const auto input_type = mapping_args.context ->tensors[mapping_args.node->inputs->data[/*kDataInputTensor*/ 2]] .type; if (input_type == kTfLiteFloat32) { bias_tensor->type = kTfLiteFloat32; } else { bias_tensor->type = kTfLiteInt32; } // Create an array with a required bias shape and resize the bias // tensor. TfLiteIntArray* bias_shape = TfLiteIntArrayCreate(1); const TfLiteTensor& output_shape = mapping_args.context->tensors[mapping_args.node->inputs ->data[/*kOutputShapeTensor*/ 0]]; const int output_depth = output_shape.data.i32[3]; bias_shape->data[0] = output_depth; bias_tensor->allocation_type = kTfLiteDynamic; mapping_args.context->ResizeTensor(mapping_args.context, bias_tensor, bias_shape); // Set tensor's values to zeroes and add it using AddVector*, so // that the values are copied to NNAPI. We don't use the AddTensor // function because it doesn't copy values and the tensor we just // created is not in the node->inputs. if (input_type == kTfLiteFloat32) { memset(bias_tensor->data.f, 0, output_depth * sizeof(float)); mapping_args.builder->AddVectorFloat32Operand(bias_tensor->data.f, output_depth); } else { memset(bias_tensor->data.i32, 0, output_depth * sizeof(int)); const TfLiteTensor& input_tensor = mapping_args.context->tensors[mapping_args.node->inputs ->data[/*kDataInputTensor*/ 2]]; const TfLiteTensor& filter_tensor = mapping_args.context->tensors[mapping_args.node->inputs ->data[/*kWeightsTensor*/ 1]]; // NNAPI requires bias scale to be a product of an input scale and // a filter scale. bias_tensor->params.scale = input_tensor.params.scale * filter_tensor.params.scale; mapping_args.builder->AddVectorInt32Operand( bias_tensor->data.i32, output_depth, input_tensor.params.scale * filter_tensor.params.scale, /*zero_point=*/0); } mapping_args.builder->AddTensorInput( mapping_args.node->inputs->data[/*kOutputShapeTensor*/ 0], hybrid_op); auto builtin = reinterpret_cast<TfLiteTransposeConvParams*>( mapping_args.node->builtin_data); mapping_args.builder->AddScalarInt32Operand(builtin->padding); mapping_args.builder->AddScalarInt32Operand(builtin->stride_width); mapping_args.builder->AddScalarInt32Operand(builtin->stride_height); mapping_args.builder->AddScalarInt32Operand( /*ANEURALNETWORKS_FUSED_NONE*/ 0); // Use NHWC layout for input and output. mapping_args.builder->AddScalarBoolOperand(false); *nn_op_type = ANEURALNETWORKS_TRANSPOSE_CONV; } break; case kTfLiteBuiltinSqrt: { *nn_op_type = ANEURALNETWORKS_SQRT; } break; case kTfLiteBuiltinRnn: { // NNAPI need both state_in and state_out. int ann_index; mapping_args.builder->AddStateFloat32Tensor( mapping_args.node->inputs->data[/*kHiddenStateTensor*/ 4], &ann_index); mapping_args.model_state_outputs->push_back(ann_index); mapping_args.model_state_tfl_inputs->push_back( mapping_args.node->inputs->data[/*kHiddenStateTensor*/ 4]); auto builtin = reinterpret_cast<TfLiteRNNParams*>(mapping_args.node->builtin_data); mapping_args.builder->AddScalarInt32Operand(builtin->activation); *nn_op_type = ANEURALNETWORKS_RNN; } break; case kTfLiteBuiltinSpaceToDepth: { auto builtin = reinterpret_cast<TfLiteSpaceToDepthParams*>( mapping_args.node->builtin_data); mapping_args.builder->AddScalarInt32Operand(builtin->block_size); *nn_op_type = ANEURALNETWORKS_SPACE_TO_DEPTH; } break; case kTfLiteBuiltinSvdf: { // NNAPI need both state_in and state_out. int ann_index; mapping_args.builder->AddStateFloat32Tensor( mapping_args.node->inputs->data[/*kInputActivationStateTensor*/ 4], &ann_index); mapping_args.model_state_outputs->push_back(ann_index); mapping_args.model_state_tfl_inputs->push_back( mapping_args.node->inputs->data[/*kInputActivationStateTensor*/ 4]); auto builtin = reinterpret_cast<TfLiteSVDFParams*>(mapping_args.node->builtin_data); mapping_args.builder->AddScalarInt32Operand(builtin->rank); mapping_args.builder->AddScalarInt32Operand(builtin->activation); *nn_op_type = ANEURALNETWORKS_SVDF; } break; case kTfLiteBuiltinLstm: { if (isLstmBasicKernel(mapping_args.node)) { const auto output_dims = mapping_args.context->tensors[mapping_args.node->outputs->data[1]] .dims; // Inputs kInputData mapping_args.builder->AddTensorInput( mapping_args.node->inputs->data[0 /* kInputData */], /* hybrid_op */ false, /* scalar_as_tensor */ false); // The 8 weights tensors are set decomposing the // kInputWeights param const auto weight_tensor = mapping_args.context->tensors[mapping_args.node->inputs ->data[2 /* kInputWeights */]]; std::vector<uint8_t> recurrent_to_input; std::vector<uint8_t> input_to_input; std::vector<uint8_t> recurrent_to_cell; std::vector<uint8_t> input_to_cell; std::vector<uint8_t> recurrent_to_forget; std::vector<uint8_t> input_to_forget; std::vector<uint8_t> recurrent_to_output; std::vector<uint8_t> input_to_output; tflite::delegate::nnapi::DecomposeQuantLstmWeightsTensor( weight_tensor.data.uint8, weight_tensor.dims, &recurrent_to_input, &input_to_input, &recurrent_to_cell, &input_to_cell, &recurrent_to_forget, &input_to_forget, &recurrent_to_output, &input_to_output); TfLiteIntArray* recurrent_weight_dims = TfLiteIntArrayCreate(2); TfLiteIntArray* input_weight_dims = TfLiteIntArrayCreate(2); tflite::delegate::nnapi::SetWeightSubmatrixDims( weight_tensor.dims, recurrent_weight_dims, input_weight_dims); int new_tensor_index = -1; mapping_args.builder->AddNewInputConstantTensor<uint8_t>( ANEURALNETWORKS_TENSOR_QUANT8_ASYMM, kTfLiteUInt8, input_weight_dims, input_to_input, weight_tensor.params, &new_tensor_index); mapping_args.builder->AddNewInputConstantTensor<uint8_t>( ANEURALNETWORKS_TENSOR_QUANT8_ASYMM, kTfLiteUInt8, input_weight_dims, input_to_forget, weight_tensor.params, &new_tensor_index); mapping_args.builder->AddNewInputConstantTensor<uint8_t>( ANEURALNETWORKS_TENSOR_QUANT8_ASYMM, kTfLiteUInt8, input_weight_dims, input_to_cell, weight_tensor.params, &new_tensor_index); mapping_args.builder->AddNewInputConstantTensor<uint8_t>( ANEURALNETWORKS_TENSOR_QUANT8_ASYMM, kTfLiteUInt8, input_weight_dims, input_to_output, weight_tensor.params, &new_tensor_index); mapping_args.builder->AddNewInputConstantTensor<uint8_t>( ANEURALNETWORKS_TENSOR_QUANT8_ASYMM, kTfLiteUInt8, recurrent_weight_dims, recurrent_to_input, weight_tensor.params, &new_tensor_index); mapping_args.builder->AddNewInputConstantTensor<uint8_t>( ANEURALNETWORKS_TENSOR_QUANT8_ASYMM, kTfLiteUInt8, recurrent_weight_dims, recurrent_to_forget, weight_tensor.params, &new_tensor_index); mapping_args.builder->AddNewInputConstantTensor<uint8_t>( ANEURALNETWORKS_TENSOR_QUANT8_ASYMM, kTfLiteUInt8, recurrent_weight_dims, recurrent_to_cell, weight_tensor.params, &new_tensor_index); mapping_args.builder->AddNewInputConstantTensor<uint8_t>( ANEURALNETWORKS_TENSOR_QUANT8_ASYMM, kTfLiteUInt8, recurrent_weight_dims, recurrent_to_output, weight_tensor.params, &new_tensor_index); TfLiteIntArrayFree(input_weight_dims); TfLiteIntArrayFree(recurrent_weight_dims); // Biases have to be split in four. const auto bias_size = output_dims->data[1]; const TfLiteTensor& biases_tensor = mapping_args.context->tensors[mapping_args.node->inputs ->data[3 /* kInputBiases */]]; std::vector<int32_t> input_bias; std::vector<int32_t> cell_bias; std::vector<int32_t> forget_bias; std::vector<int32_t> output_bias; delegate::nnapi::DecomposeBiasTensor(biases_tensor.data.i32, bias_size, &input_bias, &cell_bias, &forget_bias, &output_bias); int input_bias_tensor = -1; mapping_args.builder->AddNewInputConstantTensor<int32_t>( ANEURALNETWORKS_TENSOR_INT32, kTfLiteInt32, {bias_size}, input_bias, biases_tensor.params, &input_bias_tensor); int forget_bias_tensor = -1; mapping_args.builder->AddNewInputConstantTensor( ANEURALNETWORKS_TENSOR_INT32, kTfLiteInt32, {bias_size}, forget_bias, biases_tensor.params, &forget_bias_tensor); int cell_gate_bias_tensor = -1; mapping_args.builder->AddNewInputConstantTensor( ANEURALNETWORKS_TENSOR_INT32, kTfLiteInt32, {bias_size}, cell_bias, biases_tensor.params, &cell_gate_bias_tensor); int output_gate_bias_tensor = -1; mapping_args.builder->AddNewInputConstantTensor( ANEURALNETWORKS_TENSOR_INT32, kTfLiteInt32, {bias_size}, output_bias, biases_tensor.params, &output_gate_bias_tensor); mapping_args.builder->AddTensorInput( mapping_args.node->inputs->data[4 /* kInputPrevState */], /* hybrid_op */ false, /* scalar_as_tensor */ false); // kInputPrevActivation mapping_args.builder->AddTensorInput( mapping_args.node->inputs->data[1 /* kInputPrevActivation */], /* hybrid_op */ false, /* scalar_as_tensor */ false); // Configuring the copy from the activation, state outputs // to their associated inputs mapping_args.feedback_loops->push_back(std::make_tuple( mapping_args.node->outputs->data[0 /*kOutputActivation*/], mapping_args.node->inputs->data[1 /*kInputPrevActivation*/])); mapping_args.feedback_loops->push_back(std::make_tuple( mapping_args.node->outputs->data[1 /*kOutputState*/], mapping_args.node->inputs->data[4 /*kInputPrevState*/])); // OUTPUTS // Setting only the first two since the remaining ones are // ignored by NNAPI mapping_args.builder->AddTensorOutput( mapping_args.node->outputs->data[1 /* kOutputState */], 0); mapping_args.builder->AddTensorOutput( mapping_args.node->outputs->data[0 /* kOutputActivation */], 0); *nn_op_type = ANEURALNETWORKS_QUANTIZED_16BIT_LSTM; } else { auto builtin = reinterpret_cast<TfLiteLSTMParams*>( mapping_args.node->builtin_data); mapping_args.builder->AddScalarInt32Operand(builtin->activation); mapping_args.builder->AddScalarFloat32Operand(builtin->cell_clip); mapping_args.builder->AddScalarFloat32Operand(builtin->proj_clip); // Current NNAPI implementation requires the scratch_buffer as // output. mapping_args.builder->AddAdditionalFloat32OutputTensor(2); // NNAPI need both state_in and state_out for cell_state and // output_state. int ann_index; mapping_args.builder->AddStateFloat32Tensor( mapping_args.node->inputs->data[/*kInputActivationStateTensor*/ 18], &ann_index); mapping_args.model_state_outputs->push_back(ann_index); mapping_args.model_state_tfl_inputs->push_back( mapping_args.node->inputs ->data[/*kInputActivationStateTensor*/ 18]); mapping_args.builder->AddStateFloat32Tensor( mapping_args.node->inputs->data[/*kInputCellStateTensor*/ 19], &ann_index); mapping_args.model_state_outputs->push_back(ann_index); mapping_args.model_state_tfl_inputs->push_back( mapping_args.node->inputs->data[/*kInputCellStateTensor*/ 19]); const bool hybrid_op = IsHybridOperator( mapping_args.context, kTfLiteBuiltinLstm, mapping_args.node); if (mapping_args.node->inputs->size == 24) { for (int i = 20; i < 24; ++i) { const auto input_index = mapping_args.node->inputs->data[i]; if (input_index != kTfLiteOptionalTensor) { mapping_args.builder->AddTensorInput(input_index, hybrid_op); } else { mapping_args.builder->AddVectorFloat32Operand(nullptr, 0); } } } *nn_op_type = ANEURALNETWORKS_LSTM; } } break; case kTfLiteBuiltinMean: { auto builtin = reinterpret_cast<TfLiteReducerParams*>( mapping_args.node->builtin_data); int32_t keep_dims = 0; if (builtin->keep_dims) keep_dims = 1; mapping_args.builder->AddScalarInt32Operand(keep_dims); *nn_op_type = ANEURALNETWORKS_MEAN; } break; case kTfLiteBuiltinEmbeddingLookup: { *nn_op_type = ANEURALNETWORKS_EMBEDDING_LOOKUP; } break; case kTfLiteBuiltinHashtableLookup: { *nn_op_type = ANEURALNETWORKS_HASHTABLE_LOOKUP; } break; case kTfLiteBuiltinMaximum: { *nn_op_type = ANEURALNETWORKS_MAXIMUM; } break; case kTfLiteBuiltinMinimum: { *nn_op_type = ANEURALNETWORKS_MINIMUM; } break; case kTfLiteBuiltinCast: { *nn_op_type = ANEURALNETWORKS_CAST; } break; case kTfLiteBuiltinPrelu: { *nn_op_type = ANEURALNETWORKS_PRELU; } break; case kTfLiteBuiltinTile: { *nn_op_type = ANEURALNETWORKS_TILE; } break; case kTfLiteBuiltinLogicalOr: { *nn_op_type = ANEURALNETWORKS_LOGICAL_OR; } break; case kTfLiteBuiltinLogicalAnd: { *nn_op_type = ANEURALNETWORKS_LOGICAL_AND; } break; case kTfLiteBuiltinLogicalNot: { *nn_op_type = ANEURALNETWORKS_LOGICAL_NOT; } break; case kTfLiteBuiltinLess: { *nn_op_type = ANEURALNETWORKS_LESS; } break; case kTfLiteBuiltinLessEqual: { *nn_op_type = ANEURALNETWORKS_LESS_EQUAL; } break; case kTfLiteBuiltinGreater: { *nn_op_type = ANEURALNETWORKS_GREATER; } break; case kTfLiteBuiltinGreaterEqual: { *nn_op_type = ANEURALNETWORKS_GREATER_EQUAL; } break; case kTfLiteBuiltinEqual: { *nn_op_type = ANEURALNETWORKS_EQUAL; } break; case kTfLiteBuiltinNotEqual: { *nn_op_type = ANEURALNETWORKS_NOT_EQUAL; } break; case kTfLiteBuiltinNeg: { *nn_op_type = ANEURALNETWORKS_NEG; } break; case kTfLiteBuiltinTopkV2: { const TfLiteTensor& k_param = mapping_args.context->tensors[mapping_args.node->inputs->data[1]]; mapping_args.builder->AddScalarInt32Operand(*k_param.data.i32); *nn_op_type = ANEURALNETWORKS_TOPK_V2; } break; case kTfLiteBuiltinSelect: { *nn_op_type = ANEURALNETWORKS_SELECT; } break; case kTfLiteBuiltinGather: { auto builtin = reinterpret_cast<TfLiteGatherParams*>( mapping_args.node->builtin_data); mapping_args.builder->AddTensorInput(mapping_args.node->inputs->data[0], /* hybrid_op */ false, /* scalar_as_tensor */ false); mapping_args.builder->AddScalarInt32Operand(builtin->axis); mapping_args.builder->AddTensorInput(mapping_args.node->inputs->data[1], /* hybrid_op */ false, /* scalar_as_tensor */ false); *nn_op_type = ANEURALNETWORKS_GATHER; } break; case kTfLiteBuiltinBidirectionalSequenceLstm: { auto builtin = reinterpret_cast<TfLiteBidirectionalSequenceLSTMParams*>( mapping_args.node->builtin_data); mapping_args.builder->AddScalarInt32Operand(builtin->activation); mapping_args.builder->AddScalarFloat32Operand(builtin->cell_clip); mapping_args.builder->AddScalarFloat32Operand(builtin->proj_clip); mapping_args.builder->AddScalarBoolOperand(builtin->merge_outputs); mapping_args.builder->AddScalarBoolOperand(builtin->time_major); // TF Lite doesn't support layer normalization in bidirectional // sequence LSTM, so we insert optional tensors for NNAPI. for (int i = 0; i < 8; ++i) { mapping_args.builder->AddVectorFloat32Operand(nullptr, 0); } *nn_op_type = ANEURALNETWORKS_BIDIRECTIONAL_SEQUENCE_LSTM; } break; case kTfLiteBuiltinExpandDims: { const TfLiteTensor& axis_param = mapping_args.context->tensors[mapping_args.node->inputs->data[1]]; mapping_args.builder->AddScalarInt32Operand(*axis_param.data.i32); *nn_op_type = ANEURALNETWORKS_EXPAND_DIMS; } break; case kTfLiteBuiltinSplit: { const TfLiteTensor& axis = mapping_args.context->tensors[mapping_args.node->inputs->data[0]]; auto builtin = reinterpret_cast<TfLiteSplitParams*>(mapping_args.node->builtin_data); mapping_args.builder->AddScalarInt32Operand(*axis.data.i32); mapping_args.builder->AddScalarInt32Operand(builtin->num_splits); *nn_op_type = ANEURALNETWORKS_SPLIT; } break; case kTfLiteBuiltinLogSoftmax: { // Scaling and axis are hardcoded to respectively 1 and -1 // in TFLite. mapping_args.builder->AddScalarFloat32Operand(1); mapping_args.builder->AddScalarInt32Operand(-1); *nn_op_type = ANEURALNETWORKS_LOG_SOFTMAX; } break; case kTfLiteBuiltinQuantize: { *nn_op_type = ANEURALNETWORKS_QUANTIZE; } break; case kTfLiteBuiltinReduceAny: { auto builtin = reinterpret_cast<TfLiteReducerParams*>( mapping_args.node->builtin_data); mapping_args.builder->AddScalarBoolOperand(builtin->keep_dims); *nn_op_type = ANEURALNETWORKS_REDUCE_ANY; } break; case kTfLiteBuiltinReduceMin: { auto builtin = reinterpret_cast<TfLiteReducerParams*>( mapping_args.node->builtin_data); mapping_args.builder->AddScalarBoolOperand(builtin->keep_dims); *nn_op_type = ANEURALNETWORKS_REDUCE_MIN; } break; case kTfLiteBuiltinReduceMax: { auto builtin = reinterpret_cast<TfLiteReducerParams*>( mapping_args.node->builtin_data); mapping_args.builder->AddScalarBoolOperand(builtin->keep_dims); *nn_op_type = ANEURALNETWORKS_REDUCE_MAX; } break; case kTfLiteBuiltinDepthToSpace: { auto builtin = reinterpret_cast<TfLiteDepthToSpaceParams*>( mapping_args.node->builtin_data); mapping_args.builder->AddScalarInt32Operand(builtin->block_size); *nn_op_type = ANEURALNETWORKS_DEPTH_TO_SPACE; } break; case kTfLiteBuiltinReduceProd: { auto builtin = reinterpret_cast<TfLiteReducerParams*>( mapping_args.node->builtin_data); mapping_args.builder->AddScalarBoolOperand(builtin->keep_dims); *nn_op_type = ANEURALNETWORKS_REDUCE_PROD; } break; case kTfLiteBuiltinSum: { auto builtin = reinterpret_cast<TfLiteReducerParams*>( mapping_args.node->builtin_data); mapping_args.builder->AddScalarBoolOperand(builtin->keep_dims); *nn_op_type = ANEURALNETWORKS_REDUCE_SUM; } break; case kTfLiteBuiltinElu: { mapping_args.builder->AddScalarFloat32Operand(1.0); *nn_op_type = ANEURALNETWORKS_ELU; } break; case kTfLiteBuiltinFill: { *nn_op_type = ANEURALNETWORKS_FILL; } break; default: // All other operators are not mapped. return kTfLiteError; } return kTfLiteOk; } // Initialize the kernel (a NN model). TfLiteStatus NNAPIDelegateKernel::Init(TfLiteContext* context, const TfLiteDelegateParams* params, int* nnapi_errno) { for (auto node_index : TfLiteIntArrayView(params->nodes_to_replace)) { nodes_.push_back(node_index); } const auto delegate_options = StatefulNnApiDelegate::GetOptions(params->delegate); if (nnapi_->android_sdk_version >= kMinSdkVersionForNNAPI12 && ShouldUseTargetDevices(delegate_options)) { TF_LITE_ENSURE_STATUS(GetTargetDevices(context, params->delegate, nnapi_, nnapi_errno, &nnapi_devices_)); if (nnapi_devices_.empty()) { context->ReportError( context, "NNAPI delegate requested but no accelerators available."); return kTfLiteError; } } // Mark the handle backed tensors. tensor_memory_map_ = &StatefulNnApiDelegate::GetTensorMemoryMap(params->delegate); if (!nn_model_) { ANeuralNetworksModel* model = nullptr; RETURN_TFLITE_ERROR_IF_NN_ERROR(context, nnapi_->ANeuralNetworksModel_create(&model), "creating NNAPI model", nnapi_errno); nn_model_.reset(model); TF_LITE_ENSURE_STATUS(BuildGraph(context, delegate_options, params->input_tensors, params->output_tensors, nnapi_errno)); } // Calculating model compilation cache here since the value depends on // some of the TfLiteDelegateParams nn_compilation_cache_token_.clear(); const char* cache_dir = delegate_options.cache_dir; const char* model_token = delegate_options.model_token; if (nnapi_->android_sdk_version >= kMinSdkVersionForNNAPI12 && cache_dir && model_token) { // Compilation caching could be enabled, try construct the uint8 // token. // TODO(b/133342794): use a generic token generator class. uint64_t token_parts[4]; // bits from model_token. token_parts[0] = std::hash<std::string>{}(model_token); // bits from params->nodes_to_replace. token_parts[1] = GetHash(params->nodes_to_replace); // bits from params->input_tensors. token_parts[2] = GetHash(params->input_tensors); // bits from params->output_tensors. token_parts[3] = GetHash(params->output_tensors); // NNAPI requires the token to be 256bit long. std::vector<uint8_t> nnapi_cache_token(32, 0); // Copy the token bits. uint8_t* p = reinterpret_cast<uint8_t*>(token_parts); for (int i = 0; i < 4 * sizeof(uint64_t); i++) { nnapi_cache_token[i] = p[i]; } nn_compilation_cache_token_ = nnapi_cache_token; } initialised_ = true; return kTfLiteOk; } TfLiteStatus NNAPIDelegateKernel::Prepare(TfLiteContext* context, TfLiteNode* node, int* nnapi_errno) { if (!initialised_) { return kTfLiteError; } if (nn_compilation_) { return kTfLiteOk; } const auto delegate_options = StatefulNnApiDelegate::GetOptions(node->delegate); ANeuralNetworksCompilation* compilation = nullptr; if (!nnapi_devices_.empty()) { // Compile for the selected accelerator. RETURN_TFLITE_ERROR_IF_NN_ERROR( context, nnapi_->ANeuralNetworksCompilation_createForDevices( nn_model_.get(), nnapi_devices_.data(), nnapi_devices_.size(), &compilation), "creating NNAPI model for given devices", nnapi_errno); } else { RETURN_TFLITE_ERROR_IF_NN_ERROR(context, nnapi_->ANeuralNetworksCompilation_create( nn_model_.get(), &compilation), "creating NNAPI compilation", nnapi_errno); } auto preference = delegate_options.execution_preference; if (preference != StatefulNnApiDelegate::Options::ExecutionPreference::kUndefined) { const int preference_result = nnapi_->ANeuralNetworksCompilation_setPreference(compilation, preference); if (preference_result != ANEURALNETWORKS_NO_ERROR) { nnapi_->ANeuralNetworksCompilation_free(compilation); compilation = nullptr; } RETURN_TFLITE_ERROR_IF_NN_ERROR(context, preference_result, "setting compilation preferences", nnapi_errno); } if (!nn_compilation_cache_token_.empty()) { const char* cache_dir = delegate_options.cache_dir; const int set_caching_result = nnapi_->ANeuralNetworksCompilation_setCaching( compilation, cache_dir, nn_compilation_cache_token_.data()); if (set_caching_result != ANEURALNETWORKS_NO_ERROR) { nnapi_->ANeuralNetworksCompilation_free(compilation); compilation = nullptr; } RETURN_TFLITE_ERROR_IF_NN_ERROR(context, set_caching_result, "configuring NNAPI caching", nnapi_errno); } // Set compilation timeout if applicable. if (nnapi_->android_sdk_version >= kMinSdkVersionForNNAPI13) { if (delegate_options.max_compilation_timeout_duration_ns > 0) { RETURN_TFLITE_ERROR_IF_NN_ERROR( context, nnapi_->ANeuralNetworksCompilation_setTimeout( compilation, delegate_options.max_compilation_timeout_duration_ns), "setting compilation timeout", nnapi_errno); } RETURN_TFLITE_ERROR_IF_NN_ERROR( context, nnapi_->ANeuralNetworksCompilation_setPriority( compilation, delegate_options.execution_priority), "setting compilation priority", nnapi_errno); } const int finish_result = nnapi_->ANeuralNetworksCompilation_finish(compilation); if (finish_result != ANEURALNETWORKS_NO_ERROR) { nnapi_->ANeuralNetworksCompilation_free(compilation); compilation = nullptr; } RETURN_TFLITE_ERROR_IF_NN_ERROR(context, finish_result, "completing NNAPI compilation", nnapi_errno); nn_compilation_.reset(compilation); return kTfLiteOk; } TfLiteStatus NNAPIDelegateKernel::GetOperationsSupportedByTargetNnApiDevices( TfLiteContext* context, std::vector<int>* supported_nodes, int* nnapi_errno) { if (!nnapi_->ANeuralNetworksModel_getSupportedOperationsForDevices) { return kTfLiteError; } const auto nnapi_model_size = nnapi_to_tflite_op_mapping_.size(); // Determine the list of operations the device actually supports std::unique_ptr<bool[]> nnapi_ops_support_flags(new bool[actual_node_num]); RETURN_TFLITE_ERROR_IF_NN_ERROR( context, nnapi_->ANeuralNetworksModel_getSupportedOperationsForDevices( nn_model_.get(), nnapi_devices_.data(), nnapi_devices_.size(), nnapi_ops_support_flags.get()), "Checking supported operations for devices", nnapi_errno); // A TfLite op is supported only if all the associated NNAPI ones are. auto tflite_ops_support_status = std::map<int, bool>(); std::for_each(nodes_.begin(), nodes_.end(), [&tflite_ops_support_status](int tflite_node_index) { tflite_ops_support_status[tflite_node_index] = true; }); for (int nnapi_op_index = 0; nnapi_op_index < nnapi_model_size; nnapi_op_index++) { const auto tflite_op_index = nnapi_to_tflite_op_mapping_[nnapi_op_index]; tflite_ops_support_status[tflite_op_index] &= nnapi_ops_support_flags[nnapi_op_index]; } supported_nodes->clear(); std::for_each(nodes_.begin(), nodes_.end(), [&supported_nodes, &tflite_ops_support_status](int node_index) { if (tflite_ops_support_status[node_index]) { supported_nodes->push_back(node_index); } }); return kTfLiteOk; } TfLiteStatus NNAPIDelegateKernel::Invoke(TfLiteContext* context, TfLiteNode* node, int* nnapi_errno) { ANeuralNetworksExecution* execution = nullptr; RETURN_TFLITE_ERROR_IF_NN_ERROR(context, nnapi_->ANeuralNetworksExecution_create( nn_compilation_.get(), &execution), "creating NNAPI execution", nnapi_errno); std::unique_ptr<ANeuralNetworksExecution, NNFreeExecution> execution_unique_ptr(execution, NNFreeExecution(nnapi_)); // Set compilation timeout if applicable. const auto delegate_options = StatefulNnApiDelegate::GetOptions(node->delegate); if (nnapi_->android_sdk_version >= kMinSdkVersionForNNAPI13) { if (delegate_options.max_execution_timeout_duration_ns > 0) { RETURN_TFLITE_ERROR_IF_NN_ERROR( context, nnapi_->ANeuralNetworksExecution_setTimeout( execution, delegate_options.max_execution_timeout_duration_ns), "setting execution timeout", nnapi_errno); } if (delegate_options.max_execution_loop_timeout_duration_ns > 0) { RETURN_TFLITE_ERROR_IF_NN_ERROR( context, nnapi_->ANeuralNetworksExecution_setLoopTimeout( execution, delegate_options.max_execution_loop_timeout_duration_ns), "setting execution loop timeout", nnapi_errno); } } // Set the input tensor buffers. Note: we access tflite tensors using // absolute indices but NN api indices inputs by relative indices. int relative_input_index = 0; size_t input_offset = 0; for (auto absolute_input_index : TfLiteIntArrayView(node->inputs)) { if (absolute_input_index == kTfLiteOptionalTensor) { continue; } TfLiteTensor* tensor = &context->tensors[absolute_input_index]; if (tensor->allocation_type != kTfLiteMmapRo) { if (tensor->buffer_handle != kTfLiteNullBufferHandle && tensor->buffer_handle < tensor_memory_map_->size()) { RETURN_TFLITE_ERROR_IF_NN_ERROR( context, nnapi_->ANeuralNetworksExecution_setInputFromMemory( execution, relative_input_index, nullptr, tensor_memory_map_->at(tensor->buffer_handle).memory, 0, tensor->bytes), "associating NNAPI execution input with a memory object", nnapi_errno); relative_input_index++; continue; } TfLiteType ann_type_equivalent = operand_mapping_.lite_index_to_ann_type_conversion( absolute_input_index); int tensor_size = 0; if (ann_type_equivalent != kTfLiteNoType) { const auto num_elements = NumElements(tensor); uint8_t* input_ptr = nn_input_memory_->get_data_ptr() + input_offset; if (tensor->type == kTfLiteUInt8 && ann_type_equivalent == kTfLiteInt32) { for (int i = 0; i < num_elements; ++i) { reinterpret_cast<int32_t*>(input_ptr)[i] = static_cast<const int32_t>(tensor->data.uint8[i]); } } else if (tensor->type == kTfLiteInt8 && ann_type_equivalent == kTfLiteUInt8) { // Explicitly convert int8 values to uint8 values. for (int i = 0; i < num_elements; ++i) { input_ptr[i] = static_cast<const uint8_t>( static_cast<int32_t>(tensor->data.int8[i]) + 128); } } else if (tensor->type == kTfLiteInt8 && ann_type_equivalent == kTfLiteInt32) { for (int i = 0; i < num_elements; ++i) { reinterpret_cast<int32_t*>(input_ptr)[i] = static_cast<const int32_t>(tensor->data.int8[i]) + 128; } } else { context->ReportError( context, "NN API Delegate: unsupported tensor types conversion: " "from type code %d to type code %d.\n", tensor->type, ann_type_equivalent); return kTfLiteError; } size_t type_size; TF_LITE_ENSURE_OK( context, GetSizeOfType(context, ann_type_equivalent, &type_size)); tensor_size = NumElements(tensor) * type_size; RETURN_TFLITE_ERROR_IF_NN_ERROR( context, nnapi_->ANeuralNetworksExecution_setInputFromMemory( execution, relative_input_index, nullptr, nn_input_memory_->get_handle(), input_offset, tensor_size), "associating NNAPI execution input with a memory object", nnapi_errno); } else { // copy data to pre-allocated shared memory. memcpy(nn_input_memory_->get_data_ptr() + input_offset, tensor->data.raw, tensor->bytes); RETURN_TFLITE_ERROR_IF_NN_ERROR( context, nnapi_->ANeuralNetworksExecution_setInputFromMemory( execution, relative_input_index, nullptr, nn_input_memory_->get_handle(), input_offset, tensor->bytes), "associating NNAPI execution input with a memory object", nnapi_errno); tensor_size = tensor->bytes; } input_offset += tensor_size; input_offset += getNumPaddingBytes(tensor_size); relative_input_index++; } } // Set the output tensor buffers. int relative_output_index = 0; size_t output_offset = 0; for (auto output_index : TfLiteIntArrayView(node->outputs)) { // If the NNAPI implementation doesn't have some of the outputs // they are left unmapped and we should not try to read their value here if (operand_mapping_.lite_index_to_ann(output_index) == -1) { continue; } TfLiteTensor* tensor = &context->tensors[output_index]; if (tensor->buffer_handle != kTfLiteNullBufferHandle && tensor->buffer_handle < tensor_memory_map_->size()) { RETURN_TFLITE_ERROR_IF_NN_ERROR( context, nnapi_->ANeuralNetworksExecution_setOutputFromMemory( execution, relative_output_index, nullptr, tensor_memory_map_->at(tensor->buffer_handle).memory, 0, tensor->bytes), "associating NNAPI execution output to a memory object", nnapi_errno); } else { RETURN_TFLITE_ERROR_IF_NN_ERROR( context, nnapi_->ANeuralNetworksExecution_setOutputFromMemory( execution, relative_output_index, nullptr, nn_output_memory_->get_handle(), output_offset, tensor->bytes), "associating NNAPI execution output to a memory object", nnapi_errno); output_offset += tensor->bytes; output_offset += getNumPaddingBytes(tensor->bytes); } relative_output_index++; } // The state_out of previous invocation need to be mapped to state_in of // current invocation. for (size_t i = 0; i < model_state_tfl_inputs_.size(); i++) { int state_tensor_idx = model_state_tfl_inputs_[i]; TfLiteTensor* tensor = &context->tensors[state_tensor_idx]; // Here we are using a deep copy for state_in tensors so that we are not // reading and writing into the same buffer during a invocation. // TODO(b/110369471): using double shared buffer to minimize the copies. RETURN_TFLITE_ERROR_IF_NN_ERROR( context, nnapi_->ANeuralNetworksExecution_setOutput( execution, relative_output_index, nullptr, tensor->data.raw, tensor->bytes), "associating NNAPI execution output to a buffer", nnapi_errno); relative_output_index++; } // Invoke ANN in blocking fashion. if (nnapi_->android_sdk_version < kMinSdkVersionForNNAPI12) { ANeuralNetworksEvent* event = nullptr; RETURN_TFLITE_ERROR_IF_NN_ERROR( context, nnapi_->ANeuralNetworksExecution_startCompute(execution, &event), "starting async computation", nnapi_errno); const int wait_result = nnapi_->ANeuralNetworksEvent_wait(event); nnapi_->ANeuralNetworksEvent_free(event); RETURN_TFLITE_ERROR_IF_NN_ERROR(context, wait_result, "waiting for async computation completion", nnapi_errno); } else { // Use synchronous execution for NNAPI 1.2+. RETURN_TFLITE_ERROR_IF_NN_ERROR( context, nnapi_->ANeuralNetworksExecution_compute(execution), "running computation", nnapi_errno); } // copy results from shared memory to the destination. output_offset = 0; for (auto output_index : TfLiteIntArrayView(node->outputs)) { TfLiteTensor* tensor = &context->tensors[output_index]; if (tensor->buffer_handle != kTfLiteNullBufferHandle) { continue; } TfLiteType ann_type_equivalent = operand_mapping_.lite_index_to_ann_type_conversion(output_index); if (tensor->type == kTfLiteInt8 && ann_type_equivalent == kTfLiteUInt8) { // Explicitly convert uint8 values to int8 values. uint8_t* output_ptr = reinterpret_cast<uint8_t*>( nn_output_memory_->get_data_ptr() + output_offset); const auto num_elements = NumElements(tensor); for (int i = 0; i < num_elements; ++i) { output_ptr[i] = static_cast<uint8_t>(static_cast<int32_t>(output_ptr[i]) - 128); } } memcpy(tensor->data.raw, nn_output_memory_->get_data_ptr() + output_offset, tensor->bytes); output_offset += tensor->bytes; output_offset += getNumPaddingBytes(tensor->bytes); } // copy output of all output tensors in feedback_loops_ into the // associated input for (auto feedback_loop : feedback_loops_) { int output_tensor_idx; int input_tensor_idx; std::tie(output_tensor_idx, input_tensor_idx) = feedback_loop; TfLiteTensor& src = context->tensors[output_tensor_idx]; TfLiteTensor& dest = context->tensors[input_tensor_idx]; memcpy(dest.data.raw, src.data.raw, src.bytes); } return kTfLiteOk; } void NNAPIDelegateKernel::AddDequantizeOperatorsWhereNeeded( const TfLiteContext* context, int builtin_code, const TfLiteNode* node, int tflite_node_index, NNAPIOpBuilder* builder, int* nnapi_errno) { // Depending on the operator and the input data format, Dequantize // operators may need to be added. For example when the input is // floating-point but weights are quantized then the weights will first be // dequantized to the same format as the input before being passed to the // operator. // The tensor determining whether the inputs should be floating-point. int input_tensor_index = -1; std::vector<int> inputs_to_potentially_dequantize; switch (builtin_code) { case kTfLiteBuiltinConv2d: case kTfLiteBuiltinFullyConnected: { input_tensor_index = 0; // Weights and bias are inputs #1 and #2 respectively and may require // dequantization. inputs_to_potentially_dequantize = {1, 2}; break; } case kTfLiteBuiltinLstm: { input_tensor_index = 0; inputs_to_potentially_dequantize = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 20, 21, 22, 23}; break; } default: return; } int tensor_id = node->inputs->data[input_tensor_index]; if (tensor_id < 0) return; // Nothing to do if the input is not floating-point. if (!IsFloat(context->tensors[tensor_id].type)) return; for (int i : inputs_to_potentially_dequantize) { if (i < 0 || i >= node->inputs->size) continue; // Ignore invalid index. tensor_id = node->inputs->data[i]; if (tensor_id < 0) continue; // Ignore optional input. const TfLiteType type = context->tensors[tensor_id].type; // Nothing to do for this tensor if it's not quantized. if (!IsQuantized(type)) continue; // Insert Dequantize operator if it hasn't been done already and change // the node's input accordingly. builder->AddDequantize(i, node->inputs->data[i], type, tflite_node_index); } } TfLiteStatus NNAPIDelegateKernel::AddOpsAndTensors(TfLiteContext* context, int* nnapi_errno) { DequantizeMapping dequantize_mapping; // The operand builder allows creating a single op. It is created outside // the for loop to avoid reallocating the vectors. NNAPIOpBuilder builder(nnapi_, context, &operand_mapping_, &dequantize_mapping, &allocation_memory_mapping_, &nnapi_to_tflite_op_mapping_, nn_model_.get(), nnapi_errno); // Add Tensors. for (auto node_index : nodes_) { // Obtain the op and registration. TfLiteNode* node; TfLiteRegistration* reg; TF_LITE_ENSURE_STATUS( context->GetNodeAndRegistration(context, node_index, &node, &reg)); const bool hybrid_op = IsHybridOperator(context, reg->builtin_code, node); const bool scalar_as_tensor = IsScalarInputSupported(reg->builtin_code); const bool need_int8_conversion = NeedInt8Conversion(context, reg->builtin_code, node); int input_tensor_flags = 0; if (scalar_as_tensor) { input_tensor_flags |= NN_TENSOR_FLAG_SCALAR_AS_TENSOR; } // On SDK level less than 30, h_swish will be lowered into supported NNAPI // operations. Since SDK level 30, h_swish is supported as a single // operation. if (reg->builtin_code == kTfLiteBuiltinHardSwish && nnapi_->android_sdk_version < kMinSdkVersionForNNAPI13) { builder.TransformHardSwishIntoSupportedOps( node->inputs->data[0], node->outputs->data[0], need_int8_conversion, node_index); actual_node_num += 4; continue; } actual_node_num++; // Map inputs to NN API tensor indices. for (int input_pos = 0; input_pos < node->inputs->size; ++input_pos) { const auto input_index = node->inputs->data[input_pos]; if (need_int8_conversion && (input_pos == 0 || reg->builtin_code == kTfLiteBuiltinFullyConnected || reg->builtin_code == kTfLiteBuiltinConv2d || reg->builtin_code == kTfLiteBuiltinDepthwiseConv2d || reg->builtin_code == kTfLiteBuiltinAdd || reg->builtin_code == kTfLiteBuiltinMul || reg->builtin_code == kTfLiteBuiltinSub || reg->builtin_code == kTfLiteBuiltinConcatenation || reg->builtin_code == kTfLiteBuiltinMaximum || reg->builtin_code == kTfLiteBuiltinMinimum || reg->builtin_code == kTfLiteBuiltinLess || reg->builtin_code == kTfLiteBuiltinLessEqual || reg->builtin_code == kTfLiteBuiltinGreater || reg->builtin_code == kTfLiteBuiltinGreaterEqual || reg->builtin_code == kTfLiteBuiltinEqual || reg->builtin_code == kTfLiteBuiltinNotEqual || reg->builtin_code == kTfLiteBuiltinSelect)) { // Only selected inputs require int8 conversion. TF_LITE_ENSURE_STATUS(builder.AddTensorInput( input_index, hybrid_op, input_tensor_flags | NN_TENSOR_FLAG_INT8_CONVERSION)); continue; } if (reg->builtin_code == kTfLiteBuiltinLstm && isLstmFullKernel(node) && input_pos >= 20) { // Skip layer normalization weights. They are added in the Map // function (after all the other inputs added there) since layer // normalization weights are the last four inputs of the LSTM op in // NNAPI. continue; } if (reg->builtin_code == kTfLiteBuiltinLstm && isLstmBasicKernel(node)) { // Configuring all inputs in the Map function continue; } if (reg->builtin_code == kTfLiteBuiltinUnidirectionalSequenceLstm) { if (input_pos >= 20) { // Skip layer normalization weights. They are added in the Map // function (after all the other inputs added there) since layer // normalization weights are the last four inputs of the // unidirectional sequence LSTM op in NNAPI. continue; } if (input_index == kTfLiteOptionalTensor) { TF_LITE_ENSURE_STATUS(builder.AddVectorFloat32Operand(nullptr, 0)); continue; } } if ((reg->builtin_code == kTfLiteBuiltinSplit) && (input_index == node->inputs->data[0])) { // Skip the axis input tensor; it will be added as a scalar operand // by the Map() mapping. continue; } if (reg->builtin_code == kTfLiteBuiltinTransposeConv) { // Everything is added during Map since input tensors // have different order. continue; } // Pad and Padv2 have an optional parameter for a pad value which has // to be converted to a scalar type in NN API. if ((reg->builtin_code == kTfLiteBuiltinPadv2 || reg->builtin_code == kTfLiteBuiltinPad) && node->inputs->size == 3 && input_pos == 2) { const int constant_value_id = node->inputs->data[2]; if (constant_value_id == kTfLiteOptionalTensor) { continue; } const TfLiteTensor constant_value = context->tensors[constant_value_id]; switch (constant_value.type) { case kTfLiteFloat32: if (constant_value.allocation_type == kTfLiteMmapRo) { builder.AddScalarFloat32Operand(*constant_value.data.f); } else { builder.AddSingleValueTensorAsScalarOperand( constant_value_id, ANEURALNETWORKS_FLOAT32); } break; case kTfLiteUInt8: if (constant_value.allocation_type == kTfLiteMmapRo) { builder.AddScalarInt32Operand( static_cast<int32_t>(*constant_value.data.uint8)); } else { builder.AddSingleValueTensorAsScalarOperand( constant_value_id, ANEURALNETWORKS_INT32); } break; case kTfLiteInt8: if (constant_value.allocation_type == kTfLiteMmapRo) { builder.AddScalarInt32Operand( static_cast<int32_t>(*constant_value.data.int8) + 128); } else { builder.AddSingleValueTensorAsScalarOperand( constant_value_id, ANEURALNETWORKS_INT32); } break; default: context->ReportError(context, "Unsupported type of pad value for pad_v2\n"); return kTfLiteError; } continue; } if (input_index == kTfLiteOptionalTensor && (reg->builtin_code == kTfLiteBuiltinLstm || reg->builtin_code == kTfLiteBuiltinSvdf || reg->builtin_code == kTfLiteBuiltinBidirectionalSequenceLstm)) { // properly handle the optional tensor for LSTM and SVDF. // currently only support float32. TF_LITE_ENSURE_STATUS(builder.AddVectorFloat32Operand(nullptr, 0)); } else if (reg->builtin_code == kTfLiteBuiltinResizeBilinear || reg->builtin_code == kTfLiteBuiltinResizeNearestNeighbor) { if (input_pos == 0) { // Only the first input tensor is added. The second one, // specifying the output height and width, is not added and // instead the height and width will be added individually as // scalars by the mapping function returned by Map(). TF_LITE_ENSURE_STATUS(builder.AddTensorInput(input_index, hybrid_op)); } } else if (reg->builtin_code == kTfLiteBuiltinTopkV2 && input_pos > 0) { // The K parameter tensor is not handled here but by the functor // returned by Map, the input tensor is instead added in // the else clause below continue; } else if (reg->builtin_code == kTfLiteBuiltinGather) { // Everything is added during Map since input tensors // have different order. continue; } else if (reg->builtin_code == kTfLiteBuiltinExpandDims && input_pos == 1) { // The axis param is added during Map continue; } else if (reg->builtin_code == kTfLiteBuiltinBatchToSpaceNd && input_pos == 2) { // NNAPI does not support crops. // The Map function will check if all crops are zero. continue; } else if (reg->builtin_code == kTfLiteBuiltinArgMin || reg->builtin_code == kTfLiteBuiltinArgMax) { // The first input tensor is added as is. The second one, specifying // the axis, needs to be converted to a scalar since TFLite uses a // tensor but NNAPI uses a scalar as the axis. if (input_pos == 0) { TF_LITE_ENSURE_STATUS(builder.AddTensorInput(input_index, hybrid_op)); } else { const int axis_id = node->inputs->data[1]; const TfLiteTensor& axis_tensor = context->tensors[axis_id]; switch (axis_tensor.type) { case kTfLiteInt32: if (axis_tensor.allocation_type == kTfLiteMmapRo) { TF_LITE_ENSURE_STATUS(builder.AddScalarInt32Operand( static_cast<int32_t>(*axis_tensor.data.i32))); } else { TF_LITE_ENSURE_STATUS( builder.AddSingleValueTensorAsScalarOperand( axis_id, ANEURALNETWORKS_INT32)); } break; case kTfLiteInt64: // Map() function already makes sure int64 input is constant. TF_LITE_ENSURE_STATUS(builder.AddScalarInt32Operand( static_cast<int32_t>(*axis_tensor.data.i64))); break; default: return kTfLiteError; } } } else if (reg->builtin_code == kTfLiteBuiltinMaximum || reg->builtin_code == kTfLiteBuiltinMinimum) { const TfLiteTensor& operand_tensor = context->tensors[node->inputs->data[input_pos]]; if (operand_tensor.dims->size == 0) { int tensor_index; TF_LITE_ENSURE_EQ(context, operand_tensor.allocation_type, kTfLiteMmapRo); switch (operand_tensor.type) { case kTfLiteFloat32: TF_LITE_ENSURE_STATUS(builder.AddNewInputConstantTensor( ANEURALNETWORKS_TENSOR_FLOAT32, operand_tensor.type, {1}, std::vector<float>(1, operand_tensor.data.f[0]), operand_tensor.params, &tensor_index)); break; case kTfLiteUInt8: TF_LITE_ENSURE_STATUS(builder.AddNewInputConstantTensor( ANEURALNETWORKS_TENSOR_QUANT8_ASYMM, operand_tensor.type, {1}, std::vector<uint8_t>(1, operand_tensor.data.uint8[0]), operand_tensor.params, &tensor_index)); break; case kTfLiteInt8: TF_LITE_ENSURE_STATUS(builder.AddNewInputConstantTensor( ANEURALNETWORKS_TENSOR_QUANT8_SYMM, operand_tensor.type, {1}, std::vector<int8_t>(1, operand_tensor.data.int8[0]), operand_tensor.params, &tensor_index)); break; case kTfLiteInt32: TF_LITE_ENSURE_STATUS(builder.AddNewInputConstantTensor( ANEURALNETWORKS_TENSOR_INT32, operand_tensor.type, {1}, std::vector<int32_t>(1, operand_tensor.data.i32[0]), operand_tensor.params, &tensor_index)); break; default: return kTfLiteError; } } else { TF_LITE_ENSURE_STATUS(builder.AddTensorInput(input_index, hybrid_op, input_tensor_flags)); } } else if ((reg->builtin_code == kTfLiteBuiltinReduceAny || reg->builtin_code == kTfLiteBuiltinReduceMax || reg->builtin_code == kTfLiteBuiltinReduceMin || reg->builtin_code == kTfLiteBuiltinReduceProd || reg->builtin_code == kTfLiteBuiltinSum) && (input_pos == 1)) { // The axis needs, be converted to a tensor if specified as scalar const TfLiteTensor& axis_tensor = context->tensors[node->inputs->data[input_pos]]; if (axis_tensor.dims->size == 0) { TF_LITE_ENSURE_STATUS( builder.AddVectorInt32Operand(axis_tensor.data.i32, 1)); } else { TF_LITE_ENSURE_STATUS(builder.AddTensorInput(input_index, hybrid_op, input_tensor_flags)); } } else if (reg->builtin_code == kTfLiteBuiltinFill) { if (input_pos == 0) { const int dims_id = node->inputs->data[0]; const TfLiteTensor& dims_tensor = context->tensors[dims_id]; switch (dims_tensor.type) { case kTfLiteInt32: TF_LITE_ENSURE_STATUS( builder.AddTensorInput(input_index, hybrid_op)); break; case kTfLiteInt64: { // We made sure that dimensions are constant and fit into int32 in // Map(), so we can safely create a new tensor with casted values. const int dims_size = dims_tensor.dims->data[0]; std::vector<int32_t> dims_int32(dims_size); std::copy(dims_tensor.data.i64, dims_tensor.data.i64 + dims_size, dims_int32.begin()); int new_tensor_index = -1; builder.AddNewInputConstantTensor( ANEURALNETWORKS_TENSOR_INT32, kTfLiteInt32, dims_tensor.dims, dims_int32, dims_tensor.params, &new_tensor_index); } break; default: return kTfLiteError; } } else { const int value_id = node->inputs->data[1]; const TfLiteTensor& value_tensor = context->tensors[value_id]; switch (value_tensor.type) { case kTfLiteFloat32: TF_LITE_ENSURE_STATUS( builder.AddScalarFloat32Operand(*value_tensor.data.f)); break; case kTfLiteInt32: TF_LITE_ENSURE_STATUS( builder.AddScalarInt32Operand(*value_tensor.data.i32)); break; case kTfLiteInt64: // Map() function already makes sure int64 input is constant and // fits into int32. TF_LITE_ENSURE_STATUS(builder.AddScalarInt32Operand( static_cast<int32_t>(*value_tensor.data.i64))); break; default: return kTfLiteError; } } } else { TF_LITE_ENSURE_STATUS( builder.AddTensorInput(input_index, hybrid_op, input_tensor_flags)); } } // If we have target accelerators the target SDK version might be // different than the current android version. int target_sdk_version = nnapi_->android_sdk_version; if (!nnapi_devices_.empty()) { TF_LITE_ENSURE_STATUS(GetTargetSdkVersion( context, nnapi_, nnapi_devices_, &target_sdk_version, nnapi_errno)); } // Get op type and operands // Fails if the Validate function failed int nn_op_type; TF_LITE_ENSURE_STATUS( Map(context, reg->builtin_code, reg->version, target_sdk_version, {context, &builder, node, &model_state_outputs_, &model_state_tfl_inputs_, &feedback_loops_, nnapi_errno}, &nn_op_type)); // Map outputs to NN API tensor indices. int output_tensor_flags = 0; if (need_int8_conversion) { output_tensor_flags |= NN_TENSOR_FLAG_INT8_CONVERSION; } for (int output_pos = 0; output_pos < node->outputs->size; ++output_pos) { const auto output_index = node->outputs->data[output_pos]; // Outputs for basic LSTM cell are set in the Map function since if (reg->builtin_code == kTfLiteBuiltinLstm && isLstmBasicKernel(node)) { continue; } TF_LITE_ENSURE_STATUS( builder.AddTensorOutput(output_index, output_tensor_flags)); } // Dequantize operators may have to be added in case inputs are to be // floating-point. AddDequantizeOperatorsWhereNeeded(context, reg->builtin_code, node, node_index, &builder, nnapi_errno); builder.FinalizeAddOperation(nn_op_type, node_index); } return kTfLiteOk; } TfLiteStatus NNAPIDelegateKernel::BuildGraph( TfLiteContext* context, const StatefulNnApiDelegate::Options& delegate_options, const TfLiteIntArray* input_tensors, const TfLiteIntArray* output_tensors, int* nnapi_errno) { // Build the ops and tensors. TF_LITE_ENSURE_STATUS(AddOpsAndTensors(context, nnapi_errno)); // Map input and output tensor indices to ANN std::vector<uint32_t> inputs; inputs.reserve(input_tensors->size); std::vector<uint32_t> outputs; outputs.reserve(output_tensors->size); size_t total_input_byte_size = 0; // Make the TensorFlow Lite inputs and outputs to ann_indices. for (int i : TfLiteIntArrayView(input_tensors)) { // Constant tensors are not NNAPI inputs. if (i != kTfLiteOptionalTensor && context->tensors[i].allocation_type != kTfLiteMmapRo && // The delegate might not have mapped this input (this can // happen if one tensor is split in several ones) operand_mapping_.lite_index_to_ann(i) != -1) { inputs.push_back(operand_mapping_.lite_index_to_ann(i)); if (context->tensors[i].buffer_handle != kTfLiteNullBufferHandle) { continue; } const TfLiteType nn_type_conversion = operand_mapping_.lite_index_to_ann_type_conversion(i); int tensor_size = 0; if (nn_type_conversion == kTfLiteNoType) { tensor_size = context->tensors[i].bytes; } else { size_t type_size; TF_LITE_ENSURE_OK( context, GetSizeOfType(context, nn_type_conversion, &type_size)); tensor_size = NumElements(&context->tensors[i]) * type_size; } total_input_byte_size += tensor_size; total_input_byte_size += getNumPaddingBytes(tensor_size); } } size_t total_output_byte_size = 0; for (int i : TfLiteIntArrayView(output_tensors)) { const int output_tensor_ann_index = operand_mapping_.lite_index_to_ann(i); // Unmapped outputs are not added if (output_tensor_ann_index != -1) { outputs.push_back(output_tensor_ann_index); } if (context->tensors[i].buffer_handle != kTfLiteNullBufferHandle) { continue; } total_output_byte_size += context->tensors[i].bytes; total_output_byte_size += getNumPaddingBytes(context->tensors[i].bytes); } // Add state output tensors as model outputs. for (int i : model_state_outputs_) { outputs.push_back(i); } // Tell ANN to declare inputs/outputs RETURN_TFLITE_ERROR_IF_NN_ERROR( context, nnapi_->ANeuralNetworksModel_identifyInputsAndOutputs( nn_model_.get(), inputs.size(), inputs.data(), outputs.size(), outputs.data()), "identifying model inputs and outputs", nnapi_errno); auto allow_fp16 = context->allow_fp32_relax_to_fp16 | delegate_options.allow_fp16; if (nnapi_->android_sdk_version >= kMinSdkVersionForNNAPI11) { RETURN_TFLITE_ERROR_IF_NN_ERROR( context, nnapi_->ANeuralNetworksModel_relaxComputationFloat32toFloat16( nn_model_.get(), allow_fp16), "set relaxed computation mode for fp32 if possible", nnapi_errno); } RETURN_TFLITE_ERROR_IF_NN_ERROR( context, nnapi_->ANeuralNetworksModel_finish(nn_model_.get()), "finalizing the model", nnapi_errno); // Create shared memory pool for inputs and outputs. std::string input_pool_name = "input_pool" + std::to_string(graph_index); std::string output_pool_name = "output_pool" + std::to_string(graph_index); nn_input_memory_.reset( new NNMemory(nnapi_, input_pool_name.data(), total_input_byte_size)); nn_output_memory_.reset( new NNMemory(nnapi_, output_pool_name.data(), total_output_byte_size)); graph_index++; return kTfLiteOk; } } // namespace nnapi } // namespace delegate using ::tflite::delegate::nnapi::NNAPIDelegateKernel; StatefulNnApiDelegate::Data::Data(const NnApi* nnapi) : nnapi(nnapi) {} StatefulNnApiDelegate::Data::~Data() { std::for_each(std::begin(delegate_state_cache), std::end(delegate_state_cache), [](const std::pair<int, NNAPIDelegateKernel*>& entry) { delete entry.second; }); } void StatefulNnApiDelegate::Data::CacheDelegateKernel( const TfLiteDelegateParams* delegate_params, NNAPIDelegateKernel* delegate_state) { const int cache_key = delegate_params->nodes_to_replace->data[0]; delegate_state_cache.emplace(cache_key, delegate_state); } NNAPIDelegateKernel* StatefulNnApiDelegate::Data::MaybeGetCachedDelegateKernel( const TfLiteDelegateParams* delegate_params) { const int cache_key = delegate_params->nodes_to_replace->data[0]; const auto cached_state = delegate_state_cache.find(cache_key); if (cached_state != std::end(delegate_state_cache)) { auto result = cached_state->second; delegate_state_cache.erase(cached_state); return result; } else { return nullptr; } } StatefulNnApiDelegate::StatefulNnApiDelegate(const NnApi* nnapi) : StatefulNnApiDelegate(nnapi, Options()) {} StatefulNnApiDelegate::StatefulNnApiDelegate(Options options) : StatefulNnApiDelegate(NnApiImplementation(), options) {} StatefulNnApiDelegate::StatefulNnApiDelegate(const NnApi* nnapi, Options options) : TfLiteDelegate(TfLiteDelegateCreate()), delegate_data_(nnapi) { if (options.accelerator_name) { delegate_data_.accelerator_name = options.accelerator_name; } if (options.cache_dir) { delegate_data_.cache_dir = options.cache_dir; } if (options.model_token) { delegate_data_.model_token = options.model_token; } delegate_data_.execution_preference = options.execution_preference; delegate_data_.disallow_nnapi_cpu = options.disallow_nnapi_cpu; delegate_data_.max_number_delegated_partitions = options.max_number_delegated_partitions; delegate_data_.allow_fp16 = options.allow_fp16; TFLITE_LOG_PROD_ONCE(tflite::TFLITE_LOG_INFO, "Created TensorFlow Lite delegate for NNAPI."); Prepare = DoPrepare; CopyFromBufferHandle = DoCopyFromBufferHandle; CopyToBufferHandle = DoCopyToBufferHandle; FreeBufferHandle = DoFreeBufferHandle; data_ = &delegate_data_; } StatefulNnApiDelegate::StatefulNnApiDelegate() : StatefulNnApiDelegate(Options()) {} const StatefulNnApiDelegate::Options StatefulNnApiDelegate::GetOptions( TfLiteDelegate* delegate) { auto delegate_data = reinterpret_cast<Data*>(delegate->data_); StatefulNnApiDelegate::Options options; options.execution_preference = delegate_data->execution_preference; options.accelerator_name = delegate_data->accelerator_name.empty() // ? nullptr ? "vsi-npu" : delegate_data->accelerator_name.c_str(); options.cache_dir = delegate_data->cache_dir.empty() ? nullptr : delegate_data->cache_dir.c_str(); options.model_token = delegate_data->model_token.empty() ? nullptr : delegate_data->model_token.c_str(); options.disallow_nnapi_cpu = delegate_data->disallow_nnapi_cpu; options.max_number_delegated_partitions = delegate_data->max_number_delegated_partitions; options.allow_fp16 = delegate_data->allow_fp16; return options; } const std::vector<StatefulNnApiDelegate::MemoryRegistration>& StatefulNnApiDelegate::GetTensorMemoryMap(TfLiteDelegate* delegate) { auto delegate_data = reinterpret_cast<Data*>(delegate->data_); return delegate_data->tensor_memory_map; } TfLiteBufferHandle StatefulNnApiDelegate::RegisterNnapiMemory( ANeuralNetworksMemory* memory, CopyToHostTensorFnPtr callback, void* callback_context) { int map_size = delegate_data_.tensor_memory_map.size(); for (int i = 0; i < map_size; i++) { if (delegate_data_.tensor_memory_map[i].memory == nullptr) { delegate_data_.tensor_memory_map[i] = {memory, callback, callback_context}; return i; } } delegate_data_.tensor_memory_map.push_back( {memory, callback, callback_context}); return map_size; } TfLiteStatus StatefulNnApiDelegate::DoCopyFromBufferHandle( TfLiteContext* context, TfLiteDelegate* delegate, TfLiteBufferHandle buffer_handle, TfLiteTensor* tensor) { auto delegate_data = reinterpret_cast<Data*>(delegate->data_); if (buffer_handle < 0 || buffer_handle >= delegate_data->tensor_memory_map.size()) { return kTfLiteError; } auto memory = delegate_data->tensor_memory_map[buffer_handle].memory; auto callback = delegate_data->tensor_memory_map[buffer_handle].callback; auto callback_context = delegate_data->tensor_memory_map[buffer_handle].callback_context; if (!memory || !callback) { return kTfLiteError; } return callback(tensor, memory, 0, tensor->bytes, callback_context); } TfLiteStatus StatefulNnApiDelegate::DoCopyToBufferHandle( TfLiteContext* context, TfLiteDelegate* delegate, TfLiteBufferHandle buffer_handle, TfLiteTensor* tensor) { return kTfLiteError; } void StatefulNnApiDelegate::DoFreeBufferHandle(TfLiteContext* context, TfLiteDelegate* delegate, TfLiteBufferHandle* handle) { auto delegate_data = reinterpret_cast<Data*>(delegate->data_); if (*handle >= 0 && *handle < delegate_data->tensor_memory_map.size()) { delegate_data->tensor_memory_map[*handle] = {nullptr, nullptr, nullptr}; *handle = kTfLiteNullBufferHandle; } } int StatefulNnApiDelegate::GetNnApiErrno() const { return delegate_data_.nnapi_errno; } using ::tflite::delegate::nnapi::kMinSdkVersionForNNAPI; using ::tflite::delegate::nnapi::kMinSdkVersionForNNAPI12; // static TfLiteStatus StatefulNnApiDelegate::GetNodesSupportedByAccelerator( TfLiteContext* context, TfLiteDelegate* delegate, const NnApi* nnapi, const std::vector<int>& supported_nodes, std::vector<int>* device_supported_nodes, int* num_partitions, TfLiteDelegateParams** params_array, int* nnapi_errno) { auto* delegate_data = static_cast<Data*>(delegate->data_); // The first entry in the array is the element count auto supported_nodes_int_array = BuildTfLiteIntArray(supported_nodes); TF_LITE_ENSURE_STATUS(context->PreviewDelegatePartitioning( context, supported_nodes_int_array.get(), params_array, num_partitions)); // For each partition check if which nodes are actually supported by the // target accelerators. delegate_data->delegate_state_cache.clear(); for (int idx = 0; idx < *num_partitions; idx++) { const auto& partition_params = (*params_array)[idx]; std::unique_ptr<NNAPIDelegateKernel> kernel_state( new NNAPIDelegateKernel(nnapi)); TfLiteDelegateParams params_with_delegate = partition_params; params_with_delegate.delegate = delegate; TF_LITE_ENSURE_STATUS( kernel_state->Init(context, &params_with_delegate, nnapi_errno)); std::vector<int> supported_partition_nodes; TF_LITE_ENSURE_STATUS( kernel_state->GetOperationsSupportedByTargetNnApiDevices( context, &supported_partition_nodes, nnapi_errno)); device_supported_nodes->insert(device_supported_nodes->end(), supported_partition_nodes.begin(), supported_partition_nodes.end()); bool model_fully_supported = (supported_partition_nodes.size() == partition_params.nodes_to_replace->size); if (model_fully_supported) { delegate_data->CacheDelegateKernel(&partition_params, kernel_state.release()); } } if (device_supported_nodes->size() != supported_nodes.size()) { // We changed the set of nodes to delegate this will create a different // partitioning layout. auto device_sup_nodes_int_array = BuildTfLiteIntArray(*device_supported_nodes); TF_LITE_ENSURE_STATUS(context->PreviewDelegatePartitioning( context, device_sup_nodes_int_array.get(), params_array, num_partitions)); } return kTfLiteOk; } // static TfLiteStatus StatefulNnApiDelegate::LimitDelegatedPartitions( int max_partitions, std::vector<TfLiteDelegateParams> partition_params_array, std::vector<int>* nodes_to_delegate) { int num_partitions = partition_params_array.size(); if (max_partitions <= 0 || num_partitions <= max_partitions) { return kTfLiteOk; } int number_delegated_partitions = std::count_if( partition_params_array.begin(), partition_params_array.end(), [nodes_to_delegate](const TfLiteDelegateParams& partition_params) { return std::find(nodes_to_delegate->begin(), nodes_to_delegate->end(), partition_params.nodes_to_replace->data[0]) != nodes_to_delegate->end(); }); if (number_delegated_partitions > max_partitions) { std::sort(partition_params_array.begin(), partition_params_array.end(), [](const TfLiteDelegateParams& left, const TfLiteDelegateParams& right) -> bool { // Reverse sort return left.nodes_to_replace->size > right.nodes_to_replace->size; }); nodes_to_delegate->clear(); for (int i = 0; i < max_partitions; i++) { const TfLiteDelegateParams& partition_params = partition_params_array[i]; nodes_to_delegate->insert(nodes_to_delegate->end(), partition_params.nodes_to_replace->data, partition_params.nodes_to_replace->data + partition_params.nodes_to_replace->size); } } return kTfLiteOk; } TfLiteStatus StatefulNnApiDelegate::DoPrepare(TfLiteContext* context, TfLiteDelegate* delegate) { auto* delegate_data = static_cast<Data*>(delegate->data_); int* nnapi_errno = &(delegate_data->nnapi_errno); const NnApi* nnapi = delegate_data->nnapi; // Resetting the error code when the delegate is initialized // by TFLite. This causes the error to be reset if reusing the same // StatefulNnApiDelegate after a failure *nnapi_errno = 0; // Do not check nodes_ if NN API is unavailable. if (nnapi->android_sdk_version < kMinSdkVersionForNNAPI || !nnapi->nnapi_exists) { return kTfLiteOk; } int target_sdk_version = nnapi->android_sdk_version; const StatefulNnApiDelegate::Options delegate_options = StatefulNnApiDelegate::GetOptions(delegate); // For NNAPI 1.2+, check if there is any accelerator available. // If not, don't delegate to NNAPI's CPU reference implementation unless // it has been specified as target accelerator. if (nnapi->android_sdk_version >= kMinSdkVersionForNNAPI12) { if (ShouldUseTargetDevices(delegate_options)) { std::vector<ANeuralNetworksDevice*> devices; TF_LITE_ENSURE_STATUS( GetTargetDevices(context, delegate, nnapi, nnapi_errno, &devices)); if (devices.empty()) { if (delegate_options.accelerator_name) { // There was a selected device and it is not available. return kTfLiteError; } else { // Only nnapi-reference is available but was disabled by the delegate // options return kTfLiteOk; } } TF_LITE_ENSURE_STATUS(GetTargetSdkVersion( context, nnapi, devices, &target_sdk_version, nnapi_errno)); } else { // If no accelerator is specified, only use NNAPI if an accelerator is // available. Any available accelerator will make the device_count larger // than 1. More sophisticated check and whitelisting can be added later. uint32_t device_count = 0; RETURN_TFLITE_ERROR_IF_NN_ERROR( context, nnapi->ANeuralNetworks_getDeviceCount(&device_count), "getting number of NNAPI devices", nnapi_errno); if (device_count <= 1) { return kTfLiteOk; } } } std::vector<int> supported_nodes; // We don't care about all nodes_, we only care about ones in the // current plan. TfLiteIntArray* plan; TF_LITE_ENSURE_STATUS(context->GetExecutionPlan(context, &plan)); // Check for every node if it is supported const bool is_accelerator_specified = ShouldUseTargetDevices( delegate_options, /*exclude_nnapi_reference=*/true); for (int node_index : TfLiteIntArrayView(plan)) { TfLiteNode* node; TfLiteRegistration* registration; TF_LITE_ENSURE_STATUS(context->GetNodeAndRegistration( context, node_index, &node, &registration)); if (NNAPIDelegateKernel::Validate(context, registration->builtin_code, registration->version, target_sdk_version, node, is_accelerator_specified)) { supported_nodes.push_back(node_index); } } // If there are no delegated nodes, short-circuit node replacement. if (supported_nodes.empty()) { return kTfLiteOk; } // NN API Delegate Registration (the pseudo kernel that will invoke NN // API node sub sets) static const TfLiteRegistration nnapi_delegate_kernel = { .init = [](TfLiteContext* context, const char* buffer, size_t length) -> void* { const TfLiteDelegateParams* params = reinterpret_cast<const TfLiteDelegateParams*>(buffer); auto* delegate_data = static_cast<Data*>(params->delegate->data_); int* nnapi_errno = &(delegate_data->nnapi_errno); NNAPIDelegateKernel* kernel_state = delegate_data->MaybeGetCachedDelegateKernel(params); if (!kernel_state) { kernel_state = new NNAPIDelegateKernel(delegate_data->nnapi); kernel_state->Init(context, params, nnapi_errno); } return kernel_state; }, .free = [](TfLiteContext* context, void* buffer) -> void { delete reinterpret_cast<NNAPIDelegateKernel*>(buffer); }, .prepare = [](TfLiteContext* context, TfLiteNode* node) -> TfLiteStatus { NNAPIDelegateKernel* state = reinterpret_cast<NNAPIDelegateKernel*>(node->user_data); int* nnapi_errno = &(static_cast<Data*>(node->delegate->data_)->nnapi_errno); return state->Prepare(context, node, nnapi_errno); }, .invoke = [](TfLiteContext* context, TfLiteNode* node) -> TfLiteStatus { NNAPIDelegateKernel* state = reinterpret_cast<NNAPIDelegateKernel*>(node->user_data); int* nnapi_errno = &(static_cast<Data*>(node->delegate->data_)->nnapi_errno); return state->Invoke(context, node, nnapi_errno); }, .profiling_string = nullptr, .builtin_code = kTfLiteBuiltinDelegate, .custom_name = "TfLiteNnapiDelegate", .version = 1, }; std::vector<int> nodes_to_delegate; int num_partitions; TfLiteDelegateParams* params_array; if (is_accelerator_specified && nnapi->android_sdk_version >= kMinSdkVersionForNNAPI12) { // Filtering out nodes not supported by target accelerators. // Cannot query supported operation before NNAPI 1.2 TF_LITE_ENSURE_STATUS(GetNodesSupportedByAccelerator( context, delegate, nnapi, supported_nodes, &nodes_to_delegate, &num_partitions, &params_array, nnapi_errno)); } else { nodes_to_delegate = supported_nodes; auto supported_nodes_int_array = BuildTfLiteIntArray(supported_nodes); TF_LITE_ENSURE_STATUS(context->PreviewDelegatePartitioning( context, supported_nodes_int_array.get(), &params_array, &num_partitions)); } TF_LITE_ENSURE_STATUS( LimitDelegatedPartitions(delegate_options.max_number_delegated_partitions, std::vector<TfLiteDelegateParams>( params_array, params_array + num_partitions), &nodes_to_delegate)); if (nodes_to_delegate.empty()) { return kTfLiteOk; } else { // Request TFLite to partition the graph and make kernels // for each independent node sub set a new nnapi_delegate_kernel. auto nodes_to_delegate_int_array = BuildTfLiteIntArray(nodes_to_delegate); return context->ReplaceNodeSubsetsWithDelegateKernels( context, nnapi_delegate_kernel, nodes_to_delegate_int_array.get(), delegate); } } // Returns a singleton NNAPI Delegate that can check for support of ops. TfLiteDelegate* NnApiDelegate() { static StatefulNnApiDelegate* delegate = new StatefulNnApiDelegate(); return delegate; } } // namespace tflite
//===---- MachO_arm64.cpp - JIT linker implementation for MachO/arm64 -----===// // // 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 // //===----------------------------------------------------------------------===// // // MachO/arm64 jit-link implementation. // //===----------------------------------------------------------------------===// #include "llvm/ExecutionEngine/JITLink/MachO_arm64.h" #include "MachOLinkGraphBuilder.h" #include "PerGraphGOTAndPLTStubsBuilder.h" #define DEBUG_TYPE "jitlink" using namespace llvm; using namespace llvm::jitlink; using namespace llvm::jitlink::MachO_arm64_Edges; namespace { class MachOLinkGraphBuilder_arm64 : public MachOLinkGraphBuilder { public: MachOLinkGraphBuilder_arm64(const object::MachOObjectFile &Obj) : MachOLinkGraphBuilder(Obj, Triple("arm64-apple-darwin"), getMachOARM64RelocationKindName), NumSymbols(Obj.getSymtabLoadCommand().nsyms) {} private: static Expected<MachOARM64RelocationKind> getRelocationKind(const MachO::relocation_info &RI) { switch (RI.r_type) { case MachO::ARM64_RELOC_UNSIGNED: if (!RI.r_pcrel) { if (RI.r_length == 3) return RI.r_extern ? Pointer64 : Pointer64Anon; else if (RI.r_length == 2) return Pointer32; } break; case MachO::ARM64_RELOC_SUBTRACTOR: // SUBTRACTOR must be non-pc-rel, extern, with length 2 or 3. // Initially represent SUBTRACTOR relocations with 'Delta<W>'. // They may be turned into NegDelta<W> by parsePairRelocation. if (!RI.r_pcrel && RI.r_extern) { if (RI.r_length == 2) return Delta32; else if (RI.r_length == 3) return Delta64; } break; case MachO::ARM64_RELOC_BRANCH26: if (RI.r_pcrel && RI.r_extern && RI.r_length == 2) return Branch26; break; case MachO::ARM64_RELOC_PAGE21: if (RI.r_pcrel && RI.r_extern && RI.r_length == 2) return Page21; break; case MachO::ARM64_RELOC_PAGEOFF12: if (!RI.r_pcrel && RI.r_extern && RI.r_length == 2) return PageOffset12; break; case MachO::ARM64_RELOC_GOT_LOAD_PAGE21: if (RI.r_pcrel && RI.r_extern && RI.r_length == 2) return GOTPage21; break; case MachO::ARM64_RELOC_GOT_LOAD_PAGEOFF12: if (!RI.r_pcrel && RI.r_extern && RI.r_length == 2) return GOTPageOffset12; break; case MachO::ARM64_RELOC_POINTER_TO_GOT: if (RI.r_pcrel && RI.r_extern && RI.r_length == 2) return PointerToGOT; break; case MachO::ARM64_RELOC_ADDEND: if (!RI.r_pcrel && !RI.r_extern && RI.r_length == 2) return PairedAddend; break; } return make_error<JITLinkError>( "Unsupported arm64 relocation: address=" + formatv("{0:x8}", RI.r_address) + ", symbolnum=" + formatv("{0:x6}", RI.r_symbolnum) + ", kind=" + formatv("{0:x1}", RI.r_type) + ", pc_rel=" + (RI.r_pcrel ? "true" : "false") + ", extern=" + (RI.r_extern ? "true" : "false") + ", length=" + formatv("{0:d}", RI.r_length)); } using PairRelocInfo = std::tuple<MachOARM64RelocationKind, Symbol *, uint64_t>; // Parses paired SUBTRACTOR/UNSIGNED relocations and, on success, // returns the edge kind and addend to be used. Expected<PairRelocInfo> parsePairRelocation(Block &BlockToFix, Edge::Kind SubtractorKind, const MachO::relocation_info &SubRI, JITTargetAddress FixupAddress, const char *FixupContent, object::relocation_iterator &UnsignedRelItr, object::relocation_iterator &RelEnd) { using namespace support; assert(((SubtractorKind == Delta32 && SubRI.r_length == 2) || (SubtractorKind == Delta64 && SubRI.r_length == 3)) && "Subtractor kind should match length"); assert(SubRI.r_extern && "SUBTRACTOR reloc symbol should be extern"); assert(!SubRI.r_pcrel && "SUBTRACTOR reloc should not be PCRel"); if (UnsignedRelItr == RelEnd) return make_error<JITLinkError>("arm64 SUBTRACTOR without paired " "UNSIGNED relocation"); auto UnsignedRI = getRelocationInfo(UnsignedRelItr); if (SubRI.r_address != UnsignedRI.r_address) return make_error<JITLinkError>("arm64 SUBTRACTOR and paired UNSIGNED " "point to different addresses"); if (SubRI.r_length != UnsignedRI.r_length) return make_error<JITLinkError>("length of arm64 SUBTRACTOR and paired " "UNSIGNED reloc must match"); Symbol *FromSymbol; if (auto FromSymbolOrErr = findSymbolByIndex(SubRI.r_symbolnum)) FromSymbol = FromSymbolOrErr->GraphSymbol; else return FromSymbolOrErr.takeError(); // Read the current fixup value. uint64_t FixupValue = 0; if (SubRI.r_length == 3) FixupValue = *(const little64_t *)FixupContent; else FixupValue = *(const little32_t *)FixupContent; // Find 'ToSymbol' using symbol number or address, depending on whether the // paired UNSIGNED relocation is extern. Symbol *ToSymbol = nullptr; if (UnsignedRI.r_extern) { // Find target symbol by symbol index. if (auto ToSymbolOrErr = findSymbolByIndex(UnsignedRI.r_symbolnum)) ToSymbol = ToSymbolOrErr->GraphSymbol; else return ToSymbolOrErr.takeError(); } else { auto ToSymbolSec = findSectionByIndex(UnsignedRI.r_symbolnum - 1); if (!ToSymbolSec) return ToSymbolSec.takeError(); ToSymbol = getSymbolByAddress(ToSymbolSec->Address); assert(ToSymbol && "No symbol for section"); FixupValue -= ToSymbol->getAddress(); } MachOARM64RelocationKind DeltaKind; Symbol *TargetSymbol; uint64_t Addend; if (&BlockToFix == &FromSymbol->getAddressable()) { TargetSymbol = ToSymbol; DeltaKind = (SubRI.r_length == 3) ? Delta64 : Delta32; Addend = FixupValue + (FixupAddress - FromSymbol->getAddress()); // FIXME: handle extern 'from'. } else if (&BlockToFix == &ToSymbol->getAddressable()) { TargetSymbol = &*FromSymbol; DeltaKind = (SubRI.r_length == 3) ? NegDelta64 : NegDelta32; Addend = FixupValue - (FixupAddress - ToSymbol->getAddress()); } else { // BlockToFix was neither FromSymbol nor ToSymbol. return make_error<JITLinkError>("SUBTRACTOR relocation must fix up " "either 'A' or 'B' (or a symbol in one " "of their alt-entry groups)"); } return PairRelocInfo(DeltaKind, TargetSymbol, Addend); } Error addRelocations() override { using namespace support; auto &Obj = getObject(); LLVM_DEBUG(dbgs() << "Processing relocations:\n"); for (auto &S : Obj.sections()) { JITTargetAddress SectionAddress = S.getAddress(); // Skip relocations virtual sections. if (S.isVirtual()) { if (S.relocation_begin() != S.relocation_end()) return make_error<JITLinkError>("Virtual section contains " "relocations"); continue; } // Skip relocations for debug symbols. { auto &NSec = getSectionByIndex(Obj.getSectionIndex(S.getRawDataRefImpl())); if (!NSec.GraphSection) { LLVM_DEBUG({ dbgs() << " Skipping relocations for MachO section " << NSec.SegName << "/" << NSec.SectName << " which has no associated graph section\n"; }); continue; } } for (auto RelItr = S.relocation_begin(), RelEnd = S.relocation_end(); RelItr != RelEnd; ++RelItr) { MachO::relocation_info RI = getRelocationInfo(RelItr); // Sanity check the relocation kind. auto Kind = getRelocationKind(RI); if (!Kind) return Kind.takeError(); // Find the address of the value to fix up. JITTargetAddress FixupAddress = SectionAddress + (uint32_t)RI.r_address; LLVM_DEBUG({ auto &NSec = getSectionByIndex(Obj.getSectionIndex(S.getRawDataRefImpl())); dbgs() << " " << NSec.SectName << " + " << formatv("{0:x8}", RI.r_address) << ":\n"; }); // Find the block that the fixup points to. Block *BlockToFix = nullptr; { auto SymbolToFixOrErr = findSymbolByAddress(FixupAddress); if (!SymbolToFixOrErr) return SymbolToFixOrErr.takeError(); BlockToFix = &SymbolToFixOrErr->getBlock(); } if (FixupAddress + static_cast<JITTargetAddress>(1ULL << RI.r_length) > BlockToFix->getAddress() + BlockToFix->getContent().size()) return make_error<JITLinkError>( "Relocation content extends past end of fixup block"); // Get a pointer to the fixup content. const char *FixupContent = BlockToFix->getContent().data() + (FixupAddress - BlockToFix->getAddress()); // The target symbol and addend will be populated by the switch below. Symbol *TargetSymbol = nullptr; uint64_t Addend = 0; if (*Kind == PairedAddend) { // If this is an Addend relocation then process it and move to the // paired reloc. Addend = SignExtend64(RI.r_symbolnum, 24); if (RelItr == RelEnd) return make_error<JITLinkError>("Unpaired Addend reloc at " + formatv("{0:x16}", FixupAddress)); ++RelItr; RI = getRelocationInfo(RelItr); Kind = getRelocationKind(RI); if (!Kind) return Kind.takeError(); if (*Kind != Branch26 && *Kind != Page21 && *Kind != PageOffset12) return make_error<JITLinkError>( "Invalid relocation pair: Addend + " + StringRef(getMachOARM64RelocationKindName(*Kind))); LLVM_DEBUG({ dbgs() << " Addend: value = " << formatv("{0:x6}", Addend) << ", pair is " << getMachOARM64RelocationKindName(*Kind) << "\n"; }); // Find the address of the value to fix up. JITTargetAddress PairedFixupAddress = SectionAddress + (uint32_t)RI.r_address; if (PairedFixupAddress != FixupAddress) return make_error<JITLinkError>("Paired relocation points at " "different target"); } switch (*Kind) { case Branch26: { if (auto TargetSymbolOrErr = findSymbolByIndex(RI.r_symbolnum)) TargetSymbol = TargetSymbolOrErr->GraphSymbol; else return TargetSymbolOrErr.takeError(); uint32_t Instr = *(const ulittle32_t *)FixupContent; if ((Instr & 0x7fffffff) != 0x14000000) return make_error<JITLinkError>("BRANCH26 target is not a B or BL " "instruction with a zero addend"); break; } case Pointer32: if (auto TargetSymbolOrErr = findSymbolByIndex(RI.r_symbolnum)) TargetSymbol = TargetSymbolOrErr->GraphSymbol; else return TargetSymbolOrErr.takeError(); Addend = *(const ulittle32_t *)FixupContent; break; case Pointer64: if (auto TargetSymbolOrErr = findSymbolByIndex(RI.r_symbolnum)) TargetSymbol = TargetSymbolOrErr->GraphSymbol; else return TargetSymbolOrErr.takeError(); Addend = *(const ulittle64_t *)FixupContent; break; case Pointer64Anon: { JITTargetAddress TargetAddress = *(const ulittle64_t *)FixupContent; if (auto TargetSymbolOrErr = findSymbolByAddress(TargetAddress)) TargetSymbol = &*TargetSymbolOrErr; else return TargetSymbolOrErr.takeError(); Addend = TargetAddress - TargetSymbol->getAddress(); break; } case Page21: case GOTPage21: { if (auto TargetSymbolOrErr = findSymbolByIndex(RI.r_symbolnum)) TargetSymbol = TargetSymbolOrErr->GraphSymbol; else return TargetSymbolOrErr.takeError(); uint32_t Instr = *(const ulittle32_t *)FixupContent; if ((Instr & 0xffffffe0) != 0x90000000) return make_error<JITLinkError>("PAGE21/GOTPAGE21 target is not an " "ADRP instruction with a zero " "addend"); break; } case PageOffset12: { if (auto TargetSymbolOrErr = findSymbolByIndex(RI.r_symbolnum)) TargetSymbol = TargetSymbolOrErr->GraphSymbol; else return TargetSymbolOrErr.takeError(); uint32_t Instr = *(const ulittle32_t *)FixupContent; uint32_t EncodedAddend = (Instr & 0x003FFC00) >> 10; if (EncodedAddend != 0) return make_error<JITLinkError>("GOTPAGEOFF12 target has non-zero " "encoded addend"); break; } case GOTPageOffset12: { if (auto TargetSymbolOrErr = findSymbolByIndex(RI.r_symbolnum)) TargetSymbol = TargetSymbolOrErr->GraphSymbol; else return TargetSymbolOrErr.takeError(); uint32_t Instr = *(const ulittle32_t *)FixupContent; if ((Instr & 0xfffffc00) != 0xf9400000) return make_error<JITLinkError>("GOTPAGEOFF12 target is not an LDR " "immediate instruction with a zero " "addend"); break; } case PointerToGOT: if (auto TargetSymbolOrErr = findSymbolByIndex(RI.r_symbolnum)) TargetSymbol = TargetSymbolOrErr->GraphSymbol; else return TargetSymbolOrErr.takeError(); break; case Delta32: case Delta64: { // We use Delta32/Delta64 to represent SUBTRACTOR relocations. // parsePairRelocation handles the paired reloc, and returns the // edge kind to be used (either Delta32/Delta64, or // NegDelta32/NegDelta64, depending on the direction of the // subtraction) along with the addend. auto PairInfo = parsePairRelocation(*BlockToFix, *Kind, RI, FixupAddress, FixupContent, ++RelItr, RelEnd); if (!PairInfo) return PairInfo.takeError(); std::tie(*Kind, TargetSymbol, Addend) = *PairInfo; assert(TargetSymbol && "No target symbol from parsePairRelocation?"); break; } default: llvm_unreachable("Special relocation kind should not appear in " "mach-o file"); } LLVM_DEBUG({ dbgs() << " "; Edge GE(*Kind, FixupAddress - BlockToFix->getAddress(), *TargetSymbol, Addend); printEdge(dbgs(), *BlockToFix, GE, getMachOARM64RelocationKindName(*Kind)); dbgs() << "\n"; }); BlockToFix->addEdge(*Kind, FixupAddress - BlockToFix->getAddress(), *TargetSymbol, Addend); } } return Error::success(); } unsigned NumSymbols = 0; }; class PerGraphGOTAndPLTStubsBuilder_MachO_arm64 : public PerGraphGOTAndPLTStubsBuilder< PerGraphGOTAndPLTStubsBuilder_MachO_arm64> { public: using PerGraphGOTAndPLTStubsBuilder< PerGraphGOTAndPLTStubsBuilder_MachO_arm64>::PerGraphGOTAndPLTStubsBuilder; bool isGOTEdgeToFix(Edge &E) const { return (E.getKind() == GOTPage21 || E.getKind() == GOTPageOffset12 || E.getKind() == PointerToGOT) && E.getTarget().isExternal(); } Symbol &createGOTEntry(Symbol &Target) { auto &GOTEntryBlock = G.createContentBlock( getGOTSection(), getGOTEntryBlockContent(), 0, 8, 0); GOTEntryBlock.addEdge(Pointer64, 0, Target, 0); return G.addAnonymousSymbol(GOTEntryBlock, 0, 8, false, false); } void fixGOTEdge(Edge &E, Symbol &GOTEntry) { if (E.getKind() == GOTPage21 || E.getKind() == GOTPageOffset12) { // Update the target, but leave the edge addend as-is. E.setTarget(GOTEntry); } else if (E.getKind() == PointerToGOT) { E.setTarget(GOTEntry); E.setKind(Delta32); } else llvm_unreachable("Not a GOT edge?"); } bool isExternalBranchEdge(Edge &E) { return E.getKind() == Branch26 && !E.getTarget().isDefined(); } Symbol &createPLTStub(Symbol &Target) { auto &StubContentBlock = G.createContentBlock(getStubsSection(), getStubBlockContent(), 0, 1, 0); // Re-use GOT entries for stub targets. auto &GOTEntrySymbol = getGOTEntry(Target); StubContentBlock.addEdge(LDRLiteral19, 0, GOTEntrySymbol, 0); return G.addAnonymousSymbol(StubContentBlock, 0, 8, true, false); } void fixPLTEdge(Edge &E, Symbol &Stub) { assert(E.getKind() == Branch26 && "Not a Branch32 edge?"); assert(E.getAddend() == 0 && "Branch32 edge has non-zero addend?"); E.setTarget(Stub); } private: Section &getGOTSection() { if (!GOTSection) GOTSection = &G.createSection("$__GOT", sys::Memory::MF_READ); return *GOTSection; } Section &getStubsSection() { if (!StubsSection) { auto StubsProt = static_cast<sys::Memory::ProtectionFlags>( sys::Memory::MF_READ | sys::Memory::MF_EXEC); StubsSection = &G.createSection("$__STUBS", StubsProt); } return *StubsSection; } ArrayRef<char> getGOTEntryBlockContent() { return {reinterpret_cast<const char *>(NullGOTEntryContent), sizeof(NullGOTEntryContent)}; } ArrayRef<char> getStubBlockContent() { return {reinterpret_cast<const char *>(StubContent), sizeof(StubContent)}; } static const uint8_t NullGOTEntryContent[8]; static const uint8_t StubContent[8]; Section *GOTSection = nullptr; Section *StubsSection = nullptr; }; const uint8_t PerGraphGOTAndPLTStubsBuilder_MachO_arm64::NullGOTEntryContent[8] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; const uint8_t PerGraphGOTAndPLTStubsBuilder_MachO_arm64::StubContent[8] = { 0x10, 0x00, 0x00, 0x58, // LDR x16, <literal> 0x00, 0x02, 0x1f, 0xd6 // BR x16 }; } // namespace namespace llvm { namespace jitlink { class MachOJITLinker_arm64 : public JITLinker<MachOJITLinker_arm64> { friend class JITLinker<MachOJITLinker_arm64>; public: MachOJITLinker_arm64(std::unique_ptr<JITLinkContext> Ctx, std::unique_ptr<LinkGraph> G, PassConfiguration PassConfig) : JITLinker(std::move(Ctx), std::move(G), std::move(PassConfig)) {} private: static unsigned getPageOffset12Shift(uint32_t Instr) { constexpr uint32_t LoadStoreImm12Mask = 0x3b000000; constexpr uint32_t Vec128Mask = 0x04800000; if ((Instr & LoadStoreImm12Mask) == 0x39000000) { uint32_t ImplicitShift = Instr >> 30; if (ImplicitShift == 0) if ((Instr & Vec128Mask) == Vec128Mask) ImplicitShift = 4; return ImplicitShift; } return 0; } Error applyFixup(LinkGraph &G, Block &B, const Edge &E, char *BlockWorkingMem) const { using namespace support; char *FixupPtr = BlockWorkingMem + E.getOffset(); JITTargetAddress FixupAddress = B.getAddress() + E.getOffset(); switch (E.getKind()) { case Branch26: { assert((FixupAddress & 0x3) == 0 && "Branch-inst is not 32-bit aligned"); int64_t Value = E.getTarget().getAddress() - FixupAddress + E.getAddend(); if (static_cast<uint64_t>(Value) & 0x3) return make_error<JITLinkError>("Branch26 target is not 32-bit " "aligned"); if (Value < -(1 << 27) || Value > ((1 << 27) - 1)) return makeTargetOutOfRangeError(G, B, E); uint32_t RawInstr = *(little32_t *)FixupPtr; assert((RawInstr & 0x7fffffff) == 0x14000000 && "RawInstr isn't a B or BR immediate instruction"); uint32_t Imm = (static_cast<uint32_t>(Value) & ((1 << 28) - 1)) >> 2; uint32_t FixedInstr = RawInstr | Imm; *(little32_t *)FixupPtr = FixedInstr; break; } case Pointer32: { uint64_t Value = E.getTarget().getAddress() + E.getAddend(); if (Value > std::numeric_limits<uint32_t>::max()) return makeTargetOutOfRangeError(G, B, E); *(ulittle32_t *)FixupPtr = Value; break; } case Pointer64: case Pointer64Anon: { uint64_t Value = E.getTarget().getAddress() + E.getAddend(); *(ulittle64_t *)FixupPtr = Value; break; } case Page21: case GOTPage21: { assert((E.getKind() != GOTPage21 || E.getAddend() == 0) && "GOTPAGE21 with non-zero addend"); uint64_t TargetPage = (E.getTarget().getAddress() + E.getAddend()) & ~static_cast<uint64_t>(4096 - 1); uint64_t PCPage = FixupAddress & ~static_cast<uint64_t>(4096 - 1); int64_t PageDelta = TargetPage - PCPage; if (PageDelta < -(1 << 30) || PageDelta > ((1 << 30) - 1)) return makeTargetOutOfRangeError(G, B, E); uint32_t RawInstr = *(ulittle32_t *)FixupPtr; assert((RawInstr & 0xffffffe0) == 0x90000000 && "RawInstr isn't an ADRP instruction"); uint32_t ImmLo = (static_cast<uint64_t>(PageDelta) >> 12) & 0x3; uint32_t ImmHi = (static_cast<uint64_t>(PageDelta) >> 14) & 0x7ffff; uint32_t FixedInstr = RawInstr | (ImmLo << 29) | (ImmHi << 5); *(ulittle32_t *)FixupPtr = FixedInstr; break; } case PageOffset12: { uint64_t TargetOffset = (E.getTarget().getAddress() + E.getAddend()) & 0xfff; uint32_t RawInstr = *(ulittle32_t *)FixupPtr; unsigned ImmShift = getPageOffset12Shift(RawInstr); if (TargetOffset & ((1 << ImmShift) - 1)) return make_error<JITLinkError>("PAGEOFF12 target is not aligned"); uint32_t EncodedImm = (TargetOffset >> ImmShift) << 10; uint32_t FixedInstr = RawInstr | EncodedImm; *(ulittle32_t *)FixupPtr = FixedInstr; break; } case GOTPageOffset12: { assert(E.getAddend() == 0 && "GOTPAGEOF12 with non-zero addend"); uint32_t RawInstr = *(ulittle32_t *)FixupPtr; assert((RawInstr & 0xfffffc00) == 0xf9400000 && "RawInstr isn't a 64-bit LDR immediate"); uint32_t TargetOffset = E.getTarget().getAddress() & 0xfff; assert((TargetOffset & 0x7) == 0 && "GOT entry is not 8-byte aligned"); uint32_t EncodedImm = (TargetOffset >> 3) << 10; uint32_t FixedInstr = RawInstr | EncodedImm; *(ulittle32_t *)FixupPtr = FixedInstr; break; } case LDRLiteral19: { assert((FixupAddress & 0x3) == 0 && "LDR is not 32-bit aligned"); assert(E.getAddend() == 0 && "LDRLiteral19 with non-zero addend"); uint32_t RawInstr = *(ulittle32_t *)FixupPtr; assert(RawInstr == 0x58000010 && "RawInstr isn't a 64-bit LDR literal"); int64_t Delta = E.getTarget().getAddress() - FixupAddress; if (Delta & 0x3) return make_error<JITLinkError>("LDR literal target is not 32-bit " "aligned"); if (Delta < -(1 << 20) || Delta > ((1 << 20) - 1)) return makeTargetOutOfRangeError(G, B, E); uint32_t EncodedImm = (static_cast<uint32_t>(Delta) >> 2) << 5; uint32_t FixedInstr = RawInstr | EncodedImm; *(ulittle32_t *)FixupPtr = FixedInstr; break; } case Delta32: case Delta64: case NegDelta32: case NegDelta64: { int64_t Value; if (E.getKind() == Delta32 || E.getKind() == Delta64) Value = E.getTarget().getAddress() - FixupAddress + E.getAddend(); else Value = FixupAddress - E.getTarget().getAddress() + E.getAddend(); if (E.getKind() == Delta32 || E.getKind() == NegDelta32) { if (Value < std::numeric_limits<int32_t>::min() || Value > std::numeric_limits<int32_t>::max()) return makeTargetOutOfRangeError(G, B, E); *(little32_t *)FixupPtr = Value; } else *(little64_t *)FixupPtr = Value; break; } default: llvm_unreachable("Unrecognized edge kind"); } return Error::success(); } uint64_t NullValue = 0; }; Expected<std::unique_ptr<LinkGraph>> createLinkGraphFromMachOObject_arm64(MemoryBufferRef ObjectBuffer) { auto MachOObj = object::ObjectFile::createMachOObjectFile(ObjectBuffer); if (!MachOObj) return MachOObj.takeError(); return MachOLinkGraphBuilder_arm64(**MachOObj).buildGraph(); } void link_MachO_arm64(std::unique_ptr<LinkGraph> G, std::unique_ptr<JITLinkContext> Ctx) { PassConfiguration Config; if (Ctx->shouldAddDefaultTargetPasses(G->getTargetTriple())) { // Add a mark-live pass. if (auto MarkLive = Ctx->getMarkLivePass(G->getTargetTriple())) Config.PrePrunePasses.push_back(std::move(MarkLive)); else Config.PrePrunePasses.push_back(markAllSymbolsLive); // Add an in-place GOT/Stubs pass. Config.PostPrunePasses.push_back( PerGraphGOTAndPLTStubsBuilder_MachO_arm64::asPass); } if (auto Err = Ctx->modifyPassConfig(*G, Config)) return Ctx->notifyFailed(std::move(Err)); // Construct a JITLinker and run the link function. MachOJITLinker_arm64::link(std::move(Ctx), std::move(G), std::move(Config)); } const char *getMachOARM64RelocationKindName(Edge::Kind R) { switch (R) { case Branch26: return "Branch26"; case Pointer64: return "Pointer64"; case Pointer64Anon: return "Pointer64Anon"; case Page21: return "Page21"; case PageOffset12: return "PageOffset12"; case GOTPage21: return "GOTPage21"; case GOTPageOffset12: return "GOTPageOffset12"; case PointerToGOT: return "PointerToGOT"; case PairedAddend: return "PairedAddend"; case LDRLiteral19: return "LDRLiteral19"; case Delta32: return "Delta32"; case Delta64: return "Delta64"; case NegDelta32: return "NegDelta32"; case NegDelta64: return "NegDelta64"; default: return getGenericEdgeKindName(static_cast<Edge::Kind>(R)); } } } // end namespace jitlink } // end namespace llvm
#pragma once #include <cstdint> namespace NWNXLib { namespace API { struct XIModifierState { int32_t base; int32_t latched; int32_t locked; int32_t effective; }; } }
#include <marnav/nmea/aam.hpp> #include <marnav/nmea/alm.hpp> #include <marnav/nmea/apb.hpp> #include <marnav/nmea/bod.hpp> #include <marnav/nmea/bwc.hpp> #include <marnav/nmea/bwr.hpp> #include <marnav/nmea/bww.hpp> #include <marnav/nmea/dbk.hpp> #include <marnav/nmea/dbt.hpp> #include <marnav/nmea/dpt.hpp> #include <marnav/nmea/dsc.hpp> #include <marnav/nmea/dse.hpp> #include <marnav/nmea/dtm.hpp> #include <marnav/nmea/fsi.hpp> #include <marnav/nmea/gbs.hpp> #include <marnav/nmea/gga.hpp> #include <marnav/nmea/glc.hpp> #include <marnav/nmea/gll.hpp> #include <marnav/nmea/gns.hpp> #include <marnav/nmea/grs.hpp> #include <marnav/nmea/gsa.hpp> #include <marnav/nmea/gst.hpp> #include <marnav/nmea/gsv.hpp> #include <marnav/nmea/gtd.hpp> #include <marnav/nmea/hdg.hpp> #include <marnav/nmea/hdm.hpp> #include <marnav/nmea/hfb.hpp> #include <marnav/nmea/hsc.hpp> #include <marnav/nmea/its.hpp> #include <marnav/nmea/lcd.hpp> #include <marnav/nmea/msk.hpp> #include <marnav/nmea/mss.hpp> #include <marnav/nmea/mtw.hpp> #include <marnav/nmea/mwd.hpp> #include <marnav/nmea/mwv.hpp> #include <marnav/nmea/nmea.hpp> #include <marnav/nmea/osd.hpp> #include <marnav/nmea/pgrme.hpp> #include <marnav/nmea/r00.hpp> #include <marnav/nmea/rma.hpp> #include <marnav/nmea/rmb.hpp> #include <marnav/nmea/rmc.hpp> #include <marnav/nmea/rot.hpp> #include <marnav/nmea/rpm.hpp> #include <marnav/nmea/rsa.hpp> #include <marnav/nmea/rsd.hpp> #include <marnav/nmea/rte.hpp> #include <marnav/nmea/sfi.hpp> #include <marnav/nmea/stn.hpp> #include <marnav/nmea/tds.hpp> #include <marnav/nmea/tfi.hpp> #include <marnav/nmea/tll.hpp> #include <marnav/nmea/tpc.hpp> #include <marnav/nmea/tpr.hpp> #include <marnav/nmea/tpt.hpp> #include <marnav/nmea/ttm.hpp> #include <marnav/nmea/vbw.hpp> #include <marnav/nmea/vdm.hpp> #include <marnav/nmea/vdo.hpp> #include <marnav/nmea/vdr.hpp> #include <marnav/nmea/vhw.hpp> #include <marnav/nmea/vlw.hpp> #include <marnav/nmea/vpw.hpp> #include <marnav/nmea/vtg.hpp> #include <marnav/nmea/vwr.hpp> #include <marnav/nmea/wcv.hpp> #include <marnav/nmea/wnc.hpp> #include <marnav/nmea/wpl.hpp> #include <marnav/nmea/xdr.hpp> #include <marnav/nmea/xte.hpp> #include <marnav/nmea/xtr.hpp> #include <marnav/nmea/zda.hpp> #include <marnav/nmea/zdl.hpp> #include <marnav/nmea/zfo.hpp> #include <marnav/nmea/ztg.hpp> #include <benchmark/benchmark.h> #include <algorithm> #include <typeindex> using namespace marnav; namespace { struct sentence_data { std::type_index type; std::string tag; std::string text; }; #define INFO(s, text) \ { \ std::type_index(typeid(nmea::s)), nmea::s::TAG, text \ } // clang-format off static std::vector<sentence_data> sentences = { INFO(aam, "$GPAAM,A,A,0.5,N,POINT1*6E"), INFO(alm, "$GPALM,1,1,15,1159,00,441d,4e,16be,fd5e,a10c9f,4a2da4,686e81,58cbe1,0a4,001*77"), INFO(apb, "$GPAPB,A,A,0.10,R,N,V,V,011,M,DEST,011,M,011,M*3C"), INFO(bod, "$GPBOD,12.5,T,,,,*12"), INFO(bwc, "$GPBWC,220516,5130.02,N,00046.34,W,213.8,T,218.0,M,0004.6,N,EGLM,A*4C"), INFO(bwr, "$GPBWR,220516,5130.02,N,00046.34,W,213.8,T,218.0,M,0004.6,N,EGLM*30"), INFO(bww, "$GPBWW,213.8,T,218.0,M,POINT1,POINT2*4C"), INFO(dbk, "$IIDBK,9.3,f,1.2,M,3.4,F*00"), INFO(dbt, "$IIDBT,9.3,f,2.84,M,1.55,F*14"), INFO(dpt, "$IIDPT,9.3,1.0*4B"), INFO(dsc, "$CDDSC,20,3380210040,00,21,26,1394807410,2242,,,B,E*71"), INFO(dse, "$CDDSE,1,1,A,3664251410,00,47800350*1D"), INFO(dtm, "$GPDTM,W84,,0.000000,N,0.000000,E,0.0,W84*6F"), INFO(fsi, "$GPFSI,156000,156025,,,*60"), INFO(gbs, "$GPGBS,123456.32,1.0,2.0,3.0,034,0.1,1.2,0.6*5A"), INFO(gga, "$GPGGA,123519,4807.038,N,01131.000,E,1,08,0.9,545.4,M,46.9,M,,*47"), INFO(glc, "$GPGLC,1,1,A,1,A,2,A,3,A,4,V,,*21"), INFO(gll, "$GPGLL,3553.5295,N,13938.6570,E,002454,A,A*4F"), INFO(gns, "$GNGNS,122310.0,3722.42567,N,12258.856215,W,AA,15,0.9,1005.54,6.5,,*75"), INFO(grs, "$GPGRS,024603.00,1,-1.8,-2.7,0.3,,,,,,,,,*6C"), INFO(gsa, "$GPGSA,A,3,07,08,09,11,18,23,26,28,29,,,,6.6,2.0,3.0*38"), INFO(gst, "$GPGST,123456.34,1.0,2.1,3.2,4.3,5.4,6.5,7.6*50"), INFO(gsv, "$GPGSV,3,1,09,07,29,138,44,08,22,099,42,09,30,273,44,11,07,057,35*75"), INFO(gtd, "$GPGTD,1.0,2.0,3.0,4.0,5.0*43"), INFO(hdg, "$HCHDG,45.8,,,0.6,E*16"), INFO(hfb, "$GPHFB,1.0,M,2.0,M*58"), INFO(hdm, "$HCHDM,45.8,M*10"), INFO(hsc, "$GPHSC,45.8,T,,*0C"), INFO(its, "$GPITS,1.0,M*3B"), INFO(lcd, "$GPLCD,1,001,000,001,000,002,000,003,000,004,000,,*44"), INFO(msk, "$GPMSK,123,A,110,M,321*52"), INFO(mss, "$GPMSS,12,34,123,456,1*44"), INFO(mtw, "$IIMTW,9.5,C*2F"), INFO(mwd, "$WIMWD,12.4,T,,,,,,*0D"), INFO(mwv, "$IIMWV,084.0,R,10.4,N,A*04"), INFO(osd, "$IIOSD,123.4,A,,,,,,,*1F"), INFO(r00, "$GPR00,EGLL,EGLM,EGTB,EGUB,EGTK,MBOT,EGTB,,,,,,,*58"), INFO(rma, "$GPRMA,,1234.9333,N,,,,,,,,*0B"), INFO(rmb, "$GPRMB,A,0.00,L,SIM001,SIM002,5102.6069,N,00500.0000,E,002.4,000.,021.7,V*0D"), INFO(rmc, "$GPRMC,201126,A,4702.3944,N,00818.3381,E,0.0,328.4,260807,0.6,E,A*1E"), INFO(rot, "$GPROT,1.0,A*30"), INFO(rpm, "$IIRPM,S,1,1800.0,5.0,A*7C"), INFO(rsa, "$IIRSA,1.0,A,,*2E"), INFO(rsd, "$IIRSD,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,A,A*47"), INFO(rte, "$GPRTE,1,1,c,*37"), INFO(sfi, "$GPSFI,1,1,156025,M*03"), INFO(stn, "$GPSTN,10*73"), INFO(tds, "$GPTDS,12.3,M*07"), INFO(tfi, "$GPTFI,0,1,2*53"), INFO(tll, "$GPTLL,00,0000.0000,N,00000.0000,E,,000000,T,*00"), INFO(tpc, "$GPTPC,1.0,M,2.0,M,3.0,M*33"), INFO(tpr, "$GPTPR,1.0,M,2.0,P,3.0,M*3F"), INFO(tpt, "$GPTPT,1.0,M,2.0,P,3.0,M*39"), INFO(ttm, "$GPTTM,,,,,,,,,,,,,*76"), INFO(vbw, "$IIVBW,1.0,-1.5,A,1.0,0.5,A*6F"), INFO(vdm, "!AIVDM,1,1,,B,177KQJ5000G?tO`K>RA1wUbN0TKH,0*5C"), INFO(vdo, "!AIVDO,1,1,,B,177KQJ5000G?tO`K>RA1wUbN0TKH,0*5E"), INFO(vdr, "$IIVDR,211.0,T,1.00,M,1.25,N*3C"), INFO(vhw, "$IIVHW,,T,211.0,M,0.00,N,0.00,K*79"), INFO(vlw, "$IIVLW,7803.2,N,0.00,N*43"), INFO(vpw, "$IIVPW,4.5,N,6.7,M*52"), INFO(vtg, "$GPVTG,156.1,T,140.9,M,0.0,N,0.0,K*41"), INFO(vwr, "$IIVWR,084.0,R,10.4,N,5.4,M,19.3,K*4A"), INFO(wcv, "$GPWCV,12.3,N,POINT1*54"), INFO(wnc, "$GPWNC,12.3,N,5.6,K,POINT1,POINT2*78"), INFO(wpl, "$GPWPL,12.3,N,123.4,E,POINT1*32"), INFO(xdr, "$YXXDR,a,16.0,M,abc*1A"), INFO(xte, "$GPXTE,,,,,,*5E"), INFO(xtr, "$GPXTR,,,*65"), INFO(zda, "$GPZDA,050306,29,10,2003,,*43"), INFO(zdl, "$GPZDL,383401,12.3,R*28"), INFO(zfo, "$GPZFO,123456.1,000010,POINT1*0C"), INFO(ztg, "$GPZTG,123456.1,000010,POINT1*16"), INFO(pgrme, "$PGRME,22.0,M,52.9,M,51.0,M*14"), }; // clang-format on #undef INFO static sentence_data get_info(std::type_index t) { const auto i = std::find_if(sentences.begin(), sentences.end(), [t](const sentence_data & d) { return t == d.type; }); if (i == sentences.end()) throw std::runtime_error{"sentence info not found"}; return *i; } static void all_sentences(benchmark::internal::Benchmark * b) { for (std::size_t i = 0; i < sentences.size(); ++i) { b->Arg(i); } } template <class T> static void specific(benchmark::internal::Benchmark * b) { const auto i = std::find_if(sentences.begin(), sentences.end(), [](const std::vector<sentence_data>::value_type & v) { return T::TAG == v.tag; }); b->Arg(std::distance(sentences.begin(), i)); } } static void Benchmark_make_sentence(benchmark::State & state) { state.SetLabel(sentences[state.range(0)].tag); while (state.KeepRunning()) { auto tmp = nmea::make_sentence(sentences[state.range(0)].text); benchmark::DoNotOptimize(tmp); } } BENCHMARK(Benchmark_make_sentence)->Apply(all_sentences); static void Benchmark_sentence_to_string(benchmark::State & state) { state.SetLabel(sentences[state.range(0)].tag); while (state.KeepRunning()) { state.PauseTiming(); const auto raw = sentences[state.range(0)].text; const auto sentence = nmea::make_sentence(raw); state.ResumeTiming(); std::string s = to_string(*sentence); benchmark::DoNotOptimize(s); } } BENCHMARK(Benchmark_sentence_to_string)->Apply(all_sentences); template <class T> static void Benchmark_create_sentence(benchmark::State & state) { state.SetLabel(sentences[state.range(0)].tag); while (state.KeepRunning()) { auto tmp = nmea::create_sentence<T>(sentences[state.range(0)].text); benchmark::DoNotOptimize(tmp); } } BENCHMARK_TEMPLATE(Benchmark_create_sentence, nmea::aam)->Apply(specific<nmea::aam>); BENCHMARK_TEMPLATE(Benchmark_create_sentence, nmea::alm)->Apply(specific<nmea::alm>); BENCHMARK_TEMPLATE(Benchmark_create_sentence, nmea::apb)->Apply(specific<nmea::apb>); BENCHMARK_TEMPLATE(Benchmark_create_sentence, nmea::bod)->Apply(specific<nmea::bod>); BENCHMARK_TEMPLATE(Benchmark_create_sentence, nmea::bwc)->Apply(specific<nmea::bwc>); BENCHMARK_TEMPLATE(Benchmark_create_sentence, nmea::bwr)->Apply(specific<nmea::bwr>); BENCHMARK_TEMPLATE(Benchmark_create_sentence, nmea::bww)->Apply(specific<nmea::bww>); BENCHMARK_TEMPLATE(Benchmark_create_sentence, nmea::dbk)->Apply(specific<nmea::dbk>); BENCHMARK_TEMPLATE(Benchmark_create_sentence, nmea::dbt)->Apply(specific<nmea::dbt>); BENCHMARK_TEMPLATE(Benchmark_create_sentence, nmea::dpt)->Apply(specific<nmea::dpt>); BENCHMARK_TEMPLATE(Benchmark_create_sentence, nmea::dsc)->Apply(specific<nmea::dsc>); BENCHMARK_TEMPLATE(Benchmark_create_sentence, nmea::dse)->Apply(specific<nmea::dse>); BENCHMARK_TEMPLATE(Benchmark_create_sentence, nmea::dtm)->Apply(specific<nmea::dtm>); BENCHMARK_TEMPLATE(Benchmark_create_sentence, nmea::fsi)->Apply(specific<nmea::fsi>); BENCHMARK_TEMPLATE(Benchmark_create_sentence, nmea::gbs)->Apply(specific<nmea::gbs>); BENCHMARK_TEMPLATE(Benchmark_create_sentence, nmea::gga)->Apply(specific<nmea::gga>); BENCHMARK_TEMPLATE(Benchmark_create_sentence, nmea::glc)->Apply(specific<nmea::glc>); BENCHMARK_TEMPLATE(Benchmark_create_sentence, nmea::gll)->Apply(specific<nmea::gll>); BENCHMARK_TEMPLATE(Benchmark_create_sentence, nmea::gns)->Apply(specific<nmea::gns>); BENCHMARK_TEMPLATE(Benchmark_create_sentence, nmea::grs)->Apply(specific<nmea::grs>); BENCHMARK_TEMPLATE(Benchmark_create_sentence, nmea::gsa)->Apply(specific<nmea::gsa>); BENCHMARK_TEMPLATE(Benchmark_create_sentence, nmea::gst)->Apply(specific<nmea::gst>); BENCHMARK_TEMPLATE(Benchmark_create_sentence, nmea::gsv)->Apply(specific<nmea::gsv>); BENCHMARK_TEMPLATE(Benchmark_create_sentence, nmea::gtd)->Apply(specific<nmea::gtd>); BENCHMARK_TEMPLATE(Benchmark_create_sentence, nmea::hdg)->Apply(specific<nmea::hdg>); BENCHMARK_TEMPLATE(Benchmark_create_sentence, nmea::hfb)->Apply(specific<nmea::hfb>); BENCHMARK_TEMPLATE(Benchmark_create_sentence, nmea::hdm)->Apply(specific<nmea::hdm>); BENCHMARK_TEMPLATE(Benchmark_create_sentence, nmea::hsc)->Apply(specific<nmea::hsc>); BENCHMARK_TEMPLATE(Benchmark_create_sentence, nmea::its)->Apply(specific<nmea::its>); BENCHMARK_TEMPLATE(Benchmark_create_sentence, nmea::lcd)->Apply(specific<nmea::lcd>); BENCHMARK_TEMPLATE(Benchmark_create_sentence, nmea::msk)->Apply(specific<nmea::msk>); BENCHMARK_TEMPLATE(Benchmark_create_sentence, nmea::mss)->Apply(specific<nmea::mss>); BENCHMARK_TEMPLATE(Benchmark_create_sentence, nmea::mtw)->Apply(specific<nmea::mtw>); BENCHMARK_TEMPLATE(Benchmark_create_sentence, nmea::mwd)->Apply(specific<nmea::mwd>); BENCHMARK_TEMPLATE(Benchmark_create_sentence, nmea::mwv)->Apply(specific<nmea::mwv>); BENCHMARK_TEMPLATE(Benchmark_create_sentence, nmea::osd)->Apply(specific<nmea::osd>); BENCHMARK_TEMPLATE(Benchmark_create_sentence, nmea::r00)->Apply(specific<nmea::r00>); BENCHMARK_TEMPLATE(Benchmark_create_sentence, nmea::rma)->Apply(specific<nmea::rma>); BENCHMARK_TEMPLATE(Benchmark_create_sentence, nmea::rmb)->Apply(specific<nmea::rmb>); BENCHMARK_TEMPLATE(Benchmark_create_sentence, nmea::rmc)->Apply(specific<nmea::rmc>); BENCHMARK_TEMPLATE(Benchmark_create_sentence, nmea::rot)->Apply(specific<nmea::rot>); BENCHMARK_TEMPLATE(Benchmark_create_sentence, nmea::rpm)->Apply(specific<nmea::rpm>); BENCHMARK_TEMPLATE(Benchmark_create_sentence, nmea::rsa)->Apply(specific<nmea::rsa>); BENCHMARK_TEMPLATE(Benchmark_create_sentence, nmea::rsd)->Apply(specific<nmea::rsd>); BENCHMARK_TEMPLATE(Benchmark_create_sentence, nmea::rte)->Apply(specific<nmea::rte>); BENCHMARK_TEMPLATE(Benchmark_create_sentence, nmea::sfi)->Apply(specific<nmea::sfi>); BENCHMARK_TEMPLATE(Benchmark_create_sentence, nmea::stn)->Apply(specific<nmea::stn>); BENCHMARK_TEMPLATE(Benchmark_create_sentence, nmea::tds)->Apply(specific<nmea::tds>); BENCHMARK_TEMPLATE(Benchmark_create_sentence, nmea::tfi)->Apply(specific<nmea::tfi>); BENCHMARK_TEMPLATE(Benchmark_create_sentence, nmea::tll)->Apply(specific<nmea::tll>); BENCHMARK_TEMPLATE(Benchmark_create_sentence, nmea::tpc)->Apply(specific<nmea::tpc>); BENCHMARK_TEMPLATE(Benchmark_create_sentence, nmea::tpr)->Apply(specific<nmea::tpr>); BENCHMARK_TEMPLATE(Benchmark_create_sentence, nmea::tpt)->Apply(specific<nmea::tpt>); BENCHMARK_TEMPLATE(Benchmark_create_sentence, nmea::ttm)->Apply(specific<nmea::ttm>); BENCHMARK_TEMPLATE(Benchmark_create_sentence, nmea::vbw)->Apply(specific<nmea::vbw>); BENCHMARK_TEMPLATE(Benchmark_create_sentence, nmea::vdm)->Apply(specific<nmea::vdm>); BENCHMARK_TEMPLATE(Benchmark_create_sentence, nmea::vdo)->Apply(specific<nmea::vdo>); BENCHMARK_TEMPLATE(Benchmark_create_sentence, nmea::vdr)->Apply(specific<nmea::vdr>); BENCHMARK_TEMPLATE(Benchmark_create_sentence, nmea::vhw)->Apply(specific<nmea::vhw>); BENCHMARK_TEMPLATE(Benchmark_create_sentence, nmea::vlw)->Apply(specific<nmea::vlw>); BENCHMARK_TEMPLATE(Benchmark_create_sentence, nmea::vpw)->Apply(specific<nmea::vpw>); BENCHMARK_TEMPLATE(Benchmark_create_sentence, nmea::vtg)->Apply(specific<nmea::vtg>); BENCHMARK_TEMPLATE(Benchmark_create_sentence, nmea::vwr)->Apply(specific<nmea::vwr>); BENCHMARK_TEMPLATE(Benchmark_create_sentence, nmea::wcv)->Apply(specific<nmea::wcv>); BENCHMARK_TEMPLATE(Benchmark_create_sentence, nmea::wnc)->Apply(specific<nmea::wnc>); BENCHMARK_TEMPLATE(Benchmark_create_sentence, nmea::wpl)->Apply(specific<nmea::wpl>); BENCHMARK_TEMPLATE(Benchmark_create_sentence, nmea::xdr)->Apply(specific<nmea::xdr>); BENCHMARK_TEMPLATE(Benchmark_create_sentence, nmea::xte)->Apply(specific<nmea::xte>); BENCHMARK_TEMPLATE(Benchmark_create_sentence, nmea::xtr)->Apply(specific<nmea::xtr>); BENCHMARK_TEMPLATE(Benchmark_create_sentence, nmea::zda)->Apply(specific<nmea::zda>); BENCHMARK_TEMPLATE(Benchmark_create_sentence, nmea::zdl)->Apply(specific<nmea::zdl>); BENCHMARK_TEMPLATE(Benchmark_create_sentence, nmea::zfo)->Apply(specific<nmea::zfo>); BENCHMARK_TEMPLATE(Benchmark_create_sentence, nmea::ztg)->Apply(specific<nmea::ztg>); BENCHMARK_TEMPLATE(Benchmark_create_sentence, nmea::pgrme)->Apply(specific<nmea::pgrme>); static void Benchmark_extract_id(benchmark::State & state) { state.SetLabel(sentences[state.range(0)].tag); while (state.KeepRunning()) { auto tmp = nmea::extract_id(sentences[state.range(0)].text); benchmark::DoNotOptimize(tmp); } } BENCHMARK(Benchmark_extract_id)->Apply(all_sentences); BENCHMARK_MAIN()
/// \file /// \author /// /// \brief Implementation of custom text edit widget /// /// Copyright (c) . All rights reserved. /// Licensed under the MIT License. See LICENSE file in the project root for full license information. #include "stdafx.h" #include "SnippetEdit.h" #include <QtCore/qlogging.h> //********************************************************************************************************************** /// \brief Remve the images from the text of a document. /// /// \param[in] html The HTML document /// \return The text contained in the document, with the images removed. //********************************************************************************************************************** QString removeImagesFromHtml(QString const& html) { QTextDocument doc; doc.setHtml(html); QTextBlock block = doc.begin(); QVector<qint32> positions; while (block.isValid()) { for (QTextBlock::iterator it = block.begin(); it != block.end(); ++it) { QTextFragment const fragment = it.fragment(); if (!fragment.isValid()) continue; QTextCharFormat const format = fragment.charFormat(); if (!format.isImageFormat()) continue; QTextImageFormat const imageFormat = format.toImageFormat(); if (!format.isValid()) continue; positions.push_back(fragment.position()); } block = block.next(); } QTextCursor cursor(&doc); for (QVector<qint32>::reverse_iterator it = positions.rbegin(); it != positions.rend(); ++it) { cursor.setPosition(*it); cursor.deleteChar(); } return doc.toHtml(); } //********************************************************************************************************************** /// \param[in] parent The parent widget of the edit. //********************************************************************************************************************** SnippetEdit::SnippetEdit(QWidget* parent) : QTextEdit(parent) { } //********************************************************************************************************************** /// \param[in] source The MIME data being pasted //********************************************************************************************************************** void SnippetEdit::insertFromMimeData(const QMimeData* source) { if (!source) return; if (!this->acceptRichText()) { if (source->hasText()) QTextEdit::insertPlainText(source->text()); else if (source->hasHtml()) QTextEdit::insertHtml(source->html()); return; } if (source->hasHtml()) QTextEdit::insertHtml(removeImagesFromHtml(source->html())); else QTextEdit::insertFromMimeData(source); }
// Copyright (c) 2012-2013 The PPCoin developers // Copyright (c) 2016 The PrettyGoodPrivacy developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <boost/assign/list_of.hpp> #include "kernel.h" #include "txdb.h" using namespace std; extern bool IsConfirmedInNPrevBlocks(const CTxIndex& txindex, const CBlockIndex* pindexFrom, int nMaxDepth, int& nActualDepth); // Get time weight int64_t GetWeight(int64_t nIntervalBeginning, int64_t nIntervalEnd) { // Kernel hash weight starts from 0 at the min age // this change increases active coins participating the hash and helps // to secure the network when proof-of-stake difficulty is low return nIntervalEnd - nIntervalBeginning - nStakeMinAge; } // Get the last stake modifier and its generation time from a given block static bool GetLastStakeModifier(const CBlockIndex* pindex, uint64_t& nStakeModifier, int64_t& nModifierTime) { if (!pindex) return error("GetLastStakeModifier: null pindex"); while (pindex && pindex->pprev && !pindex->GeneratedStakeModifier()) pindex = pindex->pprev; if (!pindex->GeneratedStakeModifier()) return error("GetLastStakeModifier: no generation at genesis block"); nStakeModifier = pindex->nStakeModifier; nModifierTime = pindex->GetBlockTime(); return true; } // Get selection interval section (in seconds) static int64_t GetStakeModifierSelectionIntervalSection(int nSection) { assert (nSection >= 0 && nSection < 64); return (nModifierInterval * 63 / (63 + ((63 - nSection) * (MODIFIER_INTERVAL_RATIO - 1)))); } // Get stake modifier selection interval (in seconds) static int64_t GetStakeModifierSelectionInterval() { int64_t nSelectionInterval = 0; for (int nSection=0; nSection<64; nSection++) nSelectionInterval += GetStakeModifierSelectionIntervalSection(nSection); return nSelectionInterval; } // select a block from the candidate blocks in vSortedByTimestamp, excluding // already selected blocks in vSelectedBlocks, and with timestamp up to // nSelectionIntervalStop. static bool SelectBlockFromCandidates(vector<pair<int64_t, uint256> >& vSortedByTimestamp, map<uint256, const CBlockIndex*>& mapSelectedBlocks, int64_t nSelectionIntervalStop, uint64_t nStakeModifierPrev, const CBlockIndex** pindexSelected) { bool fSelected = false; uint256 hashBest = 0; *pindexSelected = (const CBlockIndex*) 0; BOOST_FOREACH(const PAIRTYPE(int64_t, uint256)& item, vSortedByTimestamp) { if (!mapBlockIndex.count(item.second)) return error("SelectBlockFromCandidates: failed to find block index for candidate block %s", item.second.ToString()); const CBlockIndex* pindex = mapBlockIndex[item.second]; if (fSelected && pindex->GetBlockTime() > nSelectionIntervalStop) break; if (mapSelectedBlocks.count(pindex->GetBlockHash()) > 0) continue; // compute the selection hash by hashing its proof-hash and the // previous proof-of-stake modifier CDataStream ss(SER_GETHASH, 0); ss << pindex->hashProof << nStakeModifierPrev; uint256 hashSelection = Hash(ss.begin(), ss.end()); // the selection hash is divided by 2**32 so that proof-of-stake block // is always favored over proof-of-work block. this is to preserve // the energy efficiency property if (pindex->IsProofOfStake()) hashSelection >>= 32; if (fSelected && hashSelection < hashBest) { hashBest = hashSelection; *pindexSelected = (const CBlockIndex*) pindex; } else if (!fSelected) { fSelected = true; hashBest = hashSelection; *pindexSelected = (const CBlockIndex*) pindex; } } LogPrint("stakemodifier", "SelectBlockFromCandidates: selection hash=%s\n", hashBest.ToString()); return fSelected; } // Stake Modifier (hash modifier of proof-of-stake): // The purpose of stake modifier is to prevent a txout (coin) owner from // computing future proof-of-stake generated by this txout at the time // of transaction confirmation. To meet kernel protocol, the txout // must hash with a future stake modifier to generate the proof. // Stake modifier consists of bits each of which is contributed from a // selected block of a given block group in the past. // The selection of a block is based on a hash of the block's proof-hash and // the previous stake modifier. // Stake modifier is recomputed at a fixed time interval instead of every // block. This is to make it difficult for an attacker to gain control of // additional bits in the stake modifier, even after generating a chain of // blocks. bool ComputeNextStakeModifier(const CBlockIndex* pindexPrev, uint64_t& nStakeModifier, bool& fGeneratedStakeModifier) { nStakeModifier = 0; fGeneratedStakeModifier = false; if (!pindexPrev) { fGeneratedStakeModifier = true; return true; // genesis block's modifier is 0 } // First find current stake modifier and its generation block time // if it's not old enough, return the same stake modifier int64_t nModifierTime = 0; if (!GetLastStakeModifier(pindexPrev, nStakeModifier, nModifierTime)) return error("ComputeNextStakeModifier: unable to get last modifier"); LogPrint("stakemodifier", "ComputeNextStakeModifier: prev modifier=0x%016x time=%s\n", nStakeModifier, DateTimeStrFormat(nModifierTime)); if (nModifierTime / nModifierInterval >= pindexPrev->GetBlockTime() / nModifierInterval) return true; // Sort candidate blocks by timestamp vector<pair<int64_t, uint256> > vSortedByTimestamp; vSortedByTimestamp.reserve(64 * nModifierInterval / TARGET_SPACING); int64_t nSelectionInterval = GetStakeModifierSelectionInterval(); int64_t nSelectionIntervalStart = (pindexPrev->GetBlockTime() / nModifierInterval) * nModifierInterval - nSelectionInterval; const CBlockIndex* pindex = pindexPrev; while (pindex && pindex->GetBlockTime() >= nSelectionIntervalStart) { vSortedByTimestamp.push_back(make_pair(pindex->GetBlockTime(), pindex->GetBlockHash())); pindex = pindex->pprev; } int nHeightFirstCandidate = pindex ? (pindex->nHeight + 1) : 0; reverse(vSortedByTimestamp.begin(), vSortedByTimestamp.end()); sort(vSortedByTimestamp.begin(), vSortedByTimestamp.end()); // Select 64 blocks from candidate blocks to generate stake modifier uint64_t nStakeModifierNew = 0; int64_t nSelectionIntervalStop = nSelectionIntervalStart; map<uint256, const CBlockIndex*> mapSelectedBlocks; for (int nRound=0; nRound<min(64, (int)vSortedByTimestamp.size()); nRound++) { // add an interval section to the current selection round nSelectionIntervalStop += GetStakeModifierSelectionIntervalSection(nRound); // select a block from the candidates of current round if (!SelectBlockFromCandidates(vSortedByTimestamp, mapSelectedBlocks, nSelectionIntervalStop, nStakeModifier, &pindex)) return error("ComputeNextStakeModifier: unable to select block at round %d", nRound); // write the entropy bit of the selected block nStakeModifierNew |= (((uint64_t)pindex->GetStakeEntropyBit()) << nRound); // add the selected block from candidates to selected list mapSelectedBlocks.insert(make_pair(pindex->GetBlockHash(), pindex)); LogPrint("stakemodifier", "ComputeNextStakeModifier: selected round %d stop=%s height=%d bit=%d\n", nRound, DateTimeStrFormat(nSelectionIntervalStop), pindex->nHeight, pindex->GetStakeEntropyBit()); } // Print selection map for visualization of the selected blocks if (LogAcceptCategory("stakemodifier")) { string strSelectionMap = ""; // '-' indicates proof-of-work blocks not selected strSelectionMap.insert(0, pindexPrev->nHeight - nHeightFirstCandidate + 1, '-'); pindex = pindexPrev; while (pindex && pindex->nHeight >= nHeightFirstCandidate) { // '=' indicates proof-of-stake blocks not selected if (pindex->IsProofOfStake()) strSelectionMap.replace(pindex->nHeight - nHeightFirstCandidate, 1, "="); pindex = pindex->pprev; } BOOST_FOREACH(const PAIRTYPE(uint256, const CBlockIndex*)& item, mapSelectedBlocks) { // 'S' indicates selected proof-of-stake blocks // 'W' indicates selected proof-of-work blocks strSelectionMap.replace(item.second->nHeight - nHeightFirstCandidate, 1, item.second->IsProofOfStake()? "S" : "W"); } LogPrintf("ComputeNextStakeModifier: selection height [%d, %d] map %s\n", nHeightFirstCandidate, pindexPrev->nHeight, strSelectionMap); } LogPrint("stakemodifier", "ComputeNextStakeModifier: new modifier=0x%016x time=%s\n", nStakeModifierNew, DateTimeStrFormat(pindexPrev->GetBlockTime())); nStakeModifier = nStakeModifierNew; fGeneratedStakeModifier = true; return true; } // Stake Modifier (hash modifier of proof-of-stake): // The purpose of stake modifier is to prevent a txout (coin) owner from // computing future proof-of-stake generated by this txout at the time // of transaction confirmation. To meet kernel protocol, the txout // must hash with a future stake modifier to generate the proof. uint256 ComputeStakeModifierV2(const CBlockIndex* pindexPrev, const uint256& kernel) { if (!pindexPrev) return 0; // genesis block's modifier is 0 CDataStream ss(SER_GETHASH, 0); ss << kernel << pindexPrev->bnStakeModifierV2; return Hash(ss.begin(), ss.end()); } bool CheckStakeKernelHash(CBlockIndex* pindexPrev, unsigned int nBits, unsigned int nTimeBlockFrom, const CTransaction& txPrev, const COutPoint& prevout, unsigned int nTimeTx, uint256& hashProofOfStake, uint256& targetProofOfStake, bool fPrintProofOfStake) { if (nTimeTx < txPrev.nTime) // Transaction timestamp violation return error("CheckStakeKernelHash() : nTime violation"); if (nTimeBlockFrom + nStakeMinAge > nTimeTx) // Min age requirement return error("CheckStakeKernelHash() : min age violation"); // Base target CBigNum bnTarget; bnTarget.SetCompact(nBits); // Weighted target int64_t nValueIn = txPrev.vout[prevout.n].nValue; CBigNum bnWeight = CBigNum(nValueIn); bnTarget *= bnWeight; targetProofOfStake = bnTarget.getuint256(); uint64_t nStakeModifier = pindexPrev->nStakeModifier; uint256 bnStakeModifierV2 = pindexPrev->bnStakeModifierV2; int nStakeModifierHeight = pindexPrev->nHeight; int64_t nStakeModifierTime = pindexPrev->nTime; // Calculate hash CDataStream ss(SER_GETHASH, 0); ss << bnStakeModifierV2; ss << txPrev.nTime << prevout.hash << prevout.n << nTimeTx; hashProofOfStake = Hash(ss.begin(), ss.end()); if (fPrintProofOfStake) { LogPrintf("CheckStakeKernelHash() : using modifier 0x%016x at height=%d timestamp=%s for block from timestamp=%s\n", nStakeModifier, nStakeModifierHeight, DateTimeStrFormat(nStakeModifierTime), DateTimeStrFormat(nTimeBlockFrom)); LogPrintf("CheckStakeKernelHash() : check modifier=0x%016x nTimeBlockFrom=%u nTimeTxPrev=%u nPrevout=%u nTimeTx=%u hashProof=%s\n", nStakeModifier, nTimeBlockFrom, txPrev.nTime, prevout.n, nTimeTx, hashProofOfStake.ToString()); } // Now check if proof-of-stake hash meets target protocol if (CBigNum(hashProofOfStake) > bnTarget){ return false; } if (fDebug && !fPrintProofOfStake) { LogPrintf("CheckStakeKernelHash() : using modifier 0x%016x at height=%d timestamp=%s for block from timestamp=%s\n", nStakeModifier, nStakeModifierHeight, DateTimeStrFormat(nStakeModifierTime), DateTimeStrFormat(nTimeBlockFrom)); LogPrintf("CheckStakeKernelHash() : pass modifier=0x%016x nTimeBlockFrom=%u nTimeTxPrev=%u nPrevout=%u nTimeTx=%u hashProof=%s\n", nStakeModifier, nTimeBlockFrom, txPrev.nTime, prevout.n, nTimeTx, hashProofOfStake.ToString()); } return true; } // Check kernel hash target and coinstake signature bool CheckProofOfStake(CBlockIndex* pindexPrev, const CTransaction& tx, unsigned int nBits, uint256& hashProofOfStake, uint256& targetProofOfStake) { int nStakeMinConfirmations = 200; if (!tx.IsCoinStake()) return error("CheckProofOfStake() : called on non-coinstake %s", tx.GetHash().ToString()); // Kernel (input 0) must match the stake hash target per coin age (nBits) const CTxIn& txin = tx.vin[0]; // First try finding the previous transaction in database CTxDB txdb("r"); CTransaction txPrev; CTxIndex txindex; if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex)) return tx.DoS(1, error("CheckProofOfStake() : INFO: read txPrev failed")); // previous transaction not in main chain, may occur during initial download // Verify signature if (!VerifySignature(txPrev, tx, 0, SCRIPT_VERIFY_NONE, 0)) return tx.DoS(100, error("CheckProofOfStake() : VerifySignature failed on coinstake %s", tx.GetHash().ToString())); // Read block header CBlock block; if (!block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false)) return fDebug? error("CheckProofOfStake() : read block failed") : false; // unable to read block of previous transaction int nDepth; nStakeMinConfirmations = 200; if (IsConfirmedInNPrevBlocks(txindex, pindexPrev, nStakeMinConfirmations - 1, nDepth)) return tx.DoS(100, error("CheckProofOfStake() : tried to stake at depth %d", nDepth + 1)); if (!CheckStakeKernelHash(pindexPrev, nBits, block.GetBlockTime(), txPrev, txin.prevout, tx.nTime, hashProofOfStake, targetProofOfStake, fDebug)) return tx.DoS(1, error("CheckProofOfStake() : INFO: check kernel failed on coinstake %s, hashProof=%s", tx.GetHash().ToString(), hashProofOfStake.ToString())); // may occur during initial download or if behind on block chain sync return true; } // Check whether the coinstake timestamp meets protocol bool CheckCoinStakeTimestamp(int nHeight, int64_t nTimeBlock, int64_t nTimeTx) { return (nTimeBlock == nTimeTx) && ((nTimeTx & STAKE_TIMESTAMP_MASK) == 0); } bool CheckKernel(CBlockIndex* pindexPrev, unsigned int nBits, int64_t nTime, const COutPoint& prevout, int64_t* pBlockTime) { uint256 hashProofOfStake, targetProofOfStake; CTxDB txdb("r"); CTransaction txPrev; CTxIndex txindex; if (!txPrev.ReadFromDisk(txdb, prevout, txindex)) return false; // Read block header CBlock block; if (!block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false)) return false; int nDepth; int nStakeMinConfirmations = 200; if (IsConfirmedInNPrevBlocks(txindex, pindexPrev, nStakeMinConfirmations - 1, nDepth)) return false; if (pBlockTime) *pBlockTime = block.GetBlockTime(); return CheckStakeKernelHash(pindexPrev, nBits, block.GetBlockTime(), txPrev, prevout, nTime, hashProofOfStake, targetProofOfStake); }
// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "init.h" #include "util.h" #include "sync.h" #include "ui_interface.h" #include "base58.h" #include "bitcoinrpc.h" #include "db.h" #include <boost/asio.hpp> #include <boost/asio/ip/v6_only.hpp> #include <boost/bind.hpp> #include <boost/filesystem.hpp> #include <boost/foreach.hpp> #include <boost/iostreams/concepts.hpp> #include <boost/iostreams/stream.hpp> #include <boost/algorithm/string.hpp> #include <boost/lexical_cast.hpp> #include <boost/asio/ssl.hpp> #include <boost/filesystem/fstream.hpp> #include <boost/shared_ptr.hpp> #include <list> using namespace std; using namespace boost; using namespace boost::asio; using namespace json_spirit; static std::string strRPCUserColonPass; // These are created by StartRPCThreads, destroyed in StopRPCThreads static asio::io_service* rpc_io_service = NULL; static ssl::context* rpc_ssl_context = NULL; static boost::thread_group* rpc_worker_group = NULL; static inline unsigned short GetDefaultRPCPort() { return GetBoolArg("-testnet", false) ? 11221 : 9944; } Object JSONRPCError(int code, const string& message) { Object error; error.push_back(Pair("code", code)); error.push_back(Pair("message", message)); return error; } void RPCTypeCheck(const Array& params, const list<Value_type>& typesExpected, bool fAllowNull) { unsigned int i = 0; BOOST_FOREACH(Value_type t, typesExpected) { if (params.size() <= i) break; const Value& v = params[i]; if (!((v.type() == t) || (fAllowNull && (v.type() == null_type)))) { string err = strprintf("Expected type %s, got %s", Value_type_name[t], Value_type_name[v.type()]); throw JSONRPCError(RPC_TYPE_ERROR, err); } i++; } } void RPCTypeCheck(const Object& o, const map<string, Value_type>& typesExpected, bool fAllowNull) { BOOST_FOREACH(const PAIRTYPE(string, Value_type)& t, typesExpected) { const Value& v = find_value(o, t.first); if (!fAllowNull && v.type() == null_type) throw JSONRPCError(RPC_TYPE_ERROR, strprintf("Missing %s", t.first.c_str())); if (!((v.type() == t.second) || (fAllowNull && (v.type() == null_type)))) { string err = strprintf("Expected type %s for %s, got %s", Value_type_name[t.second], t.first.c_str(), Value_type_name[v.type()]); throw JSONRPCError(RPC_TYPE_ERROR, err); } } } int64 AmountFromValue(const Value& value) { double dAmount = value.get_real(); if (dAmount <= 0.0 || dAmount > 84000000.0) throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount"); int64 nAmount = roundint64(dAmount * COIN); if (!MoneyRange(nAmount)) throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount"); return nAmount; } Value ValueFromAmount(int64 amount) { return (double)amount / (double)COIN; } std::string HexBits(unsigned int nBits) { union { int32_t nBits; char cBits[4]; } uBits; uBits.nBits = htonl((int32_t)nBits); return HexStr(BEGIN(uBits.cBits), END(uBits.cBits)); } /// /// Note: This interface may still be subject to change. /// string CRPCTable::help(string strCommand) const { string strRet; set<rpcfn_type> setDone; for (map<string, const CRPCCommand*>::const_iterator mi = mapCommands.begin(); mi != mapCommands.end(); ++mi) { const CRPCCommand *pcmd = mi->second; string strMethod = mi->first; // We already filter duplicates, but these deprecated screw up the sort order if (strMethod.find("label") != string::npos) continue; if (strCommand != "" && strMethod != strCommand) continue; if (pcmd->reqWallet && !pwalletMain) continue; try { Array params; rpcfn_type pfn = pcmd->actor; if (setDone.insert(pfn).second) (*pfn)(params, true); } catch (std::exception& e) { // Help text is returned in an exception string strHelp = string(e.what()); if (strCommand == "") if (strHelp.find('\n') != string::npos) strHelp = strHelp.substr(0, strHelp.find('\n')); strRet += strHelp + "\n"; } } if (strRet == "") strRet = strprintf("help: unknown command: %s\n", strCommand.c_str()); strRet = strRet.substr(0,strRet.size()-1); return strRet; } Value help(const Array& params, bool fHelp) { if (fHelp || params.size() > 1) throw runtime_error( "help [command]\n" "List commands, or get help for a command."); string strCommand; if (params.size() > 0) strCommand = params[0].get_str(); return tableRPC.help(strCommand); } Value stop(const Array& params, bool fHelp) { // Accept the deprecated and ignored 'detach' boolean argument if (fHelp || params.size() > 1) throw runtime_error( "stop\n" "Stop Adn server."); // Shutdown will take long enough that the response should get back StartShutdown(); return "Adn server stopping"; } // // Call Table // static const CRPCCommand vRPCCommands[] = { // name actor (function) okSafeMode threadSafe reqWallet // ------------------------ ----------------------- ---------- ---------- --------- { "help", &help, true, true, false }, { "stop", &stop, true, true, false }, { "getblockcount", &getblockcount, true, false, false }, { "getbestblockhash", &getbestblockhash, true, false, false }, { "getconnectioncount", &getconnectioncount, true, false, false }, { "getpeerinfo", &getpeerinfo, true, false, false }, { "addnode", &addnode, true, true, false }, { "getaddednodeinfo", &getaddednodeinfo, true, true, false }, { "getdifficulty", &getdifficulty, true, false, false }, { "getnetworkhashps", &getnetworkhashps, true, false, false }, { "getgenerate", &getgenerate, true, false, false }, { "setgenerate", &setgenerate, true, false, true }, { "gethashespersec", &gethashespersec, true, false, false }, { "getinfo", &getinfo, true, false, false }, { "getmininginfo", &getmininginfo, true, false, false }, { "getnewaddress", &getnewaddress, true, false, true }, { "getaccountaddress", &getaccountaddress, true, false, true }, { "setaccount", &setaccount, true, false, true }, { "getaccount", &getaccount, false, false, true }, { "getaddressesbyaccount", &getaddressesbyaccount, true, false, true }, { "sendtoaddress", &sendtoaddress, false, false, true }, { "getreceivedbyaddress", &getreceivedbyaddress, false, false, true }, { "getreceivedbyaccount", &getreceivedbyaccount, false, false, true }, { "listreceivedbyaddress", &listreceivedbyaddress, false, false, true }, { "listreceivedbyaccount", &listreceivedbyaccount, false, false, true }, { "backupwallet", &backupwallet, true, false, true }, { "keypoolrefill", &keypoolrefill, true, false, true }, { "walletpassphrase", &walletpassphrase, true, false, true }, { "walletpassphrasechange", &walletpassphrasechange, false, false, true }, { "walletlock", &walletlock, true, false, true }, { "encryptwallet", &encryptwallet, false, false, true }, { "validateaddress", &validateaddress, true, false, false }, { "getbalance", &getbalance, false, false, true }, { "move", &movecmd, false, false, true }, { "sendfrom", &sendfrom, false, false, true }, { "sendmany", &sendmany, false, false, true }, { "addmultisigaddress", &addmultisigaddress, false, false, true }, { "createmultisig", &createmultisig, true, true , false }, { "getrawmempool", &getrawmempool, true, false, false }, { "getblock", &getblock, false, false, false }, { "getblockhash", &getblockhash, false, false, false }, { "gettransaction", &gettransaction, false, false, true }, { "listtransactions", &listtransactions, false, false, true }, { "listaddressgroupings", &listaddressgroupings, false, false, true }, { "signmessage", &signmessage, false, false, true }, { "verifymessage", &verifymessage, false, false, false }, { "getwork", &getwork, true, false, true }, { "getworkex", &getworkex, true, false, true }, { "listaccounts", &listaccounts, false, false, true }, { "settxfee", &settxfee, false, false, true }, { "getblocktemplate", &getblocktemplate, true, false, false }, { "submitblock", &submitblock, false, false, false }, { "setmininput", &setmininput, false, false, false }, { "listsinceblock", &listsinceblock, false, false, true }, { "dumpprivkey", &dumpprivkey, true, false, true }, { "importprivkey", &importprivkey, false, false, true }, { "listunspent", &listunspent, false, false, true }, { "getrawtransaction", &getrawtransaction, false, false, false }, { "createrawtransaction", &createrawtransaction, false, false, false }, { "decoderawtransaction", &decoderawtransaction, false, false, false }, { "signrawtransaction", &signrawtransaction, false, false, false }, { "sendrawtransaction", &sendrawtransaction, false, false, false }, { "getnormalizedtxid", &getnormalizedtxid, true, true, false }, { "gettxoutsetinfo", &gettxoutsetinfo, true, false, false }, { "gettxout", &gettxout, true, false, false }, { "lockunspent", &lockunspent, false, false, true }, { "listlockunspent", &listlockunspent, false, false, true }, { "verifychain", &verifychain, true, false, false }, }; CRPCTable::CRPCTable() { unsigned int vcidx; for (vcidx = 0; vcidx < (sizeof(vRPCCommands) / sizeof(vRPCCommands[0])); vcidx++) { const CRPCCommand *pcmd; pcmd = &vRPCCommands[vcidx]; mapCommands[pcmd->name] = pcmd; } } const CRPCCommand *CRPCTable::operator[](string name) const { map<string, const CRPCCommand*>::const_iterator it = mapCommands.find(name); if (it == mapCommands.end()) return NULL; return (*it).second; } // // HTTP protocol // // This ain't Apache. We're just using HTTP header for the length field // and to be compatible with other JSON-RPC implementations. // string HTTPPost(const string& strMsg, const map<string,string>& mapRequestHeaders) { ostringstream s; s << "POST / HTTP/1.1\r\n" << "User-Agent: adn-json-rpc/" << FormatFullVersion() << "\r\n" << "Host: 127.0.0.1\r\n" << "Content-Type: application/json\r\n" << "Content-Length: " << strMsg.size() << "\r\n" << "Connection: close\r\n" << "Accept: application/json\r\n"; BOOST_FOREACH(const PAIRTYPE(string, string)& item, mapRequestHeaders) s << item.first << ": " << item.second << "\r\n"; s << "\r\n" << strMsg; return s.str(); } string rfc1123Time() { char buffer[64]; time_t now; time(&now); struct tm* now_gmt = gmtime(&now); string locale(setlocale(LC_TIME, NULL)); setlocale(LC_TIME, "C"); // we want POSIX (aka "C") weekday/month strings strftime(buffer, sizeof(buffer), "%a, %d %b %Y %H:%M:%S +0000", now_gmt); setlocale(LC_TIME, locale.c_str()); return string(buffer); } static string HTTPReply(int nStatus, const string& strMsg, bool keepalive) { if (nStatus == HTTP_UNAUTHORIZED) return strprintf("HTTP/1.0 401 Authorization Required\r\n" "Date: %s\r\n" "Server: adn-json-rpc/%s\r\n" "WWW-Authenticate: Basic realm=\"jsonrpc\"\r\n" "Content-Type: text/html\r\n" "Content-Length: 296\r\n" "\r\n" "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\"\r\n" "\"http://www.w3.org/TR/1999/REC-html401-19991224/loose.dtd\">\r\n" "<HTML>\r\n" "<HEAD>\r\n" "<TITLE>Error</TITLE>\r\n" "<META HTTP-EQUIV='Content-Type' CONTENT='text/html; charset=ISO-8859-1'>\r\n" "</HEAD>\r\n" "<BODY><H1>401 Unauthorized.</H1></BODY>\r\n" "</HTML>\r\n", rfc1123Time().c_str(), FormatFullVersion().c_str()); const char *cStatus; if (nStatus == HTTP_OK) cStatus = "OK"; else if (nStatus == HTTP_BAD_REQUEST) cStatus = "Bad Request"; else if (nStatus == HTTP_FORBIDDEN) cStatus = "Forbidden"; else if (nStatus == HTTP_NOT_FOUND) cStatus = "Not Found"; else if (nStatus == HTTP_INTERNAL_SERVER_ERROR) cStatus = "Internal Server Error"; else cStatus = ""; return strprintf( "HTTP/1.1 %d %s\r\n" "Date: %s\r\n" "Connection: %s\r\n" "Content-Length: %"PRIszu"\r\n" "Content-Type: application/json\r\n" "Server: adn-json-rpc/%s\r\n" "\r\n" "%s", nStatus, cStatus, rfc1123Time().c_str(), keepalive ? "keep-alive" : "close", strMsg.size(), FormatFullVersion().c_str(), strMsg.c_str()); } bool ReadHTTPRequestLine(std::basic_istream<char>& stream, int &proto, string& http_method, string& http_uri) { string str; getline(stream, str); // HTTP request line is space-delimited vector<string> vWords; boost::split(vWords, str, boost::is_any_of(" ")); if (vWords.size() < 2) return false; // HTTP methods permitted: GET, POST http_method = vWords[0]; if (http_method != "GET" && http_method != "POST") return false; // HTTP URI must be an absolute path, relative to current host http_uri = vWords[1]; if (http_uri.size() == 0 || http_uri[0] != '/') return false; // parse proto, if present string strProto = ""; if (vWords.size() > 2) strProto = vWords[2]; proto = 0; const char *ver = strstr(strProto.c_str(), "HTTP/1."); if (ver != NULL) proto = atoi(ver+7); return true; } int ReadHTTPStatus(std::basic_istream<char>& stream, int &proto) { string str; getline(stream, str); vector<string> vWords; boost::split(vWords, str, boost::is_any_of(" ")); if (vWords.size() < 2) return HTTP_INTERNAL_SERVER_ERROR; proto = 0; const char *ver = strstr(str.c_str(), "HTTP/1."); if (ver != NULL) proto = atoi(ver+7); return atoi(vWords[1].c_str()); } int ReadHTTPHeaders(std::basic_istream<char>& stream, map<string, string>& mapHeadersRet) { int nLen = 0; loop { string str; std::getline(stream, str); if (str.empty() || str == "\r") break; string::size_type nColon = str.find(":"); if (nColon != string::npos) { string strHeader = str.substr(0, nColon); boost::trim(strHeader); boost::to_lower(strHeader); string strValue = str.substr(nColon+1); boost::trim(strValue); mapHeadersRet[strHeader] = strValue; if (strHeader == "content-length") nLen = atoi(strValue.c_str()); } } return nLen; } int ReadHTTPMessage(std::basic_istream<char>& stream, map<string, string>& mapHeadersRet, string& strMessageRet, int nProto) { mapHeadersRet.clear(); strMessageRet = ""; // Read header int nLen = ReadHTTPHeaders(stream, mapHeadersRet); if (nLen < 0 || nLen > (int)MAX_SIZE) return HTTP_INTERNAL_SERVER_ERROR; // Read message if (nLen > 0) { vector<char> vch(nLen); stream.read(&vch[0], nLen); strMessageRet = string(vch.begin(), vch.end()); } string sConHdr = mapHeadersRet["connection"]; if ((sConHdr != "close") && (sConHdr != "keep-alive")) { if (nProto >= 1) mapHeadersRet["connection"] = "keep-alive"; else mapHeadersRet["connection"] = "close"; } return HTTP_OK; } bool HTTPAuthorized(map<string, string>& mapHeaders) { string strAuth = mapHeaders["authorization"]; if (strAuth.substr(0,6) != "Basic ") return false; string strUserPass64 = strAuth.substr(6); boost::trim(strUserPass64); string strUserPass = DecodeBase64(strUserPass64); return TimingResistantEqual(strUserPass, strRPCUserColonPass); } // // JSON-RPC protocol. Bitcoin speaks version 1.0 for maximum compatibility, // but uses JSON-RPC 1.1/2.0 standards for parts of the 1.0 standard that were // unspecified (HTTP errors and contents of 'error'). // // 1.0 spec: http://json-rpc.org/wiki/specification // 1.2 spec: http://groups.google.com/group/json-rpc/web/json-rpc-over-http // http://www.codeproject.com/KB/recipes/JSON_Spirit.aspx // string JSONRPCRequest(const string& strMethod, const Array& params, const Value& id) { Object request; request.push_back(Pair("method", strMethod)); request.push_back(Pair("params", params)); request.push_back(Pair("id", id)); return write_string(Value(request), false) + "\n"; } Object JSONRPCReplyObj(const Value& result, const Value& error, const Value& id) { Object reply; if (error.type() != null_type) reply.push_back(Pair("result", Value::null)); else reply.push_back(Pair("result", result)); reply.push_back(Pair("error", error)); reply.push_back(Pair("id", id)); return reply; } string JSONRPCReply(const Value& result, const Value& error, const Value& id) { Object reply = JSONRPCReplyObj(result, error, id); return write_string(Value(reply), false) + "\n"; } void ErrorReply(std::ostream& stream, const Object& objError, const Value& id) { // Send error reply from json-rpc error object int nStatus = HTTP_INTERNAL_SERVER_ERROR; int code = find_value(objError, "code").get_int(); if (code == RPC_INVALID_REQUEST) nStatus = HTTP_BAD_REQUEST; else if (code == RPC_METHOD_NOT_FOUND) nStatus = HTTP_NOT_FOUND; string strReply = JSONRPCReply(Value::null, objError, id); stream << HTTPReply(nStatus, strReply, false) << std::flush; } bool ClientAllowed(const boost::asio::ip::address& address) { // Make sure that IPv4-compatible and IPv4-mapped IPv6 addresses are treated as IPv4 addresses if (address.is_v6() && (address.to_v6().is_v4_compatible() || address.to_v6().is_v4_mapped())) return ClientAllowed(address.to_v6().to_v4()); if (address == asio::ip::address_v4::loopback() || address == asio::ip::address_v6::loopback() || (address.is_v4() // Check whether IPv4 addresses match 127.0.0.0/8 (loopback subnet) && (address.to_v4().to_ulong() & 0xff000000) == 0x7f000000)) return true; const string strAddress = address.to_string(); const vector<string>& vAllow = mapMultiArgs["-rpcallowip"]; BOOST_FOREACH(string strAllow, vAllow) if (WildcardMatch(strAddress, strAllow)) return true; return false; } // // IOStream device that speaks SSL but can also speak non-SSL // template <typename Protocol> class SSLIOStreamDevice : public iostreams::device<iostreams::bidirectional> { public: SSLIOStreamDevice(asio::ssl::stream<typename Protocol::socket> &streamIn, bool fUseSSLIn) : stream(streamIn) { fUseSSL = fUseSSLIn; fNeedHandshake = fUseSSLIn; } void handshake(ssl::stream_base::handshake_type role) { if (!fNeedHandshake) return; fNeedHandshake = false; stream.handshake(role); } std::streamsize read(char* s, std::streamsize n) { handshake(ssl::stream_base::server); // HTTPS servers read first if (fUseSSL) return stream.read_some(asio::buffer(s, n)); return stream.next_layer().read_some(asio::buffer(s, n)); } std::streamsize write(const char* s, std::streamsize n) { handshake(ssl::stream_base::client); // HTTPS clients write first if (fUseSSL) return asio::write(stream, asio::buffer(s, n)); return asio::write(stream.next_layer(), asio::buffer(s, n)); } bool connect(const std::string& server, const std::string& port) { ip::tcp::resolver resolver(stream.get_io_service()); ip::tcp::resolver::query query(server.c_str(), port.c_str()); ip::tcp::resolver::iterator endpoint_iterator = resolver.resolve(query); ip::tcp::resolver::iterator end; boost::system::error_code error = asio::error::host_not_found; while (error && endpoint_iterator != end) { stream.lowest_layer().close(); stream.lowest_layer().connect(*endpoint_iterator++, error); } if (error) return false; return true; } private: bool fNeedHandshake; bool fUseSSL; asio::ssl::stream<typename Protocol::socket>& stream; }; class AcceptedConnection { public: virtual ~AcceptedConnection() {} virtual std::iostream& stream() = 0; virtual std::string peer_address_to_string() const = 0; virtual void close() = 0; }; template <typename Protocol> class AcceptedConnectionImpl : public AcceptedConnection { public: AcceptedConnectionImpl( asio::io_service& io_service, ssl::context &context, bool fUseSSL) : sslStream(io_service, context), _d(sslStream, fUseSSL), _stream(_d) { } virtual std::iostream& stream() { return _stream; } virtual std::string peer_address_to_string() const { return peer.address().to_string(); } virtual void close() { _stream.close(); } typename Protocol::endpoint peer; asio::ssl::stream<typename Protocol::socket> sslStream; private: SSLIOStreamDevice<Protocol> _d; iostreams::stream< SSLIOStreamDevice<Protocol> > _stream; }; void ServiceConnection(AcceptedConnection *conn); // Forward declaration required for RPCListen template <typename Protocol, typename SocketAcceptorService> static void RPCAcceptHandler(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor, ssl::context& context, bool fUseSSL, AcceptedConnection* conn, const boost::system::error_code& error); /** * Sets up I/O resources to accept and handle a new connection. */ template <typename Protocol, typename SocketAcceptorService> static void RPCListen(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor, ssl::context& context, const bool fUseSSL) { // Accept connection AcceptedConnectionImpl<Protocol>* conn = new AcceptedConnectionImpl<Protocol>(acceptor->get_io_service(), context, fUseSSL); acceptor->async_accept( conn->sslStream.lowest_layer(), conn->peer, boost::bind(&RPCAcceptHandler<Protocol, SocketAcceptorService>, acceptor, boost::ref(context), fUseSSL, conn, boost::asio::placeholders::error)); } /** * Accept and handle incoming connection. */ template <typename Protocol, typename SocketAcceptorService> static void RPCAcceptHandler(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor, ssl::context& context, const bool fUseSSL, AcceptedConnection* conn, const boost::system::error_code& error) { // Immediately start accepting new connections, except when we're cancelled or our socket is closed. if (error != asio::error::operation_aborted && acceptor->is_open()) RPCListen(acceptor, context, fUseSSL); AcceptedConnectionImpl<ip::tcp>* tcp_conn = dynamic_cast< AcceptedConnectionImpl<ip::tcp>* >(conn); // TODO: Actually handle errors if (error) { delete conn; } // Restrict callers by IP. It is important to // do this before starting client thread, to filter out // certain DoS and misbehaving clients. else if (tcp_conn && !ClientAllowed(tcp_conn->peer.address())) { // Only send a 403 if we're not using SSL to prevent a DoS during the SSL handshake. if (!fUseSSL) conn->stream() << HTTPReply(HTTP_FORBIDDEN, "", false) << std::flush; delete conn; } else { ServiceConnection(conn); conn->close(); delete conn; } } void StartRPCThreads() { strRPCUserColonPass = mapArgs["-rpcuser"] + ":" + mapArgs["-rpcpassword"]; if ((mapArgs["-rpcpassword"] == "") || (mapArgs["-rpcuser"] == mapArgs["-rpcpassword"])) { unsigned char rand_pwd[32]; RAND_bytes(rand_pwd, 32); string strWhatAmI = "To use adnd"; if (mapArgs.count("-server")) strWhatAmI = strprintf(_("To use the %s option"), "\"-server\""); else if (mapArgs.count("-daemon")) strWhatAmI = strprintf(_("To use the %s option"), "\"-daemon\""); uiInterface.ThreadSafeMessageBox(strprintf( _("%s, you must set a rpcpassword in the configuration file:\n" "%s\n" "It is recommended you use the following random password:\n" "rpcuser=adnrpc\n" "rpcpassword=%s\n" "(you do not need to remember this password)\n" "The username and password MUST NOT be the same.\n" "If the file does not exist, create it with owner-readable-only file permissions.\n" "It is also recommended to set alertnotify so you are notified of problems;\n" "for example: alertnotify=echo %%s | mail -s \"Adn Alert\" admin@foo.com\n"), strWhatAmI.c_str(), GetConfigFile().string().c_str(), EncodeBase58(&rand_pwd[0],&rand_pwd[0]+32).c_str()), "", CClientUIInterface::MSG_ERROR); StartShutdown(); return; } assert(rpc_io_service == NULL); rpc_io_service = new asio::io_service(); rpc_ssl_context = new ssl::context(*rpc_io_service, ssl::context::sslv23); const bool fUseSSL = GetBoolArg("-rpcssl"); if (fUseSSL) { rpc_ssl_context->set_options(ssl::context::no_sslv2); filesystem::path pathCertFile(GetArg("-rpcsslcertificatechainfile", "server.cert")); if (!pathCertFile.is_complete()) pathCertFile = filesystem::path(GetDataDir()) / pathCertFile; if (filesystem::exists(pathCertFile)) rpc_ssl_context->use_certificate_chain_file(pathCertFile.string()); else printf("ThreadRPCServer ERROR: missing server certificate file %s\n", pathCertFile.string().c_str()); filesystem::path pathPKFile(GetArg("-rpcsslprivatekeyfile", "server.pem")); if (!pathPKFile.is_complete()) pathPKFile = filesystem::path(GetDataDir()) / pathPKFile; if (filesystem::exists(pathPKFile)) rpc_ssl_context->use_private_key_file(pathPKFile.string(), ssl::context::pem); else printf("ThreadRPCServer ERROR: missing server private key file %s\n", pathPKFile.string().c_str()); string strCiphers = GetArg("-rpcsslciphers", "TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH"); SSL_CTX_set_cipher_list(rpc_ssl_context->impl(), strCiphers.c_str()); } // Try a dual IPv6/IPv4 socket, falling back to separate IPv4 and IPv6 sockets const bool loopback = !mapArgs.count("-rpcallowip"); asio::ip::address bindAddress = loopback ? asio::ip::address_v6::loopback() : asio::ip::address_v6::any(); ip::tcp::endpoint endpoint(bindAddress, GetArg("-rpcport", GetDefaultRPCPort())); boost::system::error_code v6_only_error; boost::shared_ptr<ip::tcp::acceptor> acceptor(new ip::tcp::acceptor(*rpc_io_service)); bool fListening = false; std::string strerr; try { acceptor->open(endpoint.protocol()); acceptor->set_option(boost::asio::ip::tcp::acceptor::reuse_address(true)); // Try making the socket dual IPv6/IPv4 (if listening on the "any" address) acceptor->set_option(boost::asio::ip::v6_only(loopback), v6_only_error); acceptor->bind(endpoint); acceptor->listen(socket_base::max_connections); RPCListen(acceptor, *rpc_ssl_context, fUseSSL); fListening = true; } catch(boost::system::system_error &e) { strerr = strprintf(_("An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s"), endpoint.port(), e.what()); } try { // If dual IPv6/IPv4 failed (or we're opening loopback interfaces only), open IPv4 separately if (!fListening || loopback || v6_only_error) { bindAddress = loopback ? asio::ip::address_v4::loopback() : asio::ip::address_v4::any(); endpoint.address(bindAddress); acceptor.reset(new ip::tcp::acceptor(*rpc_io_service)); acceptor->open(endpoint.protocol()); acceptor->set_option(boost::asio::ip::tcp::acceptor::reuse_address(true)); acceptor->bind(endpoint); acceptor->listen(socket_base::max_connections); RPCListen(acceptor, *rpc_ssl_context, fUseSSL); fListening = true; } } catch(boost::system::system_error &e) { strerr = strprintf(_("An error occurred while setting up the RPC port %u for listening on IPv4: %s"), endpoint.port(), e.what()); } if (!fListening) { uiInterface.ThreadSafeMessageBox(strerr, "", CClientUIInterface::MSG_ERROR); StartShutdown(); return; } rpc_worker_group = new boost::thread_group(); for (int i = 0; i < GetArg("-rpcthreads", 4); i++) rpc_worker_group->create_thread(boost::bind(&asio::io_service::run, rpc_io_service)); } void StopRPCThreads() { if (rpc_io_service == NULL) return; rpc_io_service->stop(); if (rpc_worker_group != NULL) rpc_worker_group->join_all(); delete rpc_worker_group; rpc_worker_group = NULL; delete rpc_ssl_context; rpc_ssl_context = NULL; delete rpc_io_service; rpc_io_service = NULL; } class JSONRequest { public: Value id; string strMethod; Array params; JSONRequest() { id = Value::null; } void parse(const Value& valRequest); }; void JSONRequest::parse(const Value& valRequest) { // Parse request if (valRequest.type() != obj_type) throw JSONRPCError(RPC_INVALID_REQUEST, "Invalid Request object"); const Object& request = valRequest.get_obj(); // Parse id now so errors from here on will have the id id = find_value(request, "id"); // Parse method Value valMethod = find_value(request, "method"); if (valMethod.type() == null_type) throw JSONRPCError(RPC_INVALID_REQUEST, "Missing method"); if (valMethod.type() != str_type) throw JSONRPCError(RPC_INVALID_REQUEST, "Method must be a string"); strMethod = valMethod.get_str(); if (strMethod != "getwork" && strMethod != "getworkex" && strMethod != "getblocktemplate") printf("ThreadRPCServer method=%s\n", strMethod.c_str()); // Parse params Value valParams = find_value(request, "params"); if (valParams.type() == array_type) params = valParams.get_array(); else if (valParams.type() == null_type) params = Array(); else throw JSONRPCError(RPC_INVALID_REQUEST, "Params must be an array"); } static Object JSONRPCExecOne(const Value& req) { Object rpc_result; JSONRequest jreq; try { jreq.parse(req); Value result = tableRPC.execute(jreq.strMethod, jreq.params); rpc_result = JSONRPCReplyObj(result, Value::null, jreq.id); } catch (Object& objError) { rpc_result = JSONRPCReplyObj(Value::null, objError, jreq.id); } catch (std::exception& e) { rpc_result = JSONRPCReplyObj(Value::null, JSONRPCError(RPC_PARSE_ERROR, e.what()), jreq.id); } return rpc_result; } static string JSONRPCExecBatch(const Array& vReq) { Array ret; for (unsigned int reqIdx = 0; reqIdx < vReq.size(); reqIdx++) ret.push_back(JSONRPCExecOne(vReq[reqIdx])); return write_string(Value(ret), false) + "\n"; } void ServiceConnection(AcceptedConnection *conn) { bool fRun = true; while (fRun) { int nProto = 0; map<string, string> mapHeaders; string strRequest, strMethod, strURI; // Read HTTP request line if (!ReadHTTPRequestLine(conn->stream(), nProto, strMethod, strURI)) break; // Read HTTP message headers and body ReadHTTPMessage(conn->stream(), mapHeaders, strRequest, nProto); if (strURI != "/") { conn->stream() << HTTPReply(HTTP_NOT_FOUND, "", false) << std::flush; break; } // Check authorization if (mapHeaders.count("authorization") == 0) { conn->stream() << HTTPReply(HTTP_UNAUTHORIZED, "", false) << std::flush; break; } if (!HTTPAuthorized(mapHeaders)) { printf("ThreadRPCServer incorrect password attempt from %s\n", conn->peer_address_to_string().c_str()); /* Deter brute-forcing short passwords. If this results in a DoS the user really shouldn't have their RPC port exposed. */ if (mapArgs["-rpcpassword"].size() < 20) MilliSleep(250); conn->stream() << HTTPReply(HTTP_UNAUTHORIZED, "", false) << std::flush; break; } if (mapHeaders["connection"] == "close") fRun = false; JSONRequest jreq; try { // Parse request Value valRequest; if (!read_string(strRequest, valRequest)) throw JSONRPCError(RPC_PARSE_ERROR, "Parse error"); string strReply; // singleton request if (valRequest.type() == obj_type) { jreq.parse(valRequest); Value result = tableRPC.execute(jreq.strMethod, jreq.params); // Send reply strReply = JSONRPCReply(result, Value::null, jreq.id); // array of requests } else if (valRequest.type() == array_type) strReply = JSONRPCExecBatch(valRequest.get_array()); else throw JSONRPCError(RPC_PARSE_ERROR, "Top-level object parse error"); conn->stream() << HTTPReply(HTTP_OK, strReply, fRun) << std::flush; } catch (Object& objError) { ErrorReply(conn->stream(), objError, jreq.id); break; } catch (std::exception& e) { ErrorReply(conn->stream(), JSONRPCError(RPC_PARSE_ERROR, e.what()), jreq.id); break; } } } json_spirit::Value CRPCTable::execute(const std::string &strMethod, const json_spirit::Array &params) const { // Find method const CRPCCommand *pcmd = tableRPC[strMethod]; if (!pcmd) throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Method not found"); if (pcmd->reqWallet && !pwalletMain) throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Method not found (disabled)"); // Observe safe mode string strWarning = GetWarnings("rpc"); if (strWarning != "" && !GetBoolArg("-disablesafemode") && !pcmd->okSafeMode) throw JSONRPCError(RPC_FORBIDDEN_BY_SAFE_MODE, string("Safe mode: ") + strWarning); try { // Execute Value result; { if (pcmd->threadSafe) result = pcmd->actor(params, false); else if (!pwalletMain) { LOCK(cs_main); result = pcmd->actor(params, false); } else { LOCK2(cs_main, pwalletMain->cs_wallet); result = pcmd->actor(params, false); } } return result; } catch (std::exception& e) { throw JSONRPCError(RPC_MISC_ERROR, e.what()); } } Object CallRPC(const string& strMethod, const Array& params) { if (mapArgs["-rpcuser"] == "" && mapArgs["-rpcpassword"] == "") throw runtime_error(strprintf( _("You must set rpcpassword=<password> in the configuration file:\n%s\n" "If the file does not exist, create it with owner-readable-only file permissions."), GetConfigFile().string().c_str())); // Connect to localhost bool fUseSSL = GetBoolArg("-rpcssl"); asio::io_service io_service; ssl::context context(io_service, ssl::context::sslv23); context.set_options(ssl::context::no_sslv2); asio::ssl::stream<asio::ip::tcp::socket> sslStream(io_service, context); SSLIOStreamDevice<asio::ip::tcp> d(sslStream, fUseSSL); iostreams::stream< SSLIOStreamDevice<asio::ip::tcp> > stream(d); if (!d.connect(GetArg("-rpcconnect", "127.0.0.1"), GetArg("-rpcport", itostr(GetDefaultRPCPort())))) throw runtime_error("couldn't connect to server"); // HTTP basic authentication string strUserPass64 = EncodeBase64(mapArgs["-rpcuser"] + ":" + mapArgs["-rpcpassword"]); map<string, string> mapRequestHeaders; mapRequestHeaders["Authorization"] = string("Basic ") + strUserPass64; // Send request string strRequest = JSONRPCRequest(strMethod, params, 1); string strPost = HTTPPost(strRequest, mapRequestHeaders); stream << strPost << std::flush; // Receive HTTP reply status int nProto = 0; int nStatus = ReadHTTPStatus(stream, nProto); // Receive HTTP reply message headers and body map<string, string> mapHeaders; string strReply; ReadHTTPMessage(stream, mapHeaders, strReply, nProto); if (nStatus == HTTP_UNAUTHORIZED) throw runtime_error("incorrect rpcuser or rpcpassword (authorization failed)"); else if (nStatus >= 400 && nStatus != HTTP_BAD_REQUEST && nStatus != HTTP_NOT_FOUND && nStatus != HTTP_INTERNAL_SERVER_ERROR) throw runtime_error(strprintf("server returned HTTP error %d", nStatus)); else if (strReply.empty()) throw runtime_error("no response from server"); // Parse reply Value valReply; if (!read_string(strReply, valReply)) throw runtime_error("couldn't parse reply from server"); const Object& reply = valReply.get_obj(); if (reply.empty()) throw runtime_error("expected reply to have result, error and id properties"); return reply; } template<typename T> void ConvertTo(Value& value, bool fAllowNull=false) { if (fAllowNull && value.type() == null_type) return; if (value.type() == str_type) { // reinterpret string as unquoted json value Value value2; string strJSON = value.get_str(); if (!read_string(strJSON, value2)) throw runtime_error(string("Error parsing JSON:")+strJSON); ConvertTo<T>(value2, fAllowNull); value = value2; } else { value = value.get_value<T>(); } } // Convert strings to command-specific RPC representation Array RPCConvertValues(const std::string &strMethod, const std::vector<std::string> &strParams) { Array params; BOOST_FOREACH(const std::string &param, strParams) params.push_back(param); int n = params.size(); // // Special case non-string parameter types // if (strMethod == "stop" && n > 0) ConvertTo<bool>(params[0]); if (strMethod == "getaddednodeinfo" && n > 0) ConvertTo<bool>(params[0]); if (strMethod == "setgenerate" && n > 0) ConvertTo<bool>(params[0]); if (strMethod == "setgenerate" && n > 1) ConvertTo<boost::int64_t>(params[1]); if (strMethod == "getnetworkhashps" && n > 0) ConvertTo<boost::int64_t>(params[0]); if (strMethod == "getnetworkhashps" && n > 1) ConvertTo<boost::int64_t>(params[1]); if (strMethod == "sendtoaddress" && n > 1) ConvertTo<double>(params[1]); if (strMethod == "settxfee" && n > 0) ConvertTo<double>(params[0]); if (strMethod == "setmininput" && n > 0) ConvertTo<double>(params[0]); if (strMethod == "getreceivedbyaddress" && n > 1) ConvertTo<boost::int64_t>(params[1]); if (strMethod == "getreceivedbyaccount" && n > 1) ConvertTo<boost::int64_t>(params[1]); if (strMethod == "listreceivedbyaddress" && n > 0) ConvertTo<boost::int64_t>(params[0]); if (strMethod == "listreceivedbyaddress" && n > 1) ConvertTo<bool>(params[1]); if (strMethod == "listreceivedbyaccount" && n > 0) ConvertTo<boost::int64_t>(params[0]); if (strMethod == "listreceivedbyaccount" && n > 1) ConvertTo<bool>(params[1]); if (strMethod == "getbalance" && n > 1) ConvertTo<boost::int64_t>(params[1]); if (strMethod == "getblockhash" && n > 0) ConvertTo<boost::int64_t>(params[0]); if (strMethod == "move" && n > 2) ConvertTo<double>(params[2]); if (strMethod == "move" && n > 3) ConvertTo<boost::int64_t>(params[3]); if (strMethod == "sendfrom" && n > 2) ConvertTo<double>(params[2]); if (strMethod == "sendfrom" && n > 3) ConvertTo<boost::int64_t>(params[3]); if (strMethod == "listtransactions" && n > 1) ConvertTo<boost::int64_t>(params[1]); if (strMethod == "listtransactions" && n > 2) ConvertTo<boost::int64_t>(params[2]); if (strMethod == "listaccounts" && n > 0) ConvertTo<boost::int64_t>(params[0]); if (strMethod == "walletpassphrase" && n > 1) ConvertTo<boost::int64_t>(params[1]); if (strMethod == "getblocktemplate" && n > 0) ConvertTo<Object>(params[0]); if (strMethod == "listsinceblock" && n > 1) ConvertTo<boost::int64_t>(params[1]); if (strMethod == "sendmany" && n > 1) ConvertTo<Object>(params[1]); if (strMethod == "sendmany" && n > 2) ConvertTo<boost::int64_t>(params[2]); if (strMethod == "addmultisigaddress" && n > 0) ConvertTo<boost::int64_t>(params[0]); if (strMethod == "addmultisigaddress" && n > 1) ConvertTo<Array>(params[1]); if (strMethod == "createmultisig" && n > 0) ConvertTo<boost::int64_t>(params[0]); if (strMethod == "createmultisig" && n > 1) ConvertTo<Array>(params[1]); if (strMethod == "listunspent" && n > 0) ConvertTo<boost::int64_t>(params[0]); if (strMethod == "listunspent" && n > 1) ConvertTo<boost::int64_t>(params[1]); if (strMethod == "listunspent" && n > 2) ConvertTo<Array>(params[2]); if (strMethod == "getblock" && n > 1) ConvertTo<bool>(params[1]); if (strMethod == "getrawtransaction" && n > 1) ConvertTo<boost::int64_t>(params[1]); if (strMethod == "createrawtransaction" && n > 0) ConvertTo<Array>(params[0]); if (strMethod == "createrawtransaction" && n > 1) ConvertTo<Object>(params[1]); if (strMethod == "signrawtransaction" && n > 1) ConvertTo<Array>(params[1], true); if (strMethod == "signrawtransaction" && n > 2) ConvertTo<Array>(params[2], true); if (strMethod == "sendrawtransaction" && n > 1) ConvertTo<bool>(params[1], true); if (strMethod == "gettxout" && n > 1) ConvertTo<boost::int64_t>(params[1]); if (strMethod == "gettxout" && n > 2) ConvertTo<bool>(params[2]); if (strMethod == "lockunspent" && n > 0) ConvertTo<bool>(params[0]); if (strMethod == "lockunspent" && n > 1) ConvertTo<Array>(params[1]); if (strMethod == "importprivkey" && n > 2) ConvertTo<bool>(params[2]); if (strMethod == "verifychain" && n > 0) ConvertTo<boost::int64_t>(params[0]); if (strMethod == "verifychain" && n > 1) ConvertTo<boost::int64_t>(params[1]); return params; } int CommandLineRPC(int argc, char *argv[]) { string strPrint; int nRet = 0; try { // Skip switches while (argc > 1 && IsSwitchChar(argv[1][0])) { argc--; argv++; } // Method if (argc < 2) throw runtime_error("too few parameters"); string strMethod = argv[1]; // Parameters default to strings std::vector<std::string> strParams(&argv[2], &argv[argc]); Array params = RPCConvertValues(strMethod, strParams); // Execute Object reply = CallRPC(strMethod, params); // Parse reply const Value& result = find_value(reply, "result"); const Value& error = find_value(reply, "error"); if (error.type() != null_type) { // Error strPrint = "error: " + write_string(error, false); int code = find_value(error.get_obj(), "code").get_int(); nRet = abs(code); } else { // Result if (result.type() == null_type) strPrint = ""; else if (result.type() == str_type) strPrint = result.get_str(); else strPrint = write_string(result, true); } } catch (boost::thread_interrupted) { throw; } catch (std::exception& e) { strPrint = string("error: ") + e.what(); nRet = 87; } catch (...) { PrintException(NULL, "CommandLineRPC()"); } if (strPrint != "") { fprintf((nRet == 0 ? stdout : stderr), "%s\n", strPrint.c_str()); } return nRet; } #ifdef TEST int main(int argc, char *argv[]) { #ifdef _MSC_VER // Turn off Microsoft heap dump noise _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE); _CrtSetReportFile(_CRT_WARN, CreateFile("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0)); #endif setbuf(stdin, NULL); setbuf(stdout, NULL); setbuf(stderr, NULL); try { if (argc >= 2 && string(argv[1]) == "-server") { printf("server ready\n"); ThreadRPCServer(NULL); } else { return CommandLineRPC(argc, argv); } } catch (boost::thread_interrupted) { throw; } catch (std::exception& e) { PrintException(&e, "main()"); } catch (...) { PrintException(NULL, "main()"); } return 0; } #endif const CRPCTable tableRPC;
/* * 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 "third_party/blink/renderer/platform/heap/heap.h" #include <algorithm> #include <limits> #include <memory> #include "base/trace_event/process_memory_dump.h" #include "third_party/blink/public/platform/platform.h" #include "third_party/blink/renderer/platform/bindings/script_forbidden_scope.h" #include "third_party/blink/renderer/platform/heap/address_cache.h" #include "third_party/blink/renderer/platform/heap/blink_gc_memory_dump_provider.h" #include "third_party/blink/renderer/platform/heap/heap_compact.h" #include "third_party/blink/renderer/platform/heap/heap_stats_collector.h" #include "third_party/blink/renderer/platform/heap/marking_visitor.h" #include "third_party/blink/renderer/platform/heap/page_memory.h" #include "third_party/blink/renderer/platform/heap/page_pool.h" #include "third_party/blink/renderer/platform/heap/safe_point.h" #include "third_party/blink/renderer/platform/heap/thread_state.h" #include "third_party/blink/renderer/platform/histogram.h" #include "third_party/blink/renderer/platform/instrumentation/tracing/trace_event.h" #include "third_party/blink/renderer/platform/instrumentation/tracing/web_memory_allocator_dump.h" #include "third_party/blink/renderer/platform/instrumentation/tracing/web_process_memory_dump.h" #include "third_party/blink/renderer/platform/wtf/allocator/partitions.h" #include "third_party/blink/renderer/platform/wtf/assertions.h" #include "third_party/blink/renderer/platform/wtf/leak_annotations.h" #include "third_party/blink/renderer/platform/wtf/time.h" namespace blink { HeapAllocHooks::AllocationHook* HeapAllocHooks::allocation_hook_ = nullptr; HeapAllocHooks::FreeHook* HeapAllocHooks::free_hook_ = nullptr; ThreadHeapStats::ThreadHeapStats() : allocated_space_(0), allocated_object_size_(0), object_size_at_last_gc_(0), marked_object_size_(0), marked_object_size_at_last_complete_sweep_(0), wrapper_count_(0), wrapper_count_at_last_gc_(0), collected_wrapper_count_(0), partition_alloc_size_at_last_gc_( WTF::Partitions::TotalSizeOfCommittedPages()), estimated_marking_time_per_byte_(0.0) {} double ThreadHeapStats::EstimatedMarkingTime() { // Use 8 ms as initial estimated marking time. // 8 ms is long enough for low-end mobile devices to mark common // real-world object graphs. if (estimated_marking_time_per_byte_ == 0) return 0.008; // Assuming that the collection rate of this GC will be mostly equal to // the collection rate of the last GC, estimate the marking time of this GC. return estimated_marking_time_per_byte_ * (AllocatedObjectSize() + MarkedObjectSize()); } void ThreadHeapStats::Reset() { object_size_at_last_gc_ = allocated_object_size_ + marked_object_size_; partition_alloc_size_at_last_gc_ = WTF::Partitions::TotalSizeOfCommittedPages(); allocated_object_size_ = 0; marked_object_size_ = 0; wrapper_count_at_last_gc_ = wrapper_count_; collected_wrapper_count_ = 0; } void ThreadHeapStats::IncreaseAllocatedObjectSize(size_t delta) { allocated_object_size_ += delta; ProcessHeap::IncreaseTotalAllocatedObjectSize(delta); } void ThreadHeapStats::DecreaseAllocatedObjectSize(size_t delta) { allocated_object_size_ -= delta; ProcessHeap::DecreaseTotalAllocatedObjectSize(delta); } void ThreadHeapStats::IncreaseMarkedObjectSize(size_t delta) { marked_object_size_ += delta; ProcessHeap::IncreaseTotalMarkedObjectSize(delta); } void ThreadHeapStats::IncreaseAllocatedSpace(size_t delta) { allocated_space_ += delta; ProcessHeap::IncreaseTotalAllocatedSpace(delta); } void ThreadHeapStats::DecreaseAllocatedSpace(size_t delta) { allocated_space_ -= delta; ProcessHeap::DecreaseTotalAllocatedSpace(delta); } double ThreadHeapStats::LiveObjectRateSinceLastGC() const { if (ObjectSizeAtLastGC() > 0) return static_cast<double>(MarkedObjectSize()) / ObjectSizeAtLastGC(); return 0.0; } ThreadHeap::ThreadHeap(ThreadState* thread_state) : thread_state_(thread_state), heap_stats_collector_(std::make_unique<ThreadHeapStatsCollector>()), region_tree_(std::make_unique<RegionTree>()), address_cache_(std::make_unique<AddressCache>()), free_page_pool_(std::make_unique<PagePool>()), marking_worklist_(nullptr), not_fully_constructed_worklist_(nullptr), weak_callback_worklist_(nullptr), vector_backing_arena_index_(BlinkGC::kVector1ArenaIndex), current_arena_ages_(0) { if (ThreadState::Current()->IsMainThread()) main_thread_heap_ = this; for (int arena_index = 0; arena_index < BlinkGC::kLargeObjectArenaIndex; arena_index++) arenas_[arena_index] = new NormalPageArena(thread_state_, arena_index); arenas_[BlinkGC::kLargeObjectArenaIndex] = new LargeObjectArena(thread_state_, BlinkGC::kLargeObjectArenaIndex); likely_to_be_promptly_freed_ = std::make_unique<int[]>(kLikelyToBePromptlyFreedArraySize); ClearArenaAges(); } ThreadHeap::~ThreadHeap() { for (int i = 0; i < BlinkGC::kNumberOfArenas; ++i) delete arenas_[i]; } Address ThreadHeap::CheckAndMarkPointer(MarkingVisitor* visitor, Address address) { DCHECK(thread_state_->InAtomicMarkingPause()); #if !DCHECK_IS_ON() if (address_cache_->Lookup(address)) return nullptr; #endif if (BasePage* page = LookupPageForAddress(address)) { #if DCHECK_IS_ON() DCHECK(page->Contains(address)); #endif DCHECK(!address_cache_->Lookup(address)); DCHECK(&visitor->Heap() == &page->Arena()->GetThreadState()->Heap()); visitor->ConservativelyMarkAddress(page, address); return address; } #if !DCHECK_IS_ON() address_cache_->AddEntry(address); #else if (!address_cache_->Lookup(address)) address_cache_->AddEntry(address); #endif return nullptr; } #if DCHECK_IS_ON() // To support unit testing of the marking of off-heap root references // into the heap, provide a checkAndMarkPointer() version with an // extra notification argument. Address ThreadHeap::CheckAndMarkPointer( MarkingVisitor* visitor, Address address, MarkedPointerCallbackForTesting callback) { DCHECK(thread_state_->InAtomicMarkingPause()); if (BasePage* page = LookupPageForAddress(address)) { DCHECK(page->Contains(address)); DCHECK(!address_cache_->Lookup(address)); DCHECK(&visitor->Heap() == &page->Arena()->GetThreadState()->Heap()); visitor->ConservativelyMarkAddress(page, address, callback); return address; } if (!address_cache_->Lookup(address)) address_cache_->AddEntry(address); return nullptr; } #endif // DCHECK_IS_ON() void ThreadHeap::RegisterWeakTable(void* table, EphemeronCallback iteration_callback) { DCHECK(thread_state_->InAtomicMarkingPause()); #if DCHECK_IS_ON() auto result = ephemeron_callbacks_.insert(table, iteration_callback); DCHECK(result.is_new_entry || result.stored_value->value == iteration_callback); #else ephemeron_callbacks_.insert(table, iteration_callback); #endif // DCHECK_IS_ON() } void ThreadHeap::CommitCallbackStacks() { marking_worklist_.reset(new MarkingWorklist()); not_fully_constructed_worklist_.reset(new NotFullyConstructedWorklist()); weak_callback_worklist_.reset(new WeakCallbackWorklist()); DCHECK(ephemeron_callbacks_.IsEmpty()); } void ThreadHeap::DecommitCallbackStacks() { marking_worklist_.reset(nullptr); not_fully_constructed_worklist_.reset(nullptr); weak_callback_worklist_.reset(nullptr); ephemeron_callbacks_.clear(); } HeapCompact* ThreadHeap::Compaction() { if (!compaction_) compaction_ = HeapCompact::Create(); return compaction_.get(); } void ThreadHeap::RegisterMovingObjectReference(MovableReference* slot) { DCHECK(slot); DCHECK(*slot); Compaction()->RegisterMovingObjectReference(slot); } void ThreadHeap::RegisterMovingObjectCallback(MovableReference reference, MovingObjectCallback callback, void* callback_data) { DCHECK(reference); Compaction()->RegisterMovingObjectCallback(reference, callback, callback_data); } void ThreadHeap::ProcessMarkingStack(Visitor* visitor) { bool complete = AdvanceMarkingStackProcessing( visitor, std::numeric_limits<double>::infinity()); CHECK(complete); } void ThreadHeap::MarkNotFullyConstructedObjects(Visitor* visitor) { TRACE_EVENT0("blink_gc", "ThreadHeap::MarkNotFullyConstructedObjects"); DCHECK(!thread_state_->IsIncrementalMarking()); NotFullyConstructedItem item; while ( not_fully_constructed_worklist_->Pop(WorklistTaskId::MainThread, &item)) { BasePage* const page = PageFromObject(item); reinterpret_cast<MarkingVisitor*>(visitor)->ConservativelyMarkAddress( page, reinterpret_cast<Address>(item)); } } void ThreadHeap::InvokeEphemeronCallbacks(Visitor* visitor) { // Mark any strong pointers that have now become reachable in ephemeron maps. TRACE_EVENT0("blink_gc", "ThreadHeap::InvokeEphemeronCallbacks"); // Avoid supporting a subtle scheme that allows insertion while iterating // by just creating temporary lists for iteration and sinking. WTF::HashMap<void*, EphemeronCallback> iteration_set; WTF::HashMap<void*, EphemeronCallback> final_set; bool found_new = false; do { iteration_set = std::move(ephemeron_callbacks_); ephemeron_callbacks_.clear(); for (auto& tuple : iteration_set) { final_set.insert(tuple.key, tuple.value); tuple.value(visitor, tuple.key); } found_new = !ephemeron_callbacks_.IsEmpty(); } while (found_new); ephemeron_callbacks_ = std::move(final_set); } bool ThreadHeap::AdvanceMarkingStackProcessing(Visitor* visitor, double deadline_seconds) { const size_t kDeadlineCheckInterval = 2500; size_t processed_callback_count = 0; // Ephemeron fixed point loop. do { { // Iteratively mark all objects that are reachable from the objects // currently pushed onto the marking stack. TRACE_EVENT0("blink_gc", "ThreadHeap::processMarkingStackSingleThreaded"); MarkingItem item; while (marking_worklist_->Pop(WorklistTaskId::MainThread, &item)) { item.callback(visitor, item.object); processed_callback_count++; if (processed_callback_count % kDeadlineCheckInterval == 0) { if (deadline_seconds <= CurrentTimeTicksInSeconds()) { return false; } } } } InvokeEphemeronCallbacks(visitor); // Rerun loop if ephemeron processing queued more objects for tracing. } while (!marking_worklist_->IsGlobalEmpty()); return true; } void ThreadHeap::WeakProcessing(Visitor* visitor) { TRACE_EVENT0("blink_gc", "ThreadHeap::WeakProcessing"); double start_time = WTF::CurrentTimeTicksInMilliseconds(); // Weak processing may access unmarked objects but are forbidden from // ressurecting them. ThreadState::ObjectResurrectionForbiddenScope object_resurrection_forbidden( ThreadState::Current()); // Call weak callbacks on objects that may now be pointing to dead objects. CustomCallbackItem item; while (weak_callback_worklist_->Pop(WorklistTaskId::MainThread, &item)) { item.callback(visitor, item.object); } // Weak callbacks should not add any new objects for marking. DCHECK(marking_worklist_->IsGlobalEmpty()); double time_for_weak_processing = WTF::CurrentTimeTicksInMilliseconds() - start_time; DEFINE_THREAD_SAFE_STATIC_LOCAL( CustomCountHistogram, weak_processing_time_histogram, ("BlinkGC.TimeForGlobalWeakProcessing", 1, 10 * 1000, 50)); weak_processing_time_histogram.Count(time_for_weak_processing); } void ThreadHeap::VerifyMarking() { for (int i = 0; i < BlinkGC::kNumberOfArenas; ++i) { arenas_[i]->VerifyMarking(); } } void ThreadHeap::ReportMemoryUsageHistogram() { static size_t supported_max_size_in_mb = 4 * 1024; static size_t observed_max_size_in_mb = 0; // We only report the memory in the main thread. if (!IsMainThread()) return; // +1 is for rounding up the sizeInMB. size_t size_in_mb = ThreadState::Current()->Heap().HeapStats().AllocatedSpace() / 1024 / 1024 + 1; if (size_in_mb >= supported_max_size_in_mb) size_in_mb = supported_max_size_in_mb - 1; if (size_in_mb > observed_max_size_in_mb) { // Send a UseCounter only when we see the highest memory usage // we've ever seen. DEFINE_THREAD_SAFE_STATIC_LOCAL( EnumerationHistogram, commited_size_histogram, ("BlinkGC.CommittedSize", supported_max_size_in_mb)); commited_size_histogram.Count(size_in_mb); observed_max_size_in_mb = size_in_mb; } } void ThreadHeap::ReportMemoryUsageForTracing() { bool gc_tracing_enabled; TRACE_EVENT_CATEGORY_GROUP_ENABLED(TRACE_DISABLED_BY_DEFAULT("blink_gc"), &gc_tracing_enabled); if (!gc_tracing_enabled) return; ThreadHeap& heap = ThreadState::Current()->Heap(); // These values are divided by 1024 to avoid overflow in practical cases // (TRACE_COUNTER values are 32-bit ints). // They are capped to INT_MAX just in case. TRACE_COUNTER1(TRACE_DISABLED_BY_DEFAULT("blink_gc"), "ThreadHeap::allocatedObjectSizeKB", std::min(heap.HeapStats().AllocatedObjectSize() / 1024, static_cast<size_t>(INT_MAX))); TRACE_COUNTER1(TRACE_DISABLED_BY_DEFAULT("blink_gc"), "ThreadHeap::markedObjectSizeKB", std::min(heap.HeapStats().MarkedObjectSize() / 1024, static_cast<size_t>(INT_MAX))); TRACE_COUNTER1( TRACE_DISABLED_BY_DEFAULT("blink_gc"), "ThreadHeap::markedObjectSizeAtLastCompleteSweepKB", std::min(heap.HeapStats().MarkedObjectSizeAtLastCompleteSweep() / 1024, static_cast<size_t>(INT_MAX))); TRACE_COUNTER1(TRACE_DISABLED_BY_DEFAULT("blink_gc"), "ThreadHeap::allocatedSpaceKB", std::min(heap.HeapStats().AllocatedSpace() / 1024, static_cast<size_t>(INT_MAX))); TRACE_COUNTER1(TRACE_DISABLED_BY_DEFAULT("blink_gc"), "ThreadHeap::objectSizeAtLastGCKB", std::min(heap.HeapStats().ObjectSizeAtLastGC() / 1024, static_cast<size_t>(INT_MAX))); TRACE_COUNTER1( TRACE_DISABLED_BY_DEFAULT("blink_gc"), "ThreadHeap::wrapperCount", std::min(heap.HeapStats().WrapperCount(), static_cast<size_t>(INT_MAX))); TRACE_COUNTER1(TRACE_DISABLED_BY_DEFAULT("blink_gc"), "ThreadHeap::wrapperCountAtLastGC", std::min(heap.HeapStats().WrapperCountAtLastGC(), static_cast<size_t>(INT_MAX))); TRACE_COUNTER1(TRACE_DISABLED_BY_DEFAULT("blink_gc"), "ThreadHeap::collectedWrapperCount", std::min(heap.HeapStats().CollectedWrapperCount(), static_cast<size_t>(INT_MAX))); TRACE_COUNTER1(TRACE_DISABLED_BY_DEFAULT("blink_gc"), "ThreadHeap::partitionAllocSizeAtLastGCKB", std::min(heap.HeapStats().PartitionAllocSizeAtLastGC() / 1024, static_cast<size_t>(INT_MAX))); TRACE_COUNTER1(TRACE_DISABLED_BY_DEFAULT("blink_gc"), "Partitions::totalSizeOfCommittedPagesKB", std::min(WTF::Partitions::TotalSizeOfCommittedPages() / 1024, static_cast<size_t>(INT_MAX))); } size_t ThreadHeap::ObjectPayloadSizeForTesting() { ThreadState::AtomicPauseScope atomic_pause_scope(thread_state_); size_t object_payload_size = 0; thread_state_->SetGCPhase(ThreadState::GCPhase::kMarking); thread_state_->Heap().MakeConsistentForGC(); thread_state_->Heap().PrepareForSweep(); for (int i = 0; i < BlinkGC::kNumberOfArenas; ++i) object_payload_size += arenas_[i]->ObjectPayloadSizeForTesting(); MakeConsistentForMutator(); thread_state_->SetGCPhase(ThreadState::GCPhase::kSweeping); thread_state_->SetGCPhase(ThreadState::GCPhase::kNone); return object_payload_size; } void ThreadHeap::VisitPersistentRoots(Visitor* visitor) { DCHECK(thread_state_->InAtomicMarkingPause()); TRACE_EVENT0("blink_gc", "ThreadHeap::visitPersistentRoots"); thread_state_->VisitPersistents(visitor); } void ThreadHeap::VisitStackRoots(MarkingVisitor* visitor) { DCHECK(thread_state_->InAtomicMarkingPause()); TRACE_EVENT0("blink_gc", "ThreadHeap::visitStackRoots"); address_cache_->FlushIfDirty(); address_cache_->EnableLookup(); thread_state_->VisitStack(visitor); address_cache_->DisableLookup(); } BasePage* ThreadHeap::LookupPageForAddress(Address address) { DCHECK(thread_state_->InAtomicMarkingPause()); if (PageMemoryRegion* region = region_tree_->Lookup(address)) { return region->PageFromAddress(address); } return nullptr; } void ThreadHeap::ResetHeapCounters() { DCHECK(thread_state_->InAtomicMarkingPause()); ThreadHeap::ReportMemoryUsageForTracing(); ProcessHeap::DecreaseTotalAllocatedObjectSize(stats_.AllocatedObjectSize()); ProcessHeap::DecreaseTotalMarkedObjectSize(stats_.MarkedObjectSize()); stats_.Reset(); } void ThreadHeap::MakeConsistentForGC() { DCHECK(thread_state_->InAtomicMarkingPause()); TRACE_EVENT0("blink_gc", "ThreadHeap::MakeConsistentForGC"); for (int i = 0; i < BlinkGC::kNumberOfArenas; ++i) arenas_[i]->MakeConsistentForGC(); } void ThreadHeap::MakeConsistentForMutator() { DCHECK(thread_state_->InAtomicMarkingPause()); for (int i = 0; i < BlinkGC::kNumberOfArenas; ++i) arenas_[i]->MakeConsistentForMutator(); } void ThreadHeap::Compact() { if (!Compaction()->IsCompacting()) return; // Compaction is done eagerly and before the mutator threads get // to run again. Doing it lazily is problematic, as the mutator's // references to live objects could suddenly be invalidated by // compaction of a page/heap. We do know all the references to // the relocating objects just after marking, but won't later. // (e.g., stack references could have been created, new objects // created which refer to old collection objects, and so on.) // Compact the hash table backing store arena first, it usually has // higher fragmentation and is larger. // // TODO: implement bail out wrt any overall deadline, not compacting // the remaining arenas if the time budget has been exceeded. Compaction()->StartThreadCompaction(); for (int i = BlinkGC::kHashTableArenaIndex; i >= BlinkGC::kVector1ArenaIndex; --i) static_cast<NormalPageArena*>(arenas_[i])->SweepAndCompact(); Compaction()->FinishThreadCompaction(); } void ThreadHeap::PrepareForSweep() { DCHECK(thread_state_->InAtomicMarkingPause()); DCHECK(thread_state_->CheckThread()); for (int i = 0; i < BlinkGC::kNumberOfArenas; i++) arenas_[i]->PrepareForSweep(); } void ThreadHeap::RemoveAllPages() { DCHECK(thread_state_->CheckThread()); for (int i = 0; i < BlinkGC::kNumberOfArenas; ++i) arenas_[i]->RemoveAllPages(); } void ThreadHeap::CompleteSweep() { static_assert(BlinkGC::kEagerSweepArenaIndex == 0, "Eagerly swept arenas must be processed first."); for (int i = 0; i < BlinkGC::kNumberOfArenas; i++) arenas_[i]->CompleteSweep(); } void ThreadHeap::ClearArenaAges() { memset(arena_ages_, 0, sizeof(size_t) * BlinkGC::kNumberOfArenas); memset(likely_to_be_promptly_freed_.get(), 0, sizeof(int) * kLikelyToBePromptlyFreedArraySize); current_arena_ages_ = 0; } int ThreadHeap::ArenaIndexOfVectorArenaLeastRecentlyExpanded( int begin_arena_index, int end_arena_index) { size_t min_arena_age = arena_ages_[begin_arena_index]; int arena_index_with_min_arena_age = begin_arena_index; for (int arena_index = begin_arena_index + 1; arena_index <= end_arena_index; arena_index++) { if (arena_ages_[arena_index] < min_arena_age) { min_arena_age = arena_ages_[arena_index]; arena_index_with_min_arena_age = arena_index; } } DCHECK(IsVectorArenaIndex(arena_index_with_min_arena_age)); return arena_index_with_min_arena_age; } BaseArena* ThreadHeap::ExpandedVectorBackingArena(size_t gc_info_index) { size_t entry_index = gc_info_index & kLikelyToBePromptlyFreedArrayMask; --likely_to_be_promptly_freed_[entry_index]; int arena_index = vector_backing_arena_index_; arena_ages_[arena_index] = ++current_arena_ages_; vector_backing_arena_index_ = ArenaIndexOfVectorArenaLeastRecentlyExpanded( BlinkGC::kVector1ArenaIndex, BlinkGC::kVector4ArenaIndex); return arenas_[arena_index]; } void ThreadHeap::AllocationPointAdjusted(int arena_index) { arena_ages_[arena_index] = ++current_arena_ages_; if (vector_backing_arena_index_ == arena_index) { vector_backing_arena_index_ = ArenaIndexOfVectorArenaLeastRecentlyExpanded( BlinkGC::kVector1ArenaIndex, BlinkGC::kVector4ArenaIndex); } } void ThreadHeap::PromptlyFreed(size_t gc_info_index) { DCHECK(thread_state_->CheckThread()); size_t entry_index = gc_info_index & kLikelyToBePromptlyFreedArrayMask; // See the comment in vectorBackingArena() for why this is +3. likely_to_be_promptly_freed_[entry_index] += 3; } #if defined(ADDRESS_SANITIZER) void ThreadHeap::PoisonAllHeaps() { RecursiveMutexLocker persistent_lock( ProcessHeap::CrossThreadPersistentMutex()); // Poisoning all unmarked objects in the other arenas. for (int i = 1; i < BlinkGC::kNumberOfArenas; i++) arenas_[i]->PoisonArena(); // CrossThreadPersistents in unmarked objects may be accessed from other // threads (e.g. in CrossThreadPersistentRegion::shouldTracePersistent) and // that would be fine. ProcessHeap::GetCrossThreadPersistentRegion() .UnpoisonCrossThreadPersistents(); } void ThreadHeap::PoisonEagerArena() { RecursiveMutexLocker persistent_lock( ProcessHeap::CrossThreadPersistentMutex()); arenas_[BlinkGC::kEagerSweepArenaIndex]->PoisonArena(); // CrossThreadPersistents in unmarked objects may be accessed from other // threads (e.g. in CrossThreadPersistentRegion::shouldTracePersistent) and // that would be fine. ProcessHeap::GetCrossThreadPersistentRegion() .UnpoisonCrossThreadPersistents(); } #endif #if DCHECK_IS_ON() BasePage* ThreadHeap::FindPageFromAddress(Address address) { for (int i = 0; i < BlinkGC::kNumberOfArenas; ++i) { if (BasePage* page = arenas_[i]->FindPageFromAddress(address)) return page; } return nullptr; } #endif void ThreadHeap::TakeSnapshot(SnapshotType type) { DCHECK(thread_state_->InAtomicMarkingPause()); // 0 is used as index for freelist entries. Objects are indexed 1 to // gcInfoIndex. ThreadState::GCSnapshotInfo info(GCInfoTable::Get().GcInfoIndex() + 1); String thread_dump_name = String::Format("blink_gc/thread_%lu", static_cast<unsigned long>(thread_state_->ThreadId())); const String heaps_dump_name = thread_dump_name + "/heaps"; const String classes_dump_name = thread_dump_name + "/classes"; int number_of_heaps_reported = 0; #define SNAPSHOT_HEAP(ArenaType) \ { \ number_of_heaps_reported++; \ switch (type) { \ case SnapshotType::kHeapSnapshot: \ arenas_[BlinkGC::k##ArenaType##ArenaIndex]->TakeSnapshot( \ heaps_dump_name + "/" #ArenaType, info); \ break; \ case SnapshotType::kFreelistSnapshot: \ arenas_[BlinkGC::k##ArenaType##ArenaIndex]->TakeFreelistSnapshot( \ heaps_dump_name + "/" #ArenaType); \ break; \ default: \ NOTREACHED(); \ } \ } SNAPSHOT_HEAP(NormalPage1); SNAPSHOT_HEAP(NormalPage2); SNAPSHOT_HEAP(NormalPage3); SNAPSHOT_HEAP(NormalPage4); SNAPSHOT_HEAP(EagerSweep); SNAPSHOT_HEAP(Vector1); SNAPSHOT_HEAP(Vector2); SNAPSHOT_HEAP(Vector3); SNAPSHOT_HEAP(Vector4); SNAPSHOT_HEAP(InlineVector); SNAPSHOT_HEAP(HashTable); SNAPSHOT_HEAP(LargeObject); FOR_EACH_TYPED_ARENA(SNAPSHOT_HEAP); DCHECK_EQ(number_of_heaps_reported, BlinkGC::kNumberOfArenas); #undef SNAPSHOT_HEAP if (type == SnapshotType::kFreelistSnapshot) return; size_t total_live_count = 0; size_t total_dead_count = 0; size_t total_live_size = 0; size_t total_dead_size = 0; for (size_t gc_info_index = 1; gc_info_index <= GCInfoTable::Get().GcInfoIndex(); ++gc_info_index) { total_live_count += info.live_count[gc_info_index]; total_dead_count += info.dead_count[gc_info_index]; total_live_size += info.live_size[gc_info_index]; total_dead_size += info.dead_size[gc_info_index]; } base::trace_event::MemoryAllocatorDump* thread_dump = BlinkGCMemoryDumpProvider::Instance() ->CreateMemoryAllocatorDumpForCurrentGC(thread_dump_name); thread_dump->AddScalar("live_count", "objects", total_live_count); thread_dump->AddScalar("dead_count", "objects", total_dead_count); thread_dump->AddScalar("live_size", "bytes", total_live_size); thread_dump->AddScalar("dead_size", "bytes", total_dead_size); base::trace_event::MemoryAllocatorDump* heaps_dump = BlinkGCMemoryDumpProvider::Instance() ->CreateMemoryAllocatorDumpForCurrentGC(heaps_dump_name); base::trace_event::MemoryAllocatorDump* classes_dump = BlinkGCMemoryDumpProvider::Instance() ->CreateMemoryAllocatorDumpForCurrentGC(classes_dump_name); BlinkGCMemoryDumpProvider::Instance() ->CurrentProcessMemoryDump() ->AddOwnershipEdge(classes_dump->guid(), heaps_dump->guid()); } bool ThreadHeap::AdvanceLazySweep(double deadline_seconds) { for (int i = 0; i < BlinkGC::kNumberOfArenas; i++) { // lazySweepWithDeadline() won't check the deadline until it sweeps // 10 pages. So we give a small slack for safety. double slack = 0.001; double remaining_budget = deadline_seconds - slack - CurrentTimeTicksInSeconds(); if (remaining_budget <= 0 || !arenas_[i]->LazySweepWithDeadline(deadline_seconds)) { return false; } } return true; } void ThreadHeap::WriteBarrier(void* value) { DCHECK(thread_state_->IsIncrementalMarking()); DCHECK(value); // '-1' is used to indicate deleted values. DCHECK_NE(value, reinterpret_cast<void*>(-1)); BasePage* const page = PageFromObject(value); HeapObjectHeader* const header = page->IsLargeObjectPage() ? static_cast<LargeObjectPage*>(page)->GetHeapObjectHeader() : static_cast<NormalPage*>(page)->FindHeaderFromAddress( reinterpret_cast<Address>(const_cast<void*>(value))); if (header->IsMarked()) return; // Mark and push trace callback. header->Mark(); marking_worklist_->Push( WorklistTaskId::MainThread, {header->Payload(), GCInfoTable::Get().GCInfoFromIndex(header->GcInfoIndex())->trace_}); } ThreadHeap* ThreadHeap::main_thread_heap_ = nullptr; } // namespace blink
// Copyright (c) 2017-2019 The Particl Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <rpc/server.h> #include <rpc/client.h> #include <base58.h> #include <validation.h> #include <wallet/hdwallet.h> #include <policy/policy.h> #include <wallet/test/hdwallet_test_fixture.h> #include <boost/algorithm/string.hpp> #include <boost/test/unit_test.hpp> #include <univalue.h> using namespace std; extern UniValue createArgs(int nRequired, const char* address1 = NULL, const char* address2 = nullptr); extern UniValue CallRPC(std::string args, std::string wallet=""); void RewindHdSxChain(CHDWallet *pwallet) { // Rewind the chain to get the same key next request ExtKeyAccountMap::iterator mi = pwallet->mapExtAccounts.find(pwallet->idDefaultAccount); BOOST_REQUIRE(mi != pwallet->mapExtAccounts.end()); CExtKeyAccount *sea = mi->second; BOOST_REQUIRE(sea->nActiveStealth < sea->vExtKeys.size()); CStoredExtKey *sek = sea->vExtKeys[sea->nActiveStealth]; sek->nHGenerated -= 2; }; BOOST_FIXTURE_TEST_SUITE(rpc_hdwallet_tests, HDWalletTestingSetup) BOOST_AUTO_TEST_CASE(rpc_hdwallet) { UniValue rv; BOOST_CHECK_NO_THROW(rv = CallRPC("extkeyimportmaster xprv9s21ZrQH143K3VrEYG4rhyPddr2o53qqqpCufLP6Rb3XSta2FZsqCanRJVfpTi4UX28pRaAfVGfiGpYDczv8tzTM6Qm5TRvUA9HDStbNUbQ")); BOOST_CHECK_NO_THROW(rv = CallRPC("getnewstealthaddress")); BOOST_CHECK(StripQuotes(rv.write()) == "SPGxiYZ1Q5dhAJxJNMk56ZbxcsUBYqTCsdEPPHsJJ96Vcns889gHTqSrTZoyrCd5E9NSe9XxLivK6izETniNp1Gu1DtrhVwv3VuZ3e"); BOOST_CHECK_NO_THROW(rv = CallRPC("getnewstealthaddress onebit 1")); BOOST_CHECK(StripQuotes(rv.write()) == "2w3KaKNNRkWvgxNVymgTwxVd95hDTKRwa98eh5fUpyZfQ17XCRDsxQ3tTARJYz2pNnCekEFni7ukDwvgdbVDgbTy449DNcJYrevkyzPL"); BOOST_CHECK_NO_THROW(rv = CallRPC("getnewstealthaddress onebit 1 0b1")); std::string sResult = StripQuotes(rv.write()); BOOST_CHECK(sResult == "2w3KJzSkeDxiZDFQ5cQdMGKyEuM2zhKHX7TWCTVFobXXcWxWS5zs3aaoF3LPWfcwKd3m65CHx7j8F9CbESmi53GqmHJmnwKggRiXQoac"); CStealthAddress s1; s1.SetEncoded(sResult); BOOST_CHECK(s1.Encoded() == sResult); BOOST_CHECK(s1.prefix.number_bits == 1); BOOST_CHECK(s1.prefix.bitfield == 0b1); RewindHdSxChain(pwalletMain.get()); BOOST_CHECK_NO_THROW(rv = CallRPC("getnewstealthaddress onebit 32")); sResult = StripQuotes(rv.write()); BOOST_CHECK(sResult == "3s73gdiUKMVi4tHMTdker9YzHAS2r6F2CJvC12GfimDdTTn9CLEnEeWW8vdXXkeZouWLgxFGqzbPsnSShNRMsW3j3yL6ssEtjc3gwNSkbBfy"); CStealthAddress s2; s2.SetEncoded(sResult); BOOST_CHECK(s2.prefix.number_bits == 32); BOOST_CHECK(s2.prefix.bitfield == 4215576597); // Check the key is the same BOOST_CHECK(s2.scan_pubkey == s1.scan_pubkey); BOOST_CHECK(s2.spend_pubkey == s1.spend_pubkey); RewindHdSxChain(pwalletMain.get()); // Check the same prefix is generated BOOST_CHECK_NO_THROW(rv = CallRPC("getnewstealthaddress onebit 32")); BOOST_CHECK(StripQuotes(rv.write()) == "3s73gdiUKMVi4tHMTdker9YzHAS2r6F2CJvC12GfimDdTTn9CLEnEeWW8vdXXkeZouWLgxFGqzbPsnSShNRMsW3j3yL6ssEtjc3gwNSkbBfy"); BOOST_CHECK_NO_THROW(rv = CallRPC("getnewstealthaddress t1bin 10 0b1010101111")); sResult = StripQuotes(rv.write()); BOOST_CHECK(sResult == "9XXDiTExjRZsi1ZrvptyJr8AVpMpS5hPsi9uQ3EHgkhicC4EP5MzTg7BkLkSjbgeE69V3wRyuvuoR8WdRPCK6aTcNFKcRYJopwy7BinU3"); RewindHdSxChain(pwalletMain.get()); BOOST_CHECK_NO_THROW(rv = CallRPC("getnewstealthaddress t2hex 10 0x2AF")); BOOST_CHECK(sResult == StripQuotes(rv.write())); RewindHdSxChain(pwalletMain.get()); BOOST_CHECK_NO_THROW(rv = CallRPC("getnewstealthaddress t3dec 10 687")); BOOST_CHECK(sResult == StripQuotes(rv.write())); BOOST_CHECK_THROW(rv = CallRPC("getnewstealthaddress mustfail 33"), runtime_error); BOOST_CHECK_THROW(rv = CallRPC("getnewstealthaddress mustfail 5 wrong"), runtime_error); BOOST_CHECK_NO_THROW(rv = CallRPC("getnewextaddress")); sResult = StripQuotes(rv.write()); } BOOST_AUTO_TEST_CASE(rpc_hdwallet_timelocks) { UniValue rv; std::string sResult, sTxn, sCmd; std::vector<std::string> vAddresses; BOOST_CHECK_NO_THROW(rv = CallRPC("extkeyimportmaster xprv9s21ZrQH143K3VrEYG4rhyPddr2o53qqqpCufLP6Rb3XSta2FZsqCanRJVfpTi4UX28pRaAfVGfiGpYDczv8tzTM6Qm5TRvUA9HDStbNUbQ")); BOOST_CHECK_NO_THROW(rv = CallRPC("getnewaddress")); sResult = StripQuotes(rv.write()); BOOST_CHECK(sResult == "PZdYWHgyhuG7NHVCzEkkx3dcLKurTpvmo6"); CKeyID id; BOOST_CHECK(CBitcoinAddress(sResult).GetKeyID(id)); CScript script = CScript() << 1487406900 << OP_CHECKLOCKTIMEVERIFY << OP_DROP << OP_DUP << OP_HASH160 << ToByteVector(id) << OP_EQUALVERIFY << OP_CHECKSIG; CMutableTransaction txn; txn.nVersion = EMPOWER_TXN_VERSION; txn.SetType(TXN_COINBASE); txn.nLockTime = 0; OUTPUT_PTR<CTxOutStandard> out0 = MAKE_OUTPUT<CTxOutStandard>(); out0->nValue = 100; out0->scriptPubKey = script; txn.vpout.push_back(out0); BOOST_CHECK_NO_THROW(rv = CallRPC("getnewaddress")); sResult = StripQuotes(rv.write()); vAddresses.push_back(sResult); BOOST_CHECK(sResult == "PdsEywwkgVLJ8bF8b8Wp9gCj63KrXX3zww"); BOOST_CHECK(CBitcoinAddress(sResult).GetKeyID(id)); sTxn = "[{\"txid\":\"" + txn.GetHash().ToString() + "\"," + "\"vout\":0," + "\"scriptPubKey\":\""+HexStr(script.begin(), script.end())+"\"," + "\"amount\":100}]"; sCmd = "createrawtransaction " + sTxn + " {\""+EncodeDestination(PKHash(id))+"\":99.99}"; BOOST_REQUIRE_NO_THROW(rv = CallRPC(sCmd)); sResult = StripQuotes(rv.write()); sCmd = "signrawtransactionwithwallet " + sResult + " " + sTxn; BOOST_REQUIRE_NO_THROW(rv = CallRPC(sCmd)); BOOST_CHECK(rv["errors"][0]["error"].getValStr() == "Locktime requirement not satisfied"); sTxn = "[{\"txid\":\"" + txn.GetHash().ToString() + "\"," + "\"vout\":0," + "\"scriptPubKey\":\""+HexStr(script.begin(), script.end())+"\"," + "\"amount\":100}]"; sCmd = "createrawtransaction " + sTxn + " {\""+EncodeDestination(PKHash(id))+"\":99.99}" + " 1487500000"; BOOST_REQUIRE_NO_THROW(rv = CallRPC(sCmd)); sResult = StripQuotes(rv.write()); sCmd = "signrawtransactionwithwallet " + sResult + " " + sTxn; BOOST_REQUIRE_NO_THROW(rv = CallRPC(sCmd)); BOOST_CHECK(rv["complete"].getBool() == true); sResult = rv["hex"].getValStr(); uint32_t nSequence = 0; int32_t nTime = 2880 / (1 << CTxIn::SEQUENCE_LOCKTIME_GRANULARITY); // 48 minutes nSequence |= CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG; nSequence |= nTime; script = CScript() << nSequence << OP_CHECKSEQUENCEVERIFY << OP_DROP << OP_DUP << OP_HASH160 << ToByteVector(id) << OP_EQUALVERIFY << OP_CHECKSIG; CScript *ps = &((CTxOutStandard*)txn.vpout[0].get())->scriptPubKey; BOOST_REQUIRE(ps); *ps = script; sTxn = "[{\"txid\":\"" + txn.GetHash().ToString() + "\"," + "\"vout\":0," + "\"scriptPubKey\":\""+HexStr(script.begin(), script.end())+"\"," + "\"amount\":100}]"; sCmd = "createrawtransaction " + sTxn + " {\""+CBitcoinAddress(vAddresses[0]).ToString()+"\":99.99}"; BOOST_REQUIRE_NO_THROW(rv = CallRPC(sCmd)); sResult = StripQuotes(rv.write()); sCmd = "signrawtransactionwithwallet " + sResult + " " + sTxn; BOOST_REQUIRE_NO_THROW(rv = CallRPC(sCmd)); BOOST_CHECK(rv["errors"][0]["error"].getValStr() == "Locktime requirement not satisfied"); sTxn = "[{\"txid\":\"" + txn.GetHash().ToString() + "\"," + "\"vout\":0," + "\"scriptPubKey\":\""+HexStr(script.begin(), script.end())+"\"," + "\"amount\":100," +"\"sequence\":"+strprintf("%d", nSequence)+"}]"; sCmd = "createrawtransaction " + sTxn + " {\""+CBitcoinAddress(vAddresses[0]).ToString()+"\":99.99}"; BOOST_REQUIRE_NO_THROW(rv = CallRPC(sCmd)); sResult = StripQuotes(rv.write()); sCmd = "signrawtransactionwithwallet " + sResult + " " + sTxn; BOOST_REQUIRE_NO_THROW(rv = CallRPC(sCmd)); BOOST_CHECK(rv["complete"].getBool() == true); sResult = rv["hex"].getValStr(); BOOST_CHECK_NO_THROW(rv = CallRPC("getnewaddress")); std::string sAddr = StripQuotes(rv.write()); BOOST_CHECK(sAddr == "PYWn26pQyqRE84XSWGmUBMQs67AzCRtvdG"); // 2147483648 is > 32bit signed BOOST_CHECK_NO_THROW(rv = CallRPC("buildscript {\"recipe\":\"abslocktime\",\"time\":2147483648,\"addr\":\""+sAddr+"\"}")); BOOST_REQUIRE(rv["hex"].isStr()); std::vector<uint8_t> vScript = ParseHex(rv["hex"].get_str()); script = CScript(vScript.begin(), vScript.end()); txnouttype whichType; BOOST_CHECK(IsStandard(script, whichType)); opcodetype opcode; valtype vchPushValue; CScript::const_iterator pc = script.begin(); BOOST_REQUIRE(script.GetOp(pc, opcode, vchPushValue)); CScriptNum nTest(vchPushValue, false, 5); BOOST_CHECK(nTest == 2147483648); BOOST_CHECK_NO_THROW(rv = CallRPC("buildscript {\"recipe\":\"rellocktime\",\"time\":1447483648,\"addr\":\""+sAddr+"\"}")); BOOST_REQUIRE(rv["hex"].isStr()); vScript = ParseHex(rv["hex"].get_str()); script = CScript(vScript.begin(), vScript.end()); BOOST_CHECK(IsStandard(script, whichType)); pc = script.begin(); BOOST_REQUIRE(script.GetOp(pc, opcode, vchPushValue)); nTest = CScriptNum(vchPushValue, false, 5); BOOST_CHECK(nTest == 1447483648); } BOOST_AUTO_TEST_SUITE_END()
/* * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or * its licensors. * * For complete copyright and license terms please see the LICENSE at the root of this * distribution (the "License"). All use of this software is governed by the License, * or, if provided, by the license below or the license accompanying this file. Do not * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * */ // Original file Copyright Crytek GMBH or its affiliates, used under license. #include "StdAfx.h" #include "SequencerKeyPropertiesDlg.h" #include "SequencerSequence.h" #include "AnimationContext.h" #include <Mannequin/ui_SequencerKeyPropertiesDlg.h> ////////////////////////////////////////////////////////////////////////// void CSequencerKeyUIControls::OnInternalVariableChange(IVariable* pVar) { SelectedKeys keys; CSequencerUtils::GetSelectedKeys(m_pKeyPropertiesDlg->GetSequence(), keys); OnUIChange(pVar, keys); } ////////////////////////////////////////////////////////////////////////// void CSequencerKeyUIControls::RefreshSequencerKeys() { GetIEditor()->Notify(eNotify_OnUpdateSequencerKeys); } ////////////////////////////////////////////////////////////////////////// CSequencerKeyPropertiesDlg::CSequencerKeyPropertiesDlg(QWidget* parent, bool overrideConstruct) : QWidget(parent) , m_pLastTrackSelected(NULL) , m_wndProps(new ReflectedPropertyControl(this)) , m_wndTrackProps(new CSequencerTrackPropsDlg(this)) { m_wndProps->Setup(false, 175); QBoxLayout* layout = new QVBoxLayout(this); layout->setMargin(0); layout->addWidget(m_wndTrackProps); m_wndProps->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Expanding); layout->addWidget(m_wndProps); layout->addStretch(1); m_pVarBlock = new CVarBlock; if (!overrideConstruct) { CreateAllVars(); } } CSequencerKeyPropertiesDlg::~CSequencerKeyPropertiesDlg() { } ////////////////////////////////////////////////////////////////////////// //BOOL CSequencerKeyPropertiesDlg::PreTranslateMessage( MSG* pMsg ) //{ //if (pMsg->message == WM_KEYDOWN) //{ // // In case of arrow keys, pass the message to keys window so that it can handle // // a key selection change by arrow keys. // int nVirtKey = (int) pMsg->wParam; // if (nVirtKey == VK_UP || nVirtKey == VK_DOWN || nVirtKey == VK_RIGHT || nVirtKey == VK_LEFT) // { // if (m_keysCtrl) // m_keysCtrl->SendMessage(WM_KEYDOWN, pMsg->wParam, pMsg->lParam); // } //} //return QWidget::PreTranslateMessage(pMsg); //return false; //} ////////////////////////////////////////////////////////////////////////// void CSequencerKeyPropertiesDlg::OnVarChange(IVariable* pVar) { } ////////////////////////////////////////////////////////////////////////// void CSequencerKeyPropertiesDlg::CreateAllVars() { for (int i = 0; i < (int)m_keyControls.size(); i++) { m_keyControls[i]->SetKeyPropertiesDlg(this); m_keyControls[i]->CreateVars(); } } ////////////////////////////////////////////////////////////////////////// void CSequencerKeyPropertiesDlg::PopulateVariables() { //SetVarBlock( m_pVarBlock,functor(*this,&CSequencerKeyPropertiesDlg::OnVarChange) ); // Must first clear any selection in properties window. m_wndProps->ClearSelection(); m_wndProps->RemoveAllItems(); m_wndProps->AddVarBlock(m_pVarBlock); m_wndProps->SetUpdateCallback(functor(*this, &CSequencerKeyPropertiesDlg::OnVarChange)); //m_wndProps->ExpandAll(); ReloadValues(); } ////////////////////////////////////////////////////////////////////////// void CSequencerKeyPropertiesDlg::PopulateVariables(ReflectedPropertyControl& propCtrl) { propCtrl.ClearSelection(); propCtrl.RemoveAllItems(); propCtrl.AddVarBlock(m_pVarBlock); propCtrl.ReloadValues(); } ////////////////////////////////////////////////////////////////////////// void CSequencerKeyPropertiesDlg::OnKeySelectionChange() { CSequencerUtils::SelectedKeys selectedKeys; CSequencerUtils::GetSelectedKeys(GetSequence(), selectedKeys); if (m_wndTrackProps) { m_wndTrackProps->OnKeySelectionChange(selectedKeys); } bool bSelectChangedInSameTrack = m_pLastTrackSelected && selectedKeys.keys.size() == 1 && selectedKeys.keys[0].pTrack == m_pLastTrackSelected; if (selectedKeys.keys.size() == 1) { m_pLastTrackSelected = selectedKeys.keys[0].pTrack; } else { m_pLastTrackSelected = NULL; } if (bSelectChangedInSameTrack == false) { m_pVarBlock->DeleteAllVariables(); } bool bAssigned = false; if (selectedKeys.keys.size() > 0) { for (int i = 0; i < (int)m_keyControls.size(); i++) { const ESequencerParamType valueType = selectedKeys.keys[0].pTrack->GetParameterType(); if (m_keyControls[i]->SupportTrackType(valueType)) { if (bSelectChangedInSameTrack == false) { AddVars(m_keyControls[i]); } if (m_keyControls[i]->OnKeySelectionChange(selectedKeys)) { bAssigned = true; } break; } } m_wndProps->setEnabled(true); } else { m_wndProps->setEnabled(false); } if (bSelectChangedInSameTrack) { m_wndProps->ClearSelection(); ReloadValues(); } else { PopulateVariables(); } if (selectedKeys.keys.size() > 1 || !bAssigned) { m_wndProps->SetDisplayOnlyModified(true); } else { m_wndProps->SetDisplayOnlyModified(false); } } ////////////////////////////////////////////////////////////////////////// void CSequencerKeyPropertiesDlg::AddVars(CSequencerKeyUIControls* pUI) { CVarBlock* pVB = pUI->GetVarBlock(); for (int i = 0, num = pVB->GetNumVariables(); i < num; i++) { IVariable* pVar = pVB->GetVariable(i); m_pVarBlock->AddVariable(pVar); } } ////////////////////////////////////////////////////////////////////////// void CSequencerKeyPropertiesDlg::ReloadValues() { if (m_wndProps) { m_wndProps->ReloadValues(); } } void CSequencerKeyPropertiesDlg::SetSequence(CSequencerSequence* pSequence) { m_pSequence = pSequence; m_wndTrackProps->SetSequence(pSequence); } void CSequencerKeyPropertiesDlg::SetVarValue(const char* varName, const char* varValue) { if (varName == NULL || varName[ 0 ] == 0) { return; } if (varValue == NULL || varValue[ 0 ] == 0) { return; } if (!m_pVarBlock) { return; } IVariable* pVar = NULL; string varNameList = varName; int start = 0; string token = varNameList.Tokenize(".", start); CRY_ASSERT(!token.empty()); while (!token.empty()) { if (pVar == NULL) { const bool recursiveSearch = true; pVar = m_pVarBlock->FindVariable(token.c_str(), recursiveSearch); } else { const bool recursiveSearch = false; pVar = pVar->FindVariable(token.c_str(), recursiveSearch); } if (pVar == NULL) { return; } token = varNameList.Tokenize(".", start); } pVar->Set(varValue); } ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// CSequencerTrackPropsDlg::CSequencerTrackPropsDlg(QWidget* parent) : QWidget(parent) , m_ui(new Ui::SequencerTrackPropsDlg) , m_inOnKeySelectionChange(false) { m_ui->setupUi(this); m_track = 0; m_key = -1; connect(m_ui->m_keySpinBtn, SIGNAL(valueChanged(int)), this, SLOT(OnDeltaposPrevnext()), Qt::QueuedConnection); connect(m_ui->m_time, SIGNAL(valueChanged(double)), this, SLOT(OnUpdateTime())); } CSequencerTrackPropsDlg::~CSequencerTrackPropsDlg() { } ////////////////////////////////////////////////////////////////////////// void CSequencerTrackPropsDlg::SetSequence(CSequencerSequence* pSequence) { if (pSequence) { Range range = pSequence->GetTimeRange(); m_ui->m_time->setRange(range.start, range.end); } } ////////////////////////////////////////////////////////////////////////// bool CSequencerTrackPropsDlg::OnKeySelectionChange(CSequencerUtils::SelectedKeys& selectedKeys) { if (m_inOnKeySelectionChange) { return false; } m_inOnKeySelectionChange = true; m_track = 0; m_key = 0; if (selectedKeys.keys.size() == 1) { m_track = selectedKeys.keys[0].pTrack; m_key = selectedKeys.keys[0].nKey; } if (m_track != NULL) { m_ui->m_time->setValue(m_track->GetKeyTime(m_key)); m_ui->m_keySpinBtn->setRange(1, m_track->GetNumKeys()); m_ui->m_keySpinBtn->setValue(m_key + 1); m_ui->m_keySpinBtn->setEnabled(true); m_ui->m_time->setEnabled(true); } else { m_ui->m_keySpinBtn->setEnabled(false); m_ui->m_time->setEnabled(false); } m_inOnKeySelectionChange = false; return true; } void CSequencerTrackPropsDlg::OnDeltaposPrevnext() { if (!m_track) { return; } int nkey = m_ui->m_keySpinBtn->value() - 1; if (nkey < 0) { nkey = m_track->GetNumKeys() - 1; } if (nkey > m_track->GetNumKeys() - 1) { nkey = 0; } SetCurrKey(nkey); } void CSequencerTrackPropsDlg::OnUpdateTime() { if (!m_track) { return; } if (m_key < 0 || m_key >= m_track->GetNumKeys()) { return; } float time = m_ui->m_time->value(); m_track->SetKeyTime(m_key, time); m_track->SortKeys(); int k = m_track->FindKey(time); if (k != m_key) { SetCurrKey(k); } } void CSequencerTrackPropsDlg::SetCurrKey(int nkey) { if (m_key >= 0 && m_key < m_track->GetNumKeys()) { m_track->SelectKey(m_key, false); } if (nkey >= 0 && nkey < m_track->GetNumKeys()) { m_track->SelectKey(nkey, true); } GetIEditor()->Notify(eNotify_OnUpdateSequencerKeySelection); } #include <Mannequin/SequencerKeyPropertiesDlg.moc>
// stdafx.cpp : source file that includes just the standard includes // GCodeInterpreter.pch will be the pre-compiled header // stdafx.obj will contain the pre-compiled type information #include "StdAfx.h" // TODO: reference any additional headers you need in STDAFX.H // and not in this file
#include <fstream> #include <math.h> #include <limits.h> #include <string.h> #include <time.h> #include <unistd.h> #include <stdio.h> #include <ctype.h> #include <sys/time.h> #include <sys/resource.h> #include <iostream> #include <sstream> #include <stdlib.h> using namespace std; char sysfile[512]; char outfile[512]; int nroao; int nroa; long long int nrofint; extern void get_sys_size(char* sysfile, int* nroao, int* nroa, long long int* nrofint); extern void read_sys(char* sysfile, double* coord, double* charges, double* mass, double* Hmat, double* Tmat, double* Smat, double* Dx, double* Dy, double *Dz, long long int* sortcount, double* intval, unsigned short* intnums); int main(int argc, char* argv[]){ if(argc != 3){ cerr << "Usage: ./readsys sysfile outfile\n"; exit(1); } sprintf(sysfile, "%s", argv[1]); // writes the name of the sysfile generated by mk_in sprintf(outfile, "%s", argv[2]); // writes the name of the output file get_sys_size(sysfile, &nroao, &nroa, &nrofint); // reads the #AOs, #atoms, and the #integrals from the sysfile ofstream outf; // defines an output filestream outf.open(outfile); // opens the output file outf << "Read Sysfile: " << sysfile << "\n"; // writes the name of the sysfile, outf << "Number of atomic orbitals: " << nroao << "\n"; // the number of AOs, outf << "Number of atoms: " << nroa << "\n"; // the number of atoms, outf << "Number of integrals: " << nrofint << "\n"; // and the number of integrals outf.flush(); // flushes the output buffer double* coord = new double[3*nroa]; // coordinates of the atoms double* charges = new double[nroa]; // charges of the atom cores double* mass = new double[nroa]; // masses of the atoms double* Hmat = new double[nroao*nroao]; // Hamiltonian matrix double* Tmat = new double[nroao*nroao]; // Kinetic energy matrix double* Smat = new double[nroao*nroao]; // Overlap matrix double* Dx = new double[nroao*nroao]; // Dipole moment along x double* Dy = new double[nroao*nroao]; // Dipole moment along y double* Dz = new double[nroao*nroao]; // Dipole moment along z long long int sortcount[4]; double* intval = new double[nrofint]; unsigned short* intnums = new unsigned short[nrofint*4]; read_sys(sysfile, coord, charges, mass, Hmat, Tmat, Smat, Dx, Dy, Dz, sortcount, intval, intnums); outf << "------------------------------------------------------------------\n"; outf << "Output of coordinates, charges and masses (index, x, y, z, q, m): \n"; for(int i = 0; i < nroa; i++){ outf << i << " " << coord[i*3+0] << " " << coord[i*3+1] << " " << coord[i*3+2] << " " << charges[i] << " " << mass[i] << "\n"; outf.flush(); } outf << "------------------------------------------------------------------------------\n"; outf << "Two electron integral indices and values (index, intnums[i*4+0...3], intval): \n"; for(int i = 0; i < nrofint; i++){ outf << i << " " << intnums[i*4+0] << " " << intnums[i*4+1] << " " << intnums[i*4+2] << " " << intnums[i*4+3] << " " << intval[i] << "\n"; outf.flush(); } }
//$Id$ //------------------------------------------------------------------------------ // ParameterFactory //------------------------------------------------------------------------------ // GMAT: General Mission Analysis Tool // // Copyright (c) 2002 - 2015 United States Government as represented by the // Administrator of the National Aeronautics and Space Administration. // All Other 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. // // Developed jointly by NASA/GSFC and Thinking Systems, Inc. under contract // number S-67573-G // // Developed further jointly by NASA/GSFC, Thinking Systems, Inc., and // Schafer Corp., under AFRL NOVA Contract #FA945104D03990003 // // Author: Darrel Conway // Created: 2003/10/28 // Modified: Dunn Idle (added MRPs) // Date: 2010/08/24 // /** * Implementation code for the ParameterFactory class, responsible * for creating Parameter objects. */ //------------------------------------------------------------------------------ #include "ParameterFactory.hpp" #include "TimeParameters.hpp" #include "CartesianParameters.hpp" #include "KeplerianParameters.hpp" #include "SphericalParameters.hpp" #include "EquinoctialParameters.hpp" #include "ModEquinoctialParameters.hpp" #include "AlternateEquinoctialParameters.hpp" #include "DelaunayParameters.hpp" #include "PlanetodeticParameters.hpp" #include "IncomingAsymptoteParameters.hpp" #include "OutgoingAsymptoteParameters.hpp" #include "BrouwerMeanShortParameters.hpp" #include "BrouwerMeanLongParameters.hpp" #include "OrbitalParameters.hpp" #include "AngularParameters.hpp" #include "PlanetParameters.hpp" #include "Variable.hpp" #include "StringVar.hpp" #include "Array.hpp" #include "BplaneParameters.hpp" #include "BurnParameters.hpp" #include "AttitudeParameters.hpp" #include "BallisticMassParameters.hpp" #include "OrbitStmParameters.hpp" #include "HardwareParameters.hpp" #include "MessageInterface.hpp" //--------------------------------- // public methods //--------------------------------- //------------------------------------------------------------------------------ // CreateParameter(const std::string &ofType, const std::string &withName) //------------------------------------------------------------------------------ /** * This method creates and returns an object of the requested Parameter class * * @param <ofType> the Parameter object to create and return. * @param <withName> the name to give the newly-created Parameter object. */ //------------------------------------------------------------------------------ Parameter* ParameterFactory::CreateParameter(const std::string &ofType, const std::string &withName) { #ifdef DEBUG_CREATE_PARAM MessageInterface::ShowMessage ("ParameterFactory::CreateParameter() entered, type = '%s', name = '%s'\n", ofType.c_str(), withName.c_str()); #endif // User defined parameters if (ofType == "Variable") return new Variable(withName); if (ofType == "String") return new StringVar(withName); if (ofType == "Array") return new Array(withName); // Time parameters if (ofType == "ElapsedDays") return new ElapsedDays(withName); if (ofType == "ElapsedSecs") return new ElapsedSecs(withName); if (ofType == "CurrA1MJD") // deprecated return new CurrA1MJD(withName); if (ofType == "A1ModJulian") return new A1ModJulian(withName); if (ofType == "A1Gregorian") return new A1Gregorian(withName); if (ofType == "TAIModJulian") return new TAIModJulian(withName); if (ofType == "TAIGregorian") return new TAIGregorian(withName); if (ofType == "TTModJulian") return new TTModJulian(withName); if (ofType == "TTGregorian") return new TTGregorian(withName); if (ofType == "TDBModJulian") return new TDBModJulian(withName); if (ofType == "TDBGregorian") return new TDBGregorian(withName); if (ofType == "UTCModJulian") return new UTCModJulian(withName); if (ofType == "UTCGregorian") return new UTCGregorian(withName); // Cartesian parameters if (ofType == "X") return new CartX(withName); if (ofType == "Y") return new CartY(withName); if (ofType == "Z") return new CartZ(withName); if (ofType == "VX") return new CartVx(withName); if (ofType == "VY") return new CartVy(withName); if (ofType == "VZ") return new CartVz(withName); if (ofType == "Cartesian") return new CartState(withName); // Keplerian parameters if (ofType == "SMA") return new KepSMA(withName); if (ofType == "ECC") return new KepEcc(withName); if (ofType == "INC") return new KepInc(withName); if (ofType == "RAAN") return new KepRAAN(withName); if (ofType == "RADN") return new KepRADN(withName); if (ofType == "AOP") return new KepAOP(withName); if (ofType == "TA") return new KepTA(withName); if (ofType == "MA") return new KepMA(withName); if (ofType == "EA") return new KepEA(withName); if (ofType == "HA") return new KepHA(withName); if (ofType == "MM") return new KepMM(withName); if (ofType == "Keplerian") return new KepElem(withName); if (ofType == "ModKeplerian") return new ModKepElem(withName); // Spherical parameters if (ofType == "RMAG") return new SphRMag(withName); if (ofType == "RA") return new SphRA(withName); if (ofType == "DEC") return new SphDec(withName); if (ofType == "VMAG") return new SphVMag(withName); if (ofType == "RAV") return new SphRAV(withName); if (ofType == "DECV") return new SphDecV(withName); if (ofType == "AZI") return new SphAzi(withName); if (ofType == "FPA") return new SphFPA(withName); if (ofType == "SphericalRADEC") return new SphRaDecElem(withName); if (ofType == "SphericalAZFPA") return new SphAzFpaElem(withName); if (ofType == "Altitude") return new Altitude(withName); // Equinoctial parameters if (ofType == "EquinoctialH") return new EquinEy(withName); if (ofType == "EquinoctialK") return new EquinEx(withName); if (ofType == "EquinoctialP") return new EquinNy(withName); if (ofType == "EquinoctialQ") return new EquinNx(withName); if (ofType == "MLONG") return new EquinMlong(withName); if (ofType == "Equinoctial") return new EquinState(withName); // ModifiedEquinoctial parameters; Modified by M.H. // Changed SemiLatusRectum to SemilatusRectum (Fix for GMT-4173) // It will create SemilatusRectum Parameter due to issues (2014.01.28) //if (ofType == "SemiLatusRectum") // return new ModEquinP(withName); if (ofType == "ModEquinoctialF") return new ModEquinF(withName); if (ofType == "ModEquinoctialG") return new ModEquinG(withName); if (ofType == "ModEquinoctialH") return new ModEquinH(withName); if (ofType == "ModEquinoctialK") return new ModEquinK(withName); if (ofType == "TLONG") return new ModEquinTLONG(withName); if (ofType == "ModifiedEquinoctial") return new ModEquinState(withName); // Alternate Equinoctial parameters by HYKim if (ofType == "AltEquinoctialP") return new AltEquinP(withName); if (ofType == "AltEquinoctialQ") return new AltEquinQ(withName); if (ofType == "AltEquinoctial") return new AltEquinState(withName); // Delaunay parameters; Modified by M.H. if (ofType == "Delaunayl") return new Delal(withName); if (ofType == "Delaunayg") return new Delag(withName); if (ofType == "Delaunayh") return new Delah(withName); if (ofType == "DelaunayL") return new DelaL(withName); if (ofType == "DelaunayG") return new DelaG(withName); if (ofType == "DelaunayH") return new DelaH(withName); if (ofType == "Delaunay") return new DelaState(withName); // Planetodetic parameters; Modified by M.H. if (ofType == "PlanetodeticRMAG") return new PldRMAG(withName); if (ofType == "PlanetodeticLON") return new PldLON(withName); if (ofType == "PlanetodeticLAT") return new PldLAT(withName); if (ofType == "PlanetodeticVMAG") return new PldVMAG(withName); if (ofType == "PlanetodeticAZI") return new PldAZI(withName); if (ofType == "PlanetodeticHFPA") return new PldHFPA(withName); if (ofType == "Planetodetic") return new PldState(withName); // IncomingAsymptote parameters; Modified by YK // Added HyperbolicRadPer (LOJ: 2014.04.28) //if (ofType == "HyperbolicRadPer") // return new HyperbolicRadPer(withName); // Added IncomingRadPer and IncomingC3Energy (LOJ: 2014.05.07) if (ofType == "IncomingRadPer") return new IncAsymRadPer(withName); if (ofType == "IncomingC3Energy") return new IncAsymC3Energy(withName); if (ofType == "IncomingRHA") return new IncAsymRHA(withName); if (ofType == "IncomingDHA") return new IncAsymDHA(withName); if (ofType == "IncomingBVAZI") return new IncAsymBVAZI(withName); // OutgoingAsymptote parameters; Modified by YK // Added OutgoingRadPer and OutgoingC3Energy (LOJ: 2014.05.07) if (ofType == "OutgoingRadPer") return new OutAsymRadPer(withName); if (ofType == "OutgoingC3Energy") return new OutAsymC3Energy(withName); if (ofType == "OutgoingRHA") return new OutAsymRHA(withName); if (ofType == "OutgoingDHA") return new OutAsymDHA(withName); if (ofType == "OutgoingBVAZI") return new OutAsymBVAZI(withName); // Brouwer Mean Short parameters; Modified by YK // Changed Parameter names (see GMT-4228 LOJ: 2014.01.09) if (ofType == "BrouwerShortSMA") return new BLshortSMAP(withName); if (ofType == "BrouwerShortECC") return new BLshortECCP(withName); if (ofType == "BrouwerShortINC") return new BLshortINCP(withName); if (ofType == "BrouwerShortRAAN") return new BLshortRAANP(withName); if (ofType == "BrouwerShortAOP") return new BLshortAOPP(withName); if (ofType == "BrouwerShortMA") return new BLshortMAP(withName); // BrouwerMeanLong parameters; Modified by YK // Changed Parameter names (see GMT-4228 LOJ: 2014.01.09) if (ofType == "BrouwerLongSMA") return new BLlongSMADP(withName); if (ofType == "BrouwerLongECC") return new BLlongECCDP(withName); if (ofType == "BrouwerLongINC") return new BLlongINCDP(withName); if (ofType == "BrouwerLongRAAN") return new BLlongRAANDP(withName); if (ofType == "BrouwerLongAOP") return new BLlongAOPDP(withName); if (ofType == "BrouwerLongMA") return new BLlongMADP(withName); // Orbital parameters if (ofType == "VelApoapsis") return new VelApoapsis(withName); if (ofType == "VelPeriapsis") return new VelPeriapsis(withName); if (ofType == "Apoapsis") return new Apoapsis(withName); if (ofType == "Periapsis") return new Periapsis(withName); if (ofType == "OrbitPeriod") return new OrbitPeriod(withName); if (ofType == "RadApo") return new ModKepRadApo(withName); if (ofType == "RadPer") return new ModKepRadPer(withName); if (ofType == "C3Energy") return new C3Energy(withName); if (ofType == "Energy") return new Energy(withName); // Angular parameters // Changed to create ModEquinP() since it is settable Parameter // Fix for GMT-4173 (LOJ: 2014.01.22) // Changed back to create SemilatusRectum due to issues (LOJ: 2014.01.28) if (ofType == "SemilatusRectum") return new SemilatusRectum(withName); if (ofType == "HMAG") return new AngularMomentumMag(withName); if (ofType == "HX") return new AngularMomentumX(withName); if (ofType == "HY") return new AngularMomentumY(withName); if (ofType == "HZ") return new AngularMomentumZ(withName); if (ofType == "DLA") return new DLA(withName); if (ofType == "RLA") return new RLA(withName); // Planet parameters if (ofType == "MHA") return new MHA(withName); if (ofType == "Longitude") return new Longitude(withName); if (ofType == "Latitude") return new Latitude(withName); if (ofType == "LST") return new LST(withName); if (ofType == "BetaAngle") return new BetaAngle(withName); // B-Plane parameters if (ofType == "BdotT") return new BdotT(withName); if (ofType == "BdotR") return new BdotR(withName); if (ofType == "BVectorMag") return new BVectorMag(withName); if (ofType == "BVectorAngle") return new BVectorAngle(withName); // ImpulsiveBurn parameters if (ofType == "Element1" || ofType == "Element2" || ofType == "Element3") return new ImpBurnElements(ofType, withName); if (ofType == "V" || ofType == "N" || ofType == "B") return new ImpBurnElements(ofType, withName); // Attitude parameters if (ofType == "DCM11" || ofType == "DirectionCosineMatrix11") return new DCM11(withName); if (ofType == "DCM12" || ofType == "DirectionCosineMatrix12") return new DCM12(withName); if (ofType == "DCM13" || ofType == "DirectionCosineMatrix13") return new DCM13(withName); if (ofType == "DCM21" || ofType == "DirectionCosineMatrix21") return new DCM21(withName); if (ofType == "DCM22" || ofType == "DirectionCosineMatrix22") return new DCM22(withName); if (ofType == "DCM23" || ofType == "DirectionCosineMatrix23") return new DCM23(withName); if (ofType == "DCM31" || ofType == "DirectionCosineMatrix31") return new DCM31(withName); if (ofType == "DCM32" || ofType == "DirectionCosineMatrix32") return new DCM32(withName); if (ofType == "DCM33" || ofType == "DirectionCosineMatrix33") return new DCM33(withName); if (ofType == "EulerAngle1") return new EulerAngle1(withName); if (ofType == "EulerAngle2") return new EulerAngle2(withName); if (ofType == "EulerAngle3") return new EulerAngle3(withName); if (ofType == "MRP1") // Dunn Added return new MRP1(withName); if (ofType == "MRP2") // Dunn Added return new MRP2(withName); if (ofType == "MRP3") // Dunn Added return new MRP3(withName); if (ofType == "Q1" || ofType == "q1") return new Quat1(withName); if (ofType == "Q2" || ofType == "q2") return new Quat2(withName); if (ofType == "Q3" || ofType == "q3") return new Quat3(withName); if (ofType == "Q4" || ofType == "q4") return new Quat4(withName); if (ofType == "Quaternion") return new Quaternion(withName); if (ofType == "AngularVelocityX") return new AngularVelocityX(withName); if (ofType == "AngularVelocityY") return new AngularVelocityY(withName); if (ofType == "AngularVelocityZ") return new AngularVelocityZ(withName); if (ofType == "EulerAngleRate1") return new EulerAngleRate1(withName); if (ofType == "EulerAngleRate2") return new EulerAngleRate2(withName); if (ofType == "EulerAngleRate3") return new EulerAngleRate3(withName); // Ballistic/Mass parameters if (ofType == "DryMass") return new DryMass(withName); if (ofType == "Cd") return new DragCoeff(withName); if (ofType == "Cr") return new ReflectCoeff(withName); if (ofType == "DragArea") return new DragArea(withName); if (ofType == "SRPArea") return new SRPArea(withName); if (ofType == "TotalMass") return new TotalMass(withName); // orbit STM parameters if (ofType == "OrbitSTM") return new OrbitStm(withName); if (ofType == "OrbitSTMA") return new OrbitStmA(withName); if (ofType == "OrbitSTMB") return new OrbitStmB(withName); if (ofType == "OrbitSTMC") return new OrbitStmC(withName); if (ofType == "OrbitSTMD") return new OrbitStmD(withName); // FuelTank parameters if (ofType == "FuelMass") return new FuelMass(withName); if (ofType == "Pressure") return new Pressure(withName); if (ofType == "Temperature") return new Temperature(withName); if (ofType == "RefTemperature") return new RefTemperature(withName); if (ofType == "Volume") return new Volume(withName); if (ofType == "FuelDensity") return new FuelDensity(withName); // Thruster parameters if (ofType == "DutyCycle") return new DutyCycle(withName); if (ofType == "ThrustScaleFactor") return new ThrustScaleFactor(withName); if (ofType == "GravitationalAccel") return new GravitationalAccel(withName); if (ofType == "C1" || ofType == "C2" || ofType == "C3" || ofType == "C4" || ofType == "C5" || ofType == "C6" || ofType == "C7" || ofType == "C8" || ofType == "C9" || ofType == "C10" || ofType == "C11" || ofType == "C12" || ofType == "C13" || ofType == "C14" || ofType == "C15" || ofType == "C16") return new ThrustCoefficients(ofType, withName); if (ofType == "K1" || ofType == "K2" || ofType == "K3" || ofType == "K4" || ofType == "K5" || ofType == "K6" || ofType == "K7" || ofType == "K8" || ofType == "K9" || ofType == "K10" || ofType == "K11" || ofType == "K12" || ofType == "K13" || ofType == "K14" || ofType == "K15" || ofType == "K16") return new ImpulseCoefficients(ofType, withName); if (ofType == "ThrustDirection1" || ofType == "ThrustDirection2" || ofType == "ThrustDirection3") return new ThrustDirections(ofType, withName); // PowerSystem parameters if (ofType == "TotalPowerAvailable") return new TotalPowerAvailable(withName); if (ofType == "RequiredBusPower") return new RequiredBusPower(withName); if (ofType == "ThrustPowerAvailable") return new ThrustPowerAvailable(withName); // add others here MessageInterface::ShowMessage ("**** ERROR **** Cannot create a parameter with unknown type \"%s\"\n", ofType.c_str()); return NULL; } //------------------------------------------------------------------------------ // ParameterFactory() //------------------------------------------------------------------------------ /** * This method creates an object of the class ParameterFactory * (default constructor). * * */ //------------------------------------------------------------------------------ ParameterFactory::ParameterFactory() : Factory(Gmat::PARAMETER) { if (creatables.empty()) { // User defined parameters creatables.push_back("Variable"); creatables.push_back("String"); creatables.push_back("Array"); // Time parameters creatables.push_back("ElapsedDays"); creatables.push_back("ElapsedSecs"); creatables.push_back("CurrA1MJD"); // deprecated creatables.push_back("A1ModJulian"); creatables.push_back("A1Gregorian"); creatables.push_back("TAIModJulian"); creatables.push_back("TAIGregorian"); creatables.push_back("TTModJulian"); creatables.push_back("TTGregorian"); creatables.push_back("TDBModJulian"); creatables.push_back("TDBGregorian"); creatables.push_back("UTCModJulian"); creatables.push_back("UTCGregorian"); // Cartesian parameters creatables.push_back("X"); creatables.push_back("Y"); creatables.push_back("Z"); creatables.push_back("VX"); creatables.push_back("VY"); creatables.push_back("VZ"); creatables.push_back("Cartesian"); // Keplerian parameters creatables.push_back("SMA"); creatables.push_back("ECC"); creatables.push_back("INC"); creatables.push_back("RAAN"); creatables.push_back("RADN"); creatables.push_back("AOP"); creatables.push_back("TA"); creatables.push_back("MA"); creatables.push_back("EA"); creatables.push_back("HA"); creatables.push_back("MM"); creatables.push_back("Keplerian"); creatables.push_back("RadApo"); creatables.push_back("RadPer"); creatables.push_back("ModKeplerian"); // Spherical parameters creatables.push_back("RMAG"); creatables.push_back("RA"); creatables.push_back("DEC"); creatables.push_back("VMAG"); creatables.push_back("RAV"); creatables.push_back("DECV"); creatables.push_back("AZI"); creatables.push_back("FPA"); creatables.push_back("SphericalRADEC"); creatables.push_back("SphericalAZFPA"); creatables.push_back("Altitude"); // Equinoctial parameters creatables.push_back("EquinoctialH"); creatables.push_back("EquinoctialK"); creatables.push_back("EquinoctialP"); creatables.push_back("EquinoctialQ"); creatables.push_back("MLONG"); creatables.push_back("Equinoctial"); // ModifedEquinoctial parameters ; Modified by M.H. // Changed SemiLatusRectum to SemilatusRectum (Fix for GMT-4173 (LOJ: 2014.01.22)) creatables.push_back("SemilatusRectum"); creatables.push_back("ModEquinoctialF"); creatables.push_back("ModEquinoctialG"); creatables.push_back("ModEquinoctialH"); creatables.push_back("ModEquinoctialK"); creatables.push_back("TLONG"); creatables.push_back("ModEquinoctial"); // Alternate Equinoctial parameters by HYKim creatables.push_back("AltEquinoctialP"); creatables.push_back("AltEquinoctialQ"); // Delaunay parameters ; Modified by M.H. creatables.push_back("Delaunayl"); creatables.push_back("Delaunayg"); creatables.push_back("Delaunayh"); creatables.push_back("DelaunayL"); creatables.push_back("DelaunayG"); creatables.push_back("DelaunayH"); creatables.push_back("Delaunay"); // Planetodetic parameters ; Modified by M.H. creatables.push_back("PlanetodeticRMAG"); creatables.push_back("PlanetodeticLON"); creatables.push_back("PlanetodeticLAT"); creatables.push_back("PlanetodeticVMAG"); creatables.push_back("PlanetodeticAZI"); creatables.push_back("PlanetodeticHFPA"); creatables.push_back("Planetodetic"); // IncomingAsymptote parameters ; Modified by YK //creatables.push_back("HyperbolicRadPer"); creatables.push_back("IncomingRadPer"); creatables.push_back("IncomingC3Energy"); creatables.push_back("IncomingRHA"); creatables.push_back("IncomingDHA"); creatables.push_back("IncomingBVAZI"); creatables.push_back("IncomingAsymptote"); // OutgoingAsymptote parameters ; Modified by YK creatables.push_back("OutgoingRadPer"); creatables.push_back("OutgoingC3Energy"); creatables.push_back("OutgoingRHA"); creatables.push_back("OutgoingDHA"); creatables.push_back("OutgoingBVAZI"); creatables.push_back("OutgoingAsymptote"); // BrourMeanShort parameters ; Modified by YK // Changed Parameter names (see GMT-4228 LOJ: 2014.01.09) creatables.push_back("BrouwerShortSMA"); creatables.push_back("BrouwerShortECC"); creatables.push_back("BrouwerShortINC"); creatables.push_back("BrouwerShortRAAN"); creatables.push_back("BrouwerShortAOP"); creatables.push_back("BrouwerShortMA"); creatables.push_back("BrouwerMeanShort"); // BrouwerMeanLong parameters ; Modified by YK // Changed Parameter names (see GMT-4228 LOJ: 2014.01.09) creatables.push_back("BrouwerLongSMA"); creatables.push_back("BrouwerLongECC"); creatables.push_back("BrouwerLongINC"); creatables.push_back("BrouwerLongRAAN"); creatables.push_back("BrouwerLongAOP"); creatables.push_back("BrouwerLongMA"); creatables.push_back("BrouwerMeanLong"); // Orbital parameters creatables.push_back("VelApoapsis"); creatables.push_back("VelPeriapsis"); creatables.push_back("Apoapsis"); creatables.push_back("Periapsis"); creatables.push_back("OrbitPeriod"); creatables.push_back("C3Energy"); creatables.push_back("Energy"); // Angular parameters // Changed SemiLatusRectum to SemilatusRectum above // and commented out this (LOJ: 2013.01.22) //creatables.push_back("SemilatusRectum"); creatables.push_back("HMAG"); creatables.push_back("HX"); creatables.push_back("HY"); creatables.push_back("HZ"); creatables.push_back("DLA"); creatables.push_back("RLA"); // Environmental parameters #ifdef __ENABLE_ATMOS_DENSITY__ creatables.push_back("AtmosDensity"); #endif // Planet parameters creatables.push_back("MHA"); creatables.push_back("Longitude"); creatables.push_back("Latitude"); creatables.push_back("LST"); creatables.push_back("BetaAngle"); // B-Plane parameters creatables.push_back("BdotT"); creatables.push_back("BdotR"); creatables.push_back("BVectorMag"); creatables.push_back("BVectorAngle"); // Burn parameters creatables.push_back("Element1"); creatables.push_back("Element2"); creatables.push_back("Element3"); creatables.push_back("V"); creatables.push_back("N"); creatables.push_back("B"); // Attitude parameters creatables.push_back("DCM11"); creatables.push_back("DCM12"); creatables.push_back("DCM13"); creatables.push_back("DCM21"); creatables.push_back("DCM22"); creatables.push_back("DCM23"); creatables.push_back("DCM31"); creatables.push_back("DCM32"); creatables.push_back("DCM33"); creatables.push_back("EulerAngle1"); creatables.push_back("EulerAngle2"); creatables.push_back("EulerAngle3"); creatables.push_back("MRP1"); // Dunn Added creatables.push_back("MRP2"); // Dunn Added creatables.push_back("MRP3"); // Dunn Added creatables.push_back("Q1"); creatables.push_back("Q2"); creatables.push_back("Q3"); creatables.push_back("Q4"); creatables.push_back("Quaternion"); creatables.push_back("AngularVelocityX"); creatables.push_back("AngularVelocityY"); creatables.push_back("AngularVelocityZ"); creatables.push_back("EulerAngleRate1"); creatables.push_back("EulerAngleRate2"); creatables.push_back("EulerAngleRate3"); // Ballistic/Mass parameters creatables.push_back("DryMass"); creatables.push_back("Cd"); creatables.push_back("Cr"); creatables.push_back("DragArea"); creatables.push_back("SRPArea"); creatables.push_back("TotalMass"); // Orbit STM parameters creatables.push_back("OrbitSTM"); creatables.push_back("OrbitSTMA"); creatables.push_back("OrbitSTMB"); creatables.push_back("OrbitSTMC"); creatables.push_back("OrbitSTMD"); // FuelTank parameters creatables.push_back("FuelMass"); creatables.push_back("Pressure"); creatables.push_back("Temperature"); creatables.push_back("RefTemperature"); creatables.push_back("Volume"); creatables.push_back("FuelDensity"); // Thruster parameters creatables.push_back("DutyCycle"); creatables.push_back("ThrustScaleFactor"); creatables.push_back("GravitationalAccel"); creatables.push_back("C1"); creatables.push_back("C2"); creatables.push_back("C3"); creatables.push_back("C4"); creatables.push_back("C5"); creatables.push_back("C6"); creatables.push_back("C7"); creatables.push_back("C8"); creatables.push_back("C9"); creatables.push_back("C10"); creatables.push_back("C11"); creatables.push_back("C12"); creatables.push_back("C13"); creatables.push_back("C14"); creatables.push_back("C15"); creatables.push_back("C16"); creatables.push_back("K1"); creatables.push_back("K2"); creatables.push_back("K3"); creatables.push_back("K4"); creatables.push_back("K5"); creatables.push_back("K6"); creatables.push_back("K7"); creatables.push_back("K8"); creatables.push_back("K9"); creatables.push_back("K10"); creatables.push_back("K11"); creatables.push_back("K12"); creatables.push_back("K13"); creatables.push_back("K14"); creatables.push_back("K15"); creatables.push_back("K16"); creatables.push_back("ThrustDirection1"); creatables.push_back("ThrustDirection2"); creatables.push_back("ThrustDirection3"); creatables.push_back("TotalPowerAvailable"); creatables.push_back("RequiredBusPower"); creatables.push_back("ThrustPowerAvailable"); } } //------------------------------------------------------------------------------ // ParameterFactory(StringArray createList) //------------------------------------------------------------------------------ /** * This method creates an object of the class ParameterFactory * (constructor). * * @param <createList> initial list of creatable objects * */ //------------------------------------------------------------------------------ ParameterFactory::ParameterFactory(StringArray createList) : Factory(createList, Gmat::PARAMETER) { } //------------------------------------------------------------------------------ // ParameterFactory(const ParameterFactory &fact) //------------------------------------------------------------------------------ /** * This method creates an object of the class ParameterFactory * (copy constructor). * * @param <fact> the factory object to copy to "this" factory. */ //------------------------------------------------------------------------------ ParameterFactory::ParameterFactory(const ParameterFactory &fact) : Factory(fact) { } //------------------------------------------------------------------------------ // ParameterFactory& operator= (const ParameterFactory &fact) //------------------------------------------------------------------------------ /** * Assignment operator for the ParameterFactory base class. * * @param <fact> the ParameterFactory object whose data to assign to "this" * factory. * * @return "this" ParameterFactory with data of input factory fact. */ //------------------------------------------------------------------------------ ParameterFactory& ParameterFactory::operator= (const ParameterFactory &fact) { Factory::operator=(fact); return *this; } //------------------------------------------------------------------------------ // ~ParameterFactory() //------------------------------------------------------------------------------ /** * Destructor for the ParameterFactory base class. */ //------------------------------------------------------------------------------ ParameterFactory::~ParameterFactory() { // deletes handled by Factory destructor }
/* Lincoln Glauser 5/19/16 */ /* EEEE-346 */ #include "../Include/HighScores.h" /* Code highly influenced from Sildomar T. Monteiro */ HighScores::HighScores(const char *filename) { highscoreFile.open(filename, ios::in | ios::out | ios::binary); if (!highscoreFile) { cout << "Creating file: " << filename << endl; highscoreFile.open(filename, ios::out); highscoreFile.close(); highscoreFile.open(filename, ios::in | ios::out | ios::binary); if (highscoreFile) { highscores.idnum = 0; highscores.gameID = 0; highscores.name[0] = '\0'; highscores.numTurns = 0; for (int i = 0; i<100; ++i) highscoreFile.write(reinterpret_cast<char *> (&highscores), sizeof(highscores)); } else { cerr << "File could not be created." << endl; exit(1); } } } HighScores::~HighScores() { highscoreFile.close(); } int HighScores::search_open_index() { for (int num = 1; num < 100; num++) { highscoreFile.seekg((num - 1) * sizeof(highscores)); highscoreFile.read(reinterpret_cast<char *> (&highscores), sizeof(highscores)); if (num != highscores.idnum) { return num; } } cout << "Highscore file full" << endl; return 0; } highscoreRecord HighScores::search_by_name(string name, int gID) { char tmp[30]; if (name.length() < 30) { for (int i = 0; i < name.length(); i++) { tmp[i] = name[i]; } tmp[name.length()] = '\0'; } else { for (int i = 0; i < 29; i++) { tmp[i] = name[i]; } tmp[29] = '\0'; } for (int num = 1; num < 100; num++) { highscoreFile.seekg((num - 1) * sizeof(highscores)); highscoreFile.read(reinterpret_cast<char *> (&highscores), sizeof(highscores)); if ((strcmp(tmp,highscores.name) == 0) && (gID == highscores.gameID)) { return highscores; } } highscores.idnum = 0; return highscores; } // function to read the input data from the user bool HighScores::input(string name, int gID, int nTurns) { if (!replace(name, gID, nTurns)) { highscores.idnum = search_open_index(); if (name.length() < 30) { for (int i = 0; i < name.length(); i++) { highscores.name[i] = name[i]; } highscores.name[name.length()] = '\0'; } else { for (int i = 0; i < 29; i++) { highscores.name[i] = name[i]; } highscores.name[29] = '\0'; } highscores.gameID = gID; highscores.numTurns = nTurns; write_file(); } return true; } // function to write data taken from the user into the file void HighScores::write_file() { highscoreFile.seekp((highscores.idnum - 1) * sizeof(highscores)); highscoreFile.write(reinterpret_cast<char *> (&highscores), sizeof(highscores)); } void HighScores::delete_score() { int temp = highscores.idnum; highscores.idnum = 0; highscoreFile.seekp((temp - 1) * sizeof(highscores)); highscoreFile.write(reinterpret_cast<char *> (&highscores), sizeof(highscores)); } //function to read data from the file bool HighScores::read_file(int num) { highscoreFile.seekg((num - 1) * sizeof(highscores)); highscoreFile.read(reinterpret_cast<char *> (&highscores), sizeof(highscores)); if (num != highscores.idnum) { cout << "Record does not exists" << endl; return false; } else { display_data(); return true; } } bool HighScores::replace(string name, int gID, int numTurns) { if ((search_by_name(name, gID).numTurns > numTurns) && (search_by_name(name, gID).idnum > 0)) { highscores = search_by_name(name, gID); highscores.numTurns = numTurns; write_file(); return true; } else { return false; } } void HighScores::display_all(int gID) { sort(); cout << left << setw(30) << "Name" << setw(7) << "# Turns" << endl; for (int num = 1; num < 100; num++) { highscoreFile.seekg((num - 1) * sizeof(highscores)); highscoreFile.read(reinterpret_cast<char *> (&highscores), sizeof(highscores)); if (num != highscores.idnum) { break; } else if (gID == highscores.gameID){ cout << left << setw(30) << highscores.name << setw(7) << highscores.numTurns << endl; } } } void HighScores::sort() { // Current Supports gID 0 & 1 // Setup Vector vHighscores.resize(2); // Grab all gID highscores and sort for (int gID = 0; gID < 2; gID++) { for (int num = 1; num < 100; num++) { highscoreFile.seekg((num - 1) * sizeof(highscores)); highscoreFile.read(reinterpret_cast<char *> (&highscores), sizeof(highscores)); if (num != highscores.idnum) { break; } else if (highscores.gameID == gID) { vHighscores[gID].push_back(highscores); // data is now "obsolete" from file delete_score(); } } // Sort gID highscores std::sort(vHighscores[gID].begin(), vHighscores[gID].end()); } int ID = 1; for (int gID = 0; gID < 2; gID++) { for (int num = 0; num < vHighscores[gID].size(); num++) { highscores = vHighscores[gID][num]; highscores.idnum = ID; write_file(); ID++; } } vHighscores.resize(0); } // function to display results to the screen void HighScores::display_data() { cout << left << setw(6) << "ID" << setw(6) << "gID" << setw(30) << "Name" << setw(7) << "# Turns" << endl; cout << left << setw(6) << highscores.idnum << setw(6) << highscores.gameID << setw(30) << highscores.name << setw(7) << highscores.numTurns << endl; }
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "extern/beatsaber-hook/shared/utils/typedefs.h" #include "extern/beatsaber-hook/shared/utils/byref.hpp" // Completed includes // Begin forward declares // Forward declaring namespace: GlobalNamespace namespace GlobalNamespace { // Forward declaring type: LevelCompletionResults class LevelCompletionResults; } // Forward declaring namespace: System::Collections::Generic namespace System::Collections::Generic { // Forward declaring type: Dictionary`2<TKey, TValue> template<typename TKey, typename TValue> class Dictionary_2; } // Completed forward declares // Type namespace: namespace GlobalNamespace { // Size: 0x10 #pragma pack(push, 1) // Autogenerated type: LevelCompletionResultsAnalyticsHelper // [TokenAttribute] Offset: FFFFFFFF class LevelCompletionResultsAnalyticsHelper : public ::Il2CppObject { public: // Creating value type constructor for type: LevelCompletionResultsAnalyticsHelper LevelCompletionResultsAnalyticsHelper() noexcept {} // static public System.Void FillEventData(LevelCompletionResults levelCompletionResults, System.Collections.Generic.Dictionary`2<System.String,System.String> eventData) // Offset: 0x1F4818C static void FillEventData(GlobalNamespace::LevelCompletionResults* levelCompletionResults, System::Collections::Generic::Dictionary_2<::Il2CppString*, ::Il2CppString*>* eventData); }; // LevelCompletionResultsAnalyticsHelper #pragma pack(pop) } #include "extern/beatsaber-hook/shared/utils/il2cpp-type-check.hpp" DEFINE_IL2CPP_ARG_TYPE(GlobalNamespace::LevelCompletionResultsAnalyticsHelper*, "", "LevelCompletionResultsAnalyticsHelper"); #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" // Writing MetadataGetter for method: GlobalNamespace::LevelCompletionResultsAnalyticsHelper::FillEventData // Il2CppName: FillEventData template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (*)(GlobalNamespace::LevelCompletionResults*, System::Collections::Generic::Dictionary_2<::Il2CppString*, ::Il2CppString*>*)>(&GlobalNamespace::LevelCompletionResultsAnalyticsHelper::FillEventData)> { static const MethodInfo* get() { static auto* levelCompletionResults = &::il2cpp_utils::GetClassFromName("", "LevelCompletionResults")->byval_arg; static auto* eventData = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System.Collections.Generic", "Dictionary`2"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("System", "String"), ::il2cpp_utils::GetClassFromName("System", "String")})->byval_arg; return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::LevelCompletionResultsAnalyticsHelper*), "FillEventData", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{levelCompletionResults, eventData}); } };
/* DDS, a bridge double dummy solver. Copyright (C) 2006-2014 by Bo Haglund / 2014-2018 by Bo Haglund & Soren Hein. See LICENSE and README. */ #include <iostream> #include <iomanip> #include <sstream> #include <string.h> #include "SolveBoard.h" #include "CalcTables.h" #include "PlayAnalyser.h" #include "parallel.h" #include "System.h" #include "Memory.h" #include "Scheduler.h" #include "ThreadMgr.h" extern Scheduler scheduler; extern Memory memory; extern ThreadMgr threadMgr; const vector<string> DDS_SYSTEM_PLATFORM = { "", "Windows", "Cygwin", "Linux", "Apple" }; const vector<string> DDS_SYSTEM_COMPILER = { "", "Microsoft Visual C++", "MinGW", "GNU g++", "clang" }; const vector<string> DDS_SYSTEM_CONSTRUCTOR = { "", "DllMain", "Unix-style" }; const vector<string> DDS_SYSTEM_THREADING = { "None", "Windows", "OpenMP", "GCD", "Boost", "STL", "TBB", "STL-impl", "PPL-impl" }; #define DDS_SYSTEM_THREAD_BASIC 0 #define DDS_SYSTEM_THREAD_WINAPI 1 #define DDS_SYSTEM_THREAD_OPENMP 2 #define DDS_SYSTEM_THREAD_GCD 3 #define DDS_SYSTEM_THREAD_BOOST 4 #define DDS_SYSTEM_THREAD_STL 5 #define DDS_SYSTEM_THREAD_TBB 6 #define DDS_SYSTEM_THREAD_STLIMPL 7 #define DDS_SYSTEM_THREAD_PPLIMPL 8 #define DDS_SYSTEM_THREAD_SIZE 9 System::System() { System::Reset(); } System::~System() { } void System::Reset() { runCat = DDS_RUN_SOLVE; numThreads = 1; preferredSystem = DDS_SYSTEM_THREAD_BASIC; availableSystem.resize(DDS_SYSTEM_THREAD_SIZE); availableSystem[DDS_SYSTEM_THREAD_BASIC] = true; for (unsigned i = 1; i < DDS_SYSTEM_THREAD_SIZE; i++) availableSystem[i] = false; #ifdef DDS_THREADS_WINAPI availableSystem[DDS_SYSTEM_THREAD_WINAPI] = true; #endif #ifdef DDS_THREADS_OPENMP availableSystem[DDS_SYSTEM_THREAD_OPENMP] = true; #endif #ifdef DDS_THREADS_GCD availableSystem[DDS_SYSTEM_THREAD_GCD] = true; #endif #ifdef DDS_THREADS_BOOST availableSystem[DDS_SYSTEM_THREAD_BOOST] = true; #endif #ifdef DDS_THREADS_STL availableSystem[DDS_SYSTEM_THREAD_STL] = true; #endif #ifdef DDS_THREADS_TBB availableSystem[DDS_SYSTEM_THREAD_TBB] = true; #endif #ifdef DDS_THREADS_STLIMPL availableSystem[DDS_SYSTEM_THREAD_STLIMPL] = true; #endif #ifdef DDS_THREADS_PPLIMPL availableSystem[DDS_SYSTEM_THREAD_PPLIMPL] = true; #endif // Take the first of any multi-threading system defined. for (unsigned k = 1; k < availableSystem.size(); k++) { if (availableSystem[k]) { preferredSystem = k; break; } } RunPtrList.resize(DDS_SYSTEM_THREAD_SIZE); RunPtrList[DDS_SYSTEM_THREAD_BASIC] = &System::RunThreadsBasic; RunPtrList[DDS_SYSTEM_THREAD_WINAPI] = &System::RunThreadsWinAPI; RunPtrList[DDS_SYSTEM_THREAD_OPENMP] = &System::RunThreadsOpenMP; RunPtrList[DDS_SYSTEM_THREAD_GCD] = &System::RunThreadsGCD; RunPtrList[DDS_SYSTEM_THREAD_BOOST] = &System::RunThreadsBoost; RunPtrList[DDS_SYSTEM_THREAD_STL] = &System::RunThreadsSTL; RunPtrList[DDS_SYSTEM_THREAD_TBB] = &System::RunThreadsTBB; RunPtrList[DDS_SYSTEM_THREAD_STLIMPL] = &System::RunThreadsSTLIMPL; RunPtrList[DDS_SYSTEM_THREAD_PPLIMPL] = &System::RunThreadsPPLIMPL; CallbackSimpleList.resize(DDS_RUN_SIZE); CallbackSimpleList[DDS_RUN_SOLVE] = SolveChunkCommon; CallbackSimpleList[DDS_RUN_CALC] = CalcChunkCommon; CallbackSimpleList[DDS_RUN_TRACE] = PlayChunkCommon; CallbackDuplList.resize(DDS_RUN_SIZE); CallbackDuplList[DDS_RUN_SOLVE] = DetectSolveDuplicates; CallbackDuplList[DDS_RUN_CALC] = DetectCalcDuplicates; CallbackDuplList[DDS_RUN_TRACE] = DetectPlayDuplicates; CallbackSingleList.resize(DDS_RUN_SIZE); CallbackSingleList[DDS_RUN_SOLVE] = SolveSingleCommon; CallbackSingleList[DDS_RUN_CALC] = CalcSingleCommon; CallbackSingleList[DDS_RUN_TRACE] = PlaySingleCommon; CallbackCopyList.resize(DDS_RUN_SIZE); CallbackCopyList[DDS_RUN_SOLVE] = CopySolveSingle; CallbackCopyList[DDS_RUN_CALC] = CopyCalcSingle; CallbackCopyList[DDS_RUN_TRACE] = CopyPlaySingle; } void System::GetHardware( int& ncores, unsigned long long& kilobytesFree) const { kilobytesFree = 0; ncores = 1; (void) System::GetCores(ncores); #if defined(_WIN32) || defined(__CYGWIN__) // Using GlobalMemoryStatusEx instead of GlobalMemoryStatus // was suggested by Lorne Anderson. MEMORYSTATUSEX statex; statex.dwLength = sizeof(statex); GlobalMemoryStatusEx(&statex); kilobytesFree = static_cast<unsigned long long>( statex.ullTotalPhys / 1024); SYSTEM_INFO sysinfo; GetSystemInfo(&sysinfo); ncores = static_cast<int>(sysinfo.dwNumberOfProcessors); return; #endif #ifdef __APPLE__ // The code for Mac OS X was suggested by Matthew Kidd. // This is physical memory, rather than "free" memory as below // for Linux. Always leave 0.5 GB for the OS and other stuff. // It would be better to find free memory (how?) but in practice // the number of cores rather than free memory is almost certainly // the limit for Macs which have standardized hardware (whereas // say a 32 core Linux server is hardly unusual). FILE * fifo = popen("sysctl -n hw.memsize", "r"); fscanf(fifo, "%lld", &kilobytesFree); fclose(fifo); kilobytesFree /= 1024; if (kilobytesFree > 500000) { kilobytesFree -= 500000; } ncores = sysconf(_SC_NPROCESSORS_ONLN); return; #endif #ifdef __linux__ // Use half of the physical memory long pages = sysconf (_SC_PHYS_PAGES); long pagesize = sysconf (_SC_PAGESIZE); if (pages > 0 && pagesize > 0) kilobytesFree = static_cast<unsigned long long>(pages * pagesize / 1024 / 2); else kilobytesFree = 1024 * 1024; // guess 1GB ncores = sysconf(_SC_NPROCESSORS_ONLN); return; #endif } int System::RegisterParams( const int nThreads, const int mem_usable_MB) { // No upper limit -- caveat emptor. if (nThreads < 1) return RETURN_THREAD_INDEX; numThreads = nThreads; sysMem_MB = mem_usable_MB; return RETURN_NO_FAULT; } int System::RegisterRun( const RunMode mode, const boards& bdsIn) { if (mode >= DDS_RUN_SIZE) return RETURN_THREAD_MISSING; // Not quite right; runCat = mode; bop = &bdsIn; return RETURN_NO_FAULT; } bool System::IsSingleThreaded() const { return (preferredSystem == DDS_SYSTEM_THREAD_BASIC); } bool System::IsIMPL() const { return (preferredSystem >= DDS_SYSTEM_THREAD_STLIMPL); } bool System::ThreadOK(const int thrId) const { return (thrId >= 0 && thrId < numThreads); } int System::PreferThreading(const unsigned code) { if (code >= DDS_SYSTEM_THREAD_SIZE) return RETURN_THREAD_MISSING; if (! availableSystem[code]) return RETURN_THREAD_MISSING; preferredSystem = code; return RETURN_NO_FAULT; } ////////////////////////////////////////////////////////////////////// // Basic // ////////////////////////////////////////////////////////////////////// int System::RunThreadsBasic() { (*fptr)(0); return RETURN_NO_FAULT; } ////////////////////////////////////////////////////////////////////// // WinAPI // ////////////////////////////////////////////////////////////////////// #ifdef DDS_THREADS_WINAPI struct WinWrapType { int thrId; fptrType fptr; HANDLE *waitPtr; }; DWORD CALLBACK WinCallback(void * p); DWORD CALLBACK WinCallback(void * p) { WinWrapType * winWrap = static_cast<WinWrapType *>(p); (*(winWrap->fptr))(winWrap->thrId); if (SetEvent(winWrap->waitPtr[winWrap->thrId]) == 0) return 0; return 1; } #endif int System::RunThreadsWinAPI() { #ifdef DDS_THREADS_WINAPI HANDLE * solveAllEvents = static_cast<HANDLE * >( malloc(static_cast<unsigned>(numThreads) * sizeof(HANDLE))); for (int k = 0; k < numThreads; k++) { solveAllEvents[k] = CreateEvent(NULL, FALSE, FALSE, 0); if (solveAllEvents[k] == 0) return RETURN_THREAD_CREATE; } vector<WinWrapType> winWrap; const unsigned nt = static_cast<unsigned>(numThreads); winWrap.resize(nt); for (unsigned k = 0; k < nt; k++) { winWrap[k].thrId = static_cast<int>(k); winWrap[k].fptr = fptr; winWrap[k].waitPtr = solveAllEvents; int res = QueueUserWorkItem(WinCallback, static_cast<void *>(&winWrap[k]), WT_EXECUTELONGFUNCTION); if (res != 1) return res; } DWORD solveAllWaitResult; solveAllWaitResult = WaitForMultipleObjects( static_cast<unsigned>(numThreads), solveAllEvents, TRUE, INFINITE); if (solveAllWaitResult != WAIT_OBJECT_0) return RETURN_THREAD_WAIT; for (int k = 0; k < numThreads; k++) CloseHandle(solveAllEvents[k]); free(solveAllEvents); #endif return RETURN_NO_FAULT; } ////////////////////////////////////////////////////////////////////// // OpenMP // ////////////////////////////////////////////////////////////////////// int System::RunThreadsOpenMP() { #ifdef DDS_THREADS_OPENMP // Added after suggestion by Dirk Willecke. if (omp_get_dynamic()) omp_set_dynamic(0); omp_set_num_threads(numThreads); #pragma omp parallel default(none) { #pragma omp for schedule(dynamic) for (int k = 0; k < numThreads; k++) { int thrId = omp_get_thread_num(); (*fptr)(thrId); } } #endif return RETURN_NO_FAULT; } ////////////////////////////////////////////////////////////////////// // GCD // ////////////////////////////////////////////////////////////////////// int System::RunThreadsGCD() { #ifdef DDS_THREADS_GCD dispatch_apply(static_cast<size_t>(numThreads), dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^(size_t t) { int thrId = static_cast<int>(t); (*fptr)(thrId); }); #endif return RETURN_NO_FAULT; } ////////////////////////////////////////////////////////////////////// // Boost // ////////////////////////////////////////////////////////////////////// int System::RunThreadsBoost() { #ifdef DDS_THREADS_BOOST vector<boost::thread *> threads; const unsigned nu = static_cast<unsigned>(numThreads); threads.resize(nu); for (unsigned k = 0; k < nu; k++) threads[k] = new boost::thread(fptr, k); for (unsigned k = 0; k < nu; k++) { threads[k]->join(); delete threads[k]; } #endif return RETURN_NO_FAULT; } ////////////////////////////////////////////////////////////////////// // STL // ////////////////////////////////////////////////////////////////////// int System::RunThreadsSTL() { #ifdef DDS_THREADS_STL vector<thread *> threads; vector<int> uniques; vector<int> crossrefs; (* CallbackDuplList[runCat])(* bop, uniques, crossrefs); const unsigned nu = static_cast<unsigned>(numThreads); threads.resize(nu); for (unsigned k = 0; k < nu; k++) threads[k] = new thread(fptr, k); for (unsigned k = 0; k < nu; k++) { threads[k]->join(); delete threads[k]; } #endif return RETURN_NO_FAULT; } int System::RunThreadsSTLIMPL() { #ifdef DDS_THREADS_STLIMPL vector<int> uniques; vector<int> crossrefs; (* CallbackDuplList[runCat])(* bop, uniques, crossrefs); static atomic<int> thrIdNext = 0; bool err = false; threadMgr.Reset(numThreads); for_each(std::execution::par, uniques.begin(), uniques.end(), [&](int &bno) { thread_local int thrId = -1; thread_local int realThrId; if (thrId == -1) thrId = thrIdNext++; realThrId = threadMgr.Occupy(thrId); if (realThrId == -1) err = true; else (* CallbackSingleList[runCat])(realThrId, bno); if (! threadMgr.Release(thrId)) err = true; }); if (err) { cout << "Too many threads, numThreads " << numThreads << endl; return RETURN_THREAD_INDEX; } (* CallbackCopyList[runCat])(crossrefs); #endif return RETURN_NO_FAULT; } ////////////////////////////////////////////////////////////////////// // TBB // ////////////////////////////////////////////////////////////////////// int System::RunThreadsTBB() { #ifdef DDS_THREADS_TBB vector<tbb::tbb_thread *> threads; const unsigned nu = static_cast<unsigned>(numThreads); threads.resize(nu); for (unsigned k = 0; k < nu; k++) threads[k] = new tbb::tbb_thread(fptr, k); for (unsigned k = 0; k < nu; k++) { threads[k]->join(); delete threads[k]; } #endif return RETURN_NO_FAULT; } ////////////////////////////////////////////////////////////////////// // PPL // ////////////////////////////////////////////////////////////////////// int System::RunThreadsPPLIMPL() { #ifdef DDS_THREADS_PPLIMPL vector<int> uniques; vector<int> crossrefs; (* CallbackDuplList[runCat])(* bop, uniques, crossrefs); static atomic<int> thrIdNext = 0; bool err = false, err2 = false; threadMgr.Reset(numThreads); Concurrency::parallel_for_each(uniques.begin(), uniques.end(), [&](int &bno) { thread_local int thrId = -1; thread_local int realThrId; if (thrId == -1) thrId = thrIdNext++; realThrId = threadMgr.Occupy(thrId); if (realThrId == -1) err = true; else (* CallbackSingleList[runCat])(realThrId, bno); if (! threadMgr.Release(thrId)) err2 = true; }); if (err) { cout << "Too many threads, numThreads " << numThreads << endl; return RETURN_THREAD_INDEX; } else if (err2) { cout << "Release failed, numThreads " << numThreads << endl; return RETURN_THREAD_INDEX; } (* CallbackCopyList[runCat])(crossrefs); #endif return RETURN_NO_FAULT; } int System::RunThreads() { fptr = CallbackSimpleList[runCat]; return (this->*RunPtrList[preferredSystem])(); } ////////////////////////////////////////////////////////////////////// // Self-identification // ////////////////////////////////////////////////////////////////////// string System::GetVersion( int& major, int& minor, int& patch) const { major = DDS_VERSION / 10000; minor = (DDS_VERSION - major * 10000) / 100; patch = DDS_VERSION % 100; string st = to_string(major) + "." + to_string(minor) + "." + to_string(patch); return st; } string System::GetSystem(int& sys) const { #if defined(_WIN32) sys = 1; #elif defined(__CYGWIN__) sys = 2; #elif defined(__linux) sys = 3; #elif defined(__APPLE__) sys = 4; #else sys = 0; #endif return DDS_SYSTEM_PLATFORM[static_cast<unsigned>(sys)]; } string System::GetBits(int& bits) const { #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable: 4127) #endif string st; if (sizeof(void *) == 4) { bits = 32; st = "32 bits"; } else if (sizeof(void *) == 8) { bits = 64; st = "64 bits"; } else { bits = 0; st = "unknown"; } #ifdef _MSC_VER #pragma warning(pop) #endif return st; } string System::GetCompiler(int& comp) const { #if defined(_MSC_VER) comp = 1; #elif defined(__MINGW32__) comp = 2; #elif defined(__clang__) comp = 4; // Out-of-order on purpose #elif defined(__GNUC__) comp = 3; #else comp = 0; #endif return DDS_SYSTEM_COMPILER[static_cast<unsigned>(comp)]; } string System::GetConstructor(int& cons) const { #if defined(USES_DLLMAIN) cons = 1; #elif defined(USES_CONSTRUCTOR) cons = 2; #else cons = 0; #endif return DDS_SYSTEM_CONSTRUCTOR[static_cast<unsigned>(cons)]; } string System::GetCores(int& cores) const { #if defined(_WIN32) || defined(__CYGWIN__) SYSTEM_INFO sysinfo; GetSystemInfo(&sysinfo); cores = static_cast<int>(sysinfo.dwNumberOfProcessors); #elif defined(__APPLE__) || defined(__linux__) cores = sysconf(_SC_NPROCESSORS_ONLN); #endif // TODO Think about thread::hardware_concurrency(). // This should be standard in C++11. return to_string(cores); } string System::GetThreading(int& thr) const { string st = ""; thr = 0; for (unsigned k = 0; k < DDS_SYSTEM_THREAD_SIZE; k++) { if (availableSystem[k]) { st += " " + DDS_SYSTEM_THREADING[k]; if (k == preferredSystem) { st += "(*)"; thr = static_cast<int>(k); } } } return st; } string System::GetThreadSizes(char * sizes) const { int l = 0, s = 0; for (unsigned i = 0; i < static_cast<unsigned>(numThreads); i++) { if (memory.ThreadSize(i) == "S") s++; else l++; } const string st = to_string(s) + " S, " + to_string(l) + " L"; strcpy(sizes, st.c_str()); return st; } string System::str(DDSInfo * info) const { stringstream ss; ss << "DDS DLL\n-------\n"; const string strSystem = System::GetSystem(info->system); ss << left << setw(13) << "System" << setw(20) << right << strSystem << "\n"; const string strBits = System::GetBits(info->numBits); ss << left << setw(13) << "Word size" << setw(20) << right << strBits << "\n"; const string strCompiler = System::GetCompiler(info->compiler); ss << left << setw(13) << "Compiler" << setw(20) << right << strCompiler << "\n"; const string strConstructor = System::GetConstructor(info->constructor); ss << left << setw(13) << "Constructor" << setw(20) << right << strConstructor << "\n"; const string strVersion = System::GetVersion(info->major, info->minor, info->patch); ss << left << setw(13) << "Version" << setw(20) << right << strVersion << "\n"; strcpy(info->versionString, strVersion.c_str()); ss << left << setw(17) << "Memory max (MB)" << setw(16) << right << sysMem_MB << "\n"; const string stm = to_string(THREADMEM_SMALL_DEF_MB) + "-" + to_string(THREADMEM_SMALL_MAX_MB) + " / " + to_string(THREADMEM_LARGE_DEF_MB) + "-" + to_string(THREADMEM_LARGE_MAX_MB); ss << left << setw(17) << "Threads (MB)" << setw(16) << right << stm << "\n"; System::GetCores(info->numCores); ss << left << setw(17) << "Number of cores" << setw(16) << right << info->numCores << "\n"; info->noOfThreads = numThreads; ss << left << setw(17) << "Number of threads" << setw(16) << right << numThreads << "\n"; const string strThrSizes = System::GetThreadSizes(info->threadSizes); ss << left << setw(13) << "Thread sizes" << setw(20) << right << strThrSizes << "\n"; const string strThreading = System::GetThreading(info->threading); ss << left << setw(9) << "Threading" << setw(24) << right << strThreading << "\n"; const string st = ss.str(); strcpy(info->systemString, st.c_str()); return st; }
/* * Copyright Andrey Semashev 2007 - 2015. * 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) */ /*! * \file text_file_backend.cpp * \author Andrey Semashev * \date 09.06.2009 * * \brief This header is the Boost.Log library implementation, see the library documentation * at http://www.boost.org/doc/libs/release/libs/log/doc/html/index.html. */ #include <boost/log/detail/config.hpp> #include <ctime> #include <cctype> #include <cwctype> #include <ctime> #include <cstdio> #include <cstdlib> #include <cstddef> #include <list> #include <string> #include <locale> #include <ostream> #include <sstream> #include <iterator> #include <algorithm> #include <stdexcept> #include <boost/core/ref.hpp> #include <boost/bind/bind.hpp> #include <boost/cstdint.hpp> #include <boost/smart_ptr/make_shared_object.hpp> #include <boost/enable_shared_from_this.hpp> #include <boost/throw_exception.hpp> #include <boost/mpl/if.hpp> #include <boost/type_traits/is_same.hpp> #include <boost/system/error_code.hpp> #include <boost/system/system_error.hpp> #include <boost/filesystem/directory.hpp> #include <boost/filesystem/exception.hpp> #include <boost/filesystem/path.hpp> #include <boost/filesystem/fstream.hpp> #include <boost/filesystem/operations.hpp> #include <boost/filesystem/convenience.hpp> #include <boost/intrusive/list.hpp> #include <boost/intrusive/list_hook.hpp> #include <boost/intrusive/options.hpp> #include <boost/date_time/posix_time/posix_time.hpp> #include <boost/date_time/gregorian/gregorian_types.hpp> #include <boost/spirit/home/qi/numeric/numeric_utils.hpp> #include <boost/log/detail/singleton.hpp> #include <boost/log/detail/light_function.hpp> #include <boost/log/exceptions.hpp> #include <boost/log/attributes/time_traits.hpp> #include <boost/log/sinks/auto_newline_mode.hpp> #include <boost/log/sinks/text_file_backend.hpp> #include "unique_ptr.hpp" #if !defined(BOOST_LOG_NO_THREADS) #include <boost/thread/locks.hpp> #include <boost/thread/mutex.hpp> #endif // !defined(BOOST_LOG_NO_THREADS) #include <boost/log/detail/header.hpp> namespace qi = boost::spirit::qi; namespace boost { BOOST_LOG_OPEN_NAMESPACE namespace sinks { BOOST_LOG_ANONYMOUS_NAMESPACE { typedef filesystem::filesystem_error filesystem_error; //! A possible Boost.Filesystem extension - renames or moves the file to the target storage inline void move_file( filesystem::path const& from, filesystem::path const& to) { #if defined(BOOST_WINDOWS_API) // On Windows MoveFile already does what we need filesystem::rename(from, to); #else // On POSIX rename fails if the target points to a different device system::error_code ec; filesystem::rename(from, to, ec); if (ec) { if (BOOST_LIKELY(ec.value() == system::errc::cross_device_link)) { // Attempt to manually move the file instead filesystem::copy_file(from, to); filesystem::remove(from); } else { BOOST_THROW_EXCEPTION(filesystem_error("failed to move file to another location", from, to, ec)); } } #endif } typedef filesystem::path::string_type path_string_type; typedef path_string_type::value_type path_char_type; //! An auxiliary traits that contain various constants and functions regarding string and character operations template< typename CharT > struct file_char_traits; template< > struct file_char_traits< char > { typedef char char_type; static const char_type percent = '%'; static const char_type number_placeholder = 'N'; static const char_type day_placeholder = 'd'; static const char_type month_placeholder = 'm'; static const char_type year_placeholder = 'y'; static const char_type full_year_placeholder = 'Y'; static const char_type frac_sec_placeholder = 'f'; static const char_type seconds_placeholder = 'S'; static const char_type minutes_placeholder = 'M'; static const char_type hours_placeholder = 'H'; static const char_type space = ' '; static const char_type plus = '+'; static const char_type minus = '-'; static const char_type zero = '0'; static const char_type dot = '.'; static const char_type newline = '\n'; static bool is_digit(char c) { using namespace std; return (isdigit(c) != 0); } static std::string default_file_name_pattern() { return "%5N.log"; } }; #ifndef BOOST_LOG_BROKEN_STATIC_CONSTANTS_LINKAGE const file_char_traits< char >::char_type file_char_traits< char >::percent; const file_char_traits< char >::char_type file_char_traits< char >::number_placeholder; const file_char_traits< char >::char_type file_char_traits< char >::day_placeholder; const file_char_traits< char >::char_type file_char_traits< char >::month_placeholder; const file_char_traits< char >::char_type file_char_traits< char >::year_placeholder; const file_char_traits< char >::char_type file_char_traits< char >::full_year_placeholder; const file_char_traits< char >::char_type file_char_traits< char >::frac_sec_placeholder; const file_char_traits< char >::char_type file_char_traits< char >::seconds_placeholder; const file_char_traits< char >::char_type file_char_traits< char >::minutes_placeholder; const file_char_traits< char >::char_type file_char_traits< char >::hours_placeholder; const file_char_traits< char >::char_type file_char_traits< char >::space; const file_char_traits< char >::char_type file_char_traits< char >::plus; const file_char_traits< char >::char_type file_char_traits< char >::minus; const file_char_traits< char >::char_type file_char_traits< char >::zero; const file_char_traits< char >::char_type file_char_traits< char >::dot; const file_char_traits< char >::char_type file_char_traits< char >::newline; #endif // BOOST_LOG_BROKEN_STATIC_CONSTANTS_LINKAGE template< > struct file_char_traits< wchar_t > { typedef wchar_t char_type; static const char_type percent = L'%'; static const char_type number_placeholder = L'N'; static const char_type day_placeholder = L'd'; static const char_type month_placeholder = L'm'; static const char_type year_placeholder = L'y'; static const char_type full_year_placeholder = L'Y'; static const char_type frac_sec_placeholder = L'f'; static const char_type seconds_placeholder = L'S'; static const char_type minutes_placeholder = L'M'; static const char_type hours_placeholder = L'H'; static const char_type space = L' '; static const char_type plus = L'+'; static const char_type minus = L'-'; static const char_type zero = L'0'; static const char_type dot = L'.'; static const char_type newline = L'\n'; static bool is_digit(wchar_t c) { using namespace std; return (iswdigit(c) != 0); } static std::wstring default_file_name_pattern() { return L"%5N.log"; } }; #ifndef BOOST_LOG_BROKEN_STATIC_CONSTANTS_LINKAGE const file_char_traits< wchar_t >::char_type file_char_traits< wchar_t >::percent; const file_char_traits< wchar_t >::char_type file_char_traits< wchar_t >::number_placeholder; const file_char_traits< wchar_t >::char_type file_char_traits< wchar_t >::day_placeholder; const file_char_traits< wchar_t >::char_type file_char_traits< wchar_t >::month_placeholder; const file_char_traits< wchar_t >::char_type file_char_traits< wchar_t >::year_placeholder; const file_char_traits< wchar_t >::char_type file_char_traits< wchar_t >::full_year_placeholder; const file_char_traits< wchar_t >::char_type file_char_traits< wchar_t >::frac_sec_placeholder; const file_char_traits< wchar_t >::char_type file_char_traits< wchar_t >::seconds_placeholder; const file_char_traits< wchar_t >::char_type file_char_traits< wchar_t >::minutes_placeholder; const file_char_traits< wchar_t >::char_type file_char_traits< wchar_t >::hours_placeholder; const file_char_traits< wchar_t >::char_type file_char_traits< wchar_t >::space; const file_char_traits< wchar_t >::char_type file_char_traits< wchar_t >::plus; const file_char_traits< wchar_t >::char_type file_char_traits< wchar_t >::minus; const file_char_traits< wchar_t >::char_type file_char_traits< wchar_t >::zero; const file_char_traits< wchar_t >::char_type file_char_traits< wchar_t >::dot; const file_char_traits< wchar_t >::char_type file_char_traits< wchar_t >::newline; #endif // BOOST_LOG_BROKEN_STATIC_CONSTANTS_LINKAGE //! Date and time formatter class date_and_time_formatter { public: typedef path_string_type result_type; private: typedef date_time::time_facet< posix_time::ptime, path_char_type > time_facet_type; private: mutable time_facet_type m_Facet; mutable std::basic_ostringstream< path_char_type > m_Stream; public: //! Constructor date_and_time_formatter() : m_Facet(1u) { } //! Copy constructor date_and_time_formatter(date_and_time_formatter const& that) : m_Facet(1u) { } //! The method formats the current date and time according to the format string str and writes the result into it path_string_type operator()(path_string_type const& pattern, unsigned int counter) const { m_Facet.format(pattern.c_str()); m_Stream.str(path_string_type()); // Note: the regular operator<< fails because std::use_facet fails to find the facet in the locale because // the facet type in Boost.DateTime has hidden visibility. See this ticket: // https://svn.boost.org/trac/boost/ticket/11707 std::ostreambuf_iterator< path_char_type > sbuf_it(m_Stream); m_Facet.put(sbuf_it, m_Stream, m_Stream.fill(), boost::log::attributes::local_time_traits::get_clock()); if (m_Stream.good()) { return m_Stream.str(); } else { m_Stream.clear(); return pattern; } } BOOST_DELETED_FUNCTION(date_and_time_formatter& operator= (date_and_time_formatter const&)) }; //! The functor formats the file counter into the file name class file_counter_formatter { public: typedef path_string_type result_type; private: //! The position in the pattern where the file counter placeholder is path_string_type::size_type m_FileCounterPosition; //! File counter width std::streamsize m_Width; //! The file counter formatting stream mutable std::basic_ostringstream< path_char_type > m_Stream; public: //! Initializing constructor file_counter_formatter(path_string_type::size_type pos, unsigned int width) : m_FileCounterPosition(pos), m_Width(width) { typedef file_char_traits< path_char_type > traits_t; m_Stream.fill(traits_t::zero); } //! Copy constructor file_counter_formatter(file_counter_formatter const& that) : m_FileCounterPosition(that.m_FileCounterPosition), m_Width(that.m_Width) { m_Stream.fill(that.m_Stream.fill()); } //! The function formats the file counter into the file name path_string_type operator()(path_string_type const& pattern, unsigned int counter) const { path_string_type file_name = pattern; m_Stream.str(path_string_type()); m_Stream.width(m_Width); m_Stream << counter; file_name.insert(m_FileCounterPosition, m_Stream.str()); return file_name; } BOOST_DELETED_FUNCTION(file_counter_formatter& operator= (file_counter_formatter const&)) }; //! The function returns the pattern as the file name class empty_formatter { public: typedef path_string_type result_type; private: path_string_type m_Pattern; public: //! Initializing constructor explicit empty_formatter(path_string_type const& pattern) : m_Pattern(pattern) { } //! Copy constructor empty_formatter(empty_formatter const& that) : m_Pattern(that.m_Pattern) { } //! The function returns the pattern as the file name path_string_type const& operator() (unsigned int) const { return m_Pattern; } BOOST_DELETED_FUNCTION(empty_formatter& operator= (empty_formatter const&)) }; //! The function parses the format placeholder for file counter bool parse_counter_placeholder(path_string_type::const_iterator& it, path_string_type::const_iterator end, unsigned int& width) { typedef qi::extract_uint< unsigned int, 10, 1, -1 > width_extract; typedef file_char_traits< path_char_type > traits_t; if (it == end) return false; path_char_type c = *it; if (c == traits_t::zero || c == traits_t::space || c == traits_t::plus || c == traits_t::minus) { // Skip filler and alignment specification ++it; if (it == end) return false; c = *it; } if (traits_t::is_digit(c)) { // Parse width if (!width_extract::call(it, end, width)) return false; if (it == end) return false; c = *it; } if (c == traits_t::dot) { // Skip precision ++it; while (it != end && traits_t::is_digit(*it)) ++it; if (it == end) return false; c = *it; } if (c == traits_t::number_placeholder) { ++it; return true; } return false; } //! The function matches the file name and the pattern bool match_pattern(path_string_type const& file_name, path_string_type const& pattern, unsigned int& file_counter, bool& file_counter_parsed) { typedef qi::extract_uint< unsigned int, 10, 1, -1 > file_counter_extract; typedef file_char_traits< path_char_type > traits_t; struct local { // Verifies that the string contains exactly n digits static bool scan_digits(path_string_type::const_iterator& it, path_string_type::const_iterator end, std::ptrdiff_t n) { for (; n > 0; --n) { if (it == end) return false; path_char_type c = *it++; if (!traits_t::is_digit(c)) return false; } return true; } }; path_string_type::const_iterator f_it = file_name.begin(), f_end = file_name.end(), p_it = pattern.begin(), p_end = pattern.end(); bool placeholder_expected = false; while (f_it != f_end && p_it != p_end) { path_char_type p_c = *p_it, f_c = *f_it; if (!placeholder_expected) { if (p_c == traits_t::percent) { placeholder_expected = true; ++p_it; } else if (p_c == f_c) { ++p_it; ++f_it; } else return false; } else { switch (p_c) { case traits_t::percent: // An escaped '%' if (p_c == f_c) { ++p_it; ++f_it; break; } else return false; case traits_t::seconds_placeholder: // Date/time components with 2-digits width case traits_t::minutes_placeholder: case traits_t::hours_placeholder: case traits_t::day_placeholder: case traits_t::month_placeholder: case traits_t::year_placeholder: if (!local::scan_digits(f_it, f_end, 2)) return false; ++p_it; break; case traits_t::full_year_placeholder: // Date/time components with 4-digits width if (!local::scan_digits(f_it, f_end, 4)) return false; ++p_it; break; case traits_t::frac_sec_placeholder: // Fraction seconds width is configuration-dependent typedef posix_time::time_res_traits posix_resolution_traits; if (!local::scan_digits(f_it, f_end, posix_resolution_traits::num_fractional_digits())) { return false; } ++p_it; break; default: // This should be the file counter placeholder or some unsupported placeholder { path_string_type::const_iterator p = p_it; unsigned int width = 0; if (!parse_counter_placeholder(p, p_end, width)) { BOOST_THROW_EXCEPTION(std::invalid_argument("Unsupported placeholder used in pattern for file scanning")); } // Find where the file number ends path_string_type::const_iterator f = f_it; if (!local::scan_digits(f, f_end, width)) return false; while (f != f_end && traits_t::is_digit(*f)) ++f; if (!file_counter_extract::call(f_it, f, file_counter)) return false; file_counter_parsed = true; p_it = p; } break; } placeholder_expected = false; } } if (p_it == p_end) { if (f_it != f_end) { // The actual file name may end with an additional counter // that is added by the collector in case if file name clash return local::scan_digits(f_it, f_end, std::distance(f_it, f_end)); } else return true; } else return false; } //! The function parses file name pattern and splits it into path and filename and creates a function object that will generate the actual filename from the pattern void parse_file_name_pattern(filesystem::path const& pattern, filesystem::path& storage_dir, filesystem::path& file_name_pattern, boost::log::aux::light_function< path_string_type (unsigned int) >& file_name_generator) { // Note: avoid calling Boost.Filesystem functions that involve path::codecvt() // https://svn.boost.org/trac/boost/ticket/9119 typedef file_char_traits< path_char_type > traits_t; file_name_pattern = pattern.filename(); path_string_type name_pattern = file_name_pattern.native(); storage_dir = filesystem::absolute(pattern.parent_path()); // Let's try to find the file counter placeholder unsigned int placeholder_count = 0; unsigned int width = 0; bool counter_found = false; path_string_type::size_type counter_pos = 0; path_string_type::const_iterator end = name_pattern.end(); path_string_type::const_iterator it = name_pattern.begin(); do { it = std::find(it, end, traits_t::percent); if (it == end) break; path_string_type::const_iterator placeholder_begin = it++; if (it == end) break; if (*it == traits_t::percent) { // An escaped percent detected ++it; continue; } ++placeholder_count; if (!counter_found) { path_string_type::const_iterator it2 = it; if (parse_counter_placeholder(it2, end, width)) { // We've found the file counter placeholder in the pattern counter_found = true; counter_pos = placeholder_begin - name_pattern.begin(); name_pattern.erase(counter_pos, it2 - placeholder_begin); --placeholder_count; it = name_pattern.begin() + counter_pos; end = name_pattern.end(); } } } while (it != end); // Construct the formatter functor if (placeholder_count > 0) { if (counter_found) { // Both counter and date/time placeholder in the pattern file_name_generator = boost::bind(date_and_time_formatter(), boost::bind(file_counter_formatter(counter_pos, width), name_pattern, boost::placeholders::_1), boost::placeholders::_1); } else { // Only date/time placeholders in the pattern file_name_generator = boost::bind(date_and_time_formatter(), name_pattern, boost::placeholders::_1); } } else if (counter_found) { // Only counter placeholder in the pattern file_name_generator = boost::bind(file_counter_formatter(counter_pos, width), name_pattern, boost::placeholders::_1); } else { // No placeholders detected file_name_generator = empty_formatter(name_pattern); } } class file_collector_repository; //! Type of the hook used for sequencing file collectors typedef intrusive::list_base_hook< intrusive::link_mode< intrusive::safe_link > > file_collector_hook; //! Log file collector implementation class file_collector : public file::collector, public file_collector_hook, public enable_shared_from_this< file_collector > { private: //! Information about a single stored file struct file_info { uintmax_t m_Size; std::time_t m_TimeStamp; filesystem::path m_Path; }; //! A list of the stored files typedef std::list< file_info > file_list; //! The string type compatible with the universal path type typedef filesystem::path::string_type path_string_type; private: //! A reference to the repository this collector belongs to shared_ptr< file_collector_repository > m_pRepository; #if !defined(BOOST_LOG_NO_THREADS) //! Synchronization mutex mutex m_Mutex; #endif // !defined(BOOST_LOG_NO_THREADS) //! Total file size upper limit uintmax_t m_MaxSize; //! Free space lower limit uintmax_t m_MinFreeSpace; //! File count upper limit uintmax_t m_MaxFiles; //! The current path at the point when the collector is created /* * The special member is required to calculate absolute paths with no * dependency on the current path for the application, which may change */ const filesystem::path m_BasePath; //! Target directory to store files to filesystem::path m_StorageDir; //! The list of stored files file_list m_Files; //! Total size of the stored files uintmax_t m_TotalSize; public: //! Constructor file_collector( shared_ptr< file_collector_repository > const& repo, filesystem::path const& target_dir, uintmax_t max_size, uintmax_t min_free_space, uintmax_t max_files); //! Destructor ~file_collector(); //! The function stores the specified file in the storage void store_file(filesystem::path const& file_name); //! Scans the target directory for the files that have already been stored uintmax_t scan_for_files( file::scan_method method, filesystem::path const& pattern, unsigned int* counter); //! The function updates storage restrictions void update(uintmax_t max_size, uintmax_t min_free_space, uintmax_t max_files); //! The function checks if the directory is governed by this collector bool is_governed(filesystem::path const& dir) const { return filesystem::equivalent(m_StorageDir, dir); } private: //! Makes relative path absolute with respect to the base path filesystem::path make_absolute(filesystem::path const& p) { return filesystem::absolute(p, m_BasePath); } //! Acquires file name string from the path static path_string_type filename_string(filesystem::path const& p) { return p.filename().string< path_string_type >(); } }; //! The singleton of the list of file collectors class file_collector_repository : public log::aux::lazy_singleton< file_collector_repository, shared_ptr< file_collector_repository > > { private: //! Base type typedef log::aux::lazy_singleton< file_collector_repository, shared_ptr< file_collector_repository > > base_type; #if !defined(BOOST_LOG_BROKEN_FRIEND_TEMPLATE_SPECIALIZATIONS) friend class log::aux::lazy_singleton< file_collector_repository, shared_ptr< file_collector_repository > >; #else friend class base_type; #endif //! The type of the list of collectors typedef intrusive::list< file_collector, intrusive::base_hook< file_collector_hook > > file_collectors; private: #if !defined(BOOST_LOG_NO_THREADS) //! Synchronization mutex mutex m_Mutex; #endif // !defined(BOOST_LOG_NO_THREADS) //! The list of file collectors file_collectors m_Collectors; public: //! Finds or creates a file collector shared_ptr< file::collector > get_collector( filesystem::path const& target_dir, uintmax_t max_size, uintmax_t min_free_space, uintmax_t max_files); //! Removes the file collector from the list void remove_collector(file_collector* p); private: //! Initializes the singleton instance static void init_instance() { base_type::get_instance() = boost::make_shared< file_collector_repository >(); } }; //! Constructor file_collector::file_collector( shared_ptr< file_collector_repository > const& repo, filesystem::path const& target_dir, uintmax_t max_size, uintmax_t min_free_space, uintmax_t max_files ) : m_pRepository(repo), m_MaxSize(max_size), m_MinFreeSpace(min_free_space), m_MaxFiles(max_files), m_BasePath(filesystem::current_path()), m_TotalSize(0) { m_StorageDir = make_absolute(target_dir); filesystem::create_directories(m_StorageDir); } //! Destructor file_collector::~file_collector() { m_pRepository->remove_collector(this); } //! The function stores the specified file in the storage void file_collector::store_file(filesystem::path const& src_path) { // NOTE FOR THE FOLLOWING CODE: // Avoid using Boost.Filesystem functions that would call path::codecvt(). store_file() can be called // at process termination, and the global codecvt facet can already be destroyed at this point. // https://svn.boost.org/trac/boost/ticket/8642 // Let's construct the new file name file_info info; info.m_TimeStamp = filesystem::last_write_time(src_path); info.m_Size = filesystem::file_size(src_path); filesystem::path file_name_path = src_path.filename(); path_string_type file_name = file_name_path.native(); info.m_Path = m_StorageDir / file_name_path; // Check if the file is already in the target directory filesystem::path src_dir = src_path.has_parent_path() ? filesystem::system_complete(src_path.parent_path()) : m_BasePath; const bool is_in_target_dir = filesystem::equivalent(src_dir, m_StorageDir); if (!is_in_target_dir) { if (filesystem::exists(info.m_Path)) { // If the file already exists, try to mangle the file name // to ensure there's no conflict. I'll need to make this customizable some day. file_counter_formatter formatter(file_name.size(), 5); unsigned int n = 0; while (true) { path_string_type alt_file_name = formatter(file_name, n); info.m_Path = m_StorageDir / filesystem::path(alt_file_name); if (!filesystem::exists(info.m_Path)) break; if (BOOST_UNLIKELY(n == (std::numeric_limits< unsigned int >::max)())) { BOOST_THROW_EXCEPTION(filesystem_error( "Target file exists and an unused fallback file name could not be found", info.m_Path, system::error_code(system::errc::io_error, system::generic_category()))); } ++n; } } // The directory should have been created in constructor, but just in case it got deleted since then... filesystem::create_directories(m_StorageDir); } BOOST_LOG_EXPR_IF_MT(lock_guard< mutex > lock(m_Mutex);) file_list::iterator it = m_Files.begin(); const file_list::iterator end = m_Files.end(); if (is_in_target_dir) { // If the sink writes log file into the target dir (is_in_target_dir == true), it is possible that after scanning // an old file entry refers to the file that is picked up by the sink for writing. Later on, the sink attempts // to store the file in the storage. At best, this would result in duplicate file entries. At worst, if the storage // limits trigger a deletion and this file get deleted, we may have an entry that refers to no actual file. In any case, // the total size of files in the storage will be incorrect. Here we work around this problem and simply remove // the old file entry without removing the file. The entry will be re-added to the list later. while (it != end) { system::error_code ec; if (filesystem::equivalent(it->m_Path, info.m_Path, ec)) { m_TotalSize -= it->m_Size; m_Files.erase(it); break; } else { ++it; } } it = m_Files.begin(); } // Check if an old file should be erased uintmax_t free_space = m_MinFreeSpace ? filesystem::space(m_StorageDir).available : static_cast< uintmax_t >(0); while (it != end && (m_TotalSize + info.m_Size > m_MaxSize || (m_MinFreeSpace && m_MinFreeSpace > free_space) || m_MaxFiles <= m_Files.size())) { file_info& old_info = *it; system::error_code ec; filesystem::file_status status = filesystem::status(old_info.m_Path, ec); if (status.type() == filesystem::regular_file) { try { filesystem::remove(old_info.m_Path); // Free space has to be queried as it may not increase equally // to the erased file size on compressed filesystems if (m_MinFreeSpace) free_space = filesystem::space(m_StorageDir).available; m_TotalSize -= old_info.m_Size; m_Files.erase(it++); } catch (system::system_error&) { // Can't erase the file. Maybe it's locked? Never mind... ++it; } } else { // If it's not a file or is absent, just remove it from the list m_TotalSize -= old_info.m_Size; m_Files.erase(it++); } } if (!is_in_target_dir) { // Move/rename the file to the target storage move_file(src_path, info.m_Path); } m_Files.push_back(info); m_TotalSize += info.m_Size; } //! Scans the target directory for the files that have already been stored uintmax_t file_collector::scan_for_files( file::scan_method method, filesystem::path const& pattern, unsigned int* counter) { uintmax_t file_count = 0; if (method != file::no_scan) { filesystem::path dir = m_StorageDir; path_string_type mask; if (method == file::scan_matching) { mask = filename_string(pattern); if (pattern.has_parent_path()) dir = make_absolute(pattern.parent_path()); } else { counter = NULL; } system::error_code ec; filesystem::file_status status = filesystem::status(dir, ec); if (status.type() == filesystem::directory_file) { BOOST_LOG_EXPR_IF_MT(lock_guard< mutex > lock(m_Mutex);) if (counter) *counter = 0; file_list files; filesystem::directory_iterator it(dir), end; uintmax_t total_size = 0; for (; it != end; ++it) { filesystem::directory_entry const& dir_entry = *it; file_info info; info.m_Path = dir_entry.path(); status = dir_entry.status(ec); if (status.type() == filesystem::regular_file) { // Check that there are no duplicates in the resulting list struct local { static bool equivalent(filesystem::path const& left, file_info const& right) { return filesystem::equivalent(left, right.m_Path); } }; if (std::find_if(m_Files.begin(), m_Files.end(), boost::bind(&local::equivalent, boost::cref(info.m_Path), boost::placeholders::_1)) == m_Files.end()) { // Check that the file name matches the pattern unsigned int file_number = 0; bool file_number_parsed = false; if (method != file::scan_matching || match_pattern(filename_string(info.m_Path), mask, file_number, file_number_parsed)) { info.m_Size = filesystem::file_size(info.m_Path); total_size += info.m_Size; info.m_TimeStamp = filesystem::last_write_time(info.m_Path); files.push_back(info); ++file_count; // Test that the file_number >= *counter accounting for the integer overflow if (file_number_parsed && counter != NULL && (file_number - *counter) < ((~0u) ^ ((~0u) >> 1))) *counter = file_number + 1u; } } } } // Sort files chronologically m_Files.splice(m_Files.end(), files); m_TotalSize += total_size; m_Files.sort(boost::bind(&file_info::m_TimeStamp, boost::placeholders::_1) < boost::bind(&file_info::m_TimeStamp, boost::placeholders::_2)); } } return file_count; } //! The function updates storage restrictions void file_collector::update(uintmax_t max_size, uintmax_t min_free_space, uintmax_t max_files) { BOOST_LOG_EXPR_IF_MT(lock_guard< mutex > lock(m_Mutex);) m_MaxSize = (std::min)(m_MaxSize, max_size); m_MinFreeSpace = (std::max)(m_MinFreeSpace, min_free_space); m_MaxFiles = (std::min)(m_MaxFiles, max_files); } //! Finds or creates a file collector shared_ptr< file::collector > file_collector_repository::get_collector( filesystem::path const& target_dir, uintmax_t max_size, uintmax_t min_free_space, uintmax_t max_files) { BOOST_LOG_EXPR_IF_MT(lock_guard< mutex > lock(m_Mutex);) file_collectors::iterator it = std::find_if(m_Collectors.begin(), m_Collectors.end(), boost::bind(&file_collector::is_governed, boost::placeholders::_1, boost::cref(target_dir))); shared_ptr< file_collector > p; if (it != m_Collectors.end()) try { // This may throw if the collector is being currently destroyed p = it->shared_from_this(); p->update(max_size, min_free_space, max_files); } catch (bad_weak_ptr&) { } if (!p) { p = boost::make_shared< file_collector >( file_collector_repository::get(), target_dir, max_size, min_free_space, max_files); m_Collectors.push_back(*p); } return p; } //! Removes the file collector from the list void file_collector_repository::remove_collector(file_collector* p) { BOOST_LOG_EXPR_IF_MT(lock_guard< mutex > lock(m_Mutex);) m_Collectors.erase(m_Collectors.iterator_to(*p)); } //! Checks if the time point is valid void check_time_point_validity(unsigned char hour, unsigned char minute, unsigned char second) { if (BOOST_UNLIKELY(hour >= 24)) { std::ostringstream strm; strm << "Time point hours value is out of range: " << static_cast< unsigned int >(hour); BOOST_THROW_EXCEPTION(std::out_of_range(strm.str())); } if (BOOST_UNLIKELY(minute >= 60)) { std::ostringstream strm; strm << "Time point minutes value is out of range: " << static_cast< unsigned int >(minute); BOOST_THROW_EXCEPTION(std::out_of_range(strm.str())); } if (BOOST_UNLIKELY(second >= 60)) { std::ostringstream strm; strm << "Time point seconds value is out of range: " << static_cast< unsigned int >(second); BOOST_THROW_EXCEPTION(std::out_of_range(strm.str())); } } } // namespace namespace file { namespace aux { //! Creates and returns a file collector with the specified parameters BOOST_LOG_API shared_ptr< collector > make_collector( filesystem::path const& target_dir, uintmax_t max_size, uintmax_t min_free_space, uintmax_t max_files) { return file_collector_repository::get()->get_collector(target_dir, max_size, min_free_space, max_files); } } // namespace aux //! Creates a rotation time point of every day at the specified time BOOST_LOG_API rotation_at_time_point::rotation_at_time_point( unsigned char hour, unsigned char minute, unsigned char second ) : m_Day(0), m_DayKind(not_specified), m_Hour(hour), m_Minute(minute), m_Second(second), m_Previous(date_time::not_a_date_time) { check_time_point_validity(hour, minute, second); } //! Creates a rotation time point of each specified weekday at the specified time BOOST_LOG_API rotation_at_time_point::rotation_at_time_point( date_time::weekdays wday, unsigned char hour, unsigned char minute, unsigned char second ) : m_Day(static_cast< unsigned char >(wday)), m_DayKind(weekday), m_Hour(hour), m_Minute(minute), m_Second(second), m_Previous(date_time::not_a_date_time) { check_time_point_validity(hour, minute, second); } //! Creates a rotation time point of each specified day of month at the specified time BOOST_LOG_API rotation_at_time_point::rotation_at_time_point( gregorian::greg_day mday, unsigned char hour, unsigned char minute, unsigned char second ) : m_Day(static_cast< unsigned char >(mday.as_number())), m_DayKind(monthday), m_Hour(hour), m_Minute(minute), m_Second(second), m_Previous(date_time::not_a_date_time) { check_time_point_validity(hour, minute, second); } //! Checks if it's time to rotate the file BOOST_LOG_API bool rotation_at_time_point::operator()() const { bool result = false; posix_time::time_duration rotation_time( static_cast< posix_time::time_duration::hour_type >(m_Hour), static_cast< posix_time::time_duration::min_type >(m_Minute), static_cast< posix_time::time_duration::sec_type >(m_Second)); posix_time::ptime now = posix_time::second_clock::local_time(); if (m_Previous.is_special()) { m_Previous = now; return false; } const bool time_of_day_passed = rotation_time.total_seconds() <= m_Previous.time_of_day().total_seconds(); switch (static_cast< day_kind >(m_DayKind)) { case not_specified: { // The rotation takes place every day at the specified time gregorian::date previous_date = m_Previous.date(); if (time_of_day_passed) previous_date += gregorian::days(1); posix_time::ptime next(previous_date, rotation_time); result = (now >= next); } break; case weekday: { // The rotation takes place on the specified week day at the specified time gregorian::date previous_date = m_Previous.date(), next_date = previous_date; int weekday = m_Day, previous_weekday = static_cast< int >(previous_date.day_of_week().as_number()); next_date += gregorian::days(weekday - previous_weekday); if (weekday < previous_weekday || (weekday == previous_weekday && time_of_day_passed)) { next_date += gregorian::weeks(1); } posix_time::ptime next(next_date, rotation_time); result = (now >= next); } break; case monthday: { // The rotation takes place on the specified day of month at the specified time gregorian::date previous_date = m_Previous.date(); gregorian::date::day_type monthday = static_cast< gregorian::date::day_type >(m_Day), previous_monthday = previous_date.day(); gregorian::date next_date(previous_date.year(), previous_date.month(), monthday); if (monthday < previous_monthday || (monthday == previous_monthday && time_of_day_passed)) { next_date += gregorian::months(1); } posix_time::ptime next(next_date, rotation_time); result = (now >= next); } break; default: break; } if (result) m_Previous = now; return result; } //! Checks if it's time to rotate the file BOOST_LOG_API bool rotation_at_time_interval::operator()() const { bool result = false; posix_time::ptime now = posix_time::second_clock::universal_time(); if (m_Previous.is_special()) { m_Previous = now; return false; } result = (now - m_Previous) >= m_Interval; if (result) m_Previous = now; return result; } } // namespace file //////////////////////////////////////////////////////////////////////////////// // File sink backend implementation //////////////////////////////////////////////////////////////////////////////// //! Sink implementation data struct text_file_backend::implementation { //! File open mode std::ios_base::openmode m_FileOpenMode; //! File name pattern filesystem::path m_FileNamePattern; //! Directory to store files in filesystem::path m_StorageDir; //! File name generator (according to m_FileNamePattern) boost::log::aux::light_function< path_string_type (unsigned int) > m_FileNameGenerator; //! Target file name pattern filesystem::path m_TargetFileNamePattern; //! Target directory to store files in filesystem::path m_TargetStorageDir; //! Target file name generator (according to m_TargetFileNamePattern) boost::log::aux::light_function< path_string_type (unsigned int) > m_TargetFileNameGenerator; //! Stored files counter unsigned int m_FileCounter; //! Current file name filesystem::path m_FileName; //! File stream filesystem::ofstream m_File; //! Characters written uintmax_t m_CharactersWritten; //! File collector functional object shared_ptr< file::collector > m_pFileCollector; //! File open handler open_handler_type m_OpenHandler; //! File close handler close_handler_type m_CloseHandler; //! The maximum temp file size, in characters written to the stream uintmax_t m_FileRotationSize; //! Time-based rotation predicate time_based_rotation_predicate m_TimeBasedRotation; //! Indicates whether to append a trailing newline after every log record auto_newline_mode m_AutoNewlineMode; //! The flag shows if every written record should be flushed bool m_AutoFlush; //! The flag indicates whether the final rotation should be performed bool m_FinalRotationEnabled; implementation(uintmax_t rotation_size, auto_newline_mode auto_newline, bool auto_flush, bool enable_final_rotation) : m_FileOpenMode(std::ios_base::trunc | std::ios_base::out), m_FileCounter(0), m_CharactersWritten(0), m_FileRotationSize(rotation_size), m_AutoNewlineMode(auto_newline), m_AutoFlush(auto_flush), m_FinalRotationEnabled(enable_final_rotation) { } }; //! Constructor. No streams attached to the constructed backend, auto flush feature disabled. BOOST_LOG_API text_file_backend::text_file_backend() { construct(log::aux::empty_arg_list()); } //! Destructor BOOST_LOG_API text_file_backend::~text_file_backend() { try { // Attempt to put the temporary file into storage if (m_pImpl->m_FinalRotationEnabled && m_pImpl->m_File.is_open() && m_pImpl->m_CharactersWritten > 0) rotate_file(); } catch (...) { } delete m_pImpl; } //! Constructor implementation BOOST_LOG_API void text_file_backend::construct( filesystem::path const& pattern, filesystem::path const& target_file_name, std::ios_base::openmode mode, uintmax_t rotation_size, time_based_rotation_predicate const& time_based_rotation, auto_newline_mode auto_newline, bool auto_flush, bool enable_final_rotation) { m_pImpl = new implementation(rotation_size, auto_newline, auto_flush, enable_final_rotation); set_file_name_pattern_internal(pattern); set_target_file_name_pattern_internal(target_file_name); set_time_based_rotation(time_based_rotation); set_open_mode(mode); } //! The method sets maximum file size. BOOST_LOG_API void text_file_backend::set_rotation_size(uintmax_t size) { m_pImpl->m_FileRotationSize = size; } //! The method sets the maximum time interval between file rotations. BOOST_LOG_API void text_file_backend::set_time_based_rotation(time_based_rotation_predicate const& predicate) { m_pImpl->m_TimeBasedRotation = predicate; } //! The method allows to enable or disable log file rotation on sink destruction. BOOST_LOG_API void text_file_backend::enable_final_rotation(bool enable) { m_pImpl->m_FinalRotationEnabled = enable; } //! Sets the flag to automatically flush write buffers of the file being written after each log record. BOOST_LOG_API void text_file_backend::auto_flush(bool enable) { m_pImpl->m_AutoFlush = enable; } //! Selects whether a trailing newline should be automatically inserted after every log record. BOOST_LOG_API void text_file_backend::set_auto_newline_mode(auto_newline_mode mode) { m_pImpl->m_AutoNewlineMode = mode; } //! The method writes the message to the sink BOOST_LOG_API void text_file_backend::consume(record_view const& rec, string_type const& formatted_message) { typedef file_char_traits< string_type::value_type > traits_t; filesystem::path prev_file_name; bool use_prev_file_name = false; if (BOOST_UNLIKELY(!m_pImpl->m_File.good())) { // The file stream is not operational. One possible reason is that there is no more free space // on the file system. In this case it is possible that this log record will fail to be written as well, // leaving the newly creted file empty. Eventually this results in lots of empty log files. // We should take precautions to avoid this. https://svn.boost.org/trac/boost/ticket/11016 prev_file_name = m_pImpl->m_FileName; close_file(); system::error_code ec; uintmax_t size = filesystem::file_size(prev_file_name, ec); if (!!ec || size == 0) { // To reuse the empty file avoid re-generating the new file name later use_prev_file_name = true; } else if (!!m_pImpl->m_pFileCollector) { // Complete file rotation m_pImpl->m_pFileCollector->store_file(prev_file_name); } } else if ( m_pImpl->m_File.is_open() && ( m_pImpl->m_CharactersWritten + formatted_message.size() >= m_pImpl->m_FileRotationSize || (!m_pImpl->m_TimeBasedRotation.empty() && m_pImpl->m_TimeBasedRotation()) ) ) { rotate_file(); } if (!m_pImpl->m_File.is_open()) { filesystem::path new_file_name; if (!use_prev_file_name) new_file_name = m_pImpl->m_StorageDir / m_pImpl->m_FileNameGenerator(m_pImpl->m_FileCounter++); else prev_file_name.swap(new_file_name); filesystem::create_directories(new_file_name.parent_path()); m_pImpl->m_File.open(new_file_name, m_pImpl->m_FileOpenMode); if (BOOST_UNLIKELY(!m_pImpl->m_File.is_open())) { BOOST_THROW_EXCEPTION(filesystem_error( "Failed to open file for writing", new_file_name, system::error_code(system::errc::io_error, system::generic_category()))); } m_pImpl->m_FileName.swap(new_file_name); if (!m_pImpl->m_OpenHandler.empty()) m_pImpl->m_OpenHandler(m_pImpl->m_File); m_pImpl->m_CharactersWritten = static_cast< std::streamoff >(m_pImpl->m_File.tellp()); } m_pImpl->m_File.write(formatted_message.data(), static_cast< std::streamsize >(formatted_message.size())); m_pImpl->m_CharactersWritten += formatted_message.size(); if (m_pImpl->m_AutoNewlineMode != disabled_auto_newline) { if (m_pImpl->m_AutoNewlineMode == always_insert || formatted_message.empty() || *formatted_message.rbegin() != traits_t::newline) { m_pImpl->m_File.put(traits_t::newline); ++m_pImpl->m_CharactersWritten; } } if (m_pImpl->m_AutoFlush) m_pImpl->m_File.flush(); } //! The method flushes the currently open log file BOOST_LOG_API void text_file_backend::flush() { if (m_pImpl->m_File.is_open()) m_pImpl->m_File.flush(); } //! The method sets file name pattern BOOST_LOG_API void text_file_backend::set_file_name_pattern_internal(filesystem::path const& pattern) { typedef file_char_traits< path_char_type > traits_t; parse_file_name_pattern ( !pattern.empty() ? pattern : filesystem::path(traits_t::default_file_name_pattern()), m_pImpl->m_StorageDir, m_pImpl->m_FileNamePattern, m_pImpl->m_FileNameGenerator ); } //! The method sets target file name pattern BOOST_LOG_API void text_file_backend::set_target_file_name_pattern_internal(filesystem::path const& pattern) { if (!pattern.empty()) { parse_file_name_pattern(pattern, m_pImpl->m_TargetStorageDir, m_pImpl->m_TargetFileNamePattern, m_pImpl->m_TargetFileNameGenerator); } else { m_pImpl->m_TargetStorageDir.clear(); m_pImpl->m_TargetFileNamePattern.clear(); m_pImpl->m_TargetFileNameGenerator.clear(); } } //! Closes the currently open file void text_file_backend::close_file() { if (m_pImpl->m_File.is_open()) { if (!m_pImpl->m_CloseHandler.empty()) { // Rationale: We should call the close handler even if the stream is !good() because // writing the footer may not be the only thing the handler does. However, there is // a chance that the file had become writable since the last failure (e.g. there was // no space left to write the last record, but it got freed since then), so if the handler // attempts to write a footer it may succeed now. For this reason we clear the stream state // and let the handler have a try. m_pImpl->m_File.clear(); m_pImpl->m_CloseHandler(m_pImpl->m_File); } m_pImpl->m_File.close(); } m_pImpl->m_File.clear(); m_pImpl->m_CharactersWritten = 0; m_pImpl->m_FileName.clear(); } //! The method rotates the file BOOST_LOG_API void text_file_backend::rotate_file() { filesystem::path prev_file_name = m_pImpl->m_FileName; close_file(); // Check if the file has been created in the first place system::error_code ec; filesystem::file_status status = filesystem::status(prev_file_name, ec); if (status.type() == filesystem::regular_file) { if (!!m_pImpl->m_TargetFileNameGenerator) { filesystem::path new_file_name = m_pImpl->m_TargetStorageDir / m_pImpl->m_TargetFileNameGenerator(m_pImpl->m_FileCounter); if (new_file_name != prev_file_name) { filesystem::create_directories(new_file_name.parent_path()); move_file(prev_file_name, new_file_name); prev_file_name.swap(new_file_name); } } if (!!m_pImpl->m_pFileCollector) m_pImpl->m_pFileCollector->store_file(prev_file_name); } } //! The method sets the file open mode BOOST_LOG_API void text_file_backend::set_open_mode(std::ios_base::openmode mode) { mode |= std::ios_base::out; mode &= ~std::ios_base::in; if ((mode & (std::ios_base::trunc | std::ios_base::app)) == 0) mode |= std::ios_base::trunc; m_pImpl->m_FileOpenMode = mode; } //! The method sets file collector BOOST_LOG_API void text_file_backend::set_file_collector(shared_ptr< file::collector > const& collector) { m_pImpl->m_pFileCollector = collector; } //! The method sets file open handler BOOST_LOG_API void text_file_backend::set_open_handler(open_handler_type const& handler) { m_pImpl->m_OpenHandler = handler; } //! The method sets file close handler BOOST_LOG_API void text_file_backend::set_close_handler(close_handler_type const& handler) { m_pImpl->m_CloseHandler = handler; } //! The method returns name of the currently open log file. If no file is open, returns an empty path. BOOST_LOG_API filesystem::path text_file_backend::get_current_file_name() const { return m_pImpl->m_FileName; } //! Performs scanning of the target directory for log files BOOST_LOG_API uintmax_t text_file_backend::scan_for_files(file::scan_method method, bool update_counter) { if (BOOST_LIKELY(!!m_pImpl->m_pFileCollector)) { unsigned int* counter = update_counter ? &m_pImpl->m_FileCounter : static_cast< unsigned int* >(NULL); return m_pImpl->m_pFileCollector->scan_for_files ( method, m_pImpl->m_TargetFileNamePattern.empty() ? m_pImpl->m_FileNamePattern : m_pImpl->m_TargetFileNamePattern, counter ); } else { BOOST_LOG_THROW_DESCR(setup_error, "File collector is not set"); } } } // namespace sinks BOOST_LOG_CLOSE_NAMESPACE // namespace log } // namespace boost #include <boost/log/detail/footer.hpp>
// Copyright 2013 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/net/pref_proxy_config_tracker.h" PrefProxyConfigTracker::PrefProxyConfigTracker() { } PrefProxyConfigTracker::~PrefProxyConfigTracker() { }
#include "tic_tac_toe_4.h" #include "tic_tac_toe.h" /* class function check_column_win Win by column if and return true if (each column index) 0, 1, 2, 3 4, 5, 6, 7 8, 9, 10, 11 12,13,14, 15 else false */ /* class function check_row_win Win by row if 0, 1, 2, 3 are equal 4, 5, 6, 7 are equal 8, 9, 10, 11 are equal 12,13,14, 15 are equal */ /* class function check_diagonal_win Win diagonally 0, 1, 2, 3 4, 5, 6, 7 8, 9, 10, 11 12,13,14, 15 */ bool TicTacToe4::check_column_win() { if (pegs[0] == "X" && pegs[4] == "X" && pegs[8] == "X" && pegs[12] == "X") { return true; } else if (pegs[1] == "X" && pegs[5] == "X" && pegs[9] == "X" && pegs[13] == "X") { return true; } else if (pegs[2] == "X" && pegs[6] == "X" && pegs[10] == "X" && pegs[14] == "X") { return true; } else if (pegs[3] == "X" && pegs[7] == "X" && pegs[11] == "X" && pegs[15] == "X") { return true; } if (pegs[0] == "O" && pegs[4] == "O" && pegs[8] == "O" && pegs[12] == "O" ) { return true; } else if (pegs[1] == "O" && pegs[5] == "O" && pegs[9] == "O" && pegs[13] == "O") { return true; } else if (pegs[2] == "O" && pegs[6] == "O" && pegs[10] == "O" && pegs[14] == "O") { return true; } else if (pegs[3] == "O" && pegs[7] == "O" && pegs[11] == "O" && pegs[15] == "O") { return true; } return false; } bool TicTacToe4::check_row_win() { if (pegs[0] == "X" && pegs[1] == "X" && pegs[2] == "X" && pegs[3] == "X") { return true; } else if (pegs[4] == "X" && pegs[5] == "X" && pegs[6] == "X" && pegs[7] == "X") { return true; } else if (pegs[8] == "X" && pegs[9] == "X" && pegs[10] == "X" && pegs[11] == "X") { return true; } else if (pegs[12] == "X" && pegs[13] == "X" && pegs[14] == "X" && pegs[15] == "X") { return true; } if (pegs[0] == "O" && pegs[1] == "O" && pegs[2] == "O" && pegs[3] == "O") { return true; } else if (pegs[4] == "O" && pegs[5] == "O" && pegs[6] == "O" && pegs[7] == "O") { return true; } else if (pegs[8] == "O" && pegs[9] == "O" && pegs[10] == "O" && pegs[11] == "O") { return true; } else if (pegs[12] == "O" && pegs[13] == "O" && pegs[14] == "O" && pegs[15] == "O") { return true; } return false; } bool TicTacToe4::check_diagonal_win() { if (pegs[0] == "X" && pegs[5] == "X" && pegs[10] == "X" && pegs[15] == "X") { return true; } else if (pegs[3] == "X" && pegs[6] == "X" && pegs[9] == "X" && pegs[12] == "X") { return true; } if (pegs[0] == "O" && pegs[5] == "O" && pegs[10] == "O" && pegs[15] == "O") { return true; } else if (pegs[3] == "O" && pegs[6] == "O" && pegs[9] == "O" && pegs[12] == "O") { return true; } return false; }
/* Author: Masaki Murooka */ #include <gtest/gtest.h> #include <cmath> #include <fstream> #include <functional> #include <iostream> #include <limits> #include <ros/ros.h> #include <visualization_msgs/MarkerArray.h> #include <std_srvs/Empty.h> #include <nmpc_ddp/DDP.h> /** \brief DDP problem for cart-pole. State is [pos, theta, vel, omega]. Input is [force]. Running cost is sum of the respective quadratic terms of state and input. Terminal cost is quadratic term of state. */ class DDPProblemCartPole : public nmpc_ddp::DDPProblem<4, 1> { public: struct Param { Param() {} double cart_mass = 1.0; // [kg] double pole_mass = 0.5; // [kg] double pole_length = 2.0; // [m] }; struct CostWeight { CostWeight() { running_x << 0.1, 1.0, 0.01, 0.1; running_u << 0.001; terminal_x << 0.1, 1.0, 0.01, 0.1; } StateDimVector running_x; InputDimVector running_u; StateDimVector terminal_x; }; public: DDPProblemCartPole(double dt, const std::function<double(double)> & ref_pos_func, const Param & param = Param(), const CostWeight & cost_weight = CostWeight()) : DDPProblem(dt), ref_pos_func_(ref_pos_func), param_(param), cost_weight_(cost_weight) { } virtual StateDimVector stateEq(double t, const StateDimVector & x, const InputDimVector & u) const override { double pos = x[0]; double theta = x[1]; double vel = x[2]; double omega = x[3]; double f = u[0]; double m1 = param_.cart_mass; double m2 = param_.pole_mass; double l = param_.pole_length; double sin_theta = std::sin(theta); double cos_theta = std::cos(theta); double omega2 = std::pow(omega, 2); double denom = m1 + m2 * std::pow(sin_theta, 2); StateDimVector x_dot; // clang-format off x_dot[0] = vel; x_dot[1] = omega; x_dot[2] = (f - m2 * l * omega2 * sin_theta + m2 * g_ * sin_theta * cos_theta) / denom; x_dot[3] = (f * cos_theta - m2 * l * omega2 * sin_theta * cos_theta + g_ * (m1 + m2) * sin_theta) / (l * denom); // clang-format on return x + dt_ * x_dot; } virtual double runningCost(double t, const StateDimVector & x, const InputDimVector & u) const override { StateDimVector ref_x; ref_x << ref_pos_func_(t), 0, 0, 0; return 0.5 * cost_weight_.running_x.dot((x - ref_x).cwiseAbs2()) + 0.5 * cost_weight_.running_u.dot(u.cwiseAbs2()); } virtual double terminalCost(double t, const StateDimVector & x) const override { StateDimVector ref_x; ref_x << ref_pos_func_(t), 0, 0, 0; return 0.5 * cost_weight_.terminal_x.dot((x - ref_x).cwiseAbs2()); } virtual void calcStatEqDeriv(double t, const StateDimVector & x, const InputDimVector & u, Eigen::Ref<StateStateDimMatrix> state_eq_deriv_x, Eigen::Ref<StateInputDimMatrix> state_eq_deriv_u) const override { double pos = x[0]; double theta = x[1]; double vel = x[2]; double omega = x[3]; double f = u[0]; double m1 = param_.cart_mass; double m2 = param_.pole_mass; double l = param_.pole_length; double sin_theta = std::sin(theta); double cos_theta = std::cos(theta); double omega2 = std::pow(omega, 2); double denom = m1 + m2 * std::pow(sin_theta, 2); state_eq_deriv_x.setZero(); // clang-format off state_eq_deriv_x(0, 2) = 1; state_eq_deriv_x(1, 3) = 1; state_eq_deriv_x(2, 1) = ((-1 * m2 * l * omega2 * cos_theta + m2 * g_ * (1 - 2 * std::pow(sin_theta, 2))) * denom + -1 * (f - m2 * l * omega2 * sin_theta + m2 * g_ * sin_theta * cos_theta) * (2 * m2 * sin_theta * cos_theta)) / std::pow(denom, 2); state_eq_deriv_x(2, 3) = (-2 * m2 * l * omega * sin_theta) / denom; state_eq_deriv_x(3, 1) = ((-1 * f * sin_theta + -1 * m2 * l * omega2 * (1 - 2 * std::pow(sin_theta, 2)) + g_ * (m1 + m2) * cos_theta) * denom + -1 * (f * cos_theta - m2 * l * omega2 * sin_theta * cos_theta + g_ * (m1 + m2) * sin_theta) * (2 * m2 * sin_theta * cos_theta)) / (l * std::pow(denom, 2)); state_eq_deriv_x(3, 3) = (-2 * m2 * l * omega * sin_theta * cos_theta) / (l * denom); // clang-format on state_eq_deriv_x *= dt_; state_eq_deriv_x += StateStateDimMatrix::Identity(); state_eq_deriv_u.setZero(); state_eq_deriv_u[2] = 1 / denom; state_eq_deriv_u[3] = cos_theta / (l * denom); state_eq_deriv_u *= dt_; } virtual void calcStatEqDeriv(double t, const StateDimVector & x, const InputDimVector & u, Eigen::Ref<StateStateDimMatrix> state_eq_deriv_x, Eigen::Ref<StateInputDimMatrix> state_eq_deriv_u, std::vector<StateStateDimMatrix> & state_eq_deriv_xx, std::vector<InputInputDimMatrix> & state_eq_deriv_uu, std::vector<StateInputDimMatrix> & state_eq_deriv_xu) const override { throw std::runtime_error("Second-order derivatives of state equation are not implemented."); } virtual void calcRunningCostDeriv(double t, const StateDimVector & x, const InputDimVector & u, Eigen::Ref<StateDimVector> running_cost_deriv_x, Eigen::Ref<InputDimVector> running_cost_deriv_u) const override { StateDimVector ref_x; ref_x << ref_pos_func_(t), 0, 0, 0; running_cost_deriv_x = cost_weight_.running_x.cwiseProduct(x - ref_x); running_cost_deriv_u = cost_weight_.running_u.cwiseProduct(u); } virtual void calcRunningCostDeriv(double t, const StateDimVector & x, const InputDimVector & u, Eigen::Ref<StateDimVector> running_cost_deriv_x, Eigen::Ref<InputDimVector> running_cost_deriv_u, Eigen::Ref<StateStateDimMatrix> running_cost_deriv_xx, Eigen::Ref<InputInputDimMatrix> running_cost_deriv_uu, Eigen::Ref<StateInputDimMatrix> running_cost_deriv_xu) const override { StateDimVector ref_x; ref_x << ref_pos_func_(t), 0, 0, 0; running_cost_deriv_x = cost_weight_.running_x.cwiseProduct(x - ref_x); running_cost_deriv_u = cost_weight_.running_u.cwiseProduct(u); running_cost_deriv_xx = cost_weight_.running_x.asDiagonal(); running_cost_deriv_uu = cost_weight_.running_u.asDiagonal(); running_cost_deriv_xu.setZero(); } virtual void calcTerminalCostDeriv(double t, const StateDimVector & x, Eigen::Ref<StateDimVector> terminal_cost_deriv_x) const override { StateDimVector ref_x; ref_x << ref_pos_func_(t), 0, 0, 0; terminal_cost_deriv_x = cost_weight_.terminal_x.cwiseProduct(x - ref_x); } virtual void calcTerminalCostDeriv(double t, const StateDimVector & x, Eigen::Ref<StateDimVector> terminal_cost_deriv_x, Eigen::Ref<StateStateDimMatrix> terminal_cost_deriv_xx) const override { StateDimVector ref_x; ref_x << ref_pos_func_(t), 0, 0, 0; terminal_cost_deriv_x = cost_weight_.terminal_x.cwiseProduct(x - ref_x); terminal_cost_deriv_xx = cost_weight_.terminal_x.asDiagonal(); } public: static constexpr double g_ = 9.80665; // [m/s^2] std::function<double(double)> ref_pos_func_; Param param_; CostWeight cost_weight_; }; // Global variables std::shared_ptr<nmpc_ddp::DDPSolver<4, 1>> ddp_solver = nullptr; double current_t = 0; DDPProblemCartPole::StateDimVector current_x = DDPProblemCartPole::StateDimVector::Zero(); DDPProblemCartPole::InputDimVector current_u = DDPProblemCartPole::InputDimVector::Zero(); std::vector<DDPProblemCartPole::InputDimVector> initial_u_list; double dist_t = 0; DDPProblemCartPole::InputDimVector dist_u = DDPProblemCartPole::InputDimVector::Zero(); double target_pos = std::numeric_limits<double>::quiet_NaN(); bool first_iter = true; void mpcTimerCallback(const ros::TimerEvent & event) { // Solve ddp_solver->solve(current_t, current_x, initial_u_list); current_u = ddp_solver->controlData().u_list[0]; initial_u_list = ddp_solver->controlData().u_list; // Dump if(first_iter) { first_iter = false; ddp_solver->dumpTraceDataList("/tmp/TestDDPCartPoleTraceData.txt"); } } bool distCallback(std_srvs::Empty::Request & req, std_srvs::Empty::Response & res, double dist_force) { dist_u << dist_force; dist_t = current_t + 0.5; // [sec] return true; } bool targetPosCallback(std_srvs::Empty::Request & req, std_srvs::Empty::Response & res, double pos) { target_pos = pos; return true; } void checkDerivatives(const std::shared_ptr<DDPProblemCartPole> & ddp_problem) { double t = 0; DDPProblemCartPole::StateDimVector x; x << 1.0, -2.0, 3.0, -4.0; DDPProblemCartPole::InputDimVector u; u << 10.0; DDPProblemCartPole::StateStateDimMatrix state_eq_deriv_x_analytical; DDPProblemCartPole::StateInputDimMatrix state_eq_deriv_u_analytical; ddp_problem->calcStatEqDeriv(t, x, u, state_eq_deriv_x_analytical, state_eq_deriv_u_analytical); DDPProblemCartPole::StateStateDimMatrix state_eq_deriv_x_numerical; DDPProblemCartPole::StateInputDimMatrix state_eq_deriv_u_numerical; constexpr double deriv_eps = 1e-6; for(int i = 0; i < ddp_problem->stateDim(); i++) { state_eq_deriv_x_numerical.col(i) = (ddp_problem->stateEq(t, x + deriv_eps * DDPProblemCartPole::StateDimVector::Unit(i), u) - ddp_problem->stateEq(t, x - deriv_eps * DDPProblemCartPole::StateDimVector::Unit(i), u)) / (2 * deriv_eps); } for(int i = 0; i < ddp_problem->inputDim(); i++) { state_eq_deriv_u_numerical.col(i) = (ddp_problem->stateEq(t, x, u + deriv_eps * DDPProblemCartPole::InputDimVector::Unit(i)) - ddp_problem->stateEq(t, x, u - deriv_eps * DDPProblemCartPole::InputDimVector::Unit(i))) / (2 * deriv_eps); } EXPECT_LT((state_eq_deriv_x_analytical - state_eq_deriv_x_numerical).norm(), 1e-6); EXPECT_LT((state_eq_deriv_u_analytical - state_eq_deriv_u_numerical).norm(), 1e-6); } visualization_msgs::MarkerArray makeMarkerArr(const DDPProblemCartPole::StateDimVector & x, const DDPProblemCartPole::InputDimVector & u, const std::shared_ptr<DDPProblemCartPole> & ddp_problem) { std_msgs::Header header_msg; header_msg.frame_id = "world"; header_msg.stamp = ros::Time::now(); // Instantiate marker array visualization_msgs::MarkerArray marker_arr_msg; // Delete marker visualization_msgs::Marker del_marker; del_marker.action = visualization_msgs::Marker::DELETEALL; del_marker.header = header_msg; del_marker.id = marker_arr_msg.markers.size(); marker_arr_msg.markers.push_back(del_marker); // Cart marker visualization_msgs::Marker cart_marker; cart_marker.header = header_msg; cart_marker.ns = "cart"; cart_marker.id = marker_arr_msg.markers.size(); cart_marker.type = visualization_msgs::Marker::CUBE; cart_marker.color.r = 0; cart_marker.color.g = 1; cart_marker.color.b = 0; cart_marker.color.a = 1; cart_marker.scale.x = 1.0; cart_marker.scale.y = 0.6; cart_marker.scale.z = 0.12; cart_marker.pose.position.x = x[0]; cart_marker.pose.position.y = 0; cart_marker.pose.position.z = 0; cart_marker.pose.orientation.w = 1.0; marker_arr_msg.markers.push_back(cart_marker); // Mass marker visualization_msgs::Marker mass_marker; mass_marker.header = header_msg; mass_marker.ns = "mass"; cart_marker.id = marker_arr_msg.markers.size(); mass_marker.type = visualization_msgs::Marker::CYLINDER; mass_marker.color.r = 0; mass_marker.color.g = 0; mass_marker.color.b = 1; mass_marker.color.a = 1; mass_marker.scale.x = 0.6; mass_marker.scale.y = 0.6; mass_marker.scale.z = 0.1; mass_marker.pose.position.x = x[0] + ddp_problem->param_.pole_length * -1 * std::sin(x[1]); mass_marker.pose.position.y = ddp_problem->param_.pole_length * std::cos(x[1]); mass_marker.pose.position.z = 2.0; mass_marker.pose.orientation.w = 1.0; marker_arr_msg.markers.push_back(mass_marker); // Pole marker visualization_msgs::Marker pole_marker; pole_marker.header = header_msg; pole_marker.ns = "pole"; pole_marker.id = marker_arr_msg.markers.size(); pole_marker.type = visualization_msgs::Marker::LINE_LIST; pole_marker.color.r = 0; pole_marker.color.g = 0; pole_marker.color.b = 0; pole_marker.color.a = 1; pole_marker.scale.x = 0.2; pole_marker.pose.position.z = 1.0; pole_marker.pose.orientation.w = 1.0; pole_marker.points.resize(2); pole_marker.points[0].x = cart_marker.pose.position.x; pole_marker.points[0].y = cart_marker.pose.position.y; pole_marker.points[1].x = mass_marker.pose.position.x; pole_marker.points[1].y = mass_marker.pose.position.y; marker_arr_msg.markers.push_back(pole_marker); // Force marker constexpr double force_scale = 0.04; constexpr double force_thre = 1.0; // [N] if(std::abs(u[0]) > force_thre) { visualization_msgs::Marker force_marker; force_marker.header = header_msg; force_marker.ns = "force"; force_marker.id = marker_arr_msg.markers.size(); force_marker.type = visualization_msgs::Marker::ARROW; force_marker.color.r = 1; force_marker.color.g = 0; force_marker.color.b = 0; force_marker.color.a = 1; force_marker.scale.x = 0.2; force_marker.scale.y = 0.4; force_marker.scale.z = 0.2; force_marker.pose.position.z = 3.0; force_marker.pose.orientation.w = 1.0; force_marker.points.resize(2); force_marker.points[0].x = cart_marker.pose.position.x; force_marker.points[0].y = cart_marker.pose.position.y; force_marker.points[1].x = cart_marker.pose.position.x + force_scale * u[0]; force_marker.points[1].y = cart_marker.pose.position.y; marker_arr_msg.markers.push_back(force_marker); } // Disturbance marker if(std::abs(dist_u[0]) > force_thre) { visualization_msgs::Marker dist_marker; dist_marker.header = header_msg; dist_marker.ns = "disturbance"; dist_marker.id = marker_arr_msg.markers.size(); dist_marker.type = visualization_msgs::Marker::ARROW; dist_marker.color.r = 1; dist_marker.color.g = 1; dist_marker.color.b = 0; dist_marker.color.a = 1; dist_marker.scale.x = 0.2; dist_marker.scale.y = 0.4; dist_marker.scale.z = 0.2; dist_marker.pose.position.z = 3.0; dist_marker.pose.orientation.w = 1.0; dist_marker.points.resize(2); dist_marker.points[0].x = cart_marker.pose.position.x; dist_marker.points[0].y = cart_marker.pose.position.y; dist_marker.points[1].x = cart_marker.pose.position.x + force_scale * dist_u[0]; dist_marker.points[1].y = cart_marker.pose.position.y; marker_arr_msg.markers.push_back(dist_marker); } // Target marker double target_pos = ddp_problem->ref_pos_func_(current_t); visualization_msgs::Marker target_marker; target_marker.header = header_msg; target_marker.ns = "target"; target_marker.id = marker_arr_msg.markers.size(); target_marker.type = visualization_msgs::Marker::LINE_LIST; target_marker.color.r = 0; target_marker.color.g = 1; target_marker.color.b = 1; target_marker.color.a = 0.5; target_marker.scale.x = 0.05; target_marker.pose.position.z = -1.0; target_marker.pose.orientation.w = 1.0; target_marker.points.resize(2); target_marker.points[0].x = target_pos; target_marker.points[0].y = -1e3; target_marker.points[1].x = target_pos; target_marker.points[1].y = 1e3; marker_arr_msg.markers.push_back(target_marker); return marker_arr_msg; } TEST(TestDDPCartPole, TestCase1) { // Setup ROS ros::NodeHandle nh; ros::NodeHandle pnh("~"); ros::Publisher marker_arr_pub = nh.advertise<visualization_msgs::MarkerArray>("marker_arr", 1); constexpr double dist_force_small = 30; // [N] ros::ServiceServer dist_left_small_srv = nh.advertiseService<std_srvs::Empty::Request, std_srvs::Empty::Response>( "/dist_left_small", std::bind(distCallback, std::placeholders::_1, std::placeholders::_2, -1 * dist_force_small)); ros::ServiceServer dist_right_small_srv = nh.advertiseService<std_srvs::Empty::Request, std_srvs::Empty::Response>( "/dist_right_small", std::bind(distCallback, std::placeholders::_1, std::placeholders::_2, dist_force_small)); constexpr double dist_force_large = 100; // [N] ros::ServiceServer dist_left_large_srv = nh.advertiseService<std_srvs::Empty::Request, std_srvs::Empty::Response>( "/dist_left_large", std::bind(distCallback, std::placeholders::_1, std::placeholders::_2, -1 * dist_force_large)); ros::ServiceServer dist_right_large_srv = nh.advertiseService<std_srvs::Empty::Request, std_srvs::Empty::Response>( "/dist_right_large", std::bind(distCallback, std::placeholders::_1, std::placeholders::_2, dist_force_large)); ros::ServiceServer target_pos_m5_srv = nh.advertiseService<std_srvs::Empty::Request, std_srvs::Empty::Response>( "/target_pos_m5", std::bind(targetPosCallback, std::placeholders::_1, std::placeholders::_2, -5.0)); ros::ServiceServer target_pos_0_srv = nh.advertiseService<std_srvs::Empty::Request, std_srvs::Empty::Response>( "/target_pos_0", std::bind(targetPosCallback, std::placeholders::_1, std::placeholders::_2, 0.0)); ros::ServiceServer target_pos_p5_srv = nh.advertiseService<std_srvs::Empty::Request, std_srvs::Empty::Response>( "/target_pos_p5", std::bind(targetPosCallback, std::placeholders::_1, std::placeholders::_2, 5.0)); double horizon_dt = 0.01; // [sec] double horizon_duration = 2.0; // [sec] double mpc_dt = 0.004; // [sec] double sim_dt = 0.002; // [sec] double end_t = 10.0; // [sec] pnh.getParam("control/horizon_dt", horizon_dt); pnh.getParam("control/horizon_duration", horizon_duration); pnh.getParam("control/mpc_dt", mpc_dt); pnh.getParam("control/sim_dt", sim_dt); // Instantiate problem for MPC constexpr double epsilon_t = 1e-6; std::function<double(double)> ref_pos_func = [&](double t) { // Add small values to avoid numerical instability at inequality bounds t += epsilon_t; if(std::isnan(target_pos)) { if(t <= 6.0) { return 0.0; // [m] } else { return 1.0; // [m] } } else { return target_pos; } }; auto ddp_problem = std::make_shared<DDPProblemCartPole>(horizon_dt, ref_pos_func); pnh.getParam("param/cart_mass", ddp_problem->param_.cart_mass); pnh.getParam("param/pole_mass", ddp_problem->param_.pole_mass); pnh.getParam("param/pole_length", ddp_problem->param_.pole_length); std::vector<double> param_vec; if(pnh.getParam("cost/running_x", param_vec)) { ddp_problem->cost_weight_.running_x = Eigen::Map<DDPProblemCartPole::StateDimVector>(param_vec.data()); } if(pnh.getParam("cost/running_u", param_vec)) { ddp_problem->cost_weight_.running_u = Eigen::Map<DDPProblemCartPole::InputDimVector>(param_vec.data()); } if(pnh.getParam("cost/terminal_x", param_vec)) { ddp_problem->cost_weight_.terminal_x = Eigen::Map<DDPProblemCartPole::StateDimVector>(param_vec.data()); } // Check derivatives checkDerivatives(ddp_problem); // Instantiate solver ddp_solver = std::make_shared<nmpc_ddp::DDPSolver<4, 1>>(ddp_problem); int horizon_steps = static_cast<int>(horizon_duration / horizon_dt); ddp_solver->config().horizon_steps = horizon_steps; ddp_solver->config().max_iter = 3; // Instantiate simulation (only state equation is used and cost is ignored) auto sim = std::make_shared<DDPProblemCartPole>(sim_dt, ref_pos_func, ddp_problem->param_, ddp_problem->cost_weight_); // Setup simulation loop current_t = 0; current_x << 0, M_PI, 0, 0; current_u << 0; initial_u_list.assign(horizon_steps, DDPProblemCartPole::InputDimVector::Zero()); dist_t = 0; dist_u << 0; std::string file_path = "/tmp/TestDDPCartPoleResult.txt"; std::ofstream ofs(file_path); ofs << "time pos theta vel omega force ref_pos disturbance" << std::endl; ros::Rate rate(1.0 / sim_dt); bool no_exit = false; pnh.getParam("no_exit", no_exit); // Sleep to wait for Rviz to launch ros::Duration(1.0).sleep(); // Run simulation loop ros::Timer mpc_timer = nh.createTimer(ros::Duration(mpc_dt), mpcTimerCallback); while(ros::ok() && (no_exit || current_t < end_t)) { // Simulate one step if(dist_t < current_t) { dist_u << 0; } current_x = sim->stateEq(current_t, current_x, current_u + dist_u); current_t += sim_dt; // Check pos double current_pos = current_x[0]; double ref_pos = ref_pos_func(current_t); EXPECT_LT(std::abs(current_pos - ref_pos), 1e2); // Dump ofs << current_t << " " << current_x.transpose() << " " << current_u.transpose() << " " << ref_pos << " " << dist_u.transpose() << std::endl; // Publish marker marker_arr_pub.publish(makeMarkerArr(current_x, current_u, ddp_problem)); ros::spinOnce(); rate.sleep(); } mpc_timer.stop(); // Check final pos double ref_pos = ref_pos_func(current_t); EXPECT_LT(std::abs(current_x[0] - ref_pos), 1.0); EXPECT_LT(std::abs(current_x[1]), 1e-1); EXPECT_LT(std::abs(current_x[2]), 1.0); EXPECT_LT(std::abs(current_x[3]), 1e-1); std::cout << "Run the following commands in gnuplot:\n" << " set key autotitle columnhead\n" << " set key noenhanced\n" << " plot \"" << file_path << "\" u 1:2 w lp, \"\" u 1:3 w lp, \"\" u 1:7 w l lw 3\n"; } int main(int argc, char ** argv) { ros::init(argc, argv, "test_ddp_cart_pole"); testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
// Copyright (C) 2018-2022 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #include <vector> #include <gtest/gtest.h> #include <legacy/layer_transform.hpp> #include "backend/gna_types.h" #include "frontend/model_quantizer.hpp" #include "frontend/layer_quantizer.hpp" #include "gna_matcher.hpp" #include <ie_core.hpp> #include "ngraph_functions/builders.hpp" using namespace InferenceEngine; using namespace GNAPluginNS; using namespace GNATestIRs; class I16QuantisationTest : public GNATest<> { protected: LayersQuantizer<QuantI16> lc = LayersQuantizer<QuantI16>(1.0f); InferenceEngine::CNNLayerPtr quantize (InferenceEngine::CNNLayerPtr lp) { auto newLayer = InferenceEngine::injectData<QuantizedLayerParams>(lp); transformLayer(newLayer, lc); return newLayer; }; void SetUp() override { } }; template <class T> T setWeights(T blob) { blob->allocate(); // actual quantisation algorithm is involved - we need to provide weights that will be quantized with scale factor of 1 for (auto && w : *blob) { w = MAX_VAL_2B_WEIGHT; } return blob; } template <> TBlob<uint8_t>::Ptr setWeights(TBlob<uint8_t>::Ptr blob) { blob->allocate(); auto buf = blob->buffer(); auto ptr = buf.as<float*>(); for (int i = 0; i != blob->byteSize() / 4; i++) { ptr[i] = MAX_VAL_2B_WEIGHT; } return blob; } // TODO: add test for FC weights after quantization TEST_F(I16QuantisationTest, canQuantizeFCLayer){ auto fc = std::make_shared<FullyConnectedLayer>(LayerParams{"name", "type", Precision::FP32}); fc->_out_num = 9; fc->_weights = setWeights(make_shared_blob<float>({ Precision::FP32, {1, 1}, Layout::NC })); fillWeights(fc->_weights); fc->_biases = make_shared_blob<float>({ Precision::FP32, {1, 1}, Layout::NC }); fc->_biases->allocate(); fillWeights(fc->_biases); std::shared_ptr<Data> outData = std::make_shared<Data>("data", TensorDesc(Precision::FP32, SizeVector({1, 1}), Layout::NC)); fc->outData.push_back(outData); fc->insData.push_back(outData); ASSERT_NO_THROW(quantize(fc)); } TEST_F(I16QuantisationTest, canQuantizeActivation){ auto sigmoid = std::make_shared<GenericLayer >(LayerParams{"name", "type", Precision::FP32}); sigmoid->params["value"] = 2; sigmoid->type = "Activation"; ASSERT_NO_THROW(quantize(sigmoid)); } TEST_F(I16QuantisationTest, outputAffinePrecisionIs32Bits){ ModelQuantizer<QuantI16> q; auto weights = make_shared_blob<uint8_t>({ Precision::U8, {440}, C }); weights->allocate(); fillWeights(weights); Core ie; auto network = ie.ReadNetwork(Fc2DOutputModel(), weights); auto newNet = q.quantize(network, 1000); InputsDataMap inputs = newNet.getInputsInfo(); auto affineDataPtr = getInputTo(inputs.begin()->second->getInputData()).begin()->second->outData.front(); ASSERT_EQ(affineDataPtr->getTensorDesc().getPrecision(), Precision::I32); } TEST_F(I16QuantisationTest, canQuantizeLstmLikeTopology) { ModelQuantizer<QuantI16> q; auto weights = setWeights(make_shared_blob<uint8_t >({ Precision::U8, {440}, C })); //std::fill_n(weights->buffer().as<float*>(), weights->byteSize()/sizeof(float), 0); Core ie; auto network = ie.ReadNetwork(affineToMemoryModel(), weights); ASSERT_NO_THROW(q.quantize(network, 1000)); } TEST_F(I16QuantisationTest, DISABLED_outputScaleFactorForAffineIsCorrect){ ModelQuantizer<QuantI16> q; auto weights = make_shared_blob<uint8_t >({ Precision::U8, {440}, C }); weights->allocate(); fillWeights(weights, {100}); Core ie; auto network = ie.ReadNetwork(Fc2DOutputModel(), weights); auto newNet = q.quantize(network, 1000); InputsDataMap inputs = newNet.getInputsInfo(); auto affineLayerPtr = getInputTo(inputs.begin()->second->getInputData()).begin()->second; auto quantParams = getInjectedData<QuantizedLayerParams>(affineLayerPtr); ASSERT_FLOAT_EQ(quantParams->_dst_quant.GetScale(), 100); ASSERT_FLOAT_EQ(quantParams->_weights_quant.GetScale(), 100); } TEST_F(I16QuantisationTest, OnlyAffine_NoActivationInsertion) { assert_that() .onInferModel(Fc2DOutputModel()) .inNotCompactMode().withGNAConfig(GNA_CONFIG_KEY(SCALE_FACTOR), 1.0f) .gna().propagate_forward().called_without().pwl_inserted_into_nnet(); } TEST_F(I16QuantisationTest, OnlyAffine_NoActivationInsertion_ProfilingEnabled) { assert_that() .onInferModel(Fc2DOutputModel()) .inNotCompactMode().withGNAConfig(GNA_CONFIG_KEY(SCALE_FACTOR), 1.0f) .gna().propagate_forward().called_without().pwl_inserted_into_nnet().profiling_counters(); } TEST_F(I16QuantisationTest, OnlyAffineWithNanScaleFactorFails) { gna() .onInferModel(Fc2DOutputModel()) .withNanScaleFactor() .propagate_forward().throws(); } TEST_F(I16QuantisationTest, OnlyAffineWithInfScaleFactorFails) { gna() .onInferModel(Fc2DOutputModel()) .withInfScaleFactor() .propagate_forward().throws(); } TEST_F(I16QuantisationTest, AffineToMemoryWillResultInActivationInsertion) { assert_that() .onInferModel(affineToMemoryModel()) .inNotCompactMode().withGNAConfig(GNA_CONFIG_KEY(SCALE_FACTOR), 1.0f) .gna().propagate_forward().called_with().pwl_inserted_into_nnet(); } TEST_F(I16QuantisationTest, EltwiseToMemoryWithNoOutputActivationInsertion) { assert_that().inNotCompactMode().withGNAConfig(GNA_CONFIG_KEY(SCALE_FACTOR), 1.0f) .onInferModel(eltwiseToMemoryModelNoOutput(), [](CNNNetwork & net){ net.addOutput("Eltwise_8"); }).gna().propagate_forward().called_with().pwl_inserted_into_nnet(); } TEST_F(I16QuantisationTest, EltwiseToMemory_ActivationInsertion) { assert_that().onInferModel(eltwiseToMemoryModel()).withGNAConfig(GNA_CONFIG_KEY(SCALE_FACTOR), 1.0f) .inNotCompactMode().gna().propagate_forward().called_with().pwl_inserted_into_nnet(); } TEST_F(I16QuantisationTest, SplitFollowedByActivation_DummyDiagonalAffineInsertion) { auto input_params = std::make_shared<ngraph::opset8::Parameter>(ngraph::element::f32, ngraph::Shape{1, 20}); const auto axis_node = ngraph::opset8::Constant::create(ngraph::element::i64, ngraph::Shape{}, {1}); auto split = std::make_shared<ngraph::opset8::Split>(input_params, axis_node, 2); auto tanh = std::make_shared<ngraph::opset8::Tanh>(split->outputs()[0]); auto add = std::make_shared<ngraph::opset8::Add>(split->outputs()[1], tanh); auto result = std::make_shared<ngraph::opset8::Result>(add); auto function = std::make_shared<ngraph::Function>(ngraph::ResultVector{result}, ngraph::ParameterVector{input_params}); assert_that().onInferNgraphModel(function) .inNotCompactMode().withGNAConfig(GNA_CONFIG_KEY(SCALE_FACTOR), 1.0f) .gna().propagate_forward().called_with().diagonal_inserted_into_nnet(); } TEST_F(I16QuantisationTest, SliceFollowedBy2FCsAnd2Eltwises_AlignedFilterInsertion) { assert_that().onInferModel(twoFCWithPaddingAfterSliceModel()) .inNotCompactMode().withGNAConfig(GNA_CONFIG_KEY(SCALE_FACTOR), 1.0f) .gna().propagate_forward().called_with().diagonal_inserted_into_nnet(); } // ToDo requires implementation of aligning filter for concat inputs and improvement of // qunatization/scaling algorithm for concat TEST_F(I16QuantisationTest, DISABLED_DoubleConcatPropageteForwardWithSuccess_AlignedFilterInsertion) { assert_that().onInferModel(doubleConcatModel()).withGNAConfig(GNA_CONFIG_KEY(SCALE_FACTOR), 1.0f) .inNotCompactMode().gna().propagate_forward().called_with().diagonal_inserted_into_nnet(); } TEST_F(I16QuantisationTest, EltwiseSumm_onlyOneIdentityInsertion) { assert_that().onInferModel(eltwiseSummModel()).withGNAConfig(GNA_CONFIG_KEY(SCALE_FACTOR), 1.0f) .inNotCompactMode().gna().propagate_forward().called_with().pwl_inserted_into_nnet().once(); } TEST_F(I16QuantisationTest, canDetectLeakyRelu) { assert_that().onInferModel(TFLeakyReluModel()) .inNotCompactMode().withGNAConfig(GNA_CONFIG_KEY(SCALE_FACTOR), 1.0f) .gna().propagate_forward().called_with().pwl_inserted_into_nnet(); } TEST_F(I16QuantisationTest, MaxPool_followedAfterActivation) { assert_that().onInferModel(maxpoolAfterRelu()) .inNotCompactMode().withGNAConfig(GNA_CONFIG_KEY(SCALE_FACTOR), 1.0f) .gna().propagate_forward().called_with() .convolution_inserted_into_nnet() .And() .pwl_inserted_into_nnet() .And() .max_pooling_inserted_into_nnet(); } TEST_F(I16QuantisationTest, EltwiseMull_willInsertTwoIdentities) { assert_that().onInferModel(eltwiseMulModel()) .inNotCompactMode().withGNAConfig(GNA_CONFIG_KEY(SCALE_FACTOR), 1.0f) .gna().propagate_forward().called_with().pwl_inserted_into_nnet().twice(); } TEST_F(I16QuantisationTest, multiple_inputs_supported) { std::string configKey = GNA_CONFIG_KEY(SCALE_FACTOR) + std::string("_"); assert_that().onInferModel(two_inputs_to_affine()) .inNotCompactMode().withGNAConfig(configKey + std::to_string(0), 1.0f) .withGNAConfig(configKey + std::to_string(1), 2.0f).gna().propagate_forward() .called_with().pwl_inserted_into_nnet().once(); } TEST_F(I16QuantisationTest, DISABLED_multiple_inputs_into_concat_supported) { assert_that().onInferModel(two_inputs_to_concat()) .inNotCompactMode().withGNAConfig(GNA_CONFIG_KEY(SCALE_FACTOR), 1.0f).gna().propagate_forward().called_with().pwl_inserted_into_nnet().once(); } TEST_F(I16QuantisationTest, ScaleShift_Affine_WillResultInIdentityInsertion) { assert_that().onInferModel(scaleShiftAffineModel()) .inNotCompactMode().withGNAConfig(GNA_CONFIG_KEY(SCALE_FACTOR), 1.0f) .gna().propagate_forward().called_with().pwl_inserted_into_nnet().once(); } TEST_F(I16QuantisationTest, ClampFollowedByTanh_ResultInDiagonalInsertion) { auto input_params = std::make_shared<ngraph::opset8::Parameter>(ngraph::element::f32, ngraph::Shape{1, 10}); auto clamp = std::make_shared<ngraph::opset8::Clamp>(input_params, -50, 50); auto tanh = std::make_shared<ngraph::opset8::Tanh>(clamp); auto result = std::make_shared<ngraph::opset8::Result>(tanh); auto function = std::make_shared<ngraph::Function>(ngraph::ResultVector{result}, ngraph::ParameterVector{input_params}); assert_that().onInferNgraphModel(function) .inNotCompactMode().withGNAConfig(GNA_CONFIG_KEY(SCALE_FACTOR), 1.0f) .gna().propagate_forward().called_with().diagonal_inserted_into_nnet().twice(); } TEST_F(I16QuantisationTest, EltwiseWithMemoryAndActivationInput_ResultInTwoDiagonalsInsertion) { auto input_params = std::make_shared<ngraph::opset8::Parameter>(ngraph::element::f32, ngraph::Shape{1, 10}); const auto constant = ngraph::opset8::Constant::create(ngraph::element::f32, ngraph::Shape{10, 10}, {1}); auto matmul = std::make_shared<ngraph::opset8::MatMul>(input_params, constant); auto mem_i = std::make_shared<ngraph::op::v0::Constant>(ngraph::element::f32, ngraph::Shape{1, 10}, 0); auto mem_r = std::make_shared<ngraph::op::v3::ReadValue>(mem_i, "r_27-28"); auto tanh = std::make_shared<ngraph::opset8::Tanh>(matmul); auto add = std::make_shared<ngraph::opset8::Add>(tanh, mem_r); tanh->add_control_dependency(mem_r); auto mem_w = std::make_shared<ngraph::op::v3::Assign>(tanh, "r_27-28"); auto result = std::make_shared<ngraph::opset8::Result>(add); mem_w->add_control_dependency(mem_r); result->add_control_dependency(mem_w); auto function = std::make_shared<ngraph::Function>(ngraph::ResultVector{result}, ngraph::ParameterVector{input_params}); assert_that().onInferNgraphModel(function) .inNotCompactMode().withGNAConfig(GNA_CONFIG_KEY(SCALE_FACTOR), 1.0f) .gna().propagate_forward().called_with().diagonal_inserted_into_nnet().twice(); } TEST_F(I16QuantisationTest, AffineWith2AffineOutputs_ResultInOnlyOneIdentityInsertion) { // one Identity activation from first FC, and one Identity activation for eltwise assert_that().onInferModel(AffineWith2AffineOutputsModel()) .inNotCompactMode().withGNAConfig(GNA_CONFIG_KEY(SCALE_FACTOR), 1.0f) .gna().propagate_forward().called_with().pwl_inserted_into_nnet().twice(); } TEST_F(I16QuantisationTest, ScaleShiftWithBroadcast_ResultInDiagonalInsertion) { auto & affineWeights = storage<std::vector<uint16_t>>(); affineWeights = { 2048, 4096, 6144, 8192, 10240, 12288, 14336, 16384, 2048, 4096, 6144, 8192, 10240, 12288, 14336, 16384, 2048, 4096, 6144, 8192, 10240, 12288, 14336, 16384, 2048, 4096, 6144, 8192, 10240, 12288, 14336, 16384, 2048, 4096, 6144, 8192, 10240, 12288, 14336, 16384, }; assert_that().withGNAConfig(GNA_CONFIG_KEY(SCALE_FACTOR), 1.0f).onInferModel(ScaleShift3DModel()) .withWeigthsPattern({1.0f,2.0f,3.0f,4.0f,5.0f,6.0f,7.0f,8.0f}) .inNotCompactMode().gna().propagate_forward().called_with().called_with().affine_weights_eq(affineWeights); } TEST_F(I16QuantisationTest, MemoryAfterConcat_ResultInCopyInsertion) { assert_that().onInferModel(MemoryAfterConcatModel()).inNotCompactMode().gna().propagate_forward(). called_with().copy_inserted_into_nnet(); } TEST_F(I16QuantisationTest, MemoryAndConcatAfterOneNode_ResultInCopyInsertion) { assert_that().onInferModel(MemoryAndConcatAfterOneNode()).inNotCompactMode().gna().propagate_forward(). called_with().copy_inserted_into_nnet(); } TEST_F(I16QuantisationTest, DISABLED_permutationOfWeightsBetweenConvAndAffine) { auto & affineWeights = storage<std::vector<uint16_t>>(); // least likely that width and height both are multiple of 7 auto weigthsPattern = {1.f, 2.f, 3.f, 4.f, 5.f, 6.f, 7.f}; // here weights are transpozed save().onInferModel(affineAfterConvNoPermute()).withWeigthsPattern(weigthsPattern) .inNotCompactMode().from().propagate_forward().affine_weights_transpozed({128, 61}).to(affineWeights); // here weights shouldn't be transposed assert_that().onInferModel(affineAfterConvWithPermute()).withWeigthsPattern(weigthsPattern) .inNotCompactMode().gna().propagate_forward().called_with().affine_weights_eq(affineWeights); } TEST_F(I16QuantisationTest, DISABLED_noPermutationOfWeightsBetweenConvAndAffineIfPermuteLayerWithCorrectArgs) { auto & affineWeights = storage<std::vector<uint16_t>>(); // least likely that width and height both are multiple of 7 auto weigthsPattern = {1.f, 2.f, 3.f, 4.f, 5.f, 6.f, 7.f}; save().onInferModel(affineAfterConvWithPermute()).withWeigthsPattern(weigthsPattern) .inNotCompactMode().from().propagate_forward().affine_weights().to(affineWeights); assert_that().onInferModel(affineAfterConvNoPermute()).withWeigthsPattern(weigthsPattern) .inNotCompactMode().gna().propagate_forward().called_with().affine_weights_transposed(affineWeights, {128, 61}); } TEST_F(I16QuantisationTest, fp16tofp32_on_fullyConnected_model) { ModelQuantizer<QuantI16> q; auto weights = make_shared_blob<uint8_t>({ Precision::U8, {220}, Layout::C }); weights->allocate(); fillWeights(weights); Core ie; auto network = ie.ReadNetwork(FCOnlyModelFP16(), weights); q.quantize(network, 1000); } TEST_F(I16QuantisationTest, MultipleActivationsAfterAffineWithIdentityActivation_MultipleDiagonalLayersWithActivaitons) { auto input_params = std::make_shared<ngraph::opset8::Parameter>(ngraph::element::f32, ngraph::Shape{1, 10}); const auto constant = ngraph::opset8::Constant::create(ngraph::element::f32, ngraph::Shape{10, 10}, {1}); auto matmul1 = std::make_shared<ngraph::opset8::MatMul>(input_params, constant); auto matmul2 = std::make_shared<ngraph::opset8::MatMul>(input_params, constant); auto add = std::make_shared<ngraph::opset8::Add>(matmul2, matmul1); auto sigmoid = std::make_shared<ngraph::opset8::Sigmoid>(matmul2); auto relu = std::make_shared<ngraph::opset8::Relu>(matmul2); auto mul = std::make_shared<ngraph::opset8::Multiply>(sigmoid, relu); auto add2 = std::make_shared<ngraph::opset8::Add>(add, mul); auto result = std::make_shared<ngraph::opset8::Result>(add); auto function = std::make_shared<ngraph::Function>(ngraph::ResultVector{result}, ngraph::ParameterVector{input_params}); // identiy came from automatic insertion due to assert_that().onInferNgraphModel(function) .inNotCompactMode().withGNAConfig(GNA_CONFIG_KEY(SCALE_FACTOR), 1.0f) .gna().propagate_forward().called_with().pwls_inserted_into_nnet({kActSigmoid, kActRelu, kActIdentity, kActIdentity}); } TEST_F(I16QuantisationTest, MultipleActivationsAfterAffine_ResultInMultipleDiagonalLayersWithActivaitons) { auto input_params = std::make_shared<ngraph::opset8::Parameter>(ngraph::element::f32, ngraph::Shape{1, 10}); const auto constant = ngraph::opset8::Constant::create(ngraph::element::f32, ngraph::Shape{10, 10}, {1}); auto matmul = std::make_shared<ngraph::opset8::MatMul>(input_params, constant); auto sigmoid = std::make_shared<ngraph::opset8::Sigmoid>(matmul); auto relu = std::make_shared<ngraph::opset8::Relu>(matmul); auto mul = std::make_shared<ngraph::opset8::Multiply>(sigmoid, relu); auto result = std::make_shared<ngraph::opset8::Result>(mul); auto function = std::make_shared<ngraph::Function>(ngraph::ResultVector{result}, ngraph::ParameterVector{input_params}); // extra identity inserted for affine assert_that().onInferNgraphModel(function) .inNotCompactMode().withGNAConfig(GNA_CONFIG_KEY(SCALE_FACTOR), 1.0f) .gna().propagate_forward().called_with() // 1 diag for second activation, 1 for eltwise .pwls_inserted_into_nnet({kActRelu, kActSigmoid}).diagonal_inserted_into_nnet().times(3); } // TODO: build a regression test on top of it using real quantisation accuracy checking TEST_F(I16QuantisationTest, ConcatWithConstInputPropagatedForward) { assert_that().onInferModel(concatModelWithConstLayer()) .inNotCompactMode().withGNAConfig(GNA_CONFIG_KEY(SCALE_FACTOR), 1.0f) .gna().propagate_forward().called_with().pwls_inserted_into_nnet({kActIdentity}); } TEST_F(I16QuantisationTest, LSTMCell_quantize) { ModelQuantizer<QuantI16> q; auto weights = make_shared_blob<uint8_t>({ Precision::U8, {33664}, C }); weights->allocate(); fillWeights(weights); Core ie; auto network = ie.ReadNetwork(LSTMCellOnlyModel(), weights); ASSERT_NO_THROW(q.quantize(network, 1000)); } TEST_F(I16QuantisationTest, LSTMCell_unaligned_quantize) { ModelQuantizer<QuantI16> q; auto weights = make_shared_blob<uint8_t>({ Precision::U8, {3480}, C }); weights->allocate(); fillWeights(weights); Core ie; auto network = ie.ReadNetwork(LSTMCellOnlyModelUnaligned(), weights); ASSERT_NO_THROW(q.quantize(network, 1000)); } TEST_F(I16QuantisationTest, EltwisetWithConstInputPropagatedForward) { assert_that().onInferModel(eltwiseSumModelWithConstLayer()) .inNotCompactMode().withGNAConfig(GNA_CONFIG_KEY(SCALE_FACTOR), 1.0f) .gna().propagate_forward().called_with().diagonal_inserted_into_nnet(); } TEST_F(I16QuantisationTest, PowerWithScaleFactorPropagateForward) { assert_that().onInferModel(PowerWithScaleFactor1()) .inNotCompactMode().withGNAConfig(GNA_CONFIG_KEY(SCALE_FACTOR), 1.0f) .gna().propagate_forward().called_with().pwls_inserted_into_nnet({kActIdentity}).And().diagonal_inserted_into_nnet(); } TEST_F(I16QuantisationTest, ConcatWithDifferentInputScaleFactorsPropagateForward) { auto input_params = std::make_shared<ngraph::opset8::Parameter>(ngraph::element::f32, ngraph::Shape{1, 20}); const auto axis_node = ngraph::opset8::Constant::create(ngraph::element::i64, ngraph::Shape{}, {1}); auto split = std::make_shared<ngraph::opset8::Split>(input_params, axis_node, 2); auto sigmoid = std::make_shared<ngraph::opset8::Sigmoid>(split->outputs()[0]); auto tanh = std::make_shared<ngraph::opset8::Tanh>(split->outputs()[1]); auto concat = std::make_shared<ngraph::opset8::Concat>(ngraph::OutputVector{sigmoid, tanh}, 1); auto result = std::make_shared<ngraph::opset8::Result>(concat); auto function = std::make_shared<ngraph::Function>(ngraph::ResultVector{result}, ngraph::ParameterVector{input_params}); assert_that().onInferNgraphModel(function) .inNotCompactMode().withGNAConfig(GNA_CONFIG_KEY(SCALE_FACTOR), 1.0f) .gna().propagate_forward().called_with().pwls_inserted_into_nnet({kActIdentity}); } TEST_F(I16QuantisationTest, TI_quantize) { ModelQuantizer<QuantI16> q; auto weights = make_shared_blob<uint8_t>({ Precision::U8, {249748}, C }); weights->allocate(); fillWeights(weights); Core ie; auto network = ie.ReadNetwork(TIModelWithLSTMCell2(), weights); ASSERT_NO_THROW(q.quantize(network, 1000)); } TEST_F(I16QuantisationTest, TI_PropagateForward) { auto input_params = std::make_shared<ngraph::opset8::Parameter>(ngraph::element::f32, ngraph::Shape{ 1, 10 }); auto mul = std::make_shared<ngraph::opset8::Multiply>(input_params, std::make_shared<ngraph::op::Constant>(ngraph::element::f32, ngraph::Shape{ 1, 10 })); auto add = std::make_shared<ngraph::opset8::Add>(mul, std::make_shared<ngraph::op::Constant>(ngraph::element::f32, ngraph::Shape{ 1, 10 })); auto reshape = std::make_shared<ngraph::opset8::Reshape>(add, std::make_shared<ngraph::op::Constant>(ngraph::element::i64, ngraph::Shape{ 3 }, std::vector<size_t>{ 1, 1, 10 }), false); auto reshape_shape = reshape->output(0).get_shape(); const size_t batch_size = 1; const size_t hiddenSize = 10; auto H_init = ngraph::builder::makeConstant<float>(ngraph::element::f32, { batch_size, hiddenSize }, {}, true); auto C_init = ngraph::builder::makeConstant<float>(ngraph::element::f32, { batch_size, hiddenSize }, {}, true); auto H_t = std::make_shared<ngraph::opset8::Parameter>(ngraph::element::f32, ngraph::Shape{ batch_size, hiddenSize }); auto C_t = std::make_shared<ngraph::opset8::Parameter>(ngraph::element::f32, ngraph::Shape{ batch_size, hiddenSize }); //Body auto X = std::make_shared<ngraph::opset8::Parameter>(ngraph::element::f32, ngraph::Shape{ batch_size, 1, reshape_shape[2] }); auto weightsNode = ngraph::builder::makeConstant<float>(ngraph::element::f32, { 4 * hiddenSize, reshape_shape[2] }, {}, true); auto reccurrenceWeightsNode = ngraph::builder::makeConstant<float>(ngraph::element::f32, { 4 * hiddenSize, hiddenSize }, {}, true); // lstm auto constantX = ngraph::opset8::Constant::create(ngraph::element::i64, ngraph::Shape{ 2 }, { batch_size, reshape_shape[2] }); auto lstm1 = std::make_shared<ngraph::opset8::LSTMCell>(std::make_shared<ngraph::opset8::Reshape>(X, constantX, false), H_t, C_t, weightsNode, reccurrenceWeightsNode, hiddenSize); auto H_o = lstm1->output(0); auto C_o = lstm1->output(1); auto body = std::make_shared<ngraph::Function>( ngraph::OutputVector{ H_o, C_o }, ngraph::ParameterVector{ X, H_t, C_t }); auto tensor_iterator = std::make_shared<ngraph::opset8::TensorIterator>(); tensor_iterator->set_body(body); tensor_iterator->set_sliced_input(X, reshape, 0, 1, 1, -1, 1); tensor_iterator->set_merged_input(H_t, H_init, H_o); tensor_iterator->set_merged_input(C_t, C_init, C_o); auto out0 = tensor_iterator->get_iter_value(H_o, -1); const size_t output_size = 12; auto fc = ngraph::builder::makeFullyConnected(out0, ngraph::element::f32, output_size, true, { hiddenSize, output_size }, { 1 }, { 1 }); auto result = std::make_shared<ngraph::opset8::Result>(fc); auto function = std::make_shared<ngraph::Function>(ngraph::ResultVector{result}, ngraph::ParameterVector{input_params}); assert_that().onInferNgraphModel(function).withWeigthsPattern({0.1f}) .inNotCompactMode().gna().propagate_forward() .called_with().pwls_inserted_into_nnet({kActIdentity}); } TEST_F(I16QuantisationTest, SplitToConcatWith2Inputs1360NotAlignedNoFC) { assert_that().onInferModel(SplitToConcatWith2Inputs1360NotAlignedNoFC()) .inNotCompactMode() .withGNAConfig(GNA_CONFIG_KEY(SCALE_FACTOR), 1.0f) .gna() .propagate_forward() .called(); }
#pragma once /** * Copyright (c) blueback * Released under the MIT License * https://github.com/bluebackblue/brownie/blob/master/LICENSE.txt * http://bbbproject.sakura.ne.jp/wordpress/mitlicense * @brief ジオメトリ。 */ /** include */ #pragma warning(push) #pragma warning(disable:4464) #include "../types/types.h" #pragma warning(pop) /** include */ #include "./geometry_frustum.h" /** NBsys::NGeometry */ #if(BSYS_GEOMETRY_ENABLE) #pragma warning(push) #pragma warning(disable:4514) namespace NBsys{namespace NGeometry { /** constructor */ inline Geometry_Frustum::Geometry_Frustum() { } /** destructor */ inline Geometry_Frustum::~Geometry_Frustum() { } /** SetProjection */ inline void Geometry_Frustum::SetProjection(const Geometry_Matrix_44& a_projection) { this->projection = a_projection; } /** SetView */ inline void Geometry_Frustum::SetView(const Geometry_Matrix_44& a_view) { this->view = a_view; } /** CalcPlane */ inline void Geometry_Frustum::Calc() { Geometry_Matrix_44 t_matrix = Geometry_Identity(); t_matrix *= this->view; t_matrix *= this->projection; //left this->plane[0].SetABCD(t_matrix.ax_w() + t_matrix.ax_x(),t_matrix.ay_w() + t_matrix.ay_x(),t_matrix.az_w() + t_matrix.az_x(),- t_matrix.tr_w() - t_matrix.tr_x()); //right this->plane[1].SetABCD(t_matrix.ax_w() - t_matrix.ax_x(),t_matrix.ay_w() - t_matrix.ay_x(),t_matrix.az_w() - t_matrix.az_x(),- t_matrix.tr_w() + t_matrix.tr_x()); //bottom this->plane[2].SetABCD(t_matrix.ax_w() + t_matrix.ax_y(),t_matrix.ay_w() + t_matrix.ay_y(),t_matrix.az_w() + t_matrix.az_y(),- t_matrix.tr_w() - t_matrix.tr_y()); //top this->plane[3].SetABCD(t_matrix.ax_w() - t_matrix.ax_y(),t_matrix.ay_w() - t_matrix.ay_y(),t_matrix.az_w() - t_matrix.az_y(),- t_matrix.tr_w() + t_matrix.tr_y()); //near #if(BSYS_GEOMETRY_PERSPECTIVE_TYPE == 0x00) { //directx this->plane[4].SetABCD(t_matrix.ax_z(),t_matrix.ay_z(),t_matrix.az_z(),-t_matrix.tr_z()); } #else { //opengl this->plane[4].SetABCD(t_matrix.ax_w() + t_matrix.ax_z(),t_matrix.ay_w() + t_matrix.ay_z(),t_matrix.az_w() + t_matrix.az_z(),- t_matrix.tr_w() - t_matrix.tr_z()); } #endif //far this->plane[5].SetABCD(t_matrix.ax_w() - t_matrix.ax_z(),t_matrix.ay_w() - t_matrix.ay_z(),t_matrix.az_w() - t_matrix.az_z(),- t_matrix.tr_w() + t_matrix.tr_z()); } /** InFrustumCheck */ inline bool Geometry_Frustum::InFrustumCheck(Geometry_Vector3& a_position) { for(s32 ii=0;ii<COUNTOF(this->plane);ii++){ if(this->plane[ii].Distance(a_position) < 0){ //フラスタム外。 return false; } } //フラスタム内。 return true; } }} #pragma warning(pop) #endif
#pragma once #include <autoppl/util/traits.hpp> #include <autoppl/expression/model/eq_node.hpp> #include <autoppl/expression/model/glue_node.hpp> #include <autoppl/expression/variable/variable_viewer.hpp> #include <autoppl/expression/variable/constant.hpp> #include <autoppl/expression/variable/binop.hpp> #include <autoppl/expression/variable/unop.hpp> #include <autoppl/variable.hpp> #include <autoppl/expression/distribution/uniform.hpp> #include <autoppl/expression/distribution/mixture.hpp> #include <autoppl/expression/distribution/triangular.hpp> #include <autoppl/expression/distribution/normal.hpp> #include <autoppl/expression/distribution/bernoulli.hpp> #include <autoppl/expression/distribution/categorical.hpp> #include <autoppl/expression/distribution/delta.hpp> #include <autoppl/expression/distribution/discrete_uniform.hpp> #include <iostream> #include <autoppl/settings.hpp> namespace ppl { //////////////////////////////////////////////////////// // Distribution Expression Builder //////////////////////////////////////////////////////// namespace details { /** * Converter from arbitrary (decayed) type to valid continuous parameter type * by the following mapping: * - is_var_v<T> true => VariableViewer<T> * - T is an arithmetic type => Constant<T> * - is_var_expr_v<T> true => T * Assumes each condition is non-overlapping. */ #if __cplusplus <= 201703L template <class T, class = void> struct convert_to_param {}; template <class T> struct convert_to_param<T, std::enable_if_t<util::is_var_v<std::decay_t<T>> > > { using type = expr::VariableViewer<std::decay_t<T>>; }; template <class T> struct convert_to_param<T, std::enable_if_t<ppl::is_arithmetic_v<std::decay_t<T>> > > { using type = expr::Constant<std::decay_t<T>>; }; template <class T> struct convert_to_param<T, std::enable_if_t<util::is_var_expr_v<std::decay_t<T>> > > { using type = T; }; #else template <class T> struct convert_to_param; template <class T> requires util::var<std::decay_t<T>> struct convert_to_param<T> { using type = expr::VariableViewer<std::decay_t<T>>; }; template <class T> requires ppl::is_arithmeticy_v<std::decay_t<T>> struct convert_to_param<T> { using type = expr::Constant<std::decay_t<T>>; }; template <class T> requires util::var_expr<std::decay_t<T>> struct convert_to_param<T> { using type = T; }; #endif template <class T> using convert_to_param_t = typename convert_to_param<T>::type; #if __cplusplus <= 201703L /** * Checks if valid distribution parameter: * - can be arithmetic * - if not arithmetic, must be variable or variable expression * - if variable, cannot be (rvalue reference or const) */ template <class T> inline constexpr bool is_valid_dist_param_v = ppl::is_arithmetic_v<std::decay_t<T>> || (util::is_var_v<std::decay_t<T>> && !std::is_rvalue_reference_v<T> && !std::is_const_v<std::remove_reference_t<T>>) || (util::is_var_expr_v<std::decay_t<T>>) ; /** * Checks if the decayed types of T1 and T2 * are not both arithmetic types. */ template <class T1, class T2> inline constexpr bool is_not_both_arithmetic_v = !(ppl::is_arithmetic_v<std::decay_t<T1>> && ppl::is_arithmetic_v<std::decay_t<T2>>) ; #else template <class T> concept valid_dist_param = ppl::is_arithmetic_v<std::decay_t<T>> || (util::var<std::decay_t<T>> && !std::is_rvalue_reference_v<T> && !std::is_const_v<std::remove_reference_t<T>>) || (util::var_expr<std::decay_t<T>>) ; template <class T1, class T2> concept not_both_arithmetic = !(ppl::is_arithmetic_v<std::decay_t<T1>> && ppl::is_arithmetic_v<std::decay_t<T2>>) ; #endif ////////////////////////////////////////////////////////////////////////////// #if __cplusplus <= 201703L template <class T1> inline constexpr bool is_arithmetic_v = (ppl::is_arithmetic_v<std::decay_t<T1>>); #else template <class T1> concept is_arithmetic = (ppl::is_arithmetic_v<std::decay_t<T1>>); #endif ////////////////////////////////////////////////////////////////////////////// } // namespace details /** * Builds a Uniform expression only when the parameters * are both valid continuous distribution parameter types. * See var_expr.hpp for more information. */ #if __cplusplus <= 201703L template <class MinType, class MaxType, class ValueT=util::cont_param_t, class DistValueT=util::dist_value_t_default , class = std::enable_if_t< details::is_valid_dist_param_v<MinType> && details::is_valid_dist_param_v<MaxType> > > inline constexpr auto uniform(MinType&& min_expr, MaxType&& max_expr) #else template <details::valid_dist_param MinType , details::valid_dist_param MaxType> inline constexpr auto uniform(MinType&& min_expr, MaxType&& max_expr) #endif { using min_t = details::convert_to_param_t<MinType>; using max_t = details::convert_to_param_t<MaxType>; min_t wrap_min_expr = std::forward<MinType>(min_expr); max_t wrap_max_expr = std::forward<MaxType>(max_expr); return expr::Uniform<min_t, max_t, ValueT, DistValueT>(wrap_min_expr, wrap_max_expr); } #if __cplusplus <= 201703L template <class MinType, class MaxType, class ValueT=util::cont_param_t, class DistValueT=util::dist_value_t_default , class = std::enable_if_t< details::is_valid_dist_param_v<MinType> && details::is_valid_dist_param_v<MaxType> > > inline constexpr auto discrete_uniform(MinType&& min_expr, MaxType&& max_expr) #else template <details::valid_dist_param MinType , details::valid_dist_param MaxType> inline constexpr auto discrete_uniform(MinType&& min_expr, MaxType&& max_expr) #endif { using min_t = details::convert_to_param_t<MinType>; using max_t = details::convert_to_param_t<MaxType>; min_t wrap_min_expr = std::forward<MinType>(min_expr); max_t wrap_max_expr = std::forward<MaxType>(max_expr); return expr::DiscreteUniform<min_t, max_t, ValueT, DistValueT>(wrap_min_expr, wrap_max_expr); } /** * Builds a Triangular Distribution when parameters a, b, and c * are all valid continuous distribution parameter types. */ #if __cplusplus <= 201703L template <class AType, class BType, class CType, class ValueT=util::cont_param_t, class DistValueT=util::dist_value_t_default , class = std::enable_if_t< details::is_valid_dist_param_v<AType> && details::is_valid_dist_param_v<BType> > > inline constexpr auto triangular(AType&& a_expr, BType&& b_expr, CType&& c_expr) #else template <details::valid_dist_param AType , details::valid_dist_param BType> , details::valid_dist_param CType> inline constexpr auto triangular(AType&& a_expr, BType&& b_expr, CType&& c_expr) #endif { using a_t = details::convert_to_param_t<AType>; using b_t = details::convert_to_param_t<BType>; using c_t = details::convert_to_param_t<CType>; a_t wrap_a_expr = std::forward<AType>(a_expr); b_t wrap_b_expr = std::forward<BType>(b_expr); c_t wrap_c_expr = std::forward<CType>(c_expr); return expr::Triangular<a_t, b_t, c_t, ValueT, DistValueT>(wrap_a_expr, wrap_b_expr, wrap_c_expr); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // // THE FOLLOWING ARE THE OVERLOADED VERSIONS OF MIXTURE DISTRIBUTION PRIMITIVES // // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * Builds a Mixture Distribution when parameters * are all valid continuous distribution parameter types. */ #if __cplusplus <= 201703L template <class p1_type, class Dist1_type, class Dist2_type, class value_t_=util::value_t_bernoulli, class dist_value_t_=util::dist_value_t_default> /* , class = std::enable_if_t< details::is_valid_dist_param_v<MinType> && details::is_valid_dist_param_v<MaxType> > > */ inline constexpr auto mixture(p1_type p1, Dist1_type Dist1, Dist2_type Dist2) #else //template <details::valid_dist_param MinType // , details::valid_dist_param MaxType> template <class p1_type, class Dist1_type, class Dist2_type, class value_t_=util::value_t_bernoulli, class dist_value_t_=util::dist_value_t_default> inline constexpr auto mixture(p1_type p1, Dist1_type Dist1, Dist2_type Dist2) #endif { /*using min_t = details::convert_to_param_t<MinType>; using max_t = details::convert_to_param_t<MaxType>; min_t wrap_min_expr = std::forward<MinType>(min_expr); max_t wrap_max_expr = std::forward<MaxType>(max_expr);*/ using b_type = details::convert_to_param_t<p1_type>; b_type wrap_b_expr = std::forward<b_type>(p1); /*using d1_t = details::convert_to_param_t<Dist1_type>; d1_t wrap_d1_expr = std::forward<d1_t>(Dist1); using d2_t = details::convert_to_param_t<Dist2_type>; d2_t wrap_d2_expr = std::forward<d2_t>(Dist2);*/ return expr::Mixture<b_type, Dist1_type, Dist2_type>(wrap_b_expr, Dist1, Dist2); } /** * Builds a 3 component CONTINUOUS Mixture Distribution when parameters * are all valid continuous distribution parameter types. */ #if __cplusplus <= 201703L template <class p1_type, class Dist1_type, class p2_type, class Dist2_type,class p3_type, class Dist3_type, class value_t_=util::cont_param_t, class dist_value_t_=util::dist_value_t_default> /* , class = std::enable_if_t< details::is_valid_dist_param_v<MinType> && details::is_valid_dist_param_v<MaxType> > > */ inline constexpr auto mixture(p1_type p1, Dist1_type Dist1, p2_type p2, Dist2_type Dist2, p3_type p3, Dist3_type Dist3) #else //template <details::valid_dist_param MinType // , details::valid_dist_param MaxType> template <class p1_type, class Dist1_type, class p2_type, class Dist2_type,class p3_type, class Dist3_type, class value_t_=util::cont_param_t, class dist_value_t_=util::dist_value_t_default> inline constexpr auto mixture(p1_type p1, Dist1_type Dist1, p2_type p2, Dist2_type Dist2, p3_type p3, Dist3_type Dist3) #endif { //wraps constants into an Expression, eg the type "double" gets wrapped into the type Constant (subtype of Expression) using p1_t = details::convert_to_param_t<p1_type>; p1_t wrap_p1_expr = std::forward<p1_type>(p1); using p2_t = details::convert_to_param_t<p2_type>; p2_t wrap_p2_expr = std::forward<p2_type>(p2); using p3_t = details::convert_to_param_t<p3_type>; p3_t wrap_p3_expr = std::forward<p3_type>(p3); return expr::Mixture3<p1_t,Dist1_type,p2_t, Dist2_type, p3_t, Dist3_type>(wrap_p1_expr, Dist1, wrap_p2_expr, Dist2, wrap_p3_expr, Dist3); } /** * Builds a 4 component CONTINUOUS Mixture Distribution when parameters * are all valid continuous distribution parameter types. */ #if __cplusplus <= 201703L template <class p1_type, class Dist1_type, class p2_type, class Dist2_type,class p3_type, class Dist3_type,class p4_type, class Dist4_type, class value_t_=util::cont_param_t, class dist_value_t_=util::dist_value_t_default> /* , class = std::enable_if_t< details::is_valid_dist_param_v<MinType> && details::is_valid_dist_param_v<MaxType> > > */ inline constexpr auto mixture(p1_type p1, Dist1_type Dist1, p2_type p2, Dist2_type Dist2, p3_type p3, Dist3_type Dist3, p4_type p4, Dist4_type Dist4) #else //template <details::valid_dist_param MinType // , details::valid_dist_param MaxType> template <class p1_type, class Dist1_type, class p2_type, class Dist2_type,class p3_type, class Dist3_type,class p4_type, class Dist4_type, class value_t_=util::cont_param_t, class dist_value_t_=util::dist_value_t_default> inline constexpr auto mixture(p1_type p1, Dist1_type Dist1, p2_type p2, Dist2_type Dist2, p3_type p3, Dist3_type Dist3, p4_type p4, Dist4_type Dist4) #endif { //wraps constants into an Expression, eg the type "double" gets wrapped into the type Constant (subtype of Expression) using p1_t = details::convert_to_param_t<p1_type>; p1_t wrap_p1_expr = std::forward<p1_type>(p1); using p2_t = details::convert_to_param_t<p2_type>; p2_t wrap_p2_expr = std::forward<p2_type>(p2); using p3_t = details::convert_to_param_t<p3_type>; p3_t wrap_p3_expr = std::forward<p3_type>(p3); using p4_t = details::convert_to_param_t<p4_type>; p4_t wrap_p4_expr = std::forward<p4_type>(p4); //return expr::Mixture3<p1_type,Dist1_type,p2_type, Dist2_type, p3_type, Dist3_type>(p1, Dist1, p2, Dist2, p3, Dist3); return expr::Mixture4<p1_t,Dist1_type,p2_t, Dist2_type, p3_t, Dist3_type,p4_t, Dist4_type>(wrap_p1_expr, Dist1, wrap_p2_expr, Dist2, wrap_p3_expr, Dist3, wrap_p4_expr, Dist4); } /** * Builds a 3 component DISCRETE Mixture Distribution when parameters * are all valid continuous distribution parameter types. */ #if __cplusplus <= 201703L template <class p1_type, class Dist1_type, class p2_type, class Dist2_type,class p3_type, class Dist3_type, class value_t_=util::disc_param_t, class dist_value_t_=util::dist_value_t_default> /* , class = std::enable_if_t< details::is_valid_dist_param_v<MinType> && details::is_valid_dist_param_v<MaxType> > > */ inline constexpr auto discrete_mixture(p1_type p1, Dist1_type Dist1, p2_type p2, Dist2_type Dist2, p3_type p3, Dist3_type Dist3) #else //template <details::valid_dist_param MinType // , details::valid_dist_param MaxType> template <class p1_type, class Dist1_type, class p2_type, class Dist2_type,class p3_type, class Dist3_type, class value_t_=util::disc_param_t, class dist_value_t_=util::dist_value_t_default> inline constexpr auto discrete_mixture(p1_type p1, Dist1_type Dist1, p2_type p2, Dist2_type Dist2, p3_type p3, Dist3_type Dist3) #endif { //wraps constants into an Expression, eg the type "double" gets wrapped into the type Constant (subtype of Expression) using p1_t = details::convert_to_param_t<p1_type>; p1_t wrap_p1_expr = std::forward<p1_type>(p1); using p2_t = details::convert_to_param_t<p2_type>; p2_t wrap_p2_expr = std::forward<p2_type>(p2); using p3_t = details::convert_to_param_t<p3_type>; p3_t wrap_p3_expr = std::forward<p3_type>(p3); return expr::DiscreteMixture3<p1_t,Dist1_type,p2_t, Dist2_type, p3_t, Dist3_type>(wrap_p1_expr, Dist1, wrap_p2_expr, Dist2, wrap_p3_expr, Dist3); } /** * Builds a Normal expression only when the parameters * are both valid continuous distribution parameter types. * See var_expr.hpp for more information. */ #if __cplusplus <= 201703L template <class MeanType, class StddevType, class ValueT=util::cont_param_t, class DistValueT=util::dist_value_t_default , class = std::enable_if_t< details::is_valid_dist_param_v<MeanType> && details::is_valid_dist_param_v<StddevType> > > inline constexpr auto normal(MeanType&& mean_expr, StddevType&& stddev_expr) #else template <details::valid_dist_param MeanType , details::valid_dist_param StddevType> inline constexpr auto normal(MeanType&& mean_expr, StddevType&& stddev_expr) #endif { using mean_t = details::convert_to_param_t<MeanType>; using stddev_t = details::convert_to_param_t<StddevType>; mean_t wrap_mean_expr = std::forward<MeanType>(mean_expr); stddev_t wrap_stddev_expr = std::forward<StddevType>(stddev_expr); return expr::Normal<mean_t, stddev_t, ValueT, DistValueT>(wrap_mean_expr, wrap_stddev_expr); } /** * Builds a Bernoulli expression only when the parameter * is a valid discrete distribution parameter type. * See var_expr.hpp for more information. */ #if __cplusplus <= 201703L template <class ProbType, class ValueT=util::value_t_bernoulli, class DistValueT=util::dist_value_t_bernoulli , class = std::enable_if_t< details::is_valid_dist_param_v<ProbType> > > inline constexpr auto bernoulli(ProbType&& p_expr) #else template <details::valid_dist_param ProbType> inline constexpr auto bernoulli(ProbType&& p_expr) #endif { using p_t = details::convert_to_param_t<ProbType>; p_t wrap_p_expr = std::forward<ProbType>(p_expr); return expr::Bernoulli<p_t, ValueT, DistValueT>(wrap_p_expr); } /** * Builds a Dirac Delta expression only when the parameters */ #if __cplusplus <= 201703L template <class MeanType, class ValueT=util::cont_param_t, class DistValueT=util::dist_value_t_default , class = std::enable_if_t< details::is_valid_dist_param_v<MeanType> > > inline constexpr auto delta(MeanType&& mean_expr) #else template <details::valid_dist_param MeanType> inline constexpr auto delta(MeanType&& mean_expr) #endif { using mean_t = details::convert_to_param_t<MeanType>; mean_t wrap_mean_expr = std::forward<MeanType>(mean_expr); return expr::Delta<mean_t, ValueT, DistValueT>(wrap_mean_expr); } /** * Builds a 3 component Categorical Distribution */ #if __cplusplus <= 201703L template <class p_type,class value_t_=util::disc_param_t, class dist_value_t_=util::dist_value_t_default> /* , class = std::enable_if_t< details::is_valid_dist_param_v<MinType> && details::is_valid_dist_param_v<MaxType> > > */ inline constexpr auto categorical(p_type p1, p_type p2, p_type p3) #else //template <details::valid_dist_param MinType // , details::valid_dist_param MaxType> template <class p_type, class value_t_=util::disc_param_t, class dist_value_t_=util::dist_value_t_default> inline constexpr auto categorical(p_type p1, p_type p2, p_type p3) #endif { //wraps constants into an Expression, eg the type "double" gets wrapped into the type Constant (subtype of Expression) using p_t = details::convert_to_param_t<p_type>; p_t wrap_p1_expr = std::forward<p_t>(p1); //using p2_t = details::convert_to_param_t<p2_type>; p_t wrap_p2_expr = std::forward<p_t>(p2); //using p3_t = details::convert_to_param_t<p3_type>; p_t wrap_p3_expr = std::forward<p_t>(p3); //return expr::Mixture3<p1_type,Dist1_type,p2_type, Dist2_type, p3_type, Dist3_type>(p1, Dist1, p2, Dist2, p3, Dist3); return expr::Categorical<p_t,value_t_,dist_value_t_>(wrap_p1_expr, wrap_p2_expr, wrap_p3_expr); } #if __cplusplus <= 201703L template <class bool_type, class Dist1_type, class Dist2_type,class value_t_=util::disc_param_t, class dist_value_t_=util::dist_value_t_default> inline constexpr auto if_then_else(bool_type b, Dist1_type d1, Dist2_type d2) #else //template <details::valid_dist_param MinType // , details::valid_dist_param MaxType> template <class bool_type, class Dist1_type, class Dist2_type,class value_t_=util::disc_param_t, class dist_value_t_=util::dist_value_t_default> inline constexpr auto if_then_else(bool_type b, Dist1_type d1, Dist2_type d2) #endif { using b_type = details::convert_to_param_t<bool_type>; b_type wrap_b_expr = std::forward<b_type>(b); //using d1_t = details::convert_to_param_t<Dist1_type>; //d1_t wrap_d1_expr = std::forward<Dist1_type>(d1); //using d2_t = details::convert_to_param_t<Dist2_type>; //d2_t wrap_d2_expr = std::forward<Dist2_type>(d2); //return expr::Mixture3<p1_type,Dist1_type,p2_type, Dist2_type, p3_type, Dist3_type>(p1, Dist1, p2, Dist2, p3, Dist3); return expr::Mixture<b_type,Dist1_type,Dist2_type>(wrap_b_expr, d1, d2); } //////////////////////////////////////////////////////// // Model Expression Builder //////////////////////////////////////////////////////// /** * Builds an EqNode to associate var with dist * only when var is a Variable and dist is a valid distribution expression. * Ex. x |= uniform(0,1) */ template <class VarType, class DistType> inline constexpr auto operator|=( util::Var<VarType>& var, const util::DistExpr<DistType, typename DistType::dist_value_t>& dist) { return expr::EqNode(var.self(), dist.self()); } /** * Builds a GlueNode to "glue" the left expression with the right * only when both parameters are valid model expressions. * Ex. (x |= uniform(0,1), y |= uniform(0, 2)) */ template <class LHSNodeType, class RHSNodeType> inline constexpr auto operator,(const util::ModelExpr<LHSNodeType>& lhs, const util::ModelExpr<RHSNodeType>& rhs) { return expr::GlueNode(lhs.self(), rhs.self()); } //////////////////////////////////////////////////////// // Variable Expression Builder //////////////////////////////////////////////////////// namespace details { #if __cplusplus <= 201703L /** * Concept of valid variable expression parameter * for the operator overloads: * - can be arithmetic type * - if not arithmetic, must be variable expression * or a variable. */ template <class T> inline constexpr bool is_valid_op_param_v = ppl::is_arithmetic_v<std::decay_t<T>> || util::is_var_expr_v<std::decay_t<T>> || util::is_var_v<std::decay_t<T>> ; #else template <class T> concept valid_op_param = ppl::is_arithmetic_v<std::decay_t<T>> || util::var_expr<std::decay_t<T>> || util::var<std::decay_t<T>> ; #endif template <class Op, class LHSType, class RHSType> inline constexpr auto operator_helper(LHSType&& lhs, RHSType&& rhs) { // note: may be reference types if converted to itself using lhs_t = details::convert_to_param_t<LHSType>; using rhs_t = details::convert_to_param_t<RHSType>; lhs_t wrap_lhs_expr = std::forward<LHSType>(lhs); rhs_t wrap_rhs_expr = std::forward<RHSType>(rhs); using binary_t = expr::BinaryOpNode< Op, std::decay_t<lhs_t>, std::decay_t<rhs_t> >; // lhs_t and rhs_t are decayed by node_t return binary_t(wrap_lhs_expr, wrap_rhs_expr); } template <class UnOp, class LHSType> inline constexpr auto unary_operator_helper(LHSType&& lhs) { // note: may be reference types if converted to itself using lhs_t = details::convert_to_param_t<LHSType>; lhs_t wrap_lhs_expr = std::forward<LHSType>(lhs); using unary_t = expr::UnaryOpNode< UnOp, std::decay_t<lhs_t> >; // lhs_t and rhs_t are decayed by node_t return unary_t(wrap_lhs_expr); } } // namespace details /** * Operator overloads, which only check for type-safety. * SFINAE to ensure concepts are placed. */ #if __cplusplus <= 201703L template <class LHSType, class RHSType , class = std::enable_if_t< details::is_not_both_arithmetic_v<LHSType, RHSType> && details::is_valid_op_param_v<LHSType> && details::is_valid_op_param_v<RHSType> > > #else template <details::valid_op_param LHSType , details::valid_op_param RHSType> requires details::not_both_arithmetic<LHSType, RHSType> #endif inline constexpr auto operator+(LHSType&& lhs, RHSType&& rhs) { return details::operator_helper<expr::AddOp>( std::forward<LHSType>(lhs), std::forward<RHSType>(rhs)); } #if __cplusplus <= 201703L template <class LHSType, class RHSType , class = std::enable_if_t< details::is_not_both_arithmetic_v<LHSType, RHSType> && details::is_valid_op_param_v<LHSType> && details::is_valid_op_param_v<RHSType> > > #else template <details::valid_op_param LHSType , details::valid_op_param RHSType> requires details::not_both_arithmetic<LHSType, RHSType> #endif inline constexpr auto operator-(LHSType&& lhs, RHSType&& rhs) { return details::operator_helper<expr::SubOp>( std::forward<LHSType>(lhs), std::forward<RHSType>(rhs)); } #if __cplusplus <= 201703L template <class LHSType, class RHSType , class = std::enable_if_t< details::is_not_both_arithmetic_v<LHSType, RHSType> && details::is_valid_op_param_v<LHSType> && details::is_valid_op_param_v<RHSType> > > #else template <details::valid_op_param LHSType , details::valid_op_param RHSType> requires details::not_both_arithmetic<LHSType, RHSType> #endif inline constexpr auto operator*(LHSType&& lhs, RHSType&& rhs) { return details::operator_helper<expr::MultOp>( std::forward<LHSType>(lhs), std::forward<RHSType>(rhs)); } #if __cplusplus <= 201703L template <class LHSType, class RHSType , class = std::enable_if_t< details::is_not_both_arithmetic_v<LHSType, RHSType> && details::is_valid_op_param_v<LHSType> && details::is_valid_op_param_v<RHSType> > > #else template <details::valid_op_param LHSType , details::valid_op_param RHSType> requires details::not_both_arithmetic<LHSType, RHSType> #endif inline constexpr auto operator/(LHSType&& lhs, RHSType&& rhs) { return details::operator_helper<expr::DivOp>( std::forward<LHSType>(lhs), std::forward<RHSType>(rhs)); } #if __cplusplus <= 201703L template <class LHSType, class RHSType , class = std::enable_if_t< details::is_not_both_arithmetic_v<LHSType, RHSType> && details::is_valid_op_param_v<LHSType> && details::is_valid_op_param_v<RHSType> > > #else template <details::valid_op_param LHSType , details::valid_op_param RHSType> requires details::not_both_arithmetic<LHSType, RHSType> #endif inline constexpr auto max(LHSType&& lhs, RHSType&& rhs) { return details::operator_helper<expr::MaxOp>( std::forward<LHSType>(lhs), std::forward<RHSType>(rhs)); } #if __cplusplus <= 201703L template <class LHSType, class RHSType , class = std::enable_if_t< details::is_not_both_arithmetic_v<LHSType, RHSType> && details::is_valid_op_param_v<LHSType> && details::is_valid_op_param_v<RHSType> > > #else template <details::valid_op_param LHSType , details::valid_op_param RHSType> requires details::not_both_arithmetic<LHSType, RHSType> #endif inline constexpr auto min(LHSType&& lhs, RHSType&& rhs) { return details::operator_helper<expr::MinOp>( std::forward<LHSType>(lhs), std::forward<RHSType>(rhs)); } //heaviside step function used simulate conditional branching #if __cplusplus <= 201703L template <class LHSType , class = std::enable_if_t< //details::is_not_both_arithmetic_v<LHSType, LHSType> && // //details::is_arithmetic_v<LHSType> && details::is_valid_op_param_v<LHSType> > > #else template <details::valid_op_param LHSType> //requires details::not_both_arithmetic<LHSType> #endif inline constexpr auto step(LHSType&& lhs) { return details::unary_operator_helper<expr::StepOp>(std::forward<LHSType>(lhs)); } #if __cplusplus <= 201703L template <class LHSType, class RHSType , class = std::enable_if_t< details::is_not_both_arithmetic_v<LHSType, RHSType> && details::is_valid_op_param_v<LHSType> && details::is_valid_op_param_v<RHSType> > > #else template <details::valid_op_param LHSType , details::valid_op_param RHSType> requires details::not_both_arithmetic<LHSType, RHSType> #endif inline constexpr auto operator>(LHSType&& lhs, RHSType&& rhs) { return details::operator_helper<expr::GTOp>( std::forward<LHSType>(lhs), std::forward<RHSType>(rhs)); } #if __cplusplus <= 201703L template <class LHSType, class RHSType , class = std::enable_if_t< details::is_not_both_arithmetic_v<LHSType, RHSType> && details::is_valid_op_param_v<LHSType> && details::is_valid_op_param_v<RHSType> > > #else template <details::valid_op_param LHSType , details::valid_op_param RHSType> requires details::not_both_arithmetic<LHSType, RHSType> #endif inline constexpr auto operator<(LHSType&& lhs, RHSType&& rhs) { return details::operator_helper<expr::LTOp>( std::forward<LHSType>(lhs), std::forward<RHSType>(rhs)); } #if __cplusplus <= 201703L template <class LHSType, class RHSType , class = std::enable_if_t< details::is_not_both_arithmetic_v<LHSType, RHSType> && details::is_valid_op_param_v<LHSType> && details::is_valid_op_param_v<RHSType> > > #else template <details::valid_op_param LHSType , details::valid_op_param RHSType> requires details::not_both_arithmetic<LHSType, RHSType> #endif inline constexpr auto operator>=(LHSType&& lhs, RHSType&& rhs) { return details::operator_helper<expr::GTEOp>( std::forward<LHSType>(lhs), std::forward<RHSType>(rhs)); } #if __cplusplus <= 201703L template <class LHSType, class RHSType , class = std::enable_if_t< details::is_not_both_arithmetic_v<LHSType, RHSType> && details::is_valid_op_param_v<LHSType> && details::is_valid_op_param_v<RHSType> > > #else template <details::valid_op_param LHSType , details::valid_op_param RHSType> requires details::not_both_arithmetic<LHSType, RHSType> #endif inline constexpr auto operator<=(LHSType&& lhs, RHSType&& rhs) { return details::operator_helper<expr::LTEOp>( std::forward<LHSType>(lhs), std::forward<RHSType>(rhs)); } #if __cplusplus <= 201703L template <class LHSType, class RHSType , class = std::enable_if_t< details::is_not_both_arithmetic_v<LHSType, RHSType> && details::is_valid_op_param_v<LHSType> && details::is_valid_op_param_v<RHSType> > > #else template <details::valid_op_param LHSType , details::valid_op_param RHSType> requires details::not_both_arithmetic<LHSType, RHSType> #endif inline constexpr auto operator==(LHSType&& lhs, RHSType&& rhs) { return details::operator_helper<expr::EQOp>( std::forward<LHSType>(lhs), std::forward<RHSType>(rhs)); } #if __cplusplus <= 201703L template <class LHSType, class RHSType , class = std::enable_if_t< details::is_not_both_arithmetic_v<LHSType, RHSType> && details::is_valid_op_param_v<LHSType> && details::is_valid_op_param_v<RHSType> > > #else template <details::valid_op_param LHSType , details::valid_op_param RHSType> requires details::not_both_arithmetic<LHSType, RHSType> #endif inline constexpr auto Sqrt(LHSType&& lhs, RHSType&& rhs) { return details::operator_helper<expr::SqrtOp>( std::forward<LHSType>(lhs), std::forward<RHSType>(rhs)); } } // namespace ppl
//----------------------------------*-C++-*----------------------------------// /** * @file Equation_SC_MOC.i.hh * @author Jeremy Roberts * @date Mar 31, 2012 * @brief Equation_SC_MOC inline member definitions. */ //---------------------------------------------------------------------------// #ifndef detran_EQUATION_SC_MOC_I_HH_ #define detran_EQUATION_SC_MOC_I_HH_ #include <iostream> namespace detran { //---------------------------------------------------------------------------// inline void Equation_SC_MOC::solve(const size_t region, const double length, const double width, moments_type &source, double &psi_in, double &psi_out, moments_type &phi, angular_flux_type &psi) { using std::cout; using std::endl; // Preconditions. Require(region < d_mesh->number_cells()); double sigma = d_material->sigma_t(d_mat_map[region], d_g); double length_over_sin = length * d_inv_sin[d_polar]; double inv_volume = 1.0 / d_mesh->volume(region); // Coefficients from Hebert. double A = std::exp(-sigma * length_over_sin); double B = (1.0 - A) / sigma; double C = (length_over_sin / sigma) * (1.0 - B / length_over_sin); //double C = (length_over_sin / sigma) * (1.0 - (1.0-A)/(length_over_sin*sigma)); // Segment outgoing angular flux. psi_out = A * psi_in + B * source[region]; // if (!(source[region] > 0.0 ? psi_out > 0.0 : true)) // { // cout << " region = " << region << endl; // cout << " psi_in = " << psi_in << endl; // cout << " psi_out = " << psi_out << endl; // cout << " sigma = " << sigma << endl; // cout << " L / sin = " << length_over_sin << endl; // cout << " A = " << A << endl; // cout << " B = " << B << endl; // cout << " source = " << source[region] << endl; // } // Ensure(source[region] > 0.0 ? psi_out > 0.0 : true); // Segment average angular flux. double psi_average = (1.0 / length_over_sin) * (B * psi_in + C * source[region]); // cout << " t = " << length_over_sin << endl; // cout << " A = " << A << endl; // cout << " B = " << B << endl; // cout << " C = " << C << endl; // cout << " source = " << source[region] << endl; // cout << " psi_in = " << psi_in << endl; // cout << " psi_out = " << psi_out << endl; // cout << " psi_seg = " << psi_average << endl; // cout << " length = " << length << endl; // cout << " space = " << d_spacing << endl; // Contribution to region average angular flux. psi_average *= width * length * inv_volume; // Contribution to region average scalar flux. phi[region] += d_quadrature->weight(d_angle) * psi_average; // cout << " psi_reg = " << psi_average << endl; // cout << " weight = " << d_quadrature->weight(d_angle) << endl; // cout << " phi_reg = " << phi[region] << endl; // Store angular flux if needed. if (d_update_psi) psi[region] += psi_average; } } // end namespace detran #endif /* detran_EQUATION_SC_MOC_I_HH_ */ //---------------------------------------------------------------------------// // end of Equation_SC_MOC.i.hh //---------------------------------------------------------------------------//
/* * Copyright (c) 2018-2022, Andreas Kling <kling@serenityos.org> * Copyright (c) 2022, Adam Hodgen <ant1441@gmail.com> * * SPDX-License-Identifier: BSD-2-Clause */ #include <LibWeb/DOM/Document.h> #include <LibWeb/DOM/Event.h> #include <LibWeb/DOM/ShadowRoot.h> #include <LibWeb/DOM/Text.h> #include <LibWeb/HTML/BrowsingContext.h> #include <LibWeb/HTML/EventNames.h> #include <LibWeb/HTML/HTMLFormElement.h> #include <LibWeb/HTML/HTMLInputElement.h> #include <LibWeb/Layout/BlockContainer.h> #include <LibWeb/Layout/ButtonBox.h> #include <LibWeb/Layout/CheckBox.h> #include <LibWeb/Layout/RadioButton.h> namespace Web::HTML { HTMLInputElement::HTMLInputElement(DOM::Document& document, DOM::QualifiedName qualified_name) : FormAssociatedElement(document, move(qualified_name)) { } HTMLInputElement::~HTMLInputElement() { } void HTMLInputElement::did_click_button(Badge<Painting::ButtonPaintable>) { // FIXME: This should be a PointerEvent. dispatch_event(DOM::Event::create(EventNames::click)); if (type() == "submit") { if (auto* form = first_ancestor_of_type<HTMLFormElement>()) { form->submit_form(this); } return; } } void HTMLInputElement::did_click_checkbox(Badge<Painting::CheckBoxPaintable>) { // FIXME: This should be a PointerEvent. auto click_event = DOM::Event::create(EventNames::click); click_event->set_bubbles(true); dispatch_event(move(click_event)); } RefPtr<Layout::Node> HTMLInputElement::create_layout_node(NonnullRefPtr<CSS::StyleProperties> style) { if (type() == "hidden") return nullptr; if (type() == "submit" || type() == "button" || type() == "reset") return adopt_ref(*new Layout::ButtonBox(document(), *this, move(style))); if (type() == "checkbox") return adopt_ref(*new Layout::CheckBox(document(), *this, move(style))); if (type() == "radio") return adopt_ref(*new Layout::RadioButton(document(), *this, move(style))); create_shadow_tree_if_needed(); auto layout_node = adopt_ref(*new Layout::BlockContainer(document(), this, move(style))); layout_node->set_inline(true); return layout_node; } void HTMLInputElement::set_checked(bool checked, ChangeSource change_source, ShouldRunActivationBehavior should_run_activation_behavior) { if (m_checked == checked) return; // The dirty checkedness flag must be initially set to false when the element is created, // and must be set to true whenever the user interacts with the control in a way that changes the checkedness. if (change_source == ChangeSource::User) m_dirty_checkedness = true; m_checked = checked; if (layout_node()) layout_node()->set_needs_display(); if (should_run_activation_behavior == ShouldRunActivationBehavior::Yes) run_activation_behavior(); } void HTMLInputElement::run_activation_behavior() { // The activation behavior for input elements are these steps: // FIXME: 1. If this element is not mutable and is not in the Checkbox state and is not in the Radio state, then return. // 2. Run this element's input activation behavior, if any, and do nothing otherwise. run_input_activation_behavior(); } // https://html.spec.whatwg.org/multipage/input.html#input-activation-behavior void HTMLInputElement::run_input_activation_behavior() { if (type() == "checkbox") { // 1. If the element is not connected, then return. if (!is_connected()) return; // 2. Fire an event named input at the element with the bubbles and composed attributes initialized to true. auto input_event = DOM::Event::create(HTML::EventNames::input); input_event->set_bubbles(true); input_event->set_composed(true); dispatch_event(move(input_event)); // 3. Fire an event named change at the element with the bubbles attribute initialized to true. auto change_event = DOM::Event::create(HTML::EventNames::change); change_event->set_bubbles(true); dispatch_event(move(change_event)); } else { dispatch_event(DOM::Event::create(EventNames::change)); } } void HTMLInputElement::did_edit_text_node(Badge<BrowsingContext>) { // NOTE: This is a bit ad-hoc, but basically implements part of "4.10.5.5 Common event behaviors" // https://html.spec.whatwg.org/multipage/input.html#common-input-element-events queue_an_element_task(HTML::Task::Source::UserInteraction, [this] { auto input_event = DOM::Event::create(HTML::EventNames::input); input_event->set_bubbles(true); input_event->set_composed(true); dispatch_event(move(input_event)); // FIXME: This should only fire when the input is "committed", whatever that means. auto change_event = DOM::Event::create(HTML::EventNames::change); change_event->set_bubbles(true); dispatch_event(move(change_event)); }); } String HTMLInputElement::value() const { if (m_text_node) return m_text_node->data(); return default_value(); } void HTMLInputElement::set_value(String value) { auto sanitised_value = value_sanitization_algorithm(move(value)); if (m_text_node) { m_text_node->set_data(sanitised_value); return; } set_attribute(HTML::AttributeNames::value, sanitised_value); } void HTMLInputElement::create_shadow_tree_if_needed() { if (shadow_root()) return; // FIXME: This assumes that we want a text box. Is that always true? auto shadow_root = adopt_ref(*new DOM::ShadowRoot(document(), *this)); auto initial_value = attribute(HTML::AttributeNames::value); if (initial_value.is_null()) initial_value = String::empty(); auto element = document().create_element(HTML::TagNames::div).release_value(); element->set_attribute(HTML::AttributeNames::style, "white-space: pre; padding-top: 1px; padding-bottom: 1px; padding-left: 2px; padding-right: 2px"); m_text_node = adopt_ref(*new DOM::Text(document(), initial_value)); m_text_node->set_always_editable(true); m_text_node->set_owner_input_element({}, *this); element->append_child(*m_text_node); shadow_root->append_child(move(element)); set_shadow_root(move(shadow_root)); } void HTMLInputElement::did_receive_focus() { auto* browsing_context = document().browsing_context(); if (!browsing_context) return; if (!m_text_node) return; browsing_context->set_cursor_position(DOM::Position { *m_text_node, 0 }); } bool HTMLInputElement::is_focusable() const { return m_text_node; } void HTMLInputElement::parse_attribute(FlyString const& name, String const& value) { FormAssociatedElement::parse_attribute(name, value); if (name == HTML::AttributeNames::checked) { // When the checked content attribute is added, if the control does not have dirty checkedness, // the user agent must set the checkedness of the element to true if (!m_dirty_checkedness) set_checked(true, ChangeSource::Programmatic, ShouldRunActivationBehavior::No); } } void HTMLInputElement::did_remove_attribute(FlyString const& name) { FormAssociatedElement::did_remove_attribute(name); if (name == HTML::AttributeNames::checked) { // When the checked content attribute is removed, if the control does not have dirty checkedness, // the user agent must set the checkedness of the element to false. if (!m_dirty_checkedness) set_checked(false, ChangeSource::Programmatic, ShouldRunActivationBehavior::No); } } String HTMLInputElement::type() const { auto value = attribute(HTML::AttributeNames::type); #define __ENUMERATE_HTML_INPUT_TYPE_ATTRIBUTE(keyword, _) \ if (value.equals_ignoring_case(#keyword)) \ return #keyword; ENUMERATE_HTML_INPUT_TYPE_ATTRIBUTES #undef __ENUMERATE_HTML_INPUT_TYPE_ATTRIBUTE // The missing value default and the invalid value default are the Text state. // https://html.spec.whatwg.org/multipage/input.html#the-input-element:missing-value-default // https://html.spec.whatwg.org/multipage/input.html#the-input-element:invalid-value-default return "text"; } HTMLInputElement::TypeAttributeState HTMLInputElement::type_state() const { auto value = attribute(HTML::AttributeNames::type); #define __ENUMERATE_HTML_INPUT_TYPE_ATTRIBUTE(keyword, state) \ if (value.equals_ignoring_case(#keyword)) \ return HTMLInputElement::TypeAttributeState::state; ENUMERATE_HTML_INPUT_TYPE_ATTRIBUTES #undef __ENUMERATE_HTML_INPUT_TYPE_ATTRIBUTE // The missing value default and the invalid value default are the Text state. // https://html.spec.whatwg.org/multipage/input.html#the-input-element:missing-value-default // https://html.spec.whatwg.org/multipage/input.html#the-input-element:invalid-value-default return HTMLInputElement::TypeAttributeState::Text; } void HTMLInputElement::set_type(String const& type) { set_attribute(HTML::AttributeNames::type, type); } // https://html.spec.whatwg.org/multipage/input.html#value-sanitization-algorithm String HTMLInputElement::value_sanitization_algorithm(String value) const { if (type_state() == HTMLInputElement::TypeAttributeState::Text || type_state() == HTMLInputElement::TypeAttributeState::Search || type_state() == HTMLInputElement::TypeAttributeState::Telephone || type_state() == HTMLInputElement::TypeAttributeState::Password) { // Strip newlines from the value. if (value.contains('\r') || value.contains('\n')) { StringBuilder builder; for (auto c : value) { if (!(c == '\r' || c == '\n')) builder.append(c); } return builder.to_string(); } } else if (type_state() == HTMLInputElement::TypeAttributeState::URL) { // Strip newlines from the value, then strip leading and trailing ASCII whitespace from the value. if (value.contains('\r') || value.contains('\n')) { StringBuilder builder; for (auto c : value) { if (!(c == '\r' || c == '\n')) builder.append(c); } return builder.to_string().trim_whitespace(); } } else if (type_state() == HTMLInputElement::TypeAttributeState::Number) { // If the value of the element is not a valid floating-point number, then set it to the empty string instead. char* end_ptr; auto val = strtod(value.characters(), &end_ptr); if (!isfinite(val) || *end_ptr) return ""; } // FIXME: Implement remaining value sanitation algorithms return value; } }
#include "config.h" #include "log.h" string Config::conf_path; CONF_T Config::conf; string Config::ext_name; void Config::setConfFile(string file_path){ conf_path = file_path; } void Config::loadConf(){ ifstream cnf_file; char line[200]; string cur_sec; string cur_key; string cur_val; int process = PARSE_INIT; int val_quote = 0; cnf_file.open(conf_path.c_str()); if(!cnf_file.is_open()){ cerr << "fail to open config file. path is " << conf_path << endl; log_error("fail to open config file. path is %s" , conf_path.c_str()); exit(EXIT_FAILURE); } while(cnf_file.good() && !cnf_file.eof()){ memset(line,'\0',sizeof(line)); val_quote = 0; process = PARSE_INIT; cur_key.clear(); cur_val.clear(); cnf_file.getline(line,sizeof(line)); for(int i = PARSE_INIT; i < sizeof(line); i++){ if(process == PARSE_INIT && line[i] == ';'){ break; }else if(process == PARSE_INIT && line[i] <= 32){ continue; }else if(process == PARSE_INIT && line[i] == '['){ process = PARSE_SECTION; cur_sec.clear(); }else if(process == PARSE_SECTION && line[i] == ']'){ break; }else if(process == PARSE_SECTION){ cur_sec += line[i]; }else if(process == PARSE_INIT && line[i] > 32){ process = PARSE_KEY; cur_key.clear(); cur_key += line[i]; }else if(process == PARSE_KEY && line[i] == '='){ process = PARSE_VALUE; }else if(process == PARSE_KEY && line[i] > 32 ){ cur_key += line[i]; }else if(process == PARSE_VALUE && line[i] <= 32 && val_quote == 0){ continue; }else if(process == PARSE_VALUE && line[i] == '"' && val_quote == 0){ val_quote = 1; continue; }else if(process == PARSE_VALUE && line[i] == '"' && val_quote == 1){ break; }else if(process == PARSE_VALUE){ cur_val += line[i]; }else if(line[i] == '\0'){ break; } } if(!cur_key.empty() && !cur_val.empty()){ conf[cur_sec][cur_key] = cur_val; } if (cur_sec != "kvproxy" && cur_key == "extension"){ ext_name = cur_sec; } } if(!cnf_file.eof()){ cerr << "fail to parse config file. path is " << conf_path << endl; log_error("fail to parse config file. path is %s" , conf_path.c_str()); exit(EXIT_FAILURE); } } string Config::getConfStr(string section, string key){ if(section.empty() || key.empty() || conf[section][key].empty()){ return ""; }else{ return conf[section][key]; } } map<string, string> Config::getConfStr(string section){ map<string, string> ret; map<string, string>::iterator it; if(section.empty() || conf[section].empty()){ return ret; }else{ for(it = conf[section].begin(); it != conf[section].end(); it++){ ret[it->first] = it->second; } } return ret; } int Config::getConfInt(string section, string key){ int val; if(section.empty() || key.empty() || conf[section][key].empty()){ return 0; }else{ sscanf(conf[section][key].c_str(),"%d",&val); return val; } } map<string, int> Config::getConfInt(string section){ int val; map<string, int> ret; CONF_T::mapped_type::iterator it; if(section.empty() || conf[section].empty()){ return ret; }else{ for(it = conf[section].begin(); it != conf[section].end(); it++){ sscanf(conf[section][it->first].c_str(),"%d",&val); ret[it->first] = val; } return ret; } } bool Config::getConfBool(string section, string key){ string val; if(section.empty() || key.empty() || conf[section][key].empty()){ return false; } val = conf[section][key]; if(val == "on" || val == "1" || val == "yes"){ return true; }else{ return false; } } map<string, bool> Config::getConfBool(string section){ string val; map<string, bool> ret; CONF_T::mapped_type::iterator it; if(section.empty() || conf[section].empty()){ return ret; } for(it = conf[section].begin(); it != conf[section].end(); it++){ val = conf[section][it->first]; if(val == "on" || val == "1" || val == "yes"){ ret[it->first] = true; }else{ ret[it->first] = false; } } return ret; } string Config::getExtName(){ return ext_name; }
// Generated by Haxe 4.2.1+bf9ff69 #include <hxcpp.h> #ifndef INCLUDED___ASSET__flixel_flixel_ui_img_finger_big_png #include <__ASSET__flixel_flixel_ui_img_finger_big_png.h> #endif #ifndef INCLUDED_haxe_Resource #include <haxe/Resource.h> #endif #ifndef INCLUDED_haxe_io_Bytes #include <haxe/io/Bytes.h> #endif #ifndef INCLUDED_lime_graphics_Image #include <lime/graphics/Image.h> #endif #ifndef INCLUDED_lime_graphics_ImageBuffer #include <lime/graphics/ImageBuffer.h> #endif #ifndef INCLUDED_lime_graphics_ImageType #include <lime/graphics/ImageType.h> #endif HX_DEFINE_STACK_FRAME(_hx_pos_c7bf567bde4e087b_346_new,"__ASSET__flixel_flixel_ui_img_finger_big_png","new",0x847d671d,"__ASSET__flixel_flixel_ui_img_finger_big_png.new","lime/_internal/macros/AssetsMacro.hx",346,0xc651f030) HX_LOCAL_STACK_FRAME(_hx_pos_15bb0b3ecb13e771_686_boot,"__ASSET__flixel_flixel_ui_img_finger_big_png","boot",0x6155d2d5,"__ASSET__flixel_flixel_ui_img_finger_big_png.boot","ManifestResources.hx",686,0xf77aa668) void __ASSET__flixel_flixel_ui_img_finger_big_png_obj::__construct( ::lime::graphics::ImageBuffer buffer, ::Dynamic offsetX, ::Dynamic offsetY, ::Dynamic width, ::Dynamic height, ::Dynamic color, ::lime::graphics::ImageType type){ HX_STACKFRAME(&_hx_pos_c7bf567bde4e087b_346_new) HXLINE( 375) super::__construct(null(),null(),null(),null(),null(),null(),null()); HXLINE( 377) this->_hx___fromBytes(::haxe::Resource_obj::getBytes(::__ASSET__flixel_flixel_ui_img_finger_big_png_obj::resourceName),null()); } Dynamic __ASSET__flixel_flixel_ui_img_finger_big_png_obj::__CreateEmpty() { return new __ASSET__flixel_flixel_ui_img_finger_big_png_obj; } void *__ASSET__flixel_flixel_ui_img_finger_big_png_obj::_hx_vtable = 0; Dynamic __ASSET__flixel_flixel_ui_img_finger_big_png_obj::__Create(::hx::DynamicArray inArgs) { ::hx::ObjectPtr< __ASSET__flixel_flixel_ui_img_finger_big_png_obj > _hx_result = new __ASSET__flixel_flixel_ui_img_finger_big_png_obj(); _hx_result->__construct(inArgs[0],inArgs[1],inArgs[2],inArgs[3],inArgs[4],inArgs[5],inArgs[6]); return _hx_result; } bool __ASSET__flixel_flixel_ui_img_finger_big_png_obj::_hx_isInstanceOf(int inClassId) { if (inClassId<=(int)0x33f052f7) { return inClassId==(int)0x00000001 || inClassId==(int)0x33f052f7; } else { return inClassId==(int)0x766d19ef; } } ::String __ASSET__flixel_flixel_ui_img_finger_big_png_obj::resourceName; ::hx::ObjectPtr< __ASSET__flixel_flixel_ui_img_finger_big_png_obj > __ASSET__flixel_flixel_ui_img_finger_big_png_obj::__new( ::lime::graphics::ImageBuffer buffer, ::Dynamic offsetX, ::Dynamic offsetY, ::Dynamic width, ::Dynamic height, ::Dynamic color, ::lime::graphics::ImageType type) { ::hx::ObjectPtr< __ASSET__flixel_flixel_ui_img_finger_big_png_obj > __this = new __ASSET__flixel_flixel_ui_img_finger_big_png_obj(); __this->__construct(buffer,offsetX,offsetY,width,height,color,type); return __this; } ::hx::ObjectPtr< __ASSET__flixel_flixel_ui_img_finger_big_png_obj > __ASSET__flixel_flixel_ui_img_finger_big_png_obj::__alloc(::hx::Ctx *_hx_ctx, ::lime::graphics::ImageBuffer buffer, ::Dynamic offsetX, ::Dynamic offsetY, ::Dynamic width, ::Dynamic height, ::Dynamic color, ::lime::graphics::ImageType type) { __ASSET__flixel_flixel_ui_img_finger_big_png_obj *__this = (__ASSET__flixel_flixel_ui_img_finger_big_png_obj*)(::hx::Ctx::alloc(_hx_ctx, sizeof(__ASSET__flixel_flixel_ui_img_finger_big_png_obj), true, "__ASSET__flixel_flixel_ui_img_finger_big_png")); *(void **)__this = __ASSET__flixel_flixel_ui_img_finger_big_png_obj::_hx_vtable; __this->__construct(buffer,offsetX,offsetY,width,height,color,type); return __this; } __ASSET__flixel_flixel_ui_img_finger_big_png_obj::__ASSET__flixel_flixel_ui_img_finger_big_png_obj() { } bool __ASSET__flixel_flixel_ui_img_finger_big_png_obj::__GetStatic(const ::String &inName, Dynamic &outValue, ::hx::PropertyAccess inCallProp) { switch(inName.length) { case 12: if (HX_FIELD_EQ(inName,"resourceName") ) { outValue = ( resourceName ); return true; } } return false; } bool __ASSET__flixel_flixel_ui_img_finger_big_png_obj::__SetStatic(const ::String &inName,Dynamic &ioValue,::hx::PropertyAccess inCallProp) { switch(inName.length) { case 12: if (HX_FIELD_EQ(inName,"resourceName") ) { resourceName=ioValue.Cast< ::String >(); return true; } } return false; } #ifdef HXCPP_SCRIPTABLE static ::hx::StorageInfo *__ASSET__flixel_flixel_ui_img_finger_big_png_obj_sMemberStorageInfo = 0; static ::hx::StaticInfo __ASSET__flixel_flixel_ui_img_finger_big_png_obj_sStaticStorageInfo[] = { {::hx::fsString,(void *) &__ASSET__flixel_flixel_ui_img_finger_big_png_obj::resourceName,HX_("resourceName",39,7a,62,90)}, { ::hx::fsUnknown, 0, null()} }; #endif static void __ASSET__flixel_flixel_ui_img_finger_big_png_obj_sMarkStatics(HX_MARK_PARAMS) { HX_MARK_MEMBER_NAME(__ASSET__flixel_flixel_ui_img_finger_big_png_obj::resourceName,"resourceName"); }; #ifdef HXCPP_VISIT_ALLOCS static void __ASSET__flixel_flixel_ui_img_finger_big_png_obj_sVisitStatics(HX_VISIT_PARAMS) { HX_VISIT_MEMBER_NAME(__ASSET__flixel_flixel_ui_img_finger_big_png_obj::resourceName,"resourceName"); }; #endif ::hx::Class __ASSET__flixel_flixel_ui_img_finger_big_png_obj::__mClass; static ::String __ASSET__flixel_flixel_ui_img_finger_big_png_obj_sStaticFields[] = { HX_("resourceName",39,7a,62,90), ::String(null()) }; void __ASSET__flixel_flixel_ui_img_finger_big_png_obj::__register() { __ASSET__flixel_flixel_ui_img_finger_big_png_obj _hx_dummy; __ASSET__flixel_flixel_ui_img_finger_big_png_obj::_hx_vtable = *(void **)&_hx_dummy; ::hx::Static(__mClass) = new ::hx::Class_obj(); __mClass->mName = HX_("__ASSET__flixel_flixel_ui_img_finger_big_png",ab,94,62,49); __mClass->mSuper = &super::__SGetClass(); __mClass->mConstructEmpty = &__CreateEmpty; __mClass->mConstructArgs = &__Create; __mClass->mGetStaticField = &__ASSET__flixel_flixel_ui_img_finger_big_png_obj::__GetStatic; __mClass->mSetStaticField = &__ASSET__flixel_flixel_ui_img_finger_big_png_obj::__SetStatic; __mClass->mMarkFunc = __ASSET__flixel_flixel_ui_img_finger_big_png_obj_sMarkStatics; __mClass->mStatics = ::hx::Class_obj::dupFunctions(__ASSET__flixel_flixel_ui_img_finger_big_png_obj_sStaticFields); __mClass->mMembers = ::hx::Class_obj::dupFunctions(0 /* sMemberFields */); __mClass->mCanCast = ::hx::TCanCast< __ASSET__flixel_flixel_ui_img_finger_big_png_obj >; #ifdef HXCPP_VISIT_ALLOCS __mClass->mVisitFunc = __ASSET__flixel_flixel_ui_img_finger_big_png_obj_sVisitStatics; #endif #ifdef HXCPP_SCRIPTABLE __mClass->mMemberStorageInfo = __ASSET__flixel_flixel_ui_img_finger_big_png_obj_sMemberStorageInfo; #endif #ifdef HXCPP_SCRIPTABLE __mClass->mStaticStorageInfo = __ASSET__flixel_flixel_ui_img_finger_big_png_obj_sStaticStorageInfo; #endif ::hx::_hx_RegisterClass(__mClass->mName, __mClass); } void __ASSET__flixel_flixel_ui_img_finger_big_png_obj::__boot() { { HX_STACKFRAME(&_hx_pos_15bb0b3ecb13e771_686_boot) HXDLIN( 686) resourceName = HX_("__ASSET__:image___ASSET__flixel_flixel_ui_img_finger_big_png",39,e2,df,0d); } }
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2015 The Bitcoin Core developers // Copyright (c) 2009-2020 The Dash Core developers // Copyright (c) 2019-2020 The Abosom 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/abosom-config.h" #endif #include "chainparamsbase.h" #include "clientversion.h" #include "rpc/client.h" #include "rpc/protocol.h" #include "util.h" #include "utilstrencodings.h" #include <boost/filesystem/operations.hpp> #include <stdio.h> #include <event2/buffer.h> #include <event2/keyvalq_struct.h> #include "support/events.h" #include <univalue.h> static const char DEFAULT_RPCCONNECT[] = "127.0.0.1"; static const int DEFAULT_HTTP_CLIENT_TIMEOUT=900; static const bool DEFAULT_NAMED=false; static const int CONTINUE_EXECUTION=-1; std::string HelpMessageCli() { std::string strUsage; strUsage += HelpMessageGroup(_("Options:")); strUsage += HelpMessageOpt("-?", _("This help message")); strUsage += HelpMessageOpt("-conf=<file>", strprintf(_("Specify configuration file (default: %s)"), BITCOIN_CONF_FILENAME)); strUsage += HelpMessageOpt("-datadir=<dir>", _("Specify data directory")); AppendParamsHelpMessages(strUsage); strUsage += HelpMessageOpt("-named", strprintf(_("Pass named instead of positional arguments (default: %s)"), DEFAULT_NAMED)); strUsage += HelpMessageOpt("-rpcconnect=<ip>", strprintf(_("Send commands to node running on <ip> (default: %s)"), DEFAULT_RPCCONNECT)); strUsage += HelpMessageOpt("-rpcport=<port>", strprintf(_("Connect to JSON-RPC on <port> (default: %u or testnet: %u)"), BaseParams(CBaseChainParams::MAIN).RPCPort(), BaseParams(CBaseChainParams::TESTNET).RPCPort())); strUsage += HelpMessageOpt("-rpcwait", _("Wait for RPC server to start")); strUsage += HelpMessageOpt("-rpcuser=<user>", _("Username for JSON-RPC connections")); strUsage += HelpMessageOpt("-rpcpassword=<pw>", _("Password for JSON-RPC connections")); strUsage += HelpMessageOpt("-rpcclienttimeout=<n>", strprintf(_("Timeout during HTTP requests (default: %d)"), DEFAULT_HTTP_CLIENT_TIMEOUT)); strUsage += HelpMessageOpt("-stdin", _("Read extra arguments from standard input, one per line until EOF/Ctrl-D (recommended for sensitive information such as passphrases)")); return strUsage; } ////////////////////////////////////////////////////////////////////////////// // // Start // // // Exception thrown on connection error. This error is used to determine // when to wait if -rpcwait is given. // class CConnectionFailed : public std::runtime_error { public: explicit inline CConnectionFailed(const std::string& msg) : std::runtime_error(msg) {} }; // // This function returns either one of EXIT_ codes when it's expected to stop the process or // CONTINUE_EXECUTION when it's expected to continue further. // static int AppInitRPC(int argc, char* argv[]) { // // Parameters // ParseParameters(argc, argv); if (argc<2 || IsArgSet("-?") || IsArgSet("-h") || IsArgSet("-help") || IsArgSet("-version")) { std::string strUsage = strprintf(_("%s RPC client version"), _(PACKAGE_NAME)) + " " + FormatFullVersion() + "\n"; if (!IsArgSet("-version")) { strUsage += "\n" + _("Usage:") + "\n" + " abosom-cli [options] <command> [params] " + strprintf(_("Send command to %s"), _(PACKAGE_NAME)) + "\n" + " abosom-cli [options] -named <command> [name=value] ... " + strprintf(_("Send command to %s (with named arguments)"), _(PACKAGE_NAME)) + "\n" + " abosom-cli [options] help " + _("List commands") + "\n" + " abosom-cli [options] help <command> " + _("Get help for a command") + "\n"; strUsage += "\n" + HelpMessageCli(); } fprintf(stdout, "%s", strUsage.c_str()); if (argc < 2) { fprintf(stderr, "Error: too few parameters\n"); return EXIT_FAILURE; } return EXIT_SUCCESS; } bool datadirFromCmdLine = IsArgSet("-datadir"); if (datadirFromCmdLine && !boost::filesystem::is_directory(GetDataDir(false))) { fprintf(stderr, "Error: Specified data directory \"%s\" does not exist.\n", GetArg("-datadir", "").c_str()); return EXIT_FAILURE; } try { ReadConfigFile(GetArg("-conf", BITCOIN_CONF_FILENAME)); } catch (const std::exception& e) { fprintf(stderr,"Error reading configuration file: %s\n", e.what()); return EXIT_FAILURE; } if (!datadirFromCmdLine && !boost::filesystem::is_directory(GetDataDir(false))) { fprintf(stderr, "Error: Specified data directory \"%s\" from config file does not exist.\n", GetArg("-datadir", "").c_str()); return EXIT_FAILURE; } // Check for -testnet or -regtest parameter (BaseParams() calls are only valid after this clause) try { SelectBaseParams(ChainNameFromCommandLine()); } catch (const std::exception& e) { fprintf(stderr, "Error: %s\n", e.what()); return EXIT_FAILURE; } if (GetBoolArg("-rpcssl", false)) { fprintf(stderr, "Error: SSL mode for RPC (-rpcssl) is no longer supported.\n"); return EXIT_FAILURE; } return CONTINUE_EXECUTION; } /** Reply structure for request_done to fill in */ struct HTTPReply { HTTPReply(): status(0), error(-1) {} int status; int error; std::string body; }; const char *http_errorstring(int code) { switch(code) { #if LIBEVENT_VERSION_NUMBER >= 0x02010300 case EVREQ_HTTP_TIMEOUT: return "timeout reached"; case EVREQ_HTTP_EOF: return "EOF reached"; case EVREQ_HTTP_INVALID_HEADER: return "error while reading header, or invalid header"; case EVREQ_HTTP_BUFFER_ERROR: return "error encountered while reading or writing"; case EVREQ_HTTP_REQUEST_CANCEL: return "request was canceled"; case EVREQ_HTTP_DATA_TOO_LONG: return "response body is larger than allowed"; #endif default: return "unknown"; } } static void http_request_done(struct evhttp_request *req, void *ctx) { HTTPReply *reply = static_cast<HTTPReply*>(ctx); if (req == NULL) { /* If req is NULL, it means an error occurred while connecting: the * error code will have been passed to http_error_cb. */ reply->status = 0; return; } reply->status = evhttp_request_get_response_code(req); struct evbuffer *buf = evhttp_request_get_input_buffer(req); if (buf) { size_t size = evbuffer_get_length(buf); const char *data = (const char*)evbuffer_pullup(buf, size); if (data) reply->body = std::string(data, size); evbuffer_drain(buf, size); } } #if LIBEVENT_VERSION_NUMBER >= 0x02010300 static void http_error_cb(enum evhttp_request_error err, void *ctx) { HTTPReply *reply = static_cast<HTTPReply*>(ctx); reply->error = err; } #endif UniValue CallRPC(const std::string& strMethod, const UniValue& params) { std::string host = GetArg("-rpcconnect", DEFAULT_RPCCONNECT); int port = GetArg("-rpcport", BaseParams().RPCPort()); // Obtain event base raii_event_base base = obtain_event_base(); // Synchronously look up hostname raii_evhttp_connection evcon = obtain_evhttp_connection_base(base.get(), host, port); evhttp_connection_set_timeout(evcon.get(), GetArg("-rpcclienttimeout", DEFAULT_HTTP_CLIENT_TIMEOUT)); HTTPReply response; raii_evhttp_request req = obtain_evhttp_request(http_request_done, (void*)&response); if (req == NULL) throw std::runtime_error("create http request failed"); #if LIBEVENT_VERSION_NUMBER >= 0x02010300 evhttp_request_set_error_cb(req.get(), http_error_cb); #endif // Get credentials std::string strRPCUserColonPass; if (GetArg("-rpcpassword", "") == "") { // Try fall back to cookie-based authentication if no password is provided if (!GetAuthCookie(&strRPCUserColonPass)) { throw std::runtime_error(strprintf( _("Could not locate RPC credentials. No authentication cookie could be found, and no rpcpassword is set in the configuration file (%s)"), GetConfigFile(GetArg("-conf", BITCOIN_CONF_FILENAME)).string().c_str())); } } else { strRPCUserColonPass = GetArg("-rpcuser", "") + ":" + GetArg("-rpcpassword", ""); } struct evkeyvalq* output_headers = evhttp_request_get_output_headers(req.get()); assert(output_headers); evhttp_add_header(output_headers, "Host", host.c_str()); evhttp_add_header(output_headers, "Connection", "close"); evhttp_add_header(output_headers, "Authorization", (std::string("Basic ") + EncodeBase64(strRPCUserColonPass)).c_str()); // Attach request data std::string strRequest = JSONRPCRequestObj(strMethod, params, 1).write() + "\n"; struct evbuffer* output_buffer = evhttp_request_get_output_buffer(req.get()); assert(output_buffer); evbuffer_add(output_buffer, strRequest.data(), strRequest.size()); int r = evhttp_make_request(evcon.get(), req.get(), EVHTTP_REQ_POST, "/"); req.release(); // ownership moved to evcon in above call if (r != 0) { throw CConnectionFailed("send http request failed"); } event_base_dispatch(base.get()); if (response.status == 0) throw CConnectionFailed(strprintf("couldn't connect to server: %s (code %d)\n(make sure server is running and you are connecting to the correct RPC port)", http_errorstring(response.error), response.error)); else if (response.status == HTTP_UNAUTHORIZED) throw std::runtime_error("incorrect rpcuser or rpcpassword (authorization failed)"); else if (response.status >= 400 && response.status != HTTP_BAD_REQUEST && response.status != HTTP_NOT_FOUND && response.status != HTTP_INTERNAL_SERVER_ERROR) throw std::runtime_error(strprintf("server returned HTTP error %d", response.status)); else if (response.body.empty()) throw std::runtime_error("no response from server"); // Parse reply UniValue valReply(UniValue::VSTR); if (!valReply.read(response.body)) throw std::runtime_error("couldn't parse reply from server"); const UniValue& reply = valReply.get_obj(); if (reply.empty()) throw std::runtime_error("expected reply to have result, error and id properties"); return reply; } int CommandLineRPC(int argc, char *argv[]) { std::string strPrint; int nRet = 0; try { // Skip switches while (argc > 1 && IsSwitchChar(argv[1][0])) { argc--; argv++; } std::vector<std::string> args = std::vector<std::string>(&argv[1], &argv[argc]); if (GetBoolArg("-stdin", false)) { // Read one arg per line from stdin and append std::string line; while (std::getline(std::cin,line)) args.push_back(line); } if (args.size() < 1) throw std::runtime_error("too few parameters (need at least command)"); std::string strMethod = args[0]; args.erase(args.begin()); // Remove trailing method name from arguments vector UniValue params; if(GetBoolArg("-named", DEFAULT_NAMED)) { params = RPCConvertNamedValues(strMethod, args); } else { params = RPCConvertValues(strMethod, args); } // Execute and handle connection failures with -rpcwait const bool fWait = GetBoolArg("-rpcwait", false); do { try { const UniValue reply = CallRPC(strMethod, params); // Parse reply const UniValue& result = find_value(reply, "result"); const UniValue& error = find_value(reply, "error"); if (!error.isNull()) { // Error int code = error["code"].get_int(); if (fWait && code == RPC_IN_WARMUP) throw CConnectionFailed("server in warmup"); strPrint = "error: " + error.write(); nRet = abs(code); if (error.isObject()) { UniValue errCode = find_value(error, "code"); UniValue errMsg = find_value(error, "message"); strPrint = errCode.isNull() ? "" : "error code: "+errCode.getValStr()+"\n"; if (errMsg.isStr()) strPrint += "error message:\n"+errMsg.get_str(); } } else { // Result if (result.isNull()) strPrint = ""; else if (result.isStr()) strPrint = result.get_str(); else strPrint = result.write(2); } // Connection succeeded, no need to retry. break; } catch (const CConnectionFailed&) { if (fWait) MilliSleep(1000); else throw; } } while (fWait); } catch (const boost::thread_interrupted&) { throw; } catch (const std::exception& e) { strPrint = std::string("error: ") + e.what(); nRet = EXIT_FAILURE; } catch (...) { PrintExceptionContinue(NULL, "CommandLineRPC()"); throw; } if (strPrint != "") { fprintf((nRet == 0 ? stdout : stderr), "%s\n", strPrint.c_str()); } return nRet; } int main(int argc, char* argv[]) { SetupEnvironment(); if (!SetupNetworking()) { fprintf(stderr, "Error: Initializing networking failed\n"); return EXIT_FAILURE; } try { int ret = AppInitRPC(argc, argv); if (ret != CONTINUE_EXECUTION) return ret; } catch (...) { PrintExceptionContinue(std::current_exception(), "AppInitRPC()"); return EXIT_FAILURE; } int ret = EXIT_FAILURE; try { ret = CommandLineRPC(argc, argv); } catch (...) { PrintExceptionContinue(std::current_exception(), "CommandLineRPC()"); } return ret; }
#include <gtest/gtest.h> #include <test/cpp/tensorexpr/test_base.h> #include <test/cpp/tensorexpr/test_utils.h> #include <torch/csrc/jit/tensorexpr/hash_provider.h> #include <torch/csrc/jit/tensorexpr/ir_simplifier.h> #include <torch/csrc/jit/tensorexpr/loopnest.h> #include <cmath> namespace torch { namespace jit { using namespace torch::jit::tensorexpr; using SimpleIRExprEval = ExprEval<SimpleIREvaluator>; TEST(Simplify, ConstantFoldSimple) { ExprHandle a(2.0f); ExprHandle b(3.0f); ExprHandle f = (a + b); ExprHandle newF = IRSimplifier::simplify(f); ASSERT_NE(newF.AsNode<FloatImm>(), nullptr); ASSERT_EQ(newF.AsNode<FloatImm>()->value(), 5); SimpleIRExprEval eval(newF); ASSERT_EQ(eval.value<float>(), 5.f); } TEST(Simplify, ConstantFoldTwoLayer) { ExprHandle a(2.0f); ExprHandle b(3.0f); ExprHandle c(4.0f); ExprHandle d(5.0f); ExprHandle f = (a + b) - (c + d); ExprHandle newF = IRSimplifier::simplify(f); ASSERT_NE(newF.AsNode<FloatImm>(), nullptr); ASSERT_EQ(newF.AsNode<FloatImm>()->value(), -4); SimpleIRExprEval eval(newF); ASSERT_EQ(eval.value<float>(), -4.f); } TEST(Simplify, ConstantFoldShifts) { ExprHandle a(7); ExprHandle b(2); ExprHandle c(3); ExprHandle f = ((a << b) << b) >> c; ExprHandle newF = IRSimplifier::simplify(f); ASSERT_NE(newF.AsNode<IntImm>(), nullptr); ASSERT_EQ(newF.AsNode<IntImm>()->value(), 14); SimpleIRExprEval eval(newF); ASSERT_EQ(eval.value<int>(), 7 << (4 - 3)); } TEST(Simplify, ConstantFoldBitwise) { ExprHandle a(59); ExprHandle b(22); ExprHandle c(101); ExprHandle f = (a ^ b) & c; ExprHandle newF = IRSimplifier::simplify(f); ASSERT_NE(newF.AsNode<IntImm>(), nullptr); ASSERT_EQ(newF.AsNode<IntImm>()->value(), 37); SimpleIRExprEval eval(newF); ASSERT_EQ(eval.value<int>(), (59 ^ 22) & 101); } TEST(Simplify, ConstantFoldMultiOp) { ExprHandle a(2.0f); ExprHandle b(3.0f); ExprHandle c(4.0f); ExprHandle d(5.0f); ExprHandle e(6.0f); ExprHandle f(7.0f); ExprHandle fn = ((a / e) - (c + d)) * (f / b); ExprHandle newF = IRSimplifier::simplify(fn); ASSERT_NE(newF.AsNode<FloatImm>(), nullptr); SimpleIRExprEval eval(newF); SimpleIRExprEval ref(fn); ASSERT_EQ(eval.value<float>(), ref.value<float>()); } TEST(Simplify, ConstantFoldMinMax) { ExprHandle a(12.0f); ExprHandle b(15.0f); ExprHandle c(17.0f); // x = max(12, min(15, 17)). ExprHandle minHandle = Min::make(b, c, true); ExprHandle fn = Max::make(a, minHandle, false); // NOLINTNEXTLINE(clang-analyzer-cplusplus.NewDeleteLeaks) ASSERT_EQ(fn.dtype().scalar_type(), ScalarType::Float); ExprHandle newF = IRSimplifier::simplify(fn); ASSERT_NE(newF.AsNode<FloatImm>(), nullptr); SimpleIRExprEval eval(newF); ASSERT_EQ(eval.value<float>(), 15.f); } TEST(Simplify, ConstantFoldIntrinsics) { ExprHandle a(2.0f); ExprHandle b(3.0f); ExprHandle c(4.0f); ExprHandle powHandle = Intrinsics::make(kPow, a, b); ExprHandle sinHandle = Intrinsics::make(kSin, powHandle); ExprHandle modHandle = Intrinsics::make(kFmod, c, sinHandle); ExprHandle logHandle = Intrinsics::make(kLog10, modHandle); ExprHandle rndHandle = Intrinsics::make(kRound, logHandle); ExprHandle fn = Intrinsics::make(kAbs, rndHandle); ExprHandle newF = IRSimplifier::simplify(fn); ASSERT_NE(newF.AsNode<FloatImm>(), nullptr); ASSERT_EQ(newF.AsNode<FloatImm>()->value(), 1); SimpleIRExprEval eval(newF); SimpleIRExprEval ref(fn); ASSERT_EQ(eval.value<float>(), ref.value<float>()); } TEST(Simplify, ConstantFoldCastToBool) { ExprHandle f = Cast::make(kBool, IntImm::make(0)); ExprHandle newF = IRSimplifier::simplify(f); SimpleIRExprEval eval(newF); ASSERT_EQ(eval.value<bool>(), false); } TEST(Simplify, ConstantFoldWithVar) { { VarHandle x("x", kInt); ExprHandle body = x * (ExprHandle(2) + ExprHandle(4)); ExprHandle newF = IRSimplifier::simplify(body); MulPtr root = newF.AsNode<Mul>(); ASSERT_NE(root, nullptr); ASSERT_NE(to<IntImm>(root->lhs()), nullptr); SimpleIRExprEval eval(newF); eval.bindVar(x, ExprHandle(3)); ASSERT_EQ(eval.value<int>(), 3 * (2 + 4)); } { VarHandle x("x", kFloat); ExprHandle body = x * (ExprHandle(2.f) + ExprHandle(4.f)); ExprHandle newF = IRSimplifier::simplify(body); MulPtr root = newF.AsNode<Mul>(); ASSERT_NE(root, nullptr); ASSERT_NE(to<FloatImm>(root->rhs()), nullptr); SimpleIRExprEval eval(newF); eval.bindVar(x, ExprHandle(3.f)); ASSERT_EQ(eval.value<float>(), 3 * (2 + 4)); } } TEST(Simplify, ConditionalSelectFoldSimple) { ExprHandle a(3.0f); ExprHandle b(4.0f); ExprHandle c(3.0f); { ExprHandle f = (a > b); ExprHandle newF = IRSimplifier::simplify(f); ASSERT_NE(newF.AsNode<IntImm>(), nullptr); ASSERT_EQ(newF.AsNode<IntImm>()->value(), 0); SimpleIRExprEval eval(newF); ASSERT_EQ(eval.value<int>(), 0); } { ExprHandle f = (a < b); ExprHandle newF = IRSimplifier::simplify(f); ASSERT_NE(newF.AsNode<IntImm>(), nullptr); ASSERT_EQ(newF.AsNode<IntImm>()->value(), 1); SimpleIRExprEval eval(newF); ASSERT_EQ(eval.value<int>(), 1); } { ExprHandle f = (a == c); ExprHandle newF = IRSimplifier::simplify(f); ASSERT_NE(newF.AsNode<IntImm>(), nullptr); ASSERT_EQ(newF.AsNode<IntImm>()->value(), 1); SimpleIRExprEval eval(newF); ASSERT_EQ(eval.value<int>(), 1); } { ExprHandle f = (a != c); ExprHandle newF = IRSimplifier::simplify(f); ASSERT_NE(newF.AsNode<IntImm>(), nullptr); ASSERT_EQ(newF.AsNode<IntImm>()->value(), 0); SimpleIRExprEval eval(newF); ASSERT_EQ(eval.value<int>(), 0); } } TEST(Simplify, ConditionalSelectFoldTwoLayer) { ExprHandle a(3.0f); ExprHandle b(2.0f); ExprHandle c(2.0f); ExprHandle d(1.0f); { ExprHandle f = (a + b < c + d); ExprHandle newF = IRSimplifier::simplify(f); ASSERT_NE(newF.AsNode<IntImm>(), nullptr); ASSERT_EQ(newF.AsNode<IntImm>()->value(), 0); SimpleIRExprEval eval(newF); ASSERT_EQ(eval.value<int>(), 0); } { ExprHandle f = (a + b > c + d); ExprHandle newF = IRSimplifier::simplify(f); ASSERT_NE(newF.AsNode<IntImm>(), nullptr); ASSERT_EQ(newF.AsNode<IntImm>()->value(), 1); SimpleIRExprEval eval(newF); ASSERT_EQ(eval.value<int>(), 1); } { ExprHandle f = (a + d == b + c); ExprHandle newF = IRSimplifier::simplify(f); ASSERT_NE(newF.AsNode<IntImm>(), nullptr); ASSERT_EQ(newF.AsNode<IntImm>()->value(), 1); SimpleIRExprEval eval(newF); ASSERT_EQ(eval.value<int>(), 1); } { ExprHandle f = (a + d != b + c); ExprHandle newF = IRSimplifier::simplify(f); ASSERT_NE(newF.AsNode<IntImm>(), nullptr); ASSERT_EQ(newF.AsNode<IntImm>()->value(), 0); SimpleIRExprEval eval(newF); ASSERT_EQ(eval.value<int>(), 0); } } TEST(Simplify, ConditionalSelectFoldWithVar) { VarHandle x("x", kFloat); ExprHandle f = x < 4.f; ExprHandle newF = IRSimplifier::simplify(f); IntImmPtr folded = newF.AsNode<IntImm>(); ASSERT_EQ(folded, nullptr); { SimpleIRExprEval eval(newF); eval.bindVar(x, ExprHandle(3.f)); ASSERT_EQ(eval.value<int>(), 1); } { SimpleIRExprEval eval(newF); eval.bindVar(x, ExprHandle(5.f)); ASSERT_EQ(eval.value<int>(), 0); } } TEST(Simplify, UnFoldableExpr) { VarHandle x("x", kFloat); VarHandle y("y", kFloat); ExprHandle body = (ExprHandle(3) * x) + (ExprHandle(5) * y); ExprHandle newF = IRSimplifier::simplify(body); AddPtr root = newF.AsNode<Add>(); ASSERT_NE(root, nullptr); ASSERT_EQ(to<FloatImm>(root->lhs()), nullptr); ASSERT_EQ(to<FloatImm>(root->rhs()), nullptr); SimpleIRExprEval eval(newF); eval.bindVar(x, ExprHandle(3.f)); eval.bindVar(y, ExprHandle(2.f)); ASSERT_EQ(eval.value<float>(), 9 + 10); } TEST(Simplify, HashSimple) { VarHandle x("x", kFloat); ExprHandle a(2.0f); ExprHandle b(3.0f); ExprHandle f = a + b * x; HashProvider hasher; auto hash_x = hasher.hash(x.node()); auto hash_a = hasher.hash(a.node()); auto hash_f = hasher.hash(f.node()); ASSERT_NE(hash_x, (size_t)0); ASSERT_NE(hash_a, (size_t)0); ASSERT_NE(hash_f, (size_t)0); ASSERT_NE(hash_x, hash_a); ASSERT_NE(hash_x, hash_f); ASSERT_NE(hash_a, hash_f); } TEST(Simplify, HashEquivalence) { VarHandle x("x", kFloat); VarHandle y("y", kFloat); ExprHandle f = (x * y) + (x * y); AddPtr root = f.AsNode<Add>(); ASSERT_NE(root, nullptr); HashProvider hasher; auto hash_f = hasher.hash(f.node()); auto hash_l = hasher.hash(root->lhs()); auto hash_r = hasher.hash(root->rhs()); // Root not equal to either branch. ASSERT_NE(hash_f, hash_l); ASSERT_NE(hash_f, hash_r); // but branches are equal. ASSERT_EQ(hash_l, hash_r); // Still equivalent if separate. ExprHandle a(2); ExprHandle f2 = x + a / y; ExprHandle b(2); ExprHandle f3 = x + b / y; ASSERT_EQ(hasher.hash(f2.node()), hasher.hash(f3.node())); // Not equivalent if different vars (even with same name). VarHandle z("x", kFloat); ExprHandle f4 = z + b / y; ASSERT_NE(hasher.hash(f2.node()), hasher.hash(f4.node())); // Intrinsics sanity check. ExprHandle f5 = Intrinsics::make(kSin, x) * Intrinsics::make(kCos, x); ASSERT_NE(hasher.hash(f5.node()), (size_t)0); } TEST(Simplify, HashEquivalenceRand) { ExprHandle f = Intrinsics::make(kRand, kFloat) + Intrinsics::make(kRand, kInt); AddPtr root = f.AsNode<Add>(); ASSERT_NE(root, nullptr); HashProvider hasher; auto hash_f = hasher.hash(f.node()); auto hash_l = hasher.hash(root->lhs()); auto hash_r = hasher.hash(root->rhs()); // Root not equal to either branch. ASSERT_NE(hash_f, hash_l); ASSERT_NE(hash_f, hash_r); // and branches are NOT equal. ASSERT_NE(hash_l, hash_r); } TEST(Simplify, HashEquivalenceAfterFolding) { VarHandle x("x", kFloat); ExprHandle a(2.0f); ExprHandle b(3.0f); ExprHandle c(5.0f); ExprHandle f1 = ((a + b) * x); ExprHandle f2 = (c * x); HashProvider hasher; auto hash_l = hasher.hash(f1.node()); auto hash_r = hasher.hash(f2.node()); // Root not equal to either branch, and branches not equal. ASSERT_NE(hash_l, hash_r); ExprHandle ff1 = IRSimplifier::simplify(f1); ExprHandle ff2 = IRSimplifier::simplify(f2); auto hash_l_n = hasher.hash(ff1.node()); auto hash_r_n = hasher.hash(ff2.node()); // but branches are now equal. ASSERT_EQ(hash_l_n, hash_r_n); } TEST(Simplify, HashDifferenceTypes) { HashProvider hasher; std::vector<ExprPtr> immediates; immediates.push_back(alloc<DoubleImm>(1)); immediates.push_back(alloc<FloatImm>(1)); immediates.push_back(alloc<HalfImm>(1)); // NOLINTNEXTLINE(modernize-use-bool-literals) immediates.push_back(alloc<BoolImm>(1)); immediates.push_back(alloc<CharImm>(1)); immediates.push_back(alloc<ByteImm>(1)); immediates.push_back(alloc<ShortImm>(1)); immediates.push_back(alloc<IntImm>(1)); immediates.push_back(alloc<LongImm>(1)); // Immediates of different types are not equal. for (unsigned int i = 0; i < immediates.size(); ++i) { for (unsigned int j = i + 1; j < immediates.size(); ++j) { ASSERT_NE(hasher.hash(immediates[i]), hasher.hash(immediates[j])); } } // But coerced immediates are if they are the same type: ExprHandle f1 = ExprHandle(2.f) + CharImm::make(1); ExprHandle f2 = Cast::make(kFloat, IntImm::make(3)); ExprHandle ff1 = IRSimplifier::simplify(f1); ExprHandle ff2 = IRSimplifier::simplify(f2); ASSERT_EQ(hasher.hash(ff1.node()), hasher.hash(ff2.node())); } TEST(Simplify, HashLargeExpression) { constexpr int N = 1024; BufHandle a("A", {N}, kInt); BufHandle b("B", {N}, kInt); BufHandle c("C", {N}, kInt); VarHandle i("i", kInt); auto memcpy_stmt = For::make( i, 0, N, Store::make( c, {i}, CompareSelect::make( Load::make(a, {i}), Load::make(b, {i}), CompareSelectOperation::kEQ))); BufHandle d("D", {1}, kInt); BufHandle e("E", {1}, kInt); auto store_ramp_stmt = Store::make( e, {Ramp::make(0, 1, 4)}, Load::make(d, {Ramp::make(0, 1, 4)})); auto if_stmt = Cond::make( CompareSelect::make( Load::make(a, {i}), Load::make(b, {i}), CompareSelectOperation::kGE), memcpy_stmt, store_ramp_stmt); HashProvider hasher; auto hash_r = hasher.hash(if_stmt); // We should not have to do any more work. ASSERT_TRUE(hasher.cachedHash(memcpy_stmt)); auto hash_t = hasher.hash(memcpy_stmt); ASSERT_TRUE(hasher.cachedHash(store_ramp_stmt)); auto hash_f = hasher.hash(store_ramp_stmt); // Root not equal to either branch, and branches not equal. ASSERT_NE(hash_r, hash_t); ASSERT_NE(hash_r, hash_f); ASSERT_NE(hash_t, hash_f); } TEST(Simplify, HashForLoopOptions) { constexpr int N = 1024; BufHandle a("A", {N}, kInt); BufHandle b("B", {N}, kInt); BufHandle c("C", {N}, kInt); VarHandle i("i", kInt); auto for_stmt = For::make( i, 0, N, Store::make( c, {i}, CompareSelect::make( Load::make(a, {i}), Load::make(b, {i}), CompareSelectOperation::kEQ))); HashProvider hasher; auto hash_before = hasher.hash(for_stmt); hasher.clearCache(); for_stmt->set_gpu_block_index(LoopOptions::IDX_X); auto hash_block_idx = hasher.hash(for_stmt); hasher.clearCache(); ASSERT_NE(hash_before, hash_block_idx); for_stmt->set_gpu_block_index(LoopOptions::IDX_UNSET); auto hash_reset = hasher.hash(for_stmt); hasher.clearCache(); ASSERT_EQ(hash_before, hash_reset); for_stmt->set_gpu_thread_index(LoopOptions::IDX_X); auto hash_thread_idx = hasher.hash(for_stmt); ASSERT_NE(hash_before, hash_thread_idx); ASSERT_NE(hash_block_idx, hash_thread_idx); } /// (2 + x) + 4 => x + 6 TEST(Simplify, SimplifyAdd) { VarHandle x("x", kInt); VarHandle y("y", kInt); // NOLINTNEXTLINE(clang-analyzer-cplusplus.NewDeleteLeaks) VarHandle m("m", kInt); // NOLINTNEXTLINE(clang-analyzer-cplusplus.NewDeleteLeaks) VarHandle n("n", kInt); // NOLINTNEXTLINE(clang-analyzer-cplusplus.NewDeleteLeaks) VarHandle n_1("n_1", kInt); // NOLINTNEXTLINE(clang-analyzer-cplusplus.NewDeleteLeaks) ExprHandle body = (ExprHandle(2) + x) + ExprHandle(4); ExprHandle simplified = IRSimplifier::simplify(body); AddPtr root = simplified.AsNode<Add>(); ASSERT_NE(root, nullptr); VarPtr lhs = to<Var>(root->lhs()); ASSERT_NE(lhs, nullptr); ASSERT_EQ(lhs->name_hint(), "x"); IntImmPtr rhs = to<IntImm>(root->rhs()); ASSERT_NE(rhs, nullptr); ASSERT_EQ(rhs->value(), 6.f); } /// (2 - x) - 4 => -2 - x TEST(Simplify, SimplifySub) { VarHandle x("x", kInt); ExprHandle body = (ExprHandle(2) - x) - ExprHandle(4); ExprHandle simplified = IRSimplifier::simplify(body); SubPtr root = simplified.AsNode<Sub>(); ASSERT_NE(root, nullptr); IntImmPtr lhs = to<IntImm>(root->lhs()); ASSERT_NE(lhs, nullptr); ASSERT_EQ(lhs->value(), -2.f); VarPtr rhs = to<Var>(root->rhs()); ASSERT_NE(rhs, nullptr); ASSERT_EQ(rhs->name_hint(), "x"); } /// 2 * (1 - x) - 4 => 2 * (-3 - x) TEST(Simplify, SimplifyMultiLayer) { VarHandle x("x", kInt); ExprHandle body = ExprHandle(2) * ((ExprHandle(1) - x) - ExprHandle(4)); ExprHandle simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(Mul, simplified.node(), mul); IS_IMM_WITH_VAL(Int, mul->lhs(), 2); IS_NODE_WITH_NAME(Sub, mul->rhs(), sub); IS_IMM_WITH_VAL(Int, sub->lhs(), -3); IS_VAR_WITH_NAME(sub->rhs(), "x"); } /// 2 * (3 * x) - (x * 4) => 2 * x TEST(Simplify, SimplifyMultiTerm) { VarHandle x("x", kInt); ExprHandle body = (ExprHandle(2) * ((ExprHandle(3) * x)) - (x * ExprHandle(4))); ExprHandle simplified = IRSimplifier::simplify(body); MulPtr root = simplified.AsNode<Mul>(); ASSERT_NE(root, nullptr); IntImmPtr lhs = to<IntImm>(root->lhs()); ASSERT_NE(lhs, nullptr); ASSERT_EQ(lhs->value(), 2); VarPtr rhs = to<Var>(root->rhs()); ASSERT_NE(rhs, nullptr); ASSERT_EQ(rhs->name_hint(), "x"); } /// 2 * (3 * (long)x) - (x * 4) => 2 * x TEST(Simplify, SimplifyCasts) { VarHandle x("x", kLong); ExprHandle body = (ExprHandle(2) * ((ExprHandle(3) * x)) - (x * ExprHandle(4))); ExprHandle simplified = IRSimplifier::simplify(body); MulPtr root = simplified.AsNode<Mul>(); ASSERT_NE(root, nullptr); LongImmPtr lhs = to<LongImm>(root->lhs()); ASSERT_NE(lhs, nullptr); ASSERT_EQ(lhs->value(), 2); VarPtr rhs = to<Var>(root->rhs()); ASSERT_NE(rhs, nullptr); ASSERT_EQ(rhs->name_hint(), "x"); } /// (x + 0) * 1 => x TEST(Simplify, SimplifyEliminatesNoOps) { VarHandle x("x", kInt); ExprHandle body = (x + ExprHandle(0)) * 1; ExprHandle simplified = IRSimplifier::simplify(body); VarPtr root = simplified.AsNode<Var>(); ASSERT_NE(root, nullptr); ASSERT_EQ(root->name_hint(), "x"); } /// Cannot simplify this. TEST(Simplify, SimplifyMultiVar) { VarHandle x("x", kInt); VarHandle y("y", kInt); ExprHandle body = x * 24 + y * 34; ExprHandle simplified = IRSimplifier::simplify(body); AddPtr root = simplified.AsNode<Add>(); ASSERT_NE(root, nullptr); MulPtr lhs = to<Mul>(root->lhs()); ASSERT_NE(lhs, nullptr); VarPtr varX = to<Var>(lhs->rhs()); ASSERT_NE(varX, nullptr); ASSERT_EQ(varX->name_hint(), "x"); MulPtr rhs = to<Mul>(root->rhs()); ASSERT_NE(rhs, nullptr); VarPtr varY = to<Var>(rhs->rhs()); ASSERT_NE(varY, nullptr); ASSERT_EQ(varY->name_hint(), "y"); } // x + 2 + y => x + y + 2 TEST(Simplify, DISABLED_SimplifyReorderings) { VarHandle x("x", kInt); VarHandle y("y", kInt); ExprHandle body = x + 2 + y; ExprHandle simplified = IRSimplifier::simplify(body); AddPtr root = simplified.AsNode<Add>(); ASSERT_NE(root, nullptr); IS_NODE_WITH_NAME(Add, root->lhs(), rhs); IS_VAR_WITH_NAME(rhs->lhs(), "x"); IS_VAR_WITH_NAME(rhs->rhs(), "y"); IS_IMM_WITH_VAL(Int, root->rhs(), 2); } /// y + x * 0 => y TEST(Simplify, SimplifyEliminatesVar) { VarHandle x("x", kInt); VarHandle y("y", kInt); ExprHandle body = y + x * ExprHandle(0); ExprHandle simplified = IRSimplifier::simplify(body); IS_VAR_WITH_NAME(simplified.node(), "y"); } TEST(Simplify, SimplifyAdds) { VarHandle x("x", kInt); VarHandle y("y", kInt); { // (x + y) + (x + y) => 2 * (x + y) ExprHandle body = (x + y) + (x + y); ExprHandle simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(Mul, simplified.node(), root); IS_IMM_WITH_VAL(Int, root->lhs(), 2); IS_NODE_WITH_NAME(Add, root->rhs(), add); IS_VAR_WITH_NAME(add->lhs(), "x"); IS_VAR_WITH_NAME(add->rhs(), "y"); } { // (x * y) + (x * y) => 2 * (x * y) ExprHandle body = (x * y) + (x * y); ExprHandle simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(Mul, simplified.node(), root); IS_IMM_WITH_VAL(Int, root->lhs(), 2); IS_NODE_WITH_NAME(Mul, root->rhs(), mul); IS_VAR_WITH_NAME(mul->lhs(), "x"); IS_VAR_WITH_NAME(mul->rhs(), "y"); } { // (x - y) + (x - y) => 2 * (x - y) ExprHandle body = (x - y) + (x - y); ExprHandle simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(Mul, simplified.node(), mul); IS_IMM_WITH_VAL(Int, mul->lhs(), 2); IS_NODE_WITH_NAME(Sub, mul->rhs(), rhs); IS_VAR_WITH_NAME(rhs->lhs(), "x"); IS_VAR_WITH_NAME(rhs->rhs(), "y"); } { // (x + x + x + x) => 4 * x ExprHandle body = (x + x + x + x); ExprHandle simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(Mul, simplified.node(), root); IS_IMM_WITH_VAL(Int, root->lhs(), 4); IS_VAR_WITH_NAME(root->rhs(), "x"); } { // (x + 0) => x. ExprHandle body = x + 0; ExprHandle simplified = IRSimplifier::simplify(body); IS_VAR_WITH_NAME(simplified.node(), "x"); } { // (x + 0.f) => float(x). ExprHandle body = x + 0.f; ExprHandle simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(Cast, simplified.node(), cast); ASSERT_EQ(cast->dtype().scalar_type(), ScalarType::Float); IS_VAR_WITH_NAME(cast->src_value(), "x"); } } TEST(Simplify, SimplifyMuls) { VarHandle x("x", kInt); VarHandle y("y", kInt); { // (x + y) * (x + y) => (x + y) * (x + y) // We don't attempt to simplify mulitplication of polynomials since the // result is only very rarely more efficient. ExprHandle body = (x + y) * (x + y); ExprHandle simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(Mul, simplified.node(), mul); IS_NODE_WITH_NAME(Add, mul->lhs(), lhs); IS_VAR_WITH_NAME(lhs->lhs(), "x"); IS_VAR_WITH_NAME(lhs->rhs(), "y"); IS_NODE_WITH_NAME(Add, mul->rhs(), rhs); IS_VAR_WITH_NAME(rhs->lhs(), "x"); IS_VAR_WITH_NAME(rhs->rhs(), "y"); } { // x * y * x * y => x * x * y * y // These get reordered only. ExprHandle body = x * y * x * y; ExprHandle simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(Mul, simplified.node(), mul1); IS_NODE_WITH_NAME(Mul, mul1->lhs(), mul2); IS_NODE_WITH_NAME(Mul, mul2->lhs(), mul3); IS_VAR_WITH_NAME(mul1->rhs(), "y"); IS_VAR_WITH_NAME(mul2->rhs(), "y"); IS_VAR_WITH_NAME(mul3->lhs(), "x"); IS_VAR_WITH_NAME(mul3->rhs(), "x"); } { // 1 * (x * 1) => x // Ones cancel cleanly. ExprHandle body = ExprHandle(1) * (x * ExprHandle(1)); ExprHandle simplified = IRSimplifier::simplify(body); IS_VAR_WITH_NAME(simplified.node(), "x"); } { // 1.f * (x * 1.f) => x // Even float ones cancel cleanly, but carry their type. ExprHandle body = ExprHandle(1.f) * (x * ExprHandle(1.f)); ExprHandle simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(Cast, simplified.node(), cast); ASSERT_EQ(cast->dtype().scalar_type(), ScalarType::Float); IS_VAR_WITH_NAME(cast->src_value(), "x"); } { // 1 * (x * 1.f) => x // One float is enough to cast the expr. ExprHandle body = ExprHandle(1) * (x * ExprHandle(1.f)); ExprHandle simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(Cast, simplified.node(), cast); ASSERT_EQ(cast->dtype().scalar_type(), ScalarType::Float); IS_VAR_WITH_NAME(cast->src_value(), "x"); } { // 1 * (x * 0) => 0 // Zeroes are eliminated. ExprHandle body = ExprHandle(1) * (x * ExprHandle(0)); ExprHandle simplified = IRSimplifier::simplify(body); IS_IMM_WITH_VAL(Int, simplified.node(), 0); } { // 1 * (x * 0) => 0 // But not for Float since nan * 0 = nan. ExprHandle body = ExprHandle(1.f) * (x * ExprHandle(0.f)); ExprHandle simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(Mul, simplified.node(), mul); IS_NODE_WITH_NAME(Cast, mul->lhs(), cast); ASSERT_EQ(cast->dtype().scalar_type(), ScalarType::Float); IS_VAR_WITH_NAME(cast->src_value(), "x"); IS_IMM_WITH_VAL(Float, mul->rhs(), 0.0); } { // (x - y) * (x - y) => (x - y) * (x - y) // As with Add we don't attempt simplification of this. ExprHandle body = (x - y) * (x - y); ExprHandle simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(Mul, simplified.node(), mul); IS_NODE_WITH_NAME(Sub, mul->lhs(), lhs); IS_VAR_WITH_NAME(lhs->lhs(), "x"); IS_VAR_WITH_NAME(lhs->rhs(), "y"); IS_NODE_WITH_NAME(Sub, mul->rhs(), rhs); IS_VAR_WITH_NAME(rhs->lhs(), "x"); IS_VAR_WITH_NAME(rhs->rhs(), "y"); } { // (x + y) * (x - y) => (x + y) * (x - y) // Don't simplify with different ops on each side. ExprHandle body = (x + y) * (x - y); ExprHandle simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(Mul, simplified.node(), mul); IS_NODE_WITH_NAME(Add, mul->lhs(), lhs); IS_VAR_WITH_NAME(lhs->lhs(), "x"); IS_VAR_WITH_NAME(lhs->rhs(), "y"); IS_NODE_WITH_NAME(Sub, mul->rhs(), rhs); IS_VAR_WITH_NAME(rhs->lhs(), "x"); IS_VAR_WITH_NAME(rhs->rhs(), "y"); } { // Multiply a polynomial by a term. // - term with no scalar, poly with non-identity scalar. // x * (y + 1) => x + x * y ExprHandle body = x * (y + ExprHandle(1)); ExprHandle simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(Add, simplified.node(), add); IS_VAR_WITH_NAME(add->lhs(), "x"); IS_NODE_WITH_NAME(Mul, add->rhs(), mul); IS_VAR_WITH_NAME(mul->lhs(), "x"); IS_VAR_WITH_NAME(mul->rhs(), "y"); } { // Multiply a polynomial by a term. // - term with identity scalar, poly with non-identity scalar. // (x * 1) * (y + 1) => x + x * y ExprHandle body = (x * ExprHandle(1)) * (y + ExprHandle(1)); ExprHandle simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(Add, simplified.node(), add); IS_VAR_WITH_NAME(add->lhs(), "x"); IS_NODE_WITH_NAME(Mul, add->rhs(), mul); IS_VAR_WITH_NAME(mul->lhs(), "x"); IS_VAR_WITH_NAME(mul->rhs(), "y"); } { // Multiply a polynomial by a term. // - term with non-identity scalar, poly with non-identity scalar. // (x * 2) * (y + 1) => 2 * (x + x * y) ExprHandle body = (x * ExprHandle(2)) * (y + ExprHandle(1)); ExprHandle simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(Mul, simplified.node(), mul); IS_IMM_WITH_VAL(Int, mul->lhs(), 2); IS_NODE_WITH_NAME(Add, mul->rhs(), add); IS_VAR_WITH_NAME(add->lhs(), "x"); IS_NODE_WITH_NAME(Mul, add->rhs(), mul2); IS_VAR_WITH_NAME(mul2->lhs(), "x"); IS_VAR_WITH_NAME(mul2->rhs(), "y"); } { // Multiply a polynomial by a term. // - term with non-identity scalar, poly with identity scalar. // (x * 2) * (y + 0) => 2 * (x * y) ExprHandle body = (x * ExprHandle(2)) * (y + ExprHandle(0)); ExprHandle simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(Mul, simplified.node(), mul); IS_IMM_WITH_VAL(Int, mul->lhs(), 2); IS_NODE_WITH_NAME(Mul, mul->rhs(), mul2); IS_VAR_WITH_NAME(mul2->lhs(), "x"); IS_VAR_WITH_NAME(mul2->rhs(), "y"); } { // Multiply a polynomial by a term. // - term with identity scalar, poly with identity scalar. // (x * 1) * (y + 0) => x * y ExprHandle body = (x * ExprHandle(1)) * (y + ExprHandle(0)); ExprHandle simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(Mul, simplified.node(), mul); IS_VAR_WITH_NAME(mul->lhs(), "x"); IS_VAR_WITH_NAME(mul->rhs(), "y"); } { // Multiply a polynomial by a term. // - term with no scalar, poly with identity scalar. // x * (y + 0) => x * y ExprHandle body = x * (y + ExprHandle(0)); ExprHandle simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(Mul, simplified.node(), mul); IS_VAR_WITH_NAME(mul->lhs(), "x"); IS_VAR_WITH_NAME(mul->rhs(), "y"); } } // Sub an expr from itself will result in zero. TEST(Simplify, SimplifySubs) { VarHandle x("x", kInt); VarHandle y("y", kInt); { // (x + y) - (x + y) => 0 ExprHandle body = (x + y) - (x + y); ExprHandle simplified = IRSimplifier::simplify(body); IS_IMM_WITH_VAL(Int, simplified.node(), 0); } { // (x * y) - (x * y) => 0 ExprHandle body = (x * y) - (x * y); ExprHandle simplified = IRSimplifier::simplify(body); IS_IMM_WITH_VAL(Int, simplified.node(), 0); } { // (x - y) - (x - y) => 0 ExprHandle body = (x - y) - (x - y); ExprHandle simplified = IRSimplifier::simplify(body); IS_IMM_WITH_VAL(Int, simplified.node(), 0); } { // (x + y) - 2 * (x + y) => -1 * x - y ExprHandle body = (x + y) - ExprHandle(2) * (x + y); ExprHandle simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(Sub, simplified.node(), sub); IS_NODE_WITH_NAME(Mul, sub->lhs(), mul); IS_IMM_WITH_VAL(Int, mul->lhs(), -1); IS_VAR_WITH_NAME(mul->rhs(), "x"); IS_VAR_WITH_NAME(sub->rhs(), "y"); } { // (x + y) - y => x ExprHandle body = (x + y) - y; ExprHandle simplified = IRSimplifier::simplify(body); IS_VAR_WITH_NAME(simplified.node(), "x"); } { // (x - 0) => x. ExprHandle body = x - 0; ExprHandle simplified = IRSimplifier::simplify(body); IS_VAR_WITH_NAME(simplified.node(), "x"); } { // (x - 0.f) => x. // Simple enough to cancel in float. ExprHandle body = x - ExprHandle(0.f); ExprHandle simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(Cast, simplified.node(), cast); ASSERT_EQ(cast->dtype().scalar_type(), ScalarType::Float); IS_VAR_WITH_NAME(cast->src_value(), "x"); } { // (x - (float)(y - y)) => x. ExprHandle body = x - Cast::make(kFloat, y - y); ExprHandle simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(Cast, simplified.node(), cast); ASSERT_EQ(cast->dtype().scalar_type(), ScalarType::Float); IS_VAR_WITH_NAME(cast->src_value(), "x"); } { // (x - y) - y => x - 2 * y ExprHandle body = (x - y) - y; ExprHandle simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(Sub, simplified.node(), sub); IS_VAR_WITH_NAME(sub->lhs(), "x"); IS_NODE_WITH_NAME(Mul, sub->rhs(), mul); IS_IMM_WITH_VAL(Int, mul->lhs(), 2); IS_VAR_WITH_NAME(mul->rhs(), "y"); } { // 2 * x - x => x ExprHandle body = (ExprHandle(2) * x) - x; ExprHandle simplified = IRSimplifier::simplify(body); IS_VAR_WITH_NAME(simplified.node(), "x"); } { // x - 2 * x = -1 * x // We don't have a unary negate, but this could be 0 -x I guess? ExprHandle body = x - (ExprHandle(2) * x); ExprHandle simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(Mul, simplified.node(), mul); IS_IMM_WITH_VAL(Int, mul->lhs(), -1); IS_VAR_WITH_NAME(mul->rhs(), "x"); } { // (x + y + 5) * (x - x) => 0 // Cancelling out one side of Mul cancels both. ExprHandle body = (x + y + 5) * (x - x); ExprHandle simplified = IRSimplifier::simplify(body); IS_IMM_WITH_VAL(Int, simplified.node(), 0); } { // Cancel out opaque modulus. ExprHandle body = (x % y + 2) - (x % y); ExprHandle simplified = IRSimplifier::simplify(body); IS_IMM_WITH_VAL(Int, simplified.node(), 2); } { // Cancel out opaque modulus with a bit more going on. ExprHandle body = (x % y + (x * 2 - x - y * 0) - x + 2) - (x % y); ExprHandle simplified = IRSimplifier::simplify(body); IS_IMM_WITH_VAL(Int, simplified.node(), 2); } { // Sub where result is negative. ExprHandle body = x - (x + 1); ExprHandle simplified = IRSimplifier::simplify(body); IS_IMM_WITH_VAL(Int, simplified.node(), -1); } { // Sub where result is positive due to negative scalar on RHS. ExprHandle body = x - (x - 1); ExprHandle simplified = IRSimplifier::simplify(body); IS_IMM_WITH_VAL(Int, simplified.node(), 1); } { // Term - Polynomial sub where RHS must be negated. ExprHandle body = (x * 2) - (x * 2 + 1); ExprHandle simplified = IRSimplifier::simplify(body); IS_IMM_WITH_VAL(Int, simplified.node(), -1); } { // Term - Polynomial sub where the result is a Term. ExprHandle body = (y * x * 2) - (x * y); ExprHandle simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(Mul, simplified.node(), mul); IS_VAR_WITH_NAME(mul->lhs(), "x"); IS_VAR_WITH_NAME(mul->rhs(), "y"); } { // Term - Polynomial sub where the result is a Polynomial. ExprHandle body = (x * 2) - (x + 1); ExprHandle simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(Sub, simplified.node(), sub); IS_VAR_WITH_NAME(sub->lhs(), "x"); IS_IMM_WITH_VAL(Int, sub->rhs(), 1); } } TEST(Simplify, SimplifyDiv) { VarHandle x("x", kInt); { ExprHandle body = ExprHandle(0) / x; ExprHandle simplified = IRSimplifier::simplify(body); IS_IMM_WITH_VAL(Int, simplified.node(), 0); } { ExprHandle body = x / 1; ExprHandle simplified = IRSimplifier::simplify(body); IS_VAR_WITH_NAME(simplified.node(), "x"); } } TEST(Simplify, SimplifyDivWithLoopContext0) { // Stmt to simplify: // for (int i = 0; i < 100; i++) { // A[i] = i / 100; //} VarHandle i("i", kInt); BufHandle a_buf("A", {100}, kInt); auto for_stmt = For::make(i, 0, 100, Store::make(a_buf, {i}, (i / 100))); const StmtPtr simplified = IRSimplifier::simplify(for_stmt); std::ostringstream oss; oss << *(simplified); const std::string& verification_pattern = R"IR( # CHECK: for (int i # CHECK-NEXT: A[i] = 0; )IR"; torch::jit::testing::FileCheck().run(verification_pattern, oss.str()); } TEST(Simplify, SimplifyDivWithLoopContext1) { // Stmt to simplify: // for (int i = 0; i < 6; i++) { // A[i] = (i + 24) / 6; //} VarHandle i("i", kInt); BufHandle a_buf("A", {6}, kInt); auto for_stmt = For::make(i, 0, 6, Store::make(a_buf, {i}, (i + 24) / 6)); const StmtPtr simplified = IRSimplifier::simplify(for_stmt); std::ostringstream oss; oss << *(simplified); const std::string& verification_pattern = R"IR( # CHECK: for (int i # CHECK-NEXT: A[i] = 4; )IR"; torch::jit::testing::FileCheck().run(verification_pattern, oss.str()); } TEST(Simplify, SimplifyDivWithLoopContext2) { // Stmt to simplify: // for (int i = 0; i < 5; i++) { // A[i] = (i + 25) / 6; //} VarHandle i("i", kInt); BufHandle a_buf("A", {5}, kInt); auto for_stmt = For::make(i, 0, 5, Store::make(a_buf, {i}, (i + 25) / 6)); const StmtPtr simplified = IRSimplifier::simplify(for_stmt); std::ostringstream oss; oss << *(simplified); const std::string& verification_pattern = R"IR( # CHECK: for (int i # CHECK-NEXT: A[i] = 4; )IR"; torch::jit::testing::FileCheck().run(verification_pattern, oss.str()); } TEST(Simplify, SimplifyDivWithLoopContext3) { // Stmt to simplify: // for (int i = 0; i < 6; i++) { // A[i] = (i + 24) / (-6); //} VarHandle i("i", kInt); BufHandle a_buf("A", {6}, kInt); auto for_stmt = For::make(i, 0, 6, Store::make(a_buf, {i}, (i + 24) / (-6))); const StmtPtr simplified = IRSimplifier::simplify(for_stmt); std::ostringstream oss; oss << *(simplified); const std::string& verification_pattern = R"IR( # CHECK: for (int i # CHECK-NOT: A[i] = -4; )IR"; torch::jit::testing::FileCheck().run(verification_pattern, oss.str()); } TEST(Simplify, SimplifyDivWithLoopContext4) { // Stmt to simplify: // for (int i = 0; i < 5; i++) { // A[i] = (i - 5) / 6; //} VarHandle i("i", kInt); BufHandle a_buf("A", {5}, kInt); auto for_stmt = For::make(i, 0, 5, Store::make(a_buf, {i}, (i + (-5)) / 6)); const StmtPtr simplified = IRSimplifier::simplify(for_stmt); std::ostringstream oss; oss << *(simplified); const std::string& verification_pattern = R"IR( # CHECK: for (int i # CHECK-NOT: A[i] = 0; )IR"; torch::jit::testing::FileCheck().run(verification_pattern, oss.str()); } TEST(Simplify, SimplifyDivWithLoopContext5) { // Stmt to simplify: // for (int i = 0; i < 6; i++) { // for (int j = 0; j < 10; j++) { // A[i, j] = (i + 6*j) / 6; // } //} VarHandle i("i", kInt); VarHandle j("j", kInt); BufHandle a_buf("A", {6, 10}, kInt); auto for_j = For::make(j, 0, 10, Store::make(a_buf, {i, j}, (i + j * 6) / 6)); auto for_i = For::make(i, 0, 6, for_j); const StmtPtr simplified = IRSimplifier::simplify(for_i); std::ostringstream oss; oss << *(simplified); const std::string& verification_pattern = R"IR( # CHECK: for (int i # CHECK: for (int j # CHECK-NEXT: A[i, j] = j; )IR"; torch::jit::testing::FileCheck().run(verification_pattern, oss.str()); } TEST(Simplify, SimplifyDivWithLoopContext6) { // Stmt to simplify: // for (int i = 0; i < 6; i++) { // for (int j = -1; j < 9; j++) { // A[i, j+1] = (i + 6*j) / 6; // } //} VarHandle i("i", kInt); VarHandle j("j", kInt); BufHandle a_buf("A", {6, 10}, kInt); auto for_j = For::make(j, -1, 9, Store::make(a_buf, {i, j + 1}, (i + j * 6) / 6)); auto for_i = For::make(i, 0, 6, for_j); const StmtPtr simplified = IRSimplifier::simplify(for_i); std::ostringstream oss; oss << *(simplified); const std::string& verification_pattern = R"IR( # CHECK: for (int i # CHECK: for (int j # CHECK-NOT: A[i, j] = j; )IR"; torch::jit::testing::FileCheck().run(verification_pattern, oss.str()); } TEST(Simplify, SimplifyDivWithLoopContext7) { // Stmt to simplify: // for (int i = 0; i < 6; i++) { // for (int j = 0; j < 10; j++) { // A[i, j] = (i + 6*j) / (-6); // } //} VarHandle i("i", kInt); VarHandle j("j", kInt); BufHandle a_buf("A", {6, 10}, kInt); auto for_j = For::make(j, 0, 10, Store::make(a_buf, {i, j}, (i + j * 6) / (-6))); auto for_i = For::make(i, 0, 6, for_j); const StmtPtr simplified = IRSimplifier::simplify(for_i); std::ostringstream oss; oss << *(simplified); const std::string& verification_pattern = R"IR( # CHECK: for (int i # CHECK: for (int j # CHECK-NOT: A[i, j] = -j; )IR"; torch::jit::testing::FileCheck().run(verification_pattern, oss.str()); } TEST(Simplify, SimplifyModWithLoopContext0) { // Stmt to simplify: // for (int i = 0; i < 100; i++) { // A[i] = i % 100; //} VarHandle i("i", kInt); BufHandle a_buf("A", {100}, kInt); auto for_stmt = For::make(i, 0, 100, Store::make(a_buf, {i}, (i % 100))); const StmtPtr simplified = IRSimplifier::simplify(for_stmt); std::ostringstream oss; oss << *(simplified); const std::string& verification_pattern = R"IR( # CHECK: for (int i # CHECK-NEXT: A[i] = i; )IR"; torch::jit::testing::FileCheck().run(verification_pattern, oss.str()); } TEST(Simplify, SimplifyModWithLoopContext1) { // Stmt to simplify: // for (int i = 0; i < 6; i++) { // A[i] = (i + 24) % 6; //} VarHandle i("i", kInt); BufHandle a_buf("A", {6}, kInt); auto for_stmt = For::make(i, 0, 6, Store::make(a_buf, {i}, (i + 24) % 6)); const StmtPtr simplified = IRSimplifier::simplify(for_stmt); std::ostringstream oss; oss << *(simplified); const std::string& verification_pattern = R"IR( # CHECK: for (int i # CHECK-NEXT: A[i] = i; )IR"; torch::jit::testing::FileCheck().run(verification_pattern, oss.str()); } TEST(Simplify, SimplifyModWithLoopContext2) { // Stmt to simplify: // for (int i = 0; i < 5; i++) { // A[i] = (i + 25) % 6; //} VarHandle i("i", kInt); BufHandle a_buf("A", {5}, kInt); auto for_stmt = For::make(i, 0, 5, Store::make(a_buf, {i}, (i + 25) % 6)); const StmtPtr simplified = IRSimplifier::simplify(for_stmt); std::ostringstream oss; oss << *(simplified); const std::string& verification_pattern = R"IR( # CHECK: for (int i # CHECK-NEXT: A[i] = i + 1; )IR"; torch::jit::testing::FileCheck().run(verification_pattern, oss.str()); } TEST(Simplify, SimplifyModWithLoopContext3) { // Stmt to simplify: // for (int i = 0; i < 6; i++) { // A[i] = (i + 24) % (-6); //} VarHandle i("i", kInt); BufHandle a_buf("A", {6}, kInt); auto for_stmt = For::make(i, 0, 6, Store::make(a_buf, {i}, (i + 24) % (-6))); const StmtPtr simplified = IRSimplifier::simplify(for_stmt); std::ostringstream oss; oss << *(simplified); const std::string& verification_pattern = R"IR( # CHECK: for (int i # CHECK-NOT: A[i] = i; )IR"; torch::jit::testing::FileCheck().run(verification_pattern, oss.str()); } TEST(Simplify, SimplifyModWithLoopContext4) { // Stmt to simplify: // for (int i = 0; i < 5; i++) { // A[i] = (i - 5) % 6; //} VarHandle i("i", kInt); BufHandle a_buf("A", {5}, kInt); auto for_stmt = For::make(i, 0, 5, Store::make(a_buf, {i}, (i + (-5)) % 6)); const StmtPtr simplified = IRSimplifier::simplify(for_stmt); std::ostringstream oss; oss << *(simplified); const std::string& verification_pattern = R"IR( # CHECK: for (int i # CHECK-NOT: A[i] = i - 5; )IR"; torch::jit::testing::FileCheck().run(verification_pattern, oss.str()); } TEST(Simplify, SimplifyModWithLoopContext5) { // Stmt to simplify: // for (int i = 0; i < 6; i++) { // for (int j = 0; j < 10; j++) { // A[i, j] = (i + 6*j) % 6; // } //} VarHandle i("i", kInt); VarHandle j("j", kInt); BufHandle a_buf("A", {6, 10}, kInt); auto for_j = For::make(j, 0, 10, Store::make(a_buf, {i, j}, (i + j * 6) % 6)); auto for_i = For::make(i, 0, 6, for_j); const StmtPtr simplified = IRSimplifier::simplify(for_i); std::ostringstream oss; oss << *(simplified); const std::string& verification_pattern = R"IR( # CHECK: for (int i # CHECK: for (int j # CHECK-NEXT: A[i, j] = i; )IR"; torch::jit::testing::FileCheck().run(verification_pattern, oss.str()); } TEST(Simplify, SimplifyModWithLoopContext6) { // Stmt to simplify: // for (int i = 0; i < 6; i++) { // for (int j = -1; j < 9; j++) { // A[i, j+1] = (i + 6*j) % 6; // } //} VarHandle i("i", kInt); VarHandle j("j", kInt); BufHandle a_buf("A", {6, 10}, kInt); auto for_j = For::make(j, -1, 9, Store::make(a_buf, {i, j + 1}, (i + j * 6) % 6)); auto for_i = For::make(i, 0, 6, for_j); const StmtPtr simplified = IRSimplifier::simplify(for_i); std::ostringstream oss; oss << *(simplified); const std::string& verification_pattern = R"IR( # CHECK: for (int i # CHECK: for (int j # CHECK-NOT: A[i, j] = i; )IR"; torch::jit::testing::FileCheck().run(verification_pattern, oss.str()); } TEST(Simplify, SimplifyModWithLoopContext7) { // Stmt to simplify: // for (int i = 0; i < 6; i++) { // for (int j = 0; j < 10; j++) { // A[i, j] = (i + 6*j) % (-6); // } //} VarHandle i("i", kInt); VarHandle j("j", kInt); BufHandle a_buf("A", {6, 10}, kInt); auto for_j = For::make(j, 0, 10, Store::make(a_buf, {i, j}, (i + j * 6) % (-6))); auto for_i = For::make(i, 0, 6, for_j); const StmtPtr simplified = IRSimplifier::simplify(for_i); std::ostringstream oss; oss << *(simplified); const std::string& verification_pattern = R"IR( # CHECK: for (int i # CHECK: for (int j # CHECK-NOT: A[i, j] = i; )IR"; torch::jit::testing::FileCheck().run(verification_pattern, oss.str()); } TEST(Simplify, SimplifyMod) { VarHandle x("x", kInt); VarHandle y("y", kInt); VarHandle z("z", kInt); { // Constant folding works. ExprHandle body = ExprHandle(10) % 8; ExprHandle simplified = IRSimplifier::simplify(body); // NOLINTNEXTLINE(clang-analyzer-cplusplus.NewDeleteLeaks) IS_IMM_WITH_VAL(Int, simplified.node(), 2); } { // x % x => 0 ExprHandle body = x % x; ExprHandle simplified = IRSimplifier::simplify(body); IS_IMM_WITH_VAL(Int, simplified.node(), 0); } { // 0 % x => 0 ExprHandle body = ExprHandle(0) % x; ExprHandle simplified = IRSimplifier::simplify(body); IS_IMM_WITH_VAL(Int, simplified.node(), 0); } { // x % 1 => 0 ExprHandle body = x % 1; ExprHandle simplified = IRSimplifier::simplify(body); IS_IMM_WITH_VAL(Int, simplified.node(), 0); } { // Doesn't change unknown mods. // x % y => x % y ExprHandle body = x % y; ExprHandle simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(Mod, simplified.node(), mod); IS_VAR_WITH_NAME(mod->lhs(), "x"); IS_VAR_WITH_NAME(mod->rhs(), "y"); } { // don't touch if RHS is unknown. // 4 % x => 4 % x ExprHandle body = ExprHandle(4) % x; ExprHandle simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(Mod, simplified.node(), mod); IS_IMM_WITH_VAL(Int, mod->lhs(), 4); IS_VAR_WITH_NAME(mod->rhs(), "x"); } { // don't touch if LHS is unknown. // x % 4 => x % 4 ExprHandle body = x % 4; ExprHandle simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(Mod, simplified.node(), mod); IS_VAR_WITH_NAME(mod->lhs(), "x"); IS_IMM_WITH_VAL(Int, mod->rhs(), 4); } { // if LHS is a multiple of RHS, mod is zero. // 2 * x % x => 0 ExprHandle body = (x * 2) % x; ExprHandle simplified = IRSimplifier::simplify(body); IS_IMM_WITH_VAL(Int, simplified.node(), 0); } { // true even if the multiple is not constant. // x * y % x => 0 ExprHandle body = (x * y) % x; ExprHandle simplified = IRSimplifier::simplify(body); IS_IMM_WITH_VAL(Int, simplified.node(), 0); } { // true with multiple unknown values in LHS. // x * y * z % x => 0 ExprHandle body = (x * y * z) % x; ExprHandle simplified = IRSimplifier::simplify(body); IS_IMM_WITH_VAL(Int, simplified.node(), 0); } { // true if the denom is compound. // x * y * z % y * z => 0 ExprHandle body = (x * y * z) % (y * z); ExprHandle simplified = IRSimplifier::simplify(body); IS_IMM_WITH_VAL(Int, simplified.node(), 0); } { // Sanity check true with scalars that are multiples. // 12 * x % 4 => 0 ExprHandle body = (x * 12) % 4; ExprHandle simplified = IRSimplifier::simplify(body); IS_IMM_WITH_VAL(Int, simplified.node(), 0); } { // Sanity check not true if the smaller scalar is on LHS. // 4 * x % 12 => 4 * x % 12 ExprHandle body = (x * 4) % 12; ExprHandle simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(Mod, simplified.node(), mod); IS_NODE_WITH_NAME(Mul, mod->lhs(), mul); IS_IMM_WITH_VAL(Int, mul->lhs(), 4); IS_VAR_WITH_NAME(mul->rhs(), "x"); IS_IMM_WITH_VAL(Int, mod->rhs(), 12); } { // Both scalar and symbolic in multiple. // (6 * x * y) % (3 * x * y) => 0 ExprHandle body = (ExprHandle(6) * x * y) % (x * y * 3); ExprHandle simplified = IRSimplifier::simplify(body); IS_IMM_WITH_VAL(Int, simplified.node(), 0); } } // Test that mixing ops together simplifies as expected. TEST(Simplify, SimplifyMultiOp) { VarHandle x("x", kInt); VarHandle y("y", kInt); { // (x * y) + (x - y) => (x + x * y) - y ExprHandle body = (x * y) + (x - y); ExprHandle simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(Sub, simplified.node(), sub); IS_NODE_WITH_NAME(Add, sub->lhs(), add); IS_VAR_WITH_NAME(add->lhs(), "x"); IS_NODE_WITH_NAME(Mul, add->rhs(), mul); IS_VAR_WITH_NAME(mul->lhs(), "x"); IS_VAR_WITH_NAME(mul->rhs(), "y"); IS_VAR_WITH_NAME(sub->rhs(), "y"); } { // (x + y) - x * y => (x + y) - x * y ExprHandle body = (x + y) - x * y; ExprHandle simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(Sub, simplified.node(), sub); IS_NODE_WITH_NAME(Add, sub->lhs(), add); IS_NODE_WITH_NAME(Mul, sub->rhs(), mul); IS_VAR_WITH_NAME(add->lhs(), "x"); IS_VAR_WITH_NAME(add->rhs(), "y"); IS_VAR_WITH_NAME(mul->lhs(), "x"); IS_VAR_WITH_NAME(mul->rhs(), "y"); } { // (x - y) - (x + y) => -2 * y ExprHandle body = (x - y) - (x + y); ExprHandle simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(Mul, simplified.node(), mul); IS_IMM_WITH_VAL(Int, mul->lhs(), -2); IS_VAR_WITH_NAME(mul->rhs(), "y"); } { // (x - 0) + (x * 1) - (x + 0) => x ExprHandle body = (x - 0) + (x * 1) - (x + 0); ExprHandle simplified = IRSimplifier::simplify(body); IS_VAR_WITH_NAME(simplified.node(), "x"); } { // (x - 0.f) + (x * 1.f) - (x + 0.f) => float(x) + float(x) - float(x) // Even in Float simple terms cancel out, but the variable ones cannot. ExprHandle body = (x - ExprHandle(0.f)) + (x * ExprHandle(1.f)) - (x + ExprHandle(0.f)); ExprHandle simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(Sub, simplified.node(), sub); IS_NODE_WITH_NAME(Add, sub->lhs(), add); IS_NODE_WITH_NAME(Cast, add->lhs(), cast1); IS_VAR_WITH_NAME(cast1->src_value(), "x"); IS_NODE_WITH_NAME(Cast, add->rhs(), cast2); IS_VAR_WITH_NAME(cast2->src_value(), "x"); IS_NODE_WITH_NAME(Cast, sub->rhs(), cast3); IS_VAR_WITH_NAME(cast3->src_value(), "x"); } } // Test that chaining many ops together works as expected. TEST(Simplify, SimplifyManyOps) { VarHandle x("x", kInt); VarHandle y("y", kInt); { // x + y + x + x + y + y + x + y + x = 4 * y + 5 * x ExprHandle body = x + y + x + x + y + y + x + y + x; ExprHandle simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(Add, simplified.node(), add); IS_NODE_WITH_NAME(Mul, add->lhs(), lhs); IS_IMM_WITH_VAL(Int, lhs->lhs(), 4); IS_VAR_WITH_NAME(lhs->rhs(), "y"); IS_NODE_WITH_NAME(Mul, add->rhs(), rhs); IS_IMM_WITH_VAL(Int, rhs->lhs(), 5); IS_VAR_WITH_NAME(rhs->rhs(), "x"); } { // x - y + x + x - y - y + x - y + x = 5 * x - 4 * y ExprHandle body = x - y + x + x - y - y + x - y + x; ExprHandle simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(Sub, simplified.node(), add); IS_NODE_WITH_NAME(Mul, add->lhs(), lhs); IS_IMM_WITH_VAL(Int, lhs->lhs(), 5); IS_VAR_WITH_NAME(lhs->rhs(), "x"); IS_NODE_WITH_NAME(Mul, add->rhs(), rhs); IS_IMM_WITH_VAL(Int, rhs->lhs(), 4); IS_VAR_WITH_NAME(rhs->rhs(), "y"); } { // x + y + x - x - y - y + x + y + x = 3 * x ExprHandle body = x + y + x - x - y - y + x + y + x; ExprHandle simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(Mul, simplified.node(), mul); IS_IMM_WITH_VAL(Int, mul->lhs(), 3); IS_VAR_WITH_NAME(mul->rhs(), "x"); } } TEST(Simplify, SimplifyFactorization) { VarHandle x("x", kInt); VarHandle y("y", kInt); { // (2 * x) + (2 * y) => 2 * (x + y) ExprHandle body = (ExprHandle(2) * x + ExprHandle(2) * y); ExprHandle simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(Mul, simplified.node(), mul); IS_IMM_WITH_VAL(Int, mul->lhs(), 2); IS_NODE_WITH_NAME(Add, mul->rhs(), add); IS_VAR_WITH_NAME(add->lhs(), "x"); IS_VAR_WITH_NAME(add->rhs(), "y"); } { // Factorization when scalars have common divider. // (2 * x) + (4 * y) => 2 * (2 * y + x) ExprHandle body = (ExprHandle(2) * x + ExprHandle(4) * y); ExprHandle simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(Mul, simplified.node(), mul); IS_IMM_WITH_VAL(Int, mul->lhs(), 2); IS_NODE_WITH_NAME(Add, mul->rhs(), add); IS_VAR_WITH_NAME(add->lhs(), "x"); IS_NODE_WITH_NAME(Mul, add->rhs(), mul2); IS_IMM_WITH_VAL(Int, mul2->lhs(), 2); IS_VAR_WITH_NAME(mul2->rhs(), "y"); } { // Factorization attempt without a common divider. // (2 * x) + (5 * y) => (5 * y) + (2 * x) ExprHandle body = (ExprHandle(2) * x + ExprHandle(5) * y); ExprHandle simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(Add, simplified.node(), add); IS_NODE_WITH_NAME(Mul, add->lhs(), lhs); IS_IMM_WITH_VAL(Int, lhs->lhs(), 2); IS_VAR_WITH_NAME(lhs->rhs(), "x"); IS_NODE_WITH_NAME(Mul, add->rhs(), rhs); IS_IMM_WITH_VAL(Int, rhs->lhs(), 5); IS_VAR_WITH_NAME(rhs->rhs(), "y"); } { // Factorization after merging. // (2 * x) + (4 * y) + (8 * x + 6 * y) => 10 * (x + y) ExprHandle body = (ExprHandle(2) * x + ExprHandle(4) * y) + (ExprHandle(8) * x + ExprHandle(6) * y); ExprHandle simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(Mul, simplified.node(), mul); IS_IMM_WITH_VAL(Int, mul->lhs(), 10); IS_NODE_WITH_NAME(Add, mul->rhs(), add); IS_VAR_WITH_NAME(add->lhs(), "x"); IS_VAR_WITH_NAME(add->rhs(), "y"); } { // Factorization with common divider but different signs. // (2 * x) + (-4 * y) => 2 * (x - 2 * y) ExprHandle body = (ExprHandle(2) * x + ExprHandle(-4) * y); ExprHandle simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(Mul, simplified.node(), mul); IS_IMM_WITH_VAL(Int, mul->lhs(), 2); IS_NODE_WITH_NAME(Sub, mul->rhs(), sub); IS_VAR_WITH_NAME(sub->lhs(), "x"); IS_NODE_WITH_NAME(Mul, sub->rhs(), mul2); IS_IMM_WITH_VAL(Int, mul2->lhs(), 2); IS_VAR_WITH_NAME(mul2->rhs(), "y"); } { // Factorization with all negative numbers. // (-2 * x) + (-4 * y) => 2 * (-1 * x - 2 * y) ExprHandle body = ExprHandle(-2) * x + ExprHandle(-4) * y; ExprHandle simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(Mul, simplified.node(), mul); IS_IMM_WITH_VAL(Int, mul->lhs(), 2); IS_NODE_WITH_NAME(Sub, mul->rhs(), sub); IS_NODE_WITH_NAME(Mul, sub->lhs(), mul2); IS_IMM_WITH_VAL(Int, mul2->lhs(), -1); IS_VAR_WITH_NAME(mul2->rhs(), "x"); IS_NODE_WITH_NAME(Mul, sub->rhs(), mul3); IS_IMM_WITH_VAL(Int, mul3->lhs(), 2); IS_VAR_WITH_NAME(mul3->rhs(), "y"); } { // The following test ensures that there in no infinite recursion during // factorization when negative numbers are involved. VarHandle a("a", kInt); VarHandle b("b", kInt); VarHandle c("c", kInt); VarHandle d("d", kInt); VarHandle e("e", kInt); VarHandle f("f", kInt); VarHandle g("g", kInt); VarHandle h("h", kInt); ExprHandle body = a * 1024 + 0 + b * (-1) + c * (-1) + d * 1 + e * 1 + f * 32 + g * (-1024) + h * (-32); ExprHandle simplified = IRSimplifier::simplify(body); checkExprIR( simplified, "((((((d + e) + 1024 * a) + 32 * f) - b) - c) - 1024 * g) - 32 * h"); } } // (4 * x + y + z * 2) + (4 * x + y + z * 4) => 2 * (y + 3 * z + 4 * x) TEST(Simplify, SimplifyFactorizeUneven) { VarHandle x("x", kInt); VarHandle y("y", kInt); VarHandle z("z", kInt); ExprHandle body = (ExprHandle(4) * x + y + z * 2) + (ExprHandle(4) * x + y + z * 4); ExprHandle simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(Mul, simplified.node(), root); IS_IMM_WITH_VAL(Int, root->lhs(), 2); IS_NODE_WITH_NAME(Add, root->rhs(), add1); IS_NODE_WITH_NAME(Add, add1->lhs(), add2); IS_VAR_WITH_NAME(add2->lhs(), "y"); IS_NODE_WITH_NAME(Mul, add2->rhs(), zmul); IS_NODE_WITH_NAME(Mul, add1->rhs(), xmul); IS_IMM_WITH_VAL(Int, xmul->lhs(), 4); IS_VAR_WITH_NAME(xmul->rhs(), "x"); IS_IMM_WITH_VAL(Int, zmul->lhs(), 3); IS_VAR_WITH_NAME(zmul->rhs(), "z"); } // (x * y) + (2 * x) * (x + y) => 2 * (x * x) + 3 * (x * y) // This is kind of a placeholder test for variable factorization. TEST(Simplify, SimplifyDeeperTerms) { VarHandle x("x", kInt); VarHandle y("y", kInt); ExprHandle body = (x * y) + (ExprHandle(2) * x) * (x + y); ExprHandle simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(Add, simplified.node(), add); IS_NODE_WITH_NAME(Mul, add->lhs(), lhs); IS_IMM_WITH_VAL(Int, lhs->lhs(), 2); IS_NODE_WITH_NAME(Mul, lhs->rhs(), xxTerm); IS_VAR_WITH_NAME(xxTerm->lhs(), "x"); IS_VAR_WITH_NAME(xxTerm->rhs(), "x"); IS_NODE_WITH_NAME(Mul, add->rhs(), rhs); IS_IMM_WITH_VAL(Int, rhs->lhs(), 3); IS_NODE_WITH_NAME(Mul, rhs->rhs(), xyTerm); IS_VAR_WITH_NAME(xyTerm->lhs(), "x"); IS_VAR_WITH_NAME(xyTerm->rhs(), "y"); } // Tests the difference between two less trivial expressions. // (m * (1 * n_1) + (n + 1)) - (m * (1 * n_1) + n) => 1 TEST(Simplify, SimplifyDeeperDifference) { VarHandle n("n", kInt); VarHandle n_1("n_1", kInt); VarHandle m("m", kInt); ExprHandle body = (m * (ExprHandle(1) * n_1) + (n + 1)) - (m * (ExprHandle(1) * n_1) + n); ExprHandle simplified = IRSimplifier::simplify(body); IS_IMM_WITH_VAL(Int, simplified.node(), 1); } // Test constant folding into the difference between expressions. // 2 + char((m * (1 * n_1) + (n + 1)) - (m * (1 * n_1) + n)) => 3 TEST(Simplify, SimplifyFoldComplexDifference) { VarHandle n("n", kInt); VarHandle n_1("n_1", kInt); VarHandle m("m", kInt); ExprHandle body = (IntImm::make(2) + (Cast::make( kChar, (m * (ExprHandle(1) * n_1) + (n + 1)) - (m * (ExprHandle(1) * n_1) + n)))); ExprHandle simplified = IRSimplifier::simplify(body); IS_IMM_WITH_VAL(Int, simplified.node(), 3); } TEST(Simplify, SimplifyIfComponents) { VarHandle x("x", kInt); VarHandle y("y", kInt); ExprHandle body = IfThenElse::make( ((ExprHandle(5) - ExprHandle(4)) * x) > y, ExprHandle(2) * x - x, ExprHandle(2) * y - y); ExprHandle simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(IfThenElse, simplified.node(), ifexpr); IS_NODE_WITH_NAME(CompareSelect, ifexpr->condition(), cmp); ASSERT_EQ(cmp->compare_select_op(), kGT); IS_VAR_WITH_NAME(cmp->lhs(), "x"); IS_VAR_WITH_NAME(cmp->rhs(), "y"); IS_VAR_WITH_NAME(ifexpr->true_value(), "x"); IS_VAR_WITH_NAME(ifexpr->false_value(), "y"); } TEST(Simplify, SimplifyOpaqueTerms) { VarHandle x("x", kInt); VarHandle y("y", kInt); { // 2 * x/y * y - x/y * y => x/y * y ExprHandle body = ((ExprHandle(2)) * (x / y) * y) - ((x / y) * y); ExprHandle simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(Mul, simplified.node(), mul); IS_NODE_WITH_NAME(Div, mul->lhs(), div); IS_VAR_WITH_NAME(div->lhs(), "x"); IS_VAR_WITH_NAME(div->rhs(), "y"); IS_VAR_WITH_NAME(mul->rhs(), "y"); } { // x%y - (x%y - 1) => 1 ExprHandle body = (x % y) - ((x % y) - 1); ExprHandle simplified = IRSimplifier::simplify(body); IS_IMM_WITH_VAL(Int, simplified.node(), 1); } } TEST(Simplify, SimplifySymbolicMinMax) { { // Minimum with constant difference between terms. VarHandle x("x", kInt); ExprHandle body = Min::make(x + 3, x + 7, true); ExprHandle simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(Add, simplified.node(), add); IS_VAR_WITH_NAME(add->lhs(), "x"); IS_IMM_WITH_VAL(Int, add->rhs(), 3); } { // Maximum with constant difference between terms. VarHandle x("x", kInt); ExprHandle body = Max::make(x + 3, x + 7, true); ExprHandle simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(Add, simplified.node(), add); IS_VAR_WITH_NAME(add->lhs(), "x"); IS_IMM_WITH_VAL(Int, add->rhs(), 7); } { // Can't simplify multiples because of signedness of variable component. // TODO: maybe we could for unsigned types? VarHandle x("x", kInt); ExprHandle body = Max::make(x * 3, x * 7, true); ExprHandle simplified = IRSimplifier::simplify(body); IS_NODE(Max, simplified.node()); } } TEST(Simplify, SimplifyNestedMax) { VarHandle x("x", kInt); VarHandle y("y", kInt); VarHandle z("z", kInt); { // Max(x + y, x + y) => x + y ExprHandle body = Max::make(x + y, x + y, true); ExprHandle simplified = IRSimplifier::simplify(body); // NOLINTNEXTLINE(clang-analyzer-cplusplus.NewDeleteLeaks) IS_BINOP_W_VARS(Add, simplified.node(), add, "x", "y"); } { // Max(x + y, Max(x + y, z)) => Max(x + y, z) ExprHandle body = Max::make(x + y, Max::make(x + y, z, true), true); ExprHandle simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(Max, simplified.node(), max); IS_BINOP_W_VARS(Add, max->lhs(), add, "x", "y"); IS_VAR_WITH_NAME(max->rhs(), "z"); } { // Max(x + y, Max(z, x + y)) => Max(x + y, z) ExprHandle body = Max::make(x + y, Max::make(z, x + y, true), true); ExprHandle simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(Max, simplified.node(), max); IS_BINOP_W_VARS(Add, max->lhs(), add, "x", "y"); IS_VAR_WITH_NAME(max->rhs(), "z"); } { // Max(Max(x + y, z), x + y) => Max(x + y, z) ExprHandle body = Max::make(Max::make(x + y, z, true), x + y, true); ExprHandle simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(Max, simplified.node(), max); IS_BINOP_W_VARS(Add, max->lhs(), add, "x", "y"); IS_VAR_WITH_NAME(max->rhs(), "z"); } { // Max(Max(z, x + y), x + y) => Max(x + y, z) ExprHandle body = Max::make(Max::make(z, x + y, true), x + y, true); ExprHandle simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(Max, simplified.node(), max); IS_BINOP_W_VARS(Add, max->lhs(), add, "x", "y"); IS_VAR_WITH_NAME(max->rhs(), "z"); } { // Max(Max(x, y), x) => Max(Max(x, y), x) // Nested Max ops with different propagate_nans should not be simplified. ExprHandle body = Max::make(Max::make(x, y, true), x, false); ExprHandle simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(Max, simplified.node(), max); IS_BINOP_W_VARS(Max, max->lhs(), max1, "x", "y"); ASSERT_TRUE(max1->propagate_nans()); IS_VAR_WITH_NAME(max->rhs(), "x"); ASSERT_FALSE(max->propagate_nans()); } { // Max(Min(x, y), Min(x, z)) => Min(Max(y, z), x) ExprHandle body = Max::make(Min::make(x, y, true), Min::make(x, z, true), true); ExprHandle simplified = IRSimplifier::simplify(body); checkExprIR(simplified, "Min(Max(y, z, 1), x, 1)"); } { // Max(Min(x, y), Min(z, x)) => Min(Max(y, z), x) ExprHandle body = Max::make(Min::make(x, y, true), Min::make(z, x, true), true); ExprHandle simplified = IRSimplifier::simplify(body); checkExprIR(simplified, "Min(Max(y, z, 1), x, 1)"); } { // Max(Min(y, x), Min(x, z)) => Min(Max(y, z), x) ExprHandle body = Max::make(Min::make(y, x, true), Min::make(x, z, true), true); ExprHandle simplified = IRSimplifier::simplify(body); checkExprIR(simplified, "Min(Max(y, z, 1), x, 1)"); } { // Max(Min(y, x), Min(z, x)) => Min(Max(y, z), x) ExprHandle body = Max::make(Min::make(y, x, true), Min::make(z, x, true), true); ExprHandle simplified = IRSimplifier::simplify(body); checkExprIR(simplified, "Min(Max(y, z, 1), x, 1)"); } { // Max(Min(y, x), Min(z, x)) => Max(Min(x, y), Min(x, z)) // When all the ops in the pattern do not have the same propagate_nans, // it should not be simplified. ExprHandle body = Max::make(Min::make(y, x, true), Min::make(z, x, false), true); ExprHandle simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(Max, simplified.node(), max); IS_BINOP_W_VARS(Min, max->lhs(), min1, "x", "y"); ASSERT_TRUE(min1->propagate_nans()); IS_BINOP_W_VARS(Min, max->rhs(), min2, "x", "z"); ASSERT_FALSE(min2->propagate_nans()); ASSERT_TRUE(max->propagate_nans()); } { // Max(5, Max(x, 8)) => Max(x, 8) ExprHandle body = Max::make(5, Max::make(x, 8, true), true); ExprHandle simplified = IRSimplifier::simplify(body); IS_BINOP_W_CONST(Max, simplified.node(), max, "x", 8); ASSERT_TRUE(max->propagate_nans()); } { // Max(8, Max(x, 5)) => Max(x, 8) ExprHandle body = Max::make(8, Max::make(x, 5, true), true); ExprHandle simplified = IRSimplifier::simplify(body); IS_BINOP_W_CONST(Max, simplified.node(), max, "x", 8); ASSERT_TRUE(max->propagate_nans()); } { // Max(Max(x, 8), 5) => Max(x, 8) ExprHandle body = Max::make(Max::make(x, 8, true), 5, true); ExprHandle simplified = IRSimplifier::simplify(body); IS_BINOP_W_CONST(Max, simplified.node(), max, "x", 8); ASSERT_TRUE(max->propagate_nans()); } { // Max(Max(x, 5), 8) => Max(x, 8) ExprHandle body = Max::make(Max::make(x, 5, true), 8, true); ExprHandle simplified = IRSimplifier::simplify(body); IS_BINOP_W_CONST(Max, simplified.node(), max, "x", 8); ASSERT_TRUE(max->propagate_nans()); } { // Max(5, Max(x, Max(y, Max(z, 8)))) => Max(Max(Max(x, 8), y), z) ExprHandle body = Max::make( 5, Max::make(x, Max::make(y, Max::make(z, 8, true), true), true), true); ExprHandle simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(Max, simplified.node(), max1); IS_NODE_WITH_NAME(Max, max1->lhs(), max2); IS_BINOP_W_CONST(Max, max2->lhs(), max3, "x", 8); ASSERT_TRUE(max3->propagate_nans()); IS_VAR_WITH_NAME(max2->rhs(), "y"); IS_VAR_WITH_NAME(max1->rhs(), "z"); } { // Max(8, Max(Max(y, Max(z, 5)), x)) => Max(Max(Max(x, 8), y), z) ExprHandle body = Max::make( 8, Max::make(Max::make(y, Max::make(z, 5, true), true), x, true), true); ExprHandle simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(Max, simplified.node(), max1); IS_NODE_WITH_NAME(Max, max1->lhs(), max2); IS_BINOP_W_CONST(Max, max2->lhs(), max3, "x", 8); ASSERT_TRUE(max3->propagate_nans()); IS_VAR_WITH_NAME(max2->rhs(), "y"); IS_VAR_WITH_NAME(max1->rhs(), "z"); } { // Max(5, Max(Max(Max(z, 8), y), x)) => Max(Max(Max(x, 8), y), z) ExprHandle body = Max::make( 5, Max::make(Max::make(Max::make(z, 8, true), y, true), x, true), true); ExprHandle simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(Max, simplified.node(), max1); IS_NODE_WITH_NAME(Max, max1->lhs(), max2); IS_BINOP_W_CONST(Max, max2->lhs(), max3, "x", 8); ASSERT_TRUE(max3->propagate_nans()); IS_VAR_WITH_NAME(max2->rhs(), "y"); IS_VAR_WITH_NAME(max1->rhs(), "z"); } { // Max(Max(x, Max(y, Max(5, z))), 8) => Max(Max(Max(x, 8), y), z) ExprHandle body = Max::make( Max::make(x, Max::make(y, Max::make(5, z, true), true), true), 8, true); ExprHandle simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(Max, simplified.node(), max1); IS_NODE_WITH_NAME(Max, max1->lhs(), max2); IS_BINOP_W_CONST(Max, max2->lhs(), max3, "x", 8); ASSERT_TRUE(max3->propagate_nans()); IS_VAR_WITH_NAME(max2->rhs(), "y"); IS_VAR_WITH_NAME(max1->rhs(), "z"); } { // Max(Max(Max(y, Max(8, z)), x), 5) => Max(Max(Max(x, 8), y), z) ExprHandle body = Max::make( Max::make(Max::make(y, Max::make(z, 8, true), true), x, true), 5, true); ExprHandle simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(Max, simplified.node(), max1); IS_NODE_WITH_NAME(Max, max1->lhs(), max2); IS_BINOP_W_CONST(Max, max2->lhs(), max3, "x", 8); ASSERT_TRUE(max3->propagate_nans()); IS_VAR_WITH_NAME(max2->rhs(), "y"); IS_VAR_WITH_NAME(max1->rhs(), "z"); } { // Max(Max(Max(Max(5, z), y), x), 8) => Max(Max(Max(x, 8), y), z) ExprHandle body = Max::make( Max::make(Max::make(Max::make(z, 5, true), y, true), x, true), 8, true); ExprHandle simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(Max, simplified.node(), max1); IS_NODE_WITH_NAME(Max, max1->lhs(), max2); IS_BINOP_W_CONST(Max, max2->lhs(), max3, "x", 8); ASSERT_TRUE(max3->propagate_nans()); IS_VAR_WITH_NAME(max2->rhs(), "y"); IS_VAR_WITH_NAME(max1->rhs(), "z"); } { // Max(Max(Max(Max(z, 5), y), x), 8) => Max(Max(x, Max(Max(z, 5), y)), 8) // Do not simplify when all the Max ops do not have the same // propagate_nans. ExprHandle body = Max::make( Max::make(Max::make(Max::make(z, 5, true), y, false), x, true), 8, false); ExprHandle simplified = IRSimplifier::simplify(body); checkExprIR(simplified, "Max(Max(Max(Max(z, 5, 1), y, 0), x, 1), 8, 0)"); } { // Max(8, Max(Max(x, 5), Max(y, z))) => Max(Max(Max(x, 8), y), z) ExprHandle body = Max::make( 8, Max::make(Max::make(x, 5, true), Max::make(y, z, true), true), true); ExprHandle simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(Max, simplified.node(), max1); IS_NODE_WITH_NAME(Max, max1->lhs(), max2); IS_BINOP_W_CONST(Max, max2->lhs(), max3, "x", 8); ASSERT_TRUE(max3->propagate_nans()); IS_VAR_WITH_NAME(max2->rhs(), "y"); IS_VAR_WITH_NAME(max1->rhs(), "z"); } { // Max(Max(Max(x, 5), Max(y, z)), 8) => Max(Max(Max(x, 8), y), z) ExprHandle body = Max::make( Max::make(Max::make(x, 5, true), Max::make(y, z, true), true), 8, true); ExprHandle simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(Max, simplified.node(), max1); IS_NODE_WITH_NAME(Max, max1->lhs(), max2); IS_BINOP_W_CONST(Max, max2->lhs(), max3, "x", 8); ASSERT_TRUE(max3->propagate_nans()); IS_VAR_WITH_NAME(max2->rhs(), "y"); IS_VAR_WITH_NAME(max1->rhs(), "z"); } } TEST(Simplify, SimplifyNestedMin) { VarHandle x("x", kInt); VarHandle y("y", kInt); VarHandle z("z", kInt); { // Min(x + y, x + y) => x + y ExprHandle body = Min::make(x + y, x + y, true); ExprHandle simplified = IRSimplifier::simplify(body); // NOLINTNEXTLINE(clang-analyzer-cplusplus.NewDeleteLeaks) IS_BINOP_W_VARS(Add, simplified.node(), add, "x", "y"); } { // Min(x + y, Min(x + y, z)) => Min(x + y, z) ExprHandle body = Min::make(x + y, Min::make(x + y, z, true), true); ExprHandle simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(Min, simplified.node(), min); IS_BINOP_W_VARS(Add, min->lhs(), add, "x", "y"); IS_VAR_WITH_NAME(min->rhs(), "z"); } { // Min(x + y, Min(z, x + y)) => Min(x + y, z) ExprHandle body = Min::make(x + y, Min::make(z, x + y, true), true); ExprHandle simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(Min, simplified.node(), min); IS_BINOP_W_VARS(Add, min->lhs(), add, "x", "y"); IS_VAR_WITH_NAME(min->rhs(), "z"); } { // Min(Min(x + y, z), x + y) => Min(x + y, z) ExprHandle body = Min::make(Min::make(x + y, z, true), x + y, true); ExprHandle simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(Min, simplified.node(), min); IS_BINOP_W_VARS(Add, min->lhs(), add, "x", "y"); IS_VAR_WITH_NAME(min->rhs(), "z"); } { // Min(Min(z, x + y), x + y) => Min(x + y, z) ExprHandle body = Min::make(Min::make(z, x + y, true), x + y, true); ExprHandle simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(Min, simplified.node(), min); IS_BINOP_W_VARS(Add, min->lhs(), add, "x", "y"); IS_VAR_WITH_NAME(min->rhs(), "z"); } { // Min(Min(x, y), x) => Min(Min(x, y), x) // Nested Min ops with different propagate_nans should not be simplified. ExprHandle body = Min::make(Min::make(x, y, true), x, false); ExprHandle simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(Min, simplified.node(), min1); IS_BINOP_W_VARS(Min, min1->lhs(), min2, "x", "y"); ASSERT_TRUE(min2->propagate_nans()); IS_VAR_WITH_NAME(min1->rhs(), "x"); ASSERT_FALSE(min1->propagate_nans()); } { // Min(Max(x, y), Max(x, z)) => Max(Min(y, z), x) ExprHandle body = Min::make(Max::make(x, y, true), Max::make(x, z, true), true); ExprHandle simplified = IRSimplifier::simplify(body); checkExprIR(simplified, "Max(Min(y, z, 1), x, 1)"); } { // Min(Max(x, y), Max(z, x)) => Max(Min(y, z), x) ExprHandle body = Min::make(Max::make(x, y, true), Max::make(z, x, true), true); ExprHandle simplified = IRSimplifier::simplify(body); checkExprIR(simplified, "Max(Min(y, z, 1), x, 1)"); } { // Min(Max(y, x), Max(x, z)) => Max(Min(y, z), x) ExprHandle body = Min::make(Max::make(y, x, true), Max::make(x, z, true), true); ExprHandle simplified = IRSimplifier::simplify(body); checkExprIR(simplified, "Max(Min(y, z, 1), x, 1)"); } { // Min(Max(y, x), Max(z, x)) => Max(Min(y, z), x) ExprHandle body = Min::make(Max::make(y, x, true), Max::make(z, x, true), true); ExprHandle simplified = IRSimplifier::simplify(body); checkExprIR(simplified, "Max(Min(y, z, 1), x, 1)"); } { // Min(Max(y, x), Max(z, x)) => Min(Max(x, y), Max(x, z)) // When all the ops in the pattern do not have the same propagate_nans, // it should not be simplified. ExprHandle body = Min::make(Max::make(y, x, true), Max::make(z, x, false), true); ExprHandle simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(Min, simplified.node(), min); IS_BINOP_W_VARS(Max, min->lhs(), max1, "x", "y"); ASSERT_TRUE(max1->propagate_nans()); IS_BINOP_W_VARS(Max, min->rhs(), max2, "x", "z"); ASSERT_FALSE(max2->propagate_nans()); ASSERT_TRUE(min->propagate_nans()); } { // Min(5, Min(x, 8)) => Min(x, 8) ExprHandle body = Min::make(5, Min::make(x, 8, true), true); ExprHandle simplified = IRSimplifier::simplify(body); IS_BINOP_W_CONST(Min, simplified.node(), min, "x", 5); ASSERT_TRUE(min->propagate_nans()); } { // Min(8, Min(x, 5)) => Min(x, 8) ExprHandle body = Min::make(8, Min::make(x, 5, true), true); ExprHandle simplified = IRSimplifier::simplify(body); IS_BINOP_W_CONST(Min, simplified.node(), min, "x", 5); ASSERT_TRUE(min->propagate_nans()); } { // Min(Min(x, 8), 5) => Min(x, 8) ExprHandle body = Min::make(Min::make(x, 8, true), 5, true); ExprHandle simplified = IRSimplifier::simplify(body); IS_BINOP_W_CONST(Min, simplified.node(), min, "x", 5); ASSERT_TRUE(min->propagate_nans()); } { // Min(Min(x, 5), 8) => Min(x, 8) ExprHandle body = Min::make(Min::make(x, 5, true), 8, true); ExprHandle simplified = IRSimplifier::simplify(body); IS_BINOP_W_CONST(Min, simplified.node(), min, "x", 5); ASSERT_TRUE(min->propagate_nans()); } { // Min(5, Min(x, Min(y, Min(z, 8)))) => Min(Min(Min(x, 5), y), z) ExprHandle body = Min::make( 5, Min::make(x, Min::make(y, Min::make(z, 8, true), true), true), true); ExprHandle simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(Min, simplified.node(), min1); IS_NODE_WITH_NAME(Min, min1->lhs(), min2); IS_BINOP_W_CONST(Min, min2->lhs(), min3, "x", 5); ASSERT_TRUE(min3->propagate_nans()); IS_VAR_WITH_NAME(min2->rhs(), "y"); IS_VAR_WITH_NAME(min1->rhs(), "z"); } { // Min(5, Min(Min(y, Min(z, 8)), x)) => Min(Min(Min(x, 5), y), z) ExprHandle body = Min::make( 5, Min::make(Min::make(y, Min::make(z, 8, true), true), x, true), true); ExprHandle simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(Min, simplified.node(), min1); IS_NODE_WITH_NAME(Min, min1->lhs(), min2); IS_BINOP_W_CONST(Min, min2->lhs(), min3, "x", 5); ASSERT_TRUE(min3->propagate_nans()); IS_VAR_WITH_NAME(min2->rhs(), "y"); IS_VAR_WITH_NAME(min1->rhs(), "z"); } { // Min(5, Min(Min(Min(z, 8), y), x)) => Min(Min(Min(x, 5), y), z) ExprHandle body = Min::make( 5, Min::make(Min::make(Min::make(z, 8, true), y, true), x, true), true); ExprHandle simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(Min, simplified.node(), min1); IS_NODE_WITH_NAME(Min, min1->lhs(), min2); IS_BINOP_W_CONST(Min, min2->lhs(), min3, "x", 5); ASSERT_TRUE(min3->propagate_nans()); IS_VAR_WITH_NAME(min2->rhs(), "y"); IS_VAR_WITH_NAME(min1->rhs(), "z"); } { // Min(Min(x, Min(y, Min(8, z))), 5) => Min(Min(Min(x, 5), y), z) ExprHandle body = Min::make( Min::make(x, Min::make(y, Min::make(8, z, true), true), true), 5, true); ExprHandle simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(Min, simplified.node(), min1); IS_NODE_WITH_NAME(Min, min1->lhs(), min2); IS_BINOP_W_CONST(Min, min2->lhs(), min3, "x", 5); ASSERT_TRUE(min3->propagate_nans()); IS_VAR_WITH_NAME(min2->rhs(), "y"); IS_VAR_WITH_NAME(min1->rhs(), "z"); } { // Min(Min(Min(y, Min(8, z)), x), 5) => Min(Min(Min(x, 5), y), z) ExprHandle body = Min::make( Min::make(Min::make(y, Min::make(z, 8, true), true), x, true), 5, true); ExprHandle simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(Min, simplified.node(), min1); IS_NODE_WITH_NAME(Min, min1->lhs(), min2); IS_BINOP_W_CONST(Min, min2->lhs(), min3, "x", 5); ASSERT_TRUE(min3->propagate_nans()); IS_VAR_WITH_NAME(min2->rhs(), "y"); IS_VAR_WITH_NAME(min1->rhs(), "z"); } { // Min(Min(Min(Min(8, z), y), x), 5) => Min(Min(Min(x, 5), y), z) ExprHandle body = Min::make( Min::make(Min::make(Min::make(z, 8, true), y, true), x, true), 5, true); ExprHandle simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(Min, simplified.node(), min1); IS_NODE_WITH_NAME(Min, min1->lhs(), min2); IS_BINOP_W_CONST(Min, min2->lhs(), min3, "x", 5); ASSERT_TRUE(min3->propagate_nans()); IS_VAR_WITH_NAME(min2->rhs(), "y"); IS_VAR_WITH_NAME(min1->rhs(), "z"); } { // Min(Min(Min(Min(z, 5), y), x), 8) => Min(Min(Min(Min(z, 5), y), x), 8) // Do not simplify when all the Min ops do not have the same // propagate_nans. ExprHandle body = Min::make( Min::make(Min::make(Min::make(z, 5, true), y, false), x, true), 8, false); ExprHandle simplified = IRSimplifier::simplify(body); checkExprIR(simplified, "Min(Min(Min(Min(z, 5, 1), y, 0), x, 1), 8, 0)"); } { // Min(8, Min(Min(x, 5), Min(y, z))) => Min(Min(Min(x, 5), y), z) ExprHandle body = Min::make( 8, Min::make(Min::make(x, 5, true), Min::make(y, z, true), true), true); ExprHandle simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(Min, simplified.node(), min1); IS_NODE_WITH_NAME(Min, min1->lhs(), min2); IS_BINOP_W_CONST(Min, min2->lhs(), min3, "x", 5); ASSERT_TRUE(min3->propagate_nans()); IS_VAR_WITH_NAME(min2->rhs(), "y"); IS_VAR_WITH_NAME(min1->rhs(), "z"); } { // Min(Min(Min(x, 5), Min(y, z)), 8) => Min(Min(Min(x, 5), y), z) ExprHandle body = Min::make( Min::make(Min::make(x, 5, true), Min::make(y, z, true), true), 8, true); ExprHandle simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(Min, simplified.node(), min1); IS_NODE_WITH_NAME(Min, min1->lhs(), min2); IS_BINOP_W_CONST(Min, min2->lhs(), min3, "x", 5); ASSERT_TRUE(min3->propagate_nans()); IS_VAR_WITH_NAME(min2->rhs(), "y"); IS_VAR_WITH_NAME(min1->rhs(), "z"); } } TEST(Simplify, SimplifyWontReorderFloat) { { // 3 * (3 * x) - 3 * (3 * y) => 9 * (x - y) // This is an expression we can simplify. VarHandle x("x", kInt); VarHandle y("y", kInt); ExprHandle body = ExprHandle(3) * (ExprHandle(3) * x) - ExprHandle(3) * (ExprHandle(3) * y); ExprHandle simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(Mul, simplified.node(), mul); IS_IMM_WITH_VAL(Int, mul->lhs(), 9); IS_NODE_WITH_NAME(Sub, mul->rhs(), sub); IS_VAR_WITH_NAME(sub->lhs(), "x"); IS_VAR_WITH_NAME(sub->rhs(), "y"); } { // 3 * (3 * x) - 3 * (3 * y) => 3 * (3 * x) - 3 * (3 * y). // If the vars are floating point, ops are not associative and we can't // reorder. VarHandle x("x", kFloat); VarHandle y("y", kFloat); ExprHandle body = ExprHandle(3) * (ExprHandle(3) * x) - ExprHandle(3) * (ExprHandle(3) * y); ExprHandle simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(Sub, simplified.node(), sub); IS_NODE_WITH_NAME(Mul, sub->lhs(), lhsMul); IS_IMM_WITH_VAL(Float, lhsMul->lhs(), 3); IS_NODE_WITH_NAME(Mul, lhsMul->rhs(), lhsVarMul); IS_IMM_WITH_VAL(Float, lhsVarMul->lhs(), 3); IS_VAR_WITH_NAME(lhsVarMul->rhs(), "x"); IS_NODE_WITH_NAME(Mul, sub->rhs(), rhsMul); IS_IMM_WITH_VAL(Float, rhsMul->lhs(), 3); IS_NODE_WITH_NAME(Mul, rhsMul->rhs(), rhsVarMul); IS_IMM_WITH_VAL(Float, rhsVarMul->lhs(), 3); IS_VAR_WITH_NAME(rhsVarMul->rhs(), "y"); } { // 3 * (3 * x) - 3 * (3 * y) => 3 * (3 * x) - (9 * y). // We will simplify subexprs if they dont reorder floating point ops. VarHandle x("x", kDouble); VarHandle y("y", kInt); ExprHandle body = ExprHandle(3) * (ExprHandle(3) * x) - ExprHandle(3) * (ExprHandle(3) * y); ExprHandle simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(Sub, simplified.node(), sub); IS_NODE_WITH_NAME(Mul, sub->lhs(), lhsMul); IS_IMM_WITH_VAL(Double, lhsMul->lhs(), 3); IS_NODE_WITH_NAME(Mul, lhsMul->rhs(), lhsVarMul); IS_IMM_WITH_VAL(Double, lhsVarMul->lhs(), 3); IS_VAR_WITH_NAME(lhsVarMul->rhs(), "x"); IS_NODE_WITH_NAME_AND_CAST(Mul, sub->rhs(), rhsMul, Double); IS_IMM_WITH_VAL(Int, rhsMul->lhs(), 9); IS_VAR_WITH_NAME(rhsMul->rhs(), "y"); } { // Prevent reordering if FP propagated from dtypes. VarHandle x("x", kInt); VarHandle y("y", kInt); ExprHandle body = ExprHandle(3.f) * (ExprHandle(3) * x) - ExprHandle(3) * (ExprHandle(3.f) * y); ExprHandle simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(Sub, simplified.node(), sub); IS_NODE_WITH_NAME(Mul, sub->lhs(), lhsMul); IS_IMM_WITH_VAL(Float, lhsMul->lhs(), 3); IS_NODE_WITH_NAME_AND_CAST(Mul, lhsMul->rhs(), lhsVarMul, Float); IS_IMM_WITH_VAL(Int, lhsVarMul->lhs(), 3); IS_VAR_WITH_NAME(lhsVarMul->rhs(), "x"); IS_NODE_WITH_NAME(Mul, sub->rhs(), rhsMul); IS_IMM_WITH_VAL(Float, rhsMul->lhs(), 3); IS_NODE_WITH_NAME(Mul, rhsMul->rhs(), rhsVarMul); IS_IMM_WITH_VAL(Float, rhsVarMul->lhs(), 3); IS_NODE_WITH_NAME(Cast, rhsVarMul->rhs(), yCast); IS_VAR_WITH_NAME(yCast->src_value(), "y"); } { VarHandle x("x", kFloat); VarHandle y("y", kFloat); // x%y - (x%y - 1) => x%y - (x%y - 1). // We wont reorder opaque ops if they are FP. ExprHandle body = (x % y) - ((x % y) - 1); ExprHandle simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(Sub, simplified.node(), sub); IS_NODE_WITH_NAME(Mod, sub->lhs(), lhsMod); IS_VAR_WITH_NAME(lhsMod->lhs(), "x"); IS_VAR_WITH_NAME(lhsMod->rhs(), "y"); IS_NODE_WITH_NAME(Sub, sub->rhs(), rhsSub); IS_NODE_WITH_NAME(Mod, rhsSub->lhs(), rhsMod); IS_VAR_WITH_NAME(rhsMod->lhs(), "x"); IS_VAR_WITH_NAME(rhsMod->rhs(), "y"); IS_IMM_WITH_VAL(Float, rhsSub->rhs(), 1); } } TEST(Simplify, SimplifyRoundModPattern) { { // (x/y)*y + x%y => x. VarHandle x("x", kInt); VarHandle y("y", kInt); ExprHandle body = ((x / y) * y) + (x % y); ExprHandle simplified = IRSimplifier::simplify(body); IS_VAR_WITH_NAME(simplified.node(), "x"); } { // Reverse order. // x%y + (x/y)*y => x. VarHandle x("x", kInt); VarHandle y("y", kInt); ExprHandle body = (x % y) + ((x / y) * y); ExprHandle simplified = IRSimplifier::simplify(body); IS_VAR_WITH_NAME(simplified.node(), "x"); } { // Non opaque denominator. // (x / (4+y)) * (4+y)) + (x % (y + 4)) => x. VarHandle x("x", kInt); VarHandle y("y", kInt); ExprHandle body = ((x / (ExprHandle(4) + y)) * (ExprHandle(4) + y)) + (x % (y + ExprHandle(4))); ExprHandle simplified = IRSimplifier::simplify(body); IS_VAR_WITH_NAME(simplified.node(), "x"); } { // Reverse order. // (x % (y + 4)) + (x / (4+y)) * (4+y)) => x. VarHandle x("x", kInt); VarHandle y("y", kInt); ExprHandle body = (x % (y + ExprHandle(4))) + ((x / (ExprHandle(4) + y)) * (ExprHandle(4) + y)); ExprHandle simplified = IRSimplifier::simplify(body); IS_VAR_WITH_NAME(simplified.node(), "x"); } { // Opaque denominator. // (x / (2/y)) * (2/y)) + (x % (2/y)) => x. VarHandle x("x", kInt); VarHandle y("y", kInt); ExprHandle body = ((x / (ExprHandle(2) / y)) * (ExprHandle(2) / y)) + (x % (ExprHandle(2) / y)); ExprHandle simplified = IRSimplifier::simplify(body); IS_VAR_WITH_NAME(simplified.node(), "x"); } { // Non opaque numerator // ((2*x)/y * y) + ((2*x) % y) => 2 * x. VarHandle x("x", kInt); VarHandle y("y", kInt); ExprHandle body = (((ExprHandle(2) * x) / y) * y) + ((ExprHandle(2) * x) % y); ExprHandle simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(Mul, simplified.node(), mul); IS_IMM_WITH_VAL(Int, mul->lhs(), 2); IS_VAR_WITH_NAME(mul->rhs(), "x"); } { // Opaque numerator. // ((x/2) / y * y) + (x/2 % y) => x / 2. VarHandle x("x", kInt); VarHandle y("y", kInt); ExprHandle body = (((x / ExprHandle(2)) / y) * y) + ((x / ExprHandle(2)) % y); ExprHandle simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(Div, simplified.node(), div); IS_VAR_WITH_NAME(div->lhs(), "x"); IS_IMM_WITH_VAL(Int, div->rhs(), 2); } { // Numerator and denominator. // ((2*x)/(2*y) * (2*y)) + ((2*x) % (2*y)) => 2 * x. VarHandle x("x", kInt); VarHandle y("y", kInt); ExprHandle body = (((ExprHandle(2) * x) / (ExprHandle(2) * y)) * (ExprHandle(2) * y)) + ((ExprHandle(2) * x) % (ExprHandle(2) * y)); ExprHandle simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(Mul, simplified.node(), mul); IS_IMM_WITH_VAL(Int, mul->lhs(), 2); IS_VAR_WITH_NAME(mul->rhs(), "x"); } { // Reverse order. // ((2*x) % (2*y)) + ((2*x)/(2*y) * (2*y)) => 2 * x. VarHandle x("x", kInt); VarHandle y("y", kInt); ExprHandle body = ((ExprHandle(2) * x) % (ExprHandle(2) * y)) + (((ExprHandle(2) * x) / (ExprHandle(2) * y)) * (ExprHandle(2) * y)); ExprHandle simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(Mul, simplified.node(), mul); IS_IMM_WITH_VAL(Int, mul->lhs(), 2); IS_VAR_WITH_NAME(mul->rhs(), "x"); } { // Negated Subtraction of Round Mod. // (x/y) * y - (0 - x%y) => x. VarHandle x("x", kInt); VarHandle y("y", kInt); ExprHandle body = ((x / y) * y) - (ExprHandle(0) - (x % y)); ExprHandle simplified = IRSimplifier::simplify(body); IS_VAR_WITH_NAME(simplified.node(), "x"); } { // Other terms are preserved. // (x/y)*y + x%y + (y * x) => x + (y * x). VarHandle x("x", kInt); VarHandle y("y", kInt); ExprHandle body = ((x / y) * y) + (x % y) + (y * x); ExprHandle simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(Add, simplified.node(), add); IS_VAR_WITH_NAME(add->lhs(), "x"); IS_NODE_WITH_NAME(Mul, add->rhs(), mul); IS_VAR_WITH_NAME(mul->lhs(), "x"); IS_VAR_WITH_NAME(mul->rhs(), "y"); } { // Sanity checking we wont do the optimization on floats. VarHandle x("x", kFloat); VarHandle y("y", kFloat); ExprHandle body = ((x / y) * y) + (x % y); ExprHandle simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(Add, simplified.node(), add); IS_NODE_WITH_NAME(Mul, add->lhs(), roundMul); IS_NODE_WITH_NAME(Div, roundMul->lhs(), roundDiv); IS_VAR_WITH_NAME(roundDiv->lhs(), "x"); IS_VAR_WITH_NAME(roundDiv->rhs(), "y"); IS_VAR_WITH_NAME(roundMul->rhs(), "y"); IS_NODE_WITH_NAME(Mod, add->rhs(), mod); IS_VAR_WITH_NAME(mod->lhs(), "x"); IS_VAR_WITH_NAME(mod->rhs(), "y"); } { // Sanity check we wont do it if the mod term doesn't match. VarHandle x("x", kInt); VarHandle y("y", kInt); VarHandle z("z", kInt); ExprHandle body = ((x / y) * y) + (x % z); ExprHandle simplified = IRSimplifier::simplify(body); checkExprIR(simplified, "(x / y) * y + x % z"); } { // Sanity check we wont do it if the div term doesn't match. VarHandle x("x", kInt); VarHandle y("y", kInt); VarHandle z("z", kInt); ExprHandle body = (y * (x / z)) + (x % y); ExprHandle simplified = IRSimplifier::simplify(body); checkExprIR(simplified, "x % y + (x / z) * y"); } { // Sanity check we wont do it if the mul term doesn't match. VarHandle x("x", kInt); VarHandle y("y", kInt); VarHandle z("z", kInt); ExprHandle body = ((x / y) * z) + (x % y); ExprHandle simplified = IRSimplifier::simplify(body); checkExprIR(simplified, "x % y + (x / y) * z"); } } TEST(Simplify, SimplifyRoundModPatternFactorization) { { // Full factorization. // 2 * (x/y * y) + 2 * (x%y) => 2 * x. VarHandle x("x", kInt); VarHandle y("y", kInt); ExprHandle body = ExprHandle(2) * ((x / y) * y) + ExprHandle(2) * (x % y); ExprHandle simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(Mul, simplified.node(), mul); IS_IMM_WITH_VAL(Int, mul->lhs(), 2); IS_VAR_WITH_NAME(mul->rhs(), "x"); } { // Partial Factorization. // 32 * (x/8) + 4 * (x % 8) => 4 * x. VarHandle x("x", kInt); VarHandle y("y", kInt); // NOLINTNEXTLINE(clang-analyzer-cplusplus.NewDeleteLeaks,cppcoreguidelines-avoid-magic-numbers) ExprHandle body = ExprHandle(32) * (x / 8) + ExprHandle(4) * (x % 8); ExprHandle simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(Mul, simplified.node(), mul); IS_IMM_WITH_VAL(Int, mul->lhs(), 4); IS_VAR_WITH_NAME(mul->rhs(), "x"); } { // Factorization requiring constant folding. // 20 * (x / (16 / 2)) * 2 + (11 % 6) * (x % (7+1)) => 5 * x. VarHandle x("x", kInt); ExprHandle body = ExprHandle(40) * (x / (ExprHandle(16) / 2)) + (ExprHandle(11) % 6) * (x % (ExprHandle(7) + 1)); ExprHandle simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(Mul, simplified.node(), mul); IS_IMM_WITH_VAL(Int, mul->lhs(), 5); IS_VAR_WITH_NAME(mul->rhs(), "x"); } { VarHandle x("x", kInt); ExprHandle body = (x / 5) * 10 + ExprHandle(2) * (x % 5); ExprHandle simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(Mul, simplified.node(), mul); IS_IMM_WITH_VAL(Int, mul->lhs(), 2); IS_VAR_WITH_NAME(mul->rhs(), "x"); } { VarHandle x("x", kInt); ExprHandle body = (x / 10) * 0 + x % 5; ExprHandle simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(Mod, simplified.node(), mod); IS_VAR_WITH_NAME(mod->lhs(), "x"); IS_IMM_WITH_VAL(Int, mod->rhs(), 5); } } TEST(Simplify, SimplifyRoundModPatternMultivar) { { // Multivar. // (x/8) * 8 + (y/5)*5 + x%8 + y%5 => x + y. VarHandle x("x", kInt); VarHandle y("y", kInt); ExprHandle body = (x / ExprHandle(8) * ExprHandle(8)) + (y / ExprHandle(5) * ExprHandle(5)) + (x % 8) + (y % 5); ExprHandle simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(Add, simplified.node(), add); IS_VAR_WITH_NAME(add->lhs(), "x"); IS_VAR_WITH_NAME(add->rhs(), "y"); } { // Find the right var. // (y/8) * 8 x%8 + y%8 + z%8 => x%8 + y + z%8 VarHandle x("x", kInt); VarHandle y("y", kInt); VarHandle z("z", kInt); ExprHandle body = (y / ExprHandle(8) * ExprHandle(8)) + (x % 8) + (y % 8) + (z % 8); ExprHandle simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(Add, simplified.node(), add); IS_NODE_WITH_NAME(Add, add->lhs(), add2); IS_NODE_WITH_NAME(Mod, add2->lhs(), xMod); IS_VAR_WITH_NAME(xMod->lhs(), "x"); IS_IMM_WITH_VAL(Int, xMod->rhs(), 8); IS_VAR_WITH_NAME(add2->rhs(), "y"); IS_NODE_WITH_NAME(Mod, add->rhs(), zMod); IS_VAR_WITH_NAME(zMod->lhs(), "z"); IS_IMM_WITH_VAL(Int, zMod->rhs(), 8); } { // Compound. // (x + (z + 512 * y) % 16) + 16 * ((z + 512 * y) / 16) // => (z + 512 * y) + x VarHandle x("x", kInt); VarHandle y("y", kInt); VarHandle z("z", kInt); ExprHandle body = x + (z + y * 512) % 16 + ((z + y * 512) / 16 * 16); ExprHandle simplified = IRSimplifier::simplify(body); checkExprIR(simplified, "x + (z + 512 * y)"); } } TEST(Simplify, SimplifyModRoundModPattern) { { // t/7 % 9 * 7 + t % 7 => t%63 VarHandle t("t", kInt); ExprHandle body = (t / 7 % 9) * 7 + t % 7; ExprHandle simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(Mod, simplified.node(), mod); IS_VAR_WITH_NAME(mod->lhs(), "t"); IS_IMM_WITH_VAL(Int, mod->rhs(), 63); } { // 2*t/7 % 9 * 7 + 2*t % 7 => 2*t % 63 VarHandle t("t", kInt); ExprHandle body = (ExprHandle(2) * t / 7 % 9) * 7 + ExprHandle(2) * t % 7; ExprHandle simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(Mod, simplified.node(), mod); IS_NODE_WITH_NAME(Mul, mod->lhs(), mul); IS_IMM_WITH_VAL(Int, mul->lhs(), 2); IS_VAR_WITH_NAME(mul->rhs(), "t"); IS_IMM_WITH_VAL(Int, mod->rhs(), 63); } { // t/x % y * x + t % x => t%(x*y) VarHandle t("t", kInt); VarHandle x("x", kInt); VarHandle y("y", kInt); ExprHandle body = (t / x % y) * x + t % x; ExprHandle simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(Mod, simplified.node(), mod); IS_VAR_WITH_NAME(mod->lhs(), "t"); IS_NODE_WITH_NAME(Mul, mod->rhs(), mul); IS_VAR_WITH_NAME(mul->lhs(), "x"); IS_VAR_WITH_NAME(mul->rhs(), "y"); } { // k*t/x % y * x + k*t % x => k*t%(x*y) VarHandle t("t", kInt); VarHandle x("x", kInt); VarHandle y("y", kInt); VarHandle k("k", kInt); ExprHandle body = (k * t / x % y) * x + k * t % x; ExprHandle simplified = IRSimplifier::simplify(body); checkExprIR(simplified, "(k * t) % (x * y)"); } { // t/k/x % y * x + t/k % x => t/k%(x*y) VarHandle t("t", kInt); VarHandle x("x", kInt); VarHandle y("y", kInt); VarHandle k("k", kInt); ExprHandle body = (t / k / x % y) * x + t / k % x; ExprHandle simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(Mod, simplified.node(), mod); IS_NODE_WITH_NAME(Div, mod->lhs(), div); IS_VAR_WITH_NAME(div->lhs(), "t"); IS_VAR_WITH_NAME(div->rhs(), "k"); IS_NODE_WITH_NAME(Mul, mod->rhs(), mul); IS_VAR_WITH_NAME(mul->lhs(), "x"); IS_VAR_WITH_NAME(mul->rhs(), "y"); } { // Sanity checking we wont do the optimization on floats. VarHandle x("x", kFloat); VarHandle y("y", kFloat); VarHandle z("z", kFloat); ExprHandle body = ((x / y % z) * y) + (x % y); ExprHandle simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(Add, simplified.node(), add); IS_NODE_WITH_NAME(Mul, add->lhs(), mul); IS_NODE_WITH_NAME(Mod, mul->lhs(), mod); IS_NODE_WITH_NAME(Div, mod->lhs(), div); IS_VAR_WITH_NAME(div->lhs(), "x"); IS_VAR_WITH_NAME(div->rhs(), "y"); IS_VAR_WITH_NAME(mod->rhs(), "z"); IS_VAR_WITH_NAME(mul->rhs(), "y"); IS_NODE_WITH_NAME(Mod, add->rhs(), mod2); IS_VAR_WITH_NAME(mod2->lhs(), "x"); IS_VAR_WITH_NAME(mod2->rhs(), "y"); } } TEST(Simplify, SimplifyModRoundModPatternFactorization) { { // 2 * (t /7 % 9 * 7) + 2 * (t % 7) => 2 * (t % 63) VarHandle t("t", kInt); ExprHandle body = ExprHandle(2) * ((t / 7 % 9) * 7) + ExprHandle(2) * (t % 7); ExprHandle simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(Mul, simplified.node(), mul); IS_IMM_WITH_VAL(Int, mul->lhs(), 2); IS_NODE_WITH_NAME(Mod, mul->rhs(), mod); IS_VAR_WITH_NAME(mod->lhs(), "t"); IS_IMM_WITH_VAL(Int, mod->rhs(), 63); } { // t /7 % 9 * 14 + 2* (t % 7) => 2* (t % 63) VarHandle t("t", kInt); ExprHandle body = (t / 7 % 9) * 14 + ExprHandle(2) * (t % 7); ExprHandle simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(Mul, simplified.node(), mul); IS_IMM_WITH_VAL(Int, mul->lhs(), 2); IS_NODE_WITH_NAME(Mod, mul->rhs(), mod); IS_VAR_WITH_NAME(mod->lhs(), "t"); IS_IMM_WITH_VAL(Int, mod->rhs(), 63); } { // t/14 % 9 * 7 + t/2 % 7 => t/2 % 63 VarHandle t("t", kInt); ExprHandle body = (t / 14 % 9) * 7 + t / 2 % 7; ExprHandle simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(Mod, simplified.node(), mod); IS_NODE_WITH_NAME(Div, mod->lhs(), div); IS_VAR_WITH_NAME(div->lhs(), "t"); IS_IMM_WITH_VAL(Int, div->rhs(), 2); IS_IMM_WITH_VAL(Int, mod->rhs(), 63); } { // t/(7*3) % 9 * 7*3 + t % (7*3) => t % 189 VarHandle t("t", kInt); ExprHandle body = (t / (ExprHandle(7) * ExprHandle(3)) % 9) * 7 * 3 + t % (ExprHandle(7) * ExprHandle(3)); ExprHandle simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(Mod, simplified.node(), mod); IS_VAR_WITH_NAME(mod->lhs(), "t"); IS_IMM_WITH_VAL(Int, mod->rhs(), 189); } { // 2*(t/x % y * x) + 2*(t % x) => 2*(t%(x*y)) VarHandle t("t", kInt); VarHandle x("x", kInt); VarHandle y("y", kInt); ExprHandle body = ExprHandle(2) * ((t / x % y) * x) + ExprHandle(2) * (t % x); ExprHandle simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(Mul, simplified.node(), mul); IS_IMM_WITH_VAL(Int, mul->lhs(), 2); IS_NODE_WITH_NAME(Mod, mul->rhs(), mod); IS_VAR_WITH_NAME(mod->lhs(), "t"); IS_NODE_WITH_NAME(Mul, mod->rhs(), mul2); IS_VAR_WITH_NAME(mul2->lhs(), "x"); IS_VAR_WITH_NAME(mul2->rhs(), "y"); } } TEST(Simplify, SimplifyModRoundModPatternMultivar) { { // t/7 % 9 * 7 + t % 7 + t => t % 63 + t VarHandle t("t", kInt); ExprHandle body = (t / 7 % 9) * 7 + t % 7 + t; ExprHandle simplified = IRSimplifier::simplify(body); checkExprIR(simplified, "t % 63 + t"); } { // t/7 % 9 * 7 + t/8 % 9 * 8 + t % 7 + t % 8 => t % 63 + t % 72 VarHandle t("t", kInt); ExprHandle body = (t / 7 % 9) * 7 + (t / 8 % 9) * 8 + t % 7 + t % 8; ExprHandle simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(Add, simplified.node(), add); IS_NODE_WITH_NAME(Mod, add->lhs(), mod1); IS_VAR_WITH_NAME(mod1->lhs(), "t"); IS_IMM_WITH_VAL(Int, mod1->rhs(), 63); IS_NODE_WITH_NAME(Mod, add->rhs(), mod2); IS_VAR_WITH_NAME(mod2->lhs(), "t"); IS_IMM_WITH_VAL(Int, mod2->rhs(), 72); } { // k + t/x % y * x + t % x => k + t%(x*y) VarHandle t("t", kInt); VarHandle x("x", kInt); VarHandle y("y", kInt); VarHandle k("k", kInt); ExprHandle body = k + (t / x % y) * x + t % x; ExprHandle simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(Add, simplified.node(), add); IS_VAR_WITH_NAME(add->lhs(), "k"); IS_NODE_WITH_NAME(Mod, add->rhs(), mod); IS_VAR_WITH_NAME(mod->lhs(), "t"); IS_NODE_WITH_NAME(Mul, mod->rhs(), mul); IS_VAR_WITH_NAME(mul->lhs(), "x"); IS_VAR_WITH_NAME(mul->rhs(), "y"); } { // t/x % y * x + t % x + (t/k / x % y) * x + t/k % x // => t%(x*y) + t/k % (x*y) VarHandle t("t", kInt); VarHandle x("x", kInt); VarHandle y("y", kInt); VarHandle k("k", kInt); ExprHandle body = (t / x % y) * x + t % x + (t / k / x % y) * x + t / k % x; ExprHandle simplified = IRSimplifier::simplify(body); checkExprIR(simplified, "(t / k) % (x * y) + t % (x * y)"); } { // 3D: (7 * ((i0_flat / 7) % 9) + i0_flat % 7) + 63 * (i0_flat / 63) // => io_flat VarHandle t("io_flat", kInt); ExprHandle body = ExprHandle(7) * (t / 7 % 9) + t % 7 + ExprHandle(63) * (t / 63); ExprHandle simplified = IRSimplifier::simplify(body); IS_VAR_WITH_NAME(simplified.node(), "io_flat"); } { // 5D: i0_flat / (11 * 10 * 9 * 7) * (7 * 9 * 10 * 11) + // (i0_flat / (10 * 9 * 7) % 11) * 7 * 9 * 10 + // (i0_flat / (9 * 7) % 10) * 7 * 9 + // (i0_flat / 7 % 9) * 7 + // i0_flat % 7 => io_flat VarHandle t("io_flat", kInt); ExprHandle body = (t / (ExprHandle(11) * 10 * 9 * 7)) * (7 * 9 * 10 * 11) + (t / (ExprHandle(10) * 9 * 7) % 11) * 7 * 9 * 10 + (t / (ExprHandle(9) * 7) % 10) * 7 * 9 + (t / 7 % 9) * 7 + t % 7; ExprHandle simplified = IRSimplifier::simplify(body); IS_VAR_WITH_NAME(simplified.node(), "io_flat"); } { // 3D: (m * ((i0_flat / m) % n) + i0_flat % m) + (m * n) * // (i0_flat / (m * n)) => io_flat VarHandle t("io_flat", kInt); VarHandle m("m", kInt); VarHandle n("n", kInt); ExprHandle body = m * (t / m % n) + t % m + (m * n) * (t / (m * n)); ExprHandle simplified = IRSimplifier::simplify(body); IS_VAR_WITH_NAME(simplified.node(), "io_flat"); } { // 5D: i0_flat / (k * l * n * m) * (m * n * l * k) + // (i0_flat / (l * n * m) % k) * m * n * l + // (i0_flat / (n * m) % l) * m * n + // (i0_flat / m % n) * m + // i0_flat % m => io_flat VarHandle t("io_flat", kInt); VarHandle m("m", kInt); VarHandle n("n", kInt); VarHandle l("l", kInt); VarHandle k("k", kInt); ExprHandle body = (t / (k * l * n * m)) * (m * n * l * k) + (t / (l * n * m) % k) * m * n * l + (t / (n * m) % l) * m * n + (t / m % n) * m + t % m; ExprHandle simplified = IRSimplifier::simplify(body); IS_VAR_WITH_NAME(simplified.node(), "io_flat"); } } TEST(Simplify, SimplifyDivisionScalarFactorization) { { // Simple factorization of numerator and denominator. // 8x / 4y => 2x / y. VarHandle x("x", kInt); VarHandle y("y", kInt); ExprHandle body = (x * 8) / (y * 4); ExprHandle simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(Div, simplified.node(), div); IS_NODE_WITH_NAME(Mul, div->lhs(), lhs); IS_IMM_WITH_VAL(Int, lhs->lhs(), 2); IS_VAR_WITH_NAME(lhs->rhs(), "x"); IS_VAR_WITH_NAME(div->rhs(), "y"); } { // Don't change anything if we can't factorize. VarHandle x("x", kInt); VarHandle y("y", kInt); ExprHandle body = (x * 7) / (y * 4); ExprHandle simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(Div, simplified.node(), div); IS_NODE_WITH_NAME(Mul, div->lhs(), lhs); IS_IMM_WITH_VAL(Int, lhs->lhs(), 7); IS_VAR_WITH_NAME(lhs->rhs(), "x"); IS_NODE_WITH_NAME(Mul, div->rhs(), rhs); IS_IMM_WITH_VAL(Int, rhs->lhs(), 4); IS_VAR_WITH_NAME(rhs->rhs(), "y"); } { // Don't reorder floats. VarHandle x("x", kFloat); VarHandle y("y", kFloat); ExprHandle body = (x * 8) / (y * 4); ExprHandle simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(Div, simplified.node(), div); IS_NODE_WITH_NAME(Mul, div->lhs(), lhs); IS_VAR_WITH_NAME(lhs->lhs(), "x"); IS_IMM_WITH_VAL(Float, lhs->rhs(), 8.f); IS_NODE_WITH_NAME(Mul, div->rhs(), rhs); IS_VAR_WITH_NAME(rhs->lhs(), "y"); IS_IMM_WITH_VAL(Float, rhs->rhs(), 4.f); } { // Sanity check we do nothing if there are only scalar parts. VarHandle x("x", kInt); VarHandle y("y", kInt); ExprHandle body = (x * 1) / (y * 1); ExprHandle simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(Div, simplified.node(), div); IS_VAR_WITH_NAME(div->lhs(), "x"); IS_VAR_WITH_NAME(div->rhs(), "y"); } { // Can factorize amounts of variables. VarHandle x("x", kInt); VarHandle y("y", kInt); ExprHandle body = (x + x + x + x) / (y + y); ExprHandle simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(Div, simplified.node(), div); IS_NODE_WITH_NAME(Mul, div->lhs(), lhs); IS_IMM_WITH_VAL(Int, lhs->lhs(), 2); IS_VAR_WITH_NAME(lhs->rhs(), "x"); IS_VAR_WITH_NAME(div->rhs(), "y"); } } TEST(Simplify, SimplifyConstantBranches) { { // If the condition is constant true then take the true_value. // 1 ? x : y => x VarHandle x("x", kInt); VarHandle y("y", kInt); ExprHandle t(1); ExprHandle body = IfThenElse::make(t, x, y); ExprHandle simplified = IRSimplifier::simplify(body); IS_VAR_WITH_NAME(simplified.node(), "x"); } { // If the condition is constant false then take the false_value. // 0 ? x : y => y VarHandle x("x", kInt); VarHandle y("y", kInt); ExprHandle t(0); ExprHandle body = IfThenElse::make(t, x, y); ExprHandle simplified = IRSimplifier::simplify(body); IS_VAR_WITH_NAME(simplified.node(), "y"); } { // condition is simplified before checking. // (x-x) ? x : y => y VarHandle x("x", kInt); VarHandle y("y", kInt); ExprHandle body = IfThenElse::make(x - x, x, y); ExprHandle simplified = IRSimplifier::simplify(body); IS_VAR_WITH_NAME(simplified.node(), "y"); } { // If both branches are the same then don't do the condition. // y ? x : x => x VarHandle x("x", kInt); VarHandle y("y", kInt); ExprHandle body = IfThenElse::make(y, x, x); ExprHandle simplified = IRSimplifier::simplify(body); IS_VAR_WITH_NAME(simplified.node(), "x"); } { // If both branches simplify to the same thing it still works. // y ? (x + x) : (2 * x) => x VarHandle x("x", kInt); VarHandle y("y", kInt); ExprHandle body = IfThenElse::make(y, x + x, ExprHandle(2) * x); ExprHandle simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(Mul, simplified.node(), mul); IS_IMM_WITH_VAL(Int, mul->lhs(), 2); IS_VAR_WITH_NAME(mul->rhs(), "x"); } } TEST(Simplify, SimplifyConstantCond) { { // If the condition is constant true then take the true_value. // 1 ? A[0] = 1 : B[0] = 1 => A[0] = 1 BufHandle a("A", {1}, kInt); BufHandle b("B", {1}, kInt); ExprHandle condition(1); StmtPtr true_val = Store::make(a, {0}, 1); StmtPtr false_val = Store::make(b, {0}, 1); CondPtr body = alloc<Cond>(condition.node(), true_val, false_val); StmtPtr simplified = IRSimplifier::simplify(body); BlockPtr block = to<Block>(simplified); IS_NODE_WITH_NAME(Store, block->front(), store); IS_VAR_WITH_NAME(store->base_handle(), "A"); } { // If the condition is constant false then take the false_value. // 0 ? A[0] = 1 : B[0] = 1 => B[0] = 1 BufHandle a("A", {1}, kInt); BufHandle b("B", {1}, kInt); ExprHandle condition(0); StmtPtr true_val = Store::make(a, {0}, 1); StmtPtr false_val = Store::make(b, {0}, 1); StmtPtr body = alloc<Cond>(condition.node(), true_val, false_val); StmtPtr simplified = IRSimplifier::simplify(body); BlockPtr block = to<Block>(simplified); IS_NODE_WITH_NAME(Store, block->front(), store); IS_VAR_WITH_NAME(store->base_handle(), "B"); } { // condition is simplified before checking. // (x-x) ? A[0] = 1 : B[0] = 1 => B[0] = 1 VarHandle x("x", kInt); BufHandle a("A", {1}, kInt); BufHandle b("B", {1}, kInt); ExprHandle condition(x - x); StmtPtr true_val = Store::make(a, {0}, 1); StmtPtr false_val = Store::make(b, {0}, 1); StmtPtr body = alloc<Cond>(condition.node(), true_val, false_val); StmtPtr simplified = IRSimplifier::simplify(body); BlockPtr block = to<Block>(simplified); IS_NODE_WITH_NAME(Store, block->front(), store); IS_VAR_WITH_NAME(store->base_handle(), "B"); } { // If both branches are the same then don't do the condition. // x ? A[0] = x : A[0] = x => A[0] = x VarHandle x("x", kInt); BufHandle a("A", {1}, kInt); ExprHandle condition(x - x); StmtPtr true_val = Store::make(a, {0}, x); StmtPtr false_val = Store::make(a, {0}, x); StmtPtr body = alloc<Cond>(condition.node(), true_val, false_val); StmtPtr simplified = IRSimplifier::simplify(body); BlockPtr block = to<Block>(simplified); IS_NODE_WITH_NAME(Store, block->front(), store); IS_VAR_WITH_NAME(store->base_handle(), "A"); } { // If both branches simplify to the same thing it still works. // x ? (x + x) : (2 * x) => x VarHandle x("x", kInt); BufHandle a("A", {1}, kInt); ExprHandle condition(x - x); StmtPtr true_val = Store::make(a, {0}, ExprHandle(2) * x); StmtPtr false_val = Store::make(a, {0}, x + x); StmtPtr body = alloc<Cond>(condition.node(), true_val, false_val); StmtPtr simplified = IRSimplifier::simplify(body); BlockPtr block = to<Block>(simplified); IS_NODE_WITH_NAME(Store, block->front(), store); IS_VAR_WITH_NAME(store->base_handle(), "A"); } { // But not if they dont // x ? x : (2 * x) => x ? x : (2 * x) VarHandle x("x", kInt); BufHandle a("A", {1}, kInt); ExprHandle condition(x); StmtPtr true_val = Store::make(a, {0}, x); StmtPtr false_val = Store::make(a, {0}, ExprHandle(2) * x); StmtPtr body = alloc<Cond>(condition.node(), true_val, false_val); StmtPtr simplified = IRSimplifier::simplify(body); BlockPtr block = to<Block>(simplified); ASSERT_EQ(block, nullptr); } { StmtPtr cond = alloc<Cond>( ExprHandle(false).node(), alloc<Block>(std::vector<StmtPtr>({})), nullptr); StmtPtr simplified = IRSimplifier::simplify(cond); ASSERT_EQ(simplified, nullptr); } { StmtPtr cond = alloc<Cond>( ExprHandle(true).node(), nullptr, alloc<Block>(std::vector<StmtPtr>({}))); StmtPtr simplified = IRSimplifier::simplify(cond); ASSERT_EQ(simplified, nullptr); } } TEST(Simplify, SimplifyEliminateEmptyCond) { // If the branches are empty in different ways, eliminate. { VarHandle x("x", kInt); ExprHandle condition(x); StmtPtr true_val = alloc<Block>(std::vector<StmtPtr>({})); StmtPtr body = alloc<Cond>(condition.node(), true_val, nullptr); StmtPtr simplified = IRSimplifier::simplify(body); BlockPtr block = to<Block>(simplified); ASSERT_NE(block, nullptr); ASSERT_EQ(block->nstmts(), 0); } { VarHandle x("x", kInt); ExprHandle condition(x); StmtPtr false_val = alloc<Block>(std::vector<StmtPtr>({})); StmtPtr body = alloc<Cond>(condition.node(), nullptr, false_val); StmtPtr simplified = IRSimplifier::simplify(body); BlockPtr block = to<Block>(simplified); ASSERT_NE(block, nullptr); ASSERT_EQ(block->nstmts(), 0); } } TEST(Simplify, SimplifyConstantComparisons) { auto ComparisonTest = [](ExprHandle a, ExprHandle b, CompareSelectOperation op, int result) { ExprHandle body = CompareSelect::make(a, b, op); ExprHandle simplified = IRSimplifier::simplify(body); IS_IMM_WITH_VAL(Int, simplified.node(), result); }; // Equals. ComparisonTest(2, 2, kEQ, 1); ComparisonTest(1, 2, kEQ, 0); ComparisonTest(2, 1, kEQ, 0); // Greater than. ComparisonTest(2, 2, kGT, 0); ComparisonTest(1, 2, kGT, 0); ComparisonTest(2, 1, kGT, 1); // Greater or Equal. ComparisonTest(2, 2, kGE, 1); ComparisonTest(1, 2, kGE, 0); ComparisonTest(2, 1, kGE, 1); // Less Than. ComparisonTest(2, 2, kLT, 0); ComparisonTest(1, 2, kLT, 1); ComparisonTest(2, 1, kLT, 0); // Less or Equal. ComparisonTest(2, 2, kLE, 1); ComparisonTest(1, 2, kLE, 1); ComparisonTest(2, 1, kLE, 0); // Not equal. ComparisonTest(2, 2, kNE, 0); ComparisonTest(1, 2, kNE, 1); ComparisonTest(2, 1, kNE, 1); // With specified results: ExprHandle body = CompareSelect::make(2, 2, 5, 42, kNE); ExprHandle simplified = IRSimplifier::simplify(body); IS_IMM_WITH_VAL(Int, simplified.node(), 42); } TEST(Simplify, SimplifySymbolicComparisons) { VarHandle x("x", kInt); VarHandle y("y", kInt); auto TookTrueBranch = [](ExprHandle a) { IS_IMM_WITH_VAL(Int, a.node(), 1); }; auto TookFalseBranch = [](ExprHandle a) { IS_IMM_WITH_VAL(Int, a.node(), 0); }; // EQ // x == x => 1 ExprHandle body = CompareSelect::make(x, x, kEQ); TookTrueBranch(IRSimplifier::simplify(body)); // x == x+1 => 0 body = CompareSelect::make(x, x + 1, kEQ); TookFalseBranch(IRSimplifier::simplify(body)); // x == x * 2 cannot simplify since we don't know x is nonzero. body = CompareSelect::make(x, x * 2, kEQ); // NOLINTNEXTLINE(clang-analyzer-cplusplus.NewDeleteLeaks) IS_NODE(CompareSelect, IRSimplifier::simplify(body).node()); // x == x * 1 => 1 body = CompareSelect::make(x, x * 1, kEQ); TookTrueBranch(IRSimplifier::simplify(body)); { // x == y => x == y body = CompareSelect::make(x, y, kEQ); ExprHandle simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(CompareSelect, simplified.node(), cmp); ASSERT_EQ(cmp->compare_select_op(), kEQ); IS_VAR_WITH_NAME(cmp->lhs(), "x"); IS_VAR_WITH_NAME(cmp->rhs(), "y"); } { // x == 5 => x == 5 body = CompareSelect::make(x, 5, kEQ); ExprHandle simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(CompareSelect, simplified.node(), cmp); ASSERT_EQ(cmp->compare_select_op(), kEQ); IS_VAR_WITH_NAME(cmp->lhs(), "x"); IS_IMM_WITH_VAL(Int, cmp->rhs(), 5); } // GT // x+1 > x => 1 body = CompareSelect::make(x + 1, x, kGT); TookTrueBranch(IRSimplifier::simplify(body)); // x > x + 1 => 0 body = CompareSelect::make(x, x + 1, kGT); TookFalseBranch(IRSimplifier::simplify(body)); // x > x - 1 => 1 body = CompareSelect::make(x, x - 1, kGT); TookTrueBranch(IRSimplifier::simplify(body)); // x - 1 > x => 0 body = CompareSelect::make(x - 1, x, kGT); TookFalseBranch(IRSimplifier::simplify(body)); // x > x => 0 body = CompareSelect::make(x, x, kGT); TookFalseBranch(IRSimplifier::simplify(body)); // x * 2 > x => x * 2 > x // since we don't know the sign of x. body = CompareSelect::make(x * 2, x, kGT); IS_NODE(CompareSelect, IRSimplifier::simplify(body).node()); // GE // x+1 >= x => 1 body = CompareSelect::make(x + 1, x, kGE); TookTrueBranch(IRSimplifier::simplify(body)); // x >= x + 1 => 0 body = CompareSelect::make(x, x + 1, kGE); TookFalseBranch(IRSimplifier::simplify(body)); // x >= x => 1 body = CompareSelect::make(x, x, kGE); TookTrueBranch(IRSimplifier::simplify(body)); // x * 2 >= x => x * 2 >= x // since we don't know the sign of x. body = CompareSelect::make(x * 2, x, kGE); IS_NODE(CompareSelect, IRSimplifier::simplify(body).node()); // LT // x+1 < x => 0 body = CompareSelect::make(x + 1, x, kLT); TookFalseBranch(IRSimplifier::simplify(body)); // x < x + 1 => 1 body = CompareSelect::make(x, x + 1, kLT); TookTrueBranch(IRSimplifier::simplify(body)); // x < x => 0 body = CompareSelect::make(x, x, kLT); TookFalseBranch(IRSimplifier::simplify(body)); // LE // x+1 <= x => 0 body = CompareSelect::make(x + 1, x, kLE); TookFalseBranch(IRSimplifier::simplify(body)); // x <= x + 1 => 1 body = CompareSelect::make(x, x + 1, kLE); TookTrueBranch(IRSimplifier::simplify(body)); // x <= x => 1 body = CompareSelect::make(x, x, kLE); TookTrueBranch(IRSimplifier::simplify(body)); // NE // x+1 != x => 1 body = CompareSelect::make(x + 1, x, kNE); TookTrueBranch(IRSimplifier::simplify(body)); // x != x + 1 => 1 body = CompareSelect::make(x, x + 1, kNE); TookTrueBranch(IRSimplifier::simplify(body)); // x != x => 0 body = CompareSelect::make(x, x, kNE); TookFalseBranch(IRSimplifier::simplify(body)); } TEST(Simplify, SimplifyEliminateZeroLengthFor) { { // Will eliminate zero loop For. BufHandle a("A", {4}, kInt); BufHandle c("C", {4}, kInt); VarHandle i("i", kInt); auto body = For::make(i, 0, 0, Store::make(c, {i}, Load::make(a, {i}))); StmtPtr simplified = IRSimplifier::simplify(body); BlockPtr block = to<Block>(simplified); ASSERT_EQ(block->nstmts(), 0); } { // still works if start is not zero. BufHandle a("A", {4}, kInt); BufHandle c("C", {4}, kInt); VarHandle i("i", kInt); auto body = For::make(i, 2, 2, Store::make(c, {i}, Load::make(a, {i}))); StmtPtr simplified = IRSimplifier::simplify(body); BlockPtr block = to<Block>(simplified); ASSERT_EQ(block->nstmts(), 0); } { // works if both terms are variable. VarHandle x("x", kInt); BufHandle a("A", {4}, kInt); BufHandle c("C", {4}, kInt); VarHandle i("i", kInt); auto body = For::make(i, x, x, Store::make(c, {i}, Load::make(a, {i}))); StmtPtr simplified = IRSimplifier::simplify(body); BlockPtr block = to<Block>(simplified); ASSERT_EQ(block->nstmts(), 0); } { // works if one term simplifies down. VarHandle x("x", kInt); BufHandle a("A", {4}, kInt); BufHandle c("C", {4}, kInt); VarHandle i("i", kInt); auto body = For::make(i, 0, x - x, Store::make(c, {i}, Load::make(a, {i}))); StmtPtr simplified = IRSimplifier::simplify(body); BlockPtr block = to<Block>(simplified); ASSERT_EQ(block->nstmts(), 0); } { // Sanity check does nothing if the condition is not met. BufHandle a("A", {4}, kInt); BufHandle c("C", {4}, kInt); VarHandle i("i", kInt); auto body = For::make(i, 0, 3, Store::make(c, {i}, Load::make(a, {i}))); StmtPtr simplified = IRSimplifier::simplify(body); IS_NODE(For, simplified); } } TEST(Simplify, SimplifyOneLoopFor) { { // Will remove the loop if the body is run once. BufHandle a("A", {4}, kInt); BufHandle c("C", {4}, kInt); VarHandle i("i", kInt); auto body = For::make(i, 0, 1, Store::make(c, {i}, Load::make(a, {i}))); StmtPtr simplified = IRSimplifier::simplify(body); BlockPtr block = to<Block>(simplified); IS_NODE_WITH_NAME(Store, block->front(), store); IS_VAR_WITH_NAME(store->base_handle(), "C"); IS_IMM_WITH_VAL(Int, store->flat_index(), 0); } { // still works if start is not zero. BufHandle a("A", {4}, kInt); BufHandle c("C", {4}, kInt); VarHandle i("i", kInt); auto body = For::make(i, 2, 3, Store::make(c, {i}, Load::make(a, {i}))); StmtPtr simplified = IRSimplifier::simplify(body); BlockPtr block = to<Block>(simplified); IS_NODE_WITH_NAME(Store, block->front(), store); IS_VAR_WITH_NAME(store->base_handle(), "C"); IS_IMM_WITH_VAL(Int, store->flat_index(), 2); } { // works if both terms are variable. VarHandle x("x", kInt); BufHandle a("A", {4}, kInt); BufHandle c("C", {4}, kInt); VarHandle i("i", kInt); auto body = For::make(i, x, x + 1, Store::make(c, {i}, Load::make(a, {i}))); StmtPtr simplified = IRSimplifier::simplify(body); BlockPtr block = to<Block>(simplified); IS_NODE_WITH_NAME(Store, block->front(), store); IS_VAR_WITH_NAME(store->base_handle(), "C"); IS_VAR_WITH_NAME(store->flat_index(), "x"); } { // works if one term simplifies down. VarHandle x("x", kInt); BufHandle a("A", {4}, kInt); BufHandle c("C", {4}, kInt); VarHandle i("i", kInt); auto body = For::make(i, 0, x - x + 1, Store::make(c, {i}, Load::make(a, {i}))); StmtPtr simplified = IRSimplifier::simplify(body); BlockPtr block = to<Block>(simplified); IS_NODE_WITH_NAME(Store, block->front(), store); IS_VAR_WITH_NAME(store->base_handle(), "C"); IS_IMM_WITH_VAL(Int, store->flat_index(), 0); } { // Sanity check does nothing if the condition is not met. BufHandle a("A", {4}, kInt); BufHandle c("C", {4}, kInt); VarHandle i("i", kInt); auto body = For::make(i, 0, 3, Store::make(c, {i}, Load::make(a, {i}))); StmtPtr simplified = IRSimplifier::simplify(body); IS_NODE(For, simplified); } } TEST(Simplify, SimplifyForWontLoseLoopOptions) { { // Sanity check does nothing if the condition is not met. BufHandle a("A", {4}, kInt); BufHandle c("C", {4}, kInt); VarHandle i("i", kInt); LoopOptions options; options.set_gpu_block_index(LoopOptions::IDX_W); auto body = For::make(i, 0, 1, Store::make(c, {i}, Load::make(a, {i})), options); StmtPtr simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(For, simplified, for_); LoopOptions options2 = for_->loop_options(); ASSERT_EQ(options.gpu_block_index(), options2.gpu_block_index()); } } TEST(Simplify, SimplifyMultilevelFor) { { // Multiple layers of For will be simplified out. BufHandle a("A", {4}, kInt); BufHandle c("C", {4}, kInt); VarHandle i("i", kInt); VarHandle j("j", kInt); auto body = For::make(i, 0, 1, Store::make(c, {i}, Load::make(a, {i}))); auto outer = For::make(j, 0, 1, body); StmtPtr simplified = IRSimplifier::simplify(outer); BlockPtr block = to<Block>(simplified); IS_NODE_WITH_NAME(Store, block->front(), store); IS_VAR_WITH_NAME(store->base_handle(), "C"); IS_IMM_WITH_VAL(Int, store->flat_index(), 0); } { // Will maintain an outer loop if the inner loop is eliminated. BufHandle a("A", {4}, kInt); BufHandle c("C", {4}, kInt); VarHandle i("i", kInt); VarHandle j("j", kInt); auto body = For::make(i, 0, 1, Store::make(c, {i}, Load::make(a, {i}))); auto outer = For::make(j, 0, 2, body); StmtPtr simplified = IRSimplifier::simplify(outer); ForPtr for__ = static_to<For>(simplified); IS_NODE_WITH_NAME(For, for__, for_); IS_VAR_WITH_NAME(for_->var(), "j"); IS_IMM_WITH_VAL(Int, for_->start(), 0); IS_IMM_WITH_VAL(Int, for_->stop(), 2); BlockPtr block = to<Block>(for_->body()); ASSERT_NE(block, nullptr); IS_NODE_WITH_NAME(Store, block->front(), store); IS_VAR_WITH_NAME(store->base_handle(), "C"); IS_IMM_WITH_VAL(Int, store->flat_index(), 0); } { // Will maintain inner loop if outer loops is eliminated. BufHandle a("A", {4}, kInt); BufHandle c("C", {4}, kInt); VarHandle i("i", kInt); VarHandle j("j", kInt); auto body = For::make(i, 0, 2, Store::make(c, {i}, Load::make(a, {i}))); auto outer = For::make(j, 0, 1, body); StmtPtr simplified = IRSimplifier::simplify(outer); BlockPtr block = to<Block>(simplified); IS_NODE_WITH_NAME(For, block->front(), for_); IS_VAR_WITH_NAME(for_->var(), "i"); IS_IMM_WITH_VAL(Int, for_->start(), 0); IS_IMM_WITH_VAL(Int, for_->stop(), 2); IS_NODE_WITH_NAME(Store, for_->body()->front(), store); IS_VAR_WITH_NAME(store->base_handle(), "C"); IS_VAR_WITH_NAME(store->flat_index(), "i"); } } TEST(Simplify, SimplifyForCleansUp) { { BufHandle a("a", {1, 12, 1}, kFloat); VarHandle x("x", kInt); Tensor b = Compute( // NOLINTNEXTLINE(clang-analyzer-cplusplus.NewDeleteLeaks) "x", {{1, "i"}, {12, "m"}, {1, "n"}}, [](const VarHandle& i, const VarHandle& m, const VarHandle& n) { return i + m + n; }); LoopNest l({b}); l.prepareForCodegen(); StmtPtr body = l.root_stmt(); StmtPtr simplified = IRSimplifier::simplify(body); BlockPtr block = to<Block>(simplified); IS_NODE_WITH_NAME(For, block->front(), for_); // for is over "m". IS_VAR_WITH_NAME(for_->var(), "m"); // x[m] = m; IS_NODE_WITH_NAME(Store, for_->body()->front(), store); IS_VAR_WITH_NAME(store->flat_index(), "m"); IS_VAR_WITH_NAME(store->value(), "m"); } } TEST(Simplify, SimplifyEliminateEmptyFor) { { // Flatten many layers around an empty block to an empty block. StmtPtr last = alloc<Block>(std::vector<StmtPtr>({})); for (int i = 0; i < 11; ++i) { VarHandle loopVar("loopVar", kInt); last = For::make(loopVar, 0, 10, last); } StmtPtr simplified = IRSimplifier::simplify(last); IS_NODE_WITH_NAME(Block, simplified, block); ASSERT_EQ(block->nstmts(), 0); } } TEST(Simplify, SimplifyFlattenBlock) { { // Flatten multiple blocks down to one. // { { { stmt1, stmt2 } } } => { stmt1, stmt2 } BufHandle a("A", {1}, kInt); StorePtr store1 = Store::make(a, {0}, 1); StorePtr store2 = Store::make(a, {0}, 0); BlockPtr block1 = alloc<Block>(std::vector<StmtPtr>({store1, store2})); BlockPtr block2 = alloc<Block>(std::vector<StmtPtr>({block1})); BlockPtr enclosing = alloc<Block>(std::vector<StmtPtr>({block2})); StmtPtr simplified = IRSimplifier::simplify(enclosing); IS_NODE_WITH_NAME(Block, simplified, block); ASSERT_EQ(block->nstmts(), 2); IS_NODE_WITH_NAME(Store, block->front(), store1_); IS_NODE_WITH_NAME(Store, block->back(), store2_); ASSERT_EQ(store1->value(), store1_->value()); ASSERT_EQ(store2->value(), store2_->value()); } { // Flatten multiple sub blocks containing statements. // { { stmt1 }, { stmt2 } } => { stmt1, stmt2 } BufHandle a("A", {1}, kInt); StorePtr store1 = Store::make(a, {0}, 1); StorePtr store2 = Store::make(a, {0}, 0); BlockPtr block1 = alloc<Block>(std::vector<StmtPtr>({store1})); BlockPtr block2 = alloc<Block>(std::vector<StmtPtr>({store2})); BlockPtr enclosing = alloc<Block>(std::vector<StmtPtr>({block1, block2})); StmtPtr simplified = IRSimplifier::simplify(enclosing); IS_NODE_WITH_NAME(Block, simplified, block); ASSERT_EQ(block->nstmts(), 2); IS_NODE_WITH_NAME(Store, block->front(), store1_); IS_NODE_WITH_NAME(Store, block->back(), store2_); ASSERT_EQ(store1->value(), store1_->value()); ASSERT_EQ(store2->value(), store2_->value()); } { // Flatten sub blocks with different depths. // { stmt1 , { { stmt2 } } } => { stmt1, stmt2 } BufHandle a("A", {1}, kInt); StorePtr store1 = Store::make(a, {0}, 1); StorePtr store2 = Store::make(a, {0}, 0); BlockPtr block1 = alloc<Block>(std::vector<StmtPtr>({store2})); BlockPtr block2 = alloc<Block>(std::vector<StmtPtr>({block1})); BlockPtr enclosing = alloc<Block>(std::vector<StmtPtr>({store1, block2})); StmtPtr simplified = IRSimplifier::simplify(enclosing); IS_NODE_WITH_NAME(Block, simplified, block); ASSERT_EQ(block->nstmts(), 2); IS_NODE_WITH_NAME(Store, block->front(), store1_); IS_NODE_WITH_NAME(Store, block->back(), store2_); ASSERT_EQ(store1->value(), store1_->value()); ASSERT_EQ(store2->value(), store2_->value()); } { // Flatten many layers around an empty block to an empty block. StmtPtr last = alloc<Block>(std::vector<StmtPtr>({})); for (int i = 0; i < 11; ++i) { last = alloc<Block>(std::vector<StmtPtr>({last})); } StmtPtr simplified = IRSimplifier::simplify(last); IS_NODE_WITH_NAME(Block, simplified, block); ASSERT_EQ(block->nstmts(), 0); } } TEST(Simplify, SimplifyEliminateZeroLengthAlloc) { { // Simple positive case. BufHandle b("x", {0}, kInt); AllocatePtr alloc_ = Allocate::make(b); FreePtr free_ = Free::make(b); BlockPtr block1 = alloc<Block>(std::vector<StmtPtr>({alloc_, free_})); ASSERT_EQ(block1->nstmts(), 2); StmtPtr simplified = IRSimplifier::simplify(block1); IS_NODE_WITH_NAME(Block, simplified, block2); ASSERT_EQ(block2->nstmts(), 0); } { // Simple negative case. BufHandle b("x", {2}, kInt); AllocatePtr alloc_ = Allocate::make(b); FreePtr free_ = Free::make(b); BlockPtr block1 = alloc<Block>(std::vector<StmtPtr>({alloc_, free_})); ASSERT_EQ(block1->nstmts(), 2); StmtPtr simplified = IRSimplifier::simplify(block1); IS_NODE_WITH_NAME(Block, simplified, block2); ASSERT_EQ(block2->nstmts(), 2); } { // Finds right Alloc/Free. BufHandle b1("x", {0}, kInt); BufHandle b2("y", {2}, kInt); AllocatePtr alloc1 = Allocate::make(b1); AllocatePtr alloc2 = Allocate::make(b2); FreePtr free2_ = Free::make(b2); FreePtr free1_ = Free::make(b1); BlockPtr block1 = alloc<Block>(std::vector<StmtPtr>({alloc1, alloc2, free2_, free1_})); ASSERT_EQ(block1->nstmts(), 4); StmtPtr simplified = IRSimplifier::simplify(block1); IS_NODE_WITH_NAME(Block, simplified, block2); ASSERT_EQ(block2->nstmts(), 2); IS_NODE_WITH_NAME(Allocate, block2->stmts().front(), simplified_alloc); IS_VAR_WITH_NAME(simplified_alloc->buffer_var(), "y"); IS_NODE_WITH_NAME(Free, block2->stmts().back(), simplified_free); ASSERT_EQ(simplified_alloc->buffer_var(), simplified_free->buffer_var()); } { // Dynamic shape. VarHandle z("z", kInt); BufHandle b1("x", {0}, kInt); BufHandle b2("y", {z}, kInt); AllocatePtr alloc1 = Allocate::make(b1); AllocatePtr alloc2 = Allocate::make(b2); FreePtr free2_ = Free::make(b2); FreePtr free1_ = Free::make(b1); BlockPtr block1 = alloc<Block>(std::vector<StmtPtr>({alloc1, alloc2, free2_, free1_})); ASSERT_EQ(block1->nstmts(), 4); StmtPtr simplified = IRSimplifier::simplify(block1); IS_NODE_WITH_NAME(Block, simplified, block2); ASSERT_EQ(block2->nstmts(), 2); } } TEST(Simplify, DontSimplifyRand) { { // rand() + rand() = rand() + rand() NOT 2 * rand(). ExprHandle body = Intrinsics::make(kRand, kInt) + Intrinsics::make(kRand, kInt); ExprHandle simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(Add, simplified.node(), add); IS_RAND(add->lhs()); IS_RAND(add->rhs()); } { // rand() - rand() = rand() - rand() NOT 0. ExprHandle body = Intrinsics::make(kRand, kFloat) - Intrinsics::make(kRand, kFloat); ExprHandle simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(Sub, simplified.node(), sub); IS_RAND(sub->lhs()); IS_RAND(sub->rhs()); } { // rand() * rand() = rand() * rand(). ExprHandle body = Intrinsics::make(kRand, kInt) * Intrinsics::make(kRand, kInt); ExprHandle simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(Mul, simplified.node(), mul); IS_RAND(mul->lhs()); IS_RAND(mul->rhs()); } } TEST(Simplify, SimplifyReorderForCond) { BufHandle a("A", {4}, kInt); BufHandle b("B", {1}, kInt); BufHandle c("C", {4}, kInt); VarHandle i("i", kInt); VarHandle j("j", kInt); { // for ( if ( ... ) ) => if ( for ( ... ) ). auto body = For::make( i, 0, 4, Cond::make( CompareSelect::make(j, 10, CompareSelectOperation::kLT), Store::make(c, {i}, Load::make(a, {i})), nullptr)); StmtPtr simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(Cond, simplified, cond); IS_NODE_WITH_NAME(Block, cond->true_stmt(), true_block); IS_NODE_WITH_NAME(For, true_block->front(), loop); } { // Can't reorder if condition is dependent on the loop var. auto body = For::make( i, 0, 4, Cond::make( CompareSelect::make(i, 10, CompareSelectOperation::kLT), Store::make(c, {i}, Load::make(a, {i})), nullptr)); StmtPtr simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(For, simplified, loop); IS_NODE_WITH_NAME(Cond, loop->body()->front(), cond); } { // Can't reorder if condition is dependent on a var that is modified inside // the loop. auto body = For::make( i, 0, 4, Cond::make( CompareSelect::make( Load::make(c, {0}), 10, CompareSelectOperation::kLT), Store::make(c, {0}, Load::make(a, {i})), nullptr)); StmtPtr simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(For, simplified, loop); IS_NODE_WITH_NAME(Cond, loop->body()->front(), cond); } { // Condition based on buffer not referenced in body. Can reorder here. auto body = For::make( i, 0, 4, Cond::make( CompareSelect::make( Load::make(b, {0}), 10, CompareSelectOperation::kLT), Store::make(c, {0}, Load::make(a, {i})), nullptr)); StmtPtr simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(Cond, simplified, cond); IS_NODE_WITH_NAME(Block, cond->true_stmt(), true_block); IS_NODE_WITH_NAME(For, true_block->front(), loop); } { // Condition based on buffer read only in body. Can reorder here. auto body = For::make( i, 0, 4, Cond::make( CompareSelect::make( Load::make(a, {0}), 10, CompareSelectOperation::kLT), Store::make(c, {0}, Load::make(a, {i})), nullptr)); StmtPtr simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(Cond, simplified, cond); IS_NODE_WITH_NAME(Block, cond->true_stmt(), true_block); IS_NODE_WITH_NAME(For, true_block->front(), loop); } { // Condition depends on Let in the loop. Cannot reorder. auto body = For::make( i, 0, 4, Block::make( {Let::make(j, 3), Cond::make( CompareSelect::make(j, 10, CompareSelectOperation::kLT), Store::make(c, {0}, Load::make(a, {i})), nullptr)})); StmtPtr simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(For, simplified, loop); IS_NODE_WITH_NAME(Let, loop->body()->front(), let); IS_NODE_WITH_NAME(Cond, loop->body()->back(), cond); } { // Multi level Ifs where all conditions are distinct. Move BOTH Cond // statements outside the loop. auto body = For::make( i, 0, 4, Cond::make( CompareSelect::make( Load::make(a, {0}), 10, CompareSelectOperation::kLT), Cond::make( CompareSelect::make(j, 10, CompareSelectOperation::kEQ), Store::make(c, {0}, Load::make(a, {i})), nullptr), nullptr)); StmtPtr simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(Cond, simplified, cond); IS_NODE_WITH_NAME(Block, cond->true_stmt(), true_block); IS_NODE_WITH_NAME(Cond, true_block->front(), cond2); IS_NODE_WITH_NAME(Block, cond2->true_stmt(), true_block2); IS_NODE_WITH_NAME(For, true_block2->front(), loop); } { // Multi level Ifs where the inner condition does depend on a loop var, // reorder only the first Cond. auto body = For::make( i, 0, 4, Cond::make( CompareSelect::make( Load::make(a, {0}), 10, CompareSelectOperation::kLT), Cond::make( CompareSelect::make(i, 10, CompareSelectOperation::kEQ), Store::make(c, {0}, Load::make(a, {i})), nullptr), nullptr)); StmtPtr simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(Cond, simplified, cond); IS_NODE_WITH_NAME(Block, cond->true_stmt(), true_block); IS_NODE_WITH_NAME(For, true_block->front(), loop); IS_NODE_WITH_NAME(Block, loop->body(), loop_body); IS_NODE_WITH_NAME(Cond, loop_body->front(), cond2); } { // Don't reorder if there's an else block of the Cond. // We could, but is it much better? auto body = For::make( i, 0, 4, Cond::make( CompareSelect::make(j, 10, CompareSelectOperation::kLT), Store::make(c, {0}, Load::make(a, {i})), Store::make(c, {0}, 0))); StmtPtr simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(For, simplified, loop); IS_NODE_WITH_NAME(Cond, loop->body()->front(), cond); } { // Condition uses distinct region of Tensor. // We could reorder here wih better analysis, but we don't. Included for // completeness. auto body = For::make( i, 0, 4, Cond::make( CompareSelect::make( Load::make(c, {0}), 10, CompareSelectOperation::kLT), Store::make(c, {1}, Load::make(a, {i})), nullptr)); StmtPtr simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(For, simplified, loop); IS_NODE_WITH_NAME(Cond, loop->body()->front(), cond); } } TEST(Simplify, SimplifyFuseConditions) { BufHandle a("A", {2}, kInt); BufHandle b("B", {2}, kInt); VarHandle i("i", kInt); VarHandle j("j", kInt); { // Can fuse since the conditions are identical. // if (A) { X }; if (A) { Y }; => if (A) { X; Y } auto body = Block::make( {Cond::make( CompareSelect::make(i, 10, CompareSelectOperation::kLT), Store::make(a, {0}, i), nullptr), Cond::make( CompareSelect::make(i, 10, CompareSelectOperation::kLT), Store::make(a, {1}, i), nullptr)}); StmtPtr simplified = IRSimplifier::simplify(body); // NOLINTNEXTLINE(clang-analyzer-cplusplus.NewDeleteLeaks) IS_NODE_WITH_NAME(Block, simplified, block); ASSERT_EQ(block->nstmts(), 1); IS_NODE_WITH_NAME(Cond, block->front(), cond); IS_NODE_WITH_NAME(Block, cond->true_stmt(), true_stmt); ASSERT_EQ(true_stmt->nstmts(), 2); ASSERT_EQ(cond->false_stmt(), nullptr); } { // Can't fuse, conditions are not identical in lhs (i != j). auto body = Block::make( {Cond::make( CompareSelect::make(i, 10, CompareSelectOperation::kLT), Store::make(a, {0}, i), nullptr), Cond::make( CompareSelect::make(j, 10, CompareSelectOperation::kLT), Store::make(a, {1}, i), nullptr)}); StmtPtr simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(Block, simplified, block); ASSERT_EQ(block->nstmts(), 2); IS_NODE_WITH_NAME(Cond, block->front(), cond1); IS_NODE_WITH_NAME(Cond, block->back(), cond2); IS_NODE_WITH_NAME(Block, cond1->true_stmt(), true_stmt1); IS_NODE_WITH_NAME(Block, cond2->true_stmt(), true_stmt2); ASSERT_EQ(true_stmt1->nstmts(), 1); ASSERT_EQ(true_stmt2->nstmts(), 1); ASSERT_EQ(cond1->false_stmt(), nullptr); ASSERT_EQ(cond2->false_stmt(), nullptr); } { // Can't fuse, conditions are not identical in rhs (10 != 11). auto body = Block::make( {Cond::make( CompareSelect::make(i, 10, CompareSelectOperation::kLT), Store::make(a, {0}, i), nullptr), Cond::make( CompareSelect::make(i, 11, CompareSelectOperation::kLT), Store::make(a, {1}, i), nullptr)}); StmtPtr simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(Block, simplified, block); ASSERT_EQ(block->nstmts(), 2); IS_NODE_WITH_NAME(Cond, block->front(), cond1); IS_NODE_WITH_NAME(Cond, block->back(), cond2); IS_NODE_WITH_NAME(Block, cond1->true_stmt(), true_stmt1); IS_NODE_WITH_NAME(Block, cond2->true_stmt(), true_stmt2); ASSERT_EQ(true_stmt1->nstmts(), 1); ASSERT_EQ(true_stmt2->nstmts(), 1); ASSERT_EQ(cond1->false_stmt(), nullptr); ASSERT_EQ(cond2->false_stmt(), nullptr); } { // Can't fuse, conditions are not identical in operation (LT vs GT). auto body = Block::make( {Cond::make( CompareSelect::make(i, 10, CompareSelectOperation::kLT), Store::make(a, {0}, i), nullptr), Cond::make( CompareSelect::make(i, 10, CompareSelectOperation::kGT), Store::make(a, {1}, i), nullptr)}); StmtPtr simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(Block, simplified, block); ASSERT_EQ(block->nstmts(), 2); IS_NODE_WITH_NAME(Cond, block->front(), cond1); IS_NODE_WITH_NAME(Cond, block->back(), cond2); IS_NODE_WITH_NAME(Block, cond1->true_stmt(), true_stmt1); IS_NODE_WITH_NAME(Block, cond2->true_stmt(), true_stmt2); ASSERT_EQ(true_stmt1->nstmts(), 1); ASSERT_EQ(true_stmt2->nstmts(), 1); ASSERT_EQ(cond1->false_stmt(), nullptr); ASSERT_EQ(cond2->false_stmt(), nullptr); } { // Can't fuse, CompareSelect results are different. // Actually we totally could if we normalized CompareSelect results, but // TODO for later. auto body = Block::make( {Cond::make( CompareSelect::make(i, 10, 1, 0, CompareSelectOperation::kLT), Store::make(a, {0}, i), nullptr), Cond::make( CompareSelect::make(j, 10, 2, 0, CompareSelectOperation::kLT), Store::make(a, {1}, i), nullptr)}); StmtPtr simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(Block, simplified, block); ASSERT_EQ(block->nstmts(), 2); IS_NODE_WITH_NAME(Cond, block->front(), cond1); IS_NODE_WITH_NAME(Cond, block->back(), cond2); IS_NODE_WITH_NAME(Block, cond1->true_stmt(), true_stmt1); IS_NODE_WITH_NAME(Block, cond2->true_stmt(), true_stmt2); ASSERT_EQ(true_stmt1->nstmts(), 1); ASSERT_EQ(true_stmt2->nstmts(), 1); ASSERT_EQ(cond1->false_stmt(), nullptr); ASSERT_EQ(cond2->false_stmt(), nullptr); } { // Can fuse with false stmt only. auto body = Block::make( {Cond::make( CompareSelect::make(i, 10, CompareSelectOperation::kLT), nullptr, Store::make(a, {0}, i)), Cond::make( CompareSelect::make(i, 10, CompareSelectOperation::kLT), nullptr, Store::make(a, {1}, i))}); StmtPtr simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(Block, simplified, block); ASSERT_EQ(block->nstmts(), 1); IS_NODE_WITH_NAME(Cond, block->front(), cond); IS_NODE_WITH_NAME(Block, cond->false_stmt(), false_stmt); ASSERT_EQ(false_stmt->nstmts(), 2); ASSERT_EQ(cond->true_stmt(), nullptr); } { // Can fuse with both true and false stmt. auto body = Block::make( {Cond::make( CompareSelect::make(i, 10, CompareSelectOperation::kLT), Store::make(a, {0}, i), Store::make(b, {0}, i)), Cond::make( CompareSelect::make(i, 10, CompareSelectOperation::kLT), Store::make(a, {1}, i), Store::make(b, {1}, i))}); StmtPtr simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(Block, simplified, block); ASSERT_EQ(block->nstmts(), 1); IS_NODE_WITH_NAME(Cond, block->front(), cond); IS_NODE_WITH_NAME(Block, cond->true_stmt(), true_stmt); ASSERT_EQ(true_stmt->nstmts(), 2); IS_NODE_WITH_NAME(Block, cond->true_stmt(), false_stmt); ASSERT_EQ(false_stmt->nstmts(), 2); } { // Can fuse with mismatched true / false stmt existing auto body = Block::make( {Cond::make( CompareSelect::make(i, 10, CompareSelectOperation::kLT), Store::make(a, {0}, i), nullptr), Cond::make( CompareSelect::make(i, 10, CompareSelectOperation::kLT), nullptr, Store::make(b, {1}, i))}); StmtPtr simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(Block, simplified, block); ASSERT_EQ(block->nstmts(), 1); IS_NODE_WITH_NAME(Cond, block->front(), cond); IS_NODE_WITH_NAME(Block, cond->true_stmt(), true_stmt); ASSERT_EQ(true_stmt->nstmts(), 1); IS_NODE_WITH_NAME(Block, cond->true_stmt(), false_stmt); ASSERT_EQ(false_stmt->nstmts(), 1); } { // Can fuse partial block contents, ie when there are non fused stmts before // and after. // before: // if (j < 10) { A[0] = j; } // if (i < 10) { A[0] = i; } // if (i < 10) { A[1] = i; } // if (i < 11) { A[1] = j; } // // after: // // if (j < 10) { A[0] = j; } // if (i < 10) { // A[0] = i; // A[1] = i; // } // if (i < 11) { A[1] = j; } auto body = Block::make({ Cond::make( CompareSelect::make(j, 10, CompareSelectOperation::kLT), Store::make(a, {0}, j), nullptr), Cond::make( CompareSelect::make(i, 10, CompareSelectOperation::kLT), Store::make(a, {0}, i), nullptr), Cond::make( CompareSelect::make(i, 10, CompareSelectOperation::kLT), Store::make(a, {1}, i), nullptr), Cond::make( CompareSelect::make(i, 11, CompareSelectOperation::kLT), Store::make(a, {1}, j), nullptr), }); StmtPtr simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(Block, simplified, block); ASSERT_EQ(block->nstmts(), 3); auto it = block->begin(); it++; IS_NODE_WITH_NAME(Cond, *it, cond); IS_NODE_WITH_NAME(Block, cond->true_stmt(), true_stmt); ASSERT_EQ(true_stmt->nstmts(), 2); ASSERT_EQ(cond->false_stmt(), nullptr); } { // Can fuse longer sequences of identical conditions. auto body = Block::make({ Cond::make( CompareSelect::make(i, 10, CompareSelectOperation::kLT), Store::make(a, {0}, j), nullptr), Cond::make( CompareSelect::make(i, 10, CompareSelectOperation::kLT), Store::make(a, {0}, i), nullptr), Cond::make( CompareSelect::make(i, 10, CompareSelectOperation::kLT), Store::make(a, {1}, i), nullptr), Cond::make( CompareSelect::make(i, 10, CompareSelectOperation::kLT), Store::make(a, {1}, j), nullptr), }); StmtPtr simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(Block, simplified, block); ASSERT_EQ(block->nstmts(), 1); IS_NODE_WITH_NAME(Cond, block->front(), cond); IS_NODE_WITH_NAME(Block, cond->true_stmt(), true_stmt); ASSERT_EQ(true_stmt->nstmts(), 4); ASSERT_EQ(cond->false_stmt(), nullptr); } { // Can't fuse through a non condition. auto body = Block::make({ Cond::make( CompareSelect::make(i, 10, CompareSelectOperation::kLT), Store::make(a, {0}, j), nullptr), Cond::make( CompareSelect::make(i, 10, CompareSelectOperation::kLT), Store::make(a, {0}, i), nullptr), Store::make(b, {1}, i + j), Cond::make( CompareSelect::make(i, 10, CompareSelectOperation::kLT), Store::make(a, {1}, i), nullptr), Cond::make( CompareSelect::make(i, 10, CompareSelectOperation::kLT), Store::make(a, {1}, j), nullptr), }); StmtPtr simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(Block, simplified, block); ASSERT_EQ(block->nstmts(), 3); IS_NODE_WITH_NAME(Cond, block->front(), cond); IS_NODE_WITH_NAME(Block, cond->true_stmt(), true_stmt); ASSERT_EQ(true_stmt->nstmts(), 2); ASSERT_EQ(cond->false_stmt(), nullptr); IS_NODE_WITH_NAME(Cond, block->back(), cond2); IS_NODE_WITH_NAME(Block, cond->true_stmt(), true_stmt2); ASSERT_EQ(true_stmt2->nstmts(), 2); ASSERT_EQ(cond2->false_stmt(), nullptr); auto it = block->begin(); it++; IS_NODE_WITH_NAME(Store, *it, middle); } { // Can fuse if the conditions simplify to the same thing. auto body = Block::make( {Cond::make( CompareSelect::make( i * 2, ExprHandle(87) % ExprHandle(11), CompareSelectOperation::kLT), Store::make(a, {0}, i), nullptr), Cond::make( CompareSelect::make( i * 2, ExprHandle(300) / ExprHandle(30), CompareSelectOperation::kLT), Store::make(a, {1}, i), nullptr)}); StmtPtr simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(Block, simplified, block); ASSERT_EQ(block->nstmts(), 1); IS_NODE_WITH_NAME(Cond, block->front(), cond); IS_NODE_WITH_NAME(Block, cond->true_stmt(), true_stmt); ASSERT_EQ(true_stmt->nstmts(), 2); ASSERT_EQ(cond->false_stmt(), nullptr); } { // Can fuse non-CompareSelects. // if (i) { X } if (i) { Y } => if (i) { X; Y } auto body = Block::make( {Cond::make(i, Store::make(a, {0}, i), nullptr), Cond::make(i, Store::make(a, {1}, i), nullptr)}); StmtPtr simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(Block, simplified, block); ASSERT_EQ(block->nstmts(), 1); IS_NODE_WITH_NAME(Cond, block->front(), cond); IS_NODE_WITH_NAME(Block, cond->true_stmt(), true_stmt); ASSERT_EQ(true_stmt->nstmts(), 2); ASSERT_EQ(cond->false_stmt(), nullptr); } { // Sanity check wont fuse different non-CompareSelects. auto body = Block::make( {Cond::make(i, Store::make(a, {0}, i), nullptr), Cond::make(j, Store::make(a, {1}, i), nullptr)}); StmtPtr simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(Block, simplified, block); ASSERT_EQ(block->nstmts(), 2); IS_NODE_WITH_NAME(Cond, block->front(), cond1); IS_NODE_WITH_NAME(Cond, block->back(), cond2); } { // Sanity check constant condition elimination still occurs when merging is // possible. auto body = Block::make( {Cond::make(1, Store::make(a, {0}, i), nullptr), Cond::make(1, Store::make(a, {1}, i), nullptr)}); StmtPtr simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(Block, simplified, block); ASSERT_EQ(block->nstmts(), 2); IS_NODE_WITH_NAME(Store, block->front(), store1); IS_NODE_WITH_NAME(Store, block->back(), store2); } { // Sanity check for-cond reordering occurs after fusing. auto body = For::make( i, 0, 4, Block::make( {Cond::make( CompareSelect::make(j, 10, CompareSelectOperation::kLT), Store::make(a, {1}, Load::make(b, {0})), nullptr), Cond::make( CompareSelect::make(j, 10, CompareSelectOperation::kLT), Store::make(a, {2}, Load::make(b, {0})), nullptr)})); StmtPtr simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(Cond, simplified, cond); IS_NODE_WITH_NAME(Block, cond->true_stmt(), true_block); IS_NODE_WITH_NAME(For, true_block->front(), loop); } } TEST(Simplify, SimplifySyncThreads) { BufHandle a("A", {4}, kInt); VarHandle i("i", kInt); { // Merge two inner SyncThreads. auto body = Block::make( // NOLINTNEXTLINE(clang-analyzer-cplusplus.NewDeleteLeaks) {Store::make(a, {0}, 1), alloc<SyncThreads>(), alloc<SyncThreads>(), Store::make(a, {1}, 0)}); StmtPtr simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(Block, simplified, block); ASSERT_EQ(block->nstmts(), 3); auto it = block->begin(); IS_NODE(Store, *it++); IS_NODE(SyncThreads, *it++); IS_NODE(Store, *it++); } { // Eliminate outer SyncThreads. auto body = Block::make( {alloc<SyncThreads>(), Store::make(a, {1}, 0), alloc<SyncThreads>()}); StmtPtr simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(Block, simplified, block); ASSERT_EQ(block->nstmts(), 1); auto it = block->begin(); IS_NODE(Store, *it); } { // Merge many inner SyncThreads. auto body = Block::make( {Store::make(a, {0}, 1), alloc<SyncThreads>(), alloc<SyncThreads>(), alloc<SyncThreads>(), alloc<SyncThreads>(), alloc<SyncThreads>(), Store::make(a, {1}, 0)}); StmtPtr simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(Block, simplified, block); ASSERT_EQ(block->nstmts(), 3); auto it = block->begin(); IS_NODE(Store, *it++); IS_NODE(SyncThreads, *it++); IS_NODE(Store, *it++); } { // Merge multiple outer SyncThreads. auto body = Block::make( {alloc<SyncThreads>(), alloc<SyncThreads>(), Store::make(a, {1}, 0), alloc<SyncThreads>(), alloc<SyncThreads>(), alloc<SyncThreads>(), alloc<SyncThreads>()}); StmtPtr simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(Block, simplified, block); ASSERT_EQ(block->nstmts(), 1); auto it = block->begin(); IS_NODE(Store, *it); } { // Merge multiple sections; auto body = Block::make( {Store::make(a, {0}, 1), alloc<SyncThreads>(), alloc<SyncThreads>(), Store::make(a, {1}, 0), Store::make(a, {2}, 0), alloc<SyncThreads>(), alloc<SyncThreads>(), alloc<SyncThreads>(), Store::make(a, {3}, 0)}); StmtPtr simplified = IRSimplifier::simplify(body); IS_NODE_WITH_NAME(Block, simplified, block); ASSERT_EQ(block->nstmts(), 6); auto it = block->begin(); IS_NODE(Store, *it++); IS_NODE(SyncThreads, *it++); IS_NODE(Store, *it++); IS_NODE(Store, *it++); IS_NODE(SyncThreads, *it++); IS_NODE(Store, *it++); } } TEST(Simplify, SimplifyRampSubBroadcast) { int num_lanes = 4; ExprHandle ramp = Ramp::make(ExprHandle(0), ExprHandle(6), num_lanes); ExprHandle broadcast = Broadcast::make(ExprHandle(-5), num_lanes); ExprHandle simplified = IRSimplifier::simplify(ramp - broadcast); RampPtr newRamp = simplified.AsNode<Ramp>(); IS_NODE_WITH_NAME(IntImm, newRamp->base(), base); ASSERT_EQ(base->value(), 5); IS_NODE_WITH_NAME(IntImm, newRamp->stride(), stride); ASSERT_EQ(stride->value(), 6); ASSERT_EQ(newRamp->lanes(), num_lanes); } TEST(Simplify, SimplifyBroadcastTermExpander) { int num_lanes = 8; ExprHandle bc0 = Broadcast::make(ExprHandle(0), num_lanes); ExprHandle bc1 = Broadcast::make(ExprHandle(1), num_lanes); ExprHandle bc2 = Broadcast::make(ExprHandle(2), num_lanes); // NB: We need a term in the middle which isn't simplified to trigger the // relevant path in TermExpander::mutate. The two bc1 terms are brought // together and simplified to 2 * bc1, which then needs to make 2 multi-lane. ExprHandle simplified = IRSimplifier::simplify(bc1 + (bc0 / bc2) + bc1); BufHandle buf("buf", {num_lanes}, kInt); // The result isn't fully simplified currently and thus would be brittle to // match. Observe its value instead. auto store = Store::make(buf, {Ramp::make(0, 1, num_lanes)}, simplified); SimpleIREvaluator eval(store, {buf}); std::vector<int> output(num_lanes); eval(output); for (int i = 0; i < num_lanes; ++i) { ASSERT_EQ(output[i], 2); } } TEST(Simplify, DISABLED_CompareSelectCondAlwaysInLoopBounds) { // Before: // for (int n = 1; n < N; n++) { // b[n] = n < 1 ? 0.f : 1.f; // } // After: // for (int n = 1; n < N; n++) { // b[n] = 1.f; // } constexpr int N = 8; BufHandle b("b", {N}, kFloat); VarHandle n("n", kInt); StmtPtr s = For::make( n, 1, N, b.store({n}, CompareSelect::make(n, 1, 0.f, 1.0f, kLT))); s = IRSimplifier::simplify(s); std::ostringstream oss; oss << *s; torch::jit::testing::FileCheck().run( R"IR( # CHECK: b[n] = 1.f; )IR", oss.str()); } TEST(Simplify, DISABLED_IfThenCondAlwaysInLoopBounds) { // Before: // for (int n = 1; n < N; n++) { // b[n] = IfThenElse(n < 1 ? 1 : 0, 0.f, 1.f); // } // After: // for (int n = 1; n < N; n++) { // b[n] = 1.f; // } constexpr int N = 8; BufHandle b("b", {N}, kFloat); VarHandle n("n", kInt); StmtPtr s = For::make(n, 1, N, b.store({n}, IfThenElse::make(n < 1, 0.f, 1.0f))); s = IRSimplifier::simplify(s); std::ostringstream oss; oss << *s; torch::jit::testing::FileCheck().run( R"IR( # CHECK: b[n] = 1.f; )IR", oss.str()); } TEST(Simplify, DISABLED_MultiClauseCondAlwaysInLoopBounds) { // This test mimics the unpadded region of a conv2d. We want to remove any // conditional that is provably satisfied (or unsatisfied) by the entire loop // range. // Before: // for (int i = 1; i < 7; i++) { // for (int j = 1; j < 7; j++) { // b[i, j] = IfThenElse( // j>=7 ? 1 : (i>=7 ? 1 : (j<1 ? 1 : (i<1 ? 1 : 0))), 0.f, 1.f); // After: // for (int i = 1; i < 7; i++) { // for (int j = 1; j < 7; j++) { // b[i, j] = 1.f; constexpr int N = 8; BufHandle b("b", {N, N}, kFloat); VarHandle i("i", kInt); VarHandle j("j", kInt); auto csel = CompareSelect::make(i, 1, kLT); csel = CompareSelect::make(j, 1, 1, csel, kLT); csel = CompareSelect::make(i, N - 1, 1, csel, kGE); csel = CompareSelect::make(j, N - 1, 1, csel, kGE); StmtPtr s = b.store({i, j}, IfThenElse::make(csel, 0.f, 1.0f)); s = For::make(j, 1, N - 1, s); s = For::make(i, 1, N - 1, s); s = IRSimplifier::simplify(s); std::ostringstream oss; oss << *s; torch::jit::testing::FileCheck().run( R"IR( # CHECK: b[n] = 1.f; )IR", oss.str()); } TEST(Simplify, DISABLED_SimplifyLoopBounds) { // This test mimics the padded region of a conv2d. We want to adjust the // loop bounds such that the condition will be always met. Note that this // could be solved by peeling, and applying the range-based conditional // simplification in the previous tests. // Before: // for (int i = 0; i < 3; i++) { // for (int j = 0; j < 3; j++) { // b[i, j] = (b[i, j]) + (IfThenElse( // j>=7 ? 1 : (i>=7 ? 1 : (j<1 ? 1 : (i<1 ? 1 : 0))), 0.f, a[i, j])); // After: // for (int i = 1; i < 3; i++) { // for (int j = 1; j < 3; j++) { // b[i, j] = (b[i, j]) + 1.f; constexpr int N = 8; constexpr int K = 3; BufHandle a("a", {N, N}, kFloat); BufHandle b("b", {N, N}, kFloat); VarHandle i("i", kInt); VarHandle j("j", kInt); auto csel = CompareSelect::make(i, 1, kLT); csel = CompareSelect::make(j, 1, 1, csel, kLT); csel = CompareSelect::make(i, N - 1, 1, csel, kGE); csel = CompareSelect::make(j, N - 1, 1, csel, kGE); StmtPtr s = b.store( {i, j}, b.load({i, j}) + IfThenElse::make(csel, 0.f, a.load({i, j}))); s = For::make(j, 0, K, s); s = For::make(i, 0, K, s); s = IRSimplifier::simplify(s); std::ostringstream oss; oss << *s; torch::jit::testing::FileCheck().run( R"IR( # CHECK: for (int i = 1; i < 3; i++) { # CHECK: for (int j = 1; j < 3; j++) { # CHECK-NOT: IfThenElse )IR", oss.str()); } } // namespace jit } // namespace torch
/// @copyright /// Copyright (C) 2020 Assured Information Security, Inc. /// /// @copyright /// 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: /// /// @copyright /// The above copyright notice and this permission notice shall be included in /// all copies or substantial portions of the Software. /// /// @copyright /// 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. #ifndef VP_T_BASE_HPP #define VP_T_BASE_HPP #include "dummy_errc_types.hpp" #include <allocated_status_t.hpp> #include <tls_t.hpp> #include <bsl/discard.hpp> #include <bsl/errc_type.hpp> #include <bsl/safe_integral.hpp> namespace mk { /// @class mk::dummy_vp_t /// /// <!-- description --> /// @brief Provides the vp_t for testing. /// class dummy_vp_t final { /// @brief stores the ID associated with this vp_t bsl::safe_uint16 m_id{bsl::safe_uint16::failure()}; /// @brief stores whether or not this vp_t is allocated. allocated_status_t m_allocated{allocated_status_t::deallocated}; /// @brief stores the ID of the VM this vp_t is assigned to bsl::safe_uint16 m_assigned_vmid{syscall::BF_INVALID_ID}; /// @brief stores the ID of the PP this vp_t is assigned to bsl::safe_uint16 m_assigned_ppid{syscall::BF_INVALID_ID}; /// @brief stores whether or not this vp_t is active. bool m_active{}; public: /// <!-- description --> /// @brief Initializes this vp_t /// /// <!-- inputs/outputs --> /// @param tls the current TLS block /// @param i the ID for this vp_t /// @return Returns bsl::errc_success on success, bsl::errc_failure /// and friends otherwise /// [[nodiscard]] constexpr auto initialize(tls_t &tls, bsl::safe_uint16 const &i) noexcept -> bsl::errc_type { if (tls.test_ret == errc_fail_initialize) { return bsl::errc_failure; } if (tls.test_ret == errc_fail_initialize_and_release) { return bsl::errc_failure; } m_id = i; return bsl::errc_success; } /// <!-- description --> /// @brief Release the vp_t. /// /// <!-- inputs/outputs --> /// @param tls the current TLS block /// @param vps_pool the VPS pool to use /// @return Returns bsl::errc_success on success, bsl::errc_failure /// and friends otherwise /// [[nodiscard]] constexpr auto release(tls_t &tls, vps_pool_t &vps_pool) noexcept -> bsl::errc_type { bsl::discard(vps_pool); if (tls.test_ret == errc_fail_initialize_and_release) { return bsl::errc_failure; } if (tls.test_ret == errc_fail_release) { return bsl::errc_failure; } return bsl::errc_success; } /// <!-- description --> /// @brief Returns the ID of this vp_t /// /// <!-- inputs/outputs --> /// @return Returns the ID of this vp_t /// [[nodiscard]] constexpr auto id() const noexcept -> bsl::safe_uint16 const & { return m_id; } /// <!-- description --> /// @brief Allocates this vp_t /// /// <!-- inputs/outputs --> /// @param tls the current TLS block /// @param vm_pool the VM pool to use /// @param vmid The ID of the VM to assign the newly created VP to /// @param ppid The ID of the PP to assign the newly created VP to /// @return Returns bsl::errc_success on success, bsl::errc_failure /// and friends otherwise /// [[nodiscard]] constexpr auto allocate( tls_t &tls, vm_pool_t &vm_pool, bsl::safe_uint16 const &vmid, bsl::safe_uint16 const &ppid) noexcept -> bsl::safe_uint16 { bsl::discard(vm_pool); if (!tls.test_ret) { return bsl::safe_uint16::failure(); } m_assigned_vmid = vmid; m_assigned_ppid = ppid; m_allocated = allocated_status_t::allocated; return m_id; } /// <!-- description --> /// @brief Deallocates this vp_t /// /// <!-- inputs/outputs --> /// @param tls the current TLS block /// @param vps_pool the VPS pool to use /// @return Returns bsl::errc_success on success, bsl::errc_failure /// and friends otherwise /// [[nodiscard]] constexpr auto deallocate(tls_t &tls, vps_pool_t &vps_pool) noexcept -> bsl::errc_type { bsl::discard(vps_pool); m_assigned_ppid = syscall::BF_INVALID_ID; m_assigned_vmid = syscall::BF_INVALID_ID; m_allocated = allocated_status_t::deallocated; return tls.test_ret; } /// <!-- description --> /// @brief Sets this vp_t's status as zombified, meaning it is no /// longer usable. /// constexpr void zombify() noexcept { m_allocated = allocated_status_t::zombie; } /// <!-- description --> /// @brief Returns true if this vp_t is deallocated, false otherwise /// /// <!-- inputs/outputs --> /// @return Returns true if this vp_t is deallocated, false otherwise /// [[nodiscard]] constexpr auto is_deallocated() const noexcept -> bool { return m_allocated == allocated_status_t::deallocated; } /// <!-- description --> /// @brief Returns true if this vp_t is allocated, false otherwise /// /// <!-- inputs/outputs --> /// @return Returns true if this vp_t is allocated, false otherwise /// [[nodiscard]] constexpr auto is_allocated() const noexcept -> bool { return m_allocated == allocated_status_t::allocated; } /// <!-- description --> /// @brief Returns true if this vp_t is a zombie, false otherwise /// /// <!-- inputs/outputs --> /// @return Returns true if this vp_t is a zombie, false otherwise /// [[nodiscard]] constexpr auto is_zombie() const noexcept -> bool { return m_allocated == allocated_status_t::zombie; } /// <!-- description --> /// @brief Sets this vp_t as active. /// /// <!-- inputs/outputs --> /// @param tls the current TLS block /// @return Returns bsl::errc_success on success, bsl::errc_failure /// and friends otherwise /// [[nodiscard]] constexpr auto set_active(tls_t &tls) noexcept -> bsl::errc_type { m_active = true; return tls.test_ret; } /// <!-- description --> /// @brief Sets this vp_t as inactive. /// /// <!-- inputs/outputs --> /// @param tls the current TLS block /// @return Returns bsl::errc_success on success, bsl::errc_failure /// and friends otherwise /// [[nodiscard]] constexpr auto set_inactive(tls_t &tls) noexcept -> bsl::errc_type { m_active = {}; return tls.test_ret; } /// <!-- description --> /// @brief Returns the ID of the first PP identified that this VP /// is still active on. If the VP is inactive, this function /// returns bsl::safe_uint16::failure() /// /// <!-- inputs/outputs --> /// @param tls the current TLS block /// @return Returns the ID of the first PP identified that this VP /// is still active on. If the VP is inactive, this function /// returns bsl::safe_uint16::failure() /// [[nodiscard]] constexpr auto is_active(tls_t &tls) const noexcept -> bsl::safe_uint16 { bsl::discard(tls); if (m_active) { return {}; } return bsl::safe_uint16::failure(); } /// <!-- description --> /// @brief Returns true if this vp_t is active on the current PP, /// false otherwise /// /// <!-- inputs/outputs --> /// @param tls the current TLS block /// @return Returns true if this vp_t is active on the current PP, /// false otherwise /// [[nodiscard]] constexpr auto is_active_on_current_pp(tls_t &tls) const noexcept -> bool { bsl::discard(tls); return m_active; } /// <!-- description --> /// @brief Migrates this vp_t from one PP to another. If this calls /// completes successfully, the VPS's assigned PP will not /// match the VP's assigned PP. Future calls to the run ABI /// will be able to detect this an migrate mismatched VPSs to /// the proper PP as needed. Note that since the VP doesn't control /// any hardware state, all we have to do here is set which PP /// this VP is allowed to execute on. The VPS is what actually /// needs to be migrated, and that will not happen until a call /// to the run ABIs made. Once the run ABI detects a mismatch with /// the VPS and it's assigned VP, it will be migrated then. /// /// <!-- inputs/outputs --> /// @param tls the current TLS block /// @param ppid the ID of the PP to migrate to /// @return Returns bsl::errc_success on success, bsl::errc_failure /// and friends otherwise /// [[nodiscard]] constexpr auto migrate(tls_t &tls, bsl::safe_uint16 const &ppid) noexcept -> bsl::errc_type { bsl::discard(tls); bsl::discard(ppid); m_assigned_ppid = ppid; return tls.test_ret; } /// <!-- description --> /// @brief Returns the ID of the VM this vp_t is assigned to /// /// <!-- inputs/outputs --> /// @return Returns the ID of the VM this vp_t is assigned to /// [[nodiscard]] constexpr auto assigned_vm() const noexcept -> bsl::safe_uint16 { if (bsl::unlikely(syscall::BF_INVALID_ID == m_assigned_vmid)) { return bsl::safe_uint16::failure(); } return m_assigned_vmid; } /// <!-- description --> /// @brief Returns the ID of the PP this vp_t is assigned to /// /// <!-- inputs/outputs --> /// @return Returns the ID of the PP this vp_t is assigned to /// [[nodiscard]] constexpr auto assigned_pp() const noexcept -> bsl::safe_uint16 { if (bsl::unlikely(syscall::BF_INVALID_ID == m_assigned_ppid)) { return bsl::safe_uint16::failure(); } return m_assigned_ppid; } // <!-- description --> /// @brief Dumps the vp_t /// /// <!-- inputs/outputs --> /// @param tls the current TLS block /// constexpr void dump(tls_t &tls) const noexcept { bsl::discard(tls); } }; } #endif
// Copyright 2010-2021, 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 "base/system_util.h" #include <cstdint> #ifdef OS_WIN // clang-format off #include <Windows.h> #include <LMCons.h> #include <Sddl.h> #include <ShlObj.h> #include <VersionHelpers.h> // clang-format on #else // OS_WIN #include <pwd.h> #include <sys/mman.h> #include <unistd.h> #endif // OS_WIN #ifdef __APPLE__ #include <sys/stat.h> #include <sys/sysctl.h> #include <cerrno> #endif // __APPLE__ #include <cstdlib> #include <cstring> #ifdef OS_WIN #include <memory> #endif // OS_WIN #include <sstream> #include <string> #ifdef OS_ANDROID #include "base/android_util.h" #endif // OS_ANDROID #include "base/const.h" #include "base/environ.h" #include "base/file_util.h" #include "base/logging.h" #ifdef __APPLE__ #include "base/mac_util.h" #endif // __APPLE__ #include "base/mutex.h" #include "base/singleton.h" #include "base/util.h" #ifdef OS_WIN #include "base/win_util.h" #endif // OS_WIN namespace mozc { namespace { class UserProfileDirectoryImpl final { public: UserProfileDirectoryImpl() = default; ~UserProfileDirectoryImpl() = default; std::string GetDir(); void SetDir(const std::string &dir); private: std::string GetUserProfileDirectory() const; std::string dir_; Mutex mutex_; }; std::string UserProfileDirectoryImpl::GetDir() { scoped_lock l(&mutex_); if (!dir_.empty()) { return dir_; } const std::string dir = GetUserProfileDirectory(); FileUtil::CreateDirectory(dir); if (!FileUtil::DirectoryExists(dir)) { LOG(ERROR) << "Failed to create directory: " << dir; } dir_ = dir; return dir_; } void UserProfileDirectoryImpl::SetDir(const std::string &dir) { scoped_lock l(&mutex_); dir_ = dir; } #ifdef OS_WIN // TODO(yukawa): Use API wrapper so that unit test can emulate any case. class LocalAppDataDirectoryCache { public: LocalAppDataDirectoryCache() : result_(E_FAIL) { result_ = SafeTryGetLocalAppData(&path_); } HRESULT result() const { return result_; } const bool succeeded() const { return SUCCEEDED(result_); } const std::string &path() const { return path_; } private: // b/5707813 implies that TryGetLocalAppData causes an exception and makes // Singleton<LocalAppDataDirectoryCache> invalid state which results in an // infinite spin loop in CallOnce. To prevent this, the constructor of // LocalAppDataDirectoryCache must be exception free. // Note that __try and __except does not guarantees that any destruction // of internal C++ objects when a non-C++ exception occurs except that // /EHa compiler option is specified. // Since Mozc uses /EHs option in common.gypi, we must admit potential // memory leakes when any non-C++ exception occues in TryGetLocalAppData. // See http://msdn.microsoft.com/en-us/library/1deeycx5.aspx static HRESULT __declspec(nothrow) SafeTryGetLocalAppData(std::string *dir) { __try { return TryGetLocalAppData(dir); } __except (EXCEPTION_EXECUTE_HANDLER) { return E_UNEXPECTED; } } static HRESULT TryGetLocalAppData(std::string *dir) { if (dir == nullptr) { return E_FAIL; } dir->clear(); bool in_app_container = false; if (!WinUtil::IsProcessInAppContainer(::GetCurrentProcess(), &in_app_container)) { return E_FAIL; } if (in_app_container) { return TryGetLocalAppDataForAppContainer(dir); } return TryGetLocalAppDataLow(dir); } static HRESULT TryGetLocalAppDataForAppContainer(std::string *dir) { // User profiles for processes running under AppContainer seem to be as // follows, while the scheme is not officially documented. // "%LOCALAPPDATA%\Packages\<package sid>\..." // Note: You can also obtain this path by GetAppContainerFolderPath API. // http://msdn.microsoft.com/en-us/library/windows/desktop/hh448543.aspx // Anyway, here we use heuristics to obtain "LocalLow" folder path. // TODO(yukawa): Establish more reliable way to obtain the path. wchar_t config[MAX_PATH] = {}; const HRESULT result = ::SHGetFolderPathW( nullptr, CSIDL_LOCAL_APPDATA, nullptr, SHGFP_TYPE_CURRENT, &config[0]); if (FAILED(result)) { return result; } std::wstring path = config; const std::wstring::size_type local_pos = path.find(L"\\Packages\\"); if (local_pos == std::wstring::npos) { return E_FAIL; } path.erase(local_pos); path += L"Low"; if (Util::WideToUTF8(path, dir) == 0) { return E_FAIL; } return S_OK; } static HRESULT TryGetLocalAppDataLow(std::string *dir) { if (dir == nullptr) { return E_FAIL; } dir->clear(); wchar_t *task_mem_buffer = nullptr; const HRESULT result = ::SHGetKnownFolderPath(FOLDERID_LocalAppDataLow, 0, nullptr, &task_mem_buffer); if (FAILED(result)) { if (task_mem_buffer != nullptr) { ::CoTaskMemFree(task_mem_buffer); } return result; } if (task_mem_buffer == nullptr) { return E_UNEXPECTED; } std::wstring wpath = task_mem_buffer; ::CoTaskMemFree(task_mem_buffer); std::string path; if (Util::WideToUTF8(wpath, &path) == 0) { return E_UNEXPECTED; } *dir = path; return S_OK; } HRESULT result_; std::string path_; }; #endif // OS_WIN std::string UserProfileDirectoryImpl::GetUserProfileDirectory() const { #if defined(OS_CHROMEOS) // TODO(toka): Must use passed in user profile dir which passed in. If mojo // platform the user profile is determined on runtime. // It's hack, the user profile dir should be passed in. Although the value in // NaCL platform is correct. return "/mutable"; #elif defined(OS_WASM) // Do nothing for WebAssembly. return ""; #elif defined(OS_ANDROID) // For android, we do nothing here because user profile directory, // of which the path depends on active user, // is injected from Java layer. return ""; #elif defined(OS_IOS) // OS_IOS block must be placed before __APPLE__ because both macros are // currently defined on iOS. // // On iOS, use Caches directory instead of Application Spport directory // because the support directory doesn't exist by default. Also, it is backed // up by iTunes and iCloud. return FileUtil::JoinPath({MacUtil::GetCachesDirectory(), kProductPrefix}); #elif defined(OS_WIN) DCHECK(SUCCEEDED(Singleton<LocalAppDataDirectoryCache>::get()->result())); std::string dir = Singleton<LocalAppDataDirectoryCache>::get()->path(); #ifdef GOOGLE_JAPANESE_INPUT_BUILD dir = FileUtil::JoinPath(dir, kCompanyNameInEnglish); FileUtil::CreateDirectory(dir); #endif // GOOGLE_JAPANESE_INPUT_BUILD return FileUtil::JoinPath(dir, kProductNameInEnglish); #elif defined(__APPLE__) std::string dir = MacUtil::GetApplicationSupportDirectory(); #ifdef GOOGLE_JAPANESE_INPUT_BUILD dir = FileUtil::JoinPath(dir, "Google"); // The permission of ~/Library/Application Support/Google seems to be 0755. // TODO(komatsu): nice to make a wrapper function. ::mkdir(dir.c_str(), 0755); return FileUtil::JoinPath(dir, "JapaneseInput"); #else // GOOGLE_JAPANESE_INPUT_BUILD return FileUtil::JoinPath(dir, "Mozc"); #endif // GOOGLE_JAPANESE_INPUT_BUILD #elif defined(OS_LINUX) // 1. If "$HOME/.mozc" already exists, // use "$HOME/.mozc" for backward compatibility. // 2. If $XDG_CONFIG_HOME is defined // use "$XDG_CONFIG_HOME/mozc". // 3. Otherwise // use "$HOME/.config/mozc" as the default value of $XDG_CONFIG_HOME // https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html const char *home = Environ::GetEnv("HOME"); if (home == nullptr) { char buf[1024]; struct passwd pw, *ppw; const uid_t uid = geteuid(); CHECK_EQ(0, getpwuid_r(uid, &pw, buf, sizeof(buf), &ppw)) << "Can't get passwd entry for uid " << uid << "."; CHECK_LT(0, strlen(pw.pw_dir)) << "Home directory for uid " << uid << " is not set."; return FileUtil::JoinPath(pw.pw_dir, ".mozc"); } const std::string old_dir = FileUtil::JoinPath(home, ".mozc"); if (FileUtil::DirectoryExists(old_dir)) { return old_dir; } const char *xdg_config_home = Environ::GetEnv("XDG_CONFIG_HOME"); if (xdg_config_home) { return FileUtil::JoinPath(xdg_config_home, "mozc"); } return FileUtil::JoinPath(home, ".config/mozc"); #else #error Undefined target platform. #endif } } // namespace std::string SystemUtil::GetUserProfileDirectory() { return Singleton<UserProfileDirectoryImpl>::get()->GetDir(); } std::string SystemUtil::GetLoggingDirectory() { #ifdef __APPLE__ std::string dir = MacUtil::GetLoggingDirectory(); FileUtil::CreateDirectory(dir); return dir; #else // __APPLE__ return GetUserProfileDirectory(); #endif // __APPLE__ } void SystemUtil::SetUserProfileDirectory(const std::string &path) { Singleton<UserProfileDirectoryImpl>::get()->SetDir(path); } #ifdef OS_WIN namespace { // TODO(yukawa): Use API wrapper so that unit test can emulate any case. class ProgramFilesX86Cache { public: ProgramFilesX86Cache() : result_(E_FAIL) { result_ = SafeTryProgramFilesPath(&path_); } const bool succeeded() const { return SUCCEEDED(result_); } const HRESULT result() const { return result_; } const std::string &path() const { return path_; } private: // b/5707813 implies that the Shell API causes an exception in some cases. // In order to avoid potential infinite loops in CallOnce. the constructor of // ProgramFilesX86Cache must be exception free. // Note that __try and __except does not guarantees that any destruction // of internal C++ objects when a non-C++ exception occurs except that // /EHa compiler option is specified. // Since Mozc uses /EHs option in common.gypi, we must admit potential // memory leakes when any non-C++ exception occues in TryProgramFilesPath. // See http://msdn.microsoft.com/en-us/library/1deeycx5.aspx static HRESULT __declspec(nothrow) SafeTryProgramFilesPath(std::string *path) { __try { return TryProgramFilesPath(path); } __except (EXCEPTION_EXECUTE_HANDLER) { return E_UNEXPECTED; } } static HRESULT TryProgramFilesPath(std::string *path) { if (path == nullptr) { return E_FAIL; } path->clear(); wchar_t program_files_path_buffer[MAX_PATH] = {}; #if defined(_M_X64) // In 64-bit processes (such as Text Input Prosessor DLL for 64-bit apps), // CSIDL_PROGRAM_FILES points 64-bit Program Files directory. In this case, // we should use CSIDL_PROGRAM_FILESX86 to find server, renderer, and other // binaries' path. const HRESULT result = ::SHGetFolderPathW(nullptr, CSIDL_PROGRAM_FILESX86, nullptr, SHGFP_TYPE_CURRENT, program_files_path_buffer); #elif defined(_M_IX86) // In 32-bit processes (such as server, renderer, and other binaries), // CSIDL_PROGRAM_FILES always points 32-bit Program Files directory // even if they are running in 64-bit Windows. const HRESULT result = ::SHGetFolderPathW(nullptr, CSIDL_PROGRAM_FILES, nullptr, SHGFP_TYPE_CURRENT, program_files_path_buffer); #else // !_M_X64 && !_M_IX86 #error "Unsupported CPU architecture" #endif // _M_X64, _M_IX86, and others if (FAILED(result)) { return result; } std::string program_files; if (Util::WideToUTF8(program_files_path_buffer, &program_files) == 0) { return E_FAIL; } *path = program_files; return S_OK; } HRESULT result_; std::string path_; }; } // namespace #endif // OS_WIN std::string SystemUtil::GetServerDirectory() { #ifdef OS_WIN DCHECK(SUCCEEDED(Singleton<ProgramFilesX86Cache>::get()->result())); #if defined(GOOGLE_JAPANESE_INPUT_BUILD) return FileUtil::JoinPath( FileUtil::JoinPath(Singleton<ProgramFilesX86Cache>::get()->path(), kCompanyNameInEnglish), kProductNameInEnglish); #else // GOOGLE_JAPANESE_INPUT_BUILD return FileUtil::JoinPath(Singleton<ProgramFilesX86Cache>::get()->path(), kProductNameInEnglish); #endif // GOOGLE_JAPANESE_INPUT_BUILD #endif // OS_WIN #if defined(__APPLE__) return MacUtil::GetServerDirectory(); #endif // __APPLE__ #if defined(OS_LINUX) || defined(OS_ANDROID) || defined(OS_WASM) #if defined(MOZC_SERVER_DIRECTORY) return MOZC_SERVER_DIRECTORY; #else return "/usr/lib/mozc"; #endif // MOZC_SERVER_DIRECTORY #endif // OS_LINUX || OS_ANDROID || OS_WASM // If none of the above platforms is specified, the compiler raises an error // because of no return value. } std::string SystemUtil::GetServerPath() { const std::string server_path = GetServerDirectory(); // if server path is empty, return empty path if (server_path.empty()) { return ""; } return FileUtil::JoinPath(server_path, kMozcServerName); } std::string SystemUtil::GetRendererPath() { const std::string server_path = GetServerDirectory(); // if server path is empty, return empty path if (server_path.empty()) { return ""; } return FileUtil::JoinPath(server_path, kMozcRenderer); } std::string SystemUtil::GetToolPath() { const std::string server_path = GetServerDirectory(); // if server path is empty, return empty path if (server_path.empty()) { return ""; } return FileUtil::JoinPath(server_path, kMozcTool); } std::string SystemUtil::GetDocumentDirectory() { #if defined(__APPLE__) return GetServerDirectory(); #elif defined(MOZC_DOCUMENT_DIRECTORY) return MOZC_DOCUMENT_DIRECTORY; #else return FileUtil::JoinPath(GetServerDirectory(), "documents"); #endif // __APPLE__ } std::string SystemUtil::GetCrashReportDirectory() { const char kCrashReportDirectory[] = "CrashReports"; return FileUtil::JoinPath(SystemUtil::GetUserProfileDirectory(), kCrashReportDirectory); } std::string SystemUtil::GetUserNameAsString() { #if defined(OS_WIN) wchar_t wusername[UNLEN + 1]; DWORD name_size = UNLEN + 1; // Call the same name Windows API. (include Advapi32.lib). // TODO(komatsu, yukawa): Add error handling. // TODO(komatsu, yukawa): Consider the case where the current thread is // or will be impersonated. const BOOL result = ::GetUserName(wusername, &name_size); DCHECK_NE(FALSE, result); std::string username; Util::WideToUTF8(&wusername[0], &username); return username; #endif // OS_WIN #if defined(OS_ANDROID) // Android doesn't seem to support getpwuid_r. struct passwd *ppw = getpwuid(geteuid()); CHECK(ppw != nullptr); return ppw->pw_name; #endif // OS_ANDROID #if defined(__APPLE__) || defined(OS_LINUX) || defined(OS_WASM) struct passwd pw, *ppw; char buf[1024]; CHECK_EQ(0, getpwuid_r(geteuid(), &pw, buf, sizeof(buf), &ppw)); return pw.pw_name; #endif // __APPLE__ || OS_LINUX || OS_WASM // If none of the above platforms is specified, the compiler raises an error // because of no return value. } #ifdef OS_WIN namespace { class UserSidImpl { public: UserSidImpl(); const std::string &get() { return sid_; } private: std::string sid_; }; UserSidImpl::UserSidImpl() { HANDLE htoken = nullptr; if (!::OpenProcessToken(::GetCurrentProcess(), TOKEN_QUERY, &htoken)) { sid_ = SystemUtil::GetUserNameAsString(); LOG(ERROR) << "OpenProcessToken failed: " << ::GetLastError(); return; } DWORD length = 0; ::GetTokenInformation(htoken, TokenUser, nullptr, 0, &length); std::unique_ptr<char[]> buf(new char[length]); PTOKEN_USER p_user = reinterpret_cast<PTOKEN_USER>(buf.get()); if (length == 0 || !::GetTokenInformation(htoken, TokenUser, p_user, length, &length)) { ::CloseHandle(htoken); sid_ = SystemUtil::GetUserNameAsString(); LOG(ERROR) << "OpenTokenInformation failed: " << ::GetLastError(); return; } LPTSTR p_sid_user_name; if (!::ConvertSidToStringSidW(p_user->User.Sid, &p_sid_user_name)) { ::CloseHandle(htoken); sid_ = SystemUtil::GetUserNameAsString(); LOG(ERROR) << "ConvertSidToStringSidW failed: " << ::GetLastError(); return; } Util::WideToUTF8(p_sid_user_name, &sid_); ::LocalFree(p_sid_user_name); ::CloseHandle(htoken); } } // namespace #endif // OS_WIN std::string SystemUtil::GetUserSidAsString() { #ifdef OS_WIN return Singleton<UserSidImpl>::get()->get(); #else // OS_WIN return GetUserNameAsString(); #endif // OS_WIN } #ifdef OS_WIN namespace { std::string GetObjectNameAsString(HANDLE handle) { if (handle == nullptr) { LOG(ERROR) << "Unknown handle"; return ""; } DWORD size = 0; if (::GetUserObjectInformationA(handle, UOI_NAME, nullptr, 0, &size) || ERROR_INSUFFICIENT_BUFFER != ::GetLastError()) { LOG(ERROR) << "GetUserObjectInformationA() failed: " << ::GetLastError(); return ""; } if (size == 0) { LOG(ERROR) << "buffer size is 0"; return ""; } std::unique_ptr<char[]> buf(new char[size]); DWORD return_size = 0; if (!::GetUserObjectInformationA(handle, UOI_NAME, buf.get(), size, &return_size)) { LOG(ERROR) << "::GetUserObjectInformationA() failed: " << ::GetLastError(); return ""; } if (return_size <= 1) { LOG(ERROR) << "result buffer size is too small"; return ""; } char *result = buf.get(); result[return_size - 1] = '\0'; // just make sure nullptr terminated return result; } bool GetCurrentSessionId(uint32 *session_id) { DCHECK(session_id); *session_id = 0; DWORD id = 0; if (!::ProcessIdToSessionId(::GetCurrentProcessId(), &id)) { LOG(ERROR) << "cannot get session id: " << ::GetLastError(); return false; } static_assert(sizeof(DWORD) == sizeof(uint32), "DWORD and uint32 must be equivalent"); *session_id = static_cast<uint32>(id); return true; } // Here we use the input desktop instead of the desktop associated with the // current thread. One reason behind this is that some applications such as // Adobe Reader XI use multiple desktops in a process. Basically the input // desktop is most appropriate and important desktop for our use case. // See // http://blogs.adobe.com/asset/2012/10/new-security-capabilities-in-adobe-reader-and-acrobat-xi-now-available.html std::string GetInputDesktopName() { const HDESK desktop_handle = ::OpenInputDesktop(0, FALSE, DESKTOP_READOBJECTS); if (desktop_handle == nullptr) { return ""; } const std::string desktop_name = GetObjectNameAsString(desktop_handle); ::CloseDesktop(desktop_handle); return desktop_name; } std::string GetProcessWindowStationName() { // We must not close the returned value of GetProcessWindowStation(). // http://msdn.microsoft.com/en-us/library/windows/desktop/ms683225.aspx const HWINSTA window_station = ::GetProcessWindowStation(); if (window_station == nullptr) { return ""; } return GetObjectNameAsString(window_station); } std::string GetSessionIdString() { uint32 session_id = 0; if (!GetCurrentSessionId(&session_id)) { return ""; } return std::to_string(session_id); } } // namespace #endif // OS_WIN std::string SystemUtil::GetDesktopNameAsString() { #if defined(OS_LINUX) || defined(OS_ANDROID) || defined(OS_WASM) const char *display = Environ::GetEnv("DISPLAY"); if (display == nullptr) { return ""; } return display; #endif // OS_LINUX || OS_ANDROID || OS_WASM #if defined(__APPLE__) return ""; #endif // __APPLE__ #if defined(OS_WIN) const std::string &session_id = GetSessionIdString(); if (session_id.empty()) { DLOG(ERROR) << "Failed to retrieve session id"; return ""; } const std::string &window_station_name = GetProcessWindowStationName(); if (window_station_name.empty()) { DLOG(ERROR) << "Failed to retrieve window station name"; return ""; } const std::string &desktop_name = GetInputDesktopName(); if (desktop_name.empty()) { DLOG(ERROR) << "Failed to retrieve desktop name"; return ""; } return (session_id + "." + window_station_name + "." + desktop_name); #endif // OS_WIN } #ifdef OS_WIN namespace { // TODO(yukawa): Use API wrapper so that unit test can emulate any case. class SystemDirectoryCache { public: SystemDirectoryCache() : system_dir_(nullptr) { const UINT copied_len_wo_null_if_success = ::GetSystemDirectory(path_buffer_, arraysize(path_buffer_)); if (copied_len_wo_null_if_success >= arraysize(path_buffer_)) { // Function failed. return; } DCHECK_EQ(L'\0', path_buffer_[copied_len_wo_null_if_success]); system_dir_ = path_buffer_; } const bool succeeded() const { return system_dir_ != nullptr; } const wchar_t *system_dir() const { return system_dir_; } private: wchar_t path_buffer_[MAX_PATH]; wchar_t *system_dir_; }; } // namespace // TODO(team): Support other platforms. bool SystemUtil::EnsureVitalImmutableDataIsAvailable() { if (!Singleton<SystemDirectoryCache>::get()->succeeded()) { return false; } if (!Singleton<ProgramFilesX86Cache>::get()->succeeded()) { return false; } if (!Singleton<LocalAppDataDirectoryCache>::get()->succeeded()) { return false; } return true; } #endif // OS_WIN bool SystemUtil::IsWindows7OrLater() { #ifdef OS_WIN static const bool result = ::IsWindows7OrGreater(); return result; #else return false; #endif // OS_WIN } bool SystemUtil::IsWindows8OrLater() { #ifdef OS_WIN static const bool result = ::IsWindows8OrGreater(); return result; #else return false; #endif // OS_WIN } bool SystemUtil::IsWindows8_1OrLater() { #ifdef OS_WIN static const bool result = ::IsWindows8Point1OrGreater(); return result; #else return false; #endif // OS_WIN } namespace { volatile mozc::SystemUtil::IsWindowsX64Mode g_is_windows_x64_mode = mozc::SystemUtil::IS_WINDOWS_X64_DEFAULT_MODE; } // namespace bool SystemUtil::IsWindowsX64() { switch (g_is_windows_x64_mode) { case IS_WINDOWS_X64_EMULATE_32BIT_MACHINE: return false; case IS_WINDOWS_X64_EMULATE_64BIT_MACHINE: return true; case IS_WINDOWS_X64_DEFAULT_MODE: // handled below. break; default: // Should never reach here. DLOG(FATAL) << "Unexpected mode specified. mode = " << g_is_windows_x64_mode; // handled below. break; } #ifdef OS_WIN SYSTEM_INFO system_info = {}; // This function never fails. ::GetNativeSystemInfo(&system_info); return (system_info.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_AMD64); #else return false; #endif // OS_WIN } void SystemUtil::SetIsWindowsX64ModeForTest(IsWindowsX64Mode mode) { g_is_windows_x64_mode = mode; switch (g_is_windows_x64_mode) { case IS_WINDOWS_X64_EMULATE_32BIT_MACHINE: case IS_WINDOWS_X64_EMULATE_64BIT_MACHINE: case IS_WINDOWS_X64_DEFAULT_MODE: // Known mode. OK. break; default: DLOG(FATAL) << "Unexpected mode specified. mode = " << g_is_windows_x64_mode; break; } } #ifdef OS_WIN const wchar_t *SystemUtil::GetSystemDir() { DCHECK(Singleton<SystemDirectoryCache>::get()->succeeded()); return Singleton<SystemDirectoryCache>::get()->system_dir(); } std::string SystemUtil::GetMSCTFAsmCacheReadyEventName() { const std::string &session_id = GetSessionIdString(); if (session_id.empty()) { DLOG(ERROR) << "Failed to retrieve session id"; return ""; } const std::string &desktop_name = GetInputDesktopName(); if (desktop_name.empty()) { DLOG(ERROR) << "Failed to retrieve desktop name"; return ""; } // Compose "Local\MSCTF.AsmCacheReady.<desktop name><session #>". return ("Local\\MSCTF.AsmCacheReady." + desktop_name + session_id); } #endif // OS_WIN // TODO(toshiyuki): move this to the initialization module and calculate // version only when initializing. std::string SystemUtil::GetOSVersionString() { #ifdef OS_WIN std::string ret = "Windows"; OSVERSIONINFOEX osvi = {0}; osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX); if (GetVersionEx(reinterpret_cast<OSVERSIONINFO *>(&osvi))) { ret += "."; ret += std::to_string(static_cast<uint32>(osvi.dwMajorVersion)); ret += "."; ret += std::to_string(static_cast<uint32>(osvi.dwMinorVersion)); ret += "." + std::to_string(osvi.wServicePackMajor); ret += "." + std::to_string(osvi.wServicePackMinor); } else { LOG(WARNING) << "GetVersionEx failed"; } return ret; #elif defined(__APPLE__) const std::string ret = "MacOSX " + MacUtil::GetOSVersionString(); // TODO(toshiyuki): get more specific info return ret; #elif defined(OS_LINUX) const std::string ret = "Linux"; return ret; #else // !OS_WIN && !__APPLE__ && !OS_LINUX const std::string ret = "Unknown"; return ret; #endif // OS_WIN, __APPLE__, OS_LINUX } void SystemUtil::DisableIME() { #ifdef OS_WIN // Note that ImmDisableTextFrameService API is no longer supported on // Windows Vista and later. // https://msdn.microsoft.com/en-us/library/windows/desktop/dd318537.aspx ::ImmDisableIME(-1); #endif // OS_WIN } uint64_t SystemUtil::GetTotalPhysicalMemory() { #if defined(OS_WIN) MEMORYSTATUSEX memory_status = {sizeof(MEMORYSTATUSEX)}; if (!::GlobalMemoryStatusEx(&memory_status)) { return 0; } return memory_status.ullTotalPhys; #endif // OS_WIN #if defined(__APPLE__) int mib[] = {CTL_HW, HW_MEMSIZE}; uint64 total_memory = 0; size_t size = sizeof(total_memory); const int error = sysctl(mib, arraysize(mib), &total_memory, &size, nullptr, 0); if (error == -1) { const int error = errno; LOG(ERROR) << "sysctl with hw.memsize failed. " << "errno: " << error; return 0; } return total_memory; #endif // __APPLE__ #if defined(OS_LINUX) || defined(OS_ANDROID) || defined(OS_WASM) #if defined(_SC_PAGESIZE) && defined(_SC_PHYS_PAGES) const int32_t page_size = sysconf(_SC_PAGESIZE); const int32_t number_of_phyisical_pages = sysconf(_SC_PHYS_PAGES); if (number_of_phyisical_pages < 0) { // likely to be overflowed. LOG(FATAL) << number_of_phyisical_pages << ", " << page_size; return 0; } return static_cast<uint64_t>(number_of_phyisical_pages) * page_size; #else // defined(_SC_PAGESIZE) && defined(_SC_PHYS_PAGES) return 0; #endif // defined(_SC_PAGESIZE) && defined(_SC_PHYS_PAGES) #endif // OS_LINUX || OS_ANDROID || OS_WASM // If none of the above platforms is specified, the compiler raises an error // because of no return value. } } // namespace mozc
// Copyright 2022 TIER IV, 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. #ifndef TIER4_AUTOWARE_UTILS__VEHICLE__VEHICLE_STATE_CHECKER_HPP_ #define TIER4_AUTOWARE_UTILS__VEHICLE__VEHICLE_STATE_CHECKER_HPP_ #include <rclcpp/rclcpp.hpp> #include <autoware_auto_planning_msgs/msg/trajectory.hpp> #include <geometry_msgs/msg/twist_stamped.hpp> #include <nav_msgs/msg/odometry.hpp> #include <deque> #include <memory> namespace tier4_autoware_utils { using autoware_auto_planning_msgs::msg::Trajectory; using geometry_msgs::msg::TwistStamped; using nav_msgs::msg::Odometry; class VehicleStopChecker { public: explicit VehicleStopChecker(rclcpp::Node * node); bool isVehicleStopped(const double stop_duration) const; rclcpp::Logger getLogger() { return logger_; } protected: rclcpp::Subscription<Odometry>::SharedPtr sub_odom_; rclcpp::Clock::SharedPtr clock_; rclcpp::Logger logger_; Odometry::SharedPtr odometry_ptr_; std::deque<TwistStamped> twist_buffer_; private: static constexpr double velocity_buffer_time_sec = 10.0; void onOdom(const Odometry::SharedPtr msg); }; class VehicleArrivalChecker : public VehicleStopChecker { public: explicit VehicleArrivalChecker(rclcpp::Node * node); bool isVehicleStoppedAtStopPoint(const double stop_duration) const; private: static constexpr double th_arrived_distance_m = 1.0; rclcpp::Subscription<Trajectory>::SharedPtr sub_trajectory_; Trajectory::SharedPtr trajectory_ptr_; void onTrajectory(const Trajectory::SharedPtr msg); }; } // namespace tier4_autoware_utils #endif // TIER4_AUTOWARE_UTILS__VEHICLE__VEHICLE_STATE_CHECKER_HPP_
// Author(s): Jan Friso Groote // Copyright: see the accompanying file COPYING or copy at // https://svn.win.tue.nl/trac/MCRL2/browser/trunk/COPYING // // 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) // /// \file mcrl22lps.cpp /// \brief This tool linearises mcrl2 specifications into linear /// form. #define TOOLNAME "mcrl22lps" #define AUTHOR "Jan Friso Groote" #include <fstream> #include <iostream> #include <string> #include "mcrl2/utilities/logger.h" #include "mcrl2/lps/io.h" #include "mcrl2/lps/linearise.h" #include "mcrl2/utilities/input_output_tool.h" #include "mcrl2/data/rewriter_tool.h" #include "mcrl2/process/parse.h" // #include "gc.h" Required for ad hoc garbage collection. This is possible with ATcollect, // useful to find garbage collection problems. using mcrl2::utilities::tools::input_output_tool; using mcrl2::data::tools::rewriter_tool; class mcrl22lps_tool : public rewriter_tool< input_output_tool > { typedef rewriter_tool< input_output_tool > super; private: mcrl2::lps::t_lin_options m_linearisation_options; bool noalpha; // indicates whether alpha reduction is needed. bool opt_check_only; protected: void add_options(mcrl2::utilities::interface_description& desc) { super::add_options(desc); desc.add_option("lin-method", mcrl2::utilities::make_enum_argument<mcrl2::lps::t_lin_method>("NAME"). add_value(mcrl2::lps::lmRegular, true). add_value(mcrl2::lps::lmRegular2). add_value(mcrl2::lps::lmStack), "use linearisation method NAME:" , 'l'); desc.add_option("cluster", "all actions in the final LPS are clustered. " "Clustering means that summands with the same action labels are " "grouped together. For instance, a(f1) . P(g1) + a(f2) . P(g2) " "is replaced by sum b: Bool . a(if(b, f1, f2)) . P(if(b, f2, g2)). " "The advantage is that the number of summands can be reduced " "subtantially in this way. The disadvantage is that sum operators " "are introduced and new data sorts with auxiliary functions are generated. " "In order to avoid the generation of new sorts, the option -b/--binary " "can be used.", 'c'); desc.add_option("no-cluster", "the actions in intermediate LPSs are not clustered before " "they are put in parallel. By default these processes are " "clustered to avoid a blow-up in the number of summands when " "transforming two parallel linear processes into a single linear " "process. If a linear process with M summands is put in parallel " "with a linear process with N summands the resulting process has " "M×N + M + N summands. Both M and N can be substantially reduced " "by clustering at the cost of introducing new sorts and functions. " "See -c/--cluster, esp. for a short explanation of the clustering " "process.", 'n'); desc.add_option("no-alpha", "alphabet reductions are not applied. " "By default mcrl22lps attempts to distribute communication, hiding " "and allow operators over the parallel composition operator as " "this reduces the size of intermediate linear processes. By using " "this option, this step can be avoided. The name stems from the " "alphabet axioms in process algebra.", 'z'); desc.add_option("newstate", "state variables are encoded using enumerated types instead " "of positive natural numbers (Pos). By using this option new " "finite sorts named Enumk are generated where k is the size of " "the domain. Also, auxiliary case functions and equalities are " "defined. In combination with the option --binary the finite " "sorts are encoded by booleans. " "(requires linearisation method 'regular' or 'regular2').", 'w'); desc.add_option("binary", "when clustering use binary case functions instead of " "n-ary; in the presence of -w/--newstate, state variables are " "encoded by a vector of boolean variables", 'b'); desc.add_option("statenames", "the name of the variable encoding the state of a parallel process has the shape \"si\", " "with i an optional number. Using this flag this name is \"Pi\", where P is the name" "of the process. This makes it " "easier to determine to which process the state variable belongs from.", 'a'); desc.add_option("no-rewrite", "do not rewrite data terms while linearising; useful when the rewrite " "system does not terminate. This option also switches off the application of " "constant elimination.", 'o'); desc.add_option("no-globvars", "instantiate don't care values with arbitrary constants, " "instead of modelling them by global variables. This has no effect" "on global variables that are declared in the specification.", 'f'); desc.add_option("no-sumelm", "avoid applying sum elimination in parallel composition", 'm'); desc.add_option("no-deltaelm", "avoid removing spurious delta summands. " "Due to the existence of time, delta summands cannot be omitted. " "Due to the presence of multi-actions the number of summands can " "be huge. The algorithm for removing delta summands simply works " "by comparing each delta summand with each other summand to see " "whether the condition of the one implies the condition of the " "other. Clearly, this has quadratic complexity, and can take a " "long time.", 'g'); desc.add_option("delta", "add a true->delta summands to each state in each process; " "these delta's subsume all other conditional timed delta's, " "effectively reducing the number of delta summands drastically " "in the resulting linear process; speeds up linearisation. This is the default, " "but it does not deal correctly with time.", 'D'); desc.add_option("timed", "Translate the process to linear form preserving all timed information. In parallel processes the number " "of possible time constraints can be large, slowing down linearisation. Confer the --delta option " "which yiels a much faster translation that does not preserve timing correctly", 'T'); desc.add_option("no-constelm", "do not try to apply constant elimination when generating a linear " "process."); desc.add_option("check-only", "check syntax and static semantics; do not linearise", 'e'); } void parse_options(const mcrl2::utilities::command_line_parser& parser) { super::parse_options(parser); opt_check_only = 0 < parser.options.count("check-only"); noalpha = 0 < parser.options.count("no-alpha"); m_linearisation_options.final_cluster = 0 < parser.options.count("cluster"); m_linearisation_options.no_intermediate_cluster = 0 < parser.options.count("no-cluster"); m_linearisation_options.newstate = 0 < parser.options.count("newstate"); m_linearisation_options.binary = 0 < parser.options.count("binary"); m_linearisation_options.statenames = 0 < parser.options.count("statenames"); m_linearisation_options.norewrite = 0 < parser.options.count("no-rewrite"); m_linearisation_options.noglobalvars = 0 < parser.options.count("no-globvars"); m_linearisation_options.nosumelm = 0 < parser.options.count("no-sumelm"); m_linearisation_options.nodeltaelimination = 0 < parser.options.count("no-deltaelm"); m_linearisation_options.add_delta = 0 == parser.options.count("timed"); m_linearisation_options.do_not_apply_constelm = 0 < parser.options.count("no-constelm") || 0 < parser.options.count("no-rewrite"); m_linearisation_options.lin_method = parser.option_argument_as< mcrl2::lps::t_lin_method >("lin-method"); //check for dangerous and illegal option combinations if (m_linearisation_options.newstate && m_linearisation_options.lin_method == mcrl2::lps::lmStack) { throw parser.error("option -w/--newstate cannot be used with -lstack/--lin-method=stack"); } m_linearisation_options.rewrite_strategy = rewrite_strategy(); } public: mcrl22lps_tool() : super( TOOLNAME, AUTHOR, "translate an mCRL2 specification to an LPS", "Linearises the mCRL2 specification in INFILE and writes the resulting LPS to " "OUTFILE. If OUTFILE is not present, stdout is used. If INFILE is not present, " "stdin is used."), noalpha(false), opt_check_only(false) {} bool run() { //linearise infilename with options mcrl2::process::process_specification spec; if (input_filename().empty()) { //parse specification from stdin mCRL2log(mcrl2::log::verbose) << "reading input from stdin..." << std::endl; spec = mcrl2::process::parse_process_specification(std::cin, !noalpha); } else { //parse specification from infilename mCRL2log(mcrl2::log::verbose) << "reading input from file '" << input_filename() << "'..." << std::endl; std::ifstream instream(input_filename().c_str(), std::ifstream::in|std::ifstream::binary); if (!instream.is_open()) { throw mcrl2::runtime_error("cannot open input file: " + input_filename()); } spec = mcrl2::process::parse_process_specification(instream, !noalpha); instream.close(); } //report on well-formedness (if needed) if (opt_check_only) { if (input_filename().empty()) { mCRL2log(mcrl2::log::info) << "stdin contains a well-formed mCRL2 specification" << std::endl; } else { mCRL2log(mcrl2::log::info) << "the file '" << input_filename() << "' contains a well-formed mCRL2 specification" << std::endl; } return true; } //store the result mcrl2::lps::stochastic_specification linear_spec(mcrl2::lps::linearise(spec, m_linearisation_options)); mCRL2log(mcrl2::log::verbose) << "writing LPS to " << (output_filename().empty() ? "stdout" : "file " + output_filename()) << "..." << std::endl; mcrl2::lps::save_lps(linear_spec, output_filename()); return true; } }; int main(int argc, char** argv) { return mcrl22lps_tool().execute(argc, argv); }
/** * @file Laplace_Demo.cpp * @brief Sample code showing how to detect edges using the Laplace operator * @author OpenCV team */ #include "opencv2/imgproc/imgproc.hpp" #include "opencv2/highgui/highgui.hpp" #include <stdlib.h> #include <stdio.h> using namespace cv; /** * @function main */ int main( int, char** argv ) { Mat src, src_gray, dst; int kernel_size = 3; int scale = 1; int delta = 0; int ddepth = CV_16S; const char* window_name = "Laplace Demo"; /// Load an image src = imread( argv[1] ); if( !src.data ) { return -1; } /// Remove noise by blurring with a Gaussian filter GaussianBlur( src, src, Size(3,3), 0, 0, BORDER_DEFAULT ); /// Convert the image to grayscale cvtColor( src, src_gray, COLOR_RGB2GRAY ); /// Create window namedWindow( window_name, WINDOW_AUTOSIZE ); /// Apply Laplace function Mat abs_dst; Laplacian( src_gray, dst, ddepth, kernel_size, scale, delta, BORDER_DEFAULT ); convertScaleAbs( dst, abs_dst ); /// Show what you got imshow( window_name, abs_dst ); waitKey(0); return 0; }
#pragma once // This file is generated from the Game's Reflection data #include <cstdint> #include <RED4ext/Common.hpp> #include <RED4ext/DynArray.hpp> #include <RED4ext/Handle.hpp> #include <RED4ext/NativeTypes.hpp> #include <RED4ext/Scripting/Natives/Generated/quest/EmbeddedGraphNodeDefinition.hpp> #include <RED4ext/Scripting/Natives/Generated/quest/QuestPrefabEntry.hpp> namespace RED4ext { namespace quest { struct GraphDefinition; } namespace quest { struct QuestPhaseResource; } namespace quest { struct PhaseNodeDefinition : quest::EmbeddedGraphNodeDefinition { static constexpr const char* NAME = "questPhaseNodeDefinition"; static constexpr const char* ALIAS = NAME; uint8_t unk48[0x60 - 0x48]; // 48 Handle<quest::GraphDefinition> phaseGraph; // 60 DynArray<quest::QuestPrefabEntry> phaseInstancePrefabs; // 70 NodeRef unfreezingTriggerNodeRef; // 80 RaRef<quest::QuestPhaseResource> phaseResource; // 88 bool saveLock; // 90 uint8_t unk91[0x98 - 0x91]; // 91 }; RED4EXT_ASSERT_SIZE(PhaseNodeDefinition, 0x98); } // namespace quest } // namespace RED4ext