text
stringlengths 5
1.04M
|
|---|
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/snow-device-management/model/DescribeExecutionResult.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <aws/core/AmazonWebServiceResult.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/UnreferencedParam.h>
#include <utility>
using namespace Aws::SnowDeviceManagement::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
using namespace Aws;
DescribeExecutionResult::DescribeExecutionResult() :
m_state(ExecutionState::NOT_SET)
{
}
DescribeExecutionResult::DescribeExecutionResult(const Aws::AmazonWebServiceResult<JsonValue>& result) :
m_state(ExecutionState::NOT_SET)
{
*this = result;
}
DescribeExecutionResult& DescribeExecutionResult::operator =(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
JsonView jsonValue = result.GetPayload().View();
if(jsonValue.ValueExists("executionId"))
{
m_executionId = jsonValue.GetString("executionId");
}
if(jsonValue.ValueExists("lastUpdatedAt"))
{
m_lastUpdatedAt = jsonValue.GetDouble("lastUpdatedAt");
}
if(jsonValue.ValueExists("managedDeviceId"))
{
m_managedDeviceId = jsonValue.GetString("managedDeviceId");
}
if(jsonValue.ValueExists("startedAt"))
{
m_startedAt = jsonValue.GetDouble("startedAt");
}
if(jsonValue.ValueExists("state"))
{
m_state = ExecutionStateMapper::GetExecutionStateForName(jsonValue.GetString("state"));
}
if(jsonValue.ValueExists("taskId"))
{
m_taskId = jsonValue.GetString("taskId");
}
return *this;
}
|
#include "torcontrol.h"
#include "utilstrencodings.h"
#include "net.h"
#include "util.h"
#include "crypto/hmac_sha256.h"
#include <vector>
#include <deque>
#include <set>
#include <stdlib.h>
#include <boost/function.hpp>
#include <boost/bind.hpp>
#include <boost/signals2/signal.hpp>
#include <boost/foreach.hpp>
#include <boost/algorithm/string/predicate.hpp>
#include <boost/algorithm/string/split.hpp>
#include <boost/algorithm/string/classification.hpp>
#include <boost/algorithm/string/replace.hpp>
#include <event2/bufferevent.h>
#include <event2/buffer.h>
#include <event2/util.h>
#include <event2/event.h>
#include <event2/thread.h>
/** Default control port */
const std::string DEFAULT_TOR_CONTROL = "127.0.0.1:9051";
/** Tor cookie size (from control-spec.txt) */
static const int TOR_COOKIE_SIZE = 32;
/** Size of client/server nonce for SAFECOOKIE */
static const int TOR_NONCE_SIZE = 32;
/** For computing serverHash in SAFECOOKIE */
static const std::string TOR_SAFE_SERVERKEY = "Tor safe cookie authentication server-to-controller hash";
/** For computing clientHash in SAFECOOKIE */
static const std::string TOR_SAFE_CLIENTKEY = "Tor safe cookie authentication controller-to-server hash";
/** Exponential backoff configuration - initial timeout in seconds */
static const float RECONNECT_TIMEOUT_START = 1.0;
/** Exponential backoff configuration - growth factor */
static const float RECONNECT_TIMEOUT_EXP = 1.5;
/** Maximum length for lines received on TorControlConnection.
* tor-control-spec.txt mentions that there is explicitly no limit defined to line length,
* this is belt-and-suspenders sanity limit to prevent memory exhaustion.
*/
static const int MAX_LINE_LENGTH = 100000;
/****** Low-level TorControlConnection ********/
/** Reply from Tor, can be single or multi-line */
class TorControlReply
{
public:
TorControlReply() { Clear(); }
int code;
std::vector<std::string> lines;
void Clear()
{
code = 0;
lines.clear();
}
};
/** Low-level handling for Tor control connection.
* Speaks the SMTP-like protocol as defined in torspec/control-spec.txt
*/
class TorControlConnection
{
public:
typedef boost::function<void(TorControlConnection&)> ConnectionCB;
typedef boost::function<void(TorControlConnection &,const TorControlReply &)> ReplyHandlerCB;
/** Create a new TorControlConnection.
*/
TorControlConnection(struct event_base *base);
~TorControlConnection();
/**
* Connect to a Tor control port.
* target is address of the form host:port.
* connected is the handler that is called when connection is succesfully established.
* disconnected is a handler that is called when the connection is broken.
* Return true on success.
*/
bool Connect(const std::string &target, const ConnectionCB& connected, const ConnectionCB& disconnected);
/**
* Disconnect from Tor control port.
*/
bool Disconnect();
/** Send a command, register a handler for the reply.
* A trailing CRLF is automatically added.
* Return true on success.
*/
bool Command(const std::string &cmd, const ReplyHandlerCB& reply_handler);
/** Response handlers for async replies */
boost::signals2::signal<void(TorControlConnection &,const TorControlReply &)> async_handler;
private:
/** Callback when ready for use */
boost::function<void(TorControlConnection&)> connected;
/** Callback when connection lost */
boost::function<void(TorControlConnection&)> disconnected;
/** Libevent event base */
struct event_base *base;
/** Connection to control socket */
struct bufferevent *b_conn;
/** Message being received */
TorControlReply message;
/** Response handlers */
std::deque<ReplyHandlerCB> reply_handlers;
/** Libevent handlers: internal */
static void readcb(struct bufferevent *bev, void *ctx);
static void eventcb(struct bufferevent *bev, short what, void *ctx);
};
TorControlConnection::TorControlConnection(struct event_base *base):
base(base), b_conn(0)
{
}
TorControlConnection::~TorControlConnection()
{
if (b_conn)
bufferevent_free(b_conn);
}
void TorControlConnection::readcb(struct bufferevent *bev, void *ctx)
{
TorControlConnection *self = (TorControlConnection*)ctx;
struct evbuffer *input = bufferevent_get_input(bev);
size_t n_read_out = 0;
char *line;
assert(input);
// If there is not a whole line to read, evbuffer_readln returns NULL
while((line = evbuffer_readln(input, &n_read_out, EVBUFFER_EOL_CRLF)) != NULL)
{
std::string s(line, n_read_out);
free(line);
if (s.size() < 4) // Short line
continue;
// <status>(-|+| )<data><CRLF>
self->message.code = atoi(s.substr(0,3));
self->message.lines.push_back(s.substr(4));
char ch = s[3]; // '-','+' or ' '
if (ch == ' ') {
// Final line, dispatch reply and clean up
if (self->message.code >= 600) {
// Dispatch async notifications to async handler
// Synchronous and asynchronous messages are never interleaved
self->async_handler(*self, self->message);
} else {
if (!self->reply_handlers.empty()) {
// Invoke reply handler with message
self->reply_handlers.front()(*self, self->message);
self->reply_handlers.pop_front();
} else {
LogPrint("tor", "tor: Received unexpected sync reply %i\n", self->message.code);
}
}
self->message.Clear();
}
}
// Check for size of buffer - protect against memory exhaustion with very long lines
// Do this after evbuffer_readln to make sure all full lines have been
// removed from the buffer. Everything left is an incomplete line.
if (evbuffer_get_length(input) > MAX_LINE_LENGTH) {
LogPrintf("tor: Disconnecting because MAX_LINE_LENGTH exceeded\n");
self->Disconnect();
}
}
void TorControlConnection::eventcb(struct bufferevent *bev, short what, void *ctx)
{
TorControlConnection *self = (TorControlConnection*)ctx;
if (what & BEV_EVENT_CONNECTED) {
LogPrint("tor", "tor: Succesfully connected!\n");
self->connected(*self);
} else if (what & (BEV_EVENT_EOF|BEV_EVENT_ERROR)) {
if (what & BEV_EVENT_ERROR)
LogPrint("tor", "tor: Error connecting to Tor control socket\n");
else
LogPrint("tor", "tor: End of stream\n");
self->Disconnect();
self->disconnected(*self);
}
}
bool TorControlConnection::Connect(const std::string &target, const ConnectionCB& connected, const ConnectionCB& disconnected)
{
if (b_conn)
Disconnect();
// Parse target address:port
struct sockaddr_storage connect_to_addr;
int connect_to_addrlen = sizeof(connect_to_addr);
if (evutil_parse_sockaddr_port(target.c_str(),
(struct sockaddr*)&connect_to_addr, &connect_to_addrlen)<0) {
LogPrintf("tor: Error parsing socket address %s\n", target);
return false;
}
// Create a new socket, set up callbacks and enable notification bits
b_conn = bufferevent_socket_new(base, -1, BEV_OPT_CLOSE_ON_FREE);
if (!b_conn)
return false;
bufferevent_setcb(b_conn, TorControlConnection::readcb, NULL, TorControlConnection::eventcb, this);
bufferevent_enable(b_conn, EV_READ|EV_WRITE);
this->connected = connected;
this->disconnected = disconnected;
// Finally, connect to target
if (bufferevent_socket_connect(b_conn, (struct sockaddr*)&connect_to_addr, connect_to_addrlen) < 0) {
LogPrintf("tor: Error connecting to address %s\n", target);
return false;
}
return true;
}
bool TorControlConnection::Disconnect()
{
if (b_conn)
bufferevent_free(b_conn);
b_conn = 0;
return true;
}
bool TorControlConnection::Command(const std::string &cmd, const ReplyHandlerCB& reply_handler)
{
if (!b_conn)
return false;
struct evbuffer *buf = bufferevent_get_output(b_conn);
if (!buf)
return false;
evbuffer_add(buf, cmd.data(), cmd.size());
evbuffer_add(buf, "\r\n", 2);
reply_handlers.push_back(reply_handler);
return true;
}
/****** General parsing utilities ********/
/* Split reply line in the form 'AUTH METHODS=...' into a type
* 'AUTH' and arguments 'METHODS=...'.
*/
static std::pair<std::string,std::string> SplitTorReplyLine(const std::string &s)
{
size_t ptr=0;
std::string type;
while (ptr < s.size() && s[ptr] != ' ') {
type.push_back(s[ptr]);
++ptr;
}
if (ptr < s.size())
++ptr; // skip ' '
return make_pair(type, s.substr(ptr));
}
/** Parse reply arguments in the form 'METHODS=COOKIE,SAFECOOKIE COOKIEFILE=".../control_auth_cookie"'.
*/
static std::map<std::string,std::string> ParseTorReplyMapping(const std::string &s)
{
std::map<std::string,std::string> mapping;
size_t ptr=0;
while (ptr < s.size()) {
std::string key, value;
while (ptr < s.size() && s[ptr] != '=') {
key.push_back(s[ptr]);
++ptr;
}
if (ptr == s.size()) // unexpected end of line
return std::map<std::string,std::string>();
++ptr; // skip '='
if (ptr < s.size() && s[ptr] == '"') { // Quoted string
++ptr; // skip '='
bool escape_next = false;
while (ptr < s.size() && (!escape_next && s[ptr] != '"')) {
escape_next = (s[ptr] == '\\');
value.push_back(s[ptr]);
++ptr;
}
if (ptr == s.size()) // unexpected end of line
return std::map<std::string,std::string>();
++ptr; // skip closing '"'
/* TODO: unescape value - according to the spec this depends on the
* context, some strings use C-LogPrintf style escape codes, some
* don't. So may be better handled at the call site.
*/
} else { // Unquoted value. Note that values can contain '=' at will, just no spaces
while (ptr < s.size() && s[ptr] != ' ') {
value.push_back(s[ptr]);
++ptr;
}
}
if (ptr < s.size() && s[ptr] == ' ')
++ptr; // skip ' ' after key=value
mapping[key] = value;
}
return mapping;
}
/** Read full contents of a file and return them in a std::string.
* Returns a pair <status, string>.
* If an error occured, status will be false, otherwise status will be true and the data will be returned in string.
*
* @param maxsize Puts a maximum size limit on the file that is read. If the file is larger than this, truncated data
* (with len > maxsize) will be returned.
*/
static std::pair<bool,std::string> ReadBinaryFile(const std::string &filename, size_t maxsize=std::numeric_limits<size_t>::max())
{
FILE *f = fopen(filename.c_str(), "rb");
if (f == NULL)
return std::make_pair(false,"");
std::string retval;
char buffer[128];
size_t n;
while ((n=fread(buffer, 1, sizeof(buffer), f)) > 0) {
retval.append(buffer, buffer+n);
if (retval.size() > maxsize)
break;
}
fclose(f);
return std::make_pair(true,retval);
}
/** Write contents of std::string to a file.
* @return true on success.
*/
static bool WriteBinaryFile(const std::string &filename, const std::string &data)
{
FILE *f = fopen(filename.c_str(), "wb");
if (f == NULL)
return false;
if (fwrite(data.data(), 1, data.size(), f) != data.size()) {
fclose(f);
return false;
}
fclose(f);
return true;
}
/****** Bitcoin specific TorController implementation ********/
/** Controller that connects to Tor control socket, authenticate, then create
* and maintain a ephemeral hidden service.
*/
class TorController
{
public:
TorController(struct event_base* base, const std::string& target);
~TorController();
/** Get name fo file to store private key in */
std::string GetPrivateKeyFile();
/** Reconnect, after getting disconnected */
void Reconnect();
private:
struct event_base* base;
std::string target;
TorControlConnection conn;
std::string private_key;
std::string service_id;
bool reconnect;
struct event *reconnect_ev;
float reconnect_timeout;
CService service;
/** Cooie for SAFECOOKIE auth */
std::vector<uint8_t> cookie;
/** ClientNonce for SAFECOOKIE auth */
std::vector<uint8_t> clientNonce;
/** Callback for ADD_ONION result */
void add_onion_cb(TorControlConnection& conn, const TorControlReply& reply);
/** Callback for AUTHENTICATE result */
void auth_cb(TorControlConnection& conn, const TorControlReply& reply);
/** Callback for AUTHCHALLENGE result */
void authchallenge_cb(TorControlConnection& conn, const TorControlReply& reply);
/** Callback for PROTOCOLINFO result */
void protocolinfo_cb(TorControlConnection& conn, const TorControlReply& reply);
/** Callback after succesful connection */
void connected_cb(TorControlConnection& conn);
/** Callback after connection lost or failed connection attempt */
void disconnected_cb(TorControlConnection& conn);
/** Callback for reconnect timer */
static void reconnect_cb(evutil_socket_t fd, short what, void *arg);
};
TorController::TorController(struct event_base* base, const std::string& target):
base(base),
target(target), conn(base), reconnect(true), reconnect_ev(0),
reconnect_timeout(RECONNECT_TIMEOUT_START)
{
// Start connection attempts immediately
if (!conn.Connect(target, boost::bind(&TorController::connected_cb, this, _1),
boost::bind(&TorController::disconnected_cb, this, _1) )) {
LogPrintf("tor: Initiating connection to Tor control port %s failed\n", target);
}
// Read service private key if cached
std::pair<bool,std::string> pkf = ReadBinaryFile(GetPrivateKeyFile());
if (pkf.first) {
LogPrint("tor", "tor: Reading cached private key from %s\n", GetPrivateKeyFile());
private_key = pkf.second;
}
}
TorController::~TorController()
{
if (reconnect_ev)
event_del(reconnect_ev);
if (service.IsValid()) {
RemoveLocal(service);
}
}
void TorController::add_onion_cb(TorControlConnection& conn, const TorControlReply& reply)
{
if (reply.code == 250) {
LogPrint("tor", "tor: ADD_ONION succesful\n");
BOOST_FOREACH(const std::string &s, reply.lines) {
std::map<std::string,std::string> m = ParseTorReplyMapping(s);
std::map<std::string,std::string>::iterator i;
if ((i = m.find("ServiceID")) != m.end())
service_id = i->second;
if ((i = m.find("PrivateKey")) != m.end())
private_key = i->second;
}
service = CService(service_id+".onion", GetListenPort(), false);
LogPrintf("tor: Got service ID %s, advertizing service %s\n", service_id, service.ToString());
if (WriteBinaryFile(GetPrivateKeyFile(), private_key)) {
LogPrint("tor", "tor: Cached service private key to %s\n", GetPrivateKeyFile());
} else {
LogPrintf("tor: Error writing service private key to %s\n", GetPrivateKeyFile());
}
AddLocal(service, LOCAL_MANUAL);
// ... onion requested - keep connection open
} else if (reply.code == 510) { // 510 Unrecognized command
LogPrintf("tor: Add onion failed with unrecognized command (You probably need to upgrade Tor)\n");
} else {
LogPrintf("tor: Add onion failed; error code %d\n", reply.code);
}
}
void TorController::auth_cb(TorControlConnection& conn, const TorControlReply& reply)
{
if (reply.code == 250) {
LogPrint("tor", "tor: Authentication succesful\n");
// Now that we know Tor is running setup the proxy for onion addresses
// if -onion isn't set to something else.
if (GetArg("-onion", "") == "") {
proxyType addrOnion = proxyType(CService("127.0.0.1", 9050), true);
SetProxy(NET_TOR, addrOnion);
SetReachable(NET_TOR);
}
// Finally - now create the service
if (private_key.empty()) // No private key, generate one
private_key = "NEW:BEST";
// Request hidden service, redirect port.
// Note that the 'virtual' port doesn't have to be the same as our internal port, but this is just a convenient
// choice. TODO; refactor the shutdown sequence some day.
conn.Command(strprintf("ADD_ONION %s Port=%i,127.0.0.1:%i", private_key, GetListenPort(), GetListenPort()),
boost::bind(&TorController::add_onion_cb, this, _1, _2));
} else {
LogPrintf("tor: Authentication failed\n");
}
}
/** Compute Tor SAFECOOKIE response.
*
* ServerHash is computed as:
* HMAC-SHA256("Tor safe cookie authentication server-to-controller hash",
* CookieString | ClientNonce | ServerNonce)
* (with the HMAC key as its first argument)
*
* After a controller sends a successful AUTHCHALLENGE command, the
* next command sent on the connection must be an AUTHENTICATE command,
* and the only authentication string which that AUTHENTICATE command
* will accept is:
*
* HMAC-SHA256("Tor safe cookie authentication controller-to-server hash",
* CookieString | ClientNonce | ServerNonce)
*
*/
static std::vector<uint8_t> ComputeResponse(const std::string &key, const std::vector<uint8_t> &cookie, const std::vector<uint8_t> &clientNonce, const std::vector<uint8_t> &serverNonce)
{
CHMAC_SHA256 computeHash((const uint8_t*)key.data(), key.size());
std::vector<uint8_t> computedHash(CHMAC_SHA256::OUTPUT_SIZE, 0);
computeHash.Write(begin_ptr(cookie), cookie.size());
computeHash.Write(begin_ptr(clientNonce), clientNonce.size());
computeHash.Write(begin_ptr(serverNonce), serverNonce.size());
computeHash.Finalize(begin_ptr(computedHash));
return computedHash;
}
void TorController::authchallenge_cb(TorControlConnection& conn, const TorControlReply& reply)
{
if (reply.code == 250) {
LogPrint("tor", "tor: SAFECOOKIE authentication challenge succesful\n");
std::pair<std::string,std::string> l = SplitTorReplyLine(reply.lines[0]);
if (l.first == "AUTHCHALLENGE") {
std::map<std::string,std::string> m = ParseTorReplyMapping(l.second);
std::vector<uint8_t> serverHash = ParseHex(m["SERVERHASH"]);
std::vector<uint8_t> serverNonce = ParseHex(m["SERVERNONCE"]);
LogPrint("tor", "tor: AUTHCHALLENGE ServerHash %s ServerNonce %s\n", HexStr(serverHash), HexStr(serverNonce));
if (serverNonce.size() != 32) {
LogPrintf("tor: ServerNonce is not 32 bytes, as required by spec\n");
return;
}
std::vector<uint8_t> computedServerHash = ComputeResponse(TOR_SAFE_SERVERKEY, cookie, clientNonce, serverNonce);
if (computedServerHash != serverHash) {
LogPrintf("tor: ServerHash %s does not match expected ServerHash %s\n", HexStr(serverHash), HexStr(computedServerHash));
return;
}
std::vector<uint8_t> computedClientHash = ComputeResponse(TOR_SAFE_CLIENTKEY, cookie, clientNonce, serverNonce);
conn.Command("AUTHENTICATE " + HexStr(computedClientHash), boost::bind(&TorController::auth_cb, this, _1, _2));
} else {
LogPrintf("tor: Invalid reply to AUTHCHALLENGE\n");
}
} else {
LogPrintf("tor: SAFECOOKIE authentication challenge failed\n");
}
}
void TorController::protocolinfo_cb(TorControlConnection& conn, const TorControlReply& reply)
{
if (reply.code == 250) {
std::set<std::string> methods;
std::string cookiefile;
/*
* 250-AUTH METHODS=COOKIE,SAFECOOKIE COOKIEFILE="/home/x/.tor/control_auth_cookie"
* 250-AUTH METHODS=NULL
* 250-AUTH METHODS=HASHEDPASSWORD
*/
BOOST_FOREACH(const std::string &s, reply.lines) {
std::pair<std::string,std::string> l = SplitTorReplyLine(s);
if (l.first == "AUTH") {
std::map<std::string,std::string> m = ParseTorReplyMapping(l.second);
std::map<std::string,std::string>::iterator i;
if ((i = m.find("METHODS")) != m.end())
boost::split(methods, i->second, boost::is_any_of(","));
if ((i = m.find("COOKIEFILE")) != m.end())
cookiefile = i->second;
} else if (l.first == "VERSION") {
std::map<std::string,std::string> m = ParseTorReplyMapping(l.second);
std::map<std::string,std::string>::iterator i;
if ((i = m.find("Tor")) != m.end()) {
LogPrint("tor", "tor: Connected to Tor version %s\n", i->second);
}
}
}
BOOST_FOREACH(const std::string &s, methods) {
LogPrint("tor", "tor: Supported authentication method: %s\n", s);
}
// Prefer NULL, otherwise SAFECOOKIE. If a password is provided, use HASHEDPASSWORD
/* Authentication:
* cookie: hex-encoded ~/.tor/control_auth_cookie
* password: "password"
*/
std::string torpassword = GetArg("-torpassword", "");
if (methods.count("NULL")) {
LogPrint("tor", "tor: Using NULL authentication\n");
conn.Command("AUTHENTICATE", boost::bind(&TorController::auth_cb, this, _1, _2));
} else if (methods.count("SAFECOOKIE")) {
// Cookie: hexdump -e '32/1 "%02x""\n"' ~/.tor/control_auth_cookie
LogPrint("tor", "tor: Using SAFECOOKIE authentication, reading cookie authentication from %s\n", cookiefile);
std::pair<bool,std::string> status_cookie = ReadBinaryFile(cookiefile, TOR_COOKIE_SIZE);
if (status_cookie.first && status_cookie.second.size() == TOR_COOKIE_SIZE) {
// conn.Command("AUTHENTICATE " + HexStr(status_cookie.second), boost::bind(&TorController::auth_cb, this, _1, _2));
cookie = std::vector<uint8_t>(status_cookie.second.begin(), status_cookie.second.end());
clientNonce = std::vector<uint8_t>(TOR_NONCE_SIZE, 0);
GetRandBytes(&clientNonce[0], TOR_NONCE_SIZE);
conn.Command("AUTHCHALLENGE SAFECOOKIE " + HexStr(clientNonce), boost::bind(&TorController::authchallenge_cb, this, _1, _2));
} else {
if (status_cookie.first) {
LogPrintf("tor: Authentication cookie %s is not exactly %i bytes, as is required by the spec\n", cookiefile, TOR_COOKIE_SIZE);
} else {
LogPrintf("tor: Authentication cookie %s could not be opened (check permissions)\n", cookiefile);
}
}
} else if (methods.count("HASHEDPASSWORD")) {
if (!torpassword.empty()) {
LogPrint("tor", "tor: Using HASHEDPASSWORD authentication\n");
boost::replace_all(torpassword, "\"", "\\\"");
conn.Command("AUTHENTICATE \"" + torpassword + "\"", boost::bind(&TorController::auth_cb, this, _1, _2));
} else {
LogPrintf("tor: Password authentication required, but no password provided with -torpassword\n");
}
} else {
LogPrintf("tor: No supported authentication method\n");
}
} else {
LogPrintf("tor: Requesting protocol info failed\n");
}
}
void TorController::connected_cb(TorControlConnection& conn)
{
reconnect_timeout = RECONNECT_TIMEOUT_START;
// First send a PROTOCOLINFO command to figure out what authentication is expected
if (!conn.Command("PROTOCOLINFO 1", boost::bind(&TorController::protocolinfo_cb, this, _1, _2)))
LogPrintf("tor: Error sending initial protocolinfo command\n");
}
void TorController::disconnected_cb(TorControlConnection& conn)
{
// Stop advertizing service when disconnected
if (service.IsValid())
RemoveLocal(service);
service = CService();
if (!reconnect)
return;
LogPrint("tor", "tor: Not connected to Tor control port %s, trying to reconnect\n", target);
// Single-shot timer for reconnect. Use exponential backoff.
struct timeval time = MillisToTimeval(int64_t(reconnect_timeout * 1000.0));
reconnect_ev = event_new(base, -1, 0, reconnect_cb, this);
event_add(reconnect_ev, &time);
reconnect_timeout *= RECONNECT_TIMEOUT_EXP;
}
void TorController::Reconnect()
{
/* Try to reconnect and reestablish if we get booted - for example, Tor
* may be restarting.
*/
if (!conn.Connect(target, boost::bind(&TorController::connected_cb, this, _1),
boost::bind(&TorController::disconnected_cb, this, _1) )) {
LogPrintf("tor: Re-initiating connection to Tor control port %s failed\n", target);
}
}
std::string TorController::GetPrivateKeyFile()
{
return (GetDataDir() / "onion_private_key").string();
}
void TorController::reconnect_cb(evutil_socket_t fd, short what, void *arg)
{
TorController *self = (TorController*)arg;
self->Reconnect();
}
/****** Thread ********/
struct event_base *base;
boost::thread torControlThread;
static void TorControlThread()
{
TorController ctrl(base, GetArg("-torcontrol", DEFAULT_TOR_CONTROL));
event_base_dispatch(base);
}
void StartTorControl(boost::thread_group& threadGroup, CScheduler& scheduler)
{
assert(!base);
#ifdef WIN32
evthread_use_windows_threads();
#else
evthread_use_pthreads();
#endif
base = event_base_new();
if (!base) {
LogPrintf("tor: Unable to create event_base\n");
return;
}
torControlThread = boost::thread(boost::bind(&TraceThread<void (*)()>, "torcontrol", &TorControlThread));
}
void InterruptTorControl()
{
if (base) {
LogPrintf("tor: Thread interrupt\n");
event_base_loopbreak(base);
}
}
void StopTorControl()
{
// timed_join() avoids the wallet not closing during a repair-restart. For a 'normal' wallet exit
// it behaves for our cases exactly like the normal join()
if (base) {
#if BOOST_VERSION >= 105000
torControlThread.try_join_for(boost::chrono::seconds(1));
#else
torControlThread.timed_join(boost::posix_time::seconds(1));
#endif
event_base_free(base);
base = 0;
}
}
|
// Copyright (c) 2017-2019, BITRUBCOIN, The Monero Project
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are
// permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice, this list
// of conditions and the following disclaimer in the documentation and/or other
// materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its contributors may be
// used to endorse or promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
// THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
// THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "include_base_utils.h"
#include "file_io_utils.h"
#include "net/http_client.h"
#include "fuzzer.h"
class dummy_client
{
public:
bool connect(const std::string& addr, int port, std::chrono::milliseconds timeout, bool ssl = false, const std::string& bind_ip = "0.0.0.0") { return true; }
bool connect(const std::string& addr, const std::string& port, std::chrono::milliseconds timeout, bool ssl = false, const std::string& bind_ip = "0.0.0.0") { return true; }
bool disconnect() { return true; }
bool send(const std::string& buff, std::chrono::milliseconds timeout) { return true; }
bool send(const void* data, size_t sz) { return true; }
bool is_connected() { return true; }
bool recv(std::string& buff, std::chrono::milliseconds timeout)
{
buff = data;
data.clear();
return true;
}
void set_test_data(const std::string &s) { data = s; }
private:
std::string data;
};
class HTTPClientFuzzer: public Fuzzer
{
public:
HTTPClientFuzzer() {}
virtual int init();
virtual int run(const std::string &filename);
private:
epee::net_utils::http::http_simple_client_template<dummy_client> client;
};
int HTTPClientFuzzer::init()
{
return 0;
}
int HTTPClientFuzzer::run(const std::string &filename)
{
std::string s;
if (!epee::file_io_utils::load_file_to_string(filename, s))
{
std::cout << "Error: failed to load file " << filename << std::endl;
return 1;
}
try
{
client.test(s, std::chrono::milliseconds(1000));
}
catch (const std::exception &e)
{
std::cerr << "Failed to test http client: " << e.what() << std::endl;
return 1;
}
return 0;
}
int main(int argc, const char **argv)
{
TRY_ENTRY();
HTTPClientFuzzer fuzzer;
return run_fuzzer(argc, argv, fuzzer);
CATCH_ENTRY_L0("main", 1);
}
|
/**
* Copyright 2021-2022 Huawei Technologies Co., Ltd
*
* 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 "plugin/device/cpu/kernel/transpose_cpu_kernel.h"
#include <vector>
#include "plugin/device/cpu/hal/device/cpu_device_address.h"
#include "common/thread_pool.h"
#include "nnacl/fp32/transpose_fp32.h"
#include "nnacl/int8/transpose_int8.h"
namespace mindspore {
namespace kernel {
namespace {
constexpr size_t kTransposeInputsNum = 1;
constexpr size_t kTransposeOutputsNum = 1;
// kMaxTransposeSerialSize = 64 * 3 * 512 * 512
constexpr size_t kMaxTransposeSerialSize = 50331648;
} // namespace
void TransposeFwdCpuKernelMod::InitKernel(const CNodePtr &kernel_node) {
MS_EXCEPTION_IF_NULL(kernel_node);
kernel_name_ = AnfAlgo::GetCNodeName(kernel_node);
input_shape_ = AnfAlgo::GetInputDeviceShape(kernel_node, 0);
output_shape_ = AnfAlgo::GetOutputDeviceShape(kernel_node, 0);
auto tmp = AnfAlgo::GetNodeAttr<std::vector<int64_t>>(kernel_node, "perm");
axes_ = {tmp.begin(), tmp.end()};
dtype_ = AnfAlgo::GetInputDeviceDataType(kernel_node, 0);
if (axes_.size() > MAX_TRANSPOSE_DIM_SIZE) {
MS_LOG(EXCEPTION) << "For '" << kernel_name_ << "', the max dimension of input is " << MAX_TRANSPOSE_DIM_SIZE
<< "D, but got " << axes_.size() << "D.";
}
for (size_t i = 0; i < axes_.size(); ++i) {
transpose_param_.perm_[i] = SizeToInt(axes_[i]);
}
int num_axes = SizeToInt(input_shape_.size());
transpose_param_.perm_size_ = axes_.size();
transpose_param_.num_axes_ = num_axes;
transpose_param_.strides_[num_axes - 1] = 1;
transpose_param_.out_strides_[num_axes - 1] = 1;
for (int i = num_axes - 2; i >= 0; i--) {
transpose_param_.strides_[i] = SizeToInt(input_shape_[i + 1]) * transpose_param_.strides_[i + 1];
transpose_param_.out_strides_[i] = SizeToInt(output_shape_[i + 1]) * transpose_param_.out_strides_[i + 1];
}
launch_map_[kNumberTypeInt8] = &TransposeFwdCpuKernelMod::LaunchKernel<int8_t>;
launch_map_[kNumberTypeInt16] = &TransposeFwdCpuKernelMod::LaunchKernel<int16_t>;
launch_map_[kNumberTypeInt32] = &TransposeFwdCpuKernelMod::LaunchKernel<int>;
launch_map_[kNumberTypeInt64] = &TransposeFwdCpuKernelMod::LaunchKernel<int64_t>;
launch_map_[kNumberTypeUInt8] = &TransposeFwdCpuKernelMod::LaunchKernel<uint8_t>;
launch_map_[kNumberTypeUInt16] = &TransposeFwdCpuKernelMod::LaunchKernel<uint16_t>;
launch_map_[kNumberTypeUInt32] = &TransposeFwdCpuKernelMod::LaunchKernel<uint32_t>;
launch_map_[kNumberTypeUInt64] = &TransposeFwdCpuKernelMod::LaunchKernel<uint64_t>;
launch_map_[kNumberTypeFloat32] = &TransposeFwdCpuKernelMod::LaunchKernel<float>;
launch_map_[kNumberTypeFloat64] = &TransposeFwdCpuKernelMod::LaunchKernel<double>;
launch_map_[kNumberTypeBool] = &TransposeFwdCpuKernelMod::LaunchKernel<bool>;
auto iter = launch_map_.find(dtype_);
if (iter != launch_map_.end()) {
launch_func_ = iter->second;
} else {
MS_LOG(EXCEPTION) << "For '" << kernel_name_ << "', the dtype of input should be bool, int, float or uint, but got "
<< TypeIdToType(dtype_)->ToString();
}
}
bool TransposeFwdCpuKernelMod::Launch(const std::vector<kernel::AddressPtr> &inputs,
const std::vector<kernel::AddressPtr> &,
const std::vector<kernel::AddressPtr> &outputs) {
launch_func_(this, inputs, outputs);
return true;
}
template <typename T>
void TransposeFwdCpuKernelMod::LaunchKernel(const std::vector<AddressPtr> &inputs,
const std::vector<AddressPtr> &outputs) {
const auto *input_addr = reinterpret_cast<T *>(inputs[0]->addr);
auto *output_addr = reinterpret_cast<T *>(outputs[0]->addr);
transpose_param_.data_num_ = SizeToInt(inputs[0]->size / sizeof(T));
int output_shape[SizeToInt(output_shape_.size())];
for (size_t i = 0; i < output_shape_.size(); ++i) {
output_shape[i] = SizeToInt(output_shape_[i]);
}
size_t data_count = (inputs[0]->size) / sizeof(T);
if (axes_.size() > DIMENSION_6D || data_count >= kMaxTransposeSerialSize) {
ParallelRun(input_addr, output_addr, output_shape, data_count);
return;
}
int res = static_cast<int>(NNACL_OK);
if constexpr (std::is_same_v<T, int8_t>) {
res = DoTransposeInt8(input_addr, output_addr, output_shape, &transpose_param_);
} else if constexpr (std::is_same_v<T, int16_t>) {
res = DoTransposeInt16(input_addr, output_addr, output_shape, &transpose_param_);
} else if constexpr (std::is_same_v<T, int32_t>) {
res = DoTransposeInt32(input_addr, output_addr, output_shape, &transpose_param_);
} else if constexpr (std::is_same_v<T, int64_t>) {
res = DoTransposeInt64(input_addr, output_addr, output_shape, &transpose_param_);
} else if constexpr (std::is_same_v<T, uint8_t>) {
res = DoTransposeUInt8(input_addr, output_addr, output_shape, &transpose_param_);
} else if constexpr (std::is_same_v<T, uint16_t>) {
res = DoTransposeUInt16(input_addr, output_addr, output_shape, &transpose_param_);
} else if constexpr (std::is_same_v<T, uint32_t>) {
res = DoTransposeUInt32(input_addr, output_addr, output_shape, &transpose_param_);
} else if constexpr (std::is_same_v<T, uint64_t>) {
res = DoTransposeUInt64(input_addr, output_addr, output_shape, &transpose_param_);
} else if constexpr (std::is_same_v<T, float>) {
res = DoTransposeFp32(input_addr, output_addr, output_shape, &transpose_param_);
} else if constexpr (std::is_same_v<T, double>) {
res = DoTransposeFloat64(input_addr, output_addr, output_shape, &transpose_param_);
} else if constexpr (std::is_same_v<T, bool>) {
res = DoTransposeBool(input_addr, output_addr, output_shape, &transpose_param_);
} else {
MS_LOG(EXCEPTION) << "For '" << kernel_name_ << "', the dtype of input should be bool, int, float or uint, but got "
<< typeid(T).name();
}
if (res != static_cast<int>(NNACL_OK)) {
MS_LOG(EXCEPTION) << "For '" << kernel_name_ << "', run failed, error no: " << res;
}
}
template <typename T>
void TransposeFwdCpuKernelMod::ParallelRun(const T *input_addr, T *output_addr, const int *output_shape, size_t count) {
std::function<void(const T *, T *, const int *, TransposeParameter *, int, int)> TransposeDims;
if constexpr (std::is_same_v<T, int8_t>) {
TransposeDims = &TransposeDimsInt8;
} else if constexpr (std::is_same_v<T, int16_t>) {
TransposeDims = &TransposeDimsInt16;
} else if constexpr (std::is_same_v<T, int32_t>) {
TransposeDims = &TransposeDimsInt32;
} else if constexpr (std::is_same_v<T, int64_t>) {
TransposeDims = &TransposeDimsInt64;
} else if constexpr (std::is_same_v<T, uint8_t>) {
TransposeDims = &TransposeDimsUInt8;
} else if constexpr (std::is_same_v<T, uint16_t>) {
TransposeDims = &TransposeDimsUInt16;
} else if constexpr (std::is_same_v<T, uint32_t>) {
TransposeDims = &TransposeDimsUInt32;
} else if constexpr (std::is_same_v<T, uint64_t>) {
TransposeDims = &TransposeDimsUInt64;
} else if constexpr (std::is_same_v<T, float>) {
TransposeDims = &TransposeDimsFp32;
} else if constexpr (std::is_same_v<T, double>) {
TransposeDims = &TransposeDimsFloat64;
} else if constexpr (std::is_same_v<T, bool>) {
TransposeDims = &TransposeDimsBool;
}
auto thread_pool = GetActorMgrInnerThreadPool();
size_t thread_num = thread_pool->GetKernelThreadNum();
auto task = [this, &TransposeDims, input_addr, output_addr, output_shape, thread_num](size_t start, size_t end) {
for (size_t idx = start; idx < end; idx++) {
TransposeDims(input_addr, output_addr, output_shape, &transpose_param_, SizeToInt(idx), SizeToInt(thread_num));
}
};
ParallelLaunchAutoSearch(task, thread_num, this, ¶llel_search_info_);
}
} // namespace kernel
} // namespace mindspore
|
/*------------------------------------------------------------------------
* Vulkan Conformance Tests
* ------------------------
*
* Copyright (c) 2016 The Khronos Group 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.
*
*//*!
* \file vktSparseResourcesBufferSparseBinding.cpp
* \brief Buffer Sparse Binding tests
*//*--------------------------------------------------------------------*/
#include "vktSparseResourcesBufferSparseBinding.hpp"
#include "vktSparseResourcesTestsUtil.hpp"
#include "vktSparseResourcesBase.hpp"
#include "vktTestCaseUtil.hpp"
#include "vkDefs.hpp"
#include "vkRef.hpp"
#include "vkRefUtil.hpp"
#include "vkPlatform.hpp"
#include "vkPrograms.hpp"
#include "vkMemUtil.hpp"
#include "vkBuilderUtil.hpp"
#include "vkImageUtil.hpp"
#include "vkQueryUtil.hpp"
#include "vkTypeUtil.hpp"
#include "deUniquePtr.hpp"
#include "deStringUtil.hpp"
#include <string>
#include <vector>
using namespace vk;
namespace vkt
{
namespace sparse
{
namespace
{
class BufferSparseBindingCase : public TestCase
{
public:
BufferSparseBindingCase (tcu::TestContext& testCtx,
const std::string& name,
const std::string& description,
const deUint32 bufferSize);
TestInstance* createInstance (Context& context) const;
private:
const deUint32 m_bufferSize;
};
BufferSparseBindingCase::BufferSparseBindingCase (tcu::TestContext& testCtx,
const std::string& name,
const std::string& description,
const deUint32 bufferSize)
: TestCase (testCtx, name, description)
, m_bufferSize (bufferSize)
{
}
class BufferSparseBindingInstance : public SparseResourcesBaseInstance
{
public:
BufferSparseBindingInstance (Context& context,
const deUint32 bufferSize);
tcu::TestStatus iterate (void);
private:
const deUint32 m_bufferSize;
};
BufferSparseBindingInstance::BufferSparseBindingInstance (Context& context,
const deUint32 bufferSize)
: SparseResourcesBaseInstance (context)
, m_bufferSize (bufferSize)
{
}
tcu::TestStatus BufferSparseBindingInstance::iterate (void)
{
const InstanceInterface& instance = m_context.getInstanceInterface();
const DeviceInterface& deviceInterface = m_context.getDeviceInterface();
const VkPhysicalDevice physicalDevice = m_context.getPhysicalDevice();
VkPhysicalDeviceFeatures deviceFeatures;
instance.getPhysicalDeviceFeatures(physicalDevice, &deviceFeatures);
if (deviceFeatures.sparseBinding == false)
{
return tcu::TestStatus(QP_TEST_RESULT_NOT_SUPPORTED, "Sparse binding not supported");
}
VkPhysicalDeviceProperties deviceProperties;
instance.getPhysicalDeviceProperties(physicalDevice, &deviceProperties);
QueueRequirementsVec queueRequirements;
queueRequirements.push_back(QueueRequirements(VK_QUEUE_SPARSE_BINDING_BIT, 1u));
queueRequirements.push_back(QueueRequirements(VK_QUEUE_COMPUTE_BIT, 1u));
// Create logical device supporting both sparse and transfer queues
if (!createDeviceSupportingQueues(queueRequirements))
{
return tcu::TestStatus(QP_TEST_RESULT_FAIL, "Could not create device supporting sparse and compute queue");
}
const VkPhysicalDeviceMemoryProperties deviceMemoryProperties = getPhysicalDeviceMemoryProperties(instance, physicalDevice);
// Create memory allocator for logical device
const de::UniquePtr<Allocator> allocator(new SimpleAllocator(deviceInterface, *m_logicalDevice, deviceMemoryProperties));
// Create queue supporting sparse binding operations
const Queue& sparseQueue = getQueue(VK_QUEUE_SPARSE_BINDING_BIT, 0);
// Create queue supporting compute and transfer operations
const Queue& computeQueue = getQueue(VK_QUEUE_COMPUTE_BIT, 0);
VkBufferCreateInfo bufferCreateInfo;
bufferCreateInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; // VkStructureType sType;
bufferCreateInfo.pNext = DE_NULL; // const void* pNext;
bufferCreateInfo.flags = VK_BUFFER_CREATE_SPARSE_BINDING_BIT; // VkBufferCreateFlags flags;
bufferCreateInfo.size = m_bufferSize; // VkDeviceSize size;
bufferCreateInfo.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT |
VK_BUFFER_USAGE_TRANSFER_DST_BIT; // VkBufferUsageFlags usage;
bufferCreateInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE; // VkSharingMode sharingMode;
bufferCreateInfo.queueFamilyIndexCount = 0u; // deUint32 queueFamilyIndexCount;
bufferCreateInfo.pQueueFamilyIndices = DE_NULL; // const deUint32* pQueueFamilyIndices;
const deUint32 queueFamilyIndices[] = { sparseQueue.queueFamilyIndex, computeQueue.queueFamilyIndex };
if (sparseQueue.queueFamilyIndex != computeQueue.queueFamilyIndex)
{
bufferCreateInfo.sharingMode = VK_SHARING_MODE_CONCURRENT; // VkSharingMode sharingMode;
bufferCreateInfo.queueFamilyIndexCount = 2u; // deUint32 queueFamilyIndexCount;
bufferCreateInfo.pQueueFamilyIndices = queueFamilyIndices; // const deUint32* pQueueFamilyIndices;
}
// Create sparse buffer
const Unique<VkBuffer> sparseBuffer(createBuffer(deviceInterface, *m_logicalDevice, &bufferCreateInfo));
const VkMemoryRequirements bufferMemRequirement = getBufferMemoryRequirements(deviceInterface, *m_logicalDevice, *sparseBuffer);
if (bufferMemRequirement.size > deviceProperties.limits.sparseAddressSpaceSize)
{
return tcu::TestStatus(QP_TEST_RESULT_NOT_SUPPORTED, "Required memory size for sparse resources exceeds device limits");
}
DE_ASSERT((bufferMemRequirement.size % bufferMemRequirement.alignment) == 0);
const deUint32 numSparseBinds = static_cast<deUint32>(bufferMemRequirement.size / bufferMemRequirement.alignment);
typedef de::SharedPtr< Unique<VkDeviceMemory> > DeviceMemoryUniquePtr;
std::vector<VkSparseMemoryBind> sparseMemoryBinds;
std::vector<DeviceMemoryUniquePtr> deviceMemUniquePtrVec;
const deUint32 memoryType = findMatchingMemoryType(deviceMemoryProperties, bufferMemRequirement, MemoryRequirement::Any);
if (memoryType == NO_MATCH_FOUND)
{
return tcu::TestStatus(QP_TEST_RESULT_FAIL, "No matching memory type found");
}
for (deUint32 sparseBindNdx = 0; sparseBindNdx < numSparseBinds; ++sparseBindNdx)
{
const VkMemoryAllocateInfo allocInfo =
{
VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, // VkStructureType sType;
DE_NULL, // const void* pNext;
bufferMemRequirement.alignment, // VkDeviceSize allocationSize;
memoryType, // deUint32 memoryTypeIndex;
};
VkDeviceMemory deviceMemory = 0;
VK_CHECK(deviceInterface.allocateMemory(*m_logicalDevice, &allocInfo, DE_NULL, &deviceMemory));
deviceMemUniquePtrVec.push_back(makeVkSharedPtr(Move<VkDeviceMemory>(check<VkDeviceMemory>(deviceMemory), Deleter<VkDeviceMemory>(deviceInterface, *m_logicalDevice, DE_NULL))));
const VkSparseMemoryBind sparseMemoryBind = makeSparseMemoryBind
(
bufferMemRequirement.alignment * sparseBindNdx, //VkDeviceSize resourceOffset
bufferMemRequirement.alignment, //VkDeviceSize size
deviceMemory, //VkDeviceMemory memory
0u, //VkDeviceSize memoryOffset
0u //VkSparseMemoryBindFlags flags
);
sparseMemoryBinds.push_back(sparseMemoryBind);
}
const VkSparseBufferMemoryBindInfo sparseBufferBindInfo = makeSparseBufferMemoryBindInfo
(
*sparseBuffer, //VkBuffer buffer;
numSparseBinds, //deUint32 bindCount;
&sparseMemoryBinds[0] //const VkSparseMemoryBind* Binds;
);
const Unique<VkSemaphore> bufferMemoryBindSemaphore(makeSemaphore(deviceInterface, *m_logicalDevice));
const VkBindSparseInfo bindSparseInfo =
{
VK_STRUCTURE_TYPE_BIND_SPARSE_INFO, //VkStructureType sType;
DE_NULL, //const void* pNext;
0u, //deUint32 waitSemaphoreCount;
DE_NULL, //const VkSemaphore* pWaitSemaphores;
1u, //deUint32 bufferBindCount;
&sparseBufferBindInfo, //const VkSparseBufferMemoryBindInfo* pBufferBinds;
0u, //deUint32 imageOpaqueBindCount;
DE_NULL, //const VkSparseImageOpaqueMemoryBindInfo* pImageOpaqueBinds;
0u, //deUint32 imageBindCount;
DE_NULL, //const VkSparseImageMemoryBindInfo* pImageBinds;
1u, //deUint32 signalSemaphoreCount;
&bufferMemoryBindSemaphore.get() //const VkSemaphore* pSignalSemaphores;
};
// Submit sparse bind commands for execution
VK_CHECK(deviceInterface.queueBindSparse(sparseQueue.queueHandle, 1u, &bindSparseInfo, DE_NULL));
// Create command buffer for transfer oparations
const Unique<VkCommandPool> commandPool(makeCommandPool(deviceInterface, *m_logicalDevice, computeQueue.queueFamilyIndex));
const Unique<VkCommandBuffer> commandBuffer(makeCommandBuffer(deviceInterface, *m_logicalDevice, *commandPool));
// Start recording transfer commands
beginCommandBuffer(deviceInterface, *commandBuffer);
const VkBufferCreateInfo inputBufferCreateInfo = makeBufferCreateInfo(m_bufferSize, VK_BUFFER_USAGE_TRANSFER_SRC_BIT);
const de::UniquePtr<Buffer> inputBuffer(new Buffer(deviceInterface, *m_logicalDevice, *allocator, inputBufferCreateInfo, MemoryRequirement::HostVisible));
std::vector<deUint8> referenceData;
referenceData.resize(m_bufferSize);
for (deUint32 valueNdx = 0; valueNdx < m_bufferSize; ++valueNdx)
{
referenceData[valueNdx] = static_cast<deUint8>((valueNdx % bufferMemRequirement.alignment) + 1u);
}
deMemcpy(inputBuffer->getAllocation().getHostPtr(), &referenceData[0], m_bufferSize);
flushMappedMemoryRange(deviceInterface, *m_logicalDevice, inputBuffer->getAllocation().getMemory(), inputBuffer->getAllocation().getOffset(), m_bufferSize);
const VkBufferMemoryBarrier inputBufferBarrier
= makeBufferMemoryBarrier( VK_ACCESS_HOST_WRITE_BIT,
VK_ACCESS_TRANSFER_READ_BIT,
inputBuffer->get(),
0u,
m_bufferSize);
deviceInterface.cmdPipelineBarrier(*commandBuffer, VK_PIPELINE_STAGE_HOST_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0u, 0u, DE_NULL, 1u, &inputBufferBarrier, 0u, DE_NULL);
const VkBufferCopy bufferCopy = makeBufferCopy(0u, 0u, m_bufferSize);
deviceInterface.cmdCopyBuffer(*commandBuffer, inputBuffer->get(), *sparseBuffer, 1u, &bufferCopy);
const VkBufferMemoryBarrier sparseBufferBarrier
= makeBufferMemoryBarrier( VK_ACCESS_TRANSFER_WRITE_BIT,
VK_ACCESS_TRANSFER_READ_BIT,
*sparseBuffer,
0u,
m_bufferSize);
deviceInterface.cmdPipelineBarrier(*commandBuffer, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0u, 0u, DE_NULL, 1u, &sparseBufferBarrier, 0u, DE_NULL);
const VkBufferCreateInfo outputBufferCreateInfo = makeBufferCreateInfo(m_bufferSize, VK_BUFFER_USAGE_TRANSFER_DST_BIT);
const de::UniquePtr<Buffer> outputBuffer(new Buffer(deviceInterface, *m_logicalDevice, *allocator, outputBufferCreateInfo, MemoryRequirement::HostVisible));
deviceInterface.cmdCopyBuffer(*commandBuffer, *sparseBuffer, outputBuffer->get(), 1u, &bufferCopy);
const VkBufferMemoryBarrier outputBufferBarrier
= makeBufferMemoryBarrier( VK_ACCESS_TRANSFER_WRITE_BIT,
VK_ACCESS_HOST_READ_BIT,
outputBuffer->get(),
0u,
m_bufferSize);
deviceInterface.cmdPipelineBarrier(*commandBuffer, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_HOST_BIT, 0u, 0u, DE_NULL, 1u, &outputBufferBarrier, 0u, DE_NULL);
// End recording transfer commands
endCommandBuffer(deviceInterface, *commandBuffer);
const VkPipelineStageFlags waitStageBits[] = { VK_PIPELINE_STAGE_TRANSFER_BIT };
// Submit transfer commands for execution and wait for completion
submitCommandsAndWait(deviceInterface, *m_logicalDevice, computeQueue.queueHandle, *commandBuffer, 1u, &bufferMemoryBindSemaphore.get(), waitStageBits);
// Retrieve data from output buffer to host memory
const Allocation& allocation = outputBuffer->getAllocation();
invalidateMappedMemoryRange(deviceInterface, *m_logicalDevice, allocation.getMemory(), allocation.getOffset(), m_bufferSize);
const deUint8* outputData = static_cast<const deUint8*>(allocation.getHostPtr());
tcu::TestStatus testStatus = tcu::TestStatus::incomplete();
// Compare output data with reference data
if (deMemCmp(&referenceData[0], outputData, m_bufferSize) == 0)
testStatus = tcu::TestStatus::pass("Passed");
else
testStatus = tcu::TestStatus::fail("Failed");
// Wait for sparse queue to become idle
deviceInterface.queueWaitIdle(sparseQueue.queueHandle);
return testStatus;
}
TestInstance* BufferSparseBindingCase::createInstance (Context& context) const
{
return new BufferSparseBindingInstance(context, m_bufferSize);
}
} // anonymous ns
tcu::TestCaseGroup* createBufferSparseBindingTests (tcu::TestContext& testCtx)
{
de::MovePtr<tcu::TestCaseGroup> testGroup(new tcu::TestCaseGroup(testCtx, "buffer_sparse_binding", "Buffer Sparse Binding"));
testGroup->addChild(new BufferSparseBindingCase(testCtx, "buffer_size_2_10", "", 1 << 10));
testGroup->addChild(new BufferSparseBindingCase(testCtx, "buffer_size_2_12", "", 1 << 12));
testGroup->addChild(new BufferSparseBindingCase(testCtx, "buffer_size_2_16", "", 1 << 16));
testGroup->addChild(new BufferSparseBindingCase(testCtx, "buffer_size_2_17", "", 1 << 17));
testGroup->addChild(new BufferSparseBindingCase(testCtx, "buffer_size_2_20", "", 1 << 20));
testGroup->addChild(new BufferSparseBindingCase(testCtx, "buffer_size_2_24", "", 1 << 24));
return testGroup.release();
}
} // sparse
} // vkt
|
/*
* dynamic_priority_queue.hpp
*
* Created on: Sep 04, 2018 12:10
* Description:
* A dynamic array (std::vector) is used to contain elements of the queue.
* Position 0 of the vector is not used for convenience of indexing:
*
* "For any element in array position i, the left child is in position 2i, the
* right child is in the cell after the left child (2i + 1), and the parent is
* in position i/2."
*
* Reference:
* [1] Data Structures & Algorithm Analysis in C++, 4th edition. Mark A. Weiss.
* Published by Pearson (2013).
* [2] https://github.com/csbence/DynamicPriorityQueue
*
* Copyright (c) 2018 Ruixiang Du (rdu)
*/
#ifndef DYNAMIC_PRIORITY_QUEUE_HPP
#define DYNAMIC_PRIORITY_QUEUE_HPP
#include <list>
#include <vector>
#include <unordered_map>
#include <algorithm>
#include "graph/details/default_indexer.hpp"
namespace rdu {
/// A priority queue implementation that supports element priority update.
template <typename T, typename Comparator = std::less<T>,
typename ItemIndexer = DefaultIndexer<T>>
class DynamicPriorityQueue {
public:
/// Construct a queue with initial capacity
DynamicPriorityQueue(std::size_t initial_capacity = 100) {
array_.resize(initial_capacity);
}
/// Construct a queue with given elements
DynamicPriorityQueue(const std::vector<T>& elements) {
array_.resize(elements.size() * 2);
for (std::size_t i = 0; i < elements.size(); ++i)
array_[i + 1] = elements[i];
element_num_ = elements.size();
for (int i = element_num_ / 2; i > 0; --i) PercolateDown(i);
}
/// Push new element to queue, update value if element already exists
void Push(const T& element) {
// determine if resizing is necessary
if (element_num_ == array_.size() - 1) array_.resize(array_.size() * 2);
// check whether element is already in queue
if (!Contains(element)) {
PercolateUp(element, ++element_num_);
} else {
Update(element);
}
}
/// Peek min/max element without removing it.
/// Assumption: default constructed T is assumed to be invalid
T Peek() const {
if (Empty()) return T();
return array_[1];
}
/// Get min/max element and remove it from queue.
/// Assumption: default constructed T is assumed to be invalid
T Pop() {
if (Empty()) return T();
auto min = std::move(array_[1]);
DeleteMin();
return min;
}
/// Update value of an existing element in queue, do nothing if the element
/// not exists already
void Update(const T& element) {
// do nothing if element is not in queue
auto index_entry = element_map_.find(GetItemIndex(element));
if (index_entry == element_map_.end()) return;
auto index = index_entry->second;
if (Compare(element, array_[index])) {
array_[index] = element;
PercolateUp(element, index);
} else {
array_[index] = element;
PercolateDown(index);
}
}
/// Empty all elements in queue
void Clear() {
element_num_ = 0;
array_.clear();
element_map_.clear();
}
/// Check whether the queue is empty
bool Empty() const { return (element_num_ == 0); }
/// Get number of elements in the queue
std::size_t GetQueueElementNumber() const { return element_num_; }
/// Check whether an element is in the queue
bool Contains(const T& element) const {
return element_map_.find(GetItemIndex(element)) != element_map_.end();
}
/// Print queue (for debugging)
void PrintQueue() {
for (std::size_t i = 1; i < element_num_ + 1; ++i) {
std::cout << array_[i] << " ";
}
std::cout << std::endl;
}
private:
std::size_t element_num_ = 0;
std::vector<T> array_;
std::unordered_map<int64_t, std::size_t> element_map_;
ItemIndexer GetItemIndex;
Comparator Compare;
void DeleteMin() {
if (Empty()) return;
array_[1] = std::move(array_[element_num_--]);
PercolateDown(1);
}
void PercolateUp(const T& element, std::size_t index) {
T new_element = element;
// copy new element to position 0, avoid comparing with non-existing element
array_[0] = std::move(new_element);
// keep floating up until heap-order property is satisfied
for (; Compare(element, array_[index / 2]); index /= 2) {
array_[index] = std::move(array_[index / 2]);
}
// insert new element
array_[index] = std::move(new_element);
element_map_[GetItemIndex(element)] = index;
}
void PercolateDown(std::size_t index) {
std::size_t child;
T tmp = array_[index];
// keep sinking down until heap-order property is satisfied
for (; index * 2 <= element_num_; index = child) {
child = index * 2;
// check which child is smaller (if right child exists)
if (child != element_num_ && Compare(array_[child + 1], array_[child]))
++child;
// float child up if desired (according to Compare())
if (Compare(array_[child], tmp))
array_[index] = std::move(array_[child]);
else
break;
}
// place element at the new location
array_[index] = std::move(tmp);
}
};
} // namespace rdu
#endif /* DYNAMIC_PRIORITY_QUEUE_HPP */
|
/* +---------------------------------------------------------------------------+
| Mobile Robot Programming Toolkit (MRPT) |
| http://www.mrpt.org/ |
| |
| Copyright (c) 2005-2017, Individual contributors, see AUTHORS file |
| See: http://www.mrpt.org/Authors - All rights reserved. |
| Released under BSD License. See details in http://www.mrpt.org/License |
+---------------------------------------------------------------------------+ */
#include "vision-precomp.h" // Precompiled headers
#include <mrpt/vision/CDifodo.h>
#include <mrpt/utils/utils_defs.h>
#include <mrpt/utils/CTicTac.h>
#include <mrpt/utils/round.h>
using namespace mrpt;
using namespace mrpt::vision;
using namespace mrpt::math;
using namespace std;
using namespace Eigen;
using mrpt::utils::round;
using mrpt::utils::square;
CDifodo::CDifodo()
{
rows = 60;
cols = 80;
fovh = M_PIf*58.6f/180.0f;
fovv = M_PIf*45.6f/180.0f;
cam_mode = 1; // (1 - 640 x 480, 2 - 320 x 240, 4 - 160 x 120)
downsample = 1;
ctf_levels = 1;
width = 640/(cam_mode*downsample);
height = 480/(cam_mode*downsample);
fast_pyramid = true;
//Resize pyramid
const unsigned int pyr_levels = round(log(float(width/cols))/log(2.f)) + ctf_levels;
depth.resize(pyr_levels);
depth_old.resize(pyr_levels);
depth_inter.resize(pyr_levels);
depth_warped.resize(pyr_levels);
xx.resize(pyr_levels);
xx_inter.resize(pyr_levels);
xx_old.resize(pyr_levels);
xx_warped.resize(pyr_levels);
yy.resize(pyr_levels);
yy_inter.resize(pyr_levels);
yy_old.resize(pyr_levels);
yy_warped.resize(pyr_levels);
transformations.resize(pyr_levels);
for (unsigned int i = 0; i<pyr_levels; i++)
{
unsigned int s = pow(2.f,int(i));
cols_i = width/s; rows_i = height/s;
depth[i].resize(rows_i, cols_i);
depth_inter[i].resize(rows_i, cols_i);
depth_old[i].resize(rows_i, cols_i);
depth[i].assign(0.0f);
depth_old[i].assign(0.0f);
xx[i].resize(rows_i, cols_i);
xx_inter[i].resize(rows_i, cols_i);
xx_old[i].resize(rows_i, cols_i);
xx[i].assign(0.0f);
xx_old[i].assign(0.0f);
yy[i].resize(rows_i, cols_i);
yy_inter[i].resize(rows_i, cols_i);
yy_old[i].resize(rows_i, cols_i);
yy[i].assign(0.0f);
yy_old[i].assign(0.0f);
transformations[i].resize(4,4);
if (cols_i <= cols)
{
depth_warped[i].resize(rows_i,cols_i);
xx_warped[i].resize(rows_i,cols_i);
yy_warped[i].resize(rows_i,cols_i);
}
}
depth_wf.setSize(height,width);
fps = 30.f; //In Hz
previous_speed_const_weight = 0.05f;
previous_speed_eig_weight = 0.5f;
kai_loc_old.assign(0.f);
num_valid_points = 0;
//Compute gaussian mask
VectorXf v_mask(4);
v_mask(0) = 1.f; v_mask(1) = 2.f; v_mask(2) = 2.f; v_mask(3) = 1.f;
for (unsigned int i = 0; i<4; i++)
for (unsigned int j = 0; j<4; j++)
f_mask(i,j) = v_mask(i)*v_mask(j)/36.f;
//Compute gaussian mask
float v_mask2[5] = {1,4,6,4,1};
for (unsigned int i = 0; i<5; i++)
for (unsigned int j = 0; j<5; j++)
g_mask[i][j] = v_mask2[i]*v_mask2[j]/256.f;
}
void CDifodo::buildCoordinatesPyramid()
{
const float max_depth_dif = 0.1f;
//Push coordinates back
depth_old.swap(depth);
xx_old.swap(xx);
yy_old.swap(yy);
//The number of levels of the pyramid does not match the number of levels used
//in the odometry computation (because we might want to finish with lower resolutions)
unsigned int pyr_levels = round(log(float(width/cols))/log(2.f)) + ctf_levels;
//Generate levels
for (unsigned int i = 0; i<pyr_levels; i++)
{
unsigned int s = pow(2.f,int(i));
cols_i = width/s;
rows_i = height/s;
const int rows_i2 = 2*rows_i;
const int cols_i2 = 2*cols_i;
const int i_1 = i-1;
if (i == 0)
depth[i].swap(depth_wf);
// Downsampling
//-----------------------------------------------------------------------------
else
{
for (unsigned int u = 0; u < cols_i; u++)
for (unsigned int v = 0; v < rows_i; v++)
{
const int u2 = 2*u;
const int v2 = 2*v;
const float dcenter = depth[i_1](v2,u2);
//Inner pixels
if ((v>0)&&(v<rows_i-1)&&(u>0)&&(u<cols_i-1))
{
if (dcenter > 0.f)
{
float sum = 0.f;
float weight = 0.f;
for (int l = -2; l<3; l++)
for (int k = -2; k<3; k++)
{
const float abs_dif = abs(depth[i_1](v2+k,u2+l)-dcenter);
if (abs_dif < max_depth_dif)
{
const float aux_w = g_mask[2+k][2+l]*(max_depth_dif - abs_dif);
weight += aux_w;
sum += aux_w*depth[i_1](v2+k,u2+l);
}
}
depth[i](v,u) = sum/weight;
}
else
{
float min_depth = 10.f;
for (int l = -2; l<3; l++)
for (int k = -2; k<3; k++)
{
const float d = depth[i_1](v2+k,u2+l);
if ((d > 0.f)&&(d < min_depth))
min_depth = d;
}
if (min_depth < 10.f)
depth[i](v,u) = min_depth;
else
depth[i](v,u) = 0.f;
}
}
//Boundary
else
{
if (dcenter > 0.f)
{
float sum = 0.f;
float weight = 0.f;
for (int l = -2; l<3; l++)
for (int k = -2; k<3; k++)
{
const int indv = v2+k,indu = u2+l;
if ((indv>=0)&&(indv<rows_i2)&&(indu>=0)&&(indu<cols_i2))
{
const float abs_dif = abs(depth[i_1](indv,indu)-dcenter);
if (abs_dif < max_depth_dif)
{
const float aux_w = g_mask[2+k][2+l]*(max_depth_dif - abs_dif);
weight += aux_w;
sum += aux_w*depth[i_1](indv,indu);
}
}
}
depth[i](v,u) = sum/weight;
}
else
{
float min_depth = 10.f;
for (int l = -2; l<3; l++)
for (int k = -2; k<3; k++)
{
const int indv = v2+k,indu = u2+l;
if ((indv>=0)&&(indv<rows_i2)&&(indu>=0)&&(indu<cols_i2))
{
const float d = depth[i_1](indv,indu);
if ((d > 0.f)&&(d < min_depth))
min_depth = d;
}
}
if (min_depth < 10.f)
depth[i](v,u) = min_depth;
else
depth[i](v,u) = 0.f;
}
}
}
}
//Calculate coordinates "xy" of the points
const float inv_f_i = 2.f*tan(0.5f*fovh)/float(cols_i);
const float disp_u_i = 0.5f*(cols_i-1);
const float disp_v_i = 0.5f*(rows_i-1);
for (unsigned int u = 0; u < cols_i; u++)
for (unsigned int v = 0; v < rows_i; v++)
if (depth[i](v,u) > 0.f)
{
xx[i](v,u) = (u - disp_u_i)*depth[i](v,u)*inv_f_i;
yy[i](v,u) = (v - disp_v_i)*depth[i](v,u)*inv_f_i;
}
else
{
xx[i](v,u) = 0.f;
yy[i](v,u) = 0.f;
}
}
}
void CDifodo::buildCoordinatesPyramidFast()
{
const float max_depth_dif = 0.1f;
//Push coordinates back
depth_old.swap(depth);
xx_old.swap(xx);
yy_old.swap(yy);
//The number of levels of the pyramid does not match the number of levels used
//in the odometry computation (because we might want to finish with lower resolutions)
unsigned int pyr_levels = round(log(float(width/cols))/log(2.f)) + ctf_levels;
//Generate levels
for (unsigned int i = 0; i<pyr_levels; i++)
{
unsigned int s = pow(2.f,int(i));
cols_i = width/s;
rows_i = height/s;
//const int rows_i2 = 2*rows_i;
//const int cols_i2 = 2*cols_i;
const int i_1 = i-1;
if (i == 0)
depth[i].swap(depth_wf);
// Downsampling
//-----------------------------------------------------------------------------
else
{
for (unsigned int u = 0; u < cols_i; u++)
for (unsigned int v = 0; v < rows_i; v++)
{
const int u2 = 2*u;
const int v2 = 2*v;
//Inner pixels
if ((v>0)&&(v<rows_i-1)&&(u>0)&&(u<cols_i-1))
{
const Matrix4f d_block = depth[i_1].block<4,4>(v2-1,u2-1);
float depths[4] = {d_block(5),d_block(6),d_block(9),d_block(10)};
float dcenter;
//Sort the array (try to find a good/representative value)
for (signed char k = 2; k>=0; k--)
if (depths[k+1] < depths[k])
std::swap(depths[k+1],depths[k]);
for (unsigned char k = 1; k<3; k++)
if (depths[k] > depths[k+1])
std::swap(depths[k+1],depths[k]);
if (depths[2] < depths[1])
dcenter = depths[1];
else
dcenter = depths[2];
if (dcenter > 0.f)
{
float sum = 0.f;
float weight = 0.f;
for (unsigned char k = 0; k<16; k++)
{
const float abs_dif = abs(d_block(k) - dcenter);
if (abs_dif < max_depth_dif)
{
const float aux_w = f_mask(k)*(max_depth_dif - abs_dif);
weight += aux_w;
sum += aux_w*d_block(k);
}
}
depth[i](v,u) = sum/weight;
}
else
depth[i](v,u) = 0.f;
}
//Boundary
else
{
const Matrix2f d_block = depth[i_1].block<2,2>(v2,u2);
const float new_d = 0.25f*d_block.sumAll();
if (new_d < 0.4f)
depth[i](v,u) = 0.f;
else
depth[i](v,u) = new_d;
}
}
}
//Calculate coordinates "xy" of the points
const float inv_f_i = 2.f*tan(0.5f*fovh)/float(cols_i);
const float disp_u_i = 0.5f*(cols_i-1);
const float disp_v_i = 0.5f*(rows_i-1);
for (unsigned int u = 0; u < cols_i; u++)
for (unsigned int v = 0; v < rows_i; v++)
if (depth[i](v,u) > 0.f)
{
xx[i](v,u) = (u - disp_u_i)*depth[i](v,u)*inv_f_i;
yy[i](v,u) = (v - disp_v_i)*depth[i](v,u)*inv_f_i;
}
else
{
xx[i](v,u) = 0.f;
yy[i](v,u) = 0.f;
}
}
}
void CDifodo::performWarping()
{
//Camera parameters (which also depend on the level resolution)
const float f = float(cols_i)/(2.f*tan(0.5f*fovh));
const float disp_u_i = 0.5f*float(cols_i-1);
const float disp_v_i = 0.5f*float(rows_i-1);
//Rigid transformation estimated up to the present level
Matrix4f acu_trans;
acu_trans.setIdentity();
for (unsigned int i=1; i<=level; i++)
acu_trans = transformations[i-1]*acu_trans;
MatrixXf wacu(rows_i,cols_i);
wacu.assign(0.f);
depth_warped[image_level].assign(0.f);
const float cols_lim = float(cols_i-1);
const float rows_lim = float(rows_i-1);
// Warping loop
//---------------------------------------------------------
for (unsigned int j = 0; j<cols_i; j++)
for (unsigned int i = 0; i<rows_i; i++)
{
const float z = depth[image_level](i,j);
if (z > 0.f)
{
//Transform point to the warped reference frame
const float depth_w = acu_trans(0,0)*z + acu_trans(0,1)*xx[image_level](i,j) + acu_trans(0,2)*yy[image_level](i,j) + acu_trans(0,3);
const float x_w = acu_trans(1,0)*z + acu_trans(1,1)*xx[image_level](i,j) + acu_trans(1,2)*yy[image_level](i,j) + acu_trans(1,3);
const float y_w = acu_trans(2,0)*z + acu_trans(2,1)*xx[image_level](i,j) + acu_trans(2,2)*yy[image_level](i,j) + acu_trans(2,3);
//Calculate warping
const float uwarp = f*x_w/depth_w + disp_u_i;
const float vwarp = f*y_w/depth_w + disp_v_i;
//The warped pixel (which is not integer in general) contributes to all the surrounding ones
if (( uwarp >= 0.f)&&( uwarp < cols_lim)&&( vwarp >= 0.f)&&( vwarp < rows_lim))
{
const int uwarp_l = uwarp;
const int uwarp_r = uwarp_l + 1;
const int vwarp_d = vwarp;
const int vwarp_u = vwarp_d + 1;
const float delta_r = float(uwarp_r) - uwarp;
const float delta_l = uwarp - float(uwarp_l);
const float delta_u = float(vwarp_u) - vwarp;
const float delta_d = vwarp - float(vwarp_d);
//Warped pixel very close to an integer value
if (abs(round(uwarp) - uwarp) + abs(round(vwarp) - vwarp) < 0.05f)
{
depth_warped[image_level](round(vwarp), round(uwarp)) += depth_w;
wacu(round(vwarp), round(uwarp)) += 1.f;
}
else
{
const float w_ur = square(delta_l) + square(delta_d);
depth_warped[image_level](vwarp_u,uwarp_r) += w_ur*depth_w;
wacu(vwarp_u,uwarp_r) += w_ur;
const float w_ul = square(delta_r) + square(delta_d);
depth_warped[image_level](vwarp_u,uwarp_l) += w_ul*depth_w;
wacu(vwarp_u,uwarp_l) += w_ul;
const float w_dr = square(delta_l) + square(delta_u);
depth_warped[image_level](vwarp_d,uwarp_r) += w_dr*depth_w;
wacu(vwarp_d,uwarp_r) += w_dr;
const float w_dl = square(delta_r) + square(delta_u);
depth_warped[image_level](vwarp_d,uwarp_l) += w_dl*depth_w;
wacu(vwarp_d,uwarp_l) += w_dl;
}
}
}
}
//Scale the averaged depth and compute spatial coordinates
const float inv_f_i = 1.f/f;
for (unsigned int u = 0; u<cols_i; u++)
for (unsigned int v = 0; v<rows_i; v++)
{
if (wacu(v,u) > 0.f)
{
depth_warped[image_level](v,u) /= wacu(v,u);
xx_warped[image_level](v,u) = (u - disp_u_i)*depth_warped[image_level](v,u)*inv_f_i;
yy_warped[image_level](v,u) = (v - disp_v_i)*depth_warped[image_level](v,u)*inv_f_i;
}
else
{
depth_warped[image_level](v,u) = 0.f;
xx_warped[image_level](v,u) = 0.f;
yy_warped[image_level](v,u) = 0.f;
}
}
}
void CDifodo::calculateCoord()
{
null.resize(rows_i, cols_i);
null.assign(false);
num_valid_points = 0;
for (unsigned int u = 0; u < cols_i; u++)
for (unsigned int v = 0; v < rows_i; v++)
{
if ((depth_old[image_level](v,u)) == 0.f || (depth_warped[image_level](v,u) == 0.f))
{
depth_inter[image_level](v,u) = 0.f;
xx_inter[image_level](v,u) = 0.f;
yy_inter[image_level](v,u) = 0.f;
null(v, u) = true;
}
else
{
depth_inter[image_level](v,u) = 0.5f*(depth_old[image_level](v,u) + depth_warped[image_level](v,u));
xx_inter[image_level](v,u) = 0.5f*(xx_old[image_level](v,u) + xx_warped[image_level](v,u));
yy_inter[image_level](v,u) = 0.5f*(yy_old[image_level](v,u) + yy_warped[image_level](v,u));
null(v, u) = false;
if ((u>0)&&(v>0)&&(u<cols_i-1)&&(v<rows_i-1))
num_valid_points++;
}
}
}
void CDifodo::calculateDepthDerivatives()
{
dt.resize(rows_i,cols_i); dt.assign(0.f);
du.resize(rows_i,cols_i); du.assign(0.f);
dv.resize(rows_i,cols_i); dv.assign(0.f);
//Compute connectivity
MatrixXf rx_ninv(rows_i,cols_i);
MatrixXf ry_ninv(rows_i,cols_i);
rx_ninv.assign(1.f); ry_ninv.assign(1.f);
for (unsigned int u = 0; u < cols_i-1; u++)
for (unsigned int v = 0; v < rows_i; v++)
if (null(v,u) == false)
{
rx_ninv(v,u) = sqrtf(square(xx_inter[image_level](v,u+1) - xx_inter[image_level](v,u))
+ square(depth_inter[image_level](v,u+1) - depth_inter[image_level](v,u)));
}
for (unsigned int u = 0; u < cols_i; u++)
for (unsigned int v = 0; v < rows_i-1; v++)
if (null(v,u) == false)
{
ry_ninv(v,u) = sqrtf(square(yy_inter[image_level](v+1,u) - yy_inter[image_level](v,u))
+ square(depth_inter[image_level](v+1,u) - depth_inter[image_level](v,u)));
}
//Spatial derivatives
for (unsigned int v = 0; v < rows_i; v++)
{
for (unsigned int u = 1; u < cols_i-1; u++)
if (null(v,u) == false)
du(v,u) = (rx_ninv(v,u-1)*(depth_inter[image_level](v,u+1)-depth_inter[image_level](v,u)) + rx_ninv(v,u)*(depth_inter[image_level](v,u) - depth_inter[image_level](v,u-1)))/(rx_ninv(v,u)+rx_ninv(v,u-1));
du(v,0) = du(v,1);
du(v,cols_i-1) = du(v,cols_i-2);
}
for (unsigned int u = 0; u < cols_i; u++)
{
for (unsigned int v = 1; v < rows_i-1; v++)
if (null(v,u) == false)
dv(v,u) = (ry_ninv(v-1,u)*(depth_inter[image_level](v+1,u)-depth_inter[image_level](v,u)) + ry_ninv(v,u)*(depth_inter[image_level](v,u) - depth_inter[image_level](v-1,u)))/(ry_ninv(v,u)+ry_ninv(v-1,u));
dv(0,u) = dv(1,u);
dv(rows_i-1,u) = dv(rows_i-2,u);
}
//Temporal derivative
for (unsigned int u = 0; u < cols_i; u++)
for (unsigned int v = 0; v < rows_i; v++)
if (null(v,u) == false)
dt(v,u) = fps*(depth_warped[image_level](v,u) - depth_old[image_level](v,u));
}
void CDifodo::computeWeights()
{
weights.resize(rows_i, cols_i);
weights.assign(0.f);
//Obtain the velocity associated to the rigid transformation estimated up to the present level
Matrix<float,6,1> kai_level = kai_loc_old;
Matrix4f acu_trans;
acu_trans.setIdentity();
for (unsigned int i=0; i<level; i++)
acu_trans = transformations[i]*acu_trans;
//Alternative way to compute the log
CMatrixDouble44 mat_aux = acu_trans.cast<double>();
poses::CPose3D aux(mat_aux);
CArrayDouble<6> kai_level_acu = aux.ln()*fps;
kai_level -= kai_level_acu.cast<float>();
//Parameters for the measurement error
const float f_inv = float(cols_i)/(2.f*tan(0.5f*fovh));
const float kz2 = 8.122e-12f; //square(1.425e-5) / 25
//Parameters for linearization error
const float kduv = 20e-5f;
const float kdt = kduv/square(fps);
const float k2dt = 5e-6f;
const float k2duv = 5e-6f;
for (unsigned int u = 1; u < cols_i-1; u++)
for (unsigned int v = 1; v < rows_i-1; v++)
if (null(v,u) == false)
{
// Compute measurment error (simplified)
//-----------------------------------------------------------------------
const float z = depth_inter[image_level](v,u);
const float inv_d = 1.f/z;
//const float dycomp = du2(v,u)*f_inv_y*inv_d;
//const float dzcomp = dv2(v,u)*f_inv_z*inv_d;
const float z2 = z*z;
const float z4 = z2*z2;
//const float var11 = kz2*z4;
//const float var12 = kz2*xx_inter[image_level](v,u)*z2*depth_inter[image_level](v,u);
//const float var13 = kz2*yy_inter[image_level](v,u)*z2*depth_inter[image_level](v,u);
//const float var22 = kz2*square(xx_inter[image_level](v,u))*z2;
//const float var23 = kz2*xx_inter[image_level](v,u)*yy_inter[image_level](v,u)*z2;
//const float var33 = kz2*square(yy_inter[image_level](v,u))*z2;
const float var44 = kz2*z4*square(fps);
const float var55 = kz2*z4*0.25f;
const float var66 = var55;
//const float j1 = -2.f*inv_d*inv_d*(xx_inter[image_level](v,u)*dycomp + yy_inter[image_level](v,u)*dzcomp)*(kai_level[0] + yy_inter[image_level](v,u)*kai_level[4] - xx_inter[image_level](v,u)*kai_level[5])
// + inv_d*dycomp*(kai_level[1] - yy_inter[image_level](v,u)*kai_level[3]) + inv_d*dzcomp*(kai_level[2] + xx_inter[image_level](v,u)*kai_level[3]);
//const float j2 = inv_d*dycomp*(kai_level[0] + yy_inter[image_level](v,u)*kai_level[4] - 2.f*xx_inter[image_level](v,u)*kai_level[5]) - dzcomp*kai_level[3];
//const float j3 = inv_d*dzcomp*(kai_level[0] + 2.f*yy_inter[image_level](v,u)*kai_level[4] - xx_inter[image_level](v,u)*kai_level[5]) + dycomp*kai_level[3];
const float j4 = 1.f;
const float j5 = xx_inter[image_level](v,u)*inv_d*inv_d*f_inv*(kai_level[0] + yy_inter[image_level](v,u)*kai_level[4] - xx_inter[image_level](v,u)*kai_level[5])
+ inv_d*f_inv*(-kai_level[1] - z*kai_level[5] + yy_inter[image_level](v,u)*kai_level[3]);
const float j6 = yy_inter[image_level](v,u)*inv_d*inv_d*f_inv*(kai_level[0] + yy_inter[image_level](v,u)*kai_level[4] - xx_inter[image_level](v,u)*kai_level[5])
+ inv_d*f_inv*(-kai_level[2] + z*kai_level[4] - xx_inter[image_level](v,u)*kai_level[3]);
//error_measurement(v,u) = j1*(j1*var11+j2*var12+j3*var13) + j2*(j1*var12+j2*var22+j3*var23)
// +j3*(j1*var13+j2*var23+j3*var33) + j4*j4*var44 + j5*j5*var55 + j6*j6*var66;
const float error_m = j4*j4*var44 + j5*j5*var55 + j6*j6*var66;
// Compute linearization error
//-----------------------------------------------------------------------
const float ini_du = depth_old[image_level](v,u+1) - depth_old[image_level](v,u-1);
const float ini_dv = depth_old[image_level](v+1,u) - depth_old[image_level](v-1,u);
const float final_du = depth_warped[image_level](v,u+1) - depth_warped[image_level](v,u-1);
const float final_dv = depth_warped[image_level](v+1,u) - depth_warped[image_level](v-1,u);
const float dut = ini_du - final_du;
const float dvt = ini_dv - final_dv;
const float duu = du(v,u+1) - du(v,u-1);
const float dvv = dv(v+1,u) - dv(v-1,u);
const float dvu = dv(v,u+1) - dv(v,u-1); //Completely equivalent to compute duv
const float error_l = kdt*square(dt(v,u)) + kduv*(square(du(v,u)) + square(dv(v,u))) + k2dt*(square(dut) + square(dvt))
+ k2duv*(square(duu) + square(dvv) + square(dvu));
//Weight
weights(v,u) = sqrt(1.f/(error_m + error_l));
}
//Normalize weights in the range [0,1]
const float inv_max = 1.f/weights.maximum();
weights = inv_max*weights;
}
void CDifodo::solveOneLevel()
{
MatrixXf A(num_valid_points,6);
MatrixXf B(num_valid_points,1);
unsigned int cont = 0;
//Fill the matrix A and the vector B
//The order of the unknowns is (vz, vx, vy, wz, wx, wy)
//The points order will be (1,1), (1,2)...(1,cols-1), (2,1), (2,2)...(row-1,cols-1).
const float f_inv = float(cols_i)/(2.f*tan(0.5f*fovh));
for (unsigned int u = 1; u < cols_i-1; u++)
for (unsigned int v = 1; v < rows_i-1; v++)
if (null(v,u) == false)
{
// Precomputed expressions
const float d = depth_inter[image_level](v,u);
const float inv_d = 1.f/d;
const float x = xx_inter[image_level](v,u);
const float y = yy_inter[image_level](v,u);
const float dycomp = du(v,u)*f_inv*inv_d;
const float dzcomp = dv(v,u)*f_inv*inv_d;
const float tw = weights(v,u);
//Fill the matrix A
A(cont, 0) = tw*(1.f + dycomp*x*inv_d + dzcomp*y*inv_d);
A(cont, 1) = tw*(-dycomp);
A(cont, 2) = tw*(-dzcomp);
A(cont, 3) = tw*(dycomp*y - dzcomp*x);
A(cont, 4) = tw*(y + dycomp*inv_d*y*x + dzcomp*(y*y*inv_d + d));
A(cont, 5) = tw*(-x - dycomp*(x*x*inv_d + d) - dzcomp*inv_d*y*x);
B(cont,0) = tw*(-dt(v,u));
cont++;
}
//Solve the linear system of equations using weighted least squares
MatrixXf AtA, AtB;
AtA.multiply_AtA(A);
AtB.multiply_AtB(A,B);
MatrixXf Var = AtA.ldlt().solve(AtB);
//Covariance matrix calculation
MatrixXf res = -B;
for (unsigned int k = 0; k<6; k++)
res += Var(k)*A.col(k);
est_cov = (1.f/float(num_valid_points-6))*AtA.inverse()*res.squaredNorm();
//Update last velocity in local coordinates
kai_loc_level = Var;
}
void CDifodo::odometryCalculation()
{
//Clock to measure the runtime
utils::CTicTac clock;
clock.Tic();
//Build the gaussian pyramid
if (fast_pyramid) buildCoordinatesPyramidFast();
else buildCoordinatesPyramid();
//Coarse-to-fines scheme
for (unsigned int i=0; i<ctf_levels; i++)
{
//Previous computations
transformations[i].setIdentity();
level = i;
unsigned int s = pow(2.f,int(ctf_levels-(i+1)));
cols_i = cols/s; rows_i = rows/s;
image_level = ctf_levels - i + round(log(float(width/cols))/log(2.f)) - 1;
//1. Perform warping
if (i == 0)
{
depth_warped[image_level] = depth[image_level];
xx_warped[image_level] = xx[image_level];
yy_warped[image_level] = yy[image_level];
}
else
performWarping();
//2. Calculate inter coords and find null measurements
calculateCoord();
//3. Compute derivatives
calculateDepthDerivatives();
//4. Compute weights
computeWeights();
//5. Solve odometry
if (num_valid_points > 6)
solveOneLevel();
//6. Filter solution
filterLevelSolution();
}
//Update poses
poseUpdate();
//Save runtime
execution_time = 1000.f*clock.Tac();
}
void CDifodo::filterLevelSolution()
{
// Calculate Eigenvalues and Eigenvectors
//----------------------------------------------------------
SelfAdjointEigenSolver<MatrixXf> eigensolver(est_cov);
if (eigensolver.info() != Success)
{
printf("\n Eigensolver couldn't find a solution. Pose is not updated");
return;
}
//First, we have to describe both the new linear and angular velocities in the "eigenvector" basis
//-------------------------------------------------------------------------------------------------
Matrix<float,6,6> Bii;
Matrix<float,6,1> kai_b;
Bii = eigensolver.eigenvectors();
kai_b = Bii.colPivHouseholderQr().solve(kai_loc_level);
//Second, we have to describe both the old linear and angular velocities in the "eigenvector" basis
//-------------------------------------------------------------------------------------------------
Matrix<float,6,1> kai_loc_sub = kai_loc_old;
//Important: we have to substract the previous levels' solutions from the old velocity.
Matrix4f acu_trans;
acu_trans.setIdentity();
for (unsigned int i=0; i<level; i++)
acu_trans = transformations[i]*acu_trans;
CMatrixDouble44 mat_aux = acu_trans.cast<double>();
poses::CPose3D aux(mat_aux);
CArrayDouble<6> kai_level_acu = aux.ln()*fps;
kai_loc_sub -= kai_level_acu.cast<float>();
//Matrix<float, 4, 4> log_trans = fps*acu_trans.log();
//kai_loc_sub(0) -= log_trans(0,3); kai_loc_sub(1) -= log_trans(1,3); kai_loc_sub(2) -= log_trans(2,3);
//kai_loc_sub(3) += log_trans(1,2); kai_loc_sub(4) -= log_trans(0,2); kai_loc_sub(5) += log_trans(0,1);
//Transform that local representation to the "eigenvector" basis
Matrix<float,6,1> kai_b_old;
kai_b_old = Bii.colPivHouseholderQr().solve(kai_loc_sub);
// Filter velocity
//--------------------------------------------------------------------------------
const float cf = previous_speed_eig_weight*expf(-int(level)), df = previous_speed_const_weight*expf(-int(level));
Matrix<float,6,1> kai_b_fil;
for (unsigned int i=0; i<6; i++)
kai_b_fil(i) = (kai_b(i) + (cf*eigensolver.eigenvalues()(i,0) + df)*kai_b_old(i))/(1.f + cf*eigensolver.eigenvalues()(i) + df);
//Transform filtered velocity to the local reference frame
Matrix<float, 6, 1> kai_loc_fil = Bii.inverse().colPivHouseholderQr().solve(kai_b_fil);
//Compute the rigid transformation
mrpt::math::CArrayDouble<6> aux_vel = kai_loc_fil.cast<double>()/fps;
poses::CPose3D aux1, aux2;
CMatrixDouble44 trans;
aux2 = aux1.exp(aux_vel);
aux2.getHomogeneousMatrix(trans);
transformations[level] = trans.cast<float>();
}
void CDifodo::poseUpdate()
{
//First, compute the overall transformation
//---------------------------------------------------
Matrix4f acu_trans;
acu_trans.setIdentity();
for (unsigned int i=1; i<=ctf_levels; i++)
acu_trans = transformations[i-1]*acu_trans;
//Compute the new estimates in the local and absolutes reference frames
//---------------------------------------------------------------------
CMatrixDouble44 mat_aux = acu_trans.cast<double>();
poses::CPose3D aux(mat_aux);
CArrayDouble<6> kai_level_acu = aux.ln()*fps;
kai_loc = kai_level_acu.cast<float>();
//---------------------------------------------------------------------------------------------
//Directly from Eigen:
//- Eigen 3.1.0 needed for Matrix::log()
//- The line "#include <unsupported/Eigen/MatrixFunctions>" should be uncommented (CDifodo.h)
//
//Matrix<float, 4, 4> log_trans = fps*acu_trans.log();
//kai_loc(0) = log_trans(0,3); kai_loc(1) = log_trans(1,3); kai_loc(2) = log_trans(2,3);
//kai_loc(3) = -log_trans(1,2); kai_loc(4) = log_trans(0,2); kai_loc(5) = -log_trans(0,1);
//---------------------------------------------------------------------------------------------
CMatrixDouble33 inv_trans;
CMatrixFloat31 v_abs, w_abs;
cam_pose.getRotationMatrix(inv_trans);
v_abs = inv_trans.cast<float>()*kai_loc.topRows(3);
w_abs = inv_trans.cast<float>()*kai_loc.bottomRows(3);
kai_abs.topRows<3>() = v_abs;
kai_abs.bottomRows<3>() = w_abs;
// Update poses
//-------------------------------------------------------
cam_oldpose = cam_pose;
CMatrixDouble44 aux_acu = acu_trans;
poses::CPose3D pose_aux(aux_acu);
cam_pose = cam_pose + pose_aux;
//Compute the velocity estimate in the new ref frame (to be used by the filter in the next iteration)
//---------------------------------------------------------------------------------------------------
cam_pose.getRotationMatrix(inv_trans);
kai_loc_old.topRows<3>() = inv_trans.inverse().cast<float>()*kai_abs.topRows(3);
kai_loc_old.bottomRows<3>() = inv_trans.inverse().cast<float>()*kai_abs.bottomRows(3);
}
void CDifodo::setFOV(float new_fovh, float new_fovv)
{
fovh = M_PI*new_fovh/180.0;
fovv = M_PI*new_fovv/180.0;
}
void CDifodo::getPointsCoord(MatrixXf &x, MatrixXf &y, MatrixXf &z)
{
x.resize(rows,cols);
y.resize(rows,cols);
z.resize(rows,cols);
z = depth_inter[0];
x = xx_inter[0];
y = yy_inter[0];
}
void CDifodo::getDepthDerivatives(MatrixXf &cur_du, MatrixXf &cur_dv, MatrixXf &cur_dt)
{
cur_du.resize(rows,cols);
cur_dv.resize(rows,cols);
cur_dt.resize(rows,cols);
cur_du = du;
cur_dv = dv;
cur_dt = dt;
}
void CDifodo::getWeights(MatrixXf &w)
{
w.resize(rows,cols);
w = weights;
}
|
#include "framework/model_parser/parser/parser.h"
#include "framework/model_parser/parser/model_io.h"
#include "framework/model_parser/proto/graph.pb.h"
#include "framework/model_parser/proto/node.pb.h"
#include "framework/model_parser/proto/operator.pb.h"
#include "framework/model_parser/proto/tensor.pb.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <fstream>
#include <google/protobuf/io/zero_copy_stream_impl.h>
#include <google/protobuf/io/zero_copy_stream.h>
#include <google/protobuf/text_format.h>
namespace anakin {
namespace parser {
template<typename Ttype, DataType Dtype, Precision Ptype>
Status load(graph::Graph<Ttype, Dtype, Ptype>* graph, std::string& model_path) {
return load(graph, model_path.c_str());
}
#ifdef USE_CUDA
template
Status load<NV, AK_FLOAT, Precision::FP32>(graph::Graph<NV, AK_FLOAT, Precision::FP32>* graph,
std::string& model_path);
template
Status load<NV, AK_FLOAT, Precision::FP16>(graph::Graph<NV, AK_FLOAT, Precision::FP16>* graph,
std::string& model_path);
template
Status load<NV, AK_FLOAT, Precision::INT8>(graph::Graph<NV, AK_FLOAT, Precision::INT8>* graph,
std::string& model_path);
#endif
#ifdef USE_X86_PLACE
template
Status load<X86, AK_FLOAT, Precision::FP32>(graph::Graph<X86, AK_FLOAT, Precision::FP32>* graph,
std::string& model_path);
template
Status load<X86, AK_FLOAT, Precision::FP16>(graph::Graph<X86, AK_FLOAT, Precision::FP16>* graph,
std::string& model_path);
template
Status load<X86, AK_FLOAT, Precision::INT8>(graph::Graph<X86, AK_FLOAT, Precision::INT8>* graph,
std::string& model_path);
#endif
#ifdef USE_ARM_PLACE
template
Status load<ARM, AK_FLOAT, Precision::FP32>(graph::Graph<ARM, AK_FLOAT, Precision::FP32>* graph,
std::string& model_path);
template
Status load<ARM, AK_FLOAT, Precision::FP16>(graph::Graph<ARM, AK_FLOAT, Precision::FP16>* graph,
std::string& model_path);
template
Status load<ARM, AK_FLOAT, Precision::INT8>(graph::Graph<ARM, AK_FLOAT, Precision::INT8>* graph,
std::string& model_path);
#endif
template<typename Ttype, DataType Dtype, Precision Ptype>
Status load(graph::Graph<Ttype, Dtype, Ptype>* graph, const char* model_path) {
#if 0
std::fstream input(model_path, std::ios::in | std::ios::binary);
if (!input) {
DLOG(ERROR) << model_path << " : File not found. ";
return Status::FAIL("File not found");
}
GraphProto graph_proto;
// parsing GraphProto from model
if (!graph_proto.ParseFromIstream(&input)) {
DLOG(ERROR) << "Fail to parse GraphProto.";
return Status::FAIL("Fail to parse GraphProto.");
}
#else
GraphProto graph_proto;
int file_descriptor = open(model_path, O_RDONLY);
if (file_descriptor == -1) {
LOG(FATAL) << " Cant open " << model_path;
}
google::protobuf::io::ZeroCopyInputStream* raw_input = new google::protobuf::io::FileInputStream(
file_descriptor);
google::protobuf::io::CodedInputStream* coded_input = new google::protobuf::io::CodedInputStream(
raw_input);
coded_input->SetTotalBytesLimit(ProtoReadBytesLimit, 536870912);
bool success = graph_proto.ParseFromCodedStream(coded_input);
if (!success) {
LOG(FATAL) << " Parsing GraphProto " << model_path;
}
delete coded_input;
delete raw_input;
close(file_descriptor);
#endif
// fill the graph with name
LOG(INFO) << " graph name: " << graph_proto.name();
graph->name() = graph_proto.name();
// fill the graph with ins/outs
for (int i = 0; i < graph_proto.ins().size(); i++) {
LOG(INFO) << "graph in: " << graph_proto.ins()[i];
std::string in_name(graph_proto.ins()[i]);
graph->add_in(in_name);
}
for (int i = 0; i < graph_proto.outs().size(); i++) {
LOG(INFO) << "graph out: " << graph_proto.outs()[i];
std::string out_name(graph_proto.outs()[i]);
graph->add_out(out_name);
}
// fill the graph with nodes
NodeIO<Ttype, Dtype, Ptype> node_io;
for (int i = 0; i < graph_proto.nodes().size(); i++) {
node_io >> graph_proto.nodes()[i];
}
node_io << *graph;
// fill the graph with edges
auto it_in = graph_proto.edges_in().begin();
for (; it_in != graph_proto.edges_in().end(); ++it_in) {
LOG(WARNING) << " Parsing in edges of node : " << it_in->first;
auto& key = it_in->first;
auto& second = it_in->second;
for (int i = 0; i < second.val().size(); i++) {
//Tensor4dPtr<Ttype, Dtype> tensor_p = std::make_shared<Tensor4d<Ttype, Dtype>>();
graph::Edge<Ttype, Dtype> edge(second.val()[i], key);
//edge.weight() = new Tensor4d<Ttype, Dtype>();
//edge.weight() = std::make_shared<Tensor4d<Ttype, Dtype> >();
edge.shared() = (*graph_proto.mutable_edges_info())[edge.name()].shared();
edge.share_from() = (*graph_proto.mutable_edges_info())[edge.name()].share_from();
graph->add_in_arc(edge);
}
}
auto it_out = graph_proto.edges_out().begin();
for (; it_out != graph_proto.edges_out().end(); ++it_out) {
auto& key = it_out->first;
auto& second = it_out->second;
for (int i = 0; i < second.val().size(); i++) {
//Tensor4dPtr<Ttype, Dtype> tensor_p = std::make_shared<Tensor4d<Ttype, Dtype>>();
graph::Edge<Ttype, Dtype> edge(key, second.val()[i]);
//edge.weight() = new Tensor4d<Ttype, Dtype>();
//edge.weight() = std::make_shared<Tensor4d<Ttype, Dtype> >();
edge.shared() = (*graph_proto.mutable_edges_info())[edge.name()].shared();
edge.share_from() = (*graph_proto.mutable_edges_info())[edge.name()].share_from();
graph->add_out_arc(edge);
}
}
// fill the graph with edges
/*for(int i=0; i < node_io.get_node_name_in_order().size(); i++) {
auto& node_name = node_io.get_node_name_in_order()[i];
if (graph_proto.edges().count(node_name) > 0) {
auto& second_node_name_list = graph_proto.edges().at(node_name);
for(int j = 0; j < second_node_name_list.val().size(); j++) {
graph::Edge<Ttype, Dtype> edge(node_name, second_node_name_list.val()[j]);
edge.weight() = std::make_shared<Tensor4d<Ttype, Dtype> >();
edge.shared() = (*graph_proto.mutable_edges_info())[edge.name()].shared();
edge.share_from() = (*graph_proto.mutable_edges_info())[edge.name()].share_from();
graph->add_arc(edge);
}
} else {
LOG(FATAL) << " Node : " << node_name << " not found!";
}
}*/
// fill the graph with info (only use the key value: is_optimized)
graph->statistics.template set_info<graph::IS_OPTIMIZED>(graph_proto.summary().is_optimized());
graph->statistics.template set_info<graph::TEMP_MEM>(graph_proto.summary().temp_mem_used());
graph->statistics.template set_info<graph::ORI_TEMP_MEM>
(graph_proto.summary().original_temp_mem_used());
graph->statistics.template set_info<graph::SYSTEM_MEM>(graph_proto.summary().system_mem_used());
graph->statistics.template set_info<graph::MODEL_MEM>(graph_proto.summary().model_mem_used());
return Status::OK();
}
#ifdef USE_CUDA
template
Status load<NV, AK_FLOAT, Precision::FP32>(graph::Graph<NV, AK_FLOAT, Precision::FP32>* graph,
const char* model_path);
template
Status load<NV, AK_FLOAT, Precision::FP16>(graph::Graph<NV, AK_FLOAT, Precision::FP16>* graph,
const char* model_path);
template
Status load<NV, AK_FLOAT, Precision::INT8>(graph::Graph<NV, AK_FLOAT, Precision::INT8>* graph,
const char* model_path);
#endif
#ifdef USE_X86_PLACE
template
Status load<X86, AK_FLOAT, Precision::FP32>(graph::Graph<X86, AK_FLOAT, Precision::FP32>* graph,
const char* model_path);
template
Status load<X86, AK_FLOAT, Precision::FP16>(graph::Graph<X86, AK_FLOAT, Precision::FP16>* graph,
const char* model_path);
template
Status load<X86, AK_FLOAT, Precision::INT8>(graph::Graph<X86, AK_FLOAT, Precision::INT8>* graph,
const char* model_path);
#endif
#ifdef USE_ARM_PLACE
template
Status load<ARM, AK_FLOAT, Precision::FP32>(graph::Graph<ARM, AK_FLOAT, Precision::FP32>* graph,
const char* model_path);
template
Status load<ARM, AK_FLOAT, Precision::FP16>(graph::Graph<ARM, AK_FLOAT, Precision::FP16>* graph,
const char* model_path);
template
Status load<ARM, AK_FLOAT, Precision::INT8>(graph::Graph<ARM, AK_FLOAT, Precision::INT8>* graph,
const char* model_path);
#endif
template<typename Ttype, DataType Dtype, Precision Ptype>
Status save(graph::Graph<Ttype, Dtype, Ptype>* graph, std::string& model_path) {
return save(graph, model_path.c_str());
}
#ifdef USE_CUDA
template
Status save<NV, AK_FLOAT, Precision::FP32>(graph::Graph<NV, AK_FLOAT, Precision::FP32>* graph,
std::string& model_path);
template
Status save<NV, AK_FLOAT, Precision::FP16>(graph::Graph<NV, AK_FLOAT, Precision::FP16>* graph,
std::string& model_path);
template
Status save<NV, AK_FLOAT, Precision::INT8>(graph::Graph<NV, AK_FLOAT, Precision::INT8>* graph,
std::string& model_path);
#endif
#ifdef USE_X86_PLACE
template
Status save<X86, AK_FLOAT, Precision::FP32>(graph::Graph<X86, AK_FLOAT, Precision::FP32>* graph,
std::string& model_path);
template
Status save<X86, AK_FLOAT, Precision::FP16>(graph::Graph<X86, AK_FLOAT, Precision::FP16>* graph,
std::string& model_path);
template
Status save<X86, AK_FLOAT, Precision::INT8>(graph::Graph<X86, AK_FLOAT, Precision::INT8>* graph,
std::string& model_path);
#endif
#ifdef USE_ARM_PLACE
template
Status save<ARM, AK_FLOAT, Precision::FP32>(graph::Graph<ARM, AK_FLOAT, Precision::FP32>* graph,
std::string& model_path);
template
Status save<ARM, AK_FLOAT, Precision::FP16>(graph::Graph<ARM, AK_FLOAT, Precision::FP16>* graph,
std::string& model_path);
template
Status save<ARM, AK_FLOAT, Precision::INT8>(graph::Graph<ARM, AK_FLOAT, Precision::INT8>* graph,
std::string& model_path);
#endif
template<typename Ttype, DataType Dtype, Precision Ptype>
Status save(graph::Graph<Ttype, Dtype, Ptype>* graph, const char* model_path) {
std::fstream output(model_path, std::ios::out | std::ios::trunc | std::ios::binary);
if (!output) {
LOG(ERROR) << model_path << " : File not found. ";
return Status::FAIL("File not found");
}
GraphProto graph_proto;
// TODO... fill the graph_proto with graph.
// set graph proto name
graph_proto.set_name(graph->name());
// fill the graph proto with ins/outs
for (auto in : graph->get_ins()) {
graph_proto.add_ins(in);
}
for (auto out : graph->get_outs()) {
graph_proto.add_outs(out);
}
// fill the graph proto nodes with NodePtr in exec order
NodeIO<Ttype, Dtype, Ptype> node_io;
auto nodes_in_exec_order = graph->get_nodes_in_order();
for (int i = 0; i < nodes_in_exec_order.size(); i++) {
node_io >> (*graph)[nodes_in_exec_order[i]];;
}
node_io << graph_proto;
// fill the graph proto' edges/edges_info with edges
auto edges_in = graph_proto.mutable_edges_in();
auto edges_out = graph_proto.mutable_edges_out();
auto edges_info = graph_proto.mutable_edges_info();
/*auto insert_edge = [&](graph::Edge<Ttype, Dtype>& edge) {
(*edges)[edge.first()].add_val(edge.second());
TensorProto ts;
ts.set_name(edge.name());
ts.set_shared(edge.shared());
ts.set_share_from(edge.share_from());
(*edges_info)[edge.name()].CopyFrom(ts);
};*/
auto insert_edge = [&](graph::NodePtr<Ttype, Dtype, Ptype>& node_p) {
auto& arcs_it_in = graph->get_in_arc_its(node_p->name());
auto& arcs_it_out = graph->get_out_arc_its(node_p->name());
for (auto& edge_it : arcs_it_in) {
(*edges_in)[edge_it->second()].add_val(edge_it->first());
TensorProto ts;
ts.set_name(edge_it->name());
ts.set_shared(edge_it->shared());
ts.set_share_from(edge_it->share_from());
(*edges_info)[edge_it->name()].CopyFrom(ts);
}
for (auto& edge_it : arcs_it_out) {
(*edges_out)[edge_it->first()].add_val(edge_it->second());
TensorProto ts;
ts.set_name(edge_it->name());
ts.set_shared(edge_it->shared());
ts.set_share_from(edge_it->share_from());
(*edges_info)[edge_it->name()].CopyFrom(ts);
}
};
graph->Scanner->BFS(insert_edge);
// save graph info
auto summary = graph_proto.mutable_summary();
summary->set_is_optimized(graph->statistics.template get_info<graph::IS_OPTIMIZED>());
summary->set_temp_mem_used(graph->statistics.template get_info<graph::TEMP_MEM>());
summary->set_original_temp_mem_used(graph->statistics.template get_info<graph::ORI_TEMP_MEM>());
summary->set_system_mem_used(graph->statistics.template get_info<graph::SYSTEM_MEM>());
summary->set_model_mem_used(graph->statistics.template get_info<graph::MODEL_MEM>());
// save graph proto to disk
graph_proto.SerializeToOstream(&output);
return Status::OK();
}
#ifdef USE_CUDA
template
Status save<NV, AK_FLOAT, Precision::FP32>(graph::Graph<NV, AK_FLOAT, Precision::FP32>* graph,
const char* model_path);
template
Status save<NV, AK_FLOAT, Precision::FP16>(graph::Graph<NV, AK_FLOAT, Precision::FP16>* graph,
const char* model_path);
template
Status save<NV, AK_FLOAT, Precision::INT8>(graph::Graph<NV, AK_FLOAT, Precision::INT8>* graph,
const char* model_path);
#endif
#ifdef USE_X86_PLACE
template
Status save<X86, AK_FLOAT, Precision::FP32>(graph::Graph<X86, AK_FLOAT, Precision::FP32>* graph,
const char* model_path);
template
Status save<X86, AK_FLOAT, Precision::FP16>(graph::Graph<X86, AK_FLOAT, Precision::FP16>* graph,
const char* model_path);
template
Status save<X86, AK_FLOAT, Precision::INT8>(graph::Graph<X86, AK_FLOAT, Precision::INT8>* graph,
const char* model_path);
#endif
#ifdef USE_ARM_PLACE
template
Status save<ARM, AK_FLOAT, Precision::FP32>(graph::Graph<ARM, AK_FLOAT, Precision::FP32>* graph,
const char* model_path);
template
Status save<ARM, AK_FLOAT, Precision::FP16>(graph::Graph<ARM, AK_FLOAT, Precision::FP16>* graph,
const char* model_path);
template
Status save<ARM, AK_FLOAT, Precision::INT8>(graph::Graph<ARM, AK_FLOAT, Precision::INT8>* graph,
const char* model_path);
#endif
} /* parser */
} /* anakin */
|
// 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 "media/base/user_input_monitor.h"
#include <ApplicationServices/ApplicationServices.h>
namespace media {
namespace {
class UserInputMonitorMac : public UserInputMonitor {
public:
UserInputMonitorMac();
virtual ~UserInputMonitorMac();
virtual size_t GetKeyPressCount() const OVERRIDE;
private:
virtual void StartKeyboardMonitoring() OVERRIDE;
virtual void StopKeyboardMonitoring() OVERRIDE;
virtual void StartMouseMonitoring() OVERRIDE;
virtual void StopMouseMonitoring() OVERRIDE;
DISALLOW_COPY_AND_ASSIGN(UserInputMonitorMac);
};
UserInputMonitorMac::UserInputMonitorMac() {}
UserInputMonitorMac::~UserInputMonitorMac() {}
size_t UserInputMonitorMac::GetKeyPressCount() const {
// Use |kCGEventSourceStateHIDSystemState| since we only want to count
// hardware generated events.
return CGEventSourceCounterForEventType(kCGEventSourceStateHIDSystemState,
kCGEventKeyDown);
}
void UserInputMonitorMac::StartKeyboardMonitoring() {}
void UserInputMonitorMac::StopKeyboardMonitoring() {}
// TODO(jiayl): add the impl.
void UserInputMonitorMac::StartMouseMonitoring() { NOTIMPLEMENTED(); }
// TODO(jiayl): add the impl.
void UserInputMonitorMac::StopMouseMonitoring() { NOTIMPLEMENTED(); }
} // namespace
scoped_ptr<UserInputMonitor> UserInputMonitor::Create(
const scoped_refptr<base::SingleThreadTaskRunner>& input_task_runner,
const scoped_refptr<base::SingleThreadTaskRunner>& ui_task_runner) {
return scoped_ptr<UserInputMonitor>(new UserInputMonitorMac());
}
} // namespace media
|
// 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 "media/capture/video/file_video_capture_device.h"
#include <stddef.h>
#include <memory>
#include <utility>
#include "base/bind.h"
#include "base/location.h"
#include "base/logging.h"
#include "base/macros.h"
#include "base/single_thread_task_runner.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_piece.h"
#include "base/strings/string_util.h"
#include "base/threading/thread_task_runner_handle.h"
#include "media/base/video_frame.h"
#include "media/capture/mojom/image_capture_types.h"
#include "media/capture/video/blob_utils.h"
#include "media/capture/video/gpu_memory_buffer_utils.h"
#include "media/capture/video_capture_types.h"
#include "media/parsers/jpeg_parser.h"
#include "third_party/libyuv/include/libyuv.h"
namespace media {
static const int kY4MHeaderMaxSize = 200;
static const char kY4MSimpleFrameDelimiter[] = "FRAME";
static const int kY4MSimpleFrameDelimiterSize = 6;
static const float kMJpegFrameRate = 30.0f;
int ParseY4MInt(const base::StringPiece& token) {
int temp_int;
CHECK(base::StringToInt(token, &temp_int)) << token;
return temp_int;
}
// Extract numerator and denominator out of a token that must have the aspect
// numerator:denominator, both integer numbers.
void ParseY4MRational(const base::StringPiece& token,
int* numerator,
int* denominator) {
size_t index_divider = token.find(':');
CHECK_NE(index_divider, token.npos);
*numerator = ParseY4MInt(token.substr(0, index_divider));
*denominator = ParseY4MInt(token.substr(index_divider + 1, token.length()));
CHECK(*denominator);
}
// This function parses the ASCII string in |header| as belonging to a Y4M file,
// returning the collected format in |video_format|. For a non authoritative
// explanation of the header format, check
// http://wiki.multimedia.cx/index.php?title=YUV4MPEG2
// Restrictions: Only interlaced I420 pixel format is supported, and pixel
// aspect ratio is ignored.
// Implementation notes: Y4M header should end with an ASCII 0x20 (whitespace)
// character, however all examples mentioned in the Y4M header description end
// with a newline character instead. Also, some headers do _not_ specify pixel
// format, in this case it means I420.
// This code was inspired by third_party/libvpx/.../y4minput.* .
void ParseY4MTags(const std::string& file_header,
VideoCaptureFormat* video_format) {
VideoCaptureFormat format;
format.pixel_format = PIXEL_FORMAT_I420;
size_t index = 0;
size_t blank_position = 0;
base::StringPiece token;
while ((blank_position = file_header.find_first_of("\n ", index)) !=
std::string::npos) {
// Every token is supposed to have an identifier letter and a bunch of
// information immediately after, which we extract into a |token| here.
token =
base::StringPiece(&file_header[index + 1], blank_position - index - 1);
CHECK(!token.empty());
switch (file_header[index]) {
case 'W':
format.frame_size.set_width(ParseY4MInt(token));
break;
case 'H':
format.frame_size.set_height(ParseY4MInt(token));
break;
case 'F': {
// If the token is "FRAME", it means we have finished with the header.
if (token[0] == 'R')
break;
int fps_numerator, fps_denominator;
ParseY4MRational(token, &fps_numerator, &fps_denominator);
format.frame_rate = fps_numerator / fps_denominator;
break;
}
case 'I':
// Interlacing is ignored, but we don't like mixed modes.
CHECK_NE(token[0], 'm');
break;
case 'A':
// Pixel aspect ratio ignored.
break;
case 'C':
CHECK(token == "420" || token == "420jpeg" || token == "420mpeg2" ||
token == "420paldv")
<< token; // Only I420 is supported, and we fudge the variants.
break;
default:
break;
}
// We're done if we have found a newline character right after the token.
if (file_header[blank_position] == '\n')
break;
index = blank_position + 1;
}
// Last video format semantic correctness check before sending it back.
CHECK(format.IsValid());
*video_format = format;
}
class VideoFileParser {
public:
explicit VideoFileParser(const base::FilePath& file_path);
virtual ~VideoFileParser();
// Parses file header and collects format information in |capture_format|.
virtual bool Initialize(VideoCaptureFormat* capture_format) = 0;
// Gets the start pointer of next frame and stores current frame size in
// |frame_size|.
virtual const uint8_t* GetNextFrame(int* frame_size) = 0;
protected:
const base::FilePath file_path_;
int frame_size_;
size_t current_byte_index_;
size_t first_frame_byte_index_;
};
class Y4mFileParser final : public VideoFileParser {
public:
explicit Y4mFileParser(const base::FilePath& file_path);
// VideoFileParser implementation, class methods.
~Y4mFileParser() override;
bool Initialize(VideoCaptureFormat* capture_format) override;
const uint8_t* GetNextFrame(int* frame_size) override;
private:
std::unique_ptr<base::File> file_;
std::unique_ptr<uint8_t[]> video_frame_;
DISALLOW_COPY_AND_ASSIGN(Y4mFileParser);
};
class MjpegFileParser final : public VideoFileParser {
public:
explicit MjpegFileParser(const base::FilePath& file_path);
// VideoFileParser implementation, class methods.
~MjpegFileParser() override;
bool Initialize(VideoCaptureFormat* capture_format) override;
const uint8_t* GetNextFrame(int* frame_size) override;
private:
std::unique_ptr<base::MemoryMappedFile> mapped_file_;
DISALLOW_COPY_AND_ASSIGN(MjpegFileParser);
};
VideoFileParser::VideoFileParser(const base::FilePath& file_path)
: file_path_(file_path),
frame_size_(0),
current_byte_index_(0),
first_frame_byte_index_(0) {}
VideoFileParser::~VideoFileParser() = default;
Y4mFileParser::Y4mFileParser(const base::FilePath& file_path)
: VideoFileParser(file_path) {}
Y4mFileParser::~Y4mFileParser() = default;
bool Y4mFileParser::Initialize(VideoCaptureFormat* capture_format) {
file_ = std::make_unique<base::File>(
file_path_, base::File::FLAG_OPEN | base::File::FLAG_READ);
if (!file_->IsValid()) {
DLOG(ERROR) << file_path_.value() << ", error: "
<< base::File::ErrorToString(file_->error_details());
return false;
}
std::string header(kY4MHeaderMaxSize, '\0');
file_->Read(0, &header[0], header.size());
const size_t header_end = header.find(kY4MSimpleFrameDelimiter);
CHECK_NE(header_end, header.npos);
ParseY4MTags(header, capture_format);
first_frame_byte_index_ = header_end + kY4MSimpleFrameDelimiterSize;
current_byte_index_ = first_frame_byte_index_;
frame_size_ = VideoFrame::AllocationSize(capture_format->pixel_format,
capture_format->frame_size);
return true;
}
const uint8_t* Y4mFileParser::GetNextFrame(int* frame_size) {
if (!video_frame_)
video_frame_.reset(new uint8_t[frame_size_]);
int result =
file_->Read(current_byte_index_,
reinterpret_cast<char*>(video_frame_.get()), frame_size_);
// If we passed EOF to base::File, it will return 0 read characters. In that
// case, reset the pointer and read again.
if (result != frame_size_) {
CHECK_EQ(result, 0);
current_byte_index_ = first_frame_byte_index_;
CHECK_EQ(
file_->Read(current_byte_index_,
reinterpret_cast<char*>(video_frame_.get()), frame_size_),
frame_size_);
} else {
current_byte_index_ += frame_size_ + kY4MSimpleFrameDelimiterSize;
}
*frame_size = frame_size_;
return video_frame_.get();
}
MjpegFileParser::MjpegFileParser(const base::FilePath& file_path)
: VideoFileParser(file_path) {}
MjpegFileParser::~MjpegFileParser() = default;
bool MjpegFileParser::Initialize(VideoCaptureFormat* capture_format) {
mapped_file_ = std::make_unique<base::MemoryMappedFile>();
if (!mapped_file_->Initialize(file_path_) || !mapped_file_->IsValid()) {
LOG(ERROR) << "File memory map error: " << file_path_.value();
return false;
}
JpegParseResult result;
if (!ParseJpegStream(mapped_file_->data(), mapped_file_->length(), &result))
return false;
frame_size_ = result.image_size;
if (frame_size_ > static_cast<int>(mapped_file_->length())) {
LOG(ERROR) << "File is incomplete";
return false;
}
VideoCaptureFormat format;
format.pixel_format = PIXEL_FORMAT_MJPEG;
format.frame_size.set_width(result.frame_header.visible_width);
format.frame_size.set_height(result.frame_header.visible_height);
format.frame_rate = kMJpegFrameRate;
if (!format.IsValid())
return false;
*capture_format = format;
return true;
}
const uint8_t* MjpegFileParser::GetNextFrame(int* frame_size) {
const uint8_t* buf_ptr = mapped_file_->data() + current_byte_index_;
JpegParseResult result;
if (!ParseJpegStream(buf_ptr, mapped_file_->length() - current_byte_index_,
&result)) {
return nullptr;
}
*frame_size = frame_size_ = result.image_size;
current_byte_index_ += frame_size_;
// Reset the pointer to play repeatedly.
if (current_byte_index_ >= mapped_file_->length())
current_byte_index_ = first_frame_byte_index_;
return buf_ptr;
}
// static
bool FileVideoCaptureDevice::GetVideoCaptureFormat(
const base::FilePath& file_path,
VideoCaptureFormat* video_format) {
std::unique_ptr<VideoFileParser> file_parser =
GetVideoFileParser(file_path, video_format);
return file_parser != nullptr;
}
// static
std::unique_ptr<VideoFileParser> FileVideoCaptureDevice::GetVideoFileParser(
const base::FilePath& file_path,
VideoCaptureFormat* video_format) {
std::unique_ptr<VideoFileParser> file_parser;
std::string file_name(file_path.value().begin(), file_path.value().end());
if (base::EndsWith(file_name, "y4m", base::CompareCase::INSENSITIVE_ASCII)) {
file_parser = std::make_unique<Y4mFileParser>(file_path);
} else if (base::EndsWith(file_name, "mjpeg",
base::CompareCase::INSENSITIVE_ASCII)) {
file_parser = std::make_unique<MjpegFileParser>(file_path);
} else {
LOG(ERROR) << "Unsupported file format.";
return file_parser;
}
if (!file_parser->Initialize(video_format)) {
file_parser.reset();
}
return file_parser;
}
FileVideoCaptureDevice::FileVideoCaptureDevice(
const base::FilePath& file_path,
std::unique_ptr<gpu::GpuMemoryBufferSupport> gmb_support)
: capture_thread_("CaptureThread"),
file_path_(file_path),
gmb_support_(gmb_support
? std::move(gmb_support)
: std::make_unique<gpu::GpuMemoryBufferSupport>()) {}
FileVideoCaptureDevice::~FileVideoCaptureDevice() {
DCHECK(thread_checker_.CalledOnValidThread());
// Check if the thread is running.
// This means that the device have not been DeAllocated properly.
CHECK(!capture_thread_.IsRunning());
}
void FileVideoCaptureDevice::AllocateAndStart(
const VideoCaptureParams& params,
std::unique_ptr<VideoCaptureDevice::Client> client) {
DCHECK(thread_checker_.CalledOnValidThread());
CHECK(!capture_thread_.IsRunning());
capture_thread_.Start();
capture_thread_.task_runner()->PostTask(
FROM_HERE,
base::BindOnce(&FileVideoCaptureDevice::OnAllocateAndStart,
base::Unretained(this), params, std::move(client)));
}
void FileVideoCaptureDevice::StopAndDeAllocate() {
DCHECK(thread_checker_.CalledOnValidThread());
CHECK(capture_thread_.IsRunning());
capture_thread_.task_runner()->PostTask(
FROM_HERE, base::BindOnce(&FileVideoCaptureDevice::OnStopAndDeAllocate,
base::Unretained(this)));
capture_thread_.Stop();
}
void FileVideoCaptureDevice::GetPhotoState(GetPhotoStateCallback callback) {
DCHECK(thread_checker_.CalledOnValidThread());
auto photo_capabilities = mojo::CreateEmptyPhotoState();
int height = capture_format_.frame_size.height();
photo_capabilities->height = mojom::Range::New(height, height, height, 0);
int width = capture_format_.frame_size.width();
photo_capabilities->width = mojom::Range::New(width, width, width, 0);
std::move(callback).Run(std::move(photo_capabilities));
}
void FileVideoCaptureDevice::SetPhotoOptions(mojom::PhotoSettingsPtr settings,
SetPhotoOptionsCallback callback) {
DCHECK(thread_checker_.CalledOnValidThread());
if (settings->has_height &&
settings->height != capture_format_.frame_size.height()) {
return;
}
if (settings->has_width &&
settings->width != capture_format_.frame_size.width()) {
return;
}
if (settings->has_torch && settings->torch)
return;
if (settings->has_red_eye_reduction && settings->red_eye_reduction)
return;
if (settings->has_exposure_compensation || settings->has_exposure_time ||
settings->has_color_temperature || settings->has_iso ||
settings->has_brightness || settings->has_contrast ||
settings->has_saturation || settings->has_sharpness ||
settings->has_focus_distance || settings->has_pan || settings->has_tilt ||
settings->has_zoom || settings->has_fill_light_mode) {
return;
}
std::move(callback).Run(true);
}
void FileVideoCaptureDevice::TakePhoto(TakePhotoCallback callback) {
DCHECK(thread_checker_.CalledOnValidThread());
base::AutoLock lock(lock_);
take_photo_callbacks_.push(std::move(callback));
}
void FileVideoCaptureDevice::OnAllocateAndStart(
const VideoCaptureParams& params,
std::unique_ptr<VideoCaptureDevice::Client> client) {
DCHECK(capture_thread_.task_runner()->BelongsToCurrentThread());
client_ = std::move(client);
if (params.buffer_type == VideoCaptureBufferType::kGpuMemoryBuffer)
video_capture_use_gmb_ = true;
DCHECK(!file_parser_);
file_parser_ = GetVideoFileParser(file_path_, &capture_format_);
if (!file_parser_) {
client_->OnError(
VideoCaptureError::kFileVideoCaptureDeviceCouldNotOpenVideoFile,
FROM_HERE, "Could not open Video file");
return;
}
DVLOG(1) << "Opened video file " << capture_format_.frame_size.ToString()
<< ", fps: " << capture_format_.frame_rate;
client_->OnStarted();
capture_thread_.task_runner()->PostTask(
FROM_HERE, base::BindOnce(&FileVideoCaptureDevice::OnCaptureTask,
base::Unretained(this)));
}
void FileVideoCaptureDevice::OnStopAndDeAllocate() {
DCHECK(capture_thread_.task_runner()->BelongsToCurrentThread());
file_parser_.reset();
client_.reset();
next_frame_time_ = base::TimeTicks();
}
void FileVideoCaptureDevice::OnCaptureTask() {
DCHECK(capture_thread_.task_runner()->BelongsToCurrentThread());
if (!client_)
return;
base::AutoLock lock(lock_);
// Give the captured frame to the client.
int frame_size = 0;
const uint8_t* frame_ptr = file_parser_->GetNextFrame(&frame_size);
DCHECK(frame_size);
CHECK(frame_ptr);
const base::TimeTicks current_time = base::TimeTicks::Now();
if (first_ref_time_.is_null())
first_ref_time_ = current_time;
if (video_capture_use_gmb_) {
const gfx::Size& buffer_size = capture_format_.frame_size;
std::unique_ptr<gfx::GpuMemoryBuffer> gmb;
VideoCaptureDevice::Client::Buffer capture_buffer;
auto reserve_result = AllocateNV12GpuMemoryBuffer(
client_.get(), buffer_size, gmb_support_.get(), &gmb, &capture_buffer);
if (reserve_result !=
VideoCaptureDevice::Client::ReserveResult::kSucceeded) {
client_->OnFrameDropped(
ConvertReservationFailureToFrameDropReason(reserve_result));
DVLOG(2) << __func__ << " frame was dropped.";
return;
}
ScopedNV12GpuMemoryBufferMapping scoped_mapping(std::move(gmb));
const uint8_t* src_y_plane = frame_ptr;
const uint8_t* src_u_plane =
frame_ptr +
VideoFrame::PlaneSize(PIXEL_FORMAT_I420, 0, buffer_size).GetArea();
const uint8_t* src_v_plane =
frame_ptr +
VideoFrame::PlaneSize(PIXEL_FORMAT_I420, 0, buffer_size).GetArea() +
VideoFrame::PlaneSize(PIXEL_FORMAT_I420, 1, buffer_size).GetArea();
libyuv::I420ToNV12(
src_y_plane, buffer_size.width(), src_u_plane, buffer_size.width() / 2,
src_v_plane, buffer_size.width() / 2, scoped_mapping.y_plane(),
scoped_mapping.y_stride(), scoped_mapping.uv_plane(),
scoped_mapping.uv_stride(), buffer_size.width(), buffer_size.height());
VideoCaptureFormat modified_format = capture_format_;
// When GpuMemoryBuffer is used, the frame data is opaque to the CPU for
// most of the time. Currently the only supported underlying format is
// NV12.
modified_format.pixel_format = PIXEL_FORMAT_NV12;
client_->OnIncomingCapturedBuffer(std::move(capture_buffer),
modified_format, current_time,
current_time - first_ref_time_);
} else {
// Leave the color space unset for compatibility purposes but this
// information should be retrieved from the container when possible.
client_->OnIncomingCapturedData(
frame_ptr, frame_size, capture_format_, gfx::ColorSpace(),
0 /* clockwise_rotation */, false /* flip_y */, current_time,
current_time - first_ref_time_);
}
// Process waiting photo callbacks
while (!take_photo_callbacks_.empty()) {
auto cb = std::move(take_photo_callbacks_.front());
take_photo_callbacks_.pop();
mojom::BlobPtr blob =
RotateAndBlobify(frame_ptr, frame_size, capture_format_, 0);
if (!blob)
continue;
std::move(cb).Run(std::move(blob));
}
// Reschedule next CaptureTask.
const base::TimeDelta frame_interval =
base::TimeDelta::FromMicroseconds(1E6 / capture_format_.frame_rate);
if (next_frame_time_.is_null()) {
next_frame_time_ = current_time + frame_interval;
} else {
next_frame_time_ += frame_interval;
// Don't accumulate any debt if we are lagging behind - just post next frame
// immediately and continue as normal.
if (next_frame_time_ < current_time)
next_frame_time_ = current_time;
}
base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
FROM_HERE,
base::BindOnce(&FileVideoCaptureDevice::OnCaptureTask,
base::Unretained(this)),
next_frame_time_ - current_time);
}
} // namespace media
|
//*****************************************************************************
// Copyright 2017-2019 Intel Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//*****************************************************************************
#include "gtest/gtest.h"
#include "ngraph/ngraph.hpp"
#include "util/all_close_f.hpp"
#include "util/test_control.hpp"
#include "util/test_tools.hpp"
using namespace std;
using namespace ngraph;
static string s_manifest = "${MANIFEST}";
NGRAPH_TEST(dynamic_${BACKEND_NAME}, create)
{
auto backend = runtime::Backend::create("${BACKEND_NAME}", true);
ASSERT_NE(backend, nullptr);
ASSERT_TRUE(backend->supports_dynamic_tensors());
}
NGRAPH_TEST(dynamic_${BACKEND_NAME}, create_no_dynamic)
{
auto backend = runtime::Backend::create("${BACKEND_NAME}");
ASSERT_NE(backend, nullptr);
ASSERT_FALSE(backend->supports_dynamic_tensors());
}
NGRAPH_TEST(dynamic_${BACKEND_NAME}, create_dynamic_tensor)
{
auto backend = runtime::Backend::create("${BACKEND_NAME}", true);
auto t = backend->create_dynamic_tensor(element::f32, PartialShape{2, Dimension::dynamic(), 3});
ASSERT_TRUE(t->get_partial_shape().same_scheme(PartialShape{2, Dimension::dynamic(), 3}));
}
NGRAPH_TEST(dynamic_${BACKEND_NAME}, abc)
{
//
// Create a graph for f(a,b,c) = (a+b)*c, where a, b, c all have shape {2,?,3}.
//
auto a = make_shared<op::Parameter>(element::f32, PartialShape{2, Dimension::dynamic(), 3});
auto b = make_shared<op::Parameter>(element::f32, PartialShape{2, Dimension::dynamic(), 3});
auto c = make_shared<op::Parameter>(element::f32, PartialShape{2, Dimension::dynamic(), 3});
auto a_plus_b_times_c = (a + b) * c;
auto f = make_shared<Function>(NodeVector{a_plus_b_times_c}, ParameterVector{a, b, c});
//
// Get a backend with dynamic support, and compile f.
//
auto backend = runtime::Backend::create("${BACKEND_NAME}", true);
auto ex = backend->compile(f);
//
// Create a dynamic output tensor with shape {2,?,3}.
//
auto t_r =
backend->create_dynamic_tensor(element::f32, PartialShape{2, Dimension::dynamic(), 3});
//
// For each of n=[0,...,5), run the compiled executable against a test vector of shape
// {2,n,3}, and check the results.
//
for (size_t middle_dim = 0; middle_dim < 5; middle_dim++)
{
// Fill in some test input values, which we'll use for a, b, and c.
vector<float> inputs(2 * middle_dim * 3);
for (size_t i = 0; i < 2 * middle_dim * 3; i++)
{
inputs[i] = i;
}
// Create static tensors for the inputs and copy data.
auto t_a = backend->create_tensor(element::f32, Shape{2, middle_dim, 3});
auto t_b = backend->create_tensor(element::f32, Shape{2, middle_dim, 3});
auto t_c = backend->create_tensor(element::f32, Shape{2, middle_dim, 3});
copy_data(t_a, inputs);
copy_data(t_b, inputs);
copy_data(t_c, inputs);
// Call ex, writing result into t_r (note we're using the same t_r from outside the loop.)
ex->call_with_validate({t_r}, {t_a, t_b, t_c});
// After call, t_r should have a shape of {2,n,3}.
ASSERT_EQ(t_r->get_shape(), (Shape{2, middle_dim, 3}));
// Read out the results, and compare them against expected values.
auto results = read_vector<float>(t_r);
vector<float> expected_values(2 * middle_dim * 3);
for (size_t i = 0; i < 2 * middle_dim * 3; i++)
{
expected_values[i] = (i + i) * i;
}
EXPECT_TRUE(test::all_close_f(results, expected_values));
}
}
NGRAPH_TEST(dynamic_${BACKEND_NAME}, transpose)
{
//
// Create a graph for f(x,perm) = Transpose(x,Convert<i64>(perm)). We'll do the permutation in
// i32 and cast it to i64, just for fun (and to mirror the TensorFlow test I am porting here).
//
auto x = make_shared<op::Parameter>(element::f32, PartialShape::dynamic());
auto perm = make_shared<op::Parameter>(element::i32, PartialShape{Dimension::dynamic()});
auto perm_i64 = make_shared<op::Convert>(perm, element::i64);
auto x_transpose = make_shared<op::Transpose>(x, perm_i64);
auto f = make_shared<Function>(NodeVector{x_transpose}, ParameterVector{x, perm});
auto backend = runtime::Backend::create("${BACKEND_NAME}", true);
auto ex = backend->compile(f);
auto t_r = backend->create_dynamic_tensor(element::f32, PartialShape::dynamic());
std::vector<Shape> x_shapes{Shape{2, 3}, Shape{2, 3}, Shape{2, 2, 3}};
std::vector<std::vector<int32_t>> perms{{0, 1}, {1, 0}, {2, 1, 0}};
std::vector<std::vector<float>> inputs{
{1, 2, 3, 4, 5, 6}, {1, 2, 3, 4, 5, 6}, {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}};
std::vector<Shape> expected_result_shapes{Shape{2, 3}, Shape{3, 2}, {3, 2, 2}};
// Generated with numpy, so don't worry. :)
std::vector<std::vector<float>> expected_results{
{1, 2, 3, 4, 5, 6}, {1, 4, 2, 5, 3, 6}, {1, 7, 4, 10, 2, 8, 5, 11, 3, 9, 6, 12}};
for (size_t i = 0; i < x_shapes.size(); i++)
{
auto t_x = backend->create_tensor(element::f32, x_shapes[i]);
auto t_perm = backend->create_tensor(element::i32, Shape{perms[i].size()});
copy_data(t_x, inputs[i]);
copy_data(t_perm, perms[i]);
ex->call_with_validate({t_r}, {t_x, t_perm});
ASSERT_EQ(t_r->get_shape(), expected_result_shapes[i]);
auto results = read_vector<float>(t_r);
ASSERT_TRUE(test::all_close_f(results, expected_results[i], MIN_FLOAT_TOLERANCE_BITS));
}
}
NGRAPH_TEST(dynamic_${BACKEND_NAME}, broadcast)
{
// Create a graph for
// f(x,shape:i32,axes:32) = Broadcast(x,Convert<i64>(shape),Convert<i64>(axes)).
auto x = make_shared<op::Parameter>(element::f32, PartialShape::dynamic());
auto shape = make_shared<op::Parameter>(element::i32, PartialShape{Dimension::dynamic()});
auto axes = make_shared<op::Parameter>(element::i32, PartialShape{Dimension::dynamic()});
auto shape_i64 = make_shared<op::Convert>(shape, element::i64);
auto axes_i64 = make_shared<op::Convert>(axes, element::i64);
auto bc = make_shared<op::DynBroadcast>(x, shape_i64, axes_i64);
auto f = make_shared<Function>(NodeVector{bc}, ParameterVector{x, shape, axes});
auto backend = runtime::Backend::create("${BACKEND_NAME}", true);
auto ex = backend->compile(f);
auto t_r = backend->create_dynamic_tensor(element::f32, PartialShape::dynamic());
std::vector<Shape> x_shapes{Shape{}, Shape{}, Shape{2}, Shape{2}};
std::vector<std::vector<int32_t>> shapes{{2, 2}, {2, 2, 2}, {3, 2}, {2, 3}};
std::vector<std::vector<int32_t>> axeses{{0, 1}, {0, 1, 2}, {0}, {1}};
std::vector<std::vector<float>> inputs{{6}, {7}, {10, 11}, {10, 11}};
std::vector<Shape> expected_result_shapes{
Shape{2, 2}, Shape{2, 2, 2}, Shape{3, 2}, Shape{2, 3}};
std::vector<std::vector<float>> expected_results{
{6, 6, 6, 6}, {7, 7, 7, 7, 7, 7, 7, 7}, {10, 11, 10, 11, 10, 11}, {10, 10, 10, 11, 11, 11}};
for (size_t i = 0; i < x_shapes.size(); i++)
{
auto t_x = backend->create_tensor(element::f32, x_shapes[i]);
auto t_shape = backend->create_tensor(element::i32, Shape{shapes[i].size()});
auto t_axes = backend->create_tensor(element::i32, Shape{axeses[i].size()});
copy_data(t_x, inputs[i]);
copy_data(t_shape, shapes[i]);
copy_data(t_axes, axeses[i]);
ex->call_with_validate({t_r}, {t_x, t_shape, t_axes});
ASSERT_EQ(t_r->get_shape(), expected_result_shapes[i]);
auto results = read_vector<float>(t_r);
ASSERT_TRUE(test::all_close_f(results, expected_results[i], MIN_FLOAT_TOLERANCE_BITS));
}
}
NGRAPH_TEST(dynamic_${BACKEND_NAME}, sum)
{
// Create a graph for f(x,axes:int32) = Sum(x,Convert<int64>(axes)).
auto x = make_shared<op::Parameter>(element::f32, PartialShape::dynamic());
auto axes = make_shared<op::Parameter>(element::i32, PartialShape{Dimension::dynamic()});
auto axes_i64 = make_shared<op::Convert>(axes, element::i64);
auto sum = make_shared<op::Sum>(x, axes_i64);
ASSERT_TRUE(sum->get_output_partial_shape(0).rank().is_dynamic());
auto f = make_shared<Function>(NodeVector{sum}, ParameterVector{x, axes});
auto backend = runtime::Backend::create("${BACKEND_NAME}", true);
auto ex = backend->compile(f);
auto t_r = backend->create_dynamic_tensor(element::f32, PartialShape::dynamic());
std::vector<Shape> x_shapes{
Shape{2, 3}, Shape{2, 3}, Shape{2, 3}, Shape{2, 3}, Shape{5}, Shape{5}};
std::vector<std::vector<int32_t>> axeses{{}, {0}, {1}, {0, 1}, {}, {0}};
std::vector<std::vector<float>> inputs{{1, 2, 3, 4, 5, 6},
{1, 2, 3, 4, 5, 6},
{1, 2, 3, 4, 5, 6},
{1, 2, 3, 4, 5, 6},
{1, 2, 3, 4, 5},
{1, 2, 3, 4, 5}};
std::vector<Shape> expected_result_shapes{
Shape{2, 3}, Shape{3}, Shape{2}, Shape{}, Shape{5}, Shape{}};
std::vector<std::vector<float>> expected_results{
{1, 2, 3, 4, 5, 6}, {5, 7, 9}, {6, 15}, {21}, {1, 2, 3, 4, 5}, {15}};
for (size_t i = 0; i < x_shapes.size(); i++)
{
auto t_x = backend->create_tensor(element::f32, x_shapes[i]);
auto t_axes = backend->create_tensor(element::i32, Shape{axeses[i].size()});
copy_data(t_x, inputs[i]);
copy_data(t_axes, axeses[i]);
ex->call_with_validate({t_r}, {t_x, t_axes});
ASSERT_EQ(t_r->get_shape(), expected_result_shapes[i]);
auto results = read_vector<float>(t_r);
ASSERT_TRUE(test::all_close_f(results, expected_results[i], MIN_FLOAT_TOLERANCE_BITS));
}
}
NGRAPH_TEST(dynamic_${BACKEND_NAME}, all)
{
// Create a graph for f(x,axes:int32) = All(x,Convert<int64>(axes)).
auto x = make_shared<op::Parameter>(element::boolean, PartialShape::dynamic());
auto axes = make_shared<op::Parameter>(element::i32, PartialShape{Dimension::dynamic()});
auto axes_i64 = make_shared<op::Convert>(axes, element::i64);
auto all = make_shared<op::All>(x, axes_i64);
ASSERT_TRUE(all->get_output_partial_shape(0).rank().is_dynamic());
auto f = make_shared<Function>(NodeVector{all}, ParameterVector{x, axes});
auto backend = runtime::Backend::create("${BACKEND_NAME}", true);
auto ex = backend->compile(f);
auto t_r = backend->create_dynamic_tensor(element::boolean, PartialShape::dynamic());
std::vector<Shape> x_shapes{
Shape{2, 3}, Shape{2, 3}, Shape{2, 3}, Shape{2, 3}, Shape{5}, Shape{5}};
std::vector<std::vector<int32_t>> axeses{{}, {0}, {1}, {0, 1}, {}, {0}};
std::vector<std::vector<char>> inputs{{1, 0, 1, 0, 1, 0},
{1, 0, 1, 0, 0, 1},
{1, 0, 1, 1, 1, 1},
{1, 0, 1, 0, 1, 0},
{1, 0, 1, 0, 1},
{1, 0, 1, 0, 1}};
std::vector<Shape> expected_result_shapes{
Shape{2, 3}, Shape{3}, Shape{2}, Shape{}, Shape{5}, Shape{}};
std::vector<std::vector<char>> expected_results{
{1, 0, 1, 0, 1, 0}, {0, 0, 1}, {0, 1}, {0}, {1, 0, 1, 0, 1}, {0}};
for (size_t i = 0; i < x_shapes.size(); i++)
{
auto t_x = backend->create_tensor(element::boolean, x_shapes[i]);
auto t_axes = backend->create_tensor(element::i32, Shape{axeses[i].size()});
copy_data(t_x, inputs[i]);
copy_data(t_axes, axeses[i]);
ex->call_with_validate({t_r}, {t_x, t_axes});
ASSERT_EQ(t_r->get_shape(), expected_result_shapes[i]);
auto results = read_vector<char>(t_r);
ASSERT_EQ(results, expected_results[i]);
}
}
template <typename T>
struct RangeTest
{
T start;
T stop;
T step;
Shape expected_result_shape;
std::vector<T> expected_result;
};
// TODO(amprocte): We should test this with more than just int32, but there is a bug in the
// handling of element type-changing that is currently blocking doing that easily.
NGRAPH_TEST(dynamic_${BACKEND_NAME}, range)
{
// Create a graph for f(start,stop,step) = Range(start,stop,step).
auto start = make_shared<op::Parameter>(element::i32, Shape{});
auto stop = make_shared<op::Parameter>(element::i32, Shape{});
auto step = make_shared<op::Parameter>(element::i32, Shape{});
auto range = make_shared<op::Range>(start, stop, step);
ASSERT_TRUE(range->get_output_partial_shape(0).same_scheme(PartialShape::dynamic(1)));
auto f = make_shared<Function>(NodeVector{range}, ParameterVector{start, stop, step});
auto backend = runtime::Backend::create("${BACKEND_NAME}", true);
auto ex = backend->compile(f);
auto t_r = backend->create_dynamic_tensor(element::i32, PartialShape::dynamic());
std::vector<RangeTest<int32_t>> int32_tests = {
RangeTest<int32_t>{0, 10, 1, Shape{10}, {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}},
RangeTest<int32_t>{-5, 6, 3, Shape{4}, {-5, -2, 1, 4}},
RangeTest<int32_t>{10, 0, 1, Shape{0}, {}},
RangeTest<int32_t>{10, 5, -3, Shape{2}, {10, 7}}};
for (auto& test : int32_tests)
{
auto t_start = backend->create_tensor(element::i32, Shape{});
auto t_stop = backend->create_tensor(element::i32, Shape{});
auto t_step = backend->create_tensor(element::i32, Shape{});
copy_data(t_start, std::vector<int32_t>{test.start});
copy_data(t_stop, std::vector<int32_t>{test.stop});
copy_data(t_step, std::vector<int32_t>{test.step});
ex->call_with_validate({t_r}, {t_start, t_stop, t_step});
ASSERT_EQ(t_r->get_element_type(), element::i32);
ASSERT_EQ(t_r->get_shape(), test.expected_result_shape);
auto results = read_vector<int32_t>(t_r);
ASSERT_EQ(results, test.expected_result);
}
}
|
// Goal - match C++ decimal (base 10) integer strings.
// Digit = r(0|..|9)
// PositiveDigit=r(1|..|9)
// Decimal = r(0|(PositiveDigit((|')Digit)*))
#include "gtest/gtest.h"
#include <regex>
#include <string>
using namespace std;
bool IsDecimal(const std::string &candidate) {
regex matcher("(-?(0|([1-9]('?[0-9])*))|\\((0|([1-9]('?[0-9])*))\\))");
return regex_match(candidate,matcher);
}
bool IsDouble(const std::string &candidate) {
regex matcher("-?(0|([1-9]('?[0-9])*))(\\.[0-9]+)?$");
return regex_match(candidate,matcher);
}
bool IsIdentifier(const std::string &candidate) {
regex matcher("[_a-zA-Z][_a-zA-Z0-9]+");
return regex_match(candidate,matcher);
}
TEST(RegEx,DecimalInteger) {
ASSERT_TRUE(IsDecimal("0"));
ASSERT_TRUE(IsDecimal("1"));
ASSERT_TRUE(IsDecimal("1'2'3"));
ASSERT_TRUE(IsDecimal("1'000'000"));
ASSERT_TRUE(IsDecimal("-0"));
ASSERT_TRUE(IsDecimal("-1"));
ASSERT_TRUE(IsDecimal("-1'2'3"));
ASSERT_TRUE(IsDecimal("-1'000'000"));
ASSERT_FALSE(IsDecimal("-"));
ASSERT_FALSE(IsDecimal("00"));
ASSERT_FALSE(IsDecimal("00"));
ASSERT_FALSE(IsDecimal("0001"));
ASSERT_FALSE(IsDecimal("1''000''000"));
ASSERT_FALSE(IsDecimal(".20"));
ASSERT_FALSE(IsDecimal("20."));
}
TEST(RegEx,Double) {
ASSERT_TRUE(IsDouble("1"));
ASSERT_TRUE(IsDouble("123456"));
ASSERT_TRUE(IsDouble("1.234567"));
ASSERT_TRUE(IsDouble("-1"));
ASSERT_TRUE(IsDouble("-1.65768"));
ASSERT_FALSE(IsDouble("HelloMynameISNate"));
ASSERT_FALSE(IsDouble("-"));
ASSERT_FALSE(IsDouble(".384"));
ASSERT_FALSE(IsDouble("16a"));
ASSERT_FALSE(IsDouble("''afdgsee''"));
}
TEST(RegEx,Identifier) {
ASSERT_TRUE(IsIdentifier("Alabama_Tree"));
ASSERT_TRUE(IsIdentifier("_AskiValue_"));
ASSERT_FALSE(IsIdentifier("123456"));
ASSERT_FALSE(IsIdentifier("12_AASF"));
}
|
/*
* Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution.
*
* SPDX-License-Identifier: Apache-2.0 OR MIT
*
*/
#include "SystemComponentFixture.h"
namespace EMotionFX
{
TEST_F(SystemComponentFixture, SystemComponentLoads)
{
ASSERT_TRUE(true);
}
TEST_F(SystemComponentFixture, SystemComponentLoadsAgain)
{
// Having 2 tests that use the SystemComponentFixture ensures that a
// subsequent call to SystemComponent::Activate() that comes after a
// SystemComponent::Deactivate() functions as expected.
ASSERT_TRUE(true);
}
} // end namespace EMotionFX
|
// LIC// ====================================================================
// LIC// This file forms part of oomph-lib, the object-oriented,
// LIC// multi-physics finite-element library, available
// LIC// at http://www.oomph-lib.org.
// LIC//
// LIC// Copyright (C) 2006-2022 Matthias Heil and Andrew Hazel
// LIC//
// LIC// This library is free software; you can redistribute it and/or
// LIC// modify it under the terms of the GNU Lesser General Public
// LIC// License as published by the Free Software Foundation; either
// LIC// version 2.1 of the License, or (at your option) any later version.
// LIC//
// LIC// This library is distributed in the hope that it will be useful,
// LIC// but WITHOUT ANY WARRANTY; without even the implied warranty of
// LIC// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// LIC// Lesser General Public License for more details.
// LIC//
// LIC// You should have received a copy of the GNU Lesser General Public
// LIC// License along with this library; if not, write to the Free Software
// LIC// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
// LIC// 02110-1301 USA.
// LIC//
// LIC// The authors may be contacted at oomph-lib@maths.man.ac.uk.
// LIC//
// LIC//====================================================================
#include "trilinos_solver.h"
namespace oomph
{
/// ////////////////////////////////////////////////////////////////////////////
/// ////////////////////////////////////////////////////////////////////////////
// functions for TrilinosAztecOOSolver class
/// ////////////////////////////////////////////////////////////////////////////
/// ////////////////////////////////////////////////////////////////////////////
//=============================================================================
/// Function which uses problem_pt's get_jacobian(...) function to
/// generate a linear system which is then solved. This function deletes
/// any existing internal data and then generates a new AztecOO solver.
//=============================================================================
void TrilinosAztecOOSolver::solve(Problem* const& problem_pt,
DoubleVector& solution)
{
// MemoryUsage::doc_memory_usage("start of TrilinosAztecOOSolver::solve");
// MemoryUsage::insert_comment_to_continous_top(
// "start of TrilinosAztecOOSolver::solve");
// clean up from previous solve
clean_up_memory();
// if we were previously using a problem based solve then we should delete
// the oomphlib matrix as it was created during the last solve
if (Using_problem_based_solve)
{
delete Oomph_matrix_pt;
Oomph_matrix_pt = NULL;
}
// this is a problem based solve
Using_problem_based_solve = true;
// store the problem_pt
Problem_pt = problem_pt;
// Get oomph-lib Jacobian matrix and residual vector
// record the start time
double start_t = TimingHelpers::timer();
// MemoryUsage::doc_memory_usage("start of get_jacobian()");
// MemoryUsage::insert_comment_to_continous_top("start of
// get_jacobian()");
// create the residual
DoubleVector residual;
// create the jacobian
CRDoubleMatrix* cr_matrix_pt = new CRDoubleMatrix;
Oomph_matrix_pt = cr_matrix_pt;
problem_pt->get_jacobian(residual, *cr_matrix_pt);
this->build_distribution(residual.distribution_pt());
// record the end time and compute the matrix setup time
double end_t = TimingHelpers::timer();
Jacobian_setup_time = end_t - start_t;
if (this->Doc_time)
{
oomph_info << "Time to generate Jacobian [sec] : "
<< Jacobian_setup_time << std::endl;
}
// MemoryUsage::doc_memory_usage("after get_jacobian() in trilinos
// solver"); MemoryUsage::insert_comment_to_continous_top(
// "after get_jacobian() in trilinos solver");
// store the distribution of the solution vector
if (!solution.built())
{
solution.build(this->distribution_pt(), 0.0);
}
LinearAlgebraDistribution solution_dist(solution.distribution_pt());
// redistribute the distribution
solution.redistribute(this->distribution_pt());
// MemoryUsage::doc_memory_usage("before trilinos solve");
// MemoryUsage::insert_comment_to_continous_top("before trilinos solve ");
// continue solving using matrix based solve function
solve(Oomph_matrix_pt, residual, solution);
// MemoryUsage::doc_memory_usage("after trilinos solve");
// MemoryUsage::insert_comment_to_continous_top("after trilinos solve ");
// return to the original distribution
solution.redistribute(&solution_dist);
// MemoryUsage::doc_memory_usage("end of TrilinosAztecOOSolver::solve");
// MemoryUsage::insert_comment_to_continous_top(
// "end of TrilinosAztecOOSolver::solve");
}
//=============================================================================
/// Function to solve the linear system defined by matrix_pt and rhs.
/// \b NOTE 1. The matrix has to be of type CRDoubleMatrix or
/// DistributedCRDoubleMatrix.
/// \b NOTE 2. This function will delete any existing internal data and
/// generate a new AztecOO solver.
//=============================================================================
void TrilinosAztecOOSolver::solve(DoubleMatrixBase* const& matrix_pt,
const DoubleVector& rhs,
DoubleVector& result)
{
// start the timer
double start_t = TimingHelpers::timer();
#ifdef PARANOID
// check that the matrix is square
if (matrix_pt->nrow() != matrix_pt->ncol())
{
std::ostringstream error_message_stream;
error_message_stream << "The matrix at matrix_pt must be square.";
throw OomphLibError(error_message_stream.str(),
OOMPH_CURRENT_FUNCTION,
OOMPH_EXCEPTION_LOCATION);
}
// check that the matrix and the rhs vector have the same nrow()
if (matrix_pt->nrow() != rhs.nrow())
{
std::ostringstream error_message_stream;
error_message_stream
<< "The matrix and the rhs vector must have the same number of rows.";
throw OomphLibError(error_message_stream.str(),
OOMPH_CURRENT_FUNCTION,
OOMPH_EXCEPTION_LOCATION);
}
// if the matrix is distributable then it too should have the same
// communicator as the rhs vector and should not be distributed
CRDoubleMatrix* cr_matrix_pt = dynamic_cast<CRDoubleMatrix*>(matrix_pt);
if (cr_matrix_pt != 0)
{
OomphCommunicator temp_comm(*rhs.distribution_pt()->communicator_pt());
if (!(temp_comm == *cr_matrix_pt->distribution_pt()->communicator_pt()))
{
std::ostringstream error_message_stream;
error_message_stream
<< "The matrix matrix_pt must have the same communicator as the "
"vectors"
<< " rhs and result must have the same communicator";
throw OomphLibError(error_message_stream.str(),
OOMPH_CURRENT_FUNCTION,
OOMPH_EXCEPTION_LOCATION);
}
}
else
{
throw OomphLibError("Matrix must be of type CRDoubleMatrix",
OOMPH_CURRENT_FUNCTION,
OOMPH_EXCEPTION_LOCATION);
}
// if the result vector is setup then check it is not distributed and has
// the same communicator as the rhs vector
if (result.built())
{
if (!(*result.distribution_pt() == *rhs.distribution_pt()))
{
std::ostringstream error_message_stream;
error_message_stream
<< "The result vector distribution has been setup; it must have the "
<< "same distribution as the rhs vector.";
throw OomphLibError(error_message_stream.str(),
OOMPH_CURRENT_FUNCTION,
OOMPH_EXCEPTION_LOCATION);
}
}
#endif
// build the result if not built
if (!result.built())
{
result.build(rhs.distribution_pt(), 0.0);
}
if (Use_iterative_solver_as_preconditioner)
{
// Only call the setup method if this is the first time we call the
// solve method
if (First_time_solve_when_used_as_preconditioner)
{
// setup the solver
solver_setup(matrix_pt);
// Do not call the setup again
First_time_solve_when_used_as_preconditioner = false;
// Enable resolve since we are not going to build the solver, the
// matrix and the wrapper to the preconditioner again
Enable_resolve = true;
}
}
else
{
// setup the solver
solver_setup(matrix_pt);
}
// create Epetra version of r
Epetra_Vector* epetra_r_pt =
TrilinosEpetraHelpers::create_distributed_epetra_vector(rhs);
// create an empty Epetra vector for z
Epetra_Vector* epetra_z_pt =
TrilinosEpetraHelpers::create_distributed_epetra_vector(result);
double start_t_trilinos = TimingHelpers::timer();
// solve the system
solve_using_AztecOO(epetra_r_pt, epetra_z_pt);
double end_t_trilinos = TimingHelpers::timer();
if (this->Doc_time)
{
oomph_info << "Time for trilinos solve itself : "
<< end_t_trilinos - start_t_trilinos << "s" << std::endl;
}
// Copy result to z
TrilinosEpetraHelpers::copy_to_oomphlib_vector(epetra_z_pt, result);
// clean up memory
delete epetra_r_pt;
delete epetra_z_pt;
// delete solver data if required
if (!Enable_resolve)
{
clean_up_memory();
}
// stop timers and compute solve time
double end_t = TimingHelpers::timer();
Linear_solver_solution_time = end_t - start_t;
// output timings and info
if (this->Doc_time)
{
oomph_info << "Time for complete trilinos solve : "
<< Linear_solver_solution_time << "s" << std::endl;
}
}
//=============================================================================
/// Helper function for setting up the solver. Converts the oomph-lib
/// matrices to Epetra matrices, sets up the preconditioner, creates the
/// Trilinos Aztec00 solver and passes in the matrix, preconditioner and
/// parameters.
//=============================================================================
void TrilinosAztecOOSolver::solver_setup(DoubleMatrixBase* const& matrix_pt)
{
// clean up the memory
// - delete all except Oomph_matrix_pt, which may have been set in the
// problem based solve
clean_up_memory();
// cast to CRDoubleMatrix
// note cast check performed in matrix based solve(...) method
CRDoubleMatrix* cast_matrix_pt = dynamic_cast<CRDoubleMatrix*>(matrix_pt);
// store the distribution
// distribution of preconditioner is same as matrix
this->build_distribution(cast_matrix_pt->distribution_pt());
// create the new solver
AztecOO_solver_pt = new AztecOO();
// if the preconditioner is an oomph-lib preconditioner then we set it up
TrilinosPreconditionerBase* trilinos_prec_pt =
dynamic_cast<TrilinosPreconditionerBase*>(Preconditioner_pt);
if (trilinos_prec_pt == 0)
{
if (Setup_preconditioner_before_solve)
{
// setup the preconditioner
// start of prec setup
double prec_setup_start_t = TimingHelpers::timer();
Preconditioner_pt->setup(matrix_pt);
// start of prec setup
double prec_setup_finish_t = TimingHelpers::timer();
if (Doc_time)
{
double t_prec_setup = prec_setup_finish_t - prec_setup_start_t;
oomph_info << "Time for preconditioner setup [sec]: " << t_prec_setup
<< std::endl;
}
#ifdef PARANOID
if (*Preconditioner_pt->distribution_pt() != *this->distribution_pt())
{
std::ostringstream error_message;
error_message << "The oomph-lib preconditioner and the solver must "
<< "have the same distribution";
throw OomphLibError(error_message.str(),
OOMPH_CURRENT_FUNCTION,
OOMPH_EXCEPTION_LOCATION);
}
#endif
}
// wrap the oomphlib preconditioner in the Epetra_Operator derived
// OoomphLibPreconditionerEpetraOperator to allow it to be passed to the
// trilinos preconditioner
Epetra_preconditioner_pt =
new OomphLibPreconditionerEpetraOperator(Preconditioner_pt);
}
// create the matrix
double start_t_matrix = TimingHelpers::timer();
if (Use_aztecoo_workaround_for_epetra_matrix_setup)
{
Epetra_matrix_pt =
TrilinosEpetraHelpers ::create_distributed_epetra_matrix_for_aztecoo(
cast_matrix_pt);
}
else
{
Epetra_matrix_pt =
TrilinosEpetraHelpers ::create_distributed_epetra_matrix(
cast_matrix_pt, cast_matrix_pt->distribution_pt());
}
// record the end time and compute the matrix setup time
double end_t_matrix = TimingHelpers::timer();
if (trilinos_prec_pt == 0)
{
if (Using_problem_based_solve)
{
dynamic_cast<CRDoubleMatrix*>(Oomph_matrix_pt)->clear();
delete Oomph_matrix_pt;
Oomph_matrix_pt = NULL;
}
// delete Oomph-lib matrix if requested
else if (Delete_matrix)
{
dynamic_cast<CRDoubleMatrix*>(matrix_pt)->clear();
}
}
// output times
if (Doc_time)
{
oomph_info << "Time to generate Trilinos matrix : "
<< double(end_t_matrix - start_t_matrix) << "s" << std::endl;
}
// set the matrix
AztecOO_solver_pt->SetUserMatrix(Epetra_matrix_pt);
// set the preconditioner
if (trilinos_prec_pt == 0)
{
AztecOO_solver_pt->SetPrecOperator(Epetra_preconditioner_pt);
}
#ifdef PARANOID
// paranoid check the preconditioner exists
if (Preconditioner_pt == 0)
{
std::ostringstream error_message;
error_message << "Preconditioner_pt == 0. (Remember default "
<< "preconditioner is IdentityPreconditioner)";
throw OomphLibError(
error_message.str(), OOMPH_CURRENT_FUNCTION, OOMPH_EXCEPTION_LOCATION);
}
#endif
// if the preconditioner is a trilinos preconditioner then setup the
// preconditioner
if (trilinos_prec_pt != 0)
{
// only setup the preconditioner if required
if (Setup_preconditioner_before_solve)
{
// start of prec setup
double prec_setup_start_t = TimingHelpers::timer();
// setup the preconditioner
trilinos_prec_pt->set_matrix_pt(matrix_pt);
trilinos_prec_pt->setup(Epetra_matrix_pt);
// set the preconditioner
AztecOO_solver_pt->SetPrecOperator(
trilinos_prec_pt->epetra_operator_pt());
// start of prec setup
double prec_setup_finish_t = TimingHelpers::timer();
if (Doc_time)
{
double t_prec_setup = prec_setup_finish_t - prec_setup_start_t;
oomph_info << "Time for preconditioner setup [sec]: " << t_prec_setup
<< std::endl;
}
}
// delete the oomph-matrix if required
if (Using_problem_based_solve)
{
dynamic_cast<CRDoubleMatrix*>(Oomph_matrix_pt)->clear();
delete Oomph_matrix_pt;
Oomph_matrix_pt = NULL;
}
// delete Oomph-lib matrix if requested
else if (Delete_matrix)
{
dynamic_cast<CRDoubleMatrix*>(matrix_pt)->clear();
}
}
// set solver options
if (Doc_time)
{
AztecOO_solver_pt->SetAztecOption(AZ_output, AZ_warnings);
}
else
{
AztecOO_solver_pt->SetAztecOption(AZ_output, AZ_none);
}
AztecOO_solver_pt->SetAztecOption(AZ_kspace, Max_iter);
// set solver type
switch (Solver_type)
{
case CG:
AztecOO_solver_pt->SetAztecOption(AZ_solver, AZ_cg);
break;
case GMRES:
AztecOO_solver_pt->SetAztecOption(AZ_solver, AZ_gmres);
break;
case BiCGStab:
AztecOO_solver_pt->SetAztecOption(AZ_solver, AZ_bicgstab);
break;
default:
std::ostringstream error_message;
error_message << "Solver_type set to incorrect value. "
<< "Acceptable values are " << CG << ", " << GMRES
<< " and " << BiCGStab << ". Current value is "
<< Solver_type << ".";
throw OomphLibError(error_message.str(),
OOMPH_CURRENT_FUNCTION,
OOMPH_EXCEPTION_LOCATION);
}
}
//=============================================================================
/// Function to resolve a linear system using the existing solver
/// data, allowing a solve with a new right hand side vector. This
/// function must be used after a call to solve(...) with
/// enable_resolve set to true.
//=============================================================================
void TrilinosAztecOOSolver::resolve(const DoubleVector& rhs,
DoubleVector& solution)
{
// start the timer
double start_t = TimingHelpers::timer();
#ifdef PARANOID
if (Epetra_matrix_pt->NumGlobalRows() != static_cast<int>(rhs.nrow()))
{
std::ostringstream error_message;
error_message
<< "The rhs vector and the matrix must have the same number "
<< "of rows.\n"
<< "The rhs vector has " << rhs.nrow() << " rows.\n"
<< "The matrix has " << Epetra_matrix_pt->NumGlobalRows() << " rows.\n";
throw OomphLibError(
error_message.str(), OOMPH_CURRENT_FUNCTION, OOMPH_EXCEPTION_LOCATION);
}
// if the result vector is setup then check it is not distributed and has
// the same communicator as the rhs vector
if (solution.built())
{
if (!(*solution.distribution_pt() == *rhs.distribution_pt()))
{
std::ostringstream error_message_stream;
error_message_stream
<< "The result vector distribution has been setup; it must have the "
<< "same distribution as the rhs vector.";
throw OomphLibError(error_message_stream.str(),
OOMPH_CURRENT_FUNCTION,
OOMPH_EXCEPTION_LOCATION);
}
}
#endif
// build the result if not built
if (!solution.built())
{
solution.build(rhs.distribution_pt(), 0.0);
}
// create Epetra version of r
Epetra_Vector* epetra_r_pt =
TrilinosEpetraHelpers::create_distributed_epetra_vector(rhs);
// create an empty Epetra vector for z
Epetra_Vector* epetra_z_pt =
TrilinosEpetraHelpers::create_distributed_epetra_vector(solution);
// solve the system
solve_using_AztecOO(epetra_r_pt, epetra_z_pt);
// Copy result to z
if (!solution.distribution_built())
{
solution.build(rhs.distribution_pt(), 0.0);
}
TrilinosEpetraHelpers::copy_to_oomphlib_vector(epetra_z_pt, solution);
// clean up memory
delete epetra_r_pt;
delete epetra_z_pt;
double end_t = TimingHelpers::timer();
Linear_solver_solution_time = end_t - start_t;
// output timings and info
if (this->Doc_time)
{
oomph_info << "Time for resolve : "
<< Linear_solver_solution_time << "s" << std::endl;
}
}
//=============================================================================
/// Helper function performs the actual solve once the AztecOO
/// solver is set up (i.e. solver_setup() is called)
//=============================================================================
void TrilinosAztecOOSolver::solve_using_AztecOO(Epetra_Vector*& rhs_pt,
Epetra_Vector*& soln_pt)
{
#ifdef PARANOID
// check the matrix and rhs are of consistent sizes
if (AztecOO_solver_pt == 0)
{
std::ostringstream error_message;
error_message << "Solver must be called with solve(...) "
<< "before resolve(...) to set it up.\n";
throw OomphLibError(
error_message.str(), OOMPH_CURRENT_FUNCTION, OOMPH_EXCEPTION_LOCATION);
}
#endif
// set the vectors
AztecOO_solver_pt->SetLHS(soln_pt);
AztecOO_solver_pt->SetRHS(rhs_pt);
// perform solve
AztecOO_solver_pt->Iterate(Max_iter, Tolerance);
// output iterations and final norm
Iterations = AztecOO_solver_pt->NumIters();
if (Doc_time)
{
double norm = AztecOO_solver_pt->TrueResidual();
oomph_info << "Linear solver iterations : " << Iterations << std::endl;
oomph_info << "Final Relative Residual Norm: " << norm << std::endl;
}
}
/// ////////////////////////////////////////////////////////////////////////////
/// ////////////////////////////////////////////////////////////////////////////
/// ////////////////////////////////////////////////////////////////////////////
} // namespace oomph
|
//========= Copyright � 1996-2006, Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
//=============================================================================//
#include "stdafx.h"
#include <shlobj.h>
#include "GameConfig.h"
#include "EditGameConfigs.h"
#include "hammer.h"
#include "OPTConfigs.h"
#include "ConfigManager.h"
#include "process.h"
#include "Options.h"
#include "TextureBrowser.h"
#include "tier2/vconfig.h"
// memdbgon must be the last include file in a .cpp file!!!
#include <tier0/memdbgon.h>
IMPLEMENT_DYNCREATE(COPTConfigs, CPropertyPage)
//-----------------------------------------------------------------------------
// Purpose: Returns the string value of a registry key
// Input : *pName - name of the subKey to read
// *pReturn - string buffer to receive read string
// size - size of specified buffer
//-----------------------------------------------------------------------------
bool GetPersistentEnvironmentVariable(const char *pName, char *pReturn, int size) {
// Open the key
HKEY hregkey;
if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, VPROJECT_REG_KEY, 0, KEY_QUERY_VALUE, &hregkey) != ERROR_SUCCESS)
return false;
// Get the value
DWORD dwSize = size;
if (RegQueryValueEx(hregkey, pName, NULL, NULL, (LPBYTE) pReturn, &dwSize) != ERROR_SUCCESS)
return false;
// Close the key
RegCloseKey(hregkey);
return true;
}
//-----------------------------------------------------------------------------
// Purpose: Set the registry entry to a string value, under the given subKey
// Input : *pName - name of the subKey to set
// *pValue - string value
//-----------------------------------------------------------------------------
void SetPersistentEnvironmentVariable(const char *pName, const char *pValue) {
HKEY hregkey;
DWORD dwReturnValue = 0;
// Open the key
if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, VPROJECT_REG_KEY, 0, KEY_ALL_ACCESS, &hregkey) != ERROR_SUCCESS)
return;
// Set the value to the string passed in
RegSetValueEx(hregkey, pName, 0, REG_SZ, (const unsigned char *) pValue, (int) strlen(pValue));
// Propagate changes so that environment variables takes immediate effect!
SendMessageTimeout(HWND_BROADCAST, WM_SETTINGCHANGE, 0, (LPARAM) "Environment", SMTO_ABORTIFHUNG, 5000,
&dwReturnValue);
// Close the key
RegCloseKey(hregkey);
}
//-----------------------------------------------------------------------------
// Purpose: Converts a Steam path prefix to %STEAM% and back.
//-----------------------------------------------------------------------------
void EditorUtil_ConvertPath(CString &str, bool bExpand) {
CString strSteamDir;
g_pGameConfig->GetSteamDir(strSteamDir);
CString strSteamUserDir;
g_pGameConfig->GetSteamUserDir(strSteamUserDir);
if (!strSteamDir.GetLength() && !strSteamUserDir.GetLength()) {
// Can't do the token replacement.
return;
}
const char *szSteamDirToken = "$SteamDir";
const char *szSteamUserDirToken = "$SteamUserDir";
char szPathOut[MAX_PATH];
if (bExpand) {
// Replace the tokens with the full strings
if (Q_StrSubst(str, szSteamUserDirToken, strSteamUserDir, szPathOut, sizeof(szPathOut))) {
str = szPathOut;
}
if (Q_StrSubst(str, szSteamDirToken, strSteamDir, szPathOut, sizeof(szPathOut))) {
str = szPathOut;
}
} else {
// Replace the full strings with the tokens
// Go from longest paths to shortest paths to insure the most brief expression.
if (Q_StrSubst(str, strSteamUserDir, szSteamUserDirToken, szPathOut, sizeof(szPathOut))) {
str = szPathOut;
}
if (Q_StrSubst(str, strSteamDir, szSteamDirToken, szPathOut, sizeof(szPathOut))) {
str = szPathOut;
}
}
}
//-----------------------------------------------------------------------------
// Purpose: Exchanges path data between a CString and an edit control, converting
// the Steam path to %STEAM% and back.
//-----------------------------------------------------------------------------
void EditorUtil_TransferPath(CDialog *pDlg, int nIDC, char *szDest, bool bExpand) {
CWnd *pwnd = pDlg->GetDlgItem(nIDC);
if (!pwnd)
return;
CString str;
if (bExpand) {
pwnd->GetWindowText(str);
EditorUtil_ConvertPath(str, true);
strcpy(szDest, str);
} else {
str = szDest;
EditorUtil_ConvertPath(str, false);
pwnd->SetWindowText(str);
}
}
//-----------------------------------------------------------------------------
// Purpose: Constructor.
//-----------------------------------------------------------------------------
COPTConfigs::COPTConfigs(void) : CPropertyPage(COPTConfigs::IDD) {
//{{AFX_DATA_INIT(COPTConfigs)
//}}AFX_DATA_INIT
m_pLastSelConfig = NULL;
m_pInitialSelectedConfig = NULL;
}
//-----------------------------------------------------------------------------
// Purpose: Destructor.
//-----------------------------------------------------------------------------
COPTConfigs::~COPTConfigs(void) {
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : pDX -
//-----------------------------------------------------------------------------
void COPTConfigs::DoDataExchange(CDataExchange *pDX) {
CPropertyPage::DoDataExchange(pDX);
//{{AFX_DATA_MAP(COPTConfigs)
DDX_Control(pDX, IDC_MAPDIR, m_cMapDir);
DDX_Control(pDX, IDC_GAMEEXEDIR, m_cGameExeDir);
DDX_Control(pDX, IDC_MODDIR, m_cModDir);
DDX_Control(pDX, IDC_MAPFORMAT, m_cMapFormat);
DDX_Control(pDX, IDC_CORDON_TEXTURE, m_cCordonTexture);
DDX_Control(pDX, IDC_TEXTUREFORMAT, m_cTextureFormat);
DDX_Control(pDX, IDC_DEFAULTPOINT, m_cDefaultPoint);
DDX_Control(pDX, IDC_DEFAULTENTITY, m_cDefaultSolid);
DDX_Control(pDX, IDC_DATAFILES, m_cGDFiles);
DDX_Control(pDX, IDC_CONFIGURATIONS, m_cConfigs);
DDX_Control(pDX, IDC_DEFAULT_TEXTURE_SCALE, m_cDefaultTextureScale);
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(COPTConfigs, CPropertyPage)
//{{AFX_MSG_MAP(COPTConfigs)
ON_BN_CLICKED(IDC_EDITCONFIGS, OnEditconfigs)
ON_BN_CLICKED(IDC_GDFILE_ADD, OnGdfileAdd)
ON_BN_CLICKED(IDC_GDFILE_EDIT, OnGdfileEdit)
ON_BN_CLICKED(IDC_GDFILE_REMOVE, OnGdfileRemove)
ON_CBN_SELCHANGE(IDC_CONFIGURATIONS, OnSelchangeConfigurations)
ON_BN_CLICKED(IDC_BROWSEMAPDIR, OnBrowsemapdir)
ON_BN_CLICKED(IDC_BROWSEGAMEEXEDIR, OnBrowseGameExeDir)
ON_BN_CLICKED(IDC_BROWSEMODDIR, OnBrowseModDir)
ON_BN_CLICKED(IDC_BROWSE_CORDON_TEXTURE, OnBrowseCordonTexture)
ON_MESSAGE(WM_SETTINGCHANGE, OnSettingChange)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
void COPTConfigs::OnEditconfigs(void) {
SaveInfo(m_pLastSelConfig);
CEditGameConfigs dlg;
dlg.DoModal();
UpdateConfigList();
}
void COPTConfigs::OnGdfileAdd(void) {
if (m_pLastSelConfig == NULL)
return;
char szAppDir[MAX_PATH];
APP()->GetDirectory(DIR_PROGRAM, szAppDir);
// browse for .FGD files
CFileDialog dlg(TRUE, ".fgd", NULL, OFN_HIDEREADONLY | OFN_NOCHANGEDIR | OFN_FILEMUSTEXIST,
"Game Data Files (*.fgd)|*.fgd||");
dlg.m_ofn.lpstrInitialDir = szAppDir;
if (dlg.DoModal() != IDOK)
return;
CString str = dlg.GetPathName();
EditorUtil_ConvertPath(str, false);
m_cGDFiles.AddString(str);
SaveInfo(m_pLastSelConfig);
m_pLastSelConfig->LoadGDFiles();
UpdateEntityLists();
}
void COPTConfigs::OnGdfileEdit(void) {
if (m_pLastSelConfig == NULL)
return;
// edit the selected FGD file
int iCurSel = m_cGDFiles.GetCurSel();
if (iCurSel == LB_ERR)
return;
CString str;
m_cGDFiles.GetText(iCurSel, str);
EditorUtil_ConvertPath(str, true);
// call editor (notepad!)
char szBuf[MAX_PATH];
GetWindowsDirectory(szBuf, MAX_PATH);
strcat(szBuf, "\\notepad.exe");
_spawnl(_P_WAIT, szBuf, szBuf, (LPCTSTR) str, NULL);
m_pLastSelConfig->LoadGDFiles();
UpdateEntityLists();
}
void COPTConfigs::OnGdfileRemove(void) {
if (m_pLastSelConfig == NULL)
return;
int iCurSel = m_cGDFiles.GetCurSel();
if (iCurSel == LB_ERR)
return;
m_cGDFiles.DeleteString(iCurSel);
SaveInfo(m_pLastSelConfig);
m_pLastSelConfig->LoadGDFiles();
UpdateEntityLists();
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : *pConfig -
//-----------------------------------------------------------------------------
void COPTConfigs::SaveInfo(CGameConfig *pConfig) {
if (pConfig == NULL) {
return;
}
// game data files
pConfig->nGDFiles = 0;
pConfig->GDFiles.RemoveAll();
int iSize = m_cGDFiles.GetCount();
for (int i = 0; i < iSize; i++) {
CString str;
m_cGDFiles.GetText(i, str);
EditorUtil_ConvertPath(str, true);
pConfig->GDFiles.Add(str);
++pConfig->nGDFiles;
}
//
// Map file type.
//
int nIndex = m_cMapFormat.GetCurSel();
if (nIndex != CB_ERR) {
pConfig->mapformat = (MAPFORMAT) m_cMapFormat.GetItemData(nIndex);
} else {
pConfig->mapformat = mfHalfLife2;
}
//
// WAD file type.
//
nIndex = m_cTextureFormat.GetCurSel();
if (nIndex != CB_ERR) {
pConfig->SetTextureFormat((TEXTUREFORMAT) m_cTextureFormat.GetItemData(nIndex));
} else {
pConfig->SetTextureFormat(tfVMT);
}
m_cDefaultSolid.GetWindowText(pConfig->szDefaultSolid, sizeof pConfig->szDefaultSolid);
m_cDefaultPoint.GetWindowText(pConfig->szDefaultPoint, sizeof pConfig->szDefaultPoint);
EditorUtil_TransferPath(this, IDC_GAMEEXEDIR, pConfig->m_szGameExeDir, true);
EditorUtil_TransferPath(this, IDC_MODDIR, pConfig->m_szModDir, true);
EditorUtil_TransferPath(this, IDC_MAPDIR, pConfig->szMapDir, true);
char szCordonTexture[MAX_PATH];
m_cCordonTexture.GetWindowText(szCordonTexture, sizeof(szCordonTexture));
pConfig->SetCordonTexture(szCordonTexture);
//
// Default texture scale.
//
char szText[100];
m_cDefaultTextureScale.GetWindowText(szText, sizeof(szText));
float fScale = (float) atof(szText);
if (fScale == 0) {
fScale = 1;
}
pConfig->SetDefaultTextureScale(fScale);
//
// Default lightmap scale.
//
int nLightmapScale = GetDlgItemInt(IDC_DEFAULT_LIGHTMAP_SCALE, NULL, FALSE);
pConfig->SetDefaultLightmapScale(nLightmapScale);
}
void COPTConfigs::OnSelchangeConfigurations(void) {
// save info from controls into last selected config
SaveInfo(m_pLastSelConfig);
m_pLastSelConfig = NULL;
// load info from newly selected config into controls
int iCurSel = m_cConfigs.GetCurSel();
CGameConfig *pConfig = Options.configs.FindConfig(m_cConfigs.GetItemData(iCurSel));
BOOL bKillFields = FALSE;
if (pConfig == NULL) {
bKillFields = TRUE;
}
m_cGDFiles.EnableWindow(!bKillFields);
m_cDefaultPoint.EnableWindow(!bKillFields);
m_cDefaultSolid.EnableWindow(!bKillFields);
m_cTextureFormat.EnableWindow(!bKillFields);
m_cMapFormat.EnableWindow(!bKillFields);
m_cGameExeDir.EnableWindow(!bKillFields);
m_cModDir.EnableWindow(!bKillFields);
m_cMapDir.EnableWindow(!bKillFields);
m_cCordonTexture.EnableWindow(!bKillFields);
if (pConfig == NULL) {
return;
}
m_pLastSelConfig = pConfig;
// load game data files
m_cGDFiles.ResetContent();
for (int i = 0; i < pConfig->nGDFiles; i++) {
CString str(pConfig->GDFiles[i]);
EditorUtil_ConvertPath(str, false);
m_cGDFiles.AddString(str);
}
//
// Select the correct map format.
//
m_cMapFormat.SetCurSel(0);
int nItems = m_cMapFormat.GetCount();
for (int i = 0; i < nItems; i++) {
if (pConfig->mapformat == (MAPFORMAT) m_cMapFormat.GetItemData(i)) {
m_cMapFormat.SetCurSel(i);
break;
}
}
//
// Select the correct texture format.
//
m_cTextureFormat.SetCurSel(0);
nItems = m_cTextureFormat.GetCount();
for (int i = 0; i < nItems; i++) {
if (pConfig->GetTextureFormat() == (TEXTUREFORMAT) m_cTextureFormat.GetItemData(i)) {
m_cTextureFormat.SetCurSel(i);
break;
}
}
EditorUtil_TransferPath(this, IDC_GAMEEXEDIR, pConfig->m_szGameExeDir, false);
EditorUtil_TransferPath(this, IDC_MODDIR, pConfig->m_szModDir, false);
EditorUtil_TransferPath(this, IDC_MAPDIR, pConfig->szMapDir, false);
m_cCordonTexture.SetWindowText(pConfig->GetCordonTexture());
char szText[100];
sprintf(szText, "%g", pConfig->GetDefaultTextureScale());
m_cDefaultTextureScale.SetWindowText(szText);
SetDlgItemInt(IDC_DEFAULT_LIGHTMAP_SCALE, pConfig->GetDefaultLightmapScale(), FALSE);
// load entity type comboboxes and set strings
UpdateEntityLists();
}
void COPTConfigs::UpdateEntityLists(void) {
if (m_pLastSelConfig == NULL)
return;
m_cDefaultPoint.ResetContent();
m_cDefaultSolid.ResetContent();
CGameConfig *pConfig = m_pLastSelConfig;
int nCount = pConfig->GD.GetClassCount();
for (int i = 0; i < nCount; i++) {
GDclass *pClass = pConfig->GD.GetClass(i);
if (pClass->IsBaseClass()) {
continue;
} else if (pClass->IsSolidClass()) {
m_cDefaultSolid.AddString(pClass->GetName());
} else {
m_cDefaultPoint.AddString(pClass->GetName());
}
}
if (pConfig->szDefaultSolid[0] != '\0') {
m_cDefaultSolid.SetWindowText(pConfig->szDefaultSolid);
} else {
m_cDefaultSolid.SetCurSel(0);
}
if (pConfig->szDefaultPoint[0] != '\0') {
m_cDefaultPoint.SetWindowText(pConfig->szDefaultPoint);
} else {
m_cDefaultPoint.SetCurSel(0);
}
}
//-----------------------------------------------------------------------------
// Purpose: Fills the combo box with the list of configs. Tries to select the
// config that was selected before coming in or, failing that, the
// currently active config.
//-----------------------------------------------------------------------------
void UpdateConfigList(CComboBox &combo) {
int iCurSel = combo.GetCurSel();
DWORD dwSelID = 0xffffffff;
if (iCurSel != CB_ERR) {
dwSelID = combo.GetItemData(iCurSel);
}
combo.ResetContent();
// add configs to the combo box
for (int i = 0; i < Options.configs.nConfigs; i++) {
CGameConfig *pConfig = Options.configs.Configs[i];
int iIndex = combo.AddString(pConfig->szName);
combo.SetItemData(iIndex, pConfig->dwID);
}
if (dwSelID == 0xffffffff) {
dwSelID = g_pGameConfig->dwID;
}
// Find the item with the given ID.
int nSelIndex = -1;
for (int i = 0; i < Options.configs.nConfigs; i++) {
DWORD dwData = combo.GetItemData(i);
if (dwData == dwSelID) {
nSelIndex = i;
}
}
combo.SetCurSel(nSelIndex == -1 ? 0 : nSelIndex);
}
void SelectActiveConfig(CComboBox &combo) {
char szGameDir[MAX_PATH];
if (GetPersistentEnvironmentVariable(GAMEDIR_TOKEN, szGameDir, sizeof(szGameDir))) {
CGameConfig *pConfig = Options.configs.FindConfigForGame(szGameDir);
if (pConfig) {
// Find the item with the given ID.
int nSelIndex = -1;
int nCount = combo.GetCount();
for (int i = 0; i < nCount; i++) {
DWORD dwData = combo.GetItemData(i);
if (pConfig->dwID == dwData) {
nSelIndex = i;
break;
}
}
if (nSelIndex != -1) {
combo.SetCurSel(nSelIndex);
}
}
}
}
void COPTConfigs::UpdateConfigList() {
m_pLastSelConfig = NULL;
::UpdateConfigList(m_cConfigs);
::SelectActiveConfig(m_cConfigs);
OnSelchangeConfigurations();
SetModified();
}
//-----------------------------------------------------------------------------
// Purpose: Populates the combo boxes with the map formats and WAD formats, and
// the list of game configurations.
//-----------------------------------------------------------------------------
BOOL COPTConfigs::OnInitDialog(void) {
CPropertyPage::OnInitDialog();
int nIndex;
//
// Add map formats.
//
nIndex = m_cMapFormat.AddString("Half-Life 2");
m_cMapFormat.SetItemData(nIndex, mfHalfLife2);
nIndex = m_cMapFormat.AddString("Half-Life / TFC");
m_cMapFormat.SetItemData(nIndex, mfHalfLife);
//
// Add texture formats.
//
nIndex = m_cTextureFormat.AddString("Materials (Half-Life 2)");
m_cTextureFormat.SetItemData(nIndex, tfVMT);
nIndex = m_cTextureFormat.AddString("WAD3 (Half-Life / TFC)");
m_cTextureFormat.SetItemData(nIndex, tfWAD3);
UpdateConfigList();
int nCurSel = m_cConfigs.GetCurSel();
m_pInitialSelectedConfig = Options.configs.FindConfig(m_cConfigs.GetItemData(nCurSel));
m_strInitialGameDir.Empty();
if (m_pInitialSelectedConfig) {
m_strInitialGameDir = m_pInitialSelectedConfig->m_szModDir;
}
return TRUE;
}
//-----------------------------------------------------------------------------
// Purpose: Returns true if the given config is different from the one set when
// OnInitDialog was called.
//-----------------------------------------------------------------------------
bool COPTConfigs::ConfigChanged(CGameConfig *pConfig) {
if (m_pInitialSelectedConfig != pConfig)
return true;
if (pConfig && m_pInitialSelectedConfig) {
if (m_pInitialSelectedConfig->dwID != pConfig->dwID)
return true;
if (m_strInitialGameDir.CompareNoCase(pConfig->m_szModDir))
return true;
}
return false;
}
//-----------------------------------------------------------------------------
// Purpose:
// Output : Returns TRUE on success, FALSE on failure.
//-----------------------------------------------------------------------------
BOOL COPTConfigs::OnApply(void) {
SaveInfo(m_pLastSelConfig);
int nCurSel = m_cConfigs.GetCurSel();
CGameConfig *pConfig = Options.configs.FindConfig(m_cConfigs.GetItemData(nCurSel));
if (pConfig != NULL && ConfigChanged(pConfig)) {
SetPersistentEnvironmentVariable("vproject", pConfig->m_szModDir);
AfxMessageBox(
"Your changes to the active configuration will not take effect until the next time you run Hammer.");
}
Options.PerformChanges(COptions::secConfigs);
return CPropertyPage::OnApply();
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : *pszTitle -
// *pszDirectory -
// Output : Returns TRUE on success, FALSE on failure.
//-----------------------------------------------------------------------------
BOOL COPTConfigs::BrowseForFolder(char *pszTitle, char *pszDirectory) {
char szTmp[MAX_PATH];
BROWSEINFO bi;
memset(&bi, 0, sizeof bi);
bi.hwndOwner = m_hWnd;
bi.pszDisplayName = szTmp;
bi.lpszTitle = pszTitle;
bi.ulFlags = BIF_RETURNONLYFSDIRS;
LPITEMIDLIST idl = SHBrowseForFolder(&bi);
if (idl == NULL)
return FALSE;
SHGetPathFromIDList(idl, pszDirectory);
CoTaskMemFree(idl);
return TRUE;
}
void COPTConfigs::OnBrowseCordonTexture(void) {
CTextureBrowser *pBrowser = new CTextureBrowser(this);
if (pBrowser != NULL) {
//
// Use the currently selected texture format for browsing.
//
TEXTUREFORMAT eTextureFormat = tfVMT;
int nIndex = m_cTextureFormat.GetCurSel();
if (nIndex != LB_ERR) {
eTextureFormat = (TEXTUREFORMAT) m_cTextureFormat.GetItemData(nIndex);
}
pBrowser->SetTextureFormat(eTextureFormat);
//
// Select the current cordon texture in the texture browser.
//
CString strTex;
m_cCordonTexture.GetWindowText(strTex);
pBrowser->SetInitialTexture(strTex);
if (pBrowser->DoModal() == IDOK) {
m_cCordonTexture.SetWindowText(pBrowser->m_cTextureWindow.szCurTexture);
}
delete pBrowser;
}
}
void COPTConfigs::OnBrowseGameExeDir(void) {
char szTmp[MAX_PATH];
if (!BrowseForFolder("Select Game Executable Directory", szTmp)) {
return;
}
CString str(szTmp);
EditorUtil_ConvertPath(str, false);
m_cGameExeDir.SetWindowText(str);
}
void COPTConfigs::OnBrowseModDir(void) {
char szTmp[MAX_PATH];
if (!BrowseForFolder("Select Mod Directory", szTmp)) {
return;
}
CString str(szTmp);
EditorUtil_ConvertPath(str, false);
m_cModDir.SetWindowText(str);
}
void COPTConfigs::OnBrowsemapdir(void) {
char szTmp[MAX_PATH];
if (!BrowseForFolder("Select Map Directory", szTmp)) {
return;
}
CString str(szTmp);
EditorUtil_ConvertPath(str, false);
m_cMapDir.SetWindowText(str);
}
//-----------------------------------------------------------------------------
// Purpose: Handles the notification from the VCONFIG that the active config has changed.
//-----------------------------------------------------------------------------
LRESULT COPTConfigs::OnSettingChange(WPARAM wParam, LPARAM lParam) {
const char *changedSection = (const char *) lParam;
if (Q_stricmp(changedSection, "Environment") == 0) {
UpdateConfigList();
//SelectActiveConfig();
}
return 0;
}
|
//===- llvm/CodeGen/DwarfDebug.cpp - Dwarf Debug Framework ----------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file contains support for writing dwarf debug info into asm files.
//
//===----------------------------------------------------------------------===//
#include "DwarfDebug.h"
#include "ByteStreamer.h"
#include "DIEHash.h"
#include "DwarfCompileUnit.h"
#include "DwarfExpression.h"
#include "DwarfUnit.h"
#include "llvm/ADT/APInt.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/ADT/Triple.h"
#include "llvm/ADT/Twine.h"
#include "llvm/CodeGen/AsmPrinter.h"
#include "llvm/CodeGen/DIE.h"
#include "llvm/CodeGen/LexicalScopes.h"
#include "llvm/CodeGen/MachineBasicBlock.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/MachineModuleInfo.h"
#include "llvm/CodeGen/MachineOperand.h"
#include "llvm/CodeGen/TargetInstrInfo.h"
#include "llvm/CodeGen/TargetLowering.h"
#include "llvm/CodeGen/TargetRegisterInfo.h"
#include "llvm/CodeGen/TargetSubtargetInfo.h"
#include "llvm/DebugInfo/DWARF/DWARFExpression.h"
#include "llvm/DebugInfo/DWARF/DWARFDataExtractor.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/GlobalVariable.h"
#include "llvm/IR/Module.h"
#include "llvm/MC/MCAsmInfo.h"
#include "llvm/MC/MCContext.h"
#include "llvm/MC/MCSection.h"
#include "llvm/MC/MCStreamer.h"
#include "llvm/MC/MCSymbol.h"
#include "llvm/MC/MCTargetOptions.h"
#include "llvm/MC/MachineLocation.h"
#include "llvm/MC/SectionKind.h"
#include "llvm/Pass.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/MD5.h"
#include "llvm/Support/MathExtras.h"
#include "llvm/Support/Timer.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Target/TargetLoweringObjectFile.h"
#include "llvm/Target/TargetMachine.h"
#include <algorithm>
#include <cstddef>
#include <iterator>
#include <string>
using namespace llvm;
#define DEBUG_TYPE "dwarfdebug"
STATISTIC(NumCSParams, "Number of dbg call site params created");
static cl::opt<bool>
DisableDebugInfoPrinting("disable-debug-info-print", cl::Hidden,
cl::desc("Disable debug info printing"));
static cl::opt<bool> UseDwarfRangesBaseAddressSpecifier(
"use-dwarf-ranges-base-address-specifier", cl::Hidden,
cl::desc("Use base address specifiers in debug_ranges"), cl::init(false));
static cl::opt<bool> GenerateARangeSection("generate-arange-section",
cl::Hidden,
cl::desc("Generate dwarf aranges"),
cl::init(false));
static cl::opt<bool>
GenerateDwarfTypeUnits("generate-type-units", cl::Hidden,
cl::desc("Generate DWARF4 type units."),
cl::init(false));
static cl::opt<bool> SplitDwarfCrossCuReferences(
"split-dwarf-cross-cu-references", cl::Hidden,
cl::desc("Enable cross-cu references in DWO files"), cl::init(false));
enum DefaultOnOff { Default, Enable, Disable };
static cl::opt<DefaultOnOff> UnknownLocations(
"use-unknown-locations", cl::Hidden,
cl::desc("Make an absence of debug location information explicit."),
cl::values(clEnumVal(Default, "At top of block or after label"),
clEnumVal(Enable, "In all cases"), clEnumVal(Disable, "Never")),
cl::init(Default));
static cl::opt<AccelTableKind> AccelTables(
"accel-tables", cl::Hidden, cl::desc("Output dwarf accelerator tables."),
cl::values(clEnumValN(AccelTableKind::Default, "Default",
"Default for platform"),
clEnumValN(AccelTableKind::None, "Disable", "Disabled."),
clEnumValN(AccelTableKind::Apple, "Apple", "Apple"),
clEnumValN(AccelTableKind::Dwarf, "Dwarf", "DWARF")),
cl::init(AccelTableKind::Default));
static cl::opt<DefaultOnOff>
DwarfInlinedStrings("dwarf-inlined-strings", cl::Hidden,
cl::desc("Use inlined strings rather than string section."),
cl::values(clEnumVal(Default, "Default for platform"),
clEnumVal(Enable, "Enabled"),
clEnumVal(Disable, "Disabled")),
cl::init(Default));
static cl::opt<bool>
NoDwarfRangesSection("no-dwarf-ranges-section", cl::Hidden,
cl::desc("Disable emission .debug_ranges section."),
cl::init(false));
static cl::opt<DefaultOnOff> DwarfSectionsAsReferences(
"dwarf-sections-as-references", cl::Hidden,
cl::desc("Use sections+offset as references rather than labels."),
cl::values(clEnumVal(Default, "Default for platform"),
clEnumVal(Enable, "Enabled"), clEnumVal(Disable, "Disabled")),
cl::init(Default));
static cl::opt<bool>
UseGNUDebugMacro("use-gnu-debug-macro", cl::Hidden,
cl::desc("Emit the GNU .debug_macro format with DWARF <5"),
cl::init(false));
enum LinkageNameOption {
DefaultLinkageNames,
AllLinkageNames,
AbstractLinkageNames
};
static cl::opt<LinkageNameOption>
DwarfLinkageNames("dwarf-linkage-names", cl::Hidden,
cl::desc("Which DWARF linkage-name attributes to emit."),
cl::values(clEnumValN(DefaultLinkageNames, "Default",
"Default for platform"),
clEnumValN(AllLinkageNames, "All", "All"),
clEnumValN(AbstractLinkageNames, "Abstract",
"Abstract subprograms")),
cl::init(DefaultLinkageNames));
static cl::opt<unsigned> LocationAnalysisSizeLimit(
"singlevarlocation-input-bb-limit",
cl::desc("Maximum block size to analyze for single-location variables"),
cl::init(30000), cl::Hidden);
static const char *const DWARFGroupName = "dwarf";
static const char *const DWARFGroupDescription = "DWARF Emission";
static const char *const DbgTimerName = "writer";
static const char *const DbgTimerDescription = "DWARF Debug Writer";
static constexpr unsigned ULEB128PadSize = 4;
void DebugLocDwarfExpression::emitOp(uint8_t Op, const char *Comment) {
getActiveStreamer().EmitInt8(
Op, Comment ? Twine(Comment) + " " + dwarf::OperationEncodingString(Op)
: dwarf::OperationEncodingString(Op));
}
void DebugLocDwarfExpression::emitSigned(int64_t Value) {
getActiveStreamer().emitSLEB128(Value, Twine(Value));
}
void DebugLocDwarfExpression::emitUnsigned(uint64_t Value) {
getActiveStreamer().emitULEB128(Value, Twine(Value));
}
void DebugLocDwarfExpression::emitData1(uint8_t Value) {
getActiveStreamer().EmitInt8(Value, Twine(Value));
}
void DebugLocDwarfExpression::emitBaseTypeRef(uint64_t Idx) {
assert(Idx < (1ULL << (ULEB128PadSize * 7)) && "Idx wont fit");
getActiveStreamer().emitULEB128(Idx, Twine(Idx), ULEB128PadSize);
}
bool DebugLocDwarfExpression::isFrameRegister(const TargetRegisterInfo &TRI,
unsigned MachineReg) {
// This information is not available while emitting .debug_loc entries.
return false;
}
void DebugLocDwarfExpression::enableTemporaryBuffer() {
assert(!IsBuffering && "Already buffering?");
if (!TmpBuf)
TmpBuf = std::make_unique<TempBuffer>(OutBS.GenerateComments);
IsBuffering = true;
}
void DebugLocDwarfExpression::disableTemporaryBuffer() { IsBuffering = false; }
unsigned DebugLocDwarfExpression::getTemporaryBufferSize() {
return TmpBuf ? TmpBuf->Bytes.size() : 0;
}
void DebugLocDwarfExpression::commitTemporaryBuffer() {
if (!TmpBuf)
return;
for (auto Byte : enumerate(TmpBuf->Bytes)) {
const char *Comment = (Byte.index() < TmpBuf->Comments.size())
? TmpBuf->Comments[Byte.index()].c_str()
: "";
OutBS.EmitInt8(Byte.value(), Comment);
}
TmpBuf->Bytes.clear();
TmpBuf->Comments.clear();
}
const DIType *DbgVariable::getType() const {
return getVariable()->getType();
}
/// Get .debug_loc entry for the instruction range starting at MI.
static DbgValueLoc getDebugLocValue(const MachineInstr *MI) {
const DIExpression *Expr = MI->getDebugExpression();
assert(MI->getNumOperands() == 4);
if (MI->getDebugOperand(0).isReg()) {
auto RegOp = MI->getDebugOperand(0);
auto Op1 = MI->getDebugOffset();
// If the second operand is an immediate, this is a
// register-indirect address.
assert((!Op1.isImm() || (Op1.getImm() == 0)) && "unexpected offset");
MachineLocation MLoc(RegOp.getReg(), Op1.isImm());
return DbgValueLoc(Expr, MLoc);
}
if (MI->getDebugOperand(0).isTargetIndex()) {
auto Op = MI->getDebugOperand(0);
return DbgValueLoc(Expr,
TargetIndexLocation(Op.getIndex(), Op.getOffset()));
}
if (MI->getDebugOperand(0).isImm())
return DbgValueLoc(Expr, MI->getDebugOperand(0).getImm());
if (MI->getDebugOperand(0).isFPImm())
return DbgValueLoc(Expr, MI->getDebugOperand(0).getFPImm());
if (MI->getDebugOperand(0).isCImm())
return DbgValueLoc(Expr, MI->getDebugOperand(0).getCImm());
llvm_unreachable("Unexpected 4-operand DBG_VALUE instruction!");
}
void DbgVariable::initializeDbgValue(const MachineInstr *DbgValue) {
assert(FrameIndexExprs.empty() && "Already initialized?");
assert(!ValueLoc.get() && "Already initialized?");
assert(getVariable() == DbgValue->getDebugVariable() && "Wrong variable");
assert(getInlinedAt() == DbgValue->getDebugLoc()->getInlinedAt() &&
"Wrong inlined-at");
ValueLoc = std::make_unique<DbgValueLoc>(getDebugLocValue(DbgValue));
if (auto *E = DbgValue->getDebugExpression())
if (E->getNumElements())
FrameIndexExprs.push_back({0, E});
}
ArrayRef<DbgVariable::FrameIndexExpr> DbgVariable::getFrameIndexExprs() const {
if (FrameIndexExprs.size() == 1)
return FrameIndexExprs;
assert(llvm::all_of(FrameIndexExprs,
[](const FrameIndexExpr &A) {
return A.Expr->isFragment();
}) &&
"multiple FI expressions without DW_OP_LLVM_fragment");
llvm::sort(FrameIndexExprs,
[](const FrameIndexExpr &A, const FrameIndexExpr &B) -> bool {
return A.Expr->getFragmentInfo()->OffsetInBits <
B.Expr->getFragmentInfo()->OffsetInBits;
});
return FrameIndexExprs;
}
void DbgVariable::addMMIEntry(const DbgVariable &V) {
assert(DebugLocListIndex == ~0U && !ValueLoc.get() && "not an MMI entry");
assert(V.DebugLocListIndex == ~0U && !V.ValueLoc.get() && "not an MMI entry");
assert(V.getVariable() == getVariable() && "conflicting variable");
assert(V.getInlinedAt() == getInlinedAt() && "conflicting inlined-at location");
assert(!FrameIndexExprs.empty() && "Expected an MMI entry");
assert(!V.FrameIndexExprs.empty() && "Expected an MMI entry");
// FIXME: This logic should not be necessary anymore, as we now have proper
// deduplication. However, without it, we currently run into the assertion
// below, which means that we are likely dealing with broken input, i.e. two
// non-fragment entries for the same variable at different frame indices.
if (FrameIndexExprs.size()) {
auto *Expr = FrameIndexExprs.back().Expr;
if (!Expr || !Expr->isFragment())
return;
}
for (const auto &FIE : V.FrameIndexExprs)
// Ignore duplicate entries.
if (llvm::none_of(FrameIndexExprs, [&](const FrameIndexExpr &Other) {
return FIE.FI == Other.FI && FIE.Expr == Other.Expr;
}))
FrameIndexExprs.push_back(FIE);
assert((FrameIndexExprs.size() == 1 ||
llvm::all_of(FrameIndexExprs,
[](FrameIndexExpr &FIE) {
return FIE.Expr && FIE.Expr->isFragment();
})) &&
"conflicting locations for variable");
}
static AccelTableKind computeAccelTableKind(unsigned DwarfVersion,
bool GenerateTypeUnits,
DebuggerKind Tuning,
const Triple &TT) {
// Honor an explicit request.
if (AccelTables != AccelTableKind::Default)
return AccelTables;
// Accelerator tables with type units are currently not supported.
if (GenerateTypeUnits)
return AccelTableKind::None;
// Accelerator tables get emitted if targetting DWARF v5 or LLDB. DWARF v5
// always implies debug_names. For lower standard versions we use apple
// accelerator tables on apple platforms and debug_names elsewhere.
if (DwarfVersion >= 5)
return AccelTableKind::Dwarf;
if (Tuning == DebuggerKind::LLDB)
return TT.isOSBinFormatMachO() ? AccelTableKind::Apple
: AccelTableKind::Dwarf;
return AccelTableKind::None;
}
DwarfDebug::DwarfDebug(AsmPrinter *A, Module *M)
: DebugHandlerBase(A), DebugLocs(A->OutStreamer->isVerboseAsm()),
InfoHolder(A, "info_string", DIEValueAllocator),
SkeletonHolder(A, "skel_string", DIEValueAllocator),
IsDarwin(A->TM.getTargetTriple().isOSDarwin()) {
const Triple &TT = Asm->TM.getTargetTriple();
// Make sure we know our "debugger tuning". The target option takes
// precedence; fall back to triple-based defaults.
if (Asm->TM.Options.DebuggerTuning != DebuggerKind::Default)
DebuggerTuning = Asm->TM.Options.DebuggerTuning;
else if (IsDarwin)
DebuggerTuning = DebuggerKind::LLDB;
else if (TT.isPS4CPU())
DebuggerTuning = DebuggerKind::SCE;
else
DebuggerTuning = DebuggerKind::GDB;
if (DwarfInlinedStrings == Default)
UseInlineStrings = TT.isNVPTX();
else
UseInlineStrings = DwarfInlinedStrings == Enable;
UseLocSection = !TT.isNVPTX();
HasAppleExtensionAttributes = tuneForLLDB();
// Handle split DWARF.
HasSplitDwarf = !Asm->TM.Options.MCOptions.SplitDwarfFile.empty();
// SCE defaults to linkage names only for abstract subprograms.
if (DwarfLinkageNames == DefaultLinkageNames)
UseAllLinkageNames = !tuneForSCE();
else
UseAllLinkageNames = DwarfLinkageNames == AllLinkageNames;
unsigned DwarfVersionNumber = Asm->TM.Options.MCOptions.DwarfVersion;
unsigned DwarfVersion = DwarfVersionNumber ? DwarfVersionNumber
: MMI->getModule()->getDwarfVersion();
// Use dwarf 4 by default if nothing is requested. For NVPTX, use dwarf 2.
DwarfVersion =
TT.isNVPTX() ? 2 : (DwarfVersion ? DwarfVersion : dwarf::DWARF_VERSION);
UseRangesSection = !NoDwarfRangesSection && !TT.isNVPTX();
// Use sections as references. Force for NVPTX.
if (DwarfSectionsAsReferences == Default)
UseSectionsAsReferences = TT.isNVPTX();
else
UseSectionsAsReferences = DwarfSectionsAsReferences == Enable;
// Don't generate type units for unsupported object file formats.
GenerateTypeUnits =
A->TM.getTargetTriple().isOSBinFormatELF() && GenerateDwarfTypeUnits;
TheAccelTableKind = computeAccelTableKind(
DwarfVersion, GenerateTypeUnits, DebuggerTuning, A->TM.getTargetTriple());
// Work around a GDB bug. GDB doesn't support the standard opcode;
// SCE doesn't support GNU's; LLDB prefers the standard opcode, which
// is defined as of DWARF 3.
// See GDB bug 11616 - DW_OP_form_tls_address is unimplemented
// https://sourceware.org/bugzilla/show_bug.cgi?id=11616
UseGNUTLSOpcode = tuneForGDB() || DwarfVersion < 3;
// GDB does not fully support the DWARF 4 representation for bitfields.
UseDWARF2Bitfields = (DwarfVersion < 4) || tuneForGDB();
// The DWARF v5 string offsets table has - possibly shared - contributions
// from each compile and type unit each preceded by a header. The string
// offsets table used by the pre-DWARF v5 split-DWARF implementation uses
// a monolithic string offsets table without any header.
UseSegmentedStringOffsetsTable = DwarfVersion >= 5;
// Emit call-site-param debug info for GDB and LLDB, if the target supports
// the debug entry values feature. It can also be enabled explicitly.
EmitDebugEntryValues = Asm->TM.Options.ShouldEmitDebugEntryValues();
// It is unclear if the GCC .debug_macro extension is well-specified
// for split DWARF. For now, do not allow LLVM to emit it.
UseDebugMacroSection =
DwarfVersion >= 5 || (UseGNUDebugMacro && !useSplitDwarf());
Asm->OutStreamer->getContext().setDwarfVersion(DwarfVersion);
}
// Define out of line so we don't have to include DwarfUnit.h in DwarfDebug.h.
DwarfDebug::~DwarfDebug() = default;
static bool isObjCClass(StringRef Name) {
return Name.startswith("+") || Name.startswith("-");
}
static bool hasObjCCategory(StringRef Name) {
if (!isObjCClass(Name))
return false;
return Name.find(") ") != StringRef::npos;
}
static void getObjCClassCategory(StringRef In, StringRef &Class,
StringRef &Category) {
if (!hasObjCCategory(In)) {
Class = In.slice(In.find('[') + 1, In.find(' '));
Category = "";
return;
}
Class = In.slice(In.find('[') + 1, In.find('('));
Category = In.slice(In.find('[') + 1, In.find(' '));
}
static StringRef getObjCMethodName(StringRef In) {
return In.slice(In.find(' ') + 1, In.find(']'));
}
// Add the various names to the Dwarf accelerator table names.
void DwarfDebug::addSubprogramNames(const DICompileUnit &CU,
const DISubprogram *SP, DIE &Die) {
if (getAccelTableKind() != AccelTableKind::Apple &&
CU.getNameTableKind() == DICompileUnit::DebugNameTableKind::None)
return;
if (!SP->isDefinition())
return;
if (SP->getName() != "")
addAccelName(CU, SP->getName(), Die);
// If the linkage name is different than the name, go ahead and output that as
// well into the name table. Only do that if we are going to actually emit
// that name.
if (SP->getLinkageName() != "" && SP->getName() != SP->getLinkageName() &&
(useAllLinkageNames() || InfoHolder.getAbstractSPDies().lookup(SP)))
addAccelName(CU, SP->getLinkageName(), Die);
// If this is an Objective-C selector name add it to the ObjC accelerator
// too.
if (isObjCClass(SP->getName())) {
StringRef Class, Category;
getObjCClassCategory(SP->getName(), Class, Category);
addAccelObjC(CU, Class, Die);
if (Category != "")
addAccelObjC(CU, Category, Die);
// Also add the base method name to the name table.
addAccelName(CU, getObjCMethodName(SP->getName()), Die);
}
}
/// Check whether we should create a DIE for the given Scope, return true
/// if we don't create a DIE (the corresponding DIE is null).
bool DwarfDebug::isLexicalScopeDIENull(LexicalScope *Scope) {
if (Scope->isAbstractScope())
return false;
// We don't create a DIE if there is no Range.
const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges();
if (Ranges.empty())
return true;
if (Ranges.size() > 1)
return false;
// We don't create a DIE if we have a single Range and the end label
// is null.
return !getLabelAfterInsn(Ranges.front().second);
}
template <typename Func> static void forBothCUs(DwarfCompileUnit &CU, Func F) {
F(CU);
if (auto *SkelCU = CU.getSkeleton())
if (CU.getCUNode()->getSplitDebugInlining())
F(*SkelCU);
}
bool DwarfDebug::shareAcrossDWOCUs() const {
return SplitDwarfCrossCuReferences;
}
void DwarfDebug::constructAbstractSubprogramScopeDIE(DwarfCompileUnit &SrcCU,
LexicalScope *Scope) {
assert(Scope && Scope->getScopeNode());
assert(Scope->isAbstractScope());
assert(!Scope->getInlinedAt());
auto *SP = cast<DISubprogram>(Scope->getScopeNode());
// Find the subprogram's DwarfCompileUnit in the SPMap in case the subprogram
// was inlined from another compile unit.
if (useSplitDwarf() && !shareAcrossDWOCUs() && !SP->getUnit()->getSplitDebugInlining())
// Avoid building the original CU if it won't be used
SrcCU.constructAbstractSubprogramScopeDIE(Scope);
else {
auto &CU = getOrCreateDwarfCompileUnit(SP->getUnit());
if (auto *SkelCU = CU.getSkeleton()) {
(shareAcrossDWOCUs() ? CU : SrcCU)
.constructAbstractSubprogramScopeDIE(Scope);
if (CU.getCUNode()->getSplitDebugInlining())
SkelCU->constructAbstractSubprogramScopeDIE(Scope);
} else
CU.constructAbstractSubprogramScopeDIE(Scope);
}
}
DIE &DwarfDebug::constructSubprogramDefinitionDIE(const DISubprogram *SP) {
DICompileUnit *Unit = SP->getUnit();
assert(SP->isDefinition() && "Subprogram not a definition");
assert(Unit && "Subprogram definition without parent unit");
auto &CU = getOrCreateDwarfCompileUnit(Unit);
return *CU.getOrCreateSubprogramDIE(SP);
}
/// Represents a parameter whose call site value can be described by applying a
/// debug expression to a register in the forwarded register worklist.
struct FwdRegParamInfo {
/// The described parameter register.
unsigned ParamReg;
/// Debug expression that has been built up when walking through the
/// instruction chain that produces the parameter's value.
const DIExpression *Expr;
};
/// Register worklist for finding call site values.
using FwdRegWorklist = MapVector<unsigned, SmallVector<FwdRegParamInfo, 2>>;
/// Append the expression \p Addition to \p Original and return the result.
static const DIExpression *combineDIExpressions(const DIExpression *Original,
const DIExpression *Addition) {
std::vector<uint64_t> Elts = Addition->getElements().vec();
// Avoid multiple DW_OP_stack_values.
if (Original->isImplicit() && Addition->isImplicit())
erase_if(Elts, [](uint64_t Op) { return Op == dwarf::DW_OP_stack_value; });
const DIExpression *CombinedExpr =
(Elts.size() > 0) ? DIExpression::append(Original, Elts) : Original;
return CombinedExpr;
}
/// Emit call site parameter entries that are described by the given value and
/// debug expression.
template <typename ValT>
static void finishCallSiteParams(ValT Val, const DIExpression *Expr,
ArrayRef<FwdRegParamInfo> DescribedParams,
ParamSet &Params) {
for (auto Param : DescribedParams) {
bool ShouldCombineExpressions = Expr && Param.Expr->getNumElements() > 0;
// TODO: Entry value operations can currently not be combined with any
// other expressions, so we can't emit call site entries in those cases.
if (ShouldCombineExpressions && Expr->isEntryValue())
continue;
// If a parameter's call site value is produced by a chain of
// instructions we may have already created an expression for the
// parameter when walking through the instructions. Append that to the
// base expression.
const DIExpression *CombinedExpr =
ShouldCombineExpressions ? combineDIExpressions(Expr, Param.Expr)
: Expr;
assert((!CombinedExpr || CombinedExpr->isValid()) &&
"Combined debug expression is invalid");
DbgValueLoc DbgLocVal(CombinedExpr, Val);
DbgCallSiteParam CSParm(Param.ParamReg, DbgLocVal);
Params.push_back(CSParm);
++NumCSParams;
}
}
/// Add \p Reg to the worklist, if it's not already present, and mark that the
/// given parameter registers' values can (potentially) be described using
/// that register and an debug expression.
static void addToFwdRegWorklist(FwdRegWorklist &Worklist, unsigned Reg,
const DIExpression *Expr,
ArrayRef<FwdRegParamInfo> ParamsToAdd) {
auto I = Worklist.insert({Reg, {}});
auto &ParamsForFwdReg = I.first->second;
for (auto Param : ParamsToAdd) {
assert(none_of(ParamsForFwdReg,
[Param](const FwdRegParamInfo &D) {
return D.ParamReg == Param.ParamReg;
}) &&
"Same parameter described twice by forwarding reg");
// If a parameter's call site value is produced by a chain of
// instructions we may have already created an expression for the
// parameter when walking through the instructions. Append that to the
// new expression.
const DIExpression *CombinedExpr = combineDIExpressions(Expr, Param.Expr);
ParamsForFwdReg.push_back({Param.ParamReg, CombinedExpr});
}
}
/// Interpret values loaded into registers by \p CurMI.
static void interpretValues(const MachineInstr *CurMI,
FwdRegWorklist &ForwardedRegWorklist,
ParamSet &Params) {
const MachineFunction *MF = CurMI->getMF();
const DIExpression *EmptyExpr =
DIExpression::get(MF->getFunction().getContext(), {});
const auto &TRI = *MF->getSubtarget().getRegisterInfo();
const auto &TII = *MF->getSubtarget().getInstrInfo();
const auto &TLI = *MF->getSubtarget().getTargetLowering();
// If an instruction defines more than one item in the worklist, we may run
// into situations where a worklist register's value is (potentially)
// described by the previous value of another register that is also defined
// by that instruction.
//
// This can for example occur in cases like this:
//
// $r1 = mov 123
// $r0, $r1 = mvrr $r1, 456
// call @foo, $r0, $r1
//
// When describing $r1's value for the mvrr instruction, we need to make sure
// that we don't finalize an entry value for $r0, as that is dependent on the
// previous value of $r1 (123 rather than 456).
//
// In order to not have to distinguish between those cases when finalizing
// entry values, we simply postpone adding new parameter registers to the
// worklist, by first keeping them in this temporary container until the
// instruction has been handled.
FwdRegWorklist TmpWorklistItems;
// If the MI is an instruction defining one or more parameters' forwarding
// registers, add those defines.
auto getForwardingRegsDefinedByMI = [&](const MachineInstr &MI,
SmallSetVector<unsigned, 4> &Defs) {
if (MI.isDebugInstr())
return;
for (const MachineOperand &MO : MI.operands()) {
if (MO.isReg() && MO.isDef() &&
Register::isPhysicalRegister(MO.getReg())) {
for (auto FwdReg : ForwardedRegWorklist)
if (TRI.regsOverlap(FwdReg.first, MO.getReg()))
Defs.insert(FwdReg.first);
}
}
};
// Set of worklist registers that are defined by this instruction.
SmallSetVector<unsigned, 4> FwdRegDefs;
getForwardingRegsDefinedByMI(*CurMI, FwdRegDefs);
if (FwdRegDefs.empty())
return;
for (auto ParamFwdReg : FwdRegDefs) {
if (auto ParamValue = TII.describeLoadedValue(*CurMI, ParamFwdReg)) {
if (ParamValue->first.isImm()) {
int64_t Val = ParamValue->first.getImm();
finishCallSiteParams(Val, ParamValue->second,
ForwardedRegWorklist[ParamFwdReg], Params);
} else if (ParamValue->first.isReg()) {
Register RegLoc = ParamValue->first.getReg();
unsigned SP = TLI.getStackPointerRegisterToSaveRestore();
Register FP = TRI.getFrameRegister(*MF);
bool IsSPorFP = (RegLoc == SP) || (RegLoc == FP);
if (TRI.isCalleeSavedPhysReg(RegLoc, *MF) || IsSPorFP) {
MachineLocation MLoc(RegLoc, /*IsIndirect=*/IsSPorFP);
finishCallSiteParams(MLoc, ParamValue->second,
ForwardedRegWorklist[ParamFwdReg], Params);
} else {
// ParamFwdReg was described by the non-callee saved register
// RegLoc. Mark that the call site values for the parameters are
// dependent on that register instead of ParamFwdReg. Since RegLoc
// may be a register that will be handled in this iteration, we
// postpone adding the items to the worklist, and instead keep them
// in a temporary container.
addToFwdRegWorklist(TmpWorklistItems, RegLoc, ParamValue->second,
ForwardedRegWorklist[ParamFwdReg]);
}
}
}
}
// Remove all registers that this instruction defines from the worklist.
for (auto ParamFwdReg : FwdRegDefs)
ForwardedRegWorklist.erase(ParamFwdReg);
// Now that we are done handling this instruction, add items from the
// temporary worklist to the real one.
for (auto New : TmpWorklistItems)
addToFwdRegWorklist(ForwardedRegWorklist, New.first, EmptyExpr, New.second);
TmpWorklistItems.clear();
}
static bool interpretNextInstr(const MachineInstr *CurMI,
FwdRegWorklist &ForwardedRegWorklist,
ParamSet &Params) {
// Skip bundle headers.
if (CurMI->isBundle())
return true;
// If the next instruction is a call we can not interpret parameter's
// forwarding registers or we finished the interpretation of all
// parameters.
if (CurMI->isCall())
return false;
if (ForwardedRegWorklist.empty())
return false;
// Avoid NOP description.
if (CurMI->getNumOperands() == 0)
return true;
interpretValues(CurMI, ForwardedRegWorklist, Params);
return true;
}
/// Try to interpret values loaded into registers that forward parameters
/// for \p CallMI. Store parameters with interpreted value into \p Params.
static void collectCallSiteParameters(const MachineInstr *CallMI,
ParamSet &Params) {
const MachineFunction *MF = CallMI->getMF();
auto CalleesMap = MF->getCallSitesInfo();
auto CallFwdRegsInfo = CalleesMap.find(CallMI);
// There is no information for the call instruction.
if (CallFwdRegsInfo == CalleesMap.end())
return;
const MachineBasicBlock *MBB = CallMI->getParent();
// Skip the call instruction.
auto I = std::next(CallMI->getReverseIterator());
FwdRegWorklist ForwardedRegWorklist;
const DIExpression *EmptyExpr =
DIExpression::get(MF->getFunction().getContext(), {});
// Add all the forwarding registers into the ForwardedRegWorklist.
for (auto ArgReg : CallFwdRegsInfo->second) {
bool InsertedReg =
ForwardedRegWorklist.insert({ArgReg.Reg, {{ArgReg.Reg, EmptyExpr}}})
.second;
assert(InsertedReg && "Single register used to forward two arguments?");
(void)InsertedReg;
}
// We erase, from the ForwardedRegWorklist, those forwarding registers for
// which we successfully describe a loaded value (by using
// the describeLoadedValue()). For those remaining arguments in the working
// list, for which we do not describe a loaded value by
// the describeLoadedValue(), we try to generate an entry value expression
// for their call site value description, if the call is within the entry MBB.
// TODO: Handle situations when call site parameter value can be described
// as the entry value within basic blocks other than the first one.
bool ShouldTryEmitEntryVals = MBB->getIterator() == MF->begin();
// Search for a loading value in forwarding registers inside call delay slot.
if (CallMI->hasDelaySlot()) {
auto Suc = std::next(CallMI->getIterator());
// Only one-instruction delay slot is supported.
auto BundleEnd = llvm::getBundleEnd(CallMI->getIterator());
(void)BundleEnd;
assert(std::next(Suc) == BundleEnd &&
"More than one instruction in call delay slot");
// Try to interpret value loaded by instruction.
if (!interpretNextInstr(&*Suc, ForwardedRegWorklist, Params))
return;
}
// Search for a loading value in forwarding registers.
for (; I != MBB->rend(); ++I) {
// Try to interpret values loaded by instruction.
if (!interpretNextInstr(&*I, ForwardedRegWorklist, Params))
return;
}
// Emit the call site parameter's value as an entry value.
if (ShouldTryEmitEntryVals) {
// Create an expression where the register's entry value is used.
DIExpression *EntryExpr = DIExpression::get(
MF->getFunction().getContext(), {dwarf::DW_OP_LLVM_entry_value, 1});
for (auto RegEntry : ForwardedRegWorklist) {
MachineLocation MLoc(RegEntry.first);
finishCallSiteParams(MLoc, EntryExpr, RegEntry.second, Params);
}
}
}
void DwarfDebug::constructCallSiteEntryDIEs(const DISubprogram &SP,
DwarfCompileUnit &CU, DIE &ScopeDIE,
const MachineFunction &MF) {
// Add a call site-related attribute (DWARF5, Sec. 3.3.1.3). Do this only if
// the subprogram is required to have one.
if (!SP.areAllCallsDescribed() || !SP.isDefinition())
return;
// Use DW_AT_call_all_calls to express that call site entries are present
// for both tail and non-tail calls. Don't use DW_AT_call_all_source_calls
// because one of its requirements is not met: call site entries for
// optimized-out calls are elided.
CU.addFlag(ScopeDIE, CU.getDwarf5OrGNUAttr(dwarf::DW_AT_call_all_calls));
const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
assert(TII && "TargetInstrInfo not found: cannot label tail calls");
// Delay slot support check.
auto delaySlotSupported = [&](const MachineInstr &MI) {
if (!MI.isBundledWithSucc())
return false;
auto Suc = std::next(MI.getIterator());
auto CallInstrBundle = getBundleStart(MI.getIterator());
(void)CallInstrBundle;
auto DelaySlotBundle = getBundleStart(Suc);
(void)DelaySlotBundle;
// Ensure that label after call is following delay slot instruction.
// Ex. CALL_INSTRUCTION {
// DELAY_SLOT_INSTRUCTION }
// LABEL_AFTER_CALL
assert(getLabelAfterInsn(&*CallInstrBundle) ==
getLabelAfterInsn(&*DelaySlotBundle) &&
"Call and its successor instruction don't have same label after.");
return true;
};
// Emit call site entries for each call or tail call in the function.
for (const MachineBasicBlock &MBB : MF) {
for (const MachineInstr &MI : MBB.instrs()) {
// Bundles with call in them will pass the isCall() test below but do not
// have callee operand information so skip them here. Iterator will
// eventually reach the call MI.
if (MI.isBundle())
continue;
// Skip instructions which aren't calls. Both calls and tail-calling jump
// instructions (e.g TAILJMPd64) are classified correctly here.
if (!MI.isCandidateForCallSiteEntry())
continue;
// Skip instructions marked as frame setup, as they are not interesting to
// the user.
if (MI.getFlag(MachineInstr::FrameSetup))
continue;
// Check if delay slot support is enabled.
if (MI.hasDelaySlot() && !delaySlotSupported(*&MI))
return;
// If this is a direct call, find the callee's subprogram.
// In the case of an indirect call find the register that holds
// the callee.
const MachineOperand &CalleeOp = MI.getOperand(0);
if (!CalleeOp.isGlobal() && !CalleeOp.isReg())
continue;
unsigned CallReg = 0;
DIE *CalleeDIE = nullptr;
const Function *CalleeDecl = nullptr;
if (CalleeOp.isReg()) {
CallReg = CalleeOp.getReg();
if (!CallReg)
continue;
} else {
CalleeDecl = dyn_cast<Function>(CalleeOp.getGlobal());
if (!CalleeDecl || !CalleeDecl->getSubprogram())
continue;
const DISubprogram *CalleeSP = CalleeDecl->getSubprogram();
if (CalleeSP->isDefinition()) {
// Ensure that a subprogram DIE for the callee is available in the
// appropriate CU.
CalleeDIE = &constructSubprogramDefinitionDIE(CalleeSP);
} else {
// Create the declaration DIE if it is missing. This is required to
// support compilation of old bitcode with an incomplete list of
// retained metadata.
CalleeDIE = CU.getOrCreateSubprogramDIE(CalleeSP);
}
assert(CalleeDIE && "Must have a DIE for the callee");
}
// TODO: Omit call site entries for runtime calls (objc_msgSend, etc).
bool IsTail = TII->isTailCall(MI);
// If MI is in a bundle, the label was created after the bundle since
// EmitFunctionBody iterates over top-level MIs. Get that top-level MI
// to search for that label below.
const MachineInstr *TopLevelCallMI =
MI.isInsideBundle() ? &*getBundleStart(MI.getIterator()) : &MI;
// For non-tail calls, the return PC is needed to disambiguate paths in
// the call graph which could lead to some target function. For tail
// calls, no return PC information is needed, unless tuning for GDB in
// DWARF4 mode in which case we fake a return PC for compatibility.
const MCSymbol *PCAddr =
(!IsTail || CU.useGNUAnalogForDwarf5Feature())
? const_cast<MCSymbol *>(getLabelAfterInsn(TopLevelCallMI))
: nullptr;
// For tail calls, it's necessary to record the address of the branch
// instruction so that the debugger can show where the tail call occurred.
const MCSymbol *CallAddr =
IsTail ? getLabelBeforeInsn(TopLevelCallMI) : nullptr;
assert((IsTail || PCAddr) && "Non-tail call without return PC");
LLVM_DEBUG(dbgs() << "CallSiteEntry: " << MF.getName() << " -> "
<< (CalleeDecl ? CalleeDecl->getName()
: StringRef(MF.getSubtarget()
.getRegisterInfo()
->getName(CallReg)))
<< (IsTail ? " [IsTail]" : "") << "\n");
DIE &CallSiteDIE = CU.constructCallSiteEntryDIE(
ScopeDIE, CalleeDIE, IsTail, PCAddr, CallAddr, CallReg);
// Optionally emit call-site-param debug info.
if (emitDebugEntryValues()) {
ParamSet Params;
// Try to interpret values of call site parameters.
collectCallSiteParameters(&MI, Params);
CU.constructCallSiteParmEntryDIEs(CallSiteDIE, Params);
}
}
}
}
void DwarfDebug::addGnuPubAttributes(DwarfCompileUnit &U, DIE &D) const {
if (!U.hasDwarfPubSections())
return;
U.addFlag(D, dwarf::DW_AT_GNU_pubnames);
}
void DwarfDebug::finishUnitAttributes(const DICompileUnit *DIUnit,
DwarfCompileUnit &NewCU) {
DIE &Die = NewCU.getUnitDie();
StringRef FN = DIUnit->getFilename();
StringRef Producer = DIUnit->getProducer();
StringRef Flags = DIUnit->getFlags();
if (!Flags.empty() && !useAppleExtensionAttributes()) {
std::string ProducerWithFlags = Producer.str() + " " + Flags.str();
NewCU.addString(Die, dwarf::DW_AT_producer, ProducerWithFlags);
} else
NewCU.addString(Die, dwarf::DW_AT_producer, Producer);
NewCU.addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
DIUnit->getSourceLanguage());
NewCU.addString(Die, dwarf::DW_AT_name, FN);
StringRef SysRoot = DIUnit->getSysRoot();
if (!SysRoot.empty())
NewCU.addString(Die, dwarf::DW_AT_LLVM_sysroot, SysRoot);
StringRef SDK = DIUnit->getSDK();
if (!SDK.empty())
NewCU.addString(Die, dwarf::DW_AT_APPLE_sdk, SDK);
// Add DW_str_offsets_base to the unit DIE, except for split units.
if (useSegmentedStringOffsetsTable() && !useSplitDwarf())
NewCU.addStringOffsetsStart();
if (!useSplitDwarf()) {
NewCU.initStmtList();
// If we're using split dwarf the compilation dir is going to be in the
// skeleton CU and so we don't need to duplicate it here.
if (!CompilationDir.empty())
NewCU.addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
addGnuPubAttributes(NewCU, Die);
}
if (useAppleExtensionAttributes()) {
if (DIUnit->isOptimized())
NewCU.addFlag(Die, dwarf::DW_AT_APPLE_optimized);
StringRef Flags = DIUnit->getFlags();
if (!Flags.empty())
NewCU.addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
if (unsigned RVer = DIUnit->getRuntimeVersion())
NewCU.addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
dwarf::DW_FORM_data1, RVer);
}
if (DIUnit->getDWOId()) {
// This CU is either a clang module DWO or a skeleton CU.
NewCU.addUInt(Die, dwarf::DW_AT_GNU_dwo_id, dwarf::DW_FORM_data8,
DIUnit->getDWOId());
if (!DIUnit->getSplitDebugFilename().empty()) {
// This is a prefabricated skeleton CU.
dwarf::Attribute attrDWOName = getDwarfVersion() >= 5
? dwarf::DW_AT_dwo_name
: dwarf::DW_AT_GNU_dwo_name;
NewCU.addString(Die, attrDWOName, DIUnit->getSplitDebugFilename());
}
}
}
// Create new DwarfCompileUnit for the given metadata node with tag
// DW_TAG_compile_unit.
DwarfCompileUnit &
DwarfDebug::getOrCreateDwarfCompileUnit(const DICompileUnit *DIUnit) {
if (auto *CU = CUMap.lookup(DIUnit))
return *CU;
CompilationDir = DIUnit->getDirectory();
auto OwnedUnit = std::make_unique<DwarfCompileUnit>(
InfoHolder.getUnits().size(), DIUnit, Asm, this, &InfoHolder);
DwarfCompileUnit &NewCU = *OwnedUnit;
InfoHolder.addUnit(std::move(OwnedUnit));
for (auto *IE : DIUnit->getImportedEntities())
NewCU.addImportedEntity(IE);
// LTO with assembly output shares a single line table amongst multiple CUs.
// To avoid the compilation directory being ambiguous, let the line table
// explicitly describe the directory of all files, never relying on the
// compilation directory.
if (!Asm->OutStreamer->hasRawTextSupport() || SingleCU)
Asm->OutStreamer->emitDwarfFile0Directive(
CompilationDir, DIUnit->getFilename(), getMD5AsBytes(DIUnit->getFile()),
DIUnit->getSource(), NewCU.getUniqueID());
if (useSplitDwarf()) {
NewCU.setSkeleton(constructSkeletonCU(NewCU));
NewCU.setSection(Asm->getObjFileLowering().getDwarfInfoDWOSection());
} else {
finishUnitAttributes(DIUnit, NewCU);
NewCU.setSection(Asm->getObjFileLowering().getDwarfInfoSection());
}
CUMap.insert({DIUnit, &NewCU});
CUDieMap.insert({&NewCU.getUnitDie(), &NewCU});
return NewCU;
}
void DwarfDebug::constructAndAddImportedEntityDIE(DwarfCompileUnit &TheCU,
const DIImportedEntity *N) {
if (isa<DILocalScope>(N->getScope()))
return;
if (DIE *D = TheCU.getOrCreateContextDIE(N->getScope()))
D->addChild(TheCU.constructImportedEntityDIE(N));
}
/// Sort and unique GVEs by comparing their fragment offset.
static SmallVectorImpl<DwarfCompileUnit::GlobalExpr> &
sortGlobalExprs(SmallVectorImpl<DwarfCompileUnit::GlobalExpr> &GVEs) {
llvm::sort(
GVEs, [](DwarfCompileUnit::GlobalExpr A, DwarfCompileUnit::GlobalExpr B) {
// Sort order: first null exprs, then exprs without fragment
// info, then sort by fragment offset in bits.
// FIXME: Come up with a more comprehensive comparator so
// the sorting isn't non-deterministic, and so the following
// std::unique call works correctly.
if (!A.Expr || !B.Expr)
return !!B.Expr;
auto FragmentA = A.Expr->getFragmentInfo();
auto FragmentB = B.Expr->getFragmentInfo();
if (!FragmentA || !FragmentB)
return !!FragmentB;
return FragmentA->OffsetInBits < FragmentB->OffsetInBits;
});
GVEs.erase(std::unique(GVEs.begin(), GVEs.end(),
[](DwarfCompileUnit::GlobalExpr A,
DwarfCompileUnit::GlobalExpr B) {
return A.Expr == B.Expr;
}),
GVEs.end());
return GVEs;
}
// Emit all Dwarf sections that should come prior to the content. Create
// global DIEs and emit initial debug info sections. This is invoked by
// the target AsmPrinter.
void DwarfDebug::beginModule() {
NamedRegionTimer T(DbgTimerName, DbgTimerDescription, DWARFGroupName,
DWARFGroupDescription, TimePassesIsEnabled);
if (DisableDebugInfoPrinting) {
MMI->setDebugInfoAvailability(false);
return;
}
const Module *M = MMI->getModule();
unsigned NumDebugCUs = std::distance(M->debug_compile_units_begin(),
M->debug_compile_units_end());
// Tell MMI whether we have debug info.
assert(MMI->hasDebugInfo() == (NumDebugCUs > 0) &&
"DebugInfoAvailabilty initialized unexpectedly");
SingleCU = NumDebugCUs == 1;
DenseMap<DIGlobalVariable *, SmallVector<DwarfCompileUnit::GlobalExpr, 1>>
GVMap;
for (const GlobalVariable &Global : M->globals()) {
SmallVector<DIGlobalVariableExpression *, 1> GVs;
Global.getDebugInfo(GVs);
for (auto *GVE : GVs)
GVMap[GVE->getVariable()].push_back({&Global, GVE->getExpression()});
}
// Create the symbol that designates the start of the unit's contribution
// to the string offsets table. In a split DWARF scenario, only the skeleton
// unit has the DW_AT_str_offsets_base attribute (and hence needs the symbol).
if (useSegmentedStringOffsetsTable())
(useSplitDwarf() ? SkeletonHolder : InfoHolder)
.setStringOffsetsStartSym(Asm->createTempSymbol("str_offsets_base"));
// Create the symbols that designates the start of the DWARF v5 range list
// and locations list tables. They are located past the table headers.
if (getDwarfVersion() >= 5) {
DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
Holder.setRnglistsTableBaseSym(
Asm->createTempSymbol("rnglists_table_base"));
if (useSplitDwarf())
InfoHolder.setRnglistsTableBaseSym(
Asm->createTempSymbol("rnglists_dwo_table_base"));
}
// Create the symbol that points to the first entry following the debug
// address table (.debug_addr) header.
AddrPool.setLabel(Asm->createTempSymbol("addr_table_base"));
DebugLocs.setSym(Asm->createTempSymbol("loclists_table_base"));
for (DICompileUnit *CUNode : M->debug_compile_units()) {
// FIXME: Move local imported entities into a list attached to the
// subprogram, then this search won't be needed and a
// getImportedEntities().empty() test should go below with the rest.
bool HasNonLocalImportedEntities = llvm::any_of(
CUNode->getImportedEntities(), [](const DIImportedEntity *IE) {
return !isa<DILocalScope>(IE->getScope());
});
if (!HasNonLocalImportedEntities && CUNode->getEnumTypes().empty() &&
CUNode->getRetainedTypes().empty() &&
CUNode->getGlobalVariables().empty() && CUNode->getMacros().empty())
continue;
DwarfCompileUnit &CU = getOrCreateDwarfCompileUnit(CUNode);
// Global Variables.
for (auto *GVE : CUNode->getGlobalVariables()) {
// Don't bother adding DIGlobalVariableExpressions listed in the CU if we
// already know about the variable and it isn't adding a constant
// expression.
auto &GVMapEntry = GVMap[GVE->getVariable()];
auto *Expr = GVE->getExpression();
if (!GVMapEntry.size() || (Expr && Expr->isConstant()))
GVMapEntry.push_back({nullptr, Expr});
}
DenseSet<DIGlobalVariable *> Processed;
for (auto *GVE : CUNode->getGlobalVariables()) {
DIGlobalVariable *GV = GVE->getVariable();
if (Processed.insert(GV).second)
CU.getOrCreateGlobalVariableDIE(GV, sortGlobalExprs(GVMap[GV]));
}
for (auto *Ty : CUNode->getEnumTypes()) {
// The enum types array by design contains pointers to
// MDNodes rather than DIRefs. Unique them here.
CU.getOrCreateTypeDIE(cast<DIType>(Ty));
}
for (auto *Ty : CUNode->getRetainedTypes()) {
// The retained types array by design contains pointers to
// MDNodes rather than DIRefs. Unique them here.
if (DIType *RT = dyn_cast<DIType>(Ty))
// There is no point in force-emitting a forward declaration.
CU.getOrCreateTypeDIE(RT);
}
// Emit imported_modules last so that the relevant context is already
// available.
for (auto *IE : CUNode->getImportedEntities())
constructAndAddImportedEntityDIE(CU, IE);
}
}
void DwarfDebug::finishEntityDefinitions() {
for (const auto &Entity : ConcreteEntities) {
DIE *Die = Entity->getDIE();
assert(Die);
// FIXME: Consider the time-space tradeoff of just storing the unit pointer
// in the ConcreteEntities list, rather than looking it up again here.
// DIE::getUnit isn't simple - it walks parent pointers, etc.
DwarfCompileUnit *Unit = CUDieMap.lookup(Die->getUnitDie());
assert(Unit);
Unit->finishEntityDefinition(Entity.get());
}
}
void DwarfDebug::finishSubprogramDefinitions() {
for (const DISubprogram *SP : ProcessedSPNodes) {
assert(SP->getUnit()->getEmissionKind() != DICompileUnit::NoDebug);
forBothCUs(
getOrCreateDwarfCompileUnit(SP->getUnit()),
[&](DwarfCompileUnit &CU) { CU.finishSubprogramDefinition(SP); });
}
}
void DwarfDebug::finalizeModuleInfo() {
const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
finishSubprogramDefinitions();
finishEntityDefinitions();
// Include the DWO file name in the hash if there's more than one CU.
// This handles ThinLTO's situation where imported CUs may very easily be
// duplicate with the same CU partially imported into another ThinLTO unit.
StringRef DWOName;
if (CUMap.size() > 1)
DWOName = Asm->TM.Options.MCOptions.SplitDwarfFile;
// Handle anything that needs to be done on a per-unit basis after
// all other generation.
for (const auto &P : CUMap) {
auto &TheCU = *P.second;
if (TheCU.getCUNode()->isDebugDirectivesOnly())
continue;
// Emit DW_AT_containing_type attribute to connect types with their
// vtable holding type.
TheCU.constructContainingTypeDIEs();
// Add CU specific attributes if we need to add any.
// If we're splitting the dwarf out now that we've got the entire
// CU then add the dwo id to it.
auto *SkCU = TheCU.getSkeleton();
bool HasSplitUnit = SkCU && !TheCU.getUnitDie().children().empty();
if (HasSplitUnit) {
dwarf::Attribute attrDWOName = getDwarfVersion() >= 5
? dwarf::DW_AT_dwo_name
: dwarf::DW_AT_GNU_dwo_name;
finishUnitAttributes(TheCU.getCUNode(), TheCU);
TheCU.addString(TheCU.getUnitDie(), attrDWOName,
Asm->TM.Options.MCOptions.SplitDwarfFile);
SkCU->addString(SkCU->getUnitDie(), attrDWOName,
Asm->TM.Options.MCOptions.SplitDwarfFile);
// Emit a unique identifier for this CU.
uint64_t ID =
DIEHash(Asm).computeCUSignature(DWOName, TheCU.getUnitDie());
if (getDwarfVersion() >= 5) {
TheCU.setDWOId(ID);
SkCU->setDWOId(ID);
} else {
TheCU.addUInt(TheCU.getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
dwarf::DW_FORM_data8, ID);
SkCU->addUInt(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
dwarf::DW_FORM_data8, ID);
}
if (getDwarfVersion() < 5 && !SkeletonHolder.getRangeLists().empty()) {
const MCSymbol *Sym = TLOF.getDwarfRangesSection()->getBeginSymbol();
SkCU->addSectionLabel(SkCU->getUnitDie(), dwarf::DW_AT_GNU_ranges_base,
Sym, Sym);
}
} else if (SkCU) {
finishUnitAttributes(SkCU->getCUNode(), *SkCU);
}
// If we have code split among multiple sections or non-contiguous
// ranges of code then emit a DW_AT_ranges attribute on the unit that will
// remain in the .o file, otherwise add a DW_AT_low_pc.
// FIXME: We should use ranges allow reordering of code ala
// .subsections_via_symbols in mach-o. This would mean turning on
// ranges for all subprogram DIEs for mach-o.
DwarfCompileUnit &U = SkCU ? *SkCU : TheCU;
if (unsigned NumRanges = TheCU.getRanges().size()) {
if (NumRanges > 1 && useRangesSection())
// A DW_AT_low_pc attribute may also be specified in combination with
// DW_AT_ranges to specify the default base address for use in
// location lists (see Section 2.6.2) and range lists (see Section
// 2.17.3).
U.addUInt(U.getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, 0);
else
U.setBaseAddress(TheCU.getRanges().front().Begin);
U.attachRangesOrLowHighPC(U.getUnitDie(), TheCU.takeRanges());
}
// We don't keep track of which addresses are used in which CU so this
// is a bit pessimistic under LTO.
if ((HasSplitUnit || getDwarfVersion() >= 5) && !AddrPool.isEmpty())
U.addAddrTableBase();
if (getDwarfVersion() >= 5) {
if (U.hasRangeLists())
U.addRnglistsBase();
if (!DebugLocs.getLists().empty()) {
if (!useSplitDwarf())
U.addSectionLabel(U.getUnitDie(), dwarf::DW_AT_loclists_base,
DebugLocs.getSym(),
TLOF.getDwarfLoclistsSection()->getBeginSymbol());
}
}
auto *CUNode = cast<DICompileUnit>(P.first);
// If compile Unit has macros, emit "DW_AT_macro_info/DW_AT_macros"
// attribute.
if (CUNode->getMacros()) {
if (UseDebugMacroSection) {
if (useSplitDwarf())
TheCU.addSectionDelta(
TheCU.getUnitDie(), dwarf::DW_AT_macros, U.getMacroLabelBegin(),
TLOF.getDwarfMacroDWOSection()->getBeginSymbol());
else {
dwarf::Attribute MacrosAttr = getDwarfVersion() >= 5
? dwarf::DW_AT_macros
: dwarf::DW_AT_GNU_macros;
U.addSectionLabel(U.getUnitDie(), MacrosAttr, U.getMacroLabelBegin(),
TLOF.getDwarfMacroSection()->getBeginSymbol());
}
} else {
if (useSplitDwarf())
TheCU.addSectionDelta(
TheCU.getUnitDie(), dwarf::DW_AT_macro_info,
U.getMacroLabelBegin(),
TLOF.getDwarfMacinfoDWOSection()->getBeginSymbol());
else
U.addSectionLabel(U.getUnitDie(), dwarf::DW_AT_macro_info,
U.getMacroLabelBegin(),
TLOF.getDwarfMacinfoSection()->getBeginSymbol());
}
}
}
// Emit all frontend-produced Skeleton CUs, i.e., Clang modules.
for (auto *CUNode : MMI->getModule()->debug_compile_units())
if (CUNode->getDWOId())
getOrCreateDwarfCompileUnit(CUNode);
// Compute DIE offsets and sizes.
InfoHolder.computeSizeAndOffsets();
if (useSplitDwarf())
SkeletonHolder.computeSizeAndOffsets();
}
// Emit all Dwarf sections that should come after the content.
void DwarfDebug::endModule() {
assert(CurFn == nullptr);
assert(CurMI == nullptr);
for (const auto &P : CUMap) {
auto &CU = *P.second;
CU.createBaseTypeDIEs();
}
// If we aren't actually generating debug info (check beginModule -
// conditionalized on !DisableDebugInfoPrinting and the presence of the
// llvm.dbg.cu metadata node)
if (!MMI->hasDebugInfo())
return;
// Finalize the debug info for the module.
finalizeModuleInfo();
if (useSplitDwarf())
// Emit debug_loc.dwo/debug_loclists.dwo section.
emitDebugLocDWO();
else
// Emit debug_loc/debug_loclists section.
emitDebugLoc();
// Corresponding abbreviations into a abbrev section.
emitAbbreviations();
// Emit all the DIEs into a debug info section.
emitDebugInfo();
// Emit info into a debug aranges section.
if (GenerateARangeSection)
emitDebugARanges();
// Emit info into a debug ranges section.
emitDebugRanges();
if (useSplitDwarf())
// Emit info into a debug macinfo.dwo section.
emitDebugMacinfoDWO();
else
// Emit info into a debug macinfo/macro section.
emitDebugMacinfo();
emitDebugStr();
if (useSplitDwarf()) {
emitDebugStrDWO();
emitDebugInfoDWO();
emitDebugAbbrevDWO();
emitDebugLineDWO();
emitDebugRangesDWO();
}
emitDebugAddr();
// Emit info into the dwarf accelerator table sections.
switch (getAccelTableKind()) {
case AccelTableKind::Apple:
emitAccelNames();
emitAccelObjC();
emitAccelNamespaces();
emitAccelTypes();
break;
case AccelTableKind::Dwarf:
emitAccelDebugNames();
break;
case AccelTableKind::None:
break;
case AccelTableKind::Default:
llvm_unreachable("Default should have already been resolved.");
}
// Emit the pubnames and pubtypes sections if requested.
emitDebugPubSections();
// clean up.
// FIXME: AbstractVariables.clear();
}
void DwarfDebug::ensureAbstractEntityIsCreated(DwarfCompileUnit &CU,
const DINode *Node,
const MDNode *ScopeNode) {
if (CU.getExistingAbstractEntity(Node))
return;
CU.createAbstractEntity(Node, LScopes.getOrCreateAbstractScope(
cast<DILocalScope>(ScopeNode)));
}
void DwarfDebug::ensureAbstractEntityIsCreatedIfScoped(DwarfCompileUnit &CU,
const DINode *Node, const MDNode *ScopeNode) {
if (CU.getExistingAbstractEntity(Node))
return;
if (LexicalScope *Scope =
LScopes.findAbstractScope(cast_or_null<DILocalScope>(ScopeNode)))
CU.createAbstractEntity(Node, Scope);
}
// Collect variable information from side table maintained by MF.
void DwarfDebug::collectVariableInfoFromMFTable(
DwarfCompileUnit &TheCU, DenseSet<InlinedEntity> &Processed) {
SmallDenseMap<InlinedEntity, DbgVariable *> MFVars;
LLVM_DEBUG(dbgs() << "DwarfDebug: collecting variables from MF side table\n");
for (const auto &VI : Asm->MF->getVariableDbgInfo()) {
if (!VI.Var)
continue;
assert(VI.Var->isValidLocationForIntrinsic(VI.Loc) &&
"Expected inlined-at fields to agree");
InlinedEntity Var(VI.Var, VI.Loc->getInlinedAt());
Processed.insert(Var);
LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
// If variable scope is not found then skip this variable.
if (!Scope) {
LLVM_DEBUG(dbgs() << "Dropping debug info for " << VI.Var->getName()
<< ", no variable scope found\n");
continue;
}
ensureAbstractEntityIsCreatedIfScoped(TheCU, Var.first, Scope->getScopeNode());
auto RegVar = std::make_unique<DbgVariable>(
cast<DILocalVariable>(Var.first), Var.second);
RegVar->initializeMMI(VI.Expr, VI.Slot);
LLVM_DEBUG(dbgs() << "Created DbgVariable for " << VI.Var->getName()
<< "\n");
if (DbgVariable *DbgVar = MFVars.lookup(Var))
DbgVar->addMMIEntry(*RegVar);
else if (InfoHolder.addScopeVariable(Scope, RegVar.get())) {
MFVars.insert({Var, RegVar.get()});
ConcreteEntities.push_back(std::move(RegVar));
}
}
}
/// Determine whether a *singular* DBG_VALUE is valid for the entirety of its
/// enclosing lexical scope. The check ensures there are no other instructions
/// in the same lexical scope preceding the DBG_VALUE and that its range is
/// either open or otherwise rolls off the end of the scope.
static bool validThroughout(LexicalScopes &LScopes,
const MachineInstr *DbgValue,
const MachineInstr *RangeEnd) {
assert(DbgValue->getDebugLoc() && "DBG_VALUE without a debug location");
auto MBB = DbgValue->getParent();
auto DL = DbgValue->getDebugLoc();
auto *LScope = LScopes.findLexicalScope(DL);
// Scope doesn't exist; this is a dead DBG_VALUE.
if (!LScope)
return false;
auto &LSRange = LScope->getRanges();
if (LSRange.size() == 0)
return false;
// Determine if the DBG_VALUE is valid at the beginning of its lexical block.
const MachineInstr *LScopeBegin = LSRange.front().first;
// Early exit if the lexical scope begins outside of the current block.
if (LScopeBegin->getParent() != MBB)
return false;
// If there are instructions belonging to our scope in another block, and
// we're not a constant (see DWARF2 comment below), then we can't be
// validThroughout.
const MachineInstr *LScopeEnd = LSRange.back().second;
if (RangeEnd && LScopeEnd->getParent() != MBB)
return false;
MachineBasicBlock::const_reverse_iterator Pred(DbgValue);
for (++Pred; Pred != MBB->rend(); ++Pred) {
if (Pred->getFlag(MachineInstr::FrameSetup))
break;
auto PredDL = Pred->getDebugLoc();
if (!PredDL || Pred->isMetaInstruction())
continue;
// Check whether the instruction preceding the DBG_VALUE is in the same
// (sub)scope as the DBG_VALUE.
if (DL->getScope() == PredDL->getScope())
return false;
auto *PredScope = LScopes.findLexicalScope(PredDL);
if (!PredScope || LScope->dominates(PredScope))
return false;
}
// If the range of the DBG_VALUE is open-ended, report success.
if (!RangeEnd)
return true;
// Single, constant DBG_VALUEs in the prologue are promoted to be live
// throughout the function. This is a hack, presumably for DWARF v2 and not
// necessarily correct. It would be much better to use a dbg.declare instead
// if we know the constant is live throughout the scope.
if (DbgValue->getDebugOperand(0).isImm() && MBB->pred_empty())
return true;
// Now check for situations where an "open-ended" DBG_VALUE isn't enough to
// determine eligibility for a single location, e.g. nested scopes, inlined
// functions.
// FIXME: For now we just handle a simple (but common) case where the scope
// is contained in MBB. We could be smarter here.
//
// At this point we know that our scope ends in MBB. So, if RangeEnd exists
// outside of the block we can ignore it; the location is just leaking outside
// its scope.
assert(LScopeEnd->getParent() == MBB && "Scope ends outside MBB");
if (RangeEnd->getParent() != DbgValue->getParent())
return true;
// The location range and variable's enclosing scope are both contained within
// MBB, test if location terminates before end of scope.
for (auto I = RangeEnd->getIterator(); I != MBB->end(); ++I)
if (&*I == LScopeEnd)
return false;
// There's a single location which starts at the scope start, and ends at or
// after the scope end.
return true;
}
/// Build the location list for all DBG_VALUEs in the function that
/// describe the same variable. The resulting DebugLocEntries will have
/// strict monotonically increasing begin addresses and will never
/// overlap. If the resulting list has only one entry that is valid
/// throughout variable's scope return true.
//
// See the definition of DbgValueHistoryMap::Entry for an explanation of the
// different kinds of history map entries. One thing to be aware of is that if
// a debug value is ended by another entry (rather than being valid until the
// end of the function), that entry's instruction may or may not be included in
// the range, depending on if the entry is a clobbering entry (it has an
// instruction that clobbers one or more preceding locations), or if it is an
// (overlapping) debug value entry. This distinction can be seen in the example
// below. The first debug value is ended by the clobbering entry 2, and the
// second and third debug values are ended by the overlapping debug value entry
// 4.
//
// Input:
//
// History map entries [type, end index, mi]
//
// 0 | [DbgValue, 2, DBG_VALUE $reg0, [...] (fragment 0, 32)]
// 1 | | [DbgValue, 4, DBG_VALUE $reg1, [...] (fragment 32, 32)]
// 2 | | [Clobber, $reg0 = [...], -, -]
// 3 | | [DbgValue, 4, DBG_VALUE 123, [...] (fragment 64, 32)]
// 4 [DbgValue, ~0, DBG_VALUE @g, [...] (fragment 0, 96)]
//
// Output [start, end) [Value...]:
//
// [0-1) [(reg0, fragment 0, 32)]
// [1-3) [(reg0, fragment 0, 32), (reg1, fragment 32, 32)]
// [3-4) [(reg1, fragment 32, 32), (123, fragment 64, 32)]
// [4-) [(@g, fragment 0, 96)]
bool DwarfDebug::buildLocationList(
SmallVectorImpl<DebugLocEntry> &DebugLoc,
const DbgValueHistoryMap::Entries &Entries,
DenseSet<const MachineBasicBlock *> &VeryLargeBlocks) {
using OpenRange =
std::pair<DbgValueHistoryMap::EntryIndex, DbgValueLoc>;
SmallVector<OpenRange, 4> OpenRanges;
bool isSafeForSingleLocation = true;
const MachineInstr *StartDebugMI = nullptr;
const MachineInstr *EndMI = nullptr;
for (auto EB = Entries.begin(), EI = EB, EE = Entries.end(); EI != EE; ++EI) {
const MachineInstr *Instr = EI->getInstr();
// Remove all values that are no longer live.
size_t Index = std::distance(EB, EI);
auto Last =
remove_if(OpenRanges, [&](OpenRange &R) { return R.first <= Index; });
OpenRanges.erase(Last, OpenRanges.end());
// If we are dealing with a clobbering entry, this iteration will result in
// a location list entry starting after the clobbering instruction.
const MCSymbol *StartLabel =
EI->isClobber() ? getLabelAfterInsn(Instr) : getLabelBeforeInsn(Instr);
assert(StartLabel &&
"Forgot label before/after instruction starting a range!");
const MCSymbol *EndLabel;
if (std::next(EI) == Entries.end()) {
const MachineBasicBlock &EndMBB = Asm->MF->back();
EndLabel = Asm->MBBSectionRanges[EndMBB.getSectionIDNum()].EndLabel;
if (EI->isClobber())
EndMI = EI->getInstr();
}
else if (std::next(EI)->isClobber())
EndLabel = getLabelAfterInsn(std::next(EI)->getInstr());
else
EndLabel = getLabelBeforeInsn(std::next(EI)->getInstr());
assert(EndLabel && "Forgot label after instruction ending a range!");
if (EI->isDbgValue())
LLVM_DEBUG(dbgs() << "DotDebugLoc: " << *Instr << "\n");
// If this history map entry has a debug value, add that to the list of
// open ranges and check if its location is valid for a single value
// location.
if (EI->isDbgValue()) {
// Do not add undef debug values, as they are redundant information in
// the location list entries. An undef debug results in an empty location
// description. If there are any non-undef fragments then padding pieces
// with empty location descriptions will automatically be inserted, and if
// all fragments are undef then the whole location list entry is
// redundant.
if (!Instr->isUndefDebugValue()) {
auto Value = getDebugLocValue(Instr);
OpenRanges.emplace_back(EI->getEndIndex(), Value);
// TODO: Add support for single value fragment locations.
if (Instr->getDebugExpression()->isFragment())
isSafeForSingleLocation = false;
if (!StartDebugMI)
StartDebugMI = Instr;
} else {
isSafeForSingleLocation = false;
}
}
// Location list entries with empty location descriptions are redundant
// information in DWARF, so do not emit those.
if (OpenRanges.empty())
continue;
// Omit entries with empty ranges as they do not have any effect in DWARF.
if (StartLabel == EndLabel) {
LLVM_DEBUG(dbgs() << "Omitting location list entry with empty range.\n");
continue;
}
SmallVector<DbgValueLoc, 4> Values;
for (auto &R : OpenRanges)
Values.push_back(R.second);
DebugLoc.emplace_back(StartLabel, EndLabel, Values);
// Attempt to coalesce the ranges of two otherwise identical
// DebugLocEntries.
auto CurEntry = DebugLoc.rbegin();
LLVM_DEBUG({
dbgs() << CurEntry->getValues().size() << " Values:\n";
for (auto &Value : CurEntry->getValues())
Value.dump();
dbgs() << "-----\n";
});
auto PrevEntry = std::next(CurEntry);
if (PrevEntry != DebugLoc.rend() && PrevEntry->MergeRanges(*CurEntry))
DebugLoc.pop_back();
}
// If there's a single entry, safe for a single location, and not part of
// an over-sized basic block, then ask validThroughout whether this
// location can be represented as a single variable location.
if (DebugLoc.size() != 1 || !isSafeForSingleLocation)
return false;
if (VeryLargeBlocks.count(StartDebugMI->getParent()))
return false;
return validThroughout(LScopes, StartDebugMI, EndMI);
}
DbgEntity *DwarfDebug::createConcreteEntity(DwarfCompileUnit &TheCU,
LexicalScope &Scope,
const DINode *Node,
const DILocation *Location,
const MCSymbol *Sym) {
ensureAbstractEntityIsCreatedIfScoped(TheCU, Node, Scope.getScopeNode());
if (isa<const DILocalVariable>(Node)) {
ConcreteEntities.push_back(
std::make_unique<DbgVariable>(cast<const DILocalVariable>(Node),
Location));
InfoHolder.addScopeVariable(&Scope,
cast<DbgVariable>(ConcreteEntities.back().get()));
} else if (isa<const DILabel>(Node)) {
ConcreteEntities.push_back(
std::make_unique<DbgLabel>(cast<const DILabel>(Node),
Location, Sym));
InfoHolder.addScopeLabel(&Scope,
cast<DbgLabel>(ConcreteEntities.back().get()));
}
return ConcreteEntities.back().get();
}
// Find variables for each lexical scope.
void DwarfDebug::collectEntityInfo(DwarfCompileUnit &TheCU,
const DISubprogram *SP,
DenseSet<InlinedEntity> &Processed) {
// Grab the variable info that was squirreled away in the MMI side-table.
collectVariableInfoFromMFTable(TheCU, Processed);
// Identify blocks that are unreasonably sized, so that we can later
// skip lexical scope analysis over them.
DenseSet<const MachineBasicBlock *> VeryLargeBlocks;
for (const auto &MBB : *CurFn)
if (MBB.size() > LocationAnalysisSizeLimit)
VeryLargeBlocks.insert(&MBB);
for (const auto &I : DbgValues) {
InlinedEntity IV = I.first;
if (Processed.count(IV))
continue;
// Instruction ranges, specifying where IV is accessible.
const auto &HistoryMapEntries = I.second;
if (HistoryMapEntries.empty())
continue;
LexicalScope *Scope = nullptr;
const DILocalVariable *LocalVar = cast<DILocalVariable>(IV.first);
if (const DILocation *IA = IV.second)
Scope = LScopes.findInlinedScope(LocalVar->getScope(), IA);
else
Scope = LScopes.findLexicalScope(LocalVar->getScope());
// If variable scope is not found then skip this variable.
if (!Scope)
continue;
Processed.insert(IV);
DbgVariable *RegVar = cast<DbgVariable>(createConcreteEntity(TheCU,
*Scope, LocalVar, IV.second));
const MachineInstr *MInsn = HistoryMapEntries.front().getInstr();
assert(MInsn->isDebugValue() && "History must begin with debug value");
// Check if there is a single DBG_VALUE, valid throughout the var's scope.
// If the history map contains a single debug value, there may be an
// additional entry which clobbers the debug value.
size_t HistSize = HistoryMapEntries.size();
bool SingleValueWithClobber =
HistSize == 2 && HistoryMapEntries[1].isClobber();
if (HistSize == 1 || SingleValueWithClobber) {
const auto *End =
SingleValueWithClobber ? HistoryMapEntries[1].getInstr() : nullptr;
if (VeryLargeBlocks.count(MInsn->getParent()) == 0 &&
validThroughout(LScopes, MInsn, End)) {
RegVar->initializeDbgValue(MInsn);
continue;
}
}
// Do not emit location lists if .debug_loc secton is disabled.
if (!useLocSection())
continue;
// Handle multiple DBG_VALUE instructions describing one variable.
DebugLocStream::ListBuilder List(DebugLocs, TheCU, *Asm, *RegVar, *MInsn);
// Build the location list for this variable.
SmallVector<DebugLocEntry, 8> Entries;
bool isValidSingleLocation =
buildLocationList(Entries, HistoryMapEntries, VeryLargeBlocks);
// Check whether buildLocationList managed to merge all locations to one
// that is valid throughout the variable's scope. If so, produce single
// value location.
if (isValidSingleLocation) {
RegVar->initializeDbgValue(Entries[0].getValues()[0]);
continue;
}
// If the variable has a DIBasicType, extract it. Basic types cannot have
// unique identifiers, so don't bother resolving the type with the
// identifier map.
const DIBasicType *BT = dyn_cast<DIBasicType>(
static_cast<const Metadata *>(LocalVar->getType()));
// Finalize the entry by lowering it into a DWARF bytestream.
for (auto &Entry : Entries)
Entry.finalize(*Asm, List, BT, TheCU);
}
// For each InlinedEntity collected from DBG_LABEL instructions, convert to
// DWARF-related DbgLabel.
for (const auto &I : DbgLabels) {
InlinedEntity IL = I.first;
const MachineInstr *MI = I.second;
if (MI == nullptr)
continue;
LexicalScope *Scope = nullptr;
const DILabel *Label = cast<DILabel>(IL.first);
// The scope could have an extra lexical block file.
const DILocalScope *LocalScope =
Label->getScope()->getNonLexicalBlockFileScope();
// Get inlined DILocation if it is inlined label.
if (const DILocation *IA = IL.second)
Scope = LScopes.findInlinedScope(LocalScope, IA);
else
Scope = LScopes.findLexicalScope(LocalScope);
// If label scope is not found then skip this label.
if (!Scope)
continue;
Processed.insert(IL);
/// At this point, the temporary label is created.
/// Save the temporary label to DbgLabel entity to get the
/// actually address when generating Dwarf DIE.
MCSymbol *Sym = getLabelBeforeInsn(MI);
createConcreteEntity(TheCU, *Scope, Label, IL.second, Sym);
}
// Collect info for variables/labels that were optimized out.
for (const DINode *DN : SP->getRetainedNodes()) {
if (!Processed.insert(InlinedEntity(DN, nullptr)).second)
continue;
LexicalScope *Scope = nullptr;
if (auto *DV = dyn_cast<DILocalVariable>(DN)) {
Scope = LScopes.findLexicalScope(DV->getScope());
} else if (auto *DL = dyn_cast<DILabel>(DN)) {
Scope = LScopes.findLexicalScope(DL->getScope());
}
if (Scope)
createConcreteEntity(TheCU, *Scope, DN, nullptr);
}
}
// Process beginning of an instruction.
void DwarfDebug::beginInstruction(const MachineInstr *MI) {
const MachineFunction &MF = *MI->getMF();
const auto *SP = MF.getFunction().getSubprogram();
bool NoDebug =
!SP || SP->getUnit()->getEmissionKind() == DICompileUnit::NoDebug;
// Delay slot support check.
auto delaySlotSupported = [](const MachineInstr &MI) {
if (!MI.isBundledWithSucc())
return false;
auto Suc = std::next(MI.getIterator());
(void)Suc;
// Ensure that delay slot instruction is successor of the call instruction.
// Ex. CALL_INSTRUCTION {
// DELAY_SLOT_INSTRUCTION }
assert(Suc->isBundledWithPred() &&
"Call bundle instructions are out of order");
return true;
};
// When describing calls, we need a label for the call instruction.
if (!NoDebug && SP->areAllCallsDescribed() &&
MI->isCandidateForCallSiteEntry(MachineInstr::AnyInBundle) &&
(!MI->hasDelaySlot() || delaySlotSupported(*MI))) {
const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
bool IsTail = TII->isTailCall(*MI);
// For tail calls, we need the address of the branch instruction for
// DW_AT_call_pc.
if (IsTail)
requestLabelBeforeInsn(MI);
// For non-tail calls, we need the return address for the call for
// DW_AT_call_return_pc. Under GDB tuning, this information is needed for
// tail calls as well.
requestLabelAfterInsn(MI);
}
DebugHandlerBase::beginInstruction(MI);
assert(CurMI);
if (NoDebug)
return;
// Check if source location changes, but ignore DBG_VALUE and CFI locations.
// If the instruction is part of the function frame setup code, do not emit
// any line record, as there is no correspondence with any user code.
if (MI->isMetaInstruction() || MI->getFlag(MachineInstr::FrameSetup))
return;
const DebugLoc &DL = MI->getDebugLoc();
// When we emit a line-0 record, we don't update PrevInstLoc; so look at
// the last line number actually emitted, to see if it was line 0.
unsigned LastAsmLine =
Asm->OutStreamer->getContext().getCurrentDwarfLoc().getLine();
if (DL == PrevInstLoc) {
// If we have an ongoing unspecified location, nothing to do here.
if (!DL)
return;
// We have an explicit location, same as the previous location.
// But we might be coming back to it after a line 0 record.
if (LastAsmLine == 0 && DL.getLine() != 0) {
// Reinstate the source location but not marked as a statement.
const MDNode *Scope = DL.getScope();
recordSourceLine(DL.getLine(), DL.getCol(), Scope, /*Flags=*/0);
}
return;
}
if (!DL) {
// We have an unspecified location, which might want to be line 0.
// If we have already emitted a line-0 record, don't repeat it.
if (LastAsmLine == 0)
return;
// If user said Don't Do That, don't do that.
if (UnknownLocations == Disable)
return;
// See if we have a reason to emit a line-0 record now.
// Reasons to emit a line-0 record include:
// - User asked for it (UnknownLocations).
// - Instruction has a label, so it's referenced from somewhere else,
// possibly debug information; we want it to have a source location.
// - Instruction is at the top of a block; we don't want to inherit the
// location from the physically previous (maybe unrelated) block.
if (UnknownLocations == Enable || PrevLabel ||
(PrevInstBB && PrevInstBB != MI->getParent())) {
// Preserve the file and column numbers, if we can, to save space in
// the encoded line table.
// Do not update PrevInstLoc, it remembers the last non-0 line.
const MDNode *Scope = nullptr;
unsigned Column = 0;
if (PrevInstLoc) {
Scope = PrevInstLoc.getScope();
Column = PrevInstLoc.getCol();
}
recordSourceLine(/*Line=*/0, Column, Scope, /*Flags=*/0);
}
return;
}
// We have an explicit location, different from the previous location.
// Don't repeat a line-0 record, but otherwise emit the new location.
// (The new location might be an explicit line 0, which we do emit.)
if (DL.getLine() == 0 && LastAsmLine == 0)
return;
unsigned Flags = 0;
if (DL == PrologEndLoc) {
Flags |= DWARF2_FLAG_PROLOGUE_END | DWARF2_FLAG_IS_STMT;
PrologEndLoc = DebugLoc();
}
// If the line changed, we call that a new statement; unless we went to
// line 0 and came back, in which case it is not a new statement.
unsigned OldLine = PrevInstLoc ? PrevInstLoc.getLine() : LastAsmLine;
if (DL.getLine() && DL.getLine() != OldLine)
Flags |= DWARF2_FLAG_IS_STMT;
const MDNode *Scope = DL.getScope();
recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
// If we're not at line 0, remember this location.
if (DL.getLine())
PrevInstLoc = DL;
}
static DebugLoc findPrologueEndLoc(const MachineFunction *MF) {
// First known non-DBG_VALUE and non-frame setup location marks
// the beginning of the function body.
for (const auto &MBB : *MF)
for (const auto &MI : MBB)
if (!MI.isMetaInstruction() && !MI.getFlag(MachineInstr::FrameSetup) &&
MI.getDebugLoc())
return MI.getDebugLoc();
return DebugLoc();
}
/// Register a source line with debug info. Returns the unique label that was
/// emitted and which provides correspondence to the source line list.
static void recordSourceLine(AsmPrinter &Asm, unsigned Line, unsigned Col,
const MDNode *S, unsigned Flags, unsigned CUID,
uint16_t DwarfVersion,
ArrayRef<std::unique_ptr<DwarfCompileUnit>> DCUs) {
StringRef Fn;
unsigned FileNo = 1;
unsigned Discriminator = 0;
if (auto *Scope = cast_or_null<DIScope>(S)) {
Fn = Scope->getFilename();
if (Line != 0 && DwarfVersion >= 4)
if (auto *LBF = dyn_cast<DILexicalBlockFile>(Scope))
Discriminator = LBF->getDiscriminator();
FileNo = static_cast<DwarfCompileUnit &>(*DCUs[CUID])
.getOrCreateSourceID(Scope->getFile());
}
Asm.OutStreamer->emitDwarfLocDirective(FileNo, Line, Col, Flags, 0,
Discriminator, Fn);
}
DebugLoc DwarfDebug::emitInitialLocDirective(const MachineFunction &MF,
unsigned CUID) {
// Get beginning of function.
if (DebugLoc PrologEndLoc = findPrologueEndLoc(&MF)) {
// Ensure the compile unit is created if the function is called before
// beginFunction().
(void)getOrCreateDwarfCompileUnit(
MF.getFunction().getSubprogram()->getUnit());
// We'd like to list the prologue as "not statements" but GDB behaves
// poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
const DISubprogram *SP = PrologEndLoc->getInlinedAtScope()->getSubprogram();
::recordSourceLine(*Asm, SP->getScopeLine(), 0, SP, DWARF2_FLAG_IS_STMT,
CUID, getDwarfVersion(), getUnits());
return PrologEndLoc;
}
return DebugLoc();
}
// Gather pre-function debug information. Assumes being called immediately
// after the function entry point has been emitted.
void DwarfDebug::beginFunctionImpl(const MachineFunction *MF) {
CurFn = MF;
auto *SP = MF->getFunction().getSubprogram();
assert(LScopes.empty() || SP == LScopes.getCurrentFunctionScope()->getScopeNode());
if (SP->getUnit()->getEmissionKind() == DICompileUnit::NoDebug)
return;
DwarfCompileUnit &CU = getOrCreateDwarfCompileUnit(SP->getUnit());
// Set DwarfDwarfCompileUnitID in MCContext to the Compile Unit this function
// belongs to so that we add to the correct per-cu line table in the
// non-asm case.
if (Asm->OutStreamer->hasRawTextSupport())
// Use a single line table if we are generating assembly.
Asm->OutStreamer->getContext().setDwarfCompileUnitID(0);
else
Asm->OutStreamer->getContext().setDwarfCompileUnitID(CU.getUniqueID());
// Record beginning of function.
PrologEndLoc = emitInitialLocDirective(
*MF, Asm->OutStreamer->getContext().getDwarfCompileUnitID());
}
void DwarfDebug::skippedNonDebugFunction() {
// If we don't have a subprogram for this function then there will be a hole
// in the range information. Keep note of this by setting the previously used
// section to nullptr.
PrevCU = nullptr;
CurFn = nullptr;
}
// Gather and emit post-function debug information.
void DwarfDebug::endFunctionImpl(const MachineFunction *MF) {
const DISubprogram *SP = MF->getFunction().getSubprogram();
assert(CurFn == MF &&
"endFunction should be called with the same function as beginFunction");
// Set DwarfDwarfCompileUnitID in MCContext to default value.
Asm->OutStreamer->getContext().setDwarfCompileUnitID(0);
LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
assert(!FnScope || SP == FnScope->getScopeNode());
DwarfCompileUnit &TheCU = *CUMap.lookup(SP->getUnit());
if (TheCU.getCUNode()->isDebugDirectivesOnly()) {
PrevLabel = nullptr;
CurFn = nullptr;
return;
}
DenseSet<InlinedEntity> Processed;
collectEntityInfo(TheCU, SP, Processed);
// Add the range of this function to the list of ranges for the CU.
// With basic block sections, add ranges for all basic block sections.
for (const auto &R : Asm->MBBSectionRanges)
TheCU.addRange({R.second.BeginLabel, R.second.EndLabel});
// Under -gmlt, skip building the subprogram if there are no inlined
// subroutines inside it. But with -fdebug-info-for-profiling, the subprogram
// is still needed as we need its source location.
if (!TheCU.getCUNode()->getDebugInfoForProfiling() &&
TheCU.getCUNode()->getEmissionKind() == DICompileUnit::LineTablesOnly &&
LScopes.getAbstractScopesList().empty() && !IsDarwin) {
assert(InfoHolder.getScopeVariables().empty());
PrevLabel = nullptr;
CurFn = nullptr;
return;
}
#ifndef NDEBUG
size_t NumAbstractScopes = LScopes.getAbstractScopesList().size();
#endif
// Construct abstract scopes.
for (LexicalScope *AScope : LScopes.getAbstractScopesList()) {
auto *SP = cast<DISubprogram>(AScope->getScopeNode());
for (const DINode *DN : SP->getRetainedNodes()) {
if (!Processed.insert(InlinedEntity(DN, nullptr)).second)
continue;
const MDNode *Scope = nullptr;
if (auto *DV = dyn_cast<DILocalVariable>(DN))
Scope = DV->getScope();
else if (auto *DL = dyn_cast<DILabel>(DN))
Scope = DL->getScope();
else
llvm_unreachable("Unexpected DI type!");
// Collect info for variables/labels that were optimized out.
ensureAbstractEntityIsCreated(TheCU, DN, Scope);
assert(LScopes.getAbstractScopesList().size() == NumAbstractScopes
&& "ensureAbstractEntityIsCreated inserted abstract scopes");
}
constructAbstractSubprogramScopeDIE(TheCU, AScope);
}
ProcessedSPNodes.insert(SP);
DIE &ScopeDIE = TheCU.constructSubprogramScopeDIE(SP, FnScope);
if (auto *SkelCU = TheCU.getSkeleton())
if (!LScopes.getAbstractScopesList().empty() &&
TheCU.getCUNode()->getSplitDebugInlining())
SkelCU->constructSubprogramScopeDIE(SP, FnScope);
// Construct call site entries.
constructCallSiteEntryDIEs(*SP, TheCU, ScopeDIE, *MF);
// Clear debug info
// Ownership of DbgVariables is a bit subtle - ScopeVariables owns all the
// DbgVariables except those that are also in AbstractVariables (since they
// can be used cross-function)
InfoHolder.getScopeVariables().clear();
InfoHolder.getScopeLabels().clear();
PrevLabel = nullptr;
CurFn = nullptr;
}
// Register a source line with debug info. Returns the unique label that was
// emitted and which provides correspondence to the source line list.
void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
unsigned Flags) {
::recordSourceLine(*Asm, Line, Col, S, Flags,
Asm->OutStreamer->getContext().getDwarfCompileUnitID(),
getDwarfVersion(), getUnits());
}
//===----------------------------------------------------------------------===//
// Emit Methods
//===----------------------------------------------------------------------===//
// Emit the debug info section.
void DwarfDebug::emitDebugInfo() {
DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
Holder.emitUnits(/* UseOffsets */ false);
}
// Emit the abbreviation section.
void DwarfDebug::emitAbbreviations() {
DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
Holder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
}
void DwarfDebug::emitStringOffsetsTableHeader() {
DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
Holder.getStringPool().emitStringOffsetsTableHeader(
*Asm, Asm->getObjFileLowering().getDwarfStrOffSection(),
Holder.getStringOffsetsStartSym());
}
template <typename AccelTableT>
void DwarfDebug::emitAccel(AccelTableT &Accel, MCSection *Section,
StringRef TableName) {
Asm->OutStreamer->SwitchSection(Section);
// Emit the full data.
emitAppleAccelTable(Asm, Accel, TableName, Section->getBeginSymbol());
}
void DwarfDebug::emitAccelDebugNames() {
// Don't emit anything if we have no compilation units to index.
if (getUnits().empty())
return;
emitDWARF5AccelTable(Asm, AccelDebugNames, *this, getUnits());
}
// Emit visible names into a hashed accelerator table section.
void DwarfDebug::emitAccelNames() {
emitAccel(AccelNames, Asm->getObjFileLowering().getDwarfAccelNamesSection(),
"Names");
}
// Emit objective C classes and categories into a hashed accelerator table
// section.
void DwarfDebug::emitAccelObjC() {
emitAccel(AccelObjC, Asm->getObjFileLowering().getDwarfAccelObjCSection(),
"ObjC");
}
// Emit namespace dies into a hashed accelerator table.
void DwarfDebug::emitAccelNamespaces() {
emitAccel(AccelNamespace,
Asm->getObjFileLowering().getDwarfAccelNamespaceSection(),
"namespac");
}
// Emit type dies into a hashed accelerator table.
void DwarfDebug::emitAccelTypes() {
emitAccel(AccelTypes, Asm->getObjFileLowering().getDwarfAccelTypesSection(),
"types");
}
// Public name handling.
// The format for the various pubnames:
//
// dwarf pubnames - offset/name pairs where the offset is the offset into the CU
// for the DIE that is named.
//
// gnu pubnames - offset/index value/name tuples where the offset is the offset
// into the CU and the index value is computed according to the type of value
// for the DIE that is named.
//
// For type units the offset is the offset of the skeleton DIE. For split dwarf
// it's the offset within the debug_info/debug_types dwo section, however, the
// reference in the pubname header doesn't change.
/// computeIndexValue - Compute the gdb index value for the DIE and CU.
static dwarf::PubIndexEntryDescriptor computeIndexValue(DwarfUnit *CU,
const DIE *Die) {
// Entities that ended up only in a Type Unit reference the CU instead (since
// the pub entry has offsets within the CU there's no real offset that can be
// provided anyway). As it happens all such entities (namespaces and types,
// types only in C++ at that) are rendered as TYPE+EXTERNAL. If this turns out
// not to be true it would be necessary to persist this information from the
// point at which the entry is added to the index data structure - since by
// the time the index is built from that, the original type/namespace DIE in a
// type unit has already been destroyed so it can't be queried for properties
// like tag, etc.
if (Die->getTag() == dwarf::DW_TAG_compile_unit)
return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE,
dwarf::GIEL_EXTERNAL);
dwarf::GDBIndexEntryLinkage Linkage = dwarf::GIEL_STATIC;
// We could have a specification DIE that has our most of our knowledge,
// look for that now.
if (DIEValue SpecVal = Die->findAttribute(dwarf::DW_AT_specification)) {
DIE &SpecDIE = SpecVal.getDIEEntry().getEntry();
if (SpecDIE.findAttribute(dwarf::DW_AT_external))
Linkage = dwarf::GIEL_EXTERNAL;
} else if (Die->findAttribute(dwarf::DW_AT_external))
Linkage = dwarf::GIEL_EXTERNAL;
switch (Die->getTag()) {
case dwarf::DW_TAG_class_type:
case dwarf::DW_TAG_structure_type:
case dwarf::DW_TAG_union_type:
case dwarf::DW_TAG_enumeration_type:
return dwarf::PubIndexEntryDescriptor(
dwarf::GIEK_TYPE,
dwarf::isCPlusPlus((dwarf::SourceLanguage)CU->getLanguage())
? dwarf::GIEL_EXTERNAL
: dwarf::GIEL_STATIC);
case dwarf::DW_TAG_typedef:
case dwarf::DW_TAG_base_type:
case dwarf::DW_TAG_subrange_type:
return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, dwarf::GIEL_STATIC);
case dwarf::DW_TAG_namespace:
return dwarf::GIEK_TYPE;
case dwarf::DW_TAG_subprogram:
return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_FUNCTION, Linkage);
case dwarf::DW_TAG_variable:
return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, Linkage);
case dwarf::DW_TAG_enumerator:
return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE,
dwarf::GIEL_STATIC);
default:
return dwarf::GIEK_NONE;
}
}
/// emitDebugPubSections - Emit visible names and types into debug pubnames and
/// pubtypes sections.
void DwarfDebug::emitDebugPubSections() {
for (const auto &NU : CUMap) {
DwarfCompileUnit *TheU = NU.second;
if (!TheU->hasDwarfPubSections())
continue;
bool GnuStyle = TheU->getCUNode()->getNameTableKind() ==
DICompileUnit::DebugNameTableKind::GNU;
Asm->OutStreamer->SwitchSection(
GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubNamesSection()
: Asm->getObjFileLowering().getDwarfPubNamesSection());
emitDebugPubSection(GnuStyle, "Names", TheU, TheU->getGlobalNames());
Asm->OutStreamer->SwitchSection(
GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubTypesSection()
: Asm->getObjFileLowering().getDwarfPubTypesSection());
emitDebugPubSection(GnuStyle, "Types", TheU, TheU->getGlobalTypes());
}
}
void DwarfDebug::emitSectionReference(const DwarfCompileUnit &CU) {
if (useSectionsAsReferences())
Asm->emitDwarfOffset(CU.getSection()->getBeginSymbol(),
CU.getDebugSectionOffset());
else
Asm->emitDwarfSymbolReference(CU.getLabelBegin());
}
void DwarfDebug::emitDebugPubSection(bool GnuStyle, StringRef Name,
DwarfCompileUnit *TheU,
const StringMap<const DIE *> &Globals) {
if (auto *Skeleton = TheU->getSkeleton())
TheU = Skeleton;
// Emit the header.
Asm->OutStreamer->AddComment("Length of Public " + Name + " Info");
MCSymbol *BeginLabel = Asm->createTempSymbol("pub" + Name + "_begin");
MCSymbol *EndLabel = Asm->createTempSymbol("pub" + Name + "_end");
Asm->emitLabelDifference(EndLabel, BeginLabel, 4);
Asm->OutStreamer->emitLabel(BeginLabel);
Asm->OutStreamer->AddComment("DWARF Version");
Asm->emitInt16(dwarf::DW_PUBNAMES_VERSION);
Asm->OutStreamer->AddComment("Offset of Compilation Unit Info");
emitSectionReference(*TheU);
Asm->OutStreamer->AddComment("Compilation Unit Length");
Asm->emitInt32(TheU->getLength());
// Emit the pubnames for this compilation unit.
for (const auto &GI : Globals) {
const char *Name = GI.getKeyData();
const DIE *Entity = GI.second;
Asm->OutStreamer->AddComment("DIE offset");
Asm->emitInt32(Entity->getOffset());
if (GnuStyle) {
dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
Asm->OutStreamer->AddComment(
Twine("Attributes: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) +
", " + dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
Asm->emitInt8(Desc.toBits());
}
Asm->OutStreamer->AddComment("External Name");
Asm->OutStreamer->emitBytes(StringRef(Name, GI.getKeyLength() + 1));
}
Asm->OutStreamer->AddComment("End Mark");
Asm->emitInt32(0);
Asm->OutStreamer->emitLabel(EndLabel);
}
/// Emit null-terminated strings into a debug str section.
void DwarfDebug::emitDebugStr() {
MCSection *StringOffsetsSection = nullptr;
if (useSegmentedStringOffsetsTable()) {
emitStringOffsetsTableHeader();
StringOffsetsSection = Asm->getObjFileLowering().getDwarfStrOffSection();
}
DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection(),
StringOffsetsSection, /* UseRelativeOffsets = */ true);
}
void DwarfDebug::emitDebugLocEntry(ByteStreamer &Streamer,
const DebugLocStream::Entry &Entry,
const DwarfCompileUnit *CU) {
auto &&Comments = DebugLocs.getComments(Entry);
auto Comment = Comments.begin();
auto End = Comments.end();
// The expressions are inserted into a byte stream rather early (see
// DwarfExpression::addExpression) so for those ops (e.g. DW_OP_convert) that
// need to reference a base_type DIE the offset of that DIE is not yet known.
// To deal with this we instead insert a placeholder early and then extract
// it here and replace it with the real reference.
unsigned PtrSize = Asm->MAI->getCodePointerSize();
DWARFDataExtractor Data(StringRef(DebugLocs.getBytes(Entry).data(),
DebugLocs.getBytes(Entry).size()),
Asm->getDataLayout().isLittleEndian(), PtrSize);
DWARFExpression Expr(Data, PtrSize, Asm->OutContext.getDwarfFormat());
using Encoding = DWARFExpression::Operation::Encoding;
uint64_t Offset = 0;
for (auto &Op : Expr) {
assert(Op.getCode() != dwarf::DW_OP_const_type &&
"3 operand ops not yet supported");
Streamer.EmitInt8(Op.getCode(), Comment != End ? *(Comment++) : "");
Offset++;
for (unsigned I = 0; I < 2; ++I) {
if (Op.getDescription().Op[I] == Encoding::SizeNA)
continue;
if (Op.getDescription().Op[I] == Encoding::BaseTypeRef) {
uint64_t Offset =
CU->ExprRefedBaseTypes[Op.getRawOperand(I)].Die->getOffset();
assert(Offset < (1ULL << (ULEB128PadSize * 7)) && "Offset wont fit");
Streamer.emitULEB128(Offset, "", ULEB128PadSize);
// Make sure comments stay aligned.
for (unsigned J = 0; J < ULEB128PadSize; ++J)
if (Comment != End)
Comment++;
} else {
for (uint64_t J = Offset; J < Op.getOperandEndOffset(I); ++J)
Streamer.EmitInt8(Data.getData()[J], Comment != End ? *(Comment++) : "");
}
Offset = Op.getOperandEndOffset(I);
}
assert(Offset == Op.getEndOffset());
}
}
void DwarfDebug::emitDebugLocValue(const AsmPrinter &AP, const DIBasicType *BT,
const DbgValueLoc &Value,
DwarfExpression &DwarfExpr) {
auto *DIExpr = Value.getExpression();
DIExpressionCursor ExprCursor(DIExpr);
DwarfExpr.addFragmentOffset(DIExpr);
// Regular entry.
if (Value.isInt()) {
if (BT && (BT->getEncoding() == dwarf::DW_ATE_signed ||
BT->getEncoding() == dwarf::DW_ATE_signed_char))
DwarfExpr.addSignedConstant(Value.getInt());
else
DwarfExpr.addUnsignedConstant(Value.getInt());
} else if (Value.isLocation()) {
MachineLocation Location = Value.getLoc();
DwarfExpr.setLocation(Location, DIExpr);
DIExpressionCursor Cursor(DIExpr);
if (DIExpr->isEntryValue())
DwarfExpr.beginEntryValueExpression(Cursor);
const TargetRegisterInfo &TRI = *AP.MF->getSubtarget().getRegisterInfo();
if (!DwarfExpr.addMachineRegExpression(TRI, Cursor, Location.getReg()))
return;
return DwarfExpr.addExpression(std::move(Cursor));
} else if (Value.isTargetIndexLocation()) {
TargetIndexLocation Loc = Value.getTargetIndexLocation();
// TODO TargetIndexLocation is a target-independent. Currently only the WebAssembly-specific
// encoding is supported.
DwarfExpr.addWasmLocation(Loc.Index, static_cast<uint64_t>(Loc.Offset));
DwarfExpr.addExpression(std::move(ExprCursor));
return;
} else if (Value.isConstantFP()) {
APInt RawBytes = Value.getConstantFP()->getValueAPF().bitcastToAPInt();
DwarfExpr.addUnsignedConstant(RawBytes);
}
DwarfExpr.addExpression(std::move(ExprCursor));
}
void DebugLocEntry::finalize(const AsmPrinter &AP,
DebugLocStream::ListBuilder &List,
const DIBasicType *BT,
DwarfCompileUnit &TheCU) {
assert(!Values.empty() &&
"location list entries without values are redundant");
assert(Begin != End && "unexpected location list entry with empty range");
DebugLocStream::EntryBuilder Entry(List, Begin, End);
BufferByteStreamer Streamer = Entry.getStreamer();
DebugLocDwarfExpression DwarfExpr(AP.getDwarfVersion(), Streamer, TheCU);
const DbgValueLoc &Value = Values[0];
if (Value.isFragment()) {
// Emit all fragments that belong to the same variable and range.
assert(llvm::all_of(Values, [](DbgValueLoc P) {
return P.isFragment();
}) && "all values are expected to be fragments");
assert(llvm::is_sorted(Values) && "fragments are expected to be sorted");
for (auto Fragment : Values)
DwarfDebug::emitDebugLocValue(AP, BT, Fragment, DwarfExpr);
} else {
assert(Values.size() == 1 && "only fragments may have >1 value");
DwarfDebug::emitDebugLocValue(AP, BT, Value, DwarfExpr);
}
DwarfExpr.finalize();
if (DwarfExpr.TagOffset)
List.setTagOffset(*DwarfExpr.TagOffset);
}
void DwarfDebug::emitDebugLocEntryLocation(const DebugLocStream::Entry &Entry,
const DwarfCompileUnit *CU) {
// Emit the size.
Asm->OutStreamer->AddComment("Loc expr size");
if (getDwarfVersion() >= 5)
Asm->emitULEB128(DebugLocs.getBytes(Entry).size());
else if (DebugLocs.getBytes(Entry).size() <= std::numeric_limits<uint16_t>::max())
Asm->emitInt16(DebugLocs.getBytes(Entry).size());
else {
// The entry is too big to fit into 16 bit, drop it as there is nothing we
// can do.
Asm->emitInt16(0);
return;
}
// Emit the entry.
APByteStreamer Streamer(*Asm);
emitDebugLocEntry(Streamer, Entry, CU);
}
// Emit the header of a DWARF 5 range list table list table. Returns the symbol
// that designates the end of the table for the caller to emit when the table is
// complete.
static MCSymbol *emitRnglistsTableHeader(AsmPrinter *Asm,
const DwarfFile &Holder) {
MCSymbol *TableEnd = mcdwarf::emitListsTableHeaderStart(*Asm->OutStreamer);
Asm->OutStreamer->AddComment("Offset entry count");
Asm->emitInt32(Holder.getRangeLists().size());
Asm->OutStreamer->emitLabel(Holder.getRnglistsTableBaseSym());
for (const RangeSpanList &List : Holder.getRangeLists())
Asm->emitLabelDifference(List.Label, Holder.getRnglistsTableBaseSym(), 4);
return TableEnd;
}
// Emit the header of a DWARF 5 locations list table. Returns the symbol that
// designates the end of the table for the caller to emit when the table is
// complete.
static MCSymbol *emitLoclistsTableHeader(AsmPrinter *Asm,
const DwarfDebug &DD) {
MCSymbol *TableEnd = mcdwarf::emitListsTableHeaderStart(*Asm->OutStreamer);
const auto &DebugLocs = DD.getDebugLocs();
Asm->OutStreamer->AddComment("Offset entry count");
Asm->emitInt32(DebugLocs.getLists().size());
Asm->OutStreamer->emitLabel(DebugLocs.getSym());
for (const auto &List : DebugLocs.getLists())
Asm->emitLabelDifference(List.Label, DebugLocs.getSym(), 4);
return TableEnd;
}
template <typename Ranges, typename PayloadEmitter>
static void emitRangeList(
DwarfDebug &DD, AsmPrinter *Asm, MCSymbol *Sym, const Ranges &R,
const DwarfCompileUnit &CU, unsigned BaseAddressx, unsigned OffsetPair,
unsigned StartxLength, unsigned EndOfList,
StringRef (*StringifyEnum)(unsigned),
bool ShouldUseBaseAddress,
PayloadEmitter EmitPayload) {
auto Size = Asm->MAI->getCodePointerSize();
bool UseDwarf5 = DD.getDwarfVersion() >= 5;
// Emit our symbol so we can find the beginning of the range.
Asm->OutStreamer->emitLabel(Sym);
// Gather all the ranges that apply to the same section so they can share
// a base address entry.
MapVector<const MCSection *, std::vector<decltype(&*R.begin())>> SectionRanges;
for (const auto &Range : R)
SectionRanges[&Range.Begin->getSection()].push_back(&Range);
const MCSymbol *CUBase = CU.getBaseAddress();
bool BaseIsSet = false;
for (const auto &P : SectionRanges) {
auto *Base = CUBase;
if (!Base && ShouldUseBaseAddress) {
const MCSymbol *Begin = P.second.front()->Begin;
const MCSymbol *NewBase = DD.getSectionLabel(&Begin->getSection());
if (!UseDwarf5) {
Base = NewBase;
BaseIsSet = true;
Asm->OutStreamer->emitIntValue(-1, Size);
Asm->OutStreamer->AddComment(" base address");
Asm->OutStreamer->emitSymbolValue(Base, Size);
} else if (NewBase != Begin || P.second.size() > 1) {
// Only use a base address if
// * the existing pool address doesn't match (NewBase != Begin)
// * or, there's more than one entry to share the base address
Base = NewBase;
BaseIsSet = true;
Asm->OutStreamer->AddComment(StringifyEnum(BaseAddressx));
Asm->emitInt8(BaseAddressx);
Asm->OutStreamer->AddComment(" base address index");
Asm->emitULEB128(DD.getAddressPool().getIndex(Base));
}
} else if (BaseIsSet && !UseDwarf5) {
BaseIsSet = false;
assert(!Base);
Asm->OutStreamer->emitIntValue(-1, Size);
Asm->OutStreamer->emitIntValue(0, Size);
}
for (const auto *RS : P.second) {
const MCSymbol *Begin = RS->Begin;
const MCSymbol *End = RS->End;
assert(Begin && "Range without a begin symbol?");
assert(End && "Range without an end symbol?");
if (Base) {
if (UseDwarf5) {
// Emit offset_pair when we have a base.
Asm->OutStreamer->AddComment(StringifyEnum(OffsetPair));
Asm->emitInt8(OffsetPair);
Asm->OutStreamer->AddComment(" starting offset");
Asm->emitLabelDifferenceAsULEB128(Begin, Base);
Asm->OutStreamer->AddComment(" ending offset");
Asm->emitLabelDifferenceAsULEB128(End, Base);
} else {
Asm->emitLabelDifference(Begin, Base, Size);
Asm->emitLabelDifference(End, Base, Size);
}
} else if (UseDwarf5) {
Asm->OutStreamer->AddComment(StringifyEnum(StartxLength));
Asm->emitInt8(StartxLength);
Asm->OutStreamer->AddComment(" start index");
Asm->emitULEB128(DD.getAddressPool().getIndex(Begin));
Asm->OutStreamer->AddComment(" length");
Asm->emitLabelDifferenceAsULEB128(End, Begin);
} else {
Asm->OutStreamer->emitSymbolValue(Begin, Size);
Asm->OutStreamer->emitSymbolValue(End, Size);
}
EmitPayload(*RS);
}
}
if (UseDwarf5) {
Asm->OutStreamer->AddComment(StringifyEnum(EndOfList));
Asm->emitInt8(EndOfList);
} else {
// Terminate the list with two 0 values.
Asm->OutStreamer->emitIntValue(0, Size);
Asm->OutStreamer->emitIntValue(0, Size);
}
}
// Handles emission of both debug_loclist / debug_loclist.dwo
static void emitLocList(DwarfDebug &DD, AsmPrinter *Asm, const DebugLocStream::List &List) {
emitRangeList(DD, Asm, List.Label, DD.getDebugLocs().getEntries(List),
*List.CU, dwarf::DW_LLE_base_addressx,
dwarf::DW_LLE_offset_pair, dwarf::DW_LLE_startx_length,
dwarf::DW_LLE_end_of_list, llvm::dwarf::LocListEncodingString,
/* ShouldUseBaseAddress */ true,
[&](const DebugLocStream::Entry &E) {
DD.emitDebugLocEntryLocation(E, List.CU);
});
}
void DwarfDebug::emitDebugLocImpl(MCSection *Sec) {
if (DebugLocs.getLists().empty())
return;
Asm->OutStreamer->SwitchSection(Sec);
MCSymbol *TableEnd = nullptr;
if (getDwarfVersion() >= 5)
TableEnd = emitLoclistsTableHeader(Asm, *this);
for (const auto &List : DebugLocs.getLists())
emitLocList(*this, Asm, List);
if (TableEnd)
Asm->OutStreamer->emitLabel(TableEnd);
}
// Emit locations into the .debug_loc/.debug_loclists section.
void DwarfDebug::emitDebugLoc() {
emitDebugLocImpl(
getDwarfVersion() >= 5
? Asm->getObjFileLowering().getDwarfLoclistsSection()
: Asm->getObjFileLowering().getDwarfLocSection());
}
// Emit locations into the .debug_loc.dwo/.debug_loclists.dwo section.
void DwarfDebug::emitDebugLocDWO() {
if (getDwarfVersion() >= 5) {
emitDebugLocImpl(
Asm->getObjFileLowering().getDwarfLoclistsDWOSection());
return;
}
for (const auto &List : DebugLocs.getLists()) {
Asm->OutStreamer->SwitchSection(
Asm->getObjFileLowering().getDwarfLocDWOSection());
Asm->OutStreamer->emitLabel(List.Label);
for (const auto &Entry : DebugLocs.getEntries(List)) {
// GDB only supports startx_length in pre-standard split-DWARF.
// (in v5 standard loclists, it currently* /only/ supports base_address +
// offset_pair, so the implementations can't really share much since they
// need to use different representations)
// * as of October 2018, at least
//
// In v5 (see emitLocList), this uses SectionLabels to reuse existing
// addresses in the address pool to minimize object size/relocations.
Asm->emitInt8(dwarf::DW_LLE_startx_length);
unsigned idx = AddrPool.getIndex(Entry.Begin);
Asm->emitULEB128(idx);
// Also the pre-standard encoding is slightly different, emitting this as
// an address-length entry here, but its a ULEB128 in DWARFv5 loclists.
Asm->emitLabelDifference(Entry.End, Entry.Begin, 4);
emitDebugLocEntryLocation(Entry, List.CU);
}
Asm->emitInt8(dwarf::DW_LLE_end_of_list);
}
}
struct ArangeSpan {
const MCSymbol *Start, *End;
};
// Emit a debug aranges section, containing a CU lookup for any
// address we can tie back to a CU.
void DwarfDebug::emitDebugARanges() {
// Provides a unique id per text section.
MapVector<MCSection *, SmallVector<SymbolCU, 8>> SectionMap;
// Filter labels by section.
for (const SymbolCU &SCU : ArangeLabels) {
if (SCU.Sym->isInSection()) {
// Make a note of this symbol and it's section.
MCSection *Section = &SCU.Sym->getSection();
if (!Section->getKind().isMetadata())
SectionMap[Section].push_back(SCU);
} else {
// Some symbols (e.g. common/bss on mach-o) can have no section but still
// appear in the output. This sucks as we rely on sections to build
// arange spans. We can do it without, but it's icky.
SectionMap[nullptr].push_back(SCU);
}
}
DenseMap<DwarfCompileUnit *, std::vector<ArangeSpan>> Spans;
for (auto &I : SectionMap) {
MCSection *Section = I.first;
SmallVector<SymbolCU, 8> &List = I.second;
if (List.size() < 1)
continue;
// If we have no section (e.g. common), just write out
// individual spans for each symbol.
if (!Section) {
for (const SymbolCU &Cur : List) {
ArangeSpan Span;
Span.Start = Cur.Sym;
Span.End = nullptr;
assert(Cur.CU);
Spans[Cur.CU].push_back(Span);
}
continue;
}
// Sort the symbols by offset within the section.
llvm::stable_sort(List, [&](const SymbolCU &A, const SymbolCU &B) {
unsigned IA = A.Sym ? Asm->OutStreamer->GetSymbolOrder(A.Sym) : 0;
unsigned IB = B.Sym ? Asm->OutStreamer->GetSymbolOrder(B.Sym) : 0;
// Symbols with no order assigned should be placed at the end.
// (e.g. section end labels)
if (IA == 0)
return false;
if (IB == 0)
return true;
return IA < IB;
});
// Insert a final terminator.
List.push_back(SymbolCU(nullptr, Asm->OutStreamer->endSection(Section)));
// Build spans between each label.
const MCSymbol *StartSym = List[0].Sym;
for (size_t n = 1, e = List.size(); n < e; n++) {
const SymbolCU &Prev = List[n - 1];
const SymbolCU &Cur = List[n];
// Try and build the longest span we can within the same CU.
if (Cur.CU != Prev.CU) {
ArangeSpan Span;
Span.Start = StartSym;
Span.End = Cur.Sym;
assert(Prev.CU);
Spans[Prev.CU].push_back(Span);
StartSym = Cur.Sym;
}
}
}
// Start the dwarf aranges section.
Asm->OutStreamer->SwitchSection(
Asm->getObjFileLowering().getDwarfARangesSection());
unsigned PtrSize = Asm->MAI->getCodePointerSize();
// Build a list of CUs used.
std::vector<DwarfCompileUnit *> CUs;
for (const auto &it : Spans) {
DwarfCompileUnit *CU = it.first;
CUs.push_back(CU);
}
// Sort the CU list (again, to ensure consistent output order).
llvm::sort(CUs, [](const DwarfCompileUnit *A, const DwarfCompileUnit *B) {
return A->getUniqueID() < B->getUniqueID();
});
// Emit an arange table for each CU we used.
for (DwarfCompileUnit *CU : CUs) {
std::vector<ArangeSpan> &List = Spans[CU];
// Describe the skeleton CU's offset and length, not the dwo file's.
if (auto *Skel = CU->getSkeleton())
CU = Skel;
// Emit size of content not including length itself.
unsigned ContentSize =
sizeof(int16_t) + // DWARF ARange version number
sizeof(int32_t) + // Offset of CU in the .debug_info section
sizeof(int8_t) + // Pointer Size (in bytes)
sizeof(int8_t); // Segment Size (in bytes)
unsigned TupleSize = PtrSize * 2;
// 7.20 in the Dwarf specs requires the table to be aligned to a tuple.
unsigned Padding =
offsetToAlignment(sizeof(int32_t) + ContentSize, Align(TupleSize));
ContentSize += Padding;
ContentSize += (List.size() + 1) * TupleSize;
// For each compile unit, write the list of spans it covers.
Asm->OutStreamer->AddComment("Length of ARange Set");
Asm->emitInt32(ContentSize);
Asm->OutStreamer->AddComment("DWARF Arange version number");
Asm->emitInt16(dwarf::DW_ARANGES_VERSION);
Asm->OutStreamer->AddComment("Offset Into Debug Info Section");
emitSectionReference(*CU);
Asm->OutStreamer->AddComment("Address Size (in bytes)");
Asm->emitInt8(PtrSize);
Asm->OutStreamer->AddComment("Segment Size (in bytes)");
Asm->emitInt8(0);
Asm->OutStreamer->emitFill(Padding, 0xff);
for (const ArangeSpan &Span : List) {
Asm->emitLabelReference(Span.Start, PtrSize);
// Calculate the size as being from the span start to it's end.
if (Span.End) {
Asm->emitLabelDifference(Span.End, Span.Start, PtrSize);
} else {
// For symbols without an end marker (e.g. common), we
// write a single arange entry containing just that one symbol.
uint64_t Size = SymSize[Span.Start];
if (Size == 0)
Size = 1;
Asm->OutStreamer->emitIntValue(Size, PtrSize);
}
}
Asm->OutStreamer->AddComment("ARange terminator");
Asm->OutStreamer->emitIntValue(0, PtrSize);
Asm->OutStreamer->emitIntValue(0, PtrSize);
}
}
/// Emit a single range list. We handle both DWARF v5 and earlier.
static void emitRangeList(DwarfDebug &DD, AsmPrinter *Asm,
const RangeSpanList &List) {
emitRangeList(DD, Asm, List.Label, List.Ranges, *List.CU,
dwarf::DW_RLE_base_addressx, dwarf::DW_RLE_offset_pair,
dwarf::DW_RLE_startx_length, dwarf::DW_RLE_end_of_list,
llvm::dwarf::RangeListEncodingString,
List.CU->getCUNode()->getRangesBaseAddress() ||
DD.getDwarfVersion() >= 5,
[](auto) {});
}
void DwarfDebug::emitDebugRangesImpl(const DwarfFile &Holder, MCSection *Section) {
if (Holder.getRangeLists().empty())
return;
assert(useRangesSection());
assert(!CUMap.empty());
assert(llvm::any_of(CUMap, [](const decltype(CUMap)::value_type &Pair) {
return !Pair.second->getCUNode()->isDebugDirectivesOnly();
}));
Asm->OutStreamer->SwitchSection(Section);
MCSymbol *TableEnd = nullptr;
if (getDwarfVersion() >= 5)
TableEnd = emitRnglistsTableHeader(Asm, Holder);
for (const RangeSpanList &List : Holder.getRangeLists())
emitRangeList(*this, Asm, List);
if (TableEnd)
Asm->OutStreamer->emitLabel(TableEnd);
}
/// Emit address ranges into the .debug_ranges section or into the DWARF v5
/// .debug_rnglists section.
void DwarfDebug::emitDebugRanges() {
const auto &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
emitDebugRangesImpl(Holder,
getDwarfVersion() >= 5
? Asm->getObjFileLowering().getDwarfRnglistsSection()
: Asm->getObjFileLowering().getDwarfRangesSection());
}
void DwarfDebug::emitDebugRangesDWO() {
emitDebugRangesImpl(InfoHolder,
Asm->getObjFileLowering().getDwarfRnglistsDWOSection());
}
/// Emit the header of a DWARF 5 macro section, or the GNU extension for
/// DWARF 4.
static void emitMacroHeader(AsmPrinter *Asm, const DwarfDebug &DD,
const DwarfCompileUnit &CU, uint16_t DwarfVersion) {
enum HeaderFlagMask {
#define HANDLE_MACRO_FLAG(ID, NAME) MACRO_FLAG_##NAME = ID,
#include "llvm/BinaryFormat/Dwarf.def"
};
uint8_t Flags = 0;
Asm->OutStreamer->AddComment("Macro information version");
Asm->emitInt16(DwarfVersion >= 5 ? DwarfVersion : 4);
// We are setting Offset and line offset flags unconditionally here,
// since we're only supporting DWARF32 and line offset should be mostly
// present.
// FIXME: Add support for DWARF64.
Flags |= MACRO_FLAG_DEBUG_LINE_OFFSET;
Asm->OutStreamer->AddComment("Flags: 32 bit, debug_line_offset present");
Asm->emitInt8(Flags);
Asm->OutStreamer->AddComment("debug_line_offset");
if (DD.useSplitDwarf())
Asm->OutStreamer->emitIntValue(0, /*Size=*/4);
else
Asm->OutStreamer->emitSymbolValue(CU.getLineTableStartSym(), /*Size=*/4);
}
void DwarfDebug::handleMacroNodes(DIMacroNodeArray Nodes, DwarfCompileUnit &U) {
for (auto *MN : Nodes) {
if (auto *M = dyn_cast<DIMacro>(MN))
emitMacro(*M);
else if (auto *F = dyn_cast<DIMacroFile>(MN))
emitMacroFile(*F, U);
else
llvm_unreachable("Unexpected DI type!");
}
}
void DwarfDebug::emitMacro(DIMacro &M) {
StringRef Name = M.getName();
StringRef Value = M.getValue();
// There should be one space between the macro name and the macro value in
// define entries. In undef entries, only the macro name is emitted.
std::string Str = Value.empty() ? Name.str() : (Name + " " + Value).str();
if (UseDebugMacroSection) {
if (getDwarfVersion() >= 5) {
unsigned Type = M.getMacinfoType() == dwarf::DW_MACINFO_define
? dwarf::DW_MACRO_define_strx
: dwarf::DW_MACRO_undef_strx;
Asm->OutStreamer->AddComment(dwarf::MacroString(Type));
Asm->emitULEB128(Type);
Asm->OutStreamer->AddComment("Line Number");
Asm->emitULEB128(M.getLine());
Asm->OutStreamer->AddComment("Macro String");
Asm->emitULEB128(
InfoHolder.getStringPool().getIndexedEntry(*Asm, Str).getIndex());
} else {
unsigned Type = M.getMacinfoType() == dwarf::DW_MACINFO_define
? dwarf::DW_MACRO_GNU_define_indirect
: dwarf::DW_MACRO_GNU_undef_indirect;
Asm->OutStreamer->AddComment(dwarf::GnuMacroString(Type));
Asm->emitULEB128(Type);
Asm->OutStreamer->AddComment("Line Number");
Asm->emitULEB128(M.getLine());
Asm->OutStreamer->AddComment("Macro String");
// FIXME: Add support for DWARF64.
Asm->OutStreamer->emitSymbolValue(
InfoHolder.getStringPool().getEntry(*Asm, Str).getSymbol(),
/*Size=*/4);
}
} else {
Asm->OutStreamer->AddComment(dwarf::MacinfoString(M.getMacinfoType()));
Asm->emitULEB128(M.getMacinfoType());
Asm->OutStreamer->AddComment("Line Number");
Asm->emitULEB128(M.getLine());
Asm->OutStreamer->AddComment("Macro String");
Asm->OutStreamer->emitBytes(Str);
Asm->emitInt8('\0');
}
}
void DwarfDebug::emitMacroFileImpl(
DIMacroFile &MF, DwarfCompileUnit &U, unsigned StartFile, unsigned EndFile,
StringRef (*MacroFormToString)(unsigned Form)) {
Asm->OutStreamer->AddComment(MacroFormToString(StartFile));
Asm->emitULEB128(StartFile);
Asm->OutStreamer->AddComment("Line Number");
Asm->emitULEB128(MF.getLine());
Asm->OutStreamer->AddComment("File Number");
DIFile &F = *MF.getFile();
if (useSplitDwarf())
Asm->emitULEB128(getDwoLineTable(U)->getFile(
F.getDirectory(), F.getFilename(), getMD5AsBytes(&F),
Asm->OutContext.getDwarfVersion(), F.getSource()));
else
Asm->emitULEB128(U.getOrCreateSourceID(&F));
handleMacroNodes(MF.getElements(), U);
Asm->OutStreamer->AddComment(MacroFormToString(EndFile));
Asm->emitULEB128(EndFile);
}
void DwarfDebug::emitMacroFile(DIMacroFile &F, DwarfCompileUnit &U) {
// DWARFv5 macro and DWARFv4 macinfo share some common encodings,
// so for readibility/uniformity, We are explicitly emitting those.
assert(F.getMacinfoType() == dwarf::DW_MACINFO_start_file);
if (UseDebugMacroSection)
emitMacroFileImpl(
F, U, dwarf::DW_MACRO_start_file, dwarf::DW_MACRO_end_file,
(getDwarfVersion() >= 5) ? dwarf::MacroString : dwarf::GnuMacroString);
else
emitMacroFileImpl(F, U, dwarf::DW_MACINFO_start_file,
dwarf::DW_MACINFO_end_file, dwarf::MacinfoString);
}
void DwarfDebug::emitDebugMacinfoImpl(MCSection *Section) {
for (const auto &P : CUMap) {
auto &TheCU = *P.second;
auto *SkCU = TheCU.getSkeleton();
DwarfCompileUnit &U = SkCU ? *SkCU : TheCU;
auto *CUNode = cast<DICompileUnit>(P.first);
DIMacroNodeArray Macros = CUNode->getMacros();
if (Macros.empty())
continue;
Asm->OutStreamer->SwitchSection(Section);
Asm->OutStreamer->emitLabel(U.getMacroLabelBegin());
if (UseDebugMacroSection)
emitMacroHeader(Asm, *this, U, getDwarfVersion());
handleMacroNodes(Macros, U);
Asm->OutStreamer->AddComment("End Of Macro List Mark");
Asm->emitInt8(0);
}
}
/// Emit macros into a debug macinfo/macro section.
void DwarfDebug::emitDebugMacinfo() {
auto &ObjLower = Asm->getObjFileLowering();
emitDebugMacinfoImpl(UseDebugMacroSection
? ObjLower.getDwarfMacroSection()
: ObjLower.getDwarfMacinfoSection());
}
void DwarfDebug::emitDebugMacinfoDWO() {
auto &ObjLower = Asm->getObjFileLowering();
emitDebugMacinfoImpl(UseDebugMacroSection
? ObjLower.getDwarfMacroDWOSection()
: ObjLower.getDwarfMacinfoDWOSection());
}
// DWARF5 Experimental Separate Dwarf emitters.
void DwarfDebug::initSkeletonUnit(const DwarfUnit &U, DIE &Die,
std::unique_ptr<DwarfCompileUnit> NewU) {
if (!CompilationDir.empty())
NewU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
addGnuPubAttributes(*NewU, Die);
SkeletonHolder.addUnit(std::move(NewU));
}
DwarfCompileUnit &DwarfDebug::constructSkeletonCU(const DwarfCompileUnit &CU) {
auto OwnedUnit = std::make_unique<DwarfCompileUnit>(
CU.getUniqueID(), CU.getCUNode(), Asm, this, &SkeletonHolder,
UnitKind::Skeleton);
DwarfCompileUnit &NewCU = *OwnedUnit;
NewCU.setSection(Asm->getObjFileLowering().getDwarfInfoSection());
NewCU.initStmtList();
if (useSegmentedStringOffsetsTable())
NewCU.addStringOffsetsStart();
initSkeletonUnit(CU, NewCU.getUnitDie(), std::move(OwnedUnit));
return NewCU;
}
// Emit the .debug_info.dwo section for separated dwarf. This contains the
// compile units that would normally be in debug_info.
void DwarfDebug::emitDebugInfoDWO() {
assert(useSplitDwarf() && "No split dwarf debug info?");
// Don't emit relocations into the dwo file.
InfoHolder.emitUnits(/* UseOffsets */ true);
}
// Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
// abbreviations for the .debug_info.dwo section.
void DwarfDebug::emitDebugAbbrevDWO() {
assert(useSplitDwarf() && "No split dwarf?");
InfoHolder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection());
}
void DwarfDebug::emitDebugLineDWO() {
assert(useSplitDwarf() && "No split dwarf?");
SplitTypeUnitFileTable.Emit(
*Asm->OutStreamer, MCDwarfLineTableParams(),
Asm->getObjFileLowering().getDwarfLineDWOSection());
}
void DwarfDebug::emitStringOffsetsTableHeaderDWO() {
assert(useSplitDwarf() && "No split dwarf?");
InfoHolder.getStringPool().emitStringOffsetsTableHeader(
*Asm, Asm->getObjFileLowering().getDwarfStrOffDWOSection(),
InfoHolder.getStringOffsetsStartSym());
}
// Emit the .debug_str.dwo section for separated dwarf. This contains the
// string section and is identical in format to traditional .debug_str
// sections.
void DwarfDebug::emitDebugStrDWO() {
if (useSegmentedStringOffsetsTable())
emitStringOffsetsTableHeaderDWO();
assert(useSplitDwarf() && "No split dwarf?");
MCSection *OffSec = Asm->getObjFileLowering().getDwarfStrOffDWOSection();
InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),
OffSec, /* UseRelativeOffsets = */ false);
}
// Emit address pool.
void DwarfDebug::emitDebugAddr() {
AddrPool.emit(*Asm, Asm->getObjFileLowering().getDwarfAddrSection());
}
MCDwarfDwoLineTable *DwarfDebug::getDwoLineTable(const DwarfCompileUnit &CU) {
if (!useSplitDwarf())
return nullptr;
const DICompileUnit *DIUnit = CU.getCUNode();
SplitTypeUnitFileTable.maybeSetRootFile(
DIUnit->getDirectory(), DIUnit->getFilename(),
getMD5AsBytes(DIUnit->getFile()), DIUnit->getSource());
return &SplitTypeUnitFileTable;
}
uint64_t DwarfDebug::makeTypeSignature(StringRef Identifier) {
MD5 Hash;
Hash.update(Identifier);
// ... take the least significant 8 bytes and return those. Our MD5
// implementation always returns its results in little endian, so we actually
// need the "high" word.
MD5::MD5Result Result;
Hash.final(Result);
return Result.high();
}
void DwarfDebug::addDwarfTypeUnitType(DwarfCompileUnit &CU,
StringRef Identifier, DIE &RefDie,
const DICompositeType *CTy) {
// Fast path if we're building some type units and one has already used the
// address pool we know we're going to throw away all this work anyway, so
// don't bother building dependent types.
if (!TypeUnitsUnderConstruction.empty() && AddrPool.hasBeenUsed())
return;
auto Ins = TypeSignatures.insert(std::make_pair(CTy, 0));
if (!Ins.second) {
CU.addDIETypeSignature(RefDie, Ins.first->second);
return;
}
bool TopLevelType = TypeUnitsUnderConstruction.empty();
AddrPool.resetUsedFlag();
auto OwnedUnit = std::make_unique<DwarfTypeUnit>(CU, Asm, this, &InfoHolder,
getDwoLineTable(CU));
DwarfTypeUnit &NewTU = *OwnedUnit;
DIE &UnitDie = NewTU.getUnitDie();
TypeUnitsUnderConstruction.emplace_back(std::move(OwnedUnit), CTy);
NewTU.addUInt(UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
CU.getLanguage());
uint64_t Signature = makeTypeSignature(Identifier);
NewTU.setTypeSignature(Signature);
Ins.first->second = Signature;
if (useSplitDwarf()) {
MCSection *Section =
getDwarfVersion() <= 4
? Asm->getObjFileLowering().getDwarfTypesDWOSection()
: Asm->getObjFileLowering().getDwarfInfoDWOSection();
NewTU.setSection(Section);
} else {
MCSection *Section =
getDwarfVersion() <= 4
? Asm->getObjFileLowering().getDwarfTypesSection(Signature)
: Asm->getObjFileLowering().getDwarfInfoSection(Signature);
NewTU.setSection(Section);
// Non-split type units reuse the compile unit's line table.
CU.applyStmtList(UnitDie);
}
// Add DW_AT_str_offsets_base to the type unit DIE, but not for split type
// units.
if (useSegmentedStringOffsetsTable() && !useSplitDwarf())
NewTU.addStringOffsetsStart();
NewTU.setType(NewTU.createTypeDIE(CTy));
if (TopLevelType) {
auto TypeUnitsToAdd = std::move(TypeUnitsUnderConstruction);
TypeUnitsUnderConstruction.clear();
// Types referencing entries in the address table cannot be placed in type
// units.
if (AddrPool.hasBeenUsed()) {
// Remove all the types built while building this type.
// This is pessimistic as some of these types might not be dependent on
// the type that used an address.
for (const auto &TU : TypeUnitsToAdd)
TypeSignatures.erase(TU.second);
// Construct this type in the CU directly.
// This is inefficient because all the dependent types will be rebuilt
// from scratch, including building them in type units, discovering that
// they depend on addresses, throwing them out and rebuilding them.
CU.constructTypeDIE(RefDie, cast<DICompositeType>(CTy));
return;
}
// If the type wasn't dependent on fission addresses, finish adding the type
// and all its dependent types.
for (auto &TU : TypeUnitsToAdd) {
InfoHolder.computeSizeAndOffsetsForUnit(TU.first.get());
InfoHolder.emitUnit(TU.first.get(), useSplitDwarf());
}
}
CU.addDIETypeSignature(RefDie, Signature);
}
DwarfDebug::NonTypeUnitContext::NonTypeUnitContext(DwarfDebug *DD)
: DD(DD),
TypeUnitsUnderConstruction(std::move(DD->TypeUnitsUnderConstruction)) {
DD->TypeUnitsUnderConstruction.clear();
assert(TypeUnitsUnderConstruction.empty() || !DD->AddrPool.hasBeenUsed());
}
DwarfDebug::NonTypeUnitContext::~NonTypeUnitContext() {
DD->TypeUnitsUnderConstruction = std::move(TypeUnitsUnderConstruction);
DD->AddrPool.resetUsedFlag();
}
DwarfDebug::NonTypeUnitContext DwarfDebug::enterNonTypeUnitContext() {
return NonTypeUnitContext(this);
}
// Add the Name along with its companion DIE to the appropriate accelerator
// table (for AccelTableKind::Dwarf it's always AccelDebugNames, for
// AccelTableKind::Apple, we use the table we got as an argument). If
// accelerator tables are disabled, this function does nothing.
template <typename DataT>
void DwarfDebug::addAccelNameImpl(const DICompileUnit &CU,
AccelTable<DataT> &AppleAccel, StringRef Name,
const DIE &Die) {
if (getAccelTableKind() == AccelTableKind::None)
return;
if (getAccelTableKind() != AccelTableKind::Apple &&
CU.getNameTableKind() != DICompileUnit::DebugNameTableKind::Default)
return;
DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
DwarfStringPoolEntryRef Ref = Holder.getStringPool().getEntry(*Asm, Name);
switch (getAccelTableKind()) {
case AccelTableKind::Apple:
AppleAccel.addName(Ref, Die);
break;
case AccelTableKind::Dwarf:
AccelDebugNames.addName(Ref, Die);
break;
case AccelTableKind::Default:
llvm_unreachable("Default should have already been resolved.");
case AccelTableKind::None:
llvm_unreachable("None handled above");
}
}
void DwarfDebug::addAccelName(const DICompileUnit &CU, StringRef Name,
const DIE &Die) {
addAccelNameImpl(CU, AccelNames, Name, Die);
}
void DwarfDebug::addAccelObjC(const DICompileUnit &CU, StringRef Name,
const DIE &Die) {
// ObjC names go only into the Apple accelerator tables.
if (getAccelTableKind() == AccelTableKind::Apple)
addAccelNameImpl(CU, AccelObjC, Name, Die);
}
void DwarfDebug::addAccelNamespace(const DICompileUnit &CU, StringRef Name,
const DIE &Die) {
addAccelNameImpl(CU, AccelNamespace, Name, Die);
}
void DwarfDebug::addAccelType(const DICompileUnit &CU, StringRef Name,
const DIE &Die, char Flags) {
addAccelNameImpl(CU, AccelTypes, Name, Die);
}
uint16_t DwarfDebug::getDwarfVersion() const {
return Asm->OutStreamer->getContext().getDwarfVersion();
}
const MCSymbol *DwarfDebug::getSectionLabel(const MCSection *S) {
return SectionLabels.find(S)->second;
}
void DwarfDebug::insertSectionLabel(const MCSymbol *S) {
if (SectionLabels.insert(std::make_pair(&S->getSection(), S)).second)
if (useSplitDwarf() || getDwarfVersion() >= 5)
AddrPool.getIndex(S);
}
Optional<MD5::MD5Result> DwarfDebug::getMD5AsBytes(const DIFile *File) const {
assert(File);
if (getDwarfVersion() < 5)
return None;
Optional<DIFile::ChecksumInfo<StringRef>> Checksum = File->getChecksum();
if (!Checksum || Checksum->Kind != DIFile::CSK_MD5)
return None;
// Convert the string checksum to an MD5Result for the streamer.
// The verifier validates the checksum so we assume it's okay.
// An MD5 checksum is 16 bytes.
std::string ChecksumString = fromHex(Checksum->Value);
MD5::MD5Result CKMem;
std::copy(ChecksumString.begin(), ChecksumString.end(), CKMem.Bytes.data());
return CKMem;
}
|
/*
NOTICE
The software accompanying this notice (the "Software") is provided to you
free of charge to facilitate your use of the data collected by the Mars
Orbiter Camera (the "MOC Data"). Malin Space Science Systems ("MSSS")
grants to you (either as an individual or entity) a personal,
non-transferable, and non-exclusive right (i) to use and reproduce the
Software solely for the purpose of accessing the MOC Data; (ii) to modify
the source code of the Software as necessary to maintain or adapt the
Software to run on alternate computer platforms; and (iii) to compile, use
and reproduce the modified versions of the Software solely for the purpose
of accessing the MOC Data. In addition, you may distribute the Software,
including any modifications thereof, solely for use with the MOC Data,
provided that (i) you must include this notice with all copies of the
Software to be distributed; (ii) you may not remove or alter any
proprietary notices contained in the Software; (iii) you may not charge any
third party for the Software; and (iv) you will not export the Software
without the appropriate United States and foreign government licenses.
You acknowledge that no title to the intellectual property in the Software
is transferred to you. You further acknowledge that title and full
ownership rights to the Software will remain the exclusive property of MSSS
or its suppliers, and you will not acquire any rights to the Software
except as expressly set forth above. The Software is provided to you AS
IS. MSSS MAKES NO WARRANTY, EXPRESS OR IMPLIED, WITH RESPECT TO THE
SOFTWARE, AND SPECIFICALLY DISCLAIMS THE IMPLIED WARRANTIES OF
NON-INFRINGEMENT OF THIRD PARTY RIGHTS, MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE. SOME JURISDICTIONS DO NOT ALLOW THE EXCLUSION OR
LIMITATION OF INCIDENTAL OR CONSEQUENTIAL DAMAGES, SO SUCH LIMITATIONS OR
EXCLUSIONS MAY NOT APPLY TO YOU.
Your use or reproduction of the Software constitutes your agreement to the
terms of this Notice. If you do not agree with the terms of this notice,
promptly return or destroy all copies of the Software in your possession.
Copyright (C) 1999 Malin Space Science Systems. All Rights Reserved.
*/
//static char *sccsid = "@(#)decompXPRED.c 1.1 10/04/99";
#if (!defined(NOSCCSID) && (!defined(LINT)))
#endif
#include "fs.h"
#include "bitsOut.h"
#include "nextValue.h"
#include "decompXPRED.h"
void decompXPRED(register uint8 *curLine, uint32 size, uint8 *code, uint8 *left, uint8 *right, BITSTRUCT *bitStuff)
{
uint8 prev; /* Previous pixel */
uint32 bitCount;
uint8 *data;
uint8 cur;
/* The first "previous pixel" is zero */
prev = 0;
data = bitStuff->output;
bitCount = bitStuff->bitCount;
cur = (*data) >> bitCount;
/* Decode and decompress all pixels in this line */
while(size > 0) {
uint8 temp;
/*
* Decode and decompress this pixel and store it
* as the next pixel's previous pixel
*/
nextValue(temp, code, left, right, cur, bitCount, data);
prev += temp;
/* Store the current pixel */
*(curLine++) = prev;
size--;
};
bitStuff->output = data;
bitStuff->bitCount = bitCount;
}
#ifdef TEST
void initReverse(trans) uint8 *trans;
{
/*
* This function generate the bit reversal array "trans" above
*
* pre:
*
* post:
* The array "tran" contains the bit reversal of each index in that
* index's location (e.g. trans[0x05] = 0xa0).
*/
uint32 t; /* Current index */
/* Do all 8 bit numbers */
for(t = 0; t < 256; t++) {
uint8 r; /* Reversed byte */
uint8 b; /* Bit count */
uint8 mask; /* Current bit in index */
uint8 bit; /* Current bit in reversed byte */
/* Reverse all 8 bits */
r = 0;
for(b = 0, mask = 0x1, bit = 0x80; b < 8; b++) {
/*
* If the bit in index is set, set the corresponding
* bit in the reversed byte
*/
if(t & mask) {
r |= bit;
};
/* Move bit in index up and bit in reversed byte down */
mask = mask << 1;
bit = bit >> 1;
};
/* Store the reversed byte */
trans[t] = r;
};
}
void createIdentTree(code, left, right) uint8 *code, *left, *right;
{
uint32 index;
for(index = 0; index < 127; index++) {
code[index] = LEFT | RIGHT;
left[index] = 2 * index + 1;
right[index] = 2 * index + 2;
};
for(index = 127; index < 255; index++) {
code[index] = 0;
left[index] = ~(2 * (index - 127));
right[index] = ~(2 * (index - 127) + 1);
};
}
#define MAXLINE 2048
uint8 reverse[256];
uint8 data[2 * MAXLINE + 4];
uint32 tryXpred(code, left, right, bitStuff) uint8 *code, *left, *right;
BITSTRUCT *bitStuff;
{
uint32 nerror;
uint8 curLine[MAXLINE];
uint32 i;
uint8 known, actual, sum;
nerror = 0;
for(i = 0; i < MAXLINE; i++) {
curLine[i] = 0;
};
decompXPRED(curLine, MAXLINE, code, left, right, bitStuff);
sum = 0;
for(i = 0; i < MAXLINE; i++) {
sum += ~reverse[(~i) & 0xFF];
known = sum;
actual = curLine[i];
if(known != actual) {
printf("X Pred: Cur pixel: %4d (%4d %1d), expected: %3d (%02x), got: %3d (%02x)\n", i, bitStuff->data - data, bitStuff->bitCount, known, known, actual, actual);
nerror += 1;
};
};
for(i = 0; i < MAXLINE; i++) {
curLine[i] = 0;
};
decompXPRED(curLine, MAXLINE, code, left, right, bitStuff);
sum = 0;
for(i = 0; i < MAXLINE; i++) {
sum += ~reverse[(~(i+MAXLINE)) & 0xFF];
known = sum;
actual = curLine[i];
if(known != actual) {
printf("X Pred: Cur pixel: %4d (%4d %1d), expected: %3d (%02x), got: %3d (%02x)\n", i, bitStuff->data - data, bitStuff->bitCount, known, known, actual, actual);
nerror += 1;
};
};
return(nerror);
}
main() {
uint32 nerror;
uint8 code[256];
uint8 left[256];
uint8 right[256];
BITSTRUCT bitStuff;
uint32 i;
/* No errors yet */
nerror = 0;
printf("Test started\n");
initReverse(reverse);
createIdentTree(code, left, right);
/* Check decompression */
for(i = 0; i < 2 * MAXLINE + 4; i++) {
data[i] = ~i;
};
bitStuff.data = data;
bitStuff.bitQueue = 0;
bitStuff.bitCount = 0;
nerror = tryXpred(code, left, right, &bitStuff);
/* If no errors print message */
if(nerror == 0) {
printf("Test succeeded\n");
}
else {
printf("Test failed: %d\n", nerror);
};
/* Exit with the number of errors */
exit(nerror);
}
#endif
|
//
// Copyright 2019 Google LLC
//
// 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.
//
// ParseLocationTranslator is tested by public/error_helpers_test.cc and
// analyzer/testdata/parse_locations.test.
#include "zetasql/public/parse_location.h"
#include <algorithm>
#include <iterator>
#include "zetasql/base/logging.h"
#include "zetasql/proto/internal_error_location.pb.h"
#include <cstdint>
#include "zetasql/base/statusor.h"
#include "unicode/umachine.h"
#include "unicode/utf8.h"
#include "zetasql/base/mathutil.h"
#include "zetasql/base/canonical_errors.h"
#include "zetasql/base/ret_check.h"
#include "zetasql/base/status_builder.h"
namespace zetasql {
const int kTabWidth = 8;
InternalErrorLocation ParseLocationPoint::ToInternalErrorLocation() const {
InternalErrorLocation error_location;
if (!filename_.empty()) {
error_location.set_filename(std::string(filename_));
}
error_location.set_byte_offset(byte_offset_);
return error_location;
}
ParseLocationPoint ParseLocationPoint::FromInternalErrorLocation(
const InternalErrorLocation& info) {
return ParseLocationPoint::FromByteOffset(info.filename(),
info.byte_offset());
}
ParseLocationTranslator::ParseLocationTranslator(absl::string_view input)
: input_(input) {}
void ParseLocationTranslator::CalculateLineOffsets() const {
if (line_offsets_.empty()) {
line_offsets_.push_back(0); // Line 1 starts at offset 0.
int offset = 0;
while (offset < input_.size()) {
switch (input_[offset]) {
case '\n':
line_offsets_.push_back(++offset);
break;
case '\r':
if (offset + 1 < input_.size() && input_[offset + 1] == '\n') {
++offset;
}
line_offsets_.push_back(++offset);
break;
default:
++offset;
break;
}
}
}
}
namespace {
// Helper function used when iterating through a line of text to advance one
// character.
//
// On input, <byte_offset> points to a byte offset within <current_line>
// and <column> points to the one-based column number of <byte_offset>.
//
// On output, advances <*byte_offset> and <*column> by the number of bytes
// and columns represented by the current character, respectively.
//
// In most cases, one byte <=> one char <=> one column, but not always.
// <current_line> is processed as UTF-8, and multi-byte characters map to just
// one column. In addition, the tab character ('\t') advances the column number
// forward to the nearest multiple of kTabSize, so multiple columns contained
// within a single byte are also possible.
//
// Since <current_line> is assumed to represent a single line of text (not
// including the terminating newline character), we are assumed to never
// encounter newline characters within <current_line>.
//
// <stop_byte_offset> and <stop_column>, if present, specify a byte offset and
// column number which we will never advance past, even if <stop_byte_offset>
// is in the middle of a character, or <stop_column> is in the middle of a
// tab expansion. If either of these constraints are hit, we return Ok and
// partially advance either the byte offset or the column, up to the limit
// provided.
//
// If the current byte offset points at an invalid utf-8 sequence, we advance
// one column.
//
// Returns a generic::internal error if <*byte_offset> is out of bounds with
// respect to <current_line>
absl::Status AdvanceOneChar(absl::string_view current_line,
absl::optional<int> stop_byte_offset,
absl::optional<int> stop_column, int* column,
int* byte_offset) {
ZETASQL_RET_CHECK_GE(*byte_offset, 0) << "Negative byte offset";
ZETASQL_RET_CHECK_LT(*byte_offset, current_line.length())
<< "Byte offset beyond the last column of line";
if (current_line[*byte_offset] == '\t') {
int new_column = zetasql_base::MathUtil::RoundUpTo(*column, kTabWidth) + 1;
if (stop_column.has_value() && new_column > stop_column.value()) {
// <stop_column> points to whitespace in the middle of tab expansion.
*column = stop_column.value();
} else {
*column = new_column;
++*byte_offset;
}
return absl::OkStatus();
}
// Figure out the length of the current UTF-8 character. Note that
// <new_byte_offset> and <current_code_point> are passed by reference and
// modified by the U8_NEXT() macro. On output, <new_byte_offset> is the
// byte offset of the end of the current character and <current_code_point>
// is the code point of the current character, or a negative value in case of
// error.
int new_byte_offset = *byte_offset;
UChar32 current_code_point;
U8_NEXT(current_line.data(), new_byte_offset, current_line.length(),
current_code_point);
if (current_code_point < 0) {
// The line contains invalid utf-8, so just fall back to advancing a
// single byte.
new_byte_offset = *byte_offset + 1;
}
if (stop_byte_offset.has_value() &&
new_byte_offset > stop_byte_offset.value()) {
// <*stop_byte_offset> represents a byte in the middle of the UTF-8
// character.
*byte_offset = stop_byte_offset.value();
} else {
++*column;
*byte_offset = new_byte_offset;
}
return absl::OkStatus();
}
zetasql_base::StatusOr<int> ColumnNumberFromLineLocalByteOffset(
absl::string_view current_line, int desired_byte_offset) {
int column = 1; // Column numbers are one-based.
int byte_offset = 0;
while (byte_offset < desired_byte_offset) {
ZETASQL_RETURN_IF_ERROR(AdvanceOneChar(
current_line, /*stop_byte_offset=*/desired_byte_offset,
/*stop_column=*/absl::optional<int>(), &column, &byte_offset));
}
return column;
}
} // namespace
zetasql_base::StatusOr<std::pair<int, int>>
ParseLocationTranslator::GetLineAndColumnFromByteOffset(int byte_offset) const {
DCHECK_GE(byte_offset, 0);
DCHECK_LE(byte_offset, input_.size());
ZETASQL_RET_CHECK(byte_offset >= 0 &&
byte_offset <= static_cast<int64_t>(input_.size()))
<< "Byte offset " << byte_offset << " out of bounds of input (size "
<< input_.size() << ")";
CalculateLineOffsets();
DCHECK_EQ(line_offsets_[0], 0);
DCHECK(!line_offsets_.empty());
DCHECK_EQ(line_offsets_.front(), 0);
auto ub_iter =
std::upper_bound(line_offsets_.begin(), line_offsets_.end(), byte_offset);
// ub_iter points at the beginning of the *next* line.
--ub_iter;
const int line_number =
static_cast<int>(std::distance(line_offsets_.begin(), ub_iter) + 1);
ZETASQL_ASSIGN_OR_RETURN(absl::string_view current_line, GetLineText(line_number));
ZETASQL_ASSIGN_OR_RETURN(
int column_number,
ColumnNumberFromLineLocalByteOffset(
current_line, byte_offset - line_offsets_[line_number - 1]),
_ << "\nByte offset: " << byte_offset << "\nError in line " << line_number
<< ", which starts at byte offset " << line_offsets_[line_number - 1]);
return std::make_pair(line_number, column_number);
}
zetasql_base::StatusOr<int> ParseLocationTranslator::GetByteOffsetFromLineAndColumn(
int line, int column) const {
ZETASQL_RET_CHECK_GE(line, 1);
ZETASQL_RET_CHECK_GE(column, 1);
CalculateLineOffsets();
// Find the offset corresponding to the line number.
ZETASQL_RET_CHECK_LE(line, line_offsets_.size())
<< "No line " << line << " in " << input_;
ZETASQL_ASSIGN_OR_RETURN(absl::string_view current_line, GetLineText(line));
DCHECK_EQ(current_line.find('\r'), current_line.npos)
<< "GetLineText() returned string with newline characters";
DCHECK_EQ(current_line.find('\n'), current_line.npos)
<< "GetLineText() returned string with newline characters";
int byte_offset = 0;
int curr_column = 1;
while (curr_column < column) {
ZETASQL_RETURN_IF_ERROR(AdvanceOneChar(current_line,
/*stop_byte_offset=*/absl::optional<int>(),
/*stop_column=*/column, &curr_column,
&byte_offset));
}
return line_offsets_[line - 1] + byte_offset;
}
zetasql_base::StatusOr<std::pair<int, int>>
ParseLocationTranslator::GetLineAndColumnAfterTabExpansion(
ParseLocationPoint point) const {
return GetLineAndColumnFromByteOffset(point.GetByteOffset());
}
// Return <input> with tabs expanded to spaces, assuming kTabWidth-char tabs.
std::string ParseLocationTranslator::ExpandTabs(absl::string_view input) {
std::string out;
for (int i = 0; i < input.size(); ++i) {
DCHECK(input[i] != '\n' && input[i] != '\r');
if (input[i] == '\t') {
out += std::string(kTabWidth - (out.size() % kTabWidth), ' ');
} else {
out += input[i];
}
}
return out;
}
zetasql_base::StatusOr<absl::string_view> ParseLocationTranslator::GetLineText(
int line) const {
CalculateLineOffsets();
ZETASQL_RET_CHECK_GT(line, 0) << "Line number <= 0";
ZETASQL_RET_CHECK_LE(line, line_offsets_.size())
<< "No line " << line << " in " << input_;
const int line_index = line - 1;
const int line_start_offset = line_offsets_[line_index];
int line_end_offset;
if (line_index == line_offsets_.size() - 1) {
line_end_offset = static_cast<int>(input_.size());
} else {
line_end_offset = line_offsets_[line_index + 1] - 1;
}
// If the line ends with "\r\n", don't include the "\r" as part of the line.
if (line_end_offset > 0 && line_end_offset < input_.size() &&
input_[line_end_offset] == '\n' && input_[line_end_offset - 1] == '\r') {
--line_end_offset;
}
return input_.substr(line_start_offset, line_end_offset - line_start_offset);
}
} // namespace zetasql
|
//===-- AArch64ISelDAGToDAG.cpp - A dag to dag inst selector for AArch64 --===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file defines an instruction selector for the AArch64 target.
//
//===----------------------------------------------------------------------===//
#include "AArch64MachineFunctionInfo.h"
#include "AArch64TargetMachine.h"
#include "MCTargetDesc/AArch64AddressingModes.h"
#include "llvm/ADT/APSInt.h"
#include "llvm/CodeGen/SelectionDAGISel.h"
#include "llvm/IR/Function.h" // To access function attributes.
#include "llvm/IR/GlobalValue.h"
#include "llvm/IR/Intrinsics.h"
#include "llvm/IR/IntrinsicsAArch64.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/KnownBits.h"
#include "llvm/Support/MathExtras.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
#define DEBUG_TYPE "aarch64-isel"
//===--------------------------------------------------------------------===//
/// AArch64DAGToDAGISel - AArch64 specific code to select AArch64 machine
/// instructions for SelectionDAG operations.
///
namespace {
class AArch64DAGToDAGISel : public SelectionDAGISel {
/// Subtarget - Keep a pointer to the AArch64Subtarget around so that we can
/// make the right decision when generating code for different targets.
const AArch64Subtarget *Subtarget;
public:
explicit AArch64DAGToDAGISel(AArch64TargetMachine &tm,
CodeGenOpt::Level OptLevel)
: SelectionDAGISel(tm, OptLevel), Subtarget(nullptr) {}
StringRef getPassName() const override {
return "AArch64 Instruction Selection";
}
bool runOnMachineFunction(MachineFunction &MF) override {
Subtarget = &MF.getSubtarget<AArch64Subtarget>();
return SelectionDAGISel::runOnMachineFunction(MF);
}
void Select(SDNode *Node) override;
/// SelectInlineAsmMemoryOperand - Implement addressing mode selection for
/// inline asm expressions.
bool SelectInlineAsmMemoryOperand(const SDValue &Op,
unsigned ConstraintID,
std::vector<SDValue> &OutOps) override;
template <signed Low, signed High, signed Scale>
bool SelectRDVLImm(SDValue N, SDValue &Imm);
bool tryMLAV64LaneV128(SDNode *N);
bool tryMULLV64LaneV128(unsigned IntNo, SDNode *N);
bool SelectArithExtendedRegister(SDValue N, SDValue &Reg, SDValue &Shift);
bool SelectArithImmed(SDValue N, SDValue &Val, SDValue &Shift);
bool SelectNegArithImmed(SDValue N, SDValue &Val, SDValue &Shift);
bool SelectArithShiftedRegister(SDValue N, SDValue &Reg, SDValue &Shift) {
return SelectShiftedRegister(N, false, Reg, Shift);
}
bool SelectLogicalShiftedRegister(SDValue N, SDValue &Reg, SDValue &Shift) {
return SelectShiftedRegister(N, true, Reg, Shift);
}
bool SelectAddrModeIndexed7S8(SDValue N, SDValue &Base, SDValue &OffImm) {
return SelectAddrModeIndexed7S(N, 1, Base, OffImm);
}
bool SelectAddrModeIndexed7S16(SDValue N, SDValue &Base, SDValue &OffImm) {
return SelectAddrModeIndexed7S(N, 2, Base, OffImm);
}
bool SelectAddrModeIndexed7S32(SDValue N, SDValue &Base, SDValue &OffImm) {
return SelectAddrModeIndexed7S(N, 4, Base, OffImm);
}
bool SelectAddrModeIndexed7S64(SDValue N, SDValue &Base, SDValue &OffImm) {
return SelectAddrModeIndexed7S(N, 8, Base, OffImm);
}
bool SelectAddrModeIndexed7S128(SDValue N, SDValue &Base, SDValue &OffImm) {
return SelectAddrModeIndexed7S(N, 16, Base, OffImm);
}
bool SelectAddrModeIndexedS9S128(SDValue N, SDValue &Base, SDValue &OffImm) {
return SelectAddrModeIndexedBitWidth(N, true, 9, 16, Base, OffImm);
}
bool SelectAddrModeIndexedU6S128(SDValue N, SDValue &Base, SDValue &OffImm) {
return SelectAddrModeIndexedBitWidth(N, false, 6, 16, Base, OffImm);
}
bool SelectAddrModeIndexed8(SDValue N, SDValue &Base, SDValue &OffImm) {
return SelectAddrModeIndexed(N, 1, Base, OffImm);
}
bool SelectAddrModeIndexed16(SDValue N, SDValue &Base, SDValue &OffImm) {
return SelectAddrModeIndexed(N, 2, Base, OffImm);
}
bool SelectAddrModeIndexed32(SDValue N, SDValue &Base, SDValue &OffImm) {
return SelectAddrModeIndexed(N, 4, Base, OffImm);
}
bool SelectAddrModeIndexed64(SDValue N, SDValue &Base, SDValue &OffImm) {
return SelectAddrModeIndexed(N, 8, Base, OffImm);
}
bool SelectAddrModeIndexed128(SDValue N, SDValue &Base, SDValue &OffImm) {
return SelectAddrModeIndexed(N, 16, Base, OffImm);
}
bool SelectAddrModeUnscaled8(SDValue N, SDValue &Base, SDValue &OffImm) {
return SelectAddrModeUnscaled(N, 1, Base, OffImm);
}
bool SelectAddrModeUnscaled16(SDValue N, SDValue &Base, SDValue &OffImm) {
return SelectAddrModeUnscaled(N, 2, Base, OffImm);
}
bool SelectAddrModeUnscaled32(SDValue N, SDValue &Base, SDValue &OffImm) {
return SelectAddrModeUnscaled(N, 4, Base, OffImm);
}
bool SelectAddrModeUnscaled64(SDValue N, SDValue &Base, SDValue &OffImm) {
return SelectAddrModeUnscaled(N, 8, Base, OffImm);
}
bool SelectAddrModeUnscaled128(SDValue N, SDValue &Base, SDValue &OffImm) {
return SelectAddrModeUnscaled(N, 16, Base, OffImm);
}
template<int Width>
bool SelectAddrModeWRO(SDValue N, SDValue &Base, SDValue &Offset,
SDValue &SignExtend, SDValue &DoShift) {
return SelectAddrModeWRO(N, Width / 8, Base, Offset, SignExtend, DoShift);
}
template<int Width>
bool SelectAddrModeXRO(SDValue N, SDValue &Base, SDValue &Offset,
SDValue &SignExtend, SDValue &DoShift) {
return SelectAddrModeXRO(N, Width / 8, Base, Offset, SignExtend, DoShift);
}
bool SelectDupZeroOrUndef(SDValue N) {
switch(N->getOpcode()) {
case ISD::UNDEF:
return true;
case AArch64ISD::DUP:
case ISD::SPLAT_VECTOR: {
auto Opnd0 = N->getOperand(0);
if (auto CN = dyn_cast<ConstantSDNode>(Opnd0))
if (CN->isNullValue())
return true;
if (auto CN = dyn_cast<ConstantFPSDNode>(Opnd0))
if (CN->isZero())
return true;
break;
}
default:
break;
}
return false;
}
bool SelectDupZero(SDValue N) {
switch(N->getOpcode()) {
case AArch64ISD::DUP:
case ISD::SPLAT_VECTOR: {
auto Opnd0 = N->getOperand(0);
if (auto CN = dyn_cast<ConstantSDNode>(Opnd0))
if (CN->isNullValue())
return true;
if (auto CN = dyn_cast<ConstantFPSDNode>(Opnd0))
if (CN->isZero())
return true;
break;
}
}
return false;
}
template<MVT::SimpleValueType VT>
bool SelectSVEAddSubImm(SDValue N, SDValue &Imm, SDValue &Shift) {
return SelectSVEAddSubImm(N, VT, Imm, Shift);
}
template<MVT::SimpleValueType VT>
bool SelectSVELogicalImm(SDValue N, SDValue &Imm) {
return SelectSVELogicalImm(N, VT, Imm);
}
template <MVT::SimpleValueType VT>
bool SelectSVEArithImm(SDValue N, SDValue &Imm) {
return SelectSVEArithImm(N, VT, Imm);
}
template <unsigned Low, unsigned High, bool AllowSaturation = false>
bool SelectSVEShiftImm(SDValue N, SDValue &Imm) {
return SelectSVEShiftImm(N, Low, High, AllowSaturation, Imm);
}
// Returns a suitable CNT/INC/DEC/RDVL multiplier to calculate VSCALE*N.
template<signed Min, signed Max, signed Scale, bool Shift>
bool SelectCntImm(SDValue N, SDValue &Imm) {
if (!isa<ConstantSDNode>(N))
return false;
int64_t MulImm = cast<ConstantSDNode>(N)->getSExtValue();
if (Shift)
MulImm = 1LL << MulImm;
if ((MulImm % std::abs(Scale)) != 0)
return false;
MulImm /= Scale;
if ((MulImm >= Min) && (MulImm <= Max)) {
Imm = CurDAG->getTargetConstant(MulImm, SDLoc(N), MVT::i32);
return true;
}
return false;
}
/// Form sequences of consecutive 64/128-bit registers for use in NEON
/// instructions making use of a vector-list (e.g. ldN, tbl). Vecs must have
/// between 1 and 4 elements. If it contains a single element that is returned
/// unchanged; otherwise a REG_SEQUENCE value is returned.
SDValue createDTuple(ArrayRef<SDValue> Vecs);
SDValue createQTuple(ArrayRef<SDValue> Vecs);
// Form a sequence of SVE registers for instructions using list of vectors,
// e.g. structured loads and stores (ldN, stN).
SDValue createZTuple(ArrayRef<SDValue> Vecs);
/// Generic helper for the createDTuple/createQTuple
/// functions. Those should almost always be called instead.
SDValue createTuple(ArrayRef<SDValue> Vecs, const unsigned RegClassIDs[],
const unsigned SubRegs[]);
void SelectTable(SDNode *N, unsigned NumVecs, unsigned Opc, bool isExt);
bool tryIndexedLoad(SDNode *N);
bool trySelectStackSlotTagP(SDNode *N);
void SelectTagP(SDNode *N);
void SelectLoad(SDNode *N, unsigned NumVecs, unsigned Opc,
unsigned SubRegIdx);
void SelectPostLoad(SDNode *N, unsigned NumVecs, unsigned Opc,
unsigned SubRegIdx);
void SelectLoadLane(SDNode *N, unsigned NumVecs, unsigned Opc);
void SelectPostLoadLane(SDNode *N, unsigned NumVecs, unsigned Opc);
void SelectPredicatedLoad(SDNode *N, unsigned NumVecs, unsigned Scale,
unsigned Opc_rr, unsigned Opc_ri);
bool SelectAddrModeFrameIndexSVE(SDValue N, SDValue &Base, SDValue &OffImm);
/// SVE Reg+Imm addressing mode.
template <int64_t Min, int64_t Max>
bool SelectAddrModeIndexedSVE(SDNode *Root, SDValue N, SDValue &Base,
SDValue &OffImm);
/// SVE Reg+Reg address mode.
template <unsigned Scale>
bool SelectSVERegRegAddrMode(SDValue N, SDValue &Base, SDValue &Offset) {
return SelectSVERegRegAddrMode(N, Scale, Base, Offset);
}
void SelectStore(SDNode *N, unsigned NumVecs, unsigned Opc);
void SelectPostStore(SDNode *N, unsigned NumVecs, unsigned Opc);
void SelectStoreLane(SDNode *N, unsigned NumVecs, unsigned Opc);
void SelectPostStoreLane(SDNode *N, unsigned NumVecs, unsigned Opc);
void SelectPredicatedStore(SDNode *N, unsigned NumVecs, unsigned Scale,
unsigned Opc_rr, unsigned Opc_ri);
std::tuple<unsigned, SDValue, SDValue>
findAddrModeSVELoadStore(SDNode *N, unsigned Opc_rr, unsigned Opc_ri,
const SDValue &OldBase, const SDValue &OldOffset,
unsigned Scale);
bool tryBitfieldExtractOp(SDNode *N);
bool tryBitfieldExtractOpFromSExt(SDNode *N);
bool tryBitfieldInsertOp(SDNode *N);
bool tryBitfieldInsertInZeroOp(SDNode *N);
bool tryShiftAmountMod(SDNode *N);
bool tryHighFPExt(SDNode *N);
bool tryReadRegister(SDNode *N);
bool tryWriteRegister(SDNode *N);
// Include the pieces autogenerated from the target description.
#include "AArch64GenDAGISel.inc"
private:
bool SelectShiftedRegister(SDValue N, bool AllowROR, SDValue &Reg,
SDValue &Shift);
bool SelectAddrModeIndexed7S(SDValue N, unsigned Size, SDValue &Base,
SDValue &OffImm) {
return SelectAddrModeIndexedBitWidth(N, true, 7, Size, Base, OffImm);
}
bool SelectAddrModeIndexedBitWidth(SDValue N, bool IsSignedImm, unsigned BW,
unsigned Size, SDValue &Base,
SDValue &OffImm);
bool SelectAddrModeIndexed(SDValue N, unsigned Size, SDValue &Base,
SDValue &OffImm);
bool SelectAddrModeUnscaled(SDValue N, unsigned Size, SDValue &Base,
SDValue &OffImm);
bool SelectAddrModeWRO(SDValue N, unsigned Size, SDValue &Base,
SDValue &Offset, SDValue &SignExtend,
SDValue &DoShift);
bool SelectAddrModeXRO(SDValue N, unsigned Size, SDValue &Base,
SDValue &Offset, SDValue &SignExtend,
SDValue &DoShift);
bool isWorthFolding(SDValue V) const;
bool SelectExtendedSHL(SDValue N, unsigned Size, bool WantExtend,
SDValue &Offset, SDValue &SignExtend);
template<unsigned RegWidth>
bool SelectCVTFixedPosOperand(SDValue N, SDValue &FixedPos) {
return SelectCVTFixedPosOperand(N, FixedPos, RegWidth);
}
bool SelectCVTFixedPosOperand(SDValue N, SDValue &FixedPos, unsigned Width);
bool SelectCMP_SWAP(SDNode *N);
bool SelectSVE8BitLslImm(SDValue N, SDValue &Imm, SDValue &Shift);
bool SelectSVEAddSubImm(SDValue N, MVT VT, SDValue &Imm, SDValue &Shift);
bool SelectSVELogicalImm(SDValue N, MVT VT, SDValue &Imm);
bool SelectSVESignedArithImm(SDValue N, SDValue &Imm);
bool SelectSVEShiftImm(SDValue N, uint64_t Low, uint64_t High,
bool AllowSaturation, SDValue &Imm);
bool SelectSVEArithImm(SDValue N, MVT VT, SDValue &Imm);
bool SelectSVERegRegAddrMode(SDValue N, unsigned Scale, SDValue &Base,
SDValue &Offset);
};
} // end anonymous namespace
/// isIntImmediate - This method tests to see if the node is a constant
/// operand. If so Imm will receive the 32-bit value.
static bool isIntImmediate(const SDNode *N, uint64_t &Imm) {
if (const ConstantSDNode *C = dyn_cast<const ConstantSDNode>(N)) {
Imm = C->getZExtValue();
return true;
}
return false;
}
// isIntImmediate - This method tests to see if a constant operand.
// If so Imm will receive the value.
static bool isIntImmediate(SDValue N, uint64_t &Imm) {
return isIntImmediate(N.getNode(), Imm);
}
// isOpcWithIntImmediate - This method tests to see if the node is a specific
// opcode and that it has a immediate integer right operand.
// If so Imm will receive the 32 bit value.
static bool isOpcWithIntImmediate(const SDNode *N, unsigned Opc,
uint64_t &Imm) {
return N->getOpcode() == Opc &&
isIntImmediate(N->getOperand(1).getNode(), Imm);
}
bool AArch64DAGToDAGISel::SelectInlineAsmMemoryOperand(
const SDValue &Op, unsigned ConstraintID, std::vector<SDValue> &OutOps) {
switch(ConstraintID) {
default:
llvm_unreachable("Unexpected asm memory constraint");
case InlineAsm::Constraint_m:
case InlineAsm::Constraint_Q:
// We need to make sure that this one operand does not end up in XZR, thus
// require the address to be in a PointerRegClass register.
const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
const TargetRegisterClass *TRC = TRI->getPointerRegClass(*MF);
SDLoc dl(Op);
SDValue RC = CurDAG->getTargetConstant(TRC->getID(), dl, MVT::i64);
SDValue NewOp =
SDValue(CurDAG->getMachineNode(TargetOpcode::COPY_TO_REGCLASS,
dl, Op.getValueType(),
Op, RC), 0);
OutOps.push_back(NewOp);
return false;
}
return true;
}
/// SelectArithImmed - Select an immediate value that can be represented as
/// a 12-bit value shifted left by either 0 or 12. If so, return true with
/// Val set to the 12-bit value and Shift set to the shifter operand.
bool AArch64DAGToDAGISel::SelectArithImmed(SDValue N, SDValue &Val,
SDValue &Shift) {
// This function is called from the addsub_shifted_imm ComplexPattern,
// which lists [imm] as the list of opcode it's interested in, however
// we still need to check whether the operand is actually an immediate
// here because the ComplexPattern opcode list is only used in
// root-level opcode matching.
if (!isa<ConstantSDNode>(N.getNode()))
return false;
uint64_t Immed = cast<ConstantSDNode>(N.getNode())->getZExtValue();
unsigned ShiftAmt;
if (Immed >> 12 == 0) {
ShiftAmt = 0;
} else if ((Immed & 0xfff) == 0 && Immed >> 24 == 0) {
ShiftAmt = 12;
Immed = Immed >> 12;
} else
return false;
unsigned ShVal = AArch64_AM::getShifterImm(AArch64_AM::LSL, ShiftAmt);
SDLoc dl(N);
Val = CurDAG->getTargetConstant(Immed, dl, MVT::i32);
Shift = CurDAG->getTargetConstant(ShVal, dl, MVT::i32);
return true;
}
/// SelectNegArithImmed - As above, but negates the value before trying to
/// select it.
bool AArch64DAGToDAGISel::SelectNegArithImmed(SDValue N, SDValue &Val,
SDValue &Shift) {
// This function is called from the addsub_shifted_imm ComplexPattern,
// which lists [imm] as the list of opcode it's interested in, however
// we still need to check whether the operand is actually an immediate
// here because the ComplexPattern opcode list is only used in
// root-level opcode matching.
if (!isa<ConstantSDNode>(N.getNode()))
return false;
// The immediate operand must be a 24-bit zero-extended immediate.
uint64_t Immed = cast<ConstantSDNode>(N.getNode())->getZExtValue();
// This negation is almost always valid, but "cmp wN, #0" and "cmn wN, #0"
// have the opposite effect on the C flag, so this pattern mustn't match under
// those circumstances.
if (Immed == 0)
return false;
if (N.getValueType() == MVT::i32)
Immed = ~((uint32_t)Immed) + 1;
else
Immed = ~Immed + 1ULL;
if (Immed & 0xFFFFFFFFFF000000ULL)
return false;
Immed &= 0xFFFFFFULL;
return SelectArithImmed(CurDAG->getConstant(Immed, SDLoc(N), MVT::i32), Val,
Shift);
}
/// getShiftTypeForNode - Translate a shift node to the corresponding
/// ShiftType value.
static AArch64_AM::ShiftExtendType getShiftTypeForNode(SDValue N) {
switch (N.getOpcode()) {
default:
return AArch64_AM::InvalidShiftExtend;
case ISD::SHL:
return AArch64_AM::LSL;
case ISD::SRL:
return AArch64_AM::LSR;
case ISD::SRA:
return AArch64_AM::ASR;
case ISD::ROTR:
return AArch64_AM::ROR;
}
}
/// Determine whether it is worth it to fold SHL into the addressing
/// mode.
static bool isWorthFoldingSHL(SDValue V) {
assert(V.getOpcode() == ISD::SHL && "invalid opcode");
// It is worth folding logical shift of up to three places.
auto *CSD = dyn_cast<ConstantSDNode>(V.getOperand(1));
if (!CSD)
return false;
unsigned ShiftVal = CSD->getZExtValue();
if (ShiftVal > 3)
return false;
// Check if this particular node is reused in any non-memory related
// operation. If yes, do not try to fold this node into the address
// computation, since the computation will be kept.
const SDNode *Node = V.getNode();
for (SDNode *UI : Node->uses())
if (!isa<MemSDNode>(*UI))
for (SDNode *UII : UI->uses())
if (!isa<MemSDNode>(*UII))
return false;
return true;
}
/// Determine whether it is worth to fold V into an extended register.
bool AArch64DAGToDAGISel::isWorthFolding(SDValue V) const {
// Trivial if we are optimizing for code size or if there is only
// one use of the value.
if (CurDAG->shouldOptForSize() || V.hasOneUse())
return true;
// If a subtarget has a fastpath LSL we can fold a logical shift into
// the addressing mode and save a cycle.
if (Subtarget->hasLSLFast() && V.getOpcode() == ISD::SHL &&
isWorthFoldingSHL(V))
return true;
if (Subtarget->hasLSLFast() && V.getOpcode() == ISD::ADD) {
const SDValue LHS = V.getOperand(0);
const SDValue RHS = V.getOperand(1);
if (LHS.getOpcode() == ISD::SHL && isWorthFoldingSHL(LHS))
return true;
if (RHS.getOpcode() == ISD::SHL && isWorthFoldingSHL(RHS))
return true;
}
// It hurts otherwise, since the value will be reused.
return false;
}
/// SelectShiftedRegister - Select a "shifted register" operand. If the value
/// is not shifted, set the Shift operand to default of "LSL 0". The logical
/// instructions allow the shifted register to be rotated, but the arithmetic
/// instructions do not. The AllowROR parameter specifies whether ROR is
/// supported.
bool AArch64DAGToDAGISel::SelectShiftedRegister(SDValue N, bool AllowROR,
SDValue &Reg, SDValue &Shift) {
AArch64_AM::ShiftExtendType ShType = getShiftTypeForNode(N);
if (ShType == AArch64_AM::InvalidShiftExtend)
return false;
if (!AllowROR && ShType == AArch64_AM::ROR)
return false;
if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
unsigned BitSize = N.getValueSizeInBits();
unsigned Val = RHS->getZExtValue() & (BitSize - 1);
unsigned ShVal = AArch64_AM::getShifterImm(ShType, Val);
Reg = N.getOperand(0);
Shift = CurDAG->getTargetConstant(ShVal, SDLoc(N), MVT::i32);
return isWorthFolding(N);
}
return false;
}
/// getExtendTypeForNode - Translate an extend node to the corresponding
/// ExtendType value.
static AArch64_AM::ShiftExtendType
getExtendTypeForNode(SDValue N, bool IsLoadStore = false) {
if (N.getOpcode() == ISD::SIGN_EXTEND ||
N.getOpcode() == ISD::SIGN_EXTEND_INREG) {
EVT SrcVT;
if (N.getOpcode() == ISD::SIGN_EXTEND_INREG)
SrcVT = cast<VTSDNode>(N.getOperand(1))->getVT();
else
SrcVT = N.getOperand(0).getValueType();
if (!IsLoadStore && SrcVT == MVT::i8)
return AArch64_AM::SXTB;
else if (!IsLoadStore && SrcVT == MVT::i16)
return AArch64_AM::SXTH;
else if (SrcVT == MVT::i32)
return AArch64_AM::SXTW;
assert(SrcVT != MVT::i64 && "extend from 64-bits?");
return AArch64_AM::InvalidShiftExtend;
} else if (N.getOpcode() == ISD::ZERO_EXTEND ||
N.getOpcode() == ISD::ANY_EXTEND) {
EVT SrcVT = N.getOperand(0).getValueType();
if (!IsLoadStore && SrcVT == MVT::i8)
return AArch64_AM::UXTB;
else if (!IsLoadStore && SrcVT == MVT::i16)
return AArch64_AM::UXTH;
else if (SrcVT == MVT::i32)
return AArch64_AM::UXTW;
assert(SrcVT != MVT::i64 && "extend from 64-bits?");
return AArch64_AM::InvalidShiftExtend;
} else if (N.getOpcode() == ISD::AND) {
ConstantSDNode *CSD = dyn_cast<ConstantSDNode>(N.getOperand(1));
if (!CSD)
return AArch64_AM::InvalidShiftExtend;
uint64_t AndMask = CSD->getZExtValue();
switch (AndMask) {
default:
return AArch64_AM::InvalidShiftExtend;
case 0xFF:
return !IsLoadStore ? AArch64_AM::UXTB : AArch64_AM::InvalidShiftExtend;
case 0xFFFF:
return !IsLoadStore ? AArch64_AM::UXTH : AArch64_AM::InvalidShiftExtend;
case 0xFFFFFFFF:
return AArch64_AM::UXTW;
}
}
return AArch64_AM::InvalidShiftExtend;
}
// Helper for SelectMLAV64LaneV128 - Recognize high lane extracts.
static bool checkHighLaneIndex(SDNode *DL, SDValue &LaneOp, int &LaneIdx) {
if (DL->getOpcode() != AArch64ISD::DUPLANE16 &&
DL->getOpcode() != AArch64ISD::DUPLANE32)
return false;
SDValue SV = DL->getOperand(0);
if (SV.getOpcode() != ISD::INSERT_SUBVECTOR)
return false;
SDValue EV = SV.getOperand(1);
if (EV.getOpcode() != ISD::EXTRACT_SUBVECTOR)
return false;
ConstantSDNode *DLidx = cast<ConstantSDNode>(DL->getOperand(1).getNode());
ConstantSDNode *EVidx = cast<ConstantSDNode>(EV.getOperand(1).getNode());
LaneIdx = DLidx->getSExtValue() + EVidx->getSExtValue();
LaneOp = EV.getOperand(0);
return true;
}
// Helper for SelectOpcV64LaneV128 - Recognize operations where one operand is a
// high lane extract.
static bool checkV64LaneV128(SDValue Op0, SDValue Op1, SDValue &StdOp,
SDValue &LaneOp, int &LaneIdx) {
if (!checkHighLaneIndex(Op0.getNode(), LaneOp, LaneIdx)) {
std::swap(Op0, Op1);
if (!checkHighLaneIndex(Op0.getNode(), LaneOp, LaneIdx))
return false;
}
StdOp = Op1;
return true;
}
/// SelectMLAV64LaneV128 - AArch64 supports vector MLAs where one multiplicand
/// is a lane in the upper half of a 128-bit vector. Recognize and select this
/// so that we don't emit unnecessary lane extracts.
bool AArch64DAGToDAGISel::tryMLAV64LaneV128(SDNode *N) {
SDLoc dl(N);
SDValue Op0 = N->getOperand(0);
SDValue Op1 = N->getOperand(1);
SDValue MLAOp1; // Will hold ordinary multiplicand for MLA.
SDValue MLAOp2; // Will hold lane-accessed multiplicand for MLA.
int LaneIdx = -1; // Will hold the lane index.
if (Op1.getOpcode() != ISD::MUL ||
!checkV64LaneV128(Op1.getOperand(0), Op1.getOperand(1), MLAOp1, MLAOp2,
LaneIdx)) {
std::swap(Op0, Op1);
if (Op1.getOpcode() != ISD::MUL ||
!checkV64LaneV128(Op1.getOperand(0), Op1.getOperand(1), MLAOp1, MLAOp2,
LaneIdx))
return false;
}
SDValue LaneIdxVal = CurDAG->getTargetConstant(LaneIdx, dl, MVT::i64);
SDValue Ops[] = { Op0, MLAOp1, MLAOp2, LaneIdxVal };
unsigned MLAOpc = ~0U;
switch (N->getSimpleValueType(0).SimpleTy) {
default:
llvm_unreachable("Unrecognized MLA.");
case MVT::v4i16:
MLAOpc = AArch64::MLAv4i16_indexed;
break;
case MVT::v8i16:
MLAOpc = AArch64::MLAv8i16_indexed;
break;
case MVT::v2i32:
MLAOpc = AArch64::MLAv2i32_indexed;
break;
case MVT::v4i32:
MLAOpc = AArch64::MLAv4i32_indexed;
break;
}
ReplaceNode(N, CurDAG->getMachineNode(MLAOpc, dl, N->getValueType(0), Ops));
return true;
}
bool AArch64DAGToDAGISel::tryMULLV64LaneV128(unsigned IntNo, SDNode *N) {
SDLoc dl(N);
SDValue SMULLOp0;
SDValue SMULLOp1;
int LaneIdx;
if (!checkV64LaneV128(N->getOperand(1), N->getOperand(2), SMULLOp0, SMULLOp1,
LaneIdx))
return false;
SDValue LaneIdxVal = CurDAG->getTargetConstant(LaneIdx, dl, MVT::i64);
SDValue Ops[] = { SMULLOp0, SMULLOp1, LaneIdxVal };
unsigned SMULLOpc = ~0U;
if (IntNo == Intrinsic::aarch64_neon_smull) {
switch (N->getSimpleValueType(0).SimpleTy) {
default:
llvm_unreachable("Unrecognized SMULL.");
case MVT::v4i32:
SMULLOpc = AArch64::SMULLv4i16_indexed;
break;
case MVT::v2i64:
SMULLOpc = AArch64::SMULLv2i32_indexed;
break;
}
} else if (IntNo == Intrinsic::aarch64_neon_umull) {
switch (N->getSimpleValueType(0).SimpleTy) {
default:
llvm_unreachable("Unrecognized SMULL.");
case MVT::v4i32:
SMULLOpc = AArch64::UMULLv4i16_indexed;
break;
case MVT::v2i64:
SMULLOpc = AArch64::UMULLv2i32_indexed;
break;
}
} else
llvm_unreachable("Unrecognized intrinsic.");
ReplaceNode(N, CurDAG->getMachineNode(SMULLOpc, dl, N->getValueType(0), Ops));
return true;
}
/// Instructions that accept extend modifiers like UXTW expect the register
/// being extended to be a GPR32, but the incoming DAG might be acting on a
/// GPR64 (either via SEXT_INREG or AND). Extract the appropriate low bits if
/// this is the case.
static SDValue narrowIfNeeded(SelectionDAG *CurDAG, SDValue N) {
if (N.getValueType() == MVT::i32)
return N;
SDLoc dl(N);
SDValue SubReg = CurDAG->getTargetConstant(AArch64::sub_32, dl, MVT::i32);
MachineSDNode *Node = CurDAG->getMachineNode(TargetOpcode::EXTRACT_SUBREG,
dl, MVT::i32, N, SubReg);
return SDValue(Node, 0);
}
// Returns a suitable CNT/INC/DEC/RDVL multiplier to calculate VSCALE*N.
template<signed Low, signed High, signed Scale>
bool AArch64DAGToDAGISel::SelectRDVLImm(SDValue N, SDValue &Imm) {
if (!isa<ConstantSDNode>(N))
return false;
int64_t MulImm = cast<ConstantSDNode>(N)->getSExtValue();
if ((MulImm % std::abs(Scale)) == 0) {
int64_t RDVLImm = MulImm / Scale;
if ((RDVLImm >= Low) && (RDVLImm <= High)) {
Imm = CurDAG->getTargetConstant(RDVLImm, SDLoc(N), MVT::i32);
return true;
}
}
return false;
}
/// SelectArithExtendedRegister - Select a "extended register" operand. This
/// operand folds in an extend followed by an optional left shift.
bool AArch64DAGToDAGISel::SelectArithExtendedRegister(SDValue N, SDValue &Reg,
SDValue &Shift) {
unsigned ShiftVal = 0;
AArch64_AM::ShiftExtendType Ext;
if (N.getOpcode() == ISD::SHL) {
ConstantSDNode *CSD = dyn_cast<ConstantSDNode>(N.getOperand(1));
if (!CSD)
return false;
ShiftVal = CSD->getZExtValue();
if (ShiftVal > 4)
return false;
Ext = getExtendTypeForNode(N.getOperand(0));
if (Ext == AArch64_AM::InvalidShiftExtend)
return false;
Reg = N.getOperand(0).getOperand(0);
} else {
Ext = getExtendTypeForNode(N);
if (Ext == AArch64_AM::InvalidShiftExtend)
return false;
Reg = N.getOperand(0);
// Don't match if free 32-bit -> 64-bit zext can be used instead.
if (Ext == AArch64_AM::UXTW &&
Reg->getValueType(0).getSizeInBits() == 32 && isDef32(*Reg.getNode()))
return false;
}
// AArch64 mandates that the RHS of the operation must use the smallest
// register class that could contain the size being extended from. Thus,
// if we're folding a (sext i8), we need the RHS to be a GPR32, even though
// there might not be an actual 32-bit value in the program. We can
// (harmlessly) synthesize one by injected an EXTRACT_SUBREG here.
assert(Ext != AArch64_AM::UXTX && Ext != AArch64_AM::SXTX);
Reg = narrowIfNeeded(CurDAG, Reg);
Shift = CurDAG->getTargetConstant(getArithExtendImm(Ext, ShiftVal), SDLoc(N),
MVT::i32);
return isWorthFolding(N);
}
/// If there's a use of this ADDlow that's not itself a load/store then we'll
/// need to create a real ADD instruction from it anyway and there's no point in
/// folding it into the mem op. Theoretically, it shouldn't matter, but there's
/// a single pseudo-instruction for an ADRP/ADD pair so over-aggressive folding
/// leads to duplicated ADRP instructions.
static bool isWorthFoldingADDlow(SDValue N) {
for (auto Use : N->uses()) {
if (Use->getOpcode() != ISD::LOAD && Use->getOpcode() != ISD::STORE &&
Use->getOpcode() != ISD::ATOMIC_LOAD &&
Use->getOpcode() != ISD::ATOMIC_STORE)
return false;
// ldar and stlr have much more restrictive addressing modes (just a
// register).
if (isStrongerThanMonotonic(cast<MemSDNode>(Use)->getOrdering()))
return false;
}
return true;
}
/// SelectAddrModeIndexedBitWidth - Select a "register plus scaled (un)signed BW-bit
/// immediate" address. The "Size" argument is the size in bytes of the memory
/// reference, which determines the scale.
bool AArch64DAGToDAGISel::SelectAddrModeIndexedBitWidth(SDValue N, bool IsSignedImm,
unsigned BW, unsigned Size,
SDValue &Base,
SDValue &OffImm) {
SDLoc dl(N);
const DataLayout &DL = CurDAG->getDataLayout();
const TargetLowering *TLI = getTargetLowering();
if (N.getOpcode() == ISD::FrameIndex) {
int FI = cast<FrameIndexSDNode>(N)->getIndex();
Base = CurDAG->getTargetFrameIndex(FI, TLI->getPointerTy(DL));
OffImm = CurDAG->getTargetConstant(0, dl, MVT::i64);
return true;
}
// As opposed to the (12-bit) Indexed addressing mode below, the 7/9-bit signed
// selected here doesn't support labels/immediates, only base+offset.
if (CurDAG->isBaseWithConstantOffset(N)) {
if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
if (IsSignedImm) {
int64_t RHSC = RHS->getSExtValue();
unsigned Scale = Log2_32(Size);
int64_t Range = 0x1LL << (BW - 1);
if ((RHSC & (Size - 1)) == 0 && RHSC >= -(Range << Scale) &&
RHSC < (Range << Scale)) {
Base = N.getOperand(0);
if (Base.getOpcode() == ISD::FrameIndex) {
int FI = cast<FrameIndexSDNode>(Base)->getIndex();
Base = CurDAG->getTargetFrameIndex(FI, TLI->getPointerTy(DL));
}
OffImm = CurDAG->getTargetConstant(RHSC >> Scale, dl, MVT::i64);
return true;
}
} else {
// unsigned Immediate
uint64_t RHSC = RHS->getZExtValue();
unsigned Scale = Log2_32(Size);
uint64_t Range = 0x1ULL << BW;
if ((RHSC & (Size - 1)) == 0 && RHSC < (Range << Scale)) {
Base = N.getOperand(0);
if (Base.getOpcode() == ISD::FrameIndex) {
int FI = cast<FrameIndexSDNode>(Base)->getIndex();
Base = CurDAG->getTargetFrameIndex(FI, TLI->getPointerTy(DL));
}
OffImm = CurDAG->getTargetConstant(RHSC >> Scale, dl, MVT::i64);
return true;
}
}
}
}
// Base only. The address will be materialized into a register before
// the memory is accessed.
// add x0, Xbase, #offset
// stp x1, x2, [x0]
Base = N;
OffImm = CurDAG->getTargetConstant(0, dl, MVT::i64);
return true;
}
/// SelectAddrModeIndexed - Select a "register plus scaled unsigned 12-bit
/// immediate" address. The "Size" argument is the size in bytes of the memory
/// reference, which determines the scale.
bool AArch64DAGToDAGISel::SelectAddrModeIndexed(SDValue N, unsigned Size,
SDValue &Base, SDValue &OffImm) {
SDLoc dl(N);
const DataLayout &DL = CurDAG->getDataLayout();
const TargetLowering *TLI = getTargetLowering();
if (N.getOpcode() == ISD::FrameIndex) {
int FI = cast<FrameIndexSDNode>(N)->getIndex();
Base = CurDAG->getTargetFrameIndex(FI, TLI->getPointerTy(DL));
OffImm = CurDAG->getTargetConstant(0, dl, MVT::i64);
return true;
}
if (N.getOpcode() == AArch64ISD::ADDlow && isWorthFoldingADDlow(N)) {
GlobalAddressSDNode *GAN =
dyn_cast<GlobalAddressSDNode>(N.getOperand(1).getNode());
Base = N.getOperand(0);
OffImm = N.getOperand(1);
if (!GAN)
return true;
if (GAN->getOffset() % Size == 0 &&
GAN->getGlobal()->getPointerAlignment(DL) >= Size)
return true;
}
if (CurDAG->isBaseWithConstantOffset(N)) {
if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
int64_t RHSC = (int64_t)RHS->getZExtValue();
unsigned Scale = Log2_32(Size);
if ((RHSC & (Size - 1)) == 0 && RHSC >= 0 && RHSC < (0x1000 << Scale)) {
Base = N.getOperand(0);
if (Base.getOpcode() == ISD::FrameIndex) {
int FI = cast<FrameIndexSDNode>(Base)->getIndex();
Base = CurDAG->getTargetFrameIndex(FI, TLI->getPointerTy(DL));
}
OffImm = CurDAG->getTargetConstant(RHSC >> Scale, dl, MVT::i64);
return true;
}
}
}
// Before falling back to our general case, check if the unscaled
// instructions can handle this. If so, that's preferable.
if (SelectAddrModeUnscaled(N, Size, Base, OffImm))
return false;
// Base only. The address will be materialized into a register before
// the memory is accessed.
// add x0, Xbase, #offset
// ldr x0, [x0]
Base = N;
OffImm = CurDAG->getTargetConstant(0, dl, MVT::i64);
return true;
}
/// SelectAddrModeUnscaled - Select a "register plus unscaled signed 9-bit
/// immediate" address. This should only match when there is an offset that
/// is not valid for a scaled immediate addressing mode. The "Size" argument
/// is the size in bytes of the memory reference, which is needed here to know
/// what is valid for a scaled immediate.
bool AArch64DAGToDAGISel::SelectAddrModeUnscaled(SDValue N, unsigned Size,
SDValue &Base,
SDValue &OffImm) {
if (!CurDAG->isBaseWithConstantOffset(N))
return false;
if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
int64_t RHSC = RHS->getSExtValue();
// If the offset is valid as a scaled immediate, don't match here.
if ((RHSC & (Size - 1)) == 0 && RHSC >= 0 &&
RHSC < (0x1000 << Log2_32(Size)))
return false;
if (RHSC >= -256 && RHSC < 256) {
Base = N.getOperand(0);
if (Base.getOpcode() == ISD::FrameIndex) {
int FI = cast<FrameIndexSDNode>(Base)->getIndex();
const TargetLowering *TLI = getTargetLowering();
Base = CurDAG->getTargetFrameIndex(
FI, TLI->getPointerTy(CurDAG->getDataLayout()));
}
OffImm = CurDAG->getTargetConstant(RHSC, SDLoc(N), MVT::i64);
return true;
}
}
return false;
}
static SDValue Widen(SelectionDAG *CurDAG, SDValue N) {
SDLoc dl(N);
SDValue SubReg = CurDAG->getTargetConstant(AArch64::sub_32, dl, MVT::i32);
SDValue ImpDef = SDValue(
CurDAG->getMachineNode(TargetOpcode::IMPLICIT_DEF, dl, MVT::i64), 0);
MachineSDNode *Node = CurDAG->getMachineNode(
TargetOpcode::INSERT_SUBREG, dl, MVT::i64, ImpDef, N, SubReg);
return SDValue(Node, 0);
}
/// Check if the given SHL node (\p N), can be used to form an
/// extended register for an addressing mode.
bool AArch64DAGToDAGISel::SelectExtendedSHL(SDValue N, unsigned Size,
bool WantExtend, SDValue &Offset,
SDValue &SignExtend) {
assert(N.getOpcode() == ISD::SHL && "Invalid opcode.");
ConstantSDNode *CSD = dyn_cast<ConstantSDNode>(N.getOperand(1));
if (!CSD || (CSD->getZExtValue() & 0x7) != CSD->getZExtValue())
return false;
SDLoc dl(N);
if (WantExtend) {
AArch64_AM::ShiftExtendType Ext =
getExtendTypeForNode(N.getOperand(0), true);
if (Ext == AArch64_AM::InvalidShiftExtend)
return false;
Offset = narrowIfNeeded(CurDAG, N.getOperand(0).getOperand(0));
SignExtend = CurDAG->getTargetConstant(Ext == AArch64_AM::SXTW, dl,
MVT::i32);
} else {
Offset = N.getOperand(0);
SignExtend = CurDAG->getTargetConstant(0, dl, MVT::i32);
}
unsigned LegalShiftVal = Log2_32(Size);
unsigned ShiftVal = CSD->getZExtValue();
if (ShiftVal != 0 && ShiftVal != LegalShiftVal)
return false;
return isWorthFolding(N);
}
bool AArch64DAGToDAGISel::SelectAddrModeWRO(SDValue N, unsigned Size,
SDValue &Base, SDValue &Offset,
SDValue &SignExtend,
SDValue &DoShift) {
if (N.getOpcode() != ISD::ADD)
return false;
SDValue LHS = N.getOperand(0);
SDValue RHS = N.getOperand(1);
SDLoc dl(N);
// We don't want to match immediate adds here, because they are better lowered
// to the register-immediate addressing modes.
if (isa<ConstantSDNode>(LHS) || isa<ConstantSDNode>(RHS))
return false;
// Check if this particular node is reused in any non-memory related
// operation. If yes, do not try to fold this node into the address
// computation, since the computation will be kept.
const SDNode *Node = N.getNode();
for (SDNode *UI : Node->uses()) {
if (!isa<MemSDNode>(*UI))
return false;
}
// Remember if it is worth folding N when it produces extended register.
bool IsExtendedRegisterWorthFolding = isWorthFolding(N);
// Try to match a shifted extend on the RHS.
if (IsExtendedRegisterWorthFolding && RHS.getOpcode() == ISD::SHL &&
SelectExtendedSHL(RHS, Size, true, Offset, SignExtend)) {
Base = LHS;
DoShift = CurDAG->getTargetConstant(true, dl, MVT::i32);
return true;
}
// Try to match a shifted extend on the LHS.
if (IsExtendedRegisterWorthFolding && LHS.getOpcode() == ISD::SHL &&
SelectExtendedSHL(LHS, Size, true, Offset, SignExtend)) {
Base = RHS;
DoShift = CurDAG->getTargetConstant(true, dl, MVT::i32);
return true;
}
// There was no shift, whatever else we find.
DoShift = CurDAG->getTargetConstant(false, dl, MVT::i32);
AArch64_AM::ShiftExtendType Ext = AArch64_AM::InvalidShiftExtend;
// Try to match an unshifted extend on the LHS.
if (IsExtendedRegisterWorthFolding &&
(Ext = getExtendTypeForNode(LHS, true)) !=
AArch64_AM::InvalidShiftExtend) {
Base = RHS;
Offset = narrowIfNeeded(CurDAG, LHS.getOperand(0));
SignExtend = CurDAG->getTargetConstant(Ext == AArch64_AM::SXTW, dl,
MVT::i32);
if (isWorthFolding(LHS))
return true;
}
// Try to match an unshifted extend on the RHS.
if (IsExtendedRegisterWorthFolding &&
(Ext = getExtendTypeForNode(RHS, true)) !=
AArch64_AM::InvalidShiftExtend) {
Base = LHS;
Offset = narrowIfNeeded(CurDAG, RHS.getOperand(0));
SignExtend = CurDAG->getTargetConstant(Ext == AArch64_AM::SXTW, dl,
MVT::i32);
if (isWorthFolding(RHS))
return true;
}
return false;
}
// Check if the given immediate is preferred by ADD. If an immediate can be
// encoded in an ADD, or it can be encoded in an "ADD LSL #12" and can not be
// encoded by one MOVZ, return true.
static bool isPreferredADD(int64_t ImmOff) {
// Constant in [0x0, 0xfff] can be encoded in ADD.
if ((ImmOff & 0xfffffffffffff000LL) == 0x0LL)
return true;
// Check if it can be encoded in an "ADD LSL #12".
if ((ImmOff & 0xffffffffff000fffLL) == 0x0LL)
// As a single MOVZ is faster than a "ADD of LSL #12", ignore such constant.
return (ImmOff & 0xffffffffff00ffffLL) != 0x0LL &&
(ImmOff & 0xffffffffffff0fffLL) != 0x0LL;
return false;
}
bool AArch64DAGToDAGISel::SelectAddrModeXRO(SDValue N, unsigned Size,
SDValue &Base, SDValue &Offset,
SDValue &SignExtend,
SDValue &DoShift) {
if (N.getOpcode() != ISD::ADD)
return false;
SDValue LHS = N.getOperand(0);
SDValue RHS = N.getOperand(1);
SDLoc DL(N);
// Check if this particular node is reused in any non-memory related
// operation. If yes, do not try to fold this node into the address
// computation, since the computation will be kept.
const SDNode *Node = N.getNode();
for (SDNode *UI : Node->uses()) {
if (!isa<MemSDNode>(*UI))
return false;
}
// Watch out if RHS is a wide immediate, it can not be selected into
// [BaseReg+Imm] addressing mode. Also it may not be able to be encoded into
// ADD/SUB. Instead it will use [BaseReg + 0] address mode and generate
// instructions like:
// MOV X0, WideImmediate
// ADD X1, BaseReg, X0
// LDR X2, [X1, 0]
// For such situation, using [BaseReg, XReg] addressing mode can save one
// ADD/SUB:
// MOV X0, WideImmediate
// LDR X2, [BaseReg, X0]
if (isa<ConstantSDNode>(RHS)) {
int64_t ImmOff = (int64_t)cast<ConstantSDNode>(RHS)->getZExtValue();
unsigned Scale = Log2_32(Size);
// Skip the immediate can be selected by load/store addressing mode.
// Also skip the immediate can be encoded by a single ADD (SUB is also
// checked by using -ImmOff).
if ((ImmOff % Size == 0 && ImmOff >= 0 && ImmOff < (0x1000 << Scale)) ||
isPreferredADD(ImmOff) || isPreferredADD(-ImmOff))
return false;
SDValue Ops[] = { RHS };
SDNode *MOVI =
CurDAG->getMachineNode(AArch64::MOVi64imm, DL, MVT::i64, Ops);
SDValue MOVIV = SDValue(MOVI, 0);
// This ADD of two X register will be selected into [Reg+Reg] mode.
N = CurDAG->getNode(ISD::ADD, DL, MVT::i64, LHS, MOVIV);
}
// Remember if it is worth folding N when it produces extended register.
bool IsExtendedRegisterWorthFolding = isWorthFolding(N);
// Try to match a shifted extend on the RHS.
if (IsExtendedRegisterWorthFolding && RHS.getOpcode() == ISD::SHL &&
SelectExtendedSHL(RHS, Size, false, Offset, SignExtend)) {
Base = LHS;
DoShift = CurDAG->getTargetConstant(true, DL, MVT::i32);
return true;
}
// Try to match a shifted extend on the LHS.
if (IsExtendedRegisterWorthFolding && LHS.getOpcode() == ISD::SHL &&
SelectExtendedSHL(LHS, Size, false, Offset, SignExtend)) {
Base = RHS;
DoShift = CurDAG->getTargetConstant(true, DL, MVT::i32);
return true;
}
// Match any non-shifted, non-extend, non-immediate add expression.
Base = LHS;
Offset = RHS;
SignExtend = CurDAG->getTargetConstant(false, DL, MVT::i32);
DoShift = CurDAG->getTargetConstant(false, DL, MVT::i32);
// Reg1 + Reg2 is free: no check needed.
return true;
}
SDValue AArch64DAGToDAGISel::createDTuple(ArrayRef<SDValue> Regs) {
static const unsigned RegClassIDs[] = {
AArch64::DDRegClassID, AArch64::DDDRegClassID, AArch64::DDDDRegClassID};
static const unsigned SubRegs[] = {AArch64::dsub0, AArch64::dsub1,
AArch64::dsub2, AArch64::dsub3};
return createTuple(Regs, RegClassIDs, SubRegs);
}
SDValue AArch64DAGToDAGISel::createQTuple(ArrayRef<SDValue> Regs) {
static const unsigned RegClassIDs[] = {
AArch64::QQRegClassID, AArch64::QQQRegClassID, AArch64::QQQQRegClassID};
static const unsigned SubRegs[] = {AArch64::qsub0, AArch64::qsub1,
AArch64::qsub2, AArch64::qsub3};
return createTuple(Regs, RegClassIDs, SubRegs);
}
SDValue AArch64DAGToDAGISel::createZTuple(ArrayRef<SDValue> Regs) {
static const unsigned RegClassIDs[] = {AArch64::ZPR2RegClassID,
AArch64::ZPR3RegClassID,
AArch64::ZPR4RegClassID};
static const unsigned SubRegs[] = {AArch64::zsub0, AArch64::zsub1,
AArch64::zsub2, AArch64::zsub3};
return createTuple(Regs, RegClassIDs, SubRegs);
}
SDValue AArch64DAGToDAGISel::createTuple(ArrayRef<SDValue> Regs,
const unsigned RegClassIDs[],
const unsigned SubRegs[]) {
// There's no special register-class for a vector-list of 1 element: it's just
// a vector.
if (Regs.size() == 1)
return Regs[0];
assert(Regs.size() >= 2 && Regs.size() <= 4);
SDLoc DL(Regs[0]);
SmallVector<SDValue, 4> Ops;
// First operand of REG_SEQUENCE is the desired RegClass.
Ops.push_back(
CurDAG->getTargetConstant(RegClassIDs[Regs.size() - 2], DL, MVT::i32));
// Then we get pairs of source & subregister-position for the components.
for (unsigned i = 0; i < Regs.size(); ++i) {
Ops.push_back(Regs[i]);
Ops.push_back(CurDAG->getTargetConstant(SubRegs[i], DL, MVT::i32));
}
SDNode *N =
CurDAG->getMachineNode(TargetOpcode::REG_SEQUENCE, DL, MVT::Untyped, Ops);
return SDValue(N, 0);
}
void AArch64DAGToDAGISel::SelectTable(SDNode *N, unsigned NumVecs, unsigned Opc,
bool isExt) {
SDLoc dl(N);
EVT VT = N->getValueType(0);
unsigned ExtOff = isExt;
// Form a REG_SEQUENCE to force register allocation.
unsigned Vec0Off = ExtOff + 1;
SmallVector<SDValue, 4> Regs(N->op_begin() + Vec0Off,
N->op_begin() + Vec0Off + NumVecs);
SDValue RegSeq = createQTuple(Regs);
SmallVector<SDValue, 6> Ops;
if (isExt)
Ops.push_back(N->getOperand(1));
Ops.push_back(RegSeq);
Ops.push_back(N->getOperand(NumVecs + ExtOff + 1));
ReplaceNode(N, CurDAG->getMachineNode(Opc, dl, VT, Ops));
}
bool AArch64DAGToDAGISel::tryIndexedLoad(SDNode *N) {
LoadSDNode *LD = cast<LoadSDNode>(N);
if (LD->isUnindexed())
return false;
EVT VT = LD->getMemoryVT();
EVT DstVT = N->getValueType(0);
ISD::MemIndexedMode AM = LD->getAddressingMode();
bool IsPre = AM == ISD::PRE_INC || AM == ISD::PRE_DEC;
// We're not doing validity checking here. That was done when checking
// if we should mark the load as indexed or not. We're just selecting
// the right instruction.
unsigned Opcode = 0;
ISD::LoadExtType ExtType = LD->getExtensionType();
bool InsertTo64 = false;
if (VT == MVT::i64)
Opcode = IsPre ? AArch64::LDRXpre : AArch64::LDRXpost;
else if (VT == MVT::i32) {
if (ExtType == ISD::NON_EXTLOAD)
Opcode = IsPre ? AArch64::LDRWpre : AArch64::LDRWpost;
else if (ExtType == ISD::SEXTLOAD)
Opcode = IsPre ? AArch64::LDRSWpre : AArch64::LDRSWpost;
else {
Opcode = IsPre ? AArch64::LDRWpre : AArch64::LDRWpost;
InsertTo64 = true;
// The result of the load is only i32. It's the subreg_to_reg that makes
// it into an i64.
DstVT = MVT::i32;
}
} else if (VT == MVT::i16) {
if (ExtType == ISD::SEXTLOAD) {
if (DstVT == MVT::i64)
Opcode = IsPre ? AArch64::LDRSHXpre : AArch64::LDRSHXpost;
else
Opcode = IsPre ? AArch64::LDRSHWpre : AArch64::LDRSHWpost;
} else {
Opcode = IsPre ? AArch64::LDRHHpre : AArch64::LDRHHpost;
InsertTo64 = DstVT == MVT::i64;
// The result of the load is only i32. It's the subreg_to_reg that makes
// it into an i64.
DstVT = MVT::i32;
}
} else if (VT == MVT::i8) {
if (ExtType == ISD::SEXTLOAD) {
if (DstVT == MVT::i64)
Opcode = IsPre ? AArch64::LDRSBXpre : AArch64::LDRSBXpost;
else
Opcode = IsPre ? AArch64::LDRSBWpre : AArch64::LDRSBWpost;
} else {
Opcode = IsPre ? AArch64::LDRBBpre : AArch64::LDRBBpost;
InsertTo64 = DstVT == MVT::i64;
// The result of the load is only i32. It's the subreg_to_reg that makes
// it into an i64.
DstVT = MVT::i32;
}
} else if (VT == MVT::f16) {
Opcode = IsPre ? AArch64::LDRHpre : AArch64::LDRHpost;
} else if (VT == MVT::bf16) {
Opcode = IsPre ? AArch64::LDRHpre : AArch64::LDRHpost;
} else if (VT == MVT::f32) {
Opcode = IsPre ? AArch64::LDRSpre : AArch64::LDRSpost;
} else if (VT == MVT::f64 || VT.is64BitVector()) {
Opcode = IsPre ? AArch64::LDRDpre : AArch64::LDRDpost;
} else if (VT.is128BitVector()) {
Opcode = IsPre ? AArch64::LDRQpre : AArch64::LDRQpost;
} else
return false;
SDValue Chain = LD->getChain();
SDValue Base = LD->getBasePtr();
ConstantSDNode *OffsetOp = cast<ConstantSDNode>(LD->getOffset());
int OffsetVal = (int)OffsetOp->getZExtValue();
SDLoc dl(N);
SDValue Offset = CurDAG->getTargetConstant(OffsetVal, dl, MVT::i64);
SDValue Ops[] = { Base, Offset, Chain };
SDNode *Res = CurDAG->getMachineNode(Opcode, dl, MVT::i64, DstVT,
MVT::Other, Ops);
// Transfer memoperands.
MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand();
CurDAG->setNodeMemRefs(cast<MachineSDNode>(Res), {MemOp});
// Either way, we're replacing the node, so tell the caller that.
SDValue LoadedVal = SDValue(Res, 1);
if (InsertTo64) {
SDValue SubReg = CurDAG->getTargetConstant(AArch64::sub_32, dl, MVT::i32);
LoadedVal =
SDValue(CurDAG->getMachineNode(
AArch64::SUBREG_TO_REG, dl, MVT::i64,
CurDAG->getTargetConstant(0, dl, MVT::i64), LoadedVal,
SubReg),
0);
}
ReplaceUses(SDValue(N, 0), LoadedVal);
ReplaceUses(SDValue(N, 1), SDValue(Res, 0));
ReplaceUses(SDValue(N, 2), SDValue(Res, 2));
CurDAG->RemoveDeadNode(N);
return true;
}
void AArch64DAGToDAGISel::SelectLoad(SDNode *N, unsigned NumVecs, unsigned Opc,
unsigned SubRegIdx) {
SDLoc dl(N);
EVT VT = N->getValueType(0);
SDValue Chain = N->getOperand(0);
SDValue Ops[] = {N->getOperand(2), // Mem operand;
Chain};
const EVT ResTys[] = {MVT::Untyped, MVT::Other};
SDNode *Ld = CurDAG->getMachineNode(Opc, dl, ResTys, Ops);
SDValue SuperReg = SDValue(Ld, 0);
for (unsigned i = 0; i < NumVecs; ++i)
ReplaceUses(SDValue(N, i),
CurDAG->getTargetExtractSubreg(SubRegIdx + i, dl, VT, SuperReg));
ReplaceUses(SDValue(N, NumVecs), SDValue(Ld, 1));
// Transfer memoperands. In the case of AArch64::LD64B, there won't be one,
// because it's too simple to have needed special treatment during lowering.
if (auto *MemIntr = dyn_cast<MemIntrinsicSDNode>(N)) {
MachineMemOperand *MemOp = MemIntr->getMemOperand();
CurDAG->setNodeMemRefs(cast<MachineSDNode>(Ld), {MemOp});
}
CurDAG->RemoveDeadNode(N);
}
void AArch64DAGToDAGISel::SelectPostLoad(SDNode *N, unsigned NumVecs,
unsigned Opc, unsigned SubRegIdx) {
SDLoc dl(N);
EVT VT = N->getValueType(0);
SDValue Chain = N->getOperand(0);
SDValue Ops[] = {N->getOperand(1), // Mem operand
N->getOperand(2), // Incremental
Chain};
const EVT ResTys[] = {MVT::i64, // Type of the write back register
MVT::Untyped, MVT::Other};
SDNode *Ld = CurDAG->getMachineNode(Opc, dl, ResTys, Ops);
// Update uses of write back register
ReplaceUses(SDValue(N, NumVecs), SDValue(Ld, 0));
// Update uses of vector list
SDValue SuperReg = SDValue(Ld, 1);
if (NumVecs == 1)
ReplaceUses(SDValue(N, 0), SuperReg);
else
for (unsigned i = 0; i < NumVecs; ++i)
ReplaceUses(SDValue(N, i),
CurDAG->getTargetExtractSubreg(SubRegIdx + i, dl, VT, SuperReg));
// Update the chain
ReplaceUses(SDValue(N, NumVecs + 1), SDValue(Ld, 2));
CurDAG->RemoveDeadNode(N);
}
/// Optimize \param OldBase and \param OldOffset selecting the best addressing
/// mode. Returns a tuple consisting of an Opcode, an SDValue representing the
/// new Base and an SDValue representing the new offset.
std::tuple<unsigned, SDValue, SDValue>
AArch64DAGToDAGISel::findAddrModeSVELoadStore(SDNode *N, unsigned Opc_rr,
unsigned Opc_ri,
const SDValue &OldBase,
const SDValue &OldOffset,
unsigned Scale) {
SDValue NewBase = OldBase;
SDValue NewOffset = OldOffset;
// Detect a possible Reg+Imm addressing mode.
const bool IsRegImm = SelectAddrModeIndexedSVE</*Min=*/-8, /*Max=*/7>(
N, OldBase, NewBase, NewOffset);
// Detect a possible reg+reg addressing mode, but only if we haven't already
// detected a Reg+Imm one.
const bool IsRegReg =
!IsRegImm && SelectSVERegRegAddrMode(OldBase, Scale, NewBase, NewOffset);
// Select the instruction.
return std::make_tuple(IsRegReg ? Opc_rr : Opc_ri, NewBase, NewOffset);
}
void AArch64DAGToDAGISel::SelectPredicatedLoad(SDNode *N, unsigned NumVecs,
unsigned Scale, unsigned Opc_ri,
unsigned Opc_rr) {
assert(Scale < 4 && "Invalid scaling value.");
SDLoc DL(N);
EVT VT = N->getValueType(0);
SDValue Chain = N->getOperand(0);
// Optimize addressing mode.
SDValue Base, Offset;
unsigned Opc;
std::tie(Opc, Base, Offset) = findAddrModeSVELoadStore(
N, Opc_rr, Opc_ri, N->getOperand(2),
CurDAG->getTargetConstant(0, DL, MVT::i64), Scale);
SDValue Ops[] = {N->getOperand(1), // Predicate
Base, // Memory operand
Offset, Chain};
const EVT ResTys[] = {MVT::Untyped, MVT::Other};
SDNode *Load = CurDAG->getMachineNode(Opc, DL, ResTys, Ops);
SDValue SuperReg = SDValue(Load, 0);
for (unsigned i = 0; i < NumVecs; ++i)
ReplaceUses(SDValue(N, i), CurDAG->getTargetExtractSubreg(
AArch64::zsub0 + i, DL, VT, SuperReg));
// Copy chain
unsigned ChainIdx = NumVecs;
ReplaceUses(SDValue(N, ChainIdx), SDValue(Load, 1));
CurDAG->RemoveDeadNode(N);
}
void AArch64DAGToDAGISel::SelectStore(SDNode *N, unsigned NumVecs,
unsigned Opc) {
SDLoc dl(N);
EVT VT = N->getOperand(2)->getValueType(0);
// Form a REG_SEQUENCE to force register allocation.
bool Is128Bit = VT.getSizeInBits() == 128;
SmallVector<SDValue, 4> Regs(N->op_begin() + 2, N->op_begin() + 2 + NumVecs);
SDValue RegSeq = Is128Bit ? createQTuple(Regs) : createDTuple(Regs);
SDValue Ops[] = {RegSeq, N->getOperand(NumVecs + 2), N->getOperand(0)};
SDNode *St = CurDAG->getMachineNode(Opc, dl, N->getValueType(0), Ops);
// Transfer memoperands.
MachineMemOperand *MemOp = cast<MemIntrinsicSDNode>(N)->getMemOperand();
CurDAG->setNodeMemRefs(cast<MachineSDNode>(St), {MemOp});
ReplaceNode(N, St);
}
void AArch64DAGToDAGISel::SelectPredicatedStore(SDNode *N, unsigned NumVecs,
unsigned Scale, unsigned Opc_rr,
unsigned Opc_ri) {
SDLoc dl(N);
// Form a REG_SEQUENCE to force register allocation.
SmallVector<SDValue, 4> Regs(N->op_begin() + 2, N->op_begin() + 2 + NumVecs);
SDValue RegSeq = createZTuple(Regs);
// Optimize addressing mode.
unsigned Opc;
SDValue Offset, Base;
std::tie(Opc, Base, Offset) = findAddrModeSVELoadStore(
N, Opc_rr, Opc_ri, N->getOperand(NumVecs + 3),
CurDAG->getTargetConstant(0, dl, MVT::i64), Scale);
SDValue Ops[] = {RegSeq, N->getOperand(NumVecs + 2), // predicate
Base, // address
Offset, // offset
N->getOperand(0)}; // chain
SDNode *St = CurDAG->getMachineNode(Opc, dl, N->getValueType(0), Ops);
ReplaceNode(N, St);
}
bool AArch64DAGToDAGISel::SelectAddrModeFrameIndexSVE(SDValue N, SDValue &Base,
SDValue &OffImm) {
SDLoc dl(N);
const DataLayout &DL = CurDAG->getDataLayout();
const TargetLowering *TLI = getTargetLowering();
// Try to match it for the frame address
if (auto FINode = dyn_cast<FrameIndexSDNode>(N)) {
int FI = FINode->getIndex();
Base = CurDAG->getTargetFrameIndex(FI, TLI->getPointerTy(DL));
OffImm = CurDAG->getTargetConstant(0, dl, MVT::i64);
return true;
}
return false;
}
void AArch64DAGToDAGISel::SelectPostStore(SDNode *N, unsigned NumVecs,
unsigned Opc) {
SDLoc dl(N);
EVT VT = N->getOperand(2)->getValueType(0);
const EVT ResTys[] = {MVT::i64, // Type of the write back register
MVT::Other}; // Type for the Chain
// Form a REG_SEQUENCE to force register allocation.
bool Is128Bit = VT.getSizeInBits() == 128;
SmallVector<SDValue, 4> Regs(N->op_begin() + 1, N->op_begin() + 1 + NumVecs);
SDValue RegSeq = Is128Bit ? createQTuple(Regs) : createDTuple(Regs);
SDValue Ops[] = {RegSeq,
N->getOperand(NumVecs + 1), // base register
N->getOperand(NumVecs + 2), // Incremental
N->getOperand(0)}; // Chain
SDNode *St = CurDAG->getMachineNode(Opc, dl, ResTys, Ops);
ReplaceNode(N, St);
}
namespace {
/// WidenVector - Given a value in the V64 register class, produce the
/// equivalent value in the V128 register class.
class WidenVector {
SelectionDAG &DAG;
public:
WidenVector(SelectionDAG &DAG) : DAG(DAG) {}
SDValue operator()(SDValue V64Reg) {
EVT VT = V64Reg.getValueType();
unsigned NarrowSize = VT.getVectorNumElements();
MVT EltTy = VT.getVectorElementType().getSimpleVT();
MVT WideTy = MVT::getVectorVT(EltTy, 2 * NarrowSize);
SDLoc DL(V64Reg);
SDValue Undef =
SDValue(DAG.getMachineNode(TargetOpcode::IMPLICIT_DEF, DL, WideTy), 0);
return DAG.getTargetInsertSubreg(AArch64::dsub, DL, WideTy, Undef, V64Reg);
}
};
} // namespace
/// NarrowVector - Given a value in the V128 register class, produce the
/// equivalent value in the V64 register class.
static SDValue NarrowVector(SDValue V128Reg, SelectionDAG &DAG) {
EVT VT = V128Reg.getValueType();
unsigned WideSize = VT.getVectorNumElements();
MVT EltTy = VT.getVectorElementType().getSimpleVT();
MVT NarrowTy = MVT::getVectorVT(EltTy, WideSize / 2);
return DAG.getTargetExtractSubreg(AArch64::dsub, SDLoc(V128Reg), NarrowTy,
V128Reg);
}
void AArch64DAGToDAGISel::SelectLoadLane(SDNode *N, unsigned NumVecs,
unsigned Opc) {
SDLoc dl(N);
EVT VT = N->getValueType(0);
bool Narrow = VT.getSizeInBits() == 64;
// Form a REG_SEQUENCE to force register allocation.
SmallVector<SDValue, 4> Regs(N->op_begin() + 2, N->op_begin() + 2 + NumVecs);
if (Narrow)
transform(Regs, Regs.begin(),
WidenVector(*CurDAG));
SDValue RegSeq = createQTuple(Regs);
const EVT ResTys[] = {MVT::Untyped, MVT::Other};
unsigned LaneNo =
cast<ConstantSDNode>(N->getOperand(NumVecs + 2))->getZExtValue();
SDValue Ops[] = {RegSeq, CurDAG->getTargetConstant(LaneNo, dl, MVT::i64),
N->getOperand(NumVecs + 3), N->getOperand(0)};
SDNode *Ld = CurDAG->getMachineNode(Opc, dl, ResTys, Ops);
SDValue SuperReg = SDValue(Ld, 0);
EVT WideVT = RegSeq.getOperand(1)->getValueType(0);
static const unsigned QSubs[] = { AArch64::qsub0, AArch64::qsub1,
AArch64::qsub2, AArch64::qsub3 };
for (unsigned i = 0; i < NumVecs; ++i) {
SDValue NV = CurDAG->getTargetExtractSubreg(QSubs[i], dl, WideVT, SuperReg);
if (Narrow)
NV = NarrowVector(NV, *CurDAG);
ReplaceUses(SDValue(N, i), NV);
}
ReplaceUses(SDValue(N, NumVecs), SDValue(Ld, 1));
CurDAG->RemoveDeadNode(N);
}
void AArch64DAGToDAGISel::SelectPostLoadLane(SDNode *N, unsigned NumVecs,
unsigned Opc) {
SDLoc dl(N);
EVT VT = N->getValueType(0);
bool Narrow = VT.getSizeInBits() == 64;
// Form a REG_SEQUENCE to force register allocation.
SmallVector<SDValue, 4> Regs(N->op_begin() + 1, N->op_begin() + 1 + NumVecs);
if (Narrow)
transform(Regs, Regs.begin(),
WidenVector(*CurDAG));
SDValue RegSeq = createQTuple(Regs);
const EVT ResTys[] = {MVT::i64, // Type of the write back register
RegSeq->getValueType(0), MVT::Other};
unsigned LaneNo =
cast<ConstantSDNode>(N->getOperand(NumVecs + 1))->getZExtValue();
SDValue Ops[] = {RegSeq,
CurDAG->getTargetConstant(LaneNo, dl,
MVT::i64), // Lane Number
N->getOperand(NumVecs + 2), // Base register
N->getOperand(NumVecs + 3), // Incremental
N->getOperand(0)};
SDNode *Ld = CurDAG->getMachineNode(Opc, dl, ResTys, Ops);
// Update uses of the write back register
ReplaceUses(SDValue(N, NumVecs), SDValue(Ld, 0));
// Update uses of the vector list
SDValue SuperReg = SDValue(Ld, 1);
if (NumVecs == 1) {
ReplaceUses(SDValue(N, 0),
Narrow ? NarrowVector(SuperReg, *CurDAG) : SuperReg);
} else {
EVT WideVT = RegSeq.getOperand(1)->getValueType(0);
static const unsigned QSubs[] = { AArch64::qsub0, AArch64::qsub1,
AArch64::qsub2, AArch64::qsub3 };
for (unsigned i = 0; i < NumVecs; ++i) {
SDValue NV = CurDAG->getTargetExtractSubreg(QSubs[i], dl, WideVT,
SuperReg);
if (Narrow)
NV = NarrowVector(NV, *CurDAG);
ReplaceUses(SDValue(N, i), NV);
}
}
// Update the Chain
ReplaceUses(SDValue(N, NumVecs + 1), SDValue(Ld, 2));
CurDAG->RemoveDeadNode(N);
}
void AArch64DAGToDAGISel::SelectStoreLane(SDNode *N, unsigned NumVecs,
unsigned Opc) {
SDLoc dl(N);
EVT VT = N->getOperand(2)->getValueType(0);
bool Narrow = VT.getSizeInBits() == 64;
// Form a REG_SEQUENCE to force register allocation.
SmallVector<SDValue, 4> Regs(N->op_begin() + 2, N->op_begin() + 2 + NumVecs);
if (Narrow)
transform(Regs, Regs.begin(),
WidenVector(*CurDAG));
SDValue RegSeq = createQTuple(Regs);
unsigned LaneNo =
cast<ConstantSDNode>(N->getOperand(NumVecs + 2))->getZExtValue();
SDValue Ops[] = {RegSeq, CurDAG->getTargetConstant(LaneNo, dl, MVT::i64),
N->getOperand(NumVecs + 3), N->getOperand(0)};
SDNode *St = CurDAG->getMachineNode(Opc, dl, MVT::Other, Ops);
// Transfer memoperands.
MachineMemOperand *MemOp = cast<MemIntrinsicSDNode>(N)->getMemOperand();
CurDAG->setNodeMemRefs(cast<MachineSDNode>(St), {MemOp});
ReplaceNode(N, St);
}
void AArch64DAGToDAGISel::SelectPostStoreLane(SDNode *N, unsigned NumVecs,
unsigned Opc) {
SDLoc dl(N);
EVT VT = N->getOperand(2)->getValueType(0);
bool Narrow = VT.getSizeInBits() == 64;
// Form a REG_SEQUENCE to force register allocation.
SmallVector<SDValue, 4> Regs(N->op_begin() + 1, N->op_begin() + 1 + NumVecs);
if (Narrow)
transform(Regs, Regs.begin(),
WidenVector(*CurDAG));
SDValue RegSeq = createQTuple(Regs);
const EVT ResTys[] = {MVT::i64, // Type of the write back register
MVT::Other};
unsigned LaneNo =
cast<ConstantSDNode>(N->getOperand(NumVecs + 1))->getZExtValue();
SDValue Ops[] = {RegSeq, CurDAG->getTargetConstant(LaneNo, dl, MVT::i64),
N->getOperand(NumVecs + 2), // Base Register
N->getOperand(NumVecs + 3), // Incremental
N->getOperand(0)};
SDNode *St = CurDAG->getMachineNode(Opc, dl, ResTys, Ops);
// Transfer memoperands.
MachineMemOperand *MemOp = cast<MemIntrinsicSDNode>(N)->getMemOperand();
CurDAG->setNodeMemRefs(cast<MachineSDNode>(St), {MemOp});
ReplaceNode(N, St);
}
static bool isBitfieldExtractOpFromAnd(SelectionDAG *CurDAG, SDNode *N,
unsigned &Opc, SDValue &Opd0,
unsigned &LSB, unsigned &MSB,
unsigned NumberOfIgnoredLowBits,
bool BiggerPattern) {
assert(N->getOpcode() == ISD::AND &&
"N must be a AND operation to call this function");
EVT VT = N->getValueType(0);
// Here we can test the type of VT and return false when the type does not
// match, but since it is done prior to that call in the current context
// we turned that into an assert to avoid redundant code.
assert((VT == MVT::i32 || VT == MVT::i64) &&
"Type checking must have been done before calling this function");
// FIXME: simplify-demanded-bits in DAGCombine will probably have
// changed the AND node to a 32-bit mask operation. We'll have to
// undo that as part of the transform here if we want to catch all
// the opportunities.
// Currently the NumberOfIgnoredLowBits argument helps to recover
// form these situations when matching bigger pattern (bitfield insert).
// For unsigned extracts, check for a shift right and mask
uint64_t AndImm = 0;
if (!isOpcWithIntImmediate(N, ISD::AND, AndImm))
return false;
const SDNode *Op0 = N->getOperand(0).getNode();
// Because of simplify-demanded-bits in DAGCombine, the mask may have been
// simplified. Try to undo that
AndImm |= maskTrailingOnes<uint64_t>(NumberOfIgnoredLowBits);
// The immediate is a mask of the low bits iff imm & (imm+1) == 0
if (AndImm & (AndImm + 1))
return false;
bool ClampMSB = false;
uint64_t SrlImm = 0;
// Handle the SRL + ANY_EXTEND case.
if (VT == MVT::i64 && Op0->getOpcode() == ISD::ANY_EXTEND &&
isOpcWithIntImmediate(Op0->getOperand(0).getNode(), ISD::SRL, SrlImm)) {
// Extend the incoming operand of the SRL to 64-bit.
Opd0 = Widen(CurDAG, Op0->getOperand(0).getOperand(0));
// Make sure to clamp the MSB so that we preserve the semantics of the
// original operations.
ClampMSB = true;
} else if (VT == MVT::i32 && Op0->getOpcode() == ISD::TRUNCATE &&
isOpcWithIntImmediate(Op0->getOperand(0).getNode(), ISD::SRL,
SrlImm)) {
// If the shift result was truncated, we can still combine them.
Opd0 = Op0->getOperand(0).getOperand(0);
// Use the type of SRL node.
VT = Opd0->getValueType(0);
} else if (isOpcWithIntImmediate(Op0, ISD::SRL, SrlImm)) {
Opd0 = Op0->getOperand(0);
} else if (BiggerPattern) {
// Let's pretend a 0 shift right has been performed.
// The resulting code will be at least as good as the original one
// plus it may expose more opportunities for bitfield insert pattern.
// FIXME: Currently we limit this to the bigger pattern, because
// some optimizations expect AND and not UBFM.
Opd0 = N->getOperand(0);
} else
return false;
// Bail out on large immediates. This happens when no proper
// combining/constant folding was performed.
if (!BiggerPattern && (SrlImm <= 0 || SrlImm >= VT.getSizeInBits())) {
LLVM_DEBUG(
(dbgs() << N
<< ": Found large shift immediate, this should not happen\n"));
return false;
}
LSB = SrlImm;
MSB = SrlImm + (VT == MVT::i32 ? countTrailingOnes<uint32_t>(AndImm)
: countTrailingOnes<uint64_t>(AndImm)) -
1;
if (ClampMSB)
// Since we're moving the extend before the right shift operation, we need
// to clamp the MSB to make sure we don't shift in undefined bits instead of
// the zeros which would get shifted in with the original right shift
// operation.
MSB = MSB > 31 ? 31 : MSB;
Opc = VT == MVT::i32 ? AArch64::UBFMWri : AArch64::UBFMXri;
return true;
}
static bool isBitfieldExtractOpFromSExtInReg(SDNode *N, unsigned &Opc,
SDValue &Opd0, unsigned &Immr,
unsigned &Imms) {
assert(N->getOpcode() == ISD::SIGN_EXTEND_INREG);
EVT VT = N->getValueType(0);
unsigned BitWidth = VT.getSizeInBits();
assert((VT == MVT::i32 || VT == MVT::i64) &&
"Type checking must have been done before calling this function");
SDValue Op = N->getOperand(0);
if (Op->getOpcode() == ISD::TRUNCATE) {
Op = Op->getOperand(0);
VT = Op->getValueType(0);
BitWidth = VT.getSizeInBits();
}
uint64_t ShiftImm;
if (!isOpcWithIntImmediate(Op.getNode(), ISD::SRL, ShiftImm) &&
!isOpcWithIntImmediate(Op.getNode(), ISD::SRA, ShiftImm))
return false;
unsigned Width = cast<VTSDNode>(N->getOperand(1))->getVT().getSizeInBits();
if (ShiftImm + Width > BitWidth)
return false;
Opc = (VT == MVT::i32) ? AArch64::SBFMWri : AArch64::SBFMXri;
Opd0 = Op.getOperand(0);
Immr = ShiftImm;
Imms = ShiftImm + Width - 1;
return true;
}
static bool isSeveralBitsExtractOpFromShr(SDNode *N, unsigned &Opc,
SDValue &Opd0, unsigned &LSB,
unsigned &MSB) {
// We are looking for the following pattern which basically extracts several
// continuous bits from the source value and places it from the LSB of the
// destination value, all other bits of the destination value or set to zero:
//
// Value2 = AND Value, MaskImm
// SRL Value2, ShiftImm
//
// with MaskImm >> ShiftImm to search for the bit width.
//
// This gets selected into a single UBFM:
//
// UBFM Value, ShiftImm, BitWide + SrlImm -1
//
if (N->getOpcode() != ISD::SRL)
return false;
uint64_t AndMask = 0;
if (!isOpcWithIntImmediate(N->getOperand(0).getNode(), ISD::AND, AndMask))
return false;
Opd0 = N->getOperand(0).getOperand(0);
uint64_t SrlImm = 0;
if (!isIntImmediate(N->getOperand(1), SrlImm))
return false;
// Check whether we really have several bits extract here.
unsigned BitWide = 64 - countLeadingOnes(~(AndMask >> SrlImm));
if (BitWide && isMask_64(AndMask >> SrlImm)) {
if (N->getValueType(0) == MVT::i32)
Opc = AArch64::UBFMWri;
else
Opc = AArch64::UBFMXri;
LSB = SrlImm;
MSB = BitWide + SrlImm - 1;
return true;
}
return false;
}
static bool isBitfieldExtractOpFromShr(SDNode *N, unsigned &Opc, SDValue &Opd0,
unsigned &Immr, unsigned &Imms,
bool BiggerPattern) {
assert((N->getOpcode() == ISD::SRA || N->getOpcode() == ISD::SRL) &&
"N must be a SHR/SRA operation to call this function");
EVT VT = N->getValueType(0);
// Here we can test the type of VT and return false when the type does not
// match, but since it is done prior to that call in the current context
// we turned that into an assert to avoid redundant code.
assert((VT == MVT::i32 || VT == MVT::i64) &&
"Type checking must have been done before calling this function");
// Check for AND + SRL doing several bits extract.
if (isSeveralBitsExtractOpFromShr(N, Opc, Opd0, Immr, Imms))
return true;
// We're looking for a shift of a shift.
uint64_t ShlImm = 0;
uint64_t TruncBits = 0;
if (isOpcWithIntImmediate(N->getOperand(0).getNode(), ISD::SHL, ShlImm)) {
Opd0 = N->getOperand(0).getOperand(0);
} else if (VT == MVT::i32 && N->getOpcode() == ISD::SRL &&
N->getOperand(0).getNode()->getOpcode() == ISD::TRUNCATE) {
// We are looking for a shift of truncate. Truncate from i64 to i32 could
// be considered as setting high 32 bits as zero. Our strategy here is to
// always generate 64bit UBFM. This consistency will help the CSE pass
// later find more redundancy.
Opd0 = N->getOperand(0).getOperand(0);
TruncBits = Opd0->getValueType(0).getSizeInBits() - VT.getSizeInBits();
VT = Opd0.getValueType();
assert(VT == MVT::i64 && "the promoted type should be i64");
} else if (BiggerPattern) {
// Let's pretend a 0 shift left has been performed.
// FIXME: Currently we limit this to the bigger pattern case,
// because some optimizations expect AND and not UBFM
Opd0 = N->getOperand(0);
} else
return false;
// Missing combines/constant folding may have left us with strange
// constants.
if (ShlImm >= VT.getSizeInBits()) {
LLVM_DEBUG(
(dbgs() << N
<< ": Found large shift immediate, this should not happen\n"));
return false;
}
uint64_t SrlImm = 0;
if (!isIntImmediate(N->getOperand(1), SrlImm))
return false;
assert(SrlImm > 0 && SrlImm < VT.getSizeInBits() &&
"bad amount in shift node!");
int immr = SrlImm - ShlImm;
Immr = immr < 0 ? immr + VT.getSizeInBits() : immr;
Imms = VT.getSizeInBits() - ShlImm - TruncBits - 1;
// SRA requires a signed extraction
if (VT == MVT::i32)
Opc = N->getOpcode() == ISD::SRA ? AArch64::SBFMWri : AArch64::UBFMWri;
else
Opc = N->getOpcode() == ISD::SRA ? AArch64::SBFMXri : AArch64::UBFMXri;
return true;
}
bool AArch64DAGToDAGISel::tryBitfieldExtractOpFromSExt(SDNode *N) {
assert(N->getOpcode() == ISD::SIGN_EXTEND);
EVT VT = N->getValueType(0);
EVT NarrowVT = N->getOperand(0)->getValueType(0);
if (VT != MVT::i64 || NarrowVT != MVT::i32)
return false;
uint64_t ShiftImm;
SDValue Op = N->getOperand(0);
if (!isOpcWithIntImmediate(Op.getNode(), ISD::SRA, ShiftImm))
return false;
SDLoc dl(N);
// Extend the incoming operand of the shift to 64-bits.
SDValue Opd0 = Widen(CurDAG, Op.getOperand(0));
unsigned Immr = ShiftImm;
unsigned Imms = NarrowVT.getSizeInBits() - 1;
SDValue Ops[] = {Opd0, CurDAG->getTargetConstant(Immr, dl, VT),
CurDAG->getTargetConstant(Imms, dl, VT)};
CurDAG->SelectNodeTo(N, AArch64::SBFMXri, VT, Ops);
return true;
}
/// Try to form fcvtl2 instructions from a floating-point extend of a high-half
/// extract of a subvector.
bool AArch64DAGToDAGISel::tryHighFPExt(SDNode *N) {
assert(N->getOpcode() == ISD::FP_EXTEND);
// There are 2 forms of fcvtl2 - extend to double or extend to float.
SDValue Extract = N->getOperand(0);
EVT VT = N->getValueType(0);
EVT NarrowVT = Extract.getValueType();
if ((VT != MVT::v2f64 || NarrowVT != MVT::v2f32) &&
(VT != MVT::v4f32 || NarrowVT != MVT::v4f16))
return false;
// Optionally look past a bitcast.
Extract = peekThroughBitcasts(Extract);
if (Extract.getOpcode() != ISD::EXTRACT_SUBVECTOR)
return false;
// Match extract from start of high half index.
// Example: v8i16 -> v4i16 means the extract must begin at index 4.
unsigned ExtractIndex = Extract.getConstantOperandVal(1);
if (ExtractIndex != Extract.getValueType().getVectorNumElements())
return false;
auto Opcode = VT == MVT::v2f64 ? AArch64::FCVTLv4i32 : AArch64::FCVTLv8i16;
CurDAG->SelectNodeTo(N, Opcode, VT, Extract.getOperand(0));
return true;
}
static bool isBitfieldExtractOp(SelectionDAG *CurDAG, SDNode *N, unsigned &Opc,
SDValue &Opd0, unsigned &Immr, unsigned &Imms,
unsigned NumberOfIgnoredLowBits = 0,
bool BiggerPattern = false) {
if (N->getValueType(0) != MVT::i32 && N->getValueType(0) != MVT::i64)
return false;
switch (N->getOpcode()) {
default:
if (!N->isMachineOpcode())
return false;
break;
case ISD::AND:
return isBitfieldExtractOpFromAnd(CurDAG, N, Opc, Opd0, Immr, Imms,
NumberOfIgnoredLowBits, BiggerPattern);
case ISD::SRL:
case ISD::SRA:
return isBitfieldExtractOpFromShr(N, Opc, Opd0, Immr, Imms, BiggerPattern);
case ISD::SIGN_EXTEND_INREG:
return isBitfieldExtractOpFromSExtInReg(N, Opc, Opd0, Immr, Imms);
}
unsigned NOpc = N->getMachineOpcode();
switch (NOpc) {
default:
return false;
case AArch64::SBFMWri:
case AArch64::UBFMWri:
case AArch64::SBFMXri:
case AArch64::UBFMXri:
Opc = NOpc;
Opd0 = N->getOperand(0);
Immr = cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
Imms = cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
return true;
}
// Unreachable
return false;
}
bool AArch64DAGToDAGISel::tryBitfieldExtractOp(SDNode *N) {
unsigned Opc, Immr, Imms;
SDValue Opd0;
if (!isBitfieldExtractOp(CurDAG, N, Opc, Opd0, Immr, Imms))
return false;
EVT VT = N->getValueType(0);
SDLoc dl(N);
// If the bit extract operation is 64bit but the original type is 32bit, we
// need to add one EXTRACT_SUBREG.
if ((Opc == AArch64::SBFMXri || Opc == AArch64::UBFMXri) && VT == MVT::i32) {
SDValue Ops64[] = {Opd0, CurDAG->getTargetConstant(Immr, dl, MVT::i64),
CurDAG->getTargetConstant(Imms, dl, MVT::i64)};
SDNode *BFM = CurDAG->getMachineNode(Opc, dl, MVT::i64, Ops64);
SDValue SubReg = CurDAG->getTargetConstant(AArch64::sub_32, dl, MVT::i32);
ReplaceNode(N, CurDAG->getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl,
MVT::i32, SDValue(BFM, 0), SubReg));
return true;
}
SDValue Ops[] = {Opd0, CurDAG->getTargetConstant(Immr, dl, VT),
CurDAG->getTargetConstant(Imms, dl, VT)};
CurDAG->SelectNodeTo(N, Opc, VT, Ops);
return true;
}
/// Does DstMask form a complementary pair with the mask provided by
/// BitsToBeInserted, suitable for use in a BFI instruction. Roughly speaking,
/// this asks whether DstMask zeroes precisely those bits that will be set by
/// the other half.
static bool isBitfieldDstMask(uint64_t DstMask, const APInt &BitsToBeInserted,
unsigned NumberOfIgnoredHighBits, EVT VT) {
assert((VT == MVT::i32 || VT == MVT::i64) &&
"i32 or i64 mask type expected!");
unsigned BitWidth = VT.getSizeInBits() - NumberOfIgnoredHighBits;
APInt SignificantDstMask = APInt(BitWidth, DstMask);
APInt SignificantBitsToBeInserted = BitsToBeInserted.zextOrTrunc(BitWidth);
return (SignificantDstMask & SignificantBitsToBeInserted) == 0 &&
(SignificantDstMask | SignificantBitsToBeInserted).isAllOnesValue();
}
// Look for bits that will be useful for later uses.
// A bit is consider useless as soon as it is dropped and never used
// before it as been dropped.
// E.g., looking for useful bit of x
// 1. y = x & 0x7
// 2. z = y >> 2
// After #1, x useful bits are 0x7, then the useful bits of x, live through
// y.
// After #2, the useful bits of x are 0x4.
// However, if x is used on an unpredicatable instruction, then all its bits
// are useful.
// E.g.
// 1. y = x & 0x7
// 2. z = y >> 2
// 3. str x, [@x]
static void getUsefulBits(SDValue Op, APInt &UsefulBits, unsigned Depth = 0);
static void getUsefulBitsFromAndWithImmediate(SDValue Op, APInt &UsefulBits,
unsigned Depth) {
uint64_t Imm =
cast<const ConstantSDNode>(Op.getOperand(1).getNode())->getZExtValue();
Imm = AArch64_AM::decodeLogicalImmediate(Imm, UsefulBits.getBitWidth());
UsefulBits &= APInt(UsefulBits.getBitWidth(), Imm);
getUsefulBits(Op, UsefulBits, Depth + 1);
}
static void getUsefulBitsFromBitfieldMoveOpd(SDValue Op, APInt &UsefulBits,
uint64_t Imm, uint64_t MSB,
unsigned Depth) {
// inherit the bitwidth value
APInt OpUsefulBits(UsefulBits);
OpUsefulBits = 1;
if (MSB >= Imm) {
OpUsefulBits <<= MSB - Imm + 1;
--OpUsefulBits;
// The interesting part will be in the lower part of the result
getUsefulBits(Op, OpUsefulBits, Depth + 1);
// The interesting part was starting at Imm in the argument
OpUsefulBits <<= Imm;
} else {
OpUsefulBits <<= MSB + 1;
--OpUsefulBits;
// The interesting part will be shifted in the result
OpUsefulBits <<= OpUsefulBits.getBitWidth() - Imm;
getUsefulBits(Op, OpUsefulBits, Depth + 1);
// The interesting part was at zero in the argument
OpUsefulBits.lshrInPlace(OpUsefulBits.getBitWidth() - Imm);
}
UsefulBits &= OpUsefulBits;
}
static void getUsefulBitsFromUBFM(SDValue Op, APInt &UsefulBits,
unsigned Depth) {
uint64_t Imm =
cast<const ConstantSDNode>(Op.getOperand(1).getNode())->getZExtValue();
uint64_t MSB =
cast<const ConstantSDNode>(Op.getOperand(2).getNode())->getZExtValue();
getUsefulBitsFromBitfieldMoveOpd(Op, UsefulBits, Imm, MSB, Depth);
}
static void getUsefulBitsFromOrWithShiftedReg(SDValue Op, APInt &UsefulBits,
unsigned Depth) {
uint64_t ShiftTypeAndValue =
cast<const ConstantSDNode>(Op.getOperand(2).getNode())->getZExtValue();
APInt Mask(UsefulBits);
Mask.clearAllBits();
Mask.flipAllBits();
if (AArch64_AM::getShiftType(ShiftTypeAndValue) == AArch64_AM::LSL) {
// Shift Left
uint64_t ShiftAmt = AArch64_AM::getShiftValue(ShiftTypeAndValue);
Mask <<= ShiftAmt;
getUsefulBits(Op, Mask, Depth + 1);
Mask.lshrInPlace(ShiftAmt);
} else if (AArch64_AM::getShiftType(ShiftTypeAndValue) == AArch64_AM::LSR) {
// Shift Right
// We do not handle AArch64_AM::ASR, because the sign will change the
// number of useful bits
uint64_t ShiftAmt = AArch64_AM::getShiftValue(ShiftTypeAndValue);
Mask.lshrInPlace(ShiftAmt);
getUsefulBits(Op, Mask, Depth + 1);
Mask <<= ShiftAmt;
} else
return;
UsefulBits &= Mask;
}
static void getUsefulBitsFromBFM(SDValue Op, SDValue Orig, APInt &UsefulBits,
unsigned Depth) {
uint64_t Imm =
cast<const ConstantSDNode>(Op.getOperand(2).getNode())->getZExtValue();
uint64_t MSB =
cast<const ConstantSDNode>(Op.getOperand(3).getNode())->getZExtValue();
APInt OpUsefulBits(UsefulBits);
OpUsefulBits = 1;
APInt ResultUsefulBits(UsefulBits.getBitWidth(), 0);
ResultUsefulBits.flipAllBits();
APInt Mask(UsefulBits.getBitWidth(), 0);
getUsefulBits(Op, ResultUsefulBits, Depth + 1);
if (MSB >= Imm) {
// The instruction is a BFXIL.
uint64_t Width = MSB - Imm + 1;
uint64_t LSB = Imm;
OpUsefulBits <<= Width;
--OpUsefulBits;
if (Op.getOperand(1) == Orig) {
// Copy the low bits from the result to bits starting from LSB.
Mask = ResultUsefulBits & OpUsefulBits;
Mask <<= LSB;
}
if (Op.getOperand(0) == Orig)
// Bits starting from LSB in the input contribute to the result.
Mask |= (ResultUsefulBits & ~OpUsefulBits);
} else {
// The instruction is a BFI.
uint64_t Width = MSB + 1;
uint64_t LSB = UsefulBits.getBitWidth() - Imm;
OpUsefulBits <<= Width;
--OpUsefulBits;
OpUsefulBits <<= LSB;
if (Op.getOperand(1) == Orig) {
// Copy the bits from the result to the zero bits.
Mask = ResultUsefulBits & OpUsefulBits;
Mask.lshrInPlace(LSB);
}
if (Op.getOperand(0) == Orig)
Mask |= (ResultUsefulBits & ~OpUsefulBits);
}
UsefulBits &= Mask;
}
static void getUsefulBitsForUse(SDNode *UserNode, APInt &UsefulBits,
SDValue Orig, unsigned Depth) {
// Users of this node should have already been instruction selected
// FIXME: Can we turn that into an assert?
if (!UserNode->isMachineOpcode())
return;
switch (UserNode->getMachineOpcode()) {
default:
return;
case AArch64::ANDSWri:
case AArch64::ANDSXri:
case AArch64::ANDWri:
case AArch64::ANDXri:
// We increment Depth only when we call the getUsefulBits
return getUsefulBitsFromAndWithImmediate(SDValue(UserNode, 0), UsefulBits,
Depth);
case AArch64::UBFMWri:
case AArch64::UBFMXri:
return getUsefulBitsFromUBFM(SDValue(UserNode, 0), UsefulBits, Depth);
case AArch64::ORRWrs:
case AArch64::ORRXrs:
if (UserNode->getOperand(1) != Orig)
return;
return getUsefulBitsFromOrWithShiftedReg(SDValue(UserNode, 0), UsefulBits,
Depth);
case AArch64::BFMWri:
case AArch64::BFMXri:
return getUsefulBitsFromBFM(SDValue(UserNode, 0), Orig, UsefulBits, Depth);
case AArch64::STRBBui:
case AArch64::STURBBi:
if (UserNode->getOperand(0) != Orig)
return;
UsefulBits &= APInt(UsefulBits.getBitWidth(), 0xff);
return;
case AArch64::STRHHui:
case AArch64::STURHHi:
if (UserNode->getOperand(0) != Orig)
return;
UsefulBits &= APInt(UsefulBits.getBitWidth(), 0xffff);
return;
}
}
static void getUsefulBits(SDValue Op, APInt &UsefulBits, unsigned Depth) {
if (Depth >= SelectionDAG::MaxRecursionDepth)
return;
// Initialize UsefulBits
if (!Depth) {
unsigned Bitwidth = Op.getScalarValueSizeInBits();
// At the beginning, assume every produced bits is useful
UsefulBits = APInt(Bitwidth, 0);
UsefulBits.flipAllBits();
}
APInt UsersUsefulBits(UsefulBits.getBitWidth(), 0);
for (SDNode *Node : Op.getNode()->uses()) {
// A use cannot produce useful bits
APInt UsefulBitsForUse = APInt(UsefulBits);
getUsefulBitsForUse(Node, UsefulBitsForUse, Op, Depth);
UsersUsefulBits |= UsefulBitsForUse;
}
// UsefulBits contains the produced bits that are meaningful for the
// current definition, thus a user cannot make a bit meaningful at
// this point
UsefulBits &= UsersUsefulBits;
}
/// Create a machine node performing a notional SHL of Op by ShlAmount. If
/// ShlAmount is negative, do a (logical) right-shift instead. If ShlAmount is
/// 0, return Op unchanged.
static SDValue getLeftShift(SelectionDAG *CurDAG, SDValue Op, int ShlAmount) {
if (ShlAmount == 0)
return Op;
EVT VT = Op.getValueType();
SDLoc dl(Op);
unsigned BitWidth = VT.getSizeInBits();
unsigned UBFMOpc = BitWidth == 32 ? AArch64::UBFMWri : AArch64::UBFMXri;
SDNode *ShiftNode;
if (ShlAmount > 0) {
// LSL wD, wN, #Amt == UBFM wD, wN, #32-Amt, #31-Amt
ShiftNode = CurDAG->getMachineNode(
UBFMOpc, dl, VT, Op,
CurDAG->getTargetConstant(BitWidth - ShlAmount, dl, VT),
CurDAG->getTargetConstant(BitWidth - 1 - ShlAmount, dl, VT));
} else {
// LSR wD, wN, #Amt == UBFM wD, wN, #Amt, #32-1
assert(ShlAmount < 0 && "expected right shift");
int ShrAmount = -ShlAmount;
ShiftNode = CurDAG->getMachineNode(
UBFMOpc, dl, VT, Op, CurDAG->getTargetConstant(ShrAmount, dl, VT),
CurDAG->getTargetConstant(BitWidth - 1, dl, VT));
}
return SDValue(ShiftNode, 0);
}
/// Does this tree qualify as an attempt to move a bitfield into position,
/// essentially "(and (shl VAL, N), Mask)".
static bool isBitfieldPositioningOp(SelectionDAG *CurDAG, SDValue Op,
bool BiggerPattern,
SDValue &Src, int &ShiftAmount,
int &MaskWidth) {
EVT VT = Op.getValueType();
unsigned BitWidth = VT.getSizeInBits();
(void)BitWidth;
assert(BitWidth == 32 || BitWidth == 64);
KnownBits Known = CurDAG->computeKnownBits(Op);
// Non-zero in the sense that they're not provably zero, which is the key
// point if we want to use this value
uint64_t NonZeroBits = (~Known.Zero).getZExtValue();
// Discard a constant AND mask if present. It's safe because the node will
// already have been factored into the computeKnownBits calculation above.
uint64_t AndImm;
if (isOpcWithIntImmediate(Op.getNode(), ISD::AND, AndImm)) {
assert((~APInt(BitWidth, AndImm) & ~Known.Zero) == 0);
Op = Op.getOperand(0);
}
// Don't match if the SHL has more than one use, since then we'll end up
// generating SHL+UBFIZ instead of just keeping SHL+AND.
if (!BiggerPattern && !Op.hasOneUse())
return false;
uint64_t ShlImm;
if (!isOpcWithIntImmediate(Op.getNode(), ISD::SHL, ShlImm))
return false;
Op = Op.getOperand(0);
if (!isShiftedMask_64(NonZeroBits))
return false;
ShiftAmount = countTrailingZeros(NonZeroBits);
MaskWidth = countTrailingOnes(NonZeroBits >> ShiftAmount);
// BFI encompasses sufficiently many nodes that it's worth inserting an extra
// LSL/LSR if the mask in NonZeroBits doesn't quite match up with the ISD::SHL
// amount. BiggerPattern is true when this pattern is being matched for BFI,
// BiggerPattern is false when this pattern is being matched for UBFIZ, in
// which case it is not profitable to insert an extra shift.
if (ShlImm - ShiftAmount != 0 && !BiggerPattern)
return false;
Src = getLeftShift(CurDAG, Op, ShlImm - ShiftAmount);
return true;
}
static bool isShiftedMask(uint64_t Mask, EVT VT) {
assert(VT == MVT::i32 || VT == MVT::i64);
if (VT == MVT::i32)
return isShiftedMask_32(Mask);
return isShiftedMask_64(Mask);
}
// Generate a BFI/BFXIL from 'or (and X, MaskImm), OrImm' iff the value being
// inserted only sets known zero bits.
static bool tryBitfieldInsertOpFromOrAndImm(SDNode *N, SelectionDAG *CurDAG) {
assert(N->getOpcode() == ISD::OR && "Expect a OR operation");
EVT VT = N->getValueType(0);
if (VT != MVT::i32 && VT != MVT::i64)
return false;
unsigned BitWidth = VT.getSizeInBits();
uint64_t OrImm;
if (!isOpcWithIntImmediate(N, ISD::OR, OrImm))
return false;
// Skip this transformation if the ORR immediate can be encoded in the ORR.
// Otherwise, we'll trade an AND+ORR for ORR+BFI/BFXIL, which is most likely
// performance neutral.
if (AArch64_AM::isLogicalImmediate(OrImm, BitWidth))
return false;
uint64_t MaskImm;
SDValue And = N->getOperand(0);
// Must be a single use AND with an immediate operand.
if (!And.hasOneUse() ||
!isOpcWithIntImmediate(And.getNode(), ISD::AND, MaskImm))
return false;
// Compute the Known Zero for the AND as this allows us to catch more general
// cases than just looking for AND with imm.
KnownBits Known = CurDAG->computeKnownBits(And);
// Non-zero in the sense that they're not provably zero, which is the key
// point if we want to use this value.
uint64_t NotKnownZero = (~Known.Zero).getZExtValue();
// The KnownZero mask must be a shifted mask (e.g., 1110..011, 11100..00).
if (!isShiftedMask(Known.Zero.getZExtValue(), VT))
return false;
// The bits being inserted must only set those bits that are known to be zero.
if ((OrImm & NotKnownZero) != 0) {
// FIXME: It's okay if the OrImm sets NotKnownZero bits to 1, but we don't
// currently handle this case.
return false;
}
// BFI/BFXIL dst, src, #lsb, #width.
int LSB = countTrailingOnes(NotKnownZero);
int Width = BitWidth - APInt(BitWidth, NotKnownZero).countPopulation();
// BFI/BFXIL is an alias of BFM, so translate to BFM operands.
unsigned ImmR = (BitWidth - LSB) % BitWidth;
unsigned ImmS = Width - 1;
// If we're creating a BFI instruction avoid cases where we need more
// instructions to materialize the BFI constant as compared to the original
// ORR. A BFXIL will use the same constant as the original ORR, so the code
// should be no worse in this case.
bool IsBFI = LSB != 0;
uint64_t BFIImm = OrImm >> LSB;
if (IsBFI && !AArch64_AM::isLogicalImmediate(BFIImm, BitWidth)) {
// We have a BFI instruction and we know the constant can't be materialized
// with a ORR-immediate with the zero register.
unsigned OrChunks = 0, BFIChunks = 0;
for (unsigned Shift = 0; Shift < BitWidth; Shift += 16) {
if (((OrImm >> Shift) & 0xFFFF) != 0)
++OrChunks;
if (((BFIImm >> Shift) & 0xFFFF) != 0)
++BFIChunks;
}
if (BFIChunks > OrChunks)
return false;
}
// Materialize the constant to be inserted.
SDLoc DL(N);
unsigned MOVIOpc = VT == MVT::i32 ? AArch64::MOVi32imm : AArch64::MOVi64imm;
SDNode *MOVI = CurDAG->getMachineNode(
MOVIOpc, DL, VT, CurDAG->getTargetConstant(BFIImm, DL, VT));
// Create the BFI/BFXIL instruction.
SDValue Ops[] = {And.getOperand(0), SDValue(MOVI, 0),
CurDAG->getTargetConstant(ImmR, DL, VT),
CurDAG->getTargetConstant(ImmS, DL, VT)};
unsigned Opc = (VT == MVT::i32) ? AArch64::BFMWri : AArch64::BFMXri;
CurDAG->SelectNodeTo(N, Opc, VT, Ops);
return true;
}
static bool tryBitfieldInsertOpFromOr(SDNode *N, const APInt &UsefulBits,
SelectionDAG *CurDAG) {
assert(N->getOpcode() == ISD::OR && "Expect a OR operation");
EVT VT = N->getValueType(0);
if (VT != MVT::i32 && VT != MVT::i64)
return false;
unsigned BitWidth = VT.getSizeInBits();
// Because of simplify-demanded-bits in DAGCombine, involved masks may not
// have the expected shape. Try to undo that.
unsigned NumberOfIgnoredLowBits = UsefulBits.countTrailingZeros();
unsigned NumberOfIgnoredHighBits = UsefulBits.countLeadingZeros();
// Given a OR operation, check if we have the following pattern
// ubfm c, b, imm, imm2 (or something that does the same jobs, see
// isBitfieldExtractOp)
// d = e & mask2 ; where mask is a binary sequence of 1..10..0 and
// countTrailingZeros(mask2) == imm2 - imm + 1
// f = d | c
// if yes, replace the OR instruction with:
// f = BFM Opd0, Opd1, LSB, MSB ; where LSB = imm, and MSB = imm2
// OR is commutative, check all combinations of operand order and values of
// BiggerPattern, i.e.
// Opd0, Opd1, BiggerPattern=false
// Opd1, Opd0, BiggerPattern=false
// Opd0, Opd1, BiggerPattern=true
// Opd1, Opd0, BiggerPattern=true
// Several of these combinations may match, so check with BiggerPattern=false
// first since that will produce better results by matching more instructions
// and/or inserting fewer extra instructions.
for (int I = 0; I < 4; ++I) {
SDValue Dst, Src;
unsigned ImmR, ImmS;
bool BiggerPattern = I / 2;
SDValue OrOpd0Val = N->getOperand(I % 2);
SDNode *OrOpd0 = OrOpd0Val.getNode();
SDValue OrOpd1Val = N->getOperand((I + 1) % 2);
SDNode *OrOpd1 = OrOpd1Val.getNode();
unsigned BFXOpc;
int DstLSB, Width;
if (isBitfieldExtractOp(CurDAG, OrOpd0, BFXOpc, Src, ImmR, ImmS,
NumberOfIgnoredLowBits, BiggerPattern)) {
// Check that the returned opcode is compatible with the pattern,
// i.e., same type and zero extended (U and not S)
if ((BFXOpc != AArch64::UBFMXri && VT == MVT::i64) ||
(BFXOpc != AArch64::UBFMWri && VT == MVT::i32))
continue;
// Compute the width of the bitfield insertion
DstLSB = 0;
Width = ImmS - ImmR + 1;
// FIXME: This constraint is to catch bitfield insertion we may
// want to widen the pattern if we want to grab general bitfied
// move case
if (Width <= 0)
continue;
// If the mask on the insertee is correct, we have a BFXIL operation. We
// can share the ImmR and ImmS values from the already-computed UBFM.
} else if (isBitfieldPositioningOp(CurDAG, OrOpd0Val,
BiggerPattern,
Src, DstLSB, Width)) {
ImmR = (BitWidth - DstLSB) % BitWidth;
ImmS = Width - 1;
} else
continue;
// Check the second part of the pattern
EVT VT = OrOpd1Val.getValueType();
assert((VT == MVT::i32 || VT == MVT::i64) && "unexpected OR operand");
// Compute the Known Zero for the candidate of the first operand.
// This allows to catch more general case than just looking for
// AND with imm. Indeed, simplify-demanded-bits may have removed
// the AND instruction because it proves it was useless.
KnownBits Known = CurDAG->computeKnownBits(OrOpd1Val);
// Check if there is enough room for the second operand to appear
// in the first one
APInt BitsToBeInserted =
APInt::getBitsSet(Known.getBitWidth(), DstLSB, DstLSB + Width);
if ((BitsToBeInserted & ~Known.Zero) != 0)
continue;
// Set the first operand
uint64_t Imm;
if (isOpcWithIntImmediate(OrOpd1, ISD::AND, Imm) &&
isBitfieldDstMask(Imm, BitsToBeInserted, NumberOfIgnoredHighBits, VT))
// In that case, we can eliminate the AND
Dst = OrOpd1->getOperand(0);
else
// Maybe the AND has been removed by simplify-demanded-bits
// or is useful because it discards more bits
Dst = OrOpd1Val;
// both parts match
SDLoc DL(N);
SDValue Ops[] = {Dst, Src, CurDAG->getTargetConstant(ImmR, DL, VT),
CurDAG->getTargetConstant(ImmS, DL, VT)};
unsigned Opc = (VT == MVT::i32) ? AArch64::BFMWri : AArch64::BFMXri;
CurDAG->SelectNodeTo(N, Opc, VT, Ops);
return true;
}
// Generate a BFXIL from 'or (and X, Mask0Imm), (and Y, Mask1Imm)' iff
// Mask0Imm and ~Mask1Imm are equivalent and one of the MaskImms is a shifted
// mask (e.g., 0x000ffff0).
uint64_t Mask0Imm, Mask1Imm;
SDValue And0 = N->getOperand(0);
SDValue And1 = N->getOperand(1);
if (And0.hasOneUse() && And1.hasOneUse() &&
isOpcWithIntImmediate(And0.getNode(), ISD::AND, Mask0Imm) &&
isOpcWithIntImmediate(And1.getNode(), ISD::AND, Mask1Imm) &&
APInt(BitWidth, Mask0Imm) == ~APInt(BitWidth, Mask1Imm) &&
(isShiftedMask(Mask0Imm, VT) || isShiftedMask(Mask1Imm, VT))) {
// ORR is commutative, so canonicalize to the form 'or (and X, Mask0Imm),
// (and Y, Mask1Imm)' where Mask1Imm is the shifted mask masking off the
// bits to be inserted.
if (isShiftedMask(Mask0Imm, VT)) {
std::swap(And0, And1);
std::swap(Mask0Imm, Mask1Imm);
}
SDValue Src = And1->getOperand(0);
SDValue Dst = And0->getOperand(0);
unsigned LSB = countTrailingZeros(Mask1Imm);
int Width = BitWidth - APInt(BitWidth, Mask0Imm).countPopulation();
// The BFXIL inserts the low-order bits from a source register, so right
// shift the needed bits into place.
SDLoc DL(N);
unsigned ShiftOpc = (VT == MVT::i32) ? AArch64::UBFMWri : AArch64::UBFMXri;
SDNode *LSR = CurDAG->getMachineNode(
ShiftOpc, DL, VT, Src, CurDAG->getTargetConstant(LSB, DL, VT),
CurDAG->getTargetConstant(BitWidth - 1, DL, VT));
// BFXIL is an alias of BFM, so translate to BFM operands.
unsigned ImmR = (BitWidth - LSB) % BitWidth;
unsigned ImmS = Width - 1;
// Create the BFXIL instruction.
SDValue Ops[] = {Dst, SDValue(LSR, 0),
CurDAG->getTargetConstant(ImmR, DL, VT),
CurDAG->getTargetConstant(ImmS, DL, VT)};
unsigned Opc = (VT == MVT::i32) ? AArch64::BFMWri : AArch64::BFMXri;
CurDAG->SelectNodeTo(N, Opc, VT, Ops);
return true;
}
return false;
}
bool AArch64DAGToDAGISel::tryBitfieldInsertOp(SDNode *N) {
if (N->getOpcode() != ISD::OR)
return false;
APInt NUsefulBits;
getUsefulBits(SDValue(N, 0), NUsefulBits);
// If all bits are not useful, just return UNDEF.
if (!NUsefulBits) {
CurDAG->SelectNodeTo(N, TargetOpcode::IMPLICIT_DEF, N->getValueType(0));
return true;
}
if (tryBitfieldInsertOpFromOr(N, NUsefulBits, CurDAG))
return true;
return tryBitfieldInsertOpFromOrAndImm(N, CurDAG);
}
/// SelectBitfieldInsertInZeroOp - Match a UBFIZ instruction that is the
/// equivalent of a left shift by a constant amount followed by an and masking
/// out a contiguous set of bits.
bool AArch64DAGToDAGISel::tryBitfieldInsertInZeroOp(SDNode *N) {
if (N->getOpcode() != ISD::AND)
return false;
EVT VT = N->getValueType(0);
if (VT != MVT::i32 && VT != MVT::i64)
return false;
SDValue Op0;
int DstLSB, Width;
if (!isBitfieldPositioningOp(CurDAG, SDValue(N, 0), /*BiggerPattern=*/false,
Op0, DstLSB, Width))
return false;
// ImmR is the rotate right amount.
unsigned ImmR = (VT.getSizeInBits() - DstLSB) % VT.getSizeInBits();
// ImmS is the most significant bit of the source to be moved.
unsigned ImmS = Width - 1;
SDLoc DL(N);
SDValue Ops[] = {Op0, CurDAG->getTargetConstant(ImmR, DL, VT),
CurDAG->getTargetConstant(ImmS, DL, VT)};
unsigned Opc = (VT == MVT::i32) ? AArch64::UBFMWri : AArch64::UBFMXri;
CurDAG->SelectNodeTo(N, Opc, VT, Ops);
return true;
}
/// tryShiftAmountMod - Take advantage of built-in mod of shift amount in
/// variable shift/rotate instructions.
bool AArch64DAGToDAGISel::tryShiftAmountMod(SDNode *N) {
EVT VT = N->getValueType(0);
unsigned Opc;
switch (N->getOpcode()) {
case ISD::ROTR:
Opc = (VT == MVT::i32) ? AArch64::RORVWr : AArch64::RORVXr;
break;
case ISD::SHL:
Opc = (VT == MVT::i32) ? AArch64::LSLVWr : AArch64::LSLVXr;
break;
case ISD::SRL:
Opc = (VT == MVT::i32) ? AArch64::LSRVWr : AArch64::LSRVXr;
break;
case ISD::SRA:
Opc = (VT == MVT::i32) ? AArch64::ASRVWr : AArch64::ASRVXr;
break;
default:
return false;
}
uint64_t Size;
uint64_t Bits;
if (VT == MVT::i32) {
Bits = 5;
Size = 32;
} else if (VT == MVT::i64) {
Bits = 6;
Size = 64;
} else
return false;
SDValue ShiftAmt = N->getOperand(1);
SDLoc DL(N);
SDValue NewShiftAmt;
// Skip over an extend of the shift amount.
if (ShiftAmt->getOpcode() == ISD::ZERO_EXTEND ||
ShiftAmt->getOpcode() == ISD::ANY_EXTEND)
ShiftAmt = ShiftAmt->getOperand(0);
if (ShiftAmt->getOpcode() == ISD::ADD || ShiftAmt->getOpcode() == ISD::SUB) {
SDValue Add0 = ShiftAmt->getOperand(0);
SDValue Add1 = ShiftAmt->getOperand(1);
uint64_t Add0Imm;
uint64_t Add1Imm;
// If we are shifting by X+/-N where N == 0 mod Size, then just shift by X
// to avoid the ADD/SUB.
if (isIntImmediate(Add1, Add1Imm) && (Add1Imm % Size == 0))
NewShiftAmt = Add0;
// If we are shifting by N-X where N == 0 mod Size, then just shift by -X to
// generate a NEG instead of a SUB of a constant.
else if (ShiftAmt->getOpcode() == ISD::SUB &&
isIntImmediate(Add0, Add0Imm) && Add0Imm != 0 &&
(Add0Imm % Size == 0)) {
unsigned NegOpc;
unsigned ZeroReg;
EVT SubVT = ShiftAmt->getValueType(0);
if (SubVT == MVT::i32) {
NegOpc = AArch64::SUBWrr;
ZeroReg = AArch64::WZR;
} else {
assert(SubVT == MVT::i64);
NegOpc = AArch64::SUBXrr;
ZeroReg = AArch64::XZR;
}
SDValue Zero =
CurDAG->getCopyFromReg(CurDAG->getEntryNode(), DL, ZeroReg, SubVT);
MachineSDNode *Neg =
CurDAG->getMachineNode(NegOpc, DL, SubVT, Zero, Add1);
NewShiftAmt = SDValue(Neg, 0);
} else
return false;
} else {
// If the shift amount is masked with an AND, check that the mask covers the
// bits that are implicitly ANDed off by the above opcodes and if so, skip
// the AND.
uint64_t MaskImm;
if (!isOpcWithIntImmediate(ShiftAmt.getNode(), ISD::AND, MaskImm) &&
!isOpcWithIntImmediate(ShiftAmt.getNode(), AArch64ISD::ANDS, MaskImm))
return false;
if (countTrailingOnes(MaskImm) < Bits)
return false;
NewShiftAmt = ShiftAmt->getOperand(0);
}
// Narrow/widen the shift amount to match the size of the shift operation.
if (VT == MVT::i32)
NewShiftAmt = narrowIfNeeded(CurDAG, NewShiftAmt);
else if (VT == MVT::i64 && NewShiftAmt->getValueType(0) == MVT::i32) {
SDValue SubReg = CurDAG->getTargetConstant(AArch64::sub_32, DL, MVT::i32);
MachineSDNode *Ext = CurDAG->getMachineNode(
AArch64::SUBREG_TO_REG, DL, VT,
CurDAG->getTargetConstant(0, DL, MVT::i64), NewShiftAmt, SubReg);
NewShiftAmt = SDValue(Ext, 0);
}
SDValue Ops[] = {N->getOperand(0), NewShiftAmt};
CurDAG->SelectNodeTo(N, Opc, VT, Ops);
return true;
}
bool
AArch64DAGToDAGISel::SelectCVTFixedPosOperand(SDValue N, SDValue &FixedPos,
unsigned RegWidth) {
APFloat FVal(0.0);
if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
FVal = CN->getValueAPF();
else if (LoadSDNode *LN = dyn_cast<LoadSDNode>(N)) {
// Some otherwise illegal constants are allowed in this case.
if (LN->getOperand(1).getOpcode() != AArch64ISD::ADDlow ||
!isa<ConstantPoolSDNode>(LN->getOperand(1)->getOperand(1)))
return false;
ConstantPoolSDNode *CN =
dyn_cast<ConstantPoolSDNode>(LN->getOperand(1)->getOperand(1));
FVal = cast<ConstantFP>(CN->getConstVal())->getValueAPF();
} else
return false;
// An FCVT[SU] instruction performs: convertToInt(Val * 2^fbits) where fbits
// is between 1 and 32 for a destination w-register, or 1 and 64 for an
// x-register.
//
// By this stage, we've detected (fp_to_[su]int (fmul Val, THIS_NODE)) so we
// want THIS_NODE to be 2^fbits. This is much easier to deal with using
// integers.
bool IsExact;
// fbits is between 1 and 64 in the worst-case, which means the fmul
// could have 2^64 as an actual operand. Need 65 bits of precision.
APSInt IntVal(65, true);
FVal.convertToInteger(IntVal, APFloat::rmTowardZero, &IsExact);
// N.b. isPowerOf2 also checks for > 0.
if (!IsExact || !IntVal.isPowerOf2()) return false;
unsigned FBits = IntVal.logBase2();
// Checks above should have guaranteed that we haven't lost information in
// finding FBits, but it must still be in range.
if (FBits == 0 || FBits > RegWidth) return false;
FixedPos = CurDAG->getTargetConstant(FBits, SDLoc(N), MVT::i32);
return true;
}
// Inspects a register string of the form o0:op1:CRn:CRm:op2 gets the fields
// of the string and obtains the integer values from them and combines these
// into a single value to be used in the MRS/MSR instruction.
static int getIntOperandFromRegisterString(StringRef RegString) {
SmallVector<StringRef, 5> Fields;
RegString.split(Fields, ':');
if (Fields.size() == 1)
return -1;
assert(Fields.size() == 5
&& "Invalid number of fields in read register string");
SmallVector<int, 5> Ops;
bool AllIntFields = true;
for (StringRef Field : Fields) {
unsigned IntField;
AllIntFields &= !Field.getAsInteger(10, IntField);
Ops.push_back(IntField);
}
assert(AllIntFields &&
"Unexpected non-integer value in special register string.");
// Need to combine the integer fields of the string into a single value
// based on the bit encoding of MRS/MSR instruction.
return (Ops[0] << 14) | (Ops[1] << 11) | (Ops[2] << 7) |
(Ops[3] << 3) | (Ops[4]);
}
// Lower the read_register intrinsic to an MRS instruction node if the special
// register string argument is either of the form detailed in the ALCE (the
// form described in getIntOperandsFromRegsterString) or is a named register
// known by the MRS SysReg mapper.
bool AArch64DAGToDAGISel::tryReadRegister(SDNode *N) {
const MDNodeSDNode *MD = dyn_cast<MDNodeSDNode>(N->getOperand(1));
const MDString *RegString = dyn_cast<MDString>(MD->getMD()->getOperand(0));
SDLoc DL(N);
int Reg = getIntOperandFromRegisterString(RegString->getString());
if (Reg != -1) {
ReplaceNode(N, CurDAG->getMachineNode(
AArch64::MRS, DL, N->getSimpleValueType(0), MVT::Other,
CurDAG->getTargetConstant(Reg, DL, MVT::i32),
N->getOperand(0)));
return true;
}
// Use the sysreg mapper to map the remaining possible strings to the
// value for the register to be used for the instruction operand.
auto TheReg = AArch64SysReg::lookupSysRegByName(RegString->getString());
if (TheReg && TheReg->Readable &&
TheReg->haveFeatures(Subtarget->getFeatureBits()))
Reg = TheReg->Encoding;
else
Reg = AArch64SysReg::parseGenericRegister(RegString->getString());
if (Reg != -1) {
ReplaceNode(N, CurDAG->getMachineNode(
AArch64::MRS, DL, N->getSimpleValueType(0), MVT::Other,
CurDAG->getTargetConstant(Reg, DL, MVT::i32),
N->getOperand(0)));
return true;
}
if (RegString->getString() == "pc") {
ReplaceNode(N, CurDAG->getMachineNode(
AArch64::ADR, DL, N->getSimpleValueType(0), MVT::Other,
CurDAG->getTargetConstant(0, DL, MVT::i32),
N->getOperand(0)));
return true;
}
return false;
}
// Lower the write_register intrinsic to an MSR instruction node if the special
// register string argument is either of the form detailed in the ALCE (the
// form described in getIntOperandsFromRegsterString) or is a named register
// known by the MSR SysReg mapper.
bool AArch64DAGToDAGISel::tryWriteRegister(SDNode *N) {
const MDNodeSDNode *MD = dyn_cast<MDNodeSDNode>(N->getOperand(1));
const MDString *RegString = dyn_cast<MDString>(MD->getMD()->getOperand(0));
SDLoc DL(N);
int Reg = getIntOperandFromRegisterString(RegString->getString());
if (Reg != -1) {
ReplaceNode(
N, CurDAG->getMachineNode(AArch64::MSR, DL, MVT::Other,
CurDAG->getTargetConstant(Reg, DL, MVT::i32),
N->getOperand(2), N->getOperand(0)));
return true;
}
// Check if the register was one of those allowed as the pstatefield value in
// the MSR (immediate) instruction. To accept the values allowed in the
// pstatefield for the MSR (immediate) instruction, we also require that an
// immediate value has been provided as an argument, we know that this is
// the case as it has been ensured by semantic checking.
auto PMapper = AArch64PState::lookupPStateByName(RegString->getString());
if (PMapper) {
assert (isa<ConstantSDNode>(N->getOperand(2))
&& "Expected a constant integer expression.");
unsigned Reg = PMapper->Encoding;
uint64_t Immed = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
unsigned State;
if (Reg == AArch64PState::PAN || Reg == AArch64PState::UAO || Reg == AArch64PState::SSBS) {
assert(Immed < 2 && "Bad imm");
State = AArch64::MSRpstateImm1;
} else {
assert(Immed < 16 && "Bad imm");
State = AArch64::MSRpstateImm4;
}
ReplaceNode(N, CurDAG->getMachineNode(
State, DL, MVT::Other,
CurDAG->getTargetConstant(Reg, DL, MVT::i32),
CurDAG->getTargetConstant(Immed, DL, MVT::i16),
N->getOperand(0)));
return true;
}
// Use the sysreg mapper to attempt to map the remaining possible strings
// to the value for the register to be used for the MSR (register)
// instruction operand.
auto TheReg = AArch64SysReg::lookupSysRegByName(RegString->getString());
if (TheReg && TheReg->Writeable &&
TheReg->haveFeatures(Subtarget->getFeatureBits()))
Reg = TheReg->Encoding;
else
Reg = AArch64SysReg::parseGenericRegister(RegString->getString());
if (Reg != -1) {
ReplaceNode(N, CurDAG->getMachineNode(
AArch64::MSR, DL, MVT::Other,
CurDAG->getTargetConstant(Reg, DL, MVT::i32),
N->getOperand(2), N->getOperand(0)));
return true;
}
return false;
}
/// We've got special pseudo-instructions for these
bool AArch64DAGToDAGISel::SelectCMP_SWAP(SDNode *N) {
unsigned Opcode;
EVT MemTy = cast<MemSDNode>(N)->getMemoryVT();
// Leave IR for LSE if subtarget supports it.
if (Subtarget->hasLSE()) return false;
if (MemTy == MVT::i8)
Opcode = AArch64::CMP_SWAP_8;
else if (MemTy == MVT::i16)
Opcode = AArch64::CMP_SWAP_16;
else if (MemTy == MVT::i32)
Opcode = AArch64::CMP_SWAP_32;
else if (MemTy == MVT::i64)
Opcode = AArch64::CMP_SWAP_64;
else
llvm_unreachable("Unknown AtomicCmpSwap type");
MVT RegTy = MemTy == MVT::i64 ? MVT::i64 : MVT::i32;
SDValue Ops[] = {N->getOperand(1), N->getOperand(2), N->getOperand(3),
N->getOperand(0)};
SDNode *CmpSwap = CurDAG->getMachineNode(
Opcode, SDLoc(N),
CurDAG->getVTList(RegTy, MVT::i32, MVT::Other), Ops);
MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand();
CurDAG->setNodeMemRefs(cast<MachineSDNode>(CmpSwap), {MemOp});
ReplaceUses(SDValue(N, 0), SDValue(CmpSwap, 0));
ReplaceUses(SDValue(N, 1), SDValue(CmpSwap, 2));
CurDAG->RemoveDeadNode(N);
return true;
}
bool AArch64DAGToDAGISel::SelectSVE8BitLslImm(SDValue N, SDValue &Base,
SDValue &Offset) {
auto C = dyn_cast<ConstantSDNode>(N);
if (!C)
return false;
auto Ty = N->getValueType(0);
int64_t Imm = C->getSExtValue();
SDLoc DL(N);
if ((Imm >= -128) && (Imm <= 127)) {
Base = CurDAG->getTargetConstant(Imm, DL, Ty);
Offset = CurDAG->getTargetConstant(0, DL, Ty);
return true;
}
if (((Imm % 256) == 0) && (Imm >= -32768) && (Imm <= 32512)) {
Base = CurDAG->getTargetConstant(Imm/256, DL, Ty);
Offset = CurDAG->getTargetConstant(8, DL, Ty);
return true;
}
return false;
}
bool AArch64DAGToDAGISel::SelectSVEAddSubImm(SDValue N, MVT VT, SDValue &Imm, SDValue &Shift) {
if (auto CNode = dyn_cast<ConstantSDNode>(N)) {
const int64_t ImmVal = CNode->getZExtValue();
SDLoc DL(N);
switch (VT.SimpleTy) {
case MVT::i8:
if ((ImmVal & 0xFF) == ImmVal) {
Shift = CurDAG->getTargetConstant(0, DL, MVT::i32);
Imm = CurDAG->getTargetConstant(ImmVal, DL, MVT::i32);
return true;
}
break;
case MVT::i16:
case MVT::i32:
case MVT::i64:
if ((ImmVal & 0xFF) == ImmVal) {
Shift = CurDAG->getTargetConstant(0, DL, MVT::i32);
Imm = CurDAG->getTargetConstant(ImmVal, DL, MVT::i32);
return true;
} else if ((ImmVal & 0xFF00) == ImmVal) {
Shift = CurDAG->getTargetConstant(8, DL, MVT::i32);
Imm = CurDAG->getTargetConstant(ImmVal >> 8, DL, MVT::i32);
return true;
}
break;
default:
break;
}
}
return false;
}
bool AArch64DAGToDAGISel::SelectSVESignedArithImm(SDValue N, SDValue &Imm) {
if (auto CNode = dyn_cast<ConstantSDNode>(N)) {
int64_t ImmVal = CNode->getSExtValue();
SDLoc DL(N);
if (ImmVal >= -128 && ImmVal < 128) {
Imm = CurDAG->getTargetConstant(ImmVal, DL, MVT::i32);
return true;
}
}
return false;
}
bool AArch64DAGToDAGISel::SelectSVEArithImm(SDValue N, MVT VT, SDValue &Imm) {
if (auto CNode = dyn_cast<ConstantSDNode>(N)) {
uint64_t ImmVal = CNode->getZExtValue();
switch (VT.SimpleTy) {
case MVT::i8:
ImmVal &= 0xFF;
break;
case MVT::i16:
ImmVal &= 0xFFFF;
break;
case MVT::i32:
ImmVal &= 0xFFFFFFFF;
break;
case MVT::i64:
break;
default:
llvm_unreachable("Unexpected type");
}
if (ImmVal < 256) {
Imm = CurDAG->getTargetConstant(ImmVal, SDLoc(N), MVT::i32);
return true;
}
}
return false;
}
bool AArch64DAGToDAGISel::SelectSVELogicalImm(SDValue N, MVT VT, SDValue &Imm) {
if (auto CNode = dyn_cast<ConstantSDNode>(N)) {
uint64_t ImmVal = CNode->getZExtValue();
SDLoc DL(N);
// Shift mask depending on type size.
switch (VT.SimpleTy) {
case MVT::i8:
ImmVal &= 0xFF;
ImmVal |= ImmVal << 8;
ImmVal |= ImmVal << 16;
ImmVal |= ImmVal << 32;
break;
case MVT::i16:
ImmVal &= 0xFFFF;
ImmVal |= ImmVal << 16;
ImmVal |= ImmVal << 32;
break;
case MVT::i32:
ImmVal &= 0xFFFFFFFF;
ImmVal |= ImmVal << 32;
break;
case MVT::i64:
break;
default:
llvm_unreachable("Unexpected type");
}
uint64_t encoding;
if (AArch64_AM::processLogicalImmediate(ImmVal, 64, encoding)) {
Imm = CurDAG->getTargetConstant(encoding, DL, MVT::i64);
return true;
}
}
return false;
}
// SVE shift intrinsics allow shift amounts larger than the element's bitwidth.
// Rather than attempt to normalise everything we can sometimes saturate the
// shift amount during selection. This function also allows for consistent
// isel patterns by ensuring the resulting "Imm" node is of the i32 type
// required by the instructions.
bool AArch64DAGToDAGISel::SelectSVEShiftImm(SDValue N, uint64_t Low,
uint64_t High, bool AllowSaturation,
SDValue &Imm) {
if (auto *CN = dyn_cast<ConstantSDNode>(N)) {
uint64_t ImmVal = CN->getZExtValue();
// Reject shift amounts that are too small.
if (ImmVal < Low)
return false;
// Reject or saturate shift amounts that are too big.
if (ImmVal > High) {
if (!AllowSaturation)
return false;
ImmVal = High;
}
Imm = CurDAG->getTargetConstant(ImmVal, SDLoc(N), MVT::i32);
return true;
}
return false;
}
bool AArch64DAGToDAGISel::trySelectStackSlotTagP(SDNode *N) {
// tagp(FrameIndex, IRGstack, tag_offset):
// since the offset between FrameIndex and IRGstack is a compile-time
// constant, this can be lowered to a single ADDG instruction.
if (!(isa<FrameIndexSDNode>(N->getOperand(1)))) {
return false;
}
SDValue IRG_SP = N->getOperand(2);
if (IRG_SP->getOpcode() != ISD::INTRINSIC_W_CHAIN ||
cast<ConstantSDNode>(IRG_SP->getOperand(1))->getZExtValue() !=
Intrinsic::aarch64_irg_sp) {
return false;
}
const TargetLowering *TLI = getTargetLowering();
SDLoc DL(N);
int FI = cast<FrameIndexSDNode>(N->getOperand(1))->getIndex();
SDValue FiOp = CurDAG->getTargetFrameIndex(
FI, TLI->getPointerTy(CurDAG->getDataLayout()));
int TagOffset = cast<ConstantSDNode>(N->getOperand(3))->getZExtValue();
SDNode *Out = CurDAG->getMachineNode(
AArch64::TAGPstack, DL, MVT::i64,
{FiOp, CurDAG->getTargetConstant(0, DL, MVT::i64), N->getOperand(2),
CurDAG->getTargetConstant(TagOffset, DL, MVT::i64)});
ReplaceNode(N, Out);
return true;
}
void AArch64DAGToDAGISel::SelectTagP(SDNode *N) {
assert(isa<ConstantSDNode>(N->getOperand(3)) &&
"llvm.aarch64.tagp third argument must be an immediate");
if (trySelectStackSlotTagP(N))
return;
// FIXME: above applies in any case when offset between Op1 and Op2 is a
// compile-time constant, not just for stack allocations.
// General case for unrelated pointers in Op1 and Op2.
SDLoc DL(N);
int TagOffset = cast<ConstantSDNode>(N->getOperand(3))->getZExtValue();
SDNode *N1 = CurDAG->getMachineNode(AArch64::SUBP, DL, MVT::i64,
{N->getOperand(1), N->getOperand(2)});
SDNode *N2 = CurDAG->getMachineNode(AArch64::ADDXrr, DL, MVT::i64,
{SDValue(N1, 0), N->getOperand(2)});
SDNode *N3 = CurDAG->getMachineNode(
AArch64::ADDG, DL, MVT::i64,
{SDValue(N2, 0), CurDAG->getTargetConstant(0, DL, MVT::i64),
CurDAG->getTargetConstant(TagOffset, DL, MVT::i64)});
ReplaceNode(N, N3);
}
// NOTE: We cannot use EXTRACT_SUBREG in all cases because the fixed length
// vector types larger than NEON don't have a matching SubRegIndex.
static SDNode *extractSubReg(SelectionDAG *DAG, EVT VT, SDValue V) {
assert(V.getValueType().isScalableVector() &&
V.getValueType().getSizeInBits().getKnownMinSize() ==
AArch64::SVEBitsPerBlock &&
"Expected to extract from a packed scalable vector!");
assert(VT.isFixedLengthVector() &&
"Expected to extract a fixed length vector!");
SDLoc DL(V);
switch (VT.getSizeInBits()) {
case 64: {
auto SubReg = DAG->getTargetConstant(AArch64::dsub, DL, MVT::i32);
return DAG->getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, VT, V, SubReg);
}
case 128: {
auto SubReg = DAG->getTargetConstant(AArch64::zsub, DL, MVT::i32);
return DAG->getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, VT, V, SubReg);
}
default: {
auto RC = DAG->getTargetConstant(AArch64::ZPRRegClassID, DL, MVT::i64);
return DAG->getMachineNode(TargetOpcode::COPY_TO_REGCLASS, DL, VT, V, RC);
}
}
}
// NOTE: We cannot use INSERT_SUBREG in all cases because the fixed length
// vector types larger than NEON don't have a matching SubRegIndex.
static SDNode *insertSubReg(SelectionDAG *DAG, EVT VT, SDValue V) {
assert(VT.isScalableVector() &&
VT.getSizeInBits().getKnownMinSize() == AArch64::SVEBitsPerBlock &&
"Expected to insert into a packed scalable vector!");
assert(V.getValueType().isFixedLengthVector() &&
"Expected to insert a fixed length vector!");
SDLoc DL(V);
switch (V.getValueType().getSizeInBits()) {
case 64: {
auto SubReg = DAG->getTargetConstant(AArch64::dsub, DL, MVT::i32);
auto Container = DAG->getMachineNode(TargetOpcode::IMPLICIT_DEF, DL, VT);
return DAG->getMachineNode(TargetOpcode::INSERT_SUBREG, DL, VT,
SDValue(Container, 0), V, SubReg);
}
case 128: {
auto SubReg = DAG->getTargetConstant(AArch64::zsub, DL, MVT::i32);
auto Container = DAG->getMachineNode(TargetOpcode::IMPLICIT_DEF, DL, VT);
return DAG->getMachineNode(TargetOpcode::INSERT_SUBREG, DL, VT,
SDValue(Container, 0), V, SubReg);
}
default: {
auto RC = DAG->getTargetConstant(AArch64::ZPRRegClassID, DL, MVT::i64);
return DAG->getMachineNode(TargetOpcode::COPY_TO_REGCLASS, DL, VT, V, RC);
}
}
}
void AArch64DAGToDAGISel::Select(SDNode *Node) {
// If we have a custom node, we already have selected!
if (Node->isMachineOpcode()) {
LLVM_DEBUG(errs() << "== "; Node->dump(CurDAG); errs() << "\n");
Node->setNodeId(-1);
return;
}
// Few custom selection stuff.
EVT VT = Node->getValueType(0);
switch (Node->getOpcode()) {
default:
break;
case ISD::ATOMIC_CMP_SWAP:
if (SelectCMP_SWAP(Node))
return;
break;
case ISD::READ_REGISTER:
if (tryReadRegister(Node))
return;
break;
case ISD::WRITE_REGISTER:
if (tryWriteRegister(Node))
return;
break;
case ISD::ADD:
if (tryMLAV64LaneV128(Node))
return;
break;
case ISD::LOAD: {
// Try to select as an indexed load. Fall through to normal processing
// if we can't.
if (tryIndexedLoad(Node))
return;
break;
}
case ISD::SRL:
case ISD::AND:
case ISD::SRA:
case ISD::SIGN_EXTEND_INREG:
if (tryBitfieldExtractOp(Node))
return;
if (tryBitfieldInsertInZeroOp(Node))
return;
LLVM_FALLTHROUGH;
case ISD::ROTR:
case ISD::SHL:
if (tryShiftAmountMod(Node))
return;
break;
case ISD::SIGN_EXTEND:
if (tryBitfieldExtractOpFromSExt(Node))
return;
break;
case ISD::FP_EXTEND:
if (tryHighFPExt(Node))
return;
break;
case ISD::OR:
if (tryBitfieldInsertOp(Node))
return;
break;
case ISD::EXTRACT_SUBVECTOR: {
// Bail when not a "cast" like extract_subvector.
if (cast<ConstantSDNode>(Node->getOperand(1))->getZExtValue() != 0)
break;
// Bail when normal isel can do the job.
EVT InVT = Node->getOperand(0).getValueType();
if (VT.isScalableVector() || InVT.isFixedLengthVector())
break;
// NOTE: We can only get here when doing fixed length SVE code generation.
// We do manual selection because the types involved are not linked to real
// registers (despite being legal) and must be coerced into SVE registers.
//
// NOTE: If the above changes, be aware that selection will still not work
// because the td definition of extract_vector does not support extracting
// a fixed length vector from a scalable vector.
ReplaceNode(Node, extractSubReg(CurDAG, VT, Node->getOperand(0)));
return;
}
case ISD::INSERT_SUBVECTOR: {
// Bail when not a "cast" like insert_subvector.
if (cast<ConstantSDNode>(Node->getOperand(2))->getZExtValue() != 0)
break;
if (!Node->getOperand(0).isUndef())
break;
// Bail when normal isel should do the job.
EVT InVT = Node->getOperand(1).getValueType();
if (VT.isFixedLengthVector() || InVT.isScalableVector())
break;
// NOTE: We can only get here when doing fixed length SVE code generation.
// We do manual selection because the types involved are not linked to real
// registers (despite being legal) and must be coerced into SVE registers.
//
// NOTE: If the above changes, be aware that selection will still not work
// because the td definition of insert_vector does not support inserting a
// fixed length vector into a scalable vector.
ReplaceNode(Node, insertSubReg(CurDAG, VT, Node->getOperand(1)));
return;
}
case ISD::Constant: {
// Materialize zero constants as copies from WZR/XZR. This allows
// the coalescer to propagate these into other instructions.
ConstantSDNode *ConstNode = cast<ConstantSDNode>(Node);
if (ConstNode->isNullValue()) {
if (VT == MVT::i32) {
SDValue New = CurDAG->getCopyFromReg(
CurDAG->getEntryNode(), SDLoc(Node), AArch64::WZR, MVT::i32);
ReplaceNode(Node, New.getNode());
return;
} else if (VT == MVT::i64) {
SDValue New = CurDAG->getCopyFromReg(
CurDAG->getEntryNode(), SDLoc(Node), AArch64::XZR, MVT::i64);
ReplaceNode(Node, New.getNode());
return;
}
}
break;
}
case ISD::FrameIndex: {
// Selects to ADDXri FI, 0 which in turn will become ADDXri SP, imm.
int FI = cast<FrameIndexSDNode>(Node)->getIndex();
unsigned Shifter = AArch64_AM::getShifterImm(AArch64_AM::LSL, 0);
const TargetLowering *TLI = getTargetLowering();
SDValue TFI = CurDAG->getTargetFrameIndex(
FI, TLI->getPointerTy(CurDAG->getDataLayout()));
SDLoc DL(Node);
SDValue Ops[] = { TFI, CurDAG->getTargetConstant(0, DL, MVT::i32),
CurDAG->getTargetConstant(Shifter, DL, MVT::i32) };
CurDAG->SelectNodeTo(Node, AArch64::ADDXri, MVT::i64, Ops);
return;
}
case ISD::INTRINSIC_W_CHAIN: {
unsigned IntNo = cast<ConstantSDNode>(Node->getOperand(1))->getZExtValue();
switch (IntNo) {
default:
break;
case Intrinsic::aarch64_ldaxp:
case Intrinsic::aarch64_ldxp: {
unsigned Op =
IntNo == Intrinsic::aarch64_ldaxp ? AArch64::LDAXPX : AArch64::LDXPX;
SDValue MemAddr = Node->getOperand(2);
SDLoc DL(Node);
SDValue Chain = Node->getOperand(0);
SDNode *Ld = CurDAG->getMachineNode(Op, DL, MVT::i64, MVT::i64,
MVT::Other, MemAddr, Chain);
// Transfer memoperands.
MachineMemOperand *MemOp =
cast<MemIntrinsicSDNode>(Node)->getMemOperand();
CurDAG->setNodeMemRefs(cast<MachineSDNode>(Ld), {MemOp});
ReplaceNode(Node, Ld);
return;
}
case Intrinsic::aarch64_stlxp:
case Intrinsic::aarch64_stxp: {
unsigned Op =
IntNo == Intrinsic::aarch64_stlxp ? AArch64::STLXPX : AArch64::STXPX;
SDLoc DL(Node);
SDValue Chain = Node->getOperand(0);
SDValue ValLo = Node->getOperand(2);
SDValue ValHi = Node->getOperand(3);
SDValue MemAddr = Node->getOperand(4);
// Place arguments in the right order.
SDValue Ops[] = {ValLo, ValHi, MemAddr, Chain};
SDNode *St = CurDAG->getMachineNode(Op, DL, MVT::i32, MVT::Other, Ops);
// Transfer memoperands.
MachineMemOperand *MemOp =
cast<MemIntrinsicSDNode>(Node)->getMemOperand();
CurDAG->setNodeMemRefs(cast<MachineSDNode>(St), {MemOp});
ReplaceNode(Node, St);
return;
}
case Intrinsic::aarch64_neon_ld1x2:
if (VT == MVT::v8i8) {
SelectLoad(Node, 2, AArch64::LD1Twov8b, AArch64::dsub0);
return;
} else if (VT == MVT::v16i8) {
SelectLoad(Node, 2, AArch64::LD1Twov16b, AArch64::qsub0);
return;
} else if (VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v4bf16) {
SelectLoad(Node, 2, AArch64::LD1Twov4h, AArch64::dsub0);
return;
} else if (VT == MVT::v8i16 || VT == MVT::v8f16 || VT == MVT::v8bf16) {
SelectLoad(Node, 2, AArch64::LD1Twov8h, AArch64::qsub0);
return;
} else if (VT == MVT::v2i32 || VT == MVT::v2f32) {
SelectLoad(Node, 2, AArch64::LD1Twov2s, AArch64::dsub0);
return;
} else if (VT == MVT::v4i32 || VT == MVT::v4f32) {
SelectLoad(Node, 2, AArch64::LD1Twov4s, AArch64::qsub0);
return;
} else if (VT == MVT::v1i64 || VT == MVT::v1f64) {
SelectLoad(Node, 2, AArch64::LD1Twov1d, AArch64::dsub0);
return;
} else if (VT == MVT::v2i64 || VT == MVT::v2f64) {
SelectLoad(Node, 2, AArch64::LD1Twov2d, AArch64::qsub0);
return;
}
break;
case Intrinsic::aarch64_neon_ld1x3:
if (VT == MVT::v8i8) {
SelectLoad(Node, 3, AArch64::LD1Threev8b, AArch64::dsub0);
return;
} else if (VT == MVT::v16i8) {
SelectLoad(Node, 3, AArch64::LD1Threev16b, AArch64::qsub0);
return;
} else if (VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v4bf16) {
SelectLoad(Node, 3, AArch64::LD1Threev4h, AArch64::dsub0);
return;
} else if (VT == MVT::v8i16 || VT == MVT::v8f16 || VT == MVT::v8bf16) {
SelectLoad(Node, 3, AArch64::LD1Threev8h, AArch64::qsub0);
return;
} else if (VT == MVT::v2i32 || VT == MVT::v2f32) {
SelectLoad(Node, 3, AArch64::LD1Threev2s, AArch64::dsub0);
return;
} else if (VT == MVT::v4i32 || VT == MVT::v4f32) {
SelectLoad(Node, 3, AArch64::LD1Threev4s, AArch64::qsub0);
return;
} else if (VT == MVT::v1i64 || VT == MVT::v1f64) {
SelectLoad(Node, 3, AArch64::LD1Threev1d, AArch64::dsub0);
return;
} else if (VT == MVT::v2i64 || VT == MVT::v2f64) {
SelectLoad(Node, 3, AArch64::LD1Threev2d, AArch64::qsub0);
return;
}
break;
case Intrinsic::aarch64_neon_ld1x4:
if (VT == MVT::v8i8) {
SelectLoad(Node, 4, AArch64::LD1Fourv8b, AArch64::dsub0);
return;
} else if (VT == MVT::v16i8) {
SelectLoad(Node, 4, AArch64::LD1Fourv16b, AArch64::qsub0);
return;
} else if (VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v4bf16) {
SelectLoad(Node, 4, AArch64::LD1Fourv4h, AArch64::dsub0);
return;
} else if (VT == MVT::v8i16 || VT == MVT::v8f16 || VT == MVT::v8bf16) {
SelectLoad(Node, 4, AArch64::LD1Fourv8h, AArch64::qsub0);
return;
} else if (VT == MVT::v2i32 || VT == MVT::v2f32) {
SelectLoad(Node, 4, AArch64::LD1Fourv2s, AArch64::dsub0);
return;
} else if (VT == MVT::v4i32 || VT == MVT::v4f32) {
SelectLoad(Node, 4, AArch64::LD1Fourv4s, AArch64::qsub0);
return;
} else if (VT == MVT::v1i64 || VT == MVT::v1f64) {
SelectLoad(Node, 4, AArch64::LD1Fourv1d, AArch64::dsub0);
return;
} else if (VT == MVT::v2i64 || VT == MVT::v2f64) {
SelectLoad(Node, 4, AArch64::LD1Fourv2d, AArch64::qsub0);
return;
}
break;
case Intrinsic::aarch64_neon_ld2:
if (VT == MVT::v8i8) {
SelectLoad(Node, 2, AArch64::LD2Twov8b, AArch64::dsub0);
return;
} else if (VT == MVT::v16i8) {
SelectLoad(Node, 2, AArch64::LD2Twov16b, AArch64::qsub0);
return;
} else if (VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v4bf16) {
SelectLoad(Node, 2, AArch64::LD2Twov4h, AArch64::dsub0);
return;
} else if (VT == MVT::v8i16 || VT == MVT::v8f16 || VT == MVT::v8bf16) {
SelectLoad(Node, 2, AArch64::LD2Twov8h, AArch64::qsub0);
return;
} else if (VT == MVT::v2i32 || VT == MVT::v2f32) {
SelectLoad(Node, 2, AArch64::LD2Twov2s, AArch64::dsub0);
return;
} else if (VT == MVT::v4i32 || VT == MVT::v4f32) {
SelectLoad(Node, 2, AArch64::LD2Twov4s, AArch64::qsub0);
return;
} else if (VT == MVT::v1i64 || VT == MVT::v1f64) {
SelectLoad(Node, 2, AArch64::LD1Twov1d, AArch64::dsub0);
return;
} else if (VT == MVT::v2i64 || VT == MVT::v2f64) {
SelectLoad(Node, 2, AArch64::LD2Twov2d, AArch64::qsub0);
return;
}
break;
case Intrinsic::aarch64_neon_ld3:
if (VT == MVT::v8i8) {
SelectLoad(Node, 3, AArch64::LD3Threev8b, AArch64::dsub0);
return;
} else if (VT == MVT::v16i8) {
SelectLoad(Node, 3, AArch64::LD3Threev16b, AArch64::qsub0);
return;
} else if (VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v4bf16) {
SelectLoad(Node, 3, AArch64::LD3Threev4h, AArch64::dsub0);
return;
} else if (VT == MVT::v8i16 || VT == MVT::v8f16 || VT == MVT::v8bf16) {
SelectLoad(Node, 3, AArch64::LD3Threev8h, AArch64::qsub0);
return;
} else if (VT == MVT::v2i32 || VT == MVT::v2f32) {
SelectLoad(Node, 3, AArch64::LD3Threev2s, AArch64::dsub0);
return;
} else if (VT == MVT::v4i32 || VT == MVT::v4f32) {
SelectLoad(Node, 3, AArch64::LD3Threev4s, AArch64::qsub0);
return;
} else if (VT == MVT::v1i64 || VT == MVT::v1f64) {
SelectLoad(Node, 3, AArch64::LD1Threev1d, AArch64::dsub0);
return;
} else if (VT == MVT::v2i64 || VT == MVT::v2f64) {
SelectLoad(Node, 3, AArch64::LD3Threev2d, AArch64::qsub0);
return;
}
break;
case Intrinsic::aarch64_neon_ld4:
if (VT == MVT::v8i8) {
SelectLoad(Node, 4, AArch64::LD4Fourv8b, AArch64::dsub0);
return;
} else if (VT == MVT::v16i8) {
SelectLoad(Node, 4, AArch64::LD4Fourv16b, AArch64::qsub0);
return;
} else if (VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v4bf16) {
SelectLoad(Node, 4, AArch64::LD4Fourv4h, AArch64::dsub0);
return;
} else if (VT == MVT::v8i16 || VT == MVT::v8f16 || VT == MVT::v8bf16) {
SelectLoad(Node, 4, AArch64::LD4Fourv8h, AArch64::qsub0);
return;
} else if (VT == MVT::v2i32 || VT == MVT::v2f32) {
SelectLoad(Node, 4, AArch64::LD4Fourv2s, AArch64::dsub0);
return;
} else if (VT == MVT::v4i32 || VT == MVT::v4f32) {
SelectLoad(Node, 4, AArch64::LD4Fourv4s, AArch64::qsub0);
return;
} else if (VT == MVT::v1i64 || VT == MVT::v1f64) {
SelectLoad(Node, 4, AArch64::LD1Fourv1d, AArch64::dsub0);
return;
} else if (VT == MVT::v2i64 || VT == MVT::v2f64) {
SelectLoad(Node, 4, AArch64::LD4Fourv2d, AArch64::qsub0);
return;
}
break;
case Intrinsic::aarch64_neon_ld2r:
if (VT == MVT::v8i8) {
SelectLoad(Node, 2, AArch64::LD2Rv8b, AArch64::dsub0);
return;
} else if (VT == MVT::v16i8) {
SelectLoad(Node, 2, AArch64::LD2Rv16b, AArch64::qsub0);
return;
} else if (VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v4bf16) {
SelectLoad(Node, 2, AArch64::LD2Rv4h, AArch64::dsub0);
return;
} else if (VT == MVT::v8i16 || VT == MVT::v8f16 || VT == MVT::v8bf16) {
SelectLoad(Node, 2, AArch64::LD2Rv8h, AArch64::qsub0);
return;
} else if (VT == MVT::v2i32 || VT == MVT::v2f32) {
SelectLoad(Node, 2, AArch64::LD2Rv2s, AArch64::dsub0);
return;
} else if (VT == MVT::v4i32 || VT == MVT::v4f32) {
SelectLoad(Node, 2, AArch64::LD2Rv4s, AArch64::qsub0);
return;
} else if (VT == MVT::v1i64 || VT == MVT::v1f64) {
SelectLoad(Node, 2, AArch64::LD2Rv1d, AArch64::dsub0);
return;
} else if (VT == MVT::v2i64 || VT == MVT::v2f64) {
SelectLoad(Node, 2, AArch64::LD2Rv2d, AArch64::qsub0);
return;
}
break;
case Intrinsic::aarch64_neon_ld3r:
if (VT == MVT::v8i8) {
SelectLoad(Node, 3, AArch64::LD3Rv8b, AArch64::dsub0);
return;
} else if (VT == MVT::v16i8) {
SelectLoad(Node, 3, AArch64::LD3Rv16b, AArch64::qsub0);
return;
} else if (VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v4bf16) {
SelectLoad(Node, 3, AArch64::LD3Rv4h, AArch64::dsub0);
return;
} else if (VT == MVT::v8i16 || VT == MVT::v8f16 || VT == MVT::v8bf16) {
SelectLoad(Node, 3, AArch64::LD3Rv8h, AArch64::qsub0);
return;
} else if (VT == MVT::v2i32 || VT == MVT::v2f32) {
SelectLoad(Node, 3, AArch64::LD3Rv2s, AArch64::dsub0);
return;
} else if (VT == MVT::v4i32 || VT == MVT::v4f32) {
SelectLoad(Node, 3, AArch64::LD3Rv4s, AArch64::qsub0);
return;
} else if (VT == MVT::v1i64 || VT == MVT::v1f64) {
SelectLoad(Node, 3, AArch64::LD3Rv1d, AArch64::dsub0);
return;
} else if (VT == MVT::v2i64 || VT == MVT::v2f64) {
SelectLoad(Node, 3, AArch64::LD3Rv2d, AArch64::qsub0);
return;
}
break;
case Intrinsic::aarch64_neon_ld4r:
if (VT == MVT::v8i8) {
SelectLoad(Node, 4, AArch64::LD4Rv8b, AArch64::dsub0);
return;
} else if (VT == MVT::v16i8) {
SelectLoad(Node, 4, AArch64::LD4Rv16b, AArch64::qsub0);
return;
} else if (VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v4bf16) {
SelectLoad(Node, 4, AArch64::LD4Rv4h, AArch64::dsub0);
return;
} else if (VT == MVT::v8i16 || VT == MVT::v8f16 || VT == MVT::v8bf16) {
SelectLoad(Node, 4, AArch64::LD4Rv8h, AArch64::qsub0);
return;
} else if (VT == MVT::v2i32 || VT == MVT::v2f32) {
SelectLoad(Node, 4, AArch64::LD4Rv2s, AArch64::dsub0);
return;
} else if (VT == MVT::v4i32 || VT == MVT::v4f32) {
SelectLoad(Node, 4, AArch64::LD4Rv4s, AArch64::qsub0);
return;
} else if (VT == MVT::v1i64 || VT == MVT::v1f64) {
SelectLoad(Node, 4, AArch64::LD4Rv1d, AArch64::dsub0);
return;
} else if (VT == MVT::v2i64 || VT == MVT::v2f64) {
SelectLoad(Node, 4, AArch64::LD4Rv2d, AArch64::qsub0);
return;
}
break;
case Intrinsic::aarch64_neon_ld2lane:
if (VT == MVT::v16i8 || VT == MVT::v8i8) {
SelectLoadLane(Node, 2, AArch64::LD2i8);
return;
} else if (VT == MVT::v8i16 || VT == MVT::v4i16 || VT == MVT::v4f16 ||
VT == MVT::v8f16 || VT == MVT::v4bf16 || VT == MVT::v8bf16) {
SelectLoadLane(Node, 2, AArch64::LD2i16);
return;
} else if (VT == MVT::v4i32 || VT == MVT::v2i32 || VT == MVT::v4f32 ||
VT == MVT::v2f32) {
SelectLoadLane(Node, 2, AArch64::LD2i32);
return;
} else if (VT == MVT::v2i64 || VT == MVT::v1i64 || VT == MVT::v2f64 ||
VT == MVT::v1f64) {
SelectLoadLane(Node, 2, AArch64::LD2i64);
return;
}
break;
case Intrinsic::aarch64_neon_ld3lane:
if (VT == MVT::v16i8 || VT == MVT::v8i8) {
SelectLoadLane(Node, 3, AArch64::LD3i8);
return;
} else if (VT == MVT::v8i16 || VT == MVT::v4i16 || VT == MVT::v4f16 ||
VT == MVT::v8f16 || VT == MVT::v4bf16 || VT == MVT::v8bf16) {
SelectLoadLane(Node, 3, AArch64::LD3i16);
return;
} else if (VT == MVT::v4i32 || VT == MVT::v2i32 || VT == MVT::v4f32 ||
VT == MVT::v2f32) {
SelectLoadLane(Node, 3, AArch64::LD3i32);
return;
} else if (VT == MVT::v2i64 || VT == MVT::v1i64 || VT == MVT::v2f64 ||
VT == MVT::v1f64) {
SelectLoadLane(Node, 3, AArch64::LD3i64);
return;
}
break;
case Intrinsic::aarch64_neon_ld4lane:
if (VT == MVT::v16i8 || VT == MVT::v8i8) {
SelectLoadLane(Node, 4, AArch64::LD4i8);
return;
} else if (VT == MVT::v8i16 || VT == MVT::v4i16 || VT == MVT::v4f16 ||
VT == MVT::v8f16 || VT == MVT::v4bf16 || VT == MVT::v8bf16) {
SelectLoadLane(Node, 4, AArch64::LD4i16);
return;
} else if (VT == MVT::v4i32 || VT == MVT::v2i32 || VT == MVT::v4f32 ||
VT == MVT::v2f32) {
SelectLoadLane(Node, 4, AArch64::LD4i32);
return;
} else if (VT == MVT::v2i64 || VT == MVT::v1i64 || VT == MVT::v2f64 ||
VT == MVT::v1f64) {
SelectLoadLane(Node, 4, AArch64::LD4i64);
return;
}
break;
case Intrinsic::aarch64_ld64b:
SelectLoad(Node, 8, AArch64::LD64B, AArch64::x8sub_0);
return;
}
} break;
case ISD::INTRINSIC_WO_CHAIN: {
unsigned IntNo = cast<ConstantSDNode>(Node->getOperand(0))->getZExtValue();
switch (IntNo) {
default:
break;
case Intrinsic::aarch64_tagp:
SelectTagP(Node);
return;
case Intrinsic::aarch64_neon_tbl2:
SelectTable(Node, 2,
VT == MVT::v8i8 ? AArch64::TBLv8i8Two : AArch64::TBLv16i8Two,
false);
return;
case Intrinsic::aarch64_neon_tbl3:
SelectTable(Node, 3, VT == MVT::v8i8 ? AArch64::TBLv8i8Three
: AArch64::TBLv16i8Three,
false);
return;
case Intrinsic::aarch64_neon_tbl4:
SelectTable(Node, 4, VT == MVT::v8i8 ? AArch64::TBLv8i8Four
: AArch64::TBLv16i8Four,
false);
return;
case Intrinsic::aarch64_neon_tbx2:
SelectTable(Node, 2,
VT == MVT::v8i8 ? AArch64::TBXv8i8Two : AArch64::TBXv16i8Two,
true);
return;
case Intrinsic::aarch64_neon_tbx3:
SelectTable(Node, 3, VT == MVT::v8i8 ? AArch64::TBXv8i8Three
: AArch64::TBXv16i8Three,
true);
return;
case Intrinsic::aarch64_neon_tbx4:
SelectTable(Node, 4, VT == MVT::v8i8 ? AArch64::TBXv8i8Four
: AArch64::TBXv16i8Four,
true);
return;
case Intrinsic::aarch64_neon_smull:
case Intrinsic::aarch64_neon_umull:
if (tryMULLV64LaneV128(IntNo, Node))
return;
break;
}
break;
}
case ISD::INTRINSIC_VOID: {
unsigned IntNo = cast<ConstantSDNode>(Node->getOperand(1))->getZExtValue();
if (Node->getNumOperands() >= 3)
VT = Node->getOperand(2)->getValueType(0);
switch (IntNo) {
default:
break;
case Intrinsic::aarch64_neon_st1x2: {
if (VT == MVT::v8i8) {
SelectStore(Node, 2, AArch64::ST1Twov8b);
return;
} else if (VT == MVT::v16i8) {
SelectStore(Node, 2, AArch64::ST1Twov16b);
return;
} else if (VT == MVT::v4i16 || VT == MVT::v4f16 ||
VT == MVT::v4bf16) {
SelectStore(Node, 2, AArch64::ST1Twov4h);
return;
} else if (VT == MVT::v8i16 || VT == MVT::v8f16 ||
VT == MVT::v8bf16) {
SelectStore(Node, 2, AArch64::ST1Twov8h);
return;
} else if (VT == MVT::v2i32 || VT == MVT::v2f32) {
SelectStore(Node, 2, AArch64::ST1Twov2s);
return;
} else if (VT == MVT::v4i32 || VT == MVT::v4f32) {
SelectStore(Node, 2, AArch64::ST1Twov4s);
return;
} else if (VT == MVT::v2i64 || VT == MVT::v2f64) {
SelectStore(Node, 2, AArch64::ST1Twov2d);
return;
} else if (VT == MVT::v1i64 || VT == MVT::v1f64) {
SelectStore(Node, 2, AArch64::ST1Twov1d);
return;
}
break;
}
case Intrinsic::aarch64_neon_st1x3: {
if (VT == MVT::v8i8) {
SelectStore(Node, 3, AArch64::ST1Threev8b);
return;
} else if (VT == MVT::v16i8) {
SelectStore(Node, 3, AArch64::ST1Threev16b);
return;
} else if (VT == MVT::v4i16 || VT == MVT::v4f16 ||
VT == MVT::v4bf16) {
SelectStore(Node, 3, AArch64::ST1Threev4h);
return;
} else if (VT == MVT::v8i16 || VT == MVT::v8f16 ||
VT == MVT::v8bf16) {
SelectStore(Node, 3, AArch64::ST1Threev8h);
return;
} else if (VT == MVT::v2i32 || VT == MVT::v2f32) {
SelectStore(Node, 3, AArch64::ST1Threev2s);
return;
} else if (VT == MVT::v4i32 || VT == MVT::v4f32) {
SelectStore(Node, 3, AArch64::ST1Threev4s);
return;
} else if (VT == MVT::v2i64 || VT == MVT::v2f64) {
SelectStore(Node, 3, AArch64::ST1Threev2d);
return;
} else if (VT == MVT::v1i64 || VT == MVT::v1f64) {
SelectStore(Node, 3, AArch64::ST1Threev1d);
return;
}
break;
}
case Intrinsic::aarch64_neon_st1x4: {
if (VT == MVT::v8i8) {
SelectStore(Node, 4, AArch64::ST1Fourv8b);
return;
} else if (VT == MVT::v16i8) {
SelectStore(Node, 4, AArch64::ST1Fourv16b);
return;
} else if (VT == MVT::v4i16 || VT == MVT::v4f16 ||
VT == MVT::v4bf16) {
SelectStore(Node, 4, AArch64::ST1Fourv4h);
return;
} else if (VT == MVT::v8i16 || VT == MVT::v8f16 ||
VT == MVT::v8bf16) {
SelectStore(Node, 4, AArch64::ST1Fourv8h);
return;
} else if (VT == MVT::v2i32 || VT == MVT::v2f32) {
SelectStore(Node, 4, AArch64::ST1Fourv2s);
return;
} else if (VT == MVT::v4i32 || VT == MVT::v4f32) {
SelectStore(Node, 4, AArch64::ST1Fourv4s);
return;
} else if (VT == MVT::v2i64 || VT == MVT::v2f64) {
SelectStore(Node, 4, AArch64::ST1Fourv2d);
return;
} else if (VT == MVT::v1i64 || VT == MVT::v1f64) {
SelectStore(Node, 4, AArch64::ST1Fourv1d);
return;
}
break;
}
case Intrinsic::aarch64_neon_st2: {
if (VT == MVT::v8i8) {
SelectStore(Node, 2, AArch64::ST2Twov8b);
return;
} else if (VT == MVT::v16i8) {
SelectStore(Node, 2, AArch64::ST2Twov16b);
return;
} else if (VT == MVT::v4i16 || VT == MVT::v4f16 ||
VT == MVT::v4bf16) {
SelectStore(Node, 2, AArch64::ST2Twov4h);
return;
} else if (VT == MVT::v8i16 || VT == MVT::v8f16 ||
VT == MVT::v8bf16) {
SelectStore(Node, 2, AArch64::ST2Twov8h);
return;
} else if (VT == MVT::v2i32 || VT == MVT::v2f32) {
SelectStore(Node, 2, AArch64::ST2Twov2s);
return;
} else if (VT == MVT::v4i32 || VT == MVT::v4f32) {
SelectStore(Node, 2, AArch64::ST2Twov4s);
return;
} else if (VT == MVT::v2i64 || VT == MVT::v2f64) {
SelectStore(Node, 2, AArch64::ST2Twov2d);
return;
} else if (VT == MVT::v1i64 || VT == MVT::v1f64) {
SelectStore(Node, 2, AArch64::ST1Twov1d);
return;
}
break;
}
case Intrinsic::aarch64_neon_st3: {
if (VT == MVT::v8i8) {
SelectStore(Node, 3, AArch64::ST3Threev8b);
return;
} else if (VT == MVT::v16i8) {
SelectStore(Node, 3, AArch64::ST3Threev16b);
return;
} else if (VT == MVT::v4i16 || VT == MVT::v4f16 ||
VT == MVT::v4bf16) {
SelectStore(Node, 3, AArch64::ST3Threev4h);
return;
} else if (VT == MVT::v8i16 || VT == MVT::v8f16 ||
VT == MVT::v8bf16) {
SelectStore(Node, 3, AArch64::ST3Threev8h);
return;
} else if (VT == MVT::v2i32 || VT == MVT::v2f32) {
SelectStore(Node, 3, AArch64::ST3Threev2s);
return;
} else if (VT == MVT::v4i32 || VT == MVT::v4f32) {
SelectStore(Node, 3, AArch64::ST3Threev4s);
return;
} else if (VT == MVT::v2i64 || VT == MVT::v2f64) {
SelectStore(Node, 3, AArch64::ST3Threev2d);
return;
} else if (VT == MVT::v1i64 || VT == MVT::v1f64) {
SelectStore(Node, 3, AArch64::ST1Threev1d);
return;
}
break;
}
case Intrinsic::aarch64_neon_st4: {
if (VT == MVT::v8i8) {
SelectStore(Node, 4, AArch64::ST4Fourv8b);
return;
} else if (VT == MVT::v16i8) {
SelectStore(Node, 4, AArch64::ST4Fourv16b);
return;
} else if (VT == MVT::v4i16 || VT == MVT::v4f16 ||
VT == MVT::v4bf16) {
SelectStore(Node, 4, AArch64::ST4Fourv4h);
return;
} else if (VT == MVT::v8i16 || VT == MVT::v8f16 ||
VT == MVT::v8bf16) {
SelectStore(Node, 4, AArch64::ST4Fourv8h);
return;
} else if (VT == MVT::v2i32 || VT == MVT::v2f32) {
SelectStore(Node, 4, AArch64::ST4Fourv2s);
return;
} else if (VT == MVT::v4i32 || VT == MVT::v4f32) {
SelectStore(Node, 4, AArch64::ST4Fourv4s);
return;
} else if (VT == MVT::v2i64 || VT == MVT::v2f64) {
SelectStore(Node, 4, AArch64::ST4Fourv2d);
return;
} else if (VT == MVT::v1i64 || VT == MVT::v1f64) {
SelectStore(Node, 4, AArch64::ST1Fourv1d);
return;
}
break;
}
case Intrinsic::aarch64_neon_st2lane: {
if (VT == MVT::v16i8 || VT == MVT::v8i8) {
SelectStoreLane(Node, 2, AArch64::ST2i8);
return;
} else if (VT == MVT::v8i16 || VT == MVT::v4i16 || VT == MVT::v4f16 ||
VT == MVT::v8f16 || VT == MVT::v4bf16 || VT == MVT::v8bf16) {
SelectStoreLane(Node, 2, AArch64::ST2i16);
return;
} else if (VT == MVT::v4i32 || VT == MVT::v2i32 || VT == MVT::v4f32 ||
VT == MVT::v2f32) {
SelectStoreLane(Node, 2, AArch64::ST2i32);
return;
} else if (VT == MVT::v2i64 || VT == MVT::v1i64 || VT == MVT::v2f64 ||
VT == MVT::v1f64) {
SelectStoreLane(Node, 2, AArch64::ST2i64);
return;
}
break;
}
case Intrinsic::aarch64_neon_st3lane: {
if (VT == MVT::v16i8 || VT == MVT::v8i8) {
SelectStoreLane(Node, 3, AArch64::ST3i8);
return;
} else if (VT == MVT::v8i16 || VT == MVT::v4i16 || VT == MVT::v4f16 ||
VT == MVT::v8f16 || VT == MVT::v4bf16 || VT == MVT::v8bf16) {
SelectStoreLane(Node, 3, AArch64::ST3i16);
return;
} else if (VT == MVT::v4i32 || VT == MVT::v2i32 || VT == MVT::v4f32 ||
VT == MVT::v2f32) {
SelectStoreLane(Node, 3, AArch64::ST3i32);
return;
} else if (VT == MVT::v2i64 || VT == MVT::v1i64 || VT == MVT::v2f64 ||
VT == MVT::v1f64) {
SelectStoreLane(Node, 3, AArch64::ST3i64);
return;
}
break;
}
case Intrinsic::aarch64_neon_st4lane: {
if (VT == MVT::v16i8 || VT == MVT::v8i8) {
SelectStoreLane(Node, 4, AArch64::ST4i8);
return;
} else if (VT == MVT::v8i16 || VT == MVT::v4i16 || VT == MVT::v4f16 ||
VT == MVT::v8f16 || VT == MVT::v4bf16 || VT == MVT::v8bf16) {
SelectStoreLane(Node, 4, AArch64::ST4i16);
return;
} else if (VT == MVT::v4i32 || VT == MVT::v2i32 || VT == MVT::v4f32 ||
VT == MVT::v2f32) {
SelectStoreLane(Node, 4, AArch64::ST4i32);
return;
} else if (VT == MVT::v2i64 || VT == MVT::v1i64 || VT == MVT::v2f64 ||
VT == MVT::v1f64) {
SelectStoreLane(Node, 4, AArch64::ST4i64);
return;
}
break;
}
case Intrinsic::aarch64_sve_st2: {
if (VT == MVT::nxv16i8) {
SelectPredicatedStore(Node, 2, 0, AArch64::ST2B, AArch64::ST2B_IMM);
return;
} else if (VT == MVT::nxv8i16 || VT == MVT::nxv8f16 ||
(VT == MVT::nxv8bf16 && Subtarget->hasBF16())) {
SelectPredicatedStore(Node, 2, 1, AArch64::ST2H, AArch64::ST2H_IMM);
return;
} else if (VT == MVT::nxv4i32 || VT == MVT::nxv4f32) {
SelectPredicatedStore(Node, 2, 2, AArch64::ST2W, AArch64::ST2W_IMM);
return;
} else if (VT == MVT::nxv2i64 || VT == MVT::nxv2f64) {
SelectPredicatedStore(Node, 2, 3, AArch64::ST2D, AArch64::ST2D_IMM);
return;
}
break;
}
case Intrinsic::aarch64_sve_st3: {
if (VT == MVT::nxv16i8) {
SelectPredicatedStore(Node, 3, 0, AArch64::ST3B, AArch64::ST3B_IMM);
return;
} else if (VT == MVT::nxv8i16 || VT == MVT::nxv8f16 ||
(VT == MVT::nxv8bf16 && Subtarget->hasBF16())) {
SelectPredicatedStore(Node, 3, 1, AArch64::ST3H, AArch64::ST3H_IMM);
return;
} else if (VT == MVT::nxv4i32 || VT == MVT::nxv4f32) {
SelectPredicatedStore(Node, 3, 2, AArch64::ST3W, AArch64::ST3W_IMM);
return;
} else if (VT == MVT::nxv2i64 || VT == MVT::nxv2f64) {
SelectPredicatedStore(Node, 3, 3, AArch64::ST3D, AArch64::ST3D_IMM);
return;
}
break;
}
case Intrinsic::aarch64_sve_st4: {
if (VT == MVT::nxv16i8) {
SelectPredicatedStore(Node, 4, 0, AArch64::ST4B, AArch64::ST4B_IMM);
return;
} else if (VT == MVT::nxv8i16 || VT == MVT::nxv8f16 ||
(VT == MVT::nxv8bf16 && Subtarget->hasBF16())) {
SelectPredicatedStore(Node, 4, 1, AArch64::ST4H, AArch64::ST4H_IMM);
return;
} else if (VT == MVT::nxv4i32 || VT == MVT::nxv4f32) {
SelectPredicatedStore(Node, 4, 2, AArch64::ST4W, AArch64::ST4W_IMM);
return;
} else if (VT == MVT::nxv2i64 || VT == MVT::nxv2f64) {
SelectPredicatedStore(Node, 4, 3, AArch64::ST4D, AArch64::ST4D_IMM);
return;
}
break;
}
}
break;
}
case AArch64ISD::LD2post: {
if (VT == MVT::v8i8) {
SelectPostLoad(Node, 2, AArch64::LD2Twov8b_POST, AArch64::dsub0);
return;
} else if (VT == MVT::v16i8) {
SelectPostLoad(Node, 2, AArch64::LD2Twov16b_POST, AArch64::qsub0);
return;
} else if (VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v4bf16) {
SelectPostLoad(Node, 2, AArch64::LD2Twov4h_POST, AArch64::dsub0);
return;
} else if (VT == MVT::v8i16 || VT == MVT::v8f16 || VT == MVT::v8bf16) {
SelectPostLoad(Node, 2, AArch64::LD2Twov8h_POST, AArch64::qsub0);
return;
} else if (VT == MVT::v2i32 || VT == MVT::v2f32) {
SelectPostLoad(Node, 2, AArch64::LD2Twov2s_POST, AArch64::dsub0);
return;
} else if (VT == MVT::v4i32 || VT == MVT::v4f32) {
SelectPostLoad(Node, 2, AArch64::LD2Twov4s_POST, AArch64::qsub0);
return;
} else if (VT == MVT::v1i64 || VT == MVT::v1f64) {
SelectPostLoad(Node, 2, AArch64::LD1Twov1d_POST, AArch64::dsub0);
return;
} else if (VT == MVT::v2i64 || VT == MVT::v2f64) {
SelectPostLoad(Node, 2, AArch64::LD2Twov2d_POST, AArch64::qsub0);
return;
}
break;
}
case AArch64ISD::LD3post: {
if (VT == MVT::v8i8) {
SelectPostLoad(Node, 3, AArch64::LD3Threev8b_POST, AArch64::dsub0);
return;
} else if (VT == MVT::v16i8) {
SelectPostLoad(Node, 3, AArch64::LD3Threev16b_POST, AArch64::qsub0);
return;
} else if (VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v4bf16) {
SelectPostLoad(Node, 3, AArch64::LD3Threev4h_POST, AArch64::dsub0);
return;
} else if (VT == MVT::v8i16 || VT == MVT::v8f16 || VT == MVT::v8bf16) {
SelectPostLoad(Node, 3, AArch64::LD3Threev8h_POST, AArch64::qsub0);
return;
} else if (VT == MVT::v2i32 || VT == MVT::v2f32) {
SelectPostLoad(Node, 3, AArch64::LD3Threev2s_POST, AArch64::dsub0);
return;
} else if (VT == MVT::v4i32 || VT == MVT::v4f32) {
SelectPostLoad(Node, 3, AArch64::LD3Threev4s_POST, AArch64::qsub0);
return;
} else if (VT == MVT::v1i64 || VT == MVT::v1f64) {
SelectPostLoad(Node, 3, AArch64::LD1Threev1d_POST, AArch64::dsub0);
return;
} else if (VT == MVT::v2i64 || VT == MVT::v2f64) {
SelectPostLoad(Node, 3, AArch64::LD3Threev2d_POST, AArch64::qsub0);
return;
}
break;
}
case AArch64ISD::LD4post: {
if (VT == MVT::v8i8) {
SelectPostLoad(Node, 4, AArch64::LD4Fourv8b_POST, AArch64::dsub0);
return;
} else if (VT == MVT::v16i8) {
SelectPostLoad(Node, 4, AArch64::LD4Fourv16b_POST, AArch64::qsub0);
return;
} else if (VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v4bf16) {
SelectPostLoad(Node, 4, AArch64::LD4Fourv4h_POST, AArch64::dsub0);
return;
} else if (VT == MVT::v8i16 || VT == MVT::v8f16 || VT == MVT::v8bf16) {
SelectPostLoad(Node, 4, AArch64::LD4Fourv8h_POST, AArch64::qsub0);
return;
} else if (VT == MVT::v2i32 || VT == MVT::v2f32) {
SelectPostLoad(Node, 4, AArch64::LD4Fourv2s_POST, AArch64::dsub0);
return;
} else if (VT == MVT::v4i32 || VT == MVT::v4f32) {
SelectPostLoad(Node, 4, AArch64::LD4Fourv4s_POST, AArch64::qsub0);
return;
} else if (VT == MVT::v1i64 || VT == MVT::v1f64) {
SelectPostLoad(Node, 4, AArch64::LD1Fourv1d_POST, AArch64::dsub0);
return;
} else if (VT == MVT::v2i64 || VT == MVT::v2f64) {
SelectPostLoad(Node, 4, AArch64::LD4Fourv2d_POST, AArch64::qsub0);
return;
}
break;
}
case AArch64ISD::LD1x2post: {
if (VT == MVT::v8i8) {
SelectPostLoad(Node, 2, AArch64::LD1Twov8b_POST, AArch64::dsub0);
return;
} else if (VT == MVT::v16i8) {
SelectPostLoad(Node, 2, AArch64::LD1Twov16b_POST, AArch64::qsub0);
return;
} else if (VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v4bf16) {
SelectPostLoad(Node, 2, AArch64::LD1Twov4h_POST, AArch64::dsub0);
return;
} else if (VT == MVT::v8i16 || VT == MVT::v8f16 || VT == MVT::v8bf16) {
SelectPostLoad(Node, 2, AArch64::LD1Twov8h_POST, AArch64::qsub0);
return;
} else if (VT == MVT::v2i32 || VT == MVT::v2f32) {
SelectPostLoad(Node, 2, AArch64::LD1Twov2s_POST, AArch64::dsub0);
return;
} else if (VT == MVT::v4i32 || VT == MVT::v4f32) {
SelectPostLoad(Node, 2, AArch64::LD1Twov4s_POST, AArch64::qsub0);
return;
} else if (VT == MVT::v1i64 || VT == MVT::v1f64) {
SelectPostLoad(Node, 2, AArch64::LD1Twov1d_POST, AArch64::dsub0);
return;
} else if (VT == MVT::v2i64 || VT == MVT::v2f64) {
SelectPostLoad(Node, 2, AArch64::LD1Twov2d_POST, AArch64::qsub0);
return;
}
break;
}
case AArch64ISD::LD1x3post: {
if (VT == MVT::v8i8) {
SelectPostLoad(Node, 3, AArch64::LD1Threev8b_POST, AArch64::dsub0);
return;
} else if (VT == MVT::v16i8) {
SelectPostLoad(Node, 3, AArch64::LD1Threev16b_POST, AArch64::qsub0);
return;
} else if (VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v4bf16) {
SelectPostLoad(Node, 3, AArch64::LD1Threev4h_POST, AArch64::dsub0);
return;
} else if (VT == MVT::v8i16 || VT == MVT::v8f16 || VT == MVT::v8bf16) {
SelectPostLoad(Node, 3, AArch64::LD1Threev8h_POST, AArch64::qsub0);
return;
} else if (VT == MVT::v2i32 || VT == MVT::v2f32) {
SelectPostLoad(Node, 3, AArch64::LD1Threev2s_POST, AArch64::dsub0);
return;
} else if (VT == MVT::v4i32 || VT == MVT::v4f32) {
SelectPostLoad(Node, 3, AArch64::LD1Threev4s_POST, AArch64::qsub0);
return;
} else if (VT == MVT::v1i64 || VT == MVT::v1f64) {
SelectPostLoad(Node, 3, AArch64::LD1Threev1d_POST, AArch64::dsub0);
return;
} else if (VT == MVT::v2i64 || VT == MVT::v2f64) {
SelectPostLoad(Node, 3, AArch64::LD1Threev2d_POST, AArch64::qsub0);
return;
}
break;
}
case AArch64ISD::LD1x4post: {
if (VT == MVT::v8i8) {
SelectPostLoad(Node, 4, AArch64::LD1Fourv8b_POST, AArch64::dsub0);
return;
} else if (VT == MVT::v16i8) {
SelectPostLoad(Node, 4, AArch64::LD1Fourv16b_POST, AArch64::qsub0);
return;
} else if (VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v4bf16) {
SelectPostLoad(Node, 4, AArch64::LD1Fourv4h_POST, AArch64::dsub0);
return;
} else if (VT == MVT::v8i16 || VT == MVT::v8f16 || VT == MVT::v8bf16) {
SelectPostLoad(Node, 4, AArch64::LD1Fourv8h_POST, AArch64::qsub0);
return;
} else if (VT == MVT::v2i32 || VT == MVT::v2f32) {
SelectPostLoad(Node, 4, AArch64::LD1Fourv2s_POST, AArch64::dsub0);
return;
} else if (VT == MVT::v4i32 || VT == MVT::v4f32) {
SelectPostLoad(Node, 4, AArch64::LD1Fourv4s_POST, AArch64::qsub0);
return;
} else if (VT == MVT::v1i64 || VT == MVT::v1f64) {
SelectPostLoad(Node, 4, AArch64::LD1Fourv1d_POST, AArch64::dsub0);
return;
} else if (VT == MVT::v2i64 || VT == MVT::v2f64) {
SelectPostLoad(Node, 4, AArch64::LD1Fourv2d_POST, AArch64::qsub0);
return;
}
break;
}
case AArch64ISD::LD1DUPpost: {
if (VT == MVT::v8i8) {
SelectPostLoad(Node, 1, AArch64::LD1Rv8b_POST, AArch64::dsub0);
return;
} else if (VT == MVT::v16i8) {
SelectPostLoad(Node, 1, AArch64::LD1Rv16b_POST, AArch64::qsub0);
return;
} else if (VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v4bf16) {
SelectPostLoad(Node, 1, AArch64::LD1Rv4h_POST, AArch64::dsub0);
return;
} else if (VT == MVT::v8i16 || VT == MVT::v8f16 || VT == MVT::v8bf16) {
SelectPostLoad(Node, 1, AArch64::LD1Rv8h_POST, AArch64::qsub0);
return;
} else if (VT == MVT::v2i32 || VT == MVT::v2f32) {
SelectPostLoad(Node, 1, AArch64::LD1Rv2s_POST, AArch64::dsub0);
return;
} else if (VT == MVT::v4i32 || VT == MVT::v4f32) {
SelectPostLoad(Node, 1, AArch64::LD1Rv4s_POST, AArch64::qsub0);
return;
} else if (VT == MVT::v1i64 || VT == MVT::v1f64) {
SelectPostLoad(Node, 1, AArch64::LD1Rv1d_POST, AArch64::dsub0);
return;
} else if (VT == MVT::v2i64 || VT == MVT::v2f64) {
SelectPostLoad(Node, 1, AArch64::LD1Rv2d_POST, AArch64::qsub0);
return;
}
break;
}
case AArch64ISD::LD2DUPpost: {
if (VT == MVT::v8i8) {
SelectPostLoad(Node, 2, AArch64::LD2Rv8b_POST, AArch64::dsub0);
return;
} else if (VT == MVT::v16i8) {
SelectPostLoad(Node, 2, AArch64::LD2Rv16b_POST, AArch64::qsub0);
return;
} else if (VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v4bf16) {
SelectPostLoad(Node, 2, AArch64::LD2Rv4h_POST, AArch64::dsub0);
return;
} else if (VT == MVT::v8i16 || VT == MVT::v8f16 || VT == MVT::v8bf16) {
SelectPostLoad(Node, 2, AArch64::LD2Rv8h_POST, AArch64::qsub0);
return;
} else if (VT == MVT::v2i32 || VT == MVT::v2f32) {
SelectPostLoad(Node, 2, AArch64::LD2Rv2s_POST, AArch64::dsub0);
return;
} else if (VT == MVT::v4i32 || VT == MVT::v4f32) {
SelectPostLoad(Node, 2, AArch64::LD2Rv4s_POST, AArch64::qsub0);
return;
} else if (VT == MVT::v1i64 || VT == MVT::v1f64) {
SelectPostLoad(Node, 2, AArch64::LD2Rv1d_POST, AArch64::dsub0);
return;
} else if (VT == MVT::v2i64 || VT == MVT::v2f64) {
SelectPostLoad(Node, 2, AArch64::LD2Rv2d_POST, AArch64::qsub0);
return;
}
break;
}
case AArch64ISD::LD3DUPpost: {
if (VT == MVT::v8i8) {
SelectPostLoad(Node, 3, AArch64::LD3Rv8b_POST, AArch64::dsub0);
return;
} else if (VT == MVT::v16i8) {
SelectPostLoad(Node, 3, AArch64::LD3Rv16b_POST, AArch64::qsub0);
return;
} else if (VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v4bf16) {
SelectPostLoad(Node, 3, AArch64::LD3Rv4h_POST, AArch64::dsub0);
return;
} else if (VT == MVT::v8i16 || VT == MVT::v8f16 || VT == MVT::v8bf16) {
SelectPostLoad(Node, 3, AArch64::LD3Rv8h_POST, AArch64::qsub0);
return;
} else if (VT == MVT::v2i32 || VT == MVT::v2f32) {
SelectPostLoad(Node, 3, AArch64::LD3Rv2s_POST, AArch64::dsub0);
return;
} else if (VT == MVT::v4i32 || VT == MVT::v4f32) {
SelectPostLoad(Node, 3, AArch64::LD3Rv4s_POST, AArch64::qsub0);
return;
} else if (VT == MVT::v1i64 || VT == MVT::v1f64) {
SelectPostLoad(Node, 3, AArch64::LD3Rv1d_POST, AArch64::dsub0);
return;
} else if (VT == MVT::v2i64 || VT == MVT::v2f64) {
SelectPostLoad(Node, 3, AArch64::LD3Rv2d_POST, AArch64::qsub0);
return;
}
break;
}
case AArch64ISD::LD4DUPpost: {
if (VT == MVT::v8i8) {
SelectPostLoad(Node, 4, AArch64::LD4Rv8b_POST, AArch64::dsub0);
return;
} else if (VT == MVT::v16i8) {
SelectPostLoad(Node, 4, AArch64::LD4Rv16b_POST, AArch64::qsub0);
return;
} else if (VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v4bf16) {
SelectPostLoad(Node, 4, AArch64::LD4Rv4h_POST, AArch64::dsub0);
return;
} else if (VT == MVT::v8i16 || VT == MVT::v8f16 || VT == MVT::v8bf16) {
SelectPostLoad(Node, 4, AArch64::LD4Rv8h_POST, AArch64::qsub0);
return;
} else if (VT == MVT::v2i32 || VT == MVT::v2f32) {
SelectPostLoad(Node, 4, AArch64::LD4Rv2s_POST, AArch64::dsub0);
return;
} else if (VT == MVT::v4i32 || VT == MVT::v4f32) {
SelectPostLoad(Node, 4, AArch64::LD4Rv4s_POST, AArch64::qsub0);
return;
} else if (VT == MVT::v1i64 || VT == MVT::v1f64) {
SelectPostLoad(Node, 4, AArch64::LD4Rv1d_POST, AArch64::dsub0);
return;
} else if (VT == MVT::v2i64 || VT == MVT::v2f64) {
SelectPostLoad(Node, 4, AArch64::LD4Rv2d_POST, AArch64::qsub0);
return;
}
break;
}
case AArch64ISD::LD1LANEpost: {
if (VT == MVT::v16i8 || VT == MVT::v8i8) {
SelectPostLoadLane(Node, 1, AArch64::LD1i8_POST);
return;
} else if (VT == MVT::v8i16 || VT == MVT::v4i16 || VT == MVT::v4f16 ||
VT == MVT::v8f16 || VT == MVT::v4bf16 || VT == MVT::v8bf16) {
SelectPostLoadLane(Node, 1, AArch64::LD1i16_POST);
return;
} else if (VT == MVT::v4i32 || VT == MVT::v2i32 || VT == MVT::v4f32 ||
VT == MVT::v2f32) {
SelectPostLoadLane(Node, 1, AArch64::LD1i32_POST);
return;
} else if (VT == MVT::v2i64 || VT == MVT::v1i64 || VT == MVT::v2f64 ||
VT == MVT::v1f64) {
SelectPostLoadLane(Node, 1, AArch64::LD1i64_POST);
return;
}
break;
}
case AArch64ISD::LD2LANEpost: {
if (VT == MVT::v16i8 || VT == MVT::v8i8) {
SelectPostLoadLane(Node, 2, AArch64::LD2i8_POST);
return;
} else if (VT == MVT::v8i16 || VT == MVT::v4i16 || VT == MVT::v4f16 ||
VT == MVT::v8f16 || VT == MVT::v4bf16 || VT == MVT::v8bf16) {
SelectPostLoadLane(Node, 2, AArch64::LD2i16_POST);
return;
} else if (VT == MVT::v4i32 || VT == MVT::v2i32 || VT == MVT::v4f32 ||
VT == MVT::v2f32) {
SelectPostLoadLane(Node, 2, AArch64::LD2i32_POST);
return;
} else if (VT == MVT::v2i64 || VT == MVT::v1i64 || VT == MVT::v2f64 ||
VT == MVT::v1f64) {
SelectPostLoadLane(Node, 2, AArch64::LD2i64_POST);
return;
}
break;
}
case AArch64ISD::LD3LANEpost: {
if (VT == MVT::v16i8 || VT == MVT::v8i8) {
SelectPostLoadLane(Node, 3, AArch64::LD3i8_POST);
return;
} else if (VT == MVT::v8i16 || VT == MVT::v4i16 || VT == MVT::v4f16 ||
VT == MVT::v8f16 || VT == MVT::v4bf16 || VT == MVT::v8bf16) {
SelectPostLoadLane(Node, 3, AArch64::LD3i16_POST);
return;
} else if (VT == MVT::v4i32 || VT == MVT::v2i32 || VT == MVT::v4f32 ||
VT == MVT::v2f32) {
SelectPostLoadLane(Node, 3, AArch64::LD3i32_POST);
return;
} else if (VT == MVT::v2i64 || VT == MVT::v1i64 || VT == MVT::v2f64 ||
VT == MVT::v1f64) {
SelectPostLoadLane(Node, 3, AArch64::LD3i64_POST);
return;
}
break;
}
case AArch64ISD::LD4LANEpost: {
if (VT == MVT::v16i8 || VT == MVT::v8i8) {
SelectPostLoadLane(Node, 4, AArch64::LD4i8_POST);
return;
} else if (VT == MVT::v8i16 || VT == MVT::v4i16 || VT == MVT::v4f16 ||
VT == MVT::v8f16 || VT == MVT::v4bf16 || VT == MVT::v8bf16) {
SelectPostLoadLane(Node, 4, AArch64::LD4i16_POST);
return;
} else if (VT == MVT::v4i32 || VT == MVT::v2i32 || VT == MVT::v4f32 ||
VT == MVT::v2f32) {
SelectPostLoadLane(Node, 4, AArch64::LD4i32_POST);
return;
} else if (VT == MVT::v2i64 || VT == MVT::v1i64 || VT == MVT::v2f64 ||
VT == MVT::v1f64) {
SelectPostLoadLane(Node, 4, AArch64::LD4i64_POST);
return;
}
break;
}
case AArch64ISD::ST2post: {
VT = Node->getOperand(1).getValueType();
if (VT == MVT::v8i8) {
SelectPostStore(Node, 2, AArch64::ST2Twov8b_POST);
return;
} else if (VT == MVT::v16i8) {
SelectPostStore(Node, 2, AArch64::ST2Twov16b_POST);
return;
} else if (VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v4bf16) {
SelectPostStore(Node, 2, AArch64::ST2Twov4h_POST);
return;
} else if (VT == MVT::v8i16 || VT == MVT::v8f16 || VT == MVT::v8bf16) {
SelectPostStore(Node, 2, AArch64::ST2Twov8h_POST);
return;
} else if (VT == MVT::v2i32 || VT == MVT::v2f32) {
SelectPostStore(Node, 2, AArch64::ST2Twov2s_POST);
return;
} else if (VT == MVT::v4i32 || VT == MVT::v4f32) {
SelectPostStore(Node, 2, AArch64::ST2Twov4s_POST);
return;
} else if (VT == MVT::v2i64 || VT == MVT::v2f64) {
SelectPostStore(Node, 2, AArch64::ST2Twov2d_POST);
return;
} else if (VT == MVT::v1i64 || VT == MVT::v1f64) {
SelectPostStore(Node, 2, AArch64::ST1Twov1d_POST);
return;
}
break;
}
case AArch64ISD::ST3post: {
VT = Node->getOperand(1).getValueType();
if (VT == MVT::v8i8) {
SelectPostStore(Node, 3, AArch64::ST3Threev8b_POST);
return;
} else if (VT == MVT::v16i8) {
SelectPostStore(Node, 3, AArch64::ST3Threev16b_POST);
return;
} else if (VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v4bf16) {
SelectPostStore(Node, 3, AArch64::ST3Threev4h_POST);
return;
} else if (VT == MVT::v8i16 || VT == MVT::v8f16 || VT == MVT::v8bf16) {
SelectPostStore(Node, 3, AArch64::ST3Threev8h_POST);
return;
} else if (VT == MVT::v2i32 || VT == MVT::v2f32) {
SelectPostStore(Node, 3, AArch64::ST3Threev2s_POST);
return;
} else if (VT == MVT::v4i32 || VT == MVT::v4f32) {
SelectPostStore(Node, 3, AArch64::ST3Threev4s_POST);
return;
} else if (VT == MVT::v2i64 || VT == MVT::v2f64) {
SelectPostStore(Node, 3, AArch64::ST3Threev2d_POST);
return;
} else if (VT == MVT::v1i64 || VT == MVT::v1f64) {
SelectPostStore(Node, 3, AArch64::ST1Threev1d_POST);
return;
}
break;
}
case AArch64ISD::ST4post: {
VT = Node->getOperand(1).getValueType();
if (VT == MVT::v8i8) {
SelectPostStore(Node, 4, AArch64::ST4Fourv8b_POST);
return;
} else if (VT == MVT::v16i8) {
SelectPostStore(Node, 4, AArch64::ST4Fourv16b_POST);
return;
} else if (VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v4bf16) {
SelectPostStore(Node, 4, AArch64::ST4Fourv4h_POST);
return;
} else if (VT == MVT::v8i16 || VT == MVT::v8f16 || VT == MVT::v8bf16) {
SelectPostStore(Node, 4, AArch64::ST4Fourv8h_POST);
return;
} else if (VT == MVT::v2i32 || VT == MVT::v2f32) {
SelectPostStore(Node, 4, AArch64::ST4Fourv2s_POST);
return;
} else if (VT == MVT::v4i32 || VT == MVT::v4f32) {
SelectPostStore(Node, 4, AArch64::ST4Fourv4s_POST);
return;
} else if (VT == MVT::v2i64 || VT == MVT::v2f64) {
SelectPostStore(Node, 4, AArch64::ST4Fourv2d_POST);
return;
} else if (VT == MVT::v1i64 || VT == MVT::v1f64) {
SelectPostStore(Node, 4, AArch64::ST1Fourv1d_POST);
return;
}
break;
}
case AArch64ISD::ST1x2post: {
VT = Node->getOperand(1).getValueType();
if (VT == MVT::v8i8) {
SelectPostStore(Node, 2, AArch64::ST1Twov8b_POST);
return;
} else if (VT == MVT::v16i8) {
SelectPostStore(Node, 2, AArch64::ST1Twov16b_POST);
return;
} else if (VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v4bf16) {
SelectPostStore(Node, 2, AArch64::ST1Twov4h_POST);
return;
} else if (VT == MVT::v8i16 || VT == MVT::v8f16 || VT == MVT::v8bf16) {
SelectPostStore(Node, 2, AArch64::ST1Twov8h_POST);
return;
} else if (VT == MVT::v2i32 || VT == MVT::v2f32) {
SelectPostStore(Node, 2, AArch64::ST1Twov2s_POST);
return;
} else if (VT == MVT::v4i32 || VT == MVT::v4f32) {
SelectPostStore(Node, 2, AArch64::ST1Twov4s_POST);
return;
} else if (VT == MVT::v1i64 || VT == MVT::v1f64) {
SelectPostStore(Node, 2, AArch64::ST1Twov1d_POST);
return;
} else if (VT == MVT::v2i64 || VT == MVT::v2f64) {
SelectPostStore(Node, 2, AArch64::ST1Twov2d_POST);
return;
}
break;
}
case AArch64ISD::ST1x3post: {
VT = Node->getOperand(1).getValueType();
if (VT == MVT::v8i8) {
SelectPostStore(Node, 3, AArch64::ST1Threev8b_POST);
return;
} else if (VT == MVT::v16i8) {
SelectPostStore(Node, 3, AArch64::ST1Threev16b_POST);
return;
} else if (VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v4bf16) {
SelectPostStore(Node, 3, AArch64::ST1Threev4h_POST);
return;
} else if (VT == MVT::v8i16 || VT == MVT::v8f16 || VT == MVT::v8bf16 ) {
SelectPostStore(Node, 3, AArch64::ST1Threev8h_POST);
return;
} else if (VT == MVT::v2i32 || VT == MVT::v2f32) {
SelectPostStore(Node, 3, AArch64::ST1Threev2s_POST);
return;
} else if (VT == MVT::v4i32 || VT == MVT::v4f32) {
SelectPostStore(Node, 3, AArch64::ST1Threev4s_POST);
return;
} else if (VT == MVT::v1i64 || VT == MVT::v1f64) {
SelectPostStore(Node, 3, AArch64::ST1Threev1d_POST);
return;
} else if (VT == MVT::v2i64 || VT == MVT::v2f64) {
SelectPostStore(Node, 3, AArch64::ST1Threev2d_POST);
return;
}
break;
}
case AArch64ISD::ST1x4post: {
VT = Node->getOperand(1).getValueType();
if (VT == MVT::v8i8) {
SelectPostStore(Node, 4, AArch64::ST1Fourv8b_POST);
return;
} else if (VT == MVT::v16i8) {
SelectPostStore(Node, 4, AArch64::ST1Fourv16b_POST);
return;
} else if (VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v4bf16) {
SelectPostStore(Node, 4, AArch64::ST1Fourv4h_POST);
return;
} else if (VT == MVT::v8i16 || VT == MVT::v8f16 || VT == MVT::v8bf16) {
SelectPostStore(Node, 4, AArch64::ST1Fourv8h_POST);
return;
} else if (VT == MVT::v2i32 || VT == MVT::v2f32) {
SelectPostStore(Node, 4, AArch64::ST1Fourv2s_POST);
return;
} else if (VT == MVT::v4i32 || VT == MVT::v4f32) {
SelectPostStore(Node, 4, AArch64::ST1Fourv4s_POST);
return;
} else if (VT == MVT::v1i64 || VT == MVT::v1f64) {
SelectPostStore(Node, 4, AArch64::ST1Fourv1d_POST);
return;
} else if (VT == MVT::v2i64 || VT == MVT::v2f64) {
SelectPostStore(Node, 4, AArch64::ST1Fourv2d_POST);
return;
}
break;
}
case AArch64ISD::ST2LANEpost: {
VT = Node->getOperand(1).getValueType();
if (VT == MVT::v16i8 || VT == MVT::v8i8) {
SelectPostStoreLane(Node, 2, AArch64::ST2i8_POST);
return;
} else if (VT == MVT::v8i16 || VT == MVT::v4i16 || VT == MVT::v4f16 ||
VT == MVT::v8f16 || VT == MVT::v4bf16 || VT == MVT::v8bf16) {
SelectPostStoreLane(Node, 2, AArch64::ST2i16_POST);
return;
} else if (VT == MVT::v4i32 || VT == MVT::v2i32 || VT == MVT::v4f32 ||
VT == MVT::v2f32) {
SelectPostStoreLane(Node, 2, AArch64::ST2i32_POST);
return;
} else if (VT == MVT::v2i64 || VT == MVT::v1i64 || VT == MVT::v2f64 ||
VT == MVT::v1f64) {
SelectPostStoreLane(Node, 2, AArch64::ST2i64_POST);
return;
}
break;
}
case AArch64ISD::ST3LANEpost: {
VT = Node->getOperand(1).getValueType();
if (VT == MVT::v16i8 || VT == MVT::v8i8) {
SelectPostStoreLane(Node, 3, AArch64::ST3i8_POST);
return;
} else if (VT == MVT::v8i16 || VT == MVT::v4i16 || VT == MVT::v4f16 ||
VT == MVT::v8f16 || VT == MVT::v4bf16 || VT == MVT::v8bf16) {
SelectPostStoreLane(Node, 3, AArch64::ST3i16_POST);
return;
} else if (VT == MVT::v4i32 || VT == MVT::v2i32 || VT == MVT::v4f32 ||
VT == MVT::v2f32) {
SelectPostStoreLane(Node, 3, AArch64::ST3i32_POST);
return;
} else if (VT == MVT::v2i64 || VT == MVT::v1i64 || VT == MVT::v2f64 ||
VT == MVT::v1f64) {
SelectPostStoreLane(Node, 3, AArch64::ST3i64_POST);
return;
}
break;
}
case AArch64ISD::ST4LANEpost: {
VT = Node->getOperand(1).getValueType();
if (VT == MVT::v16i8 || VT == MVT::v8i8) {
SelectPostStoreLane(Node, 4, AArch64::ST4i8_POST);
return;
} else if (VT == MVT::v8i16 || VT == MVT::v4i16 || VT == MVT::v4f16 ||
VT == MVT::v8f16 || VT == MVT::v4bf16 || VT == MVT::v8bf16) {
SelectPostStoreLane(Node, 4, AArch64::ST4i16_POST);
return;
} else if (VT == MVT::v4i32 || VT == MVT::v2i32 || VT == MVT::v4f32 ||
VT == MVT::v2f32) {
SelectPostStoreLane(Node, 4, AArch64::ST4i32_POST);
return;
} else if (VT == MVT::v2i64 || VT == MVT::v1i64 || VT == MVT::v2f64 ||
VT == MVT::v1f64) {
SelectPostStoreLane(Node, 4, AArch64::ST4i64_POST);
return;
}
break;
}
case AArch64ISD::SVE_LD2_MERGE_ZERO: {
if (VT == MVT::nxv16i8) {
SelectPredicatedLoad(Node, 2, 0, AArch64::LD2B_IMM, AArch64::LD2B);
return;
} else if (VT == MVT::nxv8i16 || VT == MVT::nxv8f16 ||
(VT == MVT::nxv8bf16 && Subtarget->hasBF16())) {
SelectPredicatedLoad(Node, 2, 1, AArch64::LD2H_IMM, AArch64::LD2H);
return;
} else if (VT == MVT::nxv4i32 || VT == MVT::nxv4f32) {
SelectPredicatedLoad(Node, 2, 2, AArch64::LD2W_IMM, AArch64::LD2W);
return;
} else if (VT == MVT::nxv2i64 || VT == MVT::nxv2f64) {
SelectPredicatedLoad(Node, 2, 3, AArch64::LD2D_IMM, AArch64::LD2D);
return;
}
break;
}
case AArch64ISD::SVE_LD3_MERGE_ZERO: {
if (VT == MVT::nxv16i8) {
SelectPredicatedLoad(Node, 3, 0, AArch64::LD3B_IMM, AArch64::LD3B);
return;
} else if (VT == MVT::nxv8i16 || VT == MVT::nxv8f16 ||
(VT == MVT::nxv8bf16 && Subtarget->hasBF16())) {
SelectPredicatedLoad(Node, 3, 1, AArch64::LD3H_IMM, AArch64::LD3H);
return;
} else if (VT == MVT::nxv4i32 || VT == MVT::nxv4f32) {
SelectPredicatedLoad(Node, 3, 2, AArch64::LD3W_IMM, AArch64::LD3W);
return;
} else if (VT == MVT::nxv2i64 || VT == MVT::nxv2f64) {
SelectPredicatedLoad(Node, 3, 3, AArch64::LD3D_IMM, AArch64::LD3D);
return;
}
break;
}
case AArch64ISD::SVE_LD4_MERGE_ZERO: {
if (VT == MVT::nxv16i8) {
SelectPredicatedLoad(Node, 4, 0, AArch64::LD4B_IMM, AArch64::LD4B);
return;
} else if (VT == MVT::nxv8i16 || VT == MVT::nxv8f16 ||
(VT == MVT::nxv8bf16 && Subtarget->hasBF16())) {
SelectPredicatedLoad(Node, 4, 1, AArch64::LD4H_IMM, AArch64::LD4H);
return;
} else if (VT == MVT::nxv4i32 || VT == MVT::nxv4f32) {
SelectPredicatedLoad(Node, 4, 2, AArch64::LD4W_IMM, AArch64::LD4W);
return;
} else if (VT == MVT::nxv2i64 || VT == MVT::nxv2f64) {
SelectPredicatedLoad(Node, 4, 3, AArch64::LD4D_IMM, AArch64::LD4D);
return;
}
break;
}
}
// Select the default instruction
SelectCode(Node);
}
/// createAArch64ISelDag - This pass converts a legalized DAG into a
/// AArch64-specific DAG, ready for instruction scheduling.
FunctionPass *llvm::createAArch64ISelDag(AArch64TargetMachine &TM,
CodeGenOpt::Level OptLevel) {
return new AArch64DAGToDAGISel(TM, OptLevel);
}
/// When \p PredVT is a scalable vector predicate in the form
/// MVT::nx<M>xi1, it builds the correspondent scalable vector of
/// integers MVT::nx<M>xi<bits> s.t. M x bits = 128. When targeting
/// structured vectors (NumVec >1), the output data type is
/// MVT::nx<M*NumVec>xi<bits> s.t. M x bits = 128. If the input
/// PredVT is not in the form MVT::nx<M>xi1, it returns an invalid
/// EVT.
static EVT getPackedVectorTypeFromPredicateType(LLVMContext &Ctx, EVT PredVT,
unsigned NumVec) {
assert(NumVec > 0 && NumVec < 5 && "Invalid number of vectors.");
if (!PredVT.isScalableVector() || PredVT.getVectorElementType() != MVT::i1)
return EVT();
if (PredVT != MVT::nxv16i1 && PredVT != MVT::nxv8i1 &&
PredVT != MVT::nxv4i1 && PredVT != MVT::nxv2i1)
return EVT();
ElementCount EC = PredVT.getVectorElementCount();
EVT ScalarVT =
EVT::getIntegerVT(Ctx, AArch64::SVEBitsPerBlock / EC.getKnownMinValue());
EVT MemVT = EVT::getVectorVT(Ctx, ScalarVT, EC * NumVec);
return MemVT;
}
/// Return the EVT of the data associated to a memory operation in \p
/// Root. If such EVT cannot be retrived, it returns an invalid EVT.
static EVT getMemVTFromNode(LLVMContext &Ctx, SDNode *Root) {
if (isa<MemSDNode>(Root))
return cast<MemSDNode>(Root)->getMemoryVT();
if (isa<MemIntrinsicSDNode>(Root))
return cast<MemIntrinsicSDNode>(Root)->getMemoryVT();
const unsigned Opcode = Root->getOpcode();
// For custom ISD nodes, we have to look at them individually to extract the
// type of the data moved to/from memory.
switch (Opcode) {
case AArch64ISD::LD1_MERGE_ZERO:
case AArch64ISD::LD1S_MERGE_ZERO:
case AArch64ISD::LDNF1_MERGE_ZERO:
case AArch64ISD::LDNF1S_MERGE_ZERO:
return cast<VTSDNode>(Root->getOperand(3))->getVT();
case AArch64ISD::ST1_PRED:
return cast<VTSDNode>(Root->getOperand(4))->getVT();
case AArch64ISD::SVE_LD2_MERGE_ZERO:
return getPackedVectorTypeFromPredicateType(
Ctx, Root->getOperand(1)->getValueType(0), /*NumVec=*/2);
case AArch64ISD::SVE_LD3_MERGE_ZERO:
return getPackedVectorTypeFromPredicateType(
Ctx, Root->getOperand(1)->getValueType(0), /*NumVec=*/3);
case AArch64ISD::SVE_LD4_MERGE_ZERO:
return getPackedVectorTypeFromPredicateType(
Ctx, Root->getOperand(1)->getValueType(0), /*NumVec=*/4);
default:
break;
}
if (Opcode != ISD::INTRINSIC_VOID)
return EVT();
const unsigned IntNo =
cast<ConstantSDNode>(Root->getOperand(1))->getZExtValue();
if (IntNo != Intrinsic::aarch64_sve_prf)
return EVT();
// We are using an SVE prefetch intrinsic. Type must be inferred
// from the width of the predicate.
return getPackedVectorTypeFromPredicateType(
Ctx, Root->getOperand(2)->getValueType(0), /*NumVec=*/1);
}
/// SelectAddrModeIndexedSVE - Attempt selection of the addressing mode:
/// Base + OffImm * sizeof(MemVT) for Min >= OffImm <= Max
/// where Root is the memory access using N for its address.
template <int64_t Min, int64_t Max>
bool AArch64DAGToDAGISel::SelectAddrModeIndexedSVE(SDNode *Root, SDValue N,
SDValue &Base,
SDValue &OffImm) {
const EVT MemVT = getMemVTFromNode(*(CurDAG->getContext()), Root);
if (MemVT == EVT())
return false;
if (N.getOpcode() != ISD::ADD)
return false;
SDValue VScale = N.getOperand(1);
if (VScale.getOpcode() != ISD::VSCALE)
return false;
TypeSize TS = MemVT.getSizeInBits();
int64_t MemWidthBytes = static_cast<int64_t>(TS.getKnownMinSize()) / 8;
int64_t MulImm = cast<ConstantSDNode>(VScale.getOperand(0))->getSExtValue();
if ((MulImm % MemWidthBytes) != 0)
return false;
int64_t Offset = MulImm / MemWidthBytes;
if (Offset < Min || Offset > Max)
return false;
Base = N.getOperand(0);
OffImm = CurDAG->getTargetConstant(Offset, SDLoc(N), MVT::i64);
return true;
}
/// Select register plus register addressing mode for SVE, with scaled
/// offset.
bool AArch64DAGToDAGISel::SelectSVERegRegAddrMode(SDValue N, unsigned Scale,
SDValue &Base,
SDValue &Offset) {
if (N.getOpcode() != ISD::ADD)
return false;
// Process an ADD node.
const SDValue LHS = N.getOperand(0);
const SDValue RHS = N.getOperand(1);
// 8 bit data does not come with the SHL node, so it is treated
// separately.
if (Scale == 0) {
Base = LHS;
Offset = RHS;
return true;
}
// Check if the RHS is a shift node with a constant.
if (RHS.getOpcode() != ISD::SHL)
return false;
const SDValue ShiftRHS = RHS.getOperand(1);
if (auto *C = dyn_cast<ConstantSDNode>(ShiftRHS))
if (C->getZExtValue() == Scale) {
Base = LHS;
Offset = RHS.getOperand(0);
return true;
}
return false;
}
|
#include "GamePCH.h"
#include <xaudio2.h>
#include "AudioController.h"
#include "XAudio2/SoundObject.h"
#include "XAudio2/SoundChannel.h"
#include "XAudio2/VoiceCallback.h"
#include "Helpers/ResourceManager.h"
#include "Events/GameEventTypes.h"
AudioController::AudioController(ResourceManager* pResources)
{
m_pResources = pResources;
m_MusicSampleCount = 1;
m_Musicincrement = 0;
m_PlayBackGroundMusic = true;
CoInitializeEx(NULL, COINIT_MULTITHREADED);
HRESULT result = XAudio2Create(&m_pEngine);
if (result == S_OK)
{
result = m_pEngine->CreateMasteringVoice(&m_pMasteringVoice);
}
if (result != S_OK)
{
OutputMessage("Error initializing XAudio\n");
exit(1);
}
for (unsigned int i = 0; i < MAX_CHANNELS; i++)
{
SoundChannel* aMusicChannel = new SoundChannel(m_pEngine);
SoundChannel* aFXChannel = new SoundChannel(m_pEngine);
m_pMusicChannels.push_back(aMusicChannel);
m_pFXChannels.push_back(aFXChannel);
}
m_pFXChannels.at(0)->SetIsConst(FXType::FX_CONST);
m_pExplosions.push_back(Sounds::Explosion_1);
m_pExplosions.push_back(Sounds::Explosion_2);
m_pExplosions.push_back(Sounds::Explosion_3);
m_pExplosions.push_back(Sounds::Explosion_4);
m_ExplosionIncrement = 0;
}
AudioController::~AudioController()
{
for (unsigned int i = 0; i < MAX_CHANNELS; i++)
{
delete m_pMusicChannels.at(i);
delete m_pFXChannels.at(i);
}
for (auto pSound : m_pSoundFX)
{
delete pSound.second;
}
for (auto pMusic : m_pMusic)
{
delete pMusic.second;
}
delete m_MusicPlayer;
delete m_FXPlayer;
m_pEngine->Release();
CoUninitialize();
}
void AudioController::InitSoundPlayers()
{
m_MusicPlayer = new SoundPlayer(PlayerType::PT_MUSIC, &m_pMusicChannels[0]);
m_FXPlayer = new SoundPlayer(PlayerType::PT_MISC, &m_pFXChannels[0]);
}
void AudioController::OnEvent(Event* pEvent)
{
if (pEvent)
{
SoundEvent* soundEvent = static_cast<SoundEvent*>(pEvent);
if (soundEvent->GetEventType() == GameEventTypes::GameEventType_Sound)
{
Sounds aSound = soundEvent->GetSound();
bool aPriority = soundEvent->GetPriority();
PlaySoundEffect(aSound, aPriority);
}
}
}
void AudioController::PlayBackGroundMusic()
{
if (m_PlayBackGroundMusic)
{
if (m_MusicPlayer->GetSoundChannel(0)->GetState() == SoundChannel::SoundChannelState_Free)
{
if (m_MusicSampleCount < 10)
{
m_MusicPlayer->PlaySound(GetMusicClip(MusicClipOrder(m_MusicSampleCount)), false);
m_MusicSampleCount++;
}
else
{
m_Musicincrement = m_Musicincrement % 5;
m_MusicPlayer->PlaySound(GetMusicClip(MusicClipOrder(m_MusicLoopCount[m_Musicincrement])), false);
m_Musicincrement++;
}
}
}
}
void AudioController::PlayUIBackgroundMusic()
{
if (m_MusicPlayer->GetSoundChannel(0)->GetState() == SoundChannel::SoundChannelState_Free)
{
m_MusicPlayer->PlaySound(GetMusicClip(UIBackGround), false);
}
}
void AudioController::StopUIBackgroundMusic()
{
if (m_MusicPlayer->GetSoundChannel(0)->GetState() == SoundChannel::SoundChannelState_Playing)
{
m_MusicPlayer->StopSound(0);
}
}
void AudioController::StopMusic()
{
if (m_MusicPlayer->GetSoundChannel(0)->GetState() == SoundChannel::SoundChannelState_Playing)
{
m_MusicPlayer->StopSound(0);
}
}
void AudioController::StopSounds()
{
for (int i = 0; i < m_pFXChannels.size(); i++)
{
if (m_FXPlayer->GetSoundChannel(i)->GetState() == SoundChannel::SoundChannelState_Playing)
{
m_FXPlayer->StopSound(i);
}
}
}
void AudioController::PlaySoundEffect(Sounds aSound, bool isPriority)
{
if (aSound == Lasers_1)
{
SoundObject* laser = LaserSoundRandom();
m_FXPlayer->PlaySound(laser, isPriority);
}
else if (aSound == Explosion_1)
{
SoundObject* explosion = ExplosionSoundRandom();
m_FXPlayer->PlaySound(explosion, isPriority);
}
else
{
m_FXPlayer->PlaySound(m_pSoundFX.find(aSound)->second, isPriority);
}
}
void AudioController::AddSoundFX(SoundObject* aFXSound, Sounds aName)
{
assert(m_pSoundFX.find(aName) == m_pSoundFX.end());
m_pSoundFX[aName] = aFXSound;
}
void AudioController::AddMusicClip(MusicClipOrder aClipHandle, SoundObject* aClip)
{
assert(m_pMusic.find(aClipHandle) == m_pMusic.end());
m_pMusic[aClipHandle] = aClip;
}
SoundObject* AudioController::GetMusicClip(MusicClipOrder aClip)
{
auto it = m_pMusic.find(aClip);
if (it == m_pMusic.end())
return nullptr;
return it->second;
}
void AudioController::SetChannelVolume(float aLevel, PlayerType aPlayer)
{
if (aPlayer == PT_MUSIC)
{
for (unsigned int i = 0; i < m_pMusicChannels.size(); i++)
{
m_pMusicChannels.at(i)->GetSourceVoice()->SetVolume(aLevel);
}
}
else if (aPlayer == PT_MISC)
{
for (unsigned int i = 0; i < m_pFXChannels.size(); i++)
{
m_pFXChannels.at(i)->GetSourceVoice()->SetVolume(aLevel);
}
}
}
SoundObject* AudioController::LaserSoundRandom()
{
int randomLaserIndex = rand() % 300;
if (randomLaserIndex < 50)
{
return m_pSoundFX[Lasers_1];
}
else if (randomLaserIndex < 120)
{
return m_pSoundFX[Lasers_2];
}
else if (randomLaserIndex < 230)
{
return m_pSoundFX[Lasers_3];
}
else if (randomLaserIndex < 270)
{
return m_pSoundFX[Lasers_4];
}
else
{
return m_pSoundFX[Lasers_5];
}
}
SoundObject * AudioController::ExplosionSoundRandom()
{
if (m_ExplosionIncrement < 3)
{
Sounds anExplosion = m_pExplosions.at(m_ExplosionIndex[m_ExplosionIncrement]);
return m_pSoundFX.find(anExplosion)->second;
m_ExplosionIncrement++;
}
else
{
vector<int>newShuffle;
m_ExplosionIncrement = 0;
while (newShuffle.size() < 4)
{
int index = rand() % 4;
if (newShuffle.size() == 0)
{
newShuffle.push_back(index);
}
else
{
bool doesExist = false;
for (int i = 0; i < newShuffle.size(); i++)
{
if (newShuffle.at(i) == index)
{
doesExist = true;
}
}
if (doesExist = false)
{
newShuffle.push_back(index);
}
if (newShuffle.size() == 3)
{
int lastNum = 8;
for (int j = 0; j < newShuffle.size(); j++)
{
lastNum -= newShuffle.at(j);
}
newShuffle.push_back(lastNum);
}
}
}
for (int i = 0; i < newShuffle.size(); i++)
{
m_ExplosionIndex[i] = newShuffle.at(i);
}
Sounds anExplosion = m_pExplosions.at(m_ExplosionIndex[m_ExplosionIncrement]);
return m_pSoundFX.find(anExplosion)->second;
m_ExplosionIncrement++;
}
}
SoundPlayer* AudioController::GetSoundPlayer(PlayerType aSoundPlayerHandle)
{
if (aSoundPlayerHandle == PT_MUSIC)
{
return m_MusicPlayer;
}
else if (aSoundPlayerHandle == PT_MISC)
{
return m_FXPlayer;
}
return nullptr;
}
void AudioController::Reset()
{
for (auto pMusic : m_pMusicChannels)
{
pMusic->StopSound();
}
for (auto pFX : m_pFXChannels)
{
pFX->StopSound();
}
m_MusicSampleCount = 0;
m_MusicSampleCount = 1;
}
|
#include "net/url_fetcher.h"
#include <evhtp.h>
#include <event2/buffer.h>
#include <event2/keyvalq_struct.h>
#include <glog/logging.h>
#include <htparse.h>
#include "net/connection_pool.h"
#include "util/thread_pool.h"
using cert_trans::internal::ConnectionPool;
using std::bind;
using std::endl;
using std::make_pair;
using std::move;
using std::ostream;
using std::string;
using std::to_string;
using std::unique_ptr;
using util::Status;
using util::Task;
using util::TaskHold;
namespace cert_trans {
struct UrlFetcher::Impl {
Impl(libevent::Base* base, ThreadPool* thread_pool)
: base_(CHECK_NOTNULL(base)),
thread_pool_(CHECK_NOTNULL(thread_pool)),
pool_(base_) {
}
libevent::Base* const base_;
ThreadPool* const thread_pool_;
internal::ConnectionPool pool_;
};
namespace {
htp_method VerbToCmdType(UrlFetcher::Verb verb) {
switch (verb) {
case UrlFetcher::Verb::GET:
return htp_method_GET;
case UrlFetcher::Verb::POST:
return htp_method_POST;
case UrlFetcher::Verb::PUT:
return htp_method_PUT;
case UrlFetcher::Verb::DELETE:
return htp_method_DELETE;
}
LOG(FATAL) << "unknown UrlFetcher::Verb: " << static_cast<int>(verb);
}
struct State {
State(libevent::Base* base, ConnectionPool* pool,
const UrlFetcher::Request& request, UrlFetcher::Response* response,
Task* task);
~State() {
CHECK(!conn_) << "request state object still had a connection at cleanup?";
}
void MakeRequest();
// The following methods must only be called on the libevent
// dispatch thread.
void RunRequest();
void RequestDone(evhtp_request_t* req);
libevent::Base* const base_;
ConnectionPool* const pool_;
const UrlFetcher::Request request_;
UrlFetcher::Response* const response_;
Task* const task_;
unique_ptr<ConnectionPool::Connection> conn_;
};
void RequestCallback(evhtp_request_t* req, void* userdata) {
static_cast<State*>(CHECK_NOTNULL(userdata))->RequestDone(req);
}
UrlFetcher::Request NormaliseRequest(UrlFetcher::Request req) {
if (req.url.Path().empty()) {
req.url.SetPath("/");
}
if (req.headers.find("Host") == req.headers.end()) {
req.headers.insert(make_pair("Host", req.url.Host()));
}
return req;
}
State::State(libevent::Base* base, ConnectionPool* pool,
const UrlFetcher::Request& request,
UrlFetcher::Response* response, Task* task)
: base_(CHECK_NOTNULL(base)),
pool_(CHECK_NOTNULL(pool)),
request_(NormaliseRequest(request)),
response_(CHECK_NOTNULL(response)),
task_(CHECK_NOTNULL(task)) {
if (request_.url.Protocol() != "http" &&
request_.url.Protocol() != "https") {
VLOG(1) << "unsupported protocol: " << request_.url.Protocol();
task_->Return(Status(util::error::INVALID_ARGUMENT,
"UrlFetcher: unsupported protocol: " +
request_.url.Protocol()));
return;
}
}
void State::MakeRequest() {
CHECK(!libevent::Base::OnEventThread());
conn_ = pool_->Get(request_.url);
base_->Add(bind(&State::RunRequest, this));
}
void State::RunRequest() {
CHECK(libevent::Base::OnEventThread());
evhtp_request_t* const http_req(
CHECK_NOTNULL(evhtp_request_new(&RequestCallback, this)));
if (!request_.body.empty() &&
request_.headers.find("Content-Length") == request_.headers.end()) {
evhtp_headers_add_header(
http_req->headers_out,
evhtp_header_new("Content-Length",
to_string(request_.body.size()).c_str(), 1, 1));
}
for (const auto& header : request_.headers) {
evhtp_headers_add_header(http_req->headers_out,
evhtp_header_new(header.first.c_str(),
header.second.c_str(), 1, 1));
}
if (!conn_->connection() || conn_->GetErrored()) {
conn_.reset();
task_->Return(Status(util::error::UNAVAILABLE, "connection failed."));
return;
}
const htp_method verb(VerbToCmdType(request_.verb));
VLOG(1) << "evhtp_make_request(" << conn_.get()->connection() << ", "
<< http_req << ", " << verb << ", \"" << request_.url.PathQuery()
<< "\")";
VLOG(2) << request_;
if (evhtp_make_request(conn_->connection(), http_req, verb,
request_.url.PathQuery().c_str()) != 0) {
VLOG(1) << "evhtp_make_request error";
// Put back the connection, RequestDone is not going to get
// called.
pool_->Put(move(conn_));
task_->Return(Status(util::error::INTERNAL, "evhtp_make_request error"));
return;
}
// evhtp_make_request doesn't know anything about the body, so we send it
// outselves here:
if (!request_.body.empty()) {
if (evbuffer_add_reference(bufferevent_get_output(
conn_->connection()->bev),
request_.body.data(), request_.body.size(),
nullptr, nullptr) != 0) {
VLOG(1) << "error when adding the request body";
task_->Return(
Status(util::error::INTERNAL, "could not set the request body"));
return;
}
}
}
struct evhtp_request_deleter {
void operator()(evhtp_request_t* r) const {
evhtp_request_free(r);
}
};
void State::RequestDone(evhtp_request_t* req) {
CHECK(libevent::Base::OnEventThread());
CHECK(conn_);
this->pool_->Put(move(conn_));
unique_ptr<evhtp_request_t, evhtp_request_deleter> req_deleter(req);
if (!req) {
// TODO(pphaneuf): The dreaded null request... These are fairly
// fatal things, like protocol parse errors, but could also be a
// connection timeout. I think we should do retries in this case,
// with a deadline of our own? At least, then, it would be easier
// to distinguish between an obscure error, or a more common
// timeout.
VLOG(1) << "RequestCallback received a null request";
task_->Return(Status::UNKNOWN);
return;
}
response_->status_code = req->status;
if (response_->status_code < 100) {
util::Status status;
switch (response_->status_code) {
case kTimeout:
status =
Status(util::error::DEADLINE_EXCEEDED, "connection timed out");
break;
case kSSLErrorStatus:
// There was a problem communicating with the remote host.
status = Status(util::error::UNAVAILABLE, "SSL connection failed");
break;
case kUnknownErrorStatus:
status = Status(util::error::UNAVAILABLE, "connection failed");
break;
default:
LOG(WARNING) << "Unknown status code encountered: "
<< response_->status_code;
status =
Status(util::error::UNKNOWN, "unknown status code encountered");
}
task_->Return(status);
return;
}
response_->headers.clear();
for (evhtp_kv_s* ptr = req->headers_in->tqh_first; ptr;
ptr = ptr->next.tqe_next) {
response_->headers.insert(make_pair(ptr->key, ptr->val));
}
const size_t body_length(evbuffer_get_length(req->buffer_in));
string body(reinterpret_cast<const char*>(
evbuffer_pullup(req->buffer_in, body_length)),
body_length);
response_->body.swap(body);
VLOG(2) << *response_;
task_->Return();
}
} // namespace
// Needs to be defined where Impl is also defined.
UrlFetcher::UrlFetcher() {
}
UrlFetcher::UrlFetcher(libevent::Base* base, ThreadPool* thread_pool)
: impl_(new Impl(CHECK_NOTNULL(base), CHECK_NOTNULL(thread_pool))) {
}
// Needs to be defined where Impl is also defined.
UrlFetcher::~UrlFetcher() {
}
void UrlFetcher::Fetch(const Request& req, Response* resp, Task* task) {
TaskHold hold(task);
State* const state(new State(impl_->base_, &impl_->pool_, req, resp, task));
task->DeleteWhenDone(state);
// Run State::MakeRequest() on the task's executor because it may
// block doing DNS resolution etc.
// TODO(alcutter): this can go back to being put straight on the event Base
// once evhtp supports creating SSL connections to a DNS name.
impl_->thread_pool_->Add(bind(&State::MakeRequest, state));
}
ostream& operator<<(ostream& output, const UrlFetcher::Response& resp) {
output << "status_code: " << resp.status_code << endl
<< "headers {" << endl;
for (const auto& header : resp.headers) {
output << " " << header.first << ": " << header.second << endl;
}
output << "}" << endl
<< "body: <<EOF" << endl
<< resp.body << "EOF" << endl;
return output;
}
ostream& operator<<(ostream& output, const UrlFetcher::Request& req) {
output << "verb: " << req.verb << endl
<< "url: " << req.url << endl
<< "headers: " << req.headers << endl
<< "body: <<EOF" << endl
<< req.body << "EOF" << endl;
return output;
}
ostream& operator<<(ostream& os, const UrlFetcher::Verb& verb) {
switch (verb) {
case UrlFetcher::Verb::GET:
os << "GET";
break;
case UrlFetcher::Verb::POST:
os << "POST";
break;
case UrlFetcher::Verb::PUT:
os << "PUT";
break;
case UrlFetcher::Verb::DELETE:
os << "DELETE";
break;
}
return os;
}
ostream& operator<<(ostream& os, const UrlFetcher::Headers& headers) {
os << "{" << endl;
for (const auto& h : headers) {
os << " " << h.first << ": " << h.second << endl;
}
return os << "}";
}
} // namespace cert_trans
|
#include "stdafx.h"
#include "ExitCommand.h"
std::string SIM::ExitCommand::GetUniqueName()
{
return Name;
}
bool SIM::ExitCommand::Execute()
{
qApp->closeAllWindows();
return true;
}
const std::string SIM::ExitCommand::Name("ExitCommand");
|
#include "EngineAssist.h"
#ifndef RTSGAME_H
#include "RtsGame.h"
#endif
#ifndef PLAYERRESOURCES_H
#include "PlayerResources.h"
#endif
#ifndef GAMETECHTREE_H
#include "GameTechTree.h"
#endif
#ifndef GAMEPLAYER_H
#include "GamePlayer.h"
#endif
#ifndef GAMETYPE_H
#include "GameType.h"
#endif
#ifndef GAMEENTITY_H
#include "GameEntity.h"
#endif
#ifndef GAMERESEARCH_H
#include "GameResearch.h"
#endif
#ifndef ONLINECASEBASEDPLANNEREX_H
#include "OnlineCaseBasedPlannerEx.h"
#endif
#ifndef ABSTRACTADAPTER_H
#include "AbstractAdapter.h"
#endif
#ifndef RESEARCHDONE_H
#include "ResearchDone.h"
#endif
#ifndef ENTITYCLASSEXIST_H
#include "EntityClassExist.h"
#endif
#ifndef RESOURCEEXIST_H
#include "ResourceExist.h"
#endif
#ifndef AND_H
#include "And.h"
#endif
#include "MathHelper.h"
#include "Vector2.h"
#include <map>
#include <algorithm>
using namespace IStrategizer;
using namespace std;
int EngineAssist::GetResourceAmount(PlayerType p_playerIndex, ResourceType p_resourceId, int& p_availableAmount)
{
PlayerResources* m_resources = g_Game->GetPlayer(p_playerIndex)->Resources();
switch (p_resourceId)
{
case RESOURCE_Supply:
p_availableAmount = m_resources->AvailableSupply();
break;
case RESOURCE_Primary:
p_availableAmount = m_resources->AvailablePrimary();
break;
case RESOURCE_Secondary:
p_availableAmount = m_resources->AvailableSecondary();
break;
default:
DEBUG_THROW(InvalidParameterException(XcptHere));
}
return 0;
}
//------------------------------------------------------------------------------------------------------------------------------------------------
bool EngineAssist::DoesEntityClassExist(pair<EntityClassType, int> p_entityType, ObjectStateType state, bool checkFree, PlayerType p_playerType)
{
int matches = 0;
auto& entities = g_Game->GetPlayer(p_playerType)->Entities();
for (auto& entityR : entities)
{
auto pEntity = entityR.second;
auto currState = (ObjectStateType)pEntity->P(OP_State);
if (pEntity->TypeId() == p_entityType.first &&
(((state == OBJSTATE_END || state == DONT_CARE) && currState != OBJSTATE_BeingConstructed) ||
(state != OBJSTATE_END && currState == state)) &&
(!checkFree || !pEntity->IsLocked()))
{
if (p_entityType.second == DONT_CARE)
{
return true;
}
else
++matches;
}
}
if (p_entityType.second == DONT_CARE)
return matches > 0;
else
return matches >= p_entityType.second;
}
//------------------------------------------------------------------------------------------------------------------------------------------------
bool EngineAssist::DoesEntityClassExist(const map<EntityClassType, int> &p_entityTypes, PlayerType p_playerType)
{
GameEntity* pEntity;
int matches;
bool exist = false;
auto& entities = g_Game->GetPlayer(p_playerType)->Entities();
exist = true;
for (auto itr = p_entityTypes.begin();
itr != p_entityTypes.end(); ++itr)
{
matches = 0;
for (auto& entityR : entities)
{
pEntity = entityR.second;
_ASSERTE(pEntity);
// Units are considered exist if and only if it is constructed
if (pEntity->TypeId() == itr->first &&
pEntity->P(OP_State) != (int)OBJSTATE_BeingConstructed)
++matches;
}
if (matches < itr->second)
{
exist = false;
break;
}
}
return exist;
}
//------------------------------------------------------------------------------------------------------------------------------------------------
bool EngineAssist::IsEntityObjectReady(TID p_entityObject, PlayerType p_playerType)
{
GamePlayer *pPlayer;
GameEntity *pEntity;
bool isReady;
pPlayer = g_Game->GetPlayer(p_playerType);
_ASSERTE(pPlayer);
pEntity = pPlayer->GetEntity(p_entityObject);
isReady = pEntity != nullptr &&
pEntity->Exists() &&
pEntity->P(OP_State) != (int)OBJSTATE_BeingConstructed;
return isReady;
}
//------------------------------------------------------------------------------------------------------------------------------------------------
bool EngineAssist::DoesEntityObjectExist(TID p_entityObject, PlayerType p_playerType)
{
GamePlayer *pPlayer;
GameEntity *pEntity;
bool exist;
pPlayer = g_Game->GetPlayer(p_playerType);
_ASSERTE(pPlayer);
pEntity = pPlayer->GetEntity(p_entityObject);
exist = (pEntity != nullptr);
return exist;
}
//------------------------------------------------------------------------------------------------------------------------------------------------
bool EngineAssist::DoesEntityObjectExist(const EntityList &p_entityObjects, PlayerType p_playerType)
{
GamePlayer *pPlayer;
GameEntity *pEntity;
bool exist = true;
pPlayer = g_Game->GetPlayer(p_playerType);
_ASSERTE(pPlayer);
for (unsigned i = 0, size = p_entityObjects.size(); i < size; ++i)
{
pEntity = pPlayer->GetEntity(p_entityObjects[i]);
if (pEntity == nullptr)
{
exist = false;
break;
}
}
return exist;
}
//------------------------------------------------------------------------------------------------------------------------------------------------
bool EngineAssist::IsEntityCloseToPoint(IN const TID p_entityId, IN const Vector2& p_point, IN const unsigned p_maxDistance)
{
GameEntity* entity = g_Game->Self()->GetEntity(p_entityId);
_ASSERTE(entity);
Vector2 currentPosition = entity->Position();
double euclideanDistance = sqrt((double)
(currentPosition.Y - p_point.Y) * (currentPosition.Y - p_point.Y)
+ (currentPosition.X - p_point.X) * (currentPosition.X - p_point.X));
return euclideanDistance <= p_maxDistance;
}
//------------------------------------------------------------------------------------------------------------------------------------------------
void EngineAssist::GetPrerequisites(int p_entityOrResearchType, PlayerType p_playerType, vector<Expression*>& p_prerequisites)
{
WorldResources pReqResources;
vector<ResearchType> reqResearches;
map<EntityClassType, unsigned> reqEntities;
if (BELONG(EntityClassType, p_entityOrResearchType))
g_Game->GetEntityType((EntityClassType)p_entityOrResearchType)->GetRequirements(reqResearches, reqEntities);
else
g_Game->GetResearch((ResearchType)p_entityOrResearchType)->GetRequirements(reqResearches, reqEntities);
// 1. Required researches done
for (unsigned i = 0, size = reqResearches.size(); i < size; ++i)
{
p_prerequisites.push_back(new IStrategizer::ResearchDone(p_playerType, reqResearches[i]));
}
// 2. Additional required entities exist
for (map<EntityClassType, unsigned>::const_iterator i = reqEntities.begin(); i != reqEntities.end(); ++i)
{
p_prerequisites.push_back(new EntityClassExist(p_playerType, (*i).first, 1));
}
// 3. Source building exist
//if (BELONG(EntityClassType, p_entityOrResearchType))
// sourceEntity = g_Game->GetEntityType((EntityClassType)p_entityOrResearchType)->SourceEntity();
//else
// sourceEntity = g_Game->GetResearch((ResearchType)p_entityOrResearchType)->SourceEntity();
//_ASSERTE(sourceEntity != ECLASS_END);
//p_prerequisites.push_back(new EntityClassExist(p_playerType, sourceEntity, 1));
// 4. Required resources exist
GetPrerequisiteResources(p_entityOrResearchType, p_playerType, pReqResources);
p_prerequisites.push_back(new ResourceExist(p_playerType, RESOURCE_Primary, pReqResources.Primary()));
p_prerequisites.push_back(new ResourceExist(p_playerType, RESOURCE_Secondary, pReqResources.Secondary()));
p_prerequisites.push_back(new ResourceExist(p_playerType, RESOURCE_Supply, pReqResources.Supply()));
}
//------------------------------------------------------------------------------------------------------------------------------------------------
void EngineAssist::GetPrerequisiteResources(int p_entityOrResearchType, PlayerType p_playerType, WorldResources& p_resources)
{
GamePlayer *pPlayer = nullptr;
GameType *pEntityType = nullptr;
GameResearch *pResearchType = nullptr;
pPlayer = g_Game->GetPlayer(p_playerType);
_ASSERTE(pPlayer);
if (BELONG(ResearchType, p_entityOrResearchType))
{
pResearchType = g_Game->GetResearch((ResearchType)p_entityOrResearchType);
_ASSERTE(pResearchType);
p_resources.Set(pResearchType->RequiredResources());
}
else if (BELONG(EntityClassType, p_entityOrResearchType))
{
pEntityType = g_Game->GetEntityType((EntityClassType)p_entityOrResearchType);
_ASSERTE(pEntityType);
p_resources.Set(pEntityType->RequiredResources());
}
else _ASSERTE(!"Not supported type");
}
//------------------------------------------------------------------------------------------------------------------------------------------------
bool EngineAssist::IsEntityInState(TID p_entityObject, ObjectStateType stateType, PlayerType p_playerType)
{
if (stateType == OBJSTATE_DontCare)
{
return IsEntityObjectReady(p_entityObject, p_playerType);
}
else
{
GamePlayer *pPlayer;
GameEntity *pEntity;
bool inState;
pPlayer = g_Game->GetPlayer(p_playerType);
_ASSERTE(pPlayer);
pEntity = pPlayer->GetEntity(p_entityObject);
inState = (pEntity != nullptr) && ((ObjectStateType)pEntity->P(OP_State) == stateType);
return inState;
}
}
|
/* -*- C++ -*- */
/*************************************************************************
* Copyright(c) 1995~2005 Masaharu Goto (root-cint@cern.ch)
*
* For the licensing terms see the file COPYING
*
************************************************************************/
//____________________________________________________________________________
//*-*-*-*-*-*-*-*-*-*-*-*The Minuit standard test program-*-*-*-*-*-*-*-*-*
//*-* ======================== *
//*-* *
//*-* This program is the translation to C++ of the minexam program *
//*-* distributed with the Minuit/Fortran source file. *
//*-* original author Fred James *
//*-* *
//*-* Fit randomly-generated leptonic K0 decays to the *
//*-* time distribution expected for interfering K1 and K2, *
//*-* with free parameters Re(X), Im(X), DeltaM, and GammaS. *
//*-* *
//*-* This program can be run in batch mode with the makefile *
//*-* or executed interactively with the command: *
//*-* Root > .x minexam.cxx *
//*-* *
//*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
#ifndef __CINT__
#if 0
#include "TROOT.h"
#include "TMinuit.h"
#include "TMath.h"
#include "TStopwatch.h"
#endif
#include <math.h>
#include <stdlib.h>
#include <stdio.h>
#endif
typedef int Int_t ;
typedef double Double_t;
void fcnk0(Int_t &npar, Double_t *gin, Double_t &f, Double_t *x, Int_t iflag);
Int_t minexam();
static int ncount = 0;
class TMath {
public:
static Double_t Exp(Double_t x) { return(exp(x)); }
static Double_t Sin(Double_t x) { return(sin(x)); }
static Double_t Cos(Double_t x) { return(cos(x)); }
};
//____________________________________________________________________________
int main()
{
//TROOT mintest("TestMinuit","Test of Minuit");
//return minexam();
Int_t a;
Double_t b[100];
Double_t f;
Double_t x[100] = { 1,2,3,4,5,6,7,8,9,10,11 };
for(Int_t i=0;i<3;i++) fcnk0(a,b,f,x,0);
}
#if 0
Int_t minexam()
{
static Int_t nprm[5] = { 0 , 1 , 4 , 9 , 10};
static Double_t vstrt[5] = {0. , 0. , .535 , .892 , 518.3};
static Double_t stp[5] = {0.1 , 0.1 , 0.1 , 0. , 0.};
static Double_t p0=0;
static Double_t p1=1;
static Double_t p3=3;
static Double_t p5=5;
Int_t ierflg = 0;
TStopwatch timer;
TMinuit *gMinuit = new TMinuit(5); //initialize TMinuit with a maximum of 5 params
printf("Starting timer\n");
timer.Start();
gMinuit->mninit(5,6,7);
gMinuit->SetFCN(fcnk0);
gMinuit->mnparm(nprm[0], "Re(X)", vstrt[0], stp[0], 0,0,ierflg);
gMinuit->mnparm(nprm[1], "Im(X)", vstrt[1], stp[1], 0,0,ierflg);
gMinuit->mnparm(nprm[2], "Delta M", vstrt[2], stp[2], 0,0,ierflg);
gMinuit->mnparm(nprm[3], "T Kshort", vstrt[3], stp[3], 0,0,ierflg);
gMinuit->mnparm(nprm[4], "T Klong", vstrt[4], stp[4], 0,0,ierflg);
if (ierflg) {
printf(" UNABLE TO DEFINE PARAMETER NO.");
return ierflg;
}
// gMinuit->mnseti("Time Distribution of Leptonic K0 Decays");
//*-*- Request FCN to read in (or generate random) data (IFLAG=1)
gMinuit->mnexcm("CALL FCN", &p1 ,1,ierflg);
gMinuit->mnexcm("FIX", &p5 ,1,ierflg);
gMinuit->mnexcm("SET PRINT", &p0 ,1,ierflg);
gMinuit->mnexcm("MIGRAD", &p0 ,0,ierflg);
gMinuit->mnexcm("MINOS", &p0 ,0,ierflg);
gMinuit->mnexcm("RELEASE", &p5 ,1,ierflg);
gMinuit->mnexcm("MIGRAD", &p0 ,0,ierflg);
gMinuit->mnexcm("MINOS", &p0 ,0,ierflg);
gMinuit->mnexcm("CALL FCN", &p3 , 1,ierflg);
printf("Time at the end of job = %f seconds\n",timer.CpuTime());
return 0;
}
#endif
//_____________________________________________________________________________
void fcnk0(Int_t &, Double_t *, Double_t &f, Double_t *x, Int_t iflag)
{
const Int_t MXBIN=50;
//===>BUG if this line is activated
static Double_t thplu[MXBIN],thmin[MXBIN],t[MXBIN];
// static Double_t thplu[50],thmin[50],t[50];
static Int_t nbins = 30;
static Int_t nevtot = 250;
static Double_t evtp[30] = {
11., 9., 13., 13., 17., 9., 1., 7., 8., 9.,
6., 4., 6., 3., 7., 4., 7., 3., 8., 4.,
6., 5., 7., 2., 7., 1., 4., 1., 4., 5.};
static Double_t evtm[30] = {
0., 0., 0., 0., 0., 0., 0., 0., 1., 1.,
0., 2., 1., 4., 4., 2., 4., 2., 2., 0.,
2., 3., 7., 2., 3., 6., 2., 4., 1., 5.};
static Int_t i, nevplu, nevmin;
static Double_t xre, xim, dm, gams, gaml,gamls,xr1,xr2,em,ep;
static Double_t sthplu, sthmin, ehalf, th, sterm, sevtp, sevtm;
static Double_t chisq, ti, thp, thm, evp, evm, chi1, chi2;
xre = x[0];
xim = x[1];
dm = x[4];
gams = 1/x[9];
gaml = 1/x[10];
gamls = 0.5*(gaml+gams);
if (iflag != 1) goto L300;
// generate random data
sthplu = sthmin = 0;
for (i=1;i<=nbins; i++) {
t[i-1] = 0.1*Double_t(i);
ti = t[i-1];
ehalf = TMath::Exp(-ti*gamls);
xr1 = 1-xre;
xr2 = 1+xre;
th = (xr1*xr1 + xim*xim) * TMath::Exp(-ti*gaml);
th = th + (xr2*xr2 + xim*xim) * TMath::Exp(-ti*gams);
th = th - 4*xim*TMath::Sin(dm*ti) * ehalf;
sterm = 2*(1-xre*xre-xim*xim)*TMath::Cos(dm*ti) * ehalf;
thplu[i-1] = th + sterm;
thmin[i-1] = th - sterm;
sthplu += thplu[i-1];
sthmin += thmin[i-1];
}
nevplu = Int_t(Double_t(nevtot)*(sthplu/(sthplu+sthmin)));
nevmin = Int_t(Double_t(nevtot)*(sthmin/(sthplu+sthmin)));
printf(" LEPTONIC K ZERO DECAYS\n");
printf(" PLUS, MINUS, TOTAL=%5d %5d %5d\n",nevplu,nevmin,nevtot);
printf("0 TIME THEOR+ EXPTL+ THEOR- EXPTL-\n");
sevtp = sevtm = 0;
for (i=1;i<=nbins; i++) {
// ====>BUG if the following two lines are activated
thplu[i-1] = thplu[i-1]*Double_t(nevplu) / sthplu;
thmin[i-1] = thmin[i-1]*Double_t(nevmin) / sthmin;
//thplu[i-1] = thplu[i-1]*nevplu/ sthplu;
//thmin[i-1] = thmin[i-1]*nevmin/ sthmin;
sevtp += evtp[i-1];
sevtm += evtm[i-1];
if (iflag != 4) {
printf("%12.4f%12.4f%12.4f%12.4f%12.4f\n"
,t[i-1],thplu[i-1],evtp[i-1],thmin[i-1],evtm[i-1]);
}
}
printf(" DATA EVTS PLUS, MINUS= %10.2f%10.2f\n", sevtp,sevtm);
// calculate chisquared
L300:
chisq = sthplu = sthmin = 0;
for (i=1;i<=nbins; i++) {
ti = t[i-1];
ehalf = TMath::Exp(-ti*gamls);
xr1 = 1-xre;
xr2 = 1+xre;
th = (xr1*xr1 + xim*xim) * TMath::Exp(-ti*gaml);
th = th + (xr2*xr2 + xim*xim) * TMath::Exp(-ti*gams);
th = th - 4*xim*TMath::Sin(dm*ti) * ehalf;
sterm = 2*(1-xre*xre-xim*xim)*TMath::Cos(dm*ti) * ehalf;
thplu[i-1] = th + sterm;
thmin[i-1] = th - sterm;
sthplu += thplu[i-1];
sthmin += thmin[i-1];
}
thp = thm = evp = evm = 0;
if (iflag != 4) printf(" POSITIVE LEPTONS ,NEGATIVE LEPTONS\n");
if (iflag != 4) {
printf(" TIME THEOR EXPTL chisq TIME THEOR EXPTL chisq\n");
}
for (i=1;i<=nbins; i++) {
thplu[i-1] = thplu[i-1]*sevtp / sthplu;
thmin[i-1] = thmin[i-1]*sevtm / sthmin;
thp += thplu[i-1];
thm += thmin[i-1];
evp += evtp[i-1];
evm += evtm[i-1];
// Sum over bins until at least four events found
if (evp > 3) {
ep = evp-thp;
chi1 = (ep*ep)/evp;
chisq = chisq + chi1;
if (iflag != 4) {
printf(" %9.3f%9.3f%9.3f%9.3f\n",t[i-1],thp,evp,chi1);
}
thp = evp = 0;
}
if (evm > 3) {
em = evm-thm;
chi2 = (em*em)/evm;
chisq = chisq + chi2;
if (iflag != 4) {
printf(" %9.3f%9.3f%9.3f%9.3f\n" ,t[i-1],thm,evm,chi2);
}
thm = evm = 0;
}
}
f = chisq;
ncount++;
}
|
// 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 "components/contextual_search/renderer/contextual_search_wrapper.h"
#include "base/strings/string_util.h"
#include "content/public/common/service_registry.h"
#include "content/public/renderer/chrome_object_extensions_utils.h"
#include "content/public/renderer/render_frame.h"
#include "gin/arguments.h"
#include "gin/object_template_builder.h"
#include "third_party/WebKit/public/web/WebFrame.h"
#include "third_party/WebKit/public/web/WebKit.h"
#include "third_party/WebKit/public/web/WebLocalFrame.h"
#include "v8/include/v8.h"
namespace {
static const char kContextualSearchObjectName[] = "contextualSearch";
static const char kSetCaptionMethodName[] = "setCaption";
} // namespace
namespace contextual_search {
gin::WrapperInfo ContextualSearchWrapper::kWrapperInfo = {
gin::kEmbedderNativeGin};
// static
void ContextualSearchWrapper::Install(content::RenderFrame* render_frame) {
// NOTE: Installing new v8 functions that can access Chrome native code
// requires a security review! We did an exhaustive search for a better
// way to implement a communication channel between the page and Chrome,
// but found nothing better.
// TODO(donnd): use a better communication channel once that becomes
// available, e.g. navigator.connect API. See crbug.com/541683.
// TODO(donnd): refactor some of this boilerplate into a reusable
// method. This was cribbed from MemoryBenchmarkingExtension.
v8::Isolate* isolate = blink::mainThreadIsolate();
v8::HandleScope handle_scope(isolate);
v8::Local<v8::Context> context =
render_frame->GetWebFrame()->mainWorldScriptContext();
if (context.IsEmpty())
return;
v8::Context::Scope context_scope(context);
gin::Handle<ContextualSearchWrapper> wrapper =
gin::CreateHandle(isolate, new ContextualSearchWrapper(render_frame));
if (wrapper.IsEmpty())
return;
v8::Local<v8::Object> chrome =
content::GetOrCreateChromeObject(isolate, context->Global());
chrome->Set(gin::StringToV8(isolate, kContextualSearchObjectName),
wrapper.ToV8());
}
ContextualSearchWrapper::ContextualSearchWrapper(
content::RenderFrame* render_frame)
: RenderFrameObserver(render_frame) {}
ContextualSearchWrapper::~ContextualSearchWrapper() {}
gin::ObjectTemplateBuilder ContextualSearchWrapper::GetObjectTemplateBuilder(
v8::Isolate* isolate) {
return gin::Wrappable<ContextualSearchWrapper>::GetObjectTemplateBuilder(
isolate)
.SetMethod(kSetCaptionMethodName, &ContextualSearchWrapper::SetCaption);
}
bool ContextualSearchWrapper::EnsureServiceConnected() {
if (render_frame() && (!contextual_search_js_api_service_ ||
!contextual_search_js_api_service_.is_bound())) {
render_frame()->GetServiceRegistry()->ConnectToRemoteService(
mojo::GetProxy(&contextual_search_js_api_service_));
return true;
} else {
return false;
}
}
void ContextualSearchWrapper::OnDestruct() {}
void ContextualSearchWrapper::SetCaption(const std::string& caption,
bool does_answer) {
if (EnsureServiceConnected()) {
contextual_search_js_api_service_->HandleSetCaption(caption, does_answer);
}
}
} // namespace contextual_search
|
/*
* Test for terminate_if_throws
*/
#include <cpp_util_3/terminate_if_throws.hpp>
#include <iostream>
#include <stdexcept>
int safe_idiv( int a, int b )
{
if( 0 == b )
throw std::invalid_argument( "Division to 0" );
return a / b;
}
void do_div( int a, int b )
{
std::cout << a << "/" << b << "=" << std::flush;
const auto r = cpp_util_3::terminate_if_throws( [&] {
return safe_idiv(a, b);
} );
std::cout << r << std::endl;
}
int main()
{
do_div( 3, 2 );
do_div( 4, 0 );
return 0;
}
|
//===-- DarwinProcessLauncher.cpp -------------------------------*- C++ -*-===//
//
// 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
//
//===----------------------------------------------------------------------===//
//
// DarwinProcessLauncher.cpp
// lldb
//
// Created by Todd Fiala on 8/30/16.
//
//
#include "DarwinProcessLauncher.h"
// C includes
#include <spawn.h>
#include <sys/ptrace.h>
#include <sys/stat.h>
#include <sys/sysctl.h>
#ifndef _POSIX_SPAWN_DISABLE_ASLR
#define _POSIX_SPAWN_DISABLE_ASLR 0x0100
#endif
// LLDB includes
#include "lldb/lldb-enumerations.h"
#include "lldb/Host/PseudoTerminal.h"
#include "lldb/Target/ProcessLaunchInfo.h"
#include "lldb/Utility/Log.h"
#include "lldb/Utility/Status.h"
#include "lldb/Utility/StreamString.h"
#include "llvm/Support/Errno.h"
#include "CFBundle.h"
#include "CFString.h"
using namespace lldb;
using namespace lldb_private;
using namespace lldb_private::process_darwin;
using namespace lldb_private::darwin_process_launcher;
namespace {
static LaunchFlavor g_launch_flavor = LaunchFlavor::Default;
}
namespace lldb_private {
namespace darwin_process_launcher {
static uint32_t GetCPUTypeForLocalProcess(::pid_t pid) {
int mib[CTL_MAXNAME] = {
0,
};
size_t len = CTL_MAXNAME;
if (::sysctlnametomib("sysctl.proc_cputype", mib, &len))
return 0;
mib[len] = pid;
len++;
cpu_type_t cpu;
size_t cpu_len = sizeof(cpu);
if (::sysctl(mib, static_cast<u_int>(len), &cpu, &cpu_len, 0, 0))
cpu = 0;
return cpu;
}
static bool ResolveExecutablePath(const char *path, char *resolved_path,
size_t resolved_path_size) {
if (path == NULL || path[0] == '\0')
return false;
char max_path[PATH_MAX];
std::string result;
CFString::GlobPath(path, result);
if (result.empty())
result = path;
struct stat path_stat;
if (::stat(path, &path_stat) == 0) {
if ((path_stat.st_mode & S_IFMT) == S_IFDIR) {
CFBundle bundle(path);
CFReleaser<CFURLRef> url(bundle.CopyExecutableURL());
if (url.get()) {
if (::CFURLGetFileSystemRepresentation(
url.get(), true, (UInt8 *)resolved_path, resolved_path_size))
return true;
}
}
}
if (realpath(path, max_path)) {
// Found the path relatively...
::strncpy(resolved_path, max_path, resolved_path_size);
return strlen(resolved_path) + 1 < resolved_path_size;
} else {
// Not a relative path, check the PATH environment variable if the
const char *PATH = getenv("PATH");
if (PATH) {
const char *curr_path_start = PATH;
const char *curr_path_end;
while (curr_path_start && *curr_path_start) {
curr_path_end = strchr(curr_path_start, ':');
if (curr_path_end == NULL) {
result.assign(curr_path_start);
curr_path_start = NULL;
} else if (curr_path_end > curr_path_start) {
size_t len = curr_path_end - curr_path_start;
result.assign(curr_path_start, len);
curr_path_start += len + 1;
} else
break;
result += '/';
result += path;
struct stat s;
if (stat(result.c_str(), &s) == 0) {
::strncpy(resolved_path, result.c_str(), resolved_path_size);
return result.size() + 1 < resolved_path_size;
}
}
}
}
return false;
}
// TODO check if we have a general purpose fork and exec. We may be
// able to get rid of this entirely.
static Status ForkChildForPTraceDebugging(const char *path, char const *argv[],
char const *envp[], ::pid_t *pid,
int *pty_fd) {
Status error;
if (!path || !argv || !envp || !pid || !pty_fd) {
error.SetErrorString("invalid arguments");
return error;
}
// Use a fork that ties the child process's stdin/out/err to a pseudo
// terminal so we can read it in our MachProcess::STDIOThread as unbuffered
// io.
PseudoTerminal pty;
char fork_error[256];
memset(fork_error, 0, sizeof(fork_error));
*pid = static_cast<::pid_t>(pty.Fork(fork_error, sizeof(fork_error)));
if (*pid < 0) {
// Status during fork.
*pid = static_cast<::pid_t>(LLDB_INVALID_PROCESS_ID);
error.SetErrorStringWithFormat("%s(): fork failed: %s", __FUNCTION__,
fork_error);
return error;
} else if (pid == 0) {
// Child process
// Debug this process.
::ptrace(PT_TRACE_ME, 0, 0, 0);
// Get BSD signals as mach exceptions.
::ptrace(PT_SIGEXC, 0, 0, 0);
// If our parent is setgid, lets make sure we don't inherit those extra
// powers due to nepotism.
if (::setgid(getgid()) == 0) {
// Let the child have its own process group. We need to execute this call
// in both the child and parent to avoid a race condition between the two
// processes.
// Set the child process group to match its pid.
::setpgid(0, 0);
// Sleep a bit to before the exec call.
::sleep(1);
// Turn this process into the given executable.
::execv(path, (char *const *)argv);
}
// Exit with error code. Child process should have taken over in above exec
// call and if the exec fails it will exit the child process below.
::exit(127);
} else {
// Parent process
// Let the child have its own process group. We need to execute this call
// in both the child and parent to avoid a race condition between the two
// processes.
// Set the child process group to match its pid
::setpgid(*pid, *pid);
if (pty_fd) {
// Release our master pty file descriptor so the pty class doesn't close
// it and so we can continue to use it in our STDIO thread
*pty_fd = pty.ReleaseMasterFileDescriptor();
}
}
return error;
}
static Status
CreatePosixSpawnFileAction(const FileAction &action,
posix_spawn_file_actions_t *file_actions) {
Status error;
// Log it.
Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
if (log) {
StreamString stream;
stream.PutCString("converting file action for posix_spawn(): ");
action.Dump(stream);
stream.Flush();
log->PutCString(stream.GetString().c_str());
}
// Validate args.
if (!file_actions) {
error.SetErrorString("mandatory file_actions arg is null");
return error;
}
// Build the posix file action.
switch (action.GetAction()) {
case FileAction::eFileActionOpen: {
const int error_code = ::posix_spawn_file_actions_addopen(
file_actions, action.GetFD(), action.GetPath(),
action.GetActionArgument(), 0);
if (error_code != 0) {
error.SetError(error_code, eErrorTypePOSIX);
return error;
}
break;
}
case FileAction::eFileActionClose: {
const int error_code =
::posix_spawn_file_actions_addclose(file_actions, action.GetFD());
if (error_code != 0) {
error.SetError(error_code, eErrorTypePOSIX);
return error;
}
break;
}
case FileAction::eFileActionDuplicate: {
const int error_code = ::posix_spawn_file_actions_adddup2(
file_actions, action.GetFD(), action.GetActionArgument());
if (error_code != 0) {
error.SetError(error_code, eErrorTypePOSIX);
return error;
}
break;
}
case FileAction::eFileActionNone:
default:
LLDB_LOGF(log, "%s(): unsupported file action %u", __FUNCTION__,
action.GetAction());
break;
}
return error;
}
static Status PosixSpawnChildForPTraceDebugging(const char *path,
ProcessLaunchInfo &launch_info,
::pid_t *pid,
cpu_type_t *actual_cpu_type) {
Status error;
Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
if (!pid) {
error.SetErrorStringWithFormat("%s(): pid arg cannot be null",
__FUNCTION__);
return error;
}
posix_spawnattr_t attr;
short flags;
if (log) {
StreamString stream;
stream.Printf("%s(path='%s',...)\n", __FUNCTION__, path);
launch_info.Dump(stream, nullptr);
stream.Flush();
log->PutCString(stream.GetString().c_str());
}
int error_code;
if ((error_code = ::posix_spawnattr_init(&attr)) != 0) {
LLDB_LOGF(log, "::posix_spawnattr_init(&attr) failed");
error.SetError(error_code, eErrorTypePOSIX);
return error;
}
// Ensure we clean up the spawnattr structure however we exit this function.
std::unique_ptr<posix_spawnattr_t, int (*)(posix_spawnattr_t *)> spawnattr_up(
&attr, ::posix_spawnattr_destroy);
flags = POSIX_SPAWN_START_SUSPENDED | POSIX_SPAWN_SETSIGDEF |
POSIX_SPAWN_SETSIGMASK;
if (launch_info.GetFlags().Test(eLaunchFlagDisableASLR))
flags |= _POSIX_SPAWN_DISABLE_ASLR;
sigset_t no_signals;
sigset_t all_signals;
sigemptyset(&no_signals);
sigfillset(&all_signals);
::posix_spawnattr_setsigmask(&attr, &no_signals);
::posix_spawnattr_setsigdefault(&attr, &all_signals);
if ((error_code = ::posix_spawnattr_setflags(&attr, flags)) != 0) {
LLDB_LOG(log,
"::posix_spawnattr_setflags(&attr, "
"POSIX_SPAWN_START_SUSPENDED{0}) failed: {1}",
flags & _POSIX_SPAWN_DISABLE_ASLR ? " | _POSIX_SPAWN_DISABLE_ASLR"
: "",
llvm::sys::StrError(error_code));
error.SetError(error_code, eErrorTypePOSIX);
return error;
}
#if !defined(__arm__)
// We don't need to do this for ARM, and we really shouldn't now that we have
// multiple CPU subtypes and no posix_spawnattr call that allows us to set
// which CPU subtype to launch...
cpu_type_t desired_cpu_type = launch_info.GetArchitecture().GetMachOCPUType();
if (desired_cpu_type != LLDB_INVALID_CPUTYPE) {
size_t ocount = 0;
error_code =
::posix_spawnattr_setbinpref_np(&attr, 1, &desired_cpu_type, &ocount);
if (error_code != 0) {
LLDB_LOG(log,
"::posix_spawnattr_setbinpref_np(&attr, 1, "
"cpu_type = {0:x8}, count => {1}): {2}",
desired_cpu_type, ocount, llvm::sys::StrError(error_code));
error.SetError(error_code, eErrorTypePOSIX);
return error;
}
if (ocount != 1) {
error.SetErrorStringWithFormat("posix_spawnattr_setbinpref_np "
"did not set the expected number "
"of cpu_type entries: expected 1 "
"but was %zu",
ocount);
return error;
}
}
#endif
posix_spawn_file_actions_t file_actions;
if ((error_code = ::posix_spawn_file_actions_init(&file_actions)) != 0) {
LLDB_LOG(log, "::posix_spawn_file_actions_init(&file_actions) failed: {0}",
llvm::sys::StrError(error_code));
error.SetError(error_code, eErrorTypePOSIX);
return error;
}
// Ensure we clean up file actions however we exit this. When the
// file_actions_up below goes out of scope, we'll get our file action
// cleanup.
std::unique_ptr<posix_spawn_file_actions_t,
int (*)(posix_spawn_file_actions_t *)>
file_actions_up(&file_actions, ::posix_spawn_file_actions_destroy);
// We assume the caller has setup the file actions appropriately. We are not
// in the business of figuring out what we really need here. lldb-server will
// have already called FinalizeFileActions() as well to button these up
// properly.
const size_t num_actions = launch_info.GetNumFileActions();
for (size_t action_index = 0; action_index < num_actions; ++action_index) {
const FileAction *const action =
launch_info.GetFileActionAtIndex(action_index);
if (!action)
continue;
error = CreatePosixSpawnFileAction(*action, &file_actions);
if (!error.Success()) {
LLDB_LOGF(log,
"%s(): error converting FileAction to posix_spawn "
"file action: %s",
__FUNCTION__, error.AsCString());
return error;
}
}
// TODO: Verify if we can set the working directory back immediately
// after the posix_spawnp call without creating a race condition???
const char *const working_directory =
launch_info.GetWorkingDirectory().GetCString();
if (working_directory && working_directory[0])
::chdir(working_directory);
auto argv = launch_info.GetArguments().GetArgumentVector();
auto envp = launch_info.GetEnvironmentEntries().GetArgumentVector();
error_code = ::posix_spawnp(pid, path, &file_actions, &attr,
(char *const *)argv, (char *const *)envp);
if (error_code != 0) {
LLDB_LOG(log,
"::posix_spawnp(pid => {0}, path = '{1}', file_actions "
"= {2}, attr = {3}, argv = {4}, envp = {5}) failed: {6}",
pid, path, &file_actions, &attr, argv, envp,
llvm::sys::StrError(error_code));
error.SetError(error_code, eErrorTypePOSIX);
return error;
}
// Validate we got a pid.
if (pid == LLDB_INVALID_PROCESS_ID) {
error.SetErrorString("posix_spawn() did not indicate a failure but it "
"failed to return a pid, aborting.");
return error;
}
if (actual_cpu_type) {
*actual_cpu_type = GetCPUTypeForLocalProcess(*pid);
LLDB_LOGF(log,
"%s(): cpu type for launched process pid=%i: "
"cpu_type=0x%8.8x",
__FUNCTION__, *pid, *actual_cpu_type);
}
return error;
}
Status LaunchInferior(ProcessLaunchInfo &launch_info, int *pty_master_fd,
LaunchFlavor *launch_flavor) {
Status error;
Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
if (!launch_flavor) {
error.SetErrorString("mandatory launch_flavor field was null");
return error;
}
if (log) {
StreamString stream;
stream.Printf("NativeProcessDarwin::%s(): launching with the "
"following launch info:",
__FUNCTION__);
launch_info.Dump(stream, nullptr);
stream.Flush();
log->PutCString(stream.GetString().c_str());
}
// Retrieve the binary name given to us.
char given_path[PATH_MAX];
given_path[0] = '\0';
launch_info.GetExecutableFile().GetPath(given_path, sizeof(given_path));
// Determine the manner in which we'll launch.
*launch_flavor = g_launch_flavor;
if (*launch_flavor == LaunchFlavor::Default) {
// Our default launch method is posix spawn
*launch_flavor = LaunchFlavor::PosixSpawn;
#if defined WITH_FBS
// Check if we have an app bundle, if so launch using BackBoard Services.
if (strstr(given_path, ".app")) {
*launch_flavor = eLaunchFlavorFBS;
}
#elif defined WITH_BKS
// Check if we have an app bundle, if so launch using BackBoard Services.
if (strstr(given_path, ".app")) {
*launch_flavor = eLaunchFlavorBKS;
}
#elif defined WITH_SPRINGBOARD
// Check if we have an app bundle, if so launch using SpringBoard.
if (strstr(given_path, ".app")) {
*launch_flavor = eLaunchFlavorSpringBoard;
}
#endif
}
// Attempt to resolve the binary name to an absolute path.
char resolved_path[PATH_MAX];
resolved_path[0] = '\0';
LLDB_LOGF(log, "%s(): attempting to resolve given binary path: \"%s\"",
__FUNCTION__, given_path);
// If we fail to resolve the path to our executable, then just use what we
// were given and hope for the best
if (!ResolveExecutablePath(given_path, resolved_path,
sizeof(resolved_path))) {
LLDB_LOGF(log,
"%s(): failed to resolve binary path, using "
"what was given verbatim and hoping for the best",
__FUNCTION__);
::strncpy(resolved_path, given_path, sizeof(resolved_path));
} else {
LLDB_LOGF(log, "%s(): resolved given binary path to: \"%s\"", __FUNCTION__,
resolved_path);
}
char launch_err_str[PATH_MAX];
launch_err_str[0] = '\0';
// TODO figure out how to handle QSetProcessEvent
// const char *process_event = ctx.GetProcessEvent();
// Ensure the binary is there.
struct stat path_stat;
if (::stat(resolved_path, &path_stat) == -1) {
error.SetErrorToErrno();
return error;
}
// Fork a child process for debugging
// state_callback(eStateLaunching);
const auto argv = launch_info.GetArguments().GetConstArgumentVector();
const auto envp =
launch_info.GetEnvironmentEntries().GetConstArgumentVector();
switch (*launch_flavor) {
case LaunchFlavor::ForkExec: {
::pid_t pid = LLDB_INVALID_PROCESS_ID;
error = ForkChildForPTraceDebugging(resolved_path, argv, envp, &pid,
pty_master_fd);
if (error.Success()) {
launch_info.SetProcessID(static_cast<lldb::pid_t>(pid));
} else {
// Reset any variables that might have been set during a failed launch
// attempt.
if (pty_master_fd)
*pty_master_fd = -1;
// We're done.
return error;
}
} break;
#ifdef WITH_FBS
case LaunchFlavor::FBS: {
const char *app_ext = strstr(path, ".app");
if (app_ext && (app_ext[4] == '\0' || app_ext[4] == '/')) {
std::string app_bundle_path(path, app_ext + strlen(".app"));
m_flags |= eMachProcessFlagsUsingFBS;
if (BoardServiceLaunchForDebug(app_bundle_path.c_str(), argv, envp,
no_stdio, disable_aslr, event_data,
launch_err) != 0)
return m_pid; // A successful SBLaunchForDebug() returns and assigns a
// non-zero m_pid.
else
break; // We tried a FBS launch, but didn't succeed lets get out
}
} break;
#endif
#ifdef WITH_BKS
case LaunchFlavor::BKS: {
const char *app_ext = strstr(path, ".app");
if (app_ext && (app_ext[4] == '\0' || app_ext[4] == '/')) {
std::string app_bundle_path(path, app_ext + strlen(".app"));
m_flags |= eMachProcessFlagsUsingBKS;
if (BoardServiceLaunchForDebug(app_bundle_path.c_str(), argv, envp,
no_stdio, disable_aslr, event_data,
launch_err) != 0)
return m_pid; // A successful SBLaunchForDebug() returns and assigns a
// non-zero m_pid.
else
break; // We tried a BKS launch, but didn't succeed lets get out
}
} break;
#endif
#ifdef WITH_SPRINGBOARD
case LaunchFlavor::SpringBoard: {
// .../whatever.app/whatever ?
// Or .../com.apple.whatever.app/whatever -- be careful of ".app" in
// "com.apple.whatever" here
const char *app_ext = strstr(path, ".app/");
if (app_ext == NULL) {
// .../whatever.app ?
int len = strlen(path);
if (len > 5) {
if (strcmp(path + len - 4, ".app") == 0) {
app_ext = path + len - 4;
}
}
}
if (app_ext) {
std::string app_bundle_path(path, app_ext + strlen(".app"));
if (SBLaunchForDebug(app_bundle_path.c_str(), argv, envp, no_stdio,
disable_aslr, launch_err) != 0)
return m_pid; // A successful SBLaunchForDebug() returns and assigns a
// non-zero m_pid.
else
break; // We tried a springboard launch, but didn't succeed lets get out
}
} break;
#endif
case LaunchFlavor::PosixSpawn: {
::pid_t pid = LLDB_INVALID_PROCESS_ID;
// Retrieve paths for stdin/stdout/stderr.
cpu_type_t actual_cpu_type = 0;
error = PosixSpawnChildForPTraceDebugging(resolved_path, launch_info, &pid,
&actual_cpu_type);
if (error.Success()) {
launch_info.SetProcessID(static_cast<lldb::pid_t>(pid));
if (pty_master_fd)
*pty_master_fd = launch_info.GetPTY().ReleaseMasterFileDescriptor();
} else {
// Reset any variables that might have been set during a failed launch
// attempt.
if (pty_master_fd)
*pty_master_fd = -1;
// We're done.
return error;
}
break;
}
default:
// Invalid launch flavor.
error.SetErrorStringWithFormat("NativeProcessDarwin::%s(): unknown "
"launch flavor %d",
__FUNCTION__, (int)*launch_flavor);
return error;
}
if (launch_info.GetProcessID() == LLDB_INVALID_PROCESS_ID) {
// If we don't have a valid process ID and no one has set the error, then
// return a generic error.
if (error.Success())
error.SetErrorStringWithFormat("%s(): failed to launch, no reason "
"specified",
__FUNCTION__);
}
// We're done with the launch side of the operation.
return error;
}
}
} // namespaces
|
// (C) Copyright Artyom Beilis 2010.
// Use, modification and distribution are subject to 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)
#ifndef BOOST_CONFIG_PLATFORM_VMS_HPP
#define BOOST_CONFIG_PLATFORM_VMS_HPP
#define BOOST_PLATFORM "OpenVMS"
#undef BOOST_HAS_STDINT_H
#define BOOST_HAS_UNISTD_H
#define BOOST_HAS_NL_TYPES_H
#define BOOST_HAS_GETTIMEOFDAY
#define BOOST_HAS_DIRENT_H
#define BOOST_HAS_PTHREADS
#define BOOST_HAS_NANOSLEEP
#define BOOST_HAS_CLOCK_GETTIME
#define BOOST_HAS_PTHREAD_MUTEXATTR_SETTYPE
#define BOOST_HAS_LOG1P
#define BOOST_HAS_EXPM1
#define BOOST_HAS_THREADS
#undef BOOST_HAS_SCHED_YIELD
#endif
|
/*
* Copyright (C) 2018-2019 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#include "unit_tests/os_interface/windows/hw_info_config_win_tests.h"
#include "core/unit_tests/helpers/debug_manager_state_restore.h"
#include "runtime/os_interface/windows/os_interface.h"
#include "runtime/os_interface/windows/wddm/wddm.h"
#include "instrumentation.h"
namespace NEO {
template <>
cl_unified_shared_memory_capabilities_intel HwInfoConfigHw<IGFX_UNKNOWN>::getHostMemCapabilities() {
return 0;
}
template <>
cl_unified_shared_memory_capabilities_intel HwInfoConfigHw<IGFX_UNKNOWN>::getDeviceMemCapabilities() {
return 0;
}
template <>
cl_unified_shared_memory_capabilities_intel HwInfoConfigHw<IGFX_UNKNOWN>::getSingleDeviceSharedMemCapabilities() {
return 0;
}
template <>
cl_unified_shared_memory_capabilities_intel HwInfoConfigHw<IGFX_UNKNOWN>::getCrossDeviceSharedMemCapabilities() {
return 0;
}
template <>
cl_unified_shared_memory_capabilities_intel HwInfoConfigHw<IGFX_UNKNOWN>::getSharedSystemMemCapabilities() {
return 0;
}
template <>
int HwInfoConfigHw<IGFX_UNKNOWN>::configureHardwareCustom(HardwareInfo *hwInfo, OSInterface *osIface) {
return 0;
}
template <>
void HwInfoConfigHw<IGFX_UNKNOWN>::adjustPlatformForProductFamily(HardwareInfo *hwInfo) {
}
void HwInfoConfigTestWindows::SetUp() {
HwInfoConfigTest::SetUp();
osInterface.reset(new OSInterface());
std::unique_ptr<Wddm> wddm(Wddm::createWddm());
wddm->init(outHwInfo);
}
void HwInfoConfigTestWindows::TearDown() {
HwInfoConfigTest::TearDown();
}
TEST_F(HwInfoConfigTestWindows, givenCorrectParametersWhenConfiguringHwInfoThenReturnSuccess) {
int ret = hwConfig.configureHwInfo(&pInHwInfo, &outHwInfo, osInterface.get());
EXPECT_EQ(0, ret);
}
TEST_F(HwInfoConfigTestWindows, givenCorrectParametersWhenConfiguringHwInfoThenSetFtrSvmCorrectly) {
auto ftrSvm = outHwInfo.featureTable.ftrSVM;
int ret = hwConfig.configureHwInfo(&pInHwInfo, &outHwInfo, osInterface.get());
ASSERT_EQ(0, ret);
EXPECT_EQ(outHwInfo.capabilityTable.ftrSvm, ftrSvm);
}
TEST_F(HwInfoConfigTestWindows, givenInstrumentationForHardwareIsEnabledOrDisabledWhenConfiguringHwInfoThenOverrideItUsingHaveInstrumentation) {
int ret;
outHwInfo.capabilityTable.instrumentationEnabled = false;
ret = hwConfig.configureHwInfo(&pInHwInfo, &outHwInfo, osInterface.get());
ASSERT_EQ(0, ret);
EXPECT_FALSE(outHwInfo.capabilityTable.instrumentationEnabled);
outHwInfo.capabilityTable.instrumentationEnabled = true;
ret = hwConfig.configureHwInfo(&pInHwInfo, &outHwInfo, osInterface.get());
ASSERT_EQ(0, ret);
EXPECT_TRUE(outHwInfo.capabilityTable.instrumentationEnabled == haveInstrumentation);
}
} // namespace NEO
|
// Fill out your copyright notice in the Description page of Project Settings.
#include "GrapplingPoint.h"
// Sets default values
AGrapplingPoint::AGrapplingPoint()
{
// Set this actor to call Tick() every frame. You can turn this off to improve performance if you don't need it.
PrimaryActorTick.bCanEverTick = true;
CollisionSphere = CreateDefaultSubobject<USphereComponent>(TEXT("CollisionSphere"));
SetRootComponent(CollisionSphere);
GrappleMesh = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("GrappleMesh"));
GrappleMesh->SetupAttachment(CollisionSphere);
GrappleWidget = CreateDefaultSubobject<UWidgetComponent>(TEXT("GrappleWidget"));
GrappleWidget->SetupAttachment(GetRootComponent());
RopeOffsetTransform = CreateDefaultSubobject<USceneComponent>(TEXT("RopeOffsetTransform"));
RopeOffsetTransform->SetupAttachment(GetRootComponent());
}
// Called when the game starts or when spawned
void AGrapplingPoint::BeginPlay()
{
Super::BeginPlay();
}
// Called every frame
void AGrapplingPoint::Tick(float DeltaTime)
{
Super::Tick(DeltaTime);
}
void AGrapplingPoint::EnableFocused()
{
bCharacterFocused = true;
}
|
// 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 "base/files/scoped_temp_dir.h"
#include "base/threading/thread.h"
#include "content/browser/browser_thread_impl.h"
#include "content/browser/gpu/shader_disk_cache.h"
#include "content/public/test/test_browser_thread.h"
#include "net/base/test_completion_callback.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace content {
namespace {
const int kDefaultClientId = 42;
const char kCacheKey[] = "key";
const char kCacheValue[] = "cached value";
} // namespace
class ShaderDiskCacheTest : public testing::Test {
public:
ShaderDiskCacheTest()
: cache_thread_(BrowserThread::CACHE, &message_loop_),
io_thread_(BrowserThread::IO, &message_loop_) {
}
virtual ~ShaderDiskCacheTest() {}
const base::FilePath& cache_path() { return temp_dir_.path(); }
void InitCache() {
ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
ShaderCacheFactory::GetInstance()->SetCacheInfo(kDefaultClientId,
cache_path());
}
private:
virtual void TearDown() OVERRIDE {
ShaderCacheFactory::GetInstance()->RemoveCacheInfo(kDefaultClientId);
}
base::ScopedTempDir temp_dir_;
MessageLoopForIO message_loop_;
TestBrowserThread cache_thread_;
TestBrowserThread io_thread_;
DISALLOW_COPY_AND_ASSIGN(ShaderDiskCacheTest);
};
TEST_F(ShaderDiskCacheTest, ClearsCache) {
InitCache();
scoped_refptr<ShaderDiskCache> cache =
ShaderCacheFactory::GetInstance()->Get(kDefaultClientId);
ASSERT_TRUE(cache.get() != NULL);
net::TestCompletionCallback available_cb;
int rv = cache->SetAvailableCallback(available_cb.callback());
ASSERT_EQ(net::OK, available_cb.GetResult(rv));
EXPECT_EQ(0, cache->Size());
cache->Cache(kCacheKey, kCacheValue);
net::TestCompletionCallback complete_cb;
rv = cache->SetCacheCompleteCallback(complete_cb.callback());
ASSERT_EQ(net::OK, complete_cb.GetResult(rv));
EXPECT_EQ(1, cache->Size());
base::Time time;
net::TestCompletionCallback clear_cb;
rv = cache->Clear(time, time, clear_cb.callback());
ASSERT_EQ(net::OK, clear_cb.GetResult(rv));
EXPECT_EQ(0, cache->Size());
};
} // namespace content
|
/**********************************************************************
* File: tordmain.cpp (Formerly textordp.c)
* Description: C++ top level textord code.
* Author: Ray Smith
*
* (C) Copyright 1992, Hewlett-Packard Ltd.
** 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.
*
**********************************************************************/
#define _USE_MATH_DEFINES // for M_PI
#ifdef HAVE_CONFIG_H
# include "config_auto.h"
#endif
#include "tordmain.h"
#include "arrayaccess.h" // for GET_DATA_BYTE
#include "blobbox.h" // for BLOBNBOX_IT, BLOBNBOX, TO_BLOCK, TO_B...
#include "ccstruct.h" // for CCStruct, CCStruct::kXHeightFraction
#include "clst.h" // for CLISTIZE
#include "coutln.h" // for C_OUTLINE_IT, C_OUTLINE_LIST, C_OUTLINE
#include "drawtord.h" // for plot_box_list, to_win, create_to_win
#include "edgblob.h" // for extract_edges
#include "errcode.h" // for ASSERT_HOST, ...
#include "makerow.h" // for textord_test_x, textord_test_y, texto...
#include "ocrblock.h" // for BLOCK_IT, BLOCK, BLOCK_LIST (ptr only)
#include "ocrrow.h" // for ROW, ROW_IT, ROW_LIST, tweak_row_base...
#include "params.h" // for DoubleParam, BoolParam, IntParam
#include "pdblock.h" // for PDBLK
#include "points.h" // for FCOORD, ICOORD
#include "polyblk.h" // for POLY_BLOCK
#include "quadratc.h" // for QUAD_COEFFS
#include "quspline.h" // for QSPLINE, tweak_row_baseline
#include "rect.h" // for TBOX
#include "scrollview.h" // for ScrollView, ScrollView::WHITE
#include "statistc.h" // for STATS
#include "stepblob.h" // for C_BLOB_IT, C_BLOB, C_BLOB_LIST
#include "textord.h" // for Textord, WordWithBox, WordGrid, WordS...
#include "tprintf.h" // for tprintf
#include "werd.h" // for WERD_IT, WERD, WERD_LIST, W_DONT_CHOP
#include <allheaders.h> // for pixDestroy, pixGetHeight, boxCreate
#include <cfloat> // for FLT_MAX
#include <cmath> // for ceil, floor, M_PI
#include <cstdint> // for INT16_MAX, uint32_t, int32_t, int16_t
#include <memory>
namespace tesseract {
#define MAX_NEAREST_DIST 600 // for block skew stats
/**********************************************************************
* SetBlobStrokeWidth
*
* Set the horizontal and vertical stroke widths in the blob.
**********************************************************************/
void SetBlobStrokeWidth(Image pix, BLOBNBOX *blob) {
// Cut the blob rectangle into a Pix.
int pix_height = pixGetHeight(pix);
const TBOX &box = blob->bounding_box();
int width = box.width();
int height = box.height();
Box *blob_pix_box = boxCreate(box.left(), pix_height - box.top(), width, height);
Image pix_blob = pixClipRectangle(pix, blob_pix_box, nullptr);
boxDestroy(&blob_pix_box);
Image dist_pix = pixDistanceFunction(pix_blob, 4, 8, L_BOUNDARY_BG);
pix_blob.destroy();
// Compute the stroke widths.
uint32_t *data = pixGetData(dist_pix);
int wpl = pixGetWpl(dist_pix);
// Horizontal width of stroke.
STATS h_stats(0, width + 1);
for (int y = 0; y < height; ++y) {
uint32_t *pixels = data + y * wpl;
int prev_pixel = 0;
int pixel = GET_DATA_BYTE(pixels, 0);
for (int x = 1; x < width; ++x) {
int next_pixel = GET_DATA_BYTE(pixels, x);
// We are looking for a pixel that is equal to its vertical neighbours,
// yet greater than its left neighbour.
if (prev_pixel < pixel && (y == 0 || pixel == GET_DATA_BYTE(pixels - wpl, x - 1)) &&
(y == height - 1 || pixel == GET_DATA_BYTE(pixels + wpl, x - 1))) {
if (pixel > next_pixel) {
// Single local max, so an odd width.
h_stats.add(pixel * 2 - 1, 1);
} else if (pixel == next_pixel && x + 1 < width && pixel > GET_DATA_BYTE(pixels, x + 1)) {
// Double local max, so an even width.
h_stats.add(pixel * 2, 1);
}
}
prev_pixel = pixel;
pixel = next_pixel;
}
}
// Vertical width of stroke.
STATS v_stats(0, height + 1);
for (int x = 0; x < width; ++x) {
int prev_pixel = 0;
int pixel = GET_DATA_BYTE(data, x);
for (int y = 1; y < height; ++y) {
uint32_t *pixels = data + y * wpl;
int next_pixel = GET_DATA_BYTE(pixels, x);
// We are looking for a pixel that is equal to its horizontal neighbours,
// yet greater than its upper neighbour.
if (prev_pixel < pixel && (x == 0 || pixel == GET_DATA_BYTE(pixels - wpl, x - 1)) &&
(x == width - 1 || pixel == GET_DATA_BYTE(pixels - wpl, x + 1))) {
if (pixel > next_pixel) {
// Single local max, so an odd width.
v_stats.add(pixel * 2 - 1, 1);
} else if (pixel == next_pixel && y + 1 < height &&
pixel > GET_DATA_BYTE(pixels + wpl, x)) {
// Double local max, so an even width.
v_stats.add(pixel * 2, 1);
}
}
prev_pixel = pixel;
pixel = next_pixel;
}
}
dist_pix.destroy();
// Store the horizontal and vertical width in the blob, keeping both
// widths if there is enough information, otherwise only the one with
// the most samples.
// If there are insufficient samples, store zero, rather than using
// 2*area/perimeter, as the numbers that gives do not match the numbers
// from the distance method.
if (h_stats.get_total() >= (width + height) / 4) {
blob->set_horz_stroke_width(h_stats.ile(0.5f));
if (v_stats.get_total() >= (width + height) / 4) {
blob->set_vert_stroke_width(v_stats.ile(0.5f));
} else {
blob->set_vert_stroke_width(0.0f);
}
} else {
if (v_stats.get_total() >= (width + height) / 4 || v_stats.get_total() > h_stats.get_total()) {
blob->set_horz_stroke_width(0.0f);
blob->set_vert_stroke_width(v_stats.ile(0.5f));
} else {
blob->set_horz_stroke_width(h_stats.get_total() > 2 ? h_stats.ile(0.5f) : 0.0f);
blob->set_vert_stroke_width(0.0f);
}
}
}
/**********************************************************************
* assign_blobs_to_blocks2
*
* Make a list of TO_BLOCKs for portrait and landscape orientation.
**********************************************************************/
void assign_blobs_to_blocks2(Image pix,
BLOCK_LIST *blocks, // blocks to process
TO_BLOCK_LIST *port_blocks) { // output list
BLOCK *block; // current block
BLOBNBOX *newblob; // created blob
C_BLOB *blob; // current blob
BLOCK_IT block_it = blocks;
C_BLOB_IT blob_it; // iterator
BLOBNBOX_IT port_box_it; // iterator
// destination iterator
TO_BLOCK_IT port_block_it = port_blocks;
TO_BLOCK *port_block; // created block
for (block_it.mark_cycle_pt(); !block_it.cycled_list(); block_it.forward()) {
block = block_it.data();
port_block = new TO_BLOCK(block);
// Convert the good outlines to block->blob_list
port_box_it.set_to_list(&port_block->blobs);
blob_it.set_to_list(block->blob_list());
for (blob_it.mark_cycle_pt(); !blob_it.cycled_list(); blob_it.forward()) {
blob = blob_it.extract();
newblob = new BLOBNBOX(blob); // Convert blob to BLOBNBOX.
newblob->set_owns_cblob(true);
SetBlobStrokeWidth(pix, newblob);
port_box_it.add_after_then_move(newblob);
}
// Put the rejected outlines in block->noise_blobs, which allows them to
// be reconsidered and sorted back into rows and recover outlines mistakenly
// rejected.
port_box_it.set_to_list(&port_block->noise_blobs);
blob_it.set_to_list(block->reject_blobs());
for (blob_it.mark_cycle_pt(); !blob_it.cycled_list(); blob_it.forward()) {
blob = blob_it.extract();
newblob = new BLOBNBOX(blob); // Convert blob to BLOBNBOX.
SetBlobStrokeWidth(pix, newblob);
port_box_it.add_after_then_move(newblob);
}
port_block_it.add_after_then_move(port_block);
}
}
/**********************************************************************
* find_components
*
* Find the C_OUTLINEs of the connected components in each block, put them
* in C_BLOBs, and filter them by size, putting the different size
* grades on different lists in the matching TO_BLOCK in to_blocks.
**********************************************************************/
void Textord::find_components(Image pix, BLOCK_LIST *blocks, TO_BLOCK_LIST *to_blocks) {
int width = pixGetWidth(pix);
int height = pixGetHeight(pix);
if (width > INT16_MAX || height > INT16_MAX) {
tprintf("Input image too large! (%d, %d)\n", width, height);
return; // Can't handle it.
}
BLOCK_IT block_it(blocks); // iterator
for (block_it.mark_cycle_pt(); !block_it.cycled_list(); block_it.forward()) {
BLOCK *block = block_it.data();
if (block->pdblk.poly_block() == nullptr || block->pdblk.poly_block()->IsText()) {
extract_edges(pix, block);
}
}
assign_blobs_to_blocks2(pix, blocks, to_blocks);
ICOORD page_tr(width, height);
filter_blobs(page_tr, to_blocks, !textord_test_landscape);
}
/**********************************************************************
* filter_blobs
*
* Sort the blobs into sizes in all the blocks for later work.
**********************************************************************/
void Textord::filter_blobs(ICOORD page_tr, // top right
TO_BLOCK_LIST *blocks, // output list
bool testing_on) { // for plotting
TO_BLOCK_IT block_it = blocks; // destination iterator
TO_BLOCK *block; // created block
#ifndef GRAPHICS_DISABLED
if (to_win != nullptr) {
to_win->Clear();
}
#endif // !GRAPHICS_DISABLED
for (block_it.mark_cycle_pt(); !block_it.cycled_list(); block_it.forward()) {
block = block_it.data();
block->line_size = filter_noise_blobs(&block->blobs, &block->noise_blobs, &block->small_blobs,
&block->large_blobs);
if (block->line_size == 0) {
block->line_size = 1;
}
block->line_spacing =
block->line_size *
(tesseract::CCStruct::kDescenderFraction + tesseract::CCStruct::kXHeightFraction +
2 * tesseract::CCStruct::kAscenderFraction) /
tesseract::CCStruct::kXHeightFraction;
block->line_size *= textord_min_linesize;
block->max_blob_size = block->line_size * textord_excess_blobsize;
#ifndef GRAPHICS_DISABLED
if (textord_show_blobs && testing_on) {
if (to_win == nullptr) {
create_to_win(page_tr);
}
block->plot_graded_blobs(to_win);
}
if (textord_show_boxes && testing_on) {
if (to_win == nullptr) {
create_to_win(page_tr);
}
plot_box_list(to_win, &block->noise_blobs, ScrollView::WHITE);
plot_box_list(to_win, &block->small_blobs, ScrollView::WHITE);
plot_box_list(to_win, &block->large_blobs, ScrollView::WHITE);
plot_box_list(to_win, &block->blobs, ScrollView::WHITE);
}
#endif // !GRAPHICS_DISABLED
}
}
/**********************************************************************
* filter_noise_blobs
*
* Move small blobs to a separate list.
**********************************************************************/
float Textord::filter_noise_blobs(BLOBNBOX_LIST *src_list, // original list
BLOBNBOX_LIST *noise_list, // noise list
BLOBNBOX_LIST *small_list, // small blobs
BLOBNBOX_LIST *large_list) { // large blobs
int16_t height; // height of blob
int16_t width; // of blob
BLOBNBOX *blob; // current blob
float initial_x; // first guess
BLOBNBOX_IT src_it = src_list; // iterators
BLOBNBOX_IT noise_it = noise_list;
BLOBNBOX_IT small_it = small_list;
BLOBNBOX_IT large_it = large_list;
STATS size_stats(0, MAX_NEAREST_DIST);
// blob heights
float min_y; // size limits
float max_y;
float max_x;
float max_height; // of good blobs
for (src_it.mark_cycle_pt(); !src_it.cycled_list(); src_it.forward()) {
blob = src_it.data();
if (blob->bounding_box().height() < textord_max_noise_size) {
noise_it.add_after_then_move(src_it.extract());
} else if (blob->enclosed_area() >= blob->bounding_box().height() *
blob->bounding_box().width() *
textord_noise_area_ratio) {
small_it.add_after_then_move(src_it.extract());
}
}
for (src_it.mark_cycle_pt(); !src_it.cycled_list(); src_it.forward()) {
size_stats.add(src_it.data()->bounding_box().height(), 1);
}
initial_x = size_stats.ile(textord_initialx_ile);
max_y = ceil(initial_x *
(tesseract::CCStruct::kDescenderFraction + tesseract::CCStruct::kXHeightFraction +
2 * tesseract::CCStruct::kAscenderFraction) /
tesseract::CCStruct::kXHeightFraction);
min_y = floor(initial_x / 2);
max_x = ceil(initial_x * textord_width_limit);
small_it.move_to_first();
for (small_it.mark_cycle_pt(); !small_it.cycled_list(); small_it.forward()) {
height = small_it.data()->bounding_box().height();
if (height > max_y) {
large_it.add_after_then_move(small_it.extract());
} else if (height >= min_y) {
src_it.add_after_then_move(small_it.extract());
}
}
size_stats.clear();
for (src_it.mark_cycle_pt(); !src_it.cycled_list(); src_it.forward()) {
height = src_it.data()->bounding_box().height();
width = src_it.data()->bounding_box().width();
if (height < min_y) {
small_it.add_after_then_move(src_it.extract());
} else if (height > max_y || width > max_x) {
large_it.add_after_then_move(src_it.extract());
} else {
size_stats.add(height, 1);
}
}
max_height = size_stats.ile(textord_initialasc_ile);
// tprintf("max_y=%g, min_y=%g, initial_x=%g, max_height=%g,",
// max_y,min_y,initial_x,max_height);
max_height *= tesseract::CCStruct::kXHeightCapRatio;
if (max_height > initial_x) {
initial_x = max_height;
}
// tprintf(" ret=%g\n",initial_x);
return initial_x;
}
// Fixes the block so it obeys all the rules:
// Must have at least one ROW.
// Must have at least one WERD.
// WERDs contain a fake blob.
void Textord::cleanup_nontext_block(BLOCK *block) {
// Non-text blocks must contain at least one row.
ROW_IT row_it(block->row_list());
if (row_it.empty()) {
const TBOX &box = block->pdblk.bounding_box();
float height = box.height();
int32_t xstarts[2] = {box.left(), box.right()};
double coeffs[3] = {0.0, 0.0, static_cast<double>(box.bottom())};
ROW *row = new ROW(1, xstarts, coeffs, height / 2.0f, height / 4.0f, height / 4.0f, 0, 1);
row_it.add_after_then_move(row);
}
// Each row must contain at least one word.
for (row_it.mark_cycle_pt(); !row_it.cycled_list(); row_it.forward()) {
ROW *row = row_it.data();
WERD_IT w_it(row->word_list());
if (w_it.empty()) {
// Make a fake blob to put in the word.
TBOX box = block->row_list()->singleton() ? block->pdblk.bounding_box() : row->bounding_box();
C_BLOB *blob = C_BLOB::FakeBlob(box);
C_BLOB_LIST blobs;
C_BLOB_IT blob_it(&blobs);
blob_it.add_after_then_move(blob);
WERD *word = new WERD(&blobs, 0, nullptr);
w_it.add_after_then_move(word);
}
// Each word must contain a fake blob.
for (w_it.mark_cycle_pt(); !w_it.cycled_list(); w_it.forward()) {
WERD *word = w_it.data();
// Just assert that this is true, as it would be useful to find
// out why it isn't.
ASSERT_HOST(!word->cblob_list()->empty());
}
row->recalc_bounding_box();
}
}
/**********************************************************************
* cleanup_blocks
*
* Delete empty blocks, rows from the page.
**********************************************************************/
void Textord::cleanup_blocks(bool clean_noise, BLOCK_LIST *blocks) {
BLOCK_IT block_it = blocks; // iterator
ROW_IT row_it; // row iterator
int num_rows = 0;
int num_rows_all = 0;
int num_blocks = 0;
int num_blocks_all = 0;
for (block_it.mark_cycle_pt(); !block_it.cycled_list(); block_it.forward()) {
BLOCK *block = block_it.data();
if (block->pdblk.poly_block() != nullptr && !block->pdblk.poly_block()->IsText()) {
cleanup_nontext_block(block);
continue;
}
num_rows = 0;
num_rows_all = 0;
if (clean_noise) {
row_it.set_to_list(block->row_list());
for (row_it.mark_cycle_pt(); !row_it.cycled_list(); row_it.forward()) {
ROW *row = row_it.data();
++num_rows_all;
clean_small_noise_from_words(row);
if ((textord_noise_rejrows && !row->word_list()->empty() && clean_noise_from_row(row)) ||
row->word_list()->empty()) {
delete row_it.extract(); // lose empty row.
} else {
if (textord_noise_rejwords) {
clean_noise_from_words(row_it.data());
}
if (textord_blshift_maxshift >= 0) {
tweak_row_baseline(row, textord_blshift_maxshift, textord_blshift_xfraction);
}
++num_rows;
}
}
}
if (block->row_list()->empty()) {
delete block_it.extract(); // Lose empty text blocks.
} else {
++num_blocks;
}
++num_blocks_all;
if (textord_noise_debug) {
tprintf("cleanup_blocks: # rows = %d / %d\n", num_rows, num_rows_all);
}
}
if (textord_noise_debug) {
tprintf("cleanup_blocks: # blocks = %d / %d\n", num_blocks, num_blocks_all);
}
}
/**********************************************************************
* clean_noise_from_row
*
* Move blobs of words from rows of garbage into the reject blobs list.
**********************************************************************/
bool Textord::clean_noise_from_row( // remove empties
ROW *row // row to clean
) {
bool testing_on;
TBOX blob_box; // bounding box
C_BLOB *blob; // current blob
C_OUTLINE *outline; // current outline
WERD *word; // current word
int32_t blob_size; // biggest size
int32_t trans_count = 0; // no of transitions
int32_t trans_threshold; // noise tolerance
int32_t dot_count; // small objects
int32_t norm_count; // normal objects
int32_t super_norm_count; // real char-like
// words of row
WERD_IT word_it = row->word_list();
C_BLOB_IT blob_it; // blob iterator
C_OUTLINE_IT out_it; // outline iterator
testing_on = textord_test_y > row->base_line(textord_test_x) && textord_show_blobs &&
textord_test_y < row->base_line(textord_test_x) + row->x_height();
dot_count = 0;
norm_count = 0;
super_norm_count = 0;
for (word_it.mark_cycle_pt(); !word_it.cycled_list(); word_it.forward()) {
word = word_it.data(); // current word
// blobs in word
blob_it.set_to_list(word->cblob_list());
for (blob_it.mark_cycle_pt(); !blob_it.cycled_list(); blob_it.forward()) {
blob = blob_it.data();
if (!word->flag(W_DONT_CHOP)) {
// get outlines
out_it.set_to_list(blob->out_list());
for (out_it.mark_cycle_pt(); !out_it.cycled_list(); out_it.forward()) {
outline = out_it.data();
blob_box = outline->bounding_box();
blob_size = blob_box.width() > blob_box.height() ? blob_box.width() : blob_box.height();
if (blob_size < textord_noise_sizelimit * row->x_height()) {
dot_count++; // count small outlines
}
if (!outline->child()->empty() &&
blob_box.height() < (1 + textord_noise_syfract) * row->x_height() &&
blob_box.height() > (1 - textord_noise_syfract) * row->x_height() &&
blob_box.width() < (1 + textord_noise_sxfract) * row->x_height() &&
blob_box.width() > (1 - textord_noise_sxfract) * row->x_height()) {
super_norm_count++; // count small outlines
}
}
} else {
super_norm_count++;
}
blob_box = blob->bounding_box();
blob_size = blob_box.width() > blob_box.height() ? blob_box.width() : blob_box.height();
if (blob_size >= textord_noise_sizelimit * row->x_height() &&
blob_size < row->x_height() * 2) {
trans_threshold = blob_size / textord_noise_sizefraction;
trans_count = blob->count_transitions(trans_threshold);
if (trans_count < textord_noise_translimit) {
norm_count++;
}
} else if (blob_box.height() > row->x_height() * 2 &&
(!word_it.at_first() || !blob_it.at_first())) {
dot_count += 2;
}
if (testing_on) {
tprintf("Blob at (%d,%d) -> (%d,%d), ols=%d, tc=%d, bldiff=%g\n", blob_box.left(),
blob_box.bottom(), blob_box.right(), blob_box.top(), blob->out_list()->length(),
trans_count, blob_box.bottom() - row->base_line(blob_box.left()));
}
}
}
if (textord_noise_debug) {
tprintf("Row ending at (%d,%g):", blob_box.right(), row->base_line(blob_box.right()));
tprintf(" R=%g, dc=%d, nc=%d, %s\n",
norm_count > 0 ? static_cast<float>(dot_count) / norm_count : 9999, dot_count,
norm_count,
dot_count > norm_count * textord_noise_normratio && dot_count > 2 ? "REJECTED"
: "ACCEPTED");
}
return super_norm_count < textord_noise_sncount &&
dot_count > norm_count * textord_noise_rowratio && dot_count > 2;
}
/**********************************************************************
* clean_noise_from_words
*
* Move blobs of words from rows of garbage into the reject blobs list.
**********************************************************************/
void Textord::clean_noise_from_words( // remove empties
ROW *row // row to clean
) {
TBOX blob_box; // bounding box
C_BLOB *blob; // current blob
C_OUTLINE *outline; // current outline
WERD *word; // current word
int32_t blob_size; // biggest size
int32_t trans_count; // no of transitions
int32_t trans_threshold; // noise tolerance
int32_t dot_count; // small objects
int32_t norm_count; // normal objects
int32_t dud_words; // number discarded
int32_t ok_words; // number remaining
int32_t word_index; // current word
// words of row
WERD_IT word_it = row->word_list();
C_BLOB_IT blob_it; // blob iterator
C_OUTLINE_IT out_it; // outline iterator
ok_words = word_it.length();
if (ok_words == 0 || textord_no_rejects) {
return;
}
// was it chucked
std::vector<int8_t> word_dud(ok_words);
dud_words = 0;
ok_words = 0;
word_index = 0;
for (word_it.mark_cycle_pt(); !word_it.cycled_list(); word_it.forward()) {
word = word_it.data(); // current word
dot_count = 0;
norm_count = 0;
// blobs in word
blob_it.set_to_list(word->cblob_list());
for (blob_it.mark_cycle_pt(); !blob_it.cycled_list(); blob_it.forward()) {
blob = blob_it.data();
if (!word->flag(W_DONT_CHOP)) {
// get outlines
out_it.set_to_list(blob->out_list());
for (out_it.mark_cycle_pt(); !out_it.cycled_list(); out_it.forward()) {
outline = out_it.data();
blob_box = outline->bounding_box();
blob_size = blob_box.width() > blob_box.height() ? blob_box.width() : blob_box.height();
if (blob_size < textord_noise_sizelimit * row->x_height()) {
dot_count++; // count small outlines
}
if (!outline->child()->empty() &&
blob_box.height() < (1 + textord_noise_syfract) * row->x_height() &&
blob_box.height() > (1 - textord_noise_syfract) * row->x_height() &&
blob_box.width() < (1 + textord_noise_sxfract) * row->x_height() &&
blob_box.width() > (1 - textord_noise_sxfract) * row->x_height()) {
norm_count++; // count small outlines
}
}
} else {
norm_count++;
}
blob_box = blob->bounding_box();
blob_size = blob_box.width() > blob_box.height() ? blob_box.width() : blob_box.height();
if (blob_size >= textord_noise_sizelimit * row->x_height() &&
blob_size < row->x_height() * 2) {
trans_threshold = blob_size / textord_noise_sizefraction;
trans_count = blob->count_transitions(trans_threshold);
if (trans_count < textord_noise_translimit) {
norm_count++;
}
} else if (blob_box.height() > row->x_height() * 2 &&
(!word_it.at_first() || !blob_it.at_first())) {
dot_count += 2;
}
}
if (dot_count > 2 && !word->flag(W_REP_CHAR)) {
if (dot_count > norm_count * textord_noise_normratio * 2) {
word_dud[word_index] = 2;
} else if (dot_count > norm_count * textord_noise_normratio) {
word_dud[word_index] = 1;
} else {
word_dud[word_index] = 0;
}
} else {
word_dud[word_index] = 0;
}
if (word_dud[word_index] == 2) {
dud_words++;
} else {
ok_words++;
}
word_index++;
}
word_index = 0;
for (word_it.mark_cycle_pt(); !word_it.cycled_list(); word_it.forward()) {
if (word_dud[word_index] == 2 || (word_dud[word_index] == 1 && dud_words > ok_words)) {
word = word_it.data(); // Current word.
// Previously we threw away the entire word.
// Now just aggressively throw all small blobs into the reject list, where
// the classifier can decide whether they are actually needed.
word->CleanNoise(textord_noise_sizelimit * row->x_height());
}
word_index++;
}
}
// Remove outlines that are a tiny fraction in either width or height
// of the word height.
void Textord::clean_small_noise_from_words(ROW *row) {
WERD_IT word_it(row->word_list());
for (word_it.mark_cycle_pt(); !word_it.cycled_list(); word_it.forward()) {
WERD *word = word_it.data();
int min_size = static_cast<int>(textord_noise_hfract * word->bounding_box().height() + 0.5);
C_BLOB_IT blob_it(word->cblob_list());
for (blob_it.mark_cycle_pt(); !blob_it.cycled_list(); blob_it.forward()) {
C_BLOB *blob = blob_it.data();
C_OUTLINE_IT out_it(blob->out_list());
for (out_it.mark_cycle_pt(); !out_it.cycled_list(); out_it.forward()) {
C_OUTLINE *outline = out_it.data();
outline->RemoveSmallRecursive(min_size, &out_it);
}
if (blob->out_list()->empty()) {
delete blob_it.extract();
}
}
if (word->cblob_list()->empty()) {
if (!word_it.at_last()) {
// The next word is no longer a fuzzy non space if it was before,
// since the word before is about to be deleted.
WERD *next_word = word_it.data_relative(1);
if (next_word->flag(W_FUZZY_NON)) {
next_word->set_flag(W_FUZZY_NON, false);
}
}
delete word_it.extract();
}
}
}
// Local struct to hold a group of blocks.
struct BlockGroup {
BlockGroup() : rotation(1.0f, 0.0f), angle(0.0f), min_xheight(1.0f) {}
explicit BlockGroup(BLOCK *block)
: bounding_box(block->pdblk.bounding_box())
, rotation(block->re_rotation())
, angle(block->re_rotation().angle())
, min_xheight(block->x_height()) {
blocks.push_back(block);
}
// Union of block bounding boxes.
TBOX bounding_box;
// Common rotation of the blocks.
FCOORD rotation;
// Angle of rotation.
float angle;
// Min xheight of the blocks.
float min_xheight;
// Collection of borrowed pointers to the blocks in the group.
std::vector<BLOCK *> blocks;
};
// Groups blocks by rotation, then, for each group, makes a WordGrid and calls
// TransferDiacriticsToWords to copy the diacritic blobs to the most
// appropriate words in the group of blocks. Source blobs are not touched.
void Textord::TransferDiacriticsToBlockGroups(BLOBNBOX_LIST *diacritic_blobs, BLOCK_LIST *blocks) {
// Angle difference larger than this is too much to consider equal.
// They should only be in multiples of M_PI/2 anyway.
const double kMaxAngleDiff = 0.01; // About 0.6 degrees.
std::vector<std::unique_ptr<BlockGroup>> groups;
BLOCK_IT bk_it(blocks);
for (bk_it.mark_cycle_pt(); !bk_it.cycled_list(); bk_it.forward()) {
BLOCK *block = bk_it.data();
if (block->pdblk.poly_block() != nullptr && !block->pdblk.poly_block()->IsText()) {
continue;
}
// Linear search of the groups to find a matching rotation.
float block_angle = block->re_rotation().angle();
int best_g = 0;
float best_angle_diff = FLT_MAX;
for (const auto &group : groups) {
double angle_diff = fabs(block_angle - group->angle);
if (angle_diff > M_PI) {
angle_diff = fabs(angle_diff - 2.0 * M_PI);
}
if (angle_diff < best_angle_diff) {
best_angle_diff = angle_diff;
best_g = &group - &groups[0];
}
}
if (best_angle_diff > kMaxAngleDiff) {
groups.push_back(std::make_unique<BlockGroup>(block));
} else {
groups[best_g]->blocks.push_back(block);
groups[best_g]->bounding_box += block->pdblk.bounding_box();
float x_height = block->x_height();
if (x_height < groups[best_g]->min_xheight) {
groups[best_g]->min_xheight = x_height;
}
}
}
// Now process each group of blocks.
std::vector<std::unique_ptr<WordWithBox>> word_ptrs;
for (const auto &group : groups) {
if (group->bounding_box.null_box()) {
continue;
}
WordGrid word_grid(group->min_xheight, group->bounding_box.botleft(),
group->bounding_box.topright());
for (auto b : group->blocks) {
ROW_IT row_it(b->row_list());
for (row_it.mark_cycle_pt(); !row_it.cycled_list(); row_it.forward()) {
ROW *row = row_it.data();
// Put the words of the row into the grid.
WERD_IT w_it(row->word_list());
for (w_it.mark_cycle_pt(); !w_it.cycled_list(); w_it.forward()) {
WERD *word = w_it.data();
auto box_word = std::make_unique<WordWithBox>(word);
word_grid.InsertBBox(true, true, box_word.get());
// Save the pointer where it will be auto-deleted.
word_ptrs.emplace_back(std::move(box_word));
}
}
}
FCOORD rotation = group->rotation;
// Make it a forward rotation that will transform blob coords to block.
rotation.set_y(-rotation.y());
TransferDiacriticsToWords(diacritic_blobs, rotation, &word_grid);
}
}
// Places a copy of blobs that are near a word (after applying rotation to the
// blob) in the most appropriate word, unless there is doubt, in which case a
// blob can end up in two words. Source blobs are not touched.
void Textord::TransferDiacriticsToWords(BLOBNBOX_LIST *diacritic_blobs, const FCOORD &rotation,
WordGrid *word_grid) {
WordSearch ws(word_grid);
BLOBNBOX_IT b_it(diacritic_blobs);
// Apply rotation to each blob before finding the nearest words. The rotation
// allows us to only consider above/below placement and not left/right on
// vertical text, because all text is horizontal here.
for (b_it.mark_cycle_pt(); !b_it.cycled_list(); b_it.forward()) {
BLOBNBOX *blobnbox = b_it.data();
TBOX blob_box = blobnbox->bounding_box();
blob_box.rotate(rotation);
ws.StartRectSearch(blob_box);
// Above/below refer to word position relative to diacritic. Since some
// scripts eg Kannada/Telugu habitually put diacritics below words, and
// others eg Thai/Vietnamese/Latin put most diacritics above words, try
// for both if there isn't much in it.
WordWithBox *best_above_word = nullptr;
WordWithBox *best_below_word = nullptr;
int best_above_distance = 0;
int best_below_distance = 0;
for (WordWithBox *word = ws.NextRectSearch(); word != nullptr; word = ws.NextRectSearch()) {
if (word->word()->flag(W_REP_CHAR)) {
continue;
}
TBOX word_box = word->true_bounding_box();
int x_distance = blob_box.x_gap(word_box);
int y_distance = blob_box.y_gap(word_box);
if (x_distance > 0) {
// Arbitrarily divide x-distance by 2 if there is a major y overlap,
// and the word is to the left of the diacritic. If the
// diacritic is a dropped broken character between two words, this will
// help send all the pieces to a single word, instead of splitting them
// over the 2 words.
if (word_box.major_y_overlap(blob_box) && blob_box.left() > word_box.right()) {
x_distance /= 2;
}
y_distance += x_distance;
}
if (word_box.y_middle() > blob_box.y_middle() &&
(best_above_word == nullptr || y_distance < best_above_distance)) {
best_above_word = word;
best_above_distance = y_distance;
}
if (word_box.y_middle() <= blob_box.y_middle() &&
(best_below_word == nullptr || y_distance < best_below_distance)) {
best_below_word = word;
best_below_distance = y_distance;
}
}
bool above_good = best_above_word != nullptr &&
(best_below_word == nullptr ||
best_above_distance < best_below_distance + blob_box.height());
bool below_good = best_below_word != nullptr && best_below_word != best_above_word &&
(best_above_word == nullptr ||
best_below_distance < best_above_distance + blob_box.height());
if (below_good) {
C_BLOB *copied_blob = C_BLOB::deep_copy(blobnbox->cblob());
copied_blob->rotate(rotation);
// Put the blob into the word's reject blobs list.
C_BLOB_IT blob_it(best_below_word->RejBlobs());
blob_it.add_to_end(copied_blob);
}
if (above_good) {
C_BLOB *copied_blob = C_BLOB::deep_copy(blobnbox->cblob());
copied_blob->rotate(rotation);
// Put the blob into the word's reject blobs list.
C_BLOB_IT blob_it(best_above_word->RejBlobs());
blob_it.add_to_end(copied_blob);
}
}
}
/**********************************************************************
* tweak_row_baseline
*
* Shift baseline to fit the blobs more accurately where they are
* close enough.
**********************************************************************/
void tweak_row_baseline(ROW *row, double blshift_maxshift, double blshift_xfraction) {
TBOX blob_box; // bounding box
C_BLOB *blob; // current blob
WERD *word; // current word
int32_t blob_count; // no of blobs
int32_t src_index; // source segment
int32_t dest_index; // destination segment
float ydiff; // baseline error
float x_centre; // centre of blob
// words of row
WERD_IT word_it = row->word_list();
C_BLOB_IT blob_it; // blob iterator
blob_count = 0;
for (word_it.mark_cycle_pt(); !word_it.cycled_list(); word_it.forward()) {
word = word_it.data(); // current word
// get total blobs
blob_count += word->cblob_list()->length();
}
if (blob_count == 0) {
return;
}
// spline segments
std::vector<int32_t> xstarts(blob_count + row->baseline.segments + 1);
// spline coeffs
std::vector<double> coeffs((blob_count + row->baseline.segments) * 3);
src_index = 0;
dest_index = 0;
xstarts[0] = row->baseline.xcoords[0];
for (word_it.mark_cycle_pt(); !word_it.cycled_list(); word_it.forward()) {
word = word_it.data(); // current word
// blobs in word
blob_it.set_to_list(word->cblob_list());
for (blob_it.mark_cycle_pt(); !blob_it.cycled_list(); blob_it.forward()) {
blob = blob_it.data();
blob_box = blob->bounding_box();
x_centre = (blob_box.left() + blob_box.right()) / 2.0;
ydiff = blob_box.bottom() - row->base_line(x_centre);
if (ydiff < 0) {
ydiff = -ydiff / row->x_height();
} else {
ydiff = ydiff / row->x_height();
}
if (ydiff < blshift_maxshift && blob_box.height() / row->x_height() > blshift_xfraction) {
if (xstarts[dest_index] >= x_centre) {
xstarts[dest_index] = blob_box.left();
}
coeffs[dest_index * 3] = 0;
coeffs[dest_index * 3 + 1] = 0;
coeffs[dest_index * 3 + 2] = blob_box.bottom();
// shift it
dest_index++;
xstarts[dest_index] = blob_box.right() + 1;
} else {
if (xstarts[dest_index] <= x_centre) {
while (row->baseline.xcoords[src_index + 1] <= x_centre &&
src_index < row->baseline.segments - 1) {
if (row->baseline.xcoords[src_index + 1] > xstarts[dest_index]) {
coeffs[dest_index * 3] = row->baseline.quadratics[src_index].a;
coeffs[dest_index * 3 + 1] = row->baseline.quadratics[src_index].b;
coeffs[dest_index * 3 + 2] = row->baseline.quadratics[src_index].c;
dest_index++;
xstarts[dest_index] = row->baseline.xcoords[src_index + 1];
}
src_index++;
}
coeffs[dest_index * 3] = row->baseline.quadratics[src_index].a;
coeffs[dest_index * 3 + 1] = row->baseline.quadratics[src_index].b;
coeffs[dest_index * 3 + 2] = row->baseline.quadratics[src_index].c;
dest_index++;
xstarts[dest_index] = row->baseline.xcoords[src_index + 1];
}
}
}
}
while (src_index < row->baseline.segments &&
row->baseline.xcoords[src_index + 1] <= xstarts[dest_index]) {
src_index++;
}
while (src_index < row->baseline.segments) {
coeffs[dest_index * 3] = row->baseline.quadratics[src_index].a;
coeffs[dest_index * 3 + 1] = row->baseline.quadratics[src_index].b;
coeffs[dest_index * 3 + 2] = row->baseline.quadratics[src_index].c;
dest_index++;
src_index++;
xstarts[dest_index] = row->baseline.xcoords[src_index];
}
// turn to spline
row->baseline = QSPLINE(dest_index, &xstarts[0], &coeffs[0]);
}
} // namespace tesseract
|
#pragma once
// ARKSurvivalEvolved (329.9) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "ARKSurvivalEvolved_WyvernAnimBlueprint_structs.hpp"
namespace sdk
{
//---------------------------------------------------------------------------
//Classes
//---------------------------------------------------------------------------
// AnimBlueprintGeneratedClass WyvernAnimBlueprint.WyvernAnimBlueprint_C
// 0x0000 (0x15C1 - 0x15C1)
class UWyvernAnimBlueprint_C : public UDinoBlueprintBase_RootTransformIK_FullFlight_C
{
public:
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("AnimBlueprintGeneratedClass WyvernAnimBlueprint.WyvernAnimBlueprint_C");
return ptr;
}
void ExecuteUbergraph_WyvernAnimBlueprint(int EntryPoint);
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
|
/**
* @file Tests.cpp
*
* @brief Test routines for Zerocoin.
*
* @author Ian Miers, Christina Garman and Matthew Green
* @date June 2013
*
* @copyright Copyright 2013 Ian Miers, Christina Garman and Matthew Green
* @license This project is released under the MIT license.
**/
// Copyright (c) 2017-2018 The BITCORN developers
#include <boost/test/unit_test.hpp>
#include <string>
#include <iostream>
#include <fstream>
#include <cmath>
// #include <curses.h>
#include <exception>
#include "streams.h"
#include "libzerocoin/ParamGeneration.h"
#include "libzerocoin/Denominations.h"
#include "libzerocoin/Coin.h"
#include "libzerocoin/CoinSpend.h"
#include "libzerocoin/Accumulator.h"
#include "test_bitcorn.h"
#define COLOR_STR_GREEN "\033[32m"
#define COLOR_STR_NORMAL "\033[0m"
#define COLOR_STR_RED "\033[31m"
#define TESTS_COINS_TO_ACCUMULATE 10
#define NON_PRIME_TESTS 100
// Global test counters
uint32_t gNumTests = 0;
uint32_t gSuccessfulTests = 0;
// Proof size
uint32_t gProofSize = 0;
uint32_t gCoinSize = 0;
uint32_t gSerialNumberSize = 0;
// Global coin array
libzerocoin::PrivateCoin *gCoins[TESTS_COINS_TO_ACCUMULATE];
// Global params
libzerocoin::ZerocoinParams *g_Params;
//////////
// Utility routines
//////////
void
LogTestResult(std::string testName, bool (*testPtr)())
{
std::string colorGreen(COLOR_STR_GREEN);
std::string colorNormal(COLOR_STR_NORMAL);
std::string colorRed(COLOR_STR_RED);
std::cout << "Testing if " << testName << "..." << std::endl;
bool testResult = testPtr();
if (testResult == true) {
std::cout << "\t" << colorGreen << "[PASS]" << colorNormal << std::endl;
gSuccessfulTests++;
} else {
std::cout << colorRed << "\t[FAIL]" << colorNormal << std::endl;
}
gNumTests++;
}
CBigNum
GetTestModulus()
{
static CBigNum testModulus(0);
// TODO: should use a hard-coded RSA modulus for testing
if (!testModulus) {
CBigNum p, q;
// Note: we are NOT using safe primes for testing because
// they take too long to generate. Don't do this in real
// usage. See the paramgen utility for better code.
p = CBigNum::generatePrime(1024, false);
q = CBigNum::generatePrime(1024, false);
testModulus = p * q;
}
return testModulus;
}
//////////
// Test routines
//////////
bool
Test_GenRSAModulus()
{
CBigNum result = GetTestModulus();
if (!result) {
return false;
}
else {
return true;
}
}
bool
Test_CalcParamSizes()
{
bool result = true;
#if 0
uint32_t pLen, qLen;
try {
calculateGroupParamLengths(4000, 80, &pLen, &qLen);
if (pLen < 1024 || qLen < 256) {
result = false;
}
calculateGroupParamLengths(4000, 96, &pLen, &qLen);
if (pLen < 2048 || qLen < 256) {
result = false;
}
calculateGroupParamLengths(4000, 112, &pLen, &qLen);
if (pLen < 3072 || qLen < 320) {
result = false;
}
calculateGroupParamLengths(4000, 120, &pLen, &qLen);
if (pLen < 3072 || qLen < 320) {
result = false;
}
calculateGroupParamLengths(4000, 128, &pLen, &qLen);
if (pLen < 3072 || qLen < 320) {
result = false;
}
} catch (exception &e) {
result = false;
}
#endif
return result;
}
bool
Test_GenerateGroupParams()
{
uint32_t pLen = 1024, qLen = 256, count;
libzerocoin::IntegerGroupParams group;
for (count = 0; count < 1; count++) {
try {
group = libzerocoin::deriveIntegerGroupParams(libzerocoin::calculateSeed(GetTestModulus(), "test", ZEROCOIN_DEFAULT_SECURITYLEVEL, "TEST GROUP"), pLen, qLen);
} catch (const std::runtime_error e) {
std::cout << "Caught exception " << e.what() << std::endl;
return false;
}
// Now perform some simple tests on the resulting parameters
if ((uint32_t)group.groupOrder.bitSize() < qLen || (uint32_t)group.modulus.bitSize() < pLen) {
return false;
}
CBigNum c = group.g.pow_mod(group.groupOrder, group.modulus);
//cout << "g^q mod p = " << c << std::endl;
if (!(c.isOne())) return false;
// Try at multiple parameter sizes
pLen = pLen * 1.5;
qLen = qLen * 1.5;
}
return true;
}
bool
Test_ParamGen()
{
bool result = true;
try {
// Instantiating testParams runs the parameter generation code
libzerocoin::ZerocoinParams testParams(GetTestModulus(),ZEROCOIN_DEFAULT_SECURITYLEVEL);
} catch (const std::runtime_error e) {
std::cout << e.what() << std::endl;
result = false;
}
return result;
}
bool
Test_Accumulator()
{
// This test assumes a list of coins were generated during
// the Test_MintCoin() test.
if (gCoins[0] == NULL) {
return false;
}
try {
// Accumulate the coin list from first to last into one accumulator
libzerocoin::Accumulator accOne(&g_Params->accumulatorParams, libzerocoin::CoinDenomination::ZQ_ONE);
libzerocoin::Accumulator accTwo(&g_Params->accumulatorParams, libzerocoin::CoinDenomination::ZQ_ONE);
libzerocoin::Accumulator accThree(&g_Params->accumulatorParams, libzerocoin::CoinDenomination::ZQ_ONE);
libzerocoin::Accumulator accFour(&g_Params->accumulatorParams, libzerocoin::CoinDenomination::ZQ_ONE);
libzerocoin::AccumulatorWitness wThree(g_Params, accThree, gCoins[0]->getPublicCoin());
for (uint32_t i = 0; i < TESTS_COINS_TO_ACCUMULATE; i++) {
accOne += gCoins[i]->getPublicCoin();
accTwo += gCoins[TESTS_COINS_TO_ACCUMULATE - (i+1)]->getPublicCoin();
accThree += gCoins[i]->getPublicCoin();
wThree += gCoins[i]->getPublicCoin();
if(i != 0) {
accFour += gCoins[i]->getPublicCoin();
}
}
// Compare the accumulated results
if (accOne.getValue() != accTwo.getValue() || accOne.getValue() != accThree.getValue()) {
std::cout << "Accumulators don't match" << std::endl;
return false;
}
if(accFour.getValue() != wThree.getValue()) {
std::cout << "Witness math not working," << std::endl;
return false;
}
// Verify that the witness is correct
if (!wThree.VerifyWitness(accThree, gCoins[0]->getPublicCoin()) ) {
std::cout << "Witness not valid" << std::endl;
return false;
}
// Serialization test: see if we can serialize the accumulator
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss << accOne;
// Deserialize it into a new object
libzerocoin::Accumulator newAcc(g_Params, ss);
// Compare the results
if (accOne.getValue() != newAcc.getValue()) {
return false;
}
} catch (const std::runtime_error e) {
return false;
}
return true;
}
bool
Test_EqualityPoK()
{
// Run this test 10 times
for (uint32_t i = 0; i < 10; i++) {
try {
// Generate a random integer "val"
CBigNum val = CBigNum::randBignum(g_Params->coinCommitmentGroup.groupOrder);
// Manufacture two commitments to "val", both
// under different sets of parameters
libzerocoin::Commitment one(&g_Params->accumulatorParams.accumulatorPoKCommitmentGroup, val);
libzerocoin::Commitment two(&g_Params->serialNumberSoKCommitmentGroup, val);
// Now generate a proof of knowledge that "one" and "two" are
// both commitments to the same value
libzerocoin::CommitmentProofOfKnowledge pok(&g_Params->accumulatorParams.accumulatorPoKCommitmentGroup,
&g_Params->serialNumberSoKCommitmentGroup,
one, two);
// Serialize the proof into a stream
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss << pok;
// Deserialize back into a PoK object
libzerocoin::CommitmentProofOfKnowledge newPok(&g_Params->accumulatorParams.accumulatorPoKCommitmentGroup,
&g_Params->serialNumberSoKCommitmentGroup,
ss);
if (newPok.Verify(one.getCommitmentValue(), two.getCommitmentValue()) != true) {
return false;
}
// Just for fun, deserialize the proof a second time
CDataStream ss2(SER_NETWORK, PROTOCOL_VERSION);
ss2 << pok;
// This time tamper with it, then deserialize it back into a PoK
ss2[15] = 0;
libzerocoin::CommitmentProofOfKnowledge newPok2(&g_Params->accumulatorParams.accumulatorPoKCommitmentGroup,
&g_Params->serialNumberSoKCommitmentGroup,
ss2);
// If the tampered proof verifies, that's a failure!
if (newPok2.Verify(one.getCommitmentValue(), two.getCommitmentValue()) == true) {
return false;
}
} catch (const std::runtime_error &e) {
return false;
}
}
return true;
}
bool
Test_MintCoin()
{
gCoinSize = 0;
try {
// Generate a list of coins
for (uint32_t i = 0; i < TESTS_COINS_TO_ACCUMULATE; i++) {
gCoins[i] = new libzerocoin::PrivateCoin(g_Params,libzerocoin::CoinDenomination::ZQ_ONE);
libzerocoin::PublicCoin pc = gCoins[i]->getPublicCoin();
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss << pc;
gCoinSize += ss.size();
}
gCoinSize /= TESTS_COINS_TO_ACCUMULATE;
} catch (const std::exception &e) {
return false;
}
return true;
}
bool Test_InvalidCoin()
{
CBigNum coinValue;
try {
// Pick a random non-prime CBigNum
for (uint32_t i = 0; i < NON_PRIME_TESTS; i++) {
coinValue = CBigNum::randBignum(g_Params->coinCommitmentGroup.modulus);
coinValue = coinValue * 2;
if (!coinValue.isPrime()) break;
}
libzerocoin::PublicCoin pubCoin(g_Params);
if (pubCoin.validate()) {
// A blank coin should not be valid!
return false;
}
libzerocoin::PublicCoin pubCoin2(g_Params, coinValue, libzerocoin::ZQ_ONE);
if (pubCoin2.validate()) {
// A non-prime coin should not be valid!
return false;
}
libzerocoin::PublicCoin pubCoin3 = pubCoin2;
if (pubCoin2.validate()) {
// A copy of a non-prime coin should not be valid!
return false;
}
// Serialize and deserialize the coin
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss << pubCoin;
libzerocoin::PublicCoin pubCoin4(g_Params, ss);
if (pubCoin4.validate()) {
// A deserialized copy of a non-prime coin should not be valid!
return false;
}
} catch (const std::runtime_error &e) {
std::cout << "Caught exception: " << e.what() << std::endl;
return false;
}
return true;
}
bool
Test_MintAndSpend()
{
try {
// This test assumes a list of coins were generated in Test_MintCoin()
if (gCoins[0] == NULL)
{
// No coins: mint some.
Test_MintCoin();
if (gCoins[0] == NULL) {
return false;
}
}
// Accumulate the list of generated coins into a fresh accumulator.
// The first one gets marked as accumulated for a witness, the
// others just get accumulated normally.
libzerocoin::Accumulator acc(&g_Params->accumulatorParams, libzerocoin::CoinDenomination::ZQ_ONE);
libzerocoin::AccumulatorWitness wAcc(g_Params, acc, gCoins[0]->getPublicCoin());
for (uint32_t i = 0; i < TESTS_COINS_TO_ACCUMULATE; i++) {
acc += gCoins[i]->getPublicCoin();
wAcc +=gCoins[i]->getPublicCoin();
}
// Now spend the coin
//SpendMetaData m(1,1);
CDataStream cc(SER_NETWORK, PROTOCOL_VERSION);
cc << *gCoins[0];
libzerocoin::PrivateCoin myCoin(g_Params,cc);
libzerocoin::CoinSpend spend(g_Params, g_Params, myCoin, acc, 0, wAcc, 0, libzerocoin::SpendType::SPEND);
spend.Verify(acc);
// Serialize the proof and deserialize into newSpend
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss << spend;
gProofSize = ss.size();
libzerocoin::CoinSpend newSpend(g_Params, g_Params, ss);
// See if we can verify the deserialized proof (return our result)
bool ret = newSpend.Verify(acc);
// Extract the serial number
CBigNum serialNumber = newSpend.getCoinSerialNumber();
gSerialNumberSize = ceil((double)serialNumber.bitSize() / 8.0);
return ret;
} catch (const std::runtime_error &e) {
std::cout << e.what() << std::endl;
return false;
}
return false;
}
void
Test_RunAllTests()
{
// Make a new set of parameters from a random RSA modulus
g_Params = new libzerocoin::ZerocoinParams(GetTestModulus());
gNumTests = gSuccessfulTests = gProofSize = 0;
for (uint32_t i = 0; i < TESTS_COINS_TO_ACCUMULATE; i++) {
gCoins[i] = NULL;
}
// Run through all of the Zerocoin tests
LogTestResult("an RSA modulus can be generated", Test_GenRSAModulus);
LogTestResult("parameter sizes are correct", Test_CalcParamSizes);
LogTestResult("group/field parameters can be generated", Test_GenerateGroupParams);
LogTestResult("parameter generation is correct", Test_ParamGen);
LogTestResult("coins can be minted", Test_MintCoin);
LogTestResult("invalid coins will be rejected", Test_InvalidCoin);
LogTestResult("the accumulator works", Test_Accumulator);
LogTestResult("the commitment equality PoK works", Test_EqualityPoK);
LogTestResult("a minted coin can be spent", Test_MintAndSpend);
std::cout << std::endl << "Average coin size is " << gCoinSize << " bytes." << std::endl;
std::cout << "Serial number size is " << gSerialNumberSize << " bytes." << std::endl;
std::cout << "Spend proof size is " << gProofSize << " bytes." << std::endl;
// Summarize test results
if (gSuccessfulTests < gNumTests) {
std::cout << std::endl << "ERROR: SOME TESTS FAILED" << std::endl;
}
// Clear any generated coins
for (uint32_t i = 0; i < TESTS_COINS_TO_ACCUMULATE; i++) {
delete gCoins[i];
}
std::cout << std::endl << gSuccessfulTests << " out of " << gNumTests << " tests passed." << std::endl << std::endl;
delete g_Params;
}
BOOST_FIXTURE_TEST_SUITE(libzerocoin, TestingSetup)
BOOST_AUTO_TEST_CASE(libzerocoin_tests)
{
std::cout << "libzerocoin v" << ZEROCOIN_VERSION_STRING << " test utility." << std::endl << std::endl;
Test_RunAllTests();
}
BOOST_AUTO_TEST_SUITE_END()
|
//%LICENSE////////////////////////////////////////////////////////////////
//
// Licensed to The Open Group (TOG) under one or more contributor license
// agreements. Refer to the OpenPegasusNOTICE.txt file distributed with
// this work for additional information regarding copyright ownership.
// Each contributor licenses this file to you under the OpenPegasus Open
// Source License; you may not use this file except in compliance with the
// License.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//////////////////////////////////////////////////////////////////////////
//
//%/////////////////////////////////////////////////////////////////////////////
/*
Test Provider for cimcli. This provider is intended to be used as a
test driver only for cimcli. It provides implementation of classes and
operations that allow cimcli to exercise all of it operations and options
with known results.
This provider is based on the Test_CLITestProviderClass class the
Test_CLITestProviderLinkClass and the Test_CLITestEmbeddedClass.
The Test_CLITestProviderClass class includes all of the CIM Data types in both
scalar and array form. The Test_CLITestProviderLinkClass allows testing
association operations and the TestCLITestEmbeddedClass allows testing
operations involving embedded instances.
The provider handles the following CIM operations:
1. Initialize - Creates a single instance of the class with all of the
properties initialized. this is placed in an array.
2. EnumerateInstances - Returns all instances in the instances array
3. GetInstance - Returns the single instance found in the array with the
input object path if found
4. Create instance - Creates a new instance of any of the classes supported
by the provider and puts it into the a local cache (array if instances).
5. ModifyInstance - Attempts to modify an instance of the target class if one
is found in the instances array. Supports all of the classes defined for
the provider.
6. DeleteInstance - Delete an instance of the test class if found in the
instances array.
6. Invoke method: Includes several methods as follows:
-InOutParamTest - Returns all input parameters on the method to the caller
With return value of zero.
-setProviderParameters - Single method to allow setting provider attributes
parameters that modify the provider capabilities for testing.
Parameters:
substituteHostName - String parameter that provides an alternate name
to be used as host name on all responses that include host name.
-debugMode - method that enables or disables debug mode for
the provider. If the boolean parameter newState is set, the provider
provider internal debug flag is set to that state. The return code
-resetProviderParameters - resets all parameters set by the
set the provider parameters and clears the cache restoring
the provider to it original initialized state. This does not change
the debug mode.
-ReferenceParamTest - Generates a specific set of Out Parameters
The Test_CLITestProviderLinkClassProvides a means to test the reference and
associator operations. Note that the instances do not really represent
understandable associations, simply syntatically correct associations.
The first operation after the provider is initialized builds a set of instances
that can be used as the basis for tests. These instances may be deleted.
LIMITATIONS:
1. The provider is intended to be used in a single namespace and so
does not include the namespace in the instances placed in the local cache.
Therefore if it is enabled for multiple namespaces, a user from some
namespace could remove, get, or enumerate an instance created in another
namespace.
2. It does not check the validity of any association create or modify instance
requests received (i.e. the references can be to non-existent instances.
3. modifyInstance rejects if includeQualifier parameter == true.
4. createInstance is weak and does not completely validate instances input.
The user can add non-existent properties and change property types without
the provider figuring it out.
5. Provider uses a mixture of Provider exceptions and the general Server
exceptions (CIMException) rather than all provider exceptions.
It is intended to run a set of tests fairly rapidly so does not hold itself in
memory. Therefore, if instances are put into the array after the normal
Pegasus timeout of providers for unload, they will be discarded.
*/
#include "CLITestProvider.h"
#include <Pegasus/Common/PegasusAssert.h>
#include <Pegasus/Common/Tracer.h>
// Required because of some malignent link betweeh MessageLoader and Thread.h
#include <Pegasus/Common/MessageLoader.h>
#include <Pegasus/Common/Thread.h>
#include <Pegasus/Common/Mutex.h>
#include <Pegasus/Common/ArrayInternal.h>
#include <Pegasus/Common/CIMQualifierNames.h>
#include <Pegasus/Common/Print.h>
PEGASUS_USING_STD;
PEGASUS_USING_PEGASUS;
String _toString(Boolean x)
{
return((x)?"true" : "false");
}
static String _toString(const CIMPropertyList& pl)
{
String s;
if (pl.isNull())
{
s = "NULL";
}
else if (pl.size() == 0)
{
s = "EMPTY";
}
else
{
for (Uint32 i = 0; i < pl.size(); i++)
{
if (i > 0)
{
s.append(", ");
}
s.append(pl[i].getString());
}
}
return s;
}
/*
Add the name value pair to the String target. The result is the pair
added to target in the form
[; ]name "=" value
*/
void _addParam(String& target, const String& name, const String& value)
{
if (target.size() != 0)
{
target.append("; ");
}
target.append(name);
target.append("=");
target.append(value);
}
/*
Complete the host and namespace fields of an object path if there are
empty.
*/
void _completePath(const String& hostName,
const CIMNamespaceName& nameSpace,
CIMObjectPath& objectPath)
{
if (objectPath.getHost().size() == 0)
objectPath.setHost(hostName);
if (objectPath.getNameSpace().isNull())
objectPath.setNameSpace(nameSpace);
}
// convert a fully qualified reference into a local reference
// (class name and keys only).
CIMObjectPath _localPath(const CIMObjectPath& inputPath)
{
CIMObjectPath localPath = CIMObjectPath(
String(),
CIMNamespaceName(),
inputPath.getClassName(),
inputPath.getKeyBindings());
return localPath;
}
// Gets a host name, either the real host name or a substitute for testing.
// The substitute name option allows CLI test program to get a dependable
// host name for result comparisons.
String CLITestProvider::_getHostName()
{
if (!_useSubstituteHostName)
{
return System::getHostName();
}
else
{
return _substituteHostName;
}
}
// Serializes access to the instances array during the CIM requests
static Mutex instanceArrayMutex;
CLITestProvider::CLITestProvider()
{
_initialized = false;
_debugMode = false;
_useSubstituteHostName = false;
_propertyList = CIMPropertyList();
}
CLITestProvider::~CLITestProvider()
{
}
void CLITestProvider::initialize(CIMOMHandle & cimom)
{
_cimom = cimom;
}
void CLITestProvider::terminate()
{
_instances.clear();
_classes.clear();
delete this;
}
void CLITestProvider::invokeMethod(
const OperationContext & context,
const CIMObjectPath & objectReference,
const CIMName & methodName,
const Array<CIMParamValue> & inParameters,
MethodResultResponseHandler & handler)
{
if (_debugMode)
{
cout << "invokeMethod Method Name = " << methodName.getString()
<< " Input parameters = ";
for (Uint32 i = 0 ; i < inParameters.size(); i++)
{
CIMParamValue param = inParameters[i];
CIMValue paramVal = param.getValue();
String paramName = param.getParameterName();
cout << paramName << " ";
}
cout << endl;
}
initializeProvider(objectReference.getNameSpace());
// convert a fully qualified reference into a local reference
// (class name and keys only).
CIMObjectPath localReference = CIMObjectPath(
String(),
CIMNamespaceName(),
objectReference.getClassName(),
objectReference.getKeyBindings());
handler.processing();
String outString = "CLITestProvider Tests : ";
if (objectReference.getClassName().equal("Test_CLITestProviderClass"))
{
if (methodName.equal("ReferenceParamTest"))
{
if (inParameters.size() > 0)
{
for(Uint32 i = 0; i < inParameters.size(); ++i)
{
CIMParamValue param = inParameters[i];
CIMValue paramVal = param.getValue();
String paramName = param.getParameterName();
String outParamName;
if(String::equalNoCase(paramName,"InParam1"))
{
outParamName = "OutParam1";
PEGASUS_TEST_ASSERT(
paramVal.getType() == CIMTYPE_REFERENCE
&& !paramVal.isArray());
param.setParameterName(outParamName);
handler.deliverParamValue(param);
}
else if(String::equalNoCase(paramName,"InParam2"))
{
outParamName = "OutParam2";
PEGASUS_TEST_ASSERT(
paramVal.getType() == CIMTYPE_REFERENCE
&& paramVal.isArray());
param.setParameterName(outParamName);
handler.deliverParamValue(param);
}
}
handler.deliver(CIMValue(outString));
}
else
{
outString.append("Empty Parameters");
handler.deliver(CIMValue(Uint32(0xFFffFFff)));
}
handler.deliver(Uint32(0));
}
// This simply returns all parameters and
// sets return value set to zero. This should provide a complete
// test of all input and output parameter types for cimcli
else if(methodName.equal("InOutParamTest"))
{
if (inParameters.size() > 0)
{
//Returns all input parameters
handler.deliverParamValue(inParameters);
}
handler.deliver(Uint32(0));
}
// This simply returns all parameters and
// sets return value set to zero. This should provide a complete
// test of all input and output parameter types for cimcli
else if(methodName.equal("setProviderParameters"))
{
Uint32 rtnCode = 0;
if (inParameters.size() > 0)
{
for(Uint32 i = 0; i < inParameters.size(); ++i)
{
String paramName = inParameters[i].getParameterName();
CIMValue paramVal = inParameters[i].getValue();
if (paramName == "substituteHostName")
{
if (paramVal.getType() == CIMTYPE_STRING)
{
String sTmp = _substituteHostName;
// set the capability from the input parameter
paramVal.get(_substituteHostName);
_useSubstituteHostName = true;
// return the parameter with the original value
CIMParamValue outParam = inParameters[i].clone();
CIMValue v = outParam.getValue();
v.set(sTmp);
outParam.setValue(v);
handler.deliverParamValue(outParam);
}
else
{
String errMsg = "Incorrect in parameter type ";
errMsg.append(paramName);
errMsg.append( " for method ");
errMsg.append(methodName.getString());
throw CIMOperationFailedException(errMsg);
}
}
// NOTE: Add new parameters here with else if
// not a valid parameter. Return error
else
{
String errMsg = "Incorrect in parameter ";
errMsg.append(paramName);
errMsg.append( " for method ");
errMsg.append(methodName.getString());
throw CIMOperationFailedException(errMsg);
}
}
}
handler.deliver(rtnCode);
}
// Reset the parameters used to modify operations. Note that
// this does not reset the debugMode parameter
else if(methodName.equal("resetProviderParameters"))
{
_useSubstituteHostName = false;
_substituteHostName = String();
handler.deliver(0);
}
// Restore provider to its post initialized state. remvoes
// any instances in cache, sets cache to initialized instances,
// and sets parameters to initial state. Does not reset the
// debugMode parameter.
else if (methodName.equal("reset"))
{
// If the provider has been initialized (at least - one operation
// call clear and reinit the instance repository.
if (_initialized)
{
AutoMutex autoMut(instanceArrayMutex);
_instances.clear();
_initialized = false;
}
_useSubstituteHostName = false;
_substituteHostName = String();
handler.deliver(0);
}
else if (methodName.equal("debugMode"))
{
Boolean oldMode = _debugMode;
Uint32 rtnCode = 0;
if (inParameters.size() > 0)
{
for(Uint32 i = 0; i < inParameters.size(); ++i)
{
String paramName = inParameters[i].getParameterName();
CIMValue paramVal = inParameters[i].getValue();
if (paramName == "newState")
{
if (paramVal.getType() == CIMTYPE_BOOLEAN)
{
paramVal.get(_debugMode);
}
else
{
// return error. Incorrect type on parameter
String errMsg = "Incorrect in parameter type ";
errMsg.append(paramName);
errMsg.append( " for method ");
errMsg.append(methodName.getString());
throw CIMOperationFailedException(errMsg);
}
}
// invalid parameter for this method. Throw error
else
{
String errMsg = "Incorrect in parameter ";
errMsg.append(paramName);
errMsg.append( " for method ");
errMsg.append(methodName.getString());
throw CIMOperationFailedException(errMsg);
}
}
}
if (rtnCode == 0)
{
rtnCode = (oldMode != _debugMode)? 0: 1;
}
handler.deliver(rtnCode);
}
else
{
String errMsg = "Incorrect method name ";
errMsg.append(methodName.getString());
throw CIMOperationFailedException(errMsg);
}
}
else if (objectReference.getClassName().equal("Test_CLITestEmbeddedClass"))
{
if (methodName.equal("embeddedInstParamMethod"))
{
if (inParameters.size() > 0)
{
//Returns all input parameters
handler.deliverParamValue(inParameters);
}
handler.deliver(Uint32(0));
}
else
{
cout << "Invalid method name= "
<< methodName.getString()
<< " ignored" << endl;
}
}
else
{
String errMsg = "Incorrect className on invokeMethod ";
errMsg.append(objectReference.getClassName().getString());
throw CIMOperationFailedException(errMsg);
}
handler.complete();
}
void CLITestProvider::getInstance(
const OperationContext & context,
const CIMObjectPath & instanceReference,
const Boolean includeQualifiers,
const Boolean includeClassOrigin,
const CIMPropertyList & propertyList,
InstanceResponseHandler & handler)
{
if (_debugMode)
{
cout << "getInstance ref=" << instanceReference.toString() << endl;
}
initializeProvider(instanceReference.getNameSpace());
handler.processing();
AutoMutex autoMut(instanceArrayMutex);
Uint32 index;
if ((index = findInstance(instanceReference)) != PEG_NOT_FOUND)
{
// Put input parameters into the requestInputParameters property so
// they can be tested on by the client.
String text;
_addParam(text, "propertyList", _toString(propertyList));
_addParam(text, "includeQualifiers", _toString(includeQualifiers));
_addParam(text, "includeClassOrigin", _toString(includeClassOrigin));
try
{
CIMInstance temp = _instances[index].clone();
// Required because not assured all instances will have this
// property
if (temp.findProperty("requestInputParameters") == PEG_NOT_FOUND)
{
CIMClass tmpClass = _getClass(CIMName(
"Test_CLITestProviderClass"),
instanceReference.getNameSpace());
Uint32 pos = tmpClass.findProperty("requestInputParameters");
temp.addProperty(tmpClass.getProperty(pos));
}
temp.getProperty(temp.findProperty("requestInputParameters"))
.setValue(text);
handler.deliver(temp);
}
catch(CIMException& e)
{
cerr << "CIMCLITestProvider: Exception Occured on deliver : "
<< e.getMessage() << endl;
throw CIMException(e);
}
}
else
{
throw CIMException(CIM_ERR_NOT_FOUND);
}
handler.complete();
}
void CLITestProvider::enumerateInstances(
const OperationContext & context,
const CIMObjectPath & ref,
const Boolean includeQualifiers,
const Boolean includeClassOrigin,
const CIMPropertyList & propertyList,
InstanceResponseHandler & handler)
{
if (_debugMode)
{
cout << "Enter EnumerateInstances " << ref.toString()
<< " includeQualifiers= " << (includeQualifiers? "true":"false")
<< " includeClassOrigin= " << (includeClassOrigin? "true":"false")
<< " propertyList= " << propertyList.toString() << endl;
}
initializeProvider(ref.getNameSpace());
handler.processing();
AutoMutex autoMut(instanceArrayMutex);
CIMName reqClassName = ref.getClassName();
// Puts input parameters into the requestInputParameters property so
// they can be tested on by the client.
String text;
_addParam(text, "propertyList", _toString(propertyList));
_addParam(text, "includeQualifiers", _toString(includeQualifiers));
_addParam(text, "includeClassOrigin", _toString(includeClassOrigin));
// Loop through cache for all instances with defined className
for (Uint32 i = 0, n = _instances.size(); i < n; i++)
{
if (reqClassName == _instances[i].getClassName())
{
try
{
CIMInstance temp = _instances[i].clone();
if (temp.findProperty(
"requestInputParameters") == PEG_NOT_FOUND)
{
CIMClass tmpClass = _getClass(CIMName(
"Test_CLITestProviderClass"),
ref.getNameSpace());
Uint32 pos = tmpClass.findProperty(
"requestInputParameters");
temp.addProperty(tmpClass.getProperty(pos));
}
temp.getProperty(
temp.findProperty("requestInputParameters"))
.setValue(text);
handler.deliver(temp);
}
catch(CIMException& e)
{
cerr << "CIMCLITestProvider:Exception Occured : "
<< e.getMessage() << endl;
throw CIMException(e);
}
}
}
handler.complete();
}
void CLITestProvider::enumerateInstanceNames(
const OperationContext & context,
const CIMObjectPath & classReference,
ObjectPathResponseHandler & handler)
{
if (_debugMode)
{
cout << "Enter EnumerateInstanceNames "
<< classReference.toString() << endl;
}
initializeProvider(classReference.getNameSpace());
handler.processing();
AutoMutex autoMut(instanceArrayMutex);
CIMName reqClassName = classReference.getClassName();
for (Uint32 i = 0, n = _instances.size(); i < n; i++)
{
if (reqClassName == _instances[i].getClassName())
{
try
{
handler.deliver(_instances[i].getPath());
}
catch(CIMException& e)
{
cerr << "CIMCLITestProvider:Exception Occured : "
<< e.getMessage() << endl;
throw CIMException(e);
}
}
}
handler.complete();
}
// modifyInstance - Helper function for modifyInstance operation.
// Modify the property in existingInst with the value of modifiedProperty
// if they have different values. If modifiedProperty does not exist in
// existingInstance, add it from propertyInClass.
void modifyProperty(CIMInstance& existingInst,
CIMConstProperty& modifiedProperty,
CIMConstProperty& propertyInClass)
{
CIMName pName = modifiedProperty.getName();
try
{
Uint32 pos;
if ((pos = existingInst.findProperty(pName)) != PEG_NOT_FOUND)
{
// If values are different, move value to existing property
CIMProperty existingProp = existingInst.getProperty(pos);
CIMValue vExisting = existingProp.getValue();
if (vExisting != modifiedProperty.getValue())
{
existingProp.setValue(modifiedProperty.getValue());
}
}
else // add the property since not in instance
{
// Get property from Class
CIMProperty addProp = propertyInClass.clone();
// Do we have to do these tests if property NULL??
if ((modifiedProperty.getValue().getType()
!= addProp.getValue().getType()) ||
(modifiedProperty.getValue().isArray() !=
addProp.getValue().isArray())
)
{
throw CIMException(CIM_ERR_INVALID_PARAMETER,
"modifyInstance inputInstance Property Value type"
" mismatch: " +
pName.getString());
}
addProp.setValue(modifiedProperty.getValue());
existingInst.addProperty(addProp);
}
}
catch(CIMException& e)
{
throw CIMException(CIM_ERR_FAILED,
" modify Instance " + e.getMessage());
}
}
Uint32 testPropertyInClass(CIMName& name, CIMConstClass& mc)
{
Uint32 pos;
if ((pos = mc.findProperty(name)) == PEG_NOT_FOUND)
{
throw CIMException(CIM_ERR_INVALID_PARAMETER,
"modifyInstance: Property"
" Not in class: " +
name.getString());
}
return pos;
}
void CLITestProvider::modifyInstance(
const OperationContext & context,
const CIMObjectPath & instanceReference,
const CIMInstance & instanceObject,
const Boolean includeQualifiers,
const CIMPropertyList & propertyList,
ResponseHandler & handler)
{
if (_debugMode)
{
cout << "Enter modify Instance. instanceRef = "
<< instanceReference.toString()
<< " includeQualifiers = "
<< (includeQualifiers? "true" : "false")
<< " property List = " << _toString(propertyList) << endl;
// This only displays instance in Pegasus debug mode.
PrintInstance(cout, instanceObject);
}
initializeProvider(instanceReference.getNameSpace());
handler.processing();
// Reject includeQualifiers = true
if (includeQualifiers)
{
throw CIMException(CIM_ERR_FAILED,
" modifyInstance rejected by provider."
" includeQualifiers=true not allowed");
}
// get the class for this operation. Used several times in process.
CIMConstClass mc = _getClass(instanceReference.getClassName(),
instanceReference.getNameSpace());
// convert a fully qualified reference into a local reference
// (class name and keys only).
// Ref must be correct
CIMObjectPath localRef = _localPath(instanceReference);
AutoMutex autoMut(instanceArrayMutex);
// Find the proper instance in the cache
Uint32 index;
if ((index = findInstance(localRef)) != PEG_NOT_FOUND)
{
// Clone the instance to be modified so we do not modify unless
// completely successful.
CIMInstance instToModify = _instances[index].clone();
// If the PropertyList is NULL, the set of properties to be modified
// consists of those of ModifiedInstance with values different from
// the current values in the instance to be modified.
if (propertyList.isNull())
{
// for all properties in the input instance
Uint32 propertyCount = instanceObject.getPropertyCount();
for (Uint32 j = 0 ; j < propertyCount ; j++)
{
CIMConstProperty inputProperty = instanceObject.getProperty(j);
CIMName pName = inputProperty.getName();
// reject if input property not in class
Uint32 pos = testPropertyInClass(pName, mc);
CIMConstProperty propertyInClass = mc.getProperty(pos);
modifyProperty(instToModify,
inputProperty,
propertyInClass);
} // for loop processing properties if propertyList isNull
} // end propertyList.isNull()
else if (propertyList.size() != 0)
{
/*
If the PropertyList input parameter is not NULL, the members of the
array define one or more property names. Only properties specified
in the PropertyList are modified. Properties of the
ModifiedInstance that are missing from the PropertyList are
ignored.
If a property is not specified in the ModifiedInstance but is
specified in the PropertyList, then the class-defined default
value (or NULL if none is defined) becomes its new value in
the instance to be modified.
*/
for (Uint32 i = 0 ; i < propertyList.size() ; i++)
{
CIMName plName = propertyList[i];
// test if property in propertyList is in class
Uint32 posInClass = testPropertyInClass(plName, mc);
// If property not found in input instance, get from the class
// including value
Uint32 pos;
if ((pos = instanceObject.findProperty(plName)) ==
PEG_NOT_FOUND)
{
CIMProperty addProp = mc.getProperty(posInClass).clone();
instToModify.addProperty(addProp);
}
else // else modify existing property
{
CIMConstProperty inputProperty =
instanceObject.getProperty(pos);
CIMConstProperty propertyInClass =
mc.getProperty(posInClass);
modifyProperty(instToModify,
inputProperty,
propertyInClass);
}
} // for propertyList[] loop
} // end propertyList.size() != 0
// if propertyList empty exit without updating existingInst
else
{
handler.complete();
return;
}
// Test for no modifications to key. This allows key properties
// in instanceObject if they do not change the CIMValue.
CIMObjectPath p = instToModify.buildPath(mc);
if (p != localRef)
{
throw CIMException(CIM_ERR_INVALID_PARAMETER,
"modifyInstance input instance modifies keys.");
}
// Complete successful, replace the existing instance.
_instances.remove(index);
_instances.append(instToModify);
handler.complete();
} // end if found
else // Instance not found in cache
{
throw CIMObjectNotFoundException(
"Instance not found: " + instanceReference.toString()); }
}
// Determine if a property is a key property
static Boolean isKey(const CIMConstProperty& p)
{
Uint32 index = p.findQualifier(CIMQualifierNames::KEY);
if (index == PEG_NOT_FOUND)
{
return false;
}
Boolean flag;
const CIMValue& value = p.getQualifier(index).getValue();
if (value.getType() != CIMTYPE_BOOLEAN)
{
return false;
}
value.get(flag);
return flag;
}
void CLITestProvider::createInstance(
const OperationContext & context,
const CIMObjectPath & instanceReference,
const CIMInstance & instanceObject,
ObjectPathResponseHandler & handler)
{
if (_debugMode)
{
cout << "Enter createInstance "
<< instanceReference.toString() << endl;
// Only displays instance in Pegasus debug build
PrintInstance(cout, instanceObject);
}
initializeProvider(instanceReference.getNameSpace());
handler.processing();
CIMObjectPath newInstanceRef = _localPath(instanceReference);
AutoMutex autoMut(instanceArrayMutex);
CIMClass c = _getClass(instanceObject.getClassName(),
instanceReference.getNameSpace());
// Test the instance against class for key Properties existence
for (Uint32 i = 0 ; i < c.getPropertyCount() ; i++)
{
CIMConstProperty p = c.getProperty(i);
if (isKey(p))
{
if (instanceObject.findProperty(p.getName()) == PEG_NOT_FOUND)
{
throw CIMOperationFailedException(
"Key Property(s) Required: " + p.getName().getString());
}
}
}
// Test to assure that all properties in instance are in the class
for (Uint32 i = 0 ; i < instanceObject.getPropertyCount() ; i++)
{
CIMConstProperty p = instanceObject.getProperty(i);
if (c.findProperty(p.getName()) == PEG_NOT_FOUND)
{
throw CIMPropertyNotFoundException(
"Property " + p.getName().getString());
}
// To be completely valid we should also check type, etc.
}
// determine that key properties exist in the instance. Do we
// really need to do this or simply take whatever is there?
newInstanceRef = instanceObject.buildPath(c);
if (newInstanceRef.getKeyBindings().size() == 0)
{
throw CIMOperationFailedException("Key Property(s) Required");
}
// If the instance exists, throw already_exists exception
Uint32 index;
if ((index = findInstance(newInstanceRef)) == PEG_NOT_FOUND)
{
// add the instance to the set of instances saved in the cache.
CIMInstance myInstance = instanceObject.clone();
myInstance.setPath(newInstanceRef);
_instances.append(myInstance);
// Deliver path of new instance
handler.deliver(newInstanceRef);
handler.complete();
}
else
{
throw CIMException(CIM_ERR_ALREADY_EXISTS);
}
}
void CLITestProvider::deleteInstance(
const OperationContext & context,
const CIMObjectPath & instanceReference,
ResponseHandler & handler)
{
if (_debugMode)
{
cout << "Enter deleteInstance "
<< instanceReference.toString() << endl;
}
initializeProvider(instanceReference.getNameSpace());
handler.processing();
// convert a fully qualified reference into a local reference
// (class name and keys only).
AutoMutex autoMut(instanceArrayMutex);
Uint32 index;
if ((index = findInstance(instanceReference)) != PEG_NOT_FOUND)
{
_instances.remove(index);
}
else
{
throw CIMObjectNotFoundException(
"Instance not found: " + instanceReference.toString());
}
handler.complete();
return;
}
/*
Processing of associator/Reference Operation Requests
NOTE: This association code is not based on any definition of the
relationship between objects but simply returning information
on instances that exist in the repository. Thus typically it returns
the target instance itself (i.e. association of an instance with
itself). This works since the only goal of this provider
is a syntatic test of cimcli, not any association structure. So our
association is that every instance is associated with itself. Note that
this removes any meaning from the role and assoc/result class parameters
but we test the validity of these by returning a property in the
returned instances containing all of these values so that the client
can test to determine if the provider received what was input.
*/
void CLITestProvider::associators(
const OperationContext& context,
const CIMObjectPath& objectName,
const CIMName& associationClass,
const CIMName& resultClass,
const String& role,
const String& resultRole,
const Boolean includeQualifiers,
const Boolean includeClassOrigin,
const CIMPropertyList& propertyList,
ObjectResponseHandler& handler)
{
if (_debugMode)
{
cout << "Enter associators "
<< objectName.toString()
<< "associationClass " << associationClass.getString()
<< "resultClass " << resultClass.getString()
<< "role " << role
<< "resultRole " << resultRole << endl;
}
initializeProvider(objectName.getNameSpace());
// Get the namespace and host names to create the CIMObjectPath
CIMNamespaceName nameSpace = objectName.getNameSpace();
String host = _getHostName();
handler.processing();
// complete processing the request
// Puts input parameters into the requestInputParameters property so that
// they can be tested by the client.
String text;
_addParam(text, "role", role);
_addParam(text, "resultRole", resultRole);
_addParam(text, "associationClass", associationClass.getString());
_addParam(text, "resultClass", resultClass.getString());
_addParam(text, "includeQualifiers", _toString(includeQualifiers));
_addParam(text, "includeClassOrigin", _toString(includeClassOrigin));
_addParam(text, "propertyList", _toString(propertyList));
// Return an instance of the associated class for every instance
// currently in the local list.
Uint32 index;
if ((index = findInstance(objectName)) != PEG_NOT_FOUND)
{
try
{
CIMInstance temp = _instances[index].clone();
if (temp.findProperty("requestInputParameters") == PEG_NOT_FOUND)
{
CIMClass tmpClass = _getClass(CIMName(
"Test_CLITestProviderClass"),
nameSpace);
Uint32 pos = tmpClass.findProperty("requestInputParameters");
temp.addProperty(tmpClass.getProperty(pos));
}
temp.getProperty(temp.findProperty("requestInputParameters"))
.setValue(text);
CIMObjectPath rtnObjectName = objectName;
if (_useSubstituteHostName)
{
rtnObjectName.setHost(_getHostName());
}
temp.setPath(rtnObjectName);
handler.deliver(temp);
}
catch(CIMException& e)
{
cerr << "CIMCLITestProvider:Exception Occured : "
<< e.getMessage() << endl;
throw CIMException(e);
}
}
handler.complete();
}
void CLITestProvider::associatorNames(
const OperationContext& context,
const CIMObjectPath& objectName,
const CIMName& associationClass,
const CIMName& resultClass,
const String& role,
const String& resultRole,
ObjectPathResponseHandler& handler)
{
initializeProvider(objectName.getNameSpace());
// Get the namespace and host names to create the CIMObjectPath
CIMNamespaceName nameSpace = objectName.getNameSpace();
String host = _getHostName();
handler.processing();
// Return an instance of the associated class for every instance
// currently in the local list. Simple since we just return the
// input path if the instance exists.
Uint32 index;
if ((index = findInstance(objectName)) != PEG_NOT_FOUND)
{
try
{
CIMObjectPath rtnObjectName = objectName;
if (_useSubstituteHostName)
{
rtnObjectName.setHost(_getHostName());
}
handler.deliver(rtnObjectName);
}
catch(CIMException& e)
{
cerr << "CIMCLITestProvider:Exception Occured : "
<< e.getMessage() << endl;
throw CIMException(e);
}
}
handler.complete();
}
void CLITestProvider::references(
const OperationContext& context,
const CIMObjectPath& objectName,
const CIMName& resultClass,
const String& role,
const Boolean includeQualifiers,
const Boolean includeClassOrigin,
const CIMPropertyList& propertyList,
ObjectResponseHandler& handler)
{
initializeProvider(objectName.getNameSpace());
// Get the namespace and host names to create the CIMObjectPath
CIMNamespaceName nameSpace = objectName.getNameSpace();
String host = _getHostName();
handler.processing();
CIMName objectClassName = objectName.getClassName();
// if the target instance exists in the local storage, build the
// association class instance
AutoMutex autoMut(instanceArrayMutex);
Uint32 index;
if ((index = findInstance(objectName)) != PEG_NOT_FOUND)
{
Array<CIMName> refClassArray;
refClassArray.append(CIMName("Test_CLITestProviderLinkClass"));
// Create a single instance of the Test_CLITestProviderLinkClass
// This creates a single fixed instance simply to allow the
// cimcli client to test results. It also places the input parameters
// into the text result so that the client can confirm that the
// input parameters were passed to the provider.
// Create path for assoc instance.
CIMClass assocClass = _getClass(CIMName(
"Test_CLITestProviderLinkClass"),
nameSpace);
// Create a single instance with all properties and with path
// independent of namespace or hostname
CIMInstance assocInstance = assocClass.buildInstance(
true, true, CIMPropertyList());
CIMObjectPath rtnObjectName = objectName;
if (_useSubstituteHostName)
{
rtnObjectName.setHost(_getHostName());
}
assocInstance.getProperty(
assocInstance.findProperty("parent"))
.setValue(rtnObjectName);
assocInstance.getProperty(
assocInstance.findProperty("child"))
.setValue(rtnObjectName);
// Put input parameters into the requestInputParameters property so
// they can be confirmed by the client.
String text;
_addParam(text, "role", role);
_addParam(text, "resultClass", resultClass.getString());
_addParam(text, "includeQualifiers", _toString(includeQualifiers));
_addParam(text, "includeClassOrigin", _toString(includeClassOrigin));
_addParam(text, "propertyList", _toString(propertyList));
assocInstance.getProperty(
assocInstance.findProperty("requestInputParameters"))
.setValue(text);
CIMObjectPath objectPath =
assocInstance.buildPath(assocClass);
_completePath(host, nameSpace, objectPath);
assocInstance.setPath(objectPath);
handler.deliver(assocInstance);
}
handler.complete();
}
// Return all references (association instance names) in which the given
// object is involved.
void CLITestProvider::referenceNames(
const OperationContext& context,
const CIMObjectPath& objectName,
const CIMName& resultClass,
const String& role,
ObjectPathResponseHandler& handler)
{
CIMNamespaceName nameSpace = objectName.getNameSpace();
initializeProvider(nameSpace);
// Get the namespace and host names to create the CIMObjectPath
String host = _getHostName();
// If the objectName exists in the local list, build the instance
// of the association and then build the path for this instance.
AutoMutex autoMut(instanceArrayMutex);
Uint32 index;
if ((index = findInstance(objectName)) != PEG_NOT_FOUND)
{
Array<CIMName> refClassArray;
refClassArray.append(CIMName("Test_CLITestProviderLinkClass"));
CIMInstance assocInstance("Test_CLITestProviderLinkClass");
CIMObjectPath rtnObjectName = objectName;
if (_useSubstituteHostName)
{
rtnObjectName.setHost(_getHostName());
}
assocInstance.addProperty(CIMProperty(CIMName("parent"),
rtnObjectName,
0,
CIMName("Test_CLITestProviderClass")));
assocInstance.addProperty(CIMProperty(CIMName("child"),
rtnObjectName,
0,
CIMName("Test_CLITestProviderClass")));
CIMClass assocClass = _getClass(
CIMName("Test_CLITestProviderLinkClass"),
nameSpace);
// build path for this instance
CIMObjectPath objectPath =
assocInstance.buildPath(assocClass);
_completePath(host, nameSpace, objectPath);
handler.deliver(objectPath);
}
// complete processing the request
handler.complete();
}
/* get the defined class from the repository. Classes once acquired
are saved in an array so that future references get the local copy
@param className CIMName name of the class to get
@return CIMClass with the class or unitialized if
there was an error in the getClass
*/
CIMClass CLITestProvider::_getClass(const CIMName& className,
const CIMNamespaceName& ns)
{
// try to get from array of already acquired classess
for (Uint32 i = 0; i < _classes.size() ; i++)
{
if (_classes[i].getClassName() == className)
{
return _classes[i];
}
}
// Not in array yet, get this class from the cim server.
CIMClass c;
try
{
c = _cimom.getClass(
OperationContext(),
ns,
className,
false,
true,
true,
CIMPropertyList());
_classes.append(c);
}
catch (CIMException& e)
{
PEG_TRACE((TRC_DISCARDED_DATA, Tracer::LEVEL1,
"CLITestProvider GetClass operation failed: Class %s. Msg %s",
(const char*) className.getString().getCString(),
(const char*) e.getMessage().getCString()));
throw CIMException(CIM_ERR_FAILED);
}
return c;
}
/*
Find an instance in the instance array with path defined by
the input parameter. returns the index of the instance or PEG_NOT_FOUND
*/
Uint32 CLITestProvider::findInstance(const CIMObjectPath& path)
{
CIMObjectPath localPath = _localPath(path);
for (Uint32 i = 0; i < _instances.size(); i++)
{
if(localPath == _instances[i].getPath())
{
return i;
}
}
return PEG_NOT_FOUND;
}
// Create the instances that will be considered inherently part of the
// provider for these tests. This includes one instance of each class
// This was done with namespace input so that we could build association
// instances that require namespace. It later turned out to be easier
// to build them on the fly so that the namespace parameter and the
// corresponding dynamic initialization of the provider (initializeProvider)
// are not really necessary.
// NOTE: Uses the namespace of the initial operation to determine the
// namespace in which these instances are created and where it looks for
// the class definitions.
void CLITestProvider::createInstances(const CIMNamespaceName& ns)
{
if (_debugMode)
{
cout << "Enter createInstances function" << endl;
}
// Create instances of Test_CLITestProviderClass class
CIMClass theClass = _getClass(
CIMName("Test_CLITestProviderClass"),
ns);
// Create a single instance with all properties and with path
// independent of namespace or hostname
CIMInstance instance = theClass.buildInstance(
true, true, CIMPropertyList());
instance.getProperty(instance.findProperty("Id")).setValue(
CIMValue(String("Mike")));
instance.getProperty(instance.findProperty("Name")).setValue(
CIMValue(String("Bob")));
instance.getProperty(instance.findProperty("scalBool")).setValue(
CIMValue(Boolean(true)));
instance.getProperty(instance.findProperty("scalUint8")).setValue(
CIMValue(Uint8(220)));
instance.getProperty(instance.findProperty("scalSint8")).setValue(
CIMValue(Sint8(124)));
instance.getProperty(instance.findProperty("scalUint16")).setValue(
CIMValue(Uint16(100)));
instance.getProperty(instance.findProperty("scalSint16")).setValue(
CIMValue(Sint16(100)));
instance.getProperty(instance.findProperty("scalUint32")).setValue(
CIMValue(Uint32(100)));
instance.getProperty(instance.findProperty("scalSint32")).setValue(
CIMValue(Sint32(100)));
instance.getProperty(instance.findProperty("scalUint64")).setValue(
CIMValue(Uint64(100)));
instance.getProperty(instance.findProperty("scalReal32")).setValue(
CIMValue(Real32(100)));
instance.getProperty(instance.findProperty("scalReal64")).setValue(
CIMValue(Real64(100)));
instance.getProperty(instance.findProperty("scalString")).setValue(
CIMValue(String("teststring")));
instance.getProperty(instance.findProperty("scalDateTime")).setValue(
CIMValue(CIMDateTime("19991224120000.000000+360")));
// set Values into the corresponding array properties
Array<Boolean> ab;
ab.append(true); ab.append(false); ab.append(true);
instance.getProperty(instance.findProperty("arrayBool")).setValue(
CIMValue(ab));
Array<Uint8> auint8;
auint8.append(4); auint8.append(128); auint8.append(240);
instance.getProperty(instance.findProperty("arrayUint8")).setValue(
CIMValue(auint8));
Array<Sint8> asint8;
asint8.append(4); asint8.append(126); asint8.append(-126);
instance.getProperty(instance.findProperty("arraySint8")).setValue(
CIMValue(asint8));
Array<Uint16> auint16;
auint16.append(4); auint16.append(128); auint16.append(240);
instance.getProperty(instance.findProperty("arrayUint16")).setValue(
CIMValue(CIMValue(auint16)));
Array<Sint16> asint16;
asint16.append(4); asint16.append(126); asint16.append(-126);
instance.getProperty(instance.findProperty("arraySint16")).setValue(
CIMValue(asint16));
Array<Uint32> auint32;
auint32.append(4); auint32.append(128); auint32.append(240);
instance.getProperty(instance.findProperty("arrayUint32")).setValue(
CIMValue(auint32));
Array<Sint32> asint32;
asint32.append(4); asint32.append(126); asint32.append(-126);
instance.getProperty(instance.findProperty("arraySint32")).setValue(
CIMValue(asint32));
Array<Uint64> auint64;
auint64.append(4); auint64.append(128); auint64.append(240);
instance.getProperty(instance.findProperty("arrayUint64")).setValue(
CIMValue(auint64));
Array<Real32> aReal32;
aReal32.append(4); aReal32.append(128); aReal32.append(240);
instance.getProperty(instance.findProperty("arrayReal32")).setValue(
CIMValue(aReal32));
Array<Real64> aReal64;
aReal64.append(4); aReal64.append(128); aReal64.append(240);
instance.getProperty(instance.findProperty("arrayReal64")).setValue(
CIMValue(aReal64));
Array<String> aString;
aString.append("First"); aString.append("Second"); aString.append("Third");
instance.getProperty(instance.findProperty("arrayString")).setValue(
CIMValue(aString));
Array<CIMDateTime> aCIMDateTime;
aCIMDateTime.append(CIMDateTime("19991224120000.000000+360"));
aCIMDateTime.append(CIMDateTime("19991224120000.000000+360"));
aCIMDateTime.append(CIMDateTime("19991224120000.000000+360"));
instance.getProperty(instance.findProperty("arrayDateTime")).setValue(
CIMValue(aCIMDateTime));
CIMObjectPath p("Test_CLITestProviderClass.Id=\"Mike\"");
instance.setPath(p);
_instances.append(instance);
// Create instance of Test_CLITestEmbedded1 Class
// Create an embedded instance
CIMClass embeddedClass1 = _getClass(CIMName("Test_CLITestEmbedded1"), ns);
CIMInstance embedded1 = embeddedClass1.buildInstance(
true, true, CIMPropertyList());
embedded1.getProperty(embedded1.findProperty("Id")).setValue(
CIMValue(String("100")));
embedded1.getProperty(embedded1.findProperty("name")).setValue(
CIMValue(String("Ronald")));
embedded1.getProperty(embedded1.findProperty("comment")).setValue(
CIMValue(String("Instance created by provider.")));
CIMObjectPath p1("Test_CLITestEmbedded1.Id=100");
embedded1.setPath(p1);
if (_debugMode)
{
cout << "Created Test_CLITestEmbedded1 instance " << endl;
}
// Create instance of Test_CLITestEmbedded3 Class
CIMClass embedded3Class = _getClass(CIMName("Test_CLITestEmbedded3"), ns);
CIMInstance embedded3 = embedded3Class.buildInstance(
true, true, CIMPropertyList());
embedded3.getProperty(embedded3.findProperty("Id")).setValue(
CIMValue(String("103")));
embedded3.getProperty(embedded3.findProperty("name")).setValue(
CIMValue(String("McDonald")));
embedded3.getProperty(embedded3.findProperty("comment")).setValue(
CIMValue(String("Instance created by provider.")));
CIMObjectPath p3("Test_CLITestEmbedded3.Id=100");
embedded3.setPath(p3);
if (_debugMode)
{
cout << "Created Test_CLITestEmbedded3 instance " << endl;
}
// Create instance of Test_CLITestEmbedded2 Class
CIMClass embedded2Class = _getClass(CIMName("Test_CLITestEmbedded2"), ns);
CIMInstance embedded2 = embedded2Class.buildInstance(
true, true, CIMPropertyList());
embedded2.getProperty(embedded2.findProperty("Id")).setValue(
CIMValue(String("102")));
embedded2.getProperty(embedded2.findProperty("name")).setValue(
CIMValue(String("Ronald")));
embedded2.getProperty(embedded2.findProperty("comment")).setValue(
CIMValue(String("Instance created by provider.")));
embedded2.getProperty(
embedded2.findProperty("recursiveEmbeddedInst")).setValue(
CIMValue(CIMInstance(embedded3)));
CIMObjectPath p2("Test_CLITestEmbedded2.Id=102");
embedded2.setPath(p2);
if (_debugMode)
{
cout << "Created Test_CLITestEmbedded2 instance " << endl;
}
// build the instance that embedds the above instance
CIMClass embeddingClass = _getClass(
CIMName("Test_CLITestEmbeddedClass"), ns);
CIMInstance embeddedingClassInst =
embeddingClass.buildInstance(true, true, CIMPropertyList());
embeddedingClassInst.getProperty(
embeddedingClassInst.findProperty("Id")).setValue(
CIMValue(String("101")));
embeddedingClassInst.getProperty(
embeddedingClassInst.findProperty("embeddedInst")).setValue(
CIMValue(CIMInstance(embedded1)));
embeddedingClassInst.getProperty(
embeddedingClassInst.findProperty("embeddedInst2")).setValue(
CIMValue(CIMInstance(embedded2)));
if (_debugMode)
{
cout << "Created Embedding instance " << endl;
}
CIMObjectPath p4("Test_CLITestEmbeddedClass.Id=101");
embeddedingClassInst.setPath(p4);
_instances.append(embeddedingClassInst);
}
// initialze the provider by creating the instances that will exist
// in the instances array at startup. The namespace parameter is the
// namespace that will be set in any paths built when instances
// are created.
void CLITestProvider::initializeProvider(const CIMNamespaceName& ns)
{
if (!_initialized)
{
AutoMutex autoMut(instanceArrayMutex);
if (!_initialized)
{
createInstances(ns);
_initialized = true;
}
}
}
|
#include "includes.h"
bool Hooks::IsConnected() {
if (!this || !g_csgo.m_engine)
return false;
Stack stack;
static Address IsLoadoutAllowed{ pattern::find(g_csgo.m_client_dll, XOR("84 C0 75 04 B0 01 5F")) };
if ( c_config::get( )->b[ "unlock" ] && stack.ReturnAddress( ) == IsLoadoutAllowed )
return false;
return g_hooks.m_engine.GetOldMethod< IsConnected_t >(IVEngineClient::ISCONNECTED)(this);
}
bool Hooks::IsHLTV() {
if (!this || !g_csgo.m_engine)
return false;
Stack stack;
static const Address return_to_setup_velocity{ pattern::find(g_csgo.m_client_dll, XOR("84 C0 75 38 8B 0D ? ? ? ? 8B 01 8B 80")) };
static const Address return_to_accumulate_layers = pattern::find(g_csgo.m_client_dll, XOR("84 C0 75 0D F6 87"));
if (stack.ReturnAddress() == return_to_setup_velocity)
return true;
if (stack.ReturnAddress() == return_to_accumulate_layers)
return true;
return g_hooks.m_engine.GetOldMethod< IsHLTV_t >(IVEngineClient::ISHLTV)(this);
}
void Hooks::EmitSound( IRecipientFilter& filter, int iEntIndex, int iChannel, const char* pSoundEntry, unsigned int nSoundEntryHash, const char* pSample, float flVolume, float flAttenuation, int nSeed, int iFlags, int iPitch, const vec3_t* pOrigin, const vec3_t* pDirection, void* pUtlVecOrigins, bool bUpdatePositions, float soundtime, int speakerentity ) {
if( strstr( pSample, "null" ) ) {
iFlags = ( 1 << 2 ) | ( 1 << 5 );
}
g_hooks.m_engine_sound.GetOldMethod<EmitSound_t>( IEngineSound::EMITSOUND )( this, filter, iEntIndex, iChannel, pSoundEntry, nSoundEntryHash, pSample, flVolume, flAttenuation, nSeed, iFlags, iPitch, pOrigin, pDirection, pUtlVecOrigins, bUpdatePositions, soundtime, speakerentity );
}
|
#include "AbstractExpandedDecoder.h"
#include "AI01AndOtherAIs.h"
#include "AI013x0x1xDecoder.h"
#include "AnyAIDecoder.h"
#include "AI013103decoder.h"
#include "AI01320xDecoder.h"
#include "AI01392xDecoder.h"
#include "AI01393xDecoder.h"
namespace zxing {
namespace oned {
namespace rss {
AbstractExpandedDecoder::AbstractExpandedDecoder(Ref<BitArray> information)
: m_information(information), m_generalDecoder(GeneralAppIdDecoder(information))
{
}
Ref<BitArray> AbstractExpandedDecoder::getInformation() const
{
return m_information;
}
GeneralAppIdDecoder AbstractExpandedDecoder::getGeneralDecoder()
{
return m_generalDecoder;
}
AbstractExpandedDecoder *AbstractExpandedDecoder::createDecoder(Ref<BitArray> information)
{
if (information->get(1)) {
return new AI01AndOtherAIs(information);
}
if (!information->get(2)) {
return new AnyAIDecoder(information);
}
int fourBitEncodationMethod = GeneralAppIdDecoder::extractNumericValueFromBitArray(information, 1, 4);
switch (fourBitEncodationMethod) {
case 4: return new AI013103decoder(information);
case 5: return new AI01320xDecoder(information);
}
int fiveBitEncodationMethod = GeneralAppIdDecoder::extractNumericValueFromBitArray(information, 1, 5);
switch (fiveBitEncodationMethod) {
case 12: return new AI01392xDecoder(information);
case 13: return new AI01393xDecoder(information);
}
int sevenBitEncodationMethod = GeneralAppIdDecoder::extractNumericValueFromBitArray(information, 1, 7);
switch (sevenBitEncodationMethod) {
case 56: return new AI013x0x1xDecoder(information, String("310"), String("11"));
case 57: return new AI013x0x1xDecoder(information, String("320"), String("11"));
case 58: return new AI013x0x1xDecoder(information, String("310"), String("13"));
case 59: return new AI013x0x1xDecoder(information, String("320"), String("13"));
case 60: return new AI013x0x1xDecoder(information, String("310"), String("15"));
case 61: return new AI013x0x1xDecoder(information, String("320"), String("15"));
case 62: return new AI013x0x1xDecoder(information, String("310"), String("17"));
case 63: return new AI013x0x1xDecoder(information, String("320"), String("17"));
}
throw IllegalStateException();
}
}
}
}
|
#include "y2020/control_loops/superstructure/superstructure.h"
#include "aos/containers/sized_array.h"
#include "aos/events/event_loop.h"
#include "aos/network/team_number.h"
namespace y2020 {
namespace control_loops {
namespace superstructure {
using frc971::control_loops::AbsoluteAndAbsoluteEncoderProfiledJointStatus;
using frc971::control_loops::AbsoluteEncoderProfiledJointStatus;
using frc971::control_loops::PotAndAbsoluteEncoderProfiledJointStatus;
Superstructure::Superstructure(::aos::EventLoop *event_loop,
const ::std::string &name)
: frc971::controls::ControlLoop<Goal, Position, Status, Output>(event_loop,
name),
hood_(constants::GetValues().hood),
intake_joint_(constants::GetValues().intake),
turret_(constants::GetValues().turret.subsystem_params),
drivetrain_status_fetcher_(
event_loop->MakeFetcher<frc971::control_loops::drivetrain::Status>(
"/drivetrain")),
joystick_state_fetcher_(
event_loop->MakeFetcher<aos::JoystickState>("/aos")),
has_turret_(::aos::network::GetTeamNumber() != 9971) {
event_loop->SetRuntimeRealtimePriority(30);
}
double Superstructure::robot_speed() const {
return (drivetrain_status_fetcher_.get() != nullptr
? drivetrain_status_fetcher_->robot_speed()
: 0.0);
}
void Superstructure::RunIteration(const Goal *unsafe_goal,
const Position *position,
aos::Sender<Output>::Builder *output,
aos::Sender<Status>::Builder *status) {
if (WasReset()) {
AOS_LOG(ERROR, "WPILib reset, restarting\n");
hood_.Reset();
intake_joint_.Reset();
turret_.Reset();
}
const aos::monotonic_clock::time_point position_timestamp =
event_loop()->context().monotonic_event_time;
if (drivetrain_status_fetcher_.Fetch()) {
aos::Alliance alliance = aos::Alliance::kInvalid;
joystick_state_fetcher_.Fetch();
if (joystick_state_fetcher_.get() != nullptr) {
alliance = joystick_state_fetcher_->alliance();
}
const turret::Aimer::WrapMode mode =
(unsafe_goal != nullptr && unsafe_goal->shooting())
? turret::Aimer::WrapMode::kAvoidWrapping
: turret::Aimer::WrapMode::kAvoidEdges;
aimer_.Update(drivetrain_status_fetcher_.get(), alliance, mode,
turret::Aimer::ShotMode::kShootOnTheFly);
}
const float velocity = robot_speed();
const flatbuffers::Offset<AimerStatus> aimer_status_offset =
aimer_.PopulateStatus(status->fbb());
const double distance_to_goal = aimer_.DistanceToGoal();
aos::FlatbufferFixedAllocatorArray<
frc971::control_loops::StaticZeroingSingleDOFProfiledSubsystemGoal, 64>
hood_goal;
aos::FlatbufferFixedAllocatorArray<ShooterGoal, 64> shooter_goal;
constants::Values::ShotParams shot_params;
if (constants::GetValues().shot_interpolation_table.GetInRange(
distance_to_goal, &shot_params)) {
hood_goal.Finish(frc971::control_loops::
CreateStaticZeroingSingleDOFProfiledSubsystemGoal(
*hood_goal.fbb(), shot_params.hood_angle));
shooter_goal.Finish(CreateShooterGoal(*shooter_goal.fbb(),
shot_params.velocity_accelerator,
shot_params.velocity_finisher));
} else {
hood_goal.Finish(
frc971::control_loops::
CreateStaticZeroingSingleDOFProfiledSubsystemGoal(
*hood_goal.fbb(), constants::GetValues().hood.range.upper));
shooter_goal.Finish(CreateShooterGoal(*shooter_goal.fbb(), 0.0, 0.0));
}
OutputT output_struct;
flatbuffers::Offset<AbsoluteAndAbsoluteEncoderProfiledJointStatus>
hood_status_offset = hood_.Iterate(
unsafe_goal != nullptr
? (unsafe_goal->hood_tracking() ? &hood_goal.message()
: unsafe_goal->hood())
: nullptr,
position->hood(),
output != nullptr ? &(output_struct.hood_voltage) : nullptr,
status->fbb());
bool intake_out_jostle = false;
if (unsafe_goal != nullptr) {
if (unsafe_goal->shooting() &&
shooting_start_time_ == aos::monotonic_clock::min_time) {
shooting_start_time_ = position_timestamp;
}
if (unsafe_goal->shooting()) {
intake_joint_.set_max_acceleration(30.0);
constexpr std::chrono::milliseconds kPeriod =
std::chrono::milliseconds(250);
if ((position_timestamp - shooting_start_time_) % (kPeriod * 2) <
kPeriod) {
intake_joint_.set_min_position(-0.25);
intake_out_jostle = false;
} else {
intake_out_jostle = true;
intake_joint_.set_min_position(-0.75);
}
} else {
intake_joint_.clear_max_acceleration();
intake_joint_.clear_min_position();
}
if (!unsafe_goal->shooting()) {
shooting_start_time_ = aos::monotonic_clock::min_time;
}
}
flatbuffers::Offset<AbsoluteEncoderProfiledJointStatus> intake_status_offset =
intake_joint_.Iterate(
unsafe_goal != nullptr ? unsafe_goal->intake() : nullptr,
position->intake_joint(),
output != nullptr ? &(output_struct.intake_joint_voltage) : nullptr,
status->fbb());
const frc971::control_loops::StaticZeroingSingleDOFProfiledSubsystemGoal
*turret_goal = unsafe_goal != nullptr ? (unsafe_goal->turret_tracking()
? aimer_.TurretGoal()
: unsafe_goal->turret())
: nullptr;
flatbuffers::Offset<PotAndAbsoluteEncoderProfiledJointStatus>
turret_status_offset;
if (has_turret_) {
turret_status_offset = turret_.Iterate(
turret_goal, position->turret(),
output != nullptr ? &(output_struct.turret_voltage) : nullptr,
status->fbb());
} else {
PotAndAbsoluteEncoderProfiledJointStatus::Builder turret_builder(
*status->fbb());
turret_builder.add_position(M_PI);
turret_builder.add_velocity(0.0);
turret_status_offset = turret_builder.Finish();
}
flatbuffers::Offset<ShooterStatus> shooter_status_offset =
shooter_.RunIteration(
unsafe_goal != nullptr
? (unsafe_goal->shooter_tracking() ? &shooter_goal.message()
: unsafe_goal->shooter())
: nullptr,
position->shooter(), status->fbb(),
output != nullptr ? &(output_struct) : nullptr, position_timestamp);
const AbsoluteAndAbsoluteEncoderProfiledJointStatus *const hood_status =
GetMutableTemporaryPointer(*status->fbb(), hood_status_offset);
const PotAndAbsoluteEncoderProfiledJointStatus *const turret_status =
GetMutableTemporaryPointer(*status->fbb(), turret_status_offset);
if (output != nullptr) {
// Friction is a pain and putting a really high burden on the integrator.
// TODO(james): I'm not sure how helpful this gain is.
const double turret_velocity_sign =
turret_status->velocity() * kTurretFrictionGain;
output_struct.turret_voltage +=
std::clamp(turret_velocity_sign, -kTurretFrictionVoltageLimit,
kTurretFrictionVoltageLimit);
const double time_sec =
aos::time::DurationInSeconds(position_timestamp.time_since_epoch());
output_struct.turret_voltage +=
kTurretDitherGain * std::sin(2.0 * M_PI * time_sec * 30.0);
output_struct.turret_voltage =
std::clamp(output_struct.turret_voltage, -turret_.operating_voltage(),
turret_.operating_voltage());
}
bool zeroed;
bool estopped;
{
const AbsoluteEncoderProfiledJointStatus *const intake_status =
GetMutableTemporaryPointer(*status->fbb(), intake_status_offset);
zeroed = hood_status->zeroed() && intake_status->zeroed() &&
turret_status->zeroed();
estopped = hood_status->estopped() || intake_status->estopped() ||
turret_status->estopped();
}
flatbuffers::Offset<flatbuffers::Vector<Subsystem>>
subsystems_not_ready_offset;
const bool turret_ready =
(std::abs(turret_.goal(0) - turret_.position()) < 0.025) || !has_turret_;
if (unsafe_goal && unsafe_goal->shooting() &&
(!shooter_.ready() || !turret_ready)) {
aos::SizedArray<Subsystem, 3> subsystems_not_ready;
if (!shooter_.finisher_ready()) {
subsystems_not_ready.push_back(Subsystem::FINISHER);
}
if (!shooter_.accelerator_ready()) {
subsystems_not_ready.push_back(Subsystem::ACCELERATOR);
}
if (!turret_ready) {
subsystems_not_ready.push_back(Subsystem::TURRET);
}
subsystems_not_ready_offset =
status->fbb()->CreateVector(subsystems_not_ready.backing_array().data(),
subsystems_not_ready.size());
}
Status::Builder status_builder = status->MakeBuilder<Status>();
status_builder.add_zeroed(zeroed);
status_builder.add_estopped(estopped);
status_builder.add_hood(hood_status_offset);
status_builder.add_intake(intake_status_offset);
status_builder.add_turret(turret_status_offset);
status_builder.add_shooter(shooter_status_offset);
status_builder.add_aimer(aimer_status_offset);
status_builder.add_subsystems_not_ready(subsystems_not_ready_offset);
status_builder.add_send_failures(status_failure_counter_.failures());
status_failure_counter_.Count(status->Send(status_builder.Finish()));
if (output != nullptr) {
output_struct.washing_machine_spinner_voltage = 0.0;
output_struct.feeder_voltage = 0.0;
output_struct.intake_roller_voltage = 0.0;
output_struct.climber_voltage = 0.0;
if (unsafe_goal) {
if (unsafe_goal->has_turret()) {
output_struct.climber_voltage =
std::clamp(unsafe_goal->climber_voltage(), -12.0f, 12.0f);
// Make sure the turret is relatively close to the goal before turning
// the climber on.
CHECK(unsafe_goal->has_turret());
if (std::abs(unsafe_goal->turret()->unsafe_goal() -
turret_.position()) > 0.1 &&
has_turret_) {
output_struct.climber_voltage = 0;
}
}
if (unsafe_goal->shooting() || unsafe_goal->intake_preloading()) {
preloading_timeout_ = position_timestamp + kPreloadingTimeout;
}
if (position_timestamp <= preloading_timeout_ &&
!position->intake_beambreak_triggered()) {
output_struct.washing_machine_spinner_voltage = 5.0;
output_struct.feeder_voltage = 12.0;
preloading_backpower_timeout_ =
position_timestamp + kPreloadingBackpowerDuration;
}
if (position->intake_beambreak_triggered() &&
position_timestamp <= preloading_backpower_timeout_) {
output_struct.feeder_voltage = -12.0;
}
if (unsafe_goal->has_feed_voltage_override()) {
output_struct.feeder_voltage = unsafe_goal->feed_voltage_override();
output_struct.washing_machine_spinner_voltage = -5.0;
preloading_timeout_ = position_timestamp;
}
if (unsafe_goal->shooting()) {
if ((shooter_.ready() ||
(!has_turret_ && shooter_.accelerator_ready())) &&
turret_ready) {
output_struct.feeder_voltage = 12.0;
}
if (!intake_out_jostle) {
output_struct.washing_machine_spinner_voltage = 5.0;
} else {
output_struct.washing_machine_spinner_voltage = -5.0;
}
output_struct.intake_roller_voltage = 3.0;
} else {
output_struct.intake_roller_voltage =
unsafe_goal->roller_voltage() +
std::max(velocity * unsafe_goal->roller_speed_compensation(), 0.0f);
}
}
output->CheckOk(output->Send(Output::Pack(*output->fbb(), &output_struct)));
}
}
} // namespace superstructure
} // namespace control_loops
} // namespace y2020
|
//
// lager - library for functional interactive c++ programs
// Copyright (C) 2017 Juan Pedro Bolivar Puente
//
// This file is part of lager.
//
// lager is free software: you can redistribute it and/or modify
// it under the terms of the MIT License, as detailed in the LICENSE
// file located at the root of this source code distribution,
// or here: <https://github.com/arximboldi/lager/blob/master/LICENSE>
//
#pragma once
#include <lager/detail/access.hpp>
#include <lager/detail/nodes.hpp>
#include <lager/cursor.hpp>
namespace lager {
namespace detail {
template <typename ParentT, typename FnT>
class setter_node : public cursor_node<typename ParentT::value_type>
{
using base_t = cursor_node<typename ParentT::value_type>;
std::shared_ptr<ParentT> parent_;
FnT setter_fn_;
public:
using value_type = typename ParentT::value_type;
setter_node(std::shared_ptr<ParentT> p, FnT fn)
: base_t{p->current()}
, parent_{std::move(p)}
, setter_fn_{std::move(fn)}
{}
void recompute() final { this->push_down(parent_->current()); }
void refresh() final { parent_->refresh(); }
void send_up(const value_type& value) override
{
this->push_down(value);
setter_fn_(value);
}
void send_up(value_type&& value) override
{
this->push_down(std::move(value));
setter_fn_(value);
}
};
template <typename ParentT, typename FnT>
auto make_setter_node(std::shared_ptr<ParentT> p, FnT&& fn)
{
using node_t = setter_node<ParentT, std::decay_t<FnT>>;
auto&& pv = *p;
auto n = std::make_shared<node_t>(std::move(p), std::forward<FnT>(fn));
pv.link(n);
return n;
}
} // namespace detail
template <typename ReaderNode, typename FnT>
auto with_setter(reader_base<ReaderNode> r, FnT&& fn)
{
auto node = make_setter_node(detail::access::node(std::move(r)),
std::forward<FnT>(fn));
using node_t = typename decltype(node)::element_type;
return cursor_base<node_t>{std::move(node)};
}
} // namespace lager
|
#include "ooasm.h"
#include "computer.h"
#include <string>
#include <sstream>
#include <cassert>
namespace {
std::string memory_dump(Computer const& computer) {
std::stringstream ss;
computer.memory_dump(ss);
return ss.str();
}
}
int main() {
auto ooasm_move = program({
mov(mem(num(0)), num(42))
});
Computer computer1(1);
computer1.boot(ooasm_move);
assert(memory_dump(computer1) == "42 ");
auto ooasm_ones = program({
dec(mem(num(1))),
ones(mem(num(0)))
});
Computer computer2(2);
computer2.boot(ooasm_ones);
assert(memory_dump(computer2) == "1 -1 ");
auto ooasm_data = program({
inc(mem(lea("a"))),
data("a", num(0)),
data("b", num(2)),
data("c", num(3))
});
Computer computer3(4);
computer3.boot(ooasm_data);
assert(memory_dump(computer3) == "1 2 3 0 ");
auto ooasm_operations = program({
data("a", num(4)),
data("b", num(3)),
data("c", num(2)),
data("d", num(1)),
add(mem(lea("a")), mem(lea("c"))),
sub(mem(lea("b")), mem(lea("d"))),
mov(mem(lea("c")), num(0)),
mov(mem(lea("d")), num(0))
});
Computer computer4(5);
computer4.boot(ooasm_operations);
assert(memory_dump(computer4) == "6 2 0 0 0 ");
}
|
#include <codegen/MachineCodeGenerator.h>
#include <storage/FileLoader.h>
#include <wamr/WAMRWasmModule.h>
#include <wavm/WAVMWasmModule.h>
#include <openssl/sha.h>
#include <stdexcept>
#include <faabric/util/bytes.h>
#include <faabric/util/config.h>
#include <faabric/util/files.h>
#include <faabric/util/func.h>
using namespace faabric::util;
namespace codegen {
MachineCodeGenerator& getMachineCodeGenerator()
{
static thread_local MachineCodeGenerator gen;
return gen;
}
MachineCodeGenerator::MachineCodeGenerator()
: conf(conf::getFaasmConfig())
, loader(storage::getFileLoader())
{}
MachineCodeGenerator::MachineCodeGenerator(storage::FileLoader& loaderIn)
: conf(conf::getFaasmConfig())
, loader(loaderIn)
{}
std::vector<uint8_t> MachineCodeGenerator::hashBytes(
std::span<const uint8_t> bytes)
{
std::vector<uint8_t> result(SHA256_DIGEST_LENGTH);
SHA256(reinterpret_cast<const unsigned char*>(bytes.data()),
bytes.size(),
result.data());
return result;
}
std::vector<uint8_t> MachineCodeGenerator::doCodegen(
std::vector<uint8_t>& bytes,
conf::CodegenTargetSpec target,
const std::string& fileName,
bool isSgx)
{
if (conf.wasmVm == "wamr") {
return wasm::wamrCodegen(bytes, target, isSgx);
} else {
assert(isSgx == false);
return wasm::wavmCodegen(bytes, target, fileName);
}
}
void MachineCodeGenerator::codegenForFunction(faabric::Message& msg)
{
std::vector<uint8_t> bytes = loader.loadFunctionWasm(msg);
const std::string funcStr = funcToString(msg, false);
if (bytes.empty()) {
throw std::runtime_error("Loaded empty bytes for " + funcStr);
}
for (const auto& target : conf.codegenTargets) {
// Compare hashes
std::vector<uint8_t> newHash = hashBytes(bytes);
std::vector<uint8_t> oldHash;
if (conf.wasmVm == "wamr") {
oldHash = loader.loadFunctionWamrAotHash(msg, target);
} else if (conf.wasmVm == "wavm" && msg.issgx()) {
SPDLOG_ERROR(
"Can't run SGX codegen for WAVM. Only WAMR is supported.");
throw std::runtime_error("SGX codegen for WAVM");
} else {
oldHash = loader.loadFunctionObjectHash(msg, target);
}
if ((!oldHash.empty()) && newHash == oldHash) {
// Even if we skip the code generation step, we want to sync the
// latest object file
if (conf.wasmVm == "wamr") {
UNUSED(loader.loadFunctionWamrAotHash(msg, target));
} else {
UNUSED(loader.loadFunctionObjectFile(msg, target));
}
SPDLOG_DEBUG("Skipping codegen for {}", funcStr);
return;
} else if (oldHash.empty()) {
SPDLOG_DEBUG("No old hash found for {}", funcStr);
} else {
SPDLOG_DEBUG("Hashes differ for {}", funcStr);
}
// Run the actual codegen
std::vector<uint8_t> objBytes;
try {
objBytes = doCodegen(bytes, target, funcStr, msg.issgx());
} catch (std::runtime_error& ex) {
SPDLOG_ERROR("Codegen failed for " + funcStr);
throw ex;
}
// Upload the file contents and the hash
if (conf.wasmVm == "wamr") {
loader.uploadFunctionWamrAotFile(msg, target, objBytes);
loader.uploadFunctionWamrAotHash(msg, target, newHash);
} else {
loader.uploadFunctionObjectFile(msg, target, objBytes);
loader.uploadFunctionObjectHash(msg, target, newHash);
}
}
}
void MachineCodeGenerator::codegenForSharedObject(const std::string& inputPath)
{
// Load the wasm
std::vector<uint8_t> bytes = loader.loadSharedObjectWasm(inputPath);
// Check the hash
std::vector<uint8_t> newHash = hashBytes(bytes);
for (const auto& target : conf.codegenTargets) {
std::vector<uint8_t> oldHash =
loader.loadSharedObjectObjectHash(inputPath, target);
if ((!oldHash.empty()) && newHash == oldHash) {
// Even if we skip the code generation step, we want to sync the
// latest shared object object file
UNUSED(loader.loadSharedObjectObjectFile(inputPath, target));
SPDLOG_DEBUG("Skipping codegen for {}", inputPath);
return;
}
// Run the actual codegen
std::vector<uint8_t> objBytes = doCodegen(bytes, target, inputPath);
// Do the upload
if (conf.wasmVm == "wamr") {
throw std::runtime_error(
"Codegen for shared objects not supported with WAMR");
}
loader.uploadSharedObjectObjectFile(inputPath, target, objBytes);
loader.uploadSharedObjectObjectHash(inputPath, target, newHash);
}
}
}
|
//
// Copyright (C) 2019 Rian Quinn <user@gmail.com>
//
// 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.
// -----------------------------------------------------------------------------
#ifdef EXAMPLE01
int main(void) {
int n = 42;
int d = 0;
auto f = n / d;
}
// /home/user/book/chapter07/recipe03.cpp:30:15: runtime error: division by zero
// Floating point exception (core dumped)
#endif
// -----------------------------------------------------------------------------
#ifdef EXAMPLE02
int main(void) {
int* p = 0;
*p = 42;
}
// /home/user/book/chapter07/recipe03.cpp:44:8: runtime error: store to null pointer of type 'int'
// Segmentation fault (core dumped)
#endif
// -----------------------------------------------------------------------------
#ifdef EXAMPLE03
int main(void) {
int numbers[] = {4, 8, 15, 16, 23, 42};
numbers[10] = 0;
}
// /home/user/book/chapter07/recipe03.cpp:58:15: runtime error: index 10 out of bounds for type 'int [6]'
// /home/user/book/chapter07/recipe03.cpp:58:17: runtime error: store to address 0x7ffe75e7a0c8 with insufficient space for an object of
// type 'int' 0x7ffe75e7a0c8: note: pointer points here 00 00 00 00 33 df e9 73 49 7f 00 00 68 ff ff ff ff ff ff ff a8 a1 e7 75 fe 7f 00 00
// 60 0b cf 74
#endif
// -----------------------------------------------------------------------------
#ifdef EXAMPLE04
#include <climits>
int main(void) {
int i = INT_MAX;
i++;
}
// /home/user/book/chapter07/recipe03.cpp:76:6: runtime error: signed integer overflow: 2147483647 + 1 cannot be represented in type 'int'
#endif
|
/*
* Copyright (c) 2020 Huawei Technologies Co.,Ltd.
*
* openGauss is licensed under Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
* -------------------------------------------------------------------------
*
* hll_mpp.cpp
* distribute hll aggregation
*
* Description: distribute hll aggregation
*
* The design of HLL distribute agg
* ---------------------------------
*
* client
* |
* CN <---(2) collect phase (union hll_trans_type) (3) final phase (hll_trans_type to hll_type)
* / \
* / \ <-- dn pass the partial aggregated hll_trans_type value to cn
* / \
* DN1 DN2 <---(1) trans phase: iterate every tuple on DN and apply transfunc
* ----- -----
* | 1 | | 2 |
* | 3 | | 4 |
* | 5 | | 6 | <--- tuples
* | 7 | | 8 |
* ----- -----
*
* Thanks to the nature of HyperLogLog algorithm we can use three phased aggregation
* for the sake of ultimate performance in distribute computing.
* In Three-Phased-Agg each DN can apply the thrans phase function
* on the hashval/hll available at the Datanode. The result of transition
* phase is then transferred to the Coordinator node for collect & final
* phase processing.
*
* We create a temporary variable of data type namely hll_trans_type
* to hold the current internal state of the trans phase and collection phase
* For every input from the datanode(result of transition phase on that node),
* the collection function is invoked with the current collection state
* value and the new transition value(obtained from the datanode) to
* caculate a new internal collection state value.
*
* After all the transition values from the data nodes have been processed.
* In the third or finalization phase the final function is invoked once
* to covert the internal state type(hll_trans_type) to the hll type.
*
*
* A word about the hll_trans_type
* ---------------------------------
* we have two different data structure to repersent HyperLogLog
* namely the hll_type(packed) and hll_trans_type(unpakced). The packed type
* is small in size(1.2k typical) and good for storing the hll data in a table
* and pass hll around through network channel. However it not well suited
* for computing(add/union of hll). So we have a hll_trans_type(unpakced)
* to do the computing and for internal state passing in distribute aggeration.
*
* Compared to greenplumn implementation of distribute hll, we avoid
* the high cost of pack-unpack. Therefore we have a performance boost
* under distribute aggeration. Roughly, 1x-10x performance gain compared with
* sort/hash agg implementation of distinct algorithm.
*
* hll_add_agg
* ------------
* trans phase function : hll_trans_type hll_add_trans0(hll_trans_type, hll_hash_val)
* collect phase function: hll_trans_type hll_union_collect(hll_trans_type, hll_trans_type)
* final phase function : hll hll_pack(hll_trans_type)
*
* client
* |
* CN <---(2) collect phase: hll_trans_type hll_union_collect(hll_trans_type, hll_trans_type)
* <---(3) final phase : hll hll_pack(hll_trans_type)
* / \
* / \ <-- dn pass the partial aggregated hll_trans_type value to cn
* / \
* DN1 DN2
* ----- -----
* | 1 | | 2 |
* | 3 | | 4 |
* | 5 | | 6 | <--- (1) trans phase: hll_trans_type hll_add_trans0(hll_trans_type, hll_hash_val)
* | 7 | | 8 |
* ----- -----
*
* hll_union_agg
* --------------
* trans phase function : hll_trans_type hll_union_trans(hll_trans_type, hll)
* collect phase function: hll_trans_type hll_union_collect(hll_trans_type, hll_trans_type)
* final phase function : hll hll_pack(hll_trans_type)
*
* client
* |
* CN <---(2) collect phase: hll_trans_type hll_union_collect(hll_trans_type, hll_trans_type)
* <---(3) final phase : hll hll_pack(hll_trans_type)
* / \
* / \ <-- dn pass the partial aggregated hll_trans_type value to cn
* / \
* DN1 DN2
* ----- -----
* | 1 | | 2 |
* | 3 | | 4 |
* | 5 | | 6 | <--- (1) trans phase: hll_trans_type hll_union_trans(hll_trans_type, hll)
* | 7 | | 8 |
* ----- -----
* IDENTIFICATION
* src/gausskernel/cbb/utils/hll/hll_mpp.cpp
*
* -------------------------------------------------------------------------
*/
#include <postgres.h>
#include "catalog/pg_type.h"
#include "catalog/pg_aggregate.h"
#include "commands/extension.h"
#include "nodes/nodeFuncs.h"
#include "libpq/pqformat.h"
#include "utils/hll.h"
#include "utils/hll_mpp.h"
#include "utils/bytea.h"
PG_FUNCTION_INFO_V1(hll_add_trans0);
PG_FUNCTION_INFO_V1(hll_add_trans1);
PG_FUNCTION_INFO_V1(hll_add_trans2);
PG_FUNCTION_INFO_V1(hll_add_trans3);
PG_FUNCTION_INFO_V1(hll_add_trans4);
PG_FUNCTION_INFO_V1(hll_union_collect);
PG_FUNCTION_INFO_V1(hll_union_trans);
PG_FUNCTION_INFO_V1(hll_pack);
PG_FUNCTION_INFO_V1(hll_trans_recv);
PG_FUNCTION_INFO_V1(hll_trans_send);
PG_FUNCTION_INFO_V1(hll_trans_in);
PG_FUNCTION_INFO_V1(hll_trans_out);
static void handleParameter(HllPara *hllpara, FunctionCallInfo fcinfo);
static bool contain_hll_agg_walker(Node *node, int *context);
static int contain_hll_agg(Node *node);
static Datum hll_add_trans_n(FunctionCallInfo fcinfo);
/* Support disabling hash aggregation functionality for PG > 9.6 */
#if PG_VERSION_NUM >= 90600
#define EXTENSION_NAME "hll"
#define ADD_AGG_NAME "hll_add_agg"
#define UNION_AGG_NAME "hll_union_agg"
#define HLL_AGGREGATE_COUNT 6
static Oid hllAggregateArray[HLL_AGGREGATE_COUNT];
static bool aggregateValuesInitialized = false;
static bool ForceGroupAgg = false;
static create_upper_paths_hook_type previous_upper_path_hook;
void _PG_init(void);
void _PG_fini(void);
#if (PG_VERSION_NUM >= 110000)
static void hll_aggregation_restriction_hook(PlannerInfo *root, UpperRelationKind stage, RelOptInfo *input_rel,
RelOptInfo *output_rel, void *extra);
#else
static void hll_aggregation_restriction_hook(PlannerInfo *root, UpperRelationKind stage, RelOptInfo *input_rel,
RelOptInfo *output_rel);
#endif
static void InitializeHllAggregateOids(void);
static Oid FunctionOid(const char *schemaName, const char *functionName, int argumentCount, bool missingOk);
static void MaximizeCostOfHashAggregate(Path *path);
static bool HllAggregateOid(Oid aggregateOid);
static void RegisterConfigVariables(void);
/* _PG_init is the shared library initialization function */
void _PG_init(void)
{
/*
* Register HLL configuration variables.
*/
RegisterConfigVariables();
previous_upper_path_hook = create_upper_paths_hook;
create_upper_paths_hook = hll_aggregation_restriction_hook;
}
/* _PG_fini uninstalls extension hooks */
void _PG_fini(void)
{
create_upper_paths_hook = previous_upper_path_hook;
}
/*
* hll_aggregation_restriction_hook is assigned to create_upper_paths_hook to
* check whether there exist a path with hash aggregate. If that aggregate is
* introduced by hll, it's cost is maximized to force planner to not to select
* hash aggregate.
*
* Since the signature of the hook changes after PG 11, we define the signature
* and the previous hook call part of this function depending on the PG version.
*/
static oid
#if (PG_VERSION_NUM >= 110000)
hll_aggregation_restriction_hook(PlannerInfo *root, UpperRelationKind stage, RelOptInfo *input_rel,
RelOptInfo *output_rel, void *extra)
#else
hll_aggregation_restriction_hook(PlannerInfo *root, UpperRelationKind stage, RelOptInfo *input_rel,
RelOptInfo *output_rel)
#endif
{
Oid extensionOid = InvalidOid;
/* If previous hook exist, call it first to get most update path */
if (previous_upper_path_hook != NULL) {
#if (PG_VERSION_NUM >= 110000)
previous_upper_path_hook(root, stage, input_rel, output_rel, extra);
#else
previous_upper_path_hook(root, stage, input_rel, output_rel);
#endif
}
/* If HLL extension is not loaded, do nothing */
extensionOid = get_extension_oid(EXTENSION_NAME, true);
if (!OidIsValid(extensionOid)) {
return;
}
/* If we have the extension, that means we also have aggregations */
if (!aggregateValuesInitialized) {
InitializeHllAggregateOids();
}
/*
* If the client force the group agg, maximize the cost of the path with
* the hash agg to force planner to choose group agg instead.
*/
if (ForceGroupAgg) {
if (stage == UPPERREL_GROUP_AGG || stage == UPPERREL_FINAL) {
ListCell *pathCell = list_head(output_rel->pathlist);
foreach (pathCell, output_rel->pathlist) {
Path *path = (Path *)lfirst(pathCell);
if (path->pathtype == T_Agg && ((AggPath *)path)->aggstrategy == AGG_HASHED) {
MaximizeCostOfHashAggregate(path);
}
}
}
}
}
/*
* InitializeHllAggregateOids initializes the array of hll aggregate oids.
*/
static void InitializeHllAggregateOids()
{
Oid extensionId = get_extension_oid(EXTENSION_NAME, false);
Oid hllSchemaOid = get_extension_schema(extensionId);
const char *hllSchemaName = get_namespace_name(hllSchemaOid);
char *aggregateName = NULL;
Oid aggregateOid = InvalidOid;
int addAggArgumentCounter;
/* Initialize HLL_UNION_AGG oid */
aggregateName = UNION_AGG_NAME;
aggregateOid = FunctionOid(hllSchemaName, aggregateName, 1, true);
hllAggregateArray[0] = aggregateOid;
/* Initialize HLL_ADD_AGG with different signatures */
aggregateName = ADD_AGG_NAME;
for (addAggArgumentCounter = 1; addAggArgumentCounter < HLL_AGGREGATE_COUNT; addAggArgumentCounter++) {
aggregateOid = FunctionOid(hllSchemaName, aggregateName, addAggArgumentCounter, true);
hllAggregateArray[addAggArgumentCounter] = aggregateOid;
}
aggregateValuesInitialized = true;
}
/*
* FunctionOid searches for a given function identified by schema, functionName
* and argumentCount. It reports error if the function is not found or there
* are more than one match. If the missingOK parameter is set and there are
* no matches, then the function returns InvalidOid.
*/
static Oid FunctionOid(const char *schemaName, const char *functionName, int argumentCount, bool missingOK)
{
FuncCandidateList functionList = NULL;
Oid functionOid = InvalidOid;
char *qualifiedFunctionName = quote_qualified_identifier(schemaName, functionName);
List *qualifiedFunctionNameList = stringToQualifiedNameList(qualifiedFunctionName);
List *argumentList = NIL;
const bool findVariadics = false;
const bool findDefaults = false;
functionList = FuncnameGetCandidates(qualifiedFunctionNameList, argumentCount, argumentList, findVariadics,
findDefaults, true);
if (functionList == NULL) {
if (missingOK) {
return InvalidOid;
}
ereport(ERROR, (errcode(ERRCODE_UNDEFINED_FUNCTION), errmsg("function \"%s\" does not exist", functionName)));
} else if (functionList->next != NULL) {
ereport(ERROR,
(errcode(ERRCODE_AMBIGUOUS_FUNCTION), errmsg("more than one function named \"%s\"", functionName)));
}
/* get function oid from function list's head */
functionOid = functionList->oid;
return functionOid;
}
/*
* MaximizeCostOfHashAggregate maximizes the cost of the path if it tries
* to run hll aggregate function with hash aggregate.
*/
static void MaximizeCostOfHashAggregate(Path *path)
{
List *varList = pull_var_clause((Node *)path->pathtarget->exprs, PVC_INCLUDE_AGGREGATES);
ListCell *varCell = NULL;
foreach (varCell, varList) {
Var *var = (Var *)lfirst(varCell);
if (nodeTag(var) == T_Aggref) {
Aggref *aggref = (Aggref *)var;
if (HllAggregateOid(aggref->aggfnoid)) {
path->total_cost = INT_MAX;
}
}
}
}
/*
* HllAggregateOid checkes whether the given Oid is an id of any hll aggregate
* function using the pre-initialized hllAggregateArray.
*/
static bool HllAggregateOid(Oid aggregateOid)
{
int arrayCounter;
for (arrayCounter = 0; arrayCounter < HLL_AGGREGATE_COUNT; arrayCounter++) {
if (aggregateOid == hllAggregateArray[arrayCounter]) {
return true;
}
}
return false;
}
/* Register HLL configuration variables. */
static void RegisterConfigVariables(void)
{
DefineCustomBoolVariable("hll.force_groupagg",
gettext_noop("Forces using group aggregate with hll aggregate functions"), NULL, &ForceGroupAgg, false,
PGC_USERSET, 0, NULL, NULL, NULL);
}
#endif
/* similar to function hll_emptyn */
static void handleParameter(HllPara *hllpara, FunctionCallInfo fcinfo)
{
int32_t log2Registers = u_sess->attr.attr_sql.hll_default_log2m;
int32_t log2Explicitsize = u_sess->attr.attr_sql.hll_default_log2explicit;
int32_t log2Sparsesize = u_sess->attr.attr_sql.hll_default_log2sparse;
int32_t duplicateCheck = u_sess->attr.attr_sql.hll_duplicate_check;
switch (PG_NARGS()) {
case HLL_AGG_PARAMETER4:
if (!PG_ARGISNULL(5) && PG_GETARG_INT32(5) != -1) {
duplicateCheck = PG_GETARG_INT32(5);
}
case HLL_AGG_PARAMETER3:
if (!PG_ARGISNULL(4) && PG_GETARG_INT64(4) != -1) {
log2Sparsesize = (int32_t)PG_GETARG_INT64(4);
}
case HLL_AGG_PARAMETER2:
if (!PG_ARGISNULL(3) && PG_GETARG_INT32(3) != -1) {
log2Explicitsize = PG_GETARG_INT32(3);
}
case HLL_AGG_PARAMETER1:
if (!PG_ARGISNULL(2) && PG_GETARG_INT32(2) != -1) {
log2Registers = PG_GETARG_INT32(2);
}
case HLL_AGG_PARAMETER0:
break;
default: /* can never reach here */
ereport(ERROR, (errcode(ERRCODE_DATA_EXCEPTION), errmsg("no such parameters of input")));
}
HllCheckPararange(log2Registers, log2Explicitsize, log2Sparsesize, duplicateCheck);
hllpara->log2Registers = (uint8_t)log2Registers;
hllpara->log2Explicitsize = (uint8_t)log2Explicitsize;
hllpara->log2Sparsesize = (uint8_t)log2Sparsesize;
hllpara->duplicateCheck = (uint8_t)duplicateCheck;
}
/*
* @Description: transfunc for agg func hll_add_agg()
*
* these function works on the first phase of aggeration.
* namely the transfunc. And they are *not* strict regrading
* of NULL handling upon the first invoke of the function in
* the aggretation.
*
* we provide hll_add_trans function with different number
* of parameters which maximum to four and minimum to zero
*/
Datum hll_add_trans0(PG_FUNCTION_ARGS)
{
return hll_add_trans_n(fcinfo);
}
Datum hll_add_trans1(PG_FUNCTION_ARGS)
{
return hll_add_trans_n(fcinfo);
}
Datum hll_add_trans2(PG_FUNCTION_ARGS)
{
return hll_add_trans_n(fcinfo);
}
Datum hll_add_trans3(PG_FUNCTION_ARGS)
{
return hll_add_trans_n(fcinfo);
}
Datum hll_add_trans4(PG_FUNCTION_ARGS)
{
return hll_add_trans_n(fcinfo);
}
/*
* @Description:
* this function will be called by hll_add_agg, similar to function hll_add.
*
* @param[IN] hll: NULL indicates the first call, hll passed as input.
* @param[IN] hashval: the hashval need to be add to multiset_t.
* @return hll.
*/
static Datum hll_add_trans_n(FunctionCallInfo fcinfo)
{
/* We must be called as a transition routine or we fail. */
MemoryContext aggctx = NULL;
if (!AggCheckCallContext(fcinfo, &aggctx)) {
ereport(ERROR, (errcode(ERRCODE_DATA_EXCEPTION), errmsg("hll_add_trans_n outside transition context")));
}
/* handle numbers of parameter we need to take */
HllPara hllpara;
handleParameter(&hllpara, fcinfo);
Hll hll(aggctx);
hll.HllInit();
/*
If the first argument is a NULL on first call, init an hll_empty
If it's NON-NULL, unpacked it
*/
if (PG_ARGISNULL(0)) {
hll.HllEmpty();
hll.HllSetPara(hllpara);
} else {
bytea *byteval1 = PG_GETARG_BYTEA_P(0);
size_t hllsize1 = BYTEVAL_LENGTH(byteval1);
hll.HllObjectUnpack((uint8_t *)VARDATA(byteval1), hllsize1);
}
/* Is the second argument non-null? */
if (!PG_ARGISNULL(1)) {
uint64_t hashvalue = (uint64_t)PG_GETARG_INT64(1);
hll.HllAdd(hashvalue);
}
/* packed hll then return it, hllsize should allocate at least 1 more byte */
size_t hllsize2 = HLL_HEAD_SIZE + hll.HllDatalen() + 1;
bytea *byteval2 = (bytea *)palloc0(VARHDRSZ + hllsize2);
SET_VARSIZE(byteval2, VARHDRSZ + hllsize2);
hll.HllObjectPack((uint8_t *)VARDATA(byteval2), hllsize2);
hll.HllFree();
PG_RETURN_BYTEA_P(byteval2);
}
/*
* @Description: collectfunc for agg func hll_add_agg() and hll_union_agg(), similar to function hll_union.
*
* @param[IN] hll: NULL indicates the first call, passed in the
* transvalue in the successive call
* @param[IN] hll: the other hll to be unioned.
* @return the unioned hll as the transvalue.
*/
Datum hll_union_collect(PG_FUNCTION_ARGS)
{
/*
* If both arguments are null then we return null, because we shouldn't
* return any hll with UNINIT type state.
*/
if (PG_ARGISNULL(0) && PG_ARGISNULL(1)) {
PG_RETURN_NULL();
}
/* now inputs are all hll, we need unpack them, calculate and return hll. */
MemoryContext aggctx = NULL;
if (!AggCheckCallContext(fcinfo, &aggctx)) {
ereport(ERROR, (errcode(ERRCODE_DATA_EXCEPTION), errmsg("hll_union_collect outside transition context")));
}
Hll hll1(aggctx);
hll1.HllInit();
if (!PG_ARGISNULL(0)) {
bytea *byteval1 = PG_GETARG_BYTEA_P(0);
size_t hllsize1 = BYTEVAL_LENGTH(byteval1);
hll1.HllObjectUnpack((uint8_t *)VARDATA(byteval1), hllsize1);
}
if (!PG_ARGISNULL(1)) {
Hll hll2(aggctx);
hll2.HllInit();
bytea *byteval2 = PG_GETARG_BYTEA_P(1);
size_t hllsize2 = BYTEVAL_LENGTH(byteval2);
hll2.HllObjectUnpack((uint8_t *)VARDATA(byteval2), hllsize2);
if (hll1.HllGetType() != HLL_UNINIT) {
HllCheckParaequal(*hll1.HllGetPara(), *hll2.HllGetPara());
}
hll1.HllUnion(hll2);
hll2.HllFree();
}
/* packed multiset_t to hll then return it, hllsize should allocate at least 1 more byte */
size_t hllsize3 = HLL_HEAD_SIZE + hll1.HllDatalen() + 1;
bytea *byteval3 = (bytea *)palloc0(VARHDRSZ + hllsize3);
SET_VARSIZE(byteval3, VARHDRSZ + hllsize3);
hll1.HllObjectPack((uint8_t *)VARDATA(byteval3), hllsize3);
hll1.HllFree();
PG_RETURN_BYTEA_P(byteval3);
}
/*
* @Description: transfunc for agg func hll_union_agg()
*
* this function works on the first stage for agg func hll_union_agg()
*
* @param[IN] hll: the transvalue for aggeration
* @param[IN] hll: passed column(type is hll) for hll_union_agg()
* @return hll
*/
Datum hll_union_trans(PG_FUNCTION_ARGS)
{
/*
* If both arguments are null then we return null, because we shouldn't
* return any hll with UNINIT type state.
*/
if (PG_ARGISNULL(0) && PG_ARGISNULL(1)) {
PG_RETURN_NULL();
}
/* now inputs are all hll, we need unpack them, calculate and return hll. */
MemoryContext aggctx = NULL;
if (!AggCheckCallContext(fcinfo, &aggctx)) {
ereport(ERROR, (errcode(ERRCODE_DATA_EXCEPTION), errmsg("hll_union_trans outside transition context")));
}
Hll hll1(aggctx);
hll1.HllInit();
if (!PG_ARGISNULL(0)) {
bytea *byteval1 = PG_GETARG_BYTEA_P(0);
size_t hllsize1 = BYTEVAL_LENGTH(byteval1);
hll1.HllObjectUnpack((uint8_t *)VARDATA(byteval1), hllsize1);
}
if (!PG_ARGISNULL(1)) {
Hll hll2(aggctx);
hll2.HllInit();
bytea *byteval2 = PG_GETARG_BYTEA_P(1);
size_t hllsize2 = BYTEVAL_LENGTH(byteval2);
hll2.HllObjectUnpack((uint8_t *)VARDATA(byteval2), hllsize2);
if (hll1.HllGetType() > HLL_UNINIT) {
HllCheckParaequal(*hll1.HllGetPara(), *hll2.HllGetPara());
}
hll1.HllUnion(hll2);
hll2.HllFree();
}
/* packed multiset_t to hll then return it, hllsize should allocate at least 1 more byte */
size_t hllsize3 = HLL_HEAD_SIZE + hll1.HllDatalen() + 1;
bytea *byteval3 = (bytea *)palloc0(VARHDRSZ + hllsize3);
SET_VARSIZE(byteval3, VARHDRSZ + hllsize3);
hll1.HllObjectPack((uint8_t *)VARDATA(byteval3), hllsize3);
hll1.HllFree();
PG_RETURN_BYTEA_P(byteval3);
}
/*
* @Description: finalfunc for agg func hll_add_agg() and hll_union_agg()
*
* this function works on the final stage for hll agg funcs
*/
Datum hll_pack(PG_FUNCTION_ARGS)
{
if (PG_ARGISNULL(0)) {
PG_RETURN_NULL();
}
MemoryContext ctx = CurrentMemoryContext;
Hll hll(ctx);
hll.HllInit();
bytea *byteval = PG_GETARG_BYTEA_P(0);
size_t hllsize = BYTEVAL_LENGTH(byteval);
hll.HllObjectUnpack((uint8_t *)VARDATA(byteval), hllsize);
HllType type = hll.HllGetType();
hll.HllFree();
/* Was the aggregation uninitialized? */
if (type == HLL_UNINIT) {
PG_RETURN_NULL();
} else {
PG_RETURN_BYTEA_P(byteval);
}
}
Datum hll_trans_recv(PG_FUNCTION_ARGS)
{
return DirectFunctionCall1(bytearecv, PG_GETARG_DATUM(0));
}
Datum hll_trans_send(PG_FUNCTION_ARGS)
{
bytea *byteval = (bytea *)PG_GETARG_POINTER(0);
StringInfoData buf;
pq_begintypsend(&buf);
pq_sendbytes(&buf, VARDATA(byteval), BYTEVAL_LENGTH(byteval));
PG_RETURN_BYTEA_P(pq_endtypsend(&buf));
}
Datum hll_trans_in(PG_FUNCTION_ARGS)
{
return DirectFunctionCall1(byteain, PG_GETARG_DATUM(0));
}
Datum hll_trans_out(PG_FUNCTION_ARGS)
{
return DirectFunctionCall1(byteaout, PG_GETARG_DATUM(0));
}
static bool contain_hll_agg_walker(Node *node, int *context)
{
if (node == NULL)
return false;
if (IsA(node, Aggref)) {
Aggref *arf = (Aggref *)node;
if (arf->aggfnoid == HLL_ADD_TRANS0_OID || arf->aggfnoid == HLL_ADD_TRANS1_OID ||
arf->aggfnoid == HLL_ADD_TRANS2_OID || arf->aggfnoid == HLL_ADD_TRANS3_OID ||
arf->aggfnoid == HLL_ADD_TRANS4_OID || arf->aggfnoid == HLL_UNION_TRANS_OID)
(*context)++;
return false;
}
return expression_tree_walker(node, (bool (*)())contain_hll_agg_walker, context);
}
static int contain_hll_agg(Node *node)
{
int count = 0;
(void)contain_hll_agg_walker(node, &count);
return count;
}
/*
* @Description: the function is uesd for estimate used memory in hll mode.
*
* we use function contain_hll_agg and contain_hll_agg_walker to parse query node
* to get numbers of hll_agg functions.
*
* @return: the size of hash_table_size in hll mode which is used for estimate e-memory.
*/
double estimate_hllagg_size(double numGroups, List *tleList)
{
int tmp = contain_hll_agg((Node *)tleList);
double hash_table_size;
int64_t hll_size = (int64_t)(HLL_HEAD_SIZE + BITS_TO_VALUE(u_sess->attr.attr_sql.hll_default_log2m));
hash_table_size = ((numGroups * tmp * hll_size) / 1024L);
return hash_table_size * 2;
}
|
/* file: predict_ratings_partial_result.cpp */
/*******************************************************************************
* Copyright 2014-2018 Intel Corporation
* All Rights Reserved.
*
* If this software was obtained under the Intel Simplified Software License,
* the following terms apply:
*
* The source code, information and material ("Material") contained herein is
* owned by Intel Corporation or its suppliers or licensors, and title to such
* Material remains with Intel Corporation or its suppliers or licensors. The
* Material contains proprietary information of Intel or its suppliers and
* licensors. The Material is protected by worldwide copyright laws and treaty
* provisions. No part of the Material may be used, copied, reproduced,
* modified, published, uploaded, posted, transmitted, distributed or disclosed
* in any way without Intel's prior express written permission. No license under
* any patent, copyright or other intellectual property rights in the Material
* is granted to or conferred upon you, either expressly, by implication,
* inducement, estoppel or otherwise. Any license under such intellectual
* property rights must be express and approved by Intel in writing.
*
* Unless otherwise agreed by Intel in writing, you may not remove or alter this
* notice or any other notice embedded in Materials by Intel or Intel's
* suppliers or licensors in any way.
*
*
* If this software was obtained under the Apache License, Version 2.0 (the
* "License"), the following terms apply:
*
* 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 <jni.h>
#include "daal.h"
#include "implicit_als/prediction/ratings/JRatingsPartialResult.h"
#include "implicit_als_prediction_defines.i"
#include "common_helpers.h"
USING_COMMON_NAMESPACES()
using namespace daal::algorithms::implicit_als::prediction::ratings;
/*
* Class: com_intel_daal_algorithms_implicit_als_prediction_ratings_RatingsPartialResult
* Method: cNewPartialResult
* Signature: ()J
*/
JNIEXPORT jlong JNICALL Java_com_intel_daal_algorithms_implicit_1als_prediction_ratings_RatingsPartialResult_cNewPartialResult
(JNIEnv *env, jobject thisObj)
{
return jniArgument<implicit_als::prediction::ratings::PartialResult>::newObj();
}
/*
* Class: com_intel_daal_algorithms_implicit_als_prediction_ratings_RatingsPartialResult
* Method: cSetResult
* Signature: (JIJ)V
*/
JNIEXPORT void JNICALL Java_com_intel_daal_algorithms_implicit_1als_prediction_ratings_RatingsPartialResult_cSetResult
(JNIEnv *, jobject, jlong presAddr, jint id, jlong resAddr)
{
jniArgument<implicit_als::prediction::ratings::PartialResult>::
set<PartialResultId, implicit_als::prediction::ratings::Result>(presAddr, id, resAddr);
}
|
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
#include <string>
#include <utility>
#include <vector>
#include <gmock/gmock-matchers.h>
#include <gtest/gtest.h>
#include "arrow/json/options.h"
#include "arrow/json/parser.h"
#include "arrow/json/test_common.h"
#include "arrow/status.h"
#include "arrow/testing/gtest_util.h"
#include "arrow/util/string_view.h"
namespace arrow {
namespace json {
using util::string_view;
static std::string scalars_only_src() {
return R"(
{ "hello": 3.5, "world": false, "yo": "thing" }
{ "hello": 3.25, "world": null }
{ "hello": 3.125, "world": null, "yo": "\u5fcd" }
{ "hello": 0.0, "world": true, "yo": null }
)";
}
static std::string nested_src() {
return R"(
{ "hello": 3.5, "world": false, "yo": "thing", "arr": [1, 2, 3], "nuf": {} }
{ "hello": 3.25, "world": null, "arr": [2], "nuf": null }
{ "hello": 3.125, "world": null, "yo": "\u5fcd", "arr": [], "nuf": { "ps": 78 } }
{ "hello": 0.0, "world": true, "yo": null, "arr": null, "nuf": { "ps": 90 } }
)";
}
void AssertUnconvertedStructArraysEqual(const StructArray& expected,
const StructArray& actual);
void AssertUnconvertedArraysEqual(const Array& expected, const Array& actual) {
switch (actual.type_id()) {
case Type::BOOL:
case Type::NA:
return AssertArraysEqual(expected, actual);
case Type::DICTIONARY: {
ASSERT_EQ(expected.type_id(), Type::STRING);
std::shared_ptr<Array> actual_decoded;
ASSERT_OK(DecodeStringDictionary(static_cast<const DictionaryArray&>(actual),
&actual_decoded));
return AssertArraysEqual(expected, *actual_decoded);
}
case Type::LIST: {
ASSERT_EQ(expected.type_id(), Type::LIST);
AssertBufferEqual(*expected.null_bitmap(), *actual.null_bitmap());
const auto& expected_offsets = expected.data()->buffers[1];
const auto& actual_offsets = actual.data()->buffers[1];
AssertBufferEqual(*expected_offsets, *actual_offsets);
auto expected_values = static_cast<const ListArray&>(expected).values();
auto actual_values = static_cast<const ListArray&>(actual).values();
return AssertUnconvertedArraysEqual(*expected_values, *actual_values);
}
case Type::STRUCT:
ASSERT_EQ(expected.type_id(), Type::STRUCT);
return AssertUnconvertedStructArraysEqual(static_cast<const StructArray&>(expected),
static_cast<const StructArray&>(actual));
default:
FAIL();
}
}
void AssertUnconvertedStructArraysEqual(const StructArray& expected,
const StructArray& actual) {
ASSERT_EQ(expected.num_fields(), actual.num_fields());
for (int i = 0; i < expected.num_fields(); ++i) {
auto expected_name = expected.type()->child(i)->name();
auto actual_name = actual.type()->child(i)->name();
ASSERT_EQ(expected_name, actual_name);
AssertUnconvertedArraysEqual(*expected.field(i), *actual.field(i));
}
}
void AssertParseColumns(ParseOptions options, string_view src_str,
const std::vector<std::shared_ptr<Field>>& fields,
const std::vector<std::string>& columns_json) {
std::shared_ptr<Array> parsed;
ASSERT_OK(ParseFromString(options, src_str, &parsed));
auto struct_array = std::static_pointer_cast<StructArray>(parsed);
for (size_t i = 0; i < fields.size(); ++i) {
auto column_expected = ArrayFromJSON(fields[i]->type(), columns_json[i]);
auto column = struct_array->GetFieldByName(fields[i]->name());
AssertUnconvertedArraysEqual(*column_expected, *column);
}
}
// TODO(bkietz) parameterize (at least some of) these tests over UnexpectedFieldBehavior
TEST(BlockParserWithSchema, Basics) {
auto options = ParseOptions::Defaults();
options.explicit_schema =
schema({field("hello", float64()), field("world", boolean()), field("yo", utf8())});
options.unexpected_field_behavior = UnexpectedFieldBehavior::Ignore;
AssertParseColumns(
options, scalars_only_src(),
{field("hello", utf8()), field("world", boolean()), field("yo", utf8())},
{"[\"3.5\", \"3.25\", \"3.125\", \"0.0\"]", "[false, null, null, true]",
"[\"thing\", null, \"\xe5\xbf\x8d\", null]"});
}
TEST(BlockParserWithSchema, Empty) {
auto options = ParseOptions::Defaults();
options.explicit_schema =
schema({field("hello", float64()), field("world", boolean()), field("yo", utf8())});
options.unexpected_field_behavior = UnexpectedFieldBehavior::Ignore;
AssertParseColumns(
options, "",
{field("hello", utf8()), field("world", boolean()), field("yo", utf8())},
{"[]", "[]", "[]"});
}
TEST(BlockParserWithSchema, SkipFieldsOutsideSchema) {
auto options = ParseOptions::Defaults();
options.explicit_schema = schema({field("hello", float64()), field("yo", utf8())});
options.unexpected_field_behavior = UnexpectedFieldBehavior::Ignore;
AssertParseColumns(options, scalars_only_src(),
{field("hello", utf8()), field("yo", utf8())},
{"[\"3.5\", \"3.25\", \"3.125\", \"0.0\"]",
"[\"thing\", null, \"\xe5\xbf\x8d\", null]"});
}
class BlockParserTypeError : public ::testing::TestWithParam<UnexpectedFieldBehavior> {
public:
ParseOptions Options(std::shared_ptr<Schema> explicit_schema) {
auto options = ParseOptions::Defaults();
options.explicit_schema = std::move(explicit_schema);
options.unexpected_field_behavior = GetParam();
return options;
}
};
TEST_P(BlockParserTypeError, FailOnInconvertible) {
auto options = Options(schema({field("a", int32())}));
std::shared_ptr<Array> parsed;
Status error = ParseFromString(options, "{\"a\":0}\n{\"a\":true}", &parsed);
ASSERT_RAISES(Invalid, error);
EXPECT_THAT(
error.message(),
testing::StartsWith(
"JSON parse error: Column(/a) changed from number to boolean in row 1"));
}
TEST_P(BlockParserTypeError, FailOnNestedInconvertible) {
auto options = Options(schema({field("a", list(struct_({field("b", int32())})))}));
std::shared_ptr<Array> parsed;
Status error =
ParseFromString(options, "{\"a\":[{\"b\":0}]}\n{\"a\":[{\"b\":true}]}", &parsed);
ASSERT_RAISES(Invalid, error);
EXPECT_THAT(
error.message(),
testing::StartsWith(
"JSON parse error: Column(/a/[]/b) changed from number to boolean in row 1"));
}
TEST_P(BlockParserTypeError, FailOnDuplicateKeys) {
std::shared_ptr<Array> parsed;
Status error = ParseFromString(Options(schema({field("a", int32())})),
"{\"a\":0, \"a\":1}\n", &parsed);
ASSERT_RAISES(Invalid, error);
EXPECT_THAT(
error.message(),
testing::StartsWith("JSON parse error: Column(/a) was specified twice in row 0"));
}
INSTANTIATE_TEST_CASE_P(BlockParserTypeError, BlockParserTypeError,
::testing::Values(UnexpectedFieldBehavior::Ignore,
UnexpectedFieldBehavior::Error,
UnexpectedFieldBehavior::InferType));
TEST(BlockParserWithSchema, Nested) {
auto options = ParseOptions::Defaults();
options.explicit_schema = schema({field("yo", utf8()), field("arr", list(int32())),
field("nuf", struct_({field("ps", int32())}))});
options.unexpected_field_behavior = UnexpectedFieldBehavior::Ignore;
AssertParseColumns(options, nested_src(),
{field("yo", utf8()), field("arr", list(utf8())),
field("nuf", struct_({field("ps", utf8())}))},
{"[\"thing\", null, \"\xe5\xbf\x8d\", null]",
R"([["1", "2", "3"], ["2"], [], null])",
R"([{"ps":null}, null, {"ps":"78"}, {"ps":"90"}])"});
}
TEST(BlockParserWithSchema, FailOnIncompleteJson) {
auto options = ParseOptions::Defaults();
options.explicit_schema = schema({field("a", int32())});
options.unexpected_field_behavior = UnexpectedFieldBehavior::Ignore;
std::shared_ptr<Array> parsed;
ASSERT_RAISES(Invalid, ParseFromString(options, "{\"a\":0, \"b\"", &parsed));
}
TEST(BlockParser, Basics) {
auto options = ParseOptions::Defaults();
options.unexpected_field_behavior = UnexpectedFieldBehavior::InferType;
AssertParseColumns(
options, scalars_only_src(),
{field("hello", utf8()), field("world", boolean()), field("yo", utf8())},
{"[\"3.5\", \"3.25\", \"3.125\", \"0.0\"]", "[false, null, null, true]",
"[\"thing\", null, \"\xe5\xbf\x8d\", null]"});
}
TEST(BlockParser, Nested) {
auto options = ParseOptions::Defaults();
options.unexpected_field_behavior = UnexpectedFieldBehavior::InferType;
AssertParseColumns(options, nested_src(),
{field("yo", utf8()), field("arr", list(utf8())),
field("nuf", struct_({field("ps", utf8())}))},
{"[\"thing\", null, \"\xe5\xbf\x8d\", null]",
R"([["1", "2", "3"], ["2"], [], null])",
R"([{"ps":null}, null, {"ps":"78"}, {"ps":"90"}])"});
}
} // namespace json
} // namespace arrow
|
/*
===============================================================================
FILE: lasreaditemcompressed_v1.cpp
CONTENTS:
see corresponding header file
PROGRAMMERS:
martin.isenburg@rapidlasso.com - http://rapidlasso.com
COPYRIGHT:
(c) 2007-2014, martin isenburg, rapidlasso - fast tools to catch reality
This is free software; you can redistribute and/or modify it under the
terms of the GNU Lesser General Licence as published by the Free Software
Foundation. See the COPYING file for more information.
This software is distributed WITHOUT ANY WARRANTY and without even the
implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
CHANGE HISTORY:
see corresponding header file
===============================================================================
*/
#include "lasreaditemcompressed_v1.hpp"
#include "laszip_common_v1.hpp"
#include <assert.h>
#include <string.h>
/*
===============================================================================
LASreadItemCompressed_POINT10_v1
===============================================================================
*/
struct LASpoint10
{
I32 x;
I32 y;
I32 z;
U16 intensity;
U8 return_number : 3;
U8 number_of_returns_of_given_pulse : 3;
U8 scan_direction_flag : 1;
U8 edge_of_flight_line : 1;
U8 classification;
I8 scan_angle_rank;
U8 user_data;
U16 point_source_ID;
};
LASreadItemCompressed_POINT10_v1::LASreadItemCompressed_POINT10_v1(ArithmeticDecoder* dec)
{
U32 i;
/* set decoder */
assert(dec);
this->dec = dec;
/* create models and integer compressors */
ic_dx = new IntegerCompressor(dec, 32); // 32 bits, 1 context
ic_dy = new IntegerCompressor(dec, 32, 20); // 32 bits, 20 contexts
ic_z = new IntegerCompressor(dec, 32, 20); // 32 bits, 20 contexts
ic_intensity = new IntegerCompressor(dec, 16);
ic_scan_angle_rank = new IntegerCompressor(dec, 8, 2);
ic_point_source_ID = new IntegerCompressor(dec, 16);
m_changed_values = dec->createSymbolModel(64);
for (i = 0; i < 256; i++)
{
m_bit_byte[i] = 0;
m_classification[i] = 0;
m_user_data[i] = 0;
}
}
LASreadItemCompressed_POINT10_v1::~LASreadItemCompressed_POINT10_v1()
{
U32 i;
delete ic_dx;
delete ic_dy;
delete ic_z;
delete ic_intensity;
delete ic_scan_angle_rank;
delete ic_point_source_ID;
dec->destroySymbolModel(m_changed_values);
for (i = 0; i < 256; i++)
{
if (m_bit_byte[i]) dec->destroySymbolModel(m_bit_byte[i]);
if (m_classification[i]) dec->destroySymbolModel(m_classification[i]);
if (m_user_data[i]) dec->destroySymbolModel(m_user_data[i]);
}
}
BOOL LASreadItemCompressed_POINT10_v1::init(const U8* item)
{
U32 i;
/* init state */
last_x_diff[0] = last_x_diff[1] = last_x_diff[2] = 0;
last_y_diff[0] = last_y_diff[1] = last_y_diff[2] = 0;
last_incr = 0;
/* init models and integer compressors */
ic_dx->initDecompressor();
ic_dy->initDecompressor();
ic_z->initDecompressor();
ic_intensity->initDecompressor();
ic_scan_angle_rank->initDecompressor();
ic_point_source_ID->initDecompressor();
dec->initSymbolModel(m_changed_values);
for (i = 0; i < 256; i++)
{
if (m_bit_byte[i]) dec->initSymbolModel(m_bit_byte[i]);
if (m_classification[i]) dec->initSymbolModel(m_classification[i]);
if (m_user_data[i]) dec->initSymbolModel(m_user_data[i]);
}
/* init last item */
memcpy(last_item, item, 20);
return TRUE;
}
inline void LASreadItemCompressed_POINT10_v1::read(U8* item)
{
// find median difference for x and y from 3 preceding differences
I32 median_x;
if (last_x_diff[0] < last_x_diff[1])
{
if (last_x_diff[1] < last_x_diff[2])
median_x = last_x_diff[1];
else if (last_x_diff[0] < last_x_diff[2])
median_x = last_x_diff[2];
else
median_x = last_x_diff[0];
}
else
{
if (last_x_diff[0] < last_x_diff[2])
median_x = last_x_diff[0];
else if (last_x_diff[1] < last_x_diff[2])
median_x = last_x_diff[2];
else
median_x = last_x_diff[1];
}
I32 median_y;
if (last_y_diff[0] < last_y_diff[1])
{
if (last_y_diff[1] < last_y_diff[2])
median_y = last_y_diff[1];
else if (last_y_diff[0] < last_y_diff[2])
median_y = last_y_diff[2];
else
median_y = last_y_diff[0];
}
else
{
if (last_y_diff[0] < last_y_diff[2])
median_y = last_y_diff[0];
else if (last_y_diff[1] < last_y_diff[2])
median_y = last_y_diff[2];
else
median_y = last_y_diff[1];
}
// decompress x y z coordinates
I32 x_diff = ic_dx->decompress(median_x);
((LASpoint10*)last_item)->x += x_diff;
// we use the number k of bits corrector bits to switch contexts
U32 k_bits = ic_dx->getK();
I32 y_diff = ic_dy->decompress(median_y, (k_bits < 19 ? k_bits : 19));
((LASpoint10*)last_item)->y += y_diff;
k_bits = (k_bits + ic_dy->getK())/2;
((LASpoint10*)last_item)->z = ic_z->decompress(((LASpoint10*)last_item)->z, (k_bits < 19 ? k_bits : 19));
// decompress which other values have changed
I32 changed_values = dec->decodeSymbol(m_changed_values);
if (changed_values)
{
// decompress the intensity if it has changed
if (changed_values & 32)
{
((LASpoint10*)last_item)->intensity = (U16)ic_intensity->decompress(((LASpoint10*)last_item)->intensity);
}
// decompress the edge_of_flight_line, scan_direction_flag, ... if it has changed
if (changed_values & 16)
{
if (m_bit_byte[last_item[14]] == 0)
{
m_bit_byte[last_item[14]] = dec->createSymbolModel(256);
dec->initSymbolModel(m_bit_byte[last_item[14]]);
}
last_item[14] = (U8)dec->decodeSymbol(m_bit_byte[last_item[14]]);
}
// decompress the classification ... if it has changed
if (changed_values & 8)
{
if (m_classification[last_item[15]] == 0)
{
m_classification[last_item[15]] = dec->createSymbolModel(256);
dec->initSymbolModel(m_classification[last_item[15]]);
}
last_item[15] = (U8)dec->decodeSymbol(m_classification[last_item[15]]);
}
// decompress the scan_angle_rank ... if it has changed
if (changed_values & 4)
{
last_item[16] = (U8)ic_scan_angle_rank->decompress(last_item[16], k_bits < 3);
}
// decompress the user_data ... if it has changed
if (changed_values & 2)
{
if (m_user_data[last_item[17]] == 0)
{
m_user_data[last_item[17]] = dec->createSymbolModel(256);
dec->initSymbolModel(m_user_data[last_item[17]]);
}
last_item[17] = (U8)dec->decodeSymbol(m_user_data[last_item[17]]);
}
// decompress the point_source_ID ... if it has changed
if (changed_values & 1)
{
((LASpoint10*)last_item)->point_source_ID = (U16)ic_point_source_ID->decompress(((LASpoint10*)last_item)->point_source_ID);
}
}
// record the difference
last_x_diff[last_incr] = x_diff;
last_y_diff[last_incr] = y_diff;
last_incr++;
if (last_incr > 2) last_incr = 0;
// copy the last point
memcpy(item, last_item, 20);
}
/*
===============================================================================
LASreadItemCompressed_GPSTIME11_v1
===============================================================================
*/
#define LASZIP_GPSTIME_MULTIMAX 512
LASreadItemCompressed_GPSTIME11_v1::LASreadItemCompressed_GPSTIME11_v1(ArithmeticDecoder* dec)
{
/* set decoder */
assert(dec);
this->dec = dec;
/* create entropy models and integer compressors */
m_gpstime_multi = dec->createSymbolModel(LASZIP_GPSTIME_MULTIMAX);
m_gpstime_0diff = dec->createSymbolModel(3);
ic_gpstime = new IntegerCompressor(dec, 32, 6); // 32 bits, 6 contexts
}
LASreadItemCompressed_GPSTIME11_v1::~LASreadItemCompressed_GPSTIME11_v1()
{
dec->destroySymbolModel(m_gpstime_multi);
dec->destroySymbolModel(m_gpstime_0diff);
delete ic_gpstime;
}
BOOL LASreadItemCompressed_GPSTIME11_v1::init(const U8* item)
{
/* init state */
last_gpstime_diff = 0;
multi_extreme_counter = 0;
/* init models and integer compressors */
dec->initSymbolModel(m_gpstime_multi);
dec->initSymbolModel(m_gpstime_0diff);
ic_gpstime->initDecompressor();
/* init last item */
last_gpstime.u64 = *((U64*)item);
return TRUE;
}
inline void LASreadItemCompressed_GPSTIME11_v1::read(U8* item)
{
I32 multi;
if (last_gpstime_diff == 0) // if the last integer difference was zero
{
multi = dec->decodeSymbol(m_gpstime_0diff);
if (multi == 1) // the difference can be represented with 32 bits
{
last_gpstime_diff = ic_gpstime->decompress(0, 0);
last_gpstime.i64 += last_gpstime_diff;
}
else if (multi == 2) // the difference is huge
{
last_gpstime.u64 = dec->readInt64();
}
}
else
{
multi = dec->decodeSymbol(m_gpstime_multi);
if (multi < LASZIP_GPSTIME_MULTIMAX-2)
{
I32 gpstime_diff;
if (multi == 1)
{
gpstime_diff = ic_gpstime->decompress(last_gpstime_diff, 1);
last_gpstime_diff = gpstime_diff;
multi_extreme_counter = 0;
}
else if (multi == 0)
{
gpstime_diff = ic_gpstime->decompress(last_gpstime_diff/4, 2);
multi_extreme_counter++;
if (multi_extreme_counter > 3)
{
last_gpstime_diff = gpstime_diff;
multi_extreme_counter = 0;
}
}
else if (multi < 10)
{
gpstime_diff = ic_gpstime->decompress(multi*last_gpstime_diff, 3);
}
else if (multi < 50)
{
gpstime_diff = ic_gpstime->decompress(multi*last_gpstime_diff, 4);
}
else
{
gpstime_diff = ic_gpstime->decompress(multi*last_gpstime_diff, 5);
if (multi == LASZIP_GPSTIME_MULTIMAX-3)
{
multi_extreme_counter++;
if (multi_extreme_counter > 3)
{
last_gpstime_diff = gpstime_diff;
multi_extreme_counter = 0;
}
}
}
last_gpstime.i64 += gpstime_diff;
}
else if (multi < LASZIP_GPSTIME_MULTIMAX-1)
{
last_gpstime.u64 = dec->readInt64();
}
}
*((I64*)item) = last_gpstime.i64;
}
/*
===============================================================================
LASreadItemCompressed_RGB12_v1
===============================================================================
*/
LASreadItemCompressed_RGB12_v1::LASreadItemCompressed_RGB12_v1(ArithmeticDecoder* dec)
{
/* set decoder */
assert(dec);
this->dec = dec;
/* create models and integer compressors */
m_byte_used = dec->createSymbolModel(64);
ic_rgb = new IntegerCompressor(dec, 8, 6);
/* create last item */
last_item = new U8[6];
}
LASreadItemCompressed_RGB12_v1::~LASreadItemCompressed_RGB12_v1()
{
dec->destroySymbolModel(m_byte_used);
delete ic_rgb;
delete [] last_item;
}
BOOL LASreadItemCompressed_RGB12_v1::init(const U8* item)
{
/* init state */
/* init models and integer compressors */
dec->initSymbolModel(m_byte_used);
ic_rgb->initDecompressor();
/* init last item */
memcpy(last_item, item, 6);
return TRUE;
}
inline void LASreadItemCompressed_RGB12_v1::read(U8* item)
{
U32 sym = dec->decodeSymbol(m_byte_used);
if (sym & (1 << 0)) ((U16*)item)[0] = (U16)ic_rgb->decompress(((U16*)last_item)[0]&255, 0);
else ((U16*)item)[0] = (U16)(((U16*)last_item)[0]&0xFF);
if (sym & (1 << 1)) ((U16*)item)[0] |= (((U16)ic_rgb->decompress(((U16*)last_item)[0]>>8, 1)) << 8);
else ((U16*)item)[0] |= (((U16*)last_item)[0]&0xFF00);
if (sym & (1 << 2)) ((U16*)item)[1] = (U16)ic_rgb->decompress(((U16*)last_item)[1]&255, 2);
else ((U16*)item)[1] = (U16)(((U16*)last_item)[1]&0xFF);
if (sym & (1 << 3)) ((U16*)item)[1] |= (((U16)ic_rgb->decompress(((U16*)last_item)[1]>>8, 3)) << 8);
else ((U16*)item)[1] |= (((U16*)last_item)[1]&0xFF00);
if (sym & (1 << 4)) ((U16*)item)[2] = (U16)ic_rgb->decompress(((U16*)last_item)[2]&255, 4);
else ((U16*)item)[2] = (U16)(((U16*)last_item)[2]&0xFF);
if (sym & (1 << 5)) ((U16*)item)[2] |= (((U16)ic_rgb->decompress(((U16*)last_item)[2]>>8, 5)) << 8);
else ((U16*)item)[2] |= (((U16*)last_item)[2]&0xFF00);
memcpy(last_item, item, 6);
}
/*
===============================================================================
LASreadItemCompressed_WAVEPACKET13_v1
===============================================================================
*/
LASreadItemCompressed_WAVEPACKET13_v1::LASreadItemCompressed_WAVEPACKET13_v1(ArithmeticDecoder* dec)
{
/* set decoder */
assert(dec);
this->dec = dec;
/* create models and integer compressors */
m_packet_index = dec->createSymbolModel(256);
m_offset_diff[0] = dec->createSymbolModel(4);
m_offset_diff[1] = dec->createSymbolModel(4);
m_offset_diff[2] = dec->createSymbolModel(4);
m_offset_diff[3] = dec->createSymbolModel(4);
ic_offset_diff = new IntegerCompressor(dec, 32);
ic_packet_size = new IntegerCompressor(dec, 32);
ic_return_point = new IntegerCompressor(dec, 32);
ic_xyz = new IntegerCompressor(dec, 32, 3);
/* create last item */
last_item = new U8[28];
}
LASreadItemCompressed_WAVEPACKET13_v1::~LASreadItemCompressed_WAVEPACKET13_v1()
{
dec->destroySymbolModel(m_packet_index);
dec->destroySymbolModel(m_offset_diff[0]);
dec->destroySymbolModel(m_offset_diff[1]);
dec->destroySymbolModel(m_offset_diff[2]);
dec->destroySymbolModel(m_offset_diff[3]);
delete ic_offset_diff;
delete ic_packet_size;
delete ic_return_point;
delete ic_xyz;
delete [] last_item;
}
BOOL LASreadItemCompressed_WAVEPACKET13_v1::init(const U8* item)
{
/* init state */
last_diff_32 = 0;
sym_last_offset_diff = 0;
/* init models and integer compressors */
dec->initSymbolModel(m_packet_index);
dec->initSymbolModel(m_offset_diff[0]);
dec->initSymbolModel(m_offset_diff[1]);
dec->initSymbolModel(m_offset_diff[2]);
dec->initSymbolModel(m_offset_diff[3]);
ic_offset_diff->initDecompressor();
ic_packet_size->initDecompressor();
ic_return_point->initDecompressor();
ic_xyz->initDecompressor();
/* init last item */
item++;
memcpy(last_item, item, 28);
return TRUE;
}
inline void LASreadItemCompressed_WAVEPACKET13_v1::read(U8* item)
{
item[0] = (U8)(dec->decodeSymbol(m_packet_index));
item++;
LASwavepacket13 this_item_m;
LASwavepacket13 last_item_m = LASwavepacket13::unpack(last_item);
sym_last_offset_diff = dec->decodeSymbol(m_offset_diff[sym_last_offset_diff]);
if (sym_last_offset_diff == 0)
{
this_item_m.offset = last_item_m.offset;
}
else if (sym_last_offset_diff == 1)
{
this_item_m.offset = last_item_m.offset + last_item_m.packet_size;
}
else if (sym_last_offset_diff == 2)
{
last_diff_32 = ic_offset_diff->decompress(last_diff_32);
this_item_m.offset = last_item_m.offset + last_diff_32;
}
else
{
this_item_m.offset = dec->readInt64();
}
this_item_m.packet_size = ic_packet_size->decompress(last_item_m.packet_size);
this_item_m.return_point.i32 = ic_return_point->decompress(last_item_m.return_point.i32);
this_item_m.x.i32 = ic_xyz->decompress(last_item_m.x.i32, 0);
this_item_m.y.i32 = ic_xyz->decompress(last_item_m.y.i32, 1);
this_item_m.z.i32 = ic_xyz->decompress(last_item_m.z.i32, 2);
this_item_m.pack(item);
memcpy(last_item, item, 28);
}
/*
===============================================================================
LASreadItemCompressed_BYTE_v1
===============================================================================
*/
LASreadItemCompressed_BYTE_v1::LASreadItemCompressed_BYTE_v1(ArithmeticDecoder* dec, U32 number)
{
/* set decoder */
assert(dec);
this->dec = dec;
assert(number);
this->number = number;
/* create models and integer compressors */
ic_byte = new IntegerCompressor(dec, 8, number);
/* create last item */
last_item = new U8[number];
}
LASreadItemCompressed_BYTE_v1::~LASreadItemCompressed_BYTE_v1()
{
delete ic_byte;
delete [] last_item;
}
BOOL LASreadItemCompressed_BYTE_v1::init(const U8* item)
{
/* init state */
/* init models and integer compressors */
ic_byte->initDecompressor();
/* init last item */
memcpy(last_item, item, number);
return TRUE;
}
inline void LASreadItemCompressed_BYTE_v1::read(U8* item)
{
U32 i;
for (i = 0; i < number; i++)
{
item[i] = (U8)(ic_byte->decompress(last_item[i], i));
}
memcpy(last_item, item, number);
}
// vim: set ts=2 sw=2 expandtabs
|
// Copyright (c) 2019-2022 Dr. Colin Hirsch and Daniel Frey
// Please see LICENSE for license or visit https://github.com/taocpp/config/
#ifndef TAO_CONFIG_SCHEMA_INTERNAL_SIZE_HPP
#define TAO_CONFIG_SCHEMA_INTERNAL_SIZE_HPP
#include "node.hpp"
namespace tao::config::schema::internal
{
template< typename T >
struct compare_size : node
{
const std::size_t m_size;
explicit compare_size( const value& v )
: node( v ),
m_size( v.as< std::size_t >() )
{}
json::value validate( const value& v ) const override
{
if( v.is_string_type() ) {
return T()( m_size, v.as< std::string_view >().size() ) ? ok() : error( v, "size did not match" );
}
if( v.is_binary_type() ) {
return T()( m_size, v.as< tao::binary_view >().size() ) ? ok() : error( v, "size did not match" );
}
if( v.is_array() ) {
return T()( m_size, v.get_array().size() ) ? ok() : error( v, "size did not match" );
}
if( v.is_object() ) {
return T()( m_size, v.get_object().size() ) ? ok() : error( v, "size did not match" );
}
return error( v, "invalid type for size comparison" );
}
};
using size = compare_size< std::equal_to<> >;
using min_size = compare_size< std::less_equal<> >;
using max_size = compare_size< std::greater_equal<> >;
} // namespace tao::config::schema::internal
#endif
|
// profiles.cpp
//
// Copyright (c) 2020-2021 Kristofer Berggren
// All rights reserved.
//
// nchat is distributed under the MIT license, see LICENSE for details.
#include "profiles.h"
#include <string>
#include "fileutil.h"
void Profiles::Init()
{
static const int dirVersion = 1;
const std::string& profilesDir = FileUtil::GetApplicationDir() + "/profiles";
FileUtil::InitDirVersion(profilesDir, dirVersion);
}
void Profiles::Cleanup()
{
}
|
//
// road.cpp
// path_planning
//
// Created by Bryan Bui on 3/16/18.
//
#include "road.hpp"
#include <iostream>
#include "vehicle.hpp"
#include <math.h>
#include <map>
#include <string>
#include <iterator>
/**
* Initializes Road
*/
Road::Road(double speed_limit, int lanes) {
this->num_lanes = lanes;
this->speed_limit = speed_limit;
}
Road::~Road() {}
map<int, Vehicle> Road::get_vehicles() {
return this->vehicles;
}
map<int, Vehicle>::const_iterator Road::get_vehicle(int id) {
return this->vehicles.find(id);
}
void Road::clear_traffic() {
Vehicle ego = get_vehicle(ego_key)->second;
this->vehicles.clear();
this->vehicles.insert(std::pair<int,Vehicle>(ego_key,ego));
this->vehicles_added = 0;
}
// Function to add cars detected by sensor fusion to our road
void Road::update_traffic(int id, Vehicle car) {
this->vehicles.insert(std::pair<int,Vehicle>(id,car));
}
void Road::add_ego(int lane_num, double s, vector<int> config_data) {
Vehicle ego = Vehicle(lane_num, s, 0, 0);
ego.configure(config_data);
ego.state = "KL";
this->vehicles.insert(std::pair<int,Vehicle>(ego_key,ego));
}
void Road::update_ego(int lane_num, double s, double a, double v) {
this->vehicles.find(this->ego_key)->second.lane = lane_num;
this->vehicles.find(this->ego_key)->second.s = s;
this->vehicles.find(this->ego_key)->second.v = v;
this->vehicles.find(this->ego_key)->second.a = a;
}
void Road::update_ego_state(string new_state) {
this->vehicles.find(this->ego_key)->second.state = new_state;
}
Vehicle Road::update() {
// Generate Predictions
map<int ,vector<Vehicle> > predictions;
map<int, Vehicle>::iterator it = this->vehicles.begin();
while(it != this->vehicles.end())
{
int v_id = it->first;
if(v_id != ego_key) {
vector<Vehicle> preds = it->second.generate_predictions(2);
predictions[v_id] = preds;
// cout << v_id << " Speed: " << preds[0].v << endl;
}
it++;
}
// Generate Trajectory, or return next position for trajectory
it = this->vehicles.find(ego_key);
vector<Vehicle> trajectory = it->second.choose_next_state(predictions);
return trajectory[1];
}
bool Road::check_lane_clear(int lane) {
map<int ,vector<Vehicle> > predictions;
Vehicle ego = get_vehicle(ego_key)->second;
map<int, Vehicle>::iterator it = this->vehicles.begin();
while(it != this->vehicles.end())
{
int v_id = it->first;
if(v_id != ego_key) {
if(it->second.lane == lane) {
vector<Vehicle> preds = it->second.generate_predictions(2);
if(preds[0].s > ego.s - 8 && preds[0].s < ego.s + 8) {
return false;
}
if(preds[1].s > ego.s - 8 && preds[1].s < ego.s + 8) {
return false;
}
}
}
it++;
}
return true;
}
|
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QString>
#include <algorithm>
#include <cmath>
#include "telo.h"
#include <QDebug>
using namespace std;
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow), object(100,20,50)
{
ui->setupUi(this);
get_koef();
update_temp();
paintTimer = new QTimer(this); // создаю таймер
connect(paintTimer, SIGNAL(timeout()), this, SLOT(action()));
}
void MainWindow::update_temp()
{
ui->spinBox->setValue(time);
for (int i = 0; i < 8; ++i)
{
QLineEdit *segment = static_cast<QLineEdit*>(ui->Layout->itemAt(i)->widget());
segment->setText(QString::number(object.current_temperature[i],'g',3));
int temp_color = int((object.current_temperature[i] - min_temp) * k_temp);
segment->setStyleSheet("background-color: rgb(255, " + QString::number(255-temp_color) + ", " + QString::number(255-temp_color) + ");");
}
}
void MainWindow::get_koef()
{
max_temp = int(*max_element(object.current_temperature.begin(),object.current_temperature.end()));
min_temp = int(*min_element(object.current_temperature.begin(),object.current_temperature.end()));
k_temp = 255.0 / (max_temp - min_temp);
qDebug() << k_temp;
}
void MainWindow::disable_buttons(bool var)
{
ui->spinBox_env->setDisabled(var);
ui->spinBox_right->setDisabled(var);
ui->spinBox_left->setDisabled(var);
}
void MainWindow::action()
{
--time;
object.work();
update_temp();
if (time == 0) {paintTimer->stop(); disable_buttons(false);}
}
void MainWindow::on_pushButton_clicked()
{
if (paintTimer->isActive()) {paintTimer->stop(); disable_buttons(false);}
else if(time != 0)
{
paintTimer->start(500);
disable_buttons(true);
}
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_spinBox_valueChanged(int arg1)
{
time = arg1;
}
void MainWindow::on_spinBox_left_valueChanged(int arg1)
{
object.current_temperature[0] = arg1;
get_koef();
update_temp();
}
void MainWindow::on_spinBox_env_valueChanged(int arg1)
{
for (size_t i = 1; i < 7; i++)
{
object.current_temperature[i] = arg1;
}
get_koef();
update_temp();
}
void MainWindow::on_spinBox_right_valueChanged(int arg1)
{
object.current_temperature[7] = arg1;
get_koef();
update_temp();
}
|
/***********************************************************************************************************************
* OpenStudio(R), Copyright (c) 2008-2017, Alliance for Sustainable Energy, LLC. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
* following conditions are met:
*
* (1) Redistributions of source code must retain the above copyright notice, this list of conditions and the following
* disclaimer.
*
* (2) Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
* following disclaimer in the documentation and/or other materials provided with the distribution.
*
* (3) Neither the name of the copyright holder nor the names of any contributors may be used to endorse or promote
* products derived from this software without specific prior written permission from the respective party.
*
* (4) Other than as required in clauses (1) and (2), distributions in any form of modifications or other derivative
* works may not use the "OpenStudio" trademark, "OS", "os", or any other confusingly similar designation without
* specific prior written permission from Alliance for Sustainable Energy, LLC.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER, THE UNITED STATES GOVERNMENT, OR ANY 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 OPENSTUDIO_LUMINAIREINSPECTORVIEW_HPP
#define OPENSTUDIO_LUMINAIREINSPECTORVIEW_HPP
#include "ModelObjectInspectorView.hpp"
#include "../model/LuminaireDefinition.hpp"
namespace openstudio {
class OSLineEdit2;
class OSQuantityEdit2;
class OSDropZone;
class LuminaireDefinitionInspectorView : public ModelObjectInspectorView
{
Q_OBJECT
public:
LuminaireDefinitionInspectorView(bool isIP, const openstudio::model::Model& model, QWidget * parent = nullptr );
virtual ~LuminaireDefinitionInspectorView() {}
protected:
virtual void onClearSelection() override;
virtual void onSelectModelObject(const openstudio::model::ModelObject& modelObject) override;
virtual void onUpdate() override;
private:
void attach(openstudio::model::LuminaireDefinition & luminaireDefinition);
void detach();
void refresh();
OSLineEdit2* m_nameEdit;
OSQuantityEdit2 * m_lightingPowerEdit;
OSQuantityEdit2 * m_fractionRadiantEdit;
OSQuantityEdit2 * m_fractionVisibleEdit;
OSQuantityEdit2 * m_returnAirFractionEdit;
bool m_isIP;
boost::optional<model::LuminaireDefinition> m_luminaireDefinition;
public slots:
void toggleUnits(bool displayIP) override;
};
} // openstudio
#endif // OPENSTUDIO_LUMINAIREINSPECTORVIEW_HPP
|
#include <boost/python.hpp>
#include <lanelet2_core/LaneletMap.h>
#include <lanelet2_core/geometry/Area.h>
#include <lanelet2_core/geometry/Lanelet.h>
#include <lanelet2_core/geometry/LineString.h>
#include <lanelet2_core/geometry/Polygon.h>
#include <lanelet2_core/geometry/RegulatoryElement.h>
using namespace boost::python;
using namespace lanelet;
using HybridLs3d = ConstHybridLineString3d;
using HybridLs2d = ConstHybridLineString2d;
template <typename PrimT>
auto wrapFindNearest() {
using Sig = std::vector<std::pair<double, PrimT>> (*)(PrimitiveLayer<PrimT>&, const BasicPoint2d&, unsigned);
auto func = static_cast<Sig>(lanelet::geometry::findNearest);
return def("findNearest", func);
}
template <typename T>
lanelet::BoundingBox2d boundingBox2dFor(const T& t) {
return lanelet::geometry::boundingBox2d(t);
}
template <typename T>
lanelet::BoundingBox3d boundingBox3dFor(const T& t) {
return lanelet::geometry::boundingBox3d(t);
}
BOOST_PYTHON_MODULE(PYTHON_API_MODULE_NAME) { // NOLINT
namespace lg = lanelet::geometry;
def("to2D", utils::to2D<Point3d>);
def("to2D", utils::to2D<BasicPoint3d>);
def("to2D", utils::to2D<ConstPoint3d>);
def("to2D", utils::to2D<LineString3d>);
def("to2D", utils::to2D<ConstLineString3d>);
def("to2D", utils::to2D<Polygon3d>);
def("to2D", utils::to2D<ConstPolygon3d>);
def("to3D", utils::to3D<Point2d>);
def("to3D", utils::to2D<BasicPoint2d>);
def("to3D", utils::to3D<ConstPoint2d>);
def("to3D", utils::to3D<LineString2d>);
def("to3D", utils::to3D<ConstLineString2d>);
def("to3D", utils::to3D<Polygon2d>);
def("to3D", utils::to3D<ConstPolygon2d>);
// p2p
def("distance", lg::distance<BasicPoint2d, BasicPoint2d>);
def("distance", lg::distance<ConstPoint2d, ConstPoint2d>);
def("distance", lg::distance<ConstPoint2d, BasicPoint2d>);
def("distance", lg::distance<BasicPoint2d, ConstPoint2d>);
// p2l
def("distance", lg::distance<ConstPoint2d, HybridLs2d>);
def("distance", lg::distance<HybridLs2d, ConstPoint2d>);
def("distance", lg::distance<ConstPoint2d, ConstLineString2d>);
def("distance", lg::distance<ConstLineString2d, ConstPoint2d>);
// l2l
def("distance", +[](const ConstLineString2d& ls1, const ConstLineString2d& ls2) { return lg::distance2d(ls1, ls2); });
def("distance", lg::distance<ConstHybridLineString2d, ConstHybridLineString2d>);
// poly2p
def("distance", lg::distance<ConstHybridPolygon2d, BasicPoint2d>);
def("distance", +[](const ConstPolygon2d& p1, const BasicPoint2d& p2) { return lg::distance2d(p1, p2); });
// poly2ls
def("distance", +[](const ConstPolygon2d& p1, const ConstLineString2d& p2) { return lg::distance2d(p1, p2); });
def("distance", lg::distance<ConstHybridPolygon2d, ConstHybridLineString2d>);
// poly2poly
def("distance", lg::distance<ConstHybridPolygon2d, ConstHybridPolygon2d>);
def("distance", +[](const ConstPolygon2d& p1, const ConstPolygon2d& p2) { return lg::distance2d(p1, p2); });
// p2llt
def("distance", +[](const ConstLanelet& llt, const BasicPoint2d& p) { return lg::distance2d(llt, p); });
def("distance", +[](const ConstLanelet& llt1, const ConstLanelet& llt2) { return lg::distance2d(llt1, llt2); });
// p2area
def("distance", +[](const ConstArea& llt, const BasicPoint2d& p) { return lg::distance2d(llt, p); });
// 3d
// p2p
def("distance", lg::distance<ConstPoint3d, ConstPoint3d>);
def("distance", lg::distance<ConstPoint3d, BasicPoint3d>);
def("distance", lg::distance<BasicPoint3d, ConstPoint3d>);
def("distance", lg::distance<BasicPoint3d, BasicPoint3d>);
// p2l
def("distance", lg::distance<ConstPoint3d, HybridLs3d>);
def("distance", lg::distance<HybridLs3d, ConstPoint3d>);
def("distance", lg::distance<ConstPoint3d, ConstLineString3d>);
def("distance", lg::distance<ConstLineString3d, ConstPoint3d>);
// l2l
def("distance", +[](const ConstLineString3d& ls1, const ConstLineString3d& ls2) { return lg::distance3d(ls1, ls2); });
def("distance", +[](const HybridLs3d& ls1, const HybridLs3d& ls2) { return lg::distance3d(ls1, ls2); });
// p2llt
def("distance", lg::distance3d<ConstLanelet>);
// p2area
def("distance", +[](const ConstArea& llt, const BasicPoint3d& p) { return lg::distance3d(llt, p); });
def("boundingBox2d", boundingBox2dFor<ConstPoint2d>, "Get the surrounding axis-aligned bounding box in 2d");
def("boundingBox2d", boundingBox2dFor<ConstLineString2d>);
def("boundingBox2d", boundingBox2dFor<ConstHybridLineString2d>);
def("boundingBox2d", boundingBox2dFor<ConstPolygon2d>);
def("boundingBox2d", boundingBox2dFor<ConstHybridPolygon2d>);
def("boundingBox2d", boundingBox2dFor<ConstLanelet>);
def("boundingBox2d", boundingBox2dFor<ConstArea>);
def("boundingBox2d", boundingBox2dFor<RegulatoryElementPtr>);
def("boundingBox2d", boundingBox2dFor<RegulatoryElementConstPtr>);
def("boundingBox3d", boundingBox3dFor<ConstPoint3d>, "Get the surrounding axis-aligned bounding box in 3d");
def("boundingBox3d", boundingBox3dFor<ConstLineString3d>);
def("boundingBox3d", boundingBox3dFor<ConstHybridLineString3d>);
def("boundingBox3d", boundingBox3dFor<ConstPolygon3d>);
def("boundingBox3d", boundingBox3dFor<ConstHybridPolygon3d>);
def("boundingBox3d", boundingBox3dFor<ConstLanelet>);
def("boundingBox3d", boundingBox3dFor<ConstArea>);
def("boundingBox3d", boundingBox3dFor<RegulatoryElementPtr>);
def("boundingBox3d", boundingBox3dFor<RegulatoryElementConstPtr>);
class_<ArcCoordinates>("ArcCoordinates", "Coordinates along an arc", init<>())
.add_property("length", &ArcCoordinates::length, "lenght along arc")
.add_property("distance", &ArcCoordinates::distance, "signed distance to arc (left is positive");
def("toArcCoordinates", lg::toArcCoordinates<ConstLineString2d>,
"Project a point into arc coordinates of the linestring");
def("length", lg::length<ConstLineString2d>);
def("length", lg::length<ConstLineString3d>);
def("interpolatedPointAtDistance", lg::interpolatedPointAtDistance<ConstLineString2d>);
def("interpolatedPointAtDistance", lg::interpolatedPointAtDistance<ConstLineString3d>);
def("nearestPointAtDistance", lg::nearestPointAtDistance<ConstLineString2d>);
def("nearestPointAtDistance", lg::nearestPointAtDistance<ConstLineString3d>);
def("project", lg::project<ConstLineString2d>, "Project a point onto the linestring");
def("project", lg::project<ConstLineString3d>, "Project a point onto the linestring");
def("projectedPoint3d", lg::projectedPoint3d<ConstLineString3d>,
"Returns the respective projected points of the closest distance of two "
"linestrings");
def("projectedPoint3d", lg::projectedPoint3d<ConstHybridLineString3d>,
"Returns the respective projected points of the closest distance of two "
"linestrings");
def("intersects2d", +[](const ConstLineString2d& ls1, const ConstLineString2d& ls2) {
return lg::intersects(utils::toHybrid(ls1), utils::toHybrid(ls2));
});
def("intersects2d", lg::intersects<ConstHybridLineString2d, ConstHybridLineString2d>);
def("intersects2d", +[](const ConstPolygon2d& ls1, const ConstPolygon2d& ls2) {
return lg::intersects(utils::toHybrid(ls1), utils::toHybrid(ls2));
});
def("intersects2d", lg::intersects<ConstHybridPolygon2d, ConstHybridPolygon2d>);
def("intersects2d", lg::intersects2d<ConstLanelet, ConstLanelet>);
def("intersects2d", lg::intersects2d<ConstArea, ConstArea>);
def("intersects3d", lg::intersects3d<ConstLineString3d>);
def("intersects3d", lg::intersects3d<ConstHybridLineString3d>);
def("intersects3d", lg::intersects3d<ConstLanelet, ConstLanelet>,
"Approximates if two lanelets intersect (touch or area >0) in 3d",
(arg("lanelet1"), arg("lanelet2"), arg("heightTolerance") = 3.));
def("inside", lg::inside<ConstLanelet>, "tests whether a point is within a lanelet");
def("length2d", lg::length2d<ConstLanelet>, "calculate length of centerline");
def("length3d", lg::length3d<ConstLanelet>, "calculate length of centerline in 3d");
def("distanceToCenterline2d", lg::distanceToCenterline2d<ConstLanelet>);
def("distanceToCenterline3d", lg::distanceToCenterline3d<ConstLanelet>);
def("overlaps2d", lg::overlaps2d<ConstLanelet, ConstLanelet>, "Returns true if shared area of two lanelets is >0");
def("overlaps3d", lg::overlaps3d<ConstLanelet, ConstLanelet>, "Approximates if two lanelets overlap (area >0) in 3d",
(arg("lanelet1"), arg("lanelet2"), arg("heightTolerance") = 3.));
def("intersectCenterlines2d", lg::intersectCenterlines2d<ConstLanelet, ConstLanelet>);
def("leftOf", lg::leftOf<ConstLanelet, ConstLanelet>, "Returns if first lanelet is directly left of second");
def("rightOf", lg::rightOf<ConstLanelet, ConstLanelet>, "Returns if first lanelet is directly right of second");
def("follows", lg::follows<ConstLanelet, ConstLanelet>, "Returns if first lanelet precedes the second");
wrapFindNearest<Point3d>();
wrapFindNearest<LineString3d>();
wrapFindNearest<Lanelet>();
wrapFindNearest<Area>();
wrapFindNearest<RegulatoryElementPtr>();
}
|
// Generated by llvm2cpp - DO NOT MODIFY!
#include <llvm/Pass.h>
#include <llvm/PassManager.h>
#include <llvm/ADT/SmallVector.h>
#include <llvm/Analysis/Verifier.h>
#include <llvm/Assembly/PrintModulePass.h>
#include <llvm/IR/BasicBlock.h>
#include <llvm/IR/CallingConv.h>
#include <llvm/IR/Constants.h>
#include <llvm/IR/DerivedTypes.h>
#include <llvm/IR/Function.h>
#include <llvm/IR/GlobalVariable.h>
#include <llvm/IR/InlineAsm.h>
#include <llvm/IR/Instructions.h>
#include <llvm/IR/LLVMContext.h>
#include <llvm/IR/Module.h>
#include <llvm/Support/FormattedStream.h>
#include <llvm/Support/MathExtras.h>
#include <algorithm>
using namespace llvm;
Module* makeLLVMModule();
int main(int argc, char**argv) {
Module* Mod = makeLLVMModule();
verifyModule(*Mod, PrintMessageAction);
PassManager PM;
PM.add(createPrintModulePass(&outs()));
PM.run(*Mod);
return 0;
}
Module* makeLLVMModule() {
// Module Construction
Module* mod = new Module("test.ll", getGlobalContext());
mod->setDataLayout("e-p:32:32:32-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f32:32:32-f64:64:64-f80:128:128-v64:64:64-v128:128:128-a0:0:64-f80:32:32-n8:16:32-S32");
mod->setTargetTriple("i686-pc-mingw32");
// Type Definitions
StructType *StructTy_struct_A = mod->getTypeByName("struct.A");
if (!StructTy_struct_A) {
StructTy_struct_A = StructType::create(mod->getContext(), "struct.A");
}
std::vector<Type*>StructTy_struct_A_fields;
StructTy_struct_A_fields.push_back(IntegerType::get(mod->getContext(), 32));
StructTy_struct_A_fields.push_back(IntegerType::get(mod->getContext(), 32));
if (StructTy_struct_A->isOpaque()) {
StructTy_struct_A->setBody(StructTy_struct_A_fields, /*isPacked=*/false);
}
PointerType* PointerTy_0 = PointerType::get(StructTy_struct_A, 0);
std::vector<Type*>StructTy_2_fields;
StructTy_2_fields.push_back(IntegerType::get(mod->getContext(), 32));
std::vector<Type*>FuncTy_4_args;
FunctionType* FuncTy_4 = FunctionType::get(
/*Result=*/Type::getVoidTy(mod->getContext()),
/*Params=*/FuncTy_4_args,
/*isVarArg=*/false);
PointerType* PointerTy_3 = PointerType::get(FuncTy_4, 0);
StructTy_2_fields.push_back(PointerTy_3);
StructType *StructTy_2 = StructType::get(mod->getContext(), StructTy_2_fields, /*isPacked=*/false);
ArrayType* ArrayTy_1 = ArrayType::get(StructTy_2, 1);
PointerType* PointerTy_5 = PointerType::get(ArrayTy_1, 0);
std::vector<Type*>FuncTy_7_args;
FuncTy_7_args.push_back(PointerTy_0);
FuncTy_7_args.push_back(IntegerType::get(mod->getContext(), 32));
FunctionType* FuncTy_7 = FunctionType::get(
/*Result=*/Type::getVoidTy(mod->getContext()),
/*Params=*/FuncTy_7_args,
/*isVarArg=*/false);
PointerType* PointerTy_6 = PointerType::get(FuncTy_7, 0);
PointerType* PointerTy_8 = PointerType::get(PointerTy_0, 0);
PointerType* PointerTy_9 = PointerType::get(IntegerType::get(mod->getContext(), 32), 0);
std::vector<Type*>FuncTy_10_args;
FunctionType* FuncTy_10 = FunctionType::get(
/*Result=*/IntegerType::get(mod->getContext(), 32),
/*Params=*/FuncTy_10_args,
/*isVarArg=*/false);
// Function Declarations
Function* func___cxx_global_var_init = mod->getFunction("__cxx_global_var_init");
if (!func___cxx_global_var_init) {
func___cxx_global_var_init = Function::Create(
/*Type=*/FuncTy_4,
/*Linkage=*/GlobalValue::InternalLinkage,
/*Name=*/"__cxx_global_var_init", mod);
func___cxx_global_var_init->setCallingConv(CallingConv::C);
}
AttributeSet func___cxx_global_var_init_PAL;
func___cxx_global_var_init->setAttributes(func___cxx_global_var_init_PAL);
Function* func__ZN1AC2Ei = mod->getFunction("_ZN1AC2Ei");
if (!func__ZN1AC2Ei) {
func__ZN1AC2Ei = Function::Create(
/*Type=*/FuncTy_7,
/*Linkage=*/GlobalValue::LinkOnceODRLinkage ,
/*Name=*/"_ZN1AC2Ei", mod);
func__ZN1AC2Ei->setCallingConv(CallingConv::C);
func__ZN1AC2Ei->setAlignment(2);
}
AttributeSet func__ZN1AC2Ei_PAL;
{
SmallVector<AttributeSet, 4> Attrs;
AttributeSet PAS;
{
AttrBuilder B;
B.addAttribute(Attribute::NoUnwind);
PAS = AttributeSet::get(mod->getContext(), ~0U, B);
}
Attrs.push_back(PAS);
func__ZN1AC2Ei_PAL = AttributeSet::get(mod->getContext(), Attrs);
}
func__ZN1AC2Ei->setAttributes(func__ZN1AC2Ei_PAL);
Function* func_main = mod->getFunction("main");
if (!func_main) {
func_main = Function::Create(
/*Type=*/FuncTy_10,
/*Linkage=*/GlobalValue::ExternalLinkage,
/*Name=*/"main", mod);
func_main->setCallingConv(CallingConv::C);
}
AttributeSet func_main_PAL;
{
SmallVector<AttributeSet, 4> Attrs;
AttributeSet PAS;
{
AttrBuilder B;
B.addAttribute(Attribute::NoUnwind);
PAS = AttributeSet::get(mod->getContext(), ~0U, B);
}
Attrs.push_back(PAS);
func_main_PAL = AttributeSet::get(mod->getContext(), Attrs);
}
func_main->setAttributes(func_main_PAL);
Function* func__GLOBAL__I_a = mod->getFunction("_GLOBAL__I_a");
if (!func__GLOBAL__I_a) {
func__GLOBAL__I_a = Function::Create(
/*Type=*/FuncTy_4,
/*Linkage=*/GlobalValue::InternalLinkage,
/*Name=*/"_GLOBAL__I_a", mod);
func__GLOBAL__I_a->setCallingConv(CallingConv::C);
}
AttributeSet func__GLOBAL__I_a_PAL;
func__GLOBAL__I_a->setAttributes(func__GLOBAL__I_a_PAL);
// Global Variable Declarations
GlobalVariable* gvar_struct_a = new GlobalVariable(/*Module=*/*mod,
/*Type=*/StructTy_struct_A,
/*isConstant=*/false,
/*Linkage=*/GlobalValue::ExternalLinkage,
/*Initializer=*/0, // has initializer, specified below
/*Name=*/"a");
gvar_struct_a->setAlignment(4);
GlobalVariable* gvar_array_llvm_global_ctors = new GlobalVariable(/*Module=*/*mod,
/*Type=*/ArrayTy_1,
/*isConstant=*/false,
/*Linkage=*/GlobalValue::AppendingLinkage,
/*Initializer=*/0, // has initializer, specified below
/*Name=*/"llvm.global_ctors");
// Constant Definitions
ConstantAggregateZero* const_struct_11 = ConstantAggregateZero::get(StructTy_struct_A);
std::vector<Constant*> const_array_12_elems;
std::vector<Constant*> const_struct_13_fields;
ConstantInt* const_int32_14 = ConstantInt::get(mod->getContext(), APInt(32, StringRef("65535"), 10));
const_struct_13_fields.push_back(const_int32_14);
const_struct_13_fields.push_back(func__GLOBAL__I_a);
Constant* const_struct_13 = ConstantStruct::get(StructTy_2, const_struct_13_fields);
const_array_12_elems.push_back(const_struct_13);
Constant* const_array_12 = ConstantArray::get(ArrayTy_1, const_array_12_elems);
ConstantInt* const_int32_15 = ConstantInt::get(mod->getContext(), APInt(32, StringRef("2333"), 10));
ConstantInt* const_int32_16 = ConstantInt::get(mod->getContext(), APInt(32, StringRef("1"), 10));
ConstantInt* const_int32_17 = ConstantInt::get(mod->getContext(), APInt(32, StringRef("0"), 10));
// Global Variable Definitions
gvar_struct_a->setInitializer(const_struct_11);
gvar_array_llvm_global_ctors->setInitializer(const_array_12);
// Function Definitions
// Function: __cxx_global_var_init (func___cxx_global_var_init)
{
BasicBlock* label_entry = BasicBlock::Create(mod->getContext(), "entry",func___cxx_global_var_init,0);
// Block entry (label_entry)
std::vector<Value*> void_18_params;
void_18_params.push_back(gvar_struct_a);
void_18_params.push_back(const_int32_15);
CallInst* void_18 = CallInst::Create(func__ZN1AC2Ei, void_18_params, "", label_entry);
void_18->setCallingConv(CallingConv::C);
void_18->setTailCall(false);
AttributeSet void_18_PAL;
void_18->setAttributes(void_18_PAL);
ReturnInst::Create(mod->getContext(), label_entry);
}
// Function: _ZN1AC2Ei (func__ZN1AC2Ei)
{
Function::arg_iterator args = func__ZN1AC2Ei->arg_begin();
Value* ptr_this = args++;
ptr_this->setName("this");
Value* int32_x = args++;
int32_x->setName("x");
BasicBlock* label_entry_20 = BasicBlock::Create(mod->getContext(), "entry",func__ZN1AC2Ei,0);
// Block entry (label_entry_20)
AllocaInst* ptr_this_addr = new AllocaInst(PointerTy_0, "this.addr", label_entry_20);
ptr_this_addr->setAlignment(4);
AllocaInst* ptr_x_addr = new AllocaInst(IntegerType::get(mod->getContext(), 32), "x.addr", label_entry_20);
ptr_x_addr->setAlignment(4);
StoreInst* void_21 = new StoreInst(ptr_this, ptr_this_addr, false, label_entry_20);
void_21->setAlignment(4);
StoreInst* void_22 = new StoreInst(int32_x, ptr_x_addr, false, label_entry_20);
void_22->setAlignment(4);
LoadInst* ptr_this1 = new LoadInst(ptr_this_addr, "this1", false, label_entry_20);
LoadInst* int32_23 = new LoadInst(ptr_x_addr, "", false, label_entry_20);
int32_23->setAlignment(4);
std::vector<Value*> ptr_size_indices;
ptr_size_indices.push_back(const_int32_17);
ptr_size_indices.push_back(const_int32_17);
Instruction* ptr_size = GetElementPtrInst::Create(ptr_this1, ptr_size_indices, "size", label_entry_20);
StoreInst* void_24 = new StoreInst(int32_23, ptr_size, false, label_entry_20);
void_24->setAlignment(4);
LoadInst* int32_25 = new LoadInst(ptr_x_addr, "", false, label_entry_20);
int32_25->setAlignment(4);
std::vector<Value*> ptr_align_indices;
ptr_align_indices.push_back(const_int32_17);
ptr_align_indices.push_back(const_int32_16);
Instruction* ptr_align = GetElementPtrInst::Create(ptr_this1, ptr_align_indices, "align", label_entry_20);
StoreInst* void_26 = new StoreInst(int32_25, ptr_align, false, label_entry_20);
void_26->setAlignment(4);
ReturnInst::Create(mod->getContext(), label_entry_20);
}
// Function: main (func_main)
{
BasicBlock* label_entry_28 = BasicBlock::Create(mod->getContext(), "entry",func_main,0);
// Block entry (label_entry_28)
ReturnInst::Create(mod->getContext(), const_int32_17, label_entry_28);
}
// Function: _GLOBAL__I_a (func__GLOBAL__I_a)
{
BasicBlock* label_entry_30 = BasicBlock::Create(mod->getContext(), "entry",func__GLOBAL__I_a,0);
// Block entry (label_entry_30)
CallInst* void_31 = CallInst::Create(func___cxx_global_var_init, "", label_entry_30);
void_31->setCallingConv(CallingConv::C);
void_31->setTailCall(false);
AttributeSet void_31_PAL;
void_31->setAttributes(void_31_PAL);
ReturnInst::Create(mod->getContext(), label_entry_30);
}
return mod;
}
|
#include "stdafx.h"
#include "AFormat.h"
using namespace ::Formats;
using namespace Graph;
AdjacencyMatrix AFormat::GetMatrix(::Graph::Graph& gr)
{
::Graph::Builder builder;
AdjacencyMatrix matr = builder.GetAdjacencyMatrix(gr);
return matr;
}
void AFormat::SaveToFile(
std::ostream& stream,
::Graph::Graph& gr)
{
AdjacencyMatrix matr = GetMatrix(gr);
InnerSaveToFile(stream, matr, gr);
}
|
#include "askpassphrasedialog.h"
#include "ui_askpassphrasedialog.h"
#include "guiconstants.h"
#include "walletmodel.h"
#include <QMessageBox>
#include <QPushButton>
#include <QKeyEvent>
extern bool fWalletUnlockStakingOnly;
AskPassphraseDialog::AskPassphraseDialog(Mode mode, QWidget *parent) :
QDialog(parent),
ui(new Ui::AskPassphraseDialog),
mode(mode),
model(0),
fCapsLock(false)
{
ui->setupUi(this);
ui->passEdit1->setMaxLength(MAX_PASSPHRASE_SIZE);
ui->passEdit2->setMaxLength(MAX_PASSPHRASE_SIZE);
ui->passEdit3->setMaxLength(MAX_PASSPHRASE_SIZE);
// Setup Caps Lock detection.
ui->passEdit1->installEventFilter(this);
ui->passEdit2->installEventFilter(this);
ui->passEdit3->installEventFilter(this);
switch(mode)
{
case Encrypt: // Ask passphrase x2
ui->passLabel1->hide();
ui->passEdit1->hide();
ui->warningLabel->setText(tr("Enter the new passphrase to the wallet.<br/>Please use a passphrase of <b>10 or more random characters</b>, or <b>eight or more words</b>."));
setWindowTitle(tr("Encrypt wallet"));
break;
case UnlockStaking:
ui->stakingCheckBox->setChecked(true);
ui->stakingCheckBox->show();
// fallthru
case Unlock: // Ask passphrase
ui->warningLabel->setText(tr("This operation needs your wallet passphrase to unlock the wallet."));
ui->passLabel2->hide();
ui->passEdit2->hide();
ui->passLabel3->hide();
ui->passEdit3->hide();
setWindowTitle(tr("Unlock wallet"));
break;
case Decrypt: // Ask passphrase
ui->warningLabel->setText(tr("This operation needs your wallet passphrase to decrypt the wallet."));
ui->passLabel2->hide();
ui->passEdit2->hide();
ui->passLabel3->hide();
ui->passEdit3->hide();
setWindowTitle(tr("Decrypt wallet"));
break;
case ChangePass: // Ask old passphrase + new passphrase x2
setWindowTitle(tr("Change passphrase"));
ui->warningLabel->setText(tr("Enter the old and new passphrase to the wallet."));
break;
}
textChanged();
connect(ui->passEdit1, SIGNAL(textChanged(QString)), this, SLOT(textChanged()));
connect(ui->passEdit2, SIGNAL(textChanged(QString)), this, SLOT(textChanged()));
connect(ui->passEdit3, SIGNAL(textChanged(QString)), this, SLOT(textChanged()));
}
AskPassphraseDialog::~AskPassphraseDialog()
{
// Attempt to overwrite text so that they do not linger around in memory
ui->passEdit1->setText(QString(" ").repeated(ui->passEdit1->text().size()));
ui->passEdit2->setText(QString(" ").repeated(ui->passEdit2->text().size()));
ui->passEdit3->setText(QString(" ").repeated(ui->passEdit3->text().size()));
delete ui;
}
void AskPassphraseDialog::setModel(WalletModel *model)
{
this->model = model;
}
void AskPassphraseDialog::accept()
{
SecureString oldpass, newpass1, newpass2;
if(!model)
return;
oldpass.reserve(MAX_PASSPHRASE_SIZE);
newpass1.reserve(MAX_PASSPHRASE_SIZE);
newpass2.reserve(MAX_PASSPHRASE_SIZE);
// TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string)
// Alternately, find a way to make this input mlock()'d to begin with.
oldpass.assign(ui->passEdit1->text().toStdString().c_str());
newpass1.assign(ui->passEdit2->text().toStdString().c_str());
newpass2.assign(ui->passEdit3->text().toStdString().c_str());
switch(mode)
{
case Encrypt: {
if(newpass1.empty() || newpass2.empty())
{
// Cannot encrypt with empty passphrase
break;
}
QMessageBox::StandardButton retval = QMessageBox::question(this, tr("Confirm wallet encryption"),
tr("Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR COINS</b>!") + "<br><br>" + tr("Are you sure you wish to encrypt your wallet?"),
QMessageBox::Yes|QMessageBox::Cancel,
QMessageBox::Cancel);
if(retval == QMessageBox::Yes)
{
if(newpass1 == newpass2)
{
if(model->setWalletEncrypted(true, newpass1))
{
QMessageBox::warning(this, tr("Wallet encrypted"),
"<qt>" +
tr("geluk will close now to finish the encryption process. "
"Remember that encrypting your wallet cannot fully protect "
"your coins from being stolen by malware infecting your computer.") +
"<br><br><b>" +
tr("IMPORTANT: Any previous backups you have made of your wallet file "
"should be replaced with the newly generated, encrypted wallet file. "
"For security reasons, previous backups of the unencrypted wallet file "
"will become useless as soon as you start using the new, encrypted wallet.") +
"</b></qt>");
QApplication::quit();
}
else
{
QMessageBox::critical(this, tr("Wallet encryption failed"),
tr("Wallet encryption failed due to an internal error. Your wallet was not encrypted."));
}
QDialog::accept(); // Success
}
else
{
QMessageBox::critical(this, tr("Wallet encryption failed"),
tr("The supplied passphrases do not match."));
}
}
else
{
QDialog::reject(); // Cancelled
}
} break;
case UnlockStaking:
case Unlock:
if(!model->setWalletLocked(false, oldpass))
{
QMessageBox::critical(this, tr("Wallet unlock failed"),
tr("The passphrase entered for the wallet decryption was incorrect."));
}
else
{
fWalletUnlockStakingOnly = ui->stakingCheckBox->isChecked();
QDialog::accept(); // Success
}
break;
case Decrypt:
if(!model->setWalletEncrypted(false, oldpass))
{
QMessageBox::critical(this, tr("Wallet decryption failed"),
tr("The passphrase entered for the wallet decryption was incorrect."));
}
else
{
QDialog::accept(); // Success
}
break;
case ChangePass:
if(newpass1 == newpass2)
{
if(model->changePassphrase(oldpass, newpass1))
{
QMessageBox::information(this, tr("Wallet encrypted"),
tr("Wallet passphrase was successfully changed."));
QDialog::accept(); // Success
}
else
{
QMessageBox::critical(this, tr("Wallet encryption failed"),
tr("The passphrase entered for the wallet decryption was incorrect."));
}
}
else
{
QMessageBox::critical(this, tr("Wallet encryption failed"),
tr("The supplied passphrases do not match."));
}
break;
}
}
void AskPassphraseDialog::textChanged()
{
// Validate input, set Ok button to enabled when acceptable
bool acceptable = false;
switch(mode)
{
case Encrypt: // New passphrase x2
acceptable = !ui->passEdit2->text().isEmpty() && !ui->passEdit3->text().isEmpty();
break;
case UnlockStaking:
case Unlock: // Old passphrase x1
case Decrypt:
acceptable = !ui->passEdit1->text().isEmpty();
break;
case ChangePass: // Old passphrase x1, new passphrase x2
acceptable = !ui->passEdit1->text().isEmpty() && !ui->passEdit2->text().isEmpty() && !ui->passEdit3->text().isEmpty();
break;
}
ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(acceptable);
}
bool AskPassphraseDialog::event(QEvent *event)
{
// Detect Caps Lock key press.
if (event->type() == QEvent::KeyPress) {
QKeyEvent *ke = static_cast<QKeyEvent *>(event);
if (ke->key() == Qt::Key_CapsLock) {
fCapsLock = !fCapsLock;
}
if (fCapsLock) {
ui->capsLabel->setText(tr("Warning: The Caps Lock key is on!"));
} else {
ui->capsLabel->clear();
}
}
return QWidget::event(event);
}
bool AskPassphraseDialog::eventFilter(QObject *object, QEvent *event)
{
/* Detect Caps Lock.
* There is no good OS-independent way to check a key state in Qt, but we
* can detect Caps Lock by checking for the following condition:
* Shift key is down and the result is a lower case character, or
* Shift key is not down and the result is an upper case character.
*/
if (event->type() == QEvent::KeyPress) {
QKeyEvent *ke = static_cast<QKeyEvent *>(event);
QString str = ke->text();
if (str.length() != 0) {
const QChar *psz = str.unicode();
bool fShift = (ke->modifiers() & Qt::ShiftModifier) != 0;
if ((fShift && psz->isLower()) || (!fShift && psz->isUpper())) {
fCapsLock = true;
ui->capsLabel->setText(tr("Warning: The Caps Lock key is on!"));
} else if (psz->isLetter()) {
fCapsLock = false;
ui->capsLabel->clear();
}
}
}
return QDialog::eventFilter(object, event);
}
|
/******************************************************************************
* The MIT License (MIT)
*
* Copyright (c) 2016-2018 Baldur Karlsson
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
******************************************************************************/
#include "BufferViewer.h"
#include <float.h>
#include <QDoubleSpinBox>
#include <QFontDatabase>
#include <QItemSelection>
#include <QMenu>
#include <QMouseEvent>
#include <QMutexLocker>
#include <QScrollBar>
#include <QTimer>
#include <QtMath>
#include "Code/QRDUtils.h"
#include "Code/Resources.h"
#include "ui_BufferViewer.h"
class CameraWrapper
{
public:
virtual ~CameraWrapper() {}
virtual bool Update(QRect winSize) = 0;
virtual ICamera *camera() = 0;
virtual void MouseWheel(QWheelEvent *e) = 0;
virtual void MouseClick(QMouseEvent *e) { m_DragStartPos = e->pos(); }
virtual void MouseMove(QMouseEvent *e)
{
if(e->buttons() & Qt::LeftButton)
{
if(m_DragStartPos.x() < 0)
{
m_DragStartPos = e->pos();
}
m_DragStartPos = e->pos();
}
else
{
m_DragStartPos = QPoint(-1, -1);
}
}
virtual void KeyUp(QKeyEvent *e)
{
if(e->key() == Qt::Key_A || e->key() == Qt::Key_D)
setMove(Direction::Horiz, 0);
if(e->key() == Qt::Key_Q || e->key() == Qt::Key_E)
setMove(Direction::Vert, 0);
if(e->key() == Qt::Key_W || e->key() == Qt::Key_S)
setMove(Direction::Fwd, 0);
if(e->modifiers() & Qt::ShiftModifier)
m_CurrentSpeed = 3.0f;
else
m_CurrentSpeed = 1.0f;
}
virtual void KeyDown(QKeyEvent *e)
{
if(e->key() == Qt::Key_W)
setMove(Direction::Fwd, 1);
if(e->key() == Qt::Key_S)
setMove(Direction::Fwd, -1);
if(e->key() == Qt::Key_Q)
setMove(Direction::Vert, 1);
if(e->key() == Qt::Key_E)
setMove(Direction::Vert, -1);
if(e->key() == Qt::Key_D)
setMove(Direction::Horiz, 1);
if(e->key() == Qt::Key_A)
setMove(Direction::Horiz, -1);
if(e->modifiers() & Qt::ShiftModifier)
m_CurrentSpeed = 3.0f;
else
m_CurrentSpeed = 1.0f;
}
float SpeedMultiplier = 0.05f;
protected:
enum class Direction
{
Fwd,
Horiz,
Vert,
Num
};
int move(Direction dir) { return m_CurrentMove[(int)dir]; }
float currentSpeed() { return m_CurrentSpeed * SpeedMultiplier; }
QPoint dragStartPos() { return m_DragStartPos; }
private:
float m_CurrentSpeed = 1.0f;
int m_CurrentMove[(int)Direction::Num] = {0, 0, 0};
void setMove(Direction dir, int val) { m_CurrentMove[(int)dir] = val; }
QPoint m_DragStartPos = QPoint(-1, -1);
};
class ArcballWrapper : public CameraWrapper
{
public:
ArcballWrapper() { m_Cam = RENDERDOC_InitCamera(CameraType::Arcball); }
virtual ~ArcballWrapper() { m_Cam->Shutdown(); }
ICamera *camera() override { return m_Cam; }
void Reset(FloatVector pos, float dist)
{
m_Cam->ResetArcball();
setLookAtPos(pos);
SetDistance(dist);
}
void SetDistance(float dist)
{
m_Distance = qAbs(dist);
m_Cam->SetArcballDistance(m_Distance);
}
bool Update(QRect size) override
{
m_WinSize = size;
return false;
}
void MouseWheel(QWheelEvent *e) override
{
float mod = (1.0f - e->delta() / 2500.0f);
SetDistance(qMax(1e-6f, m_Distance * mod));
}
void MouseMove(QMouseEvent *e) override
{
if(dragStartPos().x() > 0)
{
if(e->buttons() == Qt::MiddleButton ||
(e->buttons() == Qt::LeftButton && e->modifiers() & Qt::AltModifier))
{
float xdelta = (float)(e->pos().x() - dragStartPos().x()) / 300.0f;
float ydelta = (float)(e->pos().y() - dragStartPos().y()) / 300.0f;
xdelta *= qMax(1.0f, m_Distance);
ydelta *= qMax(1.0f, m_Distance);
FloatVector right = m_Cam->GetRight();
FloatVector up = m_Cam->GetUp();
m_LookAt.x -= right.x * xdelta;
m_LookAt.y -= right.y * xdelta;
m_LookAt.z -= right.z * xdelta;
m_LookAt.x += up.x * ydelta;
m_LookAt.y += up.y * ydelta;
m_LookAt.z += up.z * ydelta;
m_Cam->SetPosition(m_LookAt.x, m_LookAt.y, m_LookAt.z);
}
else if(e->buttons() == Qt::LeftButton)
{
RotateArcball(dragStartPos(), e->pos());
}
}
CameraWrapper::MouseMove(e);
}
FloatVector lookAtPos() { return m_LookAt; }
void setLookAtPos(const FloatVector &v)
{
m_LookAt = v;
m_Cam->SetPosition(v.x, v.y, v.z);
}
private:
ICamera *m_Cam;
QRect m_WinSize;
float m_Distance = 10.0f;
FloatVector m_LookAt;
void RotateArcball(QPoint from, QPoint to)
{
float ax = ((float)from.x() / (float)m_WinSize.width()) * 2.0f - 1.0f;
float ay = ((float)from.y() / (float)m_WinSize.height()) * 2.0f - 1.0f;
float bx = ((float)to.x() / (float)m_WinSize.width()) * 2.0f - 1.0f;
float by = ((float)to.y() / (float)m_WinSize.height()) * 2.0f - 1.0f;
// this isn't a 'true arcball' but it handles extreme aspect ratios
// better. We basically 'centre' around the from point always being
// 0,0 (straight out of the screen) as if you're always dragging
// the arcball from the middle, and just use the relative movement
int minDimension = qMin(m_WinSize.width(), m_WinSize.height());
ax = ay = 0;
bx = ((float)(to.x() - from.x()) / (float)minDimension) * 2.0f;
by = ((float)(to.y() - from.y()) / (float)minDimension) * 2.0f;
ay = -ay;
by = -by;
m_Cam->RotateArcball(ax, ay, bx, by);
}
};
class FlycamWrapper : public CameraWrapper
{
public:
FlycamWrapper() { m_Cam = RENDERDOC_InitCamera(CameraType::FPSLook); }
virtual ~FlycamWrapper() { m_Cam->Shutdown(); }
ICamera *camera() override { return m_Cam; }
void Reset(FloatVector pos)
{
m_Position = pos;
m_Rotation = FloatVector();
m_Cam->SetPosition(m_Position.x, m_Position.y, m_Position.z);
m_Cam->SetFPSRotation(m_Rotation.x, m_Rotation.y, m_Rotation.z);
}
bool Update(QRect size) override
{
FloatVector fwd = m_Cam->GetForward();
FloatVector right = m_Cam->GetRight();
float speed = currentSpeed();
int horizMove = move(CameraWrapper::Direction::Horiz);
if(horizMove)
{
m_Position.x += right.x * speed * (float)horizMove;
m_Position.y += right.y * speed * (float)horizMove;
m_Position.z += right.z * speed * (float)horizMove;
}
int vertMove = move(CameraWrapper::Direction::Vert);
if(vertMove)
{
// this makes less intuitive sense, instead go 'absolute' up
// m_Position.x += up.x * speed * (float)vertMove;
// m_Position.y += up.y * speed * (float)vertMove;
// m_Position.z += up.z * speed * (float)vertMove;
m_Position.y += speed * (float)vertMove;
}
int fwdMove = move(CameraWrapper::Direction::Fwd);
if(fwdMove)
{
m_Position.x += fwd.x * speed * (float)fwdMove;
m_Position.y += fwd.y * speed * (float)fwdMove;
m_Position.z += fwd.z * speed * (float)fwdMove;
}
if(horizMove || vertMove || fwdMove)
{
m_Cam->SetPosition(m_Position.x, m_Position.y, m_Position.z);
return true;
}
return false;
}
void MouseWheel(QWheelEvent *e) override {}
void MouseMove(QMouseEvent *e) override
{
if(dragStartPos().x() > 0 && e->buttons() == Qt::LeftButton)
{
m_Rotation.y -= (float)(e->pos().x() - dragStartPos().x()) / 300.0f;
m_Rotation.x -= (float)(e->pos().y() - dragStartPos().y()) / 300.0f;
m_Cam->SetFPSRotation(m_Rotation.x, m_Rotation.y, m_Rotation.z);
}
CameraWrapper::MouseMove(e);
}
private:
ICamera *m_Cam;
FloatVector m_Position, m_Rotation;
};
struct BufferData
{
BufferData()
{
refcount.store(1);
data = end = NULL;
stride = 0;
}
void ref() { refcount.ref(); }
void deref()
{
bool alive = refcount.deref();
if(!alive)
{
delete[] data;
delete this;
}
}
QAtomicInteger<uint32_t> refcount;
byte *data;
byte *end;
size_t stride;
};
uint32_t CalcIndex(BufferData *data, uint32_t vertID, int32_t baseVertex)
{
byte *idxData = data->data + vertID * sizeof(uint32_t);
if(idxData + sizeof(uint32_t) > data->end)
return ~0U;
uint32_t idx = *(uint32_t *)idxData;
// apply base vertex but clamp to 0 if subtracting
if(baseVertex < 0)
{
uint32_t subtract = (uint32_t)(-baseVertex);
if(idx < subtract)
idx = 0;
else
idx -= subtract;
}
else if(baseVertex > 0)
{
idx += (uint32_t)baseVertex;
}
return idx;
}
static int columnGroupRole = Qt::UserRole + 10000;
class BufferItemModel : public QAbstractItemModel
{
public:
BufferItemModel(RDTableView *v, QObject *parent) : QAbstractItemModel(parent)
{
view = v;
view->setModel(this);
}
void beginReset() { emit beginResetModel(); }
void endReset()
{
cacheColumns();
m_ColumnCount = columnLookup.count() + reservedColumnCount();
emit endResetModel();
}
QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const override
{
if(row < 0 || row >= rowCount())
return QModelIndex();
return createIndex(row, column);
}
QModelIndex parent(const QModelIndex &index) const override { return QModelIndex(); }
int rowCount(const QModelIndex &parent = QModelIndex()) const override { return numRows; }
int columnCount(const QModelIndex &parent = QModelIndex()) const override
{
return m_ColumnCount;
}
Qt::ItemFlags flags(const QModelIndex &index) const override
{
if(!index.isValid())
return 0;
return QAbstractItemModel::flags(index);
}
QVariant headerData(int section, Qt::Orientation orientation, int role) const override
{
if(section < m_ColumnCount && orientation == Qt::Horizontal)
{
if(role == Qt::DisplayRole || role == columnGroupRole)
{
if(section == 0)
{
return meshView ? lit("VTX") : lit("Element");
}
else if(section == 1 && meshView)
{
return lit("IDX");
}
else
{
const FormatElement &el = elementForColumn(section);
if(el.format.compCount == 1 || role == columnGroupRole)
return el.name;
QChar comps[] = {QLatin1Char('x'), QLatin1Char('y'), QLatin1Char('z'), QLatin1Char('w')};
return QFormatStr("%1.%2").arg(el.name).arg(comps[componentForIndex(section)]);
}
}
}
return QVariant();
}
QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override
{
if(index.isValid())
{
if(role == Qt::SizeHintRole)
{
QStyleOptionViewItem opt = view->viewOptions();
opt.features |= QStyleOptionViewItem::HasDisplay;
// pad these columns to allow for sufficiently wide data
if(index.column() < reservedColumnCount())
opt.text = lit("4294967295");
else
opt.text = data(index).toString();
opt.text.replace(QLatin1Char('\n'), QChar::LineSeparator);
opt.styleObject = NULL;
QStyle *style = opt.widget ? opt.widget->style() : QApplication::style();
return style->sizeFromContents(QStyle::CT_ItemViewItem, &opt, QSize(), opt.widget);
}
uint32_t row = index.row();
int col = index.column();
if(role == columnGroupRole)
{
if(col < reservedColumnCount())
return -1 - col;
else
return columnLookup[col - reservedColumnCount()];
}
if((role == Qt::BackgroundRole || role == Qt::ForegroundRole) && col >= reservedColumnCount())
{
if(meshView)
{
int elIdx = columnLookup[col - reservedColumnCount()];
int compIdx = componentForIndex(col);
float lightnessOn = qBound(0.25, view->palette().color(QPalette::Base).lightnessF(), 0.75);
float lightnessOff = lightnessOn > 0.5f ? lightnessOn + 0.2f : lightnessOn - 0.2f;
static float a = 0.55f;
static float b = 0.8f;
if(elIdx == positionEl)
{
QColor backCol;
if(compIdx != 3 || !meshInput)
{
backCol = QColor::fromHslF(0.55f, 0.75f, lightnessOn);
}
else
{
backCol = QColor::fromHslF(0.55f, 0.75f, lightnessOff);
}
if(role == Qt::ForegroundRole)
return QBrush(contrastingColor(backCol, view->palette().color(QPalette::Text)));
return backCol;
}
else if(secondaryEnabled && elIdx == secondaryEl)
{
QColor backCol;
if((secondaryElAlpha && compIdx == 3) || (!secondaryElAlpha && compIdx != 3))
{
backCol = QColor::fromHslF(0.33f, 0.75f, lightnessOn);
}
else
{
backCol = QColor::fromHslF(0.33f, 0.75f, lightnessOff);
}
if(role == Qt::ForegroundRole)
return QBrush(contrastingColor(backCol, view->palette().color(QPalette::Text)));
return backCol;
}
}
else
{
const FormatElement &el = elementForColumn(col);
if(el.rgb && el.buffer < buffers.size())
{
const byte *data = buffers[el.buffer]->data;
const byte *end = buffers[el.buffer]->end;
data += buffers[el.buffer]->stride * row;
data += el.offset;
// only slightly wasteful, we need to fetch all variants together
// since some formats are packed and can't be read individually
QVariantList list = el.GetVariants(data, end);
if(!list.isEmpty())
{
QMetaType::Type vt = GetVariantMetatype(list[0]);
QColor rgb;
if(vt == QMetaType::Double)
{
double r = qBound(0.0, list[0].toDouble(), 1.0);
double g = list.size() > 1 ? qBound(0.0, list[1].toDouble(), 1.0) : 0.0;
double b = list.size() > 2 ? qBound(0.0, list[2].toDouble(), 1.0) : 0.0;
rgb = QColor::fromRgbF(r, g, b);
}
else if(vt == QMetaType::Float)
{
float r = qBound(0.0f, list[0].toFloat(), 1.0f);
float g = list.size() > 1 ? qBound(0.0f, list[1].toFloat(), 1.0f) : 0.0;
float b = list.size() > 2 ? qBound(0.0f, list[2].toFloat(), 1.0f) : 0.0;
rgb = QColor::fromRgbF(r, g, b);
}
else if(vt == QMetaType::UInt || vt == QMetaType::UShort || vt == QMetaType::UChar)
{
uint r = qBound(0U, list[0].toUInt(), 255U);
uint g = list.size() > 1 ? qBound(0U, list[1].toUInt(), 255U) : 0.0;
uint b = list.size() > 2 ? qBound(0U, list[2].toUInt(), 255U) : 0.0;
rgb = QColor::fromRgb(r, g, b);
}
else if(vt == QMetaType::Int || vt == QMetaType::Short || vt == QMetaType::SChar)
{
int r = qBound(0, list[0].toInt(), 255);
int g = list.size() > 1 ? qBound(0, list[1].toInt(), 255) : 0.0;
int b = list.size() > 2 ? qBound(0, list[2].toInt(), 255) : 0.0;
rgb = QColor::fromRgb(r, g, b);
}
if(role == Qt::BackgroundRole)
return QBrush(rgb);
else if(role == Qt::ForegroundRole)
return QBrush(contrastingColor(rgb, QColor::fromRgb(0, 0, 0)));
}
}
}
}
if(role == Qt::DisplayRole)
{
if(unclampedNumRows > 0 && row >= numRows - 2)
{
if(col < 2 && row == numRows - 1)
return QString::number(unclampedNumRows - numRows);
return lit("...");
}
if(col >= 0 && col < m_ColumnCount && row < numRows)
{
if(col == 0)
return row;
uint32_t idx = row;
if(indices && indices->data)
{
idx = CalcIndex(indices, row, baseVertex);
if(primRestart && idx == primRestart)
return col == 1 ? lit("--") : lit(" Restart");
if(idx == ~0U)
return outOfBounds();
}
if(col == 1 && meshView)
{
// if we have separate displayIndices, fetch that for display instead
if(displayIndices && displayIndices->data)
idx = CalcIndex(displayIndices, row, displayBaseVertex);
if(idx == ~0U)
return outOfBounds();
return idx;
}
const FormatElement &el = elementForColumn(col);
if(useGenerics(col))
return interpretGeneric(col, el);
uint32_t instIdx = 0;
if(el.instancerate > 0)
instIdx = curInstance / el.instancerate;
if(el.buffer < buffers.size())
{
const byte *data = buffers[el.buffer]->data;
const byte *end = buffers[el.buffer]->end;
if(!el.perinstance)
data += buffers[el.buffer]->stride * idx;
else
data += buffers[el.buffer]->stride * instIdx;
data += el.offset;
// only slightly wasteful, we need to fetch all variants together
// since some formats are packed and can't be read individually
QVariantList list = el.GetVariants(data, end);
int comp = componentForIndex(col);
if(comp < list.count())
{
QString ret;
uint32_t rowdim = el.matrixdim;
uint32_t coldim = el.format.compCount;
for(uint32_t r = 0; r < rowdim; r++)
{
if(r > 0)
ret += lit("\n");
if(el.rowmajor)
ret += interpretVariant(list[comp + r * coldim], el);
else
ret += interpretVariant(list[r + comp * rowdim], el);
}
return ret;
}
}
return outOfBounds();
}
}
}
return QVariant();
}
RDTableView *view = NULL;
int32_t displayBaseVertex = 0;
int32_t baseVertex = 0;
uint32_t curInstance = 0;
uint32_t numRows = 0, unclampedNumRows = 0;
bool meshView = true;
bool meshInput = false;
// we can have two index buffers for VSOut data:
// the original index buffer is used for the displayed value (in displayIndices), and the actual
// potentially remapped or permuated index buffer used for fetching data (in indices).
BufferData *displayIndices = NULL;
BufferData *indices = NULL;
QList<FormatElement> columns;
QVector<PixelValue> generics;
QVector<bool> genericsEnabled;
QList<BufferData *> buffers;
uint32_t primRestart = 0;
void setPosColumn(int pos)
{
QVector<int> roles = {Qt::BackgroundRole, Qt::ForegroundRole};
if(positionEl != pos)
{
if(positionEl >= 0)
emit dataChanged(index(0, firstColumnForElement(positionEl)),
index(rowCount() - 1, lastColumnForElement(positionEl)), roles);
if(pos >= 0)
emit dataChanged(index(0, firstColumnForElement(pos)),
index(rowCount() - 1, lastColumnForElement(pos)), roles);
}
positionEl = pos;
}
int posColumn() { return positionEl; }
QString posName()
{
if(positionEl >= 0 && positionEl < columns.count())
return columns[positionEl].name;
return QString();
}
void setSecondaryColumn(int sec, bool secEnabled, bool secAlpha)
{
QVector<int> roles = {Qt::BackgroundRole, Qt::ForegroundRole};
if(secondaryEl != sec || secondaryElAlpha != secAlpha || secondaryEnabled != secEnabled)
{
if(secondaryEl >= 0 && secondaryEl != sec)
emit dataChanged(index(0, firstColumnForElement(secondaryEl)),
index(rowCount() - 1, lastColumnForElement(secondaryEl)), roles);
if(sec >= 0)
emit dataChanged(index(0, firstColumnForElement(sec)),
index(rowCount() - 1, lastColumnForElement(sec)), roles);
}
secondaryEl = sec;
secondaryElAlpha = secAlpha;
secondaryEnabled = secEnabled;
}
int secondaryColumn() { return secondaryEl; }
bool secondaryAlpha() { return secondaryElAlpha; }
QString secondaryName()
{
if(secondaryEl >= 0 && secondaryEl < columns.count())
return columns[secondaryEl].name;
return QString();
}
int elementIndexForColumn(int col) const
{
if(col < reservedColumnCount())
return -1;
return columnLookup[col - reservedColumnCount()];
}
const FormatElement &elementForColumn(int col) const
{
return columns[columnLookup[col - reservedColumnCount()]];
}
bool useGenerics(int col) const
{
col = columnLookup[col - reservedColumnCount()];
return col < genericsEnabled.size() && genericsEnabled[col];
}
private:
// maps from column number (0-based from data, so excluding VTX/IDX columns)
// to the column element in the columns list, and lists its component.
//
// So a float4, float3, int set of columns would be:
// { 0, 0, 0, 0, 1, 1, 1, 2 };
// { 0, 1, 2, 3, 0, 1, 2, 0 };
QVector<int> columnLookup;
QVector<int> componentLookup;
int m_ColumnCount = 0;
int positionEl = -1;
int secondaryEl = -1;
bool secondaryElAlpha = false;
bool secondaryEnabled = false;
int reservedColumnCount() const { return (meshView ? 2 : 1); }
int componentForIndex(int col) const { return componentLookup[col - reservedColumnCount()]; }
int firstColumnForElement(int el) const
{
for(int i = 0; i < columnLookup.count(); i++)
{
if(columnLookup[i] == el)
return reservedColumnCount() + i;
}
return 0;
}
int lastColumnForElement(int el) const
{
for(int i = columnLookup.count() - 1; i >= 0; i--)
{
if(columnLookup[i] == el)
return reservedColumnCount() + i;
}
return columnCount() - 1;
}
void cacheColumns()
{
columnLookup.clear();
columnLookup.reserve(columns.count() * 4);
componentLookup.clear();
componentLookup.reserve(columns.count() * 4);
for(int i = 0; i < columns.count(); i++)
{
FormatElement &fmt = columns[i];
uint32_t compCount;
switch(fmt.format.type)
{
case ResourceFormatType::BC6:
case ResourceFormatType::ETC2:
case ResourceFormatType::R11G11B10:
case ResourceFormatType::R5G6B5:
case ResourceFormatType::R9G9B9E5: compCount = 3; break;
case ResourceFormatType::BC1:
case ResourceFormatType::BC7:
case ResourceFormatType::BC3:
case ResourceFormatType::BC2:
case ResourceFormatType::R10G10B10A2:
case ResourceFormatType::R5G5B5A1:
case ResourceFormatType::R4G4B4A4:
case ResourceFormatType::ASTC: compCount = 4; break;
case ResourceFormatType::BC5:
case ResourceFormatType::R4G4:
case ResourceFormatType::D16S8:
case ResourceFormatType::D24S8:
case ResourceFormatType::D32S8: compCount = 2; break;
case ResourceFormatType::BC4:
case ResourceFormatType::S8: compCount = 1; break;
case ResourceFormatType::YUV:
case ResourceFormatType::EAC:
default: compCount = fmt.format.compCount;
}
for(uint32_t c = 0; c < compCount; c++)
{
columnLookup.push_back(i);
componentLookup.push_back((int)c);
}
}
}
QString outOfBounds() const { return lit("---"); }
QString interpretGeneric(int col, const FormatElement &el) const
{
int comp = componentForIndex(col);
col = columnLookup[col - reservedColumnCount()];
if(col < generics.size())
{
if(el.format.compType == CompType::Float)
{
return interpretVariant(QVariant(generics[col].floatValue[comp]), el);
}
else if(el.format.compType == CompType::SInt)
{
return interpretVariant(QVariant(generics[col].intValue[comp]), el);
}
else if(el.format.compType == CompType::UInt)
{
return interpretVariant(QVariant(generics[col].uintValue[comp]), el);
}
}
return outOfBounds();
}
QString interpretVariant(const QVariant &v, const FormatElement &el) const
{
QString ret;
QMetaType::Type vt = GetVariantMetatype(v);
if(vt == QMetaType::Double)
{
double d = v.toDouble();
// pad with space on left if sign is missing, to better align
if(d < 0.0)
ret = Formatter::Format(d);
else if(d > 0.0)
ret = lit(" ") + Formatter::Format(d);
else if(qIsNaN(d))
ret = lit(" NaN");
else
// force negative and positive 0 together
ret = lit(" ") + Formatter::Format(0.0);
}
else if(vt == QMetaType::Float)
{
float f = v.toFloat();
// pad with space on left if sign is missing, to better align
if(f < 0.0)
ret = Formatter::Format(f);
else if(f > 0.0)
ret = lit(" ") + Formatter::Format(f);
else if(qIsNaN(f))
ret = lit(" NaN");
else
// force negative and positive 0 together
ret = lit(" ") + Formatter::Format(0.0);
}
else if(vt == QMetaType::UInt || vt == QMetaType::UShort || vt == QMetaType::UChar)
{
uint u = v.toUInt();
if(el.hex && el.format.type == ResourceFormatType::Regular)
ret = Formatter::HexFormat(u, el.format.compByteWidth);
else
ret = Formatter::Format(u, el.hex);
}
else if(vt == QMetaType::Int || vt == QMetaType::Short || vt == QMetaType::SChar)
{
int i = v.toInt();
if(i > 0)
ret = lit(" ") + Formatter::Format(i);
else
ret = Formatter::Format(i);
}
else
{
ret = v.toString();
}
return ret;
}
};
struct CachedElData
{
const FormatElement *el = NULL;
const byte *data = NULL;
const byte *end = NULL;
size_t stride;
int byteSize;
uint32_t instIdx = 0;
QByteArray nulls;
};
void CacheDataForIteration(QVector<CachedElData> &cache, const QList<FormatElement> &columns,
const QList<BufferData *> buffers, uint32_t inst)
{
cache.reserve(columns.count());
for(int col = 0; col < columns.count(); col++)
{
const FormatElement &el = columns[col];
CachedElData d;
d.el = ⪙
d.byteSize = el.byteSize();
d.nulls = QByteArray(d.byteSize, '\0');
if(el.instancerate > 0)
d.instIdx = inst / el.instancerate;
if(el.buffer < buffers.size())
{
d.data = buffers[el.buffer]->data;
d.end = buffers[el.buffer]->end;
d.stride = buffers[el.buffer]->stride;
d.data += el.offset;
if(el.perinstance)
d.data += d.stride * d.instIdx;
}
cache.push_back(d);
}
}
BufferViewer::BufferViewer(ICaptureContext &ctx, bool meshview, QWidget *parent)
: QFrame(parent), ui(new Ui::BufferViewer), m_Ctx(ctx)
{
ui->setupUi(this);
m_ModelVSIn = new BufferItemModel(ui->vsinData, this);
m_ModelVSOut = new BufferItemModel(ui->vsoutData, this);
m_ModelGSOut = new BufferItemModel(ui->gsoutData, this);
m_Flycam = new FlycamWrapper();
m_Arcball = new ArcballWrapper();
m_CurrentCamera = m_Arcball;
m_Output = NULL;
memset(&m_Config, 0, sizeof(m_Config));
m_Config.type = MeshDataStage::VSIn;
m_Config.wireframeDraw = true;
ui->outputTabs->setCurrentIndex(0);
m_CurStage = MeshDataStage::VSIn;
ui->vsinData->setFont(QFontDatabase::systemFont(QFontDatabase::FixedFont));
ui->vsoutData->setFont(QFontDatabase::systemFont(QFontDatabase::FixedFont));
ui->gsoutData->setFont(QFontDatabase::systemFont(QFontDatabase::FixedFont));
ui->rowOffset->setFont(Formatter::PreferredFont());
ui->instance->setFont(Formatter::PreferredFont());
ui->viewIndex->setFont(Formatter::PreferredFont());
ui->camSpeed->setFont(Formatter::PreferredFont());
ui->fovGuess->setFont(Formatter::PreferredFont());
ui->aspectGuess->setFont(Formatter::PreferredFont());
ui->nearGuess->setFont(Formatter::PreferredFont());
ui->farGuess->setFont(Formatter::PreferredFont());
m_ModelVSIn->meshView = m_ModelVSOut->meshView = m_ModelGSOut->meshView = m_MeshView = meshview;
m_ModelVSIn->meshInput = true;
if(meshview)
SetupMeshView();
else
SetupRawView();
m_ExportMenu = new QMenu(this);
m_ExportCSV = new QAction(tr("Export to &CSV"), this);
m_ExportCSV->setIcon(Icons::save());
m_ExportBytes = new QAction(tr("Export to &Bytes"), this);
m_ExportBytes->setIcon(Icons::save());
m_ExportMenu->addAction(m_ExportCSV);
m_ExportMenu->addAction(m_ExportBytes);
m_DebugVert = new QAction(tr("&Debug this Vertex"), this);
m_DebugVert->setIcon(Icons::wrench());
ui->exportDrop->setMenu(m_ExportMenu);
QObject::connect(m_ExportCSV, &QAction::triggered,
[this] { exportData(BufferExport(BufferExport::CSV)); });
QObject::connect(m_ExportBytes, &QAction::triggered,
[this] { exportData(BufferExport(BufferExport::RawBytes)); });
QObject::connect(m_DebugVert, &QAction::triggered, this, &BufferViewer::debugVertex);
QObject::connect(ui->exportDrop, &QToolButton::clicked,
[this] { exportData(BufferExport(BufferExport::CSV)); });
ui->vsinData->setContextMenuPolicy(Qt::CustomContextMenu);
ui->vsoutData->setContextMenuPolicy(Qt::CustomContextMenu);
ui->gsoutData->setContextMenuPolicy(Qt::CustomContextMenu);
QMenu *menu = new QMenu(this);
QObject::connect(ui->vsinData, &RDTableView::customContextMenuRequested,
[this, menu](const QPoint &pos) { stageRowMenu(MeshDataStage::VSIn, menu, pos); });
menu = new QMenu(this);
QObject::connect(
ui->vsoutData, &RDTableView::customContextMenuRequested,
[this, menu](const QPoint &pos) { stageRowMenu(MeshDataStage::VSOut, menu, pos); });
menu = new QMenu(this);
QObject::connect(
ui->gsoutData, &RDTableView::customContextMenuRequested,
[this, menu](const QPoint &pos) { stageRowMenu(MeshDataStage::GSOut, menu, pos); });
ui->dockarea->setAllowFloatingWindow(false);
ui->controlType->addItems({tr("Arcball"), tr("WASD")});
ui->controlType->adjustSize();
configureDrawRange();
ui->solidShading->addItems({tr("None"), tr("Solid Colour"), tr("Flat Shaded"), tr("Secondary")});
ui->solidShading->adjustSize();
ui->solidShading->setCurrentIndex(0);
ui->matrixType->addItems({tr("Perspective"), tr("Orthographic")});
// wireframe only available on solid shaded options
ui->wireframeRender->setEnabled(false);
ui->fovGuess->setValue(90.0);
on_controlType_currentIndexChanged(0);
QObject::connect(ui->vsinData->selectionModel(), &QItemSelectionModel::selectionChanged, this,
&BufferViewer::data_selected);
QObject::connect(ui->vsoutData->selectionModel(), &QItemSelectionModel::selectionChanged, this,
&BufferViewer::data_selected);
QObject::connect(ui->gsoutData->selectionModel(), &QItemSelectionModel::selectionChanged, this,
&BufferViewer::data_selected);
m_CurView = ui->vsinData;
QObject::connect(ui->vsinData, &RDTableView::clicked, [this]() { m_CurView = ui->vsinData; });
QObject::connect(ui->vsoutData, &RDTableView::clicked, [this]() { m_CurView = ui->vsoutData; });
QObject::connect(ui->gsoutData, &RDTableView::clicked, [this]() { m_CurView = ui->gsoutData; });
QObject::connect(ui->vsinData->verticalScrollBar(), &QScrollBar::valueChanged, this,
&BufferViewer::data_scrolled);
QObject::connect(ui->vsoutData->verticalScrollBar(), &QScrollBar::valueChanged, this,
&BufferViewer::data_scrolled);
QObject::connect(ui->gsoutData->verticalScrollBar(), &QScrollBar::valueChanged, this,
&BufferViewer::data_scrolled);
QObject::connect(ui->fovGuess, OverloadedSlot<double>::of(&QDoubleSpinBox::valueChanged), this,
&BufferViewer::camGuess_changed);
QObject::connect(ui->aspectGuess, OverloadedSlot<double>::of(&QDoubleSpinBox::valueChanged), this,
&BufferViewer::camGuess_changed);
QObject::connect(ui->nearGuess, OverloadedSlot<double>::of(&QDoubleSpinBox::valueChanged), this,
&BufferViewer::camGuess_changed);
QObject::connect(ui->farGuess, OverloadedSlot<double>::of(&QDoubleSpinBox::valueChanged), this,
&BufferViewer::camGuess_changed);
QObject::connect(ui->matrixType, OverloadedSlot<int>::of(&QComboBox::currentIndexChanged),
[this](int) { camGuess_changed(0.0); });
Reset();
m_Ctx.AddCaptureViewer(this);
}
void BufferViewer::SetupRawView()
{
ui->formatSpecifier->setVisible(true);
ui->outputTabs->setVisible(false);
ui->vsoutData->setVisible(false);
ui->gsoutData->setVisible(false);
// hide buttons we don't want in the toolbar
ui->syncViews->setVisible(false);
ui->instanceLabel->setVisible(false);
ui->instance->setVisible(false);
ui->viewLabel->setVisible(false);
ui->viewIndex->setVisible(false);
ui->vsinData->setWindowTitle(tr("Buffer Contents"));
ui->vsinData->setFrameShape(QFrame::NoFrame);
ui->dockarea->addToolWindow(ui->vsinData, ToolWindowManager::EmptySpace);
ui->dockarea->setToolWindowProperties(ui->vsinData, ToolWindowManager::HideCloseButton);
ui->vsinData->setPinnedColumns(1);
ui->vsinData->setColumnGroupRole(columnGroupRole);
ui->formatSpecifier->setWindowTitle(tr("Buffer Format"));
ui->dockarea->addToolWindow(ui->formatSpecifier, ToolWindowManager::AreaReference(
ToolWindowManager::BottomOf,
ui->dockarea->areaOf(ui->vsinData), 0.5f));
ui->dockarea->setToolWindowProperties(ui->formatSpecifier, ToolWindowManager::HideCloseButton);
QObject::connect(ui->formatSpecifier, &BufferFormatSpecifier::processFormat, this,
&BufferViewer::processFormat);
QVBoxLayout *vertical = new QVBoxLayout(this);
vertical->setSpacing(3);
vertical->setContentsMargins(3, 3, 3, 3);
vertical->addWidget(ui->meshToolbar);
vertical->addWidget(ui->dockarea);
}
void BufferViewer::SetupMeshView()
{
setWindowTitle(tr("Mesh Output"));
// hide buttons we don't want in the toolbar
ui->byteRangeLine->setVisible(false);
ui->byteRangeStartLabel->setVisible(false);
ui->byteRangeStart->setVisible(false);
ui->byteRangeLengthLabel->setVisible(false);
ui->byteRangeLength->setVisible(false);
ui->resourceDetails->setVisible(false);
ui->formatSpecifier->setVisible(false);
ui->cameraControlsGroup->setVisible(false);
ui->outputTabs->setWindowTitle(tr("Preview"));
ui->dockarea->addToolWindow(ui->outputTabs, ToolWindowManager::EmptySpace);
ui->dockarea->setToolWindowProperties(ui->outputTabs, ToolWindowManager::HideCloseButton);
ui->vsinData->setWindowTitle(tr("VS Input"));
ui->vsinData->setFrameShape(QFrame::NoFrame);
ui->dockarea->addToolWindow(
ui->vsinData, ToolWindowManager::AreaReference(ToolWindowManager::TopOf,
ui->dockarea->areaOf(ui->outputTabs), 0.5f));
ui->dockarea->setToolWindowProperties(ui->vsinData, ToolWindowManager::HideCloseButton);
ui->vsoutData->setWindowTitle(tr("VS Output"));
ui->vsoutData->setFrameShape(QFrame::NoFrame);
ui->dockarea->addToolWindow(
ui->vsoutData, ToolWindowManager::AreaReference(ToolWindowManager::RightOf,
ui->dockarea->areaOf(ui->vsinData), 0.5f));
ui->dockarea->setToolWindowProperties(ui->vsoutData, ToolWindowManager::HideCloseButton);
ui->gsoutData->setWindowTitle(tr("GS/DS Output"));
ui->gsoutData->setFrameShape(QFrame::NoFrame);
ui->dockarea->addToolWindow(
ui->gsoutData, ToolWindowManager::AreaReference(ToolWindowManager::AddTo,
ui->dockarea->areaOf(ui->vsoutData), 0.5f));
ui->dockarea->setToolWindowProperties(ui->gsoutData, ToolWindowManager::HideCloseButton);
ToolWindowManager::raiseToolWindow(ui->vsoutData);
m_HeaderMenu = new QMenu(this);
m_ResetColumnSel = new QAction(tr("Reset Selected Columns"), this);
m_SelectPosColumn = new QAction(tr("Select as Position"), this);
m_SelectSecondColumn = new QAction(tr("Select as Secondary"), this);
m_SelectSecondAlphaColumn = new QAction(tr("Select Alpha as Secondary"), this);
m_HeaderMenu->addAction(m_ResetColumnSel);
m_HeaderMenu->addSeparator();
m_HeaderMenu->addAction(m_SelectPosColumn);
m_HeaderMenu->addAction(m_SelectSecondColumn);
m_HeaderMenu->addAction(m_SelectSecondAlphaColumn);
QObject::connect(m_ResetColumnSel, &QAction::triggered, [this]() {
guessPositionColumn((BufferItemModel *)m_CurView->model());
guessSecondaryColumn((BufferItemModel *)m_CurView->model());
updatePreviewColumns();
INVOKE_MEMFN(RT_UpdateAndDisplay);
});
QObject::connect(m_SelectPosColumn, &QAction::triggered, [this]() {
BufferItemModel *model = (BufferItemModel *)m_CurView->model();
model->setPosColumn(m_ContextColumn);
updatePreviewColumns();
INVOKE_MEMFN(RT_UpdateAndDisplay);
});
QObject::connect(m_SelectSecondColumn, &QAction::triggered, [this]() {
BufferItemModel *model = (BufferItemModel *)m_CurView->model();
model->setSecondaryColumn(m_ContextColumn, m_Config.solidShadeMode == SolidShade::Secondary,
false);
updatePreviewColumns();
INVOKE_MEMFN(RT_UpdateAndDisplay);
});
QObject::connect(m_SelectSecondAlphaColumn, &QAction::triggered, [this]() {
BufferItemModel *model = (BufferItemModel *)m_CurView->model();
model->setSecondaryColumn(m_ContextColumn, m_Config.solidShadeMode == SolidShade::Secondary,
true);
updatePreviewColumns();
INVOKE_MEMFN(RT_UpdateAndDisplay);
});
ui->vsinData->horizontalHeader()->setContextMenuPolicy(Qt::CustomContextMenu);
ui->vsoutData->horizontalHeader()->setContextMenuPolicy(Qt::CustomContextMenu);
ui->gsoutData->horizontalHeader()->setContextMenuPolicy(Qt::CustomContextMenu);
ui->vsinData->setPinnedColumns(2);
ui->vsoutData->setPinnedColumns(2);
ui->gsoutData->setPinnedColumns(2);
ui->vsinData->setColumnGroupRole(columnGroupRole);
ui->vsoutData->setColumnGroupRole(columnGroupRole);
ui->gsoutData->setColumnGroupRole(columnGroupRole);
QObject::connect(ui->vsinData->horizontalHeader(), &QHeaderView::customContextMenuRequested,
[this](const QPoint &pos) { meshHeaderMenu(MeshDataStage::VSIn, pos); });
QObject::connect(ui->vsoutData->horizontalHeader(), &QHeaderView::customContextMenuRequested,
[this](const QPoint &pos) { meshHeaderMenu(MeshDataStage::VSOut, pos); });
QObject::connect(ui->gsoutData->horizontalHeader(), &QHeaderView::customContextMenuRequested,
[this](const QPoint &pos) { meshHeaderMenu(MeshDataStage::GSOut, pos); });
QVBoxLayout *vertical = new QVBoxLayout(this);
vertical->setSpacing(3);
vertical->setContentsMargins(3, 3, 3, 3);
vertical->addWidget(ui->meshToolbar);
vertical->addWidget(ui->dockarea);
QTimer *renderTimer = new QTimer(this);
QObject::connect(renderTimer, &QTimer::timeout, this, &BufferViewer::render_timer);
renderTimer->setSingleShot(false);
renderTimer->setInterval(10);
renderTimer->start();
}
void BufferViewer::meshHeaderMenu(MeshDataStage stage, const QPoint &pos)
{
int col = tableForStage(stage)->horizontalHeader()->logicalIndexAt(pos);
if(col < 2)
return;
m_CurView = tableForStage(stage);
m_ContextColumn = modelForStage(stage)->elementIndexForColumn(col);
m_SelectSecondAlphaColumn->setEnabled(
modelForStage(stage)->elementForColumn(col).format.compCount == 4);
m_HeaderMenu->popup(tableForStage(stage)->horizontalHeader()->mapToGlobal(pos));
}
void BufferViewer::stageRowMenu(MeshDataStage stage, QMenu *menu, const QPoint &pos)
{
m_CurView = tableForStage(stage);
menu->clear();
if(m_MeshView && stage != MeshDataStage::GSOut && m_Ctx.CurPipelineState().IsCaptureD3D11())
{
menu->addAction(m_DebugVert);
menu->addSeparator();
}
menu->addAction(m_ExportCSV);
menu->addAction(m_ExportBytes);
menu->popup(m_CurView->viewport()->mapToGlobal(pos));
}
BufferViewer::~BufferViewer()
{
if(m_Output)
{
m_Ctx.Replay().BlockInvoke([this](IReplayController *r) { m_Output->Shutdown(); });
}
if(m_ModelVSIn->indices)
m_ModelVSIn->indices->deref();
for(auto vb : m_ModelVSIn->buffers)
vb->deref();
if(m_ModelVSOut->indices)
m_ModelVSOut->indices->deref();
// only VSOut has display indices - GSOut has no indices at all, and VSIn has no special case
if(m_ModelVSOut->displayIndices)
m_ModelVSOut->displayIndices->deref();
for(auto vb : m_ModelVSOut->buffers)
vb->deref();
for(auto vb : m_ModelGSOut->buffers)
vb->deref();
delete m_Arcball;
delete m_Flycam;
if(m_MeshView)
m_Ctx.BuiltinWindowClosed(this);
m_Ctx.RemoveCaptureViewer(this);
delete ui;
}
void BufferViewer::OnCaptureLoaded()
{
Reset();
if(!m_MeshView)
return;
WId renderID = ui->render->winId();
m_Ctx.Replay().BlockInvoke([renderID, this](IReplayController *r) {
m_Output = r->CreateOutput(m_Ctx.CreateWindowingData(renderID), ReplayOutputType::Mesh);
ui->render->setOutput(m_Output);
RT_UpdateAndDisplay(r);
});
}
void BufferViewer::OnCaptureClosed()
{
Reset();
if(!m_MeshView)
ToolWindowManager::closeToolWindow(this);
}
void BufferViewer::OnEventChanged(uint32_t eventId)
{
int vsinHoriz = ui->vsinData->horizontalScrollBar()->value();
int vsoutHoriz = ui->vsoutData->horizontalScrollBar()->value();
int gsoutHoriz = ui->gsoutData->horizontalScrollBar()->value();
QString highlightNames[6] = {
m_ModelVSIn->posName(), m_ModelVSIn->secondaryName(), m_ModelVSOut->posName(),
m_ModelVSOut->secondaryName(), m_ModelGSOut->posName(), m_ModelGSOut->secondaryName(),
};
updateWindowTitle();
const DrawcallDescription *draw = m_Ctx.CurDrawcall();
configureDrawRange();
if(m_MeshView)
{
ClearModels();
CalcColumnWidth();
ClearModels();
m_ModelVSIn->primRestart = 0;
m_ModelVSOut->primRestart = 0;
m_ModelGSOut->primRestart = 0;
if(m_Ctx.CurPipelineState().IsStripRestartEnabled() && draw &&
(draw->flags & DrawFlags::Indexed) && IsStrip(draw->topology))
{
m_ModelVSIn->primRestart = m_Ctx.CurPipelineState().GetStripRestartIndex();
if(draw->indexByteWidth == 1)
m_ModelVSIn->primRestart &= 0xff;
else if(draw->indexByteWidth == 2)
m_ModelVSIn->primRestart &= 0xffff;
m_ModelVSOut->primRestart = m_ModelVSIn->primRestart;
}
}
else
{
QString errors;
QList<FormatElement> cols = FormatElement::ParseFormatString(m_Format, 0, true, errors);
ClearModels();
m_ModelVSIn->columns = cols;
}
EnableCameraGuessControls();
m_ModelVSIn->curInstance = m_Config.curInstance;
m_ModelVSOut->curInstance = m_Config.curInstance;
m_ModelGSOut->curInstance = m_Config.curInstance;
m_ModelVSIn->beginReset();
m_ModelVSOut->beginReset();
m_ModelGSOut->beginReset();
m_ModelVSIn->baseVertex = draw ? draw->baseVertex : 0;
ui->instance->setEnabled(draw && draw->numInstances > 1);
if(!ui->instance->isEnabled())
ui->instance->setValue(0);
if(draw)
ui->instance->setMaximum(qMax(0, int(draw->numInstances) - 1));
uint32_t numViews = m_Ctx.CurPipelineState().MultiviewBroadcastCount();
if(draw && numViews > 1)
{
ui->viewIndex->setEnabled(true);
ui->viewIndex->setMaximum(qMax(0, int(numViews) - 1));
}
else
{
ui->viewIndex->setEnabled(false);
ui->viewIndex->setValue(0);
}
if(m_MeshView)
{
configureMeshColumns();
if(m_ModelVSIn->posColumn() == -1 || highlightNames[0] != m_ModelVSIn->posName())
guessPositionColumn(m_ModelVSIn);
if(m_ModelVSIn->secondaryColumn() == -1 || highlightNames[1] != m_ModelVSIn->secondaryName())
guessSecondaryColumn(m_ModelVSIn);
if(m_ModelVSOut->posColumn() == -1 || highlightNames[2] != m_ModelVSOut->posName())
guessSecondaryColumn(m_ModelVSOut);
if(m_ModelVSOut->secondaryColumn() == -1 || highlightNames[3] != m_ModelVSOut->secondaryName())
guessPositionColumn(m_ModelVSOut);
if(m_ModelGSOut->posColumn() == -1 || highlightNames[4] != m_ModelGSOut->posName())
guessPositionColumn(m_ModelGSOut);
if(m_ModelGSOut->secondaryColumn() == -1 || highlightNames[5] != m_ModelGSOut->secondaryName())
guessSecondaryColumn(m_ModelGSOut);
}
// needs to happen here so the mesh config is accurate when highlighting data is cached.
updatePreviewColumns();
m_Ctx.Replay().AsyncInvoke([this, vsinHoriz, vsoutHoriz, gsoutHoriz](IReplayController *r) {
BufferData *buf = NULL;
if(m_MeshView)
{
RT_FetchMeshData(r);
}
else
{
buf = new BufferData;
bytebuf data;
if(m_IsBuffer)
{
uint64_t len = m_ByteSize;
if(len == UINT64_MAX)
len = 0;
data = r->GetBufferData(m_BufferID, m_ByteOffset, len);
}
else
{
data = r->GetTextureData(m_BufferID, m_TexArrayIdx, m_TexMip);
}
buf->data = new byte[data.size()];
memcpy(buf->data, data.data(), data.size());
buf->end = buf->data + data.size();
}
GUIInvoke::call(this, [this, buf, vsinHoriz, vsoutHoriz, gsoutHoriz] {
if(buf)
{
// calculate tight stride
buf->stride = 0;
for(const FormatElement &el : m_ModelVSIn->columns)
buf->stride += el.byteSize();
buf->stride = qMax((size_t)1, buf->stride);
uint32_t bufCount = uint32_t(buf->end - buf->data);
m_ModelVSIn->numRows = uint32_t((bufCount + buf->stride - 1) / buf->stride);
m_ModelVSIn->unclampedNumRows = 0;
// ownership passes to model
m_ModelVSIn->buffers.push_back(buf);
}
updatePreviewColumns();
INVOKE_MEMFN(RT_UpdateAndDisplay);
m_ModelVSIn->endReset();
m_ModelVSOut->endReset();
m_ModelGSOut->endReset();
ApplyRowAndColumnDims(m_ModelVSIn->columnCount(), ui->vsinData);
ApplyRowAndColumnDims(m_ModelVSOut->columnCount(), ui->vsoutData);
ApplyRowAndColumnDims(m_ModelGSOut->columnCount(), ui->gsoutData);
int numRows = qMax(qMax(m_ModelVSIn->numRows, m_ModelVSOut->numRows), m_ModelGSOut->numRows);
ui->rowOffset->setMaximum(qMax(0, numRows - 1));
ScrollToRow(m_ModelVSIn, ui->rowOffset->value());
ScrollToRow(m_ModelVSOut, ui->rowOffset->value());
ScrollToRow(m_ModelGSOut, ui->rowOffset->value());
ui->vsinData->horizontalScrollBar()->setValue(vsinHoriz);
ui->vsoutData->horizontalScrollBar()->setValue(vsoutHoriz);
ui->gsoutData->horizontalScrollBar()->setValue(gsoutHoriz);
});
});
}
QVariant BufferViewer::persistData()
{
QVariantMap state = ui->dockarea->saveState();
return state;
}
void BufferViewer::setPersistData(const QVariant &persistData)
{
QVariantMap state = persistData.toMap();
ui->dockarea->restoreState(state);
}
void BufferViewer::RT_FetchMeshData(IReplayController *r)
{
const DrawcallDescription *draw = m_Ctx.CurDrawcall();
BoundVBuffer ib = m_Ctx.CurPipelineState().GetIBuffer();
rdcarray<BoundVBuffer> vbs = m_Ctx.CurPipelineState().GetVBuffers();
bytebuf idata;
if(ib.resourceId != ResourceId() && draw && (draw->flags & DrawFlags::Indexed))
idata = r->GetBufferData(ib.resourceId, ib.byteOffset + draw->indexOffset * draw->indexByteWidth,
draw->numIndices * draw->indexByteWidth);
uint32_t *indices = NULL;
if(m_ModelVSIn->indices)
m_ModelVSIn->indices->deref();
m_ModelVSIn->indices = new BufferData();
if(draw && draw->indexByteWidth != 0 && !idata.isEmpty())
{
indices = new uint32_t[draw->numIndices];
m_ModelVSIn->indices->data = (byte *)indices;
m_ModelVSIn->indices->end = (byte *)(indices + draw->numIndices);
}
else if(draw && (draw->flags & DrawFlags::Indexed))
{
indices = new uint32_t[1];
m_ModelVSIn->indices->data = (byte *)indices;
m_ModelVSIn->indices->end = (byte *)indices;
}
uint32_t maxIndex = 0;
if(draw)
maxIndex = qMax(1U, draw->numIndices) - 1;
if(draw && !idata.isEmpty())
{
maxIndex = 0;
if(draw->indexByteWidth == 1)
{
uint8_t primRestart = m_ModelVSIn->primRestart & 0xff;
for(size_t i = 0; i < idata.size() && (uint32_t)i < draw->numIndices; i++)
{
if(primRestart && idata[i] == primRestart)
continue;
indices[i] = (uint32_t)idata[i];
maxIndex = qMax(maxIndex, indices[i]);
}
}
else if(draw->indexByteWidth == 2)
{
uint16_t primRestart = m_ModelVSIn->primRestart & 0xffff;
uint16_t *src = (uint16_t *)idata.data();
for(size_t i = 0; i < idata.size() / sizeof(uint16_t) && (uint32_t)i < draw->numIndices; i++)
{
if(primRestart && idata[i] == primRestart)
continue;
indices[i] = (uint32_t)src[i];
maxIndex = qMax(maxIndex, indices[i]);
}
}
else if(draw->indexByteWidth == 4)
{
uint16_t primRestart = m_ModelVSIn->primRestart;
memcpy(indices, idata.data(), qMin(idata.size(), draw->numIndices * sizeof(uint32_t)));
for(uint32_t i = 0; i < draw->numIndices; i++)
{
if(primRestart && idata[i] == primRestart)
continue;
maxIndex = qMax(maxIndex, indices[i]);
}
}
}
int vbIdx = 0;
for(BoundVBuffer vb : vbs)
{
bool used = false;
bool pi = false;
bool pv = false;
uint32_t maxAttrOffset = 0;
for(const FormatElement &col : m_ModelVSIn->columns)
{
if(col.buffer == vbIdx)
{
used = true;
maxAttrOffset = qMax(maxAttrOffset, col.offset);
if(col.perinstance)
pi = true;
else
pv = true;
}
}
vbIdx++;
uint32_t maxIdx = 0;
uint32_t offset = 0;
if(used && draw)
{
if(pi)
{
maxIdx = qMax(1U, draw->numInstances) - 1;
offset = draw->instanceOffset;
}
if(pv)
{
maxIdx = qMax(maxIndex, maxIdx);
offset = draw->vertexOffset;
if(draw->baseVertex > 0)
maxIdx += (uint32_t)draw->baseVertex;
}
if(pi && pv)
qCritical() << "Buffer used for both instance and vertex rendering!";
}
BufferData *buf = new BufferData;
if(used)
{
bytebuf bufdata = r->GetBufferData(vb.resourceId, vb.byteOffset + offset * vb.byteStride,
(maxIdx + 1) * vb.byteStride + maxAttrOffset);
buf->data = new byte[bufdata.size()];
memcpy(buf->data, bufdata.data(), bufdata.size());
buf->end = buf->data + bufdata.size();
buf->stride = vb.byteStride;
}
// ref passes to model
m_ModelVSIn->buffers.push_back(buf);
}
m_PostVS = r->GetPostVSData(m_Config.curInstance, m_Config.curView, MeshDataStage::VSOut);
m_ModelVSOut->numRows = m_PostVS.numIndices;
m_ModelVSOut->unclampedNumRows = 0;
m_ModelVSOut->baseVertex = m_PostVS.baseVertex;
m_ModelVSOut->displayBaseVertex = m_ModelVSIn->baseVertex;
if(draw && m_PostVS.indexResourceId != ResourceId() && (draw->flags & DrawFlags::Indexed))
idata = r->GetBufferData(m_PostVS.indexResourceId, m_PostVS.indexByteOffset,
draw->numIndices * m_PostVS.indexByteStride);
indices = NULL;
if(m_ModelVSOut->indices)
m_ModelVSOut->indices->deref();
if(m_ModelVSOut->displayIndices)
m_ModelVSOut->displayIndices->deref();
if(m_ModelVSIn->indices)
{
// display the same index values
m_ModelVSOut->displayIndices = m_ModelVSIn->indices;
m_ModelVSOut->displayIndices->ref();
m_ModelVSOut->indices = new BufferData();
if(draw && draw->indexByteWidth != 0 && !idata.isEmpty())
{
indices = new uint32_t[draw->numIndices];
m_ModelVSOut->indices->data = (byte *)indices;
m_ModelVSOut->indices->end = (byte *)(indices + draw->numIndices);
if(draw->indexByteWidth == 1)
{
for(size_t i = 0; i < idata.size() && (uint32_t)i < draw->numIndices; i++)
indices[i] = (uint32_t)idata[i];
}
else if(draw->indexByteWidth == 2)
{
uint16_t *src = (uint16_t *)idata.data();
for(size_t i = 0; i < idata.size() / sizeof(uint16_t) && (uint32_t)i < draw->numIndices; i++)
indices[i] = (uint32_t)src[i];
}
else if(draw->indexByteWidth == 4)
{
memcpy(indices, idata.data(), qMin(idata.size(), draw->numIndices * sizeof(uint32_t)));
}
}
}
if(m_PostVS.vertexResourceId != ResourceId())
{
BufferData *postvs = new BufferData;
bytebuf bufdata = r->GetBufferData(m_PostVS.vertexResourceId, m_PostVS.vertexByteOffset, 0);
postvs->data = new byte[bufdata.size()];
memcpy(postvs->data, bufdata.data(), bufdata.size());
postvs->end = postvs->data + bufdata.size();
postvs->stride = m_PostVS.vertexByteStride;
// ref passes to model
m_ModelVSOut->buffers.push_back(postvs);
}
m_PostGS = r->GetPostVSData(m_Config.curInstance, m_Config.curView, MeshDataStage::GSOut);
m_ModelGSOut->numRows = m_PostGS.numIndices;
m_ModelGSOut->unclampedNumRows = 0;
m_ModelGSOut->baseVertex = m_PostGS.baseVertex;
m_ModelGSOut->displayBaseVertex = m_ModelVSIn->baseVertex;
indices = NULL;
m_ModelGSOut->indices = NULL;
if(m_PostGS.vertexResourceId != ResourceId())
{
BufferData *postgs = new BufferData;
bytebuf bufdata = r->GetBufferData(m_PostGS.vertexResourceId, m_PostGS.vertexByteOffset, 0);
postgs->data = new byte[bufdata.size()];
memcpy(postgs->data, bufdata.data(), bufdata.size());
postgs->end = postgs->data + bufdata.size();
postgs->stride = m_PostGS.vertexByteStride;
// ref passes to model
m_ModelGSOut->buffers.push_back(postgs);
}
if(!draw)
return;
uint32_t eventId = draw->eventId;
bool calcNeeded = false;
{
QMutexLocker autolock(&m_BBoxLock);
calcNeeded = !m_BBoxes.contains(eventId);
}
if(!calcNeeded)
{
resetArcball();
return;
}
{
QMutexLocker autolock(&m_BBoxLock);
m_BBoxes.insert(eventId, BBoxData());
}
CalcBoundingBoxData *bbox = new CalcBoundingBoxData;
BufferItemModel *models[] = {m_ModelVSIn, m_ModelVSOut, m_ModelGSOut};
bbox->inst = m_ModelVSIn->curInstance;
bbox->eventId = eventId;
for(size_t i = 0; i < ARRAY_COUNT(bbox->input); i++)
{
bbox->input[i].elements = models[i]->columns;
bbox->input[i].buffers = models[i]->buffers;
bbox->input[i].indices = models[i]->indices;
bbox->input[i].baseVertex = models[i]->baseVertex;
bbox->input[i].count = models[i]->numRows;
// add ref all this buffer data
if(bbox->input[i].indices)
bbox->input[i].indices->ref();
for(int j = 0; j < bbox->input[i].buffers.count(); j++)
if(bbox->input[i].buffers[j])
bbox->input[i].buffers[j]->ref();
}
// fire up a thread to calculate the bounding box
LambdaThread *thread = new LambdaThread([this, bbox] {
calcBoundingData(*bbox);
GUIInvoke::call(this, [this, bbox]() { updateBoundingBox(*bbox); });
});
thread->selfDelete(true);
thread->start();
// give the thread a few ms to finish, so we don't get a tiny flicker on small/fast meshes
thread->wait(10);
}
void BufferViewer::calcBoundingData(CalcBoundingBoxData &bbox)
{
for(size_t stage = 0; stage < ARRAY_COUNT(bbox.input); stage++)
{
const CalcBoundingBoxData::StageData &s = bbox.input[stage];
QList<FloatVector> &minOutputList = bbox.output.bounds[stage].Min;
QList<FloatVector> &maxOutputList = bbox.output.bounds[stage].Max;
minOutputList.reserve(s.elements.count());
maxOutputList.reserve(s.elements.count());
for(int i = 0; i < s.elements.count(); i++)
{
minOutputList.push_back(FloatVector(FLT_MAX, FLT_MAX, FLT_MAX, FLT_MAX));
maxOutputList.push_back(FloatVector(-FLT_MAX, -FLT_MAX, -FLT_MAX, -FLT_MAX));
}
QVector<CachedElData> cache;
CacheDataForIteration(cache, s.elements, s.buffers, bbox.inst);
// possible optimisation here if this shows up as a hot spot - sort and unique the indices and
// iterate in ascending order, to be more cache friendly
for(uint32_t row = 0; row < s.count; row++)
{
uint32_t idx = row;
if(s.indices && s.indices->data)
{
idx = CalcIndex(s.indices, row, s.baseVertex);
if(idx == ~0U)
continue;
}
for(int col = 0; col < s.elements.count(); col++)
{
const CachedElData &d = cache[col];
const FormatElement *el = d.el;
float *minOut = (float *)&minOutputList[col];
float *maxOut = (float *)&maxOutputList[col];
if(d.data)
{
const byte *bytes = d.data;
if(!el->perinstance)
bytes += d.stride * idx;
QVariantList list = el->GetVariants(bytes, d.end);
for(int comp = 0; comp < list.count(); comp++)
{
const QVariant &v = list[comp];
QMetaType::Type vt = GetVariantMetatype(v);
float fval = 0.0f;
if(vt == QMetaType::Double)
fval = (float)v.toDouble();
else if(vt == QMetaType::Float)
fval = v.toFloat();
else if(vt == QMetaType::UInt || vt == QMetaType::UShort || vt == QMetaType::UChar)
fval = (float)v.toUInt();
else if(vt == QMetaType::Int || vt == QMetaType::Short || vt == QMetaType::SChar)
fval = (float)v.toInt();
else
continue;
if(qIsFinite(fval))
{
minOut[comp] = qMin(minOut[comp], fval);
maxOut[comp] = qMax(maxOut[comp], fval);
}
}
}
}
}
}
}
void BufferViewer::updateBoundingBox(const CalcBoundingBoxData &bbox)
{
{
QMutexLocker autolock(&m_BBoxLock);
m_BBoxes[bbox.eventId] = bbox.output;
}
if(m_Ctx.CurEvent() == bbox.eventId)
UpdateMeshConfig();
resetArcball();
for(size_t i = 0; i < ARRAY_COUNT(bbox.input); i++)
{
if(bbox.input[i].indices)
bbox.input[i].indices->deref();
for(int j = 0; j < bbox.input[i].buffers.count(); j++)
if(bbox.input[i].buffers[j])
bbox.input[i].buffers[j]->ref();
}
delete &bbox;
}
void BufferViewer::resetArcball()
{
BBoxData bbox;
{
QMutexLocker autolock(&m_BBoxLock);
if(m_BBoxes.contains(m_Ctx.CurEvent()))
bbox = m_BBoxes[m_Ctx.CurEvent()];
}
BufferItemModel *model = currentBufferModel();
int stage = currentStageIndex();
if(model)
{
int posEl = model->posColumn();
if(posEl >= 0 && posEl < model->columns.count() && posEl < bbox.bounds[stage].Min.count())
{
FloatVector diag;
diag.x = bbox.bounds[stage].Max[posEl].x - bbox.bounds[stage].Min[posEl].x;
diag.y = bbox.bounds[stage].Max[posEl].y - bbox.bounds[stage].Min[posEl].y;
diag.z = bbox.bounds[stage].Max[posEl].z - bbox.bounds[stage].Min[posEl].z;
float len = qSqrt(diag.x * diag.x + diag.y * diag.y + diag.z * diag.z);
if(diag.x >= 0.0f && diag.y >= 0.0f && diag.z >= 0.0f && len >= 1.0e-6f && len <= 1.0e+10f)
{
FloatVector mid;
mid.x = bbox.bounds[stage].Min[posEl].x + diag.x * 0.5f;
mid.y = bbox.bounds[stage].Min[posEl].y + diag.y * 0.5f;
mid.z = bbox.bounds[stage].Min[posEl].z + diag.z * 0.5f;
m_Arcball->Reset(mid, len * 0.7f);
GUIInvoke::call(this, [this, len]() { ui->camSpeed->setValue(len / 200.0f); });
}
}
}
INVOKE_MEMFN(RT_UpdateAndDisplay);
}
void BufferViewer::guessPositionColumn(BufferItemModel *model)
{
int posEl = -1;
if(!model->columns.empty())
{
// prioritise system value over general "POSITION" string matching
for(int i = 0; i < model->columns.count(); i++)
{
const FormatElement &el = model->columns[i];
if(el.systemValue == ShaderBuiltin::Position)
{
posEl = i;
break;
}
}
// look for an exact match
for(int i = 0; posEl == -1 && i < model->columns.count(); i++)
{
const FormatElement &el = model->columns[i];
if(el.name.compare(lit("POSITION"), Qt::CaseInsensitive) == 0 ||
el.name.compare(lit("POSITION0"), Qt::CaseInsensitive) == 0 ||
el.name.compare(lit("POS"), Qt::CaseInsensitive) == 0 ||
el.name.compare(lit("POS0"), Qt::CaseInsensitive) == 0)
{
posEl = i;
break;
}
}
// try anything containing position
for(int i = 0; posEl == -1 && i < model->columns.count(); i++)
{
const FormatElement &el = model->columns[i];
if(el.name.contains(lit("POSITION"), Qt::CaseInsensitive))
{
posEl = i;
break;
}
}
// OK last resort, just look for 'pos'
for(int i = 0; posEl == -1 && i < model->columns.count(); i++)
{
const FormatElement &el = model->columns[i];
if(el.name.contains(lit("POS"), Qt::CaseInsensitive))
{
posEl = i;
break;
}
}
// if we still have absolutely nothing, just use the first available element
if(posEl == -1)
{
posEl = 0;
}
}
model->setPosColumn(posEl);
}
void BufferViewer::guessSecondaryColumn(BufferItemModel *model)
{
int secondEl = -1;
if(!model->columns.empty())
{
// prioritise TEXCOORD over general COLOR
for(int i = 0; i < model->columns.count(); i++)
{
const FormatElement &el = model->columns[i];
if(el.name.compare(lit("TEXCOORD"), Qt::CaseInsensitive) == 0 ||
el.name.compare(lit("TEXCOORD0"), Qt::CaseInsensitive) == 0 ||
el.name.compare(lit("TEX"), Qt::CaseInsensitive) == 0 ||
el.name.compare(lit("TEX0"), Qt::CaseInsensitive) == 0 ||
el.name.compare(lit("UV"), Qt::CaseInsensitive) == 0 ||
el.name.compare(lit("UV0"), Qt::CaseInsensitive) == 0)
{
secondEl = i;
break;
}
}
for(int i = 0; secondEl == -1 && i < model->columns.count(); i++)
{
const FormatElement &el = model->columns[i];
if(el.name.compare(lit("COLOR"), Qt::CaseInsensitive) == 0 ||
el.name.compare(lit("COLOR0"), Qt::CaseInsensitive) == 0 ||
el.name.compare(lit("COL"), Qt::CaseInsensitive) == 0 ||
el.name.compare(lit("COL0"), Qt::CaseInsensitive) == 0)
{
secondEl = i;
break;
}
}
}
model->setSecondaryColumn(secondEl, m_Config.solidShadeMode == SolidShade::Secondary, false);
}
void BufferViewer::updatePreviewColumns()
{
if(!m_MeshView)
return;
rdcarray<BoundVBuffer> vbs = m_Ctx.CurPipelineState().GetVBuffers();
const DrawcallDescription *draw = m_Ctx.CurDrawcall();
if(draw)
{
m_VSInPosition = MeshFormat();
m_VSInSecondary = MeshFormat();
if(!m_ModelVSIn->columns.empty())
{
int elIdx = m_ModelVSIn->posColumn();
if(elIdx < 0 || elIdx >= m_ModelVSIn->columns.count())
elIdx = 0;
if(m_ModelVSIn->unclampedNumRows > 0)
m_VSInPosition.numIndices = m_ModelVSIn->numRows;
else
m_VSInPosition.numIndices = draw->numIndices;
m_VSInPosition.topology = draw->topology;
m_VSInPosition.indexByteStride = draw->indexByteWidth;
m_VSInPosition.baseVertex = draw->baseVertex;
BoundVBuffer ib = m_Ctx.CurPipelineState().GetIBuffer();
m_VSInPosition.indexResourceId = ib.resourceId;
m_VSInPosition.indexByteOffset = ib.byteOffset + draw->indexOffset * draw->indexByteWidth;
if((draw->flags & DrawFlags::Indexed) && m_VSInPosition.indexByteStride == 0)
m_VSInPosition.indexByteStride = 4U;
{
const FormatElement &el = m_ModelVSIn->columns[elIdx];
m_VSInPosition.instanced = el.perinstance;
m_VSInPosition.instStepRate = el.instancerate;
if(el.buffer < vbs.count())
{
m_VSInPosition.vertexResourceId = vbs[el.buffer].resourceId;
m_VSInPosition.vertexByteStride = vbs[el.buffer].byteStride;
m_VSInPosition.vertexByteOffset = vbs[el.buffer].byteOffset + el.offset +
draw->vertexOffset * m_VSInPosition.vertexByteStride;
}
else
{
m_VSInPosition.vertexResourceId = ResourceId();
m_VSInPosition.vertexByteStride = 0;
m_VSInPosition.vertexByteOffset = 0;
}
m_VSInPosition.format = el.format;
}
elIdx = m_ModelVSIn->secondaryColumn();
if(elIdx >= 0 && elIdx < m_ModelVSIn->columns.count())
{
const FormatElement &el = m_ModelVSIn->columns[elIdx];
m_VSInSecondary.instanced = el.perinstance;
m_VSInSecondary.instStepRate = el.instancerate;
if(el.buffer < vbs.count())
{
m_VSInSecondary.vertexResourceId = vbs[el.buffer].resourceId;
m_VSInSecondary.vertexByteStride = vbs[el.buffer].byteStride;
m_VSInSecondary.vertexByteOffset = vbs[el.buffer].byteOffset + el.offset +
draw->vertexOffset * m_VSInSecondary.vertexByteStride;
}
else
{
m_VSInSecondary.vertexResourceId = ResourceId();
m_VSInSecondary.vertexByteStride = 0;
m_VSInSecondary.vertexByteOffset = 0;
}
m_VSInSecondary.format = el.format;
m_VSInSecondary.showAlpha = m_ModelVSIn->secondaryAlpha();
}
}
m_PostVSPosition = MeshFormat();
m_PostVSSecondary = MeshFormat();
if(!m_ModelVSOut->columns.empty())
{
int elIdx = m_ModelVSOut->posColumn();
if(elIdx < 0 || elIdx >= m_ModelVSOut->columns.count())
elIdx = 0;
m_PostVSPosition = m_PostVS;
m_PostVSPosition.vertexByteOffset += m_ModelVSOut->columns[elIdx].offset;
elIdx = m_ModelVSOut->secondaryColumn();
if(elIdx >= 0 && elIdx < m_ModelVSOut->columns.count())
{
m_PostVSSecondary = m_PostVS;
m_PostVSSecondary.vertexByteOffset += m_ModelVSOut->columns[elIdx].offset;
m_PostVSSecondary.showAlpha = m_ModelVSOut->secondaryAlpha();
}
}
m_PostGSPosition = MeshFormat();
m_PostGSSecondary = MeshFormat();
if(!m_ModelGSOut->columns.empty())
{
int elIdx = m_ModelGSOut->posColumn();
if(elIdx < 0 || elIdx >= m_ModelGSOut->columns.count())
elIdx = 0;
m_PostGSPosition = m_PostGS;
m_PostGSPosition.vertexByteOffset += m_ModelGSOut->columns[elIdx].offset;
elIdx = m_ModelGSOut->secondaryColumn();
if(elIdx >= 0 && elIdx < m_ModelGSOut->columns.count())
{
m_PostGSSecondary = m_PostGS;
m_PostGSSecondary.vertexByteOffset += m_ModelGSOut->columns[elIdx].offset;
m_PostGSSecondary.showAlpha = m_ModelGSOut->secondaryAlpha();
}
}
m_PostGSPosition.indexByteStride = 0;
if(!(draw->flags & DrawFlags::Indexed))
m_PostVSPosition.indexByteStride = m_VSInPosition.indexByteStride = 0;
m_PostGSPosition.unproject = true;
m_PostVSPosition.unproject = !m_Ctx.CurPipelineState().IsTessellationEnabled();
}
else
{
m_VSInPosition = MeshFormat();
m_VSInSecondary = MeshFormat();
m_PostVSPosition = MeshFormat();
m_PostVSSecondary = MeshFormat();
m_PostGSPosition = MeshFormat();
m_PostGSSecondary = MeshFormat();
}
UpdateMeshConfig();
}
void BufferViewer::configureMeshColumns()
{
const DrawcallDescription *draw = m_Ctx.CurDrawcall();
rdcarray<VertexInputAttribute> vinputs = m_Ctx.CurPipelineState().GetVertexInputs();
m_ModelVSIn->columns.reserve(vinputs.count());
m_ModelVSIn->columns.clear();
m_ModelVSIn->genericsEnabled.resize(vinputs.count());
m_ModelVSIn->generics.resize(vinputs.count());
for(const VertexInputAttribute &a : vinputs)
{
if(!a.used)
continue;
FormatElement f(a.name, a.vertexBuffer, a.byteOffset, a.perInstance, a.instanceRate,
false, // row major matrix
1, // matrix dimension
a.format, false, false);
m_ModelVSIn->genericsEnabled[m_ModelVSIn->columns.size()] = false;
if(a.genericEnabled)
{
m_ModelVSIn->genericsEnabled[m_ModelVSIn->columns.size()] = true;
m_ModelVSIn->generics[m_ModelVSIn->columns.size()] = a.genericValue;
}
m_ModelVSIn->columns.push_back(f);
}
if(draw == NULL)
{
m_ModelVSIn->numRows = 0;
m_ModelVSIn->unclampedNumRows = 0;
}
else
{
m_ModelVSIn->numRows = draw->numIndices;
m_ModelVSIn->unclampedNumRows = 0;
// calculate an upper bound on the valid number of rows just in case it's an invalid value (e.g.
// 0xdeadbeef) and we want to clamp.
uint32_t numRowsUpperBound = 0;
if(draw->flags & DrawFlags::Indexed)
{
// In an indexed draw we clamp to however many indices are available in the index buffer
BoundVBuffer ib = m_Ctx.CurPipelineState().GetIBuffer();
uint32_t bytesAvailable = 0;
BufferDescription *buf = m_Ctx.GetBuffer(ib.resourceId);
if(buf)
bytesAvailable = buf->length - ib.byteOffset - draw->indexOffset * draw->indexByteWidth;
// drawing more than this many indices will read off the end of the index buffer - which while
// technically not invalid is certainly not intended, so serves as a good 'upper bound'
numRowsUpperBound = bytesAvailable / draw->indexByteWidth;
}
else
{
// for a non-indexed draw, we take the largest vertex buffer
rdcarray<BoundVBuffer> VBs = m_Ctx.CurPipelineState().GetVBuffers();
for(const BoundVBuffer &vb : VBs)
{
if(vb.byteStride == 0)
continue;
BufferDescription *buf = m_Ctx.GetBuffer(vb.resourceId);
if(buf)
{
numRowsUpperBound =
qMax(numRowsUpperBound, uint32_t(buf->length - vb.byteOffset) / vb.byteStride);
}
}
// if there are no vertex buffers we can't clamp.
if(numRowsUpperBound == 0)
numRowsUpperBound = ~0U;
}
// if we have significantly clamped, then set the unclamped number of rows and clamp.
if(numRowsUpperBound + 100 < m_ModelVSIn->numRows)
{
m_ModelVSIn->unclampedNumRows = m_ModelVSIn->numRows;
m_ModelVSIn->numRows = numRowsUpperBound + 100;
m_VSInPosition.numIndices = m_ModelVSIn->numRows;
}
}
Viewport vp = m_Ctx.CurPipelineState().GetViewport(0);
float vpWidth = qAbs(vp.width);
float vpHeight = qAbs(vp.height);
m_Config.fov = ui->fovGuess->value();
m_Config.aspect = (vpWidth > 0.0f && vpHeight > 0.0f) ? (vpWidth / vpHeight) : 1.0f;
m_Config.highlightVert = 0;
if(ui->aspectGuess->value() > 0.0)
m_Config.aspect = ui->aspectGuess->value();
if(ui->nearGuess->value() > 0.0)
m_PostVS.nearPlane = m_PostGS.nearPlane = ui->nearGuess->value();
if(ui->farGuess->value() > 0.0)
m_PostVS.farPlane = m_PostGS.farPlane = ui->farGuess->value();
const ShaderReflection *vs = m_Ctx.CurPipelineState().GetShaderReflection(ShaderStage::Vertex);
m_ModelVSOut->columns.clear();
if(draw && vs)
{
m_ModelVSOut->columns.reserve(vs->outputSignature.count());
int i = 0, posidx = -1;
for(const SigParameter &sig : vs->outputSignature)
{
FormatElement f;
f.buffer = 0;
f.name = !sig.varName.isEmpty() ? sig.varName : sig.semanticIdxName;
f.format.compByteWidth = sizeof(float);
f.format.compCount = sig.compCount;
f.format.compType = sig.compType;
f.format.type = ResourceFormatType::Regular;
f.perinstance = false;
f.instancerate = 1;
f.rowmajor = false;
f.matrixdim = 1;
f.systemValue = sig.systemValue;
if(f.systemValue == ShaderBuiltin::Position)
posidx = i;
m_ModelVSOut->columns.push_back(f);
i++;
}
// shift position attribute up to first, keeping order otherwise
// the same
if(posidx > 0)
{
FormatElement pos = m_ModelVSOut->columns[posidx];
m_ModelVSOut->columns.insert(0, m_ModelVSOut->columns.takeAt(posidx));
}
i = 0;
uint32_t offset = 0;
for(const FormatElement &sig : m_ModelVSOut->columns)
{
uint numComps = sig.format.compCount;
uint elemSize = sig.format.compType == CompType::Double ? 8U : 4U;
if(m_Ctx.CurPipelineState().HasAlignedPostVSData())
{
if(numComps == 2)
offset = AlignUp(offset, 2U * elemSize);
else if(numComps > 2)
offset = AlignUp(offset, 4U * elemSize);
}
m_ModelVSOut->columns[i++].offset = offset;
offset += numComps * elemSize;
}
}
m_ModelGSOut->columns.clear();
if(draw)
{
const ShaderReflection *last =
m_Ctx.CurPipelineState().GetShaderReflection(ShaderStage::Geometry);
if(last == NULL)
last = m_Ctx.CurPipelineState().GetShaderReflection(ShaderStage::Domain);
if(last)
{
m_ModelGSOut->columns.reserve(last->outputSignature.count());
int i = 0, posidx = -1;
for(const SigParameter &sig : last->outputSignature)
{
FormatElement f;
f.buffer = 0;
f.name = !sig.varName.isEmpty() ? sig.varName : sig.semanticIdxName;
f.format.compByteWidth = sizeof(float);
f.format.compCount = sig.compCount;
f.format.compType = sig.compType;
f.format.type = ResourceFormatType::Regular;
f.perinstance = false;
f.instancerate = 1;
f.rowmajor = false;
f.matrixdim = 1;
f.systemValue = sig.systemValue;
if(f.systemValue == ShaderBuiltin::Position)
posidx = i;
m_ModelGSOut->columns.push_back(f);
i++;
}
// shift position attribute up to first, keeping order otherwise
// the same
if(posidx > 0)
{
FormatElement pos = m_ModelGSOut->columns[posidx];
m_ModelGSOut->columns.insert(0, m_ModelGSOut->columns.takeAt(posidx));
}
i = 0;
uint32_t offset = 0;
for(const FormatElement &sig : m_ModelGSOut->columns)
{
uint numComps = sig.format.compCount;
uint elemSize = sig.format.compType == CompType::Double ? 8U : 4U;
if(m_Ctx.CurPipelineState().HasAlignedPostVSData())
{
if(numComps == 2)
offset = AlignUp(offset, 2U * elemSize);
else if(numComps > 2)
offset = AlignUp(offset, 4U * elemSize);
}
m_ModelGSOut->columns[i++].offset = offset;
offset += numComps * elemSize;
}
}
}
}
void BufferViewer::configureDrawRange()
{
const DrawcallDescription *draw = m_Ctx.CurDrawcall();
int curIndex = ui->drawRange->currentIndex();
bool instanced = true;
// don't check the flags, check if there are actually multiple instances
if(m_Ctx.IsCaptureLoaded())
instanced = draw && draw->numInstances > 1;
ui->drawRange->blockSignals(true);
ui->drawRange->clear();
if(instanced)
ui->drawRange->addItems(
{tr("This instance"), tr("Previous instances"), tr("All instances"), tr("Whole pass")});
else
ui->drawRange->addItems({tr("This draw"), tr("Previous instances (N/A)"),
tr("All instances (N/A)"), tr("Whole pass")});
// preserve the previously selected index
ui->drawRange->setCurrentIndex(qMax(0, curIndex));
ui->drawRange->blockSignals(false);
ui->drawRange->adjustSize();
ui->drawRange->setEnabled(m_CurStage != MeshDataStage::VSIn);
curIndex = ui->drawRange->currentIndex();
m_Config.showPrevInstances = (curIndex >= 1);
m_Config.showAllInstances = (curIndex >= 2);
m_Config.showWholePass = (curIndex >= 3);
}
void BufferViewer::ApplyRowAndColumnDims(int numColumns, RDTableView *view)
{
int start = 0;
QList<int> widths;
// vertex/element
widths << m_IdxColWidth;
// mesh view only - index
if(m_MeshView)
widths << m_IdxColWidth;
for(int i = start; i < numColumns; i++)
widths << m_DataColWidth;
view->verticalHeader()->setDefaultSectionSize(m_DataRowHeight);
view->setColumnWidths(widths);
}
void BufferViewer::UpdateMeshConfig()
{
BBoxData bbox;
uint32_t eventId = m_Ctx.CurEvent();
{
QMutexLocker autolocker(&m_BBoxLock);
if(m_BBoxes.contains(eventId))
bbox = m_BBoxes[eventId];
}
m_Config.type = m_CurStage;
switch(m_CurStage)
{
case MeshDataStage::VSIn:
m_Config.position = m_VSInPosition;
m_Config.second = m_VSInSecondary;
break;
case MeshDataStage::VSOut:
m_Config.position = m_PostVSPosition;
m_Config.second = m_PostVSSecondary;
break;
case MeshDataStage::GSOut:
m_Config.position = m_PostGSPosition;
m_Config.second = m_PostGSSecondary;
break;
default: break;
}
BufferItemModel *model = currentBufferModel();
int stage = currentStageIndex();
m_Config.showBBox = false;
bool nonRasterizedOutput = false;
if(stage == 0)
nonRasterizedOutput = true;
else if(stage == 1 && m_Ctx.CurPipelineState().IsTessellationEnabled())
nonRasterizedOutput = true;
if(model && nonRasterizedOutput)
{
int posEl = model->posColumn();
if(posEl >= 0 && posEl < model->columns.count() && posEl < bbox.bounds[stage].Min.count())
{
m_Config.minBounds = bbox.bounds[stage].Min[posEl];
m_Config.maxBounds = bbox.bounds[stage].Max[posEl];
m_Config.showBBox = true;
}
}
}
void BufferViewer::render_mouseMove(QMouseEvent *e)
{
if(!m_Ctx.IsCaptureLoaded())
return;
if(m_CurrentCamera)
m_CurrentCamera->MouseMove(e);
if(e->buttons() & Qt::RightButton)
render_clicked(e);
// display if any mouse buttons are held while moving.
if(e->buttons() != Qt::NoButton)
{
INVOKE_MEMFN(RT_UpdateAndDisplay);
}
}
void BufferViewer::render_clicked(QMouseEvent *e)
{
if(!m_Ctx.IsCaptureLoaded())
return;
QPoint curpos = e->pos();
curpos *= ui->render->devicePixelRatioF();
if((e->buttons() & Qt::RightButton) && m_Output)
{
m_Ctx.Replay().AsyncInvoke(lit("PickVertex"), [this, curpos](IReplayController *r) {
uint32_t instanceSelected = 0;
uint32_t vertSelected = 0;
std::tie(vertSelected, instanceSelected) =
m_Output->PickVertex(m_Ctx.CurEvent(), (uint32_t)curpos.x(), (uint32_t)curpos.y());
if(vertSelected != ~0U)
{
GUIInvoke::call(this, [this, vertSelected, instanceSelected] {
int row = (int)vertSelected;
if(instanceSelected != m_Config.curInstance)
ui->instance->setValue(instanceSelected);
BufferItemModel *model = currentBufferModel();
if(model && row >= 0 && row < model->rowCount())
ScrollToRow(model, row);
SyncViews(currentTable(), true, true);
});
}
});
}
if(m_CurrentCamera)
m_CurrentCamera->MouseClick(e);
ui->render->setFocus();
INVOKE_MEMFN(RT_UpdateAndDisplay);
}
void BufferViewer::ScrollToRow(BufferItemModel *model, int row)
{
int hs = model->view->horizontalScrollBar()->value();
model->view->scrollTo(model->index(row, 0), QAbstractItemView::PositionAtTop);
model->view->clearSelection();
model->view->selectRow(row);
model->view->horizontalScrollBar()->setValue(hs);
}
void BufferViewer::ViewBuffer(uint64_t byteOffset, uint64_t byteSize, ResourceId id,
const rdcstr &format)
{
if(!m_Ctx.IsCaptureLoaded())
return;
m_IsBuffer = true;
m_ByteOffset = byteOffset;
m_ByteSize = byteSize;
m_BufferID = id;
updateWindowTitle();
BufferDescription *buf = m_Ctx.GetBuffer(id);
if(buf)
m_ObjectByteSize = buf->length;
processFormat(format);
}
void BufferViewer::ViewTexture(uint32_t arrayIdx, uint32_t mip, ResourceId id, const rdcstr &format)
{
if(!m_Ctx.IsCaptureLoaded())
return;
m_IsBuffer = false;
m_TexArrayIdx = arrayIdx;
m_TexMip = mip;
m_BufferID = id;
updateWindowTitle();
TextureDescription *tex = m_Ctx.GetTexture(id);
if(tex)
m_ObjectByteSize = tex->byteSize;
processFormat(format);
}
void BufferViewer::updateWindowTitle()
{
if(!m_MeshView)
setWindowTitle(m_Ctx.GetResourceName(m_BufferID) + lit(" - Contents"));
}
void BufferViewer::on_resourceDetails_clicked()
{
if(!m_Ctx.HasResourceInspector())
m_Ctx.ShowResourceInspector();
m_Ctx.GetResourceInspector()->Inspect(m_BufferID);
ToolWindowManager::raiseToolWindow(m_Ctx.GetResourceInspector()->Widget());
}
void BufferViewer::render_mouseWheel(QWheelEvent *e)
{
if(m_CurrentCamera)
m_CurrentCamera->MouseWheel(e);
INVOKE_MEMFN(RT_UpdateAndDisplay);
}
void BufferViewer::render_keyPress(QKeyEvent *e)
{
m_CurrentCamera->KeyDown(e);
}
void BufferViewer::render_keyRelease(QKeyEvent *e)
{
m_CurrentCamera->KeyUp(e);
}
void BufferViewer::render_timer()
{
if(m_CurrentCamera && m_CurrentCamera->Update(ui->render->rect()))
INVOKE_MEMFN(RT_UpdateAndDisplay);
}
void BufferViewer::RT_UpdateAndDisplay(IReplayController *)
{
if(m_Output)
{
m_Config.cam = m_CurrentCamera->camera();
m_Output->SetMeshDisplay(m_Config);
}
GUIInvoke::call(this, [this]() { ui->render->update(); });
}
RDTableView *BufferViewer::tableForStage(MeshDataStage stage)
{
if(stage == MeshDataStage::VSIn)
return ui->vsinData;
else if(stage == MeshDataStage::VSOut)
return ui->vsoutData;
else if(stage == MeshDataStage::GSOut)
return ui->gsoutData;
return NULL;
}
BufferItemModel *BufferViewer::modelForStage(MeshDataStage stage)
{
if(stage == MeshDataStage::VSIn)
return m_ModelVSIn;
else if(stage == MeshDataStage::VSOut)
return m_ModelVSOut;
else if(stage == MeshDataStage::GSOut)
return m_ModelGSOut;
return NULL;
}
bool BufferViewer::isCurrentRasterOut()
{
if(m_CurStage == MeshDataStage::VSIn)
{
return false;
}
else if(m_CurStage == MeshDataStage::VSOut)
{
if(m_Ctx.IsCaptureLoaded() && m_Ctx.CurPipelineState().IsTessellationEnabled())
return false;
return true;
}
else if(m_CurStage == MeshDataStage::GSOut)
{
return true;
}
return false;
}
int BufferViewer::currentStageIndex()
{
if(m_CurStage == MeshDataStage::VSIn)
return 0;
else if(m_CurStage == MeshDataStage::VSOut)
return 1;
else if(m_CurStage == MeshDataStage::GSOut)
return 2;
return 0;
}
void BufferViewer::Reset()
{
m_Output = NULL;
configureDrawRange();
ClearModels();
ui->vsinData->setColumnWidths({40, 40});
ui->vsoutData->setColumnWidths({40, 40});
ui->gsoutData->setColumnWidths({40, 40});
m_BBoxes.clear();
ICaptureContext *ctx = &m_Ctx;
// while a capture is loaded, pass NULL into the widget
if(!m_Ctx.IsCaptureLoaded())
ctx = NULL;
{
CustomPaintWidget *render = new CustomPaintWidget(ctx, this);
render->setObjectName(ui->render->objectName());
render->setSizePolicy(ui->render->sizePolicy());
delete ui->render;
ui->render = render;
ui->renderContainerGridLayout->addWidget(ui->render, 1, 1, 1, 1);
}
QObject::connect(ui->render, &CustomPaintWidget::mouseMove, this, &BufferViewer::render_mouseMove);
QObject::connect(ui->render, &CustomPaintWidget::clicked, this, &BufferViewer::render_clicked);
QObject::connect(ui->render, &CustomPaintWidget::keyPress, this, &BufferViewer::render_keyPress);
QObject::connect(ui->render, &CustomPaintWidget::keyRelease, this,
&BufferViewer::render_keyRelease);
QObject::connect(ui->render, &CustomPaintWidget::mouseWheel, this,
&BufferViewer::render_mouseWheel);
updateCheckerboardColours();
}
void BufferViewer::updateCheckerboardColours()
{
ui->render->setColours(Formatter::DarkCheckerColor(), Formatter::LightCheckerColor());
}
void BufferViewer::ClearModels()
{
BufferItemModel *models[] = {m_ModelVSIn, m_ModelVSOut, m_ModelGSOut};
for(BufferItemModel *m : models)
{
if(!m)
continue;
m->beginReset();
if(m->indices)
m->indices->deref();
m->indices = NULL;
for(auto vb : m->buffers)
vb->deref();
m->buffers.clear();
m->columns.clear();
m->generics.clear();
m->genericsEnabled.clear();
m->numRows = 0;
m->unclampedNumRows = 0;
m->endReset();
}
}
void BufferViewer::CalcColumnWidth(int maxNumRows)
{
m_ModelVSIn->beginReset();
ResourceFormat floatFmt;
floatFmt.compByteWidth = 4;
floatFmt.compType = CompType::Float;
floatFmt.compCount = 1;
ResourceFormat intFmt;
intFmt.compByteWidth = 4;
intFmt.compType = CompType::UInt;
intFmt.compCount = 1;
QString headerText = lit("ColumnSizeTest");
m_ModelVSIn->columns.clear();
m_ModelVSIn->columns.push_back(
FormatElement(headerText, 0, 0, false, 1, false, maxNumRows, floatFmt, false, false));
m_ModelVSIn->columns.push_back(
FormatElement(headerText, 0, 4, false, 1, false, 1, floatFmt, false, false));
m_ModelVSIn->columns.push_back(
FormatElement(headerText, 0, 8, false, 1, false, 1, floatFmt, false, false));
m_ModelVSIn->columns.push_back(
FormatElement(headerText, 0, 12, false, 1, false, 1, intFmt, true, false));
m_ModelVSIn->columns.push_back(
FormatElement(headerText, 0, 16, false, 1, false, 1, intFmt, false, false));
m_ModelVSIn->numRows = 2;
m_ModelVSIn->unclampedNumRows = 0;
m_ModelVSIn->baseVertex = 0;
if(m_ModelVSIn->indices)
m_ModelVSIn->indices->deref();
m_ModelVSIn->indices = new BufferData;
m_ModelVSIn->indices->stride = sizeof(uint32_t);
m_ModelVSIn->indices->data = new byte[sizeof(uint32_t) * 2];
m_ModelVSIn->indices->end = m_ModelVSIn->indices->data + sizeof(uint32_t) * 2;
uint32_t *indices = (uint32_t *)m_ModelVSIn->indices->data;
indices[0] = 0;
indices[1] = 1000000;
m_ModelVSIn->buffers.clear();
struct TestData
{
float f[4];
uint32_t ui[3];
};
BufferData *bufdata = new BufferData;
bufdata->stride = sizeof(TestData);
bufdata->data = new byte[sizeof(TestData)];
bufdata->end = bufdata->data + sizeof(TestData);
m_ModelVSIn->buffers.push_back(bufdata);
TestData *test = (TestData *)bufdata->data;
test->f[0] = 1.0f;
test->f[1] = 1.2345e-20f;
test->f[2] = 123456.7890123456789f;
test->f[3] = -1.0f;
test->ui[1] = 0x12345678;
test->ui[2] = 0xffffffff;
m_ModelVSIn->endReset();
// measure this data so we can use this as column widths
ui->vsinData->resizeColumnsToContents();
// index/element column
m_IdxColWidth = ui->vsinData->columnWidth(0);
int col = 1;
if(m_MeshView)
col = 2;
m_DataColWidth = 10;
for(int c = 0; c < 5; c++)
{
int colWidth = ui->vsinData->columnWidth(col + c);
m_DataColWidth = qMax(m_DataColWidth, colWidth);
}
ui->vsinData->resizeRowsToContents();
m_DataRowHeight = ui->vsinData->rowHeight(0);
}
void BufferViewer::data_selected(const QItemSelection &selected, const QItemSelection &deselected)
{
QObject *sender = QObject::sender();
RDTableView *view = qobject_cast<RDTableView *>(sender);
if(view == NULL)
view = qobject_cast<RDTableView *>(sender->parent());
if(view == NULL)
return;
m_CurView = view;
if(selected.count() > 0)
{
UpdateHighlightVerts();
SyncViews(view, true, false);
INVOKE_MEMFN(RT_UpdateAndDisplay);
}
}
void BufferViewer::data_scrolled(int scrollvalue)
{
QObject *sender = QObject::sender();
RDTableView *view = qobject_cast<RDTableView *>(sender);
while(sender != NULL && view == NULL)
{
sender = sender->parent();
view = qobject_cast<RDTableView *>(sender);
}
if(view == NULL)
return;
SyncViews(view, false, true);
}
void BufferViewer::camGuess_changed(double value)
{
m_Config.ortho = (ui->matrixType->currentIndex() == 1);
m_Config.fov = ui->fovGuess->value();
m_Config.aspect = 1.0f;
// take a guess for the aspect ratio, for if the user hasn't overridden it
Viewport vp = m_Ctx.CurPipelineState().GetViewport(0);
m_Config.aspect = (vp.width > 0.0f && vp.height > 0.0f) ? (vp.width / vp.height) : 1.0f;
if(ui->aspectGuess->value() > 0.0)
m_Config.aspect = ui->aspectGuess->value();
// use estimates from post vs data (calculated from vertex position data) if the user
// hasn't overridden the values
m_Config.position.nearPlane = 0.1f;
if(m_CurStage == MeshDataStage::VSOut)
m_Config.position.nearPlane = m_PostVS.nearPlane;
else if(m_CurStage == MeshDataStage::GSOut)
m_Config.position.nearPlane = m_PostGS.nearPlane;
if(ui->nearGuess->value() > 0.0)
m_Config.position.nearPlane = ui->nearGuess->value();
m_Config.position.farPlane = 100.0f;
if(m_CurStage == MeshDataStage::VSOut)
m_Config.position.farPlane = m_PostVS.farPlane;
else if(m_CurStage == MeshDataStage::GSOut)
m_Config.position.farPlane = m_PostGS.farPlane;
if(ui->nearGuess->value() > 0.0)
m_Config.position.farPlane = ui->nearGuess->value();
if(ui->farGuess->value() > 0.0)
m_Config.position.nearPlane = ui->farGuess->value();
INVOKE_MEMFN(RT_UpdateAndDisplay);
}
void BufferViewer::processFormat(const QString &format)
{
QString errors;
Reset();
QList<FormatElement> cols = FormatElement::ParseFormatString(format, 0, true, errors);
int maxNumRows = 1;
for(const FormatElement &c : cols)
maxNumRows = qMax(maxNumRows, (int)c.matrixdim);
CalcColumnWidth(maxNumRows);
ClearModels();
m_Format = format;
ui->formatSpecifier->setFormat(format);
m_ModelVSIn->columns = cols;
uint32_t stride = 0;
for(const FormatElement &el : m_ModelVSIn->columns)
stride += el.byteSize();
stride = qMax(1U, stride);
ui->byteRangeStart->setSingleStep((int)stride);
ui->byteRangeLength->setSingleStep((int)stride);
ui->byteRangeStart->setMaximum((int)m_ObjectByteSize);
ui->byteRangeLength->setMaximum((int)m_ObjectByteSize);
ui->byteRangeStart->setValue((int)m_ByteOffset);
ui->byteRangeLength->setValue((int)m_ByteSize);
ui->formatSpecifier->setErrors(errors);
OnEventChanged(m_Ctx.CurEvent());
}
void BufferViewer::on_byteRangeStart_valueChanged(int value)
{
m_ByteOffset = value;
processFormat(m_Format);
}
void BufferViewer::on_byteRangeLength_valueChanged(int value)
{
m_ByteSize = value;
processFormat(m_Format);
}
void BufferViewer::exportData(const BufferExport ¶ms)
{
if(!m_Ctx.IsCaptureLoaded())
return;
if(!m_Ctx.CurDrawcall())
return;
if(!m_CurView)
return;
QString filter;
if(params.format == BufferExport::CSV)
filter = tr("CSV Files (*.csv)");
else if(params.format == BufferExport::RawBytes)
filter = tr("Binary Files (*.bin)");
QString filename = RDDialog::getSaveFileName(this, tr("Export buffer to bytes"), QString(),
tr("%1;;All files (*)").arg(filter));
if(filename.isEmpty())
return;
QFile *f = new QFile(filename);
if(!f->open(QIODevice::WriteOnly | QFile::Truncate))
{
delete f;
RDDialog::critical(this, tr("Error exporting file"),
tr("Couldn't open file '%1' for writing").arg(filename));
return;
}
if(m_MeshView)
{
ANALYTIC_SET(Export.MeshOutput, true);
}
else
{
ANALYTIC_SET(Export.RawBuffer, true);
}
BufferItemModel *model = (BufferItemModel *)m_CurView->model();
LambdaThread *exportThread = new LambdaThread([this, params, model, f]() {
if(params.format == BufferExport::RawBytes)
{
if(!m_MeshView)
{
// this is the simplest possible case, we just dump the contents of the first buffer, as
// it's tightly packed
f->write((const char *)model->buffers[0]->data,
int(model->buffers[0]->end - model->buffers[0]->data));
}
else
{
// cache column data for the inner loop
QVector<CachedElData> cache;
CacheDataForIteration(cache, model->columns, model->buffers, model->curInstance);
// go row by row, finding the start of the row and dumping out the elements using their
// offset and sizes
for(int i = 0; i < model->rowCount(); i++)
{
// manually calculate the index so that we get the real offset (not the displayed offset)
// in the case of vertex output.
uint32_t idx = i;
if(model->indices && model->indices->data)
{
idx = CalcIndex(model->indices, i, model->baseVertex);
// completely omit primitive restart indices
if(model->primRestart && idx == model->primRestart)
continue;
}
for(int col = 0; col < cache.count(); col++)
{
const CachedElData &d = cache[col];
const FormatElement *el = d.el;
if(d.data)
{
const char *bytes = (const char *)d.data;
if(!el->perinstance)
bytes += d.stride * idx;
if(bytes + d.byteSize <= (const char *)d.end)
{
f->write(bytes, d.byteSize);
continue;
}
}
// if we didn't continue above, something was wrong, so write nulls
f->write(d.nulls);
}
}
}
}
else if(params.format == BufferExport::CSV)
{
// this works identically no matter whether we're mesh view or what, we just iterate the
// elements and call the model's data()
QTextStream s(f);
for(int i = 0; i < model->columnCount(); i++)
{
s << model->headerData(i, Qt::Horizontal, Qt::DisplayRole).toString();
if(i + 1 < model->columnCount())
s << ", ";
}
s << "\n";
for(int row = 0; row < model->rowCount(); row++)
{
for(int col = 0; col < model->columnCount(); col++)
{
s << model->data(model->index(row, col), Qt::DisplayRole).toString();
if(col + 1 < model->columnCount())
s << ", ";
}
s << "\n";
}
}
f->close();
delete f;
});
exportThread->start();
ShowProgressDialog(this, tr("Exporting data"),
[exportThread]() { return !exportThread->isRunning(); });
exportThread->deleteLater();
}
void BufferViewer::debugVertex()
{
if(!m_Ctx.IsCaptureLoaded())
return;
if(!m_Ctx.CurDrawcall())
return;
if(!m_CurView)
return;
QModelIndex idx = m_CurView->selectionModel()->currentIndex();
if(!idx.isValid())
{
GUIInvoke::call(this, [this]() {
RDDialog::critical(this, tr("Error debugging"),
tr("Error debugging vertex - make sure a valid vertex is selected"));
});
return;
}
uint32_t vertid =
m_CurView->model()->data(m_CurView->model()->index(idx.row(), 0), Qt::DisplayRole).toUInt();
uint32_t index =
m_CurView->model()->data(m_CurView->model()->index(idx.row(), 1), Qt::DisplayRole).toUInt();
m_Ctx.Replay().AsyncInvoke([this, vertid, index](IReplayController *r) {
ShaderDebugTrace *trace =
r->DebugVertex(vertid, m_Config.curInstance, index, m_Ctx.CurDrawcall()->instanceOffset,
m_Ctx.CurDrawcall()->vertexOffset);
if(trace->states.isEmpty())
{
r->FreeTrace(trace);
GUIInvoke::call(this, [this]() {
RDDialog::critical(this, tr("Error debugging"),
tr("Error debugging vertex - make sure a valid vertex is selected"));
});
return;
}
GUIInvoke::call(this, [this, vertid, trace]() {
QString debugContext = tr("Vertex %1").arg(vertid);
if(m_Ctx.CurDrawcall()->numInstances > 1)
debugContext += tr(", Instance %1").arg(m_Config.curInstance);
const ShaderReflection *shaderDetails =
m_Ctx.CurPipelineState().GetShaderReflection(ShaderStage::Vertex);
const ShaderBindpointMapping &bindMapping =
m_Ctx.CurPipelineState().GetBindpointMapping(ShaderStage::Vertex);
ResourceId pipeline = m_Ctx.CurPipelineState().GetGraphicsPipelineObject();
// viewer takes ownership of the trace
IShaderViewer *s =
m_Ctx.DebugShader(&bindMapping, shaderDetails, pipeline, trace, debugContext);
m_Ctx.AddDockWindow(s->Widget(), DockReference::AddTo, this);
});
});
}
void BufferViewer::changeEvent(QEvent *event)
{
if(event->type() == QEvent::PaletteChange || event->type() == QEvent::StyleChange)
{
updateCheckerboardColours();
ui->render->update();
}
}
void BufferViewer::SyncViews(RDTableView *primary, bool selection, bool scroll)
{
if(!ui->syncViews->isChecked())
return;
RDTableView *views[] = {ui->vsinData, ui->vsoutData, ui->gsoutData};
int horizScrolls[ARRAY_COUNT(views)] = {0};
for(size_t i = 0; i < ARRAY_COUNT(views); i++)
horizScrolls[i] = views[i]->horizontalScrollBar()->value();
if(primary == NULL)
{
for(RDTableView *table : views)
{
if(table->hasFocus())
{
primary = table;
break;
}
}
}
if(primary == NULL)
primary = views[0];
for(RDTableView *table : views)
{
if(table == primary)
continue;
if(selection)
{
QModelIndexList selected = primary->selectionModel()->selectedRows();
if(!selected.empty())
table->selectRow(selected[0].row());
}
if(scroll)
table->verticalScrollBar()->setValue(primary->verticalScrollBar()->value());
}
for(size_t i = 0; i < ARRAY_COUNT(views); i++)
views[i]->horizontalScrollBar()->setValue(horizScrolls[i]);
}
void BufferViewer::UpdateHighlightVerts()
{
m_Config.highlightVert = ~0U;
if(!ui->highlightVerts->isChecked())
return;
RDTableView *table = currentTable();
if(!table)
return;
QModelIndexList selected = table->selectionModel()->selectedRows();
if(selected.empty())
return;
m_Config.highlightVert = selected[0].row();
}
void BufferViewer::EnableCameraGuessControls()
{
ui->aspectGuess->setEnabled(isCurrentRasterOut());
ui->nearGuess->setEnabled(isCurrentRasterOut());
ui->farGuess->setEnabled(isCurrentRasterOut());
}
void BufferViewer::on_outputTabs_currentChanged(int index)
{
ui->renderContainer->parentWidget()->layout()->removeWidget(ui->renderContainer);
ui->outputTabs->widget(index)->layout()->addWidget(ui->renderContainer);
if(index == 0)
m_CurStage = MeshDataStage::VSIn;
else if(index == 1)
m_CurStage = MeshDataStage::VSOut;
else if(index == 2)
m_CurStage = MeshDataStage::GSOut;
configureDrawRange();
on_resetCamera_clicked();
ui->autofitCamera->setEnabled(!isCurrentRasterOut());
EnableCameraGuessControls();
UpdateMeshConfig();
INVOKE_MEMFN(RT_UpdateAndDisplay);
}
void BufferViewer::on_toggleControls_toggled(bool checked)
{
ui->cameraControlsGroup->setVisible(checked);
EnableCameraGuessControls();
}
void BufferViewer::on_syncViews_toggled(bool checked)
{
SyncViews(NULL, true, true);
}
void BufferViewer::on_highlightVerts_toggled(bool checked)
{
UpdateHighlightVerts();
INVOKE_MEMFN(RT_UpdateAndDisplay);
}
void BufferViewer::on_wireframeRender_toggled(bool checked)
{
m_Config.wireframeDraw = checked;
INVOKE_MEMFN(RT_UpdateAndDisplay);
}
void BufferViewer::on_solidShading_currentIndexChanged(int index)
{
ui->wireframeRender->setEnabled(index > 0);
if(!ui->wireframeRender->isEnabled())
{
ui->wireframeRender->setChecked(true);
m_Config.wireframeDraw = true;
}
m_Config.solidShadeMode = (SolidShade)qMax(0, index);
m_ModelVSIn->setSecondaryColumn(m_ModelVSIn->secondaryColumn(),
m_Config.solidShadeMode == SolidShade::Secondary,
m_ModelVSIn->secondaryAlpha());
m_ModelVSOut->setSecondaryColumn(m_ModelVSOut->secondaryColumn(),
m_Config.solidShadeMode == SolidShade::Secondary,
m_ModelVSOut->secondaryAlpha());
m_ModelGSOut->setSecondaryColumn(m_ModelGSOut->secondaryColumn(),
m_Config.solidShadeMode == SolidShade::Secondary,
m_ModelGSOut->secondaryAlpha());
INVOKE_MEMFN(RT_UpdateAndDisplay);
}
void BufferViewer::on_drawRange_currentIndexChanged(int index)
{
configureDrawRange();
INVOKE_MEMFN(RT_UpdateAndDisplay);
}
void BufferViewer::on_controlType_currentIndexChanged(int index)
{
m_Arcball->Reset(FloatVector(), 10.0f);
m_Flycam->Reset(FloatVector());
if(index == 0)
{
m_CurrentCamera = m_Arcball;
resetArcball();
}
else
{
m_CurrentCamera = m_Flycam;
if(isCurrentRasterOut())
m_Flycam->Reset(FloatVector(0.0f, 0.0f, 0.0f, 0.0f));
else
m_Flycam->Reset(FloatVector(0.0f, 0.0f, -10.0f, 0.0f));
}
INVOKE_MEMFN(RT_UpdateAndDisplay);
}
void BufferViewer::on_resetCamera_clicked()
{
if(isCurrentRasterOut())
ui->controlType->setCurrentIndex(1);
else
ui->controlType->setCurrentIndex(0);
// make sure callback is called even if we're re-selecting same
// camera type
on_controlType_currentIndexChanged(ui->controlType->currentIndex());
}
void BufferViewer::on_camSpeed_valueChanged(double value)
{
m_Arcball->SpeedMultiplier = m_Flycam->SpeedMultiplier = value;
}
void BufferViewer::on_instance_valueChanged(int value)
{
m_Config.curInstance = value;
OnEventChanged(m_Ctx.CurEvent());
}
void BufferViewer::on_viewIndex_valueChanged(int value)
{
m_Config.curView = value;
OnEventChanged(m_Ctx.CurEvent());
}
void BufferViewer::on_rowOffset_valueChanged(int value)
{
ScrollToRow(m_ModelVSIn, value);
ScrollToRow(m_ModelVSOut, value);
ScrollToRow(m_ModelGSOut, value);
}
void BufferViewer::on_autofitCamera_clicked()
{
if(m_CurStage != MeshDataStage::VSIn)
return;
ui->controlType->setCurrentIndex(1);
BBoxData bbox;
{
QMutexLocker autolock(&m_BBoxLock);
if(m_BBoxes.contains(m_Ctx.CurEvent()))
bbox = m_BBoxes[m_Ctx.CurEvent()];
}
BufferItemModel *model = NULL;
int stage = 0;
switch(m_CurStage)
{
case MeshDataStage::VSIn:
model = m_ModelVSIn;
stage = 0;
break;
case MeshDataStage::VSOut:
model = m_ModelVSOut;
stage = 1;
break;
case MeshDataStage::GSOut:
model = m_ModelGSOut;
stage = 2;
break;
default: break;
}
if(bbox.bounds[stage].Min.isEmpty())
return;
if(!model)
return;
int posEl = model->posColumn();
if(posEl < 0 || posEl >= bbox.bounds[stage].Min.count())
return;
FloatVector diag;
diag.x = bbox.bounds[stage].Max[posEl].x - bbox.bounds[stage].Min[posEl].x;
diag.y = bbox.bounds[stage].Max[posEl].y - bbox.bounds[stage].Min[posEl].y;
diag.z = bbox.bounds[stage].Max[posEl].z - bbox.bounds[stage].Min[posEl].z;
float len = qSqrt(diag.x * diag.x + diag.y * diag.y + diag.z * diag.z);
if(diag.x >= 0.0f && diag.y >= 0.0f && diag.z >= 0.0f && len >= 1.0e-6f && len <= 1.0e+10f)
{
FloatVector mid;
mid.x = bbox.bounds[stage].Min[posEl].x + diag.x * 0.5f;
mid.y = bbox.bounds[stage].Min[posEl].y + diag.y * 0.5f;
mid.z = bbox.bounds[stage].Min[posEl].z + diag.z * 0.5f;
mid.z -= len;
m_Flycam->Reset(mid);
}
INVOKE_MEMFN(RT_UpdateAndDisplay);
}
|
#include "pxt.h"
#include "MicroBit.h"
#ifdef CODAL_CONFIG_H
#define MICROBIT_CODAL 1
#else
#define MICROBIT_CODAL 0
#define target_panic(n) microbit_panic(n)
#define target_wait(n) wait_ms(n)
#endif
#define PXT_PACKET_START 0xFD
#define PXT_PACKET_END 0xFE
#define PXT_CMD_GET_VERSION 0xD0
#define PXT_CMD_SET_DETMODE 0xD1
#define PXT_CMD_SET_FUNC 0xD2
#define PXT_CMD_SET_DELAY 0xD4
#define PXT_CMD_GET_DATA 0xD8
#define PXT_RET_FW_VERSION 0xE3
#define PXT_RET_OBJNUM 0x46 //0xE4
#define SERIAL_BUF_SIZE 64
#define DATA_SIZE 33
enum PixSerialPin {
P0 = 0,
P1 = 1,
P2 = 2,
P8 = 8,
P12 = 12,
P13 = 13,
P14 = 14,
P15 = 15,
P16 = 16
};
enum PixFunction {
//% block="color detection"
COLOR_DETECTION=1,
//% block="color codes detection"
COLOR_LABEL=2,
//% block="shape detection"
SHAPE_DETECTION=3,
//% block="sphere detection"
SPHERE_DETECTION=4,
//% block="template matching"
TEMPLATE=6,
//% block="keypoint"
KEYPOINT=8,
//% block="neural network"
NEURAL_NETWORK=9,
//% block="apriltag(16h5)"
APRILTAG=10,
//% block="face detection"
FACE_DETECTION=11,
//% block="traffic sign detection"
TRAFFIC_SIGN_DETECTION=12,
//% block="handwritten digits detection"
HANDWRITTEN_DIGITS_DETECTION=13,
//% block="handwritten letters detection"
HANDWRITTEN_LETTERS_DETECTION=14,
//% block="remote computing"
REMOTE_COMPUTING=15,
//% block="lanes detection"
LANES_DETECTION=16,
//% block="digits operation"
DIGITS_OPERATION=17,
//% block="simple classifier"
SIMPLE_CLASSIFIER=18,
//% block="voice commands"
VOICE_COMMANDS=19,
//% block="autonomous driving"
LANE_AND_SIGN=20
};
enum PixApriltagField {
//% block="position x"
APRILTAG_POS_X=1,
//% block="position y"
APRILTAG_POS_Y,
//% block="position z"
APRILTAG_POS_Z,
//% block="rotation x"
APRILTAG_ROT_X,
//% block="rotation y"
APRILTAG_ROT_Y,
//% block="rotation z"
APRILTAG_ROT_Z,
//% block="center x"
APRILTAG_CENTER_X,
//% block="center y"
APRILTAG_CENTER_Y
};
enum PixLanesField {
//% block="left x1"
LANES_LX1=1,
//% block="left y1"
LANES_LY1,
//% block="left x2"
LANES_LX2,
//% block="left y2"
LANES_LY2,
//% block="right x1"
LANES_RX1,
//% block="right y1"
LANES_RY1,
//% block="right x2"
LANES_RX2,
//% block="right y2"
LANES_RY2
};
//using namespace pxt;
//using namespace codal;
//extern MicroBit uBit;
namespace pixetto {
MicroBitSerial *serial = nullptr;
uint8_t data_buf[DATA_SIZE] = {0xFF};
int m_funcid = 0;
int data_len = 0;
int m_type = 0;
int m_x = 0;
int m_y = 0;
int m_w = 0;
int m_h = 0;
int m_eqLen = 0;
float m_eqAnswer = 0;
char m_eqExpr[17] = {0};
float m_posx=0, m_posy=0, m_posz=0, m_rotx=0, m_roty=0, m_rotz=0, m_centerx=0, m_centery=0;
bool bOnStarting = false;
int m_failcount = 0;
bool getPinName(PixSerialPin p, PinName& name) {
switch(p) {
case P0: name = MICROBIT_PIN_P0; return true;
case P1: name = MICROBIT_PIN_P1; return true;
case P2: name = MICROBIT_PIN_P2; return true;
case P8: name = MICROBIT_PIN_P8; return true;
case P12: name = MICROBIT_PIN_P12; return true;
case P13: name = MICROBIT_PIN_P13; return true;
case P14: name = MICROBIT_PIN_P14; return true;
case P15: name = MICROBIT_PIN_P15; return true;
case P16: name = MICROBIT_PIN_P16; return true;
}
return false;
}
bool ssflush()
{
uint8_t a;
int read_len = 0;
do {
read_len = serial->read(&a, 1, ASYNC);
} while (read_len > 0 && read_len != MICROBIT_NO_DATA);
return true;
}
int ssread(uint8_t *buf, int len, int wait_loop)
{
int read_len = 0;
int read_idx = 0;
int loop = 0;
do {
read_len = serial->read(&buf[read_idx], 1, ASYNC);
if (read_len == 0 || read_len == MICROBIT_NO_DATA)
loop++;
else
read_idx++;
} while (read_idx < len && loop < wait_loop);
if (read_len == 0 || read_len == MICROBIT_NO_DATA)
read_idx = read_len;
return read_idx;
}
bool verifyChecksum(uint8_t *buf, int len)
{
uint8_t sum = 0;
for (uint8_t i=1; i<len-2; i++)
sum += buf[i];
sum %= 256;
//if (sum == PXT_PACKET_START || sum == PXT_PACKET_END || sum == 0xFF)
// sum = 0xAA;
return (sum == buf[len-2]);
}
bool opencam()
{
int try_connect = 0;
do {
serial->clearRxBuffer();
uint8_t cmd_buf[5] = {PXT_PACKET_START, 0x05, PXT_CMD_GET_VERSION, 0, PXT_PACKET_END};
serial->send(cmd_buf, 5, ASYNC);
// version = {0xFD, 0, 0xE3, product, (uint8_t)major, (uint8_t)minor, (uint8_t)revision, 0, 0xFE};
int loop = 0;
int read_len = 0;
uint8_t code_buf[9] = {0xFF};
do {
read_len = serial->read(code_buf, 1, ASYNC);
loop++;
} while (code_buf[0] != PXT_PACKET_START && loop < 300000);
if (read_len == 0 || read_len == MICROBIT_NO_DATA) return false;
read_len = serial->read(&code_buf[1], 8);
if (read_len == 8 &&
code_buf[0] == PXT_PACKET_START &&
code_buf[8] == PXT_PACKET_END &&
code_buf[2] == PXT_RET_FW_VERSION)
{
serial->clearRxBuffer();
return true;
}
try_connect++;
uBit.sleep(500);
} while (try_connect < 4);
return false;
}
//%
bool begin(PixSerialPin rx, PixSerialPin tx){
bOnStarting = true;
bool ret = false;
PinName txn, rxn;
uBit.sleep(3000);
if (getPinName(tx, txn) && getPinName(rx, rxn))
{
if (serial == nullptr)
serial = new MicroBitSerial(txn, rxn, 64, 20);
#if MICROBIT_CODAL
serial->setBaudrate(38400);
#else
serial->baud(38400);
#endif
//serial->setRxBufferSize(64);
//serial->setTxBufferSize(32);
uBit.sleep(1000);
ret = opencam();
}
if (ret)
bOnStarting = false;
return ret;
}
void setDetMode(bool isStream){
uint8_t cmd_buf[6] = {PXT_PACKET_START, 0x06, PXT_CMD_SET_DETMODE, (uint8_t)isStream, 0, PXT_PACKET_END};
serial->send(cmd_buf, 6, ASYNC);
}
//%
void enableFunc(int func_id){
m_funcid = func_id;
uint8_t cmd_buf[6] = {PXT_PACKET_START, 0x06, PXT_CMD_SET_FUNC, (uint8_t)func_id, 0, PXT_PACKET_END};
serial->send(cmd_buf, 6, ASYNC);
if (m_funcid == VOICE_COMMANDS)
setDetMode(true);
return;
}
//%
bool isDetected(){
if (bOnStarting)
return false;
if (m_funcid != VOICE_COMMANDS) {
serial->clearRxBuffer();
uint8_t cmd_buf[5] = {PXT_PACKET_START, 0x05, PXT_CMD_GET_DATA, 0, PXT_PACKET_END};
serial->send(cmd_buf, 5);//, ASYNC);
}
int a = 0;
while(1){
for (a=0; a<DATA_SIZE; a++)
data_buf[a] = 0xFF;
int loop = 0;
int read_len = 0;
int buffered_len = 0;
while ((buffered_len = serial->rxBufferedSize()) <= 0 && loop < 400000)
loop++;
if (loop >= 400000) {
m_failcount++;
if (m_failcount > 5)
{
if (opencam()) {
m_failcount = 0;
enableFunc(m_funcid);
}
ssflush();
}
return false;
}
m_failcount = 0;
read_len = serial->read(&data_buf[0], 1);
if (data_buf[0] != PXT_PACKET_START) {
ssflush();
if (opencam()) {
enableFunc(m_funcid);
}
ssflush();
return false;
}
read_len = serial->read(&data_buf[1], 2);// get <len, func_id>
data_len = data_buf[1];
if (data_len > 3)
read_len = serial->read(&data_buf[3], data_len - 3);
else
return false;
if (read_len != (data_len-3)) return false;
if (data_buf[data_len-1] != PXT_PACKET_END) return false;
if (!verifyChecksum(data_buf, data_len)) return false;
if (data_buf[2] == 0) return false; // null packet
if (data_buf[2] == PXT_RET_OBJNUM)
continue;
else
break;
}
if (data_buf[2] == DIGITS_OPERATION) {
m_x = data_buf[3];
m_y = data_buf[4];
m_w = data_buf[5];
m_h = data_buf[6];
m_eqAnswer = 0;
for (a=8; a<=14; a++)
m_eqAnswer = m_eqAnswer * 10 + data_buf[a];
m_eqAnswer /= 100;
if (data_buf[7] == 0) m_eqAnswer = 0 - m_eqAnswer;
memset(m_eqExpr, 0, sizeof(m_eqExpr));
m_eqLen = data_len - 17;
for (a=0; a<m_eqLen; a++)
m_eqExpr[a] = (char)data_buf[a+15];
}
else if (data_buf[2] == LANES_DETECTION) {
m_x = data_buf[3];
m_y = data_buf[4];
}
else if (data_buf[2] == SIMPLE_CLASSIFIER) {
m_type = data_buf[3] * 256 + data_buf[4];
m_x = data_buf[5];
m_y = data_buf[6];
m_w = data_buf[7];
m_h = data_buf[8];
}
else if (data_buf[2] == LANE_AND_SIGN) {
if (data_buf[18] == 0 || data_buf[18] == 2) {
m_x = -1; m_y = -1;
}
else {
m_x = data_buf[3];
m_y = data_buf[4];
}
if (data_buf[18] == 0 || data_buf[18] == 1)
m_type = -1;
else
m_type = data_buf[13];
}
else {
m_type = data_buf[3];
m_x = data_buf[4];
m_y = data_buf[5];
m_w = data_buf[6];
m_h = data_buf[7];
if (data_buf[2] == APRILTAG) {
int value = 0;
value = (short)(data_buf[8] * 256 + data_buf[9]);
m_posx = (float)value / 100.0;
value = (short)(data_buf[10] * 256 + data_buf[11]);
m_posy = (float)value / 100.0;
value = (short)(data_buf[12] * 256 + data_buf[13]);
m_posz = (float)value / 100.0;
m_rotx = (short)(data_buf[14] * 256 + data_buf[15]);
m_roty = (short)(data_buf[16] * 256 + data_buf[17]);
m_rotz = (short)(data_buf[18] * 256 + data_buf[19]);
m_centerx = (short)(data_buf[20] * 256 + data_buf[21]);
m_centery = (short)(data_buf[22] * 256 + data_buf[23]);
}
}
return true;
}
//%
bool getFuncID(int func_id){
return (data_buf[2] == func_id);
}
//%
bool get_colordetect_color(int color) {
if (data_buf[2] == COLOR_DETECTION && data_buf[3] == color)
return true;
return false;
}
//%
bool get_shapedetect_shape(int shape) {
if (data_buf[2] == SHAPE_DETECTION && data_buf[3] == shape)
return true;
return false;
}
//%
bool get_spheredetect_color(int color) {
if (data_buf[2] == SPHERE_DETECTION && data_buf[3] == color)
return true;
return false;
}
//%
bool get_template_id(int id) {
if (data_buf[2] == TEMPLATE && data_buf[3] == id)
return true;
return false;
}
//%
bool get_keypoint_id(int id) {
if (data_buf[2] == KEYPOINT && data_buf[3] == id)
return true;
return false;
}
//%
bool get_nn_id(int id) {
if (data_buf[2] == NEURAL_NETWORK && data_buf[3] == id)
return true;
return false;
}
//%
bool get_traffic_sign(int sign) {
if (data_buf[2] == TRAFFIC_SIGN_DETECTION && data_buf[3] == sign)
return true;
if (data_buf[2] == LANE_AND_SIGN && m_type == sign)
return true;
return false;
}
//%
bool get_hand_digit(int digit) {
if (data_buf[2] == HANDWRITTEN_DIGITS_DETECTION && data_buf[3] == digit)
return true;
return false;
}
//%
bool get_hand_letter(int letter) {
if (data_buf[2] == HANDWRITTEN_LETTERS_DETECTION && data_buf[3] == letter)
return true;
return false;
}
//%
bool get_remote_computing(int id) {
if (data_buf[2] == REMOTE_COMPUTING && data_buf[3] == id)
return true;
return false;
}
//%
bool get_simple_classifier(int id) {
if (data_buf[2] == SIMPLE_CLASSIFIER && data_buf[3] == id)
return true;
return false;
}
//%
bool get_voice_command(int vcmd) {
if (data_buf[2] == VOICE_COMMANDS && data_buf[3] == vcmd)
return true;
return false;
}
//%
int getTypeID() {
return m_type;
}
//%
int getPosX() {
return m_x;
}
//%
int getPosY() {
return m_y;
}
//%
int getWidth() {
return m_w;
}
//%
int getHeight() {
return m_h;
}
//%
float getEquationAnswer() {
return m_eqAnswer;
}
//%
String getEquationExpr() {
ManagedString s = m_eqExpr;
return PSTR(s);
}
//%
float getApriltagField(int field) {
switch(field) {
case APRILTAG_POS_X:
return m_posx;
case APRILTAG_POS_Y:
return m_posy;
case APRILTAG_POS_Z:
return m_posz;
case APRILTAG_ROT_X:
return m_rotx;
case APRILTAG_ROT_Y:
return m_roty;
case APRILTAG_ROT_Z:
return m_rotz;
case APRILTAG_CENTER_X:
return m_centerx;
case APRILTAG_CENTER_Y:
return m_centery;
default:
return 0;
}
}
//%
int getLanesField(int field) {
switch(field) {
case LANES_LX1:
return data_buf[5];
case LANES_LY1:
return data_buf[6];
case LANES_LX2:
return data_buf[7];
case LANES_LY2:
return data_buf[8];
case LANES_RX1:
return data_buf[9];
case LANES_RY1:
return data_buf[10];
case LANES_RX2:
return data_buf[11];
case LANES_RY2:
return data_buf[12];
default:
return 0;
}
}
}
|
/******************************************************************************
* Copyright 2017 The Apollo 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 <iostream>
#include <thread>
#include "cyber/common/log.h"
#include "cyber/common/macros.h"
#include "cyber/cyber.h"
#include "cyber/init.h"
#include "cyber/time/time.h"
#include "modules/canbus/proto/chassis.pb.h"
#include "modules/control/proto/pad_msg.pb.h"
#include "modules/common/adapters/adapter_gflags.h"
#include "modules/common/time/time.h"
#include "modules/common/util/message_util.h"
#include "modules/control/common/control_gflags.h"
namespace {
using apollo::canbus::Chassis;
using apollo::common::time::AsInt64;
using apollo::common::time::Clock;
using apollo::control::DrivingAction;
using apollo::control::PadMessage;
using apollo::cyber::CreateNode;
using apollo::cyber::Node;
using apollo::cyber::Reader;
using apollo::cyber::Writer;
class PadTerminal {
public:
PadTerminal() : node_(CreateNode("pad_terminal")) {}
void init() {
chassis_reader_ = node_->CreateReader<Chassis>(
FLAGS_chassis_topic, [this](const std::shared_ptr<Chassis> &chassis) {
on_chassis(*chassis);
});
pad_writer_ = node_->CreateWriter<PadMessage>(FLAGS_pad_topic);
terminal_thread_.reset(new std::thread([this] { terminal_thread_func(); }));
}
void help() {
AINFO << "COMMAND:\n";
AINFO << "\t0: reset to manual drive mode.";
AINFO << "\t1: auto drive mode.";
AINFO << "\tctrl + c: exit.";
AINFO << "\tother: print help.";
}
void send(int cmd_type) {
PadMessage pad;
if (cmd_type == RESET_COMMAND) {
pad.set_action(DrivingAction::RESET);
AINFO << "sending reset action command.";
} else if (cmd_type == AUTO_DRIVE_COMMAND) {
pad.set_action(DrivingAction::START);
AINFO << "sending start action command.";
}
apollo::common::util::FillHeader("terminal", &pad);
pad_writer_->Write(std::make_shared<PadMessage>(pad));
AINFO << "send pad_message OK";
}
void on_chassis(const Chassis &chassis) {
static bool is_first_emergency_mode = true;
static int64_t count_start = 0;
static bool waiting_reset = false;
// check if chassis enter security mode, if enter, after 10s should reset to
// manual
if (chassis.driving_mode() == Chassis::EMERGENCY_MODE) {
if (is_first_emergency_mode == true) {
count_start = AsInt64<std::chrono::microseconds>(Clock::Now());
is_first_emergency_mode = false;
AINFO << "detect emergency mode.";
} else {
int64_t diff =
AsInt64<std::chrono::microseconds>(Clock::Now()) - count_start;
if (diff > EMERGENCY_MODE_HOLD_TIME) {
count_start = AsInt64<std::chrono::microseconds>(Clock::Now());
waiting_reset = true;
// send a reset command to control
send(RESET_COMMAND);
AINFO << "trigger to reset emergency mode to manual mode.";
} else {
// nothing to do
}
}
} else if (chassis.driving_mode() == Chassis::COMPLETE_MANUAL) {
if (waiting_reset) {
is_first_emergency_mode = true;
waiting_reset = false;
AINFO << "emergency mode reset to manual ok.";
}
}
}
void terminal_thread_func() {
int mode = 0;
bool should_exit = false;
while (std::cin >> mode) {
switch (mode) {
case 0:
send(RESET_COMMAND);
break;
case 1:
send(AUTO_DRIVE_COMMAND);
break;
case 9:
should_exit = true;
break;
default:
help();
break;
}
if (should_exit) {
break;
}
}
}
void stop() { terminal_thread_->join(); }
private:
std::unique_ptr<std::thread> terminal_thread_;
const int ROS_QUEUE_SIZE = 1;
const int RESET_COMMAND = 1;
const int AUTO_DRIVE_COMMAND = 2;
const int EMERGENCY_MODE_HOLD_TIME = 4 * 1000000;
std::shared_ptr<Reader<Chassis>> chassis_reader_;
std::shared_ptr<Writer<PadMessage>> pad_writer_;
std::shared_ptr<Node> node_;
};
} // namespace
int main(int argc, char **argv) {
apollo::cyber::Init("pad_terminal");
FLAGS_alsologtostderr = true;
FLAGS_v = 3;
google::ParseCommandLineFlags(&argc, &argv, true);
PadTerminal pad_terminal;
pad_terminal.init();
pad_terminal.help();
apollo::cyber::WaitForShutdown();
pad_terminal.stop();
return 0;
}
|
#define TYPEDEPARGS 0, 1
#define SINGLEARGS
#define COMPLEXINDEPENDENT
#define OCTFILENAME comp_filterbank_td // change to filename
#define OCTFILEHELP "This function calls the C-library\n\
c=comp_filterbank_td(f,g,a,offset,ext)\n Yeah."
#include "ltfat_oct_template_helper.h"
static inline void
fwd_filterbank_td(const Complex *f, const Complex *g[],
const ltfatInt L, const ltfatInt gl[],
const ltfatInt W, const ltfatInt a[],
const ltfatInt offset[], const ltfatInt M,
Complex *c[], ltfatExtType ext)
{
filterbank_td_cd(reinterpret_cast<const fftw_complex *>(f),
reinterpret_cast<const fftw_complex **>(g),
L, gl, W, a, offset, M,
reinterpret_cast<fftw_complex **>(c),
ext);
}
static inline void
fwd_filterbank_td(const FloatComplex *f, const FloatComplex *g[],
const ltfatInt L, const ltfatInt gl[],
const ltfatInt W, const ltfatInt a[],
const ltfatInt offset[], const ltfatInt M,
FloatComplex *c[], ltfatExtType ext)
{
filterbank_td_cs(reinterpret_cast<const fftwf_complex *>(f),
reinterpret_cast<const fftwf_complex **>(g),
L, gl, W, a, offset, M,
reinterpret_cast<fftwf_complex **>(c),
ext);
}
static inline void
fwd_filterbank_td(const double *f, const double *g[],
const ltfatInt L, const ltfatInt gl[],
const ltfatInt W, const ltfatInt a[],
const ltfatInt offset[], const ltfatInt M,
double *c[], ltfatExtType ext)
{
filterbank_td_d(f, g, L, gl, W, a, offset, M, c, ext);
}
static inline void
fwd_filterbank_td(const float *f, const float *g[],
const ltfatInt L, const ltfatInt gl[],
const ltfatInt W, const ltfatInt a[],
const ltfatInt offset[], const ltfatInt M,
float *c[], ltfatExtType ext)
{
filterbank_td_s(f, g, L, gl, W, a, offset, M, c, ext);
}
template <class LTFAT_TYPE, class LTFAT_REAL, class LTFAT_COMPLEX>
octave_value_list octFunction(const octave_value_list& args, int nargout)
{
// Input data
MArray<LTFAT_TYPE> f = ltfatOctArray<LTFAT_TYPE>(args(0));
// Cell aray containing impulse responses
Cell g = args(1).cell_value();
// Subsampling factors
Matrix aDouble = args(2).matrix_value();
// Skips
Matrix offsetDouble = args(3).matrix_value();
charMatrix extMat = args(4).char_matrix_value();
ltfatExtType ext = ltfatExtStringToEnum(extMat.row_as_string(0).c_str());
// Input length
const octave_idx_type L = f.rows();
// Number of channels
const octave_idx_type W = f.columns();
// Number of filters
const octave_idx_type M = g.numel();
// Allocating temporary arrays
// Filter lengts
OCTAVE_LOCAL_BUFFER (ltfatInt, filtLen, M);
OCTAVE_LOCAL_BUFFER (ltfatInt, a, M);
OCTAVE_LOCAL_BUFFER (ltfatInt, offset , M);
// Impulse responses pointers
OCTAVE_LOCAL_BUFFER (const LTFAT_TYPE*, gPtrs, M);
// Output subbands pointers
OCTAVE_LOCAL_BUFFER (LTFAT_TYPE*, cPtrs, M);
// Output cell elements array,
OCTAVE_LOCAL_BUFFER (MArray<LTFAT_TYPE>, c_elems, M);
//
OCTAVE_LOCAL_BUFFER (MArray<LTFAT_TYPE>, g_elems, M);
for (octave_idx_type m = 0; m < M; m++)
{
a[m] = (ltfatInt) aDouble(m);
offset[m] = (ltfatInt) offsetDouble(m);
g_elems[m] = ltfatOctArray<LTFAT_TYPE>(g.elem(m));
gPtrs[m] = g_elems[m].data();
filtLen[m] = (ltfatInt) g_elems[m].numel();
octave_idx_type outLen = (octave_idx_type)
filterbank_td_size(L, a[m], filtLen[m],
offset[m], ext);
c_elems[m] = MArray<LTFAT_TYPE>(dim_vector(outLen, W));
cPtrs[m] = c_elems[m].fortran_vec();
}
fwd_filterbank_td(f.data(), gPtrs, L, filtLen, W, a, offset, M, cPtrs, ext);
Cell c(dim_vector(M, 1));
for (octave_idx_type m = 0; m < M; ++m)
{
c.elem(m) = c_elems[m];
}
return octave_value(c);
}
|
/*
* Copyright (C) 2013 Trent Houliston <trent@houliston.me>, Jake Woods <jake.f.woods@gmail.com>
* 2014-2017 Trent Houliston <trent@houliston.me>
*
* 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 "nuclear_bits/util/main_thread_id.hpp"
namespace NUClear {
namespace util {
/**
* @brief The thread id of the main execution thread for this process
* @detail In order to get the main threads id, we set it as a global static variable.
* This should result in the static setup code executing on startup (in the main thread).
*/
std::thread::id main_thread_id = std::this_thread::get_id();
} // namespace util
} // namespace NUClear
|
#pragma once
#include "../relacy/relacy_std.hpp"
template<int index, int mo_index>
struct fence_synch_test : rl::test_suite<fence_synch_test<index, mo_index>, 2>
{
std::atomic<int> x;
rl::var<int> data;
void before()
{
x($) = 0;
}
void thread(unsigned th)
{
if (0 == th)
{
data($) = 1;
if (0 == index || 1 == index)
{
std::atomic_thread_fence(order().first, $);
x.store(1, std::memory_order_relaxed);
}
else
{
x.store(1, order().first, $);
}
}
else
{
if (0 == index || 2 == index)
{
if (x.load(std::memory_order_relaxed))
{
std::atomic_thread_fence(order().second, $);
data($).load();
}
}
else
{
if (x.load(order().second, $))
{
data($).load();
}
}
}
}
std::pair<std::memory_order, std::memory_order> order()
{
switch (mo_index)
{
default: RL_VERIFY(false);
case 0: return std::make_pair(std::mo_release, std::mo_acquire);
case 1: return std::make_pair(std::mo_seq_cst, std::mo_seq_cst);
}
}
};
struct two_fence_synch_test : rl::test_suite<two_fence_synch_test, 3>
{
std::atomic<int> x0;
std::atomic<int> x1;
rl::var<int> data0;
rl::var<int> data1;
void before()
{
x0($) = 0;
x1($) = 0;
}
void thread(unsigned index)
{
if (0 == index)
{
data0($) = 1;
std::atomic_thread_fence(std::memory_order_release);
x0.store(1, std::memory_order_relaxed);
}
else if (1 == index)
{
data1($) = 1;
std::atomic_thread_fence(std::memory_order_release);
x1.store(1, std::memory_order_relaxed);
}
else
{
int y0 = x0.load(std::memory_order_relaxed);
int y1 = x1.load(std::memory_order_relaxed);
if (y0 || y1)
{
std::atomic_thread_fence(std::memory_order_acquire);
if (y0)
data0($).load();
if (y1)
data1($).load();
}
}
}
};
template<int index>
struct seq_cst_fence_test : rl::test_suite<seq_cst_fence_test<index>, 2,
(rl::test_result_e)((0 == index) * rl::test_result_success
+ (1 == index) * rl::test_result_until_condition_hit)>
{
std::atomic<int> x0;
std::atomic<int> x1;
rl::var<int> r0;
rl::var<int> r1;
void before()
{
x0($) = 0;
x1($) = 0;
}
void thread(unsigned th)
{
if (0 == th)
{
x0.store(1, std::memory_order_relaxed);
std::atomic_thread_fence(std::memory_order_seq_cst);
r0($) = x1.load(std::memory_order_relaxed);
}
else
{
x1.store(1, std::memory_order_relaxed);
std::atomic_thread_fence(std::memory_order_seq_cst);
r1($) = x0.load(std::memory_order_relaxed);
}
}
void after()
{
if (0 == index)
RL_ASSERT(r0($) || r1($));
else if (1 == index)
RL_UNTIL(r0($) && r1($));
}
};
|
// Copyright (c) 2014-2017 Daniel Kraft
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "base58.h"
#include "coins.h"
#include "init.h"
#include "names/common.h"
#include "names/main.h"
#include "primitives/transaction.h"
#include "random.h"
#include "rpc/server.h"
#include "script/names.h"
#include "txmempool.h"
#include "util.h"
#include "validation.h"
#include "wallet/wallet.h"
#include <univalue.h>
// Maximum number of outputs that are checked for the NAME_NEW prevout.
constexpr unsigned MAX_NAME_PREVOUT_TRIALS = 1000;
/**
* Helper routine to fetch the name output of a previous transaction. This
* is required for name_firstupdate.
* @param txid Previous transaction ID.
* @param txOut Set to the corresponding output.
* @param txIn Set to the CTxIn to include in the new tx.
* @return True if the output could be found.
*/
static bool
getNamePrevout (const uint256& txid, CTxOut& txOut, CTxIn& txIn)
{
AssertLockHeld (cs_main);
// Unfortunately, with the change of the txdb to be based on outputs rather
// than full transactions, we can no longer just look up the txid and iterate
// over all outputs. Since this is only necessary for a corner case, we just
// keep trying with indices until we find the output (up to a maximum number
// of trials).
for (unsigned i = 0; i < MAX_NAME_PREVOUT_TRIALS; ++i)
{
const COutPoint outp(txid, i);
Coin coin;
if (!pcoinsTip->GetCoin (outp, coin))
continue;
if (!coin.out.IsNull ()
&& CNameScript::isNameScript (coin.out.scriptPubKey))
{
txOut = coin.out;
txIn = CTxIn (outp);
return true;
}
}
return false;
}
/* ************************************************************************** */
UniValue
name_list (const JSONRPCRequest& request)
{
CWallet* const pwallet = GetWalletForJSONRPCRequest(request);
if (!EnsureWalletIsAvailable (pwallet, request.fHelp))
return NullUniValue;
if (request.fHelp || request.params.size () > 1)
throw std::runtime_error (
"name_list (\"name\")\n"
"\nShow status of names in the wallet.\n"
"\nArguments:\n"
"1. \"name\" (string, optional) only include this name\n"
"\nResult:\n"
"[\n"
+ getNameInfoHelp (" ", ",") +
" ...\n"
"]\n"
"\nExamples:\n"
+ HelpExampleCli ("name_list", "")
+ HelpExampleCli ("name_list", "\"myname\"")
+ HelpExampleRpc ("name_list", "")
);
valtype nameFilter;
if (request.params.size () == 1)
nameFilter = ValtypeFromString (request.params[0].get_str ());
std::map<valtype, int> mapHeights;
std::map<valtype, UniValue> mapObjects;
{
LOCK2 (cs_main, pwallet->cs_wallet);
for (const auto& item : pwallet->mapWallet)
{
const CWalletTx& tx = item.second;
if (!tx.tx->IsDenemecoin ())
continue;
CNameScript nameOp;
int nOut = -1;
for (unsigned i = 0; i < tx.tx->vout.size (); ++i)
{
const CNameScript cur(tx.tx->vout[i].scriptPubKey);
if (cur.isNameOp ())
{
if (nOut != -1)
LogPrintf ("ERROR: wallet contains tx with multiple"
" name outputs");
else
{
nameOp = cur;
nOut = i;
}
}
}
if (nOut == -1 || !nameOp.isAnyUpdate ())
continue;
const valtype& name = nameOp.getOpName ();
if (!nameFilter.empty () && nameFilter != name)
continue;
const CBlockIndex* pindex;
const int depth = tx.GetDepthInMainChain (pindex);
if (depth <= 0)
continue;
const std::map<valtype, int>::const_iterator mit = mapHeights.find (name);
if (mit != mapHeights.end () && mit->second > pindex->nHeight)
continue;
UniValue obj
= getNameInfo (name, nameOp.getOpValue (),
COutPoint (tx.GetHash (), nOut),
nameOp.getAddress (), pindex->nHeight);
const bool mine = IsMine (*pwallet, nameOp.getAddress ());
obj.pushKV ("transferred", !mine);
mapHeights[name] = pindex->nHeight;
mapObjects[name] = obj;
}
}
UniValue res(UniValue::VARR);
for (const auto& item : mapObjects)
res.push_back (item.second);
return res;
}
/* ************************************************************************** */
UniValue
name_new (const JSONRPCRequest& request)
{
CWallet* const pwallet = GetWalletForJSONRPCRequest(request);
if (!EnsureWalletIsAvailable (pwallet, request.fHelp))
return NullUniValue;
if (request.fHelp || request.params.size () != 1)
throw std::runtime_error (
"name_new \"name\"\n"
"\nStart registration of the given name. Must be followed up with"
" name_firstupdate to finish the registration.\n"
+ HelpRequiringPassphrase (pwallet) +
"\nArguments:\n"
"1. \"name\" (string, required) the name to register\n"
"\nResult:\n"
"[\n"
" xxxxx, (string) the txid, required for name_firstupdate\n"
" xxxxx (string) random value for name_firstupdate\n"
"]\n"
"\nExamples:\n"
+ HelpExampleCli ("name_new", "\"myname\"")
+ HelpExampleRpc ("name_new", "\"myname\"")
);
const std::string nameStr = request.params[0].get_str ();
const valtype name = ValtypeFromString (nameStr);
if (name.size () > MAX_NAME_LENGTH)
throw JSONRPCError (RPC_INVALID_PARAMETER, "the name is too long");
valtype rand(20);
GetRandBytes (&rand[0], rand.size ());
valtype toHash(rand);
toHash.insert (toHash.end (), name.begin (), name.end ());
const uint160 hash = Hash160 (toHash);
/* No explicit locking should be necessary. CReserveKey takes care
of locking the wallet, and CommitTransaction (called when sending
the tx) locks cs_main as necessary. */
EnsureWalletIsUnlocked (pwallet);
CReserveKey keyName(pwallet);
CPubKey pubKey;
const bool ok = keyName.GetReservedKey (pubKey, true);
assert (ok);
const CScript addrName = GetScriptForDestination (pubKey.GetID ());
const CScript newScript = CNameScript::buildNameNew (addrName, hash);
CWalletTx wtx;
SendMoneyToScript (pwallet, newScript, NULL, NAME_LOCKED_AMOUNT, false, wtx);
keyName.KeepKey ();
const std::string randStr = HexStr (rand);
const std::string txid = wtx.GetHash ().GetHex ();
LogPrintf ("name_new: name=%s, rand=%s, tx=%s\n",
nameStr.c_str (), randStr.c_str (), txid.c_str ());
UniValue res(UniValue::VARR);
res.push_back (txid);
res.push_back (randStr);
return res;
}
/* ************************************************************************** */
UniValue
name_firstupdate (const JSONRPCRequest& request)
{
CWallet* const pwallet = GetWalletForJSONRPCRequest(request);
if (!EnsureWalletIsAvailable (pwallet, request.fHelp))
return NullUniValue;
/* There is an undocumented sixth argument that can be used to disable
the check for already existing names here (it will still be checked
by the mempool and tx validation logic, of course). This is used
by the regtests to catch a bug that was previously present but
has presumably no other use. */
if (request.fHelp || request.params.size () < 4 || request.params.size () > 6)
throw std::runtime_error (
"name_firstupdate \"name\" \"rand\" \"tx\" \"value\" (\"toaddress\")\n"
"\nFinish the registration of a name. Depends on name_new being"
" already issued.\n"
+ HelpRequiringPassphrase (pwallet) +
"\nArguments:\n"
"1. \"name\" (string, required) the name to register\n"
"2. \"rand\" (string, required) the rand value of name_new\n"
"3. \"tx\" (string, required) the name_new txid\n"
"4. \"value\" (string, required) value for the name\n"
"5. \"toaddress\" (string, optional) address to send the name to\n"
"\nResult:\n"
"\"txid\" (string) the name_firstupdate's txid\n"
"\nExamples:\n"
+ HelpExampleCli ("name_firstupdate", "\"myname\", \"555844f2db9c7f4b25da6cb8277596de45021ef2\" \"a77ceb22aa03304b7de64ec43328974aeaca211c37dd29dcce4ae461bb80ca84\", \"my-value\"")
+ HelpExampleCli ("name_firstupdate", "\"myname\", \"555844f2db9c7f4b25da6cb8277596de45021ef2\" \"a77ceb22aa03304b7de64ec43328974aeaca211c37dd29dcce4ae461bb80ca84\", \"my-value\", \"NEX4nME5p3iyNK3gFh4FUeUriHXxEFemo9\"")
+ HelpExampleRpc ("name_firstupdate", "\"myname\", \"555844f2db9c7f4b25da6cb8277596de45021ef2\" \"a77ceb22aa03304b7de64ec43328974aeaca211c37dd29dcce4ae461bb80ca84\", \"my-value\"")
);
const std::string nameStr = request.params[0].get_str ();
const valtype name = ValtypeFromString (nameStr);
if (name.size () > MAX_NAME_LENGTH)
throw JSONRPCError (RPC_INVALID_PARAMETER, "the name is too long");
const valtype rand = ParseHexV (request.params[1], "rand");
if (rand.size () > 20)
throw JSONRPCError (RPC_INVALID_PARAMETER, "invalid rand value");
const uint256 prevTxid = ParseHashV (request.params[2], "txid");
const std::string valueStr = request.params[3].get_str ();
const valtype value = ValtypeFromString (valueStr);
if (value.size () > MAX_VALUE_LENGTH_UI)
throw JSONRPCError (RPC_INVALID_PARAMETER, "the value is too long");
{
LOCK (mempool.cs);
if (mempool.registersName (name))
throw JSONRPCError (RPC_TRANSACTION_ERROR,
"this name is already being registered");
}
if (request.params.size () < 6 || !request.params[5].get_bool ())
{
LOCK (cs_main);
CNameData oldData;
if (pcoinsTip->GetName (name, oldData) && !oldData.isExpired ())
throw JSONRPCError (RPC_TRANSACTION_ERROR,
"this name is already active");
}
CTxOut prevOut;
CTxIn txIn;
{
LOCK (cs_main);
if (!getNamePrevout (prevTxid, prevOut, txIn))
throw JSONRPCError (RPC_TRANSACTION_ERROR, "previous txid not found");
}
const CNameScript prevNameOp(prevOut.scriptPubKey);
assert (prevNameOp.isNameOp ());
if (prevNameOp.getNameOp () != OP_NAME_NEW)
throw JSONRPCError (RPC_TRANSACTION_ERROR, "previous tx is not name_new");
valtype toHash(rand);
toHash.insert (toHash.end (), name.begin (), name.end ());
if (uint160 (prevNameOp.getOpHash ()) != Hash160 (toHash))
throw JSONRPCError (RPC_TRANSACTION_ERROR, "rand value is wrong");
/* No more locking required, similarly to name_new. */
EnsureWalletIsUnlocked (pwallet);
CReserveKey keyName(pwallet);
CPubKey pubKeyReserve;
const bool ok = keyName.GetReservedKey (pubKeyReserve, true);
assert (ok);
bool usedKey = false;
CScript addrName;
if (request.params.size () >= 5)
{
keyName.ReturnKey ();
const CBitcoinAddress toAddress(request.params[4].get_str ());
if (!toAddress.IsValid ())
throw JSONRPCError (RPC_INVALID_ADDRESS_OR_KEY, "invalid address");
addrName = GetScriptForDestination (toAddress.Get ());
}
else
{
usedKey = true;
addrName = GetScriptForDestination (pubKeyReserve.GetID ());
}
const CScript nameScript
= CNameScript::buildNameFirstupdate (addrName, name, value, rand);
CWalletTx wtx;
SendMoneyToScript (pwallet, nameScript, &txIn,
NAME_LOCKED_AMOUNT, false, wtx);
if (usedKey)
keyName.KeepKey ();
return wtx.GetHash ().GetHex ();
}
/* ************************************************************************** */
UniValue
name_update (const JSONRPCRequest& request)
{
CWallet* const pwallet = GetWalletForJSONRPCRequest(request);
if (!EnsureWalletIsAvailable (pwallet, request.fHelp))
return NullUniValue;
if (request.fHelp
|| (request.params.size () != 2 && request.params.size () != 3))
throw std::runtime_error (
"name_update \"name\" \"value\" (\"toaddress\")\n"
"\nUpdate a name and possibly transfer it.\n"
+ HelpRequiringPassphrase (pwallet) +
"\nArguments:\n"
"1. \"name\" (string, required) the name to update\n"
"4. \"value\" (string, required) value for the name\n"
"5. \"toaddress\" (string, optional) address to send the name to\n"
"\nResult:\n"
"\"txid\" (string) the name_update's txid\n"
"\nExamples:\n"
+ HelpExampleCli ("name_update", "\"myname\", \"new-value\"")
+ HelpExampleCli ("name_update", "\"myname\", \"new-value\", \"NEX4nME5p3iyNK3gFh4FUeUriHXxEFemo9\"")
+ HelpExampleRpc ("name_update", "\"myname\", \"new-value\"")
);
const std::string nameStr = request.params[0].get_str ();
const valtype name = ValtypeFromString (nameStr);
if (name.size () > MAX_NAME_LENGTH)
throw JSONRPCError (RPC_INVALID_PARAMETER, "the name is too long");
const std::string valueStr = request.params[1].get_str ();
const valtype value = ValtypeFromString (valueStr);
if (value.size () > MAX_VALUE_LENGTH_UI)
throw JSONRPCError (RPC_INVALID_PARAMETER, "the value is too long");
/* Reject updates to a name for which the mempool already has
a pending update. This is not a hard rule enforced by network
rules, but it is necessary with the current mempool implementation. */
{
LOCK (mempool.cs);
if (mempool.updatesName (name))
throw JSONRPCError (RPC_TRANSACTION_ERROR,
"there is already a pending update for this name");
}
CNameData oldData;
{
LOCK (cs_main);
if (!pcoinsTip->GetName (name, oldData) || oldData.isExpired ())
throw JSONRPCError (RPC_TRANSACTION_ERROR,
"this name can not be updated");
}
const COutPoint outp = oldData.getUpdateOutpoint ();
const CTxIn txIn(outp);
/* No more locking required, similarly to name_new. */
EnsureWalletIsUnlocked (pwallet);
CReserveKey keyName(pwallet);
CPubKey pubKeyReserve;
const bool ok = keyName.GetReservedKey (pubKeyReserve, true);
assert (ok);
bool usedKey = false;
CScript addrName;
if (request.params.size () == 3)
{
keyName.ReturnKey ();
const CBitcoinAddress toAddress(request.params[2].get_str ());
if (!toAddress.IsValid ())
throw JSONRPCError (RPC_INVALID_ADDRESS_OR_KEY, "invalid address");
addrName = GetScriptForDestination (toAddress.Get ());
}
else
{
usedKey = true;
addrName = GetScriptForDestination (pubKeyReserve.GetID ());
}
const CScript nameScript
= CNameScript::buildNameUpdate (addrName, name, value);
CWalletTx wtx;
SendMoneyToScript (pwallet, nameScript, &txIn,
NAME_LOCKED_AMOUNT, false, wtx);
if (usedKey)
keyName.KeepKey ();
return wtx.GetHash ().GetHex ();
}
/* ************************************************************************** */
UniValue
sendtoname (const JSONRPCRequest& request)
{
CWallet* const pwallet = GetWalletForJSONRPCRequest(request);
if (!EnsureWalletIsAvailable (pwallet, request.fHelp))
return NullUniValue;
if (request.fHelp || request.params.size () < 2 || request.params.size () > 5)
throw std::runtime_error (
"sendtoname \"name\" amount ( \"comment\" \"comment-to\" subtractfeefromamount )\n"
"\nSend an amount to the owner of a name. "
" The amount is a real and is rounded to the nearest 0.00000001.\n"
"\nIt is an error if the name is expired.\n"
+ HelpRequiringPassphrase (pwallet) +
"\nArguments:\n"
"1. \"name\" (string, required) The name to send to.\n"
"2. \"amount\" (numeric, required) The amount in nmc to send. eg 0.1\n"
"3. \"comment\" (string, optional) A comment used to store what the transaction is for. \n"
" This is not part of the transaction, just kept in your wallet.\n"
"4. \"comment-to\" (string, optional) A comment to store the name of the person or organization \n"
" to which you're sending the transaction. This is not part of the \n"
" transaction, just kept in your wallet.\n"
"5. subtractfeefromamount (boolean, optional, default=false) The fee will be deducted from the amount being sent.\n"
" The recipient will receive less denemecoins than you enter in the amount field.\n"
"\nResult:\n"
"\"transactionid\" (string) The transaction id.\n"
"\nExamples:\n"
+ HelpExampleCli ("sendtoname", "\"id/foobar\" 0.1")
+ HelpExampleCli ("sendtoname", "\"id/foobar\" 0.1 \"donation\" \"seans outpost\"")
+ HelpExampleCli ("sendtoname", "\"id/foobar\" 0.1 \"\" \"\" true")
+ HelpExampleRpc ("sendtoname", "\"id/foobar\", 0.1, \"donation\", \"seans outpost\"")
);
if (IsInitialBlockDownload ())
throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD,
"Denemecoin is downloading blocks...");
LOCK2 (cs_main, pwallet->cs_wallet);
const std::string nameStr = request.params[0].get_str ();
const valtype name = ValtypeFromString (nameStr);
CNameData data;
if (!pcoinsTip->GetName (name, data))
{
std::ostringstream msg;
msg << "name not found: '" << nameStr << "'";
throw JSONRPCError (RPC_INVALID_ADDRESS_OR_KEY, msg.str ());
}
if (data.isExpired ())
throw JSONRPCError (RPC_INVALID_ADDRESS_OR_KEY, "the name is expired");
/* The code below is strongly based on sendtoaddress. Make sure to
keep it in sync. */
// Amount
CAmount nAmount = AmountFromValue(request.params[1]);
if (nAmount <= 0)
throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount for send");
// Wallet comments
CWalletTx wtx;
if (request.params.size() > 2 && !request.params[2].isNull()
&& !request.params[2].get_str().empty())
wtx.mapValue["comment"] = request.params[2].get_str();
if (request.params.size() > 3 && !request.params[3].isNull()
&& !request.params[3].get_str().empty())
wtx.mapValue["to"] = request.params[3].get_str();
bool fSubtractFeeFromAmount = false;
if (request.params.size() > 4)
fSubtractFeeFromAmount = request.params[4].get_bool();
EnsureWalletIsUnlocked(pwallet);
SendMoneyToScript (pwallet, data.getAddress (), NULL,
nAmount, fSubtractFeeFromAmount, wtx);
return wtx.GetHash ().GetHex ();
}
|
#include <regex>
#include <array>
#include "vcpkg_Environment.h"
#include "vcpkg_Commands.h"
#include "vcpkg.h"
#include "metrics.h"
#include "vcpkg_System.h"
namespace vcpkg {namespace Environment
{
static const fs::path default_cmake_installation_dir = "C:/Program Files/CMake/bin";
static const fs::path default_cmake_installation_dir_x86 = "C:/Program Files (x86)/CMake/bin";
static const fs::path default_git_installation_dir = "C:/Program Files/git/cmd";
static const fs::path default_git_installation_dir_x86 = "C:/Program Files (x86)/git/cmd";
static void ensure_on_path(const std::array<int, 3>& version, const wchar_t* version_check_cmd, const wchar_t* install_cmd)
{
System::exit_code_and_output ec_data = System::cmd_execute_and_capture_output(version_check_cmd);
if (ec_data.exit_code == 0)
{
// version check
std::regex re(R"###((\d+)\.(\d+)\.(\d+))###");
std::match_results<std::string::const_iterator> match;
auto found = std::regex_search(ec_data.output, match, re);
if (found)
{
int d1 = atoi(match[1].str().c_str());
int d2 = atoi(match[2].str().c_str());
int d3 = atoi(match[3].str().c_str());
if (d1 > version[0] || (d1 == version[0] && d2 > version[1]) || (d1 == version[0] && d2 == version[1] && d3 >= version[2]))
{
// satisfactory version found
return;
}
}
}
auto rc = System::cmd_execute(install_cmd);
if (rc)
{
System::println(System::color::error, "Launching powershell failed or was denied");
TrackProperty("error", "powershell install failed");
TrackProperty("installcmd", install_cmd);
exit(rc);
}
}
void ensure_git_on_path(const vcpkg_paths& paths)
{
const fs::path downloaded_git = paths.downloads / "PortableGit" / "cmd";
const std::wstring path_buf = Strings::format(L"%s;%s;%s;%s",
downloaded_git.native(),
System::wdupenv_str(L"PATH"),
default_git_installation_dir.native(),
default_git_installation_dir_x86.native());
_wputenv_s(L"PATH", path_buf.c_str());
static constexpr std::array<int, 3> git_version = {2,0,0};
// TODO: switch out ExecutionPolicy Bypass with "Remove Mark Of The Web" code and restore RemoteSigned
ensure_on_path(git_version, L"git --version 2>&1", L"powershell -ExecutionPolicy Bypass scripts\\fetchDependency.ps1 -Dependency git");
}
void ensure_cmake_on_path(const vcpkg_paths& paths)
{
const fs::path downloaded_cmake = paths.downloads / "cmake-3.5.2-win32-x86" / "bin";
const std::wstring path_buf = Strings::format(L"%s;%s;%s;%s",
downloaded_cmake.native(),
System::wdupenv_str(L"PATH"),
default_cmake_installation_dir.native(),
default_cmake_installation_dir_x86.native());
_wputenv_s(L"PATH", path_buf.c_str());
static constexpr std::array<int, 3> cmake_version = {3,5,0};
// TODO: switch out ExecutionPolicy Bypass with "Remove Mark Of The Web" code and restore RemoteSigned
ensure_on_path(cmake_version, L"cmake --version 2>&1", L"powershell -ExecutionPolicy Bypass scripts\\fetchDependency.ps1 -Dependency cmake");
}
void ensure_nuget_on_path(const vcpkg_paths& paths)
{
const std::wstring path_buf = Strings::format(L"%s;%s", paths.downloads.native(), System::wdupenv_str(L"PATH"));
_wputenv_s(L"PATH", path_buf.c_str());
static constexpr std::array<int, 3> nuget_version = {1,0,0};
// TODO: switch out ExecutionPolicy Bypass with "Remove Mark Of The Web" code and restore RemoteSigned
ensure_on_path(nuget_version, L"nuget 2>&1", L"powershell -ExecutionPolicy Bypass scripts\\fetchDependency.ps1 -Dependency nuget");
}
}}
|
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE590_Free_Of_Invalid_Pointer_Not_On_The_Heap__delete_array_long_long_declare_44.cpp
Label Definition File: CWE590_Free_Of_Invalid_Pointer_Not_On_The_Heap__delete_array.label.xml
Template File: sources-sink-44.tmpl.cpp
*/
/*
* @description
* CWE: 590 Free of Invalid Pointer Not on the Heap
* BadSource: declare Data buffer is declared on the stack
* GoodSource: Allocate memory on the heap
* Sinks:
* BadSink : Print then free data
* Flow Variant: 44 Data/control flow: data passed as an argument from one function to a function in the same source file called via a function pointer
*
* */
#include "std_testcase.h"
#include <wchar.h>
namespace CWE590_Free_Of_Invalid_Pointer_Not_On_The_Heap__delete_array_long_long_declare_44
{
#ifndef OMITBAD
static void bad_sink(long long * data)
{
printLongLongLine(data[0]);
/* POTENTIAL FLAW: Possibly deallocating memory allocated on the stack */
delete [] data;
}
void bad()
{
long long * data;
/* define a function pointer */
void (*func_ptr) (long long *) = bad_sink;
data = NULL; /* Initialize data */
{
/* FLAW: data is allocated on the stack and deallocated in the BadSink */
long long data_buf[100];
{
size_t i;
for (i = 0; i < 100; i++)
{
data_buf[i] = 5L;
}
}
data = data_buf;
}
/* use the function pointer */
func_ptr(data);
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodG2B() uses the GoodSource with the BadSink */
static void goodG2B_sink(long long * data)
{
printLongLongLine(data[0]);
/* POTENTIAL FLAW: Possibly deallocating memory allocated on the stack */
delete [] data;
}
static void goodG2B()
{
long long * data;
void (*func_ptr) (long long *) = goodG2B_sink;
data = NULL; /* Initialize data */
{
/* FIX: data is allocated on the heap and deallocated in the BadSink */
long long * data_buf = new long long[100];
{
size_t i;
for (i = 0; i < 100; i++)
{
data_buf[i] = 5L;
}
}
data = data_buf;
}
func_ptr(data);
}
void good()
{
goodG2B();
}
#endif /* OMITGOOD */
} // close namespace
/* Below is the main(). It is only used when building this testcase on
its own for testing or for building a binary to use in testing binary
analysis tools. It is not used when compiling all the testcases as one
application, which is how source code analysis tools are tested. */
#ifdef INCLUDEMAIN
using namespace CWE590_Free_Of_Invalid_Pointer_Not_On_The_Heap__delete_array_long_long_declare_44; // so that we can use good and bad easily
int main(int argc, char * argv[])
{
/* seed randomness */
srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
printLine("Calling good()...");
good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
|
/*
* Copyright (C) 2014
*
* This program 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 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*
* ====================================================
* __ __ __ _____ __ __
* / / / | / / / ___/ / | / / SEZIONE di BARI
* / / / | |/ / / /_ / | |/ /
* / / / /| / / / __/ / /| / /
* /_/ /_/ |__/ /_/ /_/ |__/
*
* ====================================================
* Written by Giuseppe De Robertis <Giuseppe.DeRobertis@ba.infn.it>, 2014.
*
* 21/12/2015 Added mutex for multithread operation
*/
#include "ipbus.h"
#include "ipbusudp.h"
#include "mexception.h"
#include <iostream>
#include <stdio.h>
#include <cstdio>
#include <stdlib.h>
#include <string>
using namespace std;
// #define TRACE_IPBUS
#ifdef TRACE_IPBUS
#define TRACE(format, args...) {
fprintf(stderr, "%s ", name().c_str());
fprintf(stderr, format, ##args);
fflush(stderr);
}
#else
#define TRACE(format, args...)
#endif
const int IPbus::bufferSize = (int)MosaicIPbus::DEFAULT_PACKET_SIZE;
IPbus::IPbus()
{
txBuffer = new uint8_t[bufferSize];
rxBuffer = new uint8_t[bufferSize];
transactionList = new IPbusTransaction[bufferSize / 4];
transactionId = 0;
lastRxPktId = 0;
clearList();
}
IPbus::~IPbus()
{
delete[] transactionList;
delete txBuffer;
delete rxBuffer;
}
void IPbus::clearList()
{
numTransactions = 0;
txSize = 0;
expectedRxSize = 0;
rxPtr = 0;
}
void IPbus::addWord(uint32_t w)
{
txBuffer[txSize++] = (w >> 24) & 0xff;
txBuffer[txSize++] = (w >> 16) & 0xff;
txBuffer[txSize++] = (w >> 8) & 0xff;
txBuffer[txSize++] = w & 0xff;
}
uint32_t IPbus::getWord()
{
uint32_t w;
w = (rxBuffer[rxPtr++] & 0xff) << 24;
w |= (rxBuffer[rxPtr++] & 0xff) << 16;
w |= (rxBuffer[rxPtr++] & 0xff) << 8;
w |= (rxBuffer[rxPtr++] & 0xff);
return w;
}
void IPbus::addHeader(uint16_t words, uint8_t typeId, uint32_t *readDataPtr)
{
// Avoid consecutive packets with the same transactionId in first IPBUS request
if ((numTransactions == 0) && (transactionId == lastRxPktId)) {
transactionId++;
TRACE("IPbus::addHeader increased transactionId to %d\n", transactionId);
}
// Put the request into the list
transactionList[numTransactions].words = words;
transactionList[numTransactions].transactionId = transactionId;
transactionList[numTransactions].typeId = typeId;
transactionList[numTransactions].readDataPtr = readDataPtr;
// Add the header to the tx buffer
addWord(((int)MosaicIPbus::IPBUS_PROTOCOL_VERSION << 28) | (words << 16) | (transactionId << 8) | ((int)typeId << 4) | ((int)MosaicIPbusInfoCode::infoCodeRequest));
transactionId++;
transactionId &= 0xff;
numTransactions++;
}
void IPbus::getHeader(IPbusTransaction *tr)
{
uint32_t header = getWord();
tr->version = (header >> 28) & 0x0f;
tr->words = (header >> 16) & 0xfff;
tr->transactionId = (header >> 8) & 0xff;
tr->typeId = (header >> 4) & 0xf;
tr->infoCode = header & 0xf;
#ifdef TRACE_IPBUS
// printf("header: %08x\n", header);
#endif
}
void IPbus::chkBuffers(int txTransactionSize, int rxTransactionSize)
{
if ( (bufferSize - txSize) < txTransactionSize ||
(bufferSize - expectedRxSize) < rxTransactionSize ){
#ifdef TRACE_IPBUS
cout << "IPbus::chkBuffers() - flush the command buffer" << endl;
#endif
execute();
}
if (txTransactionSize > bufferSize)
throw MIPBusError("IPbus::chkBuffers() - Tx buffer overflow");
if (rxTransactionSize > bufferSize)
throw MIPBusError("IPbus::chkBuffers() - Rx buffer overflow");
}
void IPbus::addIdle()
{
std::lock_guard<std::recursive_mutex> lock(mutex);
TRACE("IPbus::addIdle\n");
chkBuffers(4, 4);
addHeader(0, MosaicDict::instance().iPbusTransaction(MosaicIPbusTransaction::typeIdIdle), NULL);
expectedRxSize += 4;
}
void IPbus::addWrite(int size, uint32_t address, uint32_t *data)
{
std::lock_guard<std::recursive_mutex> lock(mutex);
TRACE("IPbus::addWrite (size:%d, address:0x%08x, *data:0x%08lx)\n", size, address, (unsigned long) data);
chkBuffers(4 * (size + 2), 4);
addHeader(size, MosaicDict::instance().iPbusTransaction(MosaicIPbusTransaction::typeIdWrite), NULL);
addWord(address);
for (int i = 0; i < size; i++)
addWord(*data++);
expectedRxSize += 4;
}
void IPbus::addNIWrite(int size, uint32_t address, uint32_t *data)
{
std::lock_guard<std::recursive_mutex> lock(mutex);
TRACE("IPbus::addNIWrite (size:%d, address:0x%08x, *data:0x%08lx)\n", size, address,
(unsigned long)data);
chkBuffers(4 * (size + 2), 4);
addHeader(size, MosaicDict::instance().iPbusTransaction(MosaicIPbusTransaction::typeIdNIWrite), NULL);
addWord(address);
for (int i = 0; i < size; i++)
addWord(*data++);
expectedRxSize += 4;
}
void IPbus::addWrite(uint32_t address, uint32_t data)
{
std::lock_guard<std::recursive_mutex> lock(mutex);
TRACE("IPbus::addWrite (address:0x%08x, data:0x%08lx)\n", address, (unsigned long) data);
chkBuffers(4 *(1 + 2), 4);
addHeader(1, MosaicDict::instance().iPbusTransaction(MosaicIPbusTransaction::typeIdWrite), NULL);
addWord(address);
addWord(data);
expectedRxSize += 4;
}
void IPbus::addRead(int size, uint32_t address, uint32_t *data)
{
std::lock_guard<std::recursive_mutex> lock(mutex);
TRACE("IPbus::addRead (size:%d, address:0x%08x, *data:0x%08lx)\n", size, address, (unsigned long) data);
chkBuffers(4 * 2, 4 * (size + 1));
addHeader(size, MosaicDict::instance().iPbusTransaction(MosaicIPbusTransaction::typeIdRead), data);
addWord(address);
expectedRxSize += 4 + size * 4;
}
void IPbus::addNIRead(int size, uint32_t address, uint32_t *data)
{
std::lock_guard<std::recursive_mutex> lock(mutex);
TRACE("IPbus::addMIRead (size:%d, address:0x%08x, *data:0x%08lx)\n", size, address,
(unsigned long)data);
chkBuffers(4 * 2, 4 * (size + 1));
addHeader(size, MosaicDict::instance().iPbusTransaction(MosaicIPbusTransaction::typeIdNIRead), data);
addWord(address);
expectedRxSize += 4 + size * 4;
}
void IPbus::addRMWbits(uint32_t address, uint32_t mask, uint32_t data, uint32_t *rData)
{
std::lock_guard<std::recursive_mutex> lock(mutex);
TRACE("IPbus::addRMWbits (address:0x%08x, mask:0x%08lx, data:0x%08lx)\n", address, (unsigned long) mask, (unsigned long) data);
chkBuffers(4 * (1 + 3), 4 * 2);
addHeader(1, MosaicDict::instance().iPbusTransaction(MosaicIPbusTransaction::typeIdRMWbits), rData);
addWord(address);
addWord(mask);
addWord(data);
expectedRxSize += 8;
}
void IPbus::addRMWsum(uint32_t address, uint32_t data, uint32_t *rData)
{
std::lock_guard<std::recursive_mutex> lock(mutex);
TRACE("IPbus::addRMWsum (address:0x%08x, data:0x%08lx)\n", address, (unsigned long)data);
chkBuffers(4 * (1 + 2), 4 * 2);
addHeader(1, MosaicDict::instance().iPbusTransaction(MosaicIPbusTransaction::typeIdRMWsum), rData);
addWord(address);
addWord(data);
expectedRxSize += 8;
}
bool IPbus::duplicatedRxPkt()
{
std::lock_guard<std::recursive_mutex> lock(mutex);
IPbusTransaction tr;
rxPtr = 0;
getHeader(&tr);
// TRACE("IPbus::duplicatedRxPkt transactionId:%d lastRxPktId:%d\n", tr.transactionId, lastRxPktId);
if (tr.transactionId == lastRxPktId ) {
return true;
}
return false;
}
void IPbus::processAnswer()
{
std::lock_guard<std::recursive_mutex> lock(mutex);
IPbusTransaction tr;
int pktId = 0;
try {
rxPtr = 0;
#ifdef TRACE_IPBUS
dumpRxData();
#endif
for (int i = 0; i < numTransactions; i++){
IPbusUDP *udpbus = dynamic_cast<IPbusUDP *>(this);
string address = "";
if (udpbus) address = udpbus->getIPaddress();
if ((rxSize - rxPtr) < 4){
// printf("\n\n numTransactions:%d size:%d\n\n", numTransactions, rxSize-rxPtr);
throw MIPBusError("Wrong answer size", address);
}
getHeader(&tr);
// check the header
if (tr.version != (int)MosaicIPbus::IPBUS_PROTOCOL_VERSION) {
throw MIPBusError("Wrong version in answer", address);
}
if (tr.transactionId != transactionList[i].transactionId) {
throw MIPBusError("Wrong transaction ID in answer", address);
}
if (i == 0) {
pktId = tr.transactionId;
}
if (tr.typeId != transactionList[i].typeId) {
throw MIPBusError("Wrong transaction type in answer", address);
}
if (tr.infoCode != MosaicDict::instance().iPbusInfoCode(MosaicIPbusInfoCode::infoCodeSuccess)){
switch (tr.infoCode){
case (int)MosaicIPbusInfoCode::infoCodeBadHeader:
throw MIPBusError("Remote bus error BAD HEADER", address);
case (int)MosaicIPbusInfoCode::infoCodeBusErrRead:
throw MIPBusError("Remote bus error in read", address);
case (int)MosaicIPbusInfoCode::infoCodeBusErrWrite:
throw MIPBusErrorWrite("Remote bus error in write", address);
case (int)MosaicIPbusInfoCode::infoCodeBusTimeoutRead:
throw MIPBusErrorReadTimeout("Remote bus timeout in read", address);
case (int)MosaicIPbusInfoCode::infoCodeBusTimeoutWrite:
throw MIPBusError("Remote bus timeout in write", address);
case (int)MosaicIPbusInfoCode::infoCodeBufferOverflaw:
throw MIPBusError("Remote bus overflow TX buffer error", address);
case (int)MosaicIPbusInfoCode::infoCodeBufferUnderflaw:
throw MIPBusError("Remote bus underflow RX buffer error", address);
default: return;
}
}
if (tr.words != transactionList[i].words) {
throw MIPBusError("Wrong number of words in transaction answer", address);
}
// get data
if (tr.typeId == MosaicDict::instance().iPbusTransaction(MosaicIPbusTransaction::typeIdRead) ||
tr.typeId == MosaicDict::instance().iPbusTransaction(MosaicIPbusTransaction::typeIdNIRead) ||
tr.typeId == MosaicDict::instance().iPbusTransaction(MosaicIPbusTransaction::typeIdRMWbits) ||
tr.typeId == MosaicDict::instance().iPbusTransaction(MosaicIPbusTransaction::typeIdRMWsum) ){
if ((rxSize - rxPtr) < (tr.words * 4))
throw MIPBusError("Wrong answer size", address);
if (transactionList[i].readDataPtr != NULL)
for (int j = 0; j < tr.words; j++)
transactionList[i].readDataPtr[j] = getWord();
else
for (int j = 0; j < tr.words; j++)
getWord();
}
}
clearList();
lastRxPktId = pktId; // store the last packet ID
} catch (...) {
clearList();
throw;
}
}
/*
* Debug function tu dump received data
*/
void IPbus::dumpRxData()
{
int rxPtrSave = rxPtr;
printf("Received IPBUS data:\n");
for (int i = 0; i < rxSize; i += 4)
printf("%08x\n", getWord());
rxPtr = rxPtrSave;
}
/*
* Test functions
*/
void IPbus::addBadIdle(bool sendWrongVersion, bool sendWrongInfoCode)
{
std::lock_guard<std::recursive_mutex> lock(mutex);
TRACE("IPbus::addBadIdle\n");
chkBuffers(4, 4);
// modified copy of addHeader function
// void IPbus::addHeader(uint16_t words, uint8_t typeId, uint32_t *readDataPtr)
// addHeader(0, typeIdIdle, NULL);
uint16_t words = 0;
uint8_t typeId = MosaicDict::instance().iPbusTransaction(MosaicIPbusTransaction::typeIdIdle);
uint32_t *readDataPtr = NULL;
// Avoid consecutive packets with the same transactionId in first IPBUS request
if ((numTransactions == 0) && (transactionId == lastRxPktId)) transactionId++;
// Put the request into the list
transactionList[numTransactions].words = words;
transactionList[numTransactions].transactionId = transactionId;
transactionList[numTransactions].typeId = typeId;
transactionList[numTransactions].readDataPtr = readDataPtr;
// Add the header to the tx buffer
unsigned ipProtocol = sendWrongVersion ? MosaicDict::instance().iPbus(MosaicIPbus::WRONG_PROTOCOL_VERSION) : MosaicDict::instance().iPbus(MosaicIPbus::IPBUS_PROTOCOL_VERSION);
unsigned infoCode = sendWrongInfoCode ? MosaicDict::instance().iPbusInfoCode(MosaicIPbusInfoCode::infoCodeBusErrRead) : MosaicDict::instance().iPbusInfoCode(MosaicIPbusInfoCode::infoCodeRequest);
addWord((ipProtocol << 28) | (words << 16) | (transactionId << 8) | (typeId << 4) | infoCode);
transactionId++;
transactionId &= 0xff;
numTransactions++;
expectedRxSize += 4;
}
|
#include "opencv2/text.hpp"
#include "opencv2/highgui.hpp"
#include "opencv2/imgproc.hpp"
#include <sstream>
#include <iostream>
using namespace std;
using namespace cv;
using namespace cv::text;
inline void printHelp()
{
cout << " Demo of wordspotting CNN for text recognition." << endl;
cout << " Max Jaderberg et al.: Reading Text in the Wild with Convolutional Neural Networks, IJCV 2015"<<std::endl<<std::endl;
cout << " Usage: program <input_image>" << endl;
cout << " Caffe Model files (dictnet_vgg.caffemodel, dictnet_vgg_deploy.prototxt, dictnet_vgg_labels.txt)"<<endl;
cout << " must be in the current directory." << endl << endl;
cout << " Obtaining Caffe Model files in linux shell:"<<endl;
cout << " wget http://nicolaou.homouniversalis.org/assets/vgg_text/dictnet_vgg.caffemodel"<<endl;
cout << " wget http://nicolaou.homouniversalis.org/assets/vgg_text/dictnet_vgg_deploy.prototxt"<<endl;
cout << " wget http://nicolaou.homouniversalis.org/assets/vgg_text/dictnet_vgg_labels.txt"<<endl<<endl;
}
int main(int argc, const char * argv[])
{
if (argc != 2)
{
printHelp();
exit(1);
}
Mat image = imread(argv[1], IMREAD_GRAYSCALE);
cout << "Read image (" << argv[1] << "): " << image.size << ", channels: " << image.channels() << ", depth: " << image.depth() << endl;
if (image.empty())
{
printHelp();
exit(1);
}
Ptr<OCRHolisticWordRecognizer> wordSpotter = OCRHolisticWordRecognizer::create("dictnet_vgg_deploy.prototxt", "dictnet_vgg.caffemodel", "dictnet_vgg_labels.txt");
std::string word;
vector<float> confs;
wordSpotter->run(image, word, 0, 0, &confs);
cout << "Detected word: '" << word << "', confidence: " << confs[0] << endl;
}
|
/**
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/**
* @file utils_internal.cc
*/
#include "utils_internal.h"
#include <cassert>
#include "ts/ts.h"
#include <pthread.h>
#include <cstdlib>
#include <cassert>
#include <cstddef>
#include <mutex>
#include "tscpp/api/Plugin.h"
#include "tscpp/api/GlobalPlugin.h"
#include "tscpp/api/Transaction.h"
#include "tscpp/api/TransactionPlugin.h"
#include "tscpp/api/TransformationPlugin.h"
#include "tscpp/api/utils.h"
#include "logging_internal.h"
using namespace atscppapi;
namespace
{
/// The index used to store required transaction based data.
int TRANSACTION_STORAGE_INDEX = -1;
void
resetTransactionHandles(Transaction &transaction, TSEvent event)
{
utils::internal::resetTransactionHandles(transaction);
return;
}
int
handleTransactionEvents(TSCont cont, TSEvent event, void *edata)
{
// This function is only here to clean up Transaction objects
TSHttpTxn ats_txn_handle = static_cast<TSHttpTxn>(edata);
Transaction &transaction = utils::internal::getTransaction(ats_txn_handle);
LOG_DEBUG("Got event %d on continuation %p for transaction (ats pointer %p, object %p)", event, cont, ats_txn_handle,
&transaction);
utils::internal::setTransactionEvent(transaction, event);
switch (event) {
case TS_EVENT_HTTP_POST_REMAP:
transaction.getClientRequest().getUrl().reset();
// This is here to force a refresh of the cached client request url
TSMBuffer hdr_buf;
TSMLoc hdr_loc;
(void)TSHttpTxnClientReqGet(static_cast<TSHttpTxn>(transaction.getAtsHandle()), &hdr_buf, &hdr_loc);
break;
case TS_EVENT_HTTP_SEND_REQUEST_HDR:
case TS_EVENT_HTTP_READ_RESPONSE_HDR:
case TS_EVENT_HTTP_SEND_RESPONSE_HDR:
case TS_EVENT_HTTP_READ_CACHE_HDR:
// the buffer handles may be destroyed in the core during redirect follow
resetTransactionHandles(transaction, event);
break;
case TS_EVENT_HTTP_TXN_CLOSE: { // opening scope to declare plugins variable below
resetTransactionHandles(transaction, event);
const std::list<TransactionPlugin *> &plugins = utils::internal::getTransactionPlugins(transaction);
for (auto plugin : plugins) {
std::shared_ptr<Mutex> trans_mutex = utils::internal::getTransactionPluginMutex(*plugin);
LOG_DEBUG("Locking TransacitonPlugin mutex to delete transaction plugin at %p", plugin);
trans_mutex->lock();
LOG_DEBUG("Locked Mutex...Deleting transaction plugin at %p", plugin);
delete plugin;
trans_mutex->unlock();
}
delete &transaction;
} break;
default:
assert(false); /* we should never get here */
break;
}
TSHttpTxnReenable(ats_txn_handle, TS_EVENT_HTTP_CONTINUE);
return 0;
}
void
setupTransactionManagement()
{
// Reserve a transaction slot
TSAssert(TS_SUCCESS == TSHttpTxnArgIndexReserve("atscppapi", "ATS CPP API", &TRANSACTION_STORAGE_INDEX));
// We must always have a cleanup handler available
TSMutex mutex = nullptr;
TSCont cont = TSContCreate(handleTransactionEvents, mutex);
TSHttpHookAdd(TS_HTTP_POST_REMAP_HOOK, cont);
TSHttpHookAdd(TS_HTTP_SEND_REQUEST_HDR_HOOK, cont);
TSHttpHookAdd(TS_HTTP_READ_RESPONSE_HDR_HOOK, cont);
TSHttpHookAdd(TS_HTTP_SEND_RESPONSE_HDR_HOOK, cont);
TSHttpHookAdd(TS_HTTP_READ_CACHE_HDR_HOOK, cont);
TSHttpHookAdd(TS_HTTP_TXN_CLOSE_HOOK, cont);
}
void inline invokePluginForEvent(Plugin *plugin, TSHttpTxn ats_txn_handle, TSEvent event)
{
Transaction &transaction = utils::internal::getTransaction(ats_txn_handle);
switch (event) {
case TS_EVENT_HTTP_PRE_REMAP:
plugin->handleReadRequestHeadersPreRemap(transaction);
break;
case TS_EVENT_HTTP_POST_REMAP:
plugin->handleReadRequestHeadersPostRemap(transaction);
break;
case TS_EVENT_HTTP_SEND_REQUEST_HDR:
plugin->handleSendRequestHeaders(transaction);
break;
case TS_EVENT_HTTP_READ_RESPONSE_HDR:
plugin->handleReadResponseHeaders(transaction);
break;
case TS_EVENT_HTTP_SEND_RESPONSE_HDR:
plugin->handleSendResponseHeaders(transaction);
break;
case TS_EVENT_HTTP_OS_DNS:
plugin->handleOsDns(transaction);
break;
case TS_EVENT_HTTP_READ_REQUEST_HDR:
plugin->handleReadRequestHeaders(transaction);
break;
case TS_EVENT_HTTP_READ_CACHE_HDR:
plugin->handleReadCacheHeaders(transaction);
break;
case TS_EVENT_HTTP_CACHE_LOOKUP_COMPLETE:
plugin->handleReadCacheLookupComplete(transaction);
break;
default:
assert(false); /* we should never get here */
break;
}
}
} /* anonymous namespace */
Transaction &
utils::internal::getTransaction(TSHttpTxn ats_txn_handle)
{
Transaction *transaction = static_cast<Transaction *>(TSHttpTxnArgGet(ats_txn_handle, TRANSACTION_STORAGE_INDEX));
if (!transaction) {
transaction = new Transaction(static_cast<void *>(ats_txn_handle));
LOG_DEBUG("Created new transaction object at %p for ats pointer %p", transaction, ats_txn_handle);
TSHttpTxnArgSet(ats_txn_handle, TRANSACTION_STORAGE_INDEX, transaction);
}
return *transaction;
}
std::shared_ptr<Mutex>
utils::internal::getTransactionPluginMutex(TransactionPlugin &transaction_plugin)
{
return transaction_plugin.getMutex();
}
TSHttpHookID
utils::internal::convertInternalHookToTsHook(Plugin::HookType hooktype)
{
switch (hooktype) {
case Plugin::HOOK_READ_REQUEST_HEADERS_POST_REMAP:
return TS_HTTP_POST_REMAP_HOOK;
case Plugin::HOOK_READ_REQUEST_HEADERS_PRE_REMAP:
return TS_HTTP_PRE_REMAP_HOOK;
case Plugin::HOOK_READ_RESPONSE_HEADERS:
return TS_HTTP_READ_RESPONSE_HDR_HOOK;
case Plugin::HOOK_SEND_REQUEST_HEADERS:
return TS_HTTP_SEND_REQUEST_HDR_HOOK;
case Plugin::HOOK_SEND_RESPONSE_HEADERS:
return TS_HTTP_SEND_RESPONSE_HDR_HOOK;
case Plugin::HOOK_OS_DNS:
return TS_HTTP_OS_DNS_HOOK;
case Plugin::HOOK_READ_REQUEST_HEADERS:
return TS_HTTP_READ_REQUEST_HDR_HOOK;
case Plugin::HOOK_READ_CACHE_HEADERS:
return TS_HTTP_READ_CACHE_HDR_HOOK;
case Plugin::HOOK_CACHE_LOOKUP_COMPLETE:
return TS_HTTP_CACHE_LOOKUP_COMPLETE_HOOK;
case Plugin::HOOK_SELECT_ALT:
return TS_HTTP_SELECT_ALT_HOOK;
default:
assert(false); // shouldn't happen, let's catch it early
break;
}
return static_cast<TSHttpHookID>(-1);
}
TSHttpHookID
utils::internal::convertInternalTransformationTypeToTsHook(TransformationPlugin::Type type)
{
switch (type) {
case TransformationPlugin::RESPONSE_TRANSFORMATION:
return TS_HTTP_RESPONSE_TRANSFORM_HOOK;
case TransformationPlugin::REQUEST_TRANSFORMATION:
return TS_HTTP_REQUEST_TRANSFORM_HOOK;
case TransformationPlugin::SINK_TRANSFORMATION:
return TS_HTTP_RESPONSE_CLIENT_HOOK;
default:
assert(false); // shouldn't happen, let's catch it early
break;
}
return static_cast<TSHttpHookID>(-1);
}
void
utils::internal::invokePluginForEvent(TransactionPlugin *plugin, TSHttpTxn ats_txn_handle, TSEvent event)
{
std::lock_guard<Mutex> scopedLock(*(plugin->getMutex()));
::invokePluginForEvent(static_cast<Plugin *>(plugin), ats_txn_handle, event);
}
void
utils::internal::invokePluginForEvent(GlobalPlugin *plugin, TSHttpTxn ats_txn_handle, TSEvent event)
{
::invokePluginForEvent(static_cast<Plugin *>(plugin), ats_txn_handle, event);
}
void
utils::internal::invokePluginForEvent(GlobalPlugin *plugin, TSHttpAltInfo altinfo_handle, TSEvent event)
{
TSMBuffer hdr_buf;
TSMLoc hdr_loc;
assert(event == TS_EVENT_HTTP_SELECT_ALT);
TSHttpAltInfoClientReqGet(altinfo_handle, &hdr_buf, &hdr_loc);
const Request clientReq(hdr_buf, hdr_loc); // no MLocRelease needed
TSHttpAltInfoCachedReqGet(altinfo_handle, &hdr_buf, &hdr_loc);
const Request cachedReq(hdr_buf, hdr_loc); // no MLocRelease needed
TSHttpAltInfoCachedRespGet(altinfo_handle, &hdr_buf, &hdr_loc);
Response cachedResp;
cachedResp.init(hdr_buf, hdr_loc); // no MLocRelease needed
plugin->handleSelectAlt(clientReq, cachedReq, cachedResp);
}
std::string
utils::internal::consumeFromTSIOBufferReader(TSIOBufferReader reader)
{
std::string str;
int avail = TSIOBufferReaderAvail(reader);
if (avail != TS_ERROR) {
int consumed = 0;
if (avail > 0) {
str.reserve(avail + 1);
int64_t data_len;
const char *char_data;
TSIOBufferBlock block = TSIOBufferReaderStart(reader);
while (block != nullptr) {
char_data = TSIOBufferBlockReadStart(block, reader, &data_len);
str.append(char_data, data_len);
consumed += data_len;
block = TSIOBufferBlockNext(block);
}
}
TSIOBufferReaderConsume(reader, consumed);
} else {
LOG_ERROR("TSIOBufferReaderAvail returned error code %d for reader %p", avail, reader);
}
return str;
}
HttpVersion
utils::internal::getHttpVersion(TSMBuffer hdr_buf, TSMLoc hdr_loc)
{
int version = TSHttpHdrVersionGet(hdr_buf, hdr_loc);
if (version != TS_ERROR) {
if ((TS_HTTP_MAJOR(version) == 0) && (TS_HTTP_MINOR(version) == 0)) {
return HTTP_VERSION_0_9;
}
if ((TS_HTTP_MAJOR(version) == 1) && (TS_HTTP_MINOR(version) == 0)) {
return HTTP_VERSION_1_0;
}
if ((TS_HTTP_MAJOR(version) == 1) && (TS_HTTP_MINOR(version) == 1)) {
return HTTP_VERSION_1_1;
} else {
LOG_ERROR("Unrecognized version %d", version);
}
} else {
LOG_ERROR("Could not get version; hdr_buf %p, hdr_loc %p", hdr_buf, hdr_loc);
}
return HTTP_VERSION_UNKNOWN;
}
void
utils::internal::initTransactionManagement()
{
static pthread_once_t setup_pthread_once_control = PTHREAD_ONCE_INIT;
pthread_once(&setup_pthread_once_control, setupTransactionManagement);
}
|
#pragma once
#include "LayoutControl.hpp"
#include "cru/common/Base.hpp"
#include "cru/common/Event.hpp"
#include "cru/platform/gui/Base.hpp"
#include "cru/platform/gui/Window.hpp"
#include "cru/ui/Base.hpp"
#include "cru/ui/host/WindowHost.hpp"
namespace cru::ui::controls {
class CRU_UI_API RootControl : public LayoutControl {
protected:
explicit RootControl(Control* attached_control);
public:
CRU_DELETE_COPY(RootControl)
CRU_DELETE_MOVE(RootControl)
~RootControl() override;
public:
render::RenderObject* GetRenderObject() const override;
platform::gui::INativeWindow* GetNativeWindow();
protected:
void SetGainFocusOnCreateAndDestroyWhenLoseFocus(bool value);
private:
std::unique_ptr<host::WindowHost> window_host_;
std::unique_ptr<render::StackLayoutRenderObject> render_object_;
Control* attached_control_;
EventRevokerListGuard
gain_focus_on_create_and_destroy_when_lose_focus_event_guard_;
};
} // namespace cru::ui::controls
|
#include "stdafx.h"
#include "Blur.h"
Blur::Blur(ExecuteValues * values)
: Render2D(values, Shaders + L"032_Blur.hlsl")
{
buffer = new Buffer();
}
Blur::~Blur()
{
SAFE_DELETE(buffer);
}
void Blur::Render()
{
ImGui::Separator();
ImGui::SliderInt("Blur Select", &buffer->Data.Select, 0, 2);
ImGui::SliderInt("Blur Count", &buffer->Data.Count, 0, 20);
ImGui::Separator();
D3DXVECTOR2 scale = Scale();
buffer->Data.Width = (int)scale.x;
buffer->Data.Height = (int)scale.y;
buffer->SetPSBuffer(10);
__super::Render();
}
|
/**
******************************************************************************
* Xenia : Xbox 360 Emulator Research Project *
******************************************************************************
* Copyright 2020 Ben Vanik. All rights reserved. *
* Released under the BSD license - see LICENSE in the root for more details. *
******************************************************************************
*/
#include "xenia/kernel/xboxkrnl/xboxkrnl_module.h"
#include <vector>
#include "third_party/fmt/include/fmt/format.h"
#include "xenia/base/clock.h"
#include "xenia/base/debugging.h"
#include "xenia/base/logging.h"
#include "xenia/base/math.h"
#include "xenia/cpu/ppc/ppc_context.h"
#include "xenia/cpu/processor.h"
#include "xenia/emulator.h"
#include "xenia/kernel/kernel_state.h"
#include "xenia/kernel/user_module.h"
#include "xenia/kernel/xboxkrnl/cert_monitor.h"
#include "xenia/kernel/xboxkrnl/debug_monitor.h"
#include "xenia/kernel/xboxkrnl/xboxkrnl_private.h"
#include "xenia/kernel/xthread.h"
DEFINE_string(cl, "", "Specify additional command-line provided to guest.",
"Kernel");
DEFINE_bool(kernel_debug_monitor, false, "Enable debug monitor.", "Kernel");
DEFINE_bool(kernel_cert_monitor, false, "Enable cert monitor.", "Kernel");
DEFINE_bool(kernel_pix, false, "Enable PIX.", "Kernel");
namespace xe {
namespace kernel {
namespace xboxkrnl {
bool XboxkrnlModule::SendPIXCommand(const char* cmd) {
if (!cvars::kernel_pix) {
return false;
}
auto global_lock = global_critical_region_.Acquire();
if (!XThread::IsInThread()) {
assert_always();
return false;
}
uint32_t scratch_size = 260 + 260;
auto scratch_ptr = memory_->SystemHeapAlloc(scratch_size);
auto scratch = memory_->TranslateVirtual(scratch_ptr);
std::memset(scratch, 0, scratch_size);
auto response = reinterpret_cast<char*>(scratch + 0);
auto command = reinterpret_cast<char*>(scratch + 260);
fmt::format_to_n(command, 259, "PIX!m!{}", cmd);
global_lock.unlock();
uint64_t args[] = {scratch_ptr + 260, scratch_ptr, 260};
auto result = kernel_state_->processor()->Execute(
XThread::GetCurrentThread()->thread_state(), pix_function_, args,
xe::countof(args));
global_lock.lock();
XELOGD("PIX(command): {}", cmd);
XELOGD("PIX(response): {}", response);
memory_->SystemHeapFree(scratch_ptr);
if (XSUCCEEDED(result)) {
return true;
}
return false;
}
XboxkrnlModule::XboxkrnlModule(Emulator* emulator, KernelState* kernel_state)
: KernelModule(kernel_state, "xe:\\xboxkrnl.exe"),
timestamp_timer_(nullptr) {
RegisterExportTable(export_resolver_);
// Register all exported functions.
#define XE_MODULE_EXPORT_GROUP(m, n) \
Register##n##Exports(export_resolver_, kernel_state_);
#include "xboxkrnl_module_export_groups.inc"
#undef XE_MODULE_EXPORT_GROUP
// KeDebugMonitorData (?*)
// Set to a valid value when a remote debugger is attached.
// Offset 0x18 is a 4b pointer to a handler function that seems to take two
// arguments. If we wanted to see what would happen we could fake that.
uint32_t pKeDebugMonitorData;
if (!cvars::kernel_debug_monitor) {
pKeDebugMonitorData = memory_->SystemHeapAlloc(4);
auto lpKeDebugMonitorData = memory_->TranslateVirtual(pKeDebugMonitorData);
xe::store_and_swap<uint32_t>(lpKeDebugMonitorData, 0);
} else {
pKeDebugMonitorData =
memory_->SystemHeapAlloc(4 + sizeof(X_KEDEBUGMONITORDATA));
xe::store_and_swap<uint32_t>(memory_->TranslateVirtual(pKeDebugMonitorData),
pKeDebugMonitorData + 4);
auto lpKeDebugMonitorData =
memory_->TranslateVirtual<X_KEDEBUGMONITORDATA*>(pKeDebugMonitorData +
4);
std::memset(lpKeDebugMonitorData, 0, sizeof(X_KEDEBUGMONITORDATA));
lpKeDebugMonitorData->callback_fn =
GenerateTrampoline("KeDebugMonitorCallback", KeDebugMonitorCallback);
}
export_resolver_->SetVariableMapping(
"xboxkrnl.exe", ordinals::KeDebugMonitorData, pKeDebugMonitorData);
// KeCertMonitorData (?*)
// Always set to zero, ignored.
uint32_t pKeCertMonitorData;
if (!cvars::kernel_cert_monitor) {
pKeCertMonitorData = memory_->SystemHeapAlloc(4);
auto lpKeCertMonitorData = memory_->TranslateVirtual(pKeCertMonitorData);
xe::store_and_swap<uint32_t>(lpKeCertMonitorData, 0);
} else {
pKeCertMonitorData =
memory_->SystemHeapAlloc(4 + sizeof(X_KECERTMONITORDATA));
xe::store_and_swap<uint32_t>(memory_->TranslateVirtual(pKeCertMonitorData),
pKeCertMonitorData + 4);
auto lpKeCertMonitorData =
memory_->TranslateVirtual<X_KECERTMONITORDATA*>(pKeCertMonitorData + 4);
std::memset(lpKeCertMonitorData, 0, sizeof(X_KECERTMONITORDATA));
lpKeCertMonitorData->callback_fn =
GenerateTrampoline("KeCertMonitorCallback", KeCertMonitorCallback);
}
export_resolver_->SetVariableMapping(
"xboxkrnl.exe", ordinals::KeCertMonitorData, pKeCertMonitorData);
// XboxHardwareInfo (XboxHardwareInfo_t, 16b)
// flags cpu# ? ? ? ? ? ?
// 0x00000000, 0x06, 0x00, 0x00, 0x00, 0x00000000, 0x0000, 0x0000
// Games seem to check if bit 26 (0x20) is set, which at least for xbox1
// was whether an HDD was present. Not sure what the other flags are.
//
// aomega08 says the value is 0x02000817, bit 27: debug mode on.
// When that is set, though, allocs crash in weird ways.
//
// From kernel dissasembly, after storage is initialized
// XboxHardwareInfo flags is set with flag 5 (0x20).
uint32_t pXboxHardwareInfo = memory_->SystemHeapAlloc(16);
auto lpXboxHardwareInfo = memory_->TranslateVirtual(pXboxHardwareInfo);
export_resolver_->SetVariableMapping(
"xboxkrnl.exe", ordinals::XboxHardwareInfo, pXboxHardwareInfo);
xe::store_and_swap<uint32_t>(lpXboxHardwareInfo + 0, 0x20); // flags
xe::store_and_swap<uint8_t>(lpXboxHardwareInfo + 4, 0x06); // cpu count
// Remaining 11b are zeroes?
// ExConsoleGameRegion, probably same values as keyvault region uses?
// Just return all 0xFF, should satisfy anything that checks it
uint32_t pExConsoleGameRegion = memory_->SystemHeapAlloc(4);
auto lpExConsoleGameRegion = memory_->TranslateVirtual(pExConsoleGameRegion);
export_resolver_->SetVariableMapping(
"xboxkrnl.exe", ordinals::ExConsoleGameRegion, pExConsoleGameRegion);
xe::store<uint32_t>(lpExConsoleGameRegion, 0xFFFFFFFF);
// XexExecutableModuleHandle (?**)
// Games try to dereference this to get a pointer to some module struct.
// So far it seems like it's just in loader code, and only used to look up
// the XexHeaderBase for use by RtlImageXexHeaderField.
// We fake it so that the address passed to that looks legit.
// 0x80100FFC <- pointer to structure
// 0x80101000 <- our module structure
// 0x80101058 <- pointer to xex header
// 0x80101100 <- xex header base
uint32_t ppXexExecutableModuleHandle = memory_->SystemHeapAlloc(4);
export_resolver_->SetVariableMapping("xboxkrnl.exe",
ordinals::XexExecutableModuleHandle,
ppXexExecutableModuleHandle);
// ExLoadedImageName (char*)
// The full path to loaded image/xex including its name.
// Used usually in custom dashboards (Aurora)
// Todo(Gliniak): Confirm that official kernel always allocate space for this
// variable.
uint32_t ppExLoadedImageName =
memory_->SystemHeapAlloc(kExLoadedImageNameSize);
export_resolver_->SetVariableMapping(
"xboxkrnl.exe", ordinals::ExLoadedImageName, ppExLoadedImageName);
// ExLoadedCommandLine (char*)
// The name of the xex. Not sure this is ever really used on real devices.
// Perhaps it's how swap disc/etc data is sent?
// Always set to "default.xex" (with quotes) for now.
// TODO(gibbed): set this to the actual module name.
std::string command_line("\"default.xex\"");
if (cvars::cl.length()) {
command_line += " " + cvars::cl;
}
uint32_t command_line_length =
xe::align(static_cast<uint32_t>(command_line.length()) + 1, 1024u);
uint32_t pExLoadedCommandLine = memory_->SystemHeapAlloc(command_line_length);
auto lpExLoadedCommandLine = memory_->TranslateVirtual(pExLoadedCommandLine);
export_resolver_->SetVariableMapping(
"xboxkrnl.exe", ordinals::ExLoadedCommandLine, pExLoadedCommandLine);
std::memset(lpExLoadedCommandLine, 0, command_line_length);
std::memcpy(lpExLoadedCommandLine, command_line.c_str(),
command_line.length());
// XboxKrnlVersion (8b)
// Kernel version, looks like 2b.2b.2b.2b.
// I've only seen games check >=, so we just fake something here.
uint32_t pXboxKrnlVersion = memory_->SystemHeapAlloc(8);
auto lpXboxKrnlVersion = memory_->TranslateVirtual(pXboxKrnlVersion);
export_resolver_->SetVariableMapping(
"xboxkrnl.exe", ordinals::XboxKrnlVersion, pXboxKrnlVersion);
xe::store_and_swap<uint16_t>(lpXboxKrnlVersion + 0, 2);
xe::store_and_swap<uint16_t>(lpXboxKrnlVersion + 2, 0xFFFF);
xe::store_and_swap<uint16_t>(lpXboxKrnlVersion + 4, 0xFFFF);
xe::store_and_swap<uint8_t>(lpXboxKrnlVersion + 6, 0x80);
xe::store_and_swap<uint8_t>(lpXboxKrnlVersion + 7, 0x00);
// KeTimeStampBundle (ad)
// This must be updated during execution, at 1ms intevals.
// We setup a system timer here to do that.
uint32_t pKeTimeStampBundle = memory_->SystemHeapAlloc(24);
auto lpKeTimeStampBundle = memory_->TranslateVirtual(pKeTimeStampBundle);
export_resolver_->SetVariableMapping(
"xboxkrnl.exe", ordinals::KeTimeStampBundle, pKeTimeStampBundle);
xe::store_and_swap<uint64_t>(lpKeTimeStampBundle + 0, 0);
xe::store_and_swap<uint64_t>(lpKeTimeStampBundle + 8, 0);
xe::store_and_swap<uint32_t>(lpKeTimeStampBundle + 16,
Clock::QueryGuestUptimeMillis());
xe::store_and_swap<uint32_t>(lpKeTimeStampBundle + 20, 0);
timestamp_timer_ = xe::threading::HighResolutionTimer::CreateRepeating(
std::chrono::milliseconds(1), [lpKeTimeStampBundle]() {
xe::store_and_swap<uint32_t>(lpKeTimeStampBundle + 16,
Clock::QueryGuestUptimeMillis());
});
}
static auto& get_xboxkrnl_exports() {
static std::vector<xe::cpu::Export*> xboxkrnl_exports(4096);
return xboxkrnl_exports;
}
xe::cpu::Export* RegisterExport_xboxkrnl(xe::cpu::Export* export_entry) {
auto& xboxkrnl_exports = get_xboxkrnl_exports();
assert_true(export_entry->ordinal < xboxkrnl_exports.size());
xboxkrnl_exports[export_entry->ordinal] = export_entry;
return export_entry;
}
void XboxkrnlModule::RegisterExportTable(
xe::cpu::ExportResolver* export_resolver) {
assert_not_null(export_resolver);
// Build the export table used for resolution.
#include "xenia/kernel/util/export_table_pre.inc"
static xe::cpu::Export xboxkrnl_export_table[] = {
#include "xenia/kernel/xboxkrnl/xboxkrnl_table.inc"
};
#include "xenia/kernel/util/export_table_post.inc"
auto& xboxkrnl_exports = get_xboxkrnl_exports();
for (size_t i = 0; i < xe::countof(xboxkrnl_export_table); ++i) {
auto& export_entry = xboxkrnl_export_table[i];
assert_true(export_entry.ordinal < xboxkrnl_exports.size());
if (!xboxkrnl_exports[export_entry.ordinal]) {
xboxkrnl_exports[export_entry.ordinal] = &export_entry;
}
}
export_resolver->RegisterTable("xboxkrnl.exe", &xboxkrnl_exports);
}
XboxkrnlModule::~XboxkrnlModule() = default;
} // namespace xboxkrnl
} // namespace kernel
} // namespace xe
|
/*
* Copyright (c) 2017, NVIDIA CORPORATION. All rights reserved.
*
* 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 "gstCamera.h"
#include "glDisplay.h"
#include "detectNet.h"
#include "commandLine.h"
#include <signal.h>
bool signal_recieved = false;
void sig_handler(int signo)
{
if( signo == SIGINT )
{
printf("received SIGINT\n");
signal_recieved = true;
}
}
int usage()
{
printf("usage: detectnet-camera [-h] [--network NETWORK] [--threshold THRESHOLD]\n");
printf(" [--camera CAMERA] [--width WIDTH] [--height HEIGHT]\n\n");
printf("Locate objects in a live camera stream using an object detection DNN.\n\n");
printf("optional arguments:\n");
printf(" --help show this help message and exit\n");
printf(" --network NETWORK pre-trained model to load (see below for options)\n");
printf(" --overlay OVERLAY detection overlay flags (e.g. --overlay=box,labels,conf)\n");
printf(" valid combinations are: 'box', 'labels', 'conf', 'none'\n");
printf(" --alpha ALPHA overlay alpha blending value, range 0-255 (default: 120)\n");
printf(" --camera CAMERA index of the MIPI CSI camera to use (e.g. CSI camera 0),\n");
printf(" or for VL42 cameras the /dev/video device to use.\n");
printf(" by default, MIPI CSI camera 0 will be used.\n");
printf(" --width WIDTH desired width of camera stream (default is 1280 pixels)\n");
printf(" --height HEIGHT desired height of camera stream (default is 720 pixels)\n");
printf(" --threshold VALUE minimum threshold for detection (default is 0.5)\n\n");
printf("%s\n", detectNet::Usage());
return 0;
}
int main( int argc, char** argv )
{
/*
* parse command line
*/
commandLine cmdLine(argc, argv);
if( cmdLine.GetFlag("help") )
return usage();
/*
* attach signal handler
*/
if( signal(SIGINT, sig_handler) == SIG_ERR )
printf("\ncan't catch SIGINT\n");
/*
* create the camera device
*/
gstCamera* camera = gstCamera::Create(cmdLine.GetInt("width", gstCamera::DefaultWidth),
cmdLine.GetInt("height", gstCamera::DefaultHeight),
cmdLine.GetString("camera"));
if( !camera )
{
printf("\ndetectnet-camera: failed to initialize camera device\n");
return 0;
}
printf("\ndetectnet-camera: successfully initialized camera device\n");
printf(" width: %u\n", camera->GetWidth());
printf(" height: %u\n", camera->GetHeight());
printf(" depth: %u (bpp)\n\n", camera->GetPixelDepth());
/*
* create detection network
*/
detectNet* net = detectNet::Create(argc, argv);
if( !net )
{
printf("detectnet-camera: failed to load detectNet model\n");
return 0;
}
// parse overlay flags
const uint32_t overlayFlags = detectNet::OverlayFlagsFromStr(cmdLine.GetString("overlay", "box,labels,conf"));
/*
* create openGL window
*/
//glDisplay* display = glDisplay::Create();
//if( !display ) printf("detectnet-camera: failed to create openGL display\n");
/*
* start streaming
*/
if( !camera->Open() )
{
printf("detectnet-camera: failed to open camera for streaming\n");
return 0;
}
printf("detectnet-camera: camera open for streaming\n");
/*
* processing loop
*/
float confidence = 0.0f;
while( !signal_recieved )
{
// capture RGBA image
float* imgRGBA = NULL;
if( !camera->CaptureRGBA(&imgRGBA, 1000) )
printf("detectnet-camera: failed to capture RGBA image from camera\n");
// detect objects in the frame
detectNet::Detection* detections = NULL;
const int numDetections = net->Detect(imgRGBA, camera->GetWidth(), camera->GetHeight(), &detections, overlayFlags);
if( numDetections > 0 )
{
printf("%i objects detected\n", numDetections);
for( int n=0; n < numDetections; n++ )
{
printf("detected obj %i class #%u (%s) confidence=%f\n", n, detections[n].ClassID, net->GetClassDesc(detections[n].ClassID), detections[n].Confidence);
printf("bounding box %i (%f, %f) (%f, %f) w=%f h=%f\n", n, detections[n].Left, detections[n].Top, detections[n].Right, detections[n].Bottom, detections[n].Width(), detections[n].Height());
}
}
// update display
//if( display != NULL )
//{
// render the image
// display->RenderOnce(imgRGBA, camera->GetWidth(), camera->GetHeight());
// update the status bar
// char str[256];
// sprintf(str, "TensorRT %i.%i.%i | %s | Network %.0f FPS", NV_TENSORRT_MAJOR, NV_TENSORRT_MINOR, NV_TENSORRT_PATCH, precisionTypeToStr(net->GetPrecision()), net->GetNetworkFPS());
// display->SetTitle(str);
// check if the user quit
// if( display->IsClosed() )
// signal_recieved = true;
//}
// print out timing info
//net->PrintProfilerTimes();
}
/*
* destroy resources
*/
printf("detectnet-camera: shutting down...\n");
SAFE_DELETE(camera);
//SAFE_DELETE(display);
SAFE_DELETE(net);
printf("detectnet-camera: shutdown complete.\n");
return 0;
}
|
//===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
// <cuda/std/tuple>
// template <class... Types> class tuple;
// template <size_t I, class... Types>
// typename tuple_element<I, tuple<Types...> >::type const&
// get(const tuple<Types...>& t);
// UNSUPPORTED: c++98, c++03, msvc
#include <cuda/std/tuple>
// cuda::std::string not supported
//#include <cuda/std/string>
#include <cuda/std/cassert>
#include "test_macros.h"
struct Empty {};
int main(int, char**)
{
{
typedef cuda::std::tuple<int> T;
const T t(3);
assert(cuda::std::get<0>(t) == 3);
}
// cuda::std::string not supported
/*
{
typedef cuda::std::tuple<cuda::std::string, int> T;
const T t("high", 5);
assert(cuda::std::get<0>(t) == "high");
assert(cuda::std::get<1>(t) == 5);
}
*/
#if TEST_STD_VER > 11
{
typedef cuda::std::tuple<double, int> T;
constexpr T t(2.718, 5);
static_assert(cuda::std::get<0>(t) == 2.718, "");
static_assert(cuda::std::get<1>(t) == 5, "");
}
{
typedef cuda::std::tuple<Empty> T;
constexpr T t{Empty()};
constexpr Empty e = cuda::std::get<0>(t);
((void)e); // Prevent unused warning
}
#endif
// cuda::std::string not supported
/*
{
typedef cuda::std::tuple<double&, cuda::std::string, int> T;
double d = 1.5;
const T t(d, "high", 5);
assert(cuda::std::get<0>(t) == 1.5);
assert(cuda::std::get<1>(t) == "high");
assert(cuda::std::get<2>(t) == 5);
cuda::std::get<0>(t) = 2.5;
assert(cuda::std::get<0>(t) == 2.5);
assert(cuda::std::get<1>(t) == "high");
assert(cuda::std::get<2>(t) == 5);
assert(d == 2.5);
}
*/
{
typedef cuda::std::tuple<double&, int> T;
double d = 1.5;
const T t(d, 5);
assert(cuda::std::get<0>(t) == 1.5);
assert(cuda::std::get<1>(t) == 5);
cuda::std::get<0>(t) = 2.5;
assert(cuda::std::get<0>(t) == 2.5);
assert(cuda::std::get<1>(t) == 5);
assert(d == 2.5);
}
return 0;
}
|
// Copyright 2014 The Chromium OS 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 "login_manager/chrome_setup.h"
#include <sys/stat.h>
#include <unistd.h>
#include <array>
#include <set>
#include <base/bind.h>
#include <base/files/file_path.h>
#include <base/files/file_util.h>
#include <base/hash/sha1.h>
#include <base/json/json_writer.h>
#include <base/logging.h>
#include <base/macros.h>
#include <base/strings/string_number_conversions.h>
#include <base/strings/string_split.h>
#include <base/strings/stringprintf.h>
#include <base/values.h>
#include <brillo/userdb_utils.h>
#include <chromeos-config/libcros_config/cros_config_interface.h>
#include <chromeos/ui/chromium_command_builder.h>
#include <chromeos/ui/util.h>
#include <policy/device_policy.h>
#include <policy/libpolicy.h>
// IMPORTANT: If you want to check for the presence of a new USE flag within
// this file via UseFlagIsSet(), you need to add it to the IUSE list in the
// libchromeos-use-flags package's ebuild file. See docs/flags.md for more
// information about this file.
using chromeos::ui::ChromiumCommandBuilder;
using chromeos::ui::util::EnsureDirectoryExists;
namespace login_manager {
constexpr char kUiPath[] = "/ui";
constexpr char kSerializedAshFlagsProperty[] = "serialized-ash-flags";
const char kWallpaperProperty[] = "wallpaper";
const char kRegulatoryLabelProperty[] = "regulatory-label";
const char kPowerButtonPositionPath[] = "/ui/power-button";
const char kPowerButtonEdgeField[] = "edge";
const char kPowerButtonPositionField[] = "position";
const char kSideVolumeButtonPath[] = "/ui/side-volume-button";
const char kSideVolumeButtonRegion[] = "region";
const char kSideVolumeButtonSide[] = "side";
const char kHardwarePropertiesPath[] = "/hardware-properties";
const char kStylusCategoryField[] = "stylus-category";
const char kDisplayCategoryField[] = "display-type";
constexpr char kFingerprintPath[] = "/fingerprint";
constexpr char kFingerprintSensorLocationField[] = "sensor-location";
constexpr char kArcScalePath[] = "/arc";
constexpr char kArcScaleProperty[] = "scale";
constexpr char kInstantTetheringPath[] = "/cross-device/instant-tethering";
constexpr char kDisableInstantTetheringProperty[] = "disable-instant-tethering";
constexpr char kOzoneNNPalmPropertiesPath[] = "/nnpalm";
constexpr char kOzoneNNPalmCompatibleProperty[] = "touch-compatible";
constexpr char kOzoneNNPalmRadiusProperty[] = "radius-polynomial";
constexpr std::array<const char*, 2> kOzoneNNPalmOptionalProperties = {
kOzoneNNPalmCompatibleProperty, kOzoneNNPalmRadiusProperty};
constexpr char kArcBuildPropertiesPath[] = "/arc/build-properties";
constexpr std::array<const char*, 2> kArcBuildProperties = {"device",
"product"};
constexpr std::array<const char*, 4> kArcOptionalBuildProperties = {
"first-api-level", "marketing-name", "metrics-tag", "pai-regions"};
const char kPowerPath[] = "/power";
const char kAllowAmbientEQField[] = "allow-ambient-eq";
const char kAllowAmbientEQFeature[] = "AllowAmbientEQ";
constexpr char kEnableCrashpadFlag[] = "--enable-crashpad";
constexpr char kEnableBreakpadFlag[] = "--no-enable-crashpad";
// These hashes are only being used temporarily till we can determine if a
// device is a Chromebox for Meetings or not from the Install Time attributes.
// TODO(rkc, pbos): Remove these and related code once crbug.com/706523 is
// fixed.
const char* kChromeboxForMeetingAppIdHashes[] = {
"E703483CEF33DEC18B4B6DD84B5C776FB9182BDB",
"A3BC37E2148AC4E99BE4B16AF9D42DD1E592BBBE",
"1C93BD3CF875F4A73C0B2A163BB8FBDA8B8B3D80",
"307E96539209F95A1A8740C713E6998A73657D96",
"4F25792AF1AA7483936DE29C07806F203C7170A0",
"BD8781D757D830FC2E85470A1B6E8A718B7EE0D9",
"4AC2B6C63C6480D150DFDA13E4A5956EB1D0DDBB",
"81986D4F846CEDDDB962643FA501D1780DD441BB",
};
namespace {
// Path to file containing developer-supplied modifications to Chrome's
// environment and command line. Passed to
// ChromiumCommandBuilder::ApplyUserConfig().
const char kChromeDevConfigPath[] = "/etc/chrome_dev.conf";
// Returns a base::FilePath corresponding to the DATA_DIR environment variable.
base::FilePath GetDataDir(ChromiumCommandBuilder* builder) {
return base::FilePath(builder->ReadEnvVar("DATA_DIR"));
}
// Returns a base::FilePath corresponding to the subdirectory of DATA_DIR where
// user data is stored.
base::FilePath GetUserDir(ChromiumCommandBuilder* builder) {
return base::FilePath(GetDataDir(builder).Append("user"));
}
// Enables the "AutoNightLight" feature if "auto-night-light" is set to "True"
// in cros_config.
void SetUpAutoNightLightFlag(ChromiumCommandBuilder* builder,
brillo::CrosConfigInterface* cros_config) {
std::string auto_night_light_str;
if (!cros_config ||
!cros_config->GetString("/", "auto-night-light", &auto_night_light_str)) {
return;
}
if (auto_night_light_str != "true")
return;
builder->AddFeatureEnableOverride("AutoNightLight");
}
// Called by AddUiFlags() to take a wallpaper flag type ("default" or "guest"
// or "child") and file type (e.g. "child", "default", "oem", "guest") and
// add the corresponding flags to |builder| if the files exist. Returns false
// if the files don't exist.
bool AddWallpaperFlags(
ChromiumCommandBuilder* builder,
const std::string& flag_type,
const std::string& file_type,
base::Callback<bool(const base::FilePath&)> path_exists) {
const base::FilePath large_path(base::StringPrintf(
"/usr/share/chromeos-assets/wallpaper/%s_large.jpg", file_type.c_str()));
const base::FilePath small_path(base::StringPrintf(
"/usr/share/chromeos-assets/wallpaper/%s_small.jpg", file_type.c_str()));
if (!path_exists.Run(large_path) || !path_exists.Run(small_path)) {
LOG(WARNING) << "Could not find both paths: " << large_path.MaybeAsASCII()
<< " and " << small_path.MaybeAsASCII();
return false;
}
builder->AddArg(base::StringPrintf("--%s-wallpaper-large=%s",
flag_type.c_str(),
large_path.value().c_str()));
builder->AddArg(base::StringPrintf("--%s-wallpaper-small=%s",
flag_type.c_str(),
small_path.value().c_str()));
return true;
}
// Adds ARC related flags.
void AddArcFlags(ChromiumCommandBuilder* builder,
std::set<std::string>* disallowed_params_out,
brillo::CrosConfigInterface* cros_config) {
if (builder->UseFlagIsSet("arc") ||
(builder->UseFlagIsSet("cheets") && builder->is_test_build())) {
builder->AddArg("--arc-availability=officially-supported");
} else if (builder->UseFlagIsSet("cheets")) {
builder->AddArg("--arc-availability=installed");
} else {
// Don't pass ARC availability related flags in chrome_dev.conf to Chrome if
// ARC is not installed at all.
disallowed_params_out->insert("--arc-availability");
disallowed_params_out->insert("--enable-arc");
disallowed_params_out->insert("--arc-available");
disallowed_params_out->insert("-arc-availability");
disallowed_params_out->insert("-enable-arc");
disallowed_params_out->insert("-arc-available");
}
if (builder->UseFlagIsSet("arc_adb_sideloading"))
builder->AddFeatureEnableOverride("ArcAdbSideloading");
if (builder->UseFlagIsSet("arc_transition_m_to_n"))
builder->AddArg("--arc-transition-migration-required");
if (builder->UseFlagIsSet("arc_force_2x_scaling"))
builder->AddArg("--force-remote-shell-scale=2");
if (builder->UseFlagIsSet("arcvm") && !builder->UseFlagIsSet("arcpp"))
builder->AddArg("--enable-arcvm");
// Devices of tablet form factor will have special app behaviour.
if (builder->UseFlagIsSet("tablet_form_factor"))
builder->AddArg("--enable-tablet-form-factor");
std::string arc_scale;
if (cros_config &&
cros_config->GetString(kArcScalePath, kArcScaleProperty, &arc_scale)) {
builder->AddArg("--arc-scale=" + arc_scale);
}
// Pass USE flags of ARM binary translation libraries to Chrome.
if (builder->UseFlagIsSet("houdini"))
builder->AddArg("--enable-houdini");
if (builder->UseFlagIsSet("houdini64"))
builder->AddArg("--enable-houdini64");
if (builder->UseFlagIsSet("ndk_translation"))
builder->AddArg("--enable-ndk-translation");
if (builder->UseFlagIsSet("ndk_translation64"))
builder->AddArg("--enable-ndk-translation64");
if (builder->UseFlagIsSet("arc_native_bridge_64bit_support_experiment"))
builder->AddArg("--arc-enable-native-bridge-64bit-support-experiment");
}
void AddCrostiniFlags(ChromiumCommandBuilder* builder) {
if (builder->UseFlagIsSet("kvm_host")) {
builder->AddFeatureEnableOverride("Crostini");
}
if (builder->UseFlagIsSet("virtio_gpu")) {
builder->AddFeatureEnableOverride("CrostiniGpuSupport");
}
if (builder->UseFlagIsSet("kvm_transition")) {
builder->AddArg("--kernelnext-restrict-vms");
}
}
void AddPluginVmFlags(ChromiumCommandBuilder* builder) {
if (builder->UseFlagIsSet("pita")) {
builder->AddFeatureEnableOverride("PluginVm");
}
if (builder->UseFlagIsSet("pita-camera")) {
builder->AddFeatureEnableOverride("PluginVmShowCameraPermissions");
}
if (builder->UseFlagIsSet("pita-microphone")) {
builder->AddFeatureEnableOverride("PluginVmShowMicrophonePermissions");
}
}
void AddBorealisFlags(ChromiumCommandBuilder* builder) {
if (builder->UseFlagIsSet("borealis_host")) {
builder->AddFeatureEnableOverride("Borealis");
}
}
void AddLacrosFlags(ChromiumCommandBuilder* builder) {
if (builder->UseFlagIsSet("lacros"))
builder->AddFeatureEnableOverride("LacrosSupport");
}
// Ensures that necessary directory exist with the correct permissions and sets
// related arguments and environment variables.
void CreateDirectories(ChromiumCommandBuilder* builder) {
const uid_t uid = builder->uid();
const gid_t gid = builder->gid();
const uid_t kRootUid = 0;
const gid_t kRootGid = 0;
const base::FilePath data_dir = GetDataDir(builder);
builder->AddArg("--user-data-dir=" + data_dir.value());
const base::FilePath user_dir = GetUserDir(builder);
CHECK(EnsureDirectoryExists(user_dir, uid, gid, 0755));
// TODO(keescook): Remove Chrome's use of $HOME.
builder->AddEnvVar("HOME", user_dir.value());
// Old builds will have a profile dir that's owned by root; newer ones won't
// have this directory at all.
CHECK(EnsureDirectoryExists(data_dir.Append("Default"), uid, gid, 0755));
const base::FilePath state_dir("/run/state");
CHECK(base::DeleteFile(state_dir, true));
CHECK(EnsureDirectoryExists(state_dir, kRootUid, kRootGid, 0710));
// Create a directory where the session manager can store a copy of the user
// policy key, that will be readable by the chrome process as chronos.
const base::FilePath policy_dir("/run/user_policy");
CHECK(base::DeleteFile(policy_dir, true));
CHECK(EnsureDirectoryExists(policy_dir, kRootUid, gid, 0710));
// Create a directory where the chrome process can store a reboot request so
// that it persists across browser crashes but is always removed on reboot.
// This directory also houses the wayland and arc-bridge sockets that are
// exported to VMs and Android.
CHECK(EnsureDirectoryExists(base::FilePath("/run/chrome"), uid, gid, 0755));
// Ensure the existence of the directory in which the whitelist and other
// ownership-related state will live. Yes, it should be owned by root. The
// permissions are set such that the policy-readers group can see the content
// of known files inside whitelist. The policy-readers group is composed of
// the chronos user and other daemon accessing the device policies but not
// anything else.
gid_t policy_readers_gid;
CHECK(brillo::userdb::GetGroupInfo("policy-readers", &policy_readers_gid));
CHECK(EnsureDirectoryExists(base::FilePath("/var/lib/whitelist"), kRootUid,
policy_readers_gid, 0750));
// Create the directory where policies for extensions installed in
// device-local accounts are cached. This data is read and written by chronos.
CHECK(EnsureDirectoryExists(
base::FilePath("/var/cache/device_local_account_component_policy"), uid,
gid, 0700));
// Create the directory where external data referenced by policies is cached
// for device-local accounts. This data is read and written by chronos.
CHECK(EnsureDirectoryExists(
base::FilePath("/var/cache/device_local_account_external_policy_data"),
uid, gid, 0700));
// Create the directory where external data referenced by device policy is
// cached. This data is read and written by chronos.
CHECK(EnsureDirectoryExists(
base::FilePath("/var/cache/device_policy_external_data"), uid, gid,
0700));
// Create the directory where the AppPack extensions are cached.
// These extensions are read and written by chronos.
CHECK(EnsureDirectoryExists(base::FilePath("/var/cache/app_pack"), uid, gid,
0700));
// Create the directory where extensions for device-local accounts are cached.
// These extensions are read and written by chronos.
CHECK(EnsureDirectoryExists(
base::FilePath("/var/cache/device_local_account_extensions"), uid, gid,
0700));
// Create the directory where the Quirks Client can store downloaded
// icc and other display profiles.
CHECK(EnsureDirectoryExists(base::FilePath("/var/cache/display_profiles"),
uid, gid, 0700));
// Create the directory for shared installed extensions.
// Shared extensions are validated at runtime by the browser.
// These extensions are read and written by chronos.
CHECK(EnsureDirectoryExists(base::FilePath("/var/cache/shared_extensions"),
uid, gid, 0700));
// Create the directory where policies for extensions installed in the
// sign-in profile are cached. This data is read and written by chronos.
CHECK(EnsureDirectoryExists(
base::FilePath("/var/cache/signin_profile_component_policy"), uid, gid,
0700));
// Create the directory where extensions for the sign-in profile are cached.
// This data is read and written by chronos.
CHECK(EnsureDirectoryExists(
base::FilePath("/var/cache/signin_profile_extensions"), uid, gid, 0700));
// Tell Chrome where to write logging messages before the user logs in.
base::FilePath system_log_dir("/var/log/chrome");
CHECK(EnsureDirectoryExists(system_log_dir, uid, gid, 0755));
builder->AddEnvVar("CHROME_LOG_FILE",
system_log_dir.Append("chrome").value());
// Log directory for the user session. Note that the user dir won't be mounted
// until later (when the cryptohome is mounted), so we don't create
// CHROMEOS_SESSION_LOG_DIR here.
builder->AddEnvVar("CHROMEOS_SESSION_LOG_DIR",
user_dir.Append("log").value());
// On devices with Chrome OS camera HAL, Chrome needs to host the unix domain
// named socket /run/camera/camera3.sock to provide the camera HAL Mojo
// service to the system.
if (base::PathExists(base::FilePath("/usr/bin/cros_camera_service"))) {
// The socket is created and listened on by Chrome, and receives connections
// from the camera HAL v3 process and cameraserver process in Android
// container which run as group arc-camera. In addition, the camera HAL v3
// process also hosts a unix domain named socket in /run/camera for the
// sandboxed camera library process. Thus the directory is created with
// user chronos and group arc-camera with 0770 permission.
gid_t arc_camera_gid;
CHECK(brillo::userdb::GetGroupInfo("arc-camera", &arc_camera_gid));
CHECK(EnsureDirectoryExists(base::FilePath("/run/camera"), uid,
arc_camera_gid, 0770));
// The /var/cache/camera folder is used to store camera-related configs and
// settings that are either extracted from Android container, or generated
// by the camera HAL at runtime.
CHECK(EnsureDirectoryExists(base::FilePath("/var/cache/camera"), uid,
arc_camera_gid, 0770));
}
// On devices with CUPS proxy daemon, Chrome needs to create the directory so
// cups_proxy can host a unix domain named socket at
// /run/cups_proxy/cups_proxy.sock
if (base::PathExists(base::FilePath("/usr/bin/cups_proxy"))) {
uid_t cups_proxy_uid;
gid_t cups_proxy_gid;
CHECK(brillo::userdb::GetUserInfo("cups-proxy", &cups_proxy_uid,
&cups_proxy_gid));
// TODO(pihsun): Check if this permission is good. We need to add the
// client accessing this to cups_proxy group for this to work.
CHECK(EnsureDirectoryExists(base::FilePath("/run/cups_proxy"),
cups_proxy_uid, cups_proxy_gid, 0770));
}
}
// Adds system-related flags to the command line.
void AddSystemFlags(ChromiumCommandBuilder* builder) {
const base::FilePath data_dir = GetDataDir(builder);
// We need to delete these files as Chrome may have left them around from its
// prior run (if it crashed).
base::DeleteFile(data_dir.Append("SingletonLock"), false);
base::DeleteFile(data_dir.Append("SingletonSocket"), false);
// Some targets (embedded, VMs) do not need component updates.
if (!builder->UseFlagIsSet("compupdates"))
builder->AddArg("--disable-component-update");
if (builder->UseFlagIsSet("smartdim"))
builder->AddFeatureEnableOverride("SmartDim");
// On developer systems, set a flag to let the browser know.
if (builder->is_developer_end_user())
builder->AddArg("--system-developer-mode");
if (builder->UseFlagIsSet("diagnostics"))
builder->AddFeatureEnableOverride("UmaStorageDimensions");
// Enable Wilco only features.
if (builder->UseFlagIsSet("wilco")) {
builder->AddFeatureEnableOverride("WilcoDtc");
// Needed for scheduled update checks on Wilco.
builder->AddArg("--register-max-dark-suspend-delay");
}
// Some platforms have SMT enabled by default.
if (builder->UseFlagIsSet("scheduler_configuration_performance"))
builder->AddArg("--scheduler-configuration-default=performance");
if (builder->UseFlagIsSet("enable_neural_palm_detection_filter"))
builder->AddFeatureEnableOverride("EnableNeuralPalmDetectionFilter");
if (builder->UseFlagIsSet("enable_heuristic_palm_detection_filter"))
builder->AddFeatureEnableOverride("EnableHeuristicPalmDetectionFilter");
if (builder->UseFlagIsSet("ondevice_handwriting"))
builder->AddArg("--ondevice_handwriting=use_rootfs");
else if (builder->UseFlagIsSet("ondevice_handwriting_dlc"))
builder->AddArg("--ondevice_handwriting=use_dlc");
}
// Adds UI-related flags to the command line.
void AddUiFlags(ChromiumCommandBuilder* builder,
brillo::CrosConfigInterface* cros_config) {
const base::FilePath data_dir = GetDataDir(builder);
// Force OOBE on test images that have requested it.
if (base::PathExists(base::FilePath("/root/.test_repeat_oobe"))) {
base::DeleteFile(data_dir.Append(".oobe_completed"), false);
base::DeleteFile(data_dir.Append("Local State"), false);
}
// Disable logging redirection on test images to make debugging easier.
if (builder->is_test_build())
builder->AddArg("--disable-logging-redirect");
if (builder->UseFlagIsSet("cfm_enabled_device") &&
builder->UseFlagIsSet("screenshare_sw_codec")) {
builder->AddFeatureEnableOverride("WebRtcScreenshareSwEncoding");
}
if (builder->UseFlagIsSet("touch_centric_device")) {
// Tapping the power button should turn the screen off in laptop mode.
builder->AddArg("--force-tablet-power-button");
// Show touch centric OOBE screens during the first user run in laptop mode.
builder->AddArg("--oobe-force-tablet-first-run");
}
if (builder->UseFlagIsSet("rialto")) {
builder->AddArg("--enterprise-enable-zero-touch-enrollment=hands-off");
builder->AddArg("--disable-machine-cert-request");
builder->AddArg("--cellular-first");
builder->AddArg(
"--app-mode-oem-manifest=/etc/rialto_overlay_oem_manifest.json");
builder->AddArg("--log-level=0");
builder->AddArg("--disable-logging-redirect");
}
builder->AddArg("--login-manager");
builder->AddArg("--login-profile=user");
if (builder->UseFlagIsSet("natural_scroll_default"))
builder->AddArg("--enable-natural-scroll-default");
if (!builder->UseFlagIsSet("legacy_keyboard"))
builder->AddArg("--has-chromeos-keyboard");
if (builder->UseFlagIsSet("legacy_power_button"))
builder->AddArg("--aura-legacy-power-button");
if (builder->UseFlagIsSet("touchview"))
builder->AddArg("--enable-touchview");
if (builder->UseFlagIsSet("touchscreen_wakeup"))
builder->AddArg("--touchscreen-usable-while-screen-off");
if (builder->UseFlagIsSet("oobe_skip_to_login"))
builder->AddArg("--oobe-skip-to-login");
if (builder->UseFlagIsSet("oobe_skip_postlogin"))
builder->AddArg("--oobe-skip-postlogin");
if (builder->UseFlagIsSet("disable_background_blur"))
builder->AddFeatureDisableOverride("EnableBackgroundBlur");
if (builder->UseFlagIsSet("disable_explicit_dma_fences"))
builder->AddArg("--disable-explicit-dma-fences");
if (builder->UseFlagIsSet("shelf-hotseat"))
builder->AddFeatureEnableOverride("ShelfHotseat");
if (builder->UseFlagIsSet("webui-tab-strip")) {
builder->AddFeatureEnableOverride("WebUITabStrip");
builder->AddFeatureEnableOverride("WebUITabStripTabDragIntegration");
}
SetUpAutoDimFlag(builder, cros_config);
SetUpWallpaperFlags(builder, cros_config, base::Bind(base::PathExists));
// TODO(yongjaek): Remove the following flag when the kiosk mode app is ready
// at crbug.com/309806.
if (builder->UseFlagIsSet("moblab"))
builder->AddArg("--disable-demo-mode");
if (builder->UseFlagIsSet("allow_consumer_kiosk"))
builder->AddArg("--enable-consumer-kiosk");
if (builder->UseFlagIsSet("biod"))
builder->AddFeatureEnableOverride("QuickUnlockFingerprint");
SetUpPowerButtonPositionFlag(builder, cros_config);
SetUpSideVolumeButtonPositionFlag(builder, cros_config);
SetUpRegulatoryLabelFlag(builder, cros_config);
SetUpInternalStylusFlag(builder, cros_config);
SetUpFingerprintSensorLocationFlag(builder, cros_config);
SetUpOzoneNNPalmPropertiesFlag(builder, cros_config);
SetUpArcBuildPropertiesFlag(builder, cros_config);
SetUpAutoNightLightFlag(builder, cros_config);
SetUpAllowAmbientEQFlag(builder, cros_config);
SetUpInstantTetheringFlag(builder, cros_config);
}
// Adds enterprise-related flags to the command line.
void AddEnterpriseFlags(ChromiumCommandBuilder* builder) {
builder->AddArg("--enterprise-enrollment-initial-modulus=15");
builder->AddArg("--enterprise-enrollment-modulus-limit=19");
}
// Adds patterns to the --vmodule flag.
void AddVmodulePatterns(ChromiumCommandBuilder* builder) {
// Turn on logging about external displays being connected and disconnected.
// Different behavior is seen from different displays and these messages are
// used to determine what happened within feedback reports.
builder->AddVmodulePattern("*/ui/display/manager/chromeos/*=1");
// Turn on basic logging for Ozone platform implementations.
builder->AddVmodulePattern("*/ui/ozone/*=1");
// Turn on basic logging for enrollment flow.
builder->AddVmodulePattern("*/browser/chromeos/login/enrollment/*=1");
builder->AddVmodulePattern("enrollment_screen_handler=1");
// TODO(https://crbug.com/907158): Needed for investigating issues with tablet
// mode detection and internal input device event blocking logic.
builder->AddVmodulePattern("*/ash/wm/tablet_mode/*=1");
// TODO(https://crbug.com/943790): Remove after model development is complete.
builder->AddVmodulePattern("*/chromeos/power/auto_screen_brightness/*=1");
// TODO(https://crbug.com/1106586,https://crbug.com/1102123): Remove after
// issues with night light are closed.
builder->AddVmodulePattern("*night_light*=1");
if (builder->UseFlagIsSet("cheets"))
builder->AddVmodulePattern("*arc/*=1");
}
} // namespace
void AddSerializedAshFlags(ChromiumCommandBuilder* builder,
brillo::CrosConfigInterface* cros_config) {
using std::string_literals::operator""s;
std::string serialized_ash_flags;
if (!cros_config->GetString(kUiPath, kSerializedAshFlagsProperty,
&serialized_ash_flags)) {
return;
}
for (const auto& flag :
base::SplitString(serialized_ash_flags, "\0"s, base::KEEP_WHITESPACE,
base::SPLIT_WANT_NONEMPTY)) {
builder->AddArg(flag);
}
}
void SetUpRegulatoryLabelFlag(ChromiumCommandBuilder* builder,
brillo::CrosConfigInterface* cros_config) {
std::string subdir;
if (cros_config &&
cros_config->GetString("/", kRegulatoryLabelProperty, &subdir)) {
builder->AddArg("--regulatory-label-dir=" + subdir);
}
}
void SetUpWallpaperFlags(
ChromiumCommandBuilder* builder,
brillo::CrosConfigInterface* cros_config,
base::Callback<bool(const base::FilePath&)> path_exists) {
AddWallpaperFlags(builder, "guest", "guest", path_exists);
AddWallpaperFlags(builder, "child", "child", path_exists);
// Use the configuration if available.
std::string filename;
if (cros_config &&
cros_config->GetString("/", kWallpaperProperty, &filename) &&
AddWallpaperFlags(builder, "default", filename, path_exists)) {
// If there's a wallpaper defined in cros config, mark this as an OEM
// wallpaper.
builder->AddArg("--default-wallpaper-is-oem");
return;
}
// Fall back to oem.
if (AddWallpaperFlags(builder, "default", "oem", path_exists)) {
builder->AddArg("--default-wallpaper-is-oem");
return;
}
// Fall back to default.
AddWallpaperFlags(builder, "default", "default", path_exists);
}
void SetUpInternalStylusFlag(ChromiumCommandBuilder* builder,
brillo::CrosConfigInterface* cros_config) {
std::string stylus_category;
if (cros_config &&
cros_config->GetString(kHardwarePropertiesPath, kStylusCategoryField,
&stylus_category) &&
stylus_category == "internal") {
builder->AddArg("--has-internal-stylus");
}
}
void SetUpFingerprintSensorLocationFlag(
ChromiumCommandBuilder* builder, brillo::CrosConfigInterface* cros_config) {
std::string fingerprint_sensor_location;
if (!cros_config ||
!cros_config->GetString(kFingerprintPath, kFingerprintSensorLocationField,
&fingerprint_sensor_location)) {
return;
}
if (fingerprint_sensor_location != "none") {
builder->AddArg(base::StringPrintf("--fingerprint-sensor-location=%s",
fingerprint_sensor_location.c_str()));
}
}
void SetUpAutoDimFlag(ChromiumCommandBuilder* builder,
brillo::CrosConfigInterface* cros_config) {
std::string display_type;
if (cros_config &&
cros_config->GetString(kHardwarePropertiesPath, kDisplayCategoryField,
&display_type) &&
display_type == "old") {
builder->AddArg("--enable-dim-shelf");
}
}
void SetUpPowerButtonPositionFlag(ChromiumCommandBuilder* builder,
brillo::CrosConfigInterface* cros_config) {
std::string edge_as_string, position_as_string;
if (!cros_config ||
!cros_config->GetString(kPowerButtonPositionPath, kPowerButtonEdgeField,
&edge_as_string) ||
!cros_config->GetString(kPowerButtonPositionPath,
kPowerButtonPositionField, &position_as_string)) {
return;
}
double position_as_double = 0;
if (!base::StringToDouble(position_as_string, &position_as_double)) {
LOG(ERROR) << "Invalid value for power button position: "
<< position_as_string;
return;
}
base::DictionaryValue position_info;
position_info.SetString(kPowerButtonEdgeField, edge_as_string);
position_info.SetDouble(kPowerButtonPositionField, position_as_double);
std::string json_position_info;
base::JSONWriter::Write(position_info, &json_position_info);
builder->AddArg(base::StringPrintf("--ash-power-button-position=%s",
json_position_info.c_str()));
}
void SetUpSideVolumeButtonPositionFlag(
ChromiumCommandBuilder* builder, brillo::CrosConfigInterface* cros_config) {
std::string region_as_string, side_as_string;
if (!cros_config ||
!cros_config->GetString(kSideVolumeButtonPath, kSideVolumeButtonRegion,
®ion_as_string) ||
!cros_config->GetString(kSideVolumeButtonPath, kSideVolumeButtonSide,
&side_as_string)) {
return;
}
base::DictionaryValue position_info;
position_info.SetString(kSideVolumeButtonRegion, region_as_string);
position_info.SetString(kSideVolumeButtonSide, side_as_string);
std::string json_position_info;
if (!base::JSONWriter::Write(position_info, &json_position_info)) {
LOG(ERROR) << "JSONWriter::Write failed in writing side volume button "
<< "position info.";
return;
}
builder->AddArg("--ash-side-volume-button-position=" + json_position_info);
}
void SetUpOzoneNNPalmPropertiesFlag(ChromiumCommandBuilder* builder,
brillo::CrosConfigInterface* cros_config) {
base::DictionaryValue info;
if (cros_config) {
std::string value;
for (const char* property : kOzoneNNPalmOptionalProperties) {
if (cros_config->GetString(kOzoneNNPalmPropertiesPath, property,
&value)) {
info.SetString(property, value);
continue;
}
}
}
std::string json_info;
if (!base::JSONWriter::Write(info, &json_info)) {
LOG(ERROR)
<< "JSONWriter::Write failed in writing Ozone NNPalm properties.";
return;
}
builder->AddArg("--ozone-nnpalm-properties=" + json_info);
}
void SetUpArcBuildPropertiesFlag(ChromiumCommandBuilder* builder,
brillo::CrosConfigInterface* cros_config) {
base::DictionaryValue info;
if (cros_config) {
std::string value;
for (const char* property : kArcBuildProperties) {
if (cros_config->GetString(kArcBuildPropertiesPath, property, &value)) {
info.SetString(property, value);
continue;
}
LOG(ERROR) << property << " is not found in cros config";
}
for (const char* property : kArcOptionalBuildProperties) {
if (cros_config->GetString(kArcBuildPropertiesPath, property, &value))
info.SetString(property, value);
}
}
std::string json_info;
if (!base::JSONWriter::Write(info, &json_info)) {
LOG(ERROR)
<< "JSONWriter::Write failed in writing ARC build properties info";
return;
}
builder->AddArg("--arc-build-properties=" + json_info);
}
// Enables the "AllowAmbientEQ" feature if "allow-ambient-eq" is set to "1"
// in cros_config.
void SetUpAllowAmbientEQFlag(ChromiumCommandBuilder* builder,
brillo::CrosConfigInterface* cros_config) {
std::string allow_ambient_eq_str;
if (!cros_config || !cros_config->GetString(kPowerPath, kAllowAmbientEQField,
&allow_ambient_eq_str)) {
return;
}
if (allow_ambient_eq_str != "1")
return;
builder->AddFeatureEnableOverride("AllowAmbientEQ");
}
void SetUpInstantTetheringFlag(ChromiumCommandBuilder* builder,
brillo::CrosConfigInterface* cros_config) {
if (builder->UseFlagIsSet("disable_instant_tethering")) {
builder->AddFeatureDisableOverride("InstantTethering");
return;
}
std::string disable_instant_tethering_str;
if (!cros_config || !cros_config->GetString(kInstantTetheringPath,
kDisableInstantTetheringProperty,
&disable_instant_tethering_str)) {
return;
}
if (disable_instant_tethering_str == "true")
builder->AddFeatureDisableOverride("InstantTethering");
}
void AddCrashHandlerFlag(ChromiumCommandBuilder* builder) {
builder->AddArg(builder->UseFlagIsSet("force_breakpad")
? kEnableBreakpadFlag
: kEnableCrashpadFlag);
}
void PerformChromeSetup(brillo::CrosConfigInterface* cros_config,
bool* is_developer_end_user_out,
std::map<std::string, std::string>* env_vars_out,
std::vector<std::string>* args_out,
uid_t* uid_out) {
DCHECK(env_vars_out);
DCHECK(args_out);
DCHECK(uid_out);
ChromiumCommandBuilder builder;
std::set<std::string> disallowed_prefixes;
CHECK(builder.Init());
CHECK(builder.SetUpChromium());
// Please add new code to the most-appropriate helper function instead of
// putting it here. Things that apply to all Chromium-derived binaries (e.g.
// app_shell, content_shell, etc.) rather than just to Chrome belong in the
// ChromiumCommandBuilder class instead.
CreateDirectories(&builder);
AddSerializedAshFlags(&builder, cros_config);
AddSystemFlags(&builder);
AddUiFlags(&builder, cros_config);
AddArcFlags(&builder, &disallowed_prefixes, cros_config);
AddCrostiniFlags(&builder);
AddPluginVmFlags(&builder);
AddBorealisFlags(&builder);
AddLacrosFlags(&builder);
AddEnterpriseFlags(&builder);
AddVmodulePatterns(&builder);
AddCrashHandlerFlag(&builder);
// Apply any modifications requested by the developer.
if (builder.is_developer_end_user()) {
builder.ApplyUserConfig(base::FilePath(kChromeDevConfigPath),
disallowed_prefixes);
}
*is_developer_end_user_out = builder.is_developer_end_user();
*env_vars_out = builder.environment_variables();
*args_out = builder.arguments();
*uid_out = builder.uid();
// Do not add code here. Potentially-expensive work should be done between
// StartServer() and WaitForServer().
}
} // namespace login_manager
|
#include "dna.h"
#include<iostream>
using std::cout; using std::cin; using std::string;
void menu_options()
{
cout<<"\n\nWhat would you like to do?";
cout<<"\n1. Find factorials";
cout<<"\n2. Find greatest common divisor";
cout<<"\n3. Exit";
}
void menu()
{
int menu_selection = 0;
do
{
menu_options();
cout<<"\n\nEnter number from menu: ";
cin>> menu_selection;
if (menu_selection > 0 && menu_selection < 3) {
handle_menu(menu_selection);
}
else if (menu_selection == 3){
string confirm = "n";
cout << "Are you sure you would like to exit? (y/n): ";
cin >> confirm;
if (confirm == "y") {
cout << "Thank you! Have a nice day!";
}
else {
menu_selection = 0;
}
}
else {
cout << "Selection error: please enter valid selection from menu.";
}
}
while(menu_selection != 3);
}
int handle_menu(int menu_selection)
{
switch(menu_selection)
{
case 1: {
int num = 0;
cout << "Enter a number: ";
cin >> num;
cout << num << " factorial is : " << factorial(num);
break;
}
case 2: {
int num1 = 0;
int num2 = 0;
cout<< "Enter first number: ";
cin >> num1;
cout << "Enter second number: ";
cin >> num2;
cout << "\nThe GCD of " << num1 << " & " << num2 << " is: " << gcd(num1, num2);
break;
}
}
return(menu_selection);
}
int factorial(int num)
{
int fact_accumulator = 1;
while (num > 0) {
fact_accumulator = fact_accumulator * num;
num--;
}
return fact_accumulator;
}
int gcd(int num1, int num2)
{
while (num1 != num2) {
if (num1 == 0 || num2 == 0) {
num1 = 0;
}
else if (num1 < num2){
num1 = num1 + num2;
num2 = num1 - num2;
num1 = num1 - num2;
}
else if (num1 > num2) {
num1 = num1 - num2;
}
}
return num1;
}
|
////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2014-2016 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Michael Hackstein
////////////////////////////////////////////////////////////////////////////////
#include "Graph/ShortestPathResult.h"
#include "Aql/AqlValue.h"
#include "Basics/VelocyPackHelper.h"
#include "Graph/EdgeDocumentToken.h"
#include "Graph/TraverserCache.h"
#include "Transaction/Helpers.h"
#include "Transaction/Methods.h"
#include <velocypack/Builder.h>
#include <velocypack/StringRef.h>
#include <velocypack/velocypack-aliases.h>
using namespace arangodb;
using namespace arangodb::aql;
using namespace arangodb::graph;
using namespace arangodb::transaction;
using namespace arangodb::traverser;
ShortestPathResult::ShortestPathResult() : _readDocuments(0) {}
ShortestPathResult::~ShortestPathResult() {}
/// @brief Clears the path
void ShortestPathResult::clear() {
_vertices.clear();
_edges.clear();
}
AqlValue ShortestPathResult::edgeToAqlValue(TraverserCache* cache, size_t position) const {
if (position == 0) {
// First Edge is defined as NULL
return AqlValue(AqlValueHintNull());
}
TRI_ASSERT(position - 1 < _edges.size());
return cache->fetchEdgeAqlResult(_edges[position - 1]);
}
AqlValue ShortestPathResult::vertexToAqlValue(TraverserCache* cache, size_t position) const {
TRI_ASSERT(position < _vertices.size());
return cache->fetchVertexAqlResult(_vertices[position]);
}
void ShortestPathResult::addVertex(arangodb::velocypack::StringRef v) {
TRI_ASSERT(_edges.size() == _vertices.size());
_vertices.emplace_back(v);
}
void ShortestPathResult::addEdge(arangodb::graph::EdgeDocumentToken e) {
TRI_ASSERT(_edges.size() + 1 == _vertices.size());
_edges.emplace_back(e);
}
|
/* Copyright 2020 Stanford University, NVIDIA Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// templated priority queue
// nop, but helps IDEs
#include "realm/pri_queue.h"
namespace Realm {
////////////////////////////////////////////////////////////////////////
//
// class PriorityQueue<T, LT>
template <typename T, typename LT>
inline PriorityQueue<T, LT>::PriorityQueue(void)
: highest_priority (PRI_NEG_INF)
, entries_in_queue (0)
{
}
template <typename T, typename LT>
inline PriorityQueue<T, LT>::~PriorityQueue(void)
{
// STL cleans everything up
}
// two ways to add an item -
// 1) add it to the end of the list at that priority (i.e. FIFO order)
// 2) "unget" adds it to the front of the list (i.e. LIFO order)
template <typename T, typename LT>
inline void PriorityQueue<T, LT>::put(T item,
priority_t priority,
bool add_to_back /*= true*/)
{
// step 1: clamp the priority to the "finite" range
if(priority > PRI_MAX_FINITE)
priority = PRI_MAX_FINITE;
else if(priority < PRI_MIN_FINITE)
priority = PRI_MIN_FINITE;
// increase the entry count, if we care
if(entries_in_queue)
(*entries_in_queue) += 1;
// step 2: take the lock
lock.lock();
// step 3: if this is higher priority than anybody else, do notification callbacks
if(priority > highest_priority) {
// remember the original one in case this gets immediately grabbed
priority_t orig_highest = highest_priority;
// now update the highest before we do notifications
highest_priority = priority;
// now the notifications, if any
if(perform_notifications(item, priority)) {
// item was taken, so restore original highest priority and exit
highest_priority = orig_highest;
lock.unlock();
if(entries_in_queue)
(*entries_in_queue) -= 1;
return;
}
}
// get the right deque (this will create one if needed)
std::deque<T>& dq = queue[-priority]; // remember negation...
// and add the item
if(add_to_back)
dq.push_back(item);
else
dq.push_front(item);
// all done
lock.unlock();
}
// getting an item is always from the front of the list and can be filtered to
// ignore things that aren't above a specified priority
// the priority of the retrieved item (if any) is returned in *item_priority
template <typename T, typename LT>
inline T PriorityQueue<T, LT>::get(priority_t *item_priority,
priority_t higher_than /*= PRI_NEG_INF*/)
{
// body is protected by lock
lock.lock();
// empty queue - early out
if(queue.empty()) {
lock.unlock();
return 0; // TODO - EMPTY_VAL
}
typename std::map<priority_t, std::deque<T> >::iterator it = queue.begin();
priority_t priority = -(it->first);
// not interesting enough?
if(priority <= higher_than) {
lock.unlock();
return 0; // TODO - EMPTY_VAL
};
// take item off front
T item = it->second.front();
it->second.pop_front();
// if list is now empty, remove from the queue and adjust highest_priority
if(it->second.empty()) {
queue.erase(it);
highest_priority = (queue.empty() ?
PRI_NEG_INF :
-(queue.begin()->first));
}
// release lock and then return result
lock.unlock();
// decrease the entry count, if we care
if(entries_in_queue)
(*entries_in_queue) -= 1;
if(item_priority)
*item_priority = priority;
return item;
}
// peek is like get, but doesn't remove the element (this is only really useful when
// you don't have multiple getters)
template <typename T, typename LT>
inline T PriorityQueue<T, LT>::peek(priority_t *item_priority,
priority_t higher_than /*= PRI_NEG_INF*/) const
{
// body is protected by lock
lock.lock();
// empty queue - early out
if(queue.empty()) {
lock.unlock();
return 0; // TODO - EMPTY_VAL
}
typename std::map<priority_t, std::deque<T> >::const_iterator it = queue.begin();
priority_t priority = -(it->first);
// not interesting enough?
if(priority <= higher_than) {
lock.unlock();
return 0; // TODO - EMPTY_VAL
};
// peek at item on front
T item = it->second.front();
// release lock and then return result
lock.unlock();
if(item_priority)
*item_priority = priority;
return item;
}
// similarly, the empty-ness query can also ignore things below a certain priority
// this call is lock-free (and is again of questionable utility with multiple readers)
template <typename T, typename LT>
inline bool PriorityQueue<T, LT>::empty(priority_t higher_than /*= PRI_NEG_INF*/) const
{
return(highest_priority <= higher_than);
}
// adds (or modifies) a subscription - only items above the specified priority will
// result in callbacks
template <typename T, typename LT>
inline void PriorityQueue<T, LT>::add_subscription(NotificationCallback *callback,
priority_t higher_than /*= PRI_NEG_INF*/)
{
// just take lock and update subscription map
lock.lock();
subscriptions[callback] = higher_than;
lock.unlock();
}
template <typename T, typename LT>
inline void PriorityQueue<T, LT>::remove_subscription(NotificationCallback *callback)
{
// just take lock and erase subscription map entry (if present)
lock.lock();
subscriptions.erase(callback);
lock.unlock();
}
// helper that performs notifications for a new item - returns true if a callback
// consumes the item
template <typename T, typename LT>
inline bool PriorityQueue<T, LT>::perform_notifications(T item, priority_t item_priority)
{
// lock already held by caller
for(typename std::map<NotificationCallback *, priority_t>::const_iterator it = subscriptions.begin();
it != subscriptions.end();
it++) {
// skip if this isn't interesting to this callback
if(item_priority <= it->second)
continue;
// do callback - a return of true means the item was consumed (so we shouldn't do
// any more callbacks
if(it->first->item_available(item, item_priority))
return true;
}
// got through all the callbacks and nobody wanted it
return false;
}
template <typename T, typename LT>
inline void PriorityQueue<T, LT>::set_gauge(ProfilingGauges::AbsoluteRangeGauge<int> *new_gauge)
{
entries_in_queue = new_gauge;
}
}; // namespace Realm
|
/***************************************************************
*
* Copyright (C) 1990-2011, Condor Team, Computer Sciences Department,
* University of Wisconsin-Madison, WI.
*
* 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 "condor_common.h"
#include "condor_config.h"
#include "condor_debug.h"
#include "util_lib_proto.h"
#include "condor_auth_ssl.h"
#if defined(DLOPEN_GSI_LIBS)
#include <dlfcn.h>
#endif
#include "globus_utils.h"
#if defined(HAVE_EXT_GLOBUS)
// Note: this is from OpenSSL, but should be present if Globus is.
// Only used if HAVE_EXT_GLOBUS.
# include "openssl/x509v3.h"
#endif
#define DEFAULT_MIN_TIME_LEFT 8*60*60;
static const char * _globus_error_message = NULL;
#if defined(HAVE_EXT_GLOBUS)
// This symbol is in libglobus_gssapi_gsi, but it's not exposed in any
// public header file.
extern gss_OID_desc *gss_nt_host_ip;
// Symbols from libglobus_common
int (*globus_module_activate_ptr)(
globus_module_descriptor_t *) = NULL;
int (*globus_thread_set_model_ptr)(
const char *) = NULL;
// Symbols from libglobus_gsi_sysconfig
globus_result_t (*globus_gsi_sysconfig_get_proxy_filename_unix_ptr)(
char **, globus_gsi_proxy_file_type_t) = NULL;
// Symbols from libglobus_gsi_credential
globus_result_t (*globus_gsi_cred_get_cert_ptr)(
globus_gsi_cred_handle_t, X509 **) = NULL;
globus_result_t (*globus_gsi_cred_get_cert_chain_ptr)(
globus_gsi_cred_handle_t, STACK_OF(X509) **) = NULL;
globus_result_t (*globus_gsi_cred_get_cert_type_ptr)(
globus_gsi_cred_handle_t, globus_gsi_cert_utils_cert_type_t *) = NULL;
globus_result_t (*globus_gsi_cred_get_identity_name_ptr)(
globus_gsi_cred_handle_t, char **) = NULL;
globus_result_t (*globus_gsi_cred_get_lifetime_ptr)(
globus_gsi_cred_handle_t, time_t *) = NULL;
globus_result_t (*globus_gsi_cred_get_subject_name_ptr)(
globus_gsi_cred_handle_t, char **) = NULL;
globus_result_t (*globus_gsi_cred_handle_attrs_destroy_ptr)(
globus_gsi_cred_handle_attrs_t) = NULL;
globus_result_t (*globus_gsi_cred_handle_attrs_init_ptr)(
globus_gsi_cred_handle_attrs_t *) = NULL;
globus_result_t (*globus_gsi_cred_handle_destroy_ptr)(
globus_gsi_cred_handle_t) = NULL;
globus_result_t (*globus_gsi_cred_handle_init_ptr)(
globus_gsi_cred_handle_t *, globus_gsi_cred_handle_attrs_t) = NULL;
globus_result_t (*globus_gsi_cred_read_proxy_ptr)(
globus_gsi_cred_handle_t, const char *) = NULL;
globus_result_t (*globus_gsi_cred_write_proxy_ptr)(
globus_gsi_cred_handle_t, char *) = NULL;
// Symbols for libglobus_gsi_proxy_core
globus_result_t (*globus_gsi_proxy_assemble_cred_ptr)(
globus_gsi_proxy_handle_t, globus_gsi_cred_handle_t *, BIO *) = NULL;
globus_result_t (*globus_gsi_proxy_create_req_ptr)(
globus_gsi_proxy_handle_t, BIO *) = NULL;
globus_result_t (*globus_gsi_proxy_handle_attrs_destroy_ptr)(
globus_gsi_proxy_handle_attrs_t) = NULL;
globus_result_t (*globus_gsi_proxy_handle_attrs_get_keybits_ptr)(
globus_gsi_proxy_handle_attrs_t, int *) = NULL;
globus_result_t (*globus_gsi_proxy_handle_attrs_init_ptr)(
globus_gsi_proxy_handle_attrs_t *) = NULL;
globus_result_t (*globus_gsi_proxy_handle_attrs_set_clock_skew_allowable_ptr)(
globus_gsi_proxy_handle_attrs_t, int) = NULL;
globus_result_t (*globus_gsi_proxy_handle_attrs_set_keybits_ptr)(
globus_gsi_proxy_handle_attrs_t, int) = NULL;
globus_result_t (*globus_gsi_proxy_handle_destroy_ptr)(
globus_gsi_proxy_handle_t) = NULL;
globus_result_t (*globus_gsi_proxy_handle_init_ptr)(
globus_gsi_proxy_handle_t *, globus_gsi_proxy_handle_attrs_t) = NULL;
globus_result_t (*globus_gsi_proxy_handle_set_is_limited_ptr)(
globus_gsi_proxy_handle_t, globus_bool_t) = NULL;
globus_result_t (*globus_gsi_proxy_handle_set_time_valid_ptr)(
globus_gsi_proxy_handle_t, int) = NULL;
globus_result_t (*globus_gsi_proxy_handle_set_type_ptr)(
globus_gsi_proxy_handle_t, globus_gsi_cert_utils_cert_type_t) = NULL;
globus_result_t (*globus_gsi_proxy_inquire_req_ptr)(
globus_gsi_proxy_handle_t, BIO *) = NULL;
globus_result_t (*globus_gsi_proxy_sign_req_ptr)(
globus_gsi_proxy_handle_t, globus_gsi_cred_handle_t, BIO *) = NULL;
// Symbols from libglobus_gssapi_gsi
OM_uint32 (*gss_accept_sec_context_ptr)(
OM_uint32 *, gss_ctx_id_t *, const gss_cred_id_t, const gss_buffer_t,
const gss_channel_bindings_t, gss_name_t *, gss_OID *, gss_buffer_t,
OM_uint32 *, OM_uint32 *, gss_cred_id_t *) = NULL;
OM_uint32 (*gss_compare_name_ptr)(
OM_uint32 *, const gss_name_t, const gss_name_t, int *) = NULL;
OM_uint32 (*gss_context_time_ptr)(
OM_uint32 *, const gss_ctx_id_t, OM_uint32 *) = NULL;
OM_uint32 (*gss_delete_sec_context_ptr)(
OM_uint32 *, gss_ctx_id_t *, gss_buffer_t) = NULL;
OM_uint32 (*gss_display_name_ptr)(
OM_uint32 *, const gss_name_t, gss_buffer_t, gss_OID *) = NULL;
OM_uint32 (*gss_import_cred_ptr)(
OM_uint32 *, gss_cred_id_t *, const gss_OID, OM_uint32,
const gss_buffer_t, OM_uint32, OM_uint32 *) = NULL;
OM_uint32 (*gss_import_name_ptr)(
OM_uint32 *, const gss_buffer_t, const gss_OID, gss_name_t *) = NULL;
OM_uint32 (*gss_inquire_context_ptr)(
OM_uint32 *, const gss_ctx_id_t, gss_name_t *, gss_name_t *,
OM_uint32 *, gss_OID *, OM_uint32 *, int *, int *) = NULL;
OM_uint32 (*gss_release_buffer_ptr)(
OM_uint32 *, gss_buffer_t) = NULL;
OM_uint32 (*gss_release_cred_ptr)(
OM_uint32 *, gss_cred_id_t *) = NULL;
OM_uint32 (*gss_release_name_ptr)(
OM_uint32 *, gss_name_t *) = NULL;
OM_uint32 (*gss_unwrap_ptr)(
OM_uint32 *, const gss_ctx_id_t, const gss_buffer_t, gss_buffer_t, int *,
gss_qop_t *) = NULL;
OM_uint32 (*gss_wrap_ptr)(
OM_uint32 *, const gss_ctx_id_t, int, gss_qop_t, const gss_buffer_t,
int *, gss_buffer_t) = NULL;
gss_OID_desc **gss_nt_host_ip_ptr = NULL;
// Symbols from libglobus_gss_assist
OM_uint32 (*globus_gss_assist_display_status_str_ptr)(
char **, char *, OM_uint32, OM_uint32, int) = NULL;
globus_result_t (*globus_gss_assist_map_and_authorize_ptr)(
gss_ctx_id_t, char *, char *, char *, unsigned int) = NULL;
OM_uint32 (*globus_gss_assist_acquire_cred_ptr)(
OM_uint32 *, gss_cred_usage_t, gss_cred_id_t *) = NULL;
OM_uint32 (*globus_gss_assist_init_sec_context_ptr)(
OM_uint32 *, const gss_cred_id_t, gss_ctx_id_t *, char *, OM_uint32,
OM_uint32 *, int *, int (*)(void *, void **, size_t *), void *,
int (*)(void *, void *, size_t), void *) = NULL;
globus_module_descriptor_t *globus_i_gsi_gss_assist_module_ptr = NULL;
// Symbols from libvomsapi
#if defined(HAVE_EXT_VOMS)
void (*VOMS_Destroy_ptr)(
struct vomsdata *) = NULL;
char *(*VOMS_ErrorMessage_ptr)(
struct vomsdata *, int, char *, int) = NULL;
struct vomsdata *(*VOMS_Init_ptr)(
char *, char *) = NULL;
int (*VOMS_Retrieve_ptr)(
X509 *, STACK_OF(X509) *, int, struct vomsdata *, int *) = NULL;
int (*VOMS_SetVerificationType_ptr)(
int, struct vomsdata *, int *) = NULL;
#endif /* defined(HAVE_EXT_VOMS) */
#endif /* defined(HAVE_EXT_GLOBUS) */
#define GRAM_STATUS_STR_LEN 8
#define NOT_SUPPORTED_MSG "This version of Condor doesn't support GSI security"
const char *
GlobusJobStatusName( int status )
{
static char buf[GRAM_STATUS_STR_LEN];
#if defined(HAVE_EXT_GLOBUS)
switch ( status ) {
case GLOBUS_GRAM_PROTOCOL_JOB_STATE_PENDING:
return "PENDING";
case GLOBUS_GRAM_PROTOCOL_JOB_STATE_ACTIVE:
return "ACTIVE";
case GLOBUS_GRAM_PROTOCOL_JOB_STATE_FAILED:
return "FAILED";
case GLOBUS_GRAM_PROTOCOL_JOB_STATE_DONE:
return "DONE";
case GLOBUS_GRAM_PROTOCOL_JOB_STATE_SUSPENDED:
return "SUSPENDED";
case GLOBUS_GRAM_PROTOCOL_JOB_STATE_UNSUBMITTED:
return "UNSUBMITTED";
case GLOBUS_GRAM_PROTOCOL_JOB_STATE_STAGE_IN:
return "STAGE_IN";
case GLOBUS_GRAM_PROTOCOL_JOB_STATE_STAGE_OUT:
return "STAGE_OUT";
case GLOBUS_GRAM_PROTOCOL_JOB_STATE_UNKNOWN:
return "UNKNOWN";
default:
snprintf( buf, GRAM_STATUS_STR_LEN, "%d", status );
return buf;
}
#else
snprintf( buf, GRAM_STATUS_STR_LEN, "%d", status );
return buf;
#endif
}
const char *
x509_error_string( void )
{
return _globus_error_message;
}
static
void
set_error_string( const char *message )
{
if ( _globus_error_message ) {
free( const_cast<char *>(_globus_error_message) );
}
_globus_error_message = strdup( message );
}
/* Activate the globus gsi modules for use by functions in this file.
* Returns zero if the modules were successfully activated. Returns -1 if
* something went wrong.
*/
int
activate_globus_gsi( void )
{
#if !defined(HAVE_EXT_GLOBUS)
set_error_string( NOT_SUPPORTED_MSG );
return -1;
#else
static bool globus_gsi_activated = false;
static bool activation_failed = false;
if ( globus_gsi_activated ) {
return 0;
}
if ( activation_failed ) {
return -1;
}
if ( Condor_Auth_SSL::Initialize() == false ) {
// Error in the dlopen/sym calls for libssl, return failure.
std::string buf;
formatstr( buf, "Failed to open SSL library" );
set_error_string( buf.c_str() );
activation_failed = true;
return -1;
}
#if defined(DLOPEN_GSI_LIBS)
void *dl_hdl;
if ( (dl_hdl = dlopen(LIBLTDL_SO, RTLD_LAZY)) == NULL ||
(dl_hdl = dlopen(LIBGLOBUS_COMMON_SO, RTLD_LAZY)) == NULL ||
!(globus_module_activate_ptr = (int (*)(globus_module_descriptor_t*))dlsym(dl_hdl, "globus_module_activate")) ||
!(globus_thread_set_model_ptr = (int (*)(const char*))dlsym(dl_hdl, "globus_thread_set_model")) ||
(dl_hdl = dlopen(LIBGLOBUS_CALLOUT_SO, RTLD_LAZY)) == NULL ||
(dl_hdl = dlopen(LIBGLOBUS_PROXY_SSL_SO, RTLD_LAZY)) == NULL ||
(dl_hdl = dlopen(LIBGLOBUS_OPENSSL_ERROR_SO, RTLD_LAZY)) == NULL ||
(dl_hdl = dlopen(LIBGLOBUS_OPENSSL_SO, RTLD_LAZY)) == NULL ||
(dl_hdl = dlopen(LIBGLOBUS_GSI_CERT_UTILS_SO, RTLD_LAZY)) == NULL ||
(dl_hdl = dlopen(LIBGLOBUS_GSI_SYSCONFIG_SO, RTLD_LAZY)) == NULL ||
!(globus_gsi_sysconfig_get_proxy_filename_unix_ptr = (globus_result_t (*)(char**, globus_gsi_proxy_file_type_t))dlsym(dl_hdl, "globus_gsi_sysconfig_get_proxy_filename_unix")) ||
(dl_hdl = dlopen(LIBGLOBUS_OLDGAA_SO, RTLD_LAZY)) == NULL ||
(dl_hdl = dlopen(LIBGLOBUS_GSI_CALLBACK_SO, RTLD_LAZY)) == NULL ||
(dl_hdl = dlopen(LIBGLOBUS_GSI_CREDENTIAL_SO, RTLD_LAZY))== NULL ||
!(globus_gsi_cred_get_cert_ptr = (globus_result_t (*)(globus_l_gsi_cred_handle_s*, X509**))dlsym(dl_hdl, "globus_gsi_cred_get_cert")) ||
!(globus_gsi_cred_get_cert_chain_ptr = (globus_result_t (*)(globus_gsi_cred_handle_t, STACK_OF(X509)**))dlsym(dl_hdl, "globus_gsi_cred_get_cert_chain")) ||
!(globus_gsi_cred_get_cert_type_ptr = (globus_result_t (*)(globus_l_gsi_cred_handle_s*, globus_gsi_cert_utils_cert_type_t*))dlsym(dl_hdl, "globus_gsi_cred_get_cert_type")) ||
!(globus_gsi_cred_get_identity_name_ptr = (globus_result_t (*)(globus_l_gsi_cred_handle_s*, char**))dlsym(dl_hdl, "globus_gsi_cred_get_identity_name")) ||
!(globus_gsi_cred_get_lifetime_ptr = (globus_result_t (*)(globus_l_gsi_cred_handle_s*, time_t*))dlsym(dl_hdl, "globus_gsi_cred_get_lifetime")) ||
!(globus_gsi_cred_get_subject_name_ptr = (globus_result_t (*)(globus_l_gsi_cred_handle_s*, char**))dlsym(dl_hdl, "globus_gsi_cred_get_subject_name")) ||
!(globus_gsi_cred_handle_attrs_destroy_ptr = (globus_result_t (*)(globus_l_gsi_cred_handle_attrs_s*))dlsym(dl_hdl, "globus_gsi_cred_handle_attrs_destroy")) ||
!(globus_gsi_cred_handle_attrs_init_ptr = (globus_result_t (*)(globus_l_gsi_cred_handle_attrs_s**))dlsym(dl_hdl, "globus_gsi_cred_handle_attrs_init")) ||
!(globus_gsi_cred_handle_destroy_ptr = (globus_result_t (*)(globus_l_gsi_cred_handle_s*))dlsym(dl_hdl, "globus_gsi_cred_handle_destroy")) ||
!(globus_gsi_cred_handle_init_ptr = (globus_result_t (*)(globus_l_gsi_cred_handle_s**, globus_l_gsi_cred_handle_attrs_s*))dlsym(dl_hdl, "globus_gsi_cred_handle_init")) ||
!(globus_gsi_cred_read_proxy_ptr = (globus_result_t (*)(globus_l_gsi_cred_handle_s*, const char*))dlsym(dl_hdl, "globus_gsi_cred_read_proxy")) ||
!(globus_gsi_cred_write_proxy_ptr = (globus_result_t (*)(globus_l_gsi_cred_handle_s*, char*))dlsym(dl_hdl, "globus_gsi_cred_write_proxy")) ||
(dl_hdl = dlopen(LIBGLOBUS_GSI_PROXY_CORE_SO, RTLD_LAZY)) == NULL ||
!(globus_gsi_proxy_assemble_cred_ptr = (globus_result_t (*)(globus_l_gsi_proxy_handle_s*, globus_l_gsi_cred_handle_s**, BIO*))dlsym(dl_hdl, "globus_gsi_proxy_assemble_cred")) ||
!(globus_gsi_proxy_create_req_ptr = (globus_result_t (*)(globus_l_gsi_proxy_handle_s*, BIO*))dlsym(dl_hdl, "globus_gsi_proxy_create_req")) ||
!(globus_gsi_proxy_handle_attrs_destroy_ptr = (globus_result_t (*)(globus_l_gsi_proxy_handle_attrs_s*))dlsym(dl_hdl, "globus_gsi_proxy_handle_attrs_destroy")) ||
!(globus_gsi_proxy_handle_attrs_get_keybits_ptr = (globus_result_t (*)(globus_l_gsi_proxy_handle_attrs_s*, int*))dlsym(dl_hdl, "globus_gsi_proxy_handle_attrs_get_keybits")) ||
!(globus_gsi_proxy_handle_attrs_init_ptr = (globus_result_t (*)(globus_l_gsi_proxy_handle_attrs_s**))dlsym(dl_hdl, "globus_gsi_proxy_handle_attrs_init")) ||
!(globus_gsi_proxy_handle_attrs_set_clock_skew_allowable_ptr = (globus_result_t (*)(globus_l_gsi_proxy_handle_attrs_s*, int))dlsym(dl_hdl, "globus_gsi_proxy_handle_attrs_set_clock_skew_allowable")) ||
!(globus_gsi_proxy_handle_attrs_set_keybits_ptr = (globus_result_t (*)(globus_l_gsi_proxy_handle_attrs_s*, int))dlsym(dl_hdl, "globus_gsi_proxy_handle_attrs_set_keybits")) ||
!(globus_gsi_proxy_handle_destroy_ptr = (globus_result_t (*)(globus_l_gsi_proxy_handle_s*))dlsym(dl_hdl, "globus_gsi_proxy_handle_destroy")) ||
!(globus_gsi_proxy_handle_init_ptr = (globus_result_t (*)(globus_l_gsi_proxy_handle_s**, globus_l_gsi_proxy_handle_attrs_s*))dlsym(dl_hdl, "globus_gsi_proxy_handle_init")) ||
!(globus_gsi_proxy_handle_set_is_limited_ptr = (globus_result_t (*)(globus_l_gsi_proxy_handle_s*, globus_bool_t))dlsym(dl_hdl, "globus_gsi_proxy_handle_set_is_limited")) ||
!(globus_gsi_proxy_handle_set_time_valid_ptr = (globus_result_t (*)(globus_l_gsi_proxy_handle_s*, int))dlsym(dl_hdl, "globus_gsi_proxy_handle_set_time_valid")) ||
!(globus_gsi_proxy_handle_set_type_ptr = (globus_result_t (*)(globus_l_gsi_proxy_handle_s*, globus_gsi_cert_utils_cert_type_t))dlsym(dl_hdl, "globus_gsi_proxy_handle_set_type")) ||
!(globus_gsi_proxy_inquire_req_ptr = (globus_result_t (*)(globus_l_gsi_proxy_handle_s*, BIO*))dlsym(dl_hdl, "globus_gsi_proxy_inquire_req")) ||
!(globus_gsi_proxy_sign_req_ptr = (globus_result_t (*)(globus_l_gsi_proxy_handle_s*, globus_l_gsi_cred_handle_s*, BIO*))dlsym(dl_hdl, "globus_gsi_proxy_sign_req")) ||
(dl_hdl = dlopen(LIBGLOBUS_GSSAPI_GSI_SO, RTLD_LAZY)) == NULL ||
!(gss_accept_sec_context_ptr = (OM_uint32 (*)(OM_uint32 *, gss_ctx_id_t *, const gss_cred_id_t, const gss_buffer_t, const gss_channel_bindings_t, gss_name_t *, gss_OID *, gss_buffer_t, OM_uint32 *, OM_uint32 *, gss_cred_id_t *))dlsym(dl_hdl, "gss_accept_sec_context")) ||
!(gss_compare_name_ptr = (OM_uint32 (*)(OM_uint32*, const gss_name_t, const gss_name_t, int*))dlsym(dl_hdl, "gss_compare_name")) ||
!(gss_context_time_ptr = (OM_uint32 (*)(OM_uint32*, const gss_ctx_id_t, OM_uint32*))dlsym(dl_hdl, "gss_context_time")) ||
!(gss_delete_sec_context_ptr = (OM_uint32 (*)(OM_uint32*, gss_ctx_id_t*, gss_buffer_t))dlsym(dl_hdl, "gss_delete_sec_context")) ||
!(gss_display_name_ptr = (OM_uint32 (*)( OM_uint32*, const gss_name_t, gss_buffer_t, gss_OID*))dlsym(dl_hdl, "gss_display_name")) ||
!(gss_import_cred_ptr = (OM_uint32 (*)(OM_uint32*, gss_cred_id_desc_struct**, gss_OID_desc_struct*, OM_uint32, gss_buffer_desc_struct*, OM_uint32, OM_uint32*))dlsym(dl_hdl, "gss_import_cred")) ||
!(gss_import_name_ptr = (OM_uint32 (*)(OM_uint32*, const gss_buffer_t, const gss_OID, gss_name_t*))dlsym(dl_hdl, "gss_import_name")) ||
!(gss_inquire_context_ptr = (OM_uint32 (*)(OM_uint32*, const gss_ctx_id_t, gss_name_t*, gss_name_t*, OM_uint32*, gss_OID*, OM_uint32*, int*, int*))dlsym(dl_hdl, "gss_inquire_context")) ||
!(gss_release_buffer_ptr = (OM_uint32 (*)(OM_uint32*, gss_buffer_t))dlsym(dl_hdl, "gss_release_buffer")) ||
!(gss_release_cred_ptr = (OM_uint32 (*)(OM_uint32*, gss_cred_id_desc_struct**))dlsym(dl_hdl, "gss_release_cred")) ||
!(gss_release_name_ptr = (OM_uint32 (*)(OM_uint32*, gss_name_t*))dlsym(dl_hdl, "gss_release_name")) ||
!(gss_unwrap_ptr = (OM_uint32 (*)(OM_uint32*, const gss_ctx_id_t, const gss_buffer_t, gss_buffer_t, int*, gss_qop_t*))dlsym(dl_hdl, "gss_unwrap")) ||
!(gss_wrap_ptr = (OM_uint32 (*)(OM_uint32*, const gss_ctx_id_t, int, gss_qop_t, const gss_buffer_t, int*, gss_buffer_t))dlsym(dl_hdl, "gss_wrap")) ||
!(gss_nt_host_ip_ptr = (gss_OID_desc **)dlsym(dl_hdl, "gss_nt_host_ip")) ||
(dl_hdl = dlopen(LIBGLOBUS_GSS_ASSIST_SO, RTLD_LAZY)) == NULL ||
!(globus_gss_assist_display_status_str_ptr = (OM_uint32 (*)(char**, char*, OM_uint32, OM_uint32, int))dlsym(dl_hdl, "globus_gss_assist_display_status_str")) ||
!(globus_gss_assist_map_and_authorize_ptr = (globus_result_t (*)(gss_ctx_id_t, char*, char*, char*, unsigned int))dlsym(dl_hdl, "globus_gss_assist_map_and_authorize")) ||
!(globus_gss_assist_acquire_cred_ptr = (OM_uint32 (*)(OM_uint32*, gss_cred_usage_t, gss_cred_id_t*))dlsym(dl_hdl, "globus_gss_assist_acquire_cred")) ||
!(globus_gss_assist_init_sec_context_ptr = (OM_uint32 (*)(OM_uint32*, const gss_cred_id_t, gss_ctx_id_t*, char*, OM_uint32, OM_uint32*, int*, int (*)(void*, void**, size_t*), void*, int (*)(void*, void*, size_t), void*))dlsym(dl_hdl, "globus_gss_assist_init_sec_context")) ||
!(globus_i_gsi_gss_assist_module_ptr = (globus_module_descriptor_t*)dlsym(dl_hdl, "globus_i_gsi_gss_assist_module")) ||
#if defined(HAVE_EXT_VOMS)
(dl_hdl = dlopen(LIBVOMSAPI_SO, RTLD_LAZY)) == NULL ||
!(VOMS_Destroy_ptr = (void (*)(vomsdata*))dlsym(dl_hdl, "VOMS_Destroy")) ||
!(VOMS_ErrorMessage_ptr = (char* (*)(vomsdata*, int, char*, int))dlsym(dl_hdl, "VOMS_ErrorMessage")) ||
!(VOMS_Init_ptr = (vomsdata* (*)(char*, char*))dlsym(dl_hdl, "VOMS_Init")) ||
!(VOMS_Retrieve_ptr = (int (*)(X509*, STACK_OF(X509)*, int, struct vomsdata*, int*))dlsym(dl_hdl, "VOMS_Retrieve")) ||
!(VOMS_SetVerificationType_ptr = (int (*)(int, vomsdata*, int*))dlsym(dl_hdl, "VOMS_SetVerificationType"))
#else
false
#endif
) {
// Error in the dlopen/sym calls, return failure.
const char *err = dlerror();
std::string buf;
formatstr( buf, "Failed to open GSI libraries: %s", err ? err : "Unknown error" );
set_error_string( buf.c_str() );
activation_failed = true;
return -1;
}
#else
globus_module_activate_ptr = globus_module_activate;
globus_thread_set_model_ptr = globus_thread_set_model;
globus_gsi_sysconfig_get_proxy_filename_unix_ptr = globus_gsi_sysconfig_get_proxy_filename_unix;
globus_gsi_cred_get_cert_ptr = globus_gsi_cred_get_cert;
globus_gsi_cred_get_cert_chain_ptr = globus_gsi_cred_get_cert_chain;
globus_gsi_cred_get_cert_type_ptr = globus_gsi_cred_get_cert_type;
globus_gsi_cred_get_identity_name_ptr = globus_gsi_cred_get_identity_name;
globus_gsi_cred_get_lifetime_ptr = globus_gsi_cred_get_lifetime;
globus_gsi_cred_get_subject_name_ptr = globus_gsi_cred_get_subject_name;
globus_gsi_cred_handle_attrs_destroy_ptr = globus_gsi_cred_handle_attrs_destroy;
globus_gsi_cred_handle_attrs_init_ptr = globus_gsi_cred_handle_attrs_init;
globus_gsi_cred_handle_destroy_ptr = globus_gsi_cred_handle_destroy;
globus_gsi_cred_handle_init_ptr = globus_gsi_cred_handle_init;
globus_gsi_cred_read_proxy_ptr = globus_gsi_cred_read_proxy;
globus_gsi_cred_write_proxy_ptr = reinterpret_cast<globus_result_t (*)(globus_l_gsi_cred_handle_s*, char*)>(globus_gsi_cred_write_proxy);
globus_gsi_proxy_assemble_cred_ptr = globus_gsi_proxy_assemble_cred;
globus_gsi_proxy_create_req_ptr = globus_gsi_proxy_create_req;
globus_gsi_proxy_handle_attrs_destroy_ptr = globus_gsi_proxy_handle_attrs_destroy;
globus_gsi_proxy_handle_attrs_get_keybits_ptr = globus_gsi_proxy_handle_attrs_get_keybits;
globus_gsi_proxy_handle_attrs_init_ptr = globus_gsi_proxy_handle_attrs_init;
globus_gsi_proxy_handle_attrs_set_clock_skew_allowable_ptr = globus_gsi_proxy_handle_attrs_set_clock_skew_allowable;
globus_gsi_proxy_handle_attrs_set_keybits_ptr = globus_gsi_proxy_handle_attrs_set_keybits;
globus_gsi_proxy_handle_destroy_ptr = globus_gsi_proxy_handle_destroy;
globus_gsi_proxy_handle_init_ptr = globus_gsi_proxy_handle_init;
globus_gsi_proxy_handle_set_is_limited_ptr = globus_gsi_proxy_handle_set_is_limited;
globus_gsi_proxy_handle_set_time_valid_ptr = globus_gsi_proxy_handle_set_time_valid;
globus_gsi_proxy_handle_set_type_ptr = globus_gsi_proxy_handle_set_type;
globus_gsi_proxy_inquire_req_ptr = globus_gsi_proxy_inquire_req;
globus_gsi_proxy_sign_req_ptr = globus_gsi_proxy_sign_req;
gss_accept_sec_context_ptr = gss_accept_sec_context;
gss_compare_name_ptr = gss_compare_name;
gss_context_time_ptr = gss_context_time;
gss_delete_sec_context_ptr = gss_delete_sec_context;
gss_display_name_ptr = gss_display_name;
gss_import_cred_ptr = gss_import_cred;
gss_import_name_ptr = gss_import_name;
gss_inquire_context_ptr = gss_inquire_context;
gss_release_buffer_ptr = gss_release_buffer;
gss_release_cred_ptr = gss_release_cred;
gss_release_name_ptr = gss_release_name;
gss_unwrap_ptr = gss_unwrap;
gss_wrap_ptr = gss_wrap;
gss_nt_host_ip_ptr = &gss_nt_host_ip;
globus_gss_assist_display_status_str_ptr = globus_gss_assist_display_status_str;
globus_gss_assist_map_and_authorize_ptr = globus_gss_assist_map_and_authorize;
globus_gss_assist_acquire_cred_ptr = globus_gss_assist_acquire_cred;
globus_gss_assist_init_sec_context_ptr = globus_gss_assist_init_sec_context;
globus_i_gsi_gss_assist_module_ptr = &globus_i_gsi_gss_assist_module;
#if defined(HAVE_EXT_VOMS)
VOMS_Destroy_ptr = VOMS_Destroy;
VOMS_ErrorMessage_ptr = VOMS_ErrorMessage;
VOMS_Init_ptr = VOMS_Init;
VOMS_Retrieve_ptr = VOMS_Retrieve;
VOMS_SetVerificationType_ptr = VOMS_SetVerificationType;
#endif /* defined(HAVE_EXT_VOMS) */
#endif
// If this fails, it means something already configured a threaded
// model. That won't harm us, so ignore it.
(*globus_thread_set_model_ptr)( GLOBUS_THREAD_MODEL_NONE );
if ( (*globus_module_activate_ptr)(globus_i_gsi_gss_assist_module_ptr) ) {
set_error_string( "couldn't activate globus gsi gss assist module" );
activation_failed = true;
return -1;
}
globus_gsi_activated = true;
return 0;
#endif
}
/* Return the path to the X509 proxy file as determined by GSI/SSL.
* Returns NULL if the filename can't be determined. Otherwise, the
* string returned must be freed with free().
*/
char *
get_x509_proxy_filename( void )
{
char *proxy_file = NULL;
#if defined(HAVE_EXT_GLOBUS)
globus_gsi_proxy_file_type_t file_type = GLOBUS_PROXY_FILE_INPUT;
if ( activate_globus_gsi() != 0 ) {
return NULL;
}
if ( (*globus_gsi_sysconfig_get_proxy_filename_unix_ptr)(&proxy_file, file_type) !=
GLOBUS_SUCCESS ) {
set_error_string( "unable to locate proxy file" );
}
#endif
return proxy_file;
}
#if defined(HAVE_EXT_VOMS)
// caller must free result
static
char* trim_quotes( char* instr ) {
char * result;
int instr_len;
if (instr == NULL) {
return NULL;
}
instr_len = strlen(instr);
// to trim, must be minimum three characters with a double quote first and last
if ((instr_len > 2) && (instr[0] == '"') && (instr[instr_len-1]) == '"') {
// alloc a shorter buffer, copy everything in, and null terminate
result = (char*)malloc(instr_len - 1); // minus two quotes, plus one NULL terminator.
strncpy(result, &(instr[1]), instr_len-2);
result[instr_len-2] = 0;
} else {
result = strdup(instr);
}
return result;
}
// caller responsible for freeing
static
char*
quote_x509_string( char* instr) {
char * result_string = 0;
int result_string_len = 0;
char * x509_fqan_escape = 0;
char * x509_fqan_escape_sub = 0;
char * x509_fqan_delimiter = 0;
char * x509_fqan_delimiter_sub = 0;
int x509_fqan_escape_sub_len = 0;
int x509_fqan_delimiter_sub_len = 0;
char * tmp_scan_ptr;
// NULL in, NULL out
if (!instr) {
return NULL;
}
// we look at first char only. default '&'.
if (!(x509_fqan_escape = param("X509_FQAN_ESCAPE"))) {
x509_fqan_escape = strdup("&");
}
// can be multiple chars
if (!(x509_fqan_escape_sub = param("X509_FQAN_ESCAPE_SUB"))) {
x509_fqan_escape_sub = strdup("&");
}
// we look at first char only. default ','.
if (!(x509_fqan_delimiter = param("X509_FQAN_DELIMITER"))) {
x509_fqan_delimiter = strdup(",");
}
// can be multiple chars
if (!(x509_fqan_delimiter_sub = param("X509_FQAN_DELIMITER_SUB"))) {
x509_fqan_delimiter_sub = strdup(",");
}
// phase 0, trim quotes off if needed
// use tmp_scan_ptr to temporarily hold trimmed strings while being reassigned.
tmp_scan_ptr = trim_quotes(x509_fqan_escape);
free (x509_fqan_escape);
x509_fqan_escape = tmp_scan_ptr;
tmp_scan_ptr = trim_quotes(x509_fqan_escape_sub);
free (x509_fqan_escape_sub);
x509_fqan_escape_sub = tmp_scan_ptr;
x509_fqan_escape_sub_len = strlen(x509_fqan_escape_sub);
tmp_scan_ptr = trim_quotes(x509_fqan_delimiter);
free (x509_fqan_delimiter);
x509_fqan_delimiter = tmp_scan_ptr;
tmp_scan_ptr = trim_quotes(x509_fqan_delimiter_sub);
free (x509_fqan_delimiter_sub);
x509_fqan_delimiter_sub = tmp_scan_ptr;
x509_fqan_delimiter_sub_len = strlen(x509_fqan_delimiter_sub);
// phase 1, scan the string to compute the new length
result_string_len = 0;
for (tmp_scan_ptr = instr; *tmp_scan_ptr; tmp_scan_ptr++) {
if( (*tmp_scan_ptr)==x509_fqan_escape[0] ) {
result_string_len += x509_fqan_escape_sub_len;
} else if( (*tmp_scan_ptr)==x509_fqan_delimiter[0] ) {
result_string_len += x509_fqan_delimiter_sub_len;
} else {
result_string_len++;
}
}
// phase 2, process the string into the result buffer
// malloc new string (with NULL terminator)
result_string = (char*) malloc (result_string_len + 1);
ASSERT( result_string );
*result_string = 0;
result_string_len = 0;
for (tmp_scan_ptr = instr; *tmp_scan_ptr; tmp_scan_ptr++) {
if( (*tmp_scan_ptr)==x509_fqan_escape[0] ) {
strcat(&(result_string[result_string_len]), x509_fqan_escape_sub);
result_string_len += x509_fqan_escape_sub_len;
} else if( (*tmp_scan_ptr)==x509_fqan_delimiter[0] ) {
strcat(&(result_string[result_string_len]), x509_fqan_delimiter_sub);
result_string_len += x509_fqan_delimiter_sub_len;
} else {
result_string[result_string_len] = *tmp_scan_ptr;
result_string_len++;
}
result_string[result_string_len] = 0;
}
// clean up
free(x509_fqan_escape);
free(x509_fqan_escape_sub);
free(x509_fqan_delimiter);
free(x509_fqan_delimiter_sub);
return result_string;
}
#endif /* defined(HAVE_EXT_VOMS) */
#if defined(HAVE_EXT_GLOBUS)
globus_gsi_cred_handle_t x509_proxy_read( const char *proxy_file )
{
globus_gsi_cred_handle_t handle = NULL;
globus_gsi_cred_handle_attrs_t handle_attrs = NULL;
char *my_proxy_file = NULL;
bool error = false;
if ( activate_globus_gsi() != 0 ) {
return NULL;
}
if ((*globus_gsi_cred_handle_attrs_init_ptr)(&handle_attrs)) {
set_error_string( "problem during internal initialization1" );
error = true;
goto cleanup;
}
if ((*globus_gsi_cred_handle_init_ptr)(&handle, handle_attrs)) {
set_error_string( "problem during internal initialization2" );
error = true;
goto cleanup;
}
/* Check for proxy file */
if (proxy_file == NULL) {
my_proxy_file = get_x509_proxy_filename();
if (my_proxy_file == NULL) {
goto cleanup;
}
proxy_file = my_proxy_file;
}
// We should have a proxy file, now, try to read it
if ((*globus_gsi_cred_read_proxy_ptr)(handle, proxy_file)) {
set_error_string( "unable to read proxy file" );
error = true;
goto cleanup;
}
cleanup:
if (my_proxy_file) {
free(my_proxy_file);
}
if (handle_attrs) {
(*globus_gsi_cred_handle_attrs_destroy_ptr)(handle_attrs);
}
if (error && handle) {
(*globus_gsi_cred_handle_destroy_ptr)(handle);
handle = NULL;
}
return handle;
}
void x509_proxy_free( globus_gsi_cred_handle_t handle )
{
if ( activate_globus_gsi() != 0 ) {
return;
}
if (handle) {
(*globus_gsi_cred_handle_destroy_ptr)(handle);
}
}
time_t x509_proxy_expiration_time( globus_gsi_cred_handle_t handle )
{
time_t time_left;
if ( activate_globus_gsi() != 0 ) {
return -1;
}
if ((*globus_gsi_cred_get_lifetime_ptr)(handle, &time_left)) {
set_error_string( "unable to extract expiration time" );
return -1;
}
return time(NULL) + time_left;
}
char* x509_proxy_email( globus_gsi_cred_handle_t handle )
{
X509_NAME *email_orig = NULL;
STACK_OF(X509) *cert_chain = NULL;
GENERAL_NAME *gen;
GENERAL_NAMES *gens;
X509 *cert = NULL;
char *email = NULL, *email2 = NULL;
int i, j;
if ( activate_globus_gsi() != 0 ) {
return NULL;
}
if ((*globus_gsi_cred_get_cert_chain_ptr)(handle, &cert_chain)) {
cert = NULL;
set_error_string( "unable to find certificate in proxy" );
goto cleanup;
}
for(i = 0; i < sk_X509_num(cert_chain) && email == NULL; ++i) {
if((cert = sk_X509_value(cert_chain, i)) == NULL) {
continue;
}
if ((email_orig = (X509_NAME *)X509_get_ext_d2i(cert, NID_pkcs9_emailAddress, 0, 0)) != NULL) {
if ((email2 = X509_NAME_oneline(email_orig, NULL, 0)) == NULL) {
continue;
} else {
// Return something that we can free().
email = strdup(email2);
OPENSSL_free(email2);
break;
}
}
gens = (GENERAL_NAMES *)X509_get_ext_d2i(cert, NID_subject_alt_name, 0, 0);
if (gens) {
for (j = 0; j < sk_GENERAL_NAME_num(gens); ++j) {
if ((gen = sk_GENERAL_NAME_value(gens, j)) == NULL) {
continue;
}
if (gen->type != GEN_EMAIL) {
continue;
}
ASN1_IA5STRING *email_ia5 = gen->d.ia5;
// Sanity checks.
if (email_ia5->type != V_ASN1_IA5STRING) goto cleanup;
if (!email_ia5->data || !email_ia5->length) goto cleanup;
email2 = BUF_strdup((char *)email_ia5->data);
// We want to return something we can free(), so make another copy.
if (email2) {
email = strdup(email2);
OPENSSL_free(email2);
}
break;
}
sk_GENERAL_NAME_pop_free(gens, GENERAL_NAME_free);
}
}
if (email == NULL) {
set_error_string( "unable to extract email" );
goto cleanup;
}
cleanup:
if (cert_chain) {
sk_X509_pop_free(cert_chain, X509_free);
}
if (email_orig) {
X509_NAME_free(email_orig);
}
return email;
}
char* x509_proxy_subject_name( globus_gsi_cred_handle_t handle )
{
char *subject_name = NULL;
if ( activate_globus_gsi() != 0 ) {
return NULL;
}
if ((*globus_gsi_cred_get_subject_name_ptr)(handle, &subject_name)) {
set_error_string( "unable to extract subject name" );
return NULL;
}
return subject_name;
}
char* x509_proxy_identity_name( globus_gsi_cred_handle_t handle )
{
char *subject_name = NULL;
if ( activate_globus_gsi() != 0 ) {
return NULL;
}
if ((*globus_gsi_cred_get_identity_name_ptr)(handle, &subject_name)) {
set_error_string( "unable to extract identity name" );
return NULL;
}
return subject_name;
}
int x509_proxy_seconds_until_expire( globus_gsi_cred_handle_t handle )
{
time_t time_now;
time_t time_expire;
time_t time_diff;
time_now = time(NULL);
time_expire = x509_proxy_expiration_time( handle );
if ( time_expire == -1 ) {
return -1;
}
time_diff = time_expire - time_now;
if ( time_diff < 0 ) {
time_diff = 0;
}
return (int)time_diff;
}
int
extract_VOMS_info( globus_gsi_cred_handle_t cred_handle, int verify_type, char **voname, char **firstfqan, char **quoted_DN_and_FQAN)
{
#if !defined(HAVE_EXT_VOMS)
return 1;
#else
int ret;
struct vomsdata *voms_data = NULL;
struct voms *voms_cert = NULL;
char *subject_name = NULL;
char **fqan = NULL;
int voms_err;
int fqan_len = 0;
char *retfqan = NULL;
char *tmp_scan_ptr = NULL;
STACK_OF(X509) *chain = NULL;
X509 *cert = NULL;
char* x509_fqan_delimiter = NULL;
if ( activate_globus_gsi() != 0 ) {
return 1;
}
// calling this function on something that doesn't have VOMS attributes
// should return error 1. when the config knob disables VOMS, behave the
// same way.
if (!param_boolean_int("USE_VOMS_ATTRIBUTES", 1)) {
return 1;
}
ret = (*globus_gsi_cred_get_cert_chain_ptr)(cred_handle, &chain);
if(ret != GLOBUS_SUCCESS) {
ret = 10;
goto end;
}
ret = (*globus_gsi_cred_get_cert_ptr)(cred_handle, &cert);
if(ret != GLOBUS_SUCCESS) {
ret = 11;
goto end;
}
if ((*globus_gsi_cred_get_identity_name_ptr)(cred_handle, &subject_name)) {
set_error_string( "unable to extract subject name" );
ret = 12;
goto end;
}
voms_data = (*VOMS_Init_ptr)(NULL, NULL);
if (voms_data == NULL) {
ret = 13;
goto end;
}
if (verify_type == 0) {
ret = (*VOMS_SetVerificationType_ptr)( VERIFY_NONE, voms_data, &voms_err );
if (ret == 0) {
(*VOMS_ErrorMessage_ptr)(voms_data, voms_err, NULL, 0);
ret = voms_err;
goto end;
}
}
ret = (*VOMS_Retrieve_ptr)(cert, chain, RECURSE_CHAIN,
voms_data, &voms_err);
if (ret == 0) {
if (voms_err == VERR_NOEXT) {
// No VOMS extensions present
ret = 1;
goto end;
} else {
(*VOMS_ErrorMessage_ptr)(voms_data, voms_err, NULL, 0);
ret = voms_err;
goto end;
}
}
// we only support one cert for now. serializing and encoding all the
// attributes is bad enough, i don't want to deal with doing this to
// multiple certs.
voms_cert = voms_data->data[0];
// fill in the unquoted versions of things
if(voname) {
*voname = strdup(voms_cert->voname);
}
if(firstfqan) {
*firstfqan = strdup(voms_cert->fqan[0]);
}
// only construct the quoted_DN_and_FQAN if needed
if (quoted_DN_and_FQAN) {
// get our delimiter and trim it
if (!(x509_fqan_delimiter = param("X509_FQAN_DELIMITER"))) {
x509_fqan_delimiter = strdup(",");
}
tmp_scan_ptr = trim_quotes(x509_fqan_delimiter);
free(x509_fqan_delimiter);
x509_fqan_delimiter = tmp_scan_ptr;
// calculate the length
fqan_len = 0;
// start with the length of the quoted DN
tmp_scan_ptr = quote_x509_string( subject_name );
fqan_len += strlen( tmp_scan_ptr );
free(tmp_scan_ptr);
// add the length of delimiter plus each voms attribute
for (fqan = voms_cert->fqan; fqan && *fqan; fqan++) {
// delimiter
fqan_len += strlen(x509_fqan_delimiter);
tmp_scan_ptr = quote_x509_string( *fqan );
fqan_len += strlen( tmp_scan_ptr );
free(tmp_scan_ptr);
}
// now malloc enough room for the quoted DN, quoted attrs, delimiters, and
// NULL terminator
retfqan = (char*) malloc (fqan_len+1);
*retfqan = 0; // set null terminiator
// reset length counter -- we use this for efficient appending.
fqan_len = 0;
// start with the quoted DN
tmp_scan_ptr = quote_x509_string( subject_name );
strcat(retfqan, tmp_scan_ptr);
fqan_len += strlen( tmp_scan_ptr );
free(tmp_scan_ptr);
// add the delimiter plus each voms attribute
for (fqan = voms_cert->fqan; fqan && *fqan; fqan++) {
// delimiter
strcat(&(retfqan[fqan_len]), x509_fqan_delimiter);
fqan_len += strlen(x509_fqan_delimiter);
tmp_scan_ptr = quote_x509_string( *fqan );
strcat(&(retfqan[fqan_len]), tmp_scan_ptr);
fqan_len += strlen( tmp_scan_ptr );
free(tmp_scan_ptr);
}
*quoted_DN_and_FQAN = retfqan;
}
ret = 0;
end:
free(subject_name);
free(x509_fqan_delimiter);
if (voms_data)
(*VOMS_Destroy_ptr)(voms_data);
if (cert)
X509_free(cert);
if(chain)
sk_X509_pop_free(chain, X509_free);
return ret;
#endif
}
int
extract_VOMS_info_from_file( const char* proxy_file, int verify_type, char **voname, char **firstfqan, char **quoted_DN_and_FQAN)
{
globus_gsi_cred_handle_t handle = NULL;
globus_gsi_cred_handle_attrs_t handle_attrs = NULL;
char *my_proxy_file = NULL;
int error = 0;
if ( activate_globus_gsi() != 0 ) {
return 2;
}
if ((*globus_gsi_cred_handle_attrs_init_ptr)(&handle_attrs)) {
set_error_string( "problem during internal initialization1" );
error = 3;
goto cleanup;
}
if ((*globus_gsi_cred_handle_init_ptr)(&handle, handle_attrs)) {
set_error_string( "problem during internal initialization2" );
error = 4;
goto cleanup;
}
/* Check for proxy file */
if (proxy_file == NULL) {
my_proxy_file = get_x509_proxy_filename();
if (my_proxy_file == NULL) {
error = 5;
goto cleanup;
}
proxy_file = my_proxy_file;
}
// We should have a proxy file, now, try to read it
if ((*globus_gsi_cred_read_proxy_ptr)(handle, proxy_file)) {
set_error_string( "unable to read proxy file" );
error = 6;
goto cleanup;
}
error = extract_VOMS_info( handle, verify_type, voname, firstfqan, quoted_DN_and_FQAN );
cleanup:
if (my_proxy_file) {
free(my_proxy_file);
}
if (handle_attrs) {
(*globus_gsi_cred_handle_attrs_destroy_ptr)(handle_attrs);
}
if (handle) {
(*globus_gsi_cred_handle_destroy_ptr)(handle);
}
return error; // success
}
#endif /* defined(HAVE_EXT_GLOBUS) */
/* Return the email of a given proxy cert.
On error, return NULL.
On success, return a pointer to a null-terminated string.
IT IS THE CALLER'S RESPONSBILITY TO DE-ALLOCATE THE STIRNG
WITH free().
*/
char *
x509_proxy_email( const char *proxy_file )
{
#if !defined(HAVE_EXT_GLOBUS)
(void) proxy_file;
set_error_string( NOT_SUPPORTED_MSG );
return NULL;
#else
char *email = NULL;
globus_gsi_cred_handle_t proxy_handle = x509_proxy_read( proxy_file );
if ( proxy_handle == NULL ) {
return NULL;
}
email = x509_proxy_email( proxy_handle );
x509_proxy_free( proxy_handle );
return email;
#endif /* !defined(HAVE_EXT_GLOBUS) */
}
/* Return the subject name of a given proxy cert.
On error, return NULL.
On success, return a pointer to a null-terminated string.
IT IS THE CALLER'S RESPONSBILITY TO DE-ALLOCATE THE STIRNG
WITH free().
*/
char *
x509_proxy_subject_name( const char *proxy_file )
{
#if !defined(HAVE_EXT_GLOBUS)
(void) proxy_file;
set_error_string( NOT_SUPPORTED_MSG );
return NULL;
#else
char *subject_name = NULL;
globus_gsi_cred_handle_t proxy_handle = x509_proxy_read( proxy_file );
if ( proxy_handle == NULL ) {
return NULL;
}
subject_name = x509_proxy_subject_name( proxy_handle );
x509_proxy_free( proxy_handle );
return subject_name;
#endif /* !defined(HAVE_EXT_GLOBUS) */
}
/* Return the identity name of a given X509 cert. For proxy certs, this
will return the identity that the proxy can act on behalf of, rather than
the subject of the proxy cert itself. Normally, this will have the
practical effect of stripping off any "/CN=proxy" strings from the subject
name.
On error, return NULL.
On success, return a pointer to a null-terminated string.
IT IS THE CALLER'S RESPONSBILITY TO DE-ALLOCATE THE STIRNG
WITH free().
*/
char *
x509_proxy_identity_name( const char *proxy_file )
{
#if !defined(HAVE_EXT_GLOBUS)
(void) proxy_file;
set_error_string( NOT_SUPPORTED_MSG );
return NULL;
#else
char *subject_name = NULL;
globus_gsi_cred_handle_t proxy_handle = x509_proxy_read( proxy_file );
if ( proxy_handle == NULL ) {
return NULL;
}
subject_name = x509_proxy_identity_name( proxy_handle );
x509_proxy_free( proxy_handle );
return subject_name;
#endif /* !defined(GSS_AUTHENTICATION) */
}
/* Return the time at which the proxy expires. On error, return -1.
*/
time_t
x509_proxy_expiration_time( const char *proxy_file )
{
#if !defined(HAVE_EXT_GLOBUS)
(void) proxy_file;
set_error_string( NOT_SUPPORTED_MSG );
return -1;
#else
time_t expiration_time = -1;
globus_gsi_cred_handle_t proxy_handle = x509_proxy_read( proxy_file );
if ( proxy_handle == NULL ) {
return -1;
}
expiration_time = x509_proxy_expiration_time( proxy_handle );
x509_proxy_free( proxy_handle );
return expiration_time;
#endif /* !defined(GSS_AUTHENTICATION) */
}
/* Return the number of seconds until the supplied proxy
* file will expire.
* On error, return -1. - Todd <tannenba@cs.wisc.edu>
*/
int
x509_proxy_seconds_until_expire( const char *proxy_file )
{
#if !defined(HAVE_EXT_GLOBUS)
(void) proxy_file;
set_error_string( NOT_SUPPORTED_MSG );
return -1;
#else
time_t time_now;
time_t time_expire;
time_t time_diff;
time_now = time(NULL);
time_expire = x509_proxy_expiration_time( proxy_file );
if ( time_expire == -1 ) {
return -1;
}
time_diff = time_expire - time_now;
if ( time_diff < 0 ) {
time_diff = 0;
}
return (int)time_diff;
#endif /* !defined(GSS_AUTHENTICATION) */
}
#if defined(HAVE_EXT_GLOBUS)
static int
buffer_to_bio( char *buffer, size_t buffer_len, BIO **bio )
{
if ( buffer == NULL ) {
return FALSE;
}
*bio = BIO_new( BIO_s_mem() );
if ( *bio == NULL ) {
return FALSE;
}
if ( BIO_write( *bio, buffer, buffer_len ) < (int)buffer_len ) {
BIO_free( *bio );
return FALSE;
}
return TRUE;
}
static int
bio_to_buffer( BIO *bio, char **buffer, size_t *buffer_len )
{
if ( bio == NULL ) {
return FALSE;
}
*buffer_len = BIO_pending( bio );
*buffer = (char *)malloc( *buffer_len );
if ( *buffer == NULL ) {
return FALSE;
}
if ( BIO_read( bio, *buffer, *buffer_len ) < (int)*buffer_len ) {
free( *buffer );
return FALSE;
}
return TRUE;
}
#endif /* defined(HAVE_EXT_GLOBUS) */
int
x509_send_delegation( const char *source_file,
time_t expiration_time,
time_t *result_expiration_time,
int (*recv_data_func)(void *, void **, size_t *),
void *recv_data_ptr,
int (*send_data_func)(void *, void *, size_t),
void *send_data_ptr )
{
#if !defined(HAVE_EXT_GLOBUS)
(void) source_file;
(void) expiration_time;
(void) result_expiration_time;
(void) recv_data_func;
(void) recv_data_ptr;
(void) send_data_func;
(void) send_data_ptr;
_globus_error_message =
strdup( NOT_SUPPORTED_MSG );
return -1;
#else
int rc = 0;
int error_line = 0;
globus_result_t result = GLOBUS_SUCCESS;
globus_gsi_cred_handle_t source_cred = NULL;
globus_gsi_proxy_handle_t new_proxy = NULL;
char *buffer = NULL;
size_t buffer_len = 0;
BIO *bio = NULL;
X509 *cert = NULL;
STACK_OF(X509) *cert_chain = NULL;
int idx = 0;
globus_gsi_cert_utils_cert_type_t cert_type;
int is_limited;
if ( activate_globus_gsi() != 0 ) {
return -1;
}
result = (*globus_gsi_cred_handle_init_ptr)( &source_cred, NULL );
if ( result != GLOBUS_SUCCESS ) {
rc = -1;
error_line = __LINE__;
goto cleanup;
}
result = (*globus_gsi_proxy_handle_init_ptr)( &new_proxy, NULL );
if ( result != GLOBUS_SUCCESS ) {
rc = -1;
error_line = __LINE__;
goto cleanup;
}
result = (*globus_gsi_cred_read_proxy_ptr)( source_cred, source_file );
if ( result != GLOBUS_SUCCESS ) {
rc = -1;
error_line = __LINE__;
goto cleanup;
}
if ( recv_data_func( recv_data_ptr, (void **)&buffer, &buffer_len ) != 0 ) {
rc = -1;
error_line = __LINE__;
goto cleanup;
}
if ( buffer_to_bio( buffer, buffer_len, &bio ) == FALSE ) {
rc = -1;
error_line = __LINE__;
goto cleanup;
}
free( buffer );
buffer = NULL;
result = (*globus_gsi_proxy_inquire_req_ptr)( new_proxy, bio );
if ( result != GLOBUS_SUCCESS ) {
rc = -1;
error_line = __LINE__;
goto cleanup;
}
BIO_free( bio );
bio = NULL;
// modify certificate properties
// set the appropriate proxy type
result = (*globus_gsi_cred_get_cert_type_ptr)( source_cred, &cert_type );
if ( result != GLOBUS_SUCCESS ) {
rc = -1;
error_line = __LINE__;
goto cleanup;
}
switch ( cert_type ) {
case GLOBUS_GSI_CERT_UTILS_TYPE_CA:
rc = -1;
error_line = __LINE__;
goto cleanup;
case GLOBUS_GSI_CERT_UTILS_TYPE_EEC:
case GLOBUS_GSI_CERT_UTILS_TYPE_GSI_3_INDEPENDENT_PROXY:
case GLOBUS_GSI_CERT_UTILS_TYPE_GSI_3_RESTRICTED_PROXY:
cert_type = GLOBUS_GSI_CERT_UTILS_TYPE_GSI_3_IMPERSONATION_PROXY;
break;
case GLOBUS_GSI_CERT_UTILS_TYPE_RFC_INDEPENDENT_PROXY:
case GLOBUS_GSI_CERT_UTILS_TYPE_RFC_RESTRICTED_PROXY:
cert_type = GLOBUS_GSI_CERT_UTILS_TYPE_RFC_IMPERSONATION_PROXY;
break;
case GLOBUS_GSI_CERT_UTILS_TYPE_GSI_3_IMPERSONATION_PROXY:
case GLOBUS_GSI_CERT_UTILS_TYPE_GSI_3_LIMITED_PROXY:
case GLOBUS_GSI_CERT_UTILS_TYPE_GSI_2_PROXY:
case GLOBUS_GSI_CERT_UTILS_TYPE_GSI_2_LIMITED_PROXY:
case GLOBUS_GSI_CERT_UTILS_TYPE_RFC_IMPERSONATION_PROXY:
case GLOBUS_GSI_CERT_UTILS_TYPE_RFC_LIMITED_PROXY:
default:
// Use the same certificate type
break;
}
result = (*globus_gsi_proxy_handle_set_type_ptr)( new_proxy, cert_type);
if ( result != GLOBUS_SUCCESS ) {
rc = -1;
error_line = __LINE__;
goto cleanup;
}
// see if this should be made a limited proxy
is_limited = !(param_boolean_int("DELEGATE_FULL_JOB_GSI_CREDENTIALS", 0));
if (is_limited) {
result = (*globus_gsi_proxy_handle_set_is_limited_ptr)( new_proxy, GLOBUS_TRUE);
if ( result != GLOBUS_SUCCESS ) {
rc = -1;
error_line = __LINE__;
goto cleanup;
}
}
if( expiration_time || result_expiration_time ) {
time_t time_left = 0;
result = (*globus_gsi_cred_get_lifetime_ptr)( source_cred, &time_left );
if ( result != GLOBUS_SUCCESS ) {
rc = -1;
error_line = __LINE__;
goto cleanup;
}
time_t now = time(NULL);
int orig_expiration_time = now + time_left;
if( result_expiration_time ) {
*result_expiration_time = orig_expiration_time;
}
if( expiration_time && orig_expiration_time > expiration_time ) {
int time_valid = (expiration_time - now)/60;
result = (*globus_gsi_proxy_handle_set_time_valid_ptr)( new_proxy, time_valid );
if ( result != GLOBUS_SUCCESS ) {
rc = -1;
error_line = __LINE__;
goto cleanup;
}
if( result_expiration_time ) {
*result_expiration_time = expiration_time;
}
}
}
/* TODO Do we have to destroy and re-create bio, or can we reuse it? */
bio = BIO_new( BIO_s_mem() );
if ( bio == NULL ) {
rc = -1;
error_line = __LINE__;
goto cleanup;
}
result = (*globus_gsi_proxy_sign_req_ptr)( new_proxy, source_cred, bio );
if ( result != GLOBUS_SUCCESS ) {
rc = -1;
error_line = __LINE__;
goto cleanup;
}
// Now we need to stuff the certificate chain into in the bio.
// This consists of the signed certificate and its whole chain.
result = (*globus_gsi_cred_get_cert_ptr)( source_cred, &cert );
if ( result != GLOBUS_SUCCESS ) {
rc = -1;
error_line = __LINE__;
goto cleanup;
}
i2d_X509_bio( bio, cert );
X509_free( cert );
cert = NULL;
result = (*globus_gsi_cred_get_cert_chain_ptr)( source_cred, &cert_chain );
if ( result != GLOBUS_SUCCESS ) {
rc = -1;
error_line = __LINE__;
goto cleanup;
}
for( idx = 0; idx < sk_X509_num( cert_chain ); idx++ ) {
X509 *next_cert;
next_cert = sk_X509_value( cert_chain, idx );
i2d_X509_bio( bio, next_cert );
}
sk_X509_pop_free( cert_chain, X509_free );
cert_chain = NULL;
if ( bio_to_buffer( bio, &buffer, &buffer_len ) == FALSE ) {
rc = -1;
error_line = __LINE__;
goto cleanup;
}
if ( send_data_func( send_data_ptr, buffer, buffer_len ) != 0 ) {
rc = -1;
error_line = __LINE__;
goto cleanup;
}
cleanup:
/* TODO Extract Globus error message if result isn't GLOBUS_SUCCESS */
if ( error_line ) {
char buff[1024];
snprintf( buff, sizeof(buff), "x509_send_delegation failed at line %d",
error_line );
set_error_string( buff );
}
if ( bio ) {
BIO_free( bio );
}
if ( buffer ) {
free( buffer );
}
if ( new_proxy ) {
(*globus_gsi_proxy_handle_destroy_ptr)( new_proxy );
}
if ( source_cred ) {
(*globus_gsi_cred_handle_destroy_ptr)( source_cred );
}
if ( cert ) {
X509_free( cert );
}
if ( cert_chain ) {
sk_X509_pop_free( cert_chain, X509_free );
}
return rc;
#endif
}
#if defined(HAVE_EXT_GLOBUS)
struct x509_delegation_state
{
char *m_dest;
globus_gsi_proxy_handle_t m_request_handle;
};
#endif
int
x509_receive_delegation( const char *destination_file,
int (*recv_data_func)(void *, void **, size_t *),
void *recv_data_ptr,
int (*send_data_func)(void *, void *, size_t),
void *send_data_ptr,
void ** state_ptr )
{
#if !defined(HAVE_EXT_GLOBUS)
(void) destination_file; // Quiet compiler warnings
(void) recv_data_func; // Quiet compiler warnings
(void) recv_data_ptr; // Quiet compiler warnings
(void) send_data_func; // Quiet compiler warnings
(void) send_data_ptr; // Quiet compiler warnings
(void) state_ptr; // Quiet compiler warnings
_globus_error_message =
strdup( NOT_SUPPORTED_MSG );
return -1;
#else
int rc = 0;
int error_line = 0;
x509_delegation_state *st = new x509_delegation_state();
st->m_dest = strdup(destination_file);
globus_result_t result = GLOBUS_SUCCESS;
st->m_request_handle = NULL;
globus_gsi_proxy_handle_attrs_t handle_attrs = NULL;
char *buffer = NULL;
size_t buffer_len = 0;
BIO *bio = NULL;
if ( activate_globus_gsi() != 0 ) {
if ( st->m_dest ) { free(st->m_dest); }
delete st;
return -1;
}
// declare some vars we'll need
int globus_bits = 0;
int bits = 0;
int skew = 0;
// prepare any special attributes desired
result = (*globus_gsi_proxy_handle_attrs_init_ptr)( &handle_attrs );
if ( result != GLOBUS_SUCCESS ) {
rc = -1;
error_line = __LINE__;
goto cleanup;
}
// first, get the default that globus is using
result = (*globus_gsi_proxy_handle_attrs_get_keybits_ptr)( handle_attrs, &globus_bits );
if ( result != GLOBUS_SUCCESS ) {
rc = -1;
error_line = __LINE__;
goto cleanup;
}
// as of 2014-01-16, many various pieces of the OSG software stack no
// longer work with proxies less than 1024 bits, so make sure globus is
// defaulting to at least that large
if (globus_bits < 1024) {
globus_bits = 1024;
result = (*globus_gsi_proxy_handle_attrs_set_keybits_ptr)( handle_attrs, globus_bits );
if ( result != GLOBUS_SUCCESS ) {
rc = -1;
error_line = __LINE__;
goto cleanup;
}
}
// also allow the condor admin to increase it if they really feel the need
bits = param_integer("GSI_DELEGATION_KEYBITS", 0);
if (bits > globus_bits) {
result = (*globus_gsi_proxy_handle_attrs_set_keybits_ptr)( handle_attrs, bits );
if ( result != GLOBUS_SUCCESS ) {
rc = -1;
error_line = __LINE__;
goto cleanup;
}
}
// default for clock skew is currently (2013-03-27) 5 minutes, but allow
// that to be changed
skew = param_integer("GSI_DELEGATION_CLOCK_SKEW_ALLOWABLE", 0);
if (skew) {
result = (*globus_gsi_proxy_handle_attrs_set_clock_skew_allowable_ptr)( handle_attrs, skew );
if ( result != GLOBUS_SUCCESS ) {
rc = -1;
error_line = __LINE__;
goto cleanup;
}
}
// Note: inspecting the Globus implementation, globus_gsi_proxy_handle_init creates a copy
// of handle_attrs; hence, it's OK for handle_attrs to be destroyed before m_request_handle.
result = (*globus_gsi_proxy_handle_init_ptr)( &(st->m_request_handle), handle_attrs );
if ( result != GLOBUS_SUCCESS ) {
rc = -1;
error_line = __LINE__;
goto cleanup;
}
bio = BIO_new( BIO_s_mem() );
if ( bio == NULL ) {
rc = -1;
error_line = __LINE__;
goto cleanup;
}
result = (*globus_gsi_proxy_create_req_ptr)( st->m_request_handle, bio );
if ( result != GLOBUS_SUCCESS ) {
rc = -1;
error_line = __LINE__;
goto cleanup;
}
if ( bio_to_buffer( bio, &buffer, &buffer_len ) == FALSE ) {
rc = -1;
error_line = __LINE__;
goto cleanup;
}
BIO_free( bio );
bio = NULL;
if ( send_data_func( send_data_ptr, buffer, buffer_len ) != 0 ) {
rc = -1;
error_line = __LINE__;
goto cleanup;
}
free( buffer );
buffer = NULL;
cleanup:
/* TODO Extract Globus error message if result isn't GLOBUS_SUCCESS */
if ( error_line ) {
char buff[1024];
snprintf( buff, sizeof(buff), "x509_receive_delegation failed "
"at line %d", error_line );
buff[1023] = '\0';
set_error_string( buff );
}
if ( bio ) {
BIO_free( bio );
}
if ( buffer ) {
free( buffer );
}
if (handle_attrs) {
(*globus_gsi_proxy_handle_attrs_destroy_ptr)( handle_attrs );
}
// Error! Cleanup memory immediately and return.
if ( rc && st ) {
if ( st->m_request_handle ) {
(*globus_gsi_proxy_handle_destroy_ptr)( st->m_request_handle );
}
if ( st->m_dest ) { free(st->m_dest); }
delete st;
return rc;
}
// We were given a state pointer - caller will take care of monitoring the
// socket for more data and call delegation_finish later.
if (state_ptr != NULL) {
*state_ptr = st;
return 2;
}
// Else, we block and finish up immediately.
return x509_receive_delegation_finish(recv_data_func, recv_data_ptr, &st);
#endif
}
// Finish up the delegation operation, waiting for data on the socket if necessary.
// NOTE: get_x509_delegation_finish will take ownership of state_ptr and free its
// memory.
int x509_receive_delegation_finish(int (*recv_data_func)(void *, void **, size_t *),
void *recv_data_ptr,
void *state_ptr_raw)
{
#if !defined(HAVE_EXT_GLOBUS)
(void) recv_data_func; // Quiet compiler warnings
(void) recv_data_ptr; // Quiet compiler warnings
(void) state_ptr_raw; // Quiet compiler warnings
_globus_error_message =
strdup( NOT_SUPPORTED_MSG );
return -1;
#else
x509_delegation_state *state_ptr = static_cast<x509_delegation_state*>(state_ptr_raw);
globus_result_t result = GLOBUS_SUCCESS;
globus_gsi_cred_handle_t proxy_handle = NULL;
int rc = 0;
int error_line = 0;
char *buffer = NULL;
size_t buffer_len = 0;
BIO *bio = NULL;
if ( recv_data_func( recv_data_ptr, (void **)&buffer, &buffer_len ) != 0 ) {
rc = -1;
error_line = __LINE__;
goto cleanup;
}
if ( buffer_to_bio( buffer, buffer_len, &bio ) == FALSE ) {
rc = -1;
error_line = __LINE__;
goto cleanup;
}
result = (*globus_gsi_proxy_assemble_cred_ptr)( state_ptr->m_request_handle, &proxy_handle,
bio );
if ( result != GLOBUS_SUCCESS ) {
rc = -1;
error_line = __LINE__;
goto cleanup;
}
/* globus_gsi_cred_write_proxy() declares its second argument non-const,
* but never modifies it. The copy gets rid of compiler warnings.
*/
result = (*globus_gsi_cred_write_proxy_ptr)( proxy_handle, state_ptr->m_dest );
if ( result != GLOBUS_SUCCESS ) {
rc = -1;
error_line = __LINE__;
goto cleanup;
}
cleanup:
/* TODO Extract Globus error message if result isn't GLOBUS_SUCCESS */
if ( error_line ) {
char buff[1024];
snprintf( buff, sizeof(buff), "x509_receive_delegation failed "
"at line %d", error_line );
set_error_string( buff );
}
if ( bio ) {
BIO_free( bio );
}
if ( buffer ) {
free( buffer );
}
if ( state_ptr ) {
if ( state_ptr->m_request_handle ) {
(*globus_gsi_proxy_handle_destroy_ptr)( state_ptr->m_request_handle );
}
if ( state_ptr->m_dest ) { free(state_ptr->m_dest); }
delete state_ptr;
}
if ( proxy_handle ) {
(*globus_gsi_cred_handle_destroy_ptr)( proxy_handle );
}
return rc;
#endif
}
void parse_resource_manager_string( const char *string, char **host,
char **port, char **service,
char **subject )
{
char *p;
char *q;
size_t len = strlen( string );
char *my_host = (char *)calloc( len+1, sizeof(char) );
char *my_port = (char *)calloc( len+1, sizeof(char) );
char *my_service = (char *)calloc( len+1, sizeof(char) );
char *my_subject = (char *)calloc( len+1, sizeof(char) );
ASSERT( my_host && my_port && my_service && my_subject );
p = my_host;
q = my_host;
while ( *string != '\0' ) {
if ( *string == ':' ) {
if ( q == my_host ) {
p = my_port;
q = my_port;
string++;
} else if ( q == my_port || q == my_service ) {
p = my_subject;
q = my_subject;
string++;
} else {
*(p++) = *(string++);
}
} else if ( *string == '/' ) {
if ( q == my_host || q == my_port ) {
p = my_service;
q = my_service;
string++;
} else {
*(p++) = *(string++);
}
} else {
*(p++) = *(string++);
}
}
if ( host != NULL ) {
*host = my_host;
} else {
free( my_host );
}
if ( port != NULL ) {
*port = my_port;
} else {
free( my_port );
}
if ( service != NULL ) {
*service = my_service;
} else {
free( my_service );
}
if ( subject != NULL ) {
*subject = my_subject;
} else {
free( my_subject );
}
}
/* Returns true (non-0) if path looks like an URL that Globus
(specifically, globus-url-copy) can handle
Expected use: is the input/stdout file actually a Globus URL
that we can just hand off to Globus instead of a local file
that we need to rewrite as a Globus URL.
Probably doesn't make sense to use if universe != globus
*/
int
is_globus_friendly_url(const char * path)
{
if(path == 0)
return 0;
// Should this be more aggressive and allow anything with ://?
return
strstr(path, "http://") == path ||
strstr(path, "https://") == path ||
strstr(path, "ftp://") == path ||
strstr(path, "gsiftp://") == path ||
0;
}
|
/*
* Copyright (c) 2015 Nikolay Zapolnov (zapolnov@gmail.com).
*
* 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 "AbstractSceneComponent.h"
namespace B3D
{
AbstractSceneComponent::AbstractSceneComponent()
{
}
AbstractSceneComponent::~AbstractSceneComponent()
{
}
void AbstractSceneComponent::onBeforeSizeChanged(IScene*, glm::vec2&)
{
}
void AbstractSceneComponent::onAfterSizeChanged(IScene*, const glm::vec2&)
{
}
void AbstractSceneComponent::onBeforeUpdateScene(IScene*, double)
{
}
void AbstractSceneComponent::onAfterUpdateScene(IScene*, double)
{
}
void AbstractSceneComponent::onBeforeDrawScene(const IScene*, ICanvas*)
{
}
void AbstractSceneComponent::onAfterDrawScene(const IScene*, ICanvas*)
{
}
void AbstractSceneComponent::onBeforeTouchEvent(TouchEvent, int, glm::vec2&, bool&)
{
}
void AbstractSceneComponent::onAfterTouchEvent(TouchEvent, int, const glm::vec2&, bool&)
{
}
void AbstractSceneComponent::onBeforeSendEvent(const IEvent*, bool)
{
}
void AbstractSceneComponent::onAfterSendEvent(const IEvent*, bool)
{
}
}
|
#pragma once
namespace cuttle {
using function_id_t = unsigned int;
const function_id_t FUNCTION_ID_ERROR = 0;
const function_id_t FUNCTION_ID_UNKNOWN = 1;
const function_id_t FUNCTION_ID_LAST = 2;
const function_id_t FUNCTION_ID_START = 3;
}
|
/*
* This program 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 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* Copyright 2011, Blender Foundation.
*/
#include "COM_CompositorContext.h"
#include "COM_defines.h"
#include <cstdio>
#include "BLI_assert.h"
namespace blender::compositor {
CompositorContext::CompositorContext()
{
this->m_scene = nullptr;
this->m_rd = nullptr;
this->m_quality = eCompositorQuality::High;
this->m_hasActiveOpenCLDevices = false;
this->m_fastCalculation = false;
this->m_viewSettings = nullptr;
this->m_displaySettings = nullptr;
}
int CompositorContext::getFramenumber() const
{
BLI_assert(m_rd);
return m_rd->cfra;
}
} // namespace blender::compositor
|
/*
* Copyright (c) 2020, Liav A. <liavalb@hotmail.co.il>
* 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <Kernel/Assertions.h>
#include <Kernel/Time/HPETComparator.h>
#include <Kernel/Time/TimeManagement.h>
//#define HPET_COMPARATOR_DEBUG
namespace Kernel {
NonnullRefPtr<HPETComparator> HPETComparator::create(u8 number, u8 irq, bool periodic_capable)
{
return adopt(*new HPETComparator(number, irq, periodic_capable, [](const RegisterState& regs) { TimeManagement::stale_function(regs); }));
}
HPETComparator::HPETComparator(u8 number, u8 irq, bool periodic_capable, Function<void(const RegisterState&)> callback)
: HardwareTimer(irq, move(callback))
, m_periodic(false)
, m_periodic_capable(periodic_capable)
, m_comparator_number(number)
{
}
void HPETComparator::set_periodic()
{
ASSERT(m_periodic_capable);
HPET::the().enable_periodic_interrupt(*this);
m_periodic = true;
}
void HPETComparator::set_non_periodic()
{
ASSERT(m_periodic_capable);
HPET::the().disable_periodic_interrupt(*this);
m_periodic = false;
}
void HPETComparator::handle_irq(const RegisterState& regs)
{
HardwareTimer::handle_irq(regs);
if (!is_periodic())
set_new_countdown();
}
void HPETComparator::set_new_countdown()
{
ASSERT_INTERRUPTS_DISABLED();
ASSERT(m_frequency <= HPET::the().frequency());
HPET::the().set_non_periodic_comparator_value(*this, HPET::the().frequency() / m_frequency);
}
size_t HPETComparator::ticks_per_second() const
{
return m_frequency;
}
void HPETComparator::reset_to_default_ticks_per_second()
{
ASSERT(is_capable_of_frequency(OPTIMAL_TICKS_PER_SECOND_RATE));
m_frequency = OPTIMAL_TICKS_PER_SECOND_RATE;
if (!is_periodic())
set_new_countdown();
else
try_to_set_frequency(m_frequency);
}
bool HPETComparator::try_to_set_frequency(size_t frequency)
{
InterruptDisabler disabler;
if (!is_capable_of_frequency(frequency))
return false;
disable_irq();
auto hpet_frequency = HPET::the().frequency();
ASSERT(frequency <= hpet_frequency);
#ifdef HPET_COMPARATOR_DEBUG
dbg() << "HPET Comparator: Max frequency - " << hpet_frequency << " Hz, want to set " << frequency << " Hz";
#endif
if (is_periodic())
HPET::the().set_periodic_comparator_value(*this, hpet_frequency / frequency);
else {
HPET::the().set_non_periodic_comparator_value(*this, hpet_frequency / frequency);
HPET::the().enable(*this);
}
m_frequency = frequency;
enable_irq();
return true;
}
bool HPETComparator::is_capable_of_frequency(size_t frequency) const
{
if (frequency > HPET::the().frequency())
return false;
if ((HPET::the().frequency() % frequency) != 0)
return false;
return true;
}
size_t HPETComparator::calculate_nearest_possible_frequency(size_t frequency) const
{
if (frequency >= HPET::the().frequency())
return HPET::the().frequency();
// FIXME: Use better math here
return (frequency + (HPET::the().frequency() % frequency));
}
}
|
/*Exercise 3 - Repeatition
Convert the C program given below which calculates the Factorial of a number that you input from the keyboard to a C++ program.
Please Note that the input command in C++ is std::cin. This is a representation of the Keyboard.*/
#include <iostream>
using namespace std;
int main()
{
int no;
long fac;
cout << "Enter a Number : ";
cin >> no;
fac = 1;
for (int r=no; r >= 1; r--) {
fac = fac * r;
}
cout << "Factorial of " << no << " is "<< fac;
return 0;
}
|
// This file is part of the Luau programming language and is licensed under MIT License; see LICENSE.txt for details
#include "Luau/AstQuery.h"
#include "Luau/BuiltinDefinitions.h"
#include "Luau/Parser.h"
#include "Luau/Scope.h"
#include "Luau/TypeInfer.h"
#include "Luau/TypeVar.h"
#include "Luau/VisitTypeVar.h"
#include "Fixture.h"
#include "doctest.h"
#include <algorithm>
LUAU_FASTFLAG(LuauFixLocationSpanTableIndexExpr)
LUAU_FASTFLAG(LuauEqConstraint)
LUAU_FASTFLAG(LuauExtendedFunctionMismatchError)
using namespace Luau;
TEST_SUITE_BEGIN("TypeInfer");
TEST_CASE_FIXTURE(Fixture, "tc_hello_world")
{
CheckResult result = check("local a = 7");
LUAU_REQUIRE_NO_ERRORS(result);
TypeId aType = requireType("a");
CHECK_EQ(getPrimitiveType(aType), PrimitiveTypeVar::Number);
}
TEST_CASE_FIXTURE(Fixture, "tc_propagation")
{
CheckResult result = check("local a = 7 local b = a");
LUAU_REQUIRE_NO_ERRORS(result);
TypeId bType = requireType("b");
CHECK_EQ(getPrimitiveType(bType), PrimitiveTypeVar::Number);
}
TEST_CASE_FIXTURE(Fixture, "tc_error")
{
CheckResult result = check("local a = 7 local b = 'hi' a = b");
LUAU_REQUIRE_ERROR_COUNT(1, result);
CHECK_EQ(result.errors[0], (TypeError{Location{Position{0, 35}, Position{0, 36}}, TypeMismatch{
requireType("a"),
requireType("b"),
}}));
}
TEST_CASE_FIXTURE(Fixture, "tc_error_2")
{
CheckResult result = check("local a = 7 a = 'hi'");
LUAU_REQUIRE_ERROR_COUNT(1, result);
CHECK_EQ(result.errors[0], (TypeError{Location{Position{0, 18}, Position{0, 22}}, TypeMismatch{
requireType("a"),
typeChecker.stringType,
}}));
}
TEST_CASE_FIXTURE(Fixture, "tc_function")
{
CheckResult result = check("function five() return 5 end");
LUAU_REQUIRE_NO_ERRORS(result);
const FunctionTypeVar* fiveType = get<FunctionTypeVar>(requireType("five"));
REQUIRE(fiveType != nullptr);
}
TEST_CASE_FIXTURE(Fixture, "infer_locals_with_nil_value")
{
CheckResult result = check("local f = nil; f = 'hello world'");
LUAU_REQUIRE_NO_ERRORS(result);
TypeId ty = requireType("f");
CHECK_EQ(getPrimitiveType(ty), PrimitiveTypeVar::String);
}
TEST_CASE_FIXTURE(Fixture, "infer_locals_via_assignment_from_its_call_site")
{
CheckResult result = check(R"(
local a
function f(x) a = x end
f(1)
f("foo")
)");
LUAU_REQUIRE_ERROR_COUNT(1, result);
CHECK_EQ("number", toString(requireType("a")));
}
TEST_CASE_FIXTURE(Fixture, "infer_in_nocheck_mode")
{
CheckResult result = check(R"(
--!nocheck
function f(x)
return x
end
-- we get type information even if there's type errors
f(1, 2)
)");
CHECK_EQ("(any) -> (...any)", toString(requireType("f")));
LUAU_REQUIRE_NO_ERRORS(result);
}
TEST_CASE_FIXTURE(Fixture, "check_function_bodies")
{
CheckResult result = check("function myFunction() local a = 0 a = true end");
LUAU_REQUIRE_ERROR_COUNT(1, result);
CHECK_EQ(result.errors[0], (TypeError{Location{Position{0, 44}, Position{0, 48}}, TypeMismatch{
typeChecker.numberType,
typeChecker.booleanType,
}}));
}
TEST_CASE_FIXTURE(Fixture, "infer_return_type")
{
CheckResult result = check("function take_five() return 5 end");
LUAU_REQUIRE_NO_ERRORS(result);
const FunctionTypeVar* takeFiveType = get<FunctionTypeVar>(requireType("take_five"));
REQUIRE(takeFiveType != nullptr);
std::vector<TypeId> retVec = flatten(takeFiveType->retType).first;
REQUIRE(!retVec.empty());
REQUIRE_EQ(*follow(retVec[0]), *typeChecker.numberType);
}
TEST_CASE_FIXTURE(Fixture, "infer_from_function_return_type")
{
CheckResult result = check("function take_five() return 5 end local five = take_five()");
LUAU_REQUIRE_NO_ERRORS(result);
CHECK_EQ(*typeChecker.numberType, *follow(requireType("five")));
}
TEST_CASE_FIXTURE(Fixture, "cannot_call_primitives")
{
CheckResult result = check("local foo = 5 foo()");
LUAU_REQUIRE_ERROR_COUNT(1, result);
REQUIRE(get<CannotCallNonFunction>(result.errors[0]) != nullptr);
}
TEST_CASE_FIXTURE(Fixture, "cannot_call_tables")
{
CheckResult result = check("local foo = {} foo()");
LUAU_REQUIRE_ERROR_COUNT(1, result);
CHECK(get<CannotCallNonFunction>(result.errors[0]) != nullptr);
}
TEST_CASE_FIXTURE(Fixture, "infer_that_function_does_not_return_a_table")
{
CheckResult result = check(R"(
function take_five()
return 5
end
take_five().prop = 888
)");
LUAU_REQUIRE_ERROR_COUNT(1, result);
CHECK_EQ(result.errors[0], (TypeError{Location{Position{5, 8}, Position{5, 24}}, NotATable{typeChecker.numberType}}));
}
TEST_CASE_FIXTURE(Fixture, "expr_statement")
{
CheckResult result = check("local foo = 5 foo()");
LUAU_REQUIRE_ERROR_COUNT(1, result);
}
TEST_CASE_FIXTURE(Fixture, "generic_function")
{
CheckResult result = check(R"(
function id(x) return x end
local a = id(55)
local b = id(nil)
)");
LUAU_REQUIRE_NO_ERRORS(result);
CHECK_EQ(*typeChecker.numberType, *requireType("a"));
CHECK_EQ(*typeChecker.nilType, *requireType("b"));
}
TEST_CASE_FIXTURE(Fixture, "vararg_functions_should_allow_calls_of_any_types_and_size")
{
CheckResult result = check(R"(
function f(...) end
f(1)
f("foo", 2)
)");
LUAU_REQUIRE_NO_ERRORS(result);
}
TEST_CASE_FIXTURE(Fixture, "vararg_function_is_quantified")
{
CheckResult result = check(R"(
local T = {}
function T.f(...)
local result = {}
for i = 1, select("#", ...) do
local dictionary = select(i, ...)
for key, value in pairs(dictionary) do
result[key] = value
end
end
return result
end
return T
)");
auto r = first(getMainModule()->getModuleScope()->returnType);
REQUIRE(r);
TableTypeVar* ttv = getMutable<TableTypeVar>(*r);
REQUIRE(ttv);
TypeId k = ttv->props["f"].type;
REQUIRE(k);
LUAU_REQUIRE_NO_ERRORS(result);
}
TEST_CASE_FIXTURE(Fixture, "for_loop")
{
CheckResult result = check(R"(
local q
for i=0, 50, 2 do
q = i
end
)");
LUAU_REQUIRE_NO_ERRORS(result);
CHECK_EQ(*typeChecker.numberType, *requireType("q"));
}
TEST_CASE_FIXTURE(Fixture, "for_in_loop")
{
CheckResult result = check(R"(
local n
local s
for i, v in pairs({ "foo" }) do
n = i
s = v
end
)");
LUAU_REQUIRE_NO_ERRORS(result);
CHECK_EQ(*typeChecker.numberType, *requireType("n"));
CHECK_EQ(*typeChecker.stringType, *requireType("s"));
}
TEST_CASE_FIXTURE(Fixture, "for_in_loop_with_next")
{
CheckResult result = check(R"(
local n
local s
for i, v in next, { "foo", "bar" } do
n = i
s = v
end
)");
LUAU_REQUIRE_NO_ERRORS(result);
CHECK_EQ(*typeChecker.numberType, *requireType("n"));
CHECK_EQ(*typeChecker.stringType, *requireType("s"));
}
TEST_CASE_FIXTURE(Fixture, "for_in_with_an_iterator_of_type_any")
{
CheckResult result = check(R"(
local it: any
local a, b
for i, v in it do
a, b = i, v
end
)");
LUAU_REQUIRE_NO_ERRORS(result);
}
TEST_CASE_FIXTURE(Fixture, "for_in_loop_should_fail_with_non_function_iterator")
{
CheckResult result = check(R"(
local foo = "bar"
for i, v in foo do
end
)");
LUAU_REQUIRE_ERROR_COUNT(1, result);
}
TEST_CASE_FIXTURE(Fixture, "for_in_with_just_one_iterator_is_ok")
{
CheckResult result = check(R"(
local function keys(dictionary)
local new = {}
local index = 1
for key in pairs(dictionary) do
new[index] = key
index = index + 1
end
return new
end
)");
LUAU_REQUIRE_NO_ERRORS(result);
}
TEST_CASE_FIXTURE(Fixture, "for_in_with_a_custom_iterator_should_type_check")
{
CheckResult result = check(R"(
local function range(l, h): () -> number
return function()
return l
end
end
for n: string in range(1, 10) do
print(n)
end
)");
LUAU_REQUIRE_ERROR_COUNT(1, result);
}
TEST_CASE_FIXTURE(Fixture, "for_in_loop_on_error")
{
CheckResult result = check(R"(
function f(x)
gobble.prop = x.otherprop
end
local p
for _, part in i_am_not_defined do
p = part
f(part)
part.thirdprop = false
end
)");
CHECK_EQ(2, result.errors.size());
TypeId p = requireType("p");
CHECK_EQ("*unknown*", toString(p));
}
TEST_CASE_FIXTURE(Fixture, "for_in_loop_on_non_function")
{
CheckResult result = check(R"(
local bad_iter = 5
for a in bad_iter() do
end
)");
LUAU_REQUIRE_ERROR_COUNT(1, result);
REQUIRE(get<CannotCallNonFunction>(result.errors[0]));
}
TEST_CASE_FIXTURE(Fixture, "for_in_loop_error_on_factory_not_returning_the_right_amount_of_values")
{
CheckResult result = check(R"(
local function hasDivisors(value: number, table)
return false
end
function prime_iter(state, index)
while hasDivisors(index, state) do
index += 1
end
state[index] = true
return index
end
function primes1()
return prime_iter, {}
end
function primes2()
return prime_iter, {}, ""
end
function primes3()
return prime_iter, {}, 2
end
for p in primes1() do print(p) end -- mismatch in argument count
for p in primes2() do print(p) end -- mismatch in argument types, prime_iter takes {}, number, we are given {}, string
for p in primes3() do print(p) end -- no error
)");
LUAU_REQUIRE_ERROR_COUNT(2, result);
CountMismatch* acm = get<CountMismatch>(result.errors[0]);
REQUIRE(acm);
CHECK_EQ(acm->context, CountMismatch::Arg);
CHECK_EQ(2, acm->expected);
CHECK_EQ(1, acm->actual);
TypeMismatch* tm = get<TypeMismatch>(result.errors[1]);
REQUIRE(tm);
CHECK_EQ(typeChecker.numberType, tm->wantedType);
CHECK_EQ(typeChecker.stringType, tm->givenType);
}
TEST_CASE_FIXTURE(Fixture, "for_in_loop_error_on_iterator_requiring_args_but_none_given")
{
CheckResult result = check(R"(
function prime_iter(state, index)
return 1
end
for p in prime_iter do print(p) end
)");
LUAU_REQUIRE_ERROR_COUNT(1, result);
CountMismatch* acm = get<CountMismatch>(result.errors[0]);
REQUIRE(acm);
CHECK_EQ(acm->context, CountMismatch::Arg);
CHECK_EQ(2, acm->expected);
CHECK_EQ(0, acm->actual);
}
TEST_CASE_FIXTURE(Fixture, "for_in_loop_iterator_returns_any")
{
CheckResult result = check(R"(
function bar(): any
return true
end
local a
for b in bar do
a = b
end
)");
LUAU_REQUIRE_NO_ERRORS(result);
CHECK_EQ(typeChecker.anyType, requireType("a"));
}
TEST_CASE_FIXTURE(Fixture, "for_in_loop_iterator_returns_any2")
{
CheckResult result = check(R"(
function bar(): any
return true
end
local a
for b in bar() do
a = b
end
)");
LUAU_REQUIRE_NO_ERRORS(result);
CHECK_EQ("any", toString(requireType("a")));
}
TEST_CASE_FIXTURE(Fixture, "for_in_loop_iterator_is_any")
{
CheckResult result = check(R"(
local bar: any
local a
for b in bar do
a = b
end
)");
LUAU_REQUIRE_NO_ERRORS(result);
CHECK_EQ("any", toString(requireType("a")));
}
TEST_CASE_FIXTURE(Fixture, "for_in_loop_iterator_is_any2")
{
CheckResult result = check(R"(
local bar: any
local a
for b in bar() do
a = b
end
)");
LUAU_REQUIRE_NO_ERRORS(result);
CHECK_EQ("any", toString(requireType("a")));
}
TEST_CASE_FIXTURE(Fixture, "for_in_loop_iterator_is_error")
{
CheckResult result = check(R"(
local a
for b in bar do
a = b
end
)");
LUAU_REQUIRE_ERROR_COUNT(1, result);
CHECK_EQ("*unknown*", toString(requireType("a")));
}
TEST_CASE_FIXTURE(Fixture, "for_in_loop_iterator_is_error2")
{
CheckResult result = check(R"(
function bar(c) return c end
local a
for b in bar() do
a = b
end
)");
LUAU_REQUIRE_ERROR_COUNT(1, result);
CHECK_EQ("*unknown*", toString(requireType("a")));
}
TEST_CASE_FIXTURE(Fixture, "for_in_loop_with_custom_iterator")
{
CheckResult result = check(R"(
function primes()
return function (state: number) end, 2
end
for p, q in primes do
q = ""
end
)");
LUAU_REQUIRE_ERROR_COUNT(1, result);
TypeMismatch* tm = get<TypeMismatch>(result.errors[0]);
REQUIRE(tm);
CHECK_EQ(typeChecker.numberType, tm->wantedType);
CHECK_EQ(typeChecker.stringType, tm->givenType);
}
TEST_CASE_FIXTURE(Fixture, "if_statement")
{
CheckResult result = check(R"(
local a
local b
if true then
a = 'hello'
else
b = 999
end
)");
LUAU_REQUIRE_NO_ERRORS(result);
CHECK_EQ(*typeChecker.stringType, *requireType("a"));
CHECK_EQ(*typeChecker.numberType, *requireType("b"));
}
TEST_CASE_FIXTURE(Fixture, "while_loop")
{
CheckResult result = check(R"(
local i
while true do
i = 8
end
)");
LUAU_REQUIRE_NO_ERRORS(result);
CHECK_EQ(*typeChecker.numberType, *requireType("i"));
}
TEST_CASE_FIXTURE(Fixture, "repeat_loop")
{
CheckResult result = check(R"(
local i
repeat
i = 'hi'
until true
)");
LUAU_REQUIRE_NO_ERRORS(result);
CHECK_EQ(*typeChecker.stringType, *requireType("i"));
}
TEST_CASE_FIXTURE(Fixture, "repeat_loop_condition_binds_to_its_block")
{
CheckResult result = check(R"(
repeat
local x = true
until x
)");
LUAU_REQUIRE_NO_ERRORS(result);
}
TEST_CASE_FIXTURE(Fixture, "symbols_in_repeat_block_should_not_be_visible_beyond_until_condition")
{
CheckResult result = check(R"(
repeat
local x = true
until x
print(x)
)");
LUAU_REQUIRE_ERROR_COUNT(1, result);
}
TEST_CASE_FIXTURE(Fixture, "table_length")
{
CheckResult result = check(R"(
local t = {}
local s = #t
)");
LUAU_REQUIRE_NO_ERRORS(result);
CHECK(nullptr != get<TableTypeVar>(requireType("t")));
CHECK_EQ(*typeChecker.numberType, *requireType("s"));
}
TEST_CASE_FIXTURE(Fixture, "string_length")
{
CheckResult result = check(R"(
local s = "Hello, World!"
local t = #s
)");
LUAU_REQUIRE_NO_ERRORS(result);
CHECK_EQ("number", toString(requireType("t")));
}
TEST_CASE_FIXTURE(Fixture, "string_index")
{
CheckResult result = check(R"(
local s = "Hello, World!"
local t = s[4]
)");
LUAU_REQUIRE_ERROR_COUNT(1, result);
NotATable* nat = get<NotATable>(result.errors[0]);
REQUIRE(nat);
CHECK_EQ("string", toString(nat->ty));
CHECK_EQ("*unknown*", toString(requireType("t")));
}
TEST_CASE_FIXTURE(Fixture, "length_of_error_type_does_not_produce_an_error")
{
CheckResult result = check(R"(
local l = #this_is_not_defined
)");
LUAU_REQUIRE_ERROR_COUNT(1, result);
}
TEST_CASE_FIXTURE(Fixture, "indexing_error_type_does_not_produce_an_error")
{
CheckResult result = check(R"(
local originalReward = unknown.Parent.Reward:GetChildren()[1]
)");
LUAU_REQUIRE_ERROR_COUNT(1, result);
}
TEST_CASE_FIXTURE(Fixture, "nil_assign_doesnt_hit_indexer")
{
CheckResult result = check("local a = {} a[0] = 7 a[0] = nil");
LUAU_REQUIRE_ERROR_COUNT(0, result);
}
TEST_CASE_FIXTURE(Fixture, "wrong_assign_does_hit_indexer")
{
CheckResult result = check("local a = {} a[0] = 7 a[0] = 't'");
LUAU_REQUIRE_ERROR_COUNT(1, result);
CHECK_EQ(result.errors[0], (TypeError{Location{Position{0, 30}, Position{0, 33}}, TypeMismatch{
typeChecker.numberType,
typeChecker.stringType,
}}));
}
TEST_CASE_FIXTURE(Fixture, "nil_assign_doesnt_hit_no_indexer")
{
CheckResult result = check("local a = {a=1, b=2} a['a'] = nil");
LUAU_REQUIRE_ERROR_COUNT(1, result);
CHECK_EQ(result.errors[0], (TypeError{Location{Position{0, 30}, Position{0, 33}}, TypeMismatch{
typeChecker.numberType,
typeChecker.nilType,
}}));
}
TEST_CASE_FIXTURE(Fixture, "dot_on_error_type_does_not_produce_an_error")
{
CheckResult result = check(R"(
local foo = (true).x
foo.x = foo.y
)");
LUAU_REQUIRE_ERROR_COUNT(1, result);
}
TEST_CASE_FIXTURE(Fixture, "dont_suggest_using_colon_rather_than_dot_if_not_defined_with_colon")
{
CheckResult result = check(R"(
local someTable = {}
someTable.Function1 = function(Arg1)
end
someTable.Function1() -- Argument count mismatch
)");
LUAU_REQUIRE_ERROR_COUNT(1, result);
REQUIRE(get<CountMismatch>(result.errors[0]));
}
TEST_CASE_FIXTURE(Fixture, "dont_suggest_using_colon_rather_than_dot_if_it_wont_help_2")
{
CheckResult result = check(R"(
local someTable = {}
someTable.Function2 = function(Arg1, Arg2)
end
someTable.Function2() -- Argument count mismatch
)");
LUAU_REQUIRE_ERROR_COUNT(1, result);
REQUIRE(get<CountMismatch>(result.errors[0]));
}
TEST_CASE_FIXTURE(Fixture, "dont_suggest_using_colon_rather_than_dot_if_another_overload_works")
{
CheckResult result = check(R"(
type T = {method: ((T, number) -> number) & ((number) -> number)}
local T: T
T.method(4)
)");
LUAU_REQUIRE_NO_ERRORS(result);
}
TEST_CASE_FIXTURE(Fixture, "list_only_alternative_overloads_that_match_argument_count")
{
CheckResult result = check(R"(
local multiply: ((number)->number) & ((number)->string) & ((number, number)->number)
multiply("")
)");
LUAU_REQUIRE_ERROR_COUNT(2, result);
TypeMismatch* tm = get<TypeMismatch>(result.errors[0]);
REQUIRE(tm);
CHECK_EQ(typeChecker.numberType, tm->wantedType);
CHECK_EQ(typeChecker.stringType, tm->givenType);
ExtraInformation* ei = get<ExtraInformation>(result.errors[1]);
REQUIRE(ei);
CHECK_EQ("Other overloads are also not viable: (number) -> string", ei->message);
}
TEST_CASE_FIXTURE(Fixture, "list_all_overloads_if_no_overload_takes_given_argument_count")
{
CheckResult result = check(R"(
local multiply: ((number)->number) & ((number)->string) & ((number, number)->number)
multiply()
)");
LUAU_REQUIRE_ERROR_COUNT(2, result);
GenericError* ge = get<GenericError>(result.errors[0]);
REQUIRE(ge);
CHECK_EQ("No overload for function accepts 0 arguments.", ge->message);
ExtraInformation* ei = get<ExtraInformation>(result.errors[1]);
REQUIRE(ei);
CHECK_EQ("Available overloads: (number) -> number; (number) -> string; and (number, number) -> number", ei->message);
}
TEST_CASE_FIXTURE(Fixture, "dont_give_other_overloads_message_if_only_one_argument_matching_overload_exists")
{
CheckResult result = check(R"(
local multiply: ((number)->number) & ((number)->string) & ((number, number)->number)
multiply(1, "")
)");
LUAU_REQUIRE_ERROR_COUNT(1, result);
TypeMismatch* tm = get<TypeMismatch>(result.errors[0]);
REQUIRE(tm);
CHECK_EQ(typeChecker.numberType, tm->wantedType);
CHECK_EQ(typeChecker.stringType, tm->givenType);
}
TEST_CASE_FIXTURE(Fixture, "infer_return_type_from_selected_overload")
{
CheckResult result = check(R"(
type T = {method: ((T, number) -> number) & ((number) -> string)}
local T: T
local a = T.method(T, 4)
local b = T.method(5)
)");
LUAU_REQUIRE_NO_ERRORS(result);
CHECK_EQ("number", toString(requireType("a")));
CHECK_EQ("string", toString(requireType("b")));
}
TEST_CASE_FIXTURE(Fixture, "too_many_arguments")
{
CheckResult result = check(R"(
--!nonstrict
function g(a: number) end
g()
)");
LUAU_REQUIRE_ERROR_COUNT(1, result);
auto err = result.errors[0];
auto acm = get<CountMismatch>(err);
REQUIRE(acm);
CHECK_EQ(1, acm->expected);
CHECK_EQ(0, acm->actual);
}
TEST_CASE_FIXTURE(Fixture, "any_type_propagates")
{
CheckResult result = check(R"(
local foo: any
local bar = foo:method("argument")
)");
LUAU_REQUIRE_NO_ERRORS(result);
CHECK_EQ("any", toString(requireType("bar")));
}
TEST_CASE_FIXTURE(Fixture, "can_subscript_any")
{
CheckResult result = check(R"(
local foo: any
local bar = foo[5]
)");
LUAU_REQUIRE_NO_ERRORS(result);
CHECK_EQ("any", toString(requireType("bar")));
}
// Not strictly correct: metatables permit overriding this
TEST_CASE_FIXTURE(Fixture, "can_get_length_of_any")
{
CheckResult result = check(R"(
local foo: any = {}
local bar = #foo
)");
LUAU_REQUIRE_NO_ERRORS(result);
CHECK_EQ(PrimitiveTypeVar::Number, getPrimitiveType(requireType("bar")));
}
TEST_CASE_FIXTURE(Fixture, "recursive_function")
{
CheckResult result = check(R"(
function count(n: number)
if n == 0 then
return 0
else
return count(n - 1)
end
end
)");
LUAU_REQUIRE_NO_ERRORS(result);
}
TEST_CASE_FIXTURE(Fixture, "lambda_form_of_local_function_cannot_be_recursive")
{
CheckResult result = check(R"(
local f = function() return f() end
)");
LUAU_REQUIRE_ERROR_COUNT(1, result);
}
TEST_CASE_FIXTURE(Fixture, "recursive_local_function")
{
CheckResult result = check(R"(
local function count(n: number)
if n == 0 then
return 0
else
return count(n - 1)
end
end
)");
LUAU_REQUIRE_NO_ERRORS(result);
}
// FIXME: This and the above case get handled very differently. It's pretty dumb.
// We really should unify the two code paths, probably by deleting AstStatFunction.
TEST_CASE_FIXTURE(Fixture, "another_recursive_local_function")
{
CheckResult result = check(R"(
local count
function count(n: number)
if n == 0 then
return 0
else
return count(n - 1)
end
end
)");
LUAU_REQUIRE_NO_ERRORS(result);
}
TEST_CASE_FIXTURE(Fixture, "cyclic_function_type_in_rets")
{
ScopedFastFlag sff{"LuauOccursCheckOkWithRecursiveFunctions", true};
CheckResult result = check(R"(
function f()
return f
end
)");
LUAU_REQUIRE_NO_ERRORS(result);
CHECK_EQ("t1 where t1 = () -> t1", toString(requireType("f")));
}
TEST_CASE_FIXTURE(Fixture, "cyclic_function_type_in_args")
{
ScopedFastFlag sff{"LuauOccursCheckOkWithRecursiveFunctions", true};
CheckResult result = check(R"(
function f(g)
return f(f)
end
)");
LUAU_REQUIRE_NO_ERRORS(result);
CHECK_EQ("t1 where t1 = (t1) -> ()", toString(requireType("f")));
}
// TODO: File a Jira about this
/*
TEST_CASE_FIXTURE(Fixture, "unifying_vararg_pack_with_fixed_length_pack_produces_fixed_length_pack")
{
CheckResult result = check(R"(
function a(x) return 1 end
a(...)
)");
LUAU_REQUIRE_NO_ERRORS(result);
REQUIRE(bool(getMainModule()->getModuleScope()->varargPack));
TypePackId varargPack = *getMainModule()->getModuleScope()->varargPack;
auto iter = begin(varargPack);
auto endIter = end(varargPack);
CHECK(iter != endIter);
++iter;
CHECK(iter == endIter);
CHECK(!iter.tail());
}
*/
TEST_CASE_FIXTURE(Fixture, "method_depends_on_table")
{
CheckResult result = check(R"(
-- This catches a bug where x:m didn't count as a use of x
-- so toposort would happily reorder a definition of
-- function x:m before the definition of x.
function g() f() end
local x = {}
function x:m() end
function f() x:m() end
)");
LUAU_REQUIRE_NO_ERRORS(result);
}
TEST_CASE_FIXTURE(Fixture, "another_higher_order_function")
{
CheckResult result = check(R"(
local Get_des
function Get_des(func)
Get_des(func)
end
local function f(d)
d:IsA("BasePart")
d.Parent:FindFirstChild("Humanoid")
d:IsA("Decal")
end
Get_des(f)
)");
LUAU_REQUIRE_NO_ERRORS(result);
}
TEST_CASE_FIXTURE(Fixture, "another_other_higher_order_function")
{
CheckResult result = check(R"(
local d
d:foo()
d:foo()
)");
LUAU_REQUIRE_NO_ERRORS(result);
}
TEST_CASE_FIXTURE(Fixture, "statements_are_topologically_sorted")
{
CheckResult result = check(R"(
function foo()
return bar(999), bar("hi")
end
function bar(i)
return i
end
)");
LUAU_REQUIRE_NO_ERRORS(result);
dumpErrors(result);
}
TEST_CASE_FIXTURE(Fixture, "generic_table_method")
{
CheckResult result = check(R"(
local T = {}
function T:bar(i)
return i
end
)");
LUAU_REQUIRE_NO_ERRORS(result);
TypeId tType = requireType("T");
TableTypeVar* tTable = getMutable<TableTypeVar>(tType);
REQUIRE(tTable != nullptr);
TypeId barType = tTable->props["bar"].type;
REQUIRE(barType != nullptr);
const FunctionTypeVar* ftv = get<FunctionTypeVar>(follow(barType));
REQUIRE_MESSAGE(ftv != nullptr, "Should be a function: " << *barType);
std::vector<TypeId> args = flatten(ftv->argTypes).first;
TypeId argType = args.at(1);
CHECK_MESSAGE(get<Unifiable::Generic>(argType), "Should be generic: " << *barType);
}
TEST_CASE_FIXTURE(Fixture, "correctly_instantiate_polymorphic_member_functions")
{
CheckResult result = check(R"(
local T = {}
function T:foo()
return T:bar(5)
end
function T:bar(i)
return i
end
)");
LUAU_REQUIRE_NO_ERRORS(result);
dumpErrors(result);
const TableTypeVar* t = get<TableTypeVar>(requireType("T"));
REQUIRE(t != nullptr);
std::optional<Property> fooProp = get(t->props, "foo");
REQUIRE(bool(fooProp));
const FunctionTypeVar* foo = get<FunctionTypeVar>(follow(fooProp->type));
REQUIRE(bool(foo));
std::optional<TypeId> ret_ = first(foo->retType);
REQUIRE(bool(ret_));
TypeId ret = follow(*ret_);
REQUIRE_EQ(getPrimitiveType(ret), PrimitiveTypeVar::Number);
}
TEST_CASE_FIXTURE(Fixture, "methods_are_topologically_sorted")
{
CheckResult result = check(R"(
local T = {}
function T:foo()
return T:bar(999), T:bar("hi")
end
function T:bar(i)
return i
end
local a, b = T:foo()
)");
LUAU_REQUIRE_NO_ERRORS(result);
dumpErrors(result);
CHECK_EQ(PrimitiveTypeVar::Number, getPrimitiveType(requireType("a")));
CHECK_EQ(PrimitiveTypeVar::String, getPrimitiveType(requireType("b")));
}
TEST_CASE_FIXTURE(Fixture, "local_function")
{
CheckResult result = check(R"(
function f()
return 8
end
function g()
local function f()
return 'hello'
end
return f
end
local h = g()
)");
LUAU_REQUIRE_NO_ERRORS(result);
TypeId h = follow(requireType("h"));
const FunctionTypeVar* ftv = get<FunctionTypeVar>(h);
REQUIRE(ftv != nullptr);
std::optional<TypeId> rt = first(ftv->retType);
REQUIRE(bool(rt));
TypeId retType = follow(*rt);
CHECK_EQ(PrimitiveTypeVar::String, getPrimitiveType(retType));
}
TEST_CASE_FIXTURE(Fixture, "unify_nearly_identical_recursive_types")
{
CheckResult result = check(R"(
local o
o:method()
local p
p:method()
o = p
)");
}
/*
* We had a bug in instantiation where the argument types of 'f' and 'g' would be inferred as
* f {+ method: function(<CYCLE>): (t2, T3...) +}
* g {+ method: function({+ method: function(<CYCLE>): (t2, T3...) +}): (t5, T6...) +}
*
* The type of 'g' is totally wrong as t2 and t5 should be unified, as should T3 with T6.
*
* The correct unification of the argument to 'g' is
*
* {+ method: function(<CYCLE>): (t5, T6...) +}
*/
TEST_CASE_FIXTURE(Fixture, "instantiate_cyclic_generic_function")
{
auto result = check(R"(
function f(o)
o:method()
end
function g(o)
f(o)
end
)");
TypeId g = requireType("g");
const FunctionTypeVar* gFun = get<FunctionTypeVar>(g);
REQUIRE(gFun != nullptr);
auto optionArg = first(gFun->argTypes);
REQUIRE(bool(optionArg));
TypeId arg = follow(*optionArg);
const TableTypeVar* argTable = get<TableTypeVar>(arg);
REQUIRE(argTable != nullptr);
std::optional<Property> methodProp = get(argTable->props, "method");
REQUIRE(bool(methodProp));
const FunctionTypeVar* methodFunction = get<FunctionTypeVar>(methodProp->type);
REQUIRE(methodFunction != nullptr);
std::optional<TypeId> methodArg = first(methodFunction->argTypes);
REQUIRE(bool(methodArg));
REQUIRE_EQ(follow(*methodArg), follow(arg));
}
TEST_CASE_FIXTURE(Fixture, "varlist_declared_by_for_in_loop_should_be_free")
{
CheckResult result = check(R"(
local T = {}
function T.f(p)
for i, v in pairs(p) do
T.f(v)
end
end
)");
LUAU_REQUIRE_NO_ERRORS(result);
}
TEST_CASE_FIXTURE(Fixture, "properly_infer_iteratee_is_a_free_table")
{
// In this case, we cannot know the element type of the table {}. It could be anything.
// We therefore must initially ascribe a free typevar to iter.
CheckResult result = check(R"(
for iter in pairs({}) do
iter:g().p = true
end
)");
LUAU_REQUIRE_NO_ERRORS(result);
}
TEST_CASE_FIXTURE(Fixture, "quantify_methods_defined_using_dot_syntax_and_explicit_self_parameter")
{
check(R"(
local T = {}
function T.method(self)
self:method()
end
function T.method2(self)
self:method()
end
T:method2()
)");
}
TEST_CASE_FIXTURE(Fixture, "free_rhs_table_can_also_be_bound")
{
check(R"(
local o
local v = o:i()
function g(u)
v = u
end
o:f(g)
o:h()
o:h()
)");
}
TEST_CASE_FIXTURE(Fixture, "require")
{
fileResolver.source["game/A"] = R"(
local function hooty(x: number): string
return "Hi there!"
end
return {hooty=hooty}
)";
fileResolver.source["game/B"] = R"(
local Hooty = require(game.A)
local h -- free!
local i = Hooty.hooty(h)
)";
CheckResult aResult = frontend.check("game/A");
dumpErrors(aResult);
LUAU_REQUIRE_NO_ERRORS(aResult);
CheckResult bResult = frontend.check("game/B");
dumpErrors(bResult);
LUAU_REQUIRE_NO_ERRORS(bResult);
ModulePtr b = frontend.moduleResolver.modules["game/B"];
REQUIRE(b != nullptr);
dumpErrors(bResult);
std::optional<TypeId> iType = requireType(b, "i");
REQUIRE_EQ("string", toString(*iType));
std::optional<TypeId> hType = requireType(b, "h");
REQUIRE_EQ("number", toString(*hType));
}
TEST_CASE_FIXTURE(Fixture, "require_types")
{
fileResolver.source["workspace/A"] = R"(
export type Point = {x: number, y: number}
return {}
)";
fileResolver.source["workspace/B"] = R"(
local Hooty = require(workspace.A)
local h: Hooty.Point
)";
CheckResult bResult = frontend.check("workspace/B");
dumpErrors(bResult);
ModulePtr b = frontend.moduleResolver.modules["workspace/B"];
REQUIRE(b != nullptr);
TypeId hType = requireType(b, "h");
REQUIRE_MESSAGE(bool(get<TableTypeVar>(hType)), "Expected table but got " << toString(hType));
}
TEST_CASE_FIXTURE(Fixture, "require_a_variadic_function")
{
fileResolver.source["game/A"] = R"(
local T = {}
function T.f(...) end
return T
)";
fileResolver.source["game/B"] = R"(
local A = require(game.A)
local f = A.f
)";
CheckResult result = frontend.check("game/B");
ModulePtr bModule = frontend.moduleResolver.getModule("game/B");
REQUIRE(bModule != nullptr);
TypeId f = follow(requireType(bModule, "f"));
const FunctionTypeVar* ftv = get<FunctionTypeVar>(f);
REQUIRE(ftv);
auto iter = begin(ftv->argTypes);
auto endIter = end(ftv->argTypes);
REQUIRE(iter == endIter);
REQUIRE(iter.tail());
CHECK(get<VariadicTypePack>(*iter.tail()));
}
TEST_CASE_FIXTURE(Fixture, "assign_prop_to_table_by_calling_any_yields_any")
{
CheckResult result = check(R"(
local f: any
local T = {}
T.prop = f()
return T
)");
LUAU_REQUIRE_NO_ERRORS(result);
TableTypeVar* ttv = getMutable<TableTypeVar>(requireType("T"));
REQUIRE(ttv);
REQUIRE(ttv->props.count("prop"));
REQUIRE_EQ("any", toString(ttv->props["prop"].type));
}
TEST_CASE_FIXTURE(Fixture, "type_error_of_unknown_qualified_type")
{
CheckResult result = check(R"(
local p: SomeModule.DoesNotExist
)");
LUAU_REQUIRE_ERROR_COUNT(1, result);
REQUIRE_EQ(result.errors[0], (TypeError{Location{{1, 17}, {1, 40}}, UnknownSymbol{"SomeModule.DoesNotExist"}}));
}
TEST_CASE_FIXTURE(Fixture, "require_module_that_does_not_export")
{
const std::string sourceA = R"(
)";
const std::string sourceB = R"(
local Hooty = require(script.Parent.A)
)";
fileResolver.source["game/Workspace/A"] = sourceA;
fileResolver.source["game/Workspace/B"] = sourceB;
frontend.check("game/Workspace/A");
frontend.check("game/Workspace/B");
ModulePtr aModule = frontend.moduleResolver.modules["game/Workspace/A"];
ModulePtr bModule = frontend.moduleResolver.modules["game/Workspace/B"];
CHECK(aModule->errors.empty());
REQUIRE_EQ(1, bModule->errors.size());
CHECK_MESSAGE(get<IllegalRequire>(bModule->errors[0]), "Should be IllegalRequire: " << toString(bModule->errors[0]));
auto hootyType = requireType(bModule, "Hooty");
CHECK_EQ("*unknown*", toString(hootyType));
}
TEST_CASE_FIXTURE(Fixture, "warn_on_lowercase_parent_property")
{
CheckResult result = check(R"(
local M = require(script.parent.DoesNotMatter)
)");
LUAU_REQUIRE_ERROR_COUNT(1, result);
auto ed = get<DeprecatedApiUsed>(result.errors[0]);
REQUIRE(ed);
REQUIRE_EQ("parent", ed->symbol);
}
TEST_CASE_FIXTURE(Fixture, "quantify_any_does_not_bind_to_itself")
{
CheckResult result = check(R"(
local A : any
function A.B() end
A:C()
)");
LUAU_REQUIRE_NO_ERRORS(result);
TypeId aType = requireType("A");
CHECK_EQ(aType, typeChecker.anyType);
}
TEST_CASE_FIXTURE(Fixture, "table_unifies_into_map")
{
CheckResult result = check(R"(
local Instance: any
local UDim2: any
function Create(instanceType)
return function(data)
local obj = Instance.new(instanceType)
for k, v in pairs(data) do
if type(k) == 'number' then
--v.Parent = obj
else
obj[k] = v
end
end
return obj
end
end
local topbarShadow = Create'ImageLabel'{
Name = "TopBarShadow";
Size = UDim2.new(1, 0, 0, 3);
Position = UDim2.new(0, 0, 1, 0);
Image = "rbxasset://textures/ui/TopBar/dropshadow.png";
BackgroundTransparency = 1;
Active = false;
Visible = false;
};
)");
LUAU_REQUIRE_NO_ERRORS(result);
}
TEST_CASE_FIXTURE(Fixture, "func_expr_doesnt_leak_free")
{
CheckResult result = check(R"(
local p = function(x) return x end
)");
LUAU_REQUIRE_NO_ERRORS(result);
const Luau::FunctionTypeVar* fn = get<FunctionTypeVar>(requireType("p"));
REQUIRE(fn);
auto ret = first(fn->retType);
REQUIRE(ret);
REQUIRE(get<GenericTypeVar>(follow(*ret)));
}
TEST_CASE_FIXTURE(Fixture, "instantiate_generic_function_in_assignments")
{
CheckResult result = check(R"(
function foo(a, b)
return a(b)
end
function bar()
local c: ((number)->number, number)->number = foo -- no error
c = foo -- no error
local d: ((number)->number, string)->number = foo -- error from arg 2 (string) not being convertable to number from the call a(b)
end
)");
LUAU_REQUIRE_ERROR_COUNT(1, result);
TypeMismatch* tm = get<TypeMismatch>(result.errors[0]);
REQUIRE(tm);
CHECK_EQ("((number) -> number, string) -> number", toString(tm->wantedType));
CHECK_EQ("((number) -> number, number) -> number", toString(tm->givenType));
}
TEST_CASE_FIXTURE(Fixture, "instantiate_generic_function_in_assignments2")
{
CheckResult result = check(R"(
function foo(a, b)
return a(b)
end
function bar()
local _: (string, string)->number = foo -- string cannot be converted to (string)->number
end
)");
LUAU_REQUIRE_ERROR_COUNT(1, result);
TypeMismatch* tm = get<TypeMismatch>(result.errors[0]);
REQUIRE(tm);
CHECK_EQ("(string, string) -> number", toString(tm->wantedType));
CHECK_EQ("((string) -> number, string) -> number", toString(*tm->givenType));
}
TEST_CASE_FIXTURE(Fixture, "string_method")
{
CheckResult result = check(R"(
local p = ("tacos"):len()
)");
CHECK_EQ(0, result.errors.size());
CHECK_EQ(*requireType("p"), *typeChecker.numberType);
}
TEST_CASE_FIXTURE(Fixture, "string_function_indirect")
{
CheckResult result = check(R"(
local s:string
local l = s.lower
local p = l(s)
)");
CHECK_EQ(0, result.errors.size());
CHECK_EQ(*requireType("p"), *typeChecker.stringType);
}
TEST_CASE_FIXTURE(Fixture, "string_function_other")
{
CheckResult result = check(R"(
local s:string
local p = s:match("foo")
)");
CHECK_EQ(0, result.errors.size());
CHECK_EQ(toString(requireType("p")), "string?");
}
TEST_CASE_FIXTURE(Fixture, "weird_case")
{
CheckResult result = check(R"(
local function f() return 4 end
local d = math.deg(f())
)");
LUAU_REQUIRE_NO_ERRORS(result);
dumpErrors(result);
}
TEST_CASE_FIXTURE(Fixture, "or_joins_types")
{
CheckResult result = check(R"(
local s = "a" or 10
local x:string|number = s
)");
LUAU_REQUIRE_NO_ERRORS(result);
CHECK_EQ(toString(*requireType("s")), "number | string");
CHECK_EQ(toString(*requireType("x")), "number | string");
}
TEST_CASE_FIXTURE(Fixture, "or_joins_types_with_no_extras")
{
CheckResult result = check(R"(
local s = "a" or 10
local x:number|string = s
local y = x or "s"
)");
CHECK_EQ(0, result.errors.size());
CHECK_EQ(toString(*requireType("s")), "number | string");
CHECK_EQ(toString(*requireType("y")), "number | string");
}
TEST_CASE_FIXTURE(Fixture, "or_joins_types_with_no_superfluous_union")
{
CheckResult result = check(R"(
local s = "a" or "b"
local x:string = s
)");
CHECK_EQ(0, result.errors.size());
CHECK_EQ(*requireType("s"), *typeChecker.stringType);
}
TEST_CASE_FIXTURE(Fixture, "and_adds_boolean")
{
CheckResult result = check(R"(
local s = "a" and 10
local x:boolean|number = s
)");
CHECK_EQ(0, result.errors.size());
CHECK_EQ(toString(*requireType("s")), "boolean | number");
}
TEST_CASE_FIXTURE(Fixture, "and_adds_boolean_no_superfluous_union")
{
CheckResult result = check(R"(
local s = "a" and true
local x:boolean = s
)");
CHECK_EQ(0, result.errors.size());
CHECK_EQ(*requireType("x"), *typeChecker.booleanType);
}
TEST_CASE_FIXTURE(Fixture, "and_or_ternary")
{
CheckResult result = check(R"(
local s = (1/2) > 0.5 and "a" or 10
)");
CHECK_EQ(0, result.errors.size());
CHECK_EQ(toString(*requireType("s")), "number | string");
}
TEST_CASE_FIXTURE(Fixture, "first_argument_can_be_optional")
{
CheckResult result = check(R"(
local T = {}
function T.new(a: number?, b: number?, c: number?) return 5 end
local m = T.new()
)");
LUAU_REQUIRE_NO_ERRORS(result);
dumpErrors(result);
}
TEST_CASE_FIXTURE(Fixture, "dont_ice_when_failing_the_occurs_check")
{
ScopedFastFlag sff{"LuauOccursCheckOkWithRecursiveFunctions", true};
CheckResult result = check(R"(
--!strict
local s
s(s, 'a')
)");
LUAU_REQUIRE_ERROR_COUNT(0, result);
}
TEST_CASE_FIXTURE(Fixture, "occurs_check_does_not_recurse_forever_if_asked_to_traverse_a_cyclic_type")
{
ScopedFastFlag sff{"LuauOccursCheckOkWithRecursiveFunctions", true};
CheckResult result = check(R"(
--!strict
function u(t, w)
u(u, t)
end
)");
LUAU_REQUIRE_NO_ERRORS(result);
}
#if 0
// CLI-29798
TEST_CASE_FIXTURE(Fixture, "crazy_complexity")
{
CheckResult result = check(R"(
--!nonstrict
A:A():A():A():A():A():A():A():A():A():A():A()
)");
std::cout << "OK! Allocated " << typeChecker.typeVars.size() << " typevars" << std::endl;
}
#endif
// We had a bug where a cyclic union caused a stack overflow.
// ex type U = number | U
TEST_CASE_FIXTURE(Fixture, "dont_allow_cyclic_unions_to_be_inferred")
{
CheckResult result = check(R"(
--!strict
function f(a, b)
a:g(b or {})
a:g(b)
end
)");
LUAU_REQUIRE_NO_ERRORS(result);
}
TEST_CASE_FIXTURE(Fixture, "it_is_ok_not_to_supply_enough_retvals")
{
CheckResult result = check(R"(
function get_two() return 5, 6 end
local a = get_two()
)");
LUAU_REQUIRE_NO_ERRORS(result);
dumpErrors(result);
}
TEST_CASE_FIXTURE(Fixture, "duplicate_functions2")
{
CheckResult result = check(R"(
function foo() end
function bar()
local function foo() end
end
)");
LUAU_REQUIRE_ERROR_COUNT(0, result);
}
TEST_CASE_FIXTURE(Fixture, "duplicate_functions_allowed_in_nonstrict")
{
CheckResult result = check(R"(
--!nonstrict
function foo() end
function foo() end
function bar()
local function foo() end
end
)");
LUAU_REQUIRE_NO_ERRORS(result);
}
TEST_CASE_FIXTURE(Fixture, "duplicate_functions_with_different_signatures_not_allowed_in_nonstrict")
{
CheckResult result = check(R"(
--!nonstrict
function foo(): number
return 1
end
foo()
function foo(n: number): number
return 2
end
foo()
)");
LUAU_REQUIRE_ERROR_COUNT(1, result);
TypeMismatch* tm = get<TypeMismatch>(result.errors[0]);
REQUIRE(tm);
CHECK_EQ("() -> number", toString(tm->wantedType));
CHECK_EQ("(number) -> number", toString(tm->givenType));
}
TEST_CASE_FIXTURE(Fixture, "tables_get_names_from_their_locals")
{
CheckResult result = check(R"(
local T = {}
)");
LUAU_REQUIRE_NO_ERRORS(result);
CHECK_EQ("T", toString(requireType("T")));
}
TEST_CASE_FIXTURE(Fixture, "generalize_table_argument")
{
CheckResult result = check(R"(
function foo(arr)
local work = {}
for i = 1, #arr do
work[i] = arr[i]
end
return arr
end
)");
LUAU_REQUIRE_NO_ERRORS(result);
dumpErrors(result);
const FunctionTypeVar* fooType = get<FunctionTypeVar>(requireType("foo"));
REQUIRE(fooType);
std::optional<TypeId> fooArg1 = first(fooType->argTypes);
REQUIRE(fooArg1);
const TableTypeVar* fooArg1Table = get<TableTypeVar>(*fooArg1);
REQUIRE(fooArg1Table);
CHECK_EQ(fooArg1Table->state, TableState::Generic);
}
TEST_CASE_FIXTURE(Fixture, "complicated_return_types_require_an_explicit_annotation")
{
CheckResult result = check(R"(
local i = 0
function most_of_the_natural_numbers(): number?
if i < 10 then
i = i + 1
return i
else
return nil
end
end
)");
LUAU_REQUIRE_NO_ERRORS(result);
const FunctionTypeVar* functionType = get<FunctionTypeVar>(requireType("most_of_the_natural_numbers"));
std::optional<TypeId> retType = first(functionType->retType);
REQUIRE(retType);
CHECK(get<UnionTypeVar>(*retType));
}
TEST_CASE_FIXTURE(Fixture, "infer_higher_order_function")
{
CheckResult result = check(R"(
function apply(f, x)
return f(x)
end
)");
LUAU_REQUIRE_NO_ERRORS(result);
const FunctionTypeVar* ftv = get<FunctionTypeVar>(requireType("apply"));
REQUIRE(ftv != nullptr);
std::vector<TypeId> argVec = flatten(ftv->argTypes).first;
REQUIRE_EQ(2, argVec.size());
const FunctionTypeVar* fType = get<FunctionTypeVar>(follow(argVec[0]));
REQUIRE(fType != nullptr);
std::vector<TypeId> fArgs = flatten(fType->argTypes).first;
TypeId xType = argVec[1];
CHECK_EQ(1, fArgs.size());
CHECK_EQ(xType, fArgs[0]);
}
TEST_CASE_FIXTURE(Fixture, "higher_order_function_2")
{
CheckResult result = check(R"(
function bottomupmerge(comp, a, b, left, mid, right)
local i, j = left, mid
for k = left, right do
if i < mid and (j > right or not comp(a[j], a[i])) then
b[k] = a[i]
i = i + 1
else
b[k] = a[j]
j = j + 1
end
end
end
)");
LUAU_REQUIRE_NO_ERRORS(result);
const FunctionTypeVar* ftv = get<FunctionTypeVar>(requireType("bottomupmerge"));
REQUIRE(ftv != nullptr);
std::vector<TypeId> argVec = flatten(ftv->argTypes).first;
REQUIRE_EQ(6, argVec.size());
const FunctionTypeVar* fType = get<FunctionTypeVar>(follow(argVec[0]));
REQUIRE(fType != nullptr);
}
TEST_CASE_FIXTURE(Fixture, "higher_order_function_3")
{
CheckResult result = check(R"(
function swap(p)
local t = p[0]
p[0] = p[1]
p[1] = t
return nil
end
function swapTwice(p)
swap(p)
swap(p)
return p
end
)");
LUAU_REQUIRE_NO_ERRORS(result);
const FunctionTypeVar* ftv = get<FunctionTypeVar>(requireType("swapTwice"));
REQUIRE(ftv != nullptr);
std::vector<TypeId> argVec = flatten(ftv->argTypes).first;
REQUIRE_EQ(1, argVec.size());
const TableTypeVar* argType = get<TableTypeVar>(follow(argVec[0]));
REQUIRE(argType != nullptr);
CHECK(bool(argType->indexer));
}
TEST_CASE_FIXTURE(Fixture, "higher_order_function_4")
{
CheckResult result = check(R"(
function bottomupmerge(comp, a, b, left, mid, right)
local i, j = left, mid
for k = left, right do
if i < mid and (j > right or not comp(a[j], a[i])) then
b[k] = a[i]
i = i + 1
else
b[k] = a[j]
j = j + 1
end
end
end
function mergesort(arr, comp)
local work = {}
for i = 1, #arr do
work[i] = arr[i]
end
local width = 1
while width < #arr do
for i = 1, #arr, 2*width do
bottomupmerge(comp, arr, work, i, math.min(i+width, #arr), math.min(i+2*width-1, #arr))
end
local temp = work
work = arr
arr = temp
width = width * 2
end
return arr
end
)");
LUAU_REQUIRE_NO_ERRORS(result);
dumpErrors(result);
/*
* mergesort takes two arguments: an array of some type T and a function that takes two Ts.
* We must assert that these two types are in fact the same type.
* In other words, comp(arr[x], arr[y]) is well-typed.
*/
const FunctionTypeVar* ftv = get<FunctionTypeVar>(requireType("mergesort"));
REQUIRE(ftv != nullptr);
std::vector<TypeId> argVec = flatten(ftv->argTypes).first;
REQUIRE_EQ(2, argVec.size());
const TableTypeVar* arg0 = get<TableTypeVar>(follow(argVec[0]));
REQUIRE(arg0 != nullptr);
REQUIRE(bool(arg0->indexer));
const FunctionTypeVar* arg1 = get<FunctionTypeVar>(follow(argVec[1]));
REQUIRE(arg1 != nullptr);
REQUIRE_EQ(2, size(arg1->argTypes));
std::vector<TypeId> arg1Args = flatten(arg1->argTypes).first;
CHECK_EQ(*arg0->indexer->indexResultType, *arg1Args[0]);
CHECK_EQ(*arg0->indexer->indexResultType, *arg1Args[1]);
}
TEST_CASE_FIXTURE(Fixture, "type_errors_infer_types")
{
CheckResult result = check(R"(
local err = (true).x
local c = err.Parent.Reward.GetChildren
local d = err.Parent.Reward
local e = err.Parent
local f = err
)");
LUAU_REQUIRE_ERROR_COUNT(1, result);
UnknownProperty* err = get<UnknownProperty>(result.errors[0]);
REQUIRE(err != nullptr);
CHECK_EQ("boolean", toString(err->table));
CHECK_EQ("x", err->key);
CHECK_EQ("*unknown*", toString(requireType("c")));
CHECK_EQ("*unknown*", toString(requireType("d")));
CHECK_EQ("*unknown*", toString(requireType("e")));
CHECK_EQ("*unknown*", toString(requireType("f")));
}
TEST_CASE_FIXTURE(Fixture, "calling_error_type_yields_error")
{
CheckResult result = check(R"(
local a = unknown.Parent.Reward.GetChildren()
)");
LUAU_REQUIRE_ERROR_COUNT(1, result);
UnknownSymbol* err = get<UnknownSymbol>(result.errors[0]);
REQUIRE(err != nullptr);
CHECK_EQ("unknown", err->name);
CHECK_EQ("*unknown*", toString(requireType("a")));
}
TEST_CASE_FIXTURE(Fixture, "chain_calling_error_type_yields_error")
{
CheckResult result = check(R"(
local a = Utility.Create "Foo" {}
)");
CHECK_EQ("*unknown*", toString(requireType("a")));
}
TEST_CASE_FIXTURE(Fixture, "primitive_arith_no_metatable")
{
CheckResult result = check(R"(
function add(a: number, b: string)
return a + (tonumber(b) :: number), a .. b
end
local n, s = add(2,"3")
)");
LUAU_REQUIRE_NO_ERRORS(result);
const FunctionTypeVar* functionType = get<FunctionTypeVar>(requireType("add"));
std::optional<TypeId> retType = first(functionType->retType);
CHECK_EQ(std::optional<TypeId>(typeChecker.numberType), retType);
CHECK_EQ(requireType("n"), typeChecker.numberType);
CHECK_EQ(requireType("s"), typeChecker.stringType);
}
TEST_CASE_FIXTURE(Fixture, "primitive_arith_no_metatable_with_follows")
{
CheckResult result = check(R"(
local PI=3.1415926535897931
local SOLAR_MASS=4*PI * PI
)");
LUAU_REQUIRE_NO_ERRORS(result);
CHECK_EQ(requireType("SOLAR_MASS"), typeChecker.numberType);
}
TEST_CASE_FIXTURE(Fixture, "primitive_arith_possible_metatable")
{
CheckResult result = check(R"(
function add(a: number, b: any)
return a + b
end
local t = add(1,2)
)");
LUAU_REQUIRE_NO_ERRORS(result);
CHECK_EQ("any", toString(requireType("t")));
}
TEST_CASE_FIXTURE(Fixture, "some_primitive_binary_ops")
{
CheckResult result = check(R"(
local a = 4 + 8
local b = a + 9
local s = 'hotdogs'
local t = s .. s
local c = b - a
)");
LUAU_REQUIRE_NO_ERRORS(result);
CHECK_EQ("number", toString(requireType("a")));
CHECK_EQ("number", toString(requireType("b")));
CHECK_EQ("string", toString(requireType("s")));
CHECK_EQ("string", toString(requireType("t")));
CHECK_EQ("number", toString(requireType("c")));
}
TEST_CASE_FIXTURE(Fixture, "typecheck_overloaded_multiply_that_is_an_intersection")
{
ScopedFastFlag sff{"LuauErrorRecoveryType", true};
CheckResult result = check(R"(
--!strict
local Vec3 = {}
Vec3.__index = Vec3
function Vec3.new()
return setmetatable({x=0, y=0, z=0}, Vec3)
end
export type Vec3 = typeof(Vec3.new())
local thefun: any = function(self, o) return self end
local multiply: ((Vec3, Vec3) -> Vec3) & ((Vec3, number) -> Vec3) = thefun
Vec3.__mul = multiply
local a = Vec3.new()
local b = Vec3.new()
local c = a * b
local d = a * 2
local e = a * 'cabbage'
)");
LUAU_REQUIRE_ERROR_COUNT(1, result);
CHECK_EQ("Vec3", toString(requireType("a")));
CHECK_EQ("Vec3", toString(requireType("b")));
CHECK_EQ("Vec3", toString(requireType("c")));
CHECK_EQ("Vec3", toString(requireType("d")));
CHECK_EQ("Vec3", toString(requireType("e")));
}
TEST_CASE_FIXTURE(Fixture, "typecheck_overloaded_multiply_that_is_an_intersection_on_rhs")
{
ScopedFastFlag sff{"LuauErrorRecoveryType", true};
CheckResult result = check(R"(
--!strict
local Vec3 = {}
Vec3.__index = Vec3
function Vec3.new()
return setmetatable({x=0, y=0, z=0}, Vec3)
end
export type Vec3 = typeof(Vec3.new())
local thefun: any = function(self, o) return self end
local multiply: ((Vec3, Vec3) -> Vec3) & ((Vec3, number) -> Vec3) = thefun
Vec3.__mul = multiply
local a = Vec3.new()
local b = Vec3.new()
local c = b * a
local d = 2 * a
local e = 'cabbage' * a
)");
LUAU_REQUIRE_ERROR_COUNT(1, result);
CHECK_EQ("Vec3", toString(requireType("a")));
CHECK_EQ("Vec3", toString(requireType("b")));
CHECK_EQ("Vec3", toString(requireType("c")));
CHECK_EQ("Vec3", toString(requireType("d")));
CHECK_EQ("Vec3", toString(requireType("e")));
}
TEST_CASE_FIXTURE(Fixture, "compare_numbers")
{
CheckResult result = check(R"(
local a = 441
local b = 0
local c = a < b
)");
LUAU_REQUIRE_NO_ERRORS(result);
}
TEST_CASE_FIXTURE(Fixture, "compare_strings")
{
CheckResult result = check(R"(
local a = '441'
local b = '0'
local c = a < b
)");
LUAU_REQUIRE_NO_ERRORS(result);
}
TEST_CASE_FIXTURE(Fixture, "cannot_indirectly_compare_types_that_do_not_have_a_metatable")
{
CheckResult result = check(R"(
local a = {}
local b = {}
local c = a < b
)");
LUAU_REQUIRE_ERROR_COUNT(1, result);
GenericError* gen = get<GenericError>(result.errors[0]);
REQUIRE_EQ(gen->message, "Type a cannot be compared with < because it has no metatable");
}
TEST_CASE_FIXTURE(Fixture, "cannot_indirectly_compare_types_that_do_not_offer_overloaded_ordering_operators")
{
CheckResult result = check(R"(
local M = {}
function M.new()
return setmetatable({}, M)
end
type M = typeof(M.new())
local a = M.new()
local b = M.new()
local c = a < b
)");
LUAU_REQUIRE_ERROR_COUNT(1, result);
GenericError* gen = get<GenericError>(result.errors[0]);
REQUIRE(gen != nullptr);
REQUIRE_EQ(gen->message, "Table M does not offer metamethod __lt");
}
TEST_CASE_FIXTURE(Fixture, "cannot_compare_tables_that_do_not_have_the_same_metatable")
{
CheckResult result = check(R"(
--!strict
local M = {}
function M.new()
return setmetatable({}, M)
end
function M.__lt(left, right) return true end
local a = M.new()
local b = {}
local c = a < b -- line 10
local d = b < a -- line 11
)");
LUAU_REQUIRE_ERROR_COUNT(2, result);
REQUIRE_EQ((Location{{10, 18}, {10, 23}}), result.errors[0].location);
REQUIRE_EQ((Location{{11, 18}, {11, 23}}), result.errors[1].location);
}
TEST_CASE_FIXTURE(Fixture, "produce_the_correct_error_message_when_comparing_a_table_with_a_metatable_with_one_that_does_not")
{
CheckResult result = check(R"(
--!strict
local M = {}
function M.new()
return setmetatable({}, M)
end
function M.__lt(left, right) return true end
type M = typeof(M.new())
local a = M.new()
local b = {}
local c = a < b -- line 10
)");
LUAU_REQUIRE_ERROR_COUNT(1, result);
auto err = get<GenericError>(result.errors[0]);
REQUIRE(err != nullptr);
// Frail. :|
REQUIRE_EQ("Types M and b cannot be compared with < because they do not have the same metatable", err->message);
}
TEST_CASE_FIXTURE(Fixture, "in_nonstrict_mode_strip_nil_from_intersections_when_considering_relational_operators")
{
CheckResult result = check(R"(
--!nonstrict
function maybe_a_number(): number?
return 50
end
local a = maybe_a_number() < maybe_a_number()
)");
LUAU_REQUIRE_NO_ERRORS(result);
}
/*
* This test case exposed an oversight in the treatment of free tables.
* Free tables, like free TypeVars, need to record the scope depth where they were created so that
* we do not erroneously let-generalize them when they are used in a nested lambda.
*
* For more information about let-generalization, see <http://okmij.org/ftp/ML/generalization.html>
*
* The important idea here is that the return type of Counter.new is a table with some metatable.
* That metatable *must* be the same TypeVar as the type of Counter. If it is a copy (produced by
* the generalization process), then it loses the knowledge that its metatable will have an :incr()
* method.
*/
TEST_CASE_FIXTURE(Fixture, "dont_quantify_table_that_belongs_to_outer_scope")
{
CheckResult result = check(R"(
local Counter = {}
Counter.__index = Counter
function Counter.new()
local self = setmetatable({count=0}, Counter)
return self
end
function Counter:incr()
self.count = 1
return self.count
end
local self = Counter.new()
print(self:incr())
)");
LUAU_REQUIRE_NO_ERRORS(result);
TableTypeVar* counterType = getMutable<TableTypeVar>(requireType("Counter"));
REQUIRE(counterType);
const FunctionTypeVar* newType = get<FunctionTypeVar>(follow(counterType->props["new"].type));
REQUIRE(newType);
std::optional<TypeId> newRetType = *first(newType->retType);
REQUIRE(newRetType);
const MetatableTypeVar* newRet = get<MetatableTypeVar>(follow(*newRetType));
REQUIRE(newRet);
const TableTypeVar* newRetMeta = get<TableTypeVar>(newRet->metatable);
REQUIRE(newRetMeta);
CHECK(newRetMeta->props.count("incr"));
CHECK_EQ(follow(newRet->metatable), follow(requireType("Counter")));
}
// TODO: CLI-39624
TEST_CASE_FIXTURE(Fixture, "instantiate_tables_at_scope_level")
{
CheckResult result = check(R"(
--!strict
local Option = {}
Option.__index = Option
function Option.Is(obj)
return (type(obj) == "table" and getmetatable(obj) == Option)
end
return Option
)");
LUAU_REQUIRE_NO_ERRORS(result);
}
TEST_CASE_FIXTURE(Fixture, "typeguard_doesnt_leak_to_elseif")
{
const std::string code = R"(
function f(a)
if type(a) == "boolean" then
local a1 = a
elseif a.fn() then
local a2 = a
else
local a3 = a
end
end
)";
CheckResult result = check(code);
LUAU_REQUIRE_NO_ERRORS(result);
dumpErrors(result);
}
TEST_CASE_FIXTURE(Fixture, "should_be_able_to_infer_this_without_stack_overflowing")
{
CheckResult result = check(R"(
local function f(x, y)
return x or y
end
local function dont_crash(x, y)
local z: typeof(f(x, y)) = f(x, y)
end
)");
LUAU_REQUIRE_NO_ERRORS(result);
}
TEST_CASE_FIXTURE(Fixture, "x_or_y_forces_both_x_and_y_to_be_of_same_type_if_either_is_free")
{
CheckResult result = check(R"(
local function f(x, y) return x or y end
local x = f(1, 2)
local y = f(3, "foo")
)");
LUAU_REQUIRE_ERROR_COUNT(1, result);
CHECK_EQ(*requireType("x"), *typeChecker.numberType);
CHECK_EQ(result.errors[0], (TypeError{Location{{4, 23}, {4, 28}}, TypeMismatch{typeChecker.numberType, typeChecker.stringType}}));
}
TEST_CASE_FIXTURE(Fixture, "inferring_hundreds_of_self_calls_should_not_suffocate_memory")
{
CheckResult result = check(R"(
("foo")
:lower()
:lower()
:lower()
:lower()
:lower()
:lower()
:lower()
:lower()
:lower()
:lower()
:lower()
:lower()
:lower()
:lower()
:lower()
:lower()
:lower()
:lower()
)");
ModulePtr module = getMainModule();
CHECK_GE(50, module->internalTypes.typeVars.size());
}
TEST_CASE_FIXTURE(Fixture, "inferring_crazy_table_should_also_be_quick")
{
CheckResult result = check(R"(
--!strict
function f(U)
U(w:s(an):c()():c():U(s):c():c():U(s):c():U(s):cU()):c():U(s):c():U(s):c():c():U(s):c():U(s):cU()
end
)");
ModulePtr module = getMainModule();
CHECK_GE(100, module->internalTypes.typeVars.size());
}
TEST_CASE_FIXTURE(Fixture, "exponential_blowup_from_copying_types")
{
CheckResult result = check(R"(
--!strict
-- An example of exponential blowup in number of types
-- The problem is that if we define function f(a) return x end
-- then this has type <t>(t)->T where x:T
-- *but* it copies T each time f is applied
-- so { left = f("hi"), right = f(5) }
-- has type { left : T_L, right : T_R }
-- where T_L and T_R are copies of T.
-- x0 : T0 where T0 = {}
local x0 = {}
-- f0 : <t>(t)->T0
local function f0(a) return x0 end
-- x1 : T1 where T1 = { left : T0_L, right : T0_R }
local x1 = { left = f0("hi"), right = f0(5) }
-- f1 : <t>(t)->T1
local function f1(a) return x1 end
-- x2 : T2 where T2 = { left : T1_L, right : T1_R }
local x2 = { left = f1("hi"), right = f1(5) }
-- f2 : <t>(t)->T2
local function f2(a) return x2 end
-- etc etc
local x3 = { left = f2("hi"), right = f2(5) }
local function f3(a) return x3 end
local x4 = { left = f3("hi"), right = f3(5) }
return x4
)");
LUAU_REQUIRE_NO_ERRORS(result);
ModulePtr module = getMainModule();
// If we're not careful about copying, this ends up with O(2^N) types rather than O(N)
// (in this case 5 vs 31).
CHECK_GE(5, module->interfaceTypes.typeVars.size());
}
TEST_CASE_FIXTURE(Fixture, "mutual_recursion")
{
CheckResult result = check(R"(
--!strict
function newPlayerCharacter()
startGui() -- Unknown symbol 'startGui'
end
local characterAddedConnection: any
function startGui()
characterAddedConnection = game:GetService("Players").LocalPlayer.CharacterAdded:connect(newPlayerCharacter)
end
)");
LUAU_REQUIRE_NO_ERRORS(result);
dumpErrors(result);
}
TEST_CASE_FIXTURE(Fixture, "toposort_doesnt_break_mutual_recursion")
{
CheckResult result = check(R"(
--!strict
local x = nil
function f() g() end
-- make sure print(x) doesn't get toposorted here, breaking the mutual block
function g() x = f end
print(x)
)");
LUAU_REQUIRE_NO_ERRORS(result);
dumpErrors(result);
}
TEST_CASE_FIXTURE(Fixture, "object_constructor_can_refer_to_method_of_self")
{
// CLI-30902
CheckResult result = check(R"(
--!strict
type Foo = {
fooConn: () -> () | nil
}
local Foo = {}
Foo.__index = Foo
function Foo.new()
local self: Foo = {
fooConn = nil,
}
setmetatable(self, Foo)
self.fooConn = function()
self:method() -- Key 'method' not found in table self
end
return self
end
function Foo:method()
print("foo")
end
local foo = Foo.new()
-- TODO This is the best our current refinement support can offer :(
local bar = foo.fooConn
if bar then bar() end
-- foo.fooConn()
)");
LUAU_REQUIRE_NO_ERRORS(result);
}
TEST_CASE_FIXTURE(Fixture, "replace_every_free_type_when_unifying_a_complex_function_with_any")
{
CheckResult result = check(R"(
local a: any
local b
for _, i in pairs(a) do
b = i
end
)");
LUAU_REQUIRE_NO_ERRORS(result);
CHECK_EQ("any", toString(requireType("b")));
}
// In these tests, a successful parse is required, so we need the parser to return the AST and then we can test the recursion depth limit in type
// checker. We also want it to somewhat match up with production values, so we push up the parser recursion limit a little bit instead.
TEST_CASE_FIXTURE(Fixture, "check_type_infer_recursion_limit")
{
#if defined(LUAU_ENABLE_ASAN)
int limit = 250;
#elif defined(_DEBUG) || defined(_NOOPT)
int limit = 350;
#else
int limit = 600;
#endif
ScopedFastInt luauRecursionLimit{"LuauRecursionLimit", limit + 100};
ScopedFastInt luauTypeInferRecursionLimit{"LuauTypeInferRecursionLimit", limit - 100};
ScopedFastInt luauCheckRecursionLimit{"LuauCheckRecursionLimit", 0};
CHECK_NOTHROW(check("print('Hello!')"));
CHECK_THROWS_AS(check("function f() return " + rep("{a=", limit) + "'a'" + rep("}", limit) + " end"), std::runtime_error);
}
TEST_CASE_FIXTURE(Fixture, "check_block_recursion_limit")
{
#if defined(LUAU_ENABLE_ASAN)
int limit = 250;
#elif defined(_DEBUG) || defined(_NOOPT)
int limit = 350;
#else
int limit = 600;
#endif
ScopedFastInt luauRecursionLimit{"LuauRecursionLimit", limit + 100};
ScopedFastInt luauCheckRecursionLimit{"LuauCheckRecursionLimit", limit - 100};
CheckResult result = check(rep("do ", limit) + "local a = 1" + rep(" end", limit));
LUAU_REQUIRE_ERROR_COUNT(1, result);
CHECK(nullptr != get<CodeTooComplex>(result.errors[0]));
}
TEST_CASE_FIXTURE(Fixture, "check_expr_recursion_limit")
{
#if defined(LUAU_ENABLE_ASAN)
int limit = 250;
#elif defined(_DEBUG) || defined(_NOOPT)
int limit = 350;
#else
int limit = 600;
#endif
ScopedFastInt luauRecursionLimit{"LuauRecursionLimit", limit + 100};
ScopedFastInt luauCheckRecursionLimit{"LuauCheckRecursionLimit", limit - 100};
CheckResult result = check(R"(("foo"))" + rep(":lower()", limit));
LUAU_REQUIRE_ERROR_COUNT(1, result);
CHECK(nullptr != get<CodeTooComplex>(result.errors[0]));
}
TEST_CASE_FIXTURE(Fixture, "compound_assign_basic")
{
CheckResult result = check(R"(
local s = 10
s += 20
)");
CHECK_EQ(0, result.errors.size());
CHECK_EQ(toString(*requireType("s")), "number");
}
TEST_CASE_FIXTURE(Fixture, "compound_assign_mismatch_op")
{
CheckResult result = check(R"(
local s = 10
s += true
)");
LUAU_REQUIRE_ERROR_COUNT(1, result);
CHECK_EQ(result.errors[0], (TypeError{Location{{2, 13}, {2, 17}}, TypeMismatch{typeChecker.numberType, typeChecker.booleanType}}));
}
TEST_CASE_FIXTURE(Fixture, "compound_assign_mismatch_result")
{
CheckResult result = check(R"(
local s = 'hello'
s += 10
)");
LUAU_REQUIRE_ERROR_COUNT(2, result);
CHECK_EQ(result.errors[0], (TypeError{Location{{2, 8}, {2, 9}}, TypeMismatch{typeChecker.numberType, typeChecker.stringType}}));
CHECK_EQ(result.errors[1], (TypeError{Location{{2, 8}, {2, 15}}, TypeMismatch{typeChecker.stringType, typeChecker.numberType}}));
}
TEST_CASE_FIXTURE(Fixture, "compound_assign_metatable")
{
CheckResult result = check(R"(
--!strict
type V2B = { x: number, y: number }
local v2b: V2B = { x = 0, y = 0 }
local VMT = {}
type V2 = typeof(setmetatable(v2b, VMT))
function VMT.__add(a: V2, b: V2): V2
return setmetatable({ x = a.x + b.x, y = a.y + b.y }, VMT)
end
local v1: V2 = setmetatable({ x = 1, y = 2 }, VMT)
local v2: V2 = setmetatable({ x = 3, y = 4 }, VMT)
v1 += v2
)");
CHECK_EQ(0, result.errors.size());
}
TEST_CASE_FIXTURE(Fixture, "compound_assign_mismatch_metatable")
{
CheckResult result = check(R"(
--!strict
type V2B = { x: number, y: number }
local v2b: V2B = { x = 0, y = 0 }
local VMT = {}
type V2 = typeof(setmetatable(v2b, VMT))
function VMT.__mod(a: V2, b: V2): number
return a.x * b.x + a.y * b.y
end
local v1: V2 = setmetatable({ x = 1, y = 2 }, VMT)
local v2: V2 = setmetatable({ x = 3, y = 4 }, VMT)
v1 %= v2
)");
LUAU_REQUIRE_ERROR_COUNT(1, result);
TypeMismatch* tm = get<TypeMismatch>(result.errors[0]);
CHECK_EQ(*tm->wantedType, *requireType("v2"));
CHECK_EQ(*tm->givenType, *typeChecker.numberType);
}
TEST_CASE_FIXTURE(Fixture, "dont_ice_if_a_TypePack_is_an_error")
{
CheckResult result = check(R"(
--!strict
function f(s)
print(s)
return f
end
f("foo")("bar")
)");
}
TEST_CASE_FIXTURE(Fixture, "check_function_before_lambda_that_uses_it")
{
CheckResult result = check(R"(
--!nonstrict
function f()
return 114
end
return function()
return f():andThen()
end
)");
LUAU_REQUIRE_NO_ERRORS(result);
}
TEST_CASE_FIXTURE(Fixture, "it_is_ok_to_oversaturate_a_higher_order_function_argument")
{
CheckResult result = check(R"(
function onerror() end
function foo() end
xpcall(foo, onerror)
)");
LUAU_REQUIRE_NO_ERRORS(result);
}
TEST_CASE_FIXTURE(Fixture, "another_indirect_function_case_where_it_is_ok_to_provide_too_many_arguments")
{
CheckResult result = check(R"(
local mycb: (number, number) -> ()
function f() end
mycb = f
)");
LUAU_REQUIRE_NO_ERRORS(result);
}
TEST_CASE_FIXTURE(Fixture, "call_to_any_yields_any")
{
CheckResult result = check(R"(
local a: any
local b = a()
)");
REQUIRE_EQ("any", toString(requireType("b")));
}
TEST_CASE_FIXTURE(Fixture, "globals")
{
CheckResult result = check(R"(
--!nonstrict
foo = true
foo = "now i'm a string!"
)");
LUAU_REQUIRE_NO_ERRORS(result);
CHECK_EQ("any", toString(requireType("foo")));
}
TEST_CASE_FIXTURE(Fixture, "globals2")
{
CheckResult result = check(R"(
--!nonstrict
foo = function() return 1 end
foo = "now i'm a string!"
)");
LUAU_REQUIRE_ERROR_COUNT(1, result);
TypeMismatch* tm = get<TypeMismatch>(result.errors[0]);
REQUIRE(tm);
CHECK_EQ("() -> (...any)", toString(tm->wantedType));
CHECK_EQ("string", toString(tm->givenType));
CHECK_EQ("() -> (...any)", toString(requireType("foo")));
}
TEST_CASE_FIXTURE(Fixture, "globals_are_banned_in_strict_mode")
{
CheckResult result = check(R"(
--!strict
foo = true
)");
LUAU_REQUIRE_ERROR_COUNT(1, result);
UnknownSymbol* us = get<UnknownSymbol>(result.errors[0]);
REQUIRE(us);
CHECK_EQ("foo", us->name);
}
TEST_CASE_FIXTURE(Fixture, "globals_everywhere")
{
CheckResult result = check(R"(
--!nonstrict
foo = 1
if true then
bar = 2
end
)");
LUAU_REQUIRE_NO_ERRORS(result);
CHECK_EQ("any", toString(requireType("foo")));
CHECK_EQ("any", toString(requireType("bar")));
}
TEST_CASE_FIXTURE(Fixture, "CheckMethodsOfAny")
{
CheckResult result = check(R"(
local x: any = {}
function x:y(z: number)
local s: string = z
end
)");
LUAU_REQUIRE_ERROR_COUNT(1, result);
}
TEST_CASE_FIXTURE(Fixture, "CheckMethodsOfSealed")
{
CheckResult result = check(R"(
local x: {prop: number} = {prop=9999}
function x:y(z: number)
local s: string = z
end
)");
LUAU_REQUIRE_ERROR_COUNT(2, result);
}
TEST_CASE_FIXTURE(Fixture, "CheckMethodsOfNumber")
{
ScopedFastFlag sff{"LuauErrorRecoveryType", true};
CheckResult result = check(R"(
local x: number = 9999
function x:y(z: number)
local s: string = z
end
)");
LUAU_REQUIRE_ERROR_COUNT(2, result);
}
TEST_CASE_FIXTURE(Fixture, "CheckMethodsOfError")
{
CheckResult result = check(R"(
local x = (true).foo
function x:y(z: number)
local s: string = z
end
)");
LUAU_REQUIRE_ERRORS(result);
}
TEST_CASE_FIXTURE(Fixture, "CallOrOfFunctions")
{
CheckResult result = check(R"(
function f() return 1; end
function g() return 2; end
(f or g)()
)");
LUAU_REQUIRE_NO_ERRORS(result);
}
TEST_CASE_FIXTURE(Fixture, "CallAndOrOfFunctions")
{
CheckResult result = check(R"(
function f() return 1; end
function g() return 2; end
local x = false
(x and f or g)()
)");
LUAU_REQUIRE_NO_ERRORS(result);
}
TEST_CASE_FIXTURE(Fixture, "MixedPropertiesAndIndexers")
{
CheckResult result = check(R"(
local x = {}
x.a = "a"
x[0] = true
x.b = 37
)");
LUAU_REQUIRE_NO_ERRORS(result);
}
TEST_CASE_FIXTURE(Fixture, "correctly_scope_locals_do")
{
CheckResult result = check(R"(
do
local a = 1
end
print(a) -- oops!
)");
LUAU_REQUIRE_ERROR_COUNT(1, result);
UnknownSymbol* us = get<UnknownSymbol>(result.errors[0]);
REQUIRE(us);
CHECK_EQ(us->name, "a");
}
TEST_CASE_FIXTURE(Fixture, "correctly_scope_locals_while")
{
CheckResult result = check(R"(
while true do
local a = 1
end
print(a) -- oops!
)");
LUAU_REQUIRE_ERROR_COUNT(1, result);
UnknownSymbol* us = get<UnknownSymbol>(result.errors[0]);
REQUIRE(us);
CHECK_EQ(us->name, "a");
}
TEST_CASE_FIXTURE(Fixture, "ipairs_produces_integral_indices")
{
CheckResult result = check(R"(
local key
for i, e in ipairs({}) do key = i end
)");
LUAU_REQUIRE_NO_ERRORS(result);
REQUIRE_EQ("number", toString(requireType("key")));
}
TEST_CASE_FIXTURE(Fixture, "checking_should_not_ice")
{
CHECK_NOTHROW(check(R"(
--!nonstrict
f,g = ...
f(g(...))[...] = nil
f,xpcall = ...
local value = g(...)(g(...))
)"));
CHECK_EQ("any", toString(requireType("value")));
}
TEST_CASE_FIXTURE(Fixture, "report_exiting_without_return_nonstrict")
{
CheckResult result = check(R"(
--!nonstrict
local function f1(v): number?
if v then
return 1
end
end
local function f2(v)
if v then
return 1
end
end
local function f3(v): ()
if v then
return
end
end
local function f4(v)
if v then
return
end
end
)");
LUAU_REQUIRE_ERROR_COUNT(1, result);
FunctionExitsWithoutReturning* err = get<FunctionExitsWithoutReturning>(result.errors[0]);
CHECK(err);
}
TEST_CASE_FIXTURE(Fixture, "report_exiting_without_return_strict")
{
CheckResult result = check(R"(
--!strict
local function f1(v): number?
if v then
return 1
end
end
local function f2(v)
if v then
return 1
end
end
local function f3(v): ()
if v then
return
end
end
local function f4(v)
if v then
return
end
end
)");
LUAU_REQUIRE_ERROR_COUNT(2, result);
FunctionExitsWithoutReturning* annotatedErr = get<FunctionExitsWithoutReturning>(result.errors[0]);
CHECK(annotatedErr);
FunctionExitsWithoutReturning* inferredErr = get<FunctionExitsWithoutReturning>(result.errors[1]);
CHECK(inferredErr);
}
// TEST_CASE_FIXTURE(Fixture, "infer_method_signature_of_argument")
// {
// CheckResult result = check(R"(
// function f(a)
// if a.cond then
// return a.method()
// end
// end
// )");
// LUAU_REQUIRE_NO_ERRORS(result);
// CHECK_EQ("A", toString(requireType("f")));
// }
TEST_CASE_FIXTURE(Fixture, "warn_if_you_try_to_require_a_non_modulescript")
{
fileResolver.source["Modules/A"] = "";
fileResolver.sourceTypes["Modules/A"] = SourceCode::Local;
fileResolver.source["Modules/B"] = R"(
local M = require(script.Parent.A)
)";
CheckResult result = frontend.check("Modules/B");
LUAU_REQUIRE_ERROR_COUNT(1, result);
CHECK(get<IllegalRequire>(result.errors[0]));
}
TEST_CASE_FIXTURE(Fixture, "calling_function_with_incorrect_argument_type_yields_errors_spanning_argument")
{
CheckResult result = check(R"(
function foo(a: number, b: string) end
foo("Test", 123)
)");
LUAU_REQUIRE_ERROR_COUNT(2, result);
CHECK_EQ(result.errors[0], (TypeError{Location{Position{3, 12}, Position{3, 18}}, TypeMismatch{
typeChecker.numberType,
typeChecker.stringType,
}}));
CHECK_EQ(result.errors[1], (TypeError{Location{Position{3, 20}, Position{3, 23}}, TypeMismatch{
typeChecker.stringType,
typeChecker.numberType,
}}));
}
TEST_CASE_FIXTURE(Fixture, "calling_function_with_anytypepack_doesnt_leak_free_types")
{
CheckResult result = check(R"(
--!nonstrict
function Test(a)
return 1, ""
end
local tab = {}
table.insert(tab, Test(1));
)");
LUAU_REQUIRE_NO_ERRORS(result);
ToStringOptions opts;
opts.exhaustive = true;
opts.maxTableLength = 0;
CHECK_EQ("{any}", toString(requireType("tab"), opts));
}
TEST_CASE_FIXTURE(Fixture, "too_many_return_values")
{
CheckResult result = check(R"(
--!strict
function f()
return 55
end
local a, b = f()
)");
LUAU_REQUIRE_ERROR_COUNT(1, result);
CountMismatch* acm = get<CountMismatch>(result.errors[0]);
REQUIRE(acm);
CHECK_EQ(acm->context, CountMismatch::Result);
CHECK_EQ(acm->expected, 1);
CHECK_EQ(acm->actual, 2);
}
TEST_CASE_FIXTURE(Fixture, "ignored_return_values")
{
CheckResult result = check(R"(
--!strict
function f()
return 55, ""
end
local a = f()
)");
LUAU_REQUIRE_ERROR_COUNT(0, result);
}
TEST_CASE_FIXTURE(Fixture, "function_does_not_return_enough_values")
{
CheckResult result = check(R"(
--!strict
function f(): (number, string)
return 55
end
)");
LUAU_REQUIRE_ERROR_COUNT(1, result);
CountMismatch* acm = get<CountMismatch>(result.errors[0]);
REQUIRE(acm);
CHECK_EQ(acm->context, CountMismatch::Return);
CHECK_EQ(acm->expected, 2);
CHECK_EQ(acm->actual, 1);
}
TEST_CASE_FIXTURE(Fixture, "typecheck_unary_minus")
{
CheckResult result = check(R"(
--!strict
local foo = {
value = 10
}
local mt = {}
setmetatable(foo, mt)
mt.__unm = function(val: typeof(foo)): string
return val.value .. "test"
end
local a = -foo
local b = 1+-1
local bar = {
value = 10
}
local c = -bar -- disallowed
)");
LUAU_REQUIRE_ERROR_COUNT(1, result);
CHECK_EQ("string", toString(requireType("a")));
CHECK_EQ("number", toString(requireType("b")));
GenericError* gen = get<GenericError>(result.errors[0]);
REQUIRE_EQ(gen->message, "Unary operator '-' not supported by type 'bar'");
}
TEST_CASE_FIXTURE(Fixture, "unary_not_is_boolean")
{
CheckResult result = check(R"(
local b = not "string"
local c = not (math.random() > 0.5 and "string" or 7)
)");
LUAU_REQUIRE_NO_ERRORS(result);
REQUIRE_EQ("boolean", toString(requireType("b")));
REQUIRE_EQ("boolean", toString(requireType("c")));
}
TEST_CASE_FIXTURE(Fixture, "disallow_string_and_types_without_metatables_from_arithmetic_binary_ops")
{
CheckResult result = check(R"(
--!strict
local a = "1.24" + 123 -- not allowed
local foo = {
value = 10
}
local b = foo + 1 -- not allowed
local bar = {
value = 1
}
local mt = {}
setmetatable(bar, mt)
mt.__add = function(a: typeof(bar), b: number): number
return a.value + b
end
local c = bar + 1 -- allowed
local d = bar + foo -- not allowed
)");
LUAU_REQUIRE_ERROR_COUNT(3, result);
TypeMismatch* tm = get<TypeMismatch>(result.errors[0]);
REQUIRE_EQ(*tm->wantedType, *typeChecker.numberType);
REQUIRE_EQ(*tm->givenType, *typeChecker.stringType);
TypeMismatch* tm2 = get<TypeMismatch>(result.errors[2]);
CHECK_EQ(*tm2->wantedType, *typeChecker.numberType);
CHECK_EQ(*tm2->givenType, *requireType("foo"));
GenericError* gen2 = get<GenericError>(result.errors[1]);
REQUIRE_EQ(gen2->message, "Binary operator '+' not supported by types 'foo' and 'number'");
}
// CLI-29033
TEST_CASE_FIXTURE(Fixture, "unknown_type_in_comparison")
{
CheckResult result = check(R"(
function merge(lower, greater)
if lower.y == greater.y then
end
end
)");
LUAU_REQUIRE_NO_ERRORS(result);
}
TEST_CASE_FIXTURE(Fixture, "relation_op_on_any_lhs_where_rhs_maybe_has_metatable")
{
CheckResult result = check(R"(
local x
print((x == true and (x .. "y")) .. 1)
)");
LUAU_REQUIRE_ERROR_COUNT(1, result);
REQUIRE(get<CannotInferBinaryOperation>(result.errors[0]));
}
TEST_CASE_FIXTURE(Fixture, "concat_op_on_string_lhs_and_free_rhs")
{
CheckResult result = check(R"(
local x
print("foo" .. x)
)");
LUAU_REQUIRE_NO_ERRORS(result);
CHECK_EQ("string", toString(requireType("x")));
}
TEST_CASE_FIXTURE(Fixture, "strict_binary_op_where_lhs_unknown")
{
std::vector<std::string> ops = {"+", "-", "*", "/", "%", "^", ".."};
std::string src = R"(
function foo(a, b)
)";
for (const auto& op : ops)
src += "local _ = a " + op + "b\n";
src += "end";
CheckResult result = check(src);
LUAU_REQUIRE_ERROR_COUNT(ops.size(), result);
CHECK_EQ("Unknown type used in + operation; consider adding a type annotation to 'a'", toString(result.errors[0]));
}
TEST_CASE_FIXTURE(Fixture, "function_cast_error_uses_correct_language")
{
CheckResult result = check(R"(
function foo(a, b): number
return 0
end
local a: (string)->number = foo
local b: (number, number)->(number, number) = foo
local c: (string, number)->number = foo -- no error
)");
LUAU_REQUIRE_ERROR_COUNT(2, result);
auto tm1 = get<TypeMismatch>(result.errors[0]);
REQUIRE(tm1);
CHECK_EQ("(string) -> number", toString(tm1->wantedType));
CHECK_EQ("(string, *unknown*) -> number", toString(tm1->givenType));
auto tm2 = get<TypeMismatch>(result.errors[1]);
REQUIRE(tm2);
CHECK_EQ("(number, number) -> (number, number)", toString(tm2->wantedType));
CHECK_EQ("(string, *unknown*) -> number", toString(tm2->givenType));
}
TEST_CASE_FIXTURE(Fixture, "setmetatable_cant_be_used_to_mutate_global_types")
{
{
Fixture fix;
// inherit env from parent fixture checker
fix.typeChecker.globalScope = typeChecker.globalScope;
fix.check(R"(
--!nonstrict
type MT = typeof(setmetatable)
function wtf(arg: {MT}): typeof(table)
arg = wtf(arg)
end
)");
}
// validate sharedEnv post-typecheck; valuable for debugging some typeck crashes but slows fuzzing down
// note: it's important for typeck to be destroyed at this point!
{
for (auto& p : typeChecker.globalScope->bindings)
{
toString(p.second.typeId); // toString walks the entire type, making sure ASAN catches access to destroyed type arenas
}
}
}
TEST_CASE_FIXTURE(Fixture, "evil_table_unification")
{
// this code re-infers the type of _ while processing fields of _, which can cause use-after-free
check(R"(
--!nonstrict
_ = ...
_:table(_,string)[_:gsub(_,...,n0)],_,_:gsub(_,string)[""],_:split(_,...,table)._,n0 = nil
do end
)");
}
TEST_CASE_FIXTURE(Fixture, "overload_is_not_a_function")
{
check(R"(
--!nonstrict
function _(...):((typeof(not _))&(typeof(not _)))&((typeof(not _))&(typeof(not _)))
_(...)(setfenv,_,not _,"")[_] = nil
end
do end
_(...)(...,setfenv,_):_G()
)");
}
TEST_CASE_FIXTURE(Fixture, "cyclic_type_packs")
{
// this has a risk of creating cyclic type packs, causing infinite loops / OOMs
check(R"(
--!nonstrict
_ += _(_,...)
repeat
_ += _(...)
until ... + _
)");
check(R"(
--!nonstrict
_ += _(_(...,...),_(...))
repeat
until _
)");
}
TEST_CASE_FIXTURE(Fixture, "cyclic_follow")
{
check(R"(
--!nonstrict
l0,table,_,_,_ = ...
_,_,_,_.time(...)._.n0,l0,_ = function(l0)
end,_.__index,(_),_.time(_.n0 or _,...)
for l0=...,_,"" do
end
_ += not _
do end
)");
check(R"(
--!nonstrict
n13,_,table,_,l0,_,_ = ...
_,n0[(_)],_,_._(...)._.n39,l0,_._ = function(l84,...)
end,_.__index,"",_,l0._(nil)
for l0=...,table.n5,_ do
end
_:_(...).n1 /= _
do
_(_ + _)
do end
end
)");
}
TEST_CASE_FIXTURE(Fixture, "and_binexps_dont_unify")
{
CheckResult result = check(R"(
--!strict
local t = {}
while true and t[1] do
print(t[1].test)
end
)");
LUAU_REQUIRE_NO_ERRORS(result);
}
struct FindFreeTypeVars
{
bool foundOne = false;
template<typename ID>
void cycle(ID)
{
}
template<typename ID, typename T>
bool operator()(ID, T)
{
return !foundOne;
}
template<typename ID>
bool operator()(ID, Unifiable::Free)
{
foundOne = true;
return false;
}
};
TEST_CASE_FIXTURE(Fixture, "dont_crash_when_setmetatable_does_not_produce_a_metatabletypevar")
{
CheckResult result = check("local x = setmetatable({})");
LUAU_REQUIRE_ERROR_COUNT(1, result);
}
TEST_CASE_FIXTURE(Fixture, "for_in_loop_where_iteratee_is_free")
{
// This code doesn't pass typechecking. We just care that it doesn't crash.
(void)check(R"(
--!nonstrict
function _:_(...)
end
repeat
if _ then
else
_ = ...
end
until _
for _ in _() do
end
)");
}
TEST_CASE_FIXTURE(Fixture, "tc_after_error_recovery")
{
CheckResult result = check(R"(
local x =
local a = 7
)");
LUAU_REQUIRE_ERRORS(result);
TypeId aType = requireType("a");
CHECK_EQ(getPrimitiveType(aType), PrimitiveTypeVar::Number);
}
// Check that type checker knows about error expressions
TEST_CASE_FIXTURE(Fixture, "tc_after_error_recovery_no_assert")
{
CheckResult result = check("function +() local _ = true end");
LUAU_REQUIRE_ERRORS(result);
}
TEST_CASE_FIXTURE(Fixture, "tc_after_error_recovery_no_replacement_name_in_error")
{
{
CheckResult result = check(R"(
--!strict
local t = { x = 10, y = 20 }
return t.
)");
LUAU_REQUIRE_ERROR_COUNT(1, result);
}
{
CheckResult result = check(R"(
--!strict
export type = number
export type = string
)");
LUAU_REQUIRE_ERROR_COUNT(2, result);
}
{
CheckResult result = check(R"(
--!strict
function string.() end
)");
LUAU_REQUIRE_ERROR_COUNT(1, result);
}
{
CheckResult result = check(R"(
--!strict
local function () end
local function () end
)");
LUAU_REQUIRE_ERROR_COUNT(2, result);
}
{
CheckResult result = check(R"(
--!strict
local dm = {}
function dm.() end
function dm.() end
)");
LUAU_REQUIRE_ERROR_COUNT(2, result);
}
}
TEST_CASE_FIXTURE(Fixture, "error_on_invalid_operand_types_to_relational_operators")
{
CheckResult result = check(R"(
local a: boolean = true
local b: boolean = false
local foo = a < b
)");
LUAU_REQUIRE_ERROR_COUNT(1, result);
GenericError* ge = get<GenericError>(result.errors[0]);
REQUIRE(ge);
CHECK_EQ("Type 'boolean' cannot be compared with relational operator <", ge->message);
}
TEST_CASE_FIXTURE(Fixture, "error_on_invalid_operand_types_to_relational_operators2")
{
CheckResult result = check(R"(
local a: number | string = ""
local b: number | string = 1
local foo = a < b
)");
LUAU_REQUIRE_ERROR_COUNT(1, result);
GenericError* ge = get<GenericError>(result.errors[0]);
REQUIRE(ge);
CHECK_EQ("Type 'number | string' cannot be compared with relational operator <", ge->message);
}
TEST_CASE_FIXTURE(Fixture, "index_expr_should_be_checked")
{
CheckResult result = check(R"(
local foo: any
print(foo[(true).x])
)");
LUAU_REQUIRE_ERROR_COUNT(1, result);
UnknownProperty* up = get<UnknownProperty>(result.errors[0]); // Should probably be NotATable
REQUIRE(up);
CHECK_EQ("boolean", toString(up->table));
CHECK_EQ("x", up->key);
}
TEST_CASE_FIXTURE(Fixture, "unreachable_code_after_infinite_loop")
{
{
CheckResult result = check(R"(
function unreachablecodepath(a): number
while true do
if a then return 10 end
end
-- unreachable
end
unreachablecodepath(4)
)");
LUAU_REQUIRE_ERROR_COUNT(0, result);
}
{
CheckResult result = check(R"(
function reachablecodepath(a): number
while true do
if a then break end
return 10
end
print("x") -- correct error
end
reachablecodepath(4)
)");
LUAU_REQUIRE_ERRORS(result);
CHECK(get<FunctionExitsWithoutReturning>(result.errors[0]));
}
{
CheckResult result = check(R"(
function unreachablecodepath(a): number
repeat
if a then return 10 end
until false
-- unreachable
end
unreachablecodepath(4)
)");
LUAU_REQUIRE_ERROR_COUNT(0, result);
}
{
CheckResult result = check(R"(
function reachablecodepath(a, b): number
repeat
if a then break end
if b then return 10 end
until false
print("x") -- correct error
end
reachablecodepath(4)
)");
LUAU_REQUIRE_ERRORS(result);
CHECK(get<FunctionExitsWithoutReturning>(result.errors[0]));
}
{
CheckResult result = check(R"(
function unreachablecodepath(a: number?): number
repeat
return 10
until a ~= nil
-- unreachable
end
unreachablecodepath(4)
)");
LUAU_REQUIRE_ERROR_COUNT(0, result);
}
}
TEST_CASE_FIXTURE(Fixture, "cli_38355_recursive_union")
{
CheckResult result = check(R"(
--!strict
local _
_ += _ and _ or _ and _ or _ and _
)");
LUAU_REQUIRE_ERROR_COUNT(1, result);
CHECK_EQ("Type contains a self-recursive construct that cannot be resolved", toString(result.errors[0]));
}
TEST_CASE_FIXTURE(Fixture, "stringify_nested_unions_with_optionals")
{
CheckResult result = check(R"(
--!strict
local a: number | (string | boolean) | nil
local b: number = a
)");
LUAU_REQUIRE_ERROR_COUNT(1, result);
TypeMismatch* tm = get<TypeMismatch>(result.errors[0]);
REQUIRE(tm);
CHECK_EQ(typeChecker.numberType, tm->wantedType);
CHECK_EQ("(boolean | number | string)?", toString(tm->givenType));
}
TEST_CASE_FIXTURE(Fixture, "UnknownGlobalCompoundAssign")
{
// In non-strict mode, global definition is still allowed
{
CheckResult result = check(R"(
--!nonstrict
a = a + 1
print(a)
)");
LUAU_REQUIRE_ERROR_COUNT(1, result);
CHECK_EQ(toString(result.errors[0]), "Unknown global 'a'");
}
// In strict mode we no longer generate two errors from lhs
{
CheckResult result = check(R"(
--!strict
a += 1
print(a)
)");
LUAU_REQUIRE_ERRORS(result);
CHECK_EQ(toString(result.errors[0]), "Unknown global 'a'");
}
// In non-strict mode, compound assignment is not a definition, it's a modification
{
CheckResult result = check(R"(
--!nonstrict
a += 1
print(a)
)");
LUAU_REQUIRE_ERROR_COUNT(2, result);
CHECK_EQ(toString(result.errors[0]), "Unknown global 'a'");
}
}
TEST_CASE_FIXTURE(Fixture, "loop_typecheck_crash_on_empty_optional")
{
CheckResult result = check(R"(
local t = {}
for _ in t do
for _ in assert(missing()) do
end
end
)");
LUAU_REQUIRE_ERROR_COUNT(2, result);
}
TEST_CASE_FIXTURE(Fixture, "cli_39932_use_unifier_in_ensure_methods")
{
CheckResult result = check(R"(
local x: {number|number} = {1, 2, 3}
local y = x[1] - x[2]
)");
LUAU_REQUIRE_NO_ERRORS(result);
}
TEST_CASE_FIXTURE(Fixture, "metatable_of_any_can_be_a_table")
{
CheckResult result = check(R"(
--!strict
local T: any
T = {}
T.__index = T
function T.new(...)
local self = {}
setmetatable(self, T)
self:construct(...)
return self
end
function T:construct(index)
end
)");
LUAU_REQUIRE_NO_ERRORS(result);
}
TEST_CASE_FIXTURE(Fixture, "dont_report_type_errors_within_an_AstStatError")
{
CheckResult result = check(R"(
foo
)");
LUAU_REQUIRE_ERROR_COUNT(1, result);
}
TEST_CASE_FIXTURE(Fixture, "dont_report_type_errors_within_an_AstExprError")
{
CheckResult result = check(R"(
local a = foo:
)");
LUAU_REQUIRE_ERROR_COUNT(2, result);
}
TEST_CASE_FIXTURE(Fixture, "dont_ice_on_astexprerror")
{
CheckResult result = check(R"(
local foo = -;
)");
LUAU_REQUIRE_ERROR_COUNT(1, result);
}
TEST_CASE_FIXTURE(Fixture, "strip_nil_from_lhs_or_operator")
{
CheckResult result = check(R"(
--!strict
local a: number? = nil
local b: number = a or 1
)");
LUAU_REQUIRE_NO_ERRORS(result);
}
TEST_CASE_FIXTURE(Fixture, "strip_nil_from_lhs_or_operator2")
{
CheckResult result = check(R"(
--!nonstrict
local a: number? = nil
local b: number = a or 1
)");
LUAU_REQUIRE_NO_ERRORS(result);
}
TEST_CASE_FIXTURE(Fixture, "dont_strip_nil_from_rhs_or_operator")
{
CheckResult result = check(R"(
--!strict
local a: number? = nil
local b: number = 1 or a
)");
LUAU_REQUIRE_ERROR_COUNT(1, result);
TypeMismatch* tm = get<TypeMismatch>(result.errors[0]);
REQUIRE(tm);
CHECK_EQ(typeChecker.numberType, tm->wantedType);
CHECK_EQ("number?", toString(tm->givenType));
}
TEST_CASE_FIXTURE(Fixture, "no_lossy_function_type")
{
CheckResult result = check(R"(
--!strict
local tbl = {}
function tbl:abc(a: number, b: number)
return a
end
tbl:abc(1, 2) -- Line 6
-- | Column 14
)");
LUAU_REQUIRE_NO_ERRORS(result);
TypeId type = requireTypeAtPosition(Position(6, 14));
CHECK_EQ("(tbl, number, number) -> number", toString(type));
auto ftv = get<FunctionTypeVar>(type);
REQUIRE(ftv);
CHECK(ftv->hasSelf);
}
TEST_CASE_FIXTURE(Fixture, "luau_resolves_symbols_the_same_way_lua_does")
{
CheckResult result = check(R"(
--!strict
function Funky()
local a: number = foo
end
local foo: string = 'hello'
)");
LUAU_REQUIRE_ERROR_COUNT(1, result);
auto e = result.errors.front();
REQUIRE_MESSAGE(get<UnknownSymbol>(e) != nullptr, "Expected UnknownSymbol, but got " << e);
}
TEST_CASE_FIXTURE(Fixture, "operator_eq_verifies_types_do_intersect")
{
CheckResult result = check(R"(
type Array<T> = { [number]: T }
type Fiber = { id: number }
type null = {}
local fiberStack: Array<Fiber | null> = {}
local index = 0
local function f(fiber: Fiber)
local a = fiber ~= fiberStack[index]
local b = fiberStack[index] ~= fiber
end
return f
)");
LUAU_REQUIRE_NO_ERRORS(result);
}
TEST_CASE_FIXTURE(Fixture, "general_require_call_expression")
{
fileResolver.source["game/A"] = R"(
--!strict
return { def = 4 }
)";
fileResolver.source["game/B"] = R"(
--!strict
local tbl = { abc = require(game.A) }
local a : string = ""
a = tbl.abc.def
)";
CheckResult result = frontend.check("game/B");
LUAU_REQUIRE_ERROR_COUNT(1, result);
CHECK_EQ("Type 'number' could not be converted into 'string'", toString(result.errors[0]));
}
TEST_CASE_FIXTURE(Fixture, "general_require_type_mismatch")
{
fileResolver.source["game/A"] = R"(
return { def = 4 }
)";
fileResolver.source["game/B"] = R"(
local tbl: string = require(game.A)
)";
CheckResult result = frontend.check("game/B");
LUAU_REQUIRE_ERROR_COUNT(1, result);
CHECK_EQ("Type '{| def: number |}' could not be converted into 'string'", toString(result.errors[0]));
}
TEST_CASE_FIXTURE(Fixture, "nonstrict_self_mismatch_tail")
{
CheckResult result = check(R"(
--!nonstrict
local f = {}
function f:foo(a: number, b: number) end
function bar(...)
f.foo(f, 1, ...)
end
bar(2)
)");
LUAU_REQUIRE_NO_ERRORS(result);
}
TEST_CASE_FIXTURE(Fixture, "typeof_unresolved_function")
{
CheckResult result = check(R"(
local function f(a: typeof(f)) end
)");
LUAU_REQUIRE_ERROR_COUNT(1, result);
CHECK_EQ("Unknown global 'f'", toString(result.errors[0]));
}
TEST_CASE_FIXTURE(Fixture, "instantiate_table_cloning")
{
CheckResult result = check(R"(
--!nonstrict
local l0:any,l61:t0<t32> = _,math
while _ do
_()
end
function _():t0<t0>
end
type t0<t32> = any
)");
std::optional<TypeId> ty = requireType("math");
REQUIRE(ty);
const TableTypeVar* ttv = get<TableTypeVar>(*ty);
REQUIRE(ttv);
CHECK(ttv->instantiatedTypeParams.empty());
}
TEST_CASE_FIXTURE(Fixture, "bound_free_table_export_is_ok")
{
CheckResult result = check(R"(
local n = {}
function n:Clone() end
local m = {}
function m.a(x)
x:Clone()
end
function m.b()
m.a(n)
end
return m
)");
LUAU_REQUIRE_NO_ERRORS(result);
}
TEST_CASE_FIXTURE(Fixture, "no_persistent_typelevel_change")
{
TypeId mathTy = requireType(typeChecker.globalScope, "math");
REQUIRE(mathTy);
TableTypeVar* ttv = getMutable<TableTypeVar>(mathTy);
REQUIRE(ttv);
const FunctionTypeVar* ftv = get<FunctionTypeVar>(ttv->props["frexp"].type);
REQUIRE(ftv);
auto original = ftv->level;
CheckResult result = check("local a = math.frexp");
LUAU_REQUIRE_NO_ERRORS(result);
CHECK(ftv->level.level == original.level);
CHECK(ftv->level.subLevel == original.subLevel);
}
TEST_CASE_FIXTURE(Fixture, "table_indexing_error_location")
{
CheckResult result = check(R"(
local foo = {42}
local bar: number?
local baz = foo[bar]
)");
LUAU_REQUIRE_ERROR_COUNT(1, result);
CHECK_EQ(result.errors[0].location, Location{Position{3, 16}, Position{3, 19}});
}
TEST_CASE_FIXTURE(Fixture, "table_simple_call")
{
CheckResult result = check(R"(
local a = setmetatable({ x = 2 }, {
__call = function(self)
return (self.x :: number) * 2 -- should work without annotation in the future
end
})
local b = a()
local c = a(2) -- too many arguments
)");
LUAU_REQUIRE_ERROR_COUNT(1, result);
CHECK_EQ("Argument count mismatch. Function expects 1 argument, but 2 are specified", toString(result.errors[0]));
}
TEST_CASE_FIXTURE(Fixture, "custom_require_global")
{
CheckResult result = check(R"(
--!nonstrict
require = function(a) end
local crash = require(game.A)
)");
LUAU_REQUIRE_NO_ERRORS(result);
}
TEST_CASE_FIXTURE(Fixture, "operator_eq_operands_are_not_subtypes_of_each_other_but_has_overlap")
{
ScopedFastFlag sff1{"LuauEqConstraint", true};
CheckResult result = check(R"(
local function f(a: string | number, b: boolean | number)
return a == b
end
)");
// This doesn't produce any errors but for the wrong reasons.
// This unit test serves as a reminder to not try and unify the operands on `==`/`~=`.
LUAU_REQUIRE_NO_ERRORS(result);
}
TEST_CASE_FIXTURE(Fixture, "access_index_metamethod_that_returns_variadic")
{
CheckResult result = check(R"(
type Foo = {x: string}
local t = {}
setmetatable(t, {
__index = function(x: string): ...Foo
return {x = x}
end
})
local foo = t.bar
)");
LUAU_REQUIRE_NO_ERRORS(result);
ToStringOptions o;
o.exhaustive = true;
CHECK_EQ("{| x: string |}", toString(requireType("foo"), o));
}
TEST_CASE_FIXTURE(Fixture, "detect_cyclic_typepacks")
{
CheckResult result = check(R"(
type ( ... ) ( ) ;
( ... ) ( - - ... ) ( - ... )
type = ( ... ) ;
( ... ) ( ) ( ... ) ;
( ... ) ""
)");
CHECK_LE(0, result.errors.size());
}
TEST_CASE_FIXTURE(Fixture, "detect_cyclic_typepacks2")
{
CheckResult result = check(R"(
function _(l0:((typeof((pcall)))|((((t0)->())|(typeof(-67108864)))|(any)))|(any),...):(((typeof(0))|(any))|(any),typeof(-67108864),any)
xpcall(_,_,_)
_(_,_,_)
end
)");
CHECK_LE(0, result.errors.size());
}
TEST_CASE_FIXTURE(Fixture, "no_stack_overflow_from_quantifying")
{
CheckResult result = check(R"(
function _(l0:t0): (any, ()->())
end
type t0 = t0 | {}
)");
CHECK_LE(0, result.errors.size());
std::optional<TypeFun> t0 = getMainModule()->getModuleScope()->lookupType("t0");
REQUIRE(t0);
CHECK_EQ("*unknown*", toString(t0->type));
auto it = std::find_if(result.errors.begin(), result.errors.end(), [](TypeError& err) {
return get<OccursCheckFailed>(err);
});
CHECK(it != result.errors.end());
}
TEST_CASE_FIXTURE(Fixture, "no_stack_overflow_from_isoptional")
{
CheckResult result = check(R"(
function _(l0:t0): (any, ()->())
return 0,_
end
type t0 = t0 | {}
_(nil)
)");
CHECK_LE(0, result.errors.size());
std::optional<TypeFun> t0 = getMainModule()->getModuleScope()->lookupType("t0");
REQUIRE(t0);
CHECK_EQ("*unknown*", toString(t0->type));
auto it = std::find_if(result.errors.begin(), result.errors.end(), [](TypeError& err) {
return get<OccursCheckFailed>(err);
});
CHECK(it != result.errors.end());
}
TEST_CASE_FIXTURE(Fixture, "no_stack_overflow_from_isoptional2")
{
CheckResult result = check(R"(
function _(l0:({})|(t0)):((((typeof((xpcall)))|(t96<t0>))|(t13))&(t96<t0>),()->typeof(...))
return 0,_
end
type t0<t107> = ((typeof((_G)))|(({})|(t0)))|(t0)
_(nil)
local t: ({})|(t0)
)");
LUAU_REQUIRE_ERRORS(result);
}
TEST_CASE_FIXTURE(Fixture, "no_infinite_loop_when_trying_to_unify_uh_this")
{
CheckResult result = check(R"(
function _(l22,l0):((((boolean)|(t0))|(t0))&(()->(()->(()->()->{},(t0<t22>)|(t0)),any)))
return function():t0<t0>
end
end
type t0<t0> = ((typeof(_))|(any))|(typeof(_))
_()
)");
CHECK_LE(0, result.errors.size());
}
TEST_CASE_FIXTURE(Fixture, "no_stack_overflow_from_flattenintersection")
{
CheckResult result = check(R"(
local l0,l0
repeat
type t0 = ((any)|((any)&((any)|((any)&((any)|(any))))))&(t0)
function _(l0):(t0)&(t0)
while nil do
end
end
until _(_)(_)._
)");
CHECK_LE(0, result.errors.size());
}
TEST_CASE_FIXTURE(Fixture, "no_heap_use_after_free_error")
{
CheckResult result = check(R"(
--!nonstrict
_ += _:n0(xpcall,_)
local l0
do end
while _ do
function _:_()
_ += _(_._(_:n0(xpcall,_)))
end
end
)");
CHECK_LE(0, result.errors.size());
}
TEST_CASE_FIXTURE(Fixture, "dont_invalidate_the_properties_iterator_of_free_table_when_rolled_back")
{
fileResolver.source["Module/Backend/Types"] = R"(
export type Fiber = {
return_: Fiber?
}
return {}
)";
fileResolver.source["Module/Backend"] = R"(
local Types = require(script.Types)
type Fiber = Types.Fiber
type ReactRenderer = { findFiberByHostInstance: () -> Fiber? }
local function attach(renderer): ()
local function getPrimaryFiber(fiber)
local alternate = fiber.alternate
return fiber
end
local function getFiberIDForNative()
local fiber = renderer.findFiberByHostInstance()
fiber = fiber.return_
return getPrimaryFiber(fiber)
end
end
function culprit(renderer: ReactRenderer): ()
attach(renderer)
end
return culprit
)";
CheckResult result = frontend.check("Module/Backend");
}
TEST_CASE_FIXTURE(Fixture, "recursive_types_restriction_ok")
{
CheckResult result = check(R"(
type Tree<T> = { data: T, children: {Tree<T>} }
)");
LUAU_REQUIRE_NO_ERRORS(result);
}
TEST_CASE_FIXTURE(Fixture, "recursive_types_restriction_not_ok")
{
ScopedFastFlag sff{"LuauRecursiveTypeParameterRestriction", true};
CheckResult result = check(R"(
-- this would be an infinite type if we allowed it
type Tree<T> = { data: T, children: {Tree<{T}>} }
)");
LUAU_REQUIRE_ERRORS(result);
}
TEST_CASE_FIXTURE(Fixture, "record_matching_overload")
{
ScopedFastFlag sffs("LuauStoreMatchingOverloadFnType", true);
CheckResult result = check(R"(
type Overload = ((string) -> string) & ((number) -> number)
local abc: Overload
abc(1)
)");
LUAU_REQUIRE_NO_ERRORS(result);
// AstExprCall is the node that has the overload stored on it.
// findTypeAtPosition will look at the AstExprLocal, but this is not what
// we want to look at.
std::vector<AstNode*> ancestry = findAstAncestryOfPosition(*getMainSourceModule(), Position(3, 10));
REQUIRE_GE(ancestry.size(), 2);
AstExpr* parentExpr = ancestry[ancestry.size() - 2]->asExpr();
REQUIRE(bool(parentExpr));
REQUIRE(parentExpr->is<AstExprCall>());
ModulePtr module = getMainModule();
auto it = module->astOverloadResolvedTypes.find(parentExpr);
REQUIRE(it);
CHECK_EQ(toString(*it), "(number) -> number");
}
TEST_CASE_FIXTURE(Fixture, "return_type_by_overload")
{
ScopedFastFlag sff{"LuauErrorRecoveryType", true};
CheckResult result = check(R"(
type Overload = ((string) -> string) & ((number, number) -> number)
local abc: Overload
local x = abc(true)
local y = abc(true,true)
local z = abc(true,true,true)
)");
LUAU_REQUIRE_ERRORS(result);
CHECK_EQ("string", toString(requireType("x")));
CHECK_EQ("number", toString(requireType("y")));
// Should this be string|number?
CHECK_EQ("string", toString(requireType("z")));
}
TEST_CASE_FIXTURE(Fixture, "infer_anonymous_function_arguments")
{
// Simple direct arg to arg propagation
CheckResult result = check(R"(
type Table = { x: number, y: number }
local function f(a: (Table) -> number) return a({x = 1, y = 2}) end
f(function(a) return a.x + a.y end)
)");
LUAU_REQUIRE_NO_ERRORS(result);
// An optional function is accepted, but since we already provide a function, nil can be ignored
result = check(R"(
type Table = { x: number, y: number }
local function f(a: ((Table) -> number)?) if a then return a({x = 1, y = 2}) else return 0 end end
f(function(a) return a.x + a.y end)
)");
LUAU_REQUIRE_NO_ERRORS(result);
// Make sure self calls match correct index
result = check(R"(
type Table = { x: number, y: number }
local x = {}
x.b = {x = 1, y = 2}
function x:f(a: (Table) -> number) return a(self.b) end
x:f(function(a) return a.x + a.y end)
)");
LUAU_REQUIRE_NO_ERRORS(result);
// Mix inferred and explicit argument types
result = check(R"(
function f(a: (a: number, b: number, c: boolean) -> number) return a(1, 2, true) end
f(function(a: number, b, c) return c and a + b or b - a end)
)");
LUAU_REQUIRE_NO_ERRORS(result);
// Anonymous function has a variadic pack
result = check(R"(
type Table = { x: number, y: number }
local function f(a: (Table) -> number) return a({x = 1, y = 2}) end
f(function(...) return select(1, ...).z end)
)");
LUAU_REQUIRE_ERRORS(result);
CHECK_EQ("Key 'z' not found in table 'Table'", toString(result.errors[0]));
// Can't accept more arguments than provided
result = check(R"(
function f(a: (a: number, b: number) -> number) return a(1, 2) end
f(function(a, b, c, ...) return a + b end)
)");
LUAU_REQUIRE_ERRORS(result);
if (FFlag::LuauExtendedFunctionMismatchError)
{
CHECK_EQ(R"(Type '(number, number, a) -> number' could not be converted into '(number, number) -> number'
caused by:
Argument count mismatch. Function expects 3 arguments, but only 2 are specified)",
toString(result.errors[0]));
}
else
{
CHECK_EQ(R"(Type '(number, number, a) -> number' could not be converted into '(number, number) -> number')", toString(result.errors[0]));
}
// Infer from variadic packs into elements
result = check(R"(
function f(a: (...number) -> number) return a(1, 2) end
f(function(a, b) return a + b end)
)");
LUAU_REQUIRE_NO_ERRORS(result);
// Infer from variadic packs into variadic packs
result = check(R"(
type Table = { x: number, y: number }
function f(a: (...Table) -> number) return a({x = 1, y = 2}, {x = 3, y = 4}) end
f(function(a, ...) local b = ... return b.z end)
)");
LUAU_REQUIRE_ERRORS(result);
CHECK_EQ("Key 'z' not found in table 'Table'", toString(result.errors[0]));
// Return type inference
result = check(R"(
type Table = { x: number, y: number }
function f(a: (number) -> Table) return a(4) end
f(function(x) return x * 2 end)
)");
LUAU_REQUIRE_ERROR_COUNT(1, result);
CHECK_EQ("Type 'number' could not be converted into 'Table'", toString(result.errors[0]));
// Return type doesn't inference 'nil'
result = check(R"(
function f(a: (number) -> nil) return a(4) end
f(function(x) print(x) end)
)");
LUAU_REQUIRE_NO_ERRORS(result);
}
TEST_CASE_FIXTURE(Fixture, "infer_generic_function_function_argument")
{
CheckResult result = check(R"(
local function sum<a>(x: a, y: a, f: (a, a) -> a) return f(x, y) end
return sum(2, 3, function(a, b) return a + b end)
)");
LUAU_REQUIRE_NO_ERRORS(result);
result = check(R"(
local function map<a, b>(arr: {a}, f: (a) -> b) local r = {} for i,v in ipairs(arr) do table.insert(r, f(v)) end return r end
local a = {1, 2, 3}
local r = map(a, function(a) return a + a > 100 end)
)");
LUAU_REQUIRE_NO_ERRORS(result);
REQUIRE_EQ("{boolean}", toString(requireType("r")));
check(R"(
local function foldl<a, b>(arr: {a}, init: b, f: (b, a) -> b) local r = init for i,v in ipairs(arr) do r = f(r, v) end return r end
local a = {1, 2, 3}
local r = foldl(a, {s=0,c=0}, function(a, b) return {s = a.s + b, c = a.c + 1} end)
)");
LUAU_REQUIRE_NO_ERRORS(result);
REQUIRE_EQ("{| c: number, s: number |}", toString(requireType("r")));
}
TEST_CASE_FIXTURE(Fixture, "infer_generic_function_function_argument_overloaded")
{
CheckResult result = check(R"(
local function g1<T>(a: T, f: (T) -> T) return f(a) end
local function g2<T>(a: T, b: T, f: (T, T) -> T) return f(a, b) end
local g12: typeof(g1) & typeof(g2)
g12(1, function(x) return x + x end)
g12(1, 2, function(x, y) return x + y end)
)");
LUAU_REQUIRE_NO_ERRORS(result);
result = check(R"(
local function g1<T>(a: T, f: (T) -> T) return f(a) end
local function g2<T>(a: T, b: T, f: (T, T) -> T) return f(a, b) end
local g12: typeof(g1) & typeof(g2)
g12({x=1}, function(x) return {x=-x.x} end)
g12({x=1}, {x=2}, function(x, y) return {x=x.x + y.x} end)
)");
LUAU_REQUIRE_NO_ERRORS(result);
}
TEST_CASE_FIXTURE(Fixture, "infer_generic_lib_function_function_argument")
{
CheckResult result = check(R"(
local a = {{x=4}, {x=7}, {x=1}}
table.sort(a, function(x, y) return x.x < y.x end)
)");
LUAU_REQUIRE_NO_ERRORS(result);
}
TEST_CASE_FIXTURE(Fixture, "infer_anonymous_function_arguments_outside_call")
{
CheckResult result = check(R"(
type Table = { x: number, y: number }
local f: (Table) -> number = function(t) return t.x + t.y end
type TableWithFunc = { x: number, y: number, f: (number, number) -> number }
local a: TableWithFunc = { x = 3, y = 4, f = function(a, b) return a + b end }
)");
LUAU_REQUIRE_NO_ERRORS(result);
}
TEST_CASE_FIXTURE(Fixture, "do_not_infer_generic_functions")
{
CheckResult result = check(R"(
local function sum<a>(x: a, y: a, f: (a, a) -> a) return f(x, y) end
local function sumrec(f: typeof(sum))
return sum(2, 3, function(a, b) return a + b end)
end
local b = sumrec(sum) -- ok
local c = sumrec(function(x, y, f) return f(x, y) end) -- type binders are not inferred
)");
LUAU_REQUIRE_ERRORS(result);
if (FFlag::LuauExtendedFunctionMismatchError)
{
CHECK_EQ(
"Type '(a, b, (a, b) -> (c...)) -> (c...)' could not be converted into '<a>(a, a, (a, a) -> a) -> a'; different number of generic type "
"parameters",
toString(result.errors[0]));
}
else
{
CHECK_EQ("Type '(a, b, (a, b) -> (c...)) -> (c...)' could not be converted into '<a>(a, a, (a, a) -> a) -> a'", toString(result.errors[0]));
}
}
TEST_CASE_FIXTURE(Fixture, "infer_return_value_type")
{
CheckResult result = check(R"(
local function f(): {string|number}
return {1, "b", 3}
end
local function g(): (number, {string|number})
return 4, {1, "b", 3}
end
local function h(): ...{string|number}
return {4}, {1, "b", 3}, {"s"}
end
local function i(): ...{string|number}
return {1, "b", 3}, h()
end
)");
LUAU_REQUIRE_NO_ERRORS(result);
}
TEST_CASE_FIXTURE(Fixture, "infer_type_assertion_value_type")
{
CheckResult result = check(R"(
local function f()
return {4, "b", 3} :: {string|number}
end
)");
LUAU_REQUIRE_NO_ERRORS(result);
}
TEST_CASE_FIXTURE(Fixture, "infer_assignment_value_types")
{
CheckResult result = check(R"(
local a: (number, number) -> number = function(a, b) return a - b end
a = function(a, b) return a + b end
local b: {number|string}
local c: {number|string}
b, c = {2, "s"}, {"b", 4}
)");
LUAU_REQUIRE_NO_ERRORS(result);
}
TEST_CASE_FIXTURE(Fixture, "infer_assignment_value_types_mutable_lval")
{
CheckResult result = check(R"(
local a = {}
a.x = 2
a = setmetatable(a, { __call = function(x) end })
)");
LUAU_REQUIRE_NO_ERRORS(result);
}
TEST_CASE_FIXTURE(Fixture, "refine_and_or")
{
CheckResult result = check(R"(
local t: {x: number?}? = {x = nil}
local u = t and t.x or 5
)");
LUAU_REQUIRE_NO_ERRORS(result);
CHECK_EQ("number", toString(requireType("u")));
}
TEST_CASE_FIXTURE(Fixture, "checked_prop_too_early")
{
CheckResult result = check(R"(
local t: {x: number?}? = {x = nil}
local u = t.x and t or 5
)");
LUAU_REQUIRE_ERROR_COUNT(1, result);
CHECK_EQ("Value of type '{| x: number? |}?' could be nil", toString(result.errors[0]));
CHECK_EQ("number | {| x: number? |}", toString(requireType("u")));
}
TEST_CASE_FIXTURE(Fixture, "accidentally_checked_prop_in_opposite_branch")
{
CheckResult result = check(R"(
local t: {x: number?}? = {x = nil}
local u = t and t.x == 5 or t.x == 31337
)");
LUAU_REQUIRE_ERROR_COUNT(1, result);
CHECK_EQ("Value of type '{| x: number? |}?' could be nil", toString(result.errors[0]));
CHECK_EQ("boolean", toString(requireType("u")));
}
TEST_CASE_FIXTURE(Fixture, "substitution_with_bound_table")
{
ScopedFastFlag luauCloneCorrectlyBeforeMutatingTableType{"LuauCloneCorrectlyBeforeMutatingTableType", true};
CheckResult result = check(R"(
type A = { x: number }
local a: A = { x = 1 }
local b = a
type B = typeof(b)
type X<T> = T
local c: X<B>
)");
LUAU_REQUIRE_NO_ERRORS(result);
}
TEST_CASE_FIXTURE(Fixture, "tc_if_else_expressions1")
{
ScopedFastFlag sff1{"LuauIfElseExpressionBaseSupport", true};
ScopedFastFlag sff2{"LuauIfElseExpressionAnalysisSupport", true};
{
CheckResult result = check(R"(local a = if true then "true" else "false")");
LUAU_REQUIRE_NO_ERRORS(result);
TypeId aType = requireType("a");
CHECK_EQ(getPrimitiveType(aType), PrimitiveTypeVar::String);
}
}
TEST_CASE_FIXTURE(Fixture, "tc_if_else_expressions2")
{
ScopedFastFlag sff1{"LuauIfElseExpressionBaseSupport", true};
ScopedFastFlag sff2{"LuauIfElseExpressionAnalysisSupport", true};
{
// Test expression containing elseif
CheckResult result = check(R"(
local a = if false then "a" elseif false then "b" else "c"
)");
LUAU_REQUIRE_NO_ERRORS(result);
TypeId aType = requireType("a");
CHECK_EQ(getPrimitiveType(aType), PrimitiveTypeVar::String);
}
}
TEST_CASE_FIXTURE(Fixture, "tc_if_else_expressions3")
{
ScopedFastFlag sff1{"LuauIfElseExpressionBaseSupport", true};
ScopedFastFlag sff2{"LuauIfElseExpressionAnalysisSupport", true};
{
CheckResult result = check(R"(local a = if true then "true" else 42)");
// We currently require both true/false expressions to unify to the same type. However, we do intend to lift
// this restriction in the future.
LUAU_REQUIRE_ERROR_COUNT(1, result);
TypeId aType = requireType("a");
CHECK_EQ(getPrimitiveType(aType), PrimitiveTypeVar::String);
}
}
TEST_CASE_FIXTURE(Fixture, "type_error_addition")
{
CheckResult result = check(R"(
--!strict
local foo = makesandwich()
local bar = foo.nutrition + 100
)");
LUAU_REQUIRE_ERROR_COUNT(1, result);
// We should definitely get this error
CHECK_EQ("Unknown global 'makesandwich'", toString(result.errors[0]));
// We get this error if makesandwich() returns a free type
// CHECK_EQ("Unknown type used in + operation; consider adding a type annotation to 'foo'", toString(result.errors[1]));
}
TEST_CASE_FIXTURE(Fixture, "require_failed_module")
{
fileResolver.source["game/A"] = R"(
return unfortunately()
)";
CheckResult aResult = frontend.check("game/A");
LUAU_REQUIRE_ERRORS(aResult);
CheckResult result = check(R"(
local ModuleA = require(game.A)
)");
LUAU_REQUIRE_NO_ERRORS(result);
std::optional<TypeId> oty = requireType("ModuleA");
CHECK_EQ("*unknown*", toString(*oty));
}
/*
* If it wasn't instantly obvious, we have the fuzzer to thank for this gem of a test.
*
* We had an issue here where the scope for the `if` block here would
* have an elevated TypeLevel even though there is no function nesting going on.
* This would result in a free typevar for the type of _ that was much higher than
* it should be. This type would be erroneously quantified in the definition of `aaa`.
* This in turn caused an ice when evaluating `_()` in the while loop.
*/
TEST_CASE_FIXTURE(Fixture, "free_typevars_introduced_within_control_flow_constructs_do_not_get_an_elevated_TypeLevel")
{
check(R"(
--!strict
if _ then
_[_], _ = nil
_()
end
local aaa = function():typeof(_) return 1 end
if aaa then
while _() do
end
end
)");
// No ice()? No problem.
}
/*
* This is a bit elaborate. Bear with me.
*
* The type of _ becomes free with the first statement. With the second, we unify it with a function.
*
* At this point, it is important that the newly created fresh types of this new function type are promoted
* to the same level as the original free type. If we do not, they are incorrectly ascribed the level of the
* containing function.
*
* If this is allowed to happen, the final lambda erroneously quantifies the type of _ to something ridiculous
* just before we typecheck the invocation to _.
*/
TEST_CASE_FIXTURE(Fixture, "fuzzer_found_this")
{
check(R"(
l0, _ = nil
local function p()
_()
end
a = _(
function():(typeof(p),typeof(_))
end
)[nil]
)");
}
/*
* We had an issue where part of the type of pairs() was an unsealed table.
* This test depends on FFlagDebugLuauFreezeArena to trigger it.
*/
TEST_CASE_FIXTURE(Fixture, "pairs_parameters_are_not_unsealed_tables")
{
check(R"(
function _(l0:{n0:any})
_ = pairs
end
)");
}
TEST_CASE_FIXTURE(Fixture, "inferred_methods_of_free_tables_have_the_same_level_as_the_enclosing_table")
{
check(R"(
function Base64FileReader(data)
local reader = {}
local index: number
function reader:PeekByte()
return data:byte(index)
end
function reader:Byte()
return data:byte(index - 1)
end
return reader
end
Base64FileReader()
function ReadMidiEvents(data)
local reader = Base64FileReader(data)
while reader:HasMore() do
(reader:Byte() % 128)
end
end
)");
}
TEST_CASE_FIXTURE(Fixture, "error_detailed_function_mismatch_arg_count")
{
ScopedFastFlag luauExtendedFunctionMismatchError{"LuauExtendedFunctionMismatchError", true};
CheckResult result = check(R"(
type A = (number, number) -> string
type B = (number) -> string
local a: A
local b: B = a
)");
LUAU_REQUIRE_ERROR_COUNT(1, result);
CHECK_EQ(toString(result.errors[0]), R"(Type '(number, number) -> string' could not be converted into '(number) -> string'
caused by:
Argument count mismatch. Function expects 2 arguments, but only 1 is specified)");
}
TEST_CASE_FIXTURE(Fixture, "error_detailed_function_mismatch_arg")
{
ScopedFastFlag luauExtendedFunctionMismatchError{"LuauExtendedFunctionMismatchError", true};
CheckResult result = check(R"(
type A = (number, number) -> string
type B = (number, string) -> string
local a: A
local b: B = a
)");
LUAU_REQUIRE_ERROR_COUNT(1, result);
CHECK_EQ(toString(result.errors[0]), R"(Type '(number, number) -> string' could not be converted into '(number, string) -> string'
caused by:
Argument #2 type is not compatible. Type 'string' could not be converted into 'number')");
}
TEST_CASE_FIXTURE(Fixture, "error_detailed_function_mismatch_ret_count")
{
ScopedFastFlag luauExtendedFunctionMismatchError{"LuauExtendedFunctionMismatchError", true};
CheckResult result = check(R"(
type A = (number, number) -> (number)
type B = (number, number) -> (number, boolean)
local a: A
local b: B = a
)");
LUAU_REQUIRE_ERROR_COUNT(1, result);
CHECK_EQ(toString(result.errors[0]), R"(Type '(number, number) -> number' could not be converted into '(number, number) -> (number, boolean)'
caused by:
Function only returns 1 value. 2 are required here)");
}
TEST_CASE_FIXTURE(Fixture, "error_detailed_function_mismatch_ret")
{
ScopedFastFlag luauExtendedFunctionMismatchError{"LuauExtendedFunctionMismatchError", true};
CheckResult result = check(R"(
type A = (number, number) -> string
type B = (number, number) -> number
local a: A
local b: B = a
)");
LUAU_REQUIRE_ERROR_COUNT(1, result);
CHECK_EQ(toString(result.errors[0]), R"(Type '(number, number) -> string' could not be converted into '(number, number) -> number'
caused by:
Return type is not compatible. Type 'string' could not be converted into 'number')");
}
TEST_CASE_FIXTURE(Fixture, "error_detailed_function_mismatch_ret_mult")
{
ScopedFastFlag luauExtendedFunctionMismatchError{"LuauExtendedFunctionMismatchError", true};
CheckResult result = check(R"(
type A = (number, number) -> (number, string)
type B = (number, number) -> (number, boolean)
local a: A
local b: B = a
)");
LUAU_REQUIRE_ERROR_COUNT(1, result);
CHECK_EQ(
toString(result.errors[0]), R"(Type '(number, number) -> (number, string)' could not be converted into '(number, number) -> (number, boolean)'
caused by:
Return #2 type is not compatible. Type 'string' could not be converted into 'boolean')");
}
TEST_CASE_FIXTURE(Fixture, "prop_access_on_any_with_other_options")
{
ScopedFastFlag sff{"LuauLValueAsKey", true};
CheckResult result = check(R"(
local function f(thing: any | string)
local foo = thing.SomeRandomKey
end
)");
LUAU_REQUIRE_NO_ERRORS(result);
}
TEST_CASE_FIXTURE(Fixture, "table_function_check_use_after_free")
{
ScopedFastFlag luauUnifyFunctionCheckResult{"LuauUpdateFunctionNameBinding", true};
CheckResult result = check(R"(
local t = {}
function t.x(value)
for k,v in pairs(t) do end
end
)");
LUAU_REQUIRE_NO_ERRORS(result);
}
TEST_SUITE_END();
|
// Copyright (c) 2017-2021, Mudita Sp. z.o.o. All rights reserved.
// For licensing, see https://github.com/mudita/MuditaOS/LICENSE.md
#include "BluetoothSettingsModel.hpp"
#include <service-bluetooth/Constants.hpp>
#include <service-bluetooth/messages/BondedDevices.hpp>
#include <service-bluetooth/messages/Connect.hpp>
#include <service-bluetooth/messages/DeviceName.hpp>
#include <service-bluetooth/messages/Disconnect.hpp>
#include <service-bluetooth/messages/SetStatus.hpp>
#include <service-bluetooth/messages/SetDeviceName.hpp>
#include <service-bluetooth/messages/Passkey.hpp>
#include <service-bluetooth/messages/Unpair.hpp>
#include <service-bluetooth/messages/SyncDevices.hpp>
BluetoothSettingsModel::BluetoothSettingsModel(sys::Service *service) : service{service}
{}
void BluetoothSettingsModel::requestStatus()
{
service->bus.sendUnicast(std::make_shared<::message::bluetooth::RequestStatus>(), service::name::bluetooth);
}
void BluetoothSettingsModel::setStatus(const bool desiredBluetoothState, const bool desiredVisibility)
{
status.state = desiredBluetoothState ? BluetoothStatus::State::On : BluetoothStatus::State::Off;
status.visibility = desiredVisibility;
message::bluetooth::SetStatus setStatus(status);
service->bus.sendUnicast(std::make_shared<::message::bluetooth::SetStatus>(std::move(setStatus)),
service::name::bluetooth);
}
void BluetoothSettingsModel::requestDeviceName()
{
service->bus.sendUnicast(std::make_shared<::message::bluetooth::RequestDeviceName>(), service::name::bluetooth);
}
void BluetoothSettingsModel::setDeviceName(const UTF8 &deviceName)
{
service->bus.sendUnicast(std::make_shared<message::bluetooth::SetDeviceName>(deviceName), service::name::bluetooth);
}
void BluetoothSettingsModel::requestBondedDevices()
{
service->bus.sendUnicast(std::make_shared<::message::bluetooth::RequestBondedDevices>(), service::name::bluetooth);
}
void BluetoothSettingsModel::requestScan()
{
service->bus.sendUnicast(std::make_shared<BluetoothMessage>(BluetoothMessage::Request::Scan),
service::name::bluetooth);
}
void BluetoothSettingsModel::stopScan()
{
service->bus.sendUnicast(std::make_shared<BluetoothMessage>(BluetoothMessage::Request::StopScan),
service::name::bluetooth);
}
void BluetoothSettingsModel::requestDevicePair(const Devicei &device)
{
service->bus.sendUnicast(std::make_shared<BluetoothPairMessage>(device), service::name::bluetooth);
}
void BluetoothSettingsModel::requestDeviceUnpair(const Devicei &device)
{
service->bus.sendUnicast(std::make_shared<message::bluetooth::Unpair>(device), service::name::bluetooth);
}
void BluetoothSettingsModel::responsePasskey(const std::string &passkey)
{
service->bus.sendUnicast(std::make_shared<message::bluetooth::ResponsePasskey>(passkey), service::name::bluetooth);
}
void BluetoothSettingsModel::requestConnection(const Devicei &device)
{
service->bus.sendUnicast(std::make_shared<message::bluetooth::Connect>(device), service::name::bluetooth);
}
void BluetoothSettingsModel::requestDisconnection()
{
service->bus.sendUnicast(std::make_shared<message::bluetooth::Disconnect>(), service::name::bluetooth);
}
void BluetoothSettingsModel::replaceDevicesList(const std::vector<Devicei> &devicesList)
{
devices = devicesList;
}
void BluetoothSettingsModel::setActiveDeviceState(const DeviceState &state)
{
auto activeDevice = getActiveDevice();
if (activeDevice.has_value()) {
activeDevice.value().get().deviceState = state;
}
}
auto BluetoothSettingsModel::getActiveDevice() -> std::optional<std::reference_wrapper<Devicei>>
{
try {
return devices.at(activeDeviceIndex);
}
catch (const std::out_of_range &oor) {
LOG_WARN("NO DEVICE FOUND!");
return std::nullopt;
}
}
auto BluetoothSettingsModel::getSelectedDevice() -> std::optional<std::reference_wrapper<Devicei>>
{
try {
return devices.at(selectedDeviceIndex);
}
catch (const std::out_of_range &oor) {
LOG_WARN("NO DEVICE FOUND!");
return std::nullopt;
}
}
void BluetoothSettingsModel::setActiveDevice(const Devicei &device)
{
auto itr = std::find(std::begin(devices), std::end(devices), device);
activeDeviceIndex = std::distance(std::begin(devices), itr);
}
void BluetoothSettingsModel::setSelectedDevice(const Devicei &device)
{
auto itr = std::find(std::begin(devices), std::end(devices), device);
selectedDeviceIndex = std::distance(std::begin(devices), itr);
}
auto BluetoothSettingsModel::getDevices() -> std::vector<Devicei> &
{
return devices;
}
auto BluetoothSettingsModel::isDeviceConnecting() -> bool
{
auto deviceIt = std::find_if(std::begin(devices), std::end(devices), [](const Devicei &device) {
return device.deviceState == DeviceState::Connecting;
});
if (deviceIt != std::end(devices)) {
return true;
}
return false;
}
auto BluetoothSettingsModel::getStatus() const -> const BluetoothStatus
{
return status;
}
|
/*
Copyright 2020 The OneFlow 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 "oneflow/core/framework/framework.h"
namespace oneflow {
namespace {
Maybe<void> CheckPredictionLabelDesc(const user_op::TensorDesc* prediction_desc,
const user_op::TensorDesc* label_desc) {
CHECK_EQ_OR_RETURN(prediction_desc->is_dynamic(), label_desc->is_dynamic());
CHECK_GE_OR_RETURN(prediction_desc->shape().NumAxes(), 2);
const int64_t num_out_axes = prediction_desc->shape().NumAxes() - 1;
CHECK_EQ_OR_RETURN(label_desc->shape().NumAxes(), num_out_axes);
FOR_RANGE(int64_t, i, 0, num_out_axes) {
CHECK_EQ_OR_RETURN(prediction_desc->shape().At(i), label_desc->shape().At(i));
}
return Maybe<void>::Ok();
}
Maybe<void> InferTensorDescFn(user_op::InferContext* ctx) {
const user_op::TensorDesc* prediction_desc = ctx->TensorDesc4ArgNameAndIndex("prediction", 0);
const user_op::TensorDesc* label_desc = ctx->TensorDesc4ArgNameAndIndex("label", 0);
JUST(CheckPredictionLabelDesc(prediction_desc, label_desc));
user_op::TensorDesc* out_desc = ctx->OutputTensorDesc("out", 0);
*out_desc->mut_is_dynamic() = prediction_desc->is_dynamic();
*out_desc->mut_shape() = label_desc->shape();
return Maybe<void>::Ok();
}
Maybe<void> InferGradTensorDescFn(user_op::InferContext* ctx) {
const user_op::TensorDesc* prediction_desc = ctx->TensorDesc4ArgNameAndIndex("prediction", 0);
const user_op::TensorDesc* label_desc = ctx->TensorDesc4ArgNameAndIndex("label", 0);
const user_op::TensorDesc* dy_desc = ctx->TensorDesc4ArgNameAndIndex("dy", 0);
JUST(CheckPredictionLabelDesc(prediction_desc, label_desc));
CHECK_EQ_OR_RETURN(dy_desc->shape(), label_desc->shape());
*ctx->OutputShape("prediction_diff", 0) = prediction_desc->shape();
*ctx->OutputIsDynamic("prediction_diff", 0) = prediction_desc->is_dynamic();
return Maybe<void>::Ok();
}
Maybe<void> InferDataType(user_op::InferContext* ctx) {
const user_op::TensorDesc* prediction_desc = ctx->TensorDesc4ArgNameAndIndex("prediction", 0);
const user_op::TensorDesc* label_desc = ctx->TensorDesc4ArgNameAndIndex("label", 0);
CHECK_OR_RETURN(IsIndexDataType(label_desc->data_type()));
user_op::TensorDesc* out_desc = ctx->OutputTensorDesc("out", 0);
*out_desc->mut_data_type() = prediction_desc->data_type();
return Maybe<void>::Ok();
}
Maybe<void> InferDataTypeGrad(user_op::InferContext* ctx) {
const user_op::TensorDesc* prediction_desc = ctx->TensorDesc4ArgNameAndIndex("prediction", 0);
const user_op::TensorDesc* dy_desc = ctx->TensorDesc4ArgNameAndIndex("dy", 0);
const user_op::TensorDesc* label_desc = ctx->TensorDesc4ArgNameAndIndex("label", 0);
CHECK_OR_RETURN(IsIndexDataType(label_desc->data_type()));
CHECK_EQ_OR_RETURN(dy_desc->data_type(), prediction_desc->data_type());
*ctx->OutputDType("prediction_diff", 0) = prediction_desc->data_type();
return Maybe<void>::Ok();
}
Maybe<void> AddMsSignature(user_op::SbpContext* ctx) {
const user_op::TensorDesc& prediction =
ctx->LogicalTensorDesc4InputArgNameAndIndex("prediction", 0);
ctx->NewBuilder()
.Split(user_op::OpArg("prediction", 0), 0)
.Split(user_op::OpArg("label", 0), 0)
.Split(user_op::OpArg("out", 0), 0)
.Build();
ctx->NewBuilder()
.Split(user_op::OpArg("prediction", 0), prediction.shape().NumAxes() - 1)
.Broadcast(user_op::OpArg("label", 0))
.PartialSum(user_op::OpArg("out", 0))
.Build();
return Maybe<void>::Ok();
}
Maybe<void> AddSignature(user_op::SbpContext* ctx) {
ctx->NewBuilder()
.Split(user_op::OpArg("prediction", 0), 0)
.Split(user_op::OpArg("label", 0), 0)
.Split(user_op::OpArg("out", 0), 0)
.Build();
return Maybe<void>::Ok();
}
Maybe<void> AddGradMsSignature(user_op::SbpContext* ctx) {
const user_op::TensorDesc& prediction =
ctx->LogicalTensorDesc4InputArgNameAndIndex("prediction", 0);
ctx->NewBuilder()
.Split(user_op::OpArg("prediction", 0), 0)
.Split(user_op::OpArg("label", 0), 0)
.Split(user_op::OpArg("dy", 0), 0)
.Split(user_op::OpArg("prediction_diff", 0), 0)
.Build();
ctx->NewBuilder()
.Split(user_op::OpArg("prediction", 0), prediction.shape().NumAxes() - 1)
.Broadcast(user_op::OpArg("label", 0))
.Broadcast(user_op::OpArg("dy", 0))
.Split(user_op::OpArg("prediction_diff", 0), prediction.shape().NumAxes() - 1)
.Build();
return Maybe<void>::Ok();
}
Maybe<void> AddGradSignature(user_op::SbpContext* ctx) {
ctx->NewBuilder()
.Split(user_op::OpArg("prediction", 0), 0)
.Split(user_op::OpArg("label", 0), 0)
.Split(user_op::OpArg("dy", 0), 0)
.Split(user_op::OpArg("prediction_diff", 0), 0)
.Build();
return Maybe<void>::Ok();
}
template<Maybe<void> (*GetSbpSignature)(user_op::SbpContext*)>
Maybe<void> GetSbpFn(user_op::SbpContext* ctx) {
JUST(GetSbpSignature(ctx));
return Maybe<void>::Ok();
}
void GenBackwardOpConf4SparseCrossEntropy(const std::string& op_type_name,
const user_op::UserOpWrapper& op,
user_op::AddOpFn AddOp) {
if (op.NeedGenGradTensor4OpInput("prediction", 0)) {
user_op::UserOpConfWrapperBuilder builder(op.op_name() + "_grad");
user_op::UserOpConfWrapper grad_op = builder.Op(op_type_name)
.Input("prediction", op.input("prediction", 0))
.Input("label", op.input("label", 0))
.Input("dy", op.GetGradTensorWithOpOutput("out", 0))
.Output("prediction_diff")
.Attr("depth", op.attr<int64_t>("depth"))
.Build();
op.BindGradTensorWithOpInput(grad_op.output("prediction_diff", 0), "prediction", 0);
AddOp(grad_op);
}
}
} // namespace
#define REGISTER_SPAESE_CROSS_ENTROPY_USER_OP(op_name, sbp_sig) \
REGISTER_USER_OP(op_name) \
.Input("prediction") \
.Input("label") \
.Output("out") \
.Attr<int64_t>("depth") \
.SetTensorDescInferFn(InferTensorDescFn) \
.SetInputArgModifyFn([](user_op::GetInputArgModifier GetInputArgModifierFn, \
const user_op::UserOpConfWrapper&) { \
user_op::InputArgModifier* label_modifier = GetInputArgModifierFn("label", 0); \
CHECK(label_modifier != nullptr); \
label_modifier->set_requires_grad(false); \
}) \
.SetGetSbpFn(GetSbpFn<sbp_sig>) \
.SetDataTypeInferFn(InferDataType);
#define REGISTER_SPAESE_CROSS_ENTROPY_GRAD_USER_OP(op_name, sbp_sig) \
REGISTER_USER_OP(op_name) \
.Input("prediction") \
.Input("label") \
.Input("dy") \
.Output("prediction_diff") \
.Attr<int64_t>("depth") \
.SetTensorDescInferFn(InferGradTensorDescFn) \
.SetGetSbpFn(GetSbpFn<sbp_sig>) \
.SetDataTypeInferFn(InferDataTypeGrad);
REGISTER_SPAESE_CROSS_ENTROPY_USER_OP("sparse_cross_entropy", AddSignature);
REGISTER_SPAESE_CROSS_ENTROPY_USER_OP("sparse_cross_entropy_ms", AddMsSignature);
REGISTER_SPAESE_CROSS_ENTROPY_GRAD_USER_OP("sparse_cross_entropy_grad", AddGradSignature);
REGISTER_SPAESE_CROSS_ENTROPY_GRAD_USER_OP("sparse_cross_entropy_ms_grad", AddGradMsSignature);
REGISTER_USER_OP_GRAD("sparse_cross_entropy")
.SetGenBackwardOpConfFn([](const user_op::UserOpWrapper& op, user_op::AddOpFn AddOp) {
return GenBackwardOpConf4SparseCrossEntropy("sparse_cross_entropy_grad", op, AddOp);
});
REGISTER_USER_OP_GRAD("sparse_cross_entropy_ms")
.SetGenBackwardOpConfFn([](const user_op::UserOpWrapper& op, user_op::AddOpFn AddOp) {
return GenBackwardOpConf4SparseCrossEntropy("sparse_cross_entropy_ms_grad", op, AddOp);
});
} // namespace oneflow
|
// Copyright (c) 2013-2014, Matthew W. Moskewicz <moskewcz@alumni.princeton.edu>
// Copyright (c) 2013, Forrest Iandola
//#include "mex.h"
#include<octave/oct.h>
#include<octave/octave.h>
#include<octave/parse.h>
#include<octave/mxarray.h>
#include<octave/mexproto.h>
//#include "CsCascade.h" //for read_timer
double read_timer( void ) { return 0.0d; }
#include "model.h"
#include<cassert>
// see: model.h for descriptions of each class field.
// handy accessors
// return field from struct a
static inline const mxArray *F(const mxArray *a, const char *field) {
return mxGetField(a, 0, field);
}
// return pointer to field from struct a
template <typename T>
static inline T *Fpr(const mxArray *a, const char *field) {
return mxGetPr(F(a, field));
}
// return scalar of field from struct a
template <typename T>
static inline T Fsc(const mxArray *a, const char *field) {
return mxGetScalar(F(a, field));
}
// return field from struct in cell of struct array a
static inline const mxArray *CF(const mxArray *a, int cell, const char *field) {
return F(mxGetCell(a, cell), field);
}
// for SSE/AVX vectorization
//assuming layout of (x*height*depth + y_pad*depth + d)
//@param dims[0,1,2] = height, width, depth
// typically, num_features == depth, but we explicitly pass in num_features to avoid confusion about PCA vs non-PCA.
int Model::get_y_padding(const int* dims, int num_features){
int height= dims[0];
int y_padding = height + num_features%32; //e.g. if num_features=8, pad by 8*(0,1,2, or 3) to get y-dim to be 32-aligned
return y_padding;
}
// set up aligned memory, if needed. I think i'ts ok if num_features<NUM_FEATURES.
//@param dims[0,1] = height, width
//adapted from voc-release5/gdetect/fconvsse.cc
float* Model::copy_to_aligned(float *in, const int *dims, int num_features) {
float *F = (float *)malloc_aligned(32, dims[0]*dims[1]*num_features*sizeof(float)); //align to 32-blocks (for hardware...not related to HOG dimensions)
// Sanity check that memory is aligned
if (!IS_ALIGNED(F)){
printf("Memory not aligned -- in fconvsse_prepare()");
exit(0);
}
for(int i=0; i<dims[0]*dims[1]*num_features; i++){
F[i] = in[i];
}
return F;
}
// for SSE/AVX vectorization
// input layout: (x*height + y + d*height*width)
// output layout: (x*height*depth + y_pad*depth + d)
//@param dims[0,1,2] = height, width, depth
// typically, num_features == depth, but we explicitly pass in num_features to avoid confusion about PCA vs non-PCA.
float* Model::transpose_and_align(float *in, const int *dims, int num_features) {
int y_pad = get_y_padding(dims, num_features);
assert(num_features == 8 || num_features == 32);
float *F = (float *)malloc_aligned(32, y_pad*dims[1]*num_features*sizeof(float));
// Sanity check that memory is aligned
if (!IS_ALIGNED(F))
mexErrMsgTxt("Memory not aligned");
//TODO: OMP parallel for here. Need to do explicit pointer arithmetic.
float *p = F;
for (int x = 0; x < dims[1]; x++) {
for (int y = 0; y < dims[0]; y++) {
for (int f = 0; f < num_features; f++) {
*(p++) = in[y + f*dims[0]*dims[1] + x*dims[0]];
}
}
for (int y = dims[0]; y < y_pad ; y++) { //padding the end of a column, if necessary
for (int f = 0; f < num_features; f++) {
*(p++) = 0;
}
}
}
return F;
}
void Model::initmodel(const mxArray *model) {
thresh = Fsc<double>(model, "thresh");
interval = (int)Fsc<double>(model, "interval");
numcomponents = (int)Fsc<double>(model, "numcomponents");
sbin = (int)Fsc<double>(model, "sbin");
const mxArray *components = F(model, "components");
const mxArray *definfos = F(model, "defs");
const mxArray *partinfos = F(model, "partfilters");
const mxArray *rootinfos = F(model, "rootfilters");
numpartfilters = (int)(mxGetDimensions(partinfos)[1]);
numdefparams = (int)(mxGetDimensions(definfos)[1]);
numparts = new int[numcomponents];
anchors = new double**[numcomponents];
defs = new double*[numdefparams];
rootfilters[0] = new float*[numcomponents]; //non-PCA
rootfilters[1] = new float*[numcomponents]; //PCA
partfilters[0] = new float*[numpartfilters]; //non-PCA
partfilters[1] = new float*[numpartfilters]; //PCA
rootfilterdims = new mwSize*[numcomponents];
partfilterdims = new mwSize*[numpartfilters];
pfind = new int*[numcomponents];
defind = new int*[numcomponents];
loc_scores = new double*[numcomponents];
for (int i = 0; i < numpartfilters; i++) {
const mxArray *partinfo = mxGetCell(partinfos, i);
const mxArray *w = F(partinfo, "w");
partfilterdims[i] = (mwSize*)mxGetDimensions(w);
//partfilters[0][i] = (float *)mxGetPr(w);
partfilters[0][i] = transpose_and_align((float *)mxGetPr(w), partfilterdims[i], partfilterdims[i][2]); //numfeatures = partfilterdims[i][2]
w = F(partinfo, "wpca");
mwSize *pcaSize = (mwSize*)mxGetDimensions(w); //should be == (partfilterdims[i][2] == pcadim)
//partfilters[1][i] = (float *)mxGetPr(w);
partfilters[1][i] = transpose_and_align((float *)mxGetPr(w), partfilterdims[i], pcaSize[2]);
}
for (int i = 0; i < numdefparams; i++) {
const mxArray *definfo = mxGetCell(definfos, i);
defs[i] = Fpr<double>(definfo, "w");
}
const mxArray *cascadeinfo = F(model, "cascade");
const mxArray *orderinfo = F(cascadeinfo, "order");
const mxArray *mxt = F(cascadeinfo, "t");
partorder = new int*[numcomponents];
offsets = new double[numcomponents];
t = new double*[numcomponents];
for (int i = 0; i < numcomponents; i++) {
const mxArray *parts = CF(components, i, "parts");
const mxArray *w = CF(rootinfos, i, "w");
numparts[i] = mxGetDimensions(parts)[1];
rootfilterdims[i] = (mwSize*)mxGetDimensions(w); //we only have non-PCA root filters for now, since the PCA ones are handled in matlab -> fconvsse.cc
//rootfilters[i] = (float *)mxGetPr(w);
rootfilters[0][i] = transpose_and_align((float *)mxGetPr(w), rootfilterdims[i], rootfilterdims[i][2]);
w = CF(rootinfos, i, "wpca");
mwSize *pcaSize = (mwSize*)mxGetDimensions(w); //should be == (rootfilterdims[i][2] == pcadim)
rootfilters[1][i] = transpose_and_align((float *)mxGetPr(w), rootfilterdims[i], pcaSize[2]); //PCA rootfilters
anchors[i] = new double*[numparts[i]];
pfind[i] = new int[numparts[i]];
defind[i] = new int[numparts[i]];
offsets[i] = mxGetScalar(mxGetField(mxGetCell(mxGetField(model, 0, "offsets"), i), 0, "w"));
partorder[i] = new int[2*numparts[i]+2];
double *ord = mxGetPr(mxGetCell(orderinfo, i));
t[i] = mxGetPr(mxGetCell(mxt, i));
for (int j = 0; j < numparts[i]; j++) {
int dind = (int)mxGetScalar(CF(parts, j, "defindex")) - 1;
int pind = (int)mxGetScalar(CF(parts, j, "partindex")) - 1;
const mxArray *definfo = mxGetCell(definfos, dind);
anchors[i][j] = Fpr<double>(definfo, "anchor");
pfind[i][j] = pind;
defind[i][j] = dind;
}
// subtract 1 so that non-root parts are zero-indexed
for (int j = 0; j < 2*numparts[i]+2; j++)
partorder[i][j] = (int)ord[j] - 1;
}
}
void Model::initpyramid(const mxArray *pyramid, const mxArray *projpyramid) {
mxArray *mx_feat = mxGetField(pyramid, 0, "feat");
mxArray *mx_proj_feat = mxGetField(projpyramid, 0, "feat");
numfeatures = mxGetDimensions(mxGetCell(mx_feat, 0))[2];
pcadim = mxGetDimensions(mxGetCell(mx_proj_feat, 0))[2];
numlevels = (int)(mxGetDimensions(mx_feat)[0]);
featdims = new int*[numlevels];
featdimsprod = new int[numlevels];
feat[0] = new float*[numlevels];
feat[1] = new float*[numlevels];
double start_transpose = read_timer();
#pragma omp parallel for schedule(static, 1) //chunk size = 1 -> round robin
for (int l = 0; l < numlevels; l++) {
// non-PCA pyramid
const mxArray *mxA = mxGetCell(mx_feat, l);
featdims[l] = (int*)mxGetDimensions(mxA);
featdimsprod[l] = featdims[l][0]*featdims[l][1];
//feat[0][l] = (float *)mxGetPr(mxA);
feat[0][l] = transpose_and_align((float *)mxGetPr(mxA), featdims[l], numfeatures);
// projected pyramid
mxA = mxGetCell(mx_proj_feat, l);
//feat[1][l] = (float *)mxGetPr(mxA);
feat[1][l] = transpose_and_align((float *)mxGetPr(mxA), featdims[l], pcadim);
}
double time_transpose = read_timer() - start_transpose;
printf(" copied to aligned mem in %f sec \n", time_transpose);
// Location/scale scores
for (int c = 0; c < numcomponents; c++)
loc_scores[c] = mxGetPr(mxGetCell(F(pyramid, "loc_scores"), c));
}
Model::~Model() {
return;
for (int i = 0; i < numcomponents; i++) {
delete [] partorder[i];
delete [] anchors[i];
delete [] defind[i];
delete [] pfind[i];
}
delete [] loc_scores;
delete [] partorder;
delete [] t;
delete [] numparts;
delete [] offsets;
delete [] defind;
delete [] pfind;
delete [] anchors;
delete [] defs;
//TODO: free the *contents* of rootfilters and partfilters
delete [] rootfilters[0];
delete [] rootfilters[1];
delete [] rootfilterdims;
delete [] partfilters[0];
delete [] partfilters[1];
delete [] partfilterdims;
delete [] featdims;
delete [] featdimsprod;
//TODO: free the *contents* of feat[0,1][:]
delete [] feat[0];
delete [] feat[1];
}
|
/*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
// Copyright (C) 2009-2010, Willow Garage Inc., all rights reserved.
// Copyright (C) 2014, Itseez Inc., all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's 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.
//
// * The name of the copyright holders may not 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 Intel Corporation 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.
//
//M*/
/********************************* COPYRIGHT NOTICE *******************************\
Original code for Bayer->BGR/RGB conversion is provided by Dirk Schaefer
from MD-Mathematische Dienste GmbH. Below is the copyright notice:
IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
By downloading, copying, installing or using the software you agree
to this license. If you do not agree to this license, do not download,
install, copy or use the software.
Contributors License Agreement:
Copyright (c) 2002,
MD-Mathematische Dienste GmbH
Im Defdahl 5-10
44141 Dortmund
Germany
www.md-it.de
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.
The name of Contributor may not 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 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 "precomp.hpp"
#include <limits>
#define CV_DESCALE(x,n) (((x) + (1 << ((n)-1))) >> (n))
namespace cv
{
//////////////////////////// Bayer Pattern -> RGB conversion /////////////////////////////
template<typename T>
class SIMDBayerStubInterpolator_
{
public:
int bayer2Gray(const T*, int, T*, int, int, int, int) const
{
return 0;
}
int bayer2RGB(const T*, int, T*, int, int) const
{
return 0;
}
int bayer2RGBA(const T*, int, T*, int, int) const
{
return 0;
}
int bayer2RGB_EA(const T*, int, T*, int, int) const
{
return 0;
}
};
#if CV_SSE2
class SIMDBayerInterpolator_8u
{
public:
SIMDBayerInterpolator_8u()
{
use_simd = checkHardwareSupport(CV_CPU_SSE2);
}
int bayer2Gray(const uchar* bayer, int bayer_step, uchar* dst,
int width, int bcoeff, int gcoeff, int rcoeff) const
{
if( !use_simd )
return 0;
__m128i _b2y = _mm_set1_epi16((short)(rcoeff*2));
__m128i _g2y = _mm_set1_epi16((short)(gcoeff*2));
__m128i _r2y = _mm_set1_epi16((short)(bcoeff*2));
const uchar* bayer_end = bayer + width;
for( ; bayer <= bayer_end - 18; bayer += 14, dst += 14 )
{
__m128i r0 = _mm_loadu_si128((const __m128i*)bayer);
__m128i r1 = _mm_loadu_si128((const __m128i*)(bayer+bayer_step));
__m128i r2 = _mm_loadu_si128((const __m128i*)(bayer+bayer_step*2));
__m128i b1 = _mm_add_epi16(_mm_srli_epi16(_mm_slli_epi16(r0, 8), 7),
_mm_srli_epi16(_mm_slli_epi16(r2, 8), 7));
__m128i b0 = _mm_add_epi16(b1, _mm_srli_si128(b1, 2));
b1 = _mm_slli_epi16(_mm_srli_si128(b1, 2), 1);
__m128i g0 = _mm_add_epi16(_mm_srli_epi16(r0, 7), _mm_srli_epi16(r2, 7));
__m128i g1 = _mm_srli_epi16(_mm_slli_epi16(r1, 8), 7);
g0 = _mm_add_epi16(g0, _mm_add_epi16(g1, _mm_srli_si128(g1, 2)));
g1 = _mm_slli_epi16(_mm_srli_si128(g1, 2), 2);
r0 = _mm_srli_epi16(r1, 8);
r1 = _mm_slli_epi16(_mm_add_epi16(r0, _mm_srli_si128(r0, 2)), 2);
r0 = _mm_slli_epi16(r0, 3);
g0 = _mm_add_epi16(_mm_mulhi_epi16(b0, _b2y), _mm_mulhi_epi16(g0, _g2y));
g1 = _mm_add_epi16(_mm_mulhi_epi16(b1, _b2y), _mm_mulhi_epi16(g1, _g2y));
g0 = _mm_add_epi16(g0, _mm_mulhi_epi16(r0, _r2y));
g1 = _mm_add_epi16(g1, _mm_mulhi_epi16(r1, _r2y));
g0 = _mm_srli_epi16(g0, 2);
g1 = _mm_srli_epi16(g1, 2);
g0 = _mm_packus_epi16(g0, g0);
g1 = _mm_packus_epi16(g1, g1);
g0 = _mm_unpacklo_epi8(g0, g1);
_mm_storeu_si128((__m128i*)dst, g0);
}
return (int)(bayer - (bayer_end - width));
}
int bayer2RGB(const uchar* bayer, int bayer_step, uchar* dst, int width, int blue) const
{
if( !use_simd )
return 0;
/*
B G B G | B G B G | B G B G | B G B G
G R G R | G R G R | G R G R | G R G R
B G B G | B G B G | B G B G | B G B G
*/
__m128i delta1 = _mm_set1_epi16(1), delta2 = _mm_set1_epi16(2);
__m128i mask = _mm_set1_epi16(blue < 0 ? -1 : 0), z = _mm_setzero_si128();
__m128i masklo = _mm_set1_epi16(0x00ff);
const uchar* bayer_end = bayer + width;
for( ; bayer <= bayer_end - 18; bayer += 14, dst += 42 )
{
__m128i r0 = _mm_loadu_si128((const __m128i*)bayer);
__m128i r1 = _mm_loadu_si128((const __m128i*)(bayer+bayer_step));
__m128i r2 = _mm_loadu_si128((const __m128i*)(bayer+bayer_step*2));
__m128i b1 = _mm_add_epi16(_mm_and_si128(r0, masklo), _mm_and_si128(r2, masklo));
__m128i nextb1 = _mm_srli_si128(b1, 2);
__m128i b0 = _mm_add_epi16(b1, nextb1);
b1 = _mm_srli_epi16(_mm_add_epi16(nextb1, delta1), 1);
b0 = _mm_srli_epi16(_mm_add_epi16(b0, delta2), 2);
// b0 b2 ... b14 b1 b3 ... b15
b0 = _mm_packus_epi16(b0, b1);
__m128i g0 = _mm_add_epi16(_mm_srli_epi16(r0, 8), _mm_srli_epi16(r2, 8));
__m128i g1 = _mm_and_si128(r1, masklo);
g0 = _mm_add_epi16(g0, _mm_add_epi16(g1, _mm_srli_si128(g1, 2)));
g1 = _mm_srli_si128(g1, 2);
g0 = _mm_srli_epi16(_mm_add_epi16(g0, delta2), 2);
// g0 g2 ... g14 g1 g3 ... g15
g0 = _mm_packus_epi16(g0, g1);
r0 = _mm_srli_epi16(r1, 8);
r1 = _mm_add_epi16(r0, _mm_srli_si128(r0, 2));
r1 = _mm_srli_epi16(_mm_add_epi16(r1, delta1), 1);
// r0 r2 ... r14 r1 r3 ... r15
r0 = _mm_packus_epi16(r0, r1);
b1 = _mm_and_si128(_mm_xor_si128(b0, r0), mask);
b0 = _mm_xor_si128(b0, b1);
r0 = _mm_xor_si128(r0, b1);
// b1 g1 b3 g3 b5 g5...
b1 = _mm_unpackhi_epi8(b0, g0);
// b0 g0 b2 g2 b4 g4 ....
b0 = _mm_unpacklo_epi8(b0, g0);
// r1 0 r3 0 r5 0 ...
r1 = _mm_unpackhi_epi8(r0, z);
// r0 0 r2 0 r4 0 ...
r0 = _mm_unpacklo_epi8(r0, z);
// 0 b0 g0 r0 0 b2 g2 r2 ...
g0 = _mm_slli_si128(_mm_unpacklo_epi16(b0, r0), 1);
// 0 b8 g8 r8 0 b10 g10 r10 ...
g1 = _mm_slli_si128(_mm_unpackhi_epi16(b0, r0), 1);
// b1 g1 r1 0 b3 g3 r3 0 ...
r0 = _mm_unpacklo_epi16(b1, r1);
// b9 g9 r9 0 b11 g11 r11 0 ...
r1 = _mm_unpackhi_epi16(b1, r1);
// 0 b0 g0 r0 b1 g1 r1 0 ...
b0 = _mm_srli_si128(_mm_unpacklo_epi32(g0, r0), 1);
// 0 b4 g4 r4 b5 g5 r5 0 ...
b1 = _mm_srli_si128(_mm_unpackhi_epi32(g0, r0), 1);
_mm_storel_epi64((__m128i*)(dst-1+0), b0);
_mm_storel_epi64((__m128i*)(dst-1+6*1), _mm_srli_si128(b0, 8));
_mm_storel_epi64((__m128i*)(dst-1+6*2), b1);
_mm_storel_epi64((__m128i*)(dst-1+6*3), _mm_srli_si128(b1, 8));
// 0 b8 g8 r8 b9 g9 r9 0 ...
g0 = _mm_srli_si128(_mm_unpacklo_epi32(g1, r1), 1);
// 0 b12 g12 r12 b13 g13 r13 0 ...
g1 = _mm_srli_si128(_mm_unpackhi_epi32(g1, r1), 1);
_mm_storel_epi64((__m128i*)(dst-1+6*4), g0);
_mm_storel_epi64((__m128i*)(dst-1+6*5), _mm_srli_si128(g0, 8));
_mm_storel_epi64((__m128i*)(dst-1+6*6), g1);
}
return (int)(bayer - (bayer_end - width));
}
int bayer2RGBA(const uchar*, int, uchar*, int, int) const
{
return 0;
}
int bayer2RGB_EA(const uchar* bayer, int bayer_step, uchar* dst, int width, int blue) const
{
if (!use_simd)
return 0;
const uchar* bayer_end = bayer + width;
__m128i masklow = _mm_set1_epi16(0x00ff);
__m128i delta1 = _mm_set1_epi16(1), delta2 = _mm_set1_epi16(2);
__m128i full = _mm_set1_epi16(-1), z = _mm_setzero_si128();
__m128i mask = _mm_set1_epi16(blue > 0 ? -1 : 0);
for ( ; bayer <= bayer_end - 18; bayer += 14, dst += 42)
{
/*
B G B G | B G B G | B G B G | B G B G
G R G R | G R G R | G R G R | G R G R
B G B G | B G B G | B G B G | B G B G
*/
__m128i r0 = _mm_loadu_si128((const __m128i*)bayer);
__m128i r1 = _mm_loadu_si128((const __m128i*)(bayer+bayer_step));
__m128i r2 = _mm_loadu_si128((const __m128i*)(bayer+bayer_step*2));
__m128i b1 = _mm_add_epi16(_mm_and_si128(r0, masklow), _mm_and_si128(r2, masklow));
__m128i nextb1 = _mm_srli_si128(b1, 2);
__m128i b0 = _mm_add_epi16(b1, nextb1);
b1 = _mm_srli_epi16(_mm_add_epi16(nextb1, delta1), 1);
b0 = _mm_srli_epi16(_mm_add_epi16(b0, delta2), 2);
// b0 b2 ... b14 b1 b3 ... b15
b0 = _mm_packus_epi16(b0, b1);
// vertical sum
__m128i r0g = _mm_srli_epi16(r0, 8);
__m128i r2g = _mm_srli_epi16(r2, 8);
__m128i sumv = _mm_srli_epi16(_mm_add_epi16(_mm_add_epi16(r0g, r2g), delta1), 1);
// gorizontal sum
__m128i g1 = _mm_and_si128(masklow, r1);
__m128i nextg1 = _mm_srli_si128(g1, 2);
__m128i sumg = _mm_srli_epi16(_mm_add_epi16(_mm_add_epi16(g1, nextg1), delta1), 1);
// gradients
__m128i gradv = _mm_adds_epi16(_mm_subs_epu16(r0g, r2g), _mm_subs_epu16(r2g, r0g));
__m128i gradg = _mm_adds_epi16(_mm_subs_epu16(nextg1, g1), _mm_subs_epu16(g1, nextg1));
__m128i gmask = _mm_cmpgt_epi16(gradg, gradv);
__m128i g0 = _mm_add_epi16(_mm_and_si128(gmask, sumv), _mm_and_si128(sumg, _mm_xor_si128(gmask, full)));
// g0 g2 ... g14 g1 g3 ...
g0 = _mm_packus_epi16(g0, nextg1);
r0 = _mm_srli_epi16(r1, 8);
r1 = _mm_add_epi16(r0, _mm_srli_si128(r0, 2));
r1 = _mm_srli_epi16(_mm_add_epi16(r1, delta1), 1);
// r0 r2 ... r14 r1 r3 ... r15
r0 = _mm_packus_epi16(r0, r1);
b1 = _mm_and_si128(_mm_xor_si128(b0, r0), mask);
b0 = _mm_xor_si128(b0, b1);
r0 = _mm_xor_si128(r0, b1);
// b1 g1 b3 g3 b5 g5...
b1 = _mm_unpackhi_epi8(b0, g0);
// b0 g0 b2 g2 b4 g4 ....
b0 = _mm_unpacklo_epi8(b0, g0);
// r1 0 r3 0 r5 0 ...
r1 = _mm_unpackhi_epi8(r0, z);
// r0 0 r2 0 r4 0 ...
r0 = _mm_unpacklo_epi8(r0, z);
// 0 b0 g0 r0 0 b2 g2 r2 ...
g0 = _mm_slli_si128(_mm_unpacklo_epi16(b0, r0), 1);
// 0 b8 g8 r8 0 b10 g10 r10 ...
g1 = _mm_slli_si128(_mm_unpackhi_epi16(b0, r0), 1);
// b1 g1 r1 0 b3 g3 r3 0 ...
r0 = _mm_unpacklo_epi16(b1, r1);
// b9 g9 r9 0 b11 g11 r11 0 ...
r1 = _mm_unpackhi_epi16(b1, r1);
// 0 b0 g0 r0 b1 g1 r1 0 ...
b0 = _mm_srli_si128(_mm_unpacklo_epi32(g0, r0), 1);
// 0 b4 g4 r4 b5 g5 r5 0 ...
b1 = _mm_srli_si128(_mm_unpackhi_epi32(g0, r0), 1);
_mm_storel_epi64((__m128i*)(dst+0), b0);
_mm_storel_epi64((__m128i*)(dst+6*1), _mm_srli_si128(b0, 8));
_mm_storel_epi64((__m128i*)(dst+6*2), b1);
_mm_storel_epi64((__m128i*)(dst+6*3), _mm_srli_si128(b1, 8));
// 0 b8 g8 r8 b9 g9 r9 0 ...
g0 = _mm_srli_si128(_mm_unpacklo_epi32(g1, r1), 1);
// 0 b12 g12 r12 b13 g13 r13 0 ...
g1 = _mm_srli_si128(_mm_unpackhi_epi32(g1, r1), 1);
_mm_storel_epi64((__m128i*)(dst+6*4), g0);
_mm_storel_epi64((__m128i*)(dst+6*5), _mm_srli_si128(g0, 8));
_mm_storel_epi64((__m128i*)(dst+6*6), g1);
}
return int(bayer - (bayer_end - width));
}
bool use_simd;
};
#elif CV_NEON
class SIMDBayerInterpolator_8u
{
public:
SIMDBayerInterpolator_8u()
{
}
int bayer2Gray(const uchar* bayer, int bayer_step, uchar* dst,
int width, int bcoeff, int gcoeff, int rcoeff) const
{
/*
B G B G | B G B G | B G B G | B G B G
G R G R | G R G R | G R G R | G R G R
B G B G | B G B G | B G B G | B G B G
*/
uint16x8_t masklo = vdupq_n_u16(255);
const uchar* bayer_end = bayer + width;
for( ; bayer <= bayer_end - 18; bayer += 14, dst += 14 )
{
uint16x8_t r0 = vld1q_u16((const ushort*)bayer);
uint16x8_t r1 = vld1q_u16((const ushort*)(bayer + bayer_step));
uint16x8_t r2 = vld1q_u16((const ushort*)(bayer + bayer_step*2));
uint16x8_t b1_ = vaddq_u16(vandq_u16(r0, masklo), vandq_u16(r2, masklo));
uint16x8_t b1 = vextq_u16(b1_, b1_, 1);
uint16x8_t b0 = vaddq_u16(b1_, b1);
// b0 = b0 b2 b4 ...
// b1 = b1 b3 b5 ...
uint16x8_t g0 = vaddq_u16(vshrq_n_u16(r0, 8), vshrq_n_u16(r2, 8));
uint16x8_t g1 = vandq_u16(r1, masklo);
g0 = vaddq_u16(g0, vaddq_u16(g1, vextq_u16(g1, g1, 1)));
uint16x8_t rot = vextq_u16(g1, g1, 1);
g1 = vshlq_n_u16(rot, 2);
// g0 = b0 b2 b4 ...
// g1 = b1 b3 b5 ...
r0 = vshrq_n_u16(r1, 8);
r1 = vaddq_u16(r0, vextq_u16(r0, r0, 1));
r0 = vshlq_n_u16(r0, 2);
// r0 = r0 r2 r4 ...
// r1 = r1 r3 r5 ...
b0 = vreinterpretq_u16_s16(vqdmulhq_n_s16(vreinterpretq_s16_u16(b0), (short)(rcoeff*2)));
b1 = vreinterpretq_u16_s16(vqdmulhq_n_s16(vreinterpretq_s16_u16(b1), (short)(rcoeff*4)));
g0 = vreinterpretq_u16_s16(vqdmulhq_n_s16(vreinterpretq_s16_u16(g0), (short)(gcoeff*2)));
g1 = vreinterpretq_u16_s16(vqdmulhq_n_s16(vreinterpretq_s16_u16(g1), (short)(gcoeff*2)));
r0 = vreinterpretq_u16_s16(vqdmulhq_n_s16(vreinterpretq_s16_u16(r0), (short)(bcoeff*2)));
r1 = vreinterpretq_u16_s16(vqdmulhq_n_s16(vreinterpretq_s16_u16(r1), (short)(bcoeff*4)));
g0 = vaddq_u16(vaddq_u16(g0, b0), r0);
g1 = vaddq_u16(vaddq_u16(g1, b1), r1);
uint8x8x2_t p = vzip_u8(vrshrn_n_u16(g0, 2), vrshrn_n_u16(g1, 2));
vst1_u8(dst, p.val[0]);
vst1_u8(dst + 8, p.val[1]);
}
return (int)(bayer - (bayer_end - width));
}
int bayer2RGB(const uchar* bayer, int bayer_step, uchar* dst, int width, int blue) const
{
/*
B G B G | B G B G | B G B G | B G B G
G R G R | G R G R | G R G R | G R G R
B G B G | B G B G | B G B G | B G B G
*/
uint16x8_t masklo = vdupq_n_u16(255);
uint8x16x3_t pix;
const uchar* bayer_end = bayer + width;
for( ; bayer <= bayer_end - 18; bayer += 14, dst += 42 )
{
uint16x8_t r0 = vld1q_u16((const ushort*)bayer);
uint16x8_t r1 = vld1q_u16((const ushort*)(bayer + bayer_step));
uint16x8_t r2 = vld1q_u16((const ushort*)(bayer + bayer_step*2));
uint16x8_t b1 = vaddq_u16(vandq_u16(r0, masklo), vandq_u16(r2, masklo));
uint16x8_t nextb1 = vextq_u16(b1, b1, 1);
uint16x8_t b0 = vaddq_u16(b1, nextb1);
// b0 b1 b2 ...
uint8x8x2_t bb = vzip_u8(vrshrn_n_u16(b0, 2), vrshrn_n_u16(nextb1, 1));
pix.val[1-blue] = vcombine_u8(bb.val[0], bb.val[1]);
uint16x8_t g0 = vaddq_u16(vshrq_n_u16(r0, 8), vshrq_n_u16(r2, 8));
uint16x8_t g1 = vandq_u16(r1, masklo);
g0 = vaddq_u16(g0, vaddq_u16(g1, vextq_u16(g1, g1, 1)));
g1 = vextq_u16(g1, g1, 1);
// g0 g1 g2 ...
uint8x8x2_t gg = vzip_u8(vrshrn_n_u16(g0, 2), vmovn_u16(g1));
pix.val[1] = vcombine_u8(gg.val[0], gg.val[1]);
r0 = vshrq_n_u16(r1, 8);
r1 = vaddq_u16(r0, vextq_u16(r0, r0, 1));
// r0 r1 r2 ...
uint8x8x2_t rr = vzip_u8(vmovn_u16(r0), vrshrn_n_u16(r1, 1));
pix.val[1+blue] = vcombine_u8(rr.val[0], rr.val[1]);
vst3q_u8(dst-1, pix);
}
return (int)(bayer - (bayer_end - width));
}
int bayer2RGBA(const uchar* bayer, int bayer_step, uchar* dst, int width, int blue) const
{
/*
B G B G | B G B G | B G B G | B G B G
G R G R | G R G R | G R G R | G R G R
B G B G | B G B G | B G B G | B G B G
*/
uint16x8_t masklo = vdupq_n_u16(255);
uint8x16x4_t pix;
const uchar* bayer_end = bayer + width;
pix.val[3] = vdupq_n_u8(255);
for( ; bayer <= bayer_end - 18; bayer += 14, dst += 56 )
{
uint16x8_t r0 = vld1q_u16((const ushort*)bayer);
uint16x8_t r1 = vld1q_u16((const ushort*)(bayer + bayer_step));
uint16x8_t r2 = vld1q_u16((const ushort*)(bayer + bayer_step*2));
uint16x8_t b1 = vaddq_u16(vandq_u16(r0, masklo), vandq_u16(r2, masklo));
uint16x8_t nextb1 = vextq_u16(b1, b1, 1);
uint16x8_t b0 = vaddq_u16(b1, nextb1);
// b0 b1 b2 ...
uint8x8x2_t bb = vzip_u8(vrshrn_n_u16(b0, 2), vrshrn_n_u16(nextb1, 1));
pix.val[1-blue] = vcombine_u8(bb.val[0], bb.val[1]);
uint16x8_t g0 = vaddq_u16(vshrq_n_u16(r0, 8), vshrq_n_u16(r2, 8));
uint16x8_t g1 = vandq_u16(r1, masklo);
g0 = vaddq_u16(g0, vaddq_u16(g1, vextq_u16(g1, g1, 1)));
g1 = vextq_u16(g1, g1, 1);
// g0 g1 g2 ...
uint8x8x2_t gg = vzip_u8(vrshrn_n_u16(g0, 2), vmovn_u16(g1));
pix.val[1] = vcombine_u8(gg.val[0], gg.val[1]);
r0 = vshrq_n_u16(r1, 8);
r1 = vaddq_u16(r0, vextq_u16(r0, r0, 1));
// r0 r1 r2 ...
uint8x8x2_t rr = vzip_u8(vmovn_u16(r0), vrshrn_n_u16(r1, 1));
pix.val[1+blue] = vcombine_u8(rr.val[0], rr.val[1]);
vst4q_u8(dst-1, pix);
}
return (int)(bayer - (bayer_end - width));
}
int bayer2RGB_EA(const uchar*, int, uchar*, int, int) const
{
return 0;
}
};
#else
typedef SIMDBayerStubInterpolator_<uchar> SIMDBayerInterpolator_8u;
#endif
template<typename T, class SIMDInterpolator>
class Bayer2Gray_Invoker :
public ParallelLoopBody
{
public:
Bayer2Gray_Invoker(const Mat& _srcmat, Mat& _dstmat, int _start_with_green, bool _brow,
const Size& _size, int _bcoeff, int _rcoeff) :
ParallelLoopBody(), srcmat(_srcmat), dstmat(_dstmat), Start_with_green(_start_with_green),
Brow(_brow), size(_size), Bcoeff(_bcoeff), Rcoeff(_rcoeff)
{
}
virtual void operator ()(const Range& range) const CV_OVERRIDE
{
SIMDInterpolator vecOp;
const int G2Y = 9617;
const int SHIFT = 14;
const T* bayer0 = srcmat.ptr<T>();
int bayer_step = (int)(srcmat.step/sizeof(T));
T* dst0 = (T*)dstmat.data;
int dst_step = (int)(dstmat.step/sizeof(T));
int bcoeff = Bcoeff, rcoeff = Rcoeff;
int start_with_green = Start_with_green;
bool brow = Brow;
dst0 += dst_step + 1;
if (range.start % 2)
{
brow = !brow;
std::swap(bcoeff, rcoeff);
start_with_green = !start_with_green;
}
bayer0 += range.start * bayer_step;
dst0 += range.start * dst_step;
for(int i = range.start ; i < range.end; ++i, bayer0 += bayer_step, dst0 += dst_step )
{
unsigned t0, t1, t2;
const T* bayer = bayer0;
T* dst = dst0;
const T* bayer_end = bayer + size.width;
if( size.width <= 0 )
{
dst[-1] = dst[size.width] = 0;
continue;
}
if( start_with_green )
{
t0 = (bayer[1] + bayer[bayer_step*2+1])*rcoeff;
t1 = (bayer[bayer_step] + bayer[bayer_step+2])*bcoeff;
t2 = bayer[bayer_step+1]*(2*G2Y);
dst[0] = (T)CV_DESCALE(t0 + t1 + t2, SHIFT+1);
bayer++;
dst++;
}
int delta = vecOp.bayer2Gray(bayer, bayer_step, dst, size.width, bcoeff, G2Y, rcoeff);
bayer += delta;
dst += delta;
for( ; bayer <= bayer_end - 2; bayer += 2, dst += 2 )
{
t0 = (bayer[0] + bayer[2] + bayer[bayer_step*2] + bayer[bayer_step*2+2])*rcoeff;
t1 = (bayer[1] + bayer[bayer_step] + bayer[bayer_step+2] + bayer[bayer_step*2+1])*G2Y;
t2 = bayer[bayer_step+1]*(4*bcoeff);
dst[0] = (T)CV_DESCALE(t0 + t1 + t2, SHIFT+2);
t0 = (bayer[2] + bayer[bayer_step*2+2])*rcoeff;
t1 = (bayer[bayer_step+1] + bayer[bayer_step+3])*bcoeff;
t2 = bayer[bayer_step+2]*(2*G2Y);
dst[1] = (T)CV_DESCALE(t0 + t1 + t2, SHIFT+1);
}
if( bayer < bayer_end )
{
t0 = (bayer[0] + bayer[2] + bayer[bayer_step*2] + bayer[bayer_step*2+2])*rcoeff;
t1 = (bayer[1] + bayer[bayer_step] + bayer[bayer_step+2] + bayer[bayer_step*2+1])*G2Y;
t2 = bayer[bayer_step+1]*(4*bcoeff);
dst[0] = (T)CV_DESCALE(t0 + t1 + t2, SHIFT+2);
bayer++;
dst++;
}
dst0[-1] = dst0[0];
dst0[size.width] = dst0[size.width-1];
brow = !brow;
std::swap(bcoeff, rcoeff);
start_with_green = !start_with_green;
}
}
private:
Mat srcmat;
Mat dstmat;
int Start_with_green;
bool Brow;
Size size;
int Bcoeff, Rcoeff;
};
template<typename T, typename SIMDInterpolator>
static void Bayer2Gray_( const Mat& srcmat, Mat& dstmat, int code )
{
const int R2Y = 4899;
const int B2Y = 1868;
Size size = srcmat.size();
int bcoeff = B2Y, rcoeff = R2Y;
int start_with_green = code == CV_BayerGB2GRAY || code == CV_BayerGR2GRAY;
bool brow = true;
if( code != CV_BayerBG2GRAY && code != CV_BayerGB2GRAY )
{
brow = false;
std::swap(bcoeff, rcoeff);
}
size.height -= 2;
size.width -= 2;
if (size.height > 0)
{
Range range(0, size.height);
Bayer2Gray_Invoker<T, SIMDInterpolator> invoker(srcmat, dstmat,
start_with_green, brow, size, bcoeff, rcoeff);
parallel_for_(range, invoker, dstmat.total()/static_cast<double>(1<<16));
}
size = dstmat.size();
T* dst0 = dstmat.ptr<T>();
int dst_step = (int)(dstmat.step/sizeof(T));
if( size.height > 2 )
for( int i = 0; i < size.width; i++ )
{
dst0[i] = dst0[i + dst_step];
dst0[i + (size.height-1)*dst_step] = dst0[i + (size.height-2)*dst_step];
}
else
for( int i = 0; i < size.width; i++ )
dst0[i] = dst0[i + (size.height-1)*dst_step] = 0;
}
template <typename T>
struct Alpha
{
static T value() { return std::numeric_limits<T>::max(); }
};
template <>
struct Alpha<float>
{
static float value() { return 1.0f; }
};
template <typename T, typename SIMDInterpolator>
class Bayer2RGB_Invoker :
public ParallelLoopBody
{
public:
Bayer2RGB_Invoker(const Mat& _srcmat, Mat& _dstmat, int _start_with_green, int _blue, const Size& _size) :
ParallelLoopBody(),
srcmat(_srcmat), dstmat(_dstmat), Start_with_green(_start_with_green), Blue(_blue), size(_size)
{
}
virtual void operator() (const Range& range) const CV_OVERRIDE
{
SIMDInterpolator vecOp;
T alpha = Alpha<T>::value();
int dcn = dstmat.channels();
int dcn2 = dcn << 1;
int bayer_step = (int)(srcmat.step/sizeof(T));
const T* bayer0 = srcmat.ptr<T>() + bayer_step * range.start;
int dst_step = (int)(dstmat.step/sizeof(T));
T* dst0 = reinterpret_cast<T*>(dstmat.data) + (range.start + 1) * dst_step + dcn + 1;
int blue = Blue, start_with_green = Start_with_green;
if (range.start % 2)
{
blue = -blue;
start_with_green = !start_with_green;
}
for (int i = range.start; i < range.end; bayer0 += bayer_step, dst0 += dst_step, ++i )
{
int t0, t1;
const T* bayer = bayer0;
T* dst = dst0;
const T* bayer_end = bayer + size.width;
// in case of when size.width <= 2
if( size.width <= 0 )
{
if (dcn == 3)
{
dst[-4] = dst[-3] = dst[-2] = dst[size.width*dcn-1] =
dst[size.width*dcn] = dst[size.width*dcn+1] = 0;
}
else
{
dst[-5] = dst[-4] = dst[-3] = dst[size.width*dcn-1] =
dst[size.width*dcn] = dst[size.width*dcn+1] = 0;
dst[-2] = dst[size.width*dcn+2] = alpha;
}
continue;
}
if( start_with_green )
{
t0 = (bayer[1] + bayer[bayer_step*2+1] + 1) >> 1;
t1 = (bayer[bayer_step] + bayer[bayer_step+2] + 1) >> 1;
dst[-blue] = (T)t0;
dst[0] = bayer[bayer_step+1];
dst[blue] = (T)t1;
if (dcn == 4)
dst[2] = alpha; // alpha channel
bayer++;
dst += dcn;
}
// simd optimization only for dcn == 3
int delta = dcn == 4 ?
vecOp.bayer2RGBA(bayer, bayer_step, dst, size.width, blue) :
vecOp.bayer2RGB(bayer, bayer_step, dst, size.width, blue);
bayer += delta;
dst += delta*dcn;
if (dcn == 3) // Bayer to BGR
{
if( blue > 0 )
{
for( ; bayer <= bayer_end - 2; bayer += 2, dst += dcn2 )
{
t0 = (bayer[0] + bayer[2] + bayer[bayer_step*2] +
bayer[bayer_step*2+2] + 2) >> 2;
t1 = (bayer[1] + bayer[bayer_step] +
bayer[bayer_step+2] + bayer[bayer_step*2+1]+2) >> 2;
dst[-1] = (T)t0;
dst[0] = (T)t1;
dst[1] = bayer[bayer_step+1];
t0 = (bayer[2] + bayer[bayer_step*2+2] + 1) >> 1;
t1 = (bayer[bayer_step+1] + bayer[bayer_step+3] + 1) >> 1;
dst[2] = (T)t0;
dst[3] = bayer[bayer_step+2];
dst[4] = (T)t1;
}
}
else
{
for( ; bayer <= bayer_end - 2; bayer += 2, dst += dcn2 )
{
t0 = (bayer[0] + bayer[2] + bayer[bayer_step*2] +
bayer[bayer_step*2+2] + 2) >> 2;
t1 = (bayer[1] + bayer[bayer_step] +
bayer[bayer_step+2] + bayer[bayer_step*2+1]+2) >> 2;
dst[1] = (T)t0;
dst[0] = (T)t1;
dst[-1] = bayer[bayer_step+1];
t0 = (bayer[2] + bayer[bayer_step*2+2] + 1) >> 1;
t1 = (bayer[bayer_step+1] + bayer[bayer_step+3] + 1) >> 1;
dst[4] = (T)t0;
dst[3] = bayer[bayer_step+2];
dst[2] = (T)t1;
}
}
}
else // Bayer to BGRA
{
// if current row does not contain Blue pixels
if( blue > 0 )
{
for( ; bayer <= bayer_end - 2; bayer += 2, dst += dcn2 )
{
t0 = (bayer[0] + bayer[2] + bayer[bayer_step*2] +
bayer[bayer_step*2+2] + 2) >> 2;
t1 = (bayer[1] + bayer[bayer_step] +
bayer[bayer_step+2] + bayer[bayer_step*2+1]+2) >> 2;
dst[-1] = (T)t0;
dst[0] = (T)t1;
dst[1] = bayer[bayer_step+1];
dst[2] = alpha; // alpha channel
t0 = (bayer[2] + bayer[bayer_step*2+2] + 1) >> 1;
t1 = (bayer[bayer_step+1] + bayer[bayer_step+3] + 1) >> 1;
dst[3] = (T)t0;
dst[4] = bayer[bayer_step+2];
dst[5] = (T)t1;
dst[6] = alpha; // alpha channel
}
}
else // if current row contains Blue pixels
{
for( ; bayer <= bayer_end - 2; bayer += 2, dst += dcn2 )
{
t0 = (bayer[0] + bayer[2] + bayer[bayer_step*2] +
bayer[bayer_step*2+2] + 2) >> 2;
t1 = (bayer[1] + bayer[bayer_step] +
bayer[bayer_step+2] + bayer[bayer_step*2+1]+2) >> 2;
dst[-1] = bayer[bayer_step+1];
dst[0] = (T)t1;
dst[1] = (T)t0;
dst[2] = alpha; // alpha channel
t0 = (bayer[2] + bayer[bayer_step*2+2] + 1) >> 1;
t1 = (bayer[bayer_step+1] + bayer[bayer_step+3] + 1) >> 1;
dst[3] = (T)t1;
dst[4] = bayer[bayer_step+2];
dst[5] = (T)t0;
dst[6] = alpha; // alpha channel
}
}
}
// if skip one pixel at the end of row
if( bayer < bayer_end )
{
t0 = (bayer[0] + bayer[2] + bayer[bayer_step*2] +
bayer[bayer_step*2+2] + 2) >> 2;
t1 = (bayer[1] + bayer[bayer_step] +
bayer[bayer_step+2] + bayer[bayer_step*2+1]+2) >> 2;
dst[-blue] = (T)t0;
dst[0] = (T)t1;
dst[blue] = bayer[bayer_step+1];
if (dcn == 4)
dst[2] = alpha; // alpha channel
bayer++;
dst += dcn;
}
// fill the last and the first pixels of row accordingly
if (dcn == 3)
{
dst0[-4] = dst0[-1];
dst0[-3] = dst0[0];
dst0[-2] = dst0[1];
dst0[size.width*dcn-1] = dst0[size.width*dcn-4];
dst0[size.width*dcn] = dst0[size.width*dcn-3];
dst0[size.width*dcn+1] = dst0[size.width*dcn-2];
}
else
{
dst0[-5] = dst0[-1];
dst0[-4] = dst0[0];
dst0[-3] = dst0[1];
dst0[-2] = dst0[2]; // alpha channel
dst0[size.width*dcn-1] = dst0[size.width*dcn-5];
dst0[size.width*dcn] = dst0[size.width*dcn-4];
dst0[size.width*dcn+1] = dst0[size.width*dcn-3];
dst0[size.width*dcn+2] = dst0[size.width*dcn-2]; // alpha channel
}
blue = -blue;
start_with_green = !start_with_green;
}
}
private:
Mat srcmat;
Mat dstmat;
int Start_with_green, Blue;
Size size;
};
template<typename T, class SIMDInterpolator>
static void Bayer2RGB_( const Mat& srcmat, Mat& dstmat, int code )
{
int dst_step = (int)(dstmat.step/sizeof(T));
Size size = srcmat.size();
int blue = code == CV_BayerBG2BGR || code == CV_BayerGB2BGR ? -1 : 1;
int start_with_green = code == CV_BayerGB2BGR || code == CV_BayerGR2BGR;
int dcn = dstmat.channels();
size.height -= 2;
size.width -= 2;
if (size.height > 0)
{
Range range(0, size.height);
Bayer2RGB_Invoker<T, SIMDInterpolator> invoker(srcmat, dstmat, start_with_green, blue, size);
parallel_for_(range, invoker, dstmat.total()/static_cast<double>(1<<16));
}
// filling the first and the last rows
size = dstmat.size();
T* dst0 = dstmat.ptr<T>();
if( size.height > 2 )
for( int i = 0; i < size.width*dcn; i++ )
{
dst0[i] = dst0[i + dst_step];
dst0[i + (size.height-1)*dst_step] = dst0[i + (size.height-2)*dst_step];
}
else
for( int i = 0; i < size.width*dcn; i++ )
dst0[i] = dst0[i + (size.height-1)*dst_step] = 0;
}
/////////////////// Demosaicing using Variable Number of Gradients ///////////////////////
static void Bayer2RGB_VNG_8u( const Mat& srcmat, Mat& dstmat, int code )
{
const uchar* bayer = srcmat.ptr();
int bstep = (int)srcmat.step;
uchar* dst = dstmat.ptr();
int dststep = (int)dstmat.step;
Size size = srcmat.size();
int blueIdx = code == CV_BayerBG2BGR_VNG || code == CV_BayerGB2BGR_VNG ? 0 : 2;
bool greenCell0 = code != CV_BayerBG2BGR_VNG && code != CV_BayerRG2BGR_VNG;
// for too small images use the simple interpolation algorithm
if( MIN(size.width, size.height) < 8 )
{
Bayer2RGB_<uchar, SIMDBayerInterpolator_8u>( srcmat, dstmat, code );
return;
}
const int brows = 3, bcn = 7;
int N = size.width, N2 = N*2, N3 = N*3, N4 = N*4, N5 = N*5, N6 = N*6, N7 = N*7;
int i, bufstep = N7*bcn;
cv::AutoBuffer<ushort> _buf(bufstep*brows);
ushort* buf = _buf.data();
bayer += bstep*2;
#if CV_SSE2
bool haveSSE = cv::checkHardwareSupport(CV_CPU_SSE2);
#define _mm_absdiff_epu16(a,b) _mm_adds_epu16(_mm_subs_epu16(a, b), _mm_subs_epu16(b, a))
#endif
for( int y = 2; y < size.height - 4; y++ )
{
uchar* dstrow = dst + dststep*y + 6;
const uchar* srow;
for( int dy = (y == 2 ? -1 : 1); dy <= 1; dy++ )
{
ushort* brow = buf + ((y + dy - 1)%brows)*bufstep + 1;
srow = bayer + (y+dy)*bstep + 1;
for( i = 0; i < bcn; i++ )
brow[N*i-1] = brow[(N-2) + N*i] = 0;
i = 1;
#if CV_SSE2
if( haveSSE )
{
__m128i z = _mm_setzero_si128();
for( ; i <= N-9; i += 8, srow += 8, brow += 8 )
{
__m128i s1, s2, s3, s4, s6, s7, s8, s9;
s1 = _mm_unpacklo_epi8(_mm_loadl_epi64((__m128i*)(srow-1-bstep)),z);
s2 = _mm_unpacklo_epi8(_mm_loadl_epi64((__m128i*)(srow-bstep)),z);
s3 = _mm_unpacklo_epi8(_mm_loadl_epi64((__m128i*)(srow+1-bstep)),z);
s4 = _mm_unpacklo_epi8(_mm_loadl_epi64((__m128i*)(srow-1)),z);
s6 = _mm_unpacklo_epi8(_mm_loadl_epi64((__m128i*)(srow+1)),z);
s7 = _mm_unpacklo_epi8(_mm_loadl_epi64((__m128i*)(srow-1+bstep)),z);
s8 = _mm_unpacklo_epi8(_mm_loadl_epi64((__m128i*)(srow+bstep)),z);
s9 = _mm_unpacklo_epi8(_mm_loadl_epi64((__m128i*)(srow+1+bstep)),z);
__m128i b0, b1, b2, b3, b4, b5, b6;
b0 = _mm_adds_epu16(_mm_slli_epi16(_mm_absdiff_epu16(s2,s8),1),
_mm_adds_epu16(_mm_absdiff_epu16(s1, s7),
_mm_absdiff_epu16(s3, s9)));
b1 = _mm_adds_epu16(_mm_slli_epi16(_mm_absdiff_epu16(s4,s6),1),
_mm_adds_epu16(_mm_absdiff_epu16(s1, s3),
_mm_absdiff_epu16(s7, s9)));
b2 = _mm_slli_epi16(_mm_absdiff_epu16(s3,s7),1);
b3 = _mm_slli_epi16(_mm_absdiff_epu16(s1,s9),1);
_mm_storeu_si128((__m128i*)brow, b0);
_mm_storeu_si128((__m128i*)(brow + N), b1);
_mm_storeu_si128((__m128i*)(brow + N2), b2);
_mm_storeu_si128((__m128i*)(brow + N3), b3);
b4 = _mm_adds_epu16(b2,_mm_adds_epu16(_mm_absdiff_epu16(s2, s4),
_mm_absdiff_epu16(s6, s8)));
b5 = _mm_adds_epu16(b3,_mm_adds_epu16(_mm_absdiff_epu16(s2, s6),
_mm_absdiff_epu16(s4, s8)));
b6 = _mm_adds_epu16(_mm_adds_epu16(s2, s4), _mm_adds_epu16(s6, s8));
b6 = _mm_srli_epi16(b6, 1);
_mm_storeu_si128((__m128i*)(brow + N4), b4);
_mm_storeu_si128((__m128i*)(brow + N5), b5);
_mm_storeu_si128((__m128i*)(brow + N6), b6);
}
}
#endif
for( ; i < N-1; i++, srow++, brow++ )
{
brow[0] = (ushort)(std::abs(srow[-1-bstep] - srow[-1+bstep]) +
std::abs(srow[-bstep] - srow[+bstep])*2 +
std::abs(srow[1-bstep] - srow[1+bstep]));
brow[N] = (ushort)(std::abs(srow[-1-bstep] - srow[1-bstep]) +
std::abs(srow[-1] - srow[1])*2 +
std::abs(srow[-1+bstep] - srow[1+bstep]));
brow[N2] = (ushort)(std::abs(srow[+1-bstep] - srow[-1+bstep])*2);
brow[N3] = (ushort)(std::abs(srow[-1-bstep] - srow[1+bstep])*2);
brow[N4] = (ushort)(brow[N2] + std::abs(srow[-bstep] - srow[-1]) +
std::abs(srow[+bstep] - srow[1]));
brow[N5] = (ushort)(brow[N3] + std::abs(srow[-bstep] - srow[1]) +
std::abs(srow[+bstep] - srow[-1]));
brow[N6] = (ushort)((srow[-bstep] + srow[-1] + srow[1] + srow[+bstep])>>1);
}
}
const ushort* brow0 = buf + ((y - 2) % brows)*bufstep + 2;
const ushort* brow1 = buf + ((y - 1) % brows)*bufstep + 2;
const ushort* brow2 = buf + (y % brows)*bufstep + 2;
static const float scale[] = { 0.f, 0.5f, 0.25f, 0.1666666666667f, 0.125f, 0.1f, 0.08333333333f, 0.0714286f, 0.0625f };
srow = bayer + y*bstep + 2;
bool greenCell = greenCell0;
i = 2;
#if CV_SSE2
int limit = !haveSSE ? N-2 : greenCell ? std::min(3, N-2) : 2;
#else
int limit = N - 2;
#endif
do
{
for( ; i < limit; i++, srow++, brow0++, brow1++, brow2++, dstrow += 3 )
{
int gradN = brow0[0] + brow1[0];
int gradS = brow1[0] + brow2[0];
int gradW = brow1[N-1] + brow1[N];
int gradE = brow1[N] + brow1[N+1];
int minGrad = std::min(std::min(std::min(gradN, gradS), gradW), gradE);
int maxGrad = std::max(std::max(std::max(gradN, gradS), gradW), gradE);
int R, G, B;
if( !greenCell )
{
int gradNE = brow0[N4+1] + brow1[N4];
int gradSW = brow1[N4] + brow2[N4-1];
int gradNW = brow0[N5-1] + brow1[N5];
int gradSE = brow1[N5] + brow2[N5+1];
minGrad = std::min(std::min(std::min(std::min(minGrad, gradNE), gradSW), gradNW), gradSE);
maxGrad = std::max(std::max(std::max(std::max(maxGrad, gradNE), gradSW), gradNW), gradSE);
int T = minGrad + MAX(maxGrad/2, 1);
int Rs = 0, Gs = 0, Bs = 0, ng = 0;
if( gradN < T )
{
Rs += srow[-bstep*2] + srow[0];
Gs += srow[-bstep]*2;
Bs += srow[-bstep-1] + srow[-bstep+1];
ng++;
}
if( gradS < T )
{
Rs += srow[bstep*2] + srow[0];
Gs += srow[bstep]*2;
Bs += srow[bstep-1] + srow[bstep+1];
ng++;
}
if( gradW < T )
{
Rs += srow[-2] + srow[0];
Gs += srow[-1]*2;
Bs += srow[-bstep-1] + srow[bstep-1];
ng++;
}
if( gradE < T )
{
Rs += srow[2] + srow[0];
Gs += srow[1]*2;
Bs += srow[-bstep+1] + srow[bstep+1];
ng++;
}
if( gradNE < T )
{
Rs += srow[-bstep*2+2] + srow[0];
Gs += brow0[N6+1];
Bs += srow[-bstep+1]*2;
ng++;
}
if( gradSW < T )
{
Rs += srow[bstep*2-2] + srow[0];
Gs += brow2[N6-1];
Bs += srow[bstep-1]*2;
ng++;
}
if( gradNW < T )
{
Rs += srow[-bstep*2-2] + srow[0];
Gs += brow0[N6-1];
Bs += srow[-bstep+1]*2;
ng++;
}
if( gradSE < T )
{
Rs += srow[bstep*2+2] + srow[0];
Gs += brow2[N6+1];
Bs += srow[-bstep+1]*2;
ng++;
}
R = srow[0];
G = R + cvRound((Gs - Rs)*scale[ng]);
B = R + cvRound((Bs - Rs)*scale[ng]);
}
else
{
int gradNE = brow0[N2] + brow0[N2+1] + brow1[N2] + brow1[N2+1];
int gradSW = brow1[N2] + brow1[N2-1] + brow2[N2] + brow2[N2-1];
int gradNW = brow0[N3] + brow0[N3-1] + brow1[N3] + brow1[N3-1];
int gradSE = brow1[N3] + brow1[N3+1] + brow2[N3] + brow2[N3+1];
minGrad = std::min(std::min(std::min(std::min(minGrad, gradNE), gradSW), gradNW), gradSE);
maxGrad = std::max(std::max(std::max(std::max(maxGrad, gradNE), gradSW), gradNW), gradSE);
int T = minGrad + MAX(maxGrad/2, 1);
int Rs = 0, Gs = 0, Bs = 0, ng = 0;
if( gradN < T )
{
Rs += srow[-bstep*2-1] + srow[-bstep*2+1];
Gs += srow[-bstep*2] + srow[0];
Bs += srow[-bstep]*2;
ng++;
}
if( gradS < T )
{
Rs += srow[bstep*2-1] + srow[bstep*2+1];
Gs += srow[bstep*2] + srow[0];
Bs += srow[bstep]*2;
ng++;
}
if( gradW < T )
{
Rs += srow[-1]*2;
Gs += srow[-2] + srow[0];
Bs += srow[-bstep-2]+srow[bstep-2];
ng++;
}
if( gradE < T )
{
Rs += srow[1]*2;
Gs += srow[2] + srow[0];
Bs += srow[-bstep+2]+srow[bstep+2];
ng++;
}
if( gradNE < T )
{
Rs += srow[-bstep*2+1] + srow[1];
Gs += srow[-bstep+1]*2;
Bs += srow[-bstep] + srow[-bstep+2];
ng++;
}
if( gradSW < T )
{
Rs += srow[bstep*2-1] + srow[-1];
Gs += srow[bstep-1]*2;
Bs += srow[bstep] + srow[bstep-2];
ng++;
}
if( gradNW < T )
{
Rs += srow[-bstep*2-1] + srow[-1];
Gs += srow[-bstep-1]*2;
Bs += srow[-bstep-2]+srow[-bstep];
ng++;
}
if( gradSE < T )
{
Rs += srow[bstep*2+1] + srow[1];
Gs += srow[bstep+1]*2;
Bs += srow[bstep+2]+srow[bstep];
ng++;
}
G = srow[0];
R = G + cvRound((Rs - Gs)*scale[ng]);
B = G + cvRound((Bs - Gs)*scale[ng]);
}
dstrow[blueIdx] = cv::saturate_cast<uchar>(B);
dstrow[1] = cv::saturate_cast<uchar>(G);
dstrow[blueIdx^2] = cv::saturate_cast<uchar>(R);
greenCell = !greenCell;
}
#if CV_SSE2
if( !haveSSE )
break;
__m128i emask = _mm_set1_epi32(0x0000ffff),
omask = _mm_set1_epi32(0xffff0000),
z = _mm_setzero_si128(),
one = _mm_set1_epi16(1);
__m128 _0_5 = _mm_set1_ps(0.5f);
#define _mm_merge_epi16(a, b) _mm_or_si128(_mm_and_si128(a, emask), _mm_and_si128(b, omask)) //(aA_aA_aA_aA) * (bB_bB_bB_bB) => (bA_bA_bA_bA)
#define _mm_cvtloepi16_ps(a) _mm_cvtepi32_ps(_mm_srai_epi32(_mm_unpacklo_epi16(a,a), 16)) //(1,2,3,4,5,6,7,8) => (1f,2f,3f,4f)
#define _mm_cvthiepi16_ps(a) _mm_cvtepi32_ps(_mm_srai_epi32(_mm_unpackhi_epi16(a,a), 16)) //(1,2,3,4,5,6,7,8) => (5f,6f,7f,8f)
#define _mm_loadl_u8_s16(ptr, offset) _mm_unpacklo_epi8(_mm_loadl_epi64((__m128i*)((ptr) + (offset))), z) //load 8 uchars to 8 shorts
// process 8 pixels at once
for( ; i <= N - 10; i += 8, srow += 8, brow0 += 8, brow1 += 8, brow2 += 8 )
{
//int gradN = brow0[0] + brow1[0];
__m128i gradN = _mm_adds_epi16(_mm_loadu_si128((__m128i*)brow0), _mm_loadu_si128((__m128i*)brow1));
//int gradS = brow1[0] + brow2[0];
__m128i gradS = _mm_adds_epi16(_mm_loadu_si128((__m128i*)brow1), _mm_loadu_si128((__m128i*)brow2));
//int gradW = brow1[N-1] + brow1[N];
__m128i gradW = _mm_adds_epi16(_mm_loadu_si128((__m128i*)(brow1+N-1)), _mm_loadu_si128((__m128i*)(brow1+N)));
//int gradE = brow1[N+1] + brow1[N];
__m128i gradE = _mm_adds_epi16(_mm_loadu_si128((__m128i*)(brow1+N+1)), _mm_loadu_si128((__m128i*)(brow1+N)));
//int minGrad = std::min(std::min(std::min(gradN, gradS), gradW), gradE);
//int maxGrad = std::max(std::max(std::max(gradN, gradS), gradW), gradE);
__m128i minGrad = _mm_min_epi16(_mm_min_epi16(gradN, gradS), _mm_min_epi16(gradW, gradE));
__m128i maxGrad = _mm_max_epi16(_mm_max_epi16(gradN, gradS), _mm_max_epi16(gradW, gradE));
__m128i grad0, grad1;
//int gradNE = brow0[N4+1] + brow1[N4];
//int gradNE = brow0[N2] + brow0[N2+1] + brow1[N2] + brow1[N2+1];
grad0 = _mm_adds_epi16(_mm_loadu_si128((__m128i*)(brow0+N4+1)), _mm_loadu_si128((__m128i*)(brow1+N4)));
grad1 = _mm_adds_epi16( _mm_adds_epi16(_mm_loadu_si128((__m128i*)(brow0+N2)), _mm_loadu_si128((__m128i*)(brow0+N2+1))),
_mm_adds_epi16(_mm_loadu_si128((__m128i*)(brow1+N2)), _mm_loadu_si128((__m128i*)(brow1+N2+1))));
__m128i gradNE = _mm_merge_epi16(grad0, grad1);
//int gradSW = brow1[N4] + brow2[N4-1];
//int gradSW = brow1[N2] + brow1[N2-1] + brow2[N2] + brow2[N2-1];
grad0 = _mm_adds_epi16(_mm_loadu_si128((__m128i*)(brow2+N4-1)), _mm_loadu_si128((__m128i*)(brow1+N4)));
grad1 = _mm_adds_epi16(_mm_adds_epi16(_mm_loadu_si128((__m128i*)(brow2+N2)), _mm_loadu_si128((__m128i*)(brow2+N2-1))),
_mm_adds_epi16(_mm_loadu_si128((__m128i*)(brow1+N2)), _mm_loadu_si128((__m128i*)(brow1+N2-1))));
__m128i gradSW = _mm_merge_epi16(grad0, grad1);
minGrad = _mm_min_epi16(_mm_min_epi16(minGrad, gradNE), gradSW);
maxGrad = _mm_max_epi16(_mm_max_epi16(maxGrad, gradNE), gradSW);
//int gradNW = brow0[N5-1] + brow1[N5];
//int gradNW = brow0[N3] + brow0[N3-1] + brow1[N3] + brow1[N3-1];
grad0 = _mm_adds_epi16(_mm_loadu_si128((__m128i*)(brow0+N5-1)), _mm_loadu_si128((__m128i*)(brow1+N5)));
grad1 = _mm_adds_epi16(_mm_adds_epi16(_mm_loadu_si128((__m128i*)(brow0+N3)), _mm_loadu_si128((__m128i*)(brow0+N3-1))),
_mm_adds_epi16(_mm_loadu_si128((__m128i*)(brow1+N3)), _mm_loadu_si128((__m128i*)(brow1+N3-1))));
__m128i gradNW = _mm_merge_epi16(grad0, grad1);
//int gradSE = brow1[N5] + brow2[N5+1];
//int gradSE = brow1[N3] + brow1[N3+1] + brow2[N3] + brow2[N3+1];
grad0 = _mm_adds_epi16(_mm_loadu_si128((__m128i*)(brow2+N5+1)), _mm_loadu_si128((__m128i*)(brow1+N5)));
grad1 = _mm_adds_epi16(_mm_adds_epi16(_mm_loadu_si128((__m128i*)(brow2+N3)), _mm_loadu_si128((__m128i*)(brow2+N3+1))),
_mm_adds_epi16(_mm_loadu_si128((__m128i*)(brow1+N3)), _mm_loadu_si128((__m128i*)(brow1+N3+1))));
__m128i gradSE = _mm_merge_epi16(grad0, grad1);
minGrad = _mm_min_epi16(_mm_min_epi16(minGrad, gradNW), gradSE);
maxGrad = _mm_max_epi16(_mm_max_epi16(maxGrad, gradNW), gradSE);
//int T = minGrad + maxGrad/2;
__m128i T = _mm_adds_epi16(_mm_max_epi16(_mm_srli_epi16(maxGrad, 1), one), minGrad);
__m128i RGs = z, GRs = z, Bs = z, ng = z;
__m128i x0 = _mm_loadl_u8_s16(srow, +0 );
__m128i x1 = _mm_loadl_u8_s16(srow, -1 - bstep );
__m128i x2 = _mm_loadl_u8_s16(srow, -1 - bstep*2);
__m128i x3 = _mm_loadl_u8_s16(srow, - bstep );
__m128i x4 = _mm_loadl_u8_s16(srow, +1 - bstep*2);
__m128i x5 = _mm_loadl_u8_s16(srow, +1 - bstep );
__m128i x6 = _mm_loadl_u8_s16(srow, +2 - bstep );
__m128i x7 = _mm_loadl_u8_s16(srow, +1 );
__m128i x8 = _mm_loadl_u8_s16(srow, +2 + bstep );
__m128i x9 = _mm_loadl_u8_s16(srow, +1 + bstep );
__m128i x10 = _mm_loadl_u8_s16(srow, +1 + bstep*2);
__m128i x11 = _mm_loadl_u8_s16(srow, + bstep );
__m128i x12 = _mm_loadl_u8_s16(srow, -1 + bstep*2);
__m128i x13 = _mm_loadl_u8_s16(srow, -1 + bstep );
__m128i x14 = _mm_loadl_u8_s16(srow, -2 + bstep );
__m128i x15 = _mm_loadl_u8_s16(srow, -1 );
__m128i x16 = _mm_loadl_u8_s16(srow, -2 - bstep );
__m128i t0, t1, mask;
// gradN ***********************************************
mask = _mm_cmpgt_epi16(T, gradN); // mask = T>gradN
ng = _mm_sub_epi16(ng, mask); // ng += (T>gradN)
t0 = _mm_slli_epi16(x3, 1); // srow[-bstep]*2
t1 = _mm_adds_epi16(_mm_loadl_u8_s16(srow, -bstep*2), x0); // srow[-bstep*2] + srow[0]
// RGs += (srow[-bstep*2] + srow[0]) * (T>gradN)
RGs = _mm_adds_epi16(RGs, _mm_and_si128(t1, mask));
// GRs += {srow[-bstep]*2; (srow[-bstep*2-1] + srow[-bstep*2+1])} * (T>gradN)
GRs = _mm_adds_epi16(GRs, _mm_and_si128(_mm_merge_epi16(t0, _mm_adds_epi16(x2,x4)), mask));
// Bs += {(srow[-bstep-1]+srow[-bstep+1]); srow[-bstep]*2 } * (T>gradN)
Bs = _mm_adds_epi16(Bs, _mm_and_si128(_mm_merge_epi16(_mm_adds_epi16(x1,x5), t0), mask));
// gradNE **********************************************
mask = _mm_cmpgt_epi16(T, gradNE); // mask = T>gradNE
ng = _mm_sub_epi16(ng, mask); // ng += (T>gradNE)
t0 = _mm_slli_epi16(x5, 1); // srow[-bstep+1]*2
t1 = _mm_adds_epi16(_mm_loadl_u8_s16(srow, -bstep*2+2), x0); // srow[-bstep*2+2] + srow[0]
// RGs += {(srow[-bstep*2+2] + srow[0]); srow[-bstep+1]*2} * (T>gradNE)
RGs = _mm_adds_epi16(RGs, _mm_and_si128(_mm_merge_epi16(t1, t0), mask));
// GRs += {brow0[N6+1]; (srow[-bstep*2+1] + srow[1])} * (T>gradNE)
GRs = _mm_adds_epi16(GRs, _mm_and_si128(_mm_merge_epi16(_mm_loadu_si128((__m128i*)(brow0+N6+1)), _mm_adds_epi16(x4,x7)), mask));
// Bs += {srow[-bstep+1]*2; (srow[-bstep] + srow[-bstep+2])} * (T>gradNE)
Bs = _mm_adds_epi16(Bs, _mm_and_si128(_mm_merge_epi16(t0,_mm_adds_epi16(x3,x6)), mask));
// gradE ***********************************************
mask = _mm_cmpgt_epi16(T, gradE); // mask = T>gradE
ng = _mm_sub_epi16(ng, mask); // ng += (T>gradE)
t0 = _mm_slli_epi16(x7, 1); // srow[1]*2
t1 = _mm_adds_epi16(_mm_loadl_u8_s16(srow, 2), x0); // srow[2] + srow[0]
// RGs += (srow[2] + srow[0]) * (T>gradE)
RGs = _mm_adds_epi16(RGs, _mm_and_si128(t1, mask));
// GRs += (srow[1]*2) * (T>gradE)
GRs = _mm_adds_epi16(GRs, _mm_and_si128(t0, mask));
// Bs += {(srow[-bstep+1]+srow[bstep+1]); (srow[-bstep+2]+srow[bstep+2])} * (T>gradE)
Bs = _mm_adds_epi16(Bs, _mm_and_si128(_mm_merge_epi16(_mm_adds_epi16(x5,x9), _mm_adds_epi16(x6,x8)), mask));
// gradSE **********************************************
mask = _mm_cmpgt_epi16(T, gradSE); // mask = T>gradSE
ng = _mm_sub_epi16(ng, mask); // ng += (T>gradSE)
t0 = _mm_slli_epi16(x9, 1); // srow[bstep+1]*2
t1 = _mm_adds_epi16(_mm_loadl_u8_s16(srow, bstep*2+2), x0); // srow[bstep*2+2] + srow[0]
// RGs += {(srow[bstep*2+2] + srow[0]); srow[bstep+1]*2} * (T>gradSE)
RGs = _mm_adds_epi16(RGs, _mm_and_si128(_mm_merge_epi16(t1, t0), mask));
// GRs += {brow2[N6+1]; (srow[1]+srow[bstep*2+1])} * (T>gradSE)
GRs = _mm_adds_epi16(GRs, _mm_and_si128(_mm_merge_epi16(_mm_loadu_si128((__m128i*)(brow2+N6+1)), _mm_adds_epi16(x7,x10)), mask));
// Bs += {srow[-bstep+1]*2; (srow[bstep+2]+srow[bstep])} * (T>gradSE)
Bs = _mm_adds_epi16(Bs, _mm_and_si128(_mm_merge_epi16(_mm_slli_epi16(x5, 1), _mm_adds_epi16(x8,x11)), mask));
// gradS ***********************************************
mask = _mm_cmpgt_epi16(T, gradS); // mask = T>gradS
ng = _mm_sub_epi16(ng, mask); // ng += (T>gradS)
t0 = _mm_slli_epi16(x11, 1); // srow[bstep]*2
t1 = _mm_adds_epi16(_mm_loadl_u8_s16(srow,bstep*2), x0); // srow[bstep*2]+srow[0]
// RGs += (srow[bstep*2]+srow[0]) * (T>gradS)
RGs = _mm_adds_epi16(RGs, _mm_and_si128(t1, mask));
// GRs += {srow[bstep]*2; (srow[bstep*2+1]+srow[bstep*2-1])} * (T>gradS)
GRs = _mm_adds_epi16(GRs, _mm_and_si128(_mm_merge_epi16(t0, _mm_adds_epi16(x10,x12)), mask));
// Bs += {(srow[bstep+1]+srow[bstep-1]); srow[bstep]*2} * (T>gradS)
Bs = _mm_adds_epi16(Bs, _mm_and_si128(_mm_merge_epi16(_mm_adds_epi16(x9,x13), t0), mask));
// gradSW **********************************************
mask = _mm_cmpgt_epi16(T, gradSW); // mask = T>gradSW
ng = _mm_sub_epi16(ng, mask); // ng += (T>gradSW)
t0 = _mm_slli_epi16(x13, 1); // srow[bstep-1]*2
t1 = _mm_adds_epi16(_mm_loadl_u8_s16(srow, bstep*2-2), x0); // srow[bstep*2-2]+srow[0]
// RGs += {(srow[bstep*2-2]+srow[0]); srow[bstep-1]*2} * (T>gradSW)
RGs = _mm_adds_epi16(RGs, _mm_and_si128(_mm_merge_epi16(t1, t0), mask));
// GRs += {brow2[N6-1]; (srow[bstep*2-1]+srow[-1])} * (T>gradSW)
GRs = _mm_adds_epi16(GRs, _mm_and_si128(_mm_merge_epi16(_mm_loadu_si128((__m128i*)(brow2+N6-1)), _mm_adds_epi16(x12,x15)), mask));
// Bs += {srow[bstep-1]*2; (srow[bstep]+srow[bstep-2])} * (T>gradSW)
Bs = _mm_adds_epi16(Bs, _mm_and_si128(_mm_merge_epi16(t0,_mm_adds_epi16(x11,x14)), mask));
// gradW ***********************************************
mask = _mm_cmpgt_epi16(T, gradW); // mask = T>gradW
ng = _mm_sub_epi16(ng, mask); // ng += (T>gradW)
t0 = _mm_slli_epi16(x15, 1); // srow[-1]*2
t1 = _mm_adds_epi16(_mm_loadl_u8_s16(srow, -2), x0); // srow[-2]+srow[0]
// RGs += (srow[-2]+srow[0]) * (T>gradW)
RGs = _mm_adds_epi16(RGs, _mm_and_si128(t1, mask));
// GRs += (srow[-1]*2) * (T>gradW)
GRs = _mm_adds_epi16(GRs, _mm_and_si128(t0, mask));
// Bs += {(srow[-bstep-1]+srow[bstep-1]); (srow[bstep-2]+srow[-bstep-2])} * (T>gradW)
Bs = _mm_adds_epi16(Bs, _mm_and_si128(_mm_merge_epi16(_mm_adds_epi16(x1,x13), _mm_adds_epi16(x14,x16)), mask));
// gradNW **********************************************
mask = _mm_cmpgt_epi16(T, gradNW); // mask = T>gradNW
ng = _mm_sub_epi16(ng, mask); // ng += (T>gradNW)
t0 = _mm_slli_epi16(x1, 1); // srow[-bstep-1]*2
t1 = _mm_adds_epi16(_mm_loadl_u8_s16(srow,-bstep*2-2), x0); // srow[-bstep*2-2]+srow[0]
// RGs += {(srow[-bstep*2-2]+srow[0]); srow[-bstep-1]*2} * (T>gradNW)
RGs = _mm_adds_epi16(RGs, _mm_and_si128(_mm_merge_epi16(t1, t0), mask));
// GRs += {brow0[N6-1]; (srow[-bstep*2-1]+srow[-1])} * (T>gradNW)
GRs = _mm_adds_epi16(GRs, _mm_and_si128(_mm_merge_epi16(_mm_loadu_si128((__m128i*)(brow0+N6-1)), _mm_adds_epi16(x2,x15)), mask));
// Bs += {srow[-bstep-1]*2; (srow[-bstep]+srow[-bstep-2])} * (T>gradNW)
Bs = _mm_adds_epi16(Bs, _mm_and_si128(_mm_merge_epi16(_mm_slli_epi16(x5, 1),_mm_adds_epi16(x3,x16)), mask));
__m128 ngf0 = _mm_div_ps(_0_5, _mm_cvtloepi16_ps(ng));
__m128 ngf1 = _mm_div_ps(_0_5, _mm_cvthiepi16_ps(ng));
// now interpolate r, g & b
t0 = _mm_subs_epi16(GRs, RGs);
t1 = _mm_subs_epi16(Bs, RGs);
t0 = _mm_add_epi16(x0, _mm_packs_epi32(
_mm_cvtps_epi32(_mm_mul_ps(_mm_cvtloepi16_ps(t0), ngf0)),
_mm_cvtps_epi32(_mm_mul_ps(_mm_cvthiepi16_ps(t0), ngf1))));
t1 = _mm_add_epi16(x0, _mm_packs_epi32(
_mm_cvtps_epi32(_mm_mul_ps(_mm_cvtloepi16_ps(t1), ngf0)),
_mm_cvtps_epi32(_mm_mul_ps(_mm_cvthiepi16_ps(t1), ngf1))));
x1 = _mm_merge_epi16(x0, t0);
x2 = _mm_merge_epi16(t0, x0);
uchar R[8], G[8], B[8];
_mm_storel_epi64(blueIdx ? (__m128i*)B : (__m128i*)R, _mm_packus_epi16(x1, z));
_mm_storel_epi64((__m128i*)G, _mm_packus_epi16(x2, z));
_mm_storel_epi64(blueIdx ? (__m128i*)R : (__m128i*)B, _mm_packus_epi16(t1, z));
for( int j = 0; j < 8; j++, dstrow += 3 )
{
dstrow[0] = B[j]; dstrow[1] = G[j]; dstrow[2] = R[j];
}
}
#endif
limit = N - 2;
}
while( i < N - 2 );
for( i = 0; i < 6; i++ )
{
dst[dststep*y + 5 - i] = dst[dststep*y + 8 - i];
dst[dststep*y + (N - 2)*3 + i] = dst[dststep*y + (N - 3)*3 + i];
}
greenCell0 = !greenCell0;
blueIdx ^= 2;
}
for( i = 0; i < size.width*3; i++ )
{
dst[i] = dst[i + dststep] = dst[i + dststep*2];
dst[i + dststep*(size.height-4)] =
dst[i + dststep*(size.height-3)] =
dst[i + dststep*(size.height-2)] =
dst[i + dststep*(size.height-1)] = dst[i + dststep*(size.height-5)];
}
}
//////////////////////////////// Edge-Aware Demosaicing //////////////////////////////////
template <typename T, typename SIMDInterpolator>
class Bayer2RGB_EdgeAware_T_Invoker :
public cv::ParallelLoopBody
{
public:
Bayer2RGB_EdgeAware_T_Invoker(const Mat& _src, Mat& _dst, const Size& _size,
int _blue, int _start_with_green) :
ParallelLoopBody(),
src(_src), dst(_dst), size(_size), Blue(_blue), Start_with_green(_start_with_green)
{
}
virtual void operator()(const Range& range) const CV_OVERRIDE
{
int dcn = dst.channels();
int dcn2 = dcn<<1;
int start_with_green = Start_with_green, blue = Blue;
int sstep = int(src.step / src.elemSize1()), dstep = int(dst.step / dst.elemSize1());
SIMDInterpolator vecOp;
const T* S = src.ptr<T>(range.start + 1) + 1;
T* D = reinterpret_cast<T*>(dst.data + (range.start + 1) * dst.step) + dcn;
if (range.start % 2)
{
start_with_green ^= 1;
blue ^= 1;
}
// to BGR
for (int y = range.start; y < range.end; ++y)
{
int x = 1;
if (start_with_green)
{
D[blue<<1] = (S[-sstep] + S[sstep]) >> 1;
D[1] = S[0];
D[2-(blue<<1)] = (S[-1] + S[1]) >> 1;
D += dcn;
++S;
++x;
}
int delta = vecOp.bayer2RGB_EA(S - sstep - 1, sstep, D, size.width, blue);
x += delta;
S += delta;
D += dcn * delta;
if (blue)
for (; x < size.width; x += 2, S += 2, D += dcn2)
{
D[0] = S[0];
D[1] = (std::abs(S[-1] - S[1]) > std::abs(S[sstep] - S[-sstep]) ? (S[sstep] + S[-sstep] + 1) : (S[-1] + S[1] + 1)) >> 1;
D[2] = (S[-sstep-1] + S[-sstep+1] + S[sstep-1] + S[sstep+1]) >> 2;
D[3] = (S[0] + S[2] + 1) >> 1;
D[4] = S[1];
D[5] = (S[-sstep+1] + S[sstep+1] + 1) >> 1;
}
else
for (; x < size.width; x += 2, S += 2, D += dcn2)
{
D[0] = (S[-sstep-1] + S[-sstep+1] + S[sstep-1] + S[sstep+1] + 2) >> 2;
D[1] = (std::abs(S[-1] - S[1]) > std::abs(S[sstep] - S[-sstep]) ? (S[sstep] + S[-sstep] + 1) : (S[-1] + S[1] + 1)) >> 1;
D[2] = S[0];
D[3] = (S[-sstep+1] + S[sstep+1] + 1) >> 1;
D[4] = S[1];
D[5] = (S[0] + S[2] + 1) >> 1;
}
if (x <= size.width)
{
D[blue<<1] = (S[-sstep-1] + S[-sstep+1] + S[sstep-1] + S[sstep+1] + 2) >> 2;
D[1] = (std::abs(S[-1] - S[1]) > std::abs(S[sstep] - S[-sstep]) ? (S[sstep] + S[-sstep] + 1) : (S[-1] + S[1] + 1)) >> 1;
D[2-(blue<<1)] = S[0];
D += dcn;
++S;
}
for (int i = 0; i < dcn; ++i)
{
D[i] = D[-dcn + i];
D[-dstep+dcn+i] = D[-dstep+(dcn<<1)+i];
}
start_with_green ^= 1;
blue ^= 1;
S += 2;
D += dcn2;
}
}
private:
Mat src;
Mat dst;
Size size;
int Blue, Start_with_green;
};
template <typename T, typename SIMDInterpolator>
static void Bayer2RGB_EdgeAware_T(const Mat& src, Mat& dst, int code)
{
Size size = src.size();
// for small sizes
if (size.width <= 2 || size.height <= 2)
{
dst = Scalar::all(0);
return;
}
size.width -= 2;
size.height -= 2;
int start_with_green = code == CV_BayerGB2BGR_EA || code == CV_BayerGR2BGR_EA ? 1 : 0;
int blue = code == CV_BayerGB2BGR_EA || code == CV_BayerBG2BGR_EA ? 1 : 0;
if (size.height > 0)
{
Bayer2RGB_EdgeAware_T_Invoker<T, SIMDInterpolator> invoker(src, dst, size, blue, start_with_green);
Range range(0, size.height);
parallel_for_(range, invoker, dst.total()/static_cast<double>(1<<16));
}
size = dst.size();
size.width *= dst.channels();
size_t dstep = dst.step / dst.elemSize1();
T* firstRow = dst.ptr<T>();
T* lastRow = dst.ptr<T>() + (size.height-1) * dstep;
if (size.height > 2)
{
for (int x = 0; x < size.width; ++x)
{
firstRow[x] = (firstRow+dstep)[x];
lastRow[x] = (lastRow-dstep)[x];
}
}
else
for (int x = 0; x < size.width; ++x)
firstRow[x] = lastRow[x] = 0;
}
} // end namespace cv
//////////////////////////////////////////////////////////////////////////////////////////
// The main Demosaicing function //
//////////////////////////////////////////////////////////////////////////////////////////
void cv::demosaicing(InputArray _src, OutputArray _dst, int code, int dcn)
{
CV_INSTRUMENT_REGION()
Mat src = _src.getMat(), dst;
Size sz = src.size();
int scn = src.channels(), depth = src.depth();
CV_Assert(depth == CV_8U || depth == CV_16U);
CV_Assert(!src.empty());
switch (code)
{
case CV_BayerBG2GRAY: case CV_BayerGB2GRAY: case CV_BayerRG2GRAY: case CV_BayerGR2GRAY:
if (dcn <= 0)
dcn = 1;
CV_Assert( scn == 1 && dcn == 1 );
_dst.create(sz, CV_MAKETYPE(depth, dcn));
dst = _dst.getMat();
if( depth == CV_8U )
Bayer2Gray_<uchar, SIMDBayerInterpolator_8u>(src, dst, code);
else if( depth == CV_16U )
Bayer2Gray_<ushort, SIMDBayerStubInterpolator_<ushort> >(src, dst, code);
else
CV_Error(CV_StsUnsupportedFormat, "Bayer->Gray demosaicing only supports 8u and 16u types");
break;
case CV_BayerBG2BGR: case CV_BayerGB2BGR: case CV_BayerRG2BGR: case CV_BayerGR2BGR:
case CV_BayerBG2BGRA: case CV_BayerGB2BGRA: case CV_BayerRG2BGRA: case CV_BayerGR2BGRA:
case CV_BayerBG2BGR_VNG: case CV_BayerGB2BGR_VNG: case CV_BayerRG2BGR_VNG: case CV_BayerGR2BGR_VNG:
{
if (dcn <= 0)
dcn = 3;
CV_Assert( scn == 1 && (dcn == 3 || dcn == 4) );
_dst.create(sz, CV_MAKE_TYPE(depth, dcn));
Mat dst_ = _dst.getMat();
if( code == CV_BayerBG2BGR || code == CV_BayerBG2BGRA ||
code == CV_BayerGB2BGR || code == CV_BayerGB2BGRA ||
code == CV_BayerRG2BGR || code == CV_BayerRG2BGRA ||
code == CV_BayerGR2BGR || code == CV_BayerGR2BGRA )
{
if( depth == CV_8U )
Bayer2RGB_<uchar, SIMDBayerInterpolator_8u>(src, dst_, code);
else if( depth == CV_16U )
Bayer2RGB_<ushort, SIMDBayerStubInterpolator_<ushort> >(src, dst_, code);
else
CV_Error(CV_StsUnsupportedFormat, "Bayer->RGB demosaicing only supports 8u and 16u types");
}
else
{
CV_Assert( depth == CV_8U );
Bayer2RGB_VNG_8u(src, dst_, code);
}
}
break;
case CV_BayerBG2BGR_EA: case CV_BayerGB2BGR_EA: case CV_BayerRG2BGR_EA: case CV_BayerGR2BGR_EA:
if (dcn <= 0)
dcn = 3;
CV_Assert(scn == 1 && dcn == 3);
_dst.create(sz, CV_MAKETYPE(depth, dcn));
dst = _dst.getMat();
if (depth == CV_8U)
Bayer2RGB_EdgeAware_T<uchar, SIMDBayerInterpolator_8u>(src, dst, code);
else if (depth == CV_16U)
Bayer2RGB_EdgeAware_T<ushort, SIMDBayerStubInterpolator_<ushort> >(src, dst, code);
else
CV_Error(CV_StsUnsupportedFormat, "Bayer->RGB Edge-Aware demosaicing only currently supports 8u and 16u types");
break;
default:
CV_Error( CV_StsBadFlag, "Unknown / unsupported color conversion code" );
}
}
|
/**
* Copyright (c) 2021 OceanBase
* OceanBase CE is licensed under Mulan PubL v2.
* You can use this software according to the terms and conditions of the Mulan PubL v2.
* You may obtain a copy of Mulan PubL v2 at:
* http://license.coscl.org.cn/MulanPubL-2.0
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PubL v2 for more details.
*/
#include "ob_partition_log_service.h"
#include "storage/ob_partition_service.h"
#include "ob_clog_config.h"
namespace oceanbase {
using namespace common;
namespace clog {
int ObClogAggreTask::set_partition_key(const ObPartitionKey& pkey)
{
int ret = OB_SUCCESS;
if (!pkey.is_valid()) {
ret = OB_INVALID_ARGUMENT;
} else {
pkey_ = pkey;
}
return ret;
}
int ObClogAggreTask::set_run_ts(const int64_t run_ts)
{
int ret = OB_SUCCESS;
if (0 >= run_ts) {
ret = OB_INVALID_ARGUMENT;
} else {
run_ts_ = run_ts;
}
return ret;
}
void ObClogAggreTask::handle()
{
int ret = OB_SUCCESS;
const int64_t cur_ts = ObTimeUtility::current_time();
const int64_t sleep_ts = run_ts_ - cur_ts;
if (sleep_ts > 0) {
usleep(sleep_ts);
}
if (NULL != ps_) {
if (OB_FAIL(ps_->try_freeze_aggre_buffer(pkey_))) {
CLOG_LOG(WARN, "try freeze aggre buffer failed", K(ret), K_(pkey));
}
}
if (NULL != host_) {
if (OB_FAIL(host_->push_back(this))) {
CLOG_LOG(WARN, "push back aggre task failed", K(ret), K_(pkey));
}
}
}
ObClogAggreRunnable::ObClogAggreRunnable() : is_inited_(false), available_index_(-1), tg_id_(-1)
{
for (int64_t i = 0; i < TOTAL_TASK; i++) {
task_array_[i] = NULL;
}
}
ObClogAggreRunnable::~ObClogAggreRunnable()
{
destroy();
}
int ObClogAggreRunnable::init(storage::ObPartitionService* partition_service)
{
int ret = OB_SUCCESS;
if (is_inited_) {
ret = OB_INIT_TWICE;
CLOG_LOG(WARN, "ObClogAggreRunnable has already been inited", K(ret));
} else if (OB_ISNULL(partition_service)) {
ret = OB_INVALID_ARGUMENT;
CLOG_LOG(WARN, "invalid argument", K(ret), KP(partition_service));
} else if (OB_FAIL(TG_CREATE(lib::TGDefIDs::ClogAggre, tg_id_))) {
TRANS_LOG(WARN, "create tg failed", K(ret));
} else {
ObMemAttr memattr(OB_SERVER_TENANT_ID, "ObClogAggreTask");
for (int64_t i = 0; OB_SUCC(ret) && i < TOTAL_TASK; i++) {
ObClogAggreTask* ptr = (ObClogAggreTask*)ob_malloc(sizeof(ObClogAggreTask), memattr);
if (NULL == ptr) {
ret = OB_ALLOCATE_MEMORY_FAILED;
} else {
new (ptr) ObClogAggreTask(this, partition_service);
task_array_[i] = ptr;
available_index_ = i;
}
}
}
if (OB_SUCC(ret)) {
is_inited_ = true;
} else {
destroy();
}
CLOG_LOG(INFO, "ObClogAggreRunnable init finished", K(ret));
return ret;
}
int ObClogAggreRunnable::start()
{
int ret = OB_SUCCESS;
if (OB_FAIL(TG_SET_HANDLER_AND_START(tg_id_, *this))) {
TRANS_LOG(WARN, "thread pool init error", K(ret));
} else {
CLOG_LOG(INFO, "clog aggre runnable start success", KP(this));
}
return ret;
}
void ObClogAggreRunnable::stop()
{
TG_STOP(tg_id_);
CLOG_LOG(INFO, "clog aggre runnable stop success", KP(this));
}
void ObClogAggreRunnable::wait()
{
CLOG_LOG(INFO, "clog aggre runnable wait success", KP(this));
}
void ObClogAggreRunnable::destroy()
{
if (is_inited_) {
stop();
wait();
while (available_index_ >= 0) {
task_array_[available_index_]->~ObClogAggreTask();
ob_free(task_array_[available_index_]);
task_array_[available_index_] = NULL;
available_index_--;
}
tg_id_ = -1;
is_inited_ = false;
CLOG_LOG(INFO, "clog aggre runnable destroy", KP(this));
}
}
int ObClogAggreRunnable::add_task(const ObPartitionKey& pkey, const int64_t delay_us)
{
int ret = OB_SUCCESS;
if (!pkey.is_valid() || 0 >= delay_us) {
ret = OB_INVALID_ARGUMENT;
CLOG_LOG(WARN, "invalid argument", K(ret), K(pkey), K(delay_us));
} else {
ObClogAggreTask* task = NULL;
{
ObSpinLockGuard guard(lock_);
if (available_index_ >= 0) {
task = task_array_[available_index_];
task_array_[available_index_] = NULL;
available_index_--;
} else {
ret = OB_EAGAIN;
}
}
if (OB_SUCC(ret)) {
if (OB_FAIL(task->set_partition_key(pkey))) {
CLOG_LOG(WARN, "set partition key failed", K(ret), K(pkey));
} else if (OB_FAIL(task->set_run_ts(ObTimeUtility::current_time() + delay_us))) {
CLOG_LOG(WARN, "set run ts failed", K(delay_us));
} else if (OB_FAIL(TG_PUSH_TASK(tg_id_, task))) {
CLOG_LOG(WARN, "schedule timer task failed", K(ret), K(pkey), K(delay_us));
}
}
}
return ret;
}
void ObClogAggreRunnable::handle(void* task)
{
if (NULL == task) {
TRANS_LOG(ERROR, "task is null", KP(task));
} else {
ObClogAggreTask* aggre_task = static_cast<ObClogAggreTask*>(task);
aggre_task->handle();
}
}
int ObClogAggreRunnable::push_back(ObClogAggreTask* task)
{
int ret = OB_SUCCESS;
if (OB_ISNULL(task)) {
ret = OB_INVALID_ARGUMENT;
CLOG_LOG(WARN, "invalid argument", K(ret), KP(task));
} else {
ObSpinLockGuard guard(lock_);
task_array_[++available_index_] = task;
}
return ret;
}
} // namespace clog
} // namespace oceanbase
|
/****************************************************************************
*
* Copyright (c) 2018-2020 PX4 Development Team. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name PX4 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 "PX4Gyroscope.hpp"
#include <lib/drivers/device/Device.hpp>
#include <lib/parameters/param.h>
using namespace time_literals;
using matrix::Vector3f;
static constexpr int32_t sum(const int16_t samples[16], uint8_t len)
{
int32_t sum = 0;
for (int n = 0; n < len; n++) {
sum += samples[n];
}
return sum;
}
PX4Gyroscope::PX4Gyroscope(uint32_t device_id, enum Rotation rotation) :
_device_id{device_id},
_rotation{rotation}
{
// advertise immediately to keep instance numbering in sync
_sensor_pub.advertise();
param_get(param_find("IMU_GYRO_RATEMAX"), &_imu_gyro_rate_max);
}
PX4Gyroscope::~PX4Gyroscope()
{
_sensor_pub.unadvertise();
_sensor_fifo_pub.unadvertise();
}
void PX4Gyroscope::set_device_type(uint8_t devtype)
{
// current DeviceStructure
union device::Device::DeviceId device_id;
device_id.devid = _device_id;
// update to new device type
device_id.devid_s.devtype = devtype;
// copy back
_device_id = device_id.devid;
}
void PX4Gyroscope::update(const hrt_abstime ×tamp_sample, float x, float y, float z)
{
// publish
Publish(timestamp_sample, x, y, z);
}
void PX4Gyroscope::updateFIFO(sensor_gyro_fifo_s &sample)
{
// publish fifo
sample.device_id = _device_id;
sample.scale = _scale;
sample.rotation = _rotation;
sample.timestamp = hrt_absolute_time();
_sensor_fifo_pub.publish(sample);
{
// trapezoidal integration (equally spaced, scaled by dt later)
const uint8_t N = sample.samples;
const Vector3f integral{
(0.5f * (_last_sample[0] + sample.x[N - 1]) + sum(sample.x, N - 1)),
(0.5f * (_last_sample[1] + sample.y[N - 1]) + sum(sample.y, N - 1)),
(0.5f * (_last_sample[2] + sample.z[N - 1]) + sum(sample.z, N - 1)),
};
_last_sample[0] = sample.x[N - 1];
_last_sample[1] = sample.y[N - 1];
_last_sample[2] = sample.z[N - 1];
const float x = integral(0) / (float)N;
const float y = integral(1) / (float)N;
const float z = integral(2) / (float)N;
// publish
Publish(sample.timestamp_sample, x, y, z);
}
}
void PX4Gyroscope::Publish(const hrt_abstime ×tamp_sample, float x, float y, float z)
{
// Apply rotation (before scaling)
rotate_3f(_rotation, x, y, z);
sensor_gyro_s report;
report.timestamp_sample = timestamp_sample;
report.device_id = _device_id;
report.temperature = _temperature;
report.error_count = _error_count;
report.x = x * _scale;
report.y = y * _scale;
report.z = z * _scale;
report.timestamp = hrt_absolute_time();
_sensor_pub.publish(report);
}
|
/*
* #%L
* OME-XML C++ library for working with OME-XML metadata structures.
* %%
* Copyright © 2016 Open Microscopy Environment:
* - Massachusetts Institute of Technology
* - National Institutes of Health
* - University of Dundee
* - Board of Regents of the University of Wisconsin-Madison
* - Glencoe Software, 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.
*
* 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 HOLDERS 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.
*
* The views and conclusions contained in the software and documentation are
* those of the authors and should not be interpreted as representing official
* policies, either expressed or implied, of any organization.
* #L%
*/
#include <ome/xml/meta/OMEXMLMetadataModel.h>
using ome::xml::model::OMEModel;
using ome::xml::meta::MetadataModel;
namespace ome
{
namespace xml
{
namespace meta
{
OMEXMLMetadataModel::OMEXMLMetadataModel():
ome::xml::model::OMEModelObject(),
ome::xml::model::OMEModel(),
MetadataModel(),
ome::xml::model::OME()
{
}
OMEXMLMetadataModel::~OMEXMLMetadataModel()
{
}
OMEXMLMetadataModel::OMEXMLMetadataModel(const OMEXMLMetadataModel& copy):
ome::xml::model::OMEModelObject(),
ome::xml::model::OMEModel(),
MetadataModel(),
ome::xml::model::OME(copy)
{
}
OMEXMLMetadataModel::OMEXMLMetadataModel(const ome::xml::model::OME& copy):
ome::xml::model::OMEModelObject(),
ome::xml::model::OMEModel(),
MetadataModel(),
ome::xml::model::OME(copy)
{
}
}
}
}
|
/**************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*************************************************************/
#ifndef SDEXT_PRESENTER_PRESENTER_PAINT_MANAGER_HXX
#define SDEXT_PRESENTER_PRESENTER_PAINT_MANAGER_HXX
#include <com/sun/star/awt/XWindow.hpp>
#include <com/sun/star/awt/XWindowPeer.hpp>
#include <com/sun/star/drawing/XPresenterHelper.hpp>
#include <rtl/ref.hxx>
#include <boost/function.hpp>
namespace css = ::com::sun::star;
namespace sdext { namespace presenter {
class PresenterPaneContainer;
/** Synchronize painting of windows and canvases. At the moment there is
just some processing of invalidate calls.
This could be extended to process incoming windowPaint() calls.
*/
class PresenterPaintManager
{
public:
/** Create paint manager with the window that is the top node in the
local window hierarchy.
*/
PresenterPaintManager (
const css::uno::Reference<css::awt::XWindow>& rxParentWindow,
const css::uno::Reference<css::drawing::XPresenterHelper>& rxPresenterHelper,
const rtl::Reference<PresenterPaneContainer>& rpPaneContainer);
::boost::function<void(const css::awt::Rectangle& rRepaintBox)>
GetInvalidator (
const css::uno::Reference<css::awt::XWindow>& rxWindow,
const bool bSynchronous = false);
/** Request a repaint of the whole window.
@param rxWindow
May be the parent window or one of its descendents.
*/
void Invalidate (
const css::uno::Reference<css::awt::XWindow>& rxWindow,
const bool bSynchronous = false);
void Invalidate (
const css::uno::Reference<css::awt::XWindow>& rxWindow,
const sal_Int16 nInvalidateFlags);
/** Request a repaint of a part of a window.
@param rxWindow
May be the parent window or one of its descendents.
*/
void Invalidate (
const css::uno::Reference<css::awt::XWindow>& rxWindow,
const css::awt::Rectangle& rRepaintBox,
const bool bSynchronous = false);
void Invalidate (
const css::uno::Reference<css::awt::XWindow>& rxWindow,
const css::awt::Rectangle& rRepaintBox,
const sal_Int16 nInvalidateFlags);
private:
css::uno::Reference<css::awt::XWindow> mxParentWindow;
css::uno::Reference<css::awt::XWindowPeer> mxParentWindowPeer;
css::uno::Reference<css::drawing::XPresenterHelper> mxPresenterHelper;
::rtl::Reference<PresenterPaneContainer> mpPaneContainer;
};
} }
#endif
|
#ifndef BOOST_MPL_DEREF_HPP_INCLUDED
#define BOOST_MPL_DEREF_HPP_INCLUDED
// Copyright Aleksey Gurtovoy 2002-2004
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// See http://www.boost.org/libs/mpl for documentation.
// $Id$
// $Date$
// $Revision$
#include <boost/mpl/aux_/msvc_type.hpp>
#include <boost/mpl/aux_/na_spec.hpp>
#include <boost/mpl/aux_/lambda_support.hpp>
#include <boost/mpl/aux_/config/eti.hpp>
namespace bx { namespace mpl {
template<
typename BOOST_MPL_AUX_NA_PARAM(Iterator)
>
struct deref
{
#if !defined(BOOST_MPL_CFG_MSVC_70_ETI_BUG)
typedef typename Iterator::type type;
#else
typedef typename aux::msvc_type<Iterator>::type type;
#endif
BOOST_MPL_AUX_LAMBDA_SUPPORT(1,deref,(Iterator))
};
BOOST_MPL_AUX_NA_SPEC(1, deref)
}}
#endif // BOOST_MPL_DEREF_HPP_INCLUDED
|
/*
* Copyright 2016 Quora, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <algorithm>
#include <random>
#include <qmf/wals/WALSEngine.h>
namespace qmf {
WALSEngine::WALSEngine(const WALSConfig& config,
const std::unique_ptr<MetricsEngine>& metricsEngine,
const size_t nthreads)
: config_(config),
metricsEngine_(metricsEngine),
parallel_(nthreads) {
if (metricsEngine_ && !metricsEngine_->testAvgMetrics().empty() &&
metricsEngine_->config().numTestUsers == 0) {
LOG(WARNING) << "computing average test metrics on all users can be slow! "
"Set numTestUsers > 0 to sample some of them";
}
}
void WALSEngine::init(const std::vector<DatasetElem>& dataset) {
CHECK(!userFactors_ && !itemFactors_)
<< "engine was already initialized with train data";
auto mutableDataset = dataset;
groupSignals(userSignals_, userIndex_, mutableDataset);
// swap userId with itemId
for (auto& elem : mutableDataset) {
std::swap(elem.userId, elem.itemId);
}
groupSignals(itemSignals_, itemIndex_, mutableDataset);
userFactors_ = std::make_unique<FactorData>(nusers(), config_.nfactors);
itemFactors_ = std::make_unique<FactorData>(nitems(), config_.nfactors);
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_real_distribution<Double> distr(
-config_.initDistributionBound, config_.initDistributionBound);
auto genUnif = [&distr, &gen](auto...) { return distr(gen); };
// don't need to initialize user factors
itemFactors_->setFactors(genUnif);
}
void WALSEngine::initTest(const std::vector<DatasetElem>& testDataset) {
CHECK(testUsers_.empty()) << "engine was already initialized with test data";
// initialize data for test average metrics
if (metricsEngine_ && !metricsEngine_->testAvgMetrics().empty()) {
initAvgTestData(
testUsers_, testLabels_, testScores_, testDataset, userIndex_, itemIndex_,
metricsEngine_->config().numTestUsers, metricsEngine_->config().seed);
}
}
void WALSEngine::optimize() {
CHECK(userFactors_ && itemFactors_)
<< "no factor data, have you initialized the engine?";
for (size_t epoch = 1; epoch <= config_.nepochs; ++epoch) {
// fix item factors, update user factors
iterate(*userFactors_, userIndex_, userSignals_, *itemFactors_, itemIndex_);
// fix user factors, update item factors
const Double loss = iterate(*itemFactors_, itemIndex_, itemSignals_, *userFactors_, userIndex_);
LOG(INFO) << "epoch " << epoch << ": train loss = " << loss;
// evaluate
evaluate(epoch);
}
}
void WALSEngine::evaluate(const size_t epoch) {
// evaluate test average metrics
if (metricsEngine_ && !metricsEngine_->testAvgMetrics().empty() &&
!testUsers_.empty() &&
(metricsEngine_->config().alwaysCompute || epoch == config_.nepochs)) {
computeTestScores(
testScores_, testUsers_, *userFactors_, *itemFactors_, parallel_);
metricsEngine_->computeAndRecordTestAvgMetrics(
epoch, testLabels_, testScores_, parallel_);
}
}
void WALSEngine::saveUserFactors(const std::string& fileName) const {
CHECK(userFactors_) << "user factors wasn't initialized";
saveFactors(*userFactors_, userIndex_, fileName);
}
void WALSEngine::saveItemFactors(const std::string& fileName) const {
CHECK(itemFactors_) << "item factors wasn't initialized";
saveFactors(*itemFactors_, itemIndex_, fileName);
}
size_t WALSEngine::nusers() const {
return userIndex_.size();
}
size_t WALSEngine::nitems() const {
return itemIndex_.size();
}
void WALSEngine::groupSignals(std::vector<SignalGroup>& signals,
IdIndex& index,
std::vector<DatasetElem>& dataset) {
sortDataset(dataset);
const int64_t InvalidId = std::numeric_limits<int64_t>::min();
int64_t prevId = InvalidId;
std::vector<Signal> group;
for (const auto& elem : dataset) {
if (elem.userId != prevId) {
if (prevId != InvalidId) {
signals.emplace_back(SignalGroup{prevId, group});
}
prevId = elem.userId;
group.clear();
}
group.emplace_back(Signal{elem.itemId, elem.value});
}
if (prevId != InvalidId) {
signals.emplace_back(SignalGroup{prevId, group});
}
for (size_t i = 0; i < signals.size(); ++i) {
const size_t idx = index.getOrSetIdx(signals[i].sourceId);
CHECK_EQ(idx, i);
}
}
void WALSEngine::sortDataset(std::vector<DatasetElem>& dataset) {
std::sort(dataset.begin(), dataset.end(), [](const auto& x, const auto& y) {
if (x.userId != y.userId) {
return x.userId < y.userId;
}
return x.itemId < y.itemId;
});
}
Double WALSEngine::iterate(FactorData& leftData,
const IdIndex& leftIndex,
const std::vector<SignalGroup>& leftSignals,
const FactorData& rightData,
const IdIndex& rightIndex) {
auto genZero = [](auto...) { return 0.0; };
leftData.setFactors(genZero);
Matrix& X = leftData.getFactors();
const Matrix& Y = rightData.getFactors();
Matrix YtY = computeXtX(Y);
auto map = [
&X,
&leftIndex,
&Y,
&rightIndex,
&leftSignals,
YtY,
alpha = config_.confidenceWeight,
lambda = config_.regularizationLambda
](const size_t taskId) {
return updateFactorsForOne(
X, leftIndex, Y, rightIndex, leftSignals[taskId], YtY, alpha, lambda);
};
auto reduce = [](Double sum, Double x) { return sum + x; };
Double loss = parallel_.mapReduce(leftSignals.size(), map, reduce, 0.0);
return loss / nusers() / nitems();
}
Matrix WALSEngine::computeXtX(const Matrix& X) {
const size_t nrows = X.nrows();
const size_t ntasks = parallel_.nthreads();
const size_t taskSize = (nrows + ntasks - 1) / ntasks;
auto map = [&X, taskSize](const size_t taskId) {
const size_t ncols = X.ncols();
Matrix XtX(ncols, ncols);
const size_t l = taskId * taskSize;
const size_t r = std::min(X.nrows(), (taskId + 1) * taskSize);
for (size_t k = l; k < r; ++k) {
for (size_t i = 0; i < ncols; ++i) {
for (size_t j = 0; j < ncols; ++j) {
XtX(i, j) += X(k, i) * X(k, j);
}
}
}
return XtX;
};
auto reduce = [](const Matrix& S, const Matrix& X) {
return S + X;
};
Matrix O(X.ncols(), X.ncols());
return parallel_.mapReduce(ntasks, map, reduce, O);
}
Double WALSEngine::updateFactorsForOne(Matrix& X,
const IdIndex& leftIndex,
const Matrix& Y,
const IdIndex& rightIndex,
const SignalGroup& signalGroup,
Matrix A,
const Double alpha,
const Double lambda) {
Double loss = 0.0;
const size_t n = X.ncols();
Vector b(n);
for (const auto& signal : signalGroup.group) {
const size_t rightIdx = rightIndex.idx(signal.id);
for (size_t i = 0; i < n; ++i) {
b(i) += Y(rightIdx, i) * (1.0 + alpha * signal.value);
for (size_t j = 0; j < n; ++j) {
A(i, j) += Y(rightIdx, i) * alpha * signal.value * Y(rightIdx, j);
}
}
// for term p^t * C * p
loss += 1.0 + alpha * signal.value;
}
// B = Y^t * C * Y
Matrix B = A;
for (size_t i = 0; i < n; ++i) {
A(i, i) += lambda;
}
// A * x = b
Vector x = linearSymmetricSolve(A, b);
// x^t * Y^t * C * Y * x
for (size_t i = 0; i < n; ++i) {
for (size_t j = 0; j < n; ++j) {
loss += B(i, j) * x(i) * x(j);
}
}
// -2 * x^t * Y^t * C * p
for (size_t i = 0; i < n; ++i) {
loss -= 2 * x(i) * b(i);
}
const size_t leftIdx = leftIndex.idx(signalGroup.sourceId);
for (size_t i = 0; i < n; ++i) {
X(leftIdx, i) = x(i);
}
return loss;
}
}
|
/* Copyright 2016 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow_serving/core/test_util/fake_loader_source_adapter.h"
namespace tensorflow {
namespace serving {
namespace test_util {
FakeLoaderSourceAdapter::FakeLoaderSourceAdapter(
const string& suffix, std::function<void(const string&)> call_on_destruct)
: SimpleLoaderSourceAdapter(
[this](const StoragePath& path,
std::unique_ptr<string>* servable_ptr) {
const string servable = suffix_.length() > 0
? strings::StrCat(path, "/", suffix_)
: path;
servable_ptr->reset(new string(servable));
return Status::OK();
},
SimpleLoaderSourceAdapter<StoragePath,
string>::EstimateNoResources()),
suffix_(suffix),
call_on_destruct_(call_on_destruct) {}
FakeLoaderSourceAdapter::~FakeLoaderSourceAdapter() {
if (call_on_destruct_) {
call_on_destruct_(suffix_);
}
}
std::function<Status(
std::unique_ptr<SourceAdapter<StoragePath, std::unique_ptr<Loader>>>*)>
FakeLoaderSourceAdapter::GetCreator() {
return [](std::unique_ptr<tensorflow::serving::SourceAdapter<
StoragePath, std::unique_ptr<Loader>>>* source) {
source->reset(new FakeLoaderSourceAdapter);
return Status::OK();
};
}
} // namespace test_util
} // namespace serving
} // namespace tensorflow
|
#include "UserFileInput.hpp"
#include "imgui.h"
//--------------------------------------------------------------
UserFileInput::UserFileInput(const std::string& title, const std::string& ext, const std::string& defaultPath)
: _title(title)
, _ext(ext)
, filepath(defaultPath)
{
}
//--------------------------------------------------------------
UserFileInput::~UserFileInput()
{
}
//--------------------------------------------------------------
void UserFileInput::open()
{
requestOpen = true;
}
//--------------------------------------------------------------
void UserFileInput::close()
{
ImGui::CloseCurrentPopup();
}
//--------------------------------------------------------------
void UserFileInput::displayItem(const char* text, UserFileInput::Req req)
{
if(ImGui::MenuItem(text))
{
request = req;
open();
}
}
//--------------------------------------------------------------
void UserFileInput::display()
{
if(requestOpen)
{
ImGui::OpenPopup(_title.c_str());
ImGui::SetNextWindowSize(ImVec2(400, 400));
_explorer.setCurrentPath(filepath);
{
const size_t last_slash_idx = filepath.find_last_of("\\/");
if (std::string::npos != last_slash_idx)
filepath.erase(0, last_slash_idx + 1);
}
strcpy_s(_editBuffer, 512, filepath.c_str());
requestOpen = false;
}
if(!ImGui::BeginPopupModal(_title.c_str()))
return;
if (ImGui::ListBoxHeader("Explorer", ImVec2(0, -100)))
{
if(ImGui::Selectable("##< parent", false))
{
_explorer.goToParentDir();
}
ImGui::SameLine();
ImGui::TextColored(ImVec4(0.7f, 0.7f, 1.f, 1.f), "< parent");
ImGui::Separator();
size_t count = _explorer.getItemCount();
for(size_t i=0; i<count; ++i)
{
auto info = _explorer.getItem(i);
if (info.isRegular && info.ext == _ext)
{
if(ImGui::Selectable(info.name.c_str(), info.name == filepath))
{
filepath = info.name;
strcpy_s(_editBuffer, 512, filepath.c_str());
}
}
else if (info.isDir)
{
std::string folder = std::string("> ") + info.name;
std::string folder_sld = std::string("##") + folder;
if(ImGui::Selectable(folder_sld.c_str(), false))
{
_explorer.goToChildDir(i);
}
ImGui::SameLine();
ImGui::TextColored(ImVec4(0.7f, 0.7f, 1.f, 1.f), folder.c_str());
}
}
ImGui::ListBoxFooter();
}
ImGui::InputText("path", _editBuffer, sizeof(_editBuffer));
ImGui::Columns(2);
if(ImGui::Button("Cancel")) close();
ImGui::NextColumn();
if(ImGui::Button("Confirm"))
{
filepath = _editBuffer;
filepath = _explorer.buildPath(filepath, _ext);
confirmed = true;
close();
}
ImGui::NextColumn();
ImGui::Columns(1);
ImGui::EndPopup();
}
//--------------------------------------------------------------
AboutPanel::AboutPanel()
{
}
//--------------------------------------------------------------
void AboutPanel::open()
{
requestOpen = true;
}
//--------------------------------------------------------------
void AboutPanel::close()
{
ImGui::CloseCurrentPopup();
}
//--------------------------------------------------------------
void AboutPanel::display()
{
if(requestOpen)
{
ImGui::OpenPopup("About");
ImGui::SetNextWindowSize(ImVec2(400, 150));
requestOpen = false;
}
if(!ImGui::BeginPopupModal("About"))
return;
ImGui::Text("QuasarBell");
ImGui::Text("version 3.0");
ImGui::Text("2021 - Mathieu Boulet");
ImGui::Text("sources: https://www.github.com/Lut1n/QuasarBell");
if(ImGui::Button("Okay"))
close();
ImGui::EndPopup();
}
|
// this is for emacs file handling -*- mode: c++; indent-tabs-mode: nil -*-
// -- BEGIN LICENSE BLOCK ----------------------------------------------
/*!
* Copyright (C) 2018, SICK AG, Waldkirch
* Copyright (C) 2018, FZI Forschungszentrum Informatik, Karlsruhe, Germany
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// -- END LICENSE BLOCK ------------------------------------------------
//----------------------------------------------------------------------
/*!
* \file AsyncUDPClient.cpp
*
* \author Lennart Puck <puck@fzi.de>
* \date 2018-09-24
*/
//----------------------------------------------------------------------
#include <sick_safetyscanners/communication/AsyncUDPClient.h>
namespace sick {
namespace communication {
AsyncUDPClient::AsyncUDPClient(const PacketHandler& packet_handler,
boost::asio::io_service& io_service,
const uint16_t& local_port)
: m_packet_handler(packet_handler)
, m_io_service(io_service)
{
// Keep io_service busy
m_io_work_ptr = std::make_shared<boost::asio::io_service::work>(boost::ref(m_io_service));
try
{
m_socket_ptr = std::make_shared<boost::asio::ip::udp::socket>(
boost::ref(m_io_service),
boost::asio::ip::udp::endpoint(boost::asio::ip::udp::v4(), local_port));
}
catch (std::exception& e)
{
ROS_ERROR("Exception while creating socket: %s", e.what());
}
ROS_INFO("UDP client is setup");
}
AsyncUDPClient::~AsyncUDPClient()
{
m_io_service.stop();
}
void AsyncUDPClient::startReceive()
{
m_socket_ptr->async_receive_from(boost::asio::buffer(m_recv_buffer),
m_remote_endpoint,
[this](boost::system::error_code ec, std::size_t bytes_recvd) {
this->handleReceive(ec, bytes_recvd);
});
}
void AsyncUDPClient::handleReceive(const boost::system::error_code& error,
const std::size_t& bytes_transferred)
{
if (!error)
{
sick::datastructure::PacketBuffer packet_buffer(m_recv_buffer, bytes_transferred);
m_packet_handler(packet_buffer);
}
else
{
ROS_ERROR("Error in UDP handle receive: %i", error.value());
}
startReceive();
}
void AsyncUDPClient::runService()
{
startReceive();
}
unsigned short AsyncUDPClient::getLocalPort()
{
if (m_socket_ptr)
{
return m_socket_ptr->local_endpoint().port();
}
return 0;
}
} // namespace communication
} // namespace sick
|
// Copyright 2018,2019,2020,2021 Sony Corporation.
// Copyright 2021 Sony Group Corporation.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <nbla/array.hpp>
#include <nbla/function/batch_normalization.hpp>
#include <nbla/variable.hpp>
#include <algorithm>
#include <cmath>
#include <limits>
namespace nbla {
NBLA_REGISTER_FUNCTION_SOURCE(BatchNormalization, const vector<int> &, float,
float, bool, bool, bool);
template <typename T>
void BatchNormalization<T>::setup_impl(const Variables &inputs,
const Variables &outputs) {
// Check axes
NBLA_CHECK(axes_.size() == 1, error_code::not_implemented,
"Specifying axis more than one is not supported so far.")
// Check num of inputs and outputs.
size_t ninputs = inputs.size();
size_t noutputs = outputs.size();
size_t ninputs_expect = 3;
if (!no_scale_)
ninputs_expect++;
if (!no_bias_)
ninputs_expect++;
NBLA_CHECK(ninputs == ninputs_expect, error_code::value,
"Number of inputs must be 3, 4 or 5.");
if (!batch_stat_) {
NBLA_CHECK(
noutputs == 1, error_code::value,
"If batch_stat_ is false, it cannot output batch mean and variance.");
}
NBLA_CHECK(noutputs == 1 || noutputs == 3, error_code::value,
"Number of outputs must be 1 or 3.");
// calculate parameter index
b_idx_ = no_bias_ ? -1 : 1;
g_idx_ = no_scale_ ? -1 : no_bias_ ? 1 : 2;
m_idx_ = ninputs - 2; // mean
v_idx_ = ninputs - 1; // variance
// Check and parse shapes
Shape_t shape_i = inputs[0]->shape();
Size_t size = inputs[0]->size();
Size_t size_axis = inputs[0]->size(axes_[0]);
size0_ = size / size_axis; // Batch size.
size1_ = shape_i[axes_[0]]; // Size of specified axis.
size2_ = size / size0_ / size1_; // Size of rest.
size12_ = size1_ * size2_;
size02_ = size0_ * size2_;
NBLA_CHECK(size0_ * size1_ * size2_ == size, error_code::unclassified,
"An error occurred during setup BatchNormalization function.");
// Verify mean, var, beta and gamma shapes.
Shape_t shape_check(shape_i.size(), 1);
shape_check[axes_[0]] = shape_i[axes_[0]];
if (!no_bias_) {
Shape_t shape_b = inputs[b_idx_]->shape();
NBLA_CHECK(shape_check == shape_b, error_code::value,
"Shape of beta(inputs[%d]) does not match. "
"beta: (%s) != expected: (%s).",
b_idx_, string_join(shape_b, string(", ")).c_str(),
string_join(shape_check, string(", ")).c_str());
}
if (!no_scale_) {
Shape_t shape_g = inputs[g_idx_]->shape();
NBLA_CHECK(shape_check == shape_g, error_code::value,
"Shape of gamma(inputs[%d]) does not match. "
"gamma: (%s) != expected: (%s).",
g_idx_, string_join(shape_g, string(", ")).c_str(),
string_join(shape_check, string(", ")).c_str());
}
Shape_t shape_m = inputs[m_idx_]->shape();
Shape_t shape_v = inputs[v_idx_]->shape();
NBLA_CHECK(shape_check == shape_m, error_code::value,
"Shape of mean(inputs[%d]) does not match. "
"mean: (%s) != expected: (%s).",
m_idx_, string_join(shape_m, string(", ")).c_str(),
string_join(shape_check, string(", ")).c_str());
NBLA_CHECK(shape_check == shape_v, error_code::value,
"Shape of var(inputs[%d]) does not match. "
"var: (%s) != expected: (%s).",
v_idx_, string_join(shape_v, string(", ")).c_str(),
string_join(shape_check, string(", ")).c_str());
// Reshape outputs and/or temporary buffers.
outputs[0]->reshape(shape_i, true);
if (noutputs == 3) {
outputs[1]->reshape(shape_m, true); // batch mean
outputs[2]->reshape(shape_v, true); // batch var
} else {
mean_.reshape(shape_m, true); // batch mean
var_.reshape(shape_v, true); // batch var
}
// Instantiate functions used for the backward in test mode (batch_stat_ =
// False)
if (!batch_stat_) {
identity_ = create_Identity(this->ctx_);
add2_ = create_Add2(this->ctx_, false);
sub2_ = create_Sub2(this->ctx_, false);
mul2_ = create_Mul2(this->ctx_, false);
add_epsilon_ = create_AddScalar(this->ctx_, (T)this->eps_, false);
square_root_ = create_PowScalar(this->ctx_, (T)-0.5, false);
std::vector<int> raxes;
for (int i = 0; i < inputs[0]->ndim(); ++i) {
if (i != axes_[0])
raxes.push_back(i);
}
sum_ = create_Sum(this->ctx_, raxes, true);
}
}
template <class T>
void BatchNormalization<T>::forward_impl(const Variables &inputs,
const Variables &outputs) {
if (batch_stat_) { // Training mode.
forward_impl_batch(inputs, outputs,
true /* update running mean and variance */);
} else { // Testing mode.
forward_impl_global(inputs, outputs);
}
}
template <class T>
void BatchNormalization<T>::recompute_impl(const Variables &inputs,
const Variables &outputs) {
if (batch_stat_) { // Training mode.
// Prohibit updating running mean and running variance during recomputation
forward_impl_batch(inputs, outputs,
false /* update running mean and variance */);
} else { // Testing mode.
forward_impl_global(inputs, outputs);
}
}
template <class T>
void BatchNormalization<T>::forward_impl_batch(const Variables &inputs,
const Variables &outputs,
const bool update_inputs) {
// Check whether it outputs batch mean and var.
Variable *batch_mean = &mean_;
Variable *batch_var = &var_;
if (outputs.size() == 3) {
batch_mean = outputs[1];
batch_var = outputs[2];
}
// Inputs
const T *x = inputs[0]->get_data_pointer<T>(this->ctx_);
const T *beta =
no_bias_ ? nullptr
: inputs[b_idx_]->template get_data_pointer<T>(this->ctx_);
const T *gamma =
no_scale_ ? nullptr
: inputs[g_idx_]->template get_data_pointer<T>(this->ctx_);
// Output
T *y = outputs[0]->cast_data_and_get_pointer<T>(this->ctx_, true);
T *m =
batch_mean->cast_data_and_get_pointer<T>(this->ctx_, true); // batch mean
T *v =
batch_var->cast_data_and_get_pointer<T>(this->ctx_, true); // batch varf
// Inputs/Outputs
T *rm = inputs[m_idx_]->template cast_data_and_get_pointer<T>(
this->ctx_); // running mean
T *rv = inputs[v_idx_]->template cast_data_and_get_pointer<T>(
this->ctx_); // running var
// Main loop
for (int i1 = 0; i1 < size1_; ++i1) {
// Mean and variance calculation and their moving ones.
// Batch mean and var
m[i1] = 0;
v[i1] = 0;
for (int i02 = 0; i02 < size02_; ++i02) {
const int i0 = i02 / size2_;
const int i2 = i02 % size2_;
const int i = i0 * size12_ + i1 * size2_ + i2;
const T value = x[i];
m[i1] += value;
v[i1] += value * value;
}
m[i1] /= size02_;
v[i1] = v[i1] / size02_ - m[i1] * m[i1];
// Moving mean and var
if (update_inputs) {
rm[i1] = decay_rate_ * rm[i1] + (1 - decay_rate_) * m[i1];
rv[i1] = decay_rate_ * rv[i1] +
(1 - decay_rate_) * v[i1] * size02_ / (size02_ - 1);
}
// v[i1] = 1 / std::sqrt(v[i1] + (T)eps_);
// Subtract mean and divide by std, and apply beta and gamma.
for (int i02 = 0; i02 < size02_; ++i02) {
const int i0 = i02 / size2_;
const int i2 = i02 % size2_;
const int i = i0 * size12_ + i1 * size2_ + i2;
const T stdvar = std::sqrt(v[i1] + (T)eps_);
const auto scale = gamma ? gamma[i1] : (T)1;
const auto bias = beta ? beta[i1] : (T)0;
y[i] = (x[i] - m[i1]) * scale / stdvar + bias;
}
}
}
template <class T>
void BatchNormalization<T>::forward_impl_global(const Variables &inputs,
const Variables &outputs) {
// Inputs
const T *x = inputs[0]->get_data_pointer<T>(this->ctx_);
const T *beta =
no_bias_ ? nullptr
: inputs[b_idx_]->template get_data_pointer<T>(this->ctx_);
const T *gamma =
no_scale_ ? nullptr
: inputs[g_idx_]->template get_data_pointer<T>(this->ctx_);
const T *rm =
inputs[m_idx_]->template get_data_pointer<T>(this->ctx_); // running mean
const T *rv =
inputs[v_idx_]->template get_data_pointer<T>(this->ctx_); // running var
// Output
T *y = outputs[0]->cast_data_and_get_pointer<T>(this->ctx_, true);
#ifdef _OPENMP
#pragma omp parallel for schedule(static)
#endif
// Subtract mean and divide by std, and apply beta and gamma.
for (int i1 = 0; i1 < size1_; ++i1) {
for (int i02 = 0; i02 < size02_; ++i02) {
const int i0 = i02 / size2_;
const int i2 = i02 % size2_;
const int i = i0 * size12_ + i1 * size2_ + i2;
const T mean = rm[i1];
const T stdvar = std::sqrt(rv[i1] + (T)eps_);
const auto scale = gamma ? gamma[i1] : (T)1;
const auto bias = beta ? beta[i1] : (T)0;
y[i] = (x[i] - mean) * scale / stdvar + bias;
}
}
}
template <class T>
void BatchNormalization<T>::backward_impl(const Variables &inputs,
const Variables &outputs,
const vector<bool> &propagate_down,
const vector<bool> &accum) {
if (batch_stat_) { // Training mode.
backward_impl_batch(inputs, outputs, propagate_down, accum);
} else { // Testing mode.
backward_impl_global(inputs, outputs, propagate_down, accum);
}
}
template <class T>
void BatchNormalization<T>::backward_impl_batch(
const Variables &inputs, const Variables &outputs,
const vector<bool> &propagate_down, const vector<bool> &accum) {
if (!(propagate_down[0] || propagate_down[1] || propagate_down[2])) {
return;
}
const bool pd_beta =
!no_bias_ && propagate_down[b_idx_]; // propagate_down beta
const bool pd_gamma =
!no_scale_ && propagate_down[g_idx_]; // propagate_down gamma
// Check whether it outputs batch mean/var.
Variable *batch_mean = &mean_;
Variable *batch_var = &var_;
if (outputs.size() == 3) {
batch_mean = outputs[1];
batch_var = outputs[2];
}
// Common inputs wrt. gradient.
const T *dy = outputs[0]->get_grad_pointer<T>(this->ctx_);
const T *m = batch_mean->get_data_pointer<T>(this->ctx_);
const T *v = batch_var->get_data_pointer<T>(this->ctx_);
const T *x = inputs[0]->get_data_pointer<T>(this->ctx_);
// Gradient wrt. x.
if (propagate_down[0]) {
T *dx = inputs[0]->cast_grad_and_get_pointer<T>(this->ctx_, !accum[0]);
const T *g = no_scale_
? nullptr
: inputs[g_idx_]->template get_data_pointer<T>(this->ctx_);
const T *dm = nullptr;
const T *dv = nullptr;
if (outputs.size() == 3) {
dm = batch_mean->get_grad_pointer<T>(this->ctx_);
dv = batch_var->get_grad_pointer<T>(this->ctx_);
}
for (int i1 = 0; i1 < size1_; ++i1) {
// Compute gradient wrt mean and var respectively
T dvar = 0;
T dmean = 0;
T tmp = 0;
for (int i02 = 0; i02 < size02_; ++i02) {
const int i0 = i02 / size2_;
const int i2 = i02 % size2_;
const int i = i0 * size12_ + i1 * size2_ + i2;
const auto scale = g ? g[i1] : (T)1;
const T dxh = dy[i] * scale; // Grad of x hat.
const T cx = x[i] - m[i1]; // x - mean
dvar += dxh * cx;
dmean += dxh;
tmp += cx;
}
// dm and dv are set if batch mean and var are used following functions
// in computation graph.
dvar = dvar * (T)-0.5 * std::pow(v[i1] + (T)eps_, (T)-1.5) +
(dv ? dv[i1] : (T)0);
dmean = dmean * (-1 / std::sqrt(v[i1] + (T)eps_)) +
dvar * (-2) * tmp / (size02_) + (dm ? dm[i1] : (T)0);
// Compute gradient wrt x.
for (int i02 = 0; i02 < size02_; ++i02) {
const int i0 = i02 / size2_;
const int i2 = i02 % size2_;
const int i = i0 * size12_ + i1 * size2_ + i2;
const auto scale = g ? g[i1] : (T)1;
const T grad = dy[i] * scale / std::sqrt(v[i1] + (T)eps_) +
dvar * 2 * (x[i] - m[i1]) / (size02_) +
dmean / (size02_);
if (accum[0])
dx[i] += grad;
else
dx[i] = grad;
}
}
}
if (pd_beta || pd_gamma) { // beta and gamma
T *db = pd_beta
? inputs[b_idx_]->template cast_grad_and_get_pointer<T>(
this->ctx_, !accum[b_idx_])
: nullptr;
T *dg = pd_gamma
? inputs[g_idx_]->template cast_grad_and_get_pointer<T>(
this->ctx_, !accum[g_idx_])
: nullptr;
const bool b_accum = pd_beta ? accum[b_idx_] : false;
const bool g_accum = pd_gamma ? accum[g_idx_] : false;
for (int i1 = 0; i1 < size1_; ++i1) {
T dbv = b_accum ? db[i1] : (T)0;
T dgv = g_accum ? dg[i1] : (T)0;
for (int i02 = 0; i02 < size02_; ++i02) {
const int i0 = i02 / size2_;
const int i2 = i02 % size2_;
const int i = i0 * size12_ + i1 * size2_ + i2;
if (db)
dbv += dy[i];
if (dg)
dgv += dy[i] * (x[i] - m[i1]) / std::sqrt(v[i1] + (T)eps_);
}
if (db)
db[i1] = dbv;
if (dg)
dg[i1] = dgv;
}
}
}
template <class T>
void BatchNormalization<T>::backward_impl_global(
const Variables &inputs, const Variables &outputs,
const vector<bool> &propagate_down, const vector<bool> &accum) {
if (!(propagate_down[0] || propagate_down[1] || propagate_down[2])) {
return;
}
const bool pd_beta =
!no_bias_ && propagate_down[b_idx_]; // propagate_down beta
const bool pd_gamma =
!no_scale_ && propagate_down[g_idx_]; // propagate_down gamma
// Common inputs wrt. gradient.
auto x = inputs[0];
auto beta = no_bias_ ? nullptr : inputs[b_idx_];
auto gamma = no_scale_ ? nullptr : inputs[g_idx_];
auto rmean = inputs[m_idx_];
auto rvar = inputs[v_idx_];
auto y = outputs[0];
// Running std
shared_ptr<Variable> rstd_inv_sptr;
shared_ptr<Variable> g_y_sptr;
// running std
rstd_inv_sptr = make_shared<Variable>(rvar->shape());
auto rstd_inv = rstd_inv_sptr.get();
execute(identity_, Variables{rvar}, Variables{rstd_inv});
execute(add_epsilon_, Variables{rstd_inv}, Variables{rstd_inv});
execute(square_root_, Variables{rstd_inv}, Variables{rstd_inv});
// g_y variable
g_y_sptr = make_shared<Variable>(y->shape());
g_y_sptr->set_data(y->grad());
// Gradient wrt. x.
if (propagate_down[0]) {
// gamma / rstd
const auto param_shape = rmean->shape();
shared_ptr<Variable> iv_sptr = make_shared<Variable>(param_shape);
auto rstd_inv = rstd_inv_sptr.get();
auto iv = rstd_inv;
if (!no_scale_) {
iv = iv_sptr.get();
execute(mul2_, Variables{gamma, rstd_inv}, Variables{iv});
}
// g_y * gamma / rstd
auto g_x_tmp_sptr = make_shared<Variable>(x->shape());
auto g_y = g_y_sptr.get();
auto g_x_tmp = g_x_tmp_sptr.get();
mul2_ = create_Mul2(this->ctx_, false);
execute(mul2_, Variables{g_y, iv}, Variables{g_x_tmp});
// accum
auto g_x_sptr = make_shared<Variable>(x->shape());
g_x_sptr->set_data(x->grad());
auto g_x = g_x_sptr.get();
if (accum[0]) {
execute(add2_, Variables{g_x, g_x_tmp}, Variables{g_x});
} else {
execute(identity_, Variables{g_x_tmp}, Variables{g_x});
}
}
// Gradient wrt. beta and gamma.
if (pd_beta || pd_gamma) { // beta and gamma
auto g_y = g_y_sptr.get();
// 1. beta
if (pd_beta) {
auto g_beta_tmp_sptr = make_shared<Variable>(beta->shape());
auto g_beta_tmp = g_beta_tmp_sptr.get();
execute(sum_, Variables{g_y}, Variables{g_beta_tmp});
auto g_beta_sptr = make_shared<Variable>(beta->shape());
g_beta_sptr->set_data(beta->grad());
auto g_beta = g_beta_sptr.get();
if (accum[b_idx_]) {
execute(add2_, Variables{g_beta, g_beta_tmp}, Variables{g_beta});
} else {
execute(identity_, Variables{g_beta_tmp}, Variables{g_beta});
}
}
// 2. gamma
if (pd_gamma) {
// (x - rmean) / rstd
auto iv_sptr = make_shared<Variable>(x->shape());
auto iv = iv_sptr.get();
execute(sub2_, Variables{x, rmean}, Variables{iv});
auto rstd_inv = rstd_inv_sptr.get();
execute(mul2_, Variables{iv, rstd_inv}, Variables{iv});
// g_y * (x - rmean) / rstd
mul2_ = create_Mul2(this->ctx_, false);
execute(mul2_, Variables{g_y, iv}, Variables{iv});
// reduction
auto g_gamma_tmp_sptr = make_shared<Variable>(gamma->shape());
auto g_gamma_tmp = g_gamma_tmp_sptr.get();
execute(sum_, Variables{iv}, Variables{g_gamma_tmp});
auto g_gamma_sptr = make_shared<Variable>(gamma->shape());
g_gamma_sptr->set_data(gamma->grad());
auto g_gamma = g_gamma_sptr.get();
if (accum[g_idx_]) {
execute(add2_, Variables{g_gamma, g_gamma_tmp}, Variables{g_gamma});
} else {
execute(identity_, Variables{g_gamma_tmp}, Variables{g_gamma});
}
}
}
}
}
|
/****************************************************************************
*
* Copyright (c) 2012-2015 PX4 Development Team. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name PX4 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.
*
****************************************************************************/
/**
* @file param.cpp
* @author Lorenz Meier <lorenz@px4.io>
* @author Andreas Antener <andreas@uaventure.com>
*
* Parameter tool.
*/
#include <px4_config.h>
#include <px4_log.h>
#include <px4_module.h>
#include <px4_posix.h>
#include <errno.h>
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <unistd.h>
#include <fcntl.h>
#include <math.h>
#include <inttypes.h>
#include <sys/stat.h>
#include <arch/board/board.h>
#include <parameters/param.h>
#include "systemlib/err.h"
__BEGIN_DECLS
__EXPORT int param_main(int argc, char *argv[]);
__END_DECLS
enum COMPARE_OPERATOR {
COMPARE_OPERATOR_EQUAL = 0,
COMPARE_OPERATOR_GREATER = 1,
};
#ifdef __PX4_QURT
#define PARAM_PRINT PX4_INFO
#else
#define PARAM_PRINT PX4_INFO_RAW
#endif
static int do_save(const char *param_file_name);
static int do_save_default();
static int do_load(const char *param_file_name);
static int do_import(const char *param_file_name);
static int do_show(const char *search_string, bool only_changed);
static int do_show_all();
static int do_show_quiet(const char *param_name);
static int do_show_index(const char *index, bool used_index);
static void do_show_print(void *arg, param_t param);
static int do_set(const char *name, const char *val, bool fail_on_not_found);
static int do_compare(const char *name, char *vals[], unsigned comparisons, enum COMPARE_OPERATOR cmd_op);
static int do_reset(const char *excludes[], int num_excludes);
static int do_touch(const char *params[], int num_params);
static int do_reset_nostart(const char *excludes[], int num_excludes);
static int do_find(const char *name);
static void print_usage()
{
PRINT_MODULE_DESCRIPTION(
R"DESCR_STR(
### Description
Command to access and manipulate parameters via shell or script.
This is used for example in the startup script to set airframe-specific parameters.
Parameters are automatically saved when changed, eg. with `param set`. They are typically stored to FRAM
or to the SD card. `param select` can be used to change the storage location for subsequent saves (this will
need to be (re-)configured on every boot).
If the FLASH-based backend is enabled (which is done at compile time, e.g. for the Intel Aero or Omnibus),
`param select` has no effect and the default is always the FLASH backend. However `param save/load <file>`
can still be used to write to/read from files.
Each parameter has a 'used' flag, which is set when it's read during boot. It is used to only show relevant
parameters to a ground control station.
### Examples
Change the airframe and make sure the airframe's default parameters are loaded:
$ param set SYS_AUTOSTART 4001
$ param set SYS_AUTOCONFIG 1
$ reboot
)DESCR_STR");
PRINT_MODULE_USAGE_NAME("param", "command");
PRINT_MODULE_USAGE_COMMAND_DESCR("load", "Load params from a file (overwrite all)");
PRINT_MODULE_USAGE_ARG("<file>", "File name (use default if not given)", true);
PRINT_MODULE_USAGE_COMMAND_DESCR("import", "Import params from a file");
PRINT_MODULE_USAGE_ARG("<file>", "File name (use default if not given)", true);
PRINT_MODULE_USAGE_COMMAND_DESCR("save", "Save params to a file");
PRINT_MODULE_USAGE_ARG("<file>", "File name (use default if not given)", true);
PRINT_MODULE_USAGE_COMMAND_DESCR("select", "Select default file");
PRINT_MODULE_USAGE_ARG("<file>", "File name (use <root>/eeprom/parameters if not given)", true);
PRINT_MODULE_USAGE_COMMAND_DESCR("show", "Show parameter values");
PRINT_MODULE_USAGE_PARAM_FLAG('a', "Show all parameters (not just used)", true);
PRINT_MODULE_USAGE_PARAM_FLAG('c', "Show only changed and used params", true);
PRINT_MODULE_USAGE_PARAM_FLAG('q', "quiet mode, print only param value (name needs to be exact)", true);
PRINT_MODULE_USAGE_ARG("<filter>", "Filter by param name (wildcard at end allowed, eg. sys_*)", true);
PRINT_MODULE_USAGE_COMMAND_DESCR("status", "Print status of parameter system");
PRINT_MODULE_USAGE_COMMAND_DESCR("set", "Set parameter to a value");
PRINT_MODULE_USAGE_ARG("<param_name> <value>", "Parameter name and value to set", false);
PRINT_MODULE_USAGE_ARG("fail", "If provided, let the command fail if param is not found", true);
PRINT_MODULE_USAGE_COMMAND_DESCR("compare", "Compare a param with a value. Command will succeed if equal");
PRINT_MODULE_USAGE_ARG("<param_name> <value>", "Parameter name and value to compare", false);
PRINT_MODULE_USAGE_COMMAND_DESCR("greater",
"Compare a param with a value. Command will succeed if param is greater than the value");
PRINT_MODULE_USAGE_ARG("<param_name> <value>", "Parameter name and value to compare", false);
PRINT_MODULE_USAGE_COMMAND_DESCR("touch", "Mark a parameter as used");
PRINT_MODULE_USAGE_ARG("<param_name1> [<param_name2>]", "Parameter name (one or more)", true);
PRINT_MODULE_USAGE_COMMAND_DESCR("reset", "Reset params to default");
PRINT_MODULE_USAGE_ARG("<exclude1> [<exclude2>]", "Do not reset matching params (wildcard at end allowed)", true);
PRINT_MODULE_USAGE_COMMAND_DESCR("reset_nostart",
"Reset params to default, but keep SYS_AUTOSTART and SYS_AUTOCONFIG");
PRINT_MODULE_USAGE_ARG("<exclude1> [<exclude2>]", "Do not reset matching params (wildcard at end allowed)", true);
PRINT_MODULE_USAGE_COMMAND_DESCR("index", "Show param for a given index");
PRINT_MODULE_USAGE_ARG("<index>", "Index: an integer >= 0", false);
PRINT_MODULE_USAGE_COMMAND_DESCR("index_used", "Show used param for a given index");
PRINT_MODULE_USAGE_ARG("<index>", "Index: an integer >= 0", false);
PRINT_MODULE_USAGE_COMMAND_DESCR("find", "Show index of a param");
PRINT_MODULE_USAGE_ARG("<param>", "param name", false);
}
int
param_main(int argc, char *argv[])
{
if (argc >= 2) {
if (!strcmp(argv[1], "save")) {
if (argc >= 3) {
return do_save(argv[2]);
} else {
int ret = do_save_default();
if (ret) {
PX4_ERR("Param save failed (%i)", ret);
return 1;
} else {
return 0;
}
}
}
if (!strcmp(argv[1], "load")) {
if (argc >= 3) {
return do_load(argv[2]);
} else {
return do_load(param_get_default_file());
}
}
if (!strcmp(argv[1], "import")) {
if (argc >= 3) {
return do_import(argv[2]);
} else {
return do_import(param_get_default_file());
}
}
if (!strcmp(argv[1], "select")) {
if (argc >= 3) {
param_set_default_file(argv[2]);
} else {
param_set_default_file(nullptr);
}
const char *default_file = param_get_default_file();
if (default_file) {
PX4_INFO("selected parameter default file %s", default_file);
}
return 0;
}
if (!strcmp(argv[1], "show")) {
if (argc >= 3) {
// optional argument -c to show only non-default params
if (!strcmp(argv[2], "-c")) {
if (argc >= 4) {
return do_show(argv[3], true);
} else {
return do_show(nullptr, true);
}
} else if (!strcmp(argv[2], "-a")) {
return do_show_all();
} else if (!strcmp(argv[2], "-q")) {
if (argc >= 4) {
return do_show_quiet(argv[3]);
}
} else {
return do_show(argv[2], false);
}
} else {
return do_show(nullptr, false);
}
}
if (!strcmp(argv[1], "status")) {
param_print_status();
return PX4_OK;
}
if (!strcmp(argv[1], "set")) {
if (argc >= 5) {
/* if the fail switch is provided, fails the command if not found */
bool fail = !strcmp(argv[4], "fail");
return do_set(argv[2], argv[3], fail);
} else if (argc >= 4) {
return do_set(argv[2], argv[3], false);
} else {
PX4_ERR("not enough arguments.\nTry 'param set PARAM_NAME 3 [fail]'");
return 1;
}
}
if (!strcmp(argv[1], "compare")) {
if (argc >= 4) {
return do_compare(argv[2], &argv[3], argc - 3, COMPARE_OPERATOR_EQUAL);
} else {
PX4_ERR("not enough arguments.\nTry 'param compare PARAM_NAME 3'");
return 1;
}
}
if (!strcmp(argv[1], "greater")) {
if (argc >= 4) {
return do_compare(argv[2], &argv[3], argc - 3, COMPARE_OPERATOR_GREATER);
} else {
PX4_ERR("not enough arguments.\nTry 'param greater PARAM_NAME 3'");
return 1;
}
}
if (!strcmp(argv[1], "reset")) {
if (argc >= 3) {
return do_reset((const char **) &argv[2], argc - 2);
} else {
return do_reset(nullptr, 0);
}
}
if (!strcmp(argv[1], "touch")) {
if (argc >= 3) {
return do_touch((const char **) &argv[2], argc - 2);
} else {
PX4_ERR("not enough arguments.");
return 1;
}
}
if (!strcmp(argv[1], "reset_nostart")) {
if (argc >= 3) {
return do_reset_nostart((const char **) &argv[2], argc - 2);
} else {
return do_reset_nostart(nullptr, 0);
}
}
if (!strcmp(argv[1], "index_used")) {
if (argc >= 3) {
return do_show_index(argv[2], true);
} else {
PX4_ERR("no index provided");
return 1;
}
}
if (!strcmp(argv[1], "index")) {
if (argc >= 3) {
return do_show_index(argv[2], false);
} else {
PX4_ERR("no index provided");
return 1;
}
}
if (!strcmp(argv[1], "find")) {
if (argc >= 3) {
return do_find(argv[2]);
} else {
PX4_ERR("not enough arguments.\nTry 'param find PARAM_NAME'");
return 1;
}
}
}
print_usage();
return 1;
}
static int
do_save(const char *param_file_name)
{
/* create the file */
int fd = open(param_file_name, O_WRONLY | O_CREAT, PX4_O_MODE_666);
if (fd < 0) {
PX4_ERR("open '%s' failed (%i)", param_file_name, errno);
return 1;
}
int result = param_export(fd, false);
close(fd);
if (result < 0) {
#ifndef __PX4_QURT
(void)unlink(param_file_name);
#endif
PX4_ERR("exporting to '%s' failed (%i)", param_file_name, result);
return 1;
}
return 0;
}
static int
do_load(const char *param_file_name)
{
int fd = -1;
if (param_file_name) { // passing NULL means to select the flash storage
fd = open(param_file_name, O_RDONLY);
if (fd < 0) {
PX4_ERR("open '%s' failed (%i)", param_file_name, errno);
return 1;
}
}
int result = param_load(fd);
if (fd >= 0) {
close(fd);
}
if (result < 0) {
PX4_ERR("importing from '%s' failed (%i)", param_file_name, result);
return 1;
}
return 0;
}
static int
do_import(const char *param_file_name)
{
int fd = -1;
if (param_file_name) { // passing NULL means to select the flash storage
fd = open(param_file_name, O_RDONLY);
if (fd < 0) {
PX4_ERR("open '%s' failed (%i)", param_file_name, errno);
return 1;
}
}
int result = param_import(fd);
if (fd >= 0) {
close(fd);
}
if (result < 0) {
PX4_ERR("importing from '%s' failed (%i)", param_file_name, result);
return 1;
}
return 0;
}
static int
do_save_default()
{
return param_save_default();
}
static int
do_show(const char *search_string, bool only_changed)
{
PARAM_PRINT("Symbols: x = used, + = saved, * = unsaved\n");
param_foreach(do_show_print, (char *)search_string, only_changed, true);
PARAM_PRINT("\n %u/%u parameters used.\n", param_count_used(), param_count());
return 0;
}
static int
do_show_all()
{
PARAM_PRINT("Symbols: x = used, + = saved, * = unsaved\n");
param_foreach(do_show_print, nullptr, false, false);
PARAM_PRINT("\n %u parameters total, %u used.\n", param_count(), param_count_used());
return 0;
}
static int
do_show_quiet(const char *param_name)
{
param_t param = param_find_no_notification(param_name);
int32_t ii;
float ff;
// Print only the param value (can be used in scripts)
if (param == PARAM_INVALID) {
return 1;
}
switch (param_type(param)) {
case PARAM_TYPE_INT32:
if (!param_get(param, &ii)) {
PARAM_PRINT("%ld", (long)ii);
}
break;
case PARAM_TYPE_FLOAT:
if (!param_get(param, &ff)) {
PARAM_PRINT("%4.4f", (double)ff);
}
break;
default:
return 1;
}
return 0;
}
static int
do_find(const char *name)
{
param_t ret = param_find_no_notification(name);
if (ret == PARAM_INVALID) {
PX4_ERR("Parameter %s not found", name);
return 1;
}
PARAM_PRINT("Found param %s at index %i\n", name, (int)ret);
return 0;
}
static int
do_show_index(const char *index, bool used_index)
{
char *end;
int i = strtol(index, &end, 10);
param_t param;
int32_t ii;
float ff;
if (used_index) {
param = param_for_used_index(i);
} else {
param = param_for_index(i);
}
if (param == PARAM_INVALID) {
PX4_ERR("param not found for index %u", i);
return 1;
}
PARAM_PRINT("index %d: %c %c %s [%d,%d] : ", i, (param_used(param) ? 'x' : ' '),
param_value_unsaved(param) ? '*' : (param_value_is_default(param) ? ' ' : '+'),
param_name(param), param_get_used_index(param), param_get_index(param));
switch (param_type(param)) {
case PARAM_TYPE_INT32:
if (!param_get(param, &ii)) {
PARAM_PRINT("%ld\n", (long)ii);
}
break;
case PARAM_TYPE_FLOAT:
if (!param_get(param, &ff)) {
PARAM_PRINT("%4.4f\n", (double)ff);
}
break;
default:
PARAM_PRINT("<unknown type %d>\n", 0 + param_type(param));
}
return 0;
}
static void
do_show_print(void *arg, param_t param)
{
int32_t i;
float f;
const char *search_string = (const char *)arg;
const char *p_name = (const char *)param_name(param);
/* print nothing if search string is invalid and not matching */
if (!(arg == nullptr)) {
/* start search */
const char *ss = search_string;
const char *pp = p_name;
/* XXX this comparison is only ok for trailing wildcards */
while (*ss != '\0' && *pp != '\0') {
// case insensitive comparison (param_name is always upper case)
if (toupper(*ss) == *pp) {
ss++;
pp++;
} else if (*ss == '*') {
if (*(ss + 1) != '\0') {
PX4_WARN("* symbol only allowed at end of search string");
// FIXME - should exit
return;
}
pp++;
} else {
/* param not found */
return;
}
}
/* the search string must have been consumed */
if (!(*ss == '\0' || *ss == '*') || *pp != '\0') {
return;
}
}
PARAM_PRINT("%c %c %s [%d,%d] : ", (param_used(param) ? 'x' : ' '),
param_value_unsaved(param) ? '*' : (param_value_is_default(param) ? ' ' : '+'),
param_name(param), param_get_used_index(param), param_get_index(param));
/*
* This case can be expanded to handle printing common structure types.
*/
switch (param_type(param)) {
case PARAM_TYPE_INT32:
if (!param_get(param, &i)) {
PARAM_PRINT("%ld\n", (long)i);
return;
}
break;
case PARAM_TYPE_FLOAT:
if (!param_get(param, &f)) {
PARAM_PRINT("%4.4f\n", (double)f);
return;
}
break;
case PARAM_TYPE_STRUCT ... PARAM_TYPE_STRUCT_MAX:
PARAM_PRINT("<struct type %d size %zu>\n", 0 + param_type(param), param_size(param));
return;
default:
PARAM_PRINT("<unknown type %d>\n", 0 + param_type(param));
return;
}
PARAM_PRINT("<error fetching parameter %lu>\n", (unsigned long)param);
}
static int
do_set(const char *name, const char *val, bool fail_on_not_found)
{
int32_t i;
float f;
param_t param = param_find(name);
/* set nothing if parameter cannot be found */
if (param == PARAM_INVALID) {
/* param not found - fail silenty in scripts as it prevents booting */
PX4_ERR("Parameter %s not found.", name);
return (fail_on_not_found) ? 1 : 0;
}
/*
* Set parameter if type is known and conversion from string to value turns out fine
*/
switch (param_type(param)) {
case PARAM_TYPE_INT32:
if (!param_get(param, &i)) {
/* convert string */
char *end;
int32_t newval = strtol(val, &end, 10);
if (i != newval) {
PARAM_PRINT("%c %s: ",
param_value_unsaved(param) ? '*' : (param_value_is_default(param) ? ' ' : '+'),
param_name(param));
PARAM_PRINT("curr: %ld", (long)i);
param_set(param, &newval);
PARAM_PRINT(" -> new: %ld\n", (long)newval);
}
}
break;
case PARAM_TYPE_FLOAT:
if (!param_get(param, &f)) {
/* convert string */
char *end;
float newval = strtod(val, &end);
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wfloat-equal"
if (f != newval) {
#pragma GCC diagnostic pop
PARAM_PRINT("%c %s: ",
param_value_unsaved(param) ? '*' : (param_value_is_default(param) ? ' ' : '+'),
param_name(param));
PARAM_PRINT("curr: %4.4f", (double)f);
param_set(param, &newval);
PARAM_PRINT(" -> new: %4.4f\n", (double)newval);
}
}
break;
default:
PX4_ERR("<unknown / unsupported type %d>\n", 0 + param_type(param));
return 1;
}
return 0;
}
static int
do_compare(const char *name, char *vals[], unsigned comparisons, enum COMPARE_OPERATOR cmp_op)
{
int32_t i;
float f;
param_t param = param_find(name);
/* set nothing if parameter cannot be found */
if (param == PARAM_INVALID) {
/* param not found */
PX4_DEBUG("Parameter %s not found", name);
return 1;
}
/*
* Set parameter if type is known and conversion from string to value turns out fine
*/
int ret = 1;
switch (param_type(param)) {
case PARAM_TYPE_INT32:
if (!param_get(param, &i)) {
/* convert string */
char *end;
for (unsigned k = 0; k < comparisons; k++) {
int j = strtol(vals[k], &end, 10);
if (((cmp_op == COMPARE_OPERATOR_EQUAL) && (i == j)) ||
((cmp_op == COMPARE_OPERATOR_GREATER) && (i > j))) {
PX4_DEBUG(" %ld: ", (long)i);
ret = 0;
}
}
}
break;
case PARAM_TYPE_FLOAT:
if (!param_get(param, &f)) {
/* convert string */
char *end;
for (unsigned k = 0; k < comparisons; k++) {
float g = strtod(vals[k], &end);
if (((cmp_op == COMPARE_OPERATOR_EQUAL) && (fabsf(f - g) < 1e-7f)) ||
((cmp_op == COMPARE_OPERATOR_GREATER) && (f > g))) {
PX4_DEBUG(" %4.4f: ", (double)f);
ret = 0;
}
}
}
break;
default:
PX4_ERR("<unknown / unsupported type %d>", 0 + param_type(param));
return 1;
}
if (ret == 0) {
PX4_DEBUG("%c %s: match\n",
param_value_unsaved(param) ? '*' : (param_value_is_default(param) ? ' ' : '+'),
param_name(param));
}
return ret;
}
static int
do_reset(const char *excludes[], int num_excludes)
{
if (num_excludes > 0) {
param_reset_excludes(excludes, num_excludes);
} else {
param_reset_all();
}
return 0;
}
static int
do_touch(const char *params[], int num_params)
{
for (int i = 0; i < num_params; ++i) {
if (param_find(params[i]) == PARAM_INVALID) {
PX4_ERR("param %s not found", params[i]);
}
}
return 0;
}
static int
do_reset_nostart(const char *excludes[], int num_excludes)
{
int32_t autostart;
int32_t autoconfig;
(void)param_get(param_find("SYS_AUTOSTART"), &autostart);
(void)param_get(param_find("SYS_AUTOCONFIG"), &autoconfig);
if (num_excludes > 0) {
param_reset_excludes(excludes, num_excludes);
} else {
param_reset_all();
}
(void)param_set(param_find("SYS_AUTOSTART"), &autostart);
(void)param_set(param_find("SYS_AUTOCONFIG"), &autoconfig);
return 0;
}
|
// Copyright (c) 2009-2010 Satoshi Nakamoto
// 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 "txdb.h"
#include "wallet.h"
#include "walletdb.h"
#include "bloom.h"
#include "crypter.h"
#include "ui_interface.h"
#include "base58.h"
#include "kernel.h"
#include "coincontrol.h"
#include "pbkdf2.h"
#include <boost/algorithm/string/replace.hpp>
using namespace std;
//////////////////////////////////////////////////////////////////////////////
//
// mapWallet
//
struct CompareValueOnly
{
bool operator()(const pair<int64_t, pair<const CWalletTx*, unsigned int> >& t1,
const pair<int64_t, pair<const CWalletTx*, unsigned int> >& t2) const
{
return t1.first < t2.first;
}
};
CPubKey CWallet::GenerateNewKey()
{
//assert(false); // [rm] replace with HD - needed for NewKeyPool from EncryptWallet
//LogPrintf("[rm] GenerateNewKey()\n");
AssertLockHeld(cs_wallet); // mapKeyMetadata
bool fCompressed = CanSupportFeature(FEATURE_COMPRPUBKEY); // default to compressed public keys if we want 0.6.0 wallets
RandAddSeedPerfmon();
CKey secret;
secret.MakeNewKey(fCompressed);
// Compressed public keys were introduced in version 0.6.0
if (fCompressed)
SetMinVersion(FEATURE_COMPRPUBKEY);
CPubKey pubkey = secret.GetPubKey();
// Create new metadata
int64_t nCreationTime = GetTime();
mapKeyMetadata[pubkey.GetID()] = CKeyMetadata(nCreationTime);
if (!nTimeFirstKey || nCreationTime < nTimeFirstKey)
nTimeFirstKey = nCreationTime;
if (!AddKeyPubKey(secret, pubkey))
throw std::runtime_error("CWallet::GenerateNewKey() : AddKeyPubKey failed");
return pubkey;
}
bool CWallet::AddKey(const CKey &secret)
{
return CWallet::AddKeyPubKey(secret, secret.GetPubKey());
}
bool CWallet::AddKeyPubKey(const CKey &secret, const CPubKey &pubkey)
{
AssertLockHeld(cs_wallet); // mapKeyMetadata
if (!CCryptoKeyStore::AddKeyPubKey(secret, pubkey))
return false;
if (!fFileBacked)
return true;
if (!IsCrypted()) {
return CWalletDB(strWalletFile).WriteKey(pubkey, secret.GetPrivKey(), mapKeyMetadata[pubkey.GetID()]);
}
return true;
}
int CWallet::Finalise()
{
SetBestChain(CBlockLocator(pindexBest));
ExtKeyAccountMap::iterator it = mapExtAccounts.begin();
for (it = mapExtAccounts.begin(); it != mapExtAccounts.end(); ++it)
if (it->second)
delete it->second;
ExtKeyMap::iterator itl = mapExtKeys.begin();
for (itl = mapExtKeys.begin(); itl != mapExtKeys.end(); ++itl)
if (itl->second)
delete itl->second;
if (pBloomFilter)
{
delete pBloomFilter;
if (fDebug)
LogPrintf("Bloom filter destructed.\n");
};
return 0;
};
bool CWallet::AddKeyInDBTxn(CWalletDB *pdb, const CKey &key)
{
LOCK(cs_KeyStore);
// -- can't use CWallet::AddKey(), as in a db transaction
// hack: pwalletdbEncryption CCryptoKeyStore::AddKey calls CWallet::AddCryptedKey
// DB Write() uses activeTxn
CWalletDB *pwalletdbEncryptionOld = pwalletdbEncryption;
pwalletdbEncryption = pdb;
CPubKey pubkey = key.GetPubKey();
bool rv = CCryptoKeyStore::AddKeyPubKey(key, pubkey);
pwalletdbEncryption = pwalletdbEncryptionOld;
if (!rv)
{
LogPrintf("CCryptoKeyStore::AddKeyPubKey failed.\n");
return false;
};
if (fFileBacked
&& !IsCrypted())
{
if (!pdb->WriteKey(pubkey, key.GetPrivKey(), mapKeyMetadata[pubkey.GetID()]))
{
LogPrintf("WriteKey() failed.\n");
return false;
};
};
return true;
};
bool CWallet::AddCryptedKey(const CPubKey &vchPubKey, const vector<unsigned char> &vchCryptedSecret)
{
if (!CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret))
return false;
if (!fFileBacked)
return true;
{
LOCK(cs_wallet);
if (pwalletdbEncryption)
return pwalletdbEncryption->WriteCryptedKey(vchPubKey, vchCryptedSecret, mapKeyMetadata[vchPubKey.GetID()]);
else
return CWalletDB(strWalletFile).WriteCryptedKey(vchPubKey, vchCryptedSecret, mapKeyMetadata[vchPubKey.GetID()]);
}
return false;
}
bool CWallet::LoadKeyMetadata(const CPubKey &pubkey, const CKeyMetadata &meta)
{
AssertLockHeld(cs_wallet); // mapKeyMetadata
if (meta.nCreateTime && (!nTimeFirstKey || meta.nCreateTime < nTimeFirstKey))
nTimeFirstKey = meta.nCreateTime;
mapKeyMetadata[pubkey.GetID()] = meta;
return true;
}
bool CWallet::LoadCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret)
{
return CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret);
}
bool CWallet::AddCScript(const CScript& redeemScript)
{
if (!CCryptoKeyStore::AddCScript(redeemScript))
return false;
if (!fFileBacked)
return true;
return CWalletDB(strWalletFile).WriteCScript(Hash160(redeemScript), redeemScript);
}
// optional setting to unlock wallet for staking only
// serves to disable the trivial sendmoney when OS account compromised
// provides no real security
bool fWalletUnlockStakingOnly = false;
bool fWalletUnlockMessagingEnabled = false;
bool CWallet::LoadCScript(const CScript& redeemScript)
{
/* A sanity check was added in pull #3843 to avoid adding redeemScripts
* that never can be redeemed. However, old wallets may still contain
* these. Do not add them to the wallet and warn. */
if (redeemScript.size() > MAX_SCRIPT_ELEMENT_SIZE)
{
std::string strAddr = CBitcoinAddress(redeemScript.GetID()).ToString();
LogPrintf("%s: Warning: This wallet contains a redeemScript of size %u which exceeds maximum size %i thus can never be redeemed. Do not use address %s.\n",
__func__, redeemScript.size(), MAX_SCRIPT_ELEMENT_SIZE, strAddr.c_str());
return true;
};
return CCryptoKeyStore::AddCScript(redeemScript);
}
bool CWallet::Lock()
{
if (fDebug)
LogPrintf("CWallet::Lock()\n");
if (IsLocked())
return true;
LogPrintf("Locking wallet.\n");
{
LOCK(cs_wallet);
CWalletDB wdb(strWalletFile);
// -- load encrypted spend_secret of stealth addresses
CStealthAddress sxAddrTemp;
std::set<CStealthAddress>::iterator it;
for (it = stealthAddresses.begin(); it != stealthAddresses.end(); ++it)
{
if (it->scan_secret.size() < 32)
continue; // stealth address is not owned
// -- CStealthAddress are only sorted on spend_pubkey
CStealthAddress &sxAddr = const_cast<CStealthAddress&>(*it);
if (fDebug)
LogPrintf("Recrypting stealth key %s\n", sxAddr.Encoded().c_str());
sxAddrTemp.scan_pubkey = sxAddr.scan_pubkey;
if (!wdb.ReadStealthAddress(sxAddrTemp))
{
LogPrintf("Error: Failed to read stealth key from db %s\n", sxAddr.Encoded().c_str());
continue;
}
sxAddr.spend_secret = sxAddrTemp.spend_secret;
};
ExtKeyLock();
}
return LockKeyStore();
};
bool CWallet::Unlock(const SecureString& strWalletPassphrase)
{
if (fDebug)
LogPrintf("CWallet::Unlock()\n");
if (!IsLocked()
|| !IsCrypted())
return false;
CCrypter crypter;
CKeyingMaterial vMasterKey;
LogPrintf("Unlocking wallet.\n");
{
LOCK2(cs_main, cs_wallet);
BOOST_FOREACH(const MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
{
if (!crypter.SetKeyFromPassphrase(strWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
return false;
if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
return false;
if (!CCryptoKeyStore::Unlock(vMasterKey))
return false;
break;
};
UnlockStealthAddresses(vMasterKey);
ExtKeyUnlock(vMasterKey);
ProcessLockedAnonOutputs();
SecureMsgWalletUnlocked();
if (fMakeExtKeyInitials)
{
fMakeExtKeyInitials = false;
CWalletDB wdb(strWalletFile, "r+");
if (ExtKeyCreateInitial(&wdb) != 0)
{
LogPrintf("Warning: ExtKeyCreateInitial failed.\n");
};
};
} // cs_main, cs_wallet
return true;
}
bool CWallet::ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase)
{
bool fWasLocked = IsLocked();
{
LOCK(cs_wallet);
Lock();
CCrypter crypter;
CKeyingMaterial vMasterKey;
BOOST_FOREACH(MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
{
if (!crypter.SetKeyFromPassphrase(strOldWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
return false;
if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
return false;
if (CCryptoKeyStore::Unlock(vMasterKey)
&& UnlockStealthAddresses(vMasterKey))
{
int64_t nStartTime = GetTimeMillis();
crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
pMasterKey.second.nDeriveIterations = pMasterKey.second.nDeriveIterations * (100 / ((double)(GetTimeMillis() - nStartTime)));
nStartTime = GetTimeMillis();
crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
pMasterKey.second.nDeriveIterations = (pMasterKey.second.nDeriveIterations + pMasterKey.second.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
if (pMasterKey.second.nDeriveIterations < 25000)
pMasterKey.second.nDeriveIterations = 25000;
LogPrintf("Wallet passphrase changed to an nDeriveIterations of %i\n", pMasterKey.second.nDeriveIterations);
if (!crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
return false;
if (!crypter.Encrypt(vMasterKey, pMasterKey.second.vchCryptedKey))
return false;
CWalletDB(strWalletFile).WriteMasterKey(pMasterKey.first, pMasterKey.second);
if (fWasLocked)
Lock();
return true;
};
};
} // cs_wallet
return false;
}
void CWallet::SetBestChain(const CBlockLocator& loc)
{
CWalletDB walletdb(strWalletFile);
walletdb.WriteBestBlock(loc);
}
void CWallet::SetBestThinChain(const CBlockThinLocator& loc)
{
CWalletDB walletdb(strWalletFile);
walletdb.WriteBestBlockThin(loc);
}
bool CWallet::SetMinVersion(enum WalletFeature nVersion, CWalletDB* pwalletdbIn, bool fExplicit)
{
LOCK(cs_wallet); // nWalletVersion
if (nWalletVersion >= nVersion)
return true;
// when doing an explicit upgrade, if we pass the max version permitted, upgrade all the way
if (fExplicit && nVersion > nWalletMaxVersion)
nVersion = FEATURE_LATEST;
nWalletVersion = nVersion;
if (nVersion > nWalletMaxVersion)
nWalletMaxVersion = nVersion;
if (fFileBacked)
{
CWalletDB* pwalletdb = pwalletdbIn ? pwalletdbIn : new CWalletDB(strWalletFile);
if (nWalletVersion > 40000)
pwalletdb->WriteMinVersion(nWalletVersion);
if (!pwalletdbIn)
delete pwalletdb;
};
return true;
}
bool CWallet::SetMaxVersion(int nVersion)
{
LOCK(cs_wallet); // nWalletVersion, nWalletMaxVersion
// cannot downgrade below current version
if (nWalletVersion > nVersion)
return false;
nWalletMaxVersion = nVersion;
return true;
}
bool CWallet::EncryptWallet(const SecureString& strWalletPassphrase)
{
if (IsCrypted())
return false;
CKeyingMaterial vMasterKey;
RandAddSeedPerfmon();
vMasterKey.resize(WALLET_CRYPTO_KEY_SIZE);
RAND_bytes(&vMasterKey[0], WALLET_CRYPTO_KEY_SIZE);
CMasterKey kMasterKey(nDerivationMethodIndex);
RandAddSeedPerfmon();
kMasterKey.vchSalt.resize(WALLET_CRYPTO_SALT_SIZE);
RAND_bytes(&kMasterKey.vchSalt[0], WALLET_CRYPTO_SALT_SIZE);
CCrypter crypter;
int64_t nStartTime = GetTimeMillis();
crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, 25000, kMasterKey.nDerivationMethod);
kMasterKey.nDeriveIterations = 2500000 / ((double)(GetTimeMillis() - nStartTime));
nStartTime = GetTimeMillis();
crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod);
kMasterKey.nDeriveIterations = (kMasterKey.nDeriveIterations + kMasterKey.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
if (kMasterKey.nDeriveIterations < 25000)
kMasterKey.nDeriveIterations = 25000;
LogPrintf("Encrypting Wallet with an nDeriveIterations of %i\n", kMasterKey.nDeriveIterations);
if (!crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod))
return false;
if (!crypter.Encrypt(vMasterKey, kMasterKey.vchCryptedKey))
return false;
{
LOCK2(cs_main, cs_wallet);
mapMasterKeys[++nMasterKeyMaxID] = kMasterKey;
if (fFileBacked)
{
pwalletdbEncryption = new CWalletDB(strWalletFile);
if (!pwalletdbEncryption->TxnBegin())
return false;
pwalletdbEncryption->WriteMasterKey(nMasterKeyMaxID, kMasterKey);
};
if (!EncryptKeys(vMasterKey))
{
if (fFileBacked)
pwalletdbEncryption->TxnAbort();
exit(1); //We now probably have half of our keys encrypted in memory, and half not...die and let the user reload their unencrypted wallet.
};
std::set<CStealthAddress>::iterator it;
for (it = stealthAddresses.begin(); it != stealthAddresses.end(); ++it)
{
if (it->scan_secret.size() < 32)
continue; // stealth address is not owned
// -- CStealthAddress is only sorted on spend_pubkey
CStealthAddress &sxAddr = const_cast<CStealthAddress&>(*it);
if (fDebug)
LogPrintf("Encrypting stealth key %s\n", sxAddr.Encoded().c_str());
std::vector<unsigned char> vchCryptedSecret;
CSecret vchSecret;
vchSecret.resize(32);
memcpy(&vchSecret[0], &sxAddr.spend_secret[0], 32);
uint256 iv = Hash(sxAddr.spend_pubkey.begin(), sxAddr.spend_pubkey.end());
if (!EncryptSecret(vMasterKey, vchSecret, iv, vchCryptedSecret))
{
LogPrintf("Error: Failed encrypting stealth key %s\n", sxAddr.Encoded().c_str());
continue;
};
sxAddr.spend_secret = vchCryptedSecret;
pwalletdbEncryption->WriteStealthAddress(sxAddr);
};
if (0 != ExtKeyEncryptAll(pwalletdbEncryption, vMasterKey))
{
LogPrintf("Terminating - Error: ExtKeyEncryptAll failed.\n");
exit(1); // wallet on disk is still uncrypted
};
// Encryption was introduced in version 0.4.0
SetMinVersion(FEATURE_WALLETCRYPT, pwalletdbEncryption, true);
if (fFileBacked)
{
if (!pwalletdbEncryption->TxnCommit())
exit(1); //We now have keys encrypted in memory, but no on disk...die to avoid confusion and let the user reload their unencrypted wallet.
delete pwalletdbEncryption;
pwalletdbEncryption = NULL;
};
Lock();
Unlock(strWalletPassphrase);
NewKeyPool();
Lock();
// Need to completely rewrite the wallet file; if we don't, bdb might keep
// bits of the unencrypted private key in slack space in the database file.
CDB::Rewrite(strWalletFile);
}
NotifyStatusChanged(this);
return true;
}
int64_t CWallet::IncOrderPosNext(CWalletDB *pwalletdb)
{
AssertLockHeld(cs_wallet); // nOrderPosNext
int64_t nRet = nOrderPosNext++;
if (pwalletdb)
{
pwalletdb->WriteOrderPosNext(nOrderPosNext);
} else
{
CWalletDB(strWalletFile).WriteOrderPosNext(nOrderPosNext);
};
return nRet;
}
CWallet::TxItems CWallet::OrderedTxItems(std::list<CAccountingEntry>& acentries, std::string strAccount, bool fShowCoinstake)
{
AssertLockHeld(cs_wallet); // mapWallet
CWalletDB walletdb(strWalletFile);
// First: get all CWalletTx and CAccountingEntry into a sorted-by-order multimap.
TxItems txOrdered;
// Note: maintaining indices in the database of (account,time) --> txid and (account, time) --> acentry
// would make this much faster for applications that do this a lot.
for (WalletTxMap::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
{
CWalletTx* wtx = &((*it).second);
if (!fShowCoinstake
&& wtx->IsCoinStake())
continue;
txOrdered.insert(make_pair(wtx->nOrderPos, TxPair(wtx, (CAccountingEntry*)0)));
};
acentries.clear();
walletdb.ListAccountCreditDebit(strAccount, acentries);
BOOST_FOREACH(CAccountingEntry& entry, acentries)
{
txOrdered.insert(make_pair(entry.nOrderPos, TxPair((CWalletTx*)0, &entry)));
};
return txOrdered;
}
void CWallet::WalletUpdateSpent(const CTransaction &tx, bool fBlock)
{
// Anytime a signature is successfully verified, it's proof the outpoint is spent.
// Update the wallet spent flag if it doesn't know due to wallet.dat being
// restored from backup or the user making copies of wallet.dat.
{
LOCK(cs_wallet);
BOOST_FOREACH(const CTxIn& txin, tx.vin)
{
if (tx.nVersion == ANON_TXN_VERSION
&& txin.IsAnonInput())
{
// anon input
// TODO
continue;
};
WalletTxMap::iterator mi = mapWallet.find(txin.prevout.hash);
if (mi != mapWallet.end())
{
CWalletTx& wtx = (*mi).second;
if (txin.prevout.n >= wtx.vout.size())
{
LogPrintf("WalletUpdateSpent: bad wtx %s\n", wtx.GetHash().ToString().c_str());
} else
if (!wtx.IsSpent(txin.prevout.n) && IsMine(wtx.vout[txin.prevout.n]))
{
LogPrintf("WalletUpdateSpent found spent coin %s SDC %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());
wtx.MarkSpent(txin.prevout.n);
wtx.WriteToDisk();
NotifyTransactionChanged(this, txin.prevout.hash, CT_UPDATED);
};
};
};
if (fBlock)
{
uint256 hash = tx.GetHash();
WalletTxMap::iterator mi = mapWallet.find(hash);
CWalletTx& wtx = (*mi).second;
BOOST_FOREACH(const CTxOut& txout, tx.vout)
{
if (tx.nVersion == ANON_TXN_VERSION
&& txout.IsAnonOutput())
{
// anon output
// TODO
continue;
};
if (IsMine(txout))
{
wtx.MarkUnspent(&txout - &tx.vout[0]);
wtx.WriteToDisk();
NotifyTransactionChanged(this, hash, CT_UPDATED);
};
};
};
}
}
void CWallet::MarkDirty()
{
{
LOCK(cs_wallet);
BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
item.second.MarkDirty();
}
}
bool CWallet::AddToWallet(const CWalletTx& wtxIn, const uint256& hashIn)
{
//uint256 hashIn = wtxIn.GetHash();
{
LOCK(cs_wallet);
// Inserts only if not already there, returns tx inserted or tx found
pair<WalletTxMap::iterator, bool> ret = mapWallet.insert(make_pair(hashIn, wtxIn));
CWalletTx& wtx = (*ret.first).second;
wtx.BindWallet(this);
bool fInsertedNew = ret.second;
if (fInsertedNew)
{
wtx.nTimeReceived = GetAdjustedTime();
wtx.nOrderPos = IncOrderPosNext();
wtx.nTimeSmart = wtx.nTimeReceived;
if (wtxIn.hashBlock != 0)
{
bool fInBlockIndex = false;
unsigned int blocktime;
if (nNodeMode == NT_FULL)
{
fInBlockIndex = mapBlockIndex.count(wtxIn.hashBlock);
blocktime = mapBlockIndex[wtxIn.hashBlock]->nTime;
} else
{
//fInBlockIndex = mapBlockThinIndex.count(wtxIn.hashBlock);
std::map<uint256, CBlockThinIndex*>::iterator mi = mapBlockThinIndex.find(wtxIn.hashBlock);
if (mi == mapBlockThinIndex.end()
&& !fThinFullIndex
&& pindexRear)
{
CTxDB txdb("r");
CDiskBlockThinIndex diskindex;
if (txdb.ReadBlockThinIndex(wtxIn.hashBlock, diskindex)
|| diskindex.hashNext != 0)
{
fInBlockIndex = true;
blocktime = diskindex.nTime;
};
} else
{
fInBlockIndex = true;
blocktime = mi->second->nTime;
};
};
if (fInBlockIndex)
{
unsigned int latestNow = wtx.nTimeReceived;
unsigned int latestEntry = 0;
// Tolerate times up to the last timestamp in the wallet not more than 5 minutes into the future
int64_t latestTolerated = latestNow + 300;
std::list<CAccountingEntry> acentries;
TxItems txOrdered = OrderedTxItems(acentries);
for (TxItems::reverse_iterator it = txOrdered.rbegin(); it != txOrdered.rend(); ++it)
{
CWalletTx *const pwtx = (*it).second.first;
if (pwtx == &wtx)
continue;
CAccountingEntry *const pacentry = (*it).second.second;
int64_t nSmartTime;
if (pwtx)
{
nSmartTime = pwtx->nTimeSmart;
if (!nSmartTime)
nSmartTime = pwtx->nTimeReceived;
} else
{
nSmartTime = pacentry->nTime;
};
if (nSmartTime <= latestTolerated)
{
latestEntry = nSmartTime;
if (nSmartTime > latestNow)
latestNow = nSmartTime;
break;
};
};
wtx.nTimeSmart = std::max(latestEntry, std::min(blocktime, latestNow));
} else
{
LogPrintf("AddToWallet() : found %s in block %s not in index\n",
hashIn.ToString().substr(0,10).c_str(),
wtxIn.hashBlock.ToString().c_str());
};
};
};
bool fUpdated = false;
if (!fInsertedNew)
{
// Merge
if (wtxIn.hashBlock != 0 && wtxIn.hashBlock != wtx.hashBlock)
{
wtx.hashBlock = wtxIn.hashBlock;
fUpdated = true;
};
if (wtxIn.nIndex != -1 && (wtxIn.vMerkleBranch != wtx.vMerkleBranch || wtxIn.nIndex != wtx.nIndex))
{
wtx.vMerkleBranch = wtxIn.vMerkleBranch;
wtx.nIndex = wtxIn.nIndex;
fUpdated = true;
};
if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe)
{
wtx.fFromMe = wtxIn.fFromMe;
fUpdated = true;
};
fUpdated |= wtx.UpdateSpent(wtxIn.vfSpent);
};
//// debug print
LogPrintf("AddToWallet() %s %s%s\n", hashIn.ToString().substr(0,10).c_str(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : ""));
// Write to disk
if (fInsertedNew || fUpdated)
{
if (!wtx.WriteToDisk())
return false;
};
/*
if (!fHaveGUI)
{
// If default receiving address gets used, replace it with a new one
if (vchDefaultKey.IsValid())
{
CScript scriptDefaultKey;
scriptDefaultKey.SetDestination(vchDefaultKey.GetID());
BOOST_FOREACH(const CTxOut& txout, wtx.vout)
{
if (txout.scriptPubKey == scriptDefaultKey)
{
CPubKey newDefaultKey;
if (GetKeyFromPool(newDefaultKey, false))
{
SetDefaultKey(newDefaultKey);
SetAddressBookName(vchDefaultKey.GetID(), "");
};
};
};
};
};
*/
// since AddToWallet is called directly for self-originating transactions, check for consumption of own coins
WalletUpdateSpent(wtx, (wtxIn.hashBlock != 0));
// Notify UI of new or updated transaction
NotifyTransactionChanged(this, hashIn, fInsertedNew ? CT_NEW : CT_UPDATED);
if (nNodeMode == NT_THIN
&& fInsertedNew == CT_NEW
&& pBloomFilter
&& (pBloomFilter->nFlags & BLOOM_UPDATE_MASK) == BLOOM_UPDATE_ALL)
{
uint32_t nAdded = 0;
// -- add unspent outputs to bloom filters
BOOST_FOREACH(const CTxIn& txin, wtx.vin)
{
if (wtx.nVersion == ANON_TXN_VERSION
&& txin.IsAnonInput())
continue;
WalletTxMap::iterator mi = mapWallet.find(txin.prevout.hash);
if (mi == mapWallet.end())
continue;
CWalletTx& wtxPrev = (*mi).second;
if (txin.prevout.n >= wtxPrev.vout.size())
{
LogPrintf("AddToWallet(): bad wtx %s\n", wtxPrev.GetHash().ToString().c_str());
} else
if (!wtxPrev.IsSpent(txin.prevout.n) && IsMine(wtxPrev.vout[txin.prevout.n]))
{
CDataStream stream(SER_NETWORK, PROTOCOL_VERSION);
stream << txin.prevout;
std::vector<unsigned char> vData(stream.begin(), stream.end());
AddDataToMerkleFilters(vData);
nAdded++;
};
};
if (fDebug)
LogPrintf("AddToWallet() Added %u outputs to bloom filters.\n", nAdded);
}
// notify an external script when a wallet transaction comes in or is updated
std::string strCmd = GetArg("-walletnotify", "");
if (!strCmd.empty())
{
boost::replace_all(strCmd, "%s", wtxIn.GetHash().GetHex());
boost::thread t(runCommand, strCmd); // thread runs free
};
}
return true;
}
// Add a transaction to the wallet, or update it.
// pblock is optional, but should be provided if the transaction is known to be in a block.
// If fUpdate is true, existing transactions will be updated.
bool CWallet::AddToWalletIfInvolvingMe(const CTransaction& tx, const uint256& hash, const void* pblock, bool fUpdate, bool fFindBlock)
{
//LogPrintf("AddToWalletIfInvolvingMe() %s\n", hash.ToString().c_str()); // happens often
//uint256 hash = tx.GetHash();
{
LOCK(cs_wallet);
bool fExisted = mapWallet.count(hash);
if (fExisted && !fUpdate)
{
return false;
};
mapValue_t mapNarr;
bool fIsMine = false;
if(!tx.IsCoinBase() && !tx.IsCoinStake())
{
// Skip transactions that we know wouldn't be stealth...
FindStealthTransactions(tx, mapNarr);
if (tx.nVersion == ANON_TXN_VERSION)
{
LOCK(cs_main); // cs_wallet is already locked
CWalletDB walletdb(strWalletFile, "cr+");
CTxDB txdb("cr+");
uint256 blockHash = (pblock ? (nNodeMode == NT_FULL ? ((CBlock*)pblock)->GetHash() : *(uint256*)pblock) : 0);
walletdb.TxnBegin();
txdb.TxnBegin();
std::vector<WalletTxMap::iterator> vUpdatedTxns;
if (!ProcessAnonTransaction(&walletdb, &txdb, tx, blockHash, fIsMine, mapNarr, vUpdatedTxns))
{
LogPrintf("ProcessAnonTransaction failed %s\n", hash.ToString().c_str());
walletdb.TxnAbort();
txdb.TxnAbort();
return false;
} else
{
walletdb.TxnCommit();
txdb.TxnCommit();
for (std::vector<WalletTxMap::iterator>::iterator it = vUpdatedTxns.begin();
it != vUpdatedTxns.end(); ++it)
NotifyTransactionChanged(this, (*it)->first, CT_UPDATED);
};
};
}
if (fExisted || fIsMine || IsMine(tx) || IsFromMe(tx))
{
CWalletTx wtx(this, tx);
if (!mapNarr.empty())
wtx.mapValue.insert(mapNarr.begin(), mapNarr.end());
// Get merkle branch if transaction was found in a block
if (nNodeMode == NT_FULL)
{
const CBlock* pcblock = (CBlock*)pblock;
if (pcblock)
wtx.SetMerkleBranch(pcblock);
} else
{
const uint256* pblockhash = (uint256*)pblock;
if (pblockhash)
wtx.hashBlock = *pblockhash;
};
return AddToWallet(wtx, hash);
} else
{
WalletUpdateSpent(tx);
};
}
return false;
}
bool CWallet::EraseFromWallet(uint256 hash)
{
if (!fFileBacked)
return false;
{
LOCK(cs_wallet);
if (mapWallet.erase(hash))
CWalletDB(strWalletFile).EraseTx(hash);
}
return true;
}
bool CWallet::IsMine(const CTxIn &txin) const
{
{
LOCK(cs_wallet);
WalletTxMap::const_iterator mi = mapWallet.find(txin.prevout.hash);
if (mi != mapWallet.end())
{
const CWalletTx& prev = (*mi).second;
if (txin.prevout.n < prev.vout.size())
if (IsMine(prev.vout[txin.prevout.n]))
return true;
};
}
return false;
}
int64_t CWallet::GetDebit(const CTxIn &txin) const
{
{
LOCK(cs_wallet);
WalletTxMap::const_iterator mi = mapWallet.find(txin.prevout.hash);
if (mi != mapWallet.end())
{
const CWalletTx& prev = (*mi).second;
if (txin.prevout.n < prev.vout.size())
if (IsMine(prev.vout[txin.prevout.n]))
return prev.vout[txin.prevout.n].nValue;
};
}
return 0;
}
int64_t CWallet::GetShadowDebit(const CTxIn& txin) const
{
if (!txin.IsAnonInput())
return 0;
// - amount of owned shadow decreased
// TODO: store links in memory
{
LOCK(cs_wallet);
CWalletDB walletdb(strWalletFile, "r");
std::vector<uint8_t> vchImage;
txin.ExtractKeyImage(vchImage);
COwnedAnonOutput oao;
if (!walletdb.ReadOwnedAnonOutput(vchImage, oao))
return 0;
//return oao.nValue
WalletTxMap::const_iterator mi = mapWallet.find(oao.outpoint.hash);
if (mi != mapWallet.end())
{
const CWalletTx& prev = (*mi).second;
if (oao.outpoint.n < prev.vout.size())
return prev.vout[oao.outpoint.n].nValue;
};
}
return 0;
};
int64_t CWallet::GetShadowCredit(const CTxOut& txout) const
{
if (!txout.IsAnonOutput())
return 0;
// TODO: store links in memory
{
LOCK(cs_wallet);
CWalletDB walletdb(strWalletFile, "r");
CPubKey pkCoin = txout.ExtractAnonPk();
std::vector<uint8_t> vchImage;
if (!walletdb.ReadOwnedAnonOutputLink(pkCoin, vchImage))
return 0;
COwnedAnonOutput oao;
if (!walletdb.ReadOwnedAnonOutput(vchImage, oao))
return 0;
WalletTxMap::const_iterator mi = mapWallet.find(oao.outpoint.hash);
if (mi != mapWallet.end())
{
const CWalletTx& prev = (*mi).second;
if (oao.outpoint.n < prev.vout.size())
{
return prev.vout[oao.outpoint.n].nValue;
};
};
} // cs_wallet
return 0;
};
bool CWallet::IsChange(const CTxOut& txout) const
{
CTxDestination address;
// TODO: fix handling of 'change' outputs. The assumption is that any
// payment to a TX_PUBKEYHASH that is mine but isn't in the address book
// is change. That assumption is likely to break when we implement multisignature
// wallets that return change back into a multi-signature-protected address;
// a better way of identifying which outputs are 'the send' and which are
// 'the change' will need to be implemented (maybe extend CWalletTx to remember
// which output, if any, was change).
if (ExtractDestination(txout.scriptPubKey, address) && IsDestMine(*this, address))
{
LOCK(cs_wallet);
if (!mapAddressBook.count(address))
return true;
};
return false;
}
int64_t CWalletTx::GetTxTime() const
{
int64_t n = nTimeSmart;
return n ? n : nTimeReceived;
}
int CWalletTx::GetRequestCount() const
{
// Returns -1 if it wasn't being tracked
int nRequests = -1;
{
LOCK(pwallet->cs_wallet);
if (IsCoinBase() || IsCoinStake())
{
// Generated block
if (hashBlock != 0)
{
std::map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
if (mi != pwallet->mapRequestCount.end())
nRequests = (*mi).second;
};
} else
{
// Did anyone request this transaction?
map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(GetHash());
if (mi != pwallet->mapRequestCount.end())
{
nRequests = (*mi).second;
// How about the block it's in?
if (nRequests == 0 && hashBlock != 0)
{
map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
if (mi != pwallet->mapRequestCount.end())
nRequests = (*mi).second;
else
nRequests = 1; // If it's in someone else's block it must have got out
};
};
};
}
return nRequests;
}
void CWalletTx::GetAmounts(list<pair<CTxDestination, int64_t> >& listReceived,
list<pair<CTxDestination, int64_t> >& listSent, int64_t& nFee, string& strSentAccount) const
{
nFee = 0;
listReceived.clear();
listSent.clear();
strSentAccount = strFromAccount;
// Compute fee:
int64_t nDebit = GetDebit();
//if (nVersion == ANON_TXN_VERSION)
// nDebit += GetShadowDebit();
if (nDebit > 0) // debit>0 means we signed/sent this transaction
{
int64_t nValueOut = GetValueOut();
nFee = nDebit - nValueOut;
};
// Sent/received.
BOOST_FOREACH(const CTxOut& txout, vout)
{
if (nVersion == ANON_TXN_VERSION
&& txout.IsAnonOutput())
{
const CScript &s = txout.scriptPubKey;
CKeyID ckidD = CPubKey(&s[2+1], 33).GetID();
bool fIsMine = pwallet->HaveKey(ckidD);
CTxDestination address = ckidD;
// If we are debited by the transaction, add the output as a "sent" entry
if (nDebit > 0)
listSent.push_back(make_pair(address, txout.nValue));
// If we are receiving the output, add it as a "received" entry
if (fIsMine)
listReceived.push_back(make_pair(address, txout.nValue));
continue;
};
// Skip special stake out
if (txout.scriptPubKey.empty())
continue;
opcodetype firstOpCode;
CScript::const_iterator pc = txout.scriptPubKey.begin();
if (txout.scriptPubKey.GetOp(pc, firstOpCode)
&& firstOpCode == OP_RETURN)
continue;
bool fIsMine;
// Only need to handle txouts if AT LEAST one of these is true:
// 1) they debit from us (sent)
// 2) the output is to us (received)
if (nDebit > 0)
{
// Don't report 'change' txouts
if (pwallet->IsChange(txout))
continue;
fIsMine = pwallet->IsMine(txout);
} else
if (!(fIsMine = pwallet->IsMine(txout)))
continue;
// In either case, we need to get the destination address
CTxDestination address;
if (!ExtractDestination(txout.scriptPubKey, address))
{
LogPrintf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n",
this->GetHash().ToString().c_str());
address = CNoDestination();
};
// If we are debited by the transaction, add the output as a "sent" entry
if (nDebit > 0)
listSent.push_back(make_pair(address, txout.nValue));
// If we are receiving the output, add it as a "received" entry
if (fIsMine)
listReceived.push_back(make_pair(address, txout.nValue));
};
}
void CWalletTx::GetAccountAmounts(const std::string& strAccount, int64_t& nReceived,
int64_t& nSent, int64_t& nFee) const
{
nReceived = nSent = nFee = 0;
int64_t allFee;
std::string strSentAccount;
std::list<std::pair<CTxDestination, int64_t> > listReceived;
std::list<std::pair<CTxDestination, int64_t> > listSent;
GetAmounts(listReceived, listSent, allFee, strSentAccount);
if (strAccount == strSentAccount)
{
BOOST_FOREACH(const PAIRTYPE(CTxDestination,int64_t)& s, listSent)
nSent += s.second;
nFee = allFee;
};
{
LOCK(pwallet->cs_wallet);
BOOST_FOREACH(const PAIRTYPE(CTxDestination,int64_t)& r, listReceived)
{
if (pwallet->mapAddressBook.count(r.first))
{
std::map<CTxDestination, std::string>::const_iterator mi = pwallet->mapAddressBook.find(r.first);
if (mi != pwallet->mapAddressBook.end() && (*mi).second == strAccount)
nReceived += r.second;
} else
if (strAccount.empty())
{
nReceived += r.second;
};
};
} // pwallet->cs_wallet
}
void CWalletTx::AddSupportingTransactions(CTxDB& txdb)
{
vtxPrev.clear();
const int COPY_DEPTH = 3;
if (SetMerkleBranch() < COPY_DEPTH)
{
std::vector<uint256> vWorkQueue;
BOOST_FOREACH(const CTxIn& txin, vin)
vWorkQueue.push_back(txin.prevout.hash);
// This critsect is OK because txdb is already open
{
LOCK(pwallet->cs_wallet);
map<uint256, const CMerkleTx*> mapWalletPrev;
set<uint256> setAlreadyDone;
for (unsigned int i = 0; i < vWorkQueue.size(); i++)
{
uint256 hash = vWorkQueue[i];
if (setAlreadyDone.count(hash))
continue;
setAlreadyDone.insert(hash);
CMerkleTx tx;
WalletTxMap::const_iterator mi = pwallet->mapWallet.find(hash);
if (mi != pwallet->mapWallet.end())
{
tx = (*mi).second;
BOOST_FOREACH(const CMerkleTx& txWalletPrev, (*mi).second.vtxPrev)
mapWalletPrev[txWalletPrev.GetHash()] = &txWalletPrev;
} else
if (mapWalletPrev.count(hash))
{
tx = *mapWalletPrev[hash];
} else
if (txdb.ReadDiskTx(hash, tx))
{
;
} else
{
LogPrintf("ERROR: AddSupportingTransactions() : unsupported transaction\n");
continue;
};
int nDepth = tx.SetMerkleBranch();
vtxPrev.push_back(tx);
if (nDepth < COPY_DEPTH)
{
BOOST_FOREACH(const CTxIn& txin, tx.vin)
vWorkQueue.push_back(txin.prevout.hash);
};
};
} // pwallet->cs_wallet
};
reverse(vtxPrev.begin(), vtxPrev.end());
}
bool CWalletTx::WriteToDisk()
{
return CWalletDB(pwallet->strWalletFile).WriteTx(GetHash(), *this);
}
// Scan the block chain (starting in pindexStart) for transactions
// from or to us. If fUpdate is true, found transactions that already
// exist in the wallet will be updated.
int CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate)
{
if (fDebug)
LogPrintf("ScanForWalletTransactions()\n");
if (nNodeMode != NT_FULL)
{
LogPrintf("Error: CWallet::ScanForWalletTransactions() must be run in full mode.\n");
return 0;
};
int ret = 0;
int64_t nTimeFirstKeyTmp = nTimeFirstKey;
int nCurBestHeight = nBestHeight;
fReindexing = true;
// When scanning from a certain height, people could be interested in rebuilding stealth address and anonymous transaction cache.
if(pindexStart->nHeight > 1)
nTimeFirstKey = pindexStart->nTime;
CBlockIndex* pindex = pindexStart;
{
LOCK2(cs_main, cs_wallet);
while (pindex)
{
// no need to read and scan block, if block was created before
// our wallet birthday (as adjusted for block time variability)
if (nTimeFirstKey && (pindex->nTime < (nTimeFirstKey - 7200)))
{
pindex = pindex->pnext;
continue;
};
CBlock block;
block.ReadFromDisk(pindex, true);
nBestHeight = pindex->nHeight;
BOOST_FOREACH(CTransaction& tx, block.vtx)
{
uint256 hash = tx.GetHash();
if (AddToWalletIfInvolvingMe(tx, hash, &block, fUpdate))
ret++;
};
pindex = pindex->pnext;
};
} // cs_main, cs_wallet
// Reset nTimeFirstKey
nTimeFirstKey = nTimeFirstKeyTmp;
nBestHeight = nCurBestHeight;
fReindexing = false;
return ret;
}
void CWallet::ReacceptWalletTransactions()
{
if (fDebug)
LogPrintf("ReacceptWalletTransactions()\n");
CTxDB txdb("r");
if (nNodeMode == NT_THIN)
{
for (WalletTxMap::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
{
CWalletTx& wtx = (*it).second;
if ((wtx.IsCoinBase() && wtx.IsSpent(0))
|| (wtx.IsCoinStake() && wtx.IsSpent(1)))
continue;
std::map<uint256, CBlockThinIndex*>::iterator mi = mapBlockThinIndex.find(wtx.hashBlock);
if (mi == mapBlockThinIndex.end())
{
if (!fThinFullIndex)
{
CDiskBlockThinIndex diskindex;
if (txdb.ReadBlockThinIndex(wtx.hashBlock, diskindex)
&& diskindex.hashNext != 0)
continue; // block is in db and in main chain
};
// Re-accept any txes of ours that aren't already in a block
if (!(wtx.IsCoinBase() || wtx.IsCoinStake()))
wtx.AcceptWalletTransaction(txdb);
continue;
};
};
return;
};
bool fRepeat = true;
while (fRepeat)
{
LOCK2(cs_main, cs_wallet);
fRepeat = false;
std::vector<CDiskTxPos> vMissingTx;
BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
{
CWalletTx& wtx = item.second;
if ((wtx.IsCoinBase() && wtx.IsSpent(0))
|| (wtx.IsCoinStake() && wtx.IsSpent(1)))
continue;
CTxIndex txindex;
bool fUpdated = false;
if (txdb.ReadTxIndex(wtx.GetHash(), txindex))
{
// Update fSpent if a tx got spent somewhere else by a copy of wallet.dat
if (txindex.vSpent.size() != wtx.vout.size())
{
LogPrintf("ERROR: ReacceptWalletTransactions() : txindex.vSpent.size() %u != wtx.vout.size() %u\n", txindex.vSpent.size(), wtx.vout.size());
continue;
};
for (unsigned int i = 0; i < txindex.vSpent.size(); i++)
{
if (wtx.IsSpent(i))
continue;
if (!txindex.vSpent[i].IsNull() && IsMine(wtx.vout[i]))
{
wtx.MarkSpent(i);
fUpdated = true;
vMissingTx.push_back(txindex.vSpent[i]);
};
};
if (fUpdated)
{
LogPrintf("ReacceptWalletTransactions found spent coin %s SDC %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());
wtx.MarkDirty();
wtx.WriteToDisk();
};
} else
{
// Re-accept any txes of ours that aren't already in a block
if (!(wtx.IsCoinBase() || wtx.IsCoinStake()))
wtx.AcceptWalletTransaction(txdb);
};
};
if (!vMissingTx.empty())
{
// TODO: optimize this to scan just part of the block chain?
if (ScanForWalletTransactions(pindexGenesisBlock))
fRepeat = true; // Found missing transactions: re-do re-accept.
};
};
}
void CWalletTx::RelayWalletTransaction(CTxDB& txdb)
{
BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
{
if (!(tx.IsCoinBase() || tx.IsCoinStake()))
{
uint256 hash = tx.GetHash();
if (!txdb.ContainsTx(hash))
RelayTransaction((CTransaction)tx, hash);
};
};
if (!(IsCoinBase() || IsCoinStake()))
{
uint256 hash = GetHash();
if (!txdb.ContainsTx(hash))
{
LogPrintf("Relaying wtx %s\n", hash.ToString().substr(0,10).c_str());
RelayTransaction((CTransaction)*this, hash);
};
};
}
void CWalletTx::RelayWalletTransaction()
{
CTxDB txdb("r");
RelayWalletTransaction(txdb);
}
void CWallet::ResendWalletTransactions(bool fForce)
{
if (!fForce)
{
// Do this infrequently and randomly to avoid giving away
// that these are our transactions.
static int64_t nNextTime = 0;
if (GetTime() < nNextTime)
return;
bool fFirst = (nNextTime == 0);
nNextTime = GetTime() + GetRand(30 * 60);
if (fFirst)
return;
// Only do it if there's been a new block since last time
static int64_t nLastTime;
if (nTimeBestReceived < nLastTime)
return;
nLastTime = GetTime();
};
// Rebroadcast any of our txes that aren't in a block yet
LogPrintf("ResendWalletTransactions()\n");
CTxDB txdb("r");
multimap<unsigned int, CWalletTx*> mapSorted;
{
LOCK(cs_wallet);
// Sort them in chronological order
BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
{
CWalletTx& wtx = item.second;
// Don't rebroadcast until it's had plenty of time that
// it should have gotten in already by now.
if (fForce || nTimeBestReceived - (int64_t)wtx.nTimeReceived > 5 * 60)
mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx));
};
} // cs_wallet
BOOST_FOREACH(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted)
{
CWalletTx& wtx = *item.second;
if (wtx.CheckTransaction())
wtx.RelayWalletTransaction(txdb);
else
LogPrintf("ResendWalletTransactions() : CheckTransaction failed for transaction %s\n", wtx.GetHash().ToString().c_str());
};
}
//////////////////////////////////////////////////////////////////////////////
//
// Actions
//
int64_t CWallet::GetBalance() const
{
int64_t nTotal = 0;
{
LOCK2(cs_main, cs_wallet);
for (WalletTxMap::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
{
const CWalletTx* pcoin = &(*it).second;
if (pcoin->IsTrusted())
nTotal += pcoin->GetAvailableCredit();
};
}
return nTotal;
}
int64_t CWallet::GetShadowBalance() const
{
int64_t nTotal = 0;
{
LOCK2(cs_main, cs_wallet);
for (WalletTxMap::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
{
const CWalletTx* pcoin = &(*it).second;
if (pcoin->IsTrusted() && pcoin->nVersion == ANON_TXN_VERSION)
nTotal += pcoin->GetAvailableShadowCredit();
};
}
return nTotal;
};
int64_t CWallet::GetUnconfirmedBalance() const
{
int64_t nTotal = 0;
{
LOCK2(cs_main, cs_wallet);
for (WalletTxMap::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
{
const CWalletTx* pcoin = &(*it).second;
if (!pcoin->IsFinal() || (!pcoin->IsTrusted() && pcoin->GetDepthInMainChain() == 0))
nTotal += pcoin->GetAvailableCredit();
};
}
return nTotal;
}
int64_t CWallet::GetImmatureBalance() const
{
int64_t nTotal = 0;
{
LOCK2(cs_main, cs_wallet);
for (WalletTxMap::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
{
const CWalletTx& pcoin = (*it).second;
if (pcoin.IsCoinBase() && pcoin.GetBlocksToMaturity() > 0 && pcoin.IsInMainChain())
nTotal += GetCredit(pcoin);
}
}
return nTotal;
}
// populate vCoins with vector of spendable COutputs
void CWallet::AvailableCoins(std::vector<COutput>& vCoins, bool fOnlyConfirmed, const CCoinControl *coinControl) const
{
vCoins.clear();
{
LOCK2(cs_main, cs_wallet);
for (WalletTxMap::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
{
const CWalletTx* pcoin = &(*it).second;
if (!pcoin->IsFinal())
continue;
if (fOnlyConfirmed && !pcoin->IsTrusted())
continue;
if ((pcoin->IsCoinBase()||pcoin->IsCoinStake()) && pcoin->GetBlocksToMaturity() > 0)
continue;
int nDepth = pcoin->GetDepthInMainChain();
if (nDepth < 0)
continue;
for (unsigned int i = 0; i < pcoin->vout.size(); i++)
if (!(pcoin->IsSpent(i)) && IsMine(pcoin->vout[i]) && pcoin->vout[i].nValue >= nMinimumInputValue &&
(!coinControl || !coinControl->HasSelected() || coinControl->IsSelected((*it).first, i)))
vCoins.push_back(COutput(pcoin, i, nDepth));
}
}
}
void CWallet::AvailableCoinsForStaking(std::vector<COutput>& vCoins, unsigned int nSpendTime) const
{
vCoins.clear();
{
LOCK2(cs_main, cs_wallet);
for (WalletTxMap::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
{
const CWalletTx* pcoin = &(*it).second;
// Filtering by tx timestamp instead of block timestamp may give false positives but never false negatives
if (pcoin->nTime + nStakeMinAge > nSpendTime)
continue;
if (pcoin->GetBlocksToMaturity() > 0)
continue;
int nDepth = pcoin->GetDepthInMainChain();
if (nDepth < 1)
continue;
for (unsigned int i = 0; i < pcoin->vout.size(); i++)
{
if (pcoin->nVersion == ANON_TXN_VERSION
&& pcoin->vout[i].IsAnonOutput())
continue;
if (!(pcoin->IsSpent(i)) && IsMine(pcoin->vout[i]) && pcoin->vout[i].nValue >= nMinimumInputValue)
vCoins.push_back(COutput(pcoin, i, nDepth));
};
};
}
}
static void ApproximateBestSubset(
std::vector<pair<int64_t, pair<const CWalletTx*,unsigned int> > >vValue, int64_t nTotalLower, int64_t nTargetValue,
std::vector<char>& vfBest, int64_t& nBest, int iterations = 1000)
{
std::vector<char> vfIncluded;
vfBest.assign(vValue.size(), true);
nBest = nTotalLower;
for (int nRep = 0; nRep < iterations && nBest != nTargetValue; nRep++)
{
vfIncluded.assign(vValue.size(), false);
int64_t nTotal = 0;
bool fReachedTarget = false;
for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
{
for (unsigned int i = 0; i < vValue.size(); i++)
{
if (nPass == 0 ? rand() % 2 : !vfIncluded[i])
{
nTotal += vValue[i].first;
vfIncluded[i] = true;
if (nTotal >= nTargetValue)
{
fReachedTarget = true;
if (nTotal < nBest)
{
nBest = nTotal;
vfBest = vfIncluded;
}
nTotal -= vValue[i].first;
vfIncluded[i] = false;
}
}
}
}
}
}
// ppcoin: total coins staked (non-spendable until maturity)
int64_t CWallet::GetStake() const
{
int64_t nTotal = 0;
LOCK2(cs_main, cs_wallet);
for (WalletTxMap::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
{
const CWalletTx* pcoin = &(*it).second;
if (pcoin->IsCoinStake() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
nTotal += CWallet::GetCredit(*pcoin);
};
return nTotal;
}
int64_t CWallet::GetNewMint() const
{
int64_t nTotal = 0;
LOCK2(cs_main, cs_wallet);
for (WalletTxMap::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
{
const CWalletTx* pcoin = &(*it).second;
if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
nTotal += CWallet::GetCredit(*pcoin);
};
return nTotal;
}
bool CWallet::SelectCoinsMinConf(int64_t nTargetValue, unsigned int nSpendTime, int nConfMine, int nConfTheirs, std::vector<COutput> vCoins, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64_t& nValueRet) const
{
setCoinsRet.clear();
nValueRet = 0;
// List of values less than target
pair<int64_t, pair<const CWalletTx*,unsigned int> > coinLowestLarger;
coinLowestLarger.first = std::numeric_limits<int64_t>::max();
coinLowestLarger.second.first = NULL;
std::vector<std::pair<int64_t, std::pair<const CWalletTx*,unsigned int> > > vValue;
int64_t nTotalLower = 0;
random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
BOOST_FOREACH(COutput output, vCoins)
{
const CWalletTx *pcoin = output.tx;
if (output.nDepth < (pcoin->IsFromMe() ? nConfMine : nConfTheirs))
continue;
int i = output.i;
// Follow the timestamp rules
if (pcoin->nTime > nSpendTime)
continue;
int64_t n = pcoin->vout[i].nValue;
pair<int64_t,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin, i));
if (n == nTargetValue)
{
setCoinsRet.insert(coin.second);
nValueRet += coin.first;
return true;
}
else if (n < nTargetValue + CENT)
{
vValue.push_back(coin);
nTotalLower += n;
}
else if (n < coinLowestLarger.first)
{
coinLowestLarger = coin;
}
}
if (nTotalLower == nTargetValue)
{
for (unsigned int i = 0; i < vValue.size(); ++i)
{
setCoinsRet.insert(vValue[i].second);
nValueRet += vValue[i].first;
}
return true;
}
if (nTotalLower < nTargetValue)
{
if (coinLowestLarger.second.first == NULL)
return false;
setCoinsRet.insert(coinLowestLarger.second);
nValueRet += coinLowestLarger.first;
return true;
}
// Solve subset sum by stochastic approximation
sort(vValue.rbegin(), vValue.rend(), CompareValueOnly());
std::vector<char> vfBest;
int64_t nBest;
ApproximateBestSubset(vValue, nTotalLower, nTargetValue, vfBest, nBest, 1000);
if (nBest != nTargetValue && nTotalLower >= nTargetValue + CENT)
ApproximateBestSubset(vValue, nTotalLower, nTargetValue + CENT, vfBest, nBest, 1000);
// If we have a bigger coin and (either the stochastic approximation didn't find a good solution,
// or the next bigger coin is closer), return the bigger coin
if (coinLowestLarger.second.first &&
((nBest != nTargetValue && nBest < nTargetValue + CENT) || coinLowestLarger.first <= nBest))
{
setCoinsRet.insert(coinLowestLarger.second);
nValueRet += coinLowestLarger.first;
}
else
{
for (unsigned int i = 0; i < vValue.size(); i++)
if (vfBest[i])
{
setCoinsRet.insert(vValue[i].second);
nValueRet += vValue[i].first;
}
if (fDebug && GetBoolArg("-printpriority"))
{
//// debug print
LogPrintf("SelectCoins() best subset: ");
for (unsigned int i = 0; i < vValue.size(); i++)
if (vfBest[i])
LogPrintf("%s ", FormatMoney(vValue[i].first).c_str());
LogPrintf("total %s\n", FormatMoney(nBest).c_str());
}
}
return true;
}
bool CWallet::SelectCoins(int64_t nTargetValue, unsigned int nSpendTime, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64_t& nValueRet, const CCoinControl* coinControl) const
{
std::vector<COutput> vCoins;
AvailableCoins(vCoins, true, coinControl);
// coin control -> return all selected outputs (we want all selected to go into the transaction for sure)
if (coinControl && coinControl->HasSelected())
{
BOOST_FOREACH(const COutput& out, vCoins)
{
nValueRet += out.tx->vout[out.i].nValue;
setCoinsRet.insert(make_pair(out.tx, out.i));
}
return (nValueRet >= nTargetValue);
}
boost::function<bool (const CWallet*, int64_t, unsigned int, int, int, std::vector<COutput>, std::set<std::pair<const CWalletTx*,unsigned int> >&, int64_t&)> f = &CWallet::SelectCoinsMinConf;
return (f(this, nTargetValue, nSpendTime, 1, 10, vCoins, setCoinsRet, nValueRet) ||
f(this, nTargetValue, nSpendTime, 1, 1, vCoins, setCoinsRet, nValueRet) ||
f(this, nTargetValue, nSpendTime, 0, 1, vCoins, setCoinsRet, nValueRet));
}
// Select some coins without random shuffle or best subset approximation
bool CWallet::SelectCoinsForStaking(int64_t nTargetValue, unsigned int nSpendTime, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64_t& nValueRet) const
{
std::vector<COutput> vCoins;
AvailableCoinsForStaking(vCoins, nSpendTime);
setCoinsRet.clear();
nValueRet = 0;
BOOST_FOREACH(COutput output, vCoins)
{
const CWalletTx *pcoin = output.tx;
int i = output.i;
// Stop if we've chosen enough inputs
if (nValueRet >= nTargetValue)
break;
int64_t n = pcoin->vout[i].nValue;
pair<int64_t, pair<const CWalletTx*, unsigned int> > coin = make_pair(n, make_pair(pcoin, i));
if (n >= nTargetValue)
{
// If input value is greater or equal to target then simply insert
// it into the current subset and exit
setCoinsRet.insert(coin.second);
nValueRet += coin.first;
break;
} else
if (n < nTargetValue + CENT)
{
setCoinsRet.insert(coin.second);
nValueRet += coin.first;
};
}
return true;
}
bool CWallet::CreateTransaction(const std::vector<std::pair<CScript, int64_t> >& vecSend, CWalletTx& wtxNew, int64_t& nFeeRet, int32_t& nChangePos, const CCoinControl* coinControl)
{
int64_t nValue = 0;
BOOST_FOREACH (const PAIRTYPE(CScript, int64_t)& s, vecSend)
{
if (nValue < 0)
return false;
nValue += s.second;
};
if (vecSend.empty() || nValue < 0)
return false;
wtxNew.BindWallet(this);
{
LOCK2(cs_main, cs_wallet);
// txdb must be opened before the mapWallet lock
CTxDB txdb("r");
{
nFeeRet = nTransactionFee;
while (true)
{
wtxNew.vin.clear();
wtxNew.vout.clear();
wtxNew.fFromMe = true;
int64_t nTotalValue = nValue + nFeeRet;
double dPriority = 0;
// vouts to the payees
BOOST_FOREACH(const PAIRTYPE(CScript, int64_t)& s, vecSend)
{
wtxNew.vout.push_back(CTxOut(s.second, s.first));
};
// Choose coins to use
set<pair<const CWalletTx*,unsigned int> > setCoins;
int64_t nValueIn = 0;
if (!SelectCoins(nTotalValue, wtxNew.nTime, setCoins, nValueIn, coinControl))
return false;
BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
{
int64_t nCredit = pcoin.first->vout[pcoin.second].nValue;
dPriority += (double)nCredit * pcoin.first->GetDepthInMainChain();
};
int64_t nChange = nValueIn - nValue - nFeeRet;
// if sub-cent change is required, the fee must be raised to at least MIN_TX_FEE
// or until nChange becomes zero
// NOTE: this depends on the exact behaviour of GetMinFee
if (nFeeRet < MIN_TX_FEE && nChange > 0 && nChange < CENT)
{
int64_t nMoveToFee = min(nChange, MIN_TX_FEE - nFeeRet);
nChange -= nMoveToFee;
nFeeRet += nMoveToFee;
};
if (nChange > 0)
{
// Fill a vout to ourself
// TODO: pass in scriptChange instead of reservekey so
// change transaction isn't always pay-to-bitcoin-address
CScript scriptChange;
// coin control: send change to custom address
if (coinControl && !boost::get<CNoDestination>(&coinControl->destChange))
{
scriptChange.SetDestination(coinControl->destChange);
} else
{
// no coin control: send change to newly generated address
// Note: We use a new key here to keep it from being obvious which side is the change.
// Use the next key in the internal chain of the default account.
// TODO: send in more parameters so GetChangeAddress can pick the account to derive from.
CPubKey vchPubKey;
if (0 != GetChangeAddress(vchPubKey))
return false;
scriptChange.SetDestination(vchPubKey.GetID());
};
// Insert change txn at random position:
std::vector<CTxOut>::iterator position = wtxNew.vout.begin()+GetRandInt(wtxNew.vout.size() + 1);
// -- don't put change output between value and narration outputs
if (position > wtxNew.vout.begin() && position < wtxNew.vout.end())
{
while (position > wtxNew.vout.begin())
{
if (position->nValue != 0)
break;
position--;
};
};
wtxNew.vout.insert(position, CTxOut(nChange, scriptChange));
nChangePos = std::distance(wtxNew.vout.begin(), position);
};
// Fill vin
BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
wtxNew.vin.push_back(CTxIn(coin.first->GetHash(),coin.second));
// Sign
int nIn = 0;
BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
if (!SignSignature(*this, *coin.first, wtxNew, nIn++))
{
LogPrintf("%s: Error SignSignature failed.\n", __func__);
return false;
};
// Limit size
unsigned int nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK, PROTOCOL_VERSION);
if (nBytes >= MAX_BLOCK_SIZE_GEN/5)
{
LogPrintf("%s: Error MAX_BLOCK_SIZE_GEN/5 limit hit.\n", __func__);
return false;
};
dPriority /= nBytes;
// Check that enough fee is included
int64_t nPayFee = nTransactionFee * (1 + (int64_t)nBytes / 1000);
int64_t nMinFee = wtxNew.GetMinFee(1, GMF_SEND, nBytes);
if (nFeeRet < max(nPayFee, nMinFee))
{
nFeeRet = max(nPayFee, nMinFee);
continue;
};
// Fill vtxPrev by copying from previous transactions vtxPrev
wtxNew.AddSupportingTransactions(txdb);
wtxNew.fTimeReceivedIsTxTime = true;
break;
};
}
}
return true;
}
bool CWallet::CreateTransaction(CScript scriptPubKey, int64_t nValue, std::string& sNarr, CWalletTx& wtxNew, int64_t& nFeeRet, const CCoinControl* coinControl)
{
std::vector<std::pair<CScript, int64_t> > vecSend;
vecSend.push_back(make_pair(scriptPubKey, nValue));
if (sNarr.length() > 0)
{
std::vector<uint8_t> vNarr(sNarr.c_str(), sNarr.c_str() + sNarr.length());
std::vector<uint8_t> vNDesc;
vNDesc.resize(2);
vNDesc[0] = 'n';
vNDesc[1] = 'p';
CScript scriptN = CScript() << OP_RETURN << vNDesc << OP_RETURN << vNarr;
vecSend.push_back(make_pair(scriptN, 0));
};
// -- CreateTransaction won't place change between value and narr output.
// narration output will be for preceding output
int nChangePos;
bool rv = CreateTransaction(vecSend, wtxNew, nFeeRet, nChangePos, coinControl);
// -- narration will be added to mapValue later in FindStealthTransactions From CommitTransaction
return rv;
}
bool CWallet::AddStealthAddress(CStealthAddress& sxAddr)
{
LOCK(cs_wallet);
// - must add before changing spend_secret
stealthAddresses.insert(sxAddr);
bool fOwned = sxAddr.scan_secret.size() == EC_SECRET_SIZE;
if (fOwned)
{
// -- owned addresses can only be added when wallet is unlocked
if (IsLocked())
{
LogPrintf("Error: CWallet::AddStealthAddress wallet must be unlocked.\n");
stealthAddresses.erase(sxAddr);
return false;
};
if (IsCrypted())
{
std::vector<unsigned char> vchCryptedSecret;
CSecret vchSecret;
vchSecret.resize(EC_SECRET_SIZE);
memcpy(&vchSecret[0], &sxAddr.spend_secret[0], EC_SECRET_SIZE);
uint256 iv = Hash(sxAddr.spend_pubkey.begin(), sxAddr.spend_pubkey.end());
if (!EncryptSecret(vMasterKey, vchSecret, iv, vchCryptedSecret))
{
LogPrintf("Error: Failed encrypting stealth key %s\n", sxAddr.Encoded().c_str());
stealthAddresses.erase(sxAddr);
return false;
};
sxAddr.spend_secret = vchCryptedSecret;
};
};
bool rv = CWalletDB(strWalletFile).WriteStealthAddress(sxAddr);
if (rv)
NotifyAddressBookChanged(this, sxAddr, sxAddr.label, fOwned, CT_NEW, true);
return rv;
}
bool CWallet::UnlockStealthAddresses(const CKeyingMaterial& vMasterKeyIn)
{
// -- decrypt spend_secret of stealth addresses
std::set<CStealthAddress>::iterator it;
for (it = stealthAddresses.begin(); it != stealthAddresses.end(); ++it)
{
if (it->scan_secret.size() < EC_SECRET_SIZE)
continue; // stealth address is not owned
// -- CStealthAddress are only sorted on spend_pubkey
CStealthAddress &sxAddr = const_cast<CStealthAddress&>(*it);
if (fDebug)
LogPrintf("Decrypting stealth key %s\n", sxAddr.Encoded().c_str());
CSecret vchSecret;
uint256 iv = Hash(sxAddr.spend_pubkey.begin(), sxAddr.spend_pubkey.end());
if (!DecryptSecret(vMasterKeyIn, sxAddr.spend_secret, iv, vchSecret)
|| vchSecret.size() != EC_SECRET_SIZE)
{
LogPrintf("Error: Failed decrypting stealth key %s\n", sxAddr.Encoded().c_str());
continue;
};
ec_secret testSecret;
memcpy(&testSecret.e[0], &vchSecret[0], EC_SECRET_SIZE);
ec_point pkSpendTest;
if (SecretToPublicKey(testSecret, pkSpendTest) != 0
|| pkSpendTest != sxAddr.spend_pubkey)
{
LogPrintf("Error: Failed decrypting stealth key, public key mismatch %s\n", sxAddr.Encoded().c_str());
continue;
};
sxAddr.spend_secret.resize(EC_SECRET_SIZE);
memcpy(&sxAddr.spend_secret[0], &vchSecret[0], EC_SECRET_SIZE);
};
CryptedKeyMap::iterator mi = mapCryptedKeys.begin();
for (; mi != mapCryptedKeys.end(); ++mi)
{
CPubKey &pubKey = (*mi).second.first;
std::vector<unsigned char> &vchCryptedSecret = (*mi).second.second;
if (vchCryptedSecret.size() != 0)
continue;
CKeyID ckid = pubKey.GetID();
CBitcoinAddress addr(ckid);
StealthKeyMetaMap::iterator mi = mapStealthKeyMeta.find(ckid);
if (mi == mapStealthKeyMeta.end())
{
// -- could be an anon output
if (fDebug)
LogPrintf("Warning: No metadata found to add secret for %s\n", addr.ToString().c_str());
continue;
};
CStealthKeyMetadata& sxKeyMeta = mi->second;
CStealthAddress sxFind;
sxFind.SetScanPubKey(sxKeyMeta.pkScan);
std::set<CStealthAddress>::iterator si = stealthAddresses.find(sxFind);
if (si == stealthAddresses.end())
{
LogPrintf("No stealth key found to add secret for %s\n", addr.ToString().c_str());
continue;
};
if (fDebug)
LogPrintf("Expanding secret for %s\n", addr.ToString().c_str());
ec_secret sSpendR;
ec_secret sSpend;
ec_secret sScan;
if (si->spend_secret.size() != EC_SECRET_SIZE
|| si->scan_secret.size() != EC_SECRET_SIZE)
{
LogPrintf("Stealth address has no secret key for %s\n", addr.ToString().c_str());
continue;
};
memcpy(&sScan.e[0], &si->scan_secret[0], EC_SECRET_SIZE);
memcpy(&sSpend.e[0], &si->spend_secret[0], EC_SECRET_SIZE);
ec_point pkEphem;;
pkEphem.resize(sxKeyMeta.pkEphem.size());
memcpy(&pkEphem[0], sxKeyMeta.pkEphem.begin(), sxKeyMeta.pkEphem.size());
if (StealthSecretSpend(sScan, pkEphem, sSpend, sSpendR) != 0)
{
LogPrintf("StealthSecretSpend() failed.\n");
continue;
};
CKey ckey;
ckey.Set(&sSpendR.e[0], true);
if (!ckey.IsValid())
{
LogPrintf("Reconstructed key is invalid.\n");
continue;
};
CPubKey cpkT = ckey.GetPubKey(true);
if (!cpkT.IsValid())
{
LogPrintf("%s: cpkT is invalid.\n", __func__);
continue;
};
if (cpkT != pubKey)
{
LogPrintf("%s: Error: Generated secret does not match.\n", __func__);
if (fDebug)
{
LogPrintf("cpkT %s\n", HexStr(cpkT).c_str());
LogPrintf("pubKey %s\n", HexStr(pubKey).c_str());
};
continue;
};
if (fDebug)
{
CKeyID keyID = cpkT.GetID();
CBitcoinAddress coinAddress(keyID);
LogPrintf("%s: Adding secret to key %s.\n", __func__, coinAddress.ToString().c_str());
};
if (!AddKeyPubKey(ckey, cpkT))
{
LogPrintf("%s: AddKeyPubKey failed.\n", __func__);
continue;
};
if (!CWalletDB(strWalletFile).EraseStealthKeyMeta(ckid))
LogPrintf("EraseStealthKeyMeta failed for %s\n", addr.ToString().c_str());
};
return true;
}
bool CWallet::UpdateStealthAddress(std::string &addr, std::string &label, bool addIfNotExist)
{
if (fDebug)
LogPrintf("%s: %s\n", __func__, addr.c_str());
CStealthAddress sxAddr;
if (!sxAddr.SetEncoded(addr))
return error("%s: Invalid address.", __func__);
LOCK(cs_wallet);
CKeyID sxId = CPubKey(sxAddr.scan_pubkey).GetID();
ExtKeyAccountMap::const_iterator mi;
for (mi = mapExtAccounts.begin(); mi != mapExtAccounts.end(); ++mi)
{
CExtKeyAccount *ea = mi->second;
if (ea->mapStealthKeys.size() < 1)
continue;
AccStealthKeyMap::iterator it = ea->mapStealthKeys.find(sxId);
if (it != ea->mapStealthKeys.end())
{
CWalletDB wdb(strWalletFile);
return (0 == ExtKeyUpdateStealthAddress(&wdb, ea, sxId, label));
};
};
std::set<CStealthAddress>::iterator it;
it = stealthAddresses.find(sxAddr);
ChangeType nMode = CT_UPDATED;
CStealthAddress sxFound;
if (it == stealthAddresses.end())
{
if (addIfNotExist)
{
sxFound = sxAddr;
sxFound.label = label;
stealthAddresses.insert(sxFound);
nMode = CT_NEW;
} else
{
return error("%s: %s, not in set.", __func__, addr.c_str());;
};
} else
{
sxFound = const_cast<CStealthAddress&>(*it);
if (sxFound.label == label)
{
// no change
return true;
};
it->label = label; // update in .stealthAddresses
if (sxFound.scan_secret.size() == EC_SECRET_SIZE)
{
// -- read from db to keep encryption
CStealthAddress sxOwned;
if (!CWalletDB(strWalletFile).ReadStealthAddress(sxFound))
{
error("%s: error - sxFound not in db.", __func__);
return false;
};
};
};
sxFound.label = label;
if (!CWalletDB(strWalletFile).WriteStealthAddress(sxFound))
{
return error("%s: %s WriteStealthAddress failed.", __func__, addr.c_str());
};
bool fOwned = sxFound.scan_secret.size() == EC_SECRET_SIZE;
NotifyAddressBookChanged(this, sxFound, sxFound.label, fOwned, nMode, true);
return true;
};
bool CWallet::CreateStealthTransaction(CScript scriptPubKey, int64_t nValue, std::vector<uint8_t>& P, std::vector<uint8_t>& narr, std::string& sNarr, CWalletTx& wtxNew, int64_t& nFeeRet, const CCoinControl* coinControl)
{
std::vector<std::pair<CScript, int64_t> > vecSend;
vecSend.push_back(make_pair(scriptPubKey, nValue));
CScript scriptP = CScript() << OP_RETURN << P;
if (narr.size() > 0)
scriptP = scriptP << OP_RETURN << narr;
vecSend.push_back(make_pair(scriptP, 0));
// -- shuffle inputs, change output won't mix enough as it must be not fully random for plantext narrations
std::random_shuffle(vecSend.begin(), vecSend.end());
int nChangePos;
bool rv = CreateTransaction(vecSend, wtxNew, nFeeRet, nChangePos, coinControl);
// -- the change txn is inserted in a random pos, check here to match narr to output
if (rv && narr.size() > 0)
{
for (unsigned int k = 0; k < wtxNew.vout.size(); ++k)
{
if (wtxNew.vout[k].scriptPubKey != scriptPubKey
|| wtxNew.vout[k].nValue != nValue)
continue;
char key[64];
if (snprintf(key, sizeof(key), "n_%u", k) < 1)
{
LogPrintf("%s: Error creating narration key.", __func__);
break;
};
wtxNew.mapValue[key] = sNarr;
break;
};
};
return rv;
};
string CWallet::SendStealthMoney(CScript scriptPubKey, int64_t nValue, std::vector<uint8_t>& P, std::vector<uint8_t>& narr, std::string& sNarr, CWalletTx& wtxNew, bool fAskFee)
{
int64_t nFeeRequired;
if (IsLocked())
{
string strError = _("Error: Wallet locked, unable to create transaction ");
LogPrintf("SendStealthMoney(): %s", strError.c_str());
return strError;
};
if (fWalletUnlockStakingOnly)
{
string strError = _("Error: Wallet unlocked for staking only, unable to create transaction.");
LogPrintf("SendStealthMoney(): %s", strError.c_str());
return strError;
};
if (!CreateStealthTransaction(scriptPubKey, nValue, P, narr, sNarr, wtxNew, nFeeRequired))
{
string strError;
if (nValue + nFeeRequired > GetBalance())
strError = strprintf(_("Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds "), FormatMoney(nFeeRequired).c_str());
else
strError = _("Error: Transaction creation failed ");
LogPrintf("SendStealthMoney(): %s\n", strError.c_str());
return strError;
};
if (fAskFee && !uiInterface.ThreadSafeAskFee(nFeeRequired, _("Sending...")))
return "ABORTED";
if (!CommitTransaction(wtxNew))
return _("Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.");
return "";
};
bool CWallet::SendStealthMoneyToDestination(CStealthAddress& sxAddress, int64_t nValue, std::string& sNarr, CWalletTx& wtxNew, std::string& sError, bool fAskFee)
{
// -- Check amount
if (nValue <= 0)
{
sError = "Invalid amount";
return false;
};
if (nValue + nTransactionFee > GetBalance())
{
sError = "Insufficient funds";
return false;
};
ec_secret ephem_secret;
ec_secret secretShared;
ec_point pkSendTo;
ec_point ephem_pubkey;
if (GenerateRandomSecret(ephem_secret) != 0)
{
sError = "GenerateRandomSecret failed.";
return false;
};
if (StealthSecret(ephem_secret, sxAddress.scan_pubkey, sxAddress.spend_pubkey, secretShared, pkSendTo) != 0)
{
sError = "Could not generate receiving public key.";
return false;
};
CPubKey cpkTo(pkSendTo);
if (!cpkTo.IsValid())
{
sError = "Invalid public key generated.";
return false;
};
CKeyID ckidTo = cpkTo.GetID();
CBitcoinAddress addrTo(ckidTo);
if (SecretToPublicKey(ephem_secret, ephem_pubkey) != 0)
{
sError = "Could not generate ephem public key.";
return false;
};
if (fDebug)
{
LogPrintf("Stealth send to generated pubkey %u: %s\n", pkSendTo.size(), HexStr(pkSendTo).c_str());
LogPrintf("hash %s\n", addrTo.ToString().c_str());
LogPrintf("ephem_pubkey %u: %s\n", ephem_pubkey.size(), HexStr(ephem_pubkey).c_str());
};
std::vector<unsigned char> vchNarr;
if (sNarr.length() > 0)
{
SecMsgCrypter crypter;
crypter.SetKey(&secretShared.e[0], &ephem_pubkey[0]);
if (!crypter.Encrypt((uint8_t*)&sNarr[0], sNarr.length(), vchNarr))
{
sError = "Narration encryption failed.";
return false;
};
if (vchNarr.size() > MAX_STEALTH_NARRATION_SIZE)
{
sError = "Encrypted narration is too long.";
return false;
};
};
// -- Parse Bitcoin address
CScript scriptPubKey;
scriptPubKey.SetDestination(addrTo.Get());
if ((sError = SendStealthMoney(scriptPubKey, nValue, ephem_pubkey, vchNarr, sNarr, wtxNew, fAskFee)) != "")
return false;
return true;
}
bool CWallet::FindStealthTransactions(const CTransaction& tx, mapValue_t& mapNarr)
{
if (fDebug)
LogPrintf("%s: tx: %s.\n", __func__, tx.GetHash().GetHex().c_str());
mapNarr.clear();
LOCK(cs_wallet);
ec_secret sSpendR;
ec_secret sSpend;
ec_secret sScan;
ec_secret sShared;
ec_point pkExtracted;
std::vector<uint8_t> vchEphemPK;
std::vector<uint8_t> vchDataB;
std::vector<uint8_t> vchENarr;
opcodetype opCode;
char cbuf[256];
int32_t nOutputIdOuter = -1;
BOOST_FOREACH(const CTxOut& txout, tx.vout)
{
nOutputIdOuter++;
// -- for each OP_RETURN need to check all other valid outputs
// -- skip scan anon outputs
if (tx.nVersion == ANON_TXN_VERSION
&& txout.IsAnonOutput())
continue;
CScript::const_iterator itTxA = txout.scriptPubKey.begin();
if (!txout.scriptPubKey.GetOp(itTxA, opCode, vchEphemPK)
|| opCode != OP_RETURN)
continue;
else
if (!txout.scriptPubKey.GetOp(itTxA, opCode, vchEphemPK)
|| vchEphemPK.size() != EC_COMPRESSED_SIZE)
{
// -- look for plaintext narrations
if (vchEphemPK.size() > 1
&& vchEphemPK[0] == 'n'
&& vchEphemPK[1] == 'p')
{
if (txout.scriptPubKey.GetOp(itTxA, opCode, vchENarr)
&& opCode == OP_RETURN
&& txout.scriptPubKey.GetOp(itTxA, opCode, vchENarr)
&& vchENarr.size() > 0)
{
std::string sNarr = std::string(vchENarr.begin(), vchENarr.end());
snprintf(cbuf, sizeof(cbuf), "n_%d", nOutputIdOuter-1); // plaintext narration always matches preceding value output
mapNarr[cbuf] = sNarr;
} else
{
LogPrintf("%s Warning - tx: %s, Could not extract plaintext narration.\n", __func__, tx.GetHash().GetHex().c_str());
};
};
continue;
};
int32_t nOutputId = -1;
nStealth++;
BOOST_FOREACH(const CTxOut& txoutB, tx.vout)
{
nOutputId++;
// -- skip anon outputs
if (tx.nVersion == ANON_TXN_VERSION
&& txout.IsAnonOutput())
continue;
if (&txoutB == &txout)
continue;
bool txnMatch = false; // only 1 txn will match an ephem pk
CTxDestination address;
if (!ExtractDestination(txoutB.scriptPubKey, address))
continue;
if (address.type() != typeid(CKeyID))
continue;
CKeyID ckidMatch = boost::get<CKeyID>(address);
if (HaveKey(ckidMatch)) // no point checking if already have key
continue;
std::set<CStealthAddress>::iterator it;
for (it = stealthAddresses.begin(); it != stealthAddresses.end(); ++it)
{
if (it->scan_secret.size() != EC_SECRET_SIZE)
continue; // stealth address is not owned
memcpy(&sScan.e[0], &it->scan_secret[0], EC_SECRET_SIZE);
if (StealthSecret(sScan, vchEphemPK, it->spend_pubkey, sShared, pkExtracted) != 0)
{
LogPrintf("%s: StealthSecret failed.\n", __func__);
continue;
};
CPubKey cpkE(pkExtracted);
if (!cpkE.IsValid())
continue;
CKeyID ckidE = cpkE.GetID();
if (ckidMatch != ckidE)
continue;
if (fDebug)
LogPrintf("Found stealth txn to address %s\n", it->Encoded().c_str());
if (IsLocked())
{
if (fDebug)
LogPrintf("Wallet locked, adding key without secret.\n");
// -- add key without secret
std::vector<uint8_t> vchEmpty;
AddCryptedKey(cpkE, vchEmpty);
CKeyID keyId = cpkE.GetID();
CBitcoinAddress coinAddress(keyId);
std::string sLabel = it->Encoded();
SetAddressBookName(keyId, sLabel);
CPubKey cpkEphem(vchEphemPK);
CPubKey cpkScan(it->scan_pubkey);
CStealthKeyMetadata lockedSkMeta(cpkEphem, cpkScan);
if (!CWalletDB(strWalletFile).WriteStealthKeyMeta(keyId, lockedSkMeta))
LogPrintf("WriteStealthKeyMeta failed for %s.\n", coinAddress.ToString().c_str());
mapStealthKeyMeta[keyId] = lockedSkMeta;
nFoundStealth++;
} else
{
if (it->spend_secret.size() != EC_SECRET_SIZE)
continue;
memcpy(&sSpend.e[0], &it->spend_secret[0], EC_SECRET_SIZE);
if (StealthSharedToSecretSpend(sShared, sSpend, sSpendR) != 0)
{
LogPrintf("StealthSharedToSecretSpend() failed.\n");
continue;
};
CKey ckey;
ckey.Set(&sSpendR.e[0], true);
if (!ckey.IsValid())
{
LogPrintf("%s: Reconstructed key is invalid.\n", __func__);
continue;
};
CPubKey cpkT = ckey.GetPubKey();
if (!cpkT.IsValid())
{
LogPrintf("%s: cpkT is invalid.\n", __func__);
continue;
};
CKeyID keyID = cpkT.GetID();
if (keyID != ckidMatch)
{
LogPrintf("%s: Spend key mismatch!\n", __func__);
continue;
};
if (fDebug)
{
CBitcoinAddress coinAddress(keyID);
LogPrintf("Adding key %s.\n", coinAddress.ToString().c_str());
};
if (!AddKeyPubKey(ckey, cpkT))
{
LogPrintf("%s: AddKeyPubKey failed.\n", __func__);
continue;
};
std::string sLabel = it->Encoded();
SetAddressBookName(keyID, sLabel);
nFoundStealth++;
};
txnMatch = true;
break;
};
if (txnMatch)
break;
// - ext account stealth keys
ExtKeyAccountMap::const_iterator mi;
for (mi = mapExtAccounts.begin(); mi != mapExtAccounts.end(); ++mi)
{
CExtKeyAccount *ea = mi->second;
for (AccStealthKeyMap::iterator it = ea->mapStealthKeys.begin(); it != ea->mapStealthKeys.end(); ++it)
{
const CEKAStealthKey &aks = it->second;
if (!aks.skScan.IsValid())
continue;
memcpy(&sScan.e[0], aks.skScan.begin(), EC_SECRET_SIZE);
if (StealthSecret(sScan, vchEphemPK, aks.pkSpend, sShared, pkExtracted) != 0)
{
LogPrintf("%s: StealthSecret failed.\n", __func__);
continue;
};
CPubKey cpkE(pkExtracted);
if (!cpkE.IsValid())
continue;
CKeyID ckidE = cpkE.GetID();
if (ckidMatch != ckidE)
continue;
if (fDebug)
{
LogPrintf("Found stealth txn to address %s\n", aks.ToStealthAddress().c_str());
// - check key if not locked
if (!IsLocked())
{
CKey kTest;
if (0 != ea->ExpandStealthChildKey(&aks, sShared, kTest))
{
LogPrintf("%s: Error: ExpandStealthChildKey failed! %s.\n", __func__, aks.ToStealthAddress().c_str());
continue;
};
CKeyID kTestId = kTest.GetPubKey().GetID();
if (kTestId != ckidMatch)
{
LogPrintf("Error: Spend key mismatch!\n");
continue;
};
CBitcoinAddress coinAddress(kTestId);
LogPrintf("Debug: ExpandStealthChildKey matches! %s, %s.\n", aks.ToStealthAddress().c_str(), coinAddress.ToString().c_str());
};
};
// - don't need to extract key now, wallet may be locked
CKeyID idStealthKey = aks.GetID();
CEKASCKey kNew(idStealthKey, sShared);
if (0 != ExtKeySaveKey(ea, ckidMatch, kNew))
{
LogPrintf("%s: Error: ExtKeySaveKey failed!\n", __func__);
continue;
};
// - for compatability
std::string sLabel = aks.ToStealthAddress();
SetAddressBookName(ckidMatch, sLabel);
txnMatch = true;
break;
};
if (txnMatch)
break;
};
if (txnMatch)
{
// - process narration
if (txout.scriptPubKey.GetOp(itTxA, opCode, vchENarr)
&& opCode == OP_RETURN
&& txout.scriptPubKey.GetOp(itTxA, opCode, vchENarr)
&& vchENarr.size() > 0)
{
SecMsgCrypter crypter;
crypter.SetKey(&sShared.e[0], &vchEphemPK[0]);
std::vector<uint8_t> vchNarr;
if (!crypter.Decrypt(&vchENarr[0], vchENarr.size(), vchNarr))
{
LogPrintf("%s: Decrypt narration failed.\n", __func__);
continue;
};
std::string sNarr = std::string(vchNarr.begin(), vchNarr.end());
snprintf(cbuf, sizeof(cbuf), "n_%d", nOutputId);
mapNarr[cbuf] = sNarr;
};
break;
};
};
};
return true;
};
static int GetBlockHeightFromHash(const uint256& blockHash)
{
if (blockHash == 0)
return 0;
if (nNodeMode == NT_FULL)
{
std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(blockHash);
if (mi == mapBlockIndex.end())
return 0;
return mi->second->nHeight;
} else
{
std::map<uint256, CBlockThinIndex*>::iterator mi = mapBlockThinIndex.find(blockHash);
if (mi == mapBlockThinIndex.end()
&& !fThinFullIndex
&& pindexRear)
{
CTxDB txdb("r");
CDiskBlockThinIndex diskindex;
if (txdb.ReadBlockThinIndex(blockHash, diskindex)
|| diskindex.hashNext != 0)
{
return diskindex.nHeight;
};
} else
{
return mi->second->nHeight;
};
};
return 0;
}
static int IsAnonCoinCompromised(CTxDB *txdb, CPubKey &pubKey, CAnonOutput &ao, ec_point &vchSpentImage)
{
// check if its been compromised (signer known)
CKeyImageSpent kis;
ec_point pkImage;
bool fInMempool;
getOldKeyImage(pubKey, pkImage);
if (vchSpentImage == pkImage || GetKeyImage(txdb, pkImage, kis, fInMempool))
{
ao.nCompromised = 1;
txdb->WriteAnonOutput(pubKey, ao);
if(fDebugRingSig)
LogPrintf("Spent key image, mark as compromised: %s\n", pubKey.GetID().ToString());
return 1;
}
return 0;
}
bool CWallet::UpdateAnonTransaction(CTxDB *ptxdb, const CTransaction& tx, const uint256& blockHash)
{
uint256 txnHash = tx.GetHash();
if (fDebugRingSig)
{
LogPrintf("UpdateAnonTransaction() tx: %s\n", txnHash.GetHex().c_str());
AssertLockHeld(cs_main);
AssertLockHeld(cs_wallet);
};
// -- update txns not received in a block
int nNewHeight = GetBlockHeightFromHash(blockHash);
CKeyImageSpent spentKeyImage;
for (uint32_t i = 0; i < tx.vin.size(); ++i)
{
const CTxIn& txin = tx.vin[i];
if (!txin.IsAnonInput())
continue;
const CScript &s = txin.scriptSig;
std::vector<uint8_t> vchImage;
txin.ExtractKeyImage(vchImage);
int nRingSize = txin.ExtractRingSize();
// -- get nCoinValue by reading first ring element
CPubKey pkRingCoin;
CAnonOutput ao;
CTxIndex txindex;
const uint8_t *pPubkeys;
if (nRingSize > 1 && s.size() == 2 + EC_SECRET_SIZE + (EC_COMPRESSED_SIZE + EC_SECRET_SIZE) * nRingSize)
{
pPubkeys = &s[2 + EC_SECRET_SIZE + EC_SECRET_SIZE * nRingSize];
} else
if (s.size() >= 2 + (EC_COMPRESSED_SIZE + EC_SECRET_SIZE + EC_SECRET_SIZE) * nRingSize)
{
pPubkeys = &s[2];
} else
return error("%s: Input %d scriptSig too small.", __func__, i);
pkRingCoin = CPubKey(&pPubkeys[0 * EC_COMPRESSED_SIZE], EC_COMPRESSED_SIZE);
if (!ptxdb->ReadAnonOutput(pkRingCoin, ao))
{
LogPrintf("UpdateAnonTransaction(): Error input %u AnonOutput %s not found.\n", i, pkRingCoin.GetID().ToString());
//LogPrintf("%s, %s\n", pkRingCoin.GetID().ToString(), CBitcoinAddress(pkRingCoin.GetID()).ToString());
return false;
};
int64_t nCoinValue = ao.nValue;
spentKeyImage.txnHash = txnHash;
spentKeyImage.inputNo = i;
spentKeyImage.nValue = nCoinValue;
if (!ptxdb->WriteKeyImage(vchImage, spentKeyImage))
{
LogPrintf("UpdateAnonTransaction(): Error input %d WriteKeyImage failed %s .\n", i, HexStr(vchImage).c_str());
return false;
}
}
for (uint32_t i = 0; i < tx.vout.size(); ++i)
{
const CTxOut& txout = tx.vout[i];
if (!txout.IsAnonOutput())
continue;
const CScript &s = txout.scriptPubKey;
CPubKey pkCoin = CPubKey(&s[2+1], EC_COMPRESSED_SIZE);
CAnonOutput ao;
if (!ptxdb->ReadAnonOutput(pkCoin, ao))
{
LogPrintf("ReadAnonOutput %d failed.\n", i);
return false;
};
ao.nBlockHeight = nNewHeight;
if (!ptxdb->WriteAnonOutput(pkCoin, ao))
{
LogPrintf("ReadAnonOutput %d failed.\n", i);
return false;
};
LogPrintf("UpdateAnonTransaction(): updateDepth: %d, value: %d\n", nNewHeight, ao.nValue);
mapAnonOutputStats[ao.nValue].updateDepth(nNewHeight, ao.nValue);
};
return true;
};
bool CWallet::UndoAnonTransaction(const CTransaction& tx)
{
if (fDebugRingSig)
LogPrintf("UndoAnonTransaction() tx: %s\n", tx.GetHash().GetHex().c_str());
// -- undo transaction - used if block is unlinked / txn didn't commit
LOCK2(cs_main, cs_wallet);
uint256 txnHash = tx.GetHash();
CWalletDB walletdb(strWalletFile, "cr+");
CTxDB txdb("cr+");
for (unsigned int i = 0; i < tx.vin.size(); ++i)
{
const CTxIn& txin = tx.vin[i];
if (!txin.IsAnonInput())
continue;
ec_point vchImage;
txin.ExtractKeyImage(vchImage);
CKeyImageSpent spentKeyImage;
bool fInMempool;
if (!GetKeyImage(&txdb, vchImage, spentKeyImage, fInMempool))
{
if (fDebugRingSig)
LogPrintf("Error: keyImage for input %d not found.\n", i);
continue;
};
// Possible?
if (spentKeyImage.txnHash != txnHash)
{
LogPrintf("Error: spentKeyImage for %s does not match txn %s.\n", HexStr(vchImage).c_str(), txnHash.ToString().c_str());
continue;
};
if (!txdb.EraseKeyImage(vchImage))
{
LogPrintf("EraseKeyImage %d failed.\n", i);
continue;
};
mapAnonOutputStats[spentKeyImage.nValue].decSpends(spentKeyImage.nValue);
COwnedAnonOutput oao;
if (walletdb.ReadOwnedAnonOutput(vchImage, oao))
{
if (fDebugRingSig)
LogPrintf("UndoAnonTransaction(): input %d keyimage %s found in wallet (owned).\n", i, HexStr(vchImage).c_str());
WalletTxMap::iterator mi = mapWallet.find(oao.outpoint.hash);
if (mi == mapWallet.end())
{
LogPrintf("UndoAnonTransaction(): Error input %d prev txn not in mapwallet %s .\n", i, oao.outpoint.hash.ToString().c_str());
return false;
};
CWalletTx& inTx = (*mi).second;
if (oao.outpoint.n >= inTx.vout.size())
{
LogPrintf("UndoAnonTransaction(): bad wtx %s\n", oao.outpoint.hash.ToString().c_str());
return false;
} else
if (inTx.IsSpent(oao.outpoint.n))
{
LogPrintf("UndoAnonTransaction(): found spent coin %s\n", oao.outpoint.hash.ToString().c_str());
inTx.MarkUnspent(oao.outpoint.n);
if (!walletdb.WriteTx(oao.outpoint.hash, inTx))
{
LogPrintf("UndoAnonTransaction(): input %d WriteTx failed %s.\n", i, HexStr(vchImage).c_str());
return false;
};
inTx.MarkDirty(); // recalc balances
NotifyTransactionChanged(this, oao.outpoint.hash, CT_UPDATED);
};
oao.fSpent = false;
if (!walletdb.WriteOwnedAnonOutput(vchImage, oao))
{
LogPrintf("UndoAnonTransaction(): input %d WriteOwnedAnonOutput failed %s.\n", i, HexStr(vchImage).c_str());
return false;
};
};
};
for (uint32_t i = 0; i < tx.vout.size(); ++i)
{
const CTxOut& txout = tx.vout[i];
if (!txout.IsAnonOutput())
continue;
const CScript &s = txout.scriptPubKey;
CPubKey pkCoin = CPubKey(&s[2+1], EC_COMPRESSED_SIZE);
CKeyID ckCoinId = pkCoin.GetID();
CAnonOutput ao;
if (!txdb.ReadAnonOutput(pkCoin, ao)) // read only to update mapAnonOutputStats
{
LogPrintf("ReadAnonOutput(): %u failed.\n", i);
return false;
};
mapAnonOutputStats[ao.nValue].decExists(ao.nValue);
if (!txdb.EraseAnonOutput(pkCoin))
{
LogPrintf("EraseAnonOutput(): %u failed.\n", i);
continue;
};
// -- only in db if owned
walletdb.EraseLockedAnonOutput(ckCoinId);
std::vector<uint8_t> vchImage;
if (!walletdb.ReadOwnedAnonOutputLink(pkCoin, vchImage))
{
LogPrintf("ReadOwnedAnonOutputLink(): %u failed - output wasn't owned.\n", i);
continue;
};
if (!walletdb.EraseOwnedAnonOutput(vchImage))
{
LogPrintf("EraseOwnedAnonOutput(): %u failed.\n", i);
continue;
};
if (!walletdb.EraseOwnedAnonOutputLink(pkCoin))
{
LogPrintf("EraseOwnedAnonOutputLink(): %u failed.\n", i);
continue;
};
};
if (!walletdb.EraseTx(txnHash))
{
LogPrintf("UndoAnonTransaction() EraseTx %s failed.\n", txnHash.ToString().c_str());
return false;
};
mapWallet.erase(txnHash);
return true;
};
bool CWallet::ProcessAnonTransaction(CWalletDB *pwdb, CTxDB *ptxdb, const CTransaction& tx, const uint256& blockHash, bool& fIsMine, mapValue_t& mapNarr, std::vector<WalletTxMap::iterator>& vUpdatedTxns)
{
uint256 txnHash = tx.GetHash();
if (fDebugRingSig)
{
LogPrintf("%s: tx: %s.\n", __func__, txnHash.GetHex().c_str());
AssertLockHeld(cs_main);
AssertLockHeld(cs_wallet);
};
// - txdb and walletdb must be in a transaction (no commit if fail)
if (nNodeMode != NT_FULL)
{
return error("%s: Skipped - must run in full mode.\n", __func__);
};
for (uint32_t i = 0; i < tx.vin.size(); ++i)
{
const CTxIn& txin = tx.vin[i];
if (!txin.IsAnonInput())
continue;
const CScript &s = txin.scriptSig;
ec_point vchImage;
txin.ExtractKeyImage(vchImage);
CKeyImageSpent spentKeyImage;
bool fInMempool;
if (GetKeyImage(ptxdb, vchImage, spentKeyImage, fInMempool))
{
if (spentKeyImage.txnHash == txnHash
&& spentKeyImage.inputNo == i)
{
if (fDebugRingSig)
LogPrintf("found matching spent key image - txn has been processed before\n");
return UpdateAnonTransaction(ptxdb, tx, blockHash);
};
if (TxnHashInSystem(ptxdb, spentKeyImage.txnHash))
{
return error("%s: Error input %d keyimage %s already spent.", __func__, i, HexStr(vchImage).c_str());
};
if (fDebugRingSig)
LogPrintf("Input %d keyimage %s matches unknown txn %s, continuing.\n", i, HexStr(vchImage).c_str(), spentKeyImage.txnHash.ToString().c_str());
// -- keyimage is in db, but invalid as does not point to a known transaction
// could be an old mempool keyimage
// continue
};
COwnedAnonOutput oao;
ec_point vchNewImage;
if (!pwdb->ReadOldOutputLink(vchImage, vchNewImage))
vchNewImage = vchImage;
if (pwdb->ReadOwnedAnonOutput(vchNewImage, oao))
{
if (fDebugRingSig)
LogPrintf("%s: input %d keyimage %s found in wallet (owned).\n", __func__, i, HexStr(vchImage).c_str());
WalletTxMap::iterator mi = mapWallet.find(oao.outpoint.hash);
if (mi == mapWallet.end())
return error("%s: Error input %d prev txn not in mapwallet %s.", __func__, i, oao.outpoint.hash.ToString().c_str());
CWalletTx& inTx = (*mi).second;
if (oao.outpoint.n >= inTx.vout.size())
{
return error("%s: bad wtx %s.", __func__, oao.outpoint.hash.ToString().c_str());
} else
if (!inTx.IsSpent(oao.outpoint.n))
{
LogPrintf("%s: found spent coin %s.\n", __func__, oao.outpoint.hash.ToString().c_str());
inTx.MarkSpent(oao.outpoint.n);
if (!pwdb->WriteTx(oao.outpoint.hash, inTx))
{
return error("%s: Input %d WriteTx failed %s.", __func__, i, HexStr(vchImage).c_str());
};
inTx.MarkDirty(); // recalc balances
vUpdatedTxns.push_back(mi); // notify updates outside db txn
};
oao.fSpent = true;
if (!pwdb->WriteOwnedAnonOutput(vchNewImage, oao))
{
return error("%s: Input %d WriteOwnedAnonOutput failed %s.", __func__, i, HexStr(vchImage).c_str());
};
};
int nRingSize = txin.ExtractRingSize();
if (nRingSize < (Params().IsProtocolV3(nBestHeight) ? 1 : (int)MIN_RING_SIZE)
||nRingSize > (Params().IsProtocolV3(nBestHeight) ? (int)MAX_RING_SIZE : (int)MAX_RING_SIZE_OLD))
return error("%s: Input %d ringsize %d not in range [%d, %d].", __func__, i, nRingSize, MIN_RING_SIZE, MAX_RING_SIZE);
const uint8_t *pPubkeys;
int rsType;
if (nRingSize > 1 && s.size() == 2 + EC_SECRET_SIZE + (EC_COMPRESSED_SIZE + EC_SECRET_SIZE) * nRingSize)
{
rsType = RING_SIG_2;
pPubkeys = &s[2 + EC_SECRET_SIZE + EC_SECRET_SIZE * nRingSize];
} else
if (s.size() >= 2 + (EC_COMPRESSED_SIZE + EC_SECRET_SIZE + EC_SECRET_SIZE) * nRingSize)
{
rsType = RING_SIG_1;
pPubkeys = &s[2];
} else
return error("%s: Input %d scriptSig too small.", __func__, i);
int64_t nCoinValue = -1;
CPubKey pkRingCoin;
CAnonOutput ao;
CTxIndex txindex;
for (uint32_t ri = 0; ri < (uint32_t)nRingSize; ++ri)
{
pkRingCoin = CPubKey(&pPubkeys[ri * EC_COMPRESSED_SIZE], EC_COMPRESSED_SIZE);
if (!ptxdb->ReadAnonOutput(pkRingCoin, ao))
return error("%s: Input %u AnonOutput %s not found, rsType: %d.", __func__, i, HexStr(pkRingCoin).c_str(), rsType);
if (IsAnonCoinCompromised(ptxdb, pkRingCoin, ao, vchImage) and Params().IsProtocolV3(nBestHeight))
return error("%s: Found spent pubkey at index %u: AnonOutput: %s, rsType: %d.", __func__, i, HexStr(pkRingCoin).c_str(), rsType);
if (nCoinValue == -1)
nCoinValue = ao.nValue;
else
if (nCoinValue != ao.nValue)
return error("%s: Input %u ring amount mismatch %d, %d.", __func__, i, nCoinValue, ao.nValue);
if (ao.nBlockHeight == 0
|| nBestHeight - ao.nBlockHeight < MIN_ANON_SPEND_DEPTH)
return error("%s: Input %u ring coin %u depth < MIN_ANON_SPEND_DEPTH.", __func__, i, ri);
if (nRingSize == 1)
{
ao.nCompromised = 1;
if (!ptxdb->WriteAnonOutput(pkRingCoin, ao))
return error("%s: Input %d WriteAnonOutput failed %s.", __func__, i, HexStr(vchImage).c_str());
mapAnonOutputStats[ao.nValue].nCompromised++;
}
// -- ring sig validation is done in CTransaction::CheckAnonInputs()
}
spentKeyImage.txnHash = txnHash;
spentKeyImage.inputNo = i;
spentKeyImage.nValue = nCoinValue;
if (blockHash != 0)
{
if (!ptxdb->WriteKeyImage(vchImage, spentKeyImage))
return error("%s: Input %d WriteKeyImage failed %s.", __func__, i, HexStr(vchImage).c_str());
} else
// -- add keyImage to mempool, will be added to txdb in UpdateAnonTransaction
mempool.insertKeyImage(vchImage, spentKeyImage);
mapAnonOutputStats[spentKeyImage.nValue].incSpends(spentKeyImage.nValue);
}
ec_secret sSpendR;
ec_secret sSpend;
ec_secret sScan;
ec_secret sShared;
ec_point pkExtracted;
std::vector<uint8_t> vchEphemPK;
std::vector<uint8_t> vchDataB;
std::vector<uint8_t> vchENarr;
std::vector<std::vector<uint8_t> > vPrevMatch;
char cbuf[256];
try { vchEphemPK.resize(EC_COMPRESSED_SIZE); } catch (std::exception& e)
{
return error("%s: vchEphemPK.resize threw: %s.", __func__, e.what());
};
int nBlockHeight = GetBlockHeightFromHash(blockHash);
for (uint32_t i = 0; i < tx.vout.size(); ++i)
{
const CTxOut& txout = tx.vout[i];
if (!txout.IsAnonOutput())
continue;
const CScript &s = txout.scriptPubKey;
CPubKey pkCoin = CPubKey(&s[2+1], EC_COMPRESSED_SIZE);
CKeyID ckCoinId = pkCoin.GetID();
COutPoint outpoint = COutPoint(tx.GetHash(), i);
// -- add all anon outputs to txdb
CAnonOutput ao;
if (ptxdb->ReadAnonOutput(pkCoin, ao)) // check if exists
{
if (blockHash != 0)
{
if (fDebugRingSig)
LogPrintf("Found existing anon output - assuming txn has been processed before.\n");
return UpdateAnonTransaction(ptxdb, tx, blockHash);
};
return error("%s: Found duplicate anon output.", __func__);
};
ao = CAnonOutput(outpoint, txout.nValue, nBlockHeight, 0);
if (!ptxdb->WriteAnonOutput(pkCoin, ao))
{
LogPrintf("%s: WriteAnonOutput failed.\n", __func__);
continue;
};
mapAnonOutputStats[txout.nValue].addCoin(nBlockHeight, txout.nValue);
memcpy(&vchEphemPK[0], &s[2+EC_COMPRESSED_SIZE+2], EC_COMPRESSED_SIZE);
bool fHaveSpendKey = false;
bool fOwnOutput = false;
CPubKey cpkE;
data_chunk pkScan;
std::string sSxAddr;
for (std::set<CStealthAddress>::iterator it = stealthAddresses.begin(); it != stealthAddresses.end(); ++it)
{
if (it->scan_secret.size() != EC_SECRET_SIZE)
continue; // stealth address is not owned
memcpy(&sScan.e[0], &it->scan_secret[0], EC_SECRET_SIZE);
if (StealthSecret(sScan, vchEphemPK, it->spend_pubkey, sShared, pkExtracted) != 0)
{
LogPrintf("StealthSecret failed.\n");
continue;
};
cpkE = CPubKey(pkExtracted);
if (!cpkE.IsValid()
|| cpkE != pkCoin)
continue;
pkScan = it->scan_pubkey;
sSxAddr = it->Encoded();
if (!IsLocked())
{
if (it->spend_secret.size() != EC_SECRET_SIZE)
{
LogPrintf("%s: Found anon tx to sx key %s which contains no spend secret.\n", __func__, sSxAddr.c_str());
continue;
// - next iter here, stop processing (fOwnOutput not set)
};
memcpy(&sSpend.e[0], &it->spend_secret[0], EC_SECRET_SIZE);
if (StealthSharedToSecretSpend(sShared, sSpend, sSpendR) != 0)
{
LogPrintf("%s: StealthSharedToSecretSpend() failed.\n", __func__);
continue;
};
fHaveSpendKey = true;
};
fOwnOutput = true;
break;
};
// - check ext account stealth keys
ExtKeyAccountMap::const_iterator mi;
if (!fOwnOutput)
for (mi = mapExtAccounts.begin(); mi != mapExtAccounts.end(); ++mi)
{
CExtKeyAccount *ea = mi->second;
for (AccStealthKeyMap::iterator it = ea->mapStealthKeys.begin(); it != ea->mapStealthKeys.end(); ++it)
{
const CEKAStealthKey &aks = it->second;
if (!aks.skScan.IsValid())
continue;
memcpy(&sScan.e[0], aks.skScan.begin(), EC_SECRET_SIZE);
if (StealthSecret(sScan, vchEphemPK, aks.pkSpend, sShared, pkExtracted) != 0)
{
LogPrintf("%s: StealthSecret failed.\n", __func__);
continue;
};
CPubKey cpkE(pkExtracted);
if (!cpkE.IsValid()
|| cpkE != pkCoin)
continue;
pkScan = aks.pkScan;
sSxAddr = aks.ToStealthAddress();
if (!ea->IsLocked(aks))
{
CKey kChild;
if (0 != ea->ExpandStealthChildKey(&aks, sShared, kChild))
{
LogPrintf("%s: ExpandStealthChildKey failed.\n", __func__);
// - carry on, account could be crypted separately
} else
{
memcpy(&sSpendR.e[0], kChild.begin(), EC_SECRET_SIZE);
fHaveSpendKey = true;
};
} else
{
if (fDebug)
LogPrintf("Chain %d of %s IsLocked.\n", aks.akSpend.nParent, ea->GetIDString58());
};
fOwnOutput = true;
break;
};
if (fOwnOutput)
break;
};
if (!fOwnOutput)
continue;
if (fDebugRingSig)
LogPrintf("anon output match tx, no %s, %u\n", txnHash.GetHex().c_str(), i);
fIsMine = true; // mark tx to be added to wallet
int lenENarr = 0;
if (s.size() > MIN_ANON_OUT_SIZE)
lenENarr = s[2+EC_COMPRESSED_SIZE+1 + EC_COMPRESSED_SIZE+1];
if (lenENarr > 0)
{
if (fDebugRingSig)
LogPrintf("Processing encrypted narration of %d bytes\n", lenENarr);
try { vchENarr.resize(lenENarr); } catch (std::exception& e)
{
LogPrintf("%s: Error: vchENarr.resize threw: %s.\n", __func__, e.what());
continue;
};
memcpy(&vchENarr[0], &s[2+EC_COMPRESSED_SIZE+1+EC_COMPRESSED_SIZE+2], lenENarr);
SecMsgCrypter crypter;
crypter.SetKey(&sShared.e[0], &vchEphemPK[0]);
std::vector<uint8_t> vchNarr;
if (!crypter.Decrypt(&vchENarr[0], vchENarr.size(), vchNarr))
{
LogPrintf("%s: Decrypt narration failed.\n", __func__);
continue;
};
std::string sNarr = std::string(vchNarr.begin(), vchNarr.end());
snprintf(cbuf, sizeof(cbuf), "n_%u", i);
mapNarr[cbuf] = sNarr;
};
if (!fHaveSpendKey)
{
std::vector<uint8_t> vchEmpty;
CWalletDB *pwalletdbEncryptionOld = pwalletdbEncryption;
pwalletdbEncryption = pwdb; // HACK, pass pdb to AddCryptedKey
AddCryptedKey(cpkE, vchEmpty);
pwalletdbEncryption = pwalletdbEncryptionOld;
if (fDebugRingSig)
LogPrintf("Wallet locked, adding key without secret.\n");
std::string sLabel = std::string("ao ") + sSxAddr.substr(0, 16) + "...";
SetAddressBookName(ckCoinId, sLabel, pwdb, false);
CPubKey cpkEphem(vchEphemPK);
CPubKey cpkScan(pkScan);
CLockedAnonOutput lockedAo(cpkEphem, cpkScan, COutPoint(txnHash, i));
if (!pwdb->WriteLockedAnonOutput(ckCoinId, lockedAo))
{
CBitcoinAddress coinAddress(ckCoinId);
LogPrintf("%s: WriteLockedAnonOutput failed for %s.\n", __func__, coinAddress.ToString().c_str());
};
} else
{
ec_point pkTestSpendR;
if (SecretToPublicKey(sSpendR, pkTestSpendR) != 0)
{
LogPrintf("%s: SecretToPublicKey() failed.\n", __func__);
continue;
};
CKey ckey;
ckey.Set(&sSpendR.e[0], true);
if (!ckey.IsValid())
{
LogPrintf("%s: Reconstructed key is invalid.\n", __func__);
continue;
};
CPubKey cpkT = ckey.GetPubKey();
if (!cpkT.IsValid()
|| cpkT != pkCoin)
{
LogPrintf("%s: cpkT is invalid.\n", __func__);
continue;
};
if (fDebugRingSig)
{
CBitcoinAddress coinAddress(ckCoinId);
LogPrintf("Adding key %s.\n", coinAddress.ToString().c_str());
};
if (!AddKeyInDBTxn(pwdb, ckey))
{
LogPrintf("%s: AddKeyInDBTxn failed.\n", __func__);
continue;
};
// TODO: groupings?
std::string sLabel = std::string("ao ") + sSxAddr.substr(0, 16) + "...";
SetAddressBookName(ckCoinId, sLabel, pwdb, false);
// -- store keyImage
ec_point pkImage;
ec_point pkOldImage;
getOldKeyImage(pkCoin, pkOldImage);
if (generateKeyImage(pkTestSpendR, sSpendR, pkImage) != 0)
{
LogPrintf("%s: generateKeyImage() failed.\n", __func__);
continue;
}
CKeyImageSpent kis;
bool fInMemPool;
bool fSpentAOut = false;
// shouldn't be possible for kis to be in mempool here
fSpentAOut = (GetKeyImage(ptxdb, pkImage, kis, fInMemPool)
||GetKeyImage(ptxdb, pkOldImage, kis, fInMemPool));
COwnedAnonOutput oao(outpoint, fSpentAOut);
if (!pwdb->WriteOwnedAnonOutput(pkImage, oao)
||!pwdb->WriteOldOutputLink(pkOldImage, pkImage)
||!pwdb->WriteOwnedAnonOutputLink(pkCoin, pkImage))
{
LogPrintf("%s: WriteOwnedAnonOutput() failed.\n", __func__);
continue;
};
if (fDebugRingSig)
LogPrintf("Adding anon output to wallet: %s.\n", HexStr(pkImage).c_str());
};
};
return true;
};
bool CWallet::GetAnonChangeAddress(CStealthAddress &sxAddress)
{
// return owned stealth address to send anon change to.
// TODO: make an option
// NOTE: tries default ext account only, for now
ExtKeyAccountMap::iterator mi = mapExtAccounts.find(idDefaultAccount);
if (mi != mapExtAccounts.end())
{
CExtKeyAccount *ea = mi->second;
AccStealthKeyMap::iterator it = ea->mapStealthKeys.begin();
if (it != ea->mapStealthKeys.end())
return (0 == it->second.SetSxAddr(sxAddress));
};
std::set<CStealthAddress>::iterator it;
for (it = stealthAddresses.begin(); it != stealthAddresses.end(); ++it)
{
if (it->scan_secret.size() < 1)
continue; // stealth address is not owned
sxAddress = *it;
return true;
};
return false;
};
bool CWallet::CreateStealthOutput(CStealthAddress* sxAddress, int64_t nValue, std::string& sNarr, std::vector<std::pair<CScript, int64_t> >& vecSend, std::map<int, std::string>& mapNarr, std::string& sError)
{
if (fDebugRingSig)
LogPrintf("CreateStealthOutput()\n");
if (!sxAddress)
{
sError = "!sxAddress, todo.";
return false;
};
ec_secret ephem_secret;
ec_secret secretShared;
ec_point pkSendTo;
ec_point ephem_pubkey;
if (GenerateRandomSecret(ephem_secret) != 0)
{
sError = "GenerateRandomSecret failed.";
return false;
};
if (StealthSecret(ephem_secret, sxAddress->scan_pubkey, sxAddress->spend_pubkey, secretShared, pkSendTo) != 0)
{
sError = "Could not generate receiving public key.";
return false;
};
CPubKey cpkTo(pkSendTo);
if (!cpkTo.IsValid())
{
sError = "Invalid public key generated.";
return false;
};
CKeyID ckidTo = cpkTo.GetID();
CBitcoinAddress addrTo(ckidTo);
if (SecretToPublicKey(ephem_secret, ephem_pubkey) != 0)
{
sError = "Could not generate ephem public key.";
return false;
};
if (fDebug)
{
LogPrintf("CreateStealthOutput() to generated pubkey %u: %s\n", pkSendTo.size(), HexStr(pkSendTo).c_str());
LogPrintf("hash %s\n", addrTo.ToString().c_str());
LogPrintf("ephem_pubkey %u: %s\n", ephem_pubkey.size(), HexStr(ephem_pubkey).c_str());
};
std::vector<unsigned char> vchENarr;
if (sNarr.length() > 0)
{
SecMsgCrypter crypter;
crypter.SetKey(&secretShared.e[0], &ephem_pubkey[0]);
if (!crypter.Encrypt((uint8_t*)&sNarr[0], sNarr.length(), vchENarr))
{
sError = "Narration encryption failed.";
return false;
};
if (vchENarr.size() > MAX_STEALTH_NARRATION_SIZE)
{
sError = "Encrypted narration is too long.";
return false;
};
};
CScript scriptPubKey;
scriptPubKey.SetDestination(addrTo.Get());
vecSend.push_back(make_pair(scriptPubKey, nValue));
CScript scriptP = CScript() << OP_RETURN << ephem_pubkey;
if (vchENarr.size() > 0)
scriptP = scriptP << OP_RETURN << vchENarr;
vecSend.push_back(make_pair(scriptP, 0));
// TODO: shuffle change later?
if (vchENarr.size() > 0)
{
for (unsigned int k = 0; k < vecSend.size(); ++k)
{
if (vecSend[k].first != scriptPubKey
|| vecSend[k].second != nValue)
continue;
mapNarr[k] = sNarr;
break;
};
};
return true;
};
bool CWallet::CreateAnonOutputs(CStealthAddress* sxAddress, int64_t nValue, std::string& sNarr, std::vector<std::pair<CScript, int64_t> >& vecSend, CScript& scriptNarration)
{
if (fDebugRingSig)
LogPrintf("CreateAnonOutputs()\n");
ec_secret scEphem;
ec_secret scShared;
ec_point pkSendTo;
ec_point pkEphem;
CPubKey cpkTo;
// -- output scripts OP_RETURN ANON_TOKEN pkTo R enarr
// Each outputs split from the amount must go to a unique pk, or the key image would be the same
// Only the first output of the group carries the enarr (if present)
std::vector<int64_t> vOutAmounts;
if (splitAmount(nValue, vOutAmounts) != 0)
{
LogPrintf("splitAmount() failed.\n");
return false;
};
for (uint32_t i = 0; i < vOutAmounts.size(); ++i)
{
if (GenerateRandomSecret(scEphem) != 0)
{
LogPrintf("GenerateRandomSecret failed.\n");
return false;
};
if (sxAddress) // NULL for test only
{
if (StealthSecret(scEphem, sxAddress->scan_pubkey, sxAddress->spend_pubkey, scShared, pkSendTo) != 0)
{
LogPrintf("Could not generate receiving public key.\n");
return false;
};
cpkTo = CPubKey(pkSendTo);
if (!cpkTo.IsValid())
{
LogPrintf("Invalid public key generated.\n");
return false;
};
if (SecretToPublicKey(scEphem, pkEphem) != 0)
{
LogPrintf("Could not generate ephem public key.\n");
return false;
};
};
CScript scriptSendTo;
scriptSendTo.push_back(OP_RETURN);
scriptSendTo.push_back(OP_ANON_MARKER);
scriptSendTo << cpkTo;
scriptSendTo << pkEphem;
if (i == 0 && sNarr.length() > 0)
{
std::vector<unsigned char> vchNarr;
SecMsgCrypter crypter;
crypter.SetKey(&scShared.e[0], &pkEphem[0]);
if (!crypter.Encrypt((uint8_t*)&sNarr[0], sNarr.length(), vchNarr))
{
LogPrintf("Narration encryption failed.\n");
return false;
};
if (vchNarr.size() > MAX_STEALTH_NARRATION_SIZE)
{
LogPrintf("Encrypted narration is too long.\n");
return false;
};
scriptSendTo << vchNarr;
scriptNarration = scriptSendTo;
};
if (fDebug)
{
CKeyID ckidTo = cpkTo.GetID();
CBitcoinAddress addrTo(ckidTo);
LogPrintf("CreateAnonOutput to generated pubkey %u: %s\n", pkSendTo.size(), HexStr(pkSendTo).c_str());
if (!sxAddress)
LogPrintf("Test Mode\n");
LogPrintf("hash %s\n", addrTo.ToString().c_str());
LogPrintf("ephemeral pubkey %u: %s\n", pkEphem.size(), HexStr(pkEphem).c_str());
LogPrintf("scriptPubKey %s\n", scriptSendTo.ToString().c_str());
};
vecSend.push_back(make_pair(scriptSendTo, vOutAmounts[i]));
};
// TODO: will this be optimised away?
memset(&scShared.e[0], 0, EC_SECRET_SIZE);
return true;
};
static bool checkCombinations(int64_t nReq, int m, std::vector<COwnedAnonOutput*>& vData, std::vector<int>& vecInputIndex)
{
// -- m of n combinations, check smallest coins first
if (fDebugRingSig)
LogPrintf("checkCombinations() %d, %u\n", m, vData.size());
int nOwnedAnonOutputs = vData.size();
try { vecInputIndex.resize(m); } catch (std::exception& e)
{
LogPrintf("Error: checkCombinations() v.resize(%d) threw: %s.\n", m, e.what());
return false;
};
int64_t nCount = 0;
if (m > nOwnedAnonOutputs) // ERROR
{
LogPrintf("Error: checkCombinations() m > nOwnedAnonOutputs\n");
return false;
};
int i, l, startL = 0;
// -- pick better start point
// lAvailableCoins is sorted, if coin i * m < nReq, no combinations of lesser coins will be < either
for (l = m; l <= nOwnedAnonOutputs; ++l)
{
if (vData[l-1]->nValue * m < nReq)
continue;
startL = l;
break;
};
if (fDebugRingSig)
LogPrintf("Starting at level %d\n", startL);
if (startL == 0)
{
LogPrintf("checkCombinations() No possible combinations.\n");
return false;
};
for (l = startL; l <= nOwnedAnonOutputs; ++l)
{
for (i = 0; i < m; ++i)
vecInputIndex[i] = (m - i)-1;
vecInputIndex[0] = l-1;
// -- m must be > 2 to use coarse seeking
bool fSeekFine = m <= 2;
if(fDebugRingSig)
LogPrintf("coarse seek: %d, vecInputIndex[1]: %d, vecInputIndex[0]-1: %d\n", !fSeekFine, vecInputIndex[1], vecInputIndex[0]-1);
// -- coarse
while(!fSeekFine && vecInputIndex[1] < vecInputIndex[0]-1)
{
for (i = 1; i < m; ++i)
vecInputIndex[i] = vecInputIndex[i]+1;
int64_t nTotal = 0;
for (i = 0; i < m; ++i)
nTotal += vData[vecInputIndex[i]]->nValue;
if(fDebugRingSig)
LogPrintf("coarse seeking - nTotal: %d\n", nTotal);
nCount++;
if (nTotal == nReq)
{
if (fDebugRingSig)
{
LogPrintf("Found match of total %d, in %d tries, ", nTotal, nCount);
for (i = m; i--;) LogPrintf("%d%c", vecInputIndex[i], i ? ' ': '\n');
};
return true;
};
if (nTotal > nReq)
{
for (i = 1; i < m; ++i) // rewind
vecInputIndex[i] = vecInputIndex[i]-1;
if (fDebugRingSig)
{
LogPrintf("Found coarse match of total %d, in %d tries\n", nTotal, nCount);
for (i = m; i--;) LogPrintf("%d%c", vecInputIndex[i], i ? ' ': '\n');
};
fSeekFine = true;
};
};
if (!fSeekFine && l < nOwnedAnonOutputs)
continue;
// -- fine
i = m-1;
for (;;)
{
if (vecInputIndex[0] == l-1) // otherwise get duplicate combinations
{
int64_t nTotal = 0;
for (i = 0; i < m; ++i)
nTotal += vData[vecInputIndex[i]]->nValue;
if(fDebugRingSig)
LogPrintf("fine seeking - nTotal: %d\n", nTotal);
nCount++;
if (nTotal >= nReq)
{
if (fDebugRingSig)
{
LogPrintf("Found match of total %d, in %d tries\n", nTotal, nCount);
for (i = m; i--;) LogPrintf("%d%c", vecInputIndex[i], i ? ' ': '\n');
};
return true;
};
if (fDebugRingSig && !(nCount % 500))
{
LogPrintf("checkCombinations() nCount: %d - l: %d, nOwnedAnonOutputs: %d, m: %d, i: %d, nReq: %d, v[0]: %d, nTotal: %d \n", nCount, l, nOwnedAnonOutputs, m, i, nReq, vecInputIndex[0], nTotal);
for (i = m; i--;) LogPrintf("%d%c", vecInputIndex[i], i ? ' ': '\n');
};
};
for (i = 0; vecInputIndex[i] >= l - i;) // 0 is largest element
{
if (++i >= m)
goto EndInner;
};
// -- fill the set with the next values
for (vecInputIndex[i]++; i; i--)
vecInputIndex[i-1] = vecInputIndex[i] + 1;
};
EndInner:
if (i+1 > nOwnedAnonOutputs)
break;
};
return false;
}
int CWallet::PickAnonInputs(int rsType, int64_t nValue, int64_t& nFee, int nRingSize, CWalletTx& wtxNew, int nOutputs, int nSizeOutputs, int& nExpectChangeOuts, std::list<COwnedAnonOutput>& lAvailableCoins, std::vector<COwnedAnonOutput*>& vPickedCoins, std::vector<std::pair<CScript, int64_t> >& vecChange, bool fTest, std::string& sError)
{
if (fDebugRingSig)
LogPrintf("PickAnonInputs(), ChangeOuts %d\n", nExpectChangeOuts);
// - choose the smallest coin that can cover the amount + fee
// or least no. of smallest coins
int64_t nAmountCheck = 0;
std::vector<COwnedAnonOutput*> vData;
try { vData.resize(lAvailableCoins.size()); } catch (std::exception& e)
{
LogPrintf("Error: PickAnonInputs() vData.resize threw: %s.\n", e.what());
return false;
};
uint32_t vi = 0;
for (std::list<COwnedAnonOutput>::iterator it = lAvailableCoins.begin(); it != lAvailableCoins.end(); ++it)
{
vData[vi++] = &(*it);
nAmountCheck += it->nValue;
};
uint32_t nByteSizePerInCoin;
switch(rsType)
{
case RING_SIG_1:
nByteSizePerInCoin = (sizeof(COutPoint) + sizeof(unsigned int)) // CTxIn
+ GetSizeOfCompactSize(2 + (33 + 32 + 32) * nRingSize)
+ 2 + (33 + 32 + 32) * nRingSize;
break;
case RING_SIG_2:
nByteSizePerInCoin = (sizeof(COutPoint) + sizeof(unsigned int)) // CTxIn
+ GetSizeOfCompactSize(2 + 32 + (33 + 32) * nRingSize)
+ 2 + 32 + (33 + 32) * nRingSize;
break;
default:
sError = "Unknown ring signature type.";
return false;
};
if (fDebugRingSig)
LogPrintf("nByteSizePerInCoin: %d\n", nByteSizePerInCoin);
// -- repeat until all levels are tried (1 coin, 2 coins, 3 coins etc)
for (uint32_t i = 0; i < lAvailableCoins.size(); ++i)
{
if (fDebugRingSig)
LogPrintf("Input loop %u\n", i);
uint32_t nTotalBytes = (4 + 4 + 4) // Ctx: nVersion, nTime, nLockTime
+ GetSizeOfCompactSize(nOutputs + nExpectChangeOuts)
+ nSizeOutputs
+ (GetSizeOfCompactSize(MIN_ANON_OUT_SIZE) + MIN_ANON_OUT_SIZE + sizeof(int64_t)) * nExpectChangeOuts
+ GetSizeOfCompactSize((i+1))
+ nByteSizePerInCoin * (i+1);
nFee = wtxNew.GetMinFee(0, GMF_ANON, nTotalBytes);
if (fDebugRingSig)
LogPrintf("nValue + nFee: %d, nValue: %d, nAmountCheck: %d, nTotalBytes: %u\n", nValue + nFee, nValue, nAmountCheck, nTotalBytes);
if (nValue + nFee > nAmountCheck)
{
sError = "Not enough mature coins with requested ring size.";
return 3;
};
vPickedCoins.clear();
vecChange.clear();
std::vector<int> vecInputIndex;
if (checkCombinations(nValue + nFee, i+1, vData, vecInputIndex))
{
if (fDebugRingSig)
{
LogPrintf("Found combination %u, ", i+1);
for (int ic = vecInputIndex.size(); ic--;)
LogPrintf("%d%c", vecInputIndex[ic], ic ? ' ': '\n');
LogPrintf("nTotalBytes %u\n", nTotalBytes);
LogPrintf("nFee %d\n", nFee);
};
int64_t nTotalIn = 0;
vPickedCoins.resize(vecInputIndex.size());
for (uint32_t ic = 0; ic < vecInputIndex.size(); ++ic)
{
vPickedCoins[ic] = vData[vecInputIndex[ic]];
nTotalIn += vPickedCoins[ic]->nValue;
};
int64_t nChange = nTotalIn - (nValue + nFee);
CStealthAddress sxChange;
if (!GetAnonChangeAddress(sxChange))
{
sError = "GetAnonChangeAddress() change failed.";
return 3;
};
std::string sNone;
sNone.clear();
CScript scriptNone;
if (!CreateAnonOutputs(fTest ? NULL : &sxChange, nChange, sNone, vecChange, scriptNone))
{
sError = "CreateAnonOutputs() change failed.";
return 3;
};
// -- get nTotalBytes again, using actual no. of change outputs
uint32_t nTotalBytes = (4 + 4 + 4) // Ctx: nVersion, nTime, nLockTime
+ GetSizeOfCompactSize(nOutputs + vecChange.size())
+ nSizeOutputs
+ (GetSizeOfCompactSize(MIN_ANON_OUT_SIZE) + MIN_ANON_OUT_SIZE + sizeof(int64_t)) * vecChange.size()
+ GetSizeOfCompactSize((i+1))
+ nByteSizePerInCoin * (i+1);
int64_t nTestFee = wtxNew.GetMinFee(0, GMF_ANON, nTotalBytes);
if (nTestFee > nFee)
{
if (fDebugRingSig)
LogPrintf("Try again - nTestFee > nFee %d, %d, nTotalBytes %u\n", nTestFee, nFee, nTotalBytes);
nExpectChangeOuts = vecChange.size();
return 2; // up changeOutSize
};
nFee = nTestFee;
return 1; // found
};
};
return 0; // not found
};
int CWallet::GetTxnPreImage(CTransaction& txn, uint256& hash)
{
CHashWriter ss(SER_GETHASH, PROTOCOL_VERSION);
ss << txn.nVersion;
ss << txn.nTime;
for (uint32_t i = 0; i < txn.vin.size(); ++i)
{
const CTxIn& txin = txn.vin[i];
ss << txin.prevout; // keyimage only
int ringSize = txin.ExtractRingSize();
// TODO: is it neccessary to include the ring members in the hash?
if (txin.scriptSig.size() < 2 + ringSize * EC_COMPRESSED_SIZE)
{
LogPrintf("scriptSig is too small, input %u, ring size %d.\n", i, ringSize);
return 1;
};
ss.write((const char*)&txin.scriptSig[2], ringSize * EC_COMPRESSED_SIZE);
};
for (uint32_t i = 0; i < txn.vout.size(); ++i)
ss << txn.vout[i];
ss << txn.nLockTime;
hash = ss.GetHash();
return 0;
};
int CWallet::PickHidingOutputs(int64_t nValue, int nRingSize, CPubKey& pkCoin, int skip, uint8_t* p)
{
if (fDebug)
LogPrintf("PickHidingOutputs() %d, %d\n", nValue, nRingSize);
// TODO: process multiple inputs in 1 db loop?
// -- offset skip is pre filled with the real coin
LOCK(cs_main);
CTxDB txdb("r");
leveldb::DB* pdb = txdb.GetInstance();
if (!pdb)
throw runtime_error("CWallet::PickHidingOutputs() : cannot get leveldb instance");
leveldb::Iterator *iterator = pdb->NewIterator(leveldb::ReadOptions());
std::vector<CPubKey> vHideKeys;
// Seek to start key.
CPubKey pkZero;
pkZero.SetZero();
CDataStream ssStartKey(SER_DISK, CLIENT_VERSION);
ssStartKey << make_pair(string("ao"), pkZero);
iterator->Seek(ssStartKey.str());
CPubKey pkAo;
CAnonOutput anonOutput;
while (iterator->Valid())
{
// Unpack keys and values.
CDataStream ssKey(SER_DISK, CLIENT_VERSION);
ssKey.write(iterator->key().data(), iterator->key().size());
string strType;
ssKey >> strType;
if (strType != "ao")
break;
CDataStream ssValue(SER_DISK, CLIENT_VERSION);
ssValue.write(iterator->value().data(), iterator->value().size());
ssKey >> pkAo;
if (pkAo != pkCoin
&& pkAo.IsValid())
{
ssValue >> anonOutput;
if ((anonOutput.nBlockHeight > 0 && nBestHeight - anonOutput.nBlockHeight >= MIN_ANON_SPEND_DEPTH)
&& anonOutput.nValue == nValue
&& anonOutput.nCompromised == 0)
try { vHideKeys.push_back(pkAo); } catch (std::exception& e)
{
LogPrintf("Error: PickHidingOutputs() vHideKeys.push_back threw: %s.\n", e.what());
return 1;
}
}
iterator->Next();
};
delete iterator;
if ((int)vHideKeys.size() < nRingSize-1)
return errorN(1, "%s: Not enough keys found.", __func__);
for (int i = 0; i < nRingSize; ++i)
{
if (i == skip)
continue;
if (vHideKeys.size() < 1)
return errorN(1, "%s: vHideKeys.size() < 1", __func__);
uint32_t pick = GetRand(vHideKeys.size());
memcpy(p + i * 33, vHideKeys[pick].begin(), 33);
vHideKeys.erase(vHideKeys.begin()+pick);
};
return 0;
};
bool CWallet::AreOutputsUnique(CWalletTx& wtxNew)
{
LOCK(cs_main);
CTxDB txdb;
for (uint32_t i = 0; i < wtxNew.vout.size(); ++i)
{
const CTxOut& txout = wtxNew.vout[i];
if (txout.IsAnonOutput())
continue;
const CScript &s = txout.scriptPubKey;
CPubKey pkCoin = CPubKey(&s[2+1], EC_COMPRESSED_SIZE);
CAnonOutput ao;
if (txdb.ReadAnonOutput(pkCoin, ao))
{
//LogPrintf("AreOutputsUnique() pk %s is not unique.\n", pkCoin);
return false;
};
};
return true;
};
static int GetRingSigSize(int rsType, int nRingSize)
{
switch(rsType)
{
case RING_SIG_1:
return 2 + (EC_COMPRESSED_SIZE + EC_SECRET_SIZE + EC_SECRET_SIZE) * nRingSize;
case RING_SIG_2:
return 2 + EC_SECRET_SIZE + (EC_COMPRESSED_SIZE + EC_SECRET_SIZE) * nRingSize;
default:
LogPrintf("Unknown ring signature type.\n");
return 0;
};
};
static uint8_t *GetRingSigPkStart(int rsType, int nRingSize, uint8_t *pStart)
{
switch(rsType)
{
case RING_SIG_1:
return pStart + 2;
case RING_SIG_2:
return pStart + 2 + EC_SECRET_SIZE + EC_SECRET_SIZE * nRingSize;
default:
LogPrintf("Unknown ring signature type.\n");
return 0;
};
}
bool CWallet::AddAnonInputs(int rsType, int64_t nTotalOut, int nRingSize, std::vector<std::pair<CScript, int64_t> >&vecSend, std::vector<std::pair<CScript, int64_t> >&vecChange, CWalletTx& wtxNew, int64_t& nFeeRequired, bool fTestOnly, std::string& sError)
{
if (fDebugRingSig)
LogPrintf("AddAnonInputs() %d, %d, rsType:%d\n", nTotalOut, nRingSize, rsType);
std::list<COwnedAnonOutput> lAvailableCoins;
if (ListUnspentAnonOutputs(lAvailableCoins, true) != 0)
{
sError = "ListUnspentAnonOutputs() failed";
return false;
};
std::map<int64_t, int> mOutputCounts;
for (std::list<COwnedAnonOutput>::iterator it = lAvailableCoins.begin(); it != lAvailableCoins.end(); ++it)
mOutputCounts[it->nValue] = 0;
if (CountAnonOutputs(mOutputCounts, true) != 0)
{
sError = "CountAnonOutputs() failed";
return false;
};
if (fDebugRingSig)
{
for (std::map<int64_t, int>::iterator it = mOutputCounts.begin(); it != mOutputCounts.end(); ++it)
LogPrintf("mOutputCounts %ld %d\n", it->first, it->second);
};
int64_t nAmountCheck = 0;
// -- remove coins that don't have enough same value anonoutputs in the system for the ring size
std::list<COwnedAnonOutput>::iterator it = lAvailableCoins.begin();
while (it != lAvailableCoins.end())
{
std::map<int64_t, int>::iterator mi = mOutputCounts.find(it->nValue);
if (mi == mOutputCounts.end()
|| mi->second < nRingSize)
{
// -- not enough coins of same value, drop coin
lAvailableCoins.erase(it++);
continue;
};
nAmountCheck += it->nValue;
++it;
};
if (fDebugRingSig)
LogPrintf("%u coins available with ring size %d, total %d\n", lAvailableCoins.size(), nRingSize, nAmountCheck);
// -- estimate fee
uint32_t nSizeOutputs = 0;
for (uint32_t i = 0; i < vecSend.size(); ++i) // need to sum due to narration
nSizeOutputs += GetSizeOfCompactSize(vecSend[i].first.size()) + vecSend[i].first.size() + sizeof(int64_t); // CTxOut
bool fFound = false;
int64_t nFee;
int nExpectChangeOuts = 1;
std::string sPickError;
std::vector<COwnedAnonOutput*> vPickedCoins;
for (int k = 0; k < 50; ++k) // safety
{
// -- nExpectChangeOuts is raised if needed (rv == 2)
int rv = PickAnonInputs(rsType, nTotalOut, nFee, nRingSize, wtxNew, vecSend.size(), nSizeOutputs, nExpectChangeOuts, lAvailableCoins, vPickedCoins, vecChange, false, sPickError);
if (rv == 0)
break;
if (rv == 3)
{
nFeeRequired = nFee; // set in PickAnonInputs()
sError = sPickError;
return false;
};
if (rv == 1)
{
fFound = true;
break;
};
};
if (!fFound)
{
sError = "No combination of coins matches amount and ring size.";
return false;
};
nFeeRequired = nFee; // set in PickAnonInputs()
int nSigSize = GetRingSigSize(rsType, nRingSize);
// -- need hash of tx without signatures
std::vector<int> vCoinOffsets;
uint32_t ii = 0;
wtxNew.vin.resize(vPickedCoins.size());
vCoinOffsets.resize(vPickedCoins.size());
for (std::vector<COwnedAnonOutput*>::iterator it = vPickedCoins.begin(); it != vPickedCoins.end(); ++it)
{
CTxIn& txin = wtxNew.vin[ii];
if (fDebugRingSig)
LogPrintf("pickedCoin %s %d\n", HexStr((*it)->vchImage).c_str(), (*it)->nValue);
// -- overload prevout to hold keyImage
memcpy(txin.prevout.hash.begin(), &(*it)->vchImage[0], EC_SECRET_SIZE);
txin.prevout.n = 0 | (((*it)->vchImage[32]) & 0xFF) | (int32_t)(((int16_t) nRingSize) << 16);
// -- size for full signature, signature is added later after hash
try { txin.scriptSig.resize(nSigSize); } catch (std::exception& e)
{
LogPrintf("Error: AddAnonInputs() txin.scriptSig.resize threw: %s.\n", e.what());
sError = "resize failed.\n";
return false;
};
txin.scriptSig[0] = OP_RETURN;
txin.scriptSig[1] = OP_ANON_MARKER;
if (fTestOnly)
continue;
int nCoinOutId = (*it)->outpoint.n;
WalletTxMap::iterator mi = mapWallet.find((*it)->outpoint.hash);
if (mi == mapWallet.end()
|| mi->second.nVersion != ANON_TXN_VERSION
|| (int)mi->second.vout.size() < nCoinOutId)
{
LogPrintf("Error: AddAnonInputs() picked coin not in wallet, %s version %d.\n", (*it)->outpoint.hash.ToString().c_str(), (*mi).second.nVersion);
sError = "picked coin not in wallet.\n";
return false;
};
CWalletTx& wtxAnonCoin = mi->second;
const CTxOut& txout = wtxAnonCoin.vout[nCoinOutId];
const CScript &s = txout.scriptPubKey;
if (!txout.IsAnonOutput())
{
sError = "picked coin not an anon output.\n";
return false;
};
CPubKey pkCoin = CPubKey(&s[2+1], EC_COMPRESSED_SIZE);
if (!pkCoin.IsValid())
{
sError = "pkCoin is invalid.\n";
return false;
};
vCoinOffsets[ii] = GetRand(nRingSize);
uint8_t *pPubkeyStart = GetRingSigPkStart(rsType, nRingSize, &txin.scriptSig[0]);
memcpy(pPubkeyStart + vCoinOffsets[ii] * EC_COMPRESSED_SIZE, pkCoin.begin(), EC_COMPRESSED_SIZE);
if (PickHidingOutputs((*it)->nValue, nRingSize, pkCoin, vCoinOffsets[ii], pPubkeyStart) != 0)
{
sError = "PickHidingOutputs() failed.\n";
return false;
};
ii++;
};
for (uint32_t i = 0; i < vecSend.size(); ++i)
wtxNew.vout.push_back(CTxOut(vecSend[i].second, vecSend[i].first));
for (uint32_t i = 0; i < vecChange.size(); ++i)
wtxNew.vout.push_back(CTxOut(vecChange[i].second, vecChange[i].first));
std::sort(wtxNew.vout.begin(), wtxNew.vout.end());
if (fTestOnly)
return true;
uint256 preimage;
if (GetTxnPreImage(wtxNew, preimage) != 0)
{
sError = "GetPreImage() failed.\n";
return false;
};
// TODO: Does it lower security to use the same preimage for each input?
// cryptonote seems to do so too
for (uint32_t i = 0; i < wtxNew.vin.size(); ++i)
{
CTxIn& txin = wtxNew.vin[i];
// Test
std::vector<uint8_t> vchImageTest;
txin.ExtractKeyImage(vchImageTest);
int nTestRingSize = txin.ExtractRingSize();
if (nTestRingSize != nRingSize)
{
sError = "nRingSize embed error.";
return false;
};
if (txin.scriptSig.size() < nSigSize)
{
sError = "Error: scriptSig too small.";
return false;
};
int nSecretOffset = vCoinOffsets[i];
uint8_t *pPubkeyStart = GetRingSigPkStart(rsType, nRingSize, &txin.scriptSig[0]);
// -- get secret
CPubKey pkCoin = CPubKey(pPubkeyStart + EC_COMPRESSED_SIZE * nSecretOffset, EC_COMPRESSED_SIZE);
CKeyID pkId = pkCoin.GetID();
CKey key;
if (!GetKey(pkId, key))
{
sError = "Error: don't have key for output.";
return false;
};
ec_secret ecSecret;
if (key.size() != EC_SECRET_SIZE)
{
sError = "Error: key.size() != EC_SECRET_SIZE.";
return false;
};
memcpy(&ecSecret.e[0], key.begin(), key.size());
switch(rsType)
{
case RING_SIG_1:
{
uint8_t *pPubkeys = &txin.scriptSig[2];
uint8_t *pSigc = &txin.scriptSig[2 + EC_COMPRESSED_SIZE * nRingSize];
uint8_t *pSigr = &txin.scriptSig[2 + (EC_COMPRESSED_SIZE + EC_SECRET_SIZE) * nRingSize];
if (generateRingSignature(vchImageTest, preimage, nRingSize, nSecretOffset, ecSecret, pPubkeys, pSigc, pSigr) != 0)
{
sError = "Error: generateRingSignature() failed.";
return false;
};
// -- test verify
if (verifyRingSignature(vchImageTest, preimage, nRingSize, pPubkeys, pSigc, pSigr) != 0)
{
sError = "Error: verifyRingSignature() failed.";
return false;
};
}
break;
case RING_SIG_2:
{
ec_point pSigC;
uint8_t *pSigS = &txin.scriptSig[2 + EC_SECRET_SIZE];
uint8_t *pPubkeys = &txin.scriptSig[2 + EC_SECRET_SIZE + EC_SECRET_SIZE * nRingSize];
if (generateRingSignatureAB(vchImageTest, preimage, nRingSize, nSecretOffset, ecSecret, pPubkeys, pSigC, pSigS) != 0)
{
sError = "Error: generateRingSignatureAB() failed.";
return false;
};
if (pSigC.size() == EC_SECRET_SIZE)
memcpy(&txin.scriptSig[2], &pSigC[0], EC_SECRET_SIZE);
else
LogPrintf("pSigC.size() : %d Invalid!!\n", pSigC.size());
// -- test verify
if (verifyRingSignatureAB(vchImageTest, preimage, nRingSize, pPubkeys, pSigC, pSigS) != 0)
{
sError = "Error: verifyRingSignatureAB() failed.";
return false;
};
}
break;
default:
sError = "Unknown ring signature type.";
return false;
};
memset(&ecSecret.e[0], 0, EC_SECRET_SIZE); // optimised away?
};
// -- check if new coins already exist (in case random is broken ?)
if (!AreOutputsUnique(wtxNew))
{
sError = "Error: Anon outputs are not unique - is random working!.";
return false;
};
return true;
};
bool CWallet::SendSdcToAnon(CStealthAddress& sxAddress, int64_t nValue, std::string& sNarr, CWalletTx& wtxNew, std::string& sError, bool fAskFee)
{
if (fDebugRingSig)
LogPrintf("SendSdcToAnon()\n");
if (IsLocked())
{
sError = _("Error: Wallet locked, unable to create transaction.");
return false;
};
if (nNodeMode != NT_FULL)
{
sError = _("Error: Must be in full mode.");
return false;
};
if (fWalletUnlockStakingOnly)
{
sError = _("Error: Wallet unlocked for staking, unable to create transaction.");
return false;
};
if (nBestHeight < GetNumBlocksOfPeers()-1)
{
sError = _("Error: Block chain must be fully synced first.");
return false;
};
if (vNodes.empty())
{
sError = _("Error: ShadowCoin is not connected!");
return false;
};
// -- Check amount
if (nValue <= 0)
{
sError = "Invalid amount";
return false;
};
if (nValue + nTransactionFee > GetBalance())
{
sError = "Insufficient funds";
return false;
};
wtxNew.nVersion = ANON_TXN_VERSION;
CScript scriptNarration; // needed to match output id of narr
std::vector<std::pair<CScript, int64_t> > vecSend;
if (!CreateAnonOutputs(&sxAddress, nValue, sNarr, vecSend, scriptNarration))
{
sError = "CreateAnonOutputs() failed.";
return false;
};
// -- shuffle outputs
std::random_shuffle(vecSend.begin(), vecSend.end());
int64_t nFeeRequired;
int nChangePos;
if (!CreateTransaction(vecSend, wtxNew, nFeeRequired, nChangePos, NULL))
{
sError = "CreateTransaction() failed.";
return false;
};
if (scriptNarration.size() > 0)
{
for (uint32_t k = 0; k < wtxNew.vout.size(); ++k)
{
if (wtxNew.vout[k].scriptPubKey != scriptNarration)
continue;
char key[64];
if (snprintf(key, sizeof(key), "n_%u", k) < 1)
{
sError = "Error creating narration key.";
return false;
};
wtxNew.mapValue[key] = sNarr;
break;
};
};
if (fAskFee && !uiInterface.ThreadSafeAskFee(nFeeRequired, _("Sending...")))
{
sError = "ABORTED";
return false;
};
// -- check if new coins already exist (in case random is broken ?)
if (!AreOutputsUnique(wtxNew))
{
sError = "Error: Anon outputs are not unique - is random working!.";
return false;
};
if (!CommitTransaction(wtxNew))
{
sError = "Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.";
UndoAnonTransaction(wtxNew);
return false;
};
return true;
};
bool CWallet::SendAnonToAnon(CStealthAddress& sxAddress, int64_t nValue, int nRingSize, std::string& sNarr, CWalletTx& wtxNew, std::string& sError, bool fAskFee)
{
if (fDebugRingSig)
LogPrintf("SendAnonToAnon()\n");
if (IsLocked())
{
sError = _("Error: Wallet locked, unable to create transaction.");
return false;
};
if (nNodeMode != NT_FULL)
{
sError = _("Error: Must be in full mode.");
return false;
};
if (fWalletUnlockStakingOnly)
{
sError = _("Error: Wallet unlocked for staking only, unable to create transaction.");
return false;
};
if (nBestHeight < GetNumBlocksOfPeers()-1)
{
sError = _("Error: Block chain must be fully synced first.");
return false;
};
if (vNodes.empty())
{
sError = _("Error: ShadowCoin is not connected!");
return false;
};
// -- Check amount
if (nValue <= 0)
{
sError = "Invalid amount";
return false;
};
if (nValue + nTransactionFee > GetShadowBalance())
{
sError = "Insufficient shadow funds";
return false;
};
wtxNew.nVersion = ANON_TXN_VERSION;
CScript scriptNarration; // needed to match output id of narr
std::vector<std::pair<CScript, int64_t> > vecSend;
std::vector<std::pair<CScript, int64_t> > vecChange;
if (!CreateAnonOutputs(&sxAddress, nValue, sNarr, vecSend, scriptNarration))
{
sError = "CreateAnonOutputs() failed.";
return false;
};
// -- shuffle outputs (any point?)
//std::random_shuffle(vecSend.begin(), vecSend.end());
int64_t nFeeRequired;
std::string sError2;
if (!AddAnonInputs(nRingSize == 1 ? RING_SIG_1 : RING_SIG_2, nValue, nRingSize, vecSend, vecChange, wtxNew, nFeeRequired, false, sError2))
{
LogPrintf("SendAnonToAnon() AddAnonInputs failed %s.\n", sError2.c_str());
sError = "AddAnonInputs() failed : " + sError2;
return false;
};
if (scriptNarration.size() > 0)
{
for (uint32_t k = 0; k < wtxNew.vout.size(); ++k)
{
if (wtxNew.vout[k].scriptPubKey != scriptNarration)
continue;
char key[64];
if (snprintf(key, sizeof(key), "n_%u", k) < 1)
{
sError = "Error creating narration key.";
return false;
};
wtxNew.mapValue[key] = sNarr;
break;
};
};
if (!CommitTransaction(wtxNew))
{
sError = "Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.";
UndoAnonTransaction(wtxNew);
return false;
};
return true;
};
bool CWallet::SendAnonToSdc(CStealthAddress& sxAddress, int64_t nValue, int nRingSize, std::string& sNarr, CWalletTx& wtxNew, std::string& sError, bool fAskFee)
{
if (fDebug)
LogPrintf("SendAnonToSdc()\n");
if (IsLocked())
{
sError = _("Error: Wallet locked, unable to create transaction.");
return false;
};
if (nNodeMode != NT_FULL)
{
sError = _("Error: Must be in full mode.");
return false;
};
if (fWalletUnlockStakingOnly)
{
sError = _("Error: Wallet unlocked for staking only, unable to create transaction.");
return false;
};
if (nBestHeight < GetNumBlocksOfPeers()-1)
{
sError = _("Error: Block chain must be fully synced first.");
return false;
};
if (vNodes.empty())
{
sError = _("Error: ShadowCoin is not connected!");
return false;
};
// -- Check amount
if (nValue <= 0)
{
sError = "Invalid amount";
return false;
};
if (nValue + nTransactionFee > GetShadowBalance())
{
sError = "Insufficient shadow funds";
return false;
};
wtxNew.nVersion = ANON_TXN_VERSION;
std::vector<std::pair<CScript, int64_t> > vecSend;
std::vector<std::pair<CScript, int64_t> > vecChange;
std::map<int, std::string> mapStealthNarr;
if (!CreateStealthOutput(&sxAddress, nValue, sNarr, vecSend, mapStealthNarr, sError))
{
LogPrintf("SendCoinsAnon() CreateStealthOutput failed %s.\n", sError.c_str());
return false;
};
std::map<int, std::string>::iterator itN;
for (itN = mapStealthNarr.begin(); itN != mapStealthNarr.end(); ++itN)
{
int pos = itN->first;
char key[64];
if (snprintf(key, sizeof(key), "n_%u", pos) < 1)
{
LogPrintf("SendCoinsAnon(): Error creating narration key.");
continue;
};
wtxNew.mapValue[key] = itN->second;
};
// -- get anon inputs
int64_t nFeeRequired;
std::string sError2;
if (!AddAnonInputs(nRingSize == 1 ? RING_SIG_1 : RING_SIG_2, nValue, nRingSize, vecSend, vecChange, wtxNew, nFeeRequired, false, sError2))
{
LogPrintf("SendAnonToSdc() AddAnonInputs failed %s.\n", sError2.c_str());
sError = "AddAnonInputs() failed: " + sError2;
return false;
};
if (!CommitTransaction(wtxNew))
{
sError = "Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.";
UndoAnonTransaction(wtxNew);
return false;
};
return true;
};
bool CWallet::ExpandLockedAnonOutput(CWalletDB *pwdb, CKeyID &ckeyId, CLockedAnonOutput &lao, std::set<uint256> &setUpdated)
{
if (fDebugRingSig)
{
CBitcoinAddress addrTo(ckeyId);
LogPrintf("%s %s\n", __func__, addrTo.ToString().c_str());
AssertLockHeld(cs_main);
AssertLockHeld(cs_wallet);
};
CStealthAddress sxFind;
sxFind.SetScanPubKey(lao.pkScan);
bool fFound = false;
ec_secret sSpendR;
ec_secret sSpend;
ec_secret sScan;
ec_point pkEphem;
std::set<CStealthAddress>::iterator si = stealthAddresses.find(sxFind);
if (si != stealthAddresses.end())
{
fFound = true;
if (si->spend_secret.size() != EC_SECRET_SIZE
|| si->scan_secret .size() != EC_SECRET_SIZE)
return error("%s: Stealth address has no secret.", __func__);
memcpy(&sScan.e[0], &si->scan_secret[0], EC_SECRET_SIZE);
memcpy(&sSpend.e[0], &si->spend_secret[0], EC_SECRET_SIZE);
pkEphem.resize(lao.pkEphem.size());
memcpy(&pkEphem[0], lao.pkEphem.begin(), lao.pkEphem.size());
if (StealthSecretSpend(sScan, pkEphem, sSpend, sSpendR) != 0)
return error("%s: StealthSecretSpend() failed.", __func__);
};
// - check ext account stealth keys
ExtKeyAccountMap::const_iterator mi;
if (!fFound)
for (mi = mapExtAccounts.begin(); mi != mapExtAccounts.end(); ++mi)
{
fFound = true;
CExtKeyAccount *ea = mi->second;
CKeyID sxId = lao.pkScan.GetID();
AccStealthKeyMap::const_iterator miSk = ea->mapStealthKeys.find(sxId);
if (miSk == ea->mapStealthKeys.end())
continue;
const CEKAStealthKey &aks = miSk->second;
if (ea->IsLocked(aks))
return error("%s: Stealth is locked.", __func__);
ec_point pkExtracted;
ec_secret sShared;
pkEphem.resize(lao.pkEphem.size());
memcpy(&pkEphem[0], lao.pkEphem.begin(), lao.pkEphem.size());
memcpy(&sScan.e[0], aks.skScan.begin(), EC_SECRET_SIZE);
// - need sShared to extract key
if (StealthSecret(sScan, pkEphem, aks.pkSpend, sShared, pkExtracted) != 0)
return error("%s: StealthSecret() failed.", __func__);
CKey kChild;
if (0 != ea->ExpandStealthChildKey(&aks, sShared, kChild))
return error("%s: ExpandStealthChildKey() failed %s.", __func__, aks.ToStealthAddress().c_str());
memcpy(&sSpendR.e[0], kChild.begin(), EC_SECRET_SIZE);
};
if (!fFound)
return error("%s: No stealth key found.", __func__);
ec_point pkTestSpendR;
if (SecretToPublicKey(sSpendR, pkTestSpendR) != 0)
return error("%s: SecretToPublicKey() failed.", __func__);
CKey ckey;
ckey.Set(&sSpendR.e[0], true);
if (!ckey.IsValid())
return error("%s: Reconstructed key is invalid.", __func__);
CPubKey pkCoin = ckey.GetPubKey(true);
if (!pkCoin.IsValid())
return error("%s: pkCoin is invalid.", __func__);
CKeyID keyIDTest = pkCoin.GetID();
if (keyIDTest != ckeyId)
{
LogPrintf("%s: Error: Generated secret does not match.\n", __func__);
if (fDebugRingSig)
{
LogPrintf("test %s\n", keyIDTest.ToString().c_str());
LogPrintf("gen %s\n", ckeyId.ToString().c_str());
};
return false;
};
if (fDebugRingSig)
{
CBitcoinAddress coinAddress(keyIDTest);
LogPrintf("Adding secret to key %s.\n", coinAddress.ToString().c_str());
};
if (!AddKeyInDBTxn(pwdb, ckey))
return error("%s: AddKeyInDBTxn failed.", __func__);
// -- store keyimage
ec_point pkImage;
ec_point pkOldImage;
getOldKeyImage(pkCoin, pkOldImage);
if (generateKeyImage(pkTestSpendR, sSpendR, pkImage) != 0)
return error("%s: generateKeyImage failed.", __func__);
bool fSpentAOut = false;
setUpdated.insert(lao.outpoint.hash);
{
// -- check if this output is already spent
CTxDB txdb;
CKeyImageSpent kis;
bool fInMemPool;
CAnonOutput ao;
txdb.ReadAnonOutput(pkCoin, ao);
if ((GetKeyImage(&txdb, pkImage, kis, fInMemPool) && !fInMemPool)
||(GetKeyImage(&txdb, pkOldImage, kis, fInMemPool) && !fInMemPool)) // shouldn't be possible for kis to be in mempool here
{
fSpentAOut = true;
WalletTxMap::iterator miw = mapWallet.find(lao.outpoint.hash);
if (miw != mapWallet.end())
{
CWalletTx& wtx = (*miw).second;
wtx.MarkSpent(lao.outpoint.n);
if (!pwdb->WriteTx(lao.outpoint.hash, wtx))
return error("%s: WriteTx %s failed.", __func__, wtx.ToString().c_str());
wtx.MarkDirty();
};
};
} // txdb
COwnedAnonOutput oao(lao.outpoint, fSpentAOut);
if (!pwdb->WriteOwnedAnonOutput(pkImage, oao)
||!pwdb->WriteOldOutputLink(pkOldImage, pkImage)
||!pwdb->WriteOwnedAnonOutputLink(pkCoin, pkImage))
{
return error("%s: WriteOwnedAnonOutput() failed.", __func__);
};
if (fDebugRingSig)
LogPrintf("Adding anon output to wallet: %s.\n", HexStr(pkImage).c_str());
return true;
};
bool CWallet::ProcessLockedAnonOutputs()
{
if (fDebugRingSig)
{
LogPrintf("%s\n", __func__);
AssertLockHeld(cs_main);
AssertLockHeld(cs_wallet);
};
// -- process owned anon outputs received when wallet was locked.
std::set<uint256> setUpdated;
CWalletDB walletdb(strWalletFile, "cr+");
walletdb.TxnBegin();
Dbc *pcursor = walletdb.GetTxnCursor();
if (!pcursor)
throw runtime_error(strprintf("%s : cannot create DB cursor.", __func__).c_str());
unsigned int fFlags = DB_SET_RANGE;
while (true)
{
// Read next record
CDataStream ssKey(SER_DISK, CLIENT_VERSION);
if (fFlags == DB_SET_RANGE)
ssKey << std::string("lao");
CDataStream ssValue(SER_DISK, CLIENT_VERSION);
int ret = walletdb.ReadAtCursor(pcursor, ssKey, ssValue, fFlags);
fFlags = DB_NEXT;
if (ret == DB_NOTFOUND)
{
break;
} else
if (ret != 0)
{
pcursor->close();
throw runtime_error(strprintf("%s : error scanning DB.", __func__).c_str());
};
// Unserialize
string strType;
ssKey >> strType;
if (strType != "lao")
break;
CLockedAnonOutput lockedAnonOutput;
CKeyID ckeyId;
ssKey >> ckeyId;
ssValue >> lockedAnonOutput;
if (ExpandLockedAnonOutput(&walletdb, ckeyId, lockedAnonOutput, setUpdated))
{
if ((ret = pcursor->del(0)) != 0)
LogPrintf("%s : Delete failed %d, %s\n", __func__, ret, db_strerror(ret));
};
};
pcursor->close();
walletdb.TxnCommit();
std::set<uint256>::iterator it;
for (it = setUpdated.begin(); it != setUpdated.end(); ++it)
{
WalletTxMap::iterator miw = mapWallet.find(*it);
if (miw == mapWallet.end())
continue;
CWalletTx& wtx = (*miw).second;
wtx.MarkDirty();
wtx.fDebitCached = 2; // force update
NotifyTransactionChanged(this, *it, CT_UPDATED);
};
return true;
};
bool CWallet::EstimateAnonFee(int64_t nValue, int nRingSize, std::string& sNarr, CWalletTx& wtxNew, int64_t& nFeeRet, std::string& sError)
{
if (fDebugRingSig)
LogPrintf("EstimateAnonFee()\n");
if (nNodeMode != NT_FULL)
{
sError = _("Error: Must be in full mode.");
return false;
};
nFeeRet = 0;
// -- Check amount
if (nValue <= 0)
{
sError = "Invalid amount";
return false;
};
if (nValue + nTransactionFee > GetShadowBalance())
{
sError = "Insufficient shadow funds";
return false;
};
CScript scriptNarration; // needed to match output id of narr
std::vector<std::pair<CScript, int64_t> > vecSend;
std::vector<std::pair<CScript, int64_t> > vecChange;
if (!CreateAnonOutputs(NULL, nValue, sNarr, vecSend, scriptNarration))
{
sError = "CreateAnonOutputs() failed.";
return false;
};
int64_t nFeeRequired;
if (!AddAnonInputs(RING_SIG_2, nValue, nRingSize, vecSend, vecChange, wtxNew, nFeeRequired, true, sError))
{
LogPrintf("EstimateAnonFee() AddAnonInputs failed %s.\n", sError.c_str());
sError = "AddAnonInputs() failed.";
return false;
};
nFeeRet = nFeeRequired;
return true;
};
int CWallet::ListUnspentAnonOutputs(std::list<COwnedAnonOutput>& lUAnonOutputs, bool fMatureOnly)
{
CWalletDB walletdb(strWalletFile, "r");
Dbc* pcursor = walletdb.GetAtCursor();
if (!pcursor)
throw runtime_error("CWallet::ListUnspentAnonOutputs() : cannot create DB cursor");
unsigned int fFlags = DB_SET_RANGE;
while (true)
{
// Read next record
CDataStream ssKey(SER_DISK, CLIENT_VERSION);
if (fFlags == DB_SET_RANGE)
ssKey << std::string("oao");
CDataStream ssValue(SER_DISK, CLIENT_VERSION);
int ret = walletdb.ReadAtCursor(pcursor, ssKey, ssValue, fFlags);
fFlags = DB_NEXT;
if (ret == DB_NOTFOUND)
{
break;
} else
if (ret != 0)
{
pcursor->close();
throw runtime_error("CWallet::ListUnspentAnonOutputs() : error scanning DB");
};
// Unserialize
string strType;
ssKey >> strType;
if (strType != "oao")
break;
COwnedAnonOutput oao;
ssKey >> oao.vchImage;
ssValue >> oao;
if (oao.fSpent)
continue;
WalletTxMap::iterator mi = mapWallet.find(oao.outpoint.hash);
if (mi == mapWallet.end()
|| mi->second.nVersion != ANON_TXN_VERSION
|| mi->second.vout.size() <= oao.outpoint.n
|| mi->second.IsSpent(oao.outpoint.n))
continue;
// -- txn must be in MIN_ANON_SPEND_DEPTH deep in the blockchain to be spent
if (fMatureOnly
&& mi->second.GetDepthInMainChain() < MIN_ANON_SPEND_DEPTH)
{
continue;
};
// TODO: check ReadAnonOutput?
oao.nValue = mi->second.vout[oao.outpoint.n].nValue;
// -- insert by nValue asc
bool fInserted = false;
for (std::list<COwnedAnonOutput>::iterator it = lUAnonOutputs.begin(); it != lUAnonOutputs.end(); ++it)
{
if (oao.nValue > it->nValue)
continue;
lUAnonOutputs.insert(it, oao);
fInserted = true;
break;
};
if (!fInserted)
lUAnonOutputs.push_back(oao);
};
pcursor->close();
return 0;
}
int CWallet::CountAnonOutputs(std::map<int64_t, int>& mOutputCounts, bool fMatureOnly)
{
LOCK(cs_main);
CTxDB txdb("r");
leveldb::DB* pdb = txdb.GetInstance();
if (!pdb)
throw runtime_error("CWallet::CountAnonOutputs() : cannot get leveldb instance");
leveldb::Iterator *iterator = pdb->NewIterator(leveldb::ReadOptions());
// Seek to start key.
CPubKey pkZero;
pkZero.SetZero();
CDataStream ssStartKey(SER_DISK, CLIENT_VERSION);
ssStartKey << make_pair(string("ao"), pkZero);
iterator->Seek(ssStartKey.str());
while (iterator->Valid())
{
// Unpack keys and values.
CDataStream ssKey(SER_DISK, CLIENT_VERSION);
ssKey.write(iterator->key().data(), iterator->key().size());
string strType;
ssKey >> strType;
if (strType != "ao")
break;
CDataStream ssValue(SER_DISK, CLIENT_VERSION);
ssValue.write(iterator->value().data(), iterator->value().size());
CAnonOutput anonOutput;
ssValue >> anonOutput;
if ((!fMatureOnly
||(anonOutput.nBlockHeight > 0 && nBestHeight - anonOutput.nBlockHeight >= MIN_ANON_SPEND_DEPTH))
&& (Params().IsProtocolV3(nBestHeight) ? anonOutput.nCompromised == 0 : true))
{
std::map<int64_t, int>::iterator mi = mOutputCounts.find(anonOutput.nValue);
if (mi != mOutputCounts.end())
mi->second++;
};
iterator->Next();
};
delete iterator;
return 0;
};
int CWallet::CountAllAnonOutputs(std::list<CAnonOutputCount>& lOutputCounts, bool fMatureOnly)
{
if (fDebugRingSig)
LogPrintf("CountAllAnonOutputs()\n");
// TODO: there are few enough possible coin values to preinitialise a vector with all of them
LOCK(cs_main);
CTxDB txdb("r");
leveldb::DB* pdb = txdb.GetInstance();
if (!pdb)
throw runtime_error("CWallet::CountAnonOutputs() : cannot get leveldb instance");
leveldb::Iterator *iterator = pdb->NewIterator(leveldb::ReadOptions());
// Seek to start key.
CPubKey pkZero;
pkZero.SetZero();
CDataStream ssStartKey(SER_DISK, CLIENT_VERSION);
ssStartKey << make_pair(string("ao"), pkZero);
iterator->Seek(ssStartKey.str());
while (iterator->Valid())
{
// Unpack keys and values.
CDataStream ssKey(SER_DISK, CLIENT_VERSION);
ssKey.write(iterator->key().data(), iterator->key().size());
string strType;
ssKey >> strType;
if (strType != "ao")
break;
CDataStream ssValue(SER_DISK, CLIENT_VERSION);
ssValue.write(iterator->value().data(), iterator->value().size());
CAnonOutput ao;
ssValue >> ao;
if (strType != "ao")
break;
int nHeight = ao.nBlockHeight > 0 ? nBestHeight - ao.nBlockHeight : 0;
if (fMatureOnly
&& nHeight < MIN_ANON_SPEND_DEPTH)
{
// -- skip
} else
{
// -- insert by nValue asc
bool fProcessed = false;
for (std::list<CAnonOutputCount>::iterator it = lOutputCounts.begin(); it != lOutputCounts.end(); ++it)
{
if (ao.nValue == it->nValue)
{
it->nExists++;
it->nCompromised += ao.nCompromised;
if (it->nLeastDepth > nHeight)
it->nLeastDepth = nHeight;
fProcessed = true;
break;
};
if (ao.nValue > it->nValue)
continue;
lOutputCounts.insert(it, CAnonOutputCount(ao.nValue, 1, 0, 0, nHeight, ao.nCompromised));
fProcessed = true;
break;
};
if (!fProcessed)
lOutputCounts.push_back(CAnonOutputCount(ao.nValue, 1, 0, 0, nHeight, ao.nCompromised));
};
iterator->Next();
};
delete iterator;
// -- count spends
iterator = pdb->NewIterator(leveldb::ReadOptions());
ssStartKey.clear();
ssStartKey << make_pair(string("ki"), pkZero);
iterator->Seek(ssStartKey.str());
while (iterator->Valid())
{
CDataStream ssKey(SER_DISK, CLIENT_VERSION);
ssKey.write(iterator->key().data(), iterator->key().size());
string strType;
ssKey >> strType;
if (strType != "ki")
break;
CDataStream ssValue(SER_DISK, CLIENT_VERSION);
ssValue.write(iterator->value().data(), iterator->value().size());
CKeyImageSpent kis;
ssValue >> kis;
bool fProcessed = false;
for (std::list<CAnonOutputCount>::iterator it = lOutputCounts.begin(); it != lOutputCounts.end(); ++it)
{
if (kis.nValue != it->nValue)
continue;
it->nSpends++;
fProcessed = true;
break;
};
if (!fProcessed)
LogPrintf("WARNING: CountAllAnonOutputs found keyimage without matching anon output value.\n");
iterator->Next();
};
delete iterator;
return 0;
};
int CWallet::CountOwnedAnonOutputs(std::map<int64_t, int>& mOwnedOutputCounts, bool fMatureOnly)
{
if (fDebugRingSig)
LogPrintf("CountOwnedAnonOutputs()\n");
CWalletDB walletdb(strWalletFile, "r");
Dbc* pcursor = walletdb.GetAtCursor();
if (!pcursor)
throw runtime_error("CWallet::CountOwnedAnonOutputs() : cannot create DB cursor");
unsigned int fFlags = DB_SET_RANGE;
while (true)
{
// Read next record
CDataStream ssKey(SER_DISK, CLIENT_VERSION);
if (fFlags == DB_SET_RANGE)
ssKey << std::string("oao");
CDataStream ssValue(SER_DISK, CLIENT_VERSION);
int ret = walletdb.ReadAtCursor(pcursor, ssKey, ssValue, fFlags);
fFlags = DB_NEXT;
if (ret == DB_NOTFOUND)
{
break;
} else
if (ret != 0)
{
pcursor->close();
throw runtime_error("CWallet::CountOwnedAnonOutputs() : error scanning DB");
};
// Unserialize
string strType;
ssKey >> strType;
if (strType != "oao")
break;
COwnedAnonOutput oao;
ssKey >> oao.vchImage;
ssValue >> oao;
if (oao.fSpent)
continue;
WalletTxMap::iterator mi = mapWallet.find(oao.outpoint.hash);
if (mi == mapWallet.end()
|| mi->second.nVersion != ANON_TXN_VERSION
|| mi->second.vout.size() <= oao.outpoint.n
|| mi->second.IsSpent(oao.outpoint.n))
continue;
//LogPrintf("[rem] mi->second.GetDepthInMainChain() %d \n", mi->second.GetDepthInMainChain());
//LogPrintf("[rem] mi->second.hashBlock %s \n", mi->second.hashBlock.ToString().c_str());
// -- txn must be in MIN_ANON_SPEND_DEPTH deep in the blockchain to be spent
{
LOCK(cs_main);
if (fMatureOnly
&& mi->second.GetDepthInMainChain() < MIN_ANON_SPEND_DEPTH)
{
continue;
};
}
// TODO: check ReadAnonOutput?
oao.nValue = mi->second.vout[oao.outpoint.n].nValue;
mOwnedOutputCounts[oao.nValue]++;
};
pcursor->close();
return 0;
};
bool CWallet::EraseAllAnonData()
{
LogPrintf("EraseAllAnonData()\n");
int64_t nStart = GetTimeMillis();
LOCK2(cs_main, cs_wallet);
CWalletDB walletdb(strWalletFile, "r+");
CTxDB txdb("r+");
uint32_t nAo = 0;
uint32_t nKi = 0;
LogPrintf("Erasing anon outputs.\n");
txdb.EraseRange(std::string("ao"), nAo);
LogPrintf("Erasing spent key images.\n");
txdb.EraseRange(std::string("ki"), nKi);
uint32_t nLao = 0;
uint32_t nOao = 0;
uint32_t nOal = 0;
uint32_t nOol = 0;
LogPrintf("Erasing locked anon outputs.\n");
walletdb.EraseRange(std::string("lao"), nLao);
LogPrintf("Erasing owned anon outputs.\n");
walletdb.EraseRange(std::string("oao"), nOao);
LogPrintf("Erasing anon output links.\n");
walletdb.EraseRange(std::string("oal"), nOal);
LogPrintf("Erasing old output links.\n");
walletdb.EraseRange(std::string("ool"), nOol);
LogPrintf("EraseAllAnonData() Complete, %d %d %d %d %d %d, %15dms\n", nAo, nKi, nLao, nOao, nOal, nOol, GetTimeMillis() - nStart);
return true;
};
bool CWallet::CacheAnonStats()
{
if (fDebugRingSig)
LogPrintf("CacheAnonStats()\n");
mapAnonOutputStats.clear();
std::list<CAnonOutputCount> lOutputCounts;
if (CountAllAnonOutputs(lOutputCounts, false) != 0)
{
LogPrintf("Error: CountAllAnonOutputs() failed.\n");
return false;
};
for (std::list<CAnonOutputCount>::iterator it = lOutputCounts.begin(); it != lOutputCounts.end(); ++it)
{
mapAnonOutputStats[it->nValue].set(
it->nValue, it->nExists, it->nSpends, it->nOwned,
it->nLeastDepth < 1 ? 0 : nBestHeight - it->nLeastDepth, it->nCompromised); // mapAnonOutputStats stores height in chain instead of depth
};
return true;
};
bool CWallet::InitBloomFilter()
{
if (fDebug)
LogPrintf("Initialising bloom filter, max elements %d.\n", nBloomFilterElements);
LOCK(cs_wallet);
if (pBloomFilter)
return error("Bloom filter already created.");
char nFlags = BLOOM_UPDATE_ALL;
if (nLocalRequirements & THIN_STEALTH)
nFlags |= BLOOM_ACCEPT_STEALTH;
pBloomFilter = new CBloomFilter(nBloomFilterElements, 0.001, GetRandUInt32(), nFlags);
if (!pBloomFilter)
return error("Bloom filter new failed.");
if (!pBloomFilter->IsWithinSizeConstraints())
{
delete pBloomFilter;
pBloomFilter = NULL;
return error("Bloom filter is too large.");
};
std::string sAnonPrefix("ao ");
// TODO: don't load addresses created from receiving stealth txns
// TODO: exclude change addresses of spent outputs
std::set<CKeyID> setKeys;
GetKeys(setKeys);
uint32_t nKeysAdded = 0;
// -- need to add change addresses too
BOOST_FOREACH(const CKeyID &keyId, setKeys)
{
// -- don't add keys generated for aonon outputs (marked with label prefix "ao ")
std::map<CTxDestination, std::string>::iterator mi(mapAddressBook.find(keyId));
if (mi != mapAddressBook.end() && mi->second.compare(0, sAnonPrefix.length(), sAnonPrefix) == 0)
{
if (fDebugRingSig)
{
CBitcoinAddress coinAddress(keyId);
LogPrintf("InitBloomFilter() - ignoring key for anon output %s.\n", coinAddress.ToString().c_str());
};
continue;
};
pBloomFilter->UpdateEmptyFull();
if (pBloomFilter->IsFull())
{
// TODO: try resize?
LogPrintf("Error: InitBloomFilter() - Filter is full.\n");
continue; // continue so more messages show in log
};
if (fDebug)
{
CBitcoinAddress coinAddress(keyId);
if (coinAddress.IsValid())
LogPrintf("Adding key: %s.\n", coinAddress.ToString().c_str());
};
std::vector<unsigned char> vData(keyId.begin(), keyId.end());
pBloomFilter->insert(vData);
nKeysAdded++;
};
setKeys.clear();
// - load unspent outputs
uint32_t nOutPointsAdded = 0;
for (WalletTxMap::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
{
CWalletTx& wtx = (*it).second;
// -- add unspent outputs to bloom filters
BOOST_FOREACH(const CTxIn& txin, wtx.vin)
{
if (wtx.nVersion == ANON_TXN_VERSION
&& txin.IsAnonInput())
continue;
WalletTxMap::iterator mi = mapWallet.find(txin.prevout.hash);
if (mi == mapWallet.end())
continue;
CWalletTx& wtxPrev = (*mi).second;
if (txin.prevout.n >= wtxPrev.vout.size())
{
LogPrintf("InitBloomFilter(): bad wtx %s\n", wtxPrev.GetHash().ToString().c_str());
} else
//if (!wtxPrev.IsSpent(txin.prevout.n) && IsMine(wtxPrev.vout[txin.prevout.n]))
if (!wtxPrev.IsSpent(txin.prevout.n))
{
CDataStream stream(SER_NETWORK, PROTOCOL_VERSION);
stream << txin.prevout;
std::vector<unsigned char> vData(stream.begin(), stream.end());
pBloomFilter->insert(vData);
nOutPointsAdded++;
};
};
};
if (fDebug)
{
LogPrintf("Added %u key%s, %u outpoint%s to filter.\n",
nKeysAdded, nKeysAdded != 1 ? "s": "",
nOutPointsAdded, nOutPointsAdded != 1 ? "s": "");
LogPrintf("Filter bytes: %u.\n", pBloomFilter->GetSize());
};
return true;
};
// NovaCoin: get current stake weight posv2
uint64_t CWallet::GetStakeWeight() const
{
// Choose coins to use
int64_t nBalance = GetBalance();
if (nBalance <= nReserveBalance)
return false;
std::vector<const CWalletTx*> vwtxPrev;
set<pair<const CWalletTx*,unsigned int> > setCoins;
int64_t nValueIn = 0;
if (!SelectCoinsForStaking(nBalance - nReserveBalance, GetTime(), setCoins, nValueIn)
|| setCoins.empty())
return false;
uint64_t nWeight = 0;
int64_t nCurrentTime = GetTime();
CTxDB txdb("r");
BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
{
{
LOCK2(cs_main, cs_wallet);
if (nNodeMode == NT_THIN)
{
// -- check txn is in chain
std::map<uint256, CBlockThinIndex*>::iterator mi (mapBlockThinIndex.find(pcoin.first->hashBlock));
if (mi == mapBlockThinIndex.end())
{
if (fThinFullIndex
|| !pindexRear)
continue;
CDiskBlockThinIndex diskindex;
if (!txdb.ReadBlockThinIndex(pcoin.first->hashBlock, diskindex)
|| diskindex.hashNext == 0)
continue;
};
} else
{
CTxIndex txindex;
if (!txdb.ReadTxIndex(pcoin.first->GetHash(), txindex))
continue;
}
}
if (nCurrentTime - pcoin.first->nTime > nStakeMinAge)
nWeight += pcoin.first->vout[pcoin.second].nValue;
};
return nWeight;
}
bool CWallet::CreateCoinStake(unsigned int nBits, int64_t nSearchInterval, int64_t nFees, CTransaction& txNew, CKey& key)
{
CBlockIndex* pindexPrev = pindexBest;
CBigNum bnTargetPerCoinDay;
bnTargetPerCoinDay.SetCompact(nBits);
txNew.vin.clear();
txNew.vout.clear();
// Mark coin stake transaction
CScript scriptEmpty;
scriptEmpty.clear();
txNew.vout.push_back(CTxOut(0, scriptEmpty));
// Choose coins to use
int64_t nBalance = GetBalance();
if (nBalance <= nReserveBalance)
return false;
std::vector<const CWalletTx*> vwtxPrev;
set<pair<const CWalletTx*,unsigned int> > setCoins;
int64_t nValueIn = 0;
// Select coins with suitable depth
if (!SelectCoinsForStaking(nBalance - nReserveBalance, txNew.nTime, setCoins, nValueIn))
return false;
if (setCoins.empty())
return false;
int64_t nCredit = 0;
CScript scriptPubKeyKernel;
CTxDB txdb("r");
BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
{
boost::this_thread::interruption_point();
static int nMaxStakeSearchInterval = 60;
bool fKernelFound = false;
for (unsigned int n=0; n<min(nSearchInterval,(int64_t)nMaxStakeSearchInterval) && !fKernelFound && pindexPrev == pindexBest; n++)
{
boost::this_thread::interruption_point();
// Search backward in time from the given txNew timestamp
// Search nSearchInterval seconds back up to nMaxStakeSearchInterval
COutPoint prevoutStake = COutPoint(pcoin.first->GetHash(), pcoin.second);
int64_t nBlockTime;
if (CheckKernel(pindexPrev, nBits, txNew.nTime - n, prevoutStake, &nBlockTime))
{
// Found a kernel
if (fDebugPoS)
LogPrintf("CreateCoinStake : kernel found\n");
std::vector<valtype> vSolutions;
txnouttype whichType;
CScript scriptPubKeyOut;
scriptPubKeyKernel = pcoin.first->vout[pcoin.second].scriptPubKey;
if (!Solver(scriptPubKeyKernel, whichType, vSolutions))
{
if (fDebugPoS)
LogPrintf("CreateCoinStake : failed to parse kernel\n");
break;
};
if (fDebugPoS)
LogPrintf("CreateCoinStake : parsed kernel type=%d\n", whichType);
if (whichType != TX_PUBKEY && whichType != TX_PUBKEYHASH)
{
if (fDebugPoS)
LogPrintf("CreateCoinStake : no support for kernel type=%d\n", whichType);
break; // only support pay to public key and pay to address
};
if (whichType == TX_PUBKEYHASH) // pay to address type
{
// convert to pay to public key type
if (!GetKey(uint160(vSolutions[0]), key))
{
if (fDebugPoS)
LogPrintf("CreateCoinStake : failed to get key for kernel type=%d\n", whichType);
break; // unable to find corresponding public key
};
scriptPubKeyOut << key.GetPubKey() << OP_CHECKSIG;
};
if (whichType == TX_PUBKEY)
{
valtype& vchPubKey = vSolutions[0];
if (!GetKey(Hash160(vchPubKey), key))
{
if (fDebugPoS)
LogPrintf("CreateCoinStake : failed to get key for kernel type=%d\n", whichType);
break; // unable to find corresponding public key
};
if (key.GetPubKey() != vchPubKey)
{
if (fDebugPoS)
LogPrintf("CreateCoinStake : invalid key for kernel type=%d\n", whichType);
break; // keys mismatch
};
scriptPubKeyOut = scriptPubKeyKernel;
};
txNew.nTime -= n;
txNew.vin.push_back(CTxIn(pcoin.first->GetHash(), pcoin.second));
nCredit += pcoin.first->vout[pcoin.second].nValue;
vwtxPrev.push_back(pcoin.first);
txNew.vout.push_back(CTxOut(0, scriptPubKeyOut));
if (fDebugPoS)
LogPrintf("CreateCoinStake : added kernel type=%d\n", whichType);
fKernelFound = true;
break;
};
};
if (fKernelFound)
break; // if kernel is found stop searching
}
if (nCredit == 0 || nCredit > nBalance - nReserveBalance)
return false;
BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
{
// Attempt to add more inputs
// Only add coins of the same key/address as kernel
if (txNew.vout.size() == 2 && ((pcoin.first->vout[pcoin.second].scriptPubKey == scriptPubKeyKernel || pcoin.first->vout[pcoin.second].scriptPubKey == txNew.vout[1].scriptPubKey))
&& pcoin.first->GetHash() != txNew.vin[0].prevout.hash)
{
int64_t nTimeWeight = GetWeight((int64_t)pcoin.first->nTime, (int64_t)txNew.nTime);
// Stop adding more inputs if already too many inputs
if (txNew.vin.size() >= 100)
break;
// Stop adding more inputs if value is already pretty significant
if (nCredit >= nStakeCombineThreshold)
break;
// Stop adding inputs if reached reserve limit
if (nCredit + pcoin.first->vout[pcoin.second].nValue > nBalance - nReserveBalance)
break;
// Do not add additional significant input
if (pcoin.first->vout[pcoin.second].nValue >= nStakeCombineThreshold)
continue;
// Do not add input that is still too young
if (Params().IsProtocolV3(pindexPrev->nHeight))
{
// properly handled by selection function
}
else
{
if (nTimeWeight < nStakeMinAge)
continue;
}
txNew.vin.push_back(CTxIn(pcoin.first->GetHash(), pcoin.second));
nCredit += pcoin.first->vout[pcoin.second].nValue;
vwtxPrev.push_back(pcoin.first);
};
};
// Calculate coin age reward
{
uint64_t nCoinAge;
CTxDB txdb("r");
if (!txNew.GetCoinAge(txdb, pindexPrev, nCoinAge))
return error("CreateCoinStake : failed to calculate coin age");
int64_t nReward = Params().GetProofOfStakeReward(pindexPrev, nCoinAge, nFees);
if (nReward <= 0)
return false;
nCredit += nReward;
}
if (nCredit >= nStakeSplitThreshold)
txNew.vout.push_back(CTxOut(0, txNew.vout[1].scriptPubKey)); //split stake
// Set output amount
if (txNew.vout.size() == 3)
{
txNew.vout[1].nValue = (nCredit / 2 / CENT) * CENT;
txNew.vout[2].nValue = nCredit - txNew.vout[1].nValue;
} else
txNew.vout[1].nValue = nCredit;
// Sign
int nIn = 0;
BOOST_FOREACH(const CWalletTx* pcoin, vwtxPrev)
{
if (!SignSignature(*this, *pcoin, txNew, nIn++))
return error("CreateCoinStake : failed to sign coinstake");
};
// Limit size
unsigned int nBytes = ::GetSerializeSize(txNew, SER_NETWORK, PROTOCOL_VERSION);
if (nBytes >= MAX_BLOCK_SIZE_GEN/5)
return error("CreateCoinStake : exceeded coinstake size limit");
// Successfully generated coinstake
return true;
}
// Call after CreateTransaction unless you want to abort
bool CWallet::CommitTransaction(CWalletTx& wtxNew)
{
if (!wtxNew.CheckTransaction())
{
LogPrintf("%s: CheckTransaction() failed %s.\n", __func__, wtxNew.GetHash().ToString().c_str());
return false;
};
mapValue_t mapNarr;
FindStealthTransactions(wtxNew, mapNarr);
bool fIsMine = false;
if (wtxNew.nVersion == ANON_TXN_VERSION)
{
LOCK2(cs_main, cs_wallet);
CWalletDB walletdb(strWalletFile, "cr+");
CTxDB txdb("cr+");
walletdb.TxnBegin();
txdb.TxnBegin();
std::vector<WalletTxMap::iterator> vUpdatedTxns;
if (!ProcessAnonTransaction(&walletdb, &txdb, wtxNew, wtxNew.hashBlock, fIsMine, mapNarr, vUpdatedTxns))
{
LogPrintf("%s: ProcessAnonTransaction() failed %s.\n", __func__, wtxNew.GetHash().ToString().c_str());
walletdb.TxnAbort();
txdb.TxnAbort();
return false;
} else
{
walletdb.TxnCommit();
txdb.TxnCommit();
for (std::vector<WalletTxMap::iterator>::iterator it = vUpdatedTxns.begin();
it != vUpdatedTxns.end(); ++it)
NotifyTransactionChanged(this, (*it)->first, CT_UPDATED);
};
};
if (!mapNarr.empty())
{
BOOST_FOREACH(const PAIRTYPE(string,string)& item, mapNarr)
wtxNew.mapValue[item.first] = item.second;
};
{
LOCK2(cs_main, cs_wallet);
LogPrintf("%s:\n%s", __func__, wtxNew.ToString().c_str());
{
// This is only to keep the database open to defeat the auto-flush for the
// duration of this scope. This is the only place where this optimization
// maybe makes sense; please don't do it anywhere else.
CWalletDB* pwalletdb = fFileBacked ? new CWalletDB(strWalletFile,"r") : NULL;
// Take key pair from key pool so it won't be used again
//reservekey.KeepKey(); // [rm]
// Add tx to wallet, because if it has change it's also ours,
// otherwise just for transaction history.
uint256 hash = wtxNew.GetHash();
AddToWallet(wtxNew, hash);
// Mark old coins as spent
set<CWalletTx*> setCoins;
BOOST_FOREACH(const CTxIn& txin, wtxNew.vin)
{
if (wtxNew.nVersion == ANON_TXN_VERSION
&& txin.IsAnonInput())
continue;
CWalletTx &coin = mapWallet[txin.prevout.hash];
coin.BindWallet(this);
coin.MarkSpent(txin.prevout.n);
coin.WriteToDisk();
NotifyTransactionChanged(this, coin.GetHash(), CT_UPDATED);
};
if (fFileBacked)
delete pwalletdb;
}
// Track how many getdata requests our transaction gets
mapRequestCount[wtxNew.GetHash()] = 0;
// Broadcast
if (!wtxNew.AcceptToMemoryPool())
{
// This must not fail. The transaction has already been signed and recorded.
LogPrintf("%s: Error: Transaction not valid.\n", __func__);
return false;
};
wtxNew.RelayWalletTransaction();
// - look for new change addresses
BOOST_FOREACH(CTxOut txout, wtxNew.vout)
{
if (wtxNew.nVersion == ANON_TXN_VERSION
&& txout.IsAnonOutput())
continue;
if (IsChange(txout))
{
CTxDestination txoutAddr;
if (!ExtractDestination(txout.scriptPubKey, txoutAddr))
continue;
if (pBloomFilter)
AddKeyToMerkleFilters(txoutAddr);
};
};
} // cs_main, cs_wallet
return true;
}
std::string CWallet::SendMoney(CScript scriptPubKey, int64_t nValue, std::string& sNarr, CWalletTx& wtxNew, bool fAskFee)
{
int64_t nFeeRequired;
if (IsLocked())
{
std::string strError = _("Error: Wallet locked, unable to create transaction ");
LogPrintf("SendMoney() : %s", strError.c_str());
return strError;
};
if (fWalletUnlockStakingOnly)
{
std::string strError = _("Error: Wallet unlocked for staking only, unable to create transaction.");
LogPrintf("SendMoney() : %s", strError.c_str());
return strError;
};
if (!CreateTransaction(scriptPubKey, nValue, sNarr, wtxNew, nFeeRequired))
{
std::string strError;
if (nValue + nFeeRequired > GetBalance())
strError = strprintf(_("Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds "), FormatMoney(nFeeRequired).c_str());
else
strError = _("Error: Transaction creation failed ");
LogPrintf("SendMoney() : %s", strError.c_str());
return strError;
};
if (fAskFee && !uiInterface.ThreadSafeAskFee(nFeeRequired, _("Sending...")))
return "ABORTED";
if (!CommitTransaction(wtxNew))
return _("Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.");
return "";
}
std::string CWallet::SendMoneyToDestination(const CTxDestination& address, int64_t nValue, std::string& sNarr, CWalletTx& wtxNew, bool fAskFee)
{
// Check amount
if (nValue <= 0)
return _("Invalid amount");
if (nValue + nTransactionFee > GetBalance())
return _("Insufficient funds");
if (sNarr.length() > 24)
return _("Narration must be 24 characters or less.");
// Parse Bitcoin address
CScript scriptPubKey;
uint32_t nChildKey;
CExtKeyPair ek;
if (address.type() == typeid(CExtKeyPair))
{
ek = boost::get<CExtKeyPair>(address);
CExtKey58 ek58;
ek58.SetKeyP(ek);
if (0 != ExtKeyGetDestination(ek, scriptPubKey, nChildKey))
return "ExtKeyGetDestination failed.";
} else
scriptPubKey.SetDestination(address);
std::string rv = SendMoney(scriptPubKey, nValue, sNarr, wtxNew, fAskFee);
if (address.type() == typeid(CExtKeyPair) && rv == "")
ExtKeyUpdateLooseKey(ek, nChildKey, true);
return rv;
};
DBErrors CWallet::LoadWallet()
{
if (!fFileBacked)
return DB_LOAD_OK;
DBErrors nLoadWalletRet = CWalletDB(strWalletFile,"cr+").LoadWallet(this);
if (nLoadWalletRet == DB_NEED_REWRITE)
{
if (CDB::Rewrite(strWalletFile, "\x04pool"))
{
LOCK(cs_wallet);
setKeyPool.clear();
// Note: can't top-up keypool here, because wallet is locked.
// User will be prompted to unlock wallet the next operation
// the requires a new key.
};
};
if (nLoadWalletRet != DB_LOAD_OK)
return nLoadWalletRet;
return DB_LOAD_OK;
}
bool CWallet::SetAddressBookName(const CTxDestination& address, const string& strName, CWalletDB *pwdb, bool fAddKeyToMerkleFilters, bool fManual)
{
bool fOwned;
ChangeType nMode;
{
LOCK(cs_wallet); // mapAddressBook
std::map<CTxDestination, std::string>::iterator mi = mapAddressBook.find(address);
nMode = (mi == mapAddressBook.end()) ? CT_NEW : CT_UPDATED;
fOwned = IsDestMine(*this, address);
mapAddressBook[address] = strName;
}
// -- fAddKeyToMerkleFilters is always false when adding keys for anonoutputs
if (fOwned
&& fAddKeyToMerkleFilters)
{
const CBitcoinAddress& caddress = address;
SecureMsgWalletKeyChanged(caddress.ToString(), strName, nMode);
};
if (nMode == CT_NEW
&& pBloomFilter
&& fAddKeyToMerkleFilters)
{
AddKeyToMerkleFilters(address);
};
NotifyAddressBookChanged(this, address, strName, fOwned, nMode, fManual);
if (!fFileBacked)
return false;
if (!pwdb)
return CWalletDB(strWalletFile).WriteName(CBitcoinAddress(address).ToString(), strName);
return pwdb->WriteName(CBitcoinAddress(address).ToString(), strName);
}
bool CWallet::DelAddressBookName(const CTxDestination& address)
{
if (address.type() == typeid(CStealthAddress))
{
const CStealthAddress& sxAddr = boost::get<CStealthAddress>(address);
bool fOwned; // must check on copy from wallet
{
LOCK(cs_wallet);
std::set<CStealthAddress>::iterator si = stealthAddresses.find(sxAddr);
if (si == stealthAddresses.end())
{
LogPrintf("Error: DelAddressBookName() stealth address not found in wallet.\n");
return false;
};
fOwned = si->scan_secret.size() < 32 ? false : true;
if (stealthAddresses.erase(sxAddr) < 1
|| !CWalletDB(strWalletFile).EraseStealthAddress(sxAddr))
{
LogPrintf("Error: DelAddressBookName() remove stealthAddresses failed.\n");
return false;
};
}
NotifyAddressBookChanged(this, address, "", fOwned, CT_DELETED, true);
return true;
};
{
LOCK(cs_wallet); // mapAddressBook
mapAddressBook.erase(address);
}
bool fOwned = IsDestMine(*this, address);
string sName = "";
if (fOwned)
{
const CBitcoinAddress& caddress = address;
SecureMsgWalletKeyChanged(caddress.ToString(), sName, CT_DELETED);
};
NotifyAddressBookChanged(this, address, "", fOwned, CT_DELETED, true);
if (!fFileBacked)
return false;
return CWalletDB(strWalletFile).EraseName(CBitcoinAddress(address).ToString());
}
void CWallet::PrintWallet(const CBlock& block)
{
{
LOCK(cs_wallet);
if (block.IsProofOfWork() && mapWallet.count(block.vtx[0].GetHash()))
{
CWalletTx& wtx = mapWallet[block.vtx[0].GetHash()];
LogPrintf(" mine: %d %d %d", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit());
};
if (block.IsProofOfStake() && mapWallet.count(block.vtx[1].GetHash()))
{
CWalletTx& wtx = mapWallet[block.vtx[1].GetHash()];
LogPrintf(" stake: %d %d %d", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit());
};
}
LogPrintf("\n");
}
bool CWallet::GetTransaction(const uint256 &hashTx, CWalletTx& wtx)
{
{
LOCK(cs_wallet);
WalletTxMap::iterator mi = mapWallet.find(hashTx);
if (mi != mapWallet.end())
{
wtx = (*mi).second;
return true;
};
}
return false;
}
bool CWallet::SetDefaultKey(const CPubKey &vchPubKey)
{
if (fFileBacked)
{
if (!CWalletDB(strWalletFile).WriteDefaultKey(vchPubKey))
return false;
};
vchDefaultKey = vchPubKey;
return true;
}
bool GetWalletFile(CWallet* pwallet, string &strWalletFileOut)
{
if (!pwallet->fFileBacked)
return false;
strWalletFileOut = pwallet->strWalletFile;
return true;
}
//
// Mark old keypool keys as used,
// and generate all new keys
//
bool CWallet::NewKeyPool()
{
{
LOCK(cs_wallet);
CWalletDB walletdb(strWalletFile);
BOOST_FOREACH(int64_t nIndex, setKeyPool)
walletdb.ErasePool(nIndex);
setKeyPool.clear();
if (IsLocked())
return false;
int64_t nKeys = max(GetArg("-keypool", 100), (int64_t)0);
for (int i = 0; i < nKeys; i++)
{
int64_t nIndex = i+1;
walletdb.WritePool(nIndex, CKeyPool(GenerateNewKey()));
setKeyPool.insert(nIndex);
};
LogPrintf("CWallet::NewKeyPool wrote %d new keys\n", nKeys);
}
return true;
}
bool CWallet::TopUpKeyPool(unsigned int nSize)
{
{
LOCK(cs_wallet);
if (IsLocked())
return false;
CWalletDB walletdb(strWalletFile);
// Top up key pool
unsigned int nTargetSize;
if (nSize > 0)
nTargetSize = nSize;
else
nTargetSize = max(GetArg("-keypool", 100), (int64_t)0);
while (setKeyPool.size() < (nTargetSize + 1))
{
int64_t nEnd = 1;
if (!setKeyPool.empty())
nEnd = *(--setKeyPool.end()) + 1;
if (!walletdb.WritePool(nEnd, CKeyPool(GenerateNewKey())))
throw runtime_error("TopUpKeyPool() : writing generated key failed");
setKeyPool.insert(nEnd);
LogPrintf("keypool added key %d, size=%u\n", nEnd, setKeyPool.size());
};
}
return true;
}
void CWallet::ReserveKeyFromKeyPool(int64_t& nIndex, CKeyPool& keypool)
{
assert(false);
nIndex = -1;
keypool.vchPubKey = CPubKey();
{
LOCK(cs_wallet);
if (!IsLocked())
TopUpKeyPool();
// Get the oldest key
if (setKeyPool.empty())
return;
CWalletDB walletdb(strWalletFile);
nIndex = *(setKeyPool.begin());
setKeyPool.erase(setKeyPool.begin());
if (!walletdb.ReadPool(nIndex, keypool))
throw runtime_error("ReserveKeyFromKeyPool() : read failed");
if (!HaveKey(keypool.vchPubKey.GetID()))
throw runtime_error("ReserveKeyFromKeyPool() : unknown key in key pool");
assert(keypool.vchPubKey.IsValid());
if (fDebug && GetBoolArg("-printkeypool"))
LogPrintf("keypool reserve %d\n", nIndex);
}
}
int64_t CWallet::AddReserveKey(const CKeyPool& keypool)
{
{
LOCK2(cs_main, cs_wallet);
CWalletDB walletdb(strWalletFile);
int64_t nIndex = 1 + *(--setKeyPool.end());
if (!walletdb.WritePool(nIndex, keypool))
throw runtime_error("AddReserveKey() : writing added key failed");
setKeyPool.insert(nIndex);
return nIndex;
}
return -1;
}
void CWallet::KeepKey(int64_t nIndex)
{
// Remove from key pool
if (fFileBacked)
{
CWalletDB walletdb(strWalletFile);
walletdb.ErasePool(nIndex);
};
if (fDebug)
LogPrintf("keypool keep %d\n", nIndex);
}
void CWallet::ReturnKey(int64_t nIndex)
{
assert(false); // [rm]
// Return to key pool
{
LOCK(cs_wallet);
setKeyPool.insert(nIndex);
}
if (fDebug)
LogPrintf("keypool return %d\n", nIndex);
}
bool CWallet::GetKeyFromPool(CPubKey& result, bool fAllowReuse)
{
int64_t nIndex = 0;
CKeyPool keypool;
assert(false); // replace with HD
{
LOCK(cs_wallet);
ReserveKeyFromKeyPool(nIndex, keypool);
if (nIndex == -1)
{
if (fAllowReuse && vchDefaultKey.IsValid())
{
result = vchDefaultKey;
return true;
};
if (IsLocked())
return false;
result = GenerateNewKey();
return true;
};
KeepKey(nIndex);
result = keypool.vchPubKey;
}
return true;
}
int64_t CWallet::GetOldestKeyPoolTime()
{
int64_t nIndex = 0;
CKeyPool keypool;
ReserveKeyFromKeyPool(nIndex, keypool);
if (nIndex == -1)
return GetTime();
ReturnKey(nIndex);
return keypool.nTime;
}
std::map<CTxDestination, int64_t> CWallet::GetAddressBalances()
{
std::map<CTxDestination, int64_t> balances;
{
LOCK(cs_wallet);
BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet)
{
CWalletTx *pcoin = &walletEntry.second;
if (!pcoin->IsFinal() || !pcoin->IsTrusted())
continue;
if ((pcoin->IsCoinBase() || pcoin->IsCoinStake()) && pcoin->GetBlocksToMaturity() > 0)
continue;
int nDepth = pcoin->GetDepthInMainChain();
if (nDepth < (pcoin->IsFromMe() ? 0 : 1))
continue;
for (unsigned int i = 0; i < pcoin->vout.size(); i++)
{
CTxDestination addr;
if (!IsMine(pcoin->vout[i]))
continue;
if(!ExtractDestination(pcoin->vout[i].scriptPubKey, addr))
continue;
int64_t n = pcoin->IsSpent(i) ? 0 : pcoin->vout[i].nValue;
if (!balances.count(addr))
balances[addr] = 0;
balances[addr] += n;
}
}
}
return balances;
}
std::set<std::set<CTxDestination> > CWallet::GetAddressGroupings()
{
AssertLockHeld(cs_wallet); // mapWallet
set< set<CTxDestination> > groupings;
set<CTxDestination> grouping;
BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet)
{
CWalletTx *pcoin = &walletEntry.second;
if (pcoin->vin.size() > 0 && IsMine(pcoin->vin[0]))
{
// group all input addresses with each other
BOOST_FOREACH(CTxIn txin, pcoin->vin)
{
CTxDestination address;
if(!ExtractDestination(mapWallet[txin.prevout.hash].vout[txin.prevout.n].scriptPubKey, address))
continue;
grouping.insert(address);
}
// group change with input addresses
BOOST_FOREACH(CTxOut txout, pcoin->vout)
{
if (IsChange(txout))
{
CWalletTx tx = mapWallet[pcoin->vin[0].prevout.hash];
CTxDestination txoutAddr;
if(!ExtractDestination(txout.scriptPubKey, txoutAddr))
continue;
grouping.insert(txoutAddr);
};
};
groupings.insert(grouping);
grouping.clear();
};
// group lone addrs by themselves
for (unsigned int i = 0; i < pcoin->vout.size(); i++)
if (IsMine(pcoin->vout[i]))
{
CTxDestination address;
if(!ExtractDestination(pcoin->vout[i].scriptPubKey, address))
continue;
grouping.insert(address);
groupings.insert(grouping);
grouping.clear();
};
};
set< set<CTxDestination>* > uniqueGroupings; // a set of pointers to groups of addresses
map< CTxDestination, set<CTxDestination>* > setmap; // map addresses to the unique group containing it
BOOST_FOREACH(set<CTxDestination> grouping, groupings)
{
// make a set of all the groups hit by this new group
set< set<CTxDestination>* > hits;
map< CTxDestination, set<CTxDestination>* >::iterator it;
BOOST_FOREACH(CTxDestination address, grouping)
if ((it = setmap.find(address)) != setmap.end())
hits.insert((*it).second);
// merge all hit groups into a new single group and delete old groups
set<CTxDestination>* merged = new set<CTxDestination>(grouping);
BOOST_FOREACH(set<CTxDestination>* hit, hits)
{
merged->insert(hit->begin(), hit->end());
uniqueGroupings.erase(hit);
delete hit;
};
uniqueGroupings.insert(merged);
// update setmap
BOOST_FOREACH(CTxDestination element, *merged)
setmap[element] = merged;
};
set< set<CTxDestination> > ret;
BOOST_FOREACH(set<CTxDestination>* uniqueGrouping, uniqueGroupings)
{
ret.insert(*uniqueGrouping);
delete uniqueGrouping;
};
return ret;
}
// ppcoin: check 'spent' consistency between wallet and txindex
// ppcoin: fix wallet spent state according to txindex
void CWallet::FixSpentCoins(int& nMismatchFound, int64_t& nBalanceInQuestion, bool fCheckOnly)
{
if (nNodeMode != NT_FULL)
{
LogPrintf("FixSpentCoins must be run in full mode.\n");
return;
};
nMismatchFound = 0;
nBalanceInQuestion = 0;
LOCK(cs_wallet);
std::vector<CWalletTx*> vCoins;
vCoins.reserve(mapWallet.size());
for (WalletTxMap::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
vCoins.push_back(&(*it).second);
CTxDB txdb("r");
BOOST_FOREACH(CWalletTx* pcoin, vCoins)
{
// Find the corresponding transaction index
CTxIndex txindex;
if (!txdb.ReadTxIndex(pcoin->GetHash(), txindex))
continue;
for (unsigned int n=0; n < pcoin->vout.size(); n++)
{
if (IsMine(pcoin->vout[n]) && pcoin->IsSpent(n) && (txindex.vSpent.size() <= n || txindex.vSpent[n].IsNull()))
{
LogPrintf("FixSpentCoins found lost coin %s SDC %s[%d], %s\n",
FormatMoney(pcoin->vout[n].nValue).c_str(), pcoin->GetHash().ToString().c_str(), n, fCheckOnly? "repair not attempted" : "repairing");
nMismatchFound++;
nBalanceInQuestion += pcoin->vout[n].nValue;
if (!fCheckOnly)
{
pcoin->MarkUnspent(n);
pcoin->WriteToDisk();
};
} else
if (IsMine(pcoin->vout[n]) && !pcoin->IsSpent(n) && (txindex.vSpent.size() > n && !txindex.vSpent[n].IsNull()))
{
LogPrintf("FixSpentCoins found spent coin %s SDC %s[%d], %s\n",
FormatMoney(pcoin->vout[n].nValue).c_str(), pcoin->GetHash().ToString().c_str(), n, fCheckOnly? "repair not attempted" : "repairing");
nMismatchFound++;
nBalanceInQuestion += pcoin->vout[n].nValue;
if (!fCheckOnly)
{
pcoin->MarkSpent(n);
pcoin->WriteToDisk();
};
};
};
};
}
// ppcoin: disable transaction (only for coinstake)
void CWallet::DisableTransaction(const CTransaction &tx)
{
if (!tx.IsCoinStake() || !IsFromMe(tx))
return; // only disconnecting coinstake requires marking input unspent
LOCK(cs_wallet);
BOOST_FOREACH(const CTxIn& txin, tx.vin)
{
if (tx.nVersion == ANON_TXN_VERSION
&& txin.IsAnonInput())
continue;
WalletTxMap::iterator mi = mapWallet.find(txin.prevout.hash);
if (mi != mapWallet.end())
{
CWalletTx& prev = (*mi).second;
if (txin.prevout.n < prev.vout.size() && IsMine(prev.vout[txin.prevout.n]))
{
prev.MarkUnspent(txin.prevout.n);
prev.WriteToDisk();
};
};
};
}
int CWallet::GetChangeAddress(CPubKey &pk)
{
ExtKeyAccountMap::iterator mi = mapExtAccounts.find(idDefaultAccount);
if (mi == mapExtAccounts.end())
return errorN(1, "%s Unknown account.", __func__);
// - Return a key from the lookahead of the internal chain
// Don't promote the key to the main map, that will happen when the transaction is processed.
CStoredExtKey *pc;
if ((pc = mi->second->ChainInternal()) == NULL)
return errorN(1, "%s Unknown chain.", __func__);
uint32_t nChild;
if (0 != pc->DeriveNextKey(pk, nChild, false, false))
return errorN(1, "%s TryDeriveNext failed.", __func__);
if (fDebug)
{
CBitcoinAddress addr(pk.GetID());
LogPrintf("Change Address: %s\n", addr.ToString().c_str());
};
return 0;
};
int CWallet::ExtKeyNew32(CExtKey &out)
{
if (fDebug)
LogPrintf("ExtKeyNew32 from random.\n");
uint8_t data[32];
RandAddSeedPerfmon();
for (uint32_t i = 0; i < MAX_DERIVE_TRIES; ++i)
{
if (1 != RAND_bytes(data, 32))
return errorN(1, "%s RAND_bytes failed.", __func__);
if (ExtKeyNew32(out, data, 32) == 0)
break;
};
return out.IsValid() ? 0 : 1;
};
int CWallet::ExtKeyNew32(CExtKey &out, const char *sPassPhrase, int32_t nHash, const char *sSeed)
{
if (fDebug)
LogPrintf("ExtKeyNew32 from pass.\n");
uint8_t data[64];
uint8_t passData[64];
bool fPass = true;
int nPhraseLen = strlen(sPassPhrase);
int nSeedLen = strlen(sSeed);
memset(passData, 0, 64);
// - make the same key as http://bip32.org/
HMAC_SHA256_CTX ctx256;
for (int32_t i = 0; i < nHash; ++i)
{
HMAC_SHA256_Init(&ctx256, sPassPhrase, nPhraseLen);
HMAC_SHA256_Update(&ctx256, passData, 32);
HMAC_SHA256_Final(passData, &ctx256);
};
HMAC_SHA512_CTX ctx;
if (!HMAC_SHA512_Init(&ctx, passData, 32))
return errorN(1, "HMAC_SHA512_Init failed.");
if (!HMAC_SHA512_Update(&ctx, sSeed, nSeedLen))
{
LogPrintf("HMAC_SHA512_Update failed.\n");
fPass = false;
};
if (!HMAC_SHA512_Final(data, &ctx))
{
LogPrintf("HMAC_SHA512_Final failed.\n");
fPass = false;
};
if (fPass && out.SetKeyCode(data, &data[32]) != 0)
return errorN(1, "SetKeyCode failed.");
return out.IsValid() ? 0 : 1;
};
int CWallet::ExtKeyNew32(CExtKey &out, uint8_t *data, uint32_t lenData)
{
if (fDebug)
LogPrintf("ExtKeyNew32.\n");
out.SetMaster(data, lenData);
return out.IsValid() ? 0 : 1;
};
int CWallet::ExtKeyImportLoose(CWalletDB *pwdb, CStoredExtKey &sekIn, bool fBip44, bool fSaveBip44)
{
if (fDebug)
{
LogPrintf("ExtKeyImportLoose.\n");
AssertLockHeld(cs_wallet);
};
assert(pwdb);
if (IsLocked())
return errorN(1, "Wallet must be unlocked.");
CKeyID id = sekIn.GetID();
bool fsekInExist = true;
// - it's possible for a public ext key to be added first
CStoredExtKey sekExist;
CStoredExtKey sek = sekIn;
if (pwdb->ReadExtKey(id, sekExist))
{
if (IsCrypted()
&& 0 != ExtKeyUnlock(&sekExist))
return errorN(13, "%s: %s", __func__, ExtKeyGetString(13));
sek = sekExist;
if (!sek.kp.IsValidV()
&& sekIn.kp.IsValidV())
{
sek.kp = sekIn.kp;
std::vector<uint8_t> v;
sek.mapValue[EKVT_ADDED_SECRET_AT] = SetCompressedInt64(v, GetTime());
};
} else
{
// - new key
sek.nFlags |= EAF_ACTIVE;
fsekInExist = false;
};
if (fBip44)
{
// import key as bip44 root and derive a new master key
// NOTE: can't know created at time of derived key here
std::vector<uint8_t> v;
sek.mapValue[EKVT_KEY_TYPE] = SetChar(v, EKT_BIP44_MASTER);
CKeyID idRoot = sek.GetID();
CExtKey evDerivedKey;
sek.kp.Derive(evDerivedKey, BIP44_PURPOSE);
evDerivedKey.Derive(evDerivedKey, Params().BIP44ID());
v.resize(0);
PushUInt32(v, BIP44_PURPOSE);
PushUInt32(v, Params().BIP44ID());
CStoredExtKey sekDerived;
sekDerived.nFlags |= EAF_ACTIVE;
sekDerived.kp = evDerivedKey;
sekDerived.mapValue[EKVT_PATH] = v;
sekDerived.mapValue[EKVT_ROOT_ID] = SetCKeyID(v, id);
sekDerived.sLabel = sek.sLabel + " - bip44 derived.";
CKeyID idDerived = sekDerived.GetID();
if (pwdb->ReadExtKey(idDerived, sekExist))
{
if (fSaveBip44
&& !fsekInExist)
{
// - assume the user wants to save the bip44 key, drop down
} else
{
return errorN(12, "%s: %s", __func__, ExtKeyGetString(12));
};
} else
{
if (IsCrypted()
&& (ExtKeyEncrypt(&sekDerived, vMasterKey, false) != 0))
return errorN(1, "%s: ExtKeyEncrypt failed.", __func__);
if (!pwdb->WriteExtKey(idDerived, sekDerived))
return errorN(1, "%s: DB Write failed.", __func__);
};
};
if (!fBip44 || fSaveBip44)
{
if (IsCrypted()
&& ExtKeyEncrypt(&sek, vMasterKey, false) != 0)
return errorN(1, "%s: ExtKeyEncrypt failed.", __func__);
if (!pwdb->WriteExtKey(id, sek))
return errorN(1, "%s: DB Write failed.", __func__);
};
return 0;
};
int CWallet::ExtKeyImportAccount(CWalletDB *pwdb, CStoredExtKey &sekIn, int64_t nTimeStartScan, const std::string &sLabel)
{
// rv: 0 success, 1 fail, 2 existing key, 3 updated key
// It's not possible to import an account using only a public key as internal keys are derived hardened
if (fDebug)
{
LogPrintf("ExtKeyImportAccount.\n");
AssertLockHeld(cs_wallet);
if (nTimeStartScan == 0)
LogPrintf("No blockchain scanning.\n");
else
LogPrintf("Scan blockchain from %d.\n", nTimeStartScan);
};
assert(pwdb);
if (IsLocked())
return errorN(1, "Wallet must be unlocked.");
CKeyID idAccount = sekIn.GetID();
CStoredExtKey *sek = new CStoredExtKey();
*sek = sekIn;
// NOTE: is this confusing behaviour?
CStoredExtKey sekExist;
if (pwdb->ReadExtKey(idAccount, sekExist))
{
// add secret if exists in db
*sek = sekExist;
if (!sek->kp.IsValidV()
&& sekIn.kp.IsValidV())
{
sek->kp = sekIn.kp;
std::vector<uint8_t> v;
sek->mapValue[EKVT_ADDED_SECRET_AT] = SetCompressedInt64(v, GetTime());
};
};
// TODO: before allowing import of 'watch only' accounts
// txns must be linked to accounts.
if (!sek->kp.IsValidV())
{
delete sek;
return errorN(1, "Accounts must be derived from a valid private key.");
};
CExtKeyAccount *sea = new CExtKeyAccount();
if (pwdb->ReadExtAccount(idAccount, *sea))
{
if (0 != ExtKeyUnlock(sea))
{
delete sek;
delete sea;
return errorN(1, "Error unlocking existing account.");
};
CStoredExtKey *sekAccount = sea->ChainAccount();
if (!sekAccount)
{
delete sek;
delete sea;
return errorN(1, "ChainAccount failed.");
};
// - account exists, update secret if necessary
if (!sek->kp.IsValidV()
&& sekAccount->kp.IsValidV())
{
sekAccount->kp = sek->kp;
std::vector<uint8_t> v;
sekAccount->mapValue[EKVT_ADDED_SECRET_AT] = SetCompressedInt64(v, GetTime());
if (IsCrypted()
&& ExtKeyEncrypt(sekAccount, vMasterKey, false) != 0)
{
delete sek;
delete sea;
return errorN(1, "ExtKeyEncrypt failed.");
};
if (!pwdb->WriteExtKey(idAccount, *sekAccount))
{
delete sek;
delete sea;
return errorN(1, "WriteExtKey failed.");
};
if (nTimeStartScan)
ScanChainFromTime(nTimeStartScan);
delete sek;
delete sea;
return 3;
};
delete sek;
delete sea;
return 2;
};
CKeyID idMaster(0);
if (0 != ExtKeyCreateAccount(sek, idMaster, *sea, sLabel))
{
delete sek;
delete sea;
return errorN(1, "ExtKeyCreateAccount failed.");
};
std::vector<uint8_t> v;
sea->mapValue[EKVT_CREATED_AT] = SetCompressedInt64(v, nTimeStartScan);
if (0 != ExtKeySaveAccountToDB(pwdb, idAccount, sea))
{
sea->FreeChains();
delete sea;
return errorN(1, "DB Write failed.");
};
if (0 != ExtKeyAddAccountToMaps(idAccount, sea))
{
sea->FreeChains();
delete sea;
return errorN(1, "ExtKeyAddAccountToMap() failed.");
};
if (nTimeStartScan)
ScanChainFromTime(nTimeStartScan);
return 0;
};
int CWallet::ExtKeySetMaster(CWalletDB *pwdb, CKeyID &idNewMaster)
{
if (fDebug)
{
CBitcoinAddress addr;
addr.Set(idNewMaster, CChainParams::EXT_KEY_HASH);
LogPrintf("ExtKeySetMaster %s.\n", addr.ToString().c_str());
AssertLockHeld(cs_wallet);
};
assert(pwdb);
if (IsLocked())
return errorN(1, "Wallet must be unlocked.");
CKeyID idOldMaster;
bool fOldMaster = pwdb->ReadNamedExtKeyId("master", idOldMaster);
if (idNewMaster == idOldMaster)
return errorN(11, ExtKeyGetString(11));
ExtKeyMap::iterator mi;
CStoredExtKey ekOldMaster, *pEkOldMaster, *pEkNewMaster;
bool fNew = false;
mi = mapExtKeys.find(idNewMaster);
if (mi != mapExtKeys.end())
{
pEkNewMaster = mi->second;
} else
{
pEkNewMaster = new CStoredExtKey();
fNew = true;
if (!pwdb->ReadExtKey(idNewMaster, *pEkNewMaster))
{
delete pEkNewMaster;
return errorN(10, ExtKeyGetString(10));
};
};
// - prevent setting bip44 root key as a master key.
mapEKValue_t::iterator mvi = pEkNewMaster->mapValue.find(EKVT_KEY_TYPE);
if (mvi != pEkNewMaster->mapValue.end()
&& mvi->second.size() == 1
&& mvi->second[0] == EKT_BIP44_MASTER)
{
if (fNew) delete pEkNewMaster;
return errorN(9, ExtKeyGetString(9));
};
if (ExtKeyUnlock(pEkNewMaster) != 0
|| !pEkNewMaster->kp.IsValidV())
{
if (fNew) delete pEkNewMaster;
return errorN(1, "New master ext key has no secret.");
};
std::vector<uint8_t> v;
pEkNewMaster->mapValue[EKVT_KEY_TYPE] = SetChar(v, EKT_MASTER);
if (!pwdb->WriteExtKey(idNewMaster, *pEkNewMaster)
|| !pwdb->WriteNamedExtKeyId("master", idNewMaster))
{
if (fNew) delete pEkNewMaster;
return errorN(1, "DB Write failed.");
};
// -- unset old master ext key
if (fOldMaster)
{
mi = mapExtKeys.find(idOldMaster);
if (mi != mapExtKeys.end())
{
pEkOldMaster = mi->second;
} else
{
if (!pwdb->ReadExtKey(idOldMaster, ekOldMaster))
{
if (fNew) delete pEkNewMaster;
return errorN(1, "ReadExtKey failed.");
};
pEkOldMaster = &ekOldMaster;
};
mapEKValue_t::iterator it = pEkOldMaster->mapValue.find(EKVT_KEY_TYPE);
if (it != pEkOldMaster->mapValue.end())
{
if (fDebug)
LogPrintf("Removing tag from old master key %s.\n", pEkOldMaster->GetIDString58().c_str());
pEkOldMaster->mapValue.erase(it);
if (!pwdb->WriteExtKey(idOldMaster, *pEkOldMaster))
{
if (fNew) delete pEkNewMaster;
return errorN(1, "WriteExtKey failed.");
};
};
};
mapExtKeys[idNewMaster] = pEkNewMaster;
pEkMaster = pEkNewMaster;
return 0;
};
int CWallet::ExtKeyNewMaster(CWalletDB *pwdb, CKeyID &idMaster, bool fAutoGenerated)
{
// - Must pair with ExtKeySetMaster
// This creates two keys, a root key and a master key derived according
// to BIP44 (path 44'/22'), The root (bip44) key only stored in the system
// and the derived key is set as the system master key.
LogPrintf("ExtKeyNewMaster.\n");
AssertLockHeld(cs_wallet);
assert(pwdb);
if (IsLocked())
return errorN(1, "Wallet must be unlocked.");
CExtKey evRootKey;
CStoredExtKey sekRoot;
if (ExtKeyNew32(evRootKey) != 0)
return errorN(1, "ExtKeyNew32 failed.");
std::vector<uint8_t> v;
sekRoot.nFlags |= EAF_ACTIVE;
sekRoot.mapValue[EKVT_KEY_TYPE] = SetChar(v, EKT_BIP44_MASTER);
sekRoot.kp = evRootKey;
sekRoot.mapValue[EKVT_CREATED_AT] = SetCompressedInt64(v, GetTime());
sekRoot.sLabel = "Initial BIP44 Master";
CKeyID idRoot = sekRoot.GetID();
CExtKey evMasterKey;
evRootKey.Derive(evMasterKey, BIP44_PURPOSE);
evMasterKey.Derive(evMasterKey, Params().BIP44ID());
std::vector<uint8_t> vPath;
PushUInt32(vPath, BIP44_PURPOSE);
PushUInt32(vPath, Params().BIP44ID());
CStoredExtKey sekMaster;
sekMaster.nFlags |= EAF_ACTIVE;
sekMaster.kp = evMasterKey;
sekMaster.mapValue[EKVT_PATH] = vPath;
sekMaster.mapValue[EKVT_ROOT_ID] = SetCKeyID(v, idRoot);
sekMaster.mapValue[EKVT_CREATED_AT] = SetCompressedInt64(v, GetTime());
sekMaster.sLabel = "Initial Master";
idMaster = sekMaster.GetID();
if (IsCrypted()
&& (ExtKeyEncrypt(&sekRoot, vMasterKey, false) != 0
|| ExtKeyEncrypt(&sekMaster, vMasterKey, false) != 0))
{
return errorN(1, "ExtKeyEncrypt failed.");
};
if (!pwdb->WriteExtKey(idRoot, sekRoot)
|| !pwdb->WriteExtKey(idMaster, sekMaster)
|| (fAutoGenerated && !pwdb->WriteFlag("madeDefaultEKey", 1)))
{
return errorN(1, "DB Write failed.");
};
return 0;
};
int CWallet::ExtKeyCreateAccount(CStoredExtKey *sekAccount, CKeyID &idMaster, CExtKeyAccount &ekaOut, const std::string &sLabel)
{
if (fDebug)
{
LogPrintf("ExtKeyCreateAccount.\n");
AssertLockHeld(cs_wallet);
};
std::vector<uint8_t> vAccountPath, vSubKeyPath, v;
mapEKValue_t::iterator mi = sekAccount->mapValue.find(EKVT_PATH);
if (mi != sekAccount->mapValue.end())
{
vAccountPath = mi->second;
};
ekaOut.idMaster = idMaster;
ekaOut.sLabel = sLabel;
ekaOut.nFlags |= EAF_ACTIVE;
ekaOut.mapValue[EKVT_CREATED_AT] = SetCompressedInt64(v, GetTime());
if (sekAccount->kp.IsValidV())
ekaOut.nFlags |= EAF_HAVE_SECRET;
CExtKey evExternal, evInternal, evStealth;
uint32_t nExternal, nInternal, nStealth;
if (sekAccount->DeriveNextKey(evExternal, nExternal, false) != 0
|| sekAccount->DeriveNextKey(evInternal, nInternal, false) != 0
|| sekAccount->DeriveNextKey(evStealth, nStealth, true) != 0)
{
return errorN(1, "Could not derive account chain keys.");
};
CStoredExtKey *sekExternal = new CStoredExtKey();
sekExternal->kp = evExternal;
vSubKeyPath = vAccountPath;
sekExternal->mapValue[EKVT_PATH] = PushUInt32(vSubKeyPath, nExternal);
sekExternal->nFlags |= EAF_ACTIVE | EAF_RECEIVE_ON | EAF_IN_ACCOUNT;
sekExternal->mapValue[EKVT_N_LOOKAHEAD] = SetCompressedInt64(v, N_DEFAULT_EKVT_LOOKAHEAD);
CStoredExtKey *sekInternal = new CStoredExtKey();
sekInternal->kp = evInternal;
vSubKeyPath = vAccountPath;
sekInternal->mapValue[EKVT_PATH] = PushUInt32(vSubKeyPath, nInternal);
sekInternal->nFlags |= EAF_ACTIVE | EAF_RECEIVE_ON | EAF_IN_ACCOUNT;
CStoredExtKey *sekStealth = new CStoredExtKey();
sekStealth->kp = evStealth;
vSubKeyPath = vAccountPath;
sekStealth->mapValue[EKVT_PATH] = PushUInt32(vSubKeyPath, nStealth);
sekStealth->nFlags |= EAF_ACTIVE | EAF_IN_ACCOUNT;
ekaOut.vExtKeyIDs.push_back(sekAccount->GetID());
ekaOut.vExtKeyIDs.push_back(sekExternal->GetID());
ekaOut.vExtKeyIDs.push_back(sekInternal->GetID());
ekaOut.vExtKeyIDs.push_back(sekStealth->GetID());
ekaOut.vExtKeys.push_back(sekAccount);
ekaOut.vExtKeys.push_back(sekExternal);
ekaOut.vExtKeys.push_back(sekInternal);
ekaOut.vExtKeys.push_back(sekStealth);
ekaOut.nActiveExternal = 1;
ekaOut.nActiveInternal = 2;
ekaOut.nActiveStealth = 3;
if (IsCrypted()
&& ExtKeyEncrypt(&ekaOut, vMasterKey, false) != 0)
{
delete sekExternal;
delete sekInternal;
delete sekStealth;
// - sekAccount should be freed in calling function
return errorN(1, "ExtKeyEncrypt failed.");
};
return 0;
};
int CWallet::ExtKeyDeriveNewAccount(CWalletDB *pwdb, CExtKeyAccount *sea, const std::string &sLabel, const std::string &sPath)
{
// - derive a new account from the master extkey and save to wallet
LogPrintf("%s\n", __func__);
AssertLockHeld(cs_wallet);
assert(pwdb);
assert(sea);
if (IsLocked())
return errorN(1, "%s: Wallet must be unlocked.", __func__);
if (!pEkMaster || !pEkMaster->kp.IsValidV())
return errorN(1, "%s: Master ext key is invalid.", __func__);
CKeyID idMaster = pEkMaster->GetID();
CStoredExtKey *sekAccount = new CStoredExtKey();
CExtKey evAccountKey;
uint32_t nOldHGen = pEkMaster->GetCounter(true);
uint32_t nAccount;
std::vector<uint8_t> vAccountPath, vSubKeyPath;
if (sPath.length() == 0)
{
if (pEkMaster->DeriveNextKey(evAccountKey, nAccount, true) != 0)
{
delete sekAccount;
return errorN(1, "%s: Could not derive account key from master.", __func__);
};
sekAccount->kp = evAccountKey;
sekAccount->mapValue[EKVT_PATH] = PushUInt32(vAccountPath, nAccount);
} else
{
std::vector<uint32_t> vPath;
int rv;
if ((rv = ExtractExtKeyPath(sPath, vPath)) != 0)
{
delete sekAccount;
return errorN(1, "%s: ExtractExtKeyPath failed %s.", __func__, ExtKeyGetString(rv));
};
CExtKey vkOut;
CExtKey vkWork = pEkMaster->kp.GetExtKey();
for (std::vector<uint32_t>::iterator it = vPath.begin(); it != vPath.end(); ++it)
{
if (!vkWork.Derive(vkOut, *it))
{
delete sekAccount;
return errorN(1, "%s: CExtKey Derive failed %s, %d.", __func__, sPath.c_str(), *it);
};
PushUInt32(vAccountPath, *it);
vkWork = vkOut;
};
sekAccount->kp = vkOut;
sekAccount->mapValue[EKVT_PATH] = vAccountPath;
};
if (!sekAccount->kp.IsValidV()
|| !sekAccount->kp.IsValidP())
{
delete sekAccount;
pEkMaster->SetCounter(nOldHGen, true);
return errorN(1, "%s: Invalid key.", __func__);
};
sekAccount->nFlags |= EAF_ACTIVE | EAF_IN_ACCOUNT;
if (0 != ExtKeyCreateAccount(sekAccount, idMaster, *sea, sLabel))
{
delete sekAccount;
pEkMaster->SetCounter(nOldHGen, true);
return errorN(1, "%s: ExtKeyCreateAccount failed.", __func__);
};
CKeyID idAccount = sea->GetID();
if (!pwdb->WriteExtKey(idMaster, *pEkMaster)
|| 0 != ExtKeySaveAccountToDB(pwdb, idAccount, sea))
{
sea->FreeChains();
pEkMaster->SetCounter(nOldHGen, true);
return errorN(1, "%s: DB Write failed.", __func__);
};
if (0 != ExtKeyAddAccountToMaps(idAccount, sea))
{
sea->FreeChains();
return errorN(1, "%s: ExtKeyAddAccountToMaps() failed.", __func__);
};
return 0;
};
int CWallet::ExtKeyEncrypt(CStoredExtKey *sek, const CKeyingMaterial &vMKey, bool fLockKey)
{
if (!sek->kp.IsValidV())
{
if (fDebug)
LogPrintf("%s: sek %s has no secret, encryption skipped.", __func__, sek->GetIDString58());
return 0;
//return errorN(1, "Invalid secret.");
};
std::vector<uint8_t> vchCryptedSecret;
CPubKey pubkey = sek->kp.pubkey;
CKeyingMaterial vchSecret(sek->kp.key.begin(), sek->kp.key.end());
if (!EncryptSecret(vMKey, vchSecret, pubkey.GetHash(), vchCryptedSecret))
return errorN(1, "EncryptSecret failed.");
sek->nFlags |= EAF_IS_CRYPTED;
sek->vchCryptedSecret = vchCryptedSecret;
// - CStoredExtKey serialise will never save key when vchCryptedSecret is set
// thus key can be left intact here
if (fLockKey)
{
sek->fLocked = 1;
sek->kp.key.Clear();
} else
{
sek->fLocked = 0;
};
return 0;
};
int CWallet::ExtKeyEncrypt(CExtKeyAccount *sea, const CKeyingMaterial &vMKey, bool fLockKey)
{
assert(sea);
std::vector<CStoredExtKey*>::iterator it;
for (it = sea->vExtKeys.begin(); it != sea->vExtKeys.end(); ++it)
{
CStoredExtKey *sek = *it;
if (sek->nFlags & EAF_IS_CRYPTED)
continue;
if (!sek->kp.IsValidV()
&& fDebug)
{
LogPrintf("%s : Skipping account %s chain, no secret.", __func__, sea->GetIDString58().c_str());
continue;
};
if (sek->kp.IsValidV()
&& ExtKeyEncrypt(sek, vMKey, fLockKey) != 0)
return 1;
};
return 0;
};
int CWallet::ExtKeyEncryptAll(CWalletDB *pwdb, const CKeyingMaterial &vMKey)
{
LogPrintf("%s\n", __func__);
// Encrypt loose and account extkeys stored in wallet
// skip invalid private keys
Dbc *pcursor = pwdb->GetTxnCursor();
if (!pcursor)
return errorN(1, "%s : cannot create DB cursor.", __func__);
CDataStream ssKey(SER_DISK, CLIENT_VERSION);
CDataStream ssValue(SER_DISK, CLIENT_VERSION);
CKeyID ckeyId;
CBitcoinAddress addr;
CStoredExtKey sek;
CExtKeyAccount sea;
CExtKey58 eKey58;
std::string strType;
size_t nKeys = 0;
size_t nAccounts = 0;
uint32_t fFlags = DB_SET_RANGE;
ssKey << std::string("ek32");
while (pwdb->ReadAtCursor(pcursor, ssKey, ssValue, fFlags) == 0)
{
fFlags = DB_NEXT;
ssKey >> strType;
if (strType != "ek32")
break;
ssKey >> ckeyId;
ssValue >> sek;
if (!sek.kp.IsValidV())
{
if (fDebug)
{
addr.Set(ckeyId, CChainParams::EXT_KEY_HASH);
LogPrintf("%s : Skipping key %s, no secret.", __func__, sek.GetIDString58().c_str());
};
continue;
};
if (ExtKeyEncrypt(&sek, vMKey, true) != 0)
return errorN(1, "%s : ExtKeyEncrypt failed.", __func__);
nKeys++;
if (!pwdb->Replace(pcursor, sek))
return errorN(1, "%s : Replace failed.", __func__);
};
pcursor->close();
if (fDebug)
LogPrintf("%s : Encrypted %u keys, %u accounts.", __func__, nKeys, nAccounts);
return 0;
};
int CWallet::ExtKeyLock()
{
if (fDebug)
LogPrintf("ExtKeyLock.\n");
if (pEkMaster)
{
pEkMaster->kp.key.Clear();
pEkMaster->fLocked = 1;
};
// TODO: iterate over mapExtKeys instead?
ExtKeyAccountMap::iterator mi;
for (mi = mapExtAccounts.begin(); mi != mapExtAccounts.end(); ++mi)
{
CExtKeyAccount *sea = mi->second;
std::vector<CStoredExtKey*>::iterator it;
for (it = sea->vExtKeys.begin(); it != sea->vExtKeys.end(); ++it)
{
CStoredExtKey *sek = *it;
if (!(sek->nFlags & EAF_IS_CRYPTED))
continue;
sek->kp.key.Clear();
sek->fLocked = 1;
};
};
return 0;
};
int CWallet::ExtKeyUnlock(CExtKeyAccount *sea)
{
return ExtKeyUnlock(sea, vMasterKey);
};
int CWallet::ExtKeyUnlock(CExtKeyAccount *sea, const CKeyingMaterial &vMKey)
{
std::vector<CStoredExtKey*>::iterator it;
for (it = sea->vExtKeys.begin(); it != sea->vExtKeys.end(); ++it)
{
CStoredExtKey *sek = *it;
if (!(sek->nFlags & EAF_IS_CRYPTED))
continue;
if (ExtKeyUnlock(sek, vMKey) != 0)
return 1;
};
return 0;
};
int CWallet::ExtKeyUnlock(CStoredExtKey *sek)
{
return ExtKeyUnlock(sek, vMasterKey);
};
int CWallet::ExtKeyUnlock(CStoredExtKey *sek, const CKeyingMaterial &vMKey)
{
if (!(sek->nFlags & EAF_IS_CRYPTED)) // is not necessary to unlock
return 0;
CSecret vchSecret;
uint256 iv = Hash(sek->kp.pubkey.begin(), sek->kp.pubkey.end());
if (!DecryptSecret(vMKey, sek->vchCryptedSecret, iv, vchSecret)
|| vchSecret.size() != 32)
{
return errorN(1, "Failed decrypting ext key %s", sek->GetIDString58().c_str());
};
sek->kp.key.Set(vchSecret.begin(), vchSecret.end(), true);
if (!sek->kp.IsValidV())
return errorN(1, "Failed decrypting ext key %s", sek->GetIDString58().c_str());
// - check, necessary?
if (sek->kp.key.GetPubKey() != sek->kp.pubkey)
return errorN(1, "Decrypted ext key mismatch %s", sek->GetIDString58().c_str());
sek->fLocked = 0;
return 0;
};
int CWallet::ExtKeyUnlock(const CKeyingMaterial &vMKey)
{
if (fDebug)
LogPrintf("ExtKeyUnlock.\n");
if (pEkMaster
&& pEkMaster->nFlags & EAF_IS_CRYPTED)
{
if (ExtKeyUnlock(pEkMaster, vMKey) != 0)
return 1;
};
ExtKeyAccountMap::iterator mi;
mi = mapExtAccounts.begin();
for (mi = mapExtAccounts.begin(); mi != mapExtAccounts.end(); ++mi)
{
CExtKeyAccount *sea = mi->second;
if (ExtKeyUnlock(sea, vMKey) != 0)
return errorN(1, "ExtKeyUnlock() account failed.");
};
return 0;
};
int CWallet::ExtKeyCreateInitial(CWalletDB *pwdb)
{
LogPrintf("Creating intital extended master key and account.\n");
CKeyID idMaster;
if (!pwdb->TxnBegin())
return errorN(1, "TxnBegin failed.");
if (ExtKeyNewMaster(pwdb, idMaster, true) != 0
|| ExtKeySetMaster(pwdb, idMaster) != 0)
{
pwdb->TxnAbort();
return errorN(1, "Make or SetNewMasterKey failed.");
};
CExtKeyAccount *seaDefault = new CExtKeyAccount();
if (ExtKeyDeriveNewAccount(pwdb, seaDefault, "default") != 0)
{
delete seaDefault;
pwdb->TxnAbort();
return errorN(1, "DeriveNewExtAccount failed.");
};
idDefaultAccount = seaDefault->GetID();
if (!pwdb->WriteNamedExtKeyId("defaultAccount", idDefaultAccount))
{
pwdb->TxnAbort();
return errorN(1, "WriteNamedExtKeyId failed.");
};
CPubKey newKey;
if (0 != NewKeyFromAccount(pwdb, idDefaultAccount, newKey, false, false))
{
pwdb->TxnAbort();
return errorN(1, "NewKeyFromAccount failed.");
}
CEKAStealthKey aks;
string strLbl = "Default Stealth Address";
if (0 != NewStealthKeyFromAccount(pwdb, idDefaultAccount, strLbl, aks))
{
pwdb->TxnAbort();
return errorN(1, "NewKeyFromAccount failed.");
}
if (!pwdb->TxnCommit())
{
// --TxnCommit destroys activeTxn
return errorN(1, "TxnCommit failed.");
};
SetAddressBookName(CBitcoinAddress(newKey.GetID()).Get(), "Default Address", NULL, true, true);
return 0;
}
int CWallet::ExtKeyLoadMaster()
{
LogPrintf("Loading master ext key.\n");
LOCK(cs_wallet);
CKeyID idMaster;
CWalletDB wdb(strWalletFile, "r+");
if (!wdb.ReadNamedExtKeyId("master", idMaster))
{
int nValue;
if (!wdb.ReadFlag("madeDefaultEKey", nValue)
|| nValue == 0)
{
if (IsLocked())
{
fMakeExtKeyInitials = true; // set flag for unlock
LogPrintf("Wallet locked, master key will be created when unlocked.\n");
return 0;
};
if (ExtKeyCreateInitial(&wdb) != 0)
return errorN(1, "ExtKeyCreateDefaultMaster failed.");
return 0;
};
LogPrintf("Warning: No master ext key has been set.\n");
return 1;
};
pEkMaster = new CStoredExtKey();
if (!wdb.ReadExtKey(idMaster, *pEkMaster))
{
delete pEkMaster;
pEkMaster = NULL;
return errorN(1, "ReadExtKey failed to read master ext key.");
};
if (!pEkMaster->kp.IsValidP()) // wallet could be locked, check pk
{
delete pEkMaster;
pEkMaster = NULL;
return errorN(1, " Loaded master ext key is invalid %s.", pEkMaster->GetIDString58().c_str());
};
if (pEkMaster->nFlags & EAF_IS_CRYPTED)
pEkMaster->fLocked = 1;
// - add to key map
mapExtKeys[idMaster] = pEkMaster;
// find earliest key creation time, as wallet birthday
int64_t nCreatedAt;
GetCompressedInt64(pEkMaster->mapValue[EKVT_CREATED_AT], (uint64_t&)nCreatedAt);
if (!nTimeFirstKey || (nCreatedAt && nCreatedAt < nTimeFirstKey))
nTimeFirstKey = nCreatedAt;
return 0;
};
int CWallet::ExtKeyLoadAccounts()
{
LogPrintf("Loading ext accounts.\n");
LOCK(cs_wallet);
CWalletDB wdb(strWalletFile);
if (!wdb.ReadNamedExtKeyId("defaultAccount", idDefaultAccount))
{
LogPrintf("Warning: No default ext account set.\n");
};
Dbc *pcursor;
if (!(pcursor = wdb.GetAtCursor()))
throw std::runtime_error(strprintf("%s: cannot create DB cursor", __func__).c_str());
CDataStream ssKey(SER_DISK, CLIENT_VERSION);
CDataStream ssValue(SER_DISK, CLIENT_VERSION);
CBitcoinAddress addr;
CKeyID idAccount;
std::string strType;
unsigned int fFlags = DB_SET_RANGE;
ssKey << std::string("eacc");
while (wdb.ReadAtCursor(pcursor, ssKey, ssValue, fFlags) == 0)
{
fFlags = DB_NEXT;
ssKey >> strType;
if (strType != "eacc")
break;
ssKey >> idAccount;
if (fDebug)
{
addr.Set(idAccount, CChainParams::EXT_ACC_HASH);
LogPrintf("Loading account %s\n", addr.ToString().c_str());
};
CExtKeyAccount *sea = new CExtKeyAccount();
ssValue >> *sea;
ExtKeyAccountMap::iterator mi = mapExtAccounts.find(idAccount);
if (mi != mapExtAccounts.end())
{
// - account already loaded, skip, can be caused by ExtKeyCreateInitial()
if (fDebug)
LogPrintf("Account already loaded.\n");
continue;
};
if (!(sea->nFlags & EAF_ACTIVE))
{
if (fDebug)
{
addr.Set(idAccount, CChainParams::EXT_ACC_HASH);
LogPrintf("Skipping inactive %s\n", addr.ToString().c_str());
};
delete sea;
continue;
};
// find earliest key creation time, as wallet birthday
int64_t nCreatedAt;
GetCompressedInt64(sea->mapValue[EKVT_CREATED_AT], (uint64_t&)nCreatedAt);
if (!nTimeFirstKey || (nCreatedAt && nCreatedAt < nTimeFirstKey))
nTimeFirstKey = nCreatedAt;
sea->vExtKeys.resize(sea->vExtKeyIDs.size());
for (size_t i = 0; i < sea->vExtKeyIDs.size(); ++i)
{
CKeyID &id = sea->vExtKeyIDs[i];
CStoredExtKey *sek = new CStoredExtKey();
if (wdb.ReadExtKey(id, *sek))
{
sea->vExtKeys[i] = sek;
} else
{
addr.Set(idAccount, CChainParams::EXT_ACC_HASH);
LogPrintf("WARNING: Could not read key %d of account %s\n", i, addr.ToString().c_str());
sea->vExtKeys[i] = NULL;
delete sek;
};
};
if (0 != ExtKeyAddAccountToMaps(idAccount, sea))
{
addr.Set(idAccount, CChainParams::EXT_ACC_HASH);
LogPrintf("ExtKeyAddAccountToMaps() failed: %s\n", addr.ToString().c_str());
sea->FreeChains();
delete sea;
};
};
pcursor->close();
return 0;
};
int CWallet::ExtKeySaveAccountToDB(CWalletDB *pwdb, CKeyID &idAccount, CExtKeyAccount *sea)
{
if (fDebug)
{
LogPrintf("ExtKeySaveAccountToDB()\n");
AssertLockHeld(cs_wallet);
};
assert(sea);
for (size_t i = 0; i < sea->vExtKeys.size(); ++i)
{
CStoredExtKey *sek = sea->vExtKeys[i];
if (!pwdb->WriteExtKey(sea->vExtKeyIDs[i], *sek))
return errorN(1, "ExtKeySaveAccountToDB(): WriteExtKey failed.");
};
if (!pwdb->WriteExtAccount(idAccount, *sea))
return errorN(1, "ExtKeySaveAccountToDB() WriteExtAccount failed.");
return 0;
};
int CWallet::ExtKeyAddAccountToMaps(CKeyID &idAccount, CExtKeyAccount *sea)
{
// - open/activate account in wallet
// add to mapExtAccounts and mapExtKeys
if (fDebug)
{
LogPrintf("ExtKeyAddAccountToMap()\n");
AssertLockHeld(cs_wallet);
};
assert(sea);
for (size_t i = 0; i < sea->vExtKeys.size(); ++i)
{
CStoredExtKey *sek = sea->vExtKeys[i];
if (sek->nFlags & EAF_IS_CRYPTED)
sek->fLocked = 1;
if (sek->nFlags & EAF_ACTIVE
&& sek->nFlags & EAF_RECEIVE_ON)
{
uint64_t nLookAhead = N_DEFAULT_LOOKAHEAD;
mapEKValue_t::iterator itV = sek->mapValue.find(EKVT_N_LOOKAHEAD);
if (itV != sek->mapValue.end())
nLookAhead = GetCompressedInt64(itV->second, nLookAhead);
sea->AddLookAhead(i, (uint32_t)nLookAhead);
};
mapExtKeys[sea->vExtKeyIDs[i]] = sek;
};
mapExtAccounts[idAccount] = sea;
return 0;
};
int CWallet::ExtKeyLoadAccountPacks()
{
LogPrintf("Loading ext account packs.\n");
LOCK(cs_wallet);
CWalletDB wdb(strWalletFile);
Dbc *pcursor;
if (!(pcursor = wdb.GetAtCursor()))
throw std::runtime_error(strprintf("%s : cannot create DB cursor", __func__).c_str());
CDataStream ssKey(SER_DISK, CLIENT_VERSION);
CDataStream ssValue(SER_DISK, CLIENT_VERSION);
CKeyID idAccount;
CBitcoinAddress addr;
uint32_t nPack;
std::string strType;
std::vector<CEKAKeyPack> ekPak;
std::vector<CEKAStealthKeyPack> aksPak;
std::vector<CEKASCKeyPack> asckPak;
unsigned int fFlags = DB_SET_RANGE;
ssKey << std::string("epak");
while (wdb.ReadAtCursor(pcursor, ssKey, ssValue, fFlags) == 0)
{
ekPak.clear();
fFlags = DB_NEXT;
ssKey >> strType;
if (strType != "epak")
break;
ssKey >> idAccount;
ssKey >> nPack;
if (fDebug)
{
addr.Set(idAccount, CChainParams::EXT_ACC_HASH);
LogPrintf("Loading account key pack %s %u\n", addr.ToString().c_str(), nPack);
};
ExtKeyAccountMap::iterator mi = mapExtAccounts.find(idAccount);
if (mi == mapExtAccounts.end())
{
addr.Set(idAccount, CChainParams::EXT_ACC_HASH);
LogPrintf("Warning: Unknown account %s.\n", addr.ToString().c_str());
continue;
};
CExtKeyAccount *sea = mi->second;
ssValue >> ekPak;
std::vector<CEKAKeyPack>::iterator it;
for (it = ekPak.begin(); it != ekPak.end(); ++it)
{
sea->mapKeys[it->id] = it->ak;
};
};
ssKey.clear();
ssKey << std::string("espk");
fFlags = DB_SET_RANGE;
while (wdb.ReadAtCursor(pcursor, ssKey, ssValue, fFlags) == 0)
{
aksPak.clear();
fFlags = DB_NEXT;
ssKey >> strType;
if (strType != "espk")
break;
ssKey >> idAccount;
ssKey >> nPack;
if (fDebug)
LogPrintf("Loading account stealth key pack %s %u\n", idAccount.ToString().c_str(), nPack);
ExtKeyAccountMap::iterator mi = mapExtAccounts.find(idAccount);
if (mi == mapExtAccounts.end())
{
CBitcoinAddress addr;
addr.Set(idAccount, CChainParams::EXT_ACC_HASH);
LogPrintf("Warning: Unknown account %s.\n", addr.ToString().c_str());
continue;
};
CExtKeyAccount *sea = mi->second;
ssValue >> aksPak;
std::vector<CEKAStealthKeyPack>::iterator it;
for (it = aksPak.begin(); it != aksPak.end(); ++it)
{
sea->mapStealthKeys[it->id] = it->aks;
};
};
ssKey.clear();
ssKey << std::string("ecpk");
fFlags = DB_SET_RANGE;
while (wdb.ReadAtCursor(pcursor, ssKey, ssValue, fFlags) == 0)
{
aksPak.clear();
fFlags = DB_NEXT;
ssKey >> strType;
if (strType != "ecpk")
break;
ssKey >> idAccount;
ssKey >> nPack;
if (fDebug)
LogPrintf("Loading account stealth child key pack %s %u\n", idAccount.ToString().c_str(), nPack);
ExtKeyAccountMap::iterator mi = mapExtAccounts.find(idAccount);
if (mi == mapExtAccounts.end())
{
CBitcoinAddress addr;
addr.Set(idAccount, CChainParams::EXT_ACC_HASH);
LogPrintf("Warning: Unknown account %s.\n", addr.ToString().c_str());
continue;
};
CExtKeyAccount *sea = mi->second;
ssValue >> asckPak;
std::vector<CEKASCKeyPack>::iterator it;
for (it = asckPak.begin(); it != asckPak.end(); ++it)
{
sea->mapStealthChildKeys[it->id] = it->asck;
};
};
pcursor->close();
return 0;
};
int CWallet::ExtKeyAppendToPack(CWalletDB *pwdb, CExtKeyAccount *sea, const CKeyID &idKey, CEKAKey &ak, bool &fUpdateAcc) const
{
// - must call WriteExtAccount after
CKeyID idAccount = sea->GetID();
std::vector<CEKAKeyPack> ekPak;
if (!pwdb->ReadExtKeyPack(idAccount, sea->nPack, ekPak))
{
// -- new pack
ekPak.clear();
if (fDebug)
LogPrintf("Account %s, starting new keypack %u.\n", idAccount.ToString(), sea->nPack);
};
try { ekPak.push_back(CEKAKeyPack(idKey, ak)); } catch (std::exception& e)
{
return errorN(1, "%s push_back failed.", __func__, sea->nPack);
};
if (!pwdb->WriteExtKeyPack(idAccount, sea->nPack, ekPak))
{
return errorN(1, "%s Save key pack %u failed.", __func__, sea->nPack);
};
fUpdateAcc = false;
if ((uint32_t)ekPak.size() >= MAX_KEY_PACK_SIZE-1)
{
fUpdateAcc = true;
sea->nPack++;
};
return 0;
};
int CWallet::ExtKeyAppendToPack(CWalletDB *pwdb, CExtKeyAccount *sea, const CKeyID &idKey, CEKASCKey &asck, bool &fUpdateAcc) const
{
// - must call WriteExtAccount after
CKeyID idAccount = sea->GetID();
std::vector<CEKASCKeyPack> asckPak;
if (!pwdb->ReadExtStealthKeyChildPack(idAccount, sea->nPackStealthKeys, asckPak))
{
// -- new pack
asckPak.clear();
if (fDebug)
LogPrintf("Account %s, starting new stealth child keypack %u.\n", idAccount.ToString(), sea->nPackStealthKeys);
};
try { asckPak.push_back(CEKASCKeyPack(idKey, asck)); } catch (std::exception& e)
{
return errorN(1, "%s push_back failed.", __func__);
};
if (!pwdb->WriteExtStealthKeyChildPack(idAccount, sea->nPackStealthKeys, asckPak))
return errorN(1, "%s Save key pack %u failed.", __func__, sea->nPackStealthKeys);
fUpdateAcc = false;
if ((uint32_t)asckPak.size() >= MAX_KEY_PACK_SIZE-1)
{
sea->nPackStealthKeys++;
fUpdateAcc = true;
};
return 0;
};
int CWallet::ExtKeySaveKey(CWalletDB *pwdb, CExtKeyAccount *sea, const CKeyID &keyId, CEKAKey &ak) const
{
if (fDebug)
{
CBitcoinAddress addr(keyId);
LogPrintf("%s %s %s.\n", __func__, sea->GetIDString58().c_str(), addr.ToString().c_str());
AssertLockHeld(cs_wallet);
};
if (!sea->SaveKey(keyId, ak))
return errorN(1, "%s SaveKey failed.", __func__);
bool fUpdateAcc;
if (0 != ExtKeyAppendToPack(pwdb, sea, keyId, ak, fUpdateAcc))
return errorN(1, "%s ExtKeyAppendToPack failed.", __func__);
CStoredExtKey *pc = sea->GetChain(ak.nParent);
if (!pc)
return errorN(1, "%s GetChain failed.", __func__);
CKeyID idChain = sea->vExtKeyIDs[ak.nParent];
if (!pwdb->WriteExtKey(idChain, *pc))
return errorN(1, "%s WriteExtKey failed.", __func__);
if (fUpdateAcc) // only neccessary if nPack has changed
{
CKeyID idAccount = sea->GetID();
if (!pwdb->WriteExtAccount(idAccount, *sea))
return errorN(1, "%s WriteExtAccount failed.", __func__);
};
return 0;
};
int CWallet::ExtKeySaveKey(CExtKeyAccount *sea, const CKeyID &keyId, CEKAKey &ak) const
{
//LOCK(cs_wallet);
if (fDebug)
AssertLockHeld(cs_wallet);
CWalletDB wdb(strWalletFile, "r+");
if (!wdb.TxnBegin())
return errorN(1, "%s TxnBegin failed.", __func__);
if (0 != ExtKeySaveKey(&wdb, sea, keyId, ak))
{
wdb.TxnAbort();
return 1;
};
if (!wdb.TxnCommit())
return errorN(1, "%s TxnCommit failed.", __func__);
return 0;
};
int CWallet::ExtKeySaveKey(CWalletDB *pwdb, CExtKeyAccount *sea, const CKeyID &keyId, CEKASCKey &asck) const
{
if (fDebug)
{
CBitcoinAddress addr(keyId);
LogPrintf("%s %s %s.\n", __func__, sea->GetIDString58().c_str(), addr.ToString().c_str());
AssertLockHeld(cs_wallet);
};
if (!sea->SaveKey(keyId, asck))
return errorN(1, "%s SaveKey failed.", __func__);
bool fUpdateAcc;
if (0 != ExtKeyAppendToPack(pwdb, sea, keyId, asck, fUpdateAcc))
return errorN(1, "%s ExtKeyAppendToPack failed.", __func__);
if (fUpdateAcc) // only neccessary if nPackStealth has changed
{
CKeyID idAccount = sea->GetID();
if (!pwdb->WriteExtAccount(idAccount, *sea))
return errorN(1, "%s WriteExtAccount failed.", __func__);
};
return 0;
};
int CWallet::ExtKeySaveKey(CExtKeyAccount *sea, const CKeyID &keyId, CEKASCKey &asck) const
{
if (fDebug)
AssertLockHeld(cs_wallet);
CWalletDB wdb(strWalletFile, "r+");
if (!wdb.TxnBegin())
return errorN(1, "%s TxnBegin failed.", __func__);
if (0 != ExtKeySaveKey(&wdb, sea, keyId, asck))
{
wdb.TxnAbort();
return 1;
};
if (!wdb.TxnCommit())
return errorN(1, "%s TxnCommit failed.", __func__);
return 0;
};
int CWallet::ExtKeyUpdateStealthAddress(CWalletDB *pwdb, CExtKeyAccount *sea, CKeyID &sxId, std::string &sLabel)
{
if (fDebug)
{
LogPrintf("%s.\n", __func__);
AssertLockHeld(cs_wallet);
};
AccStealthKeyMap::iterator it = sea->mapStealthKeys.find(sxId);
if (it == sea->mapStealthKeys.end())
return errorN(1, "%s: Stealth key not in account.", __func__);
if (it->second.sLabel == sLabel)
return 0; // no change
CKeyID accId = sea->GetID();
std::vector<CEKAStealthKeyPack> aksPak;
for (uint32_t i = 0; i <= sea->nPackStealth; ++i)
{
if (!pwdb->ReadExtStealthKeyPack(accId, i, aksPak))
return errorN(1, "%s: ReadExtStealthKeyPack %d failed.", __func__, i);
std::vector<CEKAStealthKeyPack>::iterator itp;
for (itp = aksPak.begin(); itp != aksPak.end(); ++itp)
{
if (itp->id == sxId)
{
itp->aks.sLabel = sLabel;
if (!pwdb->WriteExtStealthKeyPack(accId, i, aksPak))
return errorN(1, "%s: WriteExtStealthKeyPack %d failed.", __func__, i);
it->second.sLabel = sLabel;
return 0;
};
};
};
return errorN(1, "%s: Stealth key not in db.", __func__);
};
int CWallet::NewKeyFromAccount(CWalletDB *pwdb, const CKeyID &idAccount, CPubKey &pkOut, bool fInternal, bool fHardened)
{
if (fDebug)
{
CBitcoinAddress addr;
addr.Set(idAccount, CChainParams::EXT_ACC_HASH);
LogPrintf("%s %s.\n", __func__, addr.ToString().c_str());
AssertLockHeld(cs_wallet);
};
assert(pwdb);
if (fHardened
&& IsLocked())
return errorN(1, "%s Wallet must be unlocked to derive hardened keys.", __func__);
ExtKeyAccountMap::iterator mi = mapExtAccounts.find(idAccount);
if (mi == mapExtAccounts.end())
return errorN(1, "%s Unknown account.", __func__);
CExtKeyAccount *sea = mi->second;
CStoredExtKey *sek = NULL;
uint32_t nExtKey = fInternal ? sea->nActiveInternal : sea->nActiveExternal;
if (nExtKey < sea->vExtKeys.size())
sek = sea->vExtKeys[nExtKey];
if (!sek)
return errorN(1, "%s Unknown chain.", __func__);
uint32_t nChildBkp = fHardened ? sek->nHGenerated : sek->nGenerated;
uint32_t nChildOut;
if (0 != sek->DeriveNextKey(pkOut, nChildOut, fHardened))
return errorN(1, "%s Derive failed.", __func__);
CEKAKey ks(nExtKey, nChildOut);
CKeyID idKey = pkOut.GetID();
bool fUpdateAcc;
if (0 != ExtKeyAppendToPack(pwdb, sea, idKey, ks, fUpdateAcc))
{
sek->SetCounter(nChildBkp, fHardened);
return errorN(1, "%s ExtKeyAppendToPack failed.", __func__);
};
if (!pwdb->WriteExtKey(sea->vExtKeyIDs[nExtKey], *sek))
{
sek->SetCounter(nChildBkp, fHardened);
return errorN(1, "%s Save account chain failed.", __func__);
};
if (fUpdateAcc)
{
CKeyID idAccount = sea->GetID();
if (!pwdb->WriteExtAccount(idAccount, *sea))
{
sek->SetCounter(nChildBkp, fHardened);
return errorN(1, "%s Save account chain failed.", __func__);
};
};
sea->SaveKey(idKey, ks); // remove from lookahead, add to pool, add new lookahead
return 0;
};
int CWallet::NewKeyFromAccount(CPubKey &pkOut, bool fInternal, bool fHardened)
{
LOCK(cs_wallet);
CWalletDB wdb(strWalletFile, "r+");
if (!wdb.TxnBegin())
return errorN(1, "%s TxnBegin failed.", __func__);
if (0 != NewKeyFromAccount(&wdb, idDefaultAccount, pkOut, fInternal, fHardened))
{
wdb.TxnAbort();
return 1;
};
if (!wdb.TxnCommit())
return errorN(1, "%s TxnCommit failed.", __func__);
return 0;
};
int CWallet::NewStealthKeyFromAccount(CWalletDB *pwdb, const CKeyID &idAccount, std::string &sLabel, CEKAStealthKey &akStealthOut)
{
if (fDebug)
{
CBitcoinAddress addr;
addr.Set(idAccount, CChainParams::EXT_ACC_HASH);
LogPrintf("%s %s.\n", __func__, addr.ToString().c_str());
AssertLockHeld(cs_wallet);
};
assert(pwdb);
if (IsLocked())
return errorN(1, "%s Wallet must be unlocked to derive hardened keys.", __func__);
ExtKeyAccountMap::iterator mi = mapExtAccounts.find(idAccount);
if (mi == mapExtAccounts.end())
return errorN(1, "%s Unknown account.", __func__);
CExtKeyAccount *sea = mi->second;
uint32_t nChain = sea->nActiveStealth;
if (nChain >= sea->vExtKeys.size())
return errorN(1, "%s Stealth chain unknown %d.", __func__, nChain);
CStoredExtKey *sek = sea->vExtKeys[nChain];
// - scan secrets must be stored uncrypted - always derive hardened keys
uint32_t nChildBkp = sek->nHGenerated;
CKey kScan, kSpend;
uint32_t nScanOut, nSpendOut;
if (0 != sek->DeriveNextKey(kScan, nScanOut, true))
return errorN(1, "%s Derive failed.", __func__);
if (0 != sek->DeriveNextKey(kSpend, nSpendOut, true))
{
sek->SetCounter(nChildBkp, true);
return errorN(1, "%s Derive failed.", __func__);
};
CEKAStealthKey aks(nChain, nScanOut, kScan, nChain, nSpendOut, kSpend);
aks.sLabel = sLabel;
std::vector<CEKAStealthKeyPack> aksPak;
CKeyID idKey = aks.GetID();
sea->mapStealthKeys[idKey] = aks;
if (!pwdb->ReadExtStealthKeyPack(idAccount, sea->nPackStealth, aksPak))
{
// -- new pack
aksPak.clear();
if (fDebug)
LogPrintf("Account %s, starting new stealth keypack %u.\n", idAccount.ToString(), sea->nPackStealth);
};
aksPak.push_back(CEKAStealthKeyPack(idKey, aks));
if (!pwdb->WriteExtStealthKeyPack(idAccount, sea->nPackStealth, aksPak))
{
sea->mapStealthKeys.erase(idKey);
sek->SetCounter(nChildBkp, true);
return errorN(1, "%s Save key pack %u failed.", __func__, sea->nPackStealth);
};
if ((uint32_t)aksPak.size() >= MAX_KEY_PACK_SIZE-1)
sea->nPackStealth++;
if (!pwdb->WriteExtKey(sea->vExtKeyIDs[nChain], *sek))
{
sea->mapStealthKeys.erase(idKey);
sek->SetCounter(nChildBkp, true);
return errorN(1, "%s Save account chain failed.", __func__);
};
bool fOwned = true;
CStealthAddress sxAddr;
if (0 != aks.SetSxAddr(sxAddr))
return errorN(1, "%s SetSxAddr failed.", __func__);
NotifyAddressBookChanged(this, sxAddr, sLabel, fOwned, CT_NEW, true);
akStealthOut = aks;
return 0;
};
int CWallet::NewStealthKeyFromAccount(std::string &sLabel, CEKAStealthKey &akStealthOut)
{
LOCK(cs_wallet);
CWalletDB wdb(strWalletFile, "r+");
if (!wdb.TxnBegin())
return errorN(1, "%s TxnBegin failed.", __func__);
if (0 != NewStealthKeyFromAccount(&wdb, idDefaultAccount, sLabel, akStealthOut))
{
wdb.TxnAbort();
return 1;
};
if (!wdb.TxnCommit())
return errorN(1, "%s TxnCommit failed.", __func__);
return 0;
};
int CWallet::NewExtKeyFromAccount(CWalletDB *pwdb, const CKeyID &idAccount, std::string &sLabel, CStoredExtKey *sekOut)
{
if (fDebug)
{
CBitcoinAddress addr;
addr.Set(idAccount, CChainParams::EXT_ACC_HASH);
LogPrintf("%s %s.\n", __func__, addr.ToString().c_str());
AssertLockHeld(cs_wallet);
};
assert(pwdb);
if (IsLocked())
return errorN(1, "%s Wallet must be unlocked to derive hardened keys.", __func__);
bool fHardened = false; // TODO: make option
ExtKeyAccountMap::iterator mi = mapExtAccounts.find(idAccount);
if (mi == mapExtAccounts.end())
return errorN(1, "%s Unknown account.", __func__);
CExtKeyAccount *sea = mi->second;
CStoredExtKey *sekAccount = sea->ChainAccount();
if (!sekAccount)
return errorN(1, "%s Unknown chain.", __func__);
std::vector<uint8_t> vAccountPath, v;
mapEKValue_t::iterator miV = sekAccount->mapValue.find(EKVT_PATH);
if (miV != sekAccount->mapValue.end())
vAccountPath = miV->second;
CExtKey evNewKey;
uint32_t nOldGen = sekAccount->GetCounter(fHardened);
uint32_t nNewChildNo;
if (sekAccount->DeriveNextKey(evNewKey, nNewChildNo, fHardened) != 0)
return errorN(1, "DeriveNextKey failed.");
sekOut->nFlags |= EAF_ACTIVE | EAF_RECEIVE_ON | EAF_IN_ACCOUNT;
sekOut->kp = evNewKey;
sekOut->mapValue[EKVT_PATH] = PushUInt32(vAccountPath, nNewChildNo);
sekOut->mapValue[EKVT_CREATED_AT] = SetCompressedInt64(v, GetTime());
sekOut->sLabel = sLabel;
if (IsCrypted()
&& ExtKeyEncrypt(sekOut, vMasterKey, false) != 0)
{
sekAccount->SetCounter(nOldGen, fHardened);
return errorN(1, "ExtKeyEncrypt failed.");
};
size_t chainNo = sea->vExtKeyIDs.size();
CKeyID idNewChain = sekOut->GetID();
sea->vExtKeyIDs.push_back(idNewChain);
sea->vExtKeys.push_back(sekOut);
if (!pwdb->WriteExtAccount(idAccount, *sea)
|| !pwdb->WriteExtKey(idAccount, *sekAccount)
|| !pwdb->WriteExtKey(idNewChain, *sekOut))
{
sekAccount->SetCounter(nOldGen, fHardened);
return errorN(1, "DB Write failed.");
};
sea->AddLookAhead(chainNo, N_DEFAULT_LOOKAHEAD);
mapExtKeys[idNewChain] = sekOut;
return 0;
};
int CWallet::NewExtKeyFromAccount(std::string &sLabel, CStoredExtKey *sekOut)
{
LOCK(cs_wallet);
CWalletDB wdb(strWalletFile, "r+");
if (!wdb.TxnBegin())
return errorN(1, "%s TxnBegin failed.", __func__);
if (0 != NewExtKeyFromAccount(&wdb, idDefaultAccount, sLabel, sekOut))
{
wdb.TxnAbort();
return 1;
};
if (!wdb.TxnCommit())
return errorN(1, "%s TxnCommit failed.", __func__);
return 0;
};
int CWallet::ExtKeyGetDestination(const CExtKeyPair &ek, CScript &scriptPubKeyOut, uint32_t &nKey)
{
if (fDebug)
{
CExtKey58 ek58;
ek58.SetKeyP(ek);
LogPrintf("%s: %s.\n", __func__, ek58.ToString().c_str());
AssertLockHeld(cs_wallet);
};
/*
get the next destination,
if key is not saved yet, return 1st key
don't save key here, save after derived key has been sucessfully used
*/
CKeyID keyId = ek.GetID();
CWalletDB wdb(strWalletFile, "r+");
CPubKey pkDest;
CStoredExtKey sek;
if (wdb.ReadExtKey(keyId, sek))
{
if (0 != sek.DeriveNextKey(pkDest, nKey))
return errorN(1, "%s: DeriveNextKey failed.", __func__);
scriptPubKeyOut.SetDestination(pkDest.GetID());
return 0;
} else
{
nKey = 0; // AddLookAhead starts from 0
for (uint32_t i = 0; i < MAX_DERIVE_TRIES; ++i)
{
if (ek.Derive(pkDest, nKey))
{
scriptPubKeyOut.SetDestination(pkDest.GetID());
return 0;
};
nKey++;
};
};
return errorN(1, "%s: Could not derive key.", __func__);
};
int CWallet::ExtKeyUpdateLooseKey(const CExtKeyPair &ek, uint32_t nKey, bool fAddToAddressBook)
{
if (fDebug)
{
CExtKey58 ek58;
ek58.SetKeyP(ek);
LogPrintf("%s %s.\n", __func__, ek58.ToString().c_str());
AssertLockHeld(cs_wallet);
};
CKeyID keyId = ek.GetID();
CWalletDB wdb(strWalletFile, "r+");
CStoredExtKey sek;
if (wdb.ReadExtKey(keyId, sek))
{
sek.nGenerated = nKey;
if (!wdb.WriteExtKey(keyId, sek))
return errorN(1, "%s: WriteExtKey failed.", __func__);
} else
{
sek.kp = ek;
sek.nGenerated = nKey;
if (0 != ExtKeyImportLoose(&wdb, sek, false, false))
return errorN(1, "%s: ExtKeyImportLoose failed.", __func__);
};
if (fAddToAddressBook
&& !mapAddressBook.count(CTxDestination(ek)))
{
SetAddressBookName(ek, "");
};
return 0;
};
bool CWallet::HaveKey(const CKeyID &address) const
{
//AssertLockHeld(cs_wallet);
LOCK(cs_wallet);
CEKAKey ak;
int rv;
ExtKeyAccountMap::const_iterator it;
for (it = mapExtAccounts.begin(); it != mapExtAccounts.end(); ++it)
{
rv = it->second->HaveKey(address, true, ak);
if (rv == 1)
return true;
if (rv == 3)
{
if (0 != ExtKeySaveKey(it->second, address, ak))
return error("HaveKey() ExtKeySaveKey failed.");
return true;
};
};
return CCryptoKeyStore::HaveKey(address);
};
bool CWallet::HaveExtKey(const CKeyID &keyID) const
{
LOCK(cs_wallet);
// NOTE: This only checks keys currently in memory (mapExtKeys)
// There may be other extkeys in the db.
ExtKeyMap::const_iterator it = mapExtKeys.find(keyID);
if (it != mapExtKeys.end())
return true;
return false;
};
bool CWallet::GetKey(const CKeyID &address, CKey &keyOut) const
{
//AssertLockHeld(cs_wallet);
LOCK(cs_wallet);
ExtKeyAccountMap::const_iterator it;
for (it = mapExtAccounts.begin(); it != mapExtAccounts.end(); ++it)
{
if (it->second->GetKey(address, keyOut))
return true;
};
return CCryptoKeyStore::GetKey(address, keyOut);
};
bool CWallet::GetPubKey(const CKeyID &address, CPubKey& pkOut) const
{
LOCK(cs_wallet);
ExtKeyAccountMap::const_iterator it;
for (it = mapExtAccounts.begin(); it != mapExtAccounts.end(); ++it)
{
if (it->second->GetPubKey(address, pkOut))
return true;
};
return CCryptoKeyStore::GetPubKey(address, pkOut);
};
bool CWallet::HaveStealthAddress(const CStealthAddress &sxAddr) const
{
if (fDebug)
{
AssertLockHeld(cs_wallet);
};
if (stealthAddresses.count(sxAddr))
return true;
CKeyID sxId = CPubKey(sxAddr.scan_pubkey).GetID();
ExtKeyAccountMap::const_iterator mi;
for (mi = mapExtAccounts.begin(); mi != mapExtAccounts.end(); ++mi)
{
CExtKeyAccount *ea = mi->second;
if (ea->mapStealthKeys.size() < 1)
continue;
AccStealthKeyMap::iterator it = ea->mapStealthKeys.find(sxId);
if (it != ea->mapStealthKeys.end())
return true;
};
return false;
};
int CWallet::ScanChainFromTime(int64_t nTimeStartScan)
{
LogPrintf("%s: %d\n", __func__, nTimeStartScan);
if (nNodeMode != NT_FULL)
return errorN(1, "%s: Can't run in thin mode.", __func__);
CBlockIndex *pindex = pindexGenesisBlock;
if (pindex == NULL)
return errorN(1, "%s: Genesis Block is not set.", __func__);
while (pindex && pindex->nTime < nTimeStartScan && pindex->pnext)
pindex = pindex->pnext;
LogPrintf("%s: Starting from height %d.", __func__, pindex->nHeight);
{
LOCK2(cs_main, cs_wallet);
MarkDirty();
ScanForWalletTransactions(pindex, true);
ReacceptWalletTransactions();
} // cs_main, cs_wallet
return 0;
};
/*------------------------------------------------------------------------------
CReserveKey
------------------------------------------------------------------------------*/
bool CReserveKey::GetReservedKey(CPubKey& pubkey)
{
if (nIndex == -1)
{
CKeyPool keypool;
pwallet->ReserveKeyFromKeyPool(nIndex, keypool);
if (nIndex != -1)
{
vchPubKey = keypool.vchPubKey;
} else
{
LogPrintf("is valid: %d", pwallet->vchDefaultKey.IsValid());
if (pwallet->vchDefaultKey.IsValid())
{
LogPrintf("CReserveKey::GetReservedKey(): Warning: Using default key instead of a new key, top up your keypool!");
vchPubKey = pwallet->vchDefaultKey;
} else
return false;
};
};
assert(vchPubKey.IsValid());
pubkey = vchPubKey;
return true;
}
void CReserveKey::KeepKey()
{
if (nIndex != -1)
pwallet->KeepKey(nIndex);
nIndex = -1;
vchPubKey = CPubKey();
}
void CReserveKey::ReturnKey()
{
if (nIndex != -1)
pwallet->ReturnKey(nIndex);
nIndex = -1;
vchPubKey = CPubKey();
}
void CWallet::GetAllReserveKeys(set<CKeyID>& setAddress) const
{
setAddress.clear();
CWalletDB walletdb(strWalletFile);
LOCK2(cs_main, cs_wallet);
BOOST_FOREACH(const int64_t& id, setKeyPool)
{
CKeyPool keypool;
if (!walletdb.ReadPool(id, keypool))
throw runtime_error("GetAllReserveKeyHashes() : read failed");
assert(keypool.vchPubKey.IsValid());
CKeyID keyID = keypool.vchPubKey.GetID();
if (!HaveKey(keyID))
throw runtime_error("GetAllReserveKeyHashes() : unknown key in key pool");
setAddress.insert(keyID);
};
}
void CWallet::UpdatedTransaction(const uint256 &hashTx)
{
{
LOCK(cs_wallet);
// Only notify UI if this transaction is in this wallet
WalletTxMap::const_iterator mi = mapWallet.find(hashTx);
if (mi != mapWallet.end())
NotifyTransactionChanged(this, hashTx, CT_UPDATED);
}
}
void CWallet::GetKeyBirthTimes(std::map<CKeyID, int64_t> &mapKeyBirth) const
{
AssertLockHeld(cs_wallet); // mapKeyMetadata
mapKeyBirth.clear();
// get birth times for keys with metadata
for (std::map<CKeyID, CKeyMetadata>::const_iterator it = mapKeyMetadata.begin(); it != mapKeyMetadata.end(); it++)
if (it->second.nCreateTime)
mapKeyBirth[it->first] = it->second.nCreateTime;
// map in which we'll infer heights of other keys
CBlockIndex *pindexMax = FindBlockByHeight(std::max(0, nBestHeight - 144)); // the tip can be reorganised; use a 144-block safety margin
std::map<CKeyID, CBlockIndex*> mapKeyFirstBlock;
std::set<CKeyID> setKeys;
GetKeys(setKeys);
BOOST_FOREACH(const CKeyID &keyid, setKeys)
{
if (mapKeyBirth.count(keyid) == 0)
mapKeyFirstBlock[keyid] = pindexMax;
};
setKeys.clear();
// if there are no such keys, we're done
if (mapKeyFirstBlock.empty())
return;
// find first block that affects those keys, if there are any left
std::vector<CKeyID> vAffected;
for (WalletTxMap::const_iterator it = mapWallet.begin(); it != mapWallet.end(); it++)
{
// iterate over all wallet transactions...
const CWalletTx &wtx = (*it).second;
std::map<uint256, CBlockIndex*>::const_iterator blit = mapBlockIndex.find(wtx.hashBlock);
if (blit != mapBlockIndex.end() && blit->second->IsInMainChain())
{
// ... which are already in a block
int nHeight = blit->second->nHeight;
BOOST_FOREACH(const CTxOut &txout, wtx.vout)
{
// iterate over all their outputs
::ExtractAffectedKeys(*this, txout.scriptPubKey, vAffected);
BOOST_FOREACH(const CKeyID &keyid, vAffected)
{
// ... and all their affected keys
std::map<CKeyID, CBlockIndex*>::iterator rit = mapKeyFirstBlock.find(keyid);
if (rit != mapKeyFirstBlock.end() && nHeight < rit->second->nHeight)
rit->second = blit->second;
};
vAffected.clear();
};
};
};
// Extract block timestamps for those keys
for (std::map<CKeyID, CBlockIndex*>::const_iterator it = mapKeyFirstBlock.begin(); it != mapKeyFirstBlock.end(); it++)
mapKeyBirth[it->first] = it->second->nTime - 7200; // block times can be 2h off
}
bool IsDestMine(const CWallet &wallet, const CTxDestination &dest)
{
return boost::apply_visitor(CWalletIsMineVisitor(&wallet), dest);
};
static unsigned int HaveKeys(const vector<valtype>& pubkeys, const CWallet& wallet)
{
unsigned int nResult = 0;
BOOST_FOREACH(const valtype& pubkey, pubkeys)
{
CKeyID keyID = CPubKey(pubkey).GetID();
if (wallet.HaveKey(keyID))
++nResult;
}
return nResult;
}
bool IsMine(const CWallet &wallet, const CScript& scriptPubKey)
{
vector<valtype> vSolutions;
txnouttype whichType;
if (!Solver(scriptPubKey, whichType, vSolutions))
return false;
CKeyID keyID;
switch (whichType)
{
case TX_NONSTANDARD:
case TX_NULL_DATA:
return false;
case TX_PUBKEY:
keyID = CPubKey(vSolutions[0]).GetID();
return wallet.HaveKey(keyID);
case TX_PUBKEYHASH:
keyID = CKeyID(uint160(vSolutions[0]));
return wallet.HaveKey(keyID);
case TX_SCRIPTHASH:
{
CScript subscript;
if (!wallet.GetCScript(CScriptID(uint160(vSolutions[0])), subscript))
return false;
return IsMine(wallet, subscript);
}
case TX_MULTISIG:
{
// Only consider transactions "mine" if we own ALL the
// keys involved. multi-signature transactions that are
// partially owned (somebody else has a key that can spend
// them) enable spend-out-from-under-you attacks, especially
// in shared-wallet situations.
std::vector<valtype> keys(vSolutions.begin()+1, vSolutions.begin()+vSolutions.size()-1);
return HaveKeys(keys, wallet) == keys.size();
}
}
return false;
}
|
#include "Application.h"
#include "WindowInspector.h"
#include "ModuleWindow.h"
#include "GameObject.h"
#include "Component.h"
Inspector::Inspector() : WindowManager()
{
active.push_back(Active());
name = "Inspector";
}
Inspector::~Inspector()
{
active.clear();
selected_object = nullptr;
}
bool Inspector::Start()
{
return true;
}
update_status Inspector::Update(float dt)
{
if (active[0].active)
ShowInspector();
return UPDATE_CONTINUE;
}
void Inspector::ShowInspector()
{
static int width;
static int height;
SDL_GetWindowSize(App->window->window, &width, &height);
ImGui::SetNextWindowPos(ImVec2(width - 300, 20));
ImGui::SetNextWindowSize(ImVec2(300, height - 20 - (height - 700)));
if (!BeginDock("Inspector", NULL, ImGuiWindowFlags_NoScrollbar))
{
EndDock();
return;
}
ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(12, 3));
ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(6, 2));
if (selected_object != nullptr)
{
selected_object->ShowInspectorInfo();
}
ImGui::PopStyleVar(2);
EndDock();
}
void Inspector::LinkObject(GameObject * obj)
{
if (obj != nullptr)
{
selected_object = obj;
if (selected_object->GetParent() != nullptr)
{
GameObject* parent_open = selected_object->GetParent();
while (parent_open != nullptr)
{
parent_open->set_next_tree_node_open = true;
parent_open = parent_open->GetParent();
}
}
}
}
void Inspector::SetLinkObjectNull()
{
selected_object = nullptr;
}
GameObject* Inspector::GetSelected() const
{
return selected_object;
}
void Inspector::SetComponentCopy(Component* copy)
{
if (copy != nullptr)
{
copied = copy;
}
}
bool Inspector::AnyComponentCopied()
{
return (copied != nullptr);
}
void Inspector::SetLinkComponentNull()
{
copied = nullptr;
}
Component * Inspector::GetComponentCopied()
{
return copied;
}
bool Inspector::CleanUp()
{
return true;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.