text
stringlengths 5
1.04M
|
|---|
/*
* Copyright (c) 2012 ARM Limited
* All rights reserved
*
* The license below extends only to copyright in the software and shall
* not be construed as granting a license to any other intellectual
* property including but not limited to intellectual property relating
* to a hardware implementation of the functionality of the software
* licensed hereunder. You may use the software subject to the license
* terms below provided that you ensure that this notice is replicated
* unmodified and in its entirety in all distributions of the software,
* modified or unmodified, in source code or in binary form.
*
* Copyright (c) 2002-2005 The Regents of The University of Michigan
* Copyright (c) 2011 Regents of the University of California
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Steve Reinhardt
* Lisa Hsu
* Nathan Binkert
* Rick Strong
*/
#ifndef __SYSTEM_HH__
#define __SYSTEM_HH__
//#define FIXADDR 0
#include <string>
#include <vector>
#include "base/loader/symtab.hh"
#include "base/misc.hh"
#include "base/statistics.hh"
#include "cpu/pc_event.hh"
#include "enums/MemoryMode.hh"
#include "kern/system_events.hh"
#include "mem/fs_translating_port_proxy.hh"
#include "mem/mem_object.hh"
#include "mem/port.hh"
#include "mem/physical.hh"
#include "params/System.hh"
class BaseCPU;
class BaseRemoteGDB;
class GDBListener;
class ObjectFile;
class Platform;
class ThreadContext;
class System : public MemObject
{
private:
/**
* Private class for the system port which is only used as a
* master for debug access and for non-structural entities that do
* not have a port of their own.
*/
class SystemPort : public MasterPort
{
public:
/**
* Create a system port with a name and an owner.
*/
SystemPort(const std::string &_name, MemObject *_owner)
: MasterPort(_name, _owner)
{ }
bool recvTimingResp(PacketPtr pkt)
{ panic("SystemPort does not receive timing!\n"); return false; }
void recvRetry()
{ panic("SystemPort does not expect retry!\n"); }
};
SystemPort _systemPort;
public:
static bool is_fast_forward;
int num_exits;
/**
* After all objects have been created and all ports are
* connected, check that the system port is connected.
*/
virtual void init();
/**
* Get a reference to the system port that can be used by
* non-structural simulation objects like processes or threads, or
* external entities like loaders and debuggers, etc, to access
* the memory system.
*
* @return a reference to the system port we own
*/
MasterPort& getSystemPort() { return _systemPort; }
/**
* Additional function to return the Port of a memory object.
*/
MasterPort& getMasterPort(const std::string &if_name, int idx = -1);
static const char *MemoryModeStrings[3];
Enums::MemoryMode
getMemoryMode()
{
assert(memoryMode);
return memoryMode;
}
/** Change the memory mode of the system. This should only be called by the
* python!!
* @param mode Mode to change to (atomic/timing)
*/
void setMemoryMode(Enums::MemoryMode mode);
PCEventQueue pcEventQueue;
std::vector<ThreadContext *> threadContexts;
int _numContexts;
ThreadContext *getThreadContext(ThreadID tid)
{
return threadContexts[tid];
}
int numContexts()
{
assert(_numContexts == (int)threadContexts.size());
return _numContexts;
}
/** Return number of running (non-halted) thread contexts in
* system. These threads could be Active or Suspended. */
int numRunningContexts();
Addr pagePtr[4];
bool fixAddr;
uint64_t init_param;
/** Port to physical memory used for writing object files into ram at
* boot.*/
PortProxy physProxy;
FSTranslatingPortProxy virtProxy;
/** kernel symbol table */
SymbolTable *kernelSymtab;
/** Object pointer for the kernel code */
ObjectFile *kernel;
/** Begining of kernel code */
Addr kernelStart;
/** End of kernel code */
Addr kernelEnd;
/** Entry point in the kernel to start at */
Addr kernelEntry;
/** Mask that should be anded for binary/symbol loading.
* This allows one two different OS requirements for the same ISA to be
* handled. Some OSes are compiled for a virtual address and need to be
* loaded into physical memory that starts at address 0, while other
* bare metal tools generate images that start at address 0.
*/
Addr loadAddrMask;
protected:
uint64_t nextPID;
public:
uint64_t allocatePID()
{
return nextPID++;
}
/** Get a pointer to access the physical memory of the system */
PhysicalMemory& getPhysMem() { return physmem; }
/** Amount of physical memory that is still free */
Addr freeMemSize() const;
/** Amount of physical memory that exists */
Addr memSize() const;
/**
* Check if a physical address is within a range of a memory that
* is part of the global address map.
*
* @param addr A physical address
* @return Whether the address corresponds to a memory
*/
bool isMemAddr(Addr addr) const;
protected:
PhysicalMemory physmem;
Enums::MemoryMode memoryMode;
uint64_t workItemsBegin;
uint64_t workItemsEnd;
uint32_t numWorkIds;
std::vector<bool> activeCpus;
/** This array is a per-sytem list of all devices capable of issuing a
* memory system request and an associated string for each master id.
* It's used to uniquely id any master in the system by name for things
* like cache statistics.
*/
std::vector<std::string> masterIds;
public:
/** Request an id used to create a request object in the system. All objects
* that intend to issues requests into the memory system must request an id
* in the init() phase of startup. All master ids must be fixed by the
* regStats() phase that immediately preceeds it. This allows objects in the
* memory system to understand how many masters may exist and
* appropriately name the bins of their per-master stats before the stats
* are finalized
*/
MasterID getMasterId(std::string req_name);
/** Get the name of an object for a given request id.
*/
std::string getMasterName(MasterID master_id);
/** Get the number of masters registered in the system */
MasterID maxMasters()
{
return masterIds.size();
}
virtual void regStats();
/**
* Called by pseudo_inst to track the number of work items started by this
* system.
*/
uint64_t
incWorkItemsBegin()
{
return ++workItemsBegin;
}
/**
* Called by pseudo_inst to track the number of work items completed by
* this system.
*/
uint64_t
incWorkItemsEnd()
{
return ++workItemsEnd;
}
/**
* Called by pseudo_inst to mark the cpus actively executing work items.
* Returns the total number of cpus that have executed work item begin or
* ends.
*/
int
markWorkItem(int index)
{
int count = 0;
assert(index < activeCpus.size());
activeCpus[index] = true;
for (std::vector<bool>::iterator i = activeCpus.begin();
i < activeCpus.end(); i++) {
if (*i) count++;
}
return count;
}
inline void workItemBegin(uint32_t tid, uint32_t workid)
{
std::pair<uint32_t,uint32_t> p(tid, workid);
lastWorkItemStarted[p] = curTick();
}
void workItemEnd(uint32_t tid, uint32_t workid);
/**
* Fix up an address used to match PCs for hooking simulator
* events on to target function executions. See comment in
* system.cc for details.
*/
virtual Addr fixFuncEventAddr(Addr addr)
{
panic("Base fixFuncEventAddr not implemented.\n");
}
/**
* Add a function-based event to the given function, to be looked
* up in the specified symbol table.
*/
template <class T>
T *addFuncEvent(SymbolTable *symtab, const char *lbl)
{
Addr addr = 0; // initialize only to avoid compiler warning
if (symtab->findAddress(lbl, addr)) {
T *ev = new T(&pcEventQueue, lbl, fixFuncEventAddr(addr));
return ev;
}
return NULL;
}
/** Add a function-based event to kernel code. */
template <class T>
T *addKernelFuncEvent(const char *lbl)
{
return addFuncEvent<T>(kernelSymtab, lbl);
}
public:
std::vector<BaseRemoteGDB *> remoteGDB;
std::vector<GDBListener *> gdbListen;
bool breakpoint();
public:
typedef SystemParams Params;
protected:
Params *_params;
public:
System(Params *p);
~System();
void initState();
const Params *params() const { return (const Params *)_params; }
public:
/**
* Returns the addess the kernel starts at.
* @return address the kernel starts at
*/
Addr getKernelStart() const { return kernelStart; }
/**
* Returns the addess the kernel ends at.
* @return address the kernel ends at
*/
Addr getKernelEnd() const { return kernelEnd; }
/**
* Returns the addess the entry point to the kernel code.
* @return entry point of the kernel code
*/
Addr getKernelEntry() const { return kernelEntry; }
/// Allocate npages contiguous unused physical pages
/// @return Starting address of first page
Addr allocPhysPages(int npages, int pid);
int registerThreadContext(ThreadContext *tc, int assigned=-1);
void replaceThreadContext(ThreadContext *tc, int context_id);
void serialize(std::ostream &os);
void unserialize(Checkpoint *cp, const std::string §ion);
virtual void resume();
public:
Counter totalNumInsts;
EventQueue instEventQueue;
std::map<std::pair<uint32_t,uint32_t>, Tick> lastWorkItemStarted;
std::map<uint32_t, Stats::Histogram*> workItemStats;
////////////////////////////////////////////
//
// STATIC GLOBAL SYSTEM LIST
//
////////////////////////////////////////////
static std::vector<System *> systemList;
static int numSystemsRunning;
static void printSystems();
// For futex system call
std::map<uint64_t, std::list<ThreadContext *> * > futexMap;
};
#endif // __SYSTEM_HH__
|
/*******************************************************************************
* Copyright (c) 2015, Lawrence Livermore National Security, LLC
* Produced at the Lawrence Livermore National Laboratory
* Written by Peer-Timo Bremer bremer5@llnl.gov
* LLNL-CODE-665196
* All rights reserved.
*
* This file is part of ADAPT. For details, see
* https://github.com/scalability-llnl/ADAPT. Please also read the
* additional BSD notice below. 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 disclaimer below.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the disclaimer (as noted below) in
* the documentation and/or other materials provided with the
* distribution.
*
* - Neither the name of the LLNS/LLNL 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 LAWRENCE
* LIVERMORE NATIONAL SECURITY, LLC, THE U.S. DEPARTMENT OF ENERGY 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.
*
* Additional BSD Notice
*
* 1. This notice is required to be provided under our contract with the
* U.S. Department of Energy (DOE). This work was produced at Lawrence
* Livermore National Laboratory under Contract No. DE-AC52-07NA27344
* with the DOE.
*
* 2. Neither the United States Government nor Lawrence Livermore
* National Security, LLC nor any of their employees, makes any warranty,
* express or implied, or assumes any liability or responsibility for the
* accuracy, completeness, or usefulness of any information, apparatus,
* product, or process disclosed, or represents that its use would not
* infringe privately-owned rights.
*
* 3. Also, reference herein to any specific commercial products,
* process, or services by trade name, trademark, manufacturer or
* otherwise does not necessarily constitute or imply its endorsement,
* recommendation, or favoring by the United States Government or
* Lawrence Livermore National Security, LLC. The views and opinions of
* authors expressed herein do not necessarily state or reflect those of
* the United States Government or Lawrence Livermore National Security,
* LLC, and shall not be used for advertising or product endorsement
* purposes.
********************************************************************************/
#include "Relevance.h"
FunctionType Relevance::eval(GlobalIndexType id, LocalIndexType label) const
{
if (label == LNULL)
return this->mDefault;
FunctionType local_max = mData[mTree->node(mTree->node(label).rep()).index()];
return 1 - (local_max - mData[id]) / (local_max - mTree->minimum());
}
|
/*
* ofMainLoop.cpp
*
* Created on: Oct 25, 2014
* Author: arturo
*/
#include <ofMainLoop.h>
#include "ofWindowSettings.h"
#include "ofConstants.h"
//========================================================================
// default windowing
#ifdef TARGET_NODISPLAY
#include "ofAppNoWindow.h"
#elif defined(TARGET_OF_IOS)
#include "ofAppiOSWindow.h"
#elif defined(TARGET_ANDROID)
#include "ofAppAndroidWindow.h"
#elif defined(TARGET_RASPBERRY_PI)
#include "ofAppEGLWindow.h"
#elif defined(TARGET_EMSCRIPTEN)
#include "ofxAppEmscriptenWindow.h"
#else
#include "ofAppGLFWWindow.h"
#endif
ofMainLoop::ofMainLoop()
:bShouldClose(false)
,status(0)
,allowMultiWindow(true)
,windowLoop(NULL)
,pollEvents(NULL)
,escapeQuits(true){
}
ofMainLoop::~ofMainLoop() {
exit();
}
shared_ptr<ofAppBaseWindow> ofMainLoop::createWindow(const ofWindowSettings & settings){
#ifdef TARGET_NODISPLAY
shared_ptr<ofAppNoWindow> window = shared_ptr<ofAppNoWindow>(new ofAppNoWindow());
#else
#if defined(TARGET_OF_IOS)
shared_ptr<ofAppiOSWindow> window = shared_ptr<ofAppiOSWindow>(new ofAppiOSWindow());
#elif defined(TARGET_ANDROID)
shared_ptr<ofAppAndroidWindow> window = shared_ptr<ofAppAndroidWindow>(new ofAppAndroidWindow());
#elif defined(TARGET_RASPBERRY_PI)
shared_ptr<ofAppEGLWindow> window = shared_ptr<ofAppEGLWindow>(new ofAppEGLWindow());
#elif defined(TARGET_EMSCRIPTEN)
shared_ptr<ofxAppEmscriptenWindow> window = shared_ptr<ofxAppEmscriptenWindow>(new ofxAppEmscriptenWindow);
#elif defined(TARGET_OPENGLES)
shared_ptr<ofAppGLFWWindow> window = shared_ptr<ofAppGLFWWindow>(new ofAppGLFWWindow());
#else
shared_ptr<ofAppGLFWWindow> window = shared_ptr<ofAppGLFWWindow>(new ofAppGLFWWindow());
#endif
#endif
addWindow(window);
window->setup(settings);
return window;
}
void ofMainLoop::run(shared_ptr<ofAppBaseWindow> window, shared_ptr<ofBaseApp> app){
windowsApps[window] = app;
if(app){
ofAddListener(window->events().setup,app.get(),&ofBaseApp::setup,OF_EVENT_ORDER_APP);
ofAddListener(window->events().update,app.get(),&ofBaseApp::update,OF_EVENT_ORDER_APP);
ofAddListener(window->events().draw,app.get(),&ofBaseApp::draw,OF_EVENT_ORDER_APP);
ofAddListener(window->events().exit,app.get(),&ofBaseApp::exit,OF_EVENT_ORDER_APP);
ofAddListener(window->events().keyPressed,app.get(),&ofBaseApp::keyPressed,OF_EVENT_ORDER_APP);
ofAddListener(window->events().keyReleased,app.get(),&ofBaseApp::keyReleased,OF_EVENT_ORDER_APP);
ofAddListener(window->events().mouseMoved,app.get(),&ofBaseApp::mouseMoved,OF_EVENT_ORDER_APP);
ofAddListener(window->events().mouseDragged,app.get(),&ofBaseApp::mouseDragged,OF_EVENT_ORDER_APP);
ofAddListener(window->events().mousePressed,app.get(),&ofBaseApp::mousePressed,OF_EVENT_ORDER_APP);
ofAddListener(window->events().mouseReleased,app.get(),&ofBaseApp::mouseReleased,OF_EVENT_ORDER_APP);
ofAddListener(window->events().mouseScrolled,app.get(),&ofBaseApp::mouseScrolled,OF_EVENT_ORDER_APP);
ofAddListener(window->events().windowEntered,app.get(),&ofBaseApp::windowEntry,OF_EVENT_ORDER_APP);
ofAddListener(window->events().windowResized,app.get(),&ofBaseApp::windowResized,OF_EVENT_ORDER_APP);
ofAddListener(window->events().messageEvent,app.get(),&ofBaseApp::messageReceived,OF_EVENT_ORDER_APP);
ofAddListener(window->events().fileDragEvent,app.get(),&ofBaseApp::dragged,OF_EVENT_ORDER_APP);
ofAddListener(window->events().touchCancelled,app.get(),&ofBaseApp::touchCancelled,OF_EVENT_ORDER_APP);
ofAddListener(window->events().touchDoubleTap,app.get(),&ofBaseApp::touchDoubleTap,OF_EVENT_ORDER_APP);
ofAddListener(window->events().touchDown,app.get(),&ofBaseApp::touchDown,OF_EVENT_ORDER_APP);
ofAddListener(window->events().touchMoved,app.get(),&ofBaseApp::touchMoved,OF_EVENT_ORDER_APP);
ofAddListener(window->events().touchUp,app.get(),&ofBaseApp::touchUp,OF_EVENT_ORDER_APP);
}
currentWindow = window;
if(!windowLoop){
window->events().notifySetup();
}
}
void ofMainLoop::run(shared_ptr<ofBaseApp> app){
if(!windowsApps.empty()){
run(windowsApps.begin()->first,app);
}
}
int ofMainLoop::loop(){
if(!windowLoop){
while(!bShouldClose && !windowsApps.empty()){
loopOnce();
}
exit();
}else{
windowLoop();
}
return status;
}
void ofMainLoop::loopOnce(){
for(auto i = windowsApps.begin();i!=windowsApps.end();i++){
if(i->first->getWindowShouldClose()){
i->first->close();
windowsApps.erase(i);
}else{
currentWindow = i->first;
i->first->update();
i->first->draw();
}
}
if(pollEvents){
pollEvents();
}
}
void ofMainLoop::exit(){
for(auto i = windowsApps.begin();i!=windowsApps.end();i++){
shared_ptr<ofAppBaseWindow> window = i->first;
shared_ptr<ofBaseApp> app = i->second;
if(window == NULL) {
continue;
}
if(app == NULL) {
continue;
}
ofRemoveListener(window->events().setup,app.get(),&ofBaseApp::setup,OF_EVENT_ORDER_APP);
ofRemoveListener(window->events().update,app.get(),&ofBaseApp::update,OF_EVENT_ORDER_APP);
ofRemoveListener(window->events().draw,app.get(),&ofBaseApp::draw,OF_EVENT_ORDER_APP);
ofRemoveListener(window->events().exit,app.get(),&ofBaseApp::exit,OF_EVENT_ORDER_APP);
ofRemoveListener(window->events().keyPressed,app.get(),&ofBaseApp::keyPressed,OF_EVENT_ORDER_APP);
ofRemoveListener(window->events().keyReleased,app.get(),&ofBaseApp::keyReleased,OF_EVENT_ORDER_APP);
ofRemoveListener(window->events().mouseMoved,app.get(),&ofBaseApp::mouseMoved,OF_EVENT_ORDER_APP);
ofRemoveListener(window->events().mouseDragged,app.get(),&ofBaseApp::mouseDragged,OF_EVENT_ORDER_APP);
ofRemoveListener(window->events().mousePressed,app.get(),&ofBaseApp::mousePressed,OF_EVENT_ORDER_APP);
ofRemoveListener(window->events().mouseReleased,app.get(),&ofBaseApp::mouseReleased,OF_EVENT_ORDER_APP);
ofRemoveListener(window->events().mouseScrolled,app.get(),&ofBaseApp::mouseScrolled,OF_EVENT_ORDER_APP);
ofRemoveListener(window->events().windowEntered,app.get(),&ofBaseApp::windowEntry,OF_EVENT_ORDER_APP);
ofRemoveListener(window->events().windowResized,app.get(),&ofBaseApp::windowResized,OF_EVENT_ORDER_APP);
ofRemoveListener(window->events().messageEvent,app.get(),&ofBaseApp::messageReceived,OF_EVENT_ORDER_APP);
ofRemoveListener(window->events().fileDragEvent,app.get(),&ofBaseApp::dragged,OF_EVENT_ORDER_APP);
ofRemoveListener(window->events().touchCancelled,app.get(),&ofBaseApp::touchCancelled,OF_EVENT_ORDER_APP);
ofRemoveListener(window->events().touchDoubleTap,app.get(),&ofBaseApp::touchDoubleTap,OF_EVENT_ORDER_APP);
ofRemoveListener(window->events().touchDown,app.get(),&ofBaseApp::touchDown,OF_EVENT_ORDER_APP);
ofRemoveListener(window->events().touchMoved,app.get(),&ofBaseApp::touchMoved,OF_EVENT_ORDER_APP);
ofRemoveListener(window->events().touchUp,app.get(),&ofBaseApp::touchUp,OF_EVENT_ORDER_APP);
}
exitEvent.notify(this);
windowsApps.clear();
}
shared_ptr<ofAppBaseWindow> ofMainLoop::getCurrentWindow(){
return currentWindow;
}
shared_ptr<ofBaseApp> ofMainLoop::getCurrentApp(){
return windowsApps[currentWindow];
}
ofCoreEvents & ofMainLoop::events(){
return currentWindow->events();
}
void ofMainLoop::shouldClose(int _status){
for(auto i = windowsApps.begin();i!=windowsApps.end();i++){
i->first->setWindowShouldClose();
}
bShouldClose = true;
status = _status;
}
void ofMainLoop::setEscapeQuitsLoop(bool quits){
escapeQuits = quits;
}
void ofMainLoop::keyPressed(ofKeyEventArgs & key){
if (key.key == OF_KEY_ESC && escapeQuits == true){ // "escape"
shouldClose(0);
}
}
|
#pragma once
#include <bio/gpu/gpu_Surface.hpp>
#include <bio/service/vi/vi_RootService.hpp>
namespace bio::gpu {
constexpr i64 LayerMinimumZ = -1;
constexpr i64 LayerMaximumZ = -2;
Result Initialize(service::nv::DrvServiceType nv_service_type, service::vi::RootServiceType vi_service_type, u32 transfer_mem_size);
void Finalize();
Result GetHOSBinderDriver(mem::SharedObject<service::dispdrv::HOSBinderDriver> &out_service);
Result GetNvDrvService(mem::SharedObject<service::nv::DrvService> &out_service);
Result GetApplicationDisplayService(mem::SharedObject<service::vi::ApplicationDisplayService> &out_service);
Result GetNvMapFd(u32 &out_fd);
Result GetNvHostFd(u32 &out_fd);
Result GetNvHostCtrlFd(u32 &out_fd);
Result CreateStrayLayerSurface(const char *display_name, service::vi::LayerFlags layer_flags, u32 width, u32 height, u32 buffer_count, ColorFormat color_fmt, PixelFormat pixel_fmt, Layout layout, mem::SharedObject<Surface> &out_surface);
Result CreateManagedLayerSurface(const char *display_name, service::vi::LayerFlags layer_flags, u64 aruid, f32 x, f32 y, u32 width, u32 height, i64 z, u32 buffer_count, ColorFormat color_fmt, PixelFormat pixel_fmt, Layout layout, mem::SharedObject<Surface> &out_surface);
}
|
/*
* $Id$
*
* Author: David Fournier
* Copyright (c) 2008-2012 Regents of the University of California
*/
/**
* \file
* Description not yet available.
*/
#include "fvar.hpp"
/**
* Description not yet available.
* \param
*/
dvar4_array::dvar4_array()
{
allocate();
}
/**
* Description not yet available.
* \param
*/
void dvar4_array::allocate(void)
{
shape=NULL;
t = NULL;
}
|
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <fstream>
#include <string>
#include <evhttp.h>
#include <iostream>
#include <algorithm>
#include <functional>
#include <map>
#include <vector>
#include <regex>
#include <tuple>
#include <cassert>
#include "Server.h"
#include "DB.h"
using namespace Database;
using namespace ServerN;
std::tuple<std::string, URI_TO_PATH_STATUS> ServerN::uri_to_path(const char *uri) {
assert(uri != NULL);
struct evhttp_uri *decodedUri = NULL;
const char *path = NULL;
const char *decodedPath = NULL;
URI_TO_PATH_STATUS status = URI_TO_PATH_STATUS::SUCCESS;
decodedUri = evhttp_uri_parse(uri);
if (!decodedUri) {
status = URI_TO_PATH_STATUS::FAILURE_URI_PARSE;
goto end;
}
path = evhttp_uri_get_path(decodedUri);
if (!path) {
status = URI_TO_PATH_STATUS::FAILURE_URI_TO_PATH;
goto end;
}
decodedPath = evhttp_uridecode(path, 0, NULL);
if (!decodedPath) {
status = URI_TO_PATH_STATUS::FAILURE_PATH_DECODE;
goto end;
}
end:
if (decodedUri) {
evhttp_uri_free(decodedUri);
}
const auto result = std::make_tuple(
(status == URI_TO_PATH_STATUS::SUCCESS ? std::string(decodedPath) : std::string("")),
status
);
free((void *)decodedPath);
return result;
}
Server::Server(const std::string addr, const std::uint16_t prt): address(addr), port(prt) {
onReq = [] (evhttp_request *req, void *) {
const char *uri = evhttp_request_get_uri(req);
std::tuple<std::string, URI_TO_PATH_STATUS> uriTuple = uri_to_path(uri);
const auto path = std::get<0>(uriTuple);
const auto status = std::get<1>(uriTuple);
assert(status == URI_TO_PATH_STATUS::SUCCESS);
struct evbuffer *buffer;
struct evkeyvalq headers;
const char *getParam;
// Parse the query for later lookups
evhttp_parse_query(uri, &headers);
std::string sPath = path;
const std::string jsFilePath = "/client/app.js";
const std::string wasmFilePath = "/client/app.wasm";
std::cout << "Got decoded path " << path << std::endl;
auto *OutBuf = evhttp_request_get_output_buffer(req);
if (!OutBuf)
return;
if (sPath == "/") {
Database::DB* db = new Database::DB();
db->init();
const Router router(db);
char* res = nullptr;
std::map<std::string, std::string> inputData;
if (evhttp_find_header(&headers, "getLeaderboard") != NULL) {
res = router("getLeaderboard", inputData);
evbuffer_add_printf(OutBuf, res);
}
else if (evhttp_find_header(&headers, "insertIntoLeaderboard") != NULL) {
const string name = std::string(evhttp_find_header(&headers, "name"));
const std::string score = std::string(evhttp_find_header(&headers, "score"));
const std::string added = std::string(evhttp_find_header(&headers, "added"));
inputData.insert(pair<std::string, std::string>("name", name));
inputData.insert(pair<std::string, std::string>("score", score));
inputData.insert(pair<std::string, std::string>("added", added));
res = router("insertIntoLeaderboard", inputData);
evbuffer_add_printf(OutBuf, res);
}
else if (evhttp_find_header(&headers, "saveGame") != NULL) {
const string gameString = std::string(evhttp_find_header(&headers, "gameString"));
inputData.insert(pair<std::string, std::string>("gameString", gameString));
res = router("saveGame", inputData);
evbuffer_add_printf(OutBuf, res);
}
else {
/**
* Get the contents of the HTML file.
*/
string singleLine, fileContent;
// open a file in read mode.
ifstream indexFile;
indexFile.open("index.html");
while (getline(indexFile, singleLine)) {
fileContent.append(singleLine);
fileContent.append("\n");
}
// close the opened file.
indexFile.close();
// Convert HTML string into char array.
char fileContentToChar[fileContent.size() + 1];
fileContent.copy(fileContentToChar, fileContent.size() + 1);
fileContentToChar[fileContent.size()] = '\0';
evbuffer_add_printf(OutBuf, fileContentToChar);
evhttp_add_header(evhttp_request_get_output_headers(req),
"Content-Type", "text/html");
}
evhttp_send_reply(req, HTTP_OK, "", OutBuf);
if (res) delete[] res;
inputData.clear();
delete db;
} else {
struct evbuffer *evb = NULL;
struct stat st;
evb = evbuffer_new();
std::regex slash("^\\/");
sPath = std::regex_replace(sPath, slash, "");
int fd = -1;
if ((fd = open(sPath.c_str(), O_RDONLY)) < 0) {
// perror("open");
// goto err;
}
if (fstat(fd, &st) < 0) {
/* Make sure the length still matches, now that we
* opened the file :/ */
// perror("fstat");
// goto err;
}
evbuffer_add_file(evb, fd, 0, st.st_size);
if (path == jsFilePath)
evhttp_add_header(evhttp_request_get_output_headers(req),
"Content-Type", "text/javascript");
if (path == wasmFilePath)
evhttp_add_header(evhttp_request_get_output_headers(req),
"Content-Type", "application/wasm");
evhttp_send_reply(req, HTTP_OK, "", evb);
}
};
};
std::string Server::getAddress() const {
return address;
}
std::uint16_t Server::getPort() const {
return port;
}
fptr Server::getOnReq() const {
return onReq;
};
|
/*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "src/base/test/test_task_runner.h"
#include <stdio.h>
#include <unistd.h>
#include <chrono>
#include "perfetto/base/logging.h"
namespace perfetto {
namespace base {
TestTaskRunner::TestTaskRunner() = default;
TestTaskRunner::~TestTaskRunner() = default;
void TestTaskRunner::Run() {
PERFETTO_DCHECK_THREAD(thread_checker_);
for (;;)
task_runner_.Run();
}
void TestTaskRunner::RunUntilIdle() {
PERFETTO_DCHECK_THREAD(thread_checker_);
task_runner_.PostTask(std::bind(&TestTaskRunner::QuitIfIdle, this));
task_runner_.Run();
}
void TestTaskRunner::QuitIfIdle() {
PERFETTO_DCHECK_THREAD(thread_checker_);
if (task_runner_.IsIdleForTesting()) {
task_runner_.Quit();
return;
}
task_runner_.PostTask(std::bind(&TestTaskRunner::QuitIfIdle, this));
}
void TestTaskRunner::RunUntilCheckpoint(const std::string& checkpoint,
uint32_t timeout_ms) {
PERFETTO_DCHECK_THREAD(thread_checker_);
if (checkpoints_.count(checkpoint) == 0) {
fprintf(stderr, "[TestTaskRunner] Checkpoint \"%s\" does not exist.\n",
checkpoint.c_str());
abort();
}
if (checkpoints_[checkpoint])
return;
task_runner_.PostDelayedTask(
[this, checkpoint] {
if (checkpoints_[checkpoint])
return;
fprintf(stderr, "[TestTaskRunner] Failed to reach checkpoint \"%s\"\n",
checkpoint.c_str());
abort();
},
timeout_ms);
pending_checkpoint_ = checkpoint;
task_runner_.Run();
}
std::function<void()> TestTaskRunner::CreateCheckpoint(
const std::string& checkpoint) {
PERFETTO_DCHECK_THREAD(thread_checker_);
PERFETTO_DCHECK(checkpoints_.count(checkpoint) == 0);
auto checkpoint_iter = checkpoints_.emplace(checkpoint, false);
return [this, checkpoint_iter] {
PERFETTO_DCHECK_THREAD(thread_checker_);
checkpoint_iter.first->second = true;
if (pending_checkpoint_ == checkpoint_iter.first->first) {
pending_checkpoint_.clear();
task_runner_.Quit();
}
};
}
// TaskRunner implementation.
void TestTaskRunner::PostTask(std::function<void()> closure) {
task_runner_.PostTask(std::move(closure));
}
void TestTaskRunner::PostDelayedTask(std::function<void()> closure,
uint32_t delay_ms) {
task_runner_.PostDelayedTask(std::move(closure), delay_ms);
}
void TestTaskRunner::AddFileDescriptorWatch(int fd,
std::function<void()> callback) {
task_runner_.AddFileDescriptorWatch(fd, std::move(callback));
}
void TestTaskRunner::RemoveFileDescriptorWatch(int fd) {
task_runner_.RemoveFileDescriptorWatch(fd);
}
} // namespace base
} // namespace perfetto
|
//=================================================================================================
/*!
// \file src/mathtest/tdvecdmatmult/VDbLDa.cpp
// \brief Source file for the VDbLDa dense vector/dense matrix multiplication math test
//
// Copyright (C) 2012-2017 Klaus Iglberger - All Rights Reserved
//
// This file is part of the Blaze library. You can redistribute it and/or modify it under
// the terms of the New (Revised) BSD License. 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 names of the Blaze development group 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.
*/
//=================================================================================================
//*************************************************************************************************
// Includes
//*************************************************************************************************
#include <cstdlib>
#include <iostream>
#include <blaze/math/DynamicMatrix.h>
#include <blaze/math/DynamicVector.h>
#include <blaze/math/LowerMatrix.h>
#include <blazetest/mathtest/Creator.h>
#include <blazetest/mathtest/tdvecdmatmult/OperationTest.h>
#include <blazetest/system/MathTest.h>
//=================================================================================================
//
// MAIN FUNCTION
//
//=================================================================================================
//*************************************************************************************************
int main()
{
std::cout << " Running 'VDbLDa'..." << std::endl;
using blazetest::mathtest::TypeA;
using blazetest::mathtest::TypeB;
try
{
// Matrix type definitions
typedef blaze::DynamicVector<TypeB> VDb;
typedef blaze::LowerMatrix< blaze::DynamicMatrix<TypeA> > LDa;
// Creator type definitions
typedef blazetest::Creator<VDb> CVDb;
typedef blazetest::Creator<LDa> CLDa;
// Running tests with small vectors and matrices
for( size_t i=0UL; i<=6UL; ++i ) {
RUN_TDVECDMATMULT_OPERATION_TEST( CVDb( i ), CLDa( i ) );
}
// Running tests with large vectors and matrices
RUN_TDVECDMATMULT_OPERATION_TEST( CVDb( 67UL ), CLDa( 67UL ) );
RUN_TDVECDMATMULT_OPERATION_TEST( CVDb( 127UL ), CLDa( 127UL ) );
RUN_TDVECDMATMULT_OPERATION_TEST( CVDb( 64UL ), CLDa( 64UL ) );
RUN_TDVECDMATMULT_OPERATION_TEST( CVDb( 128UL ), CLDa( 128UL ) );
}
catch( std::exception& ex ) {
std::cerr << "\n\n ERROR DETECTED during dense vector/dense matrix multiplication:\n"
<< ex.what() << "\n";
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
//*************************************************************************************************
|
// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved.
#include "MediaBlueprintFunctionLibrary.h"
#include "MediaCaptureSupport.h"
/* UMediaBlueprintFunctionLibrary interface
*****************************************************************************/
void UMediaBlueprintFunctionLibrary::EnumerateAudioCaptureDevices(TArray<FMediaCaptureDevice>& OutDevices, int32 Filter)
{
const auto FilterEnum = (EMediaAudioCaptureDeviceFilter)Filter;
TArray<FMediaCaptureDeviceInfo> DeviceInfos;
MediaCaptureSupport::EnumerateAudioCaptureDevices(DeviceInfos);
for (const auto& DeviceInfo : DeviceInfos)
{
if (((DeviceInfo.Type == EMediaCaptureDeviceType::Audio) && EnumHasAnyFlags(FilterEnum, EMediaAudioCaptureDeviceFilter::Unknown)) ||
((DeviceInfo.Type == EMediaCaptureDeviceType::AudioCard) && EnumHasAnyFlags(FilterEnum, EMediaAudioCaptureDeviceFilter::Card)) ||
((DeviceInfo.Type == EMediaCaptureDeviceType::AudioSoftware) && EnumHasAnyFlags(FilterEnum, EMediaAudioCaptureDeviceFilter::Software)) ||
((DeviceInfo.Type == EMediaCaptureDeviceType::Microphone) && EnumHasAnyFlags(FilterEnum, EMediaAudioCaptureDeviceFilter::Microphone)))
{
OutDevices.Add(FMediaCaptureDevice(DeviceInfo.DisplayName, DeviceInfo.Url));
}
}
}
void UMediaBlueprintFunctionLibrary::EnumerateVideoCaptureDevices(TArray<FMediaCaptureDevice>& OutDevices, int32 Filter)
{
const auto FilterEnum = (EMediaVideoCaptureDeviceFilter)Filter;
TArray<FMediaCaptureDeviceInfo> DeviceInfos;
MediaCaptureSupport::EnumerateVideoCaptureDevices(DeviceInfos);
for (const auto& DeviceInfo : DeviceInfos)
{
if (((DeviceInfo.Type == EMediaCaptureDeviceType::DepthSensor) && EnumHasAnyFlags(FilterEnum, EMediaVideoCaptureDeviceFilter::Webcam)) ||
((DeviceInfo.Type == EMediaCaptureDeviceType::Video) && EnumHasAnyFlags(FilterEnum, EMediaVideoCaptureDeviceFilter::Unknown)) ||
((DeviceInfo.Type == EMediaCaptureDeviceType::VideoCard) && EnumHasAnyFlags(FilterEnum, EMediaVideoCaptureDeviceFilter::Card)) ||
((DeviceInfo.Type == EMediaCaptureDeviceType::VideoSoftware) && EnumHasAnyFlags(FilterEnum, EMediaVideoCaptureDeviceFilter::Software)) ||
((DeviceInfo.Type == EMediaCaptureDeviceType::Webcam) && EnumHasAnyFlags(FilterEnum, EMediaVideoCaptureDeviceFilter::Webcam)) ||
((DeviceInfo.Type == EMediaCaptureDeviceType::WebcamFront) && EnumHasAnyFlags(FilterEnum, EMediaVideoCaptureDeviceFilter::Webcam)) ||
((DeviceInfo.Type == EMediaCaptureDeviceType::WebcamRear) && EnumHasAnyFlags(FilterEnum, EMediaVideoCaptureDeviceFilter::Webcam)))
{
OutDevices.Add(FMediaCaptureDevice(DeviceInfo.DisplayName, DeviceInfo.Url));
}
}
}
void UMediaBlueprintFunctionLibrary::EnumerateWebcamCaptureDevices(TArray<FMediaCaptureDevice>& OutDevices, int32 Filter)
{
const auto FilterEnum = (EMediaWebcamCaptureDeviceFilter)Filter;
TArray<FMediaCaptureDeviceInfo> DeviceInfos;
MediaCaptureSupport::EnumerateVideoCaptureDevices(DeviceInfos);
for (const auto& DeviceInfo : DeviceInfos)
{
if (((DeviceInfo.Type == EMediaCaptureDeviceType::DepthSensor) && EnumHasAnyFlags(FilterEnum, EMediaWebcamCaptureDeviceFilter::DepthSensor)) ||
((DeviceInfo.Type == EMediaCaptureDeviceType::Webcam) && EnumHasAnyFlags(FilterEnum, EMediaWebcamCaptureDeviceFilter::Unknown)) ||
((DeviceInfo.Type == EMediaCaptureDeviceType::WebcamFront) && EnumHasAnyFlags(FilterEnum, EMediaWebcamCaptureDeviceFilter::Front)) ||
((DeviceInfo.Type == EMediaCaptureDeviceType::WebcamRear) && EnumHasAnyFlags(FilterEnum, EMediaWebcamCaptureDeviceFilter::Rear)))
{
OutDevices.Add(FMediaCaptureDevice(DeviceInfo.DisplayName, DeviceInfo.Url));
}
}
}
|
////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2016 by EMC Corporation, 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.
///
/// Copyright holder is EMC Corporation
///
/// @author Andrey Abramov
/// @author Vasiliy Nabatchikov
////////////////////////////////////////////////////////////////////////////////
#if defined(_MSC_VER)
#pragma warning(disable: 4101)
#pragma warning(disable: 4267)
#endif
#include <cmdline.h>
#if defined(_MSC_VER)
#pragma warning(default: 4267)
#pragma warning(default: 4101)
#endif
#if !defined(_MSC_VER)
#include <dlfcn.h> // for RTLD_NEXT
#endif
#include <signal.h> // for signal(...)/raise(...)
#if defined(_MSC_VER)
#pragma warning(disable: 4229)
#endif
#include <unicode/uclean.h> // for u_cleanup
#if defined(_MSC_VER)
#pragma warning(default: 4229)
#endif
#include "tests_shared.hpp"
#include "tests_config.hpp"
#include <ctime>
#include <formats/formats.hpp>
#include <utils/attributes.hpp>
#include "index/doc_generator.hpp"
#include "utils/file_utils.hpp"
#include "utils/log.hpp"
#include "utils/network_utils.hpp"
#include "utils/bitset.hpp"
#include "utils/runtime_utils.hpp"
#ifdef _MSC_VER
// +1 for \0 at end of string
#define mkdtemp(templ) 0 == _mkdir(0 == _mktemp_s(templ, strlen(templ) + 1) ? templ : nullptr) ? templ : nullptr
#endif
/* -------------------------------------------------------------------
* iteration_tracker
* ------------------------------------------------------------------*/
struct iteration_tracker : ::testing::Environment {
virtual void SetUp() {
++iteration;
}
static uint32_t iteration;
};
uint32_t iteration_tracker::iteration = (std::numeric_limits<uint32_t>::max)();
/* -------------------------------------------------------------------
* test_base
* ------------------------------------------------------------------*/
const std::string IRES_HELP("help");
const std::string IRES_LOG_LEVEL("ires_log_level");
const std::string IRES_LOG_STACK("ires_log_stack");
const std::string IRES_OUTPUT("ires_output");
const std::string IRES_OUTPUT_PATH("ires_output_path");
const std::string IRES_RESOURCE_DIR("ires_resource_dir");
const std::string test_base::test_results("test_detail.xml");
irs::utf8_path test_base::exec_path_;
irs::utf8_path test_base::exec_dir_;
irs::utf8_path test_base::exec_file_;
irs::utf8_path test_base::out_dir_;
irs::utf8_path test_base::resource_dir_;
irs::utf8_path test_base::res_dir_;
irs::utf8_path test_base::res_path_;
std::string test_base::test_name_;
int test_base::argc_;
char** test_base::argv_;
decltype(test_base::argv_ires_output_) test_base::argv_ires_output_;
uint32_t test_base::iteration() {
return iteration_tracker::iteration;
}
std::string test_base::resource( const std::string& name ) {
auto path = resource_dir_;
path /= name;
return path.utf8();
}
void test_base::SetUp() {
namespace tst = ::testing;
const tst::TestInfo* ti = tst::UnitTest::GetInstance()->current_test_info();
test_case_dir_ = res_dir_;
if (::testing::FLAGS_gtest_repeat > 1 || ::testing::FLAGS_gtest_repeat < 0) {
test_case_dir_ /=
std::string("iteration ").append(std::to_string(iteration()));
}
test_case_dir_ /= ti->test_case_name();
(test_dir_ = test_case_dir_) /= ti->name();
test_dir_.mkdir();
}
void test_base::prepare(const cmdline::parser& parser) {
if (parser.exist(IRES_HELP)) {
return;
}
make_directories();
{
auto log_level = parser.get<irs::logger::level_t>(IRES_LOG_LEVEL);
irs::logger::output_le(log_level, stderr); // set desired log level
if (parser.get<bool>(IRES_LOG_STACK)) {
irs::logger::stack_trace_level(log_level); // force enable stack trace
}
}
if (parser.exist(IRES_OUTPUT)) {
std::unique_ptr<char*[]> argv(new char*[2 + argc_]);
std::memcpy(argv.get(), argv_, sizeof(char*)*(argc_));
argv_ires_output_.append("--gtest_output=xml:").append(res_path_.utf8());
argv[argc_++] = &argv_ires_output_[0];
/* let last argv equals to nullptr */
argv[argc_] = nullptr;
argv_ = argv.release();
}
}
void test_base::make_directories() {
irs::utf8_path exec_path(argv_[0]);
auto exec_native = exec_path.native();
auto path_parts = irs::file_utils::path_parts(&exec_native[0]);
exec_path_ = exec_path;
exec_file_ = path_parts.basename;
exec_dir_ = path_parts.dirname;
test_name_ = irs::utf8_path(path_parts.stem).utf8();
if (out_dir_.native().empty()) {
out_dir_ = exec_dir_;
}
std::cout << "launching: " << exec_path_.utf8() << std::endl;
std::cout << "options:" << std::endl;
std::cout << "\t" << IRES_OUTPUT_PATH << ": " << out_dir_.utf8() << std::endl;
std::cout << "\t" << IRES_RESOURCE_DIR << ": " << resource_dir_.utf8() << std::endl;
out_dir_ = out_dir_.utf8_absolute();
(res_dir_ = out_dir_) /= test_name_;
// add timestamp to res_dir_
{
std::tm tinfo;
if (iresearch::localtime(tinfo, std::time(nullptr))) {
char buf[21]{};
strftime(buf, sizeof buf, "_%Y_%m_%d_%H_%M_%S", &tinfo);
res_dir_ += irs::string_ref(buf, sizeof buf - 1);
} else {
res_dir_ += "_unknown";
}
}
// add temporary string to res_dir_
{
char templ[] = "_XXXXXX";
res_dir_ += irs::string_ref(templ, sizeof templ - 1);
}
auto res_dir_templ = res_dir_.utf8();
res_dir_ = mkdtemp(&(res_dir_templ[0]));
(res_path_ = res_dir_) /= test_results;
}
void test_base::parse_command_line(cmdline::parser& cmd) {
static const auto log_level_reader = [](const std::string &s)->irs::logger::level_t {
static const std::map<std::string, irs::logger::level_t> log_levels = {
{ "FATAL", irs::logger::level_t::IRL_FATAL },
{ "ERROR", irs::logger::level_t::IRL_ERROR },
{ "WARN", irs::logger::level_t::IRL_WARN },
{ "INFO", irs::logger::level_t::IRL_INFO },
{ "DEBUG", irs::logger::level_t::IRL_DEBUG },
{ "TRACE", irs::logger::level_t::IRL_TRACE },
};
auto itr = log_levels.find(s);
if (itr == log_levels.end()) {
throw std::invalid_argument(s);
}
return itr->second;
};
cmd.add(IRES_HELP, '?', "print this message");
cmd.add(IRES_LOG_LEVEL, 0, "threshold log level <FATAL|ERROR|WARN|INFO|DEBUG|TRACE>", false, irs::logger::level_t::IRL_FATAL, log_level_reader);
cmd.add(IRES_LOG_STACK, 0, "always log stack trace", false, false);
cmd.add(IRES_OUTPUT, 0, "generate an XML report");
cmd.add(IRES_OUTPUT_PATH, 0, "output directory", false, out_dir_.utf8());
cmd.add(IRES_RESOURCE_DIR, 0, "resource directory", false, irs::utf8_path(IResearch_test_resource_dir).utf8());
if (!cmd.parse(argc_, argv_)) {
std::cout << cmd.error_full() << std::endl;
std::cout << cmd.usage() << std::endl;
exit(1);
}
if (cmd.exist(IRES_HELP)) {
std::cout << cmd.usage() << std::endl;
return;
}
resource_dir_ = cmd.get<std::string>(IRES_RESOURCE_DIR);
out_dir_ = cmd.get<std::string>(IRES_OUTPUT_PATH);
}
int test_base::initialize(int argc, char* argv[]) {
argc_ = argc;
argv_ = argv;
::testing::AddGlobalTestEnvironment(new iteration_tracker());
::testing::InitGoogleTest(&argc_, argv_);
cmdline::parser cmd;
parse_command_line(cmd);
prepare(cmd);
return RUN_ALL_TESTS();
}
void flush_timers(std::ostream &out) {
std::map<std::string, std::pair<size_t, size_t>> ordered_stats;
iresearch::timer_utils::visit([&ordered_stats](const std::string& key, size_t count, size_t time)->bool {
std::string key_str = key;
#if defined(__GNUC__)
if (key_str.compare(0, strlen("virtual "), "virtual ") == 0) {
key_str = key_str.substr(strlen("virtual "));
}
size_t i;
if (std::string::npos != (i = key_str.find(' ')) && key_str.find('(') > i) {
key_str = key_str.substr(i + 1);
}
#elif defined(_MSC_VER)
size_t i;
if (std::string::npos != (i = key_str.find("__cdecl "))) {
key_str = key_str.substr(i + strlen("__cdecl "));
}
#endif
ordered_stats.emplace(key_str, std::make_pair(count, time));
return true;
});
for (auto& entry: ordered_stats) {
auto& key = entry.first;
auto& count = entry.second.first;
auto& time = entry.second.second;
out << key << "\tcalls:" << count << ",\ttime: " << time/1000 << " us,\tavg call: " << time/1000/(double)count << " us"<< std::endl;
}
}
void stack_trace_handler(int sig) {
// reset to default handler
signal(sig, SIG_DFL);
// print stack trace
iresearch::logger::stack_trace(iresearch::logger::IRL_FATAL); // IRL_FATAL is logged to stderr above
// re-signal to default handler (so we still get core dump if needed...)
raise(sig);
}
void install_stack_trace_handler() {
signal(SIGILL, stack_trace_handler);
signal(SIGSEGV, stack_trace_handler);
signal(SIGABRT, stack_trace_handler);
#ifndef _MSC_VER
signal(SIGBUS, stack_trace_handler);
#endif
}
#ifndef _MSC_VER
// override GCC 'throw' handler to print stack trace before throw
extern "C" {
#if defined(__APPLE__)
void __cxa_throw(void* ex, struct std::type_info* info, void(*dest)(void *)) {
static void(*rethrow)(void*,struct std::type_info*,void(*)(void*)) =
(void(*)(void*,struct std::type_info*,void(*)(void*)))dlsym(RTLD_NEXT, "__cxa_throw");
IR_FRMT_DEBUG("exception type: %s", reinterpret_cast<const std::type_info*>(info)->name());
IR_LOG_STACK_TRACE();
rethrow(ex, info, dest);
abort(); // otherwise MacOS reports "function declared 'noreturn' should not return"
}
#else
void __cxa_throw(void* ex, void* info, void(*dest)(void*)) {
static void(*rethrow)(void*,void*,void(*)(void*)) __attribute__ ((noreturn)) =
(void(*)(void*,void*,void(*)(void*)))dlsym(RTLD_NEXT, "__cxa_throw");
IR_FRMT_DEBUG("exception type: %s", reinterpret_cast<const std::type_info*>(info)->name());
IR_LOG_STACK_TRACE();
rethrow(ex, info, dest);
}
#endif
}
#endif
// -----------------------------------------------------------------------------
// --SECTION-- main
// -----------------------------------------------------------------------------
int main( int argc, char* argv[] ) {
install_stack_trace_handler();
const int code = test_base::initialize( argc, argv );
std::cout << "Path to test result directory: "
<< test_base::test_results_dir().utf8()
<< std::endl;
u_cleanup(); // cleanup ICU resources
return code;
}
// -----------------------------------------------------------------------------
// --SECTION-- END-OF-FILE
// -----------------------------------------------------------------------------
|
#include <string>
#include <vector>
#include "common/buffer/buffer_impl.h"
#include "common/network/filter_manager_impl.h"
#include "common/tcp_proxy/tcp_proxy.h"
#include "common/upstream/upstream_impl.h"
#include "extensions/filters/network/ratelimit/ratelimit.h"
#include "test/common/upstream/utility.h"
#include "test/extensions/filters/common/ratelimit/mocks.h"
#include "test/mocks/buffer/mocks.h"
#include "test/mocks/network/mocks.h"
#include "test/mocks/ratelimit/mocks.h"
#include "test/mocks/runtime/mocks.h"
#include "test/mocks/server/mocks.h"
#include "test/mocks/tracing/mocks.h"
#include "test/mocks/upstream/host.h"
#include "test/mocks/upstream/mocks.h"
#include "test/test_common/printers.h"
#include "test/test_common/utility.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
using testing::_;
using testing::InSequence;
using testing::Invoke;
using testing::NiceMock;
using testing::Return;
using testing::WithArgs;
namespace Envoy {
namespace Network {
namespace {
class NetworkFilterManagerTest : public testing::Test {
public:
void SetUp() override {
EXPECT_CALL(connection_, getReadBuffer).WillRepeatedly(Invoke([this]() {
return StreamBuffer{read_buffer_, read_end_stream_};
}));
EXPECT_CALL(connection_, getWriteBuffer).WillRepeatedly(Invoke([this]() {
return StreamBuffer{write_buffer_, write_end_stream_};
}));
}
NiceMock<MockFilterManagerConnection> connection_;
Buffer::OwnedImpl read_buffer_;
Buffer::OwnedImpl write_buffer_;
bool read_end_stream_{};
bool write_end_stream_{};
};
class LocalMockFilter : public MockFilter {
public:
~LocalMockFilter() override {
// Make sure the upstream host is still valid in the filter destructor.
callbacks_->upstreamHost()->address();
}
};
TEST_F(NetworkFilterManagerTest, All) {
InSequence s;
Upstream::HostDescription* host_description(new NiceMock<Upstream::MockHostDescription>());
MockReadFilter* read_filter(new MockReadFilter());
MockWriteFilter* write_filter(new MockWriteFilter());
MockFilter* filter(new LocalMockFilter());
FilterManagerImpl manager(connection_);
manager.addReadFilter(ReadFilterSharedPtr{read_filter});
manager.addWriteFilter(WriteFilterSharedPtr{write_filter});
manager.addFilter(FilterSharedPtr{filter});
read_filter->callbacks_->upstreamHost(Upstream::HostDescriptionConstSharedPtr{host_description});
EXPECT_EQ(read_filter->callbacks_->upstreamHost(), filter->callbacks_->upstreamHost());
EXPECT_CALL(*read_filter, onNewConnection()).WillOnce(Return(FilterStatus::StopIteration));
EXPECT_EQ(manager.initializeReadFilters(), true);
EXPECT_CALL(*filter, onNewConnection()).WillOnce(Return(FilterStatus::Continue));
read_filter->callbacks_->continueReading();
read_buffer_.add("hello");
read_end_stream_ = false;
EXPECT_CALL(*read_filter, onData(BufferStringEqual("hello"), false))
.WillOnce(Return(FilterStatus::StopIteration));
manager.onRead();
read_buffer_.add("world");
EXPECT_CALL(*filter, onData(BufferStringEqual("helloworld"), false))
.WillOnce(Return(FilterStatus::Continue));
read_filter->callbacks_->continueReading();
write_buffer_.add("foo");
write_end_stream_ = false;
EXPECT_CALL(*filter, onWrite(BufferStringEqual("foo"), false))
.WillOnce(Return(FilterStatus::StopIteration));
manager.onWrite();
write_buffer_.add("bar");
EXPECT_CALL(*filter, onWrite(BufferStringEqual("foobar"), false))
.WillOnce(Return(FilterStatus::Continue));
EXPECT_CALL(*write_filter, onWrite(BufferStringEqual("foobar"), false))
.WillOnce(Return(FilterStatus::Continue));
manager.onWrite();
}
TEST_F(NetworkFilterManagerTest, ConnectionClosedBeforeRunningFilter) {
InSequence s;
Upstream::HostDescription* host_description(new NiceMock<Upstream::MockHostDescription>());
MockReadFilter* read_filter(new MockReadFilter());
MockFilter* filter(new LocalMockFilter());
FilterManagerImpl manager(connection_);
manager.addReadFilter(ReadFilterSharedPtr{read_filter});
manager.addFilter(FilterSharedPtr{filter});
read_filter->callbacks_->upstreamHost(Upstream::HostDescriptionConstSharedPtr{host_description});
EXPECT_EQ(read_filter->callbacks_->upstreamHost(), filter->callbacks_->upstreamHost());
EXPECT_CALL(connection_, state()).WillOnce(Return(Connection::State::Closing));
EXPECT_CALL(*read_filter, onNewConnection()).Times(0);
EXPECT_CALL(*read_filter, onData(_, _)).Times(0);
EXPECT_CALL(*filter, onNewConnection()).Times(0);
EXPECT_CALL(*filter, onData(_, _)).Times(0);
manager.onRead();
EXPECT_CALL(connection_, state()).WillOnce(Return(Connection::State::Closed));
EXPECT_CALL(*filter, onWrite(_, _)).Times(0);
manager.onWrite();
}
TEST_F(NetworkFilterManagerTest, FilterReturnStopAndNoCallback) {
InSequence s;
Upstream::HostDescription* host_description(new NiceMock<Upstream::MockHostDescription>());
MockReadFilter* read_filter(new MockReadFilter());
MockWriteFilter* write_filter(new MockWriteFilter());
MockFilter* filter(new LocalMockFilter());
FilterManagerImpl manager(connection_);
manager.addReadFilter(ReadFilterSharedPtr{read_filter});
manager.addWriteFilter(WriteFilterSharedPtr{write_filter});
manager.addFilter(FilterSharedPtr{filter});
read_filter->callbacks_->upstreamHost(Upstream::HostDescriptionConstSharedPtr{host_description});
EXPECT_EQ(read_filter->callbacks_->upstreamHost(), filter->callbacks_->upstreamHost());
read_buffer_.add("hello");
EXPECT_CALL(*read_filter, onNewConnection()).WillOnce(Return(FilterStatus::Continue));
EXPECT_CALL(*read_filter, onData(BufferStringEqual("hello"), _))
.WillOnce(Return(FilterStatus::StopIteration));
EXPECT_CALL(*filter, onNewConnection()).Times(0);
EXPECT_CALL(*filter, onData(_, _)).Times(0);
manager.onRead();
EXPECT_CALL(*filter, onWrite(_, _)).WillOnce(Return(FilterStatus::StopIteration));
EXPECT_CALL(*write_filter, onWrite(_, _)).Times(0);
manager.onWrite();
}
TEST_F(NetworkFilterManagerTest, ReadFilterCloseConnectionAndReturnContinue) {
InSequence s;
Upstream::HostDescription* host_description(new NiceMock<Upstream::MockHostDescription>());
MockReadFilter* read_filter(new MockReadFilter());
MockFilter* filter(new LocalMockFilter());
FilterManagerImpl manager(connection_);
manager.addReadFilter(ReadFilterSharedPtr{read_filter});
manager.addFilter(FilterSharedPtr{filter});
read_filter->callbacks_->upstreamHost(Upstream::HostDescriptionConstSharedPtr{host_description});
EXPECT_EQ(read_filter->callbacks_->upstreamHost(), filter->callbacks_->upstreamHost());
EXPECT_CALL(*read_filter, onNewConnection()).WillOnce(Return(FilterStatus::Continue));
EXPECT_CALL(*filter, onNewConnection()).WillOnce(Return(FilterStatus::Continue));
EXPECT_EQ(manager.initializeReadFilters(), true);
read_buffer_.add("hello");
EXPECT_CALL(connection_, state()).WillOnce(Return(Connection::State::Open));
EXPECT_CALL(*read_filter, onData(BufferStringEqual("hello"), _))
.WillOnce(Return(FilterStatus::Continue));
EXPECT_CALL(connection_, state()).WillOnce(Return(Connection::State::Closing));
EXPECT_CALL(*filter, onData(_, _)).Times(0);
manager.onRead();
EXPECT_CALL(connection_, state()).WillOnce(Return(Connection::State::Closed));
EXPECT_CALL(*filter, onWrite(_, _)).Times(0);
manager.onWrite();
}
TEST_F(NetworkFilterManagerTest, WriteFilterCloseConnectionAndReturnContinue) {
InSequence s;
Upstream::HostDescription* host_description(new NiceMock<Upstream::MockHostDescription>());
MockReadFilter* read_filter(new MockReadFilter());
MockWriteFilter* write_filter(new MockWriteFilter());
MockFilter* filter(new LocalMockFilter());
FilterManagerImpl manager(connection_);
manager.addReadFilter(ReadFilterSharedPtr{read_filter});
manager.addWriteFilter(WriteFilterSharedPtr{write_filter});
manager.addFilter(FilterSharedPtr{filter});
read_filter->callbacks_->upstreamHost(Upstream::HostDescriptionConstSharedPtr{host_description});
EXPECT_EQ(read_filter->callbacks_->upstreamHost(), filter->callbacks_->upstreamHost());
EXPECT_CALL(*read_filter, onNewConnection()).WillOnce(Return(FilterStatus::Continue));
EXPECT_CALL(*filter, onNewConnection()).WillOnce(Return(FilterStatus::Continue));
EXPECT_EQ(manager.initializeReadFilters(), true);
read_buffer_.add("hello");
EXPECT_CALL(*read_filter, onData(BufferStringEqual("hello"), _))
.WillOnce(Return(FilterStatus::StopIteration));
manager.onRead();
read_buffer_.add("world");
EXPECT_CALL(*filter, onData(BufferStringEqual("helloworld"), _))
.WillOnce(Return(FilterStatus::Continue));
read_filter->callbacks_->continueReading();
write_buffer_.add("foo");
EXPECT_CALL(connection_, state()).WillOnce(Return(Connection::State::Open));
EXPECT_CALL(*filter, onWrite(BufferStringEqual("foo"), _))
.WillOnce(Return(FilterStatus::Continue));
EXPECT_CALL(connection_, state()).WillOnce(Return(Connection::State::Closing));
EXPECT_CALL(*write_filter, onWrite(_, _)).Times(0);
manager.onWrite();
}
TEST_F(NetworkFilterManagerTest, ReadCloseConnectionReturnStopAndCallback) {
InSequence s;
Upstream::HostDescription* host_description(new NiceMock<Upstream::MockHostDescription>());
MockReadFilter* read_filter(new MockReadFilter());
MockWriteFilter* write_filter(new MockWriteFilter());
MockFilter* filter(new LocalMockFilter());
FilterManagerImpl manager(connection_);
manager.addReadFilter(ReadFilterSharedPtr{read_filter});
manager.addWriteFilter(WriteFilterSharedPtr{write_filter});
manager.addFilter(FilterSharedPtr{filter});
read_filter->callbacks_->upstreamHost(Upstream::HostDescriptionConstSharedPtr{host_description});
EXPECT_EQ(read_filter->callbacks_->upstreamHost(), filter->callbacks_->upstreamHost());
EXPECT_CALL(*read_filter, onNewConnection()).WillOnce(Return(FilterStatus::Continue));
EXPECT_CALL(*filter, onNewConnection()).WillOnce(Return(FilterStatus::Continue));
EXPECT_EQ(manager.initializeReadFilters(), true);
read_buffer_.add("hello");
EXPECT_CALL(*read_filter, onData(BufferStringEqual("hello"), _))
.WillOnce(Return(FilterStatus::StopIteration));
manager.onRead();
EXPECT_CALL(connection_, state()).WillOnce(Return(Connection::State::Closing));
EXPECT_CALL(*filter, onData(_, _)).Times(0);
read_filter->callbacks_->continueReading();
EXPECT_CALL(connection_, state()).WillOnce(Return(Connection::State::Closed));
EXPECT_CALL(*filter, onWrite(_, _)).Times(0);
manager.onWrite();
}
TEST_F(NetworkFilterManagerTest, WriteCloseConnectionReturnStopAndCallback) {
InSequence s;
Upstream::HostDescription* host_description(new NiceMock<Upstream::MockHostDescription>());
MockReadFilter* read_filter(new MockReadFilter());
MockWriteFilter* write_filter(new MockWriteFilter());
MockFilter* filter(new LocalMockFilter());
FilterManagerImpl manager(connection_);
manager.addReadFilter(ReadFilterSharedPtr{read_filter});
manager.addWriteFilter(WriteFilterSharedPtr{write_filter});
manager.addFilter(FilterSharedPtr{filter});
read_filter->callbacks_->upstreamHost(Upstream::HostDescriptionConstSharedPtr{host_description});
EXPECT_EQ(read_filter->callbacks_->upstreamHost(), filter->callbacks_->upstreamHost());
EXPECT_CALL(*read_filter, onNewConnection()).WillOnce(Return(FilterStatus::Continue));
EXPECT_CALL(*filter, onNewConnection()).WillOnce(Return(FilterStatus::Continue));
EXPECT_EQ(manager.initializeReadFilters(), true);
read_buffer_.add("hello");
EXPECT_CALL(*read_filter, onData(BufferStringEqual("hello"), _))
.WillOnce(Return(FilterStatus::Continue));
EXPECT_CALL(*filter, onData(BufferStringEqual("hello"), _))
.WillOnce(Return(FilterStatus::Continue));
manager.onRead();
write_buffer_.add("foo");
EXPECT_CALL(connection_, state()).WillOnce(Return(Connection::State::Open));
EXPECT_CALL(*filter, onWrite(BufferStringEqual("foo"), _))
.WillOnce(Return(FilterStatus::StopIteration));
manager.onWrite();
EXPECT_CALL(connection_, state()).WillOnce(Return(Connection::State::Closed));
EXPECT_CALL(*filter, onWrite(_, _)).Times(0);
EXPECT_CALL(*write_filter, onWrite(_, _)).Times(0);
manager.onWrite();
}
// Test that end_stream is delivered in the correct order with the data, even
// if FilterStatus::StopIteration occurs.
TEST_F(NetworkFilterManagerTest, EndStream) {
InSequence s;
Upstream::HostDescription* host_description(new NiceMock<Upstream::MockHostDescription>());
MockReadFilter* read_filter(new MockReadFilter());
MockWriteFilter* write_filter(new MockWriteFilter());
MockFilter* filter(new LocalMockFilter());
FilterManagerImpl manager(connection_);
manager.addReadFilter(ReadFilterSharedPtr{read_filter});
manager.addWriteFilter(WriteFilterSharedPtr{write_filter});
manager.addFilter(FilterSharedPtr{filter});
read_filter->callbacks_->upstreamHost(Upstream::HostDescriptionConstSharedPtr{host_description});
EXPECT_EQ(read_filter->callbacks_->upstreamHost(), filter->callbacks_->upstreamHost());
EXPECT_CALL(*read_filter, onNewConnection()).WillOnce(Return(FilterStatus::Continue));
EXPECT_CALL(*filter, onNewConnection()).WillOnce(Return(FilterStatus::Continue));
EXPECT_EQ(manager.initializeReadFilters(), true);
read_buffer_.add("hello");
read_end_stream_ = true;
EXPECT_CALL(*read_filter, onData(BufferStringEqual("hello"), true))
.WillOnce(Return(FilterStatus::StopIteration));
manager.onRead();
read_buffer_.add("world");
EXPECT_CALL(*filter, onData(BufferStringEqual("helloworld"), true))
.WillOnce(Return(FilterStatus::Continue));
read_filter->callbacks_->continueReading();
write_buffer_.add("foo");
write_end_stream_ = true;
EXPECT_CALL(*filter, onWrite(BufferStringEqual("foo"), true))
.WillOnce(Return(FilterStatus::StopIteration));
manager.onWrite();
write_buffer_.add("bar");
EXPECT_CALL(*filter, onWrite(BufferStringEqual("foobar"), true))
.WillOnce(Return(FilterStatus::Continue));
EXPECT_CALL(*write_filter, onWrite(BufferStringEqual("foobar"), true))
.WillOnce(Return(FilterStatus::Continue));
manager.onWrite();
}
// This is a very important flow so make sure it works correctly in aggregate.
TEST_F(NetworkFilterManagerTest, RateLimitAndTcpProxy) {
InSequence s;
NiceMock<Server::Configuration::MockFactoryContext> factory_context;
NiceMock<MockClientConnection> upstream_connection;
NiceMock<Tcp::ConnectionPool::MockInstance> conn_pool;
FilterManagerImpl manager(connection_);
std::string rl_yaml = R"EOF(
domain: foo
descriptors:
- entries:
- key: hello
value: world
stat_prefix: name
)EOF";
ON_CALL(factory_context.runtime_loader_.snapshot_,
featureEnabled("ratelimit.tcp_filter_enabled", 100))
.WillByDefault(Return(true));
ON_CALL(factory_context.runtime_loader_.snapshot_,
featureEnabled("ratelimit.tcp_filter_enforcing", 100))
.WillByDefault(Return(true));
envoy::config::filter::network::rate_limit::v2::RateLimit proto_config{};
TestUtility::loadFromYaml(rl_yaml, proto_config);
Extensions::NetworkFilters::RateLimitFilter::ConfigSharedPtr rl_config(
new Extensions::NetworkFilters::RateLimitFilter::Config(proto_config, factory_context.scope_,
factory_context.runtime_loader_));
Extensions::Filters::Common::RateLimit::MockClient* rl_client =
new Extensions::Filters::Common::RateLimit::MockClient();
manager.addReadFilter(std::make_shared<Extensions::NetworkFilters::RateLimitFilter::Filter>(
rl_config, Extensions::Filters::Common::RateLimit::ClientPtr{rl_client}));
envoy::config::filter::network::tcp_proxy::v2::TcpProxy tcp_proxy;
tcp_proxy.set_stat_prefix("name");
tcp_proxy.set_cluster("fake_cluster");
TcpProxy::ConfigSharedPtr tcp_proxy_config(new TcpProxy::Config(tcp_proxy, factory_context));
manager.addReadFilter(
std::make_shared<TcpProxy::Filter>(tcp_proxy_config, factory_context.cluster_manager_,
factory_context.dispatcher().timeSource()));
Extensions::Filters::Common::RateLimit::RequestCallbacks* request_callbacks{};
EXPECT_CALL(*rl_client, limit(_, "foo",
testing::ContainerEq(
std::vector<RateLimit::Descriptor>{{{{"hello", "world"}}}}),
testing::A<Tracing::Span&>()))
.WillOnce(WithArgs<0>(
Invoke([&](Extensions::Filters::Common::RateLimit::RequestCallbacks& callbacks) -> void {
request_callbacks = &callbacks;
})));
EXPECT_EQ(manager.initializeReadFilters(), true);
EXPECT_CALL(factory_context.cluster_manager_, tcpConnPoolForCluster("fake_cluster", _, _, _))
.WillOnce(Return(&conn_pool));
request_callbacks->complete(Extensions::Filters::Common::RateLimit::LimitStatus::OK, nullptr);
conn_pool.poolReady(upstream_connection);
Buffer::OwnedImpl buffer("hello");
EXPECT_CALL(upstream_connection, write(BufferEqual(&buffer), _));
read_buffer_.add("hello");
manager.onRead();
connection_.raiseEvent(ConnectionEvent::RemoteClose);
}
TEST_F(NetworkFilterManagerTest, InjectReadDataToFilterChain) {
InSequence s;
MockReadFilter* read_filter(new MockReadFilter());
MockWriteFilter* write_filter(new MockWriteFilter());
MockFilter* filter(new MockFilter());
FilterManagerImpl manager(connection_);
manager.addReadFilter(ReadFilterSharedPtr{read_filter});
manager.addWriteFilter(WriteFilterSharedPtr{write_filter});
manager.addFilter(FilterSharedPtr{filter});
EXPECT_CALL(*read_filter, onNewConnection()).WillOnce(Return(FilterStatus::StopIteration));
EXPECT_EQ(manager.initializeReadFilters(), true);
EXPECT_CALL(*filter, onNewConnection()).WillOnce(Return(FilterStatus::Continue));
read_filter->callbacks_->continueReading();
read_buffer_.add("hello");
read_end_stream_ = true;
Buffer::OwnedImpl injected_buffer("greetings");
EXPECT_CALL(*filter, onData(BufferStringEqual("greetings"), false))
.WillOnce(Return(FilterStatus::Continue));
read_filter->callbacks_->injectReadDataToFilterChain(injected_buffer, false);
injected_buffer.add(" everyone");
EXPECT_CALL(*filter, onData(BufferStringEqual("greetings everyone"), true))
.WillOnce(Return(FilterStatus::Continue));
read_filter->callbacks_->injectReadDataToFilterChain(injected_buffer, true);
}
TEST_F(NetworkFilterManagerTest, InjectWriteDataToFilterChain) {
InSequence s;
MockReadFilter* read_filter(new MockReadFilter());
MockWriteFilter* write_filter(new MockWriteFilter());
MockFilter* filter(new MockFilter());
FilterManagerImpl manager(connection_);
manager.addReadFilter(ReadFilterSharedPtr{read_filter});
manager.addWriteFilter(WriteFilterSharedPtr{write_filter});
manager.addFilter(FilterSharedPtr{filter});
Buffer::OwnedImpl injected_buffer("greetings");
EXPECT_CALL(*write_filter, onWrite(BufferStringEqual("greetings"), false))
.WillOnce(Return(FilterStatus::Continue));
EXPECT_CALL(connection_, rawWrite(BufferStringEqual("greetings"), false));
filter->write_callbacks_->injectWriteDataToFilterChain(injected_buffer, false);
injected_buffer.add(" everyone!");
EXPECT_CALL(*write_filter, onWrite(BufferStringEqual(" everyone!"), true))
.WillOnce(Return(FilterStatus::Continue));
EXPECT_CALL(connection_, rawWrite(BufferStringEqual(" everyone!"), true));
filter->write_callbacks_->injectWriteDataToFilterChain(injected_buffer, true);
}
} // namespace
} // namespace Network
} // namespace Envoy
|
#include <stdio.h>
#include <emscripten.h>
int n = 0;
double rate = 0;
double last = -1;
void main_loop(void) {
emscripten_sleep(0);
n++;
double now = emscripten_get_now();
if (last > 0) {
double curr = now - last;
rate = (rate*(n-1)+curr)/n;
if (n > 15) {
emscripten_cancel_main_loop();
int result = rate > 600;
printf("Final rate: %.2f, success: %d\n", rate, result);
REPORT_RESULT();
return;
}
}
last = emscripten_get_now();
printf("Main loop rate: %.2f (over %d)\n", rate, n);
}
int main(void) {
emscripten_set_main_loop(main_loop, 1, 1);
}
|
/// \file
/// Getopt paramters for principal_chiral_nspt.cpp - Option parser
#include "principal_chiral_nspt_params.h"
#include <iomanip>
#include <iostream>
#ifdef _OPENMP
int n_threads = 0;
bool user_def = 0;
#endif
int seq_init = 1;
int quiet = 1;
int no_meas = 0;
int twisted = 0;
int integrator = 1;
int debug = 0;
int seed_only = 0;
int use_seed_state = 0;
std::size_t measurements = 100;
std::size_t swps = 5000;
std::size_t thermal = 200000;
std::size_t Lt = 10;
std::size_t Ls = 10;
std::size_t constr_int = 0;
double beta0 = 0.0;
double eps_t = 0.1;
double eps_constr = 1.e-10;
std::string outfile = "";
std::string file_identifier = "";
std::string seed_file = "";
std::string intnames[] = { "Euler", "RK" };
///! Struct to define long options for getopt
static struct option long_options[] = {
{ "no-seq-init", no_argument, &seq_init, 0 },
{ "verbose", no_argument, &quiet, 0 },
{ "twisted", no_argument, &twisted, 1 },
{ "configs-only", no_argument, &no_meas, 1 },
{ "seed-only", no_argument, &seed_only, 1 },
{ "use-seed-state", no_argument, &use_seed_state, 1 },
{ "debug", no_argument, &debug, 1 },
{ "eps-t", required_argument, NULL, 'e' },
{ "measurements", required_argument, NULL, 'm' },
{ "sweeps", required_argument, NULL, 's' },
{ "seed", required_argument, NULL, 'F' },
{ "thermalisation", required_argument, NULL, 't' },
{ "outfile", required_argument, NULL, 'f' },
{ "lt", required_argument, NULL, 'T' },
{ "ls", required_argument, NULL, 'S' },
{ "num-threads", required_argument, NULL, 'n' },
{ "integrator", required_argument, NULL, 'i' },
{ "constr-int", required_argument, NULL, 'c' },
{ "eps-constr", required_argument, NULL, 'p' },
{ "file-identifier", required_argument, NULL, 'x' },
{ 0, 0, 0, 0 }
};
static char short_option_list[] = "e:m:s:t:f:S:T:n:i:c:p:x:F:vw";
int parse_command_line_options(int argc, char **argv)
{
int c, option_index;
while (1) {
c = getopt_long(argc, argv, short_option_list, long_options, &option_index);
if (c == -1)
break;
switch (c) {
case 0:
break;
#ifdef _OPENMP
case 'n':
n_threads = static_cast<int>(std::stoi(optarg));
if (n_threads >= 0) {
user_def = true;
}
else {
n_threads *= -1;
}
break;
#endif
case 'e':
eps_t = static_cast<double>(std::stod(optarg));
break;
case 'p':
eps_constr = static_cast<double>(std::stod(optarg));
break;
case 'm':
measurements = static_cast<std::size_t>(std::stoi(optarg));
break;
case 't':
thermal = static_cast<std::size_t>(std::stoi(optarg));
break;
case 's':
swps = static_cast<std::size_t>(std::stoi(optarg));
break;
case 'c':
constr_int = static_cast<std::size_t>(std::stoi(optarg));
break;
case 'T':
Lt = static_cast<std::size_t>(std::stoi(optarg));
break;
case 'S':
Ls = static_cast<std::size_t>(std::stoi(optarg));
break;
case 'f':
outfile = static_cast<std::string>(optarg);
break;
case 'F':
seed_file = static_cast<std::string>(optarg);
break;
case 'i':
integrator = static_cast<int>(std::stoi(optarg));
break;
case 'v':
quiet = 0;
break;
case 'w':
twisted = 1;
break;
case 'x':
file_identifier = static_cast<std::string>(optarg);
break;
default:
break;
}
}
return 0;
}
void print_params()
{
const int f1_width = 28;
std::cout << "\tSimulation Parameters: " << std::endl;
std::cout << "\t-------------------------------------------------------------"
"---------"
<< std::endl;
std::cout << std::left;
std::cout << std::setw(f1_width)
<< "\tVerbose ouput:" << (quiet != 1 ? "ON" : "OFF") << std::endl;
std::cout << std::setw(f1_width)
<< "\tSeq. Init: " << (seq_init == 1 ? "ON" : "OFF") << std::endl;
std::cout << std::setw(f1_width) << "\tIntegrator: " << intnames[integrator]
<< std::endl;
std::cout << std::setw(f1_width)
<< "\tTwisted BC: " << (twisted == 0 ? "OFF" : "TEMPORAL DIR")
<< std::endl;
std::cout << std::setw(f1_width)
<< "\tConfigs only:" << (no_meas != 1 ? "NO" : "YES") << std::endl;
std::cout << std::setw(f1_width) << "\tThermalisation Sweeps: " << thermal
<< std::endl;
std::cout << std::setw(f1_width) << "\tSweeps: " << swps << std::endl;
std::cout << std::setw(f1_width)
<< "\tConstraint enforcing int.: " << constr_int << std::endl;
std::cout << std::setw(f1_width)
<< (no_meas != 1 ? "\tMeasurements: " : "\tConfigurations: ")
<< measurements << std::endl;
std::cout << std::setw(f1_width)
<< "\tConstraint precision goal: " << eps_constr << std::endl;
std::cout << std::setw(f1_width) << "\tStochastic time step: " << eps_t
<< std::endl;
if (not outfile.empty()) {
std::cout << std::setw(f1_width) << "\tOutput File: " << outfile
<< std::endl;
}
if (not seed_file.empty()) {
std::cout << std::setw(f1_width) << "\tSeed File: " << seed_file
<< std::endl;
}
if (not file_identifier.empty()) {
std::cout << std::setw(f1_width) << "\tFile ID: " << file_identifier
<< std::endl;
}
if (debug) {
std::cout << std::setw(f1_width) << "\tDEBUG MODE: "
<< "ON" << std::endl;
}
#ifdef _OPENMP
if (user_def) {
std::cout << std::setw(f1_width) << "\tOMP threads:" << n_threads
<< std::endl;
}
else {
std::cout << std::setw(f1_width) << "\tOMP threads:"
<< "AUTOMATIC" << std::endl;
}
#endif
std::cout << "\t-------------------------------------------------------------"
"---------\n"
<< std::endl;
}
|
// Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "beatsaber-hook/shared/utils/typedefs.h"
#include "beatsaber-hook/shared/utils/byref.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Begin forward declares
// Forward declaring namespace: System::Xml::Schema
namespace System::Xml::Schema {
// Forward declaring type: CompiledIdentityConstraint
class CompiledIdentityConstraint;
// Forward declaring type: SelectorActiveAxis
class SelectorActiveAxis;
}
// Forward declaring namespace: System::Collections
namespace System::Collections {
// Forward declaring type: ArrayList
class ArrayList;
// Forward declaring type: Hashtable
class Hashtable;
}
// Completed forward declares
// Type namespace: System.Xml.Schema
namespace System::Xml::Schema {
// Forward declaring type: ConstraintStruct
class ConstraintStruct;
}
#include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
NEED_NO_BOX(::System::Xml::Schema::ConstraintStruct);
DEFINE_IL2CPP_ARG_TYPE(::System::Xml::Schema::ConstraintStruct*, "System.Xml.Schema", "ConstraintStruct");
// Type namespace: System.Xml.Schema
namespace System::Xml::Schema {
// Size: 0x3C
#pragma pack(push, 1)
// Autogenerated type: System.Xml.Schema.ConstraintStruct
// [TokenAttribute] Offset: FFFFFFFF
class ConstraintStruct : public ::Il2CppObject {
public:
public:
// System.Xml.Schema.CompiledIdentityConstraint constraint
// Size: 0x8
// Offset: 0x10
::System::Xml::Schema::CompiledIdentityConstraint* constraint;
// Field size check
static_assert(sizeof(::System::Xml::Schema::CompiledIdentityConstraint*) == 0x8);
// System.Xml.Schema.SelectorActiveAxis axisSelector
// Size: 0x8
// Offset: 0x18
::System::Xml::Schema::SelectorActiveAxis* axisSelector;
// Field size check
static_assert(sizeof(::System::Xml::Schema::SelectorActiveAxis*) == 0x8);
// System.Collections.ArrayList axisFields
// Size: 0x8
// Offset: 0x20
::System::Collections::ArrayList* axisFields;
// Field size check
static_assert(sizeof(::System::Collections::ArrayList*) == 0x8);
// System.Collections.Hashtable qualifiedTable
// Size: 0x8
// Offset: 0x28
::System::Collections::Hashtable* qualifiedTable;
// Field size check
static_assert(sizeof(::System::Collections::Hashtable*) == 0x8);
// System.Collections.Hashtable keyrefTable
// Size: 0x8
// Offset: 0x30
::System::Collections::Hashtable* keyrefTable;
// Field size check
static_assert(sizeof(::System::Collections::Hashtable*) == 0x8);
// private System.Int32 tableDim
// Size: 0x4
// Offset: 0x38
int tableDim;
// Field size check
static_assert(sizeof(int) == 0x4);
public:
// Get instance field reference: System.Xml.Schema.CompiledIdentityConstraint constraint
[[deprecated("Use field access instead!")]] ::System::Xml::Schema::CompiledIdentityConstraint*& dyn_constraint();
// Get instance field reference: System.Xml.Schema.SelectorActiveAxis axisSelector
[[deprecated("Use field access instead!")]] ::System::Xml::Schema::SelectorActiveAxis*& dyn_axisSelector();
// Get instance field reference: System.Collections.ArrayList axisFields
[[deprecated("Use field access instead!")]] ::System::Collections::ArrayList*& dyn_axisFields();
// Get instance field reference: System.Collections.Hashtable qualifiedTable
[[deprecated("Use field access instead!")]] ::System::Collections::Hashtable*& dyn_qualifiedTable();
// Get instance field reference: System.Collections.Hashtable keyrefTable
[[deprecated("Use field access instead!")]] ::System::Collections::Hashtable*& dyn_keyrefTable();
// Get instance field reference: private System.Int32 tableDim
[[deprecated("Use field access instead!")]] int& dyn_tableDim();
// System.Int32 get_TableDim()
// Offset: 0x109E348
int get_TableDim();
// System.Void .ctor(System.Xml.Schema.CompiledIdentityConstraint constraint)
// Offset: 0x109E350
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static ConstraintStruct* New_ctor(::System::Xml::Schema::CompiledIdentityConstraint* constraint) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Xml::Schema::ConstraintStruct::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<ConstraintStruct*, creationType>(constraint)));
}
}; // System.Xml.Schema.ConstraintStruct
#pragma pack(pop)
static check_size<sizeof(ConstraintStruct), 56 + sizeof(int)> __System_Xml_Schema_ConstraintStructSizeCheck;
static_assert(sizeof(ConstraintStruct) == 0x3C);
}
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
// Writing MetadataGetter for method: System::Xml::Schema::ConstraintStruct::get_TableDim
// Il2CppName: get_TableDim
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (System::Xml::Schema::ConstraintStruct::*)()>(&System::Xml::Schema::ConstraintStruct::get_TableDim)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(System::Xml::Schema::ConstraintStruct*), "get_TableDim", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: System::Xml::Schema::ConstraintStruct::New_ctor
// Il2CppName: .ctor
// Cannot get method pointer of value based method overload from template for constructor!
// Try using FindMethod instead!
|
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/browser/renderer_host/input/gesture_event_queue.h"
#include <stddef.h>
#include <memory>
#include <utility>
#include <vector>
#include "base/location.h"
#include "base/logging.h"
#include "base/message_loop/message_loop.h"
#include "base/single_thread_task_runner.h"
#include "base/threading/thread_task_runner_handle.h"
#include "base/time/time.h"
#include "content/browser/renderer_host/input/touchpad_tap_suppression_controller.h"
#include "content/common/input/input_event_ack_state.h"
#include "content/common/input/synthetic_web_input_event_builders.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/WebKit/public/web/WebInputEvent.h"
using base::TimeDelta;
using blink::WebGestureDevice;
using blink::WebGestureEvent;
using blink::WebInputEvent;
namespace content {
class GestureEventQueueTest : public testing::Test,
public GestureEventQueueClient,
public TouchpadTapSuppressionControllerClient {
public:
GestureEventQueueTest()
: acked_gesture_event_count_(0),
sent_gesture_event_count_(0) {}
~GestureEventQueueTest() override {}
// testing::Test
void SetUp() override {
queue_.reset(new GestureEventQueue(this, this, DefaultConfig()));
}
void TearDown() override {
// Process all pending tasks to avoid leaks.
RunUntilIdle();
queue_.reset();
}
// GestureEventQueueClient
void SendGestureEventImmediately(
const GestureEventWithLatencyInfo& event) override {
++sent_gesture_event_count_;
if (sync_ack_result_) {
std::unique_ptr<InputEventAckState> ack_result =
std::move(sync_ack_result_);
SendInputEventACK(event.event.type, *ack_result);
}
}
void OnGestureEventAck(const GestureEventWithLatencyInfo& event,
InputEventAckState ack_result) override {
++acked_gesture_event_count_;
last_acked_event_ = event.event;
if (sync_followup_event_) {
auto sync_followup_event = std::move(sync_followup_event_);
SimulateGestureEvent(*sync_followup_event);
}
}
// TouchpadTapSuppressionControllerClient
void SendMouseEventImmediately(
const MouseEventWithLatencyInfo& event) override {}
protected:
static GestureEventQueue::Config DefaultConfig() {
return GestureEventQueue::Config();
}
void SetUpForDebounce(int interval_ms) {
queue()->set_debounce_interval_time_ms_for_testing(interval_ms);
}
void SimulateGestureEvent(const WebGestureEvent& gesture) {
queue()->QueueEvent(GestureEventWithLatencyInfo(gesture));
}
void SimulateGestureEvent(WebInputEvent::Type type,
WebGestureDevice sourceDevice) {
SimulateGestureEvent(
SyntheticWebGestureEventBuilder::Build(type, sourceDevice));
}
void SimulateGestureScrollUpdateEvent(float dX, float dY, int modifiers) {
SimulateGestureEvent(SyntheticWebGestureEventBuilder::BuildScrollUpdate(
dX, dY, modifiers, blink::WebGestureDeviceTouchscreen));
}
void SimulateGesturePinchUpdateEvent(float scale,
float anchorX,
float anchorY,
int modifiers) {
SimulateGestureEvent(SyntheticWebGestureEventBuilder::BuildPinchUpdate(
scale,
anchorX,
anchorY,
modifiers,
blink::WebGestureDeviceTouchscreen));
}
void SimulateGestureFlingStartEvent(float velocityX,
float velocityY,
WebGestureDevice sourceDevice) {
SimulateGestureEvent(
SyntheticWebGestureEventBuilder::BuildFling(velocityX,
velocityY,
sourceDevice));
}
void SendInputEventACK(WebInputEvent::Type type,
InputEventAckState ack) {
queue()->ProcessGestureAck(ack, type, ui::LatencyInfo());
}
void RunUntilIdle() {
base::MessageLoop::current()->RunUntilIdle();
}
size_t GetAndResetSentGestureEventCount() {
size_t count = sent_gesture_event_count_;
sent_gesture_event_count_ = 0;
return count;
}
size_t GetAndResetAckedGestureEventCount() {
size_t count = acked_gesture_event_count_;
acked_gesture_event_count_ = 0;
return count;
}
const WebGestureEvent& last_acked_event() const {
return last_acked_event_;
}
void set_synchronous_ack(InputEventAckState ack_result) {
sync_ack_result_.reset(new InputEventAckState(ack_result));
}
void set_sync_followup_event(WebInputEvent::Type type,
WebGestureDevice sourceDevice) {
sync_followup_event_.reset(new WebGestureEvent(
SyntheticWebGestureEventBuilder::Build(type, sourceDevice)));
}
unsigned GestureEventQueueSize() {
return queue()->coalesced_gesture_events_.size();
}
WebGestureEvent GestureEventSecondFromLastQueueEvent() {
return queue()->coalesced_gesture_events_.at(
GestureEventQueueSize() - 2).event;
}
WebGestureEvent GestureEventLastQueueEvent() {
return queue()->coalesced_gesture_events_.back().event;
}
unsigned GestureEventDebouncingQueueSize() {
return queue()->debouncing_deferral_queue_.size();
}
WebGestureEvent GestureEventQueueEventAt(int i) {
return queue()->coalesced_gesture_events_.at(i).event;
}
bool ScrollingInProgress() {
return queue()->scrolling_in_progress_;
}
bool FlingInProgress() { return queue()->fling_in_progress_; }
bool WillIgnoreNextACK() {
return queue()->ignore_next_ack_;
}
GestureEventQueue* queue() const {
return queue_.get();
}
private:
std::unique_ptr<GestureEventQueue> queue_;
size_t acked_gesture_event_count_;
size_t sent_gesture_event_count_;
WebGestureEvent last_acked_event_;
std::unique_ptr<InputEventAckState> sync_ack_result_;
std::unique_ptr<WebGestureEvent> sync_followup_event_;
base::MessageLoopForUI message_loop_;
};
#if GTEST_HAS_PARAM_TEST
// This is for tests that are to be run for all source devices.
class GestureEventQueueWithSourceTest
: public GestureEventQueueTest,
public testing::WithParamInterface<WebGestureDevice> {};
#endif // GTEST_HAS_PARAM_TEST
TEST_F(GestureEventQueueTest, CoalescesScrollGestureEvents) {
// Test coalescing of only GestureScrollUpdate events.
// Simulate gesture events.
// Sent.
SimulateGestureEvent(WebInputEvent::GestureScrollBegin,
blink::WebGestureDeviceTouchscreen);
EXPECT_EQ(1U, GetAndResetSentGestureEventCount());
// Enqueued.
SimulateGestureScrollUpdateEvent(8, -5, 0);
// Make sure that the queue contains what we think it should.
WebGestureEvent merged_event = GestureEventLastQueueEvent();
EXPECT_EQ(2U, GestureEventQueueSize());
EXPECT_EQ(WebInputEvent::GestureScrollUpdate, merged_event.type);
EXPECT_EQ(blink::WebGestureDeviceTouchscreen, merged_event.sourceDevice);
// Coalesced.
SimulateGestureScrollUpdateEvent(8, -6, 0);
// Check that coalescing updated the correct values.
merged_event = GestureEventLastQueueEvent();
EXPECT_EQ(WebInputEvent::GestureScrollUpdate, merged_event.type);
EXPECT_EQ(0, merged_event.modifiers);
EXPECT_EQ(16, merged_event.data.scrollUpdate.deltaX);
EXPECT_EQ(-11, merged_event.data.scrollUpdate.deltaY);
EXPECT_EQ(blink::WebGestureDeviceTouchscreen, merged_event.sourceDevice);
// Enqueued.
SimulateGestureScrollUpdateEvent(8, -7, 1);
// Check that we didn't wrongly coalesce.
merged_event = GestureEventLastQueueEvent();
EXPECT_EQ(WebInputEvent::GestureScrollUpdate, merged_event.type);
EXPECT_EQ(1, merged_event.modifiers);
EXPECT_EQ(blink::WebGestureDeviceTouchscreen, merged_event.sourceDevice);
// Different.
SimulateGestureEvent(WebInputEvent::GestureScrollEnd,
blink::WebGestureDeviceTouchscreen);
// Check that only the first event was sent.
EXPECT_EQ(0U, GetAndResetSentGestureEventCount());
// Check that the ACK sends the second message.
SendInputEventACK(WebInputEvent::GestureScrollBegin,
INPUT_EVENT_ACK_STATE_CONSUMED);
RunUntilIdle();
EXPECT_EQ(1U, GetAndResetAckedGestureEventCount());
EXPECT_EQ(1U, GetAndResetSentGestureEventCount());
// Ack for queued coalesced event.
SendInputEventACK(WebInputEvent::GestureScrollUpdate,
INPUT_EVENT_ACK_STATE_CONSUMED);
RunUntilIdle();
EXPECT_EQ(1U, GetAndResetAckedGestureEventCount());
EXPECT_EQ(1U, GetAndResetSentGestureEventCount());
// Ack for queued uncoalesced event.
SendInputEventACK(WebInputEvent::GestureScrollUpdate,
INPUT_EVENT_ACK_STATE_CONSUMED);
RunUntilIdle();
EXPECT_EQ(1U, GetAndResetAckedGestureEventCount());
EXPECT_EQ(1U, GetAndResetSentGestureEventCount());
// After the final ack, the queue should be empty.
SendInputEventACK(WebInputEvent::GestureScrollEnd,
INPUT_EVENT_ACK_STATE_CONSUMED);
RunUntilIdle();
EXPECT_EQ(1U, GetAndResetAckedGestureEventCount());
EXPECT_EQ(0U, GetAndResetSentGestureEventCount());
}
TEST_F(GestureEventQueueTest,
DoesNotCoalesceScrollGestureEventsFromDifferentDevices) {
// Test that GestureScrollUpdate events from Touchscreen and Touchpad do not
// coalesce.
// Sent.
SimulateGestureEvent(WebInputEvent::GestureScrollBegin,
blink::WebGestureDeviceTouchscreen);
EXPECT_EQ(1U, GetAndResetSentGestureEventCount());
// Enqueued.
SimulateGestureScrollUpdateEvent(8, -5, 0);
// Make sure that the queue contains what we think it should.
EXPECT_EQ(2U, GestureEventQueueSize());
EXPECT_EQ(blink::WebGestureDeviceTouchscreen,
GestureEventLastQueueEvent().sourceDevice);
// Coalesced.
SimulateGestureScrollUpdateEvent(8, -6, 0);
EXPECT_EQ(2U, GestureEventQueueSize());
EXPECT_EQ(blink::WebGestureDeviceTouchscreen,
GestureEventLastQueueEvent().sourceDevice);
// Enqueued.
SimulateGestureEvent(WebInputEvent::GestureScrollUpdate,
blink::WebGestureDeviceTouchpad);
EXPECT_EQ(3U, GestureEventQueueSize());
EXPECT_EQ(blink::WebGestureDeviceTouchpad,
GestureEventLastQueueEvent().sourceDevice);
// Coalesced.
SimulateGestureEvent(WebInputEvent::GestureScrollUpdate,
blink::WebGestureDeviceTouchpad);
EXPECT_EQ(3U, GestureEventQueueSize());
EXPECT_EQ(blink::WebGestureDeviceTouchpad,
GestureEventLastQueueEvent().sourceDevice);
// Enqueued.
SimulateGestureScrollUpdateEvent(8, -7, 0);
EXPECT_EQ(4U, GestureEventQueueSize());
EXPECT_EQ(blink::WebGestureDeviceTouchscreen,
GestureEventLastQueueEvent().sourceDevice);
}
TEST_F(GestureEventQueueTest, CoalescesScrollAndPinchEvents) {
// Test coalescing of only GestureScrollUpdate events.
// Simulate gesture events.
// Sent.
SimulateGestureEvent(WebInputEvent::GestureScrollBegin,
blink::WebGestureDeviceTouchscreen);
// Sent.
SimulateGestureEvent(WebInputEvent::GesturePinchBegin,
blink::WebGestureDeviceTouchscreen);
// Enqueued.
SimulateGestureScrollUpdateEvent(8, -4, 1);
// Make sure that the queue contains what we think it should.
WebGestureEvent merged_event = GestureEventLastQueueEvent();
EXPECT_EQ(3U, GestureEventQueueSize());
EXPECT_EQ(WebInputEvent::GestureScrollUpdate, merged_event.type);
// Coalesced without changing event order. Note anchor at (60, 60). Anchoring
// from a point that is not the origin should still give us the right scroll.
SimulateGesturePinchUpdateEvent(1.5, 60, 60, 1);
EXPECT_EQ(4U, GestureEventQueueSize());
merged_event = GestureEventLastQueueEvent();
EXPECT_EQ(WebInputEvent::GesturePinchUpdate, merged_event.type);
EXPECT_EQ(1.5, merged_event.data.pinchUpdate.scale);
EXPECT_EQ(1, merged_event.modifiers);
EXPECT_EQ(blink::WebGestureDeviceTouchscreen, merged_event.sourceDevice);
merged_event = GestureEventSecondFromLastQueueEvent();
EXPECT_EQ(WebInputEvent::GestureScrollUpdate, merged_event.type);
EXPECT_EQ(8, merged_event.data.scrollUpdate.deltaX);
EXPECT_EQ(-4, merged_event.data.scrollUpdate.deltaY);
EXPECT_EQ(1, merged_event.modifiers);
EXPECT_EQ(blink::WebGestureDeviceTouchscreen, merged_event.sourceDevice);
// Enqueued.
SimulateGestureScrollUpdateEvent(6, -3, 1);
// Check whether coalesced correctly.
EXPECT_EQ(4U, GestureEventQueueSize());
merged_event = GestureEventLastQueueEvent();
EXPECT_EQ(WebInputEvent::GesturePinchUpdate, merged_event.type);
EXPECT_EQ(1.5, merged_event.data.pinchUpdate.scale);
EXPECT_EQ(1, merged_event.modifiers);
EXPECT_EQ(blink::WebGestureDeviceTouchscreen, merged_event.sourceDevice);
merged_event = GestureEventSecondFromLastQueueEvent();
EXPECT_EQ(WebInputEvent::GestureScrollUpdate, merged_event.type);
EXPECT_EQ(12, merged_event.data.scrollUpdate.deltaX);
EXPECT_EQ(-6, merged_event.data.scrollUpdate.deltaY);
EXPECT_EQ(1, merged_event.modifiers);
EXPECT_EQ(blink::WebGestureDeviceTouchscreen, merged_event.sourceDevice);
// Enqueued.
SimulateGesturePinchUpdateEvent(2, 60, 60, 1);
// Check whether coalesced correctly.
EXPECT_EQ(4U, GestureEventQueueSize());
merged_event = GestureEventLastQueueEvent();
EXPECT_EQ(WebInputEvent::GesturePinchUpdate, merged_event.type);
EXPECT_EQ(3, merged_event.data.pinchUpdate.scale);
EXPECT_EQ(1, merged_event.modifiers);
EXPECT_EQ(blink::WebGestureDeviceTouchscreen, merged_event.sourceDevice);
merged_event = GestureEventSecondFromLastQueueEvent();
EXPECT_EQ(WebInputEvent::GestureScrollUpdate, merged_event.type);
EXPECT_EQ(12, merged_event.data.scrollUpdate.deltaX);
EXPECT_EQ(-6, merged_event.data.scrollUpdate.deltaY);
EXPECT_EQ(1, merged_event.modifiers);
EXPECT_EQ(blink::WebGestureDeviceTouchscreen, merged_event.sourceDevice);
// Enqueued.
SimulateGesturePinchUpdateEvent(2, 60, 60, 1);
// Check whether coalesced correctly.
EXPECT_EQ(4U, GestureEventQueueSize());
merged_event = GestureEventLastQueueEvent();
EXPECT_EQ(WebInputEvent::GesturePinchUpdate, merged_event.type);
EXPECT_EQ(6, merged_event.data.pinchUpdate.scale);
EXPECT_EQ(1, merged_event.modifiers);
EXPECT_EQ(blink::WebGestureDeviceTouchscreen, merged_event.sourceDevice);
merged_event = GestureEventSecondFromLastQueueEvent();
EXPECT_EQ(WebInputEvent::GestureScrollUpdate, merged_event.type);
EXPECT_EQ(12, merged_event.data.scrollUpdate.deltaX);
EXPECT_EQ(-6, merged_event.data.scrollUpdate.deltaY);
EXPECT_EQ(1, merged_event.modifiers);
EXPECT_EQ(blink::WebGestureDeviceTouchscreen, merged_event.sourceDevice);
// Check that only the first event was sent.
EXPECT_EQ(1U, GetAndResetSentGestureEventCount());
// Check that the ACK sends the second message.
SendInputEventACK(WebInputEvent::GestureScrollBegin,
INPUT_EVENT_ACK_STATE_CONSUMED);
RunUntilIdle();
EXPECT_EQ(1U, GetAndResetSentGestureEventCount());
// Enqueued.
SimulateGestureScrollUpdateEvent(6, -6, 1);
// Check whether coalesced correctly.
EXPECT_EQ(3U, GestureEventQueueSize());
merged_event = GestureEventLastQueueEvent();
EXPECT_EQ(WebInputEvent::GesturePinchUpdate, merged_event.type);
EXPECT_EQ(6, merged_event.data.pinchUpdate.scale);
EXPECT_EQ(1, merged_event.modifiers);
EXPECT_EQ(blink::WebGestureDeviceTouchscreen, merged_event.sourceDevice);
merged_event = GestureEventSecondFromLastQueueEvent();
EXPECT_EQ(WebInputEvent::GestureScrollUpdate, merged_event.type);
EXPECT_EQ(13, merged_event.data.scrollUpdate.deltaX);
EXPECT_EQ(-7, merged_event.data.scrollUpdate.deltaY);
EXPECT_EQ(1, merged_event.modifiers);
EXPECT_EQ(blink::WebGestureDeviceTouchscreen, merged_event.sourceDevice);
// At this point ACKs shouldn't be getting ignored.
EXPECT_FALSE(WillIgnoreNextACK());
// Check that the ACK sends both scroll and pinch updates.
SendInputEventACK(WebInputEvent::GesturePinchBegin,
INPUT_EVENT_ACK_STATE_CONSUMED);
RunUntilIdle();
EXPECT_EQ(2U, GetAndResetSentGestureEventCount());
// The next ACK should be getting ignored.
EXPECT_TRUE(WillIgnoreNextACK());
// Enqueued.
SimulateGestureScrollUpdateEvent(1, -1, 1);
// Check whether coalesced correctly.
EXPECT_EQ(3U, GestureEventQueueSize());
merged_event = GestureEventLastQueueEvent();
EXPECT_EQ(WebInputEvent::GestureScrollUpdate, merged_event.type);
EXPECT_EQ(1, merged_event.data.scrollUpdate.deltaX);
EXPECT_EQ(-1, merged_event.data.scrollUpdate.deltaY);
EXPECT_EQ(1, merged_event.modifiers);
EXPECT_EQ(blink::WebGestureDeviceTouchscreen, merged_event.sourceDevice);
merged_event = GestureEventSecondFromLastQueueEvent();
EXPECT_EQ(WebInputEvent::GesturePinchUpdate, merged_event.type);
EXPECT_EQ(6, merged_event.data.pinchUpdate.scale);
EXPECT_EQ(1, merged_event.modifiers);
EXPECT_EQ(blink::WebGestureDeviceTouchscreen, merged_event.sourceDevice);
// Enqueued.
SimulateGestureScrollUpdateEvent(2, -2, 1);
// Coalescing scrolls should still work.
EXPECT_EQ(3U, GestureEventQueueSize());
merged_event = GestureEventLastQueueEvent();
EXPECT_EQ(WebInputEvent::GestureScrollUpdate, merged_event.type);
EXPECT_EQ(3, merged_event.data.scrollUpdate.deltaX);
EXPECT_EQ(-3, merged_event.data.scrollUpdate.deltaY);
EXPECT_EQ(1, merged_event.modifiers);
EXPECT_EQ(blink::WebGestureDeviceTouchscreen, merged_event.sourceDevice);
merged_event = GestureEventSecondFromLastQueueEvent();
EXPECT_EQ(WebInputEvent::GesturePinchUpdate, merged_event.type);
EXPECT_EQ(6, merged_event.data.pinchUpdate.scale);
EXPECT_EQ(1, merged_event.modifiers);
EXPECT_EQ(blink::WebGestureDeviceTouchscreen, merged_event.sourceDevice);
// Enqueued.
SimulateGesturePinchUpdateEvent(0.5, 60, 60, 1);
// Check whether coalesced correctly.
EXPECT_EQ(4U, GestureEventQueueSize());
merged_event = GestureEventLastQueueEvent();
EXPECT_EQ(WebInputEvent::GesturePinchUpdate, merged_event.type);
EXPECT_EQ(0.5, merged_event.data.pinchUpdate.scale);
EXPECT_EQ(1, merged_event.modifiers);
EXPECT_EQ(blink::WebGestureDeviceTouchscreen, merged_event.sourceDevice);
merged_event = GestureEventSecondFromLastQueueEvent();
EXPECT_EQ(WebInputEvent::GestureScrollUpdate, merged_event.type);
EXPECT_EQ(3, merged_event.data.scrollUpdate.deltaX);
EXPECT_EQ(-3, merged_event.data.scrollUpdate.deltaY);
EXPECT_EQ(1, merged_event.modifiers);
EXPECT_EQ(blink::WebGestureDeviceTouchscreen, merged_event.sourceDevice);
// Check that the ACK gets ignored.
SendInputEventACK(WebInputEvent::GestureScrollUpdate,
INPUT_EVENT_ACK_STATE_CONSUMED);
EXPECT_EQ(WebInputEvent::GestureScrollUpdate, last_acked_event().type);
RunUntilIdle();
EXPECT_EQ(0U, GetAndResetSentGestureEventCount());
// The flag should have been flipped back to false.
EXPECT_FALSE(WillIgnoreNextACK());
// Enqueued.
SimulateGestureScrollUpdateEvent(2, -2, 2);
// Shouldn't coalesce with different modifiers.
EXPECT_EQ(4U, GestureEventQueueSize());
merged_event = GestureEventLastQueueEvent();
EXPECT_EQ(WebInputEvent::GestureScrollUpdate, merged_event.type);
EXPECT_EQ(2, merged_event.data.scrollUpdate.deltaX);
EXPECT_EQ(-2, merged_event.data.scrollUpdate.deltaY);
EXPECT_EQ(2, merged_event.modifiers);
EXPECT_EQ(blink::WebGestureDeviceTouchscreen, merged_event.sourceDevice);
merged_event = GestureEventSecondFromLastQueueEvent();
EXPECT_EQ(WebInputEvent::GesturePinchUpdate, merged_event.type);
EXPECT_EQ(0.5, merged_event.data.pinchUpdate.scale);
EXPECT_EQ(1, merged_event.modifiers);
EXPECT_EQ(blink::WebGestureDeviceTouchscreen, merged_event.sourceDevice);
// Check that the ACK sends the next scroll pinch pair.
SendInputEventACK(WebInputEvent::GesturePinchUpdate,
INPUT_EVENT_ACK_STATE_CONSUMED);
EXPECT_EQ(WebInputEvent::GesturePinchUpdate, last_acked_event().type);
RunUntilIdle();
EXPECT_EQ(2U, GetAndResetSentGestureEventCount());
// Check that the ACK sends the second message.
SendInputEventACK(WebInputEvent::GestureScrollUpdate,
INPUT_EVENT_ACK_STATE_CONSUMED);
EXPECT_EQ(WebInputEvent::GestureScrollUpdate, last_acked_event().type);
RunUntilIdle();
EXPECT_EQ(0U, GetAndResetSentGestureEventCount());
// Check that the ACK sends the second event.
SendInputEventACK(WebInputEvent::GesturePinchUpdate,
INPUT_EVENT_ACK_STATE_CONSUMED);
EXPECT_EQ(WebInputEvent::GesturePinchUpdate, last_acked_event().type);
RunUntilIdle();
EXPECT_EQ(1U, GetAndResetSentGestureEventCount());
// Check that the queue is empty after ACK and no events get sent.
SendInputEventACK(WebInputEvent::GestureScrollUpdate,
INPUT_EVENT_ACK_STATE_CONSUMED);
EXPECT_EQ(WebInputEvent::GestureScrollUpdate, last_acked_event().type);
RunUntilIdle();
EXPECT_EQ(0U, GetAndResetSentGestureEventCount());
EXPECT_EQ(0U, GestureEventQueueSize());
}
TEST_F(GestureEventQueueTest, CoalescesMultiplePinchEventSequences) {
// Simulate a pinch sequence.
SimulateGestureEvent(WebInputEvent::GestureScrollBegin,
blink::WebGestureDeviceTouchscreen);
SimulateGestureEvent(WebInputEvent::GesturePinchBegin,
blink::WebGestureDeviceTouchscreen);
SimulateGestureScrollUpdateEvent(8, -4, 1);
// Make sure that the queue contains what we think it should.
WebGestureEvent merged_event = GestureEventLastQueueEvent();
size_t expected_events_in_queue = 3;
EXPECT_EQ(expected_events_in_queue, GestureEventQueueSize());
EXPECT_EQ(WebInputEvent::GestureScrollUpdate, merged_event.type);
// Coalesced without changing event order. Note anchor at (60, 60). Anchoring
// from a point that is not the origin should still give us the right scroll.
SimulateGesturePinchUpdateEvent(1.5, 60, 60, 1);
EXPECT_EQ(++expected_events_in_queue, GestureEventQueueSize());
merged_event = GestureEventLastQueueEvent();
EXPECT_EQ(WebInputEvent::GesturePinchUpdate, merged_event.type);
EXPECT_EQ(1.5, merged_event.data.pinchUpdate.scale);
EXPECT_EQ(1, merged_event.modifiers);
merged_event = GestureEventSecondFromLastQueueEvent();
EXPECT_EQ(WebInputEvent::GestureScrollUpdate, merged_event.type);
EXPECT_EQ(8, merged_event.data.scrollUpdate.deltaX);
EXPECT_EQ(-4, merged_event.data.scrollUpdate.deltaY);
EXPECT_EQ(1, merged_event.modifiers);
// Enqueued.
SimulateGestureScrollUpdateEvent(6, -3, 1);
// Check whether coalesced correctly.
EXPECT_EQ(expected_events_in_queue, GestureEventQueueSize());
merged_event = GestureEventLastQueueEvent();
EXPECT_EQ(WebInputEvent::GesturePinchUpdate, merged_event.type);
EXPECT_EQ(1.5, merged_event.data.pinchUpdate.scale);
EXPECT_EQ(1, merged_event.modifiers);
merged_event = GestureEventSecondFromLastQueueEvent();
EXPECT_EQ(WebInputEvent::GestureScrollUpdate, merged_event.type);
EXPECT_EQ(12, merged_event.data.scrollUpdate.deltaX);
EXPECT_EQ(-6, merged_event.data.scrollUpdate.deltaY);
EXPECT_EQ(1, merged_event.modifiers);
// Now start another sequence before the previous sequence has been ack'ed.
SimulateGestureEvent(WebInputEvent::GesturePinchEnd,
blink::WebGestureDeviceTouchscreen);
SimulateGestureEvent(WebInputEvent::GestureScrollEnd,
blink::WebGestureDeviceTouchscreen);
SimulateGestureEvent(WebInputEvent::GestureScrollBegin,
blink::WebGestureDeviceTouchscreen);
SimulateGestureEvent(WebInputEvent::GesturePinchBegin,
blink::WebGestureDeviceTouchscreen);
SimulateGestureScrollUpdateEvent(8, -4, 1);
// Make sure that the queue contains what we think it should.
expected_events_in_queue += 5;
merged_event = GestureEventLastQueueEvent();
EXPECT_EQ(expected_events_in_queue, GestureEventQueueSize());
EXPECT_EQ(WebInputEvent::GestureScrollUpdate, merged_event.type);
// Coalesced without changing event order. Note anchor at (60, 60). Anchoring
// from a point that is not the origin should still give us the right scroll.
SimulateGesturePinchUpdateEvent(1.5, 30, 30, 1);
EXPECT_EQ(++expected_events_in_queue, GestureEventQueueSize());
merged_event = GestureEventLastQueueEvent();
EXPECT_EQ(WebInputEvent::GesturePinchUpdate, merged_event.type);
EXPECT_EQ(1.5, merged_event.data.pinchUpdate.scale);
EXPECT_EQ(1, merged_event.modifiers);
merged_event = GestureEventSecondFromLastQueueEvent();
EXPECT_EQ(WebInputEvent::GestureScrollUpdate, merged_event.type);
EXPECT_EQ(8, merged_event.data.scrollUpdate.deltaX);
EXPECT_EQ(-4, merged_event.data.scrollUpdate.deltaY);
EXPECT_EQ(1, merged_event.modifiers);
// Enqueued.
SimulateGestureScrollUpdateEvent(6, -3, 1);
// Check whether coalesced correctly.
EXPECT_EQ(expected_events_in_queue, GestureEventQueueSize());
merged_event = GestureEventLastQueueEvent();
EXPECT_EQ(WebInputEvent::GesturePinchUpdate, merged_event.type);
EXPECT_EQ(1.5, merged_event.data.pinchUpdate.scale);
EXPECT_EQ(1, merged_event.modifiers);
merged_event = GestureEventSecondFromLastQueueEvent();
EXPECT_EQ(WebInputEvent::GestureScrollUpdate, merged_event.type);
EXPECT_EQ(12, merged_event.data.scrollUpdate.deltaX);
EXPECT_EQ(-6, merged_event.data.scrollUpdate.deltaY);
EXPECT_EQ(1, merged_event.modifiers);
}
TEST_F(GestureEventQueueTest, CoalescesPinchSequencesWithEarlyAck) {
SimulateGestureEvent(WebInputEvent::GestureScrollBegin,
blink::WebGestureDeviceTouchscreen);
SendInputEventACK(WebInputEvent::GestureScrollBegin,
INPUT_EVENT_ACK_STATE_CONSUMED);
SimulateGestureEvent(WebInputEvent::GesturePinchBegin,
blink::WebGestureDeviceTouchscreen);
SendInputEventACK(WebInputEvent::GesturePinchBegin,
INPUT_EVENT_ACK_STATE_CONSUMED);
// ScrollBegin and PinchBegin have been sent
EXPECT_EQ(2U, GetAndResetSentGestureEventCount());
EXPECT_EQ(0U, GestureEventQueueSize());
SimulateGestureScrollUpdateEvent(5, 5, 1);
EXPECT_EQ(1U, GetAndResetSentGestureEventCount());
EXPECT_EQ(WebInputEvent::GestureScrollUpdate,
GestureEventLastQueueEvent().type);
EXPECT_EQ(1U, GestureEventQueueSize());
SimulateGesturePinchUpdateEvent(2, 60, 60, 1);
EXPECT_EQ(1U, GetAndResetSentGestureEventCount());
EXPECT_EQ(WebInputEvent::GesturePinchUpdate,
GestureEventLastQueueEvent().type);
EXPECT_EQ(2U, GestureEventQueueSize());
SimulateGesturePinchUpdateEvent(3, 60, 60, 1);
EXPECT_EQ(0U, GetAndResetSentGestureEventCount());
EXPECT_EQ(WebInputEvent::GesturePinchUpdate,
GestureEventLastQueueEvent().type);
EXPECT_EQ(3U, GestureEventQueueSize());
SimulateGestureScrollUpdateEvent(5, 5, 1);
EXPECT_EQ(0U, GetAndResetSentGestureEventCount());
// The coalesced pinch/scroll pair will have been re-arranged, with the
// pinch following the scroll.
EXPECT_EQ(WebInputEvent::GesturePinchUpdate,
GestureEventLastQueueEvent().type);
EXPECT_EQ(4U, GestureEventQueueSize());
SimulateGesturePinchUpdateEvent(4, 60, 60, 1);
EXPECT_EQ(0U, GetAndResetSentGestureEventCount());
EXPECT_EQ(4U, GestureEventQueueSize());
SendInputEventACK(WebInputEvent::GestureScrollUpdate,
INPUT_EVENT_ACK_STATE_CONSUMED);
EXPECT_EQ(0U, GetAndResetSentGestureEventCount());
EXPECT_EQ(3U, GestureEventQueueSize());
SendInputEventACK(WebInputEvent::GesturePinchUpdate,
INPUT_EVENT_ACK_STATE_CONSUMED);
EXPECT_EQ(2U, GetAndResetSentGestureEventCount());
EXPECT_EQ(2U, GestureEventQueueSize());
EXPECT_EQ(2.f, last_acked_event().data.pinchUpdate.scale);
SendInputEventACK(WebInputEvent::GestureScrollUpdate,
INPUT_EVENT_ACK_STATE_CONSUMED);
EXPECT_EQ(WebInputEvent::GestureScrollUpdate, last_acked_event().type);
SendInputEventACK(WebInputEvent::GesturePinchUpdate,
INPUT_EVENT_ACK_STATE_CONSUMED);
EXPECT_EQ(WebInputEvent::GesturePinchUpdate, last_acked_event().type);
EXPECT_EQ(3.f * 4.f, last_acked_event().data.pinchUpdate.scale);
EXPECT_EQ(0U, GestureEventQueueSize());
}
TEST_F(GestureEventQueueTest,
DoesNotCoalescePinchGestureEventsWithDifferentModifiers) {
// Insert an event to force queueing of gestures.
SimulateGestureEvent(WebInputEvent::GestureTapCancel,
blink::WebGestureDeviceTouchscreen);
EXPECT_EQ(1U, GetAndResetSentGestureEventCount());
EXPECT_EQ(1U, GestureEventQueueSize());
SimulateGestureScrollUpdateEvent(5, 5, 1);
EXPECT_EQ(0U, GetAndResetSentGestureEventCount());
EXPECT_EQ(2U, GestureEventQueueSize());
SimulateGesturePinchUpdateEvent(3, 60, 60, 1);
EXPECT_EQ(0U, GetAndResetSentGestureEventCount());
EXPECT_EQ(3U, GestureEventQueueSize());
SimulateGestureScrollUpdateEvent(10, 15, 1);
EXPECT_EQ(0U, GetAndResetSentGestureEventCount());
EXPECT_EQ(3U, GestureEventQueueSize());
SimulateGesturePinchUpdateEvent(4, 60, 60, 1);
EXPECT_EQ(0U, GetAndResetSentGestureEventCount());
EXPECT_EQ(3U, GestureEventQueueSize());
// Using different modifiers should prevent coalescing.
SimulateGesturePinchUpdateEvent(5, 60, 60, 2);
EXPECT_EQ(0U, GetAndResetSentGestureEventCount());
EXPECT_EQ(4U, GestureEventQueueSize());
SimulateGesturePinchUpdateEvent(6, 60, 60, 3);
EXPECT_EQ(0U, GetAndResetSentGestureEventCount());
EXPECT_EQ(5U, GestureEventQueueSize());
SendInputEventACK(WebInputEvent::GestureTapCancel,
INPUT_EVENT_ACK_STATE_CONSUMED);
EXPECT_EQ(2U, GetAndResetSentGestureEventCount());
EXPECT_EQ(4U, GestureEventQueueSize());
SendInputEventACK(WebInputEvent::GestureScrollUpdate,
INPUT_EVENT_ACK_STATE_CONSUMED);
EXPECT_EQ(WebInputEvent::GestureScrollUpdate, last_acked_event().type);
EXPECT_EQ(3U, GestureEventQueueSize());
SendInputEventACK(WebInputEvent::GesturePinchUpdate,
INPUT_EVENT_ACK_STATE_CONSUMED);
EXPECT_EQ(WebInputEvent::GesturePinchUpdate, last_acked_event().type);
EXPECT_EQ(3.f * 4.f, last_acked_event().data.pinchUpdate.scale);
EXPECT_EQ(2U, GestureEventQueueSize());
EXPECT_EQ(1U, GetAndResetSentGestureEventCount());
SendInputEventACK(WebInputEvent::GesturePinchUpdate,
INPUT_EVENT_ACK_STATE_CONSUMED);
EXPECT_EQ(WebInputEvent::GesturePinchUpdate, last_acked_event().type);
EXPECT_EQ(5.f, last_acked_event().data.pinchUpdate.scale);
EXPECT_EQ(1U, GestureEventQueueSize());
EXPECT_EQ(1U, GetAndResetSentGestureEventCount());
SendInputEventACK(WebInputEvent::GesturePinchUpdate,
INPUT_EVENT_ACK_STATE_CONSUMED);
EXPECT_EQ(WebInputEvent::GesturePinchUpdate, last_acked_event().type);
EXPECT_EQ(6.f, last_acked_event().data.pinchUpdate.scale);
EXPECT_EQ(0U, GestureEventQueueSize());
}
TEST_F(GestureEventQueueTest, CoalescesScrollAndPinchEventsIdentity) {
// Insert an event to force queueing of gestures.
SimulateGestureEvent(WebInputEvent::GestureTapCancel,
blink::WebGestureDeviceTouchscreen);
EXPECT_EQ(1U, GetAndResetSentGestureEventCount());
EXPECT_EQ(1U, GestureEventQueueSize());
// Ensure that coalescing yields an identity transform for any pinch/scroll
// pair combined with its inverse.
SimulateGestureScrollUpdateEvent(5, 5, 1);
EXPECT_EQ(0U, GetAndResetSentGestureEventCount());
EXPECT_EQ(2U, GestureEventQueueSize());
SimulateGesturePinchUpdateEvent(5, 10, 10, 1);
EXPECT_EQ(0U, GetAndResetSentGestureEventCount());
EXPECT_EQ(3U, GestureEventQueueSize());
SimulateGesturePinchUpdateEvent(.2f, 10, 10, 1);
EXPECT_EQ(0U, GetAndResetSentGestureEventCount());
EXPECT_EQ(3U, GestureEventQueueSize());
SimulateGestureScrollUpdateEvent(-5, -5, 1);
EXPECT_EQ(0U, GetAndResetSentGestureEventCount());
EXPECT_EQ(3U, GestureEventQueueSize());
SendInputEventACK(WebInputEvent::GestureTapCancel,
INPUT_EVENT_ACK_STATE_CONSUMED);
EXPECT_EQ(2U, GetAndResetSentGestureEventCount());
EXPECT_EQ(2U, GestureEventQueueSize());
SendInputEventACK(WebInputEvent::GestureScrollUpdate,
INPUT_EVENT_ACK_STATE_CONSUMED);
EXPECT_EQ(WebInputEvent::GestureScrollUpdate, last_acked_event().type);
EXPECT_EQ(0.f, last_acked_event().data.scrollUpdate.deltaX);
EXPECT_EQ(0.f, last_acked_event().data.scrollUpdate.deltaY);
SendInputEventACK(WebInputEvent::GesturePinchUpdate,
INPUT_EVENT_ACK_STATE_CONSUMED);
EXPECT_EQ(WebInputEvent::GesturePinchUpdate, last_acked_event().type);
EXPECT_EQ(1.f, last_acked_event().data.pinchUpdate.scale);
EXPECT_EQ(0U, GestureEventQueueSize());
// Insert an event to force queueing of gestures.
SimulateGestureEvent(WebInputEvent::GestureTapCancel,
blink::WebGestureDeviceTouchscreen);
EXPECT_EQ(1U, GetAndResetSentGestureEventCount());
EXPECT_EQ(1U, GestureEventQueueSize());
// Ensure that coalescing yields an identity transform for any pinch/scroll
// pair combined with its inverse.
SimulateGesturePinchUpdateEvent(2, 10, 10, 1);
EXPECT_EQ(0U, GetAndResetSentGestureEventCount());
EXPECT_EQ(2U, GestureEventQueueSize());
SimulateGestureScrollUpdateEvent(20, 20, 1);
EXPECT_EQ(0U, GetAndResetSentGestureEventCount());
EXPECT_EQ(3U, GestureEventQueueSize());
SimulateGesturePinchUpdateEvent(0.5f, 20, 20, 1);
EXPECT_EQ(0U, GetAndResetSentGestureEventCount());
EXPECT_EQ(3U, GestureEventQueueSize());
SimulateGestureScrollUpdateEvent(-5, -5, 1);
EXPECT_EQ(0U, GetAndResetSentGestureEventCount());
EXPECT_EQ(3U, GestureEventQueueSize());
SendInputEventACK(WebInputEvent::GestureTapCancel,
INPUT_EVENT_ACK_STATE_CONSUMED);
EXPECT_EQ(2U, GetAndResetSentGestureEventCount());
EXPECT_EQ(2U, GestureEventQueueSize());
SendInputEventACK(WebInputEvent::GestureScrollUpdate,
INPUT_EVENT_ACK_STATE_CONSUMED);
EXPECT_EQ(WebInputEvent::GestureScrollUpdate, last_acked_event().type);
EXPECT_EQ(0.f, last_acked_event().data.scrollUpdate.deltaX);
EXPECT_EQ(0.f, last_acked_event().data.scrollUpdate.deltaY);
SendInputEventACK(WebInputEvent::GesturePinchUpdate,
INPUT_EVENT_ACK_STATE_CONSUMED);
EXPECT_EQ(WebInputEvent::GesturePinchUpdate, last_acked_event().type);
EXPECT_EQ(1.f, last_acked_event().data.pinchUpdate.scale);
}
// Tests a single event with an synchronous ack.
TEST_F(GestureEventQueueTest, SimpleSyncAck) {
set_synchronous_ack(INPUT_EVENT_ACK_STATE_CONSUMED);
SimulateGestureEvent(WebInputEvent::GestureTapDown,
blink::WebGestureDeviceTouchscreen);
EXPECT_EQ(1U, GetAndResetSentGestureEventCount());
EXPECT_EQ(0U, GestureEventQueueSize());
EXPECT_EQ(1U, GetAndResetAckedGestureEventCount());
}
// Tests an event with an synchronous ack which enqueues an additional event.
TEST_F(GestureEventQueueTest, SyncAckQueuesEvent) {
std::unique_ptr<WebGestureEvent> queued_event;
set_synchronous_ack(INPUT_EVENT_ACK_STATE_CONSUMED);
set_sync_followup_event(WebInputEvent::GestureShowPress,
blink::WebGestureDeviceTouchscreen);
// This event enqueues the show press event.
SimulateGestureEvent(WebInputEvent::GestureTapDown,
blink::WebGestureDeviceTouchscreen);
EXPECT_EQ(2U, GetAndResetSentGestureEventCount());
EXPECT_EQ(1U, GestureEventQueueSize());
EXPECT_EQ(1U, GetAndResetAckedGestureEventCount());
SendInputEventACK(WebInputEvent::GestureShowPress,
INPUT_EVENT_ACK_STATE_CONSUMED);
EXPECT_EQ(0U, GetAndResetSentGestureEventCount());
EXPECT_EQ(0U, GestureEventQueueSize());
EXPECT_EQ(1U, GetAndResetAckedGestureEventCount());
}
// Tests an event with an async ack followed by an event with a sync ack.
TEST_F(GestureEventQueueTest, AsyncThenSyncAck) {
SimulateGestureEvent(WebInputEvent::GestureTapDown,
blink::WebGestureDeviceTouchscreen);
EXPECT_EQ(1U, GetAndResetSentGestureEventCount());
EXPECT_EQ(1U, GestureEventQueueSize());
EXPECT_EQ(0U, GetAndResetAckedGestureEventCount());
SimulateGestureEvent(WebInputEvent::GestureScrollBegin,
blink::WebGestureDeviceTouchscreen);
set_synchronous_ack(INPUT_EVENT_ACK_STATE_CONSUMED);
EXPECT_EQ(0U, GetAndResetSentGestureEventCount());
EXPECT_EQ(2U, GestureEventQueueSize());
EXPECT_EQ(0U, GetAndResetAckedGestureEventCount());
SendInputEventACK(WebInputEvent::GestureTapDown,
INPUT_EVENT_ACK_STATE_CONSUMED);
EXPECT_EQ(1U, GetAndResetSentGestureEventCount());
EXPECT_EQ(0U, GestureEventQueueSize());
EXPECT_EQ(2U, GetAndResetAckedGestureEventCount());
}
TEST_F(GestureEventQueueTest, CoalescesScrollAndPinchEventWithSyncAck) {
// Simulate a pinch sequence.
SimulateGestureEvent(WebInputEvent::GestureScrollBegin,
blink::WebGestureDeviceTouchscreen);
EXPECT_EQ(1U, GetAndResetSentGestureEventCount());
SimulateGestureEvent(WebInputEvent::GesturePinchBegin,
blink::WebGestureDeviceTouchscreen);
EXPECT_EQ(0U, GetAndResetSentGestureEventCount());
SimulateGestureScrollUpdateEvent(8, -4, 1);
// Make sure that the queue contains what we think it should.
WebGestureEvent merged_event = GestureEventLastQueueEvent();
EXPECT_EQ(3U, GestureEventQueueSize());
EXPECT_EQ(WebInputEvent::GestureScrollUpdate, merged_event.type);
// Coalesced without changing event order. Note anchor at (60, 60). Anchoring
// from a point that is not the origin should still give us the right scroll.
SimulateGesturePinchUpdateEvent(1.5, 60, 60, 1);
EXPECT_EQ(4U, GestureEventQueueSize());
SendInputEventACK(WebInputEvent::GestureScrollBegin,
INPUT_EVENT_ACK_STATE_CONSUMED);
EXPECT_EQ(1U, GetAndResetSentGestureEventCount());
EXPECT_EQ(3U, GestureEventQueueSize());
// Ack the PinchBegin, and schedule a synchronous ack for GestureScrollUpdate.
set_synchronous_ack(INPUT_EVENT_ACK_STATE_CONSUMED);
SendInputEventACK(WebInputEvent::GesturePinchBegin,
INPUT_EVENT_ACK_STATE_CONSUMED);
// Both GestureScrollUpdate and GesturePinchUpdate should have been sent.
EXPECT_EQ(WebInputEvent::GestureScrollUpdate, last_acked_event().type);
EXPECT_EQ(1U, GestureEventQueueSize());
EXPECT_EQ(2U, GetAndResetSentGestureEventCount());
// Ack the final GesturePinchUpdate.
SendInputEventACK(WebInputEvent::GesturePinchUpdate,
INPUT_EVENT_ACK_STATE_CONSUMED);
EXPECT_EQ(WebInputEvent::GesturePinchUpdate, last_acked_event().type);
EXPECT_EQ(0U, GestureEventQueueSize());
EXPECT_EQ(0U, GetAndResetSentGestureEventCount());
}
#if GTEST_HAS_PARAM_TEST
TEST_P(GestureEventQueueWithSourceTest, GestureFlingCancelsFiltered) {
WebGestureDevice source_device = GetParam();
// GFC without previous GFS is dropped.
SimulateGestureEvent(WebInputEvent::GestureFlingCancel, source_device);
EXPECT_EQ(0U, GetAndResetSentGestureEventCount());
EXPECT_EQ(0U, GestureEventQueueSize());
// GFC after previous GFS is dispatched and acked.
SimulateGestureFlingStartEvent(0, -10, source_device);
EXPECT_TRUE(FlingInProgress());
SendInputEventACK(WebInputEvent::GestureFlingStart,
INPUT_EVENT_ACK_STATE_CONSUMED);
RunUntilIdle();
EXPECT_EQ(1U, GetAndResetAckedGestureEventCount());
SimulateGestureEvent(WebInputEvent::GestureFlingCancel, source_device);
EXPECT_FALSE(FlingInProgress());
EXPECT_EQ(2U, GetAndResetSentGestureEventCount());
SendInputEventACK(WebInputEvent::GestureFlingCancel,
INPUT_EVENT_ACK_STATE_CONSUMED);
RunUntilIdle();
EXPECT_EQ(1U, GetAndResetAckedGestureEventCount());
EXPECT_EQ(0U, GestureEventQueueSize());
// GFC before previous GFS is acked.
SimulateGestureFlingStartEvent(0, -10, source_device);
EXPECT_TRUE(FlingInProgress());
SimulateGestureEvent(WebInputEvent::GestureFlingCancel, source_device);
EXPECT_FALSE(FlingInProgress());
EXPECT_EQ(1U, GetAndResetSentGestureEventCount());
EXPECT_EQ(2U, GestureEventQueueSize());
// Advance state realistically.
SendInputEventACK(WebInputEvent::GestureFlingStart,
INPUT_EVENT_ACK_STATE_CONSUMED);
RunUntilIdle();
EXPECT_EQ(1U, GetAndResetSentGestureEventCount());
SendInputEventACK(WebInputEvent::GestureFlingCancel,
INPUT_EVENT_ACK_STATE_CONSUMED);
RunUntilIdle();
EXPECT_EQ(2U, GetAndResetAckedGestureEventCount());
EXPECT_EQ(0U, GetAndResetSentGestureEventCount());
EXPECT_EQ(0U, GestureEventQueueSize());
// GFS is added to the queue if another event is pending
SimulateGestureScrollUpdateEvent(8, -7, 0);
SimulateGestureFlingStartEvent(0, -10, source_device);
EXPECT_EQ(2U, GestureEventQueueSize());
EXPECT_EQ(1U, GetAndResetSentGestureEventCount());
WebGestureEvent merged_event = GestureEventLastQueueEvent();
EXPECT_EQ(WebInputEvent::GestureFlingStart, merged_event.type);
EXPECT_TRUE(FlingInProgress());
EXPECT_EQ(2U, GestureEventQueueSize());
// GFS in queue means that a GFC is added to the queue
SimulateGestureEvent(WebInputEvent::GestureFlingCancel, source_device);
merged_event =GestureEventLastQueueEvent();
EXPECT_EQ(WebInputEvent::GestureFlingCancel, merged_event.type);
EXPECT_FALSE(FlingInProgress());
EXPECT_EQ(3U, GestureEventQueueSize());
// Adding a second GFC is dropped.
SimulateGestureEvent(WebInputEvent::GestureFlingCancel, source_device);
EXPECT_FALSE(FlingInProgress());
EXPECT_EQ(3U, GestureEventQueueSize());
// Adding another GFS will add it to the queue.
SimulateGestureFlingStartEvent(0, -10, source_device);
merged_event = GestureEventLastQueueEvent();
EXPECT_EQ(WebInputEvent::GestureFlingStart, merged_event.type);
EXPECT_TRUE(FlingInProgress());
EXPECT_EQ(4U, GestureEventQueueSize());
// GFS in queue means that a GFC is added to the queue
SimulateGestureEvent(WebInputEvent::GestureFlingCancel, source_device);
merged_event = GestureEventLastQueueEvent();
EXPECT_EQ(WebInputEvent::GestureFlingCancel, merged_event.type);
EXPECT_FALSE(FlingInProgress());
EXPECT_EQ(5U, GestureEventQueueSize());
// Adding another GFC with a GFC already there is dropped.
SimulateGestureEvent(WebInputEvent::GestureFlingCancel, source_device);
merged_event = GestureEventLastQueueEvent();
EXPECT_EQ(WebInputEvent::GestureFlingCancel, merged_event.type);
EXPECT_FALSE(FlingInProgress());
EXPECT_EQ(5U, GestureEventQueueSize());
}
INSTANTIATE_TEST_CASE_P(AllSources,
GestureEventQueueWithSourceTest,
testing::Values(blink::WebGestureDeviceTouchscreen,
blink::WebGestureDeviceTouchpad));
#endif // GTEST_HAS_PARAM_TEST
// Test that a GestureScrollEnd | GestureFlingStart are deferred during the
// debounce interval, that Scrolls are not and that the deferred events are
// sent after that timer fires.
TEST_F(GestureEventQueueTest, DebounceDefersFollowingGestureEvents) {
SetUpForDebounce(3);
SimulateGestureEvent(WebInputEvent::GestureScrollUpdate,
blink::WebGestureDeviceTouchscreen);
EXPECT_EQ(1U, GetAndResetSentGestureEventCount());
EXPECT_EQ(1U, GestureEventQueueSize());
EXPECT_EQ(0U, GestureEventDebouncingQueueSize());
EXPECT_TRUE(ScrollingInProgress());
SimulateGestureEvent(WebInputEvent::GestureScrollUpdate,
blink::WebGestureDeviceTouchscreen);
EXPECT_EQ(0U, GetAndResetSentGestureEventCount());
EXPECT_EQ(2U, GestureEventQueueSize());
EXPECT_EQ(0U, GestureEventDebouncingQueueSize());
EXPECT_TRUE(ScrollingInProgress());
SimulateGestureEvent(WebInputEvent::GestureScrollEnd,
blink::WebGestureDeviceTouchscreen);
EXPECT_EQ(0U, GetAndResetSentGestureEventCount());
EXPECT_EQ(2U, GestureEventQueueSize());
EXPECT_EQ(1U, GestureEventDebouncingQueueSize());
SimulateGestureFlingStartEvent(0, 10, blink::WebGestureDeviceTouchscreen);
EXPECT_EQ(0U, GetAndResetSentGestureEventCount());
EXPECT_EQ(2U, GestureEventQueueSize());
EXPECT_EQ(2U, GestureEventDebouncingQueueSize());
SimulateGestureEvent(WebInputEvent::GestureTapDown,
blink::WebGestureDeviceTouchscreen);
EXPECT_EQ(0U, GetAndResetSentGestureEventCount());
EXPECT_EQ(2U, GestureEventQueueSize());
EXPECT_EQ(3U, GestureEventDebouncingQueueSize());
base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
FROM_HERE, base::MessageLoop::QuitWhenIdleClosure(),
TimeDelta::FromMilliseconds(5));
base::MessageLoop::current()->Run();
// The deferred events are correctly queued in coalescing queue.
EXPECT_EQ(0U, GetAndResetSentGestureEventCount());
EXPECT_EQ(5U, GestureEventQueueSize());
EXPECT_EQ(0U, GestureEventDebouncingQueueSize());
EXPECT_FALSE(ScrollingInProgress());
// Verify that the coalescing queue contains the correct events.
WebInputEvent::Type expected[] = {
WebInputEvent::GestureScrollUpdate,
WebInputEvent::GestureScrollUpdate,
WebInputEvent::GestureScrollEnd,
WebInputEvent::GestureFlingStart};
for (unsigned i = 0; i < sizeof(expected) / sizeof(WebInputEvent::Type);
i++) {
WebGestureEvent merged_event = GestureEventQueueEventAt(i);
EXPECT_EQ(expected[i], merged_event.type);
}
}
// Test that non-scroll events are deferred while scrolling during the debounce
// interval and are discarded if a GestureScrollUpdate event arrives before the
// interval end.
TEST_F(GestureEventQueueTest, DebounceDropsDeferredEvents) {
SetUpForDebounce(3);
EXPECT_FALSE(ScrollingInProgress());
SimulateGestureEvent(WebInputEvent::GestureScrollUpdate,
blink::WebGestureDeviceTouchscreen);
EXPECT_EQ(1U, GetAndResetSentGestureEventCount());
EXPECT_EQ(1U, GestureEventQueueSize());
EXPECT_EQ(0U, GestureEventDebouncingQueueSize());
EXPECT_TRUE(ScrollingInProgress());
// This event should get discarded.
SimulateGestureEvent(WebInputEvent::GestureScrollEnd,
blink::WebGestureDeviceTouchscreen);
EXPECT_EQ(0U, GetAndResetSentGestureEventCount());
EXPECT_EQ(1U, GestureEventQueueSize());
EXPECT_EQ(1U, GestureEventDebouncingQueueSize());
SimulateGestureEvent(WebInputEvent::GestureScrollUpdate,
blink::WebGestureDeviceTouchscreen);
EXPECT_EQ(0U, GetAndResetSentGestureEventCount());
EXPECT_EQ(2U, GestureEventQueueSize());
EXPECT_EQ(0U, GestureEventDebouncingQueueSize());
EXPECT_TRUE(ScrollingInProgress());
// Verify that the coalescing queue contains the correct events.
WebInputEvent::Type expected[] = {
WebInputEvent::GestureScrollUpdate,
WebInputEvent::GestureScrollUpdate};
for (unsigned i = 0; i < sizeof(expected) / sizeof(WebInputEvent::Type);
i++) {
WebGestureEvent merged_event = GestureEventQueueEventAt(i);
EXPECT_EQ(expected[i], merged_event.type);
}
}
TEST_F(GestureEventQueueTest, CoalescesSyntheticScrollBeginEndEvents) {
// Test coalescing of only GestureScrollBegin/End events.
SimulateGestureEvent(WebInputEvent::GestureScrollUpdate,
blink::WebGestureDeviceTouchpad);
EXPECT_EQ(1U, GetAndResetSentGestureEventCount());
EXPECT_EQ(1U, GestureEventQueueSize());
WebGestureEvent synthetic_end = SyntheticWebGestureEventBuilder::Build(
WebInputEvent::GestureScrollEnd, blink::WebGestureDeviceTouchpad);
synthetic_end.data.scrollEnd.synthetic = true;
SimulateGestureEvent(synthetic_end);
EXPECT_EQ(0U, GetAndResetSentGestureEventCount());
EXPECT_EQ(2U, GestureEventQueueSize());
// Synthetic begin will remove the unsent synthetic end.
WebGestureEvent synthetic_begin = SyntheticWebGestureEventBuilder::Build(
WebInputEvent::GestureScrollBegin, blink::WebGestureDeviceTouchpad);
synthetic_begin.data.scrollBegin.synthetic = true;
SimulateGestureEvent(synthetic_begin);
EXPECT_EQ(0U, GetAndResetSentGestureEventCount());
EXPECT_EQ(1U, GestureEventQueueSize());
}
} // namespace content
|
#include<iostream>
using namespace std;
int global_scope = 7;
void print_global(){
cout << "Variable global_scope has value: " << global_scope << "\n";
}
int main(){
int global_scope = 17;
cout << "Variable global_scope has value: " << :: global_scope << "\n";
cout << "Variable global_scope has value: " << global_scope << "\n";
print_global();
return 0;
}
|
#include <vtkRenderWindow.h>
#include <vtkRenderWindowInteractor.h>
#include <vtkRenderer.h>
#include <vtkSphereSource.h>
#include <vtkPolyDataMapper.h>
#include <vtkActor.h>
#include <vtkSmartPointer.h>
#include <vtkPointPicker.h>
#include <vtkCamera.h>
#include <vtkInteractorStyleTrackballCamera.h>
#include <vtkNamedColors.h>
namespace
{
// Define interaction style
class MouseInteractorStyleDoubleClick : public vtkInteractorStyleTrackballCamera
{
public:
static MouseInteractorStyleDoubleClick* New();
vtkTypeMacro(MouseInteractorStyleDoubleClick, vtkInteractorStyleTrackballCamera);
MouseInteractorStyleDoubleClick() : NumberOfClicks(0), ResetPixelDistance(5)
{
this->PreviousPosition[0] = 0;
this->PreviousPosition[1] = 0;
}
virtual void OnLeftButtonDown()
{
this->NumberOfClicks++;
int pickPosition[2];
this->GetInteractor()->GetEventPosition(pickPosition);
int xdist = pickPosition[0] - this->PreviousPosition[0];
int ydist = pickPosition[1] - this->PreviousPosition[1];
this->PreviousPosition[0] = pickPosition[0];
this->PreviousPosition[1] = pickPosition[1];
int moveDistance = (int)sqrt((double)(xdist*xdist + ydist*ydist));
// Reset numClicks - If mouse moved further than resetPixelDistance
if(moveDistance > this->ResetPixelDistance)
{
this->NumberOfClicks = 1;
}
if(this->NumberOfClicks == 2)
{
std::cout << "Double clicked." << std::endl;
this->NumberOfClicks = 0;
}
// forward events
vtkInteractorStyleTrackballCamera::OnLeftButtonDown();
}
private:
unsigned int NumberOfClicks;
int PreviousPosition[2];
int ResetPixelDistance;
};
vtkStandardNewMacro(MouseInteractorStyleDoubleClick);
}
int main(int, char *[])
{
vtkSmartPointer<vtkSphereSource> sphereSource =
vtkSmartPointer<vtkSphereSource>::New();
sphereSource->SetCenter(0.0, 0.0, 0.0);
sphereSource->SetRadius(5.0);
sphereSource->Update();
vtkSmartPointer<vtkPolyDataMapper> mapper =
vtkSmartPointer<vtkPolyDataMapper>::New();
mapper->SetInputConnection(sphereSource->GetOutputPort());
vtkSmartPointer<vtkActor> actor =
vtkSmartPointer<vtkActor>::New();
actor->SetMapper(mapper);
vtkSmartPointer<vtkNamedColors> colors =
vtkSmartPointer<vtkNamedColors>::New();
vtkSmartPointer<vtkRenderer> renderer =
vtkSmartPointer<vtkRenderer>::New();
renderer->SetBackground(colors->GetColor3d("Slate_grey").GetData());
renderer->AddActor(actor);
vtkSmartPointer<vtkRenderWindow> renderWindow =
vtkSmartPointer<vtkRenderWindow>::New();
renderWindow->AddRenderer(renderer);
vtkSmartPointer<vtkRenderWindowInteractor> renderWindowInteractor =
vtkSmartPointer<vtkRenderWindowInteractor>::New();
renderWindowInteractor->SetRenderWindow ( renderWindow );
vtkSmartPointer<MouseInteractorStyleDoubleClick> style =
vtkSmartPointer<MouseInteractorStyleDoubleClick>::New();
renderWindowInteractor->SetInteractorStyle( style );
renderWindow->Render();
renderWindowInteractor->Initialize();
renderWindowInteractor->Start();
return EXIT_SUCCESS;
}
|
/**********************************************************************
Audacity: A Digital Audio Editor
SelectionBar.cpp
Copyright 2005 Dominic Mazzoni
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.
*******************************************************************//**
\class SelectionBar
\brief (not quite a Toolbar) at foot of screen for setting and viewing the
selection range.
*//****************************************************************//**
\class SelectionBarListener
\brief A parent class of SelectionBar, used to forward events to do
with changes in the SelectionBar.
*//*******************************************************************/
#include "../Audacity.h"
// For compilers that support precompilation, includes "wx/wx.h".
#include <wx/wxprec.h>
#ifndef WX_PRECOMP
#include <wx/button.h>
#include <wx/checkbox.h>
#include <wx/combobox.h>
#include <wx/intl.h>
#include <wx/radiobut.h>
#include <wx/settings.h>
#include <wx/sizer.h>
#include <wx/valtext.h>
#endif
#include <wx/statline.h>
#include "SelectionBar.h"
#include "../AudacityApp.h"
#include "../AudioIO.h"
#include "../AColor.h"
#include "../Prefs.h"
#include "../widgets/TimeTextCtrl.h"
IMPLEMENT_CLASS(SelectionBar, ToolBar);
const static wxChar *numbers[] =
{
wxT("0"), wxT("1"), wxT("2"), wxT("3"), wxT("4"),
wxT("5"), wxT("6"), wxT("7"), wxT("8"), wxT("9")
};
enum {
SelectionBarFirstID = 2700,
OnRateID,
OnSnapToID,
OnLengthRadioID,
OnEndRadioID,
OnLeftTimeID,
OnRightTimeID
};
BEGIN_EVENT_TABLE(SelectionBar, ToolBar)
EVT_SIZE(SelectionBar::OnSize)
EVT_TEXT(OnLeftTimeID, SelectionBar::OnLeftTime)
EVT_TEXT(OnRightTimeID, SelectionBar::OnRightTime)
EVT_RADIOBUTTON(OnLengthRadioID, SelectionBar::OnLengthRadio)
EVT_RADIOBUTTON(OnEndRadioID, SelectionBar::OnEndRadio)
EVT_CHECKBOX(OnSnapToID, SelectionBar::OnSnapTo)
EVT_COMBOBOX(OnRateID, SelectionBar::OnRate)
EVT_TEXT(OnRateID, SelectionBar::OnRate)
EVT_COMMAND(wxID_ANY, EVT_TIMETEXTCTRL_UPDATED, SelectionBar::OnUpdate)
EVT_COMMAND(wxID_ANY, EVT_CAPTURE_KEY, SelectionBar::OnCaptureKey)
END_EVENT_TABLE()
SelectionBar::SelectionBar()
: ToolBar(SelectionBarID, _("Selection"), wxT("Selection")),
mListener(NULL), mRate(0.0), mStart(0.0), mEnd(0.0), mAudio(0.0),
mLeftTime(NULL), mRightTime(NULL), mAudioTime(NULL)
{
// Make sure we have a valid rate as the TimeTextCtrl()s created in Populate()
// depend on it. Otherwise, division-by-zero floating point exceptions will occur.
// Refer to bug #462 for a scenario where the division-by-zero causes Audacity to fail.
mRate = (double) gPrefs->Read(wxT("/SamplingRate/DefaultProjectSampleRate"), AudioIO::GetOptimalSupportedSampleRate());
}
SelectionBar::~SelectionBar()
{
}
void SelectionBar::Create(wxWindow * parent)
{
ToolBar::Create(parent);
}
void SelectionBar::Populate()
{
// This will be inherited by all children:
SetFont(wxFont(9, wxSWISS, wxNORMAL, wxNORMAL));
wxFlexGridSizer *mainSizer;
wxBoxSizer *hSizer;
/* we don't actually need a control yet, but we want to use it's methods
* to do some look-ups, so we'll have to create one. We can't make the
* look-ups static because they depend on translations which are done at
* runtime */
TimeTextCtrl *ttc = new TimeTextCtrl(this, wxID_ANY, wxT(""), 0.0, mRate);
wxString formatName;
gPrefs->Read(wxT("/SelectionFormat"), &formatName);
wxString format = ttc->GetBuiltinFormat(formatName);
delete ttc;
mainSizer = new wxFlexGridSizer(7, 1, 1);
Add(mainSizer, 0, wxALIGN_CENTER_VERTICAL);
//
// Top row (mostly labels)
//
mainSizer->Add(new wxStaticText(this, -1, _("Project Rate (Hz):"),
// LLL: On my Ubuntu 7.04 install, the label wraps to two lines
// and I could not figure out why. Thus...hackage.
#if defined(__WXGTK__)
wxDefaultPosition, wxSize(110, -1)),
#else
wxDefaultPosition, wxDefaultSize),
#endif
0, wxALIGN_CENTER_VERTICAL | wxRIGHT, 5);
mainSizer->Add(5, 1);
mainSizer->Add(5, 1);
mainSizer->Add(new wxStaticText(this, -1, _("Selection Start:")),
0, wxALIGN_CENTER_VERTICAL | wxRIGHT, 5);
bool showSelectionLength = false;
gPrefs->Read(wxT("/ShowSelectionLength"), &showSelectionLength);
hSizer = new wxBoxSizer(wxHORIZONTAL);
mRightEndButton = new wxRadioButton(this, OnEndRadioID, _("End"),
wxDefaultPosition, wxDefaultSize,
wxRB_GROUP);
mRightEndButton->SetName(_("End"));
mRightEndButton->SetValue(!showSelectionLength);
hSizer->Add(mRightEndButton,
0, wxRIGHT | wxALIGN_CENTER_VERTICAL, 5);
mRightLengthButton = new wxRadioButton(this, OnLengthRadioID, _("Length"));
mRightLengthButton->SetName(_("Length"));
mRightLengthButton->SetValue(showSelectionLength);
hSizer->Add(mRightLengthButton,
0, wxALIGN_CENTER_VERTICAL | wxRIGHT, 5);
#if defined(__WXMSW__)
// Refer to Microsoft KB article 261192 for an explanation as
// to why this is needed. We've only experienced it under Win2k
// so it's probably been fixed. But, it doesn't hurt to have this
// in for all versions.
wxRadioButton* dummyButton =
new wxRadioButton(this, wxID_ANY, _("hidden"),
wxDefaultPosition, wxDefaultSize,
wxRB_GROUP);
dummyButton->Disable();
dummyButton->Hide();
#endif
mainSizer->Add(hSizer, 0, wxALIGN_CENTER_VERTICAL | wxRIGHT, 0);
mainSizer->Add(5, 1);
mainSizer->Add(new wxStaticText(this, -1, _("Audio Position:")),
0, wxALIGN_CENTER_VERTICAL | wxRIGHT, 0);
//
// Middle row (mostly time controls)
//
mRateBox = new wxComboBox(this, OnRateID,
wxT(""),
wxDefaultPosition, wxSize(80, -1));
mRateBox->SetName(_("Project Rate (Hz):"));
wxTextValidator vld(wxFILTER_INCLUDE_CHAR_LIST);
vld.SetIncludes(wxArrayString(10, numbers));
mRateBox->SetValidator(vld);
mRateBox->SetValue(wxString::Format(wxT("%d"), (int)mRate));
UpdateRates(); // Must be done _after_ setting value on mRateBox!
// We need to capture the SetFocus and KillFocus events to set up
// for keyboard capture. On Windows and GTK it's easy since the
// combobox is presented as one control to hook into.
mRateText = mRateBox;
#if defined(__WXMAC__)
// The Mac uses a standard wxTextCtrl for the edit portion and that's
// the control that gets the focus events. So we have to find the
// textctrl.
wxWindowList kids = mRateBox->GetChildren();
for (unsigned int i = 0; i < kids.GetCount(); i++) {
wxClassInfo *ci = kids[i]->GetClassInfo();
if (ci->IsKindOf(CLASSINFO(wxTextCtrl))) {
mRateText = kids[i];
break;
}
}
#endif
mRateText->Connect(wxEVT_SET_FOCUS,
wxFocusEventHandler(SelectionBar::OnFocus),
NULL,
this);
mRateText->Connect(wxEVT_KILL_FOCUS,
wxFocusEventHandler(SelectionBar::OnFocus),
NULL,
this);
mainSizer->Add(mRateBox, 0, wxALIGN_CENTER_VERTICAL | wxRIGHT, 5);
mainSizer->Add(new wxStaticLine(this, -1, wxDefaultPosition,
wxSize(1, toolbarSingle),
wxLI_VERTICAL),
0, wxRIGHT, 5);
mSnapTo = new wxCheckBox(this, OnSnapToID, _("Snap To"),
wxDefaultPosition, wxDefaultSize,
wxALIGN_RIGHT);
mainSizer->Add(mSnapTo,
0, wxALIGN_CENTER_VERTICAL | wxALIGN_CENTER | wxRIGHT, 5);
mSnapTo->SetName(_("Snap To"));
mSnapTo->SetValue(gPrefs->Read(wxT("/SnapTo"), 0L)!=0);
mSnapTo->Connect(wxEVT_SET_FOCUS,
wxFocusEventHandler(SelectionBar::OnFocus),
NULL,
this);
mSnapTo->Connect(wxEVT_KILL_FOCUS,
wxFocusEventHandler(SelectionBar::OnFocus),
NULL,
this);
mLeftTime = new TimeTextCtrl(this, OnLeftTimeID, wxT(""), 0.0, mRate);
mLeftTime->SetFormatString(format);
mLeftTime->SetName(_("Selection Start:"));
mLeftTime->EnableMenu();
mainSizer->Add(mLeftTime, 0, wxALIGN_CENTER_VERTICAL | wxRIGHT, 5);
mRightTime = new TimeTextCtrl(this, OnRightTimeID, format, 0.0, mRate);
mRightTime->SetName(wxString(_("Selection ")) + (showSelectionLength ?
_("Length") :
_("End")));
mRightTime->EnableMenu();
mainSizer->Add(mRightTime, 0, wxALIGN_CENTER_VERTICAL | wxRIGHT, 5);
mainSizer->Add(new wxStaticLine(this, -1, wxDefaultPosition,
wxSize(1, toolbarSingle),
wxLI_VERTICAL),
0, wxRIGHT, 5);
mAudioTime = new TimeTextCtrl(this, -1, format, 0.0, mRate);
mAudioTime->SetName(_("Audio Position:"));
mAudioTime->EnableMenu();
mainSizer->Add(mAudioTime, 0, wxALIGN_CENTER_VERTICAL | wxRIGHT, 0);
mainSizer->Layout();
Layout();
SetMinSize( GetSizer()->GetMinSize() );
}
void SelectionBar::UpdatePrefs()
{
mRate = (double) gPrefs->Read(wxT("/SamplingRate/DefaultProjectSampleRate"), AudioIO::GetOptimalSupportedSampleRate());
wxCommandEvent e;
e.SetInt(mLeftTime->GetFormatIndex());
OnUpdate(e);
// Set label to pull in language change
SetLabel(_("Selection"));
// Give base class a chance
ToolBar::UpdatePrefs();
}
void SelectionBar::SetListener(SelectionBarListener *l)
{
mListener = l;
};
void SelectionBar::OnSize(wxSizeEvent &evt)
{
Refresh( true );
evt.Skip();
}
void SelectionBar::ModifySelection()
{
mStart = mLeftTime->GetTimeValue();
double right = mRightTime->GetTimeValue();
if (mRightEndButton->GetValue()) {
if(mStart > right)
mEnd = mStart;
else
mEnd = right;
}
else
mEnd = mStart + right;
mListener->AS_ModifySelection(mStart, mEnd);
}
void SelectionBar::OnLeftTime(wxCommandEvent &evt)
{
ModifySelection();
}
void SelectionBar::OnRightTime(wxCommandEvent &evt)
{
ModifySelection();
}
void SelectionBar::OnLengthRadio(wxCommandEvent &evt)
{
gPrefs->Write(wxT("/ShowSelectionLength"), true);
mRightTime->SetName(wxString(_("Selection Length")));
ValuesToControls();
}
void SelectionBar::OnEndRadio(wxCommandEvent &evt)
{
gPrefs->Write(wxT("/ShowSelectionLength"), false);
mRightTime->SetName(wxString(_("Selection End")));
ValuesToControls();
}
void SelectionBar::OnUpdate(wxCommandEvent &evt)
{
int index = evt.GetInt();
wxWindow *w = FindFocus();
bool leftFocus = (w == mLeftTime);
bool rightFocus = (w == mRightTime);
bool audioFocus = (w == mAudioTime);
evt.Skip(false);
/* we don't actually need a TimeTextCtrl, but need it's
* translations which are done at runtime */
TimeTextCtrl *ttc = new TimeTextCtrl(this, wxID_ANY, wxT(""), 0.0, mRate);
wxString formatName(ttc->GetBuiltinName(index));
gPrefs->Write(wxT("/SelectionFormat"), formatName);
delete ttc;
// ToolBar::ReCreateButtons() will get rid of our sizers and controls
// so reset pointers first.
mLeftTime =
mRightTime =
mAudioTime = NULL;
mRightEndButton =
mRightLengthButton = NULL;
mRateBox = NULL;
mRateText = NULL;
ToolBar::ReCreateButtons();
ValuesToControls();
wxString formatString = mLeftTime->GetBuiltinFormat(index);
mLeftTime->SetFormatString(formatString);
mRightTime->SetFormatString(formatString);
mAudioTime->SetFormatString(formatString);
if (leftFocus) {
mLeftTime->SetFocus();
}
else if (rightFocus) {
mRightTime->SetFocus();
}
else if (audioFocus) {
mAudioTime->SetFocus();
}
Updated();
}
void SelectionBar::ValuesToControls()
{
mLeftTime->SetTimeValue(mStart);
if (mRightEndButton->GetValue())
mRightTime->SetTimeValue(mEnd);
else
{ // mRightTime is the length.
// Be sure to take into account the sub-sample offset.
// See TimeToLongSamples and LongSamplesToTime but here at the project rate.
double t = (sampleCount)floor(mEnd * mRate + 0.5);
t -= (sampleCount)floor(mStart * mRate + 0.5);
t /= mRate;
mRightTime->SetTimeValue(t);
}
mAudioTime->SetTimeValue(mAudio);
}
void SelectionBar::SetTimes(double start, double end, double audio)
{
mStart = start;
mEnd = end;
mAudio = audio;
ValuesToControls();
}
double SelectionBar::GetLeftTime()
{
return mLeftTime->GetTimeValue();
}
double SelectionBar::GetRightTime()
{
if (mRightEndButton->GetValue())
return mRightTime->GetTimeValue();
else {
// What would be shown if we were showing the end time
TimeTextCtrl ttc(this, wxID_ANY, wxT(""), 0.0, mRate);
ttc.SetFormatString(mRightTime->GetFormatString());
ttc.SetSampleRate(mRate);
ttc.SetTimeValue(mEnd);
return ttc.GetTimeValue();
}
}
void SelectionBar::SetField(const wxChar *msg, int fieldNum)
{
if (fieldNum < 0 || fieldNum >= 10)
return;
if (mField[fieldNum] != msg) {
mField[fieldNum] = msg;
Refresh(false);
}
}
void SelectionBar::SetSnapTo(bool state)
{
mSnapTo->SetValue(state);
}
void SelectionBar::SetRate(double rate)
{
if (rate != mRate) {
// if the rate is actually being changed
mRate = rate; // update the stored rate
mRateBox->SetValue(wxString::Format(wxT("%d"), (int)rate));
// update the TimeTextCtrls if they exist
if (mLeftTime) mLeftTime->SetSampleRate(rate);
if (mRightTime) mRightTime->SetSampleRate(rate);
if (mAudioTime) mAudioTime->SetSampleRate(rate);
}
}
void SelectionBar::OnRate(wxCommandEvent &evt)
{
if (mRateBox->GetValue().ToDouble(&mRate) && // is a numeric value
(mRate != 0.0))
{
if (mLeftTime) mLeftTime->SetSampleRate(mRate);
if (mRightTime) mRightTime->SetSampleRate(mRate);
if (mAudioTime) mAudioTime->SetSampleRate(mRate);
if (mListener) mListener->AS_SetRate(mRate);
}
}
void SelectionBar::UpdateRates()
{
wxString oldValue = mRateBox->GetValue();
mRateBox->Clear();
for (int i = 0; i < AudioIO::NumStandardRates; i++) {
mRateBox->Append(wxString::Format(wxT("%d"), AudioIO::StandardRates[i]));
}
mRateBox->SetValue(oldValue);
}
void SelectionBar::OnFocus(wxFocusEvent &event)
{
wxCommandEvent e(EVT_CAPTURE_KEYBOARD);
if (event.GetEventType() == wxEVT_KILL_FOCUS) {
e.SetEventType(EVT_RELEASE_KEYBOARD);
}
e.SetEventObject(this);
GetParent()->GetEventHandler()->ProcessEvent(e);
Refresh(false);
event.Skip();
}
void SelectionBar::OnCaptureKey(wxCommandEvent &event)
{
wxKeyEvent *kevent = (wxKeyEvent *)event.GetEventObject();
wxWindow *w = FindFocus();
int keyCode = kevent->GetKeyCode();
// Pass the SPACE through for SnapTo
if (w == mSnapTo && keyCode == WXK_SPACE) {
return;
}
// Convert numeric keypad entries.
if ((keyCode >= WXK_NUMPAD0) && (keyCode <= WXK_NUMPAD9)) {
keyCode -= WXK_NUMPAD0 - '0';
}
if (keyCode >= '0' && keyCode <= '9') {
return;
}
// UP/DOWN/LEFT/RIGHT for mRateText
if (w == mRateText) {
switch (keyCode)
{
case WXK_LEFT:
case WXK_RIGHT:
case WXK_UP:
case WXK_DOWN:
case WXK_DELETE:
case WXK_BACK:
return;
}
}
event.Skip();
return;
}
void SelectionBar::OnSnapTo(wxCommandEvent & event)
{
mListener->AS_SetSnapTo(mSnapTo->GetValue());
return;
}
// Indentation settings for Vim and Emacs and unique identifier for Arch, a
// version control system. Please do not modify past this point.
//
// Local Variables:
// c-basic-offset: 3
// indent-tabs-mode: nil
// End:
//
// vim: et sts=3 sw=3
// arch-tag: 147df354-77ae-4620-a8e1-9598a695548b
|
/*
* Distributed under the OSI-approved Apache License, Version 2.0. See
* accompanying file Copyright.txt for details.
*
* BP4Reader.cpp
*
* Created on: Aug 1, 2018
* Author: Lipeng Wan wanl@ornl.gov
*/
#include "BP4Reader.h"
#include "BP4Reader.tcc"
#include "adios2/toolkit/profiling/taustubs/tautimer.hpp"
#include <chrono>
#include <errno.h>
namespace adios2
{
namespace core
{
namespace engine
{
BP4Reader::BP4Reader(IO &io, const std::string &name, const Mode mode,
helper::Comm comm)
: Engine("BP4Reader", io, name, mode, std::move(comm)),
m_BP4Deserializer(m_Comm), m_MDFileManager(m_Comm), m_DataFileManager(m_Comm),
m_MDIndexFileManager(m_Comm)
{
TAU_SCOPED_TIMER("BP4Reader::Open");
Init();
}
StepStatus BP4Reader::BeginStep(StepMode mode, const float timeoutSeconds)
{
TAU_SCOPED_TIMER("BP4Reader::BeginStep");
if (mode != StepMode::Read)
{
throw std::invalid_argument("ERROR: mode is not supported yet, "
"only Read is valid for "
"engine BP4Reader, in call to "
"BeginStep\n");
}
if (!m_BP4Deserializer.m_DeferredVariables.empty())
{
throw std::invalid_argument(
"ERROR: existing variables subscribed with "
"GetDeferred, did you forget to call "
"PerformGets() or EndStep()?, in call to BeginStep\n");
}
// used to inquire for variables in streaming mode
m_IO.m_ReadStreaming = true;
StepStatus status = StepStatus::OK;
if (m_FirstStep)
{
if (m_BP4Deserializer.m_MetadataSet.StepsCount == 0)
{
status = CheckForNewSteps(Seconds(timeoutSeconds));
}
}
else
{
if (m_CurrentStep + 1 >= m_BP4Deserializer.m_MetadataSet.StepsCount)
{
status = CheckForNewSteps(Seconds(timeoutSeconds));
}
}
// This should be after getting new steps
if (status == StepStatus::OK)
{
if (m_FirstStep)
{
m_FirstStep = false;
}
else
{
++m_CurrentStep;
}
m_IO.m_EngineStep = m_CurrentStep;
m_IO.ResetVariablesStepSelection(false,
"in call to BP4 Reader BeginStep");
// caches attributes for each step
// if a variable name is a prefix
// e.g. var prefix = {var/v1, var/v2, var/v3}
m_IO.SetPrefixedNames(true);
}
return status;
}
size_t BP4Reader::CurrentStep() const { return m_CurrentStep; }
void BP4Reader::EndStep()
{
TAU_SCOPED_TIMER("BP4Reader::EndStep");
PerformGets();
}
void BP4Reader::PerformGets()
{
TAU_SCOPED_TIMER("BP4Reader::PerformGets");
if (m_BP4Deserializer.m_DeferredVariables.empty())
{
return;
}
for (const std::string &name : m_BP4Deserializer.m_DeferredVariables)
{
const std::string type = m_IO.InquireVariableType(name);
if (type == "compound")
{
}
#define declare_type(T) \
else if (type == helper::GetType<T>()) \
{ \
Variable<T> &variable = \
FindVariable<T>(name, "in call to PerformGets, EndStep or Close"); \
for (auto &blockInfo : variable.m_BlocksInfo) \
{ \
m_BP4Deserializer.SetVariableBlockInfo(variable, blockInfo); \
} \
ReadVariableBlocks(variable); \
variable.m_BlocksInfo.clear(); \
}
ADIOS2_FOREACH_STDTYPE_1ARG(declare_type)
#undef declare_type
}
m_BP4Deserializer.m_DeferredVariables.clear();
}
// PRIVATE
void BP4Reader::Init()
{
if (m_OpenMode != Mode::Read)
{
throw std::invalid_argument("ERROR: BPFileReader only "
"supports OpenMode::Read from" +
m_Name + " " + m_EndMessage);
}
m_BP4Deserializer.Init(m_IO.m_Parameters, "in call to BP4::Open to write");
InitTransports();
/* Do a collective wait for the file(s) to appear within timeout.
Make sure every process comes to the same conclusion */
const Seconds timeoutSeconds =
Seconds(m_BP4Deserializer.m_Parameters.OpenTimeoutSecs);
// set poll to 1/100 of timeout
Seconds pollSeconds = timeoutSeconds / 100.0;
static const auto pollSecondsMin = Seconds(1.0);
if (pollSeconds < pollSecondsMin)
{
pollSeconds = pollSecondsMin;
}
static const auto pollSecondsMax = Seconds(10.0);
if (pollSeconds > pollSecondsMax)
{
pollSeconds = pollSecondsMax;
}
const TimePoint timeoutInstant =
std::chrono::steady_clock::now() + timeoutSeconds;
OpenFiles(timeoutInstant, pollSeconds, timeoutSeconds);
InitBuffer(timeoutInstant, pollSeconds / 10, timeoutSeconds);
}
void BP4Reader::OpenFiles(const TimePoint &timeoutInstant,
const Seconds &pollSeconds,
const Seconds &timeoutSeconds)
{
/* Poll */
size_t flag = 1; // 0 = OK, opened file, 1 = timeout, 2 = error
std::string lasterrmsg;
if (m_BP4Deserializer.m_RankMPI == 0)
{
do
{
try
{
errno = 0;
const bool profile = m_BP4Deserializer.m_Profiler.m_IsActive;
/* Open the metadata index table */
const std::string metadataIndexFile(
m_BP4Deserializer.GetBPMetadataIndexFileName(m_Name));
m_MDIndexFileManager.OpenFiles(
{metadataIndexFile}, adios2::Mode::Read,
m_IO.m_TransportsParameters, profile);
/* Open the metadata file */
const std::string metadataFile(
m_BP4Deserializer.GetBPMetadataFileName(m_Name));
m_MDFileManager.OpenFiles({metadataFile}, adios2::Mode::Read,
m_IO.m_TransportsParameters, profile);
flag = 0; // found file
break;
}
catch (std::ios_base::failure &e)
{
lasterrmsg = std::string(e.what());
if (errno == ENOENT)
{
flag = 1; // timeout
}
else
{
flag = 2; // fatal error
break;
}
}
std::this_thread::sleep_for(pollSeconds);
} while (std::chrono::steady_clock::now() < timeoutInstant);
}
flag = m_Comm.BroadcastValue(flag, 0);
if (flag == 2)
{
if (m_BP4Deserializer.m_RankMPI == 0 && !lasterrmsg.empty())
{
throw std::ios_base::failure("ERROR: File " + m_Name +
" cannot be opened: " + lasterrmsg);
}
else
{
throw std::ios_base::failure("File " + m_Name +
" cannot be opened");
}
}
else if (flag == 1)
{
if (m_BP4Deserializer.m_RankMPI == 0)
{
throw std::ios_base::failure(
"ERROR: File " + m_Name +
" could not be found within timeout: " + lasterrmsg);
}
else
{
throw std::ios_base::failure("ERROR: File " + m_Name +
" could not be found within timeout");
}
}
/* At this point we may have an empty index table.
* The writer has created the file but no content may have been stored yet.
* We need to wait within the timeout for the index header to arrive (from
* writer's open), so that we don't need to deal with the header later.
* Zero or more actual steps in the output is fine.
* Header size = 64 bytes, each record is 64 bytes
*/
flag = 1; // timeout
if (m_BP4Deserializer.m_RankMPI == 0)
{
do
{
const size_t idxFileSize = m_MDIndexFileManager.GetFileSize(0);
if (idxFileSize > 63)
{
flag = 0; // we have at least the header
break;
}
std::this_thread::sleep_for(pollSeconds);
} while (std::chrono::steady_clock::now() < timeoutInstant);
}
flag = m_Comm.BroadcastValue(flag, 0);
if (flag == 1)
{
throw std::ios_base::failure(
"ERROR: File " + m_Name +
" was found but has not contained data within "
"the specified timeout of " +
std::to_string(timeoutSeconds.count()) + " seconds.");
}
}
void BP4Reader::InitTransports()
{
if (m_IO.m_TransportsParameters.empty())
{
Params defaultTransportParameters;
defaultTransportParameters["transport"] = "File";
m_IO.m_TransportsParameters.push_back(defaultTransportParameters);
}
}
uint64_t
MetadataExpectedMinFileSize(const format::BP4Deserializer &m_BP4Deserializer,
const std::string &IdxFileName, bool hasHeader)
{
size_t idxsize = m_BP4Deserializer.m_MetadataIndex.m_Buffer.size();
if (idxsize % 64 != 0)
{
throw std::runtime_error(
"FATAL CODING ERROR: ADIOS Index file " + IdxFileName +
" is assumed to always contain n*64 byte-length records. "
"The file size now is " +
std::to_string(idxsize) + " bytes.");
}
if ((hasHeader && idxsize < 128) || idxsize < 64)
{
// no (new) step entry in the index, so no metadata is expected
return 0;
}
uint64_t lastpos = *(uint64_t *)&(
m_BP4Deserializer.m_MetadataIndex.m_Buffer[idxsize - 24]);
return lastpos;
}
void BP4Reader::InitBuffer(const TimePoint &timeoutInstant,
const Seconds &pollSeconds,
const Seconds &timeoutSeconds)
{
// Put all metadata in buffer
if (m_BP4Deserializer.m_RankMPI == 0)
{
/* Read metadata index table into memory */
const size_t metadataIndexFileSize =
m_MDIndexFileManager.GetFileSize(0);
m_BP4Deserializer.m_MetadataIndex.Resize(
metadataIndexFileSize, "allocating metadata index buffer, "
"in call to BPFileReader Open");
m_MDIndexFileManager.ReadFile(
m_BP4Deserializer.m_MetadataIndex.m_Buffer.data(),
metadataIndexFileSize);
/* Read metadata file into memory but first make sure
* it has the content that the index table refers to */
uint64_t expectedMinFileSize =
MetadataExpectedMinFileSize(m_BP4Deserializer, m_Name, true);
size_t fileSize = 0;
do
{
fileSize = m_MDFileManager.GetFileSize(0);
if (fileSize >= expectedMinFileSize)
{
break;
}
std::this_thread::sleep_for(pollSeconds);
} while (std::chrono::steady_clock::now() < timeoutInstant);
if (fileSize >= expectedMinFileSize)
{
m_BP4Deserializer.m_Metadata.Resize(
fileSize,
"allocating metadata buffer, in call to BP4Reader Open");
m_MDFileManager.ReadFile(
m_BP4Deserializer.m_Metadata.m_Buffer.data(), fileSize);
m_MDIndexFileProcessedSize = metadataIndexFileSize;
}
else
{
throw std::ios_base::failure(
"ERROR: File " + m_Name +
" was found with an index file but md.0 "
"has not contained enough data within "
"the specified timeout of " +
std::to_string(timeoutSeconds.count()) + " seconds.");
}
}
// broadcast buffer to all ranks from zero
m_Comm.BroadcastVector(m_BP4Deserializer.m_Metadata.m_Buffer);
// broadcast metadata index buffer to all ranks from zero
m_Comm.BroadcastVector(m_BP4Deserializer.m_MetadataIndex.m_Buffer);
/* Parse metadata index table */
m_BP4Deserializer.ParseMetadataIndex(m_BP4Deserializer.m_MetadataIndex);
// fills IO with Variables and Attributes
m_MDFileProcessedSize =
m_BP4Deserializer.ParseMetadata(m_BP4Deserializer.m_Metadata, *this);
/* m_MDFileProcessedSize is the position in the buffer where processing
* ends. The processing is controlled by the number of records in the Index,
* which may be less than the actual entries in the metadata in a streaming
* situation (where writer has just written metadata for step
* K+1,...,K+L while the index contains K steps when the reader looks at
* it).
*
* In ProcessMetadataForNewSteps(), we will re-read the metadata which
* is in the buffer but has not been processed yet.
*/
}
size_t BP4Reader::UpdateBuffer(const TimePoint &timeoutInstant,
const Seconds &pollSeconds)
{
std::vector<size_t> sizes(2, 0);
if (m_BP4Deserializer.m_RankMPI == 0)
{
const size_t idxFileSize = m_MDIndexFileManager.GetFileSize(0);
if (idxFileSize > m_MDIndexFileProcessedSize)
{
const size_t newIdxSize = idxFileSize - m_MDIndexFileProcessedSize;
if (m_BP4Deserializer.m_MetadataIndex.m_Buffer.size() < newIdxSize)
{
m_BP4Deserializer.m_MetadataIndex.Resize(
newIdxSize, "re-allocating metadata index buffer, in "
"call to BP4Reader::BeginStep/UpdateBuffer");
}
m_BP4Deserializer.m_MetadataIndex.m_Position = 0;
m_MDIndexFileManager.ReadFile(
m_BP4Deserializer.m_MetadataIndex.m_Buffer.data(), newIdxSize,
m_MDIndexFileProcessedSize);
/* Wait until as much metadata arrives in the file as much
* is indicated by the existing index entries
*/
uint64_t expectedMinFileSize =
MetadataExpectedMinFileSize(m_BP4Deserializer, m_Name, false);
size_t fileSize = 0;
do
{
fileSize = m_MDFileManager.GetFileSize(0);
if (fileSize >= expectedMinFileSize)
{
break;
}
std::this_thread::sleep_for(pollSeconds);
} while (std::chrono::steady_clock::now() < timeoutInstant);
if (fileSize >= expectedMinFileSize)
{
/* Read corresponding new metadata (throwing away the old)
* There may be unprocessed entries in the metadata if the index
* had less steps than the metadata file at the last read.
* Those steps are read again here, starting in the beginning of
* the buffer now.
*/
const size_t fileSize = m_MDFileManager.GetFileSize(0);
const size_t newMDSize = fileSize - m_MDFileProcessedSize;
if (m_BP4Deserializer.m_Metadata.m_Buffer.size() < newMDSize)
{
m_BP4Deserializer.m_Metadata.Resize(
newMDSize, "allocating metadata buffer, in call to "
"BP4Reader Open");
}
m_BP4Deserializer.m_Metadata.m_Position = 0;
m_MDFileManager.ReadFile(
m_BP4Deserializer.m_Metadata.m_Buffer.data(), newMDSize,
m_MDFileProcessedSize);
sizes[0] = newIdxSize;
sizes[1] = m_MDFileProcessedSize;
}
}
}
m_Comm.BroadcastVector(sizes, 0);
size_t newIdxSize = sizes[0];
if (newIdxSize > 0)
{
// broadcast buffer to all ranks from zero
m_Comm.BroadcastVector(m_BP4Deserializer.m_Metadata.m_Buffer);
// broadcast metadata index buffer to all ranks from zero
m_Comm.BroadcastVector(m_BP4Deserializer.m_MetadataIndex.m_Buffer);
if (m_BP4Deserializer.m_RankMPI != 0)
{
m_MDFileProcessedSize = sizes[1];
// we need this pointer in Metadata buffer on all processes
// for parsing it correctly in ProcessMetadataForNewSteps()
}
}
return newIdxSize;
}
void BP4Reader::ProcessMetadataForNewSteps(const size_t newIdxSize)
{
/* Remove all existing variables from previous steps
It seems easier than trying to update them */
m_IO.RemoveAllVariables();
/* Parse metadata index table (without header) */
/* We need to skew the index table pointers with the
size of the already-processed metadata because the memory buffer of
new metadata starts from 0 */
m_BP4Deserializer.ParseMetadataIndex(m_BP4Deserializer.m_MetadataIndex,
m_MDFileProcessedSize, false);
// fills IO with Variables and Attributes (not first step)
const size_t newProcessedMDSize = m_BP4Deserializer.ParseMetadata(
m_BP4Deserializer.m_Metadata, *this, false);
// remember current end position in metadata and index table for next round
m_MDFileProcessedSize += newProcessedMDSize;
if (m_BP4Deserializer.m_RankMPI == 0)
{
m_MDIndexFileProcessedSize += newIdxSize;
}
size_t idxsize = m_BP4Deserializer.m_MetadataIndex.m_Buffer.size();
uint64_t lastpos = *(uint64_t *)&(
m_BP4Deserializer.m_MetadataIndex.m_Buffer[idxsize - 24]);
}
bool BP4Reader::CheckWriterActive()
{
size_t flag = 0;
if (m_BP4Deserializer.m_RankMPI == 0)
{
std::vector<char> header(64, '\0');
m_MDIndexFileManager.ReadFile(header.data(), 64, 0, 0);
bool active = m_BP4Deserializer.ReadActiveFlag(header);
flag = (active ? 1 : 0);
}
flag = m_BP4Deserializer.m_Comm.BroadcastValue(flag, 0);
m_BP4Deserializer.m_WriterIsActive = (flag > 0);
return m_BP4Deserializer.m_WriterIsActive;
}
StepStatus BP4Reader::CheckForNewSteps(Seconds timeoutSeconds)
{
/* Do a collective wait for a step within timeout.
Make sure every reader comes to the same conclusion */
StepStatus retval = StepStatus::OK;
bool haveNewStep = false;
if (timeoutSeconds < Seconds::zero())
{
timeoutSeconds = Seconds(999999999); // max 1 billion seconds wait
}
const TimePoint timeoutInstant =
std::chrono::steady_clock::now() + timeoutSeconds;
auto pollSeconds =
Seconds(m_BP4Deserializer.m_Parameters.BeginStepPollingFrequencySecs);
if (pollSeconds > timeoutSeconds)
{
pollSeconds = timeoutSeconds;
}
/* Poll */
// Hack: processing metadata for multiple new steps only works
// when pretending not to be in streaming mode
const bool saveReadStreaming = m_IO.m_ReadStreaming;
m_IO.m_ReadStreaming = false;
while (m_BP4Deserializer.m_WriterIsActive)
{
size_t newIdxSize = UpdateBuffer(timeoutInstant, pollSeconds / 10);
if (newIdxSize > 0)
{
haveNewStep = true;
/* we have new metadata in memory. Need to parse it now */
ProcessMetadataForNewSteps(newIdxSize);
break;
}
if (!CheckWriterActive())
{
break;
}
std::this_thread::sleep_for(pollSeconds);
if (std::chrono::steady_clock::now() >= timeoutInstant)
{
break;
}
}
if (!haveNewStep)
{
m_IO.m_ReadStreaming = false;
if (m_BP4Deserializer.m_WriterIsActive)
{
retval = StepStatus::NotReady;
}
else
{
retval = StepStatus::EndOfStream;
}
}
else
{
retval = StepStatus::OK;
}
m_IO.m_ReadStreaming = saveReadStreaming;
return retval;
}
#define declare_type(T) \
void BP4Reader::DoGetSync(Variable<T> &variable, T *data) \
{ \
TAU_SCOPED_TIMER("BP4Reader::Get"); \
GetSyncCommon(variable, data); \
} \
void BP4Reader::DoGetDeferred(Variable<T> &variable, T *data) \
{ \
TAU_SCOPED_TIMER("BP4Reader::Get"); \
GetDeferredCommon(variable, data); \
}
ADIOS2_FOREACH_STDTYPE_1ARG(declare_type)
#undef declare_type
void BP4Reader::DoClose(const int transportIndex)
{
TAU_SCOPED_TIMER("BP4Reader::Close");
PerformGets();
m_DataFileManager.CloseFiles();
m_MDFileManager.CloseFiles();
}
#define declare_type(T) \
std::map<size_t, std::vector<typename Variable<T>::Info>> \
BP4Reader::DoAllStepsBlocksInfo(const Variable<T> &variable) const \
{ \
TAU_SCOPED_TIMER("BP4Reader::AllStepsBlocksInfo"); \
return m_BP4Deserializer.AllStepsBlocksInfo(variable); \
} \
\
std::vector<std::vector<typename Variable<T>::Info>> \
BP4Reader::DoAllRelativeStepsBlocksInfo(const Variable<T> &variable) const \
{ \
TAU_SCOPED_TIMER("BP3Reader::AllRelativeStepsBlocksInfo"); \
return m_BP4Deserializer.AllRelativeStepsBlocksInfo(variable); \
} \
\
std::vector<typename Variable<T>::Info> BP4Reader::DoBlocksInfo( \
const Variable<T> &variable, const size_t step) const \
{ \
TAU_SCOPED_TIMER("BP4Reader::BlocksInfo"); \
return m_BP4Deserializer.BlocksInfo(variable, step); \
}
ADIOS2_FOREACH_STDTYPE_1ARG(declare_type)
#undef declare_type
size_t BP4Reader::DoSteps() const
{
return m_BP4Deserializer.m_MetadataSet.StepsCount;
}
} // end namespace engine
} // end namespace core
} // end namespace adios2
|
/*
* Copyright (C) 2010 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#if ENABLE(FULLSCREEN_API)
#include "InjectedBundlePageFullScreenClient.h"
#include "InjectedBundleNodeHandle.h"
#include "WKAPICast.h"
#include "WKBundleAPICast.h"
#include "WKSharedAPICast.h"
#include "WebCoreArgumentCoders.h"
#include "WebFullScreenManagerProxyMessages.h"
#include "WebPage.h"
#include <WebCore/Element.h>
namespace WebKit {
using namespace WebCore;
bool InjectedBundlePageFullScreenClient::supportsFullScreen(WebPage *page, bool withKeyboard)
{
if (m_client.supportsFullScreen)
return m_client.supportsFullScreen(toAPI(page), withKeyboard);
bool supports = true;
page->sendSync(Messages::WebFullScreenManagerProxy::SupportsFullScreen(withKeyboard), Messages::WebFullScreenManagerProxy::SupportsFullScreen::Reply(supports));
return supports;
}
void InjectedBundlePageFullScreenClient::enterFullScreenForElement(WebPage *page, WebCore::Element *element)
{
if (m_client.enterFullScreenForElement) {
RefPtr<InjectedBundleNodeHandle> nodeHandle = InjectedBundleNodeHandle::getOrCreate(element);
m_client.enterFullScreenForElement(toAPI(page), toAPI(nodeHandle.get()));
} else
page->send(Messages::WebFullScreenManagerProxy::EnterFullScreen());
}
void InjectedBundlePageFullScreenClient::exitFullScreenForElement(WebPage *page, WebCore::Element *element)
{
if (m_client.exitFullScreenForElement) {
RefPtr<InjectedBundleNodeHandle> nodeHandle = InjectedBundleNodeHandle::getOrCreate(element);
m_client.exitFullScreenForElement(toAPI(page), toAPI(nodeHandle.get()));
} else
page->send(Messages::WebFullScreenManagerProxy::ExitFullScreen());
}
void InjectedBundlePageFullScreenClient::beganEnterFullScreen(WebPage *page, IntRect& initialFrame, IntRect& finalFrame)
{
if (m_client.beganEnterFullScreen)
m_client.beganEnterFullScreen(toAPI(page), toAPI(initialFrame), toAPI(finalFrame));
else
page->send(Messages::WebFullScreenManagerProxy::BeganEnterFullScreen(initialFrame, finalFrame));
}
void InjectedBundlePageFullScreenClient::beganExitFullScreen(WebPage *page, IntRect& initialFrame, IntRect& finalFrame)
{
if (m_client.beganExitFullScreen)
m_client.beganExitFullScreen(toAPI(page), toAPI(initialFrame), toAPI(finalFrame));
else
page->send(Messages::WebFullScreenManagerProxy::BeganExitFullScreen(initialFrame, finalFrame));
}
void InjectedBundlePageFullScreenClient::closeFullScreen(WebPage *page)
{
if (m_client.closeFullScreen)
m_client.closeFullScreen(toAPI(page));
else
page->send(Messages::WebFullScreenManagerProxy::Close());
}
} // namespace WebKit
#endif // ENABLE(FULLSCREEN_API)
|
#include "core.h"
#include "wbperosagetorientation.h"
#include "configmanager.h"
#include "wbparamevaluatorfactory.h"
#include "Components/wbcomprosatransform.h"
WBPERosaGetOrientation::WBPERosaGetOrientation()
: m_EntityPE( NULL )
{
}
WBPERosaGetOrientation::~WBPERosaGetOrientation()
{
SafeDelete( m_EntityPE );
}
/*virtual*/ void WBPERosaGetOrientation::InitializeFromDefinition( const SimpleString& DefinitionName )
{
MAKEHASH( DefinitionName );
STATICHASH( Entity );
m_EntityPE = WBParamEvaluatorFactory::Create( ConfigManager::GetString( sEntity, "", sDefinitionName ) );
}
/*virtual*/ void WBPERosaGetOrientation::Evaluate( const WBParamEvaluator::SPEContext& Context, WBParamEvaluator::SEvaluatedParam& EvaluatedParam ) const
{
WBParamEvaluator::SEvaluatedParam Value;
m_EntityPE->Evaluate( Context, Value );
WBEntity* const pEntity = Value.GetEntity();
if( !pEntity )
{
return;
}
WBCompRosaTransform* const pTransform = pEntity->GetTransformComponent<WBCompRosaTransform>();
if( !pTransform )
{
return;
}
EvaluatedParam.m_Type = WBParamEvaluator::EPT_Vector;
EvaluatedParam.m_Vector = pTransform->GetOrientation().ToVector();
}
|
#include "MMake/MMake.h"
#include <CommonCLI/Colors.h>
#include <CommonCLI/Core.h>
#include <CMakeLexer/Lexer.h>
#include <CommonLexer/LexerLexer.h>
extern "C"
{
#include <Piccolo/debug/disassembler.h>
#include <Piccolo/include.h>
#include <Piccolo/stdlib/picStdlib.h>
}
#include <cstdarg>
#include <chrono>
#include <filesystem>
#include <iostream>
#include <regex>
#include <sstream>
#include <fmt/chrono.h>
#include <fmt/format.h>
namespace Generated
{
CommonLexer::Lex lexSource(CommonLexer::ISource* source, CommonLexer::SourceSpan span);
CommonLexer::Lex lexSource(CommonLexer::ISource* source);
} // namespace Generated
namespace MMake
{
static void PrintPiccoloError(const char* format, std::va_list args)
{
std::ostringstream error;
error << CommonCLI::Colors::Error;
int size = std::vsnprintf(nullptr, 0, format, args);
char* buf = new char[size + 2];
buf[size + 1] = '\0';
std::vsnprintf(buf, size + 1, format, args);
error << buf;
delete[] buf;
std::cout << error.str();
}
void Run()
{
piccolo_Engine* engine = new piccolo_Engine();
piccolo_initEngine(engine, &PrintPiccoloError);
piccolo_addIOLib(engine);
piccolo_addTimeLib(engine);
std::filesystem::path mainPicFile = std::filesystem::current_path() / "mmake.pic";
piccolo_Package* package = piccolo_loadPackage(engine, mainPicFile.string().c_str());
if (package->compilationError)
{
piccolo_freeEngine(engine);
delete engine;
return;
}
if (!piccolo_executePackage(engine, package))
{
piccolo_enginePrintError(engine, "Runtime error.\n");
}
piccolo_freeEngine(engine);
}
void PrintMessage(const CommonLexer::Message& message, CommonLexer::ISource* source)
{
std::ostringstream str;
switch (message.getSeverity())
{
case CommonLexer::EMessageSeverity::Warning:
str << CommonCLI::Colors::Warn << "CommonLexer Warning ";
break;
case CommonLexer::EMessageSeverity::Error:
str << CommonCLI::Colors::Error << "CommonLexer Error ";
break;
}
auto point = message.getPoint();
auto pointLine = point.getLine(source);
auto pointColumn = point.getColumn(source);
str << '(' << pointLine << ':' << pointColumn << "): ";
str << message.getMessage() << ANSI::GraphicsForegroundDefault << '\n';
auto span = message.getSpan();
auto lines = source->getLines(span);
auto beginLine = span.m_Begin.getLine(source);
auto beginColumn = span.m_Begin.getColumn(source);
auto endLine = span.m_End.getLine(source);
auto endColumn = span.m_End.getColumn(source);
for (std::size_t i = 0; i < lines.size(); ++i)
{
std::string ln = std::to_string(beginLine + i) + ": ";
auto& line = lines[i];
if (line.empty())
continue;
str << ln << line << '\n'
<< std::string(ln.size(), ' ');
str << CommonCLI::Colors::Note;
if (i == 0)
{
str << std::string(beginColumn - 1, ' ');
if (beginLine + i == pointLine)
{
str << std::string(pointColumn - beginColumn, '~') << '^';
if (endLine == beginLine)
str << std::string(endColumn - pointColumn, '~');
else
str << std::string(line.size() - pointColumn, '~');
}
else
{
str << std::string(line.size() - beginColumn, '~');
}
}
else if (i == lines.size() - 1)
{
if (beginLine + i == pointLine)
str << std::string(pointColumn - 1, '~') << '^' << std::string(endColumn - pointColumn, '~');
}
else
{
str << std::string(line.size(), '~');
}
str << ANSI::GraphicsForegroundDefault << '\n';
}
std::cout << str.str();
}
std::string EscapeString(const std::string& str)
{
return std::regex_replace(str, std::regex { "\"" }, "\\\"");
}
std::size_t UTF8Codepoints(const std::string& str)
{
auto itr = str.begin();
auto end = str.end();
std::size_t count = 0;
while (itr != end)
{
std::uint8_t c = *itr;
if (c < 0b1000'0000U)
++itr;
else if (c < 0b1100'0000U)
itr += 2;
else if (c < 0b1110'0000U)
itr += 3;
else if (c < 0b1111'0000U)
itr += 4;
++count;
}
return count;
}
void PrintLexNode(const CommonLexer::Node& node, std::vector<std::vector<std::string>>& lines, std::vector<bool>& layers, bool end = true)
{
{
std::vector<std::string> line;
std::ostringstream str;
for (auto layer : layers)
{
if (layer)
str << "\xE2\x94\x82 ";
else
str << " ";
}
if (end)
str << "\xE2\x94\x94\xE2\x94\x80";
else
str << "\xE2\x94\x9C\xE2\x94\x80";
layers.push_back(!end);
auto span = node.getSpan();
str << node.getRule();
line.push_back(str.str());
str = {};
auto beginLine = span.m_Begin.getLine(node.getSource());
auto beginColumn = span.m_Begin.getColumn(node.getSource());
auto endLine = span.m_End.getLine(node.getSource());
auto endColumn = span.m_End.getColumn(node.getSource());
str << '(' << beginLine << ':' << beginColumn << " -> " << endLine << ':' << endColumn << ')';
line.push_back(str.str());
str = {};
if (beginLine == endLine)
{
std::string s = node.getSource()->getSpan(span);
if (s.find_first_of('\n') >= s.size())
{
str << "= \"" << EscapeString(s) << '"';
line.push_back(str.str());
}
}
lines.push_back(std::move(line));
}
auto& children = node.getChildren();
for (std::size_t i = 0; i < children.size(); ++i)
PrintLexNode(children[i], lines, layers, i >= children.size() - 1);
layers.pop_back();
}
void PrintLex(const CommonLexer::Lex& lex)
{
std::vector<std::vector<std::string>> lines;
std::vector<bool> layers;
PrintLexNode(lex.getRoot(), lines, layers);
std::vector<std::size_t> sizes;
for (auto& line : lines)
{
if ((line.size() - 1) > sizes.size())
sizes.resize(line.size() - 1, 0);
for (std::size_t i = 0; i < line.size() - 1; ++i)
{
auto& column = line[i];
std::size_t codepoints = UTF8Codepoints(column);
if (codepoints > sizes[i])
sizes[i] = codepoints;
}
}
std::ostringstream str;
for (auto& line : lines)
{
for (std::size_t i = 0; i < line.size(); ++i)
{
auto& column = line[i];
str << column;
if (i < line.size() - 1)
str << std::string(sizes[i] - UTF8Codepoints(column) + 1, ' ');
}
str << '\n';
}
std::cout << str.str();
}
void RunCMake()
{
CommonLexer::StringSource lexerSource(R"kekw(!MainRule = File;
File?: FileElement*;
FileElement?: CommandInvocation LineEnding;
(BracketComment | Space)* LineEnding;
LineEnding?: LineComment? Newline;
Space?: '[ \t]+';
Newline?: "\n";
CommandInvocation: Space* Identifier Space* "(" Arguments ")";
Identifier: '[A-Za-z_][A-Za-z0-9_]*';
Arguments: Argument? SeparatedArguments*;
SeparatedArguments: Separation+ Argument?;
Separation* "(" Arguments ")";
Separation?: Space;
LineEnding;
Argument: BracketArgument;
QuotedArgument;
UnquotedArgument;
BracketArgument: BracketOpen BracketContent BracketClose;
BracketOpen?: "[" (<BracketCount>: '='*) "[";
BracketContent: (("]" ~\BracketCount) | '[^\\]]' | Newline)*;
BracketClose?: "]" \BracketCount "]";
QuotedArgument: "\"" QuotedElement* "\"";
QuotedElement: EscapeSequence;
QuotedContinuation;
(newline | '[^"\\]')+;
QuotedContinuation: "\\" Newline;
UnquotedArgument: UnquotedElement+;
UnqoutedLegacy;
UnqoutedElement: EscapeSequence;
'(?:[^\\s()#"\\\\])+';
UnquotedLegacy!;
EscapeSequence: '\\(?:[^A-Za-z0-9;]|[trn;])';
LineComment: '#(?!\\[=*\\[).*';
BracketComment: "#" BracketArgument;)kekw");
CommonLexer::LexerLexer lexerLexer;
auto begin = std::chrono::high_resolution_clock::now();
auto lexerLex = lexerLexer.lexSource(&lexerSource);
auto end = std::chrono::high_resolution_clock::now();
if (!lexerLex.getMessages().empty())
for (auto& message : lexerLex.getMessages())
PrintMessage(message, &lexerSource);
PrintLex(lexerLex);
std::cout << fmt::format("\nTime: {:%S} S\n", end - begin);
auto result = lexerLexer.createCPPLexer(lexerLex);
if (!result.m_Messages.empty())
for (auto& message : result.m_Messages)
PrintMessage(message, &lexerSource);
auto cpp = lexerLexer.compileLexer(result, "Generated");
std::ofstream f { "Out.cpp" };
if (f)
{
f << cpp;
f.close();
}
/*std::cout << "\n^ Original Lex ^\nv New Lex v\n\n";
auto lexBegin = std::chrono::high_resolution_clock::now();
auto lex = Generated::lexSource(&lexerSource);
auto lexEnd = std::chrono::high_resolution_clock::now();
if (!lex.getMessages().empty())
for (auto& message : lex.getMessages())
PrintMessage(message, &lexerSource);
PrintLex(lex);
std::cout << fmt::format("\nOriginal Lex: {:%S} S\nNew Lex: {:%S} S\n", end - begin, lexEnd - lexBegin);*/
/*CommonLexer::StringSource source { R"(
macro(test_macro)
function(test_func)
macro(another_macro)
message("He")
endmacro()
message("Cool")
another_macro()
endfunction()
message("World")
test_func()
return()
endmacro()
message("Hello")
test_macro()
message("Skipped")
)" };
CMakeLexer::Lexer lexer;
auto lex = lexer.lexSource(&source);
if (!lex.getMessages().empty())
{
for (auto& message : lex.getMessages())
PrintMessage(message, &source);
return;
}
PrintLex(lex);*/
}
} // namespace MMake
|
/*
* (C) 2003-2006 Gabest
* (C) 2006-2018 see Authors.txt
*
* This file is part of MPC-BE.
*
* MPC-BE is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* MPC-BE 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, see <http://www.gnu.org/licenses/>.
*
*/
#include "stdafx.h"
#include "StreamDriveThru.h"
#include "../../../DSUtil/DSUtil.h"
#ifdef REGISTER_FILTER
const AMOVIESETUP_MEDIATYPE sudPinTypesIn[] = {
{&MEDIATYPE_Stream, &MEDIASUBTYPE_NULL},
};
const AMOVIESETUP_MEDIATYPE sudPinTypesOut[] = {
{&MEDIATYPE_Stream, &MEDIASUBTYPE_NULL},
};
const AMOVIESETUP_PIN sudpPins[] = {
{L"Input", FALSE, FALSE, FALSE, FALSE, &CLSID_NULL, nullptr, _countof(sudPinTypesIn), sudPinTypesIn},
{L"Output", FALSE, TRUE, FALSE, FALSE, &CLSID_NULL, nullptr, _countof(sudPinTypesOut), sudPinTypesOut}
};
const AMOVIESETUP_FILTER sudFilter[] = {
{&__uuidof(CStreamDriveThruFilter), StreamDriveThruName, MERIT_DO_NOT_USE, _countof(sudpPins), sudpPins, CLSID_LegacyAmFilterCategory}
};
CFactoryTemplate g_Templates[] = {
{sudFilter[0].strName, sudFilter[0].clsID, CreateInstance<CStreamDriveThruFilter>, nullptr, &sudFilter[0]}
};
int g_cTemplates = _countof(g_Templates);
STDAPI DllRegisterServer()
{
return AMovieDllRegisterServer2(TRUE);
}
STDAPI DllUnregisterServer()
{
return AMovieDllRegisterServer2(FALSE);
}
#include "../../filters/Filters.h"
CFilterApp theApp;
#endif
//
// CStreamDriveThruFilter
//
CStreamDriveThruFilter::CStreamDriveThruFilter(LPUNKNOWN pUnk, HRESULT* phr)
: CBaseFilter(L"CStreamDriveThruFilter", pUnk, &m_csLock, __uuidof(this))
, m_position(0)
{
if (phr) {
*phr = S_OK;
}
m_pInput = DNew CStreamDriveThruInputPin(L"CStreamDriveThruInputPin", this, &m_csLock, phr);
m_pOutput = DNew CStreamDriveThruOutputPin(L"CStreamDriveThruOutputPin", this, &m_csLock, phr);
CAMThread::Create();
}
CStreamDriveThruFilter::~CStreamDriveThruFilter()
{
CAutoLock csAutoLock(&m_csLock);
CAMThread::CallWorker(CMD_EXIT);
CAMThread::Close();
delete m_pInput;
delete m_pOutput;
}
STDMETHODIMP CStreamDriveThruFilter::NonDelegatingQueryInterface(REFIID riid, void** ppv)
{
CheckPointer(ppv, E_POINTER);
return
QI(IMediaSeeking)
__super::NonDelegatingQueryInterface(riid, ppv);
}
#define PACKETSIZE 65536
DWORD CStreamDriveThruFilter::ThreadProc()
{
for (;;) {
DWORD cmd = GetRequest();
switch (cmd) {
default:
case CMD_EXIT:
Reply(S_OK);
return 0;
case CMD_STOP:
Reply(S_OK);
break;
case CMD_PAUSE:
Reply(S_OK);
break;
case CMD_RUN:
Reply(S_OK);
do {
CComPtr<IAsyncReader> pAsyncReader;
CComPtr<IStream> pStream;
if (!m_pInput || !m_pInput->IsConnected() || FAILED(m_pInput->GetAsyncReader(&pAsyncReader))
|| !m_pOutput || !m_pOutput->IsConnected() || FAILED(m_pOutput->GetStream(&pStream))) {
break;
}
LARGE_INTEGER li = {0};
ULARGE_INTEGER uli = {0};
if (FAILED(pStream->Seek(li, STREAM_SEEK_SET, nullptr))
|| FAILED(pStream->SetSize(uli))) {
break;
}
if (CComQIPtr<IFileSinkFilter2> pFSF = GetFilterFromPin(m_pOutput->GetConnected())) {
pFSF->SetMode(AM_FILE_OVERWRITE);
LPOLESTR pfn;
if (SUCCEEDED(pFSF->GetCurFile(&pfn, nullptr))) {
pFSF->SetFileName(pfn, nullptr);
CoTaskMemFree(pfn);
}
}
m_position = 0;
BYTE buff[PACKETSIZE];
do {
while (!CheckRequest(&cmd)) {
CAutoLock csAutoLock(&m_csLock);
LONGLONG total = 0, available = 0;
if (FAILED(pAsyncReader->Length(&total, &available)) || m_position >= total) {
cmd = CMD_STOP;
break;
}
LONG size = (LONG)std::min((LONGLONG)PACKETSIZE, total - m_position);
if (FAILED(pAsyncReader->SyncRead(m_position, size, buff))) {
cmd = CMD_STOP;
break;
}
ULONG written = 0;
if (FAILED(pStream->Write(buff, (ULONG)size, &written)) || (ULONG)size != written) {
cmd = CMD_STOP;
break;
}
m_position += size;
}
if (cmd == CMD_PAUSE) {
Reply(S_OK); // reply to CMD_PAUSE
while (!CheckRequest(&cmd)) {
Sleep(50);
}
Reply(S_OK); // reply to something
}
} while (cmd == CMD_RUN);
uli.QuadPart = m_position;
pStream->SetSize(uli);
if (CComPtr<IPin> pPin = m_pOutput->GetConnected()) {
pPin->EndOfStream();
}
} while (false);
break;
}
}
return 0;
}
int CStreamDriveThruFilter::GetPinCount()
{
return 2;
}
CBasePin* CStreamDriveThruFilter::GetPin(int n)
{
CAutoLock csAutoLock(&m_csLock);
if (n == 0) {
return m_pInput;
} else if (n == 1) {
return m_pOutput;
}
return nullptr;
}
STDMETHODIMP CStreamDriveThruFilter::Stop()
{
HRESULT hr;
if (FAILED(hr = __super::Stop())) {
return hr;
}
CallWorker(CMD_STOP);
return S_OK;
}
STDMETHODIMP CStreamDriveThruFilter::Pause()
{
HRESULT hr;
if (FAILED(hr = __super::Pause())) {
return hr;
}
CallWorker(CMD_PAUSE);
return S_OK;
}
STDMETHODIMP CStreamDriveThruFilter::Run(REFERENCE_TIME tStart)
{
HRESULT hr;
if (FAILED(hr = __super::Run(tStart))) {
return hr;
}
CallWorker(CMD_RUN);
return S_OK;
}
// IMediaSeeking
STDMETHODIMP CStreamDriveThruFilter::GetCapabilities(DWORD* pCapabilities)
{
return pCapabilities ? *pCapabilities = AM_SEEKING_CanGetCurrentPos|AM_SEEKING_CanGetStopPos|AM_SEEKING_CanGetDuration, S_OK : E_POINTER;
}
STDMETHODIMP CStreamDriveThruFilter::CheckCapabilities(DWORD* pCapabilities)
{
CheckPointer(pCapabilities, E_POINTER);
if (*pCapabilities == 0) {
return S_OK;
}
DWORD caps;
GetCapabilities(&caps);
DWORD caps2 = caps & *pCapabilities;
return caps2 == 0 ? E_FAIL : caps2 == *pCapabilities ? S_OK : S_FALSE;
}
STDMETHODIMP CStreamDriveThruFilter::IsFormatSupported(const GUID* pFormat)
{
return !pFormat ? E_POINTER : *pFormat == TIME_FORMAT_MEDIA_TIME ? S_OK : S_FALSE;
}
STDMETHODIMP CStreamDriveThruFilter::QueryPreferredFormat(GUID* pFormat)
{
return GetTimeFormat(pFormat);
}
STDMETHODIMP CStreamDriveThruFilter::GetTimeFormat(GUID* pFormat)
{
return pFormat ? *pFormat = TIME_FORMAT_MEDIA_TIME, S_OK : E_POINTER;
}
STDMETHODIMP CStreamDriveThruFilter::IsUsingTimeFormat(const GUID* pFormat)
{
return IsFormatSupported(pFormat);
}
STDMETHODIMP CStreamDriveThruFilter::SetTimeFormat(const GUID* pFormat)
{
return S_OK == IsFormatSupported(pFormat) ? S_OK : E_INVALIDARG;
}
STDMETHODIMP CStreamDriveThruFilter::GetDuration(LONGLONG* pDuration)
{
CheckPointer(pDuration, E_POINTER);
CheckPointer(m_pInput, VFW_E_NOT_CONNECTED);
if (CComQIPtr<IAsyncReader> pAsyncReader = m_pInput->GetConnected()) {
LONGLONG total, available;
if (SUCCEEDED(pAsyncReader->Length(&total, &available))) {
*pDuration = total;
return S_OK;
}
}
return E_NOINTERFACE;
}
STDMETHODIMP CStreamDriveThruFilter::GetStopPosition(LONGLONG* pStop)
{
return GetDuration(pStop);
}
STDMETHODIMP CStreamDriveThruFilter::GetCurrentPosition(LONGLONG* pCurrent)
{
return pCurrent ? *pCurrent = m_position, S_OK : E_POINTER;
}
STDMETHODIMP CStreamDriveThruFilter::ConvertTimeFormat(LONGLONG* pTarget, const GUID* pTargetFormat, LONGLONG Source, const GUID* pSourceFormat)
{
return E_NOTIMPL;
}
STDMETHODIMP CStreamDriveThruFilter::SetPositions(LONGLONG* pCurrent, DWORD dwCurrentFlags, LONGLONG* pStop, DWORD dwStopFlags)
{
return E_NOTIMPL;
}
STDMETHODIMP CStreamDriveThruFilter::GetPositions(LONGLONG* pCurrent, LONGLONG* pStop)
{
return E_NOTIMPL;
}
STDMETHODIMP CStreamDriveThruFilter::GetAvailable(LONGLONG* pEarliest, LONGLONG* pLatest)
{
return E_NOTIMPL;
}
STDMETHODIMP CStreamDriveThruFilter::SetRate(double dRate)
{
return E_NOTIMPL;
}
STDMETHODIMP CStreamDriveThruFilter::GetRate(double* pdRate)
{
return E_NOTIMPL;
}
STDMETHODIMP CStreamDriveThruFilter::GetPreroll(LONGLONG* pllPreroll)
{
return pllPreroll ? *pllPreroll = 0, S_OK : E_POINTER;
}
//
// CStreamDriveThruInputPin
//
CStreamDriveThruInputPin::CStreamDriveThruInputPin(TCHAR* pName, CBaseFilter* pFilter, CCritSec* pLock, HRESULT* phr)
: CBasePin(pName, pFilter, pLock, phr, L"Input", PINDIR_INPUT)
{
}
CStreamDriveThruInputPin::~CStreamDriveThruInputPin()
{
}
HRESULT CStreamDriveThruInputPin::GetAsyncReader(IAsyncReader** ppAsyncReader)
{
CheckPointer(ppAsyncReader, E_POINTER);
*ppAsyncReader = nullptr;
CheckPointer(m_pAsyncReader, VFW_E_NOT_CONNECTED);
(*ppAsyncReader = m_pAsyncReader)->AddRef();
return S_OK;
}
STDMETHODIMP CStreamDriveThruInputPin::NonDelegatingQueryInterface(REFIID riid, void** ppv)
{
CheckPointer(ppv, E_POINTER);
return
__super::NonDelegatingQueryInterface(riid, ppv);
}
HRESULT CStreamDriveThruInputPin::CheckMediaType(const CMediaType* pmt)
{
return pmt->majortype == MEDIATYPE_Stream
? S_OK
: E_INVALIDARG;
}
HRESULT CStreamDriveThruInputPin::CheckConnect(IPin* pPin)
{
HRESULT hr;
if (FAILED(hr = __super::CheckConnect(pPin))) {
return hr;
}
if (!CComQIPtr<IAsyncReader>(pPin)) {
return E_NOINTERFACE;
}
return S_OK;
}
HRESULT CStreamDriveThruInputPin::BreakConnect()
{
HRESULT hr;
if (FAILED(hr = __super::BreakConnect())) {
return hr;
}
m_pAsyncReader.Release();
return S_OK;
}
HRESULT CStreamDriveThruInputPin::CompleteConnect(IPin* pPin)
{
HRESULT hr;
if (FAILED(hr = __super::CompleteConnect(pPin))) {
return hr;
}
CheckPointer(pPin, E_POINTER);
m_pAsyncReader = pPin;
CheckPointer(m_pAsyncReader, E_NOINTERFACE);
return S_OK;
}
STDMETHODIMP CStreamDriveThruInputPin::BeginFlush()
{
return E_UNEXPECTED;
}
STDMETHODIMP CStreamDriveThruInputPin::EndFlush()
{
return E_UNEXPECTED;
}
//
// CStreamDriveThruOutputPin
//
CStreamDriveThruOutputPin::CStreamDriveThruOutputPin(TCHAR* pName, CBaseFilter* pFilter, CCritSec* pLock, HRESULT* phr)
: CBaseOutputPin(pName, pFilter, pLock, phr, L"Output")
{
}
CStreamDriveThruOutputPin::~CStreamDriveThruOutputPin()
{
}
HRESULT CStreamDriveThruOutputPin::GetStream(IStream** ppStream)
{
CheckPointer(ppStream, E_POINTER);
*ppStream = nullptr;
CheckPointer(m_pStream, VFW_E_NOT_CONNECTED);
(*ppStream = m_pStream)->AddRef();
return S_OK;
}
STDMETHODIMP CStreamDriveThruOutputPin::NonDelegatingQueryInterface(REFIID riid, void** ppv)
{
CheckPointer(ppv, E_POINTER);
return
__super::NonDelegatingQueryInterface(riid, ppv);
}
HRESULT CStreamDriveThruOutputPin::DecideBufferSize(IMemAllocator* pAlloc, ALLOCATOR_PROPERTIES* pProperties)
{
ASSERT(pAlloc);
ASSERT(pProperties);
HRESULT hr = NOERROR;
pProperties->cBuffers = 1;
pProperties->cbBuffer = PACKETSIZE;
ALLOCATOR_PROPERTIES Actual;
if (FAILED(hr = pAlloc->SetProperties(pProperties, &Actual))) {
return hr;
}
if (Actual.cbBuffer < pProperties->cbBuffer) {
return E_FAIL;
}
ASSERT(Actual.cBuffers == pProperties->cBuffers);
return NOERROR;
}
HRESULT CStreamDriveThruOutputPin::CheckMediaType(const CMediaType* pmt)
{
return pmt->majortype == MEDIATYPE_Stream
? S_OK
: E_INVALIDARG;
}
HRESULT CStreamDriveThruOutputPin::GetMediaType(int iPosition, CMediaType* pmt)
{
CAutoLock cAutoLock(m_pLock);
if (iPosition < 0) {
return E_INVALIDARG;
}
if (iPosition > 0) {
return VFW_S_NO_MORE_ITEMS;
}
pmt->majortype = MEDIATYPE_Stream;
pmt->subtype = GUID_NULL;
pmt->formattype = GUID_NULL;
pmt->SetSampleSize(PACKETSIZE);
return S_OK;
}
HRESULT CStreamDriveThruOutputPin::CheckConnect(IPin* pPin)
{
HRESULT hr;
if (FAILED(hr = __super::CheckConnect(pPin))) {
return hr;
}
if (!CComQIPtr<IStream>(pPin)) {
return E_NOINTERFACE;
}
return S_OK;
}
HRESULT CStreamDriveThruOutputPin::BreakConnect()
{
HRESULT hr;
if (FAILED(hr = __super::BreakConnect())) {
return hr;
}
m_pStream.Release();
return S_OK;
}
HRESULT CStreamDriveThruOutputPin::CompleteConnect(IPin* pPin)
{
HRESULT hr;
if (FAILED(hr = __super::CompleteConnect(pPin))) {
return hr;
}
CheckPointer(pPin, E_POINTER);
m_pStream = pPin;
CheckPointer(m_pStream, E_NOINTERFACE);
return S_OK;
}
STDMETHODIMP CStreamDriveThruOutputPin::BeginFlush()
{
return E_UNEXPECTED;
}
STDMETHODIMP CStreamDriveThruOutputPin::EndFlush()
{
return E_UNEXPECTED;
}
STDMETHODIMP CStreamDriveThruOutputPin::Notify(IBaseFilter* pSender, Quality q)
{
return E_NOTIMPL;
}
|
/* ===-- fixsfti.c - Implement __fixsfti -----------------------------------===
*
* The LLVM Compiler Infrastructure
*
* This file is dual licensed under the MIT and the University of Illinois Open
* Source Licenses. See LICENSE.TXT for details.
*
* ===----------------------------------------------------------------------===
*/
#include "fp32.h"
#ifdef _MSC_VER
#include <boost/multiprecision/cpp_int.hpp>
typedef boost::multiprecision::int128_t fixint_t;
typedef boost::multiprecision::uint128_t fixuint_t;
#else
typedef __int128 fixint_t;
typedef unsigned __int128 fixuint_t;
#endif
fixint_t ___fixsfti(uint32_t a) {
const fixint_t fixint_max = (fixint_t)((~(fixuint_t)0) / 2);
const fixint_t fixint_min = -fixint_max - 1;
// Break a into sign, exponent, significand
const rep_t aRep = a;
const rep_t aAbs = aRep & absMask;
const fixint_t sign = aRep & signBit ? -1 : 1;
const int exponent = (aAbs >> significandBits) - exponentBias;
const rep_t significand = (aAbs & significandMask) | implicitBit;
// If exponent is negative, the result is zero.
if (exponent < 0)
return 0;
// If the value is too large for the integer type, saturate.
if ((unsigned)exponent >= sizeof(fixint_t) * CHAR_BIT)
return sign == 1 ? fixint_max : fixint_min;
// If 0 <= exponent < significandBits, right shift to get the result.
// Otherwise, shift left.
if (exponent < significandBits)
return sign * (significand >> (significandBits - exponent));
else
return sign * ((fixint_t)significand << (exponent - significandBits));
}
|
//===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
// <valarray>
// template<class T> class valarray;
// template<class T>
// valarray<T>
// sin(const valarray<T>& x);
#include <valarray>
#include <cassert>
#include <sstream>
#include <cstddef>
#include "test_macros.h"
bool is_about(double x, double y, int p)
{
std::ostringstream o;
o.precision(p);
scientific(o);
o << x;
std::string a = o.str();
o.str("");
o << y;
return a == o.str();
}
int main(int, char**)
{
{
typedef double T;
T a1[] = {-.9, -.5, 0., .5, .75};
T a3[] = {-7.8332690962748330e-01,
-4.7942553860420301e-01,
0.0000000000000000e+00,
4.7942553860420301e-01,
6.8163876002333423e-01};
const unsigned N = sizeof(a1)/sizeof(a1[0]);
std::valarray<T> v1(a1, N);
std::valarray<T> v3 = sin(v1);
assert(v3.size() == v1.size());
for (std::size_t i = 0; i < v3.size(); ++i)
assert(is_about(v3[i], a3[i], 10));
}
return 0;
}
|
/**
* 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 <iostream>
#include <vector>
#include <glog/logging.h>
#include <mesos/values.hpp>
#include <stout/foreach.hpp>
#include <stout/strings.hpp>
#include "common/attributes.hpp"
using std::ostream;
using std::string;
using std::vector;
namespace mesos {
std::ostream& operator<<(std::ostream& stream, const Attribute& attribute)
{
stream << attribute.name() << "=";
switch (attribute.type()) {
case Value::SCALAR: stream << attribute.scalar(); break;
case Value::RANGES: stream << attribute.ranges(); break;
case Value::SET: stream << attribute.set(); break;
case Value::TEXT: stream << attribute.text(); break;
default:
LOG(FATAL) << "Unexpected Value type: " << attribute.type();
break;
}
return stream;
}
namespace internal {
bool Attributes::operator==(const Attributes& that) const
{
if (size() != that.size()) {
return false;
}
foreach (const Attribute& attribute, attributes) {
Option<Attribute> maybeAttribute = that.get(attribute);
if (maybeAttribute.isNone()) {
return false;
}
const Attribute& thatAttribute = maybeAttribute.get();
switch (attribute.type()) {
case Value::SCALAR:
if (!(attribute.scalar() == thatAttribute.scalar())) {
return false;
}
break;
case Value::RANGES:
if (!(attribute.ranges() == thatAttribute.ranges())) {
return false;
}
break;
case Value::TEXT:
if (!(attribute.text() == thatAttribute.text())) {
return false;
}
break;
case Value::SET:
LOG(FATAL) << "Sets not supported for attributes";
}
}
return true;
}
const Option<Attribute> Attributes::get(const Attribute& thatAttribute) const
{
foreach (const Attribute& attribute, attributes) {
if (attribute.name() == thatAttribute.name() &&
attribute.type() == thatAttribute.type()) {
return attribute;
}
}
return None();
}
Attribute Attributes::parse(const std::string& name, const std::string& text)
{
Attribute attribute;
Try<Value> result = values::parse(text);
if (result.isError()) {
LOG(FATAL) << "Failed to parse attribute " << name
<< " text " << text
<< " error " << result.error();
} else {
Value value = result.get();
attribute.set_name(name);
if (value.type() == Value::RANGES) {
attribute.set_type(Value::RANGES);
attribute.mutable_ranges()->MergeFrom(value.ranges());
} else if (value.type() == Value::TEXT) {
attribute.set_type(Value::TEXT);
attribute.mutable_text()->MergeFrom(value.text());
} else if (value.type() == Value::SCALAR) {
attribute.set_type(Value::SCALAR);
attribute.mutable_scalar()->MergeFrom(value.scalar());
} else {
LOG(FATAL) << "Bad type for attribute " << name
<< " text " << text
<< " type " << value.type();
}
}
return attribute;
}
Attributes Attributes::parse(const string& s)
{
// Tokenize and parse the value of "attributes".
Attributes attributes;
vector<string> tokens = strings::tokenize(s, ";\n");
for (size_t i = 0; i < tokens.size(); i++) {
const vector<string>& pairs = strings::split(tokens[i], ":", 2);
if (pairs.size() != 2 || pairs[0].empty() || pairs[1].empty()) {
LOG(FATAL) << "Invalid attribute key:value pair '" << tokens[i] << "'";
}
attributes.add(parse(pairs[0], pairs[1]));
}
return attributes;
}
bool Attributes::isValid(const Attribute& attribute)
{
if (!attribute.has_name() ||
attribute.name() == "" ||
!attribute.has_type() ||
!Value::Type_IsValid(attribute.type())) {
return false;
}
if (attribute.type() == Value::SCALAR) {
return attribute.has_scalar();
} else if (attribute.type() == Value::RANGES) {
return attribute.has_ranges();
} else if (attribute.type() == Value::TEXT) {
return attribute.has_text();
} else if (attribute.type() == Value::SET) {
// Attributes doesn't support set.
return false;
}
return false;
}
template <>
Value::Scalar Attributes::get(
const std::string& name,
const Value::Scalar& scalar) const
{
foreach (const Attribute& attribute, attributes) {
if (attribute.name() == name &&
attribute.type() == Value::SCALAR) {
return attribute.scalar();
}
}
return scalar;
}
template <>
Value::Ranges Attributes::get(
const std::string& name,
const Value::Ranges& ranges) const
{
foreach (const Attribute& attribute, attributes) {
if (attribute.name() == name &&
attribute.type() == Value::RANGES) {
return attribute.ranges();
}
}
return ranges;
}
template <>
Value::Text Attributes::get(
const std::string& name,
const Value::Text& text) const
{
foreach (const Attribute& attribute, attributes) {
if (attribute.name() == name &&
attribute.type() == Value::TEXT) {
return attribute.text();
}
}
return text;
}
} // namespace internal {
} // namespace mesos {
|
#include <ArduinoLog.h> // https://github.com/thijse/Arduino-Log
#include <ArduinoOTA.h> // https://github.com/esp8266/Arduino
#include <ESP8266mDNS.h> // https://github.com/esp8266/Arduino
#include <LittleFS.h> // https://github.com/esp8266/Arduino
#include <SerialAndBuffer.h> // ./lib/SerialAndBuffer
#include <WiFiManager.h> // https://github.com/tzapu/WiFiManager
#include "config.h"
#include "web_interface.h"
// The hostname of this device.
// It will be used:
// * to set the wifi hostname (that some routers then expose over DNS, e.g.
// hostname.fritz.box)
// * to set the mDNS hostname (with .local suffix. e.g., hostname.local)
// * as the access point name to configure the WiFi credentials (e.g.
// hostnameAP)
const char kHostName[] = "ESP8266BoilerplatePlatformIO";
// The current configuration.
// The values of this variable will be stored and available across reboots.
Config config;
// The destination for all logs.
std::unique_ptr<SerialAndBuffer> serial_and_buffer;
// The web server used for communicating with the user.
std::unique_ptr<WebInterface> web_interface;
// Prepares the timestamp prefix for the logging library.
void printTimestamp(Print* _logOutput) {
char c[14];
sprintf(c, "[%10lu] ", millis());
_logOutput->print(c);
}
void setup() {
// Set up serial port and wait until connected
Serial.begin(115200);
while (!Serial && !Serial.available()) {
}
serial_and_buffer.reset(new SerialAndBuffer(&Serial));
Log.begin(LOG_LEVEL_NOTICE, serial_and_buffer.get());
Log.setPrefix(printTimestamp);
// Go on a new line (in case there is some initial garbage on the serial
// console).
serial_and_buffer->println();
Log.notice(F("Starting up.\n\n"));
// Start filesystem support.
Log.notice(F("Starting FS...\n"));
LittleFS.begin();
Log.notice(F("FS started.\n"));
Log.notice(F("Loading config...\n"));
config.load();
Log.notice(F("Config loaded.\n"));
{
Log.notice(F("Connecting to the WiFi...\n"));
// Explicitly set the WiFI mode: ESP defaults to STA+AP
WiFi.mode(WIFI_STA);
// Set the WiFi hostname.
WiFi.hostname(kHostName);
// WiFiManager, Local intialization. Once its business is done, there is no
// need to keep it around
WiFiManager wm;
wm.setSaveConfigCallback([]() { config.setSaveFlag(); });
// Set up custom parameters.
WiFiManagerParameter customOTAPassword(
"OTAPassword", "Password protecting future Over-The-Air updates.",
config.OTAPassword.c_str(), kMaxOTAPasswordChars);
wm.addParameter(&customOTAPassword);
// Automatically connects to the WiFi using the saved credentials.
// If the connection fails, it starts an access point with the specified
// name, then goes into a blocking loop awaiting configuration and will
// return a success result
bool success;
success = wm.autoConnect((String(kHostName) + "AP").c_str());
if (!success) {
Log.fatal(F("Failed to connect. Restarting the ESP\n"));
ESP.restart();
}
Log.notice(F("Successfully connected to the WiFI\n"));
// Extracting custom paramers values.
config.OTAPassword = customOTAPassword.getValue();
}
// Set up an mDNS name for this device.
// Only required if we are searching for other devices over mDNS.
// Still useful in any case to make this device more easily detectable.
Log.notice(F("Setting up mDNS...\n"));
if ((!MDNS.begin(kHostName))) {
Log.fatal(F("Error setting up mDNS responder. Restarting the ESP\n"));
ESP.restart();
}
Log.notice(F("mDNS started\n"));
// Support for Over-The-Air updates.
Log.notice(F("Setting up OTA support...\n"));
ArduinoOTA.setPassword(config.OTAPassword.c_str());
ArduinoOTA.begin();
Log.notice(F("OTA support set up completed.\n"));
Log.notice(F("Setting up the web server...\n"));
web_interface.reset(new WebInterface(80, serial_and_buffer->GetBuffer()));
Log.notice(F("Web server setup completed...\n"));
Log.notice(F("Setup completed.\n"));
}
void loop() {
// Make sure we still have a WiFi connection
if (!(WiFi.status() == WL_CONNECTED)) {
Log.notice("No WiFi connection. Attempting to reconnect to the WiFi...");
delay(1000);
return;
}
// Check if there is any Over-The-Air update.
ArduinoOTA.handle();
// Save the configuration (if needed).
config.handleSave();
// Serve any pending HTTP traffic.
web_interface->HandleClient();
// TODO: put your main code here, to run repeatedly:
}
|
/* Copyright (c) 2006, NIF File Format Library and Tools
All rights reserved. Please see niflib.h for license. */
#include "nif/RefObject.h"
using namespace Niflib;
//Definition of TYPE constant
const Type RefObject::TYPE("RefObject", NULL );
RefObject::RefObject() {
_ref_count = 0;
objectsInMemory++;
}
RefObject::RefObject(const RefObject& src) {
_ref_count = 0;
objectsInMemory++;
}
RefObject::~RefObject() {
objectsInMemory--;
}
const Type & RefObject::GetType() const {
return TYPE;
}
unsigned int RefObject::objectsInMemory = 0;
bool RefObject::IsSameType( const Type & compare_to) const {
return GetType().IsSameType( compare_to );
}
bool RefObject::IsSameType( const RefObject * object ) const {
return GetType().IsSameType( object->GetType() );
}
bool RefObject::IsDerivedType( const Type & compare_to) const {
return GetType().IsDerivedType( compare_to );
}
bool RefObject::IsDerivedType( const RefObject * object ) const {
return GetType().IsDerivedType( object->GetType() );
}
void RefObject::AddRef() const {
++_ref_count;
}
void RefObject::SubtractRef() const {
_ref_count--;
if ( _ref_count < 1 ) {
delete this;
}
}
unsigned int RefObject::NumObjectsInMemory() {
return objectsInMemory;
}
/*! Used to format a human readable string that includes the type of the object */
string RefObject::GetIDString() const {
stringstream out;
out << this << "(" << this->GetType().GetTypeName() << ")";
return out.str();
}
|
#include "TypeChecker.hpp"
#include <cassert>
#include <string>
#include <utility>
#include "../Expressions/AccessExpr.hpp"
#include "../Expressions/AssignmentExpr.hpp"
#include "../Expressions/BinaryExpr.hpp"
#include "../Expressions/CallExpr.hpp"
#include "../Expressions/GroupExpr.hpp"
#include "../Expressions/InstantiationExpr.hpp"
#include "../Expressions/LambdaFunctionExpr.hpp"
#include "../Expressions/LiteralExpr.hpp"
#include "../Expressions/TypeExpr.hpp"
#include "../Expressions/UnaryExpr.hpp"
#include "../Expressions/VariableExpr.hpp"
#include "../Statements/BlockStmt.hpp"
#include "../Statements/ClassDeclarationStmt.hpp"
#include "../Statements/ExpressionStmt.hpp"
#include "../Statements/FunDeclarationStmt.hpp"
#include "../Statements/IfStmt.hpp"
#include "../Statements/PrintStmt.hpp"
#include "../Statements/ReturnStmt.hpp"
#include "../Statements/VarDeclarationStmt.hpp"
#include "../Statements/WhileStmt.hpp"
#include "../Values/Value.hpp"
#include "ClassType.hpp"
#include "FunctionType.hpp"
namespace Kyra {
TypeChecker& TypeChecker::the() {
static TypeChecker instance;
return instance;
}
const Result<EmptyValue>& TypeChecker::check(const std::vector<Statement::Ptr>& statements) {
m_result.reset();
for(const auto& statement : statements)
check(statement);
return m_result;
}
void TypeChecker::check(const Statement::Ptr& statement) { statement->accept(*this); }
template <class Callback>
TypeContext::Ptr TypeChecker::run_in_new_context(const Callback& function,
TypeContext::Ptr parent,
const TypeContext::Ptr& values_to_copy) {
TypeContext::Ptr context_copy = std::move(m_current_context);
m_current_context = TypeContext::make_ptr<TypeContext>(std::move(parent));
if(values_to_copy != nullptr) {
for(auto [name, variable] : values_to_copy->get_variables())
m_current_context->declare_var(name, std::move(variable));
for(auto [type_name, type] : values_to_copy->get_types())
m_current_context->declare_type(type_name, std::move(type));
}
function();
TypeContext::Ptr modified_context = std::move(m_current_context);
m_current_context = std::move(context_copy);
return modified_context;
}
void TypeChecker::visit_access_expr(AccessExpr& access_expr) {
EXPR_ACCEPT(access_expr.get_owner(), *this, Type::Ptr owner_type);
const std::string& name = access_expr.get_name().get_value().as_string();
const auto& result = owner_type->knows_about(name);
if(!result.has_value())
THROW_TYPING_ERROR(UndefinedMemberError(access_expr.get_position(), owner_type->get_name(), name));
EXPR_RETURN_FROM_VISIT(result->value);
}
void TypeChecker::visit_assignment_expr(AssignmentExpr& assignment_expr) {
Type::Ptr assigned_value_type;
const std::string& name = assignment_expr.get_name().get_value().as_string();
if(assignment_expr.get_owner() != nullptr) {
EXPR_ACCEPT(assignment_expr.get_owner(), *this, Type::Ptr owner_type);
assigned_value_type = owner_type->knows_about(name)->value;
} else
assigned_value_type = m_current_context->get_var(name)->value;
if(assigned_value_type == nullptr)
THROW_TYPING_ERROR(UndefinedVariableError(assignment_expr.get_position(), name));
if(!m_current_context->get_var(name)->is_mutable)
THROW_TYPING_ERROR(AssignmentToConstError(assignment_expr.get_position(), name));
EXPR_ACCEPT(assignment_expr.get_new_value(), *this, Type::Ptr new_value_type);
if(!new_value_type->can_be_assigned_to(assigned_value_type))
THROW_TYPING_ERROR(WrongTypeError(assignment_expr.get_position(),
assigned_value_type->get_name(),
new_value_type->get_name()));
EXPR_RETURN_FROM_VISIT(new_value_type);
}
void TypeChecker::visit_binary_expr(BinaryExpr& binary_expr) {
EXPR_ACCEPT(binary_expr.get_lhs(), *this, Type::Ptr lhs);
EXPR_ACCEPT(binary_expr.get_rhs(), *this, Type::Ptr rhs);
const std::string& expected_function_name = "operator" + binary_expr.get_operator().get_lexeme();
if(const auto& res = lhs->knows_about(expected_function_name); res.has_value()) {
Type::Ptr type = res->value;
if(type->can_be_called_with({rhs}))
EXPR_RETURN_FROM_VISIT(std::dynamic_pointer_cast<FunctionType>(type)->get_return_type());
}
THROW_TYPING_ERROR(UndefinedMemberError(binary_expr.get_position(), lhs->get_name(), expected_function_name));
}
void TypeChecker::visit_call_expr(CallExpr& call_expr) {
EXPR_ACCEPT(call_expr.get_function(), *this, Type::Ptr g_function);
const auto& function = std::dynamic_pointer_cast<FunctionType>(g_function);
if(g_function == nullptr)
return;
if(function == nullptr)
THROW_TYPING_ERROR(
WrongTypeError(call_expr.get_position(), Value::NativeTypes::Function, g_function->get_name()));
if(function->get_parameters().size() != call_expr.get_arguments().size())
THROW_TYPING_ERROR(ArityError(call_expr.get_position(),
function->get_arity(),
call_expr.get_arguments().size(),
function->get_name()));
for(unsigned long i = 0; i < function->get_parameters().size(); ++i) {
Type::Ptr param = function->get_parameters()[i];
EXPR_ACCEPT(call_expr.get_arguments()[i], *this, Type::Ptr arg);
if(!arg->can_be_assigned_to(param))
THROW_TYPING_ERROR(WrongTypeError(call_expr.get_position(), param->get_name(), arg->get_name()));
}
EXPR_RETURN_FROM_VISIT(function->get_return_type());
}
void TypeChecker::visit_lambda_function(LambdaFunctionExpr& function_expr) {
FunctionType* enclosing_function_type = m_current_function;
EXPR_ACCEPT(function_expr.get_return_type(), *this, Type::Ptr return_type);
std::vector<Type::Ptr> parameters;
TypeContext::Ptr param_scope = run_in_new_context(
[&function_expr, ¶meters, this]() {
for(const auto& param : function_expr.get_parameters()) {
EXPR_ACCEPT(param.type, *this, Type::Ptr param_type);
if(!param_type->is_applicable_for_declaration())
THROW_TYPING_ERROR(UndefinedTypeError(function_expr.get_position(), param_type->get_name()));
parameters.push_back(param_type);
if(!m_current_context->declare_var(param.name.get_value().as_string(), param_type, true))
THROW_TYPING_ERROR(AlreadyDefinedVariableError(function_expr.get_position(),
param.name.get_value().as_string()));
}
},
m_current_context);
auto function_type = std::make_shared<FunctionType>(return_type, std::move(parameters));
m_current_function = function_type.get();
run_in_new_context([&function_expr, this]() { function_expr.get_implementation()->accept(*this); },
m_current_context,
param_scope);
m_current_function = enclosing_function_type;
if(!m_does_current_function_return && function_type->get_return_type()->get_name() != Value::NativeTypes::Nothing)
THROW_TYPING_ERROR(WrongTypeError(function_expr.get_position(),
function_type->get_return_type()->get_name(),
Value::NativeTypes::Nothing));
m_does_current_function_return = false;
EXPR_RETURN_FROM_VISIT(function_type);
}
void TypeChecker::visit_group_expr(GroupExpr& group_expr) {
EXPR_ACCEPT(group_expr.get_expr(), *this, Type::Ptr type);
EXPR_RETURN_FROM_VISIT(type);
}
void TypeChecker::visit_instantiation_expr(InstantiationExpr& instantiation_expr) {
const auto& result = m_current_context->get_type(instantiation_expr.get_class_name().get_value().as_string());
if(!result.has_value())
THROW_TYPING_ERROR(UndefinedTypeError(instantiation_expr.get_position(),
instantiation_expr.get_class_name().get_value().as_string()));
auto class_type = std::dynamic_pointer_cast<ClassType>(*result);
if(instantiation_expr.get_arguments().size() != class_type->get_arity())
THROW_TYPING_ERROR(ArityError(instantiation_expr.get_position(),
class_type->get_arity(),
instantiation_expr.get_arguments().size(),
"Constructor of class " + instantiation_expr.get_class_name().get_value().as_string()));
for(unsigned long i = 0; i < class_type->get_arity(); ++i) {
Type::Ptr expected = class_type->get_constructor_parameter()[i];
EXPR_ACCEPT(instantiation_expr.get_arguments()[i], *this, Type::Ptr provided);
if(*expected != provided)
THROW_TYPING_ERROR(
WrongTypeError(instantiation_expr.get_position(), expected->get_name(), provided->get_name()));
}
EXPR_RETURN_FROM_VISIT(*result);
}
void TypeChecker::visit_literal(LiteralExpr& literal_expr) {
switch(literal_expr.get_type()) {
case LiteralExpr::t_int:
EXPR_RETURN_FROM_VISIT(*m_current_context->get_type(Value::NativeTypes::Number));
break;
case LiteralExpr::t_string:
EXPR_RETURN_FROM_VISIT(*m_current_context->get_type(Value::NativeTypes::String));
break;
case LiteralExpr::t_bool: EXPR_RETURN_FROM_VISIT(*m_current_context->get_type(Value::NativeTypes::Bool)); break;
case LiteralExpr::t_nothing:
EXPR_RETURN_FROM_VISIT(*m_current_context->get_type(Value::NativeTypes::Nothing));
break;
default: assert(false);
}
}
void TypeChecker::visit_type_expr(TypeExpr& type_expr) {
if(type_expr.is_function()) {
EXPR_ACCEPT(type_expr.get_return_type(), *this, Type::Ptr return_type);
std::vector<Type::Ptr> param_types;
for(const auto& param : type_expr.get_parameter_types()) {
EXPR_ACCEPT(param, *this, Type::Ptr param_type);
param_types.push_back(std::move(param_type));
}
EXPR_RETURN_FROM_VISIT(Type::make_ptr<FunctionType>(return_type, std::move(param_types)));
}
const auto& result = m_current_context->get_type(type_expr.get_name());
if(!result.has_value())
THROW_TYPING_ERROR(UndefinedTypeError(type_expr.get_position(), type_expr.get_name()));
EXPR_RETURN_FROM_VISIT(*result);
}
// FIXME: this does not work, as there is no operator overloading
// a type can't have the infix operator AND prefix operator +
void TypeChecker::visit_unary_expr(UnaryExpr& unary_expr) {
EXPR_ACCEPT(unary_expr.get_rhs(), *this, Type::Ptr rhs);
const std::string expected_function_name = "operator" + unary_expr.get_operator().get_lexeme();
if(const auto& res = rhs->knows_about(expected_function_name); res.has_value()) {
Type::Ptr type = res->value;
if(type->can_be_called_with({}))
EXPR_RETURN_FROM_VISIT(std::dynamic_pointer_cast<FunctionType>(type)->get_return_type());
}
THROW_TYPING_ERROR(UndefinedMemberError(unary_expr.get_position(), rhs->get_name(), expected_function_name));
}
void TypeChecker::visit_variable(VariableExpr& variable_expr) {
const std::string& name = variable_expr.get_name().get_value().as_string();
const auto& var_result = m_current_context->get_var(name);
const auto& fun_result = m_current_context->get_function(name);
if(!var_result.has_value() && !fun_result.has_value()) {
if(m_current_class_name != nullptr)
THROW_TYPING_ERROR(
UndefinedMemberError(variable_expr.get_position(), std::string(m_current_class_name), name));
else
THROW_TYPING_ERROR(UndefinedVariableError(variable_expr.get_position(), name));
}
EXPR_RETURN_FROM_VISIT(var_result.has_value() ? var_result->value : fun_result->value);
}
void TypeChecker::visit_block_stmt(BlockStmt& block_stmt) {
run_in_new_context(
[this, &block_stmt]() {
for(const auto& statement : block_stmt.get_statements())
statement->accept(*this);
},
m_current_context);
}
void TypeChecker::visit_var_declaration_stmt(VarDeclarationStmt& declaration_stmt) {
const std::string& name = declaration_stmt.get_identifier().get_value().as_string();
Type::Ptr expected_type{};
if(declaration_stmt.get_type() == nullptr) {
if(declaration_stmt.get_initializer() == nullptr)
THROW_TYPING_ERROR(TypingError(declaration_stmt.get_position(),
"Variable " + name + " needs to be explicitly typed, as it does not get initialized immediately"));
EXPR_ACCEPT(declaration_stmt.get_initializer(), *this, expected_type);
} else {
EXPR_ACCEPT(declaration_stmt.get_type(), *this, expected_type);
if(!expected_type->is_applicable_for_declaration())
THROW_TYPING_ERROR(UndefinedTypeError(declaration_stmt.get_position(), expected_type->get_name()));
if(declaration_stmt.get_initializer() != nullptr) {
if(expected_type->is_function())
m_current_context->declare_var(name, expected_type, declaration_stmt.is_mutable());
EXPR_ACCEPT(declaration_stmt.get_initializer(), *this, Type::Ptr init_type);
if(expected_type->is_function())
m_current_context->remove_var(name);
if(!init_type->can_be_assigned_to(expected_type))
THROW_TYPING_ERROR(WrongTypeError(declaration_stmt.get_position(),
expected_type->get_name(),
init_type->get_name()));
}
}
if(!m_current_context->declare_var(name, expected_type, declaration_stmt.is_mutable())) {
if(m_current_class_name != nullptr)
THROW_TYPING_ERROR(AlreadyDefinedMemberError(declaration_stmt.get_position(),
std::string(m_current_class_name),
name));
else
THROW_TYPING_ERROR(AlreadyDefinedVariableError(declaration_stmt.get_position(), name));
}
}
void TypeChecker::visit_class_declaration_stmt(ClassDeclarationStmt& class_declaration_stmt) {
m_current_class_name = class_declaration_stmt.get_class_name().get_value().as_string().data();
const std::string& name = class_declaration_stmt.get_class_name().get_value().as_string();
if(m_current_context->get_type(name).has_value())
THROW_TYPING_ERROR(AlreadyDefinedTypeError(class_declaration_stmt.get_position(), name));
auto klass = std::make_shared<ClassType>(name);
m_current_context->declare_type(name, klass);
TypeContext::Ptr param_scope = run_in_new_context(
[&class_declaration_stmt, &klass, this]() {
for(const auto& param : class_declaration_stmt.get_constructor_parameters()) {
EXPR_ACCEPT(param.type, *this, Type::Ptr param_type);
if(!param_type->is_applicable_for_declaration())
THROW_TYPING_ERROR(
UndefinedTypeError(class_declaration_stmt.get_position(), param_type->get_name()));
klass->add_constructor_param(param_type);
klass->add_declaration(param.name.get_value().as_string(),
Variable<Type::Ptr>(param_type, param.is_mutable));
if(!m_current_context->declare_var(param.name.get_value().as_string(),
param_type,
param.is_mutable))
THROW_TYPING_ERROR(AlreadyDefinedVariableError(class_declaration_stmt.get_position(),
param.name.get_value().as_string()));
}
},
m_current_context);
TypeContext::Ptr decl_scope = run_in_new_context(
[&class_declaration_stmt, this]() {
for(const auto& decl : class_declaration_stmt.get_declarations())
decl->accept(*this);
},
m_current_context,
param_scope);
for(const auto& [decl_name, decl] : decl_scope->get_variables())
klass->add_declaration(decl_name, decl);
m_current_class_name = nullptr;
}
void TypeChecker::visit_fun_declaration_stmt(FunDeclarationStmt& fun_declaration_stmt) {
const std::string& name = fun_declaration_stmt.get_identifier().get_value().as_string();
EXPR_ACCEPT(fun_declaration_stmt.get_type(), *this, Type::Ptr expected_type);
if(!expected_type->is_applicable_for_declaration())
THROW_TYPING_ERROR(UndefinedTypeError(fun_declaration_stmt.get_position(), expected_type->get_name()));
std::vector<Type::Ptr> parameters;
TypeContext::Ptr param_scope = run_in_new_context(
[&fun_declaration_stmt, ¶meters, this]() {
for(const auto& param : fun_declaration_stmt.get_function()->get_parameters()) {
EXPR_ACCEPT(param.type, *this, Type::Ptr param_type);
if(!param_type->is_applicable_for_declaration())
THROW_TYPING_ERROR(
UndefinedTypeError(fun_declaration_stmt.get_position(), param_type->get_name()));
parameters.push_back(param_type);
if(!m_current_context->declare_var(param.name.get_value().as_string(), param_type, true))
THROW_TYPING_ERROR(AlreadyDefinedVariableError(param.name.get_position(),
param.name.get_value().as_string()));
}
},
m_current_context);
m_current_context->declare_function(name, Variable(expected_type, false));
run_in_new_context([&fun_declaration_stmt,
this]() { fun_declaration_stmt.get_function()->get_implementation()->accept(*this); },
m_current_context,
param_scope);
m_current_context->remove_function(name);
if(!m_current_context->declare_function(name, Variable(expected_type, false))) {
if(m_current_class_name != nullptr)
THROW_TYPING_ERROR(AlreadyDefinedMemberError(fun_declaration_stmt.get_position(),
std::string(m_current_class_name),
name));
else
THROW_TYPING_ERROR(AlreadyDefinedVariableError(fun_declaration_stmt.get_position(), name));
}
}
void TypeChecker::visit_expression_stmt(ExpressionStmt& expression_stmt) { expression_stmt.get_expr()->accept(*this); }
void TypeChecker::visit_print_stmt(PrintStmt& print_stmt) { EXPR_ACCEPT(print_stmt.get_expr(), *this, Type::Ptr type); }
void TypeChecker::visit_return_stmt(ReturnStmt& return_stmt) {
if(m_current_function == nullptr)
THROW_TYPING_ERROR(InvalidReturnError(return_stmt.get_position()));
EXPR_ACCEPT(return_stmt.get_expr(), *this, Type::Ptr returned_type);
if(*returned_type != m_current_function->get_return_type())
THROW_TYPING_ERROR(WrongTypeError(return_stmt.get_position(),
m_current_function->get_return_type()->get_name(),
returned_type->get_name()));
m_does_current_function_return = true;
}
void TypeChecker::visit_while_stmt(WhileStmt& while_stmt) {
EXPR_ACCEPT(while_stmt.get_condition(), *this, Type::Ptr condition);
while_stmt.get_statement()->accept(*this);
}
void TypeChecker::visit_if_stmt(IfStmt& if_stmt) {
EXPR_ACCEPT(if_stmt.get_condition(), *this, Type::Ptr condition);
if_stmt.get_then()->accept(*this);
if(if_stmt.get_else() != nullptr)
if_stmt.get_else()->accept(*this);
}
}
|
// clazy:skip
#include "proofnetwork/xjdf/data/cutblock.h"
#include "proofnetwork/xjdf/data/cuttingparams.h"
#include "proofnetwork/xjdf/data/document.h"
#include "proofnetwork/xjdf/xjdfhelper.h"
#include "gtest/proof/test_global.h"
#include <QFile>
#include <QXmlStreamReader>
using namespace Proof;
using namespace Proof::XJdf;
using testing::Test;
class XJdfHelpersTest : public Test
{
public:
XJdfHelpersTest() {}
protected:
void SetUp() override
{
documentUT = Document::fromFile(":/data/proposal.xjdf");
ASSERT_TRUE(documentUT);
}
void TearDown() override {}
protected:
DocumentSP documentUT;
};
TEST_F(XJdfHelpersTest, flipCutBlocksVertically)
{
const auto cuttingParamsList = documentUT->findResources<CuttingParams>(
[](const auto &cuttingParams) { return !cuttingParams->cutBlocks().isEmpty(); });
ASSERT_FALSE(cuttingParamsList.isEmpty());
const auto cutBlocks = algorithms::filter(cuttingParamsList.first()->cutBlocks(),
[](const auto &cutBlock) { return cutBlock->blockName() == "Block_1"; });
ASSERT_FALSE(cutBlocks.isEmpty());
const auto cutBlock = cutBlocks.first();
EXPECT_EQ(1, cutBlock->x());
EXPECT_EQ(1.1, cutBlock->y());
EXPECT_EQ(400, cutBlock->width());
EXPECT_EQ(300, cutBlock->height());
flipCutBlocksVertically(documentUT);
EXPECT_EQ(1, cutBlock->x());
EXPECT_EQ(698.9, cutBlock->y());
EXPECT_EQ(400, cutBlock->width());
EXPECT_EQ(300, cutBlock->height());
}
|
//////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2008-2010, Image Engine Design Inc. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// * Neither the name of Image Engine Design nor the names of any
// other contributors to this software 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 "boost/format.hpp"
#include "IECore/ObjectParameter.h"
#include "IECore/CompoundParameter.h"
#include "IECore/CompoundObject.h"
#include "IECore/VectorTypedData.h"
#include "IECore/RunTimeTyped.h"
#include "IECore/MeshPrimitiveShrinkWrapOp.h"
#include "IECore/PrimitiveEvaluator.h"
#include "IECore/VectorOps.h"
#include "IECore/TriangulateOp.h"
#include "IECore/DespatchTypedData.h"
using namespace IECore;
using namespace Imath;
IE_CORE_DEFINERUNTIMETYPED( MeshPrimitiveShrinkWrapOp );
MeshPrimitiveShrinkWrapOp::MeshPrimitiveShrinkWrapOp() : MeshPrimitiveOp( "A MeshPrimitiveOp to shrink-wrap one mesh onto another" )
{
m_targetMeshParameter = new MeshPrimitiveParameter(
"target",
"The target mesh to shrink-wrap onto.",
new MeshPrimitive()
);
IntParameter::PresetsContainer directionPresets;
directionPresets.push_back( IntParameter::Preset( "Inside", Inside ) );
directionPresets.push_back( IntParameter::Preset( "Outside", Outside ) );
directionPresets.push_back( IntParameter::Preset( "Both", Both ) );
m_directionParameter = new IntParameter(
"direction",
"The direction by which rays are cast to find the target mesh.",
Both,
Inside,
Both,
directionPresets,
true
);
IntParameter::PresetsContainer methodPresets;
methodPresets.push_back( IntParameter::Preset( "Normal", Normal ) );
methodPresets.push_back( IntParameter::Preset( "X-axis", XAxis ) );
methodPresets.push_back( IntParameter::Preset( "Y-axis", YAxis ) );
methodPresets.push_back( IntParameter::Preset( "Z-axis", ZAxis ) );
methodPresets.push_back( IntParameter::Preset( "DirectionMesh", DirectionMesh ) );
m_methodParameter = new IntParameter(
"method",
"The method by which find the target mesh.",
Normal,
Normal,
DirectionMesh,
methodPresets,
true
);
m_directionMeshParameter = new MeshPrimitiveParameter(
"directionMesh",
"The direction mesh to use when determining where to cast rays",
new MeshPrimitive()
);
m_triangulationToleranceParameter = new FloatParameter(
"triangulationTolerance",
"Set the non-planar and non-convex tolerance for the internal triangulation tests",
1.e-6f,
0.0f
);
parameters()->addParameter( m_targetMeshParameter );
parameters()->addParameter( m_directionParameter );
parameters()->addParameter( m_methodParameter );
parameters()->addParameter( m_directionMeshParameter );
parameters()->addParameter( m_triangulationToleranceParameter );
}
MeshPrimitiveShrinkWrapOp::~MeshPrimitiveShrinkWrapOp()
{
}
MeshPrimitiveParameter * MeshPrimitiveShrinkWrapOp::targetMeshParameter()
{
return m_targetMeshParameter.get();
}
const MeshPrimitiveParameter * MeshPrimitiveShrinkWrapOp::targetMeshParameter() const
{
return m_targetMeshParameter.get();
}
IntParameter * MeshPrimitiveShrinkWrapOp::methodParameter()
{
return m_methodParameter.get();
}
const IntParameter * MeshPrimitiveShrinkWrapOp::methodParameter() const
{
return m_methodParameter.get();
}
IntParameter * MeshPrimitiveShrinkWrapOp::directionParameter()
{
return m_directionParameter.get();
}
const IntParameter * MeshPrimitiveShrinkWrapOp::directionParameter() const
{
return m_directionParameter.get();
}
MeshPrimitiveParameter * MeshPrimitiveShrinkWrapOp::directionMeshParameter()
{
return m_directionMeshParameter.get();
}
const MeshPrimitiveParameter * MeshPrimitiveShrinkWrapOp::directionMeshParameter() const
{
return m_directionMeshParameter.get();
}
FloatParameter * MeshPrimitiveShrinkWrapOp::triangulationToleranceParameter()
{
return m_triangulationToleranceParameter.get();
}
const FloatParameter * MeshPrimitiveShrinkWrapOp::triangulationToleranceParameter() const
{
return m_triangulationToleranceParameter.get();
}
struct MeshPrimitiveShrinkWrapOp::ShrinkWrapFn
{
typedef void ReturnType;
PrimitivePtr m_sourceMesh;
const Primitive * m_targetMesh;
const Data * m_directionData;
Direction m_direction;
Method m_method;
float m_tolerance;
ShrinkWrapFn( Primitive * sourceMesh, const Primitive * targetMesh, const Data * directionData, Direction direction, Method method, float tolerance )
: m_sourceMesh( sourceMesh ), m_targetMesh( targetMesh ), m_directionData( directionData ), m_direction( direction ), m_method( method ), m_tolerance( tolerance )
{
}
template<typename T>
void operator()( T * vertexData ) const
{
assert( vertexData );
typedef typename T::ValueType::value_type Vec;
assert( m_sourceMesh );
if ( ! m_targetMesh )
{
return;
}
typename T::ValueType &vertices = vertexData->writable();
const T *directionVerticesData = runTimeCast<const T , const Data >( m_directionData );
if ( m_method == DirectionMesh )
{
if ( !directionVerticesData )
{
throw InvalidArgumentException( (boost::format("MeshPrimitiveShrinkWrapOp: Direction mesh has no primitive variable \"P\" of type \"%s\" ") % T::staticTypeName() ).str() );
}
else if ( directionVerticesData->readable().size() != vertices.size() )
{
throw InvalidArgumentException("MeshPrimitiveShrinkWrapOp: Direction mesh has incorrect number of vertices" );
}
}
TriangulateOpPtr op = new TriangulateOp();
op->inputParameter()->setValue( m_sourceMesh );
op->toleranceParameter()->setNumericValue( m_tolerance );
MeshPrimitivePtr triangulatedSourcePrimitive = runTimeCast< MeshPrimitive > ( op->operate() );
PrimitiveEvaluatorPtr sourceEvaluator = 0;
PrimitiveEvaluator::ResultPtr sourceResult = 0;
if ( m_method == Normal )
{
sourceEvaluator = PrimitiveEvaluator::create( triangulatedSourcePrimitive );
assert( sourceEvaluator );
sourceResult = sourceEvaluator->createResult();
assert( sourceResult );
}
PrimitiveEvaluatorPtr targetEvaluator = PrimitiveEvaluator::create( m_targetMesh );
assert( targetEvaluator );
PrimitiveEvaluator::ResultPtr insideResult = targetEvaluator->createResult();
PrimitiveEvaluator::ResultPtr outsideResult = targetEvaluator->createResult();
assert( insideResult );
assert( outsideResult );
PrimitiveVariableMap::const_iterator it = triangulatedSourcePrimitive->variables.find( "N" );
if (it == m_sourceMesh->variables.end())
{
throw InvalidArgumentException("MeshPrimitiveShrinkWrapOp: MeshPrimitive has no primitive variable \"N\"" );
}
const PrimitiveVariable &nPrimVar = it->second;
typename T::ValueType::size_type vertexId = 0;
for ( typename T::ValueType::iterator pit = vertices.begin(); pit != vertices.end(); ++pit, ++vertexId )
{
Vec &vertexPosition = *pit;
Vec rayDirection;
if ( m_method == Normal )
{
assert( sourceEvaluator );
assert( sourceResult );
sourceEvaluator->closestPoint( vertexPosition, sourceResult.get() );
rayDirection = sourceResult->vectorPrimVar( nPrimVar ).normalized();
}
else if ( m_method == XAxis )
{
rayDirection = Vec( 1.0, 0.0, 0.0 );
}
else if ( m_method == YAxis )
{
rayDirection = Vec( 0.0, 1.0, 0.0 );
}
else if ( m_method == ZAxis )
{
rayDirection = Vec( 0.0, 0.0, 1.0 );
}
else
{
assert( m_method == DirectionMesh );
assert( directionVerticesData );
assert( vertexId < directionVerticesData->readable().size() );
rayDirection = ( directionVerticesData->readable()[ vertexId ] - vertexPosition ).normalized();
}
bool hit = false;
if ( m_direction == Inside )
{
hit = targetEvaluator->intersectionPoint( vertexPosition, -rayDirection, insideResult.get() );
if ( hit )
{
vertexPosition = insideResult->point();
}
}
else if ( m_direction == Outside )
{
hit = targetEvaluator->intersectionPoint( vertexPosition, rayDirection, outsideResult.get() );
if ( hit )
{
vertexPosition = outsideResult->point();
}
}
else
{
assert( m_direction == Both );
bool insideHit = targetEvaluator->intersectionPoint( vertexPosition, -rayDirection, insideResult.get() );
bool outsideHit = targetEvaluator->intersectionPoint( vertexPosition, rayDirection, outsideResult.get() );
/// Choose the closest, or the only, intersection
if ( insideHit && outsideHit )
{
typename Vec::BaseType insideDist = vecDistance2( vertexPosition, Vec( insideResult->point() ) );
typename Vec::BaseType outsideDist = vecDistance2( vertexPosition, Vec( outsideResult->point() ) );
if ( insideDist < outsideDist )
{
vertexPosition = insideResult->point();
}
else
{
vertexPosition = outsideResult->point();
}
}
else if ( insideHit )
{
vertexPosition = insideResult->point();
}
else if ( outsideHit )
{
vertexPosition = outsideResult->point();
}
}
}
}
struct ErrorHandler
{
template<typename T, typename F>
void operator()( const T *data, const F& functor )
{
assert( data );
throw InvalidArgumentException( ( boost::format( "MeshPrimitiveShrinkWrapOp: Invalid data type \"%s\" for primitive variable \"P\"." ) % Object::typeNameFromTypeId( data->typeId() ) ).str() );
}
};
};
void MeshPrimitiveShrinkWrapOp::modifyTypedPrimitive( MeshPrimitive * mesh, const CompoundObject * operands )
{
assert( mesh );
assert( operands );
PrimitiveVariableMap::const_iterator it = mesh->variables.find("P");
if (it == mesh->variables.end())
{
throw InvalidArgumentException("MeshPrimitive has no primitive variable \"P\" in MeshPrimitiveShrinkWrapOp" );
}
const DataPtr verticesData = it->second.data;
if (! mesh->arePrimitiveVariablesValid() )
{
throw InvalidArgumentException( "Mesh with invalid primitive variables given to MeshPrimitiveShrinkWrapOp" );
}
MeshPrimitivePtr target = targetMeshParameter()->getTypedValue< MeshPrimitive >( );
if ( !target )
{
return;
}
if ( ! target->arePrimitiveVariablesValid() )
{
throw InvalidArgumentException( "Target mesh with invalid primitive variables given to MeshPrimitiveShrinkWrapOp" );
}
TriangulateOpPtr op = new TriangulateOp();
op->inputParameter()->setValue( target );
target = runTimeCast< MeshPrimitive > ( op->operate() );
assert( target );
Direction direction = static_cast<Direction>( m_directionParameter->getNumericValue() );
Method method = static_cast<Method>( m_methodParameter->getNumericValue() );
MeshPrimitivePtr directionMesh = 0;
ConstDataPtr directionVerticesData = 0;
if ( method == DirectionMesh )
{
directionMesh = directionMeshParameter()->getTypedValue< MeshPrimitive >( );
if ( ! directionMesh )
{
throw InvalidArgumentException( "No direction mesh given to MeshPrimitiveShrinkWrapOp" );
}
if ( ! directionMesh->arePrimitiveVariablesValid() )
{
throw InvalidArgumentException( "Direction mesh with invalid primitive variables given to MeshPrimitiveShrinkWrapOp" );
}
PrimitiveVariableMap::const_iterator it = directionMesh->variables.find("P");
if (it == directionMesh->variables.end())
{
throw InvalidArgumentException("Direction mesh has no primitive variable \"P\" in MeshPrimitiveShrinkWrapOp" );
}
directionVerticesData = it->second.data;
}
ShrinkWrapFn fn( mesh, target.get(), directionVerticesData.get(), direction, method, this->triangulationToleranceParameter()->getNumericValue() );
despatchTypedData< ShrinkWrapFn, TypeTraits::IsFloatVec3VectorTypedData, ShrinkWrapFn::ErrorHandler >( verticesData.get(), fn );
}
|
/* Copyright 2022 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include <string>
#include "mlir/Dialect/Func/IR/FuncOps.h" // from @llvm-project
#include "mlir/IR/Attributes.h" // from @llvm-project
#include "mlir/IR/Operation.h" // from @llvm-project
#include "mlir/IR/SymbolTable.h" // from @llvm-project
#include "mlir/Pass/Pass.h" // from @llvm-project
#include "tensorflow/dtensor/cc/constants.h"
#include "tensorflow/dtensor/mlir/dtensor_mlir_passes.h"
#include "tensorflow/dtensor/mlir/dtensor_mlir_passes_classes.h"
namespace tensorflow {
namespace dtensor {
namespace {
#define GEN_PASS_CLASSES
#include "tensorflow/dtensor/mlir/dtensor_passes.h.inc"
struct DTensorFunctionRenaming
: public DTensorFunctionRenamingBase<DTensorFunctionRenaming> {
void runOnOperation() override {
mlir::ModuleOp module = getOperation();
const std::string append =
module->getAttrOfType<mlir::StringAttr>(dtensor::kCacheKey)
.getValue()
.str();
// If the cache key isn't set, simply return without renameing functions.
if (append.empty()) return;
mlir::SymbolTableCollection symbol_table;
mlir::SymbolUserMap symbolUsers(symbol_table, module);
for (mlir::func::FuncOp func_op :
llvm::make_early_inc_range(module.getOps<mlir::func::FuncOp>())) {
// Only rename private functions, functions which are public (i.e. the
// main function of the module), must have stable names since they are
// public and may be used by other modules/pieces of code.
if (func_op.getVisibility() != mlir::SymbolTable::Visibility::Private)
continue;
std::string new_name = absl::StrCat(
mlir::SymbolTable::getSymbolName(func_op).getValue().str(), append);
symbolUsers.replaceAllUsesWith(
func_op, mlir::StringAttr::get(&getContext(), new_name));
mlir::SymbolTable::setSymbolName(func_op, new_name);
}
};
};
} // namespace
std::unique_ptr<mlir::OperationPass<mlir::ModuleOp>>
CreateFunctionRenamingPass() {
return std::make_unique<DTensorFunctionRenaming>();
}
} // namespace dtensor
} // namespace tensorflow
|
#include <stan/math/mix/mat.hpp>
#include <gtest/gtest.h>
using stan::math::fvar;
using stan::math::var;
TEST(AgradMixMatrixTraceInvQuadFormLDLT,matrix_fv_matrix_fv_1) {
stan::math::LDLT_factor<fvar<var>,-1,-1> ldlt_Ad;
stan::math::matrix_fv Ad(2,2);
stan::math::matrix_fv Av(2,2);
fvar<var> I;
Ad << 2.0, 3.0,
3.0, 7.0;
Ad(0,0).d_ = 1.0;
Ad(0,1).d_ = 1.0;
Ad(1,0).d_ = 1.0;
Ad(1,1).d_ = 1.0;
Av << 2.0, 3.0,
5.0, 7.0;
Av(0,0).d_ = 2.0;
Av(0,1).d_ = 2.0;
Av(1,0).d_ = 2.0;
Av(1,1).d_ = 2.0;
ldlt_Ad.compute(Ad);
ASSERT_TRUE(ldlt_Ad.success());
I = trace_inv_quad_form_ldlt(ldlt_Ad,Ad);
EXPECT_FLOAT_EQ(9.0,I.val_.val());
EXPECT_FLOAT_EQ(2.0,I.d_.val());
I = trace_inv_quad_form_ldlt(ldlt_Ad,Av);
EXPECT_FLOAT_EQ(10.6,I.val_.val());
EXPECT_FLOAT_EQ(5.04,I.d_.val());
std::vector<double> grads;
std::vector<var> vars;
vars.push_back(Ad(0,0).val_);
vars.push_back(Ad(0,1).val_);
vars.push_back(Ad(1,0).val_);
vars.push_back(Ad(1,1).val_);
vars.push_back(Av(0,0).val_);
vars.push_back(Av(0,1).val_);
vars.push_back(Av(1,0).val_);
vars.push_back(Av(1,1).val_);
I.val_.grad(vars, grads);
EXPECT_FLOAT_EQ(-0.04, grads[0]);
EXPECT_FLOAT_EQ(0, grads[1]);
EXPECT_FLOAT_EQ(0.32, grads[2]);
EXPECT_FLOAT_EQ(-1.64, grads[3]);
EXPECT_FLOAT_EQ(-0.4, grads[4]);
EXPECT_FLOAT_EQ(0, grads[5]);
EXPECT_FLOAT_EQ(1.6, grads[6]);
EXPECT_FLOAT_EQ(2, grads[7]);
}
TEST(AgradMixMatrixTraceInvQuadFormLDLT,matrix_fv_matrix_fv_2) {
stan::math::LDLT_factor<fvar<var>,-1,-1> ldlt_Ad;
stan::math::matrix_fv Ad(2,2);
stan::math::matrix_fv Av(2,2);
fvar<var> I;
Ad << 2.0, 3.0,
3.0, 7.0;
Ad(0,0).d_ = 1.0;
Ad(0,1).d_ = 1.0;
Ad(1,0).d_ = 1.0;
Ad(1,1).d_ = 1.0;
Av << 2.0, 3.0,
5.0, 7.0;
Av(0,0).d_ = 2.0;
Av(0,1).d_ = 2.0;
Av(1,0).d_ = 2.0;
Av(1,1).d_ = 2.0;
ldlt_Ad.compute(Ad);
ASSERT_TRUE(ldlt_Ad.success());
I = trace_inv_quad_form_ldlt(ldlt_Ad,Av);
std::vector<double> grads;
std::vector<var> vars;
vars.push_back(Ad(0,0).val_);
vars.push_back(Ad(0,1).val_);
vars.push_back(Ad(1,0).val_);
vars.push_back(Ad(1,1).val_);
vars.push_back(Av(0,0).val_);
vars.push_back(Av(0,1).val_);
vars.push_back(Av(1,0).val_);
vars.push_back(Av(1,1).val_);
I.d_.grad(vars, grads);
EXPECT_FLOAT_EQ(0.448, grads[0]);
EXPECT_FLOAT_EQ(0, grads[1]);
EXPECT_FLOAT_EQ(-3.504, grads[2]);
EXPECT_FLOAT_EQ(0.848, grads[3]);
EXPECT_FLOAT_EQ(2.24, grads[4]);
EXPECT_FLOAT_EQ(1.6, grads[5]);
EXPECT_FLOAT_EQ(-0.56, grads[6]);
EXPECT_FLOAT_EQ(-0.4, grads[7]);
}
TEST(AgradMixMatrixTraceInvQuadFormLDLT,matrix_fv_matrix_d_1) {
stan::math::LDLT_factor<fvar<var>,-1,-1> ldlt_Ad;
stan::math::matrix_fv Ad(2,2);
stan::math::matrix_d Av(2,2);
fvar<var> I;
Ad << 2.0, 3.0,
3.0, 7.0;
Ad(0,0).d_ = 1.0;
Ad(0,1).d_ = 1.0;
Ad(1,0).d_ = 1.0;
Ad(1,1).d_ = 1.0;
Av << 2.0, 3.0,
5.0, 7.0;
ldlt_Ad.compute(Ad);
ASSERT_TRUE(ldlt_Ad.success());
I = trace_inv_quad_form_ldlt(ldlt_Ad,Av);
EXPECT_FLOAT_EQ(10.6,I.val_.val());
EXPECT_FLOAT_EQ(-1.36,I.d_.val());
std::vector<double> grads;
std::vector<var> vars;
vars.push_back(Ad(0,0).val_);
vars.push_back(Ad(0,1).val_);
vars.push_back(Ad(1,0).val_);
vars.push_back(Ad(1,1).val_);
I.val_.grad(vars, grads);
EXPECT_FLOAT_EQ(-0.04, grads[0]);
EXPECT_FLOAT_EQ(0, grads[1]);
EXPECT_FLOAT_EQ(0.32, grads[2]);
EXPECT_FLOAT_EQ(-1.64, grads[3]);
}
TEST(AgradMixMatrixTraceInvQuadFormLDLT,matrix_fv_matrix_d_2) {
stan::math::LDLT_factor<fvar<var>,-1,-1> ldlt_Ad;
stan::math::matrix_fv Ad(2,2);
stan::math::matrix_d Av(2,2);
fvar<var> I;
Ad << 2.0, 3.0,
3.0, 7.0;
Ad(0,0).d_ = 1.0;
Ad(0,1).d_ = 1.0;
Ad(1,0).d_ = 1.0;
Ad(1,1).d_ = 1.0;
Av << 2.0, 3.0,
5.0, 7.0;
ldlt_Ad.compute(Ad);
ASSERT_TRUE(ldlt_Ad.success());
I = trace_inv_quad_form_ldlt(ldlt_Ad,Av);
std::vector<double> grads;
std::vector<var> vars;
vars.push_back(Ad(0,0).val_);
vars.push_back(Ad(0,1).val_);
vars.push_back(Ad(1,0).val_);
vars.push_back(Ad(1,1).val_);
I.d_.grad(vars, grads);
EXPECT_FLOAT_EQ(-0.192, grads[0]);
EXPECT_FLOAT_EQ(0, grads[1]);
EXPECT_FLOAT_EQ(2.416, grads[2]);
EXPECT_FLOAT_EQ(-0.592, grads[3]);
}
TEST(AgradMixMatrixTraceInvQuadFormLDLT,matrix_d_matrix_fv_1) {
stan::math::LDLT_factor<double ,-1,-1> ldlt_Ad;
stan::math::matrix_d Ad(2,2);
stan::math::matrix_fv Av(2,2);
fvar<var> I;
Ad << 2.0, 3.0,
3.0, 7.0;
Av << 2.0, 3.0,
5.0, 7.0;
Av(0,0).d_ = 2.0;
Av(0,1).d_ = 2.0;
Av(1,0).d_ = 2.0;
Av(1,1).d_ = 2.0;
ldlt_Ad.compute(Ad);
ASSERT_TRUE(ldlt_Ad.success());
I = trace_inv_quad_form_ldlt(ldlt_Ad,Av);
EXPECT_FLOAT_EQ(10.6,I.val_.val());
EXPECT_FLOAT_EQ(6.4,I.d_.val());
std::vector<double> grads;
std::vector<var> vars;
vars.push_back(Av(0,0).val_);
vars.push_back(Av(0,1).val_);
vars.push_back(Av(1,0).val_);
vars.push_back(Av(1,1).val_);
I.val_.grad(vars, grads);
EXPECT_FLOAT_EQ(-0.4, grads[0]);
EXPECT_FLOAT_EQ(0, grads[1]);
EXPECT_FLOAT_EQ(1.6, grads[2]);
EXPECT_FLOAT_EQ(2, grads[3]);
}
TEST(AgradMixMatrixTraceInvQuadFormLDLT,matrix_d_matrix_fv_2) {
stan::math::LDLT_factor<double ,-1,-1> ldlt_Ad;
stan::math::matrix_d Ad(2,2);
stan::math::matrix_fv Av(2,2);
fvar<var> I;
Ad << 2.0, 3.0,
3.0, 7.0;
Av << 2.0, 3.0,
5.0, 7.0;
Av(0,0).d_ = 2.0;
Av(0,1).d_ = 2.0;
Av(1,0).d_ = 2.0;
Av(1,1).d_ = 2.0;
ldlt_Ad.compute(Ad);
ASSERT_TRUE(ldlt_Ad.success());
I = trace_inv_quad_form_ldlt(ldlt_Ad,Av);
std::vector<double> grads;
std::vector<var> vars;
vars.push_back(Av(0,0).val_);
vars.push_back(Av(0,1).val_);
vars.push_back(Av(1,0).val_);
vars.push_back(Av(1,1).val_);
I.d_.grad(vars, grads);
EXPECT_FLOAT_EQ(3.2, grads[0]);
EXPECT_FLOAT_EQ(3.2, grads[1]);
EXPECT_FLOAT_EQ(-0.8, grads[2]);
EXPECT_FLOAT_EQ(-0.8, grads[3]);
}
TEST(AgradMixMatrixTraceInvQuadFormLDLT,matrix_fv_vector_fv_1) {
stan::math::LDLT_factor<fvar<var>,-1,-1> ldlt_Ad;
stan::math::matrix_fv Ad(2,2);
stan::math::vector_fv Av(2);
fvar<var> I;
Ad << 2.0, 3.0,
3.0, 7.0;
Ad(0,0).d_ = 1.0;
Ad(0,1).d_ = 1.0;
Ad(1,0).d_ = 1.0;
Ad(1,1).d_ = 1.0;
Av << 2.0, 3.0;
Av(0).d_ = 2.0;
Av(1).d_ = 2.0;
ldlt_Ad.compute(Ad);
ASSERT_TRUE(ldlt_Ad.success());
I = trace_inv_quad_form_ldlt(ldlt_Ad,Av);
EXPECT_FLOAT_EQ(2,I.val_.val());
EXPECT_FLOAT_EQ(3,I.d_.val());
std::vector<double> grads;
std::vector<var> vars;
vars.push_back(Ad(0,0).val_);
vars.push_back(Ad(0,1).val_);
vars.push_back(Ad(1,0).val_);
vars.push_back(Ad(1,1).val_);
vars.push_back(Av(0).val_);
vars.push_back(Av(1).val_);
I.val_.grad(vars, grads);
EXPECT_FLOAT_EQ(-1, grads[0]);
EXPECT_FLOAT_EQ(0, grads[1]);
EXPECT_FLOAT_EQ(0, grads[2]);
EXPECT_NEAR(0, grads[3], 1E-12);
EXPECT_FLOAT_EQ(2, grads[4]);
EXPECT_FLOAT_EQ(0, grads[5]);
}
TEST(AgradMixMatrixTraceInvQuadFormLDLT,matrix_fv_vector_fv_2) {
stan::math::LDLT_factor<fvar<var>,-1,-1> ldlt_Ad;
stan::math::matrix_fv Ad(2,2);
stan::math::vector_fv Av(2);
fvar<var> I;
Ad << 2.0, 3.0,
3.0, 7.0;
Ad(0,0).d_ = 1.0;
Ad(0,1).d_ = 1.0;
Ad(1,0).d_ = 1.0;
Ad(1,1).d_ = 1.0;
Av << 2.0, 3.0;
Av(0).d_ = 2.0;
Av(1).d_ = 2.0;
ldlt_Ad.compute(Ad);
ASSERT_TRUE(ldlt_Ad.success());
I = trace_inv_quad_form_ldlt(ldlt_Ad,Av);
std::vector<double> grads;
std::vector<var> vars;
vars.push_back(Ad(0,0).val_);
vars.push_back(Ad(0,1).val_);
vars.push_back(Ad(1,0).val_);
vars.push_back(Ad(1,1).val_);
vars.push_back(Av(0).val_);
vars.push_back(Av(1).val_);
I.d_.grad(vars, grads);
EXPECT_FLOAT_EQ(-1.6, grads[0]);
EXPECT_FLOAT_EQ(0, grads[1]);
EXPECT_FLOAT_EQ(0.4, grads[2]);
EXPECT_NEAR(0, grads[3], 1E-12);
EXPECT_FLOAT_EQ(1.6, grads[4]);
EXPECT_FLOAT_EQ(-0.4, grads[5]);
}
TEST(AgradMixMatrixTraceInvQuadFormLDLT,matrix_fv_vector_d_1) {
stan::math::LDLT_factor<fvar<var>,-1,-1> ldlt_Ad;
stan::math::matrix_fv Ad(2,2);
stan::math::vector_d Av(2);
fvar<var> I;
Ad << 2.0, 3.0,
3.0, 7.0;
Ad(0,0).d_ = 1.0;
Ad(0,1).d_ = 1.0;
Ad(1,0).d_ = 1.0;
Ad(1,1).d_ = 1.0;
Av << 2.0, 3.0;
ldlt_Ad.compute(Ad);
ASSERT_TRUE(ldlt_Ad.success());
I = trace_inv_quad_form_ldlt(ldlt_Ad,Av);
EXPECT_FLOAT_EQ(2,I.val_.val());
EXPECT_FLOAT_EQ(-1,I.d_.val());
std::vector<double> grads;
std::vector<var> vars;
vars.push_back(Ad(0,0).val_);
vars.push_back(Ad(0,1).val_);
vars.push_back(Ad(1,0).val_);
vars.push_back(Ad(1,1).val_);
I.val_.grad(vars, grads);
EXPECT_FLOAT_EQ(-1, grads[0]);
EXPECT_FLOAT_EQ(0, grads[1]);
EXPECT_FLOAT_EQ(0, grads[2]);
EXPECT_NEAR(0, grads[3], 1E-12);
}
TEST(AgradMixMatrixTraceInvQuadFormLDLT,matrix_fv_vector_d_2) {
stan::math::LDLT_factor<fvar<var>,-1,-1> ldlt_Ad;
stan::math::matrix_fv Ad(2,2);
stan::math::vector_d Av(2);
fvar<var> I;
Ad << 2.0, 3.0,
3.0, 7.0;
Ad(0,0).d_ = 1.0;
Ad(0,1).d_ = 1.0;
Ad(1,0).d_ = 1.0;
Ad(1,1).d_ = 1.0;
Av << 2.0, 3.0;
ldlt_Ad.compute(Ad);
ASSERT_TRUE(ldlt_Ad.success());
I = trace_inv_quad_form_ldlt(ldlt_Ad,Av);
std::vector<double> grads;
std::vector<var> vars;
vars.push_back(Ad(0,0).val_);
vars.push_back(Ad(0,1).val_);
vars.push_back(Ad(1,0).val_);
vars.push_back(Ad(1,1).val_);
I.d_.grad(vars, grads);
EXPECT_FLOAT_EQ(1.6, grads[0]);
EXPECT_FLOAT_EQ(0, grads[1]);
EXPECT_FLOAT_EQ(-0.4, grads[2]);
EXPECT_NEAR(0, grads[3], 1E-12);
}
TEST(AgradMixMatrixTraceInvQuadFormLDLT,matrix_d_vector_fv_1) {
stan::math::LDLT_factor<double,-1,-1> ldlt_Ad;
stan::math::matrix_d Ad(2,2);
stan::math::vector_fv Av(2);
fvar<var> I;
Ad << 2.0, 3.0,
3.0, 7.0;
Av << 2.0, 3.0;
Av(0).d_ = 2.0;
Av(1).d_ = 2.0;
ldlt_Ad.compute(Ad);
ASSERT_TRUE(ldlt_Ad.success());
I = trace_inv_quad_form_ldlt(ldlt_Ad,Av);
EXPECT_FLOAT_EQ(2,I.val_.val());
EXPECT_FLOAT_EQ(4,I.d_.val());
std::vector<double> grads;
std::vector<var> vars;
vars.push_back(Av(0).val_);
vars.push_back(Av(1).val_);
I.val_.grad(vars, grads);
EXPECT_FLOAT_EQ(2, grads[0]);
EXPECT_FLOAT_EQ(0, grads[1]);
}
TEST(AgradMixMatrixTraceInvQuadFormLDLT,matrix_d_vector_fv_2) {
stan::math::LDLT_factor<double,-1,-1> ldlt_Ad;
stan::math::matrix_d Ad(2,2);
stan::math::vector_fv Av(2);
fvar<var> I;
Ad << 2.0, 3.0,
3.0, 7.0;
Av << 2.0, 3.0;
Av(0).d_ = 2.0;
Av(1).d_ = 2.0;
ldlt_Ad.compute(Ad);
ASSERT_TRUE(ldlt_Ad.success());
I = trace_inv_quad_form_ldlt(ldlt_Ad,Av);
std::vector<double> grads;
std::vector<var> vars;
vars.push_back(Av(0).val_);
vars.push_back(Av(1).val_);
I.d_.grad(vars, grads);
EXPECT_FLOAT_EQ(3.2, grads[0]);
EXPECT_FLOAT_EQ(-0.8, grads[1]);
}
TEST(AgradMixMatrixTraceInvQuadFormLDLT,fv_exceptions) {
using stan::math::matrix_d;
using stan::math::vector_d;
using stan::math::row_vector_d;
using stan::math::matrix_fv;
using stan::math::vector_fv;
using stan::math::row_vector_fv;
matrix_fv fv1_(3,3), fv2_(4,4);
fv1_ << 1,2,3,4,5,6,7,8,9;
fv2_ << 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16;
row_vector_fv rvf1(3), rvf2(4);
rvf1.setZero();
rvf2.setZero();
vector_fv vf1(3), vf2(4);
vf1.setZero();
vf2.setZero();
matrix_d fd1_(3,3), fd2_(4,4);
fd1_ << 1,2,3,4,5,6,7,8,9;
fd2_ << 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16;
row_vector_d rvd1(3), rvd2(4);
rvd1.setZero();
rvd2.setZero();
vector_d vd1(3), vd2(4);
vd1.setZero();
vd2.setZero();
stan::math::LDLT_factor<fvar<var>,-1,-1> fv1;
stan::math::LDLT_factor<fvar<var>,-1,-1> fv2;
stan::math::LDLT_factor<double ,-1,-1> fd1;
stan::math::LDLT_factor<double ,-1,-1> fd2;
fv1.compute(fv1_);
fv2.compute(fv2_);
fd1.compute(fd1_);
fd2.compute(fd2_);
EXPECT_THROW(trace_inv_quad_form_ldlt(fv1, fd2_), std::invalid_argument);
EXPECT_THROW(trace_inv_quad_form_ldlt(fd1, fv2_), std::invalid_argument);
EXPECT_THROW(trace_inv_quad_form_ldlt(fv1, fv2_), std::invalid_argument);
EXPECT_THROW(trace_inv_quad_form_ldlt(fv1, fv2_), std::invalid_argument);
EXPECT_THROW(trace_inv_quad_form_ldlt(fv1, fd2_), std::invalid_argument);
EXPECT_THROW(trace_inv_quad_form_ldlt(fd1, fv2_), std::invalid_argument);
EXPECT_THROW(trace_inv_quad_form_ldlt(fv1, rvf2), std::invalid_argument);
EXPECT_THROW(trace_inv_quad_form_ldlt(fv1, rvf1), std::invalid_argument);
EXPECT_THROW(trace_inv_quad_form_ldlt(fv1, rvd2), std::invalid_argument);
EXPECT_THROW(trace_inv_quad_form_ldlt(fv1, rvd1), std::invalid_argument);
EXPECT_THROW(trace_inv_quad_form_ldlt(fv1, vf2), std::invalid_argument);
EXPECT_THROW(trace_inv_quad_form_ldlt(fv1, vd2), std::invalid_argument);
EXPECT_THROW(trace_inv_quad_form_ldlt(fv2, rvf2), std::invalid_argument);
EXPECT_THROW(trace_inv_quad_form_ldlt(fv2, rvf1), std::invalid_argument);
EXPECT_THROW(trace_inv_quad_form_ldlt(fv2, rvd2), std::invalid_argument);
EXPECT_THROW(trace_inv_quad_form_ldlt(fv2, rvd1), std::invalid_argument);
EXPECT_THROW(trace_inv_quad_form_ldlt(fv2, vf1), std::invalid_argument);
EXPECT_THROW(trace_inv_quad_form_ldlt(fv2, vd1), std::invalid_argument);
EXPECT_THROW(trace_inv_quad_form_ldlt(fd1, rvf2), std::invalid_argument);
EXPECT_THROW(trace_inv_quad_form_ldlt(fd1, rvf1), std::invalid_argument);
EXPECT_THROW(trace_inv_quad_form_ldlt(fd1, vf2), std::invalid_argument);
EXPECT_THROW(trace_inv_quad_form_ldlt(fd2, rvf2), std::invalid_argument);
EXPECT_THROW(trace_inv_quad_form_ldlt(fd2, rvf1), std::invalid_argument);
EXPECT_THROW(trace_inv_quad_form_ldlt(fd2, vf1), std::invalid_argument);
}
TEST(AgradMixMatrixTraceInvQuadFormLDLT,matrix_ffv_matrix_ffv_1) {
stan::math::LDLT_factor<fvar<fvar<var> >,-1,-1> ldlt_Ad;
stan::math::matrix_ffv Ad(2,2);
stan::math::matrix_ffv Av(2,2);
fvar<fvar<var> > I;
Ad << 2.0, 3.0,
3.0, 7.0;
Ad(0,0).d_.val_ = 1.0;
Ad(0,1).d_.val_ = 1.0;
Ad(1,0).d_.val_ = 1.0;
Ad(1,1).d_.val_ = 1.0;
Av << 2.0, 3.0,
5.0, 7.0;
Av(0,0).d_.val_ = 2.0;
Av(0,1).d_.val_ = 2.0;
Av(1,0).d_.val_ = 2.0;
Av(1,1).d_.val_ = 2.0;
ldlt_Ad.compute(Ad);
ASSERT_TRUE(ldlt_Ad.success());
I = trace_inv_quad_form_ldlt(ldlt_Ad,Ad);
EXPECT_FLOAT_EQ(9.0,I.val_.val_.val());
EXPECT_FLOAT_EQ(2.0,I.d_.val_.val());
I = trace_inv_quad_form_ldlt(ldlt_Ad,Av);
EXPECT_FLOAT_EQ(10.6,I.val_.val_.val());
EXPECT_FLOAT_EQ(5.04,I.d_.val_.val());
std::vector<double> grads;
std::vector<var> vars;
vars.push_back(Ad(0,0).val_.val_);
vars.push_back(Ad(0,1).val_.val_);
vars.push_back(Ad(1,0).val_.val_);
vars.push_back(Ad(1,1).val_.val_);
vars.push_back(Av(0,0).val_.val_);
vars.push_back(Av(0,1).val_.val_);
vars.push_back(Av(1,0).val_.val_);
vars.push_back(Av(1,1).val_.val_);
I.val_.val_.grad(vars, grads);
EXPECT_FLOAT_EQ(-0.04, grads[0]);
EXPECT_FLOAT_EQ(0, grads[1]);
EXPECT_FLOAT_EQ(0.32, grads[2]);
EXPECT_FLOAT_EQ(-1.64, grads[3]);
EXPECT_FLOAT_EQ(-0.4, grads[4]);
EXPECT_FLOAT_EQ(0, grads[5]);
EXPECT_FLOAT_EQ(1.6, grads[6]);
EXPECT_FLOAT_EQ(2, grads[7]);
}
TEST(AgradMixMatrixTraceInvQuadFormLDLT,matrix_ffv_matrix_ffv_2) {
stan::math::LDLT_factor<fvar<fvar<var> >,-1,-1> ldlt_Ad;
stan::math::matrix_ffv Ad(2,2);
stan::math::matrix_ffv Av(2,2);
fvar<fvar<var> > I;
Ad << 2.0, 3.0,
3.0, 7.0;
Ad(0,0).d_.val_ = 1.0;
Ad(0,1).d_.val_ = 1.0;
Ad(1,0).d_.val_ = 1.0;
Ad(1,1).d_.val_ = 1.0;
Av << 2.0, 3.0,
5.0, 7.0;
Av(0,0).d_.val_ = 2.0;
Av(0,1).d_.val_ = 2.0;
Av(1,0).d_.val_ = 2.0;
Av(1,1).d_.val_ = 2.0;
ldlt_Ad.compute(Ad);
ASSERT_TRUE(ldlt_Ad.success());
I = trace_inv_quad_form_ldlt(ldlt_Ad,Av);
std::vector<double> grads;
std::vector<var> vars;
vars.push_back(Ad(0,0).val_.val_);
vars.push_back(Ad(0,1).val_.val_);
vars.push_back(Ad(1,0).val_.val_);
vars.push_back(Ad(1,1).val_.val_);
vars.push_back(Av(0,0).val_.val_);
vars.push_back(Av(0,1).val_.val_);
vars.push_back(Av(1,0).val_.val_);
vars.push_back(Av(1,1).val_.val_);
I.d_.val_.grad(vars, grads);
EXPECT_FLOAT_EQ(0.448, grads[0]);
EXPECT_FLOAT_EQ(0, grads[1]);
EXPECT_FLOAT_EQ(-3.504, grads[2]);
EXPECT_FLOAT_EQ(0.848, grads[3]);
EXPECT_FLOAT_EQ(2.24, grads[4]);
EXPECT_FLOAT_EQ(1.6, grads[5]);
EXPECT_FLOAT_EQ(-0.56, grads[6]);
EXPECT_FLOAT_EQ(-0.4, grads[7]);
}
TEST(AgradMixMatrixTraceInvQuadFormLDLT,matrix_ffv_matrix_ffv_3) {
stan::math::LDLT_factor<fvar<fvar<var> >,-1,-1> ldlt_Ad;
stan::math::matrix_ffv Ad(2,2);
stan::math::matrix_ffv Av(2,2);
fvar<fvar<var> > I;
Ad << 2.0, 3.0,
3.0, 7.0;
Ad(0,0).d_.val_ = 1.0;
Ad(0,1).d_.val_ = 1.0;
Ad(1,0).d_.val_ = 1.0;
Ad(1,1).d_.val_ = 1.0;
Ad(0,0).val_.d_ = 1.0;
Ad(0,1).val_.d_ = 1.0;
Ad(1,0).val_.d_ = 1.0;
Ad(1,1).val_.d_ = 1.0;
Av << 2.0, 3.0,
5.0, 7.0;
Av(0,0).d_.val_ = 2.0;
Av(0,1).d_.val_ = 2.0;
Av(1,0).d_.val_ = 2.0;
Av(1,1).d_.val_ = 2.0;
Av(0,0).val_.d_ = 2.0;
Av(0,1).val_.d_ = 2.0;
Av(1,0).val_.d_ = 2.0;
Av(1,1).val_.d_ = 2.0;
ldlt_Ad.compute(Ad);
ASSERT_TRUE(ldlt_Ad.success());
I = trace_inv_quad_form_ldlt(ldlt_Ad,Av);
std::vector<double> grads;
std::vector<var> vars;
vars.push_back(Ad(0,0).val_.val_);
vars.push_back(Ad(0,1).val_.val_);
vars.push_back(Ad(1,0).val_.val_);
vars.push_back(Ad(1,1).val_.val_);
vars.push_back(Av(0,0).val_.val_);
vars.push_back(Av(0,1).val_.val_);
vars.push_back(Av(1,0).val_.val_);
vars.push_back(Av(1,1).val_.val_);
I.val_.d_.grad(vars, grads);
EXPECT_FLOAT_EQ(0.448, grads[0]);
EXPECT_FLOAT_EQ(0, grads[1]);
EXPECT_FLOAT_EQ(-3.504, grads[2]);
EXPECT_FLOAT_EQ(0.848, grads[3]);
EXPECT_FLOAT_EQ(2.24, grads[4]);
EXPECT_FLOAT_EQ(1.6, grads[5]);
EXPECT_FLOAT_EQ(-0.56, grads[6]);
EXPECT_FLOAT_EQ(-0.4, grads[7]);
}
TEST(AgradMixMatrixTraceInvQuadFormLDLT,matrix_ffv_matrix_ffv_4) {
stan::math::LDLT_factor<fvar<fvar<var> >,-1,-1> ldlt_Ad;
stan::math::matrix_ffv Ad(2,2);
stan::math::matrix_ffv Av(2,2);
fvar<fvar<var> > I;
Ad << 2.0, 3.0,
3.0, 7.0;
Ad(0,0).d_.val_ = 1.0;
Ad(0,1).d_.val_ = 1.0;
Ad(1,0).d_.val_ = 1.0;
Ad(1,1).d_.val_ = 1.0;
Ad(0,0).val_.d_ = 1.0;
Ad(0,1).val_.d_ = 1.0;
Ad(1,0).val_.d_ = 1.0;
Ad(1,1).val_.d_ = 1.0;
Av << 2.0, 3.0,
5.0, 7.0;
Av(0,0).d_.val_ = 2.0;
Av(0,1).d_.val_ = 2.0;
Av(1,0).d_.val_ = 2.0;
Av(1,1).d_.val_ = 2.0;
Av(0,0).val_.d_ = 2.0;
Av(0,1).val_.d_ = 2.0;
Av(1,0).val_.d_ = 2.0;
Av(1,1).val_.d_ = 2.0;
ldlt_Ad.compute(Ad);
ASSERT_TRUE(ldlt_Ad.success());
I = trace_inv_quad_form_ldlt(ldlt_Ad,Av);
std::vector<double> grads;
std::vector<var> vars;
vars.push_back(Ad(0,0).val_.val_);
vars.push_back(Ad(0,1).val_.val_);
vars.push_back(Ad(1,0).val_.val_);
vars.push_back(Ad(1,1).val_.val_);
vars.push_back(Av(0,0).val_.val_);
vars.push_back(Av(0,1).val_.val_);
vars.push_back(Av(1,0).val_.val_);
vars.push_back(Av(1,1).val_.val_);
I.d_.d_.grad(vars, grads);
EXPECT_FLOAT_EQ(-4.3263998, grads[0]);
EXPECT_FLOAT_EQ(0, grads[1]);
EXPECT_FLOAT_EQ(6.0991998, grads[2]);
EXPECT_FLOAT_EQ(-1.2544, grads[3]);
EXPECT_FLOAT_EQ(-2.688, grads[4]);
EXPECT_FLOAT_EQ(-1.92, grads[5]);
EXPECT_FLOAT_EQ(0.672, grads[6]);
EXPECT_FLOAT_EQ(0.48, grads[7]);
}
TEST(AgradMixMatrixTraceInvQuadFormLDLT,matrix_ffv_matrix_d_1) {
stan::math::LDLT_factor<fvar<fvar<var> >,-1,-1> ldlt_Ad;
stan::math::matrix_ffv Ad(2,2);
stan::math::matrix_d Av(2,2);
fvar<fvar<var> > I;
Ad << 2.0, 3.0,
3.0, 7.0;
Ad(0,0).d_.val_ = 1.0;
Ad(0,1).d_.val_ = 1.0;
Ad(1,0).d_.val_ = 1.0;
Ad(1,1).d_.val_ = 1.0;
Av << 2.0, 3.0,
5.0, 7.0;
ldlt_Ad.compute(Ad);
ASSERT_TRUE(ldlt_Ad.success());
I = trace_inv_quad_form_ldlt(ldlt_Ad,Av);
EXPECT_FLOAT_EQ(10.6,I.val_.val_.val());
EXPECT_FLOAT_EQ(-1.36,I.d_.val_.val());
std::vector<double> grads;
std::vector<var> vars;
vars.push_back(Ad(0,0).val_.val_);
vars.push_back(Ad(0,1).val_.val_);
vars.push_back(Ad(1,0).val_.val_);
vars.push_back(Ad(1,1).val_.val_);
I.val_.val_.grad(vars, grads);
EXPECT_FLOAT_EQ(-0.04, grads[0]);
EXPECT_FLOAT_EQ(0, grads[1]);
EXPECT_FLOAT_EQ(0.32, grads[2]);
EXPECT_FLOAT_EQ(-1.64, grads[3]);
}
TEST(AgradMixMatrixTraceInvQuadFormLDLT,matrix_ffv_matrix_d_2) {
stan::math::LDLT_factor<fvar<fvar<var> >,-1,-1> ldlt_Ad;
stan::math::matrix_ffv Ad(2,2);
stan::math::matrix_d Av(2,2);
fvar<fvar<var> > I;
Ad << 2.0, 3.0,
3.0, 7.0;
Ad(0,0).d_.val_ = 1.0;
Ad(0,1).d_.val_ = 1.0;
Ad(1,0).d_.val_ = 1.0;
Ad(1,1).d_.val_ = 1.0;
Av << 2.0, 3.0,
5.0, 7.0;
ldlt_Ad.compute(Ad);
ASSERT_TRUE(ldlt_Ad.success());
I = trace_inv_quad_form_ldlt(ldlt_Ad,Av);
std::vector<double> grads;
std::vector<var> vars;
vars.push_back(Ad(0,0).val_.val_);
vars.push_back(Ad(0,1).val_.val_);
vars.push_back(Ad(1,0).val_.val_);
vars.push_back(Ad(1,1).val_.val_);
I.d_.val_.grad(vars, grads);
EXPECT_FLOAT_EQ(-0.192, grads[0]);
EXPECT_FLOAT_EQ(0, grads[1]);
EXPECT_FLOAT_EQ(2.416, grads[2]);
EXPECT_FLOAT_EQ(-0.592, grads[3]);
}
TEST(AgradMixMatrixTraceInvQuadFormLDLT,matrix_ffv_matrix_d_3) {
stan::math::LDLT_factor<fvar<fvar<var> >,-1,-1> ldlt_Ad;
stan::math::matrix_ffv Ad(2,2);
stan::math::matrix_d Av(2,2);
fvar<fvar<var> > I;
Ad << 2.0, 3.0,
3.0, 7.0;
Ad(0,0).d_.val_ = 1.0;
Ad(0,1).d_.val_ = 1.0;
Ad(1,0).d_.val_ = 1.0;
Ad(1,1).d_.val_ = 1.0;
Ad(0,0).val_.d_ = 1.0;
Ad(0,1).val_.d_ = 1.0;
Ad(1,0).val_.d_ = 1.0;
Ad(1,1).val_.d_ = 1.0;
Av << 2.0, 3.0,
5.0, 7.0;
ldlt_Ad.compute(Ad);
ASSERT_TRUE(ldlt_Ad.success());
I = trace_inv_quad_form_ldlt(ldlt_Ad,Av);
std::vector<double> grads;
std::vector<var> vars;
vars.push_back(Ad(0,0).val_.val_);
vars.push_back(Ad(0,1).val_.val_);
vars.push_back(Ad(1,0).val_.val_);
vars.push_back(Ad(1,1).val_.val_);
I.val_.d_.grad(vars, grads);
EXPECT_FLOAT_EQ(-0.192, grads[0]);
EXPECT_FLOAT_EQ(0, grads[1]);
EXPECT_FLOAT_EQ(2.416, grads[2]);
EXPECT_FLOAT_EQ(-0.592, grads[3]);
}
TEST(AgradMixMatrixTraceInvQuadFormLDLT,matrix_ffv_matrix_d_4) {
stan::math::LDLT_factor<fvar<fvar<var> >,-1,-1> ldlt_Ad;
stan::math::matrix_ffv Ad(2,2);
stan::math::matrix_d Av(2,2);
fvar<fvar<var> > I;
Ad << 2.0, 3.0,
3.0, 7.0;
Ad(0,0).d_.val_ = 1.0;
Ad(0,1).d_.val_ = 1.0;
Ad(1,0).d_.val_ = 1.0;
Ad(1,1).d_.val_ = 1.0;
Ad(0,0).val_.d_ = 1.0;
Ad(0,1).val_.d_ = 1.0;
Ad(1,0).val_.d_ = 1.0;
Ad(1,1).val_.d_ = 1.0;
Av << 2.0, 3.0,
5.0, 7.0;
ldlt_Ad.compute(Ad);
ASSERT_TRUE(ldlt_Ad.success());
I = trace_inv_quad_form_ldlt(ldlt_Ad,Av);
std::vector<double> grads;
std::vector<var> vars;
vars.push_back(Ad(0,0).val_.val_);
vars.push_back(Ad(0,1).val_.val_);
vars.push_back(Ad(1,0).val_.val_);
vars.push_back(Ad(1,1).val_.val_);
I.d_.d_.grad(vars, grads);
EXPECT_FLOAT_EQ(-1.5104, grads[0]);
EXPECT_FLOAT_EQ(0, grads[1]);
EXPECT_FLOAT_EQ(-2.0288, grads[2]);
EXPECT_FLOAT_EQ(0.6016, grads[3]);
}
TEST(AgradMixMatrixTraceInvQuadFormLDLT,matrix_d_matrix_ffv_1) {
stan::math::LDLT_factor<double ,-1,-1> ldlt_Ad;
stan::math::matrix_d Ad(2,2);
stan::math::matrix_ffv Av(2,2);
fvar<fvar<var> > I;
Ad << 2.0, 3.0,
3.0, 7.0;
Av << 2.0, 3.0,
5.0, 7.0;
Av(0,0).d_.val_ = 2.0;
Av(0,1).d_.val_ = 2.0;
Av(1,0).d_.val_ = 2.0;
Av(1,1).d_.val_ = 2.0;
ldlt_Ad.compute(Ad);
ASSERT_TRUE(ldlt_Ad.success());
I = trace_inv_quad_form_ldlt(ldlt_Ad,Av);
EXPECT_FLOAT_EQ(10.6,I.val_.val_.val());
EXPECT_FLOAT_EQ(6.4,I.d_.val_.val());
std::vector<double> grads;
std::vector<var> vars;
vars.push_back(Av(0,0).val_.val_);
vars.push_back(Av(0,1).val_.val_);
vars.push_back(Av(1,0).val_.val_);
vars.push_back(Av(1,1).val_.val_);
I.val_.val_.grad(vars, grads);
EXPECT_FLOAT_EQ(-0.4, grads[0]);
EXPECT_FLOAT_EQ(0, grads[1]);
EXPECT_FLOAT_EQ(1.6, grads[2]);
EXPECT_FLOAT_EQ(2, grads[3]);
}
TEST(AgradMixMatrixTraceInvQuadFormLDLT,matrix_d_matrix_ffv_2) {
stan::math::LDLT_factor<double ,-1,-1> ldlt_Ad;
stan::math::matrix_d Ad(2,2);
stan::math::matrix_ffv Av(2,2);
fvar<fvar<var> > I;
Ad << 2.0, 3.0,
3.0, 7.0;
Av << 2.0, 3.0,
5.0, 7.0;
Av(0,0).d_.val_ = 2.0;
Av(0,1).d_.val_ = 2.0;
Av(1,0).d_.val_ = 2.0;
Av(1,1).d_.val_ = 2.0;
ldlt_Ad.compute(Ad);
ASSERT_TRUE(ldlt_Ad.success());
I = trace_inv_quad_form_ldlt(ldlt_Ad,Av);
std::vector<double> grads;
std::vector<var> vars;
vars.push_back(Av(0,0).val_.val_);
vars.push_back(Av(0,1).val_.val_);
vars.push_back(Av(1,0).val_.val_);
vars.push_back(Av(1,1).val_.val_);
I.d_.val_.grad(vars, grads);
EXPECT_FLOAT_EQ(3.2, grads[0]);
EXPECT_FLOAT_EQ(3.2, grads[1]);
EXPECT_FLOAT_EQ(-0.8, grads[2]);
EXPECT_FLOAT_EQ(-0.8, grads[3]);
}
TEST(AgradMixMatrixTraceInvQuadFormLDLT,matrix_d_matrix_ffv_3) {
stan::math::LDLT_factor<double ,-1,-1> ldlt_Ad;
stan::math::matrix_d Ad(2,2);
stan::math::matrix_ffv Av(2,2);
fvar<fvar<var> > I;
Ad << 2.0, 3.0,
3.0, 7.0;
Av << 2.0, 3.0,
5.0, 7.0;
Av(0,0).d_.val_ = 2.0;
Av(0,1).d_.val_ = 2.0;
Av(1,0).d_.val_ = 2.0;
Av(1,1).d_.val_ = 2.0;
Av(0,0).val_.d_ = 2.0;
Av(0,1).val_.d_ = 2.0;
Av(1,0).val_.d_ = 2.0;
Av(1,1).val_.d_ = 2.0;
ldlt_Ad.compute(Ad);
ASSERT_TRUE(ldlt_Ad.success());
I = trace_inv_quad_form_ldlt(ldlt_Ad,Av);
std::vector<double> grads;
std::vector<var> vars;
vars.push_back(Av(0,0).val_.val_);
vars.push_back(Av(0,1).val_.val_);
vars.push_back(Av(1,0).val_.val_);
vars.push_back(Av(1,1).val_.val_);
I.val_.d_.grad(vars, grads);
EXPECT_FLOAT_EQ(3.2, grads[0]);
EXPECT_FLOAT_EQ(3.2, grads[1]);
EXPECT_FLOAT_EQ(-0.8, grads[2]);
EXPECT_FLOAT_EQ(-0.8, grads[3]);
}
TEST(AgradMixMatrixTraceInvQuadFormLDLT,matrix_d_matrix_ffv_4) {
stan::math::LDLT_factor<double ,-1,-1> ldlt_Ad;
stan::math::matrix_d Ad(2,2);
stan::math::matrix_ffv Av(2,2);
fvar<fvar<var> > I;
Ad << 2.0, 3.0,
3.0, 7.0;
Av << 2.0, 3.0,
5.0, 7.0;
Av(0,0).d_.val_ = 2.0;
Av(0,1).d_.val_ = 2.0;
Av(1,0).d_.val_ = 2.0;
Av(1,1).d_.val_ = 2.0;
Av(0,0).val_.d_ = 2.0;
Av(0,1).val_.d_ = 2.0;
Av(1,0).val_.d_ = 2.0;
Av(1,1).val_.d_ = 2.0;
ldlt_Ad.compute(Ad);
ASSERT_TRUE(ldlt_Ad.success());
I = trace_inv_quad_form_ldlt(ldlt_Ad,Av);
std::vector<double> grads;
std::vector<var> vars;
vars.push_back(Av(0,0).val_.val_);
vars.push_back(Av(0,1).val_.val_);
vars.push_back(Av(1,0).val_.val_);
vars.push_back(Av(1,1).val_.val_);
I.d_.d_.grad(vars, grads);
EXPECT_FLOAT_EQ(0, grads[0]);
EXPECT_FLOAT_EQ(0, grads[1]);
EXPECT_FLOAT_EQ(0, grads[2]);
EXPECT_FLOAT_EQ(0, grads[3]);
}
TEST(AgradMixMatrixTraceInvQuadFormLDLT,matrix_ffv_vector_ffv_1) {
stan::math::LDLT_factor<fvar<fvar<var> >,-1,-1> ldlt_Ad;
stan::math::matrix_ffv Ad(2,2);
stan::math::vector_ffv Av(2);
fvar<fvar<var> > I;
Ad << 2.0, 3.0,
3.0, 7.0;
Ad(0,0).d_.val_ = 1.0;
Ad(0,1).d_.val_ = 1.0;
Ad(1,0).d_.val_ = 1.0;
Ad(1,1).d_.val_ = 1.0;
Av << 2.0, 3.0;
Av(0).d_.val_ = 2.0;
Av(1).d_.val_ = 2.0;
ldlt_Ad.compute(Ad);
ASSERT_TRUE(ldlt_Ad.success());
I = trace_inv_quad_form_ldlt(ldlt_Ad,Av);
EXPECT_FLOAT_EQ(2,I.val_.val_.val());
EXPECT_FLOAT_EQ(3,I.d_.val_.val());
std::vector<double> grads;
std::vector<var> vars;
vars.push_back(Ad(0,0).val_.val_);
vars.push_back(Ad(0,1).val_.val_);
vars.push_back(Ad(1,0).val_.val_);
vars.push_back(Ad(1,1).val_.val_);
vars.push_back(Av(0).val_.val_);
vars.push_back(Av(1).val_.val_);
I.val_.val_.grad(vars, grads);
EXPECT_FLOAT_EQ(-1, grads[0]);
EXPECT_FLOAT_EQ(0, grads[1]);
EXPECT_FLOAT_EQ(0, grads[2]);
EXPECT_NEAR(0, grads[3], 1E-12);
EXPECT_FLOAT_EQ(2, grads[4]);
EXPECT_FLOAT_EQ(0, grads[5]);
}
TEST(AgradMixMatrixTraceInvQuadFormLDLT,matrix_ffv_vector_ffv_2) {
stan::math::LDLT_factor<fvar<fvar<var> >,-1,-1> ldlt_Ad;
stan::math::matrix_ffv Ad(2,2);
stan::math::vector_ffv Av(2);
fvar<fvar<var> > I;
Ad << 2.0, 3.0,
3.0, 7.0;
Ad(0,0).d_.val_ = 1.0;
Ad(0,1).d_.val_ = 1.0;
Ad(1,0).d_.val_ = 1.0;
Ad(1,1).d_.val_ = 1.0;
Av << 2.0, 3.0;
Av(0).d_.val_ = 2.0;
Av(1).d_.val_ = 2.0;
ldlt_Ad.compute(Ad);
ASSERT_TRUE(ldlt_Ad.success());
I = trace_inv_quad_form_ldlt(ldlt_Ad,Av);
std::vector<double> grads;
std::vector<var> vars;
vars.push_back(Ad(0,0).val_.val_);
vars.push_back(Ad(0,1).val_.val_);
vars.push_back(Ad(1,0).val_.val_);
vars.push_back(Ad(1,1).val_.val_);
vars.push_back(Av(0).val_.val_);
vars.push_back(Av(1).val_.val_);
I.d_.val_.grad(vars, grads);
EXPECT_FLOAT_EQ(-1.6, grads[0]);
EXPECT_FLOAT_EQ(0, grads[1]);
EXPECT_FLOAT_EQ(0.4, grads[2]);
EXPECT_NEAR(0, grads[3], 1E-12);
EXPECT_FLOAT_EQ(1.6, grads[4]);
EXPECT_FLOAT_EQ(-0.4, grads[5]);
}
TEST(AgradMixMatrixTraceInvQuadFormLDLT,matrix_ffv_vector_ffv_3) {
stan::math::LDLT_factor<fvar<fvar<var> >,-1,-1> ldlt_Ad;
stan::math::matrix_ffv Ad(2,2);
stan::math::vector_ffv Av(2);
fvar<fvar<var> > I;
Ad << 2.0, 3.0,
3.0, 7.0;
Ad(0,0).d_.val_ = 1.0;
Ad(0,1).d_.val_ = 1.0;
Ad(1,0).d_.val_ = 1.0;
Ad(1,1).d_.val_ = 1.0;
Ad(0,0).val_.d_ = 1.0;
Ad(0,1).val_.d_ = 1.0;
Ad(1,0).val_.d_ = 1.0;
Ad(1,1).val_.d_ = 1.0;
Av << 2.0, 3.0;
Av(0).d_.val_ = 2.0;
Av(1).d_.val_ = 2.0;
Av(0).val_.d_ = 2.0;
Av(1).val_.d_ = 2.0;
ldlt_Ad.compute(Ad);
ASSERT_TRUE(ldlt_Ad.success());
I = trace_inv_quad_form_ldlt(ldlt_Ad,Av);
std::vector<double> grads;
std::vector<var> vars;
vars.push_back(Ad(0,0).val_.val_);
vars.push_back(Ad(0,1).val_.val_);
vars.push_back(Ad(1,0).val_.val_);
vars.push_back(Ad(1,1).val_.val_);
vars.push_back(Av(0).val_.val_);
vars.push_back(Av(1).val_.val_);
I.val_.d_.grad(vars, grads);
EXPECT_FLOAT_EQ(-1.6, grads[0]);
EXPECT_FLOAT_EQ(0, grads[1]);
EXPECT_FLOAT_EQ(0.4, grads[2]);
EXPECT_NEAR(0, grads[3], 1E-12);
EXPECT_FLOAT_EQ(1.6, grads[4]);
EXPECT_FLOAT_EQ(-0.4, grads[5]);
}
TEST(AgradMixMatrixTraceInvQuadFormLDLT,matrix_ffv_vector_ffv_4) {
stan::math::LDLT_factor<fvar<fvar<var> >,-1,-1> ldlt_Ad;
stan::math::matrix_ffv Ad(2,2);
stan::math::vector_ffv Av(2);
fvar<fvar<var> > I;
Ad << 2.0, 3.0,
3.0, 7.0;
Ad(0,0).d_.val_ = 1.0;
Ad(0,1).d_.val_ = 1.0;
Ad(1,0).d_.val_ = 1.0;
Ad(1,1).d_.val_ = 1.0;
Ad(0,0).val_.d_ = 1.0;
Ad(0,1).val_.d_ = 1.0;
Ad(1,0).val_.d_ = 1.0;
Ad(1,1).val_.d_ = 1.0;
Av << 2.0, 3.0;
Av(0).d_.val_ = 2.0;
Av(1).d_.val_ = 2.0;
Av(0).val_.d_ = 2.0;
Av(1).val_.d_ = 2.0;
ldlt_Ad.compute(Ad);
ASSERT_TRUE(ldlt_Ad.success());
I = trace_inv_quad_form_ldlt(ldlt_Ad,Av);
std::vector<double> grads;
std::vector<var> vars;
vars.push_back(Ad(0,0).val_.val_);
vars.push_back(Ad(0,1).val_.val_);
vars.push_back(Ad(1,0).val_.val_);
vars.push_back(Ad(1,1).val_.val_);
vars.push_back(Av(0).val_.val_);
vars.push_back(Av(1).val_.val_);
I.d_.d_.grad(vars, grads);
EXPECT_FLOAT_EQ(0.64, grads[0]);
EXPECT_FLOAT_EQ(0, grads[1]);
EXPECT_FLOAT_EQ(0.16, grads[2]);
EXPECT_FLOAT_EQ(-0.08, grads[3]);
EXPECT_FLOAT_EQ(-1.92, grads[4]);
EXPECT_FLOAT_EQ(0.48, grads[5]);
}
TEST(AgradMixMatrixTraceInvQuadFormLDLT,matrix_ffv_vector_d_1) {
stan::math::LDLT_factor<fvar<fvar<var> >,-1,-1> ldlt_Ad;
stan::math::matrix_ffv Ad(2,2);
stan::math::vector_d Av(2);
fvar<fvar<var> > I;
Ad << 2.0, 3.0,
3.0, 7.0;
Ad(0,0).d_.val_ = 1.0;
Ad(0,1).d_.val_ = 1.0;
Ad(1,0).d_.val_ = 1.0;
Ad(1,1).d_.val_ = 1.0;
Av << 2.0, 3.0;
ldlt_Ad.compute(Ad);
ASSERT_TRUE(ldlt_Ad.success());
I = trace_inv_quad_form_ldlt(ldlt_Ad,Av);
EXPECT_FLOAT_EQ(2,I.val_.val_.val());
EXPECT_FLOAT_EQ(-1,I.d_.val_.val());
std::vector<double> grads;
std::vector<var> vars;
vars.push_back(Ad(0,0).val_.val_);
vars.push_back(Ad(0,1).val_.val_);
vars.push_back(Ad(1,0).val_.val_);
vars.push_back(Ad(1,1).val_.val_);
I.val_.val_.grad(vars, grads);
EXPECT_FLOAT_EQ(-1, grads[0]);
EXPECT_FLOAT_EQ(0, grads[1]);
EXPECT_FLOAT_EQ(0, grads[2]);
EXPECT_NEAR(0, grads[3], 1E-12);
}
TEST(AgradMixMatrixTraceInvQuadFormLDLT,matrix_ffv_vector_d_2) {
stan::math::LDLT_factor<fvar<fvar<var> >,-1,-1> ldlt_Ad;
stan::math::matrix_ffv Ad(2,2);
stan::math::vector_d Av(2);
fvar<fvar<var> > I;
Ad << 2.0, 3.0,
3.0, 7.0;
Ad(0,0).d_.val_ = 1.0;
Ad(0,1).d_.val_ = 1.0;
Ad(1,0).d_.val_ = 1.0;
Ad(1,1).d_.val_ = 1.0;
Av << 2.0, 3.0;
ldlt_Ad.compute(Ad);
ASSERT_TRUE(ldlt_Ad.success());
I = trace_inv_quad_form_ldlt(ldlt_Ad,Av);
std::vector<double> grads;
std::vector<var> vars;
vars.push_back(Ad(0,0).val_.val_);
vars.push_back(Ad(0,1).val_.val_);
vars.push_back(Ad(1,0).val_.val_);
vars.push_back(Ad(1,1).val_.val_);
I.d_.val_.grad(vars, grads);
EXPECT_FLOAT_EQ(1.6, grads[0]);
EXPECT_FLOAT_EQ(0, grads[1]);
EXPECT_FLOAT_EQ(-0.4, grads[2]);
EXPECT_NEAR(0, grads[3], 1E-12);
}
TEST(AgradMixMatrixTraceInvQuadFormLDLT,matrix_ffv_vector_d_3) {
stan::math::LDLT_factor<fvar<fvar<var> >,-1,-1> ldlt_Ad;
stan::math::matrix_ffv Ad(2,2);
stan::math::vector_d Av(2);
fvar<fvar<var> > I;
Ad << 2.0, 3.0,
3.0, 7.0;
Ad(0,0).d_.val_ = 1.0;
Ad(0,1).d_.val_ = 1.0;
Ad(1,0).d_.val_ = 1.0;
Ad(1,1).d_.val_ = 1.0;
Ad(0,0).val_.d_ = 1.0;
Ad(0,1).val_.d_ = 1.0;
Ad(1,0).val_.d_ = 1.0;
Ad(1,1).val_.d_ = 1.0;
Av << 2.0, 3.0;
ldlt_Ad.compute(Ad);
ASSERT_TRUE(ldlt_Ad.success());
I = trace_inv_quad_form_ldlt(ldlt_Ad,Av);
std::vector<double> grads;
std::vector<var> vars;
vars.push_back(Ad(0,0).val_.val_);
vars.push_back(Ad(0,1).val_.val_);
vars.push_back(Ad(1,0).val_.val_);
vars.push_back(Ad(1,1).val_.val_);
I.val_.d_.grad(vars, grads);
EXPECT_FLOAT_EQ(1.6, grads[0]);
EXPECT_FLOAT_EQ(0, grads[1]);
EXPECT_FLOAT_EQ(-0.4, grads[2]);
EXPECT_NEAR(0, grads[3], 1E-12);
}
TEST(AgradMixMatrixTraceInvQuadFormLDLT,matrix_ffv_vector_d_4) {
stan::math::LDLT_factor<fvar<fvar<var> >,-1,-1> ldlt_Ad;
stan::math::matrix_ffv Ad(2,2);
stan::math::vector_d Av(2);
fvar<fvar<var> > I;
Ad << 2.0, 3.0,
3.0, 7.0;
Ad(0,0).d_.val_ = 1.0;
Ad(0,1).d_.val_ = 1.0;
Ad(1,0).d_.val_ = 1.0;
Ad(1,1).d_.val_ = 1.0;
Ad(0,0).val_.d_ = 1.0;
Ad(0,1).val_.d_ = 1.0;
Ad(1,0).val_.d_ = 1.0;
Ad(1,1).val_.d_ = 1.0;
Av << 2.0, 3.0;
ldlt_Ad.compute(Ad);
ASSERT_TRUE(ldlt_Ad.success());
I = trace_inv_quad_form_ldlt(ldlt_Ad,Av);
std::vector<double> grads;
std::vector<var> vars;
vars.push_back(Ad(0,0).val_.val_);
vars.push_back(Ad(0,1).val_.val_);
vars.push_back(Ad(1,0).val_.val_);
vars.push_back(Ad(1,1).val_.val_);
I.d_.d_.grad(vars, grads);
EXPECT_FLOAT_EQ(-3.2, grads[0]);
EXPECT_FLOAT_EQ(0, grads[1]);
EXPECT_FLOAT_EQ(1.12, grads[2]);
EXPECT_FLOAT_EQ(-0.08, grads[3]);
}
TEST(AgradMixMatrixTraceInvQuadFormLDLT,matrix_d_vector_ffv_1) {
stan::math::LDLT_factor<double,-1,-1> ldlt_Ad;
stan::math::matrix_d Ad(2,2);
stan::math::vector_ffv Av(2);
fvar<fvar<var> > I;
Ad << 2.0, 3.0,
3.0, 7.0;
Av << 2.0, 3.0;
Av(0).d_.val_ = 2.0;
Av(1).d_.val_ = 2.0;
ldlt_Ad.compute(Ad);
ASSERT_TRUE(ldlt_Ad.success());
I = trace_inv_quad_form_ldlt(ldlt_Ad,Av);
EXPECT_FLOAT_EQ(2,I.val_.val_.val());
EXPECT_FLOAT_EQ(4,I.d_.val_.val());
std::vector<double> grads;
std::vector<var> vars;
vars.push_back(Av(0).val_.val_);
vars.push_back(Av(1).val_.val_);
I.val_.val_.grad(vars, grads);
EXPECT_FLOAT_EQ(2, grads[0]);
EXPECT_FLOAT_EQ(0, grads[1]);
}
TEST(AgradMixMatrixTraceInvQuadFormLDLT,matrix_d_vector_ffv_2) {
stan::math::LDLT_factor<double,-1,-1> ldlt_Ad;
stan::math::matrix_d Ad(2,2);
stan::math::vector_ffv Av(2);
fvar<fvar<var> > I;
Ad << 2.0, 3.0,
3.0, 7.0;
Av << 2.0, 3.0;
Av(0).d_.val_ = 2.0;
Av(1).d_.val_ = 2.0;
ldlt_Ad.compute(Ad);
ASSERT_TRUE(ldlt_Ad.success());
I = trace_inv_quad_form_ldlt(ldlt_Ad,Av);
std::vector<double> grads;
std::vector<var> vars;
vars.push_back(Av(0).val_.val_);
vars.push_back(Av(1).val_.val_);
I.d_.val_.grad(vars, grads);
EXPECT_FLOAT_EQ(3.2, grads[0]);
EXPECT_FLOAT_EQ(-0.8, grads[1]);
}
TEST(AgradMixMatrixTraceInvQuadFormLDLT,matrix_d_vector_ffv_3) {
stan::math::LDLT_factor<double,-1,-1> ldlt_Ad;
stan::math::matrix_d Ad(2,2);
stan::math::vector_ffv Av(2);
fvar<fvar<var> > I;
Ad << 2.0, 3.0,
3.0, 7.0;
Av << 2.0, 3.0;
Av(0).d_.val_ = 2.0;
Av(1).d_.val_ = 2.0;
Av(0).val_.d_ = 2.0;
Av(1).val_.d_ = 2.0;
ldlt_Ad.compute(Ad);
ASSERT_TRUE(ldlt_Ad.success());
I = trace_inv_quad_form_ldlt(ldlt_Ad,Av);
std::vector<double> grads;
std::vector<var> vars;
vars.push_back(Av(0).val_.val_);
vars.push_back(Av(1).val_.val_);
I.val_.d_.grad(vars, grads);
EXPECT_FLOAT_EQ(3.2, grads[0]);
EXPECT_FLOAT_EQ(-0.8, grads[1]);
}
TEST(AgradMixMatrixTraceInvQuadFormLDLT,matrix_d_vector_ffv_4) {
stan::math::LDLT_factor<double,-1,-1> ldlt_Ad;
stan::math::matrix_d Ad(2,2);
stan::math::vector_ffv Av(2);
fvar<fvar<var> > I;
Ad << 2.0, 3.0,
3.0, 7.0;
Av << 2.0, 3.0;
Av(0).d_.val_ = 2.0;
Av(1).d_.val_ = 2.0;
Av(0).val_.d_ = 2.0;
Av(1).val_.d_ = 2.0;
ldlt_Ad.compute(Ad);
ASSERT_TRUE(ldlt_Ad.success());
I = trace_inv_quad_form_ldlt(ldlt_Ad,Av);
std::vector<double> grads;
std::vector<var> vars;
vars.push_back(Av(0).val_.val_);
vars.push_back(Av(1).val_.val_);
I.d_.d_.grad(vars, grads);
EXPECT_FLOAT_EQ(0, grads[0]);
EXPECT_FLOAT_EQ(0, grads[1]);
}
TEST(AgradMixMatrixTraceInvQuadFormLDLT,ffv_exceptions) {
using stan::math::matrix_d;
using stan::math::vector_d;
using stan::math::row_vector_d;
using stan::math::matrix_ffv;
using stan::math::vector_ffv;
using stan::math::row_vector_ffv;
matrix_ffv fv1_(3,3), fv2_(4,4);
fv1_ << 1,2,3,4,5,6,7,8,9;
fv2_ << 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16;
row_vector_ffv rvf1(3), rvf2(4);
rvf1.setZero();
rvf2.setZero();
vector_ffv vf1(3), vf2(4);
vf1.setZero();
vf2.setZero();
matrix_d fd1_(3,3), fd2_(4,4);
fd1_ << 1,2,3,4,5,6,7,8,9;
fd2_ << 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16;
row_vector_d rvd1(3), rvd2(4);
rvd1.setZero();
rvd2.setZero();
vector_d vd1(3), vd2(4);
vd1.setZero();
vd2.setZero();
stan::math::LDLT_factor<fvar<fvar<var> >,-1,-1> fv1;
stan::math::LDLT_factor<fvar<fvar<var> >,-1,-1> fv2;
stan::math::LDLT_factor<double ,-1,-1> fd1;
stan::math::LDLT_factor<double ,-1,-1> fd2;
fv1.compute(fv1_);
fv2.compute(fv2_);
fd1.compute(fd1_);
fd2.compute(fd2_);
EXPECT_THROW(trace_inv_quad_form_ldlt(fv1, fd2_), std::invalid_argument);
EXPECT_THROW(trace_inv_quad_form_ldlt(fd1, fv2_), std::invalid_argument);
EXPECT_THROW(trace_inv_quad_form_ldlt(fv1, fv2_), std::invalid_argument);
EXPECT_THROW(trace_inv_quad_form_ldlt(fv1, fv2_), std::invalid_argument);
EXPECT_THROW(trace_inv_quad_form_ldlt(fv1, fd2_), std::invalid_argument);
EXPECT_THROW(trace_inv_quad_form_ldlt(fd1, fv2_), std::invalid_argument);
EXPECT_THROW(trace_inv_quad_form_ldlt(fv1, rvf2), std::invalid_argument);
EXPECT_THROW(trace_inv_quad_form_ldlt(fv1, rvf1), std::invalid_argument);
EXPECT_THROW(trace_inv_quad_form_ldlt(fv1, rvd2), std::invalid_argument);
EXPECT_THROW(trace_inv_quad_form_ldlt(fv1, rvd1), std::invalid_argument);
EXPECT_THROW(trace_inv_quad_form_ldlt(fv1, vf2), std::invalid_argument);
EXPECT_THROW(trace_inv_quad_form_ldlt(fv1, vd2), std::invalid_argument);
EXPECT_THROW(trace_inv_quad_form_ldlt(fv2, rvf2), std::invalid_argument);
EXPECT_THROW(trace_inv_quad_form_ldlt(fv2, rvf1), std::invalid_argument);
EXPECT_THROW(trace_inv_quad_form_ldlt(fv2, rvd2), std::invalid_argument);
EXPECT_THROW(trace_inv_quad_form_ldlt(fv2, rvd1), std::invalid_argument);
EXPECT_THROW(trace_inv_quad_form_ldlt(fv2, vf1), std::invalid_argument);
EXPECT_THROW(trace_inv_quad_form_ldlt(fv2, vd1), std::invalid_argument);
EXPECT_THROW(trace_inv_quad_form_ldlt(fd1, rvf2), std::invalid_argument);
EXPECT_THROW(trace_inv_quad_form_ldlt(fd1, rvf1), std::invalid_argument);
EXPECT_THROW(trace_inv_quad_form_ldlt(fd1, vf2), std::invalid_argument);
EXPECT_THROW(trace_inv_quad_form_ldlt(fd2, rvf2), std::invalid_argument);
EXPECT_THROW(trace_inv_quad_form_ldlt(fd2, rvf1), std::invalid_argument);
EXPECT_THROW(trace_inv_quad_form_ldlt(fd2, vf1), std::invalid_argument);
}
|
#include "stdfsc.h"
#include "fstype.h"
#include "fslist.h"
/////////////////////////////////////////////////////////////////////
// CFSBitSet
void CFSBitSet::Reserve(INTPTR ipSize)
{
ASSERT(ipSize>=0);
m_Array.Reserve((ipSize+31)/32);
}
void CFSBitSet::SetSize(INTPTR ipSize, bool bReserveMore)
{
ASSERT(ipSize>=0);
m_ipSize=ipSize;
m_Array.SetSize((m_ipSize+31)/32, bReserveMore);
int iBit=(int)(m_ipSize%32);
if (iBit) {
m_Array[m_Array.GetSize()-1]=(m_Array[m_Array.GetSize()-1]<<(32-iBit))>>(32-iBit);
}
}
INTPTR CFSBitSet::GetSetCount(bool bBit) const
{
INTPTR ipCount=0;
for (INTPTR ip=0; ip<m_Array.GetSize(); ip++){
UINT32 ui=m_Array[ip];
ui=ui-((ui>>1)&0x55555555);
ui=(ui&0x33333333)+((ui>>2)&0x33333333);
ipCount+=(((ui+(ui>>4))&0xF0F0F0F)*0x1010101)>>24;
}
return (bBit ? ipCount : GetSize()-ipCount);
}
bool CFSBitSet::operator [](INTPTR ipIndex) const
{
ASSERT(ipIndex>=0 && ipIndex<m_ipSize);
return (m_Array[ipIndex/32]&(1<<(ipIndex%32)))!=0;
}
void CFSBitSet::Set(INTPTR ipIndex, bool bBit)
{
ASSERT(ipIndex>=0 && ipIndex<m_ipSize);
if (bBit) {
m_Array[ipIndex/32]|=(1<<(ipIndex%32));
}
else {
m_Array[ipIndex/32]&=~(1<<(ipIndex%32));
}
}
bool CFSBitSet::operator ==(const CFSBitSet &BitSet) const
{
if (GetSize()!=BitSet.GetSize()) {
return false;
}
for (INTPTR ip=0; ip<m_Array.GetSize(); ip++) {
if (m_Array[ip]!=BitSet.m_Array[ip]) {
return false;
}
}
return true;
}
CFSBitSet &CFSBitSet::operator |=(const CFSBitSet &BitSet)
{
if (BitSet.GetSize()>GetSize()) {
SetSize(BitSet.GetSize());
}
for (INTPTR ip=0; ip<BitSet.m_Array.GetSize(); ip++) {
m_Array[ip]|=BitSet.m_Array[ip];
}
return *this;
}
CFSBitSet &CFSBitSet::operator &=(const CFSBitSet &BitSet)
{
if (BitSet.GetSize()<GetSize()) {
SetSize(BitSet.GetSize());
}
for (INTPTR ip=0; ip<m_Array.GetSize(); ip++) {
m_Array[ip]&=BitSet.m_Array[ip];
}
return *this;
}
CFSStream &operator<<(CFSStream &Stream, const CFSBitSet &BitSet)
{
Stream << (UINTPTR)BitSet.m_ipSize;
for (INTPTR ip=0; ip<BitSet.m_Array.GetSize(); ip++) {
Stream << BitSet.m_Array[ip];
}
return Stream;
}
CFSStream &operator>>(CFSStream &Stream, CFSBitSet &BitSet)
{
INTPTR ipSize;
Stream >> (UINTPTR &)ipSize;
if (ipSize<0) {
throw CFSFileException(CFSFileException::INVALIDDATA);
}
BitSet.SetSize(ipSize, false);
for (INTPTR ip=0; ip<BitSet.m_Array.GetSize(); ip++) {
Stream >> BitSet.m_Array[ip];
}
return Stream;
}
/////////////////////////////////////////////////////////////////////
// CFSSorter
void CFSSorter::SelectionSort(INTPTR ipStart, INTPTR ipEnd)
{
for (INTPTR ip=ipStart; ip<ipEnd; ip++){
INTPTR ipMinimal=ip;
for (INTPTR ip2=ip+1; ip2<=ipEnd; ip2++){
if (IsLessThan(ip2, ipMinimal)) {
ipMinimal=ip2;
}
}
if (ipMinimal!=ip) {
Swap(ip, ipMinimal);
}
}
}
void CFSSorter::GnomeSort(INTPTR ipStart, INTPTR ipEnd)
{
INTPTR ipCurr=ipStart+1;
INTPTR ipNext=ipCurr+1;
while (ipCurr<=ipEnd) {
if (IsLessThan(ipCurr, ipCurr-1)) {
Swap(ipCurr-1, ipCurr);
ipCurr--;
if (ipCurr<=ipStart) {
ipCurr=ipNext;
ipNext++;
}
}
else {
ipCurr=ipNext;
ipNext++;
}
}
}
void CFSSorter::IntroSort(INTPTR ipStart, INTPTR ipEnd)
{
int iLevel=0;
for (INTPTR ipSize=ipEnd-ipStart+1; ipSize>0; ipSize/=2) {
iLevel++;
}
IntroSort(ipStart, ipEnd, FSMAX(50, iLevel*2));
}
void CFSSorter::IntroSort(INTPTR ipStart, INTPTR ipEnd, int iLevel)
{
if (ipStart>=ipEnd) {
return;
}
if (iLevel<=0) {
HeapSort(ipStart, ipEnd);
return;
}
INTPTR ipLow=ipStart;
INTPTR ipMid=(ipStart+ipEnd)/2;
INTPTR ipHigh=ipEnd;
do {
while (IsLessThan(ipLow, ipMid)) {
ipLow++;
}
while (IsLessThan(ipMid, ipHigh)) {
ipHigh--;
}
if (ipLow<=ipHigh) {
Swap(ipLow, ipHigh);
if (ipMid==ipLow) ipMid=ipHigh;
else if (ipMid==ipHigh) ipMid=ipLow;
ipLow++; ipHigh--;
}
} while (ipLow<=ipHigh);
IntroSort(ipStart, ipHigh, iLevel-1);
IntroSort(ipLow, ipEnd, iLevel-1);
}
void CFSSorter::HeapSort(INTPTR ipStart, INTPTR ipEnd)
{
HeapBuild(ipStart, ipEnd);
while (ipEnd>ipStart) {
Swap(ipStart, ipEnd);
ipEnd--;
HeapDown(ipStart, ipEnd, 0);
}
}
void CFSSorter::HeapBuild(INTPTR ipStart, INTPTR ipEnd)
{
for (INTPTR ip=(ipEnd-ipStart+1)/2-1; ip>=0; ip--) {
HeapDown(ipStart, ipEnd, ip);
}
}
void CFSSorter::HeapDown(INTPTR ipStart, INTPTR ipEnd, INTPTR ipIndex)
{
INTPTR ipHeapLength=ipEnd-ipStart+1;
INTPTR ipIndex2=ipIndex*2+1;
while (ipIndex2<ipHeapLength) {
if (ipIndex2+1<ipHeapLength && IsLessThan(ipStart+ipIndex2, ipStart+ipIndex2+1)) {
ipIndex2++;
}
if (!IsLessThan(ipStart+ipIndex, ipStart+ipIndex2)) {
return;
}
Swap(ipStart+ipIndex, ipStart+ipIndex2);
ipIndex=ipIndex2;
ipIndex2=ipIndex*2+1;
}
}
|
/*
* Copyright 2009-2017 Alibaba Cloud 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 <alibabacloud/polardb/model/ModifyDBNodeClassResult.h>
#include <json/json.h>
using namespace AlibabaCloud::Polardb;
using namespace AlibabaCloud::Polardb::Model;
ModifyDBNodeClassResult::ModifyDBNodeClassResult() :
ServiceResult()
{}
ModifyDBNodeClassResult::ModifyDBNodeClassResult(const std::string &payload) :
ServiceResult()
{
parse(payload);
}
ModifyDBNodeClassResult::~ModifyDBNodeClassResult()
{}
void ModifyDBNodeClassResult::parse(const std::string &payload)
{
Json::Reader reader;
Json::Value value;
reader.parse(payload, value);
setRequestId(value["RequestId"].asString());
if(!value["DBClusterId"].isNull())
dBClusterId_ = value["DBClusterId"].asString();
if(!value["OrderId"].isNull())
orderId_ = value["OrderId"].asString();
}
std::string ModifyDBNodeClassResult::getDBClusterId()const
{
return dBClusterId_;
}
std::string ModifyDBNodeClassResult::getOrderId()const
{
return orderId_;
}
|
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) Lewis Baker
// Licenced under MIT license. See LICENSE.txt for details.
///////////////////////////////////////////////////////////////////////////////
#include <cppcoro/async_mutex.hpp>
#include <cassert>
cppcoro::async_mutex::async_mutex() noexcept
: m_state(not_locked)
, m_waiters(nullptr)
{}
cppcoro::async_mutex::~async_mutex()
{
[[maybe_unused]] auto state = m_state.load(std::memory_order_relaxed);
assert(state == not_locked || state == locked_no_waiters);
assert(m_waiters == nullptr);
}
bool cppcoro::async_mutex::try_lock() noexcept
{
// Try to atomically transition from nullptr (not-locked) -> this (locked-no-waiters).
auto oldState = not_locked;
return m_state.compare_exchange_strong(
oldState,
locked_no_waiters,
std::memory_order_acquire,
std::memory_order_relaxed);
}
cppcoro::async_mutex_lock_operation cppcoro::async_mutex::lock_async() noexcept
{
return async_mutex_lock_operation{ *this };
}
cppcoro::async_mutex_scoped_lock_operation cppcoro::async_mutex::scoped_lock_async() noexcept
{
return async_mutex_scoped_lock_operation{ *this };
}
void cppcoro::async_mutex::unlock()
{
assert(m_state.load(std::memory_order_relaxed) != not_locked);
async_mutex_lock_operation* waitersHead = m_waiters;
if (waitersHead == nullptr)
{
auto oldState = locked_no_waiters;
const bool releasedLock = m_state.compare_exchange_strong(
oldState,
not_locked,
std::memory_order_release,
std::memory_order_relaxed);
if (releasedLock)
{
return;
}
// At least one new waiter.
// Acquire the list of new waiter operations atomically.
oldState = m_state.exchange(locked_no_waiters, std::memory_order_acquire);
assert(oldState != locked_no_waiters && oldState != not_locked);
// Transfer the list to m_waiters, reversing the list in the process so
// that the head of the list is the first to be resumed.
auto* next = reinterpret_cast<async_mutex_lock_operation*>(oldState);
do
{
auto* temp = next->m_next;
next->m_next = waitersHead;
waitersHead = next;
next = temp;
} while (next != nullptr);
}
assert(waitersHead != nullptr);
m_waiters = waitersHead->m_next;
// Resume the waiter.
// This will pass the ownership of the lock on to that operation/coroutine.
waitersHead->m_awaiter.resume();
}
bool cppcoro::async_mutex_lock_operation::await_suspend(cppcoro::coroutine_handle<> awaiter) noexcept
{
m_awaiter = awaiter;
std::uintptr_t oldState = m_mutex.m_state.load(std::memory_order_acquire);
while (true)
{
if (oldState == async_mutex::not_locked)
{
if (m_mutex.m_state.compare_exchange_weak(
oldState,
async_mutex::locked_no_waiters,
std::memory_order_acquire,
std::memory_order_relaxed))
{
// Acquired lock, don't suspend.
return false;
}
}
else
{
// Try to push this operation onto the head of the waiter stack.
m_next = reinterpret_cast<async_mutex_lock_operation*>(oldState);
if (m_mutex.m_state.compare_exchange_weak(
oldState,
reinterpret_cast<std::uintptr_t>(this),
std::memory_order_release,
std::memory_order_relaxed))
{
// Queued operation to waiters list, suspend now.
return true;
}
}
}
}
|
// Copyright (c) 2018+ lriki. Distributed under the MIT license..
#pragma once
#include "Common.hpp"
#include "Plane.hpp"
namespace ln {
struct Matrix;
struct Box;
/** 交差判定の結果を表します。 */
enum class IntersectResult
{
/** 領域の外側にある */
Outside,
/** 領域の内側にある */
Inside,
/** 領域の境界上にある (交差している) */
Intersect,
};
/**
* 3D の視錐台を定義します。
*
* 視錐台は主に 3D 空間上のカメラの視野を表すために使用します。
* カメラを表すビュープロジェクション行列から作成できます。
*
* 視錐台の外側にあるオブジェクトは通常、レンダリングする必要はありません。
* intersects() を使用して視錐台とオブジェクトの交差判定 (内側に存在するか) を行うことで、レンダリングが必要かをチェックできます。
*/
struct LN_API ViewFrustum
{
public:
/** デフォルトコンストラクタ。作成された視錐台は大きさを持ちません。*/
ViewFrustum();
/**
* 指定されたビュープロジェクション行列を使用して初期化します。
* @param[in] viewProjMatrix : 視錐台の生成に使用するビュープロジェクション行列
*/
ViewFrustum(const Matrix& viewProjMatrix);
public:
/**
* 指定されたビュープロジェクション行列を使用してこの視錐台を再構築します。
* @param[in] viewProjMatrix : 視錐台の生成に使用するビュープロジェクション行列
*/
void setViewProjMatrix(const Matrix& viewProjMatrix);
/**
* 指定した点がこの視錐台の内側にあるかを判定します。
* @param[in] point : 判定する点
* @return 点が内側にある場合は true、そうでない場合は false。
*/
bool intersects(const Vector3& point) const;
/**
* 指定した球がこの視錐台と交差するかを判定します。
* @param[in] center : 球の中心点
* @param[in] radius : 球の半径
* @return 交差する場合は true、そうでない場合は false。(接触している場合も true)
*/
bool intersects(const Vector3& center, float radius) const;
/**
* 指定した Box がこの視錐台と交差するかを判定します。
*/
IntersectResult intersects(const Box& box) const;
/**
* 錐台の各頂点を取得します。
* @param[out] points : 頂点座標を格納する配列 (要素数は 8 であること)
* 頂点の順番は、Near平面の左上、右上、右下、左下、Far平面の左上、右上、右下、左下です。
*/
void getCornerPoints(Vector3* points) const;
/**
* 錐台の指定した面を取得します。
* @param[in] plane : 取得する面
*/
const Plane& plane(FrustumPlane plane) const { return m_planes[static_cast<int>(plane)]; }
private:
static const int FrustumPlane_Max = 6;
Plane m_planes[FrustumPlane_Max];
Matrix m_viewProjMatrix;
};
} // namespace ln
|
#ifndef PROTEAN_DETAIL_XML_UTILITY_HPP
#define PROTEAN_DETAIL_XML_UTILITY_HPP
#include <protean/config.hpp>
#include <protean/detail/xerces_include.hpp>
#include <string>
namespace protean {
class variant;
namespace detail {
struct xml_utility
{
static bool is_ws(const XMLCh* const arg);
static std::string transcode(const XMLCh* const arg);
static void get_attributes(const xercesc::Attributes& attrs, variant& result);
static std::string escape_chars(const std::string& arg);
static void check_invalid_chars(const std::string& arg);
};
}} // protean::detail
#endif // PROTEAN_DETAIL_XML_UTILITY_HPP
|
#include "LoCameraFiducialMap.h"
#include "Affine.h"
#include "CameraGroundMap.h"
#include "CameraSkyMap.h"
#include "IString.h"
using namespace std;
namespace Isis {
/** Constructs mapping between Lunar Orbiter detectors and focal plane x/y.
* This method sets the x-axis direction to -1 if the NAIF IK code is even
* and to 1 if the code is odd.
*
* @param inst Instrument group from the Pvl labels
* @param naifIkCode Naif code of the Lunar Orbiter instrument for reading coefficients
*
*/
LoCameraFiducialMap::LoCameraFiducialMap(PvlGroup &inst, const int naifIkCode) {
// Get the Instrument label information needed to define the fiducial map for this frame
p_naifIkCode = naifIkCode;
ReadFiducials(inst);
// Set the x-axis direction. The medium camera is reversed.
int xdir;
if(naifIkCode % 2 == 0) {
xdir = -1;
}
else {
xdir = 1;
}
CreateTrans(xdir);
}
/**
*
* Reads the fiducials from the instrument group of the labels
* @param inst Instrument group from the Pvl labels
*
* @throws IException::User - "Unable to read fiducial mapping from cube
* labels - Input cube must be processed in Isis 2 through
* lofixlabel and converted to Isis 3 with pds2isis"
*/
void LoCameraFiducialMap::ReadFiducials(PvlGroup &inst) {
// Try to read the fiducials from the labels
try {
// Fiducial mapping to define the Focal Plane map
PvlKeyword &fSamps = inst["FiducialSamples"];
PvlKeyword &fLines = inst["FiducialLines"];
PvlKeyword &fXs = inst["FiducialXCoordinates"];
PvlKeyword &fYs = inst["FiducialYCoordinates"];
for(int i = 0; i < fSamps.size(); i++) {
p_fidSamples.push_back(toDouble(fSamps[i]));
p_fidLines.push_back(toDouble(fLines[i]));
p_fidXCoords.push_back(toDouble(fXs[i]));
p_fidYCoords.push_back(toDouble(fYs[i]));
}
}
catch(IException &e) {
string msg = "Unable to read fiducial mapping from cube labels - ";
msg += "Input cube must be processed in Isis 2 through lofixlabel ";
msg += "and converted to Isis 3 with pds2isis";
throw IException(e, IException::User, msg, _FILEINFO_);
}
}
/**
* Creates focal plane affine transform.
* @param xdir The x-axis direction.
*
*
* @throws IException::User - "Unable to create fiducial map."
*/
void LoCameraFiducialMap::CreateTrans(int xdir) {
// Setup focal plane map
Affine *fptrans = new Affine();
try {
fptrans->Solve(&p_fidSamples[0], (double *) &p_fidLines[0],
(double *) &p_fidXCoords[0], (double *) &p_fidYCoords[0],
p_fidSamples.size());
}
catch(IException &e) {
string msg = "Unable to create fiducial map.";
throw IException(IException::User, msg, _FILEINFO_);
}
// Get the coefficients
vector<double> transx;
vector<double> transy;
transx = fptrans->Coefficients(1);
transy = fptrans->Coefficients(2);
// Medium camera has a reversed x-axis
for(int icoef = 0; icoef < 3; icoef++) {
transx[icoef] *= xdir;
};
// Correct the Affine order - move the constant to the front
transx.insert(transx.begin(), transx[2]);
transx.pop_back();
transy.insert(transy.begin(), transy[2]);
transy.pop_back();
string icode = "INS" + IString(p_naifIkCode);
string icodex = icode + "_TRANSX";
string icodey = icode + "_TRANSY";
pdpool_c(icodex.c_str(), 3, (double( *)) &transx[0]);
pdpool_c(icodey.c_str(), 3, (double( *)) &transy[0]);
vector<double> transs;
vector<double> transl;
transs = fptrans->InverseCoefficients(1);
transl = fptrans->InverseCoefficients(2);
// Correct the Affine order - move the constant to the front
transs.insert(transs.begin(), transs[2]);
transs.pop_back();
transl.insert(transl.begin(), transl[2]);
transl.pop_back();
// Medium camera has a reversed x-axis
transs[1] *= xdir;
transl[1] *= xdir;
string icodes = icode + "_ITRANSS";
string icodel = icode + "_ITRANSL";
pdpool_c(icodes.c_str(), 3, (double( *)) &transs[0]);
pdpool_c(icodel.c_str(), 3, (double( *)) &transl[0]);
}
}
|
//
// detail/impl/select_reactor.ipp
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2015 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// 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)
//
#ifndef ASIO_DETAIL_IMPL_SELECT_REACTOR_IPP
#define ASIO_DETAIL_IMPL_SELECT_REACTOR_IPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include "asio/detail/config.hpp"
#if defined(ASIO_HAS_IOCP) \
|| (!defined(ASIO_HAS_DEV_POLL) \
&& !defined(ASIO_HAS_EPOLL) \
&& !defined(ASIO_HAS_KQUEUE) \
&& !defined(ASIO_WINDOWS_RUNTIME))
#include "asio/detail/bind_handler.hpp"
#include "asio/detail/fd_set_adapter.hpp"
#include "asio/detail/select_reactor.hpp"
#include "asio/detail/signal_blocker.hpp"
#include "asio/detail/socket_ops.hpp"
#include "asio/detail/push_options.hpp"
namespace asio {
namespace detail {
select_reactor::select_reactor(asio::io_service& io_service)
: asio::detail::service_base<select_reactor>(io_service),
io_service_(use_service<io_service_impl>(io_service)),
mutex_(),
interrupter_(),
#if defined(ASIO_HAS_IOCP)
stop_thread_(false),
thread_(0),
#endif // defined(ASIO_HAS_IOCP)
shutdown_(false)
{
#if defined(ASIO_HAS_IOCP)
asio::detail::signal_blocker sb;
thread_ = new asio::detail::thread(
bind_handler(&select_reactor::call_run_thread, this));
#endif // defined(ASIO_HAS_IOCP)
}
select_reactor::~select_reactor()
{
shutdown_service();
}
void select_reactor::shutdown_service()
{
asio::detail::mutex::scoped_lock lock(mutex_);
shutdown_ = true;
#if defined(ASIO_HAS_IOCP)
stop_thread_ = true;
#endif // defined(ASIO_HAS_IOCP)
lock.unlock();
#if defined(ASIO_HAS_IOCP)
if (thread_)
{
interrupter_.interrupt();
thread_->join();
delete thread_;
thread_ = 0;
}
#endif // defined(ASIO_HAS_IOCP)
op_queue<operation> ops;
for (int i = 0; i < max_ops; ++i)
op_queue_[i].get_all_operations(ops);
timer_queues_.get_all_timers(ops);
io_service_.abandon_operations(ops);
}
void select_reactor::fork_service(asio::io_service::fork_event fork_ev)
{
if (fork_ev == asio::io_service::fork_child)
interrupter_.recreate();
}
void select_reactor::init_task()
{
io_service_.init_task();
}
int select_reactor::register_descriptor(socket_type,
select_reactor::per_descriptor_data&)
{
return 0;
}
int select_reactor::register_internal_descriptor(
int op_type, socket_type descriptor,
select_reactor::per_descriptor_data&, reactor_op* op)
{
asio::detail::mutex::scoped_lock lock(mutex_);
op_queue_[op_type].enqueue_operation(descriptor, op);
interrupter_.interrupt();
return 0;
}
void select_reactor::move_descriptor(socket_type,
select_reactor::per_descriptor_data&,
select_reactor::per_descriptor_data&)
{
}
void select_reactor::start_op(int op_type, socket_type descriptor,
select_reactor::per_descriptor_data&, reactor_op* op,
bool is_continuation, bool)
{
asio::detail::mutex::scoped_lock lock(mutex_);
if (shutdown_)
{
post_immediate_completion(op, is_continuation);
return;
}
bool first = op_queue_[op_type].enqueue_operation(descriptor, op);
io_service_.work_started();
if (first)
interrupter_.interrupt();
}
void select_reactor::cancel_ops(socket_type descriptor,
select_reactor::per_descriptor_data&)
{
asio::detail::mutex::scoped_lock lock(mutex_);
cancel_ops_unlocked(descriptor, asio::error::operation_aborted);
}
void select_reactor::deregister_descriptor(socket_type descriptor,
select_reactor::per_descriptor_data&, bool)
{
asio::detail::mutex::scoped_lock lock(mutex_);
cancel_ops_unlocked(descriptor, asio::error::operation_aborted);
}
void select_reactor::deregister_internal_descriptor(
socket_type descriptor, select_reactor::per_descriptor_data&)
{
asio::detail::mutex::scoped_lock lock(mutex_);
op_queue<operation> ops;
for (int i = 0; i < max_ops; ++i)
op_queue_[i].cancel_operations(descriptor, ops);
}
void select_reactor::run(bool block, op_queue<operation>& ops)
{
asio::detail::mutex::scoped_lock lock(mutex_);
#if defined(ASIO_HAS_IOCP)
// Check if the thread is supposed to stop.
if (stop_thread_)
return;
#endif // defined(ASIO_HAS_IOCP)
// Set up the descriptor sets.
for (int i = 0; i < max_select_ops; ++i)
fd_sets_[i].reset();
fd_sets_[read_op].set(interrupter_.read_descriptor());
socket_type max_fd = 0;
bool have_work_to_do = !timer_queues_.all_empty();
for (int i = 0; i < max_select_ops; ++i)
{
have_work_to_do = have_work_to_do || !op_queue_[i].empty();
fd_sets_[i].set(op_queue_[i], ops);
if (fd_sets_[i].max_descriptor() > max_fd)
max_fd = fd_sets_[i].max_descriptor();
}
#if defined(ASIO_WINDOWS)
// Connection operations on Windows use both except and write fd_sets.
have_work_to_do = have_work_to_do || !op_queue_[connect_op].empty();
fd_sets_[write_op].set(op_queue_[connect_op], ops);
if (fd_sets_[write_op].max_descriptor() > max_fd)
max_fd = fd_sets_[write_op].max_descriptor();
fd_sets_[except_op].set(op_queue_[connect_op], ops);
if (fd_sets_[except_op].max_descriptor() > max_fd)
max_fd = fd_sets_[except_op].max_descriptor();
#endif // defined(ASIO_WINDOWS)
// We can return immediately if there's no work to do and the reactor is
// not supposed to block.
if (!block && !have_work_to_do)
return;
// Determine how long to block while waiting for events.
timeval tv_buf = { 0, 0 };
timeval* tv = block ? get_timeout(tv_buf) : &tv_buf;
lock.unlock();
// Block on the select call until descriptors become ready.
asio::error_code ec;
int retval = socket_ops::select(static_cast<int>(max_fd + 1),
fd_sets_[read_op], fd_sets_[write_op], fd_sets_[except_op], tv, ec);
// Reset the interrupter.
if (retval > 0 && fd_sets_[read_op].is_set(interrupter_.read_descriptor()))
{
interrupter_.reset();
--retval;
}
lock.lock();
// Dispatch all ready operations.
if (retval > 0)
{
#if defined(ASIO_WINDOWS)
// Connection operations on Windows use both except and write fd_sets.
fd_sets_[except_op].perform(op_queue_[connect_op], ops);
fd_sets_[write_op].perform(op_queue_[connect_op], ops);
#endif // defined(ASIO_WINDOWS)
// Exception operations must be processed first to ensure that any
// out-of-band data is read before normal data.
for (int i = max_select_ops - 1; i >= 0; --i)
fd_sets_[i].perform(op_queue_[i], ops);
}
timer_queues_.get_ready_timers(ops);
}
void select_reactor::interrupt()
{
interrupter_.interrupt();
}
#if defined(ASIO_HAS_IOCP)
void select_reactor::run_thread()
{
asio::detail::mutex::scoped_lock lock(mutex_);
while (!stop_thread_)
{
lock.unlock();
op_queue<operation> ops;
run(true, ops);
io_service_.post_deferred_completions(ops);
lock.lock();
}
}
void select_reactor::call_run_thread(select_reactor* reactor)
{
reactor->run_thread();
}
#endif // defined(ASIO_HAS_IOCP)
void select_reactor::do_add_timer_queue(timer_queue_base& queue)
{
mutex::scoped_lock lock(mutex_);
timer_queues_.insert(&queue);
}
void select_reactor::do_remove_timer_queue(timer_queue_base& queue)
{
mutex::scoped_lock lock(mutex_);
timer_queues_.erase(&queue);
}
timeval* select_reactor::get_timeout(timeval& tv)
{
// By default we will wait no longer than 5 minutes. This will ensure that
// any changes to the system clock are detected after no longer than this.
long usec = timer_queues_.wait_duration_usec(5 * 60 * 1000 * 1000);
tv.tv_sec = usec / 1000000;
tv.tv_usec = usec % 1000000;
return &tv;
}
void select_reactor::cancel_ops_unlocked(socket_type descriptor,
const asio::error_code& ec)
{
bool need_interrupt = false;
op_queue<operation> ops;
for (int i = 0; i < max_ops; ++i)
need_interrupt = op_queue_[i].cancel_operations(
descriptor, ops, ec) || need_interrupt;
io_service_.post_deferred_completions(ops);
if (need_interrupt)
interrupter_.interrupt();
}
} // namespace detail
} // namespace asio
#include "asio/detail/pop_options.hpp"
#endif // defined(ASIO_HAS_IOCP)
// || (!defined(ASIO_HAS_DEV_POLL)
// && !defined(ASIO_HAS_EPOLL)
// && !defined(ASIO_HAS_KQUEUE))
// && !defined(ASIO_WINDOWS_RUNTIME))
#endif // ASIO_DETAIL_IMPL_SELECT_REACTOR_IPP
|
#ifndef JAMSCRIPT_JAMSCRIPT_SPINLOCK_HH
#define JAMSCRIPT_JAMSCRIPT_SPINLOCK_HH
#include <atomic>
namespace jamc
{
class SpinMutex
{
std::atomic_flag flag = ATOMIC_FLAG_INIT;
public:
void lock();
bool try_lock();
void unlock();
};
class SpinOnlyMutex
{
std::atomic_flag flag = ATOMIC_FLAG_INIT;
public:
void lock();
bool try_lock();
void unlock();
};
} // namespace jamc
#endif
|
#include <cstddef>
namespace Dummy {
void AddByElement(const float *a, const float *b, float *result, const size_t count) {
for (size_t i = 0; i < count; i++) {
result[i] = a[i] + b[i];
}
}
} // namespace Dummy
|
/*
* Copyright (c) 2021 WangBin <wbsecg1 at gmail.com>
*/
#if __has_include("dav1d/dav1d.h")
#include "dav1d/dav1d.h"
#include <cassert>
#include "cppcompat/cstdlib.hpp"
#if defined(_WIN32)
# include <windows.h>
# ifdef WINAPI_FAMILY
# include <winapifamily.h>
# if !WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP)
# define DAV1D_WINRT 1
# endif
# endif
# if (DAV1D_WINRT+0)
# define dlopen(filename, flags) LoadPackagedLibrary(filename, 0)
# else
# define dlopen(filename, flags) LoadLibrary(filename)
# endif
# define dlsym(handle, symbol) GetProcAddress((HMODULE)handle, symbol)
# define dlclose(handle) FreeLibrary((HMODULE)handle)
#else
# include <dlfcn.h>
#endif
using dav1d_free_callback_t = void(*)(const uint8_t *buf, void *cookie);
#define DAV1D_ARG0() (), (), ()
#define DAV1D_ARG1(P1) (P1), (P1 p1), (p1)
#define DAV1D_ARG2(P1, P2) (P1, P2), (P1 p1, P2 p2), (p1, p2)
#define DAV1D_ARG3(P1, P2, P3) (P1, P2, P3), (P1 p1, P2 p2, P3 p3), (p1, p2, p3)
#define DAV1D_ARG4(P1, P2, P3, P4) (P1, P2, P3, P4), (P1 p1, P2 p2, P3 p3, P4 p4), (p1, p2, p3, p4)
#define DAV1D_ARG5(P1, P2, P3, P4, P5) (P1, P2, P3, P4, P5), (P1 p1, P2 p2, P3 p3, P4 p4, P5 p5), (p1, p2, p3, p4, p5)
#define _DAV1D_API(...) DAV1D_API_EXPAND(__VA_ARGS__)
#define DAV1D_API_EXPAND(R, F, ARG_T, ARG_T_V, ARG_V) \
R F ARG_T_V { \
static auto fp = (decltype(&F))dlsym(load_dav1d(), #F); \
assert(fp && "Dav1d API NOT FOUND: " #F); \
return fp ARG_V; \
}
static auto load_dav1d(const char* mod = nullptr)->decltype(dlopen(nullptr, RTLD_LAZY))
{
const auto dso_default =
#if (_WIN32+0)
TEXT("libdav1d.dll")
#elif (__APPLE__+0)
"libdav1d.5.dylib"
#elif (__ANDROID__+0)
"libdav1d.so"
#else
"libdav1d.so.5"
#endif
;
const auto dso_env_a = std::getenv("DAV1D_LIB");
#if (_WIN32+0)
wchar_t dso_env_w[128+1]; // enough. strlen is not const expr
if (dso_env_a)
mbstowcs(dso_env_w, dso_env_a, strlen(dso_env_a)+1);
const auto dso_env = dso_env_a ? dso_env_w : nullptr;
#else
const auto dso_env = dso_env_a;
#endif
auto dso = dlopen(dso_env ? dso_env : dso_default, RTLD_NOW | RTLD_LOCAL);
return dso;
}
extern "C" {
_DAV1D_API(const char*, dav1d_version, DAV1D_ARG0())
_DAV1D_API(void, dav1d_default_settings, DAV1D_ARG1(Dav1dSettings*))
_DAV1D_API(int, dav1d_open, DAV1D_ARG2(Dav1dContext**, const Dav1dSettings*))
_DAV1D_API(int, dav1d_parse_sequence_header, DAV1D_ARG3(Dav1dSequenceHeader*, const uint8_t*, const size_t))
_DAV1D_API(int, dav1d_send_data, DAV1D_ARG2(Dav1dContext*, Dav1dData*))
_DAV1D_API(int, dav1d_get_picture, DAV1D_ARG2(Dav1dContext*, Dav1dPicture*))
_DAV1D_API(void, dav1d_close, DAV1D_ARG1(Dav1dContext**))
_DAV1D_API(void, dav1d_flush, DAV1D_ARG1(Dav1dContext*))
_DAV1D_API(uint8_t*, dav1d_data_create, DAV1D_ARG2(Dav1dData*, size_t))
_DAV1D_API(int, dav1d_data_wrap, DAV1D_ARG5(Dav1dData*, const uint8_t*, size_t, dav1d_free_callback_t, void*))
_DAV1D_API(int, dav1d_data_wrap_user_data, DAV1D_ARG4(Dav1dData*, const uint8_t *, dav1d_free_callback_t, void*))
_DAV1D_API(void, dav1d_data_unref, DAV1D_ARG1(Dav1dData*))
_DAV1D_API(void, dav1d_picture_unref, DAV1D_ARG1(Dav1dPicture*))
}
#endif //__has_include("dav1d/dav1d.h")
|
/*
* Copyright (c) 2020 MariaDB Corporation Ab
*
* Use of this software is governed by the Business Source License included
* in the LICENSE.TXT file and at www.mariadb.com/bsl11.
*
* Change Date: 2025-01-25
*
* On the date above, in accordance with the Business Source License, use
* of this software will be governed by version 2 or later of the General
* Public License.
*/
#include "columnstore.hh"
#include <map>
#include "csxml.hh"
using std::map;
using std::string;
using std::vector;
namespace
{
bool get_number(const char* zNumber, long* pNumber)
{
char* zEnd;
errno = 0;
long number = strtol(zNumber, &zEnd, 10);
bool valid = (errno == 0 && zEnd != zNumber && *zEnd == 0);
if (valid)
{
*pNumber = number;
}
return valid;
}
bool is_positive_number(const char* zNumber)
{
long number;
return get_number(zNumber, &number) && number > 0;
}
}
namespace cs
{
const char* to_string(Version version)
{
switch (version)
{
case CS_10:
return ZCS_10;
case CS_12:
return ZCS_12;
case CS_15:
return ZCS_15;
case CS_UNKNOWN:
return "unknown";
default:
mxb_assert(!true);
return "unknown";
}
}
const char* to_string(ClusterMode cluster_mode)
{
switch (cluster_mode)
{
case READONLY:
return "readonly";
case READWRITE:
return "readwrite";
default:
mxb_assert(!true);
return "unknown";
}
}
bool from_string(const char* zCluster_mode, ClusterMode* pCluster_mode)
{
bool rv = true;
if (strcmp(zCluster_mode, "readonly") == 0)
{
*pCluster_mode = READONLY;
}
else if (strcmp(zCluster_mode, "readwrite") == 0)
{
*pCluster_mode = READWRITE;
}
else
{
rv = false;
}
return rv;
}
const char* to_string(DbrmMode dbrm_mode)
{
switch (dbrm_mode)
{
case MASTER:
return "master";
case SLAVE:
return "slave";
default:
mxb_assert(!true);
return "unknown";
}
}
bool from_string(const char* zDbrm_mode, DbrmMode* pDbrm_mode)
{
bool rv = true;
if (strcmp(zDbrm_mode, "master") == 0)
{
*pDbrm_mode = MASTER;
}
else if (strcmp(zDbrm_mode, "slave") == 0)
{
*pDbrm_mode = SLAVE;
}
else
{
rv = false;
}
return rv;
}
const char* rest::to_string(rest::Action action)
{
switch (action)
{
case ADD_NODE:
return "add-node";
case BEGIN:
return "begin";
case COMMIT:
return "commit";
case CONFIG:
return "config";
case REMOVE_NODE:
return "remove-node";
case ROLLBACK:
return "rollback";
case SHUTDOWN:
return "shutdown";
case STATUS:
return "status";
case START:
return "start";
default:
mxb_assert(!true);
return "unknown";
}
}
bool from_string(const char* zXml, std::unique_ptr<xmlDoc>* psDoc)
{
psDoc->reset(xmlReadMemory(zXml, strlen(zXml), "columnstore.xml", NULL, 0));
return *psDoc ? true : false;
}
bool from_string(const char* zTimestamp, std::chrono::system_clock::time_point* pTimestamp)
{
struct tm tm;
bool rv = strptime(zTimestamp, "%Y-%m-%d %H:%M:%S", &tm) != nullptr;
if (rv)
{
*pTimestamp = std::chrono::system_clock::from_time_t(std::mktime(&tm));
}
return rv;
}
bool dbroots_from_array(json_t* pArray, DbRootIdVector* pDbroots)
{
bool rv = json_is_array(pArray);
if (rv)
{
DbRootIdVector dbroots;
size_t i;
json_t* pValue;
json_array_foreach(pArray, i, pValue)
{
dbroots.push_back(json_integer_value(json_array_get(pArray, i)));
}
pDbroots->swap(dbroots);
}
return rv;
}
bool services_from_array(json_t* pArray, ServiceVector* pServices)
{
bool rv = json_is_array(pArray);
if (rv)
{
ServiceVector services;
size_t i;
json_t* pService;
json_array_foreach(pArray, i, pService)
{
json_t* pName = json_object_get(pService, cs::body::NAME);
mxb_assert(pName);
json_t* pPid = json_object_get(pService, cs::body::PID);
mxb_assert(pPid);
if (pName && pPid)
{
auto zName = json_string_value(pName);
auto pid = json_integer_value(pPid);
services.emplace_back(zName, pid);
}
else
{
MXS_ERROR("Object in services array does not have 'name' and/or 'pid' fields.");
}
}
pServices->swap(services);
}
return rv;
}
string rest::create_url(const SERVER& server,
int64_t port,
const string& rest_base,
Scope scope,
rest::Action action)
{
string url("https://");
url += server.address();
url += ":";
url += std::to_string(port);
url += rest_base;
if (scope == NODE)
{
url += "/node/";
}
else
{
mxb_assert(scope == CLUSTER);
url += "/cluster/";
}
url += to_string(action);
return url;
}
namespace body
{
namespace
{
string begin_or_commit(const std::chrono::seconds& timeout, int id)
{
std::ostringstream body;
body << "{\"" << TIMEOUT << "\": "
<< timeout.count()
<< ", \"" << ID << "\": "
<< id
<< "}";
return body.str();
}
string start_or_shutdown(const std::chrono::seconds& timeout)
{
std::ostringstream body;
body << "{";
if (timeout.count() != 0)
{
body << "\"" << TIMEOUT << "\": " << timeout.count();
}
body << "}";
return body.str();
}
string add_or_remove_node(const std::string& node, const std::chrono::seconds& timeout)
{
std::ostringstream body;
body << "{\"" << TIMEOUT << "\": "
<< timeout.count()
<< ", \"" << NODE << "\": \""
<< node
<< "\"}";
return body.str();
}
}
string add_node(const std::string& node, const std::chrono::seconds& timeout)
{
return add_or_remove_node(node, timeout);
}
string begin(const std::chrono::seconds& timeout, int id)
{
return begin_or_commit(timeout, id);
}
string commit(const std::chrono::seconds& timeout, int id)
{
return begin_or_commit(timeout, id);
}
string config(const xmlDoc& csXml,
int revision,
const string& manager,
const std::chrono::seconds& timeout)
{
xmlChar* pConfig = nullptr;
int size = 0;
xmlDocDumpMemory(const_cast<xmlDoc*>(&csXml), &pConfig, &size);
json_t* pBody = json_object();
json_object_set_new(pBody, CONFIG, json_stringn(reinterpret_cast<const char*>(pConfig), size));
json_object_set_new(pBody, REVISION, json_integer(revision));
json_object_set_new(pBody, MANAGER, json_string(manager.c_str()));
json_object_set_new(pBody, TIMEOUT, json_integer(timeout.count()));
xmlFree(pConfig);
char* zBody = json_dumps(pBody, 0);
json_decref(pBody);
string body(zBody);
MXS_FREE(zBody);
return body;
}
std::string config_set_cluster_mode(ClusterMode mode,
int revision,
const std::string& manager,
const std::chrono::seconds& timeout)
{
std::ostringstream body;
body << "{"
<< "\"" << CLUSTER_MODE << "\": " << "\"" << cs::to_string(mode) << "\", "
<< "\"" << REVISION << "\": " << revision << ","
<< "\"" << TIMEOUT << "\": " << timeout.count() << ","
<< "\"" << MANAGER << "\": " << "\"" << manager << "\""
<< "}";
return body.str();
}
string remove_node(const std::string& node, const std::chrono::seconds& timeout)
{
return add_or_remove_node(node, timeout);
}
string rollback(int id)
{
std::ostringstream body;
body << "{"
<< "\"" << ID << "\": " << id
<< "}";
return body.str();
}
string shutdown(const std::chrono::seconds& timeout)
{
return start_or_shutdown(timeout);
}
string start(const std::chrono::seconds& timeout)
{
return start_or_shutdown(timeout);
}
}
}
|
// test_ssh_client.cpp
#include <ulib/file.h>
#include <ulib/ssh/net/sshsocket.h>
static const char* getArg(const char* param) { return (param && *param ? param : 0); }
int
U_EXPORT main (int argc, char* argv[])
{
U_ULIB_INIT(argv);
U_TRACE(5,"main(%d)",argc)
USSHSocket x;
UString hostname(argv[2]);
x.setVerbosity(4);
x.setUser(getArg(argv[1]));
x.setKey(getArg(argv[3]), getArg(argv[4]));
if (x.connectServer(hostname, 22))
{
UString dati = UFile::contentOf(UString(argv[5]));
const char* str = dati.data();
uint32_t size = dati.size();
if (x.send(str, size) == size)
{
cout.write(str, size);
cout << '\n';
x.sendEOF();
char buffer[4096];
while (true)
{
size = x.recv(buffer, sizeof(buffer));
if (size > 0)
{
cout.write(buffer, size);
continue;
}
if (size != sizeof(buffer)) break;
}
cout << '\n';
}
exit(0);
}
}
|
// 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 "components/autofill/core/browser/webdata/autofill_webdata_backend_impl.h"
#include <memory>
#include "base/bind.h"
#include "base/check_op.h"
#include "base/location.h"
#include "base/notreached.h"
#include "base/single_thread_task_runner.h"
#include "components/autofill/core/browser/data_model/autofill_offer_data.h"
#include "components/autofill/core/browser/data_model/autofill_profile.h"
#include "components/autofill/core/browser/data_model/credit_card.h"
#include "components/autofill/core/browser/data_model/credit_card_cloud_token_data.h"
#include "components/autofill/core/browser/geo/autofill_country.h"
#include "components/autofill/core/browser/payments/payments_customer_data.h"
#include "components/autofill/core/browser/webdata/autofill_change.h"
#include "components/autofill/core/browser/webdata/autofill_entry.h"
#include "components/autofill/core/browser/webdata/autofill_table.h"
#include "components/autofill/core/browser/webdata/autofill_webdata_backend_util.h"
#include "components/autofill/core/browser/webdata/autofill_webdata_service.h"
#include "components/autofill/core/browser/webdata/autofill_webdata_service_observer.h"
#include "components/autofill/core/common/form_field_data.h"
#include "components/webdata/common/web_database_backend.h"
using base::Time;
namespace autofill {
namespace {
WebDatabase::State DoNothingAndCommit(WebDatabase* db) {
return WebDatabase::COMMIT_NEEDED;
}
} // namespace
AutofillWebDataBackendImpl::AutofillWebDataBackendImpl(
scoped_refptr<WebDatabaseBackend> web_database_backend,
scoped_refptr<base::SingleThreadTaskRunner> ui_task_runner,
scoped_refptr<base::SingleThreadTaskRunner> db_task_runner,
const base::RepeatingClosure& on_changed_callback,
const base::RepeatingClosure& on_address_conversion_completed_callback,
const base::RepeatingCallback<void(syncer::ModelType)>&
on_sync_started_callback)
: base::RefCountedDeleteOnSequence<AutofillWebDataBackendImpl>(
std::move(db_task_runner)),
ui_task_runner_(ui_task_runner),
web_database_backend_(web_database_backend),
on_changed_callback_(on_changed_callback),
on_address_conversion_completed_callback_(
on_address_conversion_completed_callback),
on_sync_started_callback_(on_sync_started_callback) {}
void AutofillWebDataBackendImpl::AddObserver(
AutofillWebDataServiceObserverOnDBSequence* observer) {
DCHECK(owning_task_runner()->RunsTasksInCurrentSequence());
db_observer_list_.AddObserver(observer);
}
void AutofillWebDataBackendImpl::RemoveObserver(
AutofillWebDataServiceObserverOnDBSequence* observer) {
DCHECK(owning_task_runner()->RunsTasksInCurrentSequence());
db_observer_list_.RemoveObserver(observer);
}
AutofillWebDataBackendImpl::~AutofillWebDataBackendImpl() {
DCHECK(!user_data_); // Forgot to call ResetUserData?
}
void AutofillWebDataBackendImpl::SetAutofillProfileChangedCallback(
base::RepeatingCallback<void(const AutofillProfileDeepChange&)> change_cb) {
on_autofill_profile_changed_cb_ = std::move(change_cb);
}
WebDatabase* AutofillWebDataBackendImpl::GetDatabase() {
DCHECK(owning_task_runner()->RunsTasksInCurrentSequence());
return web_database_backend_->database();
}
void AutofillWebDataBackendImpl::CommitChanges() {
web_database_backend_->ExecuteWriteTask(base::BindOnce(&DoNothingAndCommit));
}
std::unique_ptr<WDTypedResult>
AutofillWebDataBackendImpl::RemoveExpiredAutocompleteEntries(WebDatabase* db) {
DCHECK(owning_task_runner()->RunsTasksInCurrentSequence());
AutofillChangeList changes;
if (AutofillTable::FromWebDatabase(db)->RemoveExpiredFormElements(&changes)) {
if (!changes.empty()) {
// Post the notifications including the list of affected keys.
// This is sent here so that work resulting from this notification
// will be done on the DB sequence, and not the UI sequence.
for (auto& db_observer : db_observer_list_)
db_observer.AutofillEntriesChanged(changes);
}
}
return std::make_unique<WDResult<size_t>>(AUTOFILL_CLEANUP_RESULT,
changes.size());
}
void AutofillWebDataBackendImpl::NotifyOfAutofillProfileChanged(
const AutofillProfileChange& change) {
DCHECK(owning_task_runner()->RunsTasksInCurrentSequence());
// DB sequence notification.
for (auto& db_observer : db_observer_list_)
db_observer.AutofillProfileChanged(change);
}
void AutofillWebDataBackendImpl::NotifyOfCreditCardChanged(
const CreditCardChange& change) {
DCHECK(owning_task_runner()->RunsTasksInCurrentSequence());
// DB sequence notification.
for (auto& db_observer : db_observer_list_)
db_observer.CreditCardChanged(change);
}
void AutofillWebDataBackendImpl::NotifyOfMultipleAutofillChanges() {
DCHECK(owning_task_runner()->RunsTasksInCurrentSequence());
// UI sequence notification.
ui_task_runner_->PostTask(FROM_HERE, on_changed_callback_);
}
void AutofillWebDataBackendImpl::NotifyOfAddressConversionCompleted() {
DCHECK(owning_task_runner()->RunsTasksInCurrentSequence());
// UI sequence notification.
ui_task_runner_->PostTask(FROM_HERE,
on_address_conversion_completed_callback_);
}
void AutofillWebDataBackendImpl::NotifyThatSyncHasStarted(
syncer::ModelType model_type) {
DCHECK(owning_task_runner()->RunsTasksInCurrentSequence());
if (on_sync_started_callback_.is_null())
return;
// UI sequence notification.
ui_task_runner_->PostTask(
FROM_HERE, base::BindOnce(on_sync_started_callback_, model_type));
}
base::SupportsUserData* AutofillWebDataBackendImpl::GetDBUserData() {
DCHECK(owning_task_runner()->RunsTasksInCurrentSequence());
if (!user_data_)
user_data_ = std::make_unique<SupportsUserDataAggregatable>();
return user_data_.get();
}
void AutofillWebDataBackendImpl::ResetUserData() {
user_data_.reset();
}
WebDatabase::State AutofillWebDataBackendImpl::AddFormElements(
const std::vector<FormFieldData>& fields,
WebDatabase* db) {
DCHECK(owning_task_runner()->RunsTasksInCurrentSequence());
AutofillChangeList changes;
if (!AutofillTable::FromWebDatabase(db)->AddFormFieldValues(fields,
&changes)) {
NOTREACHED();
return WebDatabase::COMMIT_NOT_NEEDED;
}
// Post the notifications including the list of affected keys.
// This is sent here so that work resulting from this notification will be
// done on the DB sequence, and not the UI sequence.
for (auto& db_observer : db_observer_list_)
db_observer.AutofillEntriesChanged(changes);
return WebDatabase::COMMIT_NEEDED;
}
std::unique_ptr<WDTypedResult>
AutofillWebDataBackendImpl::GetFormValuesForElementName(
const std::u16string& name,
const std::u16string& prefix,
int limit,
WebDatabase* db) {
DCHECK(owning_task_runner()->RunsTasksInCurrentSequence());
std::vector<AutofillEntry> entries;
AutofillTable::FromWebDatabase(db)->GetFormValuesForElementName(
name, prefix, &entries, limit);
return std::make_unique<WDResult<std::vector<AutofillEntry>>>(
AUTOFILL_VALUE_RESULT, entries);
}
WebDatabase::State AutofillWebDataBackendImpl::RemoveFormElementsAddedBetween(
const base::Time& delete_begin,
const base::Time& delete_end,
WebDatabase* db) {
DCHECK(owning_task_runner()->RunsTasksInCurrentSequence());
AutofillChangeList changes;
if (AutofillTable::FromWebDatabase(db)->RemoveFormElementsAddedBetween(
delete_begin, delete_end, &changes)) {
if (!changes.empty()) {
// Post the notifications including the list of affected keys.
// This is sent here so that work resulting from this notification
// will be done on the DB sequence, and not the UI sequence.
for (auto& db_observer : db_observer_list_)
db_observer.AutofillEntriesChanged(changes);
}
return WebDatabase::COMMIT_NEEDED;
}
return WebDatabase::COMMIT_NOT_NEEDED;
}
WebDatabase::State AutofillWebDataBackendImpl::RemoveFormValueForElementName(
const std::u16string& name,
const std::u16string& value,
WebDatabase* db) {
DCHECK(owning_task_runner()->RunsTasksInCurrentSequence());
if (AutofillTable::FromWebDatabase(db)->RemoveFormElement(name, value)) {
AutofillChangeList changes;
changes.push_back(
AutofillChange(AutofillChange::REMOVE, AutofillKey(name, value)));
// Post the notifications including the list of affected keys.
for (auto& db_observer : db_observer_list_)
db_observer.AutofillEntriesChanged(changes);
return WebDatabase::COMMIT_NEEDED;
}
return WebDatabase::COMMIT_NOT_NEEDED;
}
WebDatabase::State AutofillWebDataBackendImpl::AddAutofillProfile(
const AutofillProfile& profile,
WebDatabase* db) {
DCHECK(owning_task_runner()->RunsTasksInCurrentSequence());
if (!AutofillTable::FromWebDatabase(db)->AddAutofillProfile(profile)) {
NOTREACHED();
return WebDatabase::COMMIT_NOT_NEEDED;
}
// Send GUID-based notification.
AutofillProfileChange change(AutofillProfileChange::ADD, profile.guid(),
&profile);
for (auto& db_observer : db_observer_list_)
db_observer.AutofillProfileChanged(change);
if (!on_autofill_profile_changed_cb_.is_null()) {
ui_task_runner_->PostTask(
FROM_HERE, base::BindOnce(on_autofill_profile_changed_cb_,
AutofillProfileDeepChange(
AutofillProfileChange::ADD, profile)));
}
return WebDatabase::COMMIT_NEEDED;
}
WebDatabase::State AutofillWebDataBackendImpl::UpdateAutofillProfile(
const AutofillProfile& profile,
WebDatabase* db) {
DCHECK(owning_task_runner()->RunsTasksInCurrentSequence());
// Only perform the update if the profile exists. It is currently
// valid to try to update a missing profile. We simply drop the write and
// the caller will detect this on the next refresh.
std::unique_ptr<AutofillProfile> original_profile =
AutofillTable::FromWebDatabase(db)->GetAutofillProfile(profile.guid());
if (!original_profile) {
return WebDatabase::COMMIT_NOT_NEEDED;
}
if (!AutofillTable::FromWebDatabase(db)->UpdateAutofillProfile(profile)) {
NOTREACHED();
return WebDatabase::COMMIT_NEEDED;
}
// Send GUID-based notification.
AutofillProfileChange change(AutofillProfileChange::UPDATE, profile.guid(),
&profile);
for (auto& db_observer : db_observer_list_)
db_observer.AutofillProfileChanged(change);
if (!on_autofill_profile_changed_cb_.is_null()) {
ui_task_runner_->PostTask(
FROM_HERE, base::BindOnce(on_autofill_profile_changed_cb_,
AutofillProfileDeepChange(
AutofillProfileChange::UPDATE, profile)));
}
return WebDatabase::COMMIT_NEEDED;
}
WebDatabase::State AutofillWebDataBackendImpl::RemoveAutofillProfile(
const std::string& guid,
WebDatabase* db) {
DCHECK(owning_task_runner()->RunsTasksInCurrentSequence());
std::unique_ptr<AutofillProfile> profile =
AutofillTable::FromWebDatabase(db)->GetAutofillProfile(guid);
if (!profile) {
NOTREACHED();
return WebDatabase::COMMIT_NOT_NEEDED;
}
if (!AutofillTable::FromWebDatabase(db)->RemoveAutofillProfile(guid)) {
NOTREACHED();
return WebDatabase::COMMIT_NOT_NEEDED;
}
// Send GUID-based notification.
AutofillProfileChange change(AutofillProfileChange::REMOVE, guid,
profile.get());
for (auto& db_observer : db_observer_list_)
db_observer.AutofillProfileChanged(change);
if (!on_autofill_profile_changed_cb_.is_null()) {
ui_task_runner_->PostTask(
FROM_HERE,
base::BindOnce(on_autofill_profile_changed_cb_,
AutofillProfileDeepChange(AutofillProfileChange::REMOVE,
*profile.get())));
}
return WebDatabase::COMMIT_NEEDED;
}
std::unique_ptr<WDTypedResult> AutofillWebDataBackendImpl::GetAutofillProfiles(
WebDatabase* db) {
DCHECK(owning_task_runner()->RunsTasksInCurrentSequence());
std::vector<std::unique_ptr<AutofillProfile>> profiles;
AutofillTable::FromWebDatabase(db)->GetAutofillProfiles(&profiles);
return std::unique_ptr<WDTypedResult>(
new WDResult<std::vector<std::unique_ptr<AutofillProfile>>>(
AUTOFILL_PROFILES_RESULT, std::move(profiles)));
}
std::unique_ptr<WDTypedResult> AutofillWebDataBackendImpl::GetServerProfiles(
WebDatabase* db) {
DCHECK(owning_task_runner()->RunsTasksInCurrentSequence());
std::vector<std::unique_ptr<AutofillProfile>> profiles;
AutofillTable::FromWebDatabase(db)->GetServerProfiles(&profiles);
return std::unique_ptr<WDTypedResult>(
new WDResult<std::vector<std::unique_ptr<AutofillProfile>>>(
AUTOFILL_PROFILES_RESULT, std::move(profiles)));
}
WebDatabase::State
AutofillWebDataBackendImpl::ConvertWalletAddressesAndUpdateWalletCards(
const std::string& app_locale,
const std::string& primary_account_email,
WebDatabase* db) {
DCHECK(owning_task_runner()->RunsTasksInCurrentSequence());
return util::ConvertWalletAddressesAndUpdateWalletCards(
app_locale, primary_account_email, this, db);
}
std::unique_ptr<WDTypedResult>
AutofillWebDataBackendImpl::GetCountOfValuesContainedBetween(
const base::Time& begin,
const base::Time& end,
WebDatabase* db) {
DCHECK(owning_task_runner()->RunsTasksInCurrentSequence());
int value =
AutofillTable::FromWebDatabase(db)->GetCountOfValuesContainedBetween(
begin, end);
return std::unique_ptr<WDTypedResult>(
new WDResult<int>(AUTOFILL_VALUE_RESULT, value));
}
WebDatabase::State AutofillWebDataBackendImpl::UpdateAutofillEntries(
const std::vector<AutofillEntry>& autofill_entries,
WebDatabase* db) {
DCHECK(owning_task_runner()->RunsTasksInCurrentSequence());
if (!AutofillTable::FromWebDatabase(db)->UpdateAutofillEntries(
autofill_entries))
return WebDatabase::COMMIT_NOT_NEEDED;
return WebDatabase::COMMIT_NEEDED;
}
WebDatabase::State AutofillWebDataBackendImpl::AddCreditCard(
const CreditCard& credit_card,
WebDatabase* db) {
DCHECK(owning_task_runner()->RunsTasksInCurrentSequence());
if (!AutofillTable::FromWebDatabase(db)->AddCreditCard(credit_card)) {
NOTREACHED();
return WebDatabase::COMMIT_NOT_NEEDED;
}
for (auto& db_observer : db_observer_list_) {
db_observer.CreditCardChanged(CreditCardChange(
CreditCardChange::ADD, credit_card.guid(), &credit_card));
}
return WebDatabase::COMMIT_NEEDED;
}
WebDatabase::State AutofillWebDataBackendImpl::UpdateCreditCard(
const CreditCard& credit_card,
WebDatabase* db) {
DCHECK(owning_task_runner()->RunsTasksInCurrentSequence());
// It is currently valid to try to update a missing profile. We simply drop
// the write and the caller will detect this on the next refresh.
std::unique_ptr<CreditCard> original_credit_card =
AutofillTable::FromWebDatabase(db)->GetCreditCard(credit_card.guid());
if (!original_credit_card)
return WebDatabase::COMMIT_NOT_NEEDED;
if (!AutofillTable::FromWebDatabase(db)->UpdateCreditCard(credit_card)) {
NOTREACHED();
return WebDatabase::COMMIT_NOT_NEEDED;
}
for (auto& db_observer : db_observer_list_) {
db_observer.CreditCardChanged(CreditCardChange(
CreditCardChange::UPDATE, credit_card.guid(), &credit_card));
}
return WebDatabase::COMMIT_NEEDED;
}
WebDatabase::State AutofillWebDataBackendImpl::RemoveCreditCard(
const std::string& guid,
WebDatabase* db) {
DCHECK(owning_task_runner()->RunsTasksInCurrentSequence());
std::unique_ptr<CreditCard> card =
AutofillTable::FromWebDatabase(db)->GetCreditCard(guid);
if (!card) {
NOTREACHED();
return WebDatabase::COMMIT_NOT_NEEDED;
}
if (!AutofillTable::FromWebDatabase(db)->RemoveCreditCard(guid)) {
NOTREACHED();
return WebDatabase::COMMIT_NOT_NEEDED;
}
for (auto& db_observer : db_observer_list_) {
db_observer.CreditCardChanged(
CreditCardChange(CreditCardChange::REMOVE, guid, card.get()));
}
return WebDatabase::COMMIT_NEEDED;
}
WebDatabase::State AutofillWebDataBackendImpl::AddFullServerCreditCard(
const CreditCard& credit_card,
WebDatabase* db) {
DCHECK(owning_task_runner()->RunsTasksInCurrentSequence());
if (!AutofillTable::FromWebDatabase(db)->AddFullServerCreditCard(
credit_card)) {
NOTREACHED();
return WebDatabase::COMMIT_NOT_NEEDED;
}
for (auto& db_observer : db_observer_list_) {
db_observer.CreditCardChanged(CreditCardChange(
CreditCardChange::ADD, credit_card.guid(), &credit_card));
}
return WebDatabase::COMMIT_NEEDED;
}
std::unique_ptr<WDTypedResult> AutofillWebDataBackendImpl::GetCreditCards(
WebDatabase* db) {
DCHECK(owning_task_runner()->RunsTasksInCurrentSequence());
std::vector<std::unique_ptr<CreditCard>> credit_cards;
AutofillTable::FromWebDatabase(db)->GetCreditCards(&credit_cards);
return std::unique_ptr<WDTypedResult>(
new WDResult<std::vector<std::unique_ptr<CreditCard>>>(
AUTOFILL_CREDITCARDS_RESULT, std::move(credit_cards)));
}
std::unique_ptr<WDTypedResult> AutofillWebDataBackendImpl::GetServerCreditCards(
WebDatabase* db) {
DCHECK(owning_task_runner()->RunsTasksInCurrentSequence());
std::vector<std::unique_ptr<CreditCard>> credit_cards;
AutofillTable::FromWebDatabase(db)->GetServerCreditCards(&credit_cards);
return std::unique_ptr<WDTypedResult>(
new WDResult<std::vector<std::unique_ptr<CreditCard>>>(
AUTOFILL_CREDITCARDS_RESULT, std::move(credit_cards)));
}
WebDatabase::State AutofillWebDataBackendImpl::UnmaskServerCreditCard(
const CreditCard& card,
const std::u16string& full_number,
WebDatabase* db) {
DCHECK(owning_task_runner()->RunsTasksInCurrentSequence());
if (AutofillTable::FromWebDatabase(db)->UnmaskServerCreditCard(card,
full_number))
return WebDatabase::COMMIT_NEEDED;
return WebDatabase::COMMIT_NOT_NEEDED;
}
WebDatabase::State AutofillWebDataBackendImpl::MaskServerCreditCard(
const std::string& id,
WebDatabase* db) {
DCHECK(owning_task_runner()->RunsTasksInCurrentSequence());
if (AutofillTable::FromWebDatabase(db)->MaskServerCreditCard(id))
return WebDatabase::COMMIT_NEEDED;
return WebDatabase::COMMIT_NOT_NEEDED;
}
WebDatabase::State AutofillWebDataBackendImpl::UpdateServerCardMetadata(
const CreditCard& card,
WebDatabase* db) {
DCHECK(owning_task_runner()->RunsTasksInCurrentSequence());
DCHECK_NE(CreditCard::LOCAL_CARD, card.record_type());
if (!AutofillTable::FromWebDatabase(db)->UpdateServerCardMetadata(card))
return WebDatabase::COMMIT_NOT_NEEDED;
for (auto& db_observer : db_observer_list_) {
db_observer.CreditCardChanged(
CreditCardChange(CreditCardChange::UPDATE, card.server_id(), &card));
}
return WebDatabase::COMMIT_NEEDED;
}
WebDatabase::State AutofillWebDataBackendImpl::UpdateServerAddressMetadata(
const AutofillProfile& profile,
WebDatabase* db) {
DCHECK(owning_task_runner()->RunsTasksInCurrentSequence());
DCHECK_EQ(AutofillProfile::SERVER_PROFILE, profile.record_type());
if (!AutofillTable::FromWebDatabase(db)->UpdateServerAddressMetadata(
profile)) {
return WebDatabase::COMMIT_NOT_NEEDED;
}
for (auto& db_observer : db_observer_list_) {
db_observer.AutofillProfileChanged(AutofillProfileChange(
AutofillProfileChange::UPDATE, profile.server_id(), &profile));
}
return WebDatabase::COMMIT_NEEDED;
}
WebDatabase::State AutofillWebDataBackendImpl::AddUpiId(
const std::string& upi_id,
WebDatabase* db) {
DCHECK(owning_task_runner()->RunsTasksInCurrentSequence());
if (!AutofillTable::FromWebDatabase(db)->InsertUpiId(upi_id))
return WebDatabase::COMMIT_NOT_NEEDED;
return WebDatabase::COMMIT_NEEDED;
}
std::unique_ptr<WDTypedResult> AutofillWebDataBackendImpl::GetAllUpiIds(
WebDatabase* db) {
DCHECK(owning_task_runner()->RunsTasksInCurrentSequence());
std::vector<std::string> upi_ids =
AutofillTable::FromWebDatabase(db)->GetAllUpiIds();
return std::make_unique<WDResult<std::vector<std::string>>>(
AUTOFILL_UPI_RESULT, std::move(upi_ids));
}
std::unique_ptr<WDTypedResult>
AutofillWebDataBackendImpl::GetPaymentsCustomerData(WebDatabase* db) {
DCHECK(owning_task_runner()->RunsTasksInCurrentSequence());
std::unique_ptr<PaymentsCustomerData> customer_data;
AutofillTable::FromWebDatabase(db)->GetPaymentsCustomerData(&customer_data);
return std::make_unique<WDResult<std::unique_ptr<PaymentsCustomerData>>>(
AUTOFILL_CUSTOMERDATA_RESULT, std::move(customer_data));
}
std::unique_ptr<WDTypedResult>
AutofillWebDataBackendImpl::GetCreditCardCloudTokenData(WebDatabase* db) {
DCHECK(owning_task_runner()->RunsTasksInCurrentSequence());
std::vector<std::unique_ptr<CreditCardCloudTokenData>> cloud_token_data;
AutofillTable::FromWebDatabase(db)->GetCreditCardCloudTokenData(
&cloud_token_data);
return std::make_unique<
WDResult<std::vector<std::unique_ptr<CreditCardCloudTokenData>>>>(
AUTOFILL_CLOUDTOKEN_RESULT, std::move(cloud_token_data));
}
std::unique_ptr<WDTypedResult> AutofillWebDataBackendImpl::GetCreditCardOffers(
WebDatabase* db) {
DCHECK(owning_task_runner()->RunsTasksInCurrentSequence());
std::vector<std::unique_ptr<AutofillOfferData>> offers;
AutofillTable::FromWebDatabase(db)->GetCreditCardOffers(&offers);
return std::make_unique<
WDResult<std::vector<std::unique_ptr<AutofillOfferData>>>>(
AUTOFILL_OFFER_DATA, std::move(offers));
}
WebDatabase::State AutofillWebDataBackendImpl::ClearAllServerData(
WebDatabase* db) {
DCHECK(owning_task_runner()->RunsTasksInCurrentSequence());
if (AutofillTable::FromWebDatabase(db)->ClearAllServerData()) {
NotifyOfMultipleAutofillChanges();
return WebDatabase::COMMIT_NEEDED;
}
return WebDatabase::COMMIT_NOT_NEEDED;
}
WebDatabase::State AutofillWebDataBackendImpl::ClearAllLocalData(
WebDatabase* db) {
DCHECK(owning_task_runner()->RunsTasksInCurrentSequence());
if (AutofillTable::FromWebDatabase(db)->ClearAllLocalData()) {
NotifyOfMultipleAutofillChanges();
return WebDatabase::COMMIT_NEEDED;
}
return WebDatabase::COMMIT_NOT_NEEDED;
}
WebDatabase::State
AutofillWebDataBackendImpl::RemoveAutofillDataModifiedBetween(
const base::Time& delete_begin,
const base::Time& delete_end,
WebDatabase* db) {
DCHECK(owning_task_runner()->RunsTasksInCurrentSequence());
std::vector<std::unique_ptr<AutofillProfile>> profiles;
std::vector<std::unique_ptr<CreditCard>> credit_cards;
if (AutofillTable::FromWebDatabase(db)->RemoveAutofillDataModifiedBetween(
delete_begin, delete_end, &profiles, &credit_cards)) {
for (const std::unique_ptr<AutofillProfile>& profile : profiles) {
for (auto& db_observer : db_observer_list_) {
db_observer.AutofillProfileChanged(AutofillProfileChange(
AutofillProfileChange::REMOVE, profile->guid(), profile.get()));
}
}
for (const std::unique_ptr<CreditCard>& credit_card : credit_cards) {
for (auto& db_observer : db_observer_list_) {
db_observer.CreditCardChanged(CreditCardChange(
CreditCardChange::REMOVE, credit_card->guid(), credit_card.get()));
}
}
// Note: It is the caller's responsibility to post notifications for any
// changes, e.g. by calling the Refresh() method of PersonalDataManager.
return WebDatabase::COMMIT_NEEDED;
}
return WebDatabase::COMMIT_NOT_NEEDED;
}
WebDatabase::State AutofillWebDataBackendImpl::RemoveOriginURLsModifiedBetween(
const base::Time& delete_begin,
const base::Time& delete_end,
WebDatabase* db) {
DCHECK(owning_task_runner()->RunsTasksInCurrentSequence());
std::vector<std::unique_ptr<AutofillProfile>> profiles;
if (!AutofillTable::FromWebDatabase(db)->RemoveOriginURLsModifiedBetween(
delete_begin, delete_end, &profiles)) {
return WebDatabase::COMMIT_NOT_NEEDED;
}
for (const auto& profile : profiles) {
AutofillProfileChange change(AutofillProfileChange::UPDATE, profile->guid(),
profile.get());
for (auto& db_observer : db_observer_list_)
db_observer.AutofillProfileChanged(change);
}
// Note: It is the caller's responsibility to post notifications for any
// changes, e.g. by calling the Refresh() method of PersonalDataManager.
return WebDatabase::COMMIT_NEEDED;
}
WebDatabase::State AutofillWebDataBackendImpl::RemoveOrphanAutofillTableRows(
WebDatabase* db) {
DCHECK(owning_task_runner()->RunsTasksInCurrentSequence());
if (AutofillTable::FromWebDatabase(db)->RemoveOrphanAutofillTableRows()) {
return WebDatabase::COMMIT_NEEDED;
}
return WebDatabase::COMMIT_NOT_NEEDED;
}
} // namespace autofill
|
/*
* yosys -- Yosys Open SYnthesis Suite
*
* Copyright (C) 2012 Claire Xenia Wolf <claire@yosyshq.com>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
* ---
*
* This is the AST frontend library.
*
* The AST frontend library is not a frontend on it's own but provides a
* generic abstract syntax tree (AST) abstraction for HDL code and can be
* used by HDL frontends. See "ast.h" for an overview of the API and the
* Verilog frontend for an usage example.
*
*/
#include "kernel/log.h"
#include "libs/sha1/sha1.h"
#include "frontends/verilog/verilog_frontend.h"
#include "ast.h"
#include <sstream>
#include <stdarg.h>
#include <stdlib.h>
#include <math.h>
YOSYS_NAMESPACE_BEGIN
using namespace AST;
using namespace AST_INTERNAL;
// Process a format string and arguments for $display, $write, $sprintf, etc
std::string AstNode::process_format_str(const std::string &sformat, int next_arg, int stage, int width_hint, bool sign_hint) {
// Other arguments are placeholders. Process the string as we go through it
std::string sout;
for (size_t i = 0; i < sformat.length(); i++)
{
// format specifier
if (sformat[i] == '%')
{
// If there's no next character, that's a problem
if (i+1 >= sformat.length())
log_file_error(filename, location.first_line, "System task `%s' called with `%%' at end of string.\n", str.c_str());
char cformat = sformat[++i];
// %% is special, does not need a matching argument
if (cformat == '%')
{
sout += '%';
continue;
}
bool got_len = false;
bool got_zlen = false;
int len_value = 0;
while ('0' <= cformat && cformat <= '9')
{
if (!got_len && cformat == '0')
got_zlen = true;
got_len = true;
len_value = 10*len_value + (cformat - '0');
cformat = sformat[++i];
}
// Simplify the argument
AstNode *node_arg = nullptr;
// Everything from here on depends on the format specifier
switch (cformat)
{
case 's':
case 'S':
case 'd':
case 'D':
if (got_len && len_value != 0)
goto unsupported_format;
YS_FALLTHROUGH
case 'x':
case 'X':
if (next_arg >= GetSize(children))
log_file_error(filename, location.first_line, "Missing argument for %%%c format specifier in system task `%s'.\n",
cformat, str.c_str());
node_arg = children[next_arg++];
while (node_arg->simplify(true, false, false, stage, width_hint, sign_hint, false)) { }
if (node_arg->type != AST_CONSTANT)
log_file_error(filename, location.first_line, "Failed to evaluate system task `%s' with non-constant argument.\n", str.c_str());
break;
case 'm':
case 'M':
if (got_len)
goto unsupported_format;
break;
case 'l':
case 'L':
if (got_len)
goto unsupported_format;
break;
default:
unsupported_format:
log_file_error(filename, location.first_line, "System task `%s' called with invalid/unsupported format specifier.\n", str.c_str());
break;
}
switch (cformat)
{
case 's':
case 'S':
sout += node_arg->bitsAsConst().decode_string();
break;
case 'd':
case 'D':
sout += stringf("%d", node_arg->bitsAsConst().as_int());
break;
case 'x':
case 'X':
{
Const val = node_arg->bitsAsConst();
while (GetSize(val) % 4 != 0)
val.bits.push_back(State::S0);
int len = GetSize(val) / 4;
for (int i = len; i < len_value; i++)
sout += got_zlen ? '0' : ' ';
for (int i = len-1; i >= 0; i--) {
Const digit = val.extract(4*i, 4);
if (digit.is_fully_def())
sout += stringf(cformat == 'x' ? "%x" : "%X", digit.as_int());
else
sout += cformat == 'x' ? "x" : "X";
}
}
break;
case 'm':
case 'M':
sout += log_id(current_module->name);
break;
case 'l':
case 'L':
sout += log_id(current_module->name);
break;
default:
log_abort();
}
}
// not a format specifier
else
sout += sformat[i];
}
return sout;
}
void AstNode::annotateTypedEnums(AstNode *template_node)
{
//check if enum
if (template_node->attributes.count(ID::enum_type)) {
//get reference to enum node:
std::string enum_type = template_node->attributes[ID::enum_type]->str.c_str();
// log("enum_type=%s (count=%lu)\n", enum_type.c_str(), current_scope.count(enum_type));
// log("current scope:\n");
// for (auto &it : current_scope)
// log(" %s\n", it.first.c_str());
log_assert(current_scope.count(enum_type) == 1);
AstNode *enum_node = current_scope.at(enum_type);
log_assert(enum_node->type == AST_ENUM);
while (enum_node->simplify(true, false, false, 1, -1, false, true)) { }
//get width from 1st enum item:
log_assert(enum_node->children.size() >= 1);
AstNode *enum_item0 = enum_node->children[0];
log_assert(enum_item0->type == AST_ENUM_ITEM);
int width;
if (!enum_item0->range_valid)
width = 1;
else if (enum_item0->range_swapped)
width = enum_item0->range_right - enum_item0->range_left + 1;
else
width = enum_item0->range_left - enum_item0->range_right + 1;
log_assert(width > 0);
//add declared enum items:
for (auto enum_item : enum_node->children){
log_assert(enum_item->type == AST_ENUM_ITEM);
//get is_signed
bool is_signed;
if (enum_item->children.size() == 1){
is_signed = false;
} else if (enum_item->children.size() == 2){
log_assert(enum_item->children[1]->type == AST_RANGE);
is_signed = enum_item->children[1]->is_signed;
} else {
log_error("enum_item children size==%lu, expected 1 or 2 for %s (%s)\n",
enum_item->children.size(),
enum_item->str.c_str(), enum_node->str.c_str()
);
}
//start building attribute string
std::string enum_item_str = "\\enum_value_";
//get enum item value
if(enum_item->children[0]->type != AST_CONSTANT){
log_error("expected const, got %s for %s (%s)\n",
type2str(enum_item->children[0]->type).c_str(),
enum_item->str.c_str(), enum_node->str.c_str()
);
}
RTLIL::Const val = enum_item->children[0]->bitsAsConst(width, is_signed);
enum_item_str.append(val.as_string());
//set attribute for available val to enum item name mappings
attributes[enum_item_str.c_str()] = mkconst_str(enum_item->str);
}
}
}
static bool name_has_dot(const std::string &name, std::string &struct_name)
{
// check if plausible struct member name \sss.mmm
std::string::size_type pos;
if (name.substr(0, 1) == "\\" && (pos = name.find('.', 0)) != std::string::npos) {
struct_name = name.substr(0, pos);
return true;
}
return false;
}
static AstNode *make_range(int left, int right, bool is_signed = false)
{
// generate a pre-validated range node for a fixed signal range.
auto range = new AstNode(AST_RANGE);
range->range_left = left;
range->range_right = right;
range->range_valid = true;
range->children.push_back(AstNode::mkconst_int(left, true));
range->children.push_back(AstNode::mkconst_int(right, true));
range->is_signed = is_signed;
return range;
}
static int range_width(AstNode *node, AstNode *rnode)
{
log_assert(rnode->type==AST_RANGE);
if (!rnode->range_valid) {
log_file_error(node->filename, node->location.first_line, "Size must be constant in packed struct/union member %s\n", node->str.c_str());
}
// note: range swapping has already been checked for
return rnode->range_left - rnode->range_right + 1;
}
[[noreturn]] static void struct_array_packing_error(AstNode *node)
{
log_file_error(node->filename, node->location.first_line, "Unpacked array in packed struct/union member %s\n", node->str.c_str());
}
static void save_struct_array_width(AstNode *node, int width)
{
// stash the stride for the array
node->multirange_dimensions.push_back(width);
}
static int get_struct_array_width(AstNode *node)
{
// the stride for the array, 1 if not an array
return (node->multirange_dimensions.empty() ? 1 : node->multirange_dimensions.back());
}
static int size_packed_struct(AstNode *snode, int base_offset)
{
// Struct members will be laid out in the structure contiguously from left to right.
// Union members all have zero offset from the start of the union.
// Determine total packed size and assign offsets. Store these in the member node.
bool is_union = (snode->type == AST_UNION);
int offset = 0;
int packed_width = -1;
// examine members from last to first
for (auto it = snode->children.rbegin(); it != snode->children.rend(); ++it) {
auto node = *it;
int width;
if (node->type == AST_STRUCT || node->type == AST_UNION) {
// embedded struct or union
width = size_packed_struct(node, base_offset + offset);
}
else {
log_assert(node->type == AST_STRUCT_ITEM);
if (node->children.size() > 0 && node->children[0]->type == AST_RANGE) {
// member width e.g. bit [7:0] a
width = range_width(node, node->children[0]);
if (node->children.size() == 2) {
if (node->children[1]->type == AST_RANGE) {
// unpacked array e.g. bit [63:0] a [0:3]
auto rnode = node->children[1];
int array_count = range_width(node, rnode);
if (array_count == 1) {
// C-type array size e.g. bit [63:0] a [4]
array_count = rnode->range_left;
}
save_struct_array_width(node, width);
width *= array_count;
}
else {
// array element must be single bit for a packed array
struct_array_packing_error(node);
}
}
// range nodes are now redundant
for (AstNode *child : node->children)
delete child;
node->children.clear();
}
else if (node->children.size() == 1 && node->children[0]->type == AST_MULTIRANGE) {
// packed 2D array, e.g. bit [3:0][63:0] a
auto rnode = node->children[0];
if (rnode->children.size() != 2) {
// packed arrays can only be 2D
struct_array_packing_error(node);
}
int array_count = range_width(node, rnode->children[0]);
width = range_width(node, rnode->children[1]);
save_struct_array_width(node, width);
width *= array_count;
// range nodes are now redundant
for (AstNode *child : node->children)
delete child;
node->children.clear();
}
else if (node->range_left < 0) {
// 1 bit signal: bit, logic or reg
width = 1;
}
else {
// already resolved and compacted
width = node->range_left - node->range_right + 1;
}
if (is_union) {
node->range_right = base_offset;
node->range_left = base_offset + width - 1;
}
else {
node->range_right = base_offset + offset;
node->range_left = base_offset + offset + width - 1;
}
node->range_valid = true;
}
if (is_union) {
// check that all members have the same size
if (packed_width == -1) {
// first member
packed_width = width;
}
else {
if (packed_width != width) {
log_file_error(node->filename, node->location.first_line, "member %s of a packed union has %d bits, expecting %d\n", node->str.c_str(), width, packed_width);
}
}
}
else {
offset += width;
}
}
return (is_union ? packed_width : offset);
}
[[noreturn]] static void struct_op_error(AstNode *node)
{
log_file_error(node->filename, node->location.first_line, "Unsupported operation for struct/union member %s\n", node->str.c_str()+1);
}
static AstNode *node_int(int ival)
{
return AstNode::mkconst_int(ival, true);
}
static AstNode *multiply_by_const(AstNode *expr_node, int stride)
{
return new AstNode(AST_MUL, expr_node, node_int(stride));
}
static AstNode *offset_indexed_range(int offset, int stride, AstNode *left_expr, AstNode *right_expr)
{
// adjust the range expressions to add an offset into the struct
// and maybe index using an array stride
auto left = left_expr->clone();
auto right = right_expr->clone();
if (stride > 1) {
// newleft = (left + 1) * stride - 1
left = new AstNode(AST_SUB, multiply_by_const(new AstNode(AST_ADD, left, node_int(1)), stride), node_int(1));
// newright = right * stride
right = multiply_by_const(right, stride);
}
// add the offset
if (offset) {
left = new AstNode(AST_ADD, node_int(offset), left);
right = new AstNode(AST_ADD, node_int(offset), right);
}
return new AstNode(AST_RANGE, left, right);
}
static AstNode *make_struct_index_range(AstNode *node, AstNode *rnode, int stride, int offset)
{
// generate a range node to perform either bit or array indexing
if (rnode->children.size() == 1) {
// index e.g. s.a[i]
return offset_indexed_range(offset, stride, rnode->children[0], rnode->children[0]);
}
else if (rnode->children.size() == 2) {
// slice e.g. s.a[i:j]
return offset_indexed_range(offset, stride, rnode->children[0], rnode->children[1]);
}
else {
struct_op_error(node);
}
}
static AstNode *slice_range(AstNode *rnode, AstNode *snode)
{
// apply the bit slice indicated by snode to the range rnode
log_assert(rnode->type==AST_RANGE);
auto left = rnode->children[0];
auto right = rnode->children[1];
log_assert(snode->type==AST_RANGE);
auto slice_left = snode->children[0];
auto slice_right = snode->children[1];
auto width = new AstNode(AST_SUB, slice_left->clone(), slice_right->clone());
right = new AstNode(AST_ADD, right->clone(), slice_right->clone());
left = new AstNode(AST_ADD, right->clone(), width);
return new AstNode(AST_RANGE, left, right);
}
AstNode *AST::make_struct_member_range(AstNode *node, AstNode *member_node)
{
// Work out the range in the packed array that corresponds to a struct member
// taking into account any range operations applicable to the current node
// such as array indexing or slicing
int range_left = member_node->range_left;
int range_right = member_node->range_right;
if (node->children.empty()) {
// no range operations apply, return the whole width
return make_range(range_left, range_right);
}
int stride = get_struct_array_width(member_node);
if (node->children.size() == 1 && node->children[0]->type == AST_RANGE) {
// bit or array indexing e.g. s.a[2] or s.a[1:0]
return make_struct_index_range(node, node->children[0], stride, range_right);
}
else if (node->children.size() == 1 && node->children[0]->type == AST_MULTIRANGE) {
// multirange, i.e. bit slice after array index, e.g. s.a[i][p:q]
log_assert(stride > 1);
auto mrnode = node->children[0];
auto element_range = make_struct_index_range(node, mrnode->children[0], stride, range_right);
// then apply bit slice range
auto range = slice_range(element_range, mrnode->children[1]);
delete element_range;
return range;
}
else {
struct_op_error(node);
}
}
static void add_members_to_scope(AstNode *snode, std::string name)
{
// add all the members in a struct or union to local scope
// in case later referenced in assignments
log_assert(snode->type==AST_STRUCT || snode->type==AST_UNION);
for (auto *node : snode->children) {
if (node->type != AST_STRUCT_ITEM) {
// embedded struct or union
add_members_to_scope(node, name + "." + node->str);
}
else {
auto member_name = name + "." + node->str;
current_scope[member_name] = node;
}
}
}
static int get_max_offset(AstNode *node)
{
// get the width from the MS member in the struct
// as members are laid out from left to right in the packed wire
log_assert(node->type==AST_STRUCT || node->type==AST_UNION);
while (node->type != AST_STRUCT_ITEM) {
node = node->children[0];
}
return node->range_left;
}
static AstNode *make_packed_struct(AstNode *template_node, std::string &name)
{
// create a wire for the packed struct
auto wnode = new AstNode(AST_WIRE);
wnode->str = name;
wnode->is_logic = true;
wnode->range_valid = true;
wnode->is_signed = template_node->is_signed;
int offset = get_max_offset(template_node);
auto range = make_range(offset, 0);
wnode->children.push_back(range);
// make sure this node is the one in scope for this name
current_scope[name] = wnode;
// add all the struct members to scope under the wire's name
add_members_to_scope(template_node, name);
return wnode;
}
// check if a node or its children contains an assignment to the given variable
static bool node_contains_assignment_to(const AstNode* node, const AstNode* var)
{
if (node->type == AST_ASSIGN_EQ || node->type == AST_ASSIGN_LE) {
// current node is iteslf an assignment
log_assert(node->children.size() >= 2);
const AstNode* lhs = node->children[0];
if (lhs->type == AST_IDENTIFIER && lhs->str == var->str)
return false;
}
for (const AstNode* child : node->children) {
// if this child shadows the given variable
if (child != var && child->str == var->str && child->type == AST_WIRE)
break; // skip the remainder of this block/scope
// depth-first short circuit
if (!node_contains_assignment_to(child, var))
return false;
}
return true;
}
static std::string prefix_id(const std::string &prefix, const std::string &str)
{
log_assert(!prefix.empty() && (prefix.front() == '$' || prefix.front() == '\\'));
log_assert(!str.empty() && (str.front() == '$' || str.front() == '\\'));
log_assert(prefix.back() == '.');
if (str.front() == '\\')
return prefix + str.substr(1);
return prefix + str;
}
// convert the AST into a simpler AST that has all parameters substituted by their
// values, unrolled for-loops, expanded generate blocks, etc. when this function
// is done with an AST it can be converted into RTLIL using genRTLIL().
//
// this function also does all name resolving and sets the id2ast member of all
// nodes that link to a different node using names and lexical scoping.
bool AstNode::simplify(bool const_fold, bool at_zero, bool in_lvalue, int stage, int width_hint, bool sign_hint, bool in_param)
{
static int recursion_counter = 0;
static bool deep_recursion_warning = false;
if (recursion_counter++ == 1000 && deep_recursion_warning) {
log_warning("Deep recursion in AST simplifier.\nDoes this design contain overly long or deeply nested expressions, or excessive recursion?\n");
deep_recursion_warning = false;
}
static bool unevaluated_tern_branch = false;
AstNode *newNode = NULL;
bool did_something = false;
#if 0
log("-------------\n");
log("AST simplify[%d] depth %d at %s:%d on %s %p:\n", stage, recursion_counter, filename.c_str(), location.first_line, type2str(type).c_str(), this);
log("const_fold=%d, at_zero=%d, in_lvalue=%d, stage=%d, width_hint=%d, sign_hint=%d, in_param=%d\n",
int(const_fold), int(at_zero), int(in_lvalue), int(stage), int(width_hint), int(sign_hint), int(in_param));
// dumpAst(NULL, "> ");
#endif
if (stage == 0)
{
log_assert(type == AST_MODULE || type == AST_INTERFACE);
deep_recursion_warning = true;
while (simplify(const_fold, at_zero, in_lvalue, 1, width_hint, sign_hint, in_param)) { }
if (!flag_nomem2reg && !get_bool_attribute(ID::nomem2reg))
{
dict<AstNode*, pool<std::string>> mem2reg_places;
dict<AstNode*, uint32_t> mem2reg_candidates, dummy_proc_flags;
uint32_t flags = flag_mem2reg ? AstNode::MEM2REG_FL_ALL : 0;
mem2reg_as_needed_pass1(mem2reg_places, mem2reg_candidates, dummy_proc_flags, flags);
pool<AstNode*> mem2reg_set;
for (auto &it : mem2reg_candidates)
{
AstNode *mem = it.first;
uint32_t memflags = it.second;
bool this_nomeminit = flag_nomeminit;
log_assert((memflags & ~0x00ffff00) == 0);
if (mem->get_bool_attribute(ID::nomem2reg))
continue;
if (mem->get_bool_attribute(ID::nomeminit) || get_bool_attribute(ID::nomeminit))
this_nomeminit = true;
if (memflags & AstNode::MEM2REG_FL_FORCED)
goto silent_activate;
if (memflags & AstNode::MEM2REG_FL_EQ2)
goto verbose_activate;
if (memflags & AstNode::MEM2REG_FL_SET_ASYNC)
goto verbose_activate;
if ((memflags & AstNode::MEM2REG_FL_SET_INIT) && (memflags & AstNode::MEM2REG_FL_SET_ELSE) && this_nomeminit)
goto verbose_activate;
if (memflags & AstNode::MEM2REG_FL_CMPLX_LHS)
goto verbose_activate;
if ((memflags & AstNode::MEM2REG_FL_CONST_LHS) && !(memflags & AstNode::MEM2REG_FL_VAR_LHS))
goto verbose_activate;
// log("Note: Not replacing memory %s with list of registers (flags=0x%08lx).\n", mem->str.c_str(), long(memflags));
continue;
verbose_activate:
if (mem2reg_set.count(mem) == 0) {
std::string message = stringf("Replacing memory %s with list of registers.", mem->str.c_str());
bool first_element = true;
for (auto &place : mem2reg_places[it.first]) {
message += stringf("%s%s", first_element ? " See " : ", ", place.c_str());
first_element = false;
}
log_warning("%s\n", message.c_str());
}
silent_activate:
// log("Note: Replacing memory %s with list of registers (flags=0x%08lx).\n", mem->str.c_str(), long(memflags));
mem2reg_set.insert(mem);
}
for (auto node : mem2reg_set)
{
int mem_width, mem_size, addr_bits;
node->meminfo(mem_width, mem_size, addr_bits);
int data_range_left = node->children[0]->range_left;
int data_range_right = node->children[0]->range_right;
if (node->children[0]->range_swapped)
std::swap(data_range_left, data_range_right);
for (int i = 0; i < mem_size; i++) {
AstNode *reg = new AstNode(AST_WIRE, new AstNode(AST_RANGE,
mkconst_int(data_range_left, true), mkconst_int(data_range_right, true)));
reg->str = stringf("%s[%d]", node->str.c_str(), i);
reg->is_reg = true;
reg->is_signed = node->is_signed;
for (auto &it : node->attributes)
if (it.first != ID::mem2reg)
reg->attributes.emplace(it.first, it.second->clone());
reg->filename = node->filename;
reg->location = node->location;
children.push_back(reg);
while (reg->simplify(true, false, false, 1, -1, false, false)) { }
}
}
AstNode *async_block = NULL;
while (mem2reg_as_needed_pass2(mem2reg_set, this, NULL, async_block)) { }
vector<AstNode*> delnodes;
mem2reg_remove(mem2reg_set, delnodes);
for (auto node : delnodes)
delete node;
}
while (simplify(const_fold, at_zero, in_lvalue, 2, width_hint, sign_hint, in_param)) { }
recursion_counter--;
return false;
}
current_filename = filename;
// we do not look inside a task or function
// (but as soon as a task or function is instantiated we process the generated AST as usual)
if (type == AST_FUNCTION || type == AST_TASK) {
recursion_counter--;
return false;
}
// deactivate all calls to non-synthesis system tasks
// note that $display, $finish, and $stop are used for synthesis-time DRC so they're not in this list
if ((type == AST_FCALL || type == AST_TCALL) && (str == "$strobe" || str == "$monitor" || str == "$time" ||
str == "$dumpfile" || str == "$dumpvars" || str == "$dumpon" || str == "$dumpoff" || str == "$dumpall")) {
log_file_warning(filename, location.first_line, "Ignoring call to system %s %s.\n", type == AST_FCALL ? "function" : "task", str.c_str());
delete_children();
str = std::string();
}
if ((type == AST_TCALL) && (str == "$display" || str == "$write") && (!current_always || current_always->type != AST_INITIAL)) {
log_file_warning(filename, location.first_line, "System task `%s' outside initial block is unsupported.\n", str.c_str());
delete_children();
str = std::string();
}
// print messages if this a call to $display() or $write()
// This code implements only a small subset of Verilog-2005 $display() format specifiers,
// but should be good enough for most uses
if ((type == AST_TCALL) && ((str == "$display") || (str == "$write")))
{
int nargs = GetSize(children);
if (nargs < 1)
log_file_error(filename, location.first_line, "System task `%s' got %d arguments, expected >= 1.\n",
str.c_str(), int(children.size()));
// First argument is the format string
AstNode *node_string = children[0];
while (node_string->simplify(true, false, false, stage, width_hint, sign_hint, false)) { }
if (node_string->type != AST_CONSTANT)
log_file_error(filename, location.first_line, "Failed to evaluate system task `%s' with non-constant 1st argument.\n", str.c_str());
std::string sformat = node_string->bitsAsConst().decode_string();
std::string sout = process_format_str(sformat, 1, stage, width_hint, sign_hint);
// Finally, print the message (only include a \n for $display, not for $write)
log("%s", sout.c_str());
if (str == "$display")
log("\n");
delete_children();
str = std::string();
}
// activate const folding if this is anything that must be evaluated statically (ranges, parameters, attributes, etc.)
if (type == AST_WIRE || type == AST_PARAMETER || type == AST_LOCALPARAM || type == AST_ENUM_ITEM || type == AST_DEFPARAM || type == AST_PARASET || type == AST_RANGE || type == AST_PREFIX || type == AST_TYPEDEF)
const_fold = true;
if (type == AST_IDENTIFIER && current_scope.count(str) > 0 && (current_scope[str]->type == AST_PARAMETER || current_scope[str]->type == AST_LOCALPARAM || current_scope[str]->type == AST_ENUM_ITEM))
const_fold = true;
// in certain cases a function must be evaluated constant. this is what in_param controls.
if (type == AST_PARAMETER || type == AST_LOCALPARAM || type == AST_DEFPARAM || type == AST_PARASET || type == AST_PREFIX)
in_param = true;
std::map<std::string, AstNode*> backup_scope;
// create name resolution entries for all objects with names
// also merge multiple declarations for the same wire (e.g. "output foobar; reg foobar;")
if (type == AST_MODULE) {
current_scope.clear();
std::set<std::string> existing;
int counter = 0;
label_genblks(existing, counter);
std::map<std::string, AstNode*> this_wire_scope;
for (size_t i = 0; i < children.size(); i++) {
AstNode *node = children[i];
if (node->type == AST_WIRE) {
if (node->children.size() == 1 && node->children[0]->type == AST_RANGE) {
for (auto c : node->children[0]->children) {
if (!c->is_simple_const_expr()) {
if (attributes.count(ID::dynports))
delete attributes.at(ID::dynports);
attributes[ID::dynports] = AstNode::mkconst_int(1, true);
}
}
}
if (this_wire_scope.count(node->str) > 0) {
AstNode *first_node = this_wire_scope[node->str];
if (first_node->is_input && node->is_reg)
goto wires_are_incompatible;
if (!node->is_input && !node->is_output && node->is_reg && node->children.size() == 0)
goto wires_are_compatible;
if (first_node->children.size() == 0 && node->children.size() == 1 && node->children[0]->type == AST_RANGE) {
AstNode *r = node->children[0];
if (r->range_valid && r->range_left == 0 && r->range_right == 0) {
delete r;
node->children.pop_back();
}
}
if (first_node->children.size() != node->children.size())
goto wires_are_incompatible;
for (size_t j = 0; j < node->children.size(); j++) {
AstNode *n1 = first_node->children[j], *n2 = node->children[j];
if (n1->type == AST_RANGE && n2->type == AST_RANGE && n1->range_valid && n2->range_valid) {
if (n1->range_left != n2->range_left)
goto wires_are_incompatible;
if (n1->range_right != n2->range_right)
goto wires_are_incompatible;
} else if (*n1 != *n2)
goto wires_are_incompatible;
}
if (first_node->range_left != node->range_left)
goto wires_are_incompatible;
if (first_node->range_right != node->range_right)
goto wires_are_incompatible;
if (first_node->port_id == 0 && (node->is_input || node->is_output))
goto wires_are_incompatible;
wires_are_compatible:
if (node->is_input)
first_node->is_input = true;
if (node->is_output)
first_node->is_output = true;
if (node->is_reg)
first_node->is_reg = true;
if (node->is_logic)
first_node->is_logic = true;
if (node->is_signed)
first_node->is_signed = true;
for (auto &it : node->attributes) {
if (first_node->attributes.count(it.first) > 0)
delete first_node->attributes[it.first];
first_node->attributes[it.first] = it.second->clone();
}
children.erase(children.begin()+(i--));
did_something = true;
delete node;
continue;
wires_are_incompatible:
if (stage > 1)
log_file_error(filename, location.first_line, "Incompatible re-declaration of wire %s.\n", node->str.c_str());
continue;
}
this_wire_scope[node->str] = node;
}
// these nodes appear at the top level in a module and can define names
if (node->type == AST_PARAMETER || node->type == AST_LOCALPARAM || node->type == AST_WIRE || node->type == AST_AUTOWIRE || node->type == AST_GENVAR ||
node->type == AST_MEMORY || node->type == AST_FUNCTION || node->type == AST_TASK || node->type == AST_DPI_FUNCTION || node->type == AST_CELL ||
node->type == AST_TYPEDEF) {
backup_scope[node->str] = current_scope[node->str];
current_scope[node->str] = node;
}
if (node->type == AST_ENUM) {
current_scope[node->str] = node;
for (auto enode : node->children) {
log_assert(enode->type==AST_ENUM_ITEM);
if (current_scope.count(enode->str) == 0)
current_scope[enode->str] = enode;
else
log_file_error(filename, location.first_line, "enum item %s already exists\n", enode->str.c_str());
}
}
}
for (size_t i = 0; i < children.size(); i++) {
AstNode *node = children[i];
if (node->type == AST_PARAMETER || node->type == AST_LOCALPARAM || node->type == AST_WIRE || node->type == AST_AUTOWIRE || node->type == AST_MEMORY || node->type == AST_TYPEDEF)
while (node->simplify(true, false, false, 1, -1, false, node->type == AST_PARAMETER || node->type == AST_LOCALPARAM))
did_something = true;
if (node->type == AST_ENUM) {
for (auto enode : node->children){
log_assert(enode->type==AST_ENUM_ITEM);
while (node->simplify(true, false, false, 1, -1, false, in_param))
did_something = true;
}
}
}
}
// create name resolution entries for all objects with names
if (type == AST_PACKAGE) {
//add names to package scope
for (size_t i = 0; i < children.size(); i++) {
AstNode *node = children[i];
// these nodes appear at the top level in a package and can define names
if (node->type == AST_PARAMETER || node->type == AST_LOCALPARAM || node->type == AST_TYPEDEF || node->type == AST_FUNCTION || node->type == AST_TASK) {
current_scope[node->str] = node;
}
if (node->type == AST_ENUM) {
current_scope[node->str] = node;
for (auto enode : node->children) {
log_assert(enode->type==AST_ENUM_ITEM);
if (current_scope.count(enode->str) == 0)
current_scope[enode->str] = enode;
else
log_file_error(filename, location.first_line, "enum item %s already exists in package\n", enode->str.c_str());
}
}
}
}
auto backup_current_block = current_block;
auto backup_current_block_child = current_block_child;
auto backup_current_top_block = current_top_block;
auto backup_current_always = current_always;
auto backup_current_always_clocked = current_always_clocked;
if (type == AST_ALWAYS || type == AST_INITIAL)
{
if (current_always != nullptr)
log_file_error(filename, location.first_line, "Invalid nesting of always blocks and/or initializations.\n");
current_always = this;
current_always_clocked = false;
if (type == AST_ALWAYS)
for (auto child : children) {
if (child->type == AST_POSEDGE || child->type == AST_NEGEDGE)
current_always_clocked = true;
if (child->type == AST_EDGE && GetSize(child->children) == 1 &&
child->children[0]->type == AST_IDENTIFIER && child->children[0]->str == "\\$global_clock")
current_always_clocked = true;
}
}
if (type == AST_ARGUMENT)
{
if (children.size() == 1 && children[0]->type == AST_CONSTANT)
{
// HACK: For port bindings using unbased unsized literals, mark them
// signed so they sign-extend. The hierarchy will still incorrectly
// generate a warning complaining about resizing the expression.
// This also doesn't handle the complex of something like a ternary
// expression bound to a port, where the actual size of the port is
// needed to resolve the expression correctly.
AstNode *arg = children[0];
if (arg->is_unsized)
arg->is_signed = true;
}
}
int backup_width_hint = width_hint;
bool backup_sign_hint = sign_hint;
bool detect_width_simple = false;
bool child_0_is_self_determined = false;
bool child_1_is_self_determined = false;
bool child_2_is_self_determined = false;
bool children_are_self_determined = false;
bool reset_width_after_children = false;
switch (type)
{
case AST_ASSIGN_EQ:
case AST_ASSIGN_LE:
case AST_ASSIGN:
while (!children[0]->basic_prep && children[0]->simplify(false, false, true, stage, -1, false, in_param) == true)
did_something = true;
while (!children[1]->basic_prep && children[1]->simplify(false, false, false, stage, -1, false, in_param) == true)
did_something = true;
children[0]->detectSignWidth(backup_width_hint, backup_sign_hint);
children[1]->detectSignWidth(width_hint, sign_hint);
width_hint = max(width_hint, backup_width_hint);
child_0_is_self_determined = true;
// test only once, before optimizations and memory mappings but after assignment LHS was mapped to an identifier
if (children[0]->id2ast && !children[0]->was_checked) {
if ((type == AST_ASSIGN_LE || type == AST_ASSIGN_EQ) && children[0]->id2ast->is_logic)
children[0]->id2ast->is_reg = true; // if logic type is used in a block asignment
if ((type == AST_ASSIGN_LE || type == AST_ASSIGN_EQ) && !children[0]->id2ast->is_reg)
log_warning("wire '%s' is assigned in a block at %s.\n", children[0]->str.c_str(), loc_string().c_str());
if (type == AST_ASSIGN && children[0]->id2ast->is_reg) {
bool is_rand_reg = false;
if (children[1]->type == AST_FCALL) {
if (children[1]->str == "\\$anyconst")
is_rand_reg = true;
if (children[1]->str == "\\$anyseq")
is_rand_reg = true;
if (children[1]->str == "\\$allconst")
is_rand_reg = true;
if (children[1]->str == "\\$allseq")
is_rand_reg = true;
}
if (!is_rand_reg)
log_warning("reg '%s' is assigned in a continuous assignment at %s.\n", children[0]->str.c_str(), loc_string().c_str());
}
children[0]->was_checked = true;
}
break;
case AST_STRUCT:
case AST_UNION:
if (!basic_prep) {
for (auto *node : children) {
// resolve any ranges
while (!node->basic_prep && node->simplify(true, false, false, stage, -1, false, false)) {
did_something = true;
}
}
// determine member offsets and widths
size_packed_struct(this, 0);
// instance rather than just a type in a typedef or outer struct?
if (!str.empty() && str[0] == '\\') {
// instance so add a wire for the packed structure
auto wnode = make_packed_struct(this, str);
log_assert(current_ast_mod);
current_ast_mod->children.push_back(wnode);
}
basic_prep = true;
}
break;
case AST_STRUCT_ITEM:
break;
case AST_ENUM:
//log("\nENUM %s: %d child %d\n", str.c_str(), basic_prep, children[0]->basic_prep);
if (!basic_prep) {
for (auto item_node : children) {
while (!item_node->basic_prep && item_node->simplify(false, false, false, stage, -1, false, in_param))
did_something = true;
}
// allocate values (called more than once)
allocateDefaultEnumValues();
}
break;
case AST_PARAMETER:
case AST_LOCALPARAM:
while (!children[0]->basic_prep && children[0]->simplify(false, false, false, stage, -1, false, true) == true)
did_something = true;
children[0]->detectSignWidth(width_hint, sign_hint);
if (children.size() > 1 && children[1]->type == AST_RANGE) {
while (!children[1]->basic_prep && children[1]->simplify(false, false, false, stage, -1, false, true) == true)
did_something = true;
if (!children[1]->range_valid)
log_file_error(filename, location.first_line, "Non-constant width range on parameter decl.\n");
width_hint = max(width_hint, children[1]->range_left - children[1]->range_right + 1);
}
break;
case AST_ENUM_ITEM:
while (!children[0]->basic_prep && children[0]->simplify(false, false, false, stage, -1, false, in_param))
did_something = true;
children[0]->detectSignWidth(width_hint, sign_hint);
if (children.size() > 1 && children[1]->type == AST_RANGE) {
while (!children[1]->basic_prep && children[1]->simplify(false, false, false, stage, -1, false, in_param))
did_something = true;
if (!children[1]->range_valid)
log_file_error(filename, location.first_line, "Non-constant width range on enum item decl.\n");
width_hint = max(width_hint, children[1]->range_left - children[1]->range_right + 1);
}
break;
case AST_TO_BITS:
case AST_TO_SIGNED:
case AST_TO_UNSIGNED:
case AST_SELFSZ:
case AST_CAST_SIZE:
case AST_CONCAT:
case AST_REPLICATE:
case AST_REDUCE_AND:
case AST_REDUCE_OR:
case AST_REDUCE_XOR:
case AST_REDUCE_XNOR:
case AST_REDUCE_BOOL:
detect_width_simple = true;
children_are_self_determined = true;
break;
case AST_NEG:
case AST_BIT_NOT:
case AST_POS:
case AST_BIT_AND:
case AST_BIT_OR:
case AST_BIT_XOR:
case AST_BIT_XNOR:
case AST_ADD:
case AST_SUB:
case AST_MUL:
case AST_DIV:
case AST_MOD:
detect_width_simple = true;
break;
case AST_SHIFT_LEFT:
case AST_SHIFT_RIGHT:
case AST_SHIFT_SLEFT:
case AST_SHIFT_SRIGHT:
case AST_POW:
detect_width_simple = true;
child_1_is_self_determined = true;
break;
case AST_LT:
case AST_LE:
case AST_EQ:
case AST_NE:
case AST_EQX:
case AST_NEX:
case AST_GE:
case AST_GT:
width_hint = -1;
sign_hint = true;
for (auto child : children) {
while (!child->basic_prep && child->simplify(false, false, in_lvalue, stage, -1, false, in_param) == true)
did_something = true;
child->detectSignWidthWorker(width_hint, sign_hint);
}
reset_width_after_children = true;
break;
case AST_LOGIC_AND:
case AST_LOGIC_OR:
case AST_LOGIC_NOT:
detect_width_simple = true;
children_are_self_determined = true;
break;
case AST_TERNARY:
child_0_is_self_determined = true;
break;
case AST_MEMRD:
detect_width_simple = true;
children_are_self_determined = true;
break;
case AST_FCALL:
case AST_TCALL:
children_are_self_determined = true;
break;
default:
width_hint = -1;
sign_hint = false;
}
if (detect_width_simple && width_hint < 0) {
if (type == AST_REPLICATE)
while (children[0]->simplify(true, false, in_lvalue, stage, -1, false, true) == true)
did_something = true;
for (auto child : children)
while (!child->basic_prep && child->simplify(false, false, in_lvalue, stage, -1, false, in_param) == true)
did_something = true;
detectSignWidth(width_hint, sign_hint);
}
if (type == AST_FCALL && str == "\\$past")
detectSignWidth(width_hint, sign_hint);
if (type == AST_TERNARY) {
if (width_hint < 0) {
while (!children[0]->basic_prep && children[0]->simplify(true, false, in_lvalue, stage, -1, false, in_param))
did_something = true;
bool backup_unevaluated_tern_branch = unevaluated_tern_branch;
AstNode *chosen = get_tern_choice().first;
unevaluated_tern_branch = backup_unevaluated_tern_branch || chosen == children[2];
while (!children[1]->basic_prep && children[1]->simplify(false, false, in_lvalue, stage, -1, false, in_param))
did_something = true;
unevaluated_tern_branch = backup_unevaluated_tern_branch || chosen == children[1];
while (!children[2]->basic_prep && children[2]->simplify(false, false, in_lvalue, stage, -1, false, in_param))
did_something = true;
unevaluated_tern_branch = backup_unevaluated_tern_branch;
detectSignWidth(width_hint, sign_hint);
}
int width_hint_left, width_hint_right;
bool sign_hint_left, sign_hint_right;
bool found_real_left, found_real_right;
children[1]->detectSignWidth(width_hint_left, sign_hint_left, &found_real_left);
children[2]->detectSignWidth(width_hint_right, sign_hint_right, &found_real_right);
if (found_real_left || found_real_right) {
child_1_is_self_determined = true;
child_2_is_self_determined = true;
}
}
if (type == AST_CONDX && children.size() > 0 && children.at(0)->type == AST_CONSTANT) {
for (auto &bit : children.at(0)->bits)
if (bit == State::Sz || bit == State::Sx)
bit = State::Sa;
}
if (type == AST_CONDZ && children.size() > 0 && children.at(0)->type == AST_CONSTANT) {
for (auto &bit : children.at(0)->bits)
if (bit == State::Sz)
bit = State::Sa;
}
if (const_fold && type == AST_CASE)
{
int width_hint;
bool sign_hint;
detectSignWidth(width_hint, sign_hint);
while (children[0]->simplify(const_fold, at_zero, in_lvalue, stage, width_hint, sign_hint, in_param)) { }
if (children[0]->type == AST_CONSTANT && children[0]->bits_only_01()) {
RTLIL::Const case_expr = children[0]->bitsAsConst(width_hint, sign_hint);
std::vector<AstNode*> new_children;
new_children.push_back(children[0]);
for (int i = 1; i < GetSize(children); i++) {
AstNode *child = children[i];
log_assert(child->type == AST_COND || child->type == AST_CONDX || child->type == AST_CONDZ);
for (auto v : child->children) {
if (v->type == AST_DEFAULT)
goto keep_const_cond;
if (v->type == AST_BLOCK)
continue;
while (v->simplify(const_fold, at_zero, in_lvalue, stage, width_hint, sign_hint, in_param)) { }
if (v->type == AST_CONSTANT && v->bits_only_01()) {
RTLIL::Const case_item_expr = v->bitsAsConst(width_hint, sign_hint);
RTLIL::Const match = const_eq(case_expr, case_item_expr, sign_hint, sign_hint, 1);
log_assert(match.bits.size() == 1);
if (match.bits.front() == RTLIL::State::S1) {
while (i+1 < GetSize(children))
delete children[++i];
goto keep_const_cond;
}
continue;
}
goto keep_const_cond;
}
if (0)
keep_const_cond:
new_children.push_back(child);
else
delete child;
}
new_children.swap(children);
}
}
dict<std::string, pool<int>> backup_memwr_visible;
dict<std::string, pool<int>> final_memwr_visible;
if (type == AST_CASE && stage == 2) {
backup_memwr_visible = current_memwr_visible;
final_memwr_visible = current_memwr_visible;
}
// simplify all children first
// (iterate by index as e.g. auto wires can add new children in the process)
for (size_t i = 0; i < children.size(); i++) {
bool did_something_here = true;
bool backup_flag_autowire = flag_autowire;
bool backup_unevaluated_tern_branch = unevaluated_tern_branch;
if ((type == AST_GENFOR || type == AST_FOR) && i >= 3)
break;
if ((type == AST_GENIF || type == AST_GENCASE) && i >= 1)
break;
if (type == AST_GENBLOCK)
break;
if (type == AST_BLOCK && !str.empty())
break;
if (type == AST_PREFIX && i >= 1)
break;
if (type == AST_DEFPARAM && i == 0)
flag_autowire = true;
if (type == AST_TERNARY && i > 0 && !unevaluated_tern_branch) {
AstNode *chosen = get_tern_choice().first;
unevaluated_tern_branch = chosen && chosen != children[i];
}
while (did_something_here && i < children.size()) {
bool const_fold_here = const_fold, in_lvalue_here = in_lvalue;
int width_hint_here = width_hint;
bool sign_hint_here = sign_hint;
bool in_param_here = in_param;
if (i == 0 && (type == AST_REPLICATE || type == AST_WIRE))
const_fold_here = true, in_param_here = true;
if (i == 0 && (type == AST_GENIF || type == AST_GENCASE))
in_param_here = true;
if (i == 1 && (type == AST_FOR || type == AST_GENFOR))
in_param_here = true;
if (type == AST_PARAMETER || type == AST_LOCALPARAM)
const_fold_here = true;
if (i == 0 && (type == AST_ASSIGN || type == AST_ASSIGN_EQ || type == AST_ASSIGN_LE))
in_lvalue_here = true;
if (type == AST_BLOCK) {
current_block = this;
current_block_child = children[i];
}
if ((type == AST_ALWAYS || type == AST_INITIAL) && children[i]->type == AST_BLOCK)
current_top_block = children[i];
if (i == 0 && child_0_is_self_determined)
width_hint_here = -1, sign_hint_here = false;
if (i == 1 && child_1_is_self_determined)
width_hint_here = -1, sign_hint_here = false;
if (i == 2 && child_2_is_self_determined)
width_hint_here = -1, sign_hint_here = false;
if (children_are_self_determined)
width_hint_here = -1, sign_hint_here = false;
did_something_here = children[i]->simplify(const_fold_here, at_zero, in_lvalue_here, stage, width_hint_here, sign_hint_here, in_param_here);
if (did_something_here)
did_something = true;
}
if (stage == 2 && children[i]->type == AST_INITIAL && current_ast_mod != this) {
current_ast_mod->children.push_back(children[i]);
children.erase(children.begin() + (i--));
did_something = true;
}
flag_autowire = backup_flag_autowire;
unevaluated_tern_branch = backup_unevaluated_tern_branch;
if (stage == 2 && type == AST_CASE) {
for (auto &x : current_memwr_visible) {
for (int y : x.second)
final_memwr_visible[x.first].insert(y);
}
current_memwr_visible = backup_memwr_visible;
}
}
for (auto &attr : attributes) {
while (attr.second->simplify(true, false, false, stage, -1, false, true))
did_something = true;
}
if (type == AST_CASE && stage == 2) {
current_memwr_visible = final_memwr_visible;
}
if (type == AST_ALWAYS && stage == 2) {
current_memwr_visible.clear();
current_memwr_count.clear();
}
if (reset_width_after_children) {
width_hint = backup_width_hint;
sign_hint = backup_sign_hint;
if (width_hint < 0)
detectSignWidth(width_hint, sign_hint);
}
current_block = backup_current_block;
current_block_child = backup_current_block_child;
current_top_block = backup_current_top_block;
current_always = backup_current_always;
current_always_clocked = backup_current_always_clocked;
for (auto it = backup_scope.begin(); it != backup_scope.end(); it++) {
if (it->second == NULL)
current_scope.erase(it->first);
else
current_scope[it->first] = it->second;
}
current_filename = filename;
if (type == AST_MODULE)
current_scope.clear();
// convert defparam nodes to cell parameters
if (type == AST_DEFPARAM && !children.empty())
{
if (children[0]->type != AST_IDENTIFIER)
log_file_error(filename, location.first_line, "Module name in defparam contains non-constant expressions!\n");
string modname, paramname = children[0]->str;
size_t pos = paramname.rfind('.');
while (pos != 0 && pos != std::string::npos)
{
modname = paramname.substr(0, pos);
if (current_scope.count(modname))
break;
pos = paramname.rfind('.', pos - 1);
}
if (pos == std::string::npos)
log_file_error(filename, location.first_line, "Can't find object for defparam `%s`!\n", RTLIL::unescape_id(paramname).c_str());
paramname = "\\" + paramname.substr(pos+1);
if (current_scope.at(modname)->type != AST_CELL)
log_file_error(filename, location.first_line, "Defparam argument `%s . %s` does not match a cell!\n",
RTLIL::unescape_id(modname).c_str(), RTLIL::unescape_id(paramname).c_str());
AstNode *paraset = new AstNode(AST_PARASET, children[1]->clone(), GetSize(children) > 2 ? children[2]->clone() : NULL);
paraset->str = paramname;
AstNode *cell = current_scope.at(modname);
cell->children.insert(cell->children.begin() + 1, paraset);
delete_children();
}
// resolve typedefs
if (type == AST_TYPEDEF) {
log_assert(children.size() == 1);
auto type_node = children[0];
log_assert(type_node->type == AST_WIRE || type_node->type == AST_MEMORY || type_node->type == AST_STRUCT || type_node->type == AST_UNION);
while (type_node->simplify(const_fold, at_zero, in_lvalue, stage, width_hint, sign_hint, in_param)) {
did_something = true;
}
log_assert(!type_node->is_custom_type);
}
// resolve types of wires
if (type == AST_WIRE || type == AST_MEMORY) {
if (is_custom_type) {
log_assert(children.size() >= 1);
log_assert(children[0]->type == AST_WIRETYPE);
auto type_name = children[0]->str;
if (!current_scope.count(type_name)) {
log_file_error(filename, location.first_line, "Unknown identifier `%s' used as type name\n", type_name.c_str());
}
AstNode *resolved_type_node = current_scope.at(type_name);
if (resolved_type_node->type != AST_TYPEDEF)
log_file_error(filename, location.first_line, "`%s' does not name a type\n", type_name.c_str());
log_assert(resolved_type_node->children.size() == 1);
AstNode *template_node = resolved_type_node->children[0];
// Ensure typedef itself is fully simplified
while (template_node->simplify(const_fold, at_zero, in_lvalue, stage, width_hint, sign_hint, in_param)) {};
if (template_node->type == AST_STRUCT || template_node->type == AST_UNION) {
// replace with wire representing the packed structure
newNode = make_packed_struct(template_node, str);
// add original input/output attribute to resolved wire
newNode->is_input = this->is_input;
newNode->is_output = this->is_output;
current_scope[str] = this;
goto apply_newNode;
}
// Remove type reference
delete children[0];
children.erase(children.begin());
if (type == AST_WIRE)
type = template_node->type;
is_reg = template_node->is_reg;
is_logic = template_node->is_logic;
is_signed = template_node->is_signed;
is_string = template_node->is_string;
is_custom_type = template_node->is_custom_type;
range_valid = template_node->range_valid;
range_swapped = template_node->range_swapped;
range_left = template_node->range_left;
range_right = template_node->range_right;
attributes[ID::wiretype] = mkconst_str(resolved_type_node->str);
// if an enum then add attributes to support simulator tracing
annotateTypedEnums(template_node);
// Insert clones children from template at beginning
for (int i = 0; i < GetSize(template_node->children); i++)
children.insert(children.begin() + i, template_node->children[i]->clone());
if (type == AST_MEMORY && GetSize(children) == 1) {
// Single-bit memories must have [0:0] range
AstNode *rng = make_range(0, 0);
children.insert(children.begin(), rng);
}
did_something = true;
}
log_assert(!is_custom_type);
}
// resolve types of parameters
if (type == AST_LOCALPARAM || type == AST_PARAMETER) {
if (is_custom_type) {
log_assert(children.size() == 2);
log_assert(children[1]->type == AST_WIRETYPE);
if (!current_scope.count(children[1]->str))
log_file_error(filename, location.first_line, "Unknown identifier `%s' used as type name\n", children[1]->str.c_str());
AstNode *resolved_type_node = current_scope.at(children[1]->str);
if (resolved_type_node->type != AST_TYPEDEF)
log_file_error(filename, location.first_line, "`%s' does not name a type\n", children[1]->str.c_str());
log_assert(resolved_type_node->children.size() == 1);
AstNode *template_node = resolved_type_node->children[0];
delete children[1];
children.pop_back();
// Ensure typedef itself is fully simplified
while(template_node->simplify(const_fold, at_zero, in_lvalue, stage, width_hint, sign_hint, in_param)) {};
if (template_node->type == AST_MEMORY)
log_file_error(filename, location.first_line, "unpacked array type `%s' cannot be used for a parameter\n", children[1]->str.c_str());
is_signed = template_node->is_signed;
is_string = template_node->is_string;
is_custom_type = template_node->is_custom_type;
range_valid = template_node->range_valid;
range_swapped = template_node->range_swapped;
range_left = template_node->range_left;
range_right = template_node->range_right;
attributes[ID::wiretype] = mkconst_str(resolved_type_node->str);
for (auto template_child : template_node->children)
children.push_back(template_child->clone());
did_something = true;
}
log_assert(!is_custom_type);
}
// resolve constant prefixes
if (type == AST_PREFIX) {
if (children[0]->type != AST_CONSTANT) {
// dumpAst(NULL, "> ");
log_file_error(filename, location.first_line, "Index in generate block prefix syntax is not constant!\n");
}
if (children[1]->type == AST_PREFIX)
children[1]->simplify(const_fold, at_zero, in_lvalue, stage, width_hint, sign_hint, in_param);
log_assert(children[1]->type == AST_IDENTIFIER);
newNode = children[1]->clone();
const char *second_part = children[1]->str.c_str();
if (second_part[0] == '\\')
second_part++;
newNode->str = stringf("%s[%d].%s", str.c_str(), children[0]->integer, second_part);
goto apply_newNode;
}
// evaluate TO_BITS nodes
if (type == AST_TO_BITS) {
if (children[0]->type != AST_CONSTANT)
log_file_error(filename, location.first_line, "Left operand of to_bits expression is not constant!\n");
if (children[1]->type != AST_CONSTANT)
log_file_error(filename, location.first_line, "Right operand of to_bits expression is not constant!\n");
RTLIL::Const new_value = children[1]->bitsAsConst(children[0]->bitsAsConst().as_int(), children[1]->is_signed);
newNode = mkconst_bits(new_value.bits, children[1]->is_signed);
goto apply_newNode;
}
// annotate constant ranges
if (type == AST_RANGE) {
bool old_range_valid = range_valid;
range_valid = false;
range_swapped = false;
range_left = -1;
range_right = 0;
log_assert(children.size() >= 1);
if (children[0]->type == AST_CONSTANT) {
range_valid = true;
range_left = children[0]->integer;
if (children.size() == 1)
range_right = range_left;
}
if (children.size() >= 2) {
if (children[1]->type == AST_CONSTANT)
range_right = children[1]->integer;
else
range_valid = false;
}
if (old_range_valid != range_valid)
did_something = true;
if (range_valid && range_right > range_left) {
int tmp = range_right;
range_right = range_left;
range_left = tmp;
range_swapped = true;
}
}
// annotate wires with their ranges
if (type == AST_WIRE) {
if (children.size() > 0) {
if (children[0]->range_valid) {
if (!range_valid)
did_something = true;
range_valid = true;
range_swapped = children[0]->range_swapped;
range_left = children[0]->range_left;
range_right = children[0]->range_right;
bool force_upto = false, force_downto = false;
if (attributes.count(ID::force_upto)) {
AstNode *val = attributes[ID::force_upto];
if (val->type != AST_CONSTANT)
log_file_error(filename, location.first_line, "Attribute `force_upto' with non-constant value!\n");
force_upto = val->asAttrConst().as_bool();
}
if (attributes.count(ID::force_downto)) {
AstNode *val = attributes[ID::force_downto];
if (val->type != AST_CONSTANT)
log_file_error(filename, location.first_line, "Attribute `force_downto' with non-constant value!\n");
force_downto = val->asAttrConst().as_bool();
}
if (force_upto && force_downto)
log_file_error(filename, location.first_line, "Attributes `force_downto' and `force_upto' cannot be both set!\n");
if ((force_upto && !range_swapped) || (force_downto && range_swapped)) {
std::swap(range_left, range_right);
range_swapped = force_upto;
}
}
} else {
if (!range_valid)
did_something = true;
range_valid = true;
range_swapped = false;
range_left = 0;
range_right = 0;
}
}
// resolve multiranges on memory decl
if (type == AST_MEMORY && children.size() > 1 && children[1]->type == AST_MULTIRANGE)
{
int total_size = 1;
multirange_dimensions.clear();
multirange_swapped.clear();
for (auto range : children[1]->children) {
if (!range->range_valid)
log_file_error(filename, location.first_line, "Non-constant range on memory decl.\n");
multirange_dimensions.push_back(min(range->range_left, range->range_right));
multirange_dimensions.push_back(max(range->range_left, range->range_right) - min(range->range_left, range->range_right) + 1);
multirange_swapped.push_back(range->range_swapped);
total_size *= multirange_dimensions.back();
}
delete children[1];
children[1] = new AstNode(AST_RANGE, AstNode::mkconst_int(0, true), AstNode::mkconst_int(total_size-1, true));
did_something = true;
}
// resolve multiranges on memory access
if (type == AST_IDENTIFIER && id2ast && id2ast->type == AST_MEMORY && children.size() > 0 && children[0]->type == AST_MULTIRANGE)
{
AstNode *index_expr = nullptr;
integer = children[0]->children.size(); // save original number of dimensions for $size() etc.
for (int i = 0; 2*i < GetSize(id2ast->multirange_dimensions); i++)
{
if (GetSize(children[0]->children) <= i)
log_file_error(filename, location.first_line, "Insufficient number of array indices for %s.\n", log_id(str));
AstNode *new_index_expr = children[0]->children[i]->children.at(0)->clone();
if (id2ast->multirange_dimensions[2*i])
new_index_expr = new AstNode(AST_SUB, new_index_expr, AstNode::mkconst_int(id2ast->multirange_dimensions[2*i], true));
if (i == 0)
index_expr = new_index_expr;
else
index_expr = new AstNode(AST_ADD, new AstNode(AST_MUL, index_expr, AstNode::mkconst_int(id2ast->multirange_dimensions[2*i+1], true)), new_index_expr);
}
for (int i = GetSize(id2ast->multirange_dimensions)/2; i < GetSize(children[0]->children); i++)
children.push_back(children[0]->children[i]->clone());
delete children[0];
if (index_expr == nullptr)
children.erase(children.begin());
else
children[0] = new AstNode(AST_RANGE, index_expr);
did_something = true;
}
// trim/extend parameters
if (type == AST_PARAMETER || type == AST_LOCALPARAM || type == AST_ENUM_ITEM) {
if (children.size() > 1 && children[1]->type == AST_RANGE) {
if (!children[1]->range_valid)
log_file_error(filename, location.first_line, "Non-constant width range on parameter decl.\n");
int width = std::abs(children[1]->range_left - children[1]->range_right) + 1;
if (children[0]->type == AST_REALVALUE) {
RTLIL::Const constvalue = children[0]->realAsConst(width);
log_file_warning(filename, location.first_line, "converting real value %e to binary %s.\n",
children[0]->realvalue, log_signal(constvalue));
delete children[0];
children[0] = mkconst_bits(constvalue.bits, sign_hint);
did_something = true;
}
if (children[0]->type == AST_CONSTANT) {
if (width != int(children[0]->bits.size())) {
RTLIL::SigSpec sig(children[0]->bits);
sig.extend_u0(width, children[0]->is_signed);
AstNode *old_child_0 = children[0];
children[0] = mkconst_bits(sig.as_const().bits, is_signed);
delete old_child_0;
}
children[0]->is_signed = is_signed;
}
range_valid = true;
range_swapped = children[1]->range_swapped;
range_left = children[1]->range_left;
range_right = children[1]->range_right;
} else
if (children.size() > 1 && children[1]->type == AST_REALVALUE && children[0]->type == AST_CONSTANT) {
double as_realvalue = children[0]->asReal(sign_hint);
delete children[0];
children[0] = new AstNode(AST_REALVALUE);
children[0]->realvalue = as_realvalue;
did_something = true;
}
}
if (type == AST_IDENTIFIER && !basic_prep) {
// check if a plausible struct member sss.mmmm
std::string sname;
if (name_has_dot(str, sname)) {
if (current_scope.count(str) > 0) {
auto item_node = current_scope[str];
if (item_node->type == AST_STRUCT_ITEM) {
// structure member, rewrite this node to reference the packed struct wire
auto range = make_struct_member_range(this, item_node);
newNode = new AstNode(AST_IDENTIFIER, range);
newNode->str = sname;
newNode->basic_prep = true;
if (item_node->is_signed)
newNode = new AstNode(AST_TO_SIGNED, newNode);
goto apply_newNode;
}
}
}
}
// annotate identifiers using scope resolution and create auto-wires as needed
if (type == AST_IDENTIFIER) {
if (current_scope.count(str) == 0) {
AstNode *current_scope_ast = (current_ast_mod == nullptr) ? current_ast : current_ast_mod;
str = try_pop_module_prefix();
for (auto node : current_scope_ast->children) {
//log("looking at mod scope child %s\n", type2str(node->type).c_str());
switch (node->type) {
case AST_PARAMETER:
case AST_LOCALPARAM:
case AST_WIRE:
case AST_AUTOWIRE:
case AST_GENVAR:
case AST_MEMORY:
case AST_FUNCTION:
case AST_TASK:
case AST_DPI_FUNCTION:
//log("found child %s, %s\n", type2str(node->type).c_str(), node->str.c_str());
if (str == node->str) {
//log("add %s, type %s to scope\n", str.c_str(), type2str(node->type).c_str());
current_scope[node->str] = node;
}
break;
case AST_ENUM:
current_scope[node->str] = node;
for (auto enum_node : node->children) {
log_assert(enum_node->type==AST_ENUM_ITEM);
if (str == enum_node->str) {
//log("\nadding enum item %s to scope\n", str.c_str());
current_scope[str] = enum_node;
}
}
break;
default:
break;
}
}
}
if (current_scope.count(str) == 0) {
if (current_ast_mod == nullptr) {
log_file_error(filename, location.first_line, "Identifier `%s' is implicitly declared outside of a module.\n", str.c_str());
} else if (flag_autowire || str == "\\$global_clock") {
AstNode *auto_wire = new AstNode(AST_AUTOWIRE);
auto_wire->str = str;
current_ast_mod->children.push_back(auto_wire);
current_scope[str] = auto_wire;
did_something = true;
} else {
log_file_error(filename, location.first_line, "Identifier `%s' is implicitly declared and `default_nettype is set to none.\n", str.c_str());
}
}
if (id2ast != current_scope[str]) {
id2ast = current_scope[str];
did_something = true;
}
}
// split memory access with bit select to individual statements
if (type == AST_IDENTIFIER && children.size() == 2 && children[0]->type == AST_RANGE && children[1]->type == AST_RANGE && !in_lvalue && stage == 2)
{
if (id2ast == NULL || id2ast->type != AST_MEMORY || children[0]->children.size() != 1)
log_file_error(filename, location.first_line, "Invalid bit-select on memory access!\n");
int mem_width, mem_size, addr_bits;
id2ast->meminfo(mem_width, mem_size, addr_bits);
int data_range_left = id2ast->children[0]->range_left;
int data_range_right = id2ast->children[0]->range_right;
if (id2ast->children[0]->range_swapped)
std::swap(data_range_left, data_range_right);
std::stringstream sstr;
sstr << "$mem2bits$" << str << "$" << filename << ":" << location.first_line << "$" << (autoidx++);
std::string wire_id = sstr.str();
AstNode *wire = new AstNode(AST_WIRE, new AstNode(AST_RANGE, mkconst_int(data_range_left, true), mkconst_int(data_range_right, true)));
wire->str = wire_id;
if (current_block)
wire->attributes[ID::nosync] = AstNode::mkconst_int(1, false);
current_ast_mod->children.push_back(wire);
while (wire->simplify(true, false, false, 1, -1, false, false)) { }
AstNode *data = clone();
delete data->children[1];
data->children.pop_back();
AstNode *assign = new AstNode(AST_ASSIGN_EQ, new AstNode(AST_IDENTIFIER), data);
assign->children[0]->str = wire_id;
assign->children[0]->was_checked = true;
if (current_block)
{
size_t assign_idx = 0;
while (assign_idx < current_block->children.size() && current_block->children[assign_idx] != current_block_child)
assign_idx++;
log_assert(assign_idx < current_block->children.size());
current_block->children.insert(current_block->children.begin()+assign_idx, assign);
wire->is_reg = true;
}
else
{
AstNode *proc = new AstNode(AST_ALWAYS, new AstNode(AST_BLOCK));
proc->children[0]->children.push_back(assign);
current_ast_mod->children.push_back(proc);
}
newNode = new AstNode(AST_IDENTIFIER, children[1]->clone());
newNode->str = wire_id;
newNode->integer = integer; // save original number of dimensions for $size() etc.
newNode->id2ast = wire;
goto apply_newNode;
}
if (type == AST_WHILE)
log_file_error(filename, location.first_line, "While loops are only allowed in constant functions!\n");
if (type == AST_REPEAT)
{
AstNode *count = children[0];
AstNode *body = children[1];
// eval count expression
while (count->simplify(true, false, false, stage, 32, true, false)) { }
if (count->type != AST_CONSTANT)
log_file_error(filename, location.first_line, "Repeat loops outside must have constant repeat counts!\n");
// convert to a block with the body repeated n times
type = AST_BLOCK;
children.clear();
for (int i = 0; i < count->bitsAsConst().as_int(); i++)
children.insert(children.begin(), body->clone());
delete count;
delete body;
did_something = true;
}
// unroll for loops and generate-for blocks
if ((type == AST_GENFOR || type == AST_FOR) && children.size() != 0)
{
AstNode *init_ast = children[0];
AstNode *while_ast = children[1];
AstNode *next_ast = children[2];
AstNode *body_ast = children[3];
while (body_ast->type == AST_GENBLOCK && body_ast->str.empty() &&
body_ast->children.size() == 1 && body_ast->children.at(0)->type == AST_GENBLOCK)
body_ast = body_ast->children.at(0);
const char* loop_type_str = "procedural";
const char* var_type_str = "register";
AstNodeType var_type = AST_WIRE;
if (type == AST_GENFOR) {
loop_type_str = "generate";
var_type_str = "genvar";
var_type = AST_GENVAR;
}
if (init_ast->type != AST_ASSIGN_EQ)
log_file_error(filename, location.first_line, "Unsupported 1st expression of %s for-loop!\n", loop_type_str);
if (next_ast->type != AST_ASSIGN_EQ)
log_file_error(filename, location.first_line, "Unsupported 3rd expression of %s for-loop!\n", loop_type_str);
if (init_ast->children[0]->id2ast == NULL || init_ast->children[0]->id2ast->type != var_type)
log_file_error(filename, location.first_line, "Left hand side of 1st expression of %s for-loop is not a %s!\n", loop_type_str, var_type_str);
if (next_ast->children[0]->id2ast == NULL || next_ast->children[0]->id2ast->type != var_type)
log_file_error(filename, location.first_line, "Left hand side of 3rd expression of %s for-loop is not a %s!\n", loop_type_str, var_type_str);
if (init_ast->children[0]->id2ast != next_ast->children[0]->id2ast)
log_file_error(filename, location.first_line, "Incompatible left-hand sides in 1st and 3rd expression of %s for-loop!\n", loop_type_str);
// eval 1st expression
AstNode *varbuf = init_ast->children[1]->clone();
{
int expr_width_hint = -1;
bool expr_sign_hint = true;
varbuf->detectSignWidth(expr_width_hint, expr_sign_hint);
while (varbuf->simplify(true, false, false, stage, 32, true, false)) { }
}
if (varbuf->type != AST_CONSTANT)
log_file_error(filename, location.first_line, "Right hand side of 1st expression of %s for-loop is not constant!\n", loop_type_str);
auto resolved = current_scope.at(init_ast->children[0]->str);
if (resolved->range_valid) {
int const_size = varbuf->range_left - varbuf->range_right;
int resolved_size = resolved->range_left - resolved->range_right;
if (const_size < resolved_size) {
for (int i = const_size; i < resolved_size; i++)
varbuf->bits.push_back(resolved->is_signed ? varbuf->bits.back() : State::S0);
varbuf->range_left = resolved->range_left;
varbuf->range_right = resolved->range_right;
varbuf->range_swapped = resolved->range_swapped;
varbuf->range_valid = resolved->range_valid;
}
}
varbuf = new AstNode(AST_LOCALPARAM, varbuf);
varbuf->str = init_ast->children[0]->str;
AstNode *backup_scope_varbuf = current_scope[varbuf->str];
current_scope[varbuf->str] = varbuf;
size_t current_block_idx = 0;
if (type == AST_FOR) {
while (current_block_idx < current_block->children.size() &&
current_block->children[current_block_idx] != current_block_child)
current_block_idx++;
}
while (1)
{
// eval 2nd expression
AstNode *buf = while_ast->clone();
{
int expr_width_hint = -1;
bool expr_sign_hint = true;
buf->detectSignWidth(expr_width_hint, expr_sign_hint);
while (buf->simplify(true, false, false, stage, expr_width_hint, expr_sign_hint, false)) { }
}
if (buf->type != AST_CONSTANT)
log_file_error(filename, location.first_line, "2nd expression of %s for-loop is not constant!\n", loop_type_str);
if (buf->integer == 0) {
delete buf;
break;
}
delete buf;
// expand body
int index = varbuf->children[0]->integer;
log_assert(body_ast->type == AST_GENBLOCK || body_ast->type == AST_BLOCK);
log_assert(!body_ast->str.empty());
buf = body_ast->clone();
std::stringstream sstr;
sstr << buf->str << "[" << index << "].";
std::string prefix = sstr.str();
// create a scoped localparam for the current value of the loop variable
AstNode *local_index = varbuf->clone();
size_t pos = local_index->str.rfind('.');
if (pos != std::string::npos) // remove outer prefix
local_index->str = "\\" + local_index->str.substr(pos + 1);
local_index->str = prefix_id(prefix, local_index->str);
current_scope[local_index->str] = local_index;
current_ast_mod->children.push_back(local_index);
buf->expand_genblock(prefix);
if (type == AST_GENFOR) {
for (size_t i = 0; i < buf->children.size(); i++) {
buf->children[i]->simplify(const_fold, false, false, stage, -1, false, false);
current_ast_mod->children.push_back(buf->children[i]);
}
} else {
for (size_t i = 0; i < buf->children.size(); i++)
current_block->children.insert(current_block->children.begin() + current_block_idx++, buf->children[i]);
}
buf->children.clear();
delete buf;
// eval 3rd expression
buf = next_ast->children[1]->clone();
{
int expr_width_hint = -1;
bool expr_sign_hint = true;
buf->detectSignWidth(expr_width_hint, expr_sign_hint);
while (buf->simplify(true, false, false, stage, expr_width_hint, expr_sign_hint, true)) { }
}
if (buf->type != AST_CONSTANT)
log_file_error(filename, location.first_line, "Right hand side of 3rd expression of %s for-loop is not constant (%s)!\n", loop_type_str, type2str(buf->type).c_str());
delete varbuf->children[0];
varbuf->children[0] = buf;
}
if (type == AST_FOR) {
AstNode *buf = next_ast->clone();
delete buf->children[1];
buf->children[1] = varbuf->children[0]->clone();
current_block->children.insert(current_block->children.begin() + current_block_idx++, buf);
}
current_scope[varbuf->str] = backup_scope_varbuf;
delete varbuf;
delete_children();
did_something = true;
}
// check for local objects in unnamed block
if (type == AST_BLOCK && str.empty())
{
for (size_t i = 0; i < children.size(); i++)
if (children[i]->type == AST_WIRE || children[i]->type == AST_MEMORY || children[i]->type == AST_PARAMETER || children[i]->type == AST_LOCALPARAM || children[i]->type == AST_TYPEDEF)
{
log_assert(!VERILOG_FRONTEND::sv_mode);
log_file_error(children[i]->filename, children[i]->location.first_line, "Local declaration in unnamed block is only supported in SystemVerilog mode!\n");
}
}
// transform block with name
if (type == AST_BLOCK && !str.empty())
{
expand_genblock(str + ".");
std::vector<AstNode*> new_children;
for (size_t i = 0; i < children.size(); i++)
if (children[i]->type == AST_WIRE || children[i]->type == AST_MEMORY || children[i]->type == AST_PARAMETER || children[i]->type == AST_LOCALPARAM || children[i]->type == AST_TYPEDEF) {
children[i]->simplify(false, false, false, stage, -1, false, false);
current_ast_mod->children.push_back(children[i]);
current_scope[children[i]->str] = children[i];
} else
new_children.push_back(children[i]);
children.swap(new_children);
did_something = true;
str.clear();
}
// simplify unconditional generate block
if (type == AST_GENBLOCK && children.size() != 0)
{
if (!str.empty()) {
expand_genblock(str + ".");
}
for (size_t i = 0; i < children.size(); i++) {
children[i]->simplify(const_fold, false, false, stage, -1, false, false);
current_ast_mod->children.push_back(children[i]);
}
children.clear();
did_something = true;
}
// simplify generate-if blocks
if (type == AST_GENIF && children.size() != 0)
{
AstNode *buf = children[0]->clone();
while (buf->simplify(true, false, false, stage, width_hint, sign_hint, false)) { }
if (buf->type != AST_CONSTANT) {
// for (auto f : log_files)
// dumpAst(f, "verilog-ast> ");
log_file_error(filename, location.first_line, "Condition for generate if is not constant!\n");
}
if (buf->asBool() != 0) {
delete buf;
buf = children[1]->clone();
} else {
delete buf;
buf = children.size() > 2 ? children[2]->clone() : NULL;
}
if (buf)
{
if (buf->type != AST_GENBLOCK)
buf = new AstNode(AST_GENBLOCK, buf);
if (!buf->str.empty()) {
buf->expand_genblock(buf->str + ".");
}
for (size_t i = 0; i < buf->children.size(); i++) {
buf->children[i]->simplify(const_fold, false, false, stage, -1, false, false);
current_ast_mod->children.push_back(buf->children[i]);
}
buf->children.clear();
delete buf;
}
delete_children();
did_something = true;
}
// simplify generate-case blocks
if (type == AST_GENCASE && children.size() != 0)
{
AstNode *buf = children[0]->clone();
while (buf->simplify(true, false, false, stage, width_hint, sign_hint, false)) { }
if (buf->type != AST_CONSTANT) {
// for (auto f : log_files)
// dumpAst(f, "verilog-ast> ");
log_file_error(filename, location.first_line, "Condition for generate case is not constant!\n");
}
bool ref_signed = buf->is_signed;
RTLIL::Const ref_value = buf->bitsAsConst();
delete buf;
AstNode *selected_case = NULL;
for (size_t i = 1; i < children.size(); i++)
{
log_assert(children.at(i)->type == AST_COND || children.at(i)->type == AST_CONDX || children.at(i)->type == AST_CONDZ);
AstNode *this_genblock = NULL;
for (auto child : children.at(i)->children) {
log_assert(this_genblock == NULL);
if (child->type == AST_GENBLOCK)
this_genblock = child;
}
for (auto child : children.at(i)->children)
{
if (child->type == AST_DEFAULT) {
if (selected_case == NULL)
selected_case = this_genblock;
continue;
}
if (child->type == AST_GENBLOCK)
continue;
buf = child->clone();
while (buf->simplify(true, false, false, stage, width_hint, sign_hint, true)) { }
if (buf->type != AST_CONSTANT) {
// for (auto f : log_files)
// dumpAst(f, "verilog-ast> ");
log_file_error(filename, location.first_line, "Expression in generate case is not constant!\n");
}
bool is_selected = RTLIL::const_eq(ref_value, buf->bitsAsConst(), ref_signed && buf->is_signed, ref_signed && buf->is_signed, 1).as_bool();
delete buf;
if (is_selected) {
selected_case = this_genblock;
i = children.size();
break;
}
}
}
if (selected_case != NULL)
{
log_assert(selected_case->type == AST_GENBLOCK);
buf = selected_case->clone();
if (!buf->str.empty()) {
buf->expand_genblock(buf->str + ".");
}
for (size_t i = 0; i < buf->children.size(); i++) {
buf->children[i]->simplify(const_fold, false, false, stage, -1, false, false);
current_ast_mod->children.push_back(buf->children[i]);
}
buf->children.clear();
delete buf;
}
delete_children();
did_something = true;
}
// unroll cell arrays
if (type == AST_CELLARRAY)
{
if (!children.at(0)->range_valid)
log_file_error(filename, location.first_line, "Non-constant array range on cell array.\n");
newNode = new AstNode(AST_GENBLOCK);
int num = max(children.at(0)->range_left, children.at(0)->range_right) - min(children.at(0)->range_left, children.at(0)->range_right) + 1;
for (int i = 0; i < num; i++) {
int idx = children.at(0)->range_left > children.at(0)->range_right ? children.at(0)->range_right + i : children.at(0)->range_right - i;
AstNode *new_cell = children.at(1)->clone();
newNode->children.push_back(new_cell);
new_cell->str += stringf("[%d]", idx);
if (new_cell->type == AST_PRIMITIVE) {
log_file_error(filename, location.first_line, "Cell arrays of primitives are currently not supported.\n");
} else {
log_assert(new_cell->children.at(0)->type == AST_CELLTYPE);
new_cell->children.at(0)->str = stringf("$array:%d:%d:%s", i, num, new_cell->children.at(0)->str.c_str());
}
}
goto apply_newNode;
}
// replace primitives with assignments
if (type == AST_PRIMITIVE)
{
if (children.size() < 2)
log_file_error(filename, location.first_line, "Insufficient number of arguments for primitive `%s'!\n", str.c_str());
std::vector<AstNode*> children_list;
for (auto child : children) {
log_assert(child->type == AST_ARGUMENT);
log_assert(child->children.size() == 1);
children_list.push_back(child->children[0]);
child->children.clear();
delete child;
}
children.clear();
if (str == "bufif0" || str == "bufif1" || str == "notif0" || str == "notif1")
{
if (children_list.size() != 3)
log_file_error(filename, location.first_line, "Invalid number of arguments for primitive `%s'!\n", str.c_str());
std::vector<RTLIL::State> z_const(1, RTLIL::State::Sz);
AstNode *mux_input = children_list.at(1);
if (str == "notif0" || str == "notif1") {
mux_input = new AstNode(AST_BIT_NOT, mux_input);
}
AstNode *node = new AstNode(AST_TERNARY, children_list.at(2));
if (str == "bufif0") {
node->children.push_back(AstNode::mkconst_bits(z_const, false));
node->children.push_back(mux_input);
} else {
node->children.push_back(mux_input);
node->children.push_back(AstNode::mkconst_bits(z_const, false));
}
str.clear();
type = AST_ASSIGN;
children.push_back(children_list.at(0));
children.back()->was_checked = true;
children.push_back(node);
did_something = true;
}
else if (str == "buf" || str == "not")
{
AstNode *input = children_list.back();
if (str == "not")
input = new AstNode(AST_BIT_NOT, input);
newNode = new AstNode(AST_GENBLOCK);
for (auto it = children_list.begin(); it != std::prev(children_list.end()); it++) {
newNode->children.push_back(new AstNode(AST_ASSIGN, *it, input->clone()));
newNode->children.back()->was_checked = true;
}
delete input;
did_something = true;
}
else
{
AstNodeType op_type = AST_NONE;
bool invert_results = false;
if (str == "and")
op_type = AST_BIT_AND;
if (str == "nand")
op_type = AST_BIT_AND, invert_results = true;
if (str == "or")
op_type = AST_BIT_OR;
if (str == "nor")
op_type = AST_BIT_OR, invert_results = true;
if (str == "xor")
op_type = AST_BIT_XOR;
if (str == "xnor")
op_type = AST_BIT_XOR, invert_results = true;
log_assert(op_type != AST_NONE);
AstNode *node = children_list[1];
if (op_type != AST_POS)
for (size_t i = 2; i < children_list.size(); i++) {
node = new AstNode(op_type, node, children_list[i]);
node->location = location;
}
if (invert_results)
node = new AstNode(AST_BIT_NOT, node);
str.clear();
type = AST_ASSIGN;
children.push_back(children_list[0]);
children.back()->was_checked = true;
children.push_back(node);
did_something = true;
}
}
// replace dynamic ranges in left-hand side expressions (e.g. "foo[bar] <= 1'b1;") with
// either a big case block that selects the correct single-bit assignment, or mask and
// shift operations.
if (type == AST_ASSIGN_EQ || type == AST_ASSIGN_LE)
{
if (children[0]->type != AST_IDENTIFIER || children[0]->children.size() == 0)
goto skip_dynamic_range_lvalue_expansion;
if (children[0]->children[0]->range_valid || did_something)
goto skip_dynamic_range_lvalue_expansion;
if (children[0]->id2ast == NULL || children[0]->id2ast->type != AST_WIRE)
goto skip_dynamic_range_lvalue_expansion;
if (!children[0]->id2ast->range_valid)
goto skip_dynamic_range_lvalue_expansion;
int source_width = children[0]->id2ast->range_left - children[0]->id2ast->range_right + 1;
int result_width = 1;
AstNode *shift_expr = NULL;
AstNode *range = children[0]->children[0];
if (range->children.size() == 1) {
shift_expr = range->children[0]->clone();
} else {
shift_expr = range->children[1]->clone();
AstNode *left_at_zero_ast = range->children[0]->clone();
AstNode *right_at_zero_ast = range->children[1]->clone();
while (left_at_zero_ast->simplify(true, true, false, stage, -1, false, false)) { }
while (right_at_zero_ast->simplify(true, true, false, stage, -1, false, false)) { }
if (left_at_zero_ast->type != AST_CONSTANT || right_at_zero_ast->type != AST_CONSTANT)
log_file_error(filename, location.first_line, "Unsupported expression on dynamic range select on signal `%s'!\n", str.c_str());
result_width = abs(int(left_at_zero_ast->integer - right_at_zero_ast->integer)) + 1;
delete left_at_zero_ast;
delete right_at_zero_ast;
}
bool use_case_method = false;
if (children[0]->id2ast->attributes.count(ID::nowrshmsk)) {
AstNode *node = children[0]->id2ast->attributes.at(ID::nowrshmsk);
while (node->simplify(true, false, false, stage, -1, false, false)) { }
if (node->type != AST_CONSTANT)
log_file_error(filename, location.first_line, "Non-constant value for `nowrshmsk' attribute on `%s'!\n", children[0]->id2ast->str.c_str());
if (node->asAttrConst().as_bool())
use_case_method = true;
}
if (!use_case_method && current_always->detect_latch(children[0]->str))
use_case_method = true;
if (use_case_method)
{
// big case block
did_something = true;
newNode = new AstNode(AST_CASE, shift_expr);
for (int i = 0; i < source_width; i++) {
int start_bit = children[0]->id2ast->range_right + i;
int end_bit = std::min(start_bit+result_width,source_width) - 1;
AstNode *cond = new AstNode(AST_COND, mkconst_int(start_bit, true));
AstNode *lvalue = children[0]->clone();
lvalue->delete_children();
lvalue->children.push_back(new AstNode(AST_RANGE,
mkconst_int(end_bit, true), mkconst_int(start_bit, true)));
cond->children.push_back(new AstNode(AST_BLOCK, new AstNode(type, lvalue, children[1]->clone())));
newNode->children.push_back(cond);
}
}
else
{
// mask and shift operations, disabled for now
AstNode *wire_mask = new AstNode(AST_WIRE, new AstNode(AST_RANGE, mkconst_int(source_width-1, true), mkconst_int(0, true)));
wire_mask->str = stringf("$bitselwrite$mask$%s:%d$%d", filename.c_str(), location.first_line, autoidx++);
wire_mask->attributes[ID::nosync] = AstNode::mkconst_int(1, false);
wire_mask->is_logic = true;
while (wire_mask->simplify(true, false, false, 1, -1, false, false)) { }
current_ast_mod->children.push_back(wire_mask);
AstNode *wire_data = new AstNode(AST_WIRE, new AstNode(AST_RANGE, mkconst_int(source_width-1, true), mkconst_int(0, true)));
wire_data->str = stringf("$bitselwrite$data$%s:%d$%d", filename.c_str(), location.first_line, autoidx++);
wire_data->attributes[ID::nosync] = AstNode::mkconst_int(1, false);
wire_data->is_logic = true;
while (wire_data->simplify(true, false, false, 1, -1, false, false)) { }
current_ast_mod->children.push_back(wire_data);
did_something = true;
newNode = new AstNode(AST_BLOCK);
AstNode *lvalue = children[0]->clone();
lvalue->delete_children();
AstNode *ref_mask = new AstNode(AST_IDENTIFIER);
ref_mask->str = wire_mask->str;
ref_mask->id2ast = wire_mask;
ref_mask->was_checked = true;
AstNode *ref_data = new AstNode(AST_IDENTIFIER);
ref_data->str = wire_data->str;
ref_data->id2ast = wire_data;
ref_data->was_checked = true;
AstNode *old_data = lvalue->clone();
if (type == AST_ASSIGN_LE)
old_data->lookahead = true;
AstNode *shamt = shift_expr;
int shamt_width_hint = 0;
bool shamt_sign_hint = true;
shamt->detectSignWidth(shamt_width_hint, shamt_sign_hint);
int start_bit = children[0]->id2ast->range_right;
bool use_shift = shamt_sign_hint;
if (start_bit != 0) {
shamt = new AstNode(AST_SUB, shamt, mkconst_int(start_bit, true));
use_shift = true;
}
AstNode *t;
t = mkconst_bits(std::vector<RTLIL::State>(result_width, State::S1), false);
if (use_shift)
t = new AstNode(AST_SHIFT, t, new AstNode(AST_NEG, shamt->clone()));
else
t = new AstNode(AST_SHIFT_LEFT, t, shamt->clone());
t = new AstNode(AST_ASSIGN_EQ, ref_mask->clone(), t);
newNode->children.push_back(t);
t = new AstNode(AST_BIT_AND, mkconst_bits(std::vector<RTLIL::State>(result_width, State::S1), false), children[1]->clone());
if (use_shift)
t = new AstNode(AST_SHIFT, t, new AstNode(AST_NEG, shamt));
else
t = new AstNode(AST_SHIFT_LEFT, t, shamt);
t = new AstNode(AST_ASSIGN_EQ, ref_data->clone(), t);
newNode->children.push_back(t);
t = new AstNode(AST_BIT_AND, old_data, new AstNode(AST_BIT_NOT, ref_mask));
t = new AstNode(AST_BIT_OR, t, ref_data);
t = new AstNode(type, lvalue, t);
newNode->children.push_back(t);
}
goto apply_newNode;
}
skip_dynamic_range_lvalue_expansion:;
if (stage > 1 && (type == AST_ASSERT || type == AST_ASSUME || type == AST_LIVE || type == AST_FAIR || type == AST_COVER) && current_block != NULL)
{
std::stringstream sstr;
sstr << "$formal$" << filename << ":" << location.first_line << "$" << (autoidx++);
std::string id_check = sstr.str() + "_CHECK", id_en = sstr.str() + "_EN";
AstNode *wire_check = new AstNode(AST_WIRE);
wire_check->str = id_check;
wire_check->was_checked = true;
current_ast_mod->children.push_back(wire_check);
current_scope[wire_check->str] = wire_check;
while (wire_check->simplify(true, false, false, 1, -1, false, false)) { }
AstNode *wire_en = new AstNode(AST_WIRE);
wire_en->str = id_en;
wire_en->was_checked = true;
current_ast_mod->children.push_back(wire_en);
if (current_always_clocked) {
current_ast_mod->children.push_back(new AstNode(AST_INITIAL, new AstNode(AST_BLOCK, new AstNode(AST_ASSIGN_LE, new AstNode(AST_IDENTIFIER), AstNode::mkconst_int(0, false, 1)))));
current_ast_mod->children.back()->children[0]->children[0]->children[0]->str = id_en;
current_ast_mod->children.back()->children[0]->children[0]->children[0]->was_checked = true;
}
current_scope[wire_en->str] = wire_en;
while (wire_en->simplify(true, false, false, 1, -1, false, false)) { }
AstNode *check_defval;
if (type == AST_LIVE || type == AST_FAIR) {
check_defval = new AstNode(AST_REDUCE_BOOL, children[0]->clone());
} else {
std::vector<RTLIL::State> x_bit;
x_bit.push_back(RTLIL::State::Sx);
check_defval = mkconst_bits(x_bit, false);
}
AstNode *assign_check = new AstNode(AST_ASSIGN_LE, new AstNode(AST_IDENTIFIER), check_defval);
assign_check->children[0]->str = id_check;
assign_check->children[0]->was_checked = true;
AstNode *assign_en = new AstNode(AST_ASSIGN_LE, new AstNode(AST_IDENTIFIER), mkconst_int(0, false, 1));
assign_en->children[0]->str = id_en;
assign_en->children[0]->was_checked = true;
AstNode *default_signals = new AstNode(AST_BLOCK);
default_signals->children.push_back(assign_check);
default_signals->children.push_back(assign_en);
current_top_block->children.insert(current_top_block->children.begin(), default_signals);
if (type == AST_LIVE || type == AST_FAIR) {
assign_check = nullptr;
} else {
assign_check = new AstNode(AST_ASSIGN_LE, new AstNode(AST_IDENTIFIER), new AstNode(AST_REDUCE_BOOL, children[0]->clone()));
assign_check->children[0]->str = id_check;
assign_check->children[0]->was_checked = true;
}
if (current_always == nullptr || current_always->type != AST_INITIAL) {
assign_en = new AstNode(AST_ASSIGN_LE, new AstNode(AST_IDENTIFIER), mkconst_int(1, false, 1));
} else {
assign_en = new AstNode(AST_ASSIGN_LE, new AstNode(AST_IDENTIFIER), new AstNode(AST_FCALL));
assign_en->children[1]->str = "\\$initstate";
}
assign_en->children[0]->str = id_en;
assign_en->children[0]->was_checked = true;
newNode = new AstNode(AST_BLOCK);
if (assign_check != nullptr)
newNode->children.push_back(assign_check);
newNode->children.push_back(assign_en);
AstNode *assertnode = new AstNode(type);
assertnode->location = location;
assertnode->str = str;
assertnode->children.push_back(new AstNode(AST_IDENTIFIER));
assertnode->children.push_back(new AstNode(AST_IDENTIFIER));
assertnode->children[0]->str = id_check;
assertnode->children[1]->str = id_en;
assertnode->attributes.swap(attributes);
current_ast_mod->children.push_back(assertnode);
goto apply_newNode;
}
if (stage > 1 && (type == AST_ASSERT || type == AST_ASSUME || type == AST_LIVE || type == AST_FAIR || type == AST_COVER) && children.size() == 1)
{
children.push_back(mkconst_int(1, false, 1));
did_something = true;
}
// found right-hand side identifier for memory -> replace with memory read port
if (stage > 1 && type == AST_IDENTIFIER && id2ast != NULL && id2ast->type == AST_MEMORY && !in_lvalue &&
children.size() == 1 && children[0]->type == AST_RANGE && children[0]->children.size() == 1) {
newNode = new AstNode(AST_MEMRD, children[0]->children[0]->clone());
newNode->str = str;
newNode->id2ast = id2ast;
goto apply_newNode;
}
// assignment with nontrivial member in left-hand concat expression -> split assignment
if ((type == AST_ASSIGN_EQ || type == AST_ASSIGN_LE) && children[0]->type == AST_CONCAT && width_hint > 0)
{
bool found_nontrivial_member = false;
for (auto child : children[0]->children) {
if (child->type == AST_IDENTIFIER && child->id2ast != NULL && child->id2ast->type == AST_MEMORY)
found_nontrivial_member = true;
}
if (found_nontrivial_member)
{
newNode = new AstNode(AST_BLOCK);
AstNode *wire_tmp = new AstNode(AST_WIRE, new AstNode(AST_RANGE, mkconst_int(width_hint-1, true), mkconst_int(0, true)));
wire_tmp->str = stringf("$splitcmplxassign$%s:%d$%d", filename.c_str(), location.first_line, autoidx++);
current_ast_mod->children.push_back(wire_tmp);
current_scope[wire_tmp->str] = wire_tmp;
wire_tmp->attributes[ID::nosync] = AstNode::mkconst_int(1, false);
while (wire_tmp->simplify(true, false, false, 1, -1, false, false)) { }
wire_tmp->is_logic = true;
AstNode *wire_tmp_id = new AstNode(AST_IDENTIFIER);
wire_tmp_id->str = wire_tmp->str;
newNode->children.push_back(new AstNode(AST_ASSIGN_EQ, wire_tmp_id, children[1]->clone()));
newNode->children.back()->was_checked = true;
int cursor = 0;
for (auto child : children[0]->children)
{
int child_width_hint = -1;
bool child_sign_hint = true;
child->detectSignWidth(child_width_hint, child_sign_hint);
AstNode *rhs = wire_tmp_id->clone();
rhs->children.push_back(new AstNode(AST_RANGE, AstNode::mkconst_int(cursor+child_width_hint-1, true), AstNode::mkconst_int(cursor, true)));
newNode->children.push_back(new AstNode(type, child->clone(), rhs));
cursor += child_width_hint;
}
goto apply_newNode;
}
}
// assignment with memory in left-hand side expression -> replace with memory write port
if (stage > 1 && (type == AST_ASSIGN_EQ || type == AST_ASSIGN_LE) && children[0]->type == AST_IDENTIFIER &&
children[0]->id2ast && children[0]->id2ast->type == AST_MEMORY && children[0]->id2ast->children.size() >= 2 &&
children[0]->id2ast->children[0]->range_valid && children[0]->id2ast->children[1]->range_valid &&
(children[0]->children.size() == 1 || children[0]->children.size() == 2) && children[0]->children[0]->type == AST_RANGE)
{
std::stringstream sstr;
sstr << "$memwr$" << children[0]->str << "$" << filename << ":" << location.first_line << "$" << (autoidx++);
std::string id_addr = sstr.str() + "_ADDR", id_data = sstr.str() + "_DATA", id_en = sstr.str() + "_EN";
int mem_width, mem_size, addr_bits;
bool mem_signed = children[0]->id2ast->is_signed;
children[0]->id2ast->meminfo(mem_width, mem_size, addr_bits);
newNode = new AstNode(AST_BLOCK);
AstNode *defNode = new AstNode(AST_BLOCK);
int data_range_left = children[0]->id2ast->children[0]->range_left;
int data_range_right = children[0]->id2ast->children[0]->range_right;
int mem_data_range_offset = std::min(data_range_left, data_range_right);
int addr_width_hint = -1;
bool addr_sign_hint = true;
children[0]->children[0]->children[0]->detectSignWidthWorker(addr_width_hint, addr_sign_hint);
addr_bits = std::max(addr_bits, addr_width_hint);
std::vector<RTLIL::State> x_bits_addr, x_bits_data, set_bits_en;
for (int i = 0; i < addr_bits; i++)
x_bits_addr.push_back(RTLIL::State::Sx);
for (int i = 0; i < mem_width; i++)
x_bits_data.push_back(RTLIL::State::Sx);
for (int i = 0; i < mem_width; i++)
set_bits_en.push_back(RTLIL::State::S1);
AstNode *node_addr = nullptr;
if (children[0]->children[0]->children[0]->isConst()) {
node_addr = children[0]->children[0]->children[0]->clone();
} else {
AstNode *wire_addr = new AstNode(AST_WIRE, new AstNode(AST_RANGE, mkconst_int(addr_bits-1, true), mkconst_int(0, true)));
wire_addr->str = id_addr;
wire_addr->was_checked = true;
current_ast_mod->children.push_back(wire_addr);
current_scope[wire_addr->str] = wire_addr;
while (wire_addr->simplify(true, false, false, 1, -1, false, false)) { }
AstNode *assign_addr = new AstNode(AST_ASSIGN_EQ, new AstNode(AST_IDENTIFIER), mkconst_bits(x_bits_addr, false));
assign_addr->children[0]->str = id_addr;
assign_addr->children[0]->was_checked = true;
defNode->children.push_back(assign_addr);
assign_addr = new AstNode(AST_ASSIGN_EQ, new AstNode(AST_IDENTIFIER), children[0]->children[0]->children[0]->clone());
assign_addr->children[0]->str = id_addr;
assign_addr->children[0]->was_checked = true;
newNode->children.push_back(assign_addr);
node_addr = new AstNode(AST_IDENTIFIER);
node_addr->str = id_addr;
}
AstNode *node_data = nullptr;
if (children[0]->children.size() == 1 && children[1]->isConst()) {
node_data = children[1]->clone();
} else {
AstNode *wire_data = new AstNode(AST_WIRE, new AstNode(AST_RANGE, mkconst_int(mem_width-1, true), mkconst_int(0, true)));
wire_data->str = id_data;
wire_data->was_checked = true;
wire_data->is_signed = mem_signed;
current_ast_mod->children.push_back(wire_data);
current_scope[wire_data->str] = wire_data;
while (wire_data->simplify(true, false, false, 1, -1, false, false)) { }
AstNode *assign_data = new AstNode(AST_ASSIGN_EQ, new AstNode(AST_IDENTIFIER), mkconst_bits(x_bits_data, false));
assign_data->children[0]->str = id_data;
assign_data->children[0]->was_checked = true;
defNode->children.push_back(assign_data);
node_data = new AstNode(AST_IDENTIFIER);
node_data->str = id_data;
}
AstNode *wire_en = new AstNode(AST_WIRE, new AstNode(AST_RANGE, mkconst_int(mem_width-1, true), mkconst_int(0, true)));
wire_en->str = id_en;
wire_en->was_checked = true;
current_ast_mod->children.push_back(wire_en);
current_scope[wire_en->str] = wire_en;
while (wire_en->simplify(true, false, false, 1, -1, false, false)) { }
AstNode *assign_en_first = new AstNode(AST_ASSIGN_EQ, new AstNode(AST_IDENTIFIER), mkconst_int(0, false, mem_width));
assign_en_first->children[0]->str = id_en;
assign_en_first->children[0]->was_checked = true;
defNode->children.push_back(assign_en_first);
AstNode *node_en = new AstNode(AST_IDENTIFIER);
node_en->str = id_en;
if (!defNode->children.empty())
current_top_block->children.insert(current_top_block->children.begin(), defNode);
else
delete defNode;
AstNode *assign_data = nullptr;
AstNode *assign_en = nullptr;
if (children[0]->children.size() == 2)
{
if (children[0]->children[1]->range_valid)
{
int offset = children[0]->children[1]->range_right;
int width = children[0]->children[1]->range_left - offset + 1;
offset -= mem_data_range_offset;
std::vector<RTLIL::State> padding_x(offset, RTLIL::State::Sx);
assign_data = new AstNode(AST_ASSIGN_EQ, new AstNode(AST_IDENTIFIER),
new AstNode(AST_CONCAT, mkconst_bits(padding_x, false), children[1]->clone()));
assign_data->children[0]->str = id_data;
assign_data->children[0]->was_checked = true;
for (int i = 0; i < mem_width; i++)
set_bits_en[i] = offset <= i && i < offset+width ? RTLIL::State::S1 : RTLIL::State::S0;
assign_en = new AstNode(AST_ASSIGN_EQ, new AstNode(AST_IDENTIFIER), mkconst_bits(set_bits_en, false));
assign_en->children[0]->str = id_en;
assign_en->children[0]->was_checked = true;
}
else
{
AstNode *the_range = children[0]->children[1];
AstNode *left_at_zero_ast = the_range->children[0]->clone();
AstNode *right_at_zero_ast = the_range->children.size() >= 2 ? the_range->children[1]->clone() : left_at_zero_ast->clone();
AstNode *offset_ast = right_at_zero_ast->clone();
if (mem_data_range_offset)
offset_ast = new AstNode(AST_SUB, offset_ast, mkconst_int(mem_data_range_offset, true));
while (left_at_zero_ast->simplify(true, true, false, 1, -1, false, false)) { }
while (right_at_zero_ast->simplify(true, true, false, 1, -1, false, false)) { }
if (left_at_zero_ast->type != AST_CONSTANT || right_at_zero_ast->type != AST_CONSTANT)
log_file_error(filename, location.first_line, "Unsupported expression on dynamic range select on signal `%s'!\n", str.c_str());
int width = abs(int(left_at_zero_ast->integer - right_at_zero_ast->integer)) + 1;
assign_data = new AstNode(AST_ASSIGN_EQ, new AstNode(AST_IDENTIFIER),
new AstNode(AST_SHIFT_LEFT, children[1]->clone(), offset_ast->clone()));
assign_data->children[0]->str = id_data;
assign_data->children[0]->was_checked = true;
for (int i = 0; i < mem_width; i++)
set_bits_en[i] = i < width ? RTLIL::State::S1 : RTLIL::State::S0;
assign_en = new AstNode(AST_ASSIGN_EQ, new AstNode(AST_IDENTIFIER),
new AstNode(AST_SHIFT_LEFT, mkconst_bits(set_bits_en, false), offset_ast->clone()));
assign_en->children[0]->str = id_en;
assign_en->children[0]->was_checked = true;
delete left_at_zero_ast;
delete right_at_zero_ast;
delete offset_ast;
}
}
else
{
if (!(children[0]->children.size() == 1 && children[1]->isConst())) {
assign_data = new AstNode(AST_ASSIGN_EQ, new AstNode(AST_IDENTIFIER), children[1]->clone());
assign_data->children[0]->str = id_data;
assign_data->children[0]->was_checked = true;
}
assign_en = new AstNode(AST_ASSIGN_EQ, new AstNode(AST_IDENTIFIER), mkconst_bits(set_bits_en, false));
assign_en->children[0]->str = id_en;
assign_en->children[0]->was_checked = true;
}
if (assign_data)
newNode->children.push_back(assign_data);
if (assign_en)
newNode->children.push_back(assign_en);
AstNode *wrnode;
if (current_always->type == AST_INITIAL)
wrnode = new AstNode(AST_MEMINIT, node_addr, node_data, node_en, mkconst_int(1, false));
else
wrnode = new AstNode(AST_MEMWR, node_addr, node_data, node_en);
wrnode->str = children[0]->str;
wrnode->id2ast = children[0]->id2ast;
wrnode->location = location;
if (wrnode->type == AST_MEMWR) {
int portid = current_memwr_count[wrnode->str]++;
wrnode->children.push_back(mkconst_int(portid, false));
std::vector<RTLIL::State> priority_mask;
for (int i = 0; i < portid; i++) {
bool has_prio = current_memwr_visible[wrnode->str].count(i);
priority_mask.push_back(State(has_prio));
}
wrnode->children.push_back(mkconst_bits(priority_mask, false));
current_memwr_visible[wrnode->str].insert(portid);
current_always->children.push_back(wrnode);
} else {
current_ast_mod->children.push_back(wrnode);
}
if (newNode->children.empty()) {
delete newNode;
newNode = new AstNode();
}
goto apply_newNode;
}
// replace function and task calls with the code from the function or task
if ((type == AST_FCALL || type == AST_TCALL) && !str.empty())
{
if (type == AST_FCALL)
{
if (str == "\\$initstate")
{
int myidx = autoidx++;
AstNode *wire = new AstNode(AST_WIRE);
wire->str = stringf("$initstate$%d_wire", myidx);
current_ast_mod->children.push_back(wire);
while (wire->simplify(true, false, false, 1, -1, false, false)) { }
AstNode *cell = new AstNode(AST_CELL, new AstNode(AST_CELLTYPE), new AstNode(AST_ARGUMENT, new AstNode(AST_IDENTIFIER)));
cell->str = stringf("$initstate$%d", myidx);
cell->children[0]->str = "$initstate";
cell->children[1]->str = "\\Y";
cell->children[1]->children[0]->str = wire->str;
cell->children[1]->children[0]->id2ast = wire;
current_ast_mod->children.push_back(cell);
while (cell->simplify(true, false, false, 1, -1, false, false)) { }
newNode = new AstNode(AST_IDENTIFIER);
newNode->str = wire->str;
newNode->id2ast = wire;
goto apply_newNode;
}
if (str == "\\$past")
{
if (width_hint < 0)
goto replace_fcall_later;
int num_steps = 1;
if (GetSize(children) != 1 && GetSize(children) != 2)
log_file_error(filename, location.first_line, "System function %s got %d arguments, expected 1 or 2.\n",
RTLIL::unescape_id(str).c_str(), int(children.size()));
if (!current_always_clocked)
log_file_error(filename, location.first_line, "System function %s is only allowed in clocked blocks.\n",
RTLIL::unescape_id(str).c_str());
if (GetSize(children) == 2)
{
AstNode *buf = children[1]->clone();
while (buf->simplify(true, false, false, stage, -1, false, false)) { }
if (buf->type != AST_CONSTANT)
log_file_error(filename, location.first_line, "Failed to evaluate system function `%s' with non-constant value.\n", str.c_str());
num_steps = buf->asInt(true);
delete buf;
}
AstNode *block = nullptr;
for (auto child : current_always->children)
if (child->type == AST_BLOCK)
block = child;
log_assert(block != nullptr);
if (num_steps == 0) {
newNode = children[0]->clone();
goto apply_newNode;
}
int myidx = autoidx++;
AstNode *outreg = nullptr;
for (int i = 0; i < num_steps; i++)
{
AstNode *reg = new AstNode(AST_WIRE, new AstNode(AST_RANGE,
mkconst_int(width_hint-1, true), mkconst_int(0, true)));
reg->str = stringf("$past$%s:%d$%d$%d", filename.c_str(), location.first_line, myidx, i);
reg->is_reg = true;
current_ast_mod->children.push_back(reg);
while (reg->simplify(true, false, false, 1, -1, false, false)) { }
AstNode *regid = new AstNode(AST_IDENTIFIER);
regid->str = reg->str;
regid->id2ast = reg;
regid->was_checked = true;
AstNode *rhs = nullptr;
if (outreg == nullptr) {
rhs = children.at(0)->clone();
} else {
rhs = new AstNode(AST_IDENTIFIER);
rhs->str = outreg->str;
rhs->id2ast = outreg;
}
block->children.push_back(new AstNode(AST_ASSIGN_LE, regid, rhs));
outreg = reg;
}
newNode = new AstNode(AST_IDENTIFIER);
newNode->str = outreg->str;
newNode->id2ast = outreg;
goto apply_newNode;
}
if (str == "\\$stable" || str == "\\$rose" || str == "\\$fell" || str == "\\$changed")
{
if (GetSize(children) != 1)
log_file_error(filename, location.first_line, "System function %s got %d arguments, expected 1.\n",
RTLIL::unescape_id(str).c_str(), int(children.size()));
if (!current_always_clocked)
log_file_error(filename, location.first_line, "System function %s is only allowed in clocked blocks.\n",
RTLIL::unescape_id(str).c_str());
AstNode *present = children.at(0)->clone();
AstNode *past = clone();
past->str = "\\$past";
if (str == "\\$stable")
newNode = new AstNode(AST_EQ, past, present);
else if (str == "\\$changed")
newNode = new AstNode(AST_NE, past, present);
else if (str == "\\$rose")
newNode = new AstNode(AST_LOGIC_AND,
new AstNode(AST_LOGIC_NOT, new AstNode(AST_BIT_AND, past, mkconst_int(1,false))),
new AstNode(AST_BIT_AND, present, mkconst_int(1,false)));
else if (str == "\\$fell")
newNode = new AstNode(AST_LOGIC_AND,
new AstNode(AST_BIT_AND, past, mkconst_int(1,false)),
new AstNode(AST_LOGIC_NOT, new AstNode(AST_BIT_AND, present, mkconst_int(1,false))));
else
log_abort();
goto apply_newNode;
}
// $anyconst and $anyseq are mapped in AstNode::genRTLIL()
if (str == "\\$anyconst" || str == "\\$anyseq" || str == "\\$allconst" || str == "\\$allseq") {
recursion_counter--;
return false;
}
if (str == "\\$clog2")
{
if (children.size() != 1)
log_file_error(filename, location.first_line, "System function %s got %d arguments, expected 1.\n",
RTLIL::unescape_id(str).c_str(), int(children.size()));
AstNode *buf = children[0]->clone();
while (buf->simplify(true, false, false, stage, width_hint, sign_hint, false)) { }
if (buf->type != AST_CONSTANT)
log_file_error(filename, location.first_line, "Failed to evaluate system function `%s' with non-constant value.\n", str.c_str());
RTLIL::Const arg_value = buf->bitsAsConst();
if (arg_value.as_bool())
arg_value = const_sub(arg_value, 1, false, false, GetSize(arg_value));
delete buf;
uint32_t result = 0;
for (size_t i = 0; i < arg_value.bits.size(); i++)
if (arg_value.bits.at(i) == RTLIL::State::S1)
result = i + 1;
newNode = mkconst_int(result, true);
goto apply_newNode;
}
if (str == "\\$size" || str == "\\$bits" || str == "\\$high" || str == "\\$low" || str == "\\$left" || str == "\\$right")
{
int dim = 1;
if (str == "\\$bits") {
if (children.size() != 1)
log_file_error(filename, location.first_line, "System function %s got %d arguments, expected 1.\n",
RTLIL::unescape_id(str).c_str(), int(children.size()));
} else {
if (children.size() != 1 && children.size() != 2)
log_file_error(filename, location.first_line, "System function %s got %d arguments, expected 1 or 2.\n",
RTLIL::unescape_id(str).c_str(), int(children.size()));
if (children.size() == 2) {
AstNode *buf = children[1]->clone();
// Evaluate constant expression
while (buf->simplify(true, false, false, stage, width_hint, sign_hint, false)) { }
dim = buf->asInt(false);
delete buf;
}
}
AstNode *buf = children[0]->clone();
int mem_depth = 1;
int result, high = 0, low = 0, left = 0, right = 0, width = 1; // defaults for a simple wire
AstNode *id_ast = NULL;
// Is this needed?
//while (buf->simplify(true, false, false, stage, width_hint, sign_hint, false)) { }
buf->detectSignWidth(width_hint, sign_hint);
if (buf->type == AST_IDENTIFIER) {
id_ast = buf->id2ast;
if (id_ast == NULL && current_scope.count(buf->str))
id_ast = current_scope.at(buf->str);
if (!id_ast)
log_file_error(filename, location.first_line, "Failed to resolve identifier %s for width detection!\n", buf->str.c_str());
// a slice of our identifier means we advance to the next dimension, e.g. $size(a[3])
if (buf->children.size() > 0) {
// something is hanging below this identifier
if (buf->children[0]->type == AST_RANGE && buf->integer == 0)
// if integer == 0, this node was originally created as AST_RANGE so it's dimension is 1
dim++;
// more than one range, e.g. $size(a[3][2])
else // created an AST_MULTIRANGE, converted to AST_RANGE, but original dimension saved in 'integer' field
dim += buf->integer; // increment by multirange size
}
// We have 4 cases:
// wire x; ==> AST_WIRE, no AST_RANGE children
// wire [1:0]x; ==> AST_WIRE, AST_RANGE children
// wire [1:0]x[1:0]; ==> AST_MEMORY, two AST_RANGE children (1st for packed, 2nd for unpacked)
// wire [1:0]x[1:0][1:0]; ==> AST_MEMORY, one AST_RANGE child (0) for packed, then AST_MULTIRANGE child (1) for unpacked
// (updated: actually by the time we are here, AST_MULTIRANGE is converted into one big AST_RANGE)
// case 0 handled by default
if ((id_ast->type == AST_WIRE || id_ast->type == AST_MEMORY) && id_ast->children.size() > 0) {
// handle packed array left/right for case 1, and cases 2/3 when requesting the last dimension (packed side)
AstNode *wire_range = id_ast->children[0];
left = wire_range->children[0]->integer;
right = wire_range->children[1]->integer;
high = max(left, right);
low = min(left, right);
}
if (id_ast->type == AST_MEMORY) {
// We got here only if the argument is a memory
// Otherwise $size() and $bits() return the expression width
AstNode *mem_range = id_ast->children[1];
if (str == "\\$bits") {
if (mem_range->type == AST_RANGE) {
if (!mem_range->range_valid)
log_file_error(filename, location.first_line, "Failed to detect width of memory access `%s'!\n", buf->str.c_str());
mem_depth = mem_range->range_left - mem_range->range_right + 1;
} else
log_file_error(filename, location.first_line, "Unknown memory depth AST type in `%s'!\n", buf->str.c_str());
} else {
// $size(), $left(), $right(), $high(), $low()
int dims = 1;
if (mem_range->type == AST_RANGE) {
if (id_ast->multirange_dimensions.empty()) {
if (!mem_range->range_valid)
log_file_error(filename, location.first_line, "Failed to detect width of memory access `%s'!\n", buf->str.c_str());
if (dim == 1) {
left = mem_range->range_right;
right = mem_range->range_left;
high = max(left, right);
low = min(left, right);
}
} else {
dims = GetSize(id_ast->multirange_dimensions)/2;
if (dim <= dims) {
width_hint = id_ast->multirange_dimensions[2*dim-1];
high = id_ast->multirange_dimensions[2*dim-2] + id_ast->multirange_dimensions[2*dim-1] - 1;
low = id_ast->multirange_dimensions[2*dim-2];
if (id_ast->multirange_swapped[dim-1]) {
left = low;
right = high;
} else {
right = low;
left = high;
}
} else if ((dim > dims+1) || (dim < 0))
log_file_error(filename, location.first_line, "Dimension %d out of range in `%s', as it only has dimensions 1..%d!\n", dim, buf->str.c_str(), dims+1);
}
} else {
log_file_error(filename, location.first_line, "Unknown memory depth AST type in `%s'!\n", buf->str.c_str());
}
}
}
width = high - low + 1;
} else {
width = width_hint;
}
delete buf;
if (str == "\\$high")
result = high;
else if (str == "\\$low")
result = low;
else if (str == "\\$left")
result = left;
else if (str == "\\$right")
result = right;
else if (str == "\\$size")
result = width;
else {
result = width * mem_depth;
}
newNode = mkconst_int(result, false);
goto apply_newNode;
}
if (str == "\\$ln" || str == "\\$log10" || str == "\\$exp" || str == "\\$sqrt" || str == "\\$pow" ||
str == "\\$floor" || str == "\\$ceil" || str == "\\$sin" || str == "\\$cos" || str == "\\$tan" ||
str == "\\$asin" || str == "\\$acos" || str == "\\$atan" || str == "\\$atan2" || str == "\\$hypot" ||
str == "\\$sinh" || str == "\\$cosh" || str == "\\$tanh" || str == "\\$asinh" || str == "\\$acosh" || str == "\\$atanh" ||
str == "\\$rtoi" || str == "\\$itor")
{
bool func_with_two_arguments = str == "\\$pow" || str == "\\$atan2" || str == "\\$hypot";
double x = 0, y = 0;
if (func_with_two_arguments) {
if (children.size() != 2)
log_file_error(filename, location.first_line, "System function %s got %d arguments, expected 2.\n",
RTLIL::unescape_id(str).c_str(), int(children.size()));
} else {
if (children.size() != 1)
log_file_error(filename, location.first_line, "System function %s got %d arguments, expected 1.\n",
RTLIL::unescape_id(str).c_str(), int(children.size()));
}
if (children.size() >= 1) {
while (children[0]->simplify(true, false, false, stage, width_hint, sign_hint, false)) { }
if (!children[0]->isConst())
log_file_error(filename, location.first_line, "Failed to evaluate system function `%s' with non-constant argument.\n",
RTLIL::unescape_id(str).c_str());
int child_width_hint = width_hint;
bool child_sign_hint = sign_hint;
children[0]->detectSignWidth(child_width_hint, child_sign_hint);
x = children[0]->asReal(child_sign_hint);
}
if (children.size() >= 2) {
while (children[1]->simplify(true, false, false, stage, width_hint, sign_hint, false)) { }
if (!children[1]->isConst())
log_file_error(filename, location.first_line, "Failed to evaluate system function `%s' with non-constant argument.\n",
RTLIL::unescape_id(str).c_str());
int child_width_hint = width_hint;
bool child_sign_hint = sign_hint;
children[1]->detectSignWidth(child_width_hint, child_sign_hint);
y = children[1]->asReal(child_sign_hint);
}
if (str == "\\$rtoi") {
newNode = AstNode::mkconst_int(x, true);
} else {
newNode = new AstNode(AST_REALVALUE);
if (str == "\\$ln") newNode->realvalue = ::log(x);
else if (str == "\\$log10") newNode->realvalue = ::log10(x);
else if (str == "\\$exp") newNode->realvalue = ::exp(x);
else if (str == "\\$sqrt") newNode->realvalue = ::sqrt(x);
else if (str == "\\$pow") newNode->realvalue = ::pow(x, y);
else if (str == "\\$floor") newNode->realvalue = ::floor(x);
else if (str == "\\$ceil") newNode->realvalue = ::ceil(x);
else if (str == "\\$sin") newNode->realvalue = ::sin(x);
else if (str == "\\$cos") newNode->realvalue = ::cos(x);
else if (str == "\\$tan") newNode->realvalue = ::tan(x);
else if (str == "\\$asin") newNode->realvalue = ::asin(x);
else if (str == "\\$acos") newNode->realvalue = ::acos(x);
else if (str == "\\$atan") newNode->realvalue = ::atan(x);
else if (str == "\\$atan2") newNode->realvalue = ::atan2(x, y);
else if (str == "\\$hypot") newNode->realvalue = ::hypot(x, y);
else if (str == "\\$sinh") newNode->realvalue = ::sinh(x);
else if (str == "\\$cosh") newNode->realvalue = ::cosh(x);
else if (str == "\\$tanh") newNode->realvalue = ::tanh(x);
else if (str == "\\$asinh") newNode->realvalue = ::asinh(x);
else if (str == "\\$acosh") newNode->realvalue = ::acosh(x);
else if (str == "\\$atanh") newNode->realvalue = ::atanh(x);
else if (str == "\\$itor") newNode->realvalue = x;
else log_abort();
}
goto apply_newNode;
}
if (str == "\\$sformatf") {
AstNode *node_string = children[0];
while (node_string->simplify(true, false, false, stage, width_hint, sign_hint, false)) { }
if (node_string->type != AST_CONSTANT)
log_file_error(filename, location.first_line, "Failed to evaluate system function `%s' with non-constant 1st argument.\n", str.c_str());
std::string sformat = node_string->bitsAsConst().decode_string();
std::string sout = process_format_str(sformat, 1, stage, width_hint, sign_hint);
newNode = AstNode::mkconst_str(sout);
goto apply_newNode;
}
if (str == "\\$countbits") {
if (children.size() < 2)
log_file_error(filename, location.first_line, "System function %s got %d arguments, expected at least 2.\n",
RTLIL::unescape_id(str).c_str(), int(children.size()));
std::vector<RTLIL::State> control_bits;
// Determine which bits to count
for (size_t i = 1; i < children.size(); i++) {
AstNode *node = children[i];
while (node->simplify(true, false, false, stage, -1, false, false)) { }
if (node->type != AST_CONSTANT)
log_file_error(filename, location.first_line, "Failed to evaluate system function `%s' with non-constant control bit argument.\n", str.c_str());
if (node->bits.size() != 1)
log_file_error(filename, location.first_line, "Failed to evaluate system function `%s' with control bit width != 1.\n", str.c_str());
control_bits.push_back(node->bits[0]);
}
// Detect width of exp (first argument of $countbits)
int exp_width = -1;
bool exp_sign = false;
AstNode *exp = children[0];
exp->detectSignWidth(exp_width, exp_sign, NULL);
newNode = mkconst_int(0, false);
for (int i = 0; i < exp_width; i++) {
// Generate nodes for: exp << i >> ($size(exp) - 1)
// ^^ ^^
AstNode *lsh_node = new AstNode(AST_SHIFT_LEFT, exp->clone(), mkconst_int(i, false));
AstNode *rsh_node = new AstNode(AST_SHIFT_RIGHT, lsh_node, mkconst_int(exp_width - 1, false));
AstNode *or_node = nullptr;
for (RTLIL::State control_bit : control_bits) {
// Generate node for: (exp << i >> ($size(exp) - 1)) === control_bit
// ^^^
AstNode *eq_node = new AstNode(AST_EQX, rsh_node->clone(), mkconst_bits({control_bit}, false));
// Or the result for each checked bit value
if (or_node)
or_node = new AstNode(AST_LOGIC_OR, or_node, eq_node);
else
or_node = eq_node;
}
// We should have at least one element in control_bits,
// because we checked for the number of arguments above
log_assert(or_node != nullptr);
delete rsh_node;
// Generate node for adding with result of previous bit
newNode = new AstNode(AST_ADD, newNode, or_node);
}
goto apply_newNode;
}
if (str == "\\$countones" || str == "\\$isunknown" || str == "\\$onehot" || str == "\\$onehot0") {
if (children.size() != 1)
log_file_error(filename, location.first_line, "System function %s got %d arguments, expected 1.\n",
RTLIL::unescape_id(str).c_str(), int(children.size()));
AstNode *countbits = clone();
countbits->str = "\\$countbits";
if (str == "\\$countones") {
countbits->children.push_back(mkconst_bits({RTLIL::State::S1}, false));
newNode = countbits;
} else if (str == "\\$isunknown") {
countbits->children.push_back(mkconst_bits({RTLIL::Sx}, false));
countbits->children.push_back(mkconst_bits({RTLIL::Sz}, false));
newNode = new AstNode(AST_GT, countbits, mkconst_int(0, false));
} else if (str == "\\$onehot") {
countbits->children.push_back(mkconst_bits({RTLIL::State::S1}, false));
newNode = new AstNode(AST_EQ, countbits, mkconst_int(1, false));
} else if (str == "\\$onehot0") {
countbits->children.push_back(mkconst_bits({RTLIL::State::S1}, false));
newNode = new AstNode(AST_LE, countbits, mkconst_int(1, false));
} else {
log_abort();
}
goto apply_newNode;
}
if (current_scope.count(str) != 0 && current_scope[str]->type == AST_DPI_FUNCTION)
{
AstNode *dpi_decl = current_scope[str];
std::string rtype, fname;
std::vector<std::string> argtypes;
std::vector<AstNode*> args;
rtype = RTLIL::unescape_id(dpi_decl->children.at(0)->str);
fname = RTLIL::unescape_id(dpi_decl->children.at(1)->str);
for (int i = 2; i < GetSize(dpi_decl->children); i++)
{
if (i-2 >= GetSize(children))
log_file_error(filename, location.first_line, "Insufficient number of arguments in DPI function call.\n");
argtypes.push_back(RTLIL::unescape_id(dpi_decl->children.at(i)->str));
args.push_back(children.at(i-2)->clone());
while (args.back()->simplify(true, false, false, stage, -1, false, true)) { }
if (args.back()->type != AST_CONSTANT && args.back()->type != AST_REALVALUE)
log_file_error(filename, location.first_line, "Failed to evaluate DPI function with non-constant argument.\n");
}
newNode = dpi_call(rtype, fname, argtypes, args);
for (auto arg : args)
delete arg;
goto apply_newNode;
}
if (current_scope.count(str) == 0 || current_scope[str]->type != AST_FUNCTION)
log_file_error(filename, location.first_line, "Can't resolve function name `%s'.\n", str.c_str());
}
if (type == AST_TCALL)
{
if (str == "$finish" || str == "$stop")
{
if (!current_always || current_always->type != AST_INITIAL)
log_file_error(filename, location.first_line, "System task `%s' outside initial block is unsupported.\n", str.c_str());
log_file_error(filename, location.first_line, "System task `%s' executed.\n", str.c_str());
}
if (str == "\\$readmemh" || str == "\\$readmemb")
{
if (GetSize(children) < 2 || GetSize(children) > 4)
log_file_error(filename, location.first_line, "System function %s got %d arguments, expected 2-4.\n",
RTLIL::unescape_id(str).c_str(), int(children.size()));
AstNode *node_filename = children[0]->clone();
while (node_filename->simplify(true, false, false, stage, width_hint, sign_hint, false)) { }
if (node_filename->type != AST_CONSTANT)
log_file_error(filename, location.first_line, "Failed to evaluate system function `%s' with non-constant 1st argument.\n", str.c_str());
AstNode *node_memory = children[1]->clone();
while (node_memory->simplify(true, false, false, stage, width_hint, sign_hint, false)) { }
if (node_memory->type != AST_IDENTIFIER || node_memory->id2ast == nullptr || node_memory->id2ast->type != AST_MEMORY)
log_file_error(filename, location.first_line, "Failed to evaluate system function `%s' with non-memory 2nd argument.\n", str.c_str());
int start_addr = -1, finish_addr = -1;
if (GetSize(children) > 2) {
AstNode *node_addr = children[2]->clone();
while (node_addr->simplify(true, false, false, stage, width_hint, sign_hint, false)) { }
if (node_addr->type != AST_CONSTANT)
log_file_error(filename, location.first_line, "Failed to evaluate system function `%s' with non-constant 3rd argument.\n", str.c_str());
start_addr = int(node_addr->asInt(false));
}
if (GetSize(children) > 3) {
AstNode *node_addr = children[3]->clone();
while (node_addr->simplify(true, false, false, stage, width_hint, sign_hint, false)) { }
if (node_addr->type != AST_CONSTANT)
log_file_error(filename, location.first_line, "Failed to evaluate system function `%s' with non-constant 4th argument.\n", str.c_str());
finish_addr = int(node_addr->asInt(false));
}
bool unconditional_init = false;
if (current_always->type == AST_INITIAL) {
pool<AstNode*> queue;
log_assert(current_always->children[0]->type == AST_BLOCK);
queue.insert(current_always->children[0]);
while (!unconditional_init && !queue.empty()) {
pool<AstNode*> next_queue;
for (auto n : queue)
for (auto c : n->children) {
if (c == this)
unconditional_init = true;
next_queue.insert(c);
}
next_queue.swap(queue);
}
}
newNode = readmem(str == "\\$readmemh", node_filename->bitsAsConst().decode_string(), node_memory->id2ast, start_addr, finish_addr, unconditional_init);
delete node_filename;
delete node_memory;
goto apply_newNode;
}
if (current_scope.count(str) == 0 || current_scope[str]->type != AST_TASK)
log_file_error(filename, location.first_line, "Can't resolve task name `%s'.\n", str.c_str());
}
std::stringstream sstr;
sstr << str << "$func$" << filename << ":" << location.first_line << "$" << (autoidx++) << '.';
std::string prefix = sstr.str();
AstNode *decl = current_scope[str];
if (unevaluated_tern_branch && decl->is_recursive_function())
goto replace_fcall_later;
decl = decl->clone();
decl->replace_result_wire_name_in_function(str, "$result"); // enables recursion
decl->expand_genblock(prefix);
if (decl->type == AST_FUNCTION && !decl->attributes.count(ID::via_celltype))
{
bool require_const_eval = decl->has_const_only_constructs();
bool all_args_const = true;
for (auto child : children) {
while (child->simplify(true, false, false, 1, -1, false, true)) { }
if (child->type != AST_CONSTANT && child->type != AST_REALVALUE)
all_args_const = false;
}
if (all_args_const) {
AstNode *func_workspace = decl->clone();
func_workspace->str = prefix_id(prefix, "$result");
newNode = func_workspace->eval_const_function(this, in_param || require_const_eval);
delete func_workspace;
if (newNode) {
delete decl;
goto apply_newNode;
}
}
if (in_param)
log_file_error(filename, location.first_line, "Non-constant function call in constant expression.\n");
if (require_const_eval)
log_file_error(filename, location.first_line, "Function %s can only be called with constant arguments.\n", str.c_str());
}
size_t arg_count = 0;
dict<std::string, AstNode*> wire_cache;
vector<AstNode*> new_stmts;
vector<AstNode*> output_assignments;
if (current_block == NULL)
{
log_assert(type == AST_FCALL);
AstNode *wire = NULL;
std::string res_name = prefix_id(prefix, "$result");
for (auto child : decl->children)
if (child->type == AST_WIRE && child->str == res_name)
wire = child->clone();
log_assert(wire != NULL);
wire->port_id = 0;
wire->is_input = false;
wire->is_output = false;
current_scope[wire->str] = wire;
current_ast_mod->children.push_back(wire);
while (wire->simplify(true, false, false, 1, -1, false, false)) { }
AstNode *lvalue = new AstNode(AST_IDENTIFIER);
lvalue->str = wire->str;
AstNode *always = new AstNode(AST_ALWAYS, new AstNode(AST_BLOCK,
new AstNode(AST_ASSIGN_EQ, lvalue, clone())));
always->children[0]->children[0]->was_checked = true;
current_ast_mod->children.push_back(always);
goto replace_fcall_with_id;
}
if (decl->attributes.count(ID::via_celltype))
{
std::string celltype = decl->attributes.at(ID::via_celltype)->asAttrConst().decode_string();
std::string outport = str;
if (celltype.find(' ') != std::string::npos) {
int pos = celltype.find(' ');
outport = RTLIL::escape_id(celltype.substr(pos+1));
celltype = RTLIL::escape_id(celltype.substr(0, pos));
} else
celltype = RTLIL::escape_id(celltype);
AstNode *cell = new AstNode(AST_CELL, new AstNode(AST_CELLTYPE));
cell->str = prefix.substr(0, GetSize(prefix)-1);
cell->children[0]->str = celltype;
for (auto attr : decl->attributes)
if (attr.first.str().rfind("\\via_celltype_defparam_", 0) == 0)
{
AstNode *cell_arg = new AstNode(AST_PARASET, attr.second->clone());
cell_arg->str = RTLIL::escape_id(attr.first.substr(strlen("\\via_celltype_defparam_")));
cell->children.push_back(cell_arg);
}
for (auto child : decl->children)
if (child->type == AST_WIRE && (child->is_input || child->is_output || (type == AST_FCALL && child->str == str)))
{
AstNode *wire = child->clone();
wire->port_id = 0;
wire->is_input = false;
wire->is_output = false;
current_ast_mod->children.push_back(wire);
while (wire->simplify(true, false, false, 1, -1, false, false)) { }
AstNode *wire_id = new AstNode(AST_IDENTIFIER);
wire_id->str = wire->str;
if ((child->is_input || child->is_output) && arg_count < children.size())
{
AstNode *arg = children[arg_count++]->clone();
AstNode *assign = child->is_input ?
new AstNode(AST_ASSIGN_EQ, wire_id->clone(), arg) :
new AstNode(AST_ASSIGN_EQ, arg, wire_id->clone());
assign->children[0]->was_checked = true;
for (auto it = current_block->children.begin(); it != current_block->children.end(); it++) {
if (*it != current_block_child)
continue;
current_block->children.insert(it, assign);
break;
}
}
AstNode *cell_arg = new AstNode(AST_ARGUMENT, wire_id);
cell_arg->str = child->str == str ? outport : child->str;
cell->children.push_back(cell_arg);
}
current_ast_mod->children.push_back(cell);
goto replace_fcall_with_id;
}
for (auto child : decl->children)
if (child->type == AST_WIRE || child->type == AST_MEMORY || child->type == AST_PARAMETER || child->type == AST_LOCALPARAM || child->type == AST_ENUM_ITEM)
{
AstNode *wire = nullptr;
if (wire_cache.count(child->str))
{
wire = wire_cache.at(child->str);
bool contains_value = wire->type == AST_LOCALPARAM;
if (wire->children.size() == contains_value) {
for (auto c : child->children)
wire->children.push_back(c->clone());
} else if (!child->children.empty()) {
while (child->simplify(true, false, false, stage, -1, false, false)) { }
if (GetSize(child->children) == GetSize(wire->children) - contains_value) {
for (int i = 0; i < GetSize(child->children); i++)
if (*child->children.at(i) != *wire->children.at(i + contains_value))
goto tcall_incompatible_wires;
} else {
tcall_incompatible_wires:
log_file_error(filename, location.first_line, "Incompatible re-declaration of wire %s.\n", child->str.c_str());
}
}
}
else
{
wire = child->clone();
wire->port_id = 0;
wire->is_input = false;
wire->is_output = false;
wire->is_reg = true;
wire->attributes[ID::nosync] = AstNode::mkconst_int(1, false);
if (child->type == AST_ENUM_ITEM)
wire->attributes[ID::enum_base_type] = child->attributes[ID::enum_base_type];
wire_cache[child->str] = wire;
current_scope[wire->str] = wire;
current_ast_mod->children.push_back(wire);
}
while (wire->simplify(true, false, false, 1, -1, false, false)) { }
if ((child->is_input || child->is_output) && arg_count < children.size())
{
AstNode *arg = children[arg_count++]->clone();
// convert purely constant arguments into localparams
if (child->is_input && child->type == AST_WIRE && arg->type == AST_CONSTANT && node_contains_assignment_to(decl, child)) {
wire->type = AST_LOCALPARAM;
if (wire->attributes.count(ID::nosync))
delete wire->attributes.at(ID::nosync);
wire->attributes.erase(ID::nosync);
wire->children.insert(wire->children.begin(), arg->clone());
// args without a range implicitly have width 1
if (wire->children.back()->type != AST_RANGE) {
// check if this wire is redeclared with an explicit size
bool uses_explicit_size = false;
for (const AstNode *other_child : decl->children)
if (other_child->type == AST_WIRE && child->str == other_child->str
&& !other_child->children.empty()
&& other_child->children.back()->type == AST_RANGE) {
uses_explicit_size = true;
break;
}
if (!uses_explicit_size) {
AstNode* range = new AstNode();
range->type = AST_RANGE;
wire->children.push_back(range);
range->children.push_back(mkconst_int(0, true));
range->children.push_back(mkconst_int(0, true));
}
}
// updates the sizing
while (wire->simplify(true, false, false, 1, -1, false, false)) { }
delete arg;
continue;
}
AstNode *wire_id = new AstNode(AST_IDENTIFIER);
wire_id->str = wire->str;
AstNode *assign = child->is_input ?
new AstNode(AST_ASSIGN_EQ, wire_id, arg) :
new AstNode(AST_ASSIGN_EQ, arg, wire_id);
assign->children[0]->was_checked = true;
if (child->is_input)
new_stmts.push_back(assign);
else
output_assignments.push_back(assign);
}
}
for (auto child : decl->children)
if (child->type != AST_WIRE && child->type != AST_MEMORY && child->type != AST_PARAMETER && child->type != AST_LOCALPARAM)
new_stmts.push_back(child->clone());
new_stmts.insert(new_stmts.end(), output_assignments.begin(), output_assignments.end());
for (auto it = current_block->children.begin(); ; it++) {
log_assert(it != current_block->children.end());
if (*it == current_block_child) {
current_block->children.insert(it, new_stmts.begin(), new_stmts.end());
break;
}
}
replace_fcall_with_id:
delete decl;
if (type == AST_FCALL) {
delete_children();
type = AST_IDENTIFIER;
str = prefix_id(prefix, "$result");
}
if (type == AST_TCALL)
str = "";
did_something = true;
}
replace_fcall_later:;
// perform const folding when activated
if (const_fold)
{
bool string_op;
std::vector<RTLIL::State> tmp_bits;
RTLIL::Const (*const_func)(const RTLIL::Const&, const RTLIL::Const&, bool, bool, int);
RTLIL::Const dummy_arg;
switch (type)
{
case AST_IDENTIFIER:
if (current_scope.count(str) > 0 && (current_scope[str]->type == AST_PARAMETER || current_scope[str]->type == AST_LOCALPARAM || current_scope[str]->type == AST_ENUM_ITEM)) {
if (current_scope[str]->children[0]->type == AST_CONSTANT) {
if (children.size() != 0 && children[0]->type == AST_RANGE && children[0]->range_valid) {
std::vector<RTLIL::State> data;
bool param_upto = current_scope[str]->range_valid && current_scope[str]->range_swapped;
int param_offset = current_scope[str]->range_valid ? current_scope[str]->range_right : 0;
int param_width = current_scope[str]->range_valid ? current_scope[str]->range_left - current_scope[str]->range_right + 1 :
GetSize(current_scope[str]->children[0]->bits);
int tmp_range_left = children[0]->range_left, tmp_range_right = children[0]->range_right;
if (param_upto) {
tmp_range_left = (param_width + 2*param_offset) - children[0]->range_right - 1;
tmp_range_right = (param_width + 2*param_offset) - children[0]->range_left - 1;
}
for (int i = tmp_range_right; i <= tmp_range_left; i++) {
int index = i - param_offset;
if (0 <= index && index < param_width)
data.push_back(current_scope[str]->children[0]->bits[index]);
else
data.push_back(RTLIL::State::Sx);
}
newNode = mkconst_bits(data, false);
} else
if (children.size() == 0)
newNode = current_scope[str]->children[0]->clone();
} else
if (current_scope[str]->children[0]->isConst())
newNode = current_scope[str]->children[0]->clone();
}
else if (at_zero && current_scope.count(str) > 0) {
AstNode *node = current_scope[str];
if (node->type == AST_WIRE || node->type == AST_AUTOWIRE || node->type == AST_MEMORY)
newNode = mkconst_int(0, sign_hint, width_hint);
}
break;
case AST_MEMRD:
if (at_zero) {
newNode = mkconst_int(0, sign_hint, width_hint);
}
break;
case AST_BIT_NOT:
if (children[0]->type == AST_CONSTANT) {
RTLIL::Const y = RTLIL::const_not(children[0]->bitsAsConst(width_hint, sign_hint), dummy_arg, sign_hint, false, width_hint);
newNode = mkconst_bits(y.bits, sign_hint);
}
break;
case AST_TO_SIGNED:
case AST_TO_UNSIGNED:
if (children[0]->type == AST_CONSTANT) {
RTLIL::Const y = children[0]->bitsAsConst(width_hint, sign_hint);
newNode = mkconst_bits(y.bits, type == AST_TO_SIGNED);
}
break;
if (0) { case AST_BIT_AND: const_func = RTLIL::const_and; }
if (0) { case AST_BIT_OR: const_func = RTLIL::const_or; }
if (0) { case AST_BIT_XOR: const_func = RTLIL::const_xor; }
if (0) { case AST_BIT_XNOR: const_func = RTLIL::const_xnor; }
if (children[0]->type == AST_CONSTANT && children[1]->type == AST_CONSTANT) {
RTLIL::Const y = const_func(children[0]->bitsAsConst(width_hint, sign_hint),
children[1]->bitsAsConst(width_hint, sign_hint), sign_hint, sign_hint, width_hint);
newNode = mkconst_bits(y.bits, sign_hint);
}
break;
if (0) { case AST_REDUCE_AND: const_func = RTLIL::const_reduce_and; }
if (0) { case AST_REDUCE_OR: const_func = RTLIL::const_reduce_or; }
if (0) { case AST_REDUCE_XOR: const_func = RTLIL::const_reduce_xor; }
if (0) { case AST_REDUCE_XNOR: const_func = RTLIL::const_reduce_xnor; }
if (0) { case AST_REDUCE_BOOL: const_func = RTLIL::const_reduce_bool; }
if (children[0]->type == AST_CONSTANT) {
RTLIL::Const y = const_func(RTLIL::Const(children[0]->bits), dummy_arg, false, false, -1);
newNode = mkconst_bits(y.bits, false);
}
break;
case AST_LOGIC_NOT:
if (children[0]->type == AST_CONSTANT) {
RTLIL::Const y = RTLIL::const_logic_not(RTLIL::Const(children[0]->bits), dummy_arg, children[0]->is_signed, false, -1);
newNode = mkconst_bits(y.bits, false);
} else
if (children[0]->isConst()) {
newNode = mkconst_int(children[0]->asReal(sign_hint) == 0, false, 1);
}
break;
if (0) { case AST_LOGIC_AND: const_func = RTLIL::const_logic_and; }
if (0) { case AST_LOGIC_OR: const_func = RTLIL::const_logic_or; }
if (children[0]->type == AST_CONSTANT && children[1]->type == AST_CONSTANT) {
RTLIL::Const y = const_func(RTLIL::Const(children[0]->bits), RTLIL::Const(children[1]->bits),
children[0]->is_signed, children[1]->is_signed, -1);
newNode = mkconst_bits(y.bits, false);
} else
if (children[0]->isConst() && children[1]->isConst()) {
if (type == AST_LOGIC_AND)
newNode = mkconst_int((children[0]->asReal(sign_hint) != 0) && (children[1]->asReal(sign_hint) != 0), false, 1);
else
newNode = mkconst_int((children[0]->asReal(sign_hint) != 0) || (children[1]->asReal(sign_hint) != 0), false, 1);
}
break;
if (0) { case AST_SHIFT_LEFT: const_func = RTLIL::const_shl; }
if (0) { case AST_SHIFT_RIGHT: const_func = RTLIL::const_shr; }
if (0) { case AST_SHIFT_SLEFT: const_func = RTLIL::const_sshl; }
if (0) { case AST_SHIFT_SRIGHT: const_func = RTLIL::const_sshr; }
if (0) { case AST_POW: const_func = RTLIL::const_pow; }
if (children[0]->type == AST_CONSTANT && children[1]->type == AST_CONSTANT) {
RTLIL::Const y = const_func(children[0]->bitsAsConst(width_hint, sign_hint),
RTLIL::Const(children[1]->bits), sign_hint, type == AST_POW ? children[1]->is_signed : false, width_hint);
newNode = mkconst_bits(y.bits, sign_hint);
} else
if (type == AST_POW && children[0]->isConst() && children[1]->isConst()) {
newNode = new AstNode(AST_REALVALUE);
newNode->realvalue = pow(children[0]->asReal(sign_hint), children[1]->asReal(sign_hint));
}
break;
if (0) { case AST_LT: const_func = RTLIL::const_lt; }
if (0) { case AST_LE: const_func = RTLIL::const_le; }
if (0) { case AST_EQ: const_func = RTLIL::const_eq; }
if (0) { case AST_NE: const_func = RTLIL::const_ne; }
if (0) { case AST_EQX: const_func = RTLIL::const_eqx; }
if (0) { case AST_NEX: const_func = RTLIL::const_nex; }
if (0) { case AST_GE: const_func = RTLIL::const_ge; }
if (0) { case AST_GT: const_func = RTLIL::const_gt; }
if (children[0]->type == AST_CONSTANT && children[1]->type == AST_CONSTANT) {
int cmp_width = max(children[0]->bits.size(), children[1]->bits.size());
bool cmp_signed = children[0]->is_signed && children[1]->is_signed;
RTLIL::Const y = const_func(children[0]->bitsAsConst(cmp_width, cmp_signed),
children[1]->bitsAsConst(cmp_width, cmp_signed), cmp_signed, cmp_signed, 1);
newNode = mkconst_bits(y.bits, false);
} else
if (children[0]->isConst() && children[1]->isConst()) {
bool cmp_signed = (children[0]->type == AST_REALVALUE || children[0]->is_signed) && (children[1]->type == AST_REALVALUE || children[1]->is_signed);
switch (type) {
case AST_LT: newNode = mkconst_int(children[0]->asReal(cmp_signed) < children[1]->asReal(cmp_signed), false, 1); break;
case AST_LE: newNode = mkconst_int(children[0]->asReal(cmp_signed) <= children[1]->asReal(cmp_signed), false, 1); break;
case AST_EQ: newNode = mkconst_int(children[0]->asReal(cmp_signed) == children[1]->asReal(cmp_signed), false, 1); break;
case AST_NE: newNode = mkconst_int(children[0]->asReal(cmp_signed) != children[1]->asReal(cmp_signed), false, 1); break;
case AST_EQX: newNode = mkconst_int(children[0]->asReal(cmp_signed) == children[1]->asReal(cmp_signed), false, 1); break;
case AST_NEX: newNode = mkconst_int(children[0]->asReal(cmp_signed) != children[1]->asReal(cmp_signed), false, 1); break;
case AST_GE: newNode = mkconst_int(children[0]->asReal(cmp_signed) >= children[1]->asReal(cmp_signed), false, 1); break;
case AST_GT: newNode = mkconst_int(children[0]->asReal(cmp_signed) > children[1]->asReal(cmp_signed), false, 1); break;
default: log_abort();
}
}
break;
if (0) { case AST_ADD: const_func = RTLIL::const_add; }
if (0) { case AST_SUB: const_func = RTLIL::const_sub; }
if (0) { case AST_MUL: const_func = RTLIL::const_mul; }
if (0) { case AST_DIV: const_func = RTLIL::const_div; }
if (0) { case AST_MOD: const_func = RTLIL::const_mod; }
if (children[0]->type == AST_CONSTANT && children[1]->type == AST_CONSTANT) {
RTLIL::Const y = const_func(children[0]->bitsAsConst(width_hint, sign_hint),
children[1]->bitsAsConst(width_hint, sign_hint), sign_hint, sign_hint, width_hint);
newNode = mkconst_bits(y.bits, sign_hint);
} else
if (children[0]->isConst() && children[1]->isConst()) {
newNode = new AstNode(AST_REALVALUE);
switch (type) {
case AST_ADD: newNode->realvalue = children[0]->asReal(sign_hint) + children[1]->asReal(sign_hint); break;
case AST_SUB: newNode->realvalue = children[0]->asReal(sign_hint) - children[1]->asReal(sign_hint); break;
case AST_MUL: newNode->realvalue = children[0]->asReal(sign_hint) * children[1]->asReal(sign_hint); break;
case AST_DIV: newNode->realvalue = children[0]->asReal(sign_hint) / children[1]->asReal(sign_hint); break;
case AST_MOD: newNode->realvalue = fmod(children[0]->asReal(sign_hint), children[1]->asReal(sign_hint)); break;
default: log_abort();
}
}
break;
if (0) { case AST_SELFSZ: const_func = RTLIL::const_pos; }
if (0) { case AST_POS: const_func = RTLIL::const_pos; }
if (0) { case AST_NEG: const_func = RTLIL::const_neg; }
if (children[0]->type == AST_CONSTANT) {
RTLIL::Const y = const_func(children[0]->bitsAsConst(width_hint, sign_hint), dummy_arg, sign_hint, false, width_hint);
newNode = mkconst_bits(y.bits, sign_hint);
} else
if (children[0]->isConst()) {
newNode = new AstNode(AST_REALVALUE);
if (type == AST_NEG)
newNode->realvalue = -children[0]->asReal(sign_hint);
else
newNode->realvalue = +children[0]->asReal(sign_hint);
}
break;
case AST_TERNARY:
if (children[0]->isConst())
{
auto pair = get_tern_choice();
AstNode *choice = pair.first;
AstNode *not_choice = pair.second;
if (choice != NULL) {
if (choice->type == AST_CONSTANT) {
int other_width_hint = width_hint;
bool other_sign_hint = sign_hint, other_real = false;
not_choice->detectSignWidth(other_width_hint, other_sign_hint, &other_real);
if (other_real) {
newNode = new AstNode(AST_REALVALUE);
choice->detectSignWidth(width_hint, sign_hint);
newNode->realvalue = choice->asReal(sign_hint);
} else {
RTLIL::Const y = choice->bitsAsConst(width_hint, sign_hint);
if (choice->is_string && y.bits.size() % 8 == 0 && sign_hint == false)
newNode = mkconst_str(y.bits);
else
newNode = mkconst_bits(y.bits, sign_hint);
}
} else
if (choice->isConst()) {
newNode = choice->clone();
}
} else if (children[1]->type == AST_CONSTANT && children[2]->type == AST_CONSTANT) {
RTLIL::Const a = children[1]->bitsAsConst(width_hint, sign_hint);
RTLIL::Const b = children[2]->bitsAsConst(width_hint, sign_hint);
log_assert(a.bits.size() == b.bits.size());
for (size_t i = 0; i < a.bits.size(); i++)
if (a.bits[i] != b.bits[i])
a.bits[i] = RTLIL::State::Sx;
newNode = mkconst_bits(a.bits, sign_hint);
} else if (children[1]->isConst() && children[2]->isConst()) {
newNode = new AstNode(AST_REALVALUE);
if (children[1]->asReal(sign_hint) == children[2]->asReal(sign_hint))
newNode->realvalue = children[1]->asReal(sign_hint);
else
// IEEE Std 1800-2012 Sec. 11.4.11 states that the entry in Table 7-1 for
// the data type in question should be returned if the ?: is ambiguous. The
// value in Table 7-1 for the 'real' type is 0.0.
newNode->realvalue = 0.0;
}
}
break;
case AST_CAST_SIZE:
if (children.at(0)->type == AST_CONSTANT && children.at(1)->type == AST_CONSTANT) {
int width = children[0]->bitsAsConst().as_int();
RTLIL::Const val;
if (children[1]->is_unsized)
val = children[1]->bitsAsUnsizedConst(width);
else
val = children[1]->bitsAsConst(width);
newNode = mkconst_bits(val.bits, children[1]->is_signed);
}
break;
case AST_CONCAT:
string_op = !children.empty();
for (auto it = children.begin(); it != children.end(); it++) {
if ((*it)->type != AST_CONSTANT)
goto not_const;
if (!(*it)->is_string)
string_op = false;
tmp_bits.insert(tmp_bits.end(), (*it)->bits.begin(), (*it)->bits.end());
}
newNode = string_op ? mkconst_str(tmp_bits) : mkconst_bits(tmp_bits, false);
break;
case AST_REPLICATE:
if (children.at(0)->type != AST_CONSTANT || children.at(1)->type != AST_CONSTANT)
goto not_const;
for (int i = 0; i < children[0]->bitsAsConst().as_int(); i++)
tmp_bits.insert(tmp_bits.end(), children.at(1)->bits.begin(), children.at(1)->bits.end());
newNode = children.at(1)->is_string ? mkconst_str(tmp_bits) : mkconst_bits(tmp_bits, false);
break;
default:
not_const:
break;
}
}
// if any of the above set 'newNode' -> use 'newNode' as template to update 'this'
if (newNode) {
apply_newNode:
// fprintf(stderr, "----\n");
// dumpAst(stderr, "- ");
// newNode->dumpAst(stderr, "+ ");
log_assert(newNode != NULL);
newNode->filename = filename;
newNode->location = location;
newNode->cloneInto(this);
delete newNode;
did_something = true;
}
if (!did_something)
basic_prep = true;
recursion_counter--;
return did_something;
}
void AstNode::replace_result_wire_name_in_function(const std::string &from, const std::string &to)
{
for (AstNode *child : children)
child->replace_result_wire_name_in_function(from, to);
if (str == from && type != AST_FCALL && type != AST_TCALL)
str = to;
}
// replace a readmem[bh] TCALL ast node with a block of memory assignments
AstNode *AstNode::readmem(bool is_readmemh, std::string mem_filename, AstNode *memory, int start_addr, int finish_addr, bool unconditional_init)
{
int mem_width, mem_size, addr_bits;
memory->meminfo(mem_width, mem_size, addr_bits);
AstNode *block = new AstNode(AST_BLOCK);
AstNode *meminit = nullptr;
int next_meminit_cursor=0;
vector<State> meminit_bits;
vector<State> en_bits;
int meminit_size=0;
for (int i = 0; i < mem_width; i++)
en_bits.push_back(State::S1);
std::ifstream f;
f.open(mem_filename.c_str());
if (f.fail()) {
#ifdef _WIN32
char slash = '\\';
#else
char slash = '/';
#endif
std::string path = filename.substr(0, filename.find_last_of(slash)+1);
f.open(path + mem_filename.c_str());
yosys_input_files.insert(path + mem_filename);
} else {
yosys_input_files.insert(mem_filename);
}
if (f.fail() || GetSize(mem_filename) == 0)
log_file_error(filename, location.first_line, "Can not open file `%s` for %s.\n", mem_filename.c_str(), str.c_str());
log_assert(GetSize(memory->children) == 2 && memory->children[1]->type == AST_RANGE && memory->children[1]->range_valid);
int range_left = memory->children[1]->range_left, range_right = memory->children[1]->range_right;
int range_min = min(range_left, range_right), range_max = max(range_left, range_right);
if (start_addr < 0)
start_addr = range_min;
if (finish_addr < 0)
finish_addr = range_max + 1;
bool in_comment = false;
int increment = start_addr <= finish_addr ? +1 : -1;
int cursor = start_addr;
while (!f.eof())
{
std::string line, token;
std::getline(f, line);
for (int i = 0; i < GetSize(line); i++) {
if (in_comment && line.compare(i, 2, "*/") == 0) {
line[i] = ' ';
line[i+1] = ' ';
in_comment = false;
continue;
}
if (!in_comment && line.compare(i, 2, "/*") == 0)
in_comment = true;
if (in_comment)
line[i] = ' ';
}
while (1)
{
token = next_token(line, " \t\r\n");
if (token.empty() || token.compare(0, 2, "//") == 0)
break;
if (token[0] == '@') {
token = token.substr(1);
const char *nptr = token.c_str();
char *endptr;
cursor = strtol(nptr, &endptr, 16);
if (!*nptr || *endptr)
log_file_error(filename, location.first_line, "Can not parse address `%s` for %s.\n", nptr, str.c_str());
continue;
}
AstNode *value = VERILOG_FRONTEND::const2ast(stringf("%d'%c", mem_width, is_readmemh ? 'h' : 'b') + token);
if (unconditional_init)
{
if (meminit == nullptr || cursor != next_meminit_cursor)
{
if (meminit != nullptr) {
meminit->children[1] = AstNode::mkconst_bits(meminit_bits, false);
meminit->children[3] = AstNode::mkconst_int(meminit_size, false);
}
meminit = new AstNode(AST_MEMINIT);
meminit->children.push_back(AstNode::mkconst_int(cursor, false));
meminit->children.push_back(nullptr);
meminit->children.push_back(AstNode::mkconst_bits(en_bits, false));
meminit->children.push_back(nullptr);
meminit->str = memory->str;
meminit->id2ast = memory;
meminit_bits.clear();
meminit_size = 0;
current_ast_mod->children.push_back(meminit);
next_meminit_cursor = cursor;
}
meminit_size++;
next_meminit_cursor++;
meminit_bits.insert(meminit_bits.end(), value->bits.begin(), value->bits.end());
delete value;
}
else
{
block->children.push_back(new AstNode(AST_ASSIGN_EQ, new AstNode(AST_IDENTIFIER, new AstNode(AST_RANGE, AstNode::mkconst_int(cursor, false))), value));
block->children.back()->children[0]->str = memory->str;
block->children.back()->children[0]->id2ast = memory;
block->children.back()->children[0]->was_checked = true;
}
cursor += increment;
if ((cursor == finish_addr+increment) || (increment > 0 && cursor > range_max) || (increment < 0 && cursor < range_min))
break;
}
if ((cursor == finish_addr+increment) || (increment > 0 && cursor > range_max) || (increment < 0 && cursor < range_min))
break;
}
if (meminit != nullptr) {
meminit->children[1] = AstNode::mkconst_bits(meminit_bits, false);
meminit->children[3] = AstNode::mkconst_int(meminit_size, false);
}
return block;
}
// annotate the names of all wires and other named objects in a named generate
// or procedural block; nested blocks are themselves annotated such that the
// prefix is carried forward, but resolution of their children is deferred
void AstNode::expand_genblock(const std::string &prefix)
{
if (type == AST_IDENTIFIER || type == AST_FCALL || type == AST_TCALL || type == AST_WIRETYPE) {
log_assert(!str.empty());
// search starting in the innermost scope and then stepping outward
for (size_t ppos = prefix.size() - 1; ppos; --ppos) {
if (prefix.at(ppos) != '.') continue;
std::string new_prefix = prefix.substr(0, ppos + 1);
auto attempt_resolve = [&new_prefix](const std::string &ident) -> std::string {
std::string new_name = prefix_id(new_prefix, ident);
if (current_scope.count(new_name))
return new_name;
return {};
};
// attempt to resolve the full identifier
std::string resolved = attempt_resolve(str);
if (!resolved.empty()) {
str = resolved;
break;
}
// attempt to resolve hierarchical prefixes within the identifier,
// as the prefix could refer to a local scope which exists but
// hasn't yet been elaborated
for (size_t spos = str.size() - 1; spos; --spos) {
if (str.at(spos) != '.') continue;
resolved = attempt_resolve(str.substr(0, spos));
if (!resolved.empty()) {
str = resolved + str.substr(spos);
ppos = 1; // break outer loop
break;
}
}
}
}
auto prefix_node = [&prefix](AstNode* child) {
if (child->str.empty()) return;
std::string new_name = prefix_id(prefix, child->str);
if (child->type == AST_FUNCTION)
child->replace_result_wire_name_in_function(child->str, new_name);
else
child->str = new_name;
current_scope[new_name] = child;
};
for (size_t i = 0; i < children.size(); i++) {
AstNode *child = children[i];
switch (child->type) {
case AST_WIRE:
case AST_MEMORY:
case AST_PARAMETER:
case AST_LOCALPARAM:
case AST_FUNCTION:
case AST_TASK:
case AST_CELL:
case AST_TYPEDEF:
case AST_ENUM_ITEM:
case AST_GENVAR:
prefix_node(child);
break;
case AST_BLOCK:
case AST_GENBLOCK:
if (!child->str.empty())
prefix_node(child);
break;
case AST_ENUM:
current_scope[child->str] = child;
for (auto enode : child->children){
log_assert(enode->type == AST_ENUM_ITEM);
prefix_node(enode);
}
break;
default:
break;
}
}
for (size_t i = 0; i < children.size(); i++) {
AstNode *child = children[i];
// AST_PREFIX member names should not be prefixed; a nested AST_PREFIX
// still needs to recursed-into
if (type == AST_PREFIX && i == 1 && child->type == AST_IDENTIFIER)
continue;
// functions/tasks may reference wires, constants, etc. in this scope
if (child->type == AST_FUNCTION || child->type == AST_TASK)
continue;
// named blocks pick up the current prefix and will expanded later
if ((child->type == AST_GENBLOCK || child->type == AST_BLOCK) && !child->str.empty())
continue;
child->expand_genblock(prefix);
}
}
// add implicit AST_GENBLOCK names according to IEEE 1364-2005 Section 12.4.3 or
// IEEE 1800-2017 Section 27.6
void AstNode::label_genblks(std::set<std::string>& existing, int &counter)
{
switch (type) {
case AST_GENIF:
case AST_GENFOR:
case AST_GENCASE:
// seeing a proper generate control flow construct increments the
// counter once
++counter;
for (AstNode *child : children)
child->label_genblks(existing, counter);
break;
case AST_GENBLOCK: {
// if this block is unlabeled, generate its corresponding unique name
for (int padding = 0; str.empty(); ++padding) {
std::string candidate = "\\genblk";
for (int i = 0; i < padding; ++i)
candidate += '0';
candidate += std::to_string(counter);
if (!existing.count(candidate))
str = candidate;
}
// within a genblk, the counter starts fresh
std::set<std::string> existing_local = existing;
int counter_local = 0;
for (AstNode *child : children)
child->label_genblks(existing_local, counter_local);
break;
}
default:
// track names which could conflict with implicit genblk names
if (str.rfind("\\genblk", 0) == 0)
existing.insert(str);
for (AstNode *child : children)
child->label_genblks(existing, counter);
break;
}
}
// helper function for mem2reg_as_needed_pass1
static void mark_memories_assign_lhs_complex(dict<AstNode*, pool<std::string>> &mem2reg_places,
dict<AstNode*, uint32_t> &mem2reg_candidates, AstNode *that)
{
for (auto &child : that->children)
mark_memories_assign_lhs_complex(mem2reg_places, mem2reg_candidates, child);
if (that->type == AST_IDENTIFIER && that->id2ast && that->id2ast->type == AST_MEMORY) {
AstNode *mem = that->id2ast;
if (!(mem2reg_candidates[mem] & AstNode::MEM2REG_FL_CMPLX_LHS))
mem2reg_places[mem].insert(stringf("%s:%d", that->filename.c_str(), that->location.first_line));
mem2reg_candidates[mem] |= AstNode::MEM2REG_FL_CMPLX_LHS;
}
}
// find memories that should be replaced by registers
void AstNode::mem2reg_as_needed_pass1(dict<AstNode*, pool<std::string>> &mem2reg_places,
dict<AstNode*, uint32_t> &mem2reg_candidates, dict<AstNode*, uint32_t> &proc_flags, uint32_t &flags)
{
uint32_t children_flags = 0;
int lhs_children_counter = 0;
if (type == AST_TYPEDEF)
return; // don't touch content of typedefs
if (type == AST_ASSIGN || type == AST_ASSIGN_LE || type == AST_ASSIGN_EQ)
{
// mark all memories that are used in a complex expression on the left side of an assignment
for (auto &lhs_child : children[0]->children)
mark_memories_assign_lhs_complex(mem2reg_places, mem2reg_candidates, lhs_child);
if (children[0]->type == AST_IDENTIFIER && children[0]->id2ast && children[0]->id2ast->type == AST_MEMORY)
{
AstNode *mem = children[0]->id2ast;
// activate mem2reg if this is assigned in an async proc
if (flags & AstNode::MEM2REG_FL_ASYNC) {
if (!(mem2reg_candidates[mem] & AstNode::MEM2REG_FL_SET_ASYNC))
mem2reg_places[mem].insert(stringf("%s:%d", filename.c_str(), location.first_line));
mem2reg_candidates[mem] |= AstNode::MEM2REG_FL_SET_ASYNC;
}
// remember if this is assigned blocking (=)
if (type == AST_ASSIGN_EQ) {
if (!(proc_flags[mem] & AstNode::MEM2REG_FL_EQ1))
mem2reg_places[mem].insert(stringf("%s:%d", filename.c_str(), location.first_line));
proc_flags[mem] |= AstNode::MEM2REG_FL_EQ1;
}
// for proper (non-init) writes: remember if this is a constant index or not
if ((flags & MEM2REG_FL_INIT) == 0) {
if (children[0]->children.size() && children[0]->children[0]->type == AST_RANGE && children[0]->children[0]->children.size()) {
if (children[0]->children[0]->children[0]->type == AST_CONSTANT)
mem2reg_candidates[mem] |= AstNode::MEM2REG_FL_CONST_LHS;
else
mem2reg_candidates[mem] |= AstNode::MEM2REG_FL_VAR_LHS;
}
}
// remember where this is
if (flags & MEM2REG_FL_INIT) {
if (!(mem2reg_candidates[mem] & AstNode::MEM2REG_FL_SET_INIT))
mem2reg_places[mem].insert(stringf("%s:%d", filename.c_str(), location.first_line));
mem2reg_candidates[mem] |= AstNode::MEM2REG_FL_SET_INIT;
} else {
if (!(mem2reg_candidates[mem] & AstNode::MEM2REG_FL_SET_ELSE))
mem2reg_places[mem].insert(stringf("%s:%d", filename.c_str(), location.first_line));
mem2reg_candidates[mem] |= AstNode::MEM2REG_FL_SET_ELSE;
}
}
lhs_children_counter = 1;
}
if (type == AST_IDENTIFIER && id2ast && id2ast->type == AST_MEMORY)
{
AstNode *mem = id2ast;
// flag if used after blocking assignment (in same proc)
if ((proc_flags[mem] & AstNode::MEM2REG_FL_EQ1) && !(mem2reg_candidates[mem] & AstNode::MEM2REG_FL_EQ2)) {
mem2reg_places[mem].insert(stringf("%s:%d", filename.c_str(), location.first_line));
mem2reg_candidates[mem] |= AstNode::MEM2REG_FL_EQ2;
}
}
// also activate if requested, either by using mem2reg attribute or by declaring array as 'wire' instead of 'reg' or 'logic'
if (type == AST_MEMORY && (get_bool_attribute(ID::mem2reg) || (flags & AstNode::MEM2REG_FL_ALL) || !(is_reg || is_logic)))
mem2reg_candidates[this] |= AstNode::MEM2REG_FL_FORCED;
if (type == AST_MODULE && get_bool_attribute(ID::mem2reg))
children_flags |= AstNode::MEM2REG_FL_ALL;
dict<AstNode*, uint32_t> *proc_flags_p = NULL;
if (type == AST_ALWAYS) {
int count_edge_events = 0;
for (auto child : children)
if (child->type == AST_POSEDGE || child->type == AST_NEGEDGE)
count_edge_events++;
if (count_edge_events != 1)
children_flags |= AstNode::MEM2REG_FL_ASYNC;
proc_flags_p = new dict<AstNode*, uint32_t>;
}
if (type == AST_INITIAL) {
children_flags |= AstNode::MEM2REG_FL_INIT;
proc_flags_p = new dict<AstNode*, uint32_t>;
}
uint32_t backup_flags = flags;
flags |= children_flags;
log_assert((flags & ~0x000000ff) == 0);
for (auto child : children)
{
if (lhs_children_counter > 0) {
lhs_children_counter--;
if (child->children.size() && child->children[0]->type == AST_RANGE && child->children[0]->children.size()) {
for (auto c : child->children[0]->children) {
if (proc_flags_p)
c->mem2reg_as_needed_pass1(mem2reg_places, mem2reg_candidates, *proc_flags_p, flags);
else
c->mem2reg_as_needed_pass1(mem2reg_places, mem2reg_candidates, proc_flags, flags);
}
}
} else
if (proc_flags_p)
child->mem2reg_as_needed_pass1(mem2reg_places, mem2reg_candidates, *proc_flags_p, flags);
else
child->mem2reg_as_needed_pass1(mem2reg_places, mem2reg_candidates, proc_flags, flags);
}
flags &= ~children_flags | backup_flags;
if (proc_flags_p) {
#ifndef NDEBUG
for (auto it : *proc_flags_p)
log_assert((it.second & ~0xff000000) == 0);
#endif
delete proc_flags_p;
}
}
bool AstNode::mem2reg_check(pool<AstNode*> &mem2reg_set)
{
if (type != AST_IDENTIFIER || !id2ast || !mem2reg_set.count(id2ast))
return false;
if (children.empty() || children[0]->type != AST_RANGE || GetSize(children[0]->children) != 1)
log_file_error(filename, location.first_line, "Invalid array access.\n");
return true;
}
void AstNode::mem2reg_remove(pool<AstNode*> &mem2reg_set, vector<AstNode*> &delnodes)
{
log_assert(mem2reg_set.count(this) == 0);
if (mem2reg_set.count(id2ast))
id2ast = nullptr;
for (size_t i = 0; i < children.size(); i++) {
if (mem2reg_set.count(children[i]) > 0) {
delnodes.push_back(children[i]);
children.erase(children.begin() + (i--));
} else {
children[i]->mem2reg_remove(mem2reg_set, delnodes);
}
}
}
// actually replace memories with registers
bool AstNode::mem2reg_as_needed_pass2(pool<AstNode*> &mem2reg_set, AstNode *mod, AstNode *block, AstNode *&async_block)
{
bool did_something = false;
if (type == AST_BLOCK)
block = this;
if (type == AST_FUNCTION || type == AST_TASK)
return false;
if (type == AST_TYPEDEF)
return false;
if (type == AST_MEMINIT && id2ast && mem2reg_set.count(id2ast))
{
log_assert(children[0]->type == AST_CONSTANT);
log_assert(children[1]->type == AST_CONSTANT);
log_assert(children[2]->type == AST_CONSTANT);
log_assert(children[3]->type == AST_CONSTANT);
int cursor = children[0]->asInt(false);
Const data = children[1]->bitsAsConst();
Const en = children[2]->bitsAsConst();
int length = children[3]->asInt(false);
if (length != 0)
{
AstNode *block = new AstNode(AST_INITIAL, new AstNode(AST_BLOCK));
mod->children.push_back(block);
block = block->children[0];
int wordsz = GetSize(data) / length;
for (int i = 0; i < length; i++) {
int pos = 0;
while (pos < wordsz) {
if (en[pos] != State::S1) {
pos++;
} else {
int epos = pos + 1;
while (epos < wordsz && en[epos] == State::S1)
epos++;
int clen = epos - pos;
AstNode *range = new AstNode(AST_RANGE, AstNode::mkconst_int(cursor+i, false));
if (pos != 0 || epos != wordsz) {
int left;
int right;
AstNode *mrange = id2ast->children[0];
if (mrange->range_left < mrange->range_right) {
right = mrange->range_right - pos;
left = mrange->range_right - epos + 1;
} else {
right = mrange->range_right + pos;
left = mrange->range_right + epos - 1;
}
range = new AstNode(AST_MULTIRANGE, range, new AstNode(AST_RANGE, AstNode::mkconst_int(left, true), AstNode::mkconst_int(right, true)));
}
AstNode *target = new AstNode(AST_IDENTIFIER, range);
target->str = str;
target->id2ast = id2ast;
target->was_checked = true;
block->children.push_back(new AstNode(AST_ASSIGN_EQ, target, mkconst_bits(data.extract(i*wordsz + pos, clen).bits, false)));
pos = epos;
}
}
}
}
AstNode *newNode = new AstNode(AST_NONE);
newNode->cloneInto(this);
delete newNode;
did_something = true;
}
if (type == AST_ASSIGN && block == NULL && children[0]->mem2reg_check(mem2reg_set))
{
if (async_block == NULL) {
async_block = new AstNode(AST_ALWAYS, new AstNode(AST_BLOCK));
mod->children.push_back(async_block);
}
AstNode *newNode = clone();
newNode->type = AST_ASSIGN_EQ;
newNode->children[0]->was_checked = true;
async_block->children[0]->children.push_back(newNode);
newNode = new AstNode(AST_NONE);
newNode->cloneInto(this);
delete newNode;
did_something = true;
}
if ((type == AST_ASSIGN_LE || type == AST_ASSIGN_EQ) && children[0]->mem2reg_check(mem2reg_set) &&
children[0]->children[0]->children[0]->type != AST_CONSTANT)
{
std::stringstream sstr;
sstr << "$mem2reg_wr$" << children[0]->str << "$" << filename << ":" << location.first_line << "$" << (autoidx++);
std::string id_addr = sstr.str() + "_ADDR", id_data = sstr.str() + "_DATA";
int mem_width, mem_size, addr_bits;
bool mem_signed = children[0]->id2ast->is_signed;
children[0]->id2ast->meminfo(mem_width, mem_size, addr_bits);
AstNode *wire_addr = new AstNode(AST_WIRE, new AstNode(AST_RANGE, mkconst_int(addr_bits-1, true), mkconst_int(0, true)));
wire_addr->str = id_addr;
wire_addr->is_reg = true;
wire_addr->was_checked = true;
wire_addr->attributes[ID::nosync] = AstNode::mkconst_int(1, false);
mod->children.push_back(wire_addr);
while (wire_addr->simplify(true, false, false, 1, -1, false, false)) { }
AstNode *wire_data = new AstNode(AST_WIRE, new AstNode(AST_RANGE, mkconst_int(mem_width-1, true), mkconst_int(0, true)));
wire_data->str = id_data;
wire_data->is_reg = true;
wire_data->was_checked = true;
wire_data->is_signed = mem_signed;
wire_data->attributes[ID::nosync] = AstNode::mkconst_int(1, false);
mod->children.push_back(wire_data);
while (wire_data->simplify(true, false, false, 1, -1, false, false)) { }
log_assert(block != NULL);
size_t assign_idx = 0;
while (assign_idx < block->children.size() && block->children[assign_idx] != this)
assign_idx++;
log_assert(assign_idx < block->children.size());
AstNode *assign_addr = new AstNode(AST_ASSIGN_EQ, new AstNode(AST_IDENTIFIER), children[0]->children[0]->children[0]->clone());
assign_addr->children[0]->str = id_addr;
assign_addr->children[0]->was_checked = true;
block->children.insert(block->children.begin()+assign_idx+1, assign_addr);
AstNode *case_node = new AstNode(AST_CASE, new AstNode(AST_IDENTIFIER));
case_node->children[0]->str = id_addr;
for (int i = 0; i < mem_size; i++) {
if (children[0]->children[0]->children[0]->type == AST_CONSTANT && int(children[0]->children[0]->children[0]->integer) != i)
continue;
AstNode *cond_node = new AstNode(AST_COND, AstNode::mkconst_int(i, false, addr_bits), new AstNode(AST_BLOCK));
AstNode *assign_reg = new AstNode(type, new AstNode(AST_IDENTIFIER), new AstNode(AST_IDENTIFIER));
if (children[0]->children.size() == 2)
assign_reg->children[0]->children.push_back(children[0]->children[1]->clone());
assign_reg->children[0]->str = stringf("%s[%d]", children[0]->str.c_str(), i);
assign_reg->children[1]->str = id_data;
cond_node->children[1]->children.push_back(assign_reg);
case_node->children.push_back(cond_node);
}
block->children.insert(block->children.begin()+assign_idx+2, case_node);
children[0]->delete_children();
children[0]->range_valid = false;
children[0]->id2ast = NULL;
children[0]->str = id_data;
type = AST_ASSIGN_EQ;
children[0]->was_checked = true;
did_something = true;
}
if (mem2reg_check(mem2reg_set))
{
AstNode *bit_part_sel = NULL;
if (children.size() == 2)
bit_part_sel = children[1]->clone();
if (children[0]->children[0]->type == AST_CONSTANT)
{
int id = children[0]->children[0]->integer;
int left = id2ast->children[1]->children[0]->integer;
int right = id2ast->children[1]->children[1]->integer;
bool valid_const_access =
(left <= id && id <= right) ||
(right <= id && id <= left);
if (valid_const_access)
{
str = stringf("%s[%d]", str.c_str(), id);
delete_children();
range_valid = false;
id2ast = NULL;
}
else
{
int width;
if (bit_part_sel)
{
bit_part_sel->dumpAst(nullptr, "? ");
if (bit_part_sel->children.size() == 1)
width = 0;
else
width = bit_part_sel->children[0]->integer -
bit_part_sel->children[1]->integer;
delete bit_part_sel;
bit_part_sel = nullptr;
}
else
{
width = id2ast->children[0]->children[0]->integer -
id2ast->children[0]->children[1]->integer;
}
width = abs(width) + 1;
delete_children();
std::vector<RTLIL::State> x_bits;
for (int i = 0; i < width; i++)
x_bits.push_back(RTLIL::State::Sx);
AstNode *constant = AstNode::mkconst_bits(x_bits, false);
constant->cloneInto(this);
delete constant;
}
}
else
{
std::stringstream sstr;
sstr << "$mem2reg_rd$" << str << "$" << filename << ":" << location.first_line << "$" << (autoidx++);
std::string id_addr = sstr.str() + "_ADDR", id_data = sstr.str() + "_DATA";
int mem_width, mem_size, addr_bits;
bool mem_signed = id2ast->is_signed;
id2ast->meminfo(mem_width, mem_size, addr_bits);
AstNode *wire_addr = new AstNode(AST_WIRE, new AstNode(AST_RANGE, mkconst_int(addr_bits-1, true), mkconst_int(0, true)));
wire_addr->str = id_addr;
wire_addr->is_reg = true;
wire_addr->was_checked = true;
if (block)
wire_addr->attributes[ID::nosync] = AstNode::mkconst_int(1, false);
mod->children.push_back(wire_addr);
while (wire_addr->simplify(true, false, false, 1, -1, false, false)) { }
AstNode *wire_data = new AstNode(AST_WIRE, new AstNode(AST_RANGE, mkconst_int(mem_width-1, true), mkconst_int(0, true)));
wire_data->str = id_data;
wire_data->is_reg = true;
wire_data->was_checked = true;
wire_data->is_signed = mem_signed;
if (block)
wire_data->attributes[ID::nosync] = AstNode::mkconst_int(1, false);
mod->children.push_back(wire_data);
while (wire_data->simplify(true, false, false, 1, -1, false, false)) { }
AstNode *assign_addr = new AstNode(block ? AST_ASSIGN_EQ : AST_ASSIGN, new AstNode(AST_IDENTIFIER), children[0]->children[0]->clone());
assign_addr->children[0]->str = id_addr;
assign_addr->children[0]->was_checked = true;
AstNode *case_node = new AstNode(AST_CASE, new AstNode(AST_IDENTIFIER));
case_node->children[0]->str = id_addr;
for (int i = 0; i < mem_size; i++) {
if (children[0]->children[0]->type == AST_CONSTANT && int(children[0]->children[0]->integer) != i)
continue;
AstNode *cond_node = new AstNode(AST_COND, AstNode::mkconst_int(i, false, addr_bits), new AstNode(AST_BLOCK));
AstNode *assign_reg = new AstNode(AST_ASSIGN_EQ, new AstNode(AST_IDENTIFIER), new AstNode(AST_IDENTIFIER));
assign_reg->children[0]->str = id_data;
assign_reg->children[0]->was_checked = true;
assign_reg->children[1]->str = stringf("%s[%d]", str.c_str(), i);
cond_node->children[1]->children.push_back(assign_reg);
case_node->children.push_back(cond_node);
}
std::vector<RTLIL::State> x_bits;
for (int i = 0; i < mem_width; i++)
x_bits.push_back(RTLIL::State::Sx);
AstNode *cond_node = new AstNode(AST_COND, new AstNode(AST_DEFAULT), new AstNode(AST_BLOCK));
AstNode *assign_reg = new AstNode(AST_ASSIGN_EQ, new AstNode(AST_IDENTIFIER), AstNode::mkconst_bits(x_bits, false));
assign_reg->children[0]->str = id_data;
assign_reg->children[0]->was_checked = true;
cond_node->children[1]->children.push_back(assign_reg);
case_node->children.push_back(cond_node);
if (block)
{
size_t assign_idx = 0;
while (assign_idx < block->children.size() && !block->children[assign_idx]->contains(this))
assign_idx++;
log_assert(assign_idx < block->children.size());
block->children.insert(block->children.begin()+assign_idx, case_node);
block->children.insert(block->children.begin()+assign_idx, assign_addr);
}
else
{
AstNode *proc = new AstNode(AST_ALWAYS, new AstNode(AST_BLOCK));
proc->children[0]->children.push_back(case_node);
mod->children.push_back(proc);
mod->children.push_back(assign_addr);
}
delete_children();
range_valid = false;
id2ast = NULL;
str = id_data;
}
if (bit_part_sel)
children.push_back(bit_part_sel);
did_something = true;
}
log_assert(id2ast == NULL || mem2reg_set.count(id2ast) == 0);
auto children_list = children;
for (size_t i = 0; i < children_list.size(); i++)
if (children_list[i]->mem2reg_as_needed_pass2(mem2reg_set, mod, block, async_block))
did_something = true;
return did_something;
}
// calculate memory dimensions
void AstNode::meminfo(int &mem_width, int &mem_size, int &addr_bits)
{
log_assert(type == AST_MEMORY);
mem_width = children[0]->range_left - children[0]->range_right + 1;
mem_size = children[1]->range_left - children[1]->range_right;
if (mem_size < 0)
mem_size *= -1;
mem_size += min(children[1]->range_left, children[1]->range_right) + 1;
addr_bits = 1;
while ((1 << addr_bits) < mem_size)
addr_bits++;
}
bool AstNode::detect_latch(const std::string &var)
{
switch (type)
{
case AST_ALWAYS:
for (auto &c : children)
{
switch (c->type)
{
case AST_POSEDGE:
case AST_NEGEDGE:
return false;
case AST_EDGE:
break;
case AST_BLOCK:
if (!c->detect_latch(var))
return false;
break;
default:
log_abort();
}
}
return true;
case AST_BLOCK:
for (auto &c : children)
if (!c->detect_latch(var))
return false;
return true;
case AST_CASE:
{
bool r = true;
for (auto &c : children) {
if (c->type == AST_COND) {
if (c->children.at(1)->detect_latch(var))
return true;
r = false;
}
if (c->type == AST_DEFAULT) {
if (c->children.at(0)->detect_latch(var))
return true;
r = false;
}
}
return r;
}
case AST_ASSIGN_EQ:
case AST_ASSIGN_LE:
if (children.at(0)->type == AST_IDENTIFIER &&
children.at(0)->children.empty() && children.at(0)->str == var)
return false;
return true;
default:
return true;
}
}
bool AstNode::has_const_only_constructs()
{
if (type == AST_WHILE || type == AST_REPEAT)
return true;
for (auto child : children)
if (child->has_const_only_constructs())
return true;
return false;
}
bool AstNode::is_simple_const_expr()
{
if (type == AST_IDENTIFIER)
return false;
for (auto child : children)
if (!child->is_simple_const_expr())
return false;
return true;
}
// helper function for AstNode::eval_const_function()
bool AstNode::replace_variables(std::map<std::string, AstNode::varinfo_t> &variables, AstNode *fcall, bool must_succeed)
{
if (type == AST_IDENTIFIER && variables.count(str)) {
int offset = variables.at(str).offset, width = variables.at(str).val.bits.size();
if (!children.empty()) {
if (children.size() != 1 || children.at(0)->type != AST_RANGE) {
if (!must_succeed)
return false;
log_file_error(filename, location.first_line, "Memory access in constant function is not supported\n%s: ...called from here.\n",
fcall->loc_string().c_str());
}
if (!children.at(0)->replace_variables(variables, fcall, must_succeed))
return false;
while (simplify(true, false, false, 1, -1, false, true)) { }
if (!children.at(0)->range_valid) {
if (!must_succeed)
return false;
log_file_error(filename, location.first_line, "Non-constant range\n%s: ... called from here.\n",
fcall->loc_string().c_str());
}
offset = min(children.at(0)->range_left, children.at(0)->range_right);
width = min(std::abs(children.at(0)->range_left - children.at(0)->range_right) + 1, width);
}
offset -= variables.at(str).offset;
std::vector<RTLIL::State> &var_bits = variables.at(str).val.bits;
std::vector<RTLIL::State> new_bits(var_bits.begin() + offset, var_bits.begin() + offset + width);
AstNode *newNode = mkconst_bits(new_bits, variables.at(str).is_signed);
newNode->cloneInto(this);
delete newNode;
return true;
}
for (auto &child : children)
if (!child->replace_variables(variables, fcall, must_succeed))
return false;
return true;
}
// attempt to statically evaluate a functions with all-const arguments
AstNode *AstNode::eval_const_function(AstNode *fcall, bool must_succeed)
{
std::map<std::string, AstNode*> backup_scope = current_scope;
std::map<std::string, AstNode::varinfo_t> variables;
std::vector<AstNode*> to_delete;
AstNode *block = new AstNode(AST_BLOCK);
AstNode *result = nullptr;
size_t argidx = 0;
for (auto child : children)
{
block->children.push_back(child->clone());
}
while (!block->children.empty())
{
AstNode *stmt = block->children.front();
#if 0
log("-----------------------------------\n");
for (auto &it : variables)
log("%20s %40s\n", it.first.c_str(), log_signal(it.second.val));
stmt->dumpAst(NULL, "stmt> ");
#endif
if (stmt->type == AST_WIRE)
{
while (stmt->simplify(true, false, false, 1, -1, false, true)) { }
if (!stmt->range_valid) {
if (!must_succeed)
goto finished;
log_file_error(stmt->filename, stmt->location.first_line, "Can't determine size of variable %s\n%s: ... called from here.\n",
stmt->str.c_str(), fcall->loc_string().c_str());
}
AstNode::varinfo_t &variable = variables[stmt->str];
int width = abs(stmt->range_left - stmt->range_right) + 1;
// if this variable has already been declared as an input, check the
// sizes match if it already had an explicit size
if (variable.arg && variable.explicitly_sized && variable.val.size() != width) {
log_file_error(filename, location.first_line, "Incompatible re-declaration of constant function wire %s.\n", stmt->str.c_str());
}
variable.val = RTLIL::Const(RTLIL::State::Sx, width);
variable.offset = min(stmt->range_left, stmt->range_right);
variable.is_signed = stmt->is_signed;
variable.explicitly_sized = stmt->children.size() &&
stmt->children.back()->type == AST_RANGE;
// identify the argument corresponding to this wire, if applicable
if (stmt->is_input && argidx < fcall->children.size()) {
variable.arg = fcall->children.at(argidx++);
}
// load the constant arg's value into this variable
if (variable.arg) {
if (variable.arg->type == AST_CONSTANT) {
variable.val = variable.arg->bitsAsConst(width);
} else {
log_assert(variable.arg->type == AST_REALVALUE);
variable.val = variable.arg->realAsConst(width);
}
}
current_scope[stmt->str] = stmt;
block->children.erase(block->children.begin());
to_delete.push_back(stmt);
continue;
}
log_assert(variables.count(str) != 0);
if (stmt->type == AST_LOCALPARAM)
{
while (stmt->simplify(true, false, false, 1, -1, false, true)) { }
current_scope[stmt->str] = stmt;
block->children.erase(block->children.begin());
to_delete.push_back(stmt);
continue;
}
if (stmt->type == AST_ASSIGN_EQ)
{
if (stmt->children.at(0)->type == AST_IDENTIFIER && stmt->children.at(0)->children.size() != 0 &&
stmt->children.at(0)->children.at(0)->type == AST_RANGE)
if (!stmt->children.at(0)->children.at(0)->replace_variables(variables, fcall, must_succeed))
goto finished;
if (!stmt->children.at(1)->replace_variables(variables, fcall, must_succeed))
goto finished;
while (stmt->simplify(true, false, false, 1, -1, false, true)) { }
if (stmt->type != AST_ASSIGN_EQ)
continue;
if (stmt->children.at(1)->type != AST_CONSTANT) {
if (!must_succeed)
goto finished;
log_file_error(stmt->filename, stmt->location.first_line, "Non-constant expression in constant function\n%s: ... called from here. X\n",
fcall->loc_string().c_str());
}
if (stmt->children.at(0)->type != AST_IDENTIFIER) {
if (!must_succeed)
goto finished;
log_file_error(stmt->filename, stmt->location.first_line, "Unsupported composite left hand side in constant function\n%s: ... called from here.\n",
fcall->loc_string().c_str());
}
if (!variables.count(stmt->children.at(0)->str)) {
if (!must_succeed)
goto finished;
log_file_error(stmt->filename, stmt->location.first_line, "Assignment to non-local variable in constant function\n%s: ... called from here.\n",
fcall->loc_string().c_str());
}
if (stmt->children.at(0)->children.empty()) {
variables[stmt->children.at(0)->str].val = stmt->children.at(1)->bitsAsConst(variables[stmt->children.at(0)->str].val.bits.size());
} else {
AstNode *range = stmt->children.at(0)->children.at(0);
if (!range->range_valid) {
if (!must_succeed)
goto finished;
log_file_error(range->filename, range->location.first_line, "Non-constant range\n%s: ... called from here.\n",
fcall->loc_string().c_str());
}
int offset = min(range->range_left, range->range_right);
int width = std::abs(range->range_left - range->range_right) + 1;
varinfo_t &v = variables[stmt->children.at(0)->str];
RTLIL::Const r = stmt->children.at(1)->bitsAsConst(v.val.bits.size());
for (int i = 0; i < width; i++)
v.val.bits.at(i+offset-v.offset) = r.bits.at(i);
}
delete block->children.front();
block->children.erase(block->children.begin());
continue;
}
if (stmt->type == AST_FOR)
{
block->children.insert(block->children.begin(), stmt->children.at(0));
stmt->children.at(3)->children.push_back(stmt->children.at(2));
stmt->children.erase(stmt->children.begin() + 2);
stmt->children.erase(stmt->children.begin());
stmt->type = AST_WHILE;
continue;
}
if (stmt->type == AST_WHILE)
{
AstNode *cond = stmt->children.at(0)->clone();
if (!cond->replace_variables(variables, fcall, must_succeed))
goto finished;
while (cond->simplify(true, false, false, 1, -1, false, true)) { }
if (cond->type != AST_CONSTANT) {
if (!must_succeed)
goto finished;
log_file_error(stmt->filename, stmt->location.first_line, "Non-constant expression in constant function\n%s: ... called from here.\n",
fcall->loc_string().c_str());
}
if (cond->asBool()) {
block->children.insert(block->children.begin(), stmt->children.at(1)->clone());
} else {
delete block->children.front();
block->children.erase(block->children.begin());
}
delete cond;
continue;
}
if (stmt->type == AST_REPEAT)
{
AstNode *num = stmt->children.at(0)->clone();
if (!num->replace_variables(variables, fcall, must_succeed))
goto finished;
while (num->simplify(true, false, false, 1, -1, false, true)) { }
if (num->type != AST_CONSTANT) {
if (!must_succeed)
goto finished;
log_file_error(stmt->filename, stmt->location.first_line, "Non-constant expression in constant function\n%s: ... called from here.\n",
fcall->loc_string().c_str());
}
block->children.erase(block->children.begin());
for (int i = 0; i < num->bitsAsConst().as_int(); i++)
block->children.insert(block->children.begin(), stmt->children.at(1)->clone());
delete stmt;
delete num;
continue;
}
if (stmt->type == AST_CASE)
{
AstNode *expr = stmt->children.at(0)->clone();
if (!expr->replace_variables(variables, fcall, must_succeed))
goto finished;
while (expr->simplify(true, false, false, 1, -1, false, true)) { }
AstNode *sel_case = NULL;
for (size_t i = 1; i < stmt->children.size(); i++)
{
bool found_match = false;
log_assert(stmt->children.at(i)->type == AST_COND || stmt->children.at(i)->type == AST_CONDX || stmt->children.at(i)->type == AST_CONDZ);
if (stmt->children.at(i)->children.front()->type == AST_DEFAULT) {
sel_case = stmt->children.at(i)->children.back();
continue;
}
for (size_t j = 0; j+1 < stmt->children.at(i)->children.size() && !found_match; j++)
{
AstNode *cond = stmt->children.at(i)->children.at(j)->clone();
if (!cond->replace_variables(variables, fcall, must_succeed))
goto finished;
cond = new AstNode(AST_EQ, expr->clone(), cond);
while (cond->simplify(true, false, false, 1, -1, false, true)) { }
if (cond->type != AST_CONSTANT) {
if (!must_succeed)
goto finished;
log_file_error(stmt->filename, stmt->location.first_line, "Non-constant expression in constant function\n%s: ... called from here.\n",
fcall->loc_string().c_str());
}
found_match = cond->asBool();
delete cond;
}
if (found_match) {
sel_case = stmt->children.at(i)->children.back();
break;
}
}
block->children.erase(block->children.begin());
if (sel_case)
block->children.insert(block->children.begin(), sel_case->clone());
delete stmt;
delete expr;
continue;
}
if (stmt->type == AST_BLOCK)
{
if (!stmt->str.empty())
stmt->expand_genblock(stmt->str + ".");
block->children.erase(block->children.begin());
block->children.insert(block->children.begin(), stmt->children.begin(), stmt->children.end());
stmt->children.clear();
delete stmt;
continue;
}
if (!must_succeed)
goto finished;
log_file_error(stmt->filename, stmt->location.first_line, "Unsupported language construct in constant function\n%s: ... called from here.\n",
fcall->loc_string().c_str());
log_abort();
}
result = AstNode::mkconst_bits(variables.at(str).val.bits, variables.at(str).is_signed);
finished:
delete block;
current_scope = backup_scope;
for (auto it : to_delete) {
delete it;
}
to_delete.clear();
return result;
}
void AstNode::allocateDefaultEnumValues()
{
log_assert(type==AST_ENUM);
log_assert(children.size() > 0);
if (children.front()->attributes.count(ID::enum_base_type))
return; // already elaborated
int last_enum_int = -1;
for (auto node : children) {
log_assert(node->type==AST_ENUM_ITEM);
node->attributes[ID::enum_base_type] = mkconst_str(str);
for (size_t i = 0; i < node->children.size(); i++) {
switch (node->children[i]->type) {
case AST_NONE:
// replace with auto-incremented constant
delete node->children[i];
node->children[i] = AstNode::mkconst_int(++last_enum_int, true);
break;
case AST_CONSTANT:
// explicit constant (or folded expression)
// TODO: can't extend 'x or 'z item
last_enum_int = node->children[i]->integer;
break;
default:
// ignore ranges
break;
}
// TODO: range check
}
}
}
bool AstNode::is_recursive_function() const
{
std::set<const AstNode *> visited;
std::function<bool(const AstNode *node)> visit = [&](const AstNode *node) {
if (visited.count(node))
return node == this;
visited.insert(node);
if (node->type == AST_FCALL) {
auto it = current_scope.find(node->str);
if (it != current_scope.end() && visit(it->second))
return true;
}
for (const AstNode *child : node->children) {
if (visit(child))
return true;
}
return false;
};
log_assert(type == AST_FUNCTION);
return visit(this);
}
std::pair<AstNode*, AstNode*> AstNode::get_tern_choice()
{
if (!children[0]->isConst())
return {};
bool found_sure_true = false;
bool found_maybe_true = false;
if (children[0]->type == AST_CONSTANT)
for (auto &bit : children[0]->bits) {
if (bit == RTLIL::State::S1)
found_sure_true = true;
if (bit > RTLIL::State::S1)
found_maybe_true = true;
}
else
found_sure_true = children[0]->asReal(true) != 0;
AstNode *choice = nullptr, *not_choice = nullptr;
if (found_sure_true)
choice = children[1], not_choice = children[2];
else if (!found_maybe_true)
choice = children[2], not_choice = children[1];
return {choice, not_choice};
}
std::string AstNode::try_pop_module_prefix() const
{
AstNode *current_scope_ast = (current_ast_mod == nullptr) ? current_ast : current_ast_mod;
size_t pos = str.find('.', 1);
if (str[0] == '\\' && pos != std::string::npos) {
std::string new_str = "\\" + str.substr(pos + 1);
if (current_scope.count(new_str)) {
std::string prefix = str.substr(0, pos);
auto it = current_scope_ast->attributes.find(ID::hdlname);
if ((it != current_scope_ast->attributes.end() && it->second->str == prefix)
|| prefix == current_scope_ast->str)
return new_str;
}
}
return str;
}
YOSYS_NAMESPACE_END
|
// Copyright 2008-2016 Conrad Sanderson (http://conradsanderson.id.au)
// Copyright 2008-2016 National ICT Australia (NICTA)
//
// 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.
// ------------------------------------------------------------------------
//! \addtogroup SpRow
//! @{
template<typename eT>
inline
SpRow<eT>::SpRow()
: SpMat<eT>(arma_vec_indicator(), 2)
{
arma_extra_debug_sigprint();
}
template<typename eT>
inline
SpRow<eT>::SpRow(const uword in_n_elem)
: SpMat<eT>(arma_vec_indicator(), 1, in_n_elem, 2)
{
arma_extra_debug_sigprint();
}
template<typename eT>
inline
SpRow<eT>::SpRow(const uword in_n_rows, const uword in_n_cols)
: SpMat<eT>(arma_vec_indicator(), in_n_rows, in_n_cols, 2)
{
arma_extra_debug_sigprint();
}
template<typename eT>
inline
SpRow<eT>::SpRow(const SizeMat& s)
: SpMat<eT>(arma_vec_indicator(), 0, 0, 2)
{
arma_extra_debug_sigprint();
SpMat<eT>::init(s.n_rows, s.n_cols);
}
template<typename eT>
inline
SpRow<eT>::SpRow(const char* text)
: SpMat<eT>(arma_vec_indicator(), 2)
{
arma_extra_debug_sigprint();
SpMat<eT>::init(std::string(text));
}
template<typename eT>
inline
SpRow<eT>&
SpRow<eT>::operator=(const char* text)
{
arma_extra_debug_sigprint();
SpMat<eT>::init(std::string(text));
return *this;
}
template<typename eT>
inline
SpRow<eT>::SpRow(const std::string& text)
: SpMat<eT>(arma_vec_indicator(), 2)
{
arma_extra_debug_sigprint();
SpMat<eT>::init(text);
}
template<typename eT>
inline
SpRow<eT>&
SpRow<eT>::operator=(const std::string& text)
{
arma_extra_debug_sigprint();
SpMat<eT>::init(text);
return *this;
}
template<typename eT>
inline
SpRow<eT>&
SpRow<eT>::operator=(const eT val)
{
arma_extra_debug_sigprint();
SpMat<eT>::operator=(val);
return *this;
}
template<typename eT>
template<typename T1>
inline
SpRow<eT>::SpRow(const Base<eT,T1>& X)
: SpMat<eT>(arma_vec_indicator(), 2)
{
arma_extra_debug_sigprint();
SpMat<eT>::operator=(X.get_ref());
}
template<typename eT>
template<typename T1>
inline
SpRow<eT>&
SpRow<eT>::operator=(const Base<eT,T1>& X)
{
arma_extra_debug_sigprint();
SpMat<eT>::operator=(X.get_ref());
return *this;
}
template<typename eT>
template<typename T1>
inline
SpRow<eT>::SpRow(const SpBase<eT,T1>& X)
: SpMat<eT>(arma_vec_indicator(), 2)
{
arma_extra_debug_sigprint();
SpMat<eT>::operator=(X.get_ref());
}
template<typename eT>
template<typename T1>
inline
SpRow<eT>&
SpRow<eT>::operator=(const SpBase<eT,T1>& X)
{
arma_extra_debug_sigprint();
SpMat<eT>::operator=(X.get_ref());
return *this;
}
template<typename eT>
template<typename T1, typename T2>
inline
SpRow<eT>::SpRow
(
const SpBase<typename SpRow<eT>::pod_type, T1>& A,
const SpBase<typename SpRow<eT>::pod_type, T2>& B
)
: SpMat<eT>(arma_vec_indicator(), 2)
{
arma_extra_debug_sigprint();
SpMat<eT>::init(A,B);
}
template<typename eT>
inline
const SpOp<SpRow<eT>,spop_htrans>
SpRow<eT>::t() const
{
return SpOp<SpRow<eT>,spop_htrans>(*this);
}
template<typename eT>
inline
const SpOp<SpRow<eT>,spop_htrans>
SpRow<eT>::ht() const
{
return SpOp<SpRow<eT>,spop_htrans>(*this);
}
template<typename eT>
inline
const SpOp<SpRow<eT>,spop_strans>
SpRow<eT>::st() const
{
return SpOp<SpRow<eT>,spop_strans>(*this);
}
//! remove specified columns
template<typename eT>
inline
void
SpRow<eT>::shed_col(const uword col_num)
{
arma_extra_debug_sigprint();
arma_debug_check( col_num >= SpMat<eT>::n_cols, "SpRow::shed_col(): out of bounds");
shed_cols(col_num, col_num);
}
//! remove specified columns
template<typename eT>
inline
void
SpRow<eT>::shed_cols(const uword in_col1, const uword in_col2)
{
arma_extra_debug_sigprint();
arma_debug_check
(
(in_col1 > in_col2) || (in_col2 >= SpMat<eT>::n_cols),
"SpRow::shed_cols(): indices out of bounds or incorrectly used"
);
SpMat<eT>::sync_csc();
const uword diff = (in_col2 - in_col1 + 1);
// This is doubleplus easy because we have all the column pointers stored.
const uword start = SpMat<eT>::col_ptrs[in_col1];
const uword end = SpMat<eT>::col_ptrs[in_col2 + 1];
if(start != end)
{
const uword elem_diff = end - start;
eT* new_values = memory::acquire<eT> (SpMat<eT>::n_nonzero - elem_diff);
uword* new_row_indices = memory::acquire<uword>(SpMat<eT>::n_nonzero - elem_diff);
// Copy first set of elements, if necessary.
if(start > 0)
{
arrayops::copy(new_values, SpMat<eT>::values, start);
arrayops::copy(new_row_indices, SpMat<eT>::row_indices, start);
}
// Copy last set of elements, if necessary.
if(end != SpMat<eT>::n_nonzero)
{
arrayops::copy(new_values + start, SpMat<eT>::values + end, (SpMat<eT>::n_nonzero - end));
arrayops::copy(new_row_indices + start, SpMat<eT>::row_indices + end, (SpMat<eT>::n_nonzero - end));
}
memory::release(SpMat<eT>::values);
memory::release(SpMat<eT>::row_indices);
access::rw(SpMat<eT>::values) = new_values;
access::rw(SpMat<eT>::row_indices) = new_row_indices;
access::rw(SpMat<eT>::n_nonzero) -= elem_diff;
}
// Update column pointers.
uword* new_col_ptrs = memory::acquire<uword>(SpMat<eT>::n_cols - diff + 1);
// Copy first part of column pointers.
if(in_col1 > 0)
{
arrayops::copy(new_col_ptrs, SpMat<eT>::col_ptrs, in_col1);
}
// Copy last part of column pointers (and adjust their values as necessary).
if(in_col2 < SpMat<eT>::n_cols - 1)
{
arrayops::copy(new_col_ptrs + in_col1, SpMat<eT>::col_ptrs + in_col2 + 1, SpMat<eT>::n_cols - in_col2);
// Modify their values.
arrayops::inplace_minus(new_col_ptrs + in_col1, (end - start), SpMat<eT>::n_cols - in_col2);
}
memory::release(SpMat<eT>::col_ptrs);
access::rw(SpMat<eT>::col_ptrs) = new_col_ptrs;
access::rw(SpMat<eT>::n_cols) -= diff;
access::rw(SpMat<eT>::n_elem) -= diff;
SpMat<eT>::invalidate_cache();
}
// //! insert N cols at the specified col position,
// //! optionally setting the elements of the inserted cols to zero
// template<typename eT>
// inline
// void
// SpRow<eT>::insert_cols(const uword col_num, const uword N, const bool set_to_zero)
// {
// arma_extra_debug_sigprint();
//
// // insertion at col_num == n_cols is in effect an append operation
// arma_debug_check( (col_num > SpMat<eT>::n_cols), "SpRow::insert_cols(): out of bounds");
//
// arma_debug_check( (set_to_zero == false), "SpRow::insert_cols(): cannot set elements to nonzero values");
//
// uword newVal = (col_num == 0) ? 0 : SpMat<eT>::col_ptrs[col_num];
// SpMat<eT>::col_ptrs.insert(col_num, N, newVal);
// uword* new_col_ptrs = memory::acquire<uword>(SpMat<eT>::n_cols + N);
//
// arrayops::copy(new_col_ptrs, SpMat<eT>::col_ptrs, col_num);
//
// uword fill_value = (col_num == 0) ? 0 : SpMat<eT>::col_ptrs[col_num - 1];
// arrayops::inplace_set(new_col_ptrs + col_num, fill_value, N);
//
// arrayops::copy(new_col_ptrs + col_num + N, SpMat<eT>::col_ptrs + col_num, SpMat<eT>::n_cols - col_num);
//
// access::rw(SpMat<eT>::n_cols) += N;
// access::rw(SpMat<eT>::n_elem) += N;
// }
template<typename eT>
inline
typename SpRow<eT>::row_iterator
SpRow<eT>::begin_row(const uword row_num)
{
arma_extra_debug_sigprint();
// Since this is a row, row_num can only be 0. But the option is provided for
// compatibility.
arma_debug_check((row_num >= 1), "SpRow::begin_row(): index out of bounds");
return SpMat<eT>::begin();
}
template<typename eT>
inline
typename SpRow<eT>::const_row_iterator
SpRow<eT>::begin_row(const uword row_num) const
{
arma_extra_debug_sigprint();
// Since this is a row, row_num can only be 0. But the option is provided for
// compatibility.
arma_debug_check((row_num >= 1), "SpRow::begin_row(): index out of bounds");
return SpMat<eT>::begin();
}
template<typename eT>
inline
typename SpRow<eT>::row_iterator
SpRow<eT>::end_row(const uword row_num)
{
arma_extra_debug_sigprint();
// Since this is a row, row_num can only be 0. But the option is provided for
// compatibility.
arma_debug_check((row_num >= 1), "SpRow::end_row(): index out of bounds");
return SpMat<eT>::end();
}
template<typename eT>
inline
typename SpRow<eT>::const_row_iterator
SpRow<eT>::end_row(const uword row_num) const
{
arma_extra_debug_sigprint();
// Since this is a row, row_num can only be 0. But the option is provided for
// compatibility.
arma_debug_check((row_num >= 1), "SpRow::end_row(): index out of bounds");
return SpMat<eT>::end();
}
#ifdef ARMA_EXTRA_SPROW_MEAT
#include ARMA_INCFILE_WRAP(ARMA_EXTRA_SPROW_MEAT)
#endif
//! @}
|
// Copyright 2017 The Fuchsia Authors
//
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file or at
// https://opensource.org/licenses/MIT
#include "object/mbuf.h"
#include <lib/user_copy/user_ptr.h>
#include <type_traits>
#include <fbl/algorithm.h>
#include <fbl/alloc_checker.h>
#include <ktl/algorithm.h>
#define LOCAL_TRACE 0
constexpr size_t MBufChain::MBuf::kHeaderSize;
constexpr size_t MBufChain::MBuf::kMallocSize;
constexpr size_t MBufChain::MBuf::kPayloadSize;
constexpr size_t MBufChain::kSizeMax;
size_t MBufChain::MBuf::rem() const { return kPayloadSize - (off_ + len_); }
MBufChain::~MBufChain() {
while (!tail_.is_empty())
delete tail_.pop_front();
while (!freelist_.is_empty())
delete freelist_.pop_front();
}
bool MBufChain::is_full() const { return size_ >= kSizeMax; }
bool MBufChain::is_empty() const { return size_ == 0; }
zx_status_t MBufChain::Read(user_out_ptr<char> dst, size_t len, bool datagram, size_t* actual) {
return ReadHelper(this, dst, len, datagram, actual);
}
zx_status_t MBufChain::Peek(user_out_ptr<char> dst, size_t len, bool datagram,
size_t* actual) const {
return ReadHelper(this, dst, len, datagram, actual);
}
template <class T>
zx_status_t MBufChain::ReadHelper(T* chain, user_out_ptr<char> dst, size_t len, bool datagram,
size_t* actual) {
if (chain->size_ == 0) {
*actual = 0;
return ZX_OK;
}
if (datagram && len > chain->tail_.front().pkt_len_)
len = chain->tail_.front().pkt_len_;
size_t pos = 0;
auto iter = chain->tail_.begin();
while (pos < len && iter != chain->tail_.end()) {
const char* src = iter->data_ + iter->off_;
size_t copy_len = ktl::min(static_cast<size_t>(iter->len_), len - pos);
zx_status_t status = dst.byte_offset(pos).copy_array_to_user(src, copy_len);
if (status != ZX_OK) {
return status;
}
pos += copy_len;
if constexpr (std::is_const<T>::value) {
++iter;
} else {
// TODO(ZX-4366): Note, we're advancing (consuming data) after each copy. This means
// that if a subsequent copy fails (perhaps because a the write to the user buffer
// faults) data will be "dropped". Consider changing this function to only advance (and
// free) once all data has been successfully copied.
iter->off_ += static_cast<uint32_t>(copy_len);
iter->len_ -= static_cast<uint32_t>(copy_len);
chain->size_ -= copy_len;
if (iter->len_ == 0 || datagram) {
chain->size_ -= iter->len_;
if (chain->head_ == &(*iter))
chain->head_ = nullptr;
chain->FreeMBuf(chain->tail_.pop_front());
iter = chain->tail_.begin();
}
}
}
// Drain any leftover mbufs in the datagram packet if we're consuming data.
if constexpr (!std::is_const<T>::value) {
if (datagram) {
while (!chain->tail_.is_empty() && chain->tail_.front().pkt_len_ == 0) {
MBuf* cur = chain->tail_.pop_front();
chain->size_ -= cur->len_;
if (chain->head_ == cur)
chain->head_ = nullptr;
chain->FreeMBuf(cur);
}
}
}
*actual = pos;
return ZX_OK;
}
zx_status_t MBufChain::WriteDatagram(user_in_ptr<const char> src, size_t len, size_t* written) {
if (len == 0) {
return ZX_ERR_INVALID_ARGS;
}
if (len > kSizeMax)
return ZX_ERR_OUT_OF_RANGE;
if (len + size_ > kSizeMax)
return ZX_ERR_SHOULD_WAIT;
fbl::SinglyLinkedList<MBuf*> bufs;
for (size_t need = 1 + ((len - 1) / MBuf::kPayloadSize); need != 0; need--) {
auto buf = AllocMBuf();
if (buf == nullptr) {
while (!bufs.is_empty())
FreeMBuf(bufs.pop_front());
return ZX_ERR_SHOULD_WAIT;
}
bufs.push_front(buf);
}
size_t pos = 0;
for (auto& buf : bufs) {
size_t copy_len = fbl::min(MBuf::kPayloadSize, len - pos);
if (src.byte_offset(pos).copy_array_from_user(buf.data_, copy_len) != ZX_OK) {
while (!bufs.is_empty())
FreeMBuf(bufs.pop_front());
return ZX_ERR_INVALID_ARGS; // Bad user buffer.
}
pos += copy_len;
buf.len_ += static_cast<uint32_t>(copy_len);
}
bufs.front().pkt_len_ = static_cast<uint32_t>(len);
// Successfully built the packet mbufs. Put it on the socket.
while (!bufs.is_empty()) {
auto next = bufs.pop_front();
if (head_ == nullptr) {
tail_.push_front(next);
} else {
tail_.insert_after(tail_.make_iterator(*head_), next);
}
head_ = next;
}
*written = len;
size_ += len;
return ZX_OK;
}
zx_status_t MBufChain::WriteStream(user_in_ptr<const char> src, size_t len, size_t* written) {
if (head_ == nullptr) {
head_ = AllocMBuf();
if (head_ == nullptr)
return ZX_ERR_SHOULD_WAIT;
tail_.push_front(head_);
}
size_t pos = 0;
while (pos < len) {
if (head_->rem() == 0) {
auto next = AllocMBuf();
if (next == nullptr)
break;
tail_.insert_after(tail_.make_iterator(*head_), next);
head_ = next;
}
char* dst = head_->data_ + head_->off_ + head_->len_;
size_t copy_len = fbl::min(head_->rem(), len - pos);
if (size_ + copy_len > kSizeMax) {
copy_len = kSizeMax - size_;
if (copy_len == 0)
break;
}
zx_status_t status = src.byte_offset(pos).copy_array_from_user(dst, copy_len);
if (status != ZX_OK) {
// TODO(ZX-4366): Note, we're not indicating to the caller that data added so far in
// previous copies was written successfully. This means the caller may try to re-send
// the same data again, leading to duplicate data. Consider changing this function to
// report that some data was written so far, or consider not committing any of the new
// data until we can ensure success, or consider putting the socket in a state where it
// can't succeed a subsequent write.
return status;
}
pos += copy_len;
head_->len_ += static_cast<uint32_t>(copy_len);
size_ += copy_len;
}
if (pos == 0)
return ZX_ERR_SHOULD_WAIT;
*written = pos;
return ZX_OK;
}
MBufChain::MBuf* MBufChain::AllocMBuf() {
if (freelist_.is_empty()) {
fbl::AllocChecker ac;
MBuf* buf = new (&ac) MBuf();
return (!ac.check()) ? nullptr : buf;
}
return freelist_.pop_front();
}
void MBufChain::FreeMBuf(MBuf* buf) {
buf->off_ = 0u;
buf->len_ = 0u;
freelist_.push_front(buf);
}
|
//%LICENSE////////////////////////////////////////////////////////////////
//
// Licensed to The Open Group (TOG) under one or more contributor license
// agreements. Refer to the OpenPegasusNOTICE.txt file distributed with
// this work for additional information regarding copyright ownership.
// Each contributor licenses this file to you under the OpenPegasus Open
// Source License; you may not use this file except in compliance with the
// License.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//////////////////////////////////////////////////////////////////////////
//
//%////////////////////////////////////////////////////////////////////////////
#include "CIMOperationRequestDispatcher.h"
#include <Pegasus/Common/Constants.h>
#include <Pegasus/WsmServer/WsmConstants.h>
#include <Pegasus/Common/XmlReader.h> // stringToValue(), stringArrayToValue()
#include <Pegasus/Common/ContentLanguageList.h>
#include <Pegasus/Common/MessageLoader.h>
#include <Pegasus/Common/AuditLogger.h>
#include <Pegasus/Common/Tracer.h>
#include <Pegasus/Common/ObjectNormalizer.h>
#include <Pegasus/Server/reg_table.h>
#include <Pegasus/General/VersionUtil.h>
#include <ctime>
#include <Pegasus/Common/StringConversion.h>
#include <Pegasus/Common/Threads.h>
#include <Pegasus/Server/QuerySupportRouter.h>
#include <Pegasus/Server/EnumerationContext.h>
#include <Pegasus/Server/EnumerationContextTable.h>
#include <stdio.h>
#include <stdlib.h>
#ifdef PEGASUS_ENABLE_FQL
#include <Pegasus/FQL/FQLQueryExpressionRep.h>
#include <Pegasus/FQL/FQLParser.h>
#include <Pegasus/FQL/FQLInstancePropertySource.h>
#endif
/// KS_TODO delete this
#include <Pegasus/Common/Print.h>
PEGASUS_NAMESPACE_BEGIN
PEGASUS_USING_STD;
#ifndef XCOUT
# define XCOUT if (true) cout << __FILE__ << ":" << __LINE__ << " "
#endif
// KS_TODO. Replace the CSTRING args with the Str class implementaiton
#define CSTRING(ARG) (const char*) ARG.getCString()
// General class to process various objects that are made up of Pegaus
// Strings back to the String and more directly to the const char* ...
// used for display. This can be used for
// String, CIMName, CIMNamespaceName, Exception, CIMDateTime, CIMObjectPath
// The same general class exists in several places in OpenPegasus.
// TODO: make this a general part of Pegasus so it is not duplicated in
// many different files.
class Str
{
public:
Str(const String& s) : _cstr(s.getCString()) { }
Str(const CIMName& n) : _cstr(n.getString().getCString()) { }
Str(const CIMNamespaceName& n) : _cstr(n.getString().getCString()) { }
Str(const Exception& e) : _cstr(e.getMessage().getCString()) { }
Str(const CIMDateTime& x) : _cstr(x.toString().getCString()) { }
Str(const CIMObjectPath& x) : _cstr(x.toString().getCString()) { }
const char* operator*() const { return (const char*)_cstr; }
operator const char*() const { return (const char*)_cstr; }
private:
CString _cstr;
};
// Set a define based on whether FQL was enabled for this build
#ifdef PEGASUS_ENABLE_FQL
# define ENABLE_FQL_FILTER true
#else
# define ENABLE_FQL_FILTER false
#endif
/******************************************************************************
**
** Static variables outside of object context
**
******************************************************************************/
// Variable to determine the performance if we wait for pull
// response size to match request or simply for response objects to exist.
// This variable is primarily test for the advantages of each of these
// characteristics.
static Boolean requireCompleteResponses = false;
// A helper function that resets the Propagated and ClassOrigin attributes on
// properties of CIMInstance and CIMClass objects. This is used during
// Create/Modify Instance and Create/Modify Class operations, where the
// Propagated and ClassOrigin attributes must be ignored.
template <class ObjectClass>
void removePropagatedAndOriginAttributes(ObjectClass& newObject);
static const char* _getServiceName(Uint32 serviceId)
{
MessageQueue *queue = MessageQueue::lookup(serviceId);
return queue ? queue->getQueueName() : "none";
}
CIMOperationRequestDispatcher* _cimOperationRequestDispatcher = NULL;
/****************************************************************************
**
** Implementation of OperationAggregate Class
**
****************************************************************************/
OperationAggregate::OperationAggregate(
CIMOperationRequestMessage* request,
CIMName className,
CIMNamespaceName nameSpace,
Uint32 totalIssued,
Boolean requiresHostnameCompletion,
Boolean hasPropList,
QueryExpressionRep* query,
String queryLanguage)
: _messageId(request->messageId),
_filterResponse(false),
_msgRequestType(request->getType()),
_dest(request->queueIds.top()),
_className(className),
_nameSpace(nameSpace),
_requiresHostnameCompletion(requiresHostnameCompletion),
_hasPropList(hasPropList),
_query(query),
_queryLanguage(queryLanguage),
_pullOperation(false),
_enumerationFinished(false),
_closeReceived(false),
_request(request),
_totalIssued(totalIssued),
_totalReceived(0), _totalReceivedComplete(0),
_totalReceivedExpected(0), _totalReceivedErrors(0),
_totalReceivedNotSupported(0)
{
}
OperationAggregate::~OperationAggregate()
{
delete _request;
delete _query;
}
Boolean OperationAggregate::valid() const
{
// test if valid OperationAggregate object.
return _magic;
}
/* Add one response to the responseList
*/
void OperationAggregate::appendResponse(CIMResponseMessage* response)
{
PEGASUS_DEBUG_ASSERT(valid());
AutoMutex autoMut(_appendResponseMutex);
PEGASUS_DEBUG_ASSERT(response != 0);
_responseList.append(response);
}
/* Returns the count of the current number of responses in the
responseList. Note:this is not the Total number of responses,
just the number currently available for aggregation.
*/
Uint32 OperationAggregate::numberResponses() const
{
PEGASUS_DEBUG_ASSERT(valid());
return _responseList.size();
}
CIMResponseMessage* OperationAggregate::getResponse(const Uint32& pos)
{
PEGASUS_DEBUG_ASSERT(valid());
AutoMutex autoMut(_appendResponseMutex);
CIMResponseMessage* msg = _responseList[pos];
return msg;
}
CIMResponseMessage* OperationAggregate::removeResponse(const Uint32& pos)
{
PEGASUS_DEBUG_ASSERT(valid());
AutoMutex autoMut(_appendResponseMutex);
CIMResponseMessage* msg = _responseList[pos];
_responseList.remove(pos);
return msg;
}
void OperationAggregate::deleteResponse(const Uint32&pos)
{
PEGASUS_ASSERT(valid());
AutoMutex autoMut(_appendResponseMutex);
delete _responseList[pos];
_responseList.remove(pos);
}
// There are many response pieces (chunks) from potentially many
// threads funneling through this function in random order. This isolates a
// single response (by locking) from a given thread and "resequences" the
// response as part of one large response. It is crucial that the first
// response to come through here be sequenced (or indexed) as 0 and the last
// response from the last thread be marked as "isComplete"
// NOTE: Assumes no chunks can come AFTER a "isComplete" message
// of the LAST thread.
void OperationAggregate::resequenceResponse(CIMResponseMessage& response)
{
// If error, increment error counter.
// If NOT_SUPPORTED Error, increment NotSupported counter
CIMStatusCode error = response.cimException.getCode();
bool notSupportedReceived = false;
if (error != CIM_ERR_SUCCESS)
{
if (error == CIM_ERR_NOT_SUPPORTED)
{
notSupportedReceived = true;
_totalReceivedNotSupported++;
}
_totalReceivedErrors++;
// trace the error including the provider name
PEG_TRACE((TRC_DISPATCHER, Tracer::LEVEL1,
"Provider Response has errorCode=%u. Namespace=%s, ClassName=%s, "
"ResponseSequence=%u messageId=%s",
(Uint32)error,
CSTRING(_nameSpace.getString()),
CSTRING(_className.getString()),
_totalReceived, CSTRING(response.messageId) ));
}
Boolean isComplete = response.isComplete();
// if this provider is complete increment totalReceivedComplete, etc.
if (isComplete == true)
{
_totalReceivedComplete++;
_totalReceivedExpected += response.getIndex() + 1;
}
response.setIndex(_totalReceived++);
// set to incomplete until ALL completed messages have come in
isComplete = false;
// NOTE:
// _totalReceivedExpected is calculated by adding up every response index
// count WHEN the message is marked complete. This may differ from the
// following reasons:
// 1. An exception occurred in which the correct index could not be set.
// 2. Somehow the completed response arrived before the other
// (non-completed) responses ? (shouldnt happen with the current
// synchronous code).
// In either case, a message will be logged and attempt to continue
if (_totalReceivedComplete == _totalIssued)
{
if (_totalReceivedExpected == _totalReceived)
{
PEG_TRACE((TRC_DISPATCHER, Tracer::LEVEL4,
"Responses Completed. messageid=%s is complete. "
"TotalResponses=%u, totalChunks=%u, totalErrors=%u",
CSTRING(response.messageId),
_totalReceivedComplete,
_totalReceived,
_totalReceivedErrors));
}
else
{
// KS_TODO this is actually reporting an error but gets found
// only if trace is enabled. Same issue exists for lots of things
// that get reported as DISCARDED_DATA
PEG_TRACE((TRC_DISCARDED_DATA, Tracer::LEVEL1,
"All completed responses (%u) for current request"
" messageId=%s "
"have been accounted for but expected count (%u) does "
"not match the received count (%u). error count (%u).",
_totalReceivedComplete,
CSTRING(response.messageId),
_totalReceivedExpected,
_totalReceived,
_totalReceivedErrors));
}
// The goal of this logic is to send the NOT_SUPPORTED only if every
// response is a NOT_SUPPORTED so that some single provider that
// returns NOT_SUPPORTED does not mess up the complete transaction
// that is either returning other errors or some good data.
// This is because NOT_SUPPORTED should NOT be encoded into providers
// since the spec is NOT to return NOT_SUPPORTED for the enumerate,
// etc. operations. We should actually argue with ever sending the not
// supported but this appears at least logical. We could have just
// as easily simply eliminated all NOT_SUPPORT errors and done some
// other warning that a provider was returning NOT_SUPPORTED.
//
// The following eliminates NOT_SUPPORTED ERRORS unless all responses
// are NOT_SUPPORTED.
// i.e. If all of the errors received were NOT_SUPPORTED and
// all of the responses were errors, then keep the last
// NOT_SUPPORTED error. Otherwise clear the error.
//
// The condition below is the negative of that:
// If this is a NOT_SUPPORTED error response AND
// if (there was an error besides NOT_SUPPORTED), or
// (a non-error response was received), then clear the error
if (notSupportedReceived && (
(_totalReceivedErrors != _totalReceivedNotSupported)
||
(_totalReceivedErrors != _totalReceived)))
{
response.cimException = CIMException();
}
isComplete = true;
_totalReceivedComplete = 0;
_totalReceivedExpected = 0;
_totalReceivedErrors = 0;
_totalReceivedNotSupported = 0;
_totalReceived = 0;
}
else if (notSupportedReceived)
{
// Clear the NOT_SUPPORTED exception
// We ignore it unless it's the only response received
response.cimException = CIMException();
}
response.setComplete(isComplete);
}
//EXP_PULL_BEGIN
/* setPullOperation sets variables in the Operation Aggregate
specific to the pull operations upon the Open... operations for use by
subsequent pull operations. This includes:
_pullOperation - Flag to indicate that this Operation Aggregate is part
of a pull operation.
_enumerationContext - Pointer to the Enumeration Context
_EnumerationContextName - Id for this context Used only to confirm
error issues on provider responses
*/
void OperationAggregate::setPullOperation(EnumerationContext* enContext)
{
_pullOperation = true;
_enumerationContext = enContext;
_contextId = enContext->getContextId();
}
/*
*
* Common functions use by the request Handlers
*/
/*
build an array of CIMNames with all of the properties in the
class.
@param class CIMClass with the properties
@return Array<String> containing the names of all the properties
in the class.
*/
void _buildPropertyListWithTags(CIMConstClass& thisClass,
CIMPropertyList& propertyList)
{
Array<String> propertyNameArray;
Uint32 numProperties = thisClass.getPropertyCount();
for (Uint32 i = 0; i < numProperties; i++)
{
propertyNameArray.append(
thisClass.getProperty(i).getName().getString());
}
propertyList.append(propertyNameArray);
}
//EXP_PULL_END
/*************************************************************************
**
** Implementation of ProviderInfoList Class.
** NOTE: Much of this class implemented in the header file
**
***************************************************************************/
Boolean ProviderInfoList::hasMore(Boolean isProvider)
{
ConstArrayIterator<ProviderInfo> iterator(_array);
while (_index < iterator.size())
{
if (iterator[_index].hasProvider == isProvider)
{
return true;
}
else
{
_index++;
}
}
// Reset index when complete. This is so the hasMore can be used
// multiple times to cycle through the list.
_index = 0;
return false;
}
// Commmon function to display routing info for a providerInfo element.
void ProviderInfoList::pegRoutingTrace(ProviderInfo& providerInfo,
const char * reqMsgName,
String& messageId)
{
if (providerInfo.controlProviderName.size() != 0)
{
PEG_TRACE((TRC_DISPATCHER, Tracer::LEVEL4,
"%s Routing request for class %s to "
"service \"%s\" for control provider \"%s\". "
"Class # %u of %u, messageId=%s",
reqMsgName,
CSTRING(providerInfo.className.getString()),
_getServiceName(providerInfo.serviceId),
CSTRING(providerInfo.controlProviderName),
getIndex() + 1, size(),
CSTRING(messageId) ));
}
else
{
PEG_TRACE((TRC_DISPATCHER, Tracer::LEVEL4,
"%s Routing request for class %s to "
"service \"%s\". Class # %u of %u, messageId=%s",
reqMsgName,
CSTRING(providerInfo.className.getString()),
_getServiceName(providerInfo.serviceId),
getIndex() + 1, size(),
CSTRING(messageId) ));
}
}
/*************************************************************************
**
** Implementation of CIMOperationRequestDispatcher Class
**
***************************************************************************/
// Dispatcher Class Constructor. Setup Dispatcher configuration from
// compile and runtime options. This includes setting up QueueIds,
// limit parameters, etc. that will be used for request operation processing
//
CIMOperationRequestDispatcher::CIMOperationRequestDispatcher(
CIMRepository* repository,
ProviderRegistrationManager* providerRegistrationManager)
: Base(PEGASUS_QUEUENAME_OPREQDISPATCHER),
_repository(repository),
_providerRegistrationManager(providerRegistrationManager)
{
PEG_METHOD_ENTER(TRC_DISPATCHER,
"CIMOperationRequestDispatcher::CIMOperationRequestDispatcher");
_cimOperationRequestDispatcher = this;
//
// Setup enable AssociationTraversal parameter from runtime configuration.
// Determines whether association operations are allowed.
//
ConfigManager* configManager = ConfigManager::getInstance();
_enableAssociationTraversal = ConfigManager::parseBooleanValue(
configManager->getCurrentValue("enableAssociationTraversal"));
//
// Set up maximum breadth of Enums parameter from define.
// Determines maximum
// classes that can particpate in an enumeration. Can be used to
// limit size of enumerations, associations, etc. to a maximum number
// of providers
// Get the maximum breadth of enum parameter from config if it exists.
//
// ATTN: KS 20030602 Bypass param acquistion until we get it into the
// config manager
// Config param removed for Pegasus 2.2 and until PEP 66 resolved.
// In place, we simply allow anything through by setting the breadth too
// large number.
// #define MAXENUMBREADTHTESTENABLED
#ifdef MAXENUMBREADTHTESTENABLED
String maxEnumBreadthOption;
try
{
maxEnumBreadthOption =
configManager->getCurrentValue("maximumEnumerationBreadth");
if (maxEnumBreadthOption.size() != 0)
_maximumEnumerateBreadth =
atol(maxEnumBreadthOption.getCString());
}
catch (...)
{
_maximumEnumerateBreadth = 50;
}
#else
// As part of disabling the test for now, we set to very large number.
_maximumEnumerateBreadth = 1000;
#endif
//EXP_PULL_BEGIN
// setup PULL_OPERATION_MAXIMUM_OBJECT_COUNT
// Define the maximum number of objects that the server will return for a
// single pull... or open... operation. (Objects can be instances or
// CIMObjectPaths depending on the operation.
_systemPullOperationMaxObjectCount = ConfigManager::parseUint32Value(
configManager->getCurrentValue("pullOperationsMaxObjectCount"));
//
// Define maximum pull interoperation timeout value. This sets
// the maximum value for operationTimeout that will be accepted by
// Pegasus. Anything larger than this will be rejected with the
// error CIM_ERR_INVALID_OPERATION_TIMEOUT.
_pullOperationMaxTimeout = ConfigManager::parseUint32Value(
configManager->getCurrentValue("pullOperationsMaxTimeout"));
// Define variable that controls whether pegasus allows 0 as a pull
// interoperation timeout value. Since the behavior for a zero value is
// that the server maintains no timer for the context, it may be the
// decision of most implementors to not allow this value.
// NOTE: Generally this should NEVER be used as it allows the client
// to open enumerations that will NEVER be closed.
#define PEGASUS_PULL_OPERATION_REJECT_ZERO_TIMEOUT_VALUE
#ifdef PEGASUS_PULL_OPERATION_REJECT_ZERO_TIMEOUT_VALUE
_rejectZeroOperationTimeoutValue = true;
#else
// Default setting if nothing supplied externally
_rejectZeroOperationTimeoutValue = false;
#endif
// Create the EnumerationContextTable and get pointer to the
// created Instance
_enumerationContextTable = EnumerationContextTable::getInstance();
//EXP_PULL_END
//
// Setup list of provider modules that will be excluded from normalization
// List derived from runtime variable with format name, name, ....
//
#ifdef PEGASUS_ENABLE_OBJECT_NORMALIZATION
String moduleList =
configManager->getCurrentValue("excludeModulesFromNormalization");
for (Uint32 pos = moduleList.find(','); moduleList.size() != 0;
pos = moduleList.find(','))
{
String moduleName = moduleList.subString(0, pos);
_excludeModulesFromNormalization.append(moduleName);
moduleList.remove(0, (pos == PEG_NOT_FOUND ? pos : pos + 1));
}
#endif
// Get pointer to Internal Provider Routing Table. Note that table
// probably not actually built at this point since it must be build
// very late in initialization. See CIMServer.cpp
_routing_table = DynamicRoutingTable::getRoutingTable();
// Get ProviderManager QueueId (Used to forward requests
// providerManager must be initialized before
// Dispatcher so QueueId set.
_providerManagerServiceId =
lookup(PEGASUS_QUEUENAME_PROVIDERMANAGER_CPP)->getQueueId();
PEG_METHOD_EXIT();
}
//
// CIMOperationDispatcher object destructor
//
CIMOperationRequestDispatcher::~CIMOperationRequestDispatcher()
{
PEG_METHOD_ENTER(TRC_DISPATCHER,
"CIMOperationRequestDispatcher::~CIMOperationRequestDispatcher");
// Delete EnumerationContextTable
_enumerationContextTable->removeContextTable();
delete _enumerationContextTable;
PEG_METHOD_EXIT();
}
// Get Provider name and moduleName from OperationContext.
// Used only by the AuditLog functions
void CIMOperationRequestDispatcher::_getProviderName(
const OperationContext& context,
String& moduleName,
String& providerName)
{
moduleName.clear();
providerName.clear();
if (context.contains(ProviderIdContainer::NAME))
{
const ProviderIdContainer pidc =
(const ProviderIdContainer) context.get(ProviderIdContainer::NAME);
CIMConstInstance module = pidc.getModule();
Uint32 pos = module.findProperty(_PROPERTY_PROVIDERMODULE_NAME);
if (pos != PEG_NOT_FOUND)
{
module.getProperty(pos).getValue().get(moduleName);
}
CIMConstInstance provider = pidc.getProvider();
pos = provider.findProperty(PEGASUS_PROPERTYNAME_NAME);
if (pos != PEG_NOT_FOUND)
{
provider.getProperty(pos).getValue().get(providerName);
}
}
}
void CIMOperationRequestDispatcher::_logOperation(
const CIMOperationRequestMessage* request,
const CIMResponseMessage* response)
{
#ifdef PEGASUS_ENABLE_AUDIT_LOGGER
PEG_METHOD_ENTER(TRC_DISPATCHER,
"CIMOperationRequestDispatcher::_logOperation");
String moduleName;
String providerName;
if (AuditLogger::isEnabled())
{
switch (request->getType())
{
case CIM_CREATE_CLASS_REQUEST_MESSAGE:
{
const CIMCreateClassRequestMessage* req =
reinterpret_cast<const CIMCreateClassRequestMessage*>(
request);
AuditLogger::logUpdateClassOperation(
"CreateClass",
AuditLogger::EVENT_CREATE,
req->userName,
req->ipAddress,
req->nameSpace,
req->className,
response->cimException.getCode());
break;
}
case CIM_MODIFY_CLASS_REQUEST_MESSAGE:
{
const CIMModifyClassRequestMessage* req =
reinterpret_cast<const CIMModifyClassRequestMessage*>(
request);
AuditLogger::logUpdateClassOperation(
"ModifyClass",
AuditLogger::EVENT_UPDATE,
req->userName,
req->ipAddress,
req->nameSpace,
req->className,
response->cimException.getCode());
break;
}
case CIM_DELETE_CLASS_REQUEST_MESSAGE:
{
const CIMDeleteClassRequestMessage* req =
reinterpret_cast<const CIMDeleteClassRequestMessage*>(
request);
AuditLogger::logUpdateClassOperation(
"DeleteClass",
AuditLogger::EVENT_DELETE,
req->userName,
req->ipAddress,
req->nameSpace,
req->className,
response->cimException.getCode());
break;
}
case CIM_SET_QUALIFIER_REQUEST_MESSAGE:
{
const CIMSetQualifierRequestMessage* req =
reinterpret_cast<const CIMSetQualifierRequestMessage*>(
request);
AuditLogger::logUpdateQualifierOperation(
"SetQualifier",
AuditLogger::EVENT_UPDATE,
req->userName,
req->ipAddress,
req->nameSpace,
req->qualifierDeclaration.getName(),
response->cimException.getCode());
break;
}
case CIM_DELETE_QUALIFIER_REQUEST_MESSAGE:
{
const CIMDeleteQualifierRequestMessage* req =
reinterpret_cast<const CIMDeleteQualifierRequestMessage*>(
request);
AuditLogger::logUpdateQualifierOperation(
"DeleteQualifier",
AuditLogger::EVENT_DELETE,
req->userName,
req->ipAddress,
req->nameSpace,
req->qualifierName,
response->cimException.getCode());
break;
}
case CIM_CREATE_INSTANCE_REQUEST_MESSAGE:
{
const CIMCreateInstanceRequestMessage* req =
reinterpret_cast<const CIMCreateInstanceRequestMessage*>(
request);
const CIMCreateInstanceResponseMessage* resp =
reinterpret_cast<const CIMCreateInstanceResponseMessage*>(
response);
_getProviderName(
req->operationContext, moduleName, providerName);
AuditLogger::logUpdateInstanceOperation(
"CreateInstance",
AuditLogger::EVENT_CREATE,
req->userName,
req->ipAddress,
req->nameSpace,
(response->cimException.getCode() == CIM_ERR_SUCCESS) ?
resp->instanceName :
CIMObjectPath(req->className.getString()),
moduleName,
providerName,
response->cimException.getCode());
break;
}
case CIM_MODIFY_INSTANCE_REQUEST_MESSAGE:
{
const CIMModifyInstanceRequestMessage* req =
reinterpret_cast<const CIMModifyInstanceRequestMessage*>(
request);
_getProviderName(
req->operationContext, moduleName, providerName);
AuditLogger::logUpdateInstanceOperation(
"ModifyInstance",
AuditLogger::EVENT_UPDATE,
req->userName,
req->ipAddress,
req->nameSpace,
req->modifiedInstance.getPath(),
moduleName,
providerName,
response->cimException.getCode());
break;
}
case CIM_DELETE_INSTANCE_REQUEST_MESSAGE:
{
const CIMDeleteInstanceRequestMessage* req =
reinterpret_cast<const CIMDeleteInstanceRequestMessage*>(
request);
_getProviderName(
req->operationContext, moduleName, providerName);
AuditLogger::logUpdateInstanceOperation(
"DeleteInstance",
AuditLogger::EVENT_DELETE,
req->userName,
req->ipAddress,
req->nameSpace,
req->instanceName,
moduleName,
providerName,
response->cimException.getCode());
break;
}
case CIM_SET_PROPERTY_REQUEST_MESSAGE:
{
const CIMSetPropertyRequestMessage* req =
reinterpret_cast<const CIMSetPropertyRequestMessage*>(
request);
_getProviderName(
req->operationContext, moduleName, providerName);
AuditLogger::logUpdateInstanceOperation(
"SetProperty",
AuditLogger::EVENT_UPDATE,
req->userName,
req->ipAddress,
req->nameSpace,
req->instanceName,
moduleName,
providerName,
response->cimException.getCode());
break;
}
case CIM_INVOKE_METHOD_REQUEST_MESSAGE:
{
const CIMInvokeMethodRequestMessage* req =
reinterpret_cast<const CIMInvokeMethodRequestMessage*>(
request);
_getProviderName(
req->operationContext, moduleName, providerName);
AuditLogger::logInvokeMethodOperation(
req->userName,
req->ipAddress,
req->nameSpace,
req->instanceName,
req->methodName,
moduleName,
providerName,
response->cimException.getCode());
break;
}
default:
// Other operations are not logged.
break;
}
}
PEG_METHOD_EXIT();
#endif
}
/* Send the given response synchronously using the given aggregation object.
return whether the sent message was complete or not. The parameters are
pointer references because they can be come invalid from external deletes
if the message is complete after queueing. They can be zeroed in this
function preventing the caller from referencing deleted pointers.
If pull operation, send to EnumerationContext queue. If not pull sent
directly to output queue.
Operations for internal clients are gathered completely since there is
no chunking.
*/
Boolean CIMOperationRequestDispatcher::_enqueueResponse(
OperationAggregate*& poA,
CIMResponseMessage*& response)
{
PEG_METHOD_ENTER(TRC_DISPATCHER,
"CIMOperationRequestDispatcher::_enqueueResponse");
PEGASUS_DEBUG_ASSERT(poA->valid());
PEGASUS_DEBUG_ASSERT(response->valid());
// Obtain the _enqueueResponseMutex mutex for this chunked request.
// This mutex serializes chunked responses from all incoming
// provider threads. It is imperative that the sequencing done by the
// resequenceResponse() method and the writing of the chunked response
// to the connection socket (done as a synchronous enqueue at the end
// of this method) are atomic to ensure that the chunk that is marked
// as isComplete for the overall response is indeed the last chunk
// returned to the client. See PEP 140 for details.
// This mutex was moved into the OperationAggregate class as part of
// bug 5157 because we only need to serialize on a per-request basis.
// This prevents serializing independent requests on separate connections.
AutoMutex autoMut(poA->_enqueueResponseMutex);
Boolean isComplete = false;
try
{
// get the completion status of the incoming response on this thread.
isComplete = response->isComplete();
poA->appendResponse(response);
Uint32 type = poA->getRequestType();
// There should never be more than one object in the list for async
// queues these functions are called for their jobs other than
// aggregating.
// All CIMENUM.., CIM_REF,, and CIM_ASSOC... messages
if (type != CIM_EXEC_QUERY_REQUEST_MESSAGE)
{
// Hostname completion required for the four assoc-like operations
handleOperationResponseAggregation(poA);
}
else
{
handleExecQueryResponseAggregation(poA);
}
// now take the aggregated response. This is now the one we will
// work with
response = poA->removeResponse(Uint32(0));
PEGASUS_DEBUG_ASSERT(response->valid());
// reset the completion flag of the last response added to the list.
// This only makes a difference when there was at least two on the list
// to begin with before aggregation methods (above) were called.
// Typically, there will be more than two on the list when a non-async
// destination queue keeps appending the responses until the completion
// of all threads/responses has occurred.
response->setComplete(isComplete);
response->dest = poA->_dest;
poA->resequenceResponse(*response);
// now get the completion status of the response after it has been
// resequenced. This will reset the completion status of the entire
// message, not just this one thread coming through here.
isComplete = response->isComplete();
// can the destination service queue handle async responses ?
// (i.e multiple responses from one request). Certain known ones
// cannot handle it. Most notably, the internal client.
MessageQueue* q = lookup(poA->_dest);
const char* name = q ? q->getQueueName() : 0;
Boolean isDestinationQueueAsync = !(name &&
(strcmp(name, PEGASUS_QUEUENAME_INTERNALCLIENT) == 0 ||
strcmp(name, PEGASUS_QUEUENAME_WSMPROCESSOR) == 0));
// for non-async queues, we'll just keep appending until all responses
// have come in
if (isDestinationQueueAsync == false)
{
if (isComplete == false)
{
poA->appendResponse(response);
return isComplete;
}
// need to reset the first response to complete if the
// last one that came in was complete
response->setComplete(true);
response->setIndex(0);
}
// Log only if this is the last of the aggregated response
if (isComplete)
{
_logOperation(poA->getRequest(), response);
}
// If it is a pull operation response, send to the output caching queue
// in the enumeration context. If not a pull operation,
// directly queue.
if (poA->_pullOperation)
{
// pull operation. get and validate the enumerationContext
EnumerationContext* en = poA->_enumerationContext;
if (!en->valid())
{
EnumerationContext *en = _enumerationContextTable->find(
poA->_contextId);
if (en == 0)
{
// Did not find one means that the enumcontext cleaned up
// before provider responded. Just issue discard trace
PEG_TRACE((TRC_DISCARDED_DATA, Tracer::LEVEL1,
"Provider Response for non-Existent ContextId=%s"
" providers. Response Discarded",
(const char *)poA->_contextId.getCString() ));
// KS_TODO should we discard the response here and what
// about the poA. Not really sure but it is a very rare
// condition, probably when we have closed enum before
// providers complete. Probably only if providers delay
// several minutes before response.
}
// If we found one but it is invalid, we have a system error
else
{
PEGASUS_ASSERT(false);
// Concluded that an invalid enum on response is really
// a system error and should cause failure. We may want
// to rethink that in the future
//// PEG_TRACE((TRC_DISCARDED_DATA, Tracer::LEVEL1,
//// "Provider Response for invalid EnumerationContext %s"
//// "providers. System Error",
//// (const char *)poA->_contextId.getCString() ));
}
// return true, just discards everything.
return true;
}
#ifdef PEGASUS_DEBUG
else
{
EnumerationContext* ent = _enumerationContextTable->find(
poA->_contextId);
PEGASUS_DEBUG_ASSERT(ent == en);
}
#endif
PEGASUS_DEBUG_ASSERT(poA->_contextId == en->getContextId());
// When provider response receved, clear this counter.
en->clearConsecutiveZeroLenObjectResponseCounter();
// If this is an exception set the error in EnumerationContext
if (response->cimException.getCode())
{
en->setErrorState(response->cimException);
}
// Send to the EnumerationContext cache with the
// isComplete indicator. Return indicates whether cache is closed
// and providers complete for cleanup.
// The enumerationContext could also be cleaned up by the
// timer thread once the providers are marked complete in
// the enumerationContext (if the client had timed out )
en->lockContext();
// putCache returns true if client not closed
if (en->putCache(response, isComplete))
{
// if there are responses and there is a
// waiting future response, issue the response
// If request pending, test to see if responses exist to
// be sent.
if (en->_savedRequest != NULL)
{
// If there are responses or error to send, send response
if ( (en->testCacheForResponses(
en->_savedOperationMaxObjectCount,
requireCompleteResponses)) )
{
PEGASUS_DEBUG_ASSERT(en->_savedRequest->valid());
PEGASUS_DEBUG_ASSERT(en->_savedResponse->valid());
// Issue response. This may mark context closed.
_issueImmediateOpenOrPullResponseMessage(
en->_savedRequest,
en->_savedResponse,
en,
en->_savedOperationMaxObjectCount);
// Delete the request; it was allocated for
// this delayed response.
delete en->_savedRequest;
// clear the saved request to indicate it was used
en->_savedRequest = NULL;
en->_savedResponse = NULL;
en->_savedOperationMaxObjectCount = 0;
}
}
}
else
{
if (en->_savedRequest != NULL)
{
delete en->_savedRequest;
delete en->_savedResponse;
en->_savedRequest = NULL;
en->_savedResponse = NULL;
}
}
if (isComplete)
{
en->setProvidersComplete();
}
PEGASUS_DEBUG_ASSERT(response->valid());
delete response;
// If closed on client side, we can release
// This MUST BE last operation on the en since
// the en could be removed by one of the other threads
// if conditions are correct.
if (en->isClientClosed() && isComplete)
{
// en may be deleted after this call
_enumerationContextTable->releaseContext(en);
}
else
{
en->unlockContext();
// If providers not complete and client open, test for cache
// overload before continuing. Do not wait if client is
// closed since goal is to remove any existing
// provider responses
if (!isComplete && !en->isClientClosed())
{
// Wait here if the cache is too large. Sending
// requests will reduce the size of the cache and
// signal this wait function when size returns below
// limit.
en->waitCacheSize();
}
}
}
// Otherwise not a pull operation; queue response
// Send it syncronously so that multiple responses will show up in the
// receiving queue according to the order that we have set the response
// index. If this was a single complete response, we could in theory
// send it async (i.e SendForget), however, there is no need to make a
// condition point based off this.
else
{
if (q)
{
q->enqueue(response);
}
else
{
PEG_METHOD_EXIT();
throw UninitializedObjectException();
}
}
}
catch (...)
{
static const char failMsg[] =
"Failed to resequence/aggregate/forward response";
PEG_TRACE((TRC_DISCARDED_DATA, Tracer::LEVEL1,
"%s%s",
"CIMOperationRequestDispatcher::_enqueueResponse",
failMsg));
if (response->cimException.getCode() != CIM_ERR_SUCCESS)
response->cimException =
CIMException(CIM_ERR_FAILED, String(failMsg));
}
// after sending, the response has been deleted externally
response = 0;
PEG_METHOD_EXIT();
return isComplete;
}
void CIMOperationRequestDispatcher::_handle_async_request(AsyncRequest* req)
{
PEG_METHOD_ENTER(TRC_DISPATCHER,
"CIMOperationRequestDispatcher::_handle_async_request");
// pass legacy operations to handleEnqueue
// unless it is a CIM_NOTIFY_CONFIG_CHANGE
if (req->getType() == ASYNC_ASYNC_LEGACY_OP_START)
{
AutoPtr<Message> legacy(
static_cast<AsyncLegacyOperationStart *>(req)->get_action());
AutoPtr<CIMResponseMessage> response;
if (legacy->getType() == CIM_NOTIFY_CONFIG_CHANGE_REQUEST_MESSAGE)
{
try
{
response.reset(
handlePropertyUpdateRequest(
(CIMNotifyConfigChangeRequestMessage*)
legacy.get()));
}
catch (Exception& e)
{
response.reset(((CIMRequestMessage*)
legacy.get())->buildResponse());
response->cimException =
PEGASUS_CIM_EXCEPTION(CIM_ERR_FAILED, e.getMessage());
}
catch (...)
{
response.reset(((CIMRequestMessage*)
legacy.get())->buildResponse());
response->cimException =
PEGASUS_CIM_EXCEPTION(CIM_ERR_FAILED, "Exception: Unknown");
}
AutoPtr<AsyncLegacyOperationResult> result(
new AsyncLegacyOperationResult(
req->op,
response.get()));
response.release();
result.release();
_complete_op_node(req->op);
}
else
{
Message *message =
static_cast<AsyncLegacyOperationStart*>(req)->get_action();
handleEnqueue(message);
}
PEG_METHOD_EXIT();
return;
}
// pass all other operations to the default handler
Base::_handle_async_request(req);
PEG_METHOD_EXIT();
}
//
// Update the DeliveryRetryAttempts & DeliveryRetryInterval
// with the new property value
//
CIMNotifyConfigChangeResponseMessage*
CIMOperationRequestDispatcher::handlePropertyUpdateRequest(
CIMNotifyConfigChangeRequestMessage *message)
{
PEG_METHOD_ENTER(TRC_IND_HANDLER,
"CIMOperationRequestDispatcher::_handlePropertyUpdateRequest");
CIMNotifyConfigChangeRequestMessage * notifyRequest=
dynamic_cast<CIMNotifyConfigChangeRequestMessage*>(message);
Uint64 v;
StringConversion::decimalStringToUint64(
notifyRequest->newPropertyValue.getCString(),v);
if (String::equal(
notifyRequest->propertyName, "pullOperationsMaxObjectCount"))
{
_systemPullOperationMaxObjectCount = (Uint32)v;
}
else if(String::equal(
notifyRequest->propertyName, "pullOperationsMaxTimeout"))
{
_pullOperationMaxTimeout = (Uint32)v;
}
else if (String::equal(
notifyRequest->propertyName, "pullOperationsDefaultTimeout"))
{
EnumerationContextTable::setDefaultOperationTimeoutSec(v);
}
else
{
PEGASUS_UNREACHABLE(PEGASUS_ASSERT(0);)
}
CIMNotifyConfigChangeResponseMessage *response =
dynamic_cast<CIMNotifyConfigChangeResponseMessage*>(
message->buildResponse());
PEG_METHOD_EXIT();
return response;
}
/*
Get an internal provider that matches the namespace/classname pair
@parameter nameSpace CIMNamespaceName of desired provider
$param className CIMName input with className of desired provider
@providerInfo ProviderInfo with registration information for registered
provider if provider found
@return True if internal provider found. If found, registration
information is in provider. False if no internal provider found.
*/
Boolean CIMOperationRequestDispatcher::_lookupInternalProvider(
const CIMNamespaceName& nameSpace,
const CIMName& className,
ProviderInfo& providerInfo)
{
PEG_METHOD_ENTER(TRC_DISPATCHER,
"CIMOperationRequestDispatcher::_lookupInternalProvider");
// Clear the parameters since used as test after getRouting call
Uint32 serviceId = 0;
String controlProviderName;
providerInfo.hasProvider = _routing_table->getRouting(
className,
nameSpace,
controlProviderName,
serviceId);
if (providerInfo.hasProvider)
{
PEG_TRACE((TRC_DISPATCHER, Tracer::LEVEL4,
"Internal provider Service = %s provider %s found.",
_getServiceName(serviceId),
CSTRING(controlProviderName) ));
providerInfo.serviceId = serviceId;
providerInfo.controlProviderName = controlProviderName;
}
PEG_METHOD_EXIT();
return providerInfo.hasProvider;
}
/**
_getSubClassNames - Gets the names of all subclasses of the defined
class (including the class) and returns it in an array of strings. Uses a
similar function in the repository class to get the names. Note that
this prepends the result with the input classname.
@param namespace
@param className
@return Array of strings with class names. Note that there should be at
least one classname in the array (the input name)
Note that there is a special exception to this function, the __namespace
class which does not have any representation in the class repository.
@exception CIMException(CIM_ERR_INVALID_CLASS)
*/
Array<CIMName> CIMOperationRequestDispatcher::_getSubClassNames(
const CIMNamespaceName& nameSpace,
const CIMName& className)
{
PEG_METHOD_ENTER(TRC_DISPATCHER,
"CIMOperationRequestDispatcher::_getSubClassNames");
Array<CIMName> subClassNames;
//
// Get names of descendent classes:
// Ignore if the special class __Namespace because it works in very
// strange way. NOTE: This class is also deprecated in DSP0200.
//
if (!className.equal (PEGASUS_CLASSNAME___NAMESPACE))
{
// Get the complete list of subclass names
// getSubClassNames throws an exception if the class does not exist
_repository->getSubClassNames(nameSpace,
className, true, subClassNames);
}
// Prepend the array with the classname from the request so
// return is this class and all subclasses
subClassNames.prepend(className);
PEG_METHOD_EXIT();
return subClassNames;
}
///////////////////////////////////////////////////////////////////////////
//
// Provider Lookup Functions - Gets list of providers for operation types
// (ex. associations, enumerate, get, invokeMethod
//
//////////////////////////////////////////////////////////////////////////
//
/* lookupAllInstanceProviders - Returns the list of all subclasses of this
class along with information about whether it is an instance provider.
@param nameSpace - Namespace for the lookup.
@param className - className for which we are finding providers
@param providerCount - Returns count of providers in the response array.
This is because the array returned is all subclasses, not simply those
with providers.
@return Returns an array of ProviderInfo, one entry for each subclass.
Each ProviderInfo instance defines whether a provider exists and the
information on the provider so that the operation can be forwarded to the
provider.
@exception - Throws exception if the className is in error or the request
is to broad. The className exception should NEVER occur since
the className should have already been validated in the operation
validation code.
*/
ProviderInfoList CIMOperationRequestDispatcher::_lookupAllInstanceProviders(
const CIMNamespaceName& nameSpace,
const CIMName& className)
{
PEG_METHOD_ENTER(TRC_DISPATCHER,
"CIMOperationRequestDispatcher::_lookupAllInstanceProviders");
ProviderInfoList providerList;
Array<CIMName> classNames = _getSubClassNames(nameSpace, className);
// Loop for all classNames found
ConstArrayIterator<CIMName> iterator(classNames);
for (Uint32 i = 0, n = iterator.size(); i < n; i++)
{
// Lookup any instance providers and add to send list
ProviderInfo providerInfo =
_lookupInstanceProvider(nameSpace, iterator[i]);
if (providerInfo.hasProvider)
{
providerList.providerCount++;
PEG_TRACE((TRC_DISPATCHER,Tracer::LEVEL4,
"Provider found for class = %s servicename = %s "
"controlProviderName = %s",
CSTRING(providerInfo.className.getString()),
_getServiceName(providerInfo.serviceId),
CSTRING(providerInfo.controlProviderName)));
}
// Always add providerInfo to be sure we include classes without
// providers. This does not increment provider count
providerList.appendClass(providerInfo);
}
// Reject if the request is too broad
_rejectEnumerateTooBroad(
nameSpace, className, providerList.providerCount);
// Diagnostic to display list of classes returned. Enable the following
// line to see what this function returns.
// providerList.trace(nameSpace, className);
PEG_METHOD_EXIT();
return providerList;
}
/* _lookupInstanceProvider - Looks up the internal or registered instance
provider for the classname and namespace.
@return ProviderInfo struct with information about the provider found.
If ProviderInfo.hasProvider returns false, no provider for this
classname/namespace combination.
This function calls both the _lookupInternalProvider function and if
nothing found, the providerRegistration _lookupInstanceProvider function.
*/
ProviderInfo CIMOperationRequestDispatcher::_lookupInstanceProvider(
const CIMNamespaceName& nameSpace,
const CIMName& className)
{
PEG_METHOD_ENTER(TRC_DISPATCHER,
"CIMOperationRequestDispatcher::_lookupInstanceProvider");
ProviderInfo providerInfo(className);
// Check for class provided by an internal provider
Boolean hasControlProvider = _lookupInternalProvider(
nameSpace,
className,
providerInfo);
// If no internal provider, try registered providers
if (!hasControlProvider)
{
CIMInstance pInstance;
CIMInstance pmInstance;
Boolean hasNoQuery = true;
Boolean hasProvider =
_providerRegistrationManager->lookupInstanceProvider(
nameSpace,
className,
pInstance,
pmInstance,
false,
&hasNoQuery);
if (hasProvider)
{
providerInfo.addProviderInfo(_providerManagerServiceId, true,
hasNoQuery);
ProviderIdContainer* pi = _updateProviderContainer(
nameSpace, pInstance, pmInstance);
providerInfo.providerIdContainer.reset(pi);
#ifdef PEGASUS_ENABLE_OBJECT_NORMALIZATION
if (ObjectNormalizer::getEnableNormalization())
{
// normalization is enabled for all providers unless they
// have an old interface version or are explicity excluded by
// the excludeModulesFromNormalization configuration option.
// check interface type and version
String interfaceType;
String interfaceVersion;
Uint32 pos = PEG_NOT_FOUND;
// get the provder interface type
if ((pos = pmInstance.findProperty("InterfaceType")) !=
PEG_NOT_FOUND)
{
pmInstance.getProperty(pos).getValue().get(interfaceType);
}
// get the provder interface version
if ((pos = pmInstance.findProperty("InterfaceVersion")) !=
PEG_NOT_FOUND)
{
pmInstance.getProperty(pos).
getValue().get(interfaceVersion);
}
// compare the interface type and vesion
if (String::equalNoCase(interfaceType, "C++Default"))
{
// version must be greater than 2.5.0
if (VersionUtil::isVersionGreaterOrEqual(
interfaceVersion, 2, 5, 0))
{
providerInfo.hasProviderNormalization = true;
}
}
else if (String::equalNoCase(interfaceType, "CMPI"))
{
// version must be greater than 2.0.0
if (VersionUtil::isVersionGreaterOrEqual(
interfaceVersion, 2, 0, 0))
{
providerInfo.hasProviderNormalization = true;
}
}
else if (String::equalNoCase(interfaceType, "JMPI"))
{
// version must be greater than 1.0.0
if (VersionUtil::isVersionGreaterOrEqual(
interfaceVersion, 1, 0, 0))
{
providerInfo.hasProviderNormalization = true;
}
}
// check for module exclusion
String moduleName;
// get the provider module name
if ((pos = pmInstance.findProperty(
PEGASUS_PROPERTYNAME_NAME)) != PEG_NOT_FOUND)
{
pmInstance.getProperty(pos).getValue().get(moduleName);
}
// check if module name is on excludeModulesFromNormalization
// list
for (Uint32 i = 0, n = _excludeModulesFromNormalization.size();
i < n; i++)
{
if (String::equalNoCase(
moduleName, _excludeModulesFromNormalization[i]))
{
providerInfo.hasProviderNormalization = false;
break;
}
}
PEG_TRACE((TRC_DISPATCHER,Tracer::LEVEL4,
"Normalization for provider module %s is %s.",
CSTRING(moduleName),
(providerInfo.hasProviderNormalization ?
"enabled" : "disabled")));
}
#endif
} // no provider or control provider
else
{
PEG_TRACE((TRC_DISPATCHER,Tracer::LEVEL2,
"Provider for %s not found.",
CSTRING(className.getString()) ));
}
}
PEG_TRACE((TRC_DISPATCHER, Tracer::LEVEL4,
"CIMOperationRequestDispatcher::_lookupInstanceProvider - "
"Namespace: %s Class Name: %s Service Name: %s "
"Provider Name: %s found. hasProvider = %s",
CSTRING(nameSpace.getString()),
CSTRING(className.getString()),
_getServiceName(providerInfo.serviceId),
CSTRING(providerInfo.controlProviderName),
(providerInfo.hasProvider ? "true" : "false")));
PEG_METHOD_EXIT();
return providerInfo;
}
/*
Lookup the method provider for the namespace, classname, and methodname
provided.
NOTE: Lookup of internal providers is handled by the method request handler
today. This should probably be fixed to provide exactly the
same lookup for all types in the future.
*/
String CIMOperationRequestDispatcher::_lookupMethodProvider(
const CIMNamespaceName& nameSpace,
const CIMName& className,
const CIMName& methodName,
ProviderIdContainer** providerIdContainer)
{
PEG_METHOD_ENTER(TRC_DISPATCHER,
"CIMOperationRequestDispatcher::_lookupMethodProvider");
CIMInstance pInstance;
CIMInstance pmInstance;
String providerName;
// lookup the provider. Returns provider instance and provider
// module instance.
if (_providerRegistrationManager->lookupMethodProvider(
nameSpace, className, methodName, pInstance, pmInstance))
{
(*providerIdContainer) = _updateProviderContainer(
nameSpace, pInstance, pmInstance);
// get the provder name
Uint32 pos = pInstance.findProperty(PEGASUS_PROPERTYNAME_NAME);
if (pos != PEG_NOT_FOUND)
{
pInstance.getProperty(pos).getValue().get(providerName);
}
}
// return providerName. Empty if method provider not found.
PEG_METHOD_EXIT();
return providerName;
}
/* _lookupAllAssociation Providers
Returns all of the association providers that exist for the defined class
name. Uses the referencenames function to get list of classes for which
providers required and then looks up the providers for each class
@param nameSpace
@param objectName
@param - assocClass referenced parameter that is modified in this function.
@param role String defining role for this association
@param providerCount count of actual providers found, not the count of
classes. This differs from the count of classes in that the providerInfo
list is all classes including those that would go to the repository.
@returns List of ProviderInfo
@exception - Exceptions From the Repository
*/
ProviderInfoList CIMOperationRequestDispatcher::_lookupAllAssociationProviders(
const CIMNamespaceName& nameSpace,
const CIMObjectPath& objectName,
const CIMName& assocClass,
const String& role)
{
PEG_METHOD_ENTER(TRC_DISPATCHER,
"CIMOperationRequestDispatcher::_lookupAllAssociationProviders");
ProviderInfoList providerInfoList;
CIMName className = objectName.getClassName();
PEG_TRACE((TRC_DISPATCHER, Tracer::LEVEL4,
"Association Class Lookup for Class %s and assocClass %s",
CSTRING(className.getString()),
CSTRING(assocClass.getString()) ));
// The association class is the basis for association registration.
// When an association class request is received by the CIMOM the target
// class is the endpoint class or instance. Prevously we also called
// providers registered against this class. Thus, typically this would
// be the same class as the instance class. For example ClassA with
// Assoc1. We would register an instance and Association provider
// against Class A. With this change, we register the Instance class
// as before, but register the association class with the association
// itself, i.e. register it against the class Assoc1.
// In this case, the list of potential classes for providers is the same
// as the reference names, i.e the association classes that have
// associations pointing back to the target class.
// ATTN: KS 20030515. After we test and complete the move to using this
// option, go back and change the call to avoid the double
// conversion to and from CIM Object path.
Array<CIMObjectPath> objPaths;
try
{
// Note: We use assocClass because this is the association function.
// The Reference(Name)s calls must put the resultClass here.
objPaths = _repository->referenceNames(
nameSpace,
CIMObjectPath(String::EMPTY, CIMNamespaceName(), className),
assocClass,
role);
}
catch (...)
{
PEG_TRACE((TRC_DISPATCHER, Tracer::LEVEL1,
"CIMOperationRequestDispatcher::lookupAllAssociationProvider "
"exception. Namespace: %s Object Name: %s Assoc Class: %s",
CSTRING(nameSpace.getString()),
CSTRING(objectName.toString()),
CSTRING(assocClass.getString())));
throw;
}
PEG_TRACE((TRC_DISPATCHER, Tracer::LEVEL4,
"Association Lookup: %u classes found", objPaths.size()));
// lookup association providers for all classes returned by the
// reference names lookup
for (Uint32 i = 0; i < objPaths.size(); i++)
{
CIMName cn = objPaths[i].getClassName();
// Create ProviderInfo object with default info and class name
ProviderInfo pi(cn);
// Use returned classname for the association classname
// under the assumption that the registration is for the
// association class, not the target class
if (_lookupAssociationProvider(nameSpace, cn, pi))
{
providerInfoList.appendProvider(pi);
PEG_TRACE((TRC_DISPATCHER, Tracer::LEVEL4,
"Association append: class = %s to list. count = %u",
CSTRING(objPaths[i].getClassName().getString()),
providerInfoList.size() ));
}
}
PEG_TRACE((TRC_DISPATCHER, Tracer::LEVEL3,
"Association providerCount = %u.", providerInfoList.providerCount));
PEG_METHOD_EXIT();
return providerInfoList;
}
/* _lookupAssociationProvider - Look up the internal and/or registered
association provider for the defined namespace and class and return a
providerInfo struct containing information about the provider if found.
@param nameSpace
@param assocClass
@param providerInfo ProviderInfo& container holding information about
the provider found including name, etc.
@return true if a provider is found for the defined class and namespace.
*/
Boolean CIMOperationRequestDispatcher::_lookupAssociationProvider(
const CIMNamespaceName& nameSpace,
const CIMName& assocClass,
ProviderInfo& providerInfo)
{
PEG_METHOD_ENTER(TRC_DISPATCHER,
"CIMOperationRequestDispatcher::_lookupAssociationProvider");
ProviderIdContainer* providerIdContainer=NULL;
String providerName;
// Check for class provided by an internal provider
if (!_lookupInternalProvider(nameSpace, assocClass, providerInfo))
{
// get provider for class from registered providers. Note that we
// reduce it from multiple possible class names to a single one here.
// This limit is defined by ProviderRegistrationManager in that
// it will only return one provider since we allow only a single
// provider for a class. (See bug 9581)
Array<String> assocProviderList =
_lookupRegisteredAssociationProvider(
nameSpace, assocClass, &providerIdContainer);
// Provider registration should NEVER return more than a single
// provider for this lookup by design of provider registration today.
if (assocProviderList.size() > 0)
{
providerInfo.addProviderInfo(_providerManagerServiceId,true,false);
providerName = assocProviderList[0];
}
}
// Fill out providerInfo providerIdContainer
if (providerInfo.hasProvider)
{
providerInfo.providerIdContainer.reset(providerIdContainer);
}
else
{
providerInfo.providerIdContainer.reset();
}
PEG_TRACE((TRC_DISPATCHER, Tracer::LEVEL4,
"Association Provider %s for class=\"%s\" in namespace \"%s\"."
" servicename=\"%s\" provider = \"%s\" controlProvider = \"%s\"",
(providerInfo.hasProvider? "found" : "NOT found"),
CSTRING(assocClass.getString()),
CSTRING(nameSpace.getString()),
_getServiceName(providerInfo.serviceId),
CSTRING(providerName),
CSTRING(providerInfo.controlProviderName) ));
PEG_METHOD_EXIT();
return providerInfo.hasProvider;
}
// Lookup the registered Association provider(s) for this class and convert
// the result to an array of provider names.
// NOTE: The code allows for multiple providers but there is no reason
// to have this until we really support multiple providers per class.
// The multiple provider code was here because there was some code in to
// do the lookup in provider registration which was removed. Some day we
// will support multiple providers per class so it was logical to just leave
// the multiple provider code in place.
// NOTE: assocClass and resultClass are optional
//
Array<String>
CIMOperationRequestDispatcher::_lookupRegisteredAssociationProvider(
const CIMNamespaceName& nameSpace,
const CIMName& assocClass,
ProviderIdContainer** providerIdContainer)
{
PEG_METHOD_ENTER(TRC_DISPATCHER,
"CIMOperationRequestDispatcher::_lookupRegisteredAssociationProvider");
// instances of the provider class and provider module class for the
// response
Array<CIMInstance> pInstances; // Providers
Array<CIMInstance> pmInstances; // ProviderModules
Array<String> providerNames;
String providerName;
//get list of registered association providers
Boolean returnValue =
_providerRegistrationManager->lookupAssociationProvider(
nameSpace, assocClass, pInstances, pmInstances);
if (returnValue)
{
for (Uint32 i = 0, n = pInstances.size(); i < n; i++)
{
// At present only one provider per class or per association is
// supported and the same provider is stored in the
// providerIdContainer. So the array will actually have only one
// item. And hence with the same element providerIdContainer will
// be created. When we start supporting multiple providers per
// class or assoc, we need to change the code to make
// providerIdContainer accordingly.
if (i == 0)
{
// Call function that depends on the Remote CMPI flag
// to update ProviderIdContainer
(*providerIdContainer) = _updateProviderContainer(
nameSpace, pInstances[i], pmInstances[i]);
}
// get the provider name
Uint32 pos = pInstances[i].findProperty(PEGASUS_PROPERTYNAME_NAME);
if ( pos != PEG_NOT_FOUND )
{
pInstances[i].getProperty(pos).getValue().get(providerName);
PEG_TRACE((TRC_DISPATCHER, Tracer::LEVEL4,
"Association providerName = %s found for Class %s",
CSTRING(providerName),
CSTRING(assocClass.getString())));
providerNames.append(providerName);
}
}
}
if (providerNames.size() == 0)
{
PEG_TRACE((TRC_DISPATCHER,Tracer::LEVEL3,
"Association Provider NOT found for Class %s in nameSpace %s",
CSTRING(assocClass.getString()), CSTRING(nameSpace.getString()) ));
}
PEG_METHOD_EXIT();
return providerNames;
}
// Service function to build the ProviderIdContainer.
// If remote CMPI enabled and if this is a remote namespace, it must
// place the remote info into the container. Otherwise it just builds
// a new container with pmInstance and pInstance and returns it
// NOTE: nameSpace is only used in the case of REMOTE_CMPI
ProviderIdContainer* CIMOperationRequestDispatcher::_updateProviderContainer(
const CIMNamespaceName& nameSpace,
const CIMInstance& pInstance,
const CIMInstance& pmInstance)
{
ProviderIdContainer* pc;
#ifdef PEGASUS_ENABLE_REMOTE_CMPI
String remoteInformation;
Boolean isRemote = false;
isRemote = _repository->isRemoteNameSpace(
nameSpace,
remoteInformation);
if (isRemote)
{
pc = new ProviderIdContainer(
pmInstance, pInstance, isRemote, remoteInformation);
}
else
{
pc = new ProviderIdContainer(pmInstance, pInstance);
}
#else
pc = new ProviderIdContainer(pmInstance, pInstance);
#endif
return pc;
}
/*****************************************************************************
**
** Dispatcher callback functions. These functions are called by the
** service/providerManager generating responses to return response information
** to the Dispatcher Response handlers. The reference to the correct handler
** is provided by the Dispatcher request handlers when requests are passed
** forward for services or provider managers, i.e. _forwardRequest* Functions)
**
******************************************************************************/
/* Dispatcher callback for response aggregation
The userParameter contains the OperationAggregate for this operation
*/
void CIMOperationRequestDispatcher::_forwardedForAggregationCallback(
AsyncOpNode* op,
MessageQueue* q,
void* userParameter)
{
PEG_METHOD_ENTER(TRC_DISPATCHER,
"CIMOperationRequestDispatcher::_forwardForAggregationCallback");
CIMOperationRequestDispatcher* service =
static_cast<CIMOperationRequestDispatcher*>(q);
AsyncRequest* asyncRequest = static_cast<AsyncRequest*>(op->getRequest());
AsyncReply* asyncReply = static_cast<AsyncReply*>(op->removeResponse());
OperationAggregate* poA =
reinterpret_cast<OperationAggregate*>(userParameter);
PEGASUS_ASSERT(asyncRequest != 0);
PEGASUS_ASSERT(asyncReply != 0);
PEGASUS_DEBUG_ASSERT(asyncReply->valid());
PEGASUS_DEBUG_ASSERT(asyncRequest->valid());
PEGASUS_ASSERT(poA != 0);
PEGASUS_DEBUG_ASSERT(poA->valid());
CIMResponseMessage* response = 0;
MessageType msgType = asyncReply->getType();
if (msgType == ASYNC_ASYNC_LEGACY_OP_RESULT)
{
response = reinterpret_cast<CIMResponseMessage*>(
(static_cast<AsyncLegacyOperationResult*>(asyncReply))->
get_result());
}
else if (msgType == ASYNC_ASYNC_MODULE_OP_RESULT)
{
response = reinterpret_cast<CIMResponseMessage*>(
(static_cast<AsyncModuleOperationResult*>(asyncReply))->
get_result());
}
else
{
// This should never happen.
PEGASUS_UNREACHABLE(PEGASUS_ASSERT(false);)
}
PEGASUS_ASSERT(response != 0);
PEGASUS_DEBUG_ASSERT(response->valid());
PEGASUS_ASSERT(response->messageId == poA->_messageId);
delete asyncReply;
// Before resequencing, the isComplete() flag represents the completion
// status of one provider's response, not the entire response
Boolean thisResponseIsComplete = response->isComplete();
if (thisResponseIsComplete)
{
// these are per provider instantiations
op->removeRequest();
delete asyncRequest;
service->return_op(op);
}
// KS_TODO this is a temporary diagnostic. Remove before release
if (poA->_pullOperation)
{
PEGASUS_DEBUG_ASSERT(poA->_enumerationContext);
}
// After resequencing, this flag represents the completion status of
// the ENTIRE response to the request.
// Call the response handler for aggregating responses
Boolean entireResponseIsComplete = service->_enqueueResponse(poA, response);
if (entireResponseIsComplete)
{
// delete OperationAggregation and attached request.
delete poA;
poA = 0;
}
// FUTURE Consider removing this trace in the future
PEG_TRACE((TRC_DISPATCHER, Tracer::LEVEL4,
"Provider thisResponse = %s. Entire response = %s",
(thisResponseIsComplete? "complete": "incomplete"),
(entireResponseIsComplete? "complete": "incomplete") ));
PEG_METHOD_EXIT();
}
/* Dispatcher Callback function for nonAggregation calls.
The userParameter contains the request message for this operation
*/
void CIMOperationRequestDispatcher::_forwardedRequestCallback(
AsyncOpNode* op,
MessageQueue* q,
void* userParameter)
{
PEG_METHOD_ENTER(TRC_DISPATCHER,
"CIMOperationRequestDispatcher::_forwardedRequestCallback");
CIMOperationRequestDispatcher* service =
static_cast<CIMOperationRequestDispatcher*>(q);
AsyncRequest* asyncRequest =
static_cast<AsyncRequest*>(op->removeRequest());
AsyncReply* asyncReply = static_cast<AsyncReply*>(op->removeResponse());
CIMOperationRequestMessage* request =
reinterpret_cast<CIMOperationRequestMessage*>(userParameter);
PEGASUS_ASSERT(request != 0);
CIMResponseMessage* response = 0;
PEGASUS_DEBUG_ASSERT(request->valid());
MessageType msgType = asyncReply->getType();
if (msgType == ASYNC_ASYNC_LEGACY_OP_RESULT)
{
response = reinterpret_cast<CIMResponseMessage*>(
(static_cast<AsyncLegacyOperationResult*>(asyncReply))->
get_result());
}
else if (msgType == ASYNC_ASYNC_MODULE_OP_RESULT)
{
response = reinterpret_cast<CIMResponseMessage*>(
(static_cast<AsyncModuleOperationResult*>(asyncReply))->
get_result());
}
else
{
// Error
}
PEGASUS_ASSERT(response != 0);
PEGASUS_DEBUG_ASSERT(response->valid());
Boolean isComplete = response->isComplete();
service->_enqueueResponse(request, response);
if (isComplete == true)
{
delete request;
delete asyncRequest;
delete asyncReply;
service->return_op(op);
}
PEG_METHOD_EXIT();
}
/***************************************************************************
**
** The _forwardRequest* functions forward CIMOperation Requests to
** other services for processing. Normally this will be either
** Control Providers, services, or Provider Managers
**
***************************************************************************/
/* Forward requests for response aggregation( enums, etc. that
call multiple providers) to other services (providerManager, etc).
(i.e. requests where the callback is the function
_forwardForAggregationCallback. These requests include an
OperationAggregate structure that controls response handling.
This function decides based on the controlProviderName Field
whether to forward to Service or ControlProvider.
If controlProviderName String empty, ToService, else toControlProvider.
If a response is provided with the input, the caller wants to execute only
the callback asychnonously but not call another service.
*/
void CIMOperationRequestDispatcher::_forwardRequestForAggregation(
Uint32 serviceId,
const String& controlProviderName,
CIMOperationRequestMessage* request,
OperationAggregate* poA,
CIMResponseMessage* response)
{
PEG_METHOD_ENTER(TRC_DISPATCHER,
"CIMOperationRequestDispatcher::_forwardRequestForAggregation");
PEGASUS_ASSERT(serviceId);
// create an AsyncOpNode
AsyncOpNode* op = this->get_op();
// if a response is provided, execute only the asynchronous callback,
// rather than forward to the provider.
if (response)
{
// constructor of object is putting itself into a linked list
// DO NOT remove the new operator
new AsyncLegacyOperationResult(op, response);
// Setting this to complete, allows ONLY the callback to run
// without going through the typical async request apparatus
op->complete();
}
// If ControlProviderName empty, forward to service.
if (controlProviderName.size() == 0)
{
// constructor of object is putting itself into a linked list
// DO NOT remove the new operator
new AsyncLegacyOperationStart(op,serviceId,request);
PEG_TRACE((TRC_DISPATCHER, Tracer::LEVEL3,
"Forwarding %s to service %s. Response should go to queue %s.",
MessageTypeToString(request->getType()),
_getServiceName(serviceId),
((MessageQueue::lookup(request->queueIds.top())) ?
((MessageQueue::lookup(request->queueIds.top()))->getQueueName()) :
"BAD queue name")));
}
else
{
// constructor of object is putting itself into a linked list
// DO NOT remove the new operator
new AsyncModuleOperationStart(
op,
serviceId,
controlProviderName,
request);
PEG_TRACE((TRC_DISPATCHER, Tracer::LEVEL3,
"Forwarding %s to service %s, control provider %s. "
"Response should go to queue %s.",
MessageTypeToString(request->getType()),
_getServiceName(serviceId),
CSTRING(controlProviderName),
((MessageQueue::lookup(request->queueIds.top())) ?
((MessageQueue::lookup(request->queueIds.top()))->getQueueName()) :
"BAD queue name")));
}
SendAsync(
op,
serviceId,
CIMOperationRequestDispatcher::_forwardedForAggregationCallback,
this,
poA);
PEG_METHOD_EXIT();
}
/** _forwardRequestToSingleProvider
This function forwards the request to a single provider,
control provider or service. It decides based on
the controlProviderName parameter whether to forward to
Service/controlProvider or to the provider manager service.
If controlProviderName String empty,
ForwardToProviderManagerService,
else
ForwardtoControlProvider/service
As part of that forwarding process in defines a callback
function, _forwardRequestCallback(...) for responses to the
request.
*/
void CIMOperationRequestDispatcher::_forwardRequestToSingleProvider(
const ProviderInfo& providerInfo,
CIMOperationRequestMessage* request,
CIMOperationRequestMessage* requestCopy)
{
PEG_METHOD_ENTER(TRC_DISPATCHER,
"CIMOperationRequestDispatcher::_forwardRequestToSingleProvider");
PEGASUS_ASSERT(providerInfo.serviceId);
AsyncOpNode* op = this->get_op();
// If ControlProviderName empty, forward to service defined on input
if (providerInfo.controlProviderName.size() == 0)
{
AsyncLegacyOperationStart* asyncRequest =
new AsyncLegacyOperationStart(
op,
providerInfo.serviceId,
request);
asyncRequest->dest = providerInfo.serviceId;
}
// control provider name exists.
else
{
// constructor of object is putting itself into a linked list
// DO NOT remove the new operator
new AsyncModuleOperationStart(
op,
providerInfo.serviceId,
providerInfo.controlProviderName,
request);
}
// Forward the request asynchronously with call back to
// _forwardedRequestCallback()
PEG_TRACE((TRC_DISPATCHER, Tracer::LEVEL3,
"Forwarding %s on class %s to service %s, control provider %s. "
"Response to queue %s.",
MessageTypeToString(request->getType()),
CSTRING(providerInfo.className.getString()),
_getServiceName(providerInfo.serviceId),
(CSTRING(providerInfo.controlProviderName)),
((MessageQueue::lookup(request->queueIds.top())) ?
((MessageQueue::lookup(request->queueIds.top()))->getQueueName()) :
"BAD queue name")));
SendAsync(
op,
providerInfo.serviceId,
CIMOperationRequestDispatcher::_forwardedRequestCallback,
this,
requestCopy);
PEG_METHOD_EXIT();
}
/*
Enqueue an Exception response
Helper functions that create a response message with the defined
exception and queues it.
*/
void CIMOperationRequestDispatcher::_enqueueExceptionResponse(
CIMOperationRequestMessage* request,
CIMException& exception)
{
CIMResponseMessage* response = request->buildResponse();
response->cimException = exception;
_enqueueResponse(request, response);
}
void CIMOperationRequestDispatcher::_enqueueExceptionResponse(
CIMOperationRequestMessage* request,
TraceableCIMException& exception)
{
CIMResponseMessage* response = request->buildResponse();
response->cimException = exception;
_enqueueResponse(request, response);
}
void CIMOperationRequestDispatcher::_enqueueExceptionResponse(
CIMOperationRequestMessage* request,
CIMStatusCode code,
const String& ExtraInfo)
{
CIMException exception = PEGASUS_CIM_EXCEPTION(code, ExtraInfo);
_enqueueExceptionResponse(request, exception);
}
/*
Enqueue the response provided with the call to destination defined
by request.
Logs this operation, assures resquest and response
attributes are syncd, gets queue from request,
gets queue name from request,
if internal client (queuename) does
base::_enqueueResponse(request,response)
else
calls queue->enqueue(response)
*/
void CIMOperationRequestDispatcher::_enqueueResponse(
CIMOperationRequestMessage* request,
CIMResponseMessage* response)
{
PEG_METHOD_ENTER(TRC_DISPATCHER,
"CIMOperationRequestDispatcher::_enqueueResponse");
response->dest = request->queueIds.top();
// Ensure the response message attributes are synchonized with the request
PEGASUS_ASSERT(request->getMask() == response->getMask());
PEGASUS_ASSERT(request->getHttpMethod() == response->getHttpMethod());
PEGASUS_ASSERT(request->getCloseConnect() == response->getCloseConnect());
PEG_TRACE((TRC_HTTP, Tracer::LEVEL4,
"_CIMOperationRequestDispatcher::_enqueueResponse - "
"request->getCloseConnect() returned %d",
request->getCloseConnect()));
_logOperation(request, response);
// Internal client does not have async capabilities, call enqueue()
// for handling legacy messages directly.
MessageQueue* queue = MessageQueue::lookup(request->queueIds.top());
PEGASUS_ASSERT(queue != 0);
queue->enqueue(response);
PEG_METHOD_EXIT();
}
/*
handleEnqueue is the Request input processor to the Dispatcher.
It processes all incoming request messages and distributes them to
the appropriate request handler functions based on the operation type.
This function includes
a common exception try/catch to account for exceptions in any of the
individual operation request handlers. The function deletes the
incoming request upon completion of the handler execution.
*/
void CIMOperationRequestDispatcher::handleEnqueue(Message* request)
{
PEG_METHOD_ENTER(TRC_DISPATCHER,
"CIMOperationRequestDispatcher::handleEnqueue(Message* request)");
PEGASUS_ASSERT(request != 0);
PEGASUS_DEBUG_ASSERT(request->valid());
PEG_TRACE(( TRC_DISPATCHER, Tracer::LEVEL3,
"CIMOperationRequestDispatcher::handleEnqueue - MsgType: %u",
request->getType() ));
CIMOperationRequestMessage* opRequest =
dynamic_cast<CIMOperationRequestMessage*>(request);
if (!opRequest)
{
PEG_TRACE(( TRC_DISCARDED_DATA, Tracer::LEVEL2,
"Ignored unexpected message of type %u in "
"CIMOperationRequestDispatcher::handleEnqueue",
request->getType() ));
delete request;
PEG_METHOD_EXIT();
return;
}
//
// This try/catch block ensures that any exception raised during the
// processing of an operation is handled and translated into an operation
// response.
//
CIMException cimException;
// Flag to indicate that we should delete request when handler
// complete
bool del = true;
try
{
// Set the client's requested language into this service thread.
// This will allow functions in this service to return messages
// in the correct language.
opRequest->updateThreadLanguages();
switch (opRequest->getType())
{
case CIM_GET_CLASS_REQUEST_MESSAGE:
handleGetClassRequest((CIMGetClassRequestMessage*)opRequest);
break;
case CIM_GET_INSTANCE_REQUEST_MESSAGE:
handleGetInstanceRequest((CIMGetInstanceRequestMessage*)opRequest);
break;
case CIM_DELETE_CLASS_REQUEST_MESSAGE:
handleDeleteClassRequest(
(CIMDeleteClassRequestMessage*)opRequest);
break;
case CIM_DELETE_INSTANCE_REQUEST_MESSAGE:
handleDeleteInstanceRequest(
(CIMDeleteInstanceRequestMessage*)opRequest);
break;
case CIM_CREATE_CLASS_REQUEST_MESSAGE:
handleCreateClassRequest((CIMCreateClassRequestMessage*)opRequest);
break;
case CIM_CREATE_INSTANCE_REQUEST_MESSAGE:
handleCreateInstanceRequest(
(CIMCreateInstanceRequestMessage*)opRequest);
break;
case CIM_MODIFY_CLASS_REQUEST_MESSAGE:
handleModifyClassRequest((CIMModifyClassRequestMessage*)opRequest);
break;
case CIM_MODIFY_INSTANCE_REQUEST_MESSAGE:
handleModifyInstanceRequest(
(CIMModifyInstanceRequestMessage*)opRequest);
break;
case CIM_ENUMERATE_CLASSES_REQUEST_MESSAGE:
handleEnumerateClassesRequest(
(CIMEnumerateClassesRequestMessage*)opRequest);
break;
case CIM_ENUMERATE_CLASS_NAMES_REQUEST_MESSAGE:
handleEnumerateClassNamesRequest(
(CIMEnumerateClassNamesRequestMessage*)opRequest);
break;
case CIM_ENUMERATE_INSTANCES_REQUEST_MESSAGE:
handleEnumerateInstancesRequest(
(CIMEnumerateInstancesRequestMessage*)opRequest);
break;
case CIM_ENUMERATE_INSTANCE_NAMES_REQUEST_MESSAGE:
handleEnumerateInstanceNamesRequest(
(CIMEnumerateInstanceNamesRequestMessage*)opRequest);
break;
case CIM_EXEC_QUERY_REQUEST_MESSAGE:
handleExecQueryRequest(
(CIMExecQueryRequestMessage*)opRequest);
break;
case CIM_ASSOCIATORS_REQUEST_MESSAGE:
handleAssociatorsRequest((CIMAssociatorsRequestMessage*)opRequest);
break;
case CIM_ASSOCIATOR_NAMES_REQUEST_MESSAGE:
handleAssociatorNamesRequest(
(CIMAssociatorNamesRequestMessage*)opRequest);
break;
case CIM_REFERENCES_REQUEST_MESSAGE:
handleReferencesRequest((CIMReferencesRequestMessage*)opRequest);
break;
case CIM_REFERENCE_NAMES_REQUEST_MESSAGE:
handleReferenceNamesRequest(
(CIMReferenceNamesRequestMessage*)opRequest);
break;
case CIM_GET_PROPERTY_REQUEST_MESSAGE:
handleGetPropertyRequest(
(CIMGetPropertyRequestMessage*)opRequest);
break;
case CIM_SET_PROPERTY_REQUEST_MESSAGE:
handleSetPropertyRequest(
(CIMSetPropertyRequestMessage*)opRequest);
break;
case CIM_GET_QUALIFIER_REQUEST_MESSAGE:
handleGetQualifierRequest(
(CIMGetQualifierRequestMessage*)opRequest);
break;
case CIM_SET_QUALIFIER_REQUEST_MESSAGE:
handleSetQualifierRequest(
(CIMSetQualifierRequestMessage*)opRequest);
break;
case CIM_DELETE_QUALIFIER_REQUEST_MESSAGE:
handleDeleteQualifierRequest(
(CIMDeleteQualifierRequestMessage*)opRequest);
break;
case CIM_ENUMERATE_QUALIFIERS_REQUEST_MESSAGE:
handleEnumerateQualifiersRequest(
(CIMEnumerateQualifiersRequestMessage*)opRequest);
break;
case CIM_INVOKE_METHOD_REQUEST_MESSAGE:
handleInvokeMethodRequest(
(CIMInvokeMethodRequestMessage*)opRequest);
break;
// KS_PULL_BEGIN
case CIM_OPEN_ENUMERATE_INSTANCES_REQUEST_MESSAGE:
del = handleOpenEnumerateInstancesRequest(
(CIMOpenEnumerateInstancesRequestMessage*)opRequest);
break;
case CIM_OPEN_ENUMERATE_INSTANCE_PATHS_REQUEST_MESSAGE:
del = handleOpenEnumerateInstancePathsRequest(
(CIMOpenEnumerateInstancePathsRequestMessage*)opRequest);
break;
case CIM_OPEN_REFERENCE_INSTANCES_REQUEST_MESSAGE:
del = handleOpenReferenceInstancesRequest(
(CIMOpenReferenceInstancesRequestMessage*)opRequest);
break;
case CIM_OPEN_REFERENCE_INSTANCE_PATHS_REQUEST_MESSAGE:
del = handleOpenReferenceInstancePathsRequest(
(CIMOpenReferenceInstancePathsRequestMessage*)opRequest);
break;
case CIM_OPEN_ASSOCIATOR_INSTANCES_REQUEST_MESSAGE:
del = handleOpenAssociatorInstancesRequest(
(CIMOpenAssociatorInstancesRequestMessage*)opRequest);
break;
case CIM_OPEN_ASSOCIATOR_INSTANCE_PATHS_REQUEST_MESSAGE:
del = handleOpenAssociatorInstancePathsRequest(
(CIMOpenAssociatorInstancePathsRequestMessage*)opRequest);
break;
case CIM_PULL_INSTANCES_WITH_PATH_REQUEST_MESSAGE:
del = handlePullInstancesWithPath(
(CIMPullInstancesWithPathRequestMessage*) opRequest);
break;
case CIM_PULL_INSTANCE_PATHS_REQUEST_MESSAGE:
del = handlePullInstancePaths(
(CIMPullInstancePathsRequestMessage*) opRequest);
break;
case CIM_PULL_INSTANCES_REQUEST_MESSAGE:
del = handlePullInstances(
(CIMPullInstancesRequestMessage*) opRequest);
break;
case CIM_CLOSE_ENUMERATION_REQUEST_MESSAGE:
handleCloseEnumeration(
(CIMCloseEnumerationRequestMessage*) opRequest);
break;
case CIM_ENUMERATION_COUNT_REQUEST_MESSAGE:
handleEnumerationCount(
(CIMEnumerationCountRequestMessage*) opRequest);
break;
case CIM_OPEN_QUERY_INSTANCES_REQUEST_MESSAGE:
del = handleOpenQueryInstancesRequest(
(CIMOpenQueryInstancesRequestMessage*)opRequest);
break;
//KS_PULL_END
default:
PEGASUS_UNREACHABLE(PEGASUS_ASSERT(0);)
}
}
catch (const CIMException& exception)
{
cimException = exception;
}
catch (const Exception& exception)
{
cimException =
PEGASUS_CIM_EXCEPTION(CIM_ERR_FAILED, exception.getMessage());
}
catch (...)
{
cimException = PEGASUS_CIM_EXCEPTION(CIM_ERR_FAILED, String::EMPTY);
}
if (cimException.getCode() != CIM_ERR_SUCCESS)
{
AutoPtr<CIMResponseMessage> response(opRequest->buildResponse());
response->cimException = cimException;
_enqueueResponse(opRequest, response.release());
}
if (del)
{
delete request;
}
PEG_METHOD_EXIT();
}
/*
CIMOperationDispatcher dequeue function to dequeue the
next input operation request and send to the handle functions.
*/
void CIMOperationRequestDispatcher::handleEnqueue()
{
PEG_METHOD_ENTER(TRC_DISPATCHER,
"CIMOperationRequestDispatcher::handleEnqueue");
Message* request = dequeue();
PEGASUS_DEBUG_ASSERT(request->valid());
if (request)
{
handleEnqueue(request);
}
PEG_METHOD_EXIT();
}
/****************************************************************************
**
** Request Input Parameter Test and reject functions
** Each function tests a particular possible reason for reject.
** If the test fails, the reject message is generated and
** a true response returned. If the test passes, true returned.
** Generally named with the prefix reject to indicate that they
** reject and return true.
** Each function should terminate the operation processing if true
** is returned.
**
****************************************************************************/
// Test to determine if Association traversal is enabled.
// returns true if Not Enabled, false if enabled
Boolean CIMOperationRequestDispatcher::_rejectAssociationTraversalDisabled(
CIMOperationRequestMessage* request,
const String& opName)
{
if (_enableAssociationTraversal)
{
// return when AssociationTraversal is enabled
return false;
}
else
{
//// FUTURE add explicit international message. Low priority because
//// this almost never happens. The name must be illegal, not just
//// missing from target.
_enqueueExceptionResponse(request,CIM_ERR_NOT_SUPPORTED, opName);
return true;
}
}
/* Test the roleParameter to determine if it exists and is a valid CIMName.
Generate error if it exists and is not a valid CIMName.
@return true if invalid and false if valid
*/
Boolean CIMOperationRequestDispatcher::_rejectInvalidRoleParameter(
CIMOperationRequestMessage* request,
const String& roleParameter,
const String& parameterName)
{
if (roleParameter.size() != 0 && (!CIMName::legal(roleParameter)))
{
//KS_TODO internationalize This
String text = parameterName + " " + roleParameter;
_enqueueExceptionResponse(request,
CIM_ERR_INVALID_PARAMETER, text);
return true;
}
return false;
}
// _rejectEnumerateTooBroad. Checks providerCount against parameter. Generates
// exception of providerCount to large.
// This limits the number of provider invocations, not the number
// of instances returned. It throws exception because request not available
// in function where called.
void CIMOperationRequestDispatcher::_rejectEnumerateTooBroad(
const CIMNamespaceName& nameSpace,
const CIMName& className,
Uint32 providerCount)
{
if (providerCount > _maximumEnumerateBreadth)
{
PEG_TRACE((TRC_DISPATCHER, Tracer::LEVEL1,
"Operation too broad for class %s. "
" Namespace: %s Limit = %u, providerCount = %u",
CSTRING(className.getString()),
CSTRING(nameSpace.getString()),
_maximumEnumerateBreadth,
providerCount));
throw PEGASUS_CIM_EXCEPTION_L(CIM_ERR_NOT_SUPPORTED,
MessageLoaderParms(
"Server.CIMOperationRequestDispatcher.ENUM_REQ_TOO_BROAD",
"Enumerate request too Broad"));
}
}
Boolean CIMOperationRequestDispatcher::_CIMExceptionIfNoProvidersOrRepository(
CIMOperationRequestMessage* request,
const ProviderInfoList& providerInfos,
CIMException& cimException)
{
if ((providerInfos.providerCount == 0) &&
!(_repository->isDefaultInstanceProvider()))
{
cimException = PEGASUS_CIM_EXCEPTION_L(
CIM_ERR_NOT_SUPPORTED, MessageLoaderParms(
"Server.CIMOperationRequestDispatcher."
"REQUEST_CLASS_NOT_SUPPORTED",
"No provider or repository defined for class $0.",
request->className.getString()));
return true;
}
else // We have either providers or a repository
{
return false;
}
}
Boolean CIMOperationRequestDispatcher::_rejectNoProvidersOrRepository(
CIMOperationRequestMessage* request,
const ProviderInfoList& providerInfos)
{
if ((providerInfos.providerCount == 0) &&
!(_repository->isDefaultInstanceProvider()))
{
CIMException cimException = PEGASUS_CIM_EXCEPTION_L(
CIM_ERR_NOT_SUPPORTED, MessageLoaderParms(
"Server.CIMOperationRequestDispatcher."
"REQUEST_CLASS_NOT_SUPPORTED",
"No provider or repository defined for class $0.",
request->className.getString()));
_enqueueExceptionResponse(request, cimException);
return true;
}
else // We have either providers or a repository
{
return false;
}
}
// FUTURE(KS) - We have two apparently parallel class parameter checks
// One generates response, etc (_checkClassParameter) the other
// returns and has the user generate the error response. Mostly these
// are generated with a throw. Should reduce this to one function that
// is clean and uses minimum space. Also they generate different set
// of traces and we need common base for traces.
/*
Test the validity of the class name parameter and get the corresponding
class. Returns the class if found. If not found, returns with return
code false.
@param request. NOTE: This depends on the namespace and class in
the CIMOperationRequestMessage request.
@param cimClass CIMConstClass containing the requested class if the
class exists.
@return false if class found or true if class not found
*/
Boolean CIMOperationRequestDispatcher::_rejectInvalidClassParameter(
CIMOperationRequestMessage* request,
CIMConstClass& targetClass)
{
CIMException checkClassException;
targetClass = _getClass(
request->nameSpace,
request->className,
checkClassException);
if (checkClassException.getCode() != CIM_ERR_SUCCESS)
{
PEG_TRACE((TRC_DISPATCHER, Tracer::LEVEL1,
"CIMOperationRequestDispatcher - "
"CIM class exist exception has occurred. Namespace: %s "
"Class Name: %s Exception message: \"%s\"",
CSTRING(request->nameSpace.getString()),
CSTRING(request->className.getString()),
CSTRING(checkClassException.getMessage())));
_enqueueExceptionResponse(request,checkClassException);
return true;
}
return false;
}
/*
Test the validity of the class name parameter and get the corresponding
class. If not found, generates exception INVALID_PARAMETER response
and returns true.
@param request
@param objectName which contains target className
@param namespace CIMNamespaceName for this operation
@return false if class found or true if class not found
*/
Boolean CIMOperationRequestDispatcher::_rejectInvalidClassParameter(
CIMOperationRequestMessage* request,
const CIMNamespaceName& nameSpace,
const CIMObjectPath& objectName)
{
if (!_checkExistenceOfClass(nameSpace, objectName.getClassName()))
{
_enqueueExceptionResponse(request,
CIM_ERR_INVALID_PARAMETER,
objectName.getClassName().getString());
return true;
}
return false;
}
/* Build a property list of the properties in the class provided as an
argument.
@param class CIMClass with the properties to be put in list
@return propertyList containing the properties in the class.
*/
void _buildPropertyListFromClass(CIMConstClass& thisClass,
CIMPropertyList& propertyList)
{
Array<String> pla;
Uint32 numProperties = thisClass.getPropertyCount();
for (Uint32 i = 0; i < numProperties; i++)
{
pla.append(thisClass.getProperty(i).getName().getString());
}
propertyList.append(pla);
}
//EXP_PULL_BEGIN
// Test of the common input parameters for CIMOpen... messages.
// tests filter, filterLanguage, continueOnError, MaxObjectCount
// and Operation timeout
bool CIMOperationRequestDispatcher::_rejectIfPullParametersFailTests(
CIMOpenOperationRequestMessage* request,
Uint32& operationMaxObjectCount,
Boolean allowQueryFilter)
{
if (_rejectInvalidFilterParameters(request,
request->filterQueryLanguage,
request->filterQuery,
allowQueryFilter))
{
return true;
}
if (_rejectIfContinueOnError(request, request->continueOnError))
{
return true;
}
if (_rejectInvalidMaxObjectCountParam(request, request->maxObjectCount,
false, operationMaxObjectCount, Uint32(0)))
{
return true;
}
// Test for valid values in OperationTimeout
if (_rejectInvalidOperationTimeout(request, request->operationTimeout))
{
return true ;
}
return false;
}
/*
Test if this is a valid Pull message corresponding to the type
of the open. If not valid, put out error message and return false
@param request
@param valid Boolean = true if it is valid
Return true if !valid, false if valid
*/
bool CIMOperationRequestDispatcher::_rejectInvalidPullRequest(
CIMOperationRequestMessage* request, Boolean valid)
{
if (!valid)
{
CIMResponseMessage* response = request->buildResponse();
response->cimException = PEGASUS_CIM_EXCEPTION_L(
CIM_ERR_FAILED, MessageLoaderParms(
"Server.CIMOperationRequestDispatcher."
"PULL_OPERATION_TYPE_ERR",
"Open and Pull Message types do not match."));
_enqueueResponse(request, response);
}
return !valid;
}
/* Test to assure that the filter query language amd filter query are as
required. At this point, Pegasus refuses any data in these parameters in
accord with DSP0200 version 1.3. This will change when the spec and
Pegasus support these parameters.
*/
bool CIMOperationRequestDispatcher::_rejectInvalidFilterParameters(
CIMOperationRequestMessage* request,
const String& filterQueryLanguageParam,
const String& filterQueryParam,
Boolean allowQueryFilter)
{
CIMResponseMessage* response = NULL;
if (filterQueryLanguageParam.size() != 0 &&
filterQueryParam.size() == 0)
{
response = request->buildResponse();
response->cimException = PEGASUS_CIM_EXCEPTION_L(
CIM_ERR_FAILED,MessageLoaderParms(
"Server.CIMOperationRequestDispatcher."
"MISSING_FILTER_QUERY",
"filterQueryLanguage parameter without filterQuery parameter"));
}
else if (filterQueryLanguageParam.size() == 0 &&
filterQueryParam.size() != 0)
{
response = request->buildResponse();
response->cimException = PEGASUS_CIM_EXCEPTION_L(
CIM_ERR_FAILED, MessageLoaderParms(
"Server.CIMOperationRequestDispatcher."
"MISSING__FILTER_QUERY_LANGUAGE",
"filterQuery parameter without filterQueryLanguage parameter"));
}
else if(filterQueryLanguageParam.size() != 0 ||
filterQueryParam.size() != 0)
{
if (!allowQueryFilter)
{
//// KS_TODO internationalize
response = request->buildResponse();
response->cimException =
PEGASUS_CIM_EXCEPTION(
CIM_ERR_FILTERED_ENUMERATION_NOT_SUPPORTED,
"Operation does not support FilterQuery parameters");
}
}
if (response != NULL)
{
_enqueueResponse(request, response);
return true;
}
return false;
}
/* Test to assure that the CIMObjectPath is, in fact, an object path
and not just a classname. Return CIM_ERR_INVALID_PARAMETER if not
valid. The ObjecPath must be a full instance name to assure that we
do not try to follow the path for class based operations.
*/
bool CIMOperationRequestDispatcher::_rejectInvalidObjectPathParameter(
CIMOperationRequestMessage* request,
const CIMObjectPath& path)
{
if (path.getKeyBindings().size() == 0)
{
CIMResponseMessage* response = request->buildResponse();
response->cimException = PEGASUS_CIM_EXCEPTION_L(
CIM_ERR_INVALID_PARAMETER, MessageLoaderParms(
"Server.CIMOperationRequestDispatcher."
"INVALID_MODEL_PATH",
"Full Model Path with keys required."));
_enqueueResponse(request, response);
return true;
}
return false;
}
//
// Pegasus does not allow continueOnError parameter. Return Error
// if it exists.
//
bool CIMOperationRequestDispatcher::_rejectIfContinueOnError(
CIMOperationRequestMessage* request,
Boolean continueOnError)
{
if (continueOnError)
{
CIMResponseMessage* response = request->buildResponse();
response->cimException = PEGASUS_CIM_EXCEPTION_L(
CIM_ERR_NOT_SUPPORTED, MessageLoaderParms(
"Server.CIMOperationRequestDispatcher."
"CONTINUE_ON_ERROR_NOT_SUPPORTED",
"ContinueOnError = true argument not supported."));
_enqueueResponse(request, response);
return true;
}
return false;
}
// test and set maxObjectCount for this operation.
// If parameter is required, generate exception if parameter is NULL or
// test for within system max limit if exists.
// MaxObjectCount is optional for all open operations. If not
// supplied, set value = 0. Pegasus allows a systemwide
// maximum to be set. Since this is only used within
// the operation handler the result is a local function.
// Return an Exception only if the value is outside max limit.
//
// If parameter is optional, set to defaultValue if does not exist or
// test against system max limit if exists.
// @param request The operation request packet.
// @param maxObjectCount - the input parameter from the request packet
// @param requiredParameter Boolean true if parameter required
// for this operation. This is because it is optional on opens but
// required on pull operations
// @param value Value to be used if operation returns true;
// @param defaultValue Uint32 value to be used if requiredParameter = false
// and maxObjectCountParam is NULL
// @return - Returns true if parameter OK for this operation or false if
// if fails test. If true, the value to be used for maxObjectCount for
// this operation is placed in rtnValue. If false return, rtnValue is
// not changed.
// KS_TODO - We duplicate default value and _systemMaxPullOperationObjectCount
bool CIMOperationRequestDispatcher::_rejectInvalidMaxObjectCountParam(
CIMOperationRequestMessage* request,
Uint32 maxObjectCountParam,
bool requiredParameter,
Uint32& rtnValue,
const Uint32 defaultValue)
{
if (maxObjectCountParam > _systemPullOperationMaxObjectCount)
{
CIMException x = PEGASUS_CIM_EXCEPTION_L(
CIM_ERR_INVALID_PARAMETER, MessageLoaderParms(
"Server.CIMOperationRequestDispatcher."
"MAXOBJECTCOUNT_OUT_OF_RANGE",
"Operation maximum object count argument $0 too large."
" Maximum allowed: $1.",
maxObjectCountParam,
_systemPullOperationMaxObjectCount));
_enqueueExceptionResponse(request, x);
return true;
}
else
{
rtnValue = maxObjectCountParam;
}
return false;
}
// Test validity of operation timeout parameter.
// If the input value is NULL, we use our own value.
// If the value is gt system parameter we reject.
// If the value is 0 we follow the dictates of a parameter that defines
// this decision. Some systems implementations may allow this value. Others
// may elect to reject 0 (which means no timeout).
bool CIMOperationRequestDispatcher::_rejectInvalidOperationTimeout(
CIMOperationRequestMessage* request,
const Uint32Arg& operationTimeout)
{
// NULL is allowed. The EnumerationContext creation will determine
// the limit during creation based on system default. See
// EnumerationContextTable class
if (operationTimeout.isNull())
{
return false;
}
// If system does not allow zero value, send error.
if (operationTimeout.getValue() == 0)
{
if (_rejectZeroOperationTimeoutValue)
{
CIMResponseMessage* response = request->buildResponse();
response->cimException = PEGASUS_CIM_EXCEPTION_L(
CIM_ERR_INVALID_OPERATION_TIMEOUT, MessageLoaderParms(
"Server.CIMOperationRequestDispatcher."
"TIMEOUT_ZERO_NOT_ALLOWED",
"Operation timeout value of 0 not allowed."));
_enqueueResponse(request, response);
return true;
}
else
{
return false;
}
}
// If the value is greater than the system allowed max, send error
// response
if (operationTimeout.getValue() > _pullOperationMaxTimeout)
{
CIMResponseMessage* response = request->buildResponse();
response->cimException = PEGASUS_CIM_EXCEPTION_L(
CIM_ERR_INVALID_OPERATION_TIMEOUT, MessageLoaderParms(
"Server.CIMOperationRequestDispatcher."
"ENUMERATION_TIMEOUT_TO_LARGE",
"Operation timeout too large. Maximum allowed: $0.",
_pullOperationMaxTimeout));
_enqueueResponse(request, response);
return true;
}
return false;
}
/* Generate error response message if context is invalid.
@param valid Boolean = true if valid
@return true if valid=true, false if valid=false.
*/
bool CIMOperationRequestDispatcher::_rejectInvalidEnumerationContext(
CIMOperationRequestMessage* request,
EnumerationContext* en)
{
if (en == 0)
{
PEG_TRACE((TRC_DISPATCHER, Tracer::LEVEL4,
"%s Invalid Context parameter Received",
MessageTypeToString(request->getType()) ));
CIMResponseMessage* response = request->buildResponse();
response->cimException = PEGASUS_CIM_EXCEPTION_L(
CIM_ERR_INVALID_ENUMERATION_CONTEXT, MessageLoaderParms(
"Server.CIMOperationRequestDispatcher."
"ENUMERATION_CONTEXT_UNDEFINED",
"Context undefined."));
_enqueueResponse(request, response);
return true;
}
if (en->isClientClosed())
{
PEG_TRACE((TRC_DISPATCHER, Tracer::LEVEL4,
"%s Enumeration context already closed",
MessageTypeToString(request->getType()) ));
CIMResponseMessage* response = request->buildResponse();
response->cimException = PEGASUS_CIM_EXCEPTION_L(
CIM_ERR_INVALID_ENUMERATION_CONTEXT, MessageLoaderParms(
"Server.CIMOperationRequestDispatcher."
"ENUMERATION_CONTEXT_CLOSED",
"Enumeration context closed when request received."));
_enqueueResponse(request, response);
return true;
}
return false;
}
/* test if the parameter isTimedOut is true, If true an exception
return is queued amd true is returned
@param request - pointer to request
@isTimedOut - Boolean = true if timeout has occurred
@return true if timed out.
*/
bool CIMOperationRequestDispatcher::_rejectIfContextTimedOut(
CIMOperationRequestMessage* request,
Boolean isTimedOut)
{
if (isTimedOut)
{
CIMResponseMessage* response = request->buildResponse();
response->cimException = PEGASUS_CIM_EXCEPTION_L(
CIM_ERR_INVALID_ENUMERATION_CONTEXT, MessageLoaderParms(
"Server.CIMOperationRequestDispatcher."
"ENUMERATION_CONTEXT_TIMED_OUT",
"Enumeration Context timed out before request received."));
_enqueueResponse(request, response);
return true;
}
return false;
}
bool CIMOperationRequestDispatcher::_rejectIfEnumerationContextProcessing(
CIMOperationRequestMessage* request, Boolean processing)
{
if (processing)
{
CIMResponseMessage* response = request->buildResponse();
//// KS_TODO This may be wrong error message.
//// KS_TODO Internationalize
response->cimException = PEGASUS_CIM_EXCEPTION(
CIM_ERR_PULL_CANNOT_BE_ABANDONED,
"Server processing another request for this"
" Enumeration Context.");
_enqueueResponse(request, response);
}
return processing;
}
void CIMOperationRequestDispatcher::_rejectCreateContextFailed(
CIMOperationRequestMessage* request)
{
CIMResponseMessage* response = request->buildResponse();
response->cimException = PEGASUS_CIM_EXCEPTION_L(
CIM_ERR_SERVER_LIMITS_EXCEEDED, MessageLoaderParms(
"Server.CIMOperationRequestDispatcher."
"ENUMERATION_CONTEXT_EXCEEDED_LIMIT",
"Exceeded maximum number of simultaneous open Enumerations."));
_enqueueResponse(request, response);
}
// EXP_PULL_END
/*****************************************************************************
**
** Request Processing Helper Methods
**
*****************************************************************************/
/*
Helper struct/methods to issue operations requests to groups of Providers
defined by a ProviderInfoList. This struct issues requests of the type
defined by input to the providers defined in the providerInfoList.
There are separate functions for issuing:
issueEnumRequests - enumerate operations (enumerate and enumerateNames)
issueAssocRequests - association operations (includes references
and associations and their corresponding name operations).
This struct eliminates the repeated code for issuing requests in the
handle***Request functions for those input operation requests that issue
provider operation requests to multiple providers based on a
ProviderInfoList. It reduces the previously repeated code for issuing
requests to providers in the operation request processors for these
functions to a single line.
*/
/* This struct not part of CIMOperationRequestDispatcher class because it
includes template methods.
*/
struct ProviderRequests
{
// Set specific fields as part of the request type. These are required
// because we set different fields in the request message for each
// operation type with the class for the defined provider.
// References use the result class and Association requests, the
// assocClass field.
static void setSelectedRequestFields(
CIMAssociatorsRequestMessage* request,
const ProviderInfo& providerInfo)
{
request->assocClass = providerInfo.className;
}
static void setSelectedRequestFields(
CIMAssociatorNamesRequestMessage* request,
const ProviderInfo& providerInfo)
{
request->assocClass = providerInfo.className;
}
static void setSelectedRequestFields(
CIMReferencesRequestMessage* request,
const ProviderInfo& providerInfo)
{
request->resultClass = providerInfo.className;
}
static void setSelectedRequestFields(
CIMReferenceNamesRequestMessage* request,
const ProviderInfo& providerInfo)
{
request->resultClass = providerInfo.className;
}
// Set the appropriate data into the CIMResponseData container of the
// response message. This is used with the open handlers
// to set the response data into the repository response messages
// because some messages have paths and others objects.
static void setCIMResponseData(
CIMAssociatorsResponseMessage* response,
Array<CIMObject>& repositoryData)
{
response->getResponseData().setObjects(repositoryData);
}
static void setCIMResponseData(
CIMAssociatorNamesResponseMessage* response,
Array<CIMObjectPath>& repositoryData)
{
response->getResponseData().setInstanceNames(repositoryData);;
}
static void setCIMResponseData(
CIMReferencesResponseMessage* response,
Array<CIMObject>& repositoryData)
{
response->getResponseData().setObjects(repositoryData);;
}
static void setCIMResponseData(
CIMReferenceNamesResponseMessage* response,
Array<CIMObjectPath>& repositoryData)
{
response->getResponseData().setInstanceNames(repositoryData);;
}
/**************************************************************************
**
** issueAssocRequestsToProviders - Template method to issue requests for
** association/refernece operations.
**
**************************************************************************/
/* Template method to issue requests for association/reference
operations. The function issues requests of the type defined for
the template to the providers in the ProviderInfoList. It also
execute common code for this set of request types.
NOTE: The response may already have data in it from a repository
request.
*/
template<class REQ, class RSP>
static void issueAssocRequestsToProviders(
CIMOperationRequestDispatcher* dispatcher,
REQ* request,
AutoPtr<RSP>& response,
ProviderInfoList& providerInfos,
const char * reqMsgName)
{
// No providers and nothing from repository. Return empty
if ((providerInfos.providerCount == 0) && (response.get() == 0))
{
PEG_TRACE((TRC_DISPATCHER, Tracer::LEVEL1,
"%s Request, Returns nothing for %s", reqMsgName,
CSTRING(request->className.getString()) ));
response.reset(dynamic_cast<RSP*>(request->buildResponse()));
dispatcher->_enqueueResponse(request, response.release());
}
else
{
OperationAggregate *poA = new OperationAggregate(
new REQ(*request),
request->objectName.getClassName(),
request->nameSpace,
providerInfos.providerCount,
true); // requiresHostNameCompletion = true
// Include the repository response in the aggregation, if it
// exists
if (response.get() != 0)
{
poA->incTotalIssued();
dispatcher->_forwardResponseForAggregation(
new REQ(*request),
poA,
response.release());
}
while (providerInfos.hasMore(true))
{
ProviderInfo& providerInfo = providerInfos.getNext();
// Make copy of request
REQ* requestCopy = new REQ(*request);
// Insert the association class name to limit the provider
// to this class. This is a template function that sets the
// class fields as required for each msg type.
setSelectedRequestFields(requestCopy, providerInfo);
if (providerInfo.providerIdContainer.get() != 0)
{
requestCopy->operationContext.insert(
*(providerInfo.providerIdContainer.get()));
}
PEG_TRACE((TRC_DISPATCHER, Tracer::LEVEL4,
"%s Forwarding to provider for class %s, messageId %s",
reqMsgName,
CSTRING(providerInfo.className.getString()),
CSTRING(request->messageId) ));
dispatcher->_forwardAggregatingRequestToProvider(
providerInfo,
requestCopy, poA);
// Note: poA must not be referenced after last "forwardRequest
}
}
} // end issueAssocRequest
/**************************************************************************
**
** issueOpenAssocRequestMsgsToProviders - Template method to issue requests
** for Associator and Reference operations\ to each provider
**
**************************************************************************/
/* Template method issues the provider requests, repository
responses and provider requests for:
OpenAssociators
OpenAssociatorNames
OpenReferences
OpenReferenceNames
It differs from the issueAssocRequests in that this builds the
enumerationContext for the operations.
*/
template<class IREQ>
static void issueOpenAssocRequestMsgsToProviders(
CIMOperationRequestDispatcher* dispatcher,
IREQ* internalRequest,
ProviderInfoList& providerInfos,
OperationAggregate* poA,
const char * reqMsgName)
{
// Issue requests to all providers defined.
while (providerInfos.hasMore(true))
{
ProviderInfo& providerInfo = providerInfos.getNext();
IREQ* requestCopy = new IREQ(*internalRequest);
// Insert the association class name to limit the provider
// to this class.
setSelectedRequestFields(requestCopy, providerInfo);
if (providerInfo.providerIdContainer.get() != 0)
{
requestCopy->operationContext.insert(
*(providerInfo.providerIdContainer.get()));
}
PEG_TRACE((TRC_DISPATCHER, Tracer::LEVEL4,
"%s Forwarding to provider for class %s, messageId %s",
reqMsgName,
CSTRING(providerInfo.className.getString()),
CSTRING(internalRequest->messageId) ));
dispatcher->_forwardAggregatingRequestToProvider(
providerInfo, requestCopy, poA);
// Note: poA must not be referenced after last "forwardRequest"
}
} // end of issueOpenAssocRequestMessagesToProviders
/**************************************************************************
**
** IssueEnumerationRequests - Issue enumeration requests to providers
** for enumerateInstances and enumerateInstanceNames operations.
**
**************************************************************************/
/* Common Provider issue code for all
enumerate functions (enumerateInstance, EnumerateInstanceNames
openEnumerateInstancesWithPath openEnumerateInstancePaths).
Issues a request to all providers in the ProviderInfoList provided.
NOTE: Whereas today the assocRequests function starts with responses
this one starts after repository responses processed.
*/
template<class REQ>
static void issueEnumerationRequestsToProviders(
CIMOperationRequestDispatcher* dispatcher,
REQ* request,
ProviderInfoList providerInfos,
OperationAggregate* poA,
const char * reqMsgName)
{
// Loop through providerInfos, forwarding requests to providers
while (providerInfos.hasMore(true))
{
ProviderInfo& providerInfo = providerInfos.getNext();
// issue peg trace of routing info if required
providerInfos.pegRoutingTrace(providerInfo, reqMsgName,
request->messageId);
// set this className into the new request
REQ* requestCopy = new REQ(*request);
// set this className into the new request
requestCopy->className = providerInfo.className;
// Forward to provider. If fails return empty response
// FUTURE: Confirm that this short bypass is needed and works.
// The _forwardEnumerationToProvider handles any class
// checking and special tasks for NORMALIZATION
if (!dispatcher->_forwardEnumerationToProvider(
providerInfo, poA, requestCopy))
{
CIMResponseMessage* response = requestCopy->buildResponse();
dispatcher->_forwardResponseForAggregation(
requestCopy,
poA,
response);
}
}
}
}; // End Of ProviderRequests Struct
// EXP_PULL_BEGIN
#ifdef PEGASUS_ENABLE_FQL
//// Temporarily removed because we are losing the pointer to qx->_stmt when we
//// return from this function. Just set the code inline. KS_TODO
//FQLQueryExpressionRep* CIMOperationRequestDispatcher::handleFQLQueryRequest(
// CIMOpenOperationRequestMessage* request)
//{
// PEG_METHOD_ENTER(TRC_DISPATCHER,
// "CIMOperationRequestDispatcher::parseFQLFilter");
// bool exception = false;
//
// AutoPtr<FQLQueryStatement> queryStatement(new FQLQueryStatement());
//
// AutoPtr<FQLQueryExpressionRep> qx;
//
// CIMException cimException;
// if (request->filterQuery.size() != 0)
// {
// //// KS_TODO simplify by using FQLQueryExpressionRep to do this
// if (request->filterQueryLanguage != "DMTF:FQL")
// {
// cimException = PEGASUS_CIM_EXCEPTION(
// CIM_ERR_QUERY_LANGUAGE_NOT_SUPPORTED,
// request->filterQueryLanguage);
// exception = true;
// }
// else
// {
// try
// {
// FQLParser::parse(request->filterQuery, *queryStatement.get());
//
// qx.reset(new FQLQueryExpressionRep(
// request->filterQueryLanguage, queryStatement.get()));
//
// queryStatement.release();
// qx.release();
// }
// catch (ParseError& e)
// {
// String text = request->filterQuery + " " + e.getMessage();
//
// cimException = PEGASUS_CIM_EXCEPTION(
// CIM_ERR_INVALID_QUERY, text);
// exception=true;
// }
// catch (...)
// {
// cimException = PEGASUS_CIM_EXCEPTION(
// CIM_ERR_INVALID_QUERY, request->filterQuery);
// exception=true;
// }
// }
// if (exception)
// {
// CIMResponseMessage* response = request->buildResponse();
// response->cimException = cimException;
//
// XCOUT << "Gen Response " << endl;
// _enqueueResponse(request, response);
// PEG_METHOD_EXIT();
// return NULL;
// }
// }
//
// FQLQueryStatement* qsa = qx.get()->_stmt;
// qsa->print(); //// DELETE
// PEG_METHOD_EXIT();
// return qx.get();
//}
#endif
/**************************************************************************
**
** processPullRequest - Handles pullInstancesWithPath,pullInstancePaths
** and pullInstances with a single function
**
**************************************************************************/
bool CIMOperationRequestDispatcher::processPullRequest(
CIMPullOperationRequestMessage* request,
CIMOpenOrPullResponseDataMessage* pullResponse,
const char* requestName)
{
PEG_METHOD_ENTER(TRC_DISPATCHER,
"CIMOperationRequestDispatcher::processPullRequest");
AutoPtr<CIMOpenOrPullResponseDataMessage> responseDestroyer(pullResponse);
PEG_TRACE(( TRC_DISPATCHER, Tracer::LEVEL4,
"%s request for "
"namespace: %s"
"maxObjectCount: \"%u\" . "
"enumerationContext: \"%s\" . ",
requestName,
CSTRING(request->nameSpace.getString()),
request->maxObjectCount,
CSTRING(request->enumerationContext) ));
// Find the enumerationContext object from the request parameter
EnumerationContext* en = _enumerationContextTable->find(
request->enumerationContext);
// If enumeration Context,value is zero, or is already in closed status
// return Invalid Context exception with explanation.
if (_rejectInvalidEnumerationContext(request, en))
{
PEG_METHOD_EXIT();
return true;
}
if (request->nameSpace != en->getNamespace())
{
CIMResponseMessage* response = request->buildResponse();
response->cimException = PEGASUS_CIM_EXCEPTION_L(CIM_ERR_FAILED,
MessageLoaderParms("Server.CIMOperationRequestDispatcher."
"PULL_NAMESPACE_ERR",
"Incorrect namespace (%s) in pull operation. Expected: %s.",
CSTRING(request->nameSpace.getString()),
CSTRING(en->getNamespace().getString()) ));
_enqueueResponse(request, response);
PEG_METHOD_EXIT();
return true;
}
en->incrementRequestCount();
// lock the context until we have set processing state to avoid
// conflict with timer thread. Do not need to lock earlier
// because not closed (if closed, it would be invalid).
{
AutoMutex contextLock(en->_contextLock);
// reject and set closed if this is a not valid request for the
// originating operation
if (_rejectInvalidPullRequest(request,
en->isValidPullRequestType(request->getType())))
{
en->setClientClosed();
PEG_METHOD_EXIT();
return true;
}
// reject if an operation is already active on this enumeration
// context
if (_rejectIfEnumerationContextProcessing(request,
en->isProcessing()))
{
PEG_METHOD_EXIT();
return true;
}
// reject and set client closed if context timed out
if (_rejectIfContextTimedOut(request,
en->isTimedOut()))
{
en->setClientClosed();
PEG_METHOD_EXIT();
return true;
}
// Set active state and stop state timer.
en->setProcessingState(true);
// this also removes lock
}
// Test limit of the maxObjectCount consecutive zero counter
// The return is true if the limit is exceeded in which case
// close client and generate exception.
if (en->incAndTestPullCounters((request->maxObjectCount == 0)))
{
PEG_TRACE((TRC_DISPATCHER, Tracer::LEVEL4,
"%s Exceeded maxObjectCount consecutive zero limit. ContextId=%s",
requestName , (const char*)en->getContextId().getCString()));
// Force continueOnError to false.
en->setContinueOnError(false);
CIMException cimException = PEGASUS_CIM_EXCEPTION_L(
CIM_ERR_SERVER_LIMITS_EXCEEDED, MessageLoaderParms(
"Server.CIMOperationRequestDispatcher."
"ZERO_LEN_PULL_EXCEEDED_LIMIT",
"Maximum consecutive zero maxObjectCount pull requests"
" exceeded."));
en->setErrorState(cimException);
}
// KS_TODO determine if this is worthwhile trace
PEG_TRACE((TRC_DISPATCHER, Tracer::LEVEL4, // EXP_PULL_TEMP
"%s get from cache. ContextId=%s isComplete=%s cacheSize=%u "
"errorState=%s",
requestName,
(const char *)en->getContextId().getCString(),
boolToString(en->providersComplete()),
en->responseCacheSize(),
boolToString(en->isErrorState()) ));
// Issue the Response to the Request. This may be issued immediatly
// or delayed by setting information into the enumeration context
// if there are no responses from providers ready
// to avoid issuing empty responses. Enumeration Context must not
// be used after this call
bool releaseRequest = issueOpenOrPullResponseMessage(
request,
responseDestroyer.release(),
en,
request->maxObjectCount,
requireCompleteResponses);
return releaseRequest;
} // end issuePullResponse
// EXP_PULL_BEGIN
/**************************************************************************
**
** issueOpenOrPullResponseMessage - Issue immediate or delayed response
**
**************************************************************************/
// Issue the response to an open or pull. This function may issue the
// response immediatly if there are objects to send or may push the task
// off to the aggregrator if there is nothing to send immediatly.
// It is a template because there is one line that is message type
// dependent, the requirement to build a new request object.
bool CIMOperationRequestDispatcher::issueOpenOrPullResponseMessage(
CIMOperationRequestMessage* openRequest,
CIMOpenOrPullResponseDataMessage* openResponse,
EnumerationContext* en,
Uint32 operationMaxObjectCount,
Boolean requireCompleteResponses)
{
PEG_METHOD_ENTER(TRC_DISPATCHER,
"CIMOperationRequestDispatcher::_issueOpenOrPullResponseMessage");
PEGASUS_ASSERT(en->valid());
PEGASUS_ASSERT(en->_savedRequest == NULL);
PEGASUS_ASSERT(en->_savedResponse == NULL);
bool releaseRequest = true;
en->lockContext();
// Determine if there are any responses to send. Returns
// immediatly if operationMaxObjectCount satisfies what is in cache
// or maxObjectCount == 0
if (en->testCacheForResponses(operationMaxObjectCount,
requireCompleteResponses))
{
// Issue response immediatly
_issueImmediateOpenOrPullResponseMessage(
openRequest,
openResponse,
en,
operationMaxObjectCount);
if (en->isClientClosed() && en->providersComplete())
{
// en may be deleted in this call. Do not use
// after this call. This call does the unlock.
_enumerationContextTable->releaseContext(en);
}
else
{
en->unlockContext();
}
}
else
{
PEGASUS_DEBUG_ASSERT(en->isProcessing());
// Set up to issue upon provider response or timeout. Request passed
// to the delay variable so mark to not release.
en->setupDelayedResponse(
openRequest,
openResponse,
operationMaxObjectCount);
PEG_TRACE((TRC_DISPATCHER,Tracer::LEVEL4,
"EnumerationContextLock unlock %s", // KS_TODO DELETE
CSTRING(en->getContextId()) ));
en->unlockContext();
releaseRequest = false;
}
PEG_METHOD_EXIT();
return releaseRequest;
}
/**************************************************************************
**
** _issueImmediateOpenOrPullResponseMessage - issues the response define
** on the current thread
**
**************************************************************************/
// Issue the Open or Pull response immediatly.
// This function:
// 1 Checks for error responses and if found issues the next
// error response
// 2. If no errors, gets the next data from the cache and issues
// it.
// It assumes that the cache has already been tested for size, etc.
// and that there enough objects in the cache to match the request
// requirement.
// If it issues the response, it marks the response message for release
// upon completion of the send function
void CIMOperationRequestDispatcher::_issueImmediateOpenOrPullResponseMessage(
CIMOperationRequestMessage* request,
CIMOpenOrPullResponseDataMessage* response,
EnumerationContext* en,
Uint32 operationMaxObjectCount)
{
PEG_METHOD_ENTER(TRC_DISPATCHER,
"CIMOperationRequestDispatcher::"
"_issueImmediateOpenOrPullResponseMessage");
PEGASUS_DEBUG_ASSERT(en->valid());
AutoPtr<CIMOpenOrPullResponseDataMessage> responseDestroyer(response);
// KS TODO diagnostic. Remove before release.
PEG_TRACE((TRC_DISPATCHER, Tracer::LEVEL4,
"%s issueResponseMessage ContextId=%s"
" maxObjectCount=%u isComplete=%s, cacheSize=%u errorState=%s",
MessageTypeToString(request->getType()),
CSTRING(en->getContextId()),
operationMaxObjectCount,
boolToString(en->providersComplete()),
en->responseCacheSize(),
boolToString(en->isErrorState()) ));
CIMResponseData & to = response->getResponseData();
// Returns false if error flag set.
// Determine if this response is data or error
Boolean errorFound = !en->getCache(operationMaxObjectCount, to);
if (errorFound)
{
response->cimException = en->_cimException;
// KS_TODO remove this diagnostic trace before release
PEG_TRACE((TRC_DISPATCHER, Tracer::LEVEL4, // EXP_PULL_TEMP
"%s Response Error found. ContextId=%s cimException = %s",
MessageTypeToString(request->getType()),
CSTRING(en->getContextId()),
cimStatusCodeToString(response->cimException.getCode()) ));
}
_enumerationContextTable->setRequestSizeStatistics(operationMaxObjectCount);
// Check after processing the results of the get.
// This function either closes the operation if providers are complete
// and the response cache is empty or sets the processing state =
// false to allow the next operation.
// If errorFound = true, and !continueOnError, it sets the Client
// Closed.
// Context is current with provider response status
// If return = true, enumerate on sequence complete.
if (en->setNextEnumerationState(errorFound))
{
// FUTURE - Expand this for continueOnError=true (KS)
response->endOfSequence = true;
}
else
{
response->enumerationContext = en->getContextId();
}
_enqueueResponse(request, responseDestroyer.release());
PEG_METHOD_EXIT();
}
// Issue saved response. Used to send empty responses when an active
// enumerationContext times out. This allows continuing operation when
// providers are not returning responses in a timely manner and eliminates
// client timeouts. NOTE: Generally, this only occurs when providers are VERY
// slow returning responses so that the client should probably delay before
// the next request.
// Returns true if a response was generated, false if not. The only reason for
// a response not to have been generated is if none are waiting.
// This should be an impossible condition.
// It is expected that any the context is locked external to this function
// KS_TODO make this common function for all cases were we issue the
// saved request.
void CIMOperationRequestDispatcher::issueSavedResponse(EnumerationContext* en)
{
PEG_METHOD_ENTER(TRC_DISPATCHER,
"CIMOperationRequestDispatcher::issueSavedResponse");
PEGASUS_DEBUG_ASSERT(en->valid());
PEGASUS_DEBUG_ASSERT(en->isProcessing()); // assert of en is active
PEG_TRACE((TRC_DISPATCHER, Tracer::LEVEL4,
"issueSavedResponse for ContextId=%s", CSTRING(en->getContextId()) ));
if (en->_savedRequest != NULL)
{
// Force a response to be sent. This allows sending a response
// when there are no responses in the cache.
_cimOperationRequestDispatcher->
_issueImmediateOpenOrPullResponseMessage(
en->_savedRequest,
en->_savedResponse,
en,
0);
// Delete the request; it was allocated for
// this delayed response.
delete en->_savedRequest;
// clear the saved request to indicate it was used
en->_savedRequest = NULL;
en->_savedResponse = NULL;
en->_savedOperationMaxObjectCount = 0;
}
PEG_METHOD_EXIT();
}
// EXP_PULL_END
/*
Common processing for ExecQuery and OpenQueryInstances requests
This code gets the provider lists and issues the requests.
*/
bool CIMOperationRequestDispatcher::handleQueryRequestCommon(
CIMExecQueryRequestMessage* request,
CIMException& cimException,
EnumerationContext* enumerationContext,
const char* queryLanguage,
const CIMName& className,
QueryExpressionRep* qx)
{
PEG_METHOD_ENTER(TRC_DISPATCHER,
"CIMOperationRequestDispatcher::handleQueryRequestCommon");
AutoPtr<QueryExpressionRep> destroyer(qx);
//
// Get names of descendent classes:
//
ProviderInfoList providerInfos;
// This exception should not be required or we should apply for
// all _lookupInstanceProvider Calls.
try
{
providerInfos = _lookupAllInstanceProviders(
request->nameSpace,
className);
}
catch (CIMException& e)
{
// Return exception response if exception from getSubClasses
cimException = e;
PEG_METHOD_EXIT();
return false;
}
// If no provider is registered and the repository isn't the default,
// return CIM_ERR_NOT_SUPPORTED
if (_CIMExceptionIfNoProvidersOrRepository(request, providerInfos,
cimException))
{
PEG_METHOD_EXIT();
return false;
}
// We have instances for Providers and possibly repository.
// Set up an aggregate object and save a copy of the original request.
// NOTE: OperationAggregate released only when operation complete
bool isPullOperation = (enumerationContext != NULL)? true : false;
OperationAggregate* poA= new OperationAggregate(
new CIMExecQueryRequestMessage(*request),
className,
request->nameSpace,
providerInfos.providerCount,
false, false,
destroyer.release(),
queryLanguage);
if (isPullOperation)
{
poA->setPullOperation(enumerationContext);
}
// Build enum request for call to repository
AutoPtr<CIMEnumerateInstancesRequestMessage> repRequest(
new CIMEnumerateInstancesRequestMessage(
request->messageId,
request->nameSpace,
CIMName(),
false,false,false,
CIMPropertyList(),
request->queueIds,
request->authType,
request->userName));
// Gather the repository responses and send as one response
// with many instances
//
if (_enumerateFromRepository(repRequest.release(), poA, providerInfos))
{
CIMResponseMessage* response = poA->removeResponse(0);
_forwardResponseForAggregation(
new CIMExecQueryRequestMessage(*request),
poA,
response);
}
// Loop through providerInfos, forwarding requests to providers
while (providerInfos.hasMore(true))
{
// If this class has a provider
ProviderInfo& providerInfo = providerInfos.getNext();
// KS_TODO we should show if it is a query or instance provider in trace
providerInfos.pegRoutingTrace(providerInfo,
((isPullOperation)? "OpenQueryInstances": "execQuery"),
request->messageId);
ProviderIdContainer* providerIdContainer =
providerInfo.providerIdContainer.get();
// If not a provider with Query capability, execute
// EnumerateInstances for the provider.
if (providerInfo.hasNoQuery)
{
OperationContext* context = &request->operationContext;
const OperationContext::Container* container = 0;
container = &context->get(IdentityContainer::NAME);
const IdentityContainer& identityContainer =
dynamic_cast<const IdentityContainer&>(*container);
AutoPtr<CIMEnumerateInstancesRequestMessage> enumReq(
new CIMEnumerateInstancesRequestMessage(
request->messageId,
request->nameSpace,
providerInfo.className,
false,false,false,
CIMPropertyList(),
request->queueIds,
request->authType,
identityContainer.getUserName()));
context = &enumReq->operationContext;
if (providerIdContainer)
{
context->insert(*providerIdContainer);
}
context->insert(identityContainer);
_forwardRequestForAggregation(
providerInfo.serviceId,
providerInfo.controlProviderName,
enumReq.release(), poA);
}
else
{
AutoPtr<CIMExecQueryRequestMessage> requestCopy(
new CIMExecQueryRequestMessage(*request));
OperationContext* context = &request->operationContext;
if (providerIdContainer)
{
context->insert(*providerIdContainer);
}
requestCopy->operationContext = *context;
requestCopy->className = providerInfo.className;
_forwardRequestForAggregation(
providerInfo.serviceId,
providerInfo.controlProviderName,
requestCopy.release(), poA);
}
} // for all classes and derived classes
PEG_METHOD_EXIT();
return true;
}
// EXP_PULL_END
/****************************************************************************
**
** CIMOperationDispatcher request handlers. There is a handler for each
** operation request type. These handlers process the requsts including:
** - Validation of parameters (may generate error responses)
** - Passage to the correct processor (service, control providers,
** providers, repository) depending on message type)
** - Generation of responses for those handlers that are synchronous.
**
****************************************************************************/
/**$*******************************************************
handleGetClassRequest
**********************************************************/
void CIMOperationRequestDispatcher::handleGetClassRequest(
CIMGetClassRequestMessage* request)
{
PEG_METHOD_ENTER(TRC_DISPATCHER,
"CIMOperationRequestDispatcher::handleGetClassRequest");
CIMClass cimClass =
_repository->getClass(
request->nameSpace,
request->className,
request->localOnly,
request->includeQualifiers,
request->includeClassOrigin,
request->propertyList);
PEG_TRACE((TRC_DISPATCHER, Tracer::LEVEL3,
"CIMOperationRequestDispatcher::handleGetClassRequest - "
"Namespace: %s Class name: %s",
CSTRING(request->nameSpace.getString()),
CSTRING(request->className.getString())));
AutoPtr<CIMGetClassResponseMessage> response(
dynamic_cast<CIMGetClassResponseMessage*>(
request->buildResponse()));
response->cimClass = cimClass;
_enqueueResponse(request, response.release());
PEG_METHOD_EXIT();
}
/**$*******************************************************
handleGetInstanceRequest
**********************************************************/
void CIMOperationRequestDispatcher::handleGetInstanceRequest(
CIMGetInstanceRequestMessage* request)
{
PEG_METHOD_ENTER(TRC_DISPATCHER,
"CIMOperationRequestDispatcher::handleGetInstanceRequest");
// get the class name
CIMName className = request->instanceName.getClassName();
// Validate the class in the request. Returns class if not rejected
CIMConstClass cimClass;
if (_rejectInvalidClassParameter(request, cimClass))
{
PEG_METHOD_EXIT();
return;
}
ProviderInfo providerInfo = _lookupInstanceProvider(
request->nameSpace,
className);
if (providerInfo.hasProvider)
{
CIMGetInstanceRequestMessage* requestCopy =
new CIMGetInstanceRequestMessage(*request);
if (providerInfo.providerIdContainer.get() != 0)
{
requestCopy->operationContext.insert(
*providerInfo.providerIdContainer.get());
}
#ifdef PEGASUS_ENABLE_OBJECT_NORMALIZATION
if (providerInfo.hasProviderNormalization)
{
requestCopy->operationContext.insert(
CachedClassDefinitionContainer(cimClass));
}
#endif
CIMGetInstanceRequestMessage* requestCallbackCopy =
new CIMGetInstanceRequestMessage(*requestCopy);
_forwardRequestToSingleProvider(
providerInfo,
requestCopy,
requestCallbackCopy);
PEG_METHOD_EXIT();
return;
}
// not internal or found provider, go to default
if (_repository->isDefaultInstanceProvider())
{
CIMInstance cimInstance =
_repository->getInstance(
request->nameSpace,
request->instanceName,
request->includeQualifiers,
request->includeClassOrigin,
request->propertyList);
AutoPtr<CIMGetInstanceResponseMessage> response(
dynamic_cast<CIMGetInstanceResponseMessage*>(
request->buildResponse()));
response->getResponseData().setInstance(cimInstance);
_enqueueResponse(request, response.release());
}
else // No provider is registered and the repository isn't the default
{
CIMResponseMessage* response = request->buildResponse();
response->cimException =
PEGASUS_CIM_EXCEPTION(CIM_ERR_NOT_SUPPORTED, String::EMPTY);
_enqueueResponse(request, response);
}
PEG_METHOD_EXIT();
}
/**$*******************************************************
handleDeleteClassRequest
**********************************************************/
void CIMOperationRequestDispatcher::handleDeleteClassRequest(
CIMDeleteClassRequestMessage* request)
{
PEG_METHOD_ENTER(TRC_DISPATCHER,
"CIMOperationRequestDispatcher::handleDeleteClassRequest");
_repository->deleteClass(
request->nameSpace,
request->className);
PEG_TRACE((TRC_DISPATCHER, Tracer::LEVEL3,
"CIMOperationRequestDispatcher::handleDeleteClassRequest - "
"Namespace: %s Class Name: %s",
CSTRING(request->nameSpace.getString()),
CSTRING(request->className.getString())));
AutoPtr<CIMDeleteClassResponseMessage> response(
dynamic_cast<CIMDeleteClassResponseMessage*>(
request->buildResponse()));
_enqueueResponse(request, response.release());
PEG_METHOD_EXIT();
}
/**$*******************************************************
handleDeleteInstanceRequest
**********************************************************/
void CIMOperationRequestDispatcher::handleDeleteInstanceRequest(
CIMDeleteInstanceRequestMessage* request)
{
PEG_METHOD_ENTER(TRC_DISPATCHER,
"CIMOperationRequestDispatcher::handleDeleteInstanceRequest");
// get the class name
CIMName className = request->instanceName.getClassName();
if (!_checkExistenceOfClass(request->nameSpace, className))
{
PEG_TRACE((TRC_DISPATCHER, Tracer::LEVEL1,
"CIMOperationRequestDispatcher::handleDeleteInstanceRequest - "
"CIM class does not exist exception has occurred. "
"Namespace: %s Class Name: %s",
CSTRING(request->nameSpace.getString()),
CSTRING(className.getString())));
PEG_METHOD_EXIT();
throw PEGASUS_CIM_EXCEPTION(
CIM_ERR_INVALID_CLASS, className.getString());
}
ProviderInfo providerInfo = _lookupInstanceProvider(
request->nameSpace,
className);
if (providerInfo.hasProvider)
{
CIMDeleteInstanceRequestMessage* requestCopy =
new CIMDeleteInstanceRequestMessage(*request);
if (providerInfo.providerIdContainer.get() != 0)
{
requestCopy->operationContext.insert(
*providerInfo.providerIdContainer.get());
//delete providerIdContainer;
//providerIdContainer = 0;
}
CIMDeleteInstanceRequestMessage* requestCallbackCopy =
new CIMDeleteInstanceRequestMessage(*requestCopy);
_forwardRequestToSingleProvider(
providerInfo,
requestCopy,
requestCallbackCopy);
PEG_METHOD_EXIT();
return;
}
else if (_repository->isDefaultInstanceProvider())
{
_repository->deleteInstance(
request->nameSpace,
request->instanceName);
PEG_TRACE((TRC_DISPATCHER, Tracer::LEVEL3,
"CIMOperationRequestDispatcher::handleDeleteInstanceRequest - "
"Namespace: %s Instance Name: %s",
CSTRING(request->nameSpace.getString()),
CSTRING(request->instanceName.toString())));
AutoPtr<CIMDeleteInstanceResponseMessage> response(
dynamic_cast<CIMDeleteInstanceResponseMessage*>(
request->buildResponse()));
_enqueueResponse(request, response.release());
}
else // No provider is registered and the repository isn't the default
{
CIMResponseMessage* response = request->buildResponse();
response->cimException =
PEGASUS_CIM_EXCEPTION(CIM_ERR_NOT_SUPPORTED, String::EMPTY);
_enqueueResponse(request, response);
}
PEG_METHOD_EXIT();
}
/**$*******************************************************
handleCreateClassRequest
**********************************************************/
void CIMOperationRequestDispatcher::handleCreateClassRequest(
CIMCreateClassRequestMessage* request)
{
PEG_METHOD_ENTER(TRC_DISPATCHER,
"CIMOperationRequestDispatcher::handleCreateClassRequest");
removePropagatedAndOriginAttributes(request->newClass);
_repository->createClass(request->nameSpace, request->newClass);
PEG_TRACE((TRC_DISPATCHER, Tracer::LEVEL3,
"CIMOperationRequestDispatcher::handleCreateClassRequest - "
"Namespace: %s Class Name: %s",
CSTRING(request->nameSpace.getString()),
CSTRING(request->className.getString())));
AutoPtr<CIMCreateClassResponseMessage> response(
dynamic_cast<CIMCreateClassResponseMessage*>(
request->buildResponse()));
_enqueueResponse(request, response.release());
PEG_METHOD_EXIT();
}
/**$*******************************************************
handleCreateInstanceRequest
**********************************************************/
void CIMOperationRequestDispatcher::handleCreateInstanceRequest(
CIMCreateInstanceRequestMessage* request)
{
PEG_METHOD_ENTER(TRC_DISPATCHER,
"CIMOperationRequestDispatcher::handleCreateInstanceRequest()");
// get the class name
CIMName className = request->newInstance.getClassName();
if (!_checkExistenceOfClass(request->nameSpace, className))
{
PEG_TRACE((TRC_DISPATCHER, Tracer::LEVEL1,
"CIMOperationRequestDispatcher::handleCreateInstanceRequest - "
"CIM class does not exist exception has occurred. "
"Namespace: %s Class Name: %s",
CSTRING(request->nameSpace.getString()),
CSTRING(className.getString())));
PEG_METHOD_EXIT();
throw PEGASUS_CIM_EXCEPTION(
CIM_ERR_INVALID_CLASS, className.getString());
}
ProviderInfo providerInfo = _lookupInstanceProvider(
request->nameSpace,
className);
if (providerInfo.hasProvider)
{
CIMCreateInstanceRequestMessage* requestCopy =
new CIMCreateInstanceRequestMessage(*request);
removePropagatedAndOriginAttributes(requestCopy->newInstance);
if (providerInfo.providerIdContainer.get() != 0)
{
requestCopy->operationContext.insert(
*providerInfo.providerIdContainer.get());
}
CIMCreateInstanceRequestMessage* requestCallbackCopy =
new CIMCreateInstanceRequestMessage(*requestCopy);
_forwardRequestToSingleProvider(
providerInfo,
requestCopy,
requestCallbackCopy);
PEG_METHOD_EXIT();
return;
}
else if (_repository->isDefaultInstanceProvider())
{
removePropagatedAndOriginAttributes(request->newInstance);
CIMObjectPath instanceName = _repository->createInstance(
request->nameSpace,
request->newInstance);
PEG_TRACE((TRC_DISPATCHER, Tracer::LEVEL3,
"CIMOperationRequestDispatcher::handleCreateInstanceRequest - "
"Namespace: %s Instance Name: %s",
CSTRING(request->nameSpace.getString()),
CSTRING(request->newInstance.getClassName().getString())));
AutoPtr<CIMCreateInstanceResponseMessage> response(
dynamic_cast<CIMCreateInstanceResponseMessage*>(
request->buildResponse()));
response->instanceName = instanceName;
_enqueueResponse(request, response.release());
}
else // No provider is registered and the repository isn't the default
{
CIMResponseMessage* response = request->buildResponse();
response->cimException =
PEGASUS_CIM_EXCEPTION(CIM_ERR_NOT_SUPPORTED, String::EMPTY);
_enqueueResponse(request, response);
}
PEG_METHOD_EXIT();
}
/**$*******************************************************
handleModifyClassRequest
This request is analyzed and if correct, is passed directly to the
repository
**********************************************************/
void CIMOperationRequestDispatcher::handleModifyClassRequest(
CIMModifyClassRequestMessage* request)
{
PEG_METHOD_ENTER(TRC_DISPATCHER,
"CIMOperationRequestDispatcher::handleModifyClassRequest");
removePropagatedAndOriginAttributes(request->modifiedClass);
_repository->modifyClass(request->nameSpace, request->modifiedClass);
AutoPtr<CIMModifyClassResponseMessage> response(
dynamic_cast<CIMModifyClassResponseMessage*>(
request->buildResponse()));
_enqueueResponse(request, response.release());
PEG_METHOD_EXIT();
}
/**$*******************************************************
handleModifyInstanceRequest
**********************************************************/
void CIMOperationRequestDispatcher::handleModifyInstanceRequest(
CIMModifyInstanceRequestMessage* request)
{
PEG_METHOD_ENTER(TRC_DISPATCHER,
"CIMOperationRequestDispatcher::handleModifyInstanceRequest");
CIMName className = request->modifiedInstance.getClassName();
if (!_checkExistenceOfClass(request->nameSpace, className))
{
PEG_TRACE((TRC_DISPATCHER, Tracer::LEVEL1,
"CIMOperationRequestDispatcher::handleModifyInstanceRequest - "
"CIM class does not exist exception has occurred. "
"Namespace: %s Class Name: %s",
CSTRING(request->nameSpace.getString()),
CSTRING(className.getString())));
PEG_METHOD_EXIT();
throw PEGASUS_CIM_EXCEPTION(
CIM_ERR_INVALID_CLASS, className.getString());
}
ProviderInfo providerInfo = _lookupInstanceProvider(
request->nameSpace,
className);
if (providerInfo.hasProvider)
{
CIMModifyInstanceRequestMessage* requestCopy =
new CIMModifyInstanceRequestMessage(*request);
removePropagatedAndOriginAttributes(requestCopy->modifiedInstance);
if (providerInfo.providerIdContainer.get() != 0)
{
requestCopy->operationContext.insert(
*providerInfo.providerIdContainer.get());
}
CIMModifyInstanceRequestMessage* requestCallbackCopy =
new CIMModifyInstanceRequestMessage(*requestCopy);
_forwardRequestToSingleProvider(
providerInfo,
requestCopy,
requestCallbackCopy);
PEG_METHOD_EXIT();
return;
}
else if (_repository->isDefaultInstanceProvider())
{
removePropagatedAndOriginAttributes(request->modifiedInstance);
_repository->modifyInstance(
request->nameSpace,
request->modifiedInstance,
request->includeQualifiers,request->propertyList);
PEG_TRACE((TRC_DISPATCHER, Tracer::LEVEL3,
"CIMOperationRequestDispatcher::handleModifyInstanceRequest - "
"Namespace: %s Instance Name: %s",
CSTRING(request->nameSpace.getString()),
CSTRING(request->modifiedInstance.getClassName().getString())));
AutoPtr<CIMModifyInstanceResponseMessage> response(
dynamic_cast<CIMModifyInstanceResponseMessage*>(
request->buildResponse()));
_enqueueResponse(request, response.release());
}
else // No provider is registered and the repository isn't the default
{
CIMResponseMessage* response = request->buildResponse();
response->cimException =
PEGASUS_CIM_EXCEPTION(CIM_ERR_NOT_SUPPORTED, String::EMPTY);
_enqueueResponse(request, response);
}
PEG_METHOD_EXIT();
}
/**$*******************************************************
handleEnumerateClassesRequest
**********************************************************/
void CIMOperationRequestDispatcher::handleEnumerateClassesRequest(
CIMEnumerateClassesRequestMessage* request)
{
PEG_METHOD_ENTER(TRC_DISPATCHER,
"CIMOperationRequestDispatcher::handleEnumerateClassesRequest");
Array<CIMClass> cimClasses =
_repository->enumerateClasses(
request->nameSpace,
request->className,
request->deepInheritance,
request->localOnly,
request->includeQualifiers,
request->includeClassOrigin);
PEG_TRACE((TRC_DISPATCHER, Tracer::LEVEL3,
"CIMOperationRequestDispatcher::handleEnumerateClassesRequest - "
"Namespace: %s Class name: %s",
CSTRING(request->nameSpace.getString()),
CSTRING(request->className.getString())));
AutoPtr<CIMEnumerateClassesResponseMessage> response(
dynamic_cast<CIMEnumerateClassesResponseMessage*>(
request->buildResponse()));
response->cimClasses = cimClasses;
_enqueueResponse(request, response.release());
PEG_METHOD_EXIT();
}
/**$*******************************************************
handleEnumerateClassNamesRequest
**********************************************************/
void CIMOperationRequestDispatcher::handleEnumerateClassNamesRequest(
CIMEnumerateClassNamesRequestMessage* request)
{
PEG_METHOD_ENTER(TRC_DISPATCHER,
"CIMOperationRequestDispatcher::handleEnumerateClassNamesRequest");
Array<CIMName> classNames =
_repository->enumerateClassNames(
request->nameSpace,
request->className,
request->deepInheritance);
PEG_TRACE((TRC_DISPATCHER, Tracer::LEVEL3,
"CIMOperationRequestDispatcher::handleEnumerateClassNamesRequest - "
"Namespace: %s Class name: %s",
CSTRING(request->nameSpace.getString()),
CSTRING(request->className.getString())));
AutoPtr<CIMEnumerateClassNamesResponseMessage> response(
dynamic_cast<CIMEnumerateClassNamesResponseMessage*>(
request->buildResponse()));
response->classNames = classNames;
_enqueueResponse(request, response.release());
PEG_METHOD_EXIT();
}
/**$*******************************************************
handleEnumerateInstancesRequest
if !validClassName
generate exception response
return
get all subclasses to target class
for all classes
get Provider for Class
if (number of providers > BreadthLimit)
generate exception
return
if (no providers found) and !(repository is default provider)
generate CIM_ERR_NOT_SUPPORTED response
return
for all targetclass and subclasses
if (class has a provider)
copy request
substitute current class name
forward request to provider
if (repository is default provider)
for all targetclass and subclasses
if !(class has a provider)
issue request for this class to repository
put response on aggregate list
**********************************************************/
void CIMOperationRequestDispatcher::handleEnumerateInstancesRequest(
CIMEnumerateInstancesRequestMessage* request)
{
PEG_METHOD_ENTER(TRC_DISPATCHER,
"CIMOperationRequestDispatcher::handleEnumerateInstancesRequest");
PEG_TRACE((TRC_DISPATCHER, Tracer::LEVEL3,
"CIMOperationRequestDispatcher::handleEnumerateInstancesRequest - "
"Namespace=%s ClassName=%s messageId=%s",
CSTRING(request->nameSpace.getString()),
CSTRING(request->className.getString()),
CSTRING(request->messageId)));
//
// Validate the class in the request and get the target class to
// be used later in the operation.
//
CIMConstClass cimClass;
if (_rejectInvalidClassParameter(request,cimClass))
{
PEG_METHOD_EXIT();
return;
}
// Set the propertylist to be forwarded in accord with the propertyList
// parameter. The property list forwarded to providers
// is constructed from properties in the top level class when
// !deepInheritance && propertyList.isNull() to assure
// that providers will return only the properties of the requested class.
// NOTE - The request class pl should really be null. Subclasses should
// get the propertyList. But we do not have a record today of the
// original class in the providerInfo list so everybody gets the
// list.
if (!request->deepInheritance && request->propertyList.isNull())
{
_buildPropertyListFromClass(cimClass, request->propertyList);
}
//
// Get names of descendent classes and list of providers
// For Enumerate Operations; the list of providers is used for both
// repository and provider requests.
//
ProviderInfoList providerInfos = _lookupAllInstanceProviders(
request->nameSpace,
request->className);
// If no provider is registered and the repository isn't the default,
// return CIM_ERR_NOT_SUPPORTED
if (_rejectNoProvidersOrRepository(request, providerInfos))
{
PEG_METHOD_EXIT();
return;
}
//
// Set up an aggregate object with a copy of the original request.
// NOTE: OperationAggregate released only when operation complete.
// requiresHostnameCompletion false, hasPropList true
//
OperationAggregate* poA= new OperationAggregate(
new CIMEnumerateInstancesRequestMessage(*request),
request->className,
request->nameSpace,
providerInfos.providerCount,
false, // completeHostAndNamespace = false
true); // has propertyList = true
// Gather the repository responses and send as one response
// with many instances
//
if (_enumerateFromRepository(request, poA, providerInfos))
{
CIMResponseMessage* response = poA->removeResponse(0);
_forwardResponseForAggregation(
new CIMEnumerateInstancesRequestMessage(*request),
poA, response);
}
ProviderRequests::issueEnumerationRequestsToProviders(
this,
request,
providerInfos,
poA,
"enumerateInstances");
PEG_METHOD_EXIT();
}
/**$*******************************************************
handleEnumerateInstanceNamesRequest
if !validClassName
generate exception response
return
get all subclasses to target class
for all classes
get Provider for Class
if (number of providers > BreadthLimit)
generate exception
return
if (no providers found) and !(repository is default provider)
generate CIM_ERR_NOT_SUPPORTED response
return
for all targetclass and subclasses
if (class has a provider)
copy request
substitute current class name
forward request to provider
if (repository is default provider)
for all targetclass and subclasses
if !(class has a provider)
issue request for this class to repository
put response on aggregate list
**********************************************************/
void CIMOperationRequestDispatcher::handleEnumerateInstanceNamesRequest(
CIMEnumerateInstanceNamesRequestMessage* request)
{
PEG_METHOD_ENTER(TRC_DISPATCHER,
"CIMOperationRequestDispatcher::handleEnumerateInstanceNamesRequest");
//
// Validate the class name in the request
//
CIMConstClass cimClass;
if (_rejectInvalidClassParameter(request, cimClass))
{
PEG_METHOD_EXIT();
return;
}
//
// Get names of descendent classes and list of providers
//
ProviderInfoList providerInfos = _lookupAllInstanceProviders(
request->nameSpace,
request->className);
// If no provider is registered and the repository isn't the default,
// return CIM_ERR_NOT_SUPPORTED
if (_rejectNoProvidersOrRepository(request, providerInfos))
{
PEG_METHOD_EXIT();
return;
}
// We have instances for Providers and possibly repository.
// Set up an aggregate object and save a copy of the original request.
// NOTE: OperationAggregate released only when operation complete
//
OperationAggregate* poA= new OperationAggregate(
new CIMEnumerateInstanceNamesRequestMessage(*request),
request->className,
request->nameSpace,
providerInfos.providerCount,
false); // completeHostAndNamespace = false, and no property list
if (_enumerateFromRepository(request, poA, providerInfos))
{
CIMResponseMessage* response = poA->removeResponse(0);
_forwardResponseForAggregation(
new CIMEnumerateInstanceNamesRequestMessage(*request),
poA,
response);
}
// Template to issue EnumerationRequest messages to Providers.
ProviderRequests::issueEnumerationRequestsToProviders(
this,
request,
providerInfos,
poA,
"enumerateInstanceNames");
PEG_METHOD_EXIT();
}
/**$*******************************************************
handleAssociatorsRequest
**********************************************************/
void CIMOperationRequestDispatcher::handleAssociatorsRequest(
CIMAssociatorsRequestMessage* request)
{
PEG_METHOD_ENTER(TRC_DISPATCHER,
"CIMOperationRequestDispatcher::handleAssociatorsRequest");
PEG_TRACE((TRC_DISPATCHER, Tracer::LEVEL3,
"CIMOperationRequestDispatcher::handleAssociators - "
"Namespace=%s ClassName=%s messageId=%s",
CSTRING(request->nameSpace.getString()),
CSTRING(request->objectName.toString()),
CSTRING(request->messageId)));
// validate className and objectClassName same. This is
// an invariant for the handleAssoc, etc functions.
PEGASUS_DEBUG_ASSERT(
request->className == request->objectName.getClassName());
if (_rejectAssociationTraversalDisabled(request, "Associators"))
{
PEG_METHOD_EXIT();
return;
}
// Validate role and resultrole parameters
if (_rejectInvalidRoleParameter(request, request->role, "role"))
{
PEG_METHOD_EXIT();
return;
}
if (_rejectInvalidRoleParameter(request, request->resultRole, "resultrole"))
{
PEG_METHOD_EXIT();
return;
}
if (_rejectInvalidClassParameter(request, request->nameSpace,
request->objectName))
{
PEG_METHOD_EXIT();
return;
}
// The entity that creates the CIMMessage determines if this is a class
// or instance operation.
if (request->isClassRequest)
{
//
// For Class requests, get the results from the repository
//
PEG_TRACE_CSTRING(TRC_DISPATCHER, Tracer::LEVEL3,
"Associators executing Class request");
Array<CIMObject> cimObjects =
_repository->associators(
request->nameSpace,
request->objectName,
request->assocClass,
request->resultClass,
request->role,
request->resultRole,
request->includeQualifiers,
request->includeClassOrigin,
request->propertyList);
AutoPtr<CIMAssociatorsResponseMessage> response(
dynamic_cast<CIMAssociatorsResponseMessage*>(
request->buildResponse()));
// Flag to indicate that these are class objects is passed
// from request in buildResponse above
response->getResponseData().setObjects(cimObjects);
_enqueueResponse(request, response.release());
}
// This is an instance request
else
{
//
// For Instance requests, get results from providers and the repository
// Determine list of providers for this request. Note that
// providerCount may not be the same as the size of the returned
// array because not all Class will have providers.
//
ProviderInfoList providerInfos = _lookupAllAssociationProviders(
request->nameSpace,
request->objectName,
request->assocClass,
String::EMPTY);
// If no provider is registered and the repository isn't the default,
// return CIM_ERR_NOT_SUPPORTED
if (_rejectNoProvidersOrRepository(request, providerInfos))
{
PEG_METHOD_EXIT();
return;
}
//
// Get the instances from the repository, as necessary
//
// Hold the repository results in a response message.
// If not using the repository, this pointer is null.
AutoPtr<CIMAssociatorsResponseMessage> response;
if (_repository->isDefaultInstanceProvider())
{
response.reset(dynamic_cast<CIMAssociatorsResponseMessage*>(
request->buildResponse()));
const Array<CIMObject>& cimObjects = _repository->associators(
request->nameSpace,
request->objectName,
request->assocClass,
request->resultClass,
request->role,
request->resultRole,
request->includeQualifiers,
request->includeClassOrigin,
request->propertyList);
response->getResponseData().setObjects(cimObjects);
PEG_TRACE((TRC_DISPATCHER, Tracer::LEVEL4,
"Associators repository access: class = %s, count = %u.",
CSTRING(request->objectName.toString()),
response->getResponseData().getObjects().size()));
}
// Issue Provider requests and process the respository responseData
ProviderRequests::issueAssocRequestsToProviders(
this,
request,
response,
providerInfos,
"Associators");
} // End of instance processing
PEG_METHOD_EXIT();
}
/**$*******************************************************
handleAssociatorNamesRequest
**********************************************************/
void CIMOperationRequestDispatcher::handleAssociatorNamesRequest(
CIMAssociatorNamesRequestMessage* request)
{
PEG_METHOD_ENTER(TRC_DISPATCHER,
"CIMOperationRequestDispatcher::handleAssociatorNamesRequest");
PEG_TRACE(( TRC_DISPATCHER, Tracer::LEVEL3,
"CIMOperationRequestDispatcher::handleAssociatorNames - "
"Namespace: %s Class name: %s",
CSTRING(request->nameSpace.getString()),
CSTRING(request->objectName.toString())));
// validate className and objectClassName same. This is
// an invariant for the handleAssoc, etc functions.
PEGASUS_DEBUG_ASSERT(
request->className == request->objectName.getClassName());
if (_rejectAssociationTraversalDisabled(request,"AssociatorNames"))
{
PEG_METHOD_EXIT();
return;
}
// Validate role parameters syntax
if (_rejectInvalidRoleParameter(request, request->role, "role"))
{
PEG_METHOD_EXIT();
return;
}
if (_rejectInvalidRoleParameter(request, request->resultRole, "resultrole"))
{
PEG_METHOD_EXIT();
return;
}
if (_rejectInvalidClassParameter(request, request->nameSpace,
request->objectName))
{
PEG_METHOD_EXIT();
return;
}
// If Class request, get class data from repository
if (request->isClassRequest)
{
//
// For Class requests, get the results from the repository
//
PEG_TRACE_CSTRING(TRC_DISPATCHER, Tracer::LEVEL3,
"AssociatorNames executing Class request");
Array<CIMObjectPath> objectNames =
_repository->associatorNames(
request->nameSpace,
request->objectName,
request->assocClass,
request->resultClass,
request->role,
request->resultRole);
AutoPtr<CIMAssociatorNamesResponseMessage> response(
dynamic_cast<CIMAssociatorNamesResponseMessage*>(
request->buildResponse()));
// Flag to indicate that these are class objects is passed
// from request in buildResponse above.
response->getResponseData().setInstanceNames(objectNames);
_enqueueResponse(request, response.release());
}
// Else this is an Instance request
else
{
//
// For Instance requests, get results from providers and the repository
// Determine list of providers for this request
//
ProviderInfoList providerInfos = _lookupAllAssociationProviders(
request->nameSpace,
request->objectName,
request->assocClass,
String::EMPTY);
// If no provider is registered and the repository isn't the default,
// return CIM_ERR_NOT_SUPPORTED
if (_rejectNoProvidersOrRepository(request, providerInfos))
{
PEG_METHOD_EXIT();
return;
}
// Get from repository if it exists.
// Hold the repository results in a response message.
// If not using the repository, this pointer is null.
AutoPtr<CIMAssociatorNamesResponseMessage> response;
if (_repository->isDefaultInstanceProvider())
{
response.reset(dynamic_cast<CIMAssociatorNamesResponseMessage*>(
request->buildResponse()));
Array<CIMObjectPath> objectNames = _repository->associatorNames(
request->nameSpace,
request->objectName,
request->assocClass,
request->resultClass,
request->role,
request->resultRole);
response->getResponseData().setInstanceNames(objectNames);
PEG_TRACE((TRC_DISPATCHER, Tracer::LEVEL4,
"AssociatorNames repository access: class = %s, count = %u.",
CSTRING(request->objectName.toString()),
objectNames.size()));
}
// Issue Provider requests and process the respository responseData
ProviderRequests::issueAssocRequestsToProviders(
this,
request,
response,
providerInfos,
"AssociatorNames");
} // End of instance processing
PEG_METHOD_EXIT();
}
/**$*******************************************************
handleReferencesRequest
**********************************************************/
void CIMOperationRequestDispatcher::handleReferencesRequest(
CIMReferencesRequestMessage* request)
{
PEG_METHOD_ENTER(TRC_DISPATCHER,
"CIMOperationRequestDispatcher::handleReferencesRequest");
PEG_TRACE((TRC_DISPATCHER, Tracer::LEVEL3,
"CIMOperationRequestDispatcher::handleReferences - "
"Namespace: %s Class name: %s",
CSTRING(request->nameSpace.getString()),
CSTRING(request->objectName.toString())));
// validate className and objectClassName same. This is
// an invariant for the handleAssoc, etc functions.
PEGASUS_DEBUG_ASSERT(
request->className == request->objectName.getClassName());
if (_rejectAssociationTraversalDisabled(request,"References"))
{
PEG_METHOD_EXIT();
return;
}
// Validate role parameter syntax
if (_rejectInvalidRoleParameter(request, request->role, "role"))
{
PEG_METHOD_EXIT();
return;
}
if (_rejectInvalidClassParameter(request, request->nameSpace,
request->objectName))
{
PEG_METHOD_EXIT();
return;
}
// If true, this is a class Request
if (request->isClassRequest)
{
//
// For Class requests, get the results from the repository
//
PEG_TRACE_CSTRING(TRC_DISPATCHER, Tracer::LEVEL4,
"References executing Class request");
Array<CIMObject> cimObjects =
_repository->references(
request->nameSpace,
request->objectName,
request->resultClass,
request->role,
request->includeQualifiers,
request->includeClassOrigin,
request->propertyList);
AutoPtr<CIMReferencesResponseMessage> response(
dynamic_cast<CIMReferencesResponseMessage*>(
request->buildResponse()));
// Flag to indicate that these are class objects is passed
// from request in buildResponse above
response->getResponseData().setObjects(cimObjects);
_enqueueResponse(request, response.release());
}
// Else Instance Request
else
{
//
// For Instance requests, get results from providers and the repository
// Determine list of Classes and providers for this request
//
ProviderInfoList providerInfos = _lookupAllAssociationProviders(
request->nameSpace,
request->objectName,
request->resultClass,
String::EMPTY);
// If no provider is registered and the repository isn't the default,
// return CIM_ERR_NOT_SUPPORTED
if (_rejectNoProvidersOrRepository(request, providerInfos))
{
PEG_METHOD_EXIT();
return;
}
//
// Get the instances from the repository, as necessary.
// Hold the repository results in a response message.
// If not using the repository, this pointer is null.
//
AutoPtr<CIMReferencesResponseMessage> response;
if (_repository->isDefaultInstanceProvider())
{
response.reset(dynamic_cast<CIMReferencesResponseMessage*>(
request->buildResponse()));
Array<CIMObject> cimObjects = _repository->references(
request->nameSpace,
request->objectName,
request->resultClass,
request->role,
request->includeQualifiers,
request->includeClassOrigin,
request->propertyList);
response->getResponseData().setObjects(cimObjects);
PEG_TRACE((TRC_DISPATCHER, Tracer::LEVEL4,
"References repository access: class = %s, count = %u.",
CSTRING(request->objectName.toString()),
cimObjects.size()));
}
// Issue Provider requests and process the respository responseData
ProviderRequests::issueAssocRequestsToProviders(
this,
request,
response,
providerInfos,
"References");
} // End of instance processing
PEG_METHOD_EXIT();
}
/**$*******************************************************
handleReferenceNamesRequest
**********************************************************/
void CIMOperationRequestDispatcher::handleReferenceNamesRequest(
CIMReferenceNamesRequestMessage* request)
{
PEG_METHOD_ENTER(TRC_DISPATCHER,
"CIMOperationRequestDispatcher::handleReferenceNamesRequest");
PEG_TRACE((TRC_DISPATCHER, Tracer::LEVEL3,
"CIMOperationRequestDispatcher::handleReferenceNames - "
"Namespace: %s Class name: %s",
CSTRING(request->nameSpace.getString()),
CSTRING(request->objectName.toString())));
// validate className and objectClassName same. This is
// an invariant for the handleAssoc, etc functions.
PEGASUS_DEBUG_ASSERT(
request->className == request->objectName.getClassName());
if (_rejectAssociationTraversalDisabled(request,"ReferenceNames"))
{
PEG_METHOD_EXIT();
return;
}
// Validate role parameter syntax
if (_rejectInvalidRoleParameter(request, request->role, "role"))
{
PEG_METHOD_EXIT();
return;
}
if (_rejectInvalidClassParameter(request, request->nameSpace,
request->objectName))
{
PEG_METHOD_EXIT();
return;
}
if (request->isClassRequest)
{
//
// For Class requests, get the results from the repository
//
PEG_TRACE_CSTRING(TRC_DISPATCHER, Tracer::LEVEL4,
"ReferenceNames executing Class request");
Array<CIMObjectPath> objectNames =
_repository->referenceNames(
request->nameSpace,
request->objectName,
request->resultClass,
request->role);
AutoPtr<CIMReferenceNamesResponseMessage> response(
dynamic_cast<CIMReferenceNamesResponseMessage*>(
request->buildResponse()));
// Flag to indicate that these are class objects is passed
// from request in buildResponse above.
response->getResponseData().setInstanceNames(objectNames);
_enqueueResponse(request, response.release());
}
// else Instance operation
else
{
//
// For Instance requests, get results from providers and the repository
// Determine list of providers for this request
//
ProviderInfoList providerInfos = _lookupAllAssociationProviders(
request->nameSpace,
request->objectName,
request->resultClass,
String::EMPTY);
// If no provider is registered and the repository isn't the default,
// return CIM_ERR_NOT_SUPPORTED
if (_rejectNoProvidersOrRepository(request, providerInfos))
{
PEG_METHOD_EXIT();
return;
}
// Get objectNames from repository if repository
// is default provider.
AutoPtr<CIMReferenceNamesResponseMessage> response;
if (_repository->isDefaultInstanceProvider())
{
response.reset(dynamic_cast<CIMReferenceNamesResponseMessage*>(
request->buildResponse()));
Array<CIMObjectPath> objectNames = _repository->referenceNames(
request->nameSpace,
request->objectName,
request->resultClass,
request->role);
response->getResponseData().setInstanceNames(objectNames);
PEG_TRACE((TRC_DISPATCHER, Tracer::LEVEL4,
"ReferenceNames repository access: class = %s, count = %u.",
CSTRING(request->objectName.toString()),
objectNames.size()));
}
// Issue Provider requests and process the respository responseData
// NOTE: This is a template
ProviderRequests::issueAssocRequestsToProviders(
this,
request,
response,
providerInfos,
"ReferenceNames");
} // End of instance processing
PEG_METHOD_EXIT();
}
/**$*******************************************************
handleGetPropertyRequest
**********************************************************/
void CIMOperationRequestDispatcher::handleGetPropertyRequest(
CIMGetPropertyRequestMessage* request)
{
PEG_METHOD_ENTER(TRC_DISPATCHER,
"CIMOperationRequestDispatcher::handleGetPropertyRequest");
CIMName className = request->instanceName.getClassName();
ProviderInfo providerInfo = _lookupInstanceProvider(
request->nameSpace,
className);
if (providerInfo.hasProvider)
{
CIMGetPropertyRequestMessage* requestCopy =
new CIMGetPropertyRequestMessage(*request);
if (providerInfo.providerIdContainer.get() != 0)
{
requestCopy->operationContext.insert(
*providerInfo.providerIdContainer.get());
}
CIMGetPropertyRequestMessage* requestCallbackCopy =
new CIMGetPropertyRequestMessage(*requestCopy);
_forwardRequestToSingleProvider(
providerInfo,
requestCopy,
requestCallbackCopy);
}
else if (_repository->isDefaultInstanceProvider())
{
CIMValue value =
_repository->getProperty(
request->nameSpace,
request->instanceName,
request->propertyName);
AutoPtr<CIMGetPropertyResponseMessage> response(
dynamic_cast<CIMGetPropertyResponseMessage*>(
request->buildResponse()));
response->value = value;
_enqueueResponse(request, response.release());
}
else // No provider is registered and the repository isn't the default
{
CIMResponseMessage* response = request->buildResponse();
response->cimException =
PEGASUS_CIM_EXCEPTION(CIM_ERR_NOT_SUPPORTED, String::EMPTY);
_enqueueResponse(request, response);
}
PEG_METHOD_EXIT();
}
/**$*******************************************************
handleSetPropertyRequest
**********************************************************/
void CIMOperationRequestDispatcher::handleSetPropertyRequest(
CIMSetPropertyRequestMessage* request)
{
PEG_METHOD_ENTER(TRC_DISPATCHER,
"CIMOperationRequestDispatcher::handleSetPropertyRequest");
_fixSetPropertyValueType(request);
CIMName className = request->instanceName.getClassName();
ProviderInfo providerInfo = _lookupInstanceProvider(
request->nameSpace,
className);
if (providerInfo.hasProvider)
{
CIMSetPropertyRequestMessage* requestCopy =
new CIMSetPropertyRequestMessage(*request);
if (providerInfo.providerIdContainer.get() != 0)
{
requestCopy->operationContext.insert(
*providerInfo.providerIdContainer.get());
}
CIMSetPropertyRequestMessage* requestCallbackCopy =
new CIMSetPropertyRequestMessage(*requestCopy);
_forwardRequestToSingleProvider(
providerInfo,
requestCopy,
requestCallbackCopy);
}
else if (_repository->isDefaultInstanceProvider())
{
_repository->setProperty(
request->nameSpace,
request->instanceName,
request->propertyName,
request->newValue);
PEG_TRACE((TRC_DISPATCHER, Tracer::LEVEL3,
"CIMOperationRequestDispatcher::handleSetPropertyRequest - "
"Namespace: %s Instance Name: %s Property Name: %s New "
"Value: %s",
CSTRING(request->nameSpace.getString()),
CSTRING(request->instanceName.getClassName().getString()),
CSTRING(request->propertyName.getString()),
CSTRING(request->newValue.toString())));
AutoPtr<CIMSetPropertyResponseMessage> response(
dynamic_cast<CIMSetPropertyResponseMessage*>(
request->buildResponse()));
_enqueueResponse(request, response.release());
}
else // No provider is registered and the repository isn't the default
{
CIMResponseMessage* response = request->buildResponse();
response->cimException =
PEGASUS_CIM_EXCEPTION(CIM_ERR_NOT_SUPPORTED, String::EMPTY);
_enqueueResponse(request, response);
}
PEG_METHOD_EXIT();
}
/**$*******************************************************
handleGetQualifierRequest
**********************************************************/
void CIMOperationRequestDispatcher::handleGetQualifierRequest(
CIMGetQualifierRequestMessage* request)
{
PEG_METHOD_ENTER(TRC_DISPATCHER,
"CIMOperationRequestDispatcher::handleGetQualifierRequest");
CIMQualifierDecl cimQualifierDecl =
_repository->getQualifier(
request->nameSpace,
request->qualifierName);
PEG_TRACE((TRC_DISPATCHER, Tracer::LEVEL3,
"CIMOperationRequestDispatcher::handleGetQualifierRequest - "
"Namespace: %s Qualifier Name: %s",
CSTRING(request->nameSpace.getString()),
CSTRING(request->qualifierName.getString())));
AutoPtr<CIMGetQualifierResponseMessage> response(
dynamic_cast<CIMGetQualifierResponseMessage*>(
request->buildResponse()));
response->cimQualifierDecl = cimQualifierDecl;
_enqueueResponse(request, response.release());
PEG_METHOD_EXIT();
}
/**$*******************************************************
handleSetQualifierRequest
**********************************************************/
void CIMOperationRequestDispatcher::handleSetQualifierRequest(
CIMSetQualifierRequestMessage* request)
{
PEG_METHOD_ENTER(TRC_DISPATCHER,
"CIMOperationRequestDispatcher::handleSetQualifierRequest");
_repository->setQualifier(
request->nameSpace,
request->qualifierDeclaration);
PEG_TRACE((TRC_DISPATCHER, Tracer::LEVEL3,
"CIMOperationRequestDispatcher::handleSetQualifierRequest - "
"Namespace: %s Qualifier Name: %s",
CSTRING(request->nameSpace.getString()),
CSTRING(request->qualifierDeclaration.getName().getString())));
AutoPtr<CIMSetQualifierResponseMessage> response(
dynamic_cast<CIMSetQualifierResponseMessage*>(
request->buildResponse()));
_enqueueResponse(request, response.release());
PEG_METHOD_EXIT();
}
/**$*******************************************************
handleDeleteQualifierRequest
**********************************************************/
void CIMOperationRequestDispatcher::handleDeleteQualifierRequest(
CIMDeleteQualifierRequestMessage* request)
{
PEG_METHOD_ENTER(TRC_DISPATCHER,
"CIMOperationRequestDispatcher::handleDeleteQualifierRequest");
_repository->deleteQualifier(
request->nameSpace,
request->qualifierName);
PEG_TRACE((TRC_DISPATCHER, Tracer::LEVEL3,
"CIMOperationRequestDispatcher::handleDeleteQualifierRequest - "
"Namespace: %s Qualifier Name: %s",
CSTRING(request->nameSpace.getString()),
CSTRING(request->qualifierName.getString())));
AutoPtr<CIMDeleteQualifierResponseMessage> response(
dynamic_cast<CIMDeleteQualifierResponseMessage*>(
request->buildResponse()));
_enqueueResponse(request, response.release());
PEG_METHOD_EXIT();
}
/**$*******************************************************
handleEnumerateQualifiersRequest
**********************************************************/
void CIMOperationRequestDispatcher::handleEnumerateQualifiersRequest(
CIMEnumerateQualifiersRequestMessage* request)
{
PEG_METHOD_ENTER(TRC_DISPATCHER,
"CIMOperationRequestDispatcher::handleEnumerateQualifiersRequest");
Array<CIMQualifierDecl> qualifierDeclarations =
_repository->enumerateQualifiers(request->nameSpace);
PEG_TRACE((TRC_DISPATCHER,Tracer::LEVEL3,
"CIMOperationRequestDispatcher::handleEnumerateQualifiersRequest - "
"Namespace: %s",
CSTRING(request->nameSpace.getString())));
AutoPtr<CIMEnumerateQualifiersResponseMessage> response(
dynamic_cast<CIMEnumerateQualifiersResponseMessage*>(
request->buildResponse()));
response->qualifierDeclarations = qualifierDeclarations;
_enqueueResponse(request, response.release());
PEG_METHOD_EXIT();
}
/**$*******************************************************
handleExecQueryRequest
**********************************************************/
void CIMOperationRequestDispatcher::handleExecQueryRequest(
CIMExecQueryRequestMessage* request)
{
PEG_METHOD_ENTER(TRC_DISPATCHER,
"CIMOperationRequestDispatcher::handleExecQueryRequest");
AutoPtr<CIMExecQueryResponseMessage> response(
dynamic_cast<CIMExecQueryResponseMessage*>(
request->buildResponse()));
Boolean exception = false;
#ifdef PEGASUS_DISABLE_EXECQUERY
response->cimException =
PEGASUS_CIM_EXCEPTION(CIM_ERR_NOT_SUPPORTED, String::EMPTY);
exception=true;
#else
CIMException cimException;
if (!QuerySupportRouter::routeHandleExecQueryRequest(this,request,
cimException))
{
response->cimException = cimException;
exception = true;
}
#endif
if (exception)
{
_enqueueResponse(request, response.release());
PEG_METHOD_EXIT();
return;
}
PEG_METHOD_EXIT();
return;
}
/**$*******************************************************
handleInvokeMethodRequest
**********************************************************/
void CIMOperationRequestDispatcher::handleInvokeMethodRequest(
CIMInvokeMethodRequestMessage* request)
{
PEG_METHOD_ENTER(TRC_DISPATCHER,
"CIMOperationRequestDispatcher::handleInvokeMethodRequest");
_fixInvokeMethodParameterTypes(request);
CIMName className = request->instanceName.getClassName();
if (!_checkExistenceOfClass(request->nameSpace, className))
{
PEG_TRACE((TRC_DISPATCHER, Tracer::LEVEL1,
"CIMOperationRequestDispatcher::handleInvokeMethodRequest - "
"CIM class does not exist exception has occurred. "
"Namespace: %s Class Name: %s",
CSTRING(request->nameSpace.getString()),
CSTRING(className.getString()) ));
PEG_METHOD_EXIT();
throw PEGASUS_CIM_EXCEPTION(CIM_ERR_NOT_FOUND, className.getString());
}
// Find Provider for this method
ProviderIdContainer* providerIdContainer=NULL;
ProviderInfo providerInfo(className);
// First determine if there is an internal provider. If not, try
// for a registered provider.
if (!_lookupInternalProvider(request->nameSpace, className, providerInfo))
{
// check the class name for a registered provider for this namespace
// classname and methodname. There can be only one.
String providerName = _lookupMethodProvider(
request->nameSpace,
className,
request->methodName,
&providerIdContainer);
// if provider name returned, set the provider info to
// go to providerManagerService
if (providerName.size() != 0)
{
providerInfo.addProviderInfo(
_providerManagerServiceId,
true,
false);
PEG_TRACE((TRC_DISPATCHER, Tracer::LEVEL1,
"CIMOperationRequestDispatcher::invokeMethodProvider - "
"Namespace: %s Class Name: %s"
" Provider Name: %s found. ",
CSTRING(request->nameSpace.getString()),
CSTRING(className.getString()),
CSTRING(providerName) ));
}
else
{
PEG_TRACE((TRC_DISPATCHER, Tracer::LEVEL1,
"CIMOperationRequestDispatcher::invokeMethodProvider %s - "
"Namespace: %s Class Name: %s Service Name: %s "
"Control Provider Name %s"
"Provider Name: %s found. ",
((providerInfo.controlProviderName.size() ==0)?
"Intern": "Extern"),
CSTRING(request->nameSpace.getString()),
CSTRING(className.getString()),
_getServiceName(_providerManagerServiceId),
CSTRING(providerInfo.controlProviderName),
CSTRING(providerName) ));
}
}
if (providerInfo.hasProvider)
{
CIMInvokeMethodRequestMessage* requestCopy =
new CIMInvokeMethodRequestMessage(*request);
CIMInvokeMethodRequestMessage* requestCallbackCopy =
new CIMInvokeMethodRequestMessage(*requestCopy);
if (providerIdContainer != NULL)
{
requestCopy->operationContext.insert(*providerIdContainer);
delete providerIdContainer;
providerIdContainer = NULL;
}
_forwardRequestToSingleProvider(
providerInfo,
requestCopy,
requestCallbackCopy);
}
else // No provider for this method.
{
// No provider or control provider. Generate exception
CIMResponseMessage* response = request->buildResponse();
response->cimException =
PEGASUS_CIM_EXCEPTION(CIM_ERR_METHOD_NOT_AVAILABLE,
request->methodName.getString());
_enqueueResponse(request, response);
}
PEG_METHOD_EXIT();
}
//KS_PULL_BEGIN
/*************************************************************************
//
// Pull operations introduced in Pegasus 2.14 per DMTF DSP200 - V 1.4
//
*************************************************************************/
/**$**************************************************************************
**
** handleOpenEnumerateInstancesRequest
**
*****************************************************************************/
bool CIMOperationRequestDispatcher::handleOpenEnumerateInstancesRequest(
CIMOpenEnumerateInstancesRequestMessage* request)
{
PEG_METHOD_ENTER(TRC_DISPATCHER,
"CIMOperationRequestDispatcher::handleOpenEnumerateInstancesRequest");
PEG_TRACE((TRC_DISPATCHER, Tracer::LEVEL4,
"OpenEnumerateInstances request namespace=%s class=%s "
"deepInheritance=%s "
"includeClassOrigin=%s "
"propertyList=%s "
"filterQueryLanguage=%s "
"filterQuery=%s "
"operationTimeout=%s "
"continueOnError=%s "
"maxObjectCount=%u "
"messageId=%s",
CSTRING(request->nameSpace.getString()),
CSTRING(request->className.getString()),
boolToString(request->deepInheritance),
boolToString(request->includeClassOrigin),
CSTRING(request->propertyList.toString()),
CSTRING(request->filterQueryLanguage),
CSTRING(request->filterQuery),
CSTRING(request->operationTimeout.toString()),
boolToString(request->continueOnError),
request->maxObjectCount,
CSTRING(request->messageId) ));
// get the class name or generate error if class not found for target
// namespace.
CIMName className = request->className;
CIMConstClass cimClass;
if (_rejectInvalidClassParameter(request, cimClass))
{
PEG_METHOD_EXIT();
return true;
}
// Test the common open request input parameters and reject if any
// are incorrect. Tests filterQuery, continueOnError, operationTimeout
// and maxObjectCount
Uint32 operationMaxObjectCount;
if (_rejectIfPullParametersFailTests(request,operationMaxObjectCount,
ENABLE_FQL_FILTER))
{
PEG_METHOD_EXIT();
return true;
}
// If DeepInheritance==false and no PropertyList was specified by the
// client, the provider PropertyList should contain all the properties
// in the specified class. This forces subclasses to handle defined
// list rather than their full property list.
if (!request->deepInheritance && request->propertyList.isNull())
{
_buildPropertyListWithTags(cimClass, request->propertyList);
}
//
// Get names of descendent classes with indication of whether they
// have providers. providerCount is count of number of entries that
// actually have providers. Others are subclasses without providers.
//
ProviderInfoList providerInfos = _lookupAllInstanceProviders(
request->nameSpace, request->className);
// If no provider is registered and the repository isn't the default,
// return CIM_ERR_NOT_SUPPORTED.
// KS_PULL_QUESTION The following say if no provider and no
// repository return error. Aggregation(
// providerInfo.se
// KS_TODO Should we not just return nothing. See bug 9893
if (_rejectNoProvidersOrRepository(request, providerInfos))
{
PEG_METHOD_EXIT();
return true;
}
//
// Try to compile the filter. Get an exception only if the FQL
// filter compiler generates an exception.
//
#ifdef PEGASUS_ENABLE_FQL
bool filterResponse = false;
//// XCOUT << "Calling handleFQLQueryRequest " << endl;
//// FQLQueryExpressionRep* qx = handleFQLQueryRequest(request);
//// if (qx == NULL)
//// {
//// // exception generated
//// XCOUT << "Exception generated " << endl;
//// return true;
//// }
////
//// XCOUT << "Called handleFQLQueryRequest " << endl;
//// printf("pointer %p\n",qx->_stmt);
////
//// FQLQueryStatement* qs = qx->_stmt;
////
//// XCOUT << "Called handleFQLQueryRequest " << endl;
AutoPtr<FQLQueryExpressionRep> qx;
AutoPtr<FQLQueryStatement> queryStatement;
if (request->filterQueryLanguage.size() != 0)
{
bool exception = false;
CIMException cimException;
if (request->filterQueryLanguage != "DMTF:FQL")
{
cimException = PEGASUS_CIM_EXCEPTION(
CIM_ERR_QUERY_LANGUAGE_NOT_SUPPORTED,
request->filterQueryLanguage);
exception = true;
}
else
{
try
{
queryStatement.reset(new FQLQueryStatement());
FQLParser::parse(request->filterQuery, *queryStatement);
qx.reset(new FQLQueryExpressionRep(request->filterQueryLanguage,
queryStatement.get() ));
filterResponse = true;
}
catch (ParseError& e)
{
String text = request->filterQuery + " " + e.getMessage();
cimException =
PEGASUS_CIM_EXCEPTION(
CIM_ERR_INVALID_QUERY, text);
exception=true;
}
catch (...)
{
exception=true;
}
}
if (exception)
{
CIMResponseMessage* response = request->buildResponse();
response->cimException = cimException;
_enqueueResponse(request, response);
PEG_METHOD_EXIT();
return true;
}
}
#endif
//
// Setup the EnumerationContext. Returns pointer to object
//
EnumerationContext* enumerationContext =
_enumerationContextTable->createContext(
request,
CIM_PULL_INSTANCES_WITH_PATH_REQUEST_MESSAGE,
CIMResponseData::RESP_INSTANCES);
if (enumerationContext == NULL)
{
_rejectCreateContextFailed(request);
return true;
}
// Set properties from request into the context
enumerationContext->setRequestProperties(
request->includeClassOrigin, request->propertyList);
// This trace connects the request parameters to the
// ContextId which can be used to connect traces together.
// This adds ContextId
PEG_TRACE((TRC_DISPATCHER, Tracer::LEVEL4,
"OpenEnumerateInstances request started "
"ContextId=%s namespace=%s class=%s "
"operationTimeout=%s "
"maxObjectCount=%u",
CSTRING(enumerationContext->getContextId()),
CSTRING(request->nameSpace.getString()),
CSTRING(request->className.getString()),
CSTRING(request->operationTimeout.toString()),
request->maxObjectCount));
// Build a corresponding EnumerateInstancesRequest to send to
// providers. Do not pass the Pull operations request
// on to Providers; create EnumerateInstancesRequest message to
// activate providers.
// NOTE: includeQualifiers NOT part of Pull operation so force to
// false
// The messageID is set to the enumerationContext contextID to
// allow the ProviderAgentContainer to identify messages associated
// with a particular enumerationSequence when called by the
// idleTimeCleanup functions.
CIMEnumerateInstancesRequestMessage* internalRequest =
new CIMEnumerateInstancesRequestMessage(
enumerationContext->getContextId(),
request->nameSpace,
request->className,
request->deepInheritance,
false, // include qualifiers false
request->includeClassOrigin,
request->propertyList,
request->queueIds,
request->authType,
request->userName);
internalRequest->operationContext = request->operationContext;
internalRequest->internalOperation = true;
// AutoPtr to delete internalRequest at end of handler
AutoPtr<CIMEnumerateInstancesRequestMessage>
requestDestroyer(internalRequest);
// Set up an aggregate object and save a copy of the original request.
// NOTE: Build the poA for the EnumerateRequest, not the corresponding
// pull operation.
OperationAggregate* poA= new OperationAggregate(
new CIMEnumerateInstancesRequestMessage(*internalRequest),
internalRequest->className,
internalRequest->nameSpace,
providerInfos.providerCount,
true, // completeHostAndNamespace = false
true); // _hasPropList = true
//
// Set Open... operation parameters into the operationAggregate
//
poA->setPullOperation(enumerationContext);
#ifdef PEGASUS_ENABLE_FQL
if (filterResponse)
{
queryStatement.release();
poA ->setFilterParameters(qx.release(),
request->filterQueryLanguage);
}
#endif
//
// If repository as instance provider is enabled, get instances
// from the repository
//
if (_enumerateFromRepository(internalRequest, poA, providerInfos))
{
CIMResponseMessage* response = poA->removeResponse(0);
// Forward the Enum response. It will be mapped into
// the EnumerateionContext cache.
_forwardResponseForAggregation(
new CIMEnumerateInstancesRequestMessage(*internalRequest),
poA, response);
}
// Issue requests to providers before we send open response to get
// provider responses before we build response. This required to allow
// building initial response of max requested size
ProviderRequests::issueEnumerationRequestsToProviders(
this,
internalRequest,
providerInfos,
poA,
"openEnumerateIntances");
// Cannot use Operation Aggregate after this point since we are not
// sure when it might be deleted unless the providerCount is != 0
//
// Issue the Response to the Open Request. This may be issued immediatly
// or delayed by setting information into the enumeration context
// if there are no responses from providers ready
// to avoid issuing empty responses. If there are no responses expected
// at all from any source, the openResponse will be issued immediatly.
CIMOpenEnumerateInstancesResponseMessage* openResponse(
dynamic_cast<CIMOpenEnumerateInstancesResponseMessage*>(
request->buildResponse()));
// Enumeration Context must not be used after this call
bool releaseRequest = issueOpenOrPullResponseMessage(
request,
openResponse,
enumerationContext,
operationMaxObjectCount,
requireCompleteResponses);
PEG_METHOD_EXIT();
return releaseRequest;
}
/**$**************************************************************************
**
** handleOpenEnumerateInstancePathsRequest
**
*****************************************************************************/
bool CIMOperationRequestDispatcher::handleOpenEnumerateInstancePathsRequest(
CIMOpenEnumerateInstancePathsRequestMessage* request)
{
PEG_METHOD_ENTER(TRC_DISPATCHER,
"CIMOperationRequestDispatcher::"
"handleOpenEnumerateInstancePathsRequest");
PEG_TRACE((TRC_DISPATCHER, Tracer::LEVEL4,
"OpenEnumerateInstancePaths request namespace=%s class %s "
"filterQueryLanguage=%s "
"filterQuery=%s "
"operationTimeout=%s "
"continueOnError=%s "
"maxObjectCount=%u",
CSTRING(request->nameSpace.getString()),
CSTRING(request->className.getString()),
CSTRING(request->filterQueryLanguage),
CSTRING(request->filterQuery),
CSTRING(request->operationTimeout.toString()),
boolToString(request->continueOnError),
request->maxObjectCount ));
// get the class name
// FUTURE(KS) can we eliminate this completely??
CIMName className = request->className;
CIMConstClass cimClass;
if (_rejectInvalidClassParameter(request, cimClass))
{
PEG_METHOD_EXIT();
return true;
}
// Test the common open request input parameters and reject if any
// are incorrect. Tests filterQuery, continueOnError, operationTimeout
// and maxObjectCount
Uint32 operationMaxObjectCount;
if (_rejectIfPullParametersFailTests(request,operationMaxObjectCount,false))
{
PEG_METHOD_EXIT();
return true;
}
//
// Get names of descendent classes and list of providers
// For Enumerate Operations, the list of providers is used for both
// repository and provider requests.
//
ProviderInfoList providerInfos = _lookupAllInstanceProviders(
request->nameSpace, request->className);
// If no provider is registered and the repository isn't the default,
// return CIM_ERR_NOT_SUPPORTED.
// KS_PULL_QUESTION The following says if no provider and no
// repository return error. Should we not just return
// nothing.
if (_rejectNoProvidersOrRepository(request, providerInfos))
{
PEG_METHOD_EXIT();
return true;
}
//
// Setup the EnumerationContext. Returns pointer to object
//
EnumerationContext* enumerationContext =
_enumerationContextTable->createContext(
request,
CIM_PULL_INSTANCE_PATHS_REQUEST_MESSAGE,
CIMResponseData::RESP_INSTNAMES);
if (enumerationContext == NULL)
{
_rejectCreateContextFailed(request);
PEG_METHOD_EXIT();
return true;
}
// Build a corresponding EnumerateInstancesNamesRequest to send to
// providers. We do not pass the Pull operations request
// on to Providers but use the EnumerateInstancesRequest message to
// activate providers.
// NOTE: includeQualifiers NOT part of Pull operation
CIMEnumerateInstanceNamesRequestMessage* internalRequest =
new CIMEnumerateInstanceNamesRequestMessage(
enumerationContext->getContextId(),
request->nameSpace,
request->className,
request->queueIds,
request->authType,
request->userName);
internalRequest->operationContext = request->operationContext;
internalRequest->internalOperation = true;
// AutoPtr to delete at end of handler
AutoPtr<CIMEnumerateInstanceNamesRequestMessage> dummy(internalRequest);
//
// Set up op aggregate object and save a copy of the original request.
// NOTE: Build the poA for the EnumerateRequest, not the corresponding
// pull operation.
//
OperationAggregate* poA= new OperationAggregate(
new CIMEnumerateInstanceNamesRequestMessage(*internalRequest),
internalRequest->className,
internalRequest->nameSpace,
providerInfos.providerCount,
true, // completeHostAndNamespace = false
false); // No property List for this operation
//
// Set Open... operation parameters into the operationAggregate
// Includes setting namespace that is used to complete host and naespace
// in responses
//
poA->setPullOperation(enumerationContext);
// gather up the repository responses and send it to out as one response
// with many instances
//
if (_enumerateFromRepository(internalRequest, poA, providerInfos))
{
CIMResponseMessage* response = poA->removeResponse(0);
_forwardResponseForAggregation(
new CIMEnumerateInstanceNamesRequestMessage(*internalRequest),
poA, response);
}
ProviderRequests::issueEnumerationRequestsToProviders(
this,
internalRequest,
providerInfos,
poA,
"openEnumerateInstanceNames");
// Cannot use Operation Aggregate after this point since we are not
// sure when it might be deleted unless the providerCount is != 0
//
// Issue the Response to the Open Request. This may be issued immediatly
// or delayed by setting information into the enumeration context
// if there are no responses from providers ready
// to avoid issuing empty responses. If there are no responses expected
// at all from any source, the openResponse will be issued immediatly.
CIMOpenEnumerateInstancePathsResponseMessage* openResponse(
dynamic_cast<CIMOpenEnumerateInstancePathsResponseMessage*>(
request->buildResponse()));
// Enumeration Context must not be used after this call
bool releaseRequest = issueOpenOrPullResponseMessage(
request,
openResponse,
enumerationContext,
operationMaxObjectCount,
requireCompleteResponses);
PEG_METHOD_EXIT();
return releaseRequest;
}
/**$*******************************************************
handleOpenReferenceInstancesRequest
**********************************************************/
bool CIMOperationRequestDispatcher::handleOpenReferenceInstancesRequest(
CIMOpenReferenceInstancesRequestMessage* request)
{
PEG_METHOD_ENTER(TRC_DISPATCHER,
"CIMOperationRequestDispatcher::handleOpenReferenceInstancesRequest");
PEG_TRACE((TRC_DISPATCHER, Tracer::LEVEL4,
"OpenReferenceInstances request namespace=%s object=%s "
"resultClass=%s "
"role=%s "
"includeClassOrigin=%s "
"propertyList=%s "
"filterQueryLanguage=%s "
"filterQuery=%s "
"operationTimeout=%s "
"continueOnError=%s "
"maxObjectCount=%u",
CSTRING(request->nameSpace.getString()),
CSTRING(request->objectName.toString()),
CSTRING(request->resultClass.getString()),
CSTRING(request->role),
boolToString(request->includeClassOrigin),
CSTRING(request->propertyList.toString()),
CSTRING(request->filterQueryLanguage),
CSTRING(request->filterQuery),
CSTRING(request->operationTimeout.toString()),
boolToString(request->continueOnError),
request->maxObjectCount ));
// validate className and objectClassName same. This is
// an invariant for the handleAssoc, etc functions.
PEGASUS_DEBUG_ASSERT(
request->className == request->objectName.getClassName());
if (_rejectAssociationTraversalDisabled(request,"OpenReferenceInstances"))
{
PEG_METHOD_EXIT();
return true;
}
if (_rejectInvalidRoleParameter(request, request->role, "role"))
{
PEG_METHOD_EXIT();
return true;
}
if (_rejectInvalidObjectPathParameter(request, request->objectName))
{
PEG_METHOD_EXIT();
return true;
}
// Test the common open request input parameters and reject if any
// are incorrect. Tests filterQuery, continueOnError, operationTimeout
// and maxObjectCount
Uint32 operationMaxObjectCount;
if (_rejectIfPullParametersFailTests(request,operationMaxObjectCount,
ENABLE_FQL_FILTER))
{
PEG_METHOD_EXIT();
return true;
}
// KS_TODO - Should we use checkClassParameter here in place of
// _checkExistence...
if (!_checkExistenceOfClass(
request->nameSpace, request->objectName.getClassName()))
{
PEG_METHOD_EXIT();
throw PEGASUS_CIM_EXCEPTION(
CIM_ERR_INVALID_PARAMETER,
request->objectName.getClassName().getString());
}
//
// Try to compile the filter. Get an exception only if the FQL
// filter compiler generates an exception.
// Result saved in OperationAggregate later in process
//
#ifdef PEGASUS_ENABLE_FQL
bool filterResponse = false;
//// FQLQueryExpressionRep* qx = handleFQLQueryRequest(request);
//// if (qx == NULL)
//// {
//// // exception generated
//// XCOUT << "Exception generated " << endl;
//// return true;
//// }
AutoPtr<FQLQueryExpressionRep> qx;
AutoPtr<FQLQueryStatement> queryStatement;
if (request->filterQueryLanguage.size() != 0)
{
bool exception = false;
CIMException cimException;
if (request->filterQueryLanguage != "DMTF:FQL")
{
cimException = PEGASUS_CIM_EXCEPTION(
CIM_ERR_QUERY_LANGUAGE_NOT_SUPPORTED,
request->filterQueryLanguage);
exception = true;
}
else
{
if (request->filterQuery.size() != 0)
{
try
{
queryStatement.reset(new FQLQueryStatement());
FQLParser::parse(request->filterQuery, *queryStatement);
qx.reset(new FQLQueryExpressionRep(
request->filterQueryLanguage,queryStatement.get() ));
filterResponse = true;
}
catch (ParseError& e)
{
String text = request->filterQuery + " " + e.getMessage();
cimException =
PEGASUS_CIM_EXCEPTION(
CIM_ERR_INVALID_QUERY, text);
exception=true;
}
catch (...)
{
exception=true;
}
}
}
if (exception)
{
CIMResponseMessage* response = request->buildResponse();
response->cimException = cimException;
_enqueueResponse(request, response);
PEG_METHOD_EXIT();
return true;
}
}
#endif
ProviderInfoList providerInfos = _lookupAllAssociationProviders(
request->nameSpace,
request->objectName,
request->resultClass,
String::EMPTY);
// If no provider is registered and the repository isn't the default,
// return CIM_ERR_NOT_SUPPORTED
if (_rejectNoProvidersOrRepository(request, providerInfos))
{
PEG_METHOD_EXIT();
return true;
}
//
// Request the instances from the repository, as necessary.
// Instances go directly into a response because the are returned as
// a single array.
//
Array<CIMObject> cimObjects;
if (_repository->isDefaultInstanceProvider())
{
cimObjects = _repository->references(
request->nameSpace,
request->objectName,
request->resultClass,
request->role,
false, // force includeQualifiers to false
request->includeClassOrigin,
request->propertyList);
PEG_TRACE((TRC_DISPATCHER, Tracer::LEVEL4,
"OpenReferenceInstances repository access: class = %s, count = %u.",
(const char*)request->objectName.toString().getCString(),
cimObjects.size()));
// FUTURE - Why not just put this directly to the enumcache.
// If there was an exception is is caught outside of this and
// not sure any of the other checking on response really gains
// anything.
}
// Build Open Response message. We are going to issue some sort of
// response whether there are providers, repository returns or not.
AutoPtr<CIMOpenReferenceInstancesResponseMessage> openResponse;
openResponse.reset(dynamic_cast<CIMOpenReferenceInstancesResponseMessage*>(
request->buildResponse()));
// If there are no providers and nothing from repository
// return empty and exit
// FUTURE(KS) We should be able to drop through to normal code
// and drop this completely.
if ((providerInfos.providerCount == 0) && (cimObjects.size() == 0))
{
// We have no providers to call and nothing from repository.
// Return empty
PEG_TRACE((TRC_DISPATCHER, Tracer::LEVEL4,
"Repository Empty, NO providers for %s",
(const char *)request->className.getString().getCString()));
openResponse->endOfSequence = true;
_enqueueResponse(request, openResponse.release());
PEG_METHOD_EXIT();
return true;
}
//
// Process as multi operation enumeration. 1. Build context, build
// internalRequest for providers and issue to providers, build open
// response, get current objects (with wait) and enqueue open
// response.
//
// Create new context object.
EnumerationContext* enumerationContext =
_enumerationContextTable->createContext(
request,
CIM_PULL_INSTANCES_WITH_PATH_REQUEST_MESSAGE,
CIMResponseData::RESP_OBJECTS);
if (enumerationContext == NULL)
{
_rejectCreateContextFailed(request);
PEG_METHOD_EXIT();
return true;
}
enumerationContext->setRequestProperties(
request->includeClassOrigin, request->propertyList);
// Build corresponding CIMReferencesRequestMessage to issue to
// providers. We do not pass the Open operations request
// on to Providers but use the EnumerateInstancesRequest message to
// activate providers. NOTE: includeQualifiers NOT part of Pull operation
CIMReferencesRequestMessage* internalRequest =
new CIMReferencesRequestMessage(
enumerationContext->getContextId(),
request->nameSpace,
request->objectName,
request->resultClass,
request->role,
false, // force includeQualifiers to false
request->includeClassOrigin,
request->propertyList,
request->queueIds,
false, // Not a class request
request->authType,
request->userName);
internalRequest->operationContext = request->operationContext;
internalRequest->internalOperation = true;
// AutoPtr to delete at end of handler
AutoPtr<CIMReferencesRequestMessage> requestDesroyer(internalRequest);
//
// Set up an aggregate object and save the original request message
//
OperationAggregate* poA = new OperationAggregate(
new CIMReferencesRequestMessage(*internalRequest),
internalRequest->objectName.getClassName(),
internalRequest->nameSpace,
providerInfos.providerCount,
true, // requiresHostnameCompletion
true); // hasPropList
//
// Set Open... operation parameters into the operationAggregate
// since operationAggregate is what is returned from providers.
//
poA->setPullOperation(enumerationContext);
#ifdef PEGASUS_ENABLE_FQL
if (filterResponse)
{
queryStatement.release();
poA ->setFilterParameters(qx.release(),
request->filterQueryLanguage);
}
#endif
// If response from repository not empty, forward for aggregation.
if (cimObjects.size() != 0)
{
AutoPtr<CIMReferencesResponseMessage> internalResponse;
internalResponse.reset(dynamic_cast<CIMReferencesResponseMessage*>(
internalRequest->buildResponse()));
internalResponse->getResponseData().setObjects(cimObjects);
poA->incTotalIssued();
// Send the repository results for aggregation
// directly to callback (includes response).
//
_forwardResponseForAggregation(
new CIMReferencesRequestMessage(*internalRequest),
poA,
internalResponse.release());
}
ProviderRequests::issueOpenAssocRequestMsgsToProviders(
this,
internalRequest,
providerInfos,
poA,
"OpenReferenceInstances"
);
// Enumeration Context must not be used after this call
bool releaseRequest = issueOpenOrPullResponseMessage(
request,
openResponse.release(),
enumerationContext,
operationMaxObjectCount,
requireCompleteResponses);
PEG_METHOD_EXIT();
return releaseRequest;
}
/**$*******************************************************
handleOpenReferenceInstancePathsRequest
**********************************************************/
bool CIMOperationRequestDispatcher::handleOpenReferenceInstancePathsRequest(
CIMOpenReferenceInstancePathsRequestMessage* request)
{
PEG_METHOD_ENTER(TRC_DISPATCHER,
"CIMOperationRequestDispatcher::handleOpenReferenceInstancePathsRequest");
PEG_TRACE((TRC_DISPATCHER, Tracer::LEVEL4,
"OpenReferenceInstancePaths request for Namespace=%s objectName %s "
"resultClass=%s "
"role=%s "
"filterQueryLanguage=%s "
"filterQuery=%s "
"operationTimeout=%s "
"continueOnError=%s "
"maxObjectCount=%u",
CSTRING(request->nameSpace.getString()),
CSTRING(request->objectName.toString()),
CSTRING(request->resultClass.getString()),
CSTRING(request->role),
CSTRING(request->filterQueryLanguage),
CSTRING(request->filterQuery),
CSTRING(request->operationTimeout.toString()),
boolToString(request->continueOnError),
request->maxObjectCount ));
// validate className and objectClassName same. This is
// an invariant for the handleAssoc, etc functions.
PEGASUS_DEBUG_ASSERT(
request->className == request->objectName.getClassName());
if (_rejectAssociationTraversalDisabled(request,
"OpenReferenceInstancePaths"))
{
PEG_METHOD_EXIT();
return true;
}
if (_rejectInvalidRoleParameter(request, request->role, "role"))
{
PEG_METHOD_EXIT();
return true;
}
if (_rejectInvalidObjectPathParameter(request, request->objectName))
{
PEG_METHOD_EXIT();
return true;
}
// Test the common open request input parameters and reject if any
// are incorrect. Tests filterQuery, continueOnError, operationTimeout
// and maxObjectCount
Uint32 operationMaxObjectCount;
if (_rejectIfPullParametersFailTests(request,operationMaxObjectCount,false))
{
PEG_METHOD_EXIT();
return true;
}
if (!_checkExistenceOfClass(request->nameSpace,
request->objectName.getClassName()))
{
PEG_METHOD_EXIT();
throw PEGASUS_CIM_EXCEPTION(
CIM_ERR_INVALID_PARAMETER,
request->objectName.getClassName().getString());
}
//
// Get results from providers and the repository
// Determine list of providers for this request
//
ProviderInfoList providerInfos = _lookupAllAssociationProviders(
request->nameSpace,
request->objectName,
request->resultClass,
String::EMPTY);
// If no provider is registered and the repository isn't the default,
// return CIM_ERR_NOT_SUPPORTED
if (_rejectNoProvidersOrRepository(request, providerInfos))
{
PEG_METHOD_EXIT();
return true;
}
//
// Get the instances from the repository, as necessary
//
Array<CIMObjectPath> instanceNames;
if (_repository->isDefaultInstanceProvider())
{
instanceNames = _repository->referenceNames(
request->nameSpace,
request->objectName,
request->resultClass,
request->role);
PEG_TRACE((TRC_DISPATCHER, Tracer::LEVEL4,
"OpenReferenceInstamcePaths repository access:"
" class = %s, count = %u.",
(const char*)request->objectName.toString().getCString(),
instanceNames.size()));
}
// Build Open Response message.
AutoPtr<CIMOpenReferenceInstancePathsResponseMessage> openResponse;
openResponse.reset(
dynamic_cast<CIMOpenReferenceInstancePathsResponseMessage*>(
request->buildResponse()));
if (providerInfos.providerCount == 0 && instanceNames.size() == 0)
{
//
// No provider is registered and the repository isn't the
// default. Return CIM_ERR_NOT_SUPPORTED.
PEG_TRACE((TRC_DISPATCHER, Tracer::LEVEL4,
"OpenReferenceInstancePaths Return Empty."));
openResponse->endOfSequence = true;
_enqueueResponse(request, openResponse.release());
PEG_METHOD_EXIT();
return true;
}
//
// Create new enumerationContext
//
EnumerationContext* enumerationContext =
_enumerationContextTable->createContext(
request,
CIM_PULL_INSTANCE_PATHS_REQUEST_MESSAGE,
CIMResponseData::RESP_OBJECTPATHS);
if (enumerationContext == NULL)
{
_rejectCreateContextFailed(request);
PEG_METHOD_EXIT();
return true;
}
// Build corresponding EnumerateInstancePathsRequest to send to
// providers. We do not pass the Pull operations request
// on to Providers but use the EnumerateInstancesRequest message to
// activate providers. NOTE: includeQualifiers NOT part of Pull operation
CIMReferenceNamesRequestMessage* internalRequest =
new CIMReferenceNamesRequestMessage(
enumerationContext->getContextId(),
request->nameSpace,
request->objectName,
request->resultClass,
request->role,
request->queueIds,
false,
request->authType,
request->userName);
internalRequest->operationContext = request->operationContext;
internalRequest->internalOperation = true;
// AutoPtr to delete at end of handler
AutoPtr<CIMReferenceNamesRequestMessage>
requestDestroyer(internalRequest);
//
// Set up an aggregate object and save the created internalRequest
//
OperationAggregate* poA = new OperationAggregate(
new CIMReferenceNamesRequestMessage(*internalRequest),
internalRequest->objectName.getClassName(),
internalRequest->nameSpace,
providerInfos.providerCount,
true, // completeHostAndNamespace = false
false); // No property list for this operation
//
// Set Open... operation parameters into the operationAggregate
//
poA->setPullOperation(enumerationContext);
// If any return from repository, send it to aggregator.
// Send repository response for aggregation
if (instanceNames.size() != 0)
{
AutoPtr<CIMReferenceNamesResponseMessage> internalResponse;
internalResponse.reset(dynamic_cast<CIMReferenceNamesResponseMessage*>(
internalRequest->buildResponse()));
internalResponse->getResponseData().setInstanceNames(instanceNames);
poA->incTotalIssued();
// send the repository's results for aggregation
// directly to callback (includes response).
_forwardResponseForAggregation(
new CIMReferenceNamesRequestMessage(*internalRequest),
poA,
internalResponse.release());
}
ProviderRequests::issueOpenAssocRequestMsgsToProviders(
this,
internalRequest,
providerInfos,
poA,
"OpenReferenceInstancePaths"
);
// Issue the Response to the Open Request. This may be issued immediatly
// or delayed by setting information into the enumeration context
// if there are no responses from providers ready
// to avoid issuing empty responses.
// Enumeration Context must not be used after this call
bool releaseRequest = issueOpenOrPullResponseMessage(
request,
openResponse.release(),
enumerationContext,
operationMaxObjectCount,
requireCompleteResponses);
PEG_METHOD_EXIT();
return releaseRequest;
}
/**$*******************************************************
handleOpenAssociatorInstancesRequest
**********************************************************/
bool CIMOperationRequestDispatcher::handleOpenAssociatorInstancesRequest(
CIMOpenAssociatorInstancesRequestMessage* request)
{
PEG_METHOD_ENTER(TRC_DISPATCHER,
"CIMOperationRequestDispatcher::handleOpenAssociatorInstancesRequest");
PEG_TRACE((TRC_DISPATCHER, Tracer::LEVEL4,
"OpenAssociatorInstancesRequest request namespace=%s object=%s "
"assocClass = \"%s\" "
"resultClass=%s "
"role=%s "
"resultRole = \"%s\" "
"includeClassOrigin=%s "
"propertyList=%s "
"filterQueryLanguage=%s "
"filterQuery=%s "
"operationTimeout=%s "
"continueOnError=%s "
"maxObjectCount=%u",
CSTRING(request->nameSpace.getString()),
CSTRING(request->objectName.toString()),
CSTRING(request->assocClass.getString()),
CSTRING(request->resultClass.getString()),
CSTRING(request->role),
CSTRING(request->resultClass.getString()),
boolToString(request->includeClassOrigin),
CSTRING(request->propertyList.toString()),
CSTRING(request->filterQueryLanguage),
CSTRING(request->filterQuery),
CSTRING(request->operationTimeout.toString()),
boolToString(request->continueOnError),
request->maxObjectCount ));
// validate className and objectClassName same. This is
// an invariant for the handleAssoc, etc functions.
PEGASUS_DEBUG_ASSERT(
request->className == request->objectName.getClassName());
if (_rejectAssociationTraversalDisabled(request, "OpenAssociatorInstances"))
{
PEG_METHOD_EXIT();
return true;
}
if (_rejectInvalidRoleParameter(request, request->role, "role"))
{
PEG_METHOD_EXIT();
return true;
}
if (_rejectInvalidRoleParameter(request, request->resultRole, "resultRole"))
{
PEG_METHOD_EXIT();
return true;
}
if (_rejectInvalidObjectPathParameter(request, request->objectName))
{
PEG_METHOD_EXIT();
return true;
}
// Test the common open request input parameters and reject if any
// are incorrect. Tests filterQuery, continueOnError, operationTimeout
// and maxObjectCount
Uint32 operationMaxObjectCount;
if (_rejectIfPullParametersFailTests(request,operationMaxObjectCount,
ENABLE_FQL_FILTER))
{
PEG_METHOD_EXIT();
return true;
}
if (!_checkExistenceOfClass(
request->nameSpace, request->objectName.getClassName()))
{
PEG_METHOD_EXIT();
throw PEGASUS_CIM_EXCEPTION(
CIM_ERR_INVALID_PARAMETER, request->objectName.toString());
}
//
// Try to compile the filter. Get an exception only if the FQL
// filter compiler generates an exception.
//
#ifdef PEGASUS_ENABLE_FQL
bool filterResponse = false;
AutoPtr<FQLQueryExpressionRep> qx;
AutoPtr<FQLQueryStatement> queryStatement;
if (request->filterQueryLanguage.size() != 0)
{
bool exception = false;
CIMException cimException;
if (request->filterQueryLanguage != "DMTF:FQL")
{
cimException = PEGASUS_CIM_EXCEPTION(
CIM_ERR_QUERY_LANGUAGE_NOT_SUPPORTED,
request->filterQueryLanguage);
exception = true;
}
else
{
if (request->filterQuery.size() != 0)
{
try
{
queryStatement.reset(new FQLQueryStatement());
FQLParser::parse(request->filterQuery, *queryStatement);
qx.reset(new FQLQueryExpressionRep(
request->filterQueryLanguage, queryStatement.get() ));
filterResponse = true;
}
catch (ParseError& e)
{
String text = request->filterQuery + " " + e.getMessage();
cimException =
PEGASUS_CIM_EXCEPTION(
CIM_ERR_INVALID_QUERY, text);
exception=true;
}
catch (...)
{
exception=true;
}
}
}
if (exception)
{
CIMResponseMessage* response = request->buildResponse();
response->cimException = cimException;
_enqueueResponse(request, response);
PEG_METHOD_EXIT();
return true;
}
}
#endif
ProviderInfoList providerInfos = _lookupAllAssociationProviders(
request->nameSpace,
request->objectName,
request->assocClass,
String::EMPTY);
// If no provider is registered and the repository isn't the default,
// return CIM_ERR_NOT_SUPPORTED
if (_rejectNoProvidersOrRepository(request, providerInfos))
{
PEG_METHOD_EXIT();
return true;
}
//
// Get the instances from the repository, as necessary.
// Hold the repository results in a response message.
// If not using the repository, this pointer is null.
//
Array<CIMObject> cimObjects;
if (_repository->isDefaultInstanceProvider())
{
cimObjects = _repository->associators(
request->nameSpace,
request->objectName,
request->assocClass,
request->resultClass,
request->role,
request->resultRole,
false, // force includeQualifiers to false
request->includeClassOrigin,
request->propertyList);
PEG_TRACE((TRC_DISPATCHER, Tracer::LEVEL4,
"OpenAssociatorInstances repository access: class = %s,"
" count = %u.",
CSTRING(request->objectName.toString()),
cimObjects.size() ));
}
// Build OpenResponse Message
AutoPtr<CIMOpenAssociatorInstancesResponseMessage> openResponse;
openResponse.reset(dynamic_cast<CIMOpenAssociatorInstancesResponseMessage*>(
request->buildResponse()));
// if there are no providers and nothing from repository
// return with endOfSequence true. Do direct enqueue response.
//
// // KS TODO can we completely bypass this code and just use
// the main delivery path even if the repository returns nothing?
if ((providerInfos.providerCount == 0) && (cimObjects.size() == 0))
{
//
// We have no providers to call. Just return what we have.
//
PEG_TRACE((TRC_DISPATCHER, Tracer::LEVEL4,
"OpenAssociatorInstances. No Objects found for %s",
(const char *)request->className.getString().getCString()));
openResponse->endOfSequence = true;
_enqueueResponse(request, openResponse.release());
PEG_METHOD_EXIT();
return true;
}
//
// Process as multi operation enumeration. 1. Build context, build
// internalRequest for providers and issue to providers, build open
// response, get current objects (with wait) and enqueue open
// response.
//
// Create a new enumeration context
EnumerationContext* enumerationContext =
_enumerationContextTable->createContext(
request,
CIM_PULL_INSTANCES_WITH_PATH_REQUEST_MESSAGE,
CIMResponseData::RESP_OBJECTS);
if (enumerationContext == NULL)
{
_rejectCreateContextFailed(request);
PEG_METHOD_EXIT();
return true;
}
enumerationContext->setRequestProperties(
request->includeClassOrigin, request->propertyList);
// Build corresponding CIMReferencesRequestMessage to issue to
// providers. We do not pass the Pull operations request
// on to Providers but use the EnumerateInstancesRequest message to
// activate providers. NOTE: includeQualifiers NOT part of Pull operation
CIMAssociatorsRequestMessage* internalRequest =
new CIMAssociatorsRequestMessage(
enumerationContext->getContextId(),
request->nameSpace,
request->objectName,
request->assocClass,
request->resultClass,
request->role,
request->resultRole,
false, // force includeQualifiers to false
request->includeClassOrigin,
request->propertyList,
request->queueIds,
false, // By definition not a class request
request->authType,
request->userName);
internalRequest->operationContext = request->operationContext;
internalRequest->internalOperation = true;
// AutoPtr to delete at end of handler
AutoPtr<CIMAssociatorsRequestMessage> requestDestroyer(internalRequest);
//
// Set up an aggregate object and save the original request message
//
OperationAggregate* poA = new OperationAggregate(
new CIMAssociatorsRequestMessage(*internalRequest),
internalRequest->objectName.getClassName(),
internalRequest->nameSpace,
providerInfos.providerCount,
true, // completeHostAndNamespace = false
true); // Operation has property list
//
// Set Open... operation parameters into the operationAggregate
//
poA->setPullOperation(enumerationContext);
#ifdef PEGASUS_ENABLE_FQL
if (filterResponse)
{
queryStatement.release();
poA ->setFilterParameters(qx.release(),
request->filterQueryLanguage);
}
#endif
// Send repository response for aggregation
if (cimObjects.size() != 0)
{
AutoPtr<CIMAssociatorsResponseMessage> internalResponse;
internalResponse.reset(dynamic_cast<CIMAssociatorsResponseMessage*>(
internalRequest->buildResponse()));
internalResponse->getResponseData().setObjects(cimObjects);
poA->incTotalIssued();
// send the repository's results for aggregation
// directly to callback (i.e. includes response).
_forwardResponseForAggregation(
new CIMAssociatorsRequestMessage(*internalRequest),
poA,
internalResponse.release());
}
ProviderRequests::issueOpenAssocRequestMsgsToProviders(
this,
internalRequest,
providerInfos,
poA,
"OpenAssociatorInstances"
);
// Issue the Response to the Open Request. This may be issued immediatly
// or delayed by setting information into the enumeration context
// if there are no responses from providers ready
// to avoid issuing empty responses.
// Enumeration Context must not be used after this call
bool releaseRequest = issueOpenOrPullResponseMessage(
request,
openResponse.release(),
enumerationContext,
operationMaxObjectCount,
requireCompleteResponses);
PEG_METHOD_EXIT();
return releaseRequest;
}
/**$*******************************************************
handleOpenAssociatorInstancePathsRequest
**********************************************************/
bool CIMOperationRequestDispatcher::handleOpenAssociatorInstancePathsRequest(
CIMOpenAssociatorInstancePathsRequestMessage* request)
{
PEG_METHOD_ENTER(TRC_DISPATCHER,
"CIMOperationRequestDispatcher::"
"handleOpenAssociatorInstancePathsRequest");
PEG_TRACE((TRC_DISPATCHER, Tracer::LEVEL4,
"OpenAssociatorInstancePaths request namespace=%s object=%s "
"assocClass = %s "
"resultClass=%s "
"role=%s "
"resultRole = %s "
"filterQueryLanguage=%s "
"filterQuery=%s "
"operationTimeout=%s "
"continueOnError=%s "
"maxObjectCount=%u",
CSTRING(request->nameSpace.getString()),
CSTRING(request->objectName.toString()),
CSTRING(request->assocClass.getString()),
CSTRING(request->resultClass.getString()),
CSTRING(request->role),
CSTRING(request->resultRole),
CSTRING(request->filterQueryLanguage),
CSTRING(request->filterQuery),
CSTRING(request->operationTimeout.toString()),
boolToString(request->continueOnError),
request->maxObjectCount ));
// validate className and objectClassName same. This is
// an invariant for the handleAssoc, etc functions.
PEGASUS_DEBUG_ASSERT(
request->className == request->objectName.getClassName());
if (_rejectAssociationTraversalDisabled(request,
"OpenAssociatorInstancePaths"))
{
PEG_METHOD_EXIT();
return true;
}
if (_rejectInvalidRoleParameter(request, request->role, "role"))
{
PEG_METHOD_EXIT();
return true;
}
if (_rejectInvalidRoleParameter(request, request->resultRole, "roleRole"))
{
PEG_METHOD_EXIT();
return true;
}
if (_rejectInvalidObjectPathParameter(request, request->objectName))
{
PEG_METHOD_EXIT();
return true;
}
// Test the common open request input parameters and reject if any
// are incorrect. Tests filterQuery, continueOnError, operationTimeout
// and maxObjectCount
Uint32 operationMaxObjectCount;
if (_rejectIfPullParametersFailTests(request,operationMaxObjectCount,false))
{
PEG_METHOD_EXIT();
return true;
}
if (!_checkExistenceOfClass(request->nameSpace,
request->objectName.getClassName()))
{
PEG_METHOD_EXIT();
throw PEGASUS_CIM_EXCEPTION(
CIM_ERR_INVALID_PARAMETER,
request->objectName.getClassName().getString());
}
//
// Get results from providers and the repository
// Determine list of providers for this request
//
ProviderInfoList providerInfos = _lookupAllAssociationProviders(
request->nameSpace,
request->objectName,
request->resultClass,
String::EMPTY);
// If no provider is registered and the repository isn't the default,
// return CIM_ERR_NOT_SUPPORTED
if (_rejectNoProvidersOrRepository(request, providerInfos))
{
PEG_METHOD_EXIT();
return true;
}
//
// Get the instances from the repository, as necessary
//
Array<CIMObjectPath> objectNames;
if (_repository->isDefaultInstanceProvider())
{
objectNames = _repository->associatorNames(
request->nameSpace,
request->objectName,
request->assocClass,
request->resultClass,
request->role,
request->resultRole);
PEG_TRACE((TRC_DISPATCHER, Tracer::LEVEL4,
"OpenAssociatorInstancePaths repository access: class = %s,"
" count = %u.",
(const char*)request->objectName.toString().getCString(),
objectNames.size()));
}
// Build OpenResponse Message
AutoPtr<CIMOpenAssociatorInstancePathsResponseMessage> openResponse;
openResponse.reset(
dynamic_cast<CIMOpenAssociatorInstancePathsResponseMessage*>(
request->buildResponse()));
if (providerInfos.providerCount == 0 && objectNames.size() == 0)
{
//
// No provider is registered and the repository isn't the
// default. Return CIM_ERR_NOT_SUPPORTED.
//
PEG_TRACE((TRC_DISPATCHER, Tracer::LEVEL4,
"OpenAssociatorInstancePaths. No Objects found for %s",
CSTRING(request->className.getString()) ));
openResponse->endOfSequence = true;
_enqueueResponse(request, openResponse.release());
PEG_METHOD_EXIT();
return true;
}
//
// Process as multi operation enumeration. 1. Build context, build
// internalRequest for providers and issue to providers, build open
// response, get current objects (with wait) and enqueue open
// response.
//
// Create new enumerationContext and enumerationContextString.
EnumerationContext* enumerationContext =
_enumerationContextTable->createContext(
request,
CIM_PULL_INSTANCE_PATHS_REQUEST_MESSAGE,
CIMResponseData::RESP_OBJECTPATHS);
if (enumerationContext == NULL)
{
_rejectCreateContextFailed(request);
PEG_METHOD_EXIT();
return true;
}
// Build corresponding EnumerateInstancePathsRequest to send to
// providers. We do not pass the Pull operations request
// on to Providers but use the EnumerateInstancesRequest message to
// activate providers. NOTE: includeQualifiers NOT part of Pull operation
CIMAssociatorNamesRequestMessage* internalRequest =
new CIMAssociatorNamesRequestMessage(
enumerationContext->getContextId(),
request->nameSpace,
request->objectName,
request->assocClass,
request->resultClass,
request->role,
request->resultRole,
request->queueIds,
false,
request->authType,
request->userName);
internalRequest->operationContext = request->operationContext;
internalRequest->internalOperation = true;
AutoPtr<CIMAssociatorNamesRequestMessage> requestDestroyer(internalRequest);
//
// Set up an aggregate object and save the created internalRequest
//
OperationAggregate* poA = new OperationAggregate(
new CIMAssociatorNamesRequestMessage(*internalRequest),
internalRequest->objectName.getClassName(),
internalRequest->nameSpace,
providerInfos.providerCount,
true, // completeHostAndNamespace = false
false); // No property list for this operation
//
// Set Open... operation parameters into the operationAggregate
//
poA->setPullOperation(enumerationContext);
// If any return from repository, send it to aggregator.
if (objectNames.size() != 0)
{
AutoPtr<CIMAssociatorNamesResponseMessage> internalResponse;
internalResponse.reset(dynamic_cast<CIMAssociatorNamesResponseMessage*>(
internalRequest->buildResponse()));
internalResponse->getResponseData().setInstanceNames(objectNames);
poA->incTotalIssued();
// send the repository's results for aggregation
// directly to callback (includes response).
_forwardResponseForAggregation(
new CIMAssociatorNamesRequestMessage(*internalRequest),
poA,
internalResponse.release());
}
ProviderRequests::issueOpenAssocRequestMsgsToProviders(
this,
internalRequest,
providerInfos,
poA,
"OpenAssociatorInstancePaths"
);
// Issue the Response to the Open Request. This may be issued immediatly
// or delayed by setting information into the enumeration context
// if there are no responses from providers ready
// to avoid issuing empty responses.
// Enumeration Context must not be used after this call
bool releaseRequest = issueOpenOrPullResponseMessage(
request,
openResponse.release(),
enumerationContext,
operationMaxObjectCount,
requireCompleteResponses);
PEG_METHOD_EXIT();
return releaseRequest;
}
/**$**************************************************************************
**
** handleOpenQueryInstancesRequest
**
*****************************************************************************/
bool CIMOperationRequestDispatcher::handleOpenQueryInstancesRequest(
CIMOpenQueryInstancesRequestMessage* request)
{
PEG_METHOD_ENTER(TRC_DISPATCHER,
"CIMOperationRequestDispatcher::handleOpenQueryInstancesRequest");
PEG_TRACE((TRC_DISPATCHER, Tracer::LEVEL4,
"OpenQueryInstances request namespace=%s "
"queryLanguage=%s "
"query=%s "
"returnQueryResultClass=%s "
"operationTimeout=%s "
"continueOnError=%s "
"maxObjectCount=%u ",
CSTRING(request->nameSpace.getString()),
CSTRING(request->queryLanguage),
CSTRING(request->query),
boolToString(request->returnQueryResultClass),
CSTRING(request->operationTimeout.toString()),
boolToString(request->continueOnError),
request->maxObjectCount ));
if (_rejectIfContinueOnError(request, request->continueOnError))
{
PEG_METHOD_EXIT();
return true;
}
Uint32 operationMaxObjectCount;
if (_rejectInvalidMaxObjectCountParam(request, request->maxObjectCount,
false, operationMaxObjectCount, Uint32(0)))
{
PEG_METHOD_EXIT();
return true;
}
// Test for valid values in OperationTimeout
if (_rejectInvalidOperationTimeout(request, request->operationTimeout))
{
PEG_METHOD_EXIT();
return true;
}
AutoPtr<CIMOpenQueryInstancesResponseMessage> openResponse(
dynamic_cast<CIMOpenQueryInstancesResponseMessage*>(
request->buildResponse()));
#ifdef PEGASUS_DISABLE_EXECQUERY
openResponse->cimException =
PEGASUS_CIM_EXCEPTION(CIM_ERR_NOT_SUPPORTED, String::EMPTY);
_enqueueResponse(request, openResponse.release());
PEG_METHOD_EXIT();
return true;
#endif
//
// Setup the EnumerationContext. Returns pointer to object
// Objects are passed through the system (they are from ExecQuery)
// and mapped to instances on output
EnumerationContext* en =
_enumerationContextTable->createContext(
request,
CIM_PULL_INSTANCES_REQUEST_MESSAGE,
CIMResponseData::RESP_OBJECTS);
if (en == NULL)
{
_rejectCreateContextFailed(request);
PEG_METHOD_EXIT();
return true;
}
// Create the corresponding CIMExecQueryRequestMessage
CIMExecQueryRequestMessage* internalRequest =
new CIMExecQueryRequestMessage(
en->getContextId(),
request->nameSpace,
request->queryLanguage,
request->query,
request->queueIds,
request->authType,
request->userName);
internalRequest->operationContext = request->operationContext;
internalRequest->internalOperation = true;
AutoPtr<CIMExecQueryRequestMessage> requestDestroyer(internalRequest);
if (!QuerySupportRouter::routeHandleExecQueryRequest(
this, internalRequest,openResponse->cimException, en))
{
_enqueueResponse(request, openResponse.release());
PEG_METHOD_EXIT();
return true;
}
// Issue the Response to the Open Request. This may be issued immediatly
// or delayed by setting information into the enumeration context
// if there are no responses from providers ready
// to avoid issuing empty responses.
// Enumeration Context must not be used after this call
bool releaseRequest = issueOpenOrPullResponseMessage(
request,
openResponse.release(),
en,
operationMaxObjectCount,
requireCompleteResponses);
PEG_METHOD_EXIT();
return releaseRequest;
}
void CIMOperationRequestDispatcher::handleEnumerationCount(
CIMEnumerationCountRequestMessage* request)
{
PEG_METHOD_ENTER(TRC_DISPATCHER,
"CIMOperationRequestDispatcher::handleEnumerationCount");
PEGASUS_STD(cout) << "CIMOpDispatcher::handleEnumerationCount class = "
<< request->className.getString()
<< " enumContext= " << request->enumerationContext
<< PEGASUS_STD(endl);
// Determine if the enumerationContext exists
EnumerationContext* en = _enumerationContextTable->find(
request->enumerationContext);
// test for invalid context and if found, error out.
if (_rejectInvalidEnumerationContext(request, en))
{
PEG_METHOD_EXIT();
return;
}
// Issue Not supported error since, in general, we do
// not support this request operation
CIMResponseMessage* response = request->buildResponse();
response->cimException =
PEGASUS_CIM_EXCEPTION(CIM_ERR_NOT_SUPPORTED, String::EMPTY);
_enqueueResponse(request, response);
PEG_METHOD_EXIT();
return;
}
/**$********************************************************
handlePullInstancesWithPath
************************************************************/
bool CIMOperationRequestDispatcher::handlePullInstancesWithPath(
CIMPullInstancesWithPathRequestMessage* request)
{
PEG_METHOD_ENTER(TRC_DISPATCHER,
"CIMOperationRequestDispatcher::handlePullInstancesWithPath");
// Both pull operations execute off of a single templated function.
// Build and send response. getCache used to wait for objects
CIMPullInstancesWithPathResponseMessage* response(
dynamic_cast<CIMPullInstancesWithPathResponseMessage*>(
request->buildResponse()));
bool releaseRequest = processPullRequest(request,
response, "pullInstancesWithPath");
PEG_METHOD_EXIT();
return releaseRequest;
}
/**$********************************************************
handlePullInstancesPaths
************************************************************/
bool CIMOperationRequestDispatcher::handlePullInstancePaths(
CIMPullInstancePathsRequestMessage* request)
{
PEG_METHOD_ENTER(TRC_DISPATCHER,
"CIMOperationRequestDispatcher::handlePullInstancePaths");
// Both pull operations execute off of a single templated
// function.
// Build and send response. getCache used to wait for objects
CIMPullInstancePathsResponseMessage* response(
dynamic_cast<CIMPullInstancePathsResponseMessage*>(
request->buildResponse()));
bool releaseRequest = processPullRequest(request, response,
"pullInstancePaths");
PEG_METHOD_EXIT();
return releaseRequest;
}
/**$********************************************************
handlePullInstances - Part of the OpenQueryInstances
enumerationSequence
************************************************************/
bool CIMOperationRequestDispatcher::handlePullInstances(
CIMPullInstancesRequestMessage* request)
{
PEG_METHOD_ENTER(TRC_DISPATCHER,
"CIMOperationRequestDispatcher::handlePullInstances");
// All pull operations execute off of a single templated
// function.
// Build and send response. getCache used to wait for objects
CIMPullInstancesResponseMessage* response(
dynamic_cast<CIMPullInstancesResponseMessage*>(
request->buildResponse()));
bool releaseRequest = processPullRequest(request, response,
"pullInstances");
PEG_METHOD_EXIT();
return releaseRequest;
}
/**$********************************************************
handleCloseEnumeration
************************************************************/
void CIMOperationRequestDispatcher::handleCloseEnumeration(
CIMCloseEnumerationRequestMessage* request)
{
PEG_METHOD_ENTER(TRC_DISPATCHER,
"CIMOperationRequestDispatcher::handleCloseEnumeration");
PEG_TRACE((TRC_DISPATCHER, Tracer::LEVEL4,
"CloseEnumeration request for "
"contextId=%s . ",
(const char*)request->enumerationContext.getCString() ));
EnumerationContext* en = _enumerationContextTable->find(
request->enumerationContext);
if (_rejectInvalidEnumerationContext(request, en))
{
PEG_METHOD_EXIT();
return;
}
// KS_TODO should we test for received namespace here?
en->incrementRequestCount();
// lock the context until we have set processing state to avoid
// conflict with timer thread and conducted all tests.
Boolean providersComplete;
{
AutoMutex contextLock(en->_contextLock);
if (_rejectIfContextTimedOut(request, en->isTimedOut()))
{
PEG_METHOD_EXIT();
return;
}
// If another operation is active for this context, reject this
// operation.
// The specification allows as an option concurrent close (close
// while pull request active) but we do not for now. Complicates the
// code to much for right now.
if (_rejectIfEnumerationContextProcessing(request, en->isProcessing()))
{
PEG_METHOD_EXIT();
return;
}
// Stop interoperation timer thread from reviewing this context.
en->stopTimer();
// Set the EnumerationContext Closed. No more requests will be
// accepted for this enumerationContext
en->setClientClosed();
// If providers complete, we can release this context.
if ((providersComplete = en->providersComplete()))
{
// Keep the context locked when exiting from AutoMutex contextLock
// scope, _enumerationContextTable->releaseContext() below needs it
// locked and it will unlock it before it destroys it.
en->lockContext();
}
}
if (providersComplete)
{
// Unlock and destroy the context.
PEGASUS_ASSERT(_enumerationContextTable->releaseContext(en));
}
AutoPtr<CIMCloseEnumerationResponseMessage> response(
dynamic_cast<CIMCloseEnumerationResponseMessage*>(
request->buildResponse()));
response->cimException = CIMException();
_enqueueResponse(request, response.release());
PEG_METHOD_EXIT();
return;
}
//KS_PULL_END
/**************************************************************************/
// End of the Pull operation functions
/**************************************************************************/
//
// Return Aggregated responses back to the Correct Aggregator
//
// The aggregator includes an aggregation object that is used to
// accumulate responses. It is attached to each request sent and
// received back as part of the response call back in the "parm"
// Responses are aggregated until the count reaches the sent count and
// then the aggregation code is called to create a single response from
// the accumulated responses.
// It uses information from the OperationAggregate to execute
// special functions such as fixing the property list and
// settiing hostName, etc.
//
/*********************************************************************/
void CIMOperationRequestDispatcher::handleOperationResponseAggregation(
OperationAggregate* poA)
{
PEG_METHOD_ENTER(TRC_DISPATCHER,
"CIMOperationRequestDispatcher::"
"handleOperationResponseAggregation");
CIMResponseDataMessage* toResponse =
(CIMResponseDataMessage*) poA->getResponse(0);
PEG_TRACE(( TRC_DISPATCHER, Tracer::LEVEL3,
"CIMOperationRequestDispatcher - "
"RequestType=%s ResponseType=%s "
"Namespace=%s ClassName=%s ResponseCount=%u "
"messageId=%s",
MessageTypeToString(poA->_msgRequestType),
MessageTypeToString(toResponse->getType()),
CSTRING(poA->_nameSpace.getString()),
CSTRING(poA->_className.getString()),
poA->numberResponses(),
CSTRING(toResponse->messageId) ));
//// KS_TODO temporary while we finish pull testing
PEG_TRACE(( TRC_DISPATCHER, Tracer::LEVEL4,
"CIMOperationRequestDispatcher::handleOperationResponseAggregation"
" - Type=%s requiresHostnameCompletion=%s _hasPropList=%s",
MessageTypeToString(poA->_msgRequestType),
boolToString(poA->_requiresHostnameCompletion),
boolToString(poA->_hasPropList) ));
CIMResponseData & to = toResponse->getResponseData();
// Re-add the property list as stored from request after deepInheritance fix
// since on OOP on the response message the property list gets lost
// This is only done for EnumerateInstances type requests
if (poA->_hasPropList)
{
switch (poA->_msgRequestType)
{
case CIM_ENUMERATE_INSTANCES_REQUEST_MESSAGE:
{
CIMEnumerateInstancesRequestMessage* request =
(CIMEnumerateInstancesRequestMessage*)poA->getRequest();
to.setPropertyList(request->propertyList);
break;
}
case CIM_ASSOCIATORS_REQUEST_MESSAGE:
{
CIMAssociatorsRequestMessage* request =
(CIMAssociatorsRequestMessage*)poA->getRequest();
to.setPropertyList(request->propertyList);
break;
}
case CIM_REFERENCES_REQUEST_MESSAGE:
{
CIMReferencesRequestMessage* request =
(CIMReferencesRequestMessage*)poA->getRequest();
to.setPropertyList(request->propertyList);
break;
}
default:
{
PEG_TRACE(( TRC_DISPATCHER, Tracer::LEVEL4,
"CIMOperationRequestDispatcher::"
"handleOperationResponseAggregation "
"ERRORNOTHANDLINGPROPERTYLIST - Type=%s"
"requiresHostnameCompletion=%s _hasPropList=%s",
MessageTypeToString(poA->_msgRequestType),
boolToString(poA->_requiresHostnameCompletion),
boolToString(poA->_hasPropList) ));
}
}
}
// Work backward and delete each response off the end of the array
// and append it to the new responseData
for (Uint32 i = poA->numberResponses() - 1; i > 0; i--)
{
CIMResponseDataMessage* fromResponse =
(CIMResponseDataMessage*)poA->getResponse(i);
CIMResponseData & from = fromResponse->getResponseData();
to.appendResponseData(from);
poA->deleteResponse(i);
}
// If Response flagged for Filtering, Filter this response
// CIMResponseData.
#ifdef PEGASUS_ENABLE_FQL
if (poA->_filterResponse)
{
CIMException cimException;
bool exception = false;
QueryExpressionRep* query = poA->_query;
FQLQueryStatement* qs = ((FQLQueryExpressionRep*)query)->_stmt;
try
{
// If enumerate filter instances. Otherwise filter objects
if (poA->_msgRequestType == CIM_ENUMERATE_INSTANCES_REQUEST_MESSAGE)
{
Array<CIMInstance> &insts = to.getInstances();
for (int i = insts.size() - 1 ; i >= 0 ; i--)
{
FQLInstancePropertySource ips(insts[i]);
if (!qs->evaluateQuery(&ips))
{
insts.remove(i);
}
}
}
else
{
Array<CIMObject> &objcts = to.getObjects();
for (int i = objcts.size() - 1 ; i >= 0 ; i--)
{
FQLInstancePropertySource ips((CIMInstance)objcts[i]);
if (!qs->evaluateQuery(&ips))
{
objcts.remove(i);
}
}
}
}
// Should we catch parseError as a special KS_TODO
catch (CIMException& e)
{
// KS_TODO should we keep the original query string
String text = e.getMessage();
cimException =
PEGASUS_CIM_EXCEPTION(
CIM_ERR_INVALID_QUERY, text);
exception=true;
}
catch (...)
{
// KS_TODO Should this be more general error.
cimException =
PEGASUS_CIM_EXCEPTION(
CIM_ERR_INVALID_QUERY, "General error caused Exception");
exception = true;
}
// Reset the ResponseData size since we may have modified it.
to.setSize();
if (exception)
{
toResponse->cimException = cimException;
}
}
#endif
if (poA->_requiresHostnameCompletion)
{
// fill in host, namespace on all instances on all elements of array
// if they have been left out. Required because XML reader
// will fail without them populated
to.completeHostNameAndNamespace(System::getHostName(),
poA->_nameSpace, poA->_pullOperation);
}
PEG_METHOD_EXIT();
}
// Aggregator for execQuery Response Aggregation.
// Aggregates responses into a single response and maps the responses back
// to ExecQuery responses.
void CIMOperationRequestDispatcher::handleExecQueryResponseAggregation(
OperationAggregate* poA)
{
PEG_METHOD_ENTER(TRC_DISPATCHER,
"CIMOperationRequestDispatcher::handleExecQueryResponseAggregation");
Uint32 numberResponses = poA->numberResponses();
PEG_TRACE((TRC_DISPATCHER, Tracer::LEVEL4,
"CIMOperationRequestDispatcher::ExecQuery Response - "
"NameSpace=%s ClassName=%s ResponseCount=%u",
CSTRING(poA->_nameSpace.getString()),
CSTRING(poA->_className.getString()),
numberResponses));
if (numberResponses != 0)
{
CIMResponseMessage* response = poA->getResponse(0);
CIMExecQueryResponseMessage* toResponse = 0;
Uint32 startIndex = 0;
Uint32 endIndex = numberResponses - 1;
bool manyResponses = true;
// Define pointer to the applyQueryToEnumeration function appropriate
// for the query language defined.
// NOTE: typedef applyQueryToEnumerationPtr is defined in
// QuerySupportRouter.
applyQueryFunctionPtr applyQueryToEnumeration = NULL;
applyQueryToEnumeration =
QuerySupportRouter::getFunctPtr(this, poA->_query);
if (response->getType() == CIM_ENUMERATE_INSTANCES_RESPONSE_MESSAGE)
{
// Create an ExecQuery response from an EnumerateInstances request
CIMOperationRequestMessage* request = poA->getRequest();
AutoPtr<CIMExecQueryResponseMessage> query(
new CIMExecQueryResponseMessage(
request->messageId,
CIMException(),
request->queueIds.copyAndPop()));
query->syncAttributes(request);
toResponse = query.release();
}
else
{
toResponse = (CIMExecQueryResponseMessage*) response;
manyResponses = false;
}
// Work backward and delete each response off the end of the array
// KS_TODO May 2104 - The manyResponses logic is convoluted and very
// hard to understand. Not even certain is is correct since we do not
// have a wealth of query providers in our tests.
for (Uint32 i = endIndex; i >= startIndex; i--)
{
if (manyResponses)
{
response = poA->getResponse(i);
}
if (response->getType() == CIM_ENUMERATE_INSTANCES_RESPONSE_MESSAGE)
{
// convert enumerate instances response to exec query response
// This is an indirect call to the appropriate function in
// the WQL..., CQL, ... etc Class
//
// NULLness check is done as getFunctPtr may reurn NULL in case
// of when query language is not CQL, WQL
if (applyQueryToEnumeration)
{
applyQueryToEnumeration(response, poA->_query);
}
CIMClass cimClass;
Boolean clsRead = false;
CIMEnumerateInstancesResponseMessage* fromResponse =
(CIMEnumerateInstancesResponseMessage*) response;
Array<CIMInstance>& a =
fromResponse->getResponseData().getInstances();
// Map instances to objects and add objectPath
for (Uint32 j = 0, m = a.size(); j < m; j++)
{
CIMObject co=CIMObject(a[j]);
CIMObjectPath op=co.getPath();
const Array<CIMKeyBinding>& kbs=op.getKeyBindings();
if (kbs.size() == 0)
{ // no path set
if (clsRead == false)
{
cimClass = _repository->getClass(
poA->_nameSpace, op.getClassName(),
false,true,false, CIMPropertyList());
clsRead=true;
}
// Trace enum responses that do not have
// path component.
// KS_TODO should this really be log???
PEG_TRACE((TRC_DISPATCHER, Tracer::LEVEL4,
"query response, no path set in provider. "
"ClassName=%s",
CSTRING(cimClass.getClassName().getString()) ));
op = a[j].buildPath(cimClass);
}
op.setNameSpace(poA->_nameSpace);
op.setHost(System::getHostName());
co.setPath(op);
if (manyResponses)
{
toResponse->getResponseData().appendObject(co);
}
}
}
else // This response is CIMExecQueryResponse
{
CIMExecQueryResponseMessage* fromResponse =
(CIMExecQueryResponseMessage*) response;
CIMResponseData & from = fromResponse->getResponseData();
from.completeHostNameAndNamespace(
System::getHostName(),
poA->_nameSpace);
// KS_TODO this manyResponses makes no sense to me. Isn't
// this always ExecQuery which is always false?
if (manyResponses)
{
toResponse->getResponseData().appendResponseData(from);
}
}
if (manyResponses)
{
poA->deleteResponse(i);
}
if (i == 0)
{
break;
}
} // for all responses in response list
// If we started with an enumerateInstances repsonse, then add it
// to overall
if ((startIndex == 0) && manyResponses)
{
poA->appendResponse(toResponse);
}
}
PEG_METHOD_EXIT();
}
/*******End of the functions for aggregation***************************/
/**
Convert the specified CIMValue to the specified type, and return it in
a new CIMValue.
*/
CIMValue CIMOperationRequestDispatcher::_convertValueType(
const CIMValue& value,
CIMType type)
{
PEG_METHOD_ENTER(TRC_DISPATCHER,
"CIMOperationRequestDispatcher::_convertValueType");
CIMValue newValue;
if (value.isArray())
{
Array<String> stringArray;
Array<char*> charPtrArray;
Array<const char*> constCharPtrArray;
//
// Convert the value to Array<const char*> to send to conversion method
//
// ATTN-RK-P3-20020221: Deal with TypeMismatchException
// (Shouldn't really ever get that exception)
value.get(stringArray);
for (Uint32 k=0; k<stringArray.size(); k++)
{
// Need to build an Array<const char*> to send to the conversion
// routine, but also need to keep track of them pointers as char*
// because Windows won't let me delete a const char*.
char* charPtr = strdup(stringArray[k].getCString());
charPtrArray.append(charPtr);
constCharPtrArray.append(charPtr);
}
//
// Convert the value to the specified type
//
try
{
newValue =
XmlReader::stringArrayToValue(0, constCharPtrArray, type);
}
catch (XmlSemanticError&)
{
for (Uint32 k=0; k<charPtrArray.size(); k++)
{
free(charPtrArray[k]);
}
PEG_METHOD_EXIT();
throw PEGASUS_CIM_EXCEPTION_L(CIM_ERR_INVALID_PARAMETER,
MessageLoaderParms(
"Server.CIMOperationRequestDispatcher."
"CIM_ERR_INVALID_PARAMETER",
"Malformed $0 value",
cimTypeToString(type)));
}
catch (...)
{
for (Uint32 k=0; k<charPtrArray.size(); k++)
{
free(charPtrArray[k]);
}
PEG_METHOD_EXIT();
throw;
}
for (Uint32 k = 0; k < charPtrArray.size(); k++)
{
free(charPtrArray[k]);
}
}
else
{
String stringValue;
// ATTN-RK-P3-20020221: Deal with TypeMismatchException
// (Shouldn't really ever get that exception)
value.get(stringValue);
try
{
newValue =
XmlReader::stringToValue(0, stringValue.getCString(), type);
}
catch (XmlSemanticError&)
{
PEG_METHOD_EXIT();
throw PEGASUS_CIM_EXCEPTION_L(CIM_ERR_INVALID_PARAMETER,
MessageLoaderParms(
"Server.CIMOperationRequestDispatcher."
"CIM_ERR_INVALID_PARAMETER",
"Malformed $0 value",
cimTypeToString(type)));
}
}
PEG_METHOD_EXIT();
return newValue;
}
/**
Find the CIMParamValues in the InvokeMethod request whose types were
not specified in the XML encoding, and convert them to the types
specified in the method schema.
*/
void CIMOperationRequestDispatcher::_fixInvokeMethodParameterTypes(
CIMInvokeMethodRequestMessage* request)
{
PEG_METHOD_ENTER(TRC_DISPATCHER,
"CIMOperationRequestDispatcher::_fixInvokeMethodParameterTypes");
Boolean gotMethodDefinition = false;
CIMMethod method;
//
// Cycle through the input parameters, converting the untyped ones.
//
Array<CIMParamValue> inParameters = request->inParameters;
Uint32 numInParamValues = inParameters.size();
for (Uint32 i=0; i<numInParamValues; i++)
{
if (!inParameters[i].isTyped())
{
//
// Retrieve the method definition, if we haven't already done so
// (only look up the method if we have an untyped parameter value)
//
if (!gotMethodDefinition)
{
//
// Get the class definition for this method
//
CIMClass cimClass =
_repository->getClass(
request->nameSpace,
request->instanceName.getClassName(),
false, //localOnly,
false, //includeQualifiers,
false, //includeClassOrigin,
CIMPropertyList());
PEG_TRACE((TRC_DISPATCHER, Tracer::LEVEL4,
"CIMOperationRequestDispatcher::"
"_fixInvokeMethodParameterTypes - "
"Namespace=%s ClassName=%s",
CSTRING(request->nameSpace.getString()),
CSTRING(request->instanceName.getClassName().getString())));
//
// Get the method definition from the class
//
Uint32 methodPos = cimClass.findMethod(request->methodName);
if (methodPos == PEG_NOT_FOUND)
{
throw PEGASUS_CIM_EXCEPTION(
CIM_ERR_METHOD_NOT_FOUND, String::EMPTY);
}
method = cimClass.getMethod(methodPos);
gotMethodDefinition = true;
}
//
// Find the parameter definition for this input parameter
//
CIMName paramName = inParameters[i].getParameterName();
Uint32 numParams = method.getParameterCount();
for (Uint32 j=0; j<numParams; j++)
{
CIMParameter param = method.getParameter(j);
if (paramName == param.getName())
{
//
// Retype the input parameter value according to the
// type defined in the class/method schema
//
CIMType paramType = param.getType();
CIMValue newValue;
if (inParameters[i].getValue().isNull())
{
newValue.setNullValue(
param.getType(),
param.isArray());
}
else if (inParameters[i].getValue().isArray() !=
param.isArray())
{
// ATTN-RK-P1-20020222: Who catches this? They aren't.
PEG_METHOD_EXIT();
throw PEGASUS_CIM_EXCEPTION(
CIM_ERR_TYPE_MISMATCH, String::EMPTY);
}
else
{
newValue = _convertValueType(
inParameters[i].getValue(),
paramType);
}
inParameters[i].setValue(newValue);
inParameters[i].setIsTyped(true);
break;
}
}
}
}
PEG_METHOD_EXIT();
}
/**
Convert the CIMValue given in a SetProperty request to the correct
type according to the schema, because it is not possible to specify
the property type in the XML encoding.
*/
void CIMOperationRequestDispatcher::_fixSetPropertyValueType(
CIMSetPropertyRequestMessage* request)
{
PEG_METHOD_ENTER(TRC_DISPATCHER,
"CIMOperationRequestDispatcher::_fixSetPropertyValueType");
CIMValue inValue = request->newValue;
//
// Only do the conversion if the type is not already set
//
if ((inValue.getType() != CIMTYPE_STRING))
{
PEG_METHOD_EXIT();
return;
}
//
// Get the class definition for this property
//
CIMClass cimClass;
try
{
cimClass = _repository->getClass(
request->nameSpace,
request->instanceName.getClassName(),
false, //localOnly,
false, //includeQualifiers,
false, //includeClassOrigin,
CIMPropertyList());
PEG_TRACE((TRC_DISPATCHER, Tracer::LEVEL4,
"CIMOperationRequestDispatcher::_fixSetPropertyValueType - "
"Namespace: %s Class Name: %s",
CSTRING(request->nameSpace.getString()),
CSTRING(request->instanceName.getClassName().getString())));
}
catch (CIMException& exception)
{
// map CIM_ERR_NOT_FOUND to CIM_ERR_INVALID_CLASS
if (exception.getCode() == CIM_ERR_NOT_FOUND)
{
PEG_METHOD_EXIT();
throw PEGASUS_CIM_EXCEPTION(CIM_ERR_INVALID_CLASS,
request->instanceName.getClassName().getString());
}
PEG_METHOD_EXIT();
throw;
}
//
// Get the property definition from the class
//
Uint32 propertyPos = cimClass.findProperty(request->propertyName);
if (propertyPos == PEG_NOT_FOUND)
{
PEG_METHOD_EXIT();
throw PEGASUS_CIM_EXCEPTION(CIM_ERR_NO_SUCH_PROPERTY, String::EMPTY);
}
CIMProperty property = cimClass.getProperty(propertyPos);
//
// Retype the input property value according to the
// type defined in the schema
//
CIMValue newValue;
if (inValue.isNull())
{
newValue.setNullValue(property.getType(), property.isArray());
}
else if (inValue.isArray() != property.isArray())
{
// ATTN-RK-P1-20020222: Who catches this? They aren't.
PEG_METHOD_EXIT();
throw PEGASUS_CIM_EXCEPTION(CIM_ERR_TYPE_MISMATCH, String::EMPTY);
}
else
{
newValue = _convertValueType(inValue, property.getType());
}
//
// Put the retyped value back into the message
//
request->newValue = newValue;
PEG_METHOD_EXIT();
}
/*
Check the existence of a class matching a classname.
Returns true if class found in repository.
Note that this code checks for the special classname
PEGASUS_CLASSNAME___NAMESPACE and returns true.
If the repository returns exception this function returns false
if NOT CIM_ERR_NOT_FOUND. Else, rethrows the exception.
*/
Boolean CIMOperationRequestDispatcher::_checkExistenceOfClass(
const CIMNamespaceName& nameSpace,
const CIMName& className)
{
PEG_METHOD_ENTER(TRC_DISPATCHER,
"CIMOperationRequestDispatcher::_checkExistenceOfClass");
if (className.equal(CIMName(PEGASUS_CLASSNAME___NAMESPACE)))
{
PEG_METHOD_EXIT();
return true;
}
try
{
CIMClass cimClass = _repository->getClass(
nameSpace,
className,
true,
false,
false,
CIMPropertyList());
}
catch (const CIMException& exception)
{
// CIM_ERR_NOT_FOUND indicates that the class is not defined
if (exception.getCode() == CIM_ERR_NOT_FOUND)
{
PEG_METHOD_EXIT();
return false;
}
PEG_METHOD_EXIT();
throw;
}
PEG_TRACE((TRC_DISPATCHER, Tracer::LEVEL4,
"CIMOperationRequestDispatcher::_checkExistenceOfClass - "
"Namespace: %s Class Name: %s found.",
CSTRING(nameSpace.getString()),
CSTRING(className.getString())));
PEG_METHOD_EXIT();
return true;
}
CIMConstClass CIMOperationRequestDispatcher::_getClass(
const CIMNamespaceName& nameSpace,
const CIMName& className,
CIMException& cimException)
{
if (className.equal(CIMName(PEGASUS_CLASSNAME___NAMESPACE)))
{
CIMClass __namespaceClass(PEGASUS_CLASSNAME___NAMESPACE);
// ATTN: Qualifiers not added here, but they shouldn't be needed
__namespaceClass.addProperty(
CIMProperty(PEGASUS_PROPERTYNAME_NAME, String::EMPTY));
return __namespaceClass;
}
CIMConstClass cimClass;
// get the complete class, specifically not local only
try
{
cimClass = _repository->getFullConstClass(
nameSpace,
className);
PEG_TRACE((TRC_DISPATCHER, Tracer::LEVEL3,
"CIMOperationRequestDispatcher::_getClass - "
"Namespace: %s Class Name: %s",
CSTRING(nameSpace.getString()),
CSTRING(className.getString())));
}
catch (const CIMException& exception)
{
// map CIM_ERR_NOT_FOUND to CIM_ERR_INVALID_CLASS
if (exception.getCode() == CIM_ERR_NOT_FOUND)
{
cimException = PEGASUS_CIM_EXCEPTION(
CIM_ERR_INVALID_CLASS, className.getString());
}
else
{
cimException = exception;
}
}
catch (const Exception& exception)
{
cimException =
PEGASUS_CIM_EXCEPTION(CIM_ERR_FAILED, exception.getMessage());
}
catch (...)
{
cimException = PEGASUS_CIM_EXCEPTION(CIM_ERR_FAILED, String::EMPTY);
}
return cimClass;
}
template <class ObjectClass>
void removePropagatedAndOriginAttributes(ObjectClass& newObject)
{
Uint32 numProperties = newObject.getPropertyCount();
for (Uint32 i = 0; i < numProperties; i++)
{
CIMProperty currentProperty = newObject.getProperty(i);
if (currentProperty.getPropagated() == true ||
currentProperty.getClassOrigin().getString().size() > 0)
{
newObject.removeProperty(i);
currentProperty.setPropagated(false);
currentProperty.setClassOrigin(CIMName());
newObject.addProperty(currentProperty);
--i;
}
}
}
//Issue enumerateInstance...ForClass calls to the repository for each class
// that doesn ot have a provider and put the returned responses into the
// ResponseData.
// Handles exceptions from the repository inserting them as CIMException
// into the response.
// This is common code for all Enumerates to the repository because they
// all use the same pattern, doing a enumerate...ForClass loop to get
// the instances/paths for each class that does not have a provider.
//
// TODO: Do we really need the exceptions here? Actually, review to see
// if we really need the enumerate for classes itself and could not just
// use enumerateInstances Since there should NEVER be anything for both
// provider and repository.
//
// Returns a single response in the OperationAggregate object with the
// counters properly set up.
// This function throws an exception of there is an exception from the
// repository.
//
Boolean CIMOperationRequestDispatcher::_enumerateFromRepository(
CIMOperationRequestMessage* request,
OperationAggregate* poA,
ProviderInfoList& providerInfos)
{
PEG_METHOD_ENTER(TRC_DISPATCHER,
"CIMOperationRequestDispatcher::_enumerateFromRepository");
Boolean responsesExist = false;
// Create AutoPtr to force delete if exception
AutoPtr<OperationAggregate> lPoA(poA);
if (_repository->isDefaultInstanceProvider())
{
// Loop through providerInfos, forwarding requests to repository
while (providerInfos.hasMore(false))
{
ProviderInfo& providerInfo = providerInfos.getNext();
// If this class is not registered for provider, get instances
// from repository
PEG_TRACE((TRC_DISPATCHER, Tracer::LEVEL4,
"Routing request for class %s to the "
"repository. Class # %u of %u",
CSTRING(providerInfo.className.getString()),
(providerInfos.getIndex()), providerInfos.size() ));
switch (request->getType())
{
case CIM_ENUMERATE_INSTANCES_REQUEST_MESSAGE:
{
const CIMEnumerateInstancesRequestMessage* req =
reinterpret_cast<const
CIMEnumerateInstancesRequestMessage*>(request);
// create response from request
AutoPtr<CIMEnumerateInstancesResponseMessage> response(
dynamic_cast<CIMEnumerateInstancesResponseMessage*>(
req->buildResponse()));
// Enumerate instances only for this class
response->getResponseData().setInstances(
_repository->enumerateInstancesForClass(
req->nameSpace,
providerInfo.className,
req->includeQualifiers,
req->includeClassOrigin,
req->propertyList));
poA->appendResponse(response.release());
break;
}
case CIM_ENUMERATE_INSTANCE_NAMES_REQUEST_MESSAGE:
{
const CIMEnumerateInstanceNamesRequestMessage* req =
reinterpret_cast<const
CIMEnumerateInstanceNamesRequestMessage*>(request);
// create response from request
AutoPtr<CIMEnumerateInstanceNamesResponseMessage> response(
dynamic_cast<CIMEnumerateInstanceNamesResponseMessage*>(
req->buildResponse()));
// Enumerate instances only for this class
response->getResponseData().setInstanceNames(
_repository->enumerateInstanceNamesForClass(
req->nameSpace,
providerInfo.className));
poA->appendResponse(response.release());
break;
}
default:
{
PEGASUS_UNREACHABLE(PEGASUS_ASSERT(0));
}
} // switch statement
} // while loop
// Set the local number of expected responses counter
responsesExist = (poA->numberResponses() != 0);
if (responsesExist)
{
// Aggregate the responses into a single response object
handleOperationResponseAggregation(poA);
poA->incTotalIssued();
}
}
// release poA and exit with flag indicating responses exist or not
lPoA.release();
PEG_METHOD_EXIT();
return responsesExist;
}
// Forward request to provider unless class does not exist
// If class does not exist, return false
// KS_FUTURE Possibly change this to always send. Sends exception message if
// class get error. No need for Boolean Return
Boolean CIMOperationRequestDispatcher::_forwardEnumerationToProvider(
ProviderInfo &providerInfo,
OperationAggregate* poA,
CIMOperationRequestMessage* request)
{
CIMException checkClassException;
CIMConstClass cimClass = _getClass(
poA->_nameSpace,
providerInfo.className,
checkClassException);
// The following is not clean. Need better way to terminate.
// This builds an error response message in the middle of the
// normal response but lets rest of operation continue.
if (checkClassException.getCode() != CIM_ERR_SUCCESS)
{
CIMResponseMessage* response = request->buildResponse();
response->cimException = checkClassException;
_forwardResponseForAggregation(request, poA, response);
}
else
{
if (providerInfo.providerIdContainer.get() != 0)
{
request->operationContext.insert(
*(providerInfo.providerIdContainer.get()));
}
#ifdef PEGASUS_ENABLE_OBJECT_NORMALIZATION
if (providerInfo.hasProviderNormalization)
{
request->operationContext.insert(
CachedClassDefinitionContainer(cimClass));
}
#endif
_forwardAggregatingRequestToProvider(
providerInfo, request, poA);
}
return true;
}
PEGASUS_NAMESPACE_END
|
// Copyright 2017 Google 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 "nlp/parser/roles.h"
namespace sling {
namespace nlp {
void RoleSet::Init(const ActionTable &actions) {
for (int i = 0; i < actions.NumActions(); ++i) {
const auto &action = actions.Action(i);
if (action.type == ParserAction::CONNECT ||
action.type == ParserAction::ASSIGN ||
action.type == ParserAction::EMBED ||
action.type == ParserAction::ELABORATE) {
if (roles_.find(action.role) == roles_.end()) {
int index = roles_.size();
roles_[action.role] = index;
}
}
}
}
void RoleGraph::Compute(const ParserState &state,
int limit,
const RoleSet &roles) {
limit_ = limit;
num_roles_ = roles.size();
int k = limit_;
edges_.clear();
if (k > state.AttentionSize()) k = state.AttentionSize();
for (int source = 0; source < k; ++source) {
Handle handle = state.frame(state.Attention(source));
const FrameDatum *frame = state.store()->GetFrame(handle);
for (const Slot *slot = frame->begin(); slot < frame->end(); ++slot) {
int target = -1;
if (slot->value.IsIndex()) {
target = state.AttentionIndex(slot->value.AsIndex(), k);
if (target == -1) continue;
}
int role = roles.Lookup(slot->name);
if (role == -1) continue;
edges_.emplace_back(source, role, target);
}
}
}
} // namespace nlp
} // namespace sling
|
/*
*
* Copyright (c) 2021 Project CHIP Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <jni.h>
#include <lib/support/CHIPJNIError.h>
#include <lib/support/CodeUtils.h>
#include <lib/support/JniReferences.h>
#include <lib/support/JniTypeWrappers.h>
namespace chip {
void JniReferences::SetJavaVm(JavaVM * jvm, const char * clsType)
{
VerifyOrReturn(mJvm == nullptr, ChipLogError(Support, "JavaVM is already set"));
mJvm = jvm;
// Cache the classloader for CHIP Java classes. env->FindClass() can start in the system class loader if called from a different
// thread, meaning it won't find our Chip classes.
// https://developer.android.com/training/articles/perf-jni#faq_FindClass
JNIEnv * env = GetEnvForCurrentThread();
// Any chip.devicecontroller.* class will work here - just need something to call getClassLoader() on.
jclass chipClass = env->FindClass(clsType);
VerifyOrReturn(chipClass != nullptr, ChipLogError(Support, "clsType can not found"));
jclass classClass = env->FindClass("java/lang/Class");
jclass classLoaderClass = env->FindClass("java/lang/ClassLoader");
jmethodID getClassLoaderMethod = env->GetMethodID(classClass, "getClassLoader", "()Ljava/lang/ClassLoader;");
mClassLoader = env->NewGlobalRef(env->CallObjectMethod(chipClass, getClassLoaderMethod));
mFindClassMethod = env->GetMethodID(classLoaderClass, "findClass", "(Ljava/lang/String;)Ljava/lang/Class;");
}
JNIEnv * JniReferences::GetEnvForCurrentThread()
{
JNIEnv * env;
if (mJvm == nullptr)
{
ChipLogError(Support, "Missing Java VM");
return nullptr;
}
mJvm->GetEnv((void **) &env, JNI_VERSION_1_6);
if (env == nullptr)
{
jint error;
#ifdef __ANDROID__
error = mJvm->AttachCurrentThreadAsDaemon(&env, nullptr);
#else
error = mJvm->AttachCurrentThreadAsDaemon((void **) &env, nullptr);
#endif
if (error != JNI_OK)
{
ChipLogError(Support, "Failed to get JNIEnv for the current thread");
return nullptr;
}
}
return env;
}
CHIP_ERROR JniReferences::GetClassRef(JNIEnv * env, const char * clsType, jclass & outCls)
{
CHIP_ERROR err = CHIP_NO_ERROR;
jclass cls = nullptr;
cls = env->FindClass(clsType);
env->ExceptionClear();
if (cls == nullptr)
{
// Try the cached classloader if FindClass() didn't work.
cls = static_cast<jclass>(env->CallObjectMethod(mClassLoader, mFindClassMethod, env->NewStringUTF(clsType)));
VerifyOrReturnError(cls != nullptr && env->ExceptionCheck() != JNI_TRUE, CHIP_JNI_ERROR_TYPE_NOT_FOUND);
}
outCls = (jclass) env->NewGlobalRef((jobject) cls);
VerifyOrReturnError(outCls != nullptr, CHIP_JNI_ERROR_TYPE_NOT_FOUND);
return err;
}
CHIP_ERROR JniReferences::N2J_ByteArray(JNIEnv * env, const uint8_t * inArray, jsize inArrayLen, jbyteArray & outArray)
{
CHIP_ERROR err = CHIP_NO_ERROR;
outArray = env->NewByteArray(inArrayLen);
VerifyOrReturnError(outArray != NULL, CHIP_ERROR_NO_MEMORY);
env->ExceptionClear();
env->SetByteArrayRegion(outArray, 0, inArrayLen, (jbyte *) inArray);
VerifyOrExit(!env->ExceptionCheck(), err = CHIP_JNI_ERROR_EXCEPTION_THROWN);
exit:
return err;
}
CHIP_ERROR JniReferences::FindMethod(JNIEnv * env, jobject object, const char * methodName, const char * methodSignature,
jmethodID * methodId)
{
CHIP_ERROR err = CHIP_NO_ERROR;
jclass javaClass = nullptr;
VerifyOrReturnError(env != nullptr && object != nullptr, CHIP_JNI_ERROR_NULL_OBJECT);
javaClass = env->GetObjectClass(object);
VerifyOrReturnError(javaClass != nullptr, CHIP_JNI_ERROR_TYPE_NOT_FOUND);
*methodId = env->GetMethodID(javaClass, methodName, methodSignature);
VerifyOrReturnError(*methodId != nullptr, CHIP_JNI_ERROR_METHOD_NOT_FOUND);
return err;
}
void JniReferences::CallVoidInt(JNIEnv * env, jobject object, const char * methodName, jint argument)
{
CHIP_ERROR err = CHIP_NO_ERROR;
jmethodID method;
err = JniReferences::FindMethod(env, object, methodName, "(I)V", &method);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Support, "Error finding Java method: %" CHIP_ERROR_FORMAT, err.Format());
}
env->ExceptionClear();
env->CallVoidMethod(object, method, argument);
}
void JniReferences::ReportError(JNIEnv * env, CHIP_ERROR cbErr, const char * functName)
{
if (cbErr == CHIP_JNI_ERROR_EXCEPTION_THROWN)
{
ChipLogError(Support, "Java exception thrown in %s", functName);
env->ExceptionDescribe();
}
else
{
const char * errStr;
switch (cbErr.AsInteger())
{
case CHIP_JNI_ERROR_TYPE_NOT_FOUND.AsInteger():
errStr = "JNI type not found";
break;
case CHIP_JNI_ERROR_METHOD_NOT_FOUND.AsInteger():
errStr = "JNI method not found";
break;
case CHIP_JNI_ERROR_FIELD_NOT_FOUND.AsInteger():
errStr = "JNI field not found";
break;
default:
errStr = ErrorStr(cbErr);
break;
}
ChipLogError(Support, "Error in %s : %s", functName, errStr);
}
}
void JniReferences::ThrowError(JNIEnv * env, jclass exceptionCls, CHIP_ERROR errToThrow)
{
env->ExceptionClear();
jmethodID constructor = env->GetMethodID(exceptionCls, "<init>", "(ILjava/lang/String;)V");
VerifyOrReturn(constructor != NULL);
jstring jerrStr = env->NewStringUTF(ErrorStr(errToThrow));
jthrowable outEx = (jthrowable) env->NewObject(exceptionCls, constructor, static_cast<jint>(errToThrow.AsInteger()), jerrStr);
VerifyOrReturn(!env->ExceptionCheck());
env->Throw(outEx);
}
CHIP_ERROR JniReferences::CreateOptional(jobject objectToWrap, jobject & outOptional)
{
JNIEnv * env = GetEnvForCurrentThread();
jclass optionalCls;
chip::JniReferences::GetInstance().GetClassRef(env, "java/util/Optional", optionalCls);
VerifyOrReturnError(optionalCls != nullptr, CHIP_JNI_ERROR_TYPE_NOT_FOUND);
chip::JniClass jniClass(optionalCls);
jmethodID ofMethod = env->GetStaticMethodID(optionalCls, "ofNullable", "(Ljava/lang/Object;)Ljava/util/Optional;");
VerifyOrReturnError(ofMethod != nullptr, CHIP_JNI_ERROR_METHOD_NOT_FOUND);
outOptional = env->CallStaticObjectMethod(optionalCls, ofMethod, objectToWrap);
VerifyOrReturnError(!env->ExceptionCheck(), CHIP_JNI_ERROR_EXCEPTION_THROWN);
return CHIP_NO_ERROR;
}
CHIP_ERROR JniReferences::GetOptionalValue(jobject optionalObj, jobject & optionalValue)
{
JNIEnv * env = GetEnvForCurrentThread();
jclass optionalCls;
chip::JniReferences::GetInstance().GetClassRef(env, "java/util/Optional", optionalCls);
VerifyOrReturnError(optionalCls != nullptr, CHIP_JNI_ERROR_TYPE_NOT_FOUND);
chip::JniClass jniClass(optionalCls);
jmethodID isPresentMethod = env->GetMethodID(optionalCls, "isPresent", "()Z");
VerifyOrReturnError(isPresentMethod != nullptr, CHIP_JNI_ERROR_METHOD_NOT_FOUND);
jboolean isPresent = env->CallBooleanMethod(optionalObj, isPresentMethod);
if (!isPresent)
{
optionalValue = nullptr;
return CHIP_NO_ERROR;
}
jmethodID getMethod = env->GetMethodID(optionalCls, "get", "()Ljava/lang/Object;");
VerifyOrReturnError(getMethod != nullptr, CHIP_JNI_ERROR_METHOD_NOT_FOUND);
optionalValue = env->CallObjectMethod(optionalObj, getMethod);
return CHIP_NO_ERROR;
}
jint JniReferences::IntegerToPrimitive(jobject boxedInteger)
{
JNIEnv * env = GetEnvForCurrentThread();
jclass boxedTypeCls;
chip::JniReferences::GetInstance().GetClassRef(env, "java/lang/Integer", boxedTypeCls);
chip::JniClass jniClass(boxedTypeCls);
jmethodID valueMethod = env->GetMethodID(boxedTypeCls, "intValue", "()I");
return env->CallIntMethod(boxedInteger, valueMethod);
}
jlong JniReferences::LongToPrimitive(jobject boxedLong)
{
JNIEnv * env = GetEnvForCurrentThread();
jclass boxedTypeCls;
chip::JniReferences::GetInstance().GetClassRef(env, "java/lang/Long", boxedTypeCls);
chip::JniClass jniClass(boxedTypeCls);
jmethodID valueMethod = env->GetMethodID(boxedTypeCls, "longValue", "()J");
return env->CallLongMethod(boxedLong, valueMethod);
}
jboolean JniReferences::BooleanToPrimitive(jobject boxedBoolean)
{
JNIEnv * env = GetEnvForCurrentThread();
jclass boxedTypeCls;
chip::JniReferences::GetInstance().GetClassRef(env, "java/lang/Boolean", boxedTypeCls);
chip::JniClass jniClass(boxedTypeCls);
jmethodID valueMethod = env->GetMethodID(boxedTypeCls, "booleanValue", "()Z");
return env->CallBooleanMethod(boxedBoolean, valueMethod);
}
jfloat JniReferences::FloatToPrimitive(jobject boxedFloat)
{
JNIEnv * env = GetEnvForCurrentThread();
jclass boxedTypeCls;
chip::JniReferences::GetInstance().GetClassRef(env, "java/lang/Float", boxedTypeCls);
chip::JniClass jniClass(boxedTypeCls);
jmethodID valueMethod = env->GetMethodID(boxedTypeCls, "floatValue", "()F");
return env->CallFloatMethod(boxedFloat, valueMethod);
}
jdouble JniReferences::DoubleToPrimitive(jobject boxedDouble)
{
JNIEnv * env = GetEnvForCurrentThread();
jclass boxedTypeCls;
chip::JniReferences::GetInstance().GetClassRef(env, "java/lang/Double", boxedTypeCls);
chip::JniClass jniClass(boxedTypeCls);
jmethodID valueMethod = env->GetMethodID(boxedTypeCls, "doubleValue", "()D");
return env->CallDoubleMethod(boxedDouble, valueMethod);
}
CHIP_ERROR JniReferences::CallSubscriptionEstablished(jobject javaCallback)
{
CHIP_ERROR err = CHIP_NO_ERROR;
JNIEnv * env = chip::JniReferences::GetInstance().GetEnvForCurrentThread();
jmethodID subscriptionEstablishedMethod;
err = chip::JniReferences::GetInstance().FindMethod(env, javaCallback, "onSubscriptionEstablished", "()V",
&subscriptionEstablishedMethod);
VerifyOrReturnError(err == CHIP_NO_ERROR, CHIP_JNI_ERROR_METHOD_NOT_FOUND);
env->CallVoidMethod(javaCallback, subscriptionEstablishedMethod);
VerifyOrReturnError(!env->ExceptionCheck(), CHIP_JNI_ERROR_EXCEPTION_THROWN);
return err;
}
} // namespace chip
|
//<snippet1>
// This example demonstrates Math.BigMul()
using namespace System;
int main()
{
int int1 = Int32::MaxValue;
int int2 = Int32::MaxValue;
Int64 longResult;
//
longResult = Math::BigMul( int1, int2 );
Console::WriteLine( "Calculate the product of two Int32 values:" );
Console::WriteLine( "{0} * {1} = {2}", int1, int2, longResult );
}
/*
This example produces the following results:
Calculate the product of two Int32 values:
2147483647 * 2147483647 = 4611686014132420609
*/
//</snippet1>
|
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2016 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#if defined(HAVE_CONFIG_H)
#include "config/apcoin-config.h"
#endif
#include "util.h"
#include "chainparamsbase.h"
#include "random.h"
#include "serialize.h"
#include "sync.h"
#include "utilstrencodings.h"
#include "utiltime.h"
#include <stdarg.h>
#if (defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__DragonFly__))
#include <pthread.h>
#include <pthread_np.h>
#endif
#ifndef WIN32
// for posix_fallocate
#ifdef __linux__
#ifdef _POSIX_C_SOURCE
#undef _POSIX_C_SOURCE
#endif
#define _POSIX_C_SOURCE 200112L
#endif // __linux__
#include <algorithm>
#include <fcntl.h>
#include <sys/resource.h>
#include <sys/stat.h>
#else
#ifdef _MSC_VER
#pragma warning(disable:4786)
#pragma warning(disable:4804)
#pragma warning(disable:4805)
#pragma warning(disable:4717)
#endif
#ifdef _WIN32_WINNT
#undef _WIN32_WINNT
#endif
#define _WIN32_WINNT 0x0501
#ifdef _WIN32_IE
#undef _WIN32_IE
#endif
#define _WIN32_IE 0x0501
#define WIN32_LEAN_AND_MEAN 1
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <io.h> /* for _commit */
#include <shlobj.h>
#endif
#ifdef HAVE_SYS_PRCTL_H
#include <sys/prctl.h>
#endif
#ifdef HAVE_MALLOPT_ARENA_MAX
#include <malloc.h>
#endif
#include <boost/algorithm/string/case_conv.hpp> // for to_lower()
#include <boost/algorithm/string/join.hpp>
#include <boost/algorithm/string/predicate.hpp> // for startswith() and endswith()
#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
#include <boost/foreach.hpp>
#include <boost/program_options/detail/config_file.hpp>
#include <boost/program_options/parsers.hpp>
#include <boost/thread.hpp>
#include <openssl/crypto.h>
#include <openssl/rand.h>
#include <openssl/conf.h>
// Work around clang compilation problem in Boost 1.46:
// /usr/include/boost/program_options/detail/config_file.hpp:163:17: error: call to function 'to_internal' that is neither visible in the template definition nor found by argument-dependent lookup
// See also: http://stackoverflow.com/questions/10020179/compilation-fail-in-boost-librairies-program-options
// http://clang.debian.net/status.php?version=3.0&key=CANNOT_FIND_FUNCTION
namespace boost {
namespace program_options {
std::string to_internal(const std::string&);
}
} // namespace boost
using namespace std;
const char * const APCOIN_CONF_FILENAME = "apcoin.conf";
const char * const APCOIN_PID_FILENAME = "apcoind.pid";
CCriticalSection cs_args;
map<string, string> mapArgs;
static map<string, vector<string> > _mapMultiArgs;
const map<string, vector<string> >& mapMultiArgs = _mapMultiArgs;
bool fDebug = false;
bool fPrintToConsole = false;
bool fPrintToDebugLog = true;
bool fLogTimestamps = DEFAULT_LOGTIMESTAMPS;
bool fLogTimeMicros = DEFAULT_LOGTIMEMICROS;
bool fLogIPs = DEFAULT_LOGIPS;
std::atomic<bool> fReopenDebugLog(false);
CTranslationInterface translationInterface;
/** Init OpenSSL library multithreading support */
static CCriticalSection** ppmutexOpenSSL;
void locking_callback(int mode, int i, const char* file, int line) NO_THREAD_SAFETY_ANALYSIS
{
if (mode & CRYPTO_LOCK) {
ENTER_CRITICAL_SECTION(*ppmutexOpenSSL[i]);
} else {
LEAVE_CRITICAL_SECTION(*ppmutexOpenSSL[i]);
}
}
// Init
class CInit
{
public:
CInit()
{
// Init OpenSSL library multithreading support
ppmutexOpenSSL = (CCriticalSection**)OPENSSL_malloc(CRYPTO_num_locks() * sizeof(CCriticalSection*));
for (int i = 0; i < CRYPTO_num_locks(); i++)
ppmutexOpenSSL[i] = new CCriticalSection();
CRYPTO_set_locking_callback(locking_callback);
// OpenSSL can optionally load a config file which lists optional loadable modules and engines.
// We don't use them so we don't require the config. However some of our libs may call functions
// which attempt to load the config file, possibly resulting in an exit() or crash if it is missing
// or corrupt. Explicitly tell OpenSSL not to try to load the file. The result for our libs will be
// that the config appears to have been loaded and there are no modules/engines available.
OPENSSL_no_config();
#ifdef WIN32
// Seed OpenSSL PRNG with current contents of the screen
RAND_screen();
#endif
// Seed OpenSSL PRNG with performance counter
RandAddSeed();
}
~CInit()
{
// Securely erase the memory used by the PRNG
RAND_cleanup();
// Shutdown OpenSSL library multithreading support
CRYPTO_set_locking_callback(NULL);
for (int i = 0; i < CRYPTO_num_locks(); i++)
delete ppmutexOpenSSL[i];
OPENSSL_free(ppmutexOpenSSL);
}
}
instance_of_cinit;
/**
* LogPrintf() has been broken a couple of times now
* by well-meaning people adding mutexes in the most straightforward way.
* It breaks because it may be called by global destructors during shutdown.
* Since the order of destruction of static/global objects is undefined,
* defining a mutex as a global object doesn't work (the mutex gets
* destroyed, and then some later destructor calls OutputDebugStringF,
* maybe indirectly, and you get a core dump at shutdown trying to lock
* the mutex).
*/
static boost::once_flag debugPrintInitFlag = BOOST_ONCE_INIT;
/**
* We use boost::call_once() to make sure mutexDebugLog and
* vMsgsBeforeOpenLog are initialized in a thread-safe manner.
*
* NOTE: fileout, mutexDebugLog and sometimes vMsgsBeforeOpenLog
* are leaked on exit. This is ugly, but will be cleaned up by
* the OS/libc. When the shutdown sequence is fully audited and
* tested, explicit destruction of these objects can be implemented.
*/
static FILE* fileout = NULL;
static boost::mutex* mutexDebugLog = NULL;
static list<string> *vMsgsBeforeOpenLog;
static int FileWriteStr(const std::string &str, FILE *fp)
{
return fwrite(str.data(), 1, str.size(), fp);
}
static void DebugPrintInit()
{
assert(mutexDebugLog == NULL);
mutexDebugLog = new boost::mutex();
vMsgsBeforeOpenLog = new list<string>;
}
void OpenDebugLog()
{
boost::call_once(&DebugPrintInit, debugPrintInitFlag);
boost::mutex::scoped_lock scoped_lock(*mutexDebugLog);
assert(fileout == NULL);
assert(vMsgsBeforeOpenLog);
boost::filesystem::path pathDebug = GetDataDir() / "debug.log";
fileout = fopen(pathDebug.string().c_str(), "a");
if (fileout) {
setbuf(fileout, NULL); // unbuffered
// dump buffered messages from before we opened the log
while (!vMsgsBeforeOpenLog->empty()) {
FileWriteStr(vMsgsBeforeOpenLog->front(), fileout);
vMsgsBeforeOpenLog->pop_front();
}
}
delete vMsgsBeforeOpenLog;
vMsgsBeforeOpenLog = NULL;
}
bool LogAcceptCategory(const char* category)
{
if (category != NULL)
{
if (!fDebug)
return false;
// Give each thread quick access to -debug settings.
// This helps prevent issues debugging global destructors,
// where mapMultiArgs might be deleted before another
// global destructor calls LogPrint()
static boost::thread_specific_ptr<set<string> > ptrCategory;
if (ptrCategory.get() == NULL)
{
if (mapMultiArgs.count("-debug")) {
const vector<string>& categories = mapMultiArgs.at("-debug");
ptrCategory.reset(new set<string>(categories.begin(), categories.end()));
// thread_specific_ptr automatically deletes the set when the thread ends.
} else
ptrCategory.reset(new set<string>());
}
const set<string>& setCategories = *ptrCategory.get();
// if not debugging everything and not debugging specific category, LogPrint does nothing.
if (setCategories.count(string("")) == 0 &&
setCategories.count(string("1")) == 0 &&
setCategories.count(string(category)) == 0)
return false;
}
return true;
}
/**
* fStartedNewLine is a state variable held by the calling context that will
* suppress printing of the timestamp when multiple calls are made that don't
* end in a newline. Initialize it to true, and hold it, in the calling context.
*/
static std::string LogTimestampStr(const std::string &str, std::atomic_bool *fStartedNewLine)
{
string strStamped;
if (!fLogTimestamps)
return str;
if (*fStartedNewLine) {
int64_t nTimeMicros = GetLogTimeMicros();
strStamped = DateTimeStrFormat("%Y-%m-%d %H:%M:%S", nTimeMicros/1000000);
if (fLogTimeMicros)
strStamped += strprintf(".%06d", nTimeMicros%1000000);
strStamped += ' ' + str;
} else
strStamped = str;
if (!str.empty() && str[str.size()-1] == '\n')
*fStartedNewLine = true;
else
*fStartedNewLine = false;
return strStamped;
}
int LogPrintStr(const std::string &str)
{
int ret = 0; // Returns total number of characters written
static std::atomic_bool fStartedNewLine(true);
string strTimestamped = LogTimestampStr(str, &fStartedNewLine);
if (fPrintToConsole)
{
// print to console
ret = fwrite(strTimestamped.data(), 1, strTimestamped.size(), stdout);
fflush(stdout);
}
else if (fPrintToDebugLog)
{
boost::call_once(&DebugPrintInit, debugPrintInitFlag);
boost::mutex::scoped_lock scoped_lock(*mutexDebugLog);
// buffer if we haven't opened the log yet
if (fileout == NULL) {
assert(vMsgsBeforeOpenLog);
ret = strTimestamped.length();
vMsgsBeforeOpenLog->push_back(strTimestamped);
}
else
{
// reopen the log file, if requested
if (fReopenDebugLog) {
fReopenDebugLog = false;
boost::filesystem::path pathDebug = GetDataDir() / "debug.log";
if (freopen(pathDebug.string().c_str(),"a",fileout) != NULL)
setbuf(fileout, NULL); // unbuffered
}
ret = FileWriteStr(strTimestamped, fileout);
}
}
return ret;
}
/** Interpret string as boolean, for argument parsing */
static bool InterpretBool(const std::string& strValue)
{
if (strValue.empty())
return true;
return (atoi(strValue) != 0);
}
/** Turn -noX into -X=0 */
static void InterpretNegativeSetting(std::string& strKey, std::string& strValue)
{
if (strKey.length()>3 && strKey[0]=='-' && strKey[1]=='n' && strKey[2]=='o')
{
strKey = "-" + strKey.substr(3);
strValue = InterpretBool(strValue) ? "0" : "1";
}
}
void ParseParameters(int argc, const char* const argv[])
{
LOCK(cs_args);
mapArgs.clear();
_mapMultiArgs.clear();
for (int i = 1; i < argc; i++)
{
std::string str(argv[i]);
std::string strValue;
size_t is_index = str.find('=');
if (is_index != std::string::npos)
{
strValue = str.substr(is_index+1);
str = str.substr(0, is_index);
}
#ifdef WIN32
boost::to_lower(str);
if (boost::algorithm::starts_with(str, "/"))
str = "-" + str.substr(1);
#endif
if (str[0] != '-')
break;
// Interpret --foo as -foo.
// If both --foo and -foo are set, the last takes effect.
if (str.length() > 1 && str[1] == '-')
str = str.substr(1);
InterpretNegativeSetting(str, strValue);
mapArgs[str] = strValue;
_mapMultiArgs[str].push_back(strValue);
}
}
bool IsArgSet(const std::string& strArg)
{
LOCK(cs_args);
return mapArgs.count(strArg);
}
std::string GetArg(const std::string& strArg, const std::string& strDefault)
{
LOCK(cs_args);
if (mapArgs.count(strArg))
return mapArgs[strArg];
return strDefault;
}
int64_t GetArg(const std::string& strArg, int64_t nDefault)
{
LOCK(cs_args);
if (mapArgs.count(strArg))
return atoi64(mapArgs[strArg]);
return nDefault;
}
bool GetBoolArg(const std::string& strArg, bool fDefault)
{
LOCK(cs_args);
if (mapArgs.count(strArg))
return InterpretBool(mapArgs[strArg]);
return fDefault;
}
bool SoftSetArg(const std::string& strArg, const std::string& strValue)
{
LOCK(cs_args);
if (mapArgs.count(strArg))
return false;
mapArgs[strArg] = strValue;
return true;
}
bool SoftSetBoolArg(const std::string& strArg, bool fValue)
{
if (fValue)
return SoftSetArg(strArg, std::string("1"));
else
return SoftSetArg(strArg, std::string("0"));
}
void ForceSetArg(const std::string& strArg, const std::string& strValue)
{
LOCK(cs_args);
mapArgs[strArg] = strValue;
}
static const int screenWidth = 79;
static const int optIndent = 2;
static const int msgIndent = 7;
std::string HelpMessageGroup(const std::string &message) {
return std::string(message) + std::string("\n\n");
}
std::string HelpMessageOpt(const std::string &option, const std::string &message) {
return std::string(optIndent,' ') + std::string(option) +
std::string("\n") + std::string(msgIndent,' ') +
FormatParagraph(message, screenWidth - msgIndent, msgIndent) +
std::string("\n\n");
}
static std::string FormatException(const std::exception* pex, const char* pszThread)
{
#ifdef WIN32
char pszModule[MAX_PATH] = "";
GetModuleFileNameA(NULL, pszModule, sizeof(pszModule));
#else
const char* pszModule = "apcoin";
#endif
if (pex)
return strprintf(
"EXCEPTION: %s \n%s \n%s in %s \n", typeid(*pex).name(), pex->what(), pszModule, pszThread);
else
return strprintf(
"UNKNOWN EXCEPTION \n%s in %s \n", pszModule, pszThread);
}
void PrintExceptionContinue(const std::exception* pex, const char* pszThread)
{
std::string message = FormatException(pex, pszThread);
LogPrintf("\n\n************************\n%s\n", message);
fprintf(stderr, "\n\n************************\n%s\n", message.c_str());
}
boost::filesystem::path GetDefaultDataDir()
{
namespace fs = boost::filesystem;
// Windows < Vista: C:\Documents and Settings\Username\Application Data\Apcoin
// Windows >= Vista: C:\Users\Username\AppData\Roaming\Apcoin
// Mac: ~/Library/Application Support/Apcoin
// Unix: ~/.apcoin
#ifdef WIN32
// Windows
return GetSpecialFolderPath(CSIDL_APPDATA) / "Apcoin";
#else
fs::path pathRet;
char* pszHome = getenv("HOME");
if (pszHome == NULL || strlen(pszHome) == 0)
pathRet = fs::path("/");
else
pathRet = fs::path(pszHome);
#ifdef MAC_OSX
// Mac
return pathRet / "Library/Application Support/Apcoin";
#else
// Unix
return pathRet / ".apcoin";
#endif
#endif
}
static boost::filesystem::path pathCached;
static boost::filesystem::path pathCachedNetSpecific;
static CCriticalSection csPathCached;
const boost::filesystem::path &GetDataDir(bool fNetSpecific)
{
namespace fs = boost::filesystem;
LOCK(csPathCached);
fs::path &path = fNetSpecific ? pathCachedNetSpecific : pathCached;
// This can be called during exceptions by LogPrintf(), so we cache the
// value so we don't have to do memory allocations after that.
if (!path.empty())
return path;
if (IsArgSet("-datadir")) {
path = fs::system_complete(GetArg("-datadir", ""));
if (!fs::is_directory(path)) {
path = "";
return path;
}
} else {
path = GetDefaultDataDir();
}
if (fNetSpecific)
path /= BaseParams().DataDir();
fs::create_directories(path);
return path;
}
void ClearDatadirCache()
{
LOCK(csPathCached);
pathCached = boost::filesystem::path();
pathCachedNetSpecific = boost::filesystem::path();
}
boost::filesystem::path GetConfigFile(const std::string& confPath)
{
boost::filesystem::path pathConfigFile(confPath);
if (!pathConfigFile.is_complete())
pathConfigFile = GetDataDir(false) / pathConfigFile;
return pathConfigFile;
}
void ReadConfigFile(const std::string& confPath)
{
boost::filesystem::ifstream streamConfig(GetConfigFile(confPath));
if (!streamConfig.good())
return; // No apcoin.conf file is OK
{
LOCK(cs_args);
set<string> setOptions;
setOptions.insert("*");
for (boost::program_options::detail::config_file_iterator it(streamConfig, setOptions), end; it != end; ++it)
{
// Don't overwrite existing settings so command line settings override apcoin.conf
string strKey = string("-") + it->string_key;
string strValue = it->value[0];
InterpretNegativeSetting(strKey, strValue);
if (mapArgs.count(strKey) == 0)
mapArgs[strKey] = strValue;
_mapMultiArgs[strKey].push_back(strValue);
}
}
// If datadir is changed in .conf file:
ClearDatadirCache();
}
#ifndef WIN32
boost::filesystem::path GetPidFile()
{
boost::filesystem::path pathPidFile(GetArg("-pid", APCOIN_PID_FILENAME));
if (!pathPidFile.is_complete()) pathPidFile = GetDataDir() / pathPidFile;
return pathPidFile;
}
void CreatePidFile(const boost::filesystem::path &path, pid_t pid)
{
FILE* file = fopen(path.string().c_str(), "w");
if (file)
{
fprintf(file, "%d\n", pid);
fclose(file);
}
}
#endif
bool RenameOver(boost::filesystem::path src, boost::filesystem::path dest)
{
#ifdef WIN32
return MoveFileExA(src.string().c_str(), dest.string().c_str(),
MOVEFILE_REPLACE_EXISTING) != 0;
#else
int rc = std::rename(src.string().c_str(), dest.string().c_str());
return (rc == 0);
#endif /* WIN32 */
}
/**
* Ignores exceptions thrown by Boost's create_directory if the requested directory exists.
* Specifically handles case where path p exists, but it wasn't possible for the user to
* write to the parent directory.
*/
bool TryCreateDirectory(const boost::filesystem::path& p)
{
try
{
return boost::filesystem::create_directory(p);
} catch (const boost::filesystem::filesystem_error&) {
if (!boost::filesystem::exists(p) || !boost::filesystem::is_directory(p))
throw;
}
// create_directory didn't create the directory, it had to have existed already
return false;
}
void FileCommit(FILE *file)
{
fflush(file); // harmless if redundantly called
#ifdef WIN32
HANDLE hFile = (HANDLE)_get_osfhandle(_fileno(file));
FlushFileBuffers(hFile);
#else
#if defined(__linux__) || defined(__NetBSD__)
fdatasync(fileno(file));
#elif defined(__APPLE__) && defined(F_FULLFSYNC)
fcntl(fileno(file), F_FULLFSYNC, 0);
#else
fsync(fileno(file));
#endif
#endif
}
bool TruncateFile(FILE *file, unsigned int length) {
#if defined(WIN32)
return _chsize(_fileno(file), length) == 0;
#else
return ftruncate(fileno(file), length) == 0;
#endif
}
/**
* this function tries to raise the file descriptor limit to the requested number.
* It returns the actual file descriptor limit (which may be more or less than nMinFD)
*/
int RaiseFileDescriptorLimit(int nMinFD) {
#if defined(WIN32)
return 2048;
#else
struct rlimit limitFD;
if (getrlimit(RLIMIT_NOFILE, &limitFD) != -1) {
if (limitFD.rlim_cur < (rlim_t)nMinFD) {
limitFD.rlim_cur = nMinFD;
if (limitFD.rlim_cur > limitFD.rlim_max)
limitFD.rlim_cur = limitFD.rlim_max;
setrlimit(RLIMIT_NOFILE, &limitFD);
getrlimit(RLIMIT_NOFILE, &limitFD);
}
return limitFD.rlim_cur;
}
return nMinFD; // getrlimit failed, assume it's fine
#endif
}
/**
* this function tries to make a particular range of a file allocated (corresponding to disk space)
* it is advisory, and the range specified in the arguments will never contain live data
*/
void AllocateFileRange(FILE *file, unsigned int offset, unsigned int length) {
#if defined(WIN32)
// Windows-specific version
HANDLE hFile = (HANDLE)_get_osfhandle(_fileno(file));
LARGE_INTEGER nFileSize;
int64_t nEndPos = (int64_t)offset + length;
nFileSize.u.LowPart = nEndPos & 0xFFFFFFFF;
nFileSize.u.HighPart = nEndPos >> 32;
SetFilePointerEx(hFile, nFileSize, 0, FILE_BEGIN);
SetEndOfFile(hFile);
#elif defined(MAC_OSX)
// OSX specific version
fstore_t fst;
fst.fst_flags = F_ALLOCATECONTIG;
fst.fst_posmode = F_PEOFPOSMODE;
fst.fst_offset = 0;
fst.fst_length = (off_t)offset + length;
fst.fst_bytesalloc = 0;
if (fcntl(fileno(file), F_PREALLOCATE, &fst) == -1) {
fst.fst_flags = F_ALLOCATEALL;
fcntl(fileno(file), F_PREALLOCATE, &fst);
}
ftruncate(fileno(file), fst.fst_length);
#elif defined(__linux__)
// Version using posix_fallocate
off_t nEndPos = (off_t)offset + length;
posix_fallocate(fileno(file), 0, nEndPos);
#else
// Fallback version
// TODO: just write one byte per block
static const char buf[65536] = {};
fseek(file, offset, SEEK_SET);
while (length > 0) {
unsigned int now = 65536;
if (length < now)
now = length;
fwrite(buf, 1, now, file); // allowed to fail; this function is advisory anyway
length -= now;
}
#endif
}
void ShrinkDebugFile()
{
// Amount of debug.log to save at end when shrinking (must fit in memory)
constexpr size_t RECENT_DEBUG_HISTORY_SIZE = 10 * 1000000;
// Scroll debug.log if it's getting too big
boost::filesystem::path pathLog = GetDataDir() / "debug.log";
FILE* file = fopen(pathLog.string().c_str(), "r");
// If debug.log file is more than 10% bigger the RECENT_DEBUG_HISTORY_SIZE
// trim it down by saving only the last RECENT_DEBUG_HISTORY_SIZE bytes
if (file && boost::filesystem::file_size(pathLog) > 11 * (RECENT_DEBUG_HISTORY_SIZE / 10))
{
// Restart the file with some of the end
std::vector<char> vch(RECENT_DEBUG_HISTORY_SIZE, 0);
fseek(file, -((long)vch.size()), SEEK_END);
int nBytes = fread(vch.data(), 1, vch.size(), file);
fclose(file);
file = fopen(pathLog.string().c_str(), "w");
if (file)
{
fwrite(vch.data(), 1, nBytes, file);
fclose(file);
}
}
else if (file != NULL)
fclose(file);
}
#ifdef WIN32
boost::filesystem::path GetSpecialFolderPath(int nFolder, bool fCreate)
{
namespace fs = boost::filesystem;
char pszPath[MAX_PATH] = "";
if(SHGetSpecialFolderPathA(NULL, pszPath, nFolder, fCreate))
{
return fs::path(pszPath);
}
LogPrintf("SHGetSpecialFolderPathA() failed, could not obtain requested path.\n");
return fs::path("");
}
#endif
void runCommand(const std::string& strCommand)
{
int nErr = ::system(strCommand.c_str());
if (nErr)
LogPrintf("runCommand error: system(%s) returned %d\n", strCommand, nErr);
}
void RenameThread(const char* name)
{
#if defined(PR_SET_NAME)
// Only the first 15 characters are used (16 - NUL terminator)
::prctl(PR_SET_NAME, name, 0, 0, 0);
#elif (defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__DragonFly__))
pthread_set_name_np(pthread_self(), name);
#elif defined(MAC_OSX)
pthread_setname_np(name);
#else
// Prevent warnings for unused parameters...
(void)name;
#endif
}
void SetupEnvironment()
{
#ifdef HAVE_MALLOPT_ARENA_MAX
// glibc-specific: On 32-bit systems set the number of arenas to 1.
// By default, since glibc 2.10, the C library will create up to two heap
// arenas per core. This is known to cause excessive virtual address space
// usage in our usage. Work around it by setting the maximum number of
// arenas to 1.
if (sizeof(void*) == 4) {
mallopt(M_ARENA_MAX, 1);
}
#endif
// On most POSIX systems (e.g. Linux, but not BSD) the environment's locale
// may be invalid, in which case the "C" locale is used as fallback.
#if !defined(WIN32) && !defined(MAC_OSX) && !defined(__FreeBSD__) && !defined(__OpenBSD__)
try {
std::locale(""); // Raises a runtime error if current locale is invalid
} catch (const std::runtime_error&) {
setenv("LC_ALL", "C", 1);
}
#endif
// The path locale is lazy initialized and to avoid deinitialization errors
// in multithreading environments, it is set explicitly by the main thread.
// A dummy locale is used to extract the internal default locale, used by
// boost::filesystem::path, which is then used to explicitly imbue the path.
std::locale loc = boost::filesystem::path::imbue(std::locale::classic());
boost::filesystem::path::imbue(loc);
}
bool SetupNetworking()
{
#ifdef WIN32
// Initialize Windows Sockets
WSADATA wsadata;
int ret = WSAStartup(MAKEWORD(2,2), &wsadata);
if (ret != NO_ERROR || LOBYTE(wsadata.wVersion ) != 2 || HIBYTE(wsadata.wVersion) != 2)
return false;
#endif
return true;
}
int GetNumCores()
{
#if BOOST_VERSION >= 105600
return boost::thread::physical_concurrency();
#else // Must fall back to hardware_concurrency, which unfortunately counts virtual cores
return boost::thread::hardware_concurrency();
#endif
}
std::string CopyrightHolders(const std::string& strPrefix)
{
std::string strCopyrightHolders = strPrefix + strprintf(_(COPYRIGHT_HOLDERS), _(COPYRIGHT_HOLDERS_SUBSTITUTION));
// Check for untranslated substitution to make sure Bitcoin Core copyright is not removed by accident
if (strprintf(COPYRIGHT_HOLDERS, COPYRIGHT_HOLDERS_SUBSTITUTION).find("Apcoin Core") == std::string::npos) {
strCopyrightHolders += "\n" + strPrefix + "The Bitcoin Core developers";
}
return strCopyrightHolders;
}
|
// test_find_location.cpp
// Copyright John Maddock 2007.
// Copyright Paul A. Bristow 2007.
// 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)
// Basic sanity test for find_location function.
// Default domain error policy is
// #define BOOST_MATH_DOMAIN_ERROR_POLICY throw_on_error
#include <pch.hpp>
#include <boost/math/tools/test.hpp>
#include <boost/math/concepts/real_concept.hpp> // for real_concept
#include <boost/math/distributions/normal.hpp> // for normal_distribution
using boost::math::normal; // Default type double.
using boost::math::normal_distribution; // All floating-point types.
#include <boost/math/distributions/cauchy.hpp> // for cauchy_distribution
using boost::math::cauchy;
#include <boost/math/distributions/pareto.hpp> // for cauchy_distribution
using boost::math::pareto;
#include <boost/math/distributions/find_location.hpp>
using boost::math::find_location;
using boost::math::complement;// will be needed by users who want complement,
#include <boost/math/policies/policy.hpp>
using boost::math::policies::policy;
#define BOOST_TEST_MAIN
#include <boost/test/unit_test.hpp> // for test_main
#include <boost/test/floating_point_comparison.hpp> // for BOOST_CHECK_CLOSE_FRACTION, BOOST_CHECK_EQUAL...
#include <iostream>
#include <iomanip>
using std::cout; using std::endl; using std::fixed;
using std::right; using std::left; using std::showpoint;
using std::showpos; using std::setw; using std::setprecision;
#include <limits>
using std::numeric_limits;
template <class RealType> // Any floating-point type RealType.
void test_spots(RealType)
{ // Parameter only provides the type, float, double... value ignored.
// Basic sanity checks, test data may be to double precision only
// so set tolerance to 100 eps expressed as a fraction,
// or 100 eps of type double expressed as a fraction,
// whichever is the larger.
RealType tolerance = (std::max)
(boost::math::tools::epsilon<RealType>(),
static_cast<RealType>(std::numeric_limits<double>::epsilon()));
tolerance *= 100; // 100 eps as a fraction.
cout << "Tolerance for type " << typeid(RealType).name() << " is "
<< setprecision(3) << tolerance << " (or " << tolerance * 100 << "%)." << endl;
BOOST_MATH_CHECK_THROW( // Probability outside 0 to 1.
find_location<normal_distribution<RealType> >(
static_cast<RealType>(0.), static_cast<RealType>(-1.), static_cast<RealType>(0.) ),
std::domain_error);
normal_distribution<RealType> n; // standard N(0,1)
BOOST_CHECK_EQUAL(n.location(), 0); // aka mean.
BOOST_CHECK_EQUAL(n.scale(), 1); // aka standard_deviation.
// Check for 'bad' arguments.
BOOST_MATH_CHECK_THROW(find_location<normal>(0., -1., 0.), std::domain_error); // p below 0 to 1.
BOOST_MATH_CHECK_THROW(find_location<normal>(0., 2., 0.), std::domain_error); // p above 0 to 1.
BOOST_MATH_CHECK_THROW(find_location<normal>(numeric_limits<double>::infinity(), 0.5, 0.),
std::domain_error); // z not finite.
BOOST_MATH_CHECK_THROW(find_location<normal>(numeric_limits<double>::quiet_NaN(), -1., 0.),
std::domain_error); // z not finite
BOOST_MATH_CHECK_THROW(find_location<normal>(0., -1., numeric_limits<double>::quiet_NaN()),
std::domain_error); // scale not finite
BOOST_MATH_CHECK_THROW(find_location<normal>(complement(0., -1., 0.)), std::domain_error); // p below 0 to 1.
BOOST_MATH_CHECK_THROW(find_location<normal>(complement(0., 2., 0.)), std::domain_error); // p above 0 to 1.
BOOST_MATH_CHECK_THROW(find_location<normal>(complement(numeric_limits<double>::infinity(), 0.5, 0.)),
std::domain_error); // z not finite.
BOOST_MATH_CHECK_THROW(find_location<normal>(complement(numeric_limits<double>::quiet_NaN(), -1., 0.)),
std::domain_error); // z not finite
BOOST_MATH_CHECK_THROW(find_location<normal>(complement(0., -1., numeric_limits<double>::quiet_NaN())),
std::domain_error); // scale not finite
//// Check for ab-use with unsuitable distribution(s) when concept check implemented.
// BOOST_MATH_CHECK_THROW(find_location<pareto>(0., 0.5, 0.), std::domain_error); // pareto can't be used with find_location.
// Check doesn't throw when an ignore_error for domain_error policy is used.
using boost::math::policies::policy;
using boost::math::policies::domain_error;
using boost::math::policies::ignore_error;
// Define a (bad?) policy to ignore domain errors ('bad' arguments):
typedef policy<domain_error<ignore_error> > ignore_domain_policy;
// Using a typedef is convenient, especially if it is re-used.
#ifndef BOOST_NO_EXCEPTIONS
BOOST_CHECK_NO_THROW(find_location<normal>(0, -1, 1,
ignore_domain_policy())); // probability outside [0, 1]
BOOST_CHECK_NO_THROW(find_location<normal>(numeric_limits<double>::infinity(), -1, 1,
ignore_domain_policy())); // z not finite.
BOOST_CHECK_NO_THROW(find_location<normal>(complement(0, -1, 1,
ignore_domain_policy()))); // probability outside [0, 1]
BOOST_CHECK_NO_THROW(find_location<normal>(complement(numeric_limits<double>::infinity(), -1, 1,
ignore_domain_policy()))); // z not finite.
#endif
// Find location to give a probability p (0.05) of z (-2)
RealType sd = static_cast<RealType>(1); // normal default standard deviation = 1.
RealType z = static_cast<RealType>(-2); // z to give prob p
RealType p = static_cast<RealType>(0.05); // only 5% will be below z
RealType l = find_location<normal_distribution<RealType> >(z, p, sd);
// cout << z << " " << p << " " << sd << " " << l << endl;
normal_distribution<RealType> np05pc(l, sd); // Same standard_deviation (scale) but with mean(location) shifted.
// cout << "Normal distribution with mean = " << l << " has " << "fraction <= " << z << " = " << cdf(np05pc, z) << endl;
// Check cdf such that only fraction p really is below offset mean l.
BOOST_CHECK_CLOSE_FRACTION(p, cdf(np05pc, z), tolerance);
// Check that some policies can be applied (though not used here).
l = find_location<normal_distribution<RealType> >(z, p, sd, policy<>()); // Default policy, needs using boost::math::policies::policy;
l = find_location<normal_distribution<RealType> >(z, p, sd, boost::math::policies::policy<>()); // Default policy, fully specified.
l = find_location<normal_distribution<RealType> >(z, p, sd, ignore_domain_policy()); // find_location with new policy, using typedef.
l = find_location<normal_distribution<RealType> >(z, p, sd, policy<domain_error<ignore_error> >()); // New policy, without typedef.
// Check that can use the complement version.
RealType q = 1 - p; // complement.
// cout << "find_location<normal_distribution<RealType> >(complement(z, q, sd)) = " << endl;
l = find_location<normal_distribution<RealType> >(complement(z, q, sd));
normal_distribution<RealType> np95pc(l, sd); // Same standard_deviation (scale) but with mean(location) shifted
// cout << "Normal distribution with mean = " << l << " has " << "fraction <= " << z << " = " << cdf(np95pc, z) << endl;
BOOST_CHECK_CLOSE_FRACTION(q, cdf(np95pc, z), tolerance);
} // template <class RealType>void test_spots(RealType)
BOOST_AUTO_TEST_CASE( test_main )
{
// Basic sanity-check spot values.
// (Parameter value, arbitrarily zero, only communicates the floating-point type).
test_spots(0.0F); // Test float.
test_spots(0.0); // Test double.
#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS
test_spots(0.0L); // Test long double.
#if !BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x0582))
test_spots(boost::math::concepts::real_concept(0.)); // Test real concept.
#endif
#else
std::cout << "<note>The long double tests have been disabled on this platform "
"either because the long double overloads of the usual math functions are "
"not available at all, or because they are too inaccurate for these tests "
"to pass.</note>" << std::endl;
#endif
} // BOOST_AUTO_TEST_CASE( test_main )
/*
Output is:
Autorun "i:\boost-06-05-03-1300\libs\math\test\Math_test\debug\test_find_location.exe"
Running 1 test case...
Tolerance for type float is 1.19e-005 (or 0.00119%).
Tolerance for type double is 2.22e-014 (or 2.22e-012%).
Tolerance for type long double is 2.22e-014 (or 2.22e-012%).
Tolerance for type class boost::math::concepts::real_concept is 2.22e-014 (or 2.22e-012%).
*** No errors detected
*/
|
//===-- safestack.cc ------------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file implements the runtime support for the safe stack protection
// mechanism. The runtime manages allocation/deallocation of the unsafe stack
// for the main thread, as well as all pthreads that are created/destroyed
// during program execution.
//
//===----------------------------------------------------------------------===//
#include "safestack_platform.h"
#include "safestack_util.h"
#include <errno.h>
#include <sys/resource.h>
#include "interception/interception.h"
using namespace safestack;
// TODO: To make accessing the unsafe stack pointer faster, we plan to
// eventually store it directly in the thread control block data structure on
// platforms where this structure is pointed to by %fs or %gs. This is exactly
// the same mechanism as currently being used by the traditional stack
// protector pass to store the stack guard (see getStackCookieLocation()
// function above). Doing so requires changing the tcbhead_t struct in glibc
// on Linux and tcb struct in libc on FreeBSD.
//
// For now, store it in a thread-local variable.
extern "C" {
__attribute__((visibility(
"default"))) __thread void *__safestack_unsafe_stack_ptr = nullptr;
}
namespace {
// TODO: The runtime library does not currently protect the safe stack beyond
// relying on the system-enforced ASLR. The protection of the (safe) stack can
// be provided by three alternative features:
//
// 1) Protection via hardware segmentation on x86-32 and some x86-64
// architectures: the (safe) stack segment (implicitly accessed via the %ss
// segment register) can be separated from the data segment (implicitly
// accessed via the %ds segment register). Dereferencing a pointer to the safe
// segment would result in a segmentation fault.
//
// 2) Protection via software fault isolation: memory writes that are not meant
// to access the safe stack can be prevented from doing so through runtime
// instrumentation. One way to do it is to allocate the safe stack(s) in the
// upper half of the userspace and bitmask the corresponding upper bit of the
// memory addresses of memory writes that are not meant to access the safe
// stack.
//
// 3) Protection via information hiding on 64 bit architectures: the location
// of the safe stack(s) can be randomized through secure mechanisms, and the
// leakage of the stack pointer can be prevented. Currently, libc can leak the
// stack pointer in several ways (e.g. in longjmp, signal handling, user-level
// context switching related functions, etc.). These can be fixed in libc and
// in other low-level libraries, by either eliminating the escaping/dumping of
// the stack pointer (i.e., %rsp) when that's possible, or by using
// encryption/PTR_MANGLE (XOR-ing the dumped stack pointer with another secret
// we control and protect better, as is already done for setjmp in glibc.)
// Furthermore, a static machine code level verifier can be ran after code
// generation to make sure that the stack pointer is never written to memory,
// or if it is, its written on the safe stack.
//
// Finally, while the Unsafe Stack pointer is currently stored in a thread
// local variable, with libc support it could be stored in the TCB (thread
// control block) as well, eliminating another level of indirection and making
// such accesses faster. Alternatively, dedicating a separate register for
// storing it would also be possible.
/// Minimum stack alignment for the unsafe stack.
const unsigned kStackAlign = 16;
/// Default size of the unsafe stack. This value is only used if the stack
/// size rlimit is set to infinity.
const unsigned kDefaultUnsafeStackSize = 0x2800000;
// Per-thread unsafe stack information. It's not frequently accessed, so there
// it can be kept out of the tcb in normal thread-local variables.
__thread void *unsafe_stack_start = nullptr;
__thread size_t unsafe_stack_size = 0;
__thread size_t unsafe_stack_guard = 0;
inline void *unsafe_stack_alloc(size_t size, size_t guard) {
SFS_CHECK(size + guard >= size);
void *addr = Mmap(nullptr, size + guard, PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANON, -1, 0);
SFS_CHECK(MAP_FAILED != addr);
Mprotect(addr, guard, PROT_NONE);
return (char *)addr + guard;
}
inline void unsafe_stack_setup(void *start, size_t size, size_t guard) {
SFS_CHECK((char *)start + size >= (char *)start);
SFS_CHECK((char *)start + guard >= (char *)start);
void *stack_ptr = (char *)start + size;
SFS_CHECK((((size_t)stack_ptr) & (kStackAlign - 1)) == 0);
__safestack_unsafe_stack_ptr = stack_ptr;
unsafe_stack_start = start;
unsafe_stack_size = size;
unsafe_stack_guard = guard;
}
/// Thread data for the cleanup handler
pthread_key_t thread_cleanup_key;
/// Safe stack per-thread information passed to the thread_start function
struct tinfo {
void *(*start_routine)(void *);
void *start_routine_arg;
void *unsafe_stack_start;
size_t unsafe_stack_size;
size_t unsafe_stack_guard;
};
/// Wrap the thread function in order to deallocate the unsafe stack when the
/// thread terminates by returning from its main function.
void *thread_start(void *arg) {
struct tinfo *tinfo = (struct tinfo *)arg;
void *(*start_routine)(void *) = tinfo->start_routine;
void *start_routine_arg = tinfo->start_routine_arg;
// Setup the unsafe stack; this will destroy tinfo content
unsafe_stack_setup(tinfo->unsafe_stack_start, tinfo->unsafe_stack_size,
tinfo->unsafe_stack_guard);
// Make sure out thread-specific destructor will be called
pthread_setspecific(thread_cleanup_key, (void *)1);
return start_routine(start_routine_arg);
}
/// Linked list used to store exiting threads stack/thread information.
struct thread_stack_ll {
struct thread_stack_ll *next;
void *stack_base;
size_t size;
pid_t pid;
ThreadId tid;
};
/// Linked list of unsafe stacks for threads that are exiting. We delay
/// unmapping them until the thread exits.
thread_stack_ll *thread_stacks = nullptr;
pthread_mutex_t thread_stacks_mutex = PTHREAD_MUTEX_INITIALIZER;
/// Thread-specific data destructor. We want to free the unsafe stack only after
/// this thread is terminated. libc can call functions in safestack-instrumented
/// code (like free) after thread-specific data destructors have run.
void thread_cleanup_handler(void *_iter) {
SFS_CHECK(unsafe_stack_start != nullptr);
pthread_setspecific(thread_cleanup_key, NULL);
pthread_mutex_lock(&thread_stacks_mutex);
// Temporary list to hold the previous threads stacks so we don't hold the
// thread_stacks_mutex for long.
thread_stack_ll *temp_stacks = thread_stacks;
thread_stacks = nullptr;
pthread_mutex_unlock(&thread_stacks_mutex);
pid_t pid = getpid();
ThreadId tid = GetTid();
// Free stacks for dead threads
thread_stack_ll **stackp = &temp_stacks;
while (*stackp) {
thread_stack_ll *stack = *stackp;
if (stack->pid != pid ||
(-1 == TgKill(stack->pid, stack->tid, 0) && errno == ESRCH)) {
Munmap(stack->stack_base, stack->size);
*stackp = stack->next;
free(stack);
} else
stackp = &stack->next;
}
thread_stack_ll *cur_stack =
(thread_stack_ll *)malloc(sizeof(thread_stack_ll));
cur_stack->stack_base = (char *)unsafe_stack_start - unsafe_stack_guard;
cur_stack->size = unsafe_stack_size + unsafe_stack_guard;
cur_stack->pid = pid;
cur_stack->tid = tid;
pthread_mutex_lock(&thread_stacks_mutex);
// Merge thread_stacks with the current thread's stack and any remaining
// temp_stacks
*stackp = thread_stacks;
cur_stack->next = temp_stacks;
thread_stacks = cur_stack;
pthread_mutex_unlock(&thread_stacks_mutex);
unsafe_stack_start = nullptr;
}
void EnsureInterceptorsInitialized();
/// Intercept thread creation operation to allocate and setup the unsafe stack
INTERCEPTOR(int, pthread_create, pthread_t *thread,
const pthread_attr_t *attr,
void *(*start_routine)(void*), void *arg) {
EnsureInterceptorsInitialized();
size_t size = 0;
size_t guard = 0;
if (attr) {
pthread_attr_getstacksize(attr, &size);
pthread_attr_getguardsize(attr, &guard);
} else {
// get pthread default stack size
pthread_attr_t tmpattr;
pthread_attr_init(&tmpattr);
pthread_attr_getstacksize(&tmpattr, &size);
pthread_attr_getguardsize(&tmpattr, &guard);
pthread_attr_destroy(&tmpattr);
}
SFS_CHECK(size);
size = RoundUpTo(size, kStackAlign);
void *addr = unsafe_stack_alloc(size, guard);
// Put tinfo at the end of the buffer. guard may be not page aligned.
// If that is so then some bytes after addr can be mprotected.
struct tinfo *tinfo =
(struct tinfo *)(((char *)addr) + size - sizeof(struct tinfo));
tinfo->start_routine = start_routine;
tinfo->start_routine_arg = arg;
tinfo->unsafe_stack_start = addr;
tinfo->unsafe_stack_size = size;
tinfo->unsafe_stack_guard = guard;
return REAL(pthread_create)(thread, attr, thread_start, tinfo);
}
pthread_mutex_t interceptor_init_mutex = PTHREAD_MUTEX_INITIALIZER;
bool interceptors_inited = false;
void EnsureInterceptorsInitialized() {
MutexLock lock(interceptor_init_mutex);
if (interceptors_inited)
return;
// Initialize pthread interceptors for thread allocation
INTERCEPT_FUNCTION(pthread_create);
interceptors_inited = true;
}
} // namespace
extern "C" __attribute__((visibility("default")))
#if !SANITIZER_CAN_USE_PREINIT_ARRAY
// On ELF platforms, the constructor is invoked using .preinit_array (see below)
__attribute__((constructor(0)))
#endif
void __safestack_init() {
// Determine the stack size for the main thread.
size_t size = kDefaultUnsafeStackSize;
size_t guard = 4096;
struct rlimit limit;
if (getrlimit(RLIMIT_STACK, &limit) == 0 && limit.rlim_cur != RLIM_INFINITY)
size = limit.rlim_cur;
// Allocate unsafe stack for main thread
void *addr = unsafe_stack_alloc(size, guard);
unsafe_stack_setup(addr, size, guard);
// Setup the cleanup handler
pthread_key_create(&thread_cleanup_key, thread_cleanup_handler);
}
#if SANITIZER_CAN_USE_PREINIT_ARRAY
// On ELF platforms, run safestack initialization before any other constructors.
// On other platforms we use the constructor attribute to arrange to run our
// initialization early.
extern "C" {
__attribute__((section(".preinit_array"),
used)) void (*__safestack_preinit)(void) = __safestack_init;
}
#endif
extern "C"
__attribute__((visibility("default"))) void *__get_unsafe_stack_bottom() {
return unsafe_stack_start;
}
extern "C"
__attribute__((visibility("default"))) void *__get_unsafe_stack_top() {
return (char*)unsafe_stack_start + unsafe_stack_size;
}
extern "C"
__attribute__((visibility("default"))) void *__get_unsafe_stack_start() {
return unsafe_stack_start;
}
extern "C"
__attribute__((visibility("default"))) void *__get_unsafe_stack_ptr() {
return __safestack_unsafe_stack_ptr;
}
|
// Copyright (C) 2008, 2009, 2010, 2011 Tim Blechmann
//
// 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)
// Disclaimer: Not a Boost library.
#ifndef BOOST_LOCKFREE_STACK_HPP_INCLUDED
#define BOOST_LOCKFREE_STACK_HPP_INCLUDED
#include <boost/checked_delete.hpp>
#include <boost/noncopyable.hpp>
#include <boost/static_assert.hpp>
#include <boost/type_traits/has_trivial_assign.hpp>
#include <boost/type_traits/is_base_of.hpp>
#include <boost/lockfree/detail/atomic.hpp>
#include <boost/lockfree/detail/freelist.hpp>
#include <boost/lockfree/detail/tagged_ptr.hpp>
namespace boost {
namespace lockfree {
/** The stack class provides a multi-writer/multi-reader stack, pushing and poping is lockfree,
* construction/destruction has to be synchronized. It uses a freelist for memory management,
* freed nodes are pushed to the freelist and not returned to the os before the stack is destroyed.
*
* The memory management of the stack can be controlled via its freelist_t template argument. Two different
* freelists can be used. struct caching_freelist_t selects a caching freelist, which can allocate more nodes
* from the operating system, and struct static_freelist_t uses a fixed-sized freelist. With a fixed-sized
* freelist, the push operation may fail, while with a caching freelist, the push operation may block.
*
* \b Limitation: The class T is required to have a trivial assignment operator.
* */
template <typename T,
typename freelist_t = caching_freelist_t,
typename Alloc = std::allocator<T>
>
class stack:
boost::noncopyable
{
private:
BOOST_STATIC_ASSERT(boost::has_trivial_assign<T>::value);
#ifndef BOOST_DOXYGEN_INVOKED
struct node
{
typedef detail::tagged_ptr<node> tagged_node_ptr;
node(T const & v):
v(v)
{}
tagged_node_ptr next;
T v;
};
#endif
typedef detail::tagged_ptr<node> tagged_node_ptr;
typedef typename Alloc::template rebind<node>::other node_allocator;
typedef typename boost::mpl::if_<boost::is_same<freelist_t, caching_freelist_t>,
detail::freelist_stack<node, true, node_allocator>,
detail::freelist_stack<node, false, node_allocator>
>::type pool_t;
public:
/**
* \return true, if implementation is lock-free.
* */
bool is_lock_free (void) const
{
return tos.is_lock_free() && pool.is_lock_free();
}
//! Construct stack.
stack(void):
tos(tagged_node_ptr(NULL, 0))
{}
//! Construct stack, allocate n nodes for the freelist
explicit stack(std::size_t n):
tos(tagged_node_ptr(NULL, 0))
{
pool.reserve_unsafe(n);
}
//! Allocate n nodes for freelist
void reserve(std::size_t n)
{
pool.reserve(n);
}
/** \copydoc boost::lockfree::stack::reserve
*
* \note not thread-safe
*
* */
void reserve_unsafe(std::size_t n)
{
pool.reserve_unsafe(n);
}
/** Destroys stack, free all nodes from freelist.
*
* \note not thread-safe
*
* */
~stack(void)
{
if (!empty()) {
T dummy;
while(pop_unsafe(dummy))
;
}
}
/** Pushes object t to the fifo. May fail, if the freelist is not able to allocate a new fifo node.
*
* \returns true, if the push operation is successful.
*
* \note Thread-safe and non-blocking
* \warning \b Warning: May block if node needs to be allocated from the operating system
* */
bool push(T const & v)
{
node * newnode = pool.construct(v);
if (newnode == 0)
return false;
tagged_node_ptr old_tos = tos.load(detail::memory_order_relaxed);
for (;;) {
tagged_node_ptr new_tos (newnode, old_tos.get_tag());
newnode->next.set_ptr(old_tos.get_ptr());
if (tos.compare_exchange_weak(old_tos, new_tos))
return true;
}
}
/** Pushes object t to the fifo. May fail, if the freelist is not able to allocate a new fifo node.
*
* \returns true, if the push operation is successful.
*
* \note Not thread-safe
* \warning \b Warning: May block if node needs to be allocated from the operating system
* */
bool push_unsafe(T const & v)
{
node * newnode = pool.construct_unsafe(v);
if (newnode == 0)
return false;
tagged_node_ptr old_tos = tos.load(detail::memory_order_relaxed);
tagged_node_ptr new_tos (newnode, old_tos.get_tag());
newnode->next.set_ptr(old_tos.get_ptr());
tos.store(new_tos, memory_order_relaxed);
return true;
}
/** Pops object from stack.
*
* If pop operation is successful, object is written to memory location denoted by ret.
*
* \returns true, if the pop operation is successful, false if stack was empty.
*
* \note Thread-safe and non-blocking
*
* */
bool pop(T & ret)
{
tagged_node_ptr old_tos = tos.load(detail::memory_order_consume);
for (;;) {
if (!old_tos.get_ptr())
return false;
node * new_tos_ptr = old_tos->next.get_ptr();
tagged_node_ptr new_tos(new_tos_ptr, old_tos.get_tag() + 1);
if (tos.compare_exchange_weak(old_tos, new_tos)) {
ret = old_tos->v;
pool.destruct(old_tos.get_ptr());
return true;
}
}
}
/** Pops object from stack.
*
* If pop operation is successful, object is written to memory location denoted by ret.
*
* \returns true, if the pop operation is successful, false if stack was empty.
*
* \note Not thread-safe
*
* */
bool pop_unsafe(T & ret)
{
tagged_node_ptr old_tos = tos.load(detail::memory_order_relaxed);
if (!old_tos.get_ptr())
return false;
node * new_tos_ptr = old_tos->next.get_ptr();
tagged_node_ptr new_tos(new_tos_ptr, old_tos.get_tag() + 1);
tos.store(new_tos, memory_order_relaxed);
ret = old_tos->v;
pool.destruct_unsafe(old_tos.get_ptr());
return true;
}
/**
* \return true, if stack is empty.
*
* \warning The state of the stack can be modified by other threads
*
* \note While this function is thread-safe, it only guarantees that at some point during the execution of the function the
* stack has been empty
* */
bool empty(void) const
{
return tos.load().get_ptr() == NULL;
}
private:
#ifndef BOOST_DOXYGEN_INVOKED
detail::atomic<tagged_node_ptr> tos;
static const int padding_size = BOOST_LOCKFREE_CACHELINE_BYTES - sizeof(tagged_node_ptr);
char padding[padding_size];
pool_t pool;
#endif
};
} /* namespace lockfree */
} /* namespace boost */
#endif /* BOOST_LOCKFREE_STACK_HPP_INCLUDED */
|
/*
* OpenSplice DDS
*
* This software and documentation are Copyright 2006 to TO_YEAR PrismTech
* Limited, its affiliated companies and licensors. 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.
*
*/
#ifndef OSPL_DDS_TOPIC_TTOPICDESCRIPTION_HPP_
#define OSPL_DDS_TOPIC_TTOPICDESCRIPTION_HPP_
/**
* @file
*/
/*
* OMG PSM class declaration
*/
#include <spec/dds/topic/TTopicDescription.hpp>
// Implementation
namespace dds
{
namespace topic
{
template <typename T, template <typename Q> class DELEGATE>
TopicDescription<T, DELEGATE>::~TopicDescription() { }
template <typename T, template <typename Q> class DELEGATE>
const std::string& TopicDescription<T, DELEGATE>::name() const
{
return this->delegate()->name();
}
template <typename T, template <typename Q> class DELEGATE>
const std::string& TopicDescription<T, DELEGATE>::type_name() const
{
return this->delegate()->type_name();
}
template <typename T, template <typename Q> class DELEGATE>
const dds::domain::DomainParticipant& TopicDescription<T, DELEGATE>::domain_participant() const
{
return this->delegate()->domain_participant();
}
template <typename T, template <typename Q> class DELEGATE>
TopicDescription<T, DELEGATE>::TopicDescription(const dds::domain::DomainParticipant& dp,
const std::string& topic_name,
const std::string& type_name)
: ::dds::core::TEntity< DELEGATE<T> >(new DELEGATE<T>(dp, topic_name, type_name))
{ }
}
}
// End of implementation
#endif /* OSPL_DDS_TOPIC_TTOPICDESCRIPTION_HPP_ */
|
#include <bits/stdc++.h>
#define ll long long int
#define ld long double
using namespace std;
void swap(ll *a,ll *b)
{
ll temp=*a;
*a=*b;
*b=temp;
}
void recur_sort(ll *arr,ll n)
{
//small calculation
if(n==2)
{
if(arr[0]>arr[1])
swap(arr,arr+1);
return;
}
return recur_sort(arr+1,n-1);
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
ll t;
cin>>t;
ll arr[t];
for(ll i{0};i<t;i++)
cin>>arr[i];
ll size=sizeof(arr)/sizeof(ll);
recur_sort(arr,size);
for(ll i:arr)
cout<<i<<" ";
cout<<endl;
return 0;
}
|
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/views/toolbar/back_button.h"
#include "ui/gfx/geometry/insets.h"
#include "ui/views/animation/ink_drop.h"
#include "ui/views/controls/button/label_button_border.h"
#include "ui/views/painter.h"
BackButton::BackButton(Profile* profile,
views::ButtonListener* listener,
ui::MenuModel* model)
: ToolbarButton(profile, listener, model), margin_leading_(0) {}
BackButton::~BackButton() {}
void BackButton::SetLeadingMargin(int margin) {
margin_leading_ = margin;
UpdateThemedBorder();
const int inset = LabelButton::kFocusRectInset;
const bool is_rtl = base::i18n::IsRTL();
const gfx::Insets insets(inset, inset + (is_rtl ? 0 : margin),
inset, inset + (is_rtl ? margin : 0));
SetFocusPainter(views::Painter::CreateDashedFocusPainterWithInsets(insets));
InvalidateLayout();
}
const char* BackButton::GetClassName() const {
return "BackButton";
}
std::unique_ptr<views::LabelButtonBorder> BackButton::CreateDefaultBorder()
const {
std::unique_ptr<views::LabelButtonBorder> border =
ToolbarButton::CreateDefaultBorder();
// Adjust border insets to follow the margin change,
// which will be reflected in where the border is painted
// through GetThemePaintRect().
const gfx::Insets insets(border->GetInsets());
border->set_insets(gfx::Insets(insets.top(), insets.left() + margin_leading_,
insets.bottom(), insets.right()));
return border;
}
gfx::Rect BackButton::GetThemePaintRect() const {
gfx::Rect rect(LabelButton::GetThemePaintRect());
const bool is_rtl = base::i18n::IsRTL();
rect.Inset(is_rtl ? 0 : margin_leading_, 0, is_rtl ? margin_leading_ : 0, 0);
return rect;
}
|
#include "CompositorGL.h"
#include "TextureGL.h"
#include "OVR_CAPI.h"
#include "Common.h"
#include <GL/glew.h>
#include <Windows.h>
GLboolean CompositorGL::glewInitialized = GL_FALSE;
void CompositorGL::DebugCallback(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar* message, const void* userParam)
{
OutputDebugStringA(message);
OutputDebugStringA("\n");
}
CompositorGL* CompositorGL::Create()
{
if (!glewInitialized)
{
GLenum nGlewError = glewInit();
if (nGlewError != GLEW_OK)
return nullptr;
#ifdef DEBUG
glEnable(GL_DEBUG_OUTPUT);
glDebugMessageCallback((GLDEBUGPROC)DebugCallback, nullptr);
#endif // DEBUG
glGetError(); // to clear the error caused deep in GLEW
glewInitialized = GL_TRUE;
}
return new CompositorGL();
}
CompositorGL::CompositorGL()
{
// TODO: Get the mirror views from OpenVR once they fix the OpenGL implementation.
}
CompositorGL::~CompositorGL()
{
}
ovrResult CompositorGL::CreateTextureSwapChain(const ovrTextureSwapChainDesc* desc, ovrTextureSwapChain* out_TextureSwapChain)
{
ovrTextureSwapChain swapChain = new ovrTextureSwapChainData(vr::API_OpenGL, *desc);
for (int i = 0; i < swapChain->Length; i++)
{
TextureGL* texture = new TextureGL();
bool success = texture->Create(desc->Width, desc->Height, desc->MipLevels, desc->ArraySize, desc->Format,
desc->MiscFlags, desc->BindFlags);
if (!success)
return ovrError_RuntimeException;
swapChain->Textures[i].reset(texture);
}
*out_TextureSwapChain = swapChain;
return ovrSuccess;
}
ovrResult CompositorGL::CreateMirrorTexture(const ovrMirrorTextureDesc* desc, ovrMirrorTexture* out_MirrorTexture)
{
// There can only be one mirror texture at a time
if (m_MirrorTexture)
return ovrError_RuntimeException;
ovrMirrorTexture mirrorTexture = new ovrMirrorTextureData(vr::API_OpenGL, *desc);
TextureGL* texture = new TextureGL();
bool success = texture->Create(desc->Width, desc->Height, 1, 1, desc->Format,
desc->MiscFlags, 0);
if (!success)
return ovrError_RuntimeException;
mirrorTexture->Texture.reset(texture);
m_MirrorTexture = mirrorTexture;
*out_MirrorTexture = mirrorTexture;
return ovrSuccess;
}
void CompositorGL::RenderMirrorTexture(ovrMirrorTexture mirrorTexture, ovrTextureSwapChain swapChain[ovrEye_Count])
{
uint32_t width, height;
vr::VRSystem()->GetRecommendedRenderTargetSize(&width, &height);
TextureGL* texture = (TextureGL*)mirrorTexture->Texture.get();
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, texture->Framebuffer);
for (int i = 0; i < ovrEye_Count; i++)
{
// Bind the buffer to copy from the compositor to the mirror texture
glBindFramebuffer(GL_READ_FRAMEBUFFER, ((TextureGL*)swapChain[i]->Submitted)->Framebuffer);
GLint offset = (mirrorTexture->Desc.Width / 2) * i;
glBlitFramebuffer(0, 0, width, height, offset, mirrorTexture->Desc.Height, offset + mirrorTexture->Desc.Width / 2, 0, GL_COLOR_BUFFER_BIT, GL_LINEAR);
}
}
void CompositorGL::RenderTextureSwapChain(vr::EVREye eye, ovrTextureSwapChain swapChain, ovrTextureSwapChain sceneChain, ovrRecti viewport, vr::VRTextureBounds_t bounds, vr::HmdVector4_t quad)
{
// TODO: Support blending multiple scene layers
}
|
/*
Copyright (c) 2013-2018, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef TORRENT_RESOLVER_HPP_INCLUDE
#define TORRENT_RESOLVER_HPP_INCLUDE
#include "libtorrent/aux_/disable_warnings_push.hpp"
#include <boost/asio/ip/tcp.hpp>
#include <boost/function.hpp>
#include <boost/unordered_map.hpp>
#include <vector>
#include "libtorrent/aux_/disable_warnings_pop.hpp"
#include "libtorrent/error_code.hpp"
#include "libtorrent/io_service.hpp"
#include "libtorrent/socket.hpp"
#include "libtorrent/resolver_interface.hpp"
#include "libtorrent/address.hpp"
#include "libtorrent/time.hpp"
namespace libtorrent
{
struct TORRENT_EXTRA_EXPORT resolver TORRENT_FINAL : resolver_interface
{
resolver(io_service& ios);
virtual void async_resolve(std::string const& host, int flags
, callback_t const& h) TORRENT_OVERRIDE;
virtual void abort() TORRENT_OVERRIDE;
private:
void on_lookup(error_code const& ec, tcp::resolver::iterator i
, resolver_interface::callback_t h, std::string hostname);
struct dns_cache_entry
{
time_point last_seen;
std::vector<address> addresses;
};
typedef boost::unordered_map<std::string, dns_cache_entry> cache_t;
cache_t m_cache;
io_service& m_ios;
// all lookups in this resolver are aborted on shutdown.
tcp::resolver m_resolver;
// lookups in this resolver are not aborted on shutdown
tcp::resolver m_critical_resolver;
// max number of cached entries
int m_max_size;
// timeout of cache entries
time_duration m_timeout;
};
}
#endif
|
#include<bits/stdc++.h>
using namespace std;
int main(){
int t;
cin>>t;
int n;
while(t--){
cin>>n;
int even=0;
int odd=0;
while(n!=0){
int r=n%10;
if(r%2==0){
even=even+r;}
else{
odd=odd+r;}
n=n/10;
}
if(even%4==0 || odd%3==0){
cout<<"Yes"<<endl;
}
else{
cout<<"No"<<endl;
}
}
return 0;
}
|
// Generated by Haxe 4.1.5
#include <hxcpp.h>
#ifndef INCLUDED___ASSET__flixel_flixel_ui_img_check_mark_png
#include <__ASSET__flixel_flixel_ui_img_check_mark_png.h>
#endif
#ifndef INCLUDED_haxe_Resource
#include <haxe/Resource.h>
#endif
#ifndef INCLUDED_haxe_io_Bytes
#include <haxe/io/Bytes.h>
#endif
#ifndef INCLUDED_lime_graphics_Image
#include <lime/graphics/Image.h>
#endif
#ifndef INCLUDED_lime_graphics_ImageBuffer
#include <lime/graphics/ImageBuffer.h>
#endif
#ifndef INCLUDED_lime_graphics_ImageType
#include <lime/graphics/ImageType.h>
#endif
HX_DEFINE_STACK_FRAME(_hx_pos_0beb5da3a19aed74_346_new,"__ASSET__flixel_flixel_ui_img_check_mark_png","new",0xfe81e957,"__ASSET__flixel_flixel_ui_img_check_mark_png.new","lime/_internal/macros/AssetsMacro.hx",346,0xc651f030)
HX_LOCAL_STACK_FRAME(_hx_pos_ef91f2e0d62316f1_680_boot,"__ASSET__flixel_flixel_ui_img_check_mark_png","boot",0xab43435b,"__ASSET__flixel_flixel_ui_img_check_mark_png.boot","ManifestResources.hx",680,0xf77aa668)
void __ASSET__flixel_flixel_ui_img_check_mark_png_obj::__construct( ::lime::graphics::ImageBuffer buffer, ::Dynamic offsetX, ::Dynamic offsetY, ::Dynamic width, ::Dynamic height, ::Dynamic color, ::lime::graphics::ImageType type){
HX_STACKFRAME(&_hx_pos_0beb5da3a19aed74_346_new)
HXLINE( 375) super::__construct(null(),null(),null(),null(),null(),null(),null());
HXLINE( 377) this->_hx___fromBytes(::haxe::Resource_obj::getBytes(::__ASSET__flixel_flixel_ui_img_check_mark_png_obj::resourceName),null());
}
Dynamic __ASSET__flixel_flixel_ui_img_check_mark_png_obj::__CreateEmpty() { return new __ASSET__flixel_flixel_ui_img_check_mark_png_obj; }
void *__ASSET__flixel_flixel_ui_img_check_mark_png_obj::_hx_vtable = 0;
Dynamic __ASSET__flixel_flixel_ui_img_check_mark_png_obj::__Create(::hx::DynamicArray inArgs)
{
::hx::ObjectPtr< __ASSET__flixel_flixel_ui_img_check_mark_png_obj > _hx_result = new __ASSET__flixel_flixel_ui_img_check_mark_png_obj();
_hx_result->__construct(inArgs[0],inArgs[1],inArgs[2],inArgs[3],inArgs[4],inArgs[5],inArgs[6]);
return _hx_result;
}
bool __ASSET__flixel_flixel_ui_img_check_mark_png_obj::_hx_isInstanceOf(int inClassId) {
if (inClassId<=(int)0x33f052f7) {
return inClassId==(int)0x00000001 || inClassId==(int)0x33f052f7;
} else {
return inClassId==(int)0x764a10fd;
}
}
::String __ASSET__flixel_flixel_ui_img_check_mark_png_obj::resourceName;
::hx::ObjectPtr< __ASSET__flixel_flixel_ui_img_check_mark_png_obj > __ASSET__flixel_flixel_ui_img_check_mark_png_obj::__new( ::lime::graphics::ImageBuffer buffer, ::Dynamic offsetX, ::Dynamic offsetY, ::Dynamic width, ::Dynamic height, ::Dynamic color, ::lime::graphics::ImageType type) {
::hx::ObjectPtr< __ASSET__flixel_flixel_ui_img_check_mark_png_obj > __this = new __ASSET__flixel_flixel_ui_img_check_mark_png_obj();
__this->__construct(buffer,offsetX,offsetY,width,height,color,type);
return __this;
}
::hx::ObjectPtr< __ASSET__flixel_flixel_ui_img_check_mark_png_obj > __ASSET__flixel_flixel_ui_img_check_mark_png_obj::__alloc(::hx::Ctx *_hx_ctx, ::lime::graphics::ImageBuffer buffer, ::Dynamic offsetX, ::Dynamic offsetY, ::Dynamic width, ::Dynamic height, ::Dynamic color, ::lime::graphics::ImageType type) {
__ASSET__flixel_flixel_ui_img_check_mark_png_obj *__this = (__ASSET__flixel_flixel_ui_img_check_mark_png_obj*)(::hx::Ctx::alloc(_hx_ctx, sizeof(__ASSET__flixel_flixel_ui_img_check_mark_png_obj), true, "__ASSET__flixel_flixel_ui_img_check_mark_png"));
*(void **)__this = __ASSET__flixel_flixel_ui_img_check_mark_png_obj::_hx_vtable;
__this->__construct(buffer,offsetX,offsetY,width,height,color,type);
return __this;
}
__ASSET__flixel_flixel_ui_img_check_mark_png_obj::__ASSET__flixel_flixel_ui_img_check_mark_png_obj()
{
}
bool __ASSET__flixel_flixel_ui_img_check_mark_png_obj::__GetStatic(const ::String &inName, Dynamic &outValue, ::hx::PropertyAccess inCallProp)
{
switch(inName.length) {
case 12:
if (HX_FIELD_EQ(inName,"resourceName") ) { outValue = ( resourceName ); return true; }
}
return false;
}
bool __ASSET__flixel_flixel_ui_img_check_mark_png_obj::__SetStatic(const ::String &inName,Dynamic &ioValue,::hx::PropertyAccess inCallProp)
{
switch(inName.length) {
case 12:
if (HX_FIELD_EQ(inName,"resourceName") ) { resourceName=ioValue.Cast< ::String >(); return true; }
}
return false;
}
#ifdef HXCPP_SCRIPTABLE
static ::hx::StorageInfo *__ASSET__flixel_flixel_ui_img_check_mark_png_obj_sMemberStorageInfo = 0;
static ::hx::StaticInfo __ASSET__flixel_flixel_ui_img_check_mark_png_obj_sStaticStorageInfo[] = {
{::hx::fsString,(void *) &__ASSET__flixel_flixel_ui_img_check_mark_png_obj::resourceName,HX_("resourceName",39,7a,62,90)},
{ ::hx::fsUnknown, 0, null()}
};
#endif
static void __ASSET__flixel_flixel_ui_img_check_mark_png_obj_sMarkStatics(HX_MARK_PARAMS) {
HX_MARK_MEMBER_NAME(__ASSET__flixel_flixel_ui_img_check_mark_png_obj::resourceName,"resourceName");
};
#ifdef HXCPP_VISIT_ALLOCS
static void __ASSET__flixel_flixel_ui_img_check_mark_png_obj_sVisitStatics(HX_VISIT_PARAMS) {
HX_VISIT_MEMBER_NAME(__ASSET__flixel_flixel_ui_img_check_mark_png_obj::resourceName,"resourceName");
};
#endif
::hx::Class __ASSET__flixel_flixel_ui_img_check_mark_png_obj::__mClass;
static ::String __ASSET__flixel_flixel_ui_img_check_mark_png_obj_sStaticFields[] = {
HX_("resourceName",39,7a,62,90),
::String(null())
};
void __ASSET__flixel_flixel_ui_img_check_mark_png_obj::__register()
{
__ASSET__flixel_flixel_ui_img_check_mark_png_obj _hx_dummy;
__ASSET__flixel_flixel_ui_img_check_mark_png_obj::_hx_vtable = *(void **)&_hx_dummy;
::hx::Static(__mClass) = new ::hx::Class_obj();
__mClass->mName = HX_("__ASSET__flixel_flixel_ui_img_check_mark_png",e5,f1,36,20);
__mClass->mSuper = &super::__SGetClass();
__mClass->mConstructEmpty = &__CreateEmpty;
__mClass->mConstructArgs = &__Create;
__mClass->mGetStaticField = &__ASSET__flixel_flixel_ui_img_check_mark_png_obj::__GetStatic;
__mClass->mSetStaticField = &__ASSET__flixel_flixel_ui_img_check_mark_png_obj::__SetStatic;
__mClass->mMarkFunc = __ASSET__flixel_flixel_ui_img_check_mark_png_obj_sMarkStatics;
__mClass->mStatics = ::hx::Class_obj::dupFunctions(__ASSET__flixel_flixel_ui_img_check_mark_png_obj_sStaticFields);
__mClass->mMembers = ::hx::Class_obj::dupFunctions(0 /* sMemberFields */);
__mClass->mCanCast = ::hx::TCanCast< __ASSET__flixel_flixel_ui_img_check_mark_png_obj >;
#ifdef HXCPP_VISIT_ALLOCS
__mClass->mVisitFunc = __ASSET__flixel_flixel_ui_img_check_mark_png_obj_sVisitStatics;
#endif
#ifdef HXCPP_SCRIPTABLE
__mClass->mMemberStorageInfo = __ASSET__flixel_flixel_ui_img_check_mark_png_obj_sMemberStorageInfo;
#endif
#ifdef HXCPP_SCRIPTABLE
__mClass->mStaticStorageInfo = __ASSET__flixel_flixel_ui_img_check_mark_png_obj_sStaticStorageInfo;
#endif
::hx::_hx_RegisterClass(__mClass->mName, __mClass);
}
void __ASSET__flixel_flixel_ui_img_check_mark_png_obj::__boot()
{
{
HX_STACKFRAME(&_hx_pos_ef91f2e0d62316f1_680_boot)
HXDLIN( 680) resourceName = HX_("__ASSET__:image___ASSET__flixel_flixel_ui_img_check_mark_png",73,3f,b4,e4);
}
}
|
#include <iostream>
using namespace std;
class Complex
{
private:
int real;
int imag;
public:
Complex(): real(0), imag(0) { }
void readData()
{
cout << "Enter real and imaginary number respectively:"<<endl;
cin >> real >> imag;
}
void addComplexNumbers(Complex comp1, Complex comp2)
{
// real represents the real data of object c3 because this function is called using code c3.add(c1,c2);
real=comp1.real+comp2.real;
// imag represents the imag data of object c3 because this function is called using code c3.add(c1,c2);
imag=comp1.imag+comp2.imag;
}
void displaySum()
{
cout << "Sum = " << real<< "+" << imag << "i";
}
};
int main()
{
Complex c1,c2,c3;
c1.readData();
c2.readData();
c3.addComplexNumbers(c1, c2);
c3.displaySum();
return 0;
}
|
#include <iostream>
#include <vector>
#include <string>
#include "../../include/Commands.hpp"
#include "../../include/DataTypes.hpp"
#include "../../include/LangInterpreter/LanguageInterpreter.hpp"
int Interpreter::EvalCondition( const std::vector< std::string > & lineparts, int line )
{
// if a CONDITION b :
std::string replval1 = GetReplacementValue( lineparts[ 1 ], line + 1 );
std::string replval2 = GetReplacementValue( lineparts[ 3 ], line + 1 );
if( replval1.empty() || replval2.empty() )
return -1;
// if a CONDITION b :
auto dt1 = GetType( replval1 );
auto dt2 = GetType( replval2 );
if( dt1 != dt2 ) {
std::cerr << "Error in line: " << line + 1
<< "\n\tTypes of data in the condition do not match!" << std::endl;
return -1;
}
std::string cond = lineparts[ 2 ];
if( dt1 == FLT ) {
float val1, val2;
val1 = std::stof( replval1 );
val2 = std::stof( replval2 );
if( cond == "<" )
return val1 < val2 ? OK : ERR;
else if( cond == "<=" )
return val1 <= val2 ? OK : ERR;
else if( cond == ">" )
return val1 > val2 ? OK : ERR;
else if( cond == ">=" )
return val1 >= val2 ? OK : ERR;
else if( cond == "!=" )
return val1 != val2 ? OK : ERR;
else if( cond == "==" )
return val1 == val2 ? OK : ERR;
}
if( dt1 == INT ) {
int val1, val2;
val1 = std::stoi( replval1 );
val2 = std::stoi( replval2 );
if( cond == "<" )
return val1 < val2 ? OK : ERR;
else if( cond == "<=" )
return val1 <= val2 ? OK : ERR;
else if( cond == ">" )
return val1 > val2 ? OK : ERR;
else if( cond == ">=" )
return val1 >= val2 ? OK : ERR;
else if( cond == "!=" )
return val1 != val2 ? OK : ERR;
else if( cond == "==" )
return val1 == val2 ? OK : ERR;
}
if( dt1 == STR ) {
std::string & val1 = replval1;
std::string & val2 = replval2;
if( cond == "<" )
return val1 < val2 ? OK : ERR;
else if( cond == "<=" )
return val1 <= val2 ? OK : ERR;
else if( cond == ">" )
return val1 > val2 ? OK : ERR;
else if( cond == ">=" )
return val1 >= val2 ? OK : ERR;
else if( cond == "!=" )
return val1 != val2 ? OK : ERR;
else if( cond == "==" )
return val1 == val2 ? OK : ERR;
}
return -1;
}
|
#include "panelworldmap.h"
#include "ui_panelworldmap.h"
#include <world/core.h>
#include <world/terrain.h>
#include "qtworld.h"
using namespace world;
PanelWorldMap::PanelWorldMap(QWidget *parent)
: GeneratePanel(parent), ui(new Ui::PanelWorldMap) {
ui->setupUi(this);
}
PanelWorldMap::~PanelWorldMap() { delete ui; }
void PanelWorldMap::generate() {
double biomeDensity = ui->biomeDensity->value();
int limitBrightness = ui->limitBrigntness->value();
CustomWorldRMModifier generator(biomeDensity, limitBrightness);
generator.setMapResolution(513);
auto &result = generator.obtainMap(0, 0);
Image img = result.first.createImage();
emit imageChanged(QtWorld::getQImage(img));
}
|
#include "Renderer.h"
#include "Camera.h"
#include "Scene.h"
namespace phen {
Renderer::Renderer()
{
}
Renderer::~Renderer()
{
glDeleteFramebuffers(1, &FramebufferName);
glDeleteTextures(1, &renderedTexture);
glDeleteRenderbuffers(1, &depthrenderbuffer);
glDeleteBuffers(1, &quad_vertexbuffer);
glDeleteVertexArrays(1, &quad_VertexArrayID);
}
int Renderer::init(GLuint width_in, GLuint height_in, GLfloat gamma_in)
{
screen_size.set(width_in, height_in);
G_Buffer.init(screen_size.x, screen_size.y); //Init our GBuffer
setGamma(gamma_in);
FramebufferName = 0;
glGenFramebuffers(1, &FramebufferName);
glBindFramebuffer(GL_FRAMEBUFFER, FramebufferName);
glGenTextures(1, &renderedTexture);
glBindTexture(GL_TEXTURE_2D, renderedTexture);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB32F, screen_size.x, screen_size.y, 0, GL_RGB, GL_FLOAT, 0);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glGenRenderbuffers(1, &depthrenderbuffer);
glBindRenderbuffer(GL_RENDERBUFFER, depthrenderbuffer);
glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, screen_size.x, screen_size.y);
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, depthrenderbuffer);
glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, renderedTexture, 0);
DrawBuffers[0] = GL_COLOR_ATTACHMENT0;
glDrawBuffers(1, DrawBuffers);
if(glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
return false;
return true;
}
int Renderer::initQuad()
{
static const GLfloat g_quad_vertex_buffer_data[] = {
1.0f, -1.0f, 0.0f, 1.0f, 0.0f,
-1.0f, -1.0f, 0.0f, 0.0f, 0.0f,
-1.0f, 1.0f, 0.0f, 0.0f, 1.0f,
1.0f, -1.0f, 0.0f, 1.0f, 0.0f,
-1.0f, 1.0f, 0.0f, 0.0f, 1.0f,
1.0f, 1.0f, 0.0f, 1.0f, 1.0f
};
glGenVertexArrays(1, &quad_VertexArrayID);
glBindVertexArray(quad_VertexArrayID);
glGenBuffers(1, &quad_vertexbuffer);
glBindBuffer(GL_ARRAY_BUFFER, quad_vertexbuffer);
glBufferData(GL_ARRAY_BUFFER, sizeof(g_quad_vertex_buffer_data), g_quad_vertex_buffer_data, GL_STATIC_DRAW);
return 0;
}
int Renderer::initLighting(Shader* shader_in)
{
light_shader = shader_in;
light_position_textureID = glGetUniformLocation(light_shader->getShader(), "position_viewspace");
light_diffuse_textureID = glGetUniformLocation(light_shader->getShader(), "diffuse");
light_normal_textureID = glGetUniformLocation(light_shader->getShader(), "normal_viewspace");
light_screen_sizeID = glGetUniformLocation(light_shader->getShader(), "screenSize");
light_diffuse_colorID = glGetUniformLocation(light_shader->getShader(), "DiffuseColor");
light_ambient_colorID = glGetUniformLocation(light_shader->getShader(), "AmbientColor");
light_specular_colorID = glGetUniformLocation(light_shader->getShader(), "SpecularColor");
light_powerID = glGetUniformLocation(light_shader->getShader(), "LightPower");
light_positionID = glGetUniformLocation(light_shader->getShader(), "LightPosition");
camera_positionID = glGetUniformLocation(light_shader->getShader(), "CameraPosition");
return 0;
}
int Renderer::initPostProcess(Shader* shader_in)
{
post_shader = shader_in;
texID = glGetUniformLocation(post_shader->getShader(), "renderedTexture");
gammaID = glGetUniformLocation(post_shader->getShader(), "gamma_divided");
timeID = glGetUniformLocation(post_shader->getShader(), "time");
return 0;
}
int Renderer::setGamma(GLfloat gamma_in)
{
gamma_divided = 1/gamma_in;
return 0;
}
int Renderer::geometryPass(Scene* scene)
{
G_Buffer.bindForWriting();
glDepthMask(GL_TRUE); //Only the geometry pass updates the depth buffer
glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
glEnable(GL_DEPTH_TEST); //Return to normal
glDisable(GL_BLEND); //Ditto
scene->draw(this);
glDepthMask(GL_FALSE); //Light pass does not write to depth buffer
glDisable(GL_DEPTH_TEST); //Don't want to test for depth for lighting either
return 0;
}
int Renderer::beginLightingPass()
{
glEnable(GL_BLEND);
glBlendEquation(GL_FUNC_ADD);
glBlendFunc(GL_ONE, GL_ONE);
G_Buffer.bindForReading();
glClear(GL_COLOR_BUFFER_BIT);
return 0;
}
int Renderer::lightingPass(Camera* camera, Scene* scene)
{
//*
G_Buffer.bindForReading();
glBindFramebuffer(GL_DRAW_BUFFER, FramebufferName);
glUseProgram(light_shader->getShader());
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, G_Buffer.textures[GBuffer::GBUFFER_TEXTURE_TYPE_POSITION]);
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, G_Buffer.textures[GBuffer::GBUFFER_TEXTURE_TYPE_DIFFUSE]);
glActiveTexture(GL_TEXTURE2);
glBindTexture(GL_TEXTURE_2D, G_Buffer.textures[GBuffer::GBUFFER_TEXTURE_TYPE_NORMAL]);
for (GLuint i = 0; i < scene->numLights; i++)
{
glUniform1i(light_position_textureID, GBuffer::GBUFFER_TEXTURE_TYPE_POSITION);
glUniform1i(light_diffuse_textureID, GBuffer::GBUFFER_TEXTURE_TYPE_DIFFUSE);
glUniform1i(light_normal_textureID, GBuffer::GBUFFER_TEXTURE_TYPE_NORMAL);
glUniform2f(light_screen_sizeID, screen_size.x, screen_size.y);
Vector4f light_position = Vmatrix * scene->LightArray.getArrayMember(i)->getGlobalPositionv4f(); //Get the worldspace position of the light and multiply by the view matrix to get it in viewspace (shader uses viewspace)
Color3f light_diffuse = scene->LightArray.getArrayMember(i)->getDiffuse();
Color3f light_ambient = scene->LightArray.getArrayMember(i)->getAmbient();
Color3f light_specular = scene->LightArray.getArrayMember(i)->getSpecular();
camera_position = camera->getGlobalPosition();
glUniform3f(light_diffuse_colorID, light_diffuse.r, light_diffuse.g, light_diffuse.b);
glUniform3f(light_ambient_colorID, light_ambient.r, light_ambient.g, light_ambient.b);
glUniform3f(light_specular_colorID, light_specular.r, light_specular.g, light_specular.b);
glUniform1f(light_powerID, scene->LightArray.getArrayMember(i)->getPower());
glUniform3f(light_positionID, light_position.x, light_position.y, light_position.z);
glUniform3f(camera_positionID, camera_position.x, camera_position.y, camera_position.z);
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
glBindBuffer(GL_ARRAY_BUFFER, quad_vertexbuffer);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(GLfloat)*5, (void*)0);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(GLfloat)*5, (void*)12);
glDrawArrays(GL_TRIANGLES, 0, 6);
glDisableVertexAttribArray(0);
glDisableVertexAttribArray(1);
}
glBindTexture(GL_TEXTURE_2D, 0);
return 0;
}
int Renderer::preparePostProcess()
{
glBindFramebuffer(GL_FRAMEBUFFER, FramebufferName); //Bind the framebuffer that is written to for post-processing
glViewport(0, 0, screen_size.x, screen_size.y);
glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
return 0;
}
int Renderer::postProcess()
{
glBindFramebuffer(GL_FRAMEBUFFER, 0); //Render the post-processing to screen
glViewport(0, 0, screen_size.x, screen_size.y);
glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glUseProgram(post_shader->getShader());
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, renderedTexture);
glUniform1i(texID, 0);
glUniform1f(gammaID, gamma_divided);
glUniform1f(timeID, float(SDL_GetTicks()/100));
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
glBindBuffer(GL_ARRAY_BUFFER, quad_vertexbuffer);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(GLfloat)*5, (void*)0);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(GLfloat)*5, (void*)12);
glDrawArrays(GL_TRIANGLES, 0, 6);
glDisableVertexAttribArray(0);
glDisableVertexAttribArray(1);
glBindTexture(GL_TEXTURE_2D, 0);
return 0;
}
int Renderer::render(Camera* camera, Scene* scene)
{
Vmatrix = camera->getViewMatrix();
VPmatrix = camera->getProjectionMatrix() * Vmatrix;
//Here is the defferd rendering part
geometryPass(scene);
//Bind the framebuffer that the lighting pass will render into, used for post-processing
preparePostProcess();
//Now do the lighting
beginLightingPass();
lightingPass(camera, scene);
//End deffered rendering
postProcess(); //Do post-process
return 0;
}
} //End namespace
|
#include "SDL2_renderer.h"
#include "glm/glm.hpp"
#include <iostream>
int SDL2_renderer::Init(int width, int height)
{
if (SDL_Init(SDL_INIT_VIDEO) != 0)
{
fprintf(stderr, "Failed to initialize SDL2.0: %s\n", SDL_GetError());
return EXIT_FAILURE;
}
_window = SDL_CreateWindow("Game", 400, 200, width, height, SDL_WINDOW_SHOWN);
if (_window == nullptr)
{
fprintf(stderr, "Failed to create SDL2.0 window: %s\n", SDL_GetError());
return EXIT_FAILURE;
}
_renderer = SDL_CreateRenderer(_window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
if (_renderer == nullptr)
{
SDL_DestroyWindow(_window);
fprintf(stderr, "Failed to create SDL2.0 renderer: %s\n", SDL_GetError());
return EXIT_FAILURE;
}
_viewport = glm::vec4(0.0f, 0.0f, width, height);
return 0;
}
void SDL2_renderer::Clean()
{
SDL_DestroyRenderer(_renderer);
SDL_DestroyWindow(_window);
}
void SDL2_renderer::Render(const idop::CameraData& cameraData)
{
SDL_SetRenderDrawColor(_renderer, 200, 200, 200, 255);
SDL_RenderClear(_renderer);
SDL_SetRenderDrawColor(_renderer, 0, 0, 0, 255);
glm::vec3* projectedPoints = nullptr;
int* triangles;
for (int i = 0; i < _renderingData.size(); ++i)
{
for (int j = 0; j < _renderingData[i]->_modelViewData.size(); ++j)
{
if (!_renderingData[i]->_modelViewData[j]->_active)
continue;
delete[](projectedPoints);
projectedPoints = new glm::vec3[_renderingData[i]->_mesh->_verticesLength];
for (int k = 0; k < _renderingData[i]->_mesh->_verticesLength; ++k)
{
projectedPoints[k] = glm::project(_renderingData[i]->_mesh->_vertices[k],
cameraData._viewMatrix * _renderingData[i]->_modelViewData[j]->_modelMatrix,
cameraData._projectionMatrix,
_viewport);
}
triangles = _renderingData[i]->_mesh->_triangles;
for (int k = 0; k < _renderingData[i]->_mesh->_trianglesLength; k += 3)
{
SDL_RenderDrawLine(_renderer,
projectedPoints[triangles[k]].x,
projectedPoints[triangles[k]].y,
projectedPoints[triangles[k + 1]].x,
projectedPoints[triangles[k + 1]].y);
SDL_RenderDrawLine(_renderer,
projectedPoints[triangles[k + 1]].x,
projectedPoints[triangles[k + 1]].y,
projectedPoints[triangles[k + 2]].x,
projectedPoints[triangles[k + 2]].y);
SDL_RenderDrawLine(_renderer,
projectedPoints[triangles[k + 2]].x,
projectedPoints[triangles[k + 2]].y,
projectedPoints[triangles[k]].x,
projectedPoints[triangles[k]].y);
}
}
}
SDL_RenderPresent(_renderer);
}
idop::RenderingData* SDL2_renderer::AddRenderingData(idop::MeshData* mesh, idop::Texture texture)
{
_renderingData.push_back(new idop::RenderingData(mesh, texture));
return _renderingData[_renderingData.size() - 1];
}
|
/**
* Copyright (c) Facebook, Inc. and its affiliates.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
/*******************************************************
* Copyright (c) 2017, ArrayFire
* All rights reserved.
*
* This file is distributed under 3-clause BSD license.
* The complete license agreement can be obtained at:
* http://arrayfire.com/licenses/BSD-3-Clause
********************************************************/
#include "flashlight/optim/AdagradOptimizer.h"
#include <cmath>
namespace fl {
AdagradOptimizer::AdagradOptimizer(
const std::vector<Variable>& parameters,
float learningRate /* = 1.0 */,
float epsilon /* = 1e-8 */,
float weightDecay /* = 0 */)
: FirstOrderOptimizer(parameters, learningRate),
eps_(epsilon),
wd_(weightDecay) {
variance_.reserve(parameters.size());
for (const auto& param : parameters_) {
variance_.push_back(af::constant(0, param.dims(), param.type()));
variance_.back().eval();
}
}
void AdagradOptimizer::step() {
for (size_t i = 0; i < parameters_.size(); i++) {
if (!parameters_[i].isGradAvailable()) {
continue;
}
const af::array& grad = parameters_[i].grad().array();
af::array& data = parameters_[i].array();
af::array& variance = variance_[i];
if (wd_ != 0) {
// Weight decay term
data = data - wd_ * data;
}
variance = variance + grad * grad;
af::eval(variance);
data = data - lr_ * grad / (af::sqrt(variance) + eps_);
af::eval(data);
}
}
std::string AdagradOptimizer::prettyString() const {
std::ostringstream ss;
ss << "Adagrad";
if (eps_ != 0) {
ss << " (epsilon=" << eps_ << ")";
}
return ss.str();
}
} // namespace fl
|
/*
* Copyright 2011 Christoph Bumiller
*
* 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 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 "nv50_ir.h"
#include "nv50_ir_build_util.h"
namespace nv50_ir {
BuildUtil::BuildUtil()
{
init(NULL);
}
BuildUtil::BuildUtil(Program *prog)
{
init(prog);
}
void
BuildUtil::init(Program *prog)
{
this->prog = prog;
func = NULL;
bb = NULL;
pos = NULL;
memset(imms, 0, sizeof(imms));
immCount = 0;
}
void
BuildUtil::addImmediate(ImmediateValue *imm)
{
if (immCount > (NV50_IR_BUILD_IMM_HT_SIZE * 3) / 4)
return;
unsigned int pos = u32Hash(imm->reg.data.u32);
while (imms[pos])
pos = (pos + 1) % NV50_IR_BUILD_IMM_HT_SIZE;
imms[pos] = imm;
immCount++;
}
Instruction *
BuildUtil::mkOp1(operation op, DataType ty, Value *dst, Value *src)
{
Instruction *insn = new_Instruction(func, op, ty);
insn->setDef(0, dst);
insn->setSrc(0, src);
insert(insn);
return insn;
}
Instruction *
BuildUtil::mkOp2(operation op, DataType ty, Value *dst,
Value *src0, Value *src1)
{
Instruction *insn = new_Instruction(func, op, ty);
insn->setDef(0, dst);
insn->setSrc(0, src0);
insn->setSrc(1, src1);
insert(insn);
return insn;
}
Instruction *
BuildUtil::mkOp3(operation op, DataType ty, Value *dst,
Value *src0, Value *src1, Value *src2)
{
Instruction *insn = new_Instruction(func, op, ty);
insn->setDef(0, dst);
insn->setSrc(0, src0);
insn->setSrc(1, src1);
insn->setSrc(2, src2);
insert(insn);
return insn;
}
LValue *
BuildUtil::mkLoad(DataType ty, Symbol *mem, Value *ptr)
{
Instruction *insn = new_Instruction(func, OP_LOAD, ty);
LValue *def = getScratch();
insn->setDef(0, def);
insn->setSrc(0, mem);
if (ptr)
insn->setIndirect(0, 0, ptr);
insert(insn);
return def;
}
Instruction *
BuildUtil::mkStore(operation op, DataType ty, Symbol *mem, Value *ptr,
Value *stVal)
{
Instruction *insn = new_Instruction(func, op, ty);
insn->setSrc(0, mem);
insn->setSrc(1, stVal);
if (ptr)
insn->setIndirect(0, 0, ptr);
insert(insn);
return insn;
}
Instruction *
BuildUtil::mkFetch(Value *dst, DataType ty, DataFile file, int32_t offset,
Value *attrRel, Value *primRel)
{
Symbol *sym = mkSymbol(file, 0, ty, offset);
Instruction *insn = mkOp1(OP_VFETCH, ty, dst, sym);
insn->setIndirect(0, 0, attrRel);
insn->setIndirect(0, 1, primRel);
// already inserted
return insn;
}
Instruction *
BuildUtil::mkInterp(unsigned mode, Value *dst, int32_t offset, Value *rel)
{
operation op = OP_LINTERP;
DataType ty = TYPE_F32;
if ((mode & NV50_IR_INTERP_MODE_MASK) == NV50_IR_INTERP_FLAT)
ty = TYPE_U32;
else
if ((mode & NV50_IR_INTERP_MODE_MASK) == NV50_IR_INTERP_PERSPECTIVE)
op = OP_PINTERP;
Symbol *sym = mkSymbol(FILE_SHADER_INPUT, 0, ty, offset);
Instruction *insn = mkOp1(op, ty, dst, sym);
insn->setIndirect(0, 0, rel);
return insn;
}
Instruction *
BuildUtil::mkMov(Value *dst, Value *src, DataType ty)
{
Instruction *insn = new_Instruction(func, OP_MOV, ty);
insn->setDef(0, dst);
insn->setSrc(0, src);
insert(insn);
return insn;
}
Instruction *
BuildUtil::mkMovToReg(int id, Value *src)
{
Instruction *insn = new_Instruction(func, OP_MOV, typeOfSize(src->reg.size));
insn->setDef(0, new_LValue(func, FILE_GPR));
insn->getDef(0)->reg.data.id = id;
insn->setSrc(0, src);
insert(insn);
return insn;
}
Instruction *
BuildUtil::mkMovFromReg(Value *dst, int id)
{
Instruction *insn = new_Instruction(func, OP_MOV, typeOfSize(dst->reg.size));
insn->setDef(0, dst);
insn->setSrc(0, new_LValue(func, FILE_GPR));
insn->getSrc(0)->reg.data.id = id;
insert(insn);
return insn;
}
Instruction *
BuildUtil::mkCvt(operation op,
DataType dstTy, Value *dst, DataType srcTy, Value *src)
{
Instruction *insn = new_Instruction(func, op, dstTy);
insn->setType(dstTy, srcTy);
insn->setDef(0, dst);
insn->setSrc(0, src);
insert(insn);
return insn;
}
CmpInstruction *
BuildUtil::mkCmp(operation op, CondCode cc, DataType ty, Value *dst,
Value *src0, Value *src1, Value *src2)
{
CmpInstruction *insn = new_CmpInstruction(func, op);
insn->setType((dst->reg.file == FILE_PREDICATE ||
dst->reg.file == FILE_FLAGS) ? TYPE_U8 : ty, ty);
insn->setCondition(cc);
insn->setDef(0, dst);
insn->setSrc(0, src0);
insn->setSrc(1, src1);
if (src2)
insn->setSrc(2, src2);
if (dst->reg.file == FILE_FLAGS)
insn->flagsDef = 0;
insert(insn);
return insn;
}
Instruction *
BuildUtil::mkTex(operation op, TexTarget targ, uint8_t tic, uint8_t tsc,
Value **def, Value **src)
{
TexInstruction *tex = new_TexInstruction(func, op);
for (int d = 0; d < 4 && def[d]; ++d)
tex->setDef(d, def[d]);
for (int s = 0; s < 4 && src[s]; ++s)
tex->setSrc(s, src[s]);
tex->setTexture(targ, tic, tsc);
return tex;
}
Instruction *
BuildUtil::mkQuadop(uint8_t q, Value *def, uint8_t l, Value *src0, Value *src1)
{
Instruction *quadop = mkOp2(OP_QUADOP, TYPE_F32, def, src0, src1);
quadop->subOp = q;
quadop->lanes = l;
return quadop;
}
Instruction *
BuildUtil::mkSelect(Value *pred, Value *dst, Value *trSrc, Value *flSrc)
{
LValue *def0 = getSSA();
LValue *def1 = getSSA();
mkMov(def0, trSrc)->setPredicate(CC_P, pred);
mkMov(def1, flSrc)->setPredicate(CC_NOT_P, pred);
return mkOp2(OP_UNION, typeOfSize(dst->reg.size), dst, def0, def1);
}
Instruction *
BuildUtil::mkSplit(Value *h[2], uint8_t halfSize, Value *val)
{
Instruction *insn = NULL;
const DataType fTy = typeOfSize(halfSize * 2);
if (val->reg.file == FILE_IMMEDIATE)
val = mkMov(getSSA(halfSize * 2), val, fTy)->getDef(0);
if (isMemoryFile(val->reg.file)) {
h[0] = cloneShallow(getFunction(), val);
h[1] = cloneShallow(getFunction(), val);
h[0]->reg.size = halfSize;
h[1]->reg.size = halfSize;
h[1]->reg.data.offset += halfSize;
} else {
h[0] = getSSA(halfSize, val->reg.file);
h[1] = getSSA(halfSize, val->reg.file);
insn = mkOp1(OP_SPLIT, fTy, h[0], val);
insn->setDef(1, h[1]);
}
return insn;
}
FlowInstruction *
BuildUtil::mkFlow(operation op, void *targ, CondCode cc, Value *pred)
{
FlowInstruction *insn = new_FlowInstruction(func, op, targ);
if (pred)
insn->setPredicate(cc, pred);
insert(insn);
return insn;
}
void
BuildUtil::mkClobber(DataFile f, uint32_t rMask, int unit)
{
static const uint16_t baseSize2[16] =
{
0x0000, 0x0010, 0x0011, 0x0020, 0x0012, 0x1210, 0x1211, 0x1220,
0x0013, 0x1310, 0x1311, 0x1320, 0x0022, 0x2210, 0x2211, 0x0040,
};
int base = 0;
for (; rMask; rMask >>= 4, base += 4) {
const uint32_t mask = rMask & 0xf;
if (!mask)
continue;
int base1 = (baseSize2[mask] >> 0) & 0xf;
int size1 = (baseSize2[mask] >> 4) & 0xf;
int base2 = (baseSize2[mask] >> 8) & 0xf;
int size2 = (baseSize2[mask] >> 12) & 0xf;
Instruction *insn = mkOp(OP_NOP, TYPE_NONE, NULL);
if (1) { // size1 can't be 0
LValue *reg = new_LValue(func, f);
reg->reg.size = size1 << unit;
reg->reg.data.id = base + base1;
insn->setDef(0, reg);
}
if (size2) {
LValue *reg = new_LValue(func, f);
reg->reg.size = size2 << unit;
reg->reg.data.id = base + base2;
insn->setDef(1, reg);
}
}
}
ImmediateValue *
BuildUtil::mkImm(uint32_t u)
{
unsigned int pos = u32Hash(u);
while (imms[pos] && imms[pos]->reg.data.u32 != u)
pos = (pos + 1) % NV50_IR_BUILD_IMM_HT_SIZE;
ImmediateValue *imm = imms[pos];
if (!imm) {
imm = new_ImmediateValue(prog, u);
addImmediate(imm);
}
return imm;
}
ImmediateValue *
BuildUtil::mkImm(uint64_t u)
{
ImmediateValue *imm = new_ImmediateValue(prog, (uint32_t)0);
imm->reg.size = 8;
imm->reg.type = TYPE_U64;
imm->reg.data.u64 = u;
return imm;
}
ImmediateValue *
BuildUtil::mkImm(float f)
{
union {
float f32;
uint32_t u32;
} u;
u.f32 = f;
return mkImm(u.u32);
}
Value *
BuildUtil::loadImm(Value *dst, float f)
{
return mkOp1v(OP_MOV, TYPE_F32, dst ? dst : getScratch(), mkImm(f));
}
Value *
BuildUtil::loadImm(Value *dst, uint32_t u)
{
return mkOp1v(OP_MOV, TYPE_U32, dst ? dst : getScratch(), mkImm(u));
}
Value *
BuildUtil::loadImm(Value *dst, uint64_t u)
{
return mkOp1v(OP_MOV, TYPE_U64, dst ? dst : getScratch(8), mkImm(u));
}
Symbol *
BuildUtil::mkSymbol(DataFile file, int8_t fileIndex, DataType ty,
uint32_t baseAddr)
{
Symbol *sym = new_Symbol(prog, file, fileIndex);
sym->setOffset(baseAddr);
sym->reg.type = ty;
sym->reg.size = typeSizeof(ty);
return sym;
}
Symbol *
BuildUtil::mkSysVal(SVSemantic svName, uint32_t svIndex)
{
Symbol *sym = new_Symbol(prog, FILE_SYSTEM_VALUE, 0);
assert(svIndex < 4 ||
(svName == SV_CLIP_DISTANCE || svName == SV_TESS_FACTOR));
switch (svName) {
case SV_POSITION:
case SV_FACE:
case SV_YDIR:
case SV_POINT_SIZE:
case SV_POINT_COORD:
case SV_CLIP_DISTANCE:
case SV_TESS_FACTOR:
sym->reg.type = TYPE_F32;
break;
default:
sym->reg.type = TYPE_U32;
break;
}
sym->reg.size = typeSizeof(sym->reg.type);
sym->reg.data.sv.sv = svName;
sym->reg.data.sv.index = svIndex;
return sym;
}
void
BuildUtil::DataArray::setup(unsigned array, unsigned arrayIdx,
uint32_t base, int len, int vecDim, int eltSize,
DataFile file, int8_t fileIdx)
{
this->array = array;
this->arrayIdx = arrayIdx;
this->baseAddr = base;
this->arrayLen = len;
this->vecDim = vecDim;
this->eltSize = eltSize;
this->file = file;
this->regOnly = !isMemoryFile(file);
if (!regOnly) {
baseSym = new_Symbol(up->getProgram(), file, fileIdx);
baseSym->setOffset(baseAddr);
baseSym->reg.size = eltSize;
} else {
baseSym = NULL;
}
}
Value *
BuildUtil::DataArray::acquire(ValueMap &m, int i, int c)
{
if (regOnly) {
Value *v = lookup(m, i, c);
if (!v)
v = insert(m, i, c, new_LValue(up->getFunction(), file));
return v;
} else {
return up->getScratch();
}
}
Value *
BuildUtil::DataArray::load(ValueMap &m, int i, int c, Value *ptr)
{
if (regOnly) {
Value *v = lookup(m, i, c);
if (!v)
v = insert(m, i, c, new_LValue(up->getFunction(), file));
return v;
} else {
Value *sym = lookup(m, i, c);
if (!sym)
sym = insert(m, i, c, mkSymbol(i, c));
return up->mkLoad(typeOfSize(eltSize), static_cast<Symbol *>(sym), ptr);
}
}
void
BuildUtil::DataArray::store(ValueMap &m, int i, int c, Value *ptr, Value *value)
{
if (regOnly) {
assert(!ptr);
if (!lookup(m, i, c))
insert(m, i, c, value);
assert(lookup(m, i, c) == value);
} else {
Value *sym = lookup(m, i, c);
if (!sym)
sym = insert(m, i, c, mkSymbol(i, c));
const DataType stTy = typeOfSize(value->reg.size);
up->mkStore(OP_STORE, stTy, static_cast<Symbol *>(sym), ptr, value);
}
}
Symbol *
BuildUtil::DataArray::mkSymbol(int i, int c)
{
const unsigned int idx = i * vecDim + c;
Symbol *sym = new_Symbol(up->getProgram(), file, 0);
assert(baseSym || (idx < arrayLen && c < vecDim));
sym->reg.size = eltSize;
sym->reg.type = typeOfSize(eltSize);
sym->setAddress(baseSym, baseAddr + idx * eltSize);
return sym;
}
} // namespace nv50_ir
|
// Copyright (c) 2011-2014 The Bitcoin developers
// Copyright (c) 2014-2015 The Dash developers
// Copyright (c) 2015-2017 The PIVX developers
// Copyright (c) 2018 The TorkilCoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#if defined(HAVE_CONFIG_H)
#include "config/torkilcoin-config.h"
#endif
#include "optionsmodel.h"
#include "bitcoinunits.h"
#include "guiutil.h"
#include "amount.h"
#include "init.h"
#include "main.h"
#include "net.h"
#include "txdb.h" // for -dbcache defaults
#ifdef ENABLE_WALLET
#include "masternodeconfig.h"
#include "wallet.h"
#include "walletdb.h"
#endif
#include <QNetworkProxy>
#include <QSettings>
#include <QStringList>
OptionsModel::OptionsModel(QObject* parent) : QAbstractListModel(parent)
{
Init();
}
void OptionsModel::addOverriddenOption(const std::string& option)
{
strOverriddenByCommandLine += QString::fromStdString(option) + "=" + QString::fromStdString(mapArgs[option]) + " ";
}
// Writes all missing QSettings with their default values
void OptionsModel::Init()
{
resetSettings = false;
QSettings settings;
// Ensure restart flag is unset on client startup
setRestartRequired(false);
// These are Qt-only settings:
// Window
if (!settings.contains("fMinimizeToTray"))
settings.setValue("fMinimizeToTray", false);
fMinimizeToTray = settings.value("fMinimizeToTray").toBool();
if (!settings.contains("fMinimizeOnClose"))
settings.setValue("fMinimizeOnClose", false);
fMinimizeOnClose = settings.value("fMinimizeOnClose").toBool();
// Display
if (!settings.contains("nDisplayUnit"))
settings.setValue("nDisplayUnit", BitcoinUnits::TRC);
nDisplayUnit = settings.value("nDisplayUnit").toInt();
if (!settings.contains("strThirdPartyTxUrls"))
settings.setValue("strThirdPartyTxUrls", "");
strThirdPartyTxUrls = settings.value("strThirdPartyTxUrls", "").toString();
if (!settings.contains("fCoinControlFeatures"))
settings.setValue("fCoinControlFeatures", false);
fCoinControlFeatures = settings.value("fCoinControlFeatures", false).toBool();
if (!settings.contains("nObfuscationRounds"))
settings.setValue("nObfuscationRounds", 2);
if (!settings.contains("nAnonymizeTorkilcoinAmount"))
settings.setValue("nAnonymizeTorkilcoinAmount", 1000);
nObfuscationRounds = settings.value("nObfuscationRounds").toLongLong();
nAnonymizeTorkilcoinAmount = settings.value("nAnonymizeTorkilcoinAmount").toLongLong();
if (!settings.contains("fShowMasternodesTab"))
settings.setValue("fShowMasternodesTab", masternodeConfig.getCount());
// These are shared with the core or have a command-line parameter
// and we want command-line parameters to overwrite the GUI settings.
//
// If setting doesn't exist create it with defaults.
//
// If SoftSetArg() or SoftSetBoolArg() return false we were overridden
// by command-line and show this in the UI.
// Main
if (!settings.contains("nDatabaseCache"))
settings.setValue("nDatabaseCache", (qint64)nDefaultDbCache);
if (!SoftSetArg("-dbcache", settings.value("nDatabaseCache").toString().toStdString()))
addOverriddenOption("-dbcache");
if (!settings.contains("nThreadsScriptVerif"))
settings.setValue("nThreadsScriptVerif", DEFAULT_SCRIPTCHECK_THREADS);
if (!SoftSetArg("-par", settings.value("nThreadsScriptVerif").toString().toStdString()))
addOverriddenOption("-par");
// Wallet
#ifdef ENABLE_WALLET
if (!settings.contains("bSpendZeroConfChange"))
settings.setValue("bSpendZeroConfChange", true);
if (!SoftSetBoolArg("-spendzeroconfchange", settings.value("bSpendZeroConfChange").toBool()))
addOverriddenOption("-spendzeroconfchange");
#endif
// Network
if (!settings.contains("fUseUPnP"))
settings.setValue("fUseUPnP", DEFAULT_UPNP);
if (!SoftSetBoolArg("-upnp", settings.value("fUseUPnP").toBool()))
addOverriddenOption("-upnp");
if (!settings.contains("fListen"))
settings.setValue("fListen", DEFAULT_LISTEN);
if (!SoftSetBoolArg("-listen", settings.value("fListen").toBool()))
addOverriddenOption("-listen");
if (!settings.contains("fUseProxy"))
settings.setValue("fUseProxy", false);
if (!settings.contains("addrProxy"))
settings.setValue("addrProxy", "127.0.0.1:9050");
// Only try to set -proxy, if user has enabled fUseProxy
if (settings.value("fUseProxy").toBool() && !SoftSetArg("-proxy", settings.value("addrProxy").toString().toStdString()))
addOverriddenOption("-proxy");
else if (!settings.value("fUseProxy").toBool() && !GetArg("-proxy", "").empty())
addOverriddenOption("-proxy");
// Display
if (!settings.contains("digits"))
settings.setValue("digits", "2");
if (!settings.contains("theme"))
settings.setValue("theme", "");
if (!settings.contains("fCSSexternal"))
settings.setValue("fCSSexternal", false);
if (!settings.contains("language"))
settings.setValue("language", "");
if (!SoftSetArg("-lang", settings.value("language").toString().toStdString()))
addOverriddenOption("-lang");
if (settings.contains("nObfuscationRounds"))
SoftSetArg("-obfuscationrounds", settings.value("nObfuscationRounds").toString().toStdString());
if (settings.contains("nAnonymizeTorkilcoinAmount"))
SoftSetArg("-anonymizetorkilcoinamount", settings.value("nAnonymizeTorkilcoinAmount").toString().toStdString());
language = settings.value("language").toString();
}
void OptionsModel::Reset()
{
QSettings settings;
// Remove all entries from our QSettings object
settings.clear();
resetSettings = true; // Needed in torkilcoin.cpp during shotdown to also remove the window positions
// default setting for OptionsModel::StartAtStartup - disabled
if (GUIUtil::GetStartOnSystemStartup())
GUIUtil::SetStartOnSystemStartup(false);
}
int OptionsModel::rowCount(const QModelIndex& parent) const
{
return OptionIDRowCount;
}
// read QSettings values and return them
QVariant OptionsModel::data(const QModelIndex& index, int role) const
{
if (role == Qt::EditRole) {
QSettings settings;
switch (index.row()) {
case StartAtStartup:
return GUIUtil::GetStartOnSystemStartup();
case MinimizeToTray:
return fMinimizeToTray;
case MapPortUPnP:
#ifdef USE_UPNP
return settings.value("fUseUPnP");
#else
return false;
#endif
case MinimizeOnClose:
return fMinimizeOnClose;
// default proxy
case ProxyUse:
return settings.value("fUseProxy", false);
case ProxyIP: {
// contains IP at index 0 and port at index 1
QStringList strlIpPort = settings.value("addrProxy").toString().split(":", QString::SkipEmptyParts);
return strlIpPort.at(0);
}
case ProxyPort: {
// contains IP at index 0 and port at index 1
QStringList strlIpPort = settings.value("addrProxy").toString().split(":", QString::SkipEmptyParts);
return strlIpPort.at(1);
}
#ifdef ENABLE_WALLET
case SpendZeroConfChange:
return settings.value("bSpendZeroConfChange");
case ShowMasternodesTab:
return settings.value("fShowMasternodesTab");
#endif
case DisplayUnit:
return nDisplayUnit;
case ThirdPartyTxUrls:
return strThirdPartyTxUrls;
case Digits:
return settings.value("digits");
case Theme:
return settings.value("theme");
case Language:
return settings.value("language");
case CoinControlFeatures:
return fCoinControlFeatures;
case DatabaseCache:
return settings.value("nDatabaseCache");
case ThreadsScriptVerif:
return settings.value("nThreadsScriptVerif");
case ObfuscationRounds:
return QVariant(nObfuscationRounds);
case AnonymizeTorkilcoinAmount:
return QVariant(nAnonymizeTorkilcoinAmount);
case Listen:
return settings.value("fListen");
default:
return QVariant();
}
}
return QVariant();
}
// write QSettings values
bool OptionsModel::setData(const QModelIndex& index, const QVariant& value, int role)
{
bool successful = true; /* set to false on parse error */
if (role == Qt::EditRole) {
QSettings settings;
switch (index.row()) {
case StartAtStartup:
successful = GUIUtil::SetStartOnSystemStartup(value.toBool());
break;
case MinimizeToTray:
fMinimizeToTray = value.toBool();
settings.setValue("fMinimizeToTray", fMinimizeToTray);
break;
case MapPortUPnP: // core option - can be changed on-the-fly
settings.setValue("fUseUPnP", value.toBool());
MapPort(value.toBool());
break;
case MinimizeOnClose:
fMinimizeOnClose = value.toBool();
settings.setValue("fMinimizeOnClose", fMinimizeOnClose);
break;
// default proxy
case ProxyUse:
if (settings.value("fUseProxy") != value) {
settings.setValue("fUseProxy", value.toBool());
setRestartRequired(true);
}
break;
case ProxyIP: {
// contains current IP at index 0 and current port at index 1
QStringList strlIpPort = settings.value("addrProxy").toString().split(":", QString::SkipEmptyParts);
// if that key doesn't exist or has a changed IP
if (!settings.contains("addrProxy") || strlIpPort.at(0) != value.toString()) {
// construct new value from new IP and current port
QString strNewValue = value.toString() + ":" + strlIpPort.at(1);
settings.setValue("addrProxy", strNewValue);
setRestartRequired(true);
}
} break;
case ProxyPort: {
// contains current IP at index 0 and current port at index 1
QStringList strlIpPort = settings.value("addrProxy").toString().split(":", QString::SkipEmptyParts);
// if that key doesn't exist or has a changed port
if (!settings.contains("addrProxy") || strlIpPort.at(1) != value.toString()) {
// construct new value from current IP and new port
QString strNewValue = strlIpPort.at(0) + ":" + value.toString();
settings.setValue("addrProxy", strNewValue);
setRestartRequired(true);
}
} break;
#ifdef ENABLE_WALLET
case SpendZeroConfChange:
if (settings.value("bSpendZeroConfChange") != value) {
settings.setValue("bSpendZeroConfChange", value);
setRestartRequired(true);
}
break;
case ShowMasternodesTab:
if (settings.value("fShowMasternodesTab") != value) {
settings.setValue("fShowMasternodesTab", value);
setRestartRequired(true);
}
break;
#endif
case DisplayUnit:
setDisplayUnit(value);
break;
case ThirdPartyTxUrls:
if (strThirdPartyTxUrls != value.toString()) {
strThirdPartyTxUrls = value.toString();
settings.setValue("strThirdPartyTxUrls", strThirdPartyTxUrls);
setRestartRequired(true);
}
break;
case Digits:
if (settings.value("digits") != value) {
settings.setValue("digits", value);
setRestartRequired(true);
}
break;
case Theme:
if (settings.value("theme") != value) {
settings.setValue("theme", value);
setRestartRequired(true);
}
break;
case Language:
if (settings.value("language") != value) {
settings.setValue("language", value);
setRestartRequired(true);
}
break;
case ObfuscationRounds:
nObfuscationRounds = value.toInt();
settings.setValue("nObfuscationRounds", nObfuscationRounds);
emit obfuscationRoundsChanged(nObfuscationRounds);
break;
case AnonymizeTorkilcoinAmount:
nAnonymizeTorkilcoinAmount = value.toInt();
settings.setValue("nAnonymizeTorkilcoinAmount", nAnonymizeTorkilcoinAmount);
emit anonymizeTorkilcoinAmountChanged(nAnonymizeTorkilcoinAmount);
break;
case CoinControlFeatures:
fCoinControlFeatures = value.toBool();
settings.setValue("fCoinControlFeatures", fCoinControlFeatures);
emit coinControlFeaturesChanged(fCoinControlFeatures);
break;
case DatabaseCache:
if (settings.value("nDatabaseCache") != value) {
settings.setValue("nDatabaseCache", value);
setRestartRequired(true);
}
break;
case ThreadsScriptVerif:
if (settings.value("nThreadsScriptVerif") != value) {
settings.setValue("nThreadsScriptVerif", value);
setRestartRequired(true);
}
break;
case Listen:
if (settings.value("fListen") != value) {
settings.setValue("fListen", value);
setRestartRequired(true);
}
break;
default:
break;
}
}
emit dataChanged(index, index);
return successful;
}
/** Updates current unit in memory, settings and emits displayUnitChanged(newUnit) signal */
void OptionsModel::setDisplayUnit(const QVariant& value)
{
if (!value.isNull()) {
QSettings settings;
nDisplayUnit = value.toInt();
settings.setValue("nDisplayUnit", nDisplayUnit);
emit displayUnitChanged(nDisplayUnit);
}
}
bool OptionsModel::getProxySettings(QNetworkProxy& proxy) const
{
// Directly query current base proxy, because
// GUI settings can be overridden with -proxy.
proxyType curProxy;
if (GetProxy(NET_IPV4, curProxy)) {
proxy.setType(QNetworkProxy::Socks5Proxy);
proxy.setHostName(QString::fromStdString(curProxy.ToStringIP()));
proxy.setPort(curProxy.GetPort());
return true;
} else
proxy.setType(QNetworkProxy::NoProxy);
return false;
}
void OptionsModel::setRestartRequired(bool fRequired)
{
QSettings settings;
return settings.setValue("fRestartRequired", fRequired);
}
bool OptionsModel::isRestartRequired()
{
QSettings settings;
return settings.value("fRestartRequired", false).toBool();
}
|
// <Snippet1>
using namespace System;
using namespace System::Collections;
void PrintValues( IEnumerable^ myList, int myWidth );
int main()
{
// Creates and initializes two BitArrays of the same size.
BitArray^ myBA1 = gcnew BitArray( 4 );
BitArray^ myBA2 = gcnew BitArray( 4 );
myBA1[ 0 ] = false;
myBA1[ 1 ] = false;
myBA1[ 2 ] = true;
myBA1[ 3 ] = true;
myBA2[ 0 ] = false;
myBA2[ 1 ] = true;
myBA2[ 2 ] = false;
myBA2[ 3 ] = true;
// Performs a bitwise XOR operation between BitArray instances of the same size.
Console::WriteLine( "Initial values" );
Console::Write( "myBA1:" );
PrintValues( myBA1, 8 );
Console::Write( "myBA2:" );
PrintValues( myBA2, 8 );
Console::WriteLine();
Console::WriteLine( "Result" );
Console::Write( "XOR:" );
PrintValues( myBA1->Xor( myBA2 ), 8 );
Console::WriteLine();
Console::WriteLine( "After XOR" );
Console::Write( "myBA1:" );
PrintValues( myBA1, 8 );
Console::Write( "myBA2:" );
PrintValues( myBA2, 8 );
Console::WriteLine();
// Performing XOR between BitArray instances of different sizes returns an exception.
try
{
BitArray^ myBA3 = gcnew BitArray( 8 );
myBA3[ 0 ] = false;
myBA3[ 1 ] = false;
myBA3[ 2 ] = false;
myBA3[ 3 ] = false;
myBA3[ 4 ] = true;
myBA3[ 5 ] = true;
myBA3[ 6 ] = true;
myBA3[ 7 ] = true;
myBA1->Xor( myBA3 );
}
catch ( Exception^ myException )
{
Console::WriteLine( "Exception: {0}", myException );
}
}
void PrintValues( IEnumerable^ myList, int myWidth )
{
int i = myWidth;
IEnumerator^ myEnum = myList->GetEnumerator();
while ( myEnum->MoveNext() )
{
Object^ obj = safe_cast<Object^>(myEnum->Current);
if ( i <= 0 )
{
i = myWidth;
Console::WriteLine();
}
i--;
Console::Write( "{0,8}", obj );
}
Console::WriteLine();
}
/*
This code produces the following output.
Initial values
myBA1: False False True True
myBA2: False True False True
Result
XOR: False True True False
After XOR
myBA1: False True True False
myBA2: False True False True
Exception: System.ArgumentException: Array lengths must be the same.
at System.Collections.BitArray.Xor(BitArray value)
at SamplesBitArray.Main()
*/
// </Snippet1>
|
/* Copyright (C) 2021 Joshua J. Daymude, Robert Gmyr, and Kristian Hinnenthal.
* The full GNU GPLv3 can be found in the LICENSE file, and the full copyright
* notice can be found at the top of main/main.cpp. */
#include "alg/demo/discodemo.h"
DiscoDemoParticle::DiscoDemoParticle(const Node& head, const int globalTailDir,
const int orientation,
AmoebotSystem& system,
const int counterMax)
: AmoebotParticle(head, globalTailDir, orientation, system),
_counter(counterMax),
_counterMax(counterMax) {
_state = getRandColor();
}
void DiscoDemoParticle::activate() {
// First decrement the particle's counter. If it's zero, reset the counter and
// get a new color.
_counter--;
if (_counter == 0) {
_counter = _counterMax;
_state = getRandColor();
}
// Next, handle movement. If the particle is contracted, choose a random
// direction to try to expand towards, but only do so if the node in that
// direction is unoccupied. Otherwise, if the particle is expanded, simply
// contract its tail.
if (isContracted()) {
int expandDir = randDir();
if (canExpand(expandDir)) {
expand(expandDir);
}
} else { // isExpanded().
contractTail();
}
}
int DiscoDemoParticle::headMarkColor() const {
switch(_state) {
case State::Red: return 0xff0000;
case State::Orange: return 0xff9000;
case State::Yellow: return 0xffff00;
case State::Green: return 0x00ff00;
case State::Blue: return 0x0000ff;
case State::Indigo: return 0x4b0082;
case State::Violet: return 0xbb00ff;
}
return -1;
}
int DiscoDemoParticle::tailMarkColor() const {
return headMarkColor();
}
QString DiscoDemoParticle::inspectionText() const {
QString text;
text += "Global Info:\n";
text += " head: (" + QString::number(head.x) + ", "
+ QString::number(head.y) + ")\n";
text += " orientation: " + QString::number(orientation) + "\n";
text += " globalTailDir: " + QString::number(globalTailDir) + "\n\n";
text += "Local Info:\n";
text += " state: ";
text += [this](){
switch(_state) {
case State::Red: return "red\n";
case State::Orange: return "orange\n";
case State::Yellow: return "yellow\n";
case State::Green: return "green\n";
case State::Blue: return "blue\n";
case State::Indigo: return "indigo\n";
case State::Violet: return "violet\n";
}
return "no state\n";
}();
text += " counter: " + QString::number(_counter);
return text;
}
DiscoDemoParticle::State DiscoDemoParticle::getRandColor() const {
// Randomly select an integer and return the corresponding state via casting.
return static_cast<State>(randInt(0, 7));
}
DiscoDemoSystem::DiscoDemoSystem(unsigned int numParticles, int counterMax) {
// In order to enclose an area that's roughly 3.7x the # of particles using a
// regular hexagon, the hexagon should have side length 1.4*sqrt(# particles).
int sideLen = static_cast<int>(std::round(1.4 * std::sqrt(numParticles)));
Node boundNode(0, 0);
for (int dir = 0; dir < 6; ++dir) {
for (int i = 0; i < sideLen; ++i) {
insert(new Object(boundNode));
boundNode = boundNode.nodeInDir(dir);
}
}
// Let s be the bounding hexagon side length. When the hexagon is created as
// above, the nodes (x,y) strictly within the hexagon have (i) -s < x < s,
// (ii) 0 < y < 2s, and (iii) 0 < x+y < 2s. Choose interior nodes at random to
// place particles, ensuring at most one particle is placed at each node.
std::set<Node> occupied;
while (occupied.size() < numParticles) {
// First, choose an x and y position at random from the (i) and (ii) bounds.
int x = randInt(-sideLen + 1, sideLen);
int y = randInt(1, 2 * sideLen);
Node node(x, y);
// If the node satisfies (iii) and is unoccupied, place a particle there.
if (0 < x + y && x + y < 2 * sideLen
&& occupied.find(node) == occupied.end()) {
insert(new DiscoDemoParticle(node, -1, randDir(), *this, counterMax));
occupied.insert(node);
}
}
}
|
/*!
* minter_tx.
* check_tx_test.cpp
*
* \date 12/10/2019
* \author Eduard Maximovich (edward.vstock@gmail.com)
* \link https://github.com/edwardstock
*/
#include <gtest/gtest.h>
#include <minter/tx/check_tx.h>
using namespace minter;
TEST(CheckTx, MakeProof) {
dev::bytes_data valid_proof("133824027bddf75120c93cf183f5ff18beea9c350203eb7af02bcbbbca5e282201efe7e4eac2494de85b762296dd4b7ea7879b238a6dd8b012838ee6fc04d51501");
dev::bytes_data pass = dev::bytes_data::from_string_raw("hello");
address_t address("Mx5f0b55330e289490efa54c92e2120d6ebb6514ca");
dev::bytes_data res_proof = check_tx::make_proof(address, pass.get());
ASSERT_STREQ(valid_proof.to_hex().c_str(), res_proof.to_hex().c_str());
ASSERT_EQ(valid_proof, res_proof);
}
TEST(CheckTx, SignEncodeDecode) {
minter::check_t valid_check("Mcf8b08331323802843b9ac9ff8a4d4e54000000000000008906f05b59d3b20000008a4d4e5400000000000000b841b59c9a11ee79a5dbe6e40383a5db5a90960b452e5fddc63cc8f3d092ebf7e39303340d8f42bda3b55a681b9ece3229f9cf718d717ef0c2cb818c52a9b93f27d9001ca0afe5f4c59f1a1f64bd2d7bb97f0fc0cbb9cf1b40d12dc59f948dc419bbad51f8a05033b98e743a9d2af329e890933ea585785573d3a40f52aaa76858083d68654e");
minter::privkey_t priv_key = minter::privkey_t::from_mnemonic("december wedding engage learn plate lion phone lemon hill grocery effort dismiss");
minter::address_t address("Mx5f0b55330e289490efa54c92e2120d6ebb6514ca");
std::string pass = "hello";
minter::check_tx check("128", pass);
check.set_chain_id(minter::chain_id::testnet)
.set_gas_coin("MNT")
.set_coin("MNT")
.set_due_block("999999999")
.set_value("128");
minter::check_t check_result = check.sign(priv_key);
minter::check_tx decoded = minter::check_tx::decode(check_result);
ASSERT_STREQ("128", decoded.get_nonce().to_string().c_str());
ASSERT_NE(128ULL, decoded.get_nonce().to_num_any());
ASSERT_EQ(0x313238ULL, decoded.get_nonce().to_num_any());
ASSERT_EQ(dev::bytes_data("313238"), decoded.get_nonce());
ASSERT_EQ(minter::chain_id::testnet, decoded.get_chain_id());
ASSERT_STREQ("MNT", decoded.get_gas_coin().c_str());
ASSERT_STREQ("MNT", decoded.get_coin().c_str());
ASSERT_EQ(dev::bigint("999999999"), decoded.get_due_block());
ASSERT_EQ(dev::bigdec18("128"), decoded.get_value());
minter::check_tx valid_dec = minter::check_tx::decode(valid_check);
ASSERT_EQ(valid_dec.get_nonce(), decoded.get_nonce());
ASSERT_EQ(valid_dec.get_chain_id(), decoded.get_chain_id());
ASSERT_STREQ(valid_dec.get_gas_coin().c_str(), decoded.get_gas_coin().c_str());
ASSERT_STREQ(valid_dec.get_coin().c_str(), decoded.get_coin().c_str());
ASSERT_EQ(valid_dec.get_due_block(), decoded.get_due_block());
ASSERT_EQ(valid_dec.get_value(), decoded.get_value());
ASSERT_EQ(valid_check.size(), check_result.size());
ASSERT_EQ(valid_check, check_result);
}
|
// Copyright 2018 The SwiftShader 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.
#ifndef VK_SAMPLER_HPP_
#define VK_SAMPLER_HPP_
#include "VkImageView.hpp" // For ResolveIdentityMapping()
#include "Device/Config.hpp"
#include "Device/Memset.hpp"
#include "System/Math.hpp"
#include <atomic>
namespace vk {
struct SamplerState : sw::Memset<SamplerState>
{
SamplerState(const VkSamplerCreateInfo *pCreateInfo, const vk::SamplerYcbcrConversion *ycbcrConversion, VkSamplerFilteringPrecisionModeGOOGLE filteringPrecision);
// Prevents accessing mipmap levels out of range.
static float ClampLod(float lod)
{
return sw::clamp(lod, 0.0f, (float)(sw::MAX_TEXTURE_LOD));
}
const VkFilter magFilter = VK_FILTER_NEAREST;
const VkFilter minFilter = VK_FILTER_NEAREST;
const VkSamplerMipmapMode mipmapMode = VK_SAMPLER_MIPMAP_MODE_NEAREST;
const VkSamplerAddressMode addressModeU = VK_SAMPLER_ADDRESS_MODE_REPEAT;
const VkSamplerAddressMode addressModeV = VK_SAMPLER_ADDRESS_MODE_REPEAT;
const VkSamplerAddressMode addressModeW = VK_SAMPLER_ADDRESS_MODE_REPEAT;
const float mipLodBias = 0.0f;
const VkBool32 anisotropyEnable = VK_FALSE;
const float maxAnisotropy = 0.0f;
const VkBool32 compareEnable = VK_FALSE;
const VkCompareOp compareOp = VK_COMPARE_OP_NEVER;
const float minLod = 0.0f;
const float maxLod = 0.0f;
const VkBorderColor borderColor = VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK;
const VkBool32 unnormalizedCoordinates = VK_FALSE;
VkSamplerYcbcrModelConversion ycbcrModel = VK_SAMPLER_YCBCR_MODEL_CONVERSION_RGB_IDENTITY;
const VkSamplerFilteringPrecisionModeGOOGLE filteringPrecision = VK_SAMPLER_FILTERING_PRECISION_MODE_LOW_GOOGLE;
bool studioSwing = false; // Narrow range
bool swappedChroma = false; // Cb/Cr components in reverse order
};
class Sampler : public Object<Sampler, VkSampler>, public SamplerState
{
public:
Sampler(const VkSamplerCreateInfo *pCreateInfo, void *mem, const SamplerState &samplerState, uint32_t samplerID);
static size_t ComputeRequiredAllocationSize(const VkSamplerCreateInfo *pCreateInfo)
{
return 0;
}
const uint32_t id = 0;
};
class SamplerYcbcrConversion : public Object<SamplerYcbcrConversion, VkSamplerYcbcrConversion>
{
public:
SamplerYcbcrConversion(const VkSamplerYcbcrConversionCreateInfo *pCreateInfo, void *mem)
: format(pCreateInfo->format)
, ycbcrModel(pCreateInfo->ycbcrModel)
, ycbcrRange(pCreateInfo->ycbcrRange)
, components(ResolveIdentityMapping(pCreateInfo->components))
, xChromaOffset(pCreateInfo->xChromaOffset)
, yChromaOffset(pCreateInfo->yChromaOffset)
, chromaFilter(pCreateInfo->chromaFilter)
, forceExplicitReconstruction(pCreateInfo->forceExplicitReconstruction)
{
}
~SamplerYcbcrConversion() = default;
static size_t ComputeRequiredAllocationSize(const VkSamplerYcbcrConversionCreateInfo *pCreateInfo)
{
return 0;
}
const VkFormat format = VK_FORMAT_UNDEFINED;
const VkSamplerYcbcrModelConversion ycbcrModel = VK_SAMPLER_YCBCR_MODEL_CONVERSION_RGB_IDENTITY;
const VkSamplerYcbcrRange ycbcrRange = VK_SAMPLER_YCBCR_RANGE_ITU_FULL;
const VkComponentMapping components = { VK_COMPONENT_SWIZZLE_R, VK_COMPONENT_SWIZZLE_G, VK_COMPONENT_SWIZZLE_B, VK_COMPONENT_SWIZZLE_A };
const VkChromaLocation xChromaOffset = VK_CHROMA_LOCATION_COSITED_EVEN;
const VkChromaLocation yChromaOffset = VK_CHROMA_LOCATION_COSITED_EVEN;
const VkFilter chromaFilter = VK_FILTER_NEAREST;
const VkBool32 forceExplicitReconstruction = VK_FALSE;
};
static inline Sampler *Cast(VkSampler object)
{
return Sampler::Cast(object);
}
static inline SamplerYcbcrConversion *Cast(VkSamplerYcbcrConversion object)
{
return SamplerYcbcrConversion::Cast(object);
}
} // namespace vk
#endif // VK_SAMPLER_HPP_
|
#include <string.h>
#include <iostream>
#include "Components/NodeSortProblemGenerator/NodeSortProblemGenerator.h"
#include "Core/Utilities/Tools/QStatMatrix.h"
#include "Extensions/Extensions.h"
using namespace std;
USING_QPANDA
vector<vector<double>> genGraph(const string& grid, int& real_size);
int calcNodeSort(
const vector<vector<double>>& graph,
int real_size,
float lambda,
float lambda1,
float lambda2,
const std::string &filename);
int calcSIR(
const vector<vector<double>>& graph,
int real_size,
std::vector<int> sources,
float infectious_rate,
float recovery_rate,
int timestep,
const std::string& filename);
int main(int argc, char* argv[])
{
string grid = "1-2";
float lambda = 0.2;
float lambda1 = 0.5;
float lambda2 = 0.5;
bool sir = false;
std::vector<int> sources;
float infectious_rate = 0.9;
float recovery_rate = 0.1;
int timestep = 5;
string filename = "result.json";
if (argc == 2 && !strcmp(argv[1], "--help")) {
cout << "--grid \"0-1;0-2\" (necessary. 0-1;0-2 represent the grid is 1-0-2)" << endl;
cout << "--lambda 0.2 (default = 0.2)" << endl;
cout << "--lambda1 0.5 (default = 0.5)" << endl;
cout << "--lambda2 0.5 (default = 0.5)" << endl;
cout << "--SIR" << endl;
cout << "--source \"0,1\" (default = 0)" << endl;
cout << "--infectious_rate 0.9 (default = 0.9)" << endl;
cout << "--recovery_rate 0.1 (default = 0.1)" << endl;
cout << "--timestep 5 ([5~10]default = 5)" << endl;
cout << "--filename result.json (default = result.json)" << endl;
return 0;
}
for (int i = 0; i < argc; ++i) {
cout << argv[i] << endl;
}
for (int i = 1; i < argc;) {
if (!strcmp(argv[i], "--grid")) {
grid = argv[i + 1];
i = i + 2;
}
else if (!strcmp(argv[i], "--lambda")) {
lambda = atof(argv[i + 1]);
i = i + 2;
}
else if (!strcmp(argv[i], "--lambda1")) {
lambda1 = atof(argv[i + 1]);
i = i + 2;
}
else if (!strcmp(argv[i], "--lambda2")) {
lambda2 = atof(argv[i + 1]);
i = i + 2;
}
else if (!strcmp(argv[i], "--SIR")) {
sir = true;
i = i + 1;
}
else if (!strcmp(argv[i], "--source")) {
auto str_source = QString(argv[i + 1]);
auto items = str_source.split(",", QString::SkipEmptyParts);
for (auto& i : items)
{
bool ok = false;
auto source = i.toInt(&ok);
if (!ok)
{
cout << "source config error!" << endl;
return -1;
}
sources.push_back(source);
}
i = i + 2;
}
else if (!strcmp(argv[i], "--infectious_rate")) {
infectious_rate = atof(argv[i + 1]);
i = i + 2;
}
else if (!strcmp(argv[i], "--recovery_rate")) {
recovery_rate = atof(argv[i + 1]);
i = i + 2;
}
else if (!strcmp(argv[i], "--timestep")) {
timestep = atoi(argv[i + 1]);
i = i + 2;
}
else if (!strcmp(argv[i], "--filename")) {
filename = argv[i + 1];
i = i + 2;
}
}
if (sources.empty())
{
sources.push_back(0);
}
int real_size = 0;
auto graph = genGraph(grid, real_size);
if (graph.empty())
{
return -1;
}
if (sir)
{
return calcSIR(
graph,
real_size,
sources,
infectious_rate,
recovery_rate,
timestep,
filename);
}
else
{
return calcNodeSort(graph, real_size, lambda, lambda1, lambda2, filename);
}
}
vector<vector<double>> genGraph(const string& grid, int &real_size)
{
vector<vector<double>> graph;
QString str_grid(grid);
auto strs = str_grid.split(";", QString::SkipEmptyParts);
real_size = 0;
map<int, vector<int>> node_neighbors;
for (auto& item : strs)
{
auto items = item.split("-", QString::SkipEmptyParts);
if (items.size() > 2)
{
cerr << "grid format error! error item: " << item << endl;
return graph;
}
bool ok = false;
auto node = items[0].toInt(&ok);
if (!ok)
{
cerr << "node must be digital! error node: " << item[0] << endl;
return graph;
}
if (node > real_size)
{
real_size = node;
}
if (node_neighbors.find(node) == node_neighbors.end())
{
node_neighbors.insert(make_pair(node, vector<int>()));
}
if (items.size() == 2)
{
auto neighbor = items[1].toInt(&ok);
if (!ok)
{
cerr << "node must be digital! error node: " << item[1] << endl;
return graph;
}
if (neighbor > real_size)
{
real_size = neighbor;
}
node_neighbors[node].push_back(neighbor);
}
}
auto size = node_neighbors.size();
if (size == 0)
{
cerr << "no node found! error grid: " << grid << endl;
return graph;
}
real_size++;
int tmp_log = ceil(std::log2(real_size));
int tmp_size = std::pow(2, tmp_log);
graph.resize(tmp_size);
for (auto i = 0; i < tmp_size; i++)
{
graph[i].resize(tmp_size);
memset(graph[i].data(), 0, sizeof(int) * tmp_size);
}
for (auto& iter : node_neighbors)
{
if (iter.first >= real_size)
{
cerr << "node is not continus from 0. error node: " << iter.first << endl;
return vector<vector<double>>();
}
for (auto &neighbor: iter.second)
{
if (neighbor >= real_size)
{
cerr << "node is not continus from 0. error node: " << neighbor << endl;
return vector<vector<double>>();
}
graph[iter.first][neighbor] = 1.0;
graph[neighbor][iter.first] = 1.0;
}
}
return graph;
}
template<class T>
bool lessCmp(std::pair<int, T> p1, std::pair<int, T> p2)
{
return p1.second > p2.second;
}
template<class T>
std::vector<std::pair<int, T>> quickSort(const std::vector<T>& vec)
{
std::vector<std::pair<int, T>> sort_vec;
for (int i = 0; i < vec.size(); i++)
{
sort_vec.push_back(std::make_pair(i, vec[i]));
}
std::sort(sort_vec.begin(), sort_vec.end(), lessCmp<T>);
return sort_vec;
}
int calcNodeSort(
const vector<vector<double>>& graph,
int real_size,
float lambda,
float lambda1,
float lambda2,
const std::string& filename)
{
NodeSortProblemGenerator gen;
gen.setProblemGraph(graph);
gen.setLambda1(lambda);
gen.setLambda2(lambda1);
gen.setLambda3(lambda2);
gen.exec();
std::cout << "Classical Liner result: " << std::endl;
auto c_result = gen.getLinearSolverResult();
std::vector<double> tmp_result;
for (auto i = 0; i < c_result.size(); i++)
{
tmp_result.push_back(c_result[i]);
}
auto c_sort_result = quickSort(tmp_result);
for (int i = 0; i < c_sort_result.size(); i++)
{
cout << c_sort_result[i].first << ", " << c_sort_result[i].second << endl;
}
//std::cout << gen.getLinearSolverResult();
std::cout << std::endl;
auto oA = gen.getMatrixA();
auto ob = gen.getVectorB();
auto A = Eigen_to_QStat(oA);
std::vector<double> b;
for (auto i = 0; i < ob.size(); i++)
{
b.push_back(ob[i]);
}
std::cout << "HHL:" << std::endl;
QStat result = HHL_solve_linear_equations(A, b);
std::vector<double> result_vec;
result_vec.resize(real_size);
for (int i = 0; i < real_size; i++)
{
result_vec[i] = result[i].real();
std::cout << result_vec[i] << std::endl;
}
auto sort_result = quickSort(result_vec);
OriginCollection collection(filename, false);
collection = { "sort_index", "value" };
for (int i = 0; i < sort_result.size(); i++)
{
cout << sort_result[i].first << ", " << sort_result[i].second << endl;
collection.insertValue(sort_result[i].first, sort_result[i].second);
}
if (!collection.write())
{
cerr << "write sort result failed!" << endl;
return -1;
}
return 0;
}
int calcSIR(
const vector<vector<double>>& graph,
int real_size,
std::vector<int> sources,
float infectious_rate,
float recovery_rate,
int timestep,
const std::string& filename)
{
srand((int)time(0));
vector<int> state;
state.resize(real_size);
memset(state.data(), 0, sizeof(int) * real_size);
for (auto &i : sources)
{
if (i >= real_size)
{
cerr << "SIR source index error!" << endl;
return -1;
}
state[i] = 1;
}
auto tmp_state = state;
vector<vector<int>> time_states;
for (int t = 0; t < timestep; t++)
{
for (int i = 0; i < real_size; i++)
{
if (state[i] == 1) {
double r1 = 1.0 * rand() / RAND_MAX;
if (r1 < recovery_rate)
{
tmp_state[i] = 2;
}
for (int j = 0; j < real_size; j++) {
double r2 = 1.0 * rand() / RAND_MAX;
if (graph[i][j] > 1e-3
&& r2 < infectious_rate
&& state[j] == 0)
{
tmp_state[j] = 1;
}
}
}
}
time_states.push_back(tmp_state);
state = tmp_state;
}
OriginCollection collection(filename, false);
collection = { "time_step", "node_state" };
for (int i = 0; i < time_states.size(); i++)
{
collection.insertValue(i, time_states[i]);
}
if (!collection.write())
{
cerr << "write sort result failed!" << endl;
return -1;
}
return 0;
}
|
#include <iostream>
#include <world/world_constants.hpp>
#include <world/chunk/chunk_mesh.hpp>
ChunkMesh::ChunkMesh()
{
}
void ChunkMesh::add_face(
const std::vector<GLfloat> &block_face,
const std::vector<GLfloat> &texture_coords,
const sf::Vector3i &chunk_position,
const sf::Vector3i &block_position)
{
auto &verticies = mesh.vertex_positions;
auto &tex_coords = mesh.texture_coords;
auto &indices = mesh.indices;
tex_coords.insert(tex_coords.end(), texture_coords.begin(), texture_coords.end());
///Vertex: The current vertex in the "blockFace" vector, 4 vertex in total hence "< 4"
///Index: X, Y, Z
for (int i = 0, index = 0; i < 4; ++i)
{
verticies.push_back(block_face[index++] + chunk_position.x * CHUNK_SIZE + block_position.x);
verticies.push_back(block_face[index++] + chunk_position.y * CHUNK_SIZE + block_position.y);
verticies.push_back(block_face[index++] + chunk_position.z * CHUNK_SIZE + block_position.z);
}
indices.insert(indices.end(),
{index_index,
index_index + 1,
index_index + 2,
index_index + 2,
index_index + 3,
index_index});
index_index += 4;
}
void ChunkMesh::buffer_mesh()
{
std::cout << "Buffered"
<< "\nVertex: " << mesh.vertex_positions.size()
<< "\nTextures: " << mesh.texture_coords.size()
<< "\nIndices: " << mesh.indices.size() << "\n";
model.add_data(mesh);
mesh.vertex_positions.clear();
mesh.texture_coords.clear();
mesh.indices.clear();
mesh.vertex_positions.shrink_to_fit();
mesh.texture_coords.shrink_to_fit();
mesh.indices.shrink_to_fit();
index_index = 0;
}
const Model &ChunkMesh::get_model() const
{
return model;
}
|
// Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "extern/beatsaber-hook/shared/utils/typedefs.h"
#include "extern/beatsaber-hook/shared/utils/byref.hpp"
// Including type: System.Runtime.Remoting.Messaging.MessageDictionary
#include "System/Runtime/Remoting/Messaging/MessageDictionary.hpp"
// Including type: System.Collections.IDictionaryEnumerator
#include "System/Collections/IDictionaryEnumerator.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "extern/beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Begin forward declares
// Forward declaring namespace: System::Collections
namespace System::Collections {
// Forward declaring type: DictionaryEntry
struct DictionaryEntry;
}
// Completed forward declares
// Type namespace: System.Runtime.Remoting.Messaging
namespace System::Runtime::Remoting::Messaging {
// Size: 0x24
#pragma pack(push, 1)
// Autogenerated type: System.Runtime.Remoting.Messaging.MessageDictionary/System.Runtime.Remoting.Messaging.DictionaryEnumerator
// [TokenAttribute] Offset: FFFFFFFF
class MessageDictionary::DictionaryEnumerator : public ::Il2CppObject/*, public System::Collections::IDictionaryEnumerator*/ {
public:
// private System.Runtime.Remoting.Messaging.MessageDictionary _methodDictionary
// Size: 0x8
// Offset: 0x10
System::Runtime::Remoting::Messaging::MessageDictionary* methodDictionary;
// Field size check
static_assert(sizeof(System::Runtime::Remoting::Messaging::MessageDictionary*) == 0x8);
// private System.Collections.IDictionaryEnumerator _hashtableEnum
// Size: 0x8
// Offset: 0x18
System::Collections::IDictionaryEnumerator* hashtableEnum;
// Field size check
static_assert(sizeof(System::Collections::IDictionaryEnumerator*) == 0x8);
// private System.Int32 _posMethod
// Size: 0x4
// Offset: 0x20
int posMethod;
// Field size check
static_assert(sizeof(int) == 0x4);
// Creating value type constructor for type: DictionaryEnumerator
DictionaryEnumerator(System::Runtime::Remoting::Messaging::MessageDictionary* methodDictionary_ = {}, System::Collections::IDictionaryEnumerator* hashtableEnum_ = {}, int posMethod_ = {}) noexcept : methodDictionary{methodDictionary_}, hashtableEnum{hashtableEnum_}, posMethod{posMethod_} {}
// Creating interface conversion operator: operator System::Collections::IDictionaryEnumerator
operator System::Collections::IDictionaryEnumerator() noexcept {
return *reinterpret_cast<System::Collections::IDictionaryEnumerator*>(this);
}
// Get instance field reference: private System.Runtime.Remoting.Messaging.MessageDictionary _methodDictionary
System::Runtime::Remoting::Messaging::MessageDictionary*& dyn__methodDictionary();
// Get instance field reference: private System.Collections.IDictionaryEnumerator _hashtableEnum
System::Collections::IDictionaryEnumerator*& dyn__hashtableEnum();
// Get instance field reference: private System.Int32 _posMethod
int& dyn__posMethod();
// public System.Object get_Current()
// Offset: 0x1A51E84
::Il2CppObject* get_Current();
// public System.Collections.DictionaryEntry get_Entry()
// Offset: 0x1A51EF0
System::Collections::DictionaryEntry get_Entry();
// public System.Object get_Key()
// Offset: 0x1A522E4
::Il2CppObject* get_Key();
// public System.Object get_Value()
// Offset: 0x1A522E8
::Il2CppObject* get_Value();
// public System.Void .ctor(System.Runtime.Remoting.Messaging.MessageDictionary methodDictionary)
// Offset: 0x1A51D28
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static MessageDictionary::DictionaryEnumerator* New_ctor(System::Runtime::Remoting::Messaging::MessageDictionary* methodDictionary) {
static auto ___internal__logger = ::Logger::get().WithContext("System::Runtime::Remoting::Messaging::MessageDictionary::DictionaryEnumerator::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<MessageDictionary::DictionaryEnumerator*, creationType>(methodDictionary)));
}
// public System.Boolean MoveNext()
// Offset: 0x1A52064
bool MoveNext();
// public System.Void Reset()
// Offset: 0x1A52228
void Reset();
}; // System.Runtime.Remoting.Messaging.MessageDictionary/System.Runtime.Remoting.Messaging.DictionaryEnumerator
#pragma pack(pop)
static check_size<sizeof(MessageDictionary::DictionaryEnumerator), 32 + sizeof(int)> __System_Runtime_Remoting_Messaging_MessageDictionary_DictionaryEnumeratorSizeCheck;
static_assert(sizeof(MessageDictionary::DictionaryEnumerator) == 0x24);
}
DEFINE_IL2CPP_ARG_TYPE(System::Runtime::Remoting::Messaging::MessageDictionary::DictionaryEnumerator*, "System.Runtime.Remoting.Messaging", "MessageDictionary/DictionaryEnumerator");
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
// Writing MetadataGetter for method: System::Runtime::Remoting::Messaging::MessageDictionary::DictionaryEnumerator::get_Current
// Il2CppName: get_Current
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::Il2CppObject* (System::Runtime::Remoting::Messaging::MessageDictionary::DictionaryEnumerator::*)()>(&System::Runtime::Remoting::Messaging::MessageDictionary::DictionaryEnumerator::get_Current)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(System::Runtime::Remoting::Messaging::MessageDictionary::DictionaryEnumerator*), "get_Current", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: System::Runtime::Remoting::Messaging::MessageDictionary::DictionaryEnumerator::get_Entry
// Il2CppName: get_Entry
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<System::Collections::DictionaryEntry (System::Runtime::Remoting::Messaging::MessageDictionary::DictionaryEnumerator::*)()>(&System::Runtime::Remoting::Messaging::MessageDictionary::DictionaryEnumerator::get_Entry)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(System::Runtime::Remoting::Messaging::MessageDictionary::DictionaryEnumerator*), "get_Entry", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: System::Runtime::Remoting::Messaging::MessageDictionary::DictionaryEnumerator::get_Key
// Il2CppName: get_Key
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::Il2CppObject* (System::Runtime::Remoting::Messaging::MessageDictionary::DictionaryEnumerator::*)()>(&System::Runtime::Remoting::Messaging::MessageDictionary::DictionaryEnumerator::get_Key)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(System::Runtime::Remoting::Messaging::MessageDictionary::DictionaryEnumerator*), "get_Key", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: System::Runtime::Remoting::Messaging::MessageDictionary::DictionaryEnumerator::get_Value
// Il2CppName: get_Value
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::Il2CppObject* (System::Runtime::Remoting::Messaging::MessageDictionary::DictionaryEnumerator::*)()>(&System::Runtime::Remoting::Messaging::MessageDictionary::DictionaryEnumerator::get_Value)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(System::Runtime::Remoting::Messaging::MessageDictionary::DictionaryEnumerator*), "get_Value", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: System::Runtime::Remoting::Messaging::MessageDictionary::DictionaryEnumerator::New_ctor
// Il2CppName: .ctor
// Cannot get method pointer of value based method overload from template for constructor!
// Try using FindMethod instead!
// Writing MetadataGetter for method: System::Runtime::Remoting::Messaging::MessageDictionary::DictionaryEnumerator::MoveNext
// Il2CppName: MoveNext
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (System::Runtime::Remoting::Messaging::MessageDictionary::DictionaryEnumerator::*)()>(&System::Runtime::Remoting::Messaging::MessageDictionary::DictionaryEnumerator::MoveNext)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(System::Runtime::Remoting::Messaging::MessageDictionary::DictionaryEnumerator*), "MoveNext", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: System::Runtime::Remoting::Messaging::MessageDictionary::DictionaryEnumerator::Reset
// Il2CppName: Reset
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::Runtime::Remoting::Messaging::MessageDictionary::DictionaryEnumerator::*)()>(&System::Runtime::Remoting::Messaging::MessageDictionary::DictionaryEnumerator::Reset)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(System::Runtime::Remoting::Messaging::MessageDictionary::DictionaryEnumerator*), "Reset", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
|
//snippet-sourcedescription:[get_queue_url.cpp demonstrates how to retrieve the URL of an Amazon SQS queue.]
//snippet-keyword:[C++]
//snippet-keyword:[Code Sample]
//snippet-keyword:[Amazon Simple Queue Service]
//snippet-service:[sqs]
//snippet-sourcetype:[full-example]
//snippet-sourcedate:[]
//snippet-sourceauthor:[AWS]
/*
Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
This file is licensed under the Apache License, Version 2.0 (the "License").
You may not use this file except in compliance with the License. A copy of
the License is located at
http://aws.amazon.com/apache2.0/
This file 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 <aws/core/Aws.h>
#include <aws/sqs/SQSClient.h>
#include <aws/sqs/model/GetQueueUrlRequest.h>
#include <aws/sqs/model/GetQueueUrlResult.h>
#include <iostream>
/**
* Gets the url associated with an sqs queue based on command line input
*/
int main(int argc, char** argv)
{
if (argc != 2) {
std::cout << "Usage: get_queue_url <queue_name>" << std::endl;
return 1;
}
Aws::SDKOptions options;
Aws::InitAPI(options);
{
Aws::String queue_name = argv[1];
Aws::SQS::SQSClient sqs;
Aws::SQS::Model::GetQueueUrlRequest gqu_req;
gqu_req.SetQueueName(queue_name);
auto gqu_out = sqs.GetQueueUrl(gqu_req);
if (gqu_out.IsSuccess()) {
std::cout << "Queue " << queue_name << " has url " <<
gqu_out.GetResult().GetQueueUrl() << std::endl;
} else {
std::cout << "Error getting url for queue " << queue_name << ": " <<
gqu_out.GetError().GetMessage() << std::endl;
}
}
Aws::ShutdownAPI(options);
return 0;
}
|
//===-- checksum.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
//
//===----------------------------------------------------------------------===//
#include "checksum.h"
#include "atomic_helpers.h"
#if defined(__x86_64__) || defined(__i386__)
#include <cpuid.h>
#elif defined(__arm__) || defined(__aarch64__)
#if SCUDO_FUCHSIA
#include <zircon/features.h>
#include <zircon/syscalls.h>
#else
#include <sys/auxv.h>
#endif
#endif
namespace scudo {
Checksum HashAlgorithm = {Checksum::BSD};
#if defined(__x86_64__) || defined(__i386__)
// i386 and x86_64 specific code to detect CRC32 hardware support via CPUID.
// CRC32 requires the SSE 4.2 instruction set.
#ifndef bit_SSE4_2
#define bit_SSE4_2 bit_SSE42 // clang and gcc have different defines.
#endif
bool hasHardwareCRC32() {
u32 Eax, Ebx = 0, Ecx = 0, Edx = 0;
__get_cpuid(0, &Eax, &Ebx, &Ecx, &Edx);
const bool IsIntel = (Ebx == signature_INTEL_ebx) &&
(Edx == signature_INTEL_edx) &&
(Ecx == signature_INTEL_ecx);
const bool IsAMD = (Ebx == signature_AMD_ebx) && (Edx == signature_AMD_edx) &&
(Ecx == signature_AMD_ecx);
if (!IsIntel && !IsAMD)
return false;
__get_cpuid(1, &Eax, &Ebx, &Ecx, &Edx);
return !!(Ecx & bit_SSE4_2);
}
#elif defined(__arm__) || defined(__aarch64__)
#ifndef AT_HWCAP
#define AT_HWCAP 16
#endif
#ifndef HWCAP_CRC32
#define HWCAP_CRC32 (1U << 7) // HWCAP_CRC32 is missing on older platforms.
#endif
bool hasHardwareCRC32() {
#if SCUDO_FUCHSIA
u32 HWCap;
const zx_status_t Status =
zx_system_get_features(ZX_FEATURE_KIND_CPU, &HWCap);
if (Status != ZX_OK)
return false;
return !!(HWCap & ZX_ARM64_FEATURE_ISA_CRC32);
#else
return !!(getauxval(AT_HWCAP) & HWCAP_CRC32);
#endif // SCUDO_FUCHSIA
}
#endif // defined(__x86_64__) || defined(__i386__)
} // namespace scudo
|
/*
* Copyright (c) 2006, Ondrej Danek (www.ondrej-danek.net)
* All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Ondrej Danek 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 <list>
#include <unordered_map>
#include "console/Console.h"
#include "Font.h"
#include "FontException.h"
#include "Video.h"
namespace Duel6 {
Font::Font(Renderer &renderer)
: font(nullptr), renderer(renderer), fontCache(renderer, 100) {}
Font::~Font() {
if (font != nullptr) {
TTF_CloseFont(font);
font = nullptr;
}
}
void Font::load(const std::string &fontFile, Console &console) {
console.printLine(Format("...loading font: {0}") << fontFile);
font = TTF_OpenFont(fontFile.c_str(), 32);
if (font == nullptr) {
D6_THROW(FontException, Format("Unable to load font {0} due to error: {1}") << fontFile << TTF_GetError());
}
}
Float32 Font::getTextWidth(const std::string &str, Float32 height) const {
return str.size() * (height / 2.0f);
}
Int32 Font::getTextWidth(const std::string &str, Int32 height) const {
return Int32(str.size() * height) / 2;
}
void Font::print(Int32 x, Int32 y, const Color &color, const std::string &str) const {
print(Float32(x), Float32(y), 0.0f, color, str, Float32(getCharHeight()));
}
void
Font::print(Float32 x, Float32 y, Float32 z, const Color &color, const std::string &str, Float32 height) const {
if (str.length() < 1) {
return;
}
Texture texture = getTexture(str);
Material material = Material::makeColoredTexture(texture, color);
Float32 width = getTextWidth(str, height);
renderer.setBlendFunc(BlendFunc::SrcAlpha);
renderer.quadXY(Vector(x, y, z), Vector(width, height), Vector(0, 1), Vector(1, -1), material);
renderer.setBlendFunc(BlendFunc::None);
}
Texture Font::getTexture(const std::string &text) const {
if (fontCache.has(text)) {
return fontCache.get(text);
}
Texture texture = renderText(text);
fontCache.add(text, texture);
return texture;
}
Texture Font::renderText(const std::string &text) const {
SDL_Surface *surface = TTF_RenderText_Blended(font, text.c_str(), SDL_Color{255, 255, 255, 255});
Image image = Image::fromSurface(surface);
SDL_FreeSurface(surface);
Texture texture = renderer.createTexture(image, TextureFilter::Linear, true);
return texture;
}
}
|
/* # UNDERLYING CONCEPTS ===>
# Like Kruskal's algorithm, Prim's algorithm is also a Greedy algorithm.
# Prim's algorithm is very similar to Kruskal's: whereas Kruskal's "grows" a forest of trees, Prim's algorithm
grows a single tree until it becomes the minimum spanning tree.
# Both algorithms use the greedy approach - they add the cheapest edge that will not cause a cycle.
But rather than choosing the cheapest edge that will connect any pair of trees together, Prim's algorithm
only adds edges that join nodes to the existing tree. (In this respect, Prim's algorithm is very similar to
Dijkstra's algorithm for finding shortest paths.)
* Reference: [Given at the last].
# Few terms which will be used in the algorithm ---->
* V = set of all the vertices of the graph.
* MST Set = set of all the vertices which have been included in the MST so far.
* Active Edge = An edge between a vertex in MST Set and V.
* MST Edge = An edge which have been included in the MST so far.
# Algorithm ---->
1. Remove all loops and Parallel Edges.
(In case of parallel edges, keep the one which has the least cost associated and remove all others.)
2. Choose any vertex as the starting vertex and include it in MST Set and exclude it from V set.
3. Out of all the active edges choose the one with minimum weight and add it to result.
* Include the other vertex (say 'Y') of this active edge in MST Set & exclude it from V set.
* Add edges starting from 'Y' in the Active Edge list.
* NOTE: No need to consider the edge between 'Y' and previously visited vertex.
4. Repeat step 3 until MST Set doesn't contain all the vertices or V set is empty.
*/
/*****************************************************************************************************/
// METHOD - 1 O(n^2)
// Ref: https://www.geeksforgeeks.org/prims-minimum-spanning-tree-mst-greedy-algo-5/
// https://www.youtube.com/watch?v=oNTsS8lGDHw&list=PLgUwDviBIf0rGEWe64KWas0Nryn7SCRWw&index=21
#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define ld long double
#define ull unsigned long long
#define pb push_back
#define ppb pop_back
#define mp make_pair
#define F first
#define S second
#define PI 3.1415926535897932384626
#define sz(x) ((int)(x).size())
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
typedef vector<int> vi;
typedef vector<ll> vll;
typedef vector<ull> vull;
typedef vector<bool> vb;
typedef vector<char> vc;
typedef vector<string> vs;
typedef vector<pii> vpii;
typedef vector<pll> vpll;
typedef vector<vi> vvi;
typedef vector<vll> vvll;
typedef vector<vull> vvull;
typedef vector<vb> vvb;
typedef vector<vc> vvc;
typedef vector<vs> vvs;
/************************************************** DEBUGGER *******************************************************************************************************/
#ifndef ONLINE_JUDGE
#define debug(x) cerr << #x <<" "; _print(x); cerr << endl;
#else
#define debug(x)
#endif
void _print(ll t) { cerr << t; }
void _print(int t) { cerr << t; }
void _print(string t) { cerr << t; }
void _print(char t) { cerr << t; }
void _print(ld t) { cerr << t; }
void _print(double t) { cerr << t; }
void _print(ull t) { cerr << t; }
template <class T, class V> void _print(pair <T, V> p);
template <class T> void _print(vector <T> v);
template <class T> void _print(vector <vector<T>> v);
template <class T> void _print(set <T> v);
template <class T, class V> void _print(map <T, V> v);
template <class T> void _print(multiset <T> v);
template <class T, class V> void _print(pair <T, V> p) { cerr << "{"; _print(p.F); cerr << ","; _print(p.S); cerr << "}"; }
template <class T> void _print(vector <T> v) { cerr << "[ "; for (T i : v) {_print(i); cerr << " "; } cerr << "]"; }
template <class T> void _print(vector <vector<T>> v) { cerr << "==>" << endl; for (vector<T> vec : v) { for(T i : vec) {_print(i); cerr << " "; } cerr << endl; } }
template <class T> void _print(set <T> v) { cerr << "[ "; for (T i : v) {_print(i); cerr << " "; } cerr << "]"; }
template <class T> void _print(multiset <T> v) { cerr << "[ "; for (T i : v) {_print(i); cerr << " "; } cerr << "]"; }
template <class T, class V> void _print(map <T, V> v) { cerr << "[ "; for (auto i : v) {_print(i); cerr << " "; } cerr << "]"; }
/*******************************************************************************************************************************************************************/
mt19937_64 rang(chrono::high_resolution_clock::now().time_since_epoch().count());
int rng(int lim) {
uniform_int_distribution<int> uid(0,lim-1);
return uid(rang);
}
const int INF = 0x3f3f3f3f;
const int mod = 1e9+7;
ll mod_exp(ll a, ll b) { a %= mod; if(a == 0) return 0LL; ll res = 1LL;
while(b > 0) { if(b & 1) res = (res * a) % mod; a = (a * a) % mod; b >>= 1; } return res; }
ll mod_inv(ll a) { return mod_exp(a, mod - 2); } // works only for prime value of "mod"
ll GCD(ll a, ll b) { return (b == 0) ? a : GCD(b, a % b); }
/******************************************************************************************************************************/
// to store the input graph
vector<vpii> g;
int n, m;
// function to print and return the weight of MST
ll prims_algo() {
// vector to store constructed MST
vi parent(n);
// key values used to pick minimum weight edge every time
vi key(n);
// to represent set of vertices included in MST so far
vb mst(n);
// initialize all keys as INFINITE, not present in MST & no parents
for(int i = 0; i < n; i++) {
key[i] = INT_MAX, mst[i] = 0, parent[i] = -1;
}
// always include first 1st vertex in MST.
// make key 0 so that this vertex is picked as first vertex.
key[0] = 0;
parent[0] = -1;
// as MST will have (n - 1) edges so run loop for (n- 1) times
for(int count = 0; count < n - 1; count++) {
// pick the minimum key vertex from the set of vertices not yet included in MST yet
int mn = INT_MAX, u;
for(int i = 0; i < n; i++) {
if(mst[i] == 0 and key[i] < mn) {
mn = key[i], u = i;
}
}
// add the picked vertex to the MST set
mst[u] = 1;
// update key value and parent index of the adjacent vertices of the picked vertex, by
// considering only those vertices which are not yet included in MST
for(auto x: g[u]) {
int v = x.F, wt = x.S;
if(mst[v] == 0 and wt < key[v]) {
key[v] = wt;
parent[v] = u;
}
}
}
// in case you need the actual MST
vvi MST; // {u, v, wt}
for(int i = 1; i < n; i++) {
vi edg(3);
edg[0] = parent[i], edg[1] = i, edg[2] = key[i];
MST.pb(edg);
}
ll res = 0LL;
for(int i = 0; i < n; i++) res += key[i];
return res;
}
void solve()
{
cin >> n >> m;
g.clear(); g.resize(n);
// 0-based vertices
for(int i = 0; i < m; i++) {
int x, y, wt;
cin >> x >> y >> wt;
g[x].pb({y, wt});
g[y].pb({x, wt});
}
cout << prims_algo() << "\n";
}
int main()
{
ios_base::sync_with_stdio(false), cin.tie(nullptr), cout.tie(nullptr);
srand(chrono::high_resolution_clock::now().time_since_epoch().count());
// #ifndef ONLINE_JUDGE
// freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
// #endif
// #ifndef ONLINE_JUDGE
// freopen("error.txt", "w", stderr);
// #endif
int t = 1;
// int test = 1;
// cin >> t;
while(t--) {
// cout << "Case #" << test++ << ": ";
solve();
}
return 0;
}
/*****************************************************************************************************/
// METHOD - 2
// Ref: https://www.geeksforgeeks.org/prims-mst-for-adjacency-list-representation-greedy-algo-6/
// https://www.youtube.com/watch?v=oNTsS8lGDHw&list=PLgUwDviBIf0rGEWe64KWas0Nryn7SCRWw&index=21
// https://github.com/striver79/StriversGraphSeries/blob/main/primsAlgoCppEfficient
// Time complexity is also discussed in the video.
#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define ld long double
#define ull unsigned long long
#define pb push_back
#define ppb pop_back
#define mp make_pair
#define F first
#define S second
#define PI 3.1415926535897932384626
#define sz(x) ((int)(x).size())
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
typedef vector<int> vi;
typedef vector<ll> vll;
typedef vector<ull> vull;
typedef vector<bool> vb;
typedef vector<char> vc;
typedef vector<string> vs;
typedef vector<pii> vpii;
typedef vector<pll> vpll;
typedef vector<vi> vvi;
typedef vector<vll> vvll;
typedef vector<vull> vvull;
typedef vector<vb> vvb;
typedef vector<vc> vvc;
typedef vector<vs> vvs;
/************************************************** DEBUGGER *******************************************************************************************************/
#ifndef ONLINE_JUDGE
#define debug(x) cerr << #x <<" "; _print(x); cerr << endl;
#else
#define debug(x)
#endif
void _print(ll t) { cerr << t; }
void _print(int t) { cerr << t; }
void _print(string t) { cerr << t; }
void _print(char t) { cerr << t; }
void _print(ld t) { cerr << t; }
void _print(double t) { cerr << t; }
void _print(ull t) { cerr << t; }
template <class T, class V> void _print(pair <T, V> p);
template <class T> void _print(vector <T> v);
template <class T> void _print(vector <vector<T>> v);
template <class T> void _print(set <T> v);
template <class T, class V> void _print(map <T, V> v);
template <class T> void _print(multiset <T> v);
template <class T, class V> void _print(pair <T, V> p) { cerr << "{"; _print(p.F); cerr << ","; _print(p.S); cerr << "}"; }
template <class T> void _print(vector <T> v) { cerr << "[ "; for (T i : v) {_print(i); cerr << " "; } cerr << "]"; }
template <class T> void _print(vector <vector<T>> v) { cerr << "==>" << endl; for (vector<T> vec : v) { for(T i : vec) {_print(i); cerr << " "; } cerr << endl; } }
template <class T> void _print(set <T> v) { cerr << "[ "; for (T i : v) {_print(i); cerr << " "; } cerr << "]"; }
template <class T> void _print(multiset <T> v) { cerr << "[ "; for (T i : v) {_print(i); cerr << " "; } cerr << "]"; }
template <class T, class V> void _print(map <T, V> v) { cerr << "[ "; for (auto i : v) {_print(i); cerr << " "; } cerr << "]"; }
/*******************************************************************************************************************************************************************/
mt19937_64 rang(chrono::high_resolution_clock::now().time_since_epoch().count());
int rng(int lim) {
uniform_int_distribution<int> uid(0,lim-1);
return uid(rang);
}
const int INF = 0x3f3f3f3f;
const int mod = 1e9+7;
ll mod_exp(ll a, ll b) { a %= mod; if(a == 0) return 0LL; ll res = 1LL;
while(b > 0) { if(b & 1) res = (res * a) % mod; a = (a * a) % mod; b >>= 1; } return res; }
ll mod_inv(ll a) { return mod_exp(a, mod - 2); } // works only for prime value of "mod"
ll GCD(ll a, ll b) { return (b == 0) ? a : GCD(b, a % b); }
/******************************************************************************************************************************/
// to store the input graph
vector<vpii> g;
int n, m;
// function to print and return the weight of MST
ll prims_algo() {
// vector to store constructed MST
vi parent(n);
// key values used to pick minimum weight edge every time
vi key(n);
// to represent set of vertices included in MST so far
vb mst(n);
// initialize all keys as INFINITE, not present in MST & no parents
for(int i = 0; i < n; i++) {
key[i] = INT_MAX, mst[i] = 0, parent[i] = -1;
}
priority_queue<pii, vpii, greater<pii>> q;
// always include first 1st vertex in MST.
// make key 0 so that this vertex is picked as first vertex.
key[0] = 0;
parent[0] = -1;
q.push({0, 0}); // {weight, vertex}
while(!q.empty()) {
// pick the minimum key vertex from the set of vertices not yet included in MST yet
int u = q.top().S;
q.pop();
// add the picked vertex to the MST set
mst[u] = 1;
// update key value and parent index of the adjacent vertices of the picked vertex, by
// considering only those vertices which are not yet included in MST
for(auto x: g[u]) {
int v = x.F, wt = x.S;
if(mst[v] == 0 and wt < key[v]) {
key[v] = wt;
parent[v] = u;
q.push({key[v], v});
}
}
}
// in case you need the actual MST
vvi MST; // {u, v, wt}
for(int i = 1; i < n; i++) {
vi edg(3);
edg[0] = parent[i], edg[1] = i, edg[2] = key[i];
MST.pb(edg);
}
ll res = 0LL;
for(int i = 0; i < n; i++) res += key[i];
return res;
}
void solve()
{
cin >> n >> m;
g.clear(); g.resize(n);
// 0-based vertices
for(int i = 0; i < m; i++) {
int x, y, wt;
cin >> x >> y >> wt;
x -= 1, y -= 1;
g[x].pb({y, wt});
g[y].pb({x, wt});
}
cout << prims_algo() << "\n";
}
int main()
{
ios_base::sync_with_stdio(false), cin.tie(nullptr), cout.tie(nullptr);
srand(chrono::high_resolution_clock::now().time_since_epoch().count());
// #ifndef ONLINE_JUDGE
// freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
// #endif
// #ifndef ONLINE_JUDGE
// freopen("error.txt", "w", stderr);
// #endif
int t = 1;
// int test = 1;
// cin >> t;
while(t--) {
// cout << "Case #" << test++ << ": ";
solve();
}
return 0;
}
// Time Complexity: O(|E| x log|E|) which in turn = O(|E| x log|V|), same as Kruskal's algorithm.
// However, Prim's algorithm can be improved using Fibonacci Heaps to O(|E| + log|V|).
// Reference: https://www.cs.auckland.ac.nz/software/AlgAnim/prim.html#:~:text=The%20time%20complexity%20is%20O,O(E%20%2B%20logV).
|
#include <map>
#include "char.h"
static const std::map<std::string, char> charnames(
{
{"tab", '\t'},
{"return", '\r'},
{"linefeed", '\n'},
{"newline", '\n'},
{"page", '\f'},
{"nul", 0},
{"soh", 1},
{"stx", 2},
{"etx", 3},
{"eot", 4},
{"enq", 5},
{"ack", 6},
{"bel", 7},
{"bs", 8},
{"ht", 9},
{"lf", 10},
{"vt", 11},
{"ff", 12},
{"cr", 13},
{"so", 14},
{"si", 15},
{"dle", 16},
{"dc1", 17},
{"dc2", 18},
{"dc3", 19},
{"dc4", 20},
{"nak", 21},
{"syn", 22},
{"etb", 23},
{"can", 24},
{"em", 25},
{"sub", 26},
{"esc", 27},
{"fs", 28},
{"gs", 29},
{"rs", 30},
{"us", 31},
{"space", ' '},
{"del", 127},
}
);
static const std::string asciinames[128] = {"NUL", "SOH", "STX", "ETX", "EOT", "ENQ", "ACK", "BEL",
"BS", "HT", "LF", "VT", "FF", "CR", "SO", "SI",
"DLE", "DC1", "DC2", "DC3", "DC4", "NAK", "SYN", "ETB",
"CAN", "EM", "SUB", "ESC", "FS", "GS", "RS", "US",
"Space", [127]="DEL"};
std::string normalize_char_name(std::string s)
{
if(s.length() > 1)
{
for(char &c : s)
c = tolower(c);
return charnames.count(s) ? s : "";
}
return s;
}
unsigned char char_name_to_char(std::string name)
{
if(name.length() == 1)
return name[0];
name = normalize_char_name(name);
if(charnames.count(name))
return charnames.at(name);
return 0;
}
std::string char_to_char_name(unsigned char c)
{
if(asciinames[c].empty())
return std::string(1, c);
return asciinames[c];
}
|
/*
* StatsLogger.cpp
*
*/
#include <iostream>
#include <fstream>
#include <vector>
#include <chrono>
#include <string>
#include <ctime>
#include "StatsLogger.h"
StatsLogger::LoggingColumn::LoggingColumn(std::string name, std::function<std::string()> callback) : name(name), callback(callback){
}
StatsLogger::StatsLogger(){
}
void StatsLogger::registerLoggingColumn(std::string columnName, std::function<std::string()> callback){
columns.push_back(LoggingColumn(columnName, callback));
}
void StatsLogger::initLog(std::string file){
std::ofstream statsFile;
statsFile.open(file);
statsFile << columns[0].name;
for(int i=1;i<columns.size();i++){
statsFile << ";" << columns[i].name;
}
statsFile << std::endl;
}
void StatsLogger::log(std::string file){
//Log stats
std::ofstream statsFile;
statsFile.open(file, std::ios_base::app);//Append
statsFile << columns[0].callback();
for(int i=1;i<columns.size();i++){
statsFile << ";" << columns[i].callback();
}
statsFile << std::endl;
}
void StatsLogger::archiveLog(std::string file){
std::string nameAndPath = (file.substr(0, file.find_last_of(".") - 1));
std::string extension = (file.substr(0, file.find_last_of(".") + 1));
std::time_t rawtime;
std::tm* timeinfo;
char buffer [20];
std::time(&rawtime);
timeinfo = std::localtime(&rawtime);
std::strftime(buffer, 20, "%Y-%m-%d-%H-%M", timeinfo);
std::puts(buffer);
rename(file.c_str(), (nameAndPath + "-" + std::string(buffer) + extension).c_str());
}
|
// Copyright (C) 2018-2020 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#pragma once
#include <iterator>
#include <vector>
#include <unordered_map>
#include <unordered_set>
#include <limits>
#include <map>
#include <type_traits>
#include <functional>
#include <utility>
#include <ie_layouts.h>
#include <vpu/utils/enums.hpp>
#include <vpu/utils/io.hpp>
#include <vpu/utils/dot_io.hpp>
#include <vpu/utils/checked_cast.hpp>
#include <vpu/utils/error.hpp>
//
// Description (type, layout, dimensions, strides) for Data objects inside the VPU Model.
//
// The VPU Model uses own represenatation of Data layout and dimensions.
// The dimensions are stored in a special container in memory-independent order.
// Each dimension has unique name, which can be represented as an index (eg. `width` : 0, `height` : 1, etc.).
// The DimsOrder parameter provides information about actual layout in the memory.
// During the Fathom Blob serialization VPU Graph Transformer will convert the dimensions from
// memory-independant order to memory order from minor to major dimension.
//
namespace vpu {
namespace ie = InferenceEngine;
//
// DataType
//
// Must be synchronized with MvTensor
VPU_DECLARE_ENUM(DataType,
FP16 = 0,
U8 = 1,
S32 = 2,
FP32 = 3,
I8 = 4
)
DataType fromIEPrecision(const InferenceEngine::Precision& precision);
//
// StorageOrder
//
//
// Types that are used to store order permutation in packed format.
//
using StorageOrder64 = uint64_t;
using StorageOrder32 = uint32_t;
// High-order digit excluded.
const int MAX_DIMS_64 = std::numeric_limits<StorageOrder64>::digits / 4 - 1;
const int MAX_DIMS_32 = std::numeric_limits<StorageOrder32>::digits / 4;
//
// Dim
//
//
// Named dimensions for better readability.
//
VPU_DECLARE_ENUM(Dim,
Invalid = -1,
W = 0,
H = 1,
C = 2,
N = 3,
D = 4
)
// TODO: identify casts like static_cast<int>(Dim),
// and replace all with calling this function
// JIRA: #21163
int dimToIeInd(vpu::Dim const& dim, int numDims);
using DimVector = SmallVector<Dim, MAX_DIMS_64>;
using DimSet = std::unordered_set<Dim, EnumClassHash>;
//
// DimValues
//
//
// Container to store dimensions values (sizes, offsets, strides).
// Internally it is a map from Dim to `int`.
// Should be used together with DimsOrder to get the permutation array.
//
template <typename T>
class DimValues_ final {
static_assert(std::is_trivial<T>::value, "std::is_trivial<T>::value");
using ValuesCont = std::array<std::pair<Dim, T>, MAX_DIMS_64>;
using FlagsCont = std::array<bool, MAX_DIMS_64>;
public:
template <bool IsConst>
class Iterator final {
public:
using ValuesContInner = typename std::conditional<IsConst, const ValuesCont, ValuesCont>::type;
using FlagsContInner = const FlagsCont;
using value_type = typename std::conditional<IsConst, const std::pair<Dim, T>, std::pair<Dim, T>>::type;
using pointer = value_type*;
using reference = value_type&;
using iterator_category = std::bidirectional_iterator_tag;
using difference_type = std::ptrdiff_t;
Iterator() = default;
Iterator(const Iterator&) = default;
Iterator& operator=(const Iterator&) = default;
Iterator(Dim cur, ValuesContInner& values, FlagsContInner& flags) : _cur(cur), _values(&values), _flags(&flags) {
advance();
}
reference operator*() const {
auto curInd = static_cast<int32_t>(_cur);
IE_ASSERT(curInd >= 0 && curInd < MAX_DIMS_64);
IE_ASSERT((*_flags)[curInd]);
return (*_values)[curInd];
}
Iterator& operator++() {
auto curInd = static_cast<int32_t>(_cur);
IE_ASSERT(curInd >= 0 && curInd < MAX_DIMS_64);
IE_ASSERT((*_flags)[curInd]);
_cur = static_cast<Dim>(static_cast<int32_t>(_cur) + 1);
advance();
return *this;
}
Iterator operator++(int) {
auto curInd = static_cast<int32_t>(_cur);
IE_ASSERT(curInd >= 0 && curInd < MAX_DIMS_64);
IE_ASSERT((*_flags)[curInd]);
auto tmp(*this);
_cur = static_cast<Dim>(static_cast<int32_t>(_cur) + 1);
advance();
return tmp;
}
Iterator& operator--() {
auto curInd = static_cast<int32_t>(_cur);
IE_ASSERT(curInd >= 0 && curInd < MAX_DIMS_64);
IE_ASSERT((*_flags)[curInd]);
_cur = static_cast<Dim>(static_cast<int32_t>(_cur) - 1);
moveBack();
return *this;
}
Iterator operator--(int) {
auto curInd = static_cast<int32_t>(_cur);
IE_ASSERT(curInd >= 0 && curInd < MAX_DIMS_64);
IE_ASSERT((*_flags)[curInd]);
auto tmp(*this);
_cur = static_cast<Dim>(static_cast<int32_t>(_cur) - 1);
moveBack();
return tmp;
}
bool operator==(const Iterator& other) const { return _cur == other._cur; }
bool operator!=(const Iterator& other) const { return _cur != other._cur; }
private:
void advance() {
auto curInd = static_cast<int32_t>(_cur);
while (curInd >= 0 && curInd < MAX_DIMS_64 && !(*_flags)[curInd]) {
++curInd;
}
if (curInd == MAX_DIMS_64) {
curInd = -1;
}
_cur = static_cast<Dim>(curInd);
}
void moveBack() {
auto curInd = static_cast<int32_t>(_cur);
while (curInd >= 0 && curInd < MAX_DIMS_64 && !(*_flags)[curInd]) {
--curInd;
}
_cur = static_cast<Dim>(curInd);
}
private:
Dim _cur = Dim::Invalid;
ValuesContInner* _values;
FlagsContInner* _flags;
};
using value_type = std::pair<Dim, T>;
using iterator = Iterator<false>;
using const_iterator = Iterator<true>;
DimValues_() {
_flags.fill(false);
}
DimValues_(std::initializer_list<value_type> data) {
_flags.fill(false);
for (const auto& p : data) {
auto ind = static_cast<int32_t>(p.first);
IE_ASSERT(ind >= 0 && ind < MAX_DIMS_64);
IE_ASSERT(!_flags[ind]);
_values[ind] = p;
_flags[ind] = true;
}
_size = data.size();
}
DimValues_(const DimValues_&) = default;
DimValues_& operator=(const DimValues_&) = default;
size_t size() const { return _size; }
bool empty() const { return _size == 0; }
void clear() {
_flags.fill(false);
_size = 0;
}
void erase(Dim d) {
auto ind = static_cast<int32_t>(d);
IE_ASSERT(ind >= 0 && ind < MAX_DIMS_64);
if (_flags[ind]) {
IE_ASSERT(_size > 0);
_flags[ind] = false;
--_size;
}
}
bool has(Dim d) const {
auto ind = static_cast<int32_t>(d);
IE_ASSERT(ind >= 0 && ind < MAX_DIMS_64);
return _flags[static_cast<size_t>(ind)];
}
const T& operator[](Dim d) const {
auto ind = static_cast<int32_t>(d);
IE_ASSERT(ind >= 0 && ind < MAX_DIMS_64);
IE_ASSERT(_flags[static_cast<size_t>(ind)]);
return _values[static_cast<size_t>(ind)].second;
}
const T& get(Dim d, const T& def) const {
auto ind = static_cast<int32_t>(d);
IE_ASSERT(ind >= 0 && ind < MAX_DIMS_64);
return _flags[static_cast<size_t>(ind)] ? _values[static_cast<size_t>(ind)].second : def;
}
void set(Dim d, const T& val) {
auto ind = static_cast<int32_t>(d);
IE_ASSERT(ind >= 0 && ind < MAX_DIMS_64);
if (!_flags[static_cast<size_t>(ind)]) {
_flags[static_cast<size_t>(ind)] = true;
++_size;
}
_values[ind] = std::make_pair(d, val);
}
iterator begin() { return iterator(Dim::W, _values, _flags); }
iterator end() { return iterator(Dim::Invalid, _values, _flags); }
const_iterator begin() const { return const_iterator(Dim::W, _values, _flags); }
const_iterator end() const { return const_iterator(Dim::Invalid, _values, _flags); }
const_iterator cbegin() const { return const_iterator(Dim::W, _values, _flags); }
const_iterator cend() const { return const_iterator(Dim::Invalid, _values, _flags); }
std::array<T, MAX_DIMS_64> toVector(const T& emptyValue) const {
std::array<T, MAX_DIMS_64> out;
out.fill(emptyValue);
for (int ind = 0; ind < MAX_DIMS_64; ++ind) {
if (_flags[ind]) {
out[ind] = _values[ind].second;
}
}
return out;
}
bool operator==(const DimValues_& other) const {
for (int ind = 0; ind < MAX_DIMS_64; ++ind) {
if (_flags[ind] != other._flags[ind]) {
return false;
}
if (_flags[ind] && _values[ind].second != other._values[ind].second) {
return false;
}
}
return true;
}
bool operator!=(const DimValues_& other) const {
for (int ind = 0; ind < MAX_DIMS_64; ++ind) {
if (_flags[ind] != other._flags[ind]) {
return true;
}
if (_flags[ind] && _values[ind].second != other._values[ind].second) {
return true;
}
}
return false;
}
bool operator<(const DimValues_& other) const {
for (int ind = 0; ind < MAX_DIMS_64; ++ind) {
if (_flags[ind] != other._flags[ind]) {
return !_flags[ind];
}
if (_flags[ind] && _values[ind].second != other._values[ind].second) {
return _values[ind].second < other._values[ind].second;
}
}
return false;
}
void printImpl(std::ostream& os) const {
int realInd = 0;
for (int ind = 0; ind < MAX_DIMS_64; ++ind) {
if (_flags[ind]) {
vpu::printTo(os, _values[ind].first);
os << " : ";
vpu::printTo(os, _values[ind].second);
if (realInd + 1 < _size) {
os << ", ";
}
++realInd;
}
}
}
private:
ValuesCont _values = {};
FlagsCont _flags;
size_t _size = 0;
};
template <typename T>
void printTo(std::ostream& os, const DimValues_<T>& dimValues) {
os << "[";
dimValues.printImpl(os);
os << "]";
}
using DimValues = DimValues_<int>;
template<class T>
std::ostream& operator<<(std::ostream& stream, const DimValues_<T>& object) {
object.printImpl(stream);
return stream;
}
//
// DimsOrder
//
StorageOrder64 maskOrder(StorageOrder64 fullOrder, int size);
class DimsOrder final {
public:
//
// Predefined orders
//
static DimsOrder C;
static DimsOrder NC;
static DimsOrder CHW;
static DimsOrder HWC;
static DimsOrder HCW;
static DimsOrder NCHW;
static DimsOrder NHWC;
static DimsOrder NHCW;
static DimsOrder NCDHW;
static DimsOrder NDHWC;
//
// Constructor
//
DimsOrder() = default;
static DimsOrder fromCode(StorageOrder64 code);
static DimsOrder fromNumDims(size_t numDims);
static DimsOrder fromPermutation(const DimVector& perm);
static DimsOrder fromLayout(ie::Layout const& layout);
//
// Accessors
//
bool empty() const { return _code == 0; }
int numDims() const;
bool hasDim(Dim d) const;
int dimInd(Dim d) const;
StorageOrder64 code() const { return _code; }
//
// Information about dimension order
//
// Convert from packed format to array of dimensions from minor to major.
DimVector toPermutation() const;
// Get memory indeces for each dimension.
DimValues toIndices() const;
//
// Relayout helpers
//
// In-place modification.
void moveDim(Dim dim, int newPos);
// Makes new object.
DimsOrder createMovedDim(Dim dim, int newPos) const;
private:
StorageOrder64 _code = 0;
};
bool isOrdersCompatible(DimsOrder order1, DimsOrder order2);
inline bool operator==(DimsOrder order1, DimsOrder order2) {
return order1.code() == order2.code();
}
inline bool operator!=(DimsOrder order1, DimsOrder order2) {
return order1.code() != order2.code();
}
std::ostream& operator<<(std::ostream& stream, const DimsOrder& object);
void printTo(std::ostream& os, DimsOrder order);
struct DimsOrderHash final {
size_t operator()(DimsOrder order) const {
return std::hash<StorageOrder64>()(order.code());
}
};
using DimsOrderSet = std::unordered_set<DimsOrder, DimsOrderHash>;
template <typename Val>
using DimsOrderMap = std::unordered_map<DimsOrder, Val, DimsOrderHash>;
//
// Permutations
//
using PermutationIndexVector = SmallVector<int, MAX_DIMS_32>; // we could use MAX_DIMS_64, but it's now unsupported by serializer.
using PermutationDimsMap = DimValues_<Dim>;
PermutationIndexVector permuteMapToVector(const PermutationDimsMap& permutation, DimsOrder inputOrder, DimsOrder outputOrder);
PermutationDimsMap permuteVectorToMap(const PermutationIndexVector& permutation, DimsOrder inputOrder, DimsOrder outputOrder);
PermutationIndexVector combinePermutationVectors(const PermutationIndexVector& first, const PermutationIndexVector& second);
PermutationIndexVector calculatePermuteForReorder(DimsOrder oldLayout, DimsOrder newLayout);
//
// DataDesc
//
class DataDesc final {
public:
//
// Constructors
//
DataDesc() = default;
template<typename iterator,
typename value_type = typename std::iterator_traits<iterator>::value_type,
typename = typename std::enable_if<std::is_integral<value_type>::value>::type>
DataDesc(DataType type, DimsOrder dimsOrder, iterator dimsBegin, iterator dimsEnd) :
_type(type), _dimsOrder(dimsOrder) {
const auto perm = _dimsOrder.toPermutation();
const auto dimsSize = std::distance(dimsBegin, dimsEnd);
if (dimsSize != 0) {
VPU_THROW_UNLESS(dimsSize == perm.size(), "Dimensions' size ({}) and permutation size ({}) are expected to be the same", dimsSize, perm.size());
int ind = 0;
for (auto i = dimsBegin; i < dimsEnd; i++) {
auto val = *i;
_dims.set(perm[ind], static_cast<int>(val));
++ind;
}
} else {
VPU_THROW_UNLESS(_dimsOrder == DimsOrder::C,
R"(Failed to create VPU data object: empty dimensions vector is supported only with "C" layout, but "{}" layout provided)", _dimsOrder);
_dims.set(perm[0], 1);
}
}
template <typename IntValue, typename = typename std::enable_if<std::is_integral<IntValue>::value>::type>
DataDesc(DataType type, DimsOrder dimsOrder, const std::vector<IntValue>& dims) : DataDesc(type, dimsOrder, dims.cbegin(), dims.cend()) {}
template <typename IntValue, typename = typename std::enable_if<std::is_integral<IntValue>::value>::type>
DataDesc(DataType type, DimsOrder dimsOrder, std::initializer_list<IntValue> dims) : DataDesc(type, dimsOrder, dims.begin(), dims.end()) {}
template <typename IntValue, typename = typename std::enable_if<std::is_integral<IntValue>::value>::type>
DataDesc(DimsOrder dimsOrder, std::initializer_list<IntValue> dims) : DataDesc(DataType::FP16, dimsOrder, dims) {}
template <typename IntValue, typename = typename std::enable_if<std::is_integral<IntValue>::value>::type>
DataDesc(std::initializer_list<IntValue> dims) : DataDesc(DataType::FP16, DimsOrder::fromNumDims(dims.size()), dims) {}
template <typename IntValue, typename = typename std::enable_if<std::is_integral<IntValue>::value>::type>
explicit DataDesc(const std::vector<IntValue>& dims) : DataDesc(DataType::FP16, DimsOrder::fromNumDims(dims.size()), dims) {}
explicit DataDesc(const ie::TensorDesc& ieDesc);
DataDesc(DataType type, DimsOrder dimsOrder, const DimValues& dims);
//
// DataType
//
DataType type() const { return _type; }
void setType(DataType type) { _type = type; }
int elemSize() const;
//
// Dims
//
int numDims() const { return _dimsOrder.numDims(); }
const DimValues& dims() const { return _dims; }
int dim(Dim d) const { return _dims[d]; }
int dim(Dim d, int defVal) const { return _dims.has(d) ? _dims[d] : defVal; }
void setDim(Dim d, int val);
int totalDimSize() const;
int dimsByteSize() const { return numDims() * static_cast<int>(sizeof(int32_t)); }
//
// DimsOrder
//
DimsOrder dimsOrder() const { return _dimsOrder; }
void moveDim(Dim dim, int newPos) {
_dimsOrder.moveDim(dim, newPos);
}
void reorder(DimsOrder dimsOrder);
//
// Export
//
ie::TensorDesc toTensorDesc() const;
bool operator==(const DataDesc& rhs) const {
return _type == rhs.type() && _dimsOrder == rhs.dimsOrder() && _dims == rhs.dims();
}
bool operator!=(const DataDesc& rhs) const {
return !(*this == rhs);
}
private:
DataType _type = DataType::FP16;
DimsOrder _dimsOrder;
DimValues _dims;
};
std::ostream& operator<<(std::ostream& stream, const DataDesc& object);
void printTo(std::ostream& os, const DataDesc& desc);
void printTo(DotLabel& lbl, const DataDesc& desc);
//
// DimStride
//
VPU_DECLARE_ENUM(DimStride,
Any,
Compact,
Aligned,
Fixed
)
const int HW_STRIDE_ALIGNMENT = 16;
//
// StridesRequirement
//
//
// Container for stride requirement per each dimensions (in memory order).
//
class StridesRequirement final {
public:
StridesRequirement() { _map[0] = DimStride::Compact; }
static StridesRequirement empty() { return StridesRequirement().add(0, DimStride::Any); }
static StridesRequirement compact();
static StridesRequirement fixed(const std::vector<int>& strides, const DataDesc& desc);
StridesRequirement& add(int index, DimStride stride) {
IE_ASSERT(index >= 0 && index < MAX_DIMS_64);
_map[static_cast<size_t>(index)] = stride;
return *this;
}
StridesRequirement& remove(int index) {
IE_ASSERT(index >= 0 && index < MAX_DIMS_64);
_map[static_cast<size_t>(index)] = DimStride::Any;
return *this;
}
DimStride get(int index) const {
IE_ASSERT(index >= 0 && index < MAX_DIMS_64);
return _map[static_cast<size_t>(index)];
}
bool operator==(const StridesRequirement& other) const {
return (_map == other._map);
}
bool operator!=(const StridesRequirement& other) const {
return (_map != other._map);
}
const DimValues& fixedStrides() const { return _fixedStrides; }
int getFixedStride(Dim d) const { return _fixedStrides[d]; }
private:
std::array<DimStride, MAX_DIMS_64> _map{{DimStride::Any}};
DimValues _fixedStrides;
};
void printTo(std::ostream& os, const StridesRequirement& reqs);
void printTo(DotLabel& lbl, const StridesRequirement& reqs);
DimValues calcStrides(const DataDesc& desc, const StridesRequirement& reqs);
bool checkStride(
const DimValues& strides,
const DataDesc& desc,
int ind,
const StridesRequirement& req);
bool checkStrides(
const DataDesc& desc,
const DimValues& strides,
const StridesRequirement& reqs);
int calcTotalByteSize(const DataDesc& desc, const DimValues& strides);
//
// BatchSupport
//
VPU_DECLARE_ENUM(BatchSupport,
Split
)
} // namespace vpu
|
//===-- llvm-nm.cpp - Symbol table dumping utility for llvm ---------------===//
//
// 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 program is a utility that works like traditional Unix "nm", that is, it
// prints out the names of symbols in a bitcode or object file, along with some
// information about each symbol.
//
// This "nm" supports many of the features of GNU "nm", including its different
// output formats.
//
//===----------------------------------------------------------------------===//
#include "llvm/ADT/StringSwitch.h"
#include "llvm/BinaryFormat/COFF.h"
#include "llvm/Demangle/Demangle.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/Object/Archive.h"
#include "llvm/Object/COFF.h"
#include "llvm/Object/COFFImportFile.h"
#include "llvm/Object/ELFObjectFile.h"
#include "llvm/Object/IRObjectFile.h"
#include "llvm/Object/MachO.h"
#include "llvm/Object/MachOUniversal.h"
#include "llvm/Object/ObjectFile.h"
#include "llvm/Object/TapiFile.h"
#include "llvm/Object/TapiUniversal.h"
#include "llvm/Object/Wasm.h"
#include "llvm/Option/Arg.h"
#include "llvm/Option/ArgList.h"
#include "llvm/Option/Option.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/Format.h"
#include "llvm/Support/InitLLVM.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/Program.h"
#include "llvm/Support/Signals.h"
#include "llvm/Support/TargetSelect.h"
#include "llvm/Support/WithColor.h"
#include "llvm/Support/raw_ostream.h"
#include <vector>
using namespace llvm;
using namespace object;
namespace {
using namespace llvm::opt; // for HelpHidden in Opts.inc
enum ID {
OPT_INVALID = 0, // This is not an option ID.
#define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
HELPTEXT, METAVAR, VALUES) \
OPT_##ID,
#include "Opts.inc"
#undef OPTION
};
#define PREFIX(NAME, VALUE) const char *const NAME[] = VALUE;
#include "Opts.inc"
#undef PREFIX
static const opt::OptTable::Info InfoTable[] = {
#define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
HELPTEXT, METAVAR, VALUES) \
{ \
PREFIX, NAME, HELPTEXT, \
METAVAR, OPT_##ID, opt::Option::KIND##Class, \
PARAM, FLAGS, OPT_##GROUP, \
OPT_##ALIAS, ALIASARGS, VALUES},
#include "Opts.inc"
#undef OPTION
};
class NmOptTable : public opt::OptTable {
public:
NmOptTable() : OptTable(InfoTable) { setGroupedShortOptions(true); }
};
enum OutputFormatTy { bsd, sysv, posix, darwin, just_symbols };
} // namespace
static bool ArchiveMap;
static bool DebugSyms;
static bool DefinedOnly;
static bool Demangle;
static bool DynamicSyms;
static bool ExternalOnly;
static OutputFormatTy OutputFormat;
static bool NoLLVMBitcode;
static bool NoSort;
static bool NoWeakSymbols;
static bool NumericSort;
static bool PrintFileName;
static bool PrintSize;
static bool Quiet;
static bool ReverseSort;
static bool SpecialSyms;
static bool SizeSort;
static bool UndefinedOnly;
static bool WithoutAliases;
namespace {
enum Radix { d, o, x };
} // namespace
static Radix AddressRadix;
// Mach-O specific options.
static bool ArchAll = false;
static std::vector<StringRef> ArchFlags;
static bool AddDyldInfo;
static bool AddInlinedInfo;
static bool DyldInfoOnly;
static bool FormatMachOasHex;
static bool NoDyldInfo;
static std::vector<StringRef> SegSect;
static bool MachOPrintSizeWarning = false;
// Miscellaneous states.
static bool PrintAddress = true;
static bool MultipleFiles = false;
static bool HadError = false;
static StringRef ToolName;
static void error(Twine Message, Twine Path = Twine()) {
HadError = true;
WithColor::error(errs(), ToolName) << Path << ": " << Message << "\n";
}
static bool error(std::error_code EC, Twine Path = Twine()) {
if (EC) {
error(EC.message(), Path);
return true;
}
return false;
}
// This version of error() prints the archive name and member name, for example:
// "libx.a(foo.o)" after the ToolName before the error message. It sets
// HadError but returns allowing the code to move on to other archive members.
static void error(llvm::Error E, StringRef FileName, const Archive::Child &C,
StringRef ArchitectureName = StringRef()) {
HadError = true;
WithColor::error(errs(), ToolName) << FileName;
Expected<StringRef> NameOrErr = C.getName();
// TODO: if we have a error getting the name then it would be nice to print
// the index of which archive member this is and or its offset in the
// archive instead of "???" as the name.
if (!NameOrErr) {
consumeError(NameOrErr.takeError());
errs() << "(" << "???" << ")";
} else
errs() << "(" << NameOrErr.get() << ")";
if (!ArchitectureName.empty())
errs() << " (for architecture " << ArchitectureName << ")";
std::string Buf;
raw_string_ostream OS(Buf);
logAllUnhandledErrors(std::move(E), OS);
OS.flush();
errs() << ": " << Buf << "\n";
}
// This version of error() prints the file name and which architecture slice it
// is from, for example: "foo.o (for architecture i386)" after the ToolName
// before the error message. It sets HadError but returns allowing the code to
// move on to other architecture slices.
static void error(llvm::Error E, StringRef FileName,
StringRef ArchitectureName = StringRef()) {
HadError = true;
WithColor::error(errs(), ToolName) << FileName;
if (!ArchitectureName.empty())
errs() << " (for architecture " << ArchitectureName << ")";
std::string Buf;
raw_string_ostream OS(Buf);
logAllUnhandledErrors(std::move(E), OS);
OS.flush();
errs() << ": " << Buf << "\n";
}
namespace {
struct NMSymbol {
uint64_t Address;
uint64_t Size;
char TypeChar;
std::string Name;
StringRef SectionName;
StringRef TypeName;
BasicSymbolRef Sym;
// The Sym field above points to the native symbol in the object file,
// for Mach-O when we are creating symbols from the dyld info the above
// pointer is null as there is no native symbol. In these cases the fields
// below are filled in to represent what would have been a Mach-O nlist
// native symbol.
uint32_t SymFlags;
SectionRef Section;
uint8_t NType;
uint8_t NSect;
uint16_t NDesc;
std::string IndirectName;
};
} // anonymous namespace
static bool compareSymbolAddress(const NMSymbol &A, const NMSymbol &B) {
bool ADefined;
// Symbol flags have been checked in the caller.
if (A.Sym.getRawDataRefImpl().p) {
uint32_t AFlags = cantFail(A.Sym.getFlags());
ADefined = !(AFlags & SymbolRef::SF_Undefined);
} else {
ADefined = A.TypeChar != 'U';
}
bool BDefined;
// Symbol flags have been checked in the caller.
if (B.Sym.getRawDataRefImpl().p) {
uint32_t BFlags = cantFail(B.Sym.getFlags());
BDefined = !(BFlags & SymbolRef::SF_Undefined);
} else {
BDefined = B.TypeChar != 'U';
}
return std::make_tuple(ADefined, A.Address, A.Name, A.Size) <
std::make_tuple(BDefined, B.Address, B.Name, B.Size);
}
static bool compareSymbolSize(const NMSymbol &A, const NMSymbol &B) {
return std::make_tuple(A.Size, A.Name, A.Address) <
std::make_tuple(B.Size, B.Name, B.Address);
}
static bool compareSymbolName(const NMSymbol &A, const NMSymbol &B) {
return std::make_tuple(A.Name, A.Size, A.Address) <
std::make_tuple(B.Name, B.Size, B.Address);
}
static char isSymbolList64Bit(SymbolicFile &Obj) {
if (auto *IRObj = dyn_cast<IRObjectFile>(&Obj))
return Triple(IRObj->getTargetTriple()).isArch64Bit();
if (isa<COFFObjectFile>(Obj) || isa<COFFImportFile>(Obj))
return false;
if (isa<WasmObjectFile>(Obj))
return false;
if (TapiFile *Tapi = dyn_cast<TapiFile>(&Obj))
return Tapi->is64Bit();
if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(&Obj))
return MachO->is64Bit();
return cast<ELFObjectFileBase>(Obj).getBytesInAddress() == 8;
}
static StringRef CurrentFilename;
static std::vector<NMSymbol> SymbolList;
static char getSymbolNMTypeChar(IRObjectFile &Obj, basic_symbol_iterator I);
// darwinPrintSymbol() is used to print a symbol from a Mach-O file when the
// the OutputFormat is darwin or we are printing Mach-O symbols in hex. For
// the darwin format it produces the same output as darwin's nm(1) -m output
// and when printing Mach-O symbols in hex it produces the same output as
// darwin's nm(1) -x format.
static void darwinPrintSymbol(SymbolicFile &Obj, const NMSymbol &S,
char *SymbolAddrStr, const char *printBlanks,
const char *printDashes,
const char *printFormat) {
MachO::mach_header H;
MachO::mach_header_64 H_64;
uint32_t Filetype = MachO::MH_OBJECT;
uint32_t Flags = 0;
uint8_t NType = 0;
uint8_t NSect = 0;
uint16_t NDesc = 0;
uint32_t NStrx = 0;
uint64_t NValue = 0;
MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(&Obj);
if (Obj.isIR()) {
uint32_t SymFlags = cantFail(S.Sym.getFlags());
if (SymFlags & SymbolRef::SF_Global)
NType |= MachO::N_EXT;
if (SymFlags & SymbolRef::SF_Hidden)
NType |= MachO::N_PEXT;
if (SymFlags & SymbolRef::SF_Undefined)
NType |= MachO::N_EXT | MachO::N_UNDF;
else {
// Here we have a symbol definition. So to fake out a section name we
// use 1, 2 and 3 for section numbers. See below where they are used to
// print out fake section names.
NType |= MachO::N_SECT;
if (SymFlags & SymbolRef::SF_Const)
NSect = 3;
else if (SymFlags & SymbolRef::SF_Executable)
NSect = 1;
else
NSect = 2;
}
if (SymFlags & SymbolRef::SF_Weak)
NDesc |= MachO::N_WEAK_DEF;
} else {
DataRefImpl SymDRI = S.Sym.getRawDataRefImpl();
if (MachO->is64Bit()) {
H_64 = MachO->MachOObjectFile::getHeader64();
Filetype = H_64.filetype;
Flags = H_64.flags;
if (SymDRI.p){
MachO::nlist_64 STE_64 = MachO->getSymbol64TableEntry(SymDRI);
NType = STE_64.n_type;
NSect = STE_64.n_sect;
NDesc = STE_64.n_desc;
NStrx = STE_64.n_strx;
NValue = STE_64.n_value;
} else {
NType = S.NType;
NSect = S.NSect;
NDesc = S.NDesc;
NStrx = 0;
NValue = S.Address;
}
} else {
H = MachO->MachOObjectFile::getHeader();
Filetype = H.filetype;
Flags = H.flags;
if (SymDRI.p){
MachO::nlist STE = MachO->getSymbolTableEntry(SymDRI);
NType = STE.n_type;
NSect = STE.n_sect;
NDesc = STE.n_desc;
NStrx = STE.n_strx;
NValue = STE.n_value;
} else {
NType = S.NType;
NSect = S.NSect;
NDesc = S.NDesc;
NStrx = 0;
NValue = S.Address;
}
}
}
// If we are printing Mach-O symbols in hex do that and return.
if (FormatMachOasHex) {
outs() << format(printFormat, NValue) << ' '
<< format("%02x %02x %04x %08x", NType, NSect, NDesc, NStrx) << ' '
<< S.Name;
if ((NType & MachO::N_TYPE) == MachO::N_INDR) {
outs() << " (indirect for ";
outs() << format(printFormat, NValue) << ' ';
StringRef IndirectName;
if (S.Sym.getRawDataRefImpl().p) {
if (MachO->getIndirectName(S.Sym.getRawDataRefImpl(), IndirectName))
outs() << "?)";
else
outs() << IndirectName << ")";
} else
outs() << S.IndirectName << ")";
}
outs() << "\n";
return;
}
if (PrintAddress) {
if ((NType & MachO::N_TYPE) == MachO::N_INDR)
strcpy(SymbolAddrStr, printBlanks);
if (Obj.isIR() && (NType & MachO::N_TYPE) == MachO::N_TYPE)
strcpy(SymbolAddrStr, printDashes);
outs() << SymbolAddrStr << ' ';
}
switch (NType & MachO::N_TYPE) {
case MachO::N_UNDF:
if (NValue != 0) {
outs() << "(common) ";
if (MachO::GET_COMM_ALIGN(NDesc) != 0)
outs() << "(alignment 2^" << (int)MachO::GET_COMM_ALIGN(NDesc) << ") ";
} else {
if ((NType & MachO::N_TYPE) == MachO::N_PBUD)
outs() << "(prebound ";
else
outs() << "(";
if ((NDesc & MachO::REFERENCE_TYPE) ==
MachO::REFERENCE_FLAG_UNDEFINED_LAZY)
outs() << "undefined [lazy bound]) ";
else if ((NDesc & MachO::REFERENCE_TYPE) ==
MachO::REFERENCE_FLAG_PRIVATE_UNDEFINED_LAZY)
outs() << "undefined [private lazy bound]) ";
else if ((NDesc & MachO::REFERENCE_TYPE) ==
MachO::REFERENCE_FLAG_PRIVATE_UNDEFINED_NON_LAZY)
outs() << "undefined [private]) ";
else
outs() << "undefined) ";
}
break;
case MachO::N_ABS:
outs() << "(absolute) ";
break;
case MachO::N_INDR:
outs() << "(indirect) ";
break;
case MachO::N_SECT: {
if (Obj.isIR()) {
// For llvm bitcode files print out a fake section name using the values
// use 1, 2 and 3 for section numbers as set above.
if (NSect == 1)
outs() << "(LTO,CODE) ";
else if (NSect == 2)
outs() << "(LTO,DATA) ";
else if (NSect == 3)
outs() << "(LTO,RODATA) ";
else
outs() << "(?,?) ";
break;
}
section_iterator Sec = SectionRef();
if (S.Sym.getRawDataRefImpl().p) {
Expected<section_iterator> SecOrErr =
MachO->getSymbolSection(S.Sym.getRawDataRefImpl());
if (!SecOrErr) {
consumeError(SecOrErr.takeError());
outs() << "(?,?) ";
break;
}
Sec = *SecOrErr;
if (Sec == MachO->section_end()) {
outs() << "(?,?) ";
break;
}
} else {
Sec = S.Section;
}
DataRefImpl Ref = Sec->getRawDataRefImpl();
StringRef SectionName;
if (Expected<StringRef> NameOrErr = MachO->getSectionName(Ref))
SectionName = *NameOrErr;
StringRef SegmentName = MachO->getSectionFinalSegmentName(Ref);
outs() << "(" << SegmentName << "," << SectionName << ") ";
break;
}
default:
outs() << "(?) ";
break;
}
if (NType & MachO::N_EXT) {
if (NDesc & MachO::REFERENCED_DYNAMICALLY)
outs() << "[referenced dynamically] ";
if (NType & MachO::N_PEXT) {
if ((NDesc & MachO::N_WEAK_DEF) == MachO::N_WEAK_DEF)
outs() << "weak private external ";
else
outs() << "private external ";
} else {
if ((NDesc & MachO::N_WEAK_REF) == MachO::N_WEAK_REF ||
(NDesc & MachO::N_WEAK_DEF) == MachO::N_WEAK_DEF) {
if ((NDesc & (MachO::N_WEAK_REF | MachO::N_WEAK_DEF)) ==
(MachO::N_WEAK_REF | MachO::N_WEAK_DEF))
outs() << "weak external automatically hidden ";
else
outs() << "weak external ";
} else
outs() << "external ";
}
} else {
if (NType & MachO::N_PEXT)
outs() << "non-external (was a private external) ";
else
outs() << "non-external ";
}
if (Filetype == MachO::MH_OBJECT) {
if (NDesc & MachO::N_NO_DEAD_STRIP)
outs() << "[no dead strip] ";
if ((NType & MachO::N_TYPE) != MachO::N_UNDF &&
NDesc & MachO::N_SYMBOL_RESOLVER)
outs() << "[symbol resolver] ";
if ((NType & MachO::N_TYPE) != MachO::N_UNDF && NDesc & MachO::N_ALT_ENTRY)
outs() << "[alt entry] ";
if ((NType & MachO::N_TYPE) != MachO::N_UNDF && NDesc & MachO::N_COLD_FUNC)
outs() << "[cold func] ";
}
if ((NDesc & MachO::N_ARM_THUMB_DEF) == MachO::N_ARM_THUMB_DEF)
outs() << "[Thumb] ";
if ((NType & MachO::N_TYPE) == MachO::N_INDR) {
outs() << S.Name << " (for ";
StringRef IndirectName;
if (MachO) {
if (S.Sym.getRawDataRefImpl().p) {
if (MachO->getIndirectName(S.Sym.getRawDataRefImpl(), IndirectName))
outs() << "?)";
else
outs() << IndirectName << ")";
} else
outs() << S.IndirectName << ")";
} else
outs() << "?)";
} else
outs() << S.Name;
if ((Flags & MachO::MH_TWOLEVEL) == MachO::MH_TWOLEVEL &&
(((NType & MachO::N_TYPE) == MachO::N_UNDF && NValue == 0) ||
(NType & MachO::N_TYPE) == MachO::N_PBUD)) {
uint32_t LibraryOrdinal = MachO::GET_LIBRARY_ORDINAL(NDesc);
if (LibraryOrdinal != 0) {
if (LibraryOrdinal == MachO::EXECUTABLE_ORDINAL)
outs() << " (from executable)";
else if (LibraryOrdinal == MachO::DYNAMIC_LOOKUP_ORDINAL)
outs() << " (dynamically looked up)";
else {
StringRef LibraryName;
if (!MachO ||
MachO->getLibraryShortNameByIndex(LibraryOrdinal - 1, LibraryName))
outs() << " (from bad library ordinal " << LibraryOrdinal << ")";
else
outs() << " (from " << LibraryName << ")";
}
}
}
outs() << "\n";
}
// Table that maps Darwin's Mach-O stab constants to strings to allow printing.
struct DarwinStabName {
uint8_t NType;
const char *Name;
};
static const struct DarwinStabName DarwinStabNames[] = {
{MachO::N_GSYM, "GSYM"},
{MachO::N_FNAME, "FNAME"},
{MachO::N_FUN, "FUN"},
{MachO::N_STSYM, "STSYM"},
{MachO::N_LCSYM, "LCSYM"},
{MachO::N_BNSYM, "BNSYM"},
{MachO::N_PC, "PC"},
{MachO::N_AST, "AST"},
{MachO::N_OPT, "OPT"},
{MachO::N_RSYM, "RSYM"},
{MachO::N_SLINE, "SLINE"},
{MachO::N_ENSYM, "ENSYM"},
{MachO::N_SSYM, "SSYM"},
{MachO::N_SO, "SO"},
{MachO::N_OSO, "OSO"},
{MachO::N_LSYM, "LSYM"},
{MachO::N_BINCL, "BINCL"},
{MachO::N_SOL, "SOL"},
{MachO::N_PARAMS, "PARAM"},
{MachO::N_VERSION, "VERS"},
{MachO::N_OLEVEL, "OLEV"},
{MachO::N_PSYM, "PSYM"},
{MachO::N_EINCL, "EINCL"},
{MachO::N_ENTRY, "ENTRY"},
{MachO::N_LBRAC, "LBRAC"},
{MachO::N_EXCL, "EXCL"},
{MachO::N_RBRAC, "RBRAC"},
{MachO::N_BCOMM, "BCOMM"},
{MachO::N_ECOMM, "ECOMM"},
{MachO::N_ECOML, "ECOML"},
{MachO::N_LENG, "LENG"},
};
static const char *getDarwinStabString(uint8_t NType) {
for (auto I : makeArrayRef(DarwinStabNames))
if (I.NType == NType)
return I.Name;
return nullptr;
}
// darwinPrintStab() prints the n_sect, n_desc along with a symbolic name of
// a stab n_type value in a Mach-O file.
static void darwinPrintStab(MachOObjectFile *MachO, const NMSymbol &S) {
MachO::nlist_64 STE_64;
MachO::nlist STE;
uint8_t NType;
uint8_t NSect;
uint16_t NDesc;
DataRefImpl SymDRI = S.Sym.getRawDataRefImpl();
if (MachO->is64Bit()) {
STE_64 = MachO->getSymbol64TableEntry(SymDRI);
NType = STE_64.n_type;
NSect = STE_64.n_sect;
NDesc = STE_64.n_desc;
} else {
STE = MachO->getSymbolTableEntry(SymDRI);
NType = STE.n_type;
NSect = STE.n_sect;
NDesc = STE.n_desc;
}
outs() << format(" %02x %04x ", NSect, NDesc);
if (const char *stabString = getDarwinStabString(NType))
outs() << format("%5.5s", stabString);
else
outs() << format(" %02x", NType);
}
static Optional<std::string> demangle(StringRef Name, bool StripUnderscore) {
if (StripUnderscore && !Name.empty() && Name[0] == '_')
Name = Name.substr(1);
if (!Name.startswith("_Z"))
return None;
int Status;
char *Undecorated =
itaniumDemangle(Name.str().c_str(), nullptr, nullptr, &Status);
if (Status != 0)
return None;
std::string S(Undecorated);
free(Undecorated);
return S;
}
static bool symbolIsDefined(const NMSymbol &Sym) {
return Sym.TypeChar != 'U' && Sym.TypeChar != 'w' && Sym.TypeChar != 'v';
}
static void writeFileName(raw_ostream &S, StringRef ArchiveName,
StringRef ArchitectureName) {
if (!ArchitectureName.empty())
S << "(for architecture " << ArchitectureName << "):";
if (OutputFormat == posix && !ArchiveName.empty())
S << ArchiveName << "[" << CurrentFilename << "]: ";
else {
if (!ArchiveName.empty())
S << ArchiveName << ":";
S << CurrentFilename << ": ";
}
}
static void sortAndPrintSymbolList(SymbolicFile &Obj, bool printName,
StringRef ArchiveName,
StringRef ArchitectureName) {
if (!NoSort) {
using Comparator = bool (*)(const NMSymbol &, const NMSymbol &);
Comparator Cmp;
if (NumericSort)
Cmp = &compareSymbolAddress;
else if (SizeSort)
Cmp = &compareSymbolSize;
else
Cmp = &compareSymbolName;
if (ReverseSort)
llvm::sort(SymbolList, [=](const NMSymbol &A, const NMSymbol &B) -> bool {
return Cmp(B, A);
});
else
llvm::sort(SymbolList, Cmp);
}
if (!PrintFileName) {
if ((OutputFormat == bsd || OutputFormat == posix ||
OutputFormat == just_symbols) &&
MultipleFiles && printName) {
outs() << '\n' << CurrentFilename << ":\n";
} else if (OutputFormat == sysv) {
outs() << "\n\nSymbols from " << CurrentFilename << ":\n\n";
if (isSymbolList64Bit(Obj))
outs() << "Name Value Class Type"
<< " Size Line Section\n";
else
outs() << "Name Value Class Type"
<< " Size Line Section\n";
}
}
const char *printBlanks, *printDashes, *printFormat;
if (isSymbolList64Bit(Obj)) {
printBlanks = " ";
printDashes = "----------------";
switch (AddressRadix) {
case Radix::o:
printFormat = OutputFormat == posix ? "%" PRIo64 : "%016" PRIo64;
break;
case Radix::x:
printFormat = OutputFormat == posix ? "%" PRIx64 : "%016" PRIx64;
break;
default:
printFormat = OutputFormat == posix ? "%" PRId64 : "%016" PRId64;
}
} else {
printBlanks = " ";
printDashes = "--------";
switch (AddressRadix) {
case Radix::o:
printFormat = OutputFormat == posix ? "%" PRIo64 : "%08" PRIo64;
break;
case Radix::x:
printFormat = OutputFormat == posix ? "%" PRIx64 : "%08" PRIx64;
break;
default:
printFormat = OutputFormat == posix ? "%" PRId64 : "%08" PRId64;
}
}
for (const NMSymbol &S : SymbolList) {
uint32_t SymFlags;
std::string Name = S.Name;
MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(&Obj);
if (Demangle) {
if (Optional<std::string> Opt = demangle(S.Name, MachO))
Name = *Opt;
}
if (S.Sym.getRawDataRefImpl().p) {
Expected<uint32_t> SymFlagsOrErr = S.Sym.getFlags();
if (!SymFlagsOrErr) {
// TODO: Test this error.
error(SymFlagsOrErr.takeError(), Obj.getFileName());
return;
}
SymFlags = *SymFlagsOrErr;
} else
SymFlags = S.SymFlags;
bool Undefined = SymFlags & SymbolRef::SF_Undefined;
bool Global = SymFlags & SymbolRef::SF_Global;
bool Weak = SymFlags & SymbolRef::SF_Weak;
bool FormatSpecific = SymFlags & SymbolRef::SF_FormatSpecific;
if ((!Undefined && UndefinedOnly) || (Undefined && DefinedOnly) ||
(!Global && ExternalOnly) || (Weak && NoWeakSymbols) ||
(FormatSpecific && !(SpecialSyms || DebugSyms)))
continue;
if (PrintFileName)
writeFileName(outs(), ArchiveName, ArchitectureName);
if ((OutputFormat == just_symbols ||
(UndefinedOnly && MachO && OutputFormat != darwin)) &&
OutputFormat != posix) {
outs() << Name << "\n";
continue;
}
char SymbolAddrStr[23], SymbolSizeStr[23];
// If the format is SysV or the symbol isn't defined, then print spaces.
if (OutputFormat == sysv || !symbolIsDefined(S)) {
if (OutputFormat == posix) {
format(printFormat, S.Address)
.print(SymbolAddrStr, sizeof(SymbolAddrStr));
format(printFormat, S.Size).print(SymbolSizeStr, sizeof(SymbolSizeStr));
} else {
strcpy(SymbolAddrStr, printBlanks);
strcpy(SymbolSizeStr, printBlanks);
}
}
if (symbolIsDefined(S)) {
// Otherwise, print the symbol address and size.
if (Obj.isIR())
strcpy(SymbolAddrStr, printDashes);
else if (MachO && S.TypeChar == 'I')
strcpy(SymbolAddrStr, printBlanks);
else
format(printFormat, S.Address)
.print(SymbolAddrStr, sizeof(SymbolAddrStr));
format(printFormat, S.Size).print(SymbolSizeStr, sizeof(SymbolSizeStr));
}
// If OutputFormat is darwin or we are printing Mach-O symbols in hex and
// we have a MachOObjectFile, call darwinPrintSymbol to print as darwin's
// nm(1) -m output or hex, else if OutputFormat is darwin or we are
// printing Mach-O symbols in hex and not a Mach-O object fall back to
// OutputFormat bsd (see below).
if ((OutputFormat == darwin || FormatMachOasHex) && (MachO || Obj.isIR())) {
darwinPrintSymbol(Obj, S, SymbolAddrStr, printBlanks, printDashes,
printFormat);
} else if (OutputFormat == posix) {
outs() << Name << " " << S.TypeChar << " " << SymbolAddrStr << " "
<< (MachO ? "0" : SymbolSizeStr) << "\n";
} else if (OutputFormat == bsd || (OutputFormat == darwin && !MachO)) {
if (PrintAddress)
outs() << SymbolAddrStr << ' ';
if (PrintSize)
outs() << SymbolSizeStr << ' ';
outs() << S.TypeChar;
if (S.TypeChar == '-' && MachO)
darwinPrintStab(MachO, S);
outs() << " " << Name;
if (S.TypeChar == 'I' && MachO) {
outs() << " (indirect for ";
if (S.Sym.getRawDataRefImpl().p) {
StringRef IndirectName;
if (MachO->getIndirectName(S.Sym.getRawDataRefImpl(), IndirectName))
outs() << "?)";
else
outs() << IndirectName << ")";
} else
outs() << S.IndirectName << ")";
}
outs() << "\n";
} else if (OutputFormat == sysv) {
outs() << left_justify(Name, 20) << "|" << SymbolAddrStr << "| "
<< S.TypeChar << " |" << right_justify(S.TypeName, 18) << "|"
<< SymbolSizeStr << "| |" << S.SectionName << "\n";
}
}
SymbolList.clear();
}
static char getSymbolNMTypeChar(ELFObjectFileBase &Obj,
basic_symbol_iterator I) {
// OK, this is ELF
elf_symbol_iterator SymI(I);
Expected<elf_section_iterator> SecIOrErr = SymI->getSection();
if (!SecIOrErr) {
consumeError(SecIOrErr.takeError());
return '?';
}
uint8_t Binding = SymI->getBinding();
if (Binding == ELF::STB_GNU_UNIQUE)
return 'u';
assert(Binding != ELF::STB_WEAK && "STB_WEAK not tested in calling function");
if (Binding != ELF::STB_GLOBAL && Binding != ELF::STB_LOCAL)
return '?';
elf_section_iterator SecI = *SecIOrErr;
if (SecI != Obj.section_end()) {
uint32_t Type = SecI->getType();
uint64_t Flags = SecI->getFlags();
if (Flags & ELF::SHF_EXECINSTR)
return 't';
if (Type == ELF::SHT_NOBITS)
return 'b';
if (Flags & ELF::SHF_ALLOC)
return Flags & ELF::SHF_WRITE ? 'd' : 'r';
auto NameOrErr = SecI->getName();
if (!NameOrErr) {
consumeError(NameOrErr.takeError());
return '?';
}
if ((*NameOrErr).startswith(".debug"))
return 'N';
if (!(Flags & ELF::SHF_WRITE))
return 'n';
}
return '?';
}
static char getSymbolNMTypeChar(COFFObjectFile &Obj, symbol_iterator I) {
COFFSymbolRef Symb = Obj.getCOFFSymbol(*I);
// OK, this is COFF.
symbol_iterator SymI(I);
Expected<StringRef> Name = SymI->getName();
if (!Name) {
consumeError(Name.takeError());
return '?';
}
char Ret = StringSwitch<char>(*Name)
.StartsWith(".debug", 'N')
.StartsWith(".sxdata", 'N')
.Default('?');
if (Ret != '?')
return Ret;
uint32_t Characteristics = 0;
if (!COFF::isReservedSectionNumber(Symb.getSectionNumber())) {
Expected<section_iterator> SecIOrErr = SymI->getSection();
if (!SecIOrErr) {
consumeError(SecIOrErr.takeError());
return '?';
}
section_iterator SecI = *SecIOrErr;
const coff_section *Section = Obj.getCOFFSection(*SecI);
Characteristics = Section->Characteristics;
if (Expected<StringRef> NameOrErr = Obj.getSectionName(Section))
if (NameOrErr->startswith(".idata"))
return 'i';
}
switch (Symb.getSectionNumber()) {
case COFF::IMAGE_SYM_DEBUG:
return 'n';
default:
// Check section type.
if (Characteristics & COFF::IMAGE_SCN_CNT_CODE)
return 't';
if (Characteristics & COFF::IMAGE_SCN_CNT_INITIALIZED_DATA)
return Characteristics & COFF::IMAGE_SCN_MEM_WRITE ? 'd' : 'r';
if (Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA)
return 'b';
if (Characteristics & COFF::IMAGE_SCN_LNK_INFO)
return 'i';
// Check for section symbol.
if (Symb.isSectionDefinition())
return 's';
}
return '?';
}
static char getSymbolNMTypeChar(COFFImportFile &Obj) {
switch (Obj.getCOFFImportHeader()->getType()) {
case COFF::IMPORT_CODE:
return 't';
case COFF::IMPORT_DATA:
return 'd';
case COFF::IMPORT_CONST:
return 'r';
}
return '?';
}
static char getSymbolNMTypeChar(MachOObjectFile &Obj, basic_symbol_iterator I) {
DataRefImpl Symb = I->getRawDataRefImpl();
uint8_t NType = Obj.is64Bit() ? Obj.getSymbol64TableEntry(Symb).n_type
: Obj.getSymbolTableEntry(Symb).n_type;
if (NType & MachO::N_STAB)
return '-';
switch (NType & MachO::N_TYPE) {
case MachO::N_ABS:
return 's';
case MachO::N_INDR:
return 'i';
case MachO::N_SECT: {
Expected<section_iterator> SecOrErr = Obj.getSymbolSection(Symb);
if (!SecOrErr) {
consumeError(SecOrErr.takeError());
return 's';
}
section_iterator Sec = *SecOrErr;
if (Sec == Obj.section_end())
return 's';
DataRefImpl Ref = Sec->getRawDataRefImpl();
StringRef SectionName;
if (Expected<StringRef> NameOrErr = Obj.getSectionName(Ref))
SectionName = *NameOrErr;
StringRef SegmentName = Obj.getSectionFinalSegmentName(Ref);
if (Obj.is64Bit() && Obj.getHeader64().filetype == MachO::MH_KEXT_BUNDLE &&
SegmentName == "__TEXT_EXEC" && SectionName == "__text")
return 't';
if (SegmentName == "__TEXT" && SectionName == "__text")
return 't';
if (SegmentName == "__DATA" && SectionName == "__data")
return 'd';
if (SegmentName == "__DATA" && SectionName == "__bss")
return 'b';
return 's';
}
}
return '?';
}
static char getSymbolNMTypeChar(TapiFile &Obj, basic_symbol_iterator I) {
return 's';
}
static char getSymbolNMTypeChar(WasmObjectFile &Obj, basic_symbol_iterator I) {
uint32_t Flags = cantFail(I->getFlags());
if (Flags & SymbolRef::SF_Executable)
return 't';
return 'd';
}
static char getSymbolNMTypeChar(IRObjectFile &Obj, basic_symbol_iterator I) {
uint32_t Flags = cantFail(I->getFlags());
// FIXME: should we print 'b'? At the IR level we cannot be sure if this
// will be in bss or not, but we could approximate.
if (Flags & SymbolRef::SF_Executable)
return 't';
else if (Triple(Obj.getTargetTriple()).isOSDarwin() &&
(Flags & SymbolRef::SF_Const))
return 's';
else
return 'd';
}
static bool isObject(SymbolicFile &Obj, basic_symbol_iterator I) {
return isa<ELFObjectFileBase>(&Obj) &&
elf_symbol_iterator(I)->getELFType() == ELF::STT_OBJECT;
}
// For ELF object files, Set TypeName to the symbol typename, to be printed
// in the 'Type' column of the SYSV format output.
static StringRef getNMTypeName(SymbolicFile &Obj, basic_symbol_iterator I) {
if (isa<ELFObjectFileBase>(&Obj)) {
elf_symbol_iterator SymI(I);
return SymI->getELFTypeName();
}
return "";
}
// Return Posix nm class type tag (single letter), but also set SecName and
// section and name, to be used in format=sysv output.
static char getNMSectionTagAndName(SymbolicFile &Obj, basic_symbol_iterator I,
StringRef &SecName) {
// Symbol Flags have been checked in the caller.
uint32_t Symflags = cantFail(I->getFlags());
if (ELFObjectFileBase *ELFObj = dyn_cast<ELFObjectFileBase>(&Obj)) {
if (Symflags & object::SymbolRef::SF_Absolute)
SecName = "*ABS*";
else if (Symflags & object::SymbolRef::SF_Common)
SecName = "*COM*";
else if (Symflags & object::SymbolRef::SF_Undefined)
SecName = "*UND*";
else {
elf_symbol_iterator SymI(I);
Expected<elf_section_iterator> SecIOrErr = SymI->getSection();
if (!SecIOrErr) {
consumeError(SecIOrErr.takeError());
return '?';
}
if (*SecIOrErr == ELFObj->section_end())
return '?';
Expected<StringRef> NameOrErr = (*SecIOrErr)->getName();
if (!NameOrErr) {
consumeError(NameOrErr.takeError());
return '?';
}
SecName = *NameOrErr;
}
}
if (Symflags & object::SymbolRef::SF_Undefined) {
if (isa<MachOObjectFile>(Obj) || !(Symflags & object::SymbolRef::SF_Weak))
return 'U';
return isObject(Obj, I) ? 'v' : 'w';
}
if (isa<ELFObjectFileBase>(&Obj))
if (ELFSymbolRef(*I).getELFType() == ELF::STT_GNU_IFUNC)
return 'i';
if (!isa<MachOObjectFile>(Obj) && (Symflags & object::SymbolRef::SF_Weak))
return isObject(Obj, I) ? 'V' : 'W';
if (Symflags & object::SymbolRef::SF_Common)
return 'C';
char Ret = '?';
if (Symflags & object::SymbolRef::SF_Absolute)
Ret = 'a';
else if (IRObjectFile *IR = dyn_cast<IRObjectFile>(&Obj))
Ret = getSymbolNMTypeChar(*IR, I);
else if (COFFObjectFile *COFF = dyn_cast<COFFObjectFile>(&Obj))
Ret = getSymbolNMTypeChar(*COFF, I);
else if (COFFImportFile *COFFImport = dyn_cast<COFFImportFile>(&Obj))
Ret = getSymbolNMTypeChar(*COFFImport);
else if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(&Obj))
Ret = getSymbolNMTypeChar(*MachO, I);
else if (WasmObjectFile *Wasm = dyn_cast<WasmObjectFile>(&Obj))
Ret = getSymbolNMTypeChar(*Wasm, I);
else if (TapiFile *Tapi = dyn_cast<TapiFile>(&Obj))
Ret = getSymbolNMTypeChar(*Tapi, I);
else if (ELFObjectFileBase *ELF = dyn_cast<ELFObjectFileBase>(&Obj)) {
Ret = getSymbolNMTypeChar(*ELF, I);
if (ELFSymbolRef(*I).getBinding() == ELF::STB_GNU_UNIQUE)
return Ret;
} else
llvm_unreachable("unknown binary format");
if (!(Symflags & object::SymbolRef::SF_Global))
return Ret;
return toupper(Ret);
}
// getNsectForSegSect() is used to implement the Mach-O "-s segname sectname"
// option to dump only those symbols from that section in a Mach-O file.
// It is called once for each Mach-O file from dumpSymbolNamesFromObject()
// to get the section number for that named section from the command line
// arguments. It returns the section number for that section in the Mach-O
// file or zero it is not present.
static unsigned getNsectForSegSect(MachOObjectFile *Obj) {
unsigned Nsect = 1;
for (auto &S : Obj->sections()) {
DataRefImpl Ref = S.getRawDataRefImpl();
StringRef SectionName;
if (Expected<StringRef> NameOrErr = Obj->getSectionName(Ref))
SectionName = *NameOrErr;
StringRef SegmentName = Obj->getSectionFinalSegmentName(Ref);
if (SegmentName == SegSect[0] && SectionName == SegSect[1])
return Nsect;
Nsect++;
}
return 0;
}
// getNsectInMachO() is used to implement the Mach-O "-s segname sectname"
// option to dump only those symbols from that section in a Mach-O file.
// It is called once for each symbol in a Mach-O file from
// dumpSymbolNamesFromObject() and returns the section number for that symbol
// if it is in a section, else it returns 0.
static unsigned getNsectInMachO(MachOObjectFile &Obj, BasicSymbolRef Sym) {
DataRefImpl Symb = Sym.getRawDataRefImpl();
if (Obj.is64Bit()) {
MachO::nlist_64 STE = Obj.getSymbol64TableEntry(Symb);
return (STE.n_type & MachO::N_TYPE) == MachO::N_SECT ? STE.n_sect : 0;
}
MachO::nlist STE = Obj.getSymbolTableEntry(Symb);
return (STE.n_type & MachO::N_TYPE) == MachO::N_SECT ? STE.n_sect : 0;
}
static void dumpSymbolsFromDLInfoMachO(MachOObjectFile &MachO) {
size_t I = SymbolList.size();
std::string ExportsNameBuffer;
raw_string_ostream EOS(ExportsNameBuffer);
std::string BindsNameBuffer;
raw_string_ostream BOS(BindsNameBuffer);
std::string LazysNameBuffer;
raw_string_ostream LOS(LazysNameBuffer);
std::string WeaksNameBuffer;
raw_string_ostream WOS(WeaksNameBuffer);
std::string FunctionStartsNameBuffer;
raw_string_ostream FOS(FunctionStartsNameBuffer);
MachO::mach_header H;
MachO::mach_header_64 H_64;
uint32_t HFlags = 0;
if (MachO.is64Bit()) {
H_64 = MachO.MachOObjectFile::getHeader64();
HFlags = H_64.flags;
} else {
H = MachO.MachOObjectFile::getHeader();
HFlags = H.flags;
}
uint64_t BaseSegmentAddress = 0;
for (const auto &Command : MachO.load_commands()) {
if (Command.C.cmd == MachO::LC_SEGMENT) {
MachO::segment_command Seg = MachO.getSegmentLoadCommand(Command);
if (Seg.fileoff == 0 && Seg.filesize != 0) {
BaseSegmentAddress = Seg.vmaddr;
break;
}
} else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
MachO::segment_command_64 Seg = MachO.getSegment64LoadCommand(Command);
if (Seg.fileoff == 0 && Seg.filesize != 0) {
BaseSegmentAddress = Seg.vmaddr;
break;
}
}
}
if (DyldInfoOnly || AddDyldInfo ||
HFlags & MachO::MH_NLIST_OUTOFSYNC_WITH_DYLDINFO) {
unsigned ExportsAdded = 0;
Error Err = Error::success();
for (const llvm::object::ExportEntry &Entry : MachO.exports(Err)) {
bool found = false;
bool ReExport = false;
if (!DyldInfoOnly) {
for (const NMSymbol &S : SymbolList)
if (S.Address == Entry.address() + BaseSegmentAddress &&
S.Name == Entry.name()) {
found = true;
break;
}
}
if (!found) {
NMSymbol S = {};
S.Address = Entry.address() + BaseSegmentAddress;
S.Size = 0;
S.TypeChar = '\0';
S.Name = Entry.name().str();
// There is no symbol in the nlist symbol table for this so we set
// Sym effectivly to null and the rest of code in here must test for
// it and not do things like Sym.getFlags() for it.
S.Sym = BasicSymbolRef();
S.SymFlags = SymbolRef::SF_Global;
S.Section = SectionRef();
S.NType = 0;
S.NSect = 0;
S.NDesc = 0;
uint64_t EFlags = Entry.flags();
bool Abs = ((EFlags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
MachO::EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE);
bool Resolver = (EFlags & MachO::EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER);
ReExport = (EFlags & MachO::EXPORT_SYMBOL_FLAGS_REEXPORT);
bool WeakDef = (EFlags & MachO::EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION);
if (WeakDef)
S.NDesc |= MachO::N_WEAK_DEF;
if (Abs) {
S.NType = MachO::N_EXT | MachO::N_ABS;
S.TypeChar = 'A';
} else if (ReExport) {
S.NType = MachO::N_EXT | MachO::N_INDR;
S.TypeChar = 'I';
} else {
S.NType = MachO::N_EXT | MachO::N_SECT;
if (Resolver) {
S.Address = Entry.other() + BaseSegmentAddress;
if ((S.Address & 1) != 0 && !MachO.is64Bit() &&
H.cputype == MachO::CPU_TYPE_ARM) {
S.Address &= ~1LL;
S.NDesc |= MachO::N_ARM_THUMB_DEF;
}
} else {
S.Address = Entry.address() + BaseSegmentAddress;
}
StringRef SegmentName = StringRef();
StringRef SectionName = StringRef();
for (const SectionRef &Section : MachO.sections()) {
S.NSect++;
if (Expected<StringRef> NameOrErr = Section.getName())
SectionName = *NameOrErr;
else
consumeError(NameOrErr.takeError());
SegmentName =
MachO.getSectionFinalSegmentName(Section.getRawDataRefImpl());
if (S.Address >= Section.getAddress() &&
S.Address < Section.getAddress() + Section.getSize()) {
S.Section = Section;
break;
} else if (Entry.name() == "__mh_execute_header" &&
SegmentName == "__TEXT" && SectionName == "__text") {
S.Section = Section;
S.NDesc |= MachO::REFERENCED_DYNAMICALLY;
break;
}
}
if (SegmentName == "__TEXT" && SectionName == "__text")
S.TypeChar = 'T';
else if (SegmentName == "__DATA" && SectionName == "__data")
S.TypeChar = 'D';
else if (SegmentName == "__DATA" && SectionName == "__bss")
S.TypeChar = 'B';
else
S.TypeChar = 'S';
}
SymbolList.push_back(S);
EOS << Entry.name();
EOS << '\0';
ExportsAdded++;
// For ReExports there are a two more things to do, first add the
// indirect name and second create the undefined symbol using the
// referened dynamic library.
if (ReExport) {
// Add the indirect name.
if (Entry.otherName().empty())
EOS << Entry.name();
else
EOS << Entry.otherName();
EOS << '\0';
// Now create the undefined symbol using the referened dynamic
// library.
NMSymbol U = {};
U.Address = 0;
U.Size = 0;
U.TypeChar = 'U';
if (Entry.otherName().empty())
U.Name = Entry.name().str();
else
U.Name = Entry.otherName().str();
// Again there is no symbol in the nlist symbol table for this so
// we set Sym effectivly to null and the rest of code in here must
// test for it and not do things like Sym.getFlags() for it.
U.Sym = BasicSymbolRef();
U.SymFlags = SymbolRef::SF_Global | SymbolRef::SF_Undefined;
U.Section = SectionRef();
U.NType = MachO::N_EXT | MachO::N_UNDF;
U.NSect = 0;
U.NDesc = 0;
// The library ordinal for this undefined symbol is in the export
// trie Entry.other().
MachO::SET_LIBRARY_ORDINAL(U.NDesc, Entry.other());
SymbolList.push_back(U);
// Finally add the undefined symbol's name.
if (Entry.otherName().empty())
EOS << Entry.name();
else
EOS << Entry.otherName();
EOS << '\0';
ExportsAdded++;
}
}
}
if (Err)
error(std::move(Err), MachO.getFileName());
// Set the symbol names and indirect names for the added symbols.
if (ExportsAdded) {
EOS.flush();
const char *Q = ExportsNameBuffer.c_str();
for (unsigned K = 0; K < ExportsAdded; K++) {
SymbolList[I].Name = Q;
Q += strlen(Q) + 1;
if (SymbolList[I].TypeChar == 'I') {
SymbolList[I].IndirectName = Q;
Q += strlen(Q) + 1;
}
I++;
}
}
// Add the undefined symbols from the bind entries.
unsigned BindsAdded = 0;
Error BErr = Error::success();
StringRef LastSymbolName = StringRef();
for (const llvm::object::MachOBindEntry &Entry : MachO.bindTable(BErr)) {
bool found = false;
if (LastSymbolName == Entry.symbolName())
found = true;
else if (!DyldInfoOnly) {
for (unsigned J = 0; J < SymbolList.size() && !found; ++J) {
if (SymbolList[J].Name == Entry.symbolName())
found = true;
}
}
if (!found) {
LastSymbolName = Entry.symbolName();
NMSymbol B = {};
B.Address = 0;
B.Size = 0;
B.TypeChar = 'U';
// There is no symbol in the nlist symbol table for this so we set
// Sym effectivly to null and the rest of code in here must test for
// it and not do things like Sym.getFlags() for it.
B.Sym = BasicSymbolRef();
B.SymFlags = SymbolRef::SF_Global | SymbolRef::SF_Undefined;
B.NType = MachO::N_EXT | MachO::N_UNDF;
B.NSect = 0;
B.NDesc = 0;
MachO::SET_LIBRARY_ORDINAL(B.NDesc, Entry.ordinal());
B.Name = Entry.symbolName().str();
SymbolList.push_back(B);
BOS << Entry.symbolName();
BOS << '\0';
BindsAdded++;
}
}
if (BErr)
error(std::move(BErr), MachO.getFileName());
// Set the symbol names and indirect names for the added symbols.
if (BindsAdded) {
BOS.flush();
const char *Q = BindsNameBuffer.c_str();
for (unsigned K = 0; K < BindsAdded; K++) {
SymbolList[I].Name = Q;
Q += strlen(Q) + 1;
if (SymbolList[I].TypeChar == 'I') {
SymbolList[I].IndirectName = Q;
Q += strlen(Q) + 1;
}
I++;
}
}
// Add the undefined symbols from the lazy bind entries.
unsigned LazysAdded = 0;
Error LErr = Error::success();
LastSymbolName = StringRef();
for (const llvm::object::MachOBindEntry &Entry :
MachO.lazyBindTable(LErr)) {
bool found = false;
if (LastSymbolName == Entry.symbolName())
found = true;
else {
// Here we must check to see it this symbol is already in the
// SymbolList as it might have already have been added above via a
// non-lazy (bind) entry.
for (unsigned J = 0; J < SymbolList.size() && !found; ++J) {
if (SymbolList[J].Name == Entry.symbolName())
found = true;
}
}
if (!found) {
LastSymbolName = Entry.symbolName();
NMSymbol L = {};
L.Name = Entry.symbolName().str();
L.Address = 0;
L.Size = 0;
L.TypeChar = 'U';
// There is no symbol in the nlist symbol table for this so we set
// Sym effectivly to null and the rest of code in here must test for
// it and not do things like Sym.getFlags() for it.
L.Sym = BasicSymbolRef();
L.SymFlags = SymbolRef::SF_Global | SymbolRef::SF_Undefined;
L.NType = MachO::N_EXT | MachO::N_UNDF;
L.NSect = 0;
// The REFERENCE_FLAG_UNDEFINED_LAZY is no longer used but here it
// makes sence since we are creating this from a lazy bind entry.
L.NDesc = MachO::REFERENCE_FLAG_UNDEFINED_LAZY;
MachO::SET_LIBRARY_ORDINAL(L.NDesc, Entry.ordinal());
SymbolList.push_back(L);
LOS << Entry.symbolName();
LOS << '\0';
LazysAdded++;
}
}
if (LErr)
error(std::move(LErr), MachO.getFileName());
// Set the symbol names and indirect names for the added symbols.
if (LazysAdded) {
LOS.flush();
const char *Q = LazysNameBuffer.c_str();
for (unsigned K = 0; K < LazysAdded; K++) {
SymbolList[I].Name = Q;
Q += strlen(Q) + 1;
if (SymbolList[I].TypeChar == 'I') {
SymbolList[I].IndirectName = Q;
Q += strlen(Q) + 1;
}
I++;
}
}
// Add the undefineds symbol from the weak bind entries which are not
// strong symbols.
unsigned WeaksAdded = 0;
Error WErr = Error::success();
LastSymbolName = StringRef();
for (const llvm::object::MachOBindEntry &Entry :
MachO.weakBindTable(WErr)) {
bool found = false;
unsigned J = 0;
if (LastSymbolName == Entry.symbolName() ||
Entry.flags() & MachO::BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION) {
found = true;
} else {
for (J = 0; J < SymbolList.size() && !found; ++J) {
if (SymbolList[J].Name == Entry.symbolName()) {
found = true;
break;
}
}
}
if (!found) {
LastSymbolName = Entry.symbolName();
NMSymbol W = {};
W.Name = Entry.symbolName().str();
W.Address = 0;
W.Size = 0;
W.TypeChar = 'U';
// There is no symbol in the nlist symbol table for this so we set
// Sym effectivly to null and the rest of code in here must test for
// it and not do things like Sym.getFlags() for it.
W.Sym = BasicSymbolRef();
W.SymFlags = SymbolRef::SF_Global | SymbolRef::SF_Undefined;
W.NType = MachO::N_EXT | MachO::N_UNDF;
W.NSect = 0;
// Odd that we are using N_WEAK_DEF on an undefined symbol but that is
// what is created in this case by the linker when there are real
// symbols in the nlist structs.
W.NDesc = MachO::N_WEAK_DEF;
SymbolList.push_back(W);
WOS << Entry.symbolName();
WOS << '\0';
WeaksAdded++;
} else {
// This is the case the symbol was previously been found and it could
// have been added from a bind or lazy bind symbol. If so and not
// a definition also mark it as weak.
if (SymbolList[J].TypeChar == 'U')
// See comment above about N_WEAK_DEF.
SymbolList[J].NDesc |= MachO::N_WEAK_DEF;
}
}
if (WErr)
error(std::move(WErr), MachO.getFileName());
// Set the symbol names and indirect names for the added symbols.
if (WeaksAdded) {
WOS.flush();
const char *Q = WeaksNameBuffer.c_str();
for (unsigned K = 0; K < WeaksAdded; K++) {
SymbolList[I].Name = Q;
Q += strlen(Q) + 1;
if (SymbolList[I].TypeChar == 'I') {
SymbolList[I].IndirectName = Q;
Q += strlen(Q) + 1;
}
I++;
}
}
// Trying adding symbol from the function starts table and LC_MAIN entry
// point.
SmallVector<uint64_t, 8> FoundFns;
uint64_t lc_main_offset = UINT64_MAX;
for (const auto &Command : MachO.load_commands()) {
if (Command.C.cmd == MachO::LC_FUNCTION_STARTS) {
// We found a function starts segment, parse the addresses for
// consumption.
MachO::linkedit_data_command LLC =
MachO.getLinkeditDataLoadCommand(Command);
MachO.ReadULEB128s(LLC.dataoff, FoundFns);
} else if (Command.C.cmd == MachO::LC_MAIN) {
MachO::entry_point_command LCmain = MachO.getEntryPointCommand(Command);
lc_main_offset = LCmain.entryoff;
}
}
// See if these addresses are already in the symbol table.
unsigned FunctionStartsAdded = 0;
for (uint64_t f = 0; f < FoundFns.size(); f++) {
bool found = false;
for (unsigned J = 0; J < SymbolList.size() && !found; ++J) {
if (SymbolList[J].Address == FoundFns[f] + BaseSegmentAddress)
found = true;
}
// See this address is not already in the symbol table fake up an
// nlist for it.
if (!found) {
NMSymbol F = {};
F.Name = "<redacted function X>";
F.Address = FoundFns[f] + BaseSegmentAddress;
F.Size = 0;
// There is no symbol in the nlist symbol table for this so we set
// Sym effectivly to null and the rest of code in here must test for
// it and not do things like Sym.getFlags() for it.
F.Sym = BasicSymbolRef();
F.SymFlags = 0;
F.NType = MachO::N_SECT;
F.NSect = 0;
StringRef SegmentName = StringRef();
StringRef SectionName = StringRef();
for (const SectionRef &Section : MachO.sections()) {
if (Expected<StringRef> NameOrErr = Section.getName())
SectionName = *NameOrErr;
else
consumeError(NameOrErr.takeError());
SegmentName =
MachO.getSectionFinalSegmentName(Section.getRawDataRefImpl());
F.NSect++;
if (F.Address >= Section.getAddress() &&
F.Address < Section.getAddress() + Section.getSize()) {
F.Section = Section;
break;
}
}
if (SegmentName == "__TEXT" && SectionName == "__text")
F.TypeChar = 't';
else if (SegmentName == "__DATA" && SectionName == "__data")
F.TypeChar = 'd';
else if (SegmentName == "__DATA" && SectionName == "__bss")
F.TypeChar = 'b';
else
F.TypeChar = 's';
F.NDesc = 0;
SymbolList.push_back(F);
if (FoundFns[f] == lc_main_offset)
FOS << "<redacted LC_MAIN>";
else
FOS << "<redacted function " << f << ">";
FOS << '\0';
FunctionStartsAdded++;
}
}
if (FunctionStartsAdded) {
FOS.flush();
const char *Q = FunctionStartsNameBuffer.c_str();
for (unsigned K = 0; K < FunctionStartsAdded; K++) {
SymbolList[I].Name = Q;
Q += strlen(Q) + 1;
if (SymbolList[I].TypeChar == 'I') {
SymbolList[I].IndirectName = Q;
Q += strlen(Q) + 1;
}
I++;
}
}
}
}
static void dumpSymbolNamesFromObject(SymbolicFile &Obj, bool printName,
StringRef ArchiveName = {},
StringRef ArchitectureName = {}) {
auto Symbols = Obj.symbols();
std::vector<VersionEntry> SymbolVersions;
if (DynamicSyms) {
const auto *E = dyn_cast<ELFObjectFileBase>(&Obj);
if (!E) {
error("File format has no dynamic symbol table", Obj.getFileName());
return;
}
Symbols = E->getDynamicSymbolIterators();
if (Expected<std::vector<VersionEntry>> VersionsOrErr =
E->readDynsymVersions())
SymbolVersions = std::move(*VersionsOrErr);
else
WithColor::warning(errs(), ToolName)
<< "unable to read symbol versions: "
<< toString(VersionsOrErr.takeError()) << "\n";
}
// If a "-s segname sectname" option was specified and this is a Mach-O
// file get the section number for that section in this object file.
unsigned int Nsect = 0;
MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(&Obj);
if (!SegSect.empty() && MachO) {
Nsect = getNsectForSegSect(MachO);
// If this section is not in the object file no symbols are printed.
if (Nsect == 0)
return;
}
if (!(MachO && DyldInfoOnly)) {
size_t I = -1;
for (BasicSymbolRef Sym : Symbols) {
++I;
Expected<uint32_t> SymFlagsOrErr = Sym.getFlags();
if (!SymFlagsOrErr) {
error(SymFlagsOrErr.takeError(), Obj.getFileName());
return;
}
// Don't drop format specifc symbols for ARM and AArch64 ELF targets, they
// are used to repesent mapping symbols and needed to honor the
// --special-syms option.
auto *ELFObj = dyn_cast<ELFObjectFileBase>(&Obj);
if ((!ELFObj || (ELFObj->getEMachine() != ELF::EM_ARM &&
ELFObj->getEMachine() != ELF::EM_AARCH64)) &&
!DebugSyms && (*SymFlagsOrErr & SymbolRef::SF_FormatSpecific))
continue;
if (WithoutAliases && (*SymFlagsOrErr & SymbolRef::SF_Indirect))
continue;
// If a "-s segname sectname" option was specified and this is a Mach-O
// file and this section appears in this file, Nsect will be non-zero then
// see if this symbol is a symbol from that section and if not skip it.
if (Nsect && Nsect != getNsectInMachO(*MachO, Sym))
continue;
NMSymbol S = {};
S.Size = 0;
S.Address = 0;
if (isa<ELFObjectFileBase>(&Obj))
S.Size = ELFSymbolRef(Sym).getSize();
if (PrintAddress && isa<ObjectFile>(Obj)) {
SymbolRef SymRef(Sym);
Expected<uint64_t> AddressOrErr = SymRef.getAddress();
if (!AddressOrErr) {
consumeError(AddressOrErr.takeError());
break;
}
S.Address = *AddressOrErr;
}
S.TypeName = getNMTypeName(Obj, Sym);
S.TypeChar = getNMSectionTagAndName(Obj, Sym, S.SectionName);
raw_string_ostream OS(S.Name);
if (Error E = Sym.printName(OS)) {
if (MachO) {
OS << "bad string index";
consumeError(std::move(E));
} else
error(std::move(E), Obj.getFileName());
}
if (!SymbolVersions.empty() && !SymbolVersions[I].Name.empty())
S.Name +=
(SymbolVersions[I].IsVerDef ? "@@" : "@") + SymbolVersions[I].Name;
S.Sym = Sym;
SymbolList.push_back(S);
}
}
// If this is a Mach-O file where the nlist symbol table is out of sync
// with the dyld export trie then look through exports and fake up symbols
// for the ones that are missing (also done with the -add-dyldinfo flag).
// This is needed if strip(1) -T is run on a binary containing swift
// language symbols for example. The option -only-dyldinfo will fake up
// all symbols from the dyld export trie as well as the bind info.
if (MachO && !NoDyldInfo)
dumpSymbolsFromDLInfoMachO(*MachO);
CurrentFilename = Obj.getFileName();
if (Symbols.empty() && SymbolList.empty() && !Quiet) {
writeFileName(errs(), ArchiveName, ArchitectureName);
errs() << "no symbols\n";
}
sortAndPrintSymbolList(Obj, printName, ArchiveName, ArchitectureName);
}
// checkMachOAndArchFlags() checks to see if the SymbolicFile is a Mach-O file
// and if it is and there is a list of architecture flags is specified then
// check to make sure this Mach-O file is one of those architectures or all
// architectures was specificed. If not then an error is generated and this
// routine returns false. Else it returns true.
static bool checkMachOAndArchFlags(SymbolicFile *O, std::string &Filename) {
auto *MachO = dyn_cast<MachOObjectFile>(O);
if (!MachO || ArchAll || ArchFlags.empty())
return true;
MachO::mach_header H;
MachO::mach_header_64 H_64;
Triple T;
const char *McpuDefault, *ArchFlag;
if (MachO->is64Bit()) {
H_64 = MachO->MachOObjectFile::getHeader64();
T = MachOObjectFile::getArchTriple(H_64.cputype, H_64.cpusubtype,
&McpuDefault, &ArchFlag);
} else {
H = MachO->MachOObjectFile::getHeader();
T = MachOObjectFile::getArchTriple(H.cputype, H.cpusubtype,
&McpuDefault, &ArchFlag);
}
const std::string ArchFlagName(ArchFlag);
if (!llvm::is_contained(ArchFlags, ArchFlagName)) {
error("No architecture specified", Filename);
return false;
}
return true;
}
static void dumpSymbolNamesFromFile(std::string &Filename) {
ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
MemoryBuffer::getFileOrSTDIN(Filename);
if (error(BufferOrErr.getError(), Filename))
return;
LLVMContext Context;
LLVMContext *ContextPtr = NoLLVMBitcode ? nullptr : &Context;
Expected<std::unique_ptr<Binary>> BinaryOrErr =
createBinary(BufferOrErr.get()->getMemBufferRef(), ContextPtr);
if (!BinaryOrErr) {
error(BinaryOrErr.takeError(), Filename);
return;
}
Binary &Bin = *BinaryOrErr.get();
if (Archive *A = dyn_cast<Archive>(&Bin)) {
if (ArchiveMap) {
Archive::symbol_iterator I = A->symbol_begin();
Archive::symbol_iterator E = A->symbol_end();
if (I != E) {
outs() << "Archive map\n";
for (; I != E; ++I) {
Expected<Archive::Child> C = I->getMember();
if (!C) {
error(C.takeError(), Filename);
break;
}
Expected<StringRef> FileNameOrErr = C->getName();
if (!FileNameOrErr) {
error(FileNameOrErr.takeError(), Filename);
break;
}
StringRef SymName = I->getName();
outs() << SymName << " in " << FileNameOrErr.get() << "\n";
}
outs() << "\n";
}
}
{
Error Err = Error::success();
for (auto &C : A->children(Err)) {
Expected<std::unique_ptr<Binary>> ChildOrErr =
C.getAsBinary(ContextPtr);
if (!ChildOrErr) {
if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
error(std::move(E), Filename, C);
continue;
}
if (SymbolicFile *O = dyn_cast<SymbolicFile>(&*ChildOrErr.get())) {
if (!MachOPrintSizeWarning && PrintSize && isa<MachOObjectFile>(O)) {
WithColor::warning(errs(), ToolName)
<< "sizes with -print-size for Mach-O files are always zero.\n";
MachOPrintSizeWarning = true;
}
if (!checkMachOAndArchFlags(O, Filename))
return;
if (!PrintFileName) {
outs() << "\n";
if (isa<MachOObjectFile>(O)) {
outs() << Filename << "(" << O->getFileName() << ")";
} else
outs() << O->getFileName();
outs() << ":\n";
}
dumpSymbolNamesFromObject(*O, false, Filename);
}
}
if (Err)
error(std::move(Err), A->getFileName());
}
return;
}
if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin)) {
// If we have a list of architecture flags specified dump only those.
if (!ArchAll && !ArchFlags.empty()) {
// Look for a slice in the universal binary that matches each ArchFlag.
bool ArchFound;
for (unsigned i = 0; i < ArchFlags.size(); ++i) {
ArchFound = false;
for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
E = UB->end_objects();
I != E; ++I) {
if (ArchFlags[i] == I->getArchFlagName()) {
ArchFound = true;
Expected<std::unique_ptr<ObjectFile>> ObjOrErr =
I->getAsObjectFile();
std::string ArchiveName;
std::string ArchitectureName;
ArchiveName.clear();
ArchitectureName.clear();
if (ObjOrErr) {
ObjectFile &Obj = *ObjOrErr.get();
if (ArchFlags.size() > 1) {
if (PrintFileName)
ArchitectureName = I->getArchFlagName();
else
outs() << "\n" << Obj.getFileName() << " (for architecture "
<< I->getArchFlagName() << ")"
<< ":\n";
}
dumpSymbolNamesFromObject(Obj, false, ArchiveName,
ArchitectureName);
} else if (auto E = isNotObjectErrorInvalidFileType(
ObjOrErr.takeError())) {
error(std::move(E), Filename, ArchFlags.size() > 1 ?
StringRef(I->getArchFlagName()) : StringRef());
continue;
} else if (Expected<std::unique_ptr<Archive>> AOrErr =
I->getAsArchive()) {
std::unique_ptr<Archive> &A = *AOrErr;
Error Err = Error::success();
for (auto &C : A->children(Err)) {
Expected<std::unique_ptr<Binary>> ChildOrErr =
C.getAsBinary(ContextPtr);
if (!ChildOrErr) {
if (auto E = isNotObjectErrorInvalidFileType(
ChildOrErr.takeError())) {
error(std::move(E), Filename, C, ArchFlags.size() > 1 ?
StringRef(I->getArchFlagName()) : StringRef());
}
continue;
}
if (SymbolicFile *O =
dyn_cast<SymbolicFile>(&*ChildOrErr.get())) {
if (PrintFileName) {
ArchiveName = std::string(A->getFileName());
if (ArchFlags.size() > 1)
ArchitectureName = I->getArchFlagName();
} else {
outs() << "\n" << A->getFileName();
outs() << "(" << O->getFileName() << ")";
if (ArchFlags.size() > 1) {
outs() << " (for architecture " << I->getArchFlagName()
<< ")";
}
outs() << ":\n";
}
dumpSymbolNamesFromObject(*O, false, ArchiveName,
ArchitectureName);
}
}
if (Err)
error(std::move(Err), A->getFileName());
} else {
consumeError(AOrErr.takeError());
error(Filename + " for architecture " +
StringRef(I->getArchFlagName()) +
" is not a Mach-O file or an archive file",
"Mach-O universal file");
}
}
}
if (!ArchFound) {
error(ArchFlags[i],
"file: " + Filename + " does not contain architecture");
return;
}
}
return;
}
// No architecture flags were specified so if this contains a slice that
// matches the host architecture dump only that.
if (!ArchAll) {
Triple HostTriple = MachOObjectFile::getHostArch();
StringRef HostArchName = HostTriple.getArchName();
for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
E = UB->end_objects();
I != E; ++I) {
if (HostArchName == I->getArchFlagName()) {
Expected<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
std::string ArchiveName;
if (ObjOrErr) {
ObjectFile &Obj = *ObjOrErr.get();
dumpSymbolNamesFromObject(Obj, false);
} else if (auto E = isNotObjectErrorInvalidFileType(
ObjOrErr.takeError())) {
error(std::move(E), Filename);
return;
} else if (Expected<std::unique_ptr<Archive>> AOrErr =
I->getAsArchive()) {
std::unique_ptr<Archive> &A = *AOrErr;
Error Err = Error::success();
for (auto &C : A->children(Err)) {
Expected<std::unique_ptr<Binary>> ChildOrErr =
C.getAsBinary(ContextPtr);
if (!ChildOrErr) {
if (auto E = isNotObjectErrorInvalidFileType(
ChildOrErr.takeError()))
error(std::move(E), Filename, C);
continue;
}
if (SymbolicFile *O =
dyn_cast<SymbolicFile>(&*ChildOrErr.get())) {
if (PrintFileName)
ArchiveName = std::string(A->getFileName());
else
outs() << "\n" << A->getFileName() << "(" << O->getFileName()
<< ")"
<< ":\n";
dumpSymbolNamesFromObject(*O, false, ArchiveName);
}
}
if (Err)
error(std::move(Err), A->getFileName());
} else {
consumeError(AOrErr.takeError());
error(Filename + " for architecture " +
StringRef(I->getArchFlagName()) +
" is not a Mach-O file or an archive file",
"Mach-O universal file");
}
return;
}
}
}
// Either all architectures have been specified or none have been specified
// and this does not contain the host architecture so dump all the slices.
bool moreThanOneArch = UB->getNumberOfObjects() > 1;
for (const MachOUniversalBinary::ObjectForArch &O : UB->objects()) {
Expected<std::unique_ptr<ObjectFile>> ObjOrErr = O.getAsObjectFile();
std::string ArchiveName;
std::string ArchitectureName;
ArchiveName.clear();
ArchitectureName.clear();
if (ObjOrErr) {
ObjectFile &Obj = *ObjOrErr.get();
if (PrintFileName) {
if (isa<MachOObjectFile>(Obj) && moreThanOneArch)
ArchitectureName = O.getArchFlagName();
} else {
if (moreThanOneArch)
outs() << "\n";
outs() << Obj.getFileName();
if (isa<MachOObjectFile>(Obj) && moreThanOneArch)
outs() << " (for architecture " << O.getArchFlagName() << ")";
outs() << ":\n";
}
dumpSymbolNamesFromObject(Obj, false, ArchiveName, ArchitectureName);
} else if (auto E = isNotObjectErrorInvalidFileType(
ObjOrErr.takeError())) {
error(std::move(E), Filename, moreThanOneArch ?
StringRef(O.getArchFlagName()) : StringRef());
continue;
} else if (Expected<std::unique_ptr<Archive>> AOrErr =
O.getAsArchive()) {
std::unique_ptr<Archive> &A = *AOrErr;
Error Err = Error::success();
for (auto &C : A->children(Err)) {
Expected<std::unique_ptr<Binary>> ChildOrErr =
C.getAsBinary(ContextPtr);
if (!ChildOrErr) {
if (auto E = isNotObjectErrorInvalidFileType(
ChildOrErr.takeError()))
error(std::move(E), Filename, C, moreThanOneArch ?
StringRef(ArchitectureName) : StringRef());
continue;
}
if (SymbolicFile *F = dyn_cast<SymbolicFile>(&*ChildOrErr.get())) {
if (PrintFileName) {
ArchiveName = std::string(A->getFileName());
if (isa<MachOObjectFile>(F) && moreThanOneArch)
ArchitectureName = O.getArchFlagName();
} else {
outs() << "\n" << A->getFileName();
if (isa<MachOObjectFile>(F)) {
outs() << "(" << F->getFileName() << ")";
if (moreThanOneArch)
outs() << " (for architecture " << O.getArchFlagName()
<< ")";
} else
outs() << ":" << F->getFileName();
outs() << ":\n";
}
dumpSymbolNamesFromObject(*F, false, ArchiveName, ArchitectureName);
}
}
if (Err)
error(std::move(Err), A->getFileName());
} else {
consumeError(AOrErr.takeError());
error(Filename + " for architecture " +
StringRef(O.getArchFlagName()) +
" is not a Mach-O file or an archive file",
"Mach-O universal file");
}
}
return;
}
if (TapiUniversal *TU = dyn_cast<TapiUniversal>(&Bin)) {
for (const TapiUniversal::ObjectForArch &I : TU->objects()) {
StringRef ArchName = I.getArchFlagName();
const bool ShowArch =
ArchFlags.empty() || llvm::is_contained(ArchFlags, ArchName);
if (!ShowArch)
continue;
if (!AddInlinedInfo && !I.isTopLevelLib())
continue;
if (auto ObjOrErr = I.getAsObjectFile()) {
outs() << "\n"
<< I.getInstallName() << " (for architecture " << ArchName << ")"
<< ":\n";
dumpSymbolNamesFromObject(*ObjOrErr.get(), false, {}, ArchName);
} else if (Error E =
isNotObjectErrorInvalidFileType(ObjOrErr.takeError())) {
error(std::move(E), Filename, ArchName);
}
}
return;
}
if (SymbolicFile *O = dyn_cast<SymbolicFile>(&Bin)) {
if (!MachOPrintSizeWarning && PrintSize && isa<MachOObjectFile>(O)) {
WithColor::warning(errs(), ToolName)
<< "sizes with --print-size for Mach-O files are always zero.\n";
MachOPrintSizeWarning = true;
}
if (!checkMachOAndArchFlags(O, Filename))
return;
dumpSymbolNamesFromObject(*O, true);
}
}
int main(int argc, char **argv) {
InitLLVM X(argc, argv);
BumpPtrAllocator A;
StringSaver Saver(A);
NmOptTable Tbl;
ToolName = argv[0];
opt::InputArgList Args =
Tbl.parseArgs(argc, argv, OPT_UNKNOWN, Saver, [&](StringRef Msg) {
error(Msg);
exit(1);
});
if (Args.hasArg(OPT_help)) {
Tbl.printHelp(
outs(),
(Twine(ToolName) + " [options] <input object files>").str().c_str(),
"LLVM symbol table dumper");
// TODO Replace this with OptTable API once it adds extrahelp support.
outs() << "\nPass @FILE as argument to read options from FILE.\n";
return 0;
}
if (Args.hasArg(OPT_version)) {
// This needs to contain the word "GNU", libtool looks for that string.
outs() << "llvm-nm, compatible with GNU nm" << '\n';
cl::PrintVersionMessage();
return 0;
}
DebugSyms = Args.hasArg(OPT_debug_syms);
DefinedOnly = Args.hasArg(OPT_defined_only);
Demangle = Args.hasFlag(OPT_demangle, OPT_no_demangle, false);
DynamicSyms = Args.hasArg(OPT_dynamic);
ExternalOnly = Args.hasArg(OPT_extern_only);
StringRef V = Args.getLastArgValue(OPT_format_EQ, "bsd");
if (V == "bsd")
OutputFormat = bsd;
else if (V == "posix")
OutputFormat = posix;
else if (V == "sysv")
OutputFormat = sysv;
else if (V == "darwin")
OutputFormat = darwin;
else if (V == "just-symbols")
OutputFormat = just_symbols;
else
error("--format value should be one of: bsd, posix, sysv, darwin, "
"just-symbols");
NoLLVMBitcode = Args.hasArg(OPT_no_llvm_bc);
NoSort = Args.hasArg(OPT_no_sort);
NoWeakSymbols = Args.hasArg(OPT_no_weak);
NumericSort = Args.hasArg(OPT_numeric_sort);
ArchiveMap = Args.hasArg(OPT_print_armap);
PrintFileName = Args.hasArg(OPT_print_file_name);
PrintSize = Args.hasArg(OPT_print_size);
ReverseSort = Args.hasArg(OPT_reverse_sort);
Quiet = Args.hasArg(OPT_quiet);
V = Args.getLastArgValue(OPT_radix_EQ, "x");
if (V == "o")
AddressRadix = Radix::o;
else if (V == "d")
AddressRadix = Radix::d;
else if (V == "x")
AddressRadix = Radix::x;
else
error("--radix value should be one of: 'o' (octal), 'd' (decimal), 'x' "
"(hexadecimal)");
SizeSort = Args.hasArg(OPT_size_sort);
SpecialSyms = Args.hasArg(OPT_special_syms);
UndefinedOnly = Args.hasArg(OPT_undefined_only);
WithoutAliases = Args.hasArg(OPT_without_aliases);
// Mach-O specific options.
FormatMachOasHex = Args.hasArg(OPT_x);
AddDyldInfo = Args.hasArg(OPT_add_dyldinfo);
AddInlinedInfo = Args.hasArg(OPT_add_inlinedinfo);
DyldInfoOnly = Args.hasArg(OPT_dyldinfo_only);
NoDyldInfo = Args.hasArg(OPT_no_dyldinfo);
// llvm-nm only reads binary files.
if (error(sys::ChangeStdinToBinary()))
return 1;
// These calls are needed so that we can read bitcode correctly.
llvm::InitializeAllTargetInfos();
llvm::InitializeAllTargetMCs();
llvm::InitializeAllAsmParsers();
// The relative order of these is important. If you pass --size-sort it should
// only print out the size. However, if you pass -S --size-sort, it should
// print out both the size and address.
if (SizeSort && !PrintSize)
PrintAddress = false;
if (OutputFormat == sysv || SizeSort)
PrintSize = true;
for (const auto *A : Args.filtered(OPT_arch_EQ)) {
SmallVector<StringRef, 2> Values;
llvm::SplitString(A->getValue(), Values, ",");
for (StringRef V : Values) {
if (V == "all")
ArchAll = true;
else if (MachOObjectFile::isValidArch(V))
ArchFlags.push_back(V);
else
error("Unknown architecture named '" + V + "'",
"for the --arch option");
}
}
// Mach-O takes -s to accept two arguments. We emulate this by iterating over
// both OPT_s and OPT_INPUT.
std::vector<std::string> InputFilenames;
int SegSectArgs = 0;
for (opt::Arg *A : Args.filtered(OPT_s, OPT_INPUT)) {
if (SegSectArgs > 0) {
--SegSectArgs;
SegSect.push_back(A->getValue());
} else if (A->getOption().matches(OPT_s)) {
SegSectArgs = 2;
} else {
InputFilenames.push_back(A->getValue());
}
}
if (!SegSect.empty() && SegSect.size() != 2)
error("bad number of arguments (must be two arguments)",
"for the -s option");
if (InputFilenames.empty())
InputFilenames.push_back("a.out");
if (InputFilenames.size() > 1)
MultipleFiles = true;
if (NoDyldInfo && (AddDyldInfo || DyldInfoOnly))
error("--no-dyldinfo can't be used with --add-dyldinfo or --dyldinfo-only");
llvm::for_each(InputFilenames, dumpSymbolNamesFromFile);
if (HadError)
return 1;
}
|
#include <vnl/io/vnl_io_vector.hxx>
VNL_IO_VECTOR_INSTANTIATE(float);
|
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/cognito-idp/model/AdminConfirmSignUpRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::CognitoIdentityProvider::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
AdminConfirmSignUpRequest::AdminConfirmSignUpRequest() :
m_userPoolIdHasBeenSet(false),
m_usernameHasBeenSet(false),
m_clientMetadataHasBeenSet(false)
{
}
Aws::String AdminConfirmSignUpRequest::SerializePayload() const
{
JsonValue payload;
if(m_userPoolIdHasBeenSet)
{
payload.WithString("UserPoolId", m_userPoolId);
}
if(m_usernameHasBeenSet)
{
payload.WithString("Username", m_username);
}
if(m_clientMetadataHasBeenSet)
{
JsonValue clientMetadataJsonMap;
for(auto& clientMetadataItem : m_clientMetadata)
{
clientMetadataJsonMap.WithString(clientMetadataItem.first, clientMetadataItem.second);
}
payload.WithObject("ClientMetadata", std::move(clientMetadataJsonMap));
}
return payload.View().WriteReadable();
}
Aws::Http::HeaderValueCollection AdminConfirmSignUpRequest::GetRequestSpecificHeaders() const
{
Aws::Http::HeaderValueCollection headers;
headers.insert(Aws::Http::HeaderValuePair("X-Amz-Target", "AWSCognitoIdentityProviderService.AdminConfirmSignUp"));
return headers;
}
|
// slang-emit-cpp.cpp
#include "slang-emit-cpp.h"
#include "../core/slang-writer.h"
#include "slang-emit-source-writer.h"
#include "slang-mangled-lexer.h"
#include "slang-ir-clone.h"
#include <assert.h>
/*
ABI
---
In terms of ABI we need to discuss the variety of variables/resources that need to be defined by the host for appropriate execution
of the output code.
https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-variable-syntax
Broadly we could categorize these as..
1) Varying entry point parameters (or 'varying')
2) Uniform entry point parameters
3) Uniform globals
4) Thread shared (such as group shared) or ('thread shared')
5) Thread local ('static')
If we can invoke a bunch of threads as a single invocation we could effectively have the ThreadShared not part of the ABI, but something
that is say allocated on the stack before the threads are kicked off. If we kick of threads individually then we would need to pass this
in as part of ABI. NOTE that it isn't right in so far as memory barriers etc couldn't work, as each thread would run to completion, but
we aren't going to worry about barriers for now.
On 1 - there could be potentially input and outputs (perhaps in out?). On CPU I guess that's fine.
On 2 and 3 they are effectively the same, and so for now 2+3 will be referred to together as 'uniforms'.
They should be copied into a single structure that has a well known order.
On 1 these are parameters that vary on an invocation. Thus a caller might call many times with same globals structure
and different varying entry point parameters.
On 5 - This would be a global that can be set and then accessed within the context of single thread
So in order of rate of change
1 : Probably change on every invocation (in the future such an invocation might be behind the API)
2 + 3 : Changes per group of 'threads' executed together
4 : Does not change between invocations
5 : Could be placed on the stack, and so not necessarily part of the ABI
For now we are only going to implement something 'Compute shader'-like. Doing so makes the varying parameter always the same.
So for now we would need to pass in
ComputeVaryingInput - Fixed because we are doing compute shader
Uniform - All the uniform data in a big blob, both from uniform entry point parameters, and uniform globals
When called we can have a structure that holds the thread local variables, and these two pointers.
*/
namespace Slang {
static const char s_xyzwNames[] = "xyzw";
static UnownedStringSlice _getTypePrefix(IROp op)
{
switch (op)
{
case kIROp_BoolType: return UnownedStringSlice::fromLiteral("Bool");
case kIROp_IntType: return UnownedStringSlice::fromLiteral("I32");
case kIROp_UIntType: return UnownedStringSlice::fromLiteral("U32");
case kIROp_FloatType: return UnownedStringSlice::fromLiteral("F32");
case kIROp_Int64Type: return UnownedStringSlice::fromLiteral("I64");
case kIROp_UInt64Type: return UnownedStringSlice::fromLiteral("U64");
case kIROp_DoubleType: return UnownedStringSlice::fromLiteral("F64");
default: return UnownedStringSlice::fromLiteral("?");
}
}
static IROp _getTypeStyle(IROp op)
{
switch (op)
{
case kIROp_VoidType:
case kIROp_BoolType:
{
return op;
}
case kIROp_Int8Type:
case kIROp_Int16Type:
case kIROp_IntType:
case kIROp_UInt8Type:
case kIROp_UInt16Type:
case kIROp_UIntType:
case kIROp_Int64Type:
case kIROp_UInt64Type:
{
// All int like
return kIROp_IntType;
}
case kIROp_HalfType:
case kIROp_FloatType:
case kIROp_DoubleType:
{
// All float like
return kIROp_FloatType;
}
default: return kIROp_Invalid;
}
}
static IROp _getCType(IROp op)
{
switch (op)
{
case kIROp_VoidType:
case kIROp_BoolType:
{
return op;
}
case kIROp_Int8Type:
case kIROp_Int16Type:
case kIROp_IntType:
case kIROp_UInt8Type:
case kIROp_UInt16Type:
case kIROp_UIntType:
{
// Promote all these to Int
return kIROp_IntType;
}
case kIROp_Int64Type:
case kIROp_UInt64Type:
{
// Promote all these to Int64, we can just vary the call to make these work
return kIROp_Int64Type;
}
case kIROp_DoubleType:
{
return kIROp_DoubleType;
}
case kIROp_HalfType:
case kIROp_FloatType:
{
// Promote both to float
return kIROp_FloatType;
}
default:
{
SLANG_ASSERT(!"Unhandled type");
return kIROp_undefined;
}
}
}
static UnownedStringSlice _getCTypeVecPostFix(IROp op)
{
switch (op)
{
case kIROp_BoolType: return UnownedStringSlice::fromLiteral("B");
case kIROp_IntType: return UnownedStringSlice::fromLiteral("I");
case kIROp_UIntType: return UnownedStringSlice::fromLiteral("U");
case kIROp_FloatType: return UnownedStringSlice::fromLiteral("F");
case kIROp_Int64Type: return UnownedStringSlice::fromLiteral("I64");
case kIROp_DoubleType: return UnownedStringSlice::fromLiteral("F64");
default: return UnownedStringSlice::fromLiteral("?");
}
}
/* !!!!!!!!!!!!!!!!!!!!!!!! CPPEmitHandler !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! */
/* static */ UnownedStringSlice CPPSourceEmitter::getBuiltinTypeName(IROp op)
{
switch (op)
{
case kIROp_VoidType: return UnownedStringSlice("void");
case kIROp_BoolType: return UnownedStringSlice("bool");
case kIROp_Int8Type: return UnownedStringSlice("int8_t");
case kIROp_Int16Type: return UnownedStringSlice("int16_t");
case kIROp_IntType: return UnownedStringSlice("int32_t");
case kIROp_Int64Type: return UnownedStringSlice("int64_t");
case kIROp_UInt8Type: return UnownedStringSlice("uint8_t");
case kIROp_UInt16Type: return UnownedStringSlice("uint16_t");
case kIROp_UIntType: return UnownedStringSlice("uint32_t");
case kIROp_UInt64Type: return UnownedStringSlice("uint64_t");
// Not clear just yet how we should handle half... we want all processing as float probly, but when reading/writing to memory converting
case kIROp_HalfType: return UnownedStringSlice("half");
case kIROp_FloatType: return UnownedStringSlice("float");
case kIROp_DoubleType: return UnownedStringSlice("double");
default: return UnownedStringSlice();
}
}
void CPPSourceEmitter::emitTypeDefinition(IRType* inType)
{
if (m_target == CodeGenTarget::CPPSource)
{
// All types are templates in C++
return;
}
IRType* type = m_typeSet.getType(inType);
if (!m_typeSet.isOwned(type))
{
// If defined in a different module, we assume they are emitted already. (Assumed to
// be a nominal type)
return;
}
SourceWriter* writer = getSourceWriter();
switch (type->getOp())
{
case kIROp_VectorType:
{
auto vecType = static_cast<IRVectorType*>(type);
const UnownedStringSlice* elemNames = getVectorElementNames(vecType);
int count = int(getIntVal(vecType->getElementCount()));
SLANG_ASSERT(count > 0 && count < 4);
UnownedStringSlice typeName = _getTypeName(type);
UnownedStringSlice elemName = _getTypeName(vecType->getElementType());
writer->emit("struct ");
writer->emit(typeName);
writer->emit("\n{\n");
writer->indent();
writer->emit(elemName);
writer->emit(" ");
for (int i = 0; i < count; ++i)
{
if (i > 0)
{
writer->emit(", ");
}
writer->emit(elemNames[i]);
}
writer->emit(";\n");
writer->dedent();
writer->emit("};\n\n");
break;
}
case kIROp_MatrixType:
{
auto matType = static_cast<IRMatrixType*>(type);
const auto rowCount = int(getIntVal(matType->getRowCount()));
const auto colCount = int(getIntVal(matType->getColumnCount()));
IRType* vecType = m_typeSet.addVectorType(matType->getElementType(), colCount);
UnownedStringSlice typeName = _getTypeName(type);
UnownedStringSlice rowTypeName = _getTypeName(vecType);
writer->emit("struct ");
writer->emit(typeName);
writer->emit("\n{\n");
writer->indent();
writer->emit(rowTypeName);
writer->emit(" rows[");
writer->emit(rowCount);
writer->emit("];\n");
writer->dedent();
writer->emit("};\n\n");
break;
}
case kIROp_PtrType:
case kIROp_RefType:
{
// We don't need to output a definition for these types
break;
}
case kIROp_ArrayType:
case kIROp_UnsizedArrayType:
case kIROp_HLSLRWStructuredBufferType:
{
// We don't need to output a definition for these with C++ templates
// For C we may need to (or do casting at point of usage)
break;
}
default:
{
if (IRBasicType::isaImpl(type->getOp()))
{
// Don't emit anything for built in types
return;
}
SLANG_ASSERT(!"Unhandled type");
break;
}
}
}
UnownedStringSlice CPPSourceEmitter::_getTypeName(IRType* inType)
{
IRType* type = m_typeSet.getType(inType);
StringSlicePool::Handle handle = StringSlicePool::kNullHandle;
if (m_typeNameMap.TryGetValue(type, handle))
{
return m_slicePool.getSlice(handle);
}
StringBuilder builder;
if (SLANG_SUCCEEDED(calcTypeName(type, m_target, builder)))
{
handle = m_slicePool.add(builder);
}
m_typeNameMap.Add(type, handle);
SLANG_ASSERT(handle != StringSlicePool::kNullHandle);
return m_slicePool.getSlice(handle);
}
SlangResult CPPSourceEmitter::_calcCPPTextureTypeName(IRTextureTypeBase* texType, StringBuilder& outName)
{
switch (texType->getAccess())
{
case SLANG_RESOURCE_ACCESS_READ:
break;
case SLANG_RESOURCE_ACCESS_READ_WRITE:
outName << "RW";
break;
case SLANG_RESOURCE_ACCESS_RASTER_ORDERED:
outName << "RasterizerOrdered";
break;
case SLANG_RESOURCE_ACCESS_APPEND:
outName << "Append";
break;
case SLANG_RESOURCE_ACCESS_CONSUME:
outName << "Consume";
break;
case SLANG_RESOURCE_ACCESS_WRITE:
if (texType->isFeedback())
{
outName << "Feedback";
}
break;
default:
SLANG_DIAGNOSE_UNEXPECTED(getSink(), SourceLoc(), "unhandled resource access mode");
return SLANG_FAIL;
}
switch (texType->GetBaseShape())
{
case TextureFlavor::Shape::Shape1D: outName << "Texture1D"; break;
case TextureFlavor::Shape::Shape2D: outName << "Texture2D"; break;
case TextureFlavor::Shape::Shape3D: outName << "Texture3D"; break;
case TextureFlavor::Shape::ShapeCube: outName << "TextureCube"; break;
case TextureFlavor::Shape::ShapeBuffer: outName << "Buffer"; break;
default:
SLANG_DIAGNOSE_UNEXPECTED(getSink(), SourceLoc(), "unhandled resource shape");
return SLANG_FAIL;
}
if (texType->isMultisample())
{
outName << "MS";
}
if (texType->isArray())
{
outName << "Array";
}
outName << "<" << _getTypeName(texType->getElementType()) << " >";
return SLANG_OK;
}
static UnownedStringSlice _getResourceTypePrefix(IROp op)
{
switch (op)
{
case kIROp_HLSLStructuredBufferType: return UnownedStringSlice::fromLiteral("StructuredBuffer");
case kIROp_HLSLRWStructuredBufferType: return UnownedStringSlice::fromLiteral("RWStructuredBuffer");
case kIROp_HLSLRWByteAddressBufferType: return UnownedStringSlice::fromLiteral("RWByteAddressBuffer");
case kIROp_HLSLByteAddressBufferType: return UnownedStringSlice::fromLiteral("ByteAddressBuffer");
case kIROp_SamplerStateType: return UnownedStringSlice::fromLiteral("SamplerState");
case kIROp_SamplerComparisonStateType: return UnownedStringSlice::fromLiteral("SamplerComparisonState");
case kIROp_HLSLRasterizerOrderedStructuredBufferType: return UnownedStringSlice::fromLiteral("RasterizerOrderedStructuredBuffer");
case kIROp_HLSLAppendStructuredBufferType: return UnownedStringSlice::fromLiteral("AppendStructuredBuffer");
case kIROp_HLSLConsumeStructuredBufferType: return UnownedStringSlice::fromLiteral("ConsumeStructuredBuffer");
case kIROp_HLSLRasterizerOrderedByteAddressBufferType: return UnownedStringSlice::fromLiteral("RasterizerOrderedByteAddressBuffer");
case kIROp_RaytracingAccelerationStructureType: return UnownedStringSlice::fromLiteral("RaytracingAccelerationStructure");
default: return UnownedStringSlice();
}
}
SlangResult CPPSourceEmitter::calcTypeName(IRType* type, CodeGenTarget target, StringBuilder& out)
{
switch (type->getOp())
{
case kIROp_OutType:
case kIROp_InOutType:
case kIROp_PtrType:
{
auto ptrType = static_cast<IRPtrType*>(type);
SLANG_RETURN_ON_FAIL(calcTypeName(ptrType->getValueType(), target, out));
out << "*";
return SLANG_OK;
}
case kIROp_RefType:
{
auto refType = static_cast<IRRefType*>(type);
SLANG_RETURN_ON_FAIL(calcTypeName(refType->getValueType(), target, out));
out << "&";
return SLANG_OK;
}
case kIROp_HalfType:
{
// Special case half
out << getBuiltinTypeName(kIROp_FloatType);
return SLANG_OK;
}
case kIROp_VectorType:
{
auto vecType = static_cast<IRVectorType*>(type);
auto vecCount = int(getIntVal(vecType->getElementCount()));
auto elemType = vecType->getElementType();
if (target == CodeGenTarget::CPPSource || target == CodeGenTarget::CUDASource)
{
out << "Vector<" << _getTypeName(elemType) << ", " << vecCount << ">";
}
else
{
out << "Vec";
UnownedStringSlice postFix = _getCTypeVecPostFix(elemType->getOp());
out << postFix;
if (postFix.getLength() > 1)
{
out << "_";
}
out << vecCount;
}
return SLANG_OK;
}
case kIROp_MatrixType:
{
auto matType = static_cast<IRMatrixType*>(type);
auto elementType = matType->getElementType();
const auto rowCount = int(getIntVal(matType->getRowCount()));
const auto colCount = int(getIntVal(matType->getColumnCount()));
if (target == CodeGenTarget::CPPSource || target == CodeGenTarget::CUDASource)
{
out << "Matrix<" << _getTypeName(elementType) << ", " << rowCount << ", " << colCount << ">";
}
else
{
out << "Mat";
const UnownedStringSlice postFix = _getCTypeVecPostFix(_getCType(elementType->getOp()));
out << postFix;
if (postFix.getLength() > 1)
{
out << "_";
}
out << rowCount;
out << colCount;
}
return SLANG_OK;
}
case kIROp_ArrayType:
{
auto arrayType = static_cast<IRArrayType*>(type);
auto elementType = arrayType->getElementType();
int elementCount = int(getIntVal(arrayType->getElementCount()));
out << "FixedArray<";
SLANG_RETURN_ON_FAIL(calcTypeName(elementType, target, out));
out << ", " << elementCount << ">";
return SLANG_OK;
}
case kIROp_UnsizedArrayType:
{
auto arrayType = static_cast<IRUnsizedArrayType*>(type);
auto elementType = arrayType->getElementType();
out << "Array<";
SLANG_RETURN_ON_FAIL(calcTypeName(elementType, target, out));
out << ">";
return SLANG_OK;
}
case kIROp_WitnessTableType:
case kIROp_WitnessTableIDType:
{
// A witness table typed value translates to a pointer to the
// struct of function pointers corresponding to the interface type.
auto witnessTableType = static_cast<IRWitnessTableType*>(type);
auto baseType = cast<IRType>(witnessTableType->getOperand(0));
SLANG_RETURN_ON_FAIL(calcTypeName(baseType, target, out));
out << "*";
return SLANG_OK;
}
case kIROp_RawPointerType:
case kIROp_RTTIPointerType:
{
out << "void*";
return SLANG_OK;
}
case kIROp_AnyValueType:
{
out << "AnyValue<";
auto anyValueType = static_cast<IRAnyValueType*>(type);
out << getIntVal(anyValueType->getSize());
out << ">";
return SLANG_OK;
}
case kIROp_ConstantBufferType:
case kIROp_ParameterBlockType:
{
auto groupType = cast<IRParameterGroupType>(type);
auto elementType = groupType->getElementType();
SLANG_RETURN_ON_FAIL(calcTypeName(elementType, target, out));
out << "*";
return SLANG_OK;
}
case kIROp_RTTIType:
{
out << "TypeInfo";
return SLANG_OK;
}
case kIROp_RTTIHandleType:
{
out << "TypeInfo*";
return SLANG_OK;
}
default:
{
if (isNominalOp(type->getOp()))
{
out << getName(type);
return SLANG_OK;
}
if (IRBasicType::isaImpl(type->getOp()))
{
out << getBuiltinTypeName(type->getOp());
return SLANG_OK;
}
if (auto texType = as<IRTextureTypeBase>(type))
{
// We don't support TextureSampler, so ignore that
if (texType->getOp() != kIROp_TextureSamplerType)
{
return _calcCPPTextureTypeName(texType, out);
}
}
// If _getResourceTypePrefix returns something, we assume can output any specialization after it in order.
{
UnownedStringSlice prefix = _getResourceTypePrefix(type->getOp());
if (prefix.getLength() > 0)
{
auto oldWriter = m_writer;
SourceManager* sourceManager = oldWriter->getSourceManager();
// TODO(JS): This is a bit of a hack. We don't want to emit the result here,
// so we replace the writer, write out the type, grab the contents, and restore the writer
SourceWriter writer(sourceManager, LineDirectiveMode::None);
m_writer = &writer;
m_writer->emit(prefix);
// TODO(JS).
// Assumes ordering of types matches ordering of operands.
UInt operandCount = type->getOperandCount();
if (operandCount)
{
m_writer->emit("<");
for (UInt ii = 0; ii < operandCount; ++ii)
{
if (ii != 0)
{
m_writer->emit(", ");
}
emitVal(type->getOperand(ii), getInfo(EmitOp::General));
}
m_writer->emit(">");
}
out << writer.getContent();
m_writer = oldWriter;
return SLANG_OK;
}
}
break;
}
}
SLANG_DIAGNOSE_UNEXPECTED(getSink(), SourceLoc(), "unhandled type for C/C++ emit");
return SLANG_FAIL;
}
void CPPSourceEmitter::useType(IRType* type)
{
_getTypeName(type);
}
static IRBasicType* _getElementType(IRType* type)
{
switch (type->getOp())
{
case kIROp_VectorType: type = static_cast<IRVectorType*>(type)->getElementType(); break;
case kIROp_MatrixType: type = static_cast<IRMatrixType*>(type)->getElementType(); break;
default: break;
}
return dynamicCast<IRBasicType>(type);
}
/* static */CPPSourceEmitter::TypeDimension CPPSourceEmitter::_getTypeDimension(IRType* type, bool vecSwap)
{
switch (type->getOp())
{
case kIROp_PtrType:
{
type = static_cast<IRPtrType*>(type)->getValueType();
break;
}
case kIROp_RefType:
{
type = static_cast<IRRefType*>(type)->getValueType();
break;
}
default: break;
}
switch (type->getOp())
{
case kIROp_VectorType:
{
auto vecType = static_cast<IRVectorType*>(type);
IRBasicType* elemBasicType = as<IRBasicType>(vecType->getElementType());
const BaseType baseType = elemBasicType->getBaseType();
const int elemCount = int(getIntVal(vecType->getElementCount()));
return (!vecSwap) ? TypeDimension{baseType, 1, elemCount} : TypeDimension{ baseType, elemCount, 1};
}
case kIROp_MatrixType:
{
auto matType = static_cast<IRMatrixType*>(type);
const int colCount = int(getIntVal(matType->getColumnCount()));
const int rowCount = int(getIntVal(matType->getRowCount()));
IRBasicType* elemBasicType = as<IRBasicType>(matType->getElementType());
const BaseType baseType = elemBasicType->getBaseType();
return TypeDimension{baseType, rowCount, colCount};
}
default:
{
// Assume we don't know the type
BaseType baseType = BaseType::Void;
IRBasicType* basicType = as<IRBasicType>(type);
if (basicType)
{
baseType = basicType->getBaseType();
}
return TypeDimension{baseType, 1, 1};
}
}
}
void CPPSourceEmitter::_emitAccess(const UnownedStringSlice& name, const TypeDimension& dimension, int row, int col, SourceWriter* writer)
{
writer->emit(name);
const int comb = (dimension.colCount > 1 ? 2 : 0) | (dimension.rowCount > 1 ? 1 : 0);
switch (comb)
{
case 0:
{
break;
}
case 1:
{
// Vector, row count is biggest
const UnownedStringSlice* elemNames = getVectorElementNames(dimension.elemType, dimension.rowCount);
writer->emit(".");
const int index = (row > col) ? row : col;
writer->emit(elemNames[index]);
break;
}
case 2:
{
// Vector cols biggest dimension
const UnownedStringSlice* elemNames = getVectorElementNames(dimension.elemType, dimension.colCount);
writer->emit(".");
const int index = (row > col) ? row : col;
writer->emit(elemNames[index]);
break;
}
case 3:
{
// Matrix
const UnownedStringSlice* elemNames = getVectorElementNames(dimension.elemType, dimension.colCount);
writer->emit(".rows[");
writer->emit(row);
writer->emit("].");
writer->emit(elemNames[col]);
break;
}
}
}
static bool _isOperator(const UnownedStringSlice& funcName)
{
if (funcName.getLength() > 0)
{
const char c = funcName[0];
return !((c >= 'a' && c <='z') || (c >= 'A' && c <= 'Z') || c == '_');
}
return false;
}
void CPPSourceEmitter::_emitAryDefinition(const HLSLIntrinsic* specOp)
{
auto info = HLSLIntrinsic::getInfo(specOp->op);
auto funcName = info.funcName;
SLANG_ASSERT(funcName.getLength() > 0);
const bool isOperator = _isOperator(funcName);
SourceWriter* writer = getSourceWriter();
IRFuncType* funcType = specOp->signatureType;
const int numParams = int(funcType->getParamCount());
SLANG_ASSERT(numParams <= 3);
bool areAllScalar = true;
TypeDimension paramDims[3];
for (int i = 0; i < numParams; ++i)
{
paramDims[i]= _getTypeDimension(funcType->getParamType(i), false);
areAllScalar = areAllScalar && paramDims[i].isScalar();
}
// If all are scalar, then we don't need to emit a definition
if (areAllScalar)
{
return;
}
IRType* retType = specOp->returnType;
UnownedStringSlice scalarFuncName(funcName);
if (isOperator)
{
StringBuilder builder;
builder << "operator";
builder << funcName;
_emitSignature(builder.getUnownedSlice(), specOp);
}
else
{
scalarFuncName = _getScalarFuncName(specOp->op, _getElementType(funcType->getParamType(0)));
_emitSignature(funcName, specOp);
}
writer->emit("\n{\n");
writer->indent();
const bool hasReturnType = retType->getOp() != kIROp_VoidType;
TypeDimension calcDim;
if (hasReturnType)
{
emitType(retType);
writer->emit(" r;\n");
calcDim = _getTypeDimension(retType, false);
}
else
{
calcDim = _getTypeDimension(funcType->getParamType(0), false);
}
for (int i = 0; i < calcDim.rowCount; ++i)
{
for (int j = 0; j < calcDim.colCount; ++j)
{
if (hasReturnType)
{
_emitAccess(UnownedStringSlice::fromLiteral("r"), calcDim, i, j, writer);
writer->emit(" = ");
}
if (isOperator)
{
switch (numParams)
{
case 1:
{
writer->emit(funcName);
_emitAccess(UnownedStringSlice::fromLiteral("a"), paramDims[0], i, j, writer);
break;
}
case 2:
{
_emitAccess(UnownedStringSlice::fromLiteral("a"), paramDims[0], i, j, writer);
writer->emit(" ");
writer->emit(funcName);
writer->emit(" ");
_emitAccess(UnownedStringSlice::fromLiteral("b"), paramDims[1], i, j, writer);
break;
}
default: SLANG_ASSERT(!"Unhandled");
}
}
else
{
writer->emit(scalarFuncName);
writer->emit("(");
for (int k = 0; k < numParams; k++)
{
if (k > 0)
{
writer->emit(", ");
}
char c = char('a' + k);
_emitAccess(UnownedStringSlice(&c, 1), paramDims[k], i, j, writer);
}
writer->emit(")");
}
writer->emit(";\n");
}
}
if (hasReturnType)
{
writer->emit("return r;\n");
}
writer->dedent();
writer->emit("}\n\n");
}
void CPPSourceEmitter::_emitAnyAllDefinition(const UnownedStringSlice& funcName, const HLSLIntrinsic* specOp)
{
IRFuncType* funcType = specOp->signatureType;
SLANG_ASSERT(funcType->getParamCount() == 1);
IRType* paramType0 = funcType->getParamType(0);
SourceWriter* writer = getSourceWriter();
IRType* elementType = _getElementType(paramType0);
SLANG_ASSERT(elementType);
IRType* retType = specOp->returnType;
auto retTypeName = _getTypeName(retType);
IROp style = _getTypeStyle(elementType->getOp());
const TypeDimension dim = _getTypeDimension(paramType0, false);
_emitSignature(funcName, specOp);
writer->emit("\n{\n");
writer->indent();
writer->emit("return ");
for (int i = 0; i < dim.rowCount; ++i)
{
for (int j = 0; j < dim.colCount; ++j)
{
if (i > 0 || j > 0)
{
if (specOp->op == HLSLIntrinsic::Op::All)
{
writer->emit(" && ");
}
else
{
writer->emit(" || ");
}
}
switch (style)
{
case kIROp_BoolType:
{
_emitAccess(UnownedStringSlice::fromLiteral("a"), dim, i, j, writer);
break;
}
case kIROp_IntType:
{
writer->emit("(");
_emitAccess(UnownedStringSlice::fromLiteral("a"), dim, i, j, writer);
writer->emit(" != 0)");
break;
}
case kIROp_FloatType:
{
writer->emit("(");
_emitAccess(UnownedStringSlice::fromLiteral("a"), dim, i, j, writer);
writer->emit(" != 0.0)");
break;
}
}
}
}
writer->emit(";\n");
writer->dedent();
writer->emit("}\n\n");
}
void CPPSourceEmitter::_emitSignature(const UnownedStringSlice& funcName, const HLSLIntrinsic* specOp)
{
IRFuncType* funcType = specOp->signatureType;
const int paramsCount = int(funcType->getParamCount());
IRType* retType = specOp->returnType;
emitFunctionPreambleImpl(nullptr);
SourceWriter* writer = getSourceWriter();
emitType(retType);
writer->emit(" ");
writer->emit(funcName);
writer->emit("(");
for (int i = 0; i < paramsCount; ++i)
{
if (i > 0)
{
writer->emit(", ");
}
// We can't pass as const& for vector, scalar, array types, as they are pass by value
// For types passed by reference, we should do something different
IRType* paramType = funcType->getParamType(i);
#if 0
writer->emit("const ");
#endif
emitType(paramType);
#if 0
if (dynamicCast<IRBasicType>(paramType))
{
writer->emit(" ");
}
else
{
writer->emit("& ");
}
#else
writer->emit(" ");
#endif
writer->emitChar(char('a' + i));
}
writer->emit(")");
}
UnownedStringSlice CPPSourceEmitter::_getAndEmitSpecializedOperationDefinition(HLSLIntrinsic::Op op, IRType*const* argTypes, Int argCount, IRType* retType)
{
HLSLIntrinsic intrinsic;
m_intrinsicSet.calcIntrinsic(op, retType, argTypes, argCount, intrinsic);
auto specOp = m_intrinsicSet.add(intrinsic);
_maybeEmitSpecializedOperationDefinition(specOp);
return _getFuncName(specOp);
}
void CPPSourceEmitter::_emitGetAtDefinition(const UnownedStringSlice& funcName, const HLSLIntrinsic* specOp)
{
SourceWriter* writer = getSourceWriter();
IRFuncType* funcType = specOp->signatureType;
SLANG_ASSERT(funcType->getParamCount() == 2);
IRType* srcType = funcType->getParamType(0);
for (Index i = 0; i < 3; ++i)
{
UnownedStringSlice typePrefix = (i == 0) ? UnownedStringSlice::fromLiteral("const ") : UnownedStringSlice();
bool lValue = (i != 2);
emitFunctionPreambleImpl(nullptr);
writer->emit(typePrefix);
emitType(specOp->returnType);
if (lValue)
m_writer->emit("*");
writer->emit(" ");
writer->emit(funcName);
writer->emit("(");
writer->emit(typePrefix);
emitType(funcType->getParamType(0));
if (lValue)
writer->emit("*");
writer->emit(" a, ");
emitType(funcType->getParamType(1));
writer->emit(" b)\n{\n");
writer->indent();
if (auto vectorType = as<IRVectorType>(srcType))
{
int vecSize = int(getIntVal(vectorType->getElementCount()));
writer->emit("SLANG_PRELUDE_ASSERT(b >= 0 && b < ");
writer->emit(vecSize);
writer->emit(");\n");
writer->emit("return ((");
emitType(specOp->returnType);
writer->emit("*)");
if (lValue)
writer->emit("a) + b;\n");
else
writer->emit("&a)[b];\n");
}
else if (auto matrixType = as<IRMatrixType>(srcType))
{
//int colCount = int(getIntVal(matrixType->getColumnCount()));
int rowCount = int(getIntVal(matrixType->getRowCount()));
writer->emit("SLANG_PRELUDE_ASSERT(b >= 0 && b < ");
writer->emit(rowCount);
writer->emit(");\n");
if (lValue)
writer->emit("return &(a->rows[b]);\n");
else
writer->emit("return a.rows[b];\n");
}
writer->dedent();
writer->emit("}\n\n");
}
}
void CPPSourceEmitter::_emitConstructConvertDefinition(const UnownedStringSlice& funcName, const HLSLIntrinsic* specOp)
{
SourceWriter* writer = getSourceWriter();
IRFuncType* funcType = specOp->signatureType;
SLANG_ASSERT(funcType->getParamCount() == 2);
IRType* srcType = funcType->getParamType(1);
IRType* retType = specOp->returnType;
emitFunctionPreambleImpl(nullptr);
emitType(retType);
writer->emit(" ");
writer->emit(funcName);
writer->emit("(");
emitType(srcType);
writer->emitChar(' ');
writer->emitChar(char('a' + 0));
writer->emit(")");
writer->emit("\n{\n");
writer->indent();
writer->emit("return ");
emitType(retType);
writer->emit("{ ");
IRType* dstElemType = _getElementType(retType);
//IRType* srcElemType = _getElementType(srcType);
TypeDimension dim = _getTypeDimension(retType, false);
UnownedStringSlice rowTypeName;
if (dim.rowCount > 1)
{
IRType* rowType = m_typeSet.addVectorType(dstElemType, int(dim.colCount));
rowTypeName = _getTypeName(rowType);
}
for (int i = 0; i < dim.rowCount; ++i)
{
if (dim.rowCount > 1)
{
if (i > 0)
{
writer->emit(", \n");
}
if (m_target == CodeGenTarget::CUDASource)
{
m_writer->emit("make_");
writer->emit(rowTypeName);
m_writer->emit("(");
}
else
{
writer->emit(rowTypeName);
writer->emit("{ ");
}
}
for (int j = 0; j < dim.colCount; ++j)
{
if (j > 0)
{
writer->emit(", ");
}
emitType(dstElemType);
writer->emit("(");
_emitAccess(UnownedStringSlice::fromLiteral("a"), dim, i, j, writer);
writer->emit(")");
}
if (dim.rowCount > 1)
{
if (m_target == CodeGenTarget::CUDASource)
{
writer->emit(")");
}
else
{
writer->emit("}");
}
}
}
writer->emit("};\n");
writer->dedent();
writer->emit("}\n\n");
}
void CPPSourceEmitter::_emitInitDefinition(const UnownedStringSlice& funcName, const HLSLIntrinsic* specOp)
{
SourceWriter* writer = getSourceWriter();
IRFuncType* funcType = specOp->signatureType;
emitFunctionPreambleImpl(nullptr);
IRType* retType = specOp->returnType;
_emitSignature(funcName, specOp);
writer->emit("\n{\n");
writer->indent();
// Use C++ construction
writer->emit("return ");
emitType(retType);
writer->emit("{ ");
const Index paramCount = Index(funcType->getParamCount());
if (IRVectorType* vecType = as<IRVectorType>(retType))
{
Index elementCount = Index(getIntVal(vecType->getElementCount()));
Index paramIndex = 0;
Index paramSubIndex = 0;
for (Index i = 0; i < elementCount; ++i)
{
if (i > 0)
{
writer->emit(", ");
}
if (paramIndex >= paramCount)
{
writer->emit("0");
}
else
{
IRType* paramType = funcType->getParamType(paramIndex);
if (IRVectorType* paramVecType = as<IRVectorType>(paramType))
{
Index paramElementCount = Index(getIntVal(paramVecType->getElementCount()));
const UnownedStringSlice* elemNames = getVectorElementNames(paramVecType);
writer->emitChar('a' + char(paramIndex));
writer->emit(".");
writer->emit(elemNames[paramSubIndex]);
paramSubIndex ++;
if (paramSubIndex >= paramElementCount)
{
paramIndex++;
paramSubIndex = 0;
}
}
else
{
writer->emitChar('a' + char(paramIndex));
paramIndex++;
}
}
}
}
else
{
for (Index i = 0; i < paramCount; ++i)
{
if (i > 0)
{
writer->emit(", ");
}
writer->emitChar('a' + char(i));
}
}
writer->emit("};\n");
writer->dedent();
writer->emit("}\n\n");
}
void CPPSourceEmitter::_emitConstructFromScalarDefinition(const UnownedStringSlice& funcName, const HLSLIntrinsic* specOp)
{
SourceWriter* writer = getSourceWriter();
IRFuncType* funcType = specOp->signatureType;
SLANG_ASSERT(funcType->getParamCount() == 2);
IRType* srcType = funcType->getParamType(1);
IRType* retType = specOp->returnType;
emitFunctionPreambleImpl(nullptr);
emitType(retType);
writer->emit(" ");
writer->emit(funcName);
writer->emit("(");
emitType(srcType);
writer->emitChar(' ');
writer->emitChar(char('a' + 0));
writer->emit(")");
writer->emit("\n{\n");
writer->indent();
writer->emit("return ");
emitType(retType);
writer->emit("{ ");
const TypeDimension dim = _getTypeDimension(retType, false);
for (int i = 0; i < dim.rowCount; ++i)
{
if (dim.rowCount > 1)
{
if (i > 0)
{
writer->emit(", \n");
}
writer->emit("{ ");
}
for (int j = 0; j < dim.colCount; ++j)
{
if (j > 0)
{
writer->emit(", ");
}
writer->emit("a");
}
if (dim.rowCount > 1)
{
writer->emit("}");
}
}
writer->emit("};\n");
writer->dedent();
writer->emit("}\n\n");
}
void CPPSourceEmitter::_maybeEmitSpecializedOperationDefinition(const HLSLIntrinsic* specOp)
{
// Check if it's been emitted already, if not add it.
if (!m_intrinsicEmitted.Add(specOp))
{
return;
}
emitSpecializedOperationDefinition(specOp);
}
void CPPSourceEmitter::emitSpecializedOperationDefinition(const HLSLIntrinsic* specOp)
{
typedef HLSLIntrinsic::Op Op;
switch (specOp->op)
{
case Op::Init:
{
return _emitInitDefinition(_getFuncName(specOp), specOp);
}
case Op::Any:
case Op::All:
{
return _emitAnyAllDefinition(_getFuncName(specOp), specOp);
}
case Op::ConstructConvert:
{
return _emitConstructConvertDefinition(_getFuncName(specOp), specOp);
}
case Op::ConstructFromScalar:
{
return _emitConstructFromScalarDefinition(_getFuncName(specOp), specOp);
}
case Op::GetAt:
{
return _emitGetAtDefinition(_getFuncName(specOp), specOp);
}
case Op::Swizzle:
{
// Don't have to output anything for swizzle for now
return;
}
default:
{
const auto& info = HLSLIntrinsic::getInfo(specOp->op);
const int paramCount = (info.numOperands < 0) ? int(specOp->signatureType->getParamCount()) : info.numOperands;
if (paramCount >= 1 && paramCount <= 3)
{
return _emitAryDefinition(specOp);
}
break;
}
}
SLANG_ASSERT(!"Unhandled");
}
void CPPSourceEmitter::emitCall(const HLSLIntrinsic* specOp, IRInst* inst, const IRUse* operands, int numOperands, const EmitOpInfo& inOuterPrec)
{
typedef HLSLIntrinsic::Op Op;
SLANG_UNUSED(inOuterPrec);
SourceWriter* writer = getSourceWriter();
switch (specOp->op)
{
case Op::Init:
{
IRType* retType = specOp->returnType;
if (IRBasicType::isaImpl(retType->getOp()))
{
SLANG_ASSERT(numOperands == 1);
writer->emit(_getTypeName(retType));
writer->emitChar('(');
emitOperand(operands[0].get(), getInfo(EmitOp::General));
writer->emitChar(')');
return;
}
break;
}
case Op::Swizzle:
{
// Currently only works for C++ (we use {} constuction) - which means we don't need to generate a function.
// For C we need to generate suitable construction function
auto swizzleInst = static_cast<IRSwizzle*>(inst);
const Index elementCount = Index(swizzleInst->getElementCount());
IRType* srcType = swizzleInst->getBase()->getDataType();
IRVectorType* srcVecType = as<IRVectorType>(srcType);
const UnownedStringSlice* elemNames = getVectorElementNames(srcVecType);
// TODO(JS): Not 100% sure this is correct on the parens handling front
IRType* retType = specOp->returnType;
emitType(retType);
writer->emit("{");
for (Index i = 0; i < elementCount; ++i)
{
if (i > 0)
{
writer->emit(", ");
}
auto outerPrec = getInfo(EmitOp::General);
auto prec = getInfo(EmitOp::Postfix);
emitOperand(swizzleInst->getBase(), leftSide(outerPrec, prec));
writer->emit(".");
IRInst* irElementIndex = swizzleInst->getElementIndex(i);
SLANG_RELEASE_ASSERT(irElementIndex->getOp() == kIROp_IntLit);
IRConstant* irConst = (IRConstant*)irElementIndex;
UInt elementIndex = (UInt)irConst->value.intVal;
SLANG_RELEASE_ASSERT(elementIndex < 4);
writer->emit(elemNames[elementIndex]);
}
writer->emit("}");
return;
}
default: break;
}
{
const auto& info = HLSLIntrinsic::getInfo(specOp->op);
// Make sure that the return type is available
const bool isOperator = _isOperator(info.funcName);
const UnownedStringSlice funcName = _getFuncName(specOp);
switch (specOp->op)
{
case Op::ConstructFromScalar:
{
// We need to special case, because this may have come from a swizzle from a built in
// type, in that case the only parameter we want is the first one
numOperands = 1;
break;
}
default: break;
}
// add that we want a function
SLANG_ASSERT(info.numOperands < 0 || numOperands == info.numOperands);
useType(specOp->returnType);
if (isOperator)
{
// Just do the default output
defaultEmitInstExpr(inst, inOuterPrec);
}
else
{
writer->emit(funcName);
writer->emitChar('(');
for (int i = 0; i < numOperands; ++i)
{
if (i > 0)
{
writer->emit(", ");
}
emitOperand(operands[i].get(), getInfo(EmitOp::General));
}
writer->emitChar(')');
}
}
}
HLSLIntrinsic* CPPSourceEmitter::_addIntrinsic(HLSLIntrinsic::Op op, IRType* returnType, IRType*const* argTypes, Index argTypeCount)
{
HLSLIntrinsic intrinsic;
m_intrinsicSet.calcIntrinsic(op, returnType, argTypes, argTypeCount, intrinsic);
HLSLIntrinsic* addedIntrinsic = m_intrinsicSet.add(intrinsic);
_getFuncName(addedIntrinsic);
return addedIntrinsic;
}
SlangResult CPPSourceEmitter::calcScalarFuncName(HLSLIntrinsic::Op op, IRBasicType* type, StringBuilder& outBuilder)
{
outBuilder << _getTypePrefix(type->getOp()) << "_" << HLSLIntrinsic::getInfo(op).funcName;
return SLANG_OK;
}
UnownedStringSlice CPPSourceEmitter::_getScalarFuncName(HLSLIntrinsic::Op op, IRBasicType* type)
{
/* TODO(JS): This is kind of fast and loose. That we don't know all the parameters that are taken or
what the return type is, so we can't add to the HLSLIntrinsic map - we just generate the scalar
function name and use it (whilst also adding to the slice pool, so that we can return an
unowned slice). */
StringBuilder builder;
if (SLANG_FAILED(calcScalarFuncName(op, type, builder)))
{
SLANG_ASSERT(!"Unable to create scalar function name");
return UnownedStringSlice();
}
// Add to the pool.
auto handle = m_slicePool.add(builder);
return m_slicePool.getSlice(handle);
}
UnownedStringSlice CPPSourceEmitter::_getFuncName(const HLSLIntrinsic* specOp)
{
StringSlicePool::Handle handle = StringSlicePool::kNullHandle;
if (m_intrinsicNameMap.TryGetValue(specOp, handle))
{
return m_slicePool.getSlice(handle);
}
StringBuilder builder;
if (SLANG_FAILED(calcFuncName(specOp, builder)))
{
SLANG_ASSERT(!"Unable to create function name");
// Return an empty slice, as an error...
return UnownedStringSlice();
}
handle = m_slicePool.add(builder);
m_intrinsicNameMap.Add(specOp, handle);
SLANG_ASSERT(handle != StringSlicePool::kNullHandle);
return m_slicePool.getSlice(handle);
}
SlangResult CPPSourceEmitter::calcFuncName(const HLSLIntrinsic* specOp, StringBuilder& outBuilder)
{
typedef HLSLIntrinsic::Op Op;
if (specOp->isScalar())
{
IRType* paramType = specOp->signatureType->getParamType(0);
IRBasicType* basicType = as<IRBasicType>(paramType);
SLANG_ASSERT(basicType);
return calcScalarFuncName(specOp->op, basicType, outBuilder);
}
else
{
switch (specOp->op)
{
case Op::ConstructConvert:
{
// Work out the function name
IRFuncType* signatureType = specOp->signatureType;
SLANG_ASSERT(signatureType->getParamCount() == 2);
IRType* dstType = signatureType->getParamType(0);
//IRType* srcType = signatureType->getParamType(1);
outBuilder << "convert_";
// I need a function that is called that will construct this
SLANG_RETURN_ON_FAIL(calcTypeName(dstType, CodeGenTarget::CSource, outBuilder));
return SLANG_OK;
}
case Op::ConstructFromScalar:
{
// Work out the function name
IRFuncType* signatureType = specOp->signatureType;
SLANG_ASSERT(signatureType->getParamCount() == 2);
IRType* dstType = signatureType->getParamType(0);
outBuilder << "constructFromScalar_";
// I need a function that is called that will construct this
SLANG_RETURN_ON_FAIL(calcTypeName(dstType, CodeGenTarget::CSource, outBuilder));
return SLANG_OK;
}
case Op::GetAt:
{
outBuilder << "getAt";
return SLANG_OK;
}
case Op::Init:
{
outBuilder << "make_";
SLANG_RETURN_ON_FAIL(calcTypeName(specOp->returnType, CodeGenTarget::CSource, outBuilder));
return SLANG_OK;
}
default: break;
}
const auto& info = HLSLIntrinsic::getInfo(specOp->op);
if (info.funcName.getLength())
{
if (!_isOperator(info.funcName))
{
// If there is a standard default name, just use that
outBuilder << info.funcName;
return SLANG_OK;
}
}
// Just use the name of the Op. This is probably wrong, but gives a pretty good idea of what the desired (presumably missing) op is.
outBuilder << info.name;
return SLANG_OK;
}
}
/* !!!!!!!!!!!!!!!!!!!!!! CPPSourceEmitter !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! */
CPPSourceEmitter::CPPSourceEmitter(const Desc& desc):
Super(desc),
m_slicePool(StringSlicePool::Style::Default),
m_typeSet(desc.compileRequest->getSession()),
m_opLookup(new HLSLIntrinsicOpLookup),
m_intrinsicSet(&m_typeSet, m_opLookup)
{
m_semanticUsedFlags = 0;
//m_semanticUsedFlags = SemanticUsedFlag::GroupID | SemanticUsedFlag::GroupThreadID | SemanticUsedFlag::DispatchThreadID;
}
void CPPSourceEmitter::_emitInOutParamType(IRType* type, String const& name, IRType* valueType)
{
StringSliceLoc nameAndLoc(name.getUnownedSlice());
if (auto refType = as<IRRefType>(type))
{
m_writer->emit("const ");
}
UnownedStringSlice slice = _getTypeName(valueType);
m_writer->emit(slice);
m_writer->emit("* ");
m_writer->emitName(nameAndLoc);
}
void CPPSourceEmitter::emitParamTypeImpl(IRType* type, String const& name)
{
// An `out` or `inout` parameter will have been
// encoded as a parameter of pointer type, so
// we need to decode that here.
//
if (auto outType = as<IROutType>(type))
{
return _emitInOutParamType(type, name, outType->getValueType());
}
else if (auto inOutType = as<IRInOutType>(type))
{
return _emitInOutParamType(type, name, inOutType->getValueType());
}
else if (auto refType = as<IRRefType>(type))
{
return _emitInOutParamType(type, name, refType->getValueType());
}
emitType(type, name);
}
void CPPSourceEmitter::emitGlobalRTTISymbolPrefix()
{
m_writer->emit("SLANG_PRELUDE_SHARED_LIB_EXPORT");
}
void CPPSourceEmitter::emitWitnessTable(IRWitnessTable* witnessTable)
{
auto interfaceType = cast<IRInterfaceType>(witnessTable->getConformanceType());
// Ignore witness tables for builtin interface types.
if (isBuiltin(interfaceType))
return;
auto witnessTableItems = witnessTable->getChildren();
// Declare a global variable for the witness table.
m_writer->emit("extern \"C\" { ");
emitGlobalRTTISymbolPrefix();
m_writer->emit(" extern ");
emitSimpleType(interfaceType);
m_writer->emit(" ");
m_writer->emit(getName(witnessTable));
m_writer->emit("; }\n");
// The actual definition of this witness table global variable
// is deferred until the entire `Context` class is emitted, so
// that the member functions are available for reference.
// The witness table definition emission logic is defined in the
// `_emitWitnessTableDefinitions` function.
pendingWitnessTableDefinitions.add(witnessTable);
}
void CPPSourceEmitter::_emitWitnessTableDefinitions()
{
for (auto witnessTable : pendingWitnessTableDefinitions)
{
auto interfaceType = cast<IRInterfaceType>(witnessTable->getConformanceType());
List<IRWitnessTableEntry*> sortedWitnessTableEntries = getSortedWitnessTableEntries(witnessTable);
m_writer->emit("extern \"C\"\n{\n");
m_writer->indent();
emitGlobalRTTISymbolPrefix();
m_writer->emit("\n");
emitSimpleType(interfaceType);
m_writer->emit(" ");
m_writer->emit(getName(witnessTable));
m_writer->emit(" = {\n");
m_writer->indent();
auto seqIdDecoration = witnessTable->findDecoration<IRSequentialIDDecoration>();
if (seqIdDecoration)
m_writer->emit((UInt)seqIdDecoration->getSequentialID());
else
m_writer->emit("0");
for (Index i = 0; i < sortedWitnessTableEntries.getCount(); i++)
{
auto entry = sortedWitnessTableEntries[i];
if (auto funcVal = as<IRFunc>(entry->satisfyingVal.get()))
{
m_writer->emit(",\n");
m_writer->emit(getName(funcVal));
}
else if (auto witnessTableVal = as<IRWitnessTable>(entry->getSatisfyingVal()))
{
m_writer->emit(",\n");
m_writer->emit("&");
m_writer->emit(getName(witnessTableVal));
}
else if (entry->getSatisfyingVal() &&
entry->getSatisfyingVal()->getDataType()->getOp() == kIROp_RTTIHandleType)
{
m_writer->emit(",\n");
emitInstExpr(entry->getSatisfyingVal(), getInfo(EmitOp::General));
}
else
{
SLANG_UNEXPECTED("unknown witnesstable entry type");
}
}
m_writer->dedent();
m_writer->emit("\n};\n");
m_writer->dedent();
m_writer->emit("\n}\n");
}
}
void CPPSourceEmitter::emitInterface(IRInterfaceType* interfaceType)
{
// Skip built-in interfaces.
if (isBuiltin(interfaceType))
return;
m_writer->emit("struct ");
emitSimpleType(interfaceType);
m_writer->emit("\n{\n");
m_writer->indent();
m_writer->emit("uint32_t sequentialID;\n");
for (UInt i = 0; i < interfaceType->getOperandCount(); i++)
{
auto entry = as<IRInterfaceRequirementEntry>(interfaceType->getOperand(i));
if (auto funcVal = as<IRFuncType>(entry->getRequirementVal()))
{
emitType(funcVal->getResultType());
m_writer->emit(" (*");
m_writer->emit(getName(entry->getRequirementKey()));
m_writer->emit(")");
m_writer->emit("(");
bool isFirstParam = true;
for (UInt p = 0; p < funcVal->getParamCount(); p++)
{
auto paramType = funcVal->getParamType(p);
// Ingore TypeType-typed parameters for now.
if (as<IRTypeType>(paramType))
continue;
if (!isFirstParam)
m_writer->emit(", ");
else
isFirstParam = false;
emitParamType(paramType, String("param") + String(p));
}
m_writer->emit(");\n");
}
else if (auto witnessTableType = as<IRWitnessTableType>(entry->getRequirementVal()))
{
emitType((IRType*)witnessTableType->getConformanceType());
m_writer->emit("* ");
m_writer->emit(getName(entry->getRequirementKey()));
m_writer->emit(";\n");
}
else if (entry->getRequirementVal()->getOp() == kIROp_RTTIHandleType)
{
m_writer->emit("TypeInfo* ");
m_writer->emit(getName(entry->getRequirementKey()));
m_writer->emit(";\n");
}
}
m_writer->dedent();
m_writer->emit("};\n");
}
void CPPSourceEmitter::emitRTTIObject(IRRTTIObject* rttiObject)
{
m_writer->emit("extern \"C\" { ");
emitGlobalRTTISymbolPrefix();
m_writer->emit(" TypeInfo ");
m_writer->emit(getName(rttiObject));
m_writer->emit(" = {");
auto typeSizeDecoration = rttiObject->findDecoration<IRRTTITypeSizeDecoration>();
SLANG_ASSERT(typeSizeDecoration);
m_writer->emit(typeSizeDecoration->getTypeSize());
m_writer->emit("}; }\n");
}
bool CPPSourceEmitter::tryEmitGlobalParamImpl(IRGlobalParam* varDecl, IRType* varType)
{
SLANG_UNUSED(varDecl);
SLANG_UNUSED(varType);
switch (varType->getOp())
{
case kIROp_StructType:
{
String name = getName(varDecl);
UnownedStringSlice typeName = _getTypeName(varType);
m_writer->emit(typeName);
m_writer->emit("* ");
m_writer->emit(name);
m_writer->emit(";\n");
return true;
}
}
return false;
}
void CPPSourceEmitter::emitParameterGroupImpl(IRGlobalParam* varDecl, IRUniformParameterGroupType* type)
{
// Output global parameters
auto varLayout = getVarLayout(varDecl);
SLANG_RELEASE_ASSERT(varLayout);
String name = getName(varDecl);
auto elementType = type->getElementType();
switch (type->getOp())
{
case kIROp_ParameterBlockType:
case kIROp_ConstantBufferType:
{
UnownedStringSlice typeName = _getTypeName(elementType);
m_writer->emit(typeName);
m_writer->emit("* ");
m_writer->emit(name);
m_writer->emit(";\n");
break;
}
default:
{
emitType(elementType, name);
m_writer->emit(";\n");
break;
}
}
}
void CPPSourceEmitter::emitEntryPointAttributesImpl(IRFunc* irFunc, IREntryPointDecoration* entryPointDecor)
{
SLANG_UNUSED(entryPointDecor);
auto profile = m_effectiveProfile;
auto stage = profile.getStage();
switch (stage)
{
case Stage::Compute:
{
Int numThreads[kThreadGroupAxisCount];
getComputeThreadGroupSize(irFunc, numThreads);
// TODO(JS): We might want to store this information such that it can be used to execute
m_writer->emit("// [numthreads(");
for (int ii = 0; ii < kThreadGroupAxisCount; ++ii)
{
if (ii != 0) m_writer->emit(", ");
m_writer->emit(numThreads[ii]);
}
m_writer->emit(")]\n");
break;
}
default: break;
}
m_writer->emit("SLANG_PRELUDE_EXPORT\n");
}
void CPPSourceEmitter::emitSimpleFuncImpl(IRFunc* func)
{
auto resultType = func->getResultType();
auto name = getName(func);
// Deal with decorations that need
// to be emitted as attributes
// We start by emitting the result type and function name.
//
if (IREntryPointDecoration* entryPointDecor = func->findDecoration<IREntryPointDecoration>())
{
// Note: we currently emit multiple functions to represent an entry point
// on CPU/CUDA, and these all bottleneck through the actual `IRFunc`
// here as a workhorse.
//
// Because the workhorse function doesn't have the right signature to service
// general-purpose calls, it is being emitted with a `_` prefix.
//
StringBuilder prefixName;
prefixName << "_" << name;
emitType(resultType, prefixName);
}
else
{
emitType(resultType, name);
}
// Next we emit the parameter list of the function.
//
m_writer->emit("(");
auto firstParam = func->getFirstParam();
for (auto pp = firstParam; pp; pp = pp->getNextParam())
{
// Ingore TypeType-typed parameters for now.
// In the future we will pass around runtime type info
// for TypeType parameters.
if (as<IRTypeType>(pp->getFullType()))
continue;
if (pp != firstParam)
m_writer->emit(", ");
emitSimpleFuncParamImpl(pp);
}
m_writer->emit(")");
emitSemantics(func);
// TODO: encode declaration vs. definition
if (isDefinition(func))
{
m_writer->emit("\n{\n");
m_writer->indent();
// HACK: forward-declare all the local variables needed for the
// parameters of non-entry blocks.
emitPhiVarDecls(func);
// Need to emit the operations in the blocks of the function
emitFunctionBody(func);
m_writer->dedent();
m_writer->emit("}\n\n");
}
else
{
m_writer->emit(";\n\n");
}
}
void CPPSourceEmitter::emitSimpleValueImpl(IRInst* inst)
{
if (inst->getOp() == kIROp_FloatLit)
{
IRConstant* constantInst = static_cast<IRConstant*>(inst);
switch (constantInst->getFloatKind())
{
case IRConstant::FloatKind::Nan:
{
// TODO(JS):
// It's not clear this will work on all targets.
// In particular Visual Studio reports an error with this expression.
m_writer->emit("(0.0 / 0.0)");
break;
}
case IRConstant::FloatKind::PositiveInfinity:
{
m_writer->emit("SLANG_INFINITY");
break;
}
case IRConstant::FloatKind::NegativeInfinity:
{
m_writer->emit("(-SLANG_INFINITY)");
break;
}
default:
{
m_writer->emit(constantInst->value.floatVal);
// If the literal is a float, then we need to add 'f' at end, as
// without literal suffix the value defaults to double.
IRType* type = constantInst->getDataType();
if (type && type->getOp() == kIROp_FloatType)
{
m_writer->emitChar('f');
}
break;
}
}
}
else
{
Super::emitSimpleValueImpl(inst);
}
}
void CPPSourceEmitter::emitSimpleFuncParamImpl(IRParam* param)
{
CLikeSourceEmitter::emitSimpleFuncParamImpl(param);
}
void CPPSourceEmitter::emitVectorTypeNameImpl(IRType* elementType, IRIntegerValue elementCount)
{
emitSimpleType(m_typeSet.addVectorType(elementType, int(elementCount)));
}
void CPPSourceEmitter::emitSimpleTypeImpl(IRType* inType)
{
UnownedStringSlice slice = _getTypeName(m_typeSet.getType(inType));
m_writer->emit(slice);
}
void CPPSourceEmitter::emitTypeImpl(IRType* type, const StringSliceLoc* nameLoc)
{
UnownedStringSlice slice = _getTypeName(type);
m_writer->emit(slice);
if (nameLoc)
{
m_writer->emit(" ");
m_writer->emitName(*nameLoc);
}
}
void CPPSourceEmitter::emitIntrinsicCallExprImpl(
IRCall* inst,
IRTargetIntrinsicDecoration* targetIntrinsic,
EmitOpInfo const& inOuterPrec)
{
typedef HLSLIntrinsic::Op Op;
// TODO: Much of this logic duplicates code that is already
// in `CLikeSourceEmitter::emitIntrinsicCallExpr`. The only
// real difference is that when things bottom out on an ordinary
// function call there is logic to look up a C/C++-backend-specific
// opcode based on the function name, and emit using that.
auto outerPrec = inOuterPrec;
bool needClose = false;
Index argCount = Index(inst->getArgCount());
auto args = inst->getArgs();
auto name = targetIntrinsic->getDefinition();
// We will special-case some names here, that
// represent callable declarations that aren't
// ordinary functions, and thus may use different
// syntax.
if (name == ".operator[]")
{
SLANG_ASSERT(argCount == 2 || argCount == 3);
// If the first item is either a matrix or a vector, we use 'getAt' logic
IRType* targetType = args[0].get()->getDataType();
if (targetType->getOp() == kIROp_VectorType || targetType->getOp() == kIROp_MatrixType)
{
// Work out the intrinsic used
HLSLIntrinsic intrinsic;
m_intrinsicSet.calcIntrinsic(HLSLIntrinsic::Op::GetAt, inst->getDataType(), args, 2, intrinsic);
HLSLIntrinsic* specOp = m_intrinsicSet.add(intrinsic);
if (argCount == 2)
{
// Load
emitCall(specOp, inst, args, 2, inOuterPrec);
}
else
{
// Store
auto prec = getInfo(EmitOp::Postfix);
needClose = maybeEmitParens(outerPrec, prec);
emitCall(specOp, inst, inst->getOperands(), 2, inOuterPrec);
m_writer->emit(" = ");
emitOperand(inst->getOperand(2), getInfo(EmitOp::General));
maybeCloseParens(needClose);
}
}
else
{
// The user is invoking a built-in subscript operator
// Determine if we are calling the `ref` accessor:
// `ref` accessor returns a pointer of element type.
auto ptrType = as<IRPtrType>(inst->getFullType());
auto resourceType = inst->getOperand(1)->getFullType();
auto elementType = resourceType ? resourceType->getOperand(0) : nullptr;
bool isRef = ptrType && ptrType->getValueType() == elementType;
auto emitSubscript = [this, &args](EmitOpInfo _outerPrec)
{
auto prec = getInfo(EmitOp::Postfix);
bool needCloseSubscript = maybeEmitParens(_outerPrec, prec);
emitOperand(args[0].get(), leftSide(_outerPrec, prec));
m_writer->emit("[");
emitOperand(args[1].get(), getInfo(EmitOp::General));
m_writer->emit("]");
maybeCloseParens(needCloseSubscript);
};
if (isRef)
{
auto prefixPrec = getInfo(EmitOp::Prefix);
needClose = maybeEmitParens(outerPrec, prefixPrec);
m_writer->emit("&");
outerPrec = rightSide(outerPrec, prefixPrec);
}
emitSubscript(outerPrec);
maybeCloseParens(needClose);
if (argCount == 3)
{
m_writer->emit(" = ");
emitOperand(args[2].get(), getInfo(EmitOp::General));
}
}
return;
}
{
Op op = m_opLookup->getOpByName(name);
if (op != Op::Invalid)
{
// Work out the intrinsic used
HLSLIntrinsic intrinsic;
m_intrinsicSet.calcIntrinsic(op, inst->getDataType(), args, argCount, intrinsic);
HLSLIntrinsic* specOp = m_intrinsicSet.add(intrinsic);
emitCall(specOp, inst, args, int(argCount), inOuterPrec);
return;
}
}
// Use default impl (which will do intrinsic special macro expansion as necessary)
return Super::emitIntrinsicCallExprImpl(inst, targetIntrinsic, inOuterPrec);
}
void CPPSourceEmitter::emitLoopControlDecorationImpl(IRLoopControlDecoration* decl)
{
if (decl->getMode() == kIRLoopControl_Unroll)
{
// This relies on a suitable definition in slang-cpp-prelude.h or defined in C++ compiler invocation.
m_writer->emit("SLANG_UNROLL\n");
}
}
const UnownedStringSlice* CPPSourceEmitter::getVectorElementNames(BaseType baseType, Index elemCount)
{
SLANG_UNUSED(baseType);
SLANG_UNUSED(elemCount);
static const UnownedStringSlice elemNames[] =
{
UnownedStringSlice::fromLiteral("x"),
UnownedStringSlice::fromLiteral("y"),
UnownedStringSlice::fromLiteral("z"),
UnownedStringSlice::fromLiteral("w"),
};
return elemNames;
}
const UnownedStringSlice* CPPSourceEmitter::getVectorElementNames(IRVectorType* vectorType)
{
Index elemCount = Index(getIntVal(vectorType->getElementCount()));
IRType* type = vectorType->getElementType()->getCanonicalType();
IRBasicType* basicType = as<IRBasicType>(type);
SLANG_ASSERT(basicType);
return getVectorElementNames(basicType->getBaseType(), elemCount);
}
bool CPPSourceEmitter::_tryEmitInstExprAsIntrinsic(IRInst* inst, const EmitOpInfo& inOuterPrec)
{
HLSLIntrinsic* specOp = m_intrinsicSet.add(inst);
if (specOp)
{
if (inst->getOp() == kIROp_Call)
{
IRCall* call = static_cast<IRCall*>(inst);
emitCall(specOp, inst, call->getArgs(), int(call->getArgCount()), inOuterPrec);
}
else
{
emitCall(specOp, inst, inst->getOperands(), int(inst->getOperandCount()), inOuterPrec);
}
return true;
}
return false;
}
bool CPPSourceEmitter::tryEmitInstExprImpl(IRInst* inst, const EmitOpInfo& inOuterPrec)
{
switch (inst->getOp())
{
default:
{
return _tryEmitInstExprAsIntrinsic(inst, inOuterPrec);
}
case kIROp_swizzle:
{
// For C++ we don't need to emit a swizzle function
// For C we need a construction function
auto swizzleInst = static_cast<IRSwizzle*>(inst);
IRInst* baseInst = swizzleInst->getBase();
IRType* baseType = baseInst->getDataType();
// If we are swizzling from a built in type,
if (as<IRBasicType>(baseType))
{
// We can swizzle a scalar type to be a vector, or just a scalar
IRType* dstType = swizzleInst->getDataType();
if (as<IRBasicType>(dstType))
{
// If the output is a scalar, then could only have been a .x, which we can just ignore the '.x' part
emitOperand(baseInst, inOuterPrec);
return true;
}
}
else
{
const Index elementCount = Index(swizzleInst->getElementCount());
if (elementCount == 1)
{
// If just one thing is extracted then the . syntax will just work
defaultEmitInstExpr(inst, inOuterPrec);
return true;
}
}
// try doing automatically
return _tryEmitInstExprAsIntrinsic(inst, inOuterPrec);
}
case kIROp_Call:
{
auto funcValue = inst->getOperand(0);
// Does this function declare any requirements.
handleRequiredCapabilities(funcValue);
// try doing automatically
return _tryEmitInstExprAsIntrinsic(inst, inOuterPrec);
}
case kIROp_lookup_interface_method:
{
emitInstExpr(inst->getOperand(0), inOuterPrec);
m_writer->emit("->");
m_writer->emit(getName(inst->getOperand(1)));
return true;
}
case kIROp_GetSequentialID:
{
emitInstExpr(inst->getOperand(0), inOuterPrec);
m_writer->emit("->sequentialID");
return true;
}
case kIROp_WitnessTable:
{
m_writer->emit("(&");
m_writer->emit(getName(inst));
m_writer->emit(")");
return true;
}
case kIROp_getAddr:
{
// Once we clean up the pointer emitting logic, we can
// just use GetElementAddress instruction in place of
// getAddr instruction, and this case can be removed.
m_writer->emit("(&(");
emitInstExpr(inst->getOperand(0), EmitOpInfo::get(EmitOp::General));
m_writer->emit("))");
return true;
}
case kIROp_RTTIObject:
{
m_writer->emit(getName(inst));
return true;
}
case kIROp_Alloca:
{
m_writer->emit("alloca(");
emitOperand(inst->getOperand(0), EmitOpInfo::get(EmitOp::Postfix));
m_writer->emit("->typeSize)");
return true;
}
case kIROp_Copy:
{
m_writer->emit("memcpy(");
emitOperand(inst->getOperand(0), EmitOpInfo::get(EmitOp::General));
m_writer->emit(", ");
emitOperand(inst->getOperand(1), EmitOpInfo::get(EmitOp::General));
m_writer->emit(", ");
emitOperand(inst->getOperand(2), EmitOpInfo::get(EmitOp::Postfix));
m_writer->emit("->typeSize)");
return true;
}
case kIROp_BitCast:
{
m_writer->emit("(slang_bit_cast<");
emitType(inst->getDataType());
m_writer->emit(">(");
emitOperand(inst->getOperand(0), getInfo(EmitOp::General));
m_writer->emit("))");
return true;
}
}
}
// We want order of built in types (typically output nothing), vector, matrix, other types
// Types that aren't output have negative indices
static Index _calcTypeOrder(IRType* a)
{
switch (a->getOp())
{
case kIROp_FuncType:
{
return -2;
}
case kIROp_VectorType: return 1;
case kIROp_MatrixType: return 2;
default:
{
if (as<IRBasicType>(a))
{
return -1;
}
return 3;
}
}
}
void CPPSourceEmitter::emitPreprocessorDirectivesImpl()
{
SourceWriter* writer = getSourceWriter();
writer->emit("\n");
if (m_target == CodeGenTarget::CPPSource)
{
// Put all into an anonymous namespace
// This includes any generated types, and generated intrinsics
if (!m_compileRequest->getLinkage()->m_heterogeneous)
m_writer->emit("namespace { // anonymous \n\n");
m_writer->emit("#ifdef SLANG_PRELUDE_NAMESPACE\n");
m_writer->emit("using namespace SLANG_PRELUDE_NAMESPACE;\n");
m_writer->emit("#endif\n\n");
}
if (m_target == CodeGenTarget::CSource)
{
// For C output we need to emit type definitions.
List<IRType*> types;
m_typeSet.getTypes(types);
// Remove ones we don't need to emit
for (Index i = 0; i < types.getCount(); ++i)
{
if (_calcTypeOrder(types[i]) < 0)
{
types.fastRemoveAt(i);
--i;
}
}
// Sort them so that vectors come before matrices and everything else after that
types.sort([&](IRType* a, IRType* b) { return _calcTypeOrder(a) < _calcTypeOrder(b); });
// Emit the type definitions
for (auto type : types)
{
emitTypeDefinition(type);
}
}
{
List<const HLSLIntrinsic*> intrinsics;
m_intrinsicSet.getIntrinsics(intrinsics);
// Emit all the intrinsics that were used
for (auto intrinsic: intrinsics)
{
_maybeEmitSpecializedOperationDefinition(intrinsic);
}
}
}
void CPPSourceEmitter::emitOperandImpl(IRInst* inst, EmitOpInfo const& outerPrec)
{
if (shouldFoldInstIntoUseSites(inst))
{
emitInstExpr(inst, outerPrec);
return;
}
switch (inst->getOp())
{
case kIROp_Var:
case kIROp_GlobalVar:
emitVarExpr(inst, outerPrec);
break;
default:
m_writer->emit(getName(inst));
break;
}
}
/* static */bool CPPSourceEmitter::_isVariable(IROp op)
{
switch (op)
{
case kIROp_GlobalVar:
case kIROp_GlobalParam:
//case kIROp_Var:
{
return true;
}
default: return false;
}
}
static bool _isFunction(IROp op)
{
return op == kIROp_Func;
}
void CPPSourceEmitter::_emitEntryPointDefinitionStart(IRFunc* func, const String& funcName, const UnownedStringSlice& varyingTypeName)
{
auto resultType = func->getResultType();
auto entryPointDecl = func->findDecoration<IREntryPointDecoration>();
SLANG_ASSERT(entryPointDecl);
// Emit the actual function
emitEntryPointAttributes(func, entryPointDecl);
emitType(resultType, funcName);
m_writer->emit("(");
m_writer->emit(varyingTypeName);
m_writer->emit("* varyingInput, void* entryPointParams, void* globalParams)");
emitSemantics(func);
m_writer->emit("\n{\n");
m_writer->indent();
}
void CPPSourceEmitter::_emitEntryPointDefinitionEnd(IRFunc* func)
{
SLANG_UNUSED(func);
m_writer->dedent();
m_writer->emit("}\n");
}
namespace { // anonymous
struct AxisWithSize
{
typedef AxisWithSize ThisType;
bool operator<(const ThisType& rhs) const { return size < rhs.size || (size == rhs.size && axis < rhs.axis); }
int axis;
Int size;
};
} // anonymous
static void _calcAxisOrder(const Int sizeAlongAxis[CLikeSourceEmitter::kThreadGroupAxisCount], bool allowSingle, List<AxisWithSize>& out)
{
out.clear();
// Add in order z,y,x, so by default (if we don't sort), x will be the inner loop
for (int i = CLikeSourceEmitter::kThreadGroupAxisCount - 1; i >= 0; --i)
{
if (allowSingle || sizeAlongAxis[i] > 1)
{
AxisWithSize axisWithSize;
axisWithSize.axis = i;
axisWithSize.size = sizeAlongAxis[i];
out.add(axisWithSize);
}
}
// The sort here works to make the axis with the highest value the inner most loop.
// Disabled for now to make the order well defined as x, y, z
// axes.sort();
}
void CPPSourceEmitter::_emitEntryPointGroup(const Int sizeAlongAxis[kThreadGroupAxisCount], const String& funcName)
{
List<AxisWithSize> axes;
_calcAxisOrder(sizeAlongAxis, false, axes);
// Open all the loops
StringBuilder builder;
for (Index i = 0; i < axes.getCount(); ++i)
{
const auto& axis = axes[i];
builder.Clear();
const char elem[2] = { s_xyzwNames[axis.axis], 0 };
builder << "for (uint32_t " << elem << " = 0; " << elem << " < " << axis.size << "; ++" << elem << ")\n{\n";
m_writer->emit(builder);
m_writer->indent();
builder.Clear();
builder << "threadInput.groupThreadID." << elem << " = " << elem << ";\n";
m_writer->emit(builder);
}
// just call at inner loop point
m_writer->emit("_");
m_writer->emit(funcName);
m_writer->emit("(&threadInput, entryPointParams, globalParams);\n");
// Close all the loops
for (Index i = Index(axes.getCount() - 1); i >= 0; --i)
{
m_writer->dedent();
m_writer->emit("}\n");
}
}
void CPPSourceEmitter::_emitEntryPointGroupRange(const Int sizeAlongAxis[kThreadGroupAxisCount], const String& funcName)
{
List<AxisWithSize> axes;
_calcAxisOrder(sizeAlongAxis, true, axes);
// Open all the loops
StringBuilder builder;
for (Index i = 0; i < axes.getCount(); ++i)
{
const auto& axis = axes[i];
builder.Clear();
const char elem[2] = { s_xyzwNames[axis.axis], 0 };
builder << "for (uint32_t " << elem << " = vi.startGroupID." << elem << "; " << elem << " < vi.endGroupID." << elem << "; ++" << elem << ")\n{\n";
m_writer->emit(builder);
m_writer->indent();
m_writer->emit("groupVaryingInput.startGroupID.");
m_writer->emit(elem);
m_writer->emit(" = ");
m_writer->emit(elem);
m_writer->emit(";\n");
}
// just call at inner loop point
m_writer->emit(funcName);
m_writer->emit("_Group(&groupVaryingInput, entryPointParams, globalParams);\n");
// Close all the loops
for (Index i = Index(axes.getCount() - 1); i >= 0; --i)
{
m_writer->dedent();
m_writer->emit("}\n");
}
}
void CPPSourceEmitter::_emitInitAxisValues(const Int sizeAlongAxis[kThreadGroupAxisCount], const UnownedStringSlice& mulName, const UnownedStringSlice& addName)
{
StringBuilder builder;
m_writer->emit("{\n");
m_writer->indent();
for (int i = 0; i < kThreadGroupAxisCount; ++i)
{
builder.Clear();
const char elem[2] = { s_xyzwNames[i], 0 };
builder << mulName << "." << elem << " * " << sizeAlongAxis[i];
if (addName.getLength() > 0)
{
builder << " + " << addName << "." << elem;
}
if (i < kThreadGroupAxisCount - 1)
{
builder << ",";
}
builder << "\n";
m_writer->emit(builder);
}
m_writer->dedent();
m_writer->emit("};\n");
}
void CPPSourceEmitter::_emitForwardDeclarations(const List<EmitAction>& actions)
{
// Emit forward declarations. Don't emit variables that need to be grouped or function definitions (which will ref those types)
for (auto action : actions)
{
switch (action.level)
{
case EmitAction::Level::ForwardDeclaration:
emitFuncDecl(cast<IRFunc>(action.inst));
break;
case EmitAction::Level::Definition:
if (_isVariable(action.inst->getOp()) || _isFunction(action.inst->getOp()))
{
// Don't emit functions or variables that have to be grouped into structures yet
}
else
{
emitGlobalInst(action.inst);
}
break;
}
}
}
void CPPSourceEmitter::emitModuleImpl(IRModule* module, DiagnosticSink* sink)
{
// If we are emitting a heterogeneous program
// Emit the binary blob of each non-CPP target
ComponentType* program = m_compileRequest->getProgram();
auto linkage = m_compileRequest->getLinkage();
if (linkage->m_heterogeneous)
{
for (auto inst : module->getGlobalInsts())
{
auto func = as<IRFunc>(inst);
if (!func)
continue;
if (auto entryPointDecoration = func->findDecoration<IREntryPointDecoration>())
{
String entryPointName = entryPointDecoration->getName()->getStringSlice();
for (int index = 0; index < program->getEntryPointCount(); index++)
{
auto entryPoint = program->getEntryPoint(index);
if (entryPointName == entryPoint->getName()->text)
{
for (auto targetRequest : linkage->targets)
{
// Emit for all non-CPU targets
switch (targetRequest->getTarget())
{
case(CodeGenTarget::CPPSource):
case(CodeGenTarget::CSource):
case(CodeGenTarget::HostCallable):
case(CodeGenTarget::CUDASource):
break;
default:
auto targetProgram = program->getTargetProgram(targetRequest);
CompileResult result =
targetProgram->getOrCreateEntryPointResult(index, sink);
Slang::ComPtr<ISlangBlob> blob;
if (SLANG_FAILED(result.getBlob(blob)))
{
sink->diagnoseRaw(Severity::Error,
"Slang heterogeneous error: No blob to emit\n");
m_writer->emit("size_t __");
m_writer->emit(entryPointName);
m_writer->emit("Size = 0;\n");
m_writer->emit("unsigned char __");
m_writer->emit(entryPointName);
m_writer->emit("[1];\n");
}
else
{
auto ptr = (const unsigned char*)blob->getBufferPointer();
m_writer->emit("size_t __");
m_writer->emit(entryPointName);
m_writer->emit("Size = ");
m_writer->emitInt64(blob->getBufferSize());
m_writer->emit(";\n");
m_writer->emit("unsigned char __");
m_writer->emit(entryPointName);
m_writer->emit("[] = {");
// every 20 bytes, emit a newline
size_t j = 0;
for (size_t i = 0; i < blob->getBufferSize(); i++) {
m_writer->emitUInt64(ptr[i]);
m_writer->emit(", ");
if (j == 20)
{
m_writer->emit("\n");
j = 0;
}
j++;
}
m_writer->emit("};\n");
}
}
}
// Emit a wrapper function for calling the shader blob
m_writer->emit("void ");
m_writer->emit(entryPointName);
m_writer->emit("_wrapper(gfx_Device_0* device, Vector<uint32_t, 3> gridDims, \n");
m_writer->emit("\tRWStructuredBuffer<float> buffer)\n{");
/* m_writer->emit("\n\tgfx_ShaderProgram_0* shaderProgram = loadShaderProgram_0(device, __");
m_writer->emit(entryPointName);
m_writer->emit(", __");
m_writer->emit(entryPointName);
m_writer->emit("Size);");*/
m_writer->emit("\n\tgfx_ShaderProgram_0* shaderProgram = loadShaderProgram_0(device);");
m_writer->emit("\n\tgfx_TransientResourceHeap_0* transientHeap = buildTransientHeap_0(device);");
m_writer->emit("\n\tgfx_PipelineState_0* pipelineState = ");
m_writer->emit("buildPipelineState_0(device, shaderProgram);");
m_writer->emit("\n\tgfx_ResourceView_0* bufferView = createBufferView_0(device, unconvertBuffer_0(buffer));");
m_writer->emit("\n\tdispatchComputation_0(device, transientHeap, pipelineState, ");
m_writer->emit("bufferView, gridDims.x, gridDims.y, gridDims.z);");
m_writer->emit("\n}\n");
}
}
}
}
}
// Setup all built in types used in the module
m_typeSet.addAllBuiltinTypes(module);
// If any matrix types are used, then we need appropriate vector types too.
m_typeSet.addVectorForMatrixTypes();
List<EmitAction> actions;
computeEmitActions(module, actions);
_emitForwardDeclarations(actions);
{
// Output all the thread locals
for (auto action : actions)
{
if (action.level == EmitAction::Level::Definition && action.inst->getOp() == kIROp_GlobalVar)
{
emitGlobalInst(action.inst);
}
}
// Finally output the functions as methods on the context
for (auto action : actions)
{
if (action.level == EmitAction::Level::Definition && _isFunction(action.inst->getOp()))
{
emitGlobalInst(action.inst);
}
}
}
// Emit all witness table definitions.
_emitWitnessTableDefinitions();
if (m_target == CodeGenTarget::CPPSource)
{
// Need to close the anonymous namespace when outputting for C++
if (!linkage->m_heterogeneous)
m_writer->emit("} // anonymous\n\n");
}
// Finally we need to output dll entry points
for (auto action : actions)
{
if (action.level == EmitAction::Level::Definition && _isFunction(action.inst->getOp()))
{
IRFunc* func = as<IRFunc>(action.inst);
IREntryPointDecoration* entryPointDecor = func->findDecoration<IREntryPointDecoration>();
if (entryPointDecor && entryPointDecor->getProfile().getStage() == Stage::Compute)
{
Int groupThreadSize[kThreadGroupAxisCount];
getComputeThreadGroupSize(func, groupThreadSize);
String funcName = getName(func);
{
StringBuilder builder;
builder << funcName << "_Thread";
String threadFuncName = builder;
_emitEntryPointDefinitionStart(func, threadFuncName, UnownedStringSlice::fromLiteral("ComputeThreadVaryingInput"));
m_writer->emit("_");
m_writer->emit(funcName);
m_writer->emit("(varyingInput, entryPointParams, globalParams);\n");
_emitEntryPointDefinitionEnd(func);
}
// Emit the group version which runs for all elements in *single* thread group
{
StringBuilder builder;
builder << getName(func);
builder << "_Group";
String groupFuncName = builder;
_emitEntryPointDefinitionStart(func, groupFuncName, UnownedStringSlice::fromLiteral("ComputeVaryingInput"));
m_writer->emit("ComputeThreadVaryingInput threadInput = {};\n");
m_writer->emit("threadInput.groupID = varyingInput->startGroupID;\n");
_emitEntryPointGroup(groupThreadSize, funcName);
_emitEntryPointDefinitionEnd(func);
}
// Emit the main version - which takes a dispatch size
{
_emitEntryPointDefinitionStart(func, funcName, UnownedStringSlice::fromLiteral("ComputeVaryingInput"));
m_writer->emit("ComputeVaryingInput vi = *varyingInput;\n");
m_writer->emit("ComputeVaryingInput groupVaryingInput = {};\n");
_emitEntryPointGroupRange(groupThreadSize, funcName);
_emitEntryPointDefinitionEnd(func);
}
}
}
}
}
} // namespace Slang
|
// Copyright (C) 2018-2021 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
///////////////////////////////////////////////////////////////////////////////////////////////////
#pragma once
#include "primitive.hpp"
#include <vector>
namespace cldnn {
/// @addtogroup cpp_api C++ API
/// @{
/// @addtogroup cpp_topology Network Topology
/// @{
/// @addtogroup cpp_primitives Primitives
/// @{
/// @brief Broadcasts input to defined by @p broadcast_sizes output. @p broadcast_axes are used to
/// reinterpret input (reshape) inside algorithm.
///
/// @details Takes input, reinterpret it according to @p broadcast_axes
/// and copies it to output once or multiple times.
/// @n
/// @n Simple example with empty @p broadcast_axes. Lets assume that:
/// @n <tt>input_sizes = (in_b, in_f, in_y, in_x)</tt>
/// @n <tt>broadcast_sizes = (bs_b, bs_f, bs_y, bs_x)</tt>
/// @n <tt>broadcast_axes = () - empty</tt>
/// @n The input is broadcasted on each dimension where <tt>bs_{dim} > in_{dim}</tt> and <tt>bs_{dim}</tt>
/// is dividable by <tt>in_{dim}</tt> (input is copied <tt>bs_{dim} / in_{dim}</tt> times).
/// The dimensions where <tt>bs_{dim}</tt> is equal to <tt>in_{dim}</tt> remain unchanged.
/// @n The resulting output will have sizes equal to @p broadcast_sizes and contains values from
/// input that meet following criteria:
/// @n <tt>output[(b, f, y, x)] = input[(b % in_b, f % in_f, y % in_y, x % in_x)]</tt>
/// @n where <tt>(b, f, y, x)</tt> is a position of value in a primitive output.
/// @n
/// @n More complicated example with non empty @p broadcast_axes. Lets assume that:
/// @n <tt>broadcast_sizes = (bs_b, bs_f, bs_y, bs_x)</tt>
/// @n <tt>broadcast_axes = (2)</tt>
/// @n Taking into account broadcast_axes size (=1) primitive's input must be (4 - 1 = 3):
/// @n <tt>primitive input = (1, in_b, in_f, in_x)</tt>
/// @n Due to broadcast_axes = (2) primitive will interpret input as:
/// @n <tt>primitive input(internal representation) = (in_b, in_f, 1, in_x)</tt>
/// @n Now, you can apply broadcast rules from previous example to modified (reinterpreted)
/// input and output:
/// @n <tt>input_sizes = (in_b, in_f, 1, in_x)</tt>
/// @n <tt>output_shape = (bs_b, bs_f, bs_y, bs_x)</tt>
/// @n <tt>broadcast_axes = () - empty</tt>
/// @n
/// @n@b Requirements:
/// @n - @p broadcast_sizes must be positive on all dimensions.
/// @n - @p broadcast_axes size (dimensions count) must be within (inclusive) range
/// 0 - 4.
/// @n - @p broadcast_axes mustn't have duplicate values.
/// @n - Values of @p broadcast_axes must be within (inclusive) range 0 - 3
/// @n - @p output_shape must be greater (dividable) than or equal to reinterpreted
/// input on all dimensions.
/// @n Breaking any of these conditions will raise an exception.
struct broadcast : public primitive_base<broadcast> {
CLDNN_DECLARE_PRIMITIVE(broadcast)
/// @brief Constructs broadcast primitive / layer.
///
/// @param id An identifier of new primitive.
/// @param input An identifier of primitive which is an input for newly created
/// broadcast primitive.
/// @param broadcast_sizes Sizes of broadcast. Output size of current primitive
/// will match broadcast sizes (layout type will not change).
/// @param broadcast_axes Axes positions (0-based, from left to right) in output_shape
/// that are being broadcast. Values of broadcast_axes on remaining
/// axes must be greater (dividable) or equal to corresponding input
/// dimension values.
/// @param output_padding Optional padding for output from primitive.
broadcast(const primitive_id& id,
const primitive_id& input,
const tensor& broadcast_sizes,
const std::vector<uint16_t>& broadcast_axes = {},
const padding& output_padding = padding())
: primitive_base(id, {input}, output_padding),
broadcast_sizes(broadcast_sizes),
broadcast_axes(broadcast_axes) {}
/// @brief Expected sizes of output from broadcast primitive.
tensor broadcast_sizes;
/// @brief Array of axes positions from output shape (0-based, from left to right)
/// along which broadcast should happen.
std::vector<uint16_t> broadcast_axes;
};
/// @}
/// @}
/// @}
} // namespace cldnn
|
#include "pcheader.h"
#include "imgui/backends/imgui_impl_glfw.cpp"
|
//
// Created by nbdy on 04.01.21.
//
#include <BaseModule/BaseModule.h>
#include <Manager/Manager.h>
#define CTRL_BUTTON_SIZE Vector2 {16, 16}
enum ModuleStoreUIState {
LOADED = 0, LOADABLE, DOWNLOADABLE, SETTINGS
};
class ModuleStore : public BaseModule {
protected:
ModuleStoreUIState state = LOADED;
Texture2D texLoadedModules;
Texture2D texLoadableModules;
Texture2D texDownloadableModules;
Texture2D texUpdateableModules;
Texture2D texSettings;
Texture2D texControlButtons[5] = {texLoadedModules, texLoadableModules, texDownloadableModules, texUpdateableModules, texSettings};
void drawControlButtons() {
for(auto t : texControlButtons) {
// todo
}
}
void showLoadedModules(void *data) { // todo
auto *mm = ((Manager*) data)->getModuleManager();
for(auto m : mm->getLoadedModules()) {
}
};
void showLoadableModules(void *data) {}; // todo
void showDownloadableModules(void *data) {}; // todo
void showSettings(void *data) {}; // todo
void loadTextures() {
texLoadedModules = Utils::getIcon("modules", Vector2 {});
}
void unloadTextures() {
// todo
}
public:
ModuleStore(): BaseModule("ModuleStore", "(Down/Un)Load Modules", "0.1", "modules", UI, false) {
loadTextures();
}
~ModuleStore() {
// unloadTextures();
}
void loop(void *data) override {
switch (state) {
case LOADED: showLoadedModules(data); break;
case LOADABLE: showLoadableModules(data); break;
case DOWNLOADABLE: showDownloadableModules(data); break;
case SETTINGS: showSettings(data); break;
}
}
bool work(void *data, const context &ctx) override {
return true;
}
};
extern "C" tModule* create() {
return dynamic_cast<ModuleStore*>(new ModuleStore);
};
|
#include <cstdio>
/** The Assembly function */
extern "C" { int functieASM(int x, int y); }
/** The C/C++ equilavent of the Assembly function. */
int functieCPP(int x, int y)
{
int z = x * y;
return z;
}
/** Program entry point */
int main(int, char**)
{
int resultASM, resultCPP;
// These are our showcase values, chance them as you like.
const int X = 2, Y = 3;
// 1) We call our Assembly function
resultASM = functieASM(X, Y);
// 2) We call our C/C++ equilavent function
resultCPP = functieCPP(X, Y);
// 3) Display the result of both functions to the user
printf("ASM: %i\nCPP: %i\n", resultASM, resultCPP);
return 0;
}
|
/*
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010- Facebook, Inc. (http://www.facebook.com) |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
*/
#include <runtime/base/complex_types.h>
#include <runtime/base/comparisons.h>
#include <runtime/base/zend/zend_functions.h>
#include <runtime/base/variable_serializer.h>
#include <runtime/base/variable_unserializer.h>
#include <runtime/base/externals.h>
#include <runtime/ext/ext_variable.h>
#include <runtime/base/runtime_option.h>
#include <runtime/base/fiber_reference_map.h>
#include <runtime/base/zend/zend_string.h>
#include <runtime/base/array/array_iterator.h>
#include <util/parser/hphp.tab.hpp>
#include <system/lib/systemlib.h>
using namespace std;
namespace HPHP {
static const int64 cvValues[] = {
0x0000000000000000LL, 0x0000000000000000LL, // null_variant
};
static const int64 cnValues[] = {
0x0000000000000000LL, 0x0000000000000000LL, // null_varNR
0x0000000000000001LL, 0x0000000220000000LL, // true_varNR
0x0000000000000000LL, 0x0000000220000000LL, // false_varNR
0x7ff0000000000000LL, 0x0000000520000000LL, // INF_varNR
0xfff0000000000000LL, 0x0000000520000000LL, // NEGINF_varNR
0x7ff8000000000000LL, 0x0000000520000000LL, // NAN_varNR
};
const Variant &null_variant = *(const Variant *)(cvValues);
const VarNR &null_varNR = *(const VarNR*)(cnValues);
const VarNR &true_varNR = *(const VarNR*)(cnValues + 2);
const VarNR &false_varNR = *(const VarNR*)(cnValues + 4);
const VarNR &INF_varNR = *(const VarNR*)(cnValues + 6);
const VarNR &NEGINF_varNR = *(const VarNR*)(cnValues + 8);
const VarNR &NAN_varNR = *(const VarNR*)(cnValues + 10);
void Variant::RuntimeCheck() {
const VarNR &tmp_true_varNR = VarNR(true);
const VarNR &tmp_false_varNR = VarNR(false);
const VarNR &tmp_INF_varNR =
VarNR(std::numeric_limits<double>::infinity());
const VarNR &tmp_NEGINF_varNR =
VarNR(-std::numeric_limits<double>::infinity());
const VarNR &tmp_NAN_varNR =
VarNR(std::numeric_limits<double>::quiet_NaN());
if (memcmp(&tmp_true_varNR, &true_varNR, sizeof(VarNR)) != 0 ||
memcmp(&tmp_false_varNR, &false_varNR, sizeof(VarNR)) != 0 ||
memcmp(&tmp_INF_varNR, &INF_varNR, sizeof(VarNR)) != 0 ||
memcmp(&tmp_NEGINF_varNR, &NEGINF_varNR, sizeof(VarNR)) != 0 ||
memcmp(&tmp_NAN_varNR, &NAN_varNR, sizeof(VarNR) != 0)) {
assert(false);
}
// the first 8 bytes of null_variant or null_varNR isn't initialized
if (null_variant.isInitialized()) assert(false);
if (((Variant*)(&null_varNR))->isInitialized()) assert(false);
}
IMPLEMENT_SMART_ALLOCATION_NOCALLBACKS(Variant);
///////////////////////////////////////////////////////////////////////////////
// static strings
static StaticString s_offsetGet("offsetGet");
static StaticString s_offsetSet("offsetSet");
static StaticString s_offsetUnset("offsetUnset");
static StaticString s_s("s");
static StaticString s_scalar("scalar");
static StaticString s_array("Array");
static StaticString s_1("1");
static StaticString s_unserialize("unserialize");
static StaticString s_PHP_Incomplete_Class("__PHP_Incomplete_Class");
static StaticString s_PHP_Incomplete_Class_Name("__PHP_Incomplete_Class_Name");
///////////////////////////////////////////////////////////////////////////////
// local helpers
static int64 ToKey(bool i) { return (int64)i; }
static int64 ToKey(int64 i) { return i; }
static int64 ToKey(double d) { return (int64)d; }
static VarNR ToKey(CStrRef s) { return s.toKey(); }
static VarNR ToKey(CVarRef v) { return v.toKey(); }
///////////////////////////////////////////////////////////////////////////////
// private implementations
Variant::Variant(litstr v) : _count(0), m_type(KindOfString) {
m_data.pstr = NEW(StringData)(v);
m_data.pstr->incRefCount();
}
Variant::Variant(CStrRef v) : _count(0), m_type(KindOfString) {
StringData *s = v.get();
if (s) {
m_data.pstr = s;
if (s->isStatic()) {
m_type = KindOfStaticString;
} else {
s->incRefCount();
}
} else {
m_type = KindOfNull;
}
}
Variant::Variant(const std::string & v) : _count(0), m_type(KindOfString) {
StringData *s = NEW(StringData)(v.c_str(), v.size(), CopyString);
ASSERT(s);
m_data.pstr = s;
s->incRefCount();
}
HOT_FUNC
Variant::Variant(CArrRef v) : _count(0), m_type(KindOfArray) {
ArrayData *a = v.get();
if (a) {
m_data.parr = a;
a->incRefCount();
} else {
m_type = KindOfNull;
}
}
Variant::Variant(CObjRef v) : _count(0), m_type(KindOfObject) {
ObjectData *o = v.get();
if (o) {
m_data.pobj = o;
o->incRefCount();
} else {
m_type = KindOfNull;
}
}
Variant::Variant(StringData *v) : _count(0), m_type(KindOfString) {
if (v) {
m_data.pstr = v;
if (v->isStatic()) {
m_type = KindOfStaticString;
} else {
v->incRefCount();
}
} else {
m_type = KindOfNull;
}
}
Variant::Variant(ArrayData *v) : _count(0), m_type(KindOfArray) {
if (v) {
m_data.parr = v;
v->incRefCount();
} else {
m_type = KindOfNull;
}
}
Variant::Variant(ObjectData *v) : _count(0), m_type(KindOfObject) {
if (v) {
m_data.pobj = v;
v->incRefCount();
} else {
m_type = KindOfNull;
}
}
Variant::Variant(Variant *v) : _count(0), m_type(KindOfVariant) {
if (v) {
m_data.pvar = v;
} else {
m_type = KindOfNull;
}
}
// the version of the high frequency function that is not inlined
HOT_FUNC
Variant::Variant(CVarRef v) {
constructValHelper(v);
}
Variant::Variant(CVarStrongBind v) {
constructRefHelper(variant(v));
}
Variant::Variant(CVarWithRefBind v) {
constructWithRefHelper(variant(v), 0);
}
void Variant::reset() {
m_type = KindOfNull;
}
#ifdef FAST_REFCOUNT_FOR_VARIANT
static void destructString(void *p) { ((StringData *)p)->release(); }
static void destructArray(void *p) { ((ArrayData *)p)->release(); }
static void destructObject(void *p) { ((ObjectData *)p)->release(); }
static void destructVariant(void *p) { ((Variant *)p)->release(); }
static void (*destructors[4])(void *) =
{destructString, destructArray, destructObject, destructVariant};
#endif
inline ALWAYS_INLINE void Variant::destructImpl() {
ASSERT(!isPrimitive());
#ifdef FAST_REFCOUNT_FOR_VARIANT
/**
* This is safe because we have compile time assertions that guarantee that
* the _count field will always be exactly FAST_REFCOUNT_OFFSET bytes from
* the beginning of the object for the StringData, ArrayData, ObjectData,
* and Variant classes.
*/
CT_ASSERT(KindOfString + 1 == KindOfArray &&
KindOfArray + 1 == KindOfObject &&
KindOfObject + 1 == KindOfVariant);
if (m_data.pvar->decRefCount() == 0) {
ASSERT(m_type >= KindOfString && m_type <= KindOfVariant);
destructors[m_type - KindOfString]((void *)m_data.pvar);
}
#else
switch (m_type) {
case KindOfString:
if (m_data.pstr->decRefCount() == 0) {
m_data.pstr->release();
}
break;
case KindOfArray:
if (m_data.parr->decRefCount() == 0) {
m_data.parr->release();
}
break;
case KindOfObject:
if (m_data.pobj->decRefCount() == 0) {
m_data.pobj->release();
}
break;
case KindOfVariant:
if (m_data.pvar->decRefCount() == 0) {
m_data.pvar->release();
}
break;
default:
ASSERT(false);
break;
}
#endif
}
HOT_FUNC
void Variant::destruct() {
destructImpl();
}
HOT_FUNC
Variant::~Variant() {
if (IS_REFCOUNTED_TYPE(m_type)) destructImpl();
}
HOT_FUNC
Variant &Variant::assign(CVarRef v) {
AssignValHelper(this, &v);
return *this;
}
Variant &Variant::assignRef(CVarRef v) {
assignRefHelper(v);
return *this;
}
Variant &Variant::setWithRef(CVarRef v, const ArrayData *arr /* = NULL */) {
setWithRefHelper(v, arr, IS_REFCOUNTED_TYPE(m_type));
return *this;
}
void Variant::setNull() {
if (isPrimitive()) {
m_type = KindOfNull;
} else if (m_type == KindOfVariant) {
m_data.pvar->setNull();
} else {
destruct();
m_type = KindOfNull;
}
}
CVarRef Variant::set(bool v) {
if (isPrimitive()) {
// do nothing
} else if (m_type == KindOfVariant) {
m_data.pvar->set(v);
return *this;
} else {
destruct();
}
m_type = KindOfBoolean;
m_data.num = (v ? 1 : 0);
return *this;
}
CVarRef Variant::set(int v) {
if (isPrimitive()) {
// do nothing
} else if (m_type == KindOfVariant) {
m_data.pvar->set(v);
return *this;
} else {
destruct();
}
m_type = KindOfInt32;
m_data.num = v;
return *this;
}
CVarRef Variant::set(int64 v) {
if (isPrimitive()) {
// do nothing
} else if (m_type == KindOfVariant) {
m_data.pvar->set(v);
return *this;
} else {
destruct();
}
m_type = KindOfInt64;
m_data.num = v;
return *this;
}
CVarRef Variant::set(double v) {
if (isPrimitive()) {
// do nothing
} else if (m_type == KindOfVariant) {
m_data.pvar->set(v);
return *this;
} else {
destruct();
}
m_type = KindOfDouble;
m_data.dbl = v;
return *this;
}
CVarRef Variant::set(litstr v) {
if (isPrimitive()) {
// do nothing
} else if (m_type == KindOfVariant) {
m_data.pvar->set(v);
return *this;
} else {
destruct();
}
m_type = KindOfString;
m_data.pstr = NEW(StringData)(v);
m_data.pstr->incRefCount();
return *this;
}
CVarRef Variant::set(StringData *v) {
Variant *self = m_type == KindOfVariant ? m_data.pvar : this;
if (UNLIKELY(!v)) {
self->setNull();
} else {
v->incRefCount();
if (IS_REFCOUNTED_TYPE(self->m_type)) self->destruct();
self->m_type = v->isStatic() ? KindOfStaticString : KindOfString;
self->m_data.pstr = v;
}
return *this;
}
CVarRef Variant::set(const StaticString & v) {
if (isPrimitive()) {
// do nothing
} else if (m_type == KindOfVariant) {
m_data.pvar->set(v);
return *this;
} else {
destruct();
}
StringData *s = v.get();
ASSERT(s);
m_type = KindOfStaticString;
m_data.pstr = s;
return *this;
}
CVarRef Variant::set(ArrayData *v) {
Variant *self = m_type == KindOfVariant ? m_data.pvar : this;
if (UNLIKELY(!v)) {
self->setNull();
} else {
v->incRefCount();
if (IS_REFCOUNTED_TYPE(self->m_type)) self->destruct();
self->m_type = KindOfArray;
self->m_data.parr = v;
}
return *this;
}
CVarRef Variant::set(ObjectData *v) {
Variant *self = m_type == KindOfVariant ? m_data.pvar : this;
if (UNLIKELY(!v)) {
self->setNull();
} else {
v->incRefCount();
if (IS_REFCOUNTED_TYPE(self->m_type)) self->destruct();
self->m_type = KindOfObject;
self->m_data.pobj = v;
}
return *this;
}
void Variant::init(ObjectData *v) {
if (v) {
m_type = KindOfObject;
m_data.pobj = v;
v->incRefCount();
} else {
m_type = KindOfNull;
}
}
void Variant::split() {
switch (m_type) {
case KindOfVariant: m_data.pvar->split(); break;
// copy-on-write
case KindOfStaticString:
case KindOfString:
{
int len = m_data.pstr->size();
const char *copy = string_duplicate(m_data.pstr->data(), len);
set(NEW(StringData)(copy, len, AttachString));
break;
}
case KindOfArray: set(m_data.parr->copy()); break;
default:
break;
}
}
int64 Variant::hashForIntSwitch(int64 firstNonZero, int64 noMatch) const {
switch (m_type) {
case KindOfInt32:
case KindOfInt64:
return m_data.num;
case KindOfBoolean:
return m_data.num ? firstNonZero : 0;
case KindOfDouble:
return Variant::DoubleHashForIntSwitch(m_data.dbl, noMatch);
case KindOfUninit:
case KindOfNull:
// take care of the NULLs here, so below we can assume
// a non null m_data field
return 0;
case KindOfStaticString:
case KindOfString:
return m_data.pstr->hashForIntSwitch(firstNonZero, noMatch);
case KindOfArray:
return noMatch;
case KindOfObject:
return m_data.pobj->o_toInt64();
case KindOfVariant:
return m_data.pvar->hashForIntSwitch(firstNonZero, noMatch);
default:
break;
}
ASSERT(false);
return 0;
}
int64 Variant::DoubleHashForIntSwitch(double dbl, int64 noMatch) {
// only matches an int if it is integral, ie
// "50.00" -> 50
// "50.12" -> no match
int64 t = (int64) dbl;
return t == dbl ? t : noMatch;
}
int64 Variant::hashForStringSwitch(
int64 firstTrueCaseHash,
int64 firstNullCaseHash,
int64 firstFalseCaseHash,
int64 firstZeroCaseHash,
int64 firstHash,
int64 noMatchHash,
bool &needsOrder) const {
switch (m_type) {
case KindOfInt32:
case KindOfInt64:
needsOrder = false;
return m_data.num == 0 ? firstZeroCaseHash : m_data.num;
case KindOfBoolean:
needsOrder = false;
return m_data.num ? firstTrueCaseHash : firstFalseCaseHash;
case KindOfDouble:
needsOrder = false;
return m_data.dbl == 0 ? firstZeroCaseHash : toInt64();
case KindOfUninit:
case KindOfNull:
// take care of the NULLs here, so below we can assume
// a non null m_data field
needsOrder = false;
return firstNullCaseHash;
case KindOfStaticString:
case KindOfString:
return m_data.pstr->hashForStringSwitch(
firstTrueCaseHash, firstNullCaseHash, firstFalseCaseHash,
firstZeroCaseHash, firstHash, noMatchHash, needsOrder);
case KindOfArray:
needsOrder = false;
return noMatchHash;
case KindOfObject:
needsOrder = true;
return firstHash;
case KindOfVariant:
return m_data.pvar->hashForStringSwitch(
firstTrueCaseHash, firstNullCaseHash, firstFalseCaseHash,
firstZeroCaseHash, firstHash, noMatchHash, needsOrder);
default:
break;
}
ASSERT(false);
return 0;
}
int Variant::getRefCount() const {
switch (m_type) {
case KindOfString: return m_data.pstr->getCount();
case KindOfArray: return m_data.parr->getCount();
case KindOfObject: return m_data.pobj->getCount();
case KindOfVariant: return m_data.pvar->getRefCount();
default:
break;
}
return 1;
}
///////////////////////////////////////////////////////////////////////////////
// informational
bool Variant::isInteger() const {
switch (m_type) {
case KindOfInt32:
case KindOfInt64:
return true;
case KindOfVariant:
return m_data.pvar->isInteger();
default:
break;
}
return false;
}
bool Variant::isNumeric(bool checkString /* = false */) const {
int64 ival;
double dval;
DataType t = toNumeric(ival, dval, checkString);
return t == KindOfInt64 || t == KindOfDouble;
}
DataType Variant::toNumeric(int64 &ival, double &dval,
bool checkString /* = false */) const {
switch (m_type) {
case KindOfInt32:
case KindOfInt64:
ival = m_data.num;
return KindOfInt64;
case KindOfDouble:
dval = m_data.dbl;
return KindOfDouble;
case KindOfStaticString:
case KindOfString:
if (checkString) {
return m_data.pstr->toNumeric(ival, dval);
}
break;
case KindOfVariant:
return m_data.pvar->toNumeric(ival, dval, checkString);
default:
break;
}
return m_type;
}
bool Variant::isScalar() const {
switch (getType()) {
case KindOfUninit:
case KindOfNull:
case KindOfArray:
case KindOfObject:
return false;
default:
break;
}
return true;
}
bool Variant::isResource() const {
TypedValueAccessor acc = getTypedAccessor();
if (GetAccessorType(acc) == KindOfObject) {
return GetObjectData(acc)->isResource();
}
return false;
}
bool Variant::instanceof(CStrRef s) const {
if (m_type == KindOfObject) {
ASSERT(m_data.pobj);
return m_data.pobj->o_instanceof(s);
}
if (m_type == KindOfVariant) {
return m_data.pvar->instanceof(s);
}
return false;
}
///////////////////////////////////////////////////////////////////////////////
// array operations
Variant Variant::pop() {
if (m_type == KindOfVariant) {
return m_data.pvar->pop();
}
if (!is(KindOfArray)) {
throw_bad_type_exception("expecting an array");
return null_variant;
}
Variant ret;
ArrayData *newarr = getArrayData()->pop(ret);
if (newarr) {
set(newarr);
}
return ret;
}
Variant Variant::dequeue() {
if (m_type == KindOfVariant) {
return m_data.pvar->dequeue();
}
if (!is(KindOfArray)) {
throw_bad_type_exception("expecting an array");
return null_variant;
}
Variant ret;
ArrayData *newarr = getArrayData()->dequeue(ret);
if (newarr) {
set(newarr);
}
return ret;
}
void Variant::prepend(CVarRef v) {
if (m_type == KindOfVariant) {
m_data.pvar->prepend(v);
return;
}
if (isNull()) {
set(Array::Create());
}
if (is(KindOfArray)) {
ArrayData *arr = getArrayData();
ArrayData *newarr = arr->prepend(v, (arr->getCount() > 1));
if (newarr) {
set(newarr);
}
} else {
throw_bad_type_exception("expecting an array");
}
}
Variant Variant::array_iter_reset() {
if (is(KindOfArray)) {
ArrayData *arr = getArrayData();
if (arr->getCount() > 1 && !arr->isHead()
&& !arr->isGlobalArrayWrapper()) {
arr = arr->copy();
set(arr);
ASSERT(arr == getArrayData());
}
return arr->reset();
}
throw_bad_type_exception("expecting an array");
return false;
}
Variant Variant::array_iter_prev() {
if (is(KindOfArray)) {
ArrayData *arr = getArrayData();
if (arr->getCount() > 1 && !arr->isInvalid()
&& !arr->isGlobalArrayWrapper()) {
arr = arr->copy();
set(arr);
ASSERT(arr == getArrayData());
}
return arr->prev();
}
throw_bad_type_exception("expecting an array");
return false;
}
Variant Variant::array_iter_current() const {
if (is(KindOfArray)) {
return getArrayData()->current();
}
throw_bad_type_exception("expecting an array");
return false;
}
Variant Variant::array_iter_current_ref() {
if (is(KindOfArray)) {
escalate(true);
ArrayData *arr = getArrayData();
if (arr->getCount() > 1 && !arr->isGlobalArrayWrapper()) {
arr = arr->copy();
set(arr);
ASSERT(arr == getArrayData());
}
return strongBind(arr->currentRef());
}
throw_bad_type_exception("expecting an array");
return false;
}
Variant Variant::array_iter_next() {
if (is(KindOfArray)) {
ArrayData *arr = getArrayData();
if (arr->getCount() > 1 && !arr->isInvalid()
&& !arr->isGlobalArrayWrapper()) {
arr = arr->copy();
set(arr);
ASSERT(arr == getArrayData());
}
return arr->next();
}
throw_bad_type_exception("expecting an array");
return false;
}
Variant Variant::array_iter_end() {
if (is(KindOfArray)) {
ArrayData *arr = getArrayData();
if (arr->getCount() > 1 && !arr->isTail()
&& !arr->isGlobalArrayWrapper()) {
arr = arr->copy();
set(arr);
ASSERT(arr == getArrayData());
}
return arr->end();
}
throw_bad_type_exception("expecting an array");
return false;
}
Variant Variant::array_iter_key() const {
if (is(KindOfArray)) {
return getArrayData()->key();
}
throw_bad_type_exception("expecting an array");
return false;
}
Variant Variant::array_iter_each() {
if (is(KindOfArray)) {
ArrayData *arr = getArrayData();
if (arr->getCount() > 1 && !arr->isInvalid()
&& !arr->isGlobalArrayWrapper()) {
arr = arr->copy();
set(arr);
ASSERT(arr == getArrayData());
}
return arr->each();
}
throw_bad_type_exception("expecting an array");
return null_variant;
}
void Variant::array_iter_dirty_set() const {
if (is(KindOfArray)) {
getArrayData()->iter_dirty_set();
}
}
void Variant::array_iter_dirty_reset() const {
if (is(KindOfArray)) {
getArrayData()->iter_dirty_reset();
}
}
void Variant::array_iter_dirty_check() const {
if (is(KindOfArray)) {
getArrayData()->iter_dirty_check();
}
}
inline DataType Variant::convertToNumeric(int64 *lval, double *dval) const {
StringData *s = getStringData();
ASSERT(s);
return s->isNumericWithVal(*lval, *dval, 1);
}
///////////////////////////////////////////////////////////////////////////////
// unary plus
Variant Variant::operator+() const {
if (is(KindOfArray)) {
throw BadArrayOperandException();
}
if (isDouble()) {
return toDouble();
}
if (isIntVal()) {
return toInt64();
}
if (isString()) {
int64 lval; double dval;
DataType ret = convertToNumeric(&lval, &dval);
if (ret == KindOfDouble) {
return dval;
}
if (ret == KindOfInt64) {
return lval;
}
return toInt64();
}
ASSERT(false);
return 0;
}
///////////////////////////////////////////////////////////////////////////////
// add or array append
Variant Variant::operator+(CVarRef var) const {
if (m_type == KindOfInt64 && var.m_type == KindOfInt64) {
return m_data.num + var.m_data.num;
}
if (isIntVal() && var.isIntVal()) {
return toInt64() + var.toInt64();
}
int na = is(KindOfArray) + var.is(KindOfArray);
if (na == 2) {
return toCArrRef() + var.toCArrRef();
} else if (na) {
throw BadArrayMergeException();
}
if (isDouble() || var.isDouble()) {
return toDouble() + var.toDouble();
}
if (isString()) {
int64 lval; double dval;
DataType ret = convertToNumeric(&lval, &dval);
if (ret == KindOfDouble) {
return dval + var.toDouble();
}
}
if (var.isString()) {
int64 lval; double dval;
DataType ret = var.convertToNumeric(&lval, &dval);
if (ret == KindOfDouble) {
return toDouble() + dval;
}
}
return toInt64() + var.toInt64();
}
Variant &Variant::operator+=(CVarRef var) {
if (m_type == KindOfInt64 && var.m_type == KindOfInt64) {
m_data.num += var.m_data.num;
return *this;
}
if (isIntVal() && var.isIntVal()) {
set(toInt64() + var.toInt64());
return *this;
}
int na = is(KindOfArray) + var.is(KindOfArray);
if (na == 2) {
ArrayData *arr1 = getArrayData();
ArrayData *arr2 = var.getArrayData();
if (arr1 == NULL || arr2 == NULL) {
throw BadArrayMergeException();
}
if (arr2->empty() || arr1 == arr2) return *this;
if (arr1->empty()) {
set(arr2);
return *this;
}
ArrayData *escalated = arr1->append(arr2, ArrayData::Plus,
arr1->getCount() > 1);
if (escalated) set(escalated);
return *this;
} else if (na) {
throw BadArrayMergeException();
}
if (isDouble() || var.isDouble()) {
set(toDouble() + var.toDouble());
return *this;
}
if (isString()) {
int64 lval; double dval;
DataType ret = convertToNumeric(&lval, &dval);
if (ret == KindOfDouble) {
set(dval + var.toDouble());
return *this;
}
}
if (var.isString()) {
int64 lval; double dval;
DataType ret = var.convertToNumeric(&lval, &dval);
if (ret == KindOfDouble) {
set(toDouble() + dval);
return *this;
}
}
set(toInt64() + var.toInt64());
return *this;
}
Variant &Variant::operator+=(int64 n) {
if (m_type == KindOfInt64) {
m_data.num += n;
return *this;
}
if (isIntVal()) {
set(toInt64() + n);
return *this;
}
if (isDouble()) {
set(toDouble() + n);
return *this;
}
if (is(KindOfArray)) {
throw BadArrayMergeException();
}
if (isString()) {
int64 lval; double dval;
DataType ret = convertToNumeric(&lval, &dval);
if (ret == KindOfDouble) {
set(dval + n);
return *this;
}
} else {
ASSERT(false);
}
set(toInt64() + n);
return *this;
}
Variant &Variant::operator+=(double n) {
if (is(KindOfArray)) {
throw BadArrayMergeException();
}
set(toDouble() + n);
return *this;
}
///////////////////////////////////////////////////////////////////////////////
// minus
Variant Variant::operator-() const {
if (is(KindOfArray)) {
throw BadArrayOperandException();
}
if (isDouble()) {
return -toDouble();
} else if (isIntVal()) {
return -toInt64();
} else {
if (isString()) {
int64 lval; double dval;
DataType ret = convertToNumeric(&lval, &dval);
if (ret == KindOfDouble) {
return -dval;
} else if (ret == KindOfInt64) {
return -lval;
} else {
return -toInt64();
}
} else {
ASSERT(false);
}
}
return *this;
}
Variant Variant::operator-(CVarRef var) const {
if (is(KindOfArray) || var.is(KindOfArray)) {
throw BadArrayOperandException();
}
if (isDouble() || var.isDouble()) {
return toDouble() - var.toDouble();
}
if (isIntVal() && var.isIntVal()) {
return toInt64() - var.toInt64();
}
if (isString()) {
int64 lval; double dval;
DataType ret = convertToNumeric(&lval, &dval);
if (ret == KindOfDouble) {
return dval - var.toDouble();
}
}
if (var.isString()) {
int64 lval; double dval;
DataType ret = var.convertToNumeric(&lval, &dval);
if (ret == KindOfDouble) {
return toDouble() - dval;
}
}
return toInt64() - var.toInt64();
}
Variant &Variant::operator-=(CVarRef var) {
if (is(KindOfArray) || var.is(KindOfArray)) {
throw BadArrayOperandException();
}
if (isDouble() || var.isDouble()) {
set(toDouble() - var.toDouble());
} else if (isIntVal() && var.isIntVal()) {
set(toInt64() - var.toInt64());
} else {
if (isString()) {
int64 lval; double dval;
DataType ret = convertToNumeric(&lval, &dval);
if (ret == KindOfDouble) {
set(dval - var.toDouble());
return *this;
}
}
if (var.isString()) {
int64 lval; double dval;
DataType ret = var.convertToNumeric(&lval, &dval);
if (ret == KindOfDouble) {
set(toDouble() - dval);
return *this;
}
}
set(toInt64() - var.toInt64());
}
return *this;
}
Variant &Variant::operator-=(int64 n) {
if (is(KindOfArray)) {
throw BadArrayOperandException();
}
if (isDouble()) {
set(toDouble() - n);
} else if (isIntVal()) {
set(toInt64() - n);
} else {
if (isString()) {
int64 lval; double dval;
DataType ret = convertToNumeric(&lval, &dval);
if (ret == KindOfDouble) {
set(dval - n);
return *this;
}
} else {
ASSERT(false);
}
set(toInt64() - n);
}
return *this;
}
Variant &Variant::operator-=(double n) {
if (is(KindOfArray)) {
throw BadArrayOperandException();
}
set(toDouble() - n);
return *this;
}
///////////////////////////////////////////////////////////////////////////////
// multiply
Variant Variant::operator*(CVarRef var) const {
if (is(KindOfArray) || var.is(KindOfArray)) {
throw BadArrayOperandException();
}
if (isDouble() || var.isDouble()) {
return toDouble() * var.toDouble();
}
if (isIntVal() && var.isIntVal()) {
return toInt64() * var.toInt64();
}
if (isString()) {
int64 lval; double dval;
DataType ret = convertToNumeric(&lval, &dval);
if (ret == KindOfDouble) {
return dval * var.toDouble();
}
}
if (var.isString()) {
int64 lval; double dval;
DataType ret = var.convertToNumeric(&lval, &dval);
if (ret == KindOfDouble) {
return toDouble() * dval;
}
}
return toInt64() * var.toInt64();
}
Variant &Variant::operator*=(CVarRef var) {
if (is(KindOfArray) || var.is(KindOfArray)) {
throw BadArrayOperandException();
}
if (isDouble() || var.isDouble()) {
set(toDouble() * var.toDouble());
} else if (isIntVal() && var.isIntVal()) {
set(toInt64() * var.toInt64());
} else {
if (isString()) {
int64 lval; double dval;
DataType ret = convertToNumeric(&lval, &dval);
if (ret == KindOfDouble) {
set(dval * var.toDouble());
return *this;
}
}
if (var.isString()) {
int64 lval; double dval;
DataType ret = var.convertToNumeric(&lval, &dval);
if (ret == KindOfDouble) {
set(toDouble() * dval);
return *this;
}
}
set(toInt64() * var.toInt64());
}
return *this;
}
Variant &Variant::operator*=(int64 n) {
if (is(KindOfArray)) {
throw BadArrayOperandException();
}
if (isDouble()) {
set(toDouble() * n);
} else if (isIntVal()) {
set(toInt64() * n);
} else {
if (isString()) {
int64 lval; double dval;
DataType ret = convertToNumeric(&lval, &dval);
if (ret == KindOfDouble) {
set(dval * n);
return *this;
}
} else {
ASSERT(false);
}
set(toInt64() * n);
}
return *this;
}
Variant &Variant::operator*=(double n) {
if (is(KindOfArray)) {
throw BadArrayOperandException();
}
set(toDouble() * n);
return *this;
}
///////////////////////////////////////////////////////////////////////////////
// divide
Variant Variant::operator/(CVarRef var) const {
if (is(KindOfArray) || var.is(KindOfArray)) {
throw BadArrayOperandException();
}
int64 lval; double dval; bool int1 = true;
int64 lval2; double dval2; bool int2 = true;
if (isDouble()) {
dval = toDouble();
int1 = false;
} else if (isIntVal()) {
lval = toInt64();
} else if (isString()) {
DataType ret = convertToNumeric(&lval, &dval);
if (ret == KindOfDouble) {
int1 = false;
} else if (ret != KindOfInt64) {
lval = 0;
}
} else {
ASSERT(false);
}
if (var.isDouble()) {
dval2 = var.toDouble();
int2 = false;
} else if (var.isIntVal()) {
lval2 = var.toInt64();
} else if (var.isString()) {
DataType ret = var.convertToNumeric(&lval2, &dval2);
if (ret == KindOfDouble) {
int2 = false;
} else if (ret != KindOfInt64) {
lval2 = 0;
}
} else {
ASSERT(false);
}
if ((int2 && lval2 == 0) || (!int2 && dval2 == 0)) {
raise_warning("Division by zero");
return false;
}
if (int1 && int2) {
if (lval % lval2 == 0) {
return lval / lval2;
} else {
return (double)lval / lval2;
}
} else if (int1 && !int2) {
return lval / dval2;
} else if (!int1 && int2) {
return dval / lval2;
} else {
return dval / dval2;
}
}
Variant &Variant::operator/=(CVarRef var) {
if (is(KindOfArray) || var.is(KindOfArray)) {
throw BadArrayOperandException();
}
int64 lval; double dval; bool int1 = true;
int64 lval2; double dval2; bool int2 = true;
if (isDouble()) {
dval = toDouble();
int1 = false;
} else if (isIntVal()) {
lval = toInt64();
} else if (isString()) {
DataType ret = convertToNumeric(&lval, &dval);
if (ret == KindOfDouble) {
int1 = false;
} else if (ret != KindOfInt64) {
lval = 0;
}
} else {
ASSERT(false);
}
if (var.isDouble()) {
dval2 = var.toDouble();
int2 = false;
} else if (var.isIntVal()) {
lval2 = var.toInt64();
} else if (var.isString()) {
DataType ret = var.convertToNumeric(&lval2, &dval2);
if (ret == KindOfDouble) {
int2 = false;
} else if (ret != KindOfInt64) {
lval2 = 0;
}
} else {
ASSERT(false);
}
if ((int2 && lval2 == 0) || (!int2 && dval2 == 0)) {
raise_warning("Division by zero");
set(false);
return *this;
}
if (int1 && int2) {
if (lval % lval2 == 0) {
set(lval / lval2);
} else {
set((double)lval / lval2);
}
} else if (int1 && !int2) {
set(lval / dval2);
} else if (!int1 && int2) {
set(dval / lval2);
} else {
set(dval / dval2);
}
return *this;
}
Variant &Variant::operator/=(int64 n) {
if (is(KindOfArray)) {
throw BadArrayOperandException();
}
if (n == 0) {
raise_warning("Division by zero");
set(false);
return *this;
}
if (isIntVal() && toInt64() % n == 0) {
set(toInt64() / n);
} else if (isDouble()) {
set(toDouble() / n);
} else {
if (isString()) {
int64 lval; double dval;
DataType ret = convertToNumeric(&lval, &dval);
if (ret == KindOfInt64 && lval % n == 0) {
set(lval / n);
return *this;
}
}
set(toDouble() / n);
}
return *this;
}
Variant &Variant::operator/=(double n) {
if (is(KindOfArray)) {
throw BadArrayOperandException();
}
if (n == 0.0) {
raise_warning("Division by zero");
set(false);
return *this;
}
set(toDouble() / n);
return *this;
}
///////////////////////////////////////////////////////////////////////////////
// modulus
int64 Variant::operator%(CVarRef var) const {
int64 lval = toInt64();
int64 lval2 = var.toInt64();
if (lval2 == 0) {
raise_warning("Division by zero");
return false;
}
return lval % lval2;
}
Variant &Variant::operator%=(CVarRef var) {
int64 lval = toInt64();
int64 lval2 = var.toInt64();
if (lval2 == 0) {
raise_warning("Division by zero");
set(false);
return *this;
}
set(lval % lval2);
return *this;
}
Variant &Variant::operator%=(int64 n) {
if (n == 0) {
raise_warning("Division by zero");
set(false);
return *this;
}
set(toInt64() % n);
return *this;
}
Variant &Variant::operator%=(double n) {
if ((int64)n == 0) {
raise_warning("Division by zero");
set(false);
return *this;
}
set(toInt64() % (int64)n);
return *this;
}
///////////////////////////////////////////////////////////////////////////////
// bitwise
Variant Variant::operator~() const {
switch (getType()) {
case KindOfInt32:
case KindOfInt64:
return ~toInt64();
case KindOfDouble:
return ~(int64)(toDouble());
case KindOfStaticString:
case KindOfString:
return ~toString();
default:
break;
}
throw InvalidOperandException("only numerics and strings can be negated");
}
Variant Variant::operator|(CVarRef v) const {
if (isString() && v.isString()) {
return toString() | v.toString();
}
return toInt64() | v.toInt64();
}
Variant Variant::operator&(CVarRef v) const {
if (isString() && v.isString()) {
return toString() & v.toString();
}
return toInt64() & v.toInt64();
}
Variant Variant::operator^(CVarRef v) const {
if (isString() && v.isString()) {
return toString() ^ v.toString();
}
return toInt64() ^ v.toInt64();
}
Variant &Variant::operator|=(CVarRef v) {
if (isString() && v.isString()) {
set(toString() | v.toString());
} else {
set(toInt64() | v.toInt64());
}
return *this;
}
Variant &Variant::operator&=(CVarRef v) {
if (isString() && v.isString()) {
set(toString() & v.toString());
} else {
set(toInt64() & v.toInt64());
}
return *this;
}
Variant &Variant::operator^=(CVarRef v) {
if (isString() && v.isString()) {
set(toString() ^ v.toString());
} else {
set(toInt64() ^ v.toInt64());
}
return *this;
}
Variant &Variant::operator<<=(int64 n) {
set(toInt64() << n);
return *this;
}
Variant &Variant::operator>>=(int64 n) {
set(toInt64() >> n);
return *this;
}
///////////////////////////////////////////////////////////////////////////////
// increment/decrement
Variant &Variant::operator++() {
switch (getType()) {
case KindOfUninit:
case KindOfNull: set(1LL); break;
case KindOfInt32:
case KindOfInt64: set(toInt64() + 1); break;
case KindOfDouble: set(toDouble() + 1); break;
case KindOfStaticString:
case KindOfString:
{
if (getStringData()->empty()) {
set("1");
} else {
int64 lval; double dval;
DataType ret = convertToNumeric(&lval, &dval);
switch (ret) {
case KindOfInt64: set(lval + 1); break;
case KindOfDouble: set(dval + 1); break;
case KindOfUninit:
case KindOfNull:
split();
getStringData()->inc(); break;
default:
ASSERT(false);
break;
}
}
}
break;
default:
break;
}
return *this;
}
Variant Variant::operator++(int) {
Variant ret(*this);
operator++();
return ret;
}
Variant &Variant::operator--() {
switch (getType()) {
case KindOfInt32:
case KindOfInt64: set(toInt64() - 1); break;
case KindOfDouble: set(toDouble() - 1); break;
case KindOfStaticString:
case KindOfString:
{
if (getStringData()->empty()) {
set(-1LL);
} else {
int64 lval; double dval;
DataType ret = convertToNumeric(&lval, &dval);
switch (ret) {
case KindOfInt64: set(lval - 1); break;
case KindOfDouble: set(dval - 1); break;
case KindOfUninit:
case KindOfNull: /* do nothing */ break;
default:
ASSERT(false);
break;
}
}
}
break;
default:
break;
}
return *this;
}
Variant Variant::operator--(int) {
Variant ret(*this);
operator--();
return ret;
}
///////////////////////////////////////////////////////////////////////////////
// iterator functions
ArrayIter Variant::begin(CStrRef context /* = null_string */,
bool setIterDirty /* = false */) const {
if (is(KindOfArray)) {
if (setIterDirty) array_iter_dirty_set();
return ArrayIter(getArrayData());
}
if (is(KindOfObject)) {
return getObjectData()->begin(context);
}
raise_warning("Invalid argument supplied for foreach()");
return ArrayIter();
}
MutableArrayIter Variant::begin(Variant *key, Variant &val,
CStrRef context /* = null_string */,
bool setIterDirty /* = false */) {
if (is(KindOfObject)) {
return getObjectData()->begin(key, val, context);
}
// we are about to modify an array that has other weak references, so
// we have to make a copy to preserve other instances
if (is(KindOfArray)) {
if (setIterDirty) array_iter_dirty_set();
ArrayData *arr = getArrayData();
if (arr->getCount() > 1 && !arr->isGlobalArrayWrapper()) {
set(arr->copy());
}
}
return MutableArrayIter(this, key, val);
}
void Variant::escalate(bool mutableIteration /* = false */) {
TypedValueAccessor tva = getTypedAccessor();
if (GetAccessorType(tva) == KindOfArray) {
ArrayData *arr = GetArrayData(tva);
ArrayData *esc = arr->escalate(mutableIteration);
if (arr != esc) set(esc);
}
}
///////////////////////////////////////////////////////////////////////////////
// type conversions
HOT_FUNC
bool Variant::toBooleanHelper() const {
ASSERT(m_type > KindOfInt64);
switch (m_type) {
case KindOfDouble: return m_data.dbl != 0;
case KindOfStaticString:
case KindOfString: return m_data.pstr->toBoolean();
case KindOfArray: return !m_data.parr->empty();
case KindOfObject: return m_data.pobj->o_toBoolean();
case KindOfVariant: return m_data.pvar->toBoolean();
default:
ASSERT(false);
break;
}
return m_data.num;
}
int64 Variant::toInt64Helper(int base /* = 10 */) const {
ASSERT(m_type > KindOfInt64);
switch (m_type) {
case KindOfDouble: {
return (m_data.dbl > LONG_MAX) ? (uint64)m_data.dbl : (int64)m_data.dbl;
}
case KindOfStaticString:
case KindOfString: return m_data.pstr->toInt64(base);
case KindOfArray: return m_data.parr->empty() ? 0 : 1;
case KindOfObject: return m_data.pobj->o_toInt64();
case KindOfVariant: return m_data.pvar->toInt64(base);
default:
ASSERT(false);
break;
}
return m_data.num;
}
double Variant::toDoubleHelper() const {
switch (m_type) {
case KindOfUninit:
case KindOfNull: return 0.0;
case KindOfDouble: return m_data.dbl;
case KindOfStaticString:
case KindOfString: return m_data.pstr->toDouble();
case KindOfObject: return m_data.pobj->o_toDouble();
case KindOfVariant: return m_data.pvar->toDouble();
default:
break;
}
return (double)toInt64();
}
String Variant::toStringHelper() const {
switch (m_type) {
case KindOfUninit:
case KindOfNull: return empty_string;
case KindOfBoolean: return m_data.num ? s_1 : empty_string;
case KindOfDouble: return m_data.dbl;
case KindOfStaticString:
case KindOfString:
ASSERT(false); // Should be done in caller
return m_data.pstr;
case KindOfArray: return s_array;
case KindOfObject: return m_data.pobj->t___tostring();
case KindOfVariant: return m_data.pvar->toString();
default:
break;
}
return m_data.num;
}
Array Variant::toArrayHelper() const {
switch (m_type) {
case KindOfUninit:
case KindOfNull: return Array::Create();
case KindOfInt64: return Array::Create(m_data.num);
case KindOfStaticString:
case KindOfString: return Array::Create(m_data.pstr);
case KindOfArray: return m_data.parr;
case KindOfObject: return m_data.pobj->o_toArray();
case KindOfVariant: return m_data.pvar->toArray();
default:
break;
}
return Array::Create(*this);
}
Object Variant::toObjectHelper() const {
if (m_type == KindOfVariant) return m_data.pvar->toObject();
switch (m_type) {
case KindOfUninit:
case KindOfNull:
break;
case KindOfBoolean:
case KindOfInt32:
case KindOfInt64:
case KindOfDouble:
case KindOfStaticString:
case KindOfString:
{
ObjectData *obj = SystemLib::AllocStdClassObject();
obj->o_set(s_scalar, *this, false);
return obj;
}
case KindOfArray: return m_data.parr->toObject();
case KindOfObject: return m_data.pobj;
default:
ASSERT(false);
break;
}
return Object(SystemLib::AllocStdClassObject());
}
HOT_FUNC
VarNR Variant::toKey() const {
if (m_type == KindOfString || m_type == KindOfStaticString) {
int64 n;
if (m_data.pstr->isStrictlyInteger(n)) {
return n;
} else {
return m_data.pstr;
}
}
switch (m_type) {
case KindOfUninit:
case KindOfNull:
return empty_string;
case KindOfBoolean:
case KindOfInt32:
case KindOfInt64:
return m_data.num;
case KindOfDouble:
return (int64)m_data.dbl;
case KindOfObject:
if (isResource()) {
return toInt64();
}
break;
case KindOfVariant:
return m_data.pvar->toKey();
default:
break;
}
throw_bad_type_exception("Invalid type used as key");
return null_varNR;
}
Variant::operator String() const {
return toString();
}
Variant::operator Array() const {
return toArray();
}
Variant::operator Object() const {
return toObject();
}
///////////////////////////////////////////////////////////////////////////////
// comparisons
bool Variant::same(bool v2) const {
return isBoolean() && HPHP::equal(v2, getBoolean());
}
bool Variant::same(int v2) const {
return same((int64)v2);
}
bool Variant::same(int64 v2) const {
TypedValueAccessor acc = getTypedAccessor();
switch (GetAccessorType(acc)) {
case KindOfInt32:
case KindOfInt64:
return HPHP::equal(v2, GetInt64(acc));
default:
break;
}
return false;
}
bool Variant::same(double v2) const {
return isDouble() && HPHP::equal(v2, getDouble());
}
bool Variant::same(litstr v2) const {
StringData sd2(v2);
return same(&sd2);
}
bool Variant::same(const StringData *v2) const {
bool null1 = isNull();
bool null2 = (v2 == NULL);
if (null1 && null2) return true;
if (null1 || null2) return false;
return isString() && HPHP::same(getStringData(), v2);
}
bool Variant::same(CStrRef v2) const {
return same(v2.get());
}
bool Variant::same(CArrRef v2) const {
bool null1 = isNull();
bool null2 = v2.isNull();
if (null1 && null2) return true;
if (null1 || null2) return false;
return is(KindOfArray) && Array(getArrayData()).same(v2);
}
bool Variant::same(CObjRef v2) const {
bool null1 = isNull();
bool null2 = v2.isNull();
if (null1 && null2) return true;
if (null1 || null2) return false;
return is(KindOfObject) && getObjectData() == v2.get();
}
bool Variant::same(CVarRef v2) const {
bool null1 = isNull();
bool null2 = v2.isNull();
if (null1 && null2) return true;
if (null1 || null2) return false;
TypedValueAccessor acc = getTypedAccessor();
switch (GetAccessorType(acc)) {
case KindOfInt32:
case KindOfInt64: {
TypedValueAccessor acc2 = v2.getTypedAccessor();
switch (GetAccessorType(acc2)) {
case KindOfInt32:
case KindOfInt64:
return HPHP::equal(GetInt64(acc), GetInt64(acc2));
default:
break;
}
break;
}
case KindOfStaticString:
case KindOfString: {
TypedValueAccessor acc2 = v2.getTypedAccessor();
switch (GetAccessorType(acc2)) {
case KindOfStaticString:
case KindOfString:
return GetStringData(acc)->same(v2.GetStringData(acc2));
default:
return false;
}
}
case KindOfArray:
if (v2.is(KindOfArray)) {
return Array(getArrayData()).same(Array(v2.getArrayData()));
}
break;
case KindOfObject:
return v2.is(KindOfObject) && getObjectData() == v2.getObjectData();
default:
break;
}
return getType() == v2.getType() && equal(v2);
}
///////////////////////////////////////////////////////////////////////////////
#define UNWRAP(reverse) \
TypedValueAccessor acc = getTypedAccessor(); \
switch (GetAccessorType(acc)) { \
case KindOfUninit: \
case KindOfNull: return HPHP::reverse(v2, false); \
case KindOfBoolean: return HPHP::reverse(v2, GetBoolean(acc)); \
case KindOfInt32: \
case KindOfInt64: return HPHP::reverse(v2, GetInt64(acc)); \
case KindOfDouble: return HPHP::reverse(v2, GetDouble(acc)); \
case KindOfStaticString: \
case KindOfString: return HPHP::reverse(v2, GetStringData(acc)); \
case KindOfArray: return HPHP::reverse(v2, Array(GetArrayData(acc))); \
case KindOfObject: return HPHP::reverse(v2, Object(GetObjectData(acc)));\
default: \
ASSERT(false); \
break; \
} \
return false; \
// "null" needs to convert to "" before comparing with a string
#define UNWRAP_STR(reverse) \
TypedValueAccessor acc = getTypedAccessor(); \
switch (GetAccessorType(acc)) { \
case KindOfUninit: \
case KindOfNull: return HPHP::reverse(v2, empty_string); \
case KindOfBoolean: return HPHP::reverse(v2, GetBoolean(acc)); \
case KindOfInt32: \
case KindOfInt64: return HPHP::reverse(v2, GetInt64(acc)); \
case KindOfDouble: return HPHP::reverse(v2, GetDouble(acc)); \
case KindOfStaticString: \
case KindOfString: return HPHP::reverse(v2, GetStringData(acc)); \
case KindOfArray: return HPHP::reverse(v2, Array(GetArrayData(acc))); \
case KindOfObject: return HPHP::reverse(v2, Object(GetObjectData(acc)));\
default: \
ASSERT(false); \
break; \
} \
return false; \
// Array needs to convert to "Array" and Object to String
#define UNWRAP_STRING(reverse) \
TypedValueAccessor acc = getTypedAccessor(); \
switch (GetAccessorType(acc)) { \
case KindOfUninit: \
case KindOfNull: return HPHP::reverse(v2, empty_string); \
case KindOfBoolean: return HPHP::reverse(v2, GetBoolean(acc)); \
case KindOfInt32: \
case KindOfInt64: return HPHP::reverse(v2, GetInt64(acc)); \
case KindOfDouble: return HPHP::reverse(v2, GetDouble(acc)); \
case KindOfStaticString: \
case KindOfString: return HPHP::reverse(v2, GetStringData(acc)); \
case KindOfArray: return HPHP::reverse(v2, s_array); \
case KindOfObject: \
return HPHP::reverse(v2, Object(GetObjectData(acc)).toString()); \
default: \
ASSERT(false); \
break; \
} \
return false; \
// "null" needs to convert to "" before comparing with a string
#define UNWRAP_VAR(forward, reverse) \
TypedValueAccessor acc = getTypedAccessor(); \
switch (GetAccessorType(acc)) { \
case KindOfUninit: \
case KindOfNull: \
if (v2.isString()) { \
return HPHP::reverse(v2.getStringData(), empty_string); \
} \
return HPHP::reverse(v2, false); \
case KindOfBoolean: return HPHP::reverse(v2, GetBoolean(acc)); \
case KindOfInt32: \
case KindOfInt64: return HPHP::reverse(v2, GetInt64(acc)); \
case KindOfDouble: return HPHP::reverse(v2, GetDouble(acc)); \
case KindOfStaticString: \
case KindOfString: return HPHP::reverse(v2, GetStringData(acc)); \
case KindOfArray: \
if (v2.isArray()) { \
return Array(GetArrayData(acc)).forward(Array(v2.getArrayData())); \
} \
return HPHP::reverse(v2, Array(GetArrayData(acc))); \
case KindOfObject: return HPHP::reverse(v2, Object(GetObjectData(acc)));\
default: \
ASSERT(false); \
break; \
} \
return false; \
// array comparison is directional when they are uncomparable
// also, ">" is implemented as "!<=" in Zend
#define UNWRAP_ARR(forward, reverse) \
TypedValueAccessor acc = getTypedAccessor(); \
switch (GetAccessorType(acc)) { \
case KindOfUninit: \
case KindOfNull: return HPHP::reverse(v2, false); \
case KindOfBoolean: return HPHP::reverse(v2, GetBoolean(acc)); \
case KindOfInt32: \
case KindOfInt64: return HPHP::reverse(v2, GetInt64(acc)); \
case KindOfDouble: return HPHP::reverse(v2, GetDouble(acc)); \
case KindOfStaticString: \
case KindOfString: return HPHP::reverse(v2, GetStringData(acc)); \
case KindOfArray: return Array(GetArrayData(acc)).forward(v2); \
case KindOfObject: return HPHP::reverse(v2, Object(GetObjectData(acc)));\
default: \
ASSERT(false); \
break; \
} \
return false; \
bool Variant::equal(bool v2) const { UNWRAP(equal);}
bool Variant::equal(int v2) const { UNWRAP(equal);}
bool Variant::equal(int64 v2) const { UNWRAP(equal);}
bool Variant::equal(double v2) const { UNWRAP(equal);}
bool Variant::equal(litstr v2) const { UNWRAP_STR(equal);}
bool Variant::equal(const StringData *v2) const { UNWRAP_STR(equal);}
bool Variant::equal(CStrRef v2) const { UNWRAP_STR(equal);}
bool Variant::equal(CArrRef v2) const { UNWRAP(equal);}
bool Variant::equal(CObjRef v2) const { UNWRAP(equal);}
bool Variant::equal(CVarRef v2) const { UNWRAP_VAR(equal,equal);}
bool Variant::equalAsStr(bool v2) const { UNWRAP_STRING(equalAsStr);}
bool Variant::equalAsStr(int v2) const { UNWRAP_STRING(equalAsStr);}
bool Variant::equalAsStr(int64 v2) const { UNWRAP_STRING(equalAsStr);}
bool Variant::equalAsStr(double v2) const { UNWRAP_STRING(equalAsStr);}
bool Variant::equalAsStr(litstr v2) const { UNWRAP_STRING(equalAsStr);}
bool Variant::equalAsStr(const StringData *v2) const {
UNWRAP_STRING(equalAsStr);
}
bool Variant::equalAsStr(CStrRef v2) const { UNWRAP_STRING(equalAsStr);}
bool Variant::equalAsStr(CArrRef v2) const { UNWRAP_STRING(equalAsStr);}
bool Variant::equalAsStr(CObjRef v2) const { UNWRAP_STRING(equalAsStr);}
bool Variant::equalAsStr(CVarRef v2) const { UNWRAP_STRING(equalAsStr);}
bool Variant::less(bool v2) const { UNWRAP(more);}
bool Variant::less(int v2) const { UNWRAP(more);}
bool Variant::less(int64 v2) const { UNWRAP(more);}
bool Variant::less(double v2) const { UNWRAP(more);}
bool Variant::less(litstr v2) const { UNWRAP_STR(more);}
bool Variant::less(const StringData *v2) const { UNWRAP_STR(more);}
bool Variant::less(CStrRef v2) const { UNWRAP_STR(more);}
bool Variant::less(CArrRef v2) const { UNWRAP_ARR(less,more);}
bool Variant::less(CObjRef v2) const { UNWRAP(more);}
bool Variant::less(CVarRef v2) const { UNWRAP_VAR(less,more);}
bool Variant::more(bool v2) const { UNWRAP(less);}
bool Variant::more(int v2) const { UNWRAP(less);}
bool Variant::more(int64 v2) const { UNWRAP(less);}
bool Variant::more(double v2) const { UNWRAP(less);}
bool Variant::more(litstr v2) const { UNWRAP_STR(less);}
bool Variant::more(const StringData *v2) const { UNWRAP_STR(less);}
bool Variant::more(CStrRef v2) const { UNWRAP_STR(less);}
bool Variant::more(CArrRef v2) const { UNWRAP_ARR(more,less);}
bool Variant::more(CObjRef v2) const { UNWRAP(less);}
bool Variant::more(CVarRef v2) const { UNWRAP_VAR(more,less);}
///////////////////////////////////////////////////////////////////////////////
// comparison operators
bool Variant::operator==(CVarRef v) const {
return HPHP::equal(*this, v);
}
bool Variant::operator!=(CVarRef v) const {
return !HPHP::equal(*this, v);
}
bool Variant::operator>=(CVarRef v) const {
return not_less(*this, v);
}
bool Variant::operator<=(CVarRef v) const {
return not_more(*this, v);
}
bool Variant::operator>(CVarRef v) const {
return HPHP::more(*this, v);
}
bool Variant::operator<(CVarRef v) const {
return HPHP::less(*this, v);
}
///////////////////////////////////////////////////////////////////////////////
// offset functions
ObjectData *Variant::getArrayAccess() const {
ASSERT(is(KindOfObject));
ObjectData *obj = getObjectData();
ASSERT(obj);
if (!obj->o_instanceof("ArrayAccess")) {
throw InvalidOperandException("not ArrayAccess objects");
}
return obj;
}
void Variant::callOffsetUnset(CVarRef key) {
getArrayAccess()->o_invoke(s_offsetUnset, Array::Create(key));
}
static void raise_bad_offset_notice() {
if (RuntimeOption::EnableHipHopErrors) {
raise_notice("taking offset [] on bool or number");
}
}
#define IMPLEMENT_RVAL_INTEGRAL \
if (m_type == KindOfArray) { \
return m_data.parr->get((int64)offset, flags & AccessFlags::Error); \
} \
switch (m_type) { \
case KindOfStaticString: \
case KindOfString: \
return m_data.pstr->getChar((int)offset); \
case KindOfObject: \
return getArrayAccess()->o_invoke(s_offsetGet, \
Array::Create(offset)); \
case KindOfVariant: \
return m_data.pvar->rvalAt(offset, flags); \
case KindOfUninit: \
case KindOfNull: \
break; \
default: \
if (flags & AccessFlags::Error) { \
raise_bad_offset_notice(); \
} \
break; \
} \
return null_variant;
Variant Variant::rvalAt(bool offset, ACCESSPARAMS_IMPL) const {
IMPLEMENT_RVAL_INTEGRAL
}
Variant Variant::rvalAt(double offset, ACCESSPARAMS_IMPL) const {
IMPLEMENT_RVAL_INTEGRAL
}
Variant Variant::rvalAtHelper(int64 offset, ACCESSPARAMS_IMPL) const {
switch (m_type) {
case KindOfStaticString:
case KindOfString:
return m_data.pstr->getChar((int)offset);
case KindOfObject:
return getArrayAccess()->o_invoke(s_offsetGet, Array::Create(offset));
case KindOfVariant:
return m_data.pvar->rvalAt(offset, flags);
case KindOfUninit:
case KindOfNull:
break;
default:
if (flags & AccessFlags::Error) {
raise_bad_offset_notice();
}
break;
}
return null_variant;
}
Variant Variant::rvalAt(litstr offset, ACCESSPARAMS_IMPL) const {
if (m_type == KindOfArray) {
bool error = flags & AccessFlags::Error;
if (flags & AccessFlags::Key) {
return m_data.parr->get(offset, error);
}
int64 n;
int len = strlen(offset);
if (!is_strictly_integer(offset, len, n)) {
return m_data.parr->get(offset, error);
} else {
return m_data.parr->get(n, error);
}
}
switch (m_type) {
case KindOfStaticString:
case KindOfString:
return m_data.pstr->getChar(StringData(offset).toInt32());
case KindOfObject:
return getArrayAccess()->o_invoke(s_offsetGet, Array::Create(offset));
case KindOfVariant:
return m_data.pvar->rvalAt(offset, flags);
case KindOfUninit:
case KindOfNull:
break;
default:
if (flags & AccessFlags::Error) {
raise_bad_offset_notice();
}
break;
}
return null_variant;
}
Variant Variant::rvalAt(CStrRef offset, ACCESSPARAMS_IMPL) const {
if (m_type == KindOfArray) {
bool error = flags & AccessFlags::Error;
if (flags & AccessFlags::Key) {
return m_data.parr->get(offset, error);
}
if (offset.isNull()) return m_data.parr->get(empty_string, error);
int64 n;
if (!offset->isStrictlyInteger(n)) {
return m_data.parr->get(offset, error);
} else {
return m_data.parr->get(n, error);
}
}
switch (m_type) {
case KindOfStaticString:
case KindOfString:
return m_data.pstr->getChar(offset.toInt32());
case KindOfObject:
return getArrayAccess()->o_invoke(s_offsetGet, Array::Create(offset));
case KindOfVariant:
return m_data.pvar->rvalAt(offset, flags);
case KindOfUninit:
case KindOfNull:
break;
default:
if (flags & AccessFlags::Error) {
raise_bad_offset_notice();
}
break;
}
return null_variant;
}
Variant Variant::rvalAt(CVarRef offset, ACCESSPARAMS_IMPL) const {
if (m_type == KindOfArray) {
// Fast path for KindOfArray
switch (offset.m_type) {
case KindOfUninit:
case KindOfNull:
return m_data.parr->get(empty_string, flags & AccessFlags::Error);
case KindOfBoolean:
case KindOfInt32:
case KindOfInt64:
return m_data.parr->get(offset.m_data.num, flags & AccessFlags::Error);
case KindOfDouble:
return m_data.parr->get((int64)offset.m_data.dbl,
flags & AccessFlags::Error);
case KindOfStaticString:
case KindOfString: {
int64 n;
if (offset.m_data.pstr->isStrictlyInteger(n)) {
return m_data.parr->get(n, flags & AccessFlags::Error);
} else {
return m_data.parr->get(offset.asCStrRef(), flags & AccessFlags::Error);
}
}
case KindOfArray:
throw_bad_type_exception("Invalid type used as key");
break;
case KindOfObject:
if (offset.isResource()) {
return m_data.parr->get(offset.toInt64(), flags & AccessFlags::Error);
}
throw_bad_type_exception("Invalid type used as key");
break;
case KindOfVariant:
return rvalAt(*(offset.m_data.pvar), flags);
default:
ASSERT(false);
break;
}
return null_variant;
}
switch (m_type) {
case KindOfStaticString:
case KindOfString:
return m_data.pstr->getChar(offset.toInt32());
case KindOfObject:
return getArrayAccess()->o_invoke(s_offsetGet, Array::Create(offset));
case KindOfVariant:
return m_data.pvar->rvalAt(offset, flags);
case KindOfUninit:
case KindOfNull:
break;
default:
if (flags & AccessFlags::Error) {
raise_bad_offset_notice();
}
break;
}
return null_variant;
}
template <typename T>
CVarRef Variant::rvalRefHelper(T offset, CVarRef tmp, ACCESSPARAMS_IMPL) const {
switch (m_type) {
case KindOfStaticString:
case KindOfString:
const_cast<Variant&>(tmp) = m_data.pstr->getChar(HPHP::toInt32(offset));
return tmp;
case KindOfObject:
const_cast<Variant&>(tmp) =
getArrayAccess()->o_invoke(s_offsetGet, Array::Create(offset));
return tmp;
case KindOfVariant:
return m_data.pvar->rvalRef(offset, tmp, flags);
case KindOfUninit:
case KindOfNull:
break;
default:
if (flags & AccessFlags::Error) {
raise_bad_offset_notice();
}
break;
}
return null_variant;
}
template CVarRef
Variant::rvalRefHelper(int64 offset, CVarRef tmp, ACCESSPARAMS_IMPL) const;
CVarRef Variant::rvalRef(double offset, CVarRef tmp, ACCESSPARAMS_IMPL) const {
return rvalRef((int64)offset, tmp, flags);
}
CVarRef Variant::rvalRef(litstr offset, CVarRef tmp, ACCESSPARAMS_IMPL) const {
if (m_type == KindOfArray) {
bool error = flags & AccessFlags::Error;
if (flags & AccessFlags::Key) return m_data.parr->get(offset, error);
int64 n;
int len = strlen(offset);
if (!is_strictly_integer(offset, len, n)) {
return m_data.parr->get(offset, error);
} else {
return m_data.parr->get(n, error);
}
}
return rvalRefHelper(offset, tmp, flags);
}
CVarRef Variant::rvalRef(CStrRef offset, CVarRef tmp, ACCESSPARAMS_IMPL) const {
if (m_type == KindOfArray) {
bool error = flags & AccessFlags::Error;
if (flags & AccessFlags::Key) return m_data.parr->get(offset, error);
if (offset.isNull()) return m_data.parr->get(empty_string, error);
int64 n;
if (!offset->isStrictlyInteger(n)) {
return m_data.parr->get(offset, error);
} else {
return m_data.parr->get(n, error);
}
}
return rvalRefHelper(offset, tmp, flags);
}
CVarRef Variant::rvalRef(CVarRef offset, CVarRef tmp, ACCESSPARAMS_IMPL) const {
if (m_type == KindOfArray) {
// Fast path for KindOfArray
switch (offset.m_type) {
case KindOfUninit:
case KindOfNull:
return m_data.parr->get(empty_string, flags & AccessFlags::Error);
case KindOfBoolean:
case KindOfInt32:
case KindOfInt64:
return m_data.parr->get(offset.m_data.num, flags & AccessFlags::Error);
case KindOfDouble:
return m_data.parr->get((int64)offset.m_data.dbl,
flags & AccessFlags::Error);
case KindOfStaticString:
case KindOfString: {
int64 n;
if (offset.m_data.pstr->isStrictlyInteger(n)) {
return m_data.parr->get(n, flags & AccessFlags::Error);
} else {
return m_data.parr->get(offset.asCStrRef(), flags & AccessFlags::Error);
}
}
case KindOfArray:
throw_bad_type_exception("Invalid type used as key");
break;
case KindOfObject:
if (offset.isResource()) {
return m_data.parr->get(offset.toInt64(), flags & AccessFlags::Error);
}
throw_bad_type_exception("Invalid type used as key");
break;
case KindOfVariant:
return rvalRef(*(offset.m_data.pvar), tmp, flags);
default:
ASSERT(false);
break;
}
return null_variant;
}
return rvalRefHelper(offset, tmp, flags);
}
template <typename T>
class LvalHelper {};
template<>
class LvalHelper<int64> {
public:
typedef int64 KeyType;
static bool CheckKey(KeyType k) { return true; };
static const bool CheckParams = false;
};
template<>
class LvalHelper<bool> : public LvalHelper<int64> {};
template<>
class LvalHelper<double> : public LvalHelper<int64> {};
template<>
class LvalHelper<CStrRef> {
public:
typedef VarNR KeyType;
static bool CheckKey(const KeyType &k) { return true; };
static const bool CheckParams = true;
};
template<>
class LvalHelper<CVarRef> {
public:
typedef VarNR KeyType;
static bool CheckKey(const KeyType &k) { return !k.isNull(); };
static const bool CheckParams = true;
};
template<typename T>
Variant& Variant::LvalAtImpl0(
Variant *self, T key, Variant *tmp, bool blackHole, ACCESSPARAMS_IMPL) {
head:
if (self->m_type == KindOfArray) {
ArrayData *arr = self->m_data.parr;
ArrayData *escalated;
Variant *ret = NULL;
if (LvalHelper<T>::CheckParams && flags & AccessFlags::Key) {
escalated = arr->lval(key, ret, arr->getCount() > 1,
flags & AccessFlags::CheckExist);
} else {
typename LvalHelper<T>::KeyType k(ToKey(key));
if (LvalHelper<T>::CheckKey(k)) {
escalated =
arr->lval(k, ret, arr->getCount() > 1,
flags & AccessFlags::CheckExist);
} else {
if (blackHole) ret = &lvalBlackHole();
else ret = tmp;
escalated = 0;
}
}
if (escalated) {
self->set(escalated);
}
ASSERT(ret);
return *ret;
}
if (self->m_type == KindOfVariant) {
self = self->m_data.pvar;
goto head;
}
if (self->isObjectConvertable()) {
self->set(Array::Create());
goto head;
}
if (self->m_type == KindOfObject) {
Variant *ret = &(self->getArrayAccess()->___offsetget_lval(key));
if (!blackHole) {
*tmp = *ret;
ret = tmp;
}
return *ret;
}
return lvalInvalid();
}
template<typename T>
Variant& Variant::lvalAtImpl(T key, ACCESSPARAMS_IMPL) {
return Variant::LvalAtImpl0<T>(this, key, NULL, true, flags);
}
Variant &Variant::lvalAt(bool key, ACCESSPARAMS_IMPL) {
return lvalAtImpl(key, flags);
}
Variant &Variant::lvalAt(int key, ACCESSPARAMS_IMPL) {
return lvalAt((int64)key, flags);
}
Variant &Variant::lvalAt(int64 key, ACCESSPARAMS_IMPL) {
return lvalAtImpl(key, flags);
}
Variant &Variant::lvalAt(double key, ACCESSPARAMS_IMPL) {
return lvalAtImpl(key, flags);
}
Variant &Variant::lvalAt(litstr ckey, ACCESSPARAMS_IMPL) {
String key(ckey);
return lvalAt(key, flags);
}
Variant &Variant::lvalAt(CStrRef key, ACCESSPARAMS_IMPL) {
return lvalAtImpl<CStrRef>(key, flags);
}
Variant &Variant::lvalAt(CVarRef k, ACCESSPARAMS_IMPL) {
return lvalAtImpl<CVarRef>(k, flags);
}
Variant &Variant::lvalRef(bool key, Variant& tmp, ACCESSPARAMS_IMPL) {
return LvalAtImpl0(this, key, &tmp, false, flags);
}
Variant &Variant::lvalRef(int key, Variant& tmp, ACCESSPARAMS_IMPL) {
return lvalRef((int64)key, tmp, flags);
}
Variant &Variant::lvalRef(int64 key, Variant& tmp, ACCESSPARAMS_IMPL) {
return LvalAtImpl0(this, key, &tmp, false, flags);
}
Variant &Variant::lvalRef(double key, Variant& tmp, ACCESSPARAMS_IMPL) {
return LvalAtImpl0(this, key, &tmp, false, flags);
}
Variant &Variant::lvalRef(litstr ckey, Variant& tmp, ACCESSPARAMS_IMPL) {
String key(ckey);
return lvalRef(key, tmp, flags);
}
Variant &Variant::lvalRef(CStrRef key, Variant& tmp, ACCESSPARAMS_IMPL) {
return Variant::LvalAtImpl0<CStrRef>(this, key, &tmp, false, flags);
}
Variant &Variant::lvalRef(CVarRef k, Variant& tmp, ACCESSPARAMS_IMPL) {
return Variant::LvalAtImpl0<CVarRef>(this, k, &tmp, false, flags);
}
Variant *Variant::lvalPtr(CStrRef key, bool forWrite, bool create) {
Variant *t = m_type == KindOfVariant ? m_data.pvar : this;
if (t->m_type == KindOfArray) {
return t->asArrRef().lvalPtr(key, forWrite, create);
}
return NULL;
}
Variant &Variant::lvalAt() {
switch (m_type) {
case KindOfUninit:
case KindOfNull:
set(ArrayData::Create());
break;
case KindOfBoolean:
if (!toBoolean()) {
set(ArrayData::Create());
} else {
throw_bad_type_exception("[] operator not supported for this type");
return lvalBlackHole();
}
break;
case KindOfArray:
break;
case KindOfVariant:
return m_data.pvar->lvalAt();
case KindOfObject:
{
Array params = CREATE_VECTOR1(null);
Variant& ret = lvalBlackHole();
ret = m_data.pobj->o_invoke(s_offsetGet, params);
raise_warning("Indirect modification of overloaded element of %s has "
"no effect", m_data.pobj->o_getClassName().data());
return ret;
}
case KindOfStaticString:
case KindOfString:
if (getStringData()->empty()) {
set(ArrayData::Create());
break;
}
// fall through to throw
default:
throw_bad_type_exception("[] operator not supported for this type");
return lvalBlackHole();
}
ASSERT(m_type == KindOfArray);
Variant *ret = NULL;
ArrayData *arr = m_data.parr;
ArrayData *escalated = arr->lvalNew(ret, arr->getCount() > 1);
if (escalated) {
set(escalated);
}
ASSERT(ret);
return *ret;
}
Variant &Variant::lvalInvalid() {
throw_bad_type_exception("not array objects");
return lvalBlackHole();
}
Variant &Variant::lvalBlackHole() {
Variant &bh = ((Globals*)get_global_variables())->__lvalProxy;
bh.unset();
return bh;
}
Variant Variant::refvalAt(bool key) {
return refvalAtImpl(key);
}
Variant Variant::refvalAt(int key) {
return refvalAtImpl(key);
}
Variant Variant::refvalAt(int64 key) {
return refvalAtImpl(key);
}
Variant Variant::refvalAt(double key) {
return refvalAtImpl((int64)key);
}
Variant Variant::refvalAt(litstr key, bool isString /* = false */) {
return refvalAtImpl(key, isString);
}
Variant Variant::refvalAt(CStrRef key, bool isString /* = false */) {
return refvalAtImpl(key, isString);
}
Variant Variant::refvalAt(CVarRef key) {
return refvalAtImpl(key);
}
Variant Variant::refvalAtImpl(CStrRef key, bool isString /* = false */) {
if (m_type == KindOfVariant) {
return m_data.pvar->refvalAtImpl(key, isString);
}
if (is(KindOfArray) || isObjectConvertable()) {
return strongBind(lvalAt(key, AccessFlags::IsKey(isString)));
} else {
return rvalAt(key, AccessFlags::IsKey(isString));
}
}
Variant Variant::argvalAt(bool byRef, bool key) {
return argvalAtImpl(byRef, key);
}
Variant Variant::argvalAt(bool byRef, int key) {
return argvalAtImpl(byRef, key);
}
Variant Variant::argvalAt(bool byRef, int64 key) {
return argvalAtImpl(byRef, key);
}
Variant Variant::argvalAt(bool byRef, double key) {
return argvalAtImpl(byRef, (int64)key);
}
Variant Variant::argvalAt(bool byRef, litstr key,
bool isString /* = false */) {
return argvalAtImpl(byRef, key, isString);
}
Variant Variant::argvalAt(bool byRef, CStrRef key,
bool isString /* = false */) {
return argvalAtImpl(byRef, key, isString);
}
Variant Variant::argvalAt(bool byRef, CVarRef key) {
return argvalAtImpl(byRef, key);
}
Variant Variant::argvalAtImpl(bool byRef, CStrRef key,
bool isString /* = false */) {
if (m_type == KindOfVariant) {
return m_data.pvar->argvalAtImpl(byRef, key, isString);
}
if (byRef && (is(KindOfArray) || isObjectConvertable())) {
return strongBind(lvalAt(key, AccessFlags::IsKey(isString)));
} else {
return rvalAt(key, AccessFlags::IsKey(isString));
}
}
Variant Variant::o_get(CStrRef propName, bool error /* = true */,
CStrRef context /* = null_string */) const {
if (m_type == KindOfObject) {
return m_data.pobj->o_get(propName, error, context);
} else if (m_type == KindOfVariant) {
return m_data.pvar->o_get(propName, error, context);
} else if (error) {
raise_notice("Trying to get property of non-object");
}
return null_variant;
}
Variant Variant::o_getPublic(CStrRef propName, bool error /* = true */) const {
if (m_type == KindOfObject) {
return m_data.pobj->o_getPublic(propName, error);
} else if (m_type == KindOfVariant) {
return m_data.pvar->o_getPublic(propName, error);
} else if (error) {
raise_notice("Trying to get property of non-object");
}
return null_variant;
}
bool Variant::o_empty(CStrRef propName,
CStrRef context /* = null_string */) const {
if (m_type == KindOfObject) {
return m_data.pobj->o_empty(propName, context);
}
if (m_type == KindOfVariant) {
return m_data.pvar->o_empty(propName, context);
}
if (m_type == KindOfArray) {
return empty(rvalAt(propName));
}
return true;
}
bool Variant::o_isset(CStrRef propName,
CStrRef context /* = null_string */) const {
if (m_type == KindOfObject) {
return m_data.pobj->o_isset(propName, context);
}
if (m_type == KindOfVariant) {
return m_data.pvar->o_isset(propName, context);
}
if (m_type == KindOfArray) {
return isset(rvalAt(propName));
}
return false;
}
void Variant::o_unset(CStrRef propName, CStrRef context /* = null_string */) {
if (m_type == KindOfObject) {
m_data.pobj->o_unset(propName, context);
}
if (m_type == KindOfVariant) {
m_data.pvar->o_unset(propName, context);
}
}
Variant Variant::o_argval(bool byRef, CStrRef propName,
bool error /* = true */, CStrRef context /* = null_string */) const {
if (m_type == KindOfObject) {
if (byRef) {
return strongBind(m_data.pobj->o_lval(propName, context));
} else {
return m_data.pobj->o_get(propName, error, context);
}
} else if (m_type == KindOfVariant) {
if (byRef) {
return strongBind(m_data.pvar->o_lval(propName, context));
} else {
return m_data.pvar->o_get(propName, error, context);
}
} else if (error) {
raise_notice("Trying to get property of non-object");
}
return null_variant;
}
Variant Variant::o_set(CStrRef propName, CVarRef val,
CStrRef context /* = null_string */) {
if (propName.empty()) {
throw EmptyObjectPropertyException();
}
if (m_type == KindOfObject) {
} else if (m_type == KindOfVariant) {
return m_data.pvar->o_set(propName, val, context);
} else if (isObjectConvertable()) {
set(Object(SystemLib::AllocStdClassObject()));
} else {
// Raise a warning
raise_warning("Attempt to assign property of non-object");
return val;
}
return m_data.pobj->o_set(propName, val, context);
}
Variant Variant::o_setRef(CStrRef propName, CVarRef val,
CStrRef context /* = null_string */) {
if (propName.empty()) {
throw EmptyObjectPropertyException();
}
if (m_type == KindOfObject) {
} else if (m_type == KindOfVariant) {
return m_data.pvar->o_setRef(propName, val, context);
} else if (isObjectConvertable()) {
set(Object(SystemLib::AllocStdClassObject()));
} else {
// Raise a warning
raise_warning("Attempt to assign property of non-object");
return val;
}
return m_data.pobj->o_setRef(propName, val, context);
}
Variant Variant::o_setPublic(CStrRef propName, CVarRef val) {
if (propName.empty()) {
throw EmptyObjectPropertyException();
}
if (m_type == KindOfObject) {
} else if (m_type == KindOfVariant) {
return m_data.pvar->o_setPublic(propName, val);
} else if (isObjectConvertable()) {
set(Object(SystemLib::AllocStdClassObject()));
} else {
// Raise a warning
raise_warning("Attempt to assign property of non-object");
return val;
}
return m_data.pobj->o_setPublic(propName, val);
}
Variant Variant::o_setPublicRef(CStrRef propName, CVarRef val) {
if (propName.empty()) {
throw EmptyObjectPropertyException();
}
if (m_type == KindOfObject) {
} else if (m_type == KindOfVariant) {
return m_data.pvar->o_setPublicRef(propName, val);
} else if (isObjectConvertable()) {
set(Object(SystemLib::AllocStdClassObject()));
} else {
// Raise a warning
raise_warning("Attempt to assign property of non-object");
return val;
}
return m_data.pobj->o_setPublicRef(propName, val);
}
Variant Variant::o_invoke(CStrRef s, CArrRef params, int64 hash /* = -1 */) {
if (m_type == KindOfObject) {
return m_data.pobj->o_invoke(s, params, hash);
} else if (m_type == KindOfVariant) {
return m_data.pvar->o_invoke(s, params, hash);
} else {
throw InvalidOperandException(
"Call to a member function on a non-object");
}
}
Variant Variant::o_root_invoke(CStrRef s, CArrRef params,
int64 hash /* = -1 */) {
if (m_type == KindOfObject) {
return m_data.pobj->o_root_invoke(s, params, hash);
} else if (m_type == KindOfVariant) {
return m_data.pvar->o_root_invoke(s, params, hash);
} else {
throw InvalidOperandException(
"Call to a member function on a non-object");
}
}
Variant Variant::o_invoke_ex(CStrRef clsname, CStrRef s, CArrRef params) {
if (m_type == KindOfObject) {
return m_data.pobj->o_invoke_ex(clsname, s, params);
} else if (m_type == KindOfVariant) {
return m_data.pvar->o_invoke_ex(clsname, s, params);
} else {
throw InvalidOperandException(
"Call to a member function on a non-object");
}
}
Variant Variant::o_invoke_few_args(CStrRef s, int64 hash, int count,
INVOKE_FEW_ARGS_IMPL_ARGS) {
if (m_type == KindOfObject) {
return m_data.pobj->o_invoke_few_args(s, hash, count,
INVOKE_FEW_ARGS_PASS_ARGS);
} else if (m_type == KindOfVariant) {
return m_data.pvar->o_invoke_few_args(s, hash, count,
INVOKE_FEW_ARGS_PASS_ARGS);
} else {
throw InvalidOperandException(
"Call to a member function on a non-object");
}
}
Variant Variant::o_root_invoke_few_args(CStrRef s, int64 hash, int count,
INVOKE_FEW_ARGS_IMPL_ARGS) {
if (m_type == KindOfObject) {
return m_data.pobj->o_root_invoke_few_args(s, hash, count,
INVOKE_FEW_ARGS_PASS_ARGS);
} else if (m_type == KindOfVariant) {
return m_data.pvar->o_root_invoke_few_args(s, hash, count,
INVOKE_FEW_ARGS_PASS_ARGS);
} else {
throw InvalidOperandException(
"Call to a member function on a non-object");
}
}
bool Variant::o_get_call_info(MethodCallPackage &info, int64 hash /* = -1 */) {
if (m_type == KindOfObject) {
return m_data.pobj->o_get_call_info(info, hash);
} else if (m_type == KindOfVariant) {
return m_data.pvar->o_get_call_info(info, hash);
} else {
throw InvalidOperandException(
"Call to a member function on a non-object");
}
}
Variant &Variant::o_lval(CStrRef propName, CVarRef tmpForGet,
CStrRef context /* = null_string */) {
if (m_type == KindOfObject) {
return m_data.pobj->o_lval(propName, tmpForGet, context);
} else if (m_type == KindOfVariant) {
return m_data.pvar->o_lval(propName, tmpForGet, context);
} else if (isObjectConvertable()) {
set(Object(SystemLib::AllocStdClassObject()));
return m_data.pobj->o_lval(propName, tmpForGet, context);
} else {
// Raise a warning
raise_warning("Attempt to assign property of non-object");
return const_cast<Variant&>(tmpForGet);
}
}
Variant &Variant::o_unsetLval(CStrRef propName, CVarRef tmpForGet,
CStrRef context /* = null_string */) {
if (m_type == KindOfObject) {
return m_data.pobj->o_lval(propName, tmpForGet, context);
} else if (m_type == KindOfVariant) {
return m_data.pvar->o_unsetLval(propName, tmpForGet, context);
} else {
return const_cast<Variant&>(tmpForGet);
}
}
#define OPEQUAL(op, l, r) \
switch (op) { \
case T_CONCAT_EQUAL: concat_assign((l), r); break; \
case T_PLUS_EQUAL: ((l) += r); break; \
case T_MINUS_EQUAL: ((l) -= r); break; \
case T_MUL_EQUAL: ((l) *= r); break; \
case T_DIV_EQUAL: ((l) /= r); break; \
case T_MOD_EQUAL: ((l) %= r); break; \
case T_AND_EQUAL: ((l) &= r); break; \
case T_OR_EQUAL: ((l) |= r); break; \
case T_XOR_EQUAL: ((l) ^= r); break; \
case T_SL_EQUAL: ((l) <<= r); break; \
case T_SR_EQUAL: ((l) >>= r); break; \
default: \
throw FatalErrorException(0, "invalid operator %d", op); \
} \
#define IMPLEMENT_SETAT_OPEQUAL \
check_array: \
if (m_type == KindOfArray) { \
Variant *cv = NULL; \
ArrayData *escalated = \
m_data.parr->lval(ToKey(key), cv, (m_data.parr->getCount() > 1)); \
if (escalated) { \
set(escalated); \
} \
ASSERT(cv); \
OPEQUAL(op, *cv, v); \
return *cv; \
} \
switch (m_type) { \
case KindOfBoolean: \
if (toBoolean()) { \
throw_bad_type_exception("not array objects"); \
break; \
} \
/* Fall through */ \
case KindOfUninit: \
case KindOfNull: \
set(ArrayData::Create(ToKey(key), null)); \
goto check_array; \
case KindOfVariant: \
m_data.pvar->setOpEqual(op, key, v); \
break; \
case KindOfStaticString: \
case KindOfString: { \
String s = toString(); \
if (s.empty()) { \
set(ArrayData::Create(ToKey(key), null)); \
goto check_array; \
} \
throw_bad_type_exception("not array objects"); \
break; \
} \
case KindOfObject: { \
ObjectData *aa = getArrayAccess(); \
Variant &cv = aa->___offsetget_lval(key); \
OPEQUAL(op, cv, v); \
aa->o_invoke(s_offsetSet, CREATE_VECTOR2(key, cv), -1); \
return cv; \
} \
default: \
throw_bad_type_exception("not array objects"); \
break; \
} \
return v; \
template <typename T>
inline ALWAYS_INLINE CVarRef Variant::SetImpl(Variant *self, T key,
CVarRef v, bool isKey) {
retry:
if (LIKELY(self->m_type == KindOfArray)) {
ArrayData *escalated;
if (LvalHelper<T>::CheckParams && isKey) {
escalated = self->m_data.parr->set(key, v, self->needCopyForSet(v));
} else {
typename LvalHelper<T>::KeyType k(ToKey(key));
if (!LvalHelper<T>::CheckKey(k)) return lvalBlackHole();
escalated = self->m_data.parr->set(k, v, self->needCopyForSet(v));
}
if (escalated) {
self->set(escalated);
}
return v;
}
switch (self->m_type) {
case KindOfBoolean:
if (self->m_data.num) {
throw_bad_type_exception("not array objects");
break;
}
/* Fall through */
case KindOfUninit:
case KindOfNull:
create:
if (LvalHelper<T>::CheckParams && isKey) {
self->set(ArrayData::Create(key, v));
} else {
typename LvalHelper<T>::KeyType k(ToKey(key));
if (!LvalHelper<T>::CheckKey(k)) return lvalBlackHole();
self->set(ArrayData::Create(k, v));
}
break;
case KindOfVariant:
self = self->m_data.pvar;
goto retry;
case KindOfStaticString:
case KindOfString: {
StringData *s = self->m_data.pstr;
if (s->empty()) {
goto create;
}
StringData *es = StringData::Escalate(s);
es->set(key, v.toString());
if (es != s) self->set(es);
break;
}
case KindOfObject:
self->getArrayAccess()->o_invoke_few_args(s_offsetSet, -1, 2, key, v);
break;
default:
throw_bad_type_exception("not array objects");
break;
}
return v;
}
CVarRef Variant::set(bool key, CVarRef v) {
return SetImpl(this, key, v, false);
}
CVarRef Variant::set(int64 key, CVarRef v) {
return SetImpl(this, key, v, false);
}
CVarRef Variant::set(double key, CVarRef v) {
return SetImpl(this, key, v, false);
}
CVarRef Variant::set(CStrRef key, CVarRef v, bool isString /* = false */) {
return SetImpl<CStrRef>(this, key, v, isString);
}
HOT_FUNC
CVarRef Variant::set(CVarRef key, CVarRef v) {
return SetImpl<CVarRef>(this, key, v, false);
}
CVarRef Variant::append(CVarRef v) {
switch (m_type) {
case KindOfUninit:
case KindOfNull:
set(ArrayData::Create(v));
break;
case KindOfBoolean:
if (!toBoolean()) {
set(ArrayData::Create(v));
} else {
throw_bad_type_exception("[] operator not supported for this type");
}
break;
case KindOfArray:
{
ArrayData *escalated = m_data.parr->append(v, needCopyForSet(v));
if (escalated) {
set(escalated);
}
}
break;
case KindOfVariant:
m_data.pvar->append(v);
break;
case KindOfObject:
{
Array params = CREATE_VECTOR2(null, v);
m_data.pobj->o_invoke(s_offsetSet, params);
break;
}
case KindOfStaticString:
case KindOfString:
if (getStringData()->empty()) {
set(ArrayData::Create(v));
return v;
}
// fall through to throw
default:
throw_bad_type_exception("[] operator not supported for this type");
}
return v;
}
template <typename T>
inline ALWAYS_INLINE CVarRef Variant::SetRefImpl(Variant *self, T key,
CVarRef v, bool isKey) {
retry:
if (LIKELY(self->m_type == KindOfArray)) {
ArrayData *escalated;
if (LvalHelper<T>::CheckParams && isKey) {
escalated = self->m_data.parr->setRef(key, v, self->needCopyForSetRef(v));
} else {
typename LvalHelper<T>::KeyType k(ToKey(key));
if (!LvalHelper<T>::CheckKey(k)) return lvalBlackHole();
escalated = self->m_data.parr->setRef(k, v, self->needCopyForSetRef(v));
}
if (escalated) {
self->set(escalated);
}
return v;
}
switch (self->m_type) {
case KindOfBoolean:
if (self->m_data.num) {
throw_bad_type_exception("not array objects");
break;
}
/* Fall through */
case KindOfUninit:
case KindOfNull:
create:
if (LvalHelper<T>::CheckParams && isKey) {
self->set(ArrayData::CreateRef(key, v));
} else {
typename LvalHelper<T>::KeyType k(ToKey(key));
if (!LvalHelper<T>::CheckKey(k)) return lvalBlackHole();
self->set(ArrayData::CreateRef(k, v));
}
break;
case KindOfVariant:
self = self->m_data.pvar;
goto retry;
case KindOfStaticString:
case KindOfString: {
if (self->m_data.pstr->empty()) {
goto create;
}
throw_bad_type_exception("binding assignment to stringoffset");
break;
}
case KindOfObject:
self->getArrayAccess()->o_invoke_few_args(s_offsetSet, -1, 2, key, v);
break;
default:
throw_bad_type_exception("not array objects");
break;
}
return v;
}
CVarRef Variant::setRef(bool key, CVarRef v) {
return SetRefImpl(this, key, v, false);
}
CVarRef Variant::setRef(int64 key, CVarRef v) {
return SetRefImpl(this, key, v, false);
}
CVarRef Variant::setRef(double key, CVarRef v) {
return SetRefImpl(this, key, v, false);
}
CVarRef Variant::setRef(CStrRef key, CVarRef v, bool isString /* = false */) {
return SetRefImpl<CStrRef>(this, key, v, isString);
}
CVarRef Variant::setRef(CVarRef key, CVarRef v) {
return SetRefImpl<CVarRef>(this, key, v, false);
}
CVarRef Variant::appendRef(CVarRef v) {
switch (m_type) {
case KindOfUninit:
case KindOfNull:
set(ArrayData::CreateRef(v));
break;
case KindOfBoolean:
if (!toBoolean()) {
set(ArrayData::CreateRef(v));
} else {
throw_bad_type_exception("[] operator not supported for this type");
}
break;
case KindOfArray:
{
ArrayData *escalated = m_data.parr->appendRef(v, needCopyForSetRef(v));
if (escalated) {
set(escalated);
}
}
break;
case KindOfVariant:
m_data.pvar->appendRef(v);
break;
case KindOfObject:
{
m_data.pobj->o_invoke_few_args(s_offsetSet, -1, 2, null, v);
break;
}
case KindOfStaticString:
case KindOfString:
if (getStringData()->empty()) {
set(ArrayData::CreateRef(v));
return v;
}
// fall through to throw
default:
throw_bad_type_exception("[] operator not supported for this type");
}
return v;
}
CVarRef Variant::setOpEqual(int op, bool key, CVarRef v) {
IMPLEMENT_SETAT_OPEQUAL;
}
CVarRef Variant::setOpEqual(int op, int64 key, CVarRef v) {
IMPLEMENT_SETAT_OPEQUAL;
}
CVarRef Variant::setOpEqual(int op, double key, CVarRef v) {
IMPLEMENT_SETAT_OPEQUAL;
}
CVarRef Variant::setOpEqual(int op, CStrRef key, CVarRef v,
bool isString /* = false */) {
check_array:
if (m_type == KindOfArray) {
Variant *cv = NULL;
ArrayData *escalated;
if (isString) {
escalated =
m_data.parr->lval(key, cv, (m_data.parr->getCount() > 1));
} else {
escalated =
m_data.parr->lval(ToKey(key), cv, (m_data.parr->getCount() > 1));
}
if (escalated) {
set(escalated);
}
ASSERT(cv);
OPEQUAL(op, *cv, v);
return *cv;
}
switch (m_type) {
case KindOfBoolean:
if (toBoolean()) {
throw_bad_type_exception("not array objects");
break;
}
/* Fall through */
case KindOfUninit:
case KindOfNull:
if (isString) {
set(ArrayData::Create(key, null));
} else {
set(ArrayData::Create(ToKey(key), null));
}
goto check_array;
case KindOfVariant:
return m_data.pvar->setOpEqual(op, key, v, isString);
case KindOfStaticString:
case KindOfString: {
String s = toString();
if (s.empty()) {
if (isString) {
set(ArrayData::Create(key, null));
} else {
set(ArrayData::Create(ToKey(key), null));
}
goto check_array;
}
throw_bad_type_exception("not array objects");
break;
}
case KindOfObject: {
ObjectData *aa = getArrayAccess();
Variant &cv = aa->___offsetget_lval(key);
OPEQUAL(op, cv, v);
aa->o_invoke(s_offsetSet, CREATE_VECTOR2(key, cv), -1);
return cv;
}
default:
throw_bad_type_exception("not array objects");
break;
}
return v;
}
CVarRef Variant::setOpEqual(int op, CVarRef key, CVarRef v) {
check_array:
if (m_type == KindOfArray) {
Variant *cv = NULL;
VarNR k(ToKey(key));
if (k.isNull()) return lvalBlackHole();
ArrayData *escalated =
m_data.parr->lval(k, cv, (m_data.parr->getCount() > 1));
if (escalated) {
set(escalated);
}
ASSERT(cv);
OPEQUAL(op, *cv, v);
return *cv;
}
switch (m_type) {
case KindOfBoolean:
if (toBoolean()) {
throw_bad_type_exception("not array objects");
break;
}
/* Fall through */
case KindOfUninit:
case KindOfNull: {
VarNR k(ToKey(key));
if (k.isNull()) return lvalBlackHole();
set(ArrayData::Create(k, null));
goto check_array;
}
case KindOfVariant:
return m_data.pvar->setOpEqual(op, key, v);
case KindOfStaticString:
case KindOfString: {
String s = toString();
if (s.empty()) {
VarNR k(ToKey(key));
if (k.isNull()) return lvalBlackHole();
set(ArrayData::Create(k, null));
goto check_array;
}
throw_bad_type_exception("not array objects");
break;
}
case KindOfObject: {
ObjectData *aa = getArrayAccess();
Variant &cv = aa->___offsetget_lval(key);
OPEQUAL(op, cv, v);
aa->o_invoke(s_offsetSet, CREATE_VECTOR2(key, cv), -1);
return cv;
}
default:
throw_bad_type_exception("not array objects");
break;
}
return v;
}
CVarRef Variant::appendOpEqual(int op, CVarRef v) {
check_array:
if (m_type == KindOfArray) {
Variant *cv = NULL;
ArrayData *escalated =
m_data.parr->lvalNew(cv, m_data.parr->getCount() > 1);
if (escalated) {
set(escalated);
}
ASSERT(cv);
switch (op) {
case T_CONCAT_EQUAL: return concat_assign((*cv), v);
case T_PLUS_EQUAL: return ((*cv) += v);
case T_MINUS_EQUAL: return ((*cv) -= v);
case T_MUL_EQUAL: return ((*cv) *= v);
case T_DIV_EQUAL: return ((*cv) /= v);
case T_MOD_EQUAL: return ((*cv) %= v);
case T_AND_EQUAL: return ((*cv) &= v);
case T_OR_EQUAL: return ((*cv) |= v);
case T_XOR_EQUAL: return ((*cv) ^= v);
case T_SL_EQUAL: return ((*cv) <<= v);
case T_SR_EQUAL: return ((*cv) >>= v);
default:
throw FatalErrorException(0, "invalid operator %d", op);
}
return v;
}
switch (m_type) {
case KindOfUninit:
case KindOfNull:
set(ArrayData::Create());
goto check_array;
case KindOfBoolean:
if (!toBoolean()) {
set(ArrayData::Create());
goto check_array;
} else {
throw_bad_type_exception("[] operator not supported for this type");
}
break;
case KindOfVariant:
m_data.pvar->appendOpEqual(op, v);
break;
case KindOfObject: {
ObjectData *aa = getArrayAccess();
Variant &cv = aa->___offsetget_lval(null_variant);
switch (op) {
case T_CONCAT_EQUAL: concat_assign(cv, v); break;
case T_PLUS_EQUAL: cv += v; break;
case T_MINUS_EQUAL: cv -= v; break;
case T_MUL_EQUAL: cv *= v; break;
case T_DIV_EQUAL: cv /= v; break;
case T_MOD_EQUAL: cv %= v; break;
case T_AND_EQUAL: cv &= v; break;
case T_OR_EQUAL: cv |= v; break;
case T_XOR_EQUAL: cv ^= v; break;
case T_SL_EQUAL: cv <<= v; break;
case T_SR_EQUAL: cv >= v; break;
break;
default:
throw FatalErrorException(0, "invalid operator %d", op);
}
aa->o_invoke(s_offsetSet, CREATE_VECTOR2(null_variant, cv));
return cv;
}
case KindOfStaticString:
case KindOfString:
if (getStringData()->empty()) {
set(ArrayData::Create());
goto check_array;
}
// fall through to throw
default:
throw_bad_type_exception("[] operator not supported for this type");
}
return v;
}
void Variant::removeImpl(double key) {
switch (getType()) {
case KindOfUninit:
case KindOfNull:
break;
case KindOfArray:
{
ArrayData *arr = getArrayData();
if (arr) {
ArrayData *escalated = arr->remove(ToKey(key), (arr->getCount() > 1));
if (escalated) {
set(escalated);
}
}
}
break;
case KindOfObject:
callOffsetUnset(key);
break;
default:
lvalInvalid();
break;
}
}
void Variant::removeImpl(int64 key) {
switch (getType()) {
case KindOfUninit:
case KindOfNull:
break;
case KindOfArray:
{
ArrayData *arr = getArrayData();
if (arr) {
ArrayData *escalated = arr->remove(key, (arr->getCount() > 1));
if (escalated) {
set(escalated);
}
}
}
break;
case KindOfObject:
callOffsetUnset(key);
break;
default:
lvalInvalid();
break;
}
}
void Variant::removeImpl(bool key) {
switch (getType()) {
case KindOfUninit:
case KindOfNull:
break;
case KindOfArray:
{
ArrayData *arr = getArrayData();
if (arr) {
ArrayData *escalated = arr->remove(ToKey(key), (arr->getCount() > 1));
if (escalated) {
set(escalated);
}
}
}
break;
case KindOfObject:
callOffsetUnset(key);
break;
default:
lvalInvalid();
break;
}
}
void Variant::removeImpl(CVarRef key, bool isString /* false */) {
switch (getType()) {
case KindOfUninit:
case KindOfNull:
break;
case KindOfArray:
{
ArrayData *arr = getArrayData();
if (arr) {
ArrayData *escalated;
if (isString) {
escalated = arr->remove(key, (arr->getCount() > 1));
} else {
const VarNR &k = key.toKey();
if (k.isNull()) return;
escalated = arr->remove(k, (arr->getCount() > 1));
}
if (escalated) {
set(escalated);
}
}
}
break;
case KindOfObject:
callOffsetUnset(key);
break;
default:
lvalInvalid();
break;
}
}
void Variant::removeImpl(CStrRef key, bool isString /* false */) {
switch (getType()) {
case KindOfUninit:
case KindOfNull:
break;
case KindOfArray:
{
ArrayData *arr = getArrayData();
if (arr) {
ArrayData *escalated;
if (isString) {
escalated = arr->remove(key, (arr->getCount() > 1));
} else {
escalated = arr->remove(key.toKey(), (arr->getCount() > 1));
}
if (escalated) {
set(escalated);
}
}
}
break;
case KindOfObject:
callOffsetUnset(key);
break;
default:
lvalInvalid();
break;
}
}
void Variant::remove(CVarRef key) {
switch(key.getType()) {
case KindOfInt32:
case KindOfInt64:
removeImpl(key.toInt64());
return;
case KindOfString:
case KindOfStaticString:
removeImpl(key.toString());
return;
default:
break;
}
// Trouble cases: Array, Object
removeImpl(key);
}
void Variant::setStatic() const {
if (has_eval_support) return setEvalScalar();
switch (m_type) {
case KindOfString:
m_data.pstr->setStatic();
break;
case KindOfArray:
m_data.parr->setStatic();
m_data.parr->onSetStatic();
break;
case KindOfVariant:
m_data.pvar->setStatic();
break;
case KindOfObject:
ASSERT(false); // object shouldn't be in a scalar array
break;
default:
break;
}
}
void Variant::setEvalScalar() const {
switch (m_type) {
case KindOfString: {
StringData *pstr = m_data.pstr;
if (!pstr->isStatic()) {
StringData *sd = StringData::GetStaticString(pstr);
ASSERT(sd != pstr);
if (pstr && pstr->decRefCount() == 0) {
DELETE(StringData)(pstr);
}
m_data.pstr = sd;
m_type = KindOfStaticString;
}
break;
}
case KindOfArray: {
ArrayData *parr = m_data.parr;
if (!parr->isStatic()) {
ArrayData *ad = ArrayData::GetScalarArray(parr);
if (parr && parr->decRefCount() == 0) {
parr->release();
}
m_data.parr = ad;
}
break;
}
case KindOfVariant:
ASSERT(false);
break;
case KindOfObject:
ASSERT(false); // object shouldn't be in a scalar array
break;
default:
break;
}
setVarNR();
}
///////////////////////////////////////////////////////////////////////////////
// output functions
void Variant::serialize(VariableSerializer *serializer,
bool isArrayKey /* = false */,
bool skipNestCheck /* = false */) const {
if (m_type == KindOfVariant) {
// Ugly, but behavior is different for serialize
if (serializer->getType() == VariableSerializer::Serialize ||
serializer->getType() == VariableSerializer::APCSerialize ||
serializer->getType() == VariableSerializer::DebuggerSerialize) {
if (serializer->incNestedLevel(m_data.pvar)) {
serializer->writeOverflow(m_data.pvar);
} else {
// Tell the inner variant to skip the nesting check for data inside
m_data.pvar->serialize(serializer, isArrayKey, true);
}
serializer->decNestedLevel(m_data.pvar);
} else {
m_data.pvar->serialize(serializer, isArrayKey);
}
return;
}
switch (m_type) {
case KindOfUninit:
case KindOfNull:
ASSERT(!isArrayKey);
serializer->writeNull(); break;
case KindOfBoolean:
ASSERT(!isArrayKey);
serializer->write(m_data.num != 0); break;
case KindOfInt32:
case KindOfInt64:
serializer->write(m_data.num); break;
case KindOfDouble:
serializer->write(m_data.dbl); break;
case KindOfStaticString:
case KindOfString:
serializer->write(m_data.pstr->data(),
m_data.pstr->size(), isArrayKey);
break;
case KindOfArray:
ASSERT(!isArrayKey);
m_data.parr->serialize(serializer, skipNestCheck);
break;
case KindOfObject:
ASSERT(!isArrayKey);
m_data.pobj->serialize(serializer); break;
default:
ASSERT(false);
break;
}
}
void Variant::unserialize(VariableUnserializer *uns) {
char type, sep;
type = uns->readChar();
sep = uns->readChar();
if (type != 'R') {
uns->add(this);
}
if (type == 'N') {
if(sep != ';') throw Exception("Expected ';' but got '%c'", sep);
setNull(); // NULL *IS* the value, without we get undefined warnings
return;
}
if (sep != ':') {
throw Exception("Expected ':' but got '%c'", sep);
}
switch (type) {
case 'r':
{
int64 id = uns->readInt();
Variant *v = uns->get(id);
if (v == NULL) {
throw Exception("Id %ld out of range", id);
}
operator=(*v);
}
break;
case 'R':
{
int64 id = uns->readInt();
Variant *v = uns->get(id);
if (v == NULL) {
throw Exception("Id %ld out of range", id);
}
assignRef(*v);
}
break;
case 'b': { int64 v = uns->readInt(); operator=((bool)v); } break;
case 'i': { int64 v = uns->readInt(); operator=(v); } break;
case 'd':
{
double v;
char ch = uns->peek();
bool negative = false;
char buf[4];
if (ch == '-') {
negative = true;
ch = uns->readChar();
ch = uns->peek();
}
if (ch == 'I') {
uns->read(buf, 3); buf[3] = '\0';
if (strcmp(buf, "INF")) {
throw Exception("Expected 'INF' but got '%s'", buf);
}
v = atof("inf");
} else if (ch == 'N') {
uns->read(buf, 3); buf[3] = '\0';
if (strcmp(buf, "NAN")) {
throw Exception("Expected 'NAN' but got '%s'", buf);
}
v = atof("nan");
} else {
v = uns->readDouble();
}
operator=(negative ? -v : v);
}
break;
case 's':
{
String v;
v.unserialize(uns);
operator=(v);
}
break;
case 'S':
if (uns->getType() == VariableUnserializer::APCSerialize) {
union {
char buf[8];
StringData *sd;
} u;
uns->read(u.buf, 8);
operator=(u.sd);
} else {
throw Exception("Unknown type '%c'", type);
}
break;
case 'a':
{
Array v = Array::Create();
v.unserialize(uns);
operator=(v);
return; // array has '}' terminating
}
break;
case 'A':
if (uns->getType() == VariableUnserializer::APCSerialize) {
union {
char buf[8];
ArrayData *ad;
} u;
uns->read(u.buf, 8);
operator=(u.ad);
} else {
throw Exception("Unknown type '%c'", type);
}
break;
case 'o':
{
String clsName;
clsName.unserialize(uns);
sep = uns->readChar();
if (sep != ':') {
throw Exception("Expected ':' but got '%c'", sep);
}
Object obj;
try {
obj = create_object(clsName.data(), Array::Create(), false);
} catch (ClassNotFoundException &e) {
ASSERT(false);
}
operator=(obj);
Array v = Array::Create();
v.unserialize(uns);
ClassInfo::SetArray(obj.get(), obj->o_getClassPropTable(), v);
obj->t___wakeup();
return; // array has '}' terminating
}
break;
case 'O':
{
String clsName;
clsName.unserialize(uns);
sep = uns->readChar();
if (sep != ':') {
throw Exception("Expected ':' but got '%c'", sep);
}
Object obj;
try {
obj = create_object_only(clsName);
} catch (ClassNotFoundException &e) {
obj = create_object_only(s_PHP_Incomplete_Class);
obj->o_set(s_PHP_Incomplete_Class_Name, clsName);
}
operator=(obj);
int64 size = uns->readInt();
char sep = uns->readChar();
if (sep != ':') {
throw Exception("Expected ':' but got '%c'", sep);
}
sep = uns->readChar();
if (sep != '{') {
throw Exception("Expected '{' but got '%c'", sep);
}
if (size > 0) {
for (int64 i = 0; i < size; i++) {
String key = uns->unserializeKey().toString();
int subLen = 0;
if (key.size() > 0 && key.charAt(0) == '\00') {
if (key.charAt(1) == '*') {
subLen = 3; // protected
} else {
subLen = key.find('\00', 1) + 1; // private, skipping class name
if (subLen == String::npos) {
throw Exception("Mangled private object property");
}
}
}
Variant tmp;
Variant &value = subLen != 0 ?
(key.charAt(1) == '*' ?
obj->o_lval(key.substr(subLen), tmp, clsName) :
obj->o_lval(key.substr(subLen), tmp,
String(key.data() + 1, subLen - 2, AttachLiteral)))
: obj->o_lval(key, tmp);
value.unserialize(uns);
}
}
sep = uns->readChar();
if (sep != '}') {
throw Exception("Expected '}' but got '%c'", sep);
}
obj->t___wakeup();
return; // object has '}' terminating
}
break;
case 'C':
{
String clsName;
clsName.unserialize(uns);
sep = uns->readChar();
if (sep != ':') {
throw Exception("Expected ':' but got '%c'", sep);
}
String serialized;
serialized.unserialize(uns, '{', '}');
Object obj;
try {
obj = create_object_only(clsName);
if (!obj->o_instanceof("Serializable")) {
raise_error("%s didn't implement Serializable", clsName.data());
}
obj->o_invoke(s_unserialize, CREATE_VECTOR1(serialized), -1);
} catch (ClassNotFoundException &e) {
if (!uns->allowUnknownSerializableClass()) {
throw;
}
obj = create_object_only(s_PHP_Incomplete_Class);
obj->o_set(s_PHP_Incomplete_Class_Name, clsName);
obj->o_set("serialized", serialized);
}
operator=(obj);
return; // object has '}' terminating
}
break;
default:
throw Exception("Unknown type '%c'", type);
}
sep = uns->readChar();
if (sep != ';') {
throw Exception("Expected ';' but got '%c'", sep);
}
}
Variant Variant::share(bool save) const {
if (m_type == KindOfVariant) {
return m_data.pvar->share(save);
}
switch (m_type) {
case KindOfUninit:
case KindOfNull: return false; // same as non-existent
case KindOfBoolean: return (m_data.num != 0);
case KindOfInt32:
case KindOfInt64: return m_data.num;
case KindOfDouble: return m_data.dbl;
case KindOfStaticString:
case KindOfString:
return String(m_data.pstr->data(), m_data.pstr->size(), CopyString);
case KindOfArray:
{
Array ret;
for (ArrayIter iter(m_data.parr); iter; ++iter) {
ret.set(iter.first().share(save), iter.second().share(save));
}
return ret;
}
break;
case KindOfObject:
if (save) {
// we have to return an object so to remember its type
ObjectData *obj = SystemLib::AllocStdClassObject();
obj->o_set(s_s, f_serialize(*this));
return obj;
} else {
return f_unserialize(m_data.pobj->o_get(s_s));
}
break;
default:
ASSERT(false);
break;
}
return false; // same as non-existent
}
SharedVariant *Variant::getSharedVariant() const {
if (m_type == KindOfVariant) {
return m_data.pvar->getSharedVariant();
}
if (m_type == KindOfString) {
return m_data.pstr->getSharedVariant();
}
if (m_type == KindOfArray) {
return m_data.parr->getSharedVariant();
}
return NULL;
}
Variant Variant::fiberMarshal(FiberReferenceMap &refMap) const {
if (m_type == KindOfVariant) {
Variant *mpvar = m_data.pvar;
if (mpvar->getCount() > 1) {
Variant *pvar = (Variant*)refMap.lookup(mpvar);
if (pvar == NULL) {
pvar = NEW(Variant)();
refMap.insert(mpvar, pvar, true); // ahead of deep copy
*pvar = mpvar->fiberMarshal(refMap);
}
pvar->incRefCount();
return pvar;
}
return mpvar->fiberMarshal(refMap);
}
switch (m_type) {
case KindOfUninit:
case KindOfNull: return Variant();
case KindOfBoolean: return (m_data.num != 0);
case KindOfInt32:
case KindOfInt64: return m_data.num;
case KindOfDouble: return m_data.dbl;
case KindOfStaticString:
case KindOfString:
return String(m_data.pstr).fiberCopy();
case KindOfArray:
return Array(m_data.parr).fiberMarshal(refMap);
case KindOfObject:
return m_data.pobj->fiberMarshal(refMap);
default:
ASSERT(false);
break;
}
return Variant();
}
Variant Variant::fiberUnmarshal(FiberReferenceMap &refMap) const {
if (m_type == KindOfVariant) {
Variant *mpvar = m_data.pvar;
if (mpvar->getCount() > 1) {
// marshaling back to original thread
Variant *pvar = (Variant*)refMap.lookup(mpvar);
if (pvar == NULL) {
// was i in original thread?
pvar = (Variant*)refMap.reverseLookup(mpvar);
if (pvar == NULL) {
pvar = NEW(Variant)();
}
refMap.insert(mpvar, pvar, false); // ahead of deep copy
*pvar = mpvar->fiberUnmarshal(refMap);
}
pvar->incRefCount();
return pvar;
}
// i'm actually a weakly bound variant
return mpvar->fiberUnmarshal(refMap);
}
switch (m_type) {
case KindOfUninit:
case KindOfNull: return Variant();
case KindOfBoolean: return (m_data.num != 0);
case KindOfInt32:
case KindOfInt64: return m_data.num;
case KindOfDouble: return m_data.dbl;
case KindOfStaticString:
case KindOfString:
return String(m_data.pstr).fiberCopy();
case KindOfArray:
return Array(m_data.parr).fiberUnmarshal(refMap);
case KindOfObject:
return m_data.pobj->fiberUnmarshal(refMap);
default:
ASSERT(false);
break;
}
return Variant();
}
const char *Variant::getTypeString(DataType type) {
switch (type) {
case KindOfUninit:
case KindOfNull: return "KindOfNull";
case KindOfBoolean: return "KindOfBoolean";
case KindOfInt32: return "KindOfInt32";
case KindOfInt64: return "KindOfInt64";
case KindOfDouble: return "KindOfDouble";
case KindOfStaticString: return "KindOfStaticString";
case KindOfString: return "KindOfString";
case KindOfArray: return "KindOfArray";
case KindOfObject: return "KindOfObject";
case KindOfVariant: return "KindOfVariant";
default:
ASSERT(false);
break;
}
return "";
}
std::string Variant::getDebugDump() const {
char buf[1024];
snprintf(buf, sizeof(buf), "[%s: %p]", getTypeString(m_type), m_data.pstr);
return buf;
}
void Variant::dump() const {
VariableSerializer vs(VariableSerializer::VarDump);
Variant ret(vs.serialize(*this, true));
printf("Variant: %s", ret.toString().data());
}
VariantVectorBase::~VariantVectorBase() {
Variant *e = (Variant*)m_elems;
while (m_size--) {
if (IS_REFCOUNTED_TYPE(e->m_type)) e->destructImpl();
e++;
}
}
void VariantVectorBase::pushWithRef(CVarRef v) {
(*this)[m_size++].constructWithRefHelper(v, 0);
}
VarNR::VarNR(CStrRef v) {
init(KindOfString);
StringData *s = v.get();
if (s) {
m_data.pstr = s;
} else {
m_type = KindOfNull;
}
}
VarNR::VarNR(CArrRef v) {
init(KindOfArray);
ArrayData *a = v.get();
if (a) {
m_data.parr = a;
} else {
m_type = KindOfNull;
}
}
VarNR::VarNR(CObjRef v) {
init(KindOfObject);
ObjectData *o = v.get();
if (o) {
m_data.pobj = o;
} else {
m_type = KindOfNull;
}
}
VarNR::VarNR(StringData *v) {
init(KindOfString);
if (v) {
m_data.pstr = v;
} else {
m_type = KindOfNull;
}
}
VarNR::VarNR(ArrayData *v) {
init(KindOfArray);
if (v) {
m_data.parr = v;
} else {
m_type = KindOfNull;
}
}
VarNR::VarNR(ObjectData *v) {
init(KindOfObject);
if (v) {
m_data.pobj = v;
} else {
m_type = KindOfNull;
}
}
template<>
Variant AssignOp<T_CONCAT_EQUAL>::assign(Variant &var, CVarRef val) {
return concat_assign(var, val);
}
template<>
Variant AssignOp<T_PLUS_EQUAL>::assign(Variant &var, CVarRef val) {
return var += val;
}
template<>
Variant AssignOp<T_MINUS_EQUAL>::assign(Variant &var, CVarRef val) {
return var -= val;
}
template<>
Variant AssignOp<T_MUL_EQUAL>::assign(Variant &var, CVarRef val) {
return var *= val;
}
template<>
Variant AssignOp<T_DIV_EQUAL>::assign(Variant &var, CVarRef val) {
return var /= val;
}
template<>
Variant AssignOp<T_MOD_EQUAL>::assign(Variant &var, CVarRef val) {
return var %= val;
}
template<>
Variant AssignOp<T_AND_EQUAL>::assign(Variant &var, CVarRef val) {
return var &= val;
}
template<>
Variant AssignOp<T_OR_EQUAL>::assign(Variant &var, CVarRef val) {
return var |= val;
}
template<>
Variant AssignOp<T_XOR_EQUAL>::assign(Variant &var, CVarRef val) {
return var ^= val;
}
template<>
Variant AssignOp<T_SL_EQUAL>::assign(Variant &var, CVarRef val) {
return var <<= val;
}
template<>
Variant AssignOp<T_SR_EQUAL>::assign(Variant &var, CVarRef val) {
return var >>= val;
}
template<>
Variant AssignOp<T_INC>::assign(Variant &var, CVarRef val) {
return val.isNull() ? ++var : var++;
}
template<>
Variant AssignOp<T_DEC>::assign(Variant &var, CVarRef val) {
return val.isNull() ? --var : var--;
}
template<typename T, int op>
T Variant::o_assign_op(CStrRef propName, CVarRef val,
CStrRef context /* = null_string */) {
if (propName.empty()) {
throw EmptyObjectPropertyException();
}
if (m_type == KindOfObject) {
} else if (m_type == KindOfVariant) {
return (T)m_data.pvar->template o_assign_op<T,op>(propName, val, context);
} else if (isObjectConvertable()) {
set(Object(SystemLib::AllocStdClassObject()));
} else {
// Raise a warning
raise_warning("Attempt to assign property of non-object");
Variant tmp;
return (T)tmp.template o_assign_op<T,op>(propName, val, context);
}
return (T)m_data.pobj->template o_assign_op<T,op>(propName, val, context);
}
template<typename T, int op>
T Object::o_assign_op(CStrRef propName, CVarRef val,
CStrRef context /* = null_string */) {
if (propName.empty()) {
throw EmptyObjectPropertyException();
}
ObjectData *obj = m_px;
if (!obj) {
obj = SystemLib::AllocStdClassObject();
SmartPtr<ObjectData>::operator=(obj);
}
return obj->template o_assign_op<T,op>(propName, val, context);
}
template<typename T, int op>
T ObjectData::o_assign_op(CStrRef propName, CVarRef val,
CStrRef context /* = null_string */) {
bool useGet = getAttribute(ObjectData::UseGet);
bool useSet = getAttribute(ObjectData::UseSet);
int flags = useSet ? ObjectData::RealPropWrite :
ObjectData::RealPropCreate | ObjectData::RealPropWrite;
if (Variant *t = o_realProp(propName, flags, context)) {
if (useGet && !t->isInitialized()) {
AttributeClearer a(ObjectData::UseGet, this);
*t = t___get(propName);
}
return (T)AssignOp<op>::assign(*t, val);
}
ASSERT(useSet);
Variant var;
if (useGet) {
AttributeClearer a(ObjectData::UseGet, this);
var = t___get(propName);
}
Variant ret = AssignOp<op>::assign(var, val);
AttributeClearer a(ObjectData::UseSet, this);
t___set(propName, var);
return (T)ret;
}
#define DECLARE_O_ASSIGN_OP_ONE(C,T,op) \
template T \
C::o_assign_op<T,op>(CStrRef propName, CVarRef val, \
CStrRef context /* = null_string */)
#define DECLARE_O_ASSIGN_OP(op) \
DECLARE_O_ASSIGN_OP_ONE(Object,void,op); \
DECLARE_O_ASSIGN_OP_ONE(Object,Variant,op); \
DECLARE_O_ASSIGN_OP_ONE(Variant,void,op); \
DECLARE_O_ASSIGN_OP_ONE(Variant,Variant,op)
DECLARE_O_ASSIGN_OP(T_CONCAT_EQUAL);
DECLARE_O_ASSIGN_OP(T_PLUS_EQUAL);
DECLARE_O_ASSIGN_OP(T_MINUS_EQUAL);
DECLARE_O_ASSIGN_OP(T_MUL_EQUAL);
DECLARE_O_ASSIGN_OP(T_DIV_EQUAL);
DECLARE_O_ASSIGN_OP(T_MOD_EQUAL);
DECLARE_O_ASSIGN_OP(T_AND_EQUAL);
DECLARE_O_ASSIGN_OP(T_OR_EQUAL);
DECLARE_O_ASSIGN_OP(T_XOR_EQUAL);
DECLARE_O_ASSIGN_OP(T_SL_EQUAL);
DECLARE_O_ASSIGN_OP(T_SR_EQUAL);
DECLARE_O_ASSIGN_OP(T_INC);
DECLARE_O_ASSIGN_OP(T_DEC);
///////////////////////////////////////////////////////////////////////////////
}
|
#ifndef _VKTSPARSERESOURCESBUFFERMEMORYALIASING_HPP
#define _VKTSPARSERESOURCESBUFFERMEMORYALIASING_HPP
/*------------------------------------------------------------------------
* 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 vktSparseResourcesBufferMemoryAliasing.hpp
* \brief Sparse buffer memory aliasing tests
*//*--------------------------------------------------------------------*/
#include "tcuDefs.hpp"
#include "vktTestCase.hpp"
namespace vkt
{
namespace sparse
{
void addBufferSparseMemoryAliasingTests(tcu::TestCaseGroup* group);
} // sparse
} // vkt
#endif // _VKTSPARSERESOURCESBUFFERMEMORYALIASING_HPP
|
// Copyright 2016 Proyectos y Sistemas de Mantenimiento SL (eProsima).
//
// 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 TestWriterRegistered.cpp
*
*/
#include "TestWriterRegistered.h"
#include "fastrtps/rtps/writer/RTPSWriter.h"
#include "fastrtps/rtps/participant/RTPSParticipant.h"
#include "fastrtps/rtps/RTPSDomain.h"
#include "fastrtps/rtps/attributes/RTPSParticipantAttributes.h"
#include "fastrtps/rtps/attributes/WriterAttributes.h"
#include "fastrtps/rtps/attributes/HistoryAttributes.h"
#include "fastrtps/rtps/history/WriterHistory.h"
#include "fastrtps/attributes/TopicAttributes.h"
#include "fastrtps/qos/WriterQos.h"
#include "fastrtps/utils/eClock.h"
#include "fastrtps/utils/TimeConversion.h"
using namespace eprosima;
using namespace fastrtps;
TestWriterRegistered::TestWriterRegistered():
mp_participant(nullptr),
mp_writer(nullptr),
mp_history(nullptr)
{
}
TestWriterRegistered::~TestWriterRegistered()
{
RTPSDomain::removeRTPSParticipant(mp_participant);
delete(mp_history);
}
bool TestWriterRegistered::init()
{
//CREATE PARTICIPANT
RTPSParticipantAttributes PParam;
PParam.builtin.use_SIMPLE_RTPSParticipantDiscoveryProtocol = true;
PParam.builtin.use_WriterLivelinessProtocol = true;
mp_participant = RTPSDomain::createParticipant(PParam);
if(mp_participant==nullptr)
return false;
//CREATE WRITERHISTORY
HistoryAttributes hatt;
hatt.payloadMaxSize = 255;
mp_history = new WriterHistory(hatt);
//CREATE WRITER
WriterAttributes watt;
watt.endpoint.reliabilityKind = RELIABLE;
watt.times.heartbeatPeriod.seconds = 5;
mp_writer = RTPSDomain::createRTPSWriter(mp_participant,watt,mp_history,&m_listener);
if(mp_writer == nullptr)
return false;
return true;
}
bool TestWriterRegistered::reg()
{
cout << "Registering Writer" << endl;
TopicAttributes Tatt;
Tatt.topicKind = NO_KEY;
Tatt.topicDataType = "string";
Tatt.topicName = "exampleTopic";
WriterQos Wqos;
Wqos.m_reliability.kind = RELIABLE_RELIABILITY_QOS;
return mp_participant->registerWriter(mp_writer, Tatt, Wqos);
}
void TestWriterRegistered::run(uint16_t samples)
{
cout << "Waiting for matched Readers" << endl;
while (m_listener.n_matched==0)
{
eClock::my_sleep(250);
}
std::cout << "Enter to send messages"<<std::endl;
std::cin.ignore();
for(int i = 0;i<samples;++i )
{
CacheChange_t * ch = mp_writer->new_change(ALIVE);
#if defined(_WIN32)
ch->serializedPayload.length =
sprintf_s((char*)ch->serializedPayload.data,255, "My example string %d", i)+1;
#else
ch->serializedPayload.length =
sprintf((char*)ch->serializedPayload.data,"My example string %d",i)+1;
#endif
printf("Sending: %s\n",(char*)ch->serializedPayload.data);
mp_history->add_change(ch);
if(i == 3)
mp_participant->loose_next_change();
}
std::cin.ignore();
}
|
#include <iostream>
#include "../Headers/ev3dev.h"
using namespace std;
using namespace ev3dev;
int main()
{
cout << "Hello, World!";
return 0;
}
|
// Copyright (c) 2018 The PIVX developers
// Copyright (c) 2017-2018 The HUZU developers
// Copyright (c) 2018 The ZEFIR developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <primitives/deterministicmint.h>
#include "zpivtracker.h"
#include "util.h"
#include "sync.h"
#include "main.h"
#include "txdb.h"
#include "walletdb.h"
#include "accumulators.h"
using namespace std;
CzZEFIRTracker::CzZEFIRTracker(std::string strWalletFile)
{
this->strWalletFile = strWalletFile;
mapSerialHashes.clear();
mapPendingSpends.clear();
fInitialized = false;
}
CzZEFIRTracker::~CzZEFIRTracker()
{
mapSerialHashes.clear();
mapPendingSpends.clear();
}
void CzZEFIRTracker::Init()
{
//Load all CZerocoinMints and CDeterministicMints from the database
if (!fInitialized) {
ListMints(false, false, true);
fInitialized = true;
}
}
bool CzZEFIRTracker::Archive(CMintMeta& meta)
{
if (mapSerialHashes.count(meta.hashSerial))
mapSerialHashes.at(meta.hashSerial).isArchived = true;
CWalletDB walletdb(strWalletFile);
CZerocoinMint mint;
if (walletdb.ReadZerocoinMint(meta.hashPubcoin, mint)) {
if (!CWalletDB(strWalletFile).ArchiveMintOrphan(mint))
return error("%s: failed to archive zerocoinmint", __func__);
} else {
//failed to read mint from DB, try reading deterministic
CDeterministicMint dMint;
if (!walletdb.ReadDeterministicMint(meta.hashPubcoin, dMint))
return error("%s: could not find pubcoinhash %s in db", __func__, meta.hashPubcoin.GetHex());
if (!walletdb.ArchiveDeterministicOrphan(dMint))
return error("%s: failed to archive deterministic ophaned mint", __func__);
}
LogPrintf("%s: archived pubcoinhash %s\n", __func__, meta.hashPubcoin.GetHex());
return true;
}
bool CzZEFIRTracker::UnArchive(const uint256& hashPubcoin, bool isDeterministic)
{
CWalletDB walletdb(strWalletFile);
if (isDeterministic) {
CDeterministicMint dMint;
if (!walletdb.UnarchiveDeterministicMint(hashPubcoin, dMint))
return error("%s: failed to unarchive deterministic mint", __func__);
Add(dMint, false);
} else {
CZerocoinMint mint;
if (!walletdb.UnarchiveZerocoinMint(hashPubcoin, mint))
return error("%s: failed to unarchivezerocoin mint", __func__);
Add(mint, false);
}
LogPrintf("%s: unarchived %s\n", __func__, hashPubcoin.GetHex());
return true;
}
CMintMeta CzZEFIRTracker::Get(const uint256 &hashSerial)
{
if (!mapSerialHashes.count(hashSerial))
return CMintMeta();
return mapSerialHashes.at(hashSerial);
}
CMintMeta CzZEFIRTracker::GetMetaFromPubcoin(const uint256& hashPubcoin)
{
for (auto it : mapSerialHashes) {
CMintMeta meta = it.second;
if (meta.hashPubcoin == hashPubcoin)
return meta;
}
return CMintMeta();
}
bool CzZEFIRTracker::GetMetaFromStakeHash(const uint256& hashStake, CMintMeta& meta) const
{
for (auto& it : mapSerialHashes) {
if (it.second.hashStake == hashStake) {
meta = it.second;
return true;
}
}
return false;
}
std::vector<uint256> CzZEFIRTracker::GetSerialHashes()
{
vector<uint256> vHashes;
for (auto it : mapSerialHashes) {
if (it.second.isArchived)
continue;
vHashes.emplace_back(it.first);
}
return vHashes;
}
CAmount CzZEFIRTracker::GetBalance(bool fConfirmedOnly, bool fUnconfirmedOnly) const
{
CAmount nTotal = 0;
//! zerocoin specific fields
std::map<libzerocoin::CoinDenomination, unsigned int> myZerocoinSupply;
for (auto& denom : libzerocoin::zerocoinDenomList) {
myZerocoinSupply.insert(make_pair(denom, 0));
}
{
//LOCK(cs_pivtracker);
// Get Unused coins
for (auto& it : mapSerialHashes) {
CMintMeta meta = it.second;
if (meta.isUsed || meta.isArchived)
continue;
bool fConfirmed = ((meta.nHeight < chainActive.Height() - Params().Zerocoin_MintRequiredConfirmations()) && !(meta.nHeight == 0));
if (fConfirmedOnly && !fConfirmed)
continue;
if (fUnconfirmedOnly && fConfirmed)
continue;
nTotal += libzerocoin::ZerocoinDenominationToAmount(meta.denom);
myZerocoinSupply.at(meta.denom)++;
}
}
if (nTotal < 0 ) nTotal = 0; // Sanity never hurts
return nTotal;
}
CAmount CzZEFIRTracker::GetUnconfirmedBalance() const
{
return GetBalance(false, true);
}
std::vector<CMintMeta> CzZEFIRTracker::GetMints(bool fConfirmedOnly) const
{
vector<CMintMeta> vMints;
for (auto& it : mapSerialHashes) {
CMintMeta mint = it.second;
if (mint.isArchived || mint.isUsed)
continue;
bool fConfirmed = (mint.nHeight < chainActive.Height() - Params().Zerocoin_MintRequiredConfirmations());
if (fConfirmedOnly && !fConfirmed)
continue;
vMints.emplace_back(mint);
}
return vMints;
}
//Does a mint in the tracker have this txid
bool CzZEFIRTracker::HasMintTx(const uint256& txid)
{
for (auto it : mapSerialHashes) {
if (it.second.txid == txid)
return true;
}
return false;
}
bool CzZEFIRTracker::HasPubcoin(const CBigNum &bnValue) const
{
// Check if this mint's pubcoin value belongs to our mapSerialHashes (which includes hashpubcoin values)
uint256 hash = GetPubCoinHash(bnValue);
return HasPubcoinHash(hash);
}
bool CzZEFIRTracker::HasPubcoinHash(const uint256& hashPubcoin) const
{
for (auto it : mapSerialHashes) {
CMintMeta meta = it.second;
if (meta.hashPubcoin == hashPubcoin)
return true;
}
return false;
}
bool CzZEFIRTracker::HasSerial(const CBigNum& bnSerial) const
{
uint256 hash = GetSerialHash(bnSerial);
return HasSerialHash(hash);
}
bool CzZEFIRTracker::HasSerialHash(const uint256& hashSerial) const
{
auto it = mapSerialHashes.find(hashSerial);
return it != mapSerialHashes.end();
}
bool CzZEFIRTracker::UpdateZerocoinMint(const CZerocoinMint& mint)
{
if (!HasSerial(mint.GetSerialNumber()))
return error("%s: mint %s is not known", __func__, mint.GetValue().GetHex());
uint256 hashSerial = GetSerialHash(mint.GetSerialNumber());
//Update the meta object
CMintMeta meta = Get(hashSerial);
meta.isUsed = mint.IsUsed();
meta.denom = mint.GetDenomination();
meta.nHeight = mint.GetHeight();
mapSerialHashes.at(hashSerial) = meta;
//Write to db
return CWalletDB(strWalletFile).WriteZerocoinMint(mint);
}
bool CzZEFIRTracker::UpdateState(const CMintMeta& meta)
{
CWalletDB walletdb(strWalletFile);
if (meta.isDeterministic) {
CDeterministicMint dMint;
if (!walletdb.ReadDeterministicMint(meta.hashPubcoin, dMint)) {
// Check archive just in case
if (!meta.isArchived)
return error("%s: failed to read deterministic mint from database", __func__);
// Unarchive this mint since it is being requested and updated
if (!walletdb.UnarchiveDeterministicMint(meta.hashPubcoin, dMint))
return error("%s: failed to unarchive deterministic mint from database", __func__);
}
dMint.SetTxHash(meta.txid);
dMint.SetHeight(meta.nHeight);
dMint.SetUsed(meta.isUsed);
dMint.SetDenomination(meta.denom);
dMint.SetStakeHash(meta.hashStake);
if (!walletdb.WriteDeterministicMint(dMint))
return error("%s: failed to update deterministic mint when writing to db", __func__);
} else {
CZerocoinMint mint;
if (!walletdb.ReadZerocoinMint(meta.hashPubcoin, mint))
return error("%s: failed to read mint from database", __func__);
mint.SetTxHash(meta.txid);
mint.SetHeight(meta.nHeight);
mint.SetUsed(meta.isUsed);
mint.SetDenomination(meta.denom);
if (!walletdb.WriteZerocoinMint(mint))
return error("%s: failed to write mint to database", __func__);
}
mapSerialHashes[meta.hashSerial] = meta;
return true;
}
void CzZEFIRTracker::Add(const CDeterministicMint& dMint, bool isNew, bool isArchived)
{
CMintMeta meta;
meta.hashPubcoin = dMint.GetPubcoinHash();
meta.nHeight = dMint.GetHeight();
meta.nVersion = dMint.GetVersion();
meta.txid = dMint.GetTxHash();
meta.isUsed = dMint.IsUsed();
meta.hashSerial = dMint.GetSerialHash();
meta.hashStake = dMint.GetStakeHash();
meta.denom = dMint.GetDenomination();
meta.isArchived = isArchived;
meta.isDeterministic = true;
mapSerialHashes[meta.hashSerial] = meta;
if (isNew)
CWalletDB(strWalletFile).WriteDeterministicMint(dMint);
}
void CzZEFIRTracker::Add(const CZerocoinMint& mint, bool isNew, bool isArchived)
{
CMintMeta meta;
meta.hashPubcoin = GetPubCoinHash(mint.GetValue());
meta.nHeight = mint.GetHeight();
meta.nVersion = libzerocoin::ExtractVersionFromSerial(mint.GetSerialNumber());
meta.txid = mint.GetTxHash();
meta.isUsed = mint.IsUsed();
meta.hashSerial = GetSerialHash(mint.GetSerialNumber());
uint256 nSerial = mint.GetSerialNumber().getuint256();
meta.hashStake = Hash(nSerial.begin(), nSerial.end());
meta.denom = mint.GetDenomination();
meta.isArchived = isArchived;
meta.isDeterministic = false;
mapSerialHashes[meta.hashSerial] = meta;
if (isNew)
CWalletDB(strWalletFile).WriteZerocoinMint(mint);
}
void CzZEFIRTracker::SetPubcoinUsed(const uint256& hashPubcoin, const uint256& txid)
{
if (!HasPubcoinHash(hashPubcoin))
return;
CMintMeta meta = GetMetaFromPubcoin(hashPubcoin);
meta.isUsed = true;
mapPendingSpends.insert(make_pair(meta.hashSerial, txid));
UpdateState(meta);
}
void CzZEFIRTracker::SetPubcoinNotUsed(const uint256& hashPubcoin)
{
if (!HasPubcoinHash(hashPubcoin))
return;
CMintMeta meta = GetMetaFromPubcoin(hashPubcoin);
meta.isUsed = false;
if (mapPendingSpends.count(meta.hashSerial))
mapPendingSpends.erase(meta.hashSerial);
UpdateState(meta);
}
void CzZEFIRTracker::RemovePending(const uint256& txid)
{
uint256 hashSerial;
for (auto it : mapPendingSpends) {
if (it.second == txid) {
hashSerial = it.first;
break;
}
}
if (hashSerial > 0)
mapPendingSpends.erase(hashSerial);
}
bool CzZEFIRTracker::UpdateStatusInternal(const std::set<uint256>& setMempool, CMintMeta& mint)
{
//! Check whether this mint has been spent and is considered 'pending' or 'confirmed'
// If there is not a record of the block height, then look it up and assign it
uint256 txidMint;
bool isMintInChain = zerocoinDB->ReadCoinMint(mint.hashPubcoin, txidMint);
//See if there is internal record of spending this mint (note this is memory only, would reset on restart)
bool isPendingSpend = static_cast<bool>(mapPendingSpends.count(mint.hashSerial));
// See if there is a blockchain record of spending this mint
uint256 txidSpend;
bool isConfirmedSpend = zerocoinDB->ReadCoinSpend(mint.hashSerial, txidSpend);
// Double check the mempool for pending spend
if (isPendingSpend) {
uint256 txidPendingSpend = mapPendingSpends.at(mint.hashSerial);
if (!setMempool.count(txidPendingSpend) || isConfirmedSpend) {
RemovePending(txidPendingSpend);
isPendingSpend = false;
LogPrintf("%s : Pending txid %s removed because not in mempool\n", __func__, txidPendingSpend.GetHex());
}
}
bool isUsed = isPendingSpend || isConfirmedSpend;
if (!mint.nHeight || !isMintInChain || isUsed != mint.isUsed) {
CTransaction tx;
uint256 hashBlock;
// Txid will be marked 0 if there is no knowledge of the final tx hash yet
if (mint.txid == 0) {
if (!isMintInChain) {
LogPrintf("%s : Failed to find mint in zerocoinDB %s\n", __func__, mint.hashPubcoin.GetHex().substr(0, 6));
mint.isArchived = true;
Archive(mint);
return true;
}
mint.txid = txidMint;
}
if (setMempool.count(mint.txid))
return true;
// Check the transaction associated with this mint
if (!IsInitialBlockDownload() && !GetTransaction(mint.txid, tx, hashBlock, true)) {
LogPrintf("%s : Failed to find tx for mint txid=%s\n", __func__, mint.txid.GetHex());
mint.isArchived = true;
Archive(mint);
return true;
}
// An orphan tx if hashblock is in mapBlockIndex but not in chain active
if (mapBlockIndex.count(hashBlock) && !chainActive.Contains(mapBlockIndex.at(hashBlock))) {
LogPrintf("%s : Found orphaned mint txid=%s\n", __func__, mint.txid.GetHex());
mint.isUsed = false;
mint.nHeight = 0;
if (tx.IsCoinStake()) {
mint.isArchived = true;
Archive(mint);
}
return true;
}
// Check that the mint has correct used status
if (mint.isUsed != isUsed) {
LogPrintf("%s : Set mint %s isUsed to %d\n", __func__, mint.hashPubcoin.GetHex(), isUsed);
mint.isUsed = isUsed;
return true;
}
}
return false;
}
std::set<CMintMeta> CzZEFIRTracker::ListMints(bool fUnusedOnly, bool fMatureOnly, bool fUpdateStatus)
{
CWalletDB walletdb(strWalletFile);
if (fUpdateStatus) {
std::list<CZerocoinMint> listMintsDB = walletdb.ListMintedCoins();
for (auto& mint : listMintsDB)
Add(mint);
LogPrint("zero", "%s: added %d zerocoinmints from DB\n", __func__, listMintsDB.size());
std::list<CDeterministicMint> listDeterministicDB = walletdb.ListDeterministicMints();
for (auto& dMint : listDeterministicDB)
Add(dMint);
LogPrint("zero", "%s: added %d dzpiv from DB\n", __func__, listDeterministicDB.size());
}
std::vector<CMintMeta> vOverWrite;
std::set<CMintMeta> setMints;
std::set<uint256> setMempool;
{
LOCK(mempool.cs);
mempool.getTransactions(setMempool);
}
std::map<libzerocoin::CoinDenomination, int> mapMaturity = GetMintMaturityHeight();
for (auto& it : mapSerialHashes) {
CMintMeta mint = it.second;
//This is only intended for unarchived coins
if (mint.isArchived)
continue;
// Update the metadata of the mints if requested
if (fUpdateStatus && UpdateStatusInternal(setMempool, mint)) {
if (mint.isArchived)
continue;
// Mint was updated, queue for overwrite
vOverWrite.emplace_back(mint);
}
if (fUnusedOnly && mint.isUsed)
continue;
if (fMatureOnly) {
// Not confirmed
if (!mint.nHeight || mint.nHeight > chainActive.Height() - Params().Zerocoin_MintRequiredConfirmations())
continue;
if (mint.nHeight >= mapMaturity.at(mint.denom))
continue;
}
setMints.insert(mint);
}
//overwrite any updates
for (CMintMeta& meta : vOverWrite)
UpdateState(meta);
return setMints;
}
void CzZEFIRTracker::Clear()
{
mapSerialHashes.clear();
}
|
/**
* Copyright 2014 MongoDB Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, the copyright holders give permission to link the
* code of portions of this program with the OpenSSL library under certain
* conditions as described in each individual source file and distribute
* linked combinations including the program with the OpenSSL library. You
* must comply with the GNU Affero General Public License in all respects for
* all of the code used other than as permitted herein. If you modify file(s)
* with this exception, you may extend this exception to your version of the
* file(s), but you are not obligated to do so. If you do not wish to do so,
* delete this exception statement from your version. If you delete this
* exception statement from all source files in the program, then also delete
* it in the license file.
*/
#include "mongo/platform/basic.h"
#include "mongo/db/repl/repl_set_config.h"
#include <algorithm>
#include "mongo/bson/util/bson_check.h"
#include "mongo/bson/util/bson_extract.h"
#include "mongo/db/jsobj.h"
#include "mongo/db/server_options.h"
#include "mongo/stdx/functional.h"
#include "mongo/util/stringutils.h"
namespace mongo {
namespace repl {
const size_t ReplSetConfig::kMaxMembers;
const size_t ReplSetConfig::kMaxVotingMembers;
const std::string ReplSetConfig::kConfigServerFieldName = "configsvr";
const std::string ReplSetConfig::kVersionFieldName = "version";
const std::string ReplSetConfig::kMajorityWriteConcernModeName = "$majority";
const Milliseconds ReplSetConfig::kDefaultHeartbeatInterval(2000);
const Seconds ReplSetConfig::kDefaultHeartbeatTimeoutPeriod(10);
const Milliseconds ReplSetConfig::kDefaultElectionTimeoutPeriod(10000);
const Milliseconds ReplSetConfig::kDefaultCatchUpTimeoutPeriod(2000);
const bool ReplSetConfig::kDefaultChainingAllowed(true);
namespace {
const std::string kIdFieldName = "_id";
const std::string kMembersFieldName = "members";
const std::string kSettingsFieldName = "settings";
const std::string kStepDownCheckWriteConcernModeName = "$stepDownCheck";
const std::string kProtocolVersionFieldName = "protocolVersion";
const std::string kWriteConcernMajorityJournalDefaultFieldName =
"writeConcernMajorityJournalDefault";
const std::string kLegalConfigTopFieldNames[] = {kIdFieldName,
ReplSetConfig::kVersionFieldName,
kMembersFieldName,
kSettingsFieldName,
kProtocolVersionFieldName,
ReplSetConfig::kConfigServerFieldName,
kWriteConcernMajorityJournalDefaultFieldName};
const std::string kChainingAllowedFieldName = "chainingAllowed";
const std::string kElectionTimeoutFieldName = "electionTimeoutMillis";
const std::string kGetLastErrorDefaultsFieldName = "getLastErrorDefaults";
const std::string kGetLastErrorModesFieldName = "getLastErrorModes";
const std::string kHeartbeatIntervalFieldName = "heartbeatIntervalMillis";
const std::string kHeartbeatTimeoutFieldName = "heartbeatTimeoutSecs";
const std::string kCatchUpTimeoutFieldName = "catchUpTimeoutMillis";
const std::string kReplicaSetIdFieldName = "replicaSetId";
} // namespace
Status ReplSetConfig::initialize(const BSONObj& cfg,
bool usePV1ByDefault,
OID defaultReplicaSetId) {
return _initialize(cfg, false, usePV1ByDefault, defaultReplicaSetId);
}
Status ReplSetConfig::initializeForInitiate(const BSONObj& cfg, bool usePV1ByDefault) {
return _initialize(cfg, true, usePV1ByDefault, OID());
}
Status ReplSetConfig::_initialize(const BSONObj& cfg,
bool forInitiate,
bool usePV1ByDefault,
OID defaultReplicaSetId) {
_isInitialized = false;
_members.clear();
Status status =
bsonCheckOnlyHasFields("replica set configuration", cfg, kLegalConfigTopFieldNames);
if (!status.isOK())
return status;
//
// Parse replSetName
//
status = bsonExtractStringField(cfg, kIdFieldName, &_replSetName);
if (!status.isOK())
return status;
//
// Parse version
//
status = bsonExtractIntegerField(cfg, kVersionFieldName, &_version);
if (!status.isOK())
return status;
//
// Parse members
//
BSONElement membersElement;
status = bsonExtractTypedField(cfg, kMembersFieldName, Array, &membersElement);
if (!status.isOK())
return status;
for (BSONObj::iterator membersIterator(membersElement.Obj()); membersIterator.more();) {
BSONElement memberElement = membersIterator.next();
if (memberElement.type() != Object) {
return Status(ErrorCodes::TypeMismatch,
str::stream() << "Expected type of " << kMembersFieldName << "."
<< memberElement.fieldName()
<< " to be Object, but found "
<< typeName(memberElement.type()));
}
_members.resize(_members.size() + 1);
const auto& memberBSON = memberElement.Obj();
status = _members.back().initialize(memberBSON, &_tagConfig);
if (!status.isOK())
return Status(ErrorCodes::InvalidReplicaSetConfig,
str::stream() << status.toString() << " for member:" << memberBSON);
}
//
// Parse configServer
//
status = bsonExtractBooleanFieldWithDefault(
cfg,
kConfigServerFieldName,
forInitiate ? serverGlobalParams.clusterRole == ClusterRole::ConfigServer : false,
&_configServer);
if (!status.isOK()) {
return status;
}
//
// Parse protocol version
//
status = bsonExtractIntegerField(cfg, kProtocolVersionFieldName, &_protocolVersion);
if (!status.isOK()) {
if (status != ErrorCodes::NoSuchKey) {
return status;
}
if (usePV1ByDefault) {
_protocolVersion = 1;
}
}
//
// Parse writeConcernMajorityJournalDefault
//
status = bsonExtractBooleanFieldWithDefault(cfg,
kWriteConcernMajorityJournalDefaultFieldName,
_protocolVersion == 1,
&_writeConcernMajorityJournalDefault);
if (!status.isOK())
return status;
//
// Parse settings
//
BSONElement settingsElement;
status = bsonExtractTypedField(cfg, kSettingsFieldName, Object, &settingsElement);
BSONObj settings;
if (status.isOK()) {
settings = settingsElement.Obj();
} else if (status != ErrorCodes::NoSuchKey) {
return status;
}
status = _parseSettingsSubdocument(settings);
if (!status.isOK())
return status;
//
// Generate replica set ID if called from replSetInitiate.
// Otherwise, uses 'defaultReplicatSetId' as default if 'cfg' doesn't have an ID.
//
if (forInitiate) {
if (_replicaSetId.isSet()) {
return Status(ErrorCodes::InvalidReplicaSetConfig,
str::stream() << "replica set configuration cannot contain '"
<< kReplicaSetIdFieldName
<< "' "
"field when called from replSetInitiate: "
<< cfg);
}
_replicaSetId = OID::gen();
} else if (!_replicaSetId.isSet()) {
_replicaSetId = defaultReplicaSetId;
}
_calculateMajorities();
_addInternalWriteConcernModes();
_initializeConnectionString();
_isInitialized = true;
return Status::OK();
}
Status ReplSetConfig::_parseSettingsSubdocument(const BSONObj& settings) {
//
// Parse heartbeatIntervalMillis
//
long long heartbeatIntervalMillis;
Status hbIntervalStatus =
bsonExtractIntegerFieldWithDefault(settings,
kHeartbeatIntervalFieldName,
durationCount<Milliseconds>(kDefaultHeartbeatInterval),
&heartbeatIntervalMillis);
if (!hbIntervalStatus.isOK()) {
return hbIntervalStatus;
}
_heartbeatInterval = Milliseconds(heartbeatIntervalMillis);
//
// Parse electionTimeoutMillis
//
auto greaterThanZero = stdx::bind(std::greater<long long>(), stdx::placeholders::_1, 0);
long long electionTimeoutMillis;
auto electionTimeoutStatus = bsonExtractIntegerFieldWithDefaultIf(
settings,
kElectionTimeoutFieldName,
durationCount<Milliseconds>(kDefaultElectionTimeoutPeriod),
greaterThanZero,
"election timeout must be greater than 0",
&electionTimeoutMillis);
if (!electionTimeoutStatus.isOK()) {
return electionTimeoutStatus;
}
_electionTimeoutPeriod = Milliseconds(electionTimeoutMillis);
//
// Parse heartbeatTimeoutSecs
//
long long heartbeatTimeoutSecs;
Status heartbeatTimeoutStatus =
bsonExtractIntegerFieldWithDefaultIf(settings,
kHeartbeatTimeoutFieldName,
durationCount<Seconds>(kDefaultHeartbeatTimeoutPeriod),
greaterThanZero,
"heartbeat timeout must be greater than 0",
&heartbeatTimeoutSecs);
if (!heartbeatTimeoutStatus.isOK()) {
return heartbeatTimeoutStatus;
}
_heartbeatTimeoutPeriod = Seconds(heartbeatTimeoutSecs);
//
// Parse catchUpTimeoutMillis
//
auto notLessThanZero = stdx::bind(std::greater_equal<long long>(), stdx::placeholders::_1, 0);
long long catchUpTimeoutMillis;
Status catchUpTimeoutStatus = bsonExtractIntegerFieldWithDefaultIf(
settings,
kCatchUpTimeoutFieldName,
durationCount<Milliseconds>(kDefaultCatchUpTimeoutPeriod),
notLessThanZero,
"catch-up timeout must be greater than or equal to 0",
&catchUpTimeoutMillis);
if (!catchUpTimeoutStatus.isOK()) {
return catchUpTimeoutStatus;
}
_catchUpTimeoutPeriod = Milliseconds(catchUpTimeoutMillis);
//
// Parse chainingAllowed
//
Status status = bsonExtractBooleanFieldWithDefault(
settings, kChainingAllowedFieldName, kDefaultChainingAllowed, &_chainingAllowed);
if (!status.isOK())
return status;
//
// Parse getLastErrorDefaults
//
BSONElement gleDefaultsElement;
status = bsonExtractTypedField(
settings, kGetLastErrorDefaultsFieldName, Object, &gleDefaultsElement);
if (status.isOK()) {
status = _defaultWriteConcern.parse(gleDefaultsElement.Obj());
if (!status.isOK())
return status;
} else if (status == ErrorCodes::NoSuchKey) {
// Default write concern is w: 1.
_defaultWriteConcern.reset();
_defaultWriteConcern.wNumNodes = 1;
} else {
return status;
}
//
// Parse getLastErrorModes
//
BSONElement gleModesElement;
status = bsonExtractTypedField(settings, kGetLastErrorModesFieldName, Object, &gleModesElement);
BSONObj gleModes;
if (status.isOK()) {
gleModes = gleModesElement.Obj();
} else if (status != ErrorCodes::NoSuchKey) {
return status;
}
for (BSONObj::iterator gleModeIter(gleModes); gleModeIter.more();) {
const BSONElement modeElement = gleModeIter.next();
if (_customWriteConcernModes.find(modeElement.fieldNameStringData()) !=
_customWriteConcernModes.end()) {
return Status(ErrorCodes::DuplicateKey,
str::stream() << kSettingsFieldName << '.' << kGetLastErrorModesFieldName
<< " contains multiple fields named "
<< modeElement.fieldName());
}
if (modeElement.type() != Object) {
return Status(ErrorCodes::TypeMismatch,
str::stream() << "Expected " << kSettingsFieldName << '.'
<< kGetLastErrorModesFieldName
<< '.'
<< modeElement.fieldName()
<< " to be an Object, not "
<< typeName(modeElement.type()));
}
ReplSetTagPattern pattern = _tagConfig.makePattern();
for (BSONObj::iterator constraintIter(modeElement.Obj()); constraintIter.more();) {
const BSONElement constraintElement = constraintIter.next();
if (!constraintElement.isNumber()) {
return Status(ErrorCodes::TypeMismatch,
str::stream() << "Expected " << kSettingsFieldName << '.'
<< kGetLastErrorModesFieldName
<< '.'
<< modeElement.fieldName()
<< '.'
<< constraintElement.fieldName()
<< " to be a number, not "
<< typeName(constraintElement.type()));
}
const int minCount = constraintElement.numberInt();
if (minCount <= 0) {
return Status(ErrorCodes::BadValue,
str::stream() << "Value of " << kSettingsFieldName << '.'
<< kGetLastErrorModesFieldName
<< '.'
<< modeElement.fieldName()
<< '.'
<< constraintElement.fieldName()
<< " must be positive, but found "
<< minCount);
}
status = _tagConfig.addTagCountConstraintToPattern(
&pattern, constraintElement.fieldNameStringData(), minCount);
if (!status.isOK()) {
return status;
}
}
_customWriteConcernModes[modeElement.fieldNameStringData()] = pattern;
}
// Parse replica set ID.
OID replicaSetId;
status = mongo::bsonExtractOIDField(settings, kReplicaSetIdFieldName, &replicaSetId);
if (status.isOK()) {
if (!replicaSetId.isSet()) {
return Status(ErrorCodes::BadValue,
str::stream() << kReplicaSetIdFieldName << " field value cannot be null");
}
} else if (status != ErrorCodes::NoSuchKey) {
return status;
}
_replicaSetId = replicaSetId;
return Status::OK();
}
Status ReplSetConfig::validate() const {
if (_version <= 0 || _version > std::numeric_limits<int>::max()) {
return Status(ErrorCodes::BadValue,
str::stream() << kVersionFieldName << " field value of " << _version
<< " is out of range");
}
if (_replSetName.empty()) {
return Status(ErrorCodes::BadValue,
str::stream() << "Replica set configuration must have non-empty "
<< kIdFieldName
<< " field");
}
if (_heartbeatInterval < Milliseconds(0)) {
return Status(ErrorCodes::BadValue,
str::stream() << kSettingsFieldName << '.' << kHeartbeatIntervalFieldName
<< " field value must be non-negative, "
"but found "
<< durationCount<Milliseconds>(_heartbeatInterval));
}
if (_members.size() > kMaxMembers || _members.empty()) {
return Status(ErrorCodes::BadValue,
str::stream() << "Replica set configuration contains " << _members.size()
<< " members, but must have at least 1 and no more than "
<< kMaxMembers);
}
size_t localhostCount = 0;
size_t voterCount = 0;
size_t arbiterCount = 0;
size_t electableCount = 0;
for (size_t i = 0; i < _members.size(); ++i) {
const MemberConfig& memberI = _members[i];
Status status = memberI.validate();
if (!status.isOK())
return status;
if (memberI.getHostAndPort().isLocalHost()) {
++localhostCount;
}
if (memberI.isVoter()) {
++voterCount;
}
// Nodes may be arbiters or electable, or neither, but never both.
if (memberI.isArbiter()) {
++arbiterCount;
} else if (memberI.getPriority() > 0) {
++electableCount;
}
for (size_t j = 0; j < _members.size(); ++j) {
if (i == j)
continue;
const MemberConfig& memberJ = _members[j];
if (memberI.getId() == memberJ.getId()) {
return Status(ErrorCodes::BadValue,
str::stream() << "Found two member configurations with same "
<< MemberConfig::kIdFieldName
<< " field, "
<< kMembersFieldName
<< "."
<< i
<< "."
<< MemberConfig::kIdFieldName
<< " == "
<< kMembersFieldName
<< "."
<< j
<< "."
<< MemberConfig::kIdFieldName
<< " == "
<< memberI.getId());
}
if (memberI.getHostAndPort() == memberJ.getHostAndPort()) {
return Status(ErrorCodes::BadValue,
str::stream() << "Found two member configurations with same "
<< MemberConfig::kHostFieldName
<< " field, "
<< kMembersFieldName
<< "."
<< i
<< "."
<< MemberConfig::kHostFieldName
<< " == "
<< kMembersFieldName
<< "."
<< j
<< "."
<< MemberConfig::kHostFieldName
<< " == "
<< memberI.getHostAndPort().toString());
}
}
}
if (localhostCount != 0 && localhostCount != _members.size()) {
return Status(
ErrorCodes::BadValue,
str::stream()
<< "Either all host names in a replica set configuration must be localhost "
"references, or none must be; found "
<< localhostCount
<< " out of "
<< _members.size());
}
if (voterCount > kMaxVotingMembers || voterCount == 0) {
return Status(ErrorCodes::BadValue,
str::stream() << "Replica set configuration contains " << voterCount
<< " voting members, but must be at least 1 and no more than "
<< kMaxVotingMembers);
}
if (electableCount == 0) {
return Status(ErrorCodes::BadValue,
"Replica set configuration must contain at least "
"one non-arbiter member with priority > 0");
}
if (_defaultWriteConcern.wMode.empty()) {
if (_defaultWriteConcern.wNumNodes == 0) {
return Status(ErrorCodes::BadValue,
"Default write concern mode must wait for at least 1 member");
}
} else {
if (WriteConcernOptions::kMajority != _defaultWriteConcern.wMode &&
!findCustomWriteMode(_defaultWriteConcern.wMode).isOK()) {
return Status(ErrorCodes::BadValue,
str::stream() << "Default write concern requires undefined write mode "
<< _defaultWriteConcern.wMode);
}
}
if (_protocolVersion != 0 && _protocolVersion != 1) {
return Status(ErrorCodes::BadValue,
str::stream() << kProtocolVersionFieldName << " field value of "
<< _protocolVersion
<< " is not 1 or 0");
}
if (_configServer) {
if (_protocolVersion == 0) {
return Status(ErrorCodes::BadValue, "Config servers cannot run in protocolVersion 0");
}
if (arbiterCount > 0) {
return Status(ErrorCodes::BadValue,
"Arbiters are not allowed in replica set configurations being used for "
"config servers");
}
for (MemberIterator mem = membersBegin(); mem != membersEnd(); mem++) {
if (!mem->shouldBuildIndexes()) {
return Status(ErrorCodes::BadValue,
"Members in replica set configurations being used for config "
"servers must build indexes");
}
if (mem->getSlaveDelay() != Seconds(0)) {
return Status(ErrorCodes::BadValue,
"Members in replica set configurations being used for config "
"servers cannot have a non-zero slaveDelay");
}
}
if (serverGlobalParams.clusterRole != ClusterRole::ConfigServer) {
return Status(ErrorCodes::BadValue,
"Nodes being used for config servers must be started with the "
"--configsvr flag");
}
if (!_writeConcernMajorityJournalDefault) {
return Status(ErrorCodes::BadValue,
str::stream() << kWriteConcernMajorityJournalDefaultFieldName
<< " must be true in replica set configurations being "
"used for config servers");
}
} else if (serverGlobalParams.clusterRole == ClusterRole::ConfigServer) {
return Status(ErrorCodes::BadValue,
"Nodes started with the --configsvr flag must have configsvr:true in "
"their config");
}
if (!_connectionString.isValid()) {
return Status(ErrorCodes::BadValue,
"ReplSetConfig represented an invalid replica set ConnectionString");
}
return Status::OK();
}
Status ReplSetConfig::checkIfWriteConcernCanBeSatisfied(
const WriteConcernOptions& writeConcern) const {
if (!writeConcern.wMode.empty() && writeConcern.wMode != WriteConcernOptions::kMajority) {
StatusWith<ReplSetTagPattern> tagPatternStatus = findCustomWriteMode(writeConcern.wMode);
if (!tagPatternStatus.isOK()) {
return tagPatternStatus.getStatus();
}
ReplSetTagMatch matcher(tagPatternStatus.getValue());
for (size_t j = 0; j < _members.size(); ++j) {
const MemberConfig& memberConfig = _members[j];
for (MemberConfig::TagIterator it = memberConfig.tagsBegin();
it != memberConfig.tagsEnd();
++it) {
if (matcher.update(*it)) {
return Status::OK();
}
}
}
// Even if all the nodes in the set had a given write it still would not satisfy this
// write concern mode.
return Status(ErrorCodes::CannotSatisfyWriteConcern,
str::stream() << "Not enough nodes match write concern mode \""
<< writeConcern.wMode
<< "\"");
} else {
int nodesRemaining = writeConcern.wNumNodes;
for (size_t j = 0; j < _members.size(); ++j) {
if (!_members[j].isArbiter()) { // Only count data-bearing nodes
--nodesRemaining;
if (nodesRemaining <= 0) {
return Status::OK();
}
}
}
return Status(ErrorCodes::CannotSatisfyWriteConcern, "Not enough data-bearing nodes");
}
}
const MemberConfig& ReplSetConfig::getMemberAt(size_t i) const {
invariant(i < _members.size());
return _members[i];
}
const MemberConfig* ReplSetConfig::findMemberByID(int id) const {
for (std::vector<MemberConfig>::const_iterator it = _members.begin(); it != _members.end();
++it) {
if (it->getId() == id) {
return &(*it);
}
}
return NULL;
}
const int ReplSetConfig::findMemberIndexByHostAndPort(const HostAndPort& hap) const {
int x = 0;
for (std::vector<MemberConfig>::const_iterator it = _members.begin(); it != _members.end();
++it) {
if (it->getHostAndPort() == hap) {
return x;
}
++x;
}
return -1;
}
const int ReplSetConfig::findMemberIndexByConfigId(long long configId) const {
int x = 0;
for (const auto& member : _members) {
if (member.getId() == configId) {
return x;
}
++x;
}
return -1;
}
const MemberConfig* ReplSetConfig::findMemberByHostAndPort(const HostAndPort& hap) const {
int idx = findMemberIndexByHostAndPort(hap);
return idx != -1 ? &getMemberAt(idx) : NULL;
}
Milliseconds ReplSetConfig::getHeartbeatInterval() const {
return _heartbeatInterval;
}
bool ReplSetConfig::isLocalHostAllowed() const {
// It is sufficient to check any one member's hostname, since in ReplSetConfig::validate,
// it's ensured that either all members have hostname localhost or none do.
return _members.begin()->getHostAndPort().isLocalHost();
}
ReplSetTag ReplSetConfig::findTag(StringData key, StringData value) const {
return _tagConfig.findTag(key, value);
}
StatusWith<ReplSetTagPattern> ReplSetConfig::findCustomWriteMode(StringData patternName) const {
const StringMap<ReplSetTagPattern>::const_iterator iter =
_customWriteConcernModes.find(patternName);
if (iter == _customWriteConcernModes.end()) {
return StatusWith<ReplSetTagPattern>(
ErrorCodes::UnknownReplWriteConcern,
str::stream() << "No write concern mode named '" << escape(patternName.toString())
<< "' found in replica set configuration");
}
return StatusWith<ReplSetTagPattern>(iter->second);
}
void ReplSetConfig::_calculateMajorities() {
const int voters = std::count_if(_members.begin(),
_members.end(),
stdx::bind(&MemberConfig::isVoter, stdx::placeholders::_1));
const int arbiters =
std::count_if(_members.begin(),
_members.end(),
stdx::bind(&MemberConfig::isArbiter, stdx::placeholders::_1));
_totalVotingMembers = voters;
_majorityVoteCount = voters / 2 + 1;
_writeMajority = std::min(_majorityVoteCount, voters - arbiters);
}
void ReplSetConfig::_addInternalWriteConcernModes() {
// $majority: the majority of voting nodes or all non-arbiter voting nodes if
// the majority of voting nodes are arbiters.
ReplSetTagPattern pattern = _tagConfig.makePattern();
Status status = _tagConfig.addTagCountConstraintToPattern(
&pattern, MemberConfig::kInternalVoterTagName, _writeMajority);
if (status.isOK()) {
_customWriteConcernModes[kMajorityWriteConcernModeName] = pattern;
} else if (status != ErrorCodes::NoSuchKey) {
// NoSuchKey means we have no $voter-tagged nodes in this config;
// other errors are unexpected.
fassert(28693, status);
}
// $stepDownCheck: one electable node plus ourselves
pattern = _tagConfig.makePattern();
status = _tagConfig.addTagCountConstraintToPattern(
&pattern, MemberConfig::kInternalElectableTagName, 2);
if (status.isOK()) {
_customWriteConcernModes[kStepDownCheckWriteConcernModeName] = pattern;
} else if (status != ErrorCodes::NoSuchKey) {
// NoSuchKey means we have no $electable-tagged nodes in this config;
// other errors are unexpected
fassert(28694, status);
}
}
void ReplSetConfig::_initializeConnectionString() {
std::vector<HostAndPort> visibleMembers;
for (const auto& member : _members) {
if (!member.isHidden() && !member.isArbiter()) {
visibleMembers.push_back(member.getHostAndPort());
}
}
try {
_connectionString = ConnectionString::forReplicaSet(_replSetName, visibleMembers);
} catch (const DBException& e) {
invariant(e.getCode() == ErrorCodes::FailedToParse);
// Failure to construct the ConnectionString means either an invalid replica set name
// or members array, which should be caught in validate()
}
}
BSONObj ReplSetConfig::toBSON() const {
BSONObjBuilder configBuilder;
configBuilder.append(kIdFieldName, _replSetName);
configBuilder.appendIntOrLL(kVersionFieldName, _version);
if (_configServer) {
// Only include "configsvr" field if true
configBuilder.append(kConfigServerFieldName, _configServer);
}
// Only include writeConcernMajorityJournalDefault if it is not the default version for this
// ProtocolVersion to prevent breaking cross version-3.2.1 compatibilty of ReplSetConfigs.
if (_protocolVersion > 0) {
configBuilder.append(kProtocolVersionFieldName, _protocolVersion);
// Only include writeConcernMajorityJournalDefault if it is not the default version for this
// ProtocolVersion to prevent breaking cross version-3.2.1 compatibilty of
// ReplSetConfigs.
if (!_writeConcernMajorityJournalDefault) {
configBuilder.append(kWriteConcernMajorityJournalDefaultFieldName,
_writeConcernMajorityJournalDefault);
}
} else if (_writeConcernMajorityJournalDefault) {
configBuilder.append(kWriteConcernMajorityJournalDefaultFieldName,
_writeConcernMajorityJournalDefault);
}
BSONArrayBuilder members(configBuilder.subarrayStart(kMembersFieldName));
for (MemberIterator mem = membersBegin(); mem != membersEnd(); mem++) {
members.append(mem->toBSON(getTagConfig()));
}
members.done();
BSONObjBuilder settingsBuilder(configBuilder.subobjStart(kSettingsFieldName));
settingsBuilder.append(kChainingAllowedFieldName, _chainingAllowed);
settingsBuilder.appendIntOrLL(kHeartbeatIntervalFieldName,
durationCount<Milliseconds>(_heartbeatInterval));
settingsBuilder.appendIntOrLL(kHeartbeatTimeoutFieldName,
durationCount<Seconds>(_heartbeatTimeoutPeriod));
settingsBuilder.appendIntOrLL(kElectionTimeoutFieldName,
durationCount<Milliseconds>(_electionTimeoutPeriod));
settingsBuilder.appendIntOrLL(kCatchUpTimeoutFieldName,
durationCount<Milliseconds>(_catchUpTimeoutPeriod));
BSONObjBuilder gleModes(settingsBuilder.subobjStart(kGetLastErrorModesFieldName));
for (StringMap<ReplSetTagPattern>::const_iterator mode = _customWriteConcernModes.begin();
mode != _customWriteConcernModes.end();
++mode) {
if (mode->first[0] == '$') {
// Filter out internal modes
continue;
}
BSONObjBuilder modeBuilder(gleModes.subobjStart(mode->first));
for (ReplSetTagPattern::ConstraintIterator itr = mode->second.constraintsBegin();
itr != mode->second.constraintsEnd();
itr++) {
modeBuilder.append(_tagConfig.getTagKey(ReplSetTag(itr->getKeyIndex(), 0)),
itr->getMinCount());
}
modeBuilder.done();
}
gleModes.done();
settingsBuilder.append(kGetLastErrorDefaultsFieldName, _defaultWriteConcern.toBSON());
if (_replicaSetId.isSet()) {
settingsBuilder.append(kReplicaSetIdFieldName, _replicaSetId);
}
settingsBuilder.done();
return configBuilder.obj();
}
std::vector<std::string> ReplSetConfig::getWriteConcernNames() const {
std::vector<std::string> names;
for (StringMap<ReplSetTagPattern>::const_iterator mode = _customWriteConcernModes.begin();
mode != _customWriteConcernModes.end();
++mode) {
names.push_back(mode->first);
}
return names;
}
Milliseconds ReplSetConfig::getPriorityTakeoverDelay(int memberIdx) const {
auto member = getMemberAt(memberIdx);
int priorityRank = _calculatePriorityRank(member.getPriority());
return (priorityRank + 1) * getElectionTimeoutPeriod();
}
int ReplSetConfig::_calculatePriorityRank(double priority) const {
int count = 0;
for (MemberIterator mem = membersBegin(); mem != membersEnd(); mem++) {
if (mem->getPriority() > priority) {
count++;
}
}
return count;
}
} // namespace repl
} // namespace mongo
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.