hexsha stringlengths 40 40 | size int64 22 2.4M | ext stringclasses 5
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 3 260 | max_stars_repo_name stringlengths 5 109 | max_stars_repo_head_hexsha stringlengths 40 78 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 3 260 | max_issues_repo_name stringlengths 5 109 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 260 | max_forks_repo_name stringlengths 5 109 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 9 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 22 2.4M | avg_line_length float64 5 169k | max_line_length int64 5 786k | alphanum_fraction float64 0.06 0.95 | matches listlengths 1 11 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
8c083fb69bd85b3fa476797e1ab46eeb088b3c51 | 480 | h | C | godgame2/ModelHandler.h | magnificus/godgame | cafb36830263d95516eb014f432319cabf50bda7 | [
"Unlicense"
] | 5 | 2017-10-31T17:36:13.000Z | 2021-11-05T21:01:04.000Z | godgame2/ModelHandler.h | magnificus/godgame | cafb36830263d95516eb014f432319cabf50bda7 | [
"Unlicense"
] | null | null | null | godgame2/ModelHandler.h | magnificus/godgame | cafb36830263d95516eb014f432319cabf50bda7 | [
"Unlicense"
] | null | null | null | #pragma once
#include "Model.h"
#include "BaseLibrary.h"
class ModelHandler {
public:
~ModelHandler();
void clearModels();
void renderModels(bool outline, glm::mat4 proj, glm::mat4 view, Shader *overrideShader = nullptr, glm::vec3 scale = glm::vec3(1.0, 1.0, 1.0), bool outlineColor = false);
RenderInfo getRenderInfo();
std::vector<unsigned int> cutoffPositions;
void addModel(Model *m);
std::vector<Model*> models;
unsigned int VAO;
private:
}; | 22.857143 | 171 | 0.689583 | [
"vector",
"model"
] |
8c0bcc9ec59526a63c308b8029d883ce1083b63f | 10,207 | h | C | include/cetty/util/Exception.h | frankee/cetty2 | 62ac0cd1438275097e47a9ba471e72efd2746ded | [
"BSL-1.0",
"Apache-2.0",
"BSD-3-Clause"
] | 26 | 2015-11-08T10:58:21.000Z | 2021-02-25T08:27:26.000Z | include/cetty/util/Exception.h | frankee/cetty2 | 62ac0cd1438275097e47a9ba471e72efd2746ded | [
"BSL-1.0",
"Apache-2.0",
"BSD-3-Clause"
] | 1 | 2019-02-18T08:46:17.000Z | 2019-02-18T08:46:17.000Z | include/cetty/util/Exception.h | frankee/cetty2 | 62ac0cd1438275097e47a9ba471e72efd2746ded | [
"BSL-1.0",
"Apache-2.0",
"BSD-3-Clause"
] | 8 | 2016-02-27T02:37:10.000Z | 2021-09-29T05:25:00.000Z | #if !defined(CETTY_UTIL_EXCEPTION_H)
#define CETTY_UTIL_EXCEPTION_H
//
// Exception.h
//
// $Id: //poco/1.4/Foundation/include/Poco/Exception.h#1 $
//
// Library: Foundation
// Package: Core
// Module: Exception
//
// Definition of various Poco exception classes.
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// 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, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include <string>
#include <typeinfo>
#include <stdexcept>
namespace cetty {
namespace util {
/**
* This is the base class for all exceptions defined
* in the cetty class library.
*/
class Exception: public std::exception {
public:
/**
* Creates an exception.
*/
Exception(const std::string& msg, int code = 0);
/**
* Creates an exception.
*/
Exception(const std::string& msg, const std::string& arg, int code = 0);
/**
* Creates an exception and stores a clone of the nested exception.
*/
Exception(const std::string& msg, const Exception& nested, int code = 0);
/**
* Copy constructor.
*/
Exception(const Exception& exc);
/**
* Destroys the exception and deletes the nested exception.
*/
virtual ~Exception() throw();
/**
* Assignment operator.
*/
Exception& operator = (const Exception& exc);
/**
* Returns a static string describing the exception.
*/
virtual const char* name() const throw();
/**
* Returns the name of the exception class.
*/
virtual const char* className() const throw();
/**
* Returns a static string describing the exception.
* Same as name(), but for compatibility with std::exception.
*/
virtual const char* what() const throw();
/**
* Returns a pointer to the nested exception, or
* null if no nested exception exists.
*/
const Exception* nested() const { return nested_; }
/**
* Returns the message text.
*/
const std::string& message() const { return message_; }
/**
* Returns the exception code if defined.
*/
int code() const { return code_; }
/**
* Returns a string consisting of the message name and the message text.
*/
std::string displayText() const;
/**
* Creates an exact copy of the exception.
*
* The copy can later be thrown again by
* invoking rethrow() on it.
*/
virtual Exception* clone() const;
/**
* (Re)Throws the exception.
*
* This is useful for temporarily storing a
* copy of an exception (see clone()), then
* throwing it again.
*/
virtual void rethrow() const;
protected:
Exception(int code = 0);
void setMessage(const std::string& msg);
/**
* Sets the extended message for the exception.
*/
void extendedMessage(const std::string& arg);
private:
int code_;
std::string message_;
Exception* nested_;
};
inline
void Exception::setMessage(const std::string& msg) {
message_ = msg;
}
//
// Macros for quickly declaring and implementing exception classes.
// Unfortunately, we cannot use a template here because character
// pointers (which we need for specifying the exception name)
// are not allowed as template arguments.
//
#define CETTY_DECLARE_EXCEPTION(CLS, BASE) \
class CLS : public BASE { \
public: \
CLS(int code = 0); \
CLS(const std::string& message, \
int code = 0); \
CLS(const std::string& message, \
const std::string& arg, \
int code = 0); \
CLS(const std::string& message, \
const ::cetty::util::Exception& exc, \
int code = 0); \
CLS(const CLS& exc); \
virtual ~CLS() throw(); \
CLS& operator = (const CLS& exc); \
const char* name() const throw(); \
const char* className() const throw(); \
::cetty::util::Exception* clone() const; \
void rethrow() const; \
};
#define CETTY_IMPLEMENT_EXCEPTION(CLS, BASE, NAME) \
CLS::CLS(int code): BASE(code) {} \
CLS::CLS(const std::string& message, int code) \
: BASE(message, code) {} \
CLS::CLS(const std::string& message, \
const std::string& arg, int code) \
: BASE(message, arg, code) {} \
CLS::CLS(const std::string& message, \
const cetty::util::Exception& exc, \
int code) \
: BASE(message, exc, code) {} \
CLS::CLS(const CLS& exc) : BASE(exc) {} \
CLS::~CLS() throw() {} \
\
CLS& CLS::operator = (const CLS& exc) { \
BASE::operator = (exc); \
return *this; \
} \
const char* CLS::name() const throw() { \
return NAME; \
} \
const char* CLS::className() const throw() { \
return typeid(*this).name(); \
} \
cetty::util::Exception* CLS::clone() const { \
return new CLS(*this); \
} \
void CLS::rethrow() const { \
throw *this; \
}
//
// Standard exception classes
//
CETTY_DECLARE_EXCEPTION(LogicException, Exception)
CETTY_DECLARE_EXCEPTION(AssertionViolationException, LogicException)
CETTY_DECLARE_EXCEPTION(NullPointerException, LogicException)
CETTY_DECLARE_EXCEPTION(NullValueException, LogicException)
CETTY_DECLARE_EXCEPTION(BugcheckException, LogicException)
CETTY_DECLARE_EXCEPTION(InvalidArgumentException, LogicException)
CETTY_DECLARE_EXCEPTION(NotImplementedException, LogicException)
CETTY_DECLARE_EXCEPTION(UnsupportedOperationException, LogicException)
CETTY_DECLARE_EXCEPTION(RangeException, LogicException)
CETTY_DECLARE_EXCEPTION(IllegalStateException, LogicException)
CETTY_DECLARE_EXCEPTION(NumberFormatException, LogicException)
CETTY_DECLARE_EXCEPTION(InvalidAccessException, LogicException)
CETTY_DECLARE_EXCEPTION(SignalException, LogicException)
CETTY_DECLARE_EXCEPTION(UnhandledException, LogicException)
CETTY_DECLARE_EXCEPTION(RuntimeException, Exception)
CETTY_DECLARE_EXCEPTION(NotFoundException, RuntimeException)
CETTY_DECLARE_EXCEPTION(ExistsException, RuntimeException)
CETTY_DECLARE_EXCEPTION(TimeoutException, RuntimeException)
CETTY_DECLARE_EXCEPTION(SystemException, RuntimeException)
CETTY_DECLARE_EXCEPTION(RegularExpressionException, RuntimeException)
CETTY_DECLARE_EXCEPTION(LibraryLoadException, RuntimeException)
CETTY_DECLARE_EXCEPTION(LibraryAlreadyLoadedException, RuntimeException)
CETTY_DECLARE_EXCEPTION(NoThreadAvailableException, RuntimeException)
CETTY_DECLARE_EXCEPTION(NotYetConnectedException, RuntimeException)
CETTY_DECLARE_EXCEPTION(InterruptedException, RuntimeException)
CETTY_DECLARE_EXCEPTION(PropertyNotSupportedException, RuntimeException)
CETTY_DECLARE_EXCEPTION(PoolOverflowException, RuntimeException)
CETTY_DECLARE_EXCEPTION(NoPermissionException, RuntimeException)
CETTY_DECLARE_EXCEPTION(OutOfMemoryException, RuntimeException)
CETTY_DECLARE_EXCEPTION(DataException, RuntimeException)
CETTY_DECLARE_EXCEPTION(DataFormatException, DataException)
CETTY_DECLARE_EXCEPTION(SyntaxException, DataException)
CETTY_DECLARE_EXCEPTION(CircularReferenceException, DataException)
CETTY_DECLARE_EXCEPTION(PathSyntaxException, SyntaxException)
CETTY_DECLARE_EXCEPTION(IOException, RuntimeException)
CETTY_DECLARE_EXCEPTION(ProtocolException, IOException)
CETTY_DECLARE_EXCEPTION(FileException, IOException)
CETTY_DECLARE_EXCEPTION(FileExistsException, FileException)
CETTY_DECLARE_EXCEPTION(FileNotFoundException, FileException)
CETTY_DECLARE_EXCEPTION(PathNotFoundException, FileException)
CETTY_DECLARE_EXCEPTION(FileReadOnlyException, FileException)
CETTY_DECLARE_EXCEPTION(FileAccessDeniedException, FileException)
CETTY_DECLARE_EXCEPTION(CreateFileException, FileException)
CETTY_DECLARE_EXCEPTION(OpenFileException, FileException)
CETTY_DECLARE_EXCEPTION(WriteFileException, FileException)
CETTY_DECLARE_EXCEPTION(ReadFileException, FileException)
CETTY_DECLARE_EXCEPTION(UnknownURISchemeException, RuntimeException)
CETTY_DECLARE_EXCEPTION(ApplicationException, Exception)
CETTY_DECLARE_EXCEPTION(BadCastException, RuntimeException)
}
}
#endif //#if !defined(CETTY_UTIL_EXCEPTION_H)
// Local Variables:
// mode: c++
// End:
| 36.323843 | 78 | 0.666895 | [
"object"
] |
8c0e2825b1f7ce2a89592bae74aaa01edeab681c | 9,316 | c | C | libc/stdlib/lib_qsort.c | liuweisword/Nuttx | 63775322bf25adb406594f8e610122fe0cef2f7a | [
"Zlib"
] | 15 | 2017-07-21T07:26:56.000Z | 2022-01-11T17:51:02.000Z | libc/stdlib/lib_qsort.c | liuweisword/Nuttx | 63775322bf25adb406594f8e610122fe0cef2f7a | [
"Zlib"
] | 3 | 2018-12-10T08:54:04.000Z | 2019-11-04T08:53:38.000Z | libc/stdlib/lib_qsort.c | liuweisword/Nuttx | 63775322bf25adb406594f8e610122fe0cef2f7a | [
"Zlib"
] | 14 | 2017-02-20T07:36:52.000Z | 2021-12-28T03:07:04.000Z | /****************************************************************************
* libc/stdlib/lib_qsort.c
*
* Copyright (C) 2007, 2009, 2011 Gregory Nutt. All rights reserved.
* Author: Gregory Nutt <gnutt@nuttx.org>
*
* Leveraged from:
*
* Copyright (c) 1992, 1993
* The 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:
*
* 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. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the University of
* California, Berkeley and its contributors.
* 4. Neither the name of the University 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 REGENTS 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 REGENTS 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.
*
****************************************************************************/
/****************************************************************************
* Included Files
****************************************************************************/
#include <nuttx/config.h>
#include <sys/types.h>
#include <stdlib.h>
/****************************************************************************
* Pre-processor Definitions
****************************************************************************/
#define min(a, b) (a) < (b) ? a : b
#define swapcode(TYPE, parmi, parmj, n) \
{ \
long i = (n) / sizeof (TYPE); \
register TYPE *pi = (TYPE *)(parmi); \
register TYPE *pj = (TYPE *)(parmj); \
do { \
register TYPE t = *pi; \
*pi++ = *pj; \
*pj++ = t; \
} while (--i > 0); \
}
#define SWAPINIT(a, width) \
swaptype = ((FAR char *)a - (FAR char *)0) % sizeof(long) || \
width % sizeof(long) ? 2 : width == sizeof(long)? 0 : 1;
#define swap(a, b) \
if (swaptype == 0) \
{ \
long t = *(long *)(a); \
*(long *)(a) = *(long *)(b); \
*(long *)(b) = t; \
} \
else \
{ \
swapfunc(a, b, width, swaptype); \
}
#define vecswap(a, b, n) if ((n) > 0) swapfunc(a, b, n, swaptype)
/****************************************************************************
* Private Function Prototypes
****************************************************************************/
static inline void swapfunc(FAR char *a, FAR char *b, int n, int swaptype);
static inline FAR char *med3(FAR char *a, FAR char *b, FAR char *c,
CODE int (*compar)(FAR const void *,
FAR const void *));
/****************************************************************************
* Private Functions
****************************************************************************/
static inline void swapfunc(FAR char *a, FAR char *b, int n, int swaptype)
{
if (swaptype <= 1)
{
swapcode(long, a, b, n)
}
else
{
swapcode(char, a, b, n)
}
}
static inline FAR char *med3(FAR char *a, FAR char *b, FAR char *c,
CODE int (*compar)(FAR const void *,
FAR const void *))
{
return compar(a, b) < 0 ?
(compar(b, c) < 0 ? b : (compar(a, c) < 0 ? c : a)) :
(compar(b, c) > 0 ? b : (compar(a, c) < 0 ? a : c));
}
/****************************************************************************
* Public Function
****************************************************************************/
/****************************************************************************
* Name: qsort
*
* Description:
* The qsort() function will sort an array of 'nel' objects, the initial
* element of which is pointed to by 'base'. The size of each object, in
* bytes, is specified by the 'width" argument. If the 'nel' argument has
* the value zero, the comparison function pointed to by 'compar' will not
* be called and no rearrangement will take place.
*
* The application will ensure that the comparison function pointed to by
* 'compar' does not alter the contents of the array. The implementation
* may reorder elements of the array between calls to the comparison
* function, but will not alter the contents of any individual element.
*
* When the same objects (consisting of 'width" bytes, irrespective of
* their current positions in the array) are passed more than once to
* the comparison function, the results will be consistent with one
* another. That is, they will define a total ordering on the array.
*
* The contents of the array will be sorted in ascending order according
* to a comparison function. The 'compar' argument is a pointer to the
* comparison function, which is called with two arguments that point to
* the elements being compared. The application will ensure that the
* function returns an integer less than, equal to, or greater than 0,
* if the first argument is considered respectively less than, equal to,
* or greater than the second. If two members compare as equal, their
* order in the sorted array is unspecified.
*
* (Based on description from OpenGroup.org).
*
* Returned Value:
* The qsort() function will not return a value.
*
* Notes from the original BSD version:
* Qsort routine from Bentley & McIlroy's "Engineering a Sort Function".
*
****************************************************************************/
void qsort(FAR void *base, size_t nel, size_t width,
CODE int(*compar)(FAR const void *, FAR const void *))
{
FAR char *pa;
FAR char *pb;
FAR char *pc;
FAR char *pd;
FAR char *pl;
FAR char *pm;
FAR char *pn;
int swaptype;
int swap_cnt;
int d;
int r;
loop:
SWAPINIT(base, width);
swap_cnt = 0;
if (nel < 7)
{
for (pm = (FAR char *)base + width;
pm < (FAR char *)base + nel * width;
pm += width)
{
for (pl = pm;
pl > (FAR char *)base && compar(pl - width, pl) > 0;
pl -= width)
{
swap(pl, pl - width);
}
}
return;
}
pm = (FAR char *)base + (nel / 2) * width;
if (nel > 7)
{
pl = base;
pn = (FAR char *)base + (nel - 1) * width;
if (nel > 40)
{
d = (nel / 8) * width;
pl = med3(pl, pl + d, pl + 2 * d, compar);
pm = med3(pm - d, pm, pm + d, compar);
pn = med3(pn - 2 * d, pn - d, pn, compar);
}
pm = med3(pl, pm, pn, compar);
}
swap(base, pm);
pa = pb = (FAR char *)base + width;
pc = pd = (FAR char *)base + (nel - 1) * width;
for (; ; )
{
while (pb <= pc && (r = compar(pb, base)) <= 0)
{
if (r == 0)
{
swap_cnt = 1;
swap(pa, pb);
pa += width;
}
pb += width;
}
while (pb <= pc && (r = compar(pc, base)) >= 0)
{
if (r == 0)
{
swap_cnt = 1;
swap(pc, pd);
pd -= width;
}
pc -= width;
}
if (pb > pc)
{
break;
}
swap(pb, pc);
swap_cnt = 1;
pb += width;
pc -= width;
}
if (swap_cnt == 0)
{
/* Switch to insertion sort */
for (pm = (FAR char *)base + width;
pm < (FAR char *)base + nel * width;
pm += width)
{
for (pl = pm;
pl > (FAR char *)base && compar(pl - width, pl) > 0;
pl -= width)
{
swap(pl, pl - width);
}
}
return;
}
pn = (FAR char *)base + nel * width;
r = min(pa - (FAR char *)base, pb - pa);
vecswap(base, pb - r, r);
r = min(pd - pc, pn - pd - width);
vecswap(pb, pn - r, r);
if ((r = pb - pa) > width)
{
qsort(base, r / width, width, compar);
}
if ((r = pd - pc) > width)
{
/* Iterate rather than recurse to save stack space */
base = pn - r;
nel = r / width;
goto loop;
}
}
| 31.261745 | 78 | 0.505689 | [
"object"
] |
ca9d2af0358fba8f84504e3c98e8b249eb3b1962 | 6,235 | c | C | src/ilPSP/layer_0/3rd_party/WinHypre/hypre/distributed_ls/ParaSails/RowPatt.c | leyel/BoSSS | 39f58a1a64a55e44f51384022aada20a5b425230 | [
"Apache-2.0"
] | 1 | 2018-12-20T10:55:58.000Z | 2018-12-20T10:55:58.000Z | src/ilPSP/layer_0/3rd_party/WinHypre/hypre/distributed_ls/ParaSails/RowPatt.c | leyel/BoSSS | 39f58a1a64a55e44f51384022aada20a5b425230 | [
"Apache-2.0"
] | null | null | null | src/ilPSP/layer_0/3rd_party/WinHypre/hypre/distributed_ls/ParaSails/RowPatt.c | leyel/BoSSS | 39f58a1a64a55e44f51384022aada20a5b425230 | [
"Apache-2.0"
] | null | null | null | /*BHEADER**********************************************************************
* Copyright (c) 2008, Lawrence Livermore National Security, LLC.
* Produced at the Lawrence Livermore National Laboratory.
* This file is part of HYPRE. See file COPYRIGHT for details.
*
* HYPRE is free software; you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License (as published by the Free
* Software Foundation) version 2.1 dated February 1999.
*
* $Revision: 2.4 $
***********************************************************************EHEADER*/
/******************************************************************************
*
* RowPatt - Pattern of a row, and functions to manipulate the pattern of
* a row, particularly merging a pattern with a set of nonzero indices.
*
* Implementation and Notes: a full-length array is used to mark nonzeros
* in the pattern. Indices must not equal -1, which is the "empty" marker
* used in the full length array. It is expected that RowPatt will only be
* presented with local indices, otherwise the full length array may be very
* large.
*
*****************************************************************************/
#include <stdlib.h>
#include <assert.h>
#include "Common.h"
#include "RowPatt.h"
/*--------------------------------------------------------------------------
* resize - local function for automatically increasing the size of RowPatt
*--------------------------------------------------------------------------*/
static void resize(RowPatt *p, int newlen)
{
int oldlen, i;
#ifdef PARASAILS_DEBUG
printf("RowPatt resize %d\n", newlen);
#endif
oldlen = p->maxlen;
p->maxlen = newlen;
p->ind = (int *) realloc(p->ind, p->maxlen * sizeof(int));
p->mark = (int *) realloc(p->mark, p->maxlen * sizeof(int));
/* initialize the new portion of the mark array */
for (i=oldlen; i<p->maxlen; i++)
p->mark[i] = -1;
}
/*--------------------------------------------------------------------------
* RowPattCreate - Return (a pointer to) a pattern of a row with a maximum
* of "maxlen" nonzeros.
*--------------------------------------------------------------------------*/
RowPatt *RowPattCreate(int maxlen)
{
int i;
RowPatt *p = (RowPatt *) malloc(sizeof(RowPatt));
p->maxlen = maxlen;
p->len = 0;
p->prev_len = 0;
p->ind = (int *) malloc(maxlen * sizeof(int));
p->mark = (int *) malloc(maxlen * sizeof(int));
p->buffer = NULL;
p->buflen = 0;
for (i=0; i<maxlen; i++)
p->mark[i] = -1;
return p;
}
/*--------------------------------------------------------------------------
* RowPattDestroy - Destroy a row pattern object "p".
*--------------------------------------------------------------------------*/
void RowPattDestroy(RowPatt *p)
{
free(p->ind);
free(p->mark);
free(p->buffer);
free(p);
}
/*--------------------------------------------------------------------------
* RowPattReset - Empty the pattern of row pattern object "p".
*--------------------------------------------------------------------------*/
void RowPattReset(RowPatt *p)
{
int i;
for (i=0; i<p->len; i++)
p->mark[p->ind[i]] = -1;
p->len = 0;
p->prev_len = 0;
}
/*--------------------------------------------------------------------------
* RowPattMerge - Merge the "len" nonzeros in array "ind" with pattern "p".
*--------------------------------------------------------------------------*/
void RowPattMerge(RowPatt *p, int len, int *ind)
{
int i;
for (i=0; i<len; i++)
{
if (ind[i] >= p->maxlen)
resize(p, ind[i]*2);
if (p->mark[ind[i]] == -1)
{
assert(p->len < p->maxlen);
p->mark[ind[i]] = p->len;
p->ind[p->len] = ind[i];
p->len++;
}
}
}
/*--------------------------------------------------------------------------
* RowPattMergeExt - Merge the external nonzeros in the array "ind" of
* length "len" with the pattern "p". The external indices are those
* that are less than "beg" or greater than "end".
*--------------------------------------------------------------------------*/
void RowPattMergeExt(RowPatt *p, int len, int *ind, int num_loc)
{
int i;
for (i=0; i<len; i++)
{
if (ind[i] < num_loc)
continue;
if (ind[i] >= p->maxlen)
resize(p, ind[i]*2);
if (p->mark[ind[i]] == -1)
{
assert(p->len < p->maxlen);
p->mark[ind[i]] = p->len;
p->ind[p->len] = ind[i];
p->len++;
}
}
}
/*--------------------------------------------------------------------------
* RowPattGet - Return the pattern of "p". The length and pointer to the
* pattern indices are returned through the parameters "lenp" and "indp".
* A copy of the indices is returned; this copy is destroyed on the next
* call to RowPattGet or RowPattPrevLevel.
*--------------------------------------------------------------------------*/
void RowPattGet(RowPatt *p, int *lenp, int **indp)
{
int len;
len = p->len;
if (len > p->buflen)
{
free(p->buffer);
p->buflen = len + 100;
p->buffer = (int *) malloc(p->buflen * sizeof(int));
}
memcpy(p->buffer, p->ind, len*sizeof(int));
*lenp = len;
*indp = p->buffer;
}
/*--------------------------------------------------------------------------
* RowPattPrevLevel - Return the new indices added to the pattern of "p"
* since the last call to RowPattPrevLevel (or all the indices if never
* called). The length and pointer to the pattern indices are returned
* through the parameters "lenp" and "indp".
* A copy of the indices is returned; this copy is destroyed on the next
* call to RowPattGet or RowPattPrevLevel.
*--------------------------------------------------------------------------*/
void RowPattPrevLevel(RowPatt *p, int *lenp, int **indp)
{
int len;
len = p->len - p->prev_len;
if (len > p->buflen)
{
free(p->buffer);
p->buflen = len + 100;
p->buffer = (int *) malloc(p->buflen * sizeof(int));
}
memcpy(p->buffer, &p->ind[p->prev_len], len*sizeof(int));
*lenp = len;
*indp = p->buffer;
p->prev_len = p->len;
}
| 28.865741 | 81 | 0.459824 | [
"object"
] |
ca9db2cc4743f7e63e4ba5f16cd623e3631eb4ea | 2,732 | h | C | templates/safe_queue.h | alexeiradashkovsky/alexei_template_classes | 1471ce8e88807fcd0d461b49810e1885e913eac0 | [
"MIT"
] | null | null | null | templates/safe_queue.h | alexeiradashkovsky/alexei_template_classes | 1471ce8e88807fcd0d461b49810e1885e913eac0 | [
"MIT"
] | null | null | null | templates/safe_queue.h | alexeiradashkovsky/alexei_template_classes | 1471ce8e88807fcd0d461b49810e1885e913eac0 | [
"MIT"
] | null | null | null | #ifndef SAFE_QUEUE_H__
#define SAFE_QUEUE_H__
/*
MIT License
Copyright (c) 2018 Alexei Radashkovsky
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 <queue> /*< std::queue >*/
#include <mutex> /*< std::mutex >*/
#include <condition_variable>
namespace alexei_prog_snob {
template<typename T> class SafeQueue {
public:
SafeQueue(){
}
~SafeQueue(){
}
/**
* @brief get element. Blocking if empty
* @param[in] _msTimeout : time to wait before shutdown.
*/
T Pop() {
std::unique_lock<std::mutex> lock(m_mutex);
m_cv.wait(lock, [this]()->bool{ return m_q.empty() != true; });
T ret_val = m_q.front();
m_q.pop();
return ret_val;
}
void Push(const T& _data) {
std::lock_guard<std::mutex> lock(m_mutex);
m_q.push(_data);
m_cv.notify_one();
}
bool Empty() {
std::lock_guard<std::mutex> lock(m_mutex);
return m_q.empty();
}
private:
std::mutex m_mutex;
std::condition_variable m_cv;
std::queue<T> m_q;
};
template<
typename T,
typename Container = std::vector<T>,
typename Comparison = std::less<typename Container::value_type>
>
class SafePriorityQueue {
public:
SafePriorityQueue(){
}
~SafePriorityQueue(){
}
T Pop() {
std::unique_lock<std::mutex> lock(m_mutex);
m_cv.wait(lock, [this]()->bool{ return m_q.empty() != true; });
T ret_val = m_q.top();
m_q.pop();
return ret_val;
}
void Push(const T& _data){
std::lock_guard<std::mutex> lock(m_mutex);
m_q.push(_data);
m_cv.notify_one();
}
bool Empty() {
std::lock_guard<std::mutex> lock(m_mutex);
return m_q.empty();
}
private:
std::mutex m_mutex;
std::condition_variable m_cv;
std::priority_queue<T, Container, Comparison> m_q;
};
} // end namespace
#endif /* SAFE_QUEUE_H__ */ | 24.176991 | 78 | 0.710469 | [
"vector"
] |
caa1a1c69804563a834effd9fdcf20d276438aab | 3,962 | h | C | shaka/src/memory/v8_heap_tracer.h | jgongo/shaka-player-embedded | e04f97b971c684ef18a370697584d5239fb711bd | [
"Apache-2.0",
"BSD-3-Clause"
] | 185 | 2018-11-06T06:04:44.000Z | 2022-03-02T22:20:39.000Z | shaka/src/memory/v8_heap_tracer.h | jgongo/shaka-player-embedded | e04f97b971c684ef18a370697584d5239fb711bd | [
"Apache-2.0",
"BSD-3-Clause"
] | 211 | 2018-11-15T22:52:49.000Z | 2022-03-02T18:46:20.000Z | shaka/src/memory/v8_heap_tracer.h | jgongo/shaka-player-embedded | e04f97b971c684ef18a370697584d5239fb711bd | [
"Apache-2.0",
"BSD-3-Clause"
] | 52 | 2018-12-12T11:00:46.000Z | 2022-02-23T17:35:02.000Z | // Copyright 2016 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef SHAKA_EMBEDDED_MEMORY_V8_HEAP_TRACER_H_
#define SHAKA_EMBEDDED_MEMORY_V8_HEAP_TRACER_H_
#include <unordered_set>
#include <utility>
#include <vector>
#include "src/memory/heap_tracer.h"
namespace shaka {
namespace memory {
/**
* This wraps the normal HeapTracer in an interface that can be used by V8
* to track objects. Methods defined here will be called by V8 when it decides
* that a GC needs to be run.
*
* This explains how the V8 GC works and how we interact with it:
*
* There are two kinds of objects that are managed by different GCs, a
* JavaScript object (v8::Value) which is handled by the V8 gc, and
* BackingObject's which are handled by ObjectTracker. When the V8 GC runs, we
* need to tell it what objects we hold so it knows the V8 objects to delete.
* That is the purpose of this class.
*
* When a V8 pass start, V8 will call TracePrologue. Then it will traverse
* its objects, marking alive objects. Any object that looks like a wrapper
* will be added to a list. Once the traversal is done, it will call
* RegisterV8References passing in the list. Then it will call AdvanceTracing
* to allow us to traverse our heap. We should traverse our alive objects
* and any wrapper objects given to us. We should then (a) mark these object
* as alive so we don't free them, and (b) tell V8 about any objects we hold.
*
* When we tell V8 about alive objects, it may need to do some more traversals,
* which may in turn find more wrappers. If this happens, it will call
* RegisterV8References and AdvanceTracing again.
*
* At points between method calls, it is possible for JavaScript to run.
* Because this runs on the event thread, it is not possible for JavaScript to
* run while one of these methods are being called, but between it is possible.
* V8 monitors all the objects and will ensure that any new objects will be
* given to us.
*
* After V8 has traced every object TraceEpilogue is called. We use this to
* free any object that is not marked as alive.
*/
class V8HeapTracer : public v8::EmbedderHeapTracer, public HeapTracer {
public:
V8HeapTracer();
~V8HeapTracer() override;
/** @return Whether tracing is done. */
bool IsTracingDone() override;
/** Called by V8 when a GC pass begins. */
void TracePrologue(TraceFlags flags) override;
/** Called by V8 when a GC pass ends. */
void TraceEpilogue(TraceSummary* trace_summary) override;
/**
* Called by V8 when entering the final marking phase. There will be no more
* incremental marking calls.
*/
void EnterFinalPause(EmbedderStackState stack_state) override;
/**
* Called by V8 to tell us about wrapper objects. The pair contains the
* internal field values of the wrapper object. We should store the values
* and process them only in AdvanceTracing.
*/
void RegisterV8References(
const std::vector<std::pair<void*, void*>>& internal_fields) override;
/**
* Called by V8 to advance the GC run. We should only take |deadline_ms|
* time to complete, telling V8 whether there is more work to do.
* @return True if there is more work to do, false if done.
*/
bool AdvanceTracing(double deadline_ms) override;
private:
std::unordered_set<const Traceable*> fields_;
};
} // namespace memory
} // namespace shaka
#endif // SHAKA_EMBEDDED_MEMORY_V8_HEAP_TRACER_H_
| 37.733333 | 79 | 0.736749 | [
"object",
"vector"
] |
caa334a4fad1ebfa0bae4093c0de3f3a10f9807d | 1,564 | h | C | Modules/CLI/ParaToSPHARMMeshCLP/itkMeshTovtkPolyData.h | jcfr/SPHARM-PDM | 10a9fa8731ff43eedea980bade46c676413378a5 | [
"Apache-2.0"
] | 33 | 2015-03-31T16:22:24.000Z | 2022-02-25T03:32:32.000Z | Modules/CLI/ParaToSPHARMMeshCLP/itkMeshTovtkPolyData.h | jcfr/SPHARM-PDM | 10a9fa8731ff43eedea980bade46c676413378a5 | [
"Apache-2.0"
] | 39 | 2015-04-01T12:30:34.000Z | 2021-12-09T18:48:39.000Z | Modules/CLI/ParaToSPHARMMeshCLP/itkMeshTovtkPolyData.h | jcfr/SPHARM-PDM | 10a9fa8731ff43eedea980bade46c676413378a5 | [
"Apache-2.0"
] | 18 | 2015-03-31T17:31:17.000Z | 2020-05-07T15:14:29.000Z | #ifndef __itkMeshTovtkPolyData_h__
#define __itkMeshTovtkPolyData_h__
#include "vtkPoints.h"
#include "vtkCellArray.h"
#include "vtkPolyData.h"
#include "itkDefaultDynamicMeshTraits.h"
#include "itkMesh.h"
#include "itkTriangleCell.h"
#include "itkPoint.h"
#include <vtkSmartPointer.h>
/**
\class itkMeshTovtkPolyData
\brief
\warning
\sa
*/
class itkMeshTovtkPolyData
{
public:
itkMeshTovtkPolyData( void );
virtual ~itkMeshTovtkPolyData( void );
typedef itk::DefaultDynamicMeshTraits<float, 3, 3, double> TriangleMeshTraits;
typedef itk::Mesh<float, 3, TriangleMeshTraits> TriangleMeshType;
typedef TriangleMeshType::PointType PointType;
typedef TriangleMeshType::PointsContainer InputPointsContainer;
typedef InputPointsContainer::Pointer InputPointsContainerPointer;
typedef InputPointsContainer::Iterator InputPointsContainerIterator;
typedef TriangleMeshType::CellType CellType;
typedef TriangleMeshType::CellsContainerPointer CellsContainerPointer;
typedef TriangleMeshType::CellsContainerIterator CellsContainerIterator;
/**
The SetInput method provides pointer to the vtkPolyData
*/
void SetInput(TriangleMeshType::Pointer mesh);
vtkSmartPointer<vtkPolyData> GetOutput();
void ConvertitkTovtk();
TriangleMeshType::Pointer m_itkTriangleMesh;
vtkSmartPointer<vtkPoints> m_Points;
vtkSmartPointer<vtkPolyData> m_PolyData;
vtkSmartPointer<vtkCellArray> m_Polys;
};
#endif
| 27.928571 | 90 | 0.740409 | [
"mesh"
] |
caa94164467c4d25603c6d2e77dbe0ef2ef4381e | 3,907 | c | C | src/stwart.d/FORFUL.c | naruto2/CodeFEM | eb689aa7573d4ac9fc83d057f99c79a5d8f3bd90 | [
"MIT"
] | 1 | 2020-09-27T07:28:04.000Z | 2020-09-27T07:28:04.000Z | src/stwart.d/FORFUL.c | naruto2/CodeFEM | eb689aa7573d4ac9fc83d057f99c79a5d8f3bd90 | [
"MIT"
] | null | null | null | src/stwart.d/FORFUL.c | naruto2/CodeFEM | eb689aa7573d4ac9fc83d057f99c79a5d8f3bd90 | [
"MIT"
] | null | null | null | #pragma GCC diagnostic ignored "-Wimplicit-function-declaration"
/* FORFUL.F -- translated by f2c (version 12.02.01).
You must link the resulting object file with libf2c:
on Microsoft Windows system, link with libf2c.lib;
on Linux or Unix systems, link with .../path/to/libf2c.a -lm
or, if you install libf2c.a in a standard place, with -lf2c -lm
-- in that order, at the end of the command line, as in
cc *.o -lf2c -lm
Source for libf2c is in /netlib/f2c/libf2c.zip, e.g.,
http://www.netlib.org/f2c/libf2c.zip
*/
#include <stdlib.h> /* For exit() */
#include <f2c.h>
/* Table of constant values */
static integer c__9 = 9;
static integer c__1 = 1;
static integer c__3 = 3;
/* Subroutine */ int forful_(integer *ia, integer *l, integer *ma, integer *m,
integer *ip, integer *jp, integer *ir, integer *ic, integer *kerns,
integer *ier)
{
/* System generated locals */
integer i__1;
/* Local variables */
static integer i__, j, k, nd, nh, nk, nn, nl, np;
/* Fortran I/O blocks */
static cilist io___6 = { 0, 6, 0, 0, 0 };
static cilist io___9 = { 0, 6, 0, 0, 0 };
/* ********************************************************************** */
/* FORD-FULKERSON METHOD FOR ORDERING. * */
/* * */
/* PARAMETERS: * */
/* ON ENTRY: SAME AS STWART ROUTINE. * */
/* ON RETURN: * */
/* IP COLUMN INDEX IN EACH I-TH ROW. ON THE CASE OF SINGLETON, * */
/* MINUS SIGN. * */
/* JP ROW INDEX IN EACH J-TH COLUMN. * */
/* IER THE ERROR CODE. IF IER=0, NORMAL RETURN. * */
/* OTHERS: WORKING PARAMETERS. * */
/* * */
/* COPYRIGHT: TSUTOMU OGUNI SEP. 1 1991 VER. 1 * */
/* ********************************************************************** */
/* Parameter adjustments */
--ia;
--ic;
--ir;
--jp;
--ip;
/* Function Body */
*ier = 0;
i__1 = *m;
for (k = 1; k <= i__1; ++k) {
jp[k] = 0;
/* L1: */
ip[k] = 0;
}
i__1 = *kerns - 1;
for (k = 1; k <= i__1; ++k) {
ip[ir[k]] = -ic[k];
/* L3: */
jp[ic[k]] = ir[k];
}
i__ = 1;
j = 0;
L2:
if (jp[i__] == 0) {
i__1 = ma[i__];
for (k = ma[i__ - 1] + 1; k <= i__1; ++k) {
if (ip[ia[k]] == 0) {
nk = ia[k];
ip[nk] = i__;
jp[i__] = nk;
goto L20;
}
/* L10: */
}
goto L50;
}
L20:
if (i__ >= *m) {
return 0;
}
++i__;
goto L2;
L50:
nn = 0;
L52:
++nn;
if (nn > ma[i__] - ma[i__ - 1]) {
s_wsle(&io___6);
do_lio(&c__9, &c__1, "(SUBR. FORFUL) ERROR STOP. ", (ftnlen)27);
do_lio(&c__3, &c__1, (char *)&i__, (ftnlen)sizeof(integer));
do_lio(&c__3, &c__1, (char *)&j, (ftnlen)sizeof(integer));
e_wsle();
*ier = 1;
return 0;
}
nh = ia[ma[i__ - 1] + nn];
j = ip[nh];
if (j <= 0) {
goto L52;
}
ip[nh] = i__;
jp[i__] = nh;
L55:
i__1 = ma[j];
for (k = ma[j - 1] + 1; k <= i__1; ++k) {
if (ip[ia[k]] == 0) {
nl = ia[k];
ip[nl] = j;
jp[j] = nl;
goto L20;
}
/* L60: */
}
nn = 0;
L62:
++nn;
if (nn > ma[j] - ma[j - 1]) {
s_wsle(&io___9);
do_lio(&c__9, &c__1, "(SUBR. FORFUL) ERROR STOP. ", (ftnlen)27);
do_lio(&c__3, &c__1, (char *)&i__, (ftnlen)sizeof(integer));
do_lio(&c__3, &c__1, (char *)&j, (ftnlen)sizeof(integer));
e_wsle();
*ier = 1;
return 0;
}
np = ia[ma[j - 1] + nn];
nd = ip[np];
if (nd <= 0) {
goto L62;
}
ip[np] = j;
jp[j] = np;
j = nd;
goto L55;
/* END OF FORFUL */
} /* forful_ */
| 25.535948 | 78 | 0.436396 | [
"object"
] |
caac6ce5ed5f73fa9b914bb1d00805e989b56d0c | 909 | c | C | d/shadow/room/githyanki/obj/gith_symbol.c | Dbevan/SunderingShadows | 6c15ec56cef43c36361899bae6dc08d0ee907304 | [
"MIT"
] | 13 | 2019-07-19T05:24:44.000Z | 2021-11-18T04:08:19.000Z | d/shadow/room/githyanki/obj/gith_symbol.c | Dbevan/SunderingShadows | 6c15ec56cef43c36361899bae6dc08d0ee907304 | [
"MIT"
] | 4 | 2021-03-15T18:56:39.000Z | 2021-08-17T17:08:22.000Z | d/shadow/room/githyanki/obj/gith_symbol.c | Dbevan/SunderingShadows | 6c15ec56cef43c36361899bae6dc08d0ee907304 | [
"MIT"
] | 13 | 2019-09-12T06:22:38.000Z | 2022-01-31T01:15:12.000Z | //Githyanki Holy Symbol - Githyanki Fortress - LoKi - 07-02-2008
#include <std.h>
#include "../githyanki.h"
inherit OBJECT;
void create(){
::create();
set_name("gith symbol");
set_id(({"symbol","githyanki symbol","gith symbol","medallion","black medallion","small black medallion"}));
set_short("%^BLACK%^%^BOLD%^small black medallion%^RESET%^");
set_long("%^RESET%^%^BOLD%^%^BLACK%^This symbol has been cra"+
"fted from %^RESET%^%^WHITE%^iron%^RESET%^%^BOLD%^%^BLACK%^. It "+
"hangs from a thin chain and is decorated with a symbol of a %^RESET%^"+
"%^MAGENTA%^f%^RESET%^%^BOLD%^%^BLACK%^i%^RESET%^%^MAGENTA%^ve hea"+
"%^RESET%^%^WHITE%^d%^RESET%^%^MAGENTA%^ed d%^RESET%^%^WHITE%^r%^RESET%^"+
"%^MAGENTA%^ag%^RESET%^%^BOLD%^%^BLACK%^o%^RESET%^%^MAGENTA%^n%^RESET%^"+
"%^BOLD%^%^BLACK%^. It glows with an almost malign light%^RESET%^");
set_weight(2);
set_value(50);
}
| 28.40625 | 112 | 0.622662 | [
"object"
] |
caaf5aaba181cc05cf59afc8a9cf61059ef52cbe | 6,861 | h | C | newton-4.00/applications/ndTestC/dVector.h | tombish/newton-dynamics | 02175af78f9e789ff2e0559139664090a25a3b88 | [
"Zlib"
] | null | null | null | newton-4.00/applications/ndTestC/dVector.h | tombish/newton-dynamics | 02175af78f9e789ff2e0559139664090a25a3b88 | [
"Zlib"
] | null | null | null | newton-4.00/applications/ndTestC/dVector.h | tombish/newton-dynamics | 02175af78f9e789ff2e0559139664090a25a3b88 | [
"Zlib"
] | null | null | null | /* Copyright (c) <2003-2019> <Newton Game Dynamics>
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely
*/
#ifndef __dVector__
#define __dVector__
//#include "dMathDefines.h"
//#ifndef dFloat
//#ifdef _NEWTON_USE_DOUBLE
//typedef double dFloat;
//#else
//typedef float dFloat;
//#endif
//#endif
typedef float dFloat;
typedef double dFloat64;
// small but very effective 4 dimensional template vector class
template<class T>
class TemplateVector
{
public:
TemplateVector ();
TemplateVector (const T val);
TemplateVector (const T* const ptr);
TemplateVector (T m_x, T m_y, T m_z, T m_w = T(1.0f));
TemplateVector Scale (T s) const;
T& operator[] (int i);
const T& operator[] (int i) const;
TemplateVector operator+ (const TemplateVector &A) const;
TemplateVector operator- (const TemplateVector &A) const;
TemplateVector operator* (const TemplateVector &A) const;
TemplateVector& operator+= (const TemplateVector &A);
TemplateVector& operator-= (const TemplateVector &A);
TemplateVector& operator*= (const TemplateVector &A);
TemplateVector Abs() const;
TemplateVector Min(const TemplateVector &A) const;
TemplateVector Max(const TemplateVector &A) const;
T DotProduct3 (const TemplateVector &A) const;
TemplateVector Normalize () const;
TemplateVector CrossProduct (const TemplateVector &A) const;
T m_x;
T m_y;
T m_z;
T m_w;
};
class dVector: public TemplateVector<dFloat>
{
public:
dVector()
:TemplateVector<dFloat>()
{
}
dVector(dFloat val)
:TemplateVector<dFloat>(val)
{
}
dVector (const TemplateVector<dFloat>& v)
:TemplateVector<dFloat>(v)
{
}
dVector (const dFloat* const ptr)
:TemplateVector<dFloat>(ptr)
{
}
dVector (dFloat x, dFloat y, dFloat z, dFloat w = 1.0f)
:TemplateVector<dFloat>(x, y, z, w)
{
}
#ifndef _NEWTON_USE_DOUBLE
dVector (const TemplateVector<dFloat64>& v)
:TemplateVector<dFloat>(dFloat(v.m_x), dFloat(v.m_y), dFloat(v.m_z), dFloat(v.m_w))
{
}
#endif
};
class dBigVector: public TemplateVector<dFloat64>
{
public:
dBigVector(){};
dBigVector(dFloat64 val)
:TemplateVector<dFloat64> (val)
{
}
dBigVector (const dFloat64* const ptr)
:TemplateVector<dFloat64> (ptr)
{
}
dBigVector (const TemplateVector<dFloat64>& v)
:TemplateVector<dFloat64> (v.m_x, v.m_y, v.m_z, v.m_w)
{
}
dBigVector(const dVector& v)
:TemplateVector<dFloat64>(v.m_x, v.m_y, v.m_z, v.m_w)
{
}
dBigVector (dFloat64 x, dFloat64 y, dFloat64 z, dFloat64 w = dFloat(1.0f))
:TemplateVector<dFloat64> (x, y, z, w)
{
}
};
template<class T>
TemplateVector<T>::TemplateVector()
{
}
template<class T>
TemplateVector<T>::TemplateVector(const T val)
:m_x (val), m_y(val), m_z(val), m_w(val)
{
}
template<class T>
TemplateVector<T>::TemplateVector(const T *ptr)
:m_x (ptr[0]), m_y(ptr[1]), m_z(ptr[2]), m_w(0.0f)
{
}
template<class T>
TemplateVector<T>::TemplateVector(T x, T y, T z, T w)
:m_x (x), m_y(y), m_z(z), m_w(w)
{
}
template<class T>
T& TemplateVector<T>::operator[] (int i)
{
return (&m_x)[i];
}
template<class T>
const T& TemplateVector<T>::operator[] (int i) const
{
return (&m_x)[i];
}
template<class T>
TemplateVector<T> TemplateVector<T>::Scale (T scale) const
{
return TemplateVector<T> (m_x * scale, m_y * scale, m_z * scale, m_w);
}
template<class T>
TemplateVector<T> TemplateVector<T>::operator+ (const TemplateVector<T>& B) const
{
return TemplateVector<T> (m_x + B.m_x, m_y + B.m_y, m_z + B.m_z, m_w);
}
template<class T>
TemplateVector<T> TemplateVector<T>::operator* (const TemplateVector<T>& B) const
{
return TemplateVector<T>(m_x * B.m_x, m_y * B.m_y, m_z * B.m_z, m_w);
}
template<class T>
TemplateVector<T>& TemplateVector<T>::operator+= (const TemplateVector<T>& A)
{
m_x += A.m_x;
m_y += A.m_y;
m_z += A.m_z;
return *this;
}
template<class T>
TemplateVector<T> TemplateVector<T>::operator- (const TemplateVector<T>& A) const
{
return TemplateVector<T> (m_x - A.m_x, m_y - A.m_y, m_z - A.m_z, m_w);
}
template<class T>
TemplateVector<T>& TemplateVector<T>::operator-= (const TemplateVector<T>& A)
{
m_x -= A.m_x;
m_y -= A.m_y;
m_z -= A.m_z;
return *this;
}
template<class T>
TemplateVector<T>& TemplateVector<T>::operator*= (const TemplateVector<T>& A)
{
m_x *= A.m_x;
m_y *= A.m_y;
m_z *= A.m_z;
//m_w *= A.m_w;
return *this;
}
template<class T>
TemplateVector<T> TemplateVector<T>::Abs() const
{
return dVector(dAbs(m_x), dAbs(m_y), dAbs(m_z), dAbs(m_w));
}
template<class T>
TemplateVector<T> TemplateVector<T>::Min(const TemplateVector &A) const
{
return dVector (dMin (m_x, A.m_x), dMin (m_y, A.m_y), dMin (m_z, A.m_z), dMin (m_w, A.m_w));
}
template<class T>
TemplateVector<T> TemplateVector<T>::Max(const TemplateVector &A) const
{
return dVector (dMax (m_x, A.m_x), dMax (m_y, A.m_y), dMax (m_z, A.m_z), dMax (m_w, A.m_w));
}
template<class T>
T TemplateVector<T>::DotProduct3 (const TemplateVector<T>& A) const
{
return m_x * A.m_x + m_y * A.m_y + m_z * A.m_z;
}
template<class T>
TemplateVector<T> TemplateVector<T>::Normalize () const
{
T mag (DotProduct3(*this));
return Scale (1.0f / T(sqrt (mag)));
}
template<class T>
TemplateVector<T> TemplateVector<T>::CrossProduct (const TemplateVector<T>& A) const
{
return TemplateVector<T> (m_y * A.m_z - m_z * A.m_y, m_z * A.m_x - m_x * A.m_z, m_x * A.m_y - m_y * A.m_x, m_w);
}
class dSpatialVector
{
public:
inline dSpatialVector()
{
}
inline dSpatialVector(const dFloat a)
{
for (int i = 0; i < 6; i++) {
m_d[i] = a;
}
}
inline dSpatialVector(const dVector& low, const dVector& high)
{
m_d[0] = low[0];
m_d[1] = low[1];
m_d[2] = low[2];
m_d[3] = high[0];
m_d[4] = high[1];
m_d[5] = high[2];
}
inline dFloat& operator[] (int i)
{
dAssert(i < 6);
dAssert(i >= 0);
return m_d[i];
}
inline const dFloat& operator[] (int i) const
{
dAssert(i < 6);
dAssert(i >= 0);
return m_d[i];
}
inline dSpatialVector operator+ (const dSpatialVector& A) const
{
dSpatialVector tmp;
for (int i = 0; i < 6; i++) {
tmp[i] = m_d[i] + A.m_d[i];
}
return tmp;
}
inline dSpatialVector operator* (const dSpatialVector& A) const
{
dSpatialVector tmp;
for (int i = 0; i < 6; i++) {
tmp[i] = m_d[i] * A.m_d[i];
}
return tmp;
}
inline dFloat DotProduct(const dSpatialVector& v) const
{
dFloat acc = dFloat (0.0f);
for (int i = 0; i < 6; i++) {
acc += m_d[i] * v.m_d[i];
}
return acc;
}
inline dSpatialVector Scale(dFloat s) const
{
dSpatialVector tmp;
for (int i = 0; i < 6; i++) {
tmp[i] = m_d[i] * s;
}
return tmp;
}
dFloat m_d[6];
};
#endif
| 20.35905 | 113 | 0.668853 | [
"vector"
] |
cab21ec8f0a979b64fc63f8b1049000e8d2efc9f | 6,734 | h | C | Modules/QtWidgetsExt/include/QmitkFunctionalityComponentContainer.h | liu3xing3long/MITK-2016.11 | 385c506f9792414f40337e106e13d5fd61aa3ccc | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | Modules/QtWidgetsExt/include/QmitkFunctionalityComponentContainer.h | liu3xing3long/MITK-2016.11 | 385c506f9792414f40337e106e13d5fd61aa3ccc | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | Modules/QtWidgetsExt/include/QmitkFunctionalityComponentContainer.h | liu3xing3long/MITK-2016.11 | 385c506f9792414f40337e106e13d5fd61aa3ccc | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | /*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#ifndef QMITK_FUNCTIONALITYCOMPONENTCONTAINER_H
#define QMITK_FUNCTIONALITYCOMPONENTCONTAINER_H
#include "MitkQtWidgetsExtExports.h"
#include "QmitkBaseFunctionalityComponent.h"
#include "ui_QmitkFunctionalityComponentContainerControls.h"
#include <mitkDataNode.h>
#include <qlabel.h>
#include <qlayout.h>
#include <qobject.h>
#include <qpushbutton.h>
#include <qstackedwidget.h>
#include <qstring.h>
#include <qwidget.h>
#include <QmitkStdMultiWidget.h>
/**
* \brief ContainerClass for components
* \ingroup QmitkFunctionalityComponent
*
*
* - \ref QmitkBaseFunctionalityComponent
*
* \section QmitkFunctionalityComponentContainer Overview
*
* The FunctionalityComponentContainer is a containerclass for several components inherit from it.
* All Components including to one FunctionalityComponentContainer can be used together as one applied
* functionality. I.e. in particular that new functionalities can be combined with different components.
* As common ground for all inherit classes the FunctionalityComponentContainer includes a selector for
* marked data like image(s), segmentation(s) or model(s).
*/
class MITKQTWIDGETSEXT_EXPORT QmitkFunctionalityComponentContainer : public QmitkBaseFunctionalityComponent
{
Q_OBJECT
public:
/** \brief Standard-Constructor. */
QmitkFunctionalityComponentContainer(QObject *parent = 0,
const char *parentName = 0,
bool updateSelector = true,
bool showSelector = true);
/** \brief Destructor. */
virtual ~QmitkFunctionalityComponentContainer();
/*!
\brief Method to create all Signale-Slot-Connections
*/
virtual void CreateConnections();
/*!
\brief Method to create the GUI-Object
*/
virtual void CreateQtPartControl(QWidget *parent, mitk::DataStorage::Pointer dataStorage);
/** \brief Method to create the forward and backward -buttons to navigate through the wizard */
void CreateNavigationButtons();
/** \brief Method to create a textLabel at the Top of the wizard where a description can be created */
void SetWizardText(const QString &text);
/** \brief also the Graphical User Interface for the component, like m_GUI, but with its specific type */
Ui::QmitkFunctionalityComponentContainerGUI *GetFunctionalityComponentContainerGUI();
/** \brief Method to set the DataStorage*/
virtual void SetDataStorage(mitk::DataStorage::Pointer dataStorage);
/** \brief Method to get the DataStorage*/
virtual mitk::DataStorage::Pointer GetDataStorage();
/** \brief Method to set the Name of the FunctionalityComponent */
virtual void SetComponentName(QString name);
/** \brief Method to get the Name of the FunctionalityComponent */
virtual QString GetComponentName();
/** \brief Method to get the GUI of this component.*/
QWidget *GetGUI();
virtual QmitkDataStorageComboBox *GetTreeNodeSelector();
/** \brief Method to set the Image Selector visible or invisible */
virtual void SetSelectorVisibility(bool visibility);
QmitkStdMultiWidget *GetMultiWidget();
/** \brief Method to return the ComboBox that includes all GUI-elements instead of the outermost checkable CheckBox
* and that can be set visible or not*/
virtual QGroupBox *GetContentContainer();
/** \brief Method to return the outermost checkable ComboBox that is to decide whether the content shall be shown or
* not */
virtual QGroupBox *GetMainCheckBoxContainer();
/** \brief Method to set the Tree-Node-Selector visible or not as his parent group-box is set shown or not. */
virtual void SetShowTreeNodeSelector(bool show);
/** \brief Method to return the group-box that contains the tree-node-selector */
virtual QGroupBox *GetImageContent();
/** \brief Method to return the Image Selected in the Container Combo Box */
virtual mitk::Image *GetParentMitkImage();
/** \brief Method to return the NextButton to switch to the next widgetStackPage*/
QPushButton *GetNextButton();
/** \brief Method to return the BackButton to switch to the last widgetStackPage*/
QPushButton *GetBackButton();
/** \brief method to add components into this component. */
virtual void AddComponent(QmitkFunctionalityComponentContainer *componentContainer);
/** \brief method to add components into this component. */
virtual void AddComponent(QmitkFunctionalityComponentContainer *componentContainer, QString label, int stackPage);
virtual void TreeChanged(const itk::EventObject &treeChangedEvent);
virtual void Activated();
virtual void Deactivated();
/** \brief Attribute to decide whether the selector shall be updated when a parent-Selector is updatet or not */
bool m_UpdateSelector;
/** \brief Attribute to decide whether the selector shall be shown or not */
bool m_ShowSelector;
/** \brief Slot method that will be called if TreeNodeSelector widget was activated. */
void ImageSelected(const mitk::DataNode *item);
public slots:
/** \brief Method to set the "GetContentContainer"-visible or not, addicted to the visibility of a parent-component
* and the status of the checkable ComboBox from "GetMainCheckBoxContainer()" */
virtual void SetContentContainerVisibility(bool);
virtual void TreeChanged();
virtual void DataStorageChanged(mitk::DataStorage::Pointer ds);
protected:
/** \brief Method to update the content of all DataTreeComboBoxes. */
virtual void UpdateDataTreeComboBoxes();
unsigned long m_ObserverTag;
QWidget *m_GUI;
bool m_Active;
QmitkDataStorageComboBox *m_SelectedItem;
mitk::DataStorage::Pointer m_DataStorage;
private:
/** \brief also the Graphical User Interface for the component, like m_GUI, but with its specific type */
Ui::QmitkFunctionalityComponentContainerGUI *m_FunctionalityComponentContainerGUI;
QObject *m_Parent;
QString m_ComponentName;
QSpacerItem *m_Spacer;
QmitkStdMultiWidget *m_MulitWidget;
QPushButton *m_BackButton;
QPushButton *m_NextButton;
int m_MaximumWidgedStackSize;
};
#endif
| 36.4 | 119 | 0.723641 | [
"object",
"model"
] |
caba242c9d2f635dfe323f624c6fa6f6b28c0fc9 | 2,121 | h | C | RenderingEngine/Scene.h | Tidus-Zheng/ray-tracing | ebafcbafd15488ec16e94d7785ea79d3b0904529 | [
"MIT"
] | null | null | null | RenderingEngine/Scene.h | Tidus-Zheng/ray-tracing | ebafcbafd15488ec16e94d7785ea79d3b0904529 | [
"MIT"
] | null | null | null | RenderingEngine/Scene.h | Tidus-Zheng/ray-tracing | ebafcbafd15488ec16e94d7785ea79d3b0904529 | [
"MIT"
] | null | null | null | #pragma once
#include <vector>
#include "ShaderManager.h"
#include "Camera.h"
#include "CameraOrbitControl.h"
#include "Mesh.h"
#include "Texture.h"
#include "DirectionalLight.h"
#include "Model.h"
class Scene final{
private:
int width, height;
GLFWwindow* window;
bool firstClick = true;
double firstX, firstY;
Scene();
~Scene() {
delete camera;
}
static void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods)
{
if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS)
glfwSetWindowShouldClose(window, GLFW_TRUE);
Scene::Instance().keybord_event(action, key);
}
//mouse position event;
static void cursor_position_callback(GLFWwindow* window, double xpos, double ypos)
{
Scene::Instance().cursor_position_update(xpos, ypos);
}
static void mouse_button_callback(GLFWwindow* window, int button, int action, int mods)
{
Scene::Instance().mouse_button_clicked(button, mods);
}
static void scroll_callback(GLFWwindow* window, double xoffset, double yoffset)
{
Scene::Instance().wheel_update(yoffset);
}
void SetInputEvent() {
//set window pointer before get in input event
glfwSetWindowUserPointer(window, this);
glfwSetKeyCallback(window, key_callback);
glfwSetCursorPosCallback(window, cursor_position_callback);
glfwSetScrollCallback(window, scroll_callback);
}
public:
Camera* camera;
CameraOrbitControl orbitControl;
DirectionalLight directionLight;
Model model;
Model model2;
//Mesh cubeMesh;
bool showPos = false;
static Scene& Instance();
//Scene(GLFWwindow* _window, int _width, int _height)
// :window(_window), width(_width), height(_height)
//{
// SetInputEvent();
//}
void SetSceneSize(int _width, int _height) { width = _width; height = _height; }
void SetWindow(GLFWwindow* _window) {
window = _window;
SetInputEvent();
}
GLFWwindow* GetWindow() { return window; }
void start();
void update();
void destroy();
void keybord_event(int action, int key);
void cursor_position_update(double xpos, double ypos);
void mouse_button_clicked(int button, int mods);
void wheel_update(double offset);
};
| 22.56383 | 90 | 0.736917 | [
"mesh",
"vector",
"model"
] |
cac73e2146a91c54ebb116daf02cf0e39a7975f6 | 435 | h | C | recogniser.h | hatstand/symmetrical-octo-fiesta | 8a1ed099f2598e330c60d3e85448431f4bb2c117 | [
"MIT"
] | 5 | 2017-08-26T23:59:04.000Z | 2020-06-08T19:28:10.000Z | recogniser.h | hatstand/symmetrical-octo-fiesta | 8a1ed099f2598e330c60d3e85448431f4bb2c117 | [
"MIT"
] | 1 | 2017-05-16T11:22:22.000Z | 2017-06-14T12:39:32.000Z | recogniser.h | hatstand/symmetrical-octo-fiesta | 8a1ed099f2598e330c60d3e85448431f4bb2c117 | [
"MIT"
] | 1 | 2019-12-30T14:00:33.000Z | 2019-12-30T14:00:33.000Z | #ifndef RECOGNISER_H
#define RECOGNISER_H
#include <vector>
#include <opencv2/core/core.hpp>
#include "knearest.h"
class Recogniser {
public:
explicit Recogniser(const KNearest& nearest);
char Recognise(const cv::Mat& image) const;
std::vector<char> RecogniseGrid(const cv::Mat& image) const;
std::vector<char> RecogniseRack(const cv::Mat& image) const;
private:
const KNearest& nearest_;
};
#endif // RECOGNISER_H
| 18.913043 | 62 | 0.733333 | [
"vector"
] |
caca37bf558b588283ec163584efc1f17ce79667 | 4,345 | h | C | ppapi/proxy/ppapi_command_buffer_proxy.h | metux/chromium-deb | 3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | ppapi/proxy/ppapi_command_buffer_proxy.h | metux/chromium-deb | 3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | ppapi/proxy/ppapi_command_buffer_proxy.h | metux/chromium-deb | 3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef PPAPI_PROXY_COMMAND_BUFFER_PROXY_H_
#define PPAPI_PROXY_COMMAND_BUFFER_PROXY_H_
#include <stddef.h>
#include <stdint.h>
#include <memory>
#include "base/callback.h"
#include "base/containers/hash_tables.h"
#include "base/macros.h"
#include "gpu/command_buffer/client/gpu_control.h"
#include "gpu/command_buffer/common/command_buffer.h"
#include "gpu/command_buffer/common/command_buffer_id.h"
#include "gpu/command_buffer/common/command_buffer_shared.h"
#include "ppapi/proxy/plugin_dispatcher.h"
#include "ppapi/proxy/ppapi_proxy_export.h"
#include "ppapi/shared_impl/host_resource.h"
namespace IPC {
class Message;
}
namespace ppapi {
namespace proxy {
class SerializedHandle;
class PPAPI_PROXY_EXPORT PpapiCommandBufferProxy : public gpu::CommandBuffer,
public gpu::GpuControl {
public:
PpapiCommandBufferProxy(const HostResource& resource,
PluginDispatcher* dispatcher,
const gpu::Capabilities& capabilities,
const SerializedHandle& shared_state,
gpu::CommandBufferId command_buffer_id);
~PpapiCommandBufferProxy() override;
// gpu::CommandBuffer implementation:
State GetLastState() override;
void Flush(int32_t put_offset) override;
void OrderingBarrier(int32_t put_offset) override;
State WaitForTokenInRange(int32_t start, int32_t end) override;
State WaitForGetOffsetInRange(uint32_t set_get_buffer_count,
int32_t start,
int32_t end) override;
void SetGetBuffer(int32_t transfer_buffer_id) override;
scoped_refptr<gpu::Buffer> CreateTransferBuffer(size_t size,
int32_t* id) override;
void DestroyTransferBuffer(int32_t id) override;
// gpu::GpuControl implementation:
void SetGpuControlClient(gpu::GpuControlClient*) override;
gpu::Capabilities GetCapabilities() override;
int32_t CreateImage(ClientBuffer buffer,
size_t width,
size_t height,
unsigned internalformat) override;
void DestroyImage(int32_t id) override;
void SignalQuery(uint32_t query, const base::Closure& callback) override;
void SetLock(base::Lock*) override;
void EnsureWorkVisible() override;
gpu::CommandBufferNamespace GetNamespaceID() const override;
gpu::CommandBufferId GetCommandBufferID() const override;
int32_t GetStreamId() const override;
void FlushOrderingBarrierOnStream(int32_t stream_id) override;
uint64_t GenerateFenceSyncRelease() override;
bool IsFenceSyncRelease(uint64_t release) override;
bool IsFenceSyncFlushed(uint64_t release) override;
bool IsFenceSyncFlushReceived(uint64_t release) override;
bool IsFenceSyncReleased(uint64_t release) override;
void SignalSyncToken(const gpu::SyncToken& sync_token,
const base::Closure& callback) override;
void WaitSyncTokenHint(const gpu::SyncToken& sync_token) override;
bool CanWaitUnverifiedSyncToken(const gpu::SyncToken& sync_token) override;
void AddLatencyInfo(
const std::vector<ui::LatencyInfo>& latency_info) override;
private:
bool Send(IPC::Message* msg);
void UpdateState(const gpu::CommandBuffer::State& state, bool success);
// Try to read an updated copy of the state from shared memory.
void TryUpdateState();
// The shared memory area used to update state.
gpu::CommandBufferSharedState* shared_state() const;
void FlushInternal();
const gpu::CommandBufferId command_buffer_id_;
gpu::Capabilities capabilities_;
State last_state_;
std::unique_ptr<base::SharedMemory> shared_state_shm_;
HostResource resource_;
PluginDispatcher* dispatcher_;
base::Closure channel_error_callback_;
InstanceData::FlushInfo *flush_info_;
uint64_t next_fence_sync_release_;
uint64_t pending_fence_sync_release_;
uint64_t flushed_fence_sync_release_;
uint64_t validated_fence_sync_release_;
DISALLOW_COPY_AND_ASSIGN(PpapiCommandBufferProxy);
};
} // namespace proxy
} // namespace ppapi
#endif // PPAPI_PROXY_COMMAND_BUFFER_PROXY_H_
| 36.208333 | 77 | 0.736018 | [
"vector"
] |
cacd68acf8b622bf7176144df39f1fb06c265b0a | 15,265 | h | C | src/esp/geo/VoxelGrid.h | rutadesai/habitat-sim | 851dc67c8ea3dd380f03542da73d627dc4ec9685 | [
"MIT"
] | null | null | null | src/esp/geo/VoxelGrid.h | rutadesai/habitat-sim | 851dc67c8ea3dd380f03542da73d627dc4ec9685 | [
"MIT"
] | null | null | null | src/esp/geo/VoxelGrid.h | rutadesai/habitat-sim | 851dc67c8ea3dd380f03542da73d627dc4ec9685 | [
"MIT"
] | null | null | null | // Copyright (c) Facebook, Inc. and its affiliates.
// This source code is licensed under the MIT license found in the
// LICENSE file in the root directory of this source tree.
#ifndef ESP_GEO_VOXEL_GRID_H_
#define ESP_GEO_VOXEL_GRID_H_
#include <vector>
#include <Corrade/Containers/ArrayViewStl.h>
#include <Corrade/Containers/StridedArrayView.h>
#include <Corrade/Utility/Directory.h>
#include <Magnum/GL/PixelFormat.h>
#include <Magnum/Image.h>
#include <Magnum/Math/Color.h>
#include <Magnum/Math/CubicHermite.h>
#include <Magnum/Math/Range.h>
#include <Magnum/PixelFormat.h>
#include "esp/assets/MeshData.h"
#include "esp/assets/MeshMetaData.h"
#include "esp/core/esp.h"
#include "esp/geo/geo.h"
#include "esp/gfx/Drawable.h"
#include "esp/gfx/magnum.h"
#ifdef ESP_BUILD_WITH_VHACD
#include "VHACD.h"
#endif
namespace esp {
namespace geo {
enum class VoxelGridType { Bool, Int, Float, Vector3 };
// Used for generating voxel meshes
struct VoxelVertex {
Mn::Vector3 position;
Mn::Vector3 normal;
Mn::Vector3 color;
};
class VoxelGrid {
struct GridEntry {
VoxelGridType type;
Corrade::Containers::Array<char> data;
Corrade::Containers::StridedArrayView3D<void> view;
};
public:
#ifdef ESP_BUILD_WITH_VHACD
/**
* @brief Generates a Boundary voxel grid using VHACD's voxelization
* framework.
* @param MeshData The mesh that will be voxelized
* @param renderAssetHandle The handle for the render asset.
* @param resolution The approximate number of voxels in the voxel grid.
*/
VoxelGrid(const assets::MeshData& meshData,
const std::string& renderAssetHandle,
int resolution);
#endif
/**
* @brief Generates an empty voxel grid given some voxel size and voxel
* dimensions..
* @param voxelSize The size of a single voxel
* @param VoxelGridDimensions The dimensions of the voxel grid.
*/
VoxelGrid(const Magnum::Vector3& voxelSize,
const Magnum::Vector3i& voxelGridDimensions);
/**
* @brief Gets the enumerated type of a particular voxel grid type.
* @return The enumerated type.
*/
template <typename T>
VoxelGridType voxelGridTypeFor();
/**
* @brief Returns the type of the specified voxel grid.
* @param gridName The name of the grid.
* @return The enumerated type.
*
*/
VoxelGridType getGridType(const std::string& gridName) {
assert(grids_.find(gridName) != grids_.end());
return grids_[gridName].type;
}
/**
* @brief Generates a new empty voxel grid of a specified type.
* @param gridName The key under which the grid will be registered and
* accessed.
*/
template <typename T>
void addGrid(const std::string& gridName) {
VoxelGridType type = voxelGridTypeFor<T>();
std::size_t dims[3]{static_cast<std::size_t>(m_voxelGridDimensions[0]),
static_cast<std::size_t>(m_voxelGridDimensions[1]),
static_cast<std::size_t>(m_voxelGridDimensions[2])};
Corrade::Containers::StridedDimensions<3, std::ptrdiff_t> strides{
static_cast<std::ptrdiff_t>(m_voxelGridDimensions[2] *
m_voxelGridDimensions[1] * sizeof(T)),
static_cast<std::ptrdiff_t>(m_voxelGridDimensions[2] * sizeof(T)),
static_cast<std::ptrdiff_t>(sizeof(T))};
if (grids_.find(gridName) != grids_.end()) {
// grid exists, simply overwrite
Magnum::Debug() << gridName << "exists, overwriting.";
grids_[gridName].data = Corrade::Containers::Array<char>(
Corrade::Containers::ValueInit, gridSize() * sizeof(T));
Corrade::Containers::StridedArrayView3D<void> view{grids_[gridName].data,
dims, strides};
grids_[gridName].view = view;
grids_[gridName].type = type;
return;
}
GridEntry new_grid;
new_grid.data = Corrade::Containers::Array<char>(
Corrade::Containers::ValueInit, gridSize() * sizeof(T));
Corrade::Containers::StridedArrayView3D<void> view{new_grid.data, dims,
strides};
new_grid.view = view;
new_grid.type = type;
grids_.insert(std::make_pair(gridName, std::move(new_grid)));
}
/**
* @brief Returns a list of existing voxel grids and their types.
* @return A vector of pairs, where the first element is the voxel grid's
* name, and the second element is the string of the object's type.
*/
std::vector<std::pair<std::string, VoxelGridType>> getExistingGrids();
/**
* @brief Returns a bool true if a grid exists, false otherwise.
* @param gridName The name of the grid.
* @return A bool representing whether or not the specified grid exists.
*/
bool gridExists(const std::string& gridName) {
return grids_.find(gridName) != grids_.end();
}
/**
* @brief Removes a grid and frees up memory.
* @param name The name of the grid to be removed.
*/
void removeGrid(const std::string& gridName) {
assert(grids_.find(gridName) != grids_.end());
grids_.erase(gridName);
}
/**
* @brief Returns a StridedArrayView3D of a grid for easy index access and
* manipulation.
* @param gridName The name of the grid to be retrieved.
* @return A StridedArrayView3D of the specified grid.
*/
template <typename T>
Corrade::Containers::StridedArrayView3D<T> getGrid(
const std::string& gridName) {
VoxelGridType type = voxelGridTypeFor<T>();
CORRADE_ASSERT(grids_[gridName].type == type,
"VoxelGrid::getGrid(\"" + gridName +
"\") - Error: incorrect grid type cast requested.",
{});
return Corrade::Containers::arrayCast<T>(grids_[gridName].view);
}
/**
* @brief Checks to see if a given 3D voxel index is valid and does not go out
* of bounds.
* @param coords The voxel index.
* @return True if the voxel index is valid, false otherwise.
*/
bool isValidIndex(const Mn::Vector3i& coords) const {
return bool((coords >= Mn::Vector3i()).all() &&
(coords < m_voxelGridDimensions).all());
}
// --== GETTERS AND SETTERS FOR VOXELS ==--
/**
* @brief Sets a voxel at a specified index for a specified grid to a value.
* @param index The index of the voxel
* @param gridName The voxel grid.
* @param value The new value.
*/
template <typename T>
void setVoxel(const Magnum::Vector3i& index,
const std::string& gridName,
const T& value) {
Corrade::Containers::StridedArrayView3D<T> arrayView3D =
getGrid<T>(gridName);
arrayView3D[index[0]][index[1]][index[2]] = value;
}
/**
* @brief Retrieves the voxel value from a grid of a specified type (bool,
* int, float, Magnum::Vector3).
* @param index The index of the voxel
* @param gridName The voxel grid.
* @return The value from the specified voxel grid.
*/
template <typename T>
T getVoxel(const Magnum::Vector3i& index, const std::string& gridName) {
Corrade::Containers::StridedArrayView3D<T> arrayView3D =
getGrid<T>(gridName);
return arrayView3D[index[0]][index[1]][index[2]];
}
/**
* @brief Returns the dimensions of the voxel grid.
* @return The Vector3i value representing the dimensions.
*/
Magnum::Vector3i getVoxelGridDimensions() { return m_voxelGridDimensions; }
/**
* @brief Returns the size of a voxel.
* @return The Vector3 value representing the size of a voxel.
*/
Magnum::Vector3 getVoxelSize() { return m_voxelSize; }
/**
* @brief Gets the length of the voxel grid.
* @return The length of the 1 dimensional array voxel grid.
*/
int gridSize() {
return m_voxelGridDimensions[0] * m_voxelGridDimensions[1] *
m_voxelGridDimensions[2];
}
/**
* @brief Returns the bounding box minimum offset used for generating an
* aligned mesh.
* @return The Vector3 value representing the offset.
*/
Magnum::Vector3 getOffset() { return m_offset; }
/**
* @brief Returns the bounding box maximum offset used for generating an
* aligned mesh.
* @return The Vector3 value representing the offset.
*/
Magnum::Vector3 getMaxOffset() { return m_BBMaxOffset; }
/**
* @brief Retrieves the MeshData for a particular voxelGrid. If it does not
* exist, it will generate the mesh for that grid.
* @param gridName The key underwhich the desired voxel grid is registered.
* @return A shared pointer to the MeshData.
*/
std::shared_ptr<Magnum::Trade::MeshData> getMeshData(
const std::string& gridName = "Boundary");
/**
* @brief Retrieves the MeshGL used for rendering for a particular voxelGrid.
* If it does not exist, it will generate the mesh for that grid.
* @param gridName The key underwhich the desired voxel grid is registered.
* @return A reference to the MeshGL.
*/
Magnum::GL::Mesh& getMeshGL(const std::string& gridName = "Boundary");
/**
* @brief Converts a voxel index into global coords by applying the offset and
* multiplying by the real voxel size. Does not apply any transformation made
* to the object the voxle grid is a part of.
* @param coords The voxel index to be converted.
* @return A Vector3 value representing the global coordinates of the voxel
* index.
*/
Magnum::Vector3 getGlobalCoords(const Magnum::Vector3i& coords);
/**
* @brief Sets the offset of the voxel grid.
* @param coords The new offset.
*/
void setOffset(const Magnum::Vector3& coords);
/**
* @brief Generates both a MeshData and MeshGL for a particular voxelGrid.
* @param gridName The name of the voxel grid to be converted into a mesh.
*/
void generateMesh(const std::string& gridName = "Boundary");
/**
* @brief Generates a colored slice of a mesh.
* @param gridName The name of the voxel grid to be converted into a mesh
* slice.
* @param ind The index value the x axis for the slicing plane.
* @param minVal The minimum value of the grid. Used for determining heatmap
* colors.
* @param maxVal The maximum value of the grid. Used for determining heatmap
* colors.
*/
template <typename T>
void generateSliceMesh(const std::string& gridName = "Boundary",
int ind = 0,
T minVal = 0,
T maxVal = 1) {
assert(grids_.find(gridName) != grids_.end());
assert(minVal != maxVal);
Corrade::Containers::Array<VoxelVertex> vertices;
Corrade::Containers::Array<Mn::UnsignedInt> indices;
Corrade::Containers::StridedArrayView3D<T> grid = getGrid<T>(gridName);
// iterate through each voxel grid cell
for (int j = 0; j < m_voxelGridDimensions[1]; j++) {
for (int k = 0; k < m_voxelGridDimensions[2]; k++) {
T val = clamp(grid[ind][j][k], minVal, maxVal);
val -= minVal;
float colorVal = float(val) / float(maxVal - minVal);
Magnum::Vector3i local_coords(ind, j, k);
Magnum::Color3 col = Magnum::Color3(1 - colorVal, colorVal, 0);
std::vector<bool> neighbors{false, false, false, false, false, false};
addVoxelToMeshPrimitives(vertices, indices, local_coords, neighbors,
col);
}
}
generateMeshDataAndMeshGL(gridName, vertices, indices);
}
ESP_SMART_POINTERS(VoxelGrid)
protected:
/**
* @brief Fills vector neighbors with 6 booleans representing the top (y+1),
* bottom (x+1), right (y+1), left (y-1), back (z-1) and front (x-1)
* neighboring voxel's status.
* @param [in] neighbors The vector of booleans to be filled.
* @param gridName The name of the boolean grid to be checked.
* @param index The index of the voxel.
*/
void fillBoolGridNeighborhood(std::vector<bool>& neighbors,
const std::string& gridName,
const Magnum::Vector3i& index);
/**
* @brief Generates the Magnum MeshData and MeshGL given indices, positions,
* normals, and colors.
* @param gridName The grid name corresponding to the mesh's grid.
* @param vertexData A Corrade Array of VoxelVertex which each contain a
* vertex's position, normal, and color
* @param indexData A Corrade Array of indicies for the faces on the mesh.
*/
void generateMeshDataAndMeshGL(
const std::string& gridName,
Corrade::Containers::Array<VoxelVertex>& vertexData,
Corrade::Containers::Array<Mn::UnsignedInt>&
indexData // note the &&s (!)
);
/**
* @brief Helper function for generate mesh. Adds a cube voxel to a mesh.
* @param vertexData A Corrade Array of VoxelVertex which each contain a
* vertex's position, normal, and color
* @param indexData A Corrade Array of indicies for the faces on the mesh.
* @param local_coords A voxel index specifying the location of the voxel.
* @param voxel_neighbors A boolean with 6 booleans representing whether the
* voxel on the top (y+1), bottom (x+1), right (y+1), left (y-1), back (z-1)
* and front (x-1) are filled.
* @param color A Magnum::Color3 object specifying the color for a particular
* voxel. Used primarily for generating the heatmap slices.
*/
void addVoxelToMeshPrimitives(
Corrade::Containers::Array<VoxelVertex>& vertexData,
Corrade::Containers::Array<Mn::UnsignedInt>& indexData,
const Magnum::Vector3i& local_coords,
const std::vector<bool>& voxel_neighbors,
const Magnum::Color3& color = Magnum::Color3(.4, .8, 1));
/**
* @brief Helper function for generate mesh. Adds a vector voxel to a mesh
* which points in a specified direction.
* @param vertexData A Corrade Array of VoxelVertex which each contain a
* vertex's position, normal, and color
* @param indexData A Corrade Array of indicies for the faces on the mesh.
* @param local_coords A voxel index specifying the location of the voxel.
* @param vec The vector to be converted into a mesh.
*/
void addVectorToMeshPrimitives(
Corrade::Containers::Array<VoxelVertex>& vertexData,
Corrade::Containers::Array<Mn::UnsignedInt>& indexData,
const Magnum::Vector3i& local_coords,
const Magnum::Vector3& vec);
private:
// The number of voxels on the x, y, and z dimensions of the grid
Magnum::Vector3i m_voxelGridDimensions;
// The unit lengths for each voxel dimension
Magnum::Vector3 m_voxelSize;
// The relative positioning of the voxel grid to the simulation (May not
// need). VoxelGrid corner is anchored to the world origin, so grid[0] is at
// global position VoxelSize/2 + offset.dot(VoxelSize). m_offset is in
// world coordinates (not voxel).
Magnum::Vector3 m_offset;
Magnum::Vector3 m_BBMaxOffset;
// The underlying render asset handle the asset is tied to
std::string m_renderAssetHandle;
// The MeshData dictionary of various voxelizations, used for visualization
std::map<std::string, std::shared_ptr<Magnum::Trade::MeshData>> meshDataDict_;
// The GL Mesh dictionary for visualizing the voxel.
std::map<std::string, Magnum::GL::Mesh> meshGLDict_;
std::map<std::string, GridEntry> grids_;
};
} // namespace geo
} // namespace esp
#endif
| 35.917647 | 80 | 0.671078 | [
"mesh",
"render",
"object",
"vector",
"3d"
] |
cad63d79242f9424690e3f6de8163459f65c9554 | 2,234 | h | C | source/GB2ShapeCache.h | nerdcave/CollisionSprite | fd825e5a8965eceb362941df0946b80a100ef796 | [
"MIT"
] | 3 | 2015-04-10T09:28:40.000Z | 2017-01-18T11:20:09.000Z | source/GB2ShapeCache.h | nerdcave/CollisionSprite | fd825e5a8965eceb362941df0946b80a100ef796 | [
"MIT"
] | null | null | null | source/GB2ShapeCache.h | nerdcave/CollisionSprite | fd825e5a8965eceb362941df0946b80a100ef796 | [
"MIT"
] | null | null | null | //
// GB2ShapeCache.h
//
// Loads physics sprites created with http://www.codeandweb.com/physicseditor
//
// Generic Shape Cache for box2d
//
// Copyright by Andreas Loew
// http://www.codeandweb.com
//
// All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
#import <Foundation/Foundation.h>
#import <Box2D.h>
/**
* Shape cache
* This class holds the shapes and makes them accessible
* The format can be used on any MacOS/iOS system
*/
@interface GB2ShapeCache : NSObject
{
NSMutableDictionary *shapeObjects_;
float ptmRatio_;
}
+ (GB2ShapeCache *)sharedShapeCache;
/**
* Adds shapes to the shape cache
* @param plist name of the plist file to load
*/
-(void) addShapesWithFile:(NSString*)plist;
/**
* Adds fixture data to a body
* @param body body to add the fixture to
* @param shape name of the shape
*/
-(void) addFixturesToBody:(b2Body*)body forShapeName:(NSString*)shape;
/**
* Returns the anchor point of the given sprite
* @param shape name of the shape to get the anchorpoint for
* @return anchorpoint
*/
-(CGPoint) anchorPointForShape:(NSString*)shape;
/**
* Returns the ptm ratio
*/
-(float) ptmRatio;
@end | 30.60274 | 81 | 0.725604 | [
"shape"
] |
cada40861551f91961876bef46c27253ae6e179c | 4,383 | h | C | iAcqChina/lib/Chilkat/CkCharset.h | bianliu1013/acqChina | 1c180ef66429d456d2ce3908e3a2536ae2ed3463 | [
"MIT"
] | null | null | null | iAcqChina/lib/Chilkat/CkCharset.h | bianliu1013/acqChina | 1c180ef66429d456d2ce3908e3a2536ae2ed3463 | [
"MIT"
] | null | null | null | iAcqChina/lib/Chilkat/CkCharset.h | bianliu1013/acqChina | 1c180ef66429d456d2ce3908e3a2536ae2ed3463 | [
"MIT"
] | null | null | null | // CkCharset.h: interface for the CkCharset class.
//
//////////////////////////////////////////////////////////////////////
// This header is generated.
#ifndef _CkCharset_H
#define _CkCharset_H
#include "chilkatDefs.h"
#include "CkString.h"
#include "CkMultiByteBase.h"
class CkByteData;
#ifndef __sun__
#pragma pack (push, 8)
#endif
// CLASS: CkCharset
class CkCharset : public CkMultiByteBase
{
private:
// Don't allow assignment or copying these objects.
CkCharset(const CkCharset &);
CkCharset &operator=(const CkCharset &);
public:
CkCharset(void);
virtual ~CkCharset(void);
static CkCharset *createNew(void);
void inject(void *impl);
// May be called when finished with the object to free/dispose of any
// internal resources held by the object.
void dispose(void);
// BEGIN PUBLIC INTERFACE
// ----------------------
// Properties
// ----------------------
void get_AltToCharset(CkString &str);
const char *altToCharset(void);
void put_AltToCharset(const char *newVal);
int get_ErrorAction(void);
void put_ErrorAction(int newVal);
void get_FromCharset(CkString &str);
const char *fromCharset(void);
void put_FromCharset(const char *newVal);
void get_LastInputAsHex(CkString &str);
const char *lastInputAsHex(void);
void get_LastInputAsQP(CkString &str);
const char *lastInputAsQP(void);
void get_LastOutputAsHex(CkString &str);
const char *lastOutputAsHex(void);
void get_LastOutputAsQP(CkString &str);
const char *lastOutputAsQP(void);
bool get_SaveLast(void);
void put_SaveLast(bool newVal);
void get_ToCharset(CkString &str);
const char *toCharset(void);
void put_ToCharset(const char *newVal);
// ----------------------
// Methods
// ----------------------
int CharsetToCodePage(const char *charsetName);
bool CodePageToCharset(int codePage, CkString &outCharset);
const char *codePageToCharset(int codePage);
bool ConvertData(const CkByteData &inData, CkByteData &outData);
bool ConvertFile(const char *srcPath, const char *destPath);
bool ConvertFileNoPreamble(const char *srcPath, const char *destPath);
bool ConvertFromUtf16(const CkByteData &uniData, CkByteData &outMbData);
bool ConvertHtml(const CkByteData &htmlIn, CkByteData &outHtml);
bool ConvertHtmlFile(const char *srcPath, const char *destPath);
bool ConvertToUtf16(const CkByteData &mbData, CkByteData &outUniData);
bool EntityEncodeDec(const char *inStr, CkString &outStr);
const char *entityEncodeDec(const char *inStr);
bool EntityEncodeHex(const char *inStr, CkString &outStr);
const char *entityEncodeHex(const char *inStr);
bool GetHtmlCharset(const CkByteData &htmlData, CkString &outCharset);
const char *getHtmlCharset(const CkByteData &htmlData);
const char *htmlCharset(const CkByteData &htmlData);
bool GetHtmlFileCharset(const char *htmlPath, CkString &outCharset);
const char *getHtmlFileCharset(const char *htmlPath);
const char *htmlFileCharset(const char *htmlPath);
bool HtmlDecodeToStr(const char *str, CkString &outStr);
const char *htmlDecodeToStr(const char *str);
bool HtmlEntityDecode(const CkByteData &inData, CkByteData &outData);
bool HtmlEntityDecodeFile(const char *srcPath, const char *destPath);
bool IsUnlocked(void);
bool LowerCase(const char *inStr, CkString &outStr);
const char *lowerCase(const char *inStr);
bool ReadFile(const char *path, CkByteData &outData);
bool ReadFileToString(const char *path, const char *srcCharset, CkString &outStr);
const char *readFileToString(const char *path, const char *srcCharset);
void SetErrorBytes(const unsigned char *pByteData, unsigned long szByteData);
void SetErrorString(const char *str, const char *charset);
bool UnlockComponent(const char *unlockCode);
bool UpperCase(const char *inStr, CkString &outStr);
const char *upperCase(const char *inStr);
bool UrlDecodeStr(const char *inStr, CkString &outStr);
const char *urlDecodeStr(const char *inStr);
bool VerifyData(const char *charset, const CkByteData &charData);
bool VerifyFile(const char *charset, const char *path);
bool WriteFile(const char *path, const CkByteData &dataBuf);
bool WriteStringToFile(const char *str, const char *path, const char *charset);
// END PUBLIC INTERFACE
};
#ifndef __sun__
#pragma pack (pop)
#endif
#endif
| 25.482558 | 83 | 0.720055 | [
"object"
] |
cae193169080a4192888b4806e57687c5afe8d3f | 2,158 | h | C | src/include/simplecc/Visualize/ASTGraph.h | cgsdfc/Optimize | f3a28ccd5caf01d2a306859d641a1cb5aa0d36f3 | [
"MIT"
] | 1 | 2019-07-13T16:40:47.000Z | 2019-07-13T16:40:47.000Z | src/include/simplecc/Visualize/ASTGraph.h | cgsdfc/simplecc | f3a28ccd5caf01d2a306859d641a1cb5aa0d36f3 | [
"MIT"
] | null | null | null | src/include/simplecc/Visualize/ASTGraph.h | cgsdfc/simplecc | f3a28ccd5caf01d2a306859d641a1cb5aa0d36f3 | [
"MIT"
] | null | null | null | #ifndef SIMPLECC_VISUALIZE_ASTGRAPH_H
#define SIMPLECC_VISUALIZE_ASTGRAPH_H
#include "simplecc/AST/AST.h"
#include "simplecc/Visualize/ASTNode.h"
#include "simplecc/Visualize/TreeLikeIterator.h"
#include <llvm/ADT/STLExtras.h>
#include <map>
#include <memory>
#include <vector>
#include <cassert>
namespace simplecc {
/// A class that keeps all the edges of an ASTNode.
class ASTGraph {
public:
explicit ASTGraph(ProgramAST *P) : TheProgram(P), Edges(), Nodes() {}
using EdgeType = std::vector<ASTNode *>;
using ChildIteratorType = EdgeType::const_iterator;
/// Iterator to all nodes of a graph.
class ASTIterator
: public TreeLikeIterator<ASTIterator, ASTNode *, ChildIteratorType> {
public:
ASTIterator(ProgramAST *P, ASTGraph *G) : TreeLikeIterator(), Parent(G) {
Initialize(Parent->getNodeOrCreate(P));
}
ASTIterator() = default;
EdgeRange getEdges(value_type N) {
const auto &LazyEdges = Parent->getEdgeOrCreate(*N);
return llvm::make_range(LazyEdges.begin(), LazyEdges.end());
}
private:
ASTGraph *Parent = nullptr;
};
using NodeIterator = ASTIterator;
/// Iterate over all nodes.
NodeIterator nodes_begin() const {
return NodeIterator(TheProgram, const_cast<ASTGraph *>(this));
}
NodeIterator nodes_end() const { return NodeIterator(); }
llvm::iterator_range<NodeIterator> nodes() {
return llvm::make_range(nodes_begin(), nodes_end());
}
/// Iterate all children of one node.
ChildIteratorType child_begin(const ASTNode &R) {
return std::begin(getEdgeOrCreate(R));
}
ChildIteratorType child_end(const ASTNode &R) {
return std::end(getEdgeOrCreate(R));
}
/// Lazily create edges for a Node.
const std::vector<ASTNode *> &getEdgeOrCreate(const ASTNode &R);
/// Lazily create an ASTNode.
ASTNode *getNodeOrCreate(AST *Ptr);
const ProgramAST *getProgram() const { return TheProgram; }
private:
/// Root of AST.
ProgramAST *TheProgram;
/// Lazily created edges for each node.
std::map<AST *, EdgeType> Edges;
/// Lazily created nodes.
std::map<AST *, std::unique_ptr<ASTNode>> Nodes;
};
} // namespace simplecc
#endif | 28.394737 | 77 | 0.705746 | [
"vector"
] |
caf226c9f1f73e2993acf1f5bd17229a1c27a7b8 | 39,715 | h | C | Engine/Source/Runtime/Renderer/Private/BasePassRendering.h | PopCap/GameIdea | 201e1df50b2bc99afc079ce326aa0a44b178a391 | [
"BSD-2-Clause"
] | null | null | null | Engine/Source/Runtime/Renderer/Private/BasePassRendering.h | PopCap/GameIdea | 201e1df50b2bc99afc079ce326aa0a44b178a391 | [
"BSD-2-Clause"
] | 2 | 2015-06-21T17:38:11.000Z | 2015-06-22T20:54:42.000Z | Engine/Source/Runtime/Renderer/Private/BasePassRendering.h | PopCap/GameIdea | 201e1df50b2bc99afc079ce326aa0a44b178a391 | [
"BSD-2-Clause"
] | null | null | null | // Copyright 1998-2015 Epic Games, Inc. All Rights Reserved.
/*=============================================================================
BasePassRendering.h: Base pass rendering definitions.
=============================================================================*/
#pragma once
#include "LightMapRendering.h"
#include "VelocityRendering.h"
#include "ShaderBaseClasses.h"
#include "LightGrid.h"
#include "EditorCompositeParams.h"
/** Whether to allow the indirect lighting cache to be applied to dynamic objects. */
extern int32 GIndirectLightingCache;
/**
* The base shader type for vertex shaders that render the emissive color, and light-mapped/ambient lighting of a mesh.
* The base type is shared between the versions with and without atmospheric fog.
*/
template<typename LightMapPolicyType>
class TBasePassVertexShaderBaseType : public FMeshMaterialShader, public LightMapPolicyType::VertexParametersType
{
protected:
TBasePassVertexShaderBaseType() {}
TBasePassVertexShaderBaseType(const FMeshMaterialShaderType::CompiledShaderInitializerType& Initializer):
FMeshMaterialShader(Initializer)
{
LightMapPolicyType::VertexParametersType::Bind(Initializer.ParameterMap);
HeightFogParameters.Bind(Initializer.ParameterMap);
AtmosphericFogTextureParameters.Bind(Initializer.ParameterMap);
const bool bOutputsVelocityToGBuffer = FVelocityRendering::OutputsToGBuffer();
if (bOutputsVelocityToGBuffer)
{
PreviousLocalToWorldParameter.Bind(Initializer.ParameterMap, TEXT("PreviousLocalToWorld"));
//@todo-rco: Move to pixel shader
SkipOutputVelocityParameter.Bind(Initializer.ParameterMap, TEXT("SkipOutputVelocity"));
}
}
public:
static bool ShouldCache(EShaderPlatform Platform,const FMaterial* Material,const FVertexFactoryType* VertexFactoryType)
{
return LightMapPolicyType::ShouldCache(Platform, Material, VertexFactoryType);
}
static void ModifyCompilationEnvironment(EShaderPlatform Platform, const FMaterial* Material, FShaderCompilerEnvironment& OutEnvironment)
{
FMeshMaterialShader::ModifyCompilationEnvironment(Platform, Material, OutEnvironment);
LightMapPolicyType::ModifyCompilationEnvironment(Platform, Material, OutEnvironment);
}
virtual bool Serialize(FArchive& Ar)
{
bool bShaderHasOutdatedParameters = FMeshMaterialShader::Serialize(Ar);
LightMapPolicyType::VertexParametersType::Serialize(Ar);
Ar << HeightFogParameters;
Ar << AtmosphericFogTextureParameters;
Ar << PreviousLocalToWorldParameter;
Ar << SkipOutputVelocityParameter;
return bShaderHasOutdatedParameters;
}
void SetParameters(
FRHICommandList& RHICmdList,
const FMaterialRenderProxy* MaterialRenderProxy,
const FVertexFactory* VertexFactory,
const FMaterial& InMaterialResource,
const FSceneView& View,
bool bAllowGlobalFog,
ESceneRenderTargetsMode::Type TextureMode
)
{
FMeshMaterialShader::SetParameters(RHICmdList, GetVertexShader(),MaterialRenderProxy,InMaterialResource,View,TextureMode);
if (bAllowGlobalFog)
{
HeightFogParameters.Set(RHICmdList, GetVertexShader(), &View);
AtmosphericFogTextureParameters.Set(RHICmdList, GetVertexShader(), View);
}
}
void SetMesh(FRHICommandList& RHICmdList, const FVertexFactory* VertexFactory,const FSceneView& View,const FPrimitiveSceneProxy* Proxy, const FMeshBatch& Mesh, const FMeshBatchElement& BatchElement, float DitheredLODTransitionValue);
private:
/** The parameters needed to calculate the fog contribution from height fog layers. */
FHeightFogShaderParameters HeightFogParameters;
FAtmosphereShaderTextureParameters AtmosphericFogTextureParameters;
// When outputting from base pass, the previous transform
FShaderParameter PreviousLocalToWorldParameter;
FShaderParameter SkipOutputVelocityParameter;
};
template<typename LightMapPolicyType, bool bEnableAtmosphericFog>
class TBasePassVS : public TBasePassVertexShaderBaseType<LightMapPolicyType>
{
DECLARE_SHADER_TYPE(TBasePassVS,MeshMaterial);
typedef TBasePassVertexShaderBaseType<LightMapPolicyType> Super;
protected:
TBasePassVS() {}
TBasePassVS(const FMeshMaterialShaderType::CompiledShaderInitializerType& Initializer):
Super(Initializer)
{
}
public:
static bool ShouldCache(EShaderPlatform Platform,const FMaterial* Material,const FVertexFactoryType* VertexFactoryType)
{
bool bShouldCache = Super::ShouldCache(Platform, Material, VertexFactoryType);
return bShouldCache
&& (IsFeatureLevelSupported(Platform, ERHIFeatureLevel::SM4))
&& (!bEnableAtmosphericFog || IsFeatureLevelSupported(Platform, ERHIFeatureLevel::SM4));
}
static void ModifyCompilationEnvironment(EShaderPlatform Platform, const FMaterial* Material, FShaderCompilerEnvironment& OutEnvironment)
{
Super::ModifyCompilationEnvironment(Platform, Material, OutEnvironment);
OutEnvironment.SetDefine(TEXT("BASEPASS_ATMOSPHERIC_FOG"),(uint32)(bEnableAtmosphericFog ? 1 : 0));
}
};
/**
* The base shader type for hull shaders.
*/
template<typename LightMapPolicyType>
class TBasePassHS : public FBaseHS
{
DECLARE_SHADER_TYPE(TBasePassHS,MeshMaterial);
protected:
TBasePassHS() {}
TBasePassHS(const FMeshMaterialShaderType::CompiledShaderInitializerType& Initializer):
FBaseHS(Initializer)
{}
static bool ShouldCache(EShaderPlatform Platform,const FMaterial* Material,const FVertexFactoryType* VertexFactoryType)
{
// Re-use vertex shader gating
return FBaseHS::ShouldCache(Platform, Material, VertexFactoryType)
&& TBasePassVS<LightMapPolicyType,false>::ShouldCache(Platform,Material,VertexFactoryType);
}
static void ModifyCompilationEnvironment(EShaderPlatform Platform, const FMaterial* Material, FShaderCompilerEnvironment& OutEnvironment)
{
// Re-use vertex shader compilation environment
TBasePassVS<LightMapPolicyType,false>::ModifyCompilationEnvironment(Platform, Material, OutEnvironment);
}
};
/**
* The base shader type for Domain shaders.
*/
template<typename LightMapPolicyType>
class TBasePassDS : public FBaseDS
{
DECLARE_SHADER_TYPE(TBasePassDS,MeshMaterial);
protected:
TBasePassDS() {}
TBasePassDS(const FMeshMaterialShaderType::CompiledShaderInitializerType& Initializer):
FBaseDS(Initializer)
{
}
static bool ShouldCache(EShaderPlatform Platform,const FMaterial* Material,const FVertexFactoryType* VertexFactoryType)
{
// Re-use vertex shader gating
return FBaseDS::ShouldCache(Platform, Material, VertexFactoryType)
&& TBasePassVS<LightMapPolicyType,false>::ShouldCache(Platform,Material,VertexFactoryType);
}
static void ModifyCompilationEnvironment(EShaderPlatform Platform, const FMaterial* Material, FShaderCompilerEnvironment& OutEnvironment)
{
// Re-use vertex shader compilation environment
TBasePassVS<LightMapPolicyType,false>::ModifyCompilationEnvironment(Platform, Material, OutEnvironment);
}
public:
virtual bool Serialize(FArchive& Ar) override
{
bool bShaderHasOutdatedParameters = FBaseDS::Serialize(Ar);
return bShaderHasOutdatedParameters;
}
void SetParameters(
FRHICommandList& RHICmdList,
const FMaterialRenderProxy* MaterialRenderProxy,
const FVertexFactory* VertexFactory,
const FSceneView& View
)
{
FBaseDS::SetParameters(RHICmdList, MaterialRenderProxy, View);
}
};
/** Parameters needed to implement the sky light cubemap reflection. */
class FSkyLightReflectionParameters
{
public:
void Bind(const FShaderParameterMap& ParameterMap)
{
SkyLightCubemap.Bind(ParameterMap, TEXT("SkyLightCubemap"));
SkyLightCubemapSampler.Bind(ParameterMap, TEXT("SkyLightCubemapSampler"));
SkyLightBlendDestinationCubemap.Bind(ParameterMap, TEXT("SkyLightBlendDestinationCubemap"));
SkyLightBlendDestinationCubemapSampler.Bind(ParameterMap, TEXT("SkyLightBlendDestinationCubemapSampler"));
SkyLightParameters.Bind(ParameterMap, TEXT("SkyLightParameters"));
}
template<typename TParamRef>
void SetParameters(FRHICommandList& RHICmdList, const TParamRef& ShaderRHI, const FScene* Scene, bool bApplySkyLight)
{
if (SkyLightCubemap.IsBound() || SkyLightBlendDestinationCubemap.IsBound() || SkyLightParameters.IsBound())
{
FTexture* SkyLightTextureResource = GBlackTextureCube;
FTexture* SkyLightBlendDestinationTextureResource = GBlackTextureCube;
float ApplySkyLightMask = 0;
float SkyMipCount = 1;
float BlendFraction = 0;
bool bSkyLightIsDynamic = false;
GetSkyParametersFromScene(Scene, bApplySkyLight, SkyLightTextureResource, SkyLightBlendDestinationTextureResource, ApplySkyLightMask, SkyMipCount, bSkyLightIsDynamic, BlendFraction);
SetTextureParameter(RHICmdList, ShaderRHI, SkyLightCubemap, SkyLightCubemapSampler, SkyLightTextureResource);
SetTextureParameter(RHICmdList, ShaderRHI, SkyLightBlendDestinationCubemap, SkyLightBlendDestinationCubemapSampler, SkyLightBlendDestinationTextureResource);
const FVector4 SkyParametersValue(SkyMipCount - 1.0f, ApplySkyLightMask, bSkyLightIsDynamic ? 1.0f : 0.0f, BlendFraction);
SetShaderValue(RHICmdList, ShaderRHI, SkyLightParameters, SkyParametersValue);
}
}
friend FArchive& operator<<(FArchive& Ar,FSkyLightReflectionParameters& P)
{
Ar << P.SkyLightCubemap << P.SkyLightCubemapSampler << P.SkyLightParameters << P.SkyLightBlendDestinationCubemap << P.SkyLightBlendDestinationCubemapSampler;
return Ar;
}
private:
FShaderResourceParameter SkyLightCubemap;
FShaderResourceParameter SkyLightCubemapSampler;
FShaderResourceParameter SkyLightBlendDestinationCubemap;
FShaderResourceParameter SkyLightBlendDestinationCubemapSampler;
FShaderParameter SkyLightParameters;
void GetSkyParametersFromScene(
const FScene* Scene,
bool bApplySkyLight,
FTexture*& OutSkyLightTextureResource,
FTexture*& OutSkyLightBlendDestinationTextureResource,
float& OutApplySkyLightMask,
float& OutSkyMipCount,
bool& bSkyLightIsDynamic,
float& OutBlendFraction);
};
/** Parameters needed for lighting translucency, shared by multiple shaders. */
class FTranslucentLightingParameters
{
public:
void Bind(const FShaderParameterMap& ParameterMap)
{
TranslucencyLightingVolumeAmbientInner.Bind(ParameterMap, TEXT("TranslucencyLightingVolumeAmbientInner"));
TranslucencyLightingVolumeAmbientInnerSampler.Bind(ParameterMap, TEXT("TranslucencyLightingVolumeAmbientInnerSampler"));
TranslucencyLightingVolumeAmbientOuter.Bind(ParameterMap, TEXT("TranslucencyLightingVolumeAmbientOuter"));
TranslucencyLightingVolumeAmbientOuterSampler.Bind(ParameterMap, TEXT("TranslucencyLightingVolumeAmbientOuterSampler"));
TranslucencyLightingVolumeDirectionalInner.Bind(ParameterMap, TEXT("TranslucencyLightingVolumeDirectionalInner"));
TranslucencyLightingVolumeDirectionalInnerSampler.Bind(ParameterMap, TEXT("TranslucencyLightingVolumeDirectionalInnerSampler"));
TranslucencyLightingVolumeDirectionalOuter.Bind(ParameterMap, TEXT("TranslucencyLightingVolumeDirectionalOuter"));
TranslucencyLightingVolumeDirectionalOuterSampler.Bind(ParameterMap, TEXT("TranslucencyLightingVolumeDirectionalOuterSampler"));
ReflectionCubemap.Bind(ParameterMap, TEXT("ReflectionCubemap"));
ReflectionCubemapSampler.Bind(ParameterMap, TEXT("ReflectionCubemapSampler"));
CubemapArrayIndex.Bind(ParameterMap, TEXT("CubemapArrayIndex"));
SkyLightReflectionParameters.Bind(ParameterMap);
HZBTexture.Bind(ParameterMap, TEXT("HZBTexture"));
HZBSampler.Bind(ParameterMap, TEXT("HZBSampler"));
HZBUvFactorAndInvFactor.Bind(ParameterMap, TEXT("HZBUvFactorAndInvFactor"));
PrevSceneColor.Bind(ParameterMap, TEXT("PrevSceneColor"));
PrevSceneColorSampler.Bind(ParameterMap, TEXT("PrevSceneColorSampler"));
}
void Set(FRHICommandList& RHICmdList, FShader* Shader, const FViewInfo* View);
void SetMesh(FRHICommandList& RHICmdList, FShader* Shader, const FPrimitiveSceneProxy* Proxy, ERHIFeatureLevel::Type FeatureLevel);
/** Serializer. */
friend FArchive& operator<<(FArchive& Ar,FTranslucentLightingParameters& P)
{
Ar << P.TranslucencyLightingVolumeAmbientInner;
Ar << P.TranslucencyLightingVolumeAmbientInnerSampler;
Ar << P.TranslucencyLightingVolumeAmbientOuter;
Ar << P.TranslucencyLightingVolumeAmbientOuterSampler;
Ar << P.TranslucencyLightingVolumeDirectionalInner;
Ar << P.TranslucencyLightingVolumeDirectionalInnerSampler;
Ar << P.TranslucencyLightingVolumeDirectionalOuter;
Ar << P.TranslucencyLightingVolumeDirectionalOuterSampler;
Ar << P.ReflectionCubemap;
Ar << P.ReflectionCubemapSampler;
Ar << P.CubemapArrayIndex;
Ar << P.SkyLightReflectionParameters;
Ar << P.HZBTexture;
Ar << P.HZBSampler;
Ar << P.HZBUvFactorAndInvFactor;
Ar << P.PrevSceneColor;
Ar << P.PrevSceneColorSampler;
return Ar;
}
private:
FShaderResourceParameter TranslucencyLightingVolumeAmbientInner;
FShaderResourceParameter TranslucencyLightingVolumeAmbientInnerSampler;
FShaderResourceParameter TranslucencyLightingVolumeAmbientOuter;
FShaderResourceParameter TranslucencyLightingVolumeAmbientOuterSampler;
FShaderResourceParameter TranslucencyLightingVolumeDirectionalInner;
FShaderResourceParameter TranslucencyLightingVolumeDirectionalInnerSampler;
FShaderResourceParameter TranslucencyLightingVolumeDirectionalOuter;
FShaderResourceParameter TranslucencyLightingVolumeDirectionalOuterSampler;
FShaderResourceParameter ReflectionCubemap;
FShaderResourceParameter ReflectionCubemapSampler;
FShaderParameter CubemapArrayIndex;
FSkyLightReflectionParameters SkyLightReflectionParameters;
FShaderResourceParameter HZBTexture;
FShaderResourceParameter HZBSampler;
FShaderParameter HZBUvFactorAndInvFactor;
FShaderResourceParameter PrevSceneColor;
FShaderResourceParameter PrevSceneColorSampler;
};
/**
* The base type for pixel shaders that render the emissive color, and light-mapped/ambient lighting of a mesh.
* The base type is shared between the versions with and without sky light.
*/
template<typename LightMapPolicyType>
class TBasePassPixelShaderBaseType : public FMeshMaterialShader, public LightMapPolicyType::PixelParametersType
{
public:
static bool ShouldCache(EShaderPlatform Platform,const FMaterial* Material,const FVertexFactoryType* VertexFactoryType)
{
return LightMapPolicyType::ShouldCache(Platform,Material,VertexFactoryType);
}
static void ModifyCompilationEnvironment(EShaderPlatform Platform, const FMaterial* Material, FShaderCompilerEnvironment& OutEnvironment)
{
FMeshMaterialShader::ModifyCompilationEnvironment(Platform, Material, OutEnvironment);
LightMapPolicyType::ModifyCompilationEnvironment(Platform, Material, OutEnvironment);
const bool bOutputVelocity = FVelocityRendering::OutputsToGBuffer();
if (bOutputVelocity)
{
static const auto CVar = IConsoleManager::Get().FindTConsoleVariableDataInt(TEXT("r.AllowStaticLighting"));
// This needs to match FSceneRenderTargets::GetNumGBufferTargets()
const int32 VelocityIndex = (CVar && CVar->GetValueOnAnyThread() != 0) ? 6 : 5;
OutEnvironment.SetRenderTargetOutputFormat(VelocityIndex, PF_G16R16);
}
}
/** Initialization constructor. */
TBasePassPixelShaderBaseType(const FMeshMaterialShaderType::CompiledShaderInitializerType& Initializer):
FMeshMaterialShader(Initializer)
{
LightMapPolicyType::PixelParametersType::Bind(Initializer.ParameterMap);
TranslucentLightingParameters.Bind(Initializer.ParameterMap);
EditorCompositeParams.Bind(Initializer.ParameterMap);
LightGrid.Bind(Initializer.ParameterMap,TEXT("LightGrid"));
}
TBasePassPixelShaderBaseType() {}
void SetParameters(
FRHICommandList& RHICmdList,
const FMaterialRenderProxy* MaterialRenderProxy,
const FMaterial& MaterialResource,
const FViewInfo* View,
EBlendMode BlendMode,
bool bEnableEditorPrimitveDepthTest,
ESceneRenderTargetsMode::Type TextureMode)
{
const FPixelShaderRHIParamRef ShaderRHI = GetPixelShader();
FMeshMaterialShader::SetParameters(RHICmdList, ShaderRHI, MaterialRenderProxy, MaterialResource, *View, TextureMode);
if (View->GetFeatureLevel() >= ERHIFeatureLevel::SM4)
{
if (IsTranslucentBlendMode(BlendMode))
{
TranslucentLightingParameters.Set(RHICmdList, this, View);
// Experimental dynamic forward lighting for translucency. Can be the base for opaque forward lighting which will allow more lighting models or rendering without a GBuffer
if(BlendMode == BLEND_Translucent && MaterialResource.GetTranslucencyLightingMode() == TLM_SurfacePerPixelLighting)
{
check(GetUniformBufferParameter<FForwardLightData>().IsInitialized());
static const auto CVar = IConsoleManager::Get().FindTConsoleVariableDataInt(TEXT("r.ForwardLighting"));
bool bForwardLighting = CVar->GetValueOnRenderThread() != 0;
if(bForwardLighting)
{
SetUniformBufferParameter(RHICmdList, ShaderRHI,GetUniformBufferParameter<FForwardLightData>(),View->ForwardLightData);
SetSRVParameter(RHICmdList, ShaderRHI, LightGrid, GLightGridVertexBuffer.VertexBufferSRV);
}
else
{
// feature is disabled
SetUniformBufferParameter(RHICmdList, ShaderRHI,GetUniformBufferParameter<FForwardLightData>(), 0);
SetSRVParameter(RHICmdList, ShaderRHI, LightGrid, 0);
}
}
}
}
EditorCompositeParams.SetParameters(RHICmdList, MaterialResource, View, bEnableEditorPrimitveDepthTest, GetPixelShader());
}
void SetMesh(FRHICommandList& RHICmdList, const FVertexFactory* VertexFactory,const FSceneView& View,const FPrimitiveSceneProxy* Proxy,const FMeshBatchElement& BatchElement, EBlendMode BlendMode, float DitheredLODTransitionValue);
virtual bool Serialize(FArchive& Ar) override
{
bool bShaderHasOutdatedParameters = FMeshMaterialShader::Serialize(Ar);
LightMapPolicyType::PixelParametersType::Serialize(Ar);
Ar << TranslucentLightingParameters;
Ar << EditorCompositeParams;
Ar << LightGrid;
return bShaderHasOutdatedParameters;
}
private:
FTranslucentLightingParameters TranslucentLightingParameters;
FEditorCompositingParameters EditorCompositeParams;
FShaderResourceParameter LightGrid;
};
/** The concrete base pass pixel shader type. */
template<typename LightMapPolicyType, bool bEnableSkyLight>
class TBasePassPS : public TBasePassPixelShaderBaseType<LightMapPolicyType>
{
DECLARE_SHADER_TYPE(TBasePassPS,MeshMaterial);
public:
static bool ShouldCache(EShaderPlatform Platform,const FMaterial* Material,const FVertexFactoryType* VertexFactoryType)
{
// Only compile skylight version for lit materials
const bool bCacheShaders = !bEnableSkyLight || (Material->GetShadingModel() != MSM_Unlit);
return bCacheShaders
&& (IsFeatureLevelSupported(Platform, ERHIFeatureLevel::SM4))
&& TBasePassPixelShaderBaseType<LightMapPolicyType>::ShouldCache(Platform, Material, VertexFactoryType);
}
static void ModifyCompilationEnvironment(EShaderPlatform Platform, const FMaterial* Material, FShaderCompilerEnvironment& OutEnvironment)
{
OutEnvironment.SetDefine(TEXT("ENABLE_SKY_LIGHT"),(uint32)(bEnableSkyLight ? 1 : 0));
TBasePassPixelShaderBaseType<LightMapPolicyType>::ModifyCompilationEnvironment(Platform, Material, OutEnvironment);
}
/** Initialization constructor. */
TBasePassPS(const ShaderMetaType::CompiledShaderInitializerType& Initializer):
TBasePassPixelShaderBaseType<LightMapPolicyType>(Initializer)
{}
/** Default constructor. */
TBasePassPS() {}
};
/**
* Draws the emissive color and the light-map of a mesh.
*/
template<typename LightMapPolicyType>
class TBasePassDrawingPolicy : public FMeshDrawingPolicy
{
public:
/** The data the drawing policy uses for each mesh element. */
class ElementDataType
{
public:
/** The element's light-map data. */
typename LightMapPolicyType::ElementDataType LightMapElementData;
/** Default constructor. */
ElementDataType()
{}
/** Initialization constructor. */
ElementDataType(const typename LightMapPolicyType::ElementDataType& InLightMapElementData)
: LightMapElementData(InLightMapElementData)
{}
};
/** Initialization constructor. */
TBasePassDrawingPolicy(
const FVertexFactory* InVertexFactory,
const FMaterialRenderProxy* InMaterialRenderProxy,
const FMaterial& InMaterialResource,
ERHIFeatureLevel::Type InFeatureLevel,
LightMapPolicyType InLightMapPolicy,
EBlendMode InBlendMode,
ESceneRenderTargetsMode::Type InSceneTextureMode,
bool bInEnableSkyLight,
bool bInEnableAtmosphericFog,
bool bOverrideWithShaderComplexity = false,
bool bInAllowGlobalFog = false,
bool bInEnableEditorPrimitiveDepthTest = false
):
FMeshDrawingPolicy(InVertexFactory,InMaterialRenderProxy,InMaterialResource,bOverrideWithShaderComplexity),
LightMapPolicy(InLightMapPolicy),
BlendMode(InBlendMode),
SceneTextureMode(InSceneTextureMode),
bAllowGlobalFog(bInAllowGlobalFog),
bEnableSkyLight(bInEnableSkyLight),
bEnableEditorPrimitiveDepthTest(bInEnableEditorPrimitiveDepthTest),
bEnableAtmosphericFog(bInEnableAtmosphericFog)
{
HullShader = NULL;
DomainShader = NULL;
const EMaterialTessellationMode MaterialTessellationMode = InMaterialResource.GetTessellationMode();
if (RHISupportsTessellation(GShaderPlatformForFeatureLevel[InFeatureLevel])
&& InVertexFactory->GetType()->SupportsTessellationShaders()
&& MaterialTessellationMode != MTM_NoTessellation)
{
// Find the base pass tessellation shaders since the material is tessellated
HullShader = InMaterialResource.GetShader<TBasePassHS<LightMapPolicyType> >(VertexFactory->GetType());
DomainShader = InMaterialResource.GetShader<TBasePassDS<LightMapPolicyType> >(VertexFactory->GetType());
}
if (bEnableAtmosphericFog)
{
VertexShader = InMaterialResource.GetShader<TBasePassVS<LightMapPolicyType, true> >(InVertexFactory->GetType());
}
else
{
VertexShader = InMaterialResource.GetShader<TBasePassVS<LightMapPolicyType, false> >(InVertexFactory->GetType());
}
if (bEnableSkyLight)
{
PixelShader = InMaterialResource.GetShader<TBasePassPS<LightMapPolicyType, true> >(InVertexFactory->GetType());
}
else
{
PixelShader = InMaterialResource.GetShader<TBasePassPS<LightMapPolicyType, false> >(InVertexFactory->GetType());
}
#if DO_GUARD_SLOW
// Somewhat hacky
if (SceneTextureMode == ESceneRenderTargetsMode::DontSet && !bEnableEditorPrimitiveDepthTest && InMaterialResource.IsUsedWithEditorCompositing())
{
SceneTextureMode = ESceneRenderTargetsMode::DontSetIgnoreBoundByEditorCompositing;
}
#endif
}
// FMeshDrawingPolicy interface.
bool Matches(const TBasePassDrawingPolicy& Other) const
{
return FMeshDrawingPolicy::Matches(Other) &&
VertexShader == Other.VertexShader &&
PixelShader == Other.PixelShader &&
HullShader == Other.HullShader &&
DomainShader == Other.DomainShader &&
SceneTextureMode == Other.SceneTextureMode &&
bAllowGlobalFog == Other.bAllowGlobalFog &&
bEnableSkyLight == Other.bEnableSkyLight &&
LightMapPolicy == Other.LightMapPolicy;
}
void SetSharedState(FRHICommandList& RHICmdList, const FViewInfo* View, const ContextDataType PolicyContext) const
{
// Set the light-map policy.
LightMapPolicy.Set(RHICmdList, VertexShader,bOverrideWithShaderComplexity ? NULL : PixelShader,VertexShader,PixelShader,VertexFactory,MaterialRenderProxy,View);
VertexShader->SetParameters(RHICmdList, MaterialRenderProxy, VertexFactory, *MaterialResource, *View, bAllowGlobalFog, SceneTextureMode);
if(HullShader)
{
HullShader->SetParameters(RHICmdList, MaterialRenderProxy, *View);
}
if (DomainShader)
{
DomainShader->SetParameters(RHICmdList, MaterialRenderProxy, VertexFactory, *View);
}
#if !(UE_BUILD_SHIPPING || UE_BUILD_TEST)
if (bOverrideWithShaderComplexity)
{
// If we are in the translucent pass then override the blend mode, otherwise maintain additive blending.
if (IsTranslucentBlendMode(BlendMode))
{
RHICmdList.SetBlendState( TStaticBlendState<CW_RGBA, BO_Add, BF_One, BF_One, BO_Add, BF_Zero, BF_One>::GetRHI());
}
TShaderMapRef<FShaderComplexityAccumulatePS> ShaderComplexityPixelShader(View->ShaderMap);
const uint32 NumPixelShaderInstructions = PixelShader->GetNumInstructions();
const uint32 NumVertexShaderInstructions = VertexShader->GetNumInstructions();
ShaderComplexityPixelShader->SetParameters(RHICmdList, NumVertexShaderInstructions, NumPixelShaderInstructions, View->GetFeatureLevel());
}
else
#endif
{
PixelShader->SetParameters(RHICmdList, MaterialRenderProxy,*MaterialResource,View,BlendMode,bEnableEditorPrimitiveDepthTest,SceneTextureMode);
switch(BlendMode)
{
default:
case BLEND_Opaque:
// Opaque materials are rendered together in the base pass, where the blend state is set at a higher level
break;
case BLEND_Masked:
// Masked materials are rendered together in the base pass, where the blend state is set at a higher level
break;
case BLEND_Translucent:
// Alpha channel is only needed for SeparateTranslucency, before this was preserving the alpha channel but we no longer store depth in the alpha channel so it's no problem
RHICmdList.SetBlendState( TStaticBlendState<CW_RGBA, BO_Add, BF_SourceAlpha, BF_InverseSourceAlpha, BO_Add, BF_Zero, BF_InverseSourceAlpha>::GetRHI());
break;
case BLEND_Additive:
// Add to the existing scene color
// Alpha channel is only needed for SeparateTranslucency, before this was preserving the alpha channel but we no longer store depth in the alpha channel so it's no problem
RHICmdList.SetBlendState( TStaticBlendState<CW_RGBA, BO_Add, BF_One, BF_One, BO_Add, BF_Zero, BF_InverseSourceAlpha>::GetRHI());
break;
case BLEND_Modulate:
// Modulate with the existing scene color, preserve destination alpha.
RHICmdList.SetBlendState( TStaticBlendState<CW_RGB, BO_Add, BF_DestColor, BF_Zero>::GetRHI());
break;
};
}
}
/**
* Create bound shader state using the vertex decl from the mesh draw policy
* as well as the shaders needed to draw the mesh
* @param DynamicStride - optional stride for dynamic vertex data
* @return new bound shader state object
*/
FBoundShaderStateInput GetBoundShaderStateInput(ERHIFeatureLevel::Type InFeatureLevel)
{
FPixelShaderRHIParamRef PixelShaderRHIRef = PixelShader->GetPixelShader();
#if !(UE_BUILD_SHIPPING || UE_BUILD_TEST)
if (bOverrideWithShaderComplexity)
{
TShaderMapRef<FShaderComplexityAccumulatePS> ShaderComplexityAccumulatePixelShader(GetGlobalShaderMap(InFeatureLevel));
PixelShaderRHIRef = ShaderComplexityAccumulatePixelShader->GetPixelShader();
}
#endif
return FBoundShaderStateInput(
FMeshDrawingPolicy::GetVertexDeclaration(),
VertexShader->GetVertexShader(),
GETSAFERHISHADER_HULL(HullShader),
GETSAFERHISHADER_DOMAIN(DomainShader),
PixelShaderRHIRef,
FGeometryShaderRHIRef());
}
void SetMeshRenderState(
FRHICommandList& RHICmdList,
const FViewInfo& View,
const FPrimitiveSceneProxy* PrimitiveSceneProxy,
const FMeshBatch& Mesh,
int32 BatchElementIndex,
bool bBackFace,
float DitheredLODTransitionValue,
const ElementDataType& ElementData,
const ContextDataType PolicyContext
) const
{
// Set the light-map policy's mesh-specific settings.
LightMapPolicy.SetMesh(
RHICmdList,
View,
PrimitiveSceneProxy,
VertexShader,
bOverrideWithShaderComplexity ? NULL : PixelShader,
VertexShader,
PixelShader,
VertexFactory,
MaterialRenderProxy,
ElementData.LightMapElementData);
const FMeshBatchElement& BatchElement = Mesh.Elements[BatchElementIndex];
VertexShader->SetMesh(RHICmdList, VertexFactory,View,PrimitiveSceneProxy, Mesh,BatchElement,DitheredLODTransitionValue);
if(HullShader && DomainShader)
{
HullShader->SetMesh(RHICmdList, VertexFactory,View,PrimitiveSceneProxy,BatchElement,DitheredLODTransitionValue);
DomainShader->SetMesh(RHICmdList, VertexFactory,View,PrimitiveSceneProxy,BatchElement,DitheredLODTransitionValue);
}
#if !(UE_BUILD_SHIPPING || UE_BUILD_TEST)
if (bOverrideWithShaderComplexity)
{
// If we are in the translucent pass or rendering a masked material then override the blend mode, otherwise maintain opaque blending
if (BlendMode != BLEND_Opaque)
{
// Add complexity to existing, keep alpha
RHICmdList.SetBlendState(TStaticBlendState<CW_RGB,BO_Add,BF_One,BF_One>::GetRHI());
}
const auto FeatureLevel = View.GetFeatureLevel();
TShaderMapRef<FShaderComplexityAccumulatePS> ShaderComplexityPixelShader(View.ShaderMap);
const uint32 NumPixelShaderInstructions = PixelShader->GetNumInstructions();
const uint32 NumVertexShaderInstructions = VertexShader->GetNumInstructions();
ShaderComplexityPixelShader->SetParameters(RHICmdList, NumVertexShaderInstructions,NumPixelShaderInstructions, FeatureLevel);
}
else
#endif
{
PixelShader->SetMesh(RHICmdList, VertexFactory,View,PrimitiveSceneProxy,BatchElement,BlendMode,DitheredLODTransitionValue);
}
FMeshDrawingPolicy::SetMeshRenderState(RHICmdList, View,PrimitiveSceneProxy,Mesh,BatchElementIndex,bBackFace, DitheredLODTransitionValue,FMeshDrawingPolicy::ElementDataType(),PolicyContext);
}
friend int32 CompareDrawingPolicy(const TBasePassDrawingPolicy& A,const TBasePassDrawingPolicy& B)
{
COMPAREDRAWINGPOLICYMEMBERS(VertexShader);
COMPAREDRAWINGPOLICYMEMBERS(PixelShader);
COMPAREDRAWINGPOLICYMEMBERS(HullShader);
COMPAREDRAWINGPOLICYMEMBERS(DomainShader);
COMPAREDRAWINGPOLICYMEMBERS(VertexFactory);
COMPAREDRAWINGPOLICYMEMBERS(MaterialRenderProxy);
COMPAREDRAWINGPOLICYMEMBERS(SceneTextureMode);
COMPAREDRAWINGPOLICYMEMBERS(bAllowGlobalFog);
COMPAREDRAWINGPOLICYMEMBERS(bEnableSkyLight);
return CompareDrawingPolicy(A.LightMapPolicy,B.LightMapPolicy);
}
protected:
TBasePassVertexShaderBaseType<LightMapPolicyType>* VertexShader;
TBasePassHS<LightMapPolicyType>* HullShader;
TBasePassDS<LightMapPolicyType>* DomainShader;
TBasePassPixelShaderBaseType<LightMapPolicyType>* PixelShader;
LightMapPolicyType LightMapPolicy;
EBlendMode BlendMode;
ESceneRenderTargetsMode::Type SceneTextureMode;
uint32 bAllowGlobalFog : 1;
uint32 bEnableSkyLight : 1;
/** Whether or not this policy is compositing editor primitives and needs to depth test against the scene geometry in the base pass pixel shader */
uint32 bEnableEditorPrimitiveDepthTest : 1;
/** Whether or not this policy enables atmospheric fog */
uint32 bEnableAtmosphericFog : 1;
};
/**
* A drawing policy factory for the base pass drawing policy.
*/
class FBasePassOpaqueDrawingPolicyFactory
{
public:
enum { bAllowSimpleElements = true };
struct ContextType
{
/** Whether or not to perform depth test in the pixel shader */
bool bEditorCompositeDepthTest;
ESceneRenderTargetsMode::Type TextureMode;
ContextType(bool bInEditorCompositeDepthTest, ESceneRenderTargetsMode::Type InTextureMode)
: bEditorCompositeDepthTest( bInEditorCompositeDepthTest )
, TextureMode( InTextureMode )
{}
};
static void AddStaticMesh(FRHICommandList& RHICmdList, FScene* Scene, FStaticMesh* StaticMesh);
static bool DrawDynamicMesh(
FRHICommandList& RHICmdList,
const FViewInfo& View,
ContextType DrawingContext,
const FMeshBatch& Mesh,
bool bBackFace,
bool bPreFog,
const FPrimitiveSceneProxy* PrimitiveSceneProxy,
FHitProxyId HitProxyId
);
};
/** The parameters used to process a base pass mesh. */
class FProcessBasePassMeshParameters
{
public:
const FMeshBatch& Mesh;
const uint64 BatchElementMask;
const FMaterial* Material;
const FPrimitiveSceneProxy* PrimitiveSceneProxy;
EBlendMode BlendMode;
EMaterialShadingModel ShadingModel;
const bool bAllowFog;
/** Whether or not to perform depth test in the pixel shader */
const bool bEditorCompositeDepthTest;
ESceneRenderTargetsMode::Type TextureMode;
ERHIFeatureLevel::Type FeatureLevel;
/** Initialization constructor. */
FProcessBasePassMeshParameters(
const FMeshBatch& InMesh,
const FMaterial* InMaterial,
const FPrimitiveSceneProxy* InPrimitiveSceneProxy,
bool InbAllowFog,
bool bInEditorCompositeDepthTest,
ESceneRenderTargetsMode::Type InTextureMode,
ERHIFeatureLevel::Type InFeatureLevel
):
Mesh(InMesh),
BatchElementMask(Mesh.Elements.Num()==1 ? 1 : (1<<Mesh.Elements.Num())-1), // 1 bit set for each mesh element
Material(InMaterial),
PrimitiveSceneProxy(InPrimitiveSceneProxy),
BlendMode(InMaterial->GetBlendMode()),
ShadingModel(InMaterial->GetShadingModel()),
bAllowFog(InbAllowFog),
bEditorCompositeDepthTest(bInEditorCompositeDepthTest),
TextureMode(InTextureMode),
FeatureLevel(InFeatureLevel)
{
}
/** Initialization constructor. */
FProcessBasePassMeshParameters(
const FMeshBatch& InMesh,
const uint64& InBatchElementMask,
const FMaterial* InMaterial,
const FPrimitiveSceneProxy* InPrimitiveSceneProxy,
bool InbAllowFog,
bool bInEditorCompositeDepthTest,
ESceneRenderTargetsMode::Type InTextureMode,
ERHIFeatureLevel::Type InFeatureLevel
) :
Mesh(InMesh),
BatchElementMask(InBatchElementMask),
Material(InMaterial),
PrimitiveSceneProxy(InPrimitiveSceneProxy),
BlendMode(InMaterial->GetBlendMode()),
ShadingModel(InMaterial->GetShadingModel()),
bAllowFog(InbAllowFog),
bEditorCompositeDepthTest(bInEditorCompositeDepthTest),
TextureMode(InTextureMode),
FeatureLevel(InFeatureLevel)
{
}
};
/** Processes a base pass mesh using an unknown light map policy, and unknown fog density policy. */
template<typename ProcessActionType>
void ProcessBasePassMesh(
FRHICommandList& RHICmdList,
const FProcessBasePassMeshParameters& Parameters,
const ProcessActionType& Action
)
{
// Check for a cached light-map.
const bool bIsLitMaterial = Parameters.ShadingModel != MSM_Unlit;
const bool bNeedsSceneTextures = Parameters.Material->NeedsSceneTextures();
static const auto AllowStaticLightingVar = IConsoleManager::Get().FindTConsoleVariableDataInt(TEXT("r.AllowStaticLighting"));
const bool bAllowStaticLighting = (!AllowStaticLightingVar || AllowStaticLightingVar->GetValueOnRenderThread() != 0);
// Skip rendering meshes that want to use scene textures in passes which can't bind scene textures
// This should be avoided at a higher level when possible, because this is just a silent failure
// This happens for example when rendering a thumbnail of an opaque post process material that uses scene textures
if (!(Parameters.TextureMode == ESceneRenderTargetsMode::DontSet && bNeedsSceneTextures))
{
// Render self-shadowing only for >= SM4 and fallback to non-shadowed for lesser shader models
if (bIsLitMaterial && Action.UseTranslucentSelfShadowing() && Parameters.FeatureLevel >= ERHIFeatureLevel::SM4)
{
if (IsIndirectLightingCacheAllowed(Parameters.FeatureLevel)
&& Action.AllowIndirectLightingCache()
&& Parameters.PrimitiveSceneProxy)
{
// Apply cached point indirect lighting as well as self shadowing if needed
Action.template Process<FSelfShadowedCachedPointIndirectLightingPolicy>(RHICmdList, Parameters, FSelfShadowedCachedPointIndirectLightingPolicy(), FSelfShadowedTranslucencyPolicy::ElementDataType(Action.GetTranslucentSelfShadow()));
}
else
{
Action.template Process<FSelfShadowedTranslucencyPolicy>(RHICmdList, Parameters, FSelfShadowedTranslucencyPolicy(), FSelfShadowedTranslucencyPolicy::ElementDataType(Action.GetTranslucentSelfShadow()));
}
}
else
{
const FLightMapInteraction LightMapInteraction = (bAllowStaticLighting && Parameters.Mesh.LCI && bIsLitMaterial)
? Parameters.Mesh.LCI->GetLightMapInteraction(Parameters.FeatureLevel)
: FLightMapInteraction();
// force LQ lightmaps based on system settings
const bool bAllowHighQualityLightMaps = AllowHighQualityLightmaps(Parameters.FeatureLevel) && LightMapInteraction.AllowsHighQualityLightmaps();
switch(LightMapInteraction.GetType())
{
case LMIT_Texture:
if( bAllowHighQualityLightMaps )
{
const FShadowMapInteraction ShadowMapInteraction = (bAllowStaticLighting && Parameters.Mesh.LCI && bIsLitMaterial)
? Parameters.Mesh.LCI->GetShadowMapInteraction()
: FShadowMapInteraction();
if (ShadowMapInteraction.GetType() == SMIT_Texture)
{
Action.template Process< TDistanceFieldShadowsAndLightMapPolicy<HQ_LIGHTMAP> >(
RHICmdList,
Parameters,
TDistanceFieldShadowsAndLightMapPolicy<HQ_LIGHTMAP>(),
TDistanceFieldShadowsAndLightMapPolicy<HQ_LIGHTMAP>::ElementDataType(ShadowMapInteraction, LightMapInteraction));
}
else
{
Action.template Process< TLightMapPolicy<HQ_LIGHTMAP> >(RHICmdList, Parameters, TLightMapPolicy<HQ_LIGHTMAP>(), LightMapInteraction);
}
}
else
{
Action.template Process< TLightMapPolicy<LQ_LIGHTMAP> >(RHICmdList, Parameters, TLightMapPolicy<LQ_LIGHTMAP>(), LightMapInteraction);
}
break;
default:
{
// Use simple dynamic lighting if enabled, which just renders an unshadowed directional light and a skylight
if (bIsLitMaterial)
{
if (IsSimpleDynamicLightingEnabled())
{
Action.template Process<FSimpleDynamicLightingPolicy>(RHICmdList, Parameters, FSimpleDynamicLightingPolicy(), FSimpleDynamicLightingPolicy::ElementDataType());
}
else if (IsIndirectLightingCacheAllowed(Parameters.FeatureLevel)
&& Action.AllowIndirectLightingCache()
&& Parameters.PrimitiveSceneProxy)
{
const FIndirectLightingCacheAllocation* IndirectLightingCacheAllocation = Parameters.PrimitiveSceneProxy->GetPrimitiveSceneInfo()->IndirectLightingCacheAllocation;
const bool bPrimitiveIsMovable = Parameters.PrimitiveSceneProxy->IsMovable();
// Use the indirect lighting cache shaders if the object has a cache allocation
// This happens for objects with unbuilt lighting
if ((IndirectLightingCacheAllocation && IndirectLightingCacheAllocation->IsValid())
// Use the indirect lighting cache shaders if the object is movable, it may not have a cache allocation yet because that is done in InitViews
// And movable objects are sometimes rendered in the static draw lists
|| bPrimitiveIsMovable)
{
if (CanIndirectLightingCacheUseVolumeTexture(Parameters.FeatureLevel)
// Translucency forces point sample for pixel performance
&& Action.AllowIndirectLightingCacheVolumeTexture()
&& ((IndirectLightingCacheAllocation && !IndirectLightingCacheAllocation->bPointSample)
|| (bPrimitiveIsMovable && Parameters.PrimitiveSceneProxy->GetIndirectLightingCacheQuality() == ILCQ_Volume)))
{
// Use a lightmap policy that supports reading indirect lighting from a volume texture for dynamic objects
Action.template Process<FCachedVolumeIndirectLightingPolicy>(RHICmdList, Parameters, FCachedVolumeIndirectLightingPolicy(), FCachedVolumeIndirectLightingPolicy::ElementDataType());
}
else
{
// Use a lightmap policy that supports reading indirect lighting from a single SH sample
Action.template Process<FCachedPointIndirectLightingPolicy>(RHICmdList, Parameters, FCachedPointIndirectLightingPolicy(), FCachedPointIndirectLightingPolicy::ElementDataType(false));
}
}
else
{
Action.template Process<FNoLightMapPolicy>(RHICmdList, Parameters, FNoLightMapPolicy(), FNoLightMapPolicy::ElementDataType());
}
}
else
{
Action.template Process<FNoLightMapPolicy>(RHICmdList, Parameters, FNoLightMapPolicy(), FNoLightMapPolicy::ElementDataType());
}
}
else
{
Action.template Process<FNoLightMapPolicy>(RHICmdList, Parameters, FNoLightMapPolicy(), FNoLightMapPolicy::ElementDataType());
}
}
break;
};
}
}
}
| 39.994965 | 236 | 0.793806 | [
"mesh",
"geometry",
"render",
"object",
"transform"
] |
caf37d32c9f815ef5718a12f7cac8563743134e4 | 7,520 | h | C | InventoryModule/AbstractInventoryDataModel.h | zemo/naali | a02ee7a0547c5233579eda85dedb934b61c546ab | [
"Apache-2.0"
] | 1 | 2018-04-02T15:38:10.000Z | 2018-04-02T15:38:10.000Z | InventoryModule/AbstractInventoryDataModel.h | mattire/naali | 28c9cdc84c6a85e0151a222e55ae35c9403f0212 | [
"Apache-2.0"
] | null | null | null | InventoryModule/AbstractInventoryDataModel.h | mattire/naali | 28c9cdc84c6a85e0151a222e55ae35c9403f0212 | [
"Apache-2.0"
] | 1 | 2021-09-04T12:37:34.000Z | 2021-09-04T12:37:34.000Z | /**
* For conditions of distribution and use, see copyright notice in license.txt
*
* @file AbstractInventoryDataModel.h
* @brief Abstract inventory data model, pure virtual class. Inherit this class to create your own inventory
* data models to use in InventoryItemModel.
*/
#ifndef incl_InventoryModule_AbstractInventoryDataModel_h
#define incl_InventoryModule_AbstractInventoryDataModel_h
#include <QObject>
#include <QPair>
#include <QString>
// Few useful defines.
#define STD_TO_QSTR(p) QString(p.c_str())
#define QSTR_TO_UUID(p) RexUUID(p.toStdString())
#define UUID_TO_QSTR(p) QString(p.ToString().c_str())
namespace Inventory
{
typedef QPair<bool, QString> UploadResult;
class AbstractInventoryItem;
/// Abstract inventory data model, pure virtual class. Inherit this class to create your own inventory data models to use in InventoryItemModel.
class AbstractInventoryDataModel : public QObject
{
Q_OBJECT
public:
/// Default constructor.
AbstractInventoryDataModel() {}
/// Destructor.
virtual ~AbstractInventoryDataModel() {}
/// @return First folder by the requested name or null if the folder isn't found.
virtual AbstractInventoryItem *GetFirstChildFolderByName(const QString &name) const = 0;
/// @return First folder by the requested id or null if the folder isn't found.
virtual AbstractInventoryItem *GetChildFolderById(const QString &searchId) const = 0;
/// @return First item by the requested id or null if the item isn't found.
virtual AbstractInventoryItem *GetChildAssetById(const QString &searchId) const = 0;
/// @return Pointer to the requested item, or null if not found.
virtual AbstractInventoryItem *GetChildById(const QString &searchId) const = 0;
/// Returns folder by requested id, or creates a new one if the folder doesnt exist,
/// or returns null if the parent folder is invalid.
/// @param id ID.
/// @param parent Parent folder.
/// @return Pointer to the existing or just created folder.
virtual AbstractInventoryItem *GetOrCreateNewFolder(const QString &id, AbstractInventoryItem &parentFolder,
const QString &name = "New Folder", const bool ¬ify_server = true) = 0;
/// Returns asset requested id, or creates a new one if the folder doesnt exist.
/// @param inventory_id Inventory ID.
/// @param asset_id Asset ID.
/// @param parent Parent folder.
/// @return Pointer to the existing or just created asset.
virtual AbstractInventoryItem *GetOrCreateNewAsset(const QString &inventory_id, const QString &asset_id,
AbstractInventoryItem &parentFolder, const QString &name) = 0;
public slots:
/// Request inventory descendents for spesific folder from the server.
/// @param item Folder.
/// @return True, if the folder could be opened.
virtual bool FetchInventoryDescendents(AbstractInventoryItem *item) = 0;
/// Notifies server about item move operation.
/// @item Inventory item.
virtual void NotifyServerAboutItemMove(AbstractInventoryItem *item) = 0;
/// Notifies server about item move operation.
/// @item Inventory item.
virtual void NotifyServerAboutItemCopy(AbstractInventoryItem *item) = 0;
/// Notifies server about item remove operation.
/// @item Inventory item.
virtual void NotifyServerAboutItemRemove(AbstractInventoryItem *item) = 0;
/// Notifies server about item update operation(e.g. name changed).
/// @item Inventory item.
virtual void NotifyServerAboutItemUpdate(AbstractInventoryItem *item, const QString &old_name) = 0;
/// Opens inventory item.
/// @param Inventory item.
/// @return True if the item at spesific index could be opened, false otherwise.
virtual bool OpenItem(AbstractInventoryItem *item) = 0;
/// Uploads file.
/// @param filename Filename.
/// @param parent_folder Destination folder in inventory for upload.
virtual void UploadFile(const QString &filename, AbstractInventoryItem *parent_folder) = 0;
/// Uploads multiple files.
/// @param filenames List of filenames.
/// @param item_names List of names for the items.
/// @param parent_folder Destination folder in inventory for upload.
virtual void UploadFiles(QStringList &filenames, QStringList &item_names, AbstractInventoryItem *parent_folder) = 0;
/// Uploads multiple files, uses data buffers.
/// @param filenames List of filenames.
/// @param parent_folder Destination folder in inventory for upload.
virtual void UploadFilesFromBuffer(QStringList &filenames, QVector<QVector<uchar> > &buffers,
AbstractInventoryItem *parent_folder) = 0;
/// Downloads asset/file from inventory.
/// @param store_folder Store folder.
/// @param selected_item Selected item in inventory.
virtual void DownloadFile(const QString &store_folder, AbstractInventoryItem *selected_item) = 0;
/// @return Inventory root folder.
virtual AbstractInventoryItem *GetRoot() const = 0;
/// @return Inventory trash folder.
virtual AbstractInventoryItem *GetTrashFolder() const = 0;
/// @return Inventory trash folder.
virtual bool GetUseTrashFolder() const = 0;
/// Semi-hack: sends signal indicating that folders contents are fetched and
/// the dummy "Loading..." folder can be deleted.
void EmitFolderDescendentsFetched(const QString &folder_id) { emit FolderDescendentsFetched(folder_id); }
signals:
/// Indicates that multiupload has started.
/// @param file_count Number of files to be uploaded.
void MultiUploadStarted(size_t file_count);
/// Indicates that asset upload has started.
/// @param filename Filename.
void UploadStarted(const QString &filename);
/// Indicates that asset upload has failed.
/// @param filename Filename.
void UploadFailed(const QString &filename, const QString &reason = "Unknown reason");
/// Indicates that asset upload has completed.
/// @param filename Filename.
void UploadCompleted(const QString &filename, const QString &asset_ref);
/// Indicates that multiupload has completed.
void MultiUploadCompleted();
/// Indicates that asset download has started.
/// @param asset_id Asset ID.
/// @param name Name of the asset.
void DownloadStarted(const QString &asset_id, const QString &name);
/// Indicates that asset download has aborted.
/// @param asset_id Asset ID.
void DownloadAborted(const QString &asset_id);
/// Indicates that asset download is completed.
/// @param asset_id Asset ID.
void DownloadCompleted(const QString &asset_id);
///
/// @param
void NewItem(AbstractInventoryItem *item);
/// Semi-hack: signal indicating that folders contents are fetched and the dummy "Loading..." asset can be deleted.
/// @param folder_id ID of the folder whose dummy asset we want to delete.
void FolderDescendentsFetched(const QString &folder_id);
private:
Q_DISABLE_COPY(AbstractInventoryDataModel);
};
}
#endif
| 43.218391 | 148 | 0.681649 | [
"model"
] |
caf9c7c71ddfc0b07fed1f8de9303ebd00a9c35c | 468 | h | C | LearnOpenGLAAA/02hello_triangle/src/SandboxLayer.h | KirkXu/LearnOpenGLAAA | b5be7e4edb5cade6d740d020f3d13c3884bb7d30 | [
"Apache-2.0"
] | 1 | 2021-08-04T07:06:58.000Z | 2021-08-04T07:06:58.000Z | LearnOpenGLAAA/03shaders/src/SandboxLayer.h | KirkXu/LearnOpenGLAAA | b5be7e4edb5cade6d740d020f3d13c3884bb7d30 | [
"Apache-2.0"
] | null | null | null | LearnOpenGLAAA/03shaders/src/SandboxLayer.h | KirkXu/LearnOpenGLAAA | b5be7e4edb5cade6d740d020f3d13c3884bb7d30 | [
"Apache-2.0"
] | null | null | null | #pragma once
#include <GLCore.h>
#include <GLCoreUtils.h>
class SandboxLayer : public GLCore::Layer
{
public:
SandboxLayer();
virtual ~SandboxLayer();
virtual void OnAttach() override;
virtual void OnDetach() override;
virtual void OnEvent(GLCore::Event& event) override;
virtual void OnUpdate(GLCore::Timestep ts) override;
virtual void OnImGuiRender() override;
private:
std::vector<GLCore::Utils::Shader*> m_Shader;
GLuint m_VAO[2], m_VBO[2], m_IBO;
}; | 22.285714 | 53 | 0.745726 | [
"vector"
] |
cafa8475c248153b24f9aa77d5121a89787cf8ee | 3,456 | h | C | stratum/hal/lib/phal/system_interface.h | cholve/stratum | 09ddb5acb604f7e694a6b7d2fe93fea79f801794 | [
"Apache-2.0"
] | 1 | 2020-07-14T09:32:38.000Z | 2020-07-14T09:32:38.000Z | stratum/hal/lib/phal/system_interface.h | xiaozhitaba/stratum | 9f5bd2b285badbef11e81eca6c31d4a3c4342843 | [
"Apache-2.0"
] | 3 | 2020-07-09T07:37:27.000Z | 2020-08-18T10:05:26.000Z | stratum/hal/lib/phal/system_interface.h | xiaozhitaba/stratum | 9f5bd2b285badbef11e81eca6c31d4a3c4342843 | [
"Apache-2.0"
] | 1 | 2021-03-29T16:36:59.000Z | 2021-03-29T16:36:59.000Z | // Copyright 2018 Google LLC
// Copyright 2018-present Open Networking Foundation
// SPDX-License-Identifier: Apache-2.0
#ifndef STRATUM_HAL_LIB_PHAL_SYSTEM_INTERFACE_H_
#define STRATUM_HAL_LIB_PHAL_SYSTEM_INTERFACE_H_
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "stratum/glue/status/status.h"
#include "stratum/glue/status/statusor.h"
namespace stratum {
namespace hal {
namespace phal {
// We use unsigned long long int here to match the udev specification.
using UdevSequenceNumber = unsigned long long int; // NOLINT(runtime/int)
// These two classes wrap all interactions with udev.
class UdevMonitor;
// Represents an instance of Udev. This class is used to initiate all monitoring
// of system hardware state.
class Udev {
public:
// All information relating to a single udev event.
struct Event {
std::string device_path;
UdevSequenceNumber sequence_number;
std::string action_type;
};
virtual ~Udev() {}
// Creates a new udev monitor. This monitor is responsible for handling some
// subset of udev events.
virtual ::util::StatusOr<std::unique_ptr<UdevMonitor>> MakeUdevMonitor() = 0;
// Returns a list of all devices in the given subsystem, and their current
// states. Each returned pair contains <device path, action>. The returned
// action is typically "add".
virtual ::util::StatusOr<std::vector<std::pair<std::string, std::string>>>
EnumerateSubsystem(const std::string& subsystem) = 0;
};
// Represents a single Udev Monitor, which is responsible for monitoring a
// subset of hardware state changes and reporting them via GetUdevEvent.
class UdevMonitor {
public:
virtual ~UdevMonitor() {}
// Adds a filter to this monitor. By default, a monitor will receive all udev
// events. Adding filters to a monitor limits the set of events handled.
// Filters are applied by subsystem name. Note that UdevMonitorAddFilter may
// not be called after UdevMonitorEnableReceiving.
virtual ::util::Status AddFilter(const std::string& subsystem) = 0;
// Enables receiving events. GetUdevEvent may not be called before
// EnableReceiving.
virtual ::util::Status EnableReceiving() = 0;
// If a new udev event has been handled by this monitor, returns true.
// Otherwise returns false. If true is returned, the passed event is
// filled with the new udev event's information. If false is returned,
// the passed event is unchanged.
virtual ::util::StatusOr<bool> GetUdevEvent(Udev::Event* event) = 0;
};
// A mockable interface for all system interactions performed by
// our configuration code. Needed for testing and cross-platform purposes.
class SystemInterface {
public:
virtual ~SystemInterface() {}
// File access functions:
virtual bool PathExists(const std::string& path) const = 0;
virtual ::util::Status ReadFileToString(const std::string& path,
std::string* buffer) const = 0;
virtual ::util::Status WriteStringToFile(const std::string& buffer,
const std::string& path) const = 0;
// Udev functions:
// Creates a new Udev, which is responsible for all other udev functions.
virtual ::util::StatusOr<std::unique_ptr<Udev>> MakeUdev() const = 0;
// TODO(unknown): Add any other functions we need.
};
} // namespace phal
} // namespace hal
} // namespace stratum
#endif // STRATUM_HAL_LIB_PHAL_SYSTEM_INTERFACE_H_
| 35.628866 | 80 | 0.724248 | [
"vector"
] |
1b01d9a67063ccc56562c06b8ef5695f9b6a4f1c | 609 | h | C | src/sdk/hl2_csgo/game/client/swarm/iasw_client_aim_target.h | newcommerdontblame/ionlib | 47ca829009e1529f62b2134aa6c0df8673864cf3 | [
"MIT"
] | 51 | 2016-03-18T01:48:07.000Z | 2022-03-21T20:02:02.000Z | src/game/client/swarm/iasw_client_aim_target.h | senny970/AlienSwarm | c5a2d3fa853c726d040032ff2c7b90c8ed8d5d84 | [
"Unlicense"
] | null | null | null | src/game/client/swarm/iasw_client_aim_target.h | senny970/AlienSwarm | c5a2d3fa853c726d040032ff2c7b90c8ed8d5d84 | [
"Unlicense"
] | 26 | 2016-03-17T21:20:37.000Z | 2022-03-24T10:21:30.000Z | #ifndef _INCLUDED_ASW_CLIENT_AIM_TARGET_H
#define _INCLUDED_ASW_CLIENT_AIM_TARGET_H
DECLARE_AUTO_LIST( IClientAimTargetsAutoList );
abstract_class IASW_Client_Aim_Target : public IClientAimTargetsAutoList
{
public:
IASW_Client_Aim_Target( bool bAutoAdd = true ) : IClientAimTargetsAutoList( bAutoAdd ) {}
virtual float GetRadius() = 0;
virtual bool IsAimTarget() = 0;
virtual const Vector& GetAimTargetPos(const Vector &vecFiringSrc, bool bWeaponPrefersFlatAiming=false) = 0;
virtual const Vector& GetAimTargetRadiusPos(const Vector &vecFiringSrc) = 0;
};
#endif // _INCLUDED_ASW_CLIENT_AIM_TARGET_H | 33.833333 | 108 | 0.821018 | [
"vector"
] |
1b0affcac22075119db04be88118b247f5a340cb | 1,262 | c | C | practicas/k-esimo mayor/util.c | jorgeteixe/udc-prep-algoritmos | ac23ebe796c54cce243db22ae14894f3b7630e76 | [
"MIT"
] | 3 | 2022-01-08T11:44:00.000Z | 2022-01-26T10:57:53.000Z | practicas/k-esimo mayor/util.c | jorgeteixe/udc-prep-algoritmos | ac23ebe796c54cce243db22ae14894f3b7630e76 | [
"MIT"
] | 1 | 2022-01-09T09:25:07.000Z | 2022-01-09T09:25:07.000Z | practicas/k-esimo mayor/util.c | jorgeteixe/udc-prep-algoritmos | ac23ebe796c54cce243db22ae14894f3b7630e76 | [
"MIT"
] | 2 | 2021-12-31T13:02:07.000Z | 2022-01-09T15:27:52.000Z | #include "util.h"
void rellena_aleatorio(int v[], int n) {
int i, m = 2 * n + 1;
for (i = 0; i < n; i++) {
v[i] = (rand() % m) - n;
}
}
void rellena_ascendente(int v[], int n) {
int i;
for (i = 0; i < n; i++) {
v[i] = i;
}
}
void rellena_descendente(int v[], int n) {
int i;
for (i = 0; i < n; i++) {
v[i] = n - i - 1;
}
}
double microsegundos() {
struct timeval t;
if (gettimeofday(&t, NULL) < 0) {
return 0.0;
}
return t.tv_usec + t.tv_sec * 1000000.0;
}
void listar_vector(int v[], int n) {
int k;
printf("[");
for (k = 0; k < n; k++) {
printf("%3d ", v[k]);
}
printf("]\n");
}
void inicializar_semilla() {
srand(time(NULL));
}
int ordenado(int v[], int n) {
int i = 0;
while ((i < n - 1)) {
if (v[i] > v[i + 1]) {
return 0;
}
i++;
}
return 1;
}
void intercambiar(int *x, int *y) {
int aux = *x;
*x = *y;
*y = aux;
}
void ordena_insercion(int v[], int n) {
int x, j, i;
for (i = 0; i < n; i++) {
x = v[i];
j = i - 1;
while (j >= 0 && v[j] > x) {
v[j + 1] = v[j];
j = j - 1;
}
v[j + 1] = x;
}
}
| 17.054054 | 44 | 0.400158 | [
"3d"
] |
1b122a6153557469e5a3d62ecd6d5ecf6d7b2dc0 | 4,313 | h | C | .MeshSync/Plugin/MeshSync/msProtocol.h | RopyTan/MeshSync | 69c0aa3e953d5f9a99d8c0aaafe3f89bfb8c63cf | [
"MIT"
] | null | null | null | .MeshSync/Plugin/MeshSync/msProtocol.h | RopyTan/MeshSync | 69c0aa3e953d5f9a99d8c0aaafe3f89bfb8c63cf | [
"MIT"
] | null | null | null | .MeshSync/Plugin/MeshSync/msProtocol.h | RopyTan/MeshSync | 69c0aa3e953d5f9a99d8c0aaafe3f89bfb8c63cf | [
"MIT"
] | 2 | 2020-03-25T06:46:49.000Z | 2021-01-26T03:27:43.000Z | #pragma once
#include <atomic>
#include "SceneGraph/msSceneGraph.h"
namespace ms {
class Message
{
public:
enum class Type
{
Unknown,
Get,
Set,
Delete,
Fence,
Text,
Screenshot,
Query,
Response,
};
int protocol_version = msProtocolVersion;
int session_id = InvalidID;
int message_id = 0;
virtual ~Message();
virtual void serialize(std::ostream& os) const;
virtual void deserialize(std::istream& is); // throw
};
msSerializable(Message);
msDeclPtr(Message);
struct GetFlags
{
uint32_t get_transform : 1;
uint32_t get_points : 1;
uint32_t get_normals : 1;
uint32_t get_tangents : 1;
uint32_t get_uv0 : 1;
uint32_t get_uv1 : 1;
uint32_t get_colors : 1;
uint32_t get_indices : 1;
uint32_t get_material_ids : 1;
uint32_t get_bones : 1;
uint32_t get_blendshapes : 1;
uint32_t apply_culling : 1;
};
class GetMessage : public Message
{
using super = Message;
public:
GetFlags flags = {0};
SceneSettings scene_settings;
MeshRefineSettings refine_settings;
// non-serializable
std::atomic_bool ready;
public:
GetMessage();
void serialize(std::ostream& os) const override;
void deserialize(std::istream& is) override;
};
msSerializable(GetMessage);
msDeclPtr(GetMessage);
class SetMessage : public Message
{
using super = Message;
public:
Scene scene;
public:
SetMessage();
void serialize(std::ostream& os) const override;
void deserialize(std::istream& is) override;
};
msSerializable(SetMessage);
msDeclPtr(SetMessage);
class DeleteMessage : public Message
{
using super = Message;
public:
std::vector<Identifier> entities;
std::vector<Identifier> materials;
DeleteMessage();
void serialize(std::ostream& os) const override;
void deserialize(std::istream& is) override;
};
msSerializable(DeleteMessage);
msDeclPtr(DeleteMessage);
class FenceMessage : public Message
{
using super = Message;
public:
enum class FenceType
{
Unknown,
SceneBegin,
SceneEnd,
};
FenceType type = FenceType::Unknown;
~FenceMessage() override;
void serialize(std::ostream& os) const override;
void deserialize(std::istream& is) override;
};
msSerializable(FenceMessage);
msDeclPtr(FenceMessage);
class TextMessage : public Message
{
using super = Message;
public:
enum class Type
{
Normal,
Warning,
Error,
};
~TextMessage() override;
void serialize(std::ostream& os) const override;
void deserialize(std::istream& is) override;
public:
std::string text;
Type type = Type::Normal;
};
msSerializable(TextMessage);
msDeclPtr(TextMessage);
class ScreenshotMessage : public Message
{
using super = Message;
public:
// non-serializable
std::atomic_bool ready;
public:
ScreenshotMessage();
void serialize(std::ostream& os) const override;
void deserialize(std::istream& is) override;
};
msSerializable(ScreenshotMessage);
msDeclPtr(ScreenshotMessage);
class QueryMessage : public Message
{
using super = Message;
public:
enum class QueryType
{
Unknown,
ClientName,
RootNodes,
AllNodes,
};
public:
QueryType type = QueryType::Unknown;
std::atomic_bool ready; // non-serializable
MessagePtr response; //
QueryMessage();
void serialize(std::ostream& os) const override;
void deserialize(std::istream& is) override;
};
msSerializable(QueryMessage);
msDeclPtr(QueryMessage);
class ResponseMessage : public Message
{
using super = Message;
public:
std::vector<std::string> text;
ResponseMessage();
void serialize(std::ostream& os) const override;
void deserialize(std::istream& is) override;
};
msSerializable(ResponseMessage);
msDeclPtr(ResponseMessage);
class PollMessage : public Message
{
using super = Message;
public:
enum class PollType
{
Unknown,
SceneUpdate,
};
PollType type = PollType::Unknown;
std::atomic_bool ready; // non-serializable
PollMessage();
void serialize(std::ostream& os) const override;
void deserialize(std::istream& is) override;
};
msSerializable(PollMessage);
msDeclPtr(PollMessage);
} // namespace ms
| 19.340807 | 56 | 0.678646 | [
"vector"
] |
1b1a8b60350569fc357abb082225dc67b81e46f3 | 3,615 | h | C | src/GUI/lib/struct.h | theobori/drunkOS | a3ec1fbefd6f8af86c4dda87f2ccfc9784d4302f | [
"MIT"
] | null | null | null | src/GUI/lib/struct.h | theobori/drunkOS | a3ec1fbefd6f8af86c4dda87f2ccfc9784d4302f | [
"MIT"
] | null | null | null | src/GUI/lib/struct.h | theobori/drunkOS | a3ec1fbefd6f8af86c4dda87f2ccfc9784d4302f | [
"MIT"
] | 1 | 2022-03-29T20:59:27.000Z | 2022-03-29T20:59:27.000Z | #ifndef __STRUCT_H__
#define __STRUCT_H__
#include "types.h"
typedef struct {
char VbeSignature[4]; // VBE Signature
u16 VbeVersion; // VBE version number
char *OEMStringPtr; // Pointer to OEM string
u32 Capabilities; // Capabilities of video card
u32 *VideoModePtr; // Pointer to supported modes
u16 TotalMemory; // Number of 64kb memory blocks
u16 OemSoftwareRev; // VBE implementation Software revision
u32 OemVendorNamePtr; // Pointer to Vendor Name String
u32 OemProductNamePtr; // Pointer to Product Name String
u32 OemProductRevPtr; // Pointer to Product Revision String
char reserved[222]; // Pad to 256 byte block size
char OemData[256]; // Data Area for OEM Strings
} __attribute__ ((packed)) VBE20_INFOBLOCK;
typedef struct {
// Mandatory information for all VBE revisions
u16 ModeAttributes; // Mode attributes
u8 WinAAttributes; // Window A attributes
u8 WinBAttributes; // Window B attributes
u16 WinGranularity; // Window granularity in k
u16 WinSize; // Window size in k
u16 WinASegment; // Window A segment
u16 WinBSegment; // Window B segment
void (*WinFuncPtr)(void); // Pointer to window function
u16 BytesPerScanLine; // Bytes per scanline
// Mandatory information for VBE 1.2 and above
u16 XResolution; // Horizontal resolution
u16 YResolution; // Vertical resolution
u8 XCharSize; // Character cell width
u8 YCharSize; // Character cell height
u8 NumberOfPlanes; // Number of memory planes
u8 BitsPerPixel; // Bits per pixel
u8 NumberOfBanks; // Number of CGA style banks
u8 MemoryModel; // Memory model type
u8 BankSize; // Size of CGA style banks
u8 NumberOfImagePages; // Number of images pages
u8 Reserved; // Reserved
// Direct color fields
u8 RedMaskSize; // Size of direct color red mask
u8 RedFieldPosition; // Bit posn of lsb of red mask
u8 GreenMaskSize; // Size of direct color green mask
u8 GreenFieldPosition; // Bit posn of lsb of green mask
u8 BlueMaskSize; // Size of direct color blue mask
u8 BlueFieldPosition; // Bit posn of lsb of blue mask
u8 RsvdMaskSize; // Size of direct color res mask
u8 RsvdFieldPosition; // Bit posn of lsb of res mask
u8 DirectColorModeInfo; // Direct color mode attributes
// Mandatory information for VBE 2.0 and above
u32 PhysBasePtr; // physical address for flat frame buffer
u32 OffScreenMemOffset; // pointer to start of off screen memory
u16 OffScreenMemSize; // amount of off screen memory in 1k units
u8 Reserved2[206]; // remainder of ModeInfoBlock
} VBE20_MODEINFOBLOCK;
#endif | 56.484375 | 86 | 0.526694 | [
"model"
] |
1b1c4c628d8c39b88f6e3bf0a966a90a081ac00e | 11,864 | h | C | include/gipfeli/stubs-internal.h | eggrobin/gipfeli | bd986b7a7690bcb07e277f503c0ab6855bb98d4c | [
"CC-BY-3.0"
] | 1 | 2020-09-04T15:02:19.000Z | 2020-09-04T15:02:19.000Z | include/gipfeli/stubs-internal.h | eggrobin/gipfeli | bd986b7a7690bcb07e277f503c0ab6855bb98d4c | [
"CC-BY-3.0"
] | null | null | null | include/gipfeli/stubs-internal.h | eggrobin/gipfeli | bd986b7a7690bcb07e277f503c0ab6855bb98d4c | [
"CC-BY-3.0"
] | 3 | 2019-10-26T15:57:21.000Z | 2020-06-28T11:43:23.000Z | // Various stubs for the open-source version of Gipfeli.
#ifndef UTIL_COMPRESSION_GIPFELI_OPENSOURCE_STUBS_INTERNAL_H_
#define UTIL_COMPRESSION_GIPFELI_OPENSOURCE_STUBS_INTERNAL_H_
#include <string.h>
#include <assert.h>
#include <stdlib.h>
#include <stdint.h>
#include <stddef.h>
#include <string>
#include "config.h"
#if defined(__x86_64__)
// Enable 64-bit optimized versions of some routines.
#define ARCH_K8 1
#endif
// Static prediction hints.
#ifdef HAVE_BUILTIN_EXPECT
#define PREDICT_FALSE(x) (__builtin_expect(x, 0))
#define PREDICT_TRUE(x) (__builtin_expect(!!(x), 1))
#else
#define PREDICT_FALSE(x) x
#define PREDICT_TRUE(x) x
#endif
// A macro to disallow the copy constructor and operator= functions
// This should be used in the private: declarations for a class.
// (Note: this is not required when building for C++11, but is still needed
// for any portable, non-C++11 code.)
//
// For disallowing only assign or copy, delete the relevant operator or
// constructor, for example:
// void operator=(const TypeName&) = delete;
// Note, that most uses of DISALLOW_ASSIGN and DISALLOW_COPY are broken
// semantically, one should either use disallow both or neither. Try to
// avoid these in new code.
//
// When building with C++11 toolchains, just use the language support
// for explicitly deleted methods. This doesn't delete the move constructor,
// so objects can still be stored in move-aware containers, like std::vector.
#ifdef LANG_CXX11
#define DISALLOW_COPY_AND_ASSIGN(TypeName) \
TypeName(const TypeName&) = delete; \
void operator=(const TypeName&) = delete
#else
#define DISALLOW_COPY_AND_ASSIGN(TypeName) \
TypeName(const TypeName&); \
void operator=(const TypeName&)
#endif
namespace google {
namespace compression {
typedef int8_t int8;
typedef uint8_t uint8;
typedef int16_t int16;
typedef uint16_t uint16;
typedef int32_t int32;
typedef uint32_t uint32;
typedef int64_t int64;
typedef uint64_t uint64;
static const uint32 kuint32max = static_cast<uint32>(0xFFFFFFFF);
static const int64 kint64max = static_cast<int64>(0x7FFFFFFFFFFFFFFFLL);
// Potentially unaligned loads and stores.
// x86 and PowerPC can simply do these loads and stores native.
#if !defined(GIPFELI_NO_UNALIGNED) && (defined(__i386__) || defined(__x86_64__) || defined(__powerpc__))
#define UNALIGNED_LOAD16(_p) (*reinterpret_cast<const uint16 *>(_p))
#define UNALIGNED_LOAD32(_p) (*reinterpret_cast<const uint32 *>(_p))
#define UNALIGNED_LOAD64(_p) (*reinterpret_cast<const uint64 *>(_p))
#define UNALIGNED_STORE16(_p, _val) (*reinterpret_cast<uint16 *>(_p) = (_val))
#define UNALIGNED_STORE32(_p, _val) (*reinterpret_cast<uint32 *>(_p) = (_val))
#define UNALIGNED_STORE64(_p, _val) (*reinterpret_cast<uint64 *>(_p) = (_val))
// ARMv7 and newer support native unaligned accesses, but only of 16-bit
// and 32-bit values (not 64-bit); older versions either raise a fatal signal,
// do an unaligned read and rotate the words around a bit, or do the reads very
// slowly (trip through kernel mode). There's no simple #define that says just
// “ARMv7 or higher”, so we have to filter away all ARMv5 and ARMv6
// sub-architectures.
//
// This is a mess, but there's not much we can do about it.
#elif !defined(GIPFELI_NO_UNALIGNED) && \
(defined(__arm__) && \
!defined(__ARM_ARCH_4__) && \
!defined(__ARM_ARCH_4T__) && \
!defined(__ARM_ARCH_5__) && \
!defined(__ARM_ARCH_5T__) && \
!defined(__ARM_ARCH_5TE__) && \
!defined(__ARM_ARCH_5TEJ__) && \
!defined(__ARM_ARCH_6__) && \
!defined(__ARM_ARCH_6J__) && \
!defined(__ARM_ARCH_6K__) && \
!defined(__ARM_ARCH_6Z__) && \
!defined(__ARM_ARCH_6ZK__) && \
!defined(__ARM_ARCH_6T2__))
#define UNALIGNED_LOAD16(_p) (*reinterpret_cast<const uint16 *>(_p))
#define UNALIGNED_LOAD32(_p) (*reinterpret_cast<const uint32 *>(_p))
#define UNALIGNED_STORE16(_p, _val) (*reinterpret_cast<uint16 *>(_p) = (_val))
#define UNALIGNED_STORE32(_p, _val) (*reinterpret_cast<uint32 *>(_p) = (_val))
inline uint64 UNALIGNED_LOAD64(const void *p) {
uint64 t;
memcpy(&t, p, sizeof t);
return t;
}
inline void UNALIGNED_STORE64(void *p, uint64 v) {
memcpy(p, &v, sizeof v);
}
#else
// These functions are provided for architectures that don't support
// unaligned loads and stores.
inline uint16 UNALIGNED_LOAD16(const void *p) {
uint16 t;
memcpy(&t, p, sizeof t);
return t;
}
inline uint32 UNALIGNED_LOAD32(const void *p) {
uint32 t;
memcpy(&t, p, sizeof t);
return t;
}
inline uint64 UNALIGNED_LOAD64(const void *p) {
uint64 t;
memcpy(&t, p, sizeof t);
return t;
}
inline void UNALIGNED_STORE16(void *p, uint16 v) {
memcpy(p, &v, sizeof v);
}
inline void UNALIGNED_STORE32(void *p, uint32 v) {
memcpy(p, &v, sizeof v);
}
inline void UNALIGNED_STORE64(void *p, uint64 v) {
memcpy(p, &v, sizeof v);
}
#endif
class LittleEndian {
public:
#ifdef WORDS_BIGENDIAN
static bool IsLittleEndian() { return false; }
#else // !defined(WORDS_BIGENDIAN)
static bool IsLittleEndian() { return true; }
#endif // !defined(WORDS_BIGENDIAN)
};
// Some bit-manipulation functions.
class Bits {
public:
// Return floor(log2(n)) for positive integer n. Returns -1 iff n == 0.
static int Log2Floor(uint32 n);
// Potentially faster version of Log2Floor() that returns an
// undefined value if n == 0
static int Log2FloorNonZero(uint32 n);
// Return the first set least / most significant bit, 0-indexed. Returns an
// undefined value if n == 0. FindLSBSetNonZero() is similar to ffs() except
// that it's 0-indexed.
static int FindLSBSetNonZero(uint32 n);
static int FindLSBSetNonZero64(uint64 n);
// Return number of bits set to 1
static int CountOnes(uint32 n);
private:
DISALLOW_COPY_AND_ASSIGN(Bits);
};
#ifdef HAVE_BUILTIN_CTZ
inline int Bits::Log2Floor(uint32 n) {
return n == 0 ? -1 : (31 ^ __builtin_clz(n));
}
inline int Bits::Log2FloorNonZero(uint32 n) {
return 31 ^ __builtin_clz(n);
}
inline int Bits::FindLSBSetNonZero(uint32 n) {
return __builtin_ctz(n);
}
inline int Bits::FindLSBSetNonZero64(uint64 n) {
return __builtin_ctzll(n);
}
#else // Portable versions.
inline int Bits::Log2Floor(uint32 n) {
if (n == 0)
return -1;
int log = 0;
uint32 value = n;
for (int i = 4; i >= 0; --i) {
int shift = (1 << i);
uint32 x = value >> shift;
if (x != 0) {
value = x;
log += shift;
}
}
assert(value == 1);
return log;
}
inline int Bits::Log2FloorNonZero(uint32 n) {
return Bits::Log2Floor(n);
}
inline int Bits::FindLSBSetNonZero(uint32 n) {
int rc = 31;
for (int i = 4, shift = 1 << 4; i >= 0; --i) {
const uint32 x = n << shift;
if (x != 0) {
n = x;
rc -= shift;
}
shift >>= 1;
}
return rc;
}
// FindLSBSetNonZero64() is defined in terms of FindLSBSetNonZero().
inline int Bits::FindLSBSetNonZero64(uint64 n) {
const uint32 bottombits = static_cast<uint32>(n);
if (bottombits == 0) {
// Bottom bits are zero, so scan in top bits
return 32 + FindLSBSetNonZero(static_cast<uint32>(n >> 32));
} else {
return FindLSBSetNonZero(bottombits);
}
}
#endif // End portable versions.
inline int Bits::CountOnes(uint32 n) {
n -= ((n >> 1) & 0x55555555);
n = ((n >> 2) & 0x33333333) + (n & 0x33333333);
return (((n + (n >> 4)) & 0xF0F0F0F) * 0x1010101) >> 24;
}
// If you know the internal layout of the std::string in use, you can
// replace this function with one that resizes the string without
// filling the new space with zeros (if applicable) --
// it will be non-portable but faster.
inline void STLStringResizeUninitialized(std::string* s, size_t new_size) {
s->resize(new_size);
}
// Return a mutable char* pointing to a string's internal buffer,
// which may not be null-terminated. Writing through this pointer will
// modify the string.
//
// string_as_array(&str)[i] is valid for 0 <= i < str.size() until the
// next call to a string method that invalidates iterators.
//
// In C++11 you may simply use &str[0] to get a mutable char*.
//
// Prior to C++11, there was no standard-blessed way of getting a mutable
// reference to a string's internal buffer. The requirement that string be
// contiguous is officially part of the C++11 standard [string.require]/5.
inline char* string_as_array(std::string* str) {
return str->empty() ? NULL : &*str->begin();
}
// Return the largest n such that
// s1[0,n-1] == s2[0,n-1]
// and n <= (s2_limit - s2).
//
// Separate implementation for x86_64 and little endian PPC, for speed.
#if (defined(__GNUC__) && (defined(ARCH_K8) \
|| (defined(__ppc64__) && defined(_LITTLE_ENDIAN))))
static inline int FindMatchLength(const uint8* s1,
const uint8* s2,
const uint8* s2_limit) {
int matched = 0;
// Find out how long the match is. We loop over the data 64 bits at a
// time until we find a 64-bit block that doesn't match; then we find
// the first non-matching bit and use that to calculate the total
// length of the match.
while (PREDICT_TRUE(s2 <= s2_limit - 8)) {
if (PREDICT_FALSE(UNALIGNED_LOAD64(s2) == UNALIGNED_LOAD64(s1 + matched))) {
s2 += 8;
matched += 8;
} else {
// On current (mid-2008) Opteron models there is a 3% more
// efficient code sequence to find the first non-matching byte.
// However, what follows is ~10% better on Intel Core 2 and newer,
// and we expect AMD's bsf instruction to improve.
uint64 x = UNALIGNED_LOAD64(s2) ^ UNALIGNED_LOAD64(s1 + matched);
int matching_bits = Bits::FindLSBSetNonZero64(x);
matched += matching_bits >> 3;
return matched;
}
}
while (PREDICT_TRUE(s2 < s2_limit)) {
if (PREDICT_TRUE(s1[matched] == *s2)) {
++s2;
++matched;
} else {
return matched;
}
}
return matched;
}
// Same, but max length limited by an integer. This is a better fit for
// the use in util/compression/flate.
static inline int FindMatchLengthWithLimit(const uint8 *s1, const uint8 *s2,
size_t limit) {
int matched = 0;
size_t limit2 = (limit >> 3) + 1; // + 1 is for pre-decrement in while
while (PREDICT_TRUE(--limit2)) {
if (PREDICT_FALSE(UNALIGNED_LOAD64(s2) == UNALIGNED_LOAD64(s1 + matched))) {
s2 += 8;
matched += 8;
} else {
uint64 x = UNALIGNED_LOAD64(s2) ^ UNALIGNED_LOAD64(s1 + matched);
int matching_bits = Bits::FindLSBSetNonZero64(x);
matched += matching_bits >> 3;
return matched;
}
}
limit = (limit & 7) + 1; // + 1 is for pre-decrement in while
while (--limit) {
if (PREDICT_TRUE(s1[matched] == *s2)) {
++s2;
++matched;
} else {
return matched;
}
}
return matched;
}
#else
static inline int FindMatchLength(const uint8 *s1, const uint8 *s2,
const uint8 *s2_limit) {
int matched = 0;
const uint8 *s2_ptr = s2;
// Find out how long the match is. We loop over the data 32 bits at a
// time until we find a 32-bit block that doesn't match; then we find
// the first non-matching bit and use that to calculate the total
// length of the match.
while (s2_ptr <= s2_limit - 4 &&
UNALIGNED_LOAD32(s2_ptr) == UNALIGNED_LOAD32(s1 + matched)) {
s2_ptr += 4;
matched += 4;
}
while ((s2_ptr < s2_limit) && (s1[matched] == *s2_ptr)) {
++s2_ptr;
++matched;
}
return matched;
}
static inline int FindMatchLengthWithLimit(const uint8 *s1, const uint8 *s2,
size_t limit) {
return FindMatchLength(s1, s2, s2 + limit);
}
#endif
} // namespace compression
} // namespace google
#endif // UTIL_COMPRESSION_GIPFELI_OPENSOURCE_STUBS_INTERNAL_H_
| 30.656331 | 104 | 0.672033 | [
"vector"
] |
1b1d0c26457f6f4c7c1a0f906a1af536122ff250 | 5,994 | h | C | game/common.h | 3107RU/Test-Game | 3c05a8d5eafaf3fb0a3966bb15c054afeaf62a09 | [
"Unlicense"
] | null | null | null | game/common.h | 3107RU/Test-Game | 3c05a8d5eafaf3fb0a3966bb15c054afeaf62a09 | [
"Unlicense"
] | null | null | null | game/common.h | 3107RU/Test-Game | 3c05a8d5eafaf3fb0a3966bb15c054afeaf62a09 | [
"Unlicense"
] | null | null | null | /**
* @file common.h
* @author Alex Light (dev@3107.ru)
* @brief Общие определения для игры
* @version 0.1
* @date 2021-11-28
*/
#pragma once
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <ft2build.h>
#include FT_FREETYPE_H
#include <array>
#include <cmath>
#include <fstream>
#include <iostream>
#include <list>
#include <map>
#include <memory>
#include <random>
#include <regex>
#include <set>
#include <sstream>
#include <vector>
/**
* @brief количество осей игры (в реальности в геометрии используются алгоритмы 2d)
*
*/
constexpr size_t AXES = 2;
/**
* @brief Цвет
*
*/
using Color = std::array<GLfloat, 4>;
/**
* @brief Точка (вектор)
*
*/
using Point = std::array<GLfloat, AXES>;
/**
* @brief Размер
*
*/
using Size = std::array<GLfloat, AXES>;
/**
* @brief Скорость
*
*/
using Speed = Size;
/**
* @brief Сила
*
*/
using Force = Speed;
/**
* @brief Отрезок
*
*/
using Segment = std::array<Point, 2>;
/**
* @brief Треугольник
*
*/
using Triangle = std::array<Point, 3>;
/**
* @brief Прямоугольник
*
*/
using Rect = std::pair<Point, Size>;
/**
* @brief круг
*
*/
using Circle = std::pair<Point, GLfloat>;
/**
* @brief углы сцены
*
*/
using Corners = std::array<Point, 4>;
/**
* @brief размер поля игры
*
*/
constexpr GLfloat gameSize = 1.f;
/**
* @brief допустимая ошибка при сравнении float
*
*/
constexpr GLfloat gameError = 1e-6f;
/**
* @brief ошибка полигона для окружности
*
*/
constexpr GLfloat circleError = 1e-3f;
/**
* @brief углы сцены
*
*/
constexpr Corners corners = {
Point{-gameSize, -gameSize}, Point{gameSize, -gameSize},
Point{gameSize, gameSize}, Point{-gameSize, gameSize}};
/**
* @brief число пи
*
*/
constexpr GLfloat PI = 3.14159265358979323846f;
/**
* @brief задержка между обработкой движений в сек.
*
*/
constexpr double processDelay = .02;
/**
* @brief размер символа текста при создании текстур
*
*/
constexpr FT_UInt textBitmapSize = 64;
/**
* @brief цвет текста
*
*/
constexpr Color scoreColor = {1.f, 1.f, 1.f, 1.f};
/**
* @brief высота текста
*
*/
constexpr GLfloat scoreHeight = gameSize * .07f;
/**
* @brief позиция текста
*
*/
constexpr Point scorePosition = {gameSize * -.98f, gameSize * .93f};
/**
* @brief ускорение спрайта при появлении вектора движения
*
*/
constexpr GLfloat accelerateForce = gameSize * .01f;
/**
* @brief замедление (трение)
*
*/
constexpr GLfloat decelerateForce = gameSize * .001f;
/**
* @brief цвет игрового поля
*
*/
constexpr Color backColor = {1.f, .75f, .5f, 1.0f};
/**
* @brief цвет невидимой части
*
*/
constexpr Color darknessColor = {.5f, .5f, .5f, 1.0f};
/**
* @brief цвет препятствий
*
*/
constexpr Color figureColor = {0.f, 0.f, 1.f, 1.f};
/**
* @brief лимит скорости игрока
*
*/
constexpr GLfloat gamerSpeedLimit = gameSize * .02f;
/**
* @brief псевдо вес игрока (инерционность)
*
*/
constexpr GLfloat gamerWeight = 2.f;
/**
* @brief цвет игрока
*
*/
constexpr Color gamerColor = {1.f, 1.f, 0.f, 1.f};
/**
* @brief радиус игрока
*
*/
constexpr GLfloat gamerRadius = gameSize * .05f;
/**
* @brief цвет приза
*
*/
constexpr Color prizeColor = {0.f, 1.f, 0.f, 1.f};
/**
* @brief размер приза
*
*/
constexpr Size prizeSize = {gameSize * .05f, gameSize * .05f};
/**
* @brief цвет активного зомби
*
*/
constexpr Color zombyActiveColor = {1.f, 0.f, 0.f, 1.f};
/**
* @brief цвет пассивного зомби
*
*/
constexpr Color zombyInactiveColor = {1.f, 0.f, 0.f, .5f};
/**
* @brief ограничение скорости зомби
*
*/
constexpr GLfloat zombySpeedLimit = gameSize * .002f;
/**
* @brief инерция зомби
*
*/
constexpr GLfloat zombyWeight = 20.f;
/**
* @brief размер зомби
*
*/
constexpr Size zombySize = {gameSize * .04f, gameSize * .04f};
/**
* @brief количество зомби
*
*/
constexpr int zombyCount = 3;
/**
* @brief время неактивности зоби после столкновения с игроком в сек.
*
*/
constexpr double sombyInactiveTime = 1.;
/**
* @brief размер области в которой зомби выбирает случайную точку куда идти когда не видит игрока
*
*/
constexpr GLfloat zombyMemoryError = gameSize * .1f;
/**
* @brief на сколько ускоряем зомби в зависимости от очков
*
*/
constexpr GLfloat zombySpeedFromScoreKoef = .001f;
/**
* @brief приблизительное равно для float
*
* @param a float
* @param b float
* @return true
* @return false
*/
inline bool equal(GLfloat a, GLfloat b) {
return std::abs(a - b) <= std::max(std::abs(a), std::abs(b)) * gameError;
}
/**
* @brief Гарантированное меньше для float
*
* @param a float
* @param b float
* @return true
* @return false
*/
inline bool less(GLfloat a, GLfloat b) {
return (b - a) > std::max(std::abs(a), std::abs(b)) * gameError;
}
/**
* @brief примерное равно для вектора
*
* @param a вектор
* @param b вектор
* @return true
* @return false
*/
template <typename T>
bool equal(const T &a, const T &b) {
return equal(a[0], b[0]) && equal(a[1], b[1]);
}
/**
* @brief гарантированное меньше для вектора
*
* @param a вектор
* @param b вектор
* @return true
* @return false
*/
template <typename T>
bool less(const T &a, const T &b) {
return less(a.x, b.x) && less(a.y, b.y);
}
/**
* @brief оператор вычитания векторов
*
* @param u вектор
* @param v вектор
* @return T
*/
template <class T>
T operator-(const T &u, const T &v) {
return T{u[0] - v[0], u[1] - v[1]};
}
/**
* @brief оператор сложения векторов
*
* @param u вектор
* @param v вектор
* @return T
*/
template <class T>
T operator+(const T &u, const T &v) {
return T{u[0] + v[0], u[1] + v[1]};
}
/**
* @brief Оператор умножения вектора на скаляр
*
* @param u вектор
* @param m вектор
* @return T
*/
template <class T>
T operator*(const T &u, GLfloat m) {
return T{u[0] * m, u[1] * m};
}
/**
* @brief оператор умножения векторов
*
* @param u вектор
* @param v вектор
* @return T
*/
template <typename T>
T operator*(const T &u, const T &v) {
return {u[0] * v[0], u[1] * v[1]};
}
| 18.218845 | 97 | 0.627961 | [
"vector"
] |
1b2a4e0444472fa46884405ea75e8b99ed02f1d3 | 2,328 | h | C | chrome/browser/chromeos/accessibility/spoken_feedback_event_rewriter.h | google-ar/chromium | 2441c86a5fd975f09a6c30cddb57dfb7fc239699 | [
"Apache-2.0",
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 777 | 2017-08-29T15:15:32.000Z | 2022-03-21T05:29:41.000Z | chrome/browser/chromeos/accessibility/spoken_feedback_event_rewriter.h | harrymarkovskiy/WebARonARCore | 2441c86a5fd975f09a6c30cddb57dfb7fc239699 | [
"Apache-2.0",
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 66 | 2017-08-30T18:31:18.000Z | 2021-08-02T10:59:35.000Z | chrome/browser/chromeos/accessibility/spoken_feedback_event_rewriter.h | harrymarkovskiy/WebARonARCore | 2441c86a5fd975f09a6c30cddb57dfb7fc239699 | [
"Apache-2.0",
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 123 | 2017-08-30T01:19:34.000Z | 2022-03-17T22:55:31.000Z | // Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CHROME_BROWSER_CHROMEOS_ACCESSIBILITY_SPOKEN_FEEDBACK_EVENT_REWRITER_H_
#define CHROME_BROWSER_CHROMEOS_ACCESSIBILITY_SPOKEN_FEEDBACK_EVENT_REWRITER_H_
#include <vector>
#include "base/macros.h"
#include "content/public/browser/web_contents_delegate.h"
#include "ui/events/event_rewriter.h"
namespace ui {
class KeyEvent;
}
// Receives requests for spoken feedback enabled state and command dispatch.
class SpokenFeedbackEventRewriterDelegate
: public content::WebContentsDelegate {
public:
SpokenFeedbackEventRewriterDelegate();
~SpokenFeedbackEventRewriterDelegate() override {}
// Returns true when ChromeVox is enabled.
virtual bool IsSpokenFeedbackEnabled() const;
// Returns true when |key_event| is dispatched to ChromeVox.
virtual bool DispatchKeyEventToChromeVox(const ui::KeyEvent& key_event,
bool capture);
// WebContentsDelegate:
void HandleKeyboardEvent(
content::WebContents* source,
const content::NativeWebKeyboardEvent& event) override;
private:
DISALLOW_COPY_AND_ASSIGN(SpokenFeedbackEventRewriterDelegate);
};
// SpokenFeedbackEventRewriter discards all keyboard events mapped by the spoken
// feedback manifest commands block. It dispatches the associated command name
// directly to spoken feedback. This only occurs whenever spoken feedback is
// enabled.
class SpokenFeedbackEventRewriter : public ui::EventRewriter {
public:
SpokenFeedbackEventRewriter();
~SpokenFeedbackEventRewriter() override;
void SetDelegateForTest(
std::unique_ptr<SpokenFeedbackEventRewriterDelegate> delegate);
private:
// EventRewriter:
ui::EventRewriteStatus RewriteEvent(
const ui::Event& event,
std::unique_ptr<ui::Event>* new_event) override;
ui::EventRewriteStatus NextDispatchEvent(
const ui::Event& last_event,
std::unique_ptr<ui::Event>* new_event) override;
// Active delegate (used for testing).
std::unique_ptr<SpokenFeedbackEventRewriterDelegate> delegate_;
DISALLOW_COPY_AND_ASSIGN(SpokenFeedbackEventRewriter);
};
#endif // CHROME_BROWSER_CHROMEOS_ACCESSIBILITY_SPOKEN_FEEDBACK_EVENT_REWRITER_H_
| 33.73913 | 82 | 0.781357 | [
"vector"
] |
1e629f2ca5f30c29b5da8a8eb832085917f3ca13 | 330 | h | C | src/glpp/internal/assert_is_bound.h | CoolLibs/glpp | 3936a89e54fd59295dfddb614af9c2873fd0eb6a | [
"MIT"
] | null | null | null | src/glpp/internal/assert_is_bound.h | CoolLibs/glpp | 3936a89e54fd59295dfddb614af9c2873fd0eb6a | [
"MIT"
] | null | null | null | src/glpp/internal/assert_is_bound.h | CoolLibs/glpp | 3936a89e54fd59295dfddb614af9c2873fd0eb6a | [
"MIT"
] | null | null | null | #pragma once
#include <glad/glad.h>
namespace glpp {
namespace internal {
/// Raises an assert if the object bound at pname is not id
/// pname is an enum from this list: http://docs.gl/gl4/glGet
void assert_is_bound(GLenum pname, GLint id, const char* error_message);
} // namespace internal
} // namespace glpp
| 23.571429 | 73 | 0.70303 | [
"object"
] |
1e70ecf1d58bd077f25fa7d533262c6de1197a47 | 8,671 | h | C | VirtualBox-5.0.0/include/iprt/cpp/mem.h | egraba/vbox_openbsd | 6cb82f2eed1fa697d088cecc91722b55b19713c2 | [
"MIT"
] | 1 | 2015-04-30T14:18:45.000Z | 2015-04-30T14:18:45.000Z | VirtualBox-5.0.0/include/iprt/cpp/mem.h | egraba/vbox_openbsd | 6cb82f2eed1fa697d088cecc91722b55b19713c2 | [
"MIT"
] | null | null | null | VirtualBox-5.0.0/include/iprt/cpp/mem.h | egraba/vbox_openbsd | 6cb82f2eed1fa697d088cecc91722b55b19713c2 | [
"MIT"
] | null | null | null | /** @file
* IPRT - C++ Memory Resource Management.
*/
/*
* Copyright (C) 2006-2015 Oracle Corporation
*
* This file is part of VirtualBox Open Source Edition (OSE), as
* available from http://www.virtualbox.org. This file is free software;
* you can redistribute it and/or modify it under the terms of the GNU
* General Public License (GPL) as published by the Free Software
* Foundation, in version 2 as it comes in the "COPYING" file of the
* VirtualBox OSE distribution. VirtualBox OSE is distributed in the
* hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
*
* The contents of this file may alternatively be used under the terms
* of the Common Development and Distribution License Version 1.0
* (CDDL) only, as it comes in the "COPYING.CDDL" file of the
* VirtualBox OSE distribution, in which case the provisions of the
* CDDL are applicable instead of those of the GPL.
*
* You may elect to license modified versions of this file under the
* terms and conditions of either the GPL or the CDDL or both.
*/
#ifndef ___iprt_cpp_mem_h
#define ___iprt_cpp_mem_h
#include <iprt/cpp/autores.h>
#include <iprt/assert.h>
#include <iprt/mem.h>
#include <iprt/string.h> /* for memset */
/** @defgroup grp_rt_cpp_autores_mem C++ Memory Resource Management
* @ingroup grp_rt_cpp_autores
* @{
*/
/**
* Template function wrapping RTMemFree to get the correct a_fnDestruct
* signature for RTCAutoRes.
*
* We can't use a more complex template here, because the g++ on RHEL 3
* chokes on it with an internal compiler error.
*
* @tparam T The data type that's being managed.
* @param aMem Pointer to the memory that should be free.
*/
template <class T>
inline void RTCMemAutoDestructor(T *aMem) RT_NO_THROW
{
RTMemFree(aMem);
}
/**
* RTCMemAutoPtr allocator which uses RTMemTmpAlloc().
*
* @returns Allocated memory on success, NULL on failure.
* @param pvOld What to reallocate, shall always be NULL.
* @param cbNew The amount of memory to allocate (in bytes).
*/
inline void *RTCMemTmpAutoAllocator(void *pvOld, size_t cbNew) RT_NO_THROW
{
AssertReturn(!pvOld, NULL);
return RTMemTmpAlloc(cbNew);
}
/**
* Template function wrapping RTMemTmpFree to get the correct a_fnDestruct
* signature for RTCAutoRes.
*
* We can't use a more complex template here, because the g++ on RHEL 3
* chokes on it with an internal compiler error.
*
* @tparam T The data type that's being managed.
* @param aMem Pointer to the memory that should be free.
*/
template <class T>
inline void RTCMemTmpAutoDestructor(T *aMem) RT_NO_THROW
{
RTMemTmpFree(aMem);
}
/**
* Template function wrapping RTMemEfFree to get the correct a_fnDestruct
* signature for RTCAutoRes.
*
* We can't use a more complex template here, because the g++ on RHEL 3
* chokes on it with an internal compiler error.
*
* @tparam T The data type that's being managed.
* @param aMem Pointer to the memory that should be free.
*/
template <class T>
inline void RTCMemEfAutoFree(T *aMem) RT_NO_THROW
{
RTMemEfFreeNP(aMem);
}
/**
* Template function wrapping NULL to get the correct NilRes signature
* for RTCAutoRes.
*
* @tparam T The data type that's being managed.
* @returns NULL with the right type.
*/
template <class T>
inline T *RTCMemAutoNil(void) RT_NO_THROW
{
return (T *)(NULL);
}
/**
* An auto pointer-type template class for managing memory allocating
* via C APIs like RTMem (the default).
*
* The main purpose of this class is to automatically free memory that
* isn't explicitly used (release()'ed) when the object goes out of scope.
*
* As an additional service it can also make the allocations and
* reallocations for you if you like, but it can also take of memory
* you hand it.
*
* @tparam T The data type to manage allocations for.
* @tparam a_fnDestruct The function to be used to free the resource.
* This will default to RTMemFree.
* @tparam a_fnAllocator The function to be used to allocate or reallocate
* the managed memory.
* This is standard realloc() like stuff, so it's
* possible to support simple allocation without
* actually having to support reallocating memory if
* that's a problem. This will default to
* RTMemRealloc.
*/
template <class T,
void a_fnDestruct(T *) = RTCMemAutoDestructor<T>,
# if defined(RTMEM_WRAP_TO_EF_APIS) && !defined(RTMEM_NO_WRAP_TO_EF_APIS)
void *a_fnAllocator(void *, size_t, const char *) = RTMemEfReallocNP
# else
void *a_fnAllocator(void *, size_t, const char *) = RTMemReallocTag
# endif
>
class RTCMemAutoPtr
: public RTCAutoRes<T *, a_fnDestruct, RTCMemAutoNil<T> >
{
public:
/**
* Constructor.
*
* @param aPtr Memory pointer to manage. Defaults to NULL.
*/
RTCMemAutoPtr(T *aPtr = NULL)
: RTCAutoRes<T *, a_fnDestruct, RTCMemAutoNil<T> >(aPtr)
{
}
/**
* Constructor that allocates memory.
*
* @param a_cElements The number of elements (of the data type) to allocate.
* @param a_fZeroed Whether the memory should be memset with zeros after
* the allocation. Defaults to false.
*/
RTCMemAutoPtr(size_t a_cElements, bool a_fZeroed = false)
: RTCAutoRes<T *, a_fnDestruct, RTCMemAutoNil<T> >((T *)a_fnAllocator(NULL, a_cElements * sizeof(T), RTMEM_TAG))
{
if (a_fZeroed && RT_LIKELY(this->get() != NULL))
memset(this->get(), '\0', a_cElements * sizeof(T));
}
/**
* Free current memory and start managing aPtr.
*
* @param aPtr Memory pointer to manage.
*/
RTCMemAutoPtr &operator=(T *aPtr)
{
this->RTCAutoRes<T *, a_fnDestruct, RTCMemAutoNil<T> >::operator=(aPtr);
return *this;
}
/**
* Dereference with * operator.
*/
T &operator*()
{
return *this->get();
}
/**
* Dereference with -> operator.
*/
T *operator->()
{
return this->get();
}
/**
* Accessed with the subscript operator ([]).
*
* @returns Reference to the element.
* @param a_i The element to access.
*/
T &operator[](size_t a_i)
{
return this->get()[a_i];
}
/**
* Allocates memory and start manage it.
*
* Any previously managed memory will be freed before making
* the new allocation.
*
* @returns Success indicator.
* @retval true if the new allocation succeeds.
* @retval false on failure, no memory is associated with the object.
*
* @param a_cElements The number of elements (of the data type) to allocate.
* This defaults to 1.
* @param a_fZeroed Whether the memory should be memset with zeros after
* the allocation. Defaults to false.
*/
bool alloc(size_t a_cElements = 1, bool a_fZeroed = false)
{
this->reset(NULL);
T *pNewMem = (T *)a_fnAllocator(NULL, a_cElements * sizeof(T), RTMEM_TAG);
if (a_fZeroed && RT_LIKELY(pNewMem != NULL))
memset(pNewMem, '\0', a_cElements * sizeof(T));
this->reset(pNewMem);
return pNewMem != NULL;
}
/**
* Reallocate or allocates the memory resource.
*
* Free the old value if allocation fails.
*
* The content of any additional memory that was allocated is
* undefined when using the default allocator.
*
* @returns Success indicator.
* @retval true if the new allocation succeeds.
* @retval false on failure, no memory is associated with the object.
*
* @param a_cElements The new number of elements (of the data type) to
* allocate. The size of the allocation is the number of
* elements times the size of the data type - this is
* currently what's passed down to the a_fnAllocator.
* This defaults to 1.
*/
bool realloc(size_t a_cElements = 1)
{
T *aNewValue = (T *)a_fnAllocator(this->get(), a_cElements * sizeof(T), RTMEM_TAG);
if (RT_LIKELY(aNewValue != NULL))
this->release();
/* We want this both if aNewValue is non-NULL and if it is NULL. */
this->reset(aNewValue);
return aNewValue != NULL;
}
};
/** @} */
#endif
| 31.878676 | 120 | 0.632799 | [
"object"
] |
1e74ef054b16447a1deec810857c98d0d14b6946 | 676 | h | C | LonelyPlaneteer/LonelyPlaneteer/LoadingScene.h | simonlthorp/LonelyPlaneteer | 0fde07347fc231720980f0a1e39c23acc974ab50 | [
"Apache-2.0"
] | null | null | null | LonelyPlaneteer/LonelyPlaneteer/LoadingScene.h | simonlthorp/LonelyPlaneteer | 0fde07347fc231720980f0a1e39c23acc974ab50 | [
"Apache-2.0"
] | null | null | null | LonelyPlaneteer/LonelyPlaneteer/LoadingScene.h | simonlthorp/LonelyPlaneteer | 0fde07347fc231720980f0a1e39c23acc974ab50 | [
"Apache-2.0"
] | null | null | null | #pragma once
#ifndef LoadingScene_h
#define LoadingScene_h
#include "SDL.h"
#include "SDL_image.h"
#include "SDL_ttf.h"
#include <stdio.h>
#include <iostream>
class LoadingScene {
public:
LoadingScene();
~LoadingScene();
void init();
void handleEvents();
void update();
void render();
private:
void incrementCounter();
SDL_Rect srcCircle, destCircle;
SDL_Rect srcBackground, destBackground;
SDL_Texture *circle1, *circle2, *circle3, *circle4, *circle5, *circle6, *circle7, *circle8, *circle9, *circle10, *circle11, *background;
int circle1Counter = 0, circle2Counter = 0, circle3Counter = 0, circle4Counter = 0, circle5Counter = 0, circle6Counter = 0;
};
#endif | 24.142857 | 137 | 0.738166 | [
"render"
] |
1e7daa3454d55d9564ffa68dd197b3bac79c0aeb | 7,490 | h | C | PWGLF/RESONANCES/AliRsnCutSetDaughterParticle.h | ilyafokin/AliPhysics | 7a0021a9d7ad4f0a9e52e0a13f9d3ca3b74c63d4 | [
"BSD-3-Clause"
] | 1 | 2020-07-18T17:36:58.000Z | 2020-07-18T17:36:58.000Z | PWGLF/RESONANCES/AliRsnCutSetDaughterParticle.h | ilyafokin/AliPhysics | 7a0021a9d7ad4f0a9e52e0a13f9d3ca3b74c63d4 | [
"BSD-3-Clause"
] | null | null | null | PWGLF/RESONANCES/AliRsnCutSetDaughterParticle.h | ilyafokin/AliPhysics | 7a0021a9d7ad4f0a9e52e0a13f9d3ca3b74c63d4 | [
"BSD-3-Clause"
] | 1 | 2022-01-24T11:11:09.000Z | 2022-01-24T11:11:09.000Z | #ifndef ALIRSNCUTSETDAUGHTERPARTICLE_H
#define ALIRSNCUTSETDAUGHTERPARTICLE_H
//
// Cuts collection for selecting good daughter candidates for rsn analysis
//Requires:
// 1) choice of existing cuts among the enum list
// 2) PID ipothesis for the daughter particle
//
// Author: Francesca Bellini (fbellini@cern.ch)
//
#include "AliVTrack.h"
#include "AliRsnCut.h"
#include "AliRsnCutSet.h"
#include "AliRsnCutTrackQuality.h"
#include "AliRsnCutPIDNSigma.h"
#include "AliRsnCutTOFMatch.h"
#include "AliRsnCutPhi.h"
class AliRsnCutSetDaughterParticle : public AliRsnCutSet {
public:
enum ERsnDaughterCutSet {
kNoCuts,
kQualityStd2010, //quality only
kQualityStd2011,
kQualityStd2011HighPt,
kQualityStd2010TRD, //checks on TRD
kQualityStd2010NoTRD,
kTOFMatch, //TOF match
kTOFMatchTRD2010,
kTOFMatchNoTRD2010,
kTOFMatchPPB2011,
kFastTPCpidNsigma, //basic TPC PID cut without pT dependence
kFastTOFpidNsigma, //basic TOF PID cut without pT dependence
kTPCTOFpidKstarPP2010, //cuts for PbPb analysis
kTOFpidKstarPbPb2010,
kTOFTPCmismatchKstarPbPb2010,
kTOFpidKstarPbPbTRD2010,
kTOFpidKstarPbPbNoTRD2010,
kTOFMatchTPCpidNsigma, //basic TPC PID with TOF veto
kTPCpidKstarPPB2011, //vuts for pPb analysis
kTOFpidKstarPPB2011,
kTPCTOFpidKstarPPB2011,
kTPCTOFtightPidKStarPPB2011, //TPC 2.0 (3.0) sigma pid & TOF at 3.0 (5.0) sigma
kTPCpidMatchPPB2011, //Match with nsigma = fNsigmaTPC
kTPCpidTOFveto4s, //TPC n sigma + 4.0 sigma TOF veto
kTPCpidTOFveto3s, //TPC n sigma + 3.0 sigma TOF veto
kCombinedPidBestPtDep, //combined TPC-TOF cut
kTPCPidPtDep, //basic PID cuts with pt dependence
kTOFPidPtDep,
kTPCRejPtDepTOFNsigma,
kTPCNsigmaTOFVetoPtDep,
kTPCTOFpidLstar, //cuts for L* in pPb
kTPCTOFpidLstar13ppTeV, // cuts for L* pp 13 tev
kTPCTOFpidLstar13ppTeV_test, // cuts for L* pp 13 tev
kTPCTOFpidLstar13ppTeV_test1, // cuts for L* pp 13 tev with 3 sigma TOF veto
kTPCTOFpidLstar13ppTeV_test2, // cuts for L* pp 13 tev with eRej and 3 sigma TOF veto
kTPCTOFpidLstar13ppTeVERejection, // cuts for L* pp 13 tev with e rejection
kTPCTOFpidLstarPbPb2011, //cuts for L* in PbPb
kTPCTOFpidLstarPbPb2011elRej,//cuts for L* in AA with electron rejection
kTPCTOFpidphipp2015,//TPC+TOF cuts for phi in pp 13 TeV (LHC15f)
kTPCTOFpidphikstarpPb2016,//TPC+TOF cuts for phi and kstar in p-Pb 8.16 TeV (LHC16r)
kTPCpidphipp2015,//TPC cuts for phi in pp 13 TeV (LHC15f)
kTPCTOFpidTunedPbPbTOFveto, // Pb-Pb cuts tuned for Pb-Pb 2010/2011 (TOF veto)
kTPCTOFpidTunedPbPbTOFneed, // Pb-Pb cuts tuned for Pb-Pb 2010/2011 (TOF needed)
kTPCTOFpidTunedPbPbTOFneed_2018, // Pb-Pb cuts tuned for Pb-Pb 2010/2011 (TOF needed)
kTOFTPCpidKstar, //cuts for Kstar
kTOFTPCpidDelta, //cuts for Delta
kTOFTPCpidLstar, //cuts for Lstar
kTPCTOFvetoPhiXeXe, // Pb-Pb cuts tuned for Xe-Xe 2017 with TOF veto & mismatch rejection
kTPCTOFvetoElRejPhiXeXe, // Pb-Pb cuts tuned for Xe-Xe 2017 with electron rejection
kTPCTOFPhiXeXe, // Pb-Pb cuts tuned for Xe-Xe 2017 with TOF veto & strict TPC
kNDaughterCuts
};
enum ECustomQualityCuts {
kDisableCustom = -1,
kFilterBitCustom,
kStdLooserDCAXY,
kStdLooserDCAZ,
kStdCrossedRows60,
kStdCrossedRows80,
kStdRowsToCls075,
kStdRowsToCls085,
kStdCls70,
kStdChi2TPCCls35,
kStdUseTPCNcls,
kNcustomQualityCuts
};
AliRsnCutSetDaughterParticle();
AliRsnCutSetDaughterParticle(const char *name,
AliRsnCutSetDaughterParticle::ERsnDaughterCutSet cutSetID,
AliPID::EParticleType pid,
Float_t nsigmaFast,
Int_t AODfilterBit,
Bool_t useTPCCrossedRows);
AliRsnCutSetDaughterParticle(const char *name,
AliRsnCutSetDaughterParticle::ERsnDaughterCutSet cutSetID,
AliPID::EParticleType pid,
Float_t nsigmaFastTPC,
Float_t nsigmaFastTOF,
Int_t AODfilterBit,
Bool_t useTPCCrossedRows);
AliRsnCutSetDaughterParticle(const char *name,
AliRsnCutTrackQuality *rsnTrackQualityCut,
AliRsnCutSetDaughterParticle::ERsnDaughterCutSet cutSetID,
AliPID::EParticleType pid,
Float_t nSigmaFast);
AliRsnCutSetDaughterParticle(const char *name,
AliRsnCutTrackQuality *rsnTrackQualityCut,
AliRsnCutSetDaughterParticle::ERsnDaughterCutSet cutSetID,
AliPID::EParticleType pid,
Float_t nsigmaFastTPC,
Float_t nsigmaFastTOF);
AliRsnCutSetDaughterParticle(const AliRsnCutSetDaughterParticle ©);
AliRsnCutSetDaughterParticle &operator=(const AliRsnCutSetDaughterParticle ©);
virtual ~AliRsnCutSetDaughterParticle();
void Init();
void InitStdQualityCuts(Bool_t useTPCCrossedRows=kTRUE);
void SetNsigmaForFastTPCpid(Float_t nsigma) {fNsigmaTPC=nsigma; return;};
void SetNsigmaForFastTOFpid(Float_t nsigma) {fNsigmaTOF=nsigma; return;};
void SetAODTrackCutFilterBit(Int_t ibit) {fAODTrkCutFilterBit=ibit; return;}
void SetUseFilterBitOnly(Bool_t useFilterBitOnly=kTRUE) {fCheckOnlyFilterBit=useFilterBitOnly; return;}
void EnableCustomCuts(Bool_t useCustom=kFALSE) {fUseCustomQualityCuts=useCustom; return;}
void SetPtRange(Double_t a, Double_t b) {fPtRange[0] = TMath::Min(a, b); fPtRange[1] = TMath::Max(a, b); return;}
void SetEtaRange(Double_t a, Double_t b) {fEtaRange[0] = TMath::Min(a, b); fEtaRange[1] = TMath::Max(a, b); return;}
void SetUse2011StdQualityCuts(Bool_t use2011=kFALSE) {fIsUse2011stdQualityCuts=use2011; return;}
void SetUse2011StdQualityCutsHighPt(Bool_t use2011HighPt=kFALSE) {fIsUse2011stdQualityCutsHighPt=use2011HighPt; return;}
//getters
const char *GetAppliedDaughterCutSetName() { return GetName();}
Int_t GetAppliedDaughterCutSetId() { return fAppliedCutSetID;}
const AliRsnCutTrackQuality *GetQualityCut() {return fCutQuality;};
void PrintTrackQualityCuts();
private:
AliPID::EParticleType fPID; // PID for track
AliRsnCutSetDaughterParticle::ERsnDaughterCutSet fAppliedCutSetID; // ID of applied cut
Float_t fNsigmaTPC; // number of TPC sigmas for fast pid cut only
Float_t fNsigmaTOF; // number of TOF sigmas for fast pid cut only
AliRsnCutTrackQuality *fCutQuality; //pointer to quality cut object
Int_t fAODTrkCutFilterBit; //AOD filter bit for track cuts
Bool_t fCheckOnlyFilterBit; //flag to use only filter bit cut
Bool_t fUseCustomQualityCuts; //flag to enable the usage of custom quality cuts
Float_t fPtRange[2]; //single track pt range (min, max)
Float_t fEtaRange[2]; //single track eta range (min, max)
Bool_t fIsUse2011stdQualityCuts;//flag to enalble std quality cuts 2011
Bool_t fIsUse2011stdQualityCutsHighPt;//flag to enalble std quality cuts 2011
ClassDef(AliRsnCutSetDaughterParticle, 5) // cut definitions for K*
};
#endif
| 45.95092 | 135 | 0.691589 | [
"object"
] |
1e823db0a1c3b77d0f28da036f1c8c5580996160 | 1,557 | h | C | TAO/tao/Utils/Encodable.h | cflowe/ACE | 5ff60b41adbe1772372d1a43bcc1f2726ff8f810 | [
"DOC"
] | 36 | 2015-01-10T07:27:33.000Z | 2022-03-07T03:32:08.000Z | TAO/tao/Utils/Encodable.h | cflowe/ACE | 5ff60b41adbe1772372d1a43bcc1f2726ff8f810 | [
"DOC"
] | 2 | 2018-08-13T07:30:51.000Z | 2019-02-25T03:04:31.000Z | TAO/tao/Utils/Encodable.h | cflowe/ACE | 5ff60b41adbe1772372d1a43bcc1f2726ff8f810 | [
"DOC"
] | 38 | 2015-01-08T14:12:06.000Z | 2022-01-19T08:33:00.000Z | // -*- C++ -*-
//=============================================================================
/**
* @file Encodable.h
*
* $Id: Encodable.h 71473 2006-03-10 07:19:20Z jtc $
*
* Defines the interface for classes that wish to be
* encodable/decodable into/from a CDR representation.
*
* @author Angelo Corsaro <corsaro@cs.wustl.edu>
*/
//=============================================================================
#ifndef TAO_ENCODABLE_H_
#define TAO_ENCODABLE_H_
#include /**/ "ace/pre.h"
#include "tao/Basic_Types.h"
#if !defined (ACE_LACKS_PRAGMA_ONCE)
# pragma once
#endif /* ACE_LACKS_PRAGMA_ONCE */
#include "tao/Utils/utils_export.h"
TAO_BEGIN_VERSIONED_NAMESPACE_DECL
class TAO_OutputCDR;
class TAO_InputCDR;
/**
* @class TAO_Encodable
*
* @brief TAO_Encodable Interface
*
* This interface should be inherited by classes that wish to be
* encoded/decoded into/from a CDR stream. Implementation of the
* streaming methods is deferred to the subclasses.
*/
class TAO_UTILS_Export TAO_Encodable
{
public:
virtual ~TAO_Encodable (void);
/// Encodes the object implementing this method into a CDR stream.
/// Returns true on success and false on failure.
virtual CORBA::Boolean _tao_encode (TAO_OutputCDR &out_cdr) = 0;
/// Decodes the object implementing this method from a CDR stream.
/// Returns true on success and false on failure.
virtual CORBA::Boolean _tao_decode (TAO_InputCDR &in_cdr) = 0;
};
TAO_END_VERSIONED_NAMESPACE_DECL
#include /**/ "ace/post.h"
#endif /* TAO_ENCODABLE_H_ */
| 24.714286 | 79 | 0.649968 | [
"object"
] |
1e8889d275ec274d8a6b9978d31178fa5dedb058 | 3,256 | h | C | DataCollector/mozilla/xulrunner-sdk/include/nsICommandLineHandler.h | andrasigneczi/TravelOptimiser | b08805f97f0823fd28975a36db67193386aceb22 | [
"Apache-2.0"
] | 1 | 2016-04-20T08:35:44.000Z | 2016-04-20T08:35:44.000Z | DataCollector/mozilla/xulrunner-sdk/include/nsICommandLineHandler.h | andrasigneczi/TravelOptimiser | b08805f97f0823fd28975a36db67193386aceb22 | [
"Apache-2.0"
] | null | null | null | DataCollector/mozilla/xulrunner-sdk/include/nsICommandLineHandler.h | andrasigneczi/TravelOptimiser | b08805f97f0823fd28975a36db67193386aceb22 | [
"Apache-2.0"
] | null | null | null | /*
* DO NOT EDIT. THIS FILE IS GENERATED FROM ../../../dist/idl\nsICommandLineHandler.idl
*/
#ifndef __gen_nsICommandLineHandler_h__
#define __gen_nsICommandLineHandler_h__
#ifndef __gen_nsISupports_h__
#include "nsISupports.h"
#endif
/* For IDL files that don't want to include root IDL files. */
#ifndef NS_NO_VTABLE
#define NS_NO_VTABLE
#endif
class nsICommandLine; /* forward declaration */
/* starting interface: nsICommandLineHandler */
#define NS_ICOMMANDLINEHANDLER_IID_STR "d4b123df-51ee-48b1-a663-002180e60d3b"
#define NS_ICOMMANDLINEHANDLER_IID \
{0xd4b123df, 0x51ee, 0x48b1, \
{ 0xa6, 0x63, 0x00, 0x21, 0x80, 0xe6, 0x0d, 0x3b }}
class NS_NO_VTABLE nsICommandLineHandler : public nsISupports {
public:
NS_DECLARE_STATIC_IID_ACCESSOR(NS_ICOMMANDLINEHANDLER_IID)
/* void handle (in nsICommandLine aCommandLine); */
NS_IMETHOD Handle(nsICommandLine *aCommandLine) = 0;
/* readonly attribute AUTF8String helpInfo; */
NS_IMETHOD GetHelpInfo(nsACString & aHelpInfo) = 0;
};
NS_DEFINE_STATIC_IID_ACCESSOR(nsICommandLineHandler, NS_ICOMMANDLINEHANDLER_IID)
/* Use this macro when declaring classes that implement this interface. */
#define NS_DECL_NSICOMMANDLINEHANDLER \
NS_IMETHOD Handle(nsICommandLine *aCommandLine) override; \
NS_IMETHOD GetHelpInfo(nsACString & aHelpInfo) override;
/* Use this macro to declare functions that forward the behavior of this interface to another object. */
#define NS_FORWARD_NSICOMMANDLINEHANDLER(_to) \
NS_IMETHOD Handle(nsICommandLine *aCommandLine) override { return _to Handle(aCommandLine); } \
NS_IMETHOD GetHelpInfo(nsACString & aHelpInfo) override { return _to GetHelpInfo(aHelpInfo); }
/* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */
#define NS_FORWARD_SAFE_NSICOMMANDLINEHANDLER(_to) \
NS_IMETHOD Handle(nsICommandLine *aCommandLine) override { return !_to ? NS_ERROR_NULL_POINTER : _to->Handle(aCommandLine); } \
NS_IMETHOD GetHelpInfo(nsACString & aHelpInfo) override { return !_to ? NS_ERROR_NULL_POINTER : _to->GetHelpInfo(aHelpInfo); }
#if 0
/* Use the code below as a template for the implementation class for this interface. */
/* Header file */
class nsCommandLineHandler : public nsICommandLineHandler
{
public:
NS_DECL_ISUPPORTS
NS_DECL_NSICOMMANDLINEHANDLER
nsCommandLineHandler();
private:
~nsCommandLineHandler();
protected:
/* additional members */
};
/* Implementation file */
NS_IMPL_ISUPPORTS(nsCommandLineHandler, nsICommandLineHandler)
nsCommandLineHandler::nsCommandLineHandler()
{
/* member initializers and constructor code */
}
nsCommandLineHandler::~nsCommandLineHandler()
{
/* destructor code */
}
/* void handle (in nsICommandLine aCommandLine); */
NS_IMETHODIMP nsCommandLineHandler::Handle(nsICommandLine *aCommandLine)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* readonly attribute AUTF8String helpInfo; */
NS_IMETHODIMP nsCommandLineHandler::GetHelpInfo(nsACString & aHelpInfo)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* End of implementation class template. */
#endif
#endif /* __gen_nsICommandLineHandler_h__ */
| 30.716981 | 130 | 0.755221 | [
"object"
] |
1e88ca477639abba20f3556ece290be8c6b8eb40 | 958 | h | C | wznmcmbd/WznmPrctree/WznmPrctreeExtract.h | mpsitech/wznm-WhizniumSBE | 4911d561b28392d485c46e98fb915168d82b3824 | [
"MIT"
] | 3 | 2020-09-20T16:24:48.000Z | 2021-12-01T19:44:51.000Z | wznmcmbd/WznmPrctree/WznmPrctreeExtract.h | mpsitech/wznm-WhizniumSBE | 4911d561b28392d485c46e98fb915168d82b3824 | [
"MIT"
] | null | null | null | wznmcmbd/WznmPrctree/WznmPrctreeExtract.h | mpsitech/wznm-WhizniumSBE | 4911d561b28392d485c46e98fb915168d82b3824 | [
"MIT"
] | null | null | null | /**
* \file WznmPrctreeExtract.h
* Wznm operation processor - extract from file tree into extract file tree (declarations)
* \copyright (C) 2016-2020 MPSI Technologies GmbH
* \author Alexander Wirthmueller (auto-generation)
* \date created: 28 Nov 2020
*/
// IP header --- ABOVE
#ifndef WZNMPRCTREEEXTRACT_H
#define WZNMPRCTREEEXTRACT_H
#include "WznmPrctree.h"
// IP include.cust --- INSERT
namespace WznmPrctreeExtract {
DpchRetWznmPrctreeExtract* run(XchgWznm* xchg, DbsWznm* dbswznm, DpchInvWznmPrctreeExtract* dpchinv);
// IP cust --- IBEGIN
bool scanFolder(const std::string& tmppath, const std::string& infolder, const std::string& extfolder, std::fstream& logfi);
bool scanFile(const std::string& tmppath, const std::string& infile, const std::string& extfile, std::fstream& logfi);
void writeExtfile(const std::string& tmppath, const std::string& extfile, const std::vector<WznmPrctree::Ip*>& ips);
// IP cust --- IEND
};
#endif
| 33.034483 | 125 | 0.740084 | [
"vector"
] |
1e8bed1462c4f7dac003f01b53760d12a9163406 | 11,768 | h | C | FTP/FTPClient.h | sikkey/ftpcmd | 42cbd5f40458b526948d9cf43e589b58b4a4b06b | [
"MIT"
] | null | null | null | FTP/FTPClient.h | sikkey/ftpcmd | 42cbd5f40458b526948d9cf43e589b58b4a4b06b | [
"MIT"
] | null | null | null | FTP/FTPClient.h | sikkey/ftpcmd | 42cbd5f40458b526948d9cf43e589b58b4a4b06b | [
"MIT"
] | 1 | 2021-03-24T15:07:39.000Z | 2021-03-24T15:07:39.000Z | /*
* @file FTPClient.h
* @brief libcurl wrapper for FTP requests
*
* @author Mohamed Amine Mzoughi <mohamed-amine.mzoughi@laposte.net>
* @date 2017-01-17
*/
#ifndef INCLUDE_FTPCLIENT_H_
#define INCLUDE_FTPCLIENT_H_
#define FTPCLIENT_VERSION "FTPCLIENT_VERSION_1.0.0"
#include <curl/curl.h>
#include <algorithm>
#include <atomic>
#include <cstddef> // std::size_t
#include <cstdio> // snprintf
#include <cstdlib>
#include <cstring> // strerror, strlen, memcpy, strcpy
#include <ctime>
#ifndef LINUX
#include <direct.h> // mkdir
#endif
#include <stdarg.h> // va_start, etc.
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fstream>
#include <functional>
#include <iostream>
#include <memory> // std::unique_ptr
#include <mutex>
#include <sstream>
#include <string>
#include <vector>
#include "CurlHandle.h"
namespace embeddedmz {
class CFTPClient {
public:
// Public definitions
using ProgressFnCallback = std::function<int(void *, double, double, double, double)>;
using LogFnCallback = std::function<void(const std::string &)>;
// Used to download many items at once
struct WildcardTransfersCallbackData {
std::ofstream ofsOutput;
std::string strOutputPath;
std::vector<std::string> vecDirList;
// will be used to call GetWildcard recursively to download subdirectories
// content...
};
// Progress Function Data Object - parameter void* of ProgressFnCallback
// references it
struct ProgressFnStruct {
ProgressFnStruct() : dLastRunTime(0), pCurl(nullptr), pOwner(nullptr) {}
double dLastRunTime;
CURL *pCurl;
/* owner of the CFTPClient object. can be used in the body of the progress
* function to send signals to the owner (e.g. to update a GUI's progress
* bar)
*/
void *pOwner;
};
// See Info method.
struct FileInfo {
time_t tFileMTime;
double dFileSize;
};
enum SettingsFlag {
NO_FLAGS = 0x00,
ENABLE_LOG = 0x01,
ENABLE_SSH = 0x02, // only for SFTP
ALL_FLAGS = 0xFF
};
enum class FTP_PROTOCOL : unsigned char {
// These three protocols below should not be confused with the SFTP
// protocol. SFTP is an entirely different file transfer protocol
// that runs over SSH2.
FTP, // Plain, unencrypted FTP that defaults over port 21. Most web browsers
// support basic FTP.
FTPS, /* Implicit SSL/TLS encrypted FTP that works just like HTTPS.
* Security is enabled with SSL as soon as the connection starts.
* The default FTPS port is 990. This protocol was the first version
* of encrypted FTP available, and while considered deprecated, is
* still widely used. None of the major web browsers support FTPS. */
FTPES, /* Explicit FTP over SSL/TLS. This starts out as plain FTP over port
* 21, but through special FTP commands is upgraded to TLS/SSL
* encryption. This upgrade usually occurs before the user
* credentials are sent over the connection. FTPES is a somewhat
* newer form of encrypted FTP (although still over a decade old),
* and is considered the preferred way to establish encrypted
* connections because it can be more firewall friendly. None of the
* major web browsers support FTPES. */
SFTP
};
/* Please provide your logger thread-safe routine, otherwise, you can turn off
* error log messages printing by not using the flag ALL_FLAGS or ENABLE_LOG
*/
explicit CFTPClient(LogFnCallback oLogger = [](const std::string &) {});
virtual ~CFTPClient();
// copy constructor and assignment operator are disabled
CFTPClient(const CFTPClient &) = delete;
CFTPClient &operator=(const CFTPClient &) = delete;
// allow constructor and assignment operator are disabled
CFTPClient(CFTPClient &&) = delete;
CFTPClient &operator=(CFTPClient &&) = delete;
// Setters - Getters (for unit tests)
void SetProgressFnCallback(void *pOwner, const ProgressFnCallback &fnCallback);
void SetProxy(const std::string &strProxy);
inline void SetTimeout(const int &iTimeout) { m_iCurlTimeout = iTimeout; }
inline void SetActive(const bool &bEnable) { m_bActive = bEnable; }
inline void SetNoSignal(const bool &bNoSignal) { m_bNoSignal = bNoSignal; }
inline auto GetProgressFnCallback() const { return m_fnProgressCallback.target<int (*)(void *, double, double, double, double)>(); }
inline void *GetProgressFnCallbackOwner() const { return m_ProgressStruct.pOwner; }
inline const std::string &GetProxy() const { return m_strProxy; }
inline const int GetTimeout() const { return m_iCurlTimeout; }
inline const unsigned GetPort() const { return m_uPort; }
inline const bool GetActive() { return m_bActive; }
inline const bool GetNoSignal() const { return m_bNoSignal; }
inline const std::string &GetURL() const { return m_strServer; }
inline const std::string &GetUsername() const { return m_strUserName; }
inline const std::string &GetPassword() const { return m_strPassword; }
inline const unsigned char GetSettingsFlags() const { return m_eSettingsFlags; }
inline const FTP_PROTOCOL GetProtocol() const { return m_eFtpProtocol; }
// Session
const bool InitSession(const std::string &strHost, const unsigned &uPort, const std::string &strLogin, const std::string &strPassword,
const FTP_PROTOCOL &eFtpProtocol = FTP_PROTOCOL::FTP, const SettingsFlag &SettingsFlags = ALL_FLAGS);
virtual const bool CleanupSession();
const CURL *GetCurlPointer() const { return m_pCurlSession; }
// FTP requests
const bool CreateDir(const std::string &strNewDir) const;
const bool RemoveDir(const std::string &strDir) const;
const bool RemoveFile(const std::string &strRemoteFile) const;
/* Checks a single file's size and mtime from an FTP server */
const bool Info(const std::string &strRemoteFile, struct FileInfo &oFileInfo) const;
const bool List(const std::string &strRemoteFolder, std::string &strList, bool bOnlyNames = true) const;
const bool DownloadFile(const std::string &strLocalFile, const std::string &strRemoteFile) const;
const bool DownloadFile(const std::string &strRemoteFile, std::vector<char> &data) const;
const bool DownloadWildcard(const std::string &strLocalDir, const std::string &strRemoteWildcard) const;
const bool UploadFile(const std::string &strLocalFile, const std::string &strRemoteFile, const bool &bCreateDir = false) const;
// SSL certs
void SetSSLCertFile(const std::string &strPath) { m_strSSLCertFile = strPath; }
const std::string &GetSSLCertFile() const { return m_strSSLCertFile; }
void SetSSLKeyFile(const std::string &strPath) { m_strSSLKeyFile = strPath; }
const std::string &GetSSLKeyFile() const { return m_strSSLKeyFile; }
void SetSSLKeyPassword(const std::string &strPwd) { m_strSSLKeyPwd = strPwd; }
const std::string &GetSSLKeyPwd() const { return m_strSSLKeyPwd; }
#ifdef DEBUG_CURL
static void SetCurlTraceLogDirectory(const std::string &strPath);
#endif
private:
/* common operations are performed here */
inline const CURLcode Perform() const;
inline std::string ParseURL(const std::string &strURL) const;
// Curl callbacks
static size_t WriteInStringCallback(void *ptr, size_t size, size_t nmemb, void *data);
static size_t WriteToFileCallback(void *ptr, size_t size, size_t nmemb, void *data);
static size_t ReadFromFileCallback(void *ptr, size_t size, size_t nmemb, void *stream);
static size_t ThrowAwayCallback(void *ptr, size_t size, size_t nmemb, void *data);
static size_t WriteToMemory(void *ptr, size_t size, size_t nmemb, void *data);
// Wildcard transfers callbacks
static long FileIsComingCallback(struct curl_fileinfo *finfo, WildcardTransfersCallbackData *data, int remains);
static long FileIsDownloadedCallback(WildcardTransfersCallbackData *data);
static size_t WriteItCallback(char *buff, size_t size, size_t nmemb, void *cb_data);
// String Helpers
static std::string StringFormat(std::string strFormat, ...);
static void ReplaceString(std::string &strSubject, const std::string &strSearch, const std::string &strReplace);
// Curl Debug informations
#ifdef DEBUG_CURL
static int DebugCallback(CURL *curl, curl_infotype curl_info_type, char *strace, size_t nSize, void *pFile);
inline void StartCurlDebug() const;
inline void EndCurlDebug() const;
#endif
std::string m_strUserName;
std::string m_strPassword;
std::string m_strServer;
std::string m_strProxy;
bool m_bActive; // For active FTP connections
bool m_bNoSignal;
unsigned m_uPort;
FTP_PROTOCOL m_eFtpProtocol;
SettingsFlag m_eSettingsFlags;
// SSL
std::string m_strSSLCertFile;
std::string m_strSSLKeyFile;
std::string m_strSSLKeyPwd;
mutable CURL *m_pCurlSession;
int m_iCurlTimeout;
// Progress function
ProgressFnCallback m_fnProgressCallback;
ProgressFnStruct m_ProgressStruct;
bool m_bProgressCallbackSet;
// Log printer callback
LogFnCallback m_oLog;
#ifdef DEBUG_CURL
static std::string s_strCurlTraceLogDirectory;
mutable std::ofstream m_ofFileCurlTrace;
#endif
CurlHandle &m_curlHandle;
};
} // namespace embeddedmz
// Log messages
#define LOG_WARNING_OBJECT_NOT_CLEANED \
"[FTPClient][Warning] Object was freed before calling " \
"CFTPClient::CleanupSession()." \
" The API session was cleaned though."
#define LOG_ERROR_EMPTY_HOST_MSG "[FTPClient][Error] Empty hostname."
#define LOG_ERROR_CURL_ALREADY_INIT_MSG \
"[FTPClient][Error] Curl session is already initialized ! " \
"Use CleanupSession() to clean the present one."
#define LOG_ERROR_CURL_NOT_INIT_MSG \
"[FTPClient][Error] Curl session is not initialized !" \
" Use InitSession() before."
#define LOG_ERROR_CURL_REMOVE_FORMAT "[FTPClient][Error] Unable to remove file %s (Error = %d | %s)."
#define LOG_ERROR_CURL_VERIFYURL_FORMAT \
"[FTPClient][Error] Unable to connect to the remote folder %s (Error = %d " \
"| %s)."
#define LOG_ERROR_CURL_FILETIME_FORMAT "[FTPClient][Error] Unable to get file %s's info (Error = %d | %s)."
#define LOG_ERROR_CURL_GETFILE_FORMAT "[FTPClient][Error] Unable to import remote File %s/%s (Error = %d | %s)."
#define LOG_ERROR_CURL_UPLOAD_FORMAT "[FTPClient][Error] Unable to upload file %s (Error = %d | %s)."
#define LOG_ERROR_CURL_FILELIST_FORMAT \
"[FTPClient][Error] Unable to connect to remote folder %s (Error = %d | " \
"%s)."
#define LOG_ERROR_CURL_GETWILD_FORMAT "[FTPClient][Error] Unable to import elements %s/%s (Error = %d | %s)."
#define LOG_ERROR_CURL_GETWILD_REC_FORMAT "[FTPClient][Error] Encountered a problem while importing %s to %s."
#define LOG_ERROR_CURL_MKDIR_FORMAT "[FTPClient][Error] Unable to create directory %s (Error = %d | %s)."
#define LOG_ERROR_CURL_RMDIR_FORMAT "[FTPClient][Error] Unable to remove directory %s (Error = %d | %s)."
#define LOG_ERROR_FILE_UPLOAD_FORMAT \
"[FTPClient][Error] Unable to open local file %s in " \
"CFTPClient::UploadFile()."
#define LOG_ERROR_FILE_GETFILE_FORMAT \
"[FTPClient][Error] Unable to open local file %s in " \
"CFTPClient::DownloadFile()."
#define LOG_ERROR_DIR_GETWILD_FORMAT \
"[FTPClient][Error] %s is not a directory or it doesn't exist " \
"in CFTPClient::DownloadWildcard()."
#endif
| 41.291228 | 137 | 0.702413 | [
"object",
"vector"
] |
1e8c017d2eb75f98fcee283d886101434777dd79 | 7,756 | h | C | src/Envelope.h | wc895/https-github.com-audacity-audacity | 2696da89cbee575b9f7a05b900a6720f82e23f63 | [
"CC-BY-3.0"
] | 3 | 2018-01-02T13:34:25.000Z | 2019-08-05T09:21:22.000Z | src/Envelope.h | wc895/https-github.com-audacity-audacity | 2696da89cbee575b9f7a05b900a6720f82e23f63 | [
"CC-BY-3.0"
] | null | null | null | src/Envelope.h | wc895/https-github.com-audacity-audacity | 2696da89cbee575b9f7a05b900a6720f82e23f63 | [
"CC-BY-3.0"
] | 1 | 2019-06-17T09:52:11.000Z | 2019-06-17T09:52:11.000Z | /**********************************************************************
Audacity: A Digital Audio Editor
Envelope.h
Dominic Mazzoni
**********************************************************************/
#ifndef __AUDACITY_ENVELOPE__
#define __AUDACITY_ENVELOPE__
#include <stdlib.h>
#include <algorithm>
#include <vector>
#include <wx/dynarray.h>
#include <wx/brush.h>
#include <wx/pen.h>
#include "xml/XMLTagHandler.h"
#include "Internat.h"
class wxRect;
class wxDC;
class wxMouseEvent;
class wxTextFile;
class DirManager;
class Envelope;
class EnvPoint;
class ZoomInfo;
class EnvPoint final : public XMLTagHandler {
public:
inline EnvPoint(Envelope *envelope, double t, double val);
double GetT() const { return mT; }
void SetT(double t) { mT = t; }
double GetVal() const { return mVal; }
inline void SetVal(double val);
bool HandleXMLTag(const wxChar *tag, const wxChar **attrs)
{
if (!wxStrcmp(tag, wxT("controlpoint"))) {
while (*attrs) {
const wxChar *attr = *attrs++;
const wxChar *value = *attrs++;
if (!wxStrcmp(attr, wxT("t")))
SetT(Internat::CompatibleToDouble(value));
else if (!wxStrcmp(attr, wxT("val")))
SetVal(Internat::CompatibleToDouble(value));
}
return true;
}
else
return false;
}
XMLTagHandler *HandleXMLChild(const wxChar * WXUNUSED(tag))
{
return NULL;
}
private:
Envelope *mEnvelope;
double mT;
double mVal;
};
typedef std::vector<EnvPoint> EnvArray;
class Envelope final : public XMLTagHandler {
public:
Envelope();
void Initialize(int numPoints);
virtual ~ Envelope();
bool GetInterpolateDB() { return mDB; }
void SetInterpolateDB(bool db) { mDB = db; }
void Mirror(bool mirror);
void Rescale(double minValue, double maxValue);
void Flatten(double value);
int GetDragPoint(void) {return mDragPoint;}
double GetMinValue() const { return mMinValue; }
double GetMaxValue() const { return mMaxValue; }
void SetRange(double minValue, double maxValue);
double ClampValue(double value) { return std::max(mMinValue, std::min(mMaxValue, value)); }
#if LEGACY_PROJECT_FILE_SUPPORT
// File I/O
bool Load(wxTextFile * in, DirManager * dirManager) override;
bool Save(wxTextFile * out, bool overwrite) override;
#endif
// Newfangled XML file I/O
bool HandleXMLTag(const wxChar *tag, const wxChar **attrs) override;
XMLTagHandler *HandleXMLChild(const wxChar *tag) override;
void WriteXML(XMLWriter &xmlFile) const /* not override */;
void DrawPoints(wxDC & dc, const wxRect & r, const ZoomInfo &zoomInfo,
bool dB, double dBRange,
float zoomMin, float zoomMax) const;
// Event Handlers
// Each ofthese returns true if parents needs to be redrawn
bool MouseEvent(wxMouseEvent & event, wxRect & r,
const ZoomInfo &zoomInfo, bool dB, double dBRange,
float zoomMin, float zoomMax);
bool HandleMouseButtonDown( wxMouseEvent & event, wxRect & r,
const ZoomInfo &zoomInfo, bool dB, double dBRange,
float zoomMin, float zoomMax);
bool HandleDragging( wxMouseEvent & event, wxRect & r,
const ZoomInfo &zoomInfo, bool dB, double dBRange,
float zoomMin, float zoomMax);
bool HandleMouseButtonUp();
// Handling Cut/Copy/Paste events
void CollapseRegion(double t0, double t1);
void CopyFrom(const Envelope * e, double t0, double t1);
void Paste(double t0, const Envelope *e);
void InsertSpace(double t0, double tlen);
void RemoveUnneededPoints(double time = -1, double tolerence = 0.001);
// Control
void SetOffset(double newOffset);
void SetTrackLen(double trackLen);
// Accessors
/** \brief Get envelope value at time t */
double GetValue(double t) const;
/** \brief Get many envelope points at once.
*
* This is much faster than calling GetValue() multiple times if you need
* more than one value in a row. */
void GetValues(double *buffer, int len, double t0, double tstep) const;
/** \brief Get many envelope points at once, but don't assume uniform time step.
*/
void GetValues
(double *buffer, int bufferLen, int leftOffset, const ZoomInfo &zoomInfo) const;
int NumberOfPointsAfter(double t) const;
double NextPointAfter(double t) const;
double Average( double t0, double t1 ) const;
double AverageOfInverse( double t0, double t1 ) const;
double Integral( double t0, double t1 ) const;
double IntegralOfInverse( double t0, double t1 ) const;
double SolveIntegralOfInverse( double t0, double area) const;
void print() const;
void testMe();
bool IsDirty() const;
/** \brief Add a point at a particular spot */
int Insert(double when, double value);
/** \brief Move a point at when to value
*
* Returns 0 if point moved, -1 if not found.*/
int Move(double when, double value);
/** \brief DELETE a point by its position in array */
void Delete(int point);
/** \brief insert a point */
void Insert(int point, const EnvPoint &p);
/** \brief Return number of points */
int GetNumberOfPoints() const;
/** \brief Accessor for points */
const EnvPoint &operator[] (int index) const
{
return mEnv[index];
}
/** \brief Returns the sets of when and value pairs */
void GetPoints(double *bufferWhen,
double *bufferValue,
int bufferLen) const;
private:
EnvPoint * AddPointAtEnd( double t, double val );
void MarkDragPointForDeletion();
float ValueOfPixel( int y, int height, bool upper,
bool dB, double dBRange,
float zoomMin, float zoomMax);
void BinarySearchForTime( int &Lo, int &Hi, double t ) const;
double GetInterpolationStartValueAtPoint( int iPoint ) const;
void MoveDraggedPoint( wxMouseEvent & event, wxRect & r,
const ZoomInfo &zoomInfo, bool dB, double dBRange,
float zoomMin, float zoomMax);
// Possibly inline functions:
// This function resets them integral memoizers (call whenever the Envelope changes)
void resetIntegralMemoizer() { lastIntegral_t0=0; lastIntegral_t1=0; lastIntegral_result=0; }
// The list of envelope control points.
EnvArray mEnv;
bool mMirror;
/** \brief The time at which the envelope starts, i.e. the start offset */
double mOffset;
/** \brief The length of the envelope, which is the same as the length of the
* underlying track (normally) */
double mTrackLen;
// TODO: mTrackEpsilon based on assumption of 200KHz. Needs review if/when
// we support higher sample rates.
/** \brief The shortest distance appart that points on an envelope can be
* before being considered the same point */
double mTrackEpsilon;
double mDefaultValue;
/** \brief Number of pixels contour is from the true envelope. */
int mContourOffset;
double mInitialVal;
// These are used in dragging.
int mDragPoint;
int mInitialY;
bool mUpper;
bool mIsDeleting;
int mButton;
bool mDB;
bool mDirty;
double mMinValue, mMaxValue;
// These are memoizing variables for Integral()
double lastIntegral_t0;
double lastIntegral_t1;
double lastIntegral_result;
mutable int mSearchGuess;
};
inline EnvPoint::EnvPoint(Envelope *envelope, double t, double val)
{
mEnvelope = envelope;
mT = t;
mVal = mEnvelope->ClampValue(val);
}
inline void EnvPoint::SetVal(double val)
{
mVal = mEnvelope->ClampValue(val);
}
#endif
| 29.157895 | 96 | 0.651625 | [
"vector"
] |
1e8e635f8789916eee2f7c81b03eb8b84b0d0527 | 2,530 | h | C | media/remoting/end2end_test_renderer.h | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | media/remoting/end2end_test_renderer.h | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | media/remoting/end2end_test_renderer.h | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | // Copyright 2017 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.
#ifndef MEDIA_REMOTING_END2END_RENDERER_H_
#define MEDIA_REMOTING_END2END_RENDERER_H_
#include <vector>
#include "base/memory/weak_ptr.h"
#include "media/base/demuxer_stream.h"
#include "media/base/renderer.h"
#include "media/remoting/rpc_broker.h"
namespace media {
namespace remoting {
class RendererController;
class CourierRenderer;
class Receiver;
// Simulates the media remoting pipeline.
class End2EndTestRenderer final : public Renderer {
public:
explicit End2EndTestRenderer(std::unique_ptr<Renderer> renderer);
~End2EndTestRenderer() override;
// Renderer implementation.
void Initialize(MediaResource* media_resource,
RendererClient* client,
PipelineStatusCallback init_cb) override;
void SetCdm(CdmContext* cdm_context, CdmAttachedCB cdm_attached_cb) override;
void SetLatencyHint(base::Optional<base::TimeDelta> latency_hint) override;
void Flush(base::OnceClosure flush_cb) override;
void StartPlayingFrom(base::TimeDelta time) override;
void SetPlaybackRate(double playback_rate) override;
void SetVolume(float volume) override;
base::TimeDelta GetMediaTime() override;
void OnSelectedVideoTracksChanged(
const std::vector<DemuxerStream*>& enabled_tracks,
base::OnceClosure change_completed_cb) override;
void OnEnabledAudioTracksChanged(
const std::vector<DemuxerStream*>& enabled_tracks,
base::OnceClosure change_completed_cb) override;
private:
// Called to send RPC messages to |receiver_|.
void SendMessageToSink(const std::vector<uint8_t>& message);
// Called to send frame data to |receiver_|.
void SendFrameToSink(const std::vector<uint8_t>& data,
DemuxerStream::Type type);
// Called when receives RPC messages from |receiver_|.
void OnMessageFromSink(std::unique_ptr<std::vector<uint8_t>> message);
std::unique_ptr<RendererController> controller_;
std::unique_ptr<CourierRenderer> courier_renderer_;
// The RpcBroker to handle the RPC messages to/from |receiver_|.
RpcBroker receiver_rpc_broker_;
// A receiver that renders media streams.
std::unique_ptr<Receiver> receiver_;
base::WeakPtrFactory<End2EndTestRenderer> weak_factory_{this};
DISALLOW_COPY_AND_ASSIGN(End2EndTestRenderer);
};
} // namespace remoting
} // namespace media
#endif // MEDIA_REMOTING_END2END_RENDERER_H_
| 32.857143 | 79 | 0.766008 | [
"vector"
] |
1e928e4c0ee8a28a3024d16a292246ae5b4766f6 | 609 | h | C | Advance 1 MinorityGame/src/MinorityGame/Game.h | LuezhenYuan/Computational-physics | b7fa5662657699a8c633c3c81d292d36e01931c7 | [
"MIT"
] | null | null | null | Advance 1 MinorityGame/src/MinorityGame/Game.h | LuezhenYuan/Computational-physics | b7fa5662657699a8c633c3c81d292d36e01931c7 | [
"MIT"
] | null | null | null | Advance 1 MinorityGame/src/MinorityGame/Game.h | LuezhenYuan/Computational-physics | b7fa5662657699a8c633c3c81d292d36e01931c7 | [
"MIT"
] | 3 | 2017-06-27T03:21:34.000Z | 2020-11-13T12:07:03.000Z | #ifndef GAME_H_INCLUDED
#define GAME_H_INCLUDED
#include <map>
#include "agent.h"
#include "history.h"
#include <iterator>
#include <utility>
#include <string>
#include <fstream>
using namespace std;
class Game{
map<pair<int,int>,int> m_S;
agent** m_agents;
history* p_hist;
int m_N;
public:
Game(map<pair<int,int>,int> S);//Initialize N agents. use new and delete[]
~Game();
void Run(string file_name,int time_steps=10000);//Runing the minority game model for time_steps cycles.
void BatchRun(string file_name,int Individual_run=32,int time_steps=10000);
};
#endif // GAME_H_INCLUDED
| 25.375 | 104 | 0.730706 | [
"model"
] |
1e9a32d1afb2bb11b418013eb19152295a1b5899 | 2,108 | h | C | Core/Utils/StringUtils.h | zenden2k/KeeneticRainmeterPlugin | fb8e61e161422acfa095215ed1237727e5a9f5f9 | [
"MIT"
] | 2 | 2021-05-01T14:08:48.000Z | 2021-09-05T11:14:19.000Z | Core/Utils/StringUtils.h | zenden2k/KeeneticRainmeterPlugin | fb8e61e161422acfa095215ed1237727e5a9f5f9 | [
"MIT"
] | null | null | null | Core/Utils/StringUtils.h | zenden2k/KeeneticRainmeterPlugin | fb8e61e161422acfa095215ed1237727e5a9f5f9 | [
"MIT"
] | null | null | null | /*
Image Uploader - free application for uploading images/files to the Internet
Copyright 2007-2018 Sergey Svistunov (zenden2k@gmail.com)
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 IU_CORE_UTILS_STRINGUTILS_H
#define IU_CORE_UTILS_STRINGUTILS_H
#include <string>
#include <string_view>
#include <vector>
#include "CoreTypes.h"
namespace IuStringUtils
{
std::string Trim(const std::string& str);
std::string_view TrimSV(std::string_view str);
std::string Replace(const std::string& text, const std::string& s, const std::string& d);
void Split(const std::string& str, const std::string& delimiters, std::vector<std::string>& tokens, int maxCount = -1);
std::vector<std::string_view> SplitSV(std::string_view strv, std::string_view delims, int maxCount = -1);
std::string Join(const std::vector<std::string>& strings, const std::string& delim);
std::string Tail(std::string const& source, size_t length);
// Current version of toLower works only with ASCII strings
std::string toLower(const std::string& str);
// The stricmp() function compares the two strings s1 and s2,
// ignoring the case of the characters. It returns an integer less than,
// equal to, or greater than zero if s1 is found, respectively, to be less than,
// to match, or be greater than s2.
// IT WORKS ONLY WITH ANSI STRINGS!
int stricmp(const char *s1, const char *s2);
std::string ConvertUnixLineEndingsToWindows(const std::string& text);
size_t LengthOfUtf8String(const std::string &utf8_string);
};
#endif
| 39.773585 | 123 | 0.719639 | [
"vector"
] |
1e9cfcda6b942ae8d24cb1cfe4e0f089ec11562d | 385 | h | C | evelight/renderable.h | MrBad/evelight | 45e5c3a795491f922a1bf6b579d3655562b7030a | [
"MIT"
] | 6 | 2018-04-29T23:25:06.000Z | 2021-01-24T02:11:23.000Z | evelight/renderable.h | MrBad/evelight | 45e5c3a795491f922a1bf6b579d3655562b7030a | [
"MIT"
] | null | null | null | evelight/renderable.h | MrBad/evelight | 45e5c3a795491f922a1bf6b579d3655562b7030a | [
"MIT"
] | 2 | 2020-04-18T15:09:01.000Z | 2020-08-24T06:44:41.000Z | #pragma once
#include "vertex.h"
#include <GL/glew.h>
#include <vector>
namespace evl {
enum DrawType {
D_NONE,
D_POINTS,
D_LINES,
D_TRIANGLES,
D_MAX
};
struct Renderable {
std::vector<Vertex> mVertices;
std::vector<int> mIndexes;
DrawType mDrawType;
GLuint textureId;
Renderable()
: mDrawType(D_NONE)
, textureId(0){};
};
}
| 14.259259 | 34 | 0.620779 | [
"vector"
] |
1ea4b5d989bdba6d094a62dd27d443858d6083b7 | 2,965 | h | C | mindspore/ccsrc/plugin/device/ascend/hal/device/distribute/mpi_collective_group.h | httpsgithu/mindspore | c29d6bb764e233b427319cb89ba79e420f1e2c64 | [
"Apache-2.0"
] | 1 | 2022-02-23T09:13:43.000Z | 2022-02-23T09:13:43.000Z | mindspore/ccsrc/plugin/device/ascend/hal/device/distribute/mpi_collective_group.h | 949144093/mindspore | c29d6bb764e233b427319cb89ba79e420f1e2c64 | [
"Apache-2.0"
] | null | null | null | mindspore/ccsrc/plugin/device/ascend/hal/device/distribute/mpi_collective_group.h | 949144093/mindspore | c29d6bb764e233b427319cb89ba79e420f1e2c64 | [
"Apache-2.0"
] | null | null | null | /**
* Copyright 2021 Huawei Technologies Co., Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef MINDSPORE_MINDSPORE_CCSRC_RUNTIME_DEVICE_ASCEND_DISTRIBUTE_MPI_COLLECTIVE_INIT_H
#define MINDSPORE_MINDSPORE_CCSRC_RUNTIME_DEVICE_ASCEND_DISTRIBUTE_MPI_COLLECTIVE_INIT_H
#include <mpi.h>
#include <unistd.h>
#include <map>
#include <string>
#include <vector>
#include <utility>
#include <sstream>
#include "hccl/hccl_types.h"
#include "pybind11/pybind11.h"
namespace mindspore {
namespace device {
namespace ascend {
namespace collective {
constexpr int MAX_HOSTNAME_LEN = 1024;
class MPICollective {
public:
MPICollective(MPICollective const &) = delete;
MPICollective &operator=(const MPICollective &) = delete;
static MPICollective &instance();
void AssignLocalRankID();
bool Init();
void FinalizeMPI();
int GetRankIdByGroup(const std::string &name);
int GetGroupSize(const std::string &name);
HcclComm GetGroupComm(const std::string &name);
int GetDeviceId() const;
bool CreateCommGroup(const std::string &name, const std::vector<unsigned int> &ranks);
void DestroyHcclComm();
std::map<std::string, HcclComm> group_comm_;
private:
MPICollective();
~MPICollective() = default;
bool mpi_inited_;
int rank_id_;
int local_rank_id_;
int rank_size_;
MPI_Group comm_group_world_;
std::map<std::string, std::pair<int, int>> group_info_;
};
#define CHECK_RET(expression, result, message) \
{ \
auto ret = (expression); \
if (ret != result) { \
std::ostringstream oss; \
oss << "Error in file " << __FILE__ << " | Error on line " << __LINE__ \
<< " | Ascend collective Error: " << (message) << " | Error Number " << ret; \
pybind11::pybind11_fail(oss.str()); \
} \
}
} // namespace collective
} // namespace ascend
} // namespace device
} // namespace mindspore
#endif // MINDSPORE_MINDSPORE_CCSRC_RUNTIME_DEVICE_ASCEND_DISTRIBUTE_COLLECTIVE_INIT_H
| 39.533333 | 89 | 0.602361 | [
"vector"
] |
1ea885b4c03765b2cf7fc147bbb4ee8148d2433d | 535 | h | C | Project/StudentUnion/StudentUnion/ZCNewsDetailCell.h | zcill/JXNU_StudentUnion | 85db206248f47254785a28053d1123cd0addedae | [
"MIT"
] | 1 | 2016-03-23T01:15:21.000Z | 2016-03-23T01:15:21.000Z | Project/StudentUnion/StudentUnion/ZCNewsDetailCell.h | zcill/JXNU_StudentUnion | 85db206248f47254785a28053d1123cd0addedae | [
"MIT"
] | null | null | null | Project/StudentUnion/StudentUnion/ZCNewsDetailCell.h | zcill/JXNU_StudentUnion | 85db206248f47254785a28053d1123cd0addedae | [
"MIT"
] | null | null | null | //
// ZCNewsDetailCell.h
// StudentUnion
//
// Created by 朱立焜 on 16/4/10.
// Copyright © 2016年 朱立焜. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "ZCWorkNewsModel.h"
@interface ZCNewsDetailCell : UITableViewCell
@property (weak, nonatomic) IBOutlet UILabel *newsTitleLabel;
@property (weak, nonatomic) IBOutlet UITextView *contentTextView;
@property (weak, nonatomic) IBOutlet UILabel *postTimeLabel;
@property (weak, nonatomic) IBOutlet UIView *bannerView;
@property (nonatomic, strong) ZCWorkNewsModel *model;
@end
| 25.47619 | 65 | 0.757009 | [
"model"
] |
1eab819b66c7c89d4d4d1bf45f61094baeb69015 | 9,299 | h | C | dev/Gems/TouchBending/Code/Source/Simulation/PhysicsComponent.h | akulamartin/lumberyard | 2d4be458a02845179be098e40cdc0c48f28f3b5a | [
"AML"
] | 8 | 2019-10-07T16:33:47.000Z | 2020-12-07T03:59:58.000Z | dev/Gems/TouchBending/Code/Source/Simulation/PhysicsComponent.h | 29e7e280-0d1c-4bba-98fe-f7cd3ca7500a/lumberyard | 1c52b941dcb7d94341fcf21275fe71ff67173ada | [
"AML"
] | null | null | null | dev/Gems/TouchBending/Code/Source/Simulation/PhysicsComponent.h | 29e7e280-0d1c-4bba-98fe-f7cd3ca7500a/lumberyard | 1c52b941dcb7d94341fcf21275fe71ff67173ada | [
"AML"
] | 4 | 2019-08-05T07:25:46.000Z | 2020-12-07T05:12:55.000Z | /*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#pragma once
#include <PxPhysicsAPI.h>
#include <AzCore/Component/Component.h>
#include <AzCore/Component/TickBus.h>
#include <AzFramework/Physics/World.h>
#include <AzFramework/Physics/SystemBus.h>
#include <AzFramework/Physics/TouchBendingBus.h>
#include <AzFramework/Physics/WorldEventhandler.h>
#include <CrySystemBus.h>
#include <ISystem.h>
#include <PhysX/TriggerEventCallback.h>
#include "AsyncSkeletonBuilderBus.h"
namespace Physics
{
struct TouchBendingTriggerHandle;
}
namespace TouchBending
{
namespace Simulation
{
class PhysicalizedSkeleton;
/// This is the main system component of the TouchBending Gem in charge of managing physics simulation
/// of touch bendable vegetation. It is basically a liason between Touch Bendable CVegetation render nodes
/// and the PhysX Gem.
class PhysicsComponent
: public AZ::Component
, public Physics::TouchBendingBus::Handler
, public Physics::SystemNotificationBus::Handler
, public PhysX::IPhysxTriggerEventCallback
, public AsyncSkeletonBuilderBus::Handler
, private CrySystemEventBus::Handler
, private ISystemEventListener
{
public:
AZ_COMPONENT(PhysicsComponent, "{E3BE4294-1FC3-4B05-BD8F-7B6D96FE0CE1}", AZ::Component);
PhysicsComponent();
~PhysicsComponent() override = default;
static void Reflect(AZ::ReflectContext* context);
static void GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided);
static void GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible);
static void GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required);
static void GetDependentServices(AZ::ComponentDescriptor::DependencyArrayType& dependent);
//AZ::Component
void Activate() override;
void Deactivate() override;
//::Physics::TouchBendingBus::Handler START
bool IsTouchBendingEnabled() const override;
Physics::TouchBendingTriggerHandle* CreateTouchBendingTrigger(const AZ::Transform& worldTransform,
const AZ::Aabb&worldAabb, Physics::ITouchBendingCallback* callback, const void * callbackPrivateData) override;
void SetTouchBendingSkeletonVisibility(Physics::TouchBendingSkeletonHandle* skeletonHandle,
bool isVisible, AZ::u32& skeletonBoneCountOut, AZ::u32& triggerTouchCountOut) override;
void DeleteTouchBendingTrigger(Physics::TouchBendingTriggerHandle* handle) override;
void DephysicalizeTouchBendingSkeleton(Physics::TouchBendingSkeletonHandle* skeletonHandle) override;
void ReadJointPositionsOfSkeleton(Physics::TouchBendingSkeletonHandle* skeletonHandle, Physics::JointPositions* jointPositions) override;
//::Physics::TouchBendingBus::Handler END
//AsyncSkeletonBuilderBus::Handler START
void AsyncBuildSkeleton(Physics::TouchBendingTriggerHandle* proximityTrigger,
AZ::Transform worldTransform,
AZStd::shared_ptr<Physics::SpineTree> spineTreeArchetype) override;
//AsyncSkeletonBuilderBus::Handler END
//::Physics::SystemNotificationBus::Handler START
void OnPrePhysicsUpdate(float fixedDeltaTime, Physics::World* world) override;
void OnPostPhysicsUpdate(float fixedDeltaTime, Physics::World* world) override;
void OnPreWorldDestroy(Physics::World* world) override;
//::Physics::SystemNotificationBus::Handler END
//CrySystemEventBus::Handler START
//So we can register for Level Load/Unload events.
void OnCrySystemInitialized(ISystem&, const SSystemInitParams&) override;
void OnCrySystemShutdown(ISystem&) override;
//CrySystemEventBus::Handler END
//ISystemEventListener START
//Here we get level Load/Unload events
void OnSystemEvent(ESystemEvent event, UINT_PTR wparam, UINT_PTR lparam) override;
//ISystemEventListener END
//PhysX::IPhysxTriggerEventCallback START
bool OnTriggerCallback(physx::PxTriggerPair* triggerPair) override;
//PhysX::IPhysxTriggerEventCallback END
private:
/// Completely removes a TouchBending Instance.
void DeleteTouchBendingTriggerLocked(Physics::TouchBendingTriggerHandle* triggerHandle);
/** @brief Tries to erase a SpineTree Archetype from the cache.
*
* @param archetypeId Identifier of the archetype.
* @param wasPresentInTheCache [out] Set to TRUE upon return if the archetype ID was registered in the cache.
* Set to FALSE upon return if the archetype ID was not present in the cache at all.
* @returns TRUE if the archetype identifier was present in the cache
* and it was erased from the cache because its reference count was set to zero.
* Otherwise returns FALSE.
*/
bool TryEraseSpineTreeArchetypeFromCache(Physics::SpineTreeIDType archetypeId, bool& wasPresentInTheCache);
/// Clean up just the level-based physics data, but not any system-level data.
void UnloadPhysicsLevelData();
/// Reference to the physics world (aka PxScene) where all touch bending actors
/// are added for simulation.
AZStd::shared_ptr<Physics::World> m_world;
/// Reference to the PhysX Foundation, needed for establishing global SDK pointers when using separated memory spaces
physx::PxFoundation* m_foundation = nullptr;
/// Reference to the PhysX Physics SDK, needed for establishing global SDK pointers when using separated memory spaces
physx::PxPhysics* m_physics = nullptr;
///To create Shapes, even is they are used for trigger objects, you need
///a material. In this case, this material is used for proximity triggers,
///hence the prefix m_dummy...
physx::PxMaterial* m_dummyMaterialForTriggers;
/// Default PhysX material used by all Touch Bendable Rigid Actors.
physx::PxMaterial* m_commonMaterialForSkeletonBones;
/// Tree objects owned by TouchBendingTriggerHandle are built with AZ Jobs
/// to alleviate pressure on main thread. We avoid creating too many jobs
/// with this flag. If this is true, we simply add build requests implictily
/// in the queue of AsyncSkeletonBuilderBus. IF this is false we create an AZ Job
/// and dispatch the Ebus events stored in AsyncSkeletonBuilderBus.
bool m_isRunningJob;
/// Adding or removing TouchBendingTriggerHandle objects is an uncommon operation,
/// none the less it may happen that the engine wants to delete a CVegetation render node
/// while at the same time we are trying to build a Tree for it on an AZ Job. With this mutex
/// we prevent catastrophe.
AZStd::mutex m_triggerActorsLock;
/// In this set we keep track of all of the TouchBendingTriggerHandle object that
/// the engine ordered this Gem to instantiate. In other words, for each Touch Bendable
/// CVegetation render node, one corresponding TouchBendingTriggerHandle object is created
/// here in this Gem.
AZStd::unordered_set<Physics::TouchBendingTriggerHandle*> m_triggerActors;
/// We use this mutex to prevent race condition access to m_triggerActorsWithTreesReadyToBeAddedToScene,
/// between AZ::Job and the main thread.
AZStd::mutex m_triggerActorsWithSkeletonlock;
/// As PhysicalizedSkeleton objects are completely built by the AZ::Job, they are added to this Vector for further
/// dequeueing by the main thread on OnPrePhysicsUpdate().
AZStd::vector<Physics::TouchBendingTriggerHandle*> m_triggerActorsWithSkeletonReadyToBeAddedToScene;
/// This is a cache in the sense that the cache itself doesn't own the spineTrees,
/// But so long as a trigger object owns a reference to the spine tree archetype,
/// the archetype will remain in memory.
AZStd::unordered_map<Physics::SpineTreeIDType, AZStd::weak_ptr<Physics::SpineTree>> m_spineTreeArchetypeCache;
};
} // namespace Physics
} // namespace TouchBending | 53.137143 | 149 | 0.682869 | [
"render",
"object",
"vector",
"transform"
] |
1eafc602e17ea5601acee93f31c25fff328dce57 | 6,257 | c | C | openeuler-kernel/drivers/dma/dw-edma/dw-edma-pcie.c | Ddnirvana/test-CI | dd7a0a71281075e8ab300bddbab4a9fa039958f0 | [
"MulanPSL-1.0"
] | 31 | 2021-04-27T08:50:40.000Z | 2022-03-01T02:26:21.000Z | openeuler-kernel/drivers/dma/dw-edma/dw-edma-pcie.c | Ddnirvana/test-CI | dd7a0a71281075e8ab300bddbab4a9fa039958f0 | [
"MulanPSL-1.0"
] | 13 | 2021-07-10T04:36:17.000Z | 2022-03-03T10:50:05.000Z | openeuler-kernel/drivers/dma/dw-edma/dw-edma-pcie.c | Ddnirvana/test-CI | dd7a0a71281075e8ab300bddbab4a9fa039958f0 | [
"MulanPSL-1.0"
] | 12 | 2021-04-06T02:23:10.000Z | 2022-02-28T11:43:19.000Z | // SPDX-License-Identifier: GPL-2.0
/*
* Copyright (c) 2018-2019 Synopsys, Inc. and/or its affiliates.
* Synopsys DesignWare eDMA PCIe driver
*
* Author: Gustavo Pimentel <gustavo.pimentel@synopsys.com>
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/pci.h>
#include <linux/device.h>
#include <linux/dma/edma.h>
#include <linux/pci-epf.h>
#include <linux/msi.h>
#include "dw-edma-core.h"
struct dw_edma_pcie_data {
/* eDMA registers location */
enum pci_barno rg_bar;
off_t rg_off;
size_t rg_sz;
/* eDMA memory linked list location */
enum pci_barno ll_bar;
off_t ll_off;
size_t ll_sz;
/* eDMA memory data location */
enum pci_barno dt_bar;
off_t dt_off;
size_t dt_sz;
/* Other */
u32 version;
enum dw_edma_mode mode;
u8 irqs;
};
static const struct dw_edma_pcie_data snps_edda_data = {
/* eDMA registers location */
.rg_bar = BAR_0,
.rg_off = 0x00001000, /* 4 Kbytes */
.rg_sz = 0x00002000, /* 8 Kbytes */
/* eDMA memory linked list location */
.ll_bar = BAR_2,
.ll_off = 0x00000000, /* 0 Kbytes */
.ll_sz = 0x00800000, /* 8 Mbytes */
/* eDMA memory data location */
.dt_bar = BAR_2,
.dt_off = 0x00800000, /* 8 Mbytes */
.dt_sz = 0x03800000, /* 56 Mbytes */
/* Other */
.version = 0,
.mode = EDMA_MODE_UNROLL,
.irqs = 1,
};
static int dw_edma_pcie_irq_vector(struct device *dev, unsigned int nr)
{
return pci_irq_vector(to_pci_dev(dev), nr);
}
static const struct dw_edma_core_ops dw_edma_pcie_core_ops = {
.irq_vector = dw_edma_pcie_irq_vector,
};
static int dw_edma_pcie_probe(struct pci_dev *pdev,
const struct pci_device_id *pid)
{
const struct dw_edma_pcie_data *pdata = (void *)pid->driver_data;
struct device *dev = &pdev->dev;
struct dw_edma_chip *chip;
int err, nr_irqs;
struct dw_edma *dw;
/* Enable PCI device */
err = pcim_enable_device(pdev);
if (err) {
pci_err(pdev, "enabling device failed\n");
return err;
}
/* Mapping PCI BAR regions */
err = pcim_iomap_regions(pdev, BIT(pdata->rg_bar) |
BIT(pdata->ll_bar) |
BIT(pdata->dt_bar),
pci_name(pdev));
if (err) {
pci_err(pdev, "eDMA BAR I/O remapping failed\n");
return err;
}
pci_set_master(pdev);
/* DMA configuration */
err = pci_set_dma_mask(pdev, DMA_BIT_MASK(64));
if (!err) {
err = pci_set_consistent_dma_mask(pdev, DMA_BIT_MASK(64));
if (err) {
pci_err(pdev, "consistent DMA mask 64 set failed\n");
return err;
}
} else {
pci_err(pdev, "DMA mask 64 set failed\n");
err = pci_set_dma_mask(pdev, DMA_BIT_MASK(32));
if (err) {
pci_err(pdev, "DMA mask 32 set failed\n");
return err;
}
err = pci_set_consistent_dma_mask(pdev, DMA_BIT_MASK(32));
if (err) {
pci_err(pdev, "consistent DMA mask 32 set failed\n");
return err;
}
}
/* Data structure allocation */
chip = devm_kzalloc(dev, sizeof(*chip), GFP_KERNEL);
if (!chip)
return -ENOMEM;
dw = devm_kzalloc(dev, sizeof(*dw), GFP_KERNEL);
if (!dw)
return -ENOMEM;
/* IRQs allocation */
nr_irqs = pci_alloc_irq_vectors(pdev, 1, pdata->irqs,
PCI_IRQ_MSI | PCI_IRQ_MSIX);
if (nr_irqs < 1) {
pci_err(pdev, "fail to alloc IRQ vector (number of IRQs=%u)\n",
nr_irqs);
return -EPERM;
}
/* Data structure initialization */
chip->dw = dw;
chip->dev = dev;
chip->id = pdev->devfn;
chip->irq = pdev->irq;
dw->rg_region.vaddr = pcim_iomap_table(pdev)[pdata->rg_bar];
dw->rg_region.vaddr += pdata->rg_off;
dw->rg_region.paddr = pdev->resource[pdata->rg_bar].start;
dw->rg_region.paddr += pdata->rg_off;
dw->rg_region.sz = pdata->rg_sz;
dw->ll_region.vaddr = pcim_iomap_table(pdev)[pdata->ll_bar];
dw->ll_region.vaddr += pdata->ll_off;
dw->ll_region.paddr = pdev->resource[pdata->ll_bar].start;
dw->ll_region.paddr += pdata->ll_off;
dw->ll_region.sz = pdata->ll_sz;
dw->dt_region.vaddr = pcim_iomap_table(pdev)[pdata->dt_bar];
dw->dt_region.vaddr += pdata->dt_off;
dw->dt_region.paddr = pdev->resource[pdata->dt_bar].start;
dw->dt_region.paddr += pdata->dt_off;
dw->dt_region.sz = pdata->dt_sz;
dw->version = pdata->version;
dw->mode = pdata->mode;
dw->nr_irqs = nr_irqs;
dw->ops = &dw_edma_pcie_core_ops;
/* Debug info */
pci_dbg(pdev, "Version:\t%u\n", dw->version);
pci_dbg(pdev, "Mode:\t%s\n",
dw->mode == EDMA_MODE_LEGACY ? "Legacy" : "Unroll");
pci_dbg(pdev, "Registers:\tBAR=%u, off=0x%.8lx, sz=0x%zx bytes, addr(v=%p, p=%pa)\n",
pdata->rg_bar, pdata->rg_off, pdata->rg_sz,
dw->rg_region.vaddr, &dw->rg_region.paddr);
pci_dbg(pdev, "L. List:\tBAR=%u, off=0x%.8lx, sz=0x%zx bytes, addr(v=%p, p=%pa)\n",
pdata->ll_bar, pdata->ll_off, pdata->ll_sz,
dw->ll_region.vaddr, &dw->ll_region.paddr);
pci_dbg(pdev, "Data:\tBAR=%u, off=0x%.8lx, sz=0x%zx bytes, addr(v=%p, p=%pa)\n",
pdata->dt_bar, pdata->dt_off, pdata->dt_sz,
dw->dt_region.vaddr, &dw->dt_region.paddr);
pci_dbg(pdev, "Nr. IRQs:\t%u\n", dw->nr_irqs);
/* Validating if PCI interrupts were enabled */
if (!pci_dev_msi_enabled(pdev)) {
pci_err(pdev, "enable interrupt failed\n");
return -EPERM;
}
dw->irq = devm_kcalloc(dev, nr_irqs, sizeof(*dw->irq), GFP_KERNEL);
if (!dw->irq)
return -ENOMEM;
/* Starting eDMA driver */
err = dw_edma_probe(chip);
if (err) {
pci_err(pdev, "eDMA probe failed\n");
return err;
}
/* Saving data structure reference */
pci_set_drvdata(pdev, chip);
return 0;
}
static void dw_edma_pcie_remove(struct pci_dev *pdev)
{
struct dw_edma_chip *chip = pci_get_drvdata(pdev);
int err;
/* Stopping eDMA driver */
err = dw_edma_remove(chip);
if (err)
pci_warn(pdev, "can't remove device properly: %d\n", err);
/* Freeing IRQs */
pci_free_irq_vectors(pdev);
}
static const struct pci_device_id dw_edma_pcie_id_table[] = {
{ PCI_DEVICE_DATA(SYNOPSYS, EDDA, &snps_edda_data) },
{ }
};
MODULE_DEVICE_TABLE(pci, dw_edma_pcie_id_table);
static struct pci_driver dw_edma_pcie_driver = {
.name = "dw-edma-pcie",
.id_table = dw_edma_pcie_id_table,
.probe = dw_edma_pcie_probe,
.remove = dw_edma_pcie_remove,
};
module_pci_driver(dw_edma_pcie_driver);
MODULE_LICENSE("GPL v2");
MODULE_DESCRIPTION("Synopsys DesignWare eDMA PCIe driver");
MODULE_AUTHOR("Gustavo Pimentel <gustavo.pimentel@synopsys.com>");
| 26.070833 | 86 | 0.677641 | [
"vector"
] |
1eb0902860fa795156df12031a1cfca6635ac7ff | 8,418 | h | C | benchmarks/wbhart-bsdnt/zz.h | pointhi/benchmarks | 68899480c0fc8d361079a81edc6d816d5f17d58e | [
"UPL-1.0"
] | 7 | 2018-12-10T02:41:43.000Z | 2020-06-18T06:13:59.000Z | benchmarks/wbhart-bsdnt/zz.h | pointhi/benchmarks | 68899480c0fc8d361079a81edc6d816d5f17d58e | [
"UPL-1.0"
] | 23 | 2018-06-07T07:46:27.000Z | 2018-08-06T17:57:39.000Z | benchmarks/wbhart-bsdnt/zz.h | pointhi/benchmarks | 68899480c0fc8d361079a81edc6d816d5f17d58e | [
"UPL-1.0"
] | 2 | 2018-06-07T08:04:52.000Z | 2018-06-07T09:06:21.000Z | /*
Copyright (C) 2013 William Hart
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS''
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef BSDNT_ZZ_H
#define BSDNT_ZZ_H
#include <math.h>
#include <string.h> /* strspn */
#include <stdarg.h> /* variadic functions */
#include "helper.h"
#include "rand.h"
#include "nn.h"
#ifdef __cplusplus
extern "C" {
#endif
typedef struct
{
nn_t n;
len_t size;
len_t alloc;
} zz_struct;
typedef zz_struct zz_t[1];
typedef zz_struct * zz_ptr;
typedef const zz_struct * zz_srcptr;
#define ZZ_SWAP(a, b) \
TYPED_SWAP(zz_ptr, a, b)
#define ZZ_SRC_SWAP(a, b) \
TYPED_SWAP(zz_srcptr, a, b)
#define ZZ_ORDER(a, an, b, bn) \
do { \
if (an < bn) { \
BSDNT_SWAP(an, bn); \
TYPED_SWAP(zz_srcptr, a, b); \
} \
} while (0)
#define TMP_ZZ(xxx) \
do { \
(xxx) = (zz_ptr) TMP_ALLOC_BYTES(sizeof(zz_t)); \
zz_init(xxx); \
} while (0)
/**********************************************************************
Memory management
**********************************************************************/
/*
Initialise a zz_t for use.
*/
void zz_init(zz_ptr r);
/*
Initialize a null-terminated list of zz_ts for use.
E.g.: given num1, num2 and num3, they can be initialized as
zz_inits(num1, num2, num3, '\0');
*/
void zz_inits(zz_ptr num, ...);
/*
Initialise a zz_t for use and ensure it has space for an integer
whose absolute value has m words. This is included for performance
reasons only. Usually it is sufficient to call zz_init.
*/
void zz_init_fit(zz_ptr r, len_t m);
/*
Free any memory used by a zz_t.
*/
void zz_clear(zz_ptr r);
/*
Free the memory used by every variable in a null-terminated list of
zz_ts.
E.g.: given num1, num2 and num3, they can be freed as
zz_clears(num1, num2, num3, '\0');
*/
void zz_clears(zz_ptr num, ...);
/*
Ensure a zz_t has space for an integer whose absolute value has m
words. This is mainly used internally.
*/
void zz_fit(zz_ptr r, len_t m);
/*
Normalise a zz_t so that its internal representation does not have
any leading zero words. This function is mainly used internally.
*/
void zz_normalise(zz_ptr r);
/**********************************************************************
Comparison
**********************************************************************/
/*
Return 1 if the zz_t r is equal to the signed word c. Otherwise
return 0.
*/
int zz_equali(zz_srcptr r, sword_t c);
/*
Return 1 if the two zz_t's a and b are equal.
*/
static inline
int zz_equal(zz_srcptr a, zz_srcptr b)
{
if (a->size != b->size)
return 0;
if (a->size == 0)
return 1;
return (nn_cmp_m(a->n, b->n, BSDNT_ABS(a->size)) == 0);
}
/*
Compare the zz_t a with the signed word b. The return value
will be positive if a > b, zero if a == b and negative if a < b.
*/
int zz_cmpi(zz_srcptr a, sword_t b);
/*
Compare the zz_t's a and b. The return value will be positive if
a > b, zero if a == b and negative if a < b.
*/
int zz_cmp(zz_srcptr a, zz_srcptr b);
/*
Compare the absolute values of the zz_t's a and b. The return value
will be positive if abs(a) > abs(b), zero if abs(a) == abs(b) and
negative if abs(a) < abs(b).
*/
int zz_cmpabs(zz_srcptr a, zz_srcptr b);
/*
Return 1 if the zz_t is zero, otherwise return 0.
*/
int zz_is_zero(zz_srcptr r);
/**********************************************************************
Random generation
**********************************************************************/
/*
Generate a signed, uniformly random zz_t whose absolute value has
at most the given number of words.
*/
void zz_random(zz_ptr a, rand_t state, len_t words);
/**********************************************************************
Basic manipulation
**********************************************************************/
/*
Set the zz_t to the given signed word c.
*/
void zz_seti(zz_ptr r, sword_t c);
/*
Set r = a. The data is copied unless a and b are the same object.
*/
void zz_set(zz_ptr r, zz_srcptr a);
/*
Set r = -a. The date is copied unless r and a are the same object,
in which case its sign is simply changed.
*/
void zz_neg(zz_ptr r, zz_srcptr a);
/*
Efficiently swap the contents of a and b by swapping pointers and
other information.
*/
void zz_swap(zz_ptr a, zz_ptr b);
/*
Set the zz_t to zero.
*/
void zz_zero(zz_ptr a);
/**********************************************************************
Basic arithmetic
**********************************************************************/
/*
Set r = a + c, where c is a signed word.
*/
void zz_addi(zz_ptr r, zz_srcptr a, sword_t c);
/*
Set r = a - c, where c is a signed word.
*/
void zz_subi(zz_ptr r, zz_srcptr a, sword_t c);
/*
Set r = a + b.
*/
void zz_add(zz_ptr r, zz_srcptr a, zz_srcptr b);
/*
Set r = a - b.
*/
void zz_sub(zz_ptr r, zz_srcptr a, zz_srcptr b);
/*
Set r = a*2^exp.
*/
void zz_mul_2exp(zz_ptr r, zz_srcptr a, bits_t exp);
/*
Set r = a/2^exp.
*/
void zz_div_2exp(zz_ptr r, zz_srcptr a, bits_t exp);
/*
Set r = a*c, where c is a signed word.
*/
void zz_muli(zz_ptr r, zz_srcptr a, sword_t c);
/*
Set q such that a = bq + r with |r| < |b|. Rounding occurs towards
minus infinity. The remainder is returned as a signed word.
*/
sword_t zz_divremi(zz_ptr q, zz_srcptr a, sword_t b);
/*
Set r = a*b.
*/
void zz_mul(zz_ptr r, zz_srcptr a, zz_srcptr b);
/*
Set q and r such that a = bq + r with |r| < |b|. Rounding occurs
towards minus infinity.
*/
void zz_divrem(zz_ptr q, zz_ptr r, zz_srcptr a, zz_srcptr b);
/*
Set q such that a = bq + r with |r| < |b|. Rounding occurs towards
minus infinity.
*/
void zz_div(zz_ptr q, zz_srcptr a, zz_srcptr b);
/*
Set g to the greatest common divisor of a and b. If both are
negative or zero then g will be negative or zero, otherwise g will
be positive. If a = 0 then g = b, and similarly if b = 0 then g = a.
*/
void zz_gcd(zz_ptr g, zz_srcptr a, zz_srcptr b);
/*
As for zz_gcd except that additionally s and t are returned with
|s| < |b| and |t| < |a| and g = as + bt.
*/
void zz_xgcd(zz_ptr g, zz_ptr s, zz_ptr t, zz_srcptr a, zz_srcptr b);
/**********************************************************************
I/O
**********************************************************************/
/*
Return a string giving the decimal representation of the zz_t a.
If the value is negative, the string is prepended with a '-' sign.
If the value is 0, the string "0" is returned. The user is
required to clean up the string using free when finished.
*/
char * zz_get_str(zz_srcptr a);
/*
Set the zz_t a to the integer whose decimal representation is
given by the string str. If a negative value is required, the
string can be prepended with a '-' character.
*/
size_t zz_set_str(zz_t a, const char * str);
/*
Print the decimal representation of the zz_t a to stdout. No
newline character is output.
*/
void zz_print(zz_srcptr a);
#ifdef __cplusplus
}
#endif
#endif
| 25.279279 | 80 | 0.603231 | [
"object"
] |
1eb335d23fd07be92342fbb5fa8d76b0057caf50 | 18,619 | h | C | Pods/FirebaseUI/FirebaseUI/Core/API/FirebaseCollectionViewDataSource.h | LunarFlash/Chaty | 4460ce144501952b676aa36b45a3fe8e5a404677 | [
"MIT"
] | 423 | 2016-02-15T01:18:22.000Z | 2022-02-08T14:14:58.000Z | QnA/Pods/FirebaseUI/FirebaseUI/Core/API/FirebaseCollectionViewDataSource.h | drjackl/QnA | 16eba577f117078400bb383974a0621732642fb8 | [
"Apache-2.0"
] | 7 | 2016-04-12T12:06:24.000Z | 2019-04-02T07:25:05.000Z | QnA/Pods/FirebaseUI/FirebaseUI/Core/API/FirebaseCollectionViewDataSource.h | drjackl/QnA | 16eba577f117078400bb383974a0621732642fb8 | [
"Apache-2.0"
] | 101 | 2016-04-09T08:24:03.000Z | 2022-02-08T14:15:03.000Z | // clang-format off
/*
* Firebase UI Bindings iOS Library
*
* Copyright © 2015 Firebase - All Rights Reserved
* https://www.firebase.com
*
* 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 binaryform 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 FIREBASE 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 FIREBASE 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.
*/
// clang-format on
#import <UIKit/UIKit.h>
#import <FirebaseUI/XCodeMacros.h>
#import "FirebaseDataSource.h"
@class Firebase;
/**
* FirebaseCollectionViewDataSource provides an class that conforms to the
* UICollcetionViewDataSource protocol which allows UICollectionViews to
* implement
* FirebaseCollectionViewDataSource in order to provide a UICollectionView
* synchronized to a
* Firebase reference or query. In addition to handling all Firebase child
* events (added, changed,
* removed, moved), FirebaseCollectionViewDataSource handles UITableViewCell
* creation, either with
* the default UICollectionViewCell, prototype cells, custom
* UICollectionViewCell subclasses, or
* custom XIBs, and provides a simple [FirebaseCollectionViewDataSource
* populateCellWithBlock:]
* method which allows developers to populate the cells created for them with
* desired data from
* Firebase.
*/
@interface FirebaseCollectionViewDataSource : FirebaseDataSource<UICollectionViewDataSource>
/**
* The model class to coerce FDataSnapshots to (if desired). For instance, if
* the modelClass is set
* to [Message class] in Obj-C or Message.self in Swift, then objects of type
* Message will be
* returned instead of type FDataSnapshot.
*/
@property(strong, nonatomic, __NON_NULL) Class modelClass;
/**
* The cell class to coerce UICollectionViewCells to (if desired). For instance,
* if the cellClass is
* set to [CustomCollectionViewCell class] in Obj-C or CustomCollectionViewCell
* in Swift, then
* objects of type CustomCollectionViewCell will be returned instead of type
* UICollectionViewCell.
*/
@property(strong, nonatomic, __NON_NULL) Class cellClass;
/**
* The reuse identifier for cells in the UICollectionView.
*/
@property(strong, nonatomic, __NON_NULL) NSString *reuseIdentifier;
/**
* The UICollectionView instance that operations (inserts, removals, moves,
* etc.) are performed
* against.
*/
@property(strong, nonatomic, __NON_NULL) UICollectionView *collectionView;
/**
* Property to keep track of prototype cell use, to not register a class for the
* UICollectionView or
* do similar book keeping.
*/
@property BOOL hasPrototypeCell;
/**
* The callback to populate a subclass of UICollectionViewCell with an object
* provided by the
* datasource.
*/
@property(strong, nonatomic, __NON_NULL) void (^populateCell)
(__KINDOF(UICollectionViewCell) __NON_NULL_PTR cell, __KINDOF(NSObject) __NON_NULL_PTR object);
/**
* Initialize an instance of FirebaseCollectionViewDataSource that populates
* UICollectionViewCells
* with FDataSnapshots.
* @param ref A Firebase reference to bind the datasource to
* @param identifier A string to use as a CellReuseIdentifier
* @param collectionView An instance of a UICollectionView to bind to
* @return An instance of FirebaseCollectionViewDataSource that populates
* UICollectionViewCells with
* FDataSnapshots
*/
- (__NON_NULL instancetype)initWithRef:(__NON_NULL Firebase *)ref
cellReuseIdentifier:(__NON_NULL NSString *)identifier
view:(__NON_NULL UICollectionView *)collectionView;
/**
* Initialize an instance of FirebaseCollectionViewDataSource that populates
* UICollectionViewCells
* with FDataSnapshots. Note that this method is used when using prototype
* cells, where the cells
* don't need to be registered in the class.
* @param ref A Firebase reference to bind the datasource to
* @param identifier A string to use as a CellReuseIdentifier
* @param collectionView An instance of a UICollectionView to bind to
* @return An instance of FirebaseCollectionViewDataSource that populates
* UICollectionViewCells with
* FDataSnapshots
*/
- (__NON_NULL instancetype)initWithRef:(__NON_NULL Firebase *)ref
prototypeReuseIdentifier:(__NON_NULL NSString *)identifier
view:(__NON_NULL UICollectionView *)collectionView;
/**
* Initialize an instance of FirebaseCollectionViewDataSource that populates a
* custom subclass of
* UICollectionViewCell with FDataSnapshots.
* @param ref A Firebase reference to bind the datasource to
* @param cell A subclass of UICollectionViewCell used to populate the
* UICollectionView, defaults to
* UICollectionViewCell if nil
* @param identifier A string to use as a CellReuseIdentifier
* @param collectionView An instance of a UICollectionView to bind to
* @return An instance of FirebaseCollectionViewDataSource that populates a
* custom subclass of
* UICollectionViewCell with FDataSnapshots
*/
- (__NON_NULL instancetype)initWithRef:(__NON_NULL Firebase *)ref
cellClass:(__NULLABLE Class)cell
cellReuseIdentifier:(__NON_NULL NSString *)identifier
view:(__NON_NULL UICollectionView *)collectionView;
/**
* Initialize an instance of FirebaseCollectionViewDataSource that populates a
* custom xib with
* FDataSnapshots.
* @param ref A Firebase reference to bind the datasource to
* @param nibName The name of a xib file to create the layout for a
* UICollectionViewCell
* @param identifier A string to use as a CellReuseIdentifier
* @param collectionView An instance of a UICollectionView to bind to
* @return An instance of FirebaseCollectionViewDataSource that populates a
* custom xib with
* FDataSnapshots
*/
- (__NON_NULL instancetype)initWithRef:(__NON_NULL Firebase *)ref
nibNamed:(__NON_NULL NSString *)nibName
cellReuseIdentifier:(__NON_NULL NSString *)identifier
view:(__NON_NULL UICollectionView *)collectionView;
/**
* Initialize an instance of FirebaseCollectionViewDataSource that populates
* UICollectionViewCells
* with a custom model class.
* @param ref A Firebase reference to bind the datasource to
* @param model A custom class that FDataSnapshots are coerced to, defaults to
* FDataSnapshot if nil
* @param identifier A string to use as a CellReuseIdentifier
* @param collectionView An instance of a UICollectionView to bind to
* @return An instance of FirebaseCollectionViewDataSource that populates
* UICollectionViewCells with
* a custom model class
*/
- (__NON_NULL instancetype)initWithRef:(__NON_NULL Firebase *)ref
modelClass:(__NULLABLE Class)model
cellReuseIdentifier:(__NON_NULL NSString *)identifier
view:(__NON_NULL UICollectionView *)collectionView;
/**
* Initialize an instance of FirebaseCollectionViewDataSource that populates
* UICollectionViewCells
* with a custom model class. Note that this method is used when using prototype
* cells, where the
* cells don't need to be registered in the class.
* @param ref A Firebase reference to bind the datasource to
* @param model A custom class that FDataSnapshots are coerced to, defaults to
* FDataSnapshot if nil
* @param identifier A string to use as a CellReuseIdentifier
* @param collectionView An instance of a UICollectionView to bind to
* @return An instance of FirebaseCollectionViewDataSource that populates
* UICollectionViewCells with
* a custom model class
*/
- (__NON_NULL instancetype)initWithRef:(__NON_NULL Firebase *)ref
modelClass:(__NULLABLE Class)model
prototypeReuseIdentifier:(__NON_NULL NSString *)identifier
view:(__NON_NULL UICollectionView *)collectionView;
/**
* Initialize an instance of FirebaseCollectionViewDataSource that populates a
* custom subclass of
* UICollectionViewCell with a custom model class.
* @param ref A Firebase reference to bind the datasource to
* @param model A custom class that FDataSnapshots are coerced to, defaults to
* FDataSnapshot if nil
* @param cell A subclass of UICollectionViewCell used to populate the
* UICollectionView, defaults to
* UICollectionViewCell if nil
* @param identifier A string to use as a CellReuseIdentifier
* @param collectionView An instance of a UICollectionView to bind to
* @return An instance of FirebaseCollectionViewDataSource that populates a
* custom subclass of
* UICollectionViewCell with a custom model class
*/
- (__NON_NULL instancetype)initWithRef:(__NON_NULL Firebase *)ref
modelClass:(__NULLABLE Class)model
cellClass:(__NULLABLE Class)cell
cellReuseIdentifier:(__NON_NULL NSString *)identifier
view:(__NON_NULL UICollectionView *)collectionView;
/**
* Initialize an instance of FirebaseCollectionViewDataSource that populates a
* custom xib with a
* custom model class.
* @param ref A Firebase reference to bind the datasource to
* @param model A custom class that FDataSnapshots are coerced to, defaults to
* FDataSnapshot if nil
* @param nibName The name of a xib file to create the layout for a
* UICollectionViewCell
* @param identifier A string to use as a CellReuseIdentifier
* @param collectionView An instance of a UICollectionView to bind to
* @return An instance of FirebaseCollectionViewDataSource that populates a
* custom xib with a custom
* model class
*/
- (__NON_NULL instancetype)initWithRef:(__NON_NULL Firebase *)ref
modelClass:(__NULLABLE Class)model
nibNamed:(__NON_NULL NSString *)nibName
cellReuseIdentifier:(__NON_NULL NSString *)identifier
view:(__NON_NULL UICollectionView *)collectionView;
/**
* Initialize an instance of FirebaseCollectionViewDataSource that populates
* UICollectionViewCells
* with FDataSnapshots.
* @param query A Firebase query to bind the datasource to
* @param identifier A string to use as a CellReuseIdentifier
* @param collectionView An instance of a UICollectionView to bind to
* @return An instance of FirebaseCollectionViewDataSource that populates
* UICollectionViewCells with
* FDataSnapshots
*/
- (__NON_NULL instancetype)initWithQuery:(__NON_NULL FQuery *)query
cellReuseIdentifier:(__NON_NULL NSString *)identifier
view:(__NON_NULL UICollectionView *)collectionView;
/**
* Initialize an instance of FirebaseCollectionViewDataSource that populates
* UICollectionViewCells
* with FDataSnapshots. Note that this method is used when using prototype
* cells, where the cells
* don't need to be registered in the class.
* @param query A Firebase query to bind the datasource to
* @param identifier A string to use as a CellReuseIdentifier
* @param collectionView An instance of a UICollectionView to bind to
* @return An instance of FirebaseCollectionViewDataSource that populates
* UICollectionViewCells with
* FDataSnapshots
*/
- (__NON_NULL instancetype)initWithQuery:(__NON_NULL FQuery *)query
prototypeReuseIdentifier:(__NON_NULL NSString *)identifier
view:(__NON_NULL UICollectionView *)collectionView;
/**
* Initialize an instance of FirebaseCollectionViewDataSource that populates a
* custom subclass of
* UICollectionViewCell with FDataSnapshots.
* @param query A Firebase query to bind the datasource to
* @param cell A subclass of UICollectionViewCell used to populate the
* UICollectionView, defaults to
* UICollectionViewCell if nil
* @param identifier A string to use as a CellReuseIdentifier
* @param collectionView An instance of a UICollectionView to bind to
* @return An instance of FirebaseCollectionViewDataSource that populates a
* custom subclass of
* UICollectionViewCell with FDataSnapshots
*/
- (__NON_NULL instancetype)initWithQuery:(__NON_NULL FQuery *)query
cellClass:(__NULLABLE Class)cell
cellReuseIdentifier:(__NON_NULL NSString *)identifier
view:(__NON_NULL UICollectionView *)collectionView;
/**
* Initialize an instance of FirebaseCollectionViewDataSource that populates a
* custom xib with
* FDataSnapshots.
* @param query A Firebase query to bind the datasource to
* @param nibName The name of a xib file to create the layout for a
* UICollectionViewCell
* @param identifier A string to use as a CellReuseIdentifier
* @param collectionView An instance of a UICollectionView to bind to
* @return An instance of FirebaseCollectionViewDataSource that populates a
* custom xib with
* FDataSnapshots
*/
- (__NON_NULL instancetype)initWithQuery:(__NON_NULL FQuery *)query
nibNamed:(__NON_NULL NSString *)nibName
cellReuseIdentifier:(__NON_NULL NSString *)identifier
view:(__NON_NULL UICollectionView *)collectionView;
/**
* Initialize an instance of FirebaseCollectionViewDataSource that populates
* UICollectionViewCells
* with a custom model class.
* @param query A Firebase query to bind the datasource to
* @param model A custom class that FDataSnapshots are coerced to, defaults to
* FDataSnapshot if nil
* @param identifier A string to use as a CellReuseIdentifier
* @param collectionView An instance of a UICollectionView to bind to
* @return An instance of FirebaseCollectionViewDataSource that populates
* UICollectionViewCells with
* a custom model class
*/
- (__NON_NULL instancetype)initWithQuery:(__NON_NULL FQuery *)query
modelClass:(__NULLABLE Class)model
cellReuseIdentifier:(__NON_NULL NSString *)identifier
view:(__NON_NULL UICollectionView *)collectionView;
/**
* Initialize an instance of FirebaseCollectionViewDataSource that populates
* UICollectionViewCells
* with a custom model class. Note that this method is used when using prototype
* cells, where the
* cells don't need to be registered in the class.
* @param query A Firebase query to bind the datasource to
* @param model A custom class that FDataSnapshots are coerced to, defaults to
* FDataSnapshot if nil
* @param identifier A string to use as a CellReuseIdentifier
* @param collectionView An instance of a UICollectionView to bind to
* @return An instance of FirebaseCollectionViewDataSource that populates
* UICollectionViewCells with
* a custom model class
*/
- (__NON_NULL instancetype)initWithQuery:(__NON_NULL FQuery *)query
modelClass:(__NULLABLE Class)model
prototypeReuseIdentifier:(__NON_NULL NSString *)identifier
view:(__NON_NULL UICollectionView *)collectionView;
/**
* Initialize an instance of FirebaseCollectionViewDataSource that populates a
* custom subclass of
* UICollectionViewCell with a custom model class.
* @param query A Firebase query to bind the datasource to
* @param model A custom class that FDataSnapshots are coerced to, defaults to
* FDataSnapshot if nil
* @param cell A subclass of UICollectionViewCell used to populate the
* UICollectionView, defaults to
* UICollectionViewCell if nil
* @param identifier A string to use as a CellReuseIdentifier
* @param collectionView An instance of a UICollectionView to bind to
* @return An instance of FirebaseCollectionViewDataSource that populates a
* custom subclass of
* UICollectionViewCell with a custom model class
*/
- (__NON_NULL instancetype)initWithQuery:(__NON_NULL FQuery *)query
modelClass:(__NULLABLE Class)model
cellClass:(__NULLABLE Class)cell
cellReuseIdentifier:(__NON_NULL NSString *)identifier
view:(__NON_NULL UICollectionView *)collectionView;
/**
* Initialize an instance of FirebaseCollectionViewDataSource that populates a
* custom xib with a
* custom model class.
* @param query A Firebase query to bind the datasource to
* @param model A custom class that FDataSnapshots are coerced to, defaults to
* FDataSnapshot if nil
* @param nibName The name of a xib file to create the layout for a
* UICollectionViewCell
* @param identifier A string to use as a CellReuseIdentifier
* @param collectionView An instance of a UICollectionView to bind to
* @return An instance of FirebaseCollectionViewDataSource that populates a
* custom xib with a custom
* model class
*/
- (__NON_NULL instancetype)initWithQuery:(__NON_NULL FQuery *)query
modelClass:(__NULLABLE Class)model
nibNamed:(__NON_NULL NSString *)nibName
cellReuseIdentifier:(__NON_NULL NSString *)identifier
view:(__NON_NULL UICollectionView *)collectionView;
/**
* This method populates the fields of a UICollectionViewCell or subclass given
* an FDataSnapshot (or
* custom model object).
* @param callback A block which returns an initialized UICollectionViewCell (or
* subclass) and the
* corresponding object to populate the cell with.
*/
- (void)populateCellWithBlock:
(__NON_NULL void (^)(__KINDOF(UICollectionViewCell)__NON_NULL_PTR cell,
__KINDOF(NSObject)__NON_NULL_PTR object))callback;
@end
| 44.436754 | 99 | 0.73715 | [
"object",
"model"
] |
144655f4d5de0f5bf9199cff5b82aac9e1f111eb | 2,615 | h | C | src/qt/qtwebkit/Source/WebKit2/UIProcess/gtk/WebContextMenuProxyGtk.h | viewdy/phantomjs | eddb0db1d253fd0c546060a4555554c8ee08c13c | [
"BSD-3-Clause"
] | 1 | 2015-05-27T13:52:20.000Z | 2015-05-27T13:52:20.000Z | src/qt/qtwebkit/Source/WebKit2/UIProcess/gtk/WebContextMenuProxyGtk.h | mrampersad/phantomjs | dca6f77a36699eb4e1c46f7600cca618f01b0ac3 | [
"BSD-3-Clause"
] | null | null | null | src/qt/qtwebkit/Source/WebKit2/UIProcess/gtk/WebContextMenuProxyGtk.h | mrampersad/phantomjs | dca6f77a36699eb4e1c46f7600cca618f01b0ac3 | [
"BSD-3-Clause"
] | 1 | 2022-02-18T10:41:38.000Z | 2022-02-18T10:41:38.000Z | /*
* Copyright (C) 2011 Igalia S.L.
*
* 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.
*/
#ifndef WebContextMenuProxyGtk_h
#define WebContextMenuProxyGtk_h
#if ENABLE(CONTEXT_MENUS)
#include "WebContextMenuProxy.h"
#include <WebCore/ContextMenu.h>
#include <WebCore/IntPoint.h>
namespace WebKit {
class WebContextMenuItemData;
class WebPageProxy;
class WebContextMenuProxyGtk : public WebContextMenuProxy {
public:
static PassRefPtr<WebContextMenuProxyGtk> create(GtkWidget* webView, WebPageProxy* page)
{
return adoptRef(new WebContextMenuProxyGtk(webView, page));
}
~WebContextMenuProxyGtk();
virtual void showContextMenu(const WebCore::IntPoint&, const Vector<WebContextMenuItemData>&);
virtual void hideContextMenu();
void populate(Vector<WebCore::ContextMenuItem>&);
GtkMenu* gtkMenu() const { return m_menu.platformDescription(); }
private:
WebContextMenuProxyGtk(GtkWidget*, WebPageProxy*);
void append(WebCore::ContextMenuItem&);
void populate(const Vector<WebContextMenuItemData>&);
static void menuPositionFunction(GtkMenu*, gint*, gint*, gboolean*, WebContextMenuProxyGtk*);
GtkWidget* m_webView;
WebPageProxy* m_page;
WebCore::ContextMenu m_menu;
WebCore::IntPoint m_popupPosition;
};
} // namespace WebKit
#endif // ENABLE(CONTEXT_MENUS)
#endif // WebContextMenuProxyGtk_h
| 36.319444 | 98 | 0.763289 | [
"vector"
] |
1450c64438c13dcd9b76b20870c94622caa3fc66 | 888 | h | C | Toolbox/Win32_utilities/win32_clut.h | pk1954/Solutions | b224522283f82cb7d73b8005e35e0c045edc2fc0 | [
"MIT"
] | null | null | null | Toolbox/Win32_utilities/win32_clut.h | pk1954/Solutions | b224522283f82cb7d73b8005e35e0c045edc2fc0 | [
"MIT"
] | null | null | null | Toolbox/Win32_utilities/win32_clut.h | pk1954/Solutions | b224522283f82cb7d73b8005e35e0c045edc2fc0 | [
"MIT"
] | null | null | null | // win32_clut.h :
//
#pragma once
#include "NamedType.h"
#include <vector>
using std::vector;
using CLUT_INDEX = NamedType< int, struct CLUT_INDEX_Parameter >;
class CLUT
{
public:
CLUT()
{
m_uiBase = CLUT_INDEX(0);
m_colorHi = RGB(255, 255, 255);
};
virtual ~CLUT() {};
void Allocate(CLUT_INDEX const);
void SetClutBase(CLUT_INDEX const);
void SetColorHi(COLORREF const);
COLORREF GetColor(CLUT_INDEX index) const
{
assert(index.GetValue() < static_cast<int>(m_data.size()));
return m_data[ index.GetValue() ];
};
UINT GetSize() const
{
return static_cast<UINT>(m_data.size());
};
COLORREF GetColorHi() const
{
return m_colorHi;
};
private:
void setTableValues();
CLUT_INDEX m_uiBase;
vector<DWORD> m_data;
COLORREF m_colorHi;
};
| 17.076923 | 65 | 0.605856 | [
"vector"
] |
1463d6de18adb9b56a08df956a1042420f353ca4 | 609 | h | C | shared_memory/pshm_ucase.h | MiserableLife/Playground-Linux | 82c0437d3367705aa7da3eb46736bb8fb460394a | [
"MIT"
] | null | null | null | shared_memory/pshm_ucase.h | MiserableLife/Playground-Linux | 82c0437d3367705aa7da3eb46736bb8fb460394a | [
"MIT"
] | null | null | null | shared_memory/pshm_ucase.h | MiserableLife/Playground-Linux | 82c0437d3367705aa7da3eb46736bb8fb460394a | [
"MIT"
] | null | null | null | #include <sys/mman.h>
#include <fcntl.h>
#include <semaphore.h>
#include <sys/stat.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#define errExit(msg) do { perror(msg); exit(EXIT_FAILURE); \
} while (0)
#define BUF_SIZE 1024 /* Maximum size for exchanged string */
/* Define a structure that will be imposed on the shared
memory object */
struct shmbuf {
sem_t sem1; /* POSIX unnamed semaphore */
sem_t sem2; /* POSIX unnamed semaphore */
size_t cnt; /* Number of bytes used in 'buf' */
char buf[BUF_SIZE]; /* Data being transferred */
};
| 26.478261 | 63 | 0.642036 | [
"object"
] |
1464ac1999e2d1d4a680420c5e7593cef0955c2d | 4,291 | h | C | Source/Framework/Core/RenderAPI/TeVertexDataDesc.h | GameDevery/TweedeFrameworkRedux | 69a28fe171db33d00066b97b9b6bf89f6ef3e3a4 | [
"MIT"
] | 57 | 2019-09-02T01:10:37.000Z | 2022-01-11T06:28:10.000Z | Source/Framework/Core/RenderAPI/TeVertexDataDesc.h | GameDevery/TweedeFrameworkRedux | 69a28fe171db33d00066b97b9b6bf89f6ef3e3a4 | [
"MIT"
] | null | null | null | Source/Framework/Core/RenderAPI/TeVertexDataDesc.h | GameDevery/TweedeFrameworkRedux | 69a28fe171db33d00066b97b9b6bf89f6ef3e3a4 | [
"MIT"
] | 6 | 2020-02-29T17:19:30.000Z | 2021-10-30T04:29:22.000Z | #pragma once
#include "TeCorePrerequisites.h"
#include "RenderAPI/TeVertexDeclaration.h"
namespace te
{
/**
* Contains information about layout of vertices in a buffer. This is very similar to VertexDeclaration but unlike
* VertexDeclaration it has no render API object to back it up and is very lightweight.
*/
class TE_CORE_EXPORT VertexDataDesc
{
public:
VertexDataDesc() = default;
/**
* Informs the internal buffer that it needs to make room for the specified vertex element. If a vertex with same
* stream and semantics already exists it will just be updated.
*
* @param[in] type Type of the vertex element. Determines size.
* @param[in] semantic Semantic that allows the engine to connect the data to a shader input slot.
* @param[in] semanticIdx (optional) If there are multiple semantics with the same name, use different
* index to differentiate between them.
* @param[in] streamIdx (optional) Zero-based index of the stream. Each stream will internally be
* represented as a single vertex buffer.
* @param[in] instanceStepRate Determines at what rate does vertex element data advance. Zero means each vertex
* will advance the data pointer and receive new data (standard behaviour). Values
* larger than one are relevant for instanced rendering and determine how often do
* instances advance the vertex element (for example a value of 1 means each
* instance will retrieve a new value for this vertex element, a value of 2 means
* each second instance will, etc.).
*/
void AddVertElem(VertexElementType type, VertexElementSemantic semantic, UINT32 semanticIdx = 0,
UINT32 streamIdx = 0, UINT32 instanceStepRate = 0);
/** Query if we have vertex data for the specified semantic. */
bool HasElement(VertexElementSemantic semantic, UINT32 semanticIdx = 0, UINT32 streamIdx = 0) const;
/** Returns the size in bytes of the vertex element with the specified semantic. */
UINT32 GetElementSize(VertexElementSemantic semantic, UINT32 semanticIdx = 0, UINT32 streamIdx = 0) const;
/** Returns offset of the vertex from start of the stream in bytes. */
UINT32 GetElementOffsetFromStream(VertexElementSemantic semantic, UINT32 semanticIdx = 0, UINT32 streamIdx = 0) const;
/** Gets vertex stride in bytes (offset from one vertex to another) in the specified stream. */
UINT32 GetVertexStride(UINT32 streamIdx) const;
/** Gets vertex stride in bytes (offset from one vertex to another) in all the streams. */
UINT32 GetVertexStride() const;
/** Gets offset in bytes from the start of the internal buffer to the start of the specified stream. */
UINT32 GetStreamOffset(UINT32 streamIdx) const;
/** Returns the number of vertex elements. */
UINT32 GetNumElements() const { return (UINT32)_vertexElements.size(); }
/** Returns the vertex element at the specified index. */
const VertexElement& GetElement(UINT32 idx) const { return _vertexElements[idx]; }
/** Returns the vertex element with the specified semantic. */
const VertexElement* GetElement(VertexElementSemantic semantic, UINT32 semanticIdx = 0, UINT32 streamIdx = 0) const;
/** Creates a list of vertex elements from internal data. */
Vector<VertexElement> CreateElements() const;
/** Creates a new empty vertex data descriptor. */
static SPtr<VertexDataDesc> Create();
private:
friend class Mesh;
/** Returns the largest stream index of all the stored vertex elements. */
UINT32 GetMaxStreamIdx() const;
/** Checks if any of the vertex elements use the specified stream index. */
bool HasStream(UINT32 streamIdx) const;
/** Removes a vertex element of the specified type and semantics if it exists. */
void ClearIfItExists(VertexElementType type, VertexElementSemantic semantic, UINT32 semanticIdx, UINT32 streamIdx);
private:
Vector<VertexElement> _vertexElements;
};
}
| 49.895349 | 126 | 0.679562 | [
"mesh",
"render",
"object",
"vector"
] |
1469e1138512e006cedf63818ebb01ca61e5f9d2 | 44,143 | c | C | mame/src/mame/video/galaxian.c | nitrologic/emu | be2c9b72d81c3aea85ad4fd18fa4f731b31f338a | [
"Unlicense"
] | null | null | null | mame/src/mame/video/galaxian.c | nitrologic/emu | be2c9b72d81c3aea85ad4fd18fa4f731b31f338a | [
"Unlicense"
] | null | null | null | mame/src/mame/video/galaxian.c | nitrologic/emu | be2c9b72d81c3aea85ad4fd18fa4f731b31f338a | [
"Unlicense"
] | null | null | null | /***************************************************************************
Galaxian-derived video hardware
****************************************************************************
Video timing:
The master clock is an 18.432MHz crystal. It is divided by 3 by
a pair of J/K flip-flops to 6.144MHz. This 6MHz signal is used to
drive most of the video logic. Note that due to the way the
divide-by-3 circuit is implemented, the duty cycle of the 6MHz
signal is 66% (i.e., it is high for 2 18MHz clocks and low for 1).
This is important for accurate stars rendering.
Horizontal timing:
H counts from 010000000 (128) to 111111111 (511), giving 384
total H clocks per scanline
However, the top bit is inverted to become 256H, so when reading
the schematics it's really counting from:
110000000 -> 111111111 (blanking period)
and then from:
000000000 -> 011111111 (main portion of screen = 256 pixels)
HBLANK is a flip-flop clocked by 2H:
* It is held clear when 256H = 0 (main portion of screen)
* The D input is connected to !(64H & 32H & 16H & 8H)
* It is clocked to 1 when H=130
* It is clocked to 0 when H=250
* This gives 264 total non-blanked pixels:
6 additional pixels on the left (H=250..255)
256 main area pixels (H=256..511)
2 additional pixels on the right (H=128..129)
HSYNC is a flip-flop clocked by 16H:
* It is held clear when 256H = 0 (main portion of screen)
* The D input is connected to !(!64H & 32H)
* HSYNC is the /Q output
* It is clocked to 1 when H=176
* It is clocked to 0 when H=208
Vertical timing:
V counts from 011111000 (248) to 111111111 (511), giving 264
total V clocks per frame
IMPORTANT: the V sync chain is clocked by HSYNC. This means
that for the first 48 H clocks of the blanking period, the
V counter is one behind. This is important to take into account
for sprite and missile positioning.
VBLANK is a flip-flop clocked by 16V:
* The D input is connected to !(128V & 64V & 32V)
* It is clocked to 1 when V=496
* It is clocked to 0 when V=272
* This gives 224 total non-blanked pixels
VSYNC is set to !256V:
* It is set to 1 when V=248
* It is cleared to 0 when V=256
Sprites and missiles:
During the HBLANK period, sprites and missiles are processed.
Sprites are rendered into the line buffer, which was cleared
during the visible portion of the previous scanline.
It takes 8 H clocks to set up a sprite, and 16 to render it
to the line buffer. The setup clocks are overlapped with the
rendering clocks. In theory this would result in enough time
to render 128/16 = 8 sprites. However, the setup does not
begin until after HBLANK, so there is only enough time to
render the first 7 1/2 entries.
Interleaved with the setup for sprites is setup for the
shell and missile rendering. Shells and missiles are rendered
realtime during the visible portion of the frame, and are
effectively color-ORed directly into the final RGB output.
During the HBLANK setup period, each shell/missile entry is
compared against the current V position; if an exact match
is found, the H position is loaded into a dedicated 8-bit
counter. The counter clocks each pixel during the active video
period; when it reaches $FC it enables the output until it
hits zero, at which point it shuts itself off. Because there
is only one counter for shells and one for missiles, only one
shell and one missile can be specified per scanline. The last
matching entry found will always win.
The difference between shell and missile is that shells
populate the first 7 entries and are rendered as white,
whereas missiles populate the final entry and are rendered
as yellow.
Here is the detailed sequence of events for sprite and
missile/shell rendering during the first 24 H clocks of
HBLANK:
H=080: HPOSI=objram[40], /VPL latches V+objram[40]
H=081: HPOSI=objram[40]
H=082: HPOSI=objram[41], /OBJ DATA L latches picture number, H/V flip
H=083: HPOSI=objram[41]
H=084: HPOSI=objram[42], /COL L latches low 3 bits as color
H=085: HPOSI=objram[42]
H=086: HPOSI=objram[43]
H=087: HPOSI=objram[43], /CNTR LD latches X position
<sprite 0 begins rendering>
H=088: HPOSI=objram[40], /VPL latches V+objram[40]
H=089: HPOSI=objram[40]
H=08A: HPOSI=objram[61]
H=08B: HPOSI=objram[61], MSLD is latched if Y position matches shell
H=08C: HPOSI=objram[42]
H=08D: HPOSI=objram[42]
H=08E: HPOSI=objram[63]
H=08F: HPOSI=objram[63], /SLD fires to latch down shell counter value
H=090: HPOSI=objram[44], /VPL latches V+objram[44]
H=091: HPOSI=objram[44]
H=092: HPOSI=objram[45], /OBJ DATA L latches picture number, H/V flip
H=093: HPOSI=objram[45]
H=094: HPOSI=objram[46], /COL L latches low 3 bits as color
H=095: HPOSI=objram[46]
H=096: HPOSI=objram[47]
H=097: HPOSI=objram[47], /CNTR LD latches X position
<sprite 1 begins rendering>
From this, you can see the object RAM layout looks like:
objram[40] = vertical position of sprite 0
objram[41] = picture number and H/V flip of sprite 0
objram[42] = color of sprite 0
objram[43] = horizontal position of sprite 0
objram[61] = vertical position of shell 0
objram[63] = horizontal count until shell 0 starts rendering
A vertical match for a sprite is true if ((V + vpos) & 0xf0) == 0xf0.
A vertical match for a shell/missile is if ((V + vpos) & 0xff) == 0xff.
Overall, the process for sprites and missiles during HBLANK looks
like this:
H=080: begin setup sprite 0
H=082: begin HBLANK
H=088: begin render sprite 0; begin setup shell 0
H=090: begin setup sprite 1
H=098: begin render sprite 1; begin setup shell 1
H=0A0: begin setup sprite 2
H=0A8: begin render sprite 2; begin setup shell 2
H=0B0: VSYNC increments V counter; subsequent sprites match V+1
H=0B0: begin setup sprite 3
H=0B8: begin render sprite 3; begin setup shell 3
H=0C0: begin setup sprite 4
H=0C8: begin render sprite 4; begin setup shell 4
H=0D0: begin setup sprite 5
H=0D8: begin render sprite 5; begin setup shell 5
H=0E0: begin setup sprite 6
H=0E8: begin render sprite 6; begin setup shell 6
H=0F0: begin setup sprite 7
H=0F8: begin render sprite 7; begin setup missile
H=0FA: end HBLANK
H=100: finish render sprite 7 (only 1/2 way through)
/VPL: H=xxxxxx000 -> latches sum of V+HPOSI for vertical positioning
/COL L: H=xxxxxx100 -> latches HPOSI into color register (low 3 bits)
/LD: H=xxxxxx111 -> shift register load from ROM
/CNTR CLR: H=0xxxx0111 -> resets line buffer counter to 0
/OBJ DATA L: H=1xxxx0010 -> latches HPOSI into picture number latch
/CNTR LD: H=1xxxx0111 -> latches HPOSI into line buffer counter (sprite X position)
/SLD: H=1xxxx1111 -> latches down counter until shell (except when /MLD)
/MLD: H=1x1111111 -> latches down counter until missile
VRAM addresses:
addr video
VRA7 = A9 SUM7
VRA8 = A8 SUM6
VRA6 = A7 SUM5
VRA5 = A6 SUM4
VRA4 = A5 SUM3
VRA3 = A4 128HB
VRA0 = A3 64HB
VRA1 = A2 32HB
VRA2 = A1 16HB
VRA9 = A0 8HB
OBJRAM addresses:
addr 256H=0 256H=1
RA4 = A0 4H 2H
RA7 = A1 8HB 4H
RA1 = A2 16HB 16HB
RA0 = A3 32HB 32HB
RA5 = A4 64HB 64HB
RA6 = A5 128HB (2H & 8HB)
RA3 = A6 256H 256H
RA2 = A7 0 0
H=80: 00,00,01,01,02,02,03,03 00,00,21,21,02,02,23,23
H=90: 04,04,05,05,06,06,07,07 04,04,25,25,06,06,27,27
H=A0: 08,08,09,09,0A,0A,0B,0B 08,08,29,29,0A,0A,2B,2B
H=B0: 0C,0C,0D,0D,0E,0E,0F,0F 0C,0C,2D,2D,0E,0E,2F,2F
***************************************************************************/
#include "driver.h"
#include "video/resnet.h"
#include "includes/galaxian.h"
/*************************************
*
* Constants
*
*************************************/
#define STAR_RNG_PERIOD ((1 << 17) - 1)
#define RGB_MAXIMUM 224
/*************************************
*
* Global variables
*
*************************************/
/* rendering callbacks */
galaxian_draw_bullet_func galaxian_draw_bullet_ptr;
galaxian_draw_background_func galaxian_draw_background_ptr;
/* tile/sprite modification callbacks */
galaxian_extend_tile_info_func galaxian_extend_tile_info_ptr;
galaxian_extend_sprite_info_func galaxian_extend_sprite_info_ptr;
/* global tweaks */
UINT8 galaxian_frogger_adjust;
UINT8 galaxian_sfx_tilemap;
UINT8 galaxian_sprite_clip_start;
UINT8 galaxian_sprite_clip_end;
/*************************************
*
* Local variables
*
*************************************/
static tilemap *bg_tilemap;
static UINT8 flipscreen_x;
static UINT8 flipscreen_y;
static UINT8 background_enable;
static UINT8 background_red;
static UINT8 background_green;
static UINT8 background_blue;
static UINT32 star_rng_origin;
static UINT32 star_rng_origin_frame;
static rgb_t star_color[64];
static UINT8 *stars;
static UINT8 stars_enabled;
static UINT8 stars_blink_state;
static rgb_t bullet_color[8];
static UINT8 gfxbank[5];
/*************************************
*
* Function prototypes
*
*************************************/
static void state_save_register(running_machine *machine);
static TILE_GET_INFO( bg_get_tile_info );
static void sprites_draw(running_machine *machine, bitmap_t *bitmap, const rectangle *cliprect, const UINT8 *spritebase);
static void stars_init(running_machine *machine);
static void stars_update_origin(running_machine *machine);
static void stars_draw_row(bitmap_t *bitmap, int maxx, int y, UINT32 star_offs, UINT8 starmask);
static void bullets_draw(running_machine *machine, bitmap_t *bitmap, const rectangle *cliprect, const UINT8 *base);
/*************************************
*
* Palette setup
*
*************************************/
PALETTE_INIT( galaxian )
{
static const int rgb_resistances[3] = { 1000, 470, 220 };
double rweights[3], gweights[3], bweights[2];
int i, minval, midval, maxval, len;
UINT8 starmap[4];
/*
Sprite/tilemap colors are mapped through a color PROM as follows:
bit 7 -- 220 ohm resistor -- BLUE
-- 470 ohm resistor -- BLUE
-- 220 ohm resistor -- GREEN
-- 470 ohm resistor -- GREEN
-- 1 kohm resistor -- GREEN
-- 220 ohm resistor -- RED
-- 470 ohm resistor -- RED
bit 0 -- 1 kohm resistor -- RED
In parallel with these resistors are a pair of 150 ohm and 100 ohm
resistors on each R,G,B component that are connected to the star
generator.
And in parallel with the whole mess are a set of 100 ohm resistors
on each R,G,B component that are enabled when a shell/missile is
enabled.
When computing weights, we use RGB_MAXIMUM as the maximum to give
headroom for stars and shells/missiles. This is not fully accurate,
but if we included all possible sources in parallel, the brightness
of the main game would be very low to allow for all the oversaturation
of the stars and shells/missiles.
*/
compute_resistor_weights(0, RGB_MAXIMUM, -1.0,
3, &rgb_resistances[0], rweights, 470, 0,
3, &rgb_resistances[0], gweights, 470, 0,
2, &rgb_resistances[1], bweights, 470, 0);
/* decode the palette first */
len = memory_region_length(machine, "proms");
for (i = 0; i < len; i++)
{
UINT8 bit0, bit1, bit2, r, g, b;
/* red component */
bit0 = BIT(color_prom[i],0);
bit1 = BIT(color_prom[i],1);
bit2 = BIT(color_prom[i],2);
r = combine_3_weights(rweights, bit0, bit1, bit2);
/* green component */
bit0 = BIT(color_prom[i],3);
bit1 = BIT(color_prom[i],4);
bit2 = BIT(color_prom[i],5);
g = combine_3_weights(gweights, bit0, bit1, bit2);
/* blue component */
bit0 = BIT(color_prom[i],6);
bit1 = BIT(color_prom[i],7);
b = combine_2_weights(bweights, bit0, bit1);
palette_set_color(machine, i, MAKE_RGB(r,g,b));
}
/*
The maximum sprite/tilemap resistance is ~130 Ohms with all RGB
outputs enabled (1/(1/1000 + 1/470 + 1/220)). Since we normalized
to RGB_MAXIMUM, this maps RGB_MAXIMUM -> 130 Ohms.
The stars are at 150 Ohms for the LSB, and 100 Ohms for the MSB.
This means the 3 potential values are:
150 Ohms -> RGB_MAXIMUM * 130 / 150
100 Ohms -> RGB_MAXIMUM * 130 / 100
60 Ohms -> RGB_MAXIMUM * 130 / 60
Since we can't saturate that high, we instead approximate this
by compressing the values proportionally into the 194->255 range.
*/
minval = RGB_MAXIMUM * 130 / 150;
midval = RGB_MAXIMUM * 130 / 100;
maxval = RGB_MAXIMUM * 130 / 60;
/* compute the values for each of 4 possible star values */
starmap[0] = 0;
starmap[1] = minval;
starmap[2] = minval + (255 - minval) * (midval - minval) / (maxval - minval);
starmap[3] = 255;
/* generate the colors for the stars */
for (i = 0; i < 64; i++)
{
UINT8 bit0, bit1, r, g, b;
/* bit 5 = red @ 150 Ohm, bit 4 = red @ 100 Ohm */
bit0 = BIT(i,5);
bit1 = BIT(i,4);
r = starmap[(bit1 << 1) | bit0];
/* bit 3 = green @ 150 Ohm, bit 2 = green @ 100 Ohm */
bit0 = BIT(i,3);
bit1 = BIT(i,2);
g = starmap[(bit1 << 1) | bit0];
/* bit 1 = blue @ 150 Ohm, bit 0 = blue @ 100 Ohm */
bit0 = BIT(i,1);
bit1 = BIT(i,0);
b = starmap[(bit1 << 1) | bit0];
/* set the RGB color */
star_color[i] = MAKE_RGB(r, g, b);
}
/* default bullet colors are white for the first 7, and yellow for the last one */
for (i = 0; i < 7; i++)
bullet_color[i] = MAKE_RGB(0xff,0xff,0xff);
bullet_color[7] = MAKE_RGB(0xff,0xff,0x00);
}
PALETTE_INIT( moonwar )
{
PALETTE_INIT_CALL(galaxian);
/* wire mod to connect the bullet blue output to the 220 ohm resistor */
bullet_color[7] = MAKE_RGB(0xef,0xef,0x97);
}
/*************************************
*
* Common video init
*
*************************************/
VIDEO_START( galaxian )
{
/* create a tilemap for the background */
if (!galaxian_sfx_tilemap)
{
/* normal galaxian hardware is row-based and individually scrolling columns */
bg_tilemap = tilemap_create(machine, bg_get_tile_info, tilemap_scan_rows, GALAXIAN_XSCALE*8,8, 32,32);
tilemap_set_scroll_cols(bg_tilemap, 32);
tilemap_set_scrolldx(bg_tilemap, 0, -GALAXIAN_XSCALE * 128);
tilemap_set_scrolldy(bg_tilemap, 0, 8);
}
else
{
/* sfx hardware is column-based and individually scrolling rows */
bg_tilemap = tilemap_create(machine, bg_get_tile_info, tilemap_scan_cols, GALAXIAN_XSCALE*8,8, 32,32);
tilemap_set_scroll_rows(bg_tilemap, 32);
tilemap_set_scrolldx(bg_tilemap, 0, -GALAXIAN_XSCALE * 128);
tilemap_set_scrolldy(bg_tilemap, 0, 8);
}
tilemap_set_transparent_pen(bg_tilemap, 0);
/* initialize globals */
flipscreen_x = 0;
flipscreen_y = 0;
background_enable = 0;
background_blue = 0;
background_red = 0;
background_green = 0;
/* initialize stars */
stars_init(machine);
/* register for save states */
state_save_register(machine);
}
static void state_save_register(running_machine *machine)
{
state_save_register_global(machine, flipscreen_x);
state_save_register_global(machine, flipscreen_y);
state_save_register_global(machine, background_enable);
state_save_register_global(machine, background_red);
state_save_register_global(machine, background_green);
state_save_register_global(machine, background_blue);
state_save_register_global_array(machine, gfxbank);
state_save_register_global(machine, stars_enabled);
state_save_register_global(machine, star_rng_origin);
state_save_register_global(machine, star_rng_origin_frame);
state_save_register_global(machine, stars_blink_state);
}
/*************************************
*
* Common video update
*
*************************************/
VIDEO_UPDATE( galaxian )
{
/* draw the background layer (including stars) */
(*galaxian_draw_background_ptr)(screen->machine, bitmap, cliprect);
/* draw the tilemap characters over top */
tilemap_draw(bitmap, cliprect, bg_tilemap, 0, 0);
/* render the sprites next */
sprites_draw(screen->machine, bitmap, cliprect, &spriteram[0x40]);
/* if we have bullets to draw, render them following */
if (galaxian_draw_bullet_ptr != NULL)
bullets_draw(screen->machine, bitmap, cliprect, &spriteram[0x60]);
return 0;
}
/*************************************
*
* Background tilemap
*
*************************************/
static TILE_GET_INFO( bg_get_tile_info )
{
UINT8 x = tile_index & 0x1f;
UINT16 code = videoram[tile_index];
UINT8 attrib = spriteram[x*2+1];
UINT8 color = attrib & 7;
if (galaxian_extend_tile_info_ptr != NULL)
(*galaxian_extend_tile_info_ptr)(&code, &color, attrib, x);
SET_TILE_INFO(0, code, color, 0);
}
WRITE8_HANDLER( galaxian_videoram_w )
{
/* update any video up to the current scanline */
video_screen_update_now(space->machine->primary_screen);
/* store the data and mark the corresponding tile dirty */
videoram[offset] = data;
tilemap_mark_tile_dirty(bg_tilemap, offset);
}
WRITE8_HANDLER( galaxian_objram_w )
{
/* update any video up to the current scanline */
video_screen_update_now(space->machine->primary_screen);
/* store the data */
spriteram[offset] = data;
/* the first $40 bytes affect the tilemap */
if (offset < 0x40)
{
/* even entries control the scroll position */
if ((offset & 0x01) == 0)
{
/* Frogger: top and bottom 4 bits swapped entering the adder */
if (galaxian_frogger_adjust)
data = (data >> 4) | (data << 4);
if (!galaxian_sfx_tilemap)
tilemap_set_scrolly(bg_tilemap, offset >> 1, data);
else
tilemap_set_scrollx(bg_tilemap, offset >> 1, GALAXIAN_XSCALE*data);
}
/* odd entries control the color base for the row */
else
{
for (offset >>= 1; offset < 0x0400; offset += 32)
tilemap_mark_tile_dirty(bg_tilemap, offset);
}
}
}
/*************************************
*
* Sprite rendering
*
*************************************/
static void sprites_draw(running_machine *machine, bitmap_t *bitmap, const rectangle *cliprect, const UINT8 *spritebase)
{
rectangle clip = *cliprect;
int sprnum;
int clip_ofs = (flipscreen_x ? 16 : 0);
/* 16 of the 256 pixels of the sprites are hard-clipped at the line buffer */
/* according to the schematics, it should be the first 16 pixels; however, */
/* some bootlegs demonstrate that this can be shifted to other positions. */
clip.min_x = MAX(clip.min_x, (galaxian_sprite_clip_start - clip_ofs) * GALAXIAN_XSCALE);
clip.max_x = MIN(clip.max_x, (galaxian_sprite_clip_end - clip_ofs + 1) * GALAXIAN_XSCALE - 1);
/* The line buffer is only written if it contains a '0' currently; */
/* it is cleared during the visible area, and populated during HBLANK */
/* To simulate this, we render backwards so that lower numbered sprites */
/* have priority over higher numbered sprites. */
for (sprnum = 7; sprnum >= 0; sprnum--)
{
const UINT8 *base = &spritebase[sprnum * 4];
/* Frogger: top and bottom 4 bits swapped entering the adder */
UINT8 base0 = galaxian_frogger_adjust ? ((base[0] >> 4) | (base[0] << 4)) : base[0];
/* the first three sprites match against y-1 */
UINT8 sy = 240 - (base0 - (sprnum < 3));
UINT16 code = base[1] & 0x3f;
UINT8 flipx = base[1] & 0x40;
UINT8 flipy = base[1] & 0x80;
UINT8 color = base[2] & 7;
UINT8 sx = base[3];
/* extend the sprite information */
if (galaxian_extend_sprite_info_ptr != NULL)
(*galaxian_extend_sprite_info_ptr)(base, &sx, &sy, &flipx, &flipy, &code, &color);
/* apply flipscreen in X direction */
if (flipscreen_x)
{
sx = 242 - sx; // + 8 - HOFS
flipx = !flipx;
}
/* apply flipscreen in Y direction */
if (flipscreen_y)
{
sy = 240 - sy;
flipy = !flipy;
}
/* draw */
drawgfx_transpen(bitmap, &clip,
machine->gfx[1],
code, color,
flipx, flipy,
GALAXIAN_H0START + GALAXIAN_XSCALE * sx, sy, 0);
}
}
/*************************************
*
* Bullets rendering
*
*************************************/
static void bullets_draw(running_machine *machine, bitmap_t *bitmap, const rectangle *cliprect, const UINT8 *base)
{
int y;
/* iterate over scanlines */
for (y = cliprect->min_y; y <= cliprect->max_y; y++)
{
UINT8 shell = 0xff, missile = 0xff;
UINT8 effy;
int which;
/* the first 3 entries match Y-1 */
effy = flipscreen_y ? ((y - 1) ^ 255) : (y - 1);
for (which = 0; which < 3; which++)
if ((UINT8)(base[which*4+1] + effy) == 0xff)
shell = which;
/* remaining entries match Y */
effy = flipscreen_y ? (y ^ 255) : y;
for (which = 3; which < 8; which++)
if ((UINT8)(base[which*4+1] + effy) == 0xff)
{
if (which != 7)
shell = which;
else
missile = which;
}
/* draw the shell */
if (shell != 0xff)
(*galaxian_draw_bullet_ptr)(machine, bitmap, cliprect, shell, 255 - base[shell*4+3], y);
if (missile != 0xff)
(*galaxian_draw_bullet_ptr)(machine, bitmap, cliprect, missile, 255 - base[missile*4+3], y);
}
}
/*************************************
*
* Screen orientation
*
*************************************/
WRITE8_HANDLER( galaxian_flip_screen_x_w )
{
if (flipscreen_x != (data & 0x01))
{
video_screen_update_now(space->machine->primary_screen);
/* when the direction changes, we count a different number of clocks */
/* per frame, so we need to reset the origin of the stars to the current */
/* frame before we flip */
stars_update_origin(space->machine);
flipscreen_x = data & 0x01;
tilemap_set_flip(bg_tilemap, (flipscreen_x ? TILEMAP_FLIPX : 0) | (flipscreen_y ? TILEMAP_FLIPY : 0));
}
}
WRITE8_HANDLER( galaxian_flip_screen_y_w )
{
if (flipscreen_y != (data & 0x01))
{
video_screen_update_now(space->machine->primary_screen);
flipscreen_y = data & 0x01;
tilemap_set_flip(bg_tilemap, (flipscreen_x ? TILEMAP_FLIPX : 0) | (flipscreen_y ? TILEMAP_FLIPY : 0));
}
}
WRITE8_HANDLER( galaxian_flip_screen_xy_w )
{
galaxian_flip_screen_x_w(space, offset, data);
galaxian_flip_screen_y_w(space, offset, data);
}
/*************************************
*
* Background controls
*
*************************************/
WRITE8_HANDLER( galaxian_stars_enable_w )
{
if ((stars_enabled ^ data) & 0x01)
video_screen_update_now(space->machine->primary_screen);
if (!stars_enabled && (data & 0x01))
{
/* on the rising edge of this, the CLR on the shift registers is released */
/* this resets the "origin" of this frame to 0 minus the number of clocks */
/* we have counted so far */
star_rng_origin = STAR_RNG_PERIOD - (video_screen_get_vpos(space->machine->primary_screen) * 512 + video_screen_get_hpos(space->machine->primary_screen));
star_rng_origin_frame = video_screen_get_frame_number(space->machine->primary_screen);
}
stars_enabled = data & 0x01;
}
WRITE8_HANDLER( scramble_background_enable_w )
{
video_screen_update_now(space->machine->primary_screen);
background_enable = data & 0x01;
}
WRITE8_HANDLER( scramble_background_red_w )
{
video_screen_update_now(space->machine->primary_screen);
background_red = data & 0x01;
}
WRITE8_HANDLER( scramble_background_green_w )
{
video_screen_update_now(space->machine->primary_screen);
background_green = data & 0x01;
}
WRITE8_HANDLER( scramble_background_blue_w )
{
video_screen_update_now(space->machine->primary_screen);
background_blue = data & 0x01;
}
/*************************************
*
* Graphics banking
*
*************************************/
WRITE8_HANDLER( galaxian_gfxbank_w )
{
if (gfxbank[offset] != data)
{
video_screen_update_now(space->machine->primary_screen);
gfxbank[offset] = data;
tilemap_mark_all_tiles_dirty(bg_tilemap);
}
}
/*************************************
*
* Star initialization
*
*************************************/
static void stars_init(running_machine *machine)
{
UINT32 shiftreg;
int i;
/* reset the blink and enabled states */
stars_enabled = FALSE;
stars_blink_state = 0;
/* precalculate the RNG */
stars = auto_alloc_array(machine, UINT8, STAR_RNG_PERIOD);
shiftreg = 0;
for (i = 0; i < STAR_RNG_PERIOD; i++)
{
/* stars are enabled if the upper 8 bits are 1 and the low bit is 0 */
int enabled = ((shiftreg & 0x1fe01) == 0x1fe00);
/* color comes from the 6 bits below the top 8 bits */
int color = (~shiftreg & 0x1f8) >> 3;
/* store the color value in the low 6 bits and the enable in the upper bit */
stars[i] = color | (enabled << 7);
/* the LFSR is fed based on the XOR of bit 12 and the inverse of bit 0 */
shiftreg = (shiftreg >> 1) | ((((shiftreg >> 12) ^ ~shiftreg) & 1) << 16);
}
}
/*************************************
*
* Adjust the origin of stars
*
*************************************/
static void stars_update_origin(running_machine *machine)
{
int curframe = video_screen_get_frame_number(machine->primary_screen);
/* only update on a different frame */
if (curframe != star_rng_origin_frame)
{
/* The RNG period is 2^17-1; each frame, the shift register is clocked */
/* 512*256 = 2^17 times. This means that we clock one extra time each */
/* frame. However, if we are NOT flipped, there is a pair of D flip-flops */
/* at 6B which delay the count so that we count 512*256-2 = 2^17-2 times. */
/* In this case, we only one time less than the period each frame. Both */
/* of these off-by-one countings produce the horizontal star scrolling. */
int per_frame_delta = flipscreen_x ? 1 : -1;
int total_delta = per_frame_delta * (curframe - star_rng_origin_frame);
/* we can't just use % here because mod of a negative number is undefined */
while (total_delta < 0)
total_delta += STAR_RNG_PERIOD;
/* now that everything is positive, do the mod */
star_rng_origin = (star_rng_origin + total_delta) % STAR_RNG_PERIOD;
star_rng_origin_frame = curframe;
}
}
/*************************************
*
* Star blinking
*
*************************************/
TIMER_CALLBACK( galaxian_stars_blink_timer )
{
stars_blink_state++;
}
/*************************************
*
* Draw a row of stars
*
*************************************/
static void stars_draw_row(bitmap_t *bitmap, int maxx, int y, UINT32 star_offs, UINT8 starmask)
{
int x;
/* ensure our star offset is valid */
star_offs %= STAR_RNG_PERIOD;
/* iterate over the specified number of 6MHz pixels */
for (x = 0; x < maxx; x++)
{
/* stars are suppressed unless V1 ^ H8 == 1 */
int enable_star = (y ^ (x >> 3)) & 1;
UINT8 star;
/*
The RNG clock is the master clock (18MHz) ANDed with the pixel clock (6MHz).
The divide-by-3 circuit that produces the pixel clock generates a square wave
with a 2/3 duty cycle, so the result of the AND generates a clock like this:
_ _ _ _ _ _ _ _
MASTER: _| |_| |_| |_| |_| |_| |_| |_| |
_______ _______ ______
PIXEL: _| |___| |___|
_ _ _ _ _ _
RNG: _| |_| |_____| |_| |_____| |_| |
Thus for each pixel, there are 3 master clocks and 2 RNG clocks, and the RNG
is clocked asymmetrically. To simulate this, we expand the horizontal screen
size by 3 and handle the first RNG clock with one pixel and the second RNG
clock with two pixels.
*/
/* first RNG clock: one pixel */
star = stars[star_offs++];
if (star_offs >= STAR_RNG_PERIOD)
star_offs = 0;
if (enable_star && (star & 0x80) != 0 && (star & starmask) != 0)
*BITMAP_ADDR32(bitmap, y, GALAXIAN_XSCALE*x + 0) = star_color[star & 0x3f];
/* second RNG clock: two pixels */
star = stars[star_offs++];
if (star_offs >= STAR_RNG_PERIOD)
star_offs = 0;
if (enable_star && (star & 0x80) != 0 && (star & starmask) != 0)
{
*BITMAP_ADDR32(bitmap, y, GALAXIAN_XSCALE*x + 1) = star_color[star & 0x3f];
*BITMAP_ADDR32(bitmap, y, GALAXIAN_XSCALE*x + 2) = star_color[star & 0x3f];
}
}
}
/*************************************
*
* Background rendering
*
*************************************/
static int flip_and_clip(rectangle *draw, int xstart, int xend, const rectangle *cliprect)
{
*draw = *cliprect;
if (!flipscreen_x)
{
draw->min_x = xstart * GALAXIAN_XSCALE;
draw->max_x = xend * GALAXIAN_XSCALE + (GALAXIAN_XSCALE - 1);
}
else
{
draw->min_x = (xend ^ 255) * GALAXIAN_XSCALE;
draw->max_x = (xstart ^ 255) * GALAXIAN_XSCALE + (GALAXIAN_XSCALE - 1);
}
sect_rect(draw, cliprect);
return (draw->min_x <= draw->max_x);
}
void galaxian_draw_background(running_machine *machine, bitmap_t *bitmap, const rectangle *cliprect)
{
/* erase the background to black first */
bitmap_fill(bitmap, cliprect, RGB_BLACK);
/* update the star origin to the current frame */
stars_update_origin(machine);
/* render stars if enabled */
if (stars_enabled)
{
int y;
/* iterate over scanlines */
for (y = cliprect->min_y; y <= cliprect->max_y; y++)
{
UINT32 star_offs = star_rng_origin + y * 512;
stars_draw_row(bitmap, 256, y, star_offs, 0xff);
}
}
}
void frogger_draw_background(running_machine *machine, bitmap_t *bitmap, const rectangle *cliprect)
{
rectangle draw;
if (flipscreen_x)
{
/* color split point verified on real machine */
/* hmmm, according to schematics it is at 128+8; which is right? */
draw = *cliprect;
draw.max_x = MIN(draw.max_x, (128-8) * GALAXIAN_XSCALE - 1);
if (draw.min_x <= draw.max_x)
bitmap_fill(bitmap, &draw, RGB_BLACK);
draw = *cliprect;
draw.min_x = MAX(draw.min_x, (128-8) * GALAXIAN_XSCALE);
if (draw.min_x <= draw.max_x)
bitmap_fill(bitmap, &draw, MAKE_RGB(0,0,0x47));
}
else
{
/* color split point verified on real machine */
/* hmmm, according to schematics it is at 128+8; which is right? */
draw = *cliprect;
draw.max_x = MIN(draw.max_x, (128+8) * GALAXIAN_XSCALE - 1);
if (draw.min_x <= draw.max_x)
bitmap_fill(bitmap, &draw, MAKE_RGB(0,0,0x47));
draw = *cliprect;
draw.min_x = MAX(draw.min_x, (128+8) * GALAXIAN_XSCALE);
if (draw.min_x <= draw.max_x)
bitmap_fill(bitmap, &draw, RGB_BLACK);
}
}
void amidar_draw_background(running_machine *machine, bitmap_t *bitmap, const rectangle *cliprect)
{
const UINT8 *prom = memory_region(machine, "user1");
rectangle draw;
int x;
for (x = 0; x < 32; x++)
if (flip_and_clip(&draw, x * 8, x * 8 + 7, cliprect))
{
/*
The background PROM is connected the following way:
bit 0 = 0 enables the blue gun if BCB is asserted
bit 1 = 0 enables the red gun if BCR is asserted and
the green gun if BCG is asserted
bits 2-7 are unconnected
The background color generator is connected this way:
RED - 270 ohm resistor
GREEN - 560 ohm resistor
BLUE - 470 ohm resistor
*/
UINT8 red = ((~prom[x] & 0x02) && background_red) ? 0x7c : 0x00;
UINT8 green = ((~prom[x] & 0x02) && background_green) ? 0x3c : 0x00;
UINT8 blue = ((~prom[x] & 0x01) && background_blue) ? 0x47 : 0x00;
bitmap_fill(bitmap, &draw, MAKE_RGB(red, green, blue));
}
}
void turtles_draw_background(running_machine *machine, bitmap_t *bitmap, const rectangle *cliprect)
{
/*
The background color generator is connected this way:
RED - 390 ohm resistor
GREEN - 470 ohm resistor
BLUE - 390 ohm resistor
*/
bitmap_fill(bitmap, cliprect, MAKE_RGB(background_red * 0x55, background_green * 0x47, background_blue * 0x55));
}
void scramble_draw_background(running_machine *machine, bitmap_t *bitmap, const rectangle *cliprect)
{
/* blue background - 390 ohm resistor */
bitmap_fill(bitmap, cliprect, background_enable ? MAKE_RGB(0,0,0x56) : RGB_BLACK);
/* update the star origin to the current frame */
stars_update_origin(machine);
/* render stars if enabled */
if (stars_enabled)
{
int blink_state = stars_blink_state & 3;
int y;
/* iterate over scanlines */
for (y = cliprect->min_y; y <= cliprect->max_y; y++)
{
/* blink state 2 suppressed stars when 2V == 0 */
if (blink_state != 2 || (y & 2) != 0)
{
/* blink states 0 and 1 suppress stars when certain bits of the color == 0 */
static const UINT8 colormask_table[4] = { 0x20, 0x08, 0xff, 0xff };
stars_draw_row(bitmap, 256, y, y * 512, colormask_table[blink_state]);
}
}
}
}
void jumpbug_draw_background(running_machine *machine, bitmap_t *bitmap, const rectangle *cliprect)
{
/* blue background - 390 ohm resistor */
bitmap_fill(bitmap, cliprect, background_enable ? MAKE_RGB(0,0,0x56) : RGB_BLACK);
/* update the star origin to the current frame */
stars_update_origin(machine);
/* render stars if enabled -- same as scramble but nothing in the status area */
if (stars_enabled)
{
int blink_state = stars_blink_state & 3;
int y;
/* iterate over scanlines */
for (y = cliprect->min_y; y <= cliprect->max_y; y++)
{
/* blink state 2 suppressed stars when 2V == 0 */
if (blink_state != 2 || (y & 2) != 0)
{
/* blink states 0 and 1 suppress stars when certain bits of the color == 0 */
static const UINT8 colormask_table[4] = { 0x20, 0x08, 0xff, 0xff };
stars_draw_row(bitmap, 240, y, y * 512, colormask_table[blink_state]);
}
}
}
}
/*************************************
*
* Bullet rendering
*
*************************************/
INLINE void galaxian_draw_pixel(bitmap_t *bitmap, const rectangle *cliprect, int y, int x, rgb_t color)
{
if (y >= cliprect->min_y && y <= cliprect->max_y)
{
x *= GALAXIAN_XSCALE;
x += GALAXIAN_H0START;
if (x >= cliprect->min_x && x <= cliprect->max_x)
*BITMAP_ADDR32(bitmap, y, x) = color;
x++;
if (x >= cliprect->min_x && x <= cliprect->max_x)
*BITMAP_ADDR32(bitmap, y, x) = color;
x++;
if (x >= cliprect->min_x && x <= cliprect->max_x)
*BITMAP_ADDR32(bitmap, y, x) = color;
}
}
void galaxian_draw_bullet(running_machine *machine, bitmap_t *bitmap, const rectangle *cliprect, int offs, int x, int y)
{
/*
Both "shells" and "missiles" begin displaying when the horizontal counter
reaches $FC, and they stop displaying when it reaches $00, resulting in
4-pixel-long shots. The first 7 entries are called "shells" and render as
white; the final entry is called a "missile" and renders as yellow.
*/
x -= 4;
galaxian_draw_pixel(bitmap, cliprect, y, x++, bullet_color[offs]);
galaxian_draw_pixel(bitmap, cliprect, y, x++, bullet_color[offs]);
galaxian_draw_pixel(bitmap, cliprect, y, x++, bullet_color[offs]);
galaxian_draw_pixel(bitmap, cliprect, y, x++, bullet_color[offs]);
}
void mshuttle_draw_bullet(running_machine *machine, bitmap_t *bitmap, const rectangle *cliprect, int offs, int x, int y)
{
/* verified by schematics:
* both "W" and "Y" bullets are 4 pixels long
* "W" bullets are enabled when H6 == 0, and are always purple
* "Y" bullets are enabled when H6 == 1, and vary in color based on H4,H3,H2
*/
static const rgb_t colors[8] =
{
MAKE_RGB(0xff,0xff,0xff),
MAKE_RGB(0xff,0xff,0x00),
MAKE_RGB(0x00,0xff,0xff),
MAKE_RGB(0x00,0xff,0x00),
MAKE_RGB(0xff,0x00,0xff),
MAKE_RGB(0xff,0x00,0x00),
MAKE_RGB(0x00,0x00,0xff),
MAKE_RGB(0x00,0x00,0x00)
};
--x;
galaxian_draw_pixel(bitmap, cliprect, y, x, ((x & 0x40) == 0) ? colors[(x >> 2) & 7] : MAKE_RGB(0xff,0x00,0xff));
--x;
galaxian_draw_pixel(bitmap, cliprect, y, x, ((x & 0x40) == 0) ? colors[(x >> 2) & 7] : MAKE_RGB(0xff,0x00,0xff));
--x;
galaxian_draw_pixel(bitmap, cliprect, y, x, ((x & 0x40) == 0) ? colors[(x >> 2) & 7] : MAKE_RGB(0xff,0x00,0xff));
--x;
galaxian_draw_pixel(bitmap, cliprect, y, x, ((x & 0x40) == 0) ? colors[(x >> 2) & 7] : MAKE_RGB(0xff,0x00,0xff));
}
void scramble_draw_bullet(running_machine *machine, bitmap_t *bitmap, const rectangle *cliprect, int offs, int x, int y)
{
/*
Scramble only has "shells", which begin displaying when the counter
reaches $FA, and stop displaying one pixel clock layer. All shells are
rendered as yellow.
*/
x -= 6;
galaxian_draw_pixel(bitmap, cliprect, y, x, MAKE_RGB(0xff,0xff,0x00));
}
void theend_draw_bullet(running_machine *machine, bitmap_t *bitmap, const rectangle *cliprect, int offs, int x, int y)
{
/* Same as galaxian except blue/green are swapped */
x -= 4;
galaxian_draw_pixel(bitmap, cliprect, y, x++, MAKE_RGB(RGB_RED(bullet_color[offs]), RGB_BLUE(bullet_color[offs]), RGB_GREEN(bullet_color[offs])));
galaxian_draw_pixel(bitmap, cliprect, y, x++, MAKE_RGB(RGB_RED(bullet_color[offs]), RGB_BLUE(bullet_color[offs]), RGB_GREEN(bullet_color[offs])));
galaxian_draw_pixel(bitmap, cliprect, y, x++, MAKE_RGB(RGB_RED(bullet_color[offs]), RGB_BLUE(bullet_color[offs]), RGB_GREEN(bullet_color[offs])));
galaxian_draw_pixel(bitmap, cliprect, y, x++, MAKE_RGB(RGB_RED(bullet_color[offs]), RGB_BLUE(bullet_color[offs]), RGB_GREEN(bullet_color[offs])));
}
/*************************************
*
* Generic extensions
*
*************************************/
void upper_extend_tile_info(UINT16 *code, UINT8 *color, UINT8 attrib, UINT8 x)
{
/* tiles are in the upper half of a larger ROM */
*code += 0x100;
}
void upper_extend_sprite_info(const UINT8 *base, UINT8 *sx, UINT8 *sy, UINT8 *flipx, UINT8 *flipy, UINT16 *code, UINT8 *color)
{
/* sprites are in the upper half of a larger ROM */
*code += 0x40;
}
/*************************************
*
* Frogger extensions
*
*************************************/
void frogger_extend_tile_info(UINT16 *code, UINT8 *color, UINT8 attrib, UINT8 x)
{
*color = ((*color >> 1) & 0x03) | ((*color << 2) & 0x04);
}
void frogger_extend_sprite_info(const UINT8 *base, UINT8 *sx, UINT8 *sy, UINT8 *flipx, UINT8 *flipy, UINT16 *code, UINT8 *color)
{
*color = ((*color >> 1) & 0x03) | ((*color << 2) & 0x04);
}
/*************************************
*
* Ghostmuncher Galaxian extensions
*
*************************************/
void gmgalax_extend_tile_info(UINT16 *code, UINT8 *color, UINT8 attrib, UINT8 x)
{
*code |= gfxbank[0] << 9;
// *color |= gfxbank[0] << 3;
}
void gmgalax_extend_sprite_info(const UINT8 *base, UINT8 *sx, UINT8 *sy, UINT8 *flipx, UINT8 *flipy, UINT16 *code, UINT8 *color)
{
*code |= (gfxbank[0] << 7) | 0x40;
*color |= gfxbank[0] << 3;
}
/*************************************
*
* Pisces extensions
*
*************************************/
void pisces_extend_tile_info(UINT16 *code, UINT8 *color, UINT8 attrib, UINT8 x)
{
*code |= gfxbank[0] << 8;
}
void pisces_extend_sprite_info(const UINT8 *base, UINT8 *sx, UINT8 *sy, UINT8 *flipx, UINT8 *flipy, UINT16 *code, UINT8 *color)
{
*code |= gfxbank[0] << 6;
}
/*************************************
*
* Batman Part 2 extensions
*
*************************************/
void batman2_extend_tile_info(UINT16 *code, UINT8 *color, UINT8 attrib, UINT8 x)
{
if (*code & 0x80)
*code |= gfxbank[0] << 8;
}
/*************************************
*
* Moon Cresta extensions
*
*************************************/
void mooncrst_extend_tile_info(UINT16 *code, UINT8 *color, UINT8 attrib, UINT8 x)
{
if (gfxbank[2] && (*code & 0xc0) == 0x80)
*code = (*code & 0x3f) | (gfxbank[0] << 6) | (gfxbank[1] << 7) | 0x0100;
}
void mooncrst_extend_sprite_info(const UINT8 *base, UINT8 *sx, UINT8 *sy, UINT8 *flipx, UINT8 *flipy, UINT16 *code, UINT8 *color)
{
if (gfxbank[2] && (*code & 0x30) == 0x20)
*code = (*code & 0x0f) | (gfxbank[0] << 4) | (gfxbank[1] << 5) | 0x40;
}
/*************************************
*
* Moon Quasar extensions
*
*************************************/
void moonqsr_extend_tile_info(UINT16 *code, UINT8 *color, UINT8 attrib, UINT8 x)
{
*code |= (attrib & 0x20) << 3;
}
void moonqsr_extend_sprite_info(const UINT8 *base, UINT8 *sx, UINT8 *sy, UINT8 *flipx, UINT8 *flipy, UINT16 *code, UINT8 *color)
{
*code |= (base[2] & 0x20) << 1;
}
/*************************************
*
* Moon Shuttle extensions
*
*************************************/
void mshuttle_extend_tile_info(UINT16 *code, UINT8 *color, UINT8 attrib, UINT8 x)
{
*code |= (attrib & 0x30) << 4;
}
void mshuttle_extend_sprite_info(const UINT8 *base, UINT8 *sx, UINT8 *sy, UINT8 *flipx, UINT8 *flipy, UINT16 *code, UINT8 *color)
{
*code |= (base[2] & 0x30) << 2;
}
/*************************************
*
* Calipso extensions
*
*************************************/
void calipso_extend_sprite_info(const UINT8 *base, UINT8 *sx, UINT8 *sy, UINT8 *flipx, UINT8 *flipy, UINT16 *code, UINT8 *color)
{
/* same as the others, but no sprite flipping, but instead the bits are used
as extra sprite code bits, giving 256 sprite images */
/* No flips */
*code = base[1];
*flipx = 0;
*flipy = 0;
}
/*************************************
*
* Jumpbug extensions
*
*************************************/
void jumpbug_extend_tile_info(UINT16 *code, UINT8 *color, UINT8 attrib, UINT8 x)
{
if ((*code & 0xc0) == 0x80 && (gfxbank[2] & 0x01))
*code += 128 + (( gfxbank[0] & 0x01) << 6) +
(( gfxbank[1] & 0x01) << 7) +
((~gfxbank[4] & 0x01) << 8);
}
void jumpbug_extend_sprite_info(const UINT8 *base, UINT8 *sx, UINT8 *sy, UINT8 *flipx, UINT8 *flipy, UINT16 *code, UINT8 *color)
{
if ((*code & 0x30) == 0x20 && (gfxbank[2] & 0x01) != 0)
{
*code += 32 + (( gfxbank[0] & 0x01) << 4) +
(( gfxbank[1] & 0x01) << 5) +
((~gfxbank[4] & 0x01) << 6);
}
}
| 31.240623 | 157 | 0.600005 | [
"render",
"object"
] |
147601b711edeb4436bdd0279668e6092a59489d | 1,899 | h | C | cells.h | Aieener/SUS_on_S | b24ea7225063b9c753ca9b482f4e4725a90243f5 | [
"MIT"
] | null | null | null | cells.h | Aieener/SUS_on_S | b24ea7225063b9c753ca9b482f4e4725a90243f5 | [
"MIT"
] | null | null | null | cells.h | Aieener/SUS_on_S | b24ea7225063b9c753ca9b482f4e4725a90243f5 | [
"MIT"
] | null | null | null | // cells.h
// 3-D Rods
// Author: Yuding Ai
// Date: 2015.06.05
#ifndef CELLS_H
#define CELLS_H
#include <vector>
#include "hardrods.h"
#include "square.h"
#include "Boxgen.h"
#include "Planegen.h"
using namespace std;
// template< int N0, int N1, int N2> inline const int rten_idx(const int i0, const int i1, const int i2)
// {
// return i2 + N2*(i1 + N1*i0);
// }
// template< int N0, int N1, int N2> inline const int rten_idx(const int i0, const int i1, const int i2)
// {
// return i2 + N2*(i1 + N1*i0);
// }
class Cells
{
private:
int N0; // Weith;
int N1; // Length;
int N2; // Height;
int size; // the total size of the grid
Square * arr; // linearized array of Squares
std::vector<Boxgen> Boxlist; // the list storage the subboxes;
std::vector<Planegen> Planelist; // the list storage the subboxes;
public:
enum INIT {EMPTY,BOX,PLANE};
enum PLANE_DIRECTION {X_,Y_,Z_};
enum BOX_DIRECTION {VER,HOR,UP};
Cells();
/*
* Constructor builds a cells from an input stream
* @param int r - row index
* @param int c - column index
* initialize all states to 0;
*/
Cells(int X,int Y, int Z, int init,int length);
/*
* Destructor
*/
~Cells();
// *** Getters *** //
int getN0() const;
int getN1() const;
int getN2() const;
int getSize() const;
int getIdx( int x, int y, int z) const;
const vector<Boxgen>& getBoxlist() const;
const vector<Planegen>& getPlanelist() const;
// *** Other Functionality *** //
/*
* @function getSquare
* @param int i - row index, in range 0 through numRows - 1
* @param int j - column index, in range 0 through numCols - 1
* @return Square& - return a reference to the (i,j)-Square stored
* in this cells
*/
Square& getSquare(int x, int y,int z) const;
};
#endif /* CELLS_H */ | 23.444444 | 104 | 0.604529 | [
"vector"
] |
147b7c2aac4ce6dd2c55046d08058fb6d748b038 | 3,724 | h | C | modio/modio/core/entities/ModioModInfo.h | nyzeairs/friendly-eureka | ecc6ff456c9188965d51e1e92cdf6472f42d5b60 | [
"BSL-1.0"
] | 24 | 2020-11-15T05:37:53.000Z | 2022-03-26T19:00:17.000Z | modio/modio/core/entities/ModioModInfo.h | Miki-p/modio-sdk--- | 24a578091ef818fc873e071cfcb0b6306af0d803 | [
"BSL-1.0"
] | 10 | 2020-11-30T06:47:14.000Z | 2021-12-21T04:16:34.000Z | modio/modio/core/entities/ModioModInfo.h | Miki-p/modio-sdk--- | 24a578091ef818fc873e071cfcb0b6306af0d803 | [
"BSL-1.0"
] | 11 | 2020-12-08T15:09:41.000Z | 2022-03-26T19:00:20.000Z | /*
* Copyright (C) 2021 mod.io Pty Ltd. <https://mod.io>
*
* This file is part of the mod.io SDK.
*
* Distributed under the MIT License. (See accompanying file LICENSE or
* view online at <https://github.com/modio/modio-sdk/blob/main/LICENSE>)
*
*/
#pragma once
#include "ModioGeneratedVariables.h"
#include "modio/detail/ModioDefines.h"
#include "modio/core/entities/ModioFileMetadata.h"
#include "modio/core/entities/ModioModStats.h"
#include "modio/core/entities/ModioURLList.h"
#include "modio/core/entities/ModioUser.h"
#include "modio/detail/entities/ModioGalleryList.h"
#include <string>
#include <vector>
#include <nlohmann/json.hpp>
namespace Modio
{
enum class MaturityOption : std::uint8_t
{
None = 0,
Alcohol = 1,
Drugs = 2,
Violence = 4,
Explicit = 8
};
// @todo: If ModTag and Metadata is used somewhere else than in ModInfo, then migrate them to their own headers
struct ModTag
{
std::string Tag;
};
MODIO_IMPL void from_json(const nlohmann::json& Json, Modio::ModTag& ModTag);
MODIO_IMPL void to_json(nlohmann::json& Json, const Modio::ModTag& Tag);
// Migrate: std::vector<Modio::ModTag> Tags to a custom class that encapsulates std::map helpers to fetch Values as
// something like this: Metadata.Get<int32>( "OptimizedFor" );
struct Metadata
{
std::string Key;
std::string Value;
};
MODIO_IMPL void from_json(const nlohmann::json& Json, Modio::Metadata& Metadata);
MODIO_IMPL void to_json(nlohmann::json& Json, const Modio::Metadata& Metadata);
/// @docpublic
/// @brief Full mod profile including current release information, media links, and stats
struct ModInfo
{
/// @brief Unique Mod ID
Modio::ModID ModId;
/// @brief Name of the mod
std::string ProfileName;
/// @brief Summary of the mod
std::string ProfileSummary;
/// @brief Detailed description in HTML format
std::string ProfileDescription;
/// @brief Detailed description in plaintext
std::string ProfileDescriptionPlaintext;
/// @brief URL to the mod profile
std::string ProfileURL;
/// @brief Information on the user who submitted the mod
Modio::User ProfileSubmittedBy;
/// @brief Unix timestamp of the date the mod was registered
std::int64_t ProfileDateAdded;
/// @brief Unix timestamp of the date the mod was updated
std::int64_t ProfileDateUpdated;
/// @brief Unix timestamp of the date the mod was marked live
std::int64_t ProfileDateLive;
/// @brief Flags for maturity options
/// * Maturity options flagged by the mod developer, this is only relevant if the parent game allows mods to
/// * be labeled as mature.
/// *
/// * 0 = None set (default)
/// * 1 = Alcohol
/// * 2 = Drugs
/// * 4 = Violence
/// * 8 = Explicit
std::uint8_t ProfileMaturityOption;
std::string MetadataBlob;
/// @brief Information about the mod's most recent public release
Modio::FileMetadata FileInfo;
/// @brief Arbitrary key-value metadata set for this mod
std::vector<Modio::Metadata> MetadataKvp;
/// @brief Tags this mod has set
std::vector<Modio::ModTag> Tags;
/// @brief Number of images in the mod's media gallery
std::size_t NumGalleryImages;
/// @brief List of youtube links provided by the creator of the mod
Modio::YoutubeURLList YoutubeURLs;
/// @brief List of sketchfab links provided by the creator of the mod
Modio::SketchfabURLList SketchfabURLs;
/// @brief Stats and rating information for the mod
Modio::ModStats Stats;
};
MODIO_IMPL void from_json(const nlohmann::json& Json, Modio::ModInfo& ModInfo);
MODIO_IMPL void to_json(nlohmann::json& Json, const Modio::ModInfo& Info);
} // namespace Modio
#ifndef MODIO_SEPARATE_COMPILATION
#include "ModioModInfo.ipp"
#endif
| 31.294118 | 116 | 0.718314 | [
"vector"
] |
1481aae9d1ad027912b63e64eb2f0f08e46b1f4b | 3,153 | h | C | libgearman-server/plugins/queue/redis/queue.h | alionurdemetoglu/gearmand | dd9ac59a730f816e0dc5f27f98fdc06a08cc4c22 | [
"BSD-3-Clause"
] | 712 | 2016-07-02T03:32:22.000Z | 2022-03-23T14:23:02.000Z | libgearman-server/plugins/queue/redis/queue.h | alionurdemetoglu/gearmand | dd9ac59a730f816e0dc5f27f98fdc06a08cc4c22 | [
"BSD-3-Clause"
] | 294 | 2016-07-03T16:17:41.000Z | 2022-03-30T04:37:49.000Z | libgearman-server/plugins/queue/redis/queue.h | alionurdemetoglu/gearmand | dd9ac59a730f816e0dc5f27f98fdc06a08cc4c22 | [
"BSD-3-Clause"
] | 163 | 2016-07-08T10:03:38.000Z | 2022-01-21T05:03:48.000Z | /* vim:expandtab:shiftwidth=2:tabstop=2:smarttab:
*
* Gearmand client and server library.
*
* Copyright (C) 2011 Data Differential, http://datadifferential.com/
* 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.
*
* * The names of its contributors may not be used to endorse or
* promote products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE 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.
*
*/
#pragma once
#if defined(HAVE_HIREDIS) && HAVE_HIREDIS
#ifndef GEARMAND_PLUGINS_QUEUE_REDIS_H
#define GEARMAND_PLUGINS_QUEUE_REDIS_H
#include <libgearman-server/common.h>
#include <libgearman-server/plugins/queue/base.h>
#include <hiredis/hiredis.h>
typedef std::vector<char> vchar_t;
namespace gearmand {
namespace plugins {
namespace queue {
/**
* redis result record struct
*/
struct redis_record_t {
uint32_t priority;
std::string data;
};
/**
* redis queue class
* provides redisContex object
* and a set of helper methods
*/
class Hiredis : public Queue {
private:
redisContext *_redis;
public:
std::string server;
std::string service;
std::string password;
std::string prefix;
Hiredis();
~Hiredis();
gearmand_error_t initialize();
redisContext* redis();
/*
* hmset(vchar_t key, const void *data, size_t data_size, uint32_t)
*
* returns true if hiredis HMSET succeeded
*/
bool hmset(vchar_t, const void *, size_t, uint32_t);
/*
* bool fetch(char *key, redis_record_t &req)
*
* fetch redis data for the key
* and put it into record
*
* returns true on success
*/
bool fetch(char *, redis_record_t &);
}; // class Hiredis
void initialize_redis();
} // namespace queue
} // namespace plugins
} // namespace gearmand
#endif // ifndef GEARMAND_PLUGINS_QUEUE_REDIS_H
#endif // if defined(HAVE_HIREDIS) && HAVE_HIREDIS
| 28.926606 | 74 | 0.717729 | [
"object",
"vector"
] |
14820d292de1dd2a89897e7670c2721bcd713826 | 117 | c | C | orio/module/loops/submodule/pragma/examples/reference/_ex2.c | parsabee/Orio | 64de0f7ee422483b60a9f02793472e20e864aa08 | [
"MIT"
] | 24 | 2015-01-26T03:14:19.000Z | 2021-09-27T23:10:12.000Z | orio/module/loops/submodule/pragma/examples/reference/_ex2.c | parsabee/Orio | 64de0f7ee422483b60a9f02793472e20e864aa08 | [
"MIT"
] | 30 | 2015-04-17T18:14:27.000Z | 2021-05-30T15:01:47.000Z | orio/module/loops/submodule/pragma/examples/reference/_ex2.c | parsabee/Orio | 64de0f7ee422483b60a9f02793472e20e864aa08 | [
"MIT"
] | 20 | 2015-02-11T08:20:19.000Z | 2022-01-15T17:55:00.000Z |
#pragma Orio Loops(transform Pragma(pragma_str="vector always"))
{
#pragma vector always
S(i,j);
}
#pragma Oiro
| 14.625 | 64 | 0.709402 | [
"vector",
"transform"
] |
14846956423e50ae9ac17cb2ac3f6b0ab628d475 | 11,949 | h | C | include/worklist.h | prdalmia/GaloisGPU | 7b04535b4964eda933157546178e6ad3872cb7f3 | [
"BSD-3-Clause"
] | 28 | 2017-09-06T21:12:53.000Z | 2022-02-16T01:01:55.000Z | include/worklist.h | prdalmia/GaloisGPU | 7b04535b4964eda933157546178e6ad3872cb7f3 | [
"BSD-3-Clause"
] | 1 | 2019-11-11T05:16:10.000Z | 2019-11-13T18:18:10.000Z | include/worklist.h | prdalmia/GaloisGPU | 7b04535b4964eda933157546178e6ad3872cb7f3 | [
"BSD-3-Clause"
] | 34 | 2017-12-14T01:06:58.000Z | 2022-02-14T09:40:35.000Z | /*
* use atomicInc to automatically wrap around.
*/
#include <stdio.h>
#include <cuda.h>
#include <time.h>
#include <fstream>
#include <string>
#include <vector>
#include <iostream>
#include <string.h>
#define MINCAPACITY 65535
#define MAXOVERFLOWS 1
typedef struct Worklist {
enum {NotAllocated, AllocatedOnHost, AllocatedOnDevice} memory;
__device__ unsigned pushRange(unsigned *start, unsigned nitems);
__device__ unsigned push(unsigned work);
__device__ unsigned popRange(unsigned *start, unsigned nitems);
__device__ unsigned pop(unsigned &work);
__device__ void clear();
__device__ void myItems(unsigned &start, unsigned &end);
__device__ unsigned getItem(unsigned at);
__device__ unsigned getItemWithin(unsigned at, unsigned hsize);
__device__ unsigned count();
void init();
void init(unsigned initialcapacity);
void setSize(unsigned hsize);
unsigned getSize();
void setCapacity(unsigned hcapacity);
unsigned getCapacity();
void pushRangeHost(unsigned *start, unsigned nitems);
void pushHost(unsigned work);
void clearHost();
void setInitialSize(unsigned hsize);
unsigned calculateSize(unsigned hstart, unsigned hend);
void setStartEnd(unsigned hstart, unsigned hend);
void getStartEnd(unsigned &hstart, unsigned &hend);
void copyOldToNew(unsigned *olditems, unsigned *newitems, unsigned oldsize, unsigned oldcapacity);
void compressHost(unsigned wlsize, unsigned sentinel);
void printHost();
unsigned appendHost(Worklist *otherwl);
Worklist();
~Worklist();
unsigned ensureSpace(unsigned space);
unsigned *alloc(unsigned allocsize);
unsigned realloc(unsigned space);
unsigned dealloc();
unsigned freeSize();
unsigned *items;
unsigned *start, *end, *capacity; // since these change, we don't want their copies with threads, hence pointers.
unsigned noverflows;
} Worklist;
static unsigned CudaTest(char *msg);
Worklist::Worklist() {
init();
}
void Worklist::init() {
init(0);
}
void Worklist::init(unsigned initialcapacity) {
start = alloc(1);
end = alloc(1);
capacity = alloc(1);
setCapacity(initialcapacity);
setInitialSize(0);
items = NULL;
if (initialcapacity) items = alloc(initialcapacity);
noverflows = 0;
}
unsigned *Worklist::alloc(unsigned allocsize) {
unsigned *ptr = NULL;
if (cudaMalloc((void **)&ptr, allocsize * sizeof(unsigned)) != cudaSuccess) {
//CudaTest("allocating ptr failed");
printf("%s(%d): Allocating %d failed.\n", __FILE__, __LINE__, allocsize);
return NULL;
}
return ptr;
}
unsigned Worklist::getCapacity() {
unsigned hcapacity;
cudaMemcpy(&hcapacity, capacity, sizeof(hcapacity), cudaMemcpyDeviceToHost);
return hcapacity;
}
unsigned Worklist::calculateSize(unsigned hstart, unsigned hend) {
if (hend >= hstart) {
return hend - hstart;
}
// circular queue.
unsigned hcapacity = getCapacity();
return hend + (hcapacity - hstart + 1);
}
void Worklist::getStartEnd(unsigned &hstart, unsigned &hend) {
cudaMemcpy(&hstart, start, sizeof(hstart), cudaMemcpyDeviceToHost);
cudaMemcpy(&hend, end, sizeof(hend), cudaMemcpyDeviceToHost);
}
unsigned Worklist::getSize() {
unsigned hstart, hend;
getStartEnd(hstart, hend);
if (hstart != 0) { printf("\tNOTICE: hstart = %d.\n", hstart); }
return calculateSize(hstart, hend);
}
void Worklist::setStartEnd(unsigned hstart, unsigned hend) {
cudaMemcpy(start, &hstart, sizeof(hstart), cudaMemcpyHostToDevice);
cudaMemcpy(end, &hend, sizeof(hend), cudaMemcpyHostToDevice);
}
void Worklist::setCapacity(unsigned hcapacity) {
cudaMemcpy(capacity, &hcapacity, sizeof(hcapacity), cudaMemcpyHostToDevice);
}
void Worklist::setInitialSize(unsigned hsize) {
setStartEnd(0, 0);
}
void Worklist::setSize(unsigned hsize) {
unsigned hcapacity = getCapacity();
if (hsize > hcapacity) {
printf("%s(%d): buffer overflow, setting size=%d, when capacity=%d.\n", __FILE__, __LINE__, hsize, hcapacity);
return;
}
unsigned hstart, hend;
getStartEnd(hstart, hend);
if (hstart + hsize < hcapacity) {
hend = hstart + hsize;
} else {
hsize -= hcapacity - hstart;
hend = hsize;
}
setStartEnd(hstart, hend);
}
void Worklist::copyOldToNew(unsigned *olditems, unsigned *newitems, unsigned oldsize, unsigned oldcapacity) {
unsigned mystart, myend;
getStartEnd(mystart, myend);
if (mystart < myend) { // no wrap-around.
cudaMemcpy(newitems, olditems + mystart, oldsize * sizeof(unsigned), cudaMemcpyDeviceToDevice);
} else {
cudaMemcpy(newitems, olditems + mystart, (oldcapacity - mystart) * sizeof(unsigned), cudaMemcpyDeviceToDevice);
cudaMemcpy(newitems + (oldcapacity - mystart), olditems, myend * sizeof(unsigned), cudaMemcpyDeviceToDevice);
}
}
unsigned Worklist::realloc(unsigned space) {
unsigned hcapacity = getCapacity();
unsigned newcapacity = (space > MINCAPACITY ? space : MINCAPACITY);
if (hcapacity == 0) {
setCapacity(newcapacity);
items = alloc(newcapacity);
if (items == NULL) {
return 1;
}
} else {
unsigned *itemsrealloc = alloc(newcapacity);
if (itemsrealloc == NULL) {
return 1;
}
unsigned oldsize = getSize();
//cudaMemcpy(itemsrealloc, items, getSize() * sizeof(unsigned), cudaMemcpyDeviceToDevice);
copyOldToNew(items, itemsrealloc, oldsize, hcapacity);
dealloc();
items = itemsrealloc;
setCapacity(newcapacity);
setStartEnd(0, oldsize);
}
printf("\tworklist capacity set to %d.\n", getCapacity());
return 0;
}
unsigned Worklist::freeSize() {
return getCapacity() - getSize();
}
unsigned Worklist::ensureSpace(unsigned space) {
if (freeSize() >= space) {
return 0;
}
realloc(space);
// assert freeSize() >= space.
return 1;
}
unsigned Worklist::dealloc() {
cudaFree(items);
setInitialSize(0);
return 0;
}
Worklist::~Worklist() {
// dealloc();
// init();
}
__device__ unsigned Worklist::pushRange(unsigned *copyfrom, unsigned nitems) {
if (copyfrom == NULL || nitems == 0) return 0;
unsigned lcap = *capacity;
unsigned offset = atomicAdd(end, nitems);
if (offset >= lcap) { // overflow.
atomicSub(end, nitems);
//unsigned id = blockIdx.x * blockDim.x + threadIdx.x;
//printf("%s(%d): thread %d: buffer overflow, increase capacity beyond %d.\n", __FILE__, __LINE__, id, *capacity);
return 1;
}
for (unsigned ii = 0; ii < nitems; ++ii) {
items[(offset + ii) % lcap] = copyfrom[ii];
}
return 0;
}
__device__ unsigned Worklist::push(unsigned work) {
return pushRange(&work, 1);
}
__device__ unsigned Worklist::popRange(unsigned *copyto, unsigned nitems) {
unsigned currsize = count();
if (currsize < nitems) {
// popping fewer than requested number of items.
nitems = currsize;
}
//unsigned offset = atomicSub(size, nitems);
//unsigned offset = atomicCAS(size, currsize, currsize - nitems);
//unsigned offset = atomicExch(size, currsize - nitems);
unsigned offset = 0;
unsigned lcap = *capacity;
if (nitems) {
if (*start + nitems < lcap) {
offset = atomicAdd(start, nitems);
} else {
offset = atomicExch(start, *start + nitems - lcap);
}
}
// copy nitems starting from offset.
for (unsigned ii = 0; ii < nitems; ++ii) {
copyto[ii] = items[(offset + ii) % lcap];
}
return nitems;
}
__device__ unsigned Worklist::pop(unsigned &work) {
return popRange(&work, 1);
}
void Worklist::pushRangeHost(unsigned *copyfrom, unsigned nitems) {
ensureSpace(nitems);
unsigned hsize = getSize();
cudaMemcpy(items + hsize * sizeof(unsigned), copyfrom, nitems * sizeof(unsigned), cudaMemcpyHostToDevice);
hsize += nitems;
setSize(hsize);
}
void Worklist::pushHost(unsigned work) {
pushRangeHost(&work, 1);
}
__device__ void Worklist::clear() { // should be invoked by a single thread.
*end = *start;
}
void Worklist::clearHost() {
setSize(0);
}
__device__ void Worklist::myItems(unsigned &mystart, unsigned &myend) {
unsigned nblocks = gridDim.x;
unsigned nthreadsperblock = blockDim.x;
unsigned nthreads = nblocks * nthreadsperblock;
unsigned id = blockIdx.x * blockDim.x + threadIdx.x;
unsigned hsize = count();
if (nthreads > hsize) {
// each thread gets max 1 item.
if (id < hsize) {
mystart = id;
myend = mystart + 1; // one item.
} else {
mystart = id;
myend = mystart; // no items.
}
} else {
unsigned nitemsperthread = hsize / nthreads; // every thread gets at least these many.
unsigned nitemsremaining = hsize % nthreads; // initial some threads get one more.
mystart = id * nitemsperthread;
myend = mystart + nitemsperthread;
if (id < nitemsremaining) {
mystart += id; // initial few threads get one extra item, due to which
myend += id + 1; // their assignment changes.
} else {
mystart += nitemsremaining; // the others don't get anything extra, but
myend += nitemsremaining; // their assignment changes.
}
}
}
__device__ unsigned Worklist::getItem(unsigned at) {
unsigned hsize = count();
return getItemWithin(at, hsize);
}
__device__ unsigned Worklist::getItemWithin(unsigned at, unsigned hsize) {
if (at < hsize) {
return items[at];
}
unsigned id = blockIdx.x * blockDim.x + threadIdx.x;
printf("%s(%d): thread %d: buffer overflow, extracting %d when buffer size is %d.\n", __FILE__, __LINE__, id, at, hsize);
return 1;
}
__device__ unsigned Worklist::count() {
if (*end >= *start) {
return *end - *start;
} else {
return *end + (*capacity - *start + 1);
}
}
#define SWAPDEV(a, b) { unsigned tmp = a; a = b; b = tmp; }
__global__ void compress(Worklist wl, unsigned wlsize, unsigned sentinel) {
unsigned id = blockIdx.x * blockDim.x + threadIdx.x;
__shared__ unsigned shmem[MAXSHAREDUINT];
// copy my elements to my ids in shmem.
unsigned wlstart = MAXSHAREDUINT * blockIdx.x + SHAREDPERTHREAD * threadIdx.x;
unsigned shstart = SHAREDPERTHREAD * threadIdx.x;
for (unsigned ii = 0; ii < SHAREDPERTHREAD; ++ii) {
if (wlstart + ii < wlsize && shstart + ii < MAXSHAREDUINT) {
shmem[shstart + ii] = wl.getItemWithin(wlstart + ii, wlsize);
}
}
__syncthreads();
// sort in shmem.
for (unsigned s = blockDim.x / 2; s; s >>= 1) {
if (threadIdx.x < s) {
if (shmem[threadIdx.x] > shmem[threadIdx.x + s]) {
SWAPDEV(shmem[threadIdx.x], shmem[threadIdx.x + s]);
}
}
__syncthreads();
}
__syncthreads();
// uniq in shmem.
// TODO: find out how to do uniq in a hierarchical manner.
unsigned lastindex = 0;
if (id == 0) {
for (unsigned ii = 1; ii < MAXSHAREDUINT; ++ii) {
if (shmem[ii] != shmem[lastindex]) {
shmem[++lastindex] = shmem[ii];
} else {
shmem[ii] = sentinel;
}
}
}
__syncthreads();
// copy back elements to the worklist.
for (unsigned ii = 0; ii < SHAREDPERTHREAD; ++ii) {
if (wlstart + ii < wlsize) {
//shmem[shstart + ii] = getItem(wlstart + ii);
wl.items[wlstart + ii] = shmem[shstart + ii];
}
}
__syncthreads();
// update worklist indices.
if (id == 0) {
*wl.start = 0;
*wl.end = lastindex + 1;
}
}
void Worklist::compressHost(unsigned wlsize, unsigned sentinel) {
unsigned nblocks = (wlsize + MAXBLOCKSIZE - 1) / MAXBLOCKSIZE;
compress<<<nblocks, MAXBLOCKSIZE>>>(*this, wlsize, sentinel);
CudaTest("compress failed");
}
__global__ void printWorklist(Worklist wl) {
unsigned start, end;
start = *wl.start;
end = *wl.end;
printf("\t");
for (unsigned ii = start; ii < end; ++ii) {
printf("%d,", wl.getItem(ii));
}
printf("\n");
}
void Worklist::printHost() {
printWorklist<<<1, 1>>>(*this);
CudaTest("printWorklist failed");
}
__global__ void appendWorklist(Worklist dst, Worklist src, unsigned dstsize) {
unsigned start, end;
src.myItems(start, end);
for (unsigned ii = start; ii < end; ++ii) {
dst.items[dstsize + ii] = src.items[ii];
}
}
unsigned Worklist::appendHost(Worklist *otherlist) {
unsigned otherlistsize = otherlist->getSize();
unsigned nblocks = (otherlistsize + MAXBLOCKSIZE - 1) / MAXBLOCKSIZE;
appendWorklist<<<nblocks, MAXBLOCKSIZE>>>(*this, *otherlist, getSize());
CudaTest("appendWorklist failed");
unsigned hstart, hend;
getStartEnd(hstart, hend);
setStartEnd(hstart, hend + otherlistsize);
return hend + otherlistsize;
}
| 29.143902 | 122 | 0.699305 | [
"vector"
] |
1486ed47e41a2140254cf1d991e3842740e462ab | 2,019 | h | C | scene/node/transform/transform_3d.h | aconstlink/snakeoil | 3c6e02655e1134f8422f01073090efdde80fc109 | [
"MIT"
] | 1 | 2017-08-11T19:12:24.000Z | 2017-08-11T19:12:24.000Z | scene/node/transform/transform_3d.h | aconstlink/snakeoil | 3c6e02655e1134f8422f01073090efdde80fc109 | [
"MIT"
] | 11 | 2018-07-07T20:09:44.000Z | 2020-02-16T22:45:09.000Z | scene/node/transform/transform_3d.h | aconstlink/snakeoil | 3c6e02655e1134f8422f01073090efdde80fc109 | [
"MIT"
] | null | null | null | //------------------------------------------------------------
// snakeoil (c) Alexis Constantin Link
// Distributed under the MIT license
//------------------------------------------------------------
#ifndef _SNAKEOIL_SCENE_NODE_TRANSFORM_TRANSFORM_3D_H_
#define _SNAKEOIL_SCENE_NODE_TRANSFORM_TRANSFORM_3D_H_
#include "../decorator.h"
#include <snakeoil/flow/variable/variable.hpp>
#include <snakeoil/math/utility/3d/transformation.hpp>
namespace so_scene
{
namespace so_node
{
class SNAKEOIL_SCENE_API transform_3d : public decorator
{
typedef decorator base_t ;
so_this_typedefs( transform_3d ) ;
so_typedefs( so_math::so_3d::trafof_t, trafo ) ;
so_typedefs( so_flow::variable< so_math::mat4f_t >, var_mat4f ) ;
private:
trafo_t _trafo ;
var_mat4f_ptr_t _var_trafo ;
public:
transform_3d( void_t ) ;
transform_3d( this_rref_t ) ;
transform_3d( this_cref_t ) ;
transform_3d( so_math::so_3d::trafof_cref_t ) ;
transform_3d( iparent_ptr_t ) ;
transform_3d( node_ptr_t, iparent_ptr_t=nullptr ) ;
virtual ~transform_3d( void_t ) ;
private:
void_t ctor_init( void_t ) ;
public:
static this_ptr_t create( so_memory::purpose_cref_t ) ;
static this_ptr_t create( this_rref_t, so_memory::purpose_cref_t ) ;
static void_t destroy( this_ptr_t ) ;
public:
this_ref_t set_decorated( node_ptr_t ) ;
public:
void_t set_transformation( trafo_cref_t ) ;
trafo_cref_t get_transformation( void_t ) const ;
trafo_t compute_trafo( void_t ) const ;
public:
virtual so_scene::result apply( so_scene::so_visitor::ivisitor_ptr_t ptr ) ;
public:
virtual void_t destroy( void_t ) ;
};
so_typedef( transform_3d ) ;
}
}
#endif
| 27.657534 | 88 | 0.578009 | [
"3d"
] |
149323470d13a34c9aab30f8651350ded35ae312 | 4,210 | h | C | aws-cpp-sdk-lexv2-models/include/aws/lexv2-models/model/DescribeBotAliasRequest.h | perfectrecall/aws-sdk-cpp | fb8cbebf2fd62720b65aeff841ad2950e73d8ebd | [
"Apache-2.0"
] | 1 | 2022-02-10T08:06:54.000Z | 2022-02-10T08:06:54.000Z | aws-cpp-sdk-lexv2-models/include/aws/lexv2-models/model/DescribeBotAliasRequest.h | perfectrecall/aws-sdk-cpp | fb8cbebf2fd62720b65aeff841ad2950e73d8ebd | [
"Apache-2.0"
] | 1 | 2022-01-03T23:59:37.000Z | 2022-01-03T23:59:37.000Z | aws-cpp-sdk-lexv2-models/include/aws/lexv2-models/model/DescribeBotAliasRequest.h | ravindra-wagh/aws-sdk-cpp | 7d5ff01b3c3b872f31ca98fb4ce868cd01e97696 | [
"Apache-2.0"
] | 1 | 2022-02-28T21:36:42.000Z | 2022-02-28T21:36:42.000Z | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#pragma once
#include <aws/lexv2-models/LexModelsV2_EXPORTS.h>
#include <aws/lexv2-models/LexModelsV2Request.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>
namespace Aws
{
namespace LexModelsV2
{
namespace Model
{
/**
*/
class AWS_LEXMODELSV2_API DescribeBotAliasRequest : public LexModelsV2Request
{
public:
DescribeBotAliasRequest();
// Service request name is the Operation name which will send this request out,
// each operation should has unique request name, so that we can get operation's name from this request.
// Note: this is not true for response, multiple operations may have the same response name,
// so we can not get operation's name from response.
inline virtual const char* GetServiceRequestName() const override { return "DescribeBotAlias"; }
Aws::String SerializePayload() const override;
/**
* <p>The identifier of the bot alias to describe.</p>
*/
inline const Aws::String& GetBotAliasId() const{ return m_botAliasId; }
/**
* <p>The identifier of the bot alias to describe.</p>
*/
inline bool BotAliasIdHasBeenSet() const { return m_botAliasIdHasBeenSet; }
/**
* <p>The identifier of the bot alias to describe.</p>
*/
inline void SetBotAliasId(const Aws::String& value) { m_botAliasIdHasBeenSet = true; m_botAliasId = value; }
/**
* <p>The identifier of the bot alias to describe.</p>
*/
inline void SetBotAliasId(Aws::String&& value) { m_botAliasIdHasBeenSet = true; m_botAliasId = std::move(value); }
/**
* <p>The identifier of the bot alias to describe.</p>
*/
inline void SetBotAliasId(const char* value) { m_botAliasIdHasBeenSet = true; m_botAliasId.assign(value); }
/**
* <p>The identifier of the bot alias to describe.</p>
*/
inline DescribeBotAliasRequest& WithBotAliasId(const Aws::String& value) { SetBotAliasId(value); return *this;}
/**
* <p>The identifier of the bot alias to describe.</p>
*/
inline DescribeBotAliasRequest& WithBotAliasId(Aws::String&& value) { SetBotAliasId(std::move(value)); return *this;}
/**
* <p>The identifier of the bot alias to describe.</p>
*/
inline DescribeBotAliasRequest& WithBotAliasId(const char* value) { SetBotAliasId(value); return *this;}
/**
* <p>The identifier of the bot associated with the bot alias to describe.</p>
*/
inline const Aws::String& GetBotId() const{ return m_botId; }
/**
* <p>The identifier of the bot associated with the bot alias to describe.</p>
*/
inline bool BotIdHasBeenSet() const { return m_botIdHasBeenSet; }
/**
* <p>The identifier of the bot associated with the bot alias to describe.</p>
*/
inline void SetBotId(const Aws::String& value) { m_botIdHasBeenSet = true; m_botId = value; }
/**
* <p>The identifier of the bot associated with the bot alias to describe.</p>
*/
inline void SetBotId(Aws::String&& value) { m_botIdHasBeenSet = true; m_botId = std::move(value); }
/**
* <p>The identifier of the bot associated with the bot alias to describe.</p>
*/
inline void SetBotId(const char* value) { m_botIdHasBeenSet = true; m_botId.assign(value); }
/**
* <p>The identifier of the bot associated with the bot alias to describe.</p>
*/
inline DescribeBotAliasRequest& WithBotId(const Aws::String& value) { SetBotId(value); return *this;}
/**
* <p>The identifier of the bot associated with the bot alias to describe.</p>
*/
inline DescribeBotAliasRequest& WithBotId(Aws::String&& value) { SetBotId(std::move(value)); return *this;}
/**
* <p>The identifier of the bot associated with the bot alias to describe.</p>
*/
inline DescribeBotAliasRequest& WithBotId(const char* value) { SetBotId(value); return *this;}
private:
Aws::String m_botAliasId;
bool m_botAliasIdHasBeenSet;
Aws::String m_botId;
bool m_botIdHasBeenSet;
};
} // namespace Model
} // namespace LexModelsV2
} // namespace Aws
| 32.890625 | 121 | 0.674822 | [
"model"
] |
149fb884d9c7e0ee67132a02481b839aa4979450 | 1,943 | c | C | lib/wizards/jenny/events/robbers/event_ob.c | vlehtola/questmud | 8bc3099b5ad00a9e0261faeb6637c76b521b6dbe | [
"MIT"
] | null | null | null | lib/wizards/jenny/events/robbers/event_ob.c | vlehtola/questmud | 8bc3099b5ad00a9e0261faeb6637c76b521b6dbe | [
"MIT"
] | null | null | null | lib/wizards/jenny/events/robbers/event_ob.c | vlehtola/questmud | 8bc3099b5ad00a9e0261faeb6637c76b521b6dbe | [
"MIT"
] | null | null | null | #define RUNNER "/wizards/jenny/events/robbers/runner"
#define ARRAY "/wizards/jenny/events/robbers/arrays"
#define ROBBERS "/wizards/jenny/events/robbers/robber"
#define ENDIT "/wizards/jenny/events/robbers/event_ob"
#define TPQN this_player()->query_name()
#define VOID "/wizards/jenny/city/void"
#define CITY "/world/city/"
object ob1,ob2,monster,monster2, guard;
int x,y;
mixed *stuff;
status dead;
reset(arg){
if(arg) return;
stuff = allocate(31);
}
void start_event() {
string *rooms, room;
dead = 0;
write("You start the Bandit invasion.\n");
shout("Heeeeeeeelp, its Gorgola!\n");
monster2=clone_object("/wizards/jenny/events/robbers/gorgola.c");
y=random(ARRAY->query_room_size());
move_object(monster2,call_other(ARRAY+".c","query_rooms",y));
for(x=0;x < 30;x++){
y=random(ARRAY->query_room_size());
monster=clone_object("/wizards/jenny/events/robbers/robber.c");
move_object(monster,call_other(ARRAY+".c","query_rooms",y));
stuff[x] = monster;
}
room = CITY+"*.c";
rooms = get_dir(room);
for(x=0;x < sizeof(rooms);x++) {
room = CITY+rooms[x];
room = room[0..strlen(room)-3];
if(find_object(room)) {
guard = present("cityguard",find_object(room));
if(guard) {
guard->move_out();
}
}
}
call_out("ender", 20000);
}
void end_event() {
dead = 1;
write("You end the Bandit invasion.\n");
shout("City is saved, Hooray!\n");
for(x=0;x<sizeof(stuff);x++){
if (stuff[x]) destruct(stuff[x]);
}
while (remove_call_out("ender") != -1);
guard = present("guard",find_object(VOID));
while(guard) {
guard->move_in();
guard = present("guard",find_object(VOID));
}
}
void end() {
RUNNER->end_event();
for(x=0;x<sizeof(stuff);x++){
if (stuff[x]) destruct(stuff[x]);
dead = 1;
}
}
query_stf(){ return stuff; }
ender(){
if(!dead){
ENDIT->end();
dead = 1;
}
}
| 23.695122 | 67 | 0.623263 | [
"object"
] |
14a2c2a5b76720aefe795fa756a85b90f94fbc4b | 2,260 | h | C | src/Global/headers/Swap.h | nishantmehta/mainGrokit | eda13cd32d523bfc2af660c34c93a38eceaccc4a | [
"Apache-2.0"
] | null | null | null | src/Global/headers/Swap.h | nishantmehta/mainGrokit | eda13cd32d523bfc2af660c34c93a38eceaccc4a | [
"Apache-2.0"
] | null | null | null | src/Global/headers/Swap.h | nishantmehta/mainGrokit | eda13cd32d523bfc2af660c34c93a38eceaccc4a | [
"Apache-2.0"
] | null | null | null | //
// Copyright 2012 Alin Dobra and Christopher Jermaine
//
// 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 _SWAP_H_
#define _SWAP_H_
#include "Constants.h"
#include "Config.h"
#include <cstring>
#include "Pragma.h"
/**
This header contains macro definitions to streamline the swapping of data.
The main macro defined is SWAP(a,b) that swaps the content of a and b as
long as they are of the same type and they support the = operator.
Notice that the type of the a and b is not passed and it is infered using typeof()
operator.
*/
// Macro to swap variables using assignment and a temporary
#ifdef _HAS_CPP_11
#define SWAP_ASSIGN(a,b) { \
decltype(a) tmp = ( a ); \
( a ) = ( b ); \
( b ) = tmp; \
}
#else
#define SWAP_ASSIGN(a,b) { \
typeof(a) tmp = ( a ); \
( a ) = ( b ); \
( b ) = tmp; \
}
#endif
// Macro to swap variables using swap()
#ifdef _HAS_CPP_11
#include <utility>
#define SWAP_STD(a, b) { \
using std::swap; \
swap( a, b ); \
}
#else
#include <algorithm>
#define SWAP_STD(a, b) { \
using std::swap; \
swap( a, b ); \
}
#endif
/*
#define SWAP_STD(a, b) SWAP_ASSIGN(a, b)
*/
// Old swap macro
#define SWAP(a, b) \
PRAGMA_MSG("Warning: Using old swap macro") \
SWAP_ASSIGN( a , b )
/* Macro to swap classes using memmove.
WARNING: this macro introduces a horrible bug if the class contains
any STL datastructres. Use explicit SWAP.
*/
#define SWAP_memmove(class_name, object) \
char storage[sizeof (class_name)]; \
memmove ((void *) storage, (void *) this, sizeof (class_name)); \
memmove ((void *) this, (void *) &object, sizeof (class_name)); \
memmove ((void *) &object, (void *) storage, sizeof (class_name));
#endif //_SWAP_H_
| 26.588235 | 84 | 0.666814 | [
"object"
] |
e7a066eb542566a3918015985f1e96886f5bb40b | 210,586 | c | C | dynamorio/core/win32/ntdll.c | andre-motta/Project3Compilers | fa366d93ec8d49768fbc86f0c1431391822baf12 | [
"MIT"
] | 14 | 2020-12-22T03:15:38.000Z | 2022-01-30T09:22:06.000Z | dynamorio/core/win32/ntdll.c | andre-motta/Project3Compilers | fa366d93ec8d49768fbc86f0c1431391822baf12 | [
"MIT"
] | 1 | 2021-06-01T12:10:25.000Z | 2021-06-01T12:10:25.000Z | dynamorio/core/win32/ntdll.c | andre-motta/Project3Compilers | fa366d93ec8d49768fbc86f0c1431391822baf12 | [
"MIT"
] | 7 | 2021-01-01T03:03:57.000Z | 2022-03-29T07:28:38.000Z | /* **********************************************************
* Copyright (c) 2010-2020 Google, Inc. All rights reserved.
* Copyright (c) 2003-2010 VMware, 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 VMware, Inc. nor the names of its contributors may be
* used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL VMWARE, INC. OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*/
/* Copyright (c) 2003-2007 Determina Corp. */
/*
* ntdll.c
* Routines for calling Windows system calls via the ntdll.dll wrappers.
*
* This file is used by the main library, the preinject library, and the
* standalone injector.
*/
#include "configure.h"
#ifdef NOT_DYNAMORIO_CORE
# define ASSERT(x)
# define ASSERT_CURIOSITY(x)
# define ASSERT_NOT_REACHED()
# define ASSERT_NOT_IMPLEMENTED(x)
# define DODEBUG(x)
# define DOCHECK(n, x)
# define DEBUG_DECLARE(x)
# pragma warning(disable : 4210) // nonstd extension: function given file scope
# pragma warning(disable : 4204) // nonstd extension: non-constant aggregate
// initializer
# define INVALID_FILE INVALID_HANDLE_VALUE
# define snprintf _snprintf
# include <stdio.h> /* _snprintf */
#else
/* we include globals.h mainly for ASSERT, even though we're
* used by preinject.
* preinject just defines its own d_r_internal_error!
*/
# include "../globals.h"
# include "../module_shared.h"
#endif
/* We have to hack away things we use here that won't work for non-core */
#if defined(NOT_DYNAMORIO_CORE_PROPER) || defined(NOT_DYNAMORIO_CORE)
# undef ASSERT_OWN_NO_LOCKS
# define ASSERT_OWN_NO_LOCKS() /* who cares if not the core */
#endif
#include "ntdll.h"
#ifndef NOT_DYNAMORIO_CORE
# include "os_private.h"
#endif
#include <wchar.h> /* _snwprintf */
/* WARNING: these routines use the Native API, an undocumented API
* exported by ntdll.dll.
* It could change without warning with a new version of Windows.
*/
/* FIXME : combine NTPRINT with NTLOG */
/* must turn on VERBOSE in inject_shared.c as well since we're now
* using display_verbose_message() -- FIXME: link them automatically */
#if defined(NOT_DYNAMORIO_CORE_PROPER) || defined(NOT_DYNAMORIO_CORE)
# define VERBOSE 0
#else
# define VERBOSE 0
#endif
#if VERBOSE
/* in inject_shared.c: must turn on VERBOSE=1 there as well */
void
display_verbose_message(char *format, ...);
# define NTPRINT(...) display_verbose_message(__VA_ARGS__)
#else
# define NTPRINT(...)
#endif
/* i#437 support ymm */
uint context_xstate = 0;
/* needed for injector and preinject, to avoid them requiring asm and syscalls */
#if defined(NOT_DYNAMORIO_CORE_PROPER) || defined(NOT_DYNAMORIO_CORE)
/* use ntdll wrappers for simplicity, to keep ntdll.c standalone */
# define GET_SYSCALL(name, ...) GET_NTDLL(Nt##name, (__VA_ARGS__))
# define GET_RAW_SYSCALL GET_SYSCALL
# define NT_SYSCALL(name, ...) Nt##name(__VA_ARGS__)
# define NTLOG(...)
#else
# define NTLOG LOG
/* Our own syscall wrapper to avoid relying on ntdll, for 4 reasons:
* 1) Maximum interoperability w/ ntdll hookers
* 2) Security by avoiding being disabled via ntdll being messed up
* 3) Early injection: although ntdll is already in the address space,
* this way we don't need the loader
* 4) Easier trampolines on ntdll syscall wrappers for handling native code
* (don't have to worry about DR syscalls going through the trampolines)
*
* For now we only use our own wrapper for syscalls in the app-relevant array.
* When we add the rest we can:
* 1) leave out of array, and dynamically determine
* (ideally using our own version of GetProcAddress)
* 2) add to array, then everything's consistent
* 3) eliminate array completely and always dynamically determine
* But, relying on dynamic determination means we won't work if there's a hook
* already placed there (losing a big advantage of our own wrappers), and
* dynamically determining doesn't give us that much more independence --
* we still need to manually verify each new ntdll for other types of
* syscall changes (new syscalls we care about, semantic changes, etc.)
*/
/* decides which of dynamorio_syscall_{int2e,sysenter,wow64} to use */
static enum {
DR_SYSCALL_INT2E,
DR_SYSCALL_SYSENTER,
DR_SYSCALL_SYSCALL,
DR_SYSCALL_WOW64,
} dr_which_syscall_t;
/* For x64 "raw syscalls", i.e., those we call directly w/o invoking the
* ntdll wrapper routine, we play some games with types to work more
* easily w/ the x64 calling convention:
*/
# define GET_RAW_SYSCALL(name, arg1, ...) \
GET_NTDLL(Nt##name, (arg1, __VA_ARGS__)); \
typedef NTSTATUS name##_type(int sysnum, arg1, __VA_ARGS__); \
typedef NTSTATUS name##_dr_type(int sys_enum, __VA_ARGS__, arg1)
# define GET_SYSCALL(name, ...) \
GET_NTDLL(Nt##name, (__VA_ARGS__)); \
typedef NTSTATUS name##_type(int sysnum, __VA_ARGS__)
/* FIXME - since it doesn't vary we could have a variable to store the dr
* syscall routine to use, but would be yet another function pointer in
* our data segment... */
/* We use the wrappers till the native_exec Nt hooks go in (at which point
* the options have been read) so that we can have sygate compatibility as a
* runtime option. */
/* For X64 sycall we need the 1st arg last to preserve the rest in their
* proper registers. If we ever support 0-arg syscalls here we'll
* need a separate macro for those.
* Any syscall called using this macro must be declared with GET_RAW_SYSCALL
* rather than GET_SYSCALL to get the types to match up.
*/
/* i#1011: We usually use NT_SYSCALL to invoke a system call. However,
* for system calls that do not exist in older Windows, e.g. NtOpenKeyEx,
* we use NT_RAW_SYSCALL to avoid static link and build failure.
*/
# define NT_RAW_SYSCALL(name, arg1, ...) \
((dr_which_syscall_t == DR_SYSCALL_WOW64) \
? (!syscall_uses_edx_param_base() \
? ((name##_type *)dynamorio_syscall_wow64_noedx)(SYS_##name, arg1, \
__VA_ARGS__) \
: (((name##_type *)dynamorio_syscall_wow64)(SYS_##name, arg1, \
__VA_ARGS__))) \
: ((IF_X64_ELSE(dr_which_syscall_t == DR_SYSCALL_SYSCALL, false)) \
? ((name##_dr_type *)IF_X64_ELSE(dynamorio_syscall_syscall, NULL))( \
SYS_##name, __VA_ARGS__, arg1) \
: (((name##_type *)((dr_which_syscall_t == DR_SYSCALL_SYSENTER) \
? (DYNAMO_OPTION(dr_sygate_sysenter) \
? dynamorio_syscall_sygate_sysenter \
: dynamorio_syscall_sysenter) \
: (DYNAMO_OPTION(dr_sygate_int) \
? dynamorio_syscall_sygate_int2e \
: dynamorio_syscall_int2e)))( \
syscalls[SYS_##name], arg1, __VA_ARGS__))))
# define NT_SYSCALL(name, arg1, ...) \
(nt_wrappers_intercepted ? Nt##name(arg1, __VA_ARGS__) \
: NT_RAW_SYSCALL(name, arg1, __VA_ARGS__))
/* check syscall numbers without using any heap */
# ifdef X64
# define SYSNUM_OFFS 4
# else
# define SYSNUM_OFFS 1
# endif
# define CHECK_SYSNUM_AT(pc, idx) \
ASSERT(pc != NULL && \
(*((int *)((pc) + SYSNUM_OFFS)) == syscalls[idx] || ALLOW_HOOKER(pc) || \
(idx == SYS_TestAlert && *(uint *)(pc) == 0xe9505050))); /* xref 9288 */
/* assuming relative CTI's are the only one's used by hookers */
# define ALLOW_HOOKER(pc) \
(*(unsigned char *)(pc) == JMP_REL32_OPCODE || \
*(unsigned char *)(pc) == CALL_REL32_OPCODE)
/* FIXME: we'll evaluate pc multiple times in the above macro */
static void
tls_exit(void);
#endif /* !NOT_DYNAMORIO_CORE_PROPER */
/* cached value */
static PEB *own_peb = NULL;
/****************************************************************************
* Defines only needed internally to this file
*/
/* TlsSlots offset is hardcoded into kernel32!TlsGetValue as 0xe10 on all
* 32-bit platforms we've seen, 0x1480 for 64-bit:
*/
#ifdef X64
# define TEB_TLS64_OFFSET 0x1480
#else
# define TEB_TLS64_OFFSET 0xe10
#endif
/***************************************************************************
* declarations for ntdll exports shared by several routines in this file
*/
GET_NTDLL(NtQueryInformationProcess,
(IN HANDLE ProcessHandle, IN PROCESSINFOCLASS ProcessInformationClass,
OUT PVOID ProcessInformation, IN ULONG ProcessInformationLength,
OUT PULONG ReturnLength OPTIONAL));
GET_NTDLL(NtQueryInformationFile,
(IN HANDLE FileHandle, OUT PIO_STATUS_BLOCK IoStatusBlock,
OUT PVOID FileInformation, IN ULONG FileInformationLength,
IN FILE_INFORMATION_CLASS FileInformationClass));
GET_NTDLL(NtQuerySection,
(IN HANDLE SectionHandle, IN SECTION_INFORMATION_CLASS SectionInformationClass,
OUT PVOID SectionInformation, IN ULONG SectionInformationLength,
OUT PULONG ResultLength OPTIONAL));
GET_NTDLL(NtQueryInformationToken,
(IN HANDLE TokenHandle, IN TOKEN_INFORMATION_CLASS TokenInformationClass,
OUT PVOID TokenInformation, IN ULONG TokenInformationLength,
OUT PULONG ReturnLength));
/* routines that we may hook if specified in
* syscall_requires_action[], all new routines can use GET_SYSCALL
* instead of GET_NTDLL if we provide the syscall numbers - see
* comments in GET_SYSCALL definition.
*/
GET_RAW_SYSCALL(QueryVirtualMemory, IN HANDLE ProcessHandle, IN const void *BaseAddress,
IN MEMORY_INFORMATION_CLASS MemoryInformationClass,
OUT PVOID MemoryInformation, IN SIZE_T MemoryInformationLength,
OUT PSIZE_T ReturnLength OPTIONAL);
GET_RAW_SYSCALL(UnmapViewOfSection, IN HANDLE ProcessHandle, IN PVOID BaseAddress);
GET_RAW_SYSCALL(CreateSection, OUT PHANDLE SectionHandle, IN ACCESS_MASK DesiredAccess,
IN POBJECT_ATTRIBUTES ObjectAttributes,
IN PLARGE_INTEGER SectionSize OPTIONAL, IN ULONG Protect,
IN ULONG Attributes, IN HANDLE FileHandle);
GET_RAW_SYSCALL(OpenSection, OUT PHANDLE SectionHandle, IN ACCESS_MASK DesiredAccess,
IN POBJECT_ATTRIBUTES ObjectAttributes);
GET_RAW_SYSCALL(AllocateVirtualMemory, IN HANDLE ProcessHandle, IN OUT PVOID *BaseAddress,
IN ULONG ZeroBits, IN OUT PSIZE_T AllocationSize, IN ULONG AllocationType,
IN ULONG Protect);
GET_RAW_SYSCALL(FreeVirtualMemory, IN HANDLE ProcessHandle, IN OUT PVOID *BaseAddress,
IN OUT PSIZE_T FreeSize, IN ULONG FreeType);
GET_RAW_SYSCALL(ProtectVirtualMemory, IN HANDLE ProcessHandle, IN OUT PVOID *BaseAddress,
IN OUT PSIZE_T ProtectSize, IN ULONG NewProtect, OUT PULONG OldProtect);
GET_RAW_SYSCALL(QueryInformationThread, IN HANDLE ThreadHandle,
IN THREADINFOCLASS ThreadInformationClass, OUT PVOID ThreadInformation,
IN ULONG ThreadInformationLength, OUT PULONG ReturnLength OPTIONAL);
/* CreateFile is defined CreateFileW (Unicode) or CreateFileA (ANSI),
* undefine here for system call.
*/
#undef CreateFile
GET_RAW_SYSCALL(CreateFile, OUT PHANDLE FileHandle, IN ACCESS_MASK DesiredAccess,
IN POBJECT_ATTRIBUTES ObjectAttributes,
OUT PIO_STATUS_BLOCK IoStatusBlock,
IN PLARGE_INTEGER AllocationSize OPTIONAL, IN ULONG FileAttributes,
IN ULONG ShareAccess, IN ULONG CreateDisposition, IN ULONG CreateOptions,
IN PVOID EaBuffer OPTIONAL, IN ULONG EaLength);
GET_RAW_SYSCALL(CreateKey, OUT PHANDLE KeyHandle, IN ACCESS_MASK DesiredAccess,
IN POBJECT_ATTRIBUTES ObjectAttributes, IN ULONG TitleIndex,
IN PUNICODE_STRING Class OPTIONAL, IN ULONG CreateOptions,
OUT PULONG Disposition OPTIONAL);
GET_RAW_SYSCALL(OpenKey, OUT PHANDLE KeyHandle, IN ACCESS_MASK DesiredAccess,
IN POBJECT_ATTRIBUTES ObjectAttributes);
GET_RAW_SYSCALL(SetInformationFile, IN HANDLE FileHandle,
OUT PIO_STATUS_BLOCK IoStatusBlock, IN PVOID FileInformation,
IN ULONG FileInformationLength,
IN FILE_INFORMATION_CLASS FileInformationClass);
/* the same structure as _CONTEXT_EX in winnt.h */
typedef struct _context_chunk_t {
LONG offset;
DWORD length;
} context_chunk_t;
/* the same structure as _CONTEXT_CHUNK in winnt.h */
typedef struct _context_ex_t {
context_chunk_t all;
context_chunk_t legacy;
context_chunk_t xstate;
} context_ex_t;
/* XXX, the function below can be statically-linked if all versions of
* ntdll have the corresponding routine, which need to be checked, so we use
* get_proc_address to get instead here.
*/
typedef int(WINAPI *ntdll_RtlGetExtendedContextLength_t)(DWORD, int *);
typedef int(WINAPI *ntdll_RtlInitializeExtendedContext_t)(PVOID, DWORD, context_ex_t **);
typedef CONTEXT *(WINAPI *ntdll_RtlLocateLegacyContext_t)(context_ex_t *, DWORD);
ntdll_RtlGetExtendedContextLength_t ntdll_RtlGetExtendedContextLength = NULL;
ntdll_RtlInitializeExtendedContext_t ntdll_RtlInitializeExtendedContext = NULL;
ntdll_RtlLocateLegacyContext_t ntdll_RtlLocateLegacyContext = NULL;
#if !defined(NOT_DYNAMORIO_CORE_PROPER) && !defined(NOT_DYNAMORIO_CORE)
/* Nt* routines that are not available on all versions of Windows */
typedef NTSTATUS(WINAPI *NtGetNextThread_t)(__in HANDLE ProcessHandle,
__in HANDLE ThreadHandle,
__in ACCESS_MASK DesiredAccess,
__in ULONG HandleAttributes, __in ULONG Flags,
__out PHANDLE NewThreadHandle);
NtGetNextThread_t NtGetNextThread;
#endif
/***************************************************************************
* Implementation
*/
#if !defined(NOT_DYNAMORIO_CORE_PROPER) && !defined(NOT_DYNAMORIO_CORE)
/* for Sygate 5441 compatibility hack, we need a tls slot for NT_SYSCALL when
* using sysenter system calls */
uint sysenter_tls_offset = 0xffffffff; /* something that will fault */
/* will be set to false once the options are read but before the native_exec
* Nt* hooks are put in. Till then lets NT_SYSCALL know it's safe to call via
* the wrappers for Sygate compatibility before the option string is read in. */
static bool nt_wrappers_intercepted = true;
void
syscalls_init_options_read()
{
if (DYNAMO_OPTION(dr_sygate_sysenter)) {
tls_alloc(false /* don't grab lock */, &sysenter_tls_offset);
}
nt_wrappers_intercepted = false;
}
static int
syscalls_init_get_num(HANDLE ntdllh, int sys_enum)
{
app_pc wrapper;
ASSERT(ntdllh != NULL);
/* We can't check syscalls[] for SYSCALL_NOT_PRESENT b/c it's not set up yet */
/* d_r_get_proc_address() does invoke NtQueryVirtualMemory, but we go through the
* ntdll wrapper for that syscall and thus it works this early.
*/
wrapper = (app_pc)d_r_get_proc_address(ntdllh, syscall_names[sys_enum]);
if (wrapper != NULL && !ALLOW_HOOKER(wrapper))
return *((int *)((wrapper) + SYSNUM_OFFS));
else
return -1;
}
/* Called very early, prior to any system call use by us, making error
* reporting problematic once we have all syscalls requiring this!
* See windows_version_init() comments.
* The other problem w/ error reporting is that other code assumes
* that things are initialized -- that's all fixed now, with stats, dcontext,
* etc. checked for NULL in all the right places.
*/
bool
syscalls_init()
{
/* Determine which syscall routine to use
* We don't have heap available yet (no syscalls yet!) so
* we can't decode easily.
* FIXME: for app syscalls, we wait until we see one so we know
* the method being used -- should we move that decision up, since
* we're checking here for DR?
*/
/* pick a syscall that is unlikely to be hooked, ref case 5217 Sygate
* requires all int system call to occur in ntdll.dll or sysfer.dll
* so we borrow the int 2e from NtYieldExecution for system calls!
* (both our own and the apps via shared_syscall). The Nt* wrappers
* are stdcall so NtYieldExecution is convenient since it has zero
* args and is unlikely to be hooked. Ref case 5441, Sygate also sometimes
* verifies the top of the stack for sysenter system calls in a similar
* fashion (must be in ntdll/sysfer). For that we again borrow out of
* NtYieldExecution (this time just the ret) to fix up our stack. */
GET_NTDLL(NtYieldExecution, (VOID));
/* N.B.: if we change which syscall, for WOW64 the wrapper can change */
app_pc pc = (app_pc)NtYieldExecution;
app_pc int_target = pc + 9;
ushort check = *((ushort *)(int_target));
HMODULE ntdllh = get_ntdll_base();
if (!windows_version_init(syscalls_init_get_num(ntdllh, SYS_GetContextThread),
syscalls_init_get_num(ntdllh, SYS_AllocateVirtualMemory)))
return false;
ASSERT(syscalls != NULL);
/* We check the 10th and 11th bytes to identify the gateway.
* XXX i#1854: we should try and reduce how fragile we are wrt small
* changes in syscall wrapper sequences.
*
* int 2e: {2k}
* 77F97BFA: B8 BA 00 00 00 mov eax,0BAh
* 77F97BFF: 8D 54 24 04 lea edx,[esp+4]
* 77F97C03: CD 2E int 2Eh
* ret (stdcall)
* sysenter: {xpsp[0,1] 2k3sp0}
* 0x77f7eb23 b8 77 00 00 00 mov $0x00000077 -> %eax
* 0x77f7eb28 ba 00 03 fe 7f mov $0x7ffe0300 -> %edx
* 0x77f7eb2d ff d2 call %edx
* ret (stdcall)
* sysenter: {xpsp2 2k3sp1}
* 0x77f7eb23 b8 77 00 00 00 mov $0x00000077 -> %eax
* 0x77f7eb28 ba 00 03 fe 7f mov $0x7ffe0300 -> %edx
* 0x77f7eb2d ff 12 call [%edx]
* ret (stdcall)
* wow64 xp64 (case 3922):
* 7d61ce3f b843000000 mov eax,0x43
* 7d61ce44 b901000000 mov ecx,0x1
* 7d61ce49 8d542404 lea edx,[esp+0x4]
* 7d61ce4d 64ff15c0000000 call dword ptr fs:[000000c0]
* 7d61ce54 c3 ret
* x64 syscall (PR 215398):
* 00000000`78ef16c0 4c8bd1 mov r10,rcx
* 00000000`78ef16c3 b843000000 mov eax,43h
* 00000000`78ef16c8 0f05 syscall
* 00000000`78ef16ca c3 ret
* win8+ sysenter w/ co-located "inlined" callee:
* 77d7422c b801000000 mov eax,1
* 77d74231 e801000000 call ntdll!NtYieldExecution+0xb (77d74237)
* 77d74236 c3 ret
* 77d74237 8bd4 mov edx,esp
* 77d74239 0f34 sysenter
* 77d7423b c3 ret
* win8 and win8.1 wow64 syscall (has no ecx):
* 777311bc b844000100 mov eax,10044h
* 777311c1 64ff15c0000000 call dword ptr fs:[0C0h]
* 777311c8 c3 ret
* win10 wow64 syscall:
* 77cd9040 b846000100 mov eax,10046h
* 77cd9045 bab0d5ce77 mov edx,offset ntdll!Wow64SystemServiceCall
* 77cd904a ffd2 call edx
* 77cd904c c3 ret
* ntdll!Wow64SystemServiceCall:
* 77ced5b0 648b1530000000 mov edx,dword ptr fs:[30h]
* 77ced5b7 8b9254020000 mov edx,dword ptr [edx+254h]
* 77ced5bd f7c202000000 test edx,2
* 77ced5c3 7403 je ntdll!Wow64SystemServiceCall+0x18 (77ced5c8)
* 77ced5c5 cd2e int 2Eh
* 77ced5c7 c3 ret
* 77ced5c8 eacfd5ce773300 jmp 0033:77CED5CF
* 77ced5cf 41 inc ecx
* win10-1607 wow64:
* ntdll!Wow64SystemServiceCall:
* 77c32330 ff251812cc77 jmp dword ptr [ntdll!Wow64Transition (77cc1218)]
* 0:000> U poi(77cc1218)
* 58787000 ea097078583300 jmp 0033:58787009
* win10-TH2(1511) x64:
* 7ff9`13185630 4c8bd1 mov r10,rcx
* 7ff9`13185633 b843000000 mov eax,43h
* 7ff9`13185638 f604250803fe7f01 test byte ptr [SharedUserData+0x308(`7ffe0308)],1
* 7ff9`13185640 7503 jne ntdll!NtContinue+0x15 (00007ff9`13185645)
* 7ff9`13185642 0f05 syscall
* 7ff9`13185644 c3 ret
* 7ff9`13185645 cd2e int 2Eh
* 7ff9`13185647 c3 ret
*/
if (check == 0x2ecd) {
dr_which_syscall_t = DR_SYSCALL_INT2E;
set_syscall_method(SYSCALL_METHOD_INT);
int_syscall_address = int_target;
/* ASSERT is simple ret (i.e. 0 args) */
ASSERT(*(byte *)(int_target + 2) == 0xc3 /* ret 0 */);
} else if (check == 0x8d00 || check == 0x0000 /* win8 */) {
ASSERT(is_wow64_process(NT_CURRENT_PROCESS));
dr_which_syscall_t = DR_SYSCALL_WOW64;
set_syscall_method(SYSCALL_METHOD_WOW64);
if (check == 0x8d00) /* xp through win7 */
wow64_index = (int *)windows_XP_wow64_index;
DOCHECK(1, {
int call_start_offs = (check == 0x8d00) ? 5 : -4;
ASSERT(*((uint *)(int_target + call_start_offs)) == 0xc015ff64);
ASSERT(*((uint *)(int_target + call_start_offs + 3)) == WOW64_TIB_OFFSET);
});
DOCHECK(1, {
/* We assume syscalls go through teb->WOW32Reserved */
TEB *teb = get_own_teb();
ASSERT(teb != NULL && teb->WOW32Reserved != NULL);
});
# ifdef X64 /* PR 205898 covers 32-bit syscall support */
} else if (check == 0xc305 || check == 0x2504) {
dr_which_syscall_t = DR_SYSCALL_SYSCALL;
set_syscall_method(SYSCALL_METHOD_SYSCALL);
/* ASSERT is syscall */
ASSERT(*(int_target - 1) == 0x0f || *(ushort *)(int_target + 9) == 0x050f);
# endif
} else if (check == 0xff7f &&
/* rule out win10 wow64 */
*(app_pc *)(pc + 6) == VSYSCALL_BOOTSTRAP_ADDR) {
app_pc vsys;
/* verify is call %edx or call [%edx] followed by ret 0 [0xc3] */
ASSERT(*((ushort *)(int_target + 2)) == 0xc3d2 ||
*((ushort *)(int_target + 2)) == 0xc312);
/* Double check use_ki_syscall_routines() matches type of ind call used */
ASSERT((!use_ki_syscall_routines() && *((ushort *)(int_target + 1)) == 0xd2ff) ||
(use_ki_syscall_routines() && *((ushort *)(int_target + 1)) == 0x12ff));
/* verify VSYSCALL_BOOTSTRAP_ADDR */
IF_X64(ASSERT_NOT_IMPLEMENTED(false));
ASSERT(*((uint *)(int_target - 3)) == (uint)(ptr_uint_t)VSYSCALL_BOOTSTRAP_ADDR);
/* DrM i#1724 (and old case 5463): old hardware, or virtualized hardware,
* may not suport sysenter.
* Thus we need to drill down into the vsyscall code itself:
* 0x7ffe0300 8b d4 mov %esp -> %edx
* 0x7ffe0302 0f 34 sysenter
* Versus:
* 0x7c90e520 8d 54 24 08 lea edx,[esp+8]
* 0x7c90e524 cd 2e int 2Eh
* XXX: I'd like to use d_r_safe_read() but that's not set up yet.
*/
if (*((ushort *)(int_target + 1)) == 0xd2ff) {
vsys = VSYSCALL_BOOTSTRAP_ADDR;
} else {
vsys = *(app_pc *)VSYSCALL_BOOTSTRAP_ADDR;
}
if (*((ushort *)(vsys + 2)) == 0x340f) {
sysenter_ret_address = (app_pc)int_target + 3; /* save addr of ret */
# ifdef CLIENT_INTERFACE
/* i#537: we do not support XPSP{0,1} wrt showing the skipped ret,
* which requires looking at the vsyscall code.
*/
KiFastSystemCallRet_address =
(app_pc)d_r_get_proc_address(ntdllh, "KiFastSystemCallRet");
# endif
set_syscall_method(SYSCALL_METHOD_SYSENTER);
dr_which_syscall_t = DR_SYSCALL_SYSENTER;
} else {
dr_which_syscall_t = DR_SYSCALL_INT2E;
set_syscall_method(SYSCALL_METHOD_INT);
int_syscall_address = int_target;
ASSERT(*(byte *)(vsys + 6) == 0xc3 /* ret 0 */);
}
} else if (check == 0xc300 || check == 0xc200) {
/* win8: call followed by ret */
IF_X64(ASSERT_NOT_IMPLEMENTED(false));
/* kernel returns control to KiFastSystemCallRet, not local sysenter, of course */
sysenter_ret_address =
(app_pc)d_r_get_proc_address(ntdllh, "KiFastSystemCallRet");
ASSERT(sysenter_ret_address != NULL);
# ifdef CLIENT_INTERFACE
KiFastSystemCallRet_address =
(app_pc)d_r_get_proc_address(ntdllh, "KiFastSystemCallRet");
# endif
set_syscall_method(SYSCALL_METHOD_SYSENTER);
dr_which_syscall_t = DR_SYSCALL_SYSENTER;
} else {
/* win10 wow64 */
app_pc tgt;
ASSERT(*(ushort *)(pc + 10) == 0xd2ff);
ASSERT(is_wow64_process(NT_CURRENT_PROCESS));
tgt = *(app_pc *)(pc + 6);
dr_which_syscall_t = DR_SYSCALL_WOW64;
set_syscall_method(SYSCALL_METHOD_WOW64);
wow64_syscall_call_tgt = tgt;
}
/* Prime use_ki_syscall_routines() */
use_ki_syscall_routines();
if (syscalls == windows_unknown_syscalls) {
/* i#1598: try to work on new, unsupported Windows versions */
int i;
app_pc wrapper;
ASSERT(ntdllh != NULL);
for (i = 0; i < SYS_MAX; i++) {
if (syscalls[i] == SYSCALL_NOT_PRESENT) /* presumably matches known ver */
continue;
wrapper = (app_pc)d_r_get_proc_address(ntdllh, syscall_names[i]);
if (wrapper != NULL && !ALLOW_HOOKER(wrapper))
syscalls[i] = *((int *)((wrapper) + SYSNUM_OFFS));
/* We ignore TestAlert complications: we don't call it anyway */
}
}
/* quick sanity check that the syscall numbers we care about are what's
* in our static array. we still do our later full-decode sanity checks.
*/
DOCHECK(1, {
int i;
ASSERT(ntdllh != NULL);
for (i = 0; i < SYS_MAX; i++) {
if (syscalls[i] == SYSCALL_NOT_PRESENT)
continue;
/* note that this check allows a hooker so we'll need a
* better way of determining syscall numbers
*/
CHECK_SYSNUM_AT((byte *)d_r_get_proc_address(ntdllh, syscall_names[i]), i);
}
});
return true;
}
/* Returns true if machine is using the Ki*SysCall routines (indirection via vsyscall
* page), false otherwise.
*
* XXX: on win8, KiFastSystemCallRet is used, but KiFastSystemCall is never
* executed even though it exists. This routine returns true there (we have not
* yet set up the versions so can't just call get_os_version()).
*/
bool
use_ki_syscall_routines()
{
/* FIXME - two ways to do this. We could use the byte matching above in
* syscalls_init to match call edx vs call [edx] or we could check for the
* existence of the Ki*SystemCall* routines. We do the latter and have
* syscalls_init assert that the two methods agree. */
/* We use KiFastSystemCall, but KiIntSystemCall and KiFastSystemCallRet would
* work just as well. */
static generic_func_t ki_fastsyscall_addr = (generic_func_t)PTR_UINT_MINUS_1;
if (ki_fastsyscall_addr == (generic_func_t)PTR_UINT_MINUS_1) {
ki_fastsyscall_addr = d_r_get_proc_address(get_ntdll_base(), "KiFastSystemCall");
ASSERT(ki_fastsyscall_addr != (generic_func_t)PTR_UINT_MINUS_1);
}
return (ki_fastsyscall_addr != NULL);
}
static void
nt_get_context_extended_functions(app_pc base)
{
if (YMM_ENABLED()) { /* indicates OS support, not just processor support */
ntdll_RtlGetExtendedContextLength =
(ntdll_RtlGetExtendedContextLength_t)d_r_get_proc_address(
base, "RtlGetExtendedContextLength");
ntdll_RtlInitializeExtendedContext =
(ntdll_RtlInitializeExtendedContext_t)d_r_get_proc_address(
base, "RtlInitializeExtendedContext");
ntdll_RtlLocateLegacyContext =
(ntdll_RtlLocateLegacyContext_t)d_r_get_proc_address(
base, "RtlLocateLegacyContext");
ASSERT(ntdll_RtlGetExtendedContextLength != NULL &&
ntdll_RtlInitializeExtendedContext != NULL &&
ntdll_RtlLocateLegacyContext != NULL);
}
}
static void
nt_init_dynamic_syscall_wrappers(app_pc base)
{
NtGetNextThread = (NtGetNextThread_t)d_r_get_proc_address(base, "NtGetNextThread");
}
#endif /* !NOT_DYNAMORIO_CORE_PROPER */
void
ntdll_init()
{
/* FIXME: decode kernel32!TlsGetValue and get the real offset
* from there?
*/
ASSERT(offsetof(TEB, TlsSlots) == TEB_TLS64_OFFSET);
#if !defined(NOT_DYNAMORIO_CORE_PROPER) && !defined(NOT_DYNAMORIO_CORE)
nt_init_dynamic_syscall_wrappers((app_pc)get_ntdll_base());
nt_get_context_extended_functions((app_pc)get_ntdll_base());
#endif
}
/* note that this function is called even on the release fast exit path
* (via os_exit) and thus should only do necessary cleanup without ifdef
* DEBUG, but also be carefull about ifdef DEBUG since Detach wants to remove
* as much of us as possible
*/
void
ntdll_exit(void)
{
#if !defined(NOT_DYNAMORIO_CORE_PROPER) && !defined(NOT_DYNAMORIO_CORE)
tls_exit();
set_ntdll_base(NULL);
if (doing_detach) {
own_peb = NULL;
sysenter_tls_offset = 0xffffffff;
nt_wrappers_intercepted = true;
}
#endif
}
/* export this if needed elsewhere */
static NTSTATUS
query_thread_info(HANDLE h, THREAD_BASIC_INFORMATION *info)
{
NTSTATUS res;
ULONG got;
memset(info, 0, sizeof(THREAD_BASIC_INFORMATION));
res = NT_SYSCALL(QueryInformationThread, h, ThreadBasicInformation, info,
sizeof(THREAD_BASIC_INFORMATION), &got);
ASSERT(!NT_SUCCESS(res) || got == sizeof(THREAD_BASIC_INFORMATION));
return res;
}
/* Get a segment descriptor. This code assumes the selector is set
* appropriately in entry->Selector */
NTSTATUS
query_seg_descriptor(HANDLE hthread, DESCRIPTOR_TABLE_ENTRY *entry)
{
NTSTATUS res;
ULONG got;
res = NT_SYSCALL(QueryInformationThread, hthread, ThreadDescriptorTableEntry, entry,
sizeof(DESCRIPTOR_TABLE_ENTRY), &got);
/* This call only writes the LDT_ENTRY portion of the table entry */
ASSERT(!NT_SUCCESS(res) || got == sizeof(LDT_ENTRY));
return res;
}
/* Get a win32 start address. NOTE: According to Nebbet, the value
* retrieved with ThreadQuerySetWin32StartAddress is invalid if the
* thread has call ZwReplyWaitReplyPort or ZwReplyWaitReceivePort.
*/
NTSTATUS
query_win32_start_addr(HANDLE hthread, PVOID start_addr)
{
NTSTATUS res;
ULONG got;
res = NT_SYSCALL(QueryInformationThread, hthread, ThreadQuerySetWin32StartAddress,
start_addr, sizeof(app_pc), &got);
ASSERT(!NT_SUCCESS(res) || got == sizeof(PVOID));
return res;
}
/* Collects system information available through the NtQuerySystemInformation
* system call.
*/
NTSTATUS
query_system_info(IN SYSTEM_INFORMATION_CLASS info_class, IN int info_size,
OUT PVOID info)
{
NTSTATUS result;
ULONG bytes_received = 0;
GET_NTDLL(NtQuerySystemInformation,
(IN SYSTEM_INFORMATION_CLASS info_class, OUT PVOID info, IN ULONG info_size,
OUT PULONG bytes_received));
result = NtQuerySystemInformation(info_class, info, info_size, &bytes_received);
return result;
}
/* since not exporting get_own_teb() */
#ifndef NOT_DYNAMORIO_CORE
thread_id_t
d_r_get_thread_id()
{
return (thread_id_t)get_own_teb()->ClientId.UniqueThread;
}
process_id_t
get_process_id()
{
return (process_id_t)get_own_teb()->ClientId.UniqueProcess;
}
int
get_last_error()
{
return get_own_teb()->LastErrorValue;
}
void
set_last_error(int error)
{
get_own_teb()->LastErrorValue = error;
}
#endif /* !NOT_DYNAMORIO_CORE */
HANDLE
get_stderr_handle()
{
HANDLE herr = get_own_peb()->ProcessParameters->StdErrorHandle;
if (herr == NULL)
return INVALID_HANDLE_VALUE;
return herr;
}
HANDLE
get_stdout_handle()
{
HANDLE hout = get_own_peb()->ProcessParameters->StdOutputHandle;
if (hout == NULL)
return INVALID_HANDLE_VALUE;
return hout;
}
HANDLE
get_stdin_handle()
{
HANDLE hin = get_own_peb()->ProcessParameters->StdInputHandle;
if (hin == NULL)
return INVALID_HANDLE_VALUE;
return hin;
}
thread_exited_status_t
is_thread_exited(HANDLE hthread)
{
LARGE_INTEGER timeout;
wait_status_t result;
/* Keep the timeout small, just want to check if signaled. Don't want to wait at all
* really, but no way to specify that. Note negative => relative time offset (so is
* a 1 millisecond timeout). */
timeout.QuadPart = -((int)1 * TIMER_UNITS_PER_MILLISECOND);
if (thread_id_from_handle(hthread) == (thread_id_t)PTR_UINT_MINUS_1) {
/* not a thread handle */
ASSERT(false && "Not a valid thread handle.");
return THREAD_EXIT_ERROR;
}
if (!TEST(SYNCHRONIZE, nt_get_handle_access_rights(hthread))) {
/* Note that our own thread handles will have SYNCHRONIZE since, like
* THREAD_TERMINATE, that seems to be a right the thread can always get for
* itself (prob. due to how stacks are freed). So only a potential issue with
* app handles for which we try to dup with the required rights. xref 9529 */
HANDLE ht = INVALID_HANDLE_VALUE;
NTSTATUS res = duplicate_handle(NT_CURRENT_PROCESS, hthread, NT_CURRENT_PROCESS,
&ht, SYNCHRONIZE, 0, 0);
if (!NT_SUCCESS(res)) {
ASSERT_CURIOSITY(false && "Unable to check if thread has exited.");
return THREAD_EXIT_ERROR;
}
result = nt_wait_event_with_timeout(ht, &timeout);
close_handle(ht);
} else {
result = nt_wait_event_with_timeout(hthread, &timeout);
}
if (result == WAIT_SIGNALED)
return THREAD_EXITED;
if (result == WAIT_TIMEDOUT)
return THREAD_NOT_EXITED;
ASSERT(result == WAIT_ERROR);
ASSERT_CURIOSITY(false && "is_thread_exited() unknown error");
return THREAD_EXIT_ERROR;
}
/* The other ways to get thread info, like OpenThread and Toolhelp, don't
* let you go from handle to id (remember handles can be duplicated and
* there's no way to tell equivalence), plus are only on win2k.
* Returns POINTER_MAX on failure
*/
thread_id_t
thread_id_from_handle(HANDLE h)
{
THREAD_BASIC_INFORMATION info;
NTSTATUS res = query_thread_info(h, &info);
if (!NT_SUCCESS(res))
return POINTER_MAX;
else
return (thread_id_t)info.ClientId.UniqueThread;
}
/* export this if needed elsewhere */
static NTSTATUS
query_process_info(HANDLE h, PROCESS_BASIC_INFORMATION *info)
{
NTSTATUS res;
ULONG got;
memset(info, 0, sizeof(PROCESS_BASIC_INFORMATION));
res = NtQueryInformationProcess(h, ProcessBasicInformation, info,
sizeof(PROCESS_BASIC_INFORMATION), &got);
ASSERT(!NT_SUCCESS(res) || got == sizeof(PROCESS_BASIC_INFORMATION));
return res;
}
/* Returns POINTER_MAX on failure */
process_id_t
process_id_from_handle(HANDLE h)
{
PROCESS_BASIC_INFORMATION info;
NTSTATUS res = query_process_info(h, &info);
if (!NT_SUCCESS(res))
return POINTER_MAX;
else
return (process_id_t)info.UniqueProcessId;
}
/* Returns POINTER_MAX on failure */
process_id_t
process_id_from_thread_handle(HANDLE h)
{
THREAD_BASIC_INFORMATION info;
NTSTATUS res = query_thread_info(h, &info);
if (!NT_SUCCESS(res))
return POINTER_MAX;
else
return (process_id_t)info.ClientId.UniqueProcess;
}
HANDLE
process_handle_from_id(process_id_t pid)
{
NTSTATUS res;
HANDLE h;
OBJECT_ATTRIBUTES oa;
CLIENT_ID cid;
InitializeObjectAttributes(&oa, NULL, OBJ_CASE_INSENSITIVE, NULL, NULL);
memset(&cid, 0, sizeof(cid));
cid.UniqueProcess = (HANDLE)pid;
res = nt_raw_OpenProcess(&h, PROCESS_ALL_ACCESS, &oa, &cid);
if (!NT_SUCCESS(res)) {
NTPRINT("nt_open_process failed: %x\n", res);
}
if (!NT_SUCCESS(res))
return INVALID_HANDLE_VALUE;
else
return h;
}
#if !defined(NOT_DYNAMORIO_CORE_PROPER) && !defined(NOT_DYNAMORIO_CORE)
HANDLE
thread_handle_from_id(thread_id_t tid)
{
NTSTATUS res;
HANDLE h;
OBJECT_ATTRIBUTES oa;
CLIENT_ID cid;
InitializeObjectAttributes(&oa, NULL, OBJ_CASE_INSENSITIVE, NULL, NULL);
memset(&cid, 0, sizeof(cid));
cid.UniqueThread = (HANDLE)tid;
res = nt_raw_OpenThread(&h, THREAD_ALL_ACCESS, &oa, &cid);
if (!NT_SUCCESS(res)) {
NTPRINT("nt_open_thread failed: %x\n", res);
}
if (!NT_SUCCESS(res))
return INVALID_HANDLE_VALUE;
else
return h;
}
#endif
/* PEB:
* for a running thread this is stored at fs:[30h]
* it's always at 0x7FFDF000 according to InsideWin2k p.290
* but that's out of date, is randomized within 0x7ffd... on XPsp2
* so use query_process_info to get it
*/
PEB *
get_peb(HANDLE h)
{
PROCESS_BASIC_INFORMATION info;
NTSTATUS res = query_process_info(h, &info);
if (!NT_SUCCESS(res))
return NULL;
else
return info.PebBaseAddress;
}
PEB *
get_own_peb()
{
/* alt. we could use get_own_teb->PEBptr, but since we're remembering the
* results of the first lookup doesn't really gain us much */
if (own_peb == NULL) {
own_peb = get_peb(NT_CURRENT_PROCESS);
ASSERT(own_peb != NULL);
}
return own_peb;
}
/****************************************************************************/
#ifndef NOT_DYNAMORIO_CORE
/* avoid needing CXT_ macros and SELF_TIB_OFFSET from os_exports.h */
TEB *
get_teb(HANDLE h)
{
THREAD_BASIC_INFORMATION info;
NTSTATUS res = query_thread_info(h, &info);
if (!NT_SUCCESS(res))
return NULL;
else
return (TEB *)info.TebBaseAddress;
}
static app_pc ntdll_base;
void *
get_ntdll_base(void)
{
if (ntdll_base == NULL) {
# ifndef NOT_DYNAMORIO_CORE_PROPER
ASSERT(!dr_earliest_injected); /* Ldr not initialized yet */
# endif
ntdll_base = (app_pc)get_module_handle(L"ntdll.dll");
ASSERT(ntdll_base != NULL);
}
return ntdll_base;
}
# if !defined(NOT_DYNAMORIO_CORE_PROPER) && !defined(NOT_DYNAMORIO_CORE)
/* for early injection we can't use get_module_handle() to find it */
void
set_ntdll_base(app_pc base)
{
if (ntdll_base == NULL)
ntdll_base = base;
}
/* get_allocation_size() in os.c */
bool
is_in_ntdll(app_pc pc)
{
static app_pc ntdll_end;
app_pc base = get_ntdll_base();
if (ntdll_end == NULL) {
ntdll_end = base + get_allocation_size(base, NULL);
ASSERT(ntdll_end > base);
}
return (pc >= base && pc < ntdll_end);
}
static bool
context_check_extended_sizes(context_ex_t *cxt_ex, uint flags)
{
return (cxt_ex->all.offset == -(LONG)sizeof(CONTEXT) &&
cxt_ex->legacy.offset == -(LONG)sizeof(CONTEXT) &&
(cxt_ex->legacy.length ==
(DWORD)sizeof(CONTEXT)
/* We won't allocate space for ExtendedRegisters if not saving xmm */
IF_NOT_X64(||
(!TESTALL(CONTEXT_XMM_FLAG, flags) &&
cxt_ex->legacy.length ==
(DWORD)offsetof(CONTEXT, ExtendedRegisters)))));
}
/* get the ymm saved area from CONTEXT extended area
* returns NULL if the extended area is not initialized.
*/
byte *
context_ymmh_saved_area(CONTEXT *cxt)
{
/* i#437: ymm are inside XSTATE construct which should be
* laid out like this: {CONTEXT, CONTEXT_EX, XSTATE}.
* The gap between CONTEXT_EX and XSTATE varies due to
* alignment, should read CONTEXT_EX fields to get it.
*/
ptr_uint_t p = (ptr_uint_t)cxt;
context_ex_t our_cxt_ex;
context_ex_t *cxt_ex = (context_ex_t *)(p + sizeof(*cxt));
ASSERT(proc_avx_enabled());
/* verify the dr_cxt_ex is correct */
if (d_r_safe_read(cxt_ex, sizeof(*cxt_ex), &our_cxt_ex)) {
if (!context_check_extended_sizes(&our_cxt_ex, cxt->ContextFlags)) {
ASSERT_CURIOSITY(false && "CONTEXT_EX is not setup correctly");
return NULL;
}
} else {
ASSERT_CURIOSITY(false && "fail to read CONTEXT_EX");
}
/* XXX: XSTATE has xsave format minus first 512 bytes, so ymm0
* should be at offset 64.
* Should we use kernel32!LocateXStateFeature() or
* ntdll!RtlLocateExtendedFeature() to locate,
* or cpuid to find Ext_Save_Area_2?
* Currently, use hardcode XSTATE_HEADER_SIZE.
* mcontext_to_context() also uses this to get back to the header.
*/
p = p + sizeof(*cxt) + cxt_ex->xstate.offset + XSTATE_HEADER_SIZE;
return (byte *)p;
}
/* routines for conversion between CONTEXT and priv_mcontext_t */
/* assumes our segment registers are the same as the app and that
* we never touch floating-point state and debug registers.
* Note that this code will not compile for non-core (no proc_has_feature())
* but is not currently used there.
*/
/* all we need is CONTEXT_INTEGER and non-segment CONTEXT_CONTROL,
* and for PR 264138 we need the XMM registers
*/
static void
context_to_mcontext_internal(priv_mcontext_t *mcontext, CONTEXT *cxt)
{
ASSERT(TESTALL(CONTEXT_INTEGER | CONTEXT_CONTROL, cxt->ContextFlags));
/* CONTEXT_INTEGER */
mcontext->xax = cxt->CXT_XAX;
mcontext->xbx = cxt->CXT_XBX;
mcontext->xcx = cxt->CXT_XCX;
mcontext->xdx = cxt->CXT_XDX;
mcontext->xsi = cxt->CXT_XSI;
mcontext->xdi = cxt->CXT_XDI;
# ifdef X64
mcontext->r8 = cxt->R8;
mcontext->r9 = cxt->R9;
mcontext->r10 = cxt->R10;
mcontext->r11 = cxt->R11;
mcontext->r12 = cxt->R12;
mcontext->r13 = cxt->R13;
mcontext->r14 = cxt->R14;
mcontext->r15 = cxt->R15;
# endif
/* XXX i#1312: This will need attention for AVX-512, specifically the different
* xstate formats supported by the processor, compacted and standard, as well as
* MPX.
*/
if (CONTEXT_PRESERVE_XMM && TESTALL(CONTEXT_XMM_FLAG, cxt->ContextFlags)) {
/* no harm done if no sse support */
/* CONTEXT_FLOATING_POINT or CONTEXT_EXTENDED_REGISTERS */
int i;
for (i = 0; i < proc_num_simd_sse_avx_registers(); i++)
memcpy(&mcontext->simd[i], CXT_XMM(cxt, i), XMM_REG_SIZE);
}
/* if XSTATE is NOT set, the app has NOT used any ymm state and
* thus it's fine if we do not copy dr_mcontext_t ymm value.
*/
if (CONTEXT_PRESERVE_YMM && TESTALL(CONTEXT_XSTATE, cxt->ContextFlags)) {
byte *ymmh_area = context_ymmh_saved_area(cxt);
if (ymmh_area != NULL) {
int i;
for (i = 0; i < proc_num_simd_sse_avx_registers(); i++) {
memcpy(&mcontext->simd[i].u32[4], &YMMH_AREA(ymmh_area, i).u32[0],
YMMH_REG_SIZE);
}
}
}
/* XXX i#1312: AVX-512 extended register copies missing yet. */
/* CONTEXT_CONTROL without the segments */
mcontext->xbp = cxt->CXT_XBP;
mcontext->xsp = cxt->CXT_XSP;
mcontext->xflags = cxt->CXT_XFLAGS;
mcontext->pc = (app_pc)cxt->CXT_XIP; /* including XIP */
}
void
context_to_mcontext(priv_mcontext_t *mcontext, CONTEXT *cxt)
{
/* i#437: cxt might come from kernel where XSTATE is not set */
/* FIXME: This opens us up to a bug in DR where DR requests a CONTEXT but
* forgets to set XSTATE even though app has used it and we then mess up
* the app's ymm state. Any way we can detect that?
* One way is to pass a flag to indicate if the context is from kernel or
* set by DR, but it requires update a chain of calls.
*/
ASSERT(TESTALL(CONTEXT_DR_STATE_NO_YMM, cxt->ContextFlags));
context_to_mcontext_internal(mcontext, cxt);
}
void
context_to_mcontext_new_thread(priv_mcontext_t *mcontext, CONTEXT *cxt)
{
/* i#1714: new threads on win10 don't have CONTEXT_EXTENDED_REGISTERS,
* which is not a big deal as it doesn't matter if DR clobbers xmm/fp state.
*/
ASSERT(TESTALL(CONTEXT_INTEGER | CONTEXT_CONTROL, cxt->ContextFlags));
context_to_mcontext_internal(mcontext, cxt);
}
/* If set_cur_seg is true, cs and ss (part of CONTEXT_CONTROL) are set to
* the current values.
* If mcontext_to_context is used to set another thread's context,
* the caller must initialize the cs/ss value properly and set
* set_cur_seg to false
*/
void
mcontext_to_context(CONTEXT *cxt, priv_mcontext_t *mcontext, bool set_cur_seg)
{
/* xref comment in context_to_mcontext */
ASSERT(TESTALL(CONTEXT_DR_STATE_NO_YMM, cxt->ContextFlags));
if (set_cur_seg) {
/* i#1033: initialize CONTEXT_CONTROL segments for current thread */
get_segments_cs_ss(&cxt->SegCs, &cxt->SegSs);
}
/* CONTEXT_INTEGER */
cxt->CXT_XAX = mcontext->xax;
cxt->CXT_XBX = mcontext->xbx;
cxt->CXT_XCX = mcontext->xcx;
cxt->CXT_XDX = mcontext->xdx;
cxt->CXT_XSI = mcontext->xsi;
cxt->CXT_XDI = mcontext->xdi;
# ifdef X64
cxt->R8 = mcontext->r8;
cxt->R9 = mcontext->r9;
cxt->R10 = mcontext->r10;
cxt->R11 = mcontext->r11;
cxt->R12 = mcontext->r12;
cxt->R13 = mcontext->r13;
cxt->R14 = mcontext->r14;
cxt->R15 = mcontext->r15;
# endif
if (CONTEXT_PRESERVE_XMM && TESTALL(CONTEXT_XMM_FLAG, cxt->ContextFlags)) {
/* no harm done if no sse support */
/* CONTEXT_FLOATING_POINT or CONTEXT_EXTENDED_REGISTERS */
int i;
/* We can't set just xmm and not the rest of the fp state
* so we fill in w/ the current (unchanged by DR) values
* (i#462, i#457)
*/
byte fpstate_buf[MAX_FP_STATE_SIZE];
byte *fpstate = (byte *)ALIGN_FORWARD(fpstate_buf, 16);
size_t written = proc_save_fpstate(fpstate);
# ifdef X64
ASSERT(sizeof(cxt->FltSave) == written);
memcpy(&cxt->FltSave, fpstate, written);
/* We also have to set the x64-only duplicate top-level MxCsr field (i#1081) */
cxt->MxCsr = cxt->FltSave.MxCsr;
# else
ASSERT(MAXIMUM_SUPPORTED_EXTENSION == written);
memcpy(&cxt->ExtendedRegisters, fpstate, written);
# endif
/* Now update w/ the xmm values from mcontext */
for (i = 0; i < proc_num_simd_sse_avx_registers(); i++)
memcpy(CXT_XMM(cxt, i), &mcontext->simd[i], XMM_REG_SIZE);
}
/* XXX i#1312: This may need attention for AVX-512, specifically the different
* xstate formats supported by the kernel, compacted and standard, as well as
* MPX.
*/
if (CONTEXT_PRESERVE_YMM && TESTALL(CONTEXT_XSTATE, cxt->ContextFlags)) {
byte *ymmh_area = context_ymmh_saved_area(cxt);
if (ymmh_area != NULL) {
uint64 *header_bv = (uint64 *)(ymmh_area - XSTATE_HEADER_SIZE);
uint bv_high, bv_low;
int i;
# ifndef X64
/* In 32-bit Windows mcontext, we do not preserve xmm/ymm 6 and 7,
* which are callee saved registers, so we must fill them.
*/
dr_ymm_t ymms[2];
dr_ymm_t *ymm_ptr = ymms;
__asm { mov ecx, ymm_ptr }
/* Some supported (old) compilers do not support/understand AVX
* instructions, so we use RAW bit here instead.
*/
# define HEX(n) 0##n##h
# define RAW(n) __asm _emit 0x##n
/* c5 fc 11 71 00 vmovups %ymm6 -> 0x00(%XCX)
* c5 fc 11 79 20 vmovups %ymm7 -> 0x20(%XCX)
*/
RAW(c5) RAW(fc) RAW(11) RAW(71) RAW(00);
RAW(c5) RAW(fc) RAW(11) RAW(79) RAW(20);
/* XMM6/7 has been copied above, so only copy ymmh here */
memcpy(&YMMH_AREA(ymmh_area, 6).u32[0], &ymms[0].u32[4], YMMH_REG_SIZE);
memcpy(&YMMH_AREA(ymmh_area, 7).u32[0], &ymms[1].u32[4], YMMH_REG_SIZE);
# endif
for (i = 0; i < proc_num_simd_sse_avx_registers(); i++) {
memcpy(&YMMH_AREA(ymmh_area, i).u32[0], &mcontext->simd[i].u32[4],
YMMH_REG_SIZE);
}
/* XXX i#1312: AVX-512 extended register copies missing yet. */
/* The only un-reserved part of the AVX header saved by OP_xsave is
* the XSTATE_BV byte.
*/
dr_xgetbv(&bv_high, &bv_low);
*header_bv = (((uint64)bv_high) << 32) | bv_low;
}
}
/* XXX i#1312: AVX-512 extended register copies missing yet. */
/* CONTEXT_CONTROL without the segments */
cxt->CXT_XBP = mcontext->xbp;
cxt->CXT_XSP = mcontext->xsp;
IF_X64(ASSERT_TRUNCATE(cxt->CXT_XFLAGS, uint, mcontext->xflags));
cxt->CXT_XFLAGS = (uint)mcontext->xflags;
cxt->CXT_XIP = (ptr_uint_t)mcontext->pc; /* including XIP */
}
# endif /* core proper */
#endif /* !NOT_DYNAMORIO_CORE */
/****************************************************************************/
/****************************************************************************/
#if !defined(NOT_DYNAMORIO_CORE_PROPER) && !defined(NOT_DYNAMORIO_CORE)
/* avoid needing x86_code.c from x86.asm from get_own_context_helper(),
/* unstatic for use by GET_OWN_CONTEXT macro */
void
get_own_context_integer_control(CONTEXT *cxt, reg_t cs, reg_t ss, priv_mcontext_t *mc)
{
/* We could change the parameter types to cxt_seg_t, but the args
* passed by get_own_context_helper() in x86.asm are best simply
* widened in passing
*/
DEBUG_DECLARE(uint origflags = cxt->ContextFlags;)
IF_X64(ASSERT_TRUNCATE(cxt->SegCs, short, cs));
cxt->SegCs = (WORD)cs; /* FIXME : need to sanitize? */
IF_X64(ASSERT_TRUNCATE(cxt->SegSs, short, ss));
cxt->SegSs = (WORD)ss;
/* avoid assert in mcontext_to_context about not having xmm flags.
* get rid of this once we implement PR 266070. */
DODEBUG({ cxt->ContextFlags = CONTEXT_DR_STATE_NO_YMM; });
mcontext_to_context(cxt, mc, false /* !set_cur_seg */);
DODEBUG({ cxt->ContextFlags = origflags; });
}
/* don't call this directly, use GET_OWN_CONTEXT macro instead (it fills
* in CONTEXT_INTEGER and CONTEXT_CONTROL values) */
void
get_own_context(CONTEXT *cxt)
{
if (TEST(CONTEXT_SEGMENTS, cxt->ContextFlags)) {
get_segments_defg(&cxt->SegDs, &cxt->SegEs, &cxt->SegFs, &cxt->SegGs);
}
/* FIXME : do we want CONTEXT_DEBUG_REGISTERS or CONTEXT_FLOATING_POINT
* or CONTEXT_EXTENDED_REGISTERS at some point?
* Especially in light of PR 264138. However, no current uses need
* to get our own xmm registers.
*/
ASSERT_NOT_IMPLEMENTED(
(cxt->ContextFlags & ~(CONTEXT_SEGMENTS | CONTEXT_INTEGER | CONTEXT_CONTROL)) ==
0);
}
/***************************************************************************
* TLS
*/
/* Lock that protects the tls_*_taken arrays */
DECLARE_CXTSWPROT_VAR(static mutex_t alt_tls_lock, INIT_LOCK_FREE(alt_tls_lock));
# define TLS_SPAREBYTES_SLOTS \
((offsetof(TEB, TxFsContext) - offsetof(TEB, SpareBytes1)) / sizeof(void *))
static bool alt_tls_spare_taken[TLS_SPAREBYTES_SLOTS];
# ifdef X64
# define TLS_POSTTEB_SLOTS 64
static bool alt_tls_post_taken[TLS_POSTTEB_SLOTS];
/* Use the slots at the end of the 2nd page */
# define TLS_POSTTEB_BASE_OFFS \
((uint)PAGE_SIZE * 2 - TLS_POSTTEB_SLOTS * sizeof(void *))
# endif
static void
tls_exit(void)
{
# ifdef DEBUG
DELETE_LOCK(alt_tls_lock);
# endif
}
/* Caller must synchronize */
static bool
alt_tls_acquire_helper(bool *taken, size_t taken_sz, size_t base_offs,
uint *teb_offs /* OUT */, int num_slots, uint alignment)
{
bool res = false;
uint i, start = 0;
int slots_found = 0;
for (i = 0; i < taken_sz; i++) {
size_t offs = base_offs + i * sizeof(void *);
if (slots_found == 0 && !taken[i] &&
(alignment == 0 || ALIGNED(offs, alignment))) {
start = i;
slots_found++;
} else if (slots_found > 0) {
if (!taken[i])
slots_found++;
else
slots_found = 0; /* start over */
}
if (slots_found >= num_slots)
break;
}
if (slots_found >= num_slots) {
ASSERT_TRUNCATE(uint, uint, base_offs + start * sizeof(void *));
*teb_offs = (uint)(base_offs + start * sizeof(void *));
for (i = start; i < start + num_slots; i++) {
ASSERT(!taken[i]);
taken[i] = true;
DOCHECK(1, {
/* Try to check for anyone else using these slots. The TEB pages
* are zeroed before use. This is only a curiosity, as we don't
* zero on a release and thus a release-and-re-alloc can hit this.
*/
TEB *teb = get_own_teb();
ASSERT_CURIOSITY(is_region_memset_to_char((byte *)teb + *teb_offs,
num_slots * sizeof(void *), 0));
});
}
res = true;
}
return res;
}
static bool
alt_tls_acquire(uint *teb_offs /* OUT */, int num_slots, uint alignment)
{
bool res = false;
ASSERT(DYNAMO_OPTION(alt_teb_tls));
/* Strategy: first, use TEB->SpareBytes1. The only known user of that field
* is WINE, although Vista stole some of the space there for the TxFsContext
* slot, and maybe now that Win8 has just about used up the TEB single page
* for 32-bit future versions will take more?
*
* Second, on 64-bit, use space beyond the TEB on the 2nd TEB page.
*/
d_r_mutex_lock(&alt_tls_lock);
res = alt_tls_acquire_helper(alt_tls_spare_taken, TLS_SPAREBYTES_SLOTS,
offsetof(TEB, SpareBytes1), teb_offs, num_slots,
alignment);
# ifdef X64
if (!res) {
ASSERT_NOT_TESTED();
ASSERT(TLS_POSTTEB_BASE_OFFS > sizeof(TEB));
res =
alt_tls_acquire_helper(alt_tls_post_taken, TLS_POSTTEB_SLOTS,
TLS_POSTTEB_BASE_OFFS, teb_offs, num_slots, alignment);
}
# endif
d_r_mutex_unlock(&alt_tls_lock);
return res;
}
/* Caller must synchronize */
static bool
alt_tls_release_helper(bool *taken, uint base_offs, uint teb_offs, int num_slots)
{
uint i;
uint start = (teb_offs - base_offs) / sizeof(void *);
for (i = start; i < start + num_slots; i++) {
ASSERT(taken[i]);
taken[i] = false;
/* XXX: I'd like to zero the slots out for all threads but there's
* no simple way to do that
*/
}
return true;
}
static bool
alt_tls_release(uint teb_offs, int num_slots)
{
bool res = false;
size_t base_offs = offsetof(TEB, SpareBytes1);
ASSERT(DYNAMO_OPTION(alt_teb_tls));
if (teb_offs >= base_offs &&
teb_offs < base_offs + TLS_SPAREBYTES_SLOTS * sizeof(void *)) {
d_r_mutex_lock(&alt_tls_lock);
res = alt_tls_release_helper(alt_tls_spare_taken, (uint)base_offs, teb_offs,
num_slots);
d_r_mutex_unlock(&alt_tls_lock);
}
# ifdef X64
if (!res) {
if (teb_offs >= TLS_POSTTEB_BASE_OFFS &&
teb_offs < TLS_POSTTEB_BASE_OFFS + TLS_POSTTEB_SLOTS * sizeof(void *)) {
d_r_mutex_lock(&alt_tls_lock);
res = alt_tls_release_helper(alt_tls_post_taken, TLS_POSTTEB_BASE_OFFS,
teb_offs, num_slots);
d_r_mutex_unlock(&alt_tls_lock);
}
}
# endif
return res;
}
static inline uint
tls_segment_offs(int slot)
{
return (uint)(offsetof(TEB, TlsSlots) + slot * sizeof(uint *));
}
/* returns the first block sequence of num_slots found either bottom
* up or top_down, that has the selected slot aligned to given alignment.
* Returns -1 on failure to find properly aligned sequence.
*
* Note that if we only want the whole sequence to fit in a cache line, callers
* should try either align_which_slot for either first or last.
*/
int
bitmap_find_free_sequence(byte *rtl_bitmap, int bitmap_size, int num_requested_slots,
bool top_down, int align_which_slot, /* 0 based index */
uint alignment)
{
/* note: bitmap_find_set_block_sequence() works similarly on our
* internal bitmap_t which starts initialized to 0
*/
uint *p = (uint *)rtl_bitmap; /* we access in 32-bit words */
int start, open_end;
int step; /* +/- 1 */
int i;
int contig = 0;
int result;
ASSERT(ALIGNED(rtl_bitmap, sizeof(uint))); /* they promised */
ASSERT_CURIOSITY(bitmap_size == 64 /*TLS*/ || bitmap_size == 128 /*FLS*/);
ASSERT(num_requested_slots < bitmap_size);
ASSERT_CURIOSITY(alignment < 256);
ASSERT(align_which_slot >= 0 && /* including after last */
align_which_slot <= num_requested_slots);
if (top_down) {
start = bitmap_size - 1;
open_end = -1; /* 0 included */
step = -1;
} else {
start = 0;
open_end = bitmap_size;
step = +1;
}
for (i = start; i != open_end; i += step) {
uint taken = p[i / 32] & (1 << (i % 32));
NTPRINT("tls slot %d is %d\n", i, taken);
if (!taken) {
if (contig == 0) {
/* check whether first element will be aligned */
/* don't bother starting if not */
/* FIXME: could add an argument which slot should be aligned here */
int proposed_align_slot = /* first */
(top_down ? i - (num_requested_slots - 1) : i) + align_which_slot;
/* ALIGNED doesn't work for 0 so we have to special-case it */
bool aligned =
(alignment == 0 ||
ALIGNED(tls_segment_offs(proposed_align_slot), alignment));
NTPRINT("\t => @ " PFX ", pivot " PFX " %saligned to 0x%x\n",
tls_segment_offs(i), tls_segment_offs(proposed_align_slot),
aligned ? "" : "not ", alignment);
if (aligned)
contig++;
else
contig = 0; /* try at next */
} else
contig++;
NTPRINT("\t => %d contig @ " PFX "\n", contig, tls_segment_offs(i));
ASSERT(contig <= num_requested_slots);
if (contig == num_requested_slots)
break;
} else {
contig = 0; /* start over! */
}
}
if (contig < num_requested_slots) {
result = -1; /* failure */
} else {
result = top_down ? i : i - (num_requested_slots - 1);
ASSERT(i >= 0 && i < bitmap_size);
/* ALIGNED doesn't work for 0 so we have to special-case it */
ASSERT(alignment == 0 ||
ALIGNED(tls_segment_offs(result + align_which_slot), alignment));
}
return result;
}
void
bitmap_mark_taken_sequence(byte *rtl_bitmap, int bitmap_size, int first_slot,
int last_slot_open_end)
{
int i;
uint *p = (uint *)rtl_bitmap; /* we access in 32-bit words */
ASSERT(ALIGNED(rtl_bitmap, sizeof(uint))); /* they promised */
ASSERT(first_slot >= 0 && last_slot_open_end <= bitmap_size);
for (i = first_slot; i < last_slot_open_end; i++)
p[i / 32] |= (1 << (i % 32));
}
void
bitmap_mark_freed_sequence(byte *rtl_bitmap, int bitmap_size, int first_slot,
int num_slots)
{
int i;
uint *p = (uint *)rtl_bitmap; /* we access in 32-bit words */
for (i = first_slot; i < first_slot + num_slots; i++)
p[i / 32] &= ~(1 << (i % 32));
}
/* Our version of kernel32's TlsAlloc
* If synch is false, assumes that the peb lock does not need to be obtained,
* which may be safer than acquiring the lock, though when there's only a single
* thread it shouldn't make any difference (it's a recursive lock).
*/
static bool
tls_alloc_helper(int synch, uint *teb_offs /* OUT */, int num_slots, uint alignment,
uint tls_flags)
{
PEB *peb = get_own_peb();
int start;
RTL_BITMAP local_bitmap;
bool using_local_bitmap = false;
NTSTATUS res;
if (synch) {
/* XXX: I read somewhere they are removing more PEB pointers in Vista or
* earlier..
*/
/* TlsAlloc calls RtlAcquirePebLock which calls RtlEnterCriticalSection */
res = RtlEnterCriticalSection(peb->FastPebLock);
if (!NT_SUCCESS(res))
return false;
}
/* we align the fs offset and assume that the fs base is page-aligned */
ASSERT(alignment < PAGE_SIZE);
/* Transparency notes: we doubt any app relies on a particular slot to be available.
* These are dynamic TLS slots, after all, used only for dlls, who don't know
* which other dlls may be in the address space. The app is going to use
* static TLS. Furthermore, NT only has 64 slots available, so it's unlikely
* an app uses up all the available TLS slots (though we have to have one that's
* in the TEB itself, meaning one of the first 64).
* We walk backward in an attempt to not disrupt the dynamic sequence if only a
* few are in use.
*/
/* case 6770: SQL Server 2005 broke most of the above assumptions:
* - it allocates 38 TLS entries and expects them to all be in
* TLS64 furthermore it assumes that 38 consecutive calls to
* TlsAlloc() return consecutive TLS slots. Therefore we should
* have to make sure we do not leave any slots in a shorter
* earlier sequence available. Although SQL can't handle going
* into the TlsExpansionBitMap
*/
if (peb->TlsBitmap == NULL) {
/* Not initialized yet so use a temp struct to point at the real bits.
* FIXME i#812: ensure our bits here don't get zeroed when ntdll is initialized
*/
ASSERT(dr_earliest_injected);
using_local_bitmap = true;
peb->TlsBitmap = &local_bitmap;
local_bitmap.SizeOfBitMap = 64;
local_bitmap.BitMapBuffer = (void *)&peb->TlsBitmapBits;
} else
ASSERT(peb->TlsBitmap != NULL);
/* TlsBitmap always points to next field, TlsBitmapBits, but we'll only
* use the pointer for generality
*/
ASSERT(&peb->TlsBitmapBits == (void *)peb->TlsBitmap->BitMapBuffer);
DOCHECK(1, {
int first_available = bitmap_find_free_sequence(
peb->TlsBitmap->BitMapBuffer, peb->TlsBitmap->SizeOfBitMap, 1, /* single */
false, /* bottom up */
0, 0 /* no alignment */);
/* On XP ntdll seems to grab slot 0 of the TlsBitmap before loading
* kernel32, see if early injection gets us before that */
/* On Win2k usually first_available == 0, but not in some
* runall tests, so can't assert on the exact value */
ASSERT_CURIOSITY(first_available >= 0);
});
/* only when filling need to find a first_empty in release */
/* TLS_FLAG_BITMAP_FILL - should first find a single slot
* available, then look for whole sequence, then should go through
* and mark ALL entries inbetween. Of course we know we can't go
* beyond index 63 in either request.
*/
if (TEST(TLS_FLAG_BITMAP_FILL, tls_flags)) {
int first_to_fill = bitmap_find_free_sequence(
peb->TlsBitmap->BitMapBuffer, peb->TlsBitmap->SizeOfBitMap, 1, /* single */
false, /* bottom up */
0, 0 /* no alignment */);
ASSERT_NOT_TESTED();
/* we only fill from the front - and taking all up to the top isn't nice */
ASSERT(!TEST(TLS_FLAG_BITMAP_TOP_DOWN, tls_flags));
ASSERT_NOT_IMPLEMENTED(false);
/* FIXME: need to save first slot, so we can free the
* filled slots on exit */
}
/* TLS_FLAG_BITMAP_TOP_DOWN will take a slot at end if possible
* for better transparency, also for better reproducibility */
/* TLS_FLAG_CACHE_LINE_START - will align the first entry,
* otherwise align either first or last since we only care to fit
* on a line */
/* FIXME: align at specific element - not necessary since not
* aligning at all works well for our current choice
*/
/* Note the TLS64 is at fs:[0xe10-0xf10)
* 0xf00 is a cache line start for either 32 or 64 byte
*
* If we want to have commonly used items on the same cache line,
* but also could care about starting at its beginning (not
* expected to matter for data but should measure).
*
* If we only needed 4 slots 0xf00 would be at a cache line start
* and satisfy all requirements.
*
* If we can get not so important items to cross the line, then
* we can have 0xf00 as the balancing item, and the previous 8
* slots will be in one whole cache line on both 32 and 64 byte.
* If we keep it at that then we don't really need alignment hint
* at all - grabbing last is good enough.
*
* Only on P4 we can fit more than 8 entries on the same cache
* line if presumed to all be hot, then we have to use 0xec0 as
* start and leave empty the 0xf00 line. On P3 however we can
* use 0xee0 - only in DEBUG=+HASHTABLE_STATISTICS we use one
* extra slot that ends up at 0xec0. The minor point for P4 is
* then whether we use the first 12 or the last 12 slots in the
* cache line.
*/
/* FIXME: cache line front, otherwise should retry when either
* start or end is fine, and choose closest to desired end of
* bitmap */
start = bitmap_find_free_sequence(peb->TlsBitmap->BitMapBuffer,
peb->TlsBitmap->SizeOfBitMap, num_slots,
TEST(TLS_FLAG_BITMAP_TOP_DOWN, tls_flags),
0 /* align first element */, alignment);
if (!TEST(TLS_FLAG_CACHE_LINE_START, tls_flags)) {
/* try either way, worthwhile only if we fit into an alignment unit */
int end_aligned = bitmap_find_free_sequence(
peb->TlsBitmap->BitMapBuffer, peb->TlsBitmap->SizeOfBitMap, num_slots,
TEST(TLS_FLAG_BITMAP_TOP_DOWN, tls_flags),
/* align the end of last
* element, so open ended */
num_slots, alignment);
if (start < 0) {
ASSERT_NOT_TESTED();
start = end_aligned;
} else {
if (TEST(TLS_FLAG_BITMAP_TOP_DOWN, tls_flags)) {
/* prefer latest start */
if (start < end_aligned) {
start = end_aligned;
ASSERT_NOT_TESTED();
}
} else {
/* bottom up, prefer earlier start */
if (start > end_aligned) {
start = end_aligned;
}
}
}
}
if (start < 0) {
NTPRINT("Failed to find %d slots aligned at %d\n", num_slots, alignment);
goto tls_alloc_exit;
}
bitmap_mark_taken_sequence(peb->TlsBitmap->BitMapBuffer, peb->TlsBitmap->SizeOfBitMap,
start,
/* FIXME: TLS_FLAG_BITMAP_FILL should use first_to_fill */
start + num_slots);
if (teb_offs != NULL) {
*teb_offs = tls_segment_offs(start);
/* mostly safe since using the small TLS map (of 64 entries)
* and that is on TEB so reachable with a short */
/* to avoid ASSERT_TRUNCATE in os_tls_offset() checking here */
ASSERT_TRUNCATE(ushort, ushort, *teb_offs);
NTPRINT("Taking %d tls slot(s) %d-%d at offset 0x%x\n", num_slots, start,
start + num_slots, *teb_offs);
}
DOCHECK(1, {
int first_available = bitmap_find_free_sequence(
peb->TlsBitmap->BitMapBuffer, peb->TlsBitmap->SizeOfBitMap, 1, /* single */
false, /* bottom up */
0, 0 /* no alignment */);
ASSERT_CURIOSITY(first_available >= 0);
/* SQL2005 assumes that first available slot means start of a
* sequence of 38 blanks that fit in TLS64. Unfortunately
* can't assert this for all processes, since even for make
* progrun (notepad on XP SP2, late injection) 16 bits are
* already taken by others. Worse, exactly in SQL server on
* Win2k, at the time we are started there is room, but later
* loaded DLLs use it. Case 6859 on other attempts to catch
* the problem.
*/
});
tls_alloc_exit:
if (using_local_bitmap)
peb->TlsBitmap = NULL;
if (synch) {
res = RtlLeaveCriticalSection(peb->FastPebLock);
if (!NT_SUCCESS(res))
return false;
}
/* ntdll seems to grab slot 0 of the TlsBitmap before loading
* kernel32, see if early injection gets us before that if we go
* bottom up, FIXME: if hit change interface, since 0 is returned
* on error
*/
ASSERT_CURIOSITY(start != 0);
if (start <= 0 && DYNAMO_OPTION(alt_teb_tls)) {
/* i#1163: fall back on other space in TEB */
return alt_tls_acquire(teb_offs, num_slots, alignment);
}
return (start > 0);
}
bool
tls_alloc(int synch, uint *teb_offs /* OUT */)
{
return tls_alloc_helper(synch, teb_offs, 1, 0 /* any alignment */,
/* same top down or bottom up choice as tls_calloc */
DYNAMO_OPTION(tls_flags));
}
/* Allocates num tls slots aligned with particular alignment
* Alignment must be sub-page
*/
bool
tls_calloc(int synch, uint *teb_offs /* OUT */, int num, uint alignment)
{
return tls_alloc_helper(synch, teb_offs, num, alignment, DYNAMO_OPTION(tls_flags));
}
static bool
tls_free_helper(int synch, uint teb_offs, int num)
{
PEB *peb = get_own_peb();
int i, start;
int slot;
uint *p;
NTSTATUS res;
GET_NTDLL(RtlTryEnterCriticalSection, (IN OUT RTL_CRITICAL_SECTION * crit));
if (DYNAMO_OPTION(alt_teb_tls) && alt_tls_release(teb_offs, num))
return true;
if (synch) {
/* TlsFree calls RtlAcquirePebLock which calls RtlEnterCriticalSection
* I'm worried about synch problems so I'm going to just do a Try
* and if it fails I simply will not free the slot, not too bad of a leak.
* On a detach a suspended thread might be holding this lock, or a thread
* killed due to an attack might have held it. We could, on failure to
* get the lock, xchg and read back what we write and try to fix up the bits,
* with the worst case being the app hasn't written but has read and thus
* our free won't go through, but in the past we just called TlsFree and
* never had a lock problem so I'm going to assume Try will work the vast
* majority of the time and the times it doesn't we can eat the leak.
*/
res = RtlTryEnterCriticalSection(peb->FastPebLock);
ASSERT_CURIOSITY(NT_SUCCESS(res));
if (!NT_SUCCESS(res))
return false;
}
ASSERT(peb->TlsBitmap != NULL);
/* TlsBitmap always points to next field, TlsBitmapBits, but we'll only
* use the pointer for generality
*/
p = (uint *)peb->TlsBitmap->BitMapBuffer;
start = (teb_offs - offsetof(TEB, TlsSlots)) / sizeof(uint *);
for (slot = 0, i = start; slot < num; slot++, i++) {
NTPRINT("Freeing tls slot %d at offset 0x%x -> index %d\n", slot, teb_offs, i);
/* In case we aren't synched, zero the tls field before we release it,
* (of course that only takes care of one of many possible races if we
* aren't synched). */
/* This will zero this tls index for all threads (see disassembly of
* FreeTls in kernel32, wine srcs). Strange interface using a
* thread handle, would be more sensical as a process info class (esp.
* with respect to permissions). Note that in the wine srcs at least
* this syscall will only accept NT_CURRENT_THREAD as the handle. Xref
* case 8143 for why we need to zero the tls slot for all threads. */
/* XXX i#1156: we can't zero on win8 where we write the
* termination syscall args into our TLS slots (i#565, r1630).
* We always synch there though.
*/
if (!synch || doing_detach) {
res = nt_raw_SetInformationThread(NT_CURRENT_THREAD, ThreadZeroTlsCell, &i,
sizeof(i));
ASSERT(NT_SUCCESS(res));
}
p[i / 32] &= ~(1 << (i % 32));
}
bitmap_mark_freed_sequence(peb->TlsBitmap->BitMapBuffer, peb->TlsBitmap->SizeOfBitMap,
start, num);
if (synch) {
res = RtlLeaveCriticalSection(peb->FastPebLock);
ASSERT(NT_SUCCESS(res));
if (!NT_SUCCESS(res))
return false;
}
return true;
}
bool
tls_free(int synch, uint teb_offs)
{
return tls_free_helper(synch, teb_offs, 1);
}
bool
tls_cfree(int synch, uint teb_offs, int num)
{
return tls_free_helper(synch, teb_offs, num);
}
#endif /* !NOT_DYNAMORIO_CORE_PROPER */
/***************************************************************************/
bool
get_process_mem_stats(HANDLE h, VM_COUNTERS *info)
{
NTSTATUS res;
ULONG got;
res =
NtQueryInformationProcess(h, ProcessVmCounters, info, sizeof(VM_COUNTERS), &got);
ASSERT(!NT_SUCCESS(res) || got == sizeof(VM_COUNTERS));
return NT_SUCCESS(res);
}
/* Get process quota limits information */
/* Note returns raw NTSTATUS */
NTSTATUS
get_process_mem_quota(HANDLE h, QUOTA_LIMITS *qlimits)
{
NTSTATUS res;
ULONG got;
res = NtQueryInformationProcess(h, ProcessQuotaLimits, qlimits, sizeof(QUOTA_LIMITS),
&got);
ASSERT(!NT_SUCCESS(res) || got == sizeof(QUOTA_LIMITS));
return res;
}
/* Get process quota limits information */
/* Note returns raw NTSTATUS */
NTSTATUS
get_process_handle_count(HANDLE ph, ULONG *handle_count)
{
NTSTATUS res;
ULONG got;
res = NtQueryInformationProcess(ph, ProcessHandleCount, handle_count, sizeof(ULONG),
&got);
ASSERT(!NT_SUCCESS(res) || got == sizeof(ULONG));
return res;
}
int
get_process_load(HANDLE h)
{
KERNEL_USER_TIMES times;
LONGLONG scheduled_time;
LONGLONG wallclock_time;
NTSTATUS res;
ULONG len = 0;
res = NtQueryInformationProcess((HANDLE)h, ProcessTimes, ×, sizeof(times), &len);
if (!NT_SUCCESS(res))
return -1;
/* return length not trustworthy, according to Nebbett, so we don't test it */
/* we want %CPU == (scheduled time) / (wall clock time) */
scheduled_time = times.UserTime.QuadPart + times.KernelTime.QuadPart;
wallclock_time = query_time_100ns() - times.CreateTime.QuadPart;
if (wallclock_time <= 0)
return -1;
return (int)((100 * scheduled_time) / wallclock_time);
}
/* Returns 0 for both known false and error
* XXX: do we still have the restriction of not returning a bool for ntdll.c
* routines?!?
*/
bool
is_wow64_process(HANDLE h)
{
/* since this is called a lot we remember the result for the current process */
static bool self_init = false;
static bool self_is_wow64 = false;
if (h == 0)
return false;
if (!self_init || h != NT_CURRENT_PROCESS) {
ptr_uint_t is_wow64;
NTSTATUS res;
ULONG len = 0;
res = NtQueryInformationProcess((HANDLE)h, ProcessWow64Information, &is_wow64,
sizeof(is_wow64), &len);
if (!NT_SUCCESS(res) || len != sizeof(is_wow64)) {
#if !defined(NOT_DYNAMORIO_CORE_PROPER) && !defined(NOT_DYNAMORIO_CORE)
/* PR 233191: we expect failure on NT but nowhere else */
ASSERT(res == STATUS_INVALID_INFO_CLASS &&
get_os_version() == WINDOWS_VERSION_NT);
#endif
is_wow64 = 0;
}
if (h == NT_CURRENT_PROCESS) {
#if !defined(NOT_DYNAMORIO_CORE_PROPER) && !defined(NOT_DYNAMORIO_CORE)
ASSERT(!dynamo_initialized); /* .data should be writable */
#endif
self_is_wow64 = (is_wow64 != 0);
self_init = true;
}
return (is_wow64 != 0);
}
return self_is_wow64;
}
NTSTATUS
nt_get_drive_map(HANDLE process, PROCESS_DEVICEMAP_INFORMATION *map OUT)
{
ULONG len = 0;
return NtQueryInformationProcess(process, ProcessDeviceMap, map, sizeof(*map), &len);
}
/* use base hint if present; will bump size up to PAGE_SIZE multiple
* Note returns raw NTSTATUS.
*/
NTSTATUS
nt_remote_allocate_virtual_memory(HANDLE process, void **base, size_t size, uint prot,
memory_commit_status_t commit)
{
NTSTATUS res;
SIZE_T sz = size;
ASSERT(ALIGNED(*base, PAGE_SIZE) && "base argument not initialized at PAGE_SIZE");
res = NT_SYSCALL(AllocateVirtualMemory, process, base, 0 /* zero bits */, &sz, commit,
prot);
if (res == STATUS_CONFLICTING_ADDRESSES) {
NTPRINT("NtAllocateVirtualMemory: conflict at base " PFX ", res=" PFX "\n", *base,
res);
/* Let caller decide whether to retry or not. */
}
/* FIXME: alert caller if sz > size? only happens if size not PAGE_SIZE multiple */
NTPRINT("NtAllocateVirtualMemory: asked for %d bytes, got %d bytes at " PFX "\n",
size, sz, *base);
ASSERT(sz >= size);
return res;
}
/* Decommit memory previously committed with nt_remote_allocate_virtual_memory()
* Note returns raw NTSTATUS.
*/
NTSTATUS
nt_remote_free_virtual_memory(HANDLE process, void *base)
{
NTSTATUS res;
SIZE_T sz = 0; /* has to be 0 for MEM_RELEASE */
res = NT_SYSCALL(FreeVirtualMemory, process, &base, &sz, MEM_RELEASE);
NTPRINT("NtRemoteFreeVirtualMemory: freed " SZFMT " bytes\n", sz);
return res;
}
/* use base hint is present; will bump size up to PAGE_SIZE multiple
* Note returns raw NTSTATUS.
*/
NTSTATUS
nt_allocate_virtual_memory(void **base, size_t size, uint prot,
memory_commit_status_t commit)
{
return nt_remote_allocate_virtual_memory(NT_CURRENT_PROCESS, base, size, prot,
commit);
}
/* commit memory previously reserved with nt_allocate_virtual_memory()
* Note returns raw NTSTATUS.
*/
NTSTATUS
nt_commit_virtual_memory(void *base, size_t size, uint prot)
{
NTSTATUS res;
DEBUG_DECLARE(void *original_base = base;)
DEBUG_DECLARE(size_t original_size = size;)
res = NT_SYSCALL(AllocateVirtualMemory, NT_CURRENT_PROCESS, &base, 0, (SIZE_T *)&size,
MEM_COMMIT, /* should be already reserved */ prot);
ASSERT(base == original_base);
ASSERT(size == original_size);
ASSERT_CURIOSITY(NT_SUCCESS(res));
return res;
}
/* Decommit memory previously committed with nt_commit_virtual_memory() or
* nt_allocate_virtual_memory(). Still available for committing again.
* Note returns raw NTSTATUS.
*/
NTSTATUS
nt_decommit_virtual_memory(void *base, size_t size)
{
NTSTATUS res;
SIZE_T sz = size; /* copied to compare with OUT value */
res = NT_SYSCALL(FreeVirtualMemory, NT_CURRENT_PROCESS, &base, &sz, MEM_DECOMMIT);
ASSERT(sz == size);
NTPRINT("NtFreeVirtualMemory: decommitted %d bytes [res=%d]\n", sz, res);
ASSERT_CURIOSITY(NT_SUCCESS(res));
return res;
}
/* Decommit memory previously committed with nt_commit_virtual_memory() or
* nt_allocate_virtual_memory(). Still available for committing again.
* Note returns raw NTSTATUS.
*/
NTSTATUS
nt_free_virtual_memory(void *base)
{
NTSTATUS res;
SIZE_T sz = 0; /* has to be 0 for MEM_RELEASE */
res = NT_SYSCALL(FreeVirtualMemory, NT_CURRENT_PROCESS, &base, &sz, MEM_RELEASE);
NTPRINT("NtFreeVirtualMemory: freed " SZFMT " bytes\n", sz);
ASSERT_CURIOSITY(NT_SUCCESS(res));
return res;
}
/* FIXME: change name to nt_protect_virtual_memory() and use
* nt_remote_protect_virtual_memory(), or maybe just change callers to
* pass NT_CURRENT_PROCESS to nt_remote_protect_virtual_memory()
* instead to avoid the extra function call, especially with self-protection on
*/
bool
protect_virtual_memory(void *base, size_t size, uint prot, uint *old_prot)
{
NTSTATUS res;
SIZE_T sz = size;
res = NT_SYSCALL(ProtectVirtualMemory, NT_CURRENT_PROCESS, &base, &sz, prot,
(ULONG *)old_prot);
NTPRINT("NtProtectVirtualMemory: " PFX "-" PFX " 0x%x => 0x%x\n", base,
(byte *)base + size, prot, res);
ASSERT(sz == ALIGN_FORWARD(size, PAGE_SIZE));
return NT_SUCCESS(res);
}
bool
nt_remote_protect_virtual_memory(HANDLE process, void *base, size_t size, uint prot,
uint *old_prot)
{
NTSTATUS res;
SIZE_T sz = size;
res = NT_SYSCALL(ProtectVirtualMemory, process, &base, &sz, prot, (ULONG *)old_prot);
NTPRINT("NtProtectVirtualMemory: process " PFX " " PFX "-" PFX " 0x%x => 0x%x\n",
process, base, (byte *)base + size, prot, res);
ASSERT(ALIGNED(base, PAGE_SIZE) && "base argument not initialized at PAGE_SIZE");
NTPRINT("NtProtectVirtualMemory: intended to change %d bytes, "
"modified %d bytes at " PFX "\n",
size, sz, base);
ASSERT(sz >= size);
return NT_SUCCESS(res);
}
NTSTATUS
nt_remote_query_virtual_memory(HANDLE process, const byte *pc,
MEMORY_BASIC_INFORMATION *mbi, size_t mbilen, size_t *got)
{
/* XXX: we can't switch this to a raw syscall as we rely on d_r_get_proc_address()
* working in syscalls_init_get_num(), and it calls get_allocation_size()
* which ends up here.
*/
ASSERT(mbilen == sizeof(MEMORY_BASIC_INFORMATION));
memset(mbi, 0, sizeof(MEMORY_BASIC_INFORMATION));
return NT_SYSCALL(QueryVirtualMemory, process, pc, MemoryBasicInformation, mbi,
mbilen, (PSIZE_T)got);
}
/* We use this instead of VirtualQuery b/c there are problems using
* win32 API routines inside of the app using them
*/
/* We make our signature look like VirtualQuery */
size_t
query_virtual_memory(const byte *pc, MEMORY_BASIC_INFORMATION *mbi, size_t mbilen)
{
NTSTATUS res;
size_t got;
res = nt_remote_query_virtual_memory(NT_CURRENT_PROCESS, pc, mbi, mbilen, &got);
ASSERT(!NT_SUCCESS(res) || got == sizeof(MEMORY_BASIC_INFORMATION));
/* only 0 and sizeof(MEMORY_BASIC_INFORMATION) should be expected by callers */
if (!NT_SUCCESS(res))
got = 0;
#if !defined(NOT_DYNAMORIO_CORE_PROPER) && !defined(NOT_DYNAMORIO_CORE)
/* for stress testing a fake driver access */
if (INTERNAL_OPTION(stress_fake_userva) != 0) {
if (pc > (app_pc)INTERNAL_OPTION(stress_fake_userva))
return 0;
}
#endif
return got;
}
NTSTATUS
get_mapped_file_name(const byte *pc, PWSTR buf, USHORT buf_bytes)
{
NTSTATUS res;
SIZE_T got;
/* name.SectionFileName.Buffer MUST be inlined: even if Buffer is initialized
* to point elsewhere, the kernel modifies it. The size passed in must include
* the struct and the post-inlined buffer.
*/
MEMORY_SECTION_NAME *name = (MEMORY_SECTION_NAME *)buf;
name->SectionFileName.Length = 0;
name->SectionFileName.MaximumLength = buf_bytes - sizeof(*name);
name->SectionFileName.Buffer = buf + sizeof(*name);
res = NT_SYSCALL(QueryVirtualMemory, NT_CURRENT_PROCESS, pc, MemorySectionName, name,
buf_bytes, &got);
if (NT_SUCCESS(res)) {
/* save since we'll be clobbering the fields */
int len = name->SectionFileName.Length;
memmove(buf, name->SectionFileName.Buffer, len);
buf[len / sizeof(wchar_t)] = L'\0';
}
return res;
}
NTSTATUS
nt_raw_read_virtual_memory(HANDLE process, const void *base, void *buffer,
size_t buffer_length, size_t *bytes_read)
{
NTSTATUS res;
GET_NTDLL(NtReadVirtualMemory,
(IN HANDLE ProcessHandle, IN const void *BaseAddress, OUT PVOID Buffer,
IN SIZE_T BufferLength, OUT PSIZE_T ReturnLength OPTIONAL));
res = NtReadVirtualMemory(process, base, buffer, buffer_length, (SIZE_T *)bytes_read);
return res;
}
bool
nt_read_virtual_memory(HANDLE process, const void *base, void *buffer,
size_t buffer_length, size_t *bytes_read)
{
return NT_SUCCESS(
nt_raw_read_virtual_memory(process, base, buffer, buffer_length, bytes_read));
}
NTSTATUS
nt_raw_write_virtual_memory(HANDLE process, void *base, const void *buffer,
size_t buffer_length, size_t *bytes_written)
{
NTSTATUS res;
GET_RAW_SYSCALL(WriteVirtualMemory, IN HANDLE ProcessHandle, IN PVOID BaseAddress,
IN const void *Buffer, IN SIZE_T BufferLength,
OUT PSIZE_T ReturnLength OPTIONAL);
res = NT_SYSCALL(WriteVirtualMemory, process, base, buffer, buffer_length,
(SIZE_T *)bytes_written);
return res;
}
bool
nt_write_virtual_memory(HANDLE process, void *base, const void *buffer,
size_t buffer_length, size_t *bytes_written)
{
return NT_SUCCESS(
nt_raw_write_virtual_memory(process, base, buffer, buffer_length, bytes_written));
}
/* There are no Win32 API routines to do this, so we use NtContinue */
void
nt_continue(CONTEXT *cxt)
{
GET_RAW_SYSCALL(Continue, IN PCONTEXT Context, IN BOOLEAN TestAlert);
NT_SYSCALL(Continue, cxt, 0 /* don't change APC status */);
/* should not get here */
ASSERT_NOT_REACHED();
}
NTSTATUS
nt_get_context(HANDLE hthread, CONTEXT *cxt)
{
GET_RAW_SYSCALL(GetContextThread, IN HANDLE ThreadHandle, OUT PCONTEXT Context);
/* PR 263338: we get STATUS_DATATYPE_MISALIGNMENT if not aligned */
IF_X64(ASSERT(ALIGNED(cxt, 16)));
return NT_SYSCALL(GetContextThread, hthread, cxt);
/* Don't assert here -- let the caller do so if it expects a particular value.
* If we asserted here when an ldmp is being generated, we could prevent
* generation of the ldmp if there is a handle privilege problem between
* the calling thread and hthread.
*/
}
/* WARNING: any time we set a thread's context we must make sure we can
* handle two cases:
* 1) the thread was at a syscall and now we won't recognize it as such
* (case 6113) (not to mention that the kernel will finish the
* syscall and clobber eax and ecx+edx after setting to cxt: case 5074)
* 2) the thread just hit a fault but the kernel has not yet copied the
* faulting context to the user mode structures for the handler
* (case 7393)
*/
NTSTATUS
nt_set_context(HANDLE hthread, CONTEXT *cxt)
{
GET_RAW_SYSCALL(SetContextThread, IN HANDLE ThreadHandle, IN PCONTEXT Context);
/* PR 263338: we get STATUS_DATATYPE_MISALIGNMENT if not aligned */
IF_X64(ASSERT(ALIGNED(cxt, 16)));
return NT_SYSCALL(SetContextThread, hthread, cxt);
}
bool
nt_thread_suspend(HANDLE hthread, int *previous_suspend_count)
{
NTSTATUS res;
GET_RAW_SYSCALL(SuspendThread, IN HANDLE ThreadHandle,
OUT PULONG PreviousSuspendCount OPTIONAL);
res = NT_SYSCALL(SuspendThread, hthread, (ULONG *)previous_suspend_count);
/* Don't assert here -- let the caller do so if it expects a particular value.
* If we asserted here when an ldmp is being generated, we could prevent
* generation of the ldmp if there is a handle privilege problem between
* the calling thread and hthread.
*/
return NT_SUCCESS(res);
}
bool
nt_thread_resume(HANDLE hthread, int *previous_suspend_count)
{
NTSTATUS res;
GET_RAW_SYSCALL(ResumeThread, IN HANDLE ThreadHandle,
OUT PULONG PreviousSuspendCount OPTIONAL);
res = NT_SYSCALL(ResumeThread, hthread, (ULONG *)previous_suspend_count);
return NT_SUCCESS(res);
}
#if !defined(NOT_DYNAMORIO_CORE_PROPER) && !defined(NOT_DYNAMORIO_CORE)
NTSTATUS
nt_thread_iterator_next(HANDLE hprocess, HANDLE cur_thread, HANDLE *next_thread,
ACCESS_MASK access)
{
if (NtGetNextThread == NULL)
return STATUS_NOT_IMPLEMENTED;
return NtGetNextThread(hprocess, cur_thread, access, 0, 0, next_thread);
}
#endif
bool
nt_terminate_thread(HANDLE hthread, NTSTATUS exit_code)
{
NTSTATUS res;
GET_RAW_SYSCALL(TerminateThread, IN HANDLE ThreadHandle OPTIONAL,
IN NTSTATUS ExitStatus);
/* hthread == 0 means current thread, match kernel32 TerminateThread which
* disallows null to avoid bugs in our code (we should always be passing
* a valid handle or NT_CURRENT_THREAD) */
ASSERT(hthread != (HANDLE)0);
res = NT_SYSCALL(TerminateThread, hthread, exit_code);
ASSERT(hthread != NT_CURRENT_THREAD && "terminate current thread failed");
return NT_SUCCESS(res);
}
bool
nt_terminate_process(HANDLE hprocess, NTSTATUS exit_code)
{
NTSTATUS res;
GET_RAW_SYSCALL(TerminateProcess, IN HANDLE ProcessHandle OPTIONAL,
IN NTSTATUS ExitStatus);
/* hprocess == 0 has special meaning (terminate all threads but this one),
* kernel32!TerminateProcess disallows it and we currently don't use
* that functionality */
ASSERT(hprocess != (HANDLE)0);
res = NT_SYSCALL(TerminateProcess, hprocess, exit_code);
ASSERT(hprocess != NT_CURRENT_PROCESS && "terminate current process failed");
return NT_SUCCESS(res);
}
NTSTATUS
nt_terminate_process_for_app(HANDLE hprocess, NTSTATUS exit_code)
{
GET_RAW_SYSCALL(TerminateProcess, IN HANDLE ProcessHandle OPTIONAL,
IN NTSTATUS ExitStatus);
/* we allow any argument or result values */
return NT_SYSCALL(TerminateProcess, hprocess, exit_code);
}
bool
am_I_sole_thread(HANDLE hthread, int *amI /*OUT*/)
{
NTSTATUS res;
ULONG got;
res = NT_SYSCALL(QueryInformationThread, hthread, ThreadAmILastThread, amI,
sizeof(*amI), &got);
return NT_SUCCESS(res);
}
/* checks current thread, and turns errors into false */
bool
check_sole_thread()
{
int amI;
if (!am_I_sole_thread(NT_CURRENT_THREAD, &amI))
return false;
else
return (amI != 0);
}
HANDLE
nt_create_and_set_timer(PLARGE_INTEGER due_time, LONG period)
{
NTSTATUS res;
HANDLE htimer;
enum { NotificationTimer, SynchronizationTimer };
GET_NTDLL(NtCreateTimer,
(OUT PHANDLE TimerHandle, IN ACCESS_MASK DesiredAccess,
IN POBJECT_ATTRIBUTES ObjectAttributes, IN DWORD TimerType /* TIMER_TYPE */
));
res = NtCreateTimer(&htimer, TIMER_ALL_ACCESS, NULL /* no name */,
SynchronizationTimer);
ASSERT(NT_SUCCESS(res));
{
GET_NTDLL(NtSetTimer,
(IN HANDLE TimerHandle, IN PLARGE_INTEGER DueTime,
IN PVOID TimerApcRoutine, /* PTIMER_APC_ROUTINE */
IN PVOID TimerContext, IN BOOLEAN Resume, IN LONG Period,
OUT PBOOLEAN PreviousState));
res = NtSetTimer(htimer, due_time, NULL, NULL, false, period, NULL);
ASSERT(NT_SUCCESS(res));
}
return htimer;
}
bool
nt_sleep(PLARGE_INTEGER due_time)
{
NTSTATUS res;
GET_NTDLL(NtDelayExecution, (IN BOOLEAN Alertable, IN PLARGE_INTEGER Interval));
res = NtDelayExecution(false, /* non alertable sleep */
due_time);
return NT_SUCCESS(res);
}
void
nt_yield()
{
GET_NTDLL(NtYieldExecution, (VOID));
NtYieldExecution();
}
void *
get_section_address(HANDLE h)
{
SECTION_BASIC_INFORMATION info;
NTSTATUS res;
ULONG got;
memset(&info, 0, sizeof(SECTION_BASIC_INFORMATION));
res = NtQuerySection(h, SectionBasicInformation, &info,
sizeof(SECTION_BASIC_INFORMATION), &got);
ASSERT(NT_SUCCESS(res) && got == sizeof(SECTION_BASIC_INFORMATION));
return info.BaseAddress;
}
/* returns true if attributes can be read and sets them,
* otherwise the values are not modified
*/
bool
get_section_attributes(HANDLE h, uint *section_attributes /* OUT */,
LARGE_INTEGER *section_size /* OPTIONAL OUT */)
{
SECTION_BASIC_INFORMATION info;
NTSTATUS res;
ULONG got;
memset(&info, 0, sizeof(SECTION_BASIC_INFORMATION));
ASSERT(section_attributes != NULL);
res = NtQuerySection(h, SectionBasicInformation, &info,
sizeof(SECTION_BASIC_INFORMATION), &got);
if (NT_SUCCESS(res)) {
ASSERT(got == sizeof(SECTION_BASIC_INFORMATION));
*section_attributes = info.Attributes;
if (section_size != NULL) {
*section_size = info.Size;
}
return true;
} else {
/* Unfortunately, we are often passed section handles that are
* created as GrantedAccess 0xe: None,
* MapWrite,MapRead,MapExecute which cannot be queried
*/
return false;
}
}
NTSTATUS
nt_raw_close(HANDLE h)
{
GET_RAW_SYSCALL(Close, IN HANDLE Handle);
return NT_SYSCALL(Close, h);
}
bool
close_handle(HANDLE h)
{
return NT_SUCCESS(nt_raw_close(h));
}
/* Note returns raw NTSTATUS */
NTSTATUS
duplicate_handle(HANDLE source_process, HANDLE source, HANDLE target_process,
HANDLE *target, ACCESS_MASK access, uint attributes, uint options)
{
NTSTATUS res;
GET_RAW_SYSCALL(DuplicateObject, IN HANDLE SourceProcessHandle,
IN HANDLE SourceHandle, IN HANDLE TargetProcessHandle,
OUT PHANDLE TargetHandle OPTIONAL, IN ACCESS_MASK DesiredAcess,
IN ULONG Atrributes, IN ULONG options_t);
res = NT_SYSCALL(DuplicateObject, source_process, source, target_process, target,
access, attributes, options);
return res;
}
GET_NTDLL(NtQueryObject,
(IN HANDLE ObjectHandle, IN OBJECT_INFORMATION_CLASS ObjectInformationClass,
OUT PVOID ObjectInformation, IN ULONG ObjectInformationLength,
OUT PULONG ReturnLength OPTIONAL));
ACCESS_MASK
nt_get_handle_access_rights(HANDLE handle)
{
NTSTATUS res;
OBJECT_BASIC_INFORMATION obj_info;
ULONG needed_length;
res = NtQueryObject(handle, ObjectBasicInformation, &obj_info, sizeof(obj_info),
&needed_length);
ASSERT(needed_length == sizeof(obj_info));
ASSERT(NT_SUCCESS(res));
return obj_info.GrantedAccess;
}
/* byte_length is total size of UNICODE_STRING struct and an embedded buffer */
NTSTATUS
nt_get_object_name(HANDLE handle, OBJECT_NAME_INFORMATION *object_name /* OUT */,
uint byte_length, uint *returned_byte_length /* OUT */)
{
NTSTATUS res;
res = NtQueryObject(handle, ObjectNameInformation, object_name, byte_length,
(ULONG *)returned_byte_length);
ASSERT(NT_SUCCESS(res));
return res;
}
NTSTATUS
wchar_to_unicode(PUNICODE_STRING dst, PCWSTR src)
{
NTSTATUS res;
GET_NTDLL(RtlInitUnicodeString,
(IN OUT PUNICODE_STRING DestinationString, IN PCWSTR SourceString));
res = RtlInitUnicodeString(dst, src);
return res;
}
/* we don't want to allocate memory, so caller must provide
* a buffer that's big enough for char -> wchar conversion
*/
static NTSTATUS
char_to_unicode(PUNICODE_STRING dst, PCSTR src, PWSTR buf, size_t buflen)
{
_snwprintf(buf, buflen, L"%S", src);
return wchar_to_unicode(dst, buf);
}
static void
char_to_ansi(PANSI_STRING dst, const char *str)
{
GET_NTDLL(RtlInitAnsiString,
(IN OUT PANSI_STRING DestinationString, IN PCSTR SourceString));
RtlInitAnsiString(dst, str);
}
/* Collects file attributes.
* Returns 1 if successful; 0 otherwise.
* (Using bool is problematic for non-core users.)
*/
bool
query_full_attributes_file(IN PCWSTR filename, OUT PFILE_NETWORK_OPEN_INFORMATION info)
{
NTSTATUS result;
OBJECT_ATTRIBUTES attributes;
UNICODE_STRING objname;
memset(&attributes, 0, sizeof(attributes));
wchar_to_unicode(&objname, filename);
InitializeObjectAttributes(&attributes, &objname, OBJ_CASE_INSENSITIVE, NULL, NULL);
result = nt_raw_QueryFullAttributesFile(&attributes, info);
return NT_SUCCESS(result);
}
NTSTATUS
nt_query_value_key(IN HANDLE key, IN PUNICODE_STRING value_name,
IN KEY_VALUE_INFORMATION_CLASS class, OUT PVOID info,
IN ULONG info_length, OUT PULONG res_length)
{
GET_NTDLL(NtQueryValueKey,
(IN HANDLE KeyHandle, IN PUNICODE_STRING ValueName,
IN KEY_VALUE_INFORMATION_CLASS KeyValueInformationClass,
OUT PVOID KeyValueInformation, IN ULONG Length, OUT PULONG ResultLength));
return NtQueryValueKey(key, value_name, class, info, info_length, res_length);
}
/* rights should be KEY_READ or KEY_WRITE or both */
/* parent handle HAS to be opened with an absolute name */
HANDLE
reg_create_key(HANDLE parent, PCWSTR keyname, ACCESS_MASK rights)
{
NTSTATUS res;
OBJECT_ATTRIBUTES attr;
UNICODE_STRING objname;
ULONG disp;
HANDLE hkey;
res = wchar_to_unicode(&objname, keyname);
if (!NT_SUCCESS(res))
return NULL;
InitializeObjectAttributes(&attr, &objname, OBJ_CASE_INSENSITIVE, parent, NULL);
res = nt_raw_CreateKey(&hkey, rights, &attr, 0, NULL, 0, &disp);
if (!NT_SUCCESS(res)) {
NTPRINT("Error 0x%x in create key for \"%S\"\n", res, objname.Buffer);
return NULL;
} else
return hkey;
}
/* rights should be KEY_READ or KEY_WRITE or both */
HANDLE
reg_open_key(PCWSTR keyname, ACCESS_MASK rights)
{
NTSTATUS res;
HANDLE hkey;
OBJECT_ATTRIBUTES attr;
UNICODE_STRING objname;
GET_RAW_SYSCALL(OpenKey, OUT PHANDLE KeyHandle, IN ACCESS_MASK DesiredAccess,
IN POBJECT_ATTRIBUTES ObjectAttributes);
res = wchar_to_unicode(&objname, keyname);
if (!NT_SUCCESS(res)) {
NTPRINT("Error in wchar to unicode\n");
return NULL;
}
InitializeObjectAttributes(&attr, &objname, OBJ_CASE_INSENSITIVE, NULL, NULL);
res = NT_SYSCALL(OpenKey, &hkey, rights, &attr);
if (!NT_SUCCESS(res)) {
NTPRINT("Error 0x%x in open key for \"%S\"\n", res, objname.Buffer);
return NULL;
} else
return hkey;
}
bool
reg_close_key(HANDLE hkey)
{
return close_handle(hkey);
}
bool
reg_delete_key(HANDLE hkey)
{
NTSTATUS res;
GET_NTDLL(NtDeleteKey, (IN HANDLE KeyHandle));
res = NtDeleteKey(hkey);
NTPRINT("Got %d for deleting key\n", res);
return NT_SUCCESS(res);
}
/* Enumerates the values of a registry key via the NtEnumerateValueKey
* system call.
*
* Note that the caller must allocate memory at the end of
* KEY_VALUE_FULL_INFORMATION to store the actual data.
* WARNING: the Name field often has no null terminating it. It
* either runs right up next to Data or has an un-initialized value
* in it -- so make sure you zero out your buffer before calling
* this routine, and use the NameLength field (bytes not chars) and
* then check for null and skip over it if nec. to find the data start.
*/
reg_query_value_result_t
reg_query_value(IN PCWSTR keyname, IN PCWSTR subkeyname,
IN KEY_VALUE_INFORMATION_CLASS info_class, OUT PVOID info,
IN ULONG info_size, IN ACCESS_MASK rights)
{
int res;
ULONG outlen = 0;
UNICODE_STRING valuename;
HANDLE hkey = reg_open_key(keyname, KEY_READ | rights);
if (hkey == NULL)
return REG_QUERY_FAILURE;
res = wchar_to_unicode(&valuename, subkeyname);
if (!NT_SUCCESS(res))
return REG_QUERY_FAILURE;
res = nt_query_value_key(hkey, &valuename, info_class, info, info_size, &outlen);
reg_close_key(hkey);
#if VERBOSE
if (!NT_SUCCESS(res))
NTPRINT("Error 0x%x in query key \"%S\"\n", res, subkeyname);
#endif
/* When buffer is insufficient I see it return BUFFER_OVERFLOW, but nebbet
* mentions BUFFER_TOO_SMALL as well. */
if (res == STATUS_BUFFER_TOO_SMALL || res == STATUS_BUFFER_OVERFLOW) {
return REG_QUERY_BUFFER_TOO_SMALL;
}
return NT_SUCCESS(res) ? REG_QUERY_SUCCESS : REG_QUERY_FAILURE;
}
GET_RAW_SYSCALL(SetValueKey, IN HANDLE KeyHandle, IN PUNICODE_STRING ValueName,
IN ULONG TitleIndex OPTIONAL, IN ULONG Type, IN PVOID Data,
IN ULONG DataSize);
bool
reg_set_key_value(HANDLE hkey, PCWSTR subkey, PCWSTR val)
{
UNICODE_STRING name;
UNICODE_STRING value;
NTSTATUS res;
res = wchar_to_unicode(&name, subkey);
if (!NT_SUCCESS(res))
return NT_SUCCESS(res);
res = wchar_to_unicode(&value, val);
if (!NT_SUCCESS(res))
return NT_SUCCESS(res);
/* Length field is really size in bytes, have to add 1 for final 0 */
res = NT_SYSCALL(SetValueKey, hkey, &name, 0, REG_SZ, (LPBYTE)value.Buffer,
value.Length + sizeof(wchar_t));
return NT_SUCCESS(res);
}
bool
reg_set_dword_key_value(HANDLE hkey, PCWSTR subkey, DWORD value)
{
UNICODE_STRING name;
NTSTATUS res;
res = wchar_to_unicode(&name, subkey);
if (!NT_SUCCESS(res))
return NT_SUCCESS(res);
res = NT_SYSCALL(SetValueKey, hkey, &name, 0, REG_DWORD, &value, sizeof(DWORD));
return NT_SUCCESS(res);
}
/* Flushes registry changes for the given key to the disk.
* Returns 1 on success, 0 otherwise.
* Notes: See case 4138. For a valid opened key, failure can happen
* only if registry IO fails, i.e., this function shouldn't fail
* for most cases.
*/
bool
reg_flush_key(HANDLE hkey)
{
NTSTATUS res;
GET_NTDLL(NtFlushKey, (IN HANDLE KeyHandle));
res = NtFlushKey(hkey);
return NT_SUCCESS(res);
}
/* Enumerates the subkeys of a registry key via the NtEnumerateKey
* system call.
*
* Note that the caller must allocate memory at the end of
* KEY_VALUE_FULL_INFORMATION to store the actual data.
* WARNING: the Name field often has no null terminating it. It
* either runs right up next to Data or has an un-initialized value
* in it -- so make sure you zero out your buffer before calling
* this routine, and use the NameLength field (bytes not chars) and
* then check for null and skip over it if nec. to find the data start.
*
* Returns 1 on success, 0 otherwise.
*/
bool
reg_enum_key(IN PCWSTR keyname, IN ULONG index, IN KEY_INFORMATION_CLASS info_class,
OUT PVOID key_info, IN ULONG key_info_size)
{
NTSTATUS result;
ULONG received = 0;
HANDLE hkey = reg_open_key(keyname, KEY_READ);
GET_NTDLL(NtEnumerateKey,
(IN HANDLE hkey, IN ULONG index, IN KEY_INFORMATION_CLASS info_class,
OUT PVOID key_info, IN ULONG key_info_size, OUT PULONG bytes_received));
if (hkey == NULL)
return false;
result = NtEnumerateKey(hkey, index, info_class, key_info, key_info_size, &received);
reg_close_key(hkey);
return NT_SUCCESS(result);
}
/* Enumerates the values of a registry key via the NtEnumerateValueKey
* system call.
*
* Note that the caller must allocate memory at the end of
* KEY_VALUE_FULL_INFORMATION to store the actual data.
* WARNING: the Name field often has no null terminating it. It
* either runs right up next to Data or has an un-initialized value
* in it -- so make sure you zero out your buffer before calling
* this routine, and use the NameLength field (bytes not chars) and
* then check for null and skip over it if nec. to find the data start.
* Returns 1 on success, 0 otherwise.
*/
bool
reg_enum_value(IN PCWSTR keyname, IN ULONG index,
IN KEY_VALUE_INFORMATION_CLASS info_class, OUT PVOID key_info,
IN ULONG key_info_size)
{
NTSTATUS result;
ULONG bytes_received = 0;
HANDLE hkey = reg_open_key(keyname, KEY_READ);
GET_NTDLL(NtEnumerateValueKey,
(IN HANDLE hKey, IN ULONG index, IN KEY_VALUE_INFORMATION_CLASS info_class,
OUT PVOID key_info, IN ULONG key_info_size, OUT PULONG bytes_received));
if (hkey == NULL)
return false;
result = NtEnumerateValueKey(hkey, index, info_class, key_info, key_info_size,
&bytes_received);
reg_close_key(hkey);
return NT_SUCCESS(result);
}
/* queries the process env vars: NOT the separate copies used in the C
* library and in other libraries
*/
bool
env_get_value(PCWSTR var, wchar_t *val, size_t valsz)
{
PEB *peb = get_own_peb();
PWSTR env = (PWSTR)get_process_param_buf(peb->ProcessParameters,
peb->ProcessParameters->Environment);
NTSTATUS res;
UNICODE_STRING var_us, val_us;
GET_NTDLL(RtlQueryEnvironmentVariable_U,
(PWSTR Environment, PUNICODE_STRING Name, PUNICODE_STRING Value));
res = wchar_to_unicode(&var_us, var);
if (!NT_SUCCESS(res))
return false;
val_us.Length = 0;
val_us.MaximumLength = (USHORT)valsz;
val_us.Buffer = val;
res = RtlQueryEnvironmentVariable_U(env, &var_us, &val_us);
return NT_SUCCESS(res);
}
/* thread token can be primary token, impersonated, or anonymous */
NTSTATUS
get_current_user_token(PTOKEN_USER ptoken, USHORT token_buffer_length)
{
NTSTATUS res;
HANDLE htoken;
ULONG len = 0;
res = nt_raw_OpenThreadToken(NT_CURRENT_THREAD, TOKEN_QUERY, TRUE, &htoken);
if (!NT_SUCCESS(res)) {
/* anonymous impersonation token cannot be opened */
res = nt_raw_OpenProcessToken(NT_CURRENT_PROCESS, TOKEN_QUERY, &htoken);
if (!NT_SUCCESS(res)) {
return res;
}
}
res = NtQueryInformationToken(htoken, TokenUser, ptoken, token_buffer_length, &len);
close_handle(htoken);
ASSERT(len <= token_buffer_length);
if (!NT_SUCCESS(res)) {
ASSERT_CURIOSITY(false && "can't query token, impersonated?");
}
return res;
}
NTSTATUS
get_primary_user_token(PTOKEN_USER ptoken, USHORT token_buffer_length)
{
NTSTATUS res;
HANDLE htoken;
ULONG len = 0;
res = nt_raw_OpenProcessToken(NT_CURRENT_PROCESS, TOKEN_QUERY, &htoken);
if (!NT_SUCCESS(res)) {
return res;
}
res = NtQueryInformationToken(htoken, TokenUser, ptoken, token_buffer_length, &len);
close_handle(htoken);
ASSERT(len <= token_buffer_length);
if (!NT_SUCCESS(res)) {
ASSERT_CURIOSITY(false && "can't query token?");
}
return res;
}
/* returns the Owner that will be recorded for any objects created by
* this process (when not impersonating)
*/
NTSTATUS
get_primary_owner_token(PTOKEN_OWNER powner, USHORT owner_buffer_length)
{
NTSTATUS res;
HANDLE htoken;
ULONG len = 0;
res = nt_raw_OpenProcessToken(NT_CURRENT_PROCESS, TOKEN_QUERY, &htoken);
if (!NT_SUCCESS(res)) {
return res;
}
res = NtQueryInformationToken(htoken, TokenOwner, powner, owner_buffer_length, &len);
close_handle(htoken);
ASSERT(len <= owner_buffer_length);
if (!NT_SUCCESS(res)) {
ASSERT_CURIOSITY(false && "can't query token?");
}
return res;
}
/* Note that the caller must allocate buffer_length bytes in sid_string */
NTSTATUS
get_current_user_SID(PWSTR sid_string, USHORT buffer_length)
{
GET_NTDLL(RtlConvertSidToUnicodeString,
(OUT PUNICODE_STRING UnicodeString, IN PSID Sid,
BOOLEAN AllocateDestinationString));
NTSTATUS res;
UNICODE_STRING ustr;
UCHAR buf[SECURITY_MAX_TOKEN_SIZE];
PTOKEN_USER ptoken = (PTOKEN_USER)buf;
res = get_current_user_token(ptoken, sizeof(buf));
if (!NT_SUCCESS(res)) {
return res;
}
ustr.Length = 0;
ustr.MaximumLength = buffer_length;
ustr.Buffer = sid_string;
/* We assume that by passing FALSE, no memory will be allocated
* and the routine is reentrant.
*/
res = RtlConvertSidToUnicodeString(&ustr, ptoken->User.Sid, FALSE);
return res;
}
const PSID
get_process_primary_SID()
{
static PSID primary_SID = NULL;
static UCHAR buf[SECURITY_MAX_TOKEN_SIZE];
if (primary_SID == NULL) {
PTOKEN_USER ptoken = (PTOKEN_USER)buf;
NTSTATUS res;
res = get_primary_user_token(ptoken, sizeof(buf));
ASSERT(NT_SUCCESS(res));
if (!NT_SUCCESS(res)) {
return NULL;
}
primary_SID = ptoken->User.Sid;
}
return primary_SID;
}
/* based on RtlpQuerySecurityDescriptorPointers from reactos/0.2.9/lib/rtl/sd.c */
static void
get_sd_pointers(IN PISECURITY_DESCRIPTOR SecurityDescriptor, OUT PSID *Owner OPTIONAL,
OUT PSID *Group OPTIONAL, OUT PACL *Sacl OPTIONAL,
OUT PACL *Dacl OPTIONAL)
{
/* we usually deal with self-relative SIDs as returned by NtQuerySecurityObject */
if (TEST(SE_SELF_RELATIVE, SecurityDescriptor->Control)) {
PISECURITY_DESCRIPTOR_RELATIVE RelSD =
(PISECURITY_DESCRIPTOR_RELATIVE)SecurityDescriptor;
if (Owner != NULL) {
*Owner =
((RelSD->Owner != 0) ? (PSID)((ULONG_PTR)RelSD + RelSD->Owner) : NULL);
}
if (Group != NULL) {
*Group =
((RelSD->Group != 0) ? (PSID)((ULONG_PTR)RelSD + RelSD->Group) : NULL);
}
if (Sacl != NULL) {
*Sacl = (((RelSD->Control & SE_SACL_PRESENT) && (RelSD->Sacl != 0))
? (PSID)((ULONG_PTR)RelSD + RelSD->Sacl)
: NULL);
}
if (Dacl != NULL) {
*Dacl = (((RelSD->Control & SE_DACL_PRESENT) && (RelSD->Dacl != 0))
? (PSID)((ULONG_PTR)RelSD + RelSD->Dacl)
: NULL);
}
} else {
if (Owner != NULL) {
*Owner = SecurityDescriptor->Owner;
}
if (Group != NULL) {
*Group = SecurityDescriptor->Group;
}
if (Sacl != NULL) {
*Sacl = ((SecurityDescriptor->Control & SE_SACL_PRESENT)
? SecurityDescriptor->Sacl
: NULL);
}
if (Dacl != NULL) {
*Dacl = ((SecurityDescriptor->Control & SE_DACL_PRESENT)
? SecurityDescriptor->Dacl
: NULL);
}
}
}
bool
get_owner_sd(PISECURITY_DESCRIPTOR SecurityDescriptor, OUT PSID *Owner)
{
/* RtlGetOwnerSecurityDescriptor is clean enough, so could be used
* without reentrancy risks instead of writing ours here
*/
if (SecurityDescriptor->Revision != SECURITY_DESCRIPTOR_REVISION1) {
return false;
}
get_sd_pointers(SecurityDescriptor, Owner, NULL, NULL, NULL);
return true;
}
void
initialize_security_descriptor(PISECURITY_DESCRIPTOR SecurityDescriptor)
{
SecurityDescriptor->Revision = SECURITY_DESCRIPTOR_REVISION1;
SecurityDescriptor->Sbz1 = 0;
/* note using absolute format, not SE_SELF_RELATIVE */
SecurityDescriptor->Control = 0;
SecurityDescriptor->Owner = NULL;
SecurityDescriptor->Group = NULL;
SecurityDescriptor->Sacl = NULL;
SecurityDescriptor->Dacl = NULL;
}
/* use only on security descriptors created with initialize_security_descriptor() */
bool
set_owner_sd(PISECURITY_DESCRIPTOR SecurityDescriptor, PSID Owner)
{
/* RtlGetOwnerSecurityDescriptor is clean enough, so could be used
* without reentrancy risks instead of writing ours here
*/
if (SecurityDescriptor->Revision != SECURITY_DESCRIPTOR_REVISION1) {
return false;
}
if (TEST(SE_SELF_RELATIVE, SecurityDescriptor->Control)) {
ASSERT(false && "we only create absolute security descriptors");
return false;
}
ASSERT(ALIGNED(SecurityDescriptor->Owner, sizeof(void *)));
SecurityDescriptor->Owner = Owner;
/* In case we are editing an existing SD makes remove possible tag
* that Owner field was provided with default or inheritance
* mechanisms.. Otherwise practically a nop for us when building
* an SD from scratch
*/
SecurityDescriptor->Control &= ~SE_OWNER_DEFAULTED;
return true;
}
static int
length_sid(IN PSID Sid_)
{
PISID Sid = Sid_;
/* we only know about usable length of SID */
return LengthRequiredSID(Sid->SubAuthorityCount);
}
bool
equal_sid(IN PSID Sid1_, IN PSID Sid2_)
{
PISID Sid1 = Sid1_;
PISID Sid2 = Sid2_;
/* note ntdll!RtlEqualSid returns BOOLEAN and so its result is
* just in AL! I don't want to deal with here after it got me
* once when assuming regular bool=int.
*
* ntdll!RtlEqualSid+0x2e:
* 7c91a493 32c0 xor al,al
* ...
* 7c91a498 c20800 ret 0x8
*/
/* preferred to reimplement based on reactos/0.2.x/lib/rtl/sid.c*/
SIZE_T SidLen;
if (Sid1->Revision != Sid2->Revision ||
Sid1->SubAuthorityCount != Sid2->SubAuthorityCount) {
return false;
}
SidLen = length_sid(Sid1);
return memcmp(Sid1, Sid2, SidLen) == 0;
}
#ifndef NOT_DYNAMORIO_CORE
/* To avoid any possible races, we ensure tbat the static buffers are
* initialized before we become multi-threaded via
* os_init->init_debugbox_title_buf() which calls these routines */
/* get application name, (cached), used for options, event logging and
* following children */
char *
get_application_name()
{
static char exename[MAXIMUM_PATH];
if (!exename[0]) {
snprintf(exename, BUFFER_SIZE_ELEMENTS(exename), "%ls", get_own_qualified_name());
NULL_TERMINATE_BUFFER(exename);
}
return exename;
}
const char *
get_application_short_name()
{
static char short_exename[MAXIMUM_PATH];
if (!short_exename[0]) {
snprintf(short_exename, BUFFER_SIZE_ELEMENTS(short_exename), "%ls",
get_own_short_qualified_name());
NULL_TERMINATE_BUFFER(short_exename);
}
return short_exename;
}
const char *
get_application_short_unqualified_name()
{
static char short_unqual_exename[MAXIMUM_PATH];
if (!short_unqual_exename[0]) {
snprintf(short_unqual_exename, BUFFER_SIZE_ELEMENTS(short_unqual_exename), "%ls",
get_own_short_unqualified_name());
NULL_TERMINATE_BUFFER(short_unqual_exename);
}
return short_unqual_exename;
}
/* get application pid, (cached), used for event logging */
char *
get_application_pid()
{
static char pidstr[16];
if (!pidstr[0]) {
process_id_t pid = get_process_id();
snprintf(pidstr, BUFFER_SIZE_ELEMENTS(pidstr), PIDFMT, pid);
NULL_TERMINATE_BUFFER(pidstr);
}
return pidstr;
}
#endif /* NOT_DYNAMORIO_CORE */
wchar_t *
get_process_param_buf(RTL_USER_PROCESS_PARAMETERS *params, wchar_t *buf)
{
#if !defined(NOT_DYNAMORIO_CORE_PROPER) && !defined(NOT_DYNAMORIO_CORE)
/* Many of the UNICODE_STRING.Buffer fields contain a relative offset
* from the start of ProcessParameters as set by the parent process,
* until the child's init updates it, on pre-Vista.
* Xref the adjustments done inside the routines here that read
* a child's params.
*/
if (dr_earliest_injected && get_os_version() < WINDOWS_VERSION_VISTA &&
/* sanity check: some may be real ptrs, such as Environment which
* we replaced from parent. the offsets should all be small, laid
* out after the param struct.
*/
(ptr_uint_t)buf < 64 * 1024) {
return (wchar_t *)((ptr_uint_t)buf + (ptr_uint_t)params);
} else
return buf;
#else
/* Shouldn't need this routine since shouldn't be reading own params, but
* rather than ifdef-ing out all callers we just make it work
*/
return buf;
#endif
}
wchar_t *
get_application_cmdline(void)
{
PEB *peb = get_own_peb();
return get_process_param_buf(peb->ProcessParameters,
peb->ProcessParameters->CommandLine.Buffer);
}
LONGLONG
query_time_100ns()
{
/* FIXME: we could use KUSER_SHARED_DATA here, but it's too volatile
* since we can't programmatically grab its address (all we know is
* 0x7ffe0000) and it changed on win2003 (tickcount deprecated, e.g.).
* Since these time routines aren't currently on critical path we just
* use the more-stable syscalls.
*/
LARGE_INTEGER systime;
GET_NTDLL(NtQuerySystemTime, (IN PLARGE_INTEGER SystemTime));
NtQuerySystemTime(&systime);
return systime.QuadPart;
}
uint64
query_time_micros()
{
LONGLONG time100ns = query_time_100ns();
return ((uint64)time100ns / TIMER_UNITS_PER_MICROSECOND);
}
uint64
query_time_millis()
{
LONGLONG time100ns = query_time_100ns();
return ((uint64)time100ns / TIMER_UNITS_PER_MILLISECOND);
}
uint
query_time_seconds()
{
/* ntdll provides RtlTimeToSecondsSince1970 but we've standardized on
* UTC so we just divide ourselves
*/
uint64 ms = query_time_millis();
return (uint)(ms / 1000);
}
/* uses convert_millis_to_date() in utils.c so core-only for simpler linking */
#if !defined(NOT_DYNAMORIO_CORE_PROPER) && !defined(NOT_DYNAMORIO_CORE)
/* note that ntdll!RtlTimeToTimeFields has this same functionality */
void
convert_100ns_to_system_time(uint64 time_in_100ns, SYSTEMTIME *st OUT)
{
LONGLONG time = time_in_100ns / TIMER_UNITS_PER_MILLISECOND;
dr_time_t dr_time;
convert_millis_to_date((uint64)time, &dr_time);
st->wYear = (WORD)dr_time.year;
st->wMonth = (WORD)dr_time.month;
st->wDayOfWeek = (WORD)dr_time.day_of_week;
st->wDay = (WORD)dr_time.day;
st->wHour = (WORD)dr_time.hour;
st->wMinute = (WORD)dr_time.minute;
st->wSecond = (WORD)dr_time.second;
st->wMilliseconds = (WORD)dr_time.milliseconds;
}
void
convert_system_time_to_100ns(const SYSTEMTIME *st, uint64 *time_in_100ns OUT)
{
uint64 time;
dr_time_t dr_time;
dr_time.year = st->wYear;
dr_time.month = st->wMonth;
dr_time.day_of_week = st->wDayOfWeek;
dr_time.day = st->wDay;
dr_time.hour = st->wHour;
dr_time.minute = st->wMinute;
dr_time.second = st->wSecond;
dr_time.milliseconds = st->wMilliseconds;
convert_date_to_millis(&dr_time, &time);
*time_in_100ns = time * TIMER_UNITS_PER_MILLISECOND;
}
void
query_system_time(SYSTEMTIME *st OUT)
{
convert_100ns_to_system_time(query_time_100ns(), st);
}
#endif
/* returns NULL (default security descriptor) if can't setup owner,
* otherwise edits in place the passed in security descriptor
*/
static PSECURITY_DESCRIPTOR
set_primary_user_owner(PSECURITY_DESCRIPTOR psd)
{
bool ok;
initialize_security_descriptor(psd);
/* for consistency, we override the NoDefaultAdminOwner feature
* which creates files with owner Administrators instead of current user
*/
/* note we could also just return a NULL SD, if TokenOwner == TokenUser
* and create an explicit one only if we really need it
*/
ok = set_owner_sd(psd, get_process_primary_SID());
ASSERT(ok);
if (!ok)
return NULL;
/* FIXME: (not verified) note that even if we set owner, we may
* not be allowed to use it as an owner it it is not present in
* the current token.
*/
/* we rely on the correct DACL to be provided through inheritance */
/* FIXME: we don't specify primary Group, we may end up with no primary group,
* which should be OK too */
return psd; /* use the constructed security descriptor */
}
/* Exposes full power of NtCreateFile. Caller should first consider
* create_file() or nt_create_module_file() before calling this
* routine directly. See comments above nt_create_module_file() for
* more details on some of these arguments.
*
* Note that instead of asking for raw OBJECT_ATTRIBUTES we have
* enriched the NT interface with a directory handle and an additional
* disposition FILE_DISPOSITION_SET_OWNER.
*/
NTSTATUS
nt_create_file(OUT HANDLE *file_handle, const wchar_t *filename,
HANDLE dir_handle OPTIONAL, size_t alloc_size, ACCESS_MASK rights,
uint attributes, uint sharing, uint create_disposition,
uint create_options)
{
NTSTATUS res;
OBJECT_ATTRIBUTES file_attributes;
IO_STATUS_BLOCK iob = { 0, 0 };
UNICODE_STRING file_path_unicode;
SECURITY_DESCRIPTOR sd;
PSECURITY_DESCRIPTOR pSD = NULL; /* default security descriptor */
LARGE_INTEGER create_allocation_size;
create_allocation_size.QuadPart = alloc_size;
res = wchar_to_unicode(&file_path_unicode, filename);
if (!NT_SUCCESS(res)) {
NTPRINT("nt_create_file: name conversion failed, res: %x\n", res);
return res;
}
if (TEST(FILE_DISPOSITION_SET_OWNER, create_disposition)) {
pSD = set_primary_user_owner(&sd);
create_disposition &= ~FILE_DISPOSITION_SET_OWNER;
}
InitializeObjectAttributes(&file_attributes, &file_path_unicode, OBJ_CASE_INSENSITIVE,
dir_handle, pSD);
ASSERT(create_disposition <= FILE_MAXIMUM_DISPOSITION);
res = NT_SYSCALL(CreateFile, file_handle, rights, &file_attributes, &iob,
(alloc_size == 0 ? NULL : &create_allocation_size), attributes,
sharing, create_disposition, create_options, NULL, 0);
if (!NT_SUCCESS(res)) {
NTPRINT("Error 0x%x in nt_create_file %S \"%S\"\n", res, filename,
file_path_unicode.Buffer);
}
return res;
}
/* For ordinary use of NtCreateFile */
/* FIXME : can't simultaneously have GENERIC_READ, GENERIC_WRITE and SYNCH_IO
* get invalid parameter error, but any two succeeds, makes sense because
* <speculation> SYNCH_IO tells the io system to keep track of the
* current file postion which should start at 0 for read and end of file for
* write </speculation>, could do non_synch_io but had trouble getting that to
* work with read/write */
HANDLE
create_file(PCWSTR filename, bool is_dir, ACCESS_MASK rights, uint sharing,
uint create_disposition, bool synch)
{
NTSTATUS res;
HANDLE hfile;
DEBUG_DECLARE(static const uint access_allow = READ_CONTROL | GENERIC_READ |
GENERIC_WRITE | GENERIC_EXECUTE | FILE_GENERIC_READ |
FILE_GENERIC_WRITE | FILE_GENERIC_EXECUTE;)
DEBUG_DECLARE(static const uint dir_access_allow = READ_CONTROL | 0;)
/* FIXME : only support these possibilities for access mask for now
* should be all we need unless we decide to export more functionality
* from os_open/write/read */
ASSERT((synch &&
((!is_dir && ((rights & (~access_allow)) == 0)) ||
(is_dir && ((rights & (~dir_access_allow)) == 0)))) ||
(!synch && !is_dir && (GENERIC_READ | GENERIC_WRITE) == rights));
res = nt_create_file(&hfile, filename, NULL, 0,
rights | SYNCHRONIZE |
(is_dir ? FILE_LIST_DIRECTORY : FILE_READ_ATTRIBUTES),
/* CreateDirectory uses F_ATTRIB_NORM too, even though
* there is a F_ATTRIB_DIR as well */
FILE_ATTRIBUTE_NORMAL, sharing, create_disposition,
(synch ? FILE_SYNCHRONOUS_IO_NONALERT : 0) |
/* FIXME: MSDN instructs to use FILE_FLAG_BACKUP_SEMANTICS
* for opening a dir handle but we don't seem to need it */
(is_dir ? FILE_DIRECTORY_FILE | FILE_OPEN_FOR_BACKUP_INTENT
: FILE_NON_DIRECTORY_FILE));
if (!NT_SUCCESS(res))
return INVALID_FILE;
else
return hfile;
}
#if !defined(NOT_DYNAMORIO_CORE_PROPER) && !defined(NOT_DYNAMORIO_CORE)
NTSTATUS
nt_open_file(HANDLE *handle OUT, PCWSTR filename, ACCESS_MASK rights, uint sharing,
uint options)
{
NTSTATUS res;
OBJECT_ATTRIBUTES oa;
IO_STATUS_BLOCK iob = { 0, 0 };
UNICODE_STRING us;
res = wchar_to_unicode(&us, filename);
if (!NT_SUCCESS(res))
return res;
InitializeObjectAttributes(&oa, &us, OBJ_CASE_INSENSITIVE, NULL, NULL);
res = nt_raw_OpenFile(handle, rights | SYNCHRONIZE, &oa, &iob, sharing,
FILE_SYNCHRONOUS_IO_NONALERT | options);
return res;
}
#endif
NTSTATUS
nt_delete_file(PCWSTR nt_filename)
{
/* We follow the lead of Win32 and use FileDispositionInformation
* and not NtDeleteFile.
*/
/* Xref os_delete_mapped_file() which does more: but here we want
* to match something more like Win32 DeleteFile().
*/
NTSTATUS res;
HANDLE hf;
FILE_DISPOSITION_INFORMATION file_dispose_info;
res = nt_create_file(&hf, nt_filename, NULL, 0, SYNCHRONIZE | DELETE,
FILE_ATTRIBUTE_NORMAL,
FILE_SHARE_DELETE | /* if already deleted */
FILE_SHARE_READ,
FILE_OPEN,
FILE_SYNCHRONOUS_IO_NONALERT |
FILE_DELETE_ON_CLOSE
/* This should open a handle on a symlink rather
* than its target, and avoid other reparse code.
* Otherwise the FILE_DELETE_ON_CLOSE would cause
* us to delete the target of a symlink!
* FIXME: fully test this: case 10067
*/
| FILE_OPEN_REPARSE_POINT);
if (!NT_SUCCESS(res))
return res;
file_dispose_info.DeleteFile = TRUE;
res = nt_set_file_info(hf, &file_dispose_info, sizeof(file_dispose_info),
FileDispositionInformation);
/* close regardless of success */
close_handle(hf);
return res;
}
NTSTATUS
nt_flush_file_buffers(HANDLE file_handle)
{
IO_STATUS_BLOCK ret;
GET_NTDLL(NtFlushBuffersFile,
(IN HANDLE FileHandle, OUT PIO_STATUS_BLOCK IoStatusBlock));
return NtFlushBuffersFile(file_handle, &ret);
}
bool
read_file(HANDLE file_handle, void *buffer, uint num_bytes_to_read,
IN uint64 *file_byte_offset OPTIONAL, OUT size_t *num_bytes_read)
{
NTSTATUS res;
IO_STATUS_BLOCK ret = { 0 };
LARGE_INTEGER ByteOffset; /* should be the same as uint64 */
if (file_byte_offset != NULL) {
ByteOffset.QuadPart = *file_byte_offset;
}
/* if file is opened with FILE_SYNCHRONOUS_IO_[NON]ALERT then can pass
* NULL for ByteOffset to read from current file positions, otherwise
* need to pass special value to ByteOffset to read from current position
* (special value is highpart -1, low part FILE_USE_FILE_POINTER_POSITION),
* but I can't get this to work so assuming opened with SYNCH_IO */
res = NtReadFile(file_handle, NULL, NULL, NULL, &ret, buffer, num_bytes_to_read,
file_byte_offset != NULL ? &ByteOffset : NULL, NULL);
*num_bytes_read = ret.Information;
return NT_SUCCESS(res);
}
bool
write_file(HANDLE file_handle, const void *buffer, uint num_bytes_to_write,
OPTIONAL uint64 *file_byte_offset, OUT size_t *num_bytes_written)
{
NTSTATUS res;
IO_STATUS_BLOCK ret = { 0 };
LARGE_INTEGER ByteOffset;
if (file_byte_offset != NULL) {
ByteOffset.QuadPart = *file_byte_offset;
}
/* if file is opened with FILE_SYNCHRONOUS_IO_[NON]ALERT then can pass
* NULL for ByteOffset to append to end (well append to after the last
* write or end if file just opened), otherwise need to pass special value
* to ByteOffset to append, unless opened with just append permissions in
* which case always appends (special value is highpart -1, low part
* FILE_WRITE_TO_END_OF_FILE for middle case), but I can't get this to
* work so assuming opened with FILE_SYNCHRONOUS_IO_* */
res = NtWriteFile(file_handle, NULL, NULL, NULL, &ret, buffer, num_bytes_to_write,
file_byte_offset != NULL ? &ByteOffset : NULL, NULL);
*num_bytes_written = ret.Information;
return NT_SUCCESS(res);
}
bool
close_file(HANDLE hfile)
{
return close_handle(hfile);
}
HANDLE
create_iocompletion()
{
NTSTATUS res;
HANDLE hiocompletion;
GET_NTDLL(NtCreateIoCompletion,
(OUT PHANDLE IoCompletionHandle, IN ACCESS_MASK DesiredAccess,
IN POBJECT_ATTRIBUTES ObjectAttributes,
IN ULONG NumberOfConcurrentThreads));
res = NtCreateIoCompletion(&hiocompletion, EVENT_ALL_ACCESS /* 0x1f0003 */,
NULL /* no name */,
0 /* FIXME: 0 observed, shouldn't it be 1? */);
if (!NT_SUCCESS(res)) {
NTPRINT("Error 0x%x in create IoCompletion \n", res);
return NULL;
} else
return hiocompletion;
}
typedef struct _FILE_PIPE_INFORMATION { // Information Class 23
ULONG ReadModeMessage;
ULONG WaitModeBlocking;
} FILE_PIPE_INFORMATION, *PFILE_PIPE_INFORMATION;
typedef struct _FILE_COMPLETION_INFORMATION { // Information Class 30
HANDLE IoCompletionHandle;
ULONG CompletionKey;
} FILE_COMPLETION_INFORMATION, *PFILE_COMPLETION_INFORMATION;
/* Takes a pipename, and an optional IoCompletion object */
HANDLE
open_pipe(PCWSTR pipename, HANDLE hsync)
{
NTSTATUS res;
HANDLE h;
IO_STATUS_BLOCK iob;
FILE_PIPE_INFORMATION pipeinfo = { 1 /* message */, 0 /* no wait*/ };
/* setting this to wait doesn't work */
// CHECK: object attributes we see in RegisterEventSource // 1242580, "name"
h = create_file(pipename, false, GENERIC_WRITE | GENERIC_READ, FILE_SHARE_READ,
FILE_OPEN, false);
if (h == INVALID_FILE)
return NULL;
/* FIXME: call nt_set_file_info */
res = NT_SYSCALL(SetInformationFile, h, &iob, &pipeinfo, sizeof(pipeinfo),
FilePipeInformation);
if (!NT_SUCCESS(res)) {
/* FIXME: get __FUNCTION__ working for windows */
NTPRINT("Error 0x%x in %s:%d\n", res, __FILE__, __LINE__);
return NULL;
}
/* CHECK: How should synchronization work here; all I want is blocking I/O
then we'd skip this step, (yet we fail with FILE_SYNCHRONOUS_IO_NONALERT) */
/* set FileCompletionInformation just like RegisterSource does
FIXME: The problem is that the IoCompletion that is used here is not created
by RegisterSource and instead an earlier one is used.
FIXME: There is a NtCreateEvent call, but that is what should go in
NtFsControlFile calls, and I can't match how that handle gets used either.
*/
if (hsync) {
FILE_COMPLETION_INFORMATION completioninfo;
completioninfo.IoCompletionHandle = hsync;
completioninfo.CompletionKey = 0xffff0000; /* observed key */
/* FIXME: call nt_set_file_info */
res = NT_SYSCALL(SetInformationFile, h, &iob, &completioninfo,
sizeof(completioninfo), FileCompletionInformation);
if (!NT_SUCCESS(res)) {
/* FIXME: get __FUNCTION__ working for windows */
NTPRINT("Error 0x%x in %s:%d\n", res, __FILE__, __LINE__);
return NULL;
}
}
return h;
}
/* see example in Nebbett p. 419 */
/* status codes ntstatus.h (arg 1), also includes descriptions of expected
* arguments which must match the actual arguments described by args 2-4
* (which are just for packaging), (i.e the status code defines the format
* string), note that many status codes won't produce message box
* arg 2 is number of substitutions,
* arg 3 is a mask of what substitutions are pointers (i.e. strings), i.e. if
* substitutions 2 and 4 are strings then the 2nd and 4th bits will be set and
* will get 1010 or 10
* arg 4 is an array of ULONGS comprimising the substitutions (ULONG will be
* interpreted as pointer as defined by arg 3)
* arg5 is response options, eqv. of MB_OK, MB_YESNO etc, see Nebbet enum 418
* (1 is OK)
* arg 6 is return value from box, see Nebbet enum 418 */
/* bad news is that the following is somewhat brittle, the format changed
* between win2k and XP substantially (though in a forward, but not backwards
* compatible way). The following uses the format for XP since that works for
* win2k too, but the reverse is not true. On both platforms
* ServiceMessageBox (what we use, probably because of service notification
* flag?) uses the undocumented status code 0x50000018L. On win2k a three
* element array with first being the msg string, the second being the title
* and the third element being 0x10 (which seems to be ignored) is used and
* the MsgBoxType arg specifies the msg box and buttons shown. On XP a four
* element array with the first element being the msg string,
* the second being the title, the third being 0x10 (which controls the msg
* box and buttons shown), and the fourth being 0xffffffffL (seems to be
* ignored) is used and the MsgBoxType arg seems to be ignored. Also
* having the wrong arguments for RaiseHardError can leave the machine in a
* bad state. The offending thread will hang at the syscall and (if for ex.
* you use the 2k form on XP) the machine can be left in a state where it is
* unable to display any message box from any process (any thread that tries
* just hangs). At one point had to power cycle the machine since couldn't
* shut down or get task manager to appear. But following seems to work.
*/
#define STATUS_SHOW_MESSAGEBOX_UNDOCUMENTED (NTSTATUS)0x50000018L
bool
nt_messagebox(const wchar_t *msg, const wchar_t *title)
{
UNICODE_STRING m, t;
NTSTATUS res;
GET_NTDLL(NtRaiseHardError,
(IN NTSTATUS ErrorStatus, IN ULONG NumberOfArguments,
/* FIXME: ReactOS claims this is a PUNICODE_STRING */
IN ULONG UnicodeStringArgumentsMask, IN PVOID Arguments,
IN ULONG MessageBoxType, /* HARDERROR_RESPONSE_OPTION */
OUT PULONG MessageBoxResult));
/* the 0xfff... is only for XP, win2k has three element args array, its
* function is unknown (doesn't seem to matter what is there) */
/* the 0x10 argument is ignored ? on win2k, on XP chooses the icon and
* response options of the resulting dialog box */
ULONG ret;
void *args[] = { NULL, NULL, (void *)(ptr_uint_t)0x10L, (void *)PTR_UINT_MINUS_1 };
/* make UNICODE_STRINGs */
res = wchar_to_unicode(&m, msg);
ASSERT(NT_SUCCESS(res));
if (!NT_SUCCESS(res))
return NT_SUCCESS(res);
res = wchar_to_unicode(&t, title);
ASSERT(NT_SUCCESS(res));
if (!NT_SUCCESS(res))
return NT_SUCCESS(res);
args[0] = (void *)&m;
args[1] = (void *)&t;
/* see notes above */
/* 4 = length of args, set to 3 to match native behavior on win2k */
/* 1 is OptionOK dialog for win2k, but is ignored ? on XP */
res = NtRaiseHardError(STATUS_SHOW_MESSAGEBOX_UNDOCUMENTED, 4, 0x1 | 0x2, args, 1,
&ret);
return NT_SUCCESS(res);
}
bool
nt_raise_exception(EXCEPTION_RECORD *pexcrec, CONTEXT *pcontext)
{
NTSTATUS res;
GET_NTDLL(NtRaiseException,
(IN PEXCEPTION_RECORD ExceptionRecord, IN PCONTEXT Context,
IN BOOLEAN SearchFrames));
res = NtRaiseException(pexcrec, pcontext, true);
/* we just threw an exception, shouldn't get here */
ASSERT_NOT_REACHED();
return NT_SUCCESS(res);
}
HANDLE
nt_create_event(EVENT_TYPE event_type)
{
NTSTATUS res;
HANDLE hevent;
GET_NTDLL(NtCreateEvent,
(OUT PHANDLE EventHandle, IN ACCESS_MASK DesiredAccess,
IN POBJECT_ATTRIBUTES ObjectAttributes, IN EVENT_TYPE EventType,
IN BOOLEAN InitialState));
res = NtCreateEvent(&hevent, EVENT_ALL_ACCESS, NULL /* no name */, event_type,
0 /* start non-signaled */);
if (!NT_SUCCESS(res)) {
NTPRINT("Error 0x%x in create event \n", res);
return NULL;
} else
return hevent;
}
void
nt_close_event(HANDLE hevent)
{
close_handle(hevent);
}
wait_status_t
nt_wait_event_with_timeout(HANDLE hevent, PLARGE_INTEGER timeout)
{
NTSTATUS res;
/* i#4075: We use a raw syscall to keep the PC in dynamorio.dll for
* os_take_over_all_unknown_threads() and synch_with_* routines to more
* easily identify a thread in DR code. In particular this is required to
* avoid a double takeover on a race between intercept_new_thread() and
* os_take_over_all_unknown_threads().
*/
GET_RAW_SYSCALL(WaitForSingleObject, IN HANDLE ObjectHandle, IN BOOLEAN Alertable,
IN PLARGE_INTEGER TimeOut);
res = NT_SYSCALL(WaitForSingleObject, hevent, false /* not alertable */, timeout);
if (!NT_SUCCESS(res))
return WAIT_ERROR;
if (res == STATUS_TIMEOUT)
return WAIT_TIMEDOUT;
return WAIT_SIGNALED;
}
void
nt_set_event(HANDLE hevent)
{
GET_NTDLL(NtSetEvent, (IN HANDLE EventHandle, OUT PLONG PreviousState OPTIONAL));
NTSTATUS res;
res = NtSetEvent(hevent, NULL /* no previous */);
/* on WinXP critical sections use ZwSetEventBoostPriority, yet
Inside Win2k p.362 claims we always get a boost on Win2000 */
#if VERBOSE
if (!NT_SUCCESS(res)) {
NTPRINT("Error 0x%x in set event \n", res);
}
#endif
}
/* This is currently used only for manual broadcast events
* It looks like NtPulseEvent will not be a good idea.
* MSDN says that PulseEvent is bad because of kernel APCs
* taking a thread out of the wait queue. If it was only user APCs
* we wouldn't have to worry about it. However, MSDN should have said that
* non-alertable waits will not be affected, instead they say don't use it.
* Therefore we are stuck with manual event handling.
*/
void
nt_clear_event(HANDLE hevent)
{
GET_NTDLL(NtClearEvent, (IN HANDLE EventHandle));
NTSTATUS res;
res = NtClearEvent(hevent);
#if VERBOSE
if (!NT_SUCCESS(res)) {
NTPRINT("Error 0x%x in clear event \n", res);
}
#endif
}
void
nt_signal_and_wait(HANDLE hevent_to_signal, HANDLE hevent_to_wait)
{
GET_NTDLL(NtSignalAndWaitForSingleObject,
(IN HANDLE ObjectToSignal, IN HANDLE WaitableObject, IN BOOLEAN Alertable,
IN PLARGE_INTEGER Time OPTIONAL));
NTSTATUS res;
res =
NtSignalAndWaitForSingleObject(hevent_to_signal, hevent_to_wait,
false /* not alertable */, NULL /* no timeout */);
#if VERBOSE
if (!NT_SUCCESS(res)) {
NTPRINT("Error 0x%x in set event \n", res);
}
#endif
}
void
nt_query_performance_counter(PLARGE_INTEGER counter, PLARGE_INTEGER frequency)
{
GET_NTDLL(NtQueryPerformanceCounter,
(OUT PLARGE_INTEGER PerformanceCount,
OUT PLARGE_INTEGER PerformanceFrequency OPTIONAL));
NTSTATUS res;
res = NtQueryPerformanceCounter(counter, frequency);
#if VERBOSE
if (!NT_SUCCESS(res)) {
NTPRINT("Error 0x%x in query_performance_counter \n", res);
}
#endif
ASSERT(NT_SUCCESS(res));
}
/* Pipe transceive macros and types */
/* macros from WinIoCtl.h */
#define CTL_CODE(DeviceType, Function, Method, Access) \
(((DeviceType) << 16) | ((Access) << 14) | ((Function) << 2) | (Method))
// Define the method codes for how buffers are passed for I/O and FS controls
#define METHOD_BUFFERED 0
#define METHOD_IN_DIRECT 1
#define METHOD_OUT_DIRECT 2
#define METHOD_NEITHER 3
// Define the access check value for any access
#define FILE_READ_ACCESS (0x0001) // file & pipe
#define FILE_WRITE_ACCESS (0x0002) // file & pipe
#define FSCTL_PIPE_TRANSCEIVE \
CTL_CODE(FILE_DEVICE_NAMED_PIPE, 5, METHOD_NEITHER, \
FILE_READ_DATA | FILE_WRITE_DATA) /* 0x11c017 */
#ifdef DEBUG
# if defined(NOT_DYNAMORIO_CORE_PROPER) || defined(NOT_DYNAMORIO_CORE)
static bool do_once_nt_pipe_transceive = false;
# else
DECLARE_FREQPROT_VAR(static bool do_once_nt_pipe_transceive, false);
# endif
#endif
/* read/write from a pipe. Returns length of output if successful
* 0 on failure */
size_t
nt_pipe_transceive(HANDLE hpipe, void *input, uint input_size, void *output,
uint output_size, uint timeout_ms)
{
LARGE_INTEGER liDueTime;
NTSTATUS res;
IO_STATUS_BLOCK iob = { 0, 0 };
/* NOTE use an event => asynch IO, if event caller will be notified
* that routine finishes by signaling the event */
/* FIXME shared utility for this style of computation,
* is used in several places in os.c */
liDueTime.QuadPart = -((int)timeout_ms * TIMER_UNITS_PER_MILLISECOND);
ASSERT(hpipe);
res = NtFsControlFile(hpipe, NULL, NULL, NULL, &iob, FSCTL_PIPE_TRANSCEIVE, input,
input_size, output, output_size);
/* make sure that I/O is complete before we go back to the client
- otherwise we may corrupt the stack if output is a stack allocated buffer */
if (NT_SUCCESS(res)) {
/* it worked, check if we need to wait for the IO to finish */
if (res == STATUS_PENDING) {
/* we need to wait on the pipe handle */
/* ref case 666, sometimes when we are in services.exe this wait
* can hang (presumably this thread is needed on the other side
* of the pipe or something like that) so we timeout the wait */
/* name is a bit misleading (pipe vs event), but does the
* right thing */
res = nt_wait_event_with_timeout(hpipe, &liDueTime);
if (res == WAIT_TIMEDOUT) {
/* CancelIO is wrapper for NtCancelIO, msdn claims only works
* on asynch IO, but as they point out it shouldn't be possible
* to use it on synch IO (the routine shouldn't return for you
* to cancel). Still not sure why the Fs... returns when synch
* IO. Try to cancel, we may have to eventually go to quasi
* asynch IO though this appears to work. */
/* pipe == file */
GET_NTDLL(NtCancelIoFile,
(IN HANDLE FileHandle, OUT PIO_STATUS_BLOCK IoStatusBlock));
IO_STATUS_BLOCK cancel_iob;
NTLOG(GLOBAL, LOG_NT, 1, "pipe transceive timed out\n");
NTLOG(THREAD_GET, LOG_NT, 1, "pipe transceive timed out\n");
res = NtCancelIoFile(hpipe, &cancel_iob);
if (!NT_SUCCESS(res)) {
/* check, maybe finished before we could cancel (if so
* our timeout was too short) */
NTLOG(GLOBAL, LOG_NT, 1,
"pipe transceive cancel failed code=" PFX "\n", res);
NTLOG(THREAD_GET, LOG_NT, 1,
"pipe transceive cancel failed code=" PFX "\n", res);
res = nt_wait_event_with_timeout(hpipe, &liDueTime);
if (res == WAIT_TIMEDOUT) {
/* Now we are in a world of hurt, just return and hope
* for the best */
NTLOG(GLOBAL, LOG_NT, 1, "pipe transceive 2nd try FAILED!\n");
NTLOG(THREAD_GET, LOG_NT, 1, "pipe transceive 2nd try FAILED!\n");
/* DO_ONCE to avoid an infinite recursion here */
DOCHECK(1, {
/* custom DO_ONCE to avoid selfprot link issues with
* NOT_DYNAMORIO_CORE_PROPER
*/
if (!do_once_nt_pipe_transceive) {
do_once_nt_pipe_transceive = true;
ASSERT_NOT_REACHED();
}
});
return 0;
}
} else {
NTLOG(GLOBAL, LOG_NT, 1,
"pipe transceive cancel succeeded code=" PFX "\n", res);
NTLOG(THREAD_GET, LOG_NT, 1,
"pipe transceive cancel succeeded code=" PFX "\n", res);
return 0;
}
}
} else {
/* completed synchronously (success) */
NTLOG(GLOBAL, LOG_NT, 1, "pipe transceive completed sync\n");
NTLOG(THREAD_GET, LOG_NT, 1, "pipe transceive completed sync\n");
}
} else {
NTLOG(GLOBAL, LOG_NT, 1, "pipe transceive fail\n");
NTLOG(THREAD_GET, LOG_NT, 1, "pipe transceive fail\n");
return 0;
}
/* length of output */
return iob.Information;
};
#ifdef PURE_NTDLL
/* FIXME: The following should be pure ntdll.dll replacements of kernel32.dll */
/* FIXME: Currently kernel32 counterparts are used */
/* FIXME: Impersonation needs to be handled */
typedef struct _THREAD_IMPERSONATION_INFORMATION {
HANDLE ThreadImpersonationToken;
} THREAD_IMPERSONATION_INFORMATION, *PTHREAD_IMPERSONATION_INFORMATION;
/* gets a handle to thread impersonation token, returns NULL on failure */
static HANDLE
get_thread_impersonation_token(HANDLE hthread)
{
NTSTATUS res;
HANDLE htoken;
ACCESS_MASK rights = 0XC; /* CHECK */
res = NtOpenThreadToken(hthread, rights, true /* as self */, &htoken);
if (!NT_SUCCESS(res)) {
NTPRINT("Error 0x%x in get thread token\n", res);
return NULL;
} else
return htoken;
}
/* sets impersonation token, returns 0 on failure */
static bool
set_thread_impersonation_token(HANDLE hthread, HANDLE himptoken)
{
NTSTATUS res;
THREAD_IMPERSONATION_INFORMATION imp_info = { himptoken };
res = nt_raw_SetInformationThread(hthread, ThreadImpersonationToken, &imp_info,
sizeof(imp_info));
if (!NT_SUCCESS(res)) {
NTPRINT("Error 0x%x in set thread token\n", res);
return false;
} else
return true;
}
#endif /* PURE_NTDLL */
#ifdef WINDOWS_PC_SAMPLE
/* for profiling */
/* buffer size is in bytes, buffer_size >= 4 * (size / 2^shift <rounded up>) */
HANDLE
nt_create_profile(HANDLE process_handle, void *start, uint size, uint *buffer,
uint buffer_size, uint shift)
{
NTSTATUS res;
HANDLE prof_handle;
GET_NTDLL(NtCreateProfile,
(OUT PHANDLE ProfileHandle, IN HANDLE ProcessHandle, IN PVOID Base,
IN ULONG Size, IN ULONG BucketShift, IN PULONG Buffer,
IN ULONG BufferLength, IN KPROFILE_SOURCE Source, IN ULONG ProcessorMask));
/* there are restrictions on shift, check FIXME */
res = NtCreateProfile(&prof_handle, process_handle, start, size, shift,
(ULONG *)buffer, buffer_size, ProfileTime, 0);
ASSERT(NT_SUCCESS(res));
return prof_handle;
}
void
nt_set_profile_interval(uint nanoseconds)
{
NTSTATUS res;
GET_NTDLL(NtSetIntervalProfile, (IN ULONG Interval, IN KPROFILE_SOURCE Source));
res = NtSetIntervalProfile(nanoseconds, ProfileTime);
ASSERT(NT_SUCCESS(res));
}
int
nt_query_profile_interval()
{
NTSTATUS res;
ULONG interval;
GET_NTDLL(NtQueryIntervalProfile, (IN KPROFILE_SOURCE Source, OUT PULONG Interval));
res = NtQueryIntervalProfile(ProfileTime, &interval);
ASSERT(NT_SUCCESS(res));
return interval;
}
void
nt_start_profile(HANDLE profile_handle)
{
NTSTATUS res;
GET_NTDLL(NtStartProfile, (IN HANDLE ProfileHandle));
res = NtStartProfile(profile_handle);
ASSERT(NT_SUCCESS(res));
}
void
nt_stop_profile(HANDLE profile_handle)
{
NTSTATUS res;
GET_NTDLL(NtStopProfile, (IN HANDLE ProfileHandle));
res = NtStopProfile(profile_handle);
ASSERT(NT_SUCCESS(res));
}
#endif
/****************************************************************************
* These process creation routines are based on Nebbett example 6.2
*/
typedef struct _PORT_MESSAGE {
USHORT DataSize;
USHORT MessageSize;
USHORT MessageType;
USHORT VirtualRangesOffset;
CLIENT_ID ClientId;
ULONG MessageId;
ULONG SectionSize;
// UCHAR Data[];
} PORT_MESSAGE, *PPORT_MESSAGE;
typedef struct _CSRSS_MESSAGE {
ULONG Unknown1;
ULONG Opcode;
ULONG Status;
ULONG Unknown2;
} CSRSS_MESSAGE, *PCSRSS_MESSAGE;
/* N.B.: we now rely on this Csr routine, it works on 2K, XP, and 2003, let's
* hope it doesn't change in the future
*/
static int
inform_csrss(HANDLE hProcess, HANDLE hthread, process_id_t pid, thread_id_t tid)
{
GET_NTDLL(CsrClientCallServer,
(IN OUT PVOID Message, IN PVOID, IN ULONG Opcode, IN ULONG Size));
/* We pass a layered message with two headers to csrss.
* However, the two headers, PORT_MESSAGE and CSRSS_MESSAGE, are OUT values,
* not IN at all. CsrClientCallServer fills in the first 4 fields of
* PORT_MESSAGE and the first 2 fields of CSRSS_MESSAGE.
* It adds 0x10, the size of CSRSS_MESSAGE, to the size passed in when
* it passes this buffer to NtRequestWaitReplyPort, as everything after
* PORT_MESSAGE is data for the LPC to csrss.
* Coming out, everything is now filled in except the final field of CSRSS_MESSAGE.
* The CreateProcessInternalW code that calls CsrClientCallServer pushes
* the opcode and the size as immediates so this is all known at compile time.
*/
struct {
PORT_MESSAGE PortMessage; /* port header */
/* port data follows */
CSRSS_MESSAGE CsrssMessage; /* csrss header */
/* csrss data follows */
PROCESS_INFORMATION ProcessInformation;
CLIENT_ID Debugger;
ULONG CreationFlags;
ULONG VdmInfo[2];
/* the above csrss data fields (size 0x24) are all that's passed to NT,
* but other platforms have more, always observed to be 0, max of 0x98 on XP:
*/
ULONG Unknown[0x98 - 0x24];
} csrmsg = { { 0 }, { 0 }, { hProcess, hthread, (DWORD)pid, (DWORD)tid }, { 0 }, 0,
{ 0 }, { 0 } };
uint size = 0x24;
PEB *peb = get_own_peb();
/* Note the discrepancy: CLIENT_ID and PROCESS_BASIC_INFORMATION use
* HANDLE or ULONG_PTR for the ids, but here we have DWORD, and
* Windows API routines like kernel32!GetProcessId return DWORD.
*/
IF_X64(ASSERT(CHECK_TRUNCATE_TYPE_uint(pid)));
IF_X64(ASSERT(CHECK_TRUNCATE_TYPE_uint(tid)));
if (peb->OSMajorVersion == 4)
size = 0x24; /* NT */
else {
ASSERT(peb->OSMajorVersion == 5);
if (peb->OSMinorVersion == 0)
size = 0x28; /* 2000 */
else if (peb->OSMinorVersion == 1)
size = 0x98; /* XP */
else if (peb->OSMinorVersion == 2)
size = 0x90; /* 2003 */
}
return NT_SUCCESS(CsrClientCallServer(&csrmsg, 0, 0x10000, size));
}
static wchar_t *
copy_environment(HANDLE hProcess)
{
/* this is precisely what KERNEL32!GetEnvironmentStringsW returns: */
wchar_t *env = (wchar_t *)get_process_param_buf(
get_own_peb()->ProcessParameters, get_own_peb()->ProcessParameters->Environment);
SIZE_T n;
SIZE_T m;
void *p;
for (n = 0; env[n] != 0; n += wcslen(env + n) + 1)
;
n *= sizeof(*env);
m = n;
p = NULL;
if (!NT_SUCCESS(NT_SYSCALL(AllocateVirtualMemory, hProcess, &p, 0, &m, MEM_COMMIT,
PAGE_READWRITE)))
return NULL;
if (!nt_write_virtual_memory(hProcess, p, env, n, 0))
return NULL;
return (wchar_t *)p;
}
static NTSTATUS
create_process_parameters(HANDLE hProcess, PEB *peb, UNICODE_STRING *imagefile,
UNICODE_STRING *cmdline)
{
RTL_USER_PROCESS_PARAMETERS *pp;
SIZE_T n;
void *p;
GET_NTDLL(RtlCreateProcessParameters,
(OUT PRTL_USER_PROCESS_PARAMETERS * ProcParams,
IN PUNICODE_STRING ImageFile, IN PUNICODE_STRING DllPath OPTIONAL,
IN PUNICODE_STRING CurrentDirectory OPTIONAL,
IN PUNICODE_STRING CommandLine OPTIONAL, IN ULONG CreationFlags,
IN PUNICODE_STRING WindowTitle OPTIONAL,
IN PUNICODE_STRING Desktop OPTIONAL, IN PUNICODE_STRING Reserved OPTIONAL,
IN PUNICODE_STRING Reserved2 OPTIONAL));
GET_NTDLL(RtlDestroyProcessParameters, (IN PRTL_USER_PROCESS_PARAMETERS ProcParams));
RtlCreateProcessParameters(&pp, imagefile, 0, 0, cmdline, 0, 0, 0, 0, 0);
pp->Environment = copy_environment(hProcess);
if (pp->Environment == NULL)
return 0;
n = pp->Length;
p = NULL;
if (!NT_SUCCESS(NT_SYSCALL(AllocateVirtualMemory, hProcess, &p, 0, &n, MEM_COMMIT,
PAGE_READWRITE)))
return 0;
if (!nt_write_virtual_memory(hProcess, p, pp, pp->Length, 0))
return 0;
/* update the pointer in child's PEB */
if (!nt_write_virtual_memory(hProcess, &peb->ProcessParameters, &p, sizeof(void *),
0))
return 0;
if (!NT_SUCCESS(RtlDestroyProcessParameters(pp)))
return 0;
return 1;
}
/* avoid needing x86_code.c from x86.asm from get_own_context_helper() */
#if !defined(NOT_DYNAMORIO_CORE) && !defined(NOT_DYNAMORIO_CORE_PROPER)
/* Executable name must be in kernel object name form
* (e.g., \SystemRoot\System32\notepad.exe, or \??\c:\foo\bar.exe)
* The executable name on the command line can be in any form.
* On success returns a handle for the child
* On failure returns INVALID_HANDLE_VALUE
*/
HANDLE
create_process(wchar_t *exe, wchar_t *cmdline)
{
UNICODE_STRING uexe;
UNICODE_STRING ucmdline;
HANDLE hProcess = INVALID_HANDLE_VALUE;
HANDLE hthread = INVALID_HANDLE_VALUE;
HANDLE hSection = INVALID_HANDLE_VALUE;
HANDLE hFile = INVALID_HANDLE_VALUE;
OBJECT_ATTRIBUTES oa;
IO_STATUS_BLOCK iosb;
SECTION_IMAGE_INFORMATION sii;
thread_id_t tid;
PROCESS_BASIC_INFORMATION pbi;
GET_NTDLL(NtCreateProcess,
(OUT PHANDLE ProcessHandle, IN ACCESS_MASK DesiredAccess,
IN POBJECT_ATTRIBUTES ObjectAttributes, IN HANDLE InheritFromProcessHandle,
IN BOOLEAN InheritHandles, IN HANDLE SectionHandle OPTIONAL,
IN HANDLE DebugPort OPTIONAL, IN HANDLE ExceptionPort OPTIONAL));
GET_NTDLL(NtTerminateProcess,
(IN HANDLE ProcessHandle OPTIONAL, IN NTSTATUS ExitStatus));
NTPRINT("create_process starting\n");
if (!NT_SUCCESS(wchar_to_unicode(&uexe, exe)))
goto creation_error;
if (!NT_SUCCESS(wchar_to_unicode(&ucmdline, cmdline)))
goto creation_error;
/* create a section and a process that maps it in */
InitializeObjectAttributes(&oa, &uexe, OBJ_CASE_INSENSITIVE, NULL, NULL);
if (!NT_SUCCESS(nt_raw_OpenFile(&hFile, FILE_EXECUTE | SYNCHRONIZE, &oa, &iosb,
FILE_SHARE_READ, FILE_SYNCHRONOUS_IO_NONALERT))) {
NTPRINT("create_process: failed to open file %S\n", uexe.Buffer);
goto creation_error;
}
oa.ObjectName = 0;
if (!NT_SUCCESS(NT_SYSCALL(CreateSection, &hSection, SECTION_ALL_ACCESS, &oa, 0,
PAGE_EXECUTE, SEC_IMAGE, hFile))) {
NTPRINT("create_process: failed to create section\n");
goto creation_error;
}
close_file(hFile);
if (!NT_SUCCESS(NtCreateProcess(&hProcess, PROCESS_ALL_ACCESS, &oa,
NT_CURRENT_PROCESS, TRUE, hSection, 0, 0))) {
NTPRINT("create_process: failed to create process\n");
goto creation_error;
}
if (!NT_SUCCESS(
NtQuerySection(hSection, SectionImageInformation, &sii, sizeof(sii), 0))) {
NTPRINT("create_process: failed to query section\n");
goto creation_error;
}
close_handle(hSection);
NTPRINT("create_process: created section and process\n");
/* FIXME : if thread returns from its EntryPoint function will crash because
* our_create_thread skips the kernel32 ThreadStartThunk */
/* FIXME : need to know whether target process is 32bit or 64bit, for now
* assume 32bit. */
hthread = our_create_thread(hProcess, false, sii.EntryPoint, NULL, NULL, 0,
sii.StackReserve, sii.StackCommit, TRUE, &tid);
if (hthread == INVALID_HANDLE_VALUE) {
NTPRINT("create_process: failed to create thread\n");
goto creation_error;
}
if (!NT_SUCCESS(query_process_info(hProcess, &pbi))) {
NTPRINT("create_process: failed to query process info\n");
goto creation_error;
}
if (!create_process_parameters(hProcess, pbi.PebBaseAddress, &uexe, &ucmdline)) {
NTPRINT("create_process: failed to create process parameters\n");
goto creation_error;
}
if (!inform_csrss(hProcess, hthread, pbi.UniqueProcessId, tid)) {
NTPRINT("create_process: failed to inform csrss\n");
goto creation_error;
}
if (!nt_thread_resume(hthread, NULL)) {
NTPRINT("create_process: failed to resume initial thread\n");
goto creation_error;
}
close_handle(hthread);
NTPRINT("create_process: successfully created process %d!\n", pbi.UniqueProcessId);
return hProcess;
creation_error:
if (hFile != INVALID_HANDLE_VALUE)
close_file(hFile);
if (hSection != INVALID_HANDLE_VALUE)
close_handle(hSection);
if (hthread != INVALID_HANDLE_VALUE)
close_handle(hthread);
if (hProcess != INVALID_HANDLE_VALUE) {
NtTerminateProcess(hProcess, 0);
close_handle(hProcess);
}
return INVALID_HANDLE_VALUE;
}
/* NOTE does not inform csrss, if caller wants csrss informed must do it
* themselves (see inform_csrss). If csrss isn't informed then the stack will
* probably not be freed when the thread exits and certain other apps (some
* cygwin versions, debuggers) will choke on these threads. Threads created with
* this routine must also kill themselves as opposed to returning from their
* start routines (we skip the kernel32 ThreadStartThunk since we can't
* programatically get its address) and no top-level exception handler is set up
* (again the kernel32 StartThunk does that). FIXME on Vista the StartThunk equivalent
* ntdll!RtlUserThreadStart is exported so we could target it on that platform.
*/
/* If arg_buf != NULL then arg_buf_size bytes are copied from arg_buf to the new thread's
* stack and a pointer to that is passed as the argument to the thread routine instead of
* arg.
*/
/* returns INVALID_HANDLE_VALUE on error */
static HANDLE
create_thread_common(HANDLE hProcess, bool target_64bit, void *start_addr, void *arg,
const void *arg_buf, size_t arg_buf_size, USER_STACK *stack,
bool suspended, thread_id_t *tid)
{
HANDLE hthread;
OBJECT_ATTRIBUTES oa;
CLIENT_ID cid;
/* Context must be 16 byte aligned on 64bit */
byte context_buf[sizeof(CONTEXT) + 16] = { 0 };
CONTEXT *context = (CONTEXT *)ALIGN_FORWARD(context_buf, 16);
void *thread_arg = arg;
ptr_uint_t final_stack = 0;
NTSTATUS res;
GET_RAW_SYSCALL(CreateThread, OUT PHANDLE ThreadHandle, IN ACCESS_MASK DesiredAccess,
IN POBJECT_ATTRIBUTES ObjectAttributes, IN HANDLE ProcessHandle,
OUT PCLIENT_ID ClientId, IN PCONTEXT ThreadContext,
IN PUSER_STACK UserStack, IN BOOLEAN CreateSuspended);
InitializeObjectAttributes(&oa, NULL, OBJ_CASE_INSENSITIVE, NULL, NULL);
/* set the context: initialize with our own
* We need CONTEXT_CONTROL and CONTEXT_INTEGER for setting the state here. Also,
* on 2k3 (but not XP) we appear to need CONTEXT_SEGMENTS (xref PR 269230) as well.
* FIXME - on 64-bit CONTEXT_FULL includes CONTEXT_FLOATING_POINT (though not
* CONTEXT_SEGMENTS) so might be nice to grab that as well once PR 266070 is
* implemented. */
context->ContextFlags = CONTEXT_CONTROL | CONTEXT_INTEGER | CONTEXT_SEGMENTS;
GET_OWN_CONTEXT(context);
context->CXT_XSP = (ptr_uint_t)stack->ExpandableStackBase;
context->CXT_XIP = (ptr_uint_t)start_addr;
/* write the argument(s) */
if (arg_buf != NULL) {
context->CXT_XSP -= arg_buf_size;
thread_arg = (void *)context->CXT_XSP;
if (!nt_write_virtual_memory(hProcess, thread_arg, arg_buf, arg_buf_size, NULL)) {
NTPRINT("create_thread: failed to write arguments\n");
return INVALID_HANDLE_VALUE;
}
}
/* set up function call */
if (target_64bit) {
context->CXT_XCX = (ptr_uint_t)thread_arg;
/* 64-bit Windows requires 16-byte stack alignment (see calling convention) */
context->CXT_XSP = ALIGN_BACKWARD(context->CXT_XSP, 16);
/* leave spill space for 4 64-byte registers (see calling convention) */
context->CXT_XSP -= 4 * sizeof(uint64);
/* push the return address (i.e. 0) */
context->CXT_XSP -= 8;
} else {
void *buf[2];
buf[1] = thread_arg;
buf[0] = NULL; /* would be return address */
context->CXT_XSP -= sizeof(buf);
if (!nt_write_virtual_memory(hProcess, (void *)context->CXT_XSP, buf, sizeof(buf),
NULL)) {
NTPRINT("create_thread: failed to write argument\n");
return INVALID_HANDLE_VALUE;
}
}
final_stack = context->CXT_XSP;
/* create the thread - NOTE always creating suspended (see below) */
res = NT_SYSCALL(CreateThread, &hthread, THREAD_ALL_ACCESS, &oa, hProcess, &cid,
context, stack, (byte)TRUE);
if (!NT_SUCCESS(res)) {
NTPRINT("create_thread: failed to create thread: %x\n", res);
return INVALID_HANDLE_VALUE;
}
/* Xref PR 252008 & PR 252745 - on 32-bit Windows the kernel will set esp
* for the initialization APC to the value supplied in the context when the thread
* was created. However, on WOW64 and 64-bit Windows the kernel sets xsp to 20 bytes
* in from the stack base for the initialization APC. Since we have data/arguments
* sitting on the stack we need to explicitly set the context before we let the
* thread run the initialization APC. */
nt_get_context(hthread, context);
context->CXT_XSP = final_stack;
nt_set_context(hthread, context);
if (!suspended) {
int prev_count;
nt_thread_resume(hthread, &prev_count);
}
if (tid != NULL)
*tid = (thread_id_t)cid.UniqueThread;
return hthread;
}
static HANDLE
our_create_thread_ex(HANDLE hProcess, bool target_64bit, void *start_addr, void *arg,
const void *arg_buf, size_t arg_buf_size, uint stack_reserve,
uint stack_commit, bool suspended, thread_id_t *tid)
{
HANDLE hthread;
OBJECT_ATTRIBUTES oa;
CLIENT_ID cid;
TEB *teb;
void *thread_arg = arg;
create_thread_info_t info = { 0 };
NTSTATUS res;
/* NtCreateThreadEx doesn't exist prior to Vista. */
ASSERT(syscalls[SYS_CreateThreadEx] != SYSCALL_NOT_PRESENT);
GET_RAW_SYSCALL(CreateThreadEx, OUT PHANDLE ThreadHandle,
IN ACCESS_MASK DesiredAccess, IN POBJECT_ATTRIBUTES ObjectAttributes,
IN HANDLE ProcessHandle, IN LPTHREAD_START_ROUTINE Win32StartAddress,
IN LPVOID StartParameter, IN BOOL CreateSuspended,
IN uint StackZeroBits, IN SIZE_T StackCommitSize,
IN SIZE_T StackReserveSize, INOUT create_thread_info_t * thread_info);
InitializeObjectAttributes(&oa, NULL, OBJ_CASE_INSENSITIVE, NULL, NULL);
if (arg_buf != NULL) {
/* XXX: Currently we leak this memory, except for nudge where the caller
* sets NUDGE_FREE_ARG.
*/
if (!NT_SUCCESS(nt_remote_allocate_virtual_memory(
hProcess, &thread_arg, arg_buf_size, PAGE_READWRITE, MEM_COMMIT))) {
NTPRINT("create_thread: failed to allocate arg buf\n");
return INVALID_HANDLE_VALUE;
}
if (!nt_write_virtual_memory(hProcess, thread_arg, arg_buf, arg_buf_size, NULL)) {
NTPRINT("create_thread: failed to write arguments\n");
return INVALID_HANDLE_VALUE;
}
}
info.struct_size = sizeof(info);
info.client_id.flags = THREAD_INFO_ELEMENT_CLIENT_ID | THREAD_INFO_ELEMENT_UNKNOWN_2;
info.client_id.buffer_size = sizeof(cid);
info.client_id.buffer = &cid;
/* We get STATUS_INVALID_PARAMETER unless we also ask for teb. */
info.teb.flags = THREAD_INFO_ELEMENT_TEB | THREAD_INFO_ELEMENT_UNKNOWN_2;
info.teb.buffer_size = sizeof(TEB *);
info.teb.buffer = &teb;
res = NT_RAW_SYSCALL(CreateThreadEx, &hthread, THREAD_ALL_ACCESS, &oa, hProcess,
(LPTHREAD_START_ROUTINE)convert_data_to_function(start_addr),
thread_arg, suspended ? TRUE : FALSE, 0, stack_commit,
stack_reserve, &info);
if (!NT_SUCCESS(res)) {
NTPRINT("create_thread_ex: failed to create thread: %x\n", res);
return INVALID_HANDLE_VALUE;
}
if (tid != NULL)
*tid = (thread_id_t)cid.UniqueThread;
return hthread;
}
/* Creates a new stack w/ guard page */
HANDLE
our_create_thread(HANDLE hProcess, bool target_64bit, void *start_addr, void *arg,
const void *arg_buf, size_t arg_buf_size, uint stack_reserve,
uint stack_commit, bool suspended, thread_id_t *tid)
{
USER_STACK stack = { 0 };
uint num_commit_bytes, old_prot;
void *p;
ASSERT(stack_commit + PAGE_SIZE <= stack_reserve &&
ALIGNED(stack_commit, PAGE_SIZE) && ALIGNED(stack_reserve, PAGE_SIZE));
if (get_os_version() >= WINDOWS_VERSION_8) {
/* NtCreateThread not available: use Ex where the kernel makes the stack. */
return our_create_thread_ex(hProcess, target_64bit, start_addr, arg, arg_buf,
arg_buf_size, stack_reserve, stack_commit, suspended,
tid);
}
if (!NT_SUCCESS(nt_remote_allocate_virtual_memory(
hProcess, &stack.ExpandableStackBottom, stack_reserve, PAGE_READWRITE,
MEM_RESERVE))) {
NTPRINT("create_thread: failed to allocate stack\n");
return INVALID_HANDLE_VALUE;
}
/* For failures beyond this point we don't bother deallocating the stack. */
stack.ExpandableStackBase = ((byte *)stack.ExpandableStackBottom) + stack_reserve;
stack.ExpandableStackLimit = ((byte *)stack.ExpandableStackBase) - stack_commit;
num_commit_bytes = stack_commit + (uint)PAGE_SIZE;
p = ((byte *)stack.ExpandableStackBase) - num_commit_bytes;
if (!NT_SUCCESS(nt_remote_allocate_virtual_memory(hProcess, &p, num_commit_bytes,
PAGE_READWRITE, MEM_COMMIT))) {
NTPRINT("create_thread: failed to commit stack pages\n");
return INVALID_HANDLE_VALUE;
}
if (!nt_remote_protect_virtual_memory(hProcess, p, PAGE_SIZE,
PAGE_READWRITE | PAGE_GUARD, &old_prot)) {
NTPRINT("create_thread: failed to protect stack guard page\n");
return INVALID_HANDLE_VALUE;
}
return create_thread_common(hProcess, target_64bit, start_addr, arg, arg_buf,
arg_buf_size, &stack, suspended, tid);
}
/* is_new_thread_client_thread() assumes param is the stack */
void
our_create_thread_wrapper(void *param)
{
/* Thread was initialized in intercept_new_thread() */
dcontext_t *dcontext = get_thread_private_dcontext();
/* Get the data we need from where our_create_thread_have_stack() wrote them. */
byte *stack_base = (byte *)param;
size_t stack_size = *(size_t *)(stack_base - sizeof(void *));
byte *src = stack_base - stack_size;
void *func = *(void **)src;
size_t args_size = *(size_t *)(src + sizeof(void *));
void *arg = src + 2 * sizeof(void *);
/* Update TEB for proper SEH, etc. */
TEB *teb = get_own_teb();
teb->StackLimit = src;
teb->StackBase = stack_base;
call_switch_stack(arg, stack_base, (void (*)(void *))convert_data_to_function(func),
NULL, false /*no return*/);
ASSERT_NOT_REACHED();
}
/* Uses caller-allocated stack. hProcess must be NT_CURRENT_PROCESS for win8+. */
HANDLE
our_create_thread_have_stack(HANDLE hProcess, bool target_64bit, void *start_addr,
void *arg, const void *arg_buf, size_t arg_buf_size,
byte *stack_base, size_t stack_size, bool suspended,
thread_id_t *tid)
{
if (get_os_version() >= WINDOWS_VERSION_8) {
/* i#1309: we need a wrapper function so we can use NtCreateThreadEx
* and then switch stacks. This is too hard to arrange in another process.
*/
ASSERT(hProcess == NT_CURRENT_PROCESS &&
"No support for creating a remote thread with a custom stack");
/* We store what the wrapper needs on the end of the stack so it won't
* get clobbered by call_switch_stack().
*/
byte *dest = stack_base - stack_size;
*(void **)dest = start_addr;
if (arg_buf == NULL)
arg_buf_size = sizeof(void *);
*(size_t *)(dest + sizeof(void *)) = arg_buf_size;
if (arg_buf != NULL)
memcpy(dest + 2 * sizeof(void *), arg_buf, arg_buf_size);
else
*(void **)(dest + 2 * sizeof(void *)) = arg;
/* We store the stack size at the base so we can find the top. */
*(size_t *)(stack_base - sizeof(void *)) = stack_size;
return our_create_thread_ex(hProcess, target_64bit,
(void *)our_create_thread_wrapper, stack_base, NULL,
0, 0, 0, suspended, tid);
} else {
USER_STACK stack = { 0 };
stack.ExpandableStackBase = stack_base;
stack.ExpandableStackLimit = stack_base - stack_size;
stack.ExpandableStackBottom = stack_base - stack_size;
return create_thread_common(hProcess, target_64bit, start_addr, arg, arg_buf,
arg_buf_size, &stack, suspended, tid);
}
}
#endif /* !defined(NOT_DYNAMORIO_CORE) && !defined(NOT_DYNAMORIO_CORE_PROPER) */
/* Except where otherwise noted the following notes are taken from analysis of
* LoadLibrary on xpsp2 (\\araksha-tim). */
/* The kernel32 version of this function does some additional work. It checks
* to see if you are loading twain_32.dll and handles that separately. It also
* does the necessary string conversions to ntdll formats. When kernel32 calls
* LdrLoadDll it passes in a ; separated path string for PathToFile. The second
* argument is a little trickier. Some sources say it's a ULONG flags argument
* (that corresponds to Ex ver flags) while others say its PDWORD LdrErr. On
* the platforms observed, xpsp2 (\\araksha-tim) and win2k (test-east), it's
* definitely a pointer to a stack location that appears to hold a flag value.
* The flag value does not match the Ex flags however. It doesn't appear to be
* IN/OUT argument (or OUT error) since I've never seen it written to, even when
* the loader had an error). A Summary of observed 2nd arguments:
*
* for xpsp2 (araksha-tim) & win2k (test-east) (all values hex)
* Ex Flag 2nd arg to LdrLoadDll 2nd arg deref
* 1 stack ptr 2
* 0,8 stack ptr 0
* 2 (dll not loaded) calls BasepLoadLibraryAsDataFile instead of LdrLoadDll
* 2 (dll loaded) NULL
* 10 (xpsp2 only) stack ptr 1000
*
* See msdn for explanation of Ex flag values (0 is what we want and what the
* non Ex versions use). The 2nd argument definitely appears to PDWORD/PULONG
* and not a pointer to a larger struct, the next value on the stack after the
* deref value is uninitialized (both before and after LdrLoadDll is called, even
* if LdrLoadDll has an error). The argument does indeed appear to be optional.
* Our load_library appears to work fine with either a ptr to 0 or NULL as the
* 2nd argument (DllMain is called, load count adjusted correctly etc. either
* way). Another mystery is that LoadLibraryExW also goes to the trouble of
* building a UNICODE_STRING version of PathToFile, but then doesn't appear to
* use it, perhaps it is for an unusual path through the function.
* FIXME : understand behavior more.
*/
/* returns NULL on failure */
module_handle_t
load_library(wchar_t *lib_name)
{
UNICODE_STRING ulib_name;
HANDLE hMod;
NTSTATUS res;
ULONG flags = 0;
GET_NTDLL(LdrLoadDll,
(IN PCWSTR PathToFile OPTIONAL, IN PULONG Flags OPTIONAL,
IN PUNICODE_STRING ModuleFileName, OUT PHANDLE ModuleHandle));
/* we CANNOT be holding any DR locks here, since we are going to
* execute app code (we call LdrLoadDll) that may grab app locks
*/
ASSERT_OWN_NO_LOCKS();
wchar_to_unicode(&ulib_name, lib_name);
res = LdrLoadDll(NULL, &flags, &ulib_name, &hMod);
if (!NT_SUCCESS(res))
return NULL;
return hMod;
}
/* Kernel32 FreeLibrary is a simple wrapper around this routine normally.
* However, if the lsb of the module handle is set, unmaps and calls
* LdrUnloadAlternateResourceModule. For our usage (which is always real dlls)
* I think this should be fine. */
bool
free_library(module_handle_t lib)
{
NTSTATUS res;
GET_NTDLL(LdrUnloadDll, (IN HANDLE ModuleHandle));
/* we CANNOT be holding any DR locks here, since we are going to
* execute app code (we call LdrLoadDll) that may grab app locks
*/
ASSERT_OWN_NO_LOCKS();
res = LdrUnloadDll(lib);
return NT_SUCCESS(res);
}
/* FIXME : the following function (get_module_handle)
* should really be implemented in module.c rather than as wrappers to the
* undocumented ntdll ldr routines. In particular, LdrGetDllHandle does
* allocate memory on the app's heap, so this is not fully transparent!
*/
/* The Kernel32 version appears to be more or less a wrapper around this
* function. The kernel32 version has lots of code for processing the name into
* a unicode string and what looks like handling the flags for the ex version. */
/* returns NULL on failure */
module_handle_t
get_module_handle(const wchar_t *lib_name)
{
UNICODE_STRING ulib_name;
HANDLE hMod;
NTSTATUS res;
/* NOTE - I've seen the first argument be 0, 1, or a pointer to a ; separated
* path string. GetModuleHandle usually seems to use 1 though I have no idea
* what that means. Seems to work fine either way (doesn't seem to adjust
* the load count which was my first guess). */
#define LDR_GET_DLL_HANDLE_ARG1 ((PCWSTR)PTR_UINT_1)
GET_NTDLL(LdrGetDllHandle,
(IN PCWSTR PathToFile OPTIONAL, IN ULONG Unused OPTIONAL,
IN PUNICODE_STRING ModuleFileName, OUT PHANDLE ModuleHandle));
/* we CANNOT be holding any DR locks here, since we are going to
* execute app code (we call LdrLoadDll) that may grab app locks
*/
ASSERT_OWN_NO_LOCKS();
wchar_to_unicode(&ulib_name, lib_name);
res = LdrGetDllHandle(LDR_GET_DLL_HANDLE_ARG1, 0, &ulib_name, &hMod);
if (!NT_SUCCESS(res))
return NULL;
return hMod;
}
/* Mostly a wrapper around NtCreateDirectoryObject.
*
* Note that dacl == NULL allows only owner to use the object -
* sufficient for sharing only between processes of one user.
*/
NTSTATUS
nt_create_object_directory(OUT HANDLE *directory /* OUT */, PCWSTR object_directory_name,
bool permanent_directory, PSECURITY_DESCRIPTOR dacl)
{
NTSTATUS res;
UNICODE_STRING directory_name;
OBJECT_ATTRIBUTES directory_attributes = { 0 };
GET_NTDLL(NtCreateDirectoryObject,
(OUT PHANDLE DirectoryHandle, IN ACCESS_MASK DesiredAccess,
IN POBJECT_ATTRIBUTES ObjectAttributes));
res = wchar_to_unicode(&directory_name, object_directory_name);
if (!NT_SUCCESS(res)) {
NTPRINT("nt_create_object_directory: base name conversion failed, res: %x\n",
res);
return res;
}
/* see DDK about all other flags */
InitializeObjectAttributes(&directory_attributes, &directory_name,
(permanent_directory ? OBJ_PERMANENT : 0) | OBJ_OPENIF |
OBJ_CASE_INSENSITIVE,
NULL,
/* no root, directory name should be fully qualified */
dacl);
res = NtCreateDirectoryObject(directory, DIRECTORY_ALL_ACCESS, /* for creation */
&directory_attributes);
if (!NT_SUCCESS(res)) {
NTPRINT("nt_create_object_directory: failed to create directory\n");
return res;
}
return res;
}
/* only privileged processes will be allowed to create the directory
* and set DACLs.
*
* creating a permanent (until next reboot) directory requires
* SeCreatePermanentPrivilege. Note that most user mode processes do
* not have this privilege. Most services, including winlogon.exe,
* for sure have it though.
*
* If we pick any of these with ASLR_SHARED_INITIALIZE we'll be able
* to set up a directory for all other processes (in fact all
* processes can try but only the services will be able to create it,
* and only the first one will succeed so indeed can have all. Only
* unusual case will be if a low user process is started before a
* privileged process and therefore prevents a permanent directory
* from being created.
*
*/
NTSTATUS
nt_initialize_shared_directory(HANDLE *shared_directory /* OUT */, bool permanent)
{
NTSTATUS res;
HANDLE basedh = INVALID_HANDLE_VALUE;
HANDLE dh = INVALID_HANDLE_VALUE;
/* FIXME: TOFILE: need to create at least some reasonable DACL,
* note that NULL allows only creator to use, so it is not as bad
* as Everyone, but then prevents lower privileged users from even
* using this Directory
*/
PSECURITY_DESCRIPTOR dacl = NULL;
/* The ACLs in the default security descriptor come from the
* primary or impersonation token of the creator. So in fact we
* won't be able to do open this from others as is too restrictive
* in this instance.
*/
/* Create base object directory '\Determina' */
res = nt_create_object_directory(&basedh, DYNAMORIO_SHARED_OBJECT_BASE, permanent,
dacl);
if (!NT_SUCCESS(res)) {
NTPRINT("nt_create_shared_directory: failed to create shared directory\n");
return res;
}
/* SECURITY_LOCAL_SID_AUTHORITY should be allowed to read all contents
* to allow sharing between all process
*/
dacl = NULL;
/* Create shared DLL object directory '\Determina\SharedCache' */
/* FIXME: we will need directories for specific SIDs, and further
* restrict which processes can read what. See
* ASLR_SHARED_INITIALIZE. Even this shared cache security
* settings would need to be strengthened.
*/
res = nt_create_object_directory(&dh, DYNAMORIO_SHARED_OBJECT_DIRECTORY, permanent,
dacl);
if (!NT_SUCCESS(res)) {
NTPRINT("nt_create_shared_directory: failed to create shared directory\n");
return res;
}
/* FIXME: note the dual use of the permanent flag here - in
* addition to controlling the OBJ_PERMANENT object creation
* attribute, for INTERNAL uses when we don't have a proper
* initializer we simulate permanence by keeping a handle open in
* the creating process */
if (permanent) {
/* close base handle only if permanent, otherwise dh=\...\SharedCache,
* but subsequent lookup by name can't find \Determina\SharedCache,
* so closing this handle would not be really useful for a non-permanent
*/
close_handle(basedh);
}
/* caller only needs leaf node */
*shared_directory = dh;
return res;
}
/* any process should be able to open the shared mappings directory,
* and maybe even add entries to it given high enough permissions
*/
NTSTATUS
nt_open_object_directory(HANDLE *shared_directory /* OUT */, PCWSTR object_directory_name,
bool allow_object_creation)
{
NTSTATUS res;
UNICODE_STRING directory_name;
OBJECT_ATTRIBUTES directory_attributes = { 0 };
HANDLE dh = INVALID_HANDLE_VALUE;
GET_NTDLL(NtOpenDirectoryObject,
(OUT PHANDLE DirectoryHandle, IN ACCESS_MASK DesiredAccess,
IN POBJECT_ATTRIBUTES ObjectAttributes));
res = wchar_to_unicode(&directory_name, object_directory_name);
if (!NT_SUCCESS(res)) {
NTPRINT("nt_open_object_directory: name conversion failed, res: %x\n", res);
return res;
}
/* see DDK about all other flags */
InitializeObjectAttributes(&directory_attributes, &directory_name,
OBJ_CASE_INSENSITIVE, NULL,
/* no root, directory name should be fully qualified */
NULL);
res = NtOpenDirectoryObject(&dh,
DIRECTORY_QUERY | DIRECTORY_TRAVERSE |
/* should it try to obtain permission
* to create objects (e.g. publisher) */
(allow_object_creation ? DIRECTORY_CREATE_OBJECT : 0),
&directory_attributes);
/* note DIRECTORY_CREATE_OBJECT doesn't allow creating subdirs,
* for which DIRECTORY_CREATE_SUBDIRECTORY is needed */
if (!NT_SUCCESS(res)) {
NTPRINT("nt_open_object_directory: failed to open res: %x\n", res);
return res;
}
/* FIXME: we could retry if we can't get higher permissions */
*shared_directory = dh;
return res;
}
void
nt_close_object_directory(HANDLE hobjdir)
{
close_handle(hobjdir);
}
/* Returns the symbolic link target in target_name. */
/* note target_name should be initialized with a valid Buffer and MaximumLength
* Also according to the DDK returned_byte_length may be an IN
* argument setting max bytes to copy
*/
NTSTATUS
nt_get_symlink_target(IN HANDLE directory_handle, IN PCWSTR symlink_name,
IN OUT UNICODE_STRING *target_name, OUT uint *returned_byte_length)
{
NTSTATUS res;
UNICODE_STRING link_unicode_name;
OBJECT_ATTRIBUTES link_attributes = { 0 };
HANDLE link_handle = INVALID_HANDLE_VALUE;
GET_NTDLL(NtOpenSymbolicLinkObject,
(OUT PHANDLE DirectoryHandle, IN ACCESS_MASK DesiredAccess,
IN POBJECT_ATTRIBUTES ObjectAttributes));
GET_NTDLL(NtQuerySymbolicLinkObject,
(IN HANDLE DirectoryHandle, IN OUT PUNICODE_STRING TargetName,
OUT PULONG ReturnLength OPTIONAL));
res = wchar_to_unicode(&link_unicode_name, symlink_name);
if (!NT_SUCCESS(res)) {
NTPRINT("nt_get_symlink_target: name conversion failed, res: %x\n", res);
return res;
}
InitializeObjectAttributes(&link_attributes, &link_unicode_name,
OBJ_CASE_INSENSITIVE
/* note it doesn't seem to require |
* OBJ_OPENLINK and in fact returns
* STATUS_INVALID_PARAMETER when that
* is set
*/
,
directory_handle, NULL);
res = NtOpenSymbolicLinkObject(&link_handle, SYMBOLIC_LINK_QUERY, &link_attributes);
if (!NT_SUCCESS(res)) {
return res;
}
res = NtQuerySymbolicLinkObject(link_handle, target_name,
(ULONG *)returned_byte_length);
close_handle(link_handle);
ASSERT(NT_SUCCESS(res));
return res;
}
/* General notes about sharing memory */
/* section<PAGE_EXECUTE, SEC_IMAGE, app_file> gives us CoW in each
* process, and we can't share the relocation information
*/
/* section<PAGE_EXECUTE_READWRITE, SEC_IMAGE, original app_file>
* gives access denied since file is open only for execution.
* Though even proper privileges do not overwrite the original
* file - SEC_IMAGE is always copy on write.
*/
/* only using SEC_COMMIT either with page file, or with a
* {file<FILE_EXECUTE | FILE_READ_DATA | FILE_WRITE_DATA>,
* createsection<PAGE_EXECUTE_READWRITE, SEC_COMMIT, file>,
* map<PAGE_READWRITE>} allows writers to write to a true shared
* memory with readers.
* If a particular reader needs private writes they can use a mapping
* created as above by writers {file<FILE_EXECUTE | FILE_READ_DATA>,
* opensection<SEC_COMMIT>, map<PAGE_WRITECOPY>} (can even track the
* pages that have transitioned from PAGE_WRITECOPY into
* PAGE_READWRITE to find which ones have been touched.
*/
/* complete wrapper around NtCreateSection but embeds InitializeObjectAttributes */
NTSTATUS
nt_create_section(OUT PHANDLE SectionHandle, IN ACCESS_MASK DesiredAccess,
IN PLARGE_INTEGER SectionSize OPTIONAL, IN ULONG Protect,
IN ULONG section_creation_attributes, IN HANDLE FileHandle,
/* object name attributes */
IN PCWSTR section_name OPTIONAL, IN ULONG object_name_attributes,
IN HANDLE object_directory, IN PSECURITY_DESCRIPTOR dacl)
{
NTSTATUS res;
UNICODE_STRING section_name_unicode;
OBJECT_ATTRIBUTES section_attributes;
if (section_name != NULL) {
res = wchar_to_unicode(§ion_name_unicode, section_name);
ASSERT(NT_SUCCESS(res));
if (!NT_SUCCESS(res))
return res;
}
InitializeObjectAttributes(
§ion_attributes, ((section_name != NULL) ? §ion_name_unicode : NULL),
OBJ_CASE_INSENSITIVE | object_name_attributes, object_directory, dacl);
res = NT_SYSCALL(CreateSection, SectionHandle, DesiredAccess, §ion_attributes,
SectionSize, Protect, section_creation_attributes, FileHandle);
if (!NT_SUCCESS(res)) {
NTPRINT("nt_create_section: failed res: %x\n", res);
}
return res;
}
#if !defined(NOT_DYNAMORIO_CORE_PROPER) && !defined(NOT_DYNAMORIO_CORE)
/* complete wrapper around NtOpenSection */
/* note that section_name is required and is case insensitive to
* support normal Windows case insensitivity of DLL lookup.
* FIXME: unlikely may need to be changed for POSIX support
*/
NTSTATUS
nt_open_section(OUT PHANDLE SectionHandle, IN ACCESS_MASK DesiredAccess,
/* object name attributes */
IN PCWSTR section_name, /* required */
IN ULONG object_name_attributes, IN HANDLE object_directory)
{
NTSTATUS res;
UNICODE_STRING section_name_unicode;
OBJECT_ATTRIBUTES section_attributes;
ASSERT(section_name != NULL);
res = wchar_to_unicode(§ion_name_unicode, section_name);
ASSERT(NT_SUCCESS(res));
if (!NT_SUCCESS(res))
return res;
InitializeObjectAttributes(§ion_attributes, §ion_name_unicode,
OBJ_CASE_INSENSITIVE | object_name_attributes,
object_directory, NULL);
res = NT_SYSCALL(OpenSection, SectionHandle, DesiredAccess, §ion_attributes);
if (!NT_SUCCESS(res)) {
NTPRINT("nt_open_section: failed res: %x\n", res);
}
return res;
}
bool
are_mapped_files_the_same(app_pc addr1, app_pc addr2)
{
# if 0 /* NYI: case 8502 */
/* FIXME: this doesn't exist on NT4 - make sure we handle
* gracefully not finding the target - needs a very explicit
* d_r_get_proc_address() here.
*/
GET_NTDLL(ZwAreMappedFilesTheSame, (
IN PVOID Address1,
IN PVOID Address2
));
# endif
ASSERT_NOT_TESTED();
ASSERT_NOT_IMPLEMENTED(false);
/* Testing: check return values for: addresses in different DLLs;
* addresses in same DLL; addresses in same DLL but coming from
* different mappings - the key one for us.
*/
return false;
}
#endif /* !defined(NOT_DYNAMORIO_CORE_PROPER) && !defined(NOT_DYNAMORIO_CORE) */
/* Mostly a wrapper around NtCreateFile, geared to opening existing
* module files. See the DDK and SDK for complete argument documentation.
*
* callers have to close_handle() after use.
*
* file_path can be a path relative to root_directory_handle, or if
* root_directory_handle is NULL file_path has to be an NT absolute
* path (e.g. produced by the likes of RtlDosPathNameToNtPathName_U)
*/
/* desired_access_rights - a subset of FILE_EXECUTE | FILE_READ_DATA |
* FILE_WRITE_DATA. Note: FILE_READ_DATA would be necessary for a
* later section mapping as PAGE_WRITECOPY, and FILE_WRITE_DATA may be
* needed for a PAGE_EXECUTE_WRITECOPY mapping if not SEC_IMAGE
*/
/* file_special_attributes typically FILE_ATTRIBUTE_NORMAL, possible
* other flags to use here FILE_ATTRIBUTE_TEMPORARY and maybe
* FILE_FLAG_DELETE_ON_CLOSE? */
/* file_sharing_flags */
NTSTATUS
nt_create_module_file(OUT HANDLE *file_handle, const wchar_t *file_path,
HANDLE root_directory_handle OPTIONAL,
ACCESS_MASK desired_access_rights, uint file_special_attributes,
uint file_sharing_flags, uint create_disposition,
size_t allocation_size)
{
NTSTATUS res = nt_create_file(
file_handle, file_path, root_directory_handle, allocation_size,
SYNCHRONIZE | desired_access_rights, file_special_attributes, file_sharing_flags,
create_disposition, FILE_SYNCHRONOUS_IO_NONALERT | FILE_NON_DIRECTORY_FILE);
if (!NT_SUCCESS(res)) {
NTPRINT("nt_open_module_file: can't open file, res: %x\n", res);
}
return res;
}
/* thin wrapper around ZwQueryInformationFile -
* see DDK for documented information classes */
NTSTATUS
nt_query_file_info(IN HANDLE FileHandle, OUT PVOID FileInformation,
IN ULONG FileInformationLength,
IN FILE_INFORMATION_CLASS FileInformationClass)
{
NTSTATUS res;
IO_STATUS_BLOCK iob = { 0, 0 };
res = NtQueryInformationFile(FileHandle, &iob, FileInformation, FileInformationLength,
FileInformationClass);
if (!NT_SUCCESS(res)) {
NTPRINT("nt_query_file_info: can't open file, res: %x\n", res);
}
return res;
}
/* thin wrapper around ZwSetInformationFile -
* see DDK for fully documented information classes
*/
NTSTATUS
nt_set_file_info(IN HANDLE FileHandle, IN PVOID FileInformation,
IN ULONG FileInformationLength,
IN FILE_INFORMATION_CLASS FileInformationClass)
{
NTSTATUS res;
IO_STATUS_BLOCK iob = { 0, 0 };
res = NtSetInformationFile(FileHandle, &iob, FileInformation, FileInformationLength,
FileInformationClass);
if (!NT_SUCCESS(res)) {
NTPRINT("nt_set_file_info: can't open file, res: %x\n", res);
}
return res;
}
/* thin wrapper around ZwQueryVolumeInformationFile -
* see Windows Driver Kit: Installable File System Drivers
* for documented information classes,
* Note handle can be file, directory, device or volume.
*/
NTSTATUS
nt_query_volume_info(IN HANDLE FileHandle, OUT PVOID FsInformation,
IN ULONG FsInformationLength,
IN FS_INFORMATION_CLASS FsInformationClass)
{
NTSTATUS res;
IO_STATUS_BLOCK iob = { 0, 0 };
GET_NTDLL(NtQueryVolumeInformationFile,
(IN HANDLE FileHandle, OUT PIO_STATUS_BLOCK IoStatusBlock,
OUT PVOID FsInformation, IN ULONG Length,
IN FS_INFORMATION_CLASS FsInformationClass));
res = NtQueryVolumeInformationFile(FileHandle, &iob, FsInformation,
FsInformationLength, FsInformationClass);
if (!NT_SUCCESS(res)) {
NTPRINT("nt_query_volume_info: can't open file, res: %x\n", res);
} else {
ASSERT(iob.Information == FsInformationLength ||
/* volume info needs a big buffer so ok to be oversized */
(FsInformationClass == FileFsVolumeInformation &&
iob.Information >= offsetof(FILE_FS_VOLUME_INFORMATION, VolumeLabel)));
}
return res;
}
#if !defined(NOT_DYNAMORIO_CORE_PROPER) && !defined(NOT_DYNAMORIO_CORE)
/* thin wrapper around ZwQuerySecurityObject -
* Note handle can be any executive objective: including file, directory
*/
NTSTATUS
nt_query_security_object(IN HANDLE Handle, IN SECURITY_INFORMATION RequestedInformation,
OUT PSECURITY_DESCRIPTOR SecurityDescriptor,
IN ULONG SecurityDescriptorLength, OUT PULONG ReturnLength)
{
NTSTATUS res;
/* note that SecurityDescriptor returned is always PISECURITY_DESCRIPTOR_RELATIVE */
GET_NTDLL(NtQuerySecurityObject,
(IN HANDLE Handle, IN SECURITY_INFORMATION RequestedInformation,
OUT PSECURITY_DESCRIPTOR SecurityDescriptor,
IN ULONG SecurityDescriptorLength, OUT PULONG ReturnLength));
res = NtQuerySecurityObject(Handle, RequestedInformation, SecurityDescriptor,
SecurityDescriptorLength, ReturnLength);
/* if SecurityDescriptorLength is too small ReturnLength is set to
* the number of bytes required for the available data
*/
/* for a file handle possibly insufficient permissions or unsupported file system */
if (!NT_SUCCESS(res)) {
NTPRINT("nt_query_security_object: can't open file, res: %x\n", res);
}
return res;
}
/* expect SID to have already been allocated statically
* (note we cannot use RtlAllocateAndInitializeSid to allocate memory!)
*/
void
initialize_known_SID(PSID_IDENTIFIER_AUTHORITY IdentifierAuthority, ULONG SubAuthority0,
SID *pSid)
{
UCHAR SubAuthorityCount = 1;
ASSERT(pSid != NULL);
pSid->Revision = SID_REVISION;
pSid->SubAuthorityCount = SubAuthorityCount;
memcpy(&pSid->IdentifierAuthority, IdentifierAuthority,
sizeof(SID_IDENTIFIER_AUTHORITY));
pSid->SubAuthority[0] = SubAuthority0;
}
/* Initialize the buffer as CONTEXT with extension and return the pointer
* pointing to the start of CONTEXT.
* Assume buffer size is MAX_CONTEXT_SIZE;
*/
CONTEXT *
nt_initialize_context(char *buf, DWORD flags)
{
/* Ideally, kernel32!InitializeContext is used to setup context.
* However, DR should NEVER use kernel32. DR never uses anything in
* any user library other than ntdll.
*/
CONTEXT *cxt;
if (TESTALL(CONTEXT_XSTATE, flags)) {
context_ex_t *cxt_ex;
int len, res;
ASSERT(proc_avx_enabled());
/* 8d450c lea eax,[ebp+0Ch]
* 50 push eax
* 57 push edi
* ff15b0007a76 call dword ptr [_imp__RtlGetExtendedContextLength]
*/
res = ntdll_RtlGetExtendedContextLength(flags, &len);
ASSERT(res >= 0 && len <= MAX_CONTEXT_SIZE);
/* 8d45fc lea eax,[ebp-4]
* 50 push eax
* 57 push edi
* ff7508 push dword ptr [ebp+8]
* ff15b4007a76 call dword ptr [_imp__RtlInitializeExtendedContext]
*/
res = ntdll_RtlInitializeExtendedContext((PVOID)buf, flags, (PVOID)&cxt_ex);
ASSERT(res == 0);
/* 6a00 push 0
* ff75fc push dword ptr [ebp-4]
* ff15b8007a76 call dword ptr [_imp__RtlLocateLegacyContext]
*/
cxt = (CONTEXT *)ntdll_RtlLocateLegacyContext(cxt_ex, 0);
ASSERT(context_check_extended_sizes(cxt_ex, flags));
ASSERT(cxt != NULL && (char *)cxt >= buf &&
(char *)cxt + cxt_ex->all.length < buf + MAX_CONTEXT_SIZE);
} else {
/* make it 16-byte aligned */
cxt = (CONTEXT *)(ALIGN_FORWARD(buf, 0x10));
ASSERT(!CONTEXT_DYNAMICALLY_LAID_OUT(flags)); /* ensure in synch */
}
cxt->ContextFlags = flags;
return cxt;
}
/****************************************************************************
* DrM-i#1066: We implement raw system call invocation for system calls
* hooked by applications so that they can be used by private libs.
* Most raw system calls are put into NOT_DYNAMORIO_CORE_PROPER since they
* are not needed in NOT_DYNAMORIO_CORE_PROPER.
*/
GET_RAW_SYSCALL(OpenFile, PHANDLE file_handle, ACCESS_MASK desired_access,
POBJECT_ATTRIBUTES object_attributes, PIO_STATUS_BLOCK io_status_block,
ULONG share_access, ULONG open_options);
GET_RAW_SYSCALL(OpenKeyEx, PHANDLE key_handle, ACCESS_MASK desired_access,
POBJECT_ATTRIBUTES object_attributes, ULONG open_options);
GET_RAW_SYSCALL(OpenProcessTokenEx, HANDLE process_handle, ACCESS_MASK desired_access,
ULONG handle_attributes, PHANDLE token_handle);
GET_RAW_SYSCALL(OpenThread, PHANDLE thread_handle, ACCESS_MASK desired_access,
POBJECT_ATTRIBUTES object_attributes, PCLIENT_ID client_id);
GET_RAW_SYSCALL(OpenThreadTokenEx, HANDLE thread_handle, ACCESS_MASK desired_access,
BOOLEAN open_as_self, ULONG handle_attributes, PHANDLE token_handle);
GET_RAW_SYSCALL(QueryAttributesFile, POBJECT_ATTRIBUTES object_attributes,
PFILE_BASIC_INFORMATION file_information);
GET_RAW_SYSCALL(SetInformationThread, HANDLE thread_handle,
THREADINFOCLASS thread_information_class, PVOID thread_information,
ULONG thread_information_length);
NTSTATUS
nt_raw_CreateFile(PHANDLE file_handle, ACCESS_MASK desired_access,
POBJECT_ATTRIBUTES object_attributes, PIO_STATUS_BLOCK io_status_block,
PLARGE_INTEGER allocation_size, ULONG file_attributes,
ULONG share_access, ULONG create_disposition, ULONG create_options,
PVOID ea_buffer, ULONG ea_length)
{
NTSTATUS res;
res = NT_SYSCALL(CreateFile, file_handle, desired_access, object_attributes,
io_status_block, allocation_size, file_attributes, share_access,
create_disposition, create_options, ea_buffer, ea_length);
# ifdef DEBUG
if (!NT_SUCCESS(res)) {
NTLOG(GLOBAL, LOG_NT, 1, "nt_raw_CreateFile failed, res: %x\n", res);
}
# endif
return res;
}
NTSTATUS
nt_raw_OpenFile(PHANDLE file_handle, ACCESS_MASK desired_access,
POBJECT_ATTRIBUTES object_attributes, PIO_STATUS_BLOCK io_status_block,
ULONG share_access, ULONG open_options)
{
NTSTATUS res;
res = NT_SYSCALL(OpenFile, file_handle, desired_access, object_attributes,
io_status_block, share_access, open_options);
# ifdef DEBUG
if (!NT_SUCCESS(res)) {
NTLOG(GLOBAL, LOG_NT, 1, "nt_raw_OpenFile failed, res: %x\n", res);
}
# endif
return res;
}
NTSTATUS
nt_raw_OpenKey(PHANDLE key_handle, ACCESS_MASK desired_access,
POBJECT_ATTRIBUTES object_attributes)
{
NTSTATUS res;
res = NT_SYSCALL(OpenKey, key_handle, desired_access, object_attributes);
# ifdef DEBUG
if (!NT_SUCCESS(res)) {
NTLOG(GLOBAL, LOG_NT, 1, "nt_raw_OpenKey failed, res: %x\n", res);
}
# endif
return res;
}
NTSTATUS
nt_raw_OpenKeyEx(PHANDLE key_handle, ACCESS_MASK desired_access,
POBJECT_ATTRIBUTES object_attributes, ULONG open_options)
{
NTSTATUS res;
/* i#1011, OpenKeyEx does not exist in older Windows version */
ASSERT(syscalls[SYS_OpenKeyEx] != SYSCALL_NOT_PRESENT);
res = NT_RAW_SYSCALL(OpenKeyEx, key_handle, desired_access, object_attributes,
open_options);
# ifdef DEBUG
if (!NT_SUCCESS(res)) {
NTLOG(GLOBAL, LOG_NT, 1, "nt_raw_OpenKeyEx failed, res: %x\n", res);
}
# endif
return res;
}
NTSTATUS
nt_raw_OpenProcessTokenEx(HANDLE process_handle, ACCESS_MASK desired_access,
ULONG handle_attributes, PHANDLE token_handle)
{
NTSTATUS res;
res = NT_RAW_SYSCALL(OpenProcessTokenEx, process_handle, desired_access,
handle_attributes, token_handle);
# ifdef DEBUG
if (!NT_SUCCESS(res)) {
NTLOG(GLOBAL, LOG_NT, 1, "nt_raw_OpenProcessTokenEx failed, res: %x\n", res);
}
# endif
return res;
}
NTSTATUS
nt_raw_OpenThread(PHANDLE thread_handle, ACCESS_MASK desired_access,
POBJECT_ATTRIBUTES object_attributes, PCLIENT_ID client_id)
{
NTSTATUS res;
res = NT_SYSCALL(OpenThread, thread_handle, desired_access, object_attributes,
client_id);
# ifdef DEBUG
if (!NT_SUCCESS(res)) {
NTLOG(GLOBAL, LOG_NT, 1, "nt_raw_OpenThread failed, res: %x\n", res);
}
# endif
return res;
}
NTSTATUS
nt_raw_OpenThreadTokenEx(HANDLE thread_handle, ACCESS_MASK desired_access,
BOOLEAN open_as_self, ULONG handle_attributes,
PHANDLE token_handle)
{
NTSTATUS res;
res = NT_RAW_SYSCALL(OpenThreadTokenEx, thread_handle, desired_access, open_as_self,
handle_attributes, token_handle);
# ifdef DEBUG
if (!NT_SUCCESS(res)) {
NTLOG(GLOBAL, LOG_NT, 1, "nt_raw_NtOpenThreadTokenEx failed, res: %x\n", res);
}
# endif
return res;
}
NTSTATUS
nt_raw_QueryAttributesFile(POBJECT_ATTRIBUTES object_attributes,
PFILE_BASIC_INFORMATION file_information)
{
NTSTATUS res;
res = NT_SYSCALL(QueryAttributesFile, object_attributes, file_information);
# ifdef DEBUG
if (!NT_SUCCESS(res)) {
NTLOG(GLOBAL, LOG_NT, 1, "nt_raw_QueryAttributesFile failed, res: %x\n", res);
}
# endif
return res;
}
NTSTATUS
nt_raw_SetInformationFile(HANDLE file_handle, PIO_STATUS_BLOCK io_status_block,
PVOID file_information, ULONG length,
FILE_INFORMATION_CLASS file_information_class)
{
NTSTATUS res;
res = NT_SYSCALL(SetInformationFile, file_handle, io_status_block, file_information,
length, file_information_class);
# ifdef DEBUG
if (!NT_SUCCESS(res)) {
NTLOG(GLOBAL, LOG_NT, 1, "nt_raw_SetInformationFile failed, res: %x\n", res);
}
# endif
return res;
}
NTSTATUS
nt_raw_SetInformationThread(HANDLE thread_handle,
THREADINFOCLASS thread_information_class,
PVOID thread_information, ULONG thread_information_length)
{
NTSTATUS res;
res = NT_SYSCALL(SetInformationThread, thread_handle, thread_information_class,
thread_information, thread_information_length);
# ifdef DEBUG
if (!NT_SUCCESS(res)) {
NTLOG(GLOBAL, LOG_NT, 1, "nt_raw_SetInformationThread failed, res: %x\n", res);
}
# endif
return res;
}
NTSTATUS
nt_raw_UnmapViewOfSection(HANDLE process_handle, PVOID base_address)
{
NTSTATUS res;
res = NT_SYSCALL(UnmapViewOfSection, process_handle, base_address);
# ifdef DEBUG
if (!NT_SUCCESS(res)) {
NTLOG(GLOBAL, LOG_NT, 1, "nt_raw_UnmapViewOfSection failed, res: %x\n", res);
}
# endif
return res;
}
#endif /* !NOT_DYNAMORIO_CORE_PROPER && !NOT_DYNAMORIO_CORE */
GET_RAW_SYSCALL(MapViewOfSection, IN HANDLE SectionHandle, IN HANDLE ProcessHandle,
IN OUT PVOID *BaseAddress, IN ULONG_PTR ZeroBits, IN SIZE_T CommitSize,
IN OUT PLARGE_INTEGER SectionOffset OPTIONAL, IN OUT PSIZE_T ViewSize,
IN SECTION_INHERIT InheritDisposition, IN ULONG AllocationType,
IN ULONG Protect);
GET_RAW_SYSCALL(OpenProcess, PHANDLE process_handle, ACCESS_MASK desired_access,
POBJECT_ATTRIBUTES object_attributes, PCLIENT_ID client_id);
GET_RAW_SYSCALL(QueryFullAttributesFile, POBJECT_ATTRIBUTES object_attributes,
PFILE_NETWORK_OPEN_INFORMATION file_information);
GET_RAW_SYSCALL(OpenThreadToken, HANDLE thread_handle, ACCESS_MASK desired_access,
BOOLEAN open_as_self, PHANDLE token_handle);
GET_RAW_SYSCALL(OpenProcessToken, HANDLE process_handle, ACCESS_MASK desired_access,
PHANDLE token_handle);
NTSTATUS
nt_raw_MapViewOfSection(HANDLE section_handle, HANDLE process_handle, PVOID *base_address,
ULONG_PTR zero_bits, SIZE_T commit_size,
PLARGE_INTEGER section_offset, PSIZE_T view_size,
SECTION_INHERIT inherit_disposition, ULONG allocation_type,
ULONG win32_protect)
{
NTSTATUS res;
res = NT_SYSCALL(MapViewOfSection, section_handle, process_handle, base_address,
zero_bits, commit_size, section_offset, view_size,
inherit_disposition, allocation_type, win32_protect);
#ifdef DEBUG
if (!NT_SUCCESS(res)) {
NTLOG(GLOBAL, LOG_NT, 1, "nt_raw_MapViewOfSection failed, res: %x\n", res);
}
#endif
return res;
}
NTSTATUS
nt_raw_OpenProcess(PHANDLE process_handle, ACCESS_MASK desired_access,
POBJECT_ATTRIBUTES object_attributes, PCLIENT_ID client_id)
{
NTSTATUS res;
res = NT_SYSCALL(OpenProcess, process_handle, desired_access, object_attributes,
client_id);
#ifdef DEBUG
if (!NT_SUCCESS(res)) {
NTLOG(GLOBAL, LOG_NT, 1, "nt_raw_OpenProcess failed, res: %x\n", res);
}
#endif
return res;
}
NTSTATUS
nt_raw_QueryFullAttributesFile(POBJECT_ATTRIBUTES object_attributes,
PFILE_NETWORK_OPEN_INFORMATION file_information)
{
NTSTATUS res;
res = NT_SYSCALL(QueryFullAttributesFile, object_attributes, file_information);
#ifdef DEBUG
if (!NT_SUCCESS(res)) {
NTLOG(GLOBAL, LOG_NT, 1, "nt_raw_QueryFullAttributesFile failed, res: %x\n", res);
}
#endif
return res;
}
NTSTATUS
nt_raw_CreateKey(PHANDLE key_handle, ACCESS_MASK desired_access,
POBJECT_ATTRIBUTES object_attributes, ULONG title_index,
PUNICODE_STRING class, ULONG create_options, PULONG disposition)
{
NTSTATUS res;
res = NT_SYSCALL(CreateKey, key_handle, desired_access, object_attributes,
title_index, class, create_options, disposition);
#ifdef DEBUG
if (!NT_SUCCESS(res)) {
NTLOG(GLOBAL, LOG_NT, 1, "nt_raw_CreateKey failed, res: %x\n", res);
}
#endif
return res;
}
NTSTATUS
nt_raw_OpenThreadToken(HANDLE thread_handle, ACCESS_MASK desired_access,
BOOLEAN open_as_self, PHANDLE token_handle)
{
NTSTATUS res;
res = NT_SYSCALL(OpenThreadToken, thread_handle, desired_access, open_as_self,
token_handle);
#ifdef DEBUG
if (!NT_SUCCESS(res)) {
NTLOG(GLOBAL, LOG_NT, 1, "nt_raw_OpenThreadToken failed, res: %x\n", res);
}
#endif
return res;
}
NTSTATUS
nt_raw_OpenProcessToken(HANDLE process_handle, ACCESS_MASK desired_access,
PHANDLE token_handle)
{
NTSTATUS res;
res = NT_SYSCALL(OpenProcessToken, process_handle, desired_access, token_handle);
#ifdef DEBUG
if (!NT_SUCCESS(res)) {
NTLOG(GLOBAL, LOG_NT, 1, "nt_raw_OpenProcessToken failed, res: %x\n", res);
}
#endif
return res;
}
| 37.834351 | 90 | 0.652774 | [
"object"
] |
e7a920aadb3efcdf160d62b1a7e48a91b57ddb15 | 6,585 | c | C | host/src/tests/tests_helper/tests_file.c | ARM-software/Cryptocell-713-TEE-Lib | bc0aca96f9769bba1a5927aa2bc6b82ceee94dea | [
"BSD-3-Clause"
] | 2 | 2021-06-14T17:29:27.000Z | 2021-07-04T00:13:39.000Z | host/src/tests/tests_helper/tests_file.c | QPC-database/Cryptocell-713-TEE-Lib | bc0aca96f9769bba1a5927aa2bc6b82ceee94dea | [
"BSD-3-Clause"
] | null | null | null | host/src/tests/tests_helper/tests_file.c | QPC-database/Cryptocell-713-TEE-Lib | bc0aca96f9769bba1a5927aa2bc6b82ceee94dea | [
"BSD-3-Clause"
] | 5 | 2021-01-24T11:06:38.000Z | 2021-07-04T00:13:40.000Z | /*
* Copyright (c) 2001-2019, Arm Limited and Contributors. All rights reserved.
*
* SPDX-License-Identifier: BSD-3-Clause OR Arm's non-OSI source license
*
*/
#include <stdlib.h>
#include <string.h>
#include "test_pal_log.h"
#define NUM_OF_CHARS_FOR_BYTE 4
#define INT_MIN (~0x7fffffff) /* -2147483648 and 0x80000000 are unsigned */
/* minimum value for an object of type int */
#define INT_MAX 0x7fffffff
/* maximum value for an object of type int */
/******************************************************************************/
int Tests_CopyDataToBinFile (unsigned char *fileName, unsigned char *inBuff, unsigned int inBuffLen)
{
int rc = 0;
size_t actualWriten = 0;
FILE *fd;
if ((NULL == fileName) ||
(NULL == inBuff) ||
(0 == inBuffLen)) {
TEST_PRINTF_ERROR( "ilegal parameters for %s\n", __func__);
return 1;
}
fd = fopen((char *)fileName, "wb");
if (NULL == fd) {
TEST_PRINTF_ERROR( "failed to open file %s for writing\n", fileName);
return 2;
}
actualWriten = fwrite(inBuff, 1, inBuffLen, fd);
if (actualWriten != inBuffLen) {
TEST_PRINTF_ERROR( "failed to write data to file actual written %lu, expected %d\n", (unsigned long)actualWriten, inBuffLen);
rc = 2;
}
fclose(fd);
return rc;
}
int Tests_CopyDataFromBinFile (unsigned char *fileName, unsigned char *outBuff,
unsigned int *outBuffLen)
{
FILE *fd;
int actualRead = 0;
int maxBytesToRead = 0;
unsigned int actualFileLen = 0;
int ch;
if ((NULL == fileName) ||
(NULL == outBuff) ||
(0 == *outBuffLen)) {
TEST_PRINTF_ERROR( "ilegal parameters for %s\n", __func__);
return 1;
}
fd = fopen((char *)fileName, "rb");
if (NULL == fd) {
TEST_PRINTF_ERROR( "failed to open file %s for reading\n", fileName);
return 2;
}
/* Get file length */
fseek(fd, 0, SEEK_END);
actualFileLen=ftell(fd);
fseek(fd, 0, SEEK_SET);
/* calculate max bytes to read. should be the min of bytes in file and buffer size*/
maxBytesToRead = (actualFileLen > *outBuffLen)?*outBuffLen:actualFileLen;
if ( 0 == maxBytesToRead) {
TEST_PRINTF_ERROR( "ilegal case: maxBytesToRead = 0\n");
fclose(fd);
return 2;
}
if ( actualFileLen > (unsigned int)(*outBuffLen) ){
TEST_PRINTF_ERROR( "ilegal case: actualFileLen (%d) > *outBuffLen (%d)\n", actualFileLen, *outBuffLen);
fclose(fd);
return 2;
}
/* read file content */
actualRead = fread(outBuff, 1, maxBytesToRead, fd);
ch = (int)outBuff[actualRead-1];
if (EOF == ch) {
actualRead--;
}
*outBuffLen = actualRead;
fclose(fd);
return 0;
}
int Tests_BinFileSize(char *fileName, size_t *outBuffLen)
{
FILE *fd;
unsigned int actualFileLen = 0;
if ((NULL == fileName) || (NULL == outBuffLen)) {
TEST_PRINTF_ERROR("illegal parameters for %s\n", __func__);
return 1;
}
fd = fopen((char *) fileName, "rb");
if (NULL == fd) {
TEST_PRINTF_ERROR("failed to open file %s for reading\n", fileName);
return 2;
}
/* Get file length */
fseek(fd, 0, SEEK_END);
actualFileLen = ftell(fd);
fseek(fd, 0, SEEK_SET);
*outBuffLen = actualFileLen;
fclose(fd);
return 0;
}
int Tests_CopyDataFromTextCommaSepFile (unsigned char *fileName, unsigned char *outBuff,
unsigned int *outBuffLen)
{
int status = 0;
FILE *fd;
int i = 0, j=0, k=0;
unsigned int actualFileLen=0;
int tempNum=0;
int actualRead=0;
int maxBytesToRead = 0;
char *filebufptr = NULL;
char str[NUM_OF_CHARS_FOR_BYTE+1];
if ((NULL == fileName) ||
(NULL == outBuff) ||
(NULL == outBuffLen)) {
TEST_PRINTF_ERROR( "ilegal parameters for %s\n", __func__);
return 1;
}
if (0 == *outBuffLen) {
TEST_PRINTF_ERROR( "ilegal outBuffLen \n");
return 1;
}
fd = fopen((char *)fileName, "rt");
if (NULL == fd) {
TEST_PRINTF_ERROR( "failed to open file %s for reading\n", fileName);
return 1;
}
memset(outBuff, 0, *outBuffLen);
/* Get file length */
fseek(fd, 0, SEEK_END);
actualFileLen = ftell(fd);
fseek(fd, 0, SEEK_SET);
/* calculate max bytes to read. should be the min of bytes in file and buffer size*/
maxBytesToRead = (actualFileLen > (*outBuffLen*5))?(*outBuffLen*5):actualFileLen;
if (0 == maxBytesToRead) {
TEST_PRINTF_ERROR( "ilegal maxBytesToRead == 0\n");
status = 1;
goto EXIT;
}
/* allocate buffer for data from file */
filebufptr = (char*)malloc(maxBytesToRead+1);
if (filebufptr == NULL) {
TEST_PRINTF_ERROR( "failed to allocate memory\n");
status = 1;
goto EXIT;
}
/* NULL terminated string to avoid buffer overflow of the sscanf that is used later */
filebufptr[maxBytesToRead] = '\0';
/* read file content */
actualRead = fread(filebufptr, 1, maxBytesToRead, fd);
j=0;
k=0;
for (i=0; i<actualRead; i++) {
if ((((filebufptr[i] >= '0') && (filebufptr[i] <= '9')) ||
((filebufptr[i] >= 'a') && (filebufptr[i] <= 'f')) ||
((filebufptr[i] >= 'A') && (filebufptr[i] <= 'a')) ||
(filebufptr[i] == 'x') || (filebufptr[i] == 'X')) &&
(k<NUM_OF_CHARS_FOR_BYTE)) {
str[k++] = filebufptr[i];
} else {
if ((filebufptr[i] == ',') ||
(filebufptr[i] == '\n') ||
(filebufptr[i] == '\0')) {
if (k>0) {
str[k] = '\0';
tempNum = strtol(str, NULL, 16);
if ((INT_MIN == tempNum) ||
(INT_MAX == tempNum)) {
TEST_PRINTF_ERROR( "strtol failed. check file name %s\n", fileName);
status = 1;
goto EXIT_AND_FREE;
}
outBuff[j++] = tempNum;
k = 0;
}
continue;
} else {
TEST_PRINTF_ERROR( "ilegal char in file %c offset %d within file name %s\n", filebufptr[i], i, fileName);
status = 1;
goto EXIT_AND_FREE;
}
}
}
*outBuffLen = j;
EXIT_AND_FREE:
free(filebufptr);
EXIT:
fclose(fd);
return status;
}
| 28.630435 | 133 | 0.543052 | [
"object"
] |
e7b484d9a3c24781a7b4ba87d2ec1638f156b5dc | 2,142 | h | C | node_modules/nodegit/include/remote_create_options.h | CirrusMD/github-action-homebrew-release | 6404df212db80d4006ba28fec928e7380e5019da | [
"MIT"
] | 1 | 2021-04-02T11:14:53.000Z | 2021-04-02T11:14:53.000Z | node_modules/nodegit/include/remote_create_options.h | AbdulWahab0/abdul.wahab | 89c1e2d3cca309626723d0f3f621e21d71c5b978 | [
"MIT"
] | 1 | 2021-04-03T06:42:56.000Z | 2021-04-04T02:26:47.000Z | node_modules/nodegit/include/remote_create_options.h | AbdulWahab0/abdul.wahab | 89c1e2d3cca309626723d0f3f621e21d71c5b978 | [
"MIT"
] | null | null | null | // This is a generated file, modify: generate/templates/templates/struct_header.h
#ifndef GITREMOTECREATEOPTIONS_H
#define GITREMOTECREATEOPTIONS_H
#include <nan.h>
#include <string>
#include <queue>
#include <utility>
#include <unordered_map>
#include "async_baton.h"
#include "callback_wrapper.h"
#include "reference_counter.h"
#include "nodegit_wrapper.h"
extern "C" {
#include <git2.h>
}
#include "../include/repository.h"
using namespace node;
using namespace v8;
class GitRemoteCreateOptions;
struct GitRemoteCreateOptionsTraits {
typedef GitRemoteCreateOptions cppClass;
typedef git_remote_create_options cType;
static const bool isDuplicable = false;
static void duplicate(git_remote_create_options **dest, git_remote_create_options *src) {
Nan::ThrowError("duplicate called on GitRemoteCreateOptions which cannot be duplicated");
}
static const bool isSingleton = false;
static const bool isFreeable = true;
static void free(git_remote_create_options *raw) {
unsigned long referenceCount = 0;
if (referenceCount == 0) {
::free(raw); // :: to avoid calling this free recursively
}
}
};
class GitRemoteCreateOptions : public NodeGitWrapper<GitRemoteCreateOptionsTraits> {
// grant full access to base class
friend class NodeGitWrapper<GitRemoteCreateOptionsTraits>;
public:
GitRemoteCreateOptions(git_remote_create_options* raw, bool selfFreeing, v8::Local<v8::Object> owner = v8::Local<v8::Object>());
static void InitializeComponent (v8::Local<v8::Object> target);
private:
GitRemoteCreateOptions();
~GitRemoteCreateOptions();
void ConstructFields();
static NAN_GETTER(GetVersion);
static NAN_SETTER(SetVersion);
Nan::Persistent<Object> repository;
static NAN_GETTER(GetRepository);
static NAN_SETTER(SetRepository);
static NAN_GETTER(GetName);
static NAN_SETTER(SetName);
static NAN_GETTER(GetFetchspec);
static NAN_SETTER(SetFetchspec);
static NAN_GETTER(GetFlags);
static NAN_SETTER(SetFlags);
};
#endif
| 25.807229 | 132 | 0.720355 | [
"object"
] |
e7b58173876bbc09d39da1749c474f3c096f6211 | 3,522 | c | C | dabba/help.c | eroullit/dabba | 83cfbefb7a9b45769e16f8519103ce0229f76e5b | [
"MIT"
] | 1 | 2018-04-21T16:44:17.000Z | 2018-04-21T16:44:17.000Z | dabba/help.c | eroullit/dabba | 83cfbefb7a9b45769e16f8519103ce0229f76e5b | [
"MIT"
] | null | null | null | dabba/help.c | eroullit/dabba | 83cfbefb7a9b45769e16f8519103ce0229f76e5b | [
"MIT"
] | null | null | null | /**
* \file help.c
* \author written by Emmanuel Roullit emmanuel.roullit@gmail.com (C) 2013
* \date 2013
*/
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <getopt.h>
#include <assert.h>
#include <limits.h>
#include <libdabba/macros.h>
static const char dabba_usage_string[] =
"dabba [--help] [--version] <command> [<subcommand>] <action> [<args>]\n";
static const char dabba_more_info_string[] =
"See 'dabba help <command> [<subcommand>]' for more specific information.";
struct cmdname_help {
char name[16];
char help[80];
};
/**
* \brief print option list to \c stdout
* \param[in] opt Pointer to option array
*/
void show_usage(const struct option *opt)
{
assert(opt);
printf("%s", dabba_usage_string);
while (opt->name != NULL) {
printf(" --%s", opt->name);
if (opt->has_arg == required_argument)
printf(" <arg>\n");
else if (opt->has_arg == optional_argument)
printf(" [arg]\n");
else
printf("\n");
opt++;
}
}
/**
* \internal
* \brief add some indenting on \c stdout
* \param[in] c Character to indent
* \param[in] num Indent level
*/
static inline void mput_char(const char c, uint32_t num)
{
while (num--)
putchar(c);
}
/**
* \brief print on \c stdout that the invoked command is unknown
* \param[in] cmd Pointer to invoked command string
*/
void help_unknown_cmd(const char *const cmd)
{
assert(cmd);
printf("'%s' is not a dabba command. See 'dabba --help'.\n", cmd);
}
/**
* \brief list on \c stdout the commonly used commands.
*/
static void list_common_cmds_help(void)
{
size_t i, longest = 0;
static struct cmdname_help common_cmds[] = {
{"interface", "perform an interface related command"},
{"thread", "perform a thread related command"},
{"capture", "capture live traffic from an interface"},
{"replay", "replay traffic from a pcap file"}
};
for (i = 0; i < ARRAY_SIZE(common_cmds); i++) {
if (longest < strlen(common_cmds[i].name))
longest = strlen(common_cmds[i].name);
}
printf("The most commonly used dabba commands are:\n");
for (i = 0; i < ARRAY_SIZE(common_cmds); i++) {
printf(" %s ", common_cmds[i].name);
mput_char(' ', longest - strlen(common_cmds[i].name));
printf("%s\n", common_cmds[i].help);
}
}
/**
* \brief Print help
* \param[in] argc Argument counter
* \param[in] argv Argument vector
* \return Returns 0 when the help could be printed, \c errno otherwise
*
* This function prints the basic dabba usage help message.
* Furthermore, it lists all available command.
*/
int cmd_help(int argc, const char **argv)
{
char help_name[NAME_MAX];
int rc = 0, a;
size_t offset;
if (argc < 1 || !argv[0]) {
printf("usage: %s\n\n", dabba_usage_string);
list_common_cmds_help();
printf("\n%s\n", dabba_more_info_string);
} else {
offset = snprintf(help_name, sizeof(help_name), "dabba");
for (a = 0; a < argc; a++)
offset +=
snprintf(&help_name[offset],
sizeof(help_name) - offset, "-%s",
argv[a]);
rc = execlp("man", "man", help_name, NULL);
}
return rc ? errno : rc;
}
/**
* \brief Print tool version number to \c stdout
* \param[in] argc Argument counter
* \param[in] argv Argument vector
* \return Always returns zero.
*/
int cmd_version(int argc, const char **argv)
{
(void)argc;
(void)argv;
printf("dabba version %s\n", DABBA_VERSION);
return 0;
}
| 23.171053 | 79 | 0.629188 | [
"vector"
] |
e7b6cf3c481a9123370ac3e9ad2729ec04d927d5 | 1,254 | h | C | dtool/src/dtoolbase/indent.h | ethanlindley/panda3d | 2bc35287d1af4e2c5d2f8a3c58d62d35446ca6f7 | [
"PHP-3.0",
"PHP-3.01"
] | 3 | 2020-01-02T08:43:36.000Z | 2020-07-05T08:59:02.000Z | dtool/src/dtoolbase/indent.h | ethanlindley/panda3d | 2bc35287d1af4e2c5d2f8a3c58d62d35446ca6f7 | [
"PHP-3.0",
"PHP-3.01"
] | null | null | null | dtool/src/dtoolbase/indent.h | ethanlindley/panda3d | 2bc35287d1af4e2c5d2f8a3c58d62d35446ca6f7 | [
"PHP-3.0",
"PHP-3.01"
] | 1 | 2020-03-11T17:38:45.000Z | 2020-03-11T17:38:45.000Z | /**
* PANDA 3D SOFTWARE
* Copyright (c) Carnegie Mellon University. All rights reserved.
*
* All use of this software is subject to the terms of the revised BSD
* license. You should have received a copy of this license along
* with this source code in a file named "LICENSE."
*
* @file indent.h
* @author drose
* @date 1999-01-16
*/
#ifndef INDENT_H
#define INDENT_H
#include "dtoolbase.h"
/**
* A handy function for doing text formatting. This function simply outputs
* the indicated number of spaces to the given output stream, returning the
* stream itself. Useful for indenting a series of lines of text by a given
* amount.
*/
EXPCL_DTOOL ostream &
indent(ostream &out, int indent_level);
/**
* Writes a list of things to the indicated output stream, with a space
* separating each item. One or more lines will be written, and the lines
* will automatically be broken such that no line exceeds max_col columns if
* possible.
*/
template<class InputIterator>
void
write_long_list(ostream &out, int indent_level,
InputIterator ifirst, InputIterator ilast,
string first_prefix = "",
string later_prefix = "",
int max_col = 72);
#include "indent.I"
#endif
| 27.866667 | 76 | 0.698565 | [
"3d"
] |
e7c76d42811fd5e00afcdffcfde9124025b4fa7b | 29,536 | h | C | src/third_party/mozjs/extract/js/src/ds/OrderedHashTable.h | benety/mongo | 203430ac9559f82ca01e3cbb3b0e09149fec0835 | [
"Apache-2.0"
] | null | null | null | src/third_party/mozjs/extract/js/src/ds/OrderedHashTable.h | benety/mongo | 203430ac9559f82ca01e3cbb3b0e09149fec0835 | [
"Apache-2.0"
] | null | null | null | src/third_party/mozjs/extract/js/src/ds/OrderedHashTable.h | benety/mongo | 203430ac9559f82ca01e3cbb3b0e09149fec0835 | [
"Apache-2.0"
] | null | null | null | /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
* vim: set ts=8 sts=2 et sw=2 tw=80:
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#ifndef ds_OrderedHashTable_h
#define ds_OrderedHashTable_h
/*
* Define two collection templates, js::OrderedHashMap and js::OrderedHashSet.
* They are like js::HashMap and js::HashSet except that:
*
* - Iterating over an Ordered hash table visits the entries in the order in
* which they were inserted. This means that unlike a HashMap, the behavior
* of an OrderedHashMap is deterministic (as long as the HashPolicy methods
* are effect-free and consistent); the hashing is a pure performance
* optimization.
*
* - Range objects over Ordered tables remain valid even when entries are
* added or removed or the table is resized. (However in the case of
* removing entries, note the warning on class Range below.)
*
* - The API is a little different, so it's not a drop-in replacement.
* In particular, the hash policy is a little different.
* Also, the Ordered templates lack the Ptr and AddPtr types.
*
* Hash policies
*
* See the comment about "Hash policy" in HashTable.h for general features that
* hash policy classes must provide. Hash policies for OrderedHashMaps and Sets
* differ in that the hash() method takes an extra argument:
* static js::HashNumber hash(Lookup, const HashCodeScrambler&);
* They must additionally provide a distinguished "empty" key value and the
* following static member functions:
* bool isEmpty(const Key&);
* void makeEmpty(Key*);
*/
#include "mozilla/HashFunctions.h"
#include "mozilla/MemoryReporting.h"
#include <utility>
#include "js/HashTable.h"
namespace js {
namespace detail {
/*
* detail::OrderedHashTable is the underlying data structure used to implement
* both OrderedHashMap and OrderedHashSet. Programs should use one of those two
* templates rather than OrderedHashTable.
*/
template <class T, class Ops, class AllocPolicy>
class OrderedHashTable {
public:
using Key = typename Ops::KeyType;
using Lookup = typename Ops::Lookup;
struct Data {
T element;
Data* chain;
Data(const T& e, Data* c) : element(e), chain(c) {}
Data(T&& e, Data* c) : element(std::move(e)), chain(c) {}
};
class Range;
friend class Range;
private:
Data** hashTable; // hash table (has hashBuckets() elements)
Data* data; // data vector, an array of Data objects
// data[0:dataLength] are constructed
uint32_t dataLength; // number of constructed elements in data
uint32_t dataCapacity; // size of data, in elements
uint32_t liveCount; // dataLength less empty (removed) entries
uint32_t hashShift; // multiplicative hash shift
Range* ranges; // list of all live Ranges on this table in malloc memory
Range*
nurseryRanges; // list of all live Ranges on this table in the GC nursery
AllocPolicy alloc;
mozilla::HashCodeScrambler hcs; // don't reveal pointer hash codes
// TODO: This should be templated on a functor type and receive lambda
// arguments but this causes problems for the hazard analysis builds. See
// bug 1398213.
template <void (*f)(Range* range, uint32_t arg)>
void forEachRange(uint32_t arg = 0) {
Range* next;
for (Range* r = ranges; r; r = next) {
next = r->next;
f(r, arg);
}
for (Range* r = nurseryRanges; r; r = next) {
next = r->next;
f(r, arg);
}
}
public:
OrderedHashTable(AllocPolicy ap, mozilla::HashCodeScrambler hcs)
: hashTable(nullptr),
data(nullptr),
dataLength(0),
dataCapacity(0),
liveCount(0),
hashShift(0),
ranges(nullptr),
nurseryRanges(nullptr),
alloc(std::move(ap)),
hcs(hcs) {}
[[nodiscard]] bool init() {
MOZ_ASSERT(!hashTable, "init must be called at most once");
uint32_t buckets = initialBuckets();
Data** tableAlloc = alloc.template pod_malloc<Data*>(buckets);
if (!tableAlloc) {
return false;
}
for (uint32_t i = 0; i < buckets; i++) {
tableAlloc[i] = nullptr;
}
uint32_t capacity = uint32_t(buckets * fillFactor());
Data* dataAlloc = alloc.template pod_malloc<Data>(capacity);
if (!dataAlloc) {
alloc.free_(tableAlloc, buckets);
return false;
}
// clear() requires that members are assigned only after all allocation
// has succeeded, and that this->ranges is left untouched.
hashTable = tableAlloc;
data = dataAlloc;
dataLength = 0;
dataCapacity = capacity;
liveCount = 0;
hashShift = js::kHashNumberBits - initialBucketsLog2();
MOZ_ASSERT(hashBuckets() == buckets);
return true;
}
~OrderedHashTable() {
forEachRange<Range::onTableDestroyed>();
if (hashTable) {
// |hashBuckets()| isn't valid when |hashTable| hasn't been created.
alloc.free_(hashTable, hashBuckets());
}
freeData(data, dataLength, dataCapacity);
}
size_t sizeOfExcludingThis(mozilla::MallocSizeOf mallocSizeOf) const {
size_t size = 0;
if (hashTable) {
size += mallocSizeOf(hashTable);
}
if (data) {
size += mallocSizeOf(data);
}
return size;
}
/* Return the number of elements in the table. */
uint32_t count() const { return liveCount; }
/* True if any element matches l. */
bool has(const Lookup& l) const { return lookup(l) != nullptr; }
/* Return a pointer to the element, if any, that matches l, or nullptr. */
T* get(const Lookup& l) {
Data* e = lookup(l, prepareHash(l));
return e ? &e->element : nullptr;
}
/* Return a pointer to the element, if any, that matches l, or nullptr. */
const T* get(const Lookup& l) const {
return const_cast<OrderedHashTable*>(this)->get(l);
}
/*
* If the table already contains an entry that matches |element|,
* replace that entry with |element|. Otherwise add a new entry.
*
* On success, return true, whether there was already a matching element or
* not. On allocation failure, return false. If this returns false, it
* means the element was not added to the table.
*/
template <typename ElementInput>
[[nodiscard]] bool put(ElementInput&& element) {
HashNumber h = prepareHash(Ops::getKey(element));
if (Data* e = lookup(Ops::getKey(element), h)) {
e->element = std::forward<ElementInput>(element);
return true;
}
if (dataLength == dataCapacity) {
// If the hashTable is more than 1/4 deleted data, simply rehash in
// place to free up some space. Otherwise, grow the table.
uint32_t newHashShift =
liveCount >= dataCapacity * 0.75 ? hashShift - 1 : hashShift;
if (!rehash(newHashShift)) {
return false;
}
}
h >>= hashShift;
liveCount++;
Data* e = &data[dataLength++];
new (e) Data(std::forward<ElementInput>(element), hashTable[h]);
hashTable[h] = e;
return true;
}
/*
* If the table contains an element matching l, remove it and set *foundp
* to true. Otherwise set *foundp to false.
*
* Return true on success, false if we tried to shrink the table and hit an
* allocation failure. Even if this returns false, *foundp is set correctly
* and the matching element was removed. Shrinking is an optimization and
* it's OK for it to fail.
*/
bool remove(const Lookup& l, bool* foundp) {
// Note: This could be optimized so that removing the last entry,
// data[dataLength - 1], decrements dataLength. LIFO use cases would
// benefit.
// If a matching entry exists, empty it.
Data* e = lookup(l, prepareHash(l));
if (e == nullptr) {
*foundp = false;
return true;
}
*foundp = true;
liveCount--;
Ops::makeEmpty(&e->element);
// Update active Ranges.
uint32_t pos = e - data;
forEachRange<&Range::onRemove>(pos);
// If many entries have been removed, try to shrink the table.
if (hashBuckets() > initialBuckets() &&
liveCount < dataLength * minDataFill()) {
if (!rehash(hashShift + 1)) {
return false;
}
}
return true;
}
/*
* Remove all entries.
*
* Returns false on OOM, leaving the OrderedHashTable and any live Ranges
* in the old state.
*
* The effect on live Ranges is the same as removing all entries; in
* particular, those Ranges are still live and will see any entries added
* after a successful clear().
*/
[[nodiscard]] bool clear() {
if (dataLength != 0) {
Data** oldHashTable = hashTable;
Data* oldData = data;
uint32_t oldHashBuckets = hashBuckets();
uint32_t oldDataLength = dataLength;
uint32_t oldDataCapacity = dataCapacity;
hashTable = nullptr;
if (!init()) {
// init() only mutates members on success; see comment above.
hashTable = oldHashTable;
return false;
}
alloc.free_(oldHashTable, oldHashBuckets);
freeData(oldData, oldDataLength, oldDataCapacity);
forEachRange<&Range::onClear>();
}
MOZ_ASSERT(hashTable);
MOZ_ASSERT(data);
MOZ_ASSERT(dataLength == 0);
MOZ_ASSERT(liveCount == 0);
return true;
}
/*
* Ranges are used to iterate over OrderedHashTables.
*
* Suppose 'Map' is some instance of OrderedHashMap, and 'map' is a Map.
* Then you can walk all the key-value pairs like this:
*
* for (Map::Range r = map.all(); !r.empty(); r.popFront()) {
* Map::Entry& pair = r.front();
* ... do something with pair ...
* }
*
* Ranges remain valid for the lifetime of the OrderedHashTable, even if
* entries are added or removed or the table is resized. Don't do anything
* to a Range, except destroy it, after the OrderedHashTable has been
* destroyed. (We support destroying the two objects in either order to
* humor the GC, bless its nondeterministic heart.)
*
* Warning: The behavior when the current front() entry is removed from the
* table is subtly different from js::HashTable<>::Enum::removeFront()!
* HashTable::Enum doesn't skip any entries when you removeFront() and then
* popFront(). OrderedHashTable::Range does! (This is useful for using a
* Range to implement JS Map.prototype.iterator.)
*
* The workaround is to call popFront() as soon as possible,
* before there's any possibility of modifying the table:
*
* for (Map::Range r = map.all(); !r.empty(); ) {
* Key key = r.front().key; // this won't modify map
* Value val = r.front().value; // this won't modify map
* r.popFront();
* // ...do things that might modify map...
* }
*/
class Range {
friend class OrderedHashTable;
// Cannot be a reference since we need to be able to do
// |offsetof(Range, ht)|.
OrderedHashTable* ht;
/* The index of front() within ht->data. */
uint32_t i;
/*
* The number of nonempty entries in ht->data to the left of front().
* This is used when the table is resized or compacted.
*/
uint32_t count;
/*
* Links in the doubly-linked list of active Ranges on ht.
*
* prevp points to the previous Range's .next field;
* or to ht->ranges if this is the first Range in the list.
* next points to the next Range;
* or nullptr if this is the last Range in the list.
*
* Invariant: *prevp == this.
*/
Range** prevp;
Range* next;
/*
* Create a Range over all the entries in ht.
* (This is private on purpose. End users must use ht->all().)
*/
Range(OrderedHashTable* ht, Range** listp)
: ht(ht), i(0), count(0), prevp(listp), next(*listp) {
*prevp = this;
if (next) {
next->prevp = &next;
}
seek();
}
public:
Range(const Range& other)
: ht(other.ht),
i(other.i),
count(other.count),
prevp(&ht->ranges),
next(ht->ranges) {
*prevp = this;
if (next) {
next->prevp = &next;
}
}
~Range() {
*prevp = next;
if (next) {
next->prevp = prevp;
}
}
private:
// Prohibit copy assignment.
Range& operator=(const Range& other) = delete;
void seek() {
while (i < ht->dataLength &&
Ops::isEmpty(Ops::getKey(ht->data[i].element))) {
i++;
}
}
/*
* The hash table calls this when an entry is removed.
* j is the index of the removed entry.
*/
void onRemove(uint32_t j) {
MOZ_ASSERT(valid());
if (j < i) {
count--;
}
if (j == i) {
seek();
}
}
/*
* The hash table calls this when the table is resized or compacted.
* Since |count| is the number of nonempty entries to the left of
* front(), discarding the empty entries will not affect count, and it
* will make i and count equal.
*/
void onCompact() {
MOZ_ASSERT(valid());
i = count;
}
/* The hash table calls this when cleared. */
void onClear() {
MOZ_ASSERT(valid());
i = count = 0;
}
bool valid() const { return next != this; }
void onTableDestroyed() {
MOZ_ASSERT(valid());
prevp = &next;
next = this;
}
public:
bool empty() const {
MOZ_ASSERT(valid());
return i >= ht->dataLength;
}
/*
* Return the first element in the range. This must not be called if
* this->empty().
*
* Warning: Removing an entry from the table also removes it from any
* live Ranges, and a Range can become empty that way, rendering
* front() invalid. If in doubt, check empty() before calling front().
*/
T& front() {
MOZ_ASSERT(valid());
MOZ_ASSERT(!empty());
return ht->data[i].element;
}
/*
* Remove the first element from this range.
* This must not be called if this->empty().
*
* Warning: Removing an entry from the table also removes it from any
* live Ranges, and a Range can become empty that way, rendering
* popFront() invalid. If in doubt, check empty() before calling
* popFront().
*/
void popFront() {
MOZ_ASSERT(valid());
MOZ_ASSERT(!empty());
MOZ_ASSERT(!Ops::isEmpty(Ops::getKey(ht->data[i].element)));
count++;
i++;
seek();
}
/*
* Change the key of the front entry.
*
* This calls Ops::hash on both the current key and the new key.
* Ops::hash on the current key must return the same hash code as
* when the entry was added to the table.
*/
void rekeyFront(const Key& k) {
MOZ_ASSERT(valid());
Data& entry = ht->data[i];
HashNumber oldHash =
ht->prepareHash(Ops::getKey(entry.element)) >> ht->hashShift;
HashNumber newHash = ht->prepareHash(k) >> ht->hashShift;
Ops::setKey(entry.element, k);
if (newHash != oldHash) {
// Remove this entry from its old hash chain. (If this crashes
// reading nullptr, it would mean we did not find this entry on
// the hash chain where we expected it. That probably means the
// key's hash code changed since it was inserted, breaking the
// hash code invariant.)
Data** ep = &ht->hashTable[oldHash];
while (*ep != &entry) {
ep = &(*ep)->chain;
}
*ep = entry.chain;
// Add it to the new hash chain. We could just insert it at the
// beginning of the chain. Instead, we do a bit of work to
// preserve the invariant that hash chains always go in reverse
// insertion order (descending memory order). No code currently
// depends on this invariant, so it's fine to kill it if
// needed.
ep = &ht->hashTable[newHash];
while (*ep && *ep > &entry) {
ep = &(*ep)->chain;
}
entry.chain = *ep;
*ep = &entry;
}
}
static size_t offsetOfHashTable() { return offsetof(Range, ht); }
static size_t offsetOfI() { return offsetof(Range, i); }
static size_t offsetOfCount() { return offsetof(Range, count); }
static size_t offsetOfPrevP() { return offsetof(Range, prevp); }
static size_t offsetOfNext() { return offsetof(Range, next); }
static void onTableDestroyed(Range* range, uint32_t arg) {
range->onTableDestroyed();
}
static void onRemove(Range* range, uint32_t arg) { range->onRemove(arg); }
static void onClear(Range* range, uint32_t arg) { range->onClear(); }
static void onCompact(Range* range, uint32_t arg) { range->onCompact(); }
};
Range all() { return Range(this, &ranges); }
/*
* Allocate a new Range, possibly in nursery memory. The buffer must be
* large enough to hold a Range object.
*
* All nursery-allocated ranges can be freed in one go by calling
* destroyNurseryRanges().
*/
Range* createRange(void* buffer, bool inNursery) {
auto range = static_cast<Range*>(buffer);
new (range) Range(this, inNursery ? &nurseryRanges : &ranges);
return range;
}
void destroyNurseryRanges() { nurseryRanges = nullptr; }
/*
* Change the value of the given key.
*
* This calls Ops::hash on both the current key and the new key.
* Ops::hash on the current key must return the same hash code as
* when the entry was added to the table.
*/
void rekeyOneEntry(const Key& current, const Key& newKey, const T& element) {
if (current == newKey) {
return;
}
Data* entry = lookup(current, prepareHash(current));
if (!entry) {
return;
}
HashNumber oldHash = prepareHash(current) >> hashShift;
HashNumber newHash = prepareHash(newKey) >> hashShift;
entry->element = element;
// Remove this entry from its old hash chain. (If this crashes
// reading nullptr, it would mean we did not find this entry on
// the hash chain where we expected it. That probably means the
// key's hash code changed since it was inserted, breaking the
// hash code invariant.)
Data** ep = &hashTable[oldHash];
while (*ep != entry) {
ep = &(*ep)->chain;
}
*ep = entry->chain;
// Add it to the new hash chain. We could just insert it at the
// beginning of the chain. Instead, we do a bit of work to
// preserve the invariant that hash chains always go in reverse
// insertion order (descending memory order). No code currently
// depends on this invariant, so it's fine to kill it if
// needed.
ep = &hashTable[newHash];
while (*ep && *ep > entry) {
ep = &(*ep)->chain;
}
entry->chain = *ep;
*ep = entry;
}
static size_t offsetOfDataLength() {
return offsetof(OrderedHashTable, dataLength);
}
static size_t offsetOfData() { return offsetof(OrderedHashTable, data); }
static constexpr size_t offsetOfDataElement() {
static_assert(offsetof(Data, element) == 0,
"RangeFront and RangePopFront depend on offsetof(Data, "
"element) being 0");
return offsetof(Data, element);
}
static constexpr size_t sizeofData() { return sizeof(Data); }
private:
/* Logarithm base 2 of the number of buckets in the hash table initially. */
static uint32_t initialBucketsLog2() { return 1; }
static uint32_t initialBuckets() { return 1 << initialBucketsLog2(); }
/*
* The maximum load factor (mean number of entries per bucket).
* It is an invariant that
* dataCapacity == floor(hashBuckets() * fillFactor()).
*
* The fill factor should be between 2 and 4, and it should be chosen so that
* the fill factor times sizeof(Data) is close to but <= a power of 2.
* This fixed fill factor was chosen to make the size of the data
* array, in bytes, close to a power of two when sizeof(T) is 16.
*/
static double fillFactor() { return 8.0 / 3.0; }
/*
* The minimum permitted value of (liveCount / dataLength).
* If that ratio drops below this value, we shrink the table.
*/
static double minDataFill() { return 0.25; }
public:
HashNumber prepareHash(const Lookup& l) const {
return mozilla::ScrambleHashCode(Ops::hash(l, hcs));
}
private:
/* The size of hashTable, in elements. Always a power of two. */
uint32_t hashBuckets() const {
return 1 << (js::kHashNumberBits - hashShift);
}
static void destroyData(Data* data, uint32_t length) {
for (Data* p = data + length; p != data;) {
(--p)->~Data();
}
}
void freeData(Data* data, uint32_t length, uint32_t capacity) {
destroyData(data, length);
alloc.free_(data, capacity);
}
Data* lookup(const Lookup& l, HashNumber h) {
for (Data* e = hashTable[h >> hashShift]; e; e = e->chain) {
if (Ops::match(Ops::getKey(e->element), l)) {
return e;
}
}
return nullptr;
}
const Data* lookup(const Lookup& l) const {
return const_cast<OrderedHashTable*>(this)->lookup(l, prepareHash(l));
}
/* This is called after rehashing the table. */
void compacted() {
// If we had any empty entries, compacting may have moved live entries
// to the left within |data|. Notify all live Ranges of the change.
forEachRange<&Range::onCompact>();
}
/* Compact the entries in |data| and rehash them. */
void rehashInPlace() {
for (uint32_t i = 0, N = hashBuckets(); i < N; i++) {
hashTable[i] = nullptr;
}
Data* wp = data;
Data* end = data + dataLength;
for (Data* rp = data; rp != end; rp++) {
if (!Ops::isEmpty(Ops::getKey(rp->element))) {
HashNumber h = prepareHash(Ops::getKey(rp->element)) >> hashShift;
if (rp != wp) {
wp->element = std::move(rp->element);
}
wp->chain = hashTable[h];
hashTable[h] = wp;
wp++;
}
}
MOZ_ASSERT(wp == data + liveCount);
while (wp != end) {
(--end)->~Data();
}
dataLength = liveCount;
compacted();
}
/*
* Grow, shrink, or compact both |hashTable| and |data|.
*
* On success, this returns true, dataLength == liveCount, and there are no
* empty elements in data[0:dataLength]. On allocation failure, this
* leaves everything as it was and returns false.
*/
[[nodiscard]] bool rehash(uint32_t newHashShift) {
// If the size of the table is not changing, rehash in place to avoid
// allocating memory.
if (newHashShift == hashShift) {
rehashInPlace();
return true;
}
size_t newHashBuckets = size_t(1) << (js::kHashNumberBits - newHashShift);
Data** newHashTable = alloc.template pod_malloc<Data*>(newHashBuckets);
if (!newHashTable) {
return false;
}
for (uint32_t i = 0; i < newHashBuckets; i++) {
newHashTable[i] = nullptr;
}
uint32_t newCapacity = uint32_t(newHashBuckets * fillFactor());
Data* newData = alloc.template pod_malloc<Data>(newCapacity);
if (!newData) {
alloc.free_(newHashTable, newHashBuckets);
return false;
}
Data* wp = newData;
Data* end = data + dataLength;
for (Data* p = data; p != end; p++) {
if (!Ops::isEmpty(Ops::getKey(p->element))) {
HashNumber h = prepareHash(Ops::getKey(p->element)) >> newHashShift;
new (wp) Data(std::move(p->element), newHashTable[h]);
newHashTable[h] = wp;
wp++;
}
}
MOZ_ASSERT(wp == newData + liveCount);
alloc.free_(hashTable, hashBuckets());
freeData(data, dataLength, dataCapacity);
hashTable = newHashTable;
data = newData;
dataLength = liveCount;
dataCapacity = newCapacity;
hashShift = newHashShift;
MOZ_ASSERT(hashBuckets() == newHashBuckets);
compacted();
return true;
}
// Not copyable.
OrderedHashTable& operator=(const OrderedHashTable&) = delete;
OrderedHashTable(const OrderedHashTable&) = delete;
};
} // namespace detail
template <class Key, class Value, class OrderedHashPolicy, class AllocPolicy>
class OrderedHashMap {
public:
class Entry {
template <class, class, class>
friend class detail::OrderedHashTable;
void operator=(const Entry& rhs) {
const_cast<Key&>(key) = rhs.key;
value = rhs.value;
}
void operator=(Entry&& rhs) {
MOZ_ASSERT(this != &rhs, "self-move assignment is prohibited");
const_cast<Key&>(key) = std::move(rhs.key);
value = std::move(rhs.value);
}
public:
Entry() : key(), value() {}
template <typename V>
Entry(const Key& k, V&& v) : key(k), value(std::forward<V>(v)) {}
Entry(Entry&& rhs) : key(std::move(rhs.key)), value(std::move(rhs.value)) {}
const Key key;
Value value;
static size_t offsetOfKey() { return offsetof(Entry, key); }
static size_t offsetOfValue() { return offsetof(Entry, value); }
};
private:
struct MapOps : OrderedHashPolicy {
using KeyType = Key;
static void makeEmpty(Entry* e) {
OrderedHashPolicy::makeEmpty(const_cast<Key*>(&e->key));
// Clear the value. Destroying it is another possibility, but that
// would complicate class Entry considerably.
e->value = Value();
}
static const Key& getKey(const Entry& e) { return e.key; }
static void setKey(Entry& e, const Key& k) { const_cast<Key&>(e.key) = k; }
};
typedef detail::OrderedHashTable<Entry, MapOps, AllocPolicy> Impl;
Impl impl;
public:
using Range = typename Impl::Range;
OrderedHashMap(AllocPolicy ap, mozilla::HashCodeScrambler hcs)
: impl(std::move(ap), hcs) {}
[[nodiscard]] bool init() { return impl.init(); }
uint32_t count() const { return impl.count(); }
bool has(const Key& key) const { return impl.has(key); }
Range all() { return impl.all(); }
const Entry* get(const Key& key) const { return impl.get(key); }
Entry* get(const Key& key) { return impl.get(key); }
bool remove(const Key& key, bool* foundp) { return impl.remove(key, foundp); }
[[nodiscard]] bool clear() { return impl.clear(); }
template <typename V>
[[nodiscard]] bool put(const Key& key, V&& value) {
return impl.put(Entry(key, std::forward<V>(value)));
}
HashNumber hash(const Key& key) const { return impl.prepareHash(key); }
void rekeyOneEntry(const Key& current, const Key& newKey) {
const Entry* e = get(current);
if (!e) {
return;
}
return impl.rekeyOneEntry(current, newKey, Entry(newKey, e->value));
}
Range* createRange(void* buffer, bool inNursery) {
return impl.createRange(buffer, inNursery);
}
void destroyNurseryRanges() { impl.destroyNurseryRanges(); }
static size_t offsetOfEntryKey() { return Entry::offsetOfKey(); }
static size_t offsetOfImplDataLength() { return Impl::offsetOfDataLength(); }
static size_t offsetOfImplData() { return Impl::offsetOfData(); }
static constexpr size_t offsetOfImplDataElement() {
return Impl::offsetOfDataElement();
}
static constexpr size_t sizeofImplData() { return Impl::sizeofData(); }
size_t sizeOfExcludingThis(mozilla::MallocSizeOf mallocSizeOf) const {
return impl.sizeOfExcludingThis(mallocSizeOf);
}
size_t sizeOfIncludingThis(mozilla::MallocSizeOf mallocSizeOf) const {
return mallocSizeOf(this) + sizeOfExcludingThis(mallocSizeOf);
}
};
template <class T, class OrderedHashPolicy, class AllocPolicy>
class OrderedHashSet {
private:
struct SetOps : OrderedHashPolicy {
using KeyType = const T;
static const T& getKey(const T& v) { return v; }
static void setKey(const T& e, const T& v) { const_cast<T&>(e) = v; }
};
typedef detail::OrderedHashTable<T, SetOps, AllocPolicy> Impl;
Impl impl;
public:
using Range = typename Impl::Range;
explicit OrderedHashSet(AllocPolicy ap, mozilla::HashCodeScrambler hcs)
: impl(std::move(ap), hcs) {}
[[nodiscard]] bool init() { return impl.init(); }
uint32_t count() const { return impl.count(); }
bool has(const T& value) const { return impl.has(value); }
Range all() { return impl.all(); }
[[nodiscard]] bool put(const T& value) { return impl.put(value); }
bool remove(const T& value, bool* foundp) {
return impl.remove(value, foundp);
}
[[nodiscard]] bool clear() { return impl.clear(); }
HashNumber hash(const T& value) const { return impl.prepareHash(value); }
void rekeyOneEntry(const T& current, const T& newKey) {
return impl.rekeyOneEntry(current, newKey, newKey);
}
Range* createRange(void* buffer, bool inNursery) {
return impl.createRange(buffer, inNursery);
}
void destroyNurseryRanges() { impl.destroyNurseryRanges(); }
static size_t offsetOfEntryKey() { return 0; }
static size_t offsetOfImplDataLength() { return Impl::offsetOfDataLength(); }
static size_t offsetOfImplData() { return Impl::offsetOfData(); }
static constexpr size_t offsetOfImplDataElement() {
return Impl::offsetOfDataElement();
}
static constexpr size_t sizeofImplData() { return Impl::sizeofData(); }
size_t sizeOfExcludingThis(mozilla::MallocSizeOf mallocSizeOf) const {
return impl.sizeOfExcludingThis(mallocSizeOf);
}
size_t sizeOfIncludingThis(mozilla::MallocSizeOf mallocSizeOf) const {
return mallocSizeOf(this) + sizeOfExcludingThis(mallocSizeOf);
}
};
} // namespace js
#endif /* ds_OrderedHashTable_h */
| 32.104348 | 80 | 0.635428 | [
"object",
"vector"
] |
e7c9fac90d484beda7bde632ff44e0899179ade9 | 5,176 | h | C | dev/Gems/NvCloth/Code/Source/Components/ClothComponentMesh/ClothComponentMesh.h | BenjaminHCheung/lumberyard | f875f9634ebb128d1bbb5334720596e19cb6db54 | [
"AML"
] | 1 | 2021-07-09T06:32:31.000Z | 2021-07-09T06:32:31.000Z | dev/Gems/NvCloth/Code/Source/Components/ClothComponentMesh/ClothComponentMesh.h | BenjaminHCheung/lumberyard | f875f9634ebb128d1bbb5334720596e19cb6db54 | [
"AML"
] | null | null | null | dev/Gems/NvCloth/Code/Source/Components/ClothComponentMesh/ClothComponentMesh.h | BenjaminHCheung/lumberyard | f875f9634ebb128d1bbb5334720596e19cb6db54 | [
"AML"
] | null | null | null | /*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#pragma once
#include <AzCore/Component/TickBus.h>
#include <AzCore/Component/TransformBus.h>
#include <AzFramework/Physics/WindBus.h>
#include <LmbrCentral/Rendering/MeshModificationBus.h>
#include <System/ClothConfiguration.h>
#include <NvCloth/SystemBus.h>
#include <Utils/AssetHelper.h>
#include <Utils/TangentSpaceCalculation.h>
namespace NvCloth
{
class Cloth;
class ActorClothColliders;
class ActorClothSkinning;
class ClothDebugDisplay;
//! Class that handles cloth simulation and updating the
//! rendering vertex data on the correct render mesh for an entity.
class ClothComponentMesh
: public LmbrCentral::MeshModificationNotificationBus::Handler
, public SystemNotificationsBus::Handler
, public AZ::TransformNotificationBus::Handler
, public Physics::WindNotificationsBus::Handler
{
public:
AZ_RTTI(ClothComponentMesh, "{15A0F10C-6248-4CE4-A6FD-0E2D8AFCFEE8}");
ClothComponentMesh(AZ::EntityId entityId, const ClothConfiguration& config);
~ClothComponentMesh();
AZ_DISABLE_COPY_MOVE(ClothComponentMesh);
void UpdateConfiguration(AZ::EntityId entityId, const ClothConfiguration& config);
protected:
// Functions used to setup and tear down cloth component mesh
void Setup(AZ::EntityId entityId, const ClothConfiguration& config);
void TearDown();
// SystemNotificationsBus::Handler overrides
void OnPreUpdateClothSimulation(float deltaTime) override;
void OnPostUpdateClothSimulation(float deltaTime) override;
// AZ::TransformNotificationBus::Handler overrides
void OnTransformChanged(const AZ::Transform& local, const AZ::Transform& world) override;
// LmbrCentral::MeshModificationNotificationBus::Handler overrides
void ModifyMesh(size_t lodIndex, size_t primitiveIndex, IRenderMesh* renderMesh) override;
// Physics::WindNotificationsBus::Handler overrides
void OnGlobalWindChanged() override;
void OnWindChanged(const AZ::Aabb& aabb) override;
private:
// Rendering data. Stores the final particles that are going to be sent for rendering.
// Particles are the result of blending cloth simulation and skinning animation.
// It also stores the tangent space reference systems of each particle that are calculated every frame.
struct RenderData
{
AZStd::vector<SimParticleType> m_particles;
TangentSpaceCalculation m_tangentSpaces;
};
AZStd::vector<SimParticleType>& GetRenderParticles();
const AZStd::vector<SimParticleType>& GetRenderParticles() const;
TangentSpaceCalculation& GetRenderTangentSpaces();
const TangentSpaceCalculation& GetRenderTangentSpaces() const;
void ClearData();
void SetTransform(const AZ::Transform& worldTransform);
// Update functions called every frame in OnTick
void UpdateSimulationCollisions();
void UpdateSimulationStaticParticles();
void BlendSkinningAnimation();
void RecalculateTangentSpaces();
bool IsClothFullySimulated() const;
bool IsClothFullyAnimated() const;
void UpdateWindVelocity();
void UpdateWindVelocity(const AZ::Vector3& position);
// Entity Id of the cloth component
AZ::EntityId m_entityId;
// Configuration parameters of cloth simulation
ClothConfiguration m_config;
// Instance of cloth simulation
AZStd::unique_ptr<Cloth> m_clothSimulation;
// Original UVs of the mesh, they are used to calculate tangent space data.
AZStd::vector<SimUVType> m_meshInitialUVs;
// Use a double buffer of render data to always have access to the previous frame's data.
// The previous frame's data is used to workaround that debug draw is one frame delayed.
static const AZ::u32 RenderDataBufferSize = 2;
AZ::u32 m_renderDataBufferIndex = 0;
AZStd::array<RenderData, RenderDataBufferSize> m_renderDataBuffer;
// Information to map the simulation particles to render mesh nodes.
MeshNodeInfo m_meshNodeInfo;
// Cloth Colliders from the character
AZStd::unique_ptr<ActorClothColliders> m_actorClothColliders;
// Cloth Skinning from the character
AZStd::unique_ptr<ActorClothSkinning> m_actorClothSkinning;
AZStd::unique_ptr<ClothDebugDisplay> m_clothDebugDisplay;
friend class ClothDebugDisplay; // Give access to data to draw debug information
};
} // namespace NvCloth
| 38.626866 | 111 | 0.71619 | [
"mesh",
"render",
"vector",
"transform"
] |
e7cfa5b116a26f3ff2bddd293af08e248b57ab8b | 3,874 | h | C | src/compact_filter.h | caipengbo/kvrocks-annotated | a9b186bb8671304686747f2eedeb5b58dd2890bf | [
"BSD-3-Clause"
] | null | null | null | src/compact_filter.h | caipengbo/kvrocks-annotated | a9b186bb8671304686747f2eedeb5b58dd2890bf | [
"BSD-3-Clause"
] | null | null | null | src/compact_filter.h | caipengbo/kvrocks-annotated | a9b186bb8671304686747f2eedeb5b58dd2890bf | [
"BSD-3-Clause"
] | null | null | null | #pragma once
#include <vector>
#include <memory>
#include <string>
#include <rocksdb/db.h>
#include <rocksdb/compaction_filter.h>
#include "redis_metadata.h"
#include "redis_slot.h"
#include "storage.h"
namespace Engine {
// 该功能就是 RocksDB 在 compaction 每一条数据时,都会调用一个 Filter 函数 ,TTL 功能就是这样实现的
class MetadataFilter : public rocksdb::CompactionFilter {
public:
const char *Name() const override { return "MetadataFilter"; }
bool Filter(int level, const Slice &key, const Slice &value,
std::string *new_value, bool *modified) const override;
};
class MetadataFilterFactory : public rocksdb::CompactionFilterFactory {
public:
MetadataFilterFactory() = default;
const char *Name() const override { return "MetadataFilterFactory"; }
std::unique_ptr<rocksdb::CompactionFilter> CreateCompactionFilter(
const rocksdb::CompactionFilter::Context &context) override {
return std::unique_ptr<rocksdb::CompactionFilter>(new MetadataFilter());
}
};
class SubKeyFilter : public rocksdb::CompactionFilter {
public:
explicit SubKeyFilter(Storage *storage)
: cached_key_(""),
cached_metadata_(""),
stor_(storage) {}
const char *Name() const override { return "SubkeyFilter"; }
bool IsKeyExpired(const InternalKey &ikey, const Slice &value) const;
bool Filter(int level, const Slice &key, const Slice &value,
std::string *new_value, bool *modified) const override;
protected:
mutable std::string cached_key_;
mutable std::string cached_metadata_;
Engine::Storage *stor_;
};
class SubKeyFilterFactory : public rocksdb::CompactionFilterFactory {
public:
explicit SubKeyFilterFactory(Engine::Storage *storage) {
stor_ = storage;
}
const char *Name() const override { return "SubKeyFilterFactory"; }
std::unique_ptr<rocksdb::CompactionFilter> CreateCompactionFilter(
const rocksdb::CompactionFilter::Context &context) override {
return std::unique_ptr<rocksdb::CompactionFilter>(
new SubKeyFilter(stor_));
}
private:
Engine::Storage *stor_ = nullptr;
};
class PubSubFilter : public rocksdb::CompactionFilter {
public:
const char *Name() const override { return "PubSubFilter"; }
bool Filter(int level, const Slice &key, const Slice &value,
std::string *new_value, bool *modified) const override { return true; }
};
class PubSubFilterFactory : public rocksdb::CompactionFilterFactory {
public:
PubSubFilterFactory() = default;
const char *Name() const override { return "PubSubFilterFactory"; }
std::unique_ptr<rocksdb::CompactionFilter> CreateCompactionFilter(
const rocksdb::CompactionFilter::Context &context) override {
return std::unique_ptr<rocksdb::CompactionFilter>(new PubSubFilter());
}
};
class SlotKeyFilter : public rocksdb::CompactionFilter {
public:
explicit SlotKeyFilter(Storage *storage)
: cached_key_(""),
cached_metadata_(""),
stor_(storage) {}
const char *Name() const override { return "SlotKeyFilter"; }
bool IsKeyDeleted(const SlotInternalKey &ikey, const Slice &value) const;
bool Filter(int level, const Slice &key, const Slice &value,
std::string *new_value, bool *modified) const override;
protected:
mutable std::string cached_key_;
mutable std::string cached_metadata_;
Engine::Storage *stor_;
};
class SlotKeyFilterFactory : public rocksdb::CompactionFilterFactory {
public:
explicit SlotKeyFilterFactory(Engine::Storage *storage) {
stor_ = storage;
}
const char *Name() const override { return "SlotKeyFilterFactory"; }
std::unique_ptr<rocksdb::CompactionFilter> CreateCompactionFilter(
const rocksdb::CompactionFilter::Context &context) override {
return std::unique_ptr<rocksdb::CompactionFilter>(
new SlotKeyFilter(stor_));
}
private:
Engine::Storage *stor_ = nullptr;
};
} // namespace Engine
| 32.283333 | 85 | 0.726123 | [
"vector"
] |
e7d0b911c8c30ed43fad9ef362487ccf223ed7ea | 5,163 | h | C | gdal/ogr/ogrsf_frmts/ili/imdreader.h | Symena/gdal | 8f98f340b676b37fc681f08138557be81fd47470 | [
"MIT"
] | null | null | null | gdal/ogr/ogrsf_frmts/ili/imdreader.h | Symena/gdal | 8f98f340b676b37fc681f08138557be81fd47470 | [
"MIT"
] | null | null | null | gdal/ogr/ogrsf_frmts/ili/imdreader.h | Symena/gdal | 8f98f340b676b37fc681f08138557be81fd47470 | [
"MIT"
] | null | null | null | /******************************************************************************
* $Id$
*
* Project: Interlis 1/2 Translator
* Purpose: IlisMeta model reader.
* Author: Pirmin Kalberer, Sourcepole AG
*
******************************************************************************
* Copyright (c) 2014, Pirmin Kalberer, Sourcepole AG
*
* 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.
****************************************************************************/
#ifndef IMDREADER_H_INCLUDED
#define IMDREADER_H_INCLUDED
#include "cpl_vsi.h"
#include "cpl_error.h"
#include "ogr_feature.h"
#include <list>
#include <map>
class GeomFieldInfo
{
OGRFeatureDefn* geomTable; /* separate geometry table for Ili 1 */
public:
CPLString iliGeomType;
GeomFieldInfo() : geomTable(NULL) {};
~GeomFieldInfo() {
if( geomTable )
geomTable->Release();
}
GeomFieldInfo(const GeomFieldInfo& other)
{
geomTable = other.geomTable;
if( geomTable )
geomTable->Reference();
iliGeomType = other.iliGeomType;
}
GeomFieldInfo& operator= (const GeomFieldInfo& other)
{
if( this != &other )
{
if( geomTable )
geomTable->Release();
geomTable = other.geomTable;
if( geomTable )
geomTable->Reference();
iliGeomType = other.iliGeomType;
}
return *this;
}
OGRFeatureDefn* GetGeomTableDefnRef() const { return geomTable; }
void SetGeomTableDefn(OGRFeatureDefn* geomTableIn)
{
CPLAssert(geomTable == NULL);
geomTable = geomTableIn;
if( geomTable )
geomTable->Reference();
}
};
typedef std::map<CPLString,GeomFieldInfo> GeomFieldInfos; /* key: geom field name, value: ILI geom field info */
typedef std::map<CPLString,CPLString> StructFieldInfos; /* key: struct field name, value: struct table */
class FeatureDefnInfo
{
OGRFeatureDefn* poTableDefn;
public:
GeomFieldInfos poGeomFieldInfos;
StructFieldInfos poStructFieldInfos;
FeatureDefnInfo() : poTableDefn(NULL) {};
~FeatureDefnInfo() {
if( poTableDefn )
poTableDefn->Release();
}
FeatureDefnInfo(const FeatureDefnInfo& other)
{
poTableDefn = other.poTableDefn;
if( poTableDefn )
poTableDefn->Reference();
poGeomFieldInfos = other.poGeomFieldInfos;
poStructFieldInfos = other.poStructFieldInfos;
}
FeatureDefnInfo& operator= (const FeatureDefnInfo& other)
{
if( this != &other )
{
if( poTableDefn )
poTableDefn->Release();
poTableDefn = other.poTableDefn;
if( poTableDefn )
poTableDefn->Reference();
poGeomFieldInfos = other.poGeomFieldInfos;
poStructFieldInfos = other.poStructFieldInfos;
}
return *this;
}
OGRFeatureDefn* GetTableDefnRef() const { return poTableDefn; }
void SetTableDefn(OGRFeatureDefn* poTableDefnIn)
{
CPLAssert(poTableDefn == NULL);
poTableDefn= poTableDefnIn;
if( poTableDefn )
poTableDefn->Reference();
}
};
typedef std::list<FeatureDefnInfo> FeatureDefnInfos;
class IliModelInfo
{
public:
CPLString name;
CPLString version;
CPLString uri;
};
typedef std::list<IliModelInfo> IliModelInfos;
class ImdReader
{
public: // TODO(schwehr): Private?
int iliVersion; /* 1 or 2 */
IliModelInfos modelInfos;
CPLString mainModelName;
CPLString mainBasketName;
CPLString mainTopicName;
FeatureDefnInfos featureDefnInfos;
char codeBlank;
char codeUndefined;
char codeContinue;
public:
ImdReader(int iliVersion);
~ImdReader();
void ReadModel(const char *pszFilename);
FeatureDefnInfo GetFeatureDefnInfo(const char *pszLayerName);
};
#endif /* IMDREADER_H_INCLUDED */
| 31.87037 | 112 | 0.612435 | [
"geometry",
"model"
] |
e7d72d755baa9959ab0a7a7d15fe5e06ac28f746 | 3,883 | c | C | contrib/sebsd/libsemanage/src/iface_record.c | TrustedBSD/sebsd | fd5de6f587183087cf930779701d5713e8ca64cc | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | 4 | 2017-04-06T21:39:15.000Z | 2019-10-09T17:34:14.000Z | contrib/sebsd/libsemanage/src/iface_record.c | TrustedBSD/sebsd | fd5de6f587183087cf930779701d5713e8ca64cc | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | null | null | null | contrib/sebsd/libsemanage/src/iface_record.c | TrustedBSD/sebsd | fd5de6f587183087cf930779701d5713e8ca64cc | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | 1 | 2020-01-04T06:36:39.000Z | 2020-01-04T06:36:39.000Z | /* Copyright (C) 2005 Red Hat, Inc. */
/* Object: semanage_iface_t (Network Interface)
* Object: semanage_iface_key_t (Network Interface Key)
* Implements: record_t (Database Record)
* Implements: record_key_t (Database Record Key)
*/
#include <sepol/context_record.h>
#include <sepol/iface_record.h>
typedef sepol_context_t semanage_context_t;
typedef sepol_iface_t semanage_iface_t;
typedef sepol_iface_key_t semanage_iface_key_t;
#define _SEMANAGE_CONTEXT_DEFINED_
#define _SEMANAGE_IFACE_DEFINED_
typedef sepol_iface_t record_t;
typedef sepol_iface_key_t record_key_t;
#define DBASE_RECORD_DEFINED
#include "iface_internal.h"
#include "handle.h"
#include "database.h"
/* Key */
int semanage_iface_compare(const semanage_iface_t * iface,
const semanage_iface_key_t * key)
{
return sepol_iface_compare(iface, key);
}
hidden_def(semanage_iface_compare)
int semanage_iface_compare2(const semanage_iface_t * iface,
const semanage_iface_t * iface2)
{
return sepol_iface_compare2(iface, iface2);
}
hidden_def(semanage_iface_compare2)
static int semanage_iface_compare2_qsort(const semanage_iface_t ** iface,
const semanage_iface_t ** iface2)
{
return sepol_iface_compare2(*iface, *iface2);
}
int semanage_iface_key_create(semanage_handle_t * handle,
const char *name, semanage_iface_key_t ** key_ptr)
{
return sepol_iface_key_create(handle->sepolh, name, key_ptr);
}
int semanage_iface_key_extract(semanage_handle_t * handle,
const semanage_iface_t * iface,
semanage_iface_key_t ** key_ptr)
{
return sepol_iface_key_extract(handle->sepolh, iface, key_ptr);
}
hidden_def(semanage_iface_key_extract)
void semanage_iface_key_free(semanage_iface_key_t * key)
{
sepol_iface_key_free(key);
}
hidden_def(semanage_iface_key_free)
/* Name */
const char *semanage_iface_get_name(const semanage_iface_t * iface)
{
return sepol_iface_get_name(iface);
}
hidden_def(semanage_iface_get_name)
int semanage_iface_set_name(semanage_handle_t * handle,
semanage_iface_t * iface, const char *name)
{
return sepol_iface_set_name(handle->sepolh, iface, name);
}
hidden_def(semanage_iface_set_name)
/* Context */
semanage_context_t *semanage_iface_get_ifcon(const semanage_iface_t * iface)
{
return sepol_iface_get_ifcon(iface);
}
hidden_def(semanage_iface_get_ifcon)
int semanage_iface_set_ifcon(semanage_handle_t * handle,
semanage_iface_t * iface, semanage_context_t * con)
{
return sepol_iface_set_ifcon(handle->sepolh, iface, con);
}
hidden_def(semanage_iface_set_ifcon)
semanage_context_t *semanage_iface_get_msgcon(const semanage_iface_t * iface)
{
return sepol_iface_get_msgcon(iface);
}
hidden_def(semanage_iface_get_msgcon)
int semanage_iface_set_msgcon(semanage_handle_t * handle,
semanage_iface_t * iface,
semanage_context_t * con)
{
return sepol_iface_set_msgcon(handle->sepolh, iface, con);
}
hidden_def(semanage_iface_set_msgcon)
/* Create/Clone/Destroy */
int semanage_iface_create(semanage_handle_t * handle,
semanage_iface_t ** iface_ptr)
{
return sepol_iface_create(handle->sepolh, iface_ptr);
}
hidden_def(semanage_iface_create)
int semanage_iface_clone(semanage_handle_t * handle,
const semanage_iface_t * iface,
semanage_iface_t ** iface_ptr)
{
return sepol_iface_clone(handle->sepolh, iface, iface_ptr);
}
hidden_def(semanage_iface_clone)
void semanage_iface_free(semanage_iface_t * iface)
{
sepol_iface_free(iface);
}
hidden_def(semanage_iface_free)
/* Record base functions */
record_table_t SEMANAGE_IFACE_RTABLE = {
.create = semanage_iface_create,
.key_extract = semanage_iface_key_extract,
.key_free = semanage_iface_key_free,
.clone = semanage_iface_clone,
.compare = semanage_iface_compare,
.compare2 = semanage_iface_compare2,
.compare2_qsort = semanage_iface_compare2_qsort,
.free = semanage_iface_free,
};
| 22.841176 | 77 | 0.790883 | [
"object"
] |
e7dbe53647e1655978993f0362463654e92c8446 | 2,625 | h | C | src/include/ocac/obj.h | tschiemer/ocac | 0a62f43b5044addd30a02c9b856fc7cc39fa21b1 | [
"MIT"
] | 7 | 2020-10-14T06:12:17.000Z | 2021-09-24T07:37:41.000Z | src/include/ocac/obj.h | tschiemer/ocac | 0a62f43b5044addd30a02c9b856fc7cc39fa21b1 | [
"MIT"
] | null | null | null | src/include/ocac/obj.h | tschiemer/ocac | 0a62f43b5044addd30a02c9b856fc7cc39fa21b1 | [
"MIT"
] | 1 | 2021-04-12T18:40:11.000Z | 2021-04-12T18:40:11.000Z | /**
* MIT License
*
* Copyright (c) 2020 Philip Tschiemer, https://github.com/tschiemer/ocac
*
* 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.
*
*/
#ifndef OCAC_OCAC_OBJ_H
#define OCAC_OCAC_OBJ_H
#include "ocac/occ/datatypes/framework.h"
#include "ocac/class.h"
#include "ocac/session.h"
#include "ocac/opt.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
* Any ONo below this number are reserved for standard use
*/
#define OCAC_RESERVED_ONOS 4096
#define OCAC_OBJ_DEF_BEGIN(name) \
PACK_STRUCT_BEGIN \
struct ocac_obj_ ## name { \
OcaONo ono; \
OCAC_CLASS_BASE * class_ptr; \
\
#define OCAC_OBJ_DEF_END(name) \
} PACK_STRUCT_STRUCT; \
PACK_STRUCT_END \
// End of class definition: name
// undefine forward declaration in class.h
#ifdef OCAC_OBJ_BASE
#undef OCAC_OBJ_BASE
#endif
#define OCAC_OBJ_TYPE(name) struct ocac_obj_ ## name
#define OCAC_OBJ_BASE OCAC_OBJ_TYPE(base)
#define OCAC_OBJ_CAST(name,obj_ptr) ((OCAC_OBJ_TYPE(name)*)obj_ptr)
#define OCAC_OBJ_PTR(obj_ptr) OCAC_OBJ_CAST(base, obj_ptr)
/** struct ocac_obj_base
* declaration of object base type
*
* When renaming remember to change forward declaration in class.h used for method pointers
*/
OCAC_OBJ_DEF_BEGIN(base)
OCAC_OBJ_DEF_END(base)
OcaStatus ocac_obj_exec(OCAC_OBJ_BASE * obj, u16_t deflevel, u16_t index, u8_t * argv, u32_t argvlen, u8_t * rsp, u32_t * rsplen, u32_t maxrsplen, struct ocac_session * session);
#ifdef DEBUG
void ocac_dump_obj( OCAC_OBJ_BASE * obj );
#endif
#ifdef __cplusplus
}
#endif
#endif //OCAC_OCAC_OBJ_H
| 29.166667 | 178 | 0.741333 | [
"object"
] |
e7e6038adb5adb7bf07584c033620a36981b4b4f | 10,130 | c | C | common/libmport/samples/riodp_test_server.c | RapidIO/RRMAP | 0e73fd45b272ceb8d732a144b7a2d8fe90dbe50e | [
"BSD-3-Clause"
] | 14 | 2017-08-30T09:39:29.000Z | 2022-03-28T13:38:44.000Z | common/libmport/samples/riodp_test_server.c | RapidIO/RRMAP | 0e73fd45b272ceb8d732a144b7a2d8fe90dbe50e | [
"BSD-3-Clause"
] | null | null | null | common/libmport/samples/riodp_test_server.c | RapidIO/RRMAP | 0e73fd45b272ceb8d732a144b7a2d8fe90dbe50e | [
"BSD-3-Clause"
] | 5 | 2017-02-17T03:54:36.000Z | 2019-09-05T11:04:13.000Z | /*
* Copyright 2014, 2015 Integrated Device Technology, Inc.
*
* User-space RIO_CM server test program.
*
* This software is available to you under a choice of one of two licenses.
* You may choose to be licensed under the terms of the GNU General Public
* License(GPL) Version 2, or the BSD-3 Clause license below:
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* \file
* \brief Server part of client/server test program for RapidIO channelized messaging.
*
* Listens for connection requests from remote peers and start a child process for new connection.
* Each child process receives a message from a client and echoes it back to the sender. This echo loop
* continues until the client closes connection (or server program is terminated by a signal).
*/
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>
#include <signal.h>
#include <unistd.h> /* for sleep() */
#include <sys/wait.h>
#include <stdint.h> /* For size_t */
#include <fcntl.h>
#include <sys/ioctl.h>
#include "rio_route.h"
#include "tok_parse.h"
#include "rapidio_mport_mgmt.h"
#include "rapidio_mport_sock.h"
#ifdef __cplusplus
extern "C" {
#endif
struct args {
uint32_t mport_id;
uint16_t loc_channel;
};
/// @endcond
static volatile sig_atomic_t srv_exit;
static volatile sig_atomic_t report_status;
static int srv_debug;
static void usage(char *program)
{
printf("%s - library test server\n", program);
printf("Usage:\n");
printf(" %s [options]\n", program);
printf("Options are:\n");
printf(" <mport> mport device index\n");
printf(" <channel> channel number to listen for connection requests\n");
printf(" [debug] enable debug output\n");
printf("\n");
}
static void srv_sig_handler(int signum)
{
switch (signum) {
case SIGTERM:
case SIGINT:
srv_exit = 1;
break;
case SIGUSR1:
report_status = 1;
break;
}
}
/**
* \brief Display available devices
*/
void show_rio_devs(void)
{
mport_list_t *mport_list = NULL;
mport_list_t *list_ptr;
uint8_t number_of_mports = RIO_MAX_MPORTS;
uint8_t mport_id;
did_val_t *ep_list = NULL;
uint32_t number_of_eps = 0;
uint32_t ep;
int i;
int ret;
/** - request from driver list of available local mport devices */
ret = riomp_mgmt_get_mport_list(&mport_list, &number_of_mports);
if (ret) {
printf("ERR: riomp_mgmt_get_mport_list() ERR %d\n", ret);
return;
}
printf("\nAvailable %d local mport(s):\n", number_of_mports);
if (number_of_mports > RIO_MAX_MPORTS) {
printf("WARNING: Only %d out of %d have been retrieved\n",
RIO_MAX_MPORTS, number_of_mports);
}
/** - for each local mport display list of remote RapidIO devices */
list_ptr = mport_list;
for (i = 0; i < number_of_mports; i++, list_ptr++) {
mport_id = *list_ptr >> 16;
printf("+++ mport_id: %u dest_id: %u\n", mport_id,
*list_ptr & 0xffff);
/* Display EPs for this MPORT */
ret = riomp_mgmt_get_ep_list(mport_id, &ep_list,
&number_of_eps);
if (ret) {
printf("ERR: riodp_ep_get_list() ERR %d\n", ret);
break;
}
printf("\t%u Endpoints (dest_ID): ", number_of_eps);
for (ep = 0; ep < number_of_eps; ep++) {
printf("%u ", *(ep_list + ep));
}
printf("\n");
ret = riomp_mgmt_free_ep_list(&ep_list);
if (ret) {
printf("ERR: riodp_ep_free_list() ERR %d\n", ret);
}
}
printf("\n");
ret = riomp_mgmt_free_mport_list(&mport_list);
if (ret) {
printf("ERR: riodp_ep_free_list() ERR %d\n", ret);
}
}
/**
* \brief Child process created by main() to service an individual connection.
*
* \param[in] new_socket Socket associated with this connection
* In a loop performs the following steps until terminated:
*/
void doprocessing(riomp_sock_t new_socket)
{
int ret = 0;
rapidio_mport_socket_msg *msg_rx = NULL;
printf("CM_SERVER processing child(%d) started\n", (int)getpid());
// use malloc to get rx buffer, because buffers aren't managed yet
msg_rx = (rapidio_mport_socket_msg *) malloc(sizeof(rapidio_mport_socket_msg));
if (msg_rx == NULL) {
printf("CM_SERVER(%d): error allocating rx buffer\n",
(int)getpid());
exit(1);
}
while (!srv_exit) {
/** - Receive an inbound message */
ret = riomp_sock_receive(new_socket, &msg_rx,
60 * 1000, &srv_exit);
//@sonar:off - c:S3584 Allocated memory not released
if (ret) {
printf("CM_SERVER(%d): riomp_sock_receive() ERR=%d\n",
(int)getpid(), ret);
break;
}
//@sonar:on
if (srv_debug) {
printf("CM_SERVER(%d): RX_MSG=%s\n", (int)getpid(),
(char *)msg_rx->msg.payload);
}
/** - Send a message back to the client */
ret = riomp_sock_send(new_socket, msg_rx,
sizeof(*msg_rx), &srv_exit);
if (ret) {
printf("CM_SERVER(%d): riomp_sock_send() ERR %d (%d)\n",
(int)getpid(), ret, errno);
break;
}
}
riomp_sock_release_receive_buffer(new_socket, msg_rx);
/** - Close a socket assigned to this process if connection closed by
* a client or process terminated */
ret = riomp_sock_close(&new_socket);
//@sonar:off - c:S3584 Allocated memory not released
if (ret) {
printf("CM_SERVER(%d): riomp_sock_close() ERR %d\n",
(int)getpid(), ret);
}
//@sonar:on
if (ret && ret != ECONNRESET) {
exit(1);
}
}
/**
* \brief Starting point for the program
*
* \param[in] argc Command line parameter count
* \param[in] argv Array of pointers to command line parameter null terminated
* strings
*
* \retval 0 means success
*
* When running without expected number of arguments displays list of available local
* and remote devices.
*
* Performs the following steps:
*/
int main(int argc, char** argv)
{
int ret = 0;
struct args arg;
riomp_mailbox_t mailbox = NULL;
riomp_sock_t socket = NULL;
riomp_sock_t new_socket = NULL;
pid_t pid, wpid;
int status = 0;
int tmp;
/** - Parse console arguments */
/** - If number of arguments is less than expected display help message and list of devices. */
if (argc < 3) {
usage(argv[0]);
show_rio_devs();
exit(EXIT_FAILURE);
}
if (tok_parse_mport_id(argv[1], &arg.mport_id, 0)) {
printf(TOK_ERR_MPORT_MSG_FMT);
exit(EXIT_FAILURE);
}
if (tok_parse_socket(argv[2], &arg.loc_channel, 0)) {
printf(TOK_ERR_SOCKET_MSG_FMT, "Channel number");
exit(EXIT_FAILURE);
}
if (argc == 4) {
srv_debug = 1;
}
/** - Trap signals that we expect to receive */
signal(SIGINT, srv_sig_handler);
signal(SIGTERM, srv_sig_handler);
signal(SIGUSR1, srv_sig_handler);
printf("CM_SERVER(%d): Running on RapidIO mport_%d\n", (int)getpid(),
arg.mport_id);
/** - Create rapidio_mport_mailbox control structure */
ret = riomp_sock_mbox_create_handle(arg.mport_id, 0, &mailbox);
if (ret) {
printf("CM_SERVER: riodp_mbox_init() ERR %d\n", ret);
goto out;
}
/** - Create a socket structure associated with given mailbox */
ret = riomp_sock_socket(mailbox, &socket);
if (ret) {
printf("CM_SERVER: riomp_sock_socket() ERR %d\n", ret);
goto out;
}
/** - Bind the listen channel to opened MPORT device */
ret = riomp_sock_bind(socket, arg.loc_channel);
if (ret) {
printf("CM_SERVER: riomp_sock_bind() ERR %d\n", ret);
goto out;
}
/** - Initiate LISTEN on the specified channel */
ret = riomp_sock_listen(socket);
if (ret) {
printf("CM_SERVER: riomp_sock_listen() ERR %d\n", ret);
goto out;
}
/** - Create child process for each accepted request */
while (!srv_exit) {
/* Create new socket object for accept */
ret = riomp_sock_socket(mailbox, &new_socket);
if (ret) {
printf("CM_SERVER(%d): riomp_sock_socket() ERR %d\n",
(int)getpid(), ret);
break;
}
while (1) {
wpid = waitpid(-1, &status, WNOHANG);
if (wpid != -1 && wpid != 0) {
printf(
"CM_SERVER(%d): terminated with status %d\n",
wpid, status);
} else {
break;
}
}
ret = riomp_sock_accept(socket, &new_socket, 3 * 60000,
&srv_exit); /* Time out = 3 min */
if (ret) {
printf("CM_SERVER(%d): riomp_sock_accept() ERR %d\n",
(int)getpid(), ret);
riomp_sock_close(&new_socket);
srv_exit = 2;
break;
}
// Create child process
pid = fork();
if (pid < 0) {
perror("CM_SERVER: ERROR on fork()\n");
exit(1);
}
if (pid == 0) {
// This is the child process
doprocessing(new_socket);
exit(0);
} else {
// TBD
}
free(new_socket);
}
out:
/** - Exit closing listening channel */
tmp = riomp_sock_close(&socket);
if (tmp) {
printf("CM_SERVER(%d): riomp_sock_close() ERR %d\n",
(int)getpid(), tmp);
}
/** - Release rapidio_mport_mailbox control structure */
tmp = riomp_sock_mbox_destroy_handle(&mailbox);
if (tmp) {
printf("riodp_mbox_shutdown error: %d\n", tmp);
}
return ret;
}
#ifdef __cplusplus
}
#endif
| 26.380208 | 103 | 0.6846 | [
"object"
] |
e7e8c8ed159590296b9efb4aba6371951859fa89 | 8,801 | h | C | src/optimizers/optimizers.h | asivokon/marian-dev | ab6b8260835a9f77a7b3cd48e3af4e4039280384 | [
"MIT"
] | 143 | 2017-08-27T19:01:38.000Z | 2022-03-16T18:13:44.000Z | src/optimizers/optimizers.h | asivokon/marian-dev | ab6b8260835a9f77a7b3cd48e3af4e4039280384 | [
"MIT"
] | 732 | 2017-07-21T15:32:27.000Z | 2022-03-22T10:26:09.000Z | src/optimizers/optimizers.h | asivokon/marian-dev | ab6b8260835a9f77a7b3cd48e3af4e4039280384 | [
"MIT"
] | 124 | 2017-08-31T13:51:21.000Z | 2022-03-23T13:58:17.000Z | #pragma once
#include "common/options.h"
#include "graph/expression_graph.h"
#include "optimizers/clippers.h"
#include "optimizers/exponential_smoothing.h"
#include "tensors/backend.h"
#include "tensors/tensor.h"
#include "training/training_state.h"
#include <algorithm>
#include <map>
#include <memory>
namespace marian {
/**
* Base class for optimizers.
*/
class OptimizerBase : public TrainingObserver, public ExponentialSmoothing {
public:
OptimizerBase(Ptr<Options> options)
: ExponentialSmoothing(options),
options_(options),
eta_(options_->get<float>("learn-rate")),
refMBWordsParam_(options_->get<size_t>("mini-batch-words-ref", 0)),
normalizedGradient_{options_->get<bool>("normalize-gradient", false)} // @TODO: get rid of this if we manage to confirm that it does not help with fp16 training
{
auto precisions = options_->get<std::vector<std::string>>("precision", {"float32", "float32"});
ABORT_IF(precisions.size() < 2, "No optimizer precision type specified??");
auto paramType = typeFromString(precisions[0]);
optimizerType_ = typeFromString(precisions[1]);
// if true model for forward/backward uses a different type than the optimizer
castOptimizerType_ = paramType != optimizerType_;
// automatic learning-rate adjustment
// If users provide, in addition to the hyper-parameters, a reference minibatch size,
// that these hyper-parameters were originally tuned for, then the learning-rate gets
// adjusted accordingly. Note: Requires user to also use ce-sum criterion.
if (refMBWordsParam_ != 0)
LOG_ONCE(info, "[optimizers] Learning rate gets automatically adjusted as if minibatch size was {}", refMBWordsParam_);
}
virtual ~OptimizerBase() {}
float update(Ptr<ExpressionGraph> graph, size_t mbSize, float costScaleFactor = 1.f) {
Tensor p = graph->params()->vals();
Tensor g = graph->params()->grads();
return update(p, g, mbSize, costScaleFactor);
}
float update(Tensor params, Tensor grads, size_t mbSize, float costScaleFactor = 1.f);
virtual void init(TrainingState& state) override {
eta_ = state.eta;
batchesSeen_ = state.batches;
}
virtual void actAfterLoaded(TrainingState& state) override {
eta_ = state.eta;
batchesSeen_ = state.batches;
}
virtual void actAfterEpoch(TrainingState& state) override {
eta_ = state.eta;
batchesSeen_ = state.batches;
if(state.reset)
resetStats();
}
virtual void actAfterBatches(TrainingState& state) override {
eta_ = state.eta;
batchesSeen_ = state.batches;
if(state.reset)
resetStats();
}
virtual void actAfterStalled(TrainingState& state) override {
eta_ = state.eta;
batchesSeen_ = state.batches;
if(state.reset)
resetStats();
}
virtual void setParams(const std::vector<float>& params) = 0;
typedef std::function<void(size_t /*localDeviceIndex*/,
const char* /*begin*/,
const char* /*end*/)> ScatterStateSetFunc;
typedef std::function<io::Item(size_t /*localDeviceIndex*/)> GatherStateGetFunc;
typedef std::function<void(const io::Item& /*data*/, const ScatterStateSetFunc& /*setFn*/)> ScatterStateFunc;
typedef std::function<io::Item(const GatherStateGetFunc& /*getFn*/)> GatherStateFunc;
virtual void load(std::vector<io::Item>& /*items*/,
const std::vector<Ptr<OptimizerBase>>& /*opts*/,
const std::vector<Ptr<Backend>>& /*backends*/,
const ScatterStateFunc& /*scatterFn*/,
bool isMainProcess);
virtual void save(std::vector<io::Item>& /*items*/,
const std::vector<Ptr<OptimizerBase>>& /*opts*/,
const GatherStateFunc& /*gatherFn*/,
bool isMainProcess);
// This function swaps out the current optimizer parameters with the smoothed version (provided smoothing is enabled).
// Usually we will call this twice, to swap in and to swap out.
void swapWithSmoothed(Tensor params);
// return stateful optimizer shards, for base that's only averaged parameters
virtual std::vector<Tensor> getShards() {
if(avg_)
return { avg_ };
else
return { };
}
protected:
virtual void updateImpl(Tensor params, Tensor grads, size_t actualMBSize) = 0;
virtual void resetStats() = 0;
Ptr<Options> options_;
float eta_; // Learning rate
size_t refMBWordsParam_{0}; // reference MB size. This enables automatic adjustment of optimizer hyper-parameters to MB size. 0 means no adjustment
size_t batchesSeen_{0}; // updates seen so far
bool normalizedGradient_{false}; // has the gradient been normalized by MB size? @TODO: get rid of this if we manage to confirm that it does not help with fp16 training
Type optimizerType_{Type::float32};
bool castOptimizerType_{false};
Ptr<Clipper> clipper_; // Clip gradient norm
Ptr<TensorAllocator> baseAlloc_;
Ptr<Allocator> alloc_;
Tensor avg_;
Tensor pm_;
Tensor gd_;
};
/**
* @brief Stochastic gradient descent optimizer.
*/
class Sgd : public OptimizerBase {
public:
Sgd(Ptr<Options> options) : OptimizerBase(options) {}
void load(std::vector<io::Item>& /*items*/,
const std::vector<Ptr<OptimizerBase>>& /*opts*/,
const std::vector<Ptr<Backend>>& /*backends*/,
const ScatterStateFunc& /*scatterFn*/,
bool isMainProcess) override;
void save(std::vector<io::Item>& items,
const std::vector<Ptr<OptimizerBase>>& opts,
const GatherStateFunc& gatherFn,
bool isMainProcess) override;
virtual void setParams(const std::vector<float>& /*params*/) override {}
private:
void updateImpl(Tensor params, Tensor grads, size_t actualMBSize) override;
virtual void resetStats() override {}
};
/**
* @brief Adagrad optimizer
*
* http://www.jmlr.org/papers/volume12/duchi11a/duchi11a.pdf
*/
class Adagrad : public OptimizerBase {
public:
Adagrad(Ptr<Options> options) : OptimizerBase(options) {}
void load(std::vector<io::Item>& /*items*/,
const std::vector<Ptr<OptimizerBase>>& /*opts*/,
const std::vector<Ptr<Backend>>& /*backends*/,
const ScatterStateFunc& /*scatterFn*/,
bool isMainProcess) override;
void save(std::vector<io::Item>& items,
const std::vector<Ptr<OptimizerBase>>& opts,
const GatherStateFunc& gatherFn,
bool isMainProcess) override;
void setParams(const std::vector<float>& params) override {
if(params.size() > 0)
eps_ = params[0];
}
std::vector<Tensor> getShards() override {
auto shards = OptimizerBase::getShards();
shards.push_back(gt_);
return shards;
}
private:
void updateImpl(Tensor params, Tensor grads, size_t actualMBSize) override;
void resetStats() override;
float eps_ = 1e-8f;
Ptr<TensorAllocator> alloc_;
Tensor gt_;
};
/**
* @brief Adam optimizer
*
* https://arxiv.org/pdf/1412.6980v8.pdf
*
* with Frank's modifications for automatic hyper-parameter adjustment.
*/
class Adam : public OptimizerBase {
public:
Adam(Ptr<Options> options) : OptimizerBase(options) {}
void load(std::vector<io::Item>& /*items*/,
const std::vector<Ptr<OptimizerBase>>& /*opts*/,
const std::vector<Ptr<Backend>>& /*backends*/,
const ScatterStateFunc& /*scatterFn*/,
bool isMainProcess) override;
void save(std::vector<io::Item>& items,
const std::vector<Ptr<OptimizerBase>>& opts,
const GatherStateFunc& gatherFn,
bool isMainProcess) override;
std::vector<Tensor> getShards() override {
auto shards = OptimizerBase::getShards();
shards.push_back(mt_);
shards.push_back(vt_);
return shards;
}
private:
void updateImpl(Tensor params, Tensor grads, size_t actualMBSize) override;
void resetStats() override;
// Adam parameters:
// [beta1, beta2, eps, w, refMBWords]
virtual void setParams(const std::vector<float>& params) override {
if(params.size() > 0)
beta1_ = params[0];
if(params.size() > 1)
beta2_ = params[1];
if(params.size() > 2)
eps_ = params[2];
// weighted decay for AdamW, to be explored, disabled by default
if(params.size() > 3)
w_ = params[3]; // default (disabled): 0
}
// hyper-parameters
float beta1_ = 0.9f;
float beta2_ = 0.999f;
float eps_ = 1e-8f;
float w_ = 0.0f;
// CPU-side running accumulators
double denom1_ = 0;
double denom2_ = 0;
// GPU-side running accumulators
Ptr<TensorAllocator> alloc_;
Tensor mt_;
Tensor vt_;
};
Ptr<OptimizerBase> Optimizer(Ptr<Options> options);
} // namespace marian
| 31.20922 | 170 | 0.667538 | [
"vector",
"model"
] |
e7eebe09335c49e04f1f91c9e0a50814d74c2e18 | 363 | h | C | code/Engine/Random.h | warzes/SapphireShooter | 10ce2efbb9426050f0e16629aadc1977055ca62c | [
"MIT"
] | null | null | null | code/Engine/Random.h | warzes/SapphireShooter | 10ce2efbb9426050f0e16629aadc1977055ca62c | [
"MIT"
] | null | null | null | code/Engine/Random.h | warzes/SapphireShooter | 10ce2efbb9426050f0e16629aadc1977055ca62c | [
"MIT"
] | null | null | null | #pragma once
#if SE_OPENGL
#include "TextureGenerator.h"
class Random : public TextureGenerateMethod
{
unsigned min;
unsigned max;
public:
Random(const unsigned& pMin, const unsigned& pMax) :min(pMin), max(pMax) { ; }
virtual void fillData(std::vector<GLubyte>& data, const unsigned& width, const unsigned& height, const unsigned& depth) const;
};
#endif | 21.352941 | 127 | 0.741047 | [
"vector"
] |
f005e5a1bb57a8df6b30ae29b2363826480f5d6f | 2,807 | h | C | SprityBird/spritybird/python3.5/lib/python3.5/site-packages/objc/Frameworks/Foundation.framework/Versions/C/Headers/NSXMLDTDNode.h | MobileAnalytics/iPython-Framework | da0e598308c067cd5c5290a6364b3ffaf2d2418f | [
"MIT"
] | 4 | 2018-07-04T17:20:12.000Z | 2019-07-14T18:07:25.000Z | SprityBird/spritybird/python3.5/lib/python3.5/site-packages/objc/Frameworks/Foundation.framework/Versions/C/Headers/NSXMLDTDNode.h | MobileAnalytics/iPython-Framework | da0e598308c067cd5c5290a6364b3ffaf2d2418f | [
"MIT"
] | null | null | null | SprityBird/spritybird/python3.5/lib/python3.5/site-packages/objc/Frameworks/Foundation.framework/Versions/C/Headers/NSXMLDTDNode.h | MobileAnalytics/iPython-Framework | da0e598308c067cd5c5290a6364b3ffaf2d2418f | [
"MIT"
] | 1 | 2018-09-03T03:02:06.000Z | 2018-09-03T03:02:06.000Z | /* NSXMLDTDNode.h
Copyright (c) 2004-2017, Apple Inc. All rights reserved.
*/
#import <Foundation/NSXMLNode.h>
NS_ASSUME_NONNULL_BEGIN
/*!
@typedef NSXMLDTDNodeKind
@abstract The subkind of a DTD node kind.
*/
typedef NS_ENUM(NSUInteger, NSXMLDTDNodeKind) {
NSXMLEntityGeneralKind = 1,
NSXMLEntityParsedKind,
NSXMLEntityUnparsedKind,
NSXMLEntityParameterKind,
NSXMLEntityPredefined,
NSXMLAttributeCDATAKind,
NSXMLAttributeIDKind,
NSXMLAttributeIDRefKind,
NSXMLAttributeIDRefsKind,
NSXMLAttributeEntityKind,
NSXMLAttributeEntitiesKind,
NSXMLAttributeNMTokenKind,
NSXMLAttributeNMTokensKind,
NSXMLAttributeEnumerationKind,
NSXMLAttributeNotationKind,
NSXMLElementDeclarationUndefinedKind,
NSXMLElementDeclarationEmptyKind,
NSXMLElementDeclarationAnyKind,
NSXMLElementDeclarationMixedKind,
NSXMLElementDeclarationElementKind
};
/*!
@class NSXMLDTDNode
@abstract The nodes that are exclusive to a DTD
@discussion Every DTD node has a name. Object value is defined as follows:<ul>
<li><b>Entity declaration</b> - the string that that entity resolves to eg "<"</li>
<li><b>Attribute declaration</b> - the default value, if any</li>
<li><b>Element declaration</b> - the validation string</li>
<li><b>Notation declaration</b> - no objectValue</li></ul>
*/
@interface NSXMLDTDNode : NSXMLNode {
@protected
NSXMLDTDNodeKind _DTDKind;
NSString *_name;
NSString *_notationName;
NSString *_publicID;
NSString *_systemID;
}
/*!
@method initWithXMLString:
@abstract Returns an element, attribute, entity, or notation DTD node based on the full XML string.
*/
- (nullable instancetype)initWithXMLString:(NSString *)string NS_DESIGNATED_INITIALIZER; //primitive
- (instancetype)initWithKind:(NSXMLNodeKind)kind options:(NSXMLNodeOptions)options NS_DESIGNATED_INITIALIZER; //primitive
- (instancetype)init NS_DESIGNATED_INITIALIZER;
/*!
@abstract Sets the DTD sub kind.
*/
@property NSXMLDTDNodeKind DTDKind; //primitive
/*!
@abstract True if the system id is set. Valid for entities and notations.
*/
@property (readonly, getter=isExternal) BOOL external; //primitive
/*!
@abstract Sets the public id. This identifier should be in the default catalog in /etc/xml/catalog or in a path specified by the environment variable XML_CATALOG_FILES. When the public id is set the system id must also be set. Valid for entities and notations.
*/
@property (nullable, copy) NSString *publicID; //primitive
/*!
@abstract Sets the system id. This should be a URL that points to a valid DTD. Valid for entities and notations.
*/
@property (nullable, copy) NSString *systemID; //primitive
/*!
@abstract Set the notation name. Valid for entities only.
*/
@property (nullable, copy) NSString *notationName; //primitive
@end
NS_ASSUME_NONNULL_END
| 29.861702 | 264 | 0.774492 | [
"object"
] |
f006938a40b34e0961d9492908607565e66fb760 | 2,079 | h | C | StandardAssets/Models/AnimatedModel.h | zurl/ElfGE | 9689ca3d890bfc538f74d449a9ecde8c7aa02d7b | [
"MIT"
] | 23 | 2017-11-01T15:31:34.000Z | 2021-08-18T00:57:45.000Z | StandardAssets/Models/AnimatedModel.h | zurl/ElfGE | 9689ca3d890bfc538f74d449a9ecde8c7aa02d7b | [
"MIT"
] | null | null | null | StandardAssets/Models/AnimatedModel.h | zurl/ElfGE | 9689ca3d890bfc538f74d449a9ecde8c7aa02d7b | [
"MIT"
] | 3 | 2017-12-07T16:15:04.000Z | 2018-08-14T15:55:37.000Z | //
// Created by 张程易 on 26/11/2017.
//
#ifndef ELFGE_ANIMATEDMODEL_H
#define ELFGE_ANIMATEDMODEL_H
#include "DefaultModel.h"
#include "../Meshs/AnimatedMesh.h"
class AnimatedModel : public DefaultModel {
Assimp::Importer import;
struct BoneInfo {
glm::mat4 offset;
glm::mat4 transform;
};
std::vector<BoneInfo> bonesInfo;
std::map<std::string, unsigned int> bonesMap;
std::map<std::string, unsigned int> animationMap;
struct Animation {
unsigned int startFrame;
unsigned int endFrame;
double start;
double end;
};
std::map<std::string, Animation> customAnimationMap;
unsigned int bonesCnt = 0;
const aiAnimation *pAnimation;
Animation currentAnimation;
double animation_now;
double duration = 0;
double timeCounter = 10.0f;
const aiScene *scene;
glm::mat4 globalInverseTransform;
const aiNodeAnim *FindNodeAnim(const aiAnimation *pAnimation, const std::string NodeName);
unsigned int FindPosition(double AnimationTime, const aiNodeAnim *pNodeAnim);
unsigned int FindRotation(double AnimationTime, const aiNodeAnim *pNodeAnim);
unsigned int FindScaling(double AnimationTime, const aiNodeAnim *pNodeAnim);
void CalcInterpolatedPosition(aiVector3D &Out, double AnimationTime, const aiNodeAnim *pNodeAnim);
void CalcInterpolatedRotation(aiQuaternion &Out, double AnimationTime, const aiNodeAnim *pNodeAnim);
void CalcInterpolatedScaling(aiVector3D &Out, double AnimationTime, const aiNodeAnim *pNodeAnim);
void computeNodeTransform(double AnimationTime, const aiNode *pNode, const glm::mat4 &ParentTransform);
void processNode(aiNode *node, const aiScene *scene);
public:
AnimatedModel(const std::string &path);
void render(Shader *shader, RenderLayer renderLayer) override;
void update() override;
void registerAnimation(const std::string &name, unsigned int startFrame, unsigned int endFrame);
void playAnimation(const std::string &name);
};
#endif //ELFGE_ANIMATEDMODEL_H
| 24.458824 | 107 | 0.724868 | [
"render",
"vector",
"transform"
] |
f006c66922cf99cabb00e5bbbd209751e49273ff | 835 | c | C | examples/code-samples/c/59_GetGame.c | MarkusRannare/modio-sdk | 70220009ac6c375bebd4b807de1e7f8a19680a41 | [
"MIT"
] | 42 | 2017-11-14T19:45:20.000Z | 2019-02-03T02:43:24.000Z | examples/code-samples/c/59_GetGame.c | MarkusRannare/modio-sdk | 70220009ac6c375bebd4b807de1e7f8a19680a41 | [
"MIT"
] | 16 | 2019-05-09T02:14:02.000Z | 2020-09-03T05:35:49.000Z | examples/code-samples/c/59_GetGame.c | MarkusRannare/modio-sdk | 70220009ac6c375bebd4b807de1e7f8a19680a41 | [
"MIT"
] | 15 | 2019-07-15T04:26:01.000Z | 2020-09-12T03:58:19.000Z | #include <stdbool.h>
#include "c/ModioC.h"
#include <stdio.h>
void onGetGame(void* object, ModioResponse response, ModioGame game)
{
bool* wait = object;
printf("On mod get response: %i\n", response.code);
if (response.code == 200)
{
printf("Id:\t%i\n", game.id);
printf("Name:\t%s\n", game.name);
printf("Summary:\t%s\n", game.summary);
}
*wait = false;
}
int main(void)
{
modioInit(MODIO_ENVIRONMENT_TEST, 7, false, false, "e91c01b8882f4affeddd56c96111977b", NULL);
bool wait = true;
// To retreive a game we simply need it's id
printf("Please enter the game id: \n");
u32 game_id;
scanf("%i", &game_id);
printf("Getting game...\n");
modioGetGame(&wait, game_id, &onGetGame);
while (wait)
{
modioProcess();
}
modioShutdown();
printf("Process finished\n");
return 0;
}
| 19.418605 | 95 | 0.643114 | [
"object"
] |
f00874611eb3077cc4a49c62c72fb38af4417e3e | 6,144 | h | C | libs/media/image.h | kdt3rd/gecko | 756a4e4587eb5023495294d9b6c6d80ebd79ebde | [
"MIT"
] | 15 | 2017-10-18T05:08:16.000Z | 2022-02-02T11:01:46.000Z | libs/media/image.h | kdt3rd/gecko | 756a4e4587eb5023495294d9b6c6d80ebd79ebde | [
"MIT"
] | null | null | null | libs/media/image.h | kdt3rd/gecko | 756a4e4587eb5023495294d9b6c6d80ebd79ebde | [
"MIT"
] | 1 | 2018-11-10T03:12:57.000Z | 2018-11-10T03:12:57.000Z | // SPDX-License-Identifier: MIT
// Copyright contributors to the gecko project.
#pragma once
#include "metadata.h"
#include <base/endian.h>
#include <base/small_vector.h>
#include <color/state.h>
#include <cstdint>
#include <string>
#include <vector>
namespace base
{
class allocator;
}
////////////////////////////////////////
namespace media
{
class image_buffer;
/// TODO: add packing (i.e. dpx 10-bit, 12-bit)
struct plane_layout
{
base::endianness _endian = base::endianness::NATIVE;
int8_t _bits = -1;
int8_t _ysubsample = 1;
int8_t _ysubsample_shift = 0;
int8_t _xsubsample = 1;
int8_t _xsubsample_shift = 0;
bool _floating = false;
bool _unsigned = true;
};
///
/// @brief Class image provides...
///
class image
{
/// not copyable, meant to be subclassed and carried in a smart pointer
image( const image & ) = delete;
image &operator=( const image & ) = delete;
image( image && ) = delete;
image &operator=( image & ) = delete;
public:
using plane_list = base::small_vector<std::string, 4>;
image( void );
image( const area_rect &area );
virtual ~image( void );
bool interleaved( void ) const { return storage_interleaved(); }
/// TODO: add level
//bool has_mipmap( void ) const ;
//bool is_tiled( void ) const;
/// TODO:
//int tile_x( void ) const;
//int tile_y( void ) const;
//int tile_z( void ) const;
/// this is informational only, but can be used to control the
/// processing, such that the reader can help determine whether to
/// process in tiles, single scanline or scanline chunks
/// (i.e. openexr has tiled, single scanline, 16-scanline chunks)
std::pair<int, int> preferred_chunk_size() const
{
return compute_preferred_chunk();
}
/// The "full" resolution of the image
inline const area_rect &full_area( void ) const { return _full_area; }
/// Active (data) window - where there are real pixels
inline const area_rect &active_area( void ) const { return _active_area; }
/// aspect ratio for pixels (square or not)
inline float aspect_ratio( void ) const { return _pix_aspect_ratio; }
inline void aspect_ratio( float ar ) { _pix_aspect_ratio = ar; }
inline const color::state &color_state( void ) const
{
return _color_state;
}
void color_state( const color::state &s );
inline bool empty( void ) const { return _planes.empty(); }
inline size_t size( void ) const { return _planes.size(); }
plane_list available_planes( void ) const;
const std::string &plane_name( size_t p ) const { return at( p )._name; }
plane_layout layout( size_t p ) const { return at( p )._layout; }
double outside_value( size_t p ) const { return at( p )._outside; }
/// utility function to create image buffers for the entire active
/// area. This may create an overlapped set of image_buffers that
/// use the same large memory block if the underlying format is
/// interleaved. Or if the image is planar, it will create
/// separate buffers.
///
/// This routine is probably not the most efficient way to access
/// image data for processing, where it is more memory efficient
/// to access by scanline or tile. Instead, a consumer of this
/// image probably wants to allocate memory itself and pass that
/// in. This places a burden on the consumer to conform to the
/// plane layout, but is provided as a default path to get to as
/// close to zero-copy imaging as possible.
///
/// @param planes place to store the image_buffers. if the incoming
/// list is not empty, will re-use the image_buffer if
/// they are the correct layout
/// @param a allocator to use when creating memory for the image_buffer
/// @param preferred_chunk only creates the image buffer large
/// enough for the preferred processing size.
void create_buffers(
std::vector<image_buffer> &planes,
base::allocator & a,
bool preferred_chunk ) const;
void extract_plane( size_t plane, image_buffer &pbuf );
void extract_image( std::vector<image_buffer> &planes );
inline void set_meta( base::cstring name, metadata_value v )
{
_metadata[name] = std::move( v );
}
inline const metadata &meta( void ) const { return _metadata; }
protected:
virtual bool storage_interleaved( void ) const = 0;
virtual void fill_plane( size_t plane, image_buffer &buffer ) = 0;
virtual void fill_image( std::vector<image_buffer> &planes ) = 0;
/// by default, returns the entire area
virtual std::pair<int64_t, int64_t> compute_preferred_chunk( void ) const;
/// sets both full and active area to the same value
void set_area( const area_rect &r )
{
_full_area = r;
_active_area = r;
}
/// sets only the full area
void set_full_area( const area_rect &r ) { _full_area = r; }
/// sets only the active area (data window)
void set_active_area( const area_rect &r ) { _active_area = r; }
void register_plane(
std::string name, const plane_layout &pl, double outsideval )
{
_planes.emplace_back( std::move( name ), pl, outsideval );
}
private:
struct plane_info
{
plane_info( std::string n, const plane_layout &pl, double ov )
: _name( std::move( n ) ), _layout( pl ), _outside( ov )
{}
std::string _name;
plane_layout _layout;
double _outside;
};
inline const plane_info &at( size_t p ) const { return _planes.at( p ); }
using plane_store = base::small_vector<plane_info, 4>;
area_rect _full_area;
area_rect _active_area;
float _pix_aspect_ratio = 1.f;
color::state _color_state;
plane_store _planes;
metadata _metadata;
};
} // namespace media
| 33.758242 | 78 | 0.627279 | [
"vector"
] |
f00efabcab0fc57139eef3a855f61a2a8aeafe54 | 2,470 | h | C | provider/include/ocpn-import/bbox.h | free-x/avnav-ocharts-provider | 7df95482d7bcef30f0cb0e1ae538cb9befc30deb | [
"MIT"
] | 1 | 2020-09-10T21:11:10.000Z | 2020-09-10T21:11:10.000Z | provider/include/ocpn-import/bbox.h | free-x/avnav-ocharts-provider | 7df95482d7bcef30f0cb0e1ae538cb9befc30deb | [
"MIT"
] | 15 | 2020-09-10T17:58:35.000Z | 2022-03-08T18:03:08.000Z | provider/include/ocpn-import/bbox.h | free-x/avnav-ocharts-provider | 7df95482d7bcef30f0cb0e1ae538cb9befc30deb | [
"MIT"
] | 2 | 2020-06-18T07:29:05.000Z | 2021-05-07T09:47:59.000Z | //testing
#ifndef __WXBOUNDINGBOX_H__
#define __WXBOUNDINGBOX_H__
#ifndef WX_PRECOMP
#include "wx/wx.h"
#endif
#include "wx/matrix.h"
#include "wx/geometry.h"
enum OVERLAP {_IN,_ON,_OUT};
//Purpose The wxBoundingBox class stores one wxBoundingBox.
//The wxBoundingBox is defined by two coordiates,
//a upperleft coordinate and a lowerright coordinate.
class wxBoundingBox
{
public:
wxBoundingBox();
wxBoundingBox(const wxBoundingBox&);
wxBoundingBox(const wxPoint2DDouble&);
wxBoundingBox(double xmin, double ymin, double xmax, double ymax);
virtual ~wxBoundingBox();
bool And(wxBoundingBox*, double Marge = 0);
void EnLarge(const double Marge);
void Shrink(const double Marge);
void Expand(const wxPoint2DDouble& , const wxPoint2DDouble&);
void Expand(const wxPoint2DDouble&);
void Expand(double x,double y);
void Expand(const wxBoundingBox& bbox);
OVERLAP Intersect( wxBoundingBox &, double Marge = 0);
bool LineIntersect(const wxPoint2DDouble& begin, const wxPoint2DDouble& end );
bool PointInBox( const wxPoint2DDouble&, double Marge = 0);
virtual bool PointInBox( double, double, double Marge = 0);
void Reset();
void Translate( wxPoint2DDouble& );
void MapBbox( const wxTransformMatrix& matrix);
double GetWidth() {return m_maxx-m_minx;};
double GetHeight(){return m_maxy-m_miny;};
bool GetValid() const;
void SetValid(bool);
void SetBoundingBox(const wxPoint2DDouble& a_point);
void SetMin(double, double);
void SetMax(double, double);
inline wxPoint2DDouble GetMin();
inline wxPoint2DDouble GetMax();
inline double GetMinX(){return m_minx;};
inline double GetMinY(){return m_miny;};
inline double GetMaxX(){return m_maxx;};
inline double GetMaxY(){return m_maxy;};
wxBoundingBox& operator+( wxBoundingBox& );
wxBoundingBox& operator=( const wxBoundingBox& );
protected:
//bounding box in world
double m_minx;
double m_miny;
double m_maxx;
double m_maxy;
bool m_validbbox;
};
// A class derived from wxBoundingBox
// that is assummed to be a geographic area, with coordinates
// expressed in Lat/Lon.
// This class understands the International Date Line (E/W Longitude)
class LLBBox : public wxBoundingBox
{
public:
bool PointInBox(double Lon, double Lat, double Marge);
};
#endif
| 27.752809 | 82 | 0.691903 | [
"geometry"
] |
f00f21db5583bc1c64773a23a93554413b2850fb | 8,940 | h | C | src/Geometry/refinement/RefinerUtils.h | Chuanming-Liu/SeisSol | 1a8c6ed697de4d9dfbecb0b501ae624e2b2202ae | [
"BSD-3-Clause"
] | null | null | null | src/Geometry/refinement/RefinerUtils.h | Chuanming-Liu/SeisSol | 1a8c6ed697de4d9dfbecb0b501ae624e2b2202ae | [
"BSD-3-Clause"
] | null | null | null | src/Geometry/refinement/RefinerUtils.h | Chuanming-Liu/SeisSol | 1a8c6ed697de4d9dfbecb0b501ae624e2b2202ae | [
"BSD-3-Clause"
] | 1 | 2022-01-05T03:45:12.000Z | 2022-01-05T03:45:12.000Z | /**
* @file
* This file is part of SeisSol.
*
* @author Sebastian Rettenberger (sebastian.rettenberger AT tum.de, http://www5.in.tum.de/wiki/index.php/Sebastian_Rettenberger)
*
* @section LICENSE
* Copyright (c) 2015, SeisSol Group
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* @section DESCRIPTION
*/
#ifndef _REFINER_UTILS_H_
#define _REFINER_UTILS_H_
#include <vector>
#include <glm/vec3.hpp>
#include <glm/gtc/type_ptr.hpp>
namespace seissol {
namespace refinement {
//------------------------------------------------------------------------------
template<class T>
const glm::tvec3<T> middle(const glm::tvec3<T>& a, const glm::tvec3<T>& b)
{
return (a+b)/static_cast<T>(2);
}
//------------------------------------------------------------------------------
template<class T>
struct Tetrahedron {
/** Indices of the vertices */
unsigned int i, j, k, l;
glm::tvec3<T> a, b, c, d;
Tetrahedron()
: i(0), j(0), k(0), l(0)
{};
Tetrahedron(const glm::tvec3<T>& A, const glm::tvec3<T>& B, const glm::tvec3<T>& C,
const glm::tvec3<T>& D)
: i(0), j(0), k(0), l(0),
a(A), b(B), c(C), d(D)
{};
Tetrahedron(const glm::tvec3<T>& A, const glm::tvec3<T>& B, const glm::tvec3<T>& C,
const glm::tvec3<T>& D,
unsigned int I, unsigned int J, unsigned int K, unsigned int L)
: i(I), j(J), k(K), l(L),
a(A), b(B), c(C), d(D)
{};
Tetrahedron(const T A[3], const T B[3], const T C[3], const T D[3],
unsigned int I, unsigned int J, unsigned int K, unsigned int L)
: i(I), j(J), k(K), l(L),
a(glm::make_vec3(A)), b(glm::make_vec3(B)),
c(glm::make_vec3(C)), d(glm::make_vec3(D))
{};
static const Tetrahedron<T> unitTetrahedron()
{
return Tetrahedron(
glm::tvec3<T>(0,0,0),
glm::tvec3<T>(0,0,1),
glm::tvec3<T>(1,0,0),
glm::tvec3<T>(0,1,0));
}
const glm::tvec3<T> center() const
{
return middle(middle(a, b), middle(c, d));
}
};
//------------------------------------------------------------------------------
template<class T>
class TetrahedronRefiner {
public:
virtual ~TetrahedronRefiner() {}
/** Generates the new cells */
virtual void refine(const Tetrahedron<T>& in, unsigned int addVertexStart,
Tetrahedron<T>* out, glm::tvec3<T>* addVertices) const = 0;
/** The additional number of vertices generated per original tetrahedron */
virtual unsigned int additionalVerticesPerCell() const = 0;
virtual unsigned int getDivisionCount() const = 0;
};
//------------------------------------------------------------------------------
template<class T>
class IdentityRefiner : public TetrahedronRefiner<T> {
public:
void refine(const Tetrahedron<T>& in, unsigned int addVertexStart,
Tetrahedron<T>* out, glm::tvec3<T>* addVertices) const
{
out[0] = in;
}
unsigned int additionalVerticesPerCell() const
{
return 0;
}
unsigned int getDivisionCount() const
{
return 1;
}
};
//------------------------------------------------------------------------------
template<class T>
class DivideTetrahedronBy4 : public TetrahedronRefiner<T> {
public:
void refine(const Tetrahedron<T>& in, unsigned int addVertexStart,
Tetrahedron<T>* out, glm::tvec3<T>* addVertices) const
{
addVertices[0] = in.center();
out[0] = Tetrahedron<T>(in.a, in.b, in.c, addVertices[0],
in.i, in.j, in.k, addVertexStart);
out[1] = Tetrahedron<T>(in.a, in.b, in.d, addVertices[0],
in.i, in.j, in.l, addVertexStart);
out[2] = Tetrahedron<T>(in.a, in.c, in.d, addVertices[0],
in.i, in.k, in.l, addVertexStart);
out[3] = Tetrahedron<T>(in.b, in.c, in.d, addVertices[0],
in.j, in.k, in.l, addVertexStart);
}
unsigned int additionalVerticesPerCell() const
{
return 1;
}
unsigned int getDivisionCount() const
{
return 4;
}
};
//------------------------------------------------------------------------------
template<class T>
class DivideTetrahedronBy8 : public TetrahedronRefiner<T> {
public:
void refine(const Tetrahedron<T>& in, unsigned int addVertexStart,
Tetrahedron<T>* out, glm::tvec3<T>* addVertices) const
{
const glm::tvec3<T>& a = in.a;
const glm::tvec3<T>& b = in.b;
const glm::tvec3<T>& c = in.c;
const glm::tvec3<T>& d = in.d;
addVertices[0] = middle(a, b);
addVertices[1] = middle(a, c);
addVertices[2] = middle(a, d);
addVertices[3] = middle(b, c);
addVertices[4] = middle(b, d);
addVertices[5] = middle(c, d);
const glm::tvec3<T>& ab = addVertices[0];
const glm::tvec3<T>& ac = addVertices[1];
const glm::tvec3<T>& ad = addVertices[2];
const glm::tvec3<T>& bc = addVertices[3];
const glm::tvec3<T>& bd = addVertices[4];
const glm::tvec3<T>& cd = addVertices[5];
const unsigned int iab = addVertexStart;
const unsigned int iac = addVertexStart+1;
const unsigned int iad = addVertexStart+2;
const unsigned int ibc = addVertexStart+3;
const unsigned int ibd = addVertexStart+4;
const unsigned int icd = addVertexStart+5;
out[0] = Tetrahedron<T>( a, ab, ac, ad,
in.i, iab, iac, iad);
out[1] = Tetrahedron<T>( b, ab, bc, bd,
in.j, iab, ibc, ibd);
out[2] = Tetrahedron<T>( c, ac, bc, cd,
in.k, iac, ibc, icd);
out[3] = Tetrahedron<T>( d, ad, bd, cd,
in.l, iad, ibd, icd);
// Inner upper cells
out[4] = Tetrahedron<T>(ab, ac, ad, bd,
iab, iac, iad, ibd);
out[5] = Tetrahedron<T>(ab, ac, bc, bd,
iab, iac, ibc, ibd);
// Inner lower cells
out[6] = Tetrahedron<T>(ac, ad, bd, cd,
iac, iad, ibd, icd);
out[7] = Tetrahedron<T>(ac, bc, bd, cd,
iac, ibc, ibd, icd);
}
unsigned int additionalVerticesPerCell() const
{
return 6;
}
unsigned int getDivisionCount() const
{
return 8;
}
};
//------------------------------------------------------------------------------
template<class T>
class DivideTetrahedronBy32 : public TetrahedronRefiner<T> {
private:
DivideTetrahedronBy4<T> div4;
DivideTetrahedronBy8<T> div8;
public:
void refine(const Tetrahedron<T>& in, unsigned int addVertexStart,
Tetrahedron<T>* out, glm::tvec3<T>* addVertices) const
{
auto tmp = std::vector<Tetrahedron<T>>(div8.getDivisionCount());
div8.refine(in, addVertexStart, tmp.data(), addVertices);
addVertexStart += div8.additionalVerticesPerCell();
addVertices += div8.additionalVerticesPerCell();
for (unsigned int i = 0; i < div8.getDivisionCount(); i++) {
div4.refine(tmp[i],
addVertexStart + i*div4.additionalVerticesPerCell(),
out + (i*div4.getDivisionCount()),
addVertices + (i*div4.additionalVerticesPerCell()));
}
}
unsigned int additionalVerticesPerCell() const
{
return div8.additionalVerticesPerCell()
+ div8.getDivisionCount() * div4.additionalVerticesPerCell();
}
unsigned int getDivisionCount() const
{
return div4.getDivisionCount() * div8.getDivisionCount();
}
};
//------------------------------------------------------------------------------
} // namespace
}
#endif // _REFINER_UTILS_H_
| 31.590106 | 129 | 0.587136 | [
"vector"
] |
f02df046a45dbf8b6a1bbf58cd425897e454910b | 5,547 | h | C | DirectZobEngine/Wrappers/ZobUserControls/ZobUserControls.h | zeralph/directZob | 7682ec0b77b697659be157cce62413e3ee877ee4 | [
"WTFPL"
] | 2 | 2019-06-12T18:11:36.000Z | 2022-01-19T00:26:00.000Z | DirectZobEngine/Wrappers/ZobUserControls/ZobUserControls.h | zeralph/directZob | 7682ec0b77b697659be157cce62413e3ee877ee4 | [
"WTFPL"
] | null | null | null | DirectZobEngine/Wrappers/ZobUserControls/ZobUserControls.h | zeralph/directZob | 7682ec0b77b697659be157cce62413e3ee877ee4 | [
"WTFPL"
] | 1 | 2019-10-05T02:44:47.000Z | 2019-10-05T02:44:47.000Z | #ifdef _WINDLL
#pragma once
#include "../../DirectZobEngine/Rendering/ZobVector3.h"
#include "../DirectZobWrapperEvents.h"
#using "System.Windows.Forms.dll"
#using "System.dll"
#using "System.Drawing.dll"
#include "../../Misc/ZobVariablesExposer.h"
using namespace System;
using namespace System::Windows;
using namespace System::Windows::Forms;
using namespace System::Collections::Generic;
using namespace System::Drawing;
namespace CLI {
public ref class ZobGroupBox : GroupBox
{
public:
ZobGroupBox(String^ name, bool collapsable);
~ZobGroupBox();
void OnToggle(Object^ sender, EventArgs^ e);
bool bToggled;
Button^ _label;
EventHandler^ _event;
};
public ref class ZobControl : TableLayoutPanel
{
public:
ZobControl(const ZobVariablesExposer::wrapperData& w);
~ZobControl();
static ZobGroupBox^ CreateWrappedVariablesView(std::string& name, ZobVariablesExposer* ze);
static const ZobVariablesExposer::wrapperData* GetDataFromWrapperVariable(String^ variableName, ZobVariablesExposer* ze);
protected:
virtual void OnValueChanged(Object^ sender, EventArgs^ e) {}
void UpdateControl();
virtual void UpdateControlInternal() {}
bool IsControlOk();
const ZobVariablesExposer::wrapperData* _w;
DirectZobWrapperEvents::OnEditorUpdate^ _updateEvent;
Action^ _update;
};
public ref class ZobControlString : ZobControl
{
public:
ZobControlString(const ZobVariablesExposer::wrapperData& w);
~ZobControlString();
EventHandler^ _event;
Label^ _label;
TextBox^ _txt;
protected:
void OnValueChanged(Object^ sender, EventArgs^ e) override;
};
public ref class ZobControlFilePath : ZobControl
{
public:
ZobControlFilePath(const ZobVariablesExposer::wrapperData& w);
~ZobControlFilePath();
TextBox^ _txt;
Label^ _label;
Button^ _btn;
EventHandler^ _event;
protected:
void OnValueChanged(Object^ sender, EventArgs^ e) override;
void OnOpen(Object^ sender, EventArgs^ e);
void OnOk(Object^ sender, System::ComponentModel::CancelEventArgs^ e);
};
public ref class ZobControlVector3 : ZobControl
{
public:
ZobControlVector3(const ZobVariablesExposer::wrapperData& w);
~ZobControlVector3();
void UpdateControlInternal() override;
TextBox^ _txt_X;
TextBox^ _txt_Y;
TextBox^ _txt_Z;
Label^ _label;
EventHandler^ _eventX;
EventHandler^ _eventY;
EventHandler^ _eventZ;
protected:
void OnValueChanged(Object^ sender, EventArgs^ e) override;
};
public ref class ZobControlFloat : ZobControl
{
public:
ZobControlFloat(const ZobVariablesExposer::wrapperData& w);
~ZobControlFloat();
TextBox^ _txt;
Label^ _label;
EventHandler^ _event;
protected:
void OnValueChanged(Object^ sender, EventArgs^ e) override;
void UpdateControlInternal() override;
};
public ref class ZobControlBool : ZobControl
{
public:
ZobControlBool(const ZobVariablesExposer::wrapperData& w);
~ZobControlBool();
EventHandler^ _event;
Label^ _label;
CheckBox^ _checkBox;
bool _checked;
protected:
void OnValueChanged(Object^ sender, EventArgs^ e) override;
void UpdateControlInternal() override;
};
public ref class ZobControlAction : ZobControl
{
public:
ZobControlAction(const ZobVariablesExposer::wrapperData& w);
~ZobControlAction();
EventHandler^ _event;
Label^ _label;
Button^ _button;
bool _checked;
protected:
void OnValueChanged(Object^ sender, EventArgs^ e) override;
void UpdateControlInternal() override;
};
public ref class ZobControlColor : ZobControl
{
public:
ZobControlColor(const ZobVariablesExposer::wrapperData& w);
~ZobControlColor();
TextBox^ _txt_A;
TextBox^ _txt_R;
TextBox^ _txt_G;
TextBox^ _txt_B;
Label^ _label;
EventHandler^ _eventA;
EventHandler^ _eventR;
EventHandler^ _eventG;
EventHandler^ _eventB;
Button^ _btn;
protected:
void OnValueChanged(Object^ sender, EventArgs^ e) override;
void OnClickColor(Object^ sender, EventArgs^ e);
void UpdateControlInternal() override;
};
public ref class ZobControlEnum : ZobControl
{
public:
ZobControlEnum(const ZobVariablesExposer::wrapperData& w);
~ZobControlEnum();
Label^ _label;
ComboBox^ _list;
EventHandler^ _event;
protected:
void OnValueChanged(Object^ sender, EventArgs^ e) override;
void UpdateControlInternal() override;
};
public ref class ZobControlZobObject : ZobControl
{
public:
ZobControlZobObject(const ZobVariablesExposer::wrapperData& w);
~ZobControlZobObject();
Label^ _label;
TextBox^ _txt;
protected:
void OnValueChanged(Object^ sender, EventArgs^ e) override;
void UpdateControlInternal() override;
};
public ref class ZobControlZobId : ZobControl
{
public:
ZobControlZobId(const ZobVariablesExposer::wrapperData& w);
~ZobControlZobId();
Label^ _label;
Label^ _txt;
protected:
};
public ref class ZobControlTreeNode : public TreeNode
{
public:
ZobControlTreeNode(String^ zobObjectGuid);
~ZobControlTreeNode();
ZobControlTreeNode^ GetChildNode(String^ guid);
bool IsSelectable() { return m_isSelectable; }
bool IsReadOnly() { return m_isReadOnly; }
String^ m_zobObjectGuid;
bool m_isSelectable;
bool m_isReadOnly;
};
public ref class ZobControlTreeview : TreeView
{
public:
ZobControlTreeview();
void UpdateZobControl();
};
public ref class ZobPropertiesContainer : TableLayoutPanel
{
public:
ZobPropertiesContainer();
};
public ref class ZobPropertiesLayout : TableLayoutPanel
{
public:
ZobPropertiesLayout(String^ name);
~ZobPropertiesLayout();
Label^ _label;
};
};
#endif //_WINDLL | 24.986486 | 124 | 0.750856 | [
"object"
] |
6ccd1d3a213639cece7efb1dd9a3245a6de4c431 | 1,994 | h | C | application/include/mqtt.h | intel-iot-devkit/shopper-mood-monitor-cpp | 857fea1d732c6997599ec7371e4c6b52abbc48d3 | [
"BSD-3-Clause"
] | 10 | 2018-11-08T04:00:07.000Z | 2021-05-18T11:22:30.000Z | application/include/mqtt.h | intel-iot-devkit/restricted-zone-notifier-cpp | 46b08074fe26d98ef247d8863a973111211cb6c0 | [
"BSD-3-Clause"
] | 2 | 2019-01-03T05:32:32.000Z | 2019-03-06T19:42:40.000Z | application/include/mqtt.h | intel-iot-devkit/machine-operator-monitor-cpp | daa12a0b7765462d274db2b2f14c4e4b7c53c4c2 | [
"BSD-3-Clause"
] | 13 | 2018-10-31T18:07:03.000Z | 2021-11-24T08:38:04.000Z | /*
* Copyright (c) 2015 - 2018 Intel Corporation.
*
* 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.
*/
#ifndef MQTT_H_INCLUDED
#define MQTT_H_INCLUDED
#include <stdlib.h>
#include <iostream>
#include <sstream>
#include <utility>
#include <vector>
#include <tuple>
#include <cstring>
extern "C" {
#include "MQTTClient.h"
#include "MQTTClientPersistence.h"
}
#define QOS 1
#define TIMEOUT 1000L
struct mqtt_service_config
{
std::string server;
std::string client_id;
std::string topic;
std::string username;
std::string password;
std::string cert;
std::string cert_key;
std::string ca_root;
};
std::string std_getenv(const std::string &name);
std::pair<mqtt_service_config, bool> get_mqtt_config();
int mqtt_start(MQTTClient_messageArrived* msgrcv);
void mqtt_close();
void mqtt_connect();
void mqtt_disconnect();
int mqtt_publish(std::string const &topic, std::string const &message);
void mqtt_subscribe(std::string const &topic);
#endif
| 30.676923 | 72 | 0.754263 | [
"vector"
] |
6ccfb4ecfa1b698c078966057f10caa326c35103 | 154,699 | c | C | tool_examples/function_counter/function_counter.c | m2700/qmpi | 4a5381619c3d31863249fa13653c0d8fd41c58b3 | [
"BSD-3-Clause"
] | null | null | null | tool_examples/function_counter/function_counter.c | m2700/qmpi | 4a5381619c3d31863249fa13653c0d8fd41c58b3 | [
"BSD-3-Clause"
] | null | null | null | tool_examples/function_counter/function_counter.c | m2700/qmpi | 4a5381619c3d31863249fa13653c0d8fd41c58b3 | [
"BSD-3-Clause"
] | null | null | null | /**
Copyright (C) 2018 Technische Universitaet Muenchen
Chair of Computer Architecture and
Parallel Systems
Author: Bengisu Elis
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
USA */
#include <time.h>
#include "qmpi.h"
#include <assert.h>
#include <mpi.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "counter.h"
#include "interceptions.h"
/* ================== C Wrappers for MPI_Finalize ================== */
int E_Finalize(int i, vector *v) {
void *f_dl = NULL;
counters[138]++;
QMPI_TABLE_QUERY(138, &f_dl, (*VECTOR_GET(v, i)).table);
int counters_copy[NUM_MPI_FUNCS];
for (size_t i = 0; i < NUM_MPI_FUNCS; i++) {
counters_copy[i] = counters[i];
}
int all_counts[NUM_MPI_FUNCS];
int red_scc = MPI_Reduce(counters_copy, all_counts, NUM_MPI_FUNCS, MPI_INT,
MPI_SUM, 0, MPI_COMM_WORLD);
if (red_scc != MPI_SUCCESS) {
return red_scc;
}
int rank;
int cr_scc = MPI_Comm_rank(MPI_COMM_WORLD, &rank);
if (cr_scc != MPI_SUCCESS) {
return red_scc;
}
char *fin_debug = getenv("FINALIZE_DEBUG_CONFIRM");
if (rank == 0 && (fin_debug == NULL || strcmp(fin_debug, "1") == 0)) {
for (size_t fi = 0; fi < NUM_MPI_FUNCS; fi++) {
if (all_counts[fi] != 0) {
printf("MPI%s: %u\n", interceptions[fi] + 1,
(unsigned)all_counts[fi]);
}
}
}
int ret = EXEC_FUNC(f_dl, i, 138, v);
return ret;
}
/* ================== C Wrappers for MPI_Init ================== */
int E_Init(int *argc, char ***argv, int i, vector *v) {
void *f_dl = NULL;
counters[200]++;
QMPI_TABLE_QUERY(200, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 200, v, argc, argv);
return ret;
}
/* ================== C Wrappers for MPI_Abort ================== 0*/
int E_Abort(MPI_Comm comm, int errorcode, int i, vector *v) {
void *f_dl = NULL;
counters[0]++;
QMPI_TABLE_QUERY(0, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 0, v, comm, errorcode);
return ret;
}
/* ================== C Wrappers for MPI_Accumulate ================== 1*/
int E_Accumulate(const void *origin_addr, int origin_count,
MPI_Datatype origin_datatype, int target_rank,
MPI_Aint target_disp, int target_count,
MPI_Datatype target_datatype, MPI_Op op, MPI_Win win, int i,
vector *v) {
void *f_dl = NULL;
counters[1]++;
QMPI_TABLE_QUERY(1, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 1, v, origin_addr, origin_count,
origin_datatype, target_rank, target_disp, target_count,
target_datatype, op, win);
return ret;
}
/* ================== C Wrappers for MPI_Add_error_class ================== 2*/
int E_Add_error_class(int *errorclass, int i, vector *v) {
void *f_dl = NULL;
counters[2]++;
QMPI_TABLE_QUERY(2, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 2, v, errorclass);
return ret;
}
/* ================== C Wrappers for MPI_Add_error_code ==================3 */
int E_Add_error_code(int errorclass, int *errorcode, int i, vector *v) {
void *f_dl = NULL;
counters[3]++;
QMPI_TABLE_QUERY(3, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 3, v, errorclass, errorcode);
return ret;
}
/* ================== C Wrappers for MPI_Add_error_string ================== 4*/
int E_Add_error_string(int errorcode, const char *string, int i, vector *v) {
void *f_dl = NULL;
counters[4]++;
QMPI_TABLE_QUERY(4, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 4, v, errorcode, string);
return ret;
}
/* ================== C Wrappers for MPI_Address ================== 5*/
int E_Address(void *location, MPI_Aint *address, int i, vector *v) {
void *f_dl = NULL;
counters[5]++;
QMPI_TABLE_QUERY(5, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 5, v, location, address);
return ret;
}
/* ================== C Wrappers for MPI_Allgather ================== 6*/
int E_Allgather(const void *sendbuf, int sendcount, MPI_Datatype sendtype,
void *recvbuf, int recvcount, MPI_Datatype recvtype,
MPI_Comm comm, int i, vector *v) {
void *f_dl = NULL;
counters[6]++;
QMPI_TABLE_QUERY(6, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 6, v, sendbuf, sendcount, sendtype, recvbuf,
recvcount, recvtype, comm);
return ret;
}
/* ================== C Wrappers for MPI_Allgatherv ================== 7*/
int E_Allgatherv(const void *sendbuf, int sendcount, MPI_Datatype sendtype,
void *recvbuf, const int recvcounts[], const int displs[],
MPI_Datatype recvtype, MPI_Comm comm, int i, vector *v) {
void *f_dl = NULL;
counters[7]++;
QMPI_TABLE_QUERY(7, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 7, v, sendbuf, sendcount, sendtype, recvbuf,
recvcounts, displs, recvtype, comm);
return ret;
}
/* ================== C Wrappers for MPI_Alloc_mem ================== 8*/
int E_Alloc_mem(MPI_Aint size, MPI_Info info, void *baseptr, int i, vector *v) {
void *f_dl = NULL;
counters[8]++;
QMPI_TABLE_QUERY(8, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 8, v, size, info, baseptr);
return ret;
}
/* ================== C Wrappers for MPI_Allreduce ================== 9*/
int E_Allreduce(const void *sendbuf, void *recvbuf, int count,
MPI_Datatype datatype, MPI_Op op, MPI_Comm comm, int i,
vector *v) {
void *f_dl = NULL;
counters[9]++;
QMPI_TABLE_QUERY(9, &f_dl, (*VECTOR_GET(v, i)).table);
int ret =
EXEC_FUNC(f_dl, i, 9, v, sendbuf, recvbuf, count, datatype, op, comm);
return ret;
}
/* ================== C Wrappers for MPI_Alltoall ================== 10*/
int E_Alltoall(const void *sendbuf, int sendcount, MPI_Datatype sendtype,
void *recvbuf, int recvcount, MPI_Datatype recvtype,
MPI_Comm comm, int i, vector *v) {
void *f_dl = NULL;
counters[10]++;
QMPI_TABLE_QUERY(10, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 10, v, sendbuf, sendcount, sendtype, recvbuf,
recvcount, recvtype, comm);
return ret;
}
/* ================== C Wrappers for MPI_Alltoallv ================== 11*/
int E_Alltoallv(const void *sendbuf, const int sendcounts[],
const int sdispls[], MPI_Datatype sendtype, void *recvbuf,
const int recvcounts[], const int rdispls[],
MPI_Datatype recvtype, MPI_Comm comm, int i, vector *v) {
void *f_dl = NULL;
counters[11]++;
QMPI_TABLE_QUERY(11, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 11, v, sendbuf, sendcounts, sdispls, sendtype,
recvbuf, recvcounts, rdispls, recvtype, comm);
return ret;
}
/* ================== C Wrappers for MPI_Alltoallw ================== 12*/
int E_Alltoallw(const void *sendbuf, const int sendcounts[],
const int sdispls[], const MPI_Datatype sendtypes[],
void *recvbuf, const int recvcounts[], const int rdispls[],
const MPI_Datatype recvtypes[], MPI_Comm comm, int i,
vector *v) {
void *f_dl = NULL;
counters[12]++;
QMPI_TABLE_QUERY(12, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 12, v, sendbuf, sendcounts, sdispls, sendtypes,
recvbuf, recvcounts, rdispls, recvtypes, comm);
return ret;
}
/* ================== C Wrappers for MPI_Attr_delete ================== 13*/
int E_Attr_delete(MPI_Comm comm, int keyval, int i, vector *v) {
void *f_dl = NULL;
counters[13]++;
QMPI_TABLE_QUERY(13, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 13, v, comm, keyval);
return ret;
}
/* ================== C Wrappers for MPI_Attr_get ================== 14*/
int E_Attr_get(MPI_Comm comm, int keyval, void *attribute_val, int *flag, int i,
vector *v) {
void *f_dl = NULL;
counters[14]++;
QMPI_TABLE_QUERY(14, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 14, v, comm, keyval, attribute_val, flag);
return ret;
}
/* ================== C Wrappers for MPI_Attr_put ================== 15*/
int E_Attr_put(MPI_Comm comm, int keyval, void *attribute_val, int i,
vector *v) {
void *f_dl = NULL;
counters[15]++;
QMPI_TABLE_QUERY(15, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 15, v, comm, keyval, attribute_val);
return ret;
}
/* ================== C Wrappers for MPI_Barrier ==================16 */
int E_Barrier(MPI_Comm comm, int i, vector *v) {
void *f_dl = NULL;
counters[16]++;
QMPI_TABLE_QUERY(16, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 16, v, comm);
return ret;
}
/* ================== C Wrappers for MPI_Bcast ================== 17*/
int E_Bcast(void *buffer, int count, MPI_Datatype datatype, int root,
MPI_Comm comm, int i, vector *v) {
void *f_dl = NULL;
counters[17]++;
QMPI_TABLE_QUERY(17, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 17, v, buffer, count, datatype, root, comm);
return ret;
}
/* ================== C Wrappers for MPI_Bsend ================== 18*/
int E_Bsend(const void *buf, int count, MPI_Datatype datatype, int dest,
int tag, MPI_Comm comm, int i, vector *v) {
void *f_dl = NULL;
counters[18]++;
QMPI_TABLE_QUERY(18, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 18, v, buf, count, datatype, dest, tag, comm);
return ret;
}
/* ================== C Wrappers for MPI_Bsend_init ==================19 */
int E_Bsend_init(const void *buf, int count, MPI_Datatype datatype, int dest,
int tag, MPI_Comm comm, MPI_Request *request, int i,
vector *v) {
void *f_dl = NULL;
counters[19]++;
QMPI_TABLE_QUERY(19, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 19, v, buf, count, datatype, dest, tag, comm,
request);
return ret;
}
/* ================== C Wrappers for MPI_Buffer_attach ==================20 */
int E_Buffer_attach(void *buffer, int size, int i, vector *v) {
void *f_dl = NULL;
counters[20]++;
QMPI_TABLE_QUERY(20, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 20, v, buffer, size);
return ret;
}
/* ================== C Wrappers for MPI_Buffer_detach ================== 21*/
int E_Buffer_detach(void *buffer, int *size, int i, vector *v) {
void *f_dl = NULL;
counters[21]++;
QMPI_TABLE_QUERY(21, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 21, v, buffer, size);
return ret;
}
/* ================== C Wrappers for MPI_Cancel ================== 22*/
int E_Cancel(MPI_Request *request, int i, vector *v) {
void *f_dl = NULL;
counters[22]++;
QMPI_TABLE_QUERY(22, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 22, v, request);
return ret;
}
/* ================== C Wrappers for MPI_Cart_coords ================== 23*/
int E_Cart_coords(MPI_Comm comm, int rank, int maxdims, int coords[], int i,
vector *v) {
void *f_dl = NULL;
counters[23]++;
QMPI_TABLE_QUERY(23, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 23, v, comm, rank, maxdims, coords);
return ret;
}
/* ================== C Wrappers for MPI_Cart_create ================== 24*/
int E_Cart_create(MPI_Comm old_comm, int ndims, const int dims[],
const int periods[], int reorder, MPI_Comm *comm_cart, int i,
vector *v) {
void *f_dl = NULL;
counters[24]++;
QMPI_TABLE_QUERY(24, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 24, v, old_comm, ndims, dims, periods, reorder,
comm_cart);
return ret;
}
/* ================== C Wrappers for MPI_Cart_get ==================25 */
int E_Cart_get(MPI_Comm comm, int maxdims, int dims[], int periods[],
int coords[], int i, vector *v) {
void *f_dl = NULL;
counters[25]++;
QMPI_TABLE_QUERY(25, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 25, v, comm, maxdims, dims, periods, coords);
return ret;
}
/* ================== C Wrappers for MPI_Cart_map ================== 26*/
int E_Cart_map(MPI_Comm comm, int ndims, const int dims[], const int periods[],
int *newrank, int i, vector *v) {
void *f_dl = NULL;
counters[26]++;
QMPI_TABLE_QUERY(26, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 26, v, comm, ndims, dims, periods, newrank);
return ret;
}
/* ================== C Wrappers for MPI_Cart_rank ================== 27*/
int E_Cart_rank(MPI_Comm comm, const int coords[], int *rank, int i,
vector *v) {
void *f_dl = NULL;
counters[27]++;
QMPI_TABLE_QUERY(27, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 27, v, comm, coords, rank);
return ret;
}
/* ================== C Wrappers for MPI_Cart_shift ================== 28*/
int E_Cart_shift(MPI_Comm comm, int direction, int disp, int *rank_source,
int *rank_dest, int i, vector *v) {
void *f_dl = NULL;
counters[28]++;
QMPI_TABLE_QUERY(28, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 28, v, comm, direction, disp, rank_source,
rank_dest);
return ret;
}
/* ================== C Wrappers for MPI_Cart_sub ================== 29*/
int E_Cart_sub(MPI_Comm comm, const int remain_dims[], MPI_Comm *new_comm,
int i, vector *v) {
void *f_dl = NULL;
counters[29]++;
QMPI_TABLE_QUERY(29, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 29, v, comm, remain_dims, new_comm);
return ret;
}
/* ================== C Wrappers for MPI_Cartdim_get ================== 30*/
int E_Cartdim_get(MPI_Comm comm, int *ndims, int i, vector *v) {
void *f_dl = NULL;
counters[30]++;
QMPI_TABLE_QUERY(30, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 30, v, comm, ndims);
return ret;
}
/* ================== C Wrappers for MPI_Close_port ================== 31*/
int E_Close_port(const char *port_name, int i, vector *v) {
void *f_dl = NULL;
counters[31]++;
QMPI_TABLE_QUERY(31, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 31, v, port_name);
return ret;
}
/* ================== C Wrappers for MPI_Comm_accept ================== 32*/
int E_Comm_accept(const char *port_name, MPI_Info info, int root, MPI_Comm comm,
MPI_Comm *newcomm, int i, vector *v) {
void *f_dl = NULL;
counters[32]++;
QMPI_TABLE_QUERY(32, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 32, v, port_name, info, root, comm, newcomm);
return ret;
}
/* ================== C Wrappers for MPI_Comm_call_errhandler ==================
* 33*/
int E_Comm_call_errhandler(MPI_Comm comm, int errorcode, int i, vector *v) {
void *f_dl = NULL;
counters[33]++;
QMPI_TABLE_QUERY(33, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 33, v, comm, errorcode);
return ret;
}
/* ================== C Wrappers for MPI_Comm_compare ================== 34*/
int E_Comm_compare(MPI_Comm comm1, MPI_Comm comm2, int *result, int i,
vector *v) {
void *f_dl = NULL;
counters[34]++;
QMPI_TABLE_QUERY(34, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 34, v, comm1, comm2, result);
return ret;
}
/* ================== C Wrappers for MPI_Comm_connect ================== 35*/
int E_Comm_connect(const char *port_name, MPI_Info info, int root,
MPI_Comm comm, MPI_Comm *newcomm, int i, vector *v) {
void *f_dl = NULL;
counters[35]++;
QMPI_TABLE_QUERY(35, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 35, v, port_name, info, root, comm, newcomm);
return ret;
}
/* ================== C Wrappers for MPI_Comm_create ================== 36*/
int E_Comm_create(MPI_Comm comm, MPI_Group group, MPI_Comm *newcomm, int i,
vector *v) {
void *f_dl = NULL;
counters[36]++;
QMPI_TABLE_QUERY(36, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 36, v, comm, group, newcomm);
return ret;
}
/* ================== C Wrappers for MPI_Comm_create_errhandler
* ================== 37*/
int E_Comm_create_errhandler(MPI_Comm_errhandler_function *function,
MPI_Errhandler *errhandler, int i, vector *v) {
void *f_dl = NULL;
counters[37]++;
QMPI_TABLE_QUERY(37, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 37, v, function, errhandler);
return ret;
}
/* ================== C Wrappers for MPI_Comm_create_group ==================
* 38*/
int E_Comm_create_group(MPI_Comm comm, MPI_Group group, int tag,
MPI_Comm *newcomm, int i, vector *v) {
void *f_dl = NULL;
counters[38]++;
QMPI_TABLE_QUERY(38, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 38, v, comm, group, tag, newcomm);
return ret;
}
/* ================== C Wrappers for MPI_Comm_create_keyval
* ==================39*/
int E_Comm_create_keyval(MPI_Comm_copy_attr_function *comm_copy_attr_fn,
MPI_Comm_delete_attr_function *comm_delete_attr_fn,
int *comm_keyval, void *extra_state, int i,
vector *v) {
void *f_dl = NULL;
counters[39]++;
QMPI_TABLE_QUERY(39, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 39, v, comm_copy_attr_fn, comm_delete_attr_fn,
comm_keyval, extra_state);
return ret;
}
/* ================== C Wrappers for MPI_Comm_delete_attr ==================
* 40*/
int E_Comm_delete_attr(MPI_Comm comm, int comm_keyval, int i, vector *v) {
void *f_dl = NULL;
counters[40]++;
QMPI_TABLE_QUERY(40, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 40, v, comm, comm_keyval);
return ret;
}
/* ================== C Wrappers for MPI_Comm_disconnect ================== 41*/
int E_Comm_disconnect(MPI_Comm *comm, int i, vector *v) {
void *f_dl = NULL;
counters[41]++;
QMPI_TABLE_QUERY(41, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 41, v, comm);
return ret;
}
/* ================== C Wrappers for MPI_Comm_dup ==================42*/
int E_Comm_dup(MPI_Comm comm, MPI_Comm *newcomm, int i, vector *v) {
void *f_dl = NULL;
counters[42]++;
QMPI_TABLE_QUERY(42, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 42, v, comm, newcomm);
return ret;
}
/* ================== C Wrappers for MPI_Comm_dup_with_info ==================
* 43*/
int E_Comm_dup_with_info(MPI_Comm comm, MPI_Info info, MPI_Comm *newcomm, int i,
vector *v) {
void *f_dl = NULL;
counters[43]++;
QMPI_TABLE_QUERY(43, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 43, v, comm, info, newcomm);
return ret;
}
/* ================== C Wrappers for MPI_Comm_free ==================44 */
int E_Comm_free(MPI_Comm *comm, int i, vector *v) {
void *f_dl = NULL;
counters[44]++;
QMPI_TABLE_QUERY(44, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 44, v, comm);
return ret;
}
/* ================== C Wrappers for MPI_Comm_free_keyval ==================
* 45*/
int E_Comm_free_keyval(int *comm_keyval, int i, vector *v) {
void *f_dl = NULL;
counters[45]++;
QMPI_TABLE_QUERY(45, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 45, v, comm_keyval);
return ret;
}
/* ================== C Wrappers for MPI_Comm_get_attr ================== 46*/
int E_Comm_get_attr(MPI_Comm comm, int comm_keyval, void *attribute_val,
int *flag, int i, vector *v) {
void *f_dl = NULL;
counters[46]++;
QMPI_TABLE_QUERY(46, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 46, v, comm, comm_keyval, attribute_val, flag);
return ret;
}
/* ================== C Wrappers for MPI_Comm_get_errhandler ==================
* 47*/
int E_Comm_get_errhandler(MPI_Comm comm, MPI_Errhandler *erhandler, int i,
vector *v) {
void *f_dl = NULL;
counters[47]++;
QMPI_TABLE_QUERY(47, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 47, v, comm, erhandler);
return ret;
}
/* ================== C Wrappers for MPI_Comm_get_info ================== 48*/
int E_Comm_get_info(MPI_Comm comm, MPI_Info *info_used, int i, vector *v) {
void *f_dl = NULL;
counters[48]++;
QMPI_TABLE_QUERY(48, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 48, v, comm, info_used);
return ret;
}
/* ================== C Wrappers for MPI_Comm_get_name ==================49 */
int E_Comm_get_name(MPI_Comm comm, char *comm_name, int *resultlen, int i,
vector *v) {
void *f_dl = NULL;
counters[49]++;
QMPI_TABLE_QUERY(49, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 49, v, comm, comm_name, resultlen);
return ret;
}
/* ================== C Wrappers for MPI_Comm_get_parent ================== 50*/
int E_Comm_get_parent(MPI_Comm *parent, int i, vector *v) {
void *f_dl = NULL;
counters[50]++;
QMPI_TABLE_QUERY(50, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 50, v, parent);
return ret;
}
/* ================== C Wrappers for MPI_Comm_group ==================51 */
int E_Comm_group(MPI_Comm comm, MPI_Group *group, int i, vector *v) {
void *f_dl = NULL;
counters[51]++;
QMPI_TABLE_QUERY(51, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 51, v, comm, group);
return ret;
}
/* ================== C Wrappers for MPI_Comm_idup ================== 52*/
int E_Comm_idup(MPI_Comm comm, MPI_Comm *newcomm, MPI_Request *request, int i,
vector *v) {
void *f_dl = NULL;
counters[52]++;
QMPI_TABLE_QUERY(52, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 52, v, comm, newcomm, request);
return ret;
}
/* ================== C Wrappers for MPI_Comm_join ================== 53*/
int E_Comm_join(int fd, MPI_Comm *intercomm, int i, vector *v) {
void *f_dl = NULL;
counters[53]++;
QMPI_TABLE_QUERY(53, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 53, v, fd, intercomm);
return ret;
}
/* ================== C Wrappers for MPI_Comm_rank ================== 54*/
int E_Comm_rank(MPI_Comm comm, int *rank, int i, vector *v) {
void *f_dl = NULL;
counters[54]++;
QMPI_TABLE_QUERY(54, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 54, v, comm, rank);
return ret;
}
/* ================== C Wrappers for MPI_Comm_remote_group ==================
* 55*/
int E_Comm_remote_group(MPI_Comm comm, MPI_Group *group, int i, vector *v) {
void *f_dl = NULL;
counters[55]++;
QMPI_TABLE_QUERY(55, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 55, v, comm, group);
return ret;
}
/* ================== C Wrappers for MPI_Comm_remote_size ==================
* 56*/
int E_Comm_remote_size(MPI_Comm comm, int *size, int i, vector *v) {
void *f_dl = NULL;
counters[56]++;
QMPI_TABLE_QUERY(56, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 56, v, comm, size);
return ret;
}
/* ================== C Wrappers for MPI_Comm_set_attr ================== 57*/
int E_Comm_set_attr(MPI_Comm comm, int comm_keyval, void *attribute_val, int i,
vector *v) {
void *f_dl = NULL;
counters[57]++;
QMPI_TABLE_QUERY(57, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 57, v, comm, comm_keyval, attribute_val);
return ret;
}
/* ================== C Wrappers for MPI_Comm_set_errhandler
* ==================58 */
int E_Comm_set_errhandler(MPI_Comm comm, MPI_Errhandler errhandler, int i,
vector *v) {
void *f_dl = NULL;
counters[58]++;
QMPI_TABLE_QUERY(58, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 58, v, comm, errhandler);
return ret;
}
/* ================== C Wrappers for MPI_Comm_set_info ================== 59*/
int E_Comm_set_info(MPI_Comm comm, MPI_Info info, int i, vector *v) {
void *f_dl = NULL;
counters[59]++;
QMPI_TABLE_QUERY(59, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 59, v, comm, info);
return ret;
}
/* ================== C Wrappers for MPI_Comm_set_name ================== 60*/
int E_Comm_set_name(MPI_Comm comm, const char *comm_name, int i, vector *v) {
void *f_dl = NULL;
counters[60]++;
QMPI_TABLE_QUERY(60, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 60, v, comm, comm_name);
return ret;
}
/* ================== C Wrappers for MPI_Comm_size ================== 61*/
int E_Comm_size(MPI_Comm comm, int *size, int i, vector *v) {
void *f_dl = NULL;
counters[61]++;
QMPI_TABLE_QUERY(61, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 61, v, comm, size);
return ret;
}
/* ================== C Wrappers for MPI_Comm_split ================== */
int E_Comm_split(MPI_Comm comm, int color, int key, MPI_Comm *newcomm, int i,
vector *v) {
void *f_dl = NULL;
counters[62]++;
QMPI_TABLE_QUERY(62, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 62, v, comm, color, key, newcomm);
return ret;
}
/* ================== C Wrappers for MPI_Comm_split_type ================== */
int E_Comm_split_type(MPI_Comm comm, int split_type, int key, MPI_Info info,
MPI_Comm *newcomm, int i, vector *v) {
void *f_dl = NULL;
counters[63]++;
QMPI_TABLE_QUERY(63, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 63, v, comm, split_type, key, info, newcomm);
return ret;
}
/* ================== C Wrappers for MPI_Comm_test_inter ================== */
int E_Comm_test_inter(MPI_Comm comm, int *flag, int i, vector *v) {
void *f_dl = NULL;
counters[64]++;
QMPI_TABLE_QUERY(64, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 64, v, comm, flag);
return ret;
}
/* ================== C Wrappers for MPI_Compare_and_swap ================== */
int E_Compare_and_swap(const void *origin_addr, const void *compare_addr,
void *result_addr, MPI_Datatype datatype,
int target_rank, MPI_Aint target_disp, MPI_Win win,
int i, vector *v) {
void *f_dl = NULL;
counters[65]++;
QMPI_TABLE_QUERY(65, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 65, v, origin_addr, compare_addr, result_addr,
datatype, target_rank, target_disp, win);
return ret;
}
/* ================== C Wrappers for MPI_Dims_create ================== */
int E_Dims_create(int nnodes, int ndims, int dims[], int i, vector *v) {
void *f_dl = NULL;
counters[66]++;
QMPI_TABLE_QUERY(66, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 66, v, nnodes, ndims, dims);
return ret;
}
/* ================== C Wrappers for MPI_Dist_graph_create ================== */
int E_Dist_graph_create(MPI_Comm comm_old, int n, const int nodes[],
const int degrees[], const int targets[],
const int weights[], MPI_Info info, int reorder,
MPI_Comm *newcomm, int i, vector *v) {
void *f_dl = NULL;
counters[67]++;
QMPI_TABLE_QUERY(67, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 67, v, comm_old, n, nodes, degrees, targets,
weights, info, reorder, newcomm);
return ret;
}
/* ================== C Wrappers for MPI_Dist_graph_create_adjacent
* ================== */
int E_Dist_graph_create_adjacent(MPI_Comm comm_old, int indegree,
const int sources[], const int sourceweights[],
int outdegree, const int destinations[],
const int destweights[], MPI_Info info,
int reorder, MPI_Comm *comm_dist_graph, int i,
vector *v) {
void *f_dl = NULL;
counters[68]++;
QMPI_TABLE_QUERY(68, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 68, v, comm_old, indegree, sources,
sourceweights, outdegree, destinations, destweights,
info, reorder, comm_dist_graph);
return ret;
}
/* ================== C Wrappers for MPI_Dist_graph_neighbors ==================
*/
int E_Dist_graph_neighbors(MPI_Comm comm, int maxindegree, int sources[],
int sourceweights[], int maxoutdegree,
int destinations[], int destweights[], int i,
vector *v) {
void *f_dl = NULL;
counters[69]++;
QMPI_TABLE_QUERY(69, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 69, v, comm, maxindegree, sources,
sourceweights, maxoutdegree, destinations, destweights);
return ret;
}
/* ================== C Wrappers for MPI_Dist_graph_neighbors_count
* ================== */
int E_Dist_graph_neighbors_count(MPI_Comm comm, int *inneighbors,
int *outneighbors, int *weighted, int i,
vector *v) {
void *f_dl = NULL;
counters[70]++;
QMPI_TABLE_QUERY(70, &f_dl, (*VECTOR_GET(v, i)).table);
int ret =
EXEC_FUNC(f_dl, i, 70, v, comm, inneighbors, outneighbors, weighted);
return ret;
}
/* ================== C Wrappers for MPI_Errhandler_create ================== */
int E_Errhandler_create(MPI_Handler_function *function,
MPI_Errhandler *errhandler, int i, vector *v) {
void *f_dl = NULL;
counters[71]++;
QMPI_TABLE_QUERY(71, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 71, v, function, errhandler);
return ret;
}
/* ================== C Wrappers for MPI_Errhandler_free ================== */
int E_Errhandler_free(MPI_Errhandler *errhandler, int i, vector *v) {
void *f_dl = NULL;
counters[72]++;
QMPI_TABLE_QUERY(72, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 72, v, errhandler);
return ret;
}
/* ================== C Wrappers for MPI_Errhandler_get ================== */
int E_Errhandler_get(MPI_Comm comm, MPI_Errhandler *errhandler, int i,
vector *v) {
void *f_dl = NULL;
counters[73]++;
QMPI_TABLE_QUERY(73, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 73, v, comm, errhandler);
return ret;
}
/* ================== C Wrappers for MPI_Errhandler_set ================== */
int E_Errhandler_set(MPI_Comm comm, MPI_Errhandler errhandler, int i,
vector *v) {
void *f_dl = NULL;
counters[74]++;
QMPI_TABLE_QUERY(74, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 74, v, comm, errhandler);
return ret;
}
/* ================== C Wrappers for MPI_Error_class ================== */
int E_Error_class(int errorcode, int *errorclass, int i, vector *v) {
void *f_dl = NULL;
counters[75]++;
QMPI_TABLE_QUERY(75, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 75, v, errorcode, errorclass);
return ret;
}
/* ================== C Wrappers for MPI_Error_string ================== */
int E_Error_string(int errorcode, char *string, int *resultlen, int i,
vector *v) {
void *f_dl = NULL;
counters[76]++;
QMPI_TABLE_QUERY(76, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 76, v, errorcode, string, resultlen);
return ret;
}
/* ================== C Wrappers for MPI_Exscan ================== */
int E_Exscan(const void *sendbuf, void *recvbuf, int count,
MPI_Datatype datatype, MPI_Op op, MPI_Comm comm, int i,
vector *v) {
void *f_dl = NULL;
counters[77]++;
QMPI_TABLE_QUERY(77, &f_dl, (*VECTOR_GET(v, i)).table);
int ret =
EXEC_FUNC(f_dl, i, 77, v, sendbuf, recvbuf, count, datatype, op, comm);
return ret;
}
/* ================== C Wrappers for MPI_Fetch_and_op ================== */
int E_Fetch_and_op(const void *origin_addr, void *result_addr,
MPI_Datatype datatype, int target_rank, MPI_Aint target_disp,
MPI_Op op, MPI_Win win, int i, vector *v) {
void *f_dl = NULL;
counters[78]++;
QMPI_TABLE_QUERY(78, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 78, v, origin_addr, result_addr, datatype,
target_rank, target_disp, op, win);
return ret;
}
/* ================== C Wrappers for MPI_File_call_errhandler ==================
*/
int E_File_call_errhandler(MPI_File fh, int errorcode, int i, vector *v) {
void *f_dl = NULL;
counters[79]++;
QMPI_TABLE_QUERY(79, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 79, v, fh, errorcode);
return ret;
}
/* ================== C Wrappers for MPI_File_close ================== */
int E_File_close(MPI_File *fh, int i, vector *v) {
void *f_dl = NULL;
counters[80]++;
QMPI_TABLE_QUERY(80, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 80, v, fh);
return ret;
}
/* ================== C Wrappers for MPI_File_create_errhandler
* ================== */
int E_File_create_errhandler(MPI_File_errhandler_function *function,
MPI_Errhandler *errhandler, int i, vector *v) {
void *f_dl = NULL;
counters[81]++;
QMPI_TABLE_QUERY(81, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 81, v, function, errhandler);
return ret;
}
/* ================== C Wrappers for MPI_File_delete ================== */
int E_File_delete(const char *filename, MPI_Info info, int i, vector *v) {
void *f_dl = NULL;
counters[82]++;
QMPI_TABLE_QUERY(82, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 82, v, filename, info);
return ret;
}
/* ================== C Wrappers for MPI_File_get_amode ================== */
int E_File_get_amode(MPI_File fh, int *amode, int i, vector *v) {
void *f_dl = NULL;
counters[83]++;
QMPI_TABLE_QUERY(83, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 83, v, fh, amode);
return ret;
}
/* ================== C Wrappers for MPI_File_get_atomicity ==================
*/
int E_File_get_atomicity(MPI_File fh, int *flag, int i, vector *v) {
void *f_dl = NULL;
counters[84]++;
QMPI_TABLE_QUERY(84, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 84, v, fh, flag);
return ret;
}
/* ================== C Wrappers for MPI_File_get_byte_offset ==================
*/
int E_File_get_byte_offset(MPI_File fh, MPI_Offset offset, MPI_Offset *disp,
int i, vector *v) {
void *f_dl = NULL;
counters[85]++;
QMPI_TABLE_QUERY(85, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 85, v, fh, offset, disp);
return ret;
}
/* ================== C Wrappers for MPI_File_get_errhandler ==================
*/
int E_File_get_errhandler(MPI_File file, MPI_Errhandler *errhandler, int i,
vector *v) {
void *f_dl = NULL;
counters[86]++;
QMPI_TABLE_QUERY(86, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 86, v, file, errhandler);
return ret;
}
/* ================== C Wrappers for MPI_File_get_group ================== */
int E_File_get_group(MPI_File fh, MPI_Group *group, int i, vector *v) {
void *f_dl = NULL;
counters[87]++;
QMPI_TABLE_QUERY(87, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 87, v, fh, group);
return ret;
}
/* ================== C Wrappers for MPI_File_get_info ================== */
int E_File_get_info(MPI_File fh, MPI_Info *info_used, int i, vector *v) {
void *f_dl = NULL;
counters[88]++;
QMPI_TABLE_QUERY(88, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 88, v, fh, info_used);
return ret;
}
/* ================== C Wrappers for MPI_File_get_position ================== */
int E_File_get_position(MPI_File fh, MPI_Offset *offset, int i, vector *v) {
void *f_dl = NULL;
counters[89]++;
QMPI_TABLE_QUERY(89, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 89, v, fh, offset);
return ret;
}
/* ================== C Wrappers for MPI_File_get_position_shared
* ================== */
int E_File_get_position_shared(MPI_File fh, MPI_Offset *offset, int i,
vector *v) {
void *f_dl = NULL;
counters[90]++;
QMPI_TABLE_QUERY(90, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 90, v, fh, offset);
return ret;
}
/* ================== C Wrappers for MPI_File_get_size ================== */
int E_File_get_size(MPI_File fh, MPI_Offset *size, int i, vector *v) {
void *f_dl = NULL;
counters[91]++;
QMPI_TABLE_QUERY(91, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 91, v, fh, size);
return ret;
}
/* ================== C Wrappers for MPI_File_get_type_extent ==================
*/
int E_File_get_type_extent(MPI_File fh, MPI_Datatype datatype, MPI_Aint *extent,
int i, vector *v) {
void *f_dl = NULL;
counters[92]++;
QMPI_TABLE_QUERY(92, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 92, v, fh, datatype, extent);
return ret;
}
/* ================== C Wrappers for MPI_File_get_view ================== */
int E_File_get_view(MPI_File fh, MPI_Offset *disp, MPI_Datatype *etype,
MPI_Datatype *filetype, char *datarep, int i, vector *v) {
void *f_dl = NULL;
counters[93]++;
QMPI_TABLE_QUERY(93, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 93, v, fh, disp, etype, filetype, datarep);
return ret;
}
/* ================== C Wrappers for MPI_File_iread ================== */
int E_File_iread(MPI_File fh, void *buf, int count, MPI_Datatype datatype,
MPI_Request *request, int i, vector *v) {
void *f_dl = NULL;
counters[94]++;
QMPI_TABLE_QUERY(94, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 94, v, fh, buf, count, datatype, request);
return ret;
}
/* ================== C Wrappers for MPI_File_iread_all ================== */
int E_File_iread_all(MPI_File fh, void *buf, int count, MPI_Datatype datatype,
MPI_Request *request, int i, vector *v) {
void *f_dl = NULL;
counters[95]++;
QMPI_TABLE_QUERY(95, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 95, v, fh, buf, count, datatype, request);
return ret;
}
/* ================== C Wrappers for MPI_File_iread_at ================== */
int E_File_iread_at(MPI_File fh, MPI_Offset offset, void *buf, int count,
MPI_Datatype datatype, MPI_Request *request, int i,
vector *v) {
void *f_dl = NULL;
counters[96]++;
QMPI_TABLE_QUERY(96, &f_dl, (*VECTOR_GET(v, i)).table);
int ret =
EXEC_FUNC(f_dl, i, 96, v, fh, offset, buf, count, datatype, request);
return ret;
}
/* ================== C Wrappers for MPI_File_iread_at_all ================== */
int E_File_iread_at_all(MPI_File fh, MPI_Offset offset, void *buf, int count,
MPI_Datatype datatype, MPI_Request *request, int i,
vector *v) {
void *f_dl = NULL;
counters[97]++;
QMPI_TABLE_QUERY(97, &f_dl, (*VECTOR_GET(v, i)).table);
int ret =
EXEC_FUNC(f_dl, i, 97, v, fh, offset, buf, count, datatype, request);
return ret;
}
/* ================== C Wrappers for MPI_File_iread_shared ================== */
int E_File_iread_shared(MPI_File fh, void *buf, int count,
MPI_Datatype datatype, MPI_Request *request, int i,
vector *v) {
void *f_dl = NULL;
counters[98]++;
QMPI_TABLE_QUERY(98, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 98, v, fh, buf, count, datatype, request);
return ret;
}
/* ================== C Wrappers for MPI_File_iwrite ================== */
int E_File_iwrite(MPI_File fh, const void *buf, int count,
MPI_Datatype datatype, MPI_Request *request, int i,
vector *v) {
void *f_dl = NULL;
counters[99]++;
QMPI_TABLE_QUERY(99, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 99, v, fh, buf, count, datatype, request);
return ret;
}
/* ================== C Wrappers for MPI_File_iwrite_all ================== */
int E_File_iwrite_all(MPI_File fh, const void *buf, int count,
MPI_Datatype datatype, MPI_Request *request, int i,
vector *v) {
void *f_dl = NULL;
counters[100]++;
QMPI_TABLE_QUERY(100, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 100, v, fh, buf, count, datatype, request);
return ret;
}
/* ================== C Wrappers for MPI_File_iwrite_at ================== */
int E_File_iwrite_at(MPI_File fh, MPI_Offset offset, const void *buf, int count,
MPI_Datatype datatype, MPI_Request *request, int i,
vector *v) {
void *f_dl = NULL;
counters[101]++;
QMPI_TABLE_QUERY(101, &f_dl, (*VECTOR_GET(v, i)).table);
int ret =
EXEC_FUNC(f_dl, i, 101, v, fh, offset, buf, count, datatype, request);
return ret;
}
/* ================== C Wrappers for MPI_File_iwrite_at_all ==================
*/
int E_File_iwrite_at_all(MPI_File fh, MPI_Offset offset, const void *buf,
int count, MPI_Datatype datatype, MPI_Request *request,
int i, vector *v) {
void *f_dl = NULL;
counters[102]++;
QMPI_TABLE_QUERY(102, &f_dl, (*VECTOR_GET(v, i)).table);
int ret =
EXEC_FUNC(f_dl, i, 102, v, fh, offset, buf, count, datatype, request);
return ret;
}
/* ================== C Wrappers for MPI_File_iwrite_shared ==================
*/
int E_File_iwrite_shared(MPI_File fh, const void *buf, int count,
MPI_Datatype datatype, MPI_Request *request, int i,
vector *v) {
void *f_dl = NULL;
counters[103]++;
QMPI_TABLE_QUERY(103, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 103, v, fh, buf, count, datatype, request);
return ret;
}
/* ================== C Wrappers for MPI_File_open ================== */
int E_File_open(MPI_Comm comm, const char *filename, int amode, MPI_Info info,
MPI_File *fh, int i, vector *v) {
void *f_dl = NULL;
counters[104]++;
QMPI_TABLE_QUERY(104, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 104, v, comm, filename, amode, info, fh);
return ret;
}
/* ================== C Wrappers for MPI_File_preallocate ================== */
int E_File_preallocate(MPI_File fh, MPI_Offset size, int i, vector *v) {
void *f_dl = NULL;
counters[105]++;
QMPI_TABLE_QUERY(105, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 105, v, fh, size);
return ret;
}
/* ================== C Wrappers for MPI_File_read ================== */
int E_File_read(MPI_File fh, void *buf, int count, MPI_Datatype datatype,
MPI_Status *status, int i, vector *v) {
void *f_dl = NULL;
counters[106]++;
QMPI_TABLE_QUERY(106, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 106, v, fh, buf, count, datatype, status);
return ret;
}
/* ================== C Wrappers for MPI_File_read_all ================== */
int E_File_read_all(MPI_File fh, void *buf, int count, MPI_Datatype datatype,
MPI_Status *status, int i, vector *v) {
void *f_dl = NULL;
counters[107]++;
QMPI_TABLE_QUERY(107, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 107, v, fh, buf, count, datatype, status);
return ret;
}
/* ================== C Wrappers for MPI_File_read_all_begin ==================
*/
int E_File_read_all_begin(MPI_File fh, void *buf, int count,
MPI_Datatype datatype, int i, vector *v) {
void *f_dl = NULL;
counters[108]++;
QMPI_TABLE_QUERY(108, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 108, v, fh, buf, count, datatype);
return ret;
}
/* ================== C Wrappers for MPI_File_read_all_end ================== */
int E_File_read_all_end(MPI_File fh, void *buf, MPI_Status *status, int i,
vector *v) {
void *f_dl = NULL;
counters[109]++;
QMPI_TABLE_QUERY(109, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 109, v, fh, buf, status);
return ret;
}
/* ================== C Wrappers for MPI_File_read_at ================== */
int E_File_read_at(MPI_File fh, MPI_Offset offset, void *buf, int count,
MPI_Datatype datatype, MPI_Status *status, int i,
vector *v) {
void *f_dl = NULL;
counters[110]++;
QMPI_TABLE_QUERY(110, &f_dl, (*VECTOR_GET(v, i)).table);
int ret =
EXEC_FUNC(f_dl, i, 110, v, fh, offset, buf, count, datatype, status);
return ret;
}
/* ================== C Wrappers for MPI_File_read_at_all ================== */
int E_File_read_at_all(MPI_File fh, MPI_Offset offset, void *buf, int count,
MPI_Datatype datatype, MPI_Status *status, int i,
vector *v) {
void *f_dl = NULL;
counters[111]++;
QMPI_TABLE_QUERY(111, &f_dl, (*VECTOR_GET(v, i)).table);
int ret =
EXEC_FUNC(f_dl, i, 111, v, fh, offset, buf, count, datatype, status);
return ret;
}
/* ================== C Wrappers for MPI_File_read_at_all_begin
* ================== */
int E_File_read_at_all_begin(MPI_File fh, MPI_Offset offset, void *buf,
int count, MPI_Datatype datatype, int i,
vector *v) {
void *f_dl = NULL;
counters[112]++;
QMPI_TABLE_QUERY(112, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 112, v, fh, offset, buf, count, datatype);
return ret;
}
/* ================== C Wrappers for MPI_File_read_at_all_end ==================
*/
int E_File_read_at_all_end(MPI_File fh, void *buf, MPI_Status *status, int i,
vector *v) {
void *f_dl = NULL;
counters[113]++;
QMPI_TABLE_QUERY(113, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 113, v, fh, buf, status);
return ret;
}
/* ================== C Wrappers for MPI_File_read_ordered ================== */
int E_File_read_ordered(MPI_File fh, void *buf, int count,
MPI_Datatype datatype, MPI_Status *status, int i,
vector *v) {
void *f_dl = NULL;
counters[114]++;
QMPI_TABLE_QUERY(114, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 114, v, fh, buf, count, datatype, status);
return ret;
}
/* ================== C Wrappers for MPI_File_read_ordered_begin
* ================== */
int E_File_read_ordered_begin(MPI_File fh, void *buf, int count,
MPI_Datatype datatype, int i, vector *v) {
void *f_dl = NULL;
counters[115]++;
QMPI_TABLE_QUERY(115, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 115, v, fh, buf, count, datatype);
return ret;
}
/* ================== C Wrappers for MPI_File_read_ordered_end
* ================== */
int E_File_read_ordered_end(MPI_File fh, void *buf, MPI_Status *status, int i,
vector *v) {
void *f_dl = NULL;
counters[116]++;
QMPI_TABLE_QUERY(116, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 116, v, fh, buf, status);
return ret;
}
/* ================== C Wrappers for MPI_File_read_shared ================== */
int E_File_read_shared(MPI_File fh, void *buf, int count, MPI_Datatype datatype,
MPI_Status *status, int i, vector *v) {
void *f_dl = NULL;
counters[117]++;
QMPI_TABLE_QUERY(117, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 117, v, fh, buf, count, datatype, status);
return ret;
}
/* ================== C Wrappers for MPI_File_seek ================== */
int E_File_seek(MPI_File fh, MPI_Offset offset, int whence, int i, vector *v) {
void *f_dl = NULL;
counters[118]++;
QMPI_TABLE_QUERY(118, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 118, v, fh, offset, whence);
return ret;
}
/* ================== C Wrappers for MPI_File_seek_shared ================== */
int E_File_seek_shared(MPI_File fh, MPI_Offset offset, int whence, int i,
vector *v) {
void *f_dl = NULL;
counters[119]++;
QMPI_TABLE_QUERY(119, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 119, v, fh, offset, whence);
return ret;
}
/* ================== C Wrappers for MPI_File_set_atomicity ==================
*/
int E_File_set_atomicity(MPI_File fh, int flag, int i, vector *v) {
void *f_dl = NULL;
counters[120]++;
QMPI_TABLE_QUERY(120, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 120, v, fh, flag);
return ret;
}
/* ================== C Wrappers for MPI_File_set_errhandler ==================
*/
int E_File_set_errhandler(MPI_File file, MPI_Errhandler errhandler, int i,
vector *v) {
void *f_dl = NULL;
counters[121]++;
QMPI_TABLE_QUERY(121, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 121, v, file, errhandler);
return ret;
}
/* ================== C Wrappers for MPI_File_set_info ================== */
int E_File_set_info(MPI_File fh, MPI_Info info, int i, vector *v) {
void *f_dl = NULL;
counters[122]++;
QMPI_TABLE_QUERY(122, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 122, v, fh, info);
return ret;
}
/* ================== C Wrappers for MPI_File_set_size ================== */
int E_File_set_size(MPI_File fh, MPI_Offset size, int i, vector *v) {
void *f_dl = NULL;
counters[123]++;
QMPI_TABLE_QUERY(123, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 123, v, fh, size);
return ret;
}
/* ================== C Wrappers for MPI_File_set_view ================== */
int E_File_set_view(MPI_File fh, MPI_Offset disp, MPI_Datatype etype,
MPI_Datatype filetype, const char *datarep, MPI_Info info,
int i, vector *v) {
void *f_dl = NULL;
counters[124]++;
QMPI_TABLE_QUERY(124, &f_dl, (*VECTOR_GET(v, i)).table);
int ret =
EXEC_FUNC(f_dl, i, 124, v, fh, disp, etype, filetype, datarep, info);
return ret;
}
/* ================== C Wrappers for MPI_File_sync ================== */
int E_File_sync(MPI_File fh, int i, vector *v) {
void *f_dl = NULL;
counters[125]++;
QMPI_TABLE_QUERY(125, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 125, v, fh);
return ret;
}
/* ================== C Wrappers for MPI_File_write ================== */
int E_File_write(MPI_File fh, const void *buf, int count, MPI_Datatype datatype,
MPI_Status *status, int i, vector *v) {
void *f_dl = NULL;
counters[126]++;
QMPI_TABLE_QUERY(126, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 126, v, fh, buf, count, datatype, status);
return ret;
}
/* ================== C Wrappers for MPI_File_write_all ================== */
int E_File_write_all(MPI_File fh, const void *buf, int count,
MPI_Datatype datatype, MPI_Status *status, int i,
vector *v) {
void *f_dl = NULL;
counters[127]++;
QMPI_TABLE_QUERY(127, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 127, v, fh, buf, count, datatype, status);
return ret;
}
/* ================== C Wrappers for MPI_File_write_all_begin ==================
*/
int E_File_write_all_begin(MPI_File fh, const void *buf, int count,
MPI_Datatype datatype, int i, vector *v) {
void *f_dl = NULL;
counters[128]++;
QMPI_TABLE_QUERY(128, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 128, v, fh, buf, count, datatype);
return ret;
}
/* ================== C Wrappers for MPI_File_write_all_end ==================
*/
int E_File_write_all_end(MPI_File fh, const void *buf, MPI_Status *status,
int i, vector *v) {
void *f_dl = NULL;
counters[129]++;
QMPI_TABLE_QUERY(129, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 129, v, fh, buf, status);
return ret;
}
/* ================== C Wrappers for MPI_File_write_at ================== */
int E_File_write_at(MPI_File fh, MPI_Offset offset, const void *buf, int count,
MPI_Datatype datatype, MPI_Status *status, int i,
vector *v) {
void *f_dl = NULL;
counters[130]++;
QMPI_TABLE_QUERY(130, &f_dl, (*VECTOR_GET(v, i)).table);
int ret =
EXEC_FUNC(f_dl, i, 130, v, fh, offset, buf, count, datatype, status);
return ret;
}
/* ================== C Wrappers for MPI_File_write_at_all ================== */
int E_File_write_at_all(MPI_File fh, MPI_Offset offset, const void *buf,
int count, MPI_Datatype datatype, MPI_Status *status,
int i, vector *v) {
void *f_dl = NULL;
counters[131]++;
QMPI_TABLE_QUERY(131, &f_dl, (*VECTOR_GET(v, i)).table);
int ret =
EXEC_FUNC(f_dl, i, 131, v, fh, offset, buf, count, datatype, status);
return ret;
}
/* ================== C Wrappers for MPI_File_write_at_all_begin
* ================== */
int E_File_write_at_all_begin(MPI_File fh, MPI_Offset offset, const void *buf,
int count, MPI_Datatype datatype, int i,
vector *v) {
void *f_dl = NULL;
counters[132]++;
QMPI_TABLE_QUERY(132, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 132, v, fh, offset, buf, count, datatype);
return ret;
}
/* ================== C Wrappers for MPI_File_write_at_all_end
* ================== */
int E_File_write_at_all_end(MPI_File fh, const void *buf, MPI_Status *status,
int i, vector *v) {
void *f_dl = NULL;
counters[133]++;
QMPI_TABLE_QUERY(133, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 133, v, fh, buf, status);
return ret;
}
/* ================== C Wrappers for MPI_File_write_ordered ==================
*/
int E_File_write_ordered(MPI_File fh, const void *buf, int count,
MPI_Datatype datatype, MPI_Status *status, int i,
vector *v) {
void *f_dl = NULL;
counters[134]++;
QMPI_TABLE_QUERY(134, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 134, v, fh, buf, count, datatype, status);
return ret;
}
/* ================== C Wrappers for MPI_File_write_ordered_begin
* ================== */
int E_File_write_ordered_begin(MPI_File fh, const void *buf, int count,
MPI_Datatype datatype, int i, vector *v) {
void *f_dl = NULL;
counters[135]++;
QMPI_TABLE_QUERY(135, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 135, v, fh, buf, count, datatype);
return ret;
}
/* ================== C Wrappers for MPI_File_write_ordered_end
* ================== */
int E_File_write_ordered_end(MPI_File fh, const void *buf, MPI_Status *status,
int i, vector *v) {
void *f_dl = NULL;
counters[136]++;
QMPI_TABLE_QUERY(136, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 136, v, fh, buf, status);
return ret;
}
/* ================== C Wrappers for MPI_File_write_shared ================== */
int E_File_write_shared(MPI_File fh, const void *buf, int count,
MPI_Datatype datatype, MPI_Status *status, int i,
vector *v) {
void *f_dl = NULL;
counters[137]++;
QMPI_TABLE_QUERY(137, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 137, v, fh, buf, count, datatype, status);
return ret;
}
/* ================== C Wrappers for MPI_Finalized ================== */
int E_Finalized(int *flag, int i, vector *v) {
void *f_dl = NULL;
counters[139]++;
QMPI_TABLE_QUERY(139, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 139, v, flag);
return ret;
}
/* ================== C Wrappers for MPI_Free_mem ================== */
int E_Free_mem(void *base, int i, vector *v) {
void *f_dl = NULL;
counters[140]++;
QMPI_TABLE_QUERY(140, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 140, v, base);
return ret;
}
/* ================== C Wrappers for MPI_Gather ================== */
int E_Gather(const void *sendbuf, int sendcount, MPI_Datatype sendtype,
void *recvbuf, int recvcount, MPI_Datatype recvtype, int root,
MPI_Comm comm, int i, vector *v) {
void *f_dl = NULL;
counters[141]++;
QMPI_TABLE_QUERY(141, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 141, v, sendbuf, sendcount, sendtype, recvbuf,
recvcount, recvtype, root, comm);
return ret;
}
/* ================== C Wrappers for MPI_Gatherv ================== */
int E_Gatherv(const void *sendbuf, int sendcount, MPI_Datatype sendtype,
void *recvbuf, const int recvcounts[], const int displs[],
MPI_Datatype recvtype, int root, MPI_Comm comm, int i,
vector *v) {
void *f_dl = NULL;
counters[142]++;
QMPI_TABLE_QUERY(142, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 142, v, sendbuf, sendcount, sendtype, recvbuf,
recvcounts, displs, recvtype, root, comm);
return ret;
}
/* ================== C Wrappers for MPI_Get ================== */
int E_Get(void *origin_addr, int origin_count, MPI_Datatype origin_datatype,
int target_rank, MPI_Aint target_disp, int target_count,
MPI_Datatype target_datatype, MPI_Win win, int i, vector *v) {
void *f_dl = NULL;
counters[143]++;
QMPI_TABLE_QUERY(143, &f_dl, (*VECTOR_GET(v, i)).table);
int ret =
EXEC_FUNC(f_dl, i, 143, v, origin_addr, origin_count, origin_datatype,
target_rank, target_disp, target_count, target_datatype, win);
return ret;
}
/* ================== C Wrappers for MPI_Get_accumulate ================== */
int E_Get_accumulate(const void *origin_addr, int origin_count,
MPI_Datatype origin_datatype, void *result_addr,
int result_count, MPI_Datatype result_datatype,
int target_rank, MPI_Aint target_disp, int target_count,
MPI_Datatype target_datatype, MPI_Op op, MPI_Win win,
int i, vector *v) {
void *f_dl = NULL;
counters[144]++;
QMPI_TABLE_QUERY(144, &f_dl, (*VECTOR_GET(v, i)).table);
int ret =
EXEC_FUNC(f_dl, i, 144, v, origin_addr, origin_count, origin_datatype,
result_addr, result_count, result_datatype, target_rank,
target_disp, target_count, target_datatype, op, win);
return ret;
}
/* ================== C Wrappers for MPI_Get_address ================== */
int E_Get_address(const void *location, MPI_Aint *address, int i, vector *v) {
void *f_dl = NULL;
counters[145]++;
QMPI_TABLE_QUERY(145, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 145, v, location, address);
return ret;
}
/* ================== C Wrappers for MPI_Get_count ================== */
int E_Get_count(const MPI_Status *status, MPI_Datatype datatype, int *count,
int i, vector *v) {
void *f_dl = NULL;
counters[146]++;
QMPI_TABLE_QUERY(146, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 146, v, status, datatype, count);
return ret;
}
/* ================== C Wrappers for MPI_Get_elements ================== */
int E_Get_elements(const MPI_Status *status, MPI_Datatype datatype, int *count,
int i, vector *v) {
void *f_dl = NULL;
counters[147]++;
QMPI_TABLE_QUERY(147, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 147, v, status, datatype, count);
return ret;
}
/* ================== C Wrappers for MPI_Get_elements_x ================== */
int E_Get_elements_x(const MPI_Status *status, MPI_Datatype datatype,
MPI_Count *count, int i, vector *v) {
void *f_dl = NULL;
counters[148]++;
QMPI_TABLE_QUERY(148, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 148, v, status, datatype, count);
return ret;
}
/* ================== C Wrappers for MPI_Get_library_version ==================
*/
int E_Get_library_version(char *version, int *resultlen, int i, vector *v) {
void *f_dl = NULL;
counters[149]++;
QMPI_TABLE_QUERY(149, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 149, v, version, resultlen);
return ret;
}
/* ================== C Wrappers for MPI_Get_processor_name ==================
*/
int E_Get_processor_name(char *name, int *resultlen, int i, vector *v) {
void *f_dl = NULL;
counters[150]++;
QMPI_TABLE_QUERY(150, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 150, v, name, resultlen);
return ret;
}
/* ================== C Wrappers for MPI_Get_version ================== */
int E_Get_version(int *version, int *subversion, int i, vector *v) {
void *f_dl = NULL;
counters[151]++;
QMPI_TABLE_QUERY(151, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 151, v, version, subversion);
return ret;
}
/* ================== C Wrappers for MPI_Graph_create ================== */
int E_Graph_create(MPI_Comm comm_old, int nnodes, const int index[],
const int edges[], int reorder, MPI_Comm *comm_graph, int i,
vector *v) {
void *f_dl = NULL;
counters[152]++;
QMPI_TABLE_QUERY(152, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 152, v, comm_old, nnodes, index, edges,
reorder, comm_graph);
return ret;
}
/* ================== C Wrappers for MPI_Graph_get ================== */
int E_Graph_get(MPI_Comm comm, int maxindex, int maxedges, int index[],
int edges[], int i, vector *v) {
void *f_dl = NULL;
counters[153]++;
QMPI_TABLE_QUERY(153, &f_dl, (*VECTOR_GET(v, i)).table);
int ret =
EXEC_FUNC(f_dl, i, 153, v, comm, maxindex, maxedges, index, edges);
return ret;
}
/* ================== C Wrappers for MPI_Graph_map ================== */
int E_Graph_map(MPI_Comm comm, int nnodes, const int index[], const int edges[],
int *newrank, int i, vector *v) {
void *f_dl = NULL;
counters[154]++;
QMPI_TABLE_QUERY(154, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 154, v, comm, nnodes, index, edges, newrank);
return ret;
}
/* ================== C Wrappers for MPI_Graph_neighbors ================== */
int E_Graph_neighbors(MPI_Comm comm, int rank, int maxneighbors,
int neighbors[], int i, vector *v) {
void *f_dl = NULL;
counters[155]++;
QMPI_TABLE_QUERY(155, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 155, v, comm, rank, maxneighbors, neighbors);
return ret;
}
/* ================== C Wrappers for MPI_Graph_neighbors_count
* ================== */
int E_Graph_neighbors_count(MPI_Comm comm, int rank, int *nneighbors, int i,
vector *v) {
void *f_dl = NULL;
counters[156]++;
QMPI_TABLE_QUERY(156, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 156, v, comm, rank, nneighbors);
return ret;
}
/* ================== C Wrappers for MPI_Graphdims_get ================== */
int E_Graphdims_get(MPI_Comm comm, int *nnodes, int *nedges, int i, vector *v) {
void *f_dl = NULL;
counters[157]++;
QMPI_TABLE_QUERY(157, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 157, v, comm, nnodes, nedges);
return ret;
}
/* ================== C Wrappers for MPI_Grequest_complete ================== */
int E_Grequest_complete(MPI_Request request, int i, vector *v) {
void *f_dl = NULL;
counters[158]++;
QMPI_TABLE_QUERY(158, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 158, v, request);
return ret;
}
/* ================== C Wrappers for MPI_Grequest_start ================== */
int E_Grequest_start(MPI_Grequest_query_function *query_fn,
MPI_Grequest_free_function *free_fn,
MPI_Grequest_cancel_function *cancel_fn, void *extra_state,
MPI_Request *request, int i, vector *v) {
void *f_dl = NULL;
counters[159]++;
QMPI_TABLE_QUERY(159, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 159, v, query_fn, free_fn, cancel_fn,
extra_state, request);
return ret;
}
/* ================== C Wrappers for MPI_Group_compare ================== */
int E_Group_compare(MPI_Group group1, MPI_Group group2, int *result, int i,
vector *v) {
void *f_dl = NULL;
counters[160]++;
QMPI_TABLE_QUERY(160, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 160, v, group1, group2, result);
return ret;
}
/* ================== C Wrappers for MPI_Group_difference ================== */
int E_Group_difference(MPI_Group group1, MPI_Group group2, MPI_Group *newgroup,
int i, vector *v) {
void *f_dl = NULL;
counters[161]++;
QMPI_TABLE_QUERY(161, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 161, v, group1, group2, newgroup);
return ret;
}
/* ================== C Wrappers for MPI_Group_excl ================== */
int E_Group_excl(MPI_Group group, int n, const int ranks[], MPI_Group *newgroup,
int i, vector *v) {
void *f_dl = NULL;
counters[162]++;
QMPI_TABLE_QUERY(162, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 162, v, group, n, ranks, newgroup);
return ret;
}
/* ================== C Wrappers for MPI_Group_free ================== */
int E_Group_free(MPI_Group *group, int i, vector *v) {
void *f_dl = NULL;
counters[163]++;
QMPI_TABLE_QUERY(163, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 163, v, group);
return ret;
}
/* ================== C Wrappers for MPI_Group_incl ================== */
int E_Group_incl(MPI_Group group, int n, const int ranks[], MPI_Group *newgroup,
int i, vector *v) {
void *f_dl = NULL;
counters[164]++;
QMPI_TABLE_QUERY(164, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 164, v, group, n, ranks, newgroup);
return ret;
}
/* ================== C Wrappers for MPI_Group_intersection ==================
*/
int E_Group_intersection(MPI_Group group1, MPI_Group group2,
MPI_Group *newgroup, int i, vector *v) {
void *f_dl = NULL;
counters[165]++;
QMPI_TABLE_QUERY(165, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 165, v, group1, group2, newgroup);
return ret;
}
/* ================== C Wrappers for MPI_Group_range_excl ================== */
int E_Group_range_excl(MPI_Group group, int n, int ranges[][3],
MPI_Group *newgroup, int i, vector *v) {
void *f_dl = NULL;
counters[166]++;
QMPI_TABLE_QUERY(166, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 166, v, group, n, ranges, newgroup);
return ret;
}
/* ================== C Wrappers for MPI_Group_range_incl ================== */
int E_Group_range_incl(MPI_Group group, int n, int ranges[][3],
MPI_Group *newgroup, int i, vector *v) {
void *f_dl = NULL;
counters[167]++;
QMPI_TABLE_QUERY(167, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 167, v, group, n, ranges, newgroup);
return ret;
}
/* ================== C Wrappers for MPI_Group_rank ================== */
int E_Group_rank(MPI_Group group, int *rank, int i, vector *v) {
void *f_dl = NULL;
counters[168]++;
QMPI_TABLE_QUERY(168, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 168, v, group, rank);
return ret;
}
/* ================== C Wrappers for MPI_Group_size ================== */
int E_Group_size(MPI_Group group, int *size, int i, vector *v) {
void *f_dl = NULL;
counters[169]++;
QMPI_TABLE_QUERY(169, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 169, v, group, size);
return ret;
}
/* ================== C Wrappers for MPI_Group_translate_ranks
* ================== */
int E_Group_translate_ranks(MPI_Group group1, int n, const int ranks1[],
MPI_Group group2, int ranks2[], int i, vector *v) {
void *f_dl = NULL;
counters[170]++;
QMPI_TABLE_QUERY(170, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 170, v, group1, n, ranks1, group2, ranks2);
return ret;
}
/* ================== C Wrappers for MPI_Group_union ================== */
int E_Group_union(MPI_Group group1, MPI_Group group2, MPI_Group *newgroup,
int i, vector *v) {
void *f_dl = NULL;
counters[171]++;
QMPI_TABLE_QUERY(171, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 171, v, group1, group2, newgroup);
return ret;
}
/* ================== C Wrappers for MPI_Iallgather ================== */
int E_Iallgather(const void *sendbuf, int sendcount, MPI_Datatype sendtype,
void *recvbuf, int recvcount, MPI_Datatype recvtype,
MPI_Comm comm, MPI_Request *request, int i, vector *v) {
void *f_dl = NULL;
counters[172]++;
QMPI_TABLE_QUERY(172, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 172, v, sendbuf, sendcount, sendtype, recvbuf,
recvcount, recvtype, comm, request);
return ret;
}
/* ================== C Wrappers for MPI_Iallgatherv ================== */
int E_Iallgatherv(const void *sendbuf, int sendcount, MPI_Datatype sendtype,
void *recvbuf, const int recvcounts[], const int displs[],
MPI_Datatype recvtype, MPI_Comm comm, MPI_Request *request,
int i, vector *v) {
void *f_dl = NULL;
counters[173]++;
QMPI_TABLE_QUERY(173, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 173, v, sendbuf, sendcount, sendtype, recvbuf,
recvcounts, displs, recvtype, comm, request);
return ret;
}
/* ================== C Wrappers for MPI_Iallreduce ================== */
int E_Iallreduce(const void *sendbuf, void *recvbuf, int count,
MPI_Datatype datatype, MPI_Op op, MPI_Comm comm,
MPI_Request *request, int i, vector *v) {
void *f_dl = NULL;
counters[174]++;
QMPI_TABLE_QUERY(174, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 174, v, sendbuf, recvbuf, count, datatype, op,
comm, request);
return ret;
}
/* ================== C Wrappers for MPI_Ialltoall ================== */
int E_Ialltoall(const void *sendbuf, int sendcount, MPI_Datatype sendtype,
void *recvbuf, int recvcount, MPI_Datatype recvtype,
MPI_Comm comm, MPI_Request *request, int i, vector *v) {
void *f_dl = NULL;
counters[175]++;
QMPI_TABLE_QUERY(175, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 175, v, sendbuf, sendcount, sendtype, recvbuf,
recvcount, recvtype, comm, request);
return ret;
}
/* ================== C Wrappers for MPI_Ialltoallv ================== */
int E_Ialltoallv(const void *sendbuf, const int sendcounts[],
const int sdispls[], MPI_Datatype sendtype, void *recvbuf,
const int recvcounts[], const int rdispls[],
MPI_Datatype recvtype, MPI_Comm comm, MPI_Request *request,
int i, vector *v) {
void *f_dl = NULL;
counters[176]++;
QMPI_TABLE_QUERY(176, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 176, v, sendbuf, sendcounts, sdispls, sendtype,
recvbuf, recvcounts, rdispls, recvtype, comm, request);
return ret;
}
/* ================== C Wrappers for MPI_Ialltoallw ================== */
int E_Ialltoallw(const void *sendbuf, const int sendcounts[],
const int sdispls[], const MPI_Datatype sendtypes[],
void *recvbuf, const int recvcounts[], const int rdispls[],
const MPI_Datatype recvtypes[], MPI_Comm comm,
MPI_Request *request, int i, vector *v) {
void *f_dl = NULL;
counters[177]++;
QMPI_TABLE_QUERY(177, &f_dl, (*VECTOR_GET(v, i)).table);
int ret =
EXEC_FUNC(f_dl, i, 177, v, sendbuf, sendcounts, sdispls, sendtypes,
recvbuf, recvcounts, rdispls, recvtypes, comm, request);
return ret;
}
/* ================== C Wrappers for MPI_Ibarrier ================== */
int E_Ibarrier(MPI_Comm comm, MPI_Request *request, int i, vector *v) {
void *f_dl = NULL;
counters[178]++;
QMPI_TABLE_QUERY(178, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 178, v, comm, request);
return ret;
}
/* ================== C Wrappers for MPI_Ibcast ================== */
int E_Ibcast(void *buffer, int count, MPI_Datatype datatype, int root,
MPI_Comm comm, MPI_Request *request, int i, vector *v) {
void *f_dl = NULL;
counters[179]++;
QMPI_TABLE_QUERY(179, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 179, v, buffer, count, datatype, root, comm,
request);
return ret;
}
/* ================== C Wrappers for MPI_Ibsend ================== */
int E_Ibsend(const void *buf, int count, MPI_Datatype datatype, int dest,
int tag, MPI_Comm comm, MPI_Request *request, int i, vector *v) {
void *f_dl = NULL;
counters[180]++;
QMPI_TABLE_QUERY(180, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 180, v, buf, count, datatype, dest, tag, comm,
request);
return ret;
}
/* ================== C Wrappers for MPI_Iexscan ================== */
int E_Iexscan(const void *sendbuf, void *recvbuf, int count,
MPI_Datatype datatype, MPI_Op op, MPI_Comm comm,
MPI_Request *request, int i, vector *v) {
void *f_dl = NULL;
counters[181]++;
QMPI_TABLE_QUERY(181, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 181, v, sendbuf, recvbuf, count, datatype, op,
comm, request);
return ret;
}
/* ================== C Wrappers for MPI_Igather ================== */
int E_Igather(const void *sendbuf, int sendcount, MPI_Datatype sendtype,
void *recvbuf, int recvcount, MPI_Datatype recvtype, int root,
MPI_Comm comm, MPI_Request *request, int i, vector *v) {
void *f_dl = NULL;
counters[182]++;
QMPI_TABLE_QUERY(182, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 182, v, sendbuf, sendcount, sendtype, recvbuf,
recvcount, recvtype, root, comm, request);
return ret;
}
/* ================== C Wrappers for MPI_Igatherv ================== */
int E_Igatherv(const void *sendbuf, int sendcount, MPI_Datatype sendtype,
void *recvbuf, const int recvcounts[], const int displs[],
MPI_Datatype recvtype, int root, MPI_Comm comm,
MPI_Request *request, int i, vector *v) {
void *f_dl = NULL;
counters[183]++;
QMPI_TABLE_QUERY(183, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 183, v, sendbuf, sendcount, sendtype, recvbuf,
recvcounts, displs, recvtype, root, comm, request);
return ret;
}
/* ================== C Wrappers for MPI_Improbe ================== */
int E_Improbe(int source, int tag, MPI_Comm comm, int *flag,
MPI_Message *message, MPI_Status *status, int i, vector *v) {
void *f_dl = NULL;
counters[184]++;
QMPI_TABLE_QUERY(184, &f_dl, (*VECTOR_GET(v, i)).table);
int ret =
EXEC_FUNC(f_dl, i, 184, v, source, tag, comm, flag, message, status);
return ret;
}
/* ================== C Wrappers for MPI_Imrecv ================== */
int E_Imrecv(void *buf, int count, MPI_Datatype type, MPI_Message *message,
MPI_Request *request, int i, vector *v) {
void *f_dl = NULL;
counters[185]++;
QMPI_TABLE_QUERY(185, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 185, v, buf, count, type, message, request);
return ret;
}
/* ================== C Wrappers for MPI_Ineighbor_allgather ==================
*/
int E_Ineighbor_allgather(const void *sendbuf, int sendcount,
MPI_Datatype sendtype, void *recvbuf, int recvcount,
MPI_Datatype recvtype, MPI_Comm comm,
MPI_Request *request, int i, vector *v) {
void *f_dl = NULL;
counters[186]++;
QMPI_TABLE_QUERY(186, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 186, v, sendbuf, sendcount, sendtype, recvbuf,
recvcount, recvtype, comm, request);
return ret;
}
/* ================== C Wrappers for MPI_Ineighbor_allgatherv ==================
*/
int E_Ineighbor_allgatherv(const void *sendbuf, int sendcount,
MPI_Datatype sendtype, void *recvbuf,
const int recvcounts[], const int displs[],
MPI_Datatype recvtype, MPI_Comm comm,
MPI_Request *request, int i, vector *v) {
void *f_dl = NULL;
counters[187]++;
QMPI_TABLE_QUERY(187, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 187, v, sendbuf, sendcount, sendtype, recvbuf,
recvcounts, displs, recvtype, comm, request);
return ret;
}
/* ================== C Wrappers for MPI_Ineighbor_alltoall ==================
*/
int E_Ineighbor_alltoall(const void *sendbuf, int sendcount,
MPI_Datatype sendtype, void *recvbuf, int recvcount,
MPI_Datatype recvtype, MPI_Comm comm,
MPI_Request *request, int i, vector *v) {
void *f_dl = NULL;
counters[188]++;
QMPI_TABLE_QUERY(188, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 188, v, sendbuf, sendcount, sendtype, recvbuf,
recvcount, recvtype, comm, request);
return ret;
}
/* ================== C Wrappers for MPI_Ineighbor_alltoallv ==================
*/
int E_Ineighbor_alltoallv(const void *sendbuf, const int sendcounts[],
const int sdispls[], MPI_Datatype sendtype,
void *recvbuf, const int recvcounts[],
const int rdispls[], MPI_Datatype recvtype,
MPI_Comm comm, MPI_Request *request, int i,
vector *v) {
void *f_dl = NULL;
counters[189]++;
QMPI_TABLE_QUERY(189, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 189, v, sendbuf, sendcounts, sdispls, sendtype,
recvbuf, recvcounts, rdispls, recvtype, comm, request);
return ret;
}
/* ================== C Wrappers for MPI_Ineighbor_alltoallw ==================
*/
int E_Ineighbor_alltoallw(const void *sendbuf, const int sendcounts[],
const MPI_Aint sdispls[],
const MPI_Datatype sendtypes[], void *recvbuf,
const int recvcounts[], const MPI_Aint rdispls[],
const MPI_Datatype recvtypes[], MPI_Comm comm,
MPI_Request *request, int i, vector *v) {
void *f_dl = NULL;
counters[190]++;
QMPI_TABLE_QUERY(190, &f_dl, (*VECTOR_GET(v, i)).table);
int ret =
EXEC_FUNC(f_dl, i, 190, v, sendbuf, sendcounts, sdispls, sendtypes,
recvbuf, recvcounts, rdispls, recvtypes, comm, request);
return ret;
}
/* ================== C Wrappers for MPI_Info_create ================== */
int E_Info_create(MPI_Info *info, int i, vector *v) {
void *f_dl = NULL;
counters[191]++;
QMPI_TABLE_QUERY(191, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 191, v, info);
return ret;
}
/* ================== C Wrappers for MPI_Info_delete ================== */
int E_Info_delete(MPI_Info info, const char *key, int i, vector *v) {
void *f_dl = NULL;
counters[192]++;
QMPI_TABLE_QUERY(192, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 192, v, info, key);
return ret;
}
/* ================== C Wrappers for MPI_Info_dup ================== */
int E_Info_dup(MPI_Info info, MPI_Info *newinfo, int i, vector *v) {
void *f_dl = NULL;
counters[193]++;
QMPI_TABLE_QUERY(193, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 193, v, info, newinfo);
return ret;
}
/* ================== C Wrappers for MPI_Info_free ================== */
int E_Info_free(MPI_Info *info, int i, vector *v) {
void *f_dl = NULL;
counters[194]++;
QMPI_TABLE_QUERY(194, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 194, v, info);
return ret;
}
/* ================== C Wrappers for MPI_Info_get ================== */
int E_Info_get(MPI_Info info, const char *key, int valuelen, char *value,
int *flag, int i, vector *v) {
void *f_dl = NULL;
counters[195]++;
QMPI_TABLE_QUERY(195, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 195, v, info, key, valuelen, value, flag);
return ret;
}
/* ================== C Wrappers for MPI_Info_get_nkeys ================== */
int E_Info_get_nkeys(MPI_Info info, int *nkeys, int i, vector *v) {
void *f_dl = NULL;
counters[196]++;
QMPI_TABLE_QUERY(196, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 196, v, info, nkeys);
return ret;
}
/* ================== C Wrappers for MPI_Info_get_nthkey ================== */
int E_Info_get_nthkey(MPI_Info info, int n, char *key, int i, vector *v) {
void *f_dl = NULL;
counters[197]++;
QMPI_TABLE_QUERY(197, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 197, v, info, n, key);
return ret;
}
/* ================== C Wrappers for MPI_Info_get_valuelen ================== */
int E_Info_get_valuelen(MPI_Info info, const char *key, int *valuelen,
int *flag, int i, vector *v) {
void *f_dl = NULL;
counters[198]++;
QMPI_TABLE_QUERY(198, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 198, v, info, key, valuelen, flag);
return ret;
}
/* ================== C Wrappers for MPI_Info_set ================== */
int E_Info_set(MPI_Info info, const char *key, const char *value, int i,
vector *v) {
void *f_dl = NULL;
counters[199]++;
QMPI_TABLE_QUERY(199, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 199, v, info, key, value);
return ret;
}
/* ================== C Wrappers for MPI_Init_thread ================== */
int E_Init_thread(int *argc, char ***argv, int required, int *provided, int i,
vector *v) {
void *f_dl = NULL;
counters[201]++;
QMPI_TABLE_QUERY(201, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 201, v, argc, argv, required, provided);
return ret;
}
/* ================== C Wrappers for MPI_Initialized ================== */
int E_Initialized(int *flag, int i, vector *v) {
void *f_dl = NULL;
counters[202]++;
QMPI_TABLE_QUERY(202, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 202, v, flag);
return ret;
}
/* ================== C Wrappers for MPI_Intercomm_create ================== */
int E_Intercomm_create(MPI_Comm local_comm, int local_leader,
MPI_Comm bridge_comm, int remote_leader, int tag,
MPI_Comm *newintercomm, int i, vector *v) {
void *f_dl = NULL;
counters[203]++;
QMPI_TABLE_QUERY(203, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 203, v, local_comm, local_leader, bridge_comm,
remote_leader, tag, newintercomm);
return ret;
}
/* ================== C Wrappers for MPI_Intercomm_merge ================== */
int E_Intercomm_merge(MPI_Comm intercomm, int high, MPI_Comm *newintercomm,
int i, vector *v) {
void *f_dl = NULL;
counters[204]++;
QMPI_TABLE_QUERY(204, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 204, v, intercomm, high, newintercomm);
return ret;
}
/* ================== C Wrappers for MPI_Iprobe ================== */
int E_Iprobe(int source, int tag, MPI_Comm comm, int *flag, MPI_Status *status,
int i, vector *v) {
void *f_dl = NULL;
counters[205]++;
QMPI_TABLE_QUERY(205, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 205, v, source, tag, comm, flag, status);
return ret;
}
/* ================== C Wrappers for MPI_Irecv ================== */
int E_Irecv(void *buf, int count, MPI_Datatype datatype, int source, int tag,
MPI_Comm comm, MPI_Request *request, int i, vector *v) {
void *f_dl = NULL;
counters[206]++;
QMPI_TABLE_QUERY(206, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 206, v, buf, count, datatype, source, tag,
comm, request);
return ret;
}
/* ================== C Wrappers for MPI_Ireduce ================== */
int E_Ireduce(const void *sendbuf, void *recvbuf, int count,
MPI_Datatype datatype, MPI_Op op, int root, MPI_Comm comm,
MPI_Request *request, int i, vector *v) {
void *f_dl = NULL;
counters[207]++;
QMPI_TABLE_QUERY(207, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 207, v, sendbuf, recvbuf, count, datatype, op,
root, comm, request);
return ret;
}
/* ================== C Wrappers for MPI_Ireduce_scatter ================== */
int E_Ireduce_scatter(const void *sendbuf, void *recvbuf,
const int recvcounts[], MPI_Datatype datatype, MPI_Op op,
MPI_Comm comm, MPI_Request *request, int i, vector *v) {
void *f_dl = NULL;
counters[208]++;
QMPI_TABLE_QUERY(208, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 208, v, sendbuf, recvbuf, recvcounts, datatype,
op, comm, request);
return ret;
}
/* ================== C Wrappers for MPI_Ireduce_scatter_block
* ================== */
int E_Ireduce_scatter_block(const void *sendbuf, void *recvbuf, int recvcount,
MPI_Datatype datatype, MPI_Op op, MPI_Comm comm,
MPI_Request *request, int i, vector *v) {
void *f_dl = NULL;
counters[209]++;
QMPI_TABLE_QUERY(209, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 209, v, sendbuf, recvbuf, recvcount, datatype,
op, comm, request);
return ret;
}
/* ================== C Wrappers for MPI_Irsend ================== */
int E_Irsend(const void *buf, int count, MPI_Datatype datatype, int dest,
int tag, MPI_Comm comm, MPI_Request *request, int i, vector *v) {
void *f_dl = NULL;
counters[210]++;
QMPI_TABLE_QUERY(210, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 210, v, buf, count, datatype, dest, tag, comm,
request);
return ret;
}
/* ================== C Wrappers for MPI_Is_thread_main ================== */
int E_Is_thread_main(int *flag, int i, vector *v) {
void *f_dl = NULL;
counters[211]++;
QMPI_TABLE_QUERY(211, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 211, v, flag);
return ret;
}
/* ================== C Wrappers for MPI_Iscan ================== */
int E_Iscan(const void *sendbuf, void *recvbuf, int count,
MPI_Datatype datatype, MPI_Op op, MPI_Comm comm,
MPI_Request *request, int i, vector *v) {
void *f_dl = NULL;
counters[212]++;
QMPI_TABLE_QUERY(212, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 212, v, sendbuf, recvbuf, count, datatype, op,
comm, request);
return ret;
}
/* ================== C Wrappers for MPI_Iscatter ================== */
int E_Iscatter(const void *sendbuf, int sendcount, MPI_Datatype sendtype,
void *recvbuf, int recvcount, MPI_Datatype recvtype, int root,
MPI_Comm comm, MPI_Request *request, int i, vector *v) {
void *f_dl = NULL;
counters[213]++;
QMPI_TABLE_QUERY(213, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 213, v, sendbuf, sendcount, sendtype, recvbuf,
recvcount, recvtype, root, comm, request);
return ret;
}
/* ================== C Wrappers for MPI_Iscatterv ================== */
int E_Iscatterv(const void *sendbuf, const int sendcounts[], const int displs[],
MPI_Datatype sendtype, void *recvbuf, int recvcount,
MPI_Datatype recvtype, int root, MPI_Comm comm,
MPI_Request *request, int i, vector *v) {
void *f_dl = NULL;
counters[214]++;
QMPI_TABLE_QUERY(214, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 214, v, sendbuf, sendcounts, displs, sendtype,
recvbuf, recvcount, recvtype, root, comm, request);
return ret;
}
/* ================== C Wrappers for MPI_Isend ================== */
int E_Isend(const void *buf, int count, MPI_Datatype datatype, int dest,
int tag, MPI_Comm comm, MPI_Request *request, int i, vector *v) {
void *f_dl = NULL;
counters[215]++;
QMPI_TABLE_QUERY(215, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 215, v, buf, count, datatype, dest, tag, comm,
request);
return ret;
}
/* ================== C Wrappers for MPI_Issend ================== */
int E_Issend(const void *buf, int count, MPI_Datatype datatype, int dest,
int tag, MPI_Comm comm, MPI_Request *request, int i, vector *v) {
void *f_dl = NULL;
counters[216]++;
QMPI_TABLE_QUERY(216, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 216, v, buf, count, datatype, dest, tag, comm,
request);
return ret;
}
/* ================== C Wrappers for MPI_Keyval_create ================== */
int E_Keyval_create(MPI_Copy_function *copy_fn, MPI_Delete_function *delete_fn,
int *keyval, void *extra_state, int i, vector *v) {
void *f_dl = NULL;
counters[217]++;
QMPI_TABLE_QUERY(217, &f_dl, (*VECTOR_GET(v, i)).table);
int ret =
EXEC_FUNC(f_dl, i, 217, v, copy_fn, delete_fn, keyval, extra_state);
return ret;
}
/* ================== C Wrappers for MPI_Keyval_free ================== */
int E_Keyval_free(int *keyval, int i, vector *v) {
void *f_dl = NULL;
counters[218]++;
QMPI_TABLE_QUERY(218, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 218, v, keyval);
return ret;
}
/* ================== C Wrappers for MPI_Lookup_name ================== */
int E_Lookup_name(const char *service_name, MPI_Info info, char *port_name,
int i, vector *v) {
void *f_dl = NULL;
counters[219]++;
QMPI_TABLE_QUERY(219, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 219, v, service_name, info, port_name);
return ret;
}
/* ================== C Wrappers for MPI_Mprobe ================== */
int E_Mprobe(int source, int tag, MPI_Comm comm, MPI_Message *message,
MPI_Status *status, int i, vector *v) {
void *f_dl = NULL;
counters[220]++;
QMPI_TABLE_QUERY(220, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 220, v, source, tag, comm, message, status);
return ret;
}
/* ================== C Wrappers for MPI_Mrecv ================== */
int E_Mrecv(void *buf, int count, MPI_Datatype type, MPI_Message *message,
MPI_Status *status, int i, vector *v) {
void *f_dl = NULL;
counters[221]++;
QMPI_TABLE_QUERY(221, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 221, v, buf, count, type, message, status);
return ret;
}
/* ================== C Wrappers for MPI_Neighbor_allgather ==================
*/
int E_Neighbor_allgather(const void *sendbuf, int sendcount,
MPI_Datatype sendtype, void *recvbuf, int recvcount,
MPI_Datatype recvtype, MPI_Comm comm, int i,
vector *v) {
void *f_dl = NULL;
counters[222]++;
QMPI_TABLE_QUERY(222, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 222, v, sendbuf, sendcount, sendtype, recvbuf,
recvcount, recvtype, comm);
return ret;
}
/* ================== C Wrappers for MPI_Neighbor_allgatherv ==================
*/
int E_Neighbor_allgatherv(const void *sendbuf, int sendcount,
MPI_Datatype sendtype, void *recvbuf,
const int recvcounts[], const int displs[],
MPI_Datatype recvtype, MPI_Comm comm, int i,
vector *v) {
void *f_dl = NULL;
counters[223]++;
QMPI_TABLE_QUERY(223, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 223, v, sendbuf, sendcount, sendtype, recvbuf,
recvcounts, displs, recvtype, comm);
return ret;
}
/* ================== C Wrappers for MPI_Neighbor_alltoall ================== */
int E_Neighbor_alltoall(const void *sendbuf, int sendcount,
MPI_Datatype sendtype, void *recvbuf, int recvcount,
MPI_Datatype recvtype, MPI_Comm comm, int i,
vector *v) {
void *f_dl = NULL;
counters[224]++;
QMPI_TABLE_QUERY(224, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 224, v, sendbuf, sendcount, sendtype, recvbuf,
recvcount, recvtype, comm);
return ret;
}
/* ================== C Wrappers for MPI_Neighbor_alltoallv ==================
*/
int E_Neighbor_alltoallv(const void *sendbuf, const int sendcounts[],
const int sdispls[], MPI_Datatype sendtype,
void *recvbuf, const int recvcounts[],
const int rdispls[], MPI_Datatype recvtype,
MPI_Comm comm, int i, vector *v) {
void *f_dl = NULL;
counters[225]++;
QMPI_TABLE_QUERY(225, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 225, v, sendbuf, sendcounts, sdispls, sendtype,
recvbuf, recvcounts, rdispls, recvtype, comm);
return ret;
}
/* ================== C Wrappers for MPI_Neighbor_alltoallw ==================
*/
int E_Neighbor_alltoallw(const void *sendbuf, const int sendcounts[],
const MPI_Aint sdispls[],
const MPI_Datatype sendtypes[], void *recvbuf,
const int recvcounts[], const MPI_Aint rdispls[],
const MPI_Datatype recvtypes[], MPI_Comm comm, int i,
vector *v) {
void *f_dl = NULL;
counters[226]++;
QMPI_TABLE_QUERY(226, &f_dl, (*VECTOR_GET(v, i)).table);
int ret =
EXEC_FUNC(f_dl, i, 226, v, sendbuf, sendcounts, sdispls, sendtypes,
recvbuf, recvcounts, rdispls, recvtypes, comm);
return ret;
}
/* ================== C Wrappers for MPI_Op_commutative ================== */
int E_Op_commutative(MPI_Op op, int *commute, int i, vector *v) {
void *f_dl = NULL;
counters[227]++;
QMPI_TABLE_QUERY(227, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 227, v, op, commute);
return ret;
}
/* ================== C Wrappers for MPI_Op_create ================== */
int E_Op_create(MPI_User_function *function, int commute, MPI_Op *op, int i,
vector *v) {
void *f_dl = NULL;
counters[228]++;
QMPI_TABLE_QUERY(228, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 228, v, function, commute, op);
return ret;
}
/* ================== C Wrappers for MPI_Op_free ================== */
int E_Op_free(MPI_Op *op, int i, vector *v) {
void *f_dl = NULL;
counters[229]++;
QMPI_TABLE_QUERY(229, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 229, v, op);
return ret;
}
/* ================== C Wrappers for MPI_Open_port ================== */
int E_Open_port(MPI_Info info, char *port_name, int i, vector *v) {
void *f_dl = NULL;
counters[230]++;
QMPI_TABLE_QUERY(230, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 230, v, info, port_name);
return ret;
}
/* ================== C Wrappers for MPI_Pack ================== */
int E_Pack(const void *inbuf, int incount, MPI_Datatype datatype, void *outbuf,
int outsize, int *position, MPI_Comm comm, int i, vector *v) {
void *f_dl = NULL;
counters[231]++;
QMPI_TABLE_QUERY(231, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 231, v, inbuf, incount, datatype, outbuf,
outsize, position, comm);
return ret;
}
/* ================== C Wrappers for MPI_Pack_external ================== */
int E_Pack_external(const char datarep[], const void *inbuf, int incount,
MPI_Datatype datatype, void *outbuf, MPI_Aint outsize,
MPI_Aint *position, int i, vector *v) {
void *f_dl = NULL;
counters[232]++;
QMPI_TABLE_QUERY(232, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 232, v, datarep, inbuf, incount, datatype,
outbuf, outsize, position);
return ret;
}
/* ================== C Wrappers for MPI_Pack_external_size ==================
*/
int E_Pack_external_size(const char datarep[], int incount,
MPI_Datatype datatype, MPI_Aint *size, int i,
vector *v) {
void *f_dl = NULL;
counters[233]++;
QMPI_TABLE_QUERY(233, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 233, v, datarep, incount, datatype, size);
return ret;
}
/* ================== C Wrappers for MPI_Pack_size ================== */
int E_Pack_size(int incount, MPI_Datatype datatype, MPI_Comm comm, int *size,
int i, vector *v) {
void *f_dl = NULL;
counters[234]++;
QMPI_TABLE_QUERY(234, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 234, v, incount, datatype, comm, size);
return ret;
}
/* ================== C Wrappers for MPI_Pcontrol ================== */
int E_Pcontrol(const int level, int i, vector *v) {
void *f_dl = NULL;
counters[235]++;
QMPI_TABLE_QUERY(235, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 235, v, level);
return ret;
}
/* ================== C Wrappers for MPI_Probe ================== */
int E_Probe(int source, int tag, MPI_Comm comm, MPI_Status *status, int i,
vector *v) {
void *f_dl = NULL;
counters[236]++;
QMPI_TABLE_QUERY(236, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 236, v, source, tag, comm, status);
return ret;
}
/* ================== C Wrappers for MPI_Publish_name ================== */
int E_Publish_name(const char *service_name, MPI_Info info,
const char *port_name, int i, vector *v) {
void *f_dl = NULL;
counters[237]++;
QMPI_TABLE_QUERY(237, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 237, v, service_name, info, port_name);
return ret;
}
/* ================== C Wrappers for MPI_Put ================== */
int E_Put(const void *origin_addr, int origin_count,
MPI_Datatype origin_datatype, int target_rank, MPI_Aint target_disp,
int target_count, MPI_Datatype target_datatype, MPI_Win win, int i,
vector *v) {
void *f_dl = NULL;
counters[238]++;
QMPI_TABLE_QUERY(238, &f_dl, (*VECTOR_GET(v, i)).table);
int ret =
EXEC_FUNC(f_dl, i, 238, v, origin_addr, origin_count, origin_datatype,
target_rank, target_disp, target_count, target_datatype, win);
return ret;
}
/* ================== C Wrappers for MPI_Query_thread ================== */
int E_Query_thread(int *provided, int i, vector *v) {
void *f_dl = NULL;
counters[239]++;
QMPI_TABLE_QUERY(239, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 239, v, provided);
return ret;
}
/* ================== C Wrappers for MPI_Raccumulate ================== */
int E_Raccumulate(const void *origin_addr, int origin_count,
MPI_Datatype origin_datatype, int target_rank,
MPI_Aint target_disp, int target_count,
MPI_Datatype target_datatype, MPI_Op op, MPI_Win win,
MPI_Request *request, int i, vector *v) {
void *f_dl = NULL;
counters[240]++;
QMPI_TABLE_QUERY(240, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 240, v, origin_addr, origin_count,
origin_datatype, target_rank, target_disp, target_count,
target_datatype, op, win, request);
return ret;
}
/* ================== C Wrappers for MPI_Recv ================== */
int E_Recv(void *buf, int count, MPI_Datatype datatype, int source, int tag,
MPI_Comm comm, MPI_Status *status, int i, vector *v) {
void *f_dl = NULL;
counters[241]++;
QMPI_TABLE_QUERY(241, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 241, v, buf, count, datatype, source, tag,
comm, status);
return ret;
}
/* ================== C Wrappers for MPI_Recv_init ================== */
int E_Recv_init(void *buf, int count, MPI_Datatype datatype, int source,
int tag, MPI_Comm comm, MPI_Request *request, int i,
vector *v) {
void *f_dl = NULL;
counters[242]++;
QMPI_TABLE_QUERY(242, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 242, v, buf, count, datatype, source, tag,
comm, request);
return ret;
}
/* ================== C Wrappers for MPI_Reduce ================== */
int E_Reduce(const void *sendbuf, void *recvbuf, int count,
MPI_Datatype datatype, MPI_Op op, int root, MPI_Comm comm, int i,
vector *v) {
void *f_dl = NULL;
counters[243]++;
QMPI_TABLE_QUERY(243, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 243, v, sendbuf, recvbuf, count, datatype, op,
root, comm);
return ret;
}
/* ================== C Wrappers for MPI_Reduce_local ================== */
int E_Reduce_local(const void *inbuf, void *inoutbuf, int count,
MPI_Datatype datatype, MPI_Op op, int i, vector *v) {
void *f_dl = NULL;
counters[244]++;
QMPI_TABLE_QUERY(244, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 244, v, inbuf, inoutbuf, count, datatype, op);
return ret;
}
/* ================== C Wrappers for MPI_Reduce_scatter ================== */
int E_Reduce_scatter(const void *sendbuf, void *recvbuf, const int recvcounts[],
MPI_Datatype datatype, MPI_Op op, MPI_Comm comm, int i,
vector *v) {
void *f_dl = NULL;
counters[245]++;
QMPI_TABLE_QUERY(245, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 245, v, sendbuf, recvbuf, recvcounts, datatype,
op, comm);
return ret;
}
/* ================== C Wrappers for MPI_Reduce_scatter_block ==================
*/
int E_Reduce_scatter_block(const void *sendbuf, void *recvbuf, int recvcount,
MPI_Datatype datatype, MPI_Op op, MPI_Comm comm,
int i, vector *v) {
void *f_dl = NULL;
counters[246]++;
QMPI_TABLE_QUERY(246, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 246, v, sendbuf, recvbuf, recvcount, datatype,
op, comm);
return ret;
}
/* ================== C Wrappers for MPI_Register_datarep ================== */
int E_Register_datarep(const char *datarep,
MPI_Datarep_conversion_function *read_conversion_fn,
MPI_Datarep_conversion_function *write_conversion_fn,
MPI_Datarep_extent_function *dtype_file_extent_fn,
void *extra_state, int i, vector *v) {
void *f_dl = NULL;
counters[247]++;
QMPI_TABLE_QUERY(247, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 247, v, datarep, read_conversion_fn,
write_conversion_fn, dtype_file_extent_fn, extra_state);
return ret;
}
/* ================== C Wrappers for MPI_Request_free ================== */
int E_Request_free(MPI_Request *request, int i, vector *v) {
void *f_dl = NULL;
counters[248]++;
QMPI_TABLE_QUERY(248, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 248, v, request);
return ret;
}
/* ================== C Wrappers for MPI_Request_get_status ==================
*/
int E_Request_get_status(MPI_Request request, int *flag, MPI_Status *status,
int i, vector *v) {
void *f_dl = NULL;
counters[249]++;
QMPI_TABLE_QUERY(249, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 249, v, request, flag, status);
return ret;
}
/* ================== C Wrappers for MPI_Rget ================== */
int E_Rget(void *origin_addr, int origin_count, MPI_Datatype origin_datatype,
int target_rank, MPI_Aint target_disp, int target_count,
MPI_Datatype target_datatype, MPI_Win win, MPI_Request *request,
int i, vector *v) {
void *f_dl = NULL;
counters[250]++;
QMPI_TABLE_QUERY(250, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 250, v, origin_addr, origin_count,
origin_datatype, target_rank, target_disp, target_count,
target_datatype, win, request);
return ret;
}
/* ================== C Wrappers for MPI_Rget_accumulate ================== */
int E_Rget_accumulate(const void *origin_addr, int origin_count,
MPI_Datatype origin_datatype, void *result_addr,
int result_count, MPI_Datatype result_datatype,
int target_rank, MPI_Aint target_disp, int target_count,
MPI_Datatype target_datatype, MPI_Op op, MPI_Win win,
MPI_Request *request, int i, vector *v) {
void *f_dl = NULL;
counters[251]++;
QMPI_TABLE_QUERY(251, &f_dl, (*VECTOR_GET(v, i)).table);
int ret =
EXEC_FUNC(f_dl, i, 251, v, origin_addr, origin_count, origin_datatype,
result_addr, result_count, result_datatype, target_rank,
target_disp, target_count, target_datatype, op, win, request);
return ret;
}
/* ================== C Wrappers for MPI_Rput ================== */
int E_Rput(const void *origin_addr, int origin_count,
MPI_Datatype origin_datatype, int target_rank, MPI_Aint target_disp,
int target_cout, MPI_Datatype target_datatype, MPI_Win win,
MPI_Request *request, int i, vector *v) {
void *f_dl = NULL;
counters[252]++;
QMPI_TABLE_QUERY(252, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 252, v, origin_addr, origin_count,
origin_datatype, target_rank, target_disp, target_cout,
target_datatype, win, request);
return ret;
}
/* ================== C Wrappers for MPI_Rsend ================== */
int E_Rsend(const void *ibuf, int count, MPI_Datatype datatype, int dest,
int tag, MPI_Comm comm, int i, vector *v) {
void *f_dl = NULL;
counters[253]++;
QMPI_TABLE_QUERY(253, &f_dl, (*VECTOR_GET(v, i)).table);
int ret =
EXEC_FUNC(f_dl, i, 253, v, ibuf, count, datatype, dest, tag, comm);
return ret;
}
/* ================== C Wrappers for MPI_Rsend_init ================== */
int E_Rsend_init(const void *buf, int count, MPI_Datatype datatype, int dest,
int tag, MPI_Comm comm, MPI_Request *request, int i,
vector *v) {
void *f_dl = NULL;
counters[254]++;
QMPI_TABLE_QUERY(254, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 254, v, buf, count, datatype, dest, tag, comm,
request);
return ret;
}
/* ================== C Wrappers for MPI_Scan ================== */
int E_Scan(const void *sendbuf, void *recvbuf, int count, MPI_Datatype datatype,
MPI_Op op, MPI_Comm comm, int i, vector *v) {
void *f_dl = NULL;
counters[255]++;
QMPI_TABLE_QUERY(255, &f_dl, (*VECTOR_GET(v, i)).table);
int ret =
EXEC_FUNC(f_dl, i, 255, v, sendbuf, recvbuf, count, datatype, op, comm);
return ret;
}
/* ================== C Wrappers for MPI_Scatter ================== */
int E_Scatter(const void *sendbuf, int sendcount, MPI_Datatype sendtype,
void *recvbuf, int recvcount, MPI_Datatype recvtype, int root,
MPI_Comm comm, int i, vector *v) {
void *f_dl = NULL;
counters[256]++;
QMPI_TABLE_QUERY(256, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 256, v, sendbuf, sendcount, sendtype, recvbuf,
recvcount, recvtype, root, comm);
return ret;
}
/* ================== C Wrappers for MPI_Scatterv ================== */
int E_Scatterv(const void *sendbuf, const int sendcounts[], const int displs[],
MPI_Datatype sendtype, void *recvbuf, int recvcount,
MPI_Datatype recvtype, int root, MPI_Comm comm, int i,
vector *v) {
void *f_dl = NULL;
counters[257]++;
QMPI_TABLE_QUERY(257, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 257, v, sendbuf, sendcounts, displs, sendtype,
recvbuf, recvcount, recvtype, root, comm);
return ret;
}
/* ================== C Wrappers for MPI_Send ================== */
int E_Send(const void *buf, int count, MPI_Datatype datatype, int dest, int tag,
MPI_Comm comm, int i, vector *v) {
void *f_dl = NULL;
counters[258]++;
QMPI_TABLE_QUERY(258, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 258, v, buf, count, datatype, dest, tag, comm);
return ret;
}
/* ================== C Wrappers for MPI_Send_init ================== */
int E_Send_init(const void *buf, int count, MPI_Datatype datatype, int dest,
int tag, MPI_Comm comm, MPI_Request *request, int i,
vector *v) {
void *f_dl = NULL;
counters[259]++;
QMPI_TABLE_QUERY(259, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 259, v, buf, count, datatype, dest, tag, comm,
request);
return ret;
}
/* ================== C Wrappers for MPI_Sendrecv ================== */
int E_Sendrecv(const void *sendbuf, int sendcount, MPI_Datatype sendtype,
int dest, int sendtag, void *recvbuf, int recvcount,
MPI_Datatype recvtype, int source, int recvtag, MPI_Comm comm,
MPI_Status *status, int i, vector *v) {
void *f_dl = NULL;
counters[260]++;
QMPI_TABLE_QUERY(260, &f_dl, (*VECTOR_GET(v, i)).table);
int ret =
EXEC_FUNC(f_dl, i, 260, v, sendbuf, sendcount, sendtype, dest, sendtag,
recvbuf, recvcount, recvtype, source, recvtag, comm, status);
return ret;
}
/* ================== C Wrappers for MPI_Sendrecv_replace ================== */
int E_Sendrecv_replace(void *buf, int count, MPI_Datatype datatype, int dest,
int sendtag, int source, int recvtag, MPI_Comm comm,
MPI_Status *status, int i, vector *v) {
void *f_dl = NULL;
counters[261]++;
QMPI_TABLE_QUERY(261, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 261, v, buf, count, datatype, dest, sendtag,
source, recvtag, comm, status);
return ret;
}
/* ================== C Wrappers for MPI_Ssend ================== */
int E_Ssend(const void *buf, int count, MPI_Datatype datatype, int dest,
int tag, MPI_Comm comm, int i, vector *v) {
void *f_dl = NULL;
counters[262]++;
QMPI_TABLE_QUERY(262, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 262, v, buf, count, datatype, dest, tag, comm);
return ret;
}
/* ================== C Wrappers for MPI_Ssend_init ================== */
int E_Ssend_init(const void *buf, int count, MPI_Datatype datatype, int dest,
int tag, MPI_Comm comm, MPI_Request *request, int i,
vector *v) {
void *f_dl = NULL;
counters[263]++;
QMPI_TABLE_QUERY(263, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 263, v, buf, count, datatype, dest, tag, comm,
request);
return ret;
}
/* ================== C Wrappers for MPI_Start ================== */
int E_Start(MPI_Request *request, int i, vector *v) {
void *f_dl = NULL;
counters[264]++;
QMPI_TABLE_QUERY(264, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 264, v, request);
return ret;
}
/* ================== C Wrappers for MPI_Startall ================== */
int E_Startall(int count, MPI_Request array_of_requests[], int i, vector *v) {
void *f_dl = NULL;
counters[265]++;
QMPI_TABLE_QUERY(265, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 265, v, count, array_of_requests);
return ret;
}
/* ================== C Wrappers for MPI_Status_set_cancelled ==================
*/
int E_Status_set_cancelled(MPI_Status *status, int flag, int i, vector *v) {
void *f_dl = NULL;
counters[266]++;
QMPI_TABLE_QUERY(266, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 266, v, status, flag);
return ret;
}
/* ================== C Wrappers for MPI_Status_set_elements ==================
*/
int E_Status_set_elements(MPI_Status *status, MPI_Datatype datatype, int count,
int i, vector *v) {
void *f_dl = NULL;
counters[267]++;
QMPI_TABLE_QUERY(267, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 267, v, status, datatype, count);
return ret;
}
/* ================== C Wrappers for MPI_Status_set_elements_x
* ================== */
int E_Status_set_elements_x(MPI_Status *status, MPI_Datatype datatype,
MPI_Count count, int i, vector *v) {
void *f_dl = NULL;
counters[268]++;
QMPI_TABLE_QUERY(268, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 268, v, status, datatype, count);
return ret;
}
/* ================== C Wrappers for MPI_Test ================== */
int E_Test(MPI_Request *request, int *flag, MPI_Status *status, int i,
vector *v) {
void *f_dl = NULL;
counters[269]++;
QMPI_TABLE_QUERY(269, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 269, v, request, flag, status);
return ret;
}
/* ================== C Wrappers for MPI_Test_cancelled ================== */
int E_Test_cancelled(const MPI_Status *status, int *flag, int i, vector *v) {
void *f_dl = NULL;
counters[270]++;
QMPI_TABLE_QUERY(270, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 270, v, status, flag);
return ret;
}
/* ================== C Wrappers for MPI_Testall ================== */
int E_Testall(int count, MPI_Request array_of_requests[], int *flag,
MPI_Status array_of_statuses[], int i, vector *v) {
void *f_dl = NULL;
counters[271]++;
QMPI_TABLE_QUERY(271, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 271, v, count, array_of_requests, flag,
array_of_statuses);
return ret;
}
/* ================== C Wrappers for MPI_Testany ================== */
int E_Testany(int count, MPI_Request array_of_requests[], int *index, int *flag,
MPI_Status *status, int i, vector *v) {
void *f_dl = NULL;
counters[272]++;
QMPI_TABLE_QUERY(272, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 272, v, count, array_of_requests, index, flag,
status);
return ret;
}
/* ================== C Wrappers for MPI_Testsome ================== */
int E_Testsome(int incount, MPI_Request array_of_requests[], int *outcount,
int array_of_indices[], MPI_Status array_of_statuses[], int i,
vector *v) {
void *f_dl = NULL;
counters[273]++;
QMPI_TABLE_QUERY(273, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 273, v, incount, array_of_requests, outcount,
array_of_indices, array_of_statuses);
return ret;
}
/* ================== C Wrappers for MPI_Topo_test ================== */
int E_Topo_test(MPI_Comm comm, int *status, int i, vector *v) {
void *f_dl = NULL;
counters[274]++;
QMPI_TABLE_QUERY(274, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 274, v, comm, status);
return ret;
}
/* ================== C Wrappers for MPI_Type_commit ================== */
int E_Type_commit(MPI_Datatype *type, int i, vector *v) {
void *f_dl = NULL;
counters[275]++;
QMPI_TABLE_QUERY(275, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 275, v, type);
return ret;
}
/* ================== C Wrappers for MPI_Type_contiguous ================== */
int E_Type_contiguous(int count, MPI_Datatype oldtype, MPI_Datatype *newtype,
int i, vector *v) {
void *f_dl = NULL;
counters[276]++;
QMPI_TABLE_QUERY(276, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 276, v, count, oldtype, newtype);
return ret;
}
/* ================== C Wrappers for MPI_Type_create_darray ==================
*/
int E_Type_create_darray(int size, int rank, int ndims, const int gsize_array[],
const int distrib_array[], const int darg_array[],
const int psize_array[], int order,
MPI_Datatype oldtype, MPI_Datatype *newtype, int i,
vector *v) {
void *f_dl = NULL;
counters[277]++;
QMPI_TABLE_QUERY(277, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 277, v, size, rank, ndims, gsize_array,
distrib_array, darg_array, psize_array, order, oldtype,
newtype);
return ret;
}
/* ================== C Wrappers for MPI_Type_create_f90_complex
* ================== */
int E_Type_create_f90_complex(int p, int r, MPI_Datatype *newtype, int i,
vector *v) {
void *f_dl = NULL;
counters[278]++;
QMPI_TABLE_QUERY(278, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 278, v, p, r, newtype);
return ret;
}
/* ================== C Wrappers for MPI_Type_create_f90_integer
* ================== */
int E_Type_create_f90_integer(int r, MPI_Datatype *newtype, int i, vector *v) {
void *f_dl = NULL;
counters[279]++;
QMPI_TABLE_QUERY(279, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 279, v, r, newtype);
return ret;
}
/* ================== C Wrappers for MPI_Type_create_f90_real ==================
*/
int E_Type_create_f90_real(int p, int r, MPI_Datatype *newtype, int i,
vector *v) {
void *f_dl = NULL;
counters[280]++;
QMPI_TABLE_QUERY(280, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 280, v, p, r, newtype);
return ret;
}
/* ================== C Wrappers for MPI_Type_create_hindexed ==================
*/
int E_Type_create_hindexed(int count, const int array_of_blocklengths[],
const MPI_Aint array_of_displacements[],
MPI_Datatype oldtype, MPI_Datatype *newtype, int i,
vector *v) {
void *f_dl = NULL;
counters[281]++;
QMPI_TABLE_QUERY(281, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 281, v, count, array_of_blocklengths,
array_of_displacements, oldtype, newtype);
return ret;
}
/* ================== C Wrappers for MPI_Type_create_hindexed_block
* ================== */
int E_Type_create_hindexed_block(int count, int blocklength,
const MPI_Aint array_of_displacements[],
MPI_Datatype oldtype, MPI_Datatype *newtype,
int i, vector *v) {
void *f_dl = NULL;
counters[282]++;
QMPI_TABLE_QUERY(282, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 282, v, count, blocklength,
array_of_displacements, oldtype, newtype);
return ret;
}
/* ================== C Wrappers for MPI_Type_create_hvector ==================
*/
int E_Type_create_hvector(int count, int blocklength, MPI_Aint stride,
MPI_Datatype oldtype, MPI_Datatype *newtype, int i,
vector *v) {
void *f_dl = NULL;
counters[283]++;
QMPI_TABLE_QUERY(283, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 283, v, count, blocklength, stride, oldtype,
newtype);
return ret;
}
/* ================== C Wrappers for MPI_Type_create_indexed_block
* ================== */
int E_Type_create_indexed_block(int count, int blocklength,
const int array_of_displacements[],
MPI_Datatype oldtype, MPI_Datatype *newtype,
int i, vector *v) {
void *f_dl = NULL;
counters[284]++;
QMPI_TABLE_QUERY(284, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 284, v, count, blocklength,
array_of_displacements, oldtype, newtype);
return ret;
}
/* ================== C Wrappers for MPI_Type_create_keyval ==================
*/
int E_Type_create_keyval(MPI_Type_copy_attr_function *type_copy_attr_fn,
MPI_Type_delete_attr_function *type_delete_attr_fn,
int *type_keyval, void *extra_state, int i,
vector *v) {
void *f_dl = NULL;
counters[285]++;
QMPI_TABLE_QUERY(285, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 285, v, type_copy_attr_fn, type_delete_attr_fn,
type_keyval, extra_state);
return ret;
}
/* ================== C Wrappers for MPI_Type_create_resized ==================
*/
int E_Type_create_resized(MPI_Datatype oldtype, MPI_Aint lb, MPI_Aint extent,
MPI_Datatype *newtype, int i, vector *v) {
void *f_dl = NULL;
counters[286]++;
QMPI_TABLE_QUERY(286, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 286, v, oldtype, lb, extent, newtype);
return ret;
}
/* ================== C Wrappers for MPI_Type_create_struct ==================
*/
int E_Type_create_struct(int count, const int array_of_block_lengths[],
const MPI_Aint array_of_displacements[],
const MPI_Datatype array_of_types[],
MPI_Datatype *newtype, int i, vector *v) {
void *f_dl = NULL;
counters[287]++;
QMPI_TABLE_QUERY(287, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 287, v, count, array_of_block_lengths,
array_of_displacements, array_of_types, newtype);
return ret;
}
/* ================== C Wrappers for MPI_Type_create_subarray ==================
*/
int E_Type_create_subarray(int ndims, const int size_array[],
const int subsize_array[], const int start_array[],
int order, MPI_Datatype oldtype,
MPI_Datatype *newtype, int i, vector *v) {
void *f_dl = NULL;
counters[288]++;
QMPI_TABLE_QUERY(288, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 288, v, ndims, size_array, subsize_array,
start_array, order, oldtype, newtype);
return ret;
}
/* ================== C Wrappers for MPI_Type_delete_attr ================== */
int E_Type_delete_attr(MPI_Datatype type, int type_keyval, int i, vector *v) {
void *f_dl = NULL;
counters[289]++;
QMPI_TABLE_QUERY(289, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 289, v, type, type_keyval);
return ret;
}
/* ================== C Wrappers for MPI_Type_dup ================== */
int E_Type_dup(MPI_Datatype type, MPI_Datatype *newtype, int i, vector *v) {
void *f_dl = NULL;
counters[290]++;
QMPI_TABLE_QUERY(290, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 290, v, type, newtype);
return ret;
}
/* ================== C Wrappers for MPI_Type_extent ================== */
int E_Type_extent(MPI_Datatype type, MPI_Aint *extent, int i, vector *v) {
void *f_dl = NULL;
counters[291]++;
QMPI_TABLE_QUERY(291, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 291, v, type, extent);
return ret;
}
/* ================== C Wrappers for MPI_Type_free ================== */
int E_Type_free(MPI_Datatype *type, int i, vector *v) {
void *f_dl = NULL;
counters[292]++;
QMPI_TABLE_QUERY(292, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 292, v, type);
return ret;
}
/* ================== C Wrappers for MPI_Type_free_keyval ================== */
int E_Type_free_keyval(int *type_keyval, int i, vector *v) {
void *f_dl = NULL;
counters[293]++;
QMPI_TABLE_QUERY(293, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 293, v, type_keyval);
return ret;
}
/* ================== C Wrappers for MPI_Type_get_attr ================== */
int E_Type_get_attr(MPI_Datatype type, int type_keyval, void *attribute_val,
int *flag, int i, vector *v) {
void *f_dl = NULL;
counters[294]++;
QMPI_TABLE_QUERY(294, &f_dl, (*VECTOR_GET(v, i)).table);
int ret =
EXEC_FUNC(f_dl, i, 294, v, type, type_keyval, attribute_val, flag);
return ret;
}
/* ================== C Wrappers for MPI_Type_get_contents ================== */
int E_Type_get_contents(MPI_Datatype mtype, int max_integers, int max_addresses,
int max_datatypes, int array_of_integers[],
MPI_Aint array_of_addresses[],
MPI_Datatype array_of_datatypes[], int i, vector *v) {
void *f_dl = NULL;
counters[295]++;
QMPI_TABLE_QUERY(295, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 295, v, mtype, max_integers, max_addresses,
max_datatypes, array_of_integers, array_of_addresses,
array_of_datatypes);
return ret;
}
/* ================== C Wrappers for MPI_Type_get_envelope ================== */
int E_Type_get_envelope(MPI_Datatype type, int *num_integers,
int *num_addresses, int *num_datatypes, int *combiner,
int i, vector *v) {
void *f_dl = NULL;
counters[296]++;
QMPI_TABLE_QUERY(296, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 296, v, type, num_integers, num_addresses,
num_datatypes, combiner);
return ret;
}
/* ================== C Wrappers for MPI_Type_get_extent ================== */
int E_Type_get_extent(MPI_Datatype type, MPI_Aint *lb, MPI_Aint *extent, int i,
vector *v) {
void *f_dl = NULL;
counters[297]++;
QMPI_TABLE_QUERY(297, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 297, v, type, lb, extent);
return ret;
}
/* ================== C Wrappers for MPI_Type_get_extent_x ================== */
int E_Type_get_extent_x(MPI_Datatype type, MPI_Count *lb, MPI_Count *extent,
int i, vector *v) {
void *f_dl = NULL;
counters[298]++;
QMPI_TABLE_QUERY(298, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 298, v, type, lb, extent);
return ret;
}
/* ================== C Wrappers for MPI_Type_get_name ================== */
int E_Type_get_name(MPI_Datatype type, char *type_name, int *resultlen, int i,
vector *v) {
void *f_dl = NULL;
counters[299]++;
QMPI_TABLE_QUERY(299, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 299, v, type, type_name, resultlen);
return ret;
}
/* ================== C Wrappers for MPI_Type_get_true_extent ==================
*/
int E_Type_get_true_extent(MPI_Datatype datatype, MPI_Aint *true_lb,
MPI_Aint *true_extent, int i, vector *v) {
void *f_dl = NULL;
counters[300]++;
QMPI_TABLE_QUERY(300, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 300, v, datatype, true_lb, true_extent);
return ret;
}
/* ================== C Wrappers for MPI_Type_get_true_extent_x
* ================== */
int E_Type_get_true_extent_x(MPI_Datatype datatype, MPI_Count *true_lb,
MPI_Count *true_extent, int i, vector *v) {
void *f_dl = NULL;
counters[301]++;
QMPI_TABLE_QUERY(301, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 301, v, datatype, true_lb, true_extent);
return ret;
}
/* ================== C Wrappers for MPI_Type_hindexed ================== */
int E_Type_hindexed(int count, int array_of_blocklengths[],
MPI_Aint array_of_displacements[], MPI_Datatype oldtype,
MPI_Datatype *newtype, int i, vector *v) {
void *f_dl = NULL;
counters[302]++;
QMPI_TABLE_QUERY(302, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 302, v, count, array_of_blocklengths,
array_of_displacements, oldtype, newtype);
return ret;
}
/* ================== C Wrappers for MPI_Type_hvector ================== */
int E_Type_hvector(int count, int blocklength, MPI_Aint stride,
MPI_Datatype oldtype, MPI_Datatype *newtype, int i,
vector *v) {
void *f_dl = NULL;
counters[303]++;
QMPI_TABLE_QUERY(303, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 303, v, count, blocklength, stride, oldtype,
newtype);
return ret;
}
/* ================== C Wrappers for MPI_Type_indexed ================== */
int E_Type_indexed(int count, const int array_of_blocklengths[],
const int array_of_displacements[], MPI_Datatype oldtype,
MPI_Datatype *newtype, int i, vector *v) {
void *f_dl = NULL;
counters[304]++;
QMPI_TABLE_QUERY(304, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 304, v, count, array_of_blocklengths,
array_of_displacements, oldtype, newtype);
return ret;
}
/* ================== C Wrappers for MPI_Type_lb ================== */
int E_Type_lb(MPI_Datatype type, MPI_Aint *lb, int i, vector *v) {
void *f_dl = NULL;
counters[305]++;
QMPI_TABLE_QUERY(305, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 305, v, type, lb);
return ret;
}
/* ================== C Wrappers for MPI_Type_match_size ================== */
int E_Type_match_size(int typeclass, int size, MPI_Datatype *type, int i,
vector *v) {
void *f_dl = NULL;
counters[306]++;
QMPI_TABLE_QUERY(306, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 306, v, typeclass, size, type);
return ret;
}
/* ================== C Wrappers for MPI_Type_set_attr ================== */
int E_Type_set_attr(MPI_Datatype type, int type_keyval, void *attr_val, int i,
vector *v) {
void *f_dl = NULL;
counters[307]++;
QMPI_TABLE_QUERY(307, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 307, v, type, type_keyval, attr_val);
return ret;
}
/* ================== C Wrappers for MPI_Type_set_name ================== */
int E_Type_set_name(MPI_Datatype type, const char *type_name, int i,
vector *v) {
void *f_dl = NULL;
counters[308]++;
QMPI_TABLE_QUERY(308, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 308, v, type, type_name);
return ret;
}
/* ================== C Wrappers for MPI_Type_size ================== */
int E_Type_size(MPI_Datatype type, int *size, int i, vector *v) {
void *f_dl = NULL;
counters[309]++;
QMPI_TABLE_QUERY(309, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 309, v, type, size);
return ret;
}
/* ================== C Wrappers for MPI_Type_size_x ================== */
int E_Type_size_x(MPI_Datatype type, MPI_Count *size, int i, vector *v) {
void *f_dl = NULL;
counters[310]++;
QMPI_TABLE_QUERY(310, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 310, v, type, size);
return ret;
}
/* ================== C Wrappers for MPI_Type_struct ================== */
int E_Type_struct(int count, int array_of_blocklengths[],
MPI_Aint array_of_displacements[],
MPI_Datatype array_of_types[], MPI_Datatype *newtype, int i,
vector *v) {
void *f_dl = NULL;
counters[311]++;
QMPI_TABLE_QUERY(311, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 311, v, count, array_of_blocklengths,
array_of_displacements, array_of_types, newtype);
return ret;
}
/* ================== C Wrappers for MPI_Type_ub ================== */
int E_Type_ub(MPI_Datatype mtype, MPI_Aint *ub, int i, vector *v) {
void *f_dl = NULL;
counters[312]++;
QMPI_TABLE_QUERY(312, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 312, v, mtype, ub);
return ret;
}
/* ================== C Wrappers for MPI_Type_vector ================== */
int E_Type_vector(int count, int blocklength, int stride, MPI_Datatype oldtype,
MPI_Datatype *newtype, int i, vector *v) {
void *f_dl = NULL;
counters[313]++;
QMPI_TABLE_QUERY(313, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 313, v, count, blocklength, stride, oldtype,
newtype);
return ret;
}
/* ================== C Wrappers for MPI_Unpack ================== */
int E_Unpack(const void *inbuf, int insize, int *position, void *outbuf,
int outcount, MPI_Datatype datatype, MPI_Comm comm, int i,
vector *v) {
void *f_dl = NULL;
counters[314]++;
QMPI_TABLE_QUERY(314, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 314, v, inbuf, insize, position, outbuf,
outcount, datatype, comm);
return ret;
}
/* ================== C Wrappers for MPI_Unpack_external ================== */
int E_Unpack_external(const char datarep[], const void *inbuf, MPI_Aint insize,
MPI_Aint *position, void *outbuf, int outcount,
MPI_Datatype datatype, int i, vector *v) {
void *f_dl = NULL;
counters[315]++;
QMPI_TABLE_QUERY(315, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 315, v, datarep, inbuf, insize, position,
outbuf, outcount, datatype);
return ret;
}
/* ================== C Wrappers for MPI_Unpublish_name ================== */
int E_Unpublish_name(const char *service_name, MPI_Info info,
const char *port_name, int i, vector *v) {
void *f_dl = NULL;
counters[316]++;
QMPI_TABLE_QUERY(316, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 316, v, service_name, info, port_name);
return ret;
}
/* ================== C Wrappers for MPI_Wait ================== */
int E_Wait(MPI_Request *request, MPI_Status *status, int i, vector *v) {
void *f_dl = NULL;
counters[317]++;
QMPI_TABLE_QUERY(317, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 317, v, request, status);
return ret;
}
/* ================== C Wrappers for MPI_Waitall ================== */
int E_Waitall(int count, MPI_Request array_of_requests[],
MPI_Status *array_of_statuses, int i, vector *v) {
void *f_dl = NULL;
counters[318]++;
QMPI_TABLE_QUERY(318, &f_dl, (*VECTOR_GET(v, i)).table);
int ret =
EXEC_FUNC(f_dl, i, 318, v, count, array_of_requests, array_of_statuses);
return ret;
}
/* ================== C Wrappers for MPI_Waitany ================== */
int E_Waitany(int count, MPI_Request array_of_requests[], int *index,
MPI_Status *status, int i, vector *v) {
void *f_dl = NULL;
counters[319]++;
QMPI_TABLE_QUERY(319, &f_dl, (*VECTOR_GET(v, i)).table);
int ret =
EXEC_FUNC(f_dl, i, 319, v, count, array_of_requests, index, status);
return ret;
}
/* ================== C Wrappers for MPI_Waitsome ================== */
int E_Waitsome(int incount, MPI_Request array_of_requests[], int *outcount,
int array_of_indices[], MPI_Status array_of_statuses[], int i,
vector *v) {
void *f_dl = NULL;
counters[320]++;
QMPI_TABLE_QUERY(320, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 320, v, incount, array_of_requests, outcount,
array_of_indices, array_of_statuses);
return ret;
}
/* ================== C Wrappers for MPI_Win_allocate ================== */
int E_Win_allocate(MPI_Aint size, int disp_unit, MPI_Info info, MPI_Comm comm,
void *baseptr, MPI_Win *win, int i, vector *v) {
void *f_dl = NULL;
counters[321]++;
QMPI_TABLE_QUERY(321, &f_dl, (*VECTOR_GET(v, i)).table);
int ret =
EXEC_FUNC(f_dl, i, 321, v, size, disp_unit, info, comm, baseptr, win);
return ret;
}
/* ================== C Wrappers for MPI_Win_allocate_shared ==================
*/
int E_Win_allocate_shared(MPI_Aint size, int disp_unit, MPI_Info info,
MPI_Comm comm, void *baseptr, MPI_Win *win, int i,
vector *v) {
void *f_dl = NULL;
counters[322]++;
QMPI_TABLE_QUERY(322, &f_dl, (*VECTOR_GET(v, i)).table);
int ret =
EXEC_FUNC(f_dl, i, 322, v, size, disp_unit, info, comm, baseptr, win);
return ret;
}
/* ================== C Wrappers for MPI_Win_attach ================== */
int E_Win_attach(MPI_Win win, void *base, MPI_Aint size, int i, vector *v) {
void *f_dl = NULL;
counters[323]++;
QMPI_TABLE_QUERY(323, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 323, v, win, base, size);
return ret;
}
/* ================== C Wrappers for MPI_Win_call_errhandler ==================
*/
int E_Win_call_errhandler(MPI_Win win, int errorcode, int i, vector *v) {
void *f_dl = NULL;
counters[324]++;
QMPI_TABLE_QUERY(324, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 324, v, win, errorcode);
return ret;
}
/* ================== C Wrappers for MPI_Win_complete ================== */
int E_Win_complete(MPI_Win win, int i, vector *v) {
void *f_dl = NULL;
counters[325]++;
QMPI_TABLE_QUERY(325, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 325, v, win);
return ret;
}
/* ================== C Wrappers for MPI_Win_create ================== */
int E_Win_create(void *base, MPI_Aint size, int disp_unit, MPI_Info info,
MPI_Comm comm, MPI_Win *win, int i, vector *v) {
void *f_dl = NULL;
counters[326]++;
QMPI_TABLE_QUERY(326, &f_dl, (*VECTOR_GET(v, i)).table);
int ret =
EXEC_FUNC(f_dl, i, 326, v, base, size, disp_unit, info, comm, win);
return ret;
}
/* ================== C Wrappers for MPI_Win_create_dynamic ==================
*/
int E_Win_create_dynamic(MPI_Info info, MPI_Comm comm, MPI_Win *win, int i,
vector *v) {
void *f_dl = NULL;
counters[327]++;
QMPI_TABLE_QUERY(327, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 327, v, info, comm, win);
return ret;
}
/* ================== C Wrappers for MPI_Win_create_errhandler
* ================== */
int E_Win_create_errhandler(MPI_Win_errhandler_function *function,
MPI_Errhandler *errhandler, int i, vector *v) {
void *f_dl = NULL;
counters[328]++;
QMPI_TABLE_QUERY(328, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 328, v, function, errhandler);
return ret;
}
/* ================== C Wrappers for MPI_Win_create_keyval ================== */
int E_Win_create_keyval(MPI_Win_copy_attr_function *win_copy_attr_fn,
MPI_Win_delete_attr_function *win_delete_attr_fn,
int *win_keyval, void *extra_state, int i, vector *v) {
void *f_dl = NULL;
counters[329]++;
QMPI_TABLE_QUERY(329, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 329, v, win_copy_attr_fn, win_delete_attr_fn,
win_keyval, extra_state);
return ret;
}
/* ================== C Wrappers for MPI_Win_delete_attr ================== */
int E_Win_delete_attr(MPI_Win win, int win_keyval, int i, vector *v) {
void *f_dl = NULL;
counters[330]++;
QMPI_TABLE_QUERY(330, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 330, v, win, win_keyval);
return ret;
}
/* ================== C Wrappers for MPI_Win_detach ================== */
int E_Win_detach(MPI_Win win, const void *base, int i, vector *v) {
void *f_dl = NULL;
counters[331]++;
QMPI_TABLE_QUERY(331, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 331, v, win, base);
return ret;
}
/* ================== C Wrappers for MPI_Win_fence ================== */
int E_Win_fence(int assert, MPI_Win win, int i, vector *v) {
void *f_dl = NULL;
counters[332]++;
QMPI_TABLE_QUERY(332, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 332, v, assert, win);
return ret;
}
/* ================== C Wrappers for MPI_Win_flush ================== */
int E_Win_flush(int rank, MPI_Win win, int i, vector *v) {
void *f_dl = NULL;
counters[333]++;
QMPI_TABLE_QUERY(333, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 333, v, rank, win);
return ret;
}
/* ================== C Wrappers for MPI_Win_flush_all ================== */
int E_Win_flush_all(MPI_Win win, int i, vector *v) {
void *f_dl = NULL;
counters[334]++;
QMPI_TABLE_QUERY(334, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 334, v, win);
return ret;
}
/* ================== C Wrappers for MPI_Win_flush_local ================== */
int E_Win_flush_local(int rank, MPI_Win win, int i, vector *v) {
void *f_dl = NULL;
counters[335]++;
QMPI_TABLE_QUERY(335, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 335, v, rank, win);
return ret;
}
/* ================== C Wrappers for MPI_Win_flush_local_all ==================
*/
int E_Win_flush_local_all(MPI_Win win, int i, vector *v) {
void *f_dl = NULL;
counters[336]++;
QMPI_TABLE_QUERY(336, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 336, v, win);
return ret;
}
/* ================== C Wrappers for MPI_Win_free ================== */
int E_Win_free(MPI_Win *win, int i, vector *v) {
void *f_dl = NULL;
counters[337]++;
QMPI_TABLE_QUERY(337, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 337, v, win);
return ret;
}
/* ================== C Wrappers for MPI_Win_free_keyval ================== */
int E_Win_free_keyval(int *win_keyval, int i, vector *v) {
void *f_dl = NULL;
counters[338]++;
QMPI_TABLE_QUERY(338, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 338, v, win_keyval);
return ret;
}
/* ================== C Wrappers for MPI_Win_get_attr ================== */
int E_Win_get_attr(MPI_Win win, int win_keyval, void *attribute_val, int *flag,
int i, vector *v) {
void *f_dl = NULL;
counters[339]++;
QMPI_TABLE_QUERY(339, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 339, v, win, win_keyval, attribute_val, flag);
return ret;
}
/* ================== C Wrappers for MPI_Win_get_errhandler ==================
*/
int E_Win_get_errhandler(MPI_Win win, MPI_Errhandler *errhandler, int i,
vector *v) {
void *f_dl = NULL;
counters[340]++;
QMPI_TABLE_QUERY(340, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 340, v, win, errhandler);
return ret;
}
/* ================== C Wrappers for MPI_Win_get_group ================== */
int E_Win_get_group(MPI_Win win, MPI_Group *group, int i, vector *v) {
void *f_dl = NULL;
counters[341]++;
QMPI_TABLE_QUERY(341, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 341, v, win, group);
return ret;
}
/* ================== C Wrappers for MPI_Win_get_info ================== */
int E_Win_get_info(MPI_Win win, MPI_Info *info_used, int i, vector *v) {
void *f_dl = NULL;
counters[342]++;
QMPI_TABLE_QUERY(342, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 342, v, win, info_used);
return ret;
}
/* ================== C Wrappers for MPI_Win_get_name ================== */
int E_Win_get_name(MPI_Win win, char *win_name, int *resultlen, int i,
vector *v) {
void *f_dl = NULL;
counters[343]++;
QMPI_TABLE_QUERY(343, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 343, v, win, win_name, resultlen);
return ret;
}
/* ================== C Wrappers for MPI_Win_lock ================== */
int E_Win_lock(int lock_type, int rank, int assert, MPI_Win win, int i,
vector *v) {
void *f_dl = NULL;
counters[344]++;
QMPI_TABLE_QUERY(344, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 344, v, lock_type, rank, assert, win);
return ret;
}
/* ================== C Wrappers for MPI_Win_lock_all ================== */
int E_Win_lock_all(int assert, MPI_Win win, int i, vector *v) {
void *f_dl = NULL;
counters[345]++;
QMPI_TABLE_QUERY(345, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 345, v, assert, win);
return ret;
}
/* ================== C Wrappers for MPI_Win_post ================== */
int E_Win_post(MPI_Group group, int assert, MPI_Win win, int i, vector *v) {
void *f_dl = NULL;
counters[346]++;
QMPI_TABLE_QUERY(346, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 346, v, group, assert, win);
return ret;
}
/* ================== C Wrappers for MPI_Win_set_attr ================== */
int E_Win_set_attr(MPI_Win win, int win_keyval, void *attribute_val, int i,
vector *v) {
void *f_dl = NULL;
counters[347]++;
QMPI_TABLE_QUERY(347, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 347, v, win, win_keyval, attribute_val);
return ret;
}
/* ================== C Wrappers for MPI_Win_set_errhandler ==================
*/
int E_Win_set_errhandler(MPI_Win win, MPI_Errhandler errhandler, int i,
vector *v) {
void *f_dl = NULL;
counters[348]++;
QMPI_TABLE_QUERY(348, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 348, v, win, errhandler);
return ret;
}
/* ================== C Wrappers for MPI_Win_set_info ================== */
int E_Win_set_info(MPI_Win win, MPI_Info info, int i, vector *v) {
void *f_dl = NULL;
counters[349]++;
QMPI_TABLE_QUERY(349, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 349, v, win, info);
return ret;
}
/* ================== C Wrappers for MPI_Win_set_name ================== */
int E_Win_set_name(MPI_Win win, const char *win_name, int i, vector *v) {
void *f_dl = NULL;
counters[350]++;
QMPI_TABLE_QUERY(350, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 350, v, win, win_name);
return ret;
}
/* ================== C Wrappers for MPI_Win_shared_query ================== */
int E_Win_shared_query(MPI_Win win, int rank, MPI_Aint *size, int *disp_unit,
void *baseptr, int i, vector *v) {
void *f_dl = NULL;
counters[351]++;
QMPI_TABLE_QUERY(351, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 351, v, win, rank, size, disp_unit, baseptr);
return ret;
}
/* ================== C Wrappers for MPI_Win_start ================== */
int E_Win_start(MPI_Group group, int assert, MPI_Win win, int i, vector *v) {
void *f_dl = NULL;
counters[352]++;
QMPI_TABLE_QUERY(352, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 352, v, group, assert, win);
return ret;
}
/* ================== C Wrappers for MPI_Win_sync ================== */
int E_Win_sync(MPI_Win win, int i, vector *v) {
void *f_dl = NULL;
counters[353]++;
QMPI_TABLE_QUERY(353, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 353, v, win);
return ret;
}
/* ================== C Wrappers for MPI_Win_test ================== */
int E_Win_test(MPI_Win win, int *flag, int i, vector *v) {
void *f_dl = NULL;
counters[354]++;
QMPI_TABLE_QUERY(354, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 354, v, win, flag);
return ret;
}
/* ================== C Wrappers for MPI_Win_unlock ================== */
int E_Win_unlock(int rank, MPI_Win win, int i, vector *v) {
void *f_dl = NULL;
counters[355]++;
QMPI_TABLE_QUERY(355, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 355, v, rank, win);
return ret;
}
/* ================== C Wrappers for MPI_Win_unlock_all ================== */
int E_Win_unlock_all(MPI_Win win, int i, vector *v) {
void *f_dl = NULL;
counters[356]++;
QMPI_TABLE_QUERY(356, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 356, v, win);
return ret;
}
/* ================== C Wrappers for MPI_Win_wait ================== */
int E_Win_wait(MPI_Win win, int i, vector *v) {
void *f_dl = NULL;
counters[357]++;
QMPI_TABLE_QUERY(357, &f_dl, (*VECTOR_GET(v, i)).table);
int ret = EXEC_FUNC(f_dl, i, 357, v, win);
return ret;
}
/* ================== C Wrappers for MPI_Wtick ================== */
double E_Wtick(int i, vector *v) {
void *f_dl = NULL;
counters[358]++;
QMPI_TABLE_QUERY(358, &f_dl, (*VECTOR_GET(v, i)).table);
// int ret=EXEC_FUNC(f_dl,i,358,v);
int level = QMPI_GET_LEVEL(i, 358, v);
int ret = 0;
if (f_dl == NULL) {
printf(
"function pointer for execution is null,function can't be executed "
", returns \n");
return ret;
} else {
typedef double (*wtick_func)(int level, vector *v);
wtick_func QMPI_Wtick_ptr = (wtick_func)f_dl;
double ret_Wtick = (QMPI_Wtick_ptr)(level, v);
return ret_Wtick;
}
}
/* ================== C Wrappers for MPI_Wtime ================== */
double E_Wtime(int i, vector *v) {
void *f_dl = NULL;
counters[359]++;
QMPI_TABLE_QUERY(359, &f_dl, (*VECTOR_GET(v, i)).table);
// int ret=EXEC_FUNC(f_dl,i,359,v);
int level = QMPI_GET_LEVEL(i, 359, v);
int ret = 0;
if (f_dl == NULL) {
printf(
"function pointer for execution is null,function can't be executed "
", returns \n");
return ret;
} else {
typedef double (*wtime_func)(int level, vector *v);
wtime_func QMPI_Wtime_ptr = (wtime_func)f_dl;
double ret_Wtime = (QMPI_Wtime_ptr)(level, v);
return ret_Wtime;
}
}
| 39.085144 | 80 | 0.565065 | [
"vector"
] |
6cd0c55dcc4e0794e8a2638caf50ae220aab2f3c | 567 | h | C | Fireworks/Calo/interface/thetaBins.h | nistefan/cmssw | ea13af97f7f2117a4f590a5e654e06ecd9825a5b | [
"Apache-2.0"
] | 3 | 2018-08-24T19:10:26.000Z | 2019-02-19T11:45:32.000Z | Fireworks/Calo/interface/thetaBins.h | nistefan/cmssw | ea13af97f7f2117a4f590a5e654e06ecd9825a5b | [
"Apache-2.0"
] | 3 | 2018-08-23T13:40:24.000Z | 2019-12-05T21:16:03.000Z | Fireworks/Calo/interface/thetaBins.h | nistefan/cmssw | ea13af97f7f2117a4f590a5e654e06ecd9825a5b | [
"Apache-2.0"
] | 5 | 2018-08-21T16:37:52.000Z | 2020-01-09T13:33:17.000Z | #ifndef Fireworks_Calo_thetaBins_h
#define Fireworks_Calo_thetaBins_h
// -*- C++ -*-
//
// Package: Calo
// Class : thetaBins
//
/**\class thetaBins thetaBins.h Fireworks/Calo/interface/thetaBins.h
Description: <one line class summary>
Usage:
<usage>
*/
//
// Original Author: Chris Jones
// Created: Thu Dec 11 22:59:29 EST 2008
//
// system include files
#include <vector>
#include <algorithm>
// user include files
// forward declarations
namespace fireworks {
std::vector<std::pair<double,double> > thetaBins();
}
#endif
| 16.2 | 68 | 0.670194 | [
"vector"
] |
6cd5b286cfef12cfadc20cd68ccdb0077e590fe0 | 9,709 | h | C | vpr7_x2p/printhandler/SRC/TC_Common/TCT_RegExpIter.h | ganeshgore/OpenFPGA | e2e4a9287ddd3f88ee6d436fa4b7e616bcd20390 | [
"MIT"
] | 31 | 2016-02-15T02:57:28.000Z | 2021-06-02T10:40:25.000Z | vpr7_x2p/printhandler/SRC/TC_Common/TCT_RegExpIter.h | ganeshgore/OpenFPGA | e2e4a9287ddd3f88ee6d436fa4b7e616bcd20390 | [
"MIT"
] | null | null | null | vpr7_x2p/printhandler/SRC/TC_Common/TCT_RegExpIter.h | ganeshgore/OpenFPGA | e2e4a9287ddd3f88ee6d436fa4b7e616bcd20390 | [
"MIT"
] | 6 | 2017-02-08T21:51:51.000Z | 2021-06-02T10:40:40.000Z | //===========================================================================//
// Purpose : Template version for a regular expression list iterator class.
// This class handles applying a name string, possibly defined
// using regular expression constructs, to a match list template
// object, returning 0 or more indices to list elements with
// matching name strings.
//
// Inline methods include:
// - TCT_RegExpIter, ~TCT_RegExpIter
// - HasRegExp
// - IsValid
//
// Public methods include:
// - Init
// - Next
//
//===========================================================================//
#ifndef TCT_REGEXP_ITER_H
#define TCT_REGEXP_ITER_H
#include <stdio.h>
#include <limits.h>
#include <string>
using namespace std;
#include "RegExp.h"
#include "TIO_PrintHandler.h"
#include "TC_Typedefs.h"
// Define a default invalid index value
#define TCT_REGEXP_INDEX_INVALID SIZE_MAX
//===========================================================================//
// Purpose : Class declaration
// Author : Jeff Rudolph
//---------------------------------------------------------------------------//
// Version history
// 05/01/12 jeffr : Original
//===========================================================================//
template< class T > class TCT_RegExpIter_c
{
public:
TCT_RegExpIter_c( void );
TCT_RegExpIter_c( const char* pszRegExp,
const T& matchList );
TCT_RegExpIter_c( const string& srRegExp,
const T& matchList );
~TCT_RegExpIter_c( void );
bool Init( const char* pszRegExp,
const T& matchList );
bool Init( const string& srRegExp,
const T& matchList );
size_t Next( void );
bool HasRegExp( void ) const;
bool IsValid( void ) const;
private:
RegExp* pregExp_; // Ptr to object for RE pattern matching
string* psrRegExp_; // Ptr to simple RE pattern string
T* pmatchList_; // Ptr to a match list for pattern matching
size_t matchIndex_; // Current index to match list for matching
size_t nextIndex_; // Next index to match list for matching
bool isValid_; // true => object has been initialized;
};
//===========================================================================//
// Purpose : Class inline definition(s)
// Author : Jeff Rudolph
//---------------------------------------------------------------------------//
// Version history
// 05/01/12 jeffr : Original
//===========================================================================//
template< class T > inline TCT_RegExpIter_c< T >::TCT_RegExpIter_c(
void )
:
pregExp_( 0 ),
psrRegExp_( 0 ),
pmatchList_( 0 ),
matchIndex_( TCT_REGEXP_INDEX_INVALID ),
nextIndex_( 0 ),
isValid_( false )
{
}
//===========================================================================//
template< class T > inline TCT_RegExpIter_c< T >::TCT_RegExpIter_c(
const char* pszRegExp,
const T& matchList )
:
pregExp_( 0 ),
psrRegExp_( 0 ),
pmatchList_( 0 ),
matchIndex_( TCT_REGEXP_INDEX_INVALID ),
nextIndex_( 0 ),
isValid_( false )
{
this->Init( pszRegExp, matchList );
}
//===========================================================================//
template< class T > inline TCT_RegExpIter_c< T >::TCT_RegExpIter_c(
const string& srRegExp,
const T& matchList )
:
pregExp_( 0 ),
psrRegExp_( 0 ),
pmatchList_( 0 ),
matchIndex_( TCT_REGEXP_INDEX_INVALID ),
nextIndex_( 0 ),
isValid_( false )
{
this->Init( srRegExp, matchList );
}
//===========================================================================//
template< class T > inline TCT_RegExpIter_c< T >::~TCT_RegExpIter_c(
void )
{
delete this->pregExp_;
delete this->psrRegExp_;
}
//===========================================================================//
template< class T > inline bool TCT_RegExpIter_c< T >::HasRegExp(
void ) const
{
return( this->pregExp_ ? true : false );
}
//===========================================================================//
template< class T > inline bool TCT_RegExpIter_c< T >::IsValid(
void ) const
{
return( this->isValid_ );
}
//===========================================================================//
// Method : Init
// Purpose : Initialize this object for regular expression pattern
// matching based on the given regular expression string
// and given match list used for pattern matching.
// Author : Jeff Rudolph
//---------------------------------------------------------------------------//
// Version history
// 05/01/12 jeffr : Original
//===========================================================================//
template< class T > bool TCT_RegExpIter_c< T >::Init(
const char* pszRegExp,
const T& matchList )
{
string srRegExp( pszRegExp ? pszRegExp : "" );
return( this->Init( srRegExp, matchList ));
}
//===========================================================================//
template< class T > bool TCT_RegExpIter_c< T >::Init(
const string& srRegExp,
const T& matchList )
{
bool ok = true;
// Reset object state (object may have been used by a previous pattern)
delete this->pregExp_;
this->pregExp_ = 0;
delete this->psrRegExp_;
this->psrRegExp_ = 0;
this->pmatchList_ = const_cast< T* >( &matchList );
this->matchIndex_ = TCT_REGEXP_INDEX_INVALID;
this->nextIndex_ = 0;
// Make regular expression object or simple string, whichever is needed
string srRegExp_( srRegExp );
const char* pszSpecialChars = "^.?[]+*$";
if ( srRegExp_.find_first_of( pszSpecialChars ) != string::npos )
{
size_t escape = srRegExp_.find( '\\' );
while (( escape != string::npos ) &&
( escape < srRegExp_.length( ) - 1 ))
{
srRegExp_.replace( escape, 2, "" );
escape = srRegExp_.find( '\\' );
}
}
if ( srRegExp_.find_first_of( pszSpecialChars ) != string::npos )
{
// Regular expression string may require 'pattern-matching'
this->pregExp_ = new TC_NOTHROW RegExp( srRegExp.data( ));
TIO_PrintHandler_c& printHandler = TIO_PrintHandler_c::GetInstance( );
ok = printHandler.IsValidNew( this->pregExp_,
sizeof( RegExp ),
"TCT_RegExpIter_c< T >::Init" );
if ( ok )
{
if ( !this->pregExp_->IsValidRE( ) )
{
printHandler.Error( "Invalid regular expression '%s', pattern is illegal!\n",
TIO_SR_STR( srRegExp ));
ok = printHandler.IsWithinMaxErrorCount( );
delete this->pregExp_;
this->pregExp_ = 0;
}
}
}
else
{
// Simple string does not have to be 'pattern-matched'
this->psrRegExp_ = new TC_NOTHROW string( srRegExp );
TIO_PrintHandler_c& printHandler = TIO_PrintHandler_c::GetInstance( );
ok = printHandler.IsValidNew( this->psrRegExp_,
sizeof( string ),
"TCT_RegExpIter_c< T >::Init" );
}
this->isValid_ = ok;
return( ok );
}
//===========================================================================//
// Method : Next
// Purpose : Apply the current regular expression to the current
// match list, returning an index to the next element in
// the current match list with a matching string
// Author : Jeff Rudolph
//---------------------------------------------------------------------------//
// Version history
// 05/01/12 jeffr : Original
//===========================================================================//
template< class T > size_t TCT_RegExpIter_c< T >::Next(
void )
{
if ( this->pregExp_ )
{
// Using 'complex' pattern matching (ie. with special characters)
this->matchIndex_ = TCT_REGEXP_INDEX_INVALID;
while (( this->matchIndex_ == TCT_REGEXP_INDEX_INVALID ) &&
( this->nextIndex_ <= this->pmatchList_->GetLength( ) - 1 ))
{
// Get next string, then apply the current regular expression
size_t nextIndex = this->nextIndex_;
const char* pszNextString = this->pmatchList_->FindName( nextIndex );
string srNextString( pszNextString ? pszNextString : "" );
size_t matchStart = 0;
size_t matchLength = 0;
bool match = this->pregExp_->Index( srNextString.data( ),
&matchStart,
&matchLength );
if ( match && ( srNextString.length( ) == matchLength ))
{
this->matchIndex_ = this->nextIndex_;
}
++this->nextIndex_;
}
if ( this->matchIndex_ == TCT_REGEXP_INDEX_INVALID )
{
delete this->psrRegExp_;
this->psrRegExp_ = 0;
}
}
else if ( this->psrRegExp_ )
{
// Using 'simple' pattern matching (ie. no special characters)
const string& srRegExp = *this->psrRegExp_;
this->matchIndex_ = this->pmatchList_->FindIndex( srRegExp );
delete this->psrRegExp_;
this->psrRegExp_ = 0;
}
else
{
this->matchIndex_ = TCT_REGEXP_INDEX_INVALID;
}
return( this->matchIndex_ );
}
#endif
| 32.471572 | 89 | 0.492018 | [
"object"
] |
6cd7bde5ce92682c249dbd176f6aca791ed54a7b | 1,893 | c | C | extendingPython_CAPI-cython/c_code/src/pywrapper.c | karthik/berkeley | 966563f24320cb002a6e48318ece0e8fe9cf6983 | [
"BSD-3-Clause"
] | 106 | 2015-01-08T13:49:44.000Z | 2022-03-12T13:32:03.000Z | extendingPython_CAPI-cython/c_code/src/pywrapper.c | karthik/berkeley | 966563f24320cb002a6e48318ece0e8fe9cf6983 | [
"BSD-3-Clause"
] | 57 | 2015-01-29T21:44:08.000Z | 2018-10-01T09:37:45.000Z | extendingPython_CAPI-cython/c_code/src/pywrapper.c | karthik/berkeley | 966563f24320cb002a6e48318ece0e8fe9cf6983 | [
"BSD-3-Clause"
] | 86 | 2015-01-13T19:05:32.000Z | 2021-09-14T08:42:45.000Z | // Python headers
#include <Python.h>
#include "numpy/arrayobject.h"
// C-headers
#include <stdint.h>
// Our headers
#include "my_function.h"
// Our wrapper function - handles the communication between python and C
PyObject* wrap_find_potential_event_ptrs( PyObject* self, PyObject* args )
{
// Pointers for holding input from python (use PyArg_ParseTuple)
PyArrayObject* dtarr; // Pointer to array object
uint64_t* timestamps; // Pointer to timestamp data array
int ary_len; // length of timestamp array
int coinc_win; // size of coincidence window
int min_ev_size; // min event size
int max_ev_size; // max event size
// Extract input using PyArg_ParseTuple. If parsing fails, raise exception
// i.e. return NULL
if( !PyArg_ParseTuple( args, "Oiii", &dtarr, &coinc_win, &min_ev_size,
&max_ev_size ) )
{ return NULL; }
// Get access to data in numpy array
timestamps = (uint64_t*) dtarr->data;
ary_len = dtarr->dimensions[0];
// Create lists for use in our function
Py_ssize_t list_size = 0;
PyObject* ptr_list = PyList_New(list_size);
PyObject* len_list = PyList_New(list_size);
// Call our C function
int ret = find_potential_event_ptrs(timestamps, ary_len, coinc_win,
min_ev_size, max_ev_size, ptr_list,
len_list);
// Return our lists pythonically
return Py_BuildValue( "OO", ptr_list, len_list );
}
// ---------------- Make our wrapped function visible to python ---------------
static PyMethodDef AnalysisMethods[] =
{
{"find_potential_event_ptrs", (PyCFunction)wrap_find_potential_event_ptrs,
METH_VARARGS, "C-version of find_potential_event_ptrs"},
{NULL, NULL} // Ends the method list
};
// Initialize our module with the methods we've defined
PyMODINIT_FUNC initc_version(void)
{
(void) Py_InitModule("c_version", AnalysisMethods );
import_array(); // load numpy
};
| 32.084746 | 79 | 0.705758 | [
"object"
] |
6cdb1920bc0351e81a3f742e3533d2a58c2c05e7 | 9,191 | h | C | garnet/lib/magma/tests/helper/command_buffer_helper.h | opensource-assist/fuschia | 66646c55b3d0b36aae90a4b6706b87f1a6261935 | [
"BSD-3-Clause"
] | 3 | 2020-08-02T04:46:18.000Z | 2020-08-07T10:10:53.000Z | garnet/lib/magma/tests/helper/command_buffer_helper.h | opensource-assist/fuschia | 66646c55b3d0b36aae90a4b6706b87f1a6261935 | [
"BSD-3-Clause"
] | 16 | 2020-09-04T19:01:11.000Z | 2021-05-28T03:23:09.000Z | garnet/lib/magma/tests/helper/command_buffer_helper.h | OpenTrustGroup/fuchsia | 647e593ea661b8bf98dcad2096e20e8950b24a97 | [
"BSD-3-Clause"
] | 1 | 2020-08-07T10:11:49.000Z | 2020-08-07T10:11:49.000Z | // Copyright 2016 The Fuchsia 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 "gtest/gtest.h"
#include "platform_pci_device.h"
#include "sys_driver/magma_driver.h"
#include "sys_driver/magma_system_connection.h"
#include "sys_driver/magma_system_context.h"
// a class to create and own the command buffer were trying to execute
class CommandBufferHelper {
public:
static std::unique_ptr<CommandBufferHelper> Create(
magma::PlatformPciDevice* platform_device = nullptr) {
auto msd_drv = msd_driver_unique_ptr_t(msd_driver_create(), &msd_driver_destroy);
if (!msd_drv)
return DRETP(nullptr, "failed to create msd driver");
msd_driver_configure(msd_drv.get(), MSD_DRIVER_CONFIG_TEST_NO_DEVICE_THREAD);
auto msd_dev = msd_driver_create_device(
msd_drv.get(), platform_device ? platform_device->GetDeviceHandle() : nullptr);
if (!msd_dev)
return DRETP(nullptr, "failed to create msd device");
auto dev =
std::shared_ptr<MagmaSystemDevice>(MagmaSystemDevice::Create(MsdDeviceUniquePtr(msd_dev)));
uint32_t ctx_id = 0;
auto msd_connection_t = msd_device_open(msd_dev, 0);
if (!msd_connection_t)
return DRETP(nullptr, "msd_device_open failed");
auto connection = std::unique_ptr<MagmaSystemConnection>(
new MagmaSystemConnection(dev, MsdConnectionUniquePtr(msd_connection_t)));
if (!connection)
return DRETP(nullptr, "failed to connect to msd device");
connection->CreateContext(ctx_id);
auto ctx = connection->LookupContext(ctx_id);
if (!msd_dev)
return DRETP(nullptr, "failed to create context");
return std::unique_ptr<CommandBufferHelper>(
new CommandBufferHelper(std::move(msd_drv), std::move(dev), std::move(connection), ctx));
}
static constexpr uint32_t kNumResources = 3;
static constexpr uint32_t kBufferSize = PAGE_SIZE * 2;
static constexpr uint32_t kWaitSemaphoreCount = 2;
static constexpr uint32_t kSignalSemaphoreCount = 2;
std::vector<MagmaSystemBuffer*>& resources() { return resources_; }
std::vector<msd_buffer_t*>& msd_resources() { return msd_resources_; }
msd_context_t* ctx() { return ctx_->msd_ctx(); }
MagmaSystemDevice* dev() { return dev_.get(); }
MagmaSystemConnection* connection() { return connection_.get(); }
magma::PlatformBuffer* buffer() {
DASSERT(buffer_);
return buffer_.get();
}
msd_semaphore_t** msd_wait_semaphores() { return msd_wait_semaphores_.data(); }
msd_semaphore_t** msd_signal_semaphores() { return msd_signal_semaphores_.data(); }
magma_system_command_buffer* abi_cmd_buf() {
DASSERT(buffer_data_);
return reinterpret_cast<magma_system_command_buffer*>(buffer_data_);
}
uint64_t* abi_wait_semaphore_ids() { return reinterpret_cast<uint64_t*>(abi_cmd_buf() + 1); }
uint64_t* abi_signal_semaphore_ids() {
return reinterpret_cast<uint64_t*>(abi_wait_semaphore_ids() + kWaitSemaphoreCount);
}
magma_system_exec_resource* abi_resources() {
return reinterpret_cast<magma_system_exec_resource*>(abi_signal_semaphore_ids() +
kSignalSemaphoreCount);
}
bool Execute() {
auto command_buffer = std::make_unique<magma_system_command_buffer>(*abi_cmd_buf());
std::vector<magma_system_exec_resource> resources;
for (uint32_t i = 0; i < kNumResources; i++) {
resources.emplace_back(abi_resources()[i]);
}
std::vector<uint64_t> semaphores;
for (uint32_t i = 0; i < kWaitSemaphoreCount; i++) {
semaphores.emplace_back(abi_wait_semaphore_ids()[i]);
}
for (uint32_t i = 0; i < kSignalSemaphoreCount; i++) {
semaphores.emplace_back(abi_signal_semaphore_ids()[i]);
}
if (!ctx_->ExecuteCommandBufferWithResources(std::move(command_buffer), std::move(resources),
std::move(semaphores)))
return false;
for (uint32_t i = 0; i < wait_semaphores_.size(); i++) {
wait_semaphores_[i]->Signal();
}
return true;
}
bool ExecuteAndWait() {
if (!Execute())
return false;
for (uint32_t i = 0; i < signal_semaphores_.size(); i++) {
if (!signal_semaphores_[i]->Wait(5000))
return DRETF(false, "timed out waiting for signal semaphore %d", i);
}
return true;
}
private:
CommandBufferHelper(msd_driver_unique_ptr_t msd_drv, std::shared_ptr<MagmaSystemDevice> dev,
std::unique_ptr<MagmaSystemConnection> connection, MagmaSystemContext* ctx)
: msd_drv_(std::move(msd_drv)),
dev_(std::move(dev)),
connection_(std::move(connection)),
ctx_(ctx) {
uint64_t buffer_size = sizeof(magma_system_command_buffer) +
sizeof(uint64_t) * kSignalSemaphoreCount +
sizeof(magma_system_exec_resource) * kNumResources;
buffer_ = magma::PlatformBuffer::Create(buffer_size, "command-buffer-backing");
DASSERT(buffer_);
DLOG("CommandBuffer backing buffer: %p", buffer_.get());
bool success = buffer_->MapCpu(&buffer_data_);
DASSERT(success);
DASSERT(buffer_data_);
abi_cmd_buf()->batch_buffer_resource_index = 0;
abi_cmd_buf()->batch_start_offset = 0;
abi_cmd_buf()->num_resources = kNumResources;
abi_cmd_buf()->wait_semaphore_count = kWaitSemaphoreCount;
abi_cmd_buf()->signal_semaphore_count = kSignalSemaphoreCount;
// batch buffer
{
auto batch_buf = &abi_resources()[0];
auto buffer = MagmaSystemBuffer::Create(
magma::PlatformBuffer::Create(kBufferSize, "command-buffer-batch"));
DASSERT(buffer);
uint32_t duplicate_handle;
success = buffer->platform_buffer()->duplicate_handle(&duplicate_handle);
DASSERT(success);
uint64_t id;
success = connection_->ImportBuffer(duplicate_handle, &id);
DASSERT(success);
resources_.push_back(connection_->LookupBuffer(id).get());
success = buffer->platform_buffer()->duplicate_handle(&duplicate_handle);
DASSERT(success);
batch_buf->buffer_id = id;
batch_buf->offset = 0;
batch_buf->length = buffer->platform_buffer()->size();
}
// other buffers
for (uint32_t i = 1; i < kNumResources; i++) {
auto resource = &abi_resources()[i];
auto buffer =
MagmaSystemBuffer::Create(magma::PlatformBuffer::Create(kBufferSize, "resource"));
DASSERT(buffer);
uint32_t duplicate_handle;
success = buffer->platform_buffer()->duplicate_handle(&duplicate_handle);
DASSERT(success);
uint64_t id;
success = connection_->ImportBuffer(duplicate_handle, &id);
DASSERT(success);
resources_.push_back(connection_->LookupBuffer(id).get());
success = buffer->platform_buffer()->duplicate_handle(&duplicate_handle);
DASSERT(success);
resource->buffer_id = id;
resource->offset = 0;
resource->length = buffer->platform_buffer()->size();
}
for (auto resource : resources_)
msd_resources_.push_back(resource->msd_buf());
// wait semaphores
for (uint32_t i = 0; i < kWaitSemaphoreCount; i++) {
auto semaphore =
std::shared_ptr<magma::PlatformSemaphore>(magma::PlatformSemaphore::Create());
DASSERT(semaphore);
uint32_t duplicate_handle;
success = semaphore->duplicate_handle(&duplicate_handle);
DASSERT(success);
wait_semaphores_.push_back(semaphore);
success = connection_->ImportObject(duplicate_handle, magma::PlatformObject::SEMAPHORE);
DASSERT(success);
abi_wait_semaphore_ids()[i] = semaphore->id();
msd_wait_semaphores_.push_back(
connection_->LookupSemaphore(semaphore->id())->msd_semaphore());
}
// signal semaphores
for (uint32_t i = 0; i < kSignalSemaphoreCount; i++) {
auto semaphore =
std::shared_ptr<magma::PlatformSemaphore>(magma::PlatformSemaphore::Create());
DASSERT(semaphore);
uint32_t duplicate_handle;
success = semaphore->duplicate_handle(&duplicate_handle);
DASSERT(success);
signal_semaphores_.push_back(semaphore);
success = connection_->ImportObject(duplicate_handle, magma::PlatformObject::SEMAPHORE);
DASSERT(success);
abi_signal_semaphore_ids()[i] = semaphore->id();
msd_signal_semaphores_.push_back(
connection_->LookupSemaphore(semaphore->id())->msd_semaphore());
}
}
msd_driver_unique_ptr_t msd_drv_;
std::shared_ptr<MagmaSystemDevice> dev_;
std::unique_ptr<MagmaSystemConnection> connection_;
MagmaSystemContext* ctx_; // owned by the connection
std::unique_ptr<magma::PlatformBuffer> buffer_;
// mapped address of buffer_, do not free
void* buffer_data_ = nullptr;
std::vector<MagmaSystemBuffer*> resources_;
std::vector<msd_buffer_t*> msd_resources_;
std::vector<std::shared_ptr<magma::PlatformSemaphore>> wait_semaphores_;
std::vector<msd_semaphore_t*> msd_wait_semaphores_;
std::vector<std::shared_ptr<magma::PlatformSemaphore>> signal_semaphores_;
std::vector<msd_semaphore_t*> msd_signal_semaphores_;
};
| 39.277778 | 99 | 0.695354 | [
"vector"
] |
6cdb72941ed6f1be11f9a36fc52ae8663447bb94 | 532 | h | C | src/qt/setvotesdialog.h | scificrypto/HyperStake | 51518f77863346f5eddbc95448871b28f23238a4 | [
"X11",
"MIT"
] | 2 | 2021-09-28T08:32:28.000Z | 2021-09-28T20:13:10.000Z | src/qt/setvotesdialog.h | scificrypto/HyperStake | 51518f77863346f5eddbc95448871b28f23238a4 | [
"X11",
"MIT"
] | null | null | null | src/qt/setvotesdialog.h | scificrypto/HyperStake | 51518f77863346f5eddbc95448871b28f23238a4 | [
"X11",
"MIT"
] | 5 | 2020-04-19T01:52:33.000Z | 2021-09-08T16:07:52.000Z | #ifndef ELEMENT_SETVOTESDIALOG_H
#define ELEMENT_SETVOTESDIALOG_H
#include <QDialog>
#include <QObject>
class WalletModel;
namespace Ui {
class SetVotesDialog;
}
class SetVotesDialog : public QDialog
{
Q_OBJECT
public:
SetVotesDialog(QWidget* parent);
~SetVotesDialog();
void SetWalletModel(WalletModel* model);
void UpdateTable();
private slots:
void on_voteButton_clicked();
private:
Ui::SetVotesDialog* ui;
WalletModel* walletModel;
void Clear();
};
#endif //ELEMENT_SETVOTESDIALOG_H
| 17.733333 | 44 | 0.736842 | [
"model"
] |
6cdd51495a128f5a191b02954f4e7d5e7e1435b7 | 729 | h | C | VertexBuffer.h | kagekiyo/3Dengine | f0942632df2bcba1a2d842fbbdef3f312d7b5313 | [
"MIT"
] | 1 | 2017-10-16T10:21:32.000Z | 2017-10-16T10:21:32.000Z | VertexBuffer.h | kagekiyo/3Dengine | f0942632df2bcba1a2d842fbbdef3f312d7b5313 | [
"MIT"
] | 2 | 2017-10-17T09:49:59.000Z | 2017-10-17T12:06:04.000Z | VertexBuffer.h | kagekiyo/3Dengine | f0942632df2bcba1a2d842fbbdef3f312d7b5313 | [
"MIT"
] | null | null | null | #ifndef UGE_VERTEXBUFFER_H
#define UGE_VERTEXBUFFER_H
#include <vector>
namespace UGE
{
class VertexBuffer
{
public:
struct Attribute
{
unsigned int id;
unsigned int components;
int offset;
};
VertexBuffer();
~VertexBuffer();
unsigned int getID() const;
void bind();
void setData(int size, const void *data);
int getSize() const;
void addAttribute(unsigned int id, unsigned int components, int offset);
const std::vector<Attribute>& getAttributes() const;
int getStride() const;
private:
void calculateStride();
unsigned int mID;
int mSize;
std::vector<Attribute> mAttributes;
int mStride;
};
}
#endif | 19.184211 | 80 | 0.633745 | [
"vector"
] |
6cde09a82b518d503395b1b0b038d1366974e136 | 40,780 | c | C | xev.c | freedesktop/xorg-xev | d1f08f62b455f5921ee4b7c86bc5b8e92d2871ed | [
"X11"
] | 8 | 2017-05-17T07:16:25.000Z | 2022-02-11T17:11:11.000Z | xev.c | freedesktop/xorg-xev | d1f08f62b455f5921ee4b7c86bc5b8e92d2871ed | [
"X11"
] | null | null | null | xev.c | freedesktop/xorg-xev | d1f08f62b455f5921ee4b7c86bc5b8e92d2871ed | [
"X11"
] | 7 | 2017-04-19T02:58:31.000Z | 2022-02-18T02:36:39.000Z | /*
Copyright (c) 1988 X Consortium
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 X CONSORTIUM 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.
Except as contained in this notice, the name of the X Consortium shall
not be used in advertising or otherwise to promote the sale, use or
other dealings in this Software without prior written authorization
from the X Consortium.
*/
/*
* Author: Jim Fulton, MIT X Consortium
*/
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <X11/Xlocale.h>
#include <X11/Xos.h>
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <X11/Xproto.h>
#include <X11/extensions/Xrandr.h>
#define INNER_WINDOW_WIDTH 50
#define INNER_WINDOW_HEIGHT 50
#define INNER_WINDOW_BORDER 4
#define INNER_WINDOW_X 10
#define INNER_WINDOW_Y 10
#define OUTER_WINDOW_MIN_WIDTH (INNER_WINDOW_WIDTH + \
2 * (INNER_WINDOW_BORDER + INNER_WINDOW_X))
#define OUTER_WINDOW_MIN_HEIGHT (INNER_WINDOW_HEIGHT + \
2 * (INNER_WINDOW_BORDER + INNER_WINDOW_Y))
#define OUTER_WINDOW_DEF_WIDTH (OUTER_WINDOW_MIN_WIDTH + 100)
#define OUTER_WINDOW_DEF_HEIGHT (OUTER_WINDOW_MIN_HEIGHT + 100)
#define OUTER_WINDOW_DEF_X 100
#define OUTER_WINDOW_DEF_Y 100
typedef unsigned long Pixel;
const char *Yes = "YES";
const char *No = "NO";
const char *Unknown = "unknown";
const char *ProgramName;
Display *dpy;
int screen;
XIC xic = NULL;
Atom wm_delete_window;
Atom wm_protocols;
Bool have_rr;
int rr_event_base, rr_error_base;
enum EventMaskIndex {
EVENT_MASK_INDEX_CORE,
EVENT_MASK_INDEX_RANDR,
NUM_EVENT_MASKS
};
static void usage (const char *errmsg) _X_NORETURN;
static void
prologue (XEvent *eventp, const char *event_name)
{
XAnyEvent *e = (XAnyEvent *) eventp;
printf ("\n%s event, serial %ld, synthetic %s, window 0x%lx,\n",
event_name, e->serial, e->send_event ? Yes : No, e->window);
}
static void
dump (char *str, int len)
{
printf("(");
len--;
while (len-- > 0)
printf("%02x ", (unsigned char) *str++);
printf("%02x)", (unsigned char) *str++);
}
static void
do_KeyPress (XEvent *eventp)
{
XKeyEvent *e = (XKeyEvent *) eventp;
KeySym ks;
KeyCode kc = 0;
Bool kc_set = False;
const char *ksname;
int nbytes, nmbbytes = 0;
char str[256+1];
static char *buf = NULL;
static int bsize = 8;
Status status;
if (buf == NULL)
buf = malloc (bsize);
nbytes = XLookupString (e, str, 256, &ks, NULL);
/* not supposed to call XmbLookupString on a key release event */
if (e->type == KeyPress && xic) {
do {
nmbbytes = XmbLookupString (xic, e, buf, bsize - 1, &ks, &status);
buf[nmbbytes] = '\0';
if (status == XBufferOverflow) {
bsize = nmbbytes + 1;
buf = realloc (buf, bsize);
}
} while (status == XBufferOverflow);
}
if (ks == NoSymbol)
ksname = "NoSymbol";
else {
if (!(ksname = XKeysymToString (ks)))
ksname = "(no name)";
kc = XKeysymToKeycode(dpy, ks);
kc_set = True;
}
printf (" root 0x%lx, subw 0x%lx, time %lu, (%d,%d), root:(%d,%d),\n",
e->root, e->subwindow, e->time, e->x, e->y, e->x_root, e->y_root);
printf (" state 0x%x, keycode %u (keysym 0x%lx, %s), same_screen %s,\n",
e->state, e->keycode, (unsigned long) ks, ksname,
e->same_screen ? Yes : No);
if (kc_set && e->keycode != kc)
printf (" XKeysymToKeycode returns keycode: %u\n",kc);
if (nbytes < 0) nbytes = 0;
if (nbytes > 256) nbytes = 256;
str[nbytes] = '\0';
printf (" XLookupString gives %d bytes: ", nbytes);
if (nbytes > 0) {
dump (str, nbytes);
printf (" \"%s\"\n", str);
} else {
printf ("\n");
}
/* not supposed to call XmbLookupString on a key release event */
if (e->type == KeyPress && xic) {
printf (" XmbLookupString gives %d bytes: ", nmbbytes);
if (nmbbytes > 0) {
dump (buf, nmbbytes);
printf (" \"%s\"\n", buf);
} else {
printf ("\n");
}
}
printf (" XFilterEvent returns: %s\n",
XFilterEvent (eventp, e->window) ? "True" : "False");
}
static void
do_KeyRelease (XEvent *eventp)
{
do_KeyPress (eventp); /* since it has the same info */
}
static void
do_ButtonPress (XEvent *eventp)
{
XButtonEvent *e = (XButtonEvent *) eventp;
printf (" root 0x%lx, subw 0x%lx, time %lu, (%d,%d), root:(%d,%d),\n",
e->root, e->subwindow, e->time, e->x, e->y, e->x_root, e->y_root);
printf (" state 0x%x, button %u, same_screen %s\n",
e->state, e->button, e->same_screen ? Yes : No);
}
static void
do_ButtonRelease (XEvent *eventp)
{
do_ButtonPress (eventp); /* since it has the same info */
}
static void
do_MotionNotify (XEvent *eventp)
{
XMotionEvent *e = (XMotionEvent *) eventp;
printf (" root 0x%lx, subw 0x%lx, time %lu, (%d,%d), root:(%d,%d),\n",
e->root, e->subwindow, e->time, e->x, e->y, e->x_root, e->y_root);
printf (" state 0x%x, is_hint %u, same_screen %s\n",
e->state, e->is_hint, e->same_screen ? Yes : No);
}
static void
do_EnterNotify (XEvent *eventp)
{
XCrossingEvent *e = (XCrossingEvent *) eventp;
const char *mode, *detail;
char dmode[10], ddetail[10];
switch (e->mode) {
case NotifyNormal: mode = "NotifyNormal"; break;
case NotifyGrab: mode = "NotifyGrab"; break;
case NotifyUngrab: mode = "NotifyUngrab"; break;
case NotifyWhileGrabbed: mode = "NotifyWhileGrabbed"; break;
default: mode = dmode, sprintf (dmode, "%u", e->mode); break;
}
switch (e->detail) {
case NotifyAncestor: detail = "NotifyAncestor"; break;
case NotifyVirtual: detail = "NotifyVirtual"; break;
case NotifyInferior: detail = "NotifyInferior"; break;
case NotifyNonlinear: detail = "NotifyNonlinear"; break;
case NotifyNonlinearVirtual: detail = "NotifyNonlinearVirtual"; break;
case NotifyPointer: detail = "NotifyPointer"; break;
case NotifyPointerRoot: detail = "NotifyPointerRoot"; break;
case NotifyDetailNone: detail = "NotifyDetailNone"; break;
default: detail = ddetail; sprintf (ddetail, "%u", e->detail); break;
}
printf (" root 0x%lx, subw 0x%lx, time %lu, (%d,%d), root:(%d,%d),\n",
e->root, e->subwindow, e->time, e->x, e->y, e->x_root, e->y_root);
printf (" mode %s, detail %s, same_screen %s,\n",
mode, detail, e->same_screen ? Yes : No);
printf (" focus %s, state %u\n", e->focus ? Yes : No, e->state);
}
static void
do_LeaveNotify (XEvent *eventp)
{
do_EnterNotify (eventp); /* since it has same information */
}
static void
do_FocusIn (XEvent *eventp)
{
XFocusChangeEvent *e = (XFocusChangeEvent *) eventp;
const char *mode, *detail;
char dmode[10], ddetail[10];
switch (e->mode) {
case NotifyNormal: mode = "NotifyNormal"; break;
case NotifyGrab: mode = "NotifyGrab"; break;
case NotifyUngrab: mode = "NotifyUngrab"; break;
case NotifyWhileGrabbed: mode = "NotifyWhileGrabbed"; break;
default: mode = dmode, sprintf (dmode, "%u", e->mode); break;
}
switch (e->detail) {
case NotifyAncestor: detail = "NotifyAncestor"; break;
case NotifyVirtual: detail = "NotifyVirtual"; break;
case NotifyInferior: detail = "NotifyInferior"; break;
case NotifyNonlinear: detail = "NotifyNonlinear"; break;
case NotifyNonlinearVirtual: detail = "NotifyNonlinearVirtual"; break;
case NotifyPointer: detail = "NotifyPointer"; break;
case NotifyPointerRoot: detail = "NotifyPointerRoot"; break;
case NotifyDetailNone: detail = "NotifyDetailNone"; break;
default: detail = ddetail; sprintf (ddetail, "%u", e->detail); break;
}
printf (" mode %s, detail %s\n", mode, detail);
}
static void
do_FocusOut (XEvent *eventp)
{
do_FocusIn (eventp); /* since it has same information */
}
static void
do_KeymapNotify (XEvent *eventp)
{
XKeymapEvent *e = (XKeymapEvent *) eventp;
int i;
printf (" keys: ");
for (i = 0; i < 32; i++) {
if (i == 16) printf ("\n ");
printf ("%-3u ", (unsigned int) e->key_vector[i]);
}
printf ("\n");
}
static void
do_Expose (XEvent *eventp)
{
XExposeEvent *e = (XExposeEvent *) eventp;
printf (" (%d,%d), width %d, height %d, count %d\n",
e->x, e->y, e->width, e->height, e->count);
}
static void
do_GraphicsExpose (XEvent *eventp)
{
XGraphicsExposeEvent *e = (XGraphicsExposeEvent *) eventp;
const char *m;
char mdummy[10];
switch (e->major_code) {
case X_CopyArea: m = "CopyArea"; break;
case X_CopyPlane: m = "CopyPlane"; break;
default: m = mdummy; sprintf (mdummy, "%d", e->major_code); break;
}
printf (" (%d,%d), width %d, height %d, count %d,\n",
e->x, e->y, e->width, e->height, e->count);
printf (" major %s, minor %d\n", m, e->minor_code);
}
static void
do_NoExpose (XEvent *eventp)
{
XNoExposeEvent *e = (XNoExposeEvent *) eventp;
const char *m;
char mdummy[10];
switch (e->major_code) {
case X_CopyArea: m = "CopyArea"; break;
case X_CopyPlane: m = "CopyPlane"; break;
default: m = mdummy; sprintf (mdummy, "%d", e->major_code); break;
}
printf (" major %s, minor %d\n", m, e->minor_code);
return;
}
static void
do_VisibilityNotify (XEvent *eventp)
{
XVisibilityEvent *e = (XVisibilityEvent *) eventp;
const char *v;
char vdummy[10];
switch (e->state) {
case VisibilityUnobscured: v = "VisibilityUnobscured"; break;
case VisibilityPartiallyObscured: v = "VisibilityPartiallyObscured"; break;
case VisibilityFullyObscured: v = "VisibilityFullyObscured"; break;
default: v = vdummy; sprintf (vdummy, "%d", e->state); break;
}
printf (" state %s\n", v);
}
static void
do_CreateNotify (XEvent *eventp)
{
XCreateWindowEvent *e = (XCreateWindowEvent *) eventp;
printf (" parent 0x%lx, window 0x%lx, (%d,%d), width %d, height %d\n",
e->parent, e->window, e->x, e->y, e->width, e->height);
printf ("border_width %d, override %s\n",
e->border_width, e->override_redirect ? Yes : No);
}
static void
do_DestroyNotify (XEvent *eventp)
{
XDestroyWindowEvent *e = (XDestroyWindowEvent *) eventp;
printf (" event 0x%lx, window 0x%lx\n", e->event, e->window);
}
static void
do_UnmapNotify (XEvent *eventp)
{
XUnmapEvent *e = (XUnmapEvent *) eventp;
printf (" event 0x%lx, window 0x%lx, from_configure %s\n",
e->event, e->window, e->from_configure ? Yes : No);
}
static void
do_MapNotify (XEvent *eventp)
{
XMapEvent *e = (XMapEvent *) eventp;
printf (" event 0x%lx, window 0x%lx, override %s\n",
e->event, e->window, e->override_redirect ? Yes : No);
}
static void
do_MapRequest (XEvent *eventp)
{
XMapRequestEvent *e = (XMapRequestEvent *) eventp;
printf (" parent 0x%lx, window 0x%lx\n", e->parent, e->window);
}
static void
do_ReparentNotify (XEvent *eventp)
{
XReparentEvent *e = (XReparentEvent *) eventp;
printf (" event 0x%lx, window 0x%lx, parent 0x%lx,\n",
e->event, e->window, e->parent);
printf (" (%d,%d), override %s\n", e->x, e->y,
e->override_redirect ? Yes : No);
}
static void
do_ConfigureNotify (XEvent *eventp)
{
XConfigureEvent *e = (XConfigureEvent *) eventp;
printf (" event 0x%lx, window 0x%lx, (%d,%d), width %d, height %d,\n",
e->event, e->window, e->x, e->y, e->width, e->height);
printf (" border_width %d, above 0x%lx, override %s\n",
e->border_width, e->above, e->override_redirect ? Yes : No);
}
static void
do_ConfigureRequest (XEvent *eventp)
{
XConfigureRequestEvent *e = (XConfigureRequestEvent *) eventp;
const char *detail;
char ddummy[10];
switch (e->detail) {
case Above: detail = "Above"; break;
case Below: detail = "Below"; break;
case TopIf: detail = "TopIf"; break;
case BottomIf: detail = "BottomIf"; break;
case Opposite: detail = "Opposite"; break;
default: detail = ddummy; sprintf (ddummy, "%d", e->detail); break;
}
printf (" parent 0x%lx, window 0x%lx, (%d,%d), width %d, height %d,\n",
e->parent, e->window, e->x, e->y, e->width, e->height);
printf (" border_width %d, above 0x%lx, detail %s, value 0x%lx\n",
e->border_width, e->above, detail, e->value_mask);
}
static void
do_GravityNotify (XEvent *eventp)
{
XGravityEvent *e = (XGravityEvent *) eventp;
printf (" event 0x%lx, window 0x%lx, (%d,%d)\n",
e->event, e->window, e->x, e->y);
}
static void
do_ResizeRequest (XEvent *eventp)
{
XResizeRequestEvent *e = (XResizeRequestEvent *) eventp;
printf (" width %d, height %d\n", e->width, e->height);
}
static void
do_CirculateNotify (XEvent *eventp)
{
XCirculateEvent *e = (XCirculateEvent *) eventp;
const char *p;
char pdummy[10];
switch (e->place) {
case PlaceOnTop: p = "PlaceOnTop"; break;
case PlaceOnBottom: p = "PlaceOnBottom"; break;
default: p = pdummy; sprintf (pdummy, "%d", e->place); break;
}
printf (" event 0x%lx, window 0x%lx, place %s\n",
e->event, e->window, p);
}
static void
do_CirculateRequest (XEvent *eventp)
{
XCirculateRequestEvent *e = (XCirculateRequestEvent *) eventp;
const char *p;
char pdummy[10];
switch (e->place) {
case PlaceOnTop: p = "PlaceOnTop"; break;
case PlaceOnBottom: p = "PlaceOnBottom"; break;
default: p = pdummy; sprintf (pdummy, "%d", e->place); break;
}
printf (" parent 0x%lx, window 0x%lx, place %s\n",
e->parent, e->window, p);
}
static void
do_PropertyNotify (XEvent *eventp)
{
XPropertyEvent *e = (XPropertyEvent *) eventp;
char *aname = XGetAtomName (dpy, e->atom);
const char *s;
char sdummy[10];
switch (e->state) {
case PropertyNewValue: s = "PropertyNewValue"; break;
case PropertyDelete: s = "PropertyDelete"; break;
default: s = sdummy; sprintf (sdummy, "%d", e->state); break;
}
printf (" atom 0x%lx (%s), time %lu, state %s\n",
e->atom, aname ? aname : Unknown, e->time, s);
XFree (aname);
}
static void
do_SelectionClear (XEvent *eventp)
{
XSelectionClearEvent *e = (XSelectionClearEvent *) eventp;
char *sname = XGetAtomName (dpy, e->selection);
printf (" selection 0x%lx (%s), time %lu\n",
e->selection, sname ? sname : Unknown, e->time);
XFree (sname);
}
static void
do_SelectionRequest (XEvent *eventp)
{
XSelectionRequestEvent *e = (XSelectionRequestEvent *) eventp;
char *sname = XGetAtomName (dpy, e->selection);
char *tname = XGetAtomName (dpy, e->target);
char *pname = XGetAtomName (dpy, e->property);
printf (" owner 0x%lx, requestor 0x%lx, selection 0x%lx (%s),\n",
e->owner, e->requestor, e->selection, sname ? sname : Unknown);
printf (" target 0x%lx (%s), property 0x%lx (%s), time %lu\n",
e->target, tname ? tname : Unknown, e->property,
pname ? pname : Unknown, e->time);
XFree (sname);
XFree (tname);
XFree (pname);
}
static void
do_SelectionNotify (XEvent *eventp)
{
XSelectionEvent *e = (XSelectionEvent *) eventp;
char *sname = XGetAtomName (dpy, e->selection);
char *tname = XGetAtomName (dpy, e->target);
char *pname = XGetAtomName (dpy, e->property);
printf (" selection 0x%lx (%s), target 0x%lx (%s),\n",
e->selection, sname ? sname : Unknown, e->target,
tname ? tname : Unknown);
printf (" property 0x%lx (%s), time %lu\n",
e->property, pname ? pname : Unknown, e->time);
XFree (sname);
XFree (tname);
XFree (pname);
}
static void
do_ColormapNotify (XEvent *eventp)
{
XColormapEvent *e = (XColormapEvent *) eventp;
const char *s;
char sdummy[10];
switch (e->state) {
case ColormapInstalled: s = "ColormapInstalled"; break;
case ColormapUninstalled: s = "ColormapUninstalled"; break;
default: s = sdummy; sprintf (sdummy, "%d", e->state); break;
}
printf (" colormap 0x%lx, new %s, state %s\n",
e->colormap, e->new ? Yes : No, s);
}
static void
do_ClientMessage (XEvent *eventp)
{
XClientMessageEvent *e = (XClientMessageEvent *) eventp;
char *mname = XGetAtomName (dpy, e->message_type);
if (e->message_type == wm_protocols) {
char *message = XGetAtomName (dpy, e->data.l[0]);
printf (" message_type 0x%lx (%s), format %d, message 0x%lx (%s)\n",
e->message_type, mname ? mname : Unknown, e->format, e->data.l[0], message);
XFree (message);
}
else {
printf (" message_type 0x%lx (%s), format %d\n",
e->message_type, mname ? mname : Unknown, e->format);
}
XFree (mname);
if (e->format == 32
&& e->message_type == wm_protocols
&& (Atom) e->data.l[0] == wm_delete_window)
exit (0);
}
static void
do_MappingNotify (XEvent *eventp)
{
XMappingEvent *e = (XMappingEvent *) eventp;
const char *r;
char rdummy[10];
switch (e->request) {
case MappingModifier: r = "MappingModifier"; break;
case MappingKeyboard: r = "MappingKeyboard"; break;
case MappingPointer: r = "MappingPointer"; break;
default: r = rdummy; sprintf (rdummy, "%d", e->request); break;
}
printf (" request %s, first_keycode %d, count %d\n",
r, e->first_keycode, e->count);
XRefreshKeyboardMapping(e);
}
static void
print_SubPixelOrder (SubpixelOrder subpixel_order)
{
switch (subpixel_order) {
case SubPixelUnknown: printf ("SubPixelUnknown"); return;
case SubPixelHorizontalRGB: printf ("SubPixelHorizontalRGB"); return;
case SubPixelHorizontalBGR: printf ("SubPixelHorizontalBGR"); return;
case SubPixelVerticalRGB: printf ("SubPixelVerticalRGB"); return;
case SubPixelVerticalBGR: printf ("SubPixelVerticalBGR"); return;
case SubPixelNone: printf ("SubPixelNone"); return;
default: printf ("%d", subpixel_order);
}
}
static void
print_Rotation (Rotation rotation)
{
if (rotation & RR_Rotate_0)
printf ("RR_Rotate_0");
else if (rotation & RR_Rotate_90)
printf ("RR_Rotate_90");
else if (rotation & RR_Rotate_180)
printf ("RR_Rotate_180");
else if (rotation & RR_Rotate_270)
printf ("RR_Rotate_270");
else {
printf ("%d", rotation);
return;
}
if (rotation & RR_Reflect_X)
printf (", RR_Reflect_X");
if (rotation & RR_Reflect_Y)
printf (", RR_Reflect_Y");
}
static void
print_Connection (Connection connection)
{
switch (connection) {
case RR_Connected: printf ("RR_Connected"); return;
case RR_Disconnected: printf ("RR_Disconnected"); return;
case RR_UnknownConnection: printf ("RR_UnknownConnection"); return;
default: printf ("%d", connection);
}
}
static void
do_RRScreenChangeNotify (XEvent *eventp)
{
XRRScreenChangeNotifyEvent *e = (XRRScreenChangeNotifyEvent *) eventp;
XRRUpdateConfiguration (eventp);
printf (" root 0x%lx, timestamp %lu, config_timestamp %lu\n",
e->root, e->timestamp, e->config_timestamp);
printf (" size_index %hu", e->size_index);
printf (", subpixel_order ");
print_SubPixelOrder (e->subpixel_order);
printf ("\n rotation ");
print_Rotation (e->rotation);
printf("\n width %d, height %d, mwidth %d, mheight %d\n",
e->width, e->height, e->mwidth, e->mheight);
}
static void
do_RRNotify_OutputChange (XEvent *eventp, XRRScreenResources *screen_resources)
{
XRROutputChangeNotifyEvent *e = (XRROutputChangeNotifyEvent *) eventp;
XRROutputInfo *output_info = NULL;
XRRModeInfo *mode_info = NULL;
if (screen_resources) {
int i;
output_info = XRRGetOutputInfo (dpy, screen_resources, e->output);
for (i = 0; i < screen_resources->nmode; i++)
if (screen_resources->modes[i].id == e->mode) {
mode_info = &screen_resources->modes[i]; break;
}
}
printf (" subtype XRROutputChangeNotifyEvent\n");
if (output_info)
printf (" output %s, ", output_info->name);
else
printf (" output %lu, ", e->output);
if (e->crtc)
printf("crtc %lu, ", e->crtc);
else
printf("crtc None, ");
if (mode_info)
printf ("mode %s (%dx%d)\n", mode_info->name, mode_info->width,
mode_info->height);
else if (e->mode)
printf ("mode %lu\n", e->mode);
else
printf("mode None\n");
printf (" rotation ");
print_Rotation (e->rotation);
printf ("\n connection ");
print_Connection (e->connection);
printf (", subpixel_order ");
print_SubPixelOrder (e->subpixel_order);
printf ("\n");
XRRFreeOutputInfo (output_info);
}
static void
do_RRNotify_CrtcChange (XEvent *eventp, XRRScreenResources *screen_resources)
{
XRRCrtcChangeNotifyEvent *e = (XRRCrtcChangeNotifyEvent *) eventp;
XRRModeInfo *mode_info = NULL;
if (screen_resources) {
int i;
for (i = 0; i < screen_resources->nmode; i++)
if (screen_resources->modes[i].id == e->mode) {
mode_info = &screen_resources->modes[i]; break;
}
}
printf (" subtype XRRCrtcChangeNotifyEvent\n");
if (e->crtc)
printf(" crtc %lu, ", e->crtc);
else
printf(" crtc None, ");
if (mode_info)
printf ("mode %s, ", mode_info->name);
else if (e->mode)
printf ("mode %lu, ", e->mode);
else
printf("mode None, ");
printf ("rotation ");
print_Rotation (e->rotation);
printf ("\n x %d, y %d, width %d, height %d\n",
e->x, e->y, e->width, e->height);
}
static void
do_RRNotify_OutputProperty (XEvent *eventp,
XRRScreenResources *screen_resources)
{
XRROutputPropertyNotifyEvent *e = (XRROutputPropertyNotifyEvent *) eventp;
XRROutputInfo *output_info = NULL;
char *property = XGetAtomName (dpy, e->property);
if (screen_resources)
output_info = XRRGetOutputInfo (dpy, screen_resources, e->output);
printf (" subtype XRROutputPropertyChangeNotifyEvent\n");
if (output_info)
printf (" output %s, ", output_info->name);
else
printf (" output %lu, ", e->output);
printf ("property %s, timestamp %lu, state ",
property, e->timestamp);
if (e->state == PropertyNewValue)
printf ("NewValue\n");
else if (e->state == PropertyDelete)
printf ("Delete\n");
else
printf ("%d\n", e->state);
XRRFreeOutputInfo (output_info);
XFree (property);
}
static void
do_RRNotify (XEvent *eventp)
{
XRRNotifyEvent *e = (XRRNotifyEvent *) eventp;
XRRScreenResources *screen_resources;
XRRUpdateConfiguration (eventp);
screen_resources = XRRGetScreenResources (dpy, e->window);
prologue (eventp, "RRNotify");
switch (e->subtype) {
case RRNotify_OutputChange:
do_RRNotify_OutputChange (eventp, screen_resources); break;
case RRNotify_CrtcChange:
do_RRNotify_CrtcChange (eventp, screen_resources); break;
case RRNotify_OutputProperty:
do_RRNotify_OutputProperty (eventp, screen_resources); break;
default:
printf (" subtype %d\n", e->subtype);
}
XRRFreeScreenResources (screen_resources);
}
static void
set_sizehints (XSizeHints *hintp, int min_width, int min_height,
int defwidth, int defheight, int defx, int defy,
char *geom)
{
int geom_result;
/* set the size hints, algorithm from xlib xbiff */
hintp->width = hintp->min_width = min_width;
hintp->height = hintp->min_height = min_height;
hintp->flags = PMinSize;
hintp->x = hintp->y = 0;
geom_result = NoValue;
if (geom != NULL) {
geom_result = XParseGeometry (geom, &hintp->x, &hintp->y,
(unsigned int *)&hintp->width,
(unsigned int *)&hintp->height);
if ((geom_result & WidthValue) && (geom_result & HeightValue)) {
#ifndef max
#define max(a,b) ((a) > (b) ? (a) : (b))
#endif
hintp->width = max (hintp->width, hintp->min_width);
hintp->height = max (hintp->height, hintp->min_height);
hintp->flags |= USSize;
}
if ((geom_result & XValue) && (geom_result & YValue)) {
hintp->flags += USPosition;
}
}
if (!(hintp->flags & USSize)) {
hintp->width = defwidth;
hintp->height = defheight;
hintp->flags |= PSize;
}
/*
if (!(hintp->flags & USPosition)) {
hintp->x = defx;
hintp->y = defy;
hintp->flags |= PPosition;
}
*/
if (geom_result & XNegative) {
hintp->x = DisplayWidth (dpy, DefaultScreen (dpy)) + hintp->x -
hintp->width;
}
if (geom_result & YNegative) {
hintp->y = DisplayHeight (dpy, DefaultScreen (dpy)) + hintp->y -
hintp->height;
}
}
static void
usage (const char *errmsg)
{
static const char *msg[] = {
" -display displayname X server to contact",
" -geometry geom size and location of window",
" -bw pixels border width in pixels",
" -bs {NotUseful,WhenMapped,Always} backingstore attribute",
" -id windowid use existing window",
" -root use root window",
" -s set save-unders attribute",
" -name string window name",
" -rv reverse video",
" -event event_mask select 'event_mask' events",
" Supported event masks: keyboard mouse expose visibility structure",
" substructure focus property colormap",
" owner_grab_button randr button",
" This option can be specified multiple times to select multiple",
" event masks.",
"",
NULL};
const char **cpp;
if (errmsg != NULL)
fprintf (stderr, "%s: %s\n", ProgramName, errmsg);
fprintf (stderr, "usage: %s [-options ...]\n", ProgramName);
fprintf (stderr, "where options include:\n");
for (cpp = msg; *cpp; cpp++)
fprintf (stderr, "%s\n", *cpp);
exit (1);
}
static int
parse_backing_store (const char *s)
{
size_t len = strlen (s);
if (strncasecmp (s, "NotUseful", len) == 0) return (NotUseful);
if (strncasecmp (s, "WhenMapped", len) == 0) return (WhenMapped);
if (strncasecmp (s, "Always", len) == 0) return (Always);
fprintf (stderr, "%s: unrecognized argument '%s' for -bs\n",
ProgramName, s);
usage (NULL);
}
static Bool
parse_event_mask (const char *s, long event_masks[])
{
const struct {
const char *name;
enum EventMaskIndex mask_index;
long mask;
} events[] = {
{ "keyboard",
EVENT_MASK_INDEX_CORE,
KeyPressMask | KeyReleaseMask | KeymapStateMask },
{ "mouse",
EVENT_MASK_INDEX_CORE,
ButtonPressMask | ButtonReleaseMask | EnterWindowMask |
LeaveWindowMask | PointerMotionMask | Button1MotionMask |
Button2MotionMask | Button3MotionMask | Button4MotionMask |
Button5MotionMask | ButtonMotionMask },
{ "button",
EVENT_MASK_INDEX_CORE,
ButtonPressMask | ButtonReleaseMask },
{ "expose",
EVENT_MASK_INDEX_CORE,
ExposureMask },
{ "visibility",
EVENT_MASK_INDEX_CORE,
VisibilityChangeMask },
{ "structure",
EVENT_MASK_INDEX_CORE,
StructureNotifyMask },
{ "substructure",
EVENT_MASK_INDEX_CORE,
SubstructureNotifyMask | SubstructureRedirectMask },
{ "focus",
EVENT_MASK_INDEX_CORE,
FocusChangeMask },
{ "property",
EVENT_MASK_INDEX_CORE,
PropertyChangeMask },
{ "colormap",
EVENT_MASK_INDEX_CORE,
ColormapChangeMask },
{ "owner_grab_button",
EVENT_MASK_INDEX_CORE,
OwnerGrabButtonMask },
{ "randr",
EVENT_MASK_INDEX_RANDR,
RRScreenChangeNotifyMask | RRCrtcChangeNotifyMask |
RROutputChangeNotifyMask | RROutputPropertyNotifyMask },
{ NULL, 0, 0 }
};
int i;
for (i = 0; events[i].name; i++) {
if (!s || !strcmp(s, events[i].name)) {
event_masks[events[i].mask_index] |= events[i].mask;
if (s)
return True;
}
}
if (s != NULL)
fprintf (stderr, "%s: unrecognized event mask '%s'\n", ProgramName, s);
return False;
}
int
main (int argc, char **argv)
{
char *displayname = NULL;
char *geom = NULL;
int i;
XSizeHints hints;
int borderwidth = 2;
Window w, subw;
XSetWindowAttributes attr;
XWindowAttributes wattr;
unsigned long mask = 0L;
int done;
const char *name = "Event Tester";
Bool reverse = False;
Bool use_root = False;
unsigned long back, fore;
XIM xim;
XIMStyles *xim_styles;
XIMStyle xim_style = 0;
char *modifiers;
char *imvalret;
long event_masks[NUM_EVENT_MASKS];
Bool event_mask_specified = False;
ProgramName = argv[0];
if (setlocale(LC_ALL,"") == NULL) {
fprintf(stderr, "%s: warning: could not set default locale\n",
ProgramName);
}
memset(event_masks, 0, sizeof(event_masks));
w = 0;
for (i = 1; i < argc; i++) {
char *arg = argv[i];
if (arg[0] == '-') {
switch (arg[1]) {
case 'd': /* -display host:dpy */
if (++i >= argc) usage ("-display requires an argument");
displayname = argv[i];
continue;
case 'g': /* -geometry geom */
if (++i >= argc) usage ("-geometry requires an argument");
geom = argv[i];
continue;
case 'b':
switch (arg[2]) {
case 'w': /* -bw pixels */
if (++i >= argc) usage ("-bw requires an argument");
borderwidth = atoi (argv[i]);
continue;
case 's': /* -bs type */
if (++i >= argc) usage ("-bs requires an argument");
attr.backing_store = parse_backing_store (argv[i]);
mask |= CWBackingStore;
continue;
default:
goto unrecognized;
}
case 'i': /* -id */
if (++i >= argc) usage ("-id requires an argument");
sscanf(argv[i], "0x%lx", &w);
if (!w)
sscanf(argv[i], "%lu", &w);
if (!w) {
fprintf (stderr,
"%s: unable to parse argument '%s' for -id\n",
ProgramName, argv[i]);
usage (NULL);
}
continue;
case 'n': /* -name */
if (++i >= argc) usage ("-name requires an argument");
name = argv[i];
continue;
case 'r':
switch (arg[2]) {
case 'o': /* -root */
use_root = True;
continue;
case 'v': /* -rv */
reverse = True;
continue;
default:
goto unrecognized;
}
continue;
case 's': /* -s */
attr.save_under = True;
mask |= CWSaveUnder;
continue;
case 'e': /* -event */
if (++i >= argc) usage ("-event requires an argument");
if (!parse_event_mask (argv[i], event_masks))
usage (NULL);
event_mask_specified = True;
continue;
case 'v':
puts(PACKAGE_STRING);
exit(0);
default:
goto unrecognized;
} /* end switch on - */
} else {
unrecognized:
fprintf (stderr, "%s: unrecognized argument '%s'\n",
ProgramName, arg);
usage (NULL);
}
} /* end for over argc */
/* if no -event options were specified, pretend all of them were */
if (!event_mask_specified)
parse_event_mask (NULL, event_masks);
dpy = XOpenDisplay (displayname);
if (!dpy) {
fprintf (stderr, "%s: unable to open display '%s'\n",
ProgramName, XDisplayName (displayname));
exit (1);
}
/* we're testing the default input method */
modifiers = XSetLocaleModifiers ("@im=none");
if (modifiers == NULL) {
fprintf (stderr, "%s: XSetLocaleModifiers failed\n", ProgramName);
}
xim = XOpenIM (dpy, NULL, NULL, NULL);
if (xim == NULL) {
fprintf (stderr, "%s: XOpenIM failed\n", ProgramName);
}
if (xim) {
imvalret = XGetIMValues (xim, XNQueryInputStyle, &xim_styles, NULL);
if (imvalret != NULL || xim_styles == NULL) {
fprintf (stderr, "%s: input method doesn't support any styles\n", ProgramName);
}
if (xim_styles) {
xim_style = 0;
for (i = 0; i < xim_styles->count_styles; i++) {
if (xim_styles->supported_styles[i] ==
(XIMPreeditNothing | XIMStatusNothing)) {
xim_style = xim_styles->supported_styles[i];
break;
}
}
if (xim_style == 0) {
fprintf (stderr, "%s: input method doesn't support the style we support\n",
ProgramName);
}
XFree (xim_styles);
}
}
screen = DefaultScreen (dpy);
attr.event_mask = event_masks[EVENT_MASK_INDEX_CORE];
if (use_root)
w = RootWindow(dpy, screen);
if (w) {
XGetWindowAttributes(dpy, w, &wattr);
if (wattr.all_event_masks & ButtonPressMask)
attr.event_mask &= ~ButtonPressMask;
attr.event_mask &= ~SubstructureRedirectMask;
XSelectInput(dpy, w, attr.event_mask);
} else {
set_sizehints (&hints, OUTER_WINDOW_MIN_WIDTH, OUTER_WINDOW_MIN_HEIGHT,
OUTER_WINDOW_DEF_WIDTH, OUTER_WINDOW_DEF_HEIGHT,
OUTER_WINDOW_DEF_X, OUTER_WINDOW_DEF_Y, geom);
if (reverse) {
back = BlackPixel(dpy,screen);
fore = WhitePixel(dpy,screen);
} else {
back = WhitePixel(dpy,screen);
fore = BlackPixel(dpy,screen);
}
attr.background_pixel = back;
attr.border_pixel = fore;
mask |= (CWBackPixel | CWBorderPixel | CWEventMask);
w = XCreateWindow (dpy, RootWindow (dpy, screen), hints.x, hints.y,
hints.width, hints.height, borderwidth, 0,
InputOutput, (Visual *)CopyFromParent,
mask, &attr);
XSetStandardProperties (dpy, w, name, NULL, (Pixmap) 0,
argv, argc, &hints);
subw = XCreateSimpleWindow (dpy, w, INNER_WINDOW_X, INNER_WINDOW_Y,
INNER_WINDOW_WIDTH, INNER_WINDOW_HEIGHT,
INNER_WINDOW_BORDER,
attr.border_pixel, attr.background_pixel);
wm_protocols = XInternAtom(dpy, "WM_PROTOCOLS", False);
wm_delete_window = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
XSetWMProtocols(dpy, w, &wm_delete_window, 1);
XMapWindow (dpy, subw); /* map before w so that it appears */
XMapWindow (dpy, w);
printf ("Outer window is 0x%lx, inner window is 0x%lx\n", w, subw);
}
if (xim && xim_style) {
xic = XCreateIC (xim,
XNInputStyle, xim_style,
XNClientWindow, w,
XNFocusWindow, w,
NULL);
if (xic == NULL) {
fprintf (stderr, "XCreateIC failed\n");
}
}
have_rr = XRRQueryExtension (dpy, &rr_event_base, &rr_error_base);
if (have_rr) {
int rr_major, rr_minor;
if (XRRQueryVersion (dpy, &rr_major, &rr_minor)) {
int rr_mask = event_masks[EVENT_MASK_INDEX_RANDR];
if (rr_major == 1 && rr_minor <= 1) {
rr_mask &= ~(RRCrtcChangeNotifyMask |
RROutputChangeNotifyMask |
RROutputPropertyNotifyMask);
}
XRRSelectInput (dpy, w, rr_mask);
}
}
for (done = 0; !done; ) {
XEvent event;
XNextEvent (dpy, &event);
switch (event.type) {
case KeyPress:
prologue (&event, "KeyPress");
do_KeyPress (&event);
break;
case KeyRelease:
prologue (&event, "KeyRelease");
do_KeyRelease (&event);
break;
case ButtonPress:
prologue (&event, "ButtonPress");
do_ButtonPress (&event);
break;
case ButtonRelease:
prologue (&event, "ButtonRelease");
do_ButtonRelease (&event);
break;
case MotionNotify:
prologue (&event, "MotionNotify");
do_MotionNotify (&event);
break;
case EnterNotify:
prologue (&event, "EnterNotify");
do_EnterNotify (&event);
break;
case LeaveNotify:
prologue (&event, "LeaveNotify");
do_LeaveNotify (&event);
break;
case FocusIn:
prologue (&event, "FocusIn");
do_FocusIn (&event);
break;
case FocusOut:
prologue (&event, "FocusOut");
do_FocusOut (&event);
break;
case KeymapNotify:
prologue (&event, "KeymapNotify");
do_KeymapNotify (&event);
break;
case Expose:
prologue (&event, "Expose");
do_Expose (&event);
break;
case GraphicsExpose:
prologue (&event, "GraphicsExpose");
do_GraphicsExpose (&event);
break;
case NoExpose:
prologue (&event, "NoExpose");
do_NoExpose (&event);
break;
case VisibilityNotify:
prologue (&event, "VisibilityNotify");
do_VisibilityNotify (&event);
break;
case CreateNotify:
prologue (&event, "CreateNotify");
do_CreateNotify (&event);
break;
case DestroyNotify:
prologue (&event, "DestroyNotify");
do_DestroyNotify (&event);
break;
case UnmapNotify:
prologue (&event, "UnmapNotify");
do_UnmapNotify (&event);
break;
case MapNotify:
prologue (&event, "MapNotify");
do_MapNotify (&event);
break;
case MapRequest:
prologue (&event, "MapRequest");
do_MapRequest (&event);
break;
case ReparentNotify:
prologue (&event, "ReparentNotify");
do_ReparentNotify (&event);
break;
case ConfigureNotify:
prologue (&event, "ConfigureNotify");
do_ConfigureNotify (&event);
break;
case ConfigureRequest:
prologue (&event, "ConfigureRequest");
do_ConfigureRequest (&event);
break;
case GravityNotify:
prologue (&event, "GravityNotify");
do_GravityNotify (&event);
break;
case ResizeRequest:
prologue (&event, "ResizeRequest");
do_ResizeRequest (&event);
break;
case CirculateNotify:
prologue (&event, "CirculateNotify");
do_CirculateNotify (&event);
break;
case CirculateRequest:
prologue (&event, "CirculateRequest");
do_CirculateRequest (&event);
break;
case PropertyNotify:
prologue (&event, "PropertyNotify");
do_PropertyNotify (&event);
break;
case SelectionClear:
prologue (&event, "SelectionClear");
do_SelectionClear (&event);
break;
case SelectionRequest:
prologue (&event, "SelectionRequest");
do_SelectionRequest (&event);
break;
case SelectionNotify:
prologue (&event, "SelectionNotify");
do_SelectionNotify (&event);
break;
case ColormapNotify:
prologue (&event, "ColormapNotify");
do_ColormapNotify (&event);
break;
case ClientMessage:
prologue (&event, "ClientMessage");
do_ClientMessage (&event);
break;
case MappingNotify:
prologue (&event, "MappingNotify");
do_MappingNotify (&event);
break;
default:
if (have_rr) {
if (event.type == rr_event_base + RRScreenChangeNotify) {
prologue (&event, "RRScreenChangeNotify");
do_RRScreenChangeNotify (&event);
break;
}
if (event.type == rr_event_base + RRNotify) {
do_RRNotify (&event);
break;
}
}
printf ("Unknown event type %d\n", event.type);
break;
}
fflush(stdout);
}
XCloseDisplay (dpy);
return 0;
}
| 29.274946 | 92 | 0.606498 | [
"geometry"
] |
6ce24230399ebb0ceacc4e60d8e163d87618237e | 34,307 | h | C | include/maxscale/query_classifier.h | lishubing/MaxScale | 72ce2d2bc1468fd1f409fc885f8da67ab8a9bb0a | [
"MIT"
] | null | null | null | include/maxscale/query_classifier.h | lishubing/MaxScale | 72ce2d2bc1468fd1f409fc885f8da67ab8a9bb0a | [
"MIT"
] | 1 | 2019-07-02T09:59:27.000Z | 2019-07-02T09:59:49.000Z | include/maxscale/query_classifier.h | lishubing/MaxScale | 72ce2d2bc1468fd1f409fc885f8da67ab8a9bb0a | [
"MIT"
] | null | null | null | /*
* Copyright (c) 2018 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: 2022-01-01
*
* 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.
*/
#pragma once
#include <maxscale/cdefs.h>
#include <maxbase/jansson.h>
#include <maxscale/buffer.h>
MXS_BEGIN_DECLS
#define MXS_QUERY_CLASSIFIER_VERSION {3, 0, 0}
/**
* qc_init_kind_t specifies what kind of initialization should be performed.
*/
typedef enum qc_init_kind
{
QC_INIT_SELF = 0x01, /*< Initialize/finalize the query classifier itself. */
QC_INIT_PLUGIN = 0x02, /*< Initialize/finalize the plugin. */
QC_INIT_BOTH = 0x03
} qc_init_kind_t;
/**
* qc_option_t defines options that affect the classification.
*/
enum qc_option_t
{
QC_OPTION_STRING_ARG_AS_FIELD = (1 << 0), /*< Report a string argument to a function as a field. */
QC_OPTION_STRING_AS_FIELD = (1 << 1), /*< Report strings as fields. */
};
const uint32_t QC_OPTION_MASK = QC_OPTION_STRING_ARG_AS_FIELD | QC_OPTION_STRING_AS_FIELD;
/**
* qc_sql_mode_t specifies what should be assumed of the statements
* that will be parsed.
*/
typedef enum qc_sql_mode
{
QC_SQL_MODE_DEFAULT, /*< Assume the statements are MariaDB SQL. */
QC_SQL_MODE_ORACLE /*< Assume the statements are PL/SQL. */
} qc_sql_mode_t;
/**
* @c qc_collect_info_t specifies what information should be collected during parsing.
*/
typedef enum qc_collect_info
{
QC_COLLECT_ESSENTIALS = 0x00, /*< Collect only the base minimum. */
QC_COLLECT_TABLES = 0x01, /*< Collect table names. */
QC_COLLECT_DATABASES = 0x02, /*< Collect database names. */
QC_COLLECT_FIELDS = 0x04, /*< Collect field information. */
QC_COLLECT_FUNCTIONS = 0x08, /*< Collect function information. */
QC_COLLECT_ALL = (QC_COLLECT_TABLES | QC_COLLECT_DATABASES | QC_COLLECT_FIELDS | QC_COLLECT_FUNCTIONS)
} qc_collect_info_t;
/**
* qc_query_type_t defines bits that provide information about a
* particular statement.
*
* Note that more than one bit may be set for a single statement.
*/
typedef enum qc_query_type
{
QUERY_TYPE_UNKNOWN = 0x000000, /*< Initial value, can't be tested bitwisely */
QUERY_TYPE_LOCAL_READ = 0x000001, /*< Read non-database data, execute in MaxScale:any */
QUERY_TYPE_READ = 0x000002, /*< Read database data:any */
QUERY_TYPE_WRITE = 0x000004, /*< Master data will be modified:master */
QUERY_TYPE_MASTER_READ = 0x000008, /*< Read from the master:master */
QUERY_TYPE_SESSION_WRITE = 0x000010, /*< Session data will be modified:master or all */
QUERY_TYPE_USERVAR_WRITE = 0x000020, /*< Write a user variable:master or all */
QUERY_TYPE_USERVAR_READ = 0x000040, /*< Read a user variable:master or any */
QUERY_TYPE_SYSVAR_READ = 0x000080, /*< Read a system variable:master or any */
/** Not implemented yet */
// QUERY_TYPE_SYSVAR_WRITE = 0x000100, /*< Write a system variable:master or all */
QUERY_TYPE_GSYSVAR_READ = 0x000200, /*< Read global system variable:master or any */
QUERY_TYPE_GSYSVAR_WRITE = 0x000400, /*< Write global system variable:master or all */
QUERY_TYPE_BEGIN_TRX = 0x000800, /*< BEGIN or START TRANSACTION */
QUERY_TYPE_ENABLE_AUTOCOMMIT = 0x001000, /*< SET autocommit=1 */
QUERY_TYPE_DISABLE_AUTOCOMMIT = 0x002000, /*< SET autocommit=0 */
QUERY_TYPE_ROLLBACK = 0x004000, /*< ROLLBACK */
QUERY_TYPE_COMMIT = 0x008000, /*< COMMIT */
QUERY_TYPE_PREPARE_NAMED_STMT = 0x010000, /*< Prepared stmt with name from user:all */
QUERY_TYPE_PREPARE_STMT = 0x020000, /*< Prepared stmt with id provided by server:all */
QUERY_TYPE_EXEC_STMT = 0x040000, /*< Execute prepared statement:master or any */
QUERY_TYPE_CREATE_TMP_TABLE = 0x080000, /*< Create temporary table:master (could be all) */
QUERY_TYPE_READ_TMP_TABLE = 0x100000, /*< Read temporary table:master (could be any) */
QUERY_TYPE_SHOW_DATABASES = 0x200000, /*< Show list of databases */
QUERY_TYPE_SHOW_TABLES = 0x400000, /*< Show list of tables */
QUERY_TYPE_DEALLOC_PREPARE = 0x1000000 /*< Dealloc named prepare stmt:all */
} qc_query_type_t;
/**
* qc_query_op_t defines the operations a particular statement can perform.
*/
typedef enum qc_query_op
{
QUERY_OP_UNDEFINED = 0,
QUERY_OP_ALTER,
QUERY_OP_CALL,
QUERY_OP_CHANGE_DB,
QUERY_OP_CREATE,
QUERY_OP_DELETE,
QUERY_OP_DROP,
QUERY_OP_EXECUTE,
QUERY_OP_EXPLAIN,
QUERY_OP_GRANT,
QUERY_OP_INSERT,
QUERY_OP_LOAD_LOCAL,
QUERY_OP_LOAD,
QUERY_OP_REVOKE,
QUERY_OP_SELECT,
QUERY_OP_SHOW,
QUERY_OP_TRUNCATE,
QUERY_OP_UPDATE,
} qc_query_op_t;
/**
* qc_parse_result_t defines the possible outcomes when a statement is parsed.
*/
typedef enum qc_parse_result
{
QC_QUERY_INVALID = 0, /*< The query was not recognized or could not be parsed. */
QC_QUERY_TOKENIZED = 1, /*< The query was classified based on tokens; incompletely classified. */
QC_QUERY_PARTIALLY_PARSED = 2, /*< The query was only partially parsed; incompletely classified. */
QC_QUERY_PARSED = 3 /*< The query was fully parsed; completely classified. */
} qc_parse_result_t;
/**
* qc_field_context_t defines the context where a field appears.
*
* NOTE: A particular bit does NOT mean that the field appears ONLY in the context,
* but it may appear in other contexts as well.
*/
typedef enum qc_field_context
{
QC_FIELD_UNION = 1, /** The field appears on the right hand side in a UNION. */
QC_FIELD_SUBQUERY = 2 /** The field appears in a subquery. */
} qc_field_context_t;
typedef struct qc_field_info
{
char* database; /** Present if the field is of the form "a.b.c", NULL otherwise. */
char* table; /** Present if the field is of the form "a.b", NULL otherwise. */
char* column; /** Always present. */
uint32_t context; /** The context in which the field appears. */
} QC_FIELD_INFO;
/**
* QC_FUNCTION_INFO contains information about a function used in a statement.
*/
typedef struct qc_function_info
{
char* name; /** Name of function. */
QC_FIELD_INFO* fields; /** What fields the function accesses. */
uint32_t n_fields;/** The number of fields in @c fields. */
} QC_FUNCTION_INFO;
/**
* Each API function returns @c QC_RESULT_OK if the actual parsing process
* succeeded, and some error code otherwise.
*/
typedef enum qc_result
{
QC_RESULT_OK,
QC_RESULT_ERROR
} qc_result_t;
/**
* QC_STMT_INFO is an opaque type where the query classifier stores
* information about a statement.
*/
typedef struct qc_stmt_info
{
} QC_STMT_INFO;
/**
* QUERY_CLASSIFIER defines the object a query classifier plugin must
* implement and return.
*
* To a user of the query classifier functionality, it can in general
* be ignored.
*/
typedef struct query_classifier
{
/**
* Called once to setup the query classifier
*
* @param sql_mode The default sql mode.
* @param args The value of `query_classifier_args` in the configuration file.
*
* @return QC_RESULT_OK, if the query classifier could be setup, otherwise
* some specific error code.
*/
int32_t (* qc_setup)(qc_sql_mode_t sql_mode, const char* args);
/**
* Called once at process startup, after @c qc_setup has successfully
* been called.
*
* @return QC_RESULT_OK, if the process initialization succeeded.
*/
int32_t (* qc_process_init)(void);
/**
* Called once at process shutdown.
*/
void (* qc_process_end)(void);
/**
* Called once per each thread.
*
* @return QC_RESULT_OK, if the thread initialization succeeded.
*/
int32_t (* qc_thread_init)(void);
/**
* Called once when a thread finishes.
*/
void (* qc_thread_end)(void);
/**
* Called to explicitly parse a statement.
*
* @param stmt The statement to be parsed.
* @param collect A bitmask of @c qc_collect_info_t values. Specifies what information
* should be collected. Only a hint and must not restrict what information
* later can be queried.
* @param result On return, the parse result, if @c QC_RESULT_OK is returned.
*
* @return QC_RESULT_OK, if the parsing was not aborted due to resource
* exhaustion or equivalent.
*/
int32_t (* qc_parse)(GWBUF* stmt, uint32_t collect, int32_t* result);
/**
* Reports the type of the statement.
*
* @param stmt A COM_QUERY or COM_STMT_PREPARE packet.
* @param type On return, the type mask (combination of @c qc_query_type_t),
* if @c QC_RESULT_OK is returned.
*
* @return QC_RESULT_OK, if the parsing was not aborted due to resource
* exhaustion or equivalent.
*/
int32_t (* qc_get_type_mask)(GWBUF* stmt, uint32_t* type);
/**
* Reports the operation of the statement.
*
* @param stmt A COM_QUERY or COM_STMT_PREPARE packet.
* @param type On return, the operation (one of @c qc_query_op_t), if
* @c QC_RESULT_OK is returned.
*
* @return QC_RESULT_OK, if the parsing was not aborted due to resource
* exhaustion or equivalent.
*/
int32_t (* qc_get_operation)(GWBUF* stmt, int32_t* op);
/**
* Reports the name of a created table.
*
* @param stmt A COM_QUERY or COM_STMT_PREPARE packet.
* @param name On return, the name of the created table, if
* @c QC_RESULT_OK is returned.
*
* @return QC_RESULT_OK, if the parsing was not aborted due to resource
* exhaustion or equivalent.
*/
int32_t (* qc_get_created_table_name)(GWBUF* stmt, char** name);
/**
* Reports whether a statement is a "DROP TABLE ..." statement.
*
* @param stmt A COM_QUERY or COM_STMT_PREPARE packet
* @param is_drop_table On return, non-zero if the statement is a DROP TABLE
* statement, if @c QC_RESULT_OK is returned.
*
* @return QC_RESULT_OK, if the parsing was not aborted due to resource
* exhaustion or equivalent.
*/
int32_t (* qc_is_drop_table_query)(GWBUF* stmt, int32_t* is_drop_table);
/**
* Returns all table names.
*
* @param stmt A COM_QUERY or COM_STMT_PREPARE packet.
* @param fullnames If non-zero, the full (i.e. qualified) names are returned.
* @param names On return, the names of the statement, if @c QC_RESULT_OK
* is returned.
* @param n_names On return, how many names were returned, if @c QC_RESULT_OK
* is returned.
*
* @return QC_RESULT_OK, if the parsing was not aborted due to resource
* exhaustion or equivalent.
*/
int32_t (* qc_get_table_names)(GWBUF* stmt, int32_t full_names, char*** names, int32_t* n_names);
/**
* The canonical version of a statement.
*
* @param stmt A COM_QUERY or COM_STMT_PREPARE packet.
* @param canonical On return, the canonical version of the statement, if @c QC_RESULT_OK
* is returned.
*
* @return QC_RESULT_OK, if the parsing was not aborted due to resource
* exhaustion or equivalent.
*/
int32_t (* qc_get_canonical)(GWBUF* stmt, char** canonical);
/**
* Reports whether the statement has a where clause.
*
* @param stmt A COM_QUERY or COM_STMT_PREPARE packet.
* @param has_clause On return, non-zero if the statement has a where clause, if
* @c QC_RESULT_OK is returned.
*
* @return QC_RESULT_OK, if the parsing was not aborted due to resource
* exhaustion or equivalent.
*/
int32_t (* qc_query_has_clause)(GWBUF* stmt, int32_t* has_clause);
/**
* Reports the database names.
*
* @param stmt A COM_QUERY or COM_STMT_PREPARE packet.
* @param names On return, the database names, if
* @c QC_RESULT_OK is returned.
* @param size On return, the number of names in @names, if
* @c QC_RESULT_OK is returned.
*
* @return QC_RESULT_OK, if the parsing was not aborted due to resource
* exhaustion or equivalent.
*/
int32_t (* qc_get_database_names)(GWBUF* stmt, char*** names, int32_t* size);
/**
* Reports the prepare name.
*
* @param stmt A COM_QUERY or COM_STMT_PREPARE packet.
* @param name On return, the name of a prepare statement, if
* @c QC_RESULT_OK is returned.
*
* @return QC_RESULT_OK, if the parsing was not aborted due to resource
* exhaustion or equivalent.
*/
int32_t (* qc_get_prepare_name)(GWBUF* stmt, char** name);
/**
* Reports field information.
*
* @param stmt A COM_QUERY or COM_STMT_PREPARE packet.
* @param infos On return, array of field infos, if @c QC_RESULT_OK is returned.
* @param n_infos On return, the size of @c infos, if @c QC_RESULT_OK is returned.
*
* @return QC_RESULT_OK, if the parsing was not aborted due to resource
* exhaustion or equivalent.
*/
int32_t (* qc_get_field_info)(GWBUF* stmt, const QC_FIELD_INFO** infos, uint32_t* n_infos);
/**
* The canonical version of a statement.
*
* @param stmt A COM_QUERY or COM_STMT_PREPARE packet.
* @param infos On return, array of function infos, if @c QC_RESULT_OK is returned.
* @param n_infos On return, the size of @c infos, if @c QC_RESULT_OK is returned.
*
* @return QC_RESULT_OK, if the parsing was not aborted due to resource
* exhaustion or equivalent.
*/
int32_t (* qc_get_function_info)(GWBUF* stmt, const QC_FUNCTION_INFO** infos, uint32_t* n_infos);
/**
* Return the preparable statement of a PREPARE statement.
*
* @param stmt A COM_QUERY or COM_STMT_PREPARE packet.
* @param preparable_stmt On return, the preparable statement (provided @c stmt is a
* PREPARE statement), if @c QC_RESULT_OK is returned. Otherwise
* NULL.
*
* @attention The returned GWBUF is the property of @c stmt and will be deleted when
* @c stmt is. If the preparable statement need to be retained beyond the
* lifetime of @c stmt, it must be cloned.
*
* @return QC_RESULT_OK, if the parsing was not aborted due to resource
* exhaustion or equivalent.
*/
int32_t (* qc_get_preparable_stmt)(GWBUF* stmt, GWBUF** preparable_stmt);
/**
* Set the version of the server. The version may affect how a statement
* is classified. Note that the server version is maintained separately
* for each thread.
*
* @param version Version encoded as MariaDB encodes the version, i.e.:
* version = major * 10000 + minor * 100 + patch
*/
void (* qc_set_server_version)(uint64_t version);
/**
* Get the thread specific version assumed of the server. If the version has
* not been set, all values are 0.
*
* @param version The version encoded as MariaDB encodes the version, i.e.:
* version = major * 10000 + minor * 100 + patch
*/
void (* qc_get_server_version)(uint64_t* version);
/**
* Gets the sql mode of the *calling* thread.
*
* @param sql_mode The mode.
*
* @return QC_RESULT_OK
*/
int32_t (* qc_get_sql_mode)(qc_sql_mode_t* sql_mode);
/**
* Sets the sql mode for the *calling* thread.
*
* @param sql_mode The mode.
*
* @return QC_RESULT_OK if @sql_mode is valid, otherwise QC_RESULT_ERROR.
*/
int32_t (* qc_set_sql_mode)(qc_sql_mode_t sql_mode);
/**
* Dups the provided info object. After having been dupped, the info object
* can be stored on another GWBUF.
*
* @param info The info to be dupped.
*
* @return The same info that was provided as argument.
*/
QC_STMT_INFO* (*qc_info_dup)(QC_STMT_INFO * info);
/**
* Closes a dupped info object. After the info object has been closed, it must
* not be accessed.
*
* @param info The info to be closed.
*/
void (* qc_info_close)(QC_STMT_INFO* info);
/**
* Gets the options of the *calling* thread.
*
* @return Bit mask of values from qc_option_t.
*/
uint32_t (* qc_get_options)();
/**
* Sets the options for the *calling* thread.
*
* @param options Bits from qc_option_t.
*
* @return QC_RESULT_OK if @c options is valid, otherwise QC_RESULT_ERROR.
*/
int32_t (* qc_set_options)(uint32_t options);
} QUERY_CLASSIFIER;
/**
* QC_CACHE_PROPERTIES specifies the limits of the query classification cache.
*/
typedef struct QC_CACHE_PROPERTIES
{
int64_t max_size; /** The maximum size of the cache. */
} QC_CACHE_PROPERTIES;
/**
* QC_CACHE_STATS provides statistics of the cache.
*/
typedef struct QC_CACHE_STATS
{
int64_t size; /** The current size of the cache. */
int64_t inserts; /** The number of inserts. */
int64_t hits; /** The number of hits. */
int64_t misses; /** The number of misses. */
int64_t evictions; /** The number of evictions. */
} QC_CACHE_STATS;
/**
* Loads and sets up the default query classifier.
*
* This must be called once during the execution of a process. The query
* classifier functions can only be used if this function first and thereafter
* the @c qc_process_init return true.
*
* MaxScale calls this function, so plugins should not do that.
*
* @param cache_properties If non-NULL, specifies the properties of the QC cache.
* @param sql_mode The default sql mode.
* @param plugin_name The name of the plugin from which the query classifier
* should be loaded.
* @param plugin_args The arguments to be provided to the query classifier.
*
* @return True if the query classifier could be loaded and initialized,
* false otherwise.
*
* @see qc_process_init qc_thread_init
*/
bool qc_setup(const QC_CACHE_PROPERTIES* cache_properties,
qc_sql_mode_t sql_mode,
const char* plugin_name,
const char* plugin_args);
/**
* Loads and setups the default query classifier, and performs
* process and thread initialization.
*
* This is primary intended for making the setup of stand-alone
* test-programs simpler.
*
* @param cache_properties If non-NULL, specifies the properties of the QC cache.
* @param sql_mode The default sql mode.
* @param plugin_name The name of the plugin from which the query classifier
* should be loaded.
* @param plugin_args The arguments to be provided to the query classifier.
*
* @return True if the query classifier could be loaded and initialized,
* false otherwise.
*
* @see qc_end.
*/
bool qc_init(const QC_CACHE_PROPERTIES* cache_properties,
qc_sql_mode_t sql_mode,
const char* plugin_name,
const char* plugin_args);
/**
* Performs thread and process finalization.
*
* This is primary intended for making the tear-down of stand-alone
* test-programs simpler.
*/
void qc_end();
/**
* Intializes the query classifier.
*
* This function should be called once, provided @c qc_setup returned true,
* before the query classifier functionality is used.
*
* MaxScale calls this functions, so plugins should not do that.
*
* @param kind What kind of initialization should be performed.
* Combination of qc_init_kind_t.
*
* @return True, if the process wide initialization could be performed.
*
* @see qc_process_end qc_thread_init
*/
bool qc_process_init(uint32_t kind);
/**
* Finalizes the query classifier.
*
* A successful call of @c qc_process_init should before program exit be
* followed by a call to this function. MaxScale calls this function, so
* plugins should not do that.
*
* @param kind What kind of finalization should be performed.
* Combination of qc_init_kind_t.
*
* @see qc_process_init qc_thread_end
*/
void qc_process_end(uint32_t kind);
/**
* Loads a particular query classifier.
*
* In general there is no need to use this function, but rely upon qc_init().
* However, if there is a need to use multiple query classifiers concurrently
* then this function provides the means for that. Note that after a query
* classifier has been loaded, it must explicitly be initialized before it
* can be used.
*
* @param plugin_name The name of the plugin from which the query classifier
* should be loaded.
*
* @return A QUERY_CLASSIFIER object if successful, NULL otherwise.
*
* @see qc_unload
*/
QUERY_CLASSIFIER* qc_load(const char* plugin_name);
/**
* Unloads an explicitly loaded query classifier.
*
* @see qc_load
*/
void qc_unload(QUERY_CLASSIFIER* classifier);
/**
* Performs thread initialization needed by the query classifier. Should
* be called in every thread.
*
* MaxScale calls this function, so plugins should not do that.
*
* @param kind What kind of initialization should be performed.
* Combination of qc_init_kind_t.
*
* @return True if the initialization succeeded, false otherwise.
*
* @see qc_thread_end
*/
bool qc_thread_init(uint32_t kind);
/**
* Performs thread finalization needed by the query classifier.
* A successful call to @c qc_thread_init should at some point be
* followed by a call to this function.
*
* MaxScale calls this function, so plugins should not do that.
*
* @param kind What kind of finalization should be performed.
* Combination of qc_init_kind_t.
*
* @see qc_thread_init
*/
void qc_thread_end(uint32_t kind);
/**
* Parses the statement in the provided buffer and returns a value specifying
* to what extent the statement could be parsed.
*
* There is no need to call this function explicitly before calling any of
* the other functions; e.g. qc_get_type_mask(). When some particular property of
* a statement is asked for, the statement will be parsed if it has not been
* parsed yet. Also, if the statement in the provided buffer has been parsed
* already then this function will only return the result of that parsing;
* the statement will not be parsed again.
*
* @param stmt A buffer containing an COM_QUERY or COM_STMT_PREPARE packet.
* @param collect A bitmask of @c qc_collect_info_t values. Specifies what information
* should be collected.
*
* Note that this is merely a hint and does not restrict what
* information can be queried for. If necessary, the statement
* will transparently be reparsed.
*
* @return To what extent the statement could be parsed.
*/
qc_parse_result_t qc_parse(GWBUF* stmt, uint32_t collect);
/**
* Returns information about affected fields.
*
* @param stmt A buffer containing a COM_QUERY or COM_STMT_PREPARE packet.
* @param infos Pointer to pointer that after the call will point to an
* array of QC_FIELD_INFO:s.
* @param n_infos Pointer to size_t variable where the number of items
* in @c infos will be returned.
*
* @note The returned array belongs to the GWBUF and remains valid for as
* long as the GWBUF is valid. If the data is needed for longer than
* that, it must be copied.
*/
void qc_get_field_info(GWBUF* stmt, const QC_FIELD_INFO** infos, size_t* n_infos);
/**
* Returns information about function usage.
*
* @param stmt A buffer containing a COM_QUERY or COM_STMT_PREPARE packet.
* @param infos Pointer to pointer that after the call will point to an
* array of QC_FUNCTION_INFO:s.
* @param n_infos Pointer to size_t variable where the number of items
* in @c infos will be returned.
*
* @note The returned array belongs to the GWBUF and remains valid for as
* long as the GWBUF is valid. If the data is needed for longer than
* that, it must be copied.
*
* @note For each function, only the fields that any invocation of it directly
* accesses will be returned. For instance:
*
* select length(a), length(concat(b, length(a))) from t
*
* will for @length return the field @a and for @c concat the field @b.
*/
void qc_get_function_info(GWBUF* stmt, const QC_FUNCTION_INFO** infos, size_t* n_infos);
/**
* Returns the statement, with literals replaced with question marks.
*
* @param stmt A buffer containing a COM_QUERY or COM_STMT_PREPARE packet.
*
* @return A statement in its canonical form, or NULL if a memory
* allocation fails. The string must be freed by the caller.
*/
char* qc_get_canonical(GWBUF* stmt);
/**
* Returns the name of the created table.
*
* @param stmt A buffer containing a COM_QUERY or COM_STMT_PREPARE packet.
*
* @return The name of the created table or NULL if the statement
* does not create a table or a memory allocation failed.
* The string must be freed by the caller.
*/
char* qc_get_created_table_name(GWBUF* stmt);
/**
* Returns the databases accessed by the statement. Note that a
* possible default database is not returned.
*
* @param stmt A buffer containing a COM_QUERY or COM_STMT_PREPARE packet.
* @param size Pointer to integer where the number of databases
* is stored.
*
* @return Array of strings or NULL if a memory allocation fails.
*
* @note The returned array and the strings pointed to @b must be freed
* by the caller.
*/
char** qc_get_database_names(GWBUF* stmt, int* size);
/**
* Returns the operation of the statement.
*
* @param stmt A buffer containing a COM_QUERY or COM_STMT_PREPARE packet.
*
* @return The operation of the statement.
*/
qc_query_op_t qc_get_operation(GWBUF* stmt);
/**
* Returns the name of the prepared statement, if the statement
* is a PREPARE or EXECUTE statement.
*
* @param stmt A buffer containing a COM_QUERY or COM_STMT_PREPARE packet.
*
* @return The name of the prepared statement, if the statement
* is a PREPARE or EXECUTE statement; otherwise NULL.
*
* @note The returned string @b must be freed by the caller.
*
* @note Even though a COM_STMT_PREPARE can be given to the query
* classifier for parsing, this function will in that case
* return NULL since the id of the statement is provided by
* the server.
*/
char* qc_get_prepare_name(GWBUF* stmt);
/**
* Returns the preparable statement of a PREPARE statment. Other query classifier
* functions can then be used on the returned statement to find out information
* about the preparable statement. The returned @c GWBUF should not be used for
* anything else but for obtaining information about the preparable statement.
*
* @param stmt A buffer containing a COM_QUERY or COM_STMT_PREPARE packet.
*
* @return The preparable statement, if @stmt was a COM_QUERY PREPARE statement,
* or NULL.
*
* @attention If the packet was a COM_STMT_PREPARE, then this function will
* return NULL and the actual properties of the query can be obtained
* by calling any of the qc-functions directly on the GWBUF containing
* the COM_STMT_PREPARE. However, the type mask will contain the
* bit @c QUERY_TYPE_PREPARE_STMT.
*
* @attention The returned @c GWBUF is the property of @c stmt and will be
* deleted along with it.
*/
GWBUF* qc_get_preparable_stmt(GWBUF* stmt);
/**
* Gets the sql mode of the *calling* thread.
*
* @return The mode.
*/
qc_sql_mode_t qc_get_sql_mode();
/**
* Returns the tables accessed by the statement.
*
* @param stmt A buffer containing a COM_QUERY or COM_STMT_PREPARE packet.
* @param tblsize Pointer to integer where the number of tables is stored.
* @param fullnames If true, a table names will include the database name
* as well (if explicitly referred to in the statement).
*
* @return Array of strings or NULL if a memory allocation fails.
*
* @note The returned array and the strings pointed to @b must be freed
* by the caller.
*/
char** qc_get_table_names(GWBUF* stmt, int* size, bool fullnames);
/**
* Free tables returned by qc_get_table_names
*
* @param names List of names
* @param size Size of @c names
*/
void qc_free_table_names(char** names, int size);
/**
* Returns a bitmask specifying the type(s) of the statement. The result
* should be tested against specific qc_query_type_t values* using the
* bitwise & operator, never using the == operator.
*
* @param stmt A buffer containing a COM_QUERY or COM_STMT_PREPARE packet.
*
* @return A bitmask with the type(s) the query.
*
* @see qc_query_is_type
*/
uint32_t qc_get_type_mask(GWBUF* stmt);
/**
* Returns the type bitmask of transaction related statements.
*
* If the statement starts a transaction, ends a transaction or
* changes the autocommit state, the returned bitmap will be a
* combination of:
*
* QUERY_TYPE_BEGIN_TRX
* QUERY_TYPE_COMMIT
* QUERY_TYPE_ROLLBACK
* QUERY_TYPE_ENABLE_AUTOCOMMIT
* QUERY_TYPE_DISABLE_AUTOCOMMIT
* QUERY_TYPE_READ (explicitly read only transaction)
* QUERY_TYPE_WRITE (explicitly read write transaction)
*
* Otherwise the result will be 0.
*
* @param stmt A COM_QUERY or COM_STMT_PREPARE packet.
*
* @return The relevant type bits if the statement is transaction
* related, otherwise 0.
*/
uint32_t qc_get_trx_type_mask(GWBUF* stmt);
/**
* Returns whether the statement is a DROP TABLE statement.
*
* @param stmt A buffer containing a COM_QUERY or COM_STMT_PREPARE packet.
*
* @return True if the statement is a DROP TABLE statement, false otherwise.
*
* @todo This function is far too specific.
*/
bool qc_is_drop_table_query(GWBUF* stmt);
/**
* Returns the string representation of a query operation.
*
* @param op A query operation.
*
* @return The corresponding string.
*
* @note The returned string is statically allocated and must *not* be freed.
*/
const char* qc_op_to_string(qc_query_op_t op);
/**
* Returns whether the typemask contains a particular type.
*
* @param typemask A bitmask of query types.
* @param type A particular qc_query_type_t value.
*
* @return True, if the type is in the mask.
*/
static inline bool qc_query_is_type(uint32_t typemask, qc_query_type_t type)
{
return (typemask & (uint32_t)type) == (uint32_t)type;
}
/**
* Returns whether the statement has a WHERE or a USING clause.
*
* @param stmt A buffer containing a COM_QUERY or COM_STMT_PREPARE packet.
*
* @return True, if the statement has a WHERE or USING clause, false
* otherwise.
*/
bool qc_query_has_clause(GWBUF* stmt);
/**
* Sets the sql mode for the *calling* thread.
*
* @param sql_mode The mode.
*/
void qc_set_sql_mode(qc_sql_mode_t sql_mode);
/**
* Returns the string representation of a query type.
*
* @param type A query type (not a bitmask of several).
*
* @return The corresponding string.
*
* @note The returned string is statically allocated and must @b not be freed.
*/
const char* qc_type_to_string(qc_query_type_t type);
/**
* Returns a string representation of a type bitmask.
*
* @param typemask A bit mask of query types.
*
* @return The corresponding string or NULL if the allocation fails.
*
* @note The returned string is dynamically allocated and @b must be freed.
*/
char* qc_typemask_to_string(uint32_t typemask);
/**
* Set the version of the server. The version may affect how a statement
* is classified. Note that the server version is maintained separately
* for each thread.
*
* @param version Version encoded as MariaDB encodes the version, i.e.:
* version = major * 10000 + minor * 100 + patch
*/
void qc_set_server_version(uint64_t version);
/**
* Get the thread specific version assumed of the server. If the version has
* not been set, all values are 0.
*
* @return The version as MariaDB encodes the version, i.e:
* version = major * 10000 + minor * 100 + patch
*/
uint64_t qc_get_server_version();
/**
* Get the cache properties.
*
* @param[out] properties Cache properties.
*/
void qc_get_cache_properties(QC_CACHE_PROPERTIES* properties);
/**
* Set the cache properties.
*
* @param properties Cache properties.
*
* @return True, if the properties could be set, false if at least
* one property is invalid or if the combination of property
* values is invalid.
*/
bool qc_set_cache_properties(const QC_CACHE_PROPERTIES* properties);
/**
* Get cache statistics for the calling thread.
*
* @param stats[out] Cache statistics.
*
* @return True, if caching is enabled, false otherwise.
*/
bool qc_get_cache_stats(QC_CACHE_STATS* stats);
/**
* Get cache statistics for the calling thread.
*
* @return An object if caching is enabled, NULL otherwise.
*/
json_t* qc_get_cache_stats_as_json();
/**
* String represenation for the parse result.
*
* @param result A parsing result.
*
* @return The corresponding string.
*/
const char* qc_result_to_string(qc_parse_result_t result);
/**
* Gets the options of the *calling* thread.
*
* @return Bit mask of values from qc_option_t.
*/
uint32_t qc_get_options();
/**
* Sets the options for the *calling* thread.
*
* @param options Bits from qc_option_t.
*
* @return true if the options were valid, false otherwise.
*/
bool qc_set_options(uint32_t options);
MXS_END_DECLS
| 34.341341 | 109 | 0.676801 | [
"object"
] |
6ce2570ad86c335a584bbea5a34fdeedb8bc7e23 | 4,158 | h | C | Universal-Physics-mod/src/client/GameSave.h | AllSafeCyberSecur1ty/Nuclear-Engineering | 302d6dcc7c0a85a9191098366b076cf9cb5a9f6e | [
"MIT"
] | 1 | 2022-03-26T20:01:13.000Z | 2022-03-26T20:01:13.000Z | Universal-Physics-mod/src/client/GameSave.h | AllSafeCyberSecur1ty/Nuclear-Engineering | 302d6dcc7c0a85a9191098366b076cf9cb5a9f6e | [
"MIT"
] | null | null | null | Universal-Physics-mod/src/client/GameSave.h | AllSafeCyberSecur1ty/Nuclear-Engineering | 302d6dcc7c0a85a9191098366b076cf9cb5a9f6e | [
"MIT"
] | 1 | 2022-03-26T19:59:13.000Z | 2022-03-26T19:59:13.000Z | #ifndef The_Powder_Toy_GameSave_h
#define The_Powder_Toy_GameSave_h
#include "Config.h"
#include <vector>
#include "common/String.h"
#include "Misc.h"
#include "bson/BSON.h"
#include "json/json.h"
struct sign;
struct Particle;
struct ParseException: public std::exception {
enum ParseResult { OK = 0, Corrupt, WrongVersion, InvalidDimensions, InternalError, MissingElement };
ByteString message;
ParseResult result;
public:
ParseException(ParseResult result, String message): message(message.ToUtf8()), result(result) {}
const char * what() const throw() override
{
return message.c_str();
}
~ParseException() throw() {}
};
struct BuildException: public std::exception {
ByteString message;
public:
BuildException(String message): message(message.ToUtf8()) {}
const char * what() const throw() override
{
return message.c_str();
}
~BuildException() throw() {}
};
class StkmData
{
public:
bool rocketBoots1 = false;
bool rocketBoots2 = false;
bool fan1 = false;
bool fan2 = false;
std::vector<unsigned int> rocketBootsFigh = std::vector<unsigned int>();
std::vector<unsigned int> fanFigh = std::vector<unsigned int>();
StkmData() = default;
StkmData(const StkmData & stkmData):
rocketBoots1(stkmData.rocketBoots1),
rocketBoots2(stkmData.rocketBoots2),
fan1(stkmData.fan1),
fan2(stkmData.fan2),
rocketBootsFigh(stkmData.rocketBootsFigh),
fanFigh(stkmData.fanFigh)
{
}
bool hasData()
{
return rocketBoots1 || rocketBoots2 || fan1 || fan2
|| rocketBootsFigh.size() || fanFigh.size();
}
};
class GameSave
{
public:
int blockWidth, blockHeight;
bool fromNewerVersion;
int majorVersion, minorVersion;
bool hasPressure;
bool hasAmbientHeat;
//Simulation data
//int ** particleMap;
int particlesCount;
Particle * particles;
unsigned char ** blockMap;
float ** fanVelX;
float ** fanVelY;
float ** pressure;
float ** velocityX;
float ** velocityY;
float ** ambientHeat;
//Simulation Options
bool waterEEnabled;
bool legacyEnable;
bool gravityEnable;
bool aheatEnable;
bool NoWeightSwitch;
bool BetterBurningEnable;
bool paused;
int gravityMode;
int airMode;
int edgeMode;
//Signs
std::vector<sign> signs;
StkmData stkm;
//Element palette
typedef std::pair<ByteString, int> PaletteItem;
std::vector<PaletteItem> palette;
// author information
Json::Value authors;
int pmapbits;
GameSave();
GameSave(GameSave & save);
GameSave(int width, int height);
GameSave(char * data, int dataSize);
GameSave(std::vector<char> data);
GameSave(std::vector<unsigned char> data);
~GameSave();
void setSize(int width, int height);
char * Serialise(unsigned int & dataSize);
std::vector<char> Serialise();
vector2d Translate(vector2d translate);
void Transform(matrix2d transform, vector2d translate);
void Transform(matrix2d transform, vector2d translate, vector2d translateReal, int newWidth, int newHeight);
void Expand();
void Collapse();
bool Collapsed();
static bool TypeInCtype(int type, int ctype);
static bool TypeInTmp(int type);
static bool TypeInTmp2(int type, int tmp2);
GameSave& operator << (Particle &v);
GameSave& operator << (sign &v);
private:
bool expanded;
bool hasOriginalData;
// number of pixels translated. When translating CELL pixels, shift all CELL grids
vector2d translated;
std::vector<char> originalData;
void InitData();
void InitVars();
void CheckBsonFieldUser(bson_iterator iter, const char *field, unsigned char **data, unsigned int *fieldLen);
void CheckBsonFieldBool(bson_iterator iter, const char *field, bool *flag);
void CheckBsonFieldInt(bson_iterator iter, const char *field, int *setting);
template <typename T> T ** Allocate2DArray(int blockWidth, int blockHeight, T defaultVal);
template <typename T> void Deallocate2DArray(T ***array, int blockHeight);
void dealloc();
void read(char * data, int dataSize);
void readOPS(char * data, int dataLength);
void readPSv(char * data, int dataLength);
char * serialiseOPS(unsigned int & dataSize);
void ConvertJsonToBson(bson *b, Json::Value j, int depth = 0);
void ConvertBsonToJson(bson_iterator *b, Json::Value *j, int depth = 0);
};
#endif
| 25.048193 | 110 | 0.737133 | [
"vector",
"transform"
] |
6ce63f71bc1ae36158b434dd2843601924e7cce2 | 1,912 | h | C | include/math/Statistics.h | sbowman-mitre/FMACM | 510e8c23291425c56a387fadf4ba2b41a07e094d | [
"Apache-2.0"
] | null | null | null | include/math/Statistics.h | sbowman-mitre/FMACM | 510e8c23291425c56a387fadf4ba2b41a07e094d | [
"Apache-2.0"
] | null | null | null | include/math/Statistics.h | sbowman-mitre/FMACM | 510e8c23291425c56a387fadf4ba2b41a07e094d | [
"Apache-2.0"
] | null | null | null | // ****************************************************************************
// NOTICE
//
// This is the copyright work of The MITRE Corporation, and was produced
// for the U. S. Government under Contract Number DTFAWA-10-C-00080, and
// is subject to Federal Aviation Administration Acquisition Management
// System Clause 3.5-13, Rights In Data-General, Alt. III and Alt. IV
// (Oct. 1996). No other use other than that granted to the U. S.
// Government, or to those acting on behalf of the U. S. Government,
// under that Clause is authorized without the express written
// permission of The MITRE Corporation. For further information, please
// contact The MITRE Corporation, Contracts Office, 7515 Colshire Drive,
// McLean, VA 22102-7539, (703) 983-6000.
//
// Copyright 2018 The MITRE Corporation. All Rights Reserved.
// ****************************************************************************
#pragma once
/*
When you use this class you must specify both the type of the data you will be putting into it and the type you get when you multiply to objects of that type.
For instance you could instantiate it with double, double
Or Distance, Area
*/
#include <vector>
using std::vector;
class Statistics
{
public:
Statistics(void);
~Statistics(void);
virtual void insert(double value);
double get_std()const;
inline double get_mean()const
{
return s1 / samples.size();
}
inline long get_number_of_samples()const
{
return samples.size();
}
inline double get_max()const
{
return max;
}
inline double get_min()const
{
return min;
}
//gwang 2013-11-08
//input: pct is the percent (0 <= pct <= 1)
double get_percentile(double pct);
double get_bound95();
private:
double s1; // sum of all values seen so far
vector<double> samples;
double max; // private data members
double min; // private data members
};
| 27.314286 | 159 | 0.649059 | [
"vector"
] |
6ce8a90989dd3767f6801f1b02c079e654efeb59 | 1,971 | h | C | private/inet/mshtml/imgfilt/wmffilt/cwmffilt.h | King0987654/windows2000 | 01f9c2e62c4289194e33244aade34b7d19e7c9b8 | [
"MIT"
] | 11 | 2017-09-02T11:27:08.000Z | 2022-01-02T15:25:24.000Z | private/inet/mshtml/imgfilt/wmffilt/cwmffilt.h | King0987654/windows2000 | 01f9c2e62c4289194e33244aade34b7d19e7c9b8 | [
"MIT"
] | null | null | null | private/inet/mshtml/imgfilt/wmffilt/cwmffilt.h | King0987654/windows2000 | 01f9c2e62c4289194e33244aade34b7d19e7c9b8 | [
"MIT"
] | 14 | 2019-01-16T01:01:23.000Z | 2022-02-20T15:54:27.000Z | // CWMFFilter.H : Declaration of the CWMFFilter
#pragma pack( push, WMF )
#pragma pack( 1 )
typedef struct tagSRECT
{
short left;
short top;
short right;
short bottom;
} SRECT;
typedef struct
{
DWORD key;
WORD hmf;
SRECT bbox;
WORD inch;
DWORD reserved;
WORD checksum;
} ALDUSMFHEADER;
#pragma pack( pop, WMF )
const DWORD ALDUSKEY = 0x9AC6CDD7;
/////////////////////////////////////////////////////////////////////////////
// WMFFilter
class CWMFFilter :
public IImageDecodeFilter,
public CComObjectRoot,
public CComCoClass< CWMFFilter,&CLSID_CoWMFFilter >
{
public:
CWMFFilter();
~CWMFFilter();
BEGIN_COM_MAP( CWMFFilter )
COM_INTERFACE_ENTRY( IImageDecodeFilter )
END_COM_MAP()
DECLARE_NOT_AGGREGATABLE( CWMFFilter )
// Remove the comment from the line above if you don't want your object to
// support aggregation. The default is to support it
DECLARE_REGISTRY( CWMFFilter, _T( "WMFFilter.CoWMFFilter.1" ),
_T( "WMFFilter.CoWMFFilter" ), IDS_COWMFFILTER_DESC, THREADFLAGS_BOTH )
// DECLARE_NO_REGISTRY()
// IImageDecodeFilter
public:
STDMETHOD( Initialize )( IImageDecodeEventSink* pEventSink );
STDMETHOD( Process )( IStream* pStream );
STDMETHOD( Terminate )( HRESULT hrStatus );
protected:
HRESULT FireGetSurfaceEvent();
HRESULT FireOnBeginDecodeEvent();
HRESULT FireOnBitsCompleteEvent();
HRESULT FireOnProgressEvent();
HRESULT GetColors();
HRESULT ReadImage();
HRESULT LockBits(RECT *prcBounds, DWORD dwLockFlags, void **ppBits, long *pPitch);
HRESULT UnlockBits(RECT *prcBounds, void *pBits);
protected:
IStream* m_pStream;
CComPtr< IImageDecodeEventSink > m_pEventSink;
CComPtr< IDirectDrawSurface > m_pDDrawSurface;
RGBQUAD m_argbPalette[256];
ULONG m_nColors;
DWORD m_dwEvents;
ULONG m_nWidth;
ULONG m_nHeight;
LONG m_lTrans;
};
| 24.333333 | 87 | 0.665145 | [
"object"
] |
6cef234d95b6e7b95ed5b5041fde4f16925338eb | 14,368 | h | C | include/locationList.h | khbence/pansim | 6920545d07122c8bcbff33ef1a38bc109b1e9a3f | [
"CC-BY-4.0"
] | 4 | 2021-05-22T17:25:50.000Z | 2022-01-05T11:32:06.000Z | include/locationList.h | khbence/pansim | 6920545d07122c8bcbff33ef1a38bc109b1e9a3f | [
"CC-BY-4.0"
] | null | null | null | include/locationList.h | khbence/pansim | 6920545d07122c8bcbff33ef1a38bc109b1e9a3f | [
"CC-BY-4.0"
] | null | null | null | #pragma once
#include <vector>
#include "globalStates.h"
#include "agent.h"
#include <cmath>
#include <algorithm>
#include <random>
#include "randomGenerator.h"
#include "statistics.h"
#include "datatypes.h"
#include "timing.h"
#include "util.h"
#include <string>
#include "locationTypesFormat.h"
#include <map>
#include "locationsFormat.h"
#include "customExceptions.h"
#include "timeHandler.h"
#include <cxxopts.hpp>
template<typename SimulationType>
class LocationsList {
using AgentType = Agent<typename SimulationType::AgentListType>;
using PositionType = typename SimulationType::PositionType_t;
using TypeOfLocation = typename SimulationType::TypeOfLocation_t;
Statistic<typename SimulationType::PPState_t, AgentType> globalStats;
LocationsList() = default;
void reserve(std::size_t s) {
position.reserve(s);
locType.reserve(s);
areas.reserve(s);
capacity.reserve(s);
states.reserve(s);
quarantineUntil.reserve(s);
closedUntil.reserve(s);
essential.reserve(s);
}
public:
// the following vectors are the input data for locations in separated
// vectors
thrust::device_vector<TypeOfLocation> locType;
thrust::device_vector<PositionType> position;
thrust::device_vector<double> infectiousness;
thrust::device_vector<unsigned> areas;
thrust::device_vector<unsigned> capacity;
thrust::device_vector<bool> states;// Closed/open or ON/OFF
thrust::device_vector<unsigned> quarantineUntil;
thrust::device_vector<unsigned> closedUntil;
thrust::device_vector<unsigned> schools;
thrust::device_vector<unsigned> classrooms;
thrust::device_vector<unsigned> classroomOffsets;
thrust::device_vector<uint8_t> essential;
// indices of agents sorted by location, and sorted by agent index
thrust::device_vector<unsigned> locationAgentList;
// indices of locations of the agents sorted
// by location, and sorted by agent index
thrust::device_vector<unsigned> locationIdsOfAgents;
// into locationAgentList
thrust::device_vector<unsigned> locationListOffsets;
std::map<unsigned, std::string> generalLocationTypes;
unsigned tracked;
[[nodiscard]] static LocationsList* getInstance() {
static LocationsList instance;
return &instance;
}
void initLocationTypes(const parser::LocationTypes& inputData) {
for (auto& type : inputData.types) { generalLocationTypes.emplace(std::make_pair(type.ID, std::move(type.name))); }
unsigned cemeteryTypeID = generalLocationTypes.rbegin()->first + 1;
generalLocationTypes.emplace(std::make_pair(cemeteryTypeID, "cemetery"));
}
void initializeArgs(const cxxopts::ParseResult& result) {
try {
tracked = result["trace"].as<unsigned>();
} catch (std::exception& e) { tracked = std::numeric_limits<unsigned>::max(); }
}
[[nodiscard]] std::pair<unsigned, std::map<std::string, unsigned>> initLocations(const parser::Locations& inputData,
const parser::LocationTypes& locTypes) {
// For the runtime performance, it would be better, that the IDs of the
// locations would be the same as their indexes, but we can not ensure
// it in the input file, so I create this mapping, that will be used by
// the agents when I fill them up. Use it only during initialization ID
// from files -> index in vectors
std::map<std::string, unsigned> IDMapping{};
thrust::host_vector<TypeOfLocation> locType_h;
thrust::host_vector<PositionType> position_h;
thrust::host_vector<double> infectiousness_h;
thrust::host_vector<unsigned> areas_h;
thrust::host_vector<bool> states_h;
thrust::host_vector<unsigned> capacity_h;
thrust::host_vector<uint8_t> essential_h;
thrust::host_vector<unsigned> quarantineUntil_h;
auto s = inputData.places.size() + 1;//+1 because of the cemetery
locType_h.reserve(s);
position_h.reserve(s);
infectiousness_h.reserve(s);
areas_h.reserve(s);
states_h.reserve(s);
capacity_h.reserve(s);
essential_h.reserve(s);
quarantineUntil_h.reserve(s);
thrust::host_vector<unsigned> schools_h;
thrust::host_vector<std::string> schoolIDs_h;
thrust::host_vector<unsigned> classrooms_h;
thrust::host_vector<std::string> classroomsIDs_h;
thrust::host_vector<unsigned> classroomOffsets_h;
reserve(s);
unsigned idx = 0;
for (unsigned i = 0; i < inputData.places.size(); i++) {
const auto& loc = inputData.places[i];
auto it = IDMapping.find(loc.ID);
if (it != IDMapping.end()) {
if (loc.type != locType_h[it->second])
printf("Location with ID %s already exists with mismatching type %d and %d\n",
loc.ID.c_str(),
loc.type,
locType_h[it->second]);
// continue;
}
IDMapping.emplace(loc.ID, idx);
locType_h.push_back(loc.type);
position_h.push_back(PositionType{ loc.coordinates[0], loc.coordinates[1] });
// if (loc.type == locTypes.hospital)
// infectiousness_h.push_back(0.1);
// else
infectiousness_h.push_back(loc.infectious);
capacity_h.push_back(loc.capacity);
essential_h.push_back(loc.essential);
areas_h.push_back(loc.area);
quarantineUntil_h.push_back(0);
if (loc.type == locTypes.classroom) {
classrooms_h.push_back(idx);
classroomsIDs_h.push_back(loc.ID);
}
if (loc.type == locTypes.school) {
schools_h.push_back(idx);
schoolIDs_h.push_back(loc.ID);
}
// Transform to upper case, to make it case insensitive
std::string tmp = loc.state;
std::for_each(tmp.begin(), tmp.end(), [](char c) { return std::toupper(c); });
if (tmp == "ON" || tmp == "OPEN") {
states_h.push_back(true);
} else if (tmp == "OFF" || tmp == "CLOSED") {
states_h.push_back(false);
} else {
throw IOLocations::WrongState(loc.state);
}
idx++;
}
// adding cemetery
locType_h.push_back(generalLocationTypes.rbegin()->first);
position_h.push_back(PositionType{ 0, 0 });
infectiousness_h.push_back(0.0);
areas_h.push_back(std::numeric_limits<unsigned>::max());
states_h.push_back(true);
capacity_h.push_back(std::numeric_limits<unsigned>::max());
essential_h.push_back(1);
// classroom-school pairings
thrust::host_vector<unsigned> schoolIdForClassroom(classrooms_h.size());
for (unsigned i = 0; i < classrooms_h.size(); i++) {
const std::string& s = classroomsIDs_h[i];
size_t pos = s.find("_");
if (pos != std::string::npos) {
std::string schoolid = s.substr(pos + 1);
auto it = IDMapping.find(schoolid);
if (it != IDMapping.end()) {
schoolIdForClassroom[i] = it->second;
} else
throw CustomErrors(
"classroom id does not have class_school structure: " + s + " school ID not found " + schoolid);
} else
throw CustomErrors("classroom id does not have class_school structure " + s);
}
thrust::stable_sort_by_key(schoolIdForClassroom.begin(), schoolIdForClassroom.end(), classrooms_h.begin());
for (unsigned i = 0; i < schools_h.size(); i++) {
auto it = thrust::find(schoolIdForClassroom.begin(), schoolIdForClassroom.end(), schools_h[i]);
if (it != schoolIdForClassroom.end())
classroomOffsets_h.push_back(thrust::distance(schoolIdForClassroom.begin(), it));
else {
// printf("School %d (%s) has no classrooms\n", schools_h[i], schoolIDs_h[i].c_str());
if (classroomOffsets_h.size() == 0) classroomOffsets_h.push_back(0);
classroomOffsets_h.push_back(classroomOffsets_h[classroomOffsets_h.size() - 1]);
}
}
classroomOffsets_h.push_back(schoolIdForClassroom.size());
// TODO: do not quarantine loc if already quarantined
schools = schools_h;
classrooms = classrooms_h;
classroomOffsets = classroomOffsets_h;
locType = locType_h;
position = position_h;
infectiousness = infectiousness_h;
areas = areas_h;
states = states_h;
capacity = capacity_h;
essential = essential_h;
quarantineUntil = quarantineUntil_h;
closedUntil.resize(capacity.size());
thrust::fill(closedUntil.begin(), closedUntil.end(), 0);
return std::make_pair(locType.size() - 1, IDMapping);
}
void initialize() {
auto agents = SimulationType::AgentListType::getInstance();
locationAgentList.resize(agents->location.size());
locationIdsOfAgents.resize(agents->location.size());
locationListOffsets.resize(position.size() + 1);
Util::updatePerLocationAgentLists(agents->location, locationIdsOfAgents, locationAgentList, locationListOffsets);
}
// TODO optimise randoms for performance
static void infectAgents(thrust::device_vector<double>& infectionRatioAtLocations,
thrust::device_vector<unsigned>& agentLocations,
thrust::device_vector<bool>& infectionAtLocation,
thrust::device_vector<unsigned>& newlyInfectedAgents,
bool flagInfectionsAtLocation,
Timehandler& simTime,
uint8_t variant) {
// PROFILE_FUNCTION();
auto& ppstates = SimulationType::AgentListType::getInstance()->PPValues;
auto& agentStats = SimulationType::AgentListType::getInstance()->agentStats;
unsigned timestamp = simTime.getTimestamp();
unsigned tracked2 = getInstance()->tracked;
unsigned hour = simTime.getMinutes() / 60;
// DEBUG unsigned count1 =
// thrust::count_if(ppstates.begin(),ppstates.end(), [](auto &ppstate)
// {return ppstate.getSIRD() == states::SIRD::I;}); DESC: for (int i =
// 0; i < number_of_agents; i++) {ppstate = ppstates[i]; infectionRatio
// = infectionRatioAtLocations[agentLocations[i]];...}
thrust::for_each(thrust::make_zip_iterator(thrust::make_tuple(ppstates.begin(),
thrust::make_permutation_iterator(infectionRatioAtLocations.begin(), agentLocations.begin()),
thrust::make_permutation_iterator(getInstance()->locType.begin(), agentLocations.begin()),
agentStats.begin(),
agentLocations.begin(),
thrust::make_counting_iterator<unsigned>(0),
thrust::make_permutation_iterator(infectionAtLocation.begin(), agentLocations.begin()),
newlyInfectedAgents.begin())),
thrust::make_zip_iterator(thrust::make_tuple(ppstates.end(),
thrust::make_permutation_iterator(infectionRatioAtLocations.begin(), agentLocations.end()),
thrust::make_permutation_iterator(getInstance()->locType.begin(), agentLocations.end()),
agentStats.end(),
agentLocations.end(),
thrust::make_counting_iterator<unsigned>(0) + ppstates.size(),
thrust::make_permutation_iterator(infectionAtLocation.begin(), agentLocations.end()),
newlyInfectedAgents.begin() + ppstates.size())),
[timestamp, tracked2, flagInfectionsAtLocation, variant] HD(thrust::tuple<typename SimulationType::PPState_t&,
double&,
TypeOfLocation&,
AgentStats&,
unsigned&,
unsigned,
bool&,
unsigned&> tuple) {
auto& ppstate = thrust::get<0>(tuple);
double& infectionRatio = thrust::get<1>(tuple);
TypeOfLocation& locType = thrust::get<2>(tuple);
auto& agentStat = thrust::get<3>(tuple);
unsigned& agentLocation = thrust::get<4>(tuple);
unsigned agentID = thrust::get<5>(tuple);
bool& infectionAtLocation = thrust::get<6>(tuple);
unsigned& newlyInfectedAgent = thrust::get<7>(tuple);
if (ppstate.getSusceptible(variant) > 0.0f
&& RandomGenerator::randomUnit() < infectionRatio * ppstate.getSusceptible(variant)) {
ppstate.gotInfected(variant);
agentStat.infectedTimestamp = timestamp;
agentStat.infectedCount++;
agentStat.infectedLocation = agentLocation;
agentStat.worstState = ppstate.getStateIdx();
agentStat.worstStateTimestamp = timestamp;
agentStat.variant = variant;
if (flagInfectionsAtLocation) {
infectionAtLocation = true;
newlyInfectedAgent = 1;
}
if (agentID == tracked2) {
printf("Agent %d got infected with variant %d at location %d of type %d at timestamp %d\n",
agentID,
variant,
agentLocation,
locType,
timestamp);
}
}
});
// DEBUG unsigned count2 =
// thrust::count_if(ppstates.begin(),ppstates.end(), [](auto &ppstate)
// {return ppstate.getSIRD() == states::SIRD::I;}); DEBUG std::cout <<
// count1 << " " << count2 << std::endl;
}
const auto& refreshAndGetStatistic() {
std::pair<unsigned, unsigned> agents{ locationListOffsets[0], locationListOffsets.back() };
return globalStats.refreshandGetAfterMidnight(agents, locationAgentList);
}
};
| 45.324921 | 123 | 0.606626 | [
"vector",
"transform"
] |
6cf7fe7a5e637569fd637ea70b06c645ac6f2740 | 1,496 | h | C | source/math_lib/line_3d.h | diegoarjz/selector | 976abd0d9e721639e6314e2599ef7e6f3dafdc4f | [
"MIT"
] | 12 | 2019-04-16T17:35:53.000Z | 2020-04-12T14:37:27.000Z | source/math_lib/line_3d.h | diegoarjz/selector | 976abd0d9e721639e6314e2599ef7e6f3dafdc4f | [
"MIT"
] | 47 | 2019-05-27T15:24:43.000Z | 2020-04-27T17:54:54.000Z | source/math_lib/line_3d.h | diegoarjz/selector | 976abd0d9e721639e6314e2599ef7e6f3dafdc4f | [
"MIT"
] | null | null | null | #ifndef PAGODA_MATH_LIB_LINE_3D_H_
#define PAGODA_MATH_LIB_LINE_3D_H_
#include "vec_base.h"
#include <boost/qvm/vec.hpp>
#include <boost/qvm/vec_operations.hpp>
namespace pagoda
{
template<class Rep>
class Line3D
{
public:
using VectorType = boost::qvm::vec<Rep, 3>;
/**
* Constructs and returns a \c Line3D going through \p p1 and \p p2 and has the
* normalized direction ||(\p p2 - \p p1)||
*/
static Line3D<Rep> FromTwoPoints(const VectorType& p1, const VectorType& p2)
{
return Line3D<Rep>(p1, boost::qvm::normalized(p2 - p1));
}
/**
* Constructs the x axis.
*/
Line3D() : m_point{0, 0, 0}, m_direction{1, 0, 0} {}
/**
* Constructs the 3D line going through the \p point and with the \p normalizedDirection direction.
*/
Line3D(const VectorType& point, const VectorType& normalizedDirection)
: m_point(point), m_direction(normalizedDirection)
{
}
/**
* Returns a point this line goes through.
*/
const VectorType& GetPoint() const { return m_point; }
/**
* Returns the normalized direction of this line.
*/
const VectorType& GetSupportVector() const { return m_direction; }
bool operator==(const Line3D<Rep>& other) const
{
return m_point == other.m_point && m_direction == other.m_direction;
}
bool operator!=(const Line3D<Rep>& other) const { return !(*this == other); }
private:
VectorType m_point; ///< A point in this line
VectorType m_direction; ///< The line's normalized direction
};
} // namespace pagoda
#endif
| 23.746032 | 100 | 0.692513 | [
"3d"
] |
9f017e56a061c11e1c341a090e2456d60ef54a09 | 325,514 | h | C | include/cuda-11.3/cusparse.h | dgSPARSE/dgSPARSE-Wrapper | d1aa92db1598487a13099388251f522b51cee0f0 | [
"Apache-2.0"
] | 7 | 2021-07-01T13:22:12.000Z | 2021-07-06T06:44:37.000Z | include/cuda-11.3/cusparse.h | dgSPARSE/dgSPARSE-Wrapper | d1aa92db1598487a13099388251f522b51cee0f0 | [
"Apache-2.0"
] | null | null | null | include/cuda-11.3/cusparse.h | dgSPARSE/dgSPARSE-Wrapper | d1aa92db1598487a13099388251f522b51cee0f0 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 1993-2020 NVIDIA Corporation. All rights reserved.
*
* NOTICE TO LICENSEE:
*
* This source code and/or documentation ("Licensed Deliverables") are
* subject to NVIDIA intellectual property rights under U.S. and
* international Copyright laws.
*
* These Licensed Deliverables contained herein is PROPRIETARY and
* CONFIDENTIAL to NVIDIA and is being provided under the terms and
* conditions of a form of NVIDIA software license agreement by and
* between NVIDIA and Licensee ("License Agreement") or electronically
* accepted by Licensee. Notwithstanding any terms or conditions to
* the contrary in the License Agreement, reproduction or disclosure
* of the Licensed Deliverables to any third party without the express
* written consent of NVIDIA is prohibited.
*
* NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE
* LICENSE AGREEMENT, NVIDIA MAKES NO REPRESENTATION ABOUT THE
* SUITABILITY OF THESE LICENSED DELIVERABLES FOR ANY PURPOSE. IT IS
* PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY OF ANY KIND.
* NVIDIA DISCLAIMS ALL WARRANTIES WITH REGARD TO THESE LICENSED
* DELIVERABLES, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY,
* NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE.
* NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE
* LICENSE AGREEMENT, IN NO EVENT SHALL NVIDIA BE LIABLE FOR ANY
* SPECIAL, INDIRECT, INCIDENTAL, 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 THESE LICENSED DELIVERABLES.
*
* U.S. Government End Users. These Licensed Deliverables are a
* "commercial item" as that term is defined at 48 C.F.R. 2.101 (OCT
* 1995), consisting of "commercial computer software" and "commercial
* computer software documentation" as such terms are used in 48
* C.F.R. 12.212 (SEPT 1995) and is provided to the U.S. Government
* only as a commercial end item. Consistent with 48 C.F.R.12.212 and
* 48 C.F.R. 227.7202-1 through 227.7202-4 (JUNE 1995), all
* U.S. Government End Users acquire the Licensed Deliverables with
* only those rights set forth herein.
*
* Any use of the Licensed Deliverables in individual and commercial
* software must include, in the user documentation and internal
* comments to the code, the above Disclaimer and U.S. Government End
* Users Notice.
*/
#if !defined(CUSPARSE_H_)
#define CUSPARSE_H_
#include "cuda-11.3/cuComplex.h"
#include "cuda-11.3/cuda_fp16.h"
#include "cuda-11.3/driver_types.h"
#include "cuda-11.3/library_types.h"
#include <stdint.h>
//##############################################################################
//# CUSPARSE VERSION INFORMATION
//##############################################################################
#define CUSPARSE_VER_MAJOR 11
#define CUSPARSE_VER_MINOR 5
#define CUSPARSE_VER_PATCH 0
#define CUSPARSE_VER_BUILD 58
#define CUSPARSE_VERSION (CUSPARSE_VER_MAJOR * 1000 + \
CUSPARSE_VER_MINOR * 100 + \
CUSPARSE_VER_PATCH)
// #############################################################################
// # MACRO
// #############################################################################
#if !defined(CUSPARSEAPI)
# if defined(_WIN32)
# define CUSPARSEAPI __stdcall
# else
# define CUSPARSEAPI
# endif
#endif
//------------------------------------------------------------------------------
#if !defined(_MSC_VER)
# define CUSPARSE_CPP_VERSION __cplusplus
#elif _MSC_FULL_VER >= 190024210 // Visual Studio 2015 Update 3
# define CUSPARSE_CPP_VERSION _MSVC_LANG
#else
# define CUSPARSE_CPP_VERSION 0
#endif
//------------------------------------------------------------------------------
#if !defined(DISABLE_CUSPARSE_DEPRECATED)
# if CUSPARSE_CPP_VERSION >= 201402L
# define CUSPARSE_DEPRECATED(new_func) \
[[deprecated("please use " #new_func " instead")]]
# elif defined(_MSC_VER)
# define CUSPARSE_DEPRECATED(new_func) \
__declspec(deprecated("please use " #new_func " instead"))
# elif defined(__INTEL_COMPILER) || defined(__clang__) || \
(defined(__GNUC__) && \
(__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 5)))
# define CUSPARSE_DEPRECATED(new_func) \
__attribute__((deprecated("please use " #new_func " instead")))
# elif defined(__GNUC__) || defined(__xlc__)
# define CUSPARSE_DEPRECATED(new_func) \
__attribute__((deprecated))
# else
# define CUSPARSE_DEPRECATED(new_func)
# endif // defined(__cplusplus) && __cplusplus >= 201402L
//------------------------------------------------------------------------------
# if CUSPARSE_CPP_VERSION >= 201703L
# define CUSPARSE_DEPRECATED_ENUM(new_enum) \
[[deprecated("please use " #new_enum " instead")]]
# elif defined(__clang__) || \
(defined(__GNUC__) && __GNUC__ >= 6 && !defined(__PGI))
# define CUSPARSE_DEPRECATED_ENUM(new_enum) \
__attribute__((deprecated("please use " #new_enum " instead")))
# else
# define CUSPARSE_DEPRECATED_ENUM(new_enum)
# endif // defined(__cplusplus) && __cplusplus >= 201402L
#else // defined(DISABLE_CUSPARSE_DEPRECATED)
# define CUSPARSE_DEPRECATED(new_func)
# define CUSPARSE_DEPRECATED_ENUM(new_enum)
#endif // !defined(DISABLE_CUSPARSE_DEPRECATED)
#undef CUSPARSE_CPP_VERSION
//------------------------------------------------------------------------------
#if defined(__cplusplus)
extern "C" {
#endif // defined(__cplusplus)
//##############################################################################
//# OPAQUE DATA STRUCTURES
//##############################################################################
struct cusparseContext;
typedef struct cusparseContext* cusparseHandle_t;
struct cusparseMatDescr;
typedef struct cusparseMatDescr* cusparseMatDescr_t;
struct csrsv2Info;
typedef struct csrsv2Info* csrsv2Info_t;
struct csrsm2Info;
typedef struct csrsm2Info* csrsm2Info_t;
struct bsrsv2Info;
typedef struct bsrsv2Info* bsrsv2Info_t;
struct bsrsm2Info;
typedef struct bsrsm2Info* bsrsm2Info_t;
struct csric02Info;
typedef struct csric02Info* csric02Info_t;
struct bsric02Info;
typedef struct bsric02Info* bsric02Info_t;
struct csrilu02Info;
typedef struct csrilu02Info* csrilu02Info_t;
struct bsrilu02Info;
typedef struct bsrilu02Info* bsrilu02Info_t;
struct csrgemm2Info;
typedef struct csrgemm2Info* csrgemm2Info_t;
struct csru2csrInfo;
typedef struct csru2csrInfo* csru2csrInfo_t;
struct cusparseColorInfo;
typedef struct cusparseColorInfo* cusparseColorInfo_t;
struct pruneInfo;
typedef struct pruneInfo* pruneInfo_t;
//##############################################################################
//# ENUMERATORS
//##############################################################################
typedef enum {
CUSPARSE_STATUS_SUCCESS = 0,
CUSPARSE_STATUS_NOT_INITIALIZED = 1,
CUSPARSE_STATUS_ALLOC_FAILED = 2,
CUSPARSE_STATUS_INVALID_VALUE = 3,
CUSPARSE_STATUS_ARCH_MISMATCH = 4,
CUSPARSE_STATUS_MAPPING_ERROR = 5,
CUSPARSE_STATUS_EXECUTION_FAILED = 6,
CUSPARSE_STATUS_INTERNAL_ERROR = 7,
CUSPARSE_STATUS_MATRIX_TYPE_NOT_SUPPORTED = 8,
CUSPARSE_STATUS_ZERO_PIVOT = 9,
CUSPARSE_STATUS_NOT_SUPPORTED = 10,
CUSPARSE_STATUS_INSUFFICIENT_RESOURCES = 11
} cusparseStatus_t;
typedef enum {
CUSPARSE_POINTER_MODE_HOST = 0,
CUSPARSE_POINTER_MODE_DEVICE = 1
} cusparsePointerMode_t;
typedef enum {
CUSPARSE_ACTION_SYMBOLIC = 0,
CUSPARSE_ACTION_NUMERIC = 1
} cusparseAction_t;
typedef enum {
CUSPARSE_MATRIX_TYPE_GENERAL = 0,
CUSPARSE_MATRIX_TYPE_SYMMETRIC = 1,
CUSPARSE_MATRIX_TYPE_HERMITIAN = 2,
CUSPARSE_MATRIX_TYPE_TRIANGULAR = 3
} cusparseMatrixType_t;
typedef enum {
CUSPARSE_FILL_MODE_LOWER = 0,
CUSPARSE_FILL_MODE_UPPER = 1
} cusparseFillMode_t;
typedef enum {
CUSPARSE_DIAG_TYPE_NON_UNIT = 0,
CUSPARSE_DIAG_TYPE_UNIT = 1
} cusparseDiagType_t;
typedef enum {
CUSPARSE_INDEX_BASE_ZERO = 0,
CUSPARSE_INDEX_BASE_ONE = 1
} cusparseIndexBase_t;
typedef enum {
CUSPARSE_OPERATION_NON_TRANSPOSE = 0,
CUSPARSE_OPERATION_TRANSPOSE = 1,
CUSPARSE_OPERATION_CONJUGATE_TRANSPOSE = 2
} cusparseOperation_t;
typedef enum {
CUSPARSE_DIRECTION_ROW = 0,
CUSPARSE_DIRECTION_COLUMN = 1
} cusparseDirection_t;
typedef enum {
CUSPARSE_SOLVE_POLICY_NO_LEVEL = 0,
CUSPARSE_SOLVE_POLICY_USE_LEVEL = 1
} cusparseSolvePolicy_t;
typedef enum {
CUSPARSE_SIDE_LEFT = 0,
CUSPARSE_SIDE_RIGHT = 1
} cusparseSideMode_t;
typedef enum {
CUSPARSE_COLOR_ALG0 = 0, // default
CUSPARSE_COLOR_ALG1 = 1
} cusparseColorAlg_t;
typedef enum {
CUSPARSE_ALG_MERGE_PATH // merge path alias
} cusparseAlgMode_t;
//##############################################################################
//# INITIALIZATION AND MANAGEMENT ROUTINES
//##############################################################################
cusparseStatus_t CUSPARSEAPI
cusparseCreate(cusparseHandle_t* handle);
cusparseStatus_t CUSPARSEAPI
cusparseDestroy(cusparseHandle_t handle);
cusparseStatus_t CUSPARSEAPI
cusparseGetVersion(cusparseHandle_t handle,
int* version);
cusparseStatus_t CUSPARSEAPI
cusparseGetProperty(libraryPropertyType type,
int* value);
const char* CUSPARSEAPI
cusparseGetErrorName(cusparseStatus_t status);
const char* CUSPARSEAPI
cusparseGetErrorString(cusparseStatus_t status);
cusparseStatus_t CUSPARSEAPI
cusparseSetStream(cusparseHandle_t handle,
cudaStream_t streamId);
cusparseStatus_t CUSPARSEAPI
cusparseGetStream(cusparseHandle_t handle,
cudaStream_t* streamId);
cusparseStatus_t CUSPARSEAPI
cusparseGetPointerMode(cusparseHandle_t handle,
cusparsePointerMode_t* mode);
cusparseStatus_t CUSPARSEAPI
cusparseSetPointerMode(cusparseHandle_t handle,
cusparsePointerMode_t mode);
//##############################################################################
//# HELPER ROUTINES
//##############################################################################
cusparseStatus_t CUSPARSEAPI
cusparseCreateMatDescr(cusparseMatDescr_t* descrA);
cusparseStatus_t CUSPARSEAPI
cusparseDestroyMatDescr(cusparseMatDescr_t descrA);
cusparseStatus_t CUSPARSEAPI
cusparseCopyMatDescr(cusparseMatDescr_t dest,
const cusparseMatDescr_t src);
cusparseStatus_t CUSPARSEAPI
cusparseSetMatType(cusparseMatDescr_t descrA,
cusparseMatrixType_t type);
cusparseMatrixType_t CUSPARSEAPI
cusparseGetMatType(const cusparseMatDescr_t descrA);
cusparseStatus_t CUSPARSEAPI
cusparseSetMatFillMode(cusparseMatDescr_t descrA,
cusparseFillMode_t fillMode);
cusparseFillMode_t CUSPARSEAPI
cusparseGetMatFillMode(const cusparseMatDescr_t descrA);
cusparseStatus_t CUSPARSEAPI
cusparseSetMatDiagType(cusparseMatDescr_t descrA,
cusparseDiagType_t diagType);
cusparseDiagType_t CUSPARSEAPI
cusparseGetMatDiagType(const cusparseMatDescr_t descrA);
cusparseStatus_t CUSPARSEAPI
cusparseSetMatIndexBase(cusparseMatDescr_t descrA,
cusparseIndexBase_t base);
cusparseIndexBase_t CUSPARSEAPI
cusparseGetMatIndexBase(const cusparseMatDescr_t descrA);
CUSPARSE_DEPRECATED(cusparseSpSV)
cusparseStatus_t CUSPARSEAPI
cusparseCreateCsrsv2Info(csrsv2Info_t* info);
CUSPARSE_DEPRECATED(cusparseSpSV)
cusparseStatus_t CUSPARSEAPI
cusparseDestroyCsrsv2Info(csrsv2Info_t info);
cusparseStatus_t CUSPARSEAPI
cusparseCreateCsric02Info(csric02Info_t* info);
cusparseStatus_t CUSPARSEAPI
cusparseDestroyCsric02Info(csric02Info_t info);
cusparseStatus_t CUSPARSEAPI
cusparseCreateBsric02Info(bsric02Info_t* info);
cusparseStatus_t CUSPARSEAPI
cusparseDestroyBsric02Info(bsric02Info_t info);
cusparseStatus_t CUSPARSEAPI
cusparseCreateCsrilu02Info(csrilu02Info_t* info);
cusparseStatus_t CUSPARSEAPI
cusparseDestroyCsrilu02Info(csrilu02Info_t info);
cusparseStatus_t CUSPARSEAPI
cusparseCreateBsrilu02Info(bsrilu02Info_t* info);
cusparseStatus_t CUSPARSEAPI
cusparseDestroyBsrilu02Info(bsrilu02Info_t info);
cusparseStatus_t CUSPARSEAPI
cusparseCreateBsrsv2Info(bsrsv2Info_t* info);
cusparseStatus_t CUSPARSEAPI
cusparseDestroyBsrsv2Info(bsrsv2Info_t info);
cusparseStatus_t CUSPARSEAPI
cusparseCreateBsrsm2Info(bsrsm2Info_t* info);
cusparseStatus_t CUSPARSEAPI
cusparseDestroyBsrsm2Info(bsrsm2Info_t info);
cusparseStatus_t CUSPARSEAPI
cusparseCreateCsru2csrInfo(csru2csrInfo_t* info);
cusparseStatus_t CUSPARSEAPI
cusparseDestroyCsru2csrInfo(csru2csrInfo_t info);
cusparseStatus_t CUSPARSEAPI
cusparseCreateColorInfo(cusparseColorInfo_t* info);
cusparseStatus_t CUSPARSEAPI
cusparseDestroyColorInfo(cusparseColorInfo_t info);
cusparseStatus_t CUSPARSEAPI
cusparseSetColorAlgs(cusparseColorInfo_t info,
cusparseColorAlg_t alg);
cusparseStatus_t CUSPARSEAPI
cusparseGetColorAlgs(cusparseColorInfo_t info,
cusparseColorAlg_t* alg);
cusparseStatus_t CUSPARSEAPI
cusparseCreatePruneInfo(pruneInfo_t* info);
cusparseStatus_t CUSPARSEAPI
cusparseDestroyPruneInfo(pruneInfo_t info);
//##############################################################################
//# SPARSE LEVEL 1 ROUTINES
//##############################################################################
CUSPARSE_DEPRECATED(cusparseAxpby)
cusparseStatus_t CUSPARSEAPI
cusparseSaxpyi(cusparseHandle_t handle,
int nnz,
const float* alpha,
const float* xVal,
const int* xInd,
float* y,
cusparseIndexBase_t idxBase);
CUSPARSE_DEPRECATED(cusparseAxpby)
cusparseStatus_t CUSPARSEAPI
cusparseDaxpyi(cusparseHandle_t handle,
int nnz,
const double* alpha,
const double* xVal,
const int* xInd,
double* y,
cusparseIndexBase_t idxBase);
CUSPARSE_DEPRECATED(cusparseAxpby)
cusparseStatus_t CUSPARSEAPI
cusparseCaxpyi(cusparseHandle_t handle,
int nnz,
const cuComplex* alpha,
const cuComplex* xVal,
const int* xInd,
cuComplex* y,
cusparseIndexBase_t idxBase);
CUSPARSE_DEPRECATED(cusparseAxpby)
cusparseStatus_t CUSPARSEAPI
cusparseZaxpyi(cusparseHandle_t handle,
int nnz,
const cuDoubleComplex* alpha,
const cuDoubleComplex* xVal,
const int* xInd,
cuDoubleComplex* y,
cusparseIndexBase_t idxBase);
CUSPARSE_DEPRECATED(cusparseGather)
cusparseStatus_t CUSPARSEAPI
cusparseSgthr(cusparseHandle_t handle,
int nnz,
const float* y,
float* xVal,
const int* xInd,
cusparseIndexBase_t idxBase);
CUSPARSE_DEPRECATED(cusparseGather)
cusparseStatus_t CUSPARSEAPI
cusparseDgthr(cusparseHandle_t handle,
int nnz,
const double* y,
double* xVal,
const int* xInd,
cusparseIndexBase_t idxBase);
CUSPARSE_DEPRECATED(cusparseGather)
cusparseStatus_t CUSPARSEAPI
cusparseCgthr(cusparseHandle_t handle,
int nnz,
const cuComplex* y,
cuComplex* xVal,
const int* xInd,
cusparseIndexBase_t idxBase);
CUSPARSE_DEPRECATED(cusparseGather)
cusparseStatus_t CUSPARSEAPI
cusparseZgthr(cusparseHandle_t handle,
int nnz,
const cuDoubleComplex* y,
cuDoubleComplex* xVal,
const int* xInd,
cusparseIndexBase_t idxBase);
CUSPARSE_DEPRECATED(cusparseGather)
cusparseStatus_t CUSPARSEAPI
cusparseSgthrz(cusparseHandle_t handle,
int nnz,
float* y,
float* xVal,
const int* xInd,
cusparseIndexBase_t idxBase);
CUSPARSE_DEPRECATED(cusparseGather)
cusparseStatus_t CUSPARSEAPI
cusparseDgthrz(cusparseHandle_t handle,
int nnz,
double* y,
double* xVal,
const int* xInd,
cusparseIndexBase_t idxBase);
CUSPARSE_DEPRECATED(cusparseGather)
cusparseStatus_t CUSPARSEAPI
cusparseCgthrz(cusparseHandle_t handle,
int nnz,
cuComplex* y,
cuComplex* xVal,
const int* xInd,
cusparseIndexBase_t idxBase);
CUSPARSE_DEPRECATED(cusparseGather)
cusparseStatus_t CUSPARSEAPI
cusparseZgthrz(cusparseHandle_t handle,
int nnz,
cuDoubleComplex* y,
cuDoubleComplex* xVal,
const int* xInd,
cusparseIndexBase_t idxBase);
CUSPARSE_DEPRECATED(cusparseScatter)
cusparseStatus_t CUSPARSEAPI
cusparseSsctr(cusparseHandle_t handle,
int nnz,
const float* xVal,
const int* xInd,
float* y,
cusparseIndexBase_t idxBase);
CUSPARSE_DEPRECATED(cusparseScatter)
cusparseStatus_t CUSPARSEAPI
cusparseDsctr(cusparseHandle_t handle,
int nnz,
const double* xVal,
const int* xInd,
double* y,
cusparseIndexBase_t idxBase);
CUSPARSE_DEPRECATED(cusparseScatter)
cusparseStatus_t CUSPARSEAPI
cusparseCsctr(cusparseHandle_t handle,
int nnz,
const cuComplex* xVal,
const int* xInd,
cuComplex* y,
cusparseIndexBase_t idxBase);
CUSPARSE_DEPRECATED(cusparseScatter)
cusparseStatus_t CUSPARSEAPI
cusparseZsctr(cusparseHandle_t handle,
int nnz,
const cuDoubleComplex* xVal,
const int* xInd,
cuDoubleComplex* y,
cusparseIndexBase_t idxBase);
CUSPARSE_DEPRECATED(cusparseRot)
cusparseStatus_t CUSPARSEAPI
cusparseSroti(cusparseHandle_t handle,
int nnz,
float* xVal,
const int* xInd,
float* y,
const float* c,
const float* s,
cusparseIndexBase_t idxBase);
CUSPARSE_DEPRECATED(cusparseRot)
cusparseStatus_t CUSPARSEAPI
cusparseDroti(cusparseHandle_t handle,
int nnz,
double* xVal,
const int* xInd,
double* y,
const double* c,
const double* s,
cusparseIndexBase_t idxBase);
//##############################################################################
//# SPARSE LEVEL 2 ROUTINES
//##############################################################################
cusparseStatus_t CUSPARSEAPI
cusparseSgemvi(cusparseHandle_t handle,
cusparseOperation_t transA,
int m,
int n,
const float* alpha,
const float* A,
int lda,
int nnz,
const float* xVal,
const int* xInd,
const float* beta,
float* y,
cusparseIndexBase_t idxBase,
void* pBuffer);
cusparseStatus_t CUSPARSEAPI
cusparseSgemvi_bufferSize(cusparseHandle_t handle,
cusparseOperation_t transA,
int m,
int n,
int nnz,
int* pBufferSize);
cusparseStatus_t CUSPARSEAPI
cusparseDgemvi(cusparseHandle_t handle,
cusparseOperation_t transA,
int m,
int n,
const double* alpha,
const double* A,
int lda,
int nnz,
const double* xVal,
const int* xInd,
const double* beta,
double* y,
cusparseIndexBase_t idxBase,
void* pBuffer);
cusparseStatus_t CUSPARSEAPI
cusparseDgemvi_bufferSize(cusparseHandle_t handle,
cusparseOperation_t transA,
int m,
int n,
int nnz,
int* pBufferSize);
cusparseStatus_t CUSPARSEAPI
cusparseCgemvi(cusparseHandle_t handle,
cusparseOperation_t transA,
int m,
int n,
const cuComplex* alpha,
const cuComplex* A,
int lda,
int nnz,
const cuComplex* xVal,
const int* xInd,
const cuComplex* beta,
cuComplex* y,
cusparseIndexBase_t idxBase,
void* pBuffer);
cusparseStatus_t CUSPARSEAPI
cusparseCgemvi_bufferSize(cusparseHandle_t handle,
cusparseOperation_t transA,
int m,
int n,
int nnz,
int* pBufferSize);
cusparseStatus_t CUSPARSEAPI
cusparseZgemvi(cusparseHandle_t handle,
cusparseOperation_t transA,
int m,
int n,
const cuDoubleComplex* alpha,
const cuDoubleComplex* A,
int lda,
int nnz,
const cuDoubleComplex* xVal,
const int* xInd,
const cuDoubleComplex* beta,
cuDoubleComplex* y,
cusparseIndexBase_t idxBase,
void* pBuffer);
cusparseStatus_t CUSPARSEAPI
cusparseZgemvi_bufferSize(cusparseHandle_t handle,
cusparseOperation_t transA,
int m,
int n,
int nnz,
int* pBufferSize);
CUSPARSE_DEPRECATED(cusparseSpMV)
cusparseStatus_t CUSPARSEAPI
cusparseCsrmvEx_bufferSize(cusparseHandle_t handle,
cusparseAlgMode_t alg,
cusparseOperation_t transA,
int m,
int n,
int nnz,
const void* alpha,
cudaDataType alphatype,
const cusparseMatDescr_t descrA,
const void* csrValA,
cudaDataType csrValAtype,
const int* csrRowPtrA,
const int* csrColIndA,
const void* x,
cudaDataType xtype,
const void* beta,
cudaDataType betatype,
void* y,
cudaDataType ytype,
cudaDataType executiontype,
size_t* bufferSizeInBytes);
CUSPARSE_DEPRECATED(cusparseSpMV)
cusparseStatus_t CUSPARSEAPI
cusparseCsrmvEx(cusparseHandle_t handle,
cusparseAlgMode_t alg,
cusparseOperation_t transA,
int m,
int n,
int nnz,
const void* alpha,
cudaDataType alphatype,
const cusparseMatDescr_t descrA,
const void* csrValA,
cudaDataType csrValAtype,
const int* csrRowPtrA,
const int* csrColIndA,
const void* x,
cudaDataType xtype,
const void* beta,
cudaDataType betatype,
void* y,
cudaDataType ytype,
cudaDataType executiontype,
void* buffer);
cusparseStatus_t CUSPARSEAPI
cusparseSbsrmv(cusparseHandle_t handle,
cusparseDirection_t dirA,
cusparseOperation_t transA,
int mb,
int nb,
int nnzb,
const float* alpha,
const cusparseMatDescr_t descrA,
const float* bsrSortedValA,
const int* bsrSortedRowPtrA,
const int* bsrSortedColIndA,
int blockDim,
const float* x,
const float* beta,
float* y);
cusparseStatus_t CUSPARSEAPI
cusparseDbsrmv(cusparseHandle_t handle,
cusparseDirection_t dirA,
cusparseOperation_t transA,
int mb,
int nb,
int nnzb,
const double* alpha,
const cusparseMatDescr_t descrA,
const double* bsrSortedValA,
const int* bsrSortedRowPtrA,
const int* bsrSortedColIndA,
int blockDim,
const double* x,
const double* beta,
double* y);
cusparseStatus_t CUSPARSEAPI
cusparseCbsrmv(cusparseHandle_t handle,
cusparseDirection_t dirA,
cusparseOperation_t transA,
int mb,
int nb,
int nnzb,
const cuComplex* alpha,
const cusparseMatDescr_t descrA,
const cuComplex* bsrSortedValA,
const int* bsrSortedRowPtrA,
const int* bsrSortedColIndA,
int blockDim,
const cuComplex* x,
const cuComplex* beta,
cuComplex* y);
cusparseStatus_t CUSPARSEAPI
cusparseZbsrmv(cusparseHandle_t handle,
cusparseDirection_t dirA,
cusparseOperation_t transA,
int mb,
int nb,
int nnzb,
const cuDoubleComplex* alpha,
const cusparseMatDescr_t descrA,
const cuDoubleComplex* bsrSortedValA,
const int* bsrSortedRowPtrA,
const int* bsrSortedColIndA,
int blockDim,
const cuDoubleComplex* x,
const cuDoubleComplex* beta,
cuDoubleComplex* y);
cusparseStatus_t CUSPARSEAPI
cusparseSbsrxmv(cusparseHandle_t handle,
cusparseDirection_t dirA,
cusparseOperation_t transA,
int sizeOfMask,
int mb,
int nb,
int nnzb,
const float* alpha,
const cusparseMatDescr_t descrA,
const float* bsrSortedValA,
const int* bsrSortedMaskPtrA,
const int* bsrSortedRowPtrA,
const int* bsrSortedEndPtrA,
const int* bsrSortedColIndA,
int blockDim,
const float* x,
const float* beta,
float* y);
cusparseStatus_t CUSPARSEAPI
cusparseDbsrxmv(cusparseHandle_t handle,
cusparseDirection_t dirA,
cusparseOperation_t transA,
int sizeOfMask,
int mb,
int nb,
int nnzb,
const double* alpha,
const cusparseMatDescr_t descrA,
const double* bsrSortedValA,
const int* bsrSortedMaskPtrA,
const int* bsrSortedRowPtrA,
const int* bsrSortedEndPtrA,
const int* bsrSortedColIndA,
int blockDim,
const double* x,
const double* beta,
double* y);
cusparseStatus_t CUSPARSEAPI
cusparseCbsrxmv(cusparseHandle_t handle,
cusparseDirection_t dirA,
cusparseOperation_t transA,
int sizeOfMask,
int mb,
int nb,
int nnzb,
const cuComplex* alpha,
const cusparseMatDescr_t descrA,
const cuComplex* bsrSortedValA,
const int* bsrSortedMaskPtrA,
const int* bsrSortedRowPtrA,
const int* bsrSortedEndPtrA,
const int* bsrSortedColIndA,
int blockDim,
const cuComplex* x,
const cuComplex* beta,
cuComplex* y);
cusparseStatus_t CUSPARSEAPI
cusparseZbsrxmv(cusparseHandle_t handle,
cusparseDirection_t dirA,
cusparseOperation_t transA,
int sizeOfMask,
int mb,
int nb,
int nnzb,
const cuDoubleComplex* alpha,
const cusparseMatDescr_t descrA,
const cuDoubleComplex* bsrSortedValA,
const int* bsrSortedMaskPtrA,
const int* bsrSortedRowPtrA,
const int* bsrSortedEndPtrA,
const int* bsrSortedColIndA,
int blockDim,
const cuDoubleComplex* x,
const cuDoubleComplex* beta,
cuDoubleComplex* y);
CUSPARSE_DEPRECATED(cusparseSpSV)
cusparseStatus_t CUSPARSEAPI
cusparseXcsrsv2_zeroPivot(cusparseHandle_t handle,
csrsv2Info_t info,
int* position);
CUSPARSE_DEPRECATED(cusparseSpSV)
cusparseStatus_t CUSPARSEAPI
cusparseScsrsv2_bufferSize(cusparseHandle_t handle,
cusparseOperation_t transA,
int m,
int nnz,
const cusparseMatDescr_t descrA,
float* csrSortedValA,
const int* csrSortedRowPtrA,
const int* csrSortedColIndA,
csrsv2Info_t info,
int* pBufferSizeInBytes);
CUSPARSE_DEPRECATED(cusparseSpSV)
cusparseStatus_t CUSPARSEAPI
cusparseDcsrsv2_bufferSize(cusparseHandle_t handle,
cusparseOperation_t transA,
int m,
int nnz,
const cusparseMatDescr_t descrA,
double* csrSortedValA,
const int* csrSortedRowPtrA,
const int* csrSortedColIndA,
csrsv2Info_t info,
int* pBufferSizeInBytes);
CUSPARSE_DEPRECATED(cusparseSpSV)
cusparseStatus_t CUSPARSEAPI
cusparseCcsrsv2_bufferSize(cusparseHandle_t handle,
cusparseOperation_t transA,
int m,
int nnz,
const cusparseMatDescr_t descrA,
cuComplex* csrSortedValA,
const int* csrSortedRowPtrA,
const int* csrSortedColIndA,
csrsv2Info_t info,
int* pBufferSizeInBytes);
CUSPARSE_DEPRECATED(cusparseSpSV)
cusparseStatus_t CUSPARSEAPI
cusparseZcsrsv2_bufferSize(cusparseHandle_t handle,
cusparseOperation_t transA,
int m,
int nnz,
const cusparseMatDescr_t descrA,
cuDoubleComplex* csrSortedValA,
const int* csrSortedRowPtrA,
const int* csrSortedColIndA,
csrsv2Info_t info,
int* pBufferSizeInBytes);
CUSPARSE_DEPRECATED(cusparseSpSV)
cusparseStatus_t CUSPARSEAPI
cusparseScsrsv2_bufferSizeExt(cusparseHandle_t handle,
cusparseOperation_t transA,
int m,
int nnz,
const cusparseMatDescr_t descrA,
float* csrSortedValA,
const int* csrSortedRowPtrA,
const int* csrSortedColIndA,
csrsv2Info_t info,
size_t* pBufferSize);
CUSPARSE_DEPRECATED(cusparseSpSV)
cusparseStatus_t CUSPARSEAPI
cusparseDcsrsv2_bufferSizeExt(cusparseHandle_t handle,
cusparseOperation_t transA,
int m,
int nnz,
const cusparseMatDescr_t descrA,
double* csrSortedValA,
const int* csrSortedRowPtrA,
const int* csrSortedColIndA,
csrsv2Info_t info,
size_t* pBufferSize);
CUSPARSE_DEPRECATED(cusparseSpSV)
cusparseStatus_t CUSPARSEAPI
cusparseCcsrsv2_bufferSizeExt(cusparseHandle_t handle,
cusparseOperation_t transA,
int m,
int nnz,
const cusparseMatDescr_t descrA,
cuComplex* csrSortedValA,
const int* csrSortedRowPtrA,
const int* csrSortedColIndA,
csrsv2Info_t info,
size_t* pBufferSize);
CUSPARSE_DEPRECATED(cusparseSpSV)
cusparseStatus_t CUSPARSEAPI
cusparseZcsrsv2_bufferSizeExt(cusparseHandle_t handle,
cusparseOperation_t transA,
int m,
int nnz,
const cusparseMatDescr_t descrA,
cuDoubleComplex* csrSortedValA,
const int* csrSortedRowPtrA,
const int* csrSortedColIndA,
csrsv2Info_t info,
size_t* pBufferSize);
CUSPARSE_DEPRECATED(cusparseSpSV)
cusparseStatus_t CUSPARSEAPI
cusparseScsrsv2_analysis(cusparseHandle_t handle,
cusparseOperation_t transA,
int m,
int nnz,
const cusparseMatDescr_t descrA,
const float* csrSortedValA,
const int* csrSortedRowPtrA,
const int* csrSortedColIndA,
csrsv2Info_t info,
cusparseSolvePolicy_t policy,
void* pBuffer);
CUSPARSE_DEPRECATED(cusparseSpSV)
cusparseStatus_t CUSPARSEAPI
cusparseDcsrsv2_analysis(cusparseHandle_t handle,
cusparseOperation_t transA,
int m,
int nnz,
const cusparseMatDescr_t descrA,
const double* csrSortedValA,
const int* csrSortedRowPtrA,
const int* csrSortedColIndA,
csrsv2Info_t info,
cusparseSolvePolicy_t policy,
void* pBuffer);
CUSPARSE_DEPRECATED(cusparseSpSV)
cusparseStatus_t CUSPARSEAPI
cusparseCcsrsv2_analysis(cusparseHandle_t handle,
cusparseOperation_t transA,
int m,
int nnz,
const cusparseMatDescr_t descrA,
const cuComplex* csrSortedValA,
const int* csrSortedRowPtrA,
const int* csrSortedColIndA,
csrsv2Info_t info,
cusparseSolvePolicy_t policy,
void* pBuffer);
CUSPARSE_DEPRECATED(cusparseSpSV)
cusparseStatus_t CUSPARSEAPI
cusparseZcsrsv2_analysis(cusparseHandle_t handle,
cusparseOperation_t transA,
int m,
int nnz,
const cusparseMatDescr_t descrA,
const cuDoubleComplex* csrSortedValA,
const int* csrSortedRowPtrA,
const int* csrSortedColIndA,
csrsv2Info_t info,
cusparseSolvePolicy_t policy,
void* pBuffer);
CUSPARSE_DEPRECATED(cusparseSpSV)
cusparseStatus_t CUSPARSEAPI
cusparseScsrsv2_solve(cusparseHandle_t handle,
cusparseOperation_t transA,
int m,
int nnz,
const float* alpha,
const cusparseMatDescr_t descrA,
const float* csrSortedValA,
const int* csrSortedRowPtrA,
const int* csrSortedColIndA,
csrsv2Info_t info,
const float* f,
float* x,
cusparseSolvePolicy_t policy,
void* pBuffer);
CUSPARSE_DEPRECATED(cusparseSpSV)
cusparseStatus_t CUSPARSEAPI
cusparseDcsrsv2_solve(cusparseHandle_t handle,
cusparseOperation_t transA,
int m,
int nnz,
const double* alpha,
const cusparseMatDescr_t descrA,
const double* csrSortedValA,
const int* csrSortedRowPtrA,
const int* csrSortedColIndA,
csrsv2Info_t info,
const double* f,
double* x,
cusparseSolvePolicy_t policy,
void* pBuffer);
CUSPARSE_DEPRECATED(cusparseSpSV)
cusparseStatus_t CUSPARSEAPI
cusparseCcsrsv2_solve(cusparseHandle_t handle,
cusparseOperation_t transA,
int m,
int nnz,
const cuComplex* alpha,
const cusparseMatDescr_t descrA,
const cuComplex* csrSortedValA,
const int* csrSortedRowPtrA,
const int* csrSortedColIndA,
csrsv2Info_t info,
const cuComplex* f,
cuComplex* x,
cusparseSolvePolicy_t policy,
void* pBuffer);
CUSPARSE_DEPRECATED(cusparseSpSV)
cusparseStatus_t CUSPARSEAPI
cusparseZcsrsv2_solve(cusparseHandle_t handle,
cusparseOperation_t transA,
int m,
int nnz,
const cuDoubleComplex* alpha,
const cusparseMatDescr_t descrA,
const cuDoubleComplex* csrSortedValA,
const int* csrSortedRowPtrA,
const int* csrSortedColIndA,
csrsv2Info_t info,
const cuDoubleComplex* f,
cuDoubleComplex* x,
cusparseSolvePolicy_t policy,
void* pBuffer);
cusparseStatus_t CUSPARSEAPI
cusparseXbsrsv2_zeroPivot(cusparseHandle_t handle,
bsrsv2Info_t info,
int* position);
cusparseStatus_t CUSPARSEAPI
cusparseSbsrsv2_bufferSize(cusparseHandle_t handle,
cusparseDirection_t dirA,
cusparseOperation_t transA,
int mb,
int nnzb,
const cusparseMatDescr_t descrA,
float* bsrSortedValA,
const int* bsrSortedRowPtrA,
const int* bsrSortedColIndA,
int blockDim,
bsrsv2Info_t info,
int* pBufferSizeInBytes);
cusparseStatus_t CUSPARSEAPI
cusparseDbsrsv2_bufferSize(cusparseHandle_t handle,
cusparseDirection_t dirA,
cusparseOperation_t transA,
int mb,
int nnzb,
const cusparseMatDescr_t descrA,
double* bsrSortedValA,
const int* bsrSortedRowPtrA,
const int* bsrSortedColIndA,
int blockDim,
bsrsv2Info_t info,
int* pBufferSizeInBytes);
cusparseStatus_t CUSPARSEAPI
cusparseCbsrsv2_bufferSize(cusparseHandle_t handle,
cusparseDirection_t dirA,
cusparseOperation_t transA,
int mb,
int nnzb,
const cusparseMatDescr_t descrA,
cuComplex* bsrSortedValA,
const int* bsrSortedRowPtrA,
const int* bsrSortedColIndA,
int blockDim,
bsrsv2Info_t info,
int* pBufferSizeInBytes);
cusparseStatus_t CUSPARSEAPI
cusparseZbsrsv2_bufferSize(cusparseHandle_t handle,
cusparseDirection_t dirA,
cusparseOperation_t transA,
int mb,
int nnzb,
const cusparseMatDescr_t descrA,
cuDoubleComplex* bsrSortedValA,
const int* bsrSortedRowPtrA,
const int* bsrSortedColIndA,
int blockDim,
bsrsv2Info_t info,
int* pBufferSizeInBytes);
cusparseStatus_t CUSPARSEAPI
cusparseSbsrsv2_bufferSizeExt(cusparseHandle_t handle,
cusparseDirection_t dirA,
cusparseOperation_t transA,
int mb,
int nnzb,
const cusparseMatDescr_t descrA,
float* bsrSortedValA,
const int* bsrSortedRowPtrA,
const int* bsrSortedColIndA,
int blockSize,
bsrsv2Info_t info,
size_t* pBufferSize);
cusparseStatus_t CUSPARSEAPI
cusparseDbsrsv2_bufferSizeExt(cusparseHandle_t handle,
cusparseDirection_t dirA,
cusparseOperation_t transA,
int mb,
int nnzb,
const cusparseMatDescr_t descrA,
double* bsrSortedValA,
const int* bsrSortedRowPtrA,
const int* bsrSortedColIndA,
int blockSize,
bsrsv2Info_t info,
size_t* pBufferSize);
cusparseStatus_t CUSPARSEAPI
cusparseCbsrsv2_bufferSizeExt(cusparseHandle_t handle,
cusparseDirection_t dirA,
cusparseOperation_t transA,
int mb,
int nnzb,
const cusparseMatDescr_t descrA,
cuComplex* bsrSortedValA,
const int* bsrSortedRowPtrA,
const int* bsrSortedColIndA,
int blockSize,
bsrsv2Info_t info,
size_t* pBufferSize);
cusparseStatus_t CUSPARSEAPI
cusparseZbsrsv2_bufferSizeExt(cusparseHandle_t handle,
cusparseDirection_t dirA,
cusparseOperation_t transA,
int mb,
int nnzb,
const cusparseMatDescr_t descrA,
cuDoubleComplex* bsrSortedValA,
const int* bsrSortedRowPtrA,
const int* bsrSortedColIndA,
int blockSize,
bsrsv2Info_t info,
size_t* pBufferSize);
cusparseStatus_t CUSPARSEAPI
cusparseSbsrsv2_analysis(cusparseHandle_t handle,
cusparseDirection_t dirA,
cusparseOperation_t transA,
int mb,
int nnzb,
const cusparseMatDescr_t descrA,
const float* bsrSortedValA,
const int* bsrSortedRowPtrA,
const int* bsrSortedColIndA,
int blockDim,
bsrsv2Info_t info,
cusparseSolvePolicy_t policy,
void* pBuffer);
cusparseStatus_t CUSPARSEAPI
cusparseDbsrsv2_analysis(cusparseHandle_t handle,
cusparseDirection_t dirA,
cusparseOperation_t transA,
int mb,
int nnzb,
const cusparseMatDescr_t descrA,
const double* bsrSortedValA,
const int* bsrSortedRowPtrA,
const int* bsrSortedColIndA,
int blockDim,
bsrsv2Info_t info,
cusparseSolvePolicy_t policy,
void* pBuffer);
cusparseStatus_t CUSPARSEAPI
cusparseCbsrsv2_analysis(cusparseHandle_t handle,
cusparseDirection_t dirA,
cusparseOperation_t transA,
int mb,
int nnzb,
const cusparseMatDescr_t descrA,
const cuComplex* bsrSortedValA,
const int* bsrSortedRowPtrA,
const int* bsrSortedColIndA,
int blockDim,
bsrsv2Info_t info,
cusparseSolvePolicy_t policy,
void* pBuffer);
cusparseStatus_t CUSPARSEAPI
cusparseZbsrsv2_analysis(cusparseHandle_t handle,
cusparseDirection_t dirA,
cusparseOperation_t transA,
int mb,
int nnzb,
const cusparseMatDescr_t descrA,
const cuDoubleComplex* bsrSortedValA,
const int* bsrSortedRowPtrA,
const int* bsrSortedColIndA,
int blockDim,
bsrsv2Info_t info,
cusparseSolvePolicy_t policy,
void* pBuffer);
cusparseStatus_t CUSPARSEAPI
cusparseSbsrsv2_solve(cusparseHandle_t handle,
cusparseDirection_t dirA,
cusparseOperation_t transA,
int mb,
int nnzb,
const float* alpha,
const cusparseMatDescr_t descrA,
const float* bsrSortedValA,
const int* bsrSortedRowPtrA,
const int* bsrSortedColIndA,
int blockDim,
bsrsv2Info_t info,
const float* f,
float* x,
cusparseSolvePolicy_t policy,
void* pBuffer);
cusparseStatus_t CUSPARSEAPI
cusparseDbsrsv2_solve(cusparseHandle_t handle,
cusparseDirection_t dirA,
cusparseOperation_t transA,
int mb,
int nnzb,
const double* alpha,
const cusparseMatDescr_t descrA,
const double* bsrSortedValA,
const int* bsrSortedRowPtrA,
const int* bsrSortedColIndA,
int blockDim,
bsrsv2Info_t info,
const double* f,
double* x,
cusparseSolvePolicy_t policy,
void* pBuffer);
cusparseStatus_t CUSPARSEAPI
cusparseCbsrsv2_solve(cusparseHandle_t handle,
cusparseDirection_t dirA,
cusparseOperation_t transA,
int mb,
int nnzb,
const cuComplex* alpha,
const cusparseMatDescr_t descrA,
const cuComplex* bsrSortedValA,
const int* bsrSortedRowPtrA,
const int* bsrSortedColIndA,
int blockDim,
bsrsv2Info_t info,
const cuComplex* f,
cuComplex* x,
cusparseSolvePolicy_t policy,
void* pBuffer);
cusparseStatus_t CUSPARSEAPI
cusparseZbsrsv2_solve(cusparseHandle_t handle,
cusparseDirection_t dirA,
cusparseOperation_t transA,
int mb,
int nnzb,
const cuDoubleComplex* alpha,
const cusparseMatDescr_t descrA,
const cuDoubleComplex* bsrSortedValA,
const int* bsrSortedRowPtrA,
const int* bsrSortedColIndA,
int blockDim,
bsrsv2Info_t info,
const cuDoubleComplex* f,
cuDoubleComplex* x,
cusparseSolvePolicy_t policy,
void* pBuffer);
//##############################################################################
//# SPARSE LEVEL 3 ROUTINES
//##############################################################################
cusparseStatus_t CUSPARSEAPI
cusparseSbsrmm(cusparseHandle_t handle,
cusparseDirection_t dirA,
cusparseOperation_t transA,
cusparseOperation_t transB,
int mb,
int n,
int kb,
int nnzb,
const float* alpha,
const cusparseMatDescr_t descrA,
const float* bsrSortedValA,
const int* bsrSortedRowPtrA,
const int* bsrSortedColIndA,
const int blockSize,
const float* B,
const int ldb,
const float* beta,
float* C,
int ldc);
cusparseStatus_t CUSPARSEAPI
cusparseDbsrmm(cusparseHandle_t handle,
cusparseDirection_t dirA,
cusparseOperation_t transA,
cusparseOperation_t transB,
int mb,
int n,
int kb,
int nnzb,
const double* alpha,
const cusparseMatDescr_t descrA,
const double* bsrSortedValA,
const int* bsrSortedRowPtrA,
const int* bsrSortedColIndA,
const int blockSize,
const double* B,
const int ldb,
const double* beta,
double* C,
int ldc);
cusparseStatus_t CUSPARSEAPI
cusparseCbsrmm(cusparseHandle_t handle,
cusparseDirection_t dirA,
cusparseOperation_t transA,
cusparseOperation_t transB,
int mb,
int n,
int kb,
int nnzb,
const cuComplex* alpha,
const cusparseMatDescr_t descrA,
const cuComplex* bsrSortedValA,
const int* bsrSortedRowPtrA,
const int* bsrSortedColIndA,
const int blockSize,
const cuComplex* B,
const int ldb,
const cuComplex* beta,
cuComplex* C,
int ldc);
cusparseStatus_t CUSPARSEAPI
cusparseZbsrmm(cusparseHandle_t handle,
cusparseDirection_t dirA,
cusparseOperation_t transA,
cusparseOperation_t transB,
int mb,
int n,
int kb,
int nnzb,
const cuDoubleComplex* alpha,
const cusparseMatDescr_t descrA,
const cuDoubleComplex* bsrSortedValA,
const int* bsrSortedRowPtrA,
const int* bsrSortedColIndA,
const int blockSize,
const cuDoubleComplex* B,
const int ldb,
const cuDoubleComplex* beta,
cuDoubleComplex* C,
int ldc);
CUSPARSE_DEPRECATED(cusparseSpMM)
cusparseStatus_t CUSPARSEAPI
cusparseSgemmi(cusparseHandle_t handle,
int m,
int n,
int k,
int nnz,
const float* alpha,
const float* A,
int lda,
const float* cscValB,
const int* cscColPtrB,
const int* cscRowIndB,
const float* beta,
float* C,
int ldc);
CUSPARSE_DEPRECATED(cusparseSpMM)
cusparseStatus_t CUSPARSEAPI
cusparseDgemmi(cusparseHandle_t handle,
int m,
int n,
int k,
int nnz,
const double* alpha,
const double* A,
int lda,
const double* cscValB,
const int* cscColPtrB,
const int* cscRowIndB,
const double* beta,
double* C,
int ldc);
CUSPARSE_DEPRECATED(cusparseSpMM)
cusparseStatus_t CUSPARSEAPI
cusparseCgemmi(cusparseHandle_t handle,
int m,
int n,
int k,
int nnz,
const cuComplex* alpha,
const cuComplex* A,
int lda,
const cuComplex* cscValB,
const int* cscColPtrB,
const int* cscRowIndB,
const cuComplex* beta,
cuComplex* C,
int ldc);
CUSPARSE_DEPRECATED(cusparseSpMM)
cusparseStatus_t CUSPARSEAPI
cusparseZgemmi(cusparseHandle_t handle,
int m,
int n,
int k,
int nnz,
const cuDoubleComplex* alpha,
const cuDoubleComplex* A,
int lda,
const cuDoubleComplex* cscValB,
const int* cscColPtrB,
const int* cscRowIndB,
const cuDoubleComplex* beta,
cuDoubleComplex* C,
int ldc);
cusparseStatus_t CUSPARSEAPI
cusparseCreateCsrsm2Info(csrsm2Info_t* info);
cusparseStatus_t CUSPARSEAPI
cusparseDestroyCsrsm2Info(csrsm2Info_t info);
cusparseStatus_t CUSPARSEAPI
cusparseXcsrsm2_zeroPivot(cusparseHandle_t handle,
csrsm2Info_t info,
int* position);
cusparseStatus_t CUSPARSEAPI
cusparseScsrsm2_bufferSizeExt(cusparseHandle_t handle,
int algo,
cusparseOperation_t transA,
cusparseOperation_t transB,
int m,
int nrhs,
int nnz,
const float* alpha,
const cusparseMatDescr_t descrA,
const float* csrSortedValA,
const int* csrSortedRowPtrA,
const int* csrSortedColIndA,
const float* B,
int ldb,
csrsm2Info_t info,
cusparseSolvePolicy_t policy,
size_t* pBufferSize);
cusparseStatus_t CUSPARSEAPI
cusparseDcsrsm2_bufferSizeExt(cusparseHandle_t handle,
int algo,
cusparseOperation_t transA,
cusparseOperation_t transB,
int m,
int nrhs,
int nnz,
const double* alpha,
const cusparseMatDescr_t descrA,
const double* csrSortedValA,
const int* csrSortedRowPtrA,
const int* csrSortedColIndA,
const double* B,
int ldb,
csrsm2Info_t info,
cusparseSolvePolicy_t policy,
size_t* pBufferSize);
cusparseStatus_t CUSPARSEAPI
cusparseCcsrsm2_bufferSizeExt(cusparseHandle_t handle,
int algo,
cusparseOperation_t transA,
cusparseOperation_t transB,
int m,
int nrhs,
int nnz,
const cuComplex* alpha,
const cusparseMatDescr_t descrA,
const cuComplex* csrSortedValA,
const int* csrSortedRowPtrA,
const int* csrSortedColIndA,
const cuComplex* B,
int ldb,
csrsm2Info_t info,
cusparseSolvePolicy_t policy,
size_t* pBufferSize);
cusparseStatus_t CUSPARSEAPI
cusparseZcsrsm2_bufferSizeExt(cusparseHandle_t handle,
int algo,
cusparseOperation_t transA,
cusparseOperation_t transB,
int m,
int nrhs,
int nnz,
const cuDoubleComplex* alpha,
const cusparseMatDescr_t descrA,
const cuDoubleComplex* csrSortedValA,
const int* csrSortedRowPtrA,
const int* csrSortedColIndA,
const cuDoubleComplex* B,
int ldb,
csrsm2Info_t info,
cusparseSolvePolicy_t policy,
size_t* pBufferSize);
cusparseStatus_t CUSPARSEAPI
cusparseScsrsm2_analysis(cusparseHandle_t handle,
int algo,
cusparseOperation_t transA,
cusparseOperation_t transB,
int m,
int nrhs,
int nnz,
const float* alpha,
const cusparseMatDescr_t descrA,
const float* csrSortedValA,
const int* csrSortedRowPtrA,
const int* csrSortedColIndA,
const float* B,
int ldb,
csrsm2Info_t info,
cusparseSolvePolicy_t policy,
void* pBuffer);
cusparseStatus_t CUSPARSEAPI
cusparseDcsrsm2_analysis(cusparseHandle_t handle,
int algo,
cusparseOperation_t transA,
cusparseOperation_t transB,
int m,
int nrhs,
int nnz,
const double* alpha,
const cusparseMatDescr_t descrA,
const double* csrSortedValA,
const int* csrSortedRowPtrA,
const int* csrSortedColIndA,
const double* B,
int ldb,
csrsm2Info_t info,
cusparseSolvePolicy_t policy,
void* pBuffer);
cusparseStatus_t CUSPARSEAPI
cusparseCcsrsm2_analysis(cusparseHandle_t handle,
int algo,
cusparseOperation_t transA,
cusparseOperation_t transB,
int m,
int nrhs,
int nnz,
const cuComplex* alpha,
const cusparseMatDescr_t descrA,
const cuComplex* csrSortedValA,
const int* csrSortedRowPtrA,
const int* csrSortedColIndA,
const cuComplex* B,
int ldb,
csrsm2Info_t info,
cusparseSolvePolicy_t policy,
void* pBuffer);
cusparseStatus_t CUSPARSEAPI
cusparseZcsrsm2_analysis(cusparseHandle_t handle,
int algo,
cusparseOperation_t transA,
cusparseOperation_t transB,
int m,
int nrhs,
int nnz,
const cuDoubleComplex* alpha,
const cusparseMatDescr_t descrA,
const cuDoubleComplex* csrSortedValA,
const int* csrSortedRowPtrA,
const int* csrSortedColIndA,
const cuDoubleComplex* B,
int ldb,
csrsm2Info_t info,
cusparseSolvePolicy_t policy,
void* pBuffer);
cusparseStatus_t CUSPARSEAPI
cusparseScsrsm2_solve(cusparseHandle_t handle,
int algo,
cusparseOperation_t transA,
cusparseOperation_t transB,
int m,
int nrhs,
int nnz,
const float* alpha,
const cusparseMatDescr_t descrA,
const float* csrSortedValA,
const int* csrSortedRowPtrA,
const int* csrSortedColIndA,
float* B,
int ldb,
csrsm2Info_t info,
cusparseSolvePolicy_t policy,
void* pBuffer);
cusparseStatus_t CUSPARSEAPI
cusparseDcsrsm2_solve(cusparseHandle_t handle,
int algo,
cusparseOperation_t transA,
cusparseOperation_t transB,
int m,
int nrhs,
int nnz,
const double* alpha,
const cusparseMatDescr_t descrA,
const double* csrSortedValA,
const int* csrSortedRowPtrA,
const int* csrSortedColIndA,
double* B,
int ldb,
csrsm2Info_t info,
cusparseSolvePolicy_t policy,
void* pBuffer);
cusparseStatus_t CUSPARSEAPI
cusparseCcsrsm2_solve(cusparseHandle_t handle,
int algo,
cusparseOperation_t transA,
cusparseOperation_t transB,
int m,
int nrhs,
int nnz,
const cuComplex* alpha,
const cusparseMatDescr_t descrA,
const cuComplex* csrSortedValA,
const int* csrSortedRowPtrA,
const int* csrSortedColIndA,
cuComplex* B,
int ldb,
csrsm2Info_t info,
cusparseSolvePolicy_t policy,
void* pBuffer);
cusparseStatus_t CUSPARSEAPI
cusparseZcsrsm2_solve(cusparseHandle_t handle,
int algo,
cusparseOperation_t transA,
cusparseOperation_t transB,
int m,
int nrhs,
int nnz,
const cuDoubleComplex* alpha,
const cusparseMatDescr_t descrA,
const cuDoubleComplex* csrSortedValA,
const int* csrSortedRowPtrA,
const int* csrSortedColIndA,
cuDoubleComplex* B,
int ldb,
csrsm2Info_t info,
cusparseSolvePolicy_t policy,
void* pBuffer);
cusparseStatus_t CUSPARSEAPI
cusparseXbsrsm2_zeroPivot(cusparseHandle_t handle,
bsrsm2Info_t info,
int* position);
cusparseStatus_t CUSPARSEAPI
cusparseSbsrsm2_bufferSize(cusparseHandle_t handle,
cusparseDirection_t dirA,
cusparseOperation_t transA,
cusparseOperation_t transXY,
int mb,
int n,
int nnzb,
const cusparseMatDescr_t descrA,
float* bsrSortedVal,
const int* bsrSortedRowPtr,
const int* bsrSortedColInd,
int blockSize,
bsrsm2Info_t info,
int* pBufferSizeInBytes);
cusparseStatus_t CUSPARSEAPI
cusparseDbsrsm2_bufferSize(cusparseHandle_t handle,
cusparseDirection_t dirA,
cusparseOperation_t transA,
cusparseOperation_t transXY,
int mb,
int n,
int nnzb,
const cusparseMatDescr_t descrA,
double* bsrSortedVal,
const int* bsrSortedRowPtr,
const int* bsrSortedColInd,
int blockSize,
bsrsm2Info_t info,
int* pBufferSizeInBytes);
cusparseStatus_t CUSPARSEAPI
cusparseCbsrsm2_bufferSize(cusparseHandle_t handle,
cusparseDirection_t dirA,
cusparseOperation_t transA,
cusparseOperation_t transXY,
int mb,
int n,
int nnzb,
const cusparseMatDescr_t descrA,
cuComplex* bsrSortedVal,
const int* bsrSortedRowPtr,
const int* bsrSortedColInd,
int blockSize,
bsrsm2Info_t info,
int* pBufferSizeInBytes);
cusparseStatus_t CUSPARSEAPI
cusparseZbsrsm2_bufferSize(cusparseHandle_t handle,
cusparseDirection_t dirA,
cusparseOperation_t transA,
cusparseOperation_t transXY,
int mb,
int n,
int nnzb,
const cusparseMatDescr_t descrA,
cuDoubleComplex* bsrSortedVal,
const int* bsrSortedRowPtr,
const int* bsrSortedColInd,
int blockSize,
bsrsm2Info_t info,
int* pBufferSizeInBytes);
cusparseStatus_t CUSPARSEAPI
cusparseSbsrsm2_bufferSizeExt(cusparseHandle_t handle,
cusparseDirection_t dirA,
cusparseOperation_t transA,
cusparseOperation_t transB,
int mb,
int n,
int nnzb,
const cusparseMatDescr_t descrA,
float* bsrSortedVal,
const int* bsrSortedRowPtr,
const int* bsrSortedColInd,
int blockSize,
bsrsm2Info_t info,
size_t* pBufferSize);
cusparseStatus_t CUSPARSEAPI
cusparseDbsrsm2_bufferSizeExt(cusparseHandle_t handle,
cusparseDirection_t dirA,
cusparseOperation_t transA,
cusparseOperation_t transB,
int mb,
int n,
int nnzb,
const cusparseMatDescr_t descrA,
double* bsrSortedVal,
const int* bsrSortedRowPtr,
const int* bsrSortedColInd,
int blockSize,
bsrsm2Info_t info,
size_t* pBufferSize);
cusparseStatus_t CUSPARSEAPI
cusparseCbsrsm2_bufferSizeExt(cusparseHandle_t handle,
cusparseDirection_t dirA,
cusparseOperation_t transA,
cusparseOperation_t transB,
int mb,
int n,
int nnzb,
const cusparseMatDescr_t descrA,
cuComplex* bsrSortedVal,
const int* bsrSortedRowPtr,
const int* bsrSortedColInd,
int blockSize,
bsrsm2Info_t info,
size_t* pBufferSize);
cusparseStatus_t CUSPARSEAPI
cusparseZbsrsm2_bufferSizeExt(cusparseHandle_t handle,
cusparseDirection_t dirA,
cusparseOperation_t transA,
cusparseOperation_t transB,
int mb,
int n,
int nnzb,
const cusparseMatDescr_t descrA,
cuDoubleComplex* bsrSortedVal,
const int* bsrSortedRowPtr,
const int* bsrSortedColInd,
int blockSize,
bsrsm2Info_t info,
size_t* pBufferSize);
cusparseStatus_t CUSPARSEAPI
cusparseSbsrsm2_analysis(cusparseHandle_t handle,
cusparseDirection_t dirA,
cusparseOperation_t transA,
cusparseOperation_t transXY,
int mb,
int n,
int nnzb,
const cusparseMatDescr_t descrA,
const float* bsrSortedVal,
const int* bsrSortedRowPtr,
const int* bsrSortedColInd,
int blockSize,
bsrsm2Info_t info,
cusparseSolvePolicy_t policy,
void* pBuffer);
cusparseStatus_t CUSPARSEAPI
cusparseDbsrsm2_analysis(cusparseHandle_t handle,
cusparseDirection_t dirA,
cusparseOperation_t transA,
cusparseOperation_t transXY,
int mb,
int n,
int nnzb,
const cusparseMatDescr_t descrA,
const double* bsrSortedVal,
const int* bsrSortedRowPtr,
const int* bsrSortedColInd,
int blockSize,
bsrsm2Info_t info,
cusparseSolvePolicy_t policy,
void* pBuffer);
cusparseStatus_t CUSPARSEAPI
cusparseCbsrsm2_analysis(cusparseHandle_t handle,
cusparseDirection_t dirA,
cusparseOperation_t transA,
cusparseOperation_t transXY,
int mb,
int n,
int nnzb,
const cusparseMatDescr_t descrA,
const cuComplex* bsrSortedVal,
const int* bsrSortedRowPtr,
const int* bsrSortedColInd,
int blockSize,
bsrsm2Info_t info,
cusparseSolvePolicy_t policy,
void* pBuffer);
cusparseStatus_t CUSPARSEAPI
cusparseZbsrsm2_analysis(cusparseHandle_t handle,
cusparseDirection_t dirA,
cusparseOperation_t transA,
cusparseOperation_t transXY,
int mb,
int n,
int nnzb,
const cusparseMatDescr_t descrA,
const cuDoubleComplex* bsrSortedVal,
const int* bsrSortedRowPtr,
const int* bsrSortedColInd,
int blockSize,
bsrsm2Info_t info,
cusparseSolvePolicy_t policy,
void* pBuffer);
cusparseStatus_t CUSPARSEAPI
cusparseSbsrsm2_solve(cusparseHandle_t handle,
cusparseDirection_t dirA,
cusparseOperation_t transA,
cusparseOperation_t transXY,
int mb,
int n,
int nnzb,
const float* alpha,
const cusparseMatDescr_t descrA,
const float* bsrSortedVal,
const int* bsrSortedRowPtr,
const int* bsrSortedColInd,
int blockSize,
bsrsm2Info_t info,
const float* B,
int ldb,
float* X,
int ldx,
cusparseSolvePolicy_t policy,
void* pBuffer);
cusparseStatus_t CUSPARSEAPI
cusparseDbsrsm2_solve(cusparseHandle_t handle,
cusparseDirection_t dirA,
cusparseOperation_t transA,
cusparseOperation_t transXY,
int mb,
int n,
int nnzb,
const double* alpha,
const cusparseMatDescr_t descrA,
const double* bsrSortedVal,
const int* bsrSortedRowPtr,
const int* bsrSortedColInd,
int blockSize,
bsrsm2Info_t info,
const double* B,
int ldb,
double* X,
int ldx,
cusparseSolvePolicy_t policy,
void* pBuffer);
cusparseStatus_t CUSPARSEAPI
cusparseCbsrsm2_solve(cusparseHandle_t handle,
cusparseDirection_t dirA,
cusparseOperation_t transA,
cusparseOperation_t transXY,
int mb,
int n,
int nnzb,
const cuComplex* alpha,
const cusparseMatDescr_t descrA,
const cuComplex* bsrSortedVal,
const int* bsrSortedRowPtr,
const int* bsrSortedColInd,
int blockSize,
bsrsm2Info_t info,
const cuComplex* B,
int ldb,
cuComplex* X,
int ldx,
cusparseSolvePolicy_t policy,
void* pBuffer);
cusparseStatus_t CUSPARSEAPI
cusparseZbsrsm2_solve(cusparseHandle_t handle,
cusparseDirection_t dirA,
cusparseOperation_t transA,
cusparseOperation_t transXY,
int mb,
int n,
int nnzb,
const cuDoubleComplex* alpha,
const cusparseMatDescr_t descrA,
const cuDoubleComplex* bsrSortedVal,
const int* bsrSortedRowPtr,
const int* bsrSortedColInd,
int blockSize,
bsrsm2Info_t info,
const cuDoubleComplex* B,
int ldb,
cuDoubleComplex* X,
int ldx,
cusparseSolvePolicy_t policy,
void* pBuffer);
//##############################################################################
//# PRECONDITIONERS
//##############################################################################
cusparseStatus_t CUSPARSEAPI
cusparseScsrilu02_numericBoost(cusparseHandle_t handle,
csrilu02Info_t info,
int enable_boost,
double* tol,
float* boost_val);
cusparseStatus_t CUSPARSEAPI
cusparseDcsrilu02_numericBoost(cusparseHandle_t handle,
csrilu02Info_t info,
int enable_boost,
double* tol,
double* boost_val);
cusparseStatus_t CUSPARSEAPI
cusparseCcsrilu02_numericBoost(cusparseHandle_t handle,
csrilu02Info_t info,
int enable_boost,
double* tol,
cuComplex* boost_val);
cusparseStatus_t CUSPARSEAPI
cusparseZcsrilu02_numericBoost(cusparseHandle_t handle,
csrilu02Info_t info,
int enable_boost,
double* tol,
cuDoubleComplex* boost_val);
cusparseStatus_t CUSPARSEAPI
cusparseXcsrilu02_zeroPivot(cusparseHandle_t handle,
csrilu02Info_t info,
int* position);
cusparseStatus_t CUSPARSEAPI
cusparseScsrilu02_bufferSize(cusparseHandle_t handle,
int m,
int nnz,
const cusparseMatDescr_t descrA,
float* csrSortedValA,
const int* csrSortedRowPtrA,
const int* csrSortedColIndA,
csrilu02Info_t info,
int* pBufferSizeInBytes);
cusparseStatus_t CUSPARSEAPI
cusparseDcsrilu02_bufferSize(cusparseHandle_t handle,
int m,
int nnz,
const cusparseMatDescr_t descrA,
double* csrSortedValA,
const int* csrSortedRowPtrA,
const int* csrSortedColIndA,
csrilu02Info_t info,
int* pBufferSizeInBytes);
cusparseStatus_t CUSPARSEAPI
cusparseCcsrilu02_bufferSize(cusparseHandle_t handle,
int m,
int nnz,
const cusparseMatDescr_t descrA,
cuComplex* csrSortedValA,
const int* csrSortedRowPtrA,
const int* csrSortedColIndA,
csrilu02Info_t info,
int* pBufferSizeInBytes);
cusparseStatus_t CUSPARSEAPI
cusparseZcsrilu02_bufferSize(cusparseHandle_t handle,
int m,
int nnz,
const cusparseMatDescr_t descrA,
cuDoubleComplex* csrSortedValA,
const int* csrSortedRowPtrA,
const int* csrSortedColIndA,
csrilu02Info_t info,
int* pBufferSizeInBytes);
cusparseStatus_t CUSPARSEAPI
cusparseScsrilu02_bufferSizeExt(cusparseHandle_t handle,
int m,
int nnz,
const cusparseMatDescr_t descrA,
float* csrSortedVal,
const int* csrSortedRowPtr,
const int* csrSortedColInd,
csrilu02Info_t info,
size_t* pBufferSize);
cusparseStatus_t CUSPARSEAPI
cusparseDcsrilu02_bufferSizeExt(cusparseHandle_t handle,
int m,
int nnz,
const cusparseMatDescr_t descrA,
double* csrSortedVal,
const int* csrSortedRowPtr,
const int* csrSortedColInd,
csrilu02Info_t info,
size_t* pBufferSize);
cusparseStatus_t CUSPARSEAPI
cusparseCcsrilu02_bufferSizeExt(cusparseHandle_t handle,
int m,
int nnz,
const cusparseMatDescr_t descrA,
cuComplex* csrSortedVal,
const int* csrSortedRowPtr,
const int* csrSortedColInd,
csrilu02Info_t info,
size_t* pBufferSize);
cusparseStatus_t CUSPARSEAPI
cusparseZcsrilu02_bufferSizeExt(cusparseHandle_t handle,
int m,
int nnz,
const cusparseMatDescr_t descrA,
cuDoubleComplex* csrSortedVal,
const int* csrSortedRowPtr,
const int* csrSortedColInd,
csrilu02Info_t info,
size_t* pBufferSize);
cusparseStatus_t CUSPARSEAPI
cusparseScsrilu02_analysis(cusparseHandle_t handle,
int m,
int nnz,
const cusparseMatDescr_t descrA,
const float* csrSortedValA,
const int* csrSortedRowPtrA,
const int* csrSortedColIndA,
csrilu02Info_t info,
cusparseSolvePolicy_t policy,
void* pBuffer);
cusparseStatus_t CUSPARSEAPI
cusparseDcsrilu02_analysis(cusparseHandle_t handle,
int m,
int nnz,
const cusparseMatDescr_t descrA,
const double* csrSortedValA,
const int* csrSortedRowPtrA,
const int* csrSortedColIndA,
csrilu02Info_t info,
cusparseSolvePolicy_t policy,
void* pBuffer);
cusparseStatus_t CUSPARSEAPI
cusparseCcsrilu02_analysis(cusparseHandle_t handle,
int m,
int nnz,
const cusparseMatDescr_t descrA,
const cuComplex* csrSortedValA,
const int* csrSortedRowPtrA,
const int* csrSortedColIndA,
csrilu02Info_t info,
cusparseSolvePolicy_t policy,
void* pBuffer);
cusparseStatus_t CUSPARSEAPI
cusparseZcsrilu02_analysis(cusparseHandle_t handle,
int m,
int nnz,
const cusparseMatDescr_t descrA,
const cuDoubleComplex* csrSortedValA,
const int* csrSortedRowPtrA,
const int* csrSortedColIndA,
csrilu02Info_t info,
cusparseSolvePolicy_t policy,
void* pBuffer);
cusparseStatus_t CUSPARSEAPI
cusparseScsrilu02(cusparseHandle_t handle,
int m,
int nnz,
const cusparseMatDescr_t descrA,
float* csrSortedValA_valM,
const int* csrSortedRowPtrA,
const int* csrSortedColIndA,
csrilu02Info_t info,
cusparseSolvePolicy_t policy,
void* pBuffer);
cusparseStatus_t CUSPARSEAPI
cusparseDcsrilu02(cusparseHandle_t handle,
int m,
int nnz,
const cusparseMatDescr_t descrA,
double* csrSortedValA_valM,
const int* csrSortedRowPtrA,
const int* csrSortedColIndA,
csrilu02Info_t info,
cusparseSolvePolicy_t policy,
void* pBuffer);
cusparseStatus_t CUSPARSEAPI
cusparseCcsrilu02(cusparseHandle_t handle,
int m,
int nnz,
const cusparseMatDescr_t descrA,
cuComplex* csrSortedValA_valM,
const int* csrSortedRowPtrA,
const int* csrSortedColIndA,
csrilu02Info_t info,
cusparseSolvePolicy_t policy,
void* pBuffer);
cusparseStatus_t CUSPARSEAPI
cusparseZcsrilu02(cusparseHandle_t handle,
int m,
int nnz,
const cusparseMatDescr_t descrA,
cuDoubleComplex* csrSortedValA_valM,
const int* csrSortedRowPtrA,
const int* csrSortedColIndA,
csrilu02Info_t info,
cusparseSolvePolicy_t policy,
void* pBuffer);
cusparseStatus_t CUSPARSEAPI
cusparseSbsrilu02_numericBoost(cusparseHandle_t handle,
bsrilu02Info_t info,
int enable_boost,
double* tol,
float* boost_val);
cusparseStatus_t CUSPARSEAPI
cusparseDbsrilu02_numericBoost(cusparseHandle_t handle,
bsrilu02Info_t info,
int enable_boost,
double* tol,
double* boost_val);
cusparseStatus_t CUSPARSEAPI
cusparseCbsrilu02_numericBoost(cusparseHandle_t handle,
bsrilu02Info_t info,
int enable_boost,
double* tol,
cuComplex* boost_val);
cusparseStatus_t CUSPARSEAPI
cusparseZbsrilu02_numericBoost(cusparseHandle_t handle,
bsrilu02Info_t info,
int enable_boost,
double* tol,
cuDoubleComplex* boost_val);
cusparseStatus_t CUSPARSEAPI
cusparseXbsrilu02_zeroPivot(cusparseHandle_t handle,
bsrilu02Info_t info,
int* position);
cusparseStatus_t CUSPARSEAPI
cusparseSbsrilu02_bufferSize(cusparseHandle_t handle,
cusparseDirection_t dirA,
int mb,
int nnzb,
const cusparseMatDescr_t descrA,
float* bsrSortedVal,
const int* bsrSortedRowPtr,
const int* bsrSortedColInd,
int blockDim,
bsrilu02Info_t info,
int* pBufferSizeInBytes);
cusparseStatus_t CUSPARSEAPI
cusparseDbsrilu02_bufferSize(cusparseHandle_t handle,
cusparseDirection_t dirA,
int mb,
int nnzb,
const cusparseMatDescr_t descrA,
double* bsrSortedVal,
const int* bsrSortedRowPtr,
const int* bsrSortedColInd,
int blockDim,
bsrilu02Info_t info,
int* pBufferSizeInBytes);
cusparseStatus_t CUSPARSEAPI
cusparseCbsrilu02_bufferSize(cusparseHandle_t handle,
cusparseDirection_t dirA,
int mb,
int nnzb,
const cusparseMatDescr_t descrA,
cuComplex* bsrSortedVal,
const int* bsrSortedRowPtr,
const int* bsrSortedColInd,
int blockDim,
bsrilu02Info_t info,
int* pBufferSizeInBytes);
cusparseStatus_t CUSPARSEAPI
cusparseZbsrilu02_bufferSize(cusparseHandle_t handle,
cusparseDirection_t dirA,
int mb,
int nnzb,
const cusparseMatDescr_t descrA,
cuDoubleComplex* bsrSortedVal,
const int* bsrSortedRowPtr,
const int* bsrSortedColInd,
int blockDim,
bsrilu02Info_t info,
int* pBufferSizeInBytes);
cusparseStatus_t CUSPARSEAPI
cusparseSbsrilu02_bufferSizeExt(cusparseHandle_t handle,
cusparseDirection_t dirA,
int mb,
int nnzb,
const cusparseMatDescr_t descrA,
float* bsrSortedVal,
const int* bsrSortedRowPtr,
const int* bsrSortedColInd,
int blockSize,
bsrilu02Info_t info,
size_t* pBufferSize);
cusparseStatus_t CUSPARSEAPI
cusparseDbsrilu02_bufferSizeExt(cusparseHandle_t handle,
cusparseDirection_t dirA,
int mb,
int nnzb,
const cusparseMatDescr_t descrA,
double* bsrSortedVal,
const int* bsrSortedRowPtr,
const int* bsrSortedColInd,
int blockSize,
bsrilu02Info_t info,
size_t* pBufferSize);
cusparseStatus_t CUSPARSEAPI
cusparseCbsrilu02_bufferSizeExt(cusparseHandle_t handle,
cusparseDirection_t dirA,
int mb,
int nnzb,
const cusparseMatDescr_t descrA,
cuComplex* bsrSortedVal,
const int* bsrSortedRowPtr,
const int* bsrSortedColInd,
int blockSize,
bsrilu02Info_t info,
size_t* pBufferSize);
cusparseStatus_t CUSPARSEAPI
cusparseZbsrilu02_bufferSizeExt(cusparseHandle_t handle,
cusparseDirection_t dirA,
int mb,
int nnzb,
const cusparseMatDescr_t descrA,
cuDoubleComplex* bsrSortedVal,
const int* bsrSortedRowPtr,
const int* bsrSortedColInd,
int blockSize,
bsrilu02Info_t info,
size_t* pBufferSize);
cusparseStatus_t CUSPARSEAPI
cusparseSbsrilu02_analysis(cusparseHandle_t handle,
cusparseDirection_t dirA,
int mb,
int nnzb,
const cusparseMatDescr_t descrA,
float* bsrSortedVal,
const int* bsrSortedRowPtr,
const int* bsrSortedColInd,
int blockDim,
bsrilu02Info_t info,
cusparseSolvePolicy_t policy,
void* pBuffer);
cusparseStatus_t CUSPARSEAPI
cusparseDbsrilu02_analysis(cusparseHandle_t handle,
cusparseDirection_t dirA,
int mb,
int nnzb,
const cusparseMatDescr_t descrA,
double* bsrSortedVal,
const int* bsrSortedRowPtr,
const int* bsrSortedColInd,
int blockDim,
bsrilu02Info_t info,
cusparseSolvePolicy_t policy,
void* pBuffer);
cusparseStatus_t CUSPARSEAPI
cusparseCbsrilu02_analysis(cusparseHandle_t handle,
cusparseDirection_t dirA,
int mb,
int nnzb,
const cusparseMatDescr_t descrA,
cuComplex* bsrSortedVal,
const int* bsrSortedRowPtr,
const int* bsrSortedColInd,
int blockDim,
bsrilu02Info_t info,
cusparseSolvePolicy_t policy,
void* pBuffer);
cusparseStatus_t CUSPARSEAPI
cusparseZbsrilu02_analysis(cusparseHandle_t handle,
cusparseDirection_t dirA,
int mb,
int nnzb,
const cusparseMatDescr_t descrA,
cuDoubleComplex* bsrSortedVal,
const int* bsrSortedRowPtr,
const int* bsrSortedColInd,
int blockDim,
bsrilu02Info_t info,
cusparseSolvePolicy_t policy,
void* pBuffer);
cusparseStatus_t CUSPARSEAPI
cusparseSbsrilu02(cusparseHandle_t handle,
cusparseDirection_t dirA,
int mb,
int nnzb,
const cusparseMatDescr_t descrA,
float* bsrSortedVal,
const int* bsrSortedRowPtr,
const int* bsrSortedColInd,
int blockDim,
bsrilu02Info_t info,
cusparseSolvePolicy_t policy,
void* pBuffer);
cusparseStatus_t CUSPARSEAPI
cusparseDbsrilu02(cusparseHandle_t handle,
cusparseDirection_t dirA,
int mb,
int nnzb,
const cusparseMatDescr_t descrA,
double* bsrSortedVal,
const int* bsrSortedRowPtr,
const int* bsrSortedColInd,
int blockDim,
bsrilu02Info_t info,
cusparseSolvePolicy_t policy,
void* pBuffer);
cusparseStatus_t CUSPARSEAPI
cusparseCbsrilu02(cusparseHandle_t handle,
cusparseDirection_t dirA,
int mb,
int nnzb,
const cusparseMatDescr_t descrA,
cuComplex* bsrSortedVal,
const int* bsrSortedRowPtr,
const int* bsrSortedColInd,
int blockDim,
bsrilu02Info_t info,
cusparseSolvePolicy_t policy,
void* pBuffer);
cusparseStatus_t CUSPARSEAPI
cusparseZbsrilu02(cusparseHandle_t handle,
cusparseDirection_t dirA,
int mb,
int nnzb,
const cusparseMatDescr_t descrA,
cuDoubleComplex* bsrSortedVal,
const int* bsrSortedRowPtr,
const int* bsrSortedColInd,
int blockDim,
bsrilu02Info_t info,
cusparseSolvePolicy_t policy,
void* pBuffer);
cusparseStatus_t CUSPARSEAPI
cusparseXcsric02_zeroPivot(cusparseHandle_t handle,
csric02Info_t info,
int* position);
cusparseStatus_t CUSPARSEAPI
cusparseScsric02_bufferSize(cusparseHandle_t handle,
int m,
int nnz,
const cusparseMatDescr_t descrA,
float* csrSortedValA,
const int* csrSortedRowPtrA,
const int* csrSortedColIndA,
csric02Info_t info,
int* pBufferSizeInBytes);
cusparseStatus_t CUSPARSEAPI
cusparseDcsric02_bufferSize(cusparseHandle_t handle,
int m,
int nnz,
const cusparseMatDescr_t descrA,
double* csrSortedValA,
const int* csrSortedRowPtrA,
const int* csrSortedColIndA,
csric02Info_t info,
int* pBufferSizeInBytes);
cusparseStatus_t CUSPARSEAPI
cusparseCcsric02_bufferSize(cusparseHandle_t handle,
int m,
int nnz,
const cusparseMatDescr_t descrA,
cuComplex* csrSortedValA,
const int* csrSortedRowPtrA,
const int* csrSortedColIndA,
csric02Info_t info,
int* pBufferSizeInBytes);
cusparseStatus_t CUSPARSEAPI
cusparseZcsric02_bufferSize(cusparseHandle_t handle,
int m,
int nnz,
const cusparseMatDescr_t descrA,
cuDoubleComplex* csrSortedValA,
const int* csrSortedRowPtrA,
const int* csrSortedColIndA,
csric02Info_t info,
int* pBufferSizeInBytes);
cusparseStatus_t CUSPARSEAPI
cusparseScsric02_bufferSizeExt(cusparseHandle_t handle,
int m,
int nnz,
const cusparseMatDescr_t descrA,
float* csrSortedVal,
const int* csrSortedRowPtr,
const int* csrSortedColInd,
csric02Info_t info,
size_t* pBufferSize);
cusparseStatus_t CUSPARSEAPI
cusparseDcsric02_bufferSizeExt(cusparseHandle_t handle,
int m,
int nnz,
const cusparseMatDescr_t descrA,
double* csrSortedVal,
const int* csrSortedRowPtr,
const int* csrSortedColInd,
csric02Info_t info,
size_t* pBufferSize);
cusparseStatus_t CUSPARSEAPI
cusparseCcsric02_bufferSizeExt(cusparseHandle_t handle,
int m,
int nnz,
const cusparseMatDescr_t descrA,
cuComplex* csrSortedVal,
const int* csrSortedRowPtr,
const int* csrSortedColInd,
csric02Info_t info,
size_t* pBufferSize);
cusparseStatus_t CUSPARSEAPI
cusparseZcsric02_bufferSizeExt(cusparseHandle_t handle,
int m,
int nnz,
const cusparseMatDescr_t descrA,
cuDoubleComplex* csrSortedVal,
const int* csrSortedRowPtr,
const int* csrSortedColInd,
csric02Info_t info,
size_t* pBufferSize);
cusparseStatus_t CUSPARSEAPI
cusparseScsric02_analysis(cusparseHandle_t handle,
int m,
int nnz,
const cusparseMatDescr_t descrA,
const float* csrSortedValA,
const int* csrSortedRowPtrA,
const int* csrSortedColIndA,
csric02Info_t info,
cusparseSolvePolicy_t policy,
void* pBuffer);
cusparseStatus_t CUSPARSEAPI
cusparseDcsric02_analysis(cusparseHandle_t handle,
int m,
int nnz,
const cusparseMatDescr_t descrA,
const double* csrSortedValA,
const int* csrSortedRowPtrA,
const int* csrSortedColIndA,
csric02Info_t info,
cusparseSolvePolicy_t policy,
void* pBuffer);
cusparseStatus_t CUSPARSEAPI
cusparseCcsric02_analysis(cusparseHandle_t handle,
int m,
int nnz,
const cusparseMatDescr_t descrA,
const cuComplex* csrSortedValA,
const int* csrSortedRowPtrA,
const int* csrSortedColIndA,
csric02Info_t info,
cusparseSolvePolicy_t policy,
void* pBuffer);
cusparseStatus_t CUSPARSEAPI
cusparseZcsric02_analysis(cusparseHandle_t handle,
int m,
int nnz,
const cusparseMatDescr_t descrA,
const cuDoubleComplex* csrSortedValA,
const int* csrSortedRowPtrA,
const int* csrSortedColIndA,
csric02Info_t info,
cusparseSolvePolicy_t policy,
void* pBuffer);
cusparseStatus_t CUSPARSEAPI
cusparseScsric02(cusparseHandle_t handle,
int m,
int nnz,
const cusparseMatDescr_t descrA,
float* csrSortedValA_valM,
const int* csrSortedRowPtrA,
const int* csrSortedColIndA,
csric02Info_t info,
cusparseSolvePolicy_t policy,
void* pBuffer);
cusparseStatus_t CUSPARSEAPI
cusparseDcsric02(cusparseHandle_t handle,
int m,
int nnz,
const cusparseMatDescr_t descrA,
double* csrSortedValA_valM,
const int* csrSortedRowPtrA,
const int* csrSortedColIndA,
csric02Info_t info,
cusparseSolvePolicy_t policy,
void* pBuffer);
cusparseStatus_t CUSPARSEAPI
cusparseCcsric02(cusparseHandle_t handle,
int m,
int nnz,
const cusparseMatDescr_t descrA,
cuComplex* csrSortedValA_valM,
const int* csrSortedRowPtrA,
const int* csrSortedColIndA,
csric02Info_t info,
cusparseSolvePolicy_t policy,
void* pBuffer);
cusparseStatus_t CUSPARSEAPI
cusparseZcsric02(cusparseHandle_t handle,
int m,
int nnz,
const cusparseMatDescr_t descrA,
cuDoubleComplex* csrSortedValA_valM,
const int* csrSortedRowPtrA,
const int* csrSortedColIndA,
csric02Info_t info,
cusparseSolvePolicy_t policy,
void* pBuffer);
cusparseStatus_t CUSPARSEAPI
cusparseXbsric02_zeroPivot(cusparseHandle_t handle,
bsric02Info_t info,
int* position);
cusparseStatus_t CUSPARSEAPI
cusparseSbsric02_bufferSize(cusparseHandle_t handle,
cusparseDirection_t dirA,
int mb,
int nnzb,
const cusparseMatDescr_t descrA,
float* bsrSortedVal,
const int* bsrSortedRowPtr,
const int* bsrSortedColInd,
int blockDim,
bsric02Info_t info,
int* pBufferSizeInBytes);
cusparseStatus_t CUSPARSEAPI
cusparseDbsric02_bufferSize(cusparseHandle_t handle,
cusparseDirection_t dirA,
int mb,
int nnzb,
const cusparseMatDescr_t descrA,
double* bsrSortedVal,
const int* bsrSortedRowPtr,
const int* bsrSortedColInd,
int blockDim,
bsric02Info_t info,
int* pBufferSizeInBytes);
cusparseStatus_t CUSPARSEAPI
cusparseCbsric02_bufferSize(cusparseHandle_t handle,
cusparseDirection_t dirA,
int mb,
int nnzb,
const cusparseMatDescr_t descrA,
cuComplex* bsrSortedVal,
const int* bsrSortedRowPtr,
const int* bsrSortedColInd,
int blockDim,
bsric02Info_t info,
int* pBufferSizeInBytes);
cusparseStatus_t CUSPARSEAPI
cusparseZbsric02_bufferSize(cusparseHandle_t handle,
cusparseDirection_t dirA,
int mb,
int nnzb,
const cusparseMatDescr_t descrA,
cuDoubleComplex* bsrSortedVal,
const int* bsrSortedRowPtr,
const int* bsrSortedColInd,
int blockDim,
bsric02Info_t info,
int* pBufferSizeInBytes);
cusparseStatus_t CUSPARSEAPI
cusparseSbsric02_bufferSizeExt(cusparseHandle_t handle,
cusparseDirection_t dirA,
int mb,
int nnzb,
const cusparseMatDescr_t descrA,
float* bsrSortedVal,
const int* bsrSortedRowPtr,
const int* bsrSortedColInd,
int blockSize,
bsric02Info_t info,
size_t* pBufferSize);
cusparseStatus_t CUSPARSEAPI
cusparseDbsric02_bufferSizeExt(cusparseHandle_t handle,
cusparseDirection_t dirA,
int mb,
int nnzb,
const cusparseMatDescr_t descrA,
double* bsrSortedVal,
const int* bsrSortedRowPtr,
const int* bsrSortedColInd,
int blockSize,
bsric02Info_t info,
size_t* pBufferSize);
cusparseStatus_t CUSPARSEAPI
cusparseCbsric02_bufferSizeExt(cusparseHandle_t handle,
cusparseDirection_t dirA,
int mb,
int nnzb,
const cusparseMatDescr_t descrA,
cuComplex* bsrSortedVal,
const int* bsrSortedRowPtr,
const int* bsrSortedColInd,
int blockSize,
bsric02Info_t info,
size_t* pBufferSize);
cusparseStatus_t CUSPARSEAPI
cusparseZbsric02_bufferSizeExt(cusparseHandle_t handle,
cusparseDirection_t dirA,
int mb,
int nnzb,
const cusparseMatDescr_t descrA,
cuDoubleComplex* bsrSortedVal,
const int* bsrSortedRowPtr,
const int* bsrSortedColInd,
int blockSize,
bsric02Info_t info,
size_t* pBufferSize);
cusparseStatus_t CUSPARSEAPI
cusparseSbsric02_analysis(cusparseHandle_t handle,
cusparseDirection_t dirA,
int mb,
int nnzb,
const cusparseMatDescr_t descrA,
const float* bsrSortedVal,
const int* bsrSortedRowPtr,
const int* bsrSortedColInd,
int blockDim,
bsric02Info_t info,
cusparseSolvePolicy_t policy,
void* pInputBuffer);
cusparseStatus_t CUSPARSEAPI
cusparseDbsric02_analysis(cusparseHandle_t handle,
cusparseDirection_t dirA,
int mb,
int nnzb,
const cusparseMatDescr_t descrA,
const double* bsrSortedVal,
const int* bsrSortedRowPtr,
const int* bsrSortedColInd,
int blockDim,
bsric02Info_t info,
cusparseSolvePolicy_t policy,
void* pInputBuffer);
cusparseStatus_t CUSPARSEAPI
cusparseCbsric02_analysis(cusparseHandle_t handle,
cusparseDirection_t dirA,
int mb,
int nnzb,
const cusparseMatDescr_t descrA,
const cuComplex* bsrSortedVal,
const int* bsrSortedRowPtr,
const int* bsrSortedColInd,
int blockDim,
bsric02Info_t info,
cusparseSolvePolicy_t policy,
void* pInputBuffer);
cusparseStatus_t CUSPARSEAPI
cusparseZbsric02_analysis(cusparseHandle_t handle,
cusparseDirection_t dirA,
int mb,
int nnzb,
const cusparseMatDescr_t descrA,
const cuDoubleComplex* bsrSortedVal,
const int* bsrSortedRowPtr,
const int* bsrSortedColInd,
int blockDim,
bsric02Info_t info,
cusparseSolvePolicy_t policy,
void* pInputBuffer);
cusparseStatus_t CUSPARSEAPI
cusparseSbsric02(cusparseHandle_t handle,
cusparseDirection_t dirA,
int mb,
int nnzb,
const cusparseMatDescr_t descrA,
float* bsrSortedVal,
const int* bsrSortedRowPtr,
const int* bsrSortedColInd,
int blockDim,
bsric02Info_t info,
cusparseSolvePolicy_t policy,
void* pBuffer);
cusparseStatus_t CUSPARSEAPI
cusparseDbsric02(cusparseHandle_t handle,
cusparseDirection_t dirA,
int mb,
int nnzb,
const cusparseMatDescr_t descrA,
double* bsrSortedVal,
const int* bsrSortedRowPtr,
const int* bsrSortedColInd,
int blockDim,
bsric02Info_t info,
cusparseSolvePolicy_t policy,
void* pBuffer);
cusparseStatus_t CUSPARSEAPI
cusparseCbsric02(cusparseHandle_t handle,
cusparseDirection_t dirA,
int mb,
int nnzb,
const cusparseMatDescr_t descrA,
cuComplex* bsrSortedVal,
const int* bsrSortedRowPtr,
const int*
bsrSortedColInd,
int blockDim,
bsric02Info_t info,
cusparseSolvePolicy_t policy,
void* pBuffer);
cusparseStatus_t CUSPARSEAPI
cusparseZbsric02(cusparseHandle_t handle,
cusparseDirection_t dirA,
int mb,
int nnzb,
const cusparseMatDescr_t descrA,
cuDoubleComplex* bsrSortedVal,
const int* bsrSortedRowPtr,
const int* bsrSortedColInd,
int blockDim,
bsric02Info_t info,
cusparseSolvePolicy_t policy,
void* pBuffer);
cusparseStatus_t CUSPARSEAPI
cusparseSgtsv2_bufferSizeExt(cusparseHandle_t handle,
int m,
int n,
const float* dl,
const float* d,
const float* du,
const float* B,
int ldb,
size_t* bufferSizeInBytes);
cusparseStatus_t CUSPARSEAPI
cusparseDgtsv2_bufferSizeExt(cusparseHandle_t handle,
int m,
int n,
const double* dl,
const double* d,
const double* du,
const double* B,
int ldb,
size_t* bufferSizeInBytes);
cusparseStatus_t CUSPARSEAPI
cusparseCgtsv2_bufferSizeExt(cusparseHandle_t handle,
int m,
int n,
const cuComplex* dl,
const cuComplex* d,
const cuComplex* du,
const cuComplex* B,
int ldb,
size_t* bufferSizeInBytes);
cusparseStatus_t CUSPARSEAPI
cusparseZgtsv2_bufferSizeExt(cusparseHandle_t handle,
int m,
int n,
const cuDoubleComplex* dl,
const cuDoubleComplex* d,
const cuDoubleComplex* du,
const cuDoubleComplex* B,
int ldb,
size_t* bufferSizeInBytes);
cusparseStatus_t CUSPARSEAPI
cusparseSgtsv2(cusparseHandle_t handle,
int m,
int n,
const float* dl,
const float* d,
const float* du,
float* B,
int ldb,
void* pBuffer);
cusparseStatus_t CUSPARSEAPI
cusparseDgtsv2(cusparseHandle_t handle,
int m,
int n,
const double* dl,
const double* d,
const double* du,
double* B,
int ldb,
void* pBuffer);
cusparseStatus_t CUSPARSEAPI
cusparseCgtsv2(cusparseHandle_t handle,
int m,
int n,
const cuComplex* dl,
const cuComplex* d,
const cuComplex* du,
cuComplex* B,
int ldb,
void* pBuffer);
cusparseStatus_t CUSPARSEAPI
cusparseZgtsv2(cusparseHandle_t handle,
int m,
int n,
const cuDoubleComplex* dl,
const cuDoubleComplex* d,
const cuDoubleComplex* du,
cuDoubleComplex* B,
int ldb,
void* pBuffer);
cusparseStatus_t CUSPARSEAPI
cusparseSgtsv2_nopivot_bufferSizeExt(cusparseHandle_t handle,
int m,
int n,
const float* dl,
const float* d,
const float* du,
const float* B,
int ldb,
size_t* bufferSizeInBytes);
cusparseStatus_t CUSPARSEAPI
cusparseDgtsv2_nopivot_bufferSizeExt(cusparseHandle_t handle,
int m,
int n,
const double* dl,
const double* d,
const double* du,
const double* B,
int ldb,
size_t* bufferSizeInBytes);
cusparseStatus_t CUSPARSEAPI
cusparseCgtsv2_nopivot_bufferSizeExt(cusparseHandle_t handle,
int m,
int n,
const cuComplex* dl,
const cuComplex* d,
const cuComplex* du,
const cuComplex* B,
int ldb,
size_t* bufferSizeInBytes);
cusparseStatus_t CUSPARSEAPI
cusparseZgtsv2_nopivot_bufferSizeExt(cusparseHandle_t handle,
int m,
int n,
const cuDoubleComplex* dl,
const cuDoubleComplex* d,
const cuDoubleComplex* du,
const cuDoubleComplex* B,
int ldb,
size_t* bufferSizeInBytes);
cusparseStatus_t CUSPARSEAPI
cusparseSgtsv2_nopivot(cusparseHandle_t handle,
int m,
int n,
const float* dl,
const float* d,
const float* du,
float* B,
int ldb,
void* pBuffer);
cusparseStatus_t CUSPARSEAPI
cusparseDgtsv2_nopivot(cusparseHandle_t handle,
int m,
int n,
const double* dl,
const double* d,
const double* du,
double* B,
int ldb,
void* pBuffer);
cusparseStatus_t CUSPARSEAPI
cusparseCgtsv2_nopivot(cusparseHandle_t handle,
int m,
int n,
const cuComplex* dl,
const cuComplex* d,
const cuComplex* du,
cuComplex* B,
int ldb,
void* pBuffer);
cusparseStatus_t CUSPARSEAPI
cusparseZgtsv2_nopivot(cusparseHandle_t handle,
int m,
int n,
const cuDoubleComplex* dl,
const cuDoubleComplex* d,
const cuDoubleComplex* du,
cuDoubleComplex* B,
int ldb,
void* pBuffer);
cusparseStatus_t CUSPARSEAPI
cusparseSgtsv2StridedBatch_bufferSizeExt(cusparseHandle_t handle,
int m,
const float* dl,
const float* d,
const float* du,
const float* x,
int batchCount,
int batchStride,
size_t* bufferSizeInBytes);
cusparseStatus_t CUSPARSEAPI
cusparseDgtsv2StridedBatch_bufferSizeExt(cusparseHandle_t handle,
int m,
const double* dl,
const double* d,
const double* du,
const double* x,
int batchCount,
int batchStride,
size_t* bufferSizeInBytes);
cusparseStatus_t CUSPARSEAPI
cusparseCgtsv2StridedBatch_bufferSizeExt(cusparseHandle_t handle,
int m,
const cuComplex* dl,
const cuComplex* d,
const cuComplex* du,
const cuComplex* x,
int batchCount,
int batchStride,
size_t* bufferSizeInBytes);
cusparseStatus_t CUSPARSEAPI
cusparseZgtsv2StridedBatch_bufferSizeExt(cusparseHandle_t handle,
int m,
const cuDoubleComplex* dl,
const cuDoubleComplex* d,
const cuDoubleComplex* du,
const cuDoubleComplex* x,
int batchCount,
int batchStride,
size_t* bufferSizeInBytes);
cusparseStatus_t CUSPARSEAPI
cusparseSgtsv2StridedBatch(cusparseHandle_t handle,
int m,
const float* dl,
const float* d,
const float* du,
float* x,
int batchCount,
int batchStride,
void* pBuffer);
cusparseStatus_t CUSPARSEAPI
cusparseDgtsv2StridedBatch(cusparseHandle_t handle,
int m,
const double* dl,
const double* d,
const double* du,
double* x,
int batchCount,
int batchStride,
void* pBuffer);
cusparseStatus_t CUSPARSEAPI
cusparseCgtsv2StridedBatch(cusparseHandle_t handle,
int m,
const cuComplex* dl,
const cuComplex* d,
const cuComplex* du,
cuComplex* x,
int batchCount,
int batchStride,
void* pBuffer);
cusparseStatus_t CUSPARSEAPI
cusparseZgtsv2StridedBatch(cusparseHandle_t handle,
int m,
const cuDoubleComplex* dl,
const cuDoubleComplex* d,
const cuDoubleComplex* du,
cuDoubleComplex* x,
int batchCount,
int batchStride,
void* pBuffer);
cusparseStatus_t CUSPARSEAPI
cusparseSgtsvInterleavedBatch_bufferSizeExt(cusparseHandle_t handle,
int algo,
int m,
const float* dl,
const float* d,
const float* du,
const float* x,
int batchCount,
size_t* pBufferSizeInBytes);
cusparseStatus_t CUSPARSEAPI
cusparseDgtsvInterleavedBatch_bufferSizeExt(cusparseHandle_t handle,
int algo,
int m,
const double* dl,
const double* d,
const double* du,
const double* x,
int batchCount,
size_t* pBufferSizeInBytes);
cusparseStatus_t CUSPARSEAPI
cusparseCgtsvInterleavedBatch_bufferSizeExt(cusparseHandle_t handle,
int algo,
int m,
const cuComplex* dl,
const cuComplex* d,
const cuComplex* du,
const cuComplex* x,
int batchCount,
size_t* pBufferSizeInBytes);
cusparseStatus_t CUSPARSEAPI
cusparseZgtsvInterleavedBatch_bufferSizeExt(cusparseHandle_t handle,
int algo,
int m,
const cuDoubleComplex* dl,
const cuDoubleComplex* d,
const cuDoubleComplex* du,
const cuDoubleComplex* x,
int batchCount,
size_t* pBufferSizeInBytes);
cusparseStatus_t CUSPARSEAPI
cusparseSgtsvInterleavedBatch(cusparseHandle_t handle,
int algo,
int m,
float* dl,
float* d,
float* du,
float* x,
int batchCount,
void* pBuffer);
cusparseStatus_t CUSPARSEAPI
cusparseDgtsvInterleavedBatch(cusparseHandle_t handle,
int algo,
int m,
double* dl,
double* d,
double* du,
double* x,
int batchCount,
void* pBuffer);
cusparseStatus_t CUSPARSEAPI
cusparseCgtsvInterleavedBatch(cusparseHandle_t handle,
int algo,
int m,
cuComplex* dl,
cuComplex* d,
cuComplex* du,
cuComplex* x,
int batchCount,
void* pBuffer);
cusparseStatus_t CUSPARSEAPI
cusparseZgtsvInterleavedBatch(cusparseHandle_t handle,
int algo,
int m,
cuDoubleComplex* dl,
cuDoubleComplex* d,
cuDoubleComplex* du,
cuDoubleComplex* x,
int batchCount,
void* pBuffer);
cusparseStatus_t CUSPARSEAPI
cusparseSgpsvInterleavedBatch_bufferSizeExt(cusparseHandle_t handle,
int algo,
int m,
const float* ds,
const float* dl,
const float* d,
const float* du,
const float* dw,
const float* x,
int batchCount,
size_t* pBufferSizeInBytes);
cusparseStatus_t CUSPARSEAPI
cusparseDgpsvInterleavedBatch_bufferSizeExt(cusparseHandle_t handle,
int algo,
int m,
const double* ds,
const double* dl,
const double* d,
const double* du,
const double* dw,
const double* x,
int batchCount,
size_t* pBufferSizeInBytes);
cusparseStatus_t CUSPARSEAPI
cusparseCgpsvInterleavedBatch_bufferSizeExt(cusparseHandle_t handle,
int algo,
int m,
const cuComplex* ds,
const cuComplex* dl,
const cuComplex* d,
const cuComplex* du,
const cuComplex* dw,
const cuComplex* x,
int batchCount,
size_t* pBufferSizeInBytes);
cusparseStatus_t CUSPARSEAPI
cusparseZgpsvInterleavedBatch_bufferSizeExt(cusparseHandle_t handle,
int algo,
int m,
const cuDoubleComplex* ds,
const cuDoubleComplex* dl,
const cuDoubleComplex* d,
const cuDoubleComplex* du,
const cuDoubleComplex* dw,
const cuDoubleComplex* x,
int batchCount,
size_t* pBufferSizeInBytes);
cusparseStatus_t CUSPARSEAPI
cusparseSgpsvInterleavedBatch(cusparseHandle_t handle,
int algo,
int m,
float* ds,
float* dl,
float* d,
float* du,
float* dw,
float* x,
int batchCount,
void* pBuffer);
cusparseStatus_t CUSPARSEAPI
cusparseDgpsvInterleavedBatch(cusparseHandle_t handle,
int algo,
int m,
double* ds,
double* dl,
double* d,
double* du,
double* dw,
double* x,
int batchCount,
void* pBuffer);
cusparseStatus_t CUSPARSEAPI
cusparseCgpsvInterleavedBatch(cusparseHandle_t handle,
int algo,
int m,
cuComplex* ds,
cuComplex* dl,
cuComplex* d,
cuComplex* du,
cuComplex* dw,
cuComplex* x,
int batchCount,
void* pBuffer);
cusparseStatus_t CUSPARSEAPI
cusparseZgpsvInterleavedBatch(cusparseHandle_t handle,
int algo,
int m,
cuDoubleComplex* ds,
cuDoubleComplex* dl,
cuDoubleComplex* d,
cuDoubleComplex* du,
cuDoubleComplex* dw,
cuDoubleComplex* x,
int batchCount,
void* pBuffer);
//##############################################################################
//# EXTRA ROUTINES
//##############################################################################
CUSPARSE_DEPRECATED(cusparseSpGEMM)
cusparseStatus_t CUSPARSEAPI
cusparseCreateCsrgemm2Info(csrgemm2Info_t* info);
CUSPARSE_DEPRECATED(cusparseSpGEMM)
cusparseStatus_t CUSPARSEAPI
cusparseDestroyCsrgemm2Info(csrgemm2Info_t info);
CUSPARSE_DEPRECATED(cusparseSpGEMM)
cusparseStatus_t CUSPARSEAPI
cusparseScsrgemm2_bufferSizeExt(cusparseHandle_t handle,
int m,
int n,
int k,
const float* alpha,
const cusparseMatDescr_t descrA,
int nnzA,
const int* csrSortedRowPtrA,
const int* csrSortedColIndA,
const cusparseMatDescr_t descrB,
int nnzB,
const int* csrSortedRowPtrB,
const int* csrSortedColIndB,
const float* beta,
const cusparseMatDescr_t descrD,
int nnzD,
const int* csrSortedRowPtrD,
const int* csrSortedColIndD,
csrgemm2Info_t info,
size_t* pBufferSizeInBytes);
CUSPARSE_DEPRECATED(cusparseSpGEMM)
cusparseStatus_t CUSPARSEAPI
cusparseDcsrgemm2_bufferSizeExt(cusparseHandle_t handle,
int m,
int n,
int k,
const double* alpha,
const cusparseMatDescr_t descrA,
int nnzA,
const int* csrSortedRowPtrA,
const int* csrSortedColIndA,
const cusparseMatDescr_t descrB,
int nnzB,
const int* csrSortedRowPtrB,
const int* csrSortedColIndB,
const double* beta,
const cusparseMatDescr_t descrD,
int nnzD,
const int* csrSortedRowPtrD,
const int* csrSortedColIndD,
csrgemm2Info_t info,
size_t* pBufferSizeInBytes);
CUSPARSE_DEPRECATED(cusparseSpGEMM)
cusparseStatus_t CUSPARSEAPI
cusparseCcsrgemm2_bufferSizeExt(cusparseHandle_t handle,
int m,
int n,
int k,
const cuComplex* alpha,
const cusparseMatDescr_t descrA,
int nnzA,
const int* csrSortedRowPtrA,
const int* csrSortedColIndA,
const cusparseMatDescr_t descrB,
int nnzB,
const int* csrSortedRowPtrB,
const int* csrSortedColIndB,
const cuComplex* beta,
const cusparseMatDescr_t descrD,
int nnzD,
const int* csrSortedRowPtrD,
const int* csrSortedColIndD,
csrgemm2Info_t info,
size_t* pBufferSizeInBytes);
CUSPARSE_DEPRECATED(cusparseSpGEMM)
cusparseStatus_t CUSPARSEAPI
cusparseZcsrgemm2_bufferSizeExt(cusparseHandle_t handle,
int m,
int n,
int k,
const cuDoubleComplex* alpha,
const cusparseMatDescr_t descrA,
int nnzA,
const int* csrSortedRowPtrA,
const int* csrSortedColIndA,
const cusparseMatDescr_t descrB,
int nnzB,
const int* csrSortedRowPtrB,
const int* csrSortedColIndB,
const cuDoubleComplex* beta,
const cusparseMatDescr_t descrD,
int nnzD,
const int* csrSortedRowPtrD,
const int* csrSortedColIndD,
csrgemm2Info_t info,
size_t* pBufferSizeInBytes);
CUSPARSE_DEPRECATED(cusparseSpGEMM)
cusparseStatus_t CUSPARSEAPI
cusparseXcsrgemm2Nnz(cusparseHandle_t handle,
int m,
int n,
int k,
const cusparseMatDescr_t descrA,
int nnzA,
const int* csrSortedRowPtrA,
const int* csrSortedColIndA,
const cusparseMatDescr_t descrB,
int nnzB,
const int* csrSortedRowPtrB,
const int* csrSortedColIndB,
const cusparseMatDescr_t descrD,
int nnzD,
const int* csrSortedRowPtrD,
const int* csrSortedColIndD,
const cusparseMatDescr_t descrC,
int* csrSortedRowPtrC,
int* nnzTotalDevHostPtr,
const csrgemm2Info_t info,
void* pBuffer);
CUSPARSE_DEPRECATED(cusparseSpGEMM)
cusparseStatus_t CUSPARSEAPI
cusparseScsrgemm2(cusparseHandle_t handle,
int m,
int n,
int k,
const float* alpha,
const cusparseMatDescr_t descrA,
int nnzA,
const float* csrSortedValA,
const int* csrSortedRowPtrA,
const int* csrSortedColIndA,
const cusparseMatDescr_t descrB,
int nnzB,
const float* csrSortedValB,
const int* csrSortedRowPtrB,
const int* csrSortedColIndB,
const float* beta,
const cusparseMatDescr_t descrD,
int nnzD,
const float* csrSortedValD,
const int* csrSortedRowPtrD,
const int* csrSortedColIndD,
const cusparseMatDescr_t descrC,
float* csrSortedValC,
const int* csrSortedRowPtrC,
int* csrSortedColIndC,
const csrgemm2Info_t info,
void* pBuffer);
CUSPARSE_DEPRECATED(cusparseSpGEMM)
cusparseStatus_t CUSPARSEAPI
cusparseDcsrgemm2(cusparseHandle_t handle,
int m,
int n,
int k,
const double* alpha,
const cusparseMatDescr_t descrA,
int nnzA,
const double* csrSortedValA,
const int* csrSortedRowPtrA,
const int* csrSortedColIndA,
const cusparseMatDescr_t descrB,
int nnzB,
const double* csrSortedValB,
const int* csrSortedRowPtrB,
const int* csrSortedColIndB,
const double* beta,
const cusparseMatDescr_t descrD,
int nnzD,
const double* csrSortedValD,
const int* csrSortedRowPtrD,
const int* csrSortedColIndD,
const cusparseMatDescr_t descrC,
double* csrSortedValC,
const int* csrSortedRowPtrC,
int* csrSortedColIndC,
const csrgemm2Info_t info,
void* pBuffer);
CUSPARSE_DEPRECATED(cusparseSpGEMM)
cusparseStatus_t CUSPARSEAPI
cusparseCcsrgemm2(cusparseHandle_t handle,
int m,
int n,
int k,
const cuComplex* alpha,
const cusparseMatDescr_t descrA,
int nnzA,
const cuComplex* csrSortedValA,
const int* csrSortedRowPtrA,
const int* csrSortedColIndA,
const cusparseMatDescr_t descrB,
int nnzB,
const cuComplex* csrSortedValB,
const int* csrSortedRowPtrB,
const int* csrSortedColIndB,
const cuComplex* beta,
const cusparseMatDescr_t descrD,
int nnzD,
const cuComplex* csrSortedValD,
const int* csrSortedRowPtrD,
const int* csrSortedColIndD,
const cusparseMatDescr_t descrC,
cuComplex* csrSortedValC,
const int* csrSortedRowPtrC,
int* csrSortedColIndC,
const csrgemm2Info_t info,
void* pBuffer);
CUSPARSE_DEPRECATED(cusparseSpGEMM)
cusparseStatus_t CUSPARSEAPI
cusparseZcsrgemm2(cusparseHandle_t handle,
int m,
int n,
int k,
const cuDoubleComplex* alpha,
const cusparseMatDescr_t descrA,
int nnzA,
const cuDoubleComplex* csrSortedValA,
const int* csrSortedRowPtrA,
const int* csrSortedColIndA,
const cusparseMatDescr_t descrB,
int nnzB,
const cuDoubleComplex* csrSortedValB,
const int* csrSortedRowPtrB,
const int* csrSortedColIndB,
const cuDoubleComplex* beta,
const cusparseMatDescr_t descrD,
int nnzD,
const cuDoubleComplex* csrSortedValD,
const int* csrSortedRowPtrD,
const int* csrSortedColIndD,
const cusparseMatDescr_t descrC,
cuDoubleComplex* csrSortedValC,
const int* csrSortedRowPtrC,
int* csrSortedColIndC,
const csrgemm2Info_t info,
void* pBuffer);
cusparseStatus_t CUSPARSEAPI
cusparseScsrgeam2_bufferSizeExt(cusparseHandle_t handle,
int m,
int n,
const float* alpha,
const cusparseMatDescr_t descrA,
int nnzA,
const float* csrSortedValA,
const int* csrSortedRowPtrA,
const int* csrSortedColIndA,
const float* beta,
const cusparseMatDescr_t descrB,
int nnzB,
const float* csrSortedValB,
const int* csrSortedRowPtrB,
const int* csrSortedColIndB,
const cusparseMatDescr_t descrC,
const float* csrSortedValC,
const int* csrSortedRowPtrC,
const int* csrSortedColIndC,
size_t* pBufferSizeInBytes);
cusparseStatus_t CUSPARSEAPI
cusparseDcsrgeam2_bufferSizeExt(cusparseHandle_t handle,
int m,
int n,
const double* alpha,
const cusparseMatDescr_t descrA,
int nnzA,
const double* csrSortedValA,
const int* csrSortedRowPtrA,
const int* csrSortedColIndA,
const double* beta,
const cusparseMatDescr_t descrB,
int nnzB,
const double* csrSortedValB,
const int* csrSortedRowPtrB,
const int* csrSortedColIndB,
const cusparseMatDescr_t descrC,
const double* csrSortedValC,
const int* csrSortedRowPtrC,
const int* csrSortedColIndC,
size_t* pBufferSizeInBytes);
cusparseStatus_t CUSPARSEAPI
cusparseCcsrgeam2_bufferSizeExt(cusparseHandle_t handle,
int m,
int n,
const cuComplex* alpha,
const cusparseMatDescr_t descrA,
int nnzA,
const cuComplex* csrSortedValA,
const int* csrSortedRowPtrA,
const int* csrSortedColIndA,
const cuComplex* beta,
const cusparseMatDescr_t descrB,
int nnzB,
const cuComplex* csrSortedValB,
const int* csrSortedRowPtrB,
const int* csrSortedColIndB,
const cusparseMatDescr_t descrC,
const cuComplex* csrSortedValC,
const int* csrSortedRowPtrC,
const int* csrSortedColIndC,
size_t* pBufferSizeInBytes);
cusparseStatus_t CUSPARSEAPI
cusparseZcsrgeam2_bufferSizeExt(cusparseHandle_t handle,
int m,
int n,
const cuDoubleComplex* alpha,
const cusparseMatDescr_t descrA,
int nnzA,
const cuDoubleComplex* csrSortedValA,
const int* csrSortedRowPtrA,
const int* csrSortedColIndA,
const cuDoubleComplex* beta,
const cusparseMatDescr_t descrB,
int nnzB,
const cuDoubleComplex* csrSortedValB,
const int* csrSortedRowPtrB,
const int* csrSortedColIndB,
const cusparseMatDescr_t descrC,
const cuDoubleComplex* csrSortedValC,
const int* csrSortedRowPtrC,
const int* csrSortedColIndC,
size_t* pBufferSizeInBytes);
cusparseStatus_t CUSPARSEAPI
cusparseXcsrgeam2Nnz(cusparseHandle_t handle,
int m,
int n,
const cusparseMatDescr_t descrA,
int nnzA,
const int* csrSortedRowPtrA,
const int* csrSortedColIndA,
const cusparseMatDescr_t descrB,
int nnzB,
const int* csrSortedRowPtrB,
const int* csrSortedColIndB,
const cusparseMatDescr_t descrC,
int* csrSortedRowPtrC,
int* nnzTotalDevHostPtr,
void* workspace);
cusparseStatus_t CUSPARSEAPI
cusparseScsrgeam2(cusparseHandle_t handle,
int m,
int n,
const float* alpha,
const cusparseMatDescr_t descrA,
int nnzA,
const float* csrSortedValA,
const int* csrSortedRowPtrA,
const int* csrSortedColIndA,
const float* beta,
const cusparseMatDescr_t descrB,
int nnzB,
const float* csrSortedValB,
const int* csrSortedRowPtrB,
const int* csrSortedColIndB,
const cusparseMatDescr_t descrC,
float* csrSortedValC,
int* csrSortedRowPtrC,
int* csrSortedColIndC,
void* pBuffer);
cusparseStatus_t CUSPARSEAPI
cusparseDcsrgeam2(cusparseHandle_t handle,
int m,
int n,
const double* alpha,
const cusparseMatDescr_t descrA,
int nnzA,
const double* csrSortedValA,
const int* csrSortedRowPtrA,
const int* csrSortedColIndA,
const double* beta,
const cusparseMatDescr_t descrB,
int nnzB,
const double* csrSortedValB,
const int* csrSortedRowPtrB,
const int* csrSortedColIndB,
const cusparseMatDescr_t descrC,
double* csrSortedValC,
int* csrSortedRowPtrC,
int* csrSortedColIndC,
void* pBuffer);
cusparseStatus_t CUSPARSEAPI
cusparseCcsrgeam2(cusparseHandle_t handle,
int m,
int n,
const cuComplex* alpha,
const cusparseMatDescr_t descrA,
int nnzA,
const cuComplex* csrSortedValA,
const int* csrSortedRowPtrA,
const int* csrSortedColIndA,
const cuComplex* beta,
const cusparseMatDescr_t descrB,
int nnzB,
const cuComplex* csrSortedValB,
const int* csrSortedRowPtrB,
const int* csrSortedColIndB,
const cusparseMatDescr_t descrC,
cuComplex* csrSortedValC,
int* csrSortedRowPtrC,
int* csrSortedColIndC,
void* pBuffer);
cusparseStatus_t CUSPARSEAPI
cusparseZcsrgeam2(cusparseHandle_t handle,
int m,
int n,
const cuDoubleComplex* alpha,
const cusparseMatDescr_t descrA,
int nnzA,
const cuDoubleComplex* csrSortedValA,
const int* csrSortedRowPtrA,
const int* csrSortedColIndA,
const cuDoubleComplex* beta,
const cusparseMatDescr_t descrB,
int nnzB,
const cuDoubleComplex* csrSortedValB,
const int* csrSortedRowPtrB,
const int* csrSortedColIndB,
const cusparseMatDescr_t descrC,
cuDoubleComplex* csrSortedValC,
int* csrSortedRowPtrC,
int* csrSortedColIndC,
void* pBuffer);
//##############################################################################
//# SPARSE MATRIX REORDERING
//##############################################################################
cusparseStatus_t CUSPARSEAPI
cusparseScsrcolor(cusparseHandle_t handle,
int m,
int nnz,
const cusparseMatDescr_t descrA,
const float* csrSortedValA,
const int* csrSortedRowPtrA,
const int* csrSortedColIndA,
const float* fractionToColor,
int* ncolors,
int* coloring,
int* reordering,
const cusparseColorInfo_t info);
cusparseStatus_t CUSPARSEAPI
cusparseDcsrcolor(cusparseHandle_t handle,
int m,
int nnz,
const cusparseMatDescr_t descrA,
const double* csrSortedValA,
const int* csrSortedRowPtrA,
const int* csrSortedColIndA,
const double* fractionToColor,
int* ncolors,
int* coloring,
int* reordering,
const cusparseColorInfo_t info);
cusparseStatus_t CUSPARSEAPI
cusparseCcsrcolor(cusparseHandle_t handle,
int m,
int nnz,
const cusparseMatDescr_t descrA,
const cuComplex* csrSortedValA,
const int* csrSortedRowPtrA,
const int* csrSortedColIndA,
const float* fractionToColor,
int* ncolors,
int* coloring,
int* reordering,
const cusparseColorInfo_t info);
cusparseStatus_t CUSPARSEAPI
cusparseZcsrcolor(cusparseHandle_t handle,
int m,
int nnz,
const cusparseMatDescr_t descrA,
const cuDoubleComplex* csrSortedValA,
const int* csrSortedRowPtrA,
const int* csrSortedColIndA,
const double* fractionToColor,
int* ncolors,
int* coloring,
int* reordering,
const cusparseColorInfo_t info);
//##############################################################################
//# SPARSE FORMAT CONVERSION
//##############################################################################
cusparseStatus_t CUSPARSEAPI
cusparseSnnz(cusparseHandle_t handle,
cusparseDirection_t dirA,
int m,
int n,
const cusparseMatDescr_t descrA,
const float* A,
int lda,
int* nnzPerRowCol,
int* nnzTotalDevHostPtr);
cusparseStatus_t CUSPARSEAPI
cusparseDnnz(cusparseHandle_t handle,
cusparseDirection_t dirA,
int m,
int n,
const cusparseMatDescr_t descrA,
const double* A,
int lda,
int* nnzPerRowCol,
int* nnzTotalDevHostPtr);
cusparseStatus_t CUSPARSEAPI
cusparseCnnz(cusparseHandle_t handle,
cusparseDirection_t dirA,
int m,
int n,
const cusparseMatDescr_t descrA,
const cuComplex* A,
int lda,
int* nnzPerRowCol,
int* nnzTotalDevHostPtr);
cusparseStatus_t CUSPARSEAPI
cusparseZnnz(cusparseHandle_t handle,
cusparseDirection_t dirA,
int m,
int n,
const cusparseMatDescr_t descrA,
const cuDoubleComplex* A,
int lda,
int* nnzPerRowCol,
int* nnzTotalDevHostPtr);
//##############################################################################
//# SPARSE FORMAT CONVERSION
//##############################################################################
cusparseStatus_t CUSPARSEAPI
cusparseSnnz_compress(cusparseHandle_t handle,
int m,
const cusparseMatDescr_t descr,
const float* csrSortedValA,
const int* csrSortedRowPtrA,
int* nnzPerRow,
int* nnzC,
float tol);
cusparseStatus_t CUSPARSEAPI
cusparseDnnz_compress(cusparseHandle_t handle,
int m,
const cusparseMatDescr_t descr,
const double* csrSortedValA,
const int* csrSortedRowPtrA,
int* nnzPerRow,
int* nnzC,
double tol);
cusparseStatus_t CUSPARSEAPI
cusparseCnnz_compress(cusparseHandle_t handle,
int m,
const cusparseMatDescr_t descr,
const cuComplex* csrSortedValA,
const int* csrSortedRowPtrA,
int* nnzPerRow,
int* nnzC,
cuComplex tol);
cusparseStatus_t CUSPARSEAPI
cusparseZnnz_compress(cusparseHandle_t handle,
int m,
const cusparseMatDescr_t descr,
const cuDoubleComplex* csrSortedValA,
const int* csrSortedRowPtrA,
int* nnzPerRow,
int* nnzC,
cuDoubleComplex tol);
cusparseStatus_t CUSPARSEAPI
cusparseScsr2csr_compress(cusparseHandle_t handle,
int m,
int n,
const cusparseMatDescr_t descrA,
const float* csrSortedValA,
const int* csrSortedColIndA,
const int* csrSortedRowPtrA,
int nnzA,
const int* nnzPerRow,
float* csrSortedValC,
int* csrSortedColIndC,
int* csrSortedRowPtrC,
float tol);
cusparseStatus_t CUSPARSEAPI
cusparseDcsr2csr_compress(cusparseHandle_t handle,
int m,
int n,
const cusparseMatDescr_t descrA,
const double* csrSortedValA,
const int* csrSortedColIndA,
const int* csrSortedRowPtrA,
int nnzA,
const int* nnzPerRow,
double* csrSortedValC,
int* csrSortedColIndC,
int* csrSortedRowPtrC,
double tol);
cusparseStatus_t CUSPARSEAPI
cusparseCcsr2csr_compress(cusparseHandle_t handle,
int m,
int n,
const cusparseMatDescr_t descrA,
const cuComplex* csrSortedValA,
const int* csrSortedColIndA,
const int* csrSortedRowPtrA,
int nnzA,
const int* nnzPerRow,
cuComplex* csrSortedValC,
int* csrSortedColIndC,
int* csrSortedRowPtrC,
cuComplex tol);
cusparseStatus_t CUSPARSEAPI
cusparseZcsr2csr_compress(cusparseHandle_t handle,
int m,
int n,
const cusparseMatDescr_t descrA,
const cuDoubleComplex* csrSortedValA,
const int* csrSortedColIndA,
const int* csrSortedRowPtrA,
int nnzA,
const int* nnzPerRow,
cuDoubleComplex* csrSortedValC,
int* csrSortedColIndC,
int* csrSortedRowPtrC,
cuDoubleComplex tol);
CUSPARSE_DEPRECATED(cusparseDenseToSparse)
cusparseStatus_t CUSPARSEAPI
cusparseSdense2csr(cusparseHandle_t handle,
int m,
int n,
const cusparseMatDescr_t descrA,
const float* A,
int lda,
const int* nnzPerRow,
float* csrSortedValA,
int* csrSortedRowPtrA,
int* csrSortedColIndA);
CUSPARSE_DEPRECATED(cusparseDenseToSparse)
cusparseStatus_t CUSPARSEAPI
cusparseDdense2csr(cusparseHandle_t handle,
int m,
int n,
const cusparseMatDescr_t descrA,
const double* A,
int lda,
const int* nnzPerRow,
double* csrSortedValA,
int* csrSortedRowPtrA,
int* csrSortedColIndA);
CUSPARSE_DEPRECATED(cusparseDenseToSparse)
cusparseStatus_t CUSPARSEAPI
cusparseCdense2csr(cusparseHandle_t handle,
int m,
int n,
const cusparseMatDescr_t descrA,
const cuComplex* A,
int lda,
const int* nnzPerRow,
cuComplex* csrSortedValA,
int* csrSortedRowPtrA,
int* csrSortedColIndA);
CUSPARSE_DEPRECATED(cusparseDenseToSparse)
cusparseStatus_t CUSPARSEAPI
cusparseZdense2csr(cusparseHandle_t handle,
int m,
int n,
const cusparseMatDescr_t descrA,
const cuDoubleComplex* A,
int lda,
const int* nnzPerRow,
cuDoubleComplex* csrSortedValA,
int* csrSortedRowPtrA,
int* csrSortedColIndA);
CUSPARSE_DEPRECATED(cusparseSparseToDense)
cusparseStatus_t CUSPARSEAPI
cusparseScsr2dense(cusparseHandle_t handle,
int m,
int n,
const cusparseMatDescr_t descrA,
const float* csrSortedValA,
const int* csrSortedRowPtrA,
const int* csrSortedColIndA,
float* A,
int lda);
CUSPARSE_DEPRECATED(cusparseSparseToDense)
cusparseStatus_t CUSPARSEAPI
cusparseDcsr2dense(cusparseHandle_t handle,
int m,
int n,
const cusparseMatDescr_t descrA,
const double* csrSortedValA,
const int* csrSortedRowPtrA,
const int* csrSortedColIndA,
double* A,
int lda);
CUSPARSE_DEPRECATED(cusparseSparseToDense)
cusparseStatus_t CUSPARSEAPI
cusparseCcsr2dense(cusparseHandle_t handle,
int m,
int n,
const cusparseMatDescr_t descrA,
const cuComplex* csrSortedValA,
const int* csrSortedRowPtrA,
const int* csrSortedColIndA,
cuComplex* A,
int lda);
CUSPARSE_DEPRECATED(cusparseSparseToDense)
cusparseStatus_t CUSPARSEAPI
cusparseZcsr2dense(cusparseHandle_t handle,
int m,
int n,
const cusparseMatDescr_t descrA,
const cuDoubleComplex* csrSortedValA,
const int* csrSortedRowPtrA,
const int* csrSortedColIndA,
cuDoubleComplex* A,
int lda);
CUSPARSE_DEPRECATED(cusparseDenseToSparse)
cusparseStatus_t CUSPARSEAPI
cusparseSdense2csc(cusparseHandle_t handle,
int m,
int n,
const cusparseMatDescr_t descrA,
const float* A,
int lda,
const int* nnzPerCol,
float* cscSortedValA,
int* cscSortedRowIndA,
int* cscSortedColPtrA);
CUSPARSE_DEPRECATED(cusparseDenseToSparse)
cusparseStatus_t CUSPARSEAPI
cusparseDdense2csc(cusparseHandle_t handle,
int m,
int n,
const cusparseMatDescr_t descrA,
const double* A,
int lda,
const int* nnzPerCol,
double* cscSortedValA,
int* cscSortedRowIndA,
int* cscSortedColPtrA);
CUSPARSE_DEPRECATED(cusparseDenseToSparse)
cusparseStatus_t CUSPARSEAPI
cusparseCdense2csc(cusparseHandle_t handle,
int m,
int n,
const cusparseMatDescr_t descrA,
const cuComplex* A,
int lda,
const int* nnzPerCol,
cuComplex* cscSortedValA,
int* cscSortedRowIndA,
int* cscSortedColPtrA);
CUSPARSE_DEPRECATED(cusparseDenseToSparse)
cusparseStatus_t CUSPARSEAPI
cusparseZdense2csc(cusparseHandle_t handle,
int m,
int n,
const cusparseMatDescr_t descrA,
const cuDoubleComplex* A,
int lda,
const int* nnzPerCol,
cuDoubleComplex* cscSortedValA,
int* cscSortedRowIndA,
int* cscSortedColPtrA);
CUSPARSE_DEPRECATED(cusparseSparseToDense)
cusparseStatus_t CUSPARSEAPI
cusparseScsc2dense(cusparseHandle_t handle,
int m,
int n,
const cusparseMatDescr_t descrA,
const float* cscSortedValA,
const int* cscSortedRowIndA,
const int* cscSortedColPtrA,
float* A,
int lda);
CUSPARSE_DEPRECATED(cusparseSparseToDense)
cusparseStatus_t CUSPARSEAPI
cusparseDcsc2dense(cusparseHandle_t handle,
int m,
int n,
const cusparseMatDescr_t descrA,
const double* cscSortedValA,
const int* cscSortedRowIndA,
const int* cscSortedColPtrA,
double* A,
int lda);
CUSPARSE_DEPRECATED(cusparseSparseToDense)
cusparseStatus_t CUSPARSEAPI
cusparseCcsc2dense(cusparseHandle_t handle,
int m,
int n,
const cusparseMatDescr_t descrA,
const cuComplex* cscSortedValA,
const int* cscSortedRowIndA,
const int* cscSortedColPtrA,
cuComplex* A,
int lda);
CUSPARSE_DEPRECATED(cusparseSparseToDense)
cusparseStatus_t CUSPARSEAPI
cusparseZcsc2dense(cusparseHandle_t handle,
int m,
int n,
const cusparseMatDescr_t descrA,
const cuDoubleComplex* cscSortedValA,
const int* cscSortedRowIndA,
const int* cscSortedColPtrA,
cuDoubleComplex* A,
int lda);
cusparseStatus_t CUSPARSEAPI
cusparseXcoo2csr(cusparseHandle_t handle,
const int* cooRowInd,
int nnz,
int m,
int* csrSortedRowPtr,
cusparseIndexBase_t idxBase);
cusparseStatus_t CUSPARSEAPI
cusparseXcsr2coo(cusparseHandle_t handle,
const int* csrSortedRowPtr,
int nnz,
int m,
int* cooRowInd,
cusparseIndexBase_t idxBase);
cusparseStatus_t CUSPARSEAPI
cusparseXcsr2bsrNnz(cusparseHandle_t handle,
cusparseDirection_t dirA,
int m,
int n,
const cusparseMatDescr_t descrA,
const int* csrSortedRowPtrA,
const int* csrSortedColIndA,
int blockDim,
const cusparseMatDescr_t descrC,
int* bsrSortedRowPtrC,
int* nnzTotalDevHostPtr);
cusparseStatus_t CUSPARSEAPI
cusparseScsr2bsr(cusparseHandle_t handle,
cusparseDirection_t dirA,
int m,
int n,
const cusparseMatDescr_t descrA,
const float* csrSortedValA,
const int* csrSortedRowPtrA,
const int* csrSortedColIndA,
int blockDim,
const cusparseMatDescr_t descrC,
float* bsrSortedValC,
int* bsrSortedRowPtrC,
int* bsrSortedColIndC);
cusparseStatus_t CUSPARSEAPI
cusparseDcsr2bsr(cusparseHandle_t handle,
cusparseDirection_t dirA,
int m,
int n,
const cusparseMatDescr_t descrA,
const double* csrSortedValA,
const int* csrSortedRowPtrA,
const int* csrSortedColIndA,
int blockDim,
const cusparseMatDescr_t descrC,
double* bsrSortedValC,
int* bsrSortedRowPtrC,
int* bsrSortedColIndC);
cusparseStatus_t CUSPARSEAPI
cusparseCcsr2bsr(cusparseHandle_t handle,
cusparseDirection_t dirA,
int m,
int n,
const cusparseMatDescr_t descrA,
const cuComplex* csrSortedValA,
const int* csrSortedRowPtrA,
const int* csrSortedColIndA,
int blockDim,
const cusparseMatDescr_t descrC,
cuComplex* bsrSortedValC,
int* bsrSortedRowPtrC,
int* bsrSortedColIndC);
cusparseStatus_t CUSPARSEAPI
cusparseZcsr2bsr(cusparseHandle_t handle,
cusparseDirection_t dirA,
int m,
int n,
const cusparseMatDescr_t descrA,
const cuDoubleComplex* csrSortedValA,
const int* csrSortedRowPtrA,
const int* csrSortedColIndA,
int blockDim,
const cusparseMatDescr_t descrC,
cuDoubleComplex* bsrSortedValC,
int* bsrSortedRowPtrC,
int* bsrSortedColIndC);
cusparseStatus_t CUSPARSEAPI
cusparseSbsr2csr(cusparseHandle_t handle,
cusparseDirection_t dirA,
int mb,
int nb,
const cusparseMatDescr_t descrA,
const float* bsrSortedValA,
const int* bsrSortedRowPtrA,
const int* bsrSortedColIndA,
int blockDim,
const cusparseMatDescr_t descrC,
float* csrSortedValC,
int* csrSortedRowPtrC,
int* csrSortedColIndC);
cusparseStatus_t CUSPARSEAPI
cusparseDbsr2csr(cusparseHandle_t handle,
cusparseDirection_t dirA,
int mb,
int nb,
const cusparseMatDescr_t descrA,
const double* bsrSortedValA,
const int* bsrSortedRowPtrA,
const int* bsrSortedColIndA,
int blockDim,
const cusparseMatDescr_t descrC,
double* csrSortedValC,
int* csrSortedRowPtrC,
int* csrSortedColIndC);
cusparseStatus_t CUSPARSEAPI
cusparseCbsr2csr(cusparseHandle_t handle,
cusparseDirection_t dirA,
int mb,
int nb,
const cusparseMatDescr_t descrA,
const cuComplex* bsrSortedValA,
const int* bsrSortedRowPtrA,
const int* bsrSortedColIndA,
int blockDim,
const cusparseMatDescr_t descrC,
cuComplex* csrSortedValC,
int* csrSortedRowPtrC,
int* csrSortedColIndC);
cusparseStatus_t CUSPARSEAPI
cusparseZbsr2csr(cusparseHandle_t handle,
cusparseDirection_t dirA,
int mb,
int nb,
const cusparseMatDescr_t descrA,
const cuDoubleComplex* bsrSortedValA,
const int* bsrSortedRowPtrA,
const int* bsrSortedColIndA,
int blockDim,
const cusparseMatDescr_t descrC,
cuDoubleComplex* csrSortedValC,
int* csrSortedRowPtrC,
int* csrSortedColIndC);
cusparseStatus_t CUSPARSEAPI
cusparseSgebsr2gebsc_bufferSize(cusparseHandle_t handle,
int mb,
int nb,
int nnzb,
const float* bsrSortedVal,
const int* bsrSortedRowPtr,
const int* bsrSortedColInd,
int rowBlockDim,
int colBlockDim,
int* pBufferSizeInBytes);
cusparseStatus_t CUSPARSEAPI
cusparseDgebsr2gebsc_bufferSize(cusparseHandle_t handle,
int mb,
int nb,
int nnzb,
const double* bsrSortedVal,
const int* bsrSortedRowPtr,
const int* bsrSortedColInd,
int rowBlockDim,
int colBlockDim,
int* pBufferSizeInBytes);
cusparseStatus_t CUSPARSEAPI
cusparseCgebsr2gebsc_bufferSize(cusparseHandle_t handle,
int mb,
int nb,
int nnzb,
const cuComplex* bsrSortedVal,
const int* bsrSortedRowPtr,
const int* bsrSortedColInd,
int rowBlockDim,
int colBlockDim,
int* pBufferSizeInBytes);
cusparseStatus_t CUSPARSEAPI
cusparseZgebsr2gebsc_bufferSize(cusparseHandle_t handle,
int mb,
int nb,
int nnzb,
const cuDoubleComplex* bsrSortedVal,
const int* bsrSortedRowPtr,
const int* bsrSortedColInd,
int rowBlockDim,
int colBlockDim,
int* pBufferSizeInBytes);
cusparseStatus_t CUSPARSEAPI
cusparseSgebsr2gebsc_bufferSizeExt(cusparseHandle_t handle,
int mb,
int nb,
int nnzb,
const float* bsrSortedVal,
const int* bsrSortedRowPtr,
const int* bsrSortedColInd,
int rowBlockDim,
int colBlockDim,
size_t* pBufferSize);
cusparseStatus_t CUSPARSEAPI
cusparseDgebsr2gebsc_bufferSizeExt(cusparseHandle_t handle,
int mb,
int nb,
int nnzb,
const double* bsrSortedVal,
const int* bsrSortedRowPtr,
const int* bsrSortedColInd,
int rowBlockDim,
int colBlockDim,
size_t* pBufferSize);
cusparseStatus_t CUSPARSEAPI
cusparseCgebsr2gebsc_bufferSizeExt(cusparseHandle_t handle,
int mb,
int nb,
int nnzb,
const cuComplex* bsrSortedVal,
const int* bsrSortedRowPtr,
const int* bsrSortedColInd,
int rowBlockDim,
int colBlockDim,
size_t* pBufferSize);
cusparseStatus_t CUSPARSEAPI
cusparseZgebsr2gebsc_bufferSizeExt(cusparseHandle_t handle,
int mb,
int nb,
int nnzb,
const cuDoubleComplex* bsrSortedVal,
const int* bsrSortedRowPtr,
const int* bsrSortedColInd,
int rowBlockDim,
int colBlockDim,
size_t* pBufferSize);
cusparseStatus_t CUSPARSEAPI
cusparseSgebsr2gebsc(cusparseHandle_t handle,
int mb,
int nb,
int nnzb,
const float* bsrSortedVal,
const int* bsrSortedRowPtr,
const int* bsrSortedColInd,
int rowBlockDim,
int colBlockDim,
float* bscVal,
int* bscRowInd,
int* bscColPtr,
cusparseAction_t copyValues,
cusparseIndexBase_t idxBase,
void* pBuffer);
cusparseStatus_t CUSPARSEAPI
cusparseDgebsr2gebsc(cusparseHandle_t handle,
int mb,
int nb,
int nnzb,
const double* bsrSortedVal,
const int* bsrSortedRowPtr,
const int* bsrSortedColInd,
int rowBlockDim,
int colBlockDim,
double* bscVal,
int* bscRowInd,
int* bscColPtr,
cusparseAction_t copyValues,
cusparseIndexBase_t idxBase,
void* pBuffer);
cusparseStatus_t CUSPARSEAPI
cusparseCgebsr2gebsc(cusparseHandle_t handle,
int mb,
int nb,
int nnzb,
const cuComplex* bsrSortedVal,
const int* bsrSortedRowPtr,
const int* bsrSortedColInd,
int rowBlockDim,
int colBlockDim,
cuComplex* bscVal,
int* bscRowInd,
int* bscColPtr,
cusparseAction_t copyValues,
cusparseIndexBase_t idxBase,
void* pBuffer);
cusparseStatus_t CUSPARSEAPI
cusparseZgebsr2gebsc(cusparseHandle_t handle,
int mb,
int nb,
int nnzb,
const cuDoubleComplex* bsrSortedVal,
const int* bsrSortedRowPtr,
const int* bsrSortedColInd,
int rowBlockDim,
int colBlockDim,
cuDoubleComplex* bscVal,
int* bscRowInd,
int* bscColPtr,
cusparseAction_t copyValues,
cusparseIndexBase_t idxBase,
void* pBuffer);
cusparseStatus_t CUSPARSEAPI
cusparseXgebsr2csr(cusparseHandle_t handle,
cusparseDirection_t dirA,
int mb,
int nb,
const cusparseMatDescr_t descrA,
const int* bsrSortedRowPtrA,
const int* bsrSortedColIndA,
int rowBlockDim,
int colBlockDim,
const cusparseMatDescr_t descrC,
int* csrSortedRowPtrC,
int* csrSortedColIndC);
cusparseStatus_t CUSPARSEAPI
cusparseSgebsr2csr(cusparseHandle_t handle,
cusparseDirection_t dirA,
int mb,
int nb,
const cusparseMatDescr_t descrA,
const float* bsrSortedValA,
const int* bsrSortedRowPtrA,
const int* bsrSortedColIndA,
int rowBlockDim,
int colBlockDim,
const cusparseMatDescr_t descrC,
float* csrSortedValC,
int* csrSortedRowPtrC,
int* csrSortedColIndC);
cusparseStatus_t CUSPARSEAPI
cusparseDgebsr2csr(cusparseHandle_t handle,
cusparseDirection_t dirA,
int mb,
int nb,
const cusparseMatDescr_t descrA,
const double* bsrSortedValA,
const int* bsrSortedRowPtrA,
const int* bsrSortedColIndA,
int rowBlockDim,
int colBlockDim,
const cusparseMatDescr_t descrC,
double* csrSortedValC,
int* csrSortedRowPtrC,
int* csrSortedColIndC);
cusparseStatus_t CUSPARSEAPI
cusparseCgebsr2csr(cusparseHandle_t handle,
cusparseDirection_t dirA,
int mb,
int nb,
const cusparseMatDescr_t descrA,
const cuComplex* bsrSortedValA,
const int* bsrSortedRowPtrA,
const int* bsrSortedColIndA,
int rowBlockDim,
int colBlockDim,
const cusparseMatDescr_t descrC,
cuComplex* csrSortedValC,
int* csrSortedRowPtrC,
int* csrSortedColIndC);
cusparseStatus_t CUSPARSEAPI
cusparseZgebsr2csr(cusparseHandle_t handle,
cusparseDirection_t dirA,
int mb,
int nb,
const cusparseMatDescr_t descrA,
const cuDoubleComplex* bsrSortedValA,
const int* bsrSortedRowPtrA,
const int* bsrSortedColIndA,
int rowBlockDim,
int colBlockDim,
const cusparseMatDescr_t descrC,
cuDoubleComplex* csrSortedValC,
int* csrSortedRowPtrC,
int* csrSortedColIndC);
cusparseStatus_t CUSPARSEAPI
cusparseScsr2gebsr_bufferSize(cusparseHandle_t handle,
cusparseDirection_t dirA,
int m,
int n,
const cusparseMatDescr_t descrA,
const float* csrSortedValA,
const int* csrSortedRowPtrA,
const int* csrSortedColIndA,
int rowBlockDim,
int colBlockDim,
int* pBufferSizeInBytes);
cusparseStatus_t CUSPARSEAPI
cusparseDcsr2gebsr_bufferSize(cusparseHandle_t handle,
cusparseDirection_t dirA,
int m,
int n,
const cusparseMatDescr_t descrA,
const double* csrSortedValA,
const int* csrSortedRowPtrA,
const int* csrSortedColIndA,
int rowBlockDim,
int colBlockDim,
int* pBufferSizeInBytes);
cusparseStatus_t CUSPARSEAPI
cusparseCcsr2gebsr_bufferSize(cusparseHandle_t handle,
cusparseDirection_t dirA,
int m,
int n,
const cusparseMatDescr_t descrA,
const cuComplex* csrSortedValA,
const int* csrSortedRowPtrA,
const int* csrSortedColIndA,
int rowBlockDim,
int colBlockDim,
int* pBufferSizeInBytes);
cusparseStatus_t CUSPARSEAPI
cusparseZcsr2gebsr_bufferSize(cusparseHandle_t handle,
cusparseDirection_t dirA,
int m,
int n,
const cusparseMatDescr_t descrA,
const cuDoubleComplex* csrSortedValA,
const int* csrSortedRowPtrA,
const int* csrSortedColIndA,
int rowBlockDim,
int colBlockDim,
int* pBufferSizeInBytes);
cusparseStatus_t CUSPARSEAPI
cusparseScsr2gebsr_bufferSizeExt(cusparseHandle_t handle,
cusparseDirection_t dirA,
int m,
int n,
const cusparseMatDescr_t descrA,
const float* csrSortedValA,
const int* csrSortedRowPtrA,
const int* csrSortedColIndA,
int rowBlockDim,
int colBlockDim,
size_t* pBufferSize);
cusparseStatus_t CUSPARSEAPI
cusparseDcsr2gebsr_bufferSizeExt(cusparseHandle_t handle,
cusparseDirection_t dirA,
int m,
int n,
const cusparseMatDescr_t descrA,
const double* csrSortedValA,
const int* csrSortedRowPtrA,
const int* csrSortedColIndA,
int rowBlockDim,
int colBlockDim,
size_t* pBufferSize);
cusparseStatus_t CUSPARSEAPI
cusparseCcsr2gebsr_bufferSizeExt(cusparseHandle_t handle,
cusparseDirection_t dirA,
int m,
int n,
const cusparseMatDescr_t descrA,
const cuComplex* csrSortedValA,
const int* csrSortedRowPtrA,
const int* csrSortedColIndA,
int rowBlockDim,
int colBlockDim,
size_t* pBufferSize);
cusparseStatus_t CUSPARSEAPI
cusparseZcsr2gebsr_bufferSizeExt(cusparseHandle_t handle,
cusparseDirection_t dirA,
int m,
int n,
const cusparseMatDescr_t descrA,
const cuDoubleComplex* csrSortedValA,
const int* csrSortedRowPtrA,
const int* csrSortedColIndA,
int rowBlockDim,
int colBlockDim,
size_t* pBufferSize);
cusparseStatus_t CUSPARSEAPI
cusparseXcsr2gebsrNnz(cusparseHandle_t handle,
cusparseDirection_t dirA,
int m,
int n,
const cusparseMatDescr_t descrA,
const int* csrSortedRowPtrA,
const int* csrSortedColIndA,
const cusparseMatDescr_t descrC,
int* bsrSortedRowPtrC,
int rowBlockDim,
int colBlockDim,
int* nnzTotalDevHostPtr,
void* pBuffer);
cusparseStatus_t CUSPARSEAPI
cusparseScsr2gebsr(cusparseHandle_t handle,
cusparseDirection_t dirA,
int m,
int n,
const cusparseMatDescr_t descrA,
const float* csrSortedValA,
const int* csrSortedRowPtrA,
const int* csrSortedColIndA,
const cusparseMatDescr_t descrC,
float* bsrSortedValC,
int* bsrSortedRowPtrC,
int* bsrSortedColIndC,
int rowBlockDim,
int colBlockDim,
void* pBuffer);
cusparseStatus_t CUSPARSEAPI
cusparseDcsr2gebsr(cusparseHandle_t handle,
cusparseDirection_t dirA,
int m,
int n,
const cusparseMatDescr_t descrA,
const double* csrSortedValA,
const int* csrSortedRowPtrA,
const int* csrSortedColIndA,
const cusparseMatDescr_t descrC,
double* bsrSortedValC,
int* bsrSortedRowPtrC,
int* bsrSortedColIndC,
int rowBlockDim,
int colBlockDim,
void* pBuffer);
cusparseStatus_t CUSPARSEAPI
cusparseCcsr2gebsr(cusparseHandle_t handle,
cusparseDirection_t dirA,
int m,
int n,
const cusparseMatDescr_t descrA,
const cuComplex* csrSortedValA,
const int* csrSortedRowPtrA,
const int* csrSortedColIndA,
const cusparseMatDescr_t descrC,
cuComplex* bsrSortedValC,
int* bsrSortedRowPtrC,
int* bsrSortedColIndC,
int rowBlockDim,
int colBlockDim,
void* pBuffer);
cusparseStatus_t CUSPARSEAPI
cusparseZcsr2gebsr(cusparseHandle_t handle,
cusparseDirection_t dirA,
int m,
int n,
const cusparseMatDescr_t descrA,
const cuDoubleComplex* csrSortedValA,
const int* csrSortedRowPtrA,
const int* csrSortedColIndA,
const cusparseMatDescr_t descrC,
cuDoubleComplex* bsrSortedValC,
int* bsrSortedRowPtrC,
int* bsrSortedColIndC,
int rowBlockDim,
int colBlockDim,
void* pBuffer);
cusparseStatus_t CUSPARSEAPI
cusparseSgebsr2gebsr_bufferSize(cusparseHandle_t handle,
cusparseDirection_t dirA,
int mb,
int nb,
int nnzb,
const cusparseMatDescr_t descrA,
const float* bsrSortedValA,
const int* bsrSortedRowPtrA,
const int* bsrSortedColIndA,
int rowBlockDimA,
int colBlockDimA,
int rowBlockDimC,
int colBlockDimC,
int* pBufferSizeInBytes);
cusparseStatus_t CUSPARSEAPI
cusparseDgebsr2gebsr_bufferSize(cusparseHandle_t handle,
cusparseDirection_t dirA,
int mb,
int nb,
int nnzb,
const cusparseMatDescr_t descrA,
const double* bsrSortedValA,
const int* bsrSortedRowPtrA,
const int* bsrSortedColIndA,
int rowBlockDimA,
int colBlockDimA,
int rowBlockDimC,
int colBlockDimC,
int* pBufferSizeInBytes);
cusparseStatus_t CUSPARSEAPI
cusparseCgebsr2gebsr_bufferSize(cusparseHandle_t handle,
cusparseDirection_t dirA,
int mb,
int nb,
int nnzb,
const cusparseMatDescr_t descrA,
const cuComplex* bsrSortedValA,
const int* bsrSortedRowPtrA,
const int* bsrSortedColIndA,
int rowBlockDimA,
int colBlockDimA,
int rowBlockDimC,
int colBlockDimC,
int* pBufferSizeInBytes);
cusparseStatus_t CUSPARSEAPI
cusparseZgebsr2gebsr_bufferSize(cusparseHandle_t handle,
cusparseDirection_t dirA,
int mb,
int nb,
int nnzb,
const cusparseMatDescr_t descrA,
const cuDoubleComplex* bsrSortedValA,
const int* bsrSortedRowPtrA,
const int* bsrSortedColIndA,
int rowBlockDimA,
int colBlockDimA,
int rowBlockDimC,
int colBlockDimC,
int* pBufferSizeInBytes);
cusparseStatus_t CUSPARSEAPI
cusparseSgebsr2gebsr_bufferSizeExt(cusparseHandle_t handle,
cusparseDirection_t dirA,
int mb,
int nb,
int nnzb,
const cusparseMatDescr_t descrA,
const float* bsrSortedValA,
const int* bsrSortedRowPtrA,
const int* bsrSortedColIndA,
int rowBlockDimA,
int colBlockDimA,
int rowBlockDimC,
int colBlockDimC,
size_t* pBufferSize);
cusparseStatus_t CUSPARSEAPI
cusparseDgebsr2gebsr_bufferSizeExt(cusparseHandle_t handle,
cusparseDirection_t dirA,
int mb,
int nb,
int nnzb,
const cusparseMatDescr_t descrA,
const double* bsrSortedValA,
const int* bsrSortedRowPtrA,
const int* bsrSortedColIndA,
int rowBlockDimA,
int colBlockDimA,
int rowBlockDimC,
int colBlockDimC,
size_t* pBufferSize);
cusparseStatus_t CUSPARSEAPI
cusparseCgebsr2gebsr_bufferSizeExt(cusparseHandle_t handle,
cusparseDirection_t dirA,
int mb,
int nb,
int nnzb,
const cusparseMatDescr_t descrA,
const cuComplex* bsrSortedValA,
const int* bsrSortedRowPtrA,
const int* bsrSortedColIndA,
int rowBlockDimA,
int colBlockDimA,
int rowBlockDimC,
int colBlockDimC,
size_t* pBufferSize);
cusparseStatus_t CUSPARSEAPI
cusparseZgebsr2gebsr_bufferSizeExt(cusparseHandle_t handle,
cusparseDirection_t dirA,
int mb,
int nb,
int nnzb,
const cusparseMatDescr_t descrA,
const cuDoubleComplex* bsrSortedValA,
const int* bsrSortedRowPtrA,
const int* bsrSortedColIndA,
int rowBlockDimA,
int colBlockDimA,
int rowBlockDimC,
int colBlockDimC,
size_t* pBufferSize);
cusparseStatus_t CUSPARSEAPI
cusparseXgebsr2gebsrNnz(cusparseHandle_t handle,
cusparseDirection_t dirA,
int mb,
int nb,
int nnzb,
const cusparseMatDescr_t descrA,
const int* bsrSortedRowPtrA,
const int* bsrSortedColIndA,
int rowBlockDimA,
int colBlockDimA,
const cusparseMatDescr_t descrC,
int* bsrSortedRowPtrC,
int rowBlockDimC,
int colBlockDimC,
int* nnzTotalDevHostPtr,
void* pBuffer);
cusparseStatus_t CUSPARSEAPI
cusparseSgebsr2gebsr(cusparseHandle_t handle,
cusparseDirection_t dirA,
int mb,
int nb,
int nnzb,
const cusparseMatDescr_t descrA,
const float* bsrSortedValA,
const int* bsrSortedRowPtrA,
const int* bsrSortedColIndA,
int rowBlockDimA,
int colBlockDimA,
const cusparseMatDescr_t descrC,
float* bsrSortedValC,
int* bsrSortedRowPtrC,
int* bsrSortedColIndC,
int rowBlockDimC,
int colBlockDimC,
void* pBuffer);
cusparseStatus_t CUSPARSEAPI
cusparseDgebsr2gebsr(cusparseHandle_t handle,
cusparseDirection_t dirA,
int mb,
int nb,
int nnzb,
const cusparseMatDescr_t descrA,
const double* bsrSortedValA,
const int* bsrSortedRowPtrA,
const int* bsrSortedColIndA,
int rowBlockDimA,
int colBlockDimA,
const cusparseMatDescr_t descrC,
double* bsrSortedValC,
int* bsrSortedRowPtrC,
int* bsrSortedColIndC,
int rowBlockDimC,
int colBlockDimC,
void* pBuffer);
cusparseStatus_t CUSPARSEAPI
cusparseCgebsr2gebsr(cusparseHandle_t handle,
cusparseDirection_t dirA,
int mb,
int nb,
int nnzb,
const cusparseMatDescr_t descrA,
const cuComplex* bsrSortedValA,
const int* bsrSortedRowPtrA,
const int* bsrSortedColIndA,
int rowBlockDimA,
int colBlockDimA,
const cusparseMatDescr_t descrC,
cuComplex* bsrSortedValC,
int* bsrSortedRowPtrC,
int* bsrSortedColIndC,
int rowBlockDimC,
int colBlockDimC,
void* pBuffer);
cusparseStatus_t CUSPARSEAPI
cusparseZgebsr2gebsr(cusparseHandle_t handle,
cusparseDirection_t dirA,
int mb,
int nb,
int nnzb,
const cusparseMatDescr_t descrA,
const cuDoubleComplex* bsrSortedValA,
const int* bsrSortedRowPtrA,
const int* bsrSortedColIndA,
int rowBlockDimA,
int colBlockDimA,
const cusparseMatDescr_t descrC,
cuDoubleComplex* bsrSortedValC,
int* bsrSortedRowPtrC,
int* bsrSortedColIndC,
int rowBlockDimC,
int colBlockDimC,
void* pBuffer);
//##############################################################################
//# SPARSE MATRIX SORTING
//##############################################################################
cusparseStatus_t CUSPARSEAPI
cusparseCreateIdentityPermutation(cusparseHandle_t handle,
int n,
int* p);
cusparseStatus_t CUSPARSEAPI
cusparseXcoosort_bufferSizeExt(cusparseHandle_t handle,
int m,
int n,
int nnz,
const int* cooRowsA,
const int* cooColsA,
size_t* pBufferSizeInBytes);
cusparseStatus_t CUSPARSEAPI
cusparseXcoosortByRow(cusparseHandle_t handle,
int m,
int n,
int nnz,
int* cooRowsA,
int* cooColsA,
int* P,
void* pBuffer);
cusparseStatus_t CUSPARSEAPI
cusparseXcoosortByColumn(cusparseHandle_t handle,
int m,
int n,
int nnz,
int* cooRowsA,
int* cooColsA,
int* P,
void* pBuffer);
cusparseStatus_t CUSPARSEAPI
cusparseXcsrsort_bufferSizeExt(cusparseHandle_t handle,
int m,
int n,
int nnz,
const int* csrRowPtrA,
const int* csrColIndA,
size_t* pBufferSizeInBytes);
cusparseStatus_t CUSPARSEAPI
cusparseXcsrsort(cusparseHandle_t handle,
int m,
int n,
int nnz,
const cusparseMatDescr_t descrA,
const int* csrRowPtrA,
int* csrColIndA,
int* P,
void* pBuffer);
cusparseStatus_t CUSPARSEAPI
cusparseXcscsort_bufferSizeExt(cusparseHandle_t handle,
int m,
int n,
int nnz,
const int* cscColPtrA,
const int* cscRowIndA,
size_t* pBufferSizeInBytes);
cusparseStatus_t CUSPARSEAPI
cusparseXcscsort(cusparseHandle_t handle,
int m,
int n,
int nnz,
const cusparseMatDescr_t descrA,
const int* cscColPtrA,
int* cscRowIndA,
int* P,
void* pBuffer);
cusparseStatus_t CUSPARSEAPI
cusparseScsru2csr_bufferSizeExt(cusparseHandle_t handle,
int m,
int n,
int nnz,
float* csrVal,
const int* csrRowPtr,
int* csrColInd,
csru2csrInfo_t info,
size_t* pBufferSizeInBytes);
cusparseStatus_t CUSPARSEAPI
cusparseDcsru2csr_bufferSizeExt(cusparseHandle_t handle,
int m,
int n,
int nnz,
double* csrVal,
const int* csrRowPtr,
int* csrColInd,
csru2csrInfo_t info,
size_t* pBufferSizeInBytes);
cusparseStatus_t CUSPARSEAPI
cusparseCcsru2csr_bufferSizeExt(cusparseHandle_t handle,
int m,
int n,
int nnz,
cuComplex* csrVal,
const int* csrRowPtr,
int* csrColInd,
csru2csrInfo_t info,
size_t* pBufferSizeInBytes);
cusparseStatus_t CUSPARSEAPI
cusparseZcsru2csr_bufferSizeExt(cusparseHandle_t handle,
int m,
int n,
int nnz,
cuDoubleComplex* csrVal,
const int* csrRowPtr,
int* csrColInd,
csru2csrInfo_t info,
size_t* pBufferSizeInBytes);
cusparseStatus_t CUSPARSEAPI
cusparseScsru2csr(cusparseHandle_t handle,
int m,
int n,
int nnz,
const cusparseMatDescr_t descrA,
float* csrVal,
const int* csrRowPtr,
int* csrColInd,
csru2csrInfo_t info,
void* pBuffer);
cusparseStatus_t CUSPARSEAPI
cusparseDcsru2csr(cusparseHandle_t handle,
int m,
int n,
int nnz,
const cusparseMatDescr_t descrA,
double* csrVal,
const int* csrRowPtr,
int* csrColInd,
csru2csrInfo_t info,
void* pBuffer);
cusparseStatus_t CUSPARSEAPI
cusparseCcsru2csr(cusparseHandle_t handle,
int m,
int n,
int nnz,
const cusparseMatDescr_t descrA,
cuComplex* csrVal,
const int* csrRowPtr,
int* csrColInd,
csru2csrInfo_t info,
void* pBuffer);
cusparseStatus_t CUSPARSEAPI
cusparseZcsru2csr(cusparseHandle_t handle,
int m,
int n,
int nnz,
const cusparseMatDescr_t descrA,
cuDoubleComplex* csrVal,
const int* csrRowPtr,
int* csrColInd,
csru2csrInfo_t info,
void* pBuffer);
cusparseStatus_t CUSPARSEAPI
cusparseScsr2csru(cusparseHandle_t handle,
int m,
int n,
int nnz,
const cusparseMatDescr_t descrA,
float* csrVal,
const int* csrRowPtr,
int* csrColInd,
csru2csrInfo_t info,
void* pBuffer);
cusparseStatus_t CUSPARSEAPI
cusparseDcsr2csru(cusparseHandle_t handle,
int m,
int n,
int nnz,
const cusparseMatDescr_t descrA,
double* csrVal,
const int* csrRowPtr,
int* csrColInd,
csru2csrInfo_t info,
void* pBuffer);
cusparseStatus_t CUSPARSEAPI
cusparseCcsr2csru(cusparseHandle_t handle,
int m,
int n,
int nnz,
const cusparseMatDescr_t descrA,
cuComplex* csrVal,
const int* csrRowPtr,
int* csrColInd,
csru2csrInfo_t info,
void* pBuffer);
cusparseStatus_t CUSPARSEAPI
cusparseZcsr2csru(cusparseHandle_t handle,
int m,
int n,
int nnz,
const cusparseMatDescr_t descrA,
cuDoubleComplex* csrVal,
const int* csrRowPtr,
int* csrColInd,
csru2csrInfo_t info,
void* pBuffer);
#if defined(__cplusplus)
cusparseStatus_t CUSPARSEAPI
cusparseHpruneDense2csr_bufferSizeExt(cusparseHandle_t handle,
int m,
int n,
const __half* A,
int lda,
const __half* threshold,
const cusparseMatDescr_t descrC,
const __half* csrSortedValC,
const int* csrSortedRowPtrC,
const int* csrSortedColIndC,
size_t* pBufferSizeInBytes);
#endif // defined(__cplusplus)
cusparseStatus_t CUSPARSEAPI
cusparseSpruneDense2csr_bufferSizeExt(cusparseHandle_t handle,
int m,
int n,
const float* A,
int lda,
const float* threshold,
const cusparseMatDescr_t descrC,
const float* csrSortedValC,
const int* csrSortedRowPtrC,
const int* csrSortedColIndC,
size_t* pBufferSizeInBytes);
cusparseStatus_t CUSPARSEAPI
cusparseDpruneDense2csr_bufferSizeExt(cusparseHandle_t handle,
int m,
int n,
const double* A,
int lda,
const double* threshold,
const cusparseMatDescr_t descrC,
const double* csrSortedValC,
const int* csrSortedRowPtrC,
const int* csrSortedColIndC,
size_t* pBufferSizeInBytes);
#if defined(__cplusplus)
cusparseStatus_t CUSPARSEAPI
cusparseHpruneDense2csrNnz(cusparseHandle_t handle,
int m,
int n,
const __half* A,
int lda,
const __half* threshold,
const cusparseMatDescr_t descrC,
int* csrRowPtrC,
int* nnzTotalDevHostPtr,
void* pBuffer);
#endif // defined(__cplusplus)
cusparseStatus_t CUSPARSEAPI
cusparseSpruneDense2csrNnz(cusparseHandle_t handle,
int m,
int n,
const float* A,
int lda,
const float* threshold,
const cusparseMatDescr_t descrC,
int* csrRowPtrC,
int* nnzTotalDevHostPtr,
void* pBuffer);
cusparseStatus_t CUSPARSEAPI
cusparseDpruneDense2csrNnz(cusparseHandle_t handle,
int m,
int n,
const double* A,
int lda,
const double* threshold,
const cusparseMatDescr_t descrC,
int* csrSortedRowPtrC,
int* nnzTotalDevHostPtr,
void* pBuffer);
#if defined(__cplusplus)
cusparseStatus_t CUSPARSEAPI
cusparseHpruneDense2csr(cusparseHandle_t handle,
int m,
int n,
const __half* A,
int lda,
const __half* threshold,
const cusparseMatDescr_t descrC,
__half* csrSortedValC,
const int* csrSortedRowPtrC,
int* csrSortedColIndC,
void* pBuffer);
#endif // defined(__cplusplus)
cusparseStatus_t CUSPARSEAPI
cusparseSpruneDense2csr(cusparseHandle_t handle,
int m,
int n,
const float* A,
int lda,
const float* threshold,
const cusparseMatDescr_t descrC,
float* csrSortedValC,
const int* csrSortedRowPtrC,
int* csrSortedColIndC,
void* pBuffer);
cusparseStatus_t CUSPARSEAPI
cusparseDpruneDense2csr(cusparseHandle_t handle,
int m,
int n,
const double* A,
int lda,
const double* threshold,
const cusparseMatDescr_t descrC,
double* csrSortedValC,
const int* csrSortedRowPtrC,
int* csrSortedColIndC,
void* pBuffer);
#if defined(__cplusplus)
cusparseStatus_t CUSPARSEAPI
cusparseHpruneCsr2csr_bufferSizeExt(cusparseHandle_t handle,
int m,
int n,
int nnzA,
const cusparseMatDescr_t descrA,
const __half* csrSortedValA,
const int* csrSortedRowPtrA,
const int* csrSortedColIndA,
const __half* threshold,
const cusparseMatDescr_t descrC,
const __half* csrSortedValC,
const int* csrSortedRowPtrC,
const int* csrSortedColIndC,
size_t* pBufferSizeInBytes);
#endif // defined(__cplusplus)
cusparseStatus_t CUSPARSEAPI
cusparseSpruneCsr2csr_bufferSizeExt(cusparseHandle_t handle,
int m,
int n,
int nnzA,
const cusparseMatDescr_t descrA,
const float* csrSortedValA,
const int* csrSortedRowPtrA,
const int* csrSortedColIndA,
const float* threshold,
const cusparseMatDescr_t descrC,
const float* csrSortedValC,
const int* csrSortedRowPtrC,
const int* csrSortedColIndC,
size_t* pBufferSizeInBytes);
cusparseStatus_t CUSPARSEAPI
cusparseDpruneCsr2csr_bufferSizeExt(cusparseHandle_t handle,
int m,
int n,
int nnzA,
const cusparseMatDescr_t descrA,
const double* csrSortedValA,
const int* csrSortedRowPtrA,
const int* csrSortedColIndA,
const double* threshold,
const cusparseMatDescr_t descrC,
const double* csrSortedValC,
const int* csrSortedRowPtrC,
const int* csrSortedColIndC,
size_t* pBufferSizeInBytes);
#if defined(__cplusplus)
cusparseStatus_t CUSPARSEAPI
cusparseHpruneCsr2csrNnz(cusparseHandle_t handle,
int m,
int n,
int nnzA,
const cusparseMatDescr_t descrA,
const __half* csrSortedValA,
const int* csrSortedRowPtrA,
const int* csrSortedColIndA,
const __half* threshold,
const cusparseMatDescr_t descrC,
int* csrSortedRowPtrC,
int* nnzTotalDevHostPtr,
void* pBuffer);
#endif // defined(__cplusplus)
cusparseStatus_t CUSPARSEAPI
cusparseSpruneCsr2csrNnz(cusparseHandle_t handle,
int m,
int n,
int nnzA,
const cusparseMatDescr_t descrA,
const float* csrSortedValA,
const int* csrSortedRowPtrA,
const int* csrSortedColIndA,
const float* threshold,
const cusparseMatDescr_t descrC,
int* csrSortedRowPtrC,
int* nnzTotalDevHostPtr,
void* pBuffer);
cusparseStatus_t CUSPARSEAPI
cusparseDpruneCsr2csrNnz(cusparseHandle_t handle,
int m,
int n,
int nnzA,
const cusparseMatDescr_t descrA,
const double* csrSortedValA,
const int* csrSortedRowPtrA,
const int* csrSortedColIndA,
const double* threshold,
const cusparseMatDescr_t descrC,
int* csrSortedRowPtrC,
int* nnzTotalDevHostPtr,
void* pBuffer);
#if defined(__cplusplus)
cusparseStatus_t CUSPARSEAPI
cusparseHpruneCsr2csr(cusparseHandle_t handle,
int m,
int n,
int nnzA,
const cusparseMatDescr_t descrA,
const __half* csrSortedValA,
const int* csrSortedRowPtrA,
const int* csrSortedColIndA,
const __half* threshold,
const cusparseMatDescr_t descrC,
__half* csrSortedValC,
const int* csrSortedRowPtrC,
int* csrSortedColIndC,
void* pBuffer);
#endif // defined(__cplusplus)
cusparseStatus_t CUSPARSEAPI
cusparseSpruneCsr2csr(cusparseHandle_t handle,
int m,
int n,
int nnzA,
const cusparseMatDescr_t descrA,
const float* csrSortedValA,
const int* csrSortedRowPtrA,
const int* csrSortedColIndA,
const float* threshold,
const cusparseMatDescr_t descrC,
float* csrSortedValC,
const int* csrSortedRowPtrC,
int* csrSortedColIndC,
void* pBuffer);
cusparseStatus_t CUSPARSEAPI
cusparseDpruneCsr2csr(cusparseHandle_t handle,
int m,
int n,
int nnzA,
const cusparseMatDescr_t descrA,
const double* csrSortedValA,
const int* csrSortedRowPtrA,
const int* csrSortedColIndA,
const double* threshold,
const cusparseMatDescr_t descrC,
double* csrSortedValC,
const int* csrSortedRowPtrC,
int* csrSortedColIndC,
void* pBuffer);
#if defined(__cplusplus)
cusparseStatus_t CUSPARSEAPI
cusparseHpruneDense2csrByPercentage_bufferSizeExt(
cusparseHandle_t handle,
int m,
int n,
const __half* A,
int lda,
float percentage,
const cusparseMatDescr_t descrC,
const __half* csrSortedValC,
const int* csrSortedRowPtrC,
const int* csrSortedColIndC,
pruneInfo_t info,
size_t* pBufferSizeInBytes);
#endif // defined(__cplusplus)
cusparseStatus_t CUSPARSEAPI
cusparseSpruneDense2csrByPercentage_bufferSizeExt(
cusparseHandle_t handle,
int m,
int n,
const float* A,
int lda,
float percentage,
const cusparseMatDescr_t descrC,
const float* csrSortedValC,
const int* csrSortedRowPtrC,
const int* csrSortedColIndC,
pruneInfo_t info,
size_t* pBufferSizeInBytes);
cusparseStatus_t CUSPARSEAPI
cusparseDpruneDense2csrByPercentage_bufferSizeExt(
cusparseHandle_t handle,
int m,
int n,
const double* A,
int lda,
float percentage,
const cusparseMatDescr_t descrC,
const double* csrSortedValC,
const int* csrSortedRowPtrC,
const int* csrSortedColIndC,
pruneInfo_t info,
size_t* pBufferSizeInBytes);
#if defined(__cplusplus)
cusparseStatus_t CUSPARSEAPI
cusparseHpruneDense2csrNnzByPercentage(
cusparseHandle_t handle,
int m,
int n,
const __half* A,
int lda,
float percentage,
const cusparseMatDescr_t descrC,
int* csrRowPtrC,
int* nnzTotalDevHostPtr,
pruneInfo_t info,
void* pBuffer);
#endif // defined(__cplusplus)
cusparseStatus_t CUSPARSEAPI
cusparseSpruneDense2csrNnzByPercentage(
cusparseHandle_t handle,
int m,
int n,
const float* A,
int lda,
float percentage,
const cusparseMatDescr_t descrC,
int* csrRowPtrC,
int* nnzTotalDevHostPtr,
pruneInfo_t info,
void* pBuffer);
cusparseStatus_t CUSPARSEAPI
cusparseDpruneDense2csrNnzByPercentage(
cusparseHandle_t handle,
int m,
int n,
const double* A,
int lda,
float percentage,
const cusparseMatDescr_t descrC,
int* csrRowPtrC,
int* nnzTotalDevHostPtr,
pruneInfo_t info,
void* pBuffer);
#if defined(__cplusplus)
cusparseStatus_t CUSPARSEAPI
cusparseHpruneDense2csrByPercentage(cusparseHandle_t handle,
int m,
int n,
const __half* A,
int lda,
float percentage,
const cusparseMatDescr_t descrC,
__half* csrSortedValC,
const int* csrSortedRowPtrC,
int* csrSortedColIndC,
pruneInfo_t info,
void* pBuffer);
#endif // defined(__cplusplus)
cusparseStatus_t CUSPARSEAPI
cusparseSpruneDense2csrByPercentage(cusparseHandle_t handle,
int m,
int n,
const float* A,
int lda,
float percentage,
const cusparseMatDescr_t descrC,
float* csrSortedValC,
const int* csrSortedRowPtrC,
int* csrSortedColIndC,
pruneInfo_t info,
void* pBuffer);
cusparseStatus_t CUSPARSEAPI
cusparseDpruneDense2csrByPercentage(cusparseHandle_t handle,
int m,
int n,
const double* A,
int lda,
float percentage,
const cusparseMatDescr_t descrC,
double* csrSortedValC,
const int* csrSortedRowPtrC,
int* csrSortedColIndC,
pruneInfo_t info,
void* pBuffer);
#if defined(__cplusplus)
cusparseStatus_t CUSPARSEAPI
cusparseHpruneCsr2csrByPercentage_bufferSizeExt(
cusparseHandle_t handle,
int m,
int n,
int nnzA,
const cusparseMatDescr_t descrA,
const __half* csrSortedValA,
const int* csrSortedRowPtrA,
const int* csrSortedColIndA,
float percentage,
const cusparseMatDescr_t descrC,
const __half* csrSortedValC,
const int* csrSortedRowPtrC,
const int* csrSortedColIndC,
pruneInfo_t info,
size_t* pBufferSizeInBytes);
#endif // defined(__cplusplus)
cusparseStatus_t CUSPARSEAPI
cusparseSpruneCsr2csrByPercentage_bufferSizeExt(
cusparseHandle_t handle,
int m,
int n,
int nnzA,
const cusparseMatDescr_t descrA,
const float* csrSortedValA,
const int* csrSortedRowPtrA,
const int* csrSortedColIndA,
float percentage,
const cusparseMatDescr_t descrC,
const float* csrSortedValC,
const int* csrSortedRowPtrC,
const int* csrSortedColIndC,
pruneInfo_t info,
size_t* pBufferSizeInBytes);
cusparseStatus_t CUSPARSEAPI
cusparseDpruneCsr2csrByPercentage_bufferSizeExt(
cusparseHandle_t handle,
int m,
int n,
int nnzA,
const cusparseMatDescr_t descrA,
const double* csrSortedValA,
const int* csrSortedRowPtrA,
const int* csrSortedColIndA,
float percentage,
const cusparseMatDescr_t descrC,
const double* csrSortedValC,
const int* csrSortedRowPtrC,
const int* csrSortedColIndC,
pruneInfo_t info,
size_t* pBufferSizeInBytes);
#if defined(__cplusplus)
cusparseStatus_t CUSPARSEAPI
cusparseHpruneCsr2csrNnzByPercentage(
cusparseHandle_t handle,
int m,
int n,
int nnzA,
const cusparseMatDescr_t descrA,
const __half* csrSortedValA,
const int* csrSortedRowPtrA,
const int* csrSortedColIndA,
float percentage,
const cusparseMatDescr_t descrC,
int* csrSortedRowPtrC,
int* nnzTotalDevHostPtr,
pruneInfo_t info,
void* pBuffer);
#endif // defined(__cplusplus)
cusparseStatus_t CUSPARSEAPI
cusparseSpruneCsr2csrNnzByPercentage(
cusparseHandle_t handle,
int m,
int n,
int nnzA,
const cusparseMatDescr_t descrA,
const float* csrSortedValA,
const int* csrSortedRowPtrA,
const int* csrSortedColIndA,
float percentage,
const cusparseMatDescr_t descrC,
int* csrSortedRowPtrC,
int* nnzTotalDevHostPtr,
pruneInfo_t info,
void* pBuffer);
cusparseStatus_t CUSPARSEAPI
cusparseDpruneCsr2csrNnzByPercentage(
cusparseHandle_t handle,
int m,
int n,
int nnzA,
const cusparseMatDescr_t descrA,
const double* csrSortedValA,
const int* csrSortedRowPtrA,
const int* csrSortedColIndA,
float percentage,
const cusparseMatDescr_t descrC,
int* csrSortedRowPtrC,
int* nnzTotalDevHostPtr,
pruneInfo_t info,
void* pBuffer);
#if defined(__cplusplus)
cusparseStatus_t CUSPARSEAPI
cusparseHpruneCsr2csrByPercentage(cusparseHandle_t handle,
int m,
int n,
int nnzA,
const cusparseMatDescr_t descrA,
const __half* csrSortedValA,
const int* csrSortedRowPtrA,
const int* csrSortedColIndA,
float percentage, /* between 0 to 100 */
const cusparseMatDescr_t descrC,
__half* csrSortedValC,
const int* csrSortedRowPtrC,
int* csrSortedColIndC,
pruneInfo_t info,
void* pBuffer);
#endif // defined(__cplusplus)
cusparseStatus_t CUSPARSEAPI
cusparseSpruneCsr2csrByPercentage(cusparseHandle_t handle,
int m,
int n,
int nnzA,
const cusparseMatDescr_t descrA,
const float* csrSortedValA,
const int* csrSortedRowPtrA,
const int* csrSortedColIndA,
float percentage,
const cusparseMatDescr_t descrC,
float* csrSortedValC,
const int* csrSortedRowPtrC,
int* csrSortedColIndC,
pruneInfo_t info,
void* pBuffer);
cusparseStatus_t CUSPARSEAPI
cusparseDpruneCsr2csrByPercentage(cusparseHandle_t handle,
int m,
int n,
int nnzA,
const cusparseMatDescr_t descrA,
const double* csrSortedValA,
const int* csrSortedRowPtrA,
const int* csrSortedColIndA,
float percentage,
const cusparseMatDescr_t descrC,
double* csrSortedValC,
const int* csrSortedRowPtrC,
int* csrSortedColIndC,
pruneInfo_t info,
void* pBuffer);
//##############################################################################
//# CSR2CSC
//##############################################################################
typedef enum {
CUSPARSE_CSR2CSC_ALG1 = 1, // faster than V2 (in general), deterministc
CUSPARSE_CSR2CSC_ALG2 = 2 // low memory requirement, non-deterministc
} cusparseCsr2CscAlg_t;
cusparseStatus_t CUSPARSEAPI
cusparseCsr2cscEx2(cusparseHandle_t handle,
int m,
int n,
int nnz,
const void* csrVal,
const int* csrRowPtr,
const int* csrColInd,
void* cscVal,
int* cscColPtr,
int* cscRowInd,
cudaDataType valType,
cusparseAction_t copyValues,
cusparseIndexBase_t idxBase,
cusparseCsr2CscAlg_t alg,
void* buffer);
cusparseStatus_t CUSPARSEAPI
cusparseCsr2cscEx2_bufferSize(cusparseHandle_t handle,
int m,
int n,
int nnz,
const void* csrVal,
const int* csrRowPtr,
const int* csrColInd,
void* cscVal,
int* cscColPtr,
int* cscRowInd,
cudaDataType valType,
cusparseAction_t copyValues,
cusparseIndexBase_t idxBase,
cusparseCsr2CscAlg_t alg,
size_t* bufferSize);
// #############################################################################
// # GENERIC APIs - Enumerators and Opaque Data Structures
// #############################################################################
typedef enum {
CUSPARSE_FORMAT_CSR = 1, ///< Compressed Sparse Row (CSR)
CUSPARSE_FORMAT_CSC = 2, ///< Compressed Sparse Column (CSC)
CUSPARSE_FORMAT_COO = 3, ///< Coordinate (COO) - Structure of Arrays
CUSPARSE_FORMAT_COO_AOS = 4, ///< Coordinate (COO) - Array of Structures
CUSPARSE_FORMAT_BLOCKED_ELL = 5, ///< Blocked ELL
} cusparseFormat_t;
typedef enum {
CUSPARSE_ORDER_COL = 1, ///< Column-Major Order - Matrix memory layout
CUSPARSE_ORDER_ROW = 2 ///< Row-Major Order - Matrix memory layout
} cusparseOrder_t;
typedef enum {
CUSPARSE_INDEX_16U = 1, ///< 16-bit unsigned integer for matrix/vector
///< indices
CUSPARSE_INDEX_32I = 2, ///< 32-bit signed integer for matrix/vector indices
CUSPARSE_INDEX_64I = 3 ///< 64-bit signed integer for matrix/vector indices
} cusparseIndexType_t;
//------------------------------------------------------------------------------
struct cusparseSpVecDescr;
struct cusparseDnVecDescr;
struct cusparseSpMatDescr;
struct cusparseDnMatDescr;
typedef struct cusparseSpVecDescr* cusparseSpVecDescr_t;
typedef struct cusparseDnVecDescr* cusparseDnVecDescr_t;
typedef struct cusparseSpMatDescr* cusparseSpMatDescr_t;
typedef struct cusparseDnMatDescr* cusparseDnMatDescr_t;
// #############################################################################
// # SPARSE VECTOR DESCRIPTOR
// #############################################################################
cusparseStatus_t CUSPARSEAPI
cusparseCreateSpVec(cusparseSpVecDescr_t* spVecDescr,
int64_t size,
int64_t nnz,
void* indices,
void* values,
cusparseIndexType_t idxType,
cusparseIndexBase_t idxBase,
cudaDataType valueType);
cusparseStatus_t CUSPARSEAPI
cusparseDestroySpVec(cusparseSpVecDescr_t spVecDescr);
cusparseStatus_t CUSPARSEAPI
cusparseSpVecGet(cusparseSpVecDescr_t spVecDescr,
int64_t* size,
int64_t* nnz,
void** indices,
void** values,
cusparseIndexType_t* idxType,
cusparseIndexBase_t* idxBase,
cudaDataType* valueType);
cusparseStatus_t CUSPARSEAPI
cusparseSpVecGetIndexBase(cusparseSpVecDescr_t spVecDescr,
cusparseIndexBase_t* idxBase);
cusparseStatus_t CUSPARSEAPI
cusparseSpVecGetValues(cusparseSpVecDescr_t spVecDescr,
void** values);
cusparseStatus_t CUSPARSEAPI
cusparseSpVecSetValues(cusparseSpVecDescr_t spVecDescr,
void* values);
// #############################################################################
// # DENSE VECTOR DESCRIPTOR
// #############################################################################
cusparseStatus_t CUSPARSEAPI
cusparseCreateDnVec(cusparseDnVecDescr_t* dnVecDescr,
int64_t size,
void* values,
cudaDataType valueType);
cusparseStatus_t CUSPARSEAPI
cusparseDestroyDnVec(cusparseDnVecDescr_t dnVecDescr);
cusparseStatus_t CUSPARSEAPI
cusparseDnVecGet(cusparseDnVecDescr_t dnVecDescr,
int64_t* size,
void** values,
cudaDataType* valueType);
cusparseStatus_t CUSPARSEAPI
cusparseDnVecGetValues(cusparseDnVecDescr_t dnVecDescr,
void** values);
cusparseStatus_t CUSPARSEAPI
cusparseDnVecSetValues(cusparseDnVecDescr_t dnVecDescr,
void* values);
// #############################################################################
// # SPARSE MATRIX DESCRIPTOR
// #############################################################################
cusparseStatus_t CUSPARSEAPI
cusparseDestroySpMat(cusparseSpMatDescr_t spMatDescr);
cusparseStatus_t CUSPARSEAPI
cusparseSpMatGetFormat(cusparseSpMatDescr_t spMatDescr,
cusparseFormat_t* format);
cusparseStatus_t CUSPARSEAPI
cusparseSpMatGetIndexBase(cusparseSpMatDescr_t spMatDescr,
cusparseIndexBase_t* idxBase);
cusparseStatus_t CUSPARSEAPI
cusparseSpMatGetValues(cusparseSpMatDescr_t spMatDescr,
void** values);
cusparseStatus_t CUSPARSEAPI
cusparseSpMatSetValues(cusparseSpMatDescr_t spMatDescr,
void* values);
cusparseStatus_t CUSPARSEAPI
cusparseSpMatGetSize(cusparseSpMatDescr_t spMatDescr,
int64_t* rows,
int64_t* cols,
int64_t* nnz);
cusparseStatus_t CUSPARSEAPI
cusparseSpMatSetStridedBatch(cusparseSpMatDescr_t spMatDescr,
int batchCount);
cusparseStatus_t CUSPARSEAPI
cusparseSpMatGetStridedBatch(cusparseSpMatDescr_t spMatDescr,
int* batchCount);
cusparseStatus_t CUSPARSEAPI
cusparseCooSetStridedBatch(cusparseSpMatDescr_t spMatDescr,
int batchCount,
int64_t batchStride);
cusparseStatus_t CUSPARSEAPI
cusparseCsrSetStridedBatch(cusparseSpMatDescr_t spMatDescr,
int batchCount,
int64_t offsetsBatchStride,
int64_t columnsValuesBatchStride);
typedef enum {
CUSPARSE_SPMAT_FILL_MODE,
CUSPARSE_SPMAT_DIAG_TYPE
} cusparseSpMatAttribute_t;
cusparseStatus_t CUSPARSEAPI
cusparseSpMatGetAttribute(cusparseSpMatDescr_t spMatDescr,
cusparseSpMatAttribute_t attribute,
void* data,
size_t dataSize);
cusparseStatus_t CUSPARSEAPI
cusparseSpMatSetAttribute(cusparseSpMatDescr_t spMatDescr,
cusparseSpMatAttribute_t attribute,
void* data,
size_t dataSize);
//------------------------------------------------------------------------------
// ### CSR ###
cusparseStatus_t CUSPARSEAPI
cusparseCreateCsr(cusparseSpMatDescr_t* spMatDescr,
int64_t rows,
int64_t cols,
int64_t nnz,
void* csrRowOffsets,
void* csrColInd,
void* csrValues,
cusparseIndexType_t csrRowOffsetsType,
cusparseIndexType_t csrColIndType,
cusparseIndexBase_t idxBase,
cudaDataType valueType);
cusparseStatus_t CUSPARSEAPI
cusparseCreateCsc(cusparseSpMatDescr_t* spMatDescr,
int64_t rows,
int64_t cols,
int64_t nnz,
void* cscColOffsets,
void* cscRowInd,
void* cscValues,
cusparseIndexType_t cscColOffsetsType,
cusparseIndexType_t cscRowIndType,
cusparseIndexBase_t idxBase,
cudaDataType valueType);
cusparseStatus_t CUSPARSEAPI
cusparseCsrGet(cusparseSpMatDescr_t spMatDescr,
int64_t* rows,
int64_t* cols,
int64_t* nnz,
void** csrRowOffsets,
void** csrColInd,
void** csrValues,
cusparseIndexType_t* csrRowOffsetsType,
cusparseIndexType_t* csrColIndType,
cusparseIndexBase_t* idxBase,
cudaDataType* valueType);
cusparseStatus_t CUSPARSEAPI
cusparseCsrSetPointers(cusparseSpMatDescr_t spMatDescr,
void* csrRowOffsets,
void* csrColInd,
void* csrValues);
cusparseStatus_t CUSPARSEAPI
cusparseCscSetPointers(cusparseSpMatDescr_t spMatDescr,
void* cscColOffsets,
void* cscRowInd,
void* cscValues);
//------------------------------------------------------------------------------
// ### COO ###
cusparseStatus_t CUSPARSEAPI
cusparseCreateCoo(cusparseSpMatDescr_t* spMatDescr,
int64_t rows,
int64_t cols,
int64_t nnz,
void* cooRowInd,
void* cooColInd,
void* cooValues,
cusparseIndexType_t cooIdxType,
cusparseIndexBase_t idxBase,
cudaDataType valueType);
CUSPARSE_DEPRECATED(cusparseCreateCoo)
cusparseStatus_t CUSPARSEAPI
cusparseCreateCooAoS(cusparseSpMatDescr_t* spMatDescr,
int64_t rows,
int64_t cols,
int64_t nnz,
void* cooInd,
void* cooValues,
cusparseIndexType_t cooIdxType,
cusparseIndexBase_t idxBase,
cudaDataType valueType);
cusparseStatus_t CUSPARSEAPI
cusparseCooGet(cusparseSpMatDescr_t spMatDescr,
int64_t* rows,
int64_t* cols,
int64_t* nnz,
void** cooRowInd, // COO row indices
void** cooColInd, // COO column indices
void** cooValues, // COO values
cusparseIndexType_t* idxType,
cusparseIndexBase_t* idxBase,
cudaDataType* valueType);
CUSPARSE_DEPRECATED(cusparseCooGet)
cusparseStatus_t CUSPARSEAPI
cusparseCooAoSGet(cusparseSpMatDescr_t spMatDescr,
int64_t* rows,
int64_t* cols,
int64_t* nnz,
void** cooInd, // COO indices
void** cooValues, // COO values
cusparseIndexType_t* idxType,
cusparseIndexBase_t* idxBase,
cudaDataType* valueType);
cusparseStatus_t CUSPARSEAPI
cusparseCooSetPointers(cusparseSpMatDescr_t spMatDescr,
void* cooRows,
void* cooColumns,
void* cooValues);
//------------------------------------------------------------------------------
// ### BLOCKED ELL ###
cusparseStatus_t CUSPARSEAPI
cusparseCreateBlockedEll(cusparseSpMatDescr_t* spMatDescr,
int64_t rows,
int64_t cols,
int64_t ellBlockSize,
int64_t ellCols,
void* ellColInd,
void* ellValue,
cusparseIndexType_t ellIdxType,
cusparseIndexBase_t idxBase,
cudaDataType valueType);
cusparseStatus_t CUSPARSEAPI
cusparseBlockedEllGet(cusparseSpMatDescr_t spMatDescr,
int64_t* rows,
int64_t* cols,
int64_t* ellBlockSize,
int64_t* ellCols,
void** ellColInd,
void** ellValue,
cusparseIndexType_t* ellIdxType,
cusparseIndexBase_t* idxBase,
cudaDataType* valueType);
// #############################################################################
// # DENSE MATRIX DESCRIPTOR
// #############################################################################
cusparseStatus_t CUSPARSEAPI
cusparseCreateDnMat(cusparseDnMatDescr_t* dnMatDescr,
int64_t rows,
int64_t cols,
int64_t ld,
void* values,
cudaDataType valueType,
cusparseOrder_t order);
cusparseStatus_t CUSPARSEAPI
cusparseDestroyDnMat(cusparseDnMatDescr_t dnMatDescr);
cusparseStatus_t CUSPARSEAPI
cusparseDnMatGet(cusparseDnMatDescr_t dnMatDescr,
int64_t* rows,
int64_t* cols,
int64_t* ld,
void** values,
cudaDataType* type,
cusparseOrder_t* order);
cusparseStatus_t CUSPARSEAPI
cusparseDnMatGetValues(cusparseDnMatDescr_t dnMatDescr,
void** values);
cusparseStatus_t CUSPARSEAPI
cusparseDnMatSetValues(cusparseDnMatDescr_t dnMatDescr,
void* values);
cusparseStatus_t CUSPARSEAPI
cusparseDnMatSetStridedBatch(cusparseDnMatDescr_t dnMatDescr,
int batchCount,
int64_t batchStride);
cusparseStatus_t CUSPARSEAPI
cusparseDnMatGetStridedBatch(cusparseDnMatDescr_t dnMatDescr,
int* batchCount,
int64_t* batchStride);
// #############################################################################
// # VECTOR-VECTOR OPERATIONS
// #############################################################################
cusparseStatus_t CUSPARSEAPI
cusparseAxpby(cusparseHandle_t handle,
const void* alpha,
cusparseSpVecDescr_t vecX,
const void* beta,
cusparseDnVecDescr_t vecY);
cusparseStatus_t CUSPARSEAPI
cusparseGather(cusparseHandle_t handle,
cusparseDnVecDescr_t vecY,
cusparseSpVecDescr_t vecX);
cusparseStatus_t CUSPARSEAPI
cusparseScatter(cusparseHandle_t handle,
cusparseSpVecDescr_t vecX,
cusparseDnVecDescr_t vecY);
cusparseStatus_t CUSPARSEAPI
cusparseRot(cusparseHandle_t handle,
const void* c_coeff,
const void* s_coeff,
cusparseSpVecDescr_t vecX,
cusparseDnVecDescr_t vecY);
cusparseStatus_t CUSPARSEAPI
cusparseSpVV_bufferSize(cusparseHandle_t handle,
cusparseOperation_t opX,
cusparseSpVecDescr_t vecX,
cusparseDnVecDescr_t vecY,
const void* result,
cudaDataType computeType,
size_t* bufferSize);
cusparseStatus_t CUSPARSEAPI
cusparseSpVV(cusparseHandle_t handle,
cusparseOperation_t opX,
cusparseSpVecDescr_t vecX,
cusparseDnVecDescr_t vecY,
void* result,
cudaDataType computeType,
void* externalBuffer);
// #############################################################################
// # SPARSE TO DENSE
// #############################################################################
typedef enum {
CUSPARSE_SPARSETODENSE_ALG_DEFAULT = 0
} cusparseSparseToDenseAlg_t;
cusparseStatus_t CUSPARSEAPI
cusparseSparseToDense_bufferSize(cusparseHandle_t handle,
cusparseSpMatDescr_t matA,
cusparseDnMatDescr_t matB,
cusparseSparseToDenseAlg_t alg,
size_t* bufferSize);
cusparseStatus_t CUSPARSEAPI
cusparseSparseToDense(cusparseHandle_t handle,
cusparseSpMatDescr_t matA,
cusparseDnMatDescr_t matB,
cusparseSparseToDenseAlg_t alg,
void* buffer);
// #############################################################################
// # DENSE TO SPARSE
// #############################################################################
typedef enum {
CUSPARSE_DENSETOSPARSE_ALG_DEFAULT = 0
} cusparseDenseToSparseAlg_t;
cusparseStatus_t CUSPARSEAPI
cusparseDenseToSparse_bufferSize(cusparseHandle_t handle,
cusparseDnMatDescr_t matA,
cusparseSpMatDescr_t matB,
cusparseDenseToSparseAlg_t alg,
size_t* bufferSize);
cusparseStatus_t CUSPARSEAPI
cusparseDenseToSparse_analysis(cusparseHandle_t handle,
cusparseDnMatDescr_t matA,
cusparseSpMatDescr_t matB,
cusparseDenseToSparseAlg_t alg,
void* buffer);
cusparseStatus_t CUSPARSEAPI
cusparseDenseToSparse_convert(cusparseHandle_t handle,
cusparseDnMatDescr_t matA,
cusparseSpMatDescr_t matB,
cusparseDenseToSparseAlg_t alg,
void* buffer);
// #############################################################################
// # SPARSE MATRIX-VECTOR MULTIPLICATION
// #############################################################################
typedef enum {
CUSPARSE_MV_ALG_DEFAULT
/*CUSPARSE_DEPRECATED_ENUM(CUSPARSE_SPMV_ALG_DEFAULT)*/ = 0,
CUSPARSE_COOMV_ALG CUSPARSE_DEPRECATED_ENUM(CUSPARSE_SPMV_COO_ALG1) = 1,
CUSPARSE_CSRMV_ALG1 CUSPARSE_DEPRECATED_ENUM(CUSPARSE_SPMV_CSR_ALG1) = 2,
CUSPARSE_CSRMV_ALG2 CUSPARSE_DEPRECATED_ENUM(CUSPARSE_SPMV_CSR_ALG2) = 3,
CUSPARSE_SPMV_ALG_DEFAULT = 0,
CUSPARSE_SPMV_CSR_ALG1 = 2,
CUSPARSE_SPMV_CSR_ALG2 = 3,
CUSPARSE_SPMV_COO_ALG1 = 1,
CUSPARSE_SPMV_COO_ALG2 = 4
} cusparseSpMVAlg_t;
cusparseStatus_t CUSPARSEAPI
cusparseSpMV(cusparseHandle_t handle,
cusparseOperation_t opA,
const void* alpha,
cusparseSpMatDescr_t matA,
cusparseDnVecDescr_t vecX,
const void* beta,
cusparseDnVecDescr_t vecY,
cudaDataType computeType,
cusparseSpMVAlg_t alg,
void* externalBuffer);
cusparseStatus_t CUSPARSEAPI
cusparseSpMV_bufferSize(cusparseHandle_t handle,
cusparseOperation_t opA,
const void* alpha,
cusparseSpMatDescr_t matA,
cusparseDnVecDescr_t vecX,
const void* beta,
cusparseDnVecDescr_t vecY,
cudaDataType computeType,
cusparseSpMVAlg_t alg,
size_t* bufferSize);
// #############################################################################
// # SPARSE TRIANGULAR VECTOR SOLVE
// #############################################################################
typedef enum {
CUSPARSE_SPSV_ALG_DEFAULT = 0,
} cusparseSpSVAlg_t;
struct cusparseSpSVDescr;
typedef struct cusparseSpSVDescr* cusparseSpSVDescr_t;
cusparseStatus_t CUSPARSEAPI
cusparseSpSV_createDescr(cusparseSpSVDescr_t* descr);
cusparseStatus_t CUSPARSEAPI
cusparseSpSV_destroyDescr(cusparseSpSVDescr_t descr);
cusparseStatus_t CUSPARSEAPI
cusparseSpSV_bufferSize(cusparseHandle_t handle,
cusparseOperation_t opA,
const void* alpha,
cusparseSpMatDescr_t matA,
cusparseDnVecDescr_t vecX,
cusparseDnVecDescr_t vecY,
cudaDataType computeType,
cusparseSpSVAlg_t alg,
cusparseSpSVDescr_t spsvDescr,
size_t* bufferSize);
cusparseStatus_t CUSPARSEAPI
cusparseSpSV_analysis(cusparseHandle_t handle,
cusparseOperation_t opA,
const void* alpha,
cusparseSpMatDescr_t matA,
cusparseDnVecDescr_t vecX,
cusparseDnVecDescr_t vecY,
cudaDataType computeType,
cusparseSpSVAlg_t alg,
cusparseSpSVDescr_t spsvDescr,
void* externalBuffer);
cusparseStatus_t CUSPARSEAPI
cusparseSpSV_solve(cusparseHandle_t handle,
cusparseOperation_t opA,
const void* alpha,
cusparseSpMatDescr_t matA,
cusparseDnVecDescr_t vecX,
cusparseDnVecDescr_t vecY,
cudaDataType computeType,
cusparseSpSVAlg_t alg,
cusparseSpSVDescr_t spsvDescr);
// #############################################################################
// # SPARSE MATRIX-MATRIX MULTIPLICATION
// #############################################################################
typedef enum {
CUSPARSE_MM_ALG_DEFAULT
CUSPARSE_DEPRECATED_ENUM(CUSPARSE_SPMM_ALG_DEFAULT) = 0,
CUSPARSE_COOMM_ALG1 CUSPARSE_DEPRECATED_ENUM(CUSPARSE_SPMM_COO_ALG1) = 1,
CUSPARSE_COOMM_ALG2 CUSPARSE_DEPRECATED_ENUM(CUSPARSE_SPMM_COO_ALG2) = 2,
CUSPARSE_COOMM_ALG3 CUSPARSE_DEPRECATED_ENUM(CUSPARSE_SPMM_COO_ALG3) = 3,
CUSPARSE_CSRMM_ALG1 CUSPARSE_DEPRECATED_ENUM(CUSPARSE_SPMM_CSR_ALG1) = 4,
CUSPARSE_SPMM_ALG_DEFAULT = 0,
CUSPARSE_SPMM_COO_ALG1 = 1,
CUSPARSE_SPMM_COO_ALG2 = 2,
CUSPARSE_SPMM_COO_ALG3 = 3,
CUSPARSE_SPMM_COO_ALG4 = 5,
CUSPARSE_SPMM_CSR_ALG1 = 4,
CUSPARSE_SPMM_CSR_ALG2 = 6,
CUSPARSE_SPMM_CSR_ALG3 = 12,
CUSPARSE_SPMM_BLOCKED_ELL_ALG1 = 13
} cusparseSpMMAlg_t;
cusparseStatus_t CUSPARSEAPI
cusparseSpMM_bufferSize(cusparseHandle_t handle,
cusparseOperation_t opA,
cusparseOperation_t opB,
const void* alpha,
cusparseSpMatDescr_t matA,
cusparseDnMatDescr_t matB,
const void* beta,
cusparseDnMatDescr_t matC,
cudaDataType computeType,
cusparseSpMMAlg_t alg,
size_t* bufferSize);
cusparseStatus_t CUSPARSEAPI
cusparseSpMM_preprocess(cusparseHandle_t handle,
cusparseOperation_t opA,
cusparseOperation_t opB,
const void* alpha,
cusparseSpMatDescr_t matA,
cusparseDnMatDescr_t matB,
const void* beta,
cusparseDnMatDescr_t matC,
cudaDataType computeType,
cusparseSpMMAlg_t alg,
void* externalBuffer);
cusparseStatus_t CUSPARSEAPI
cusparseSpMM(cusparseHandle_t handle,
cusparseOperation_t opA,
cusparseOperation_t opB,
const void* alpha,
cusparseSpMatDescr_t matA,
cusparseDnMatDescr_t matB,
const void* beta,
cusparseDnMatDescr_t matC,
cudaDataType computeType,
cusparseSpMMAlg_t alg,
void* externalBuffer);
// #############################################################################
// # SPARSE MATRIX - SPARSE MATRIX MULTIPLICATION (SpGEMM)
// #############################################################################
typedef enum {
CUSPARSE_SPGEMM_DEFAULT = 0
} cusparseSpGEMMAlg_t;
struct cusparseSpGEMMDescr;
typedef struct cusparseSpGEMMDescr* cusparseSpGEMMDescr_t;
cusparseStatus_t CUSPARSEAPI
cusparseSpGEMM_createDescr(cusparseSpGEMMDescr_t* descr);
cusparseStatus_t CUSPARSEAPI
cusparseSpGEMM_destroyDescr(cusparseSpGEMMDescr_t descr);
cusparseStatus_t CUSPARSEAPI
cusparseSpGEMM_workEstimation(cusparseHandle_t handle,
cusparseOperation_t opA,
cusparseOperation_t opB,
const void* alpha,
cusparseSpMatDescr_t matA,
cusparseSpMatDescr_t matB,
const void* beta,
cusparseSpMatDescr_t matC,
cudaDataType computeType,
cusparseSpGEMMAlg_t alg,
cusparseSpGEMMDescr_t spgemmDescr,
size_t* bufferSize1,
void* externalBuffer1);
cusparseStatus_t CUSPARSEAPI
cusparseSpGEMM_compute(cusparseHandle_t handle,
cusparseOperation_t opA,
cusparseOperation_t opB,
const void* alpha,
cusparseSpMatDescr_t matA,
cusparseSpMatDescr_t matB,
const void* beta,
cusparseSpMatDescr_t matC,
cudaDataType computeType,
cusparseSpGEMMAlg_t alg,
cusparseSpGEMMDescr_t spgemmDescr,
size_t* bufferSize2,
void* externalBuffer2);
cusparseStatus_t CUSPARSEAPI
cusparseSpGEMM_copy(cusparseHandle_t handle,
cusparseOperation_t opA,
cusparseOperation_t opB,
const void* alpha,
cusparseSpMatDescr_t matA,
cusparseSpMatDescr_t matB,
const void* beta,
cusparseSpMatDescr_t matC,
cudaDataType computeType,
cusparseSpGEMMAlg_t alg,
cusparseSpGEMMDescr_t spgemmDescr);
// #############################################################################
// # SAMPLED DENSE-DENSE MATRIX MULTIPLICATION
// #############################################################################
CUSPARSE_DEPRECATED(cusparseSDDMM)
cusparseStatus_t CUSPARSEAPI
cusparseConstrainedGeMM(cusparseHandle_t handle,
cusparseOperation_t opA,
cusparseOperation_t opB,
const void* alpha,
cusparseDnMatDescr_t matA,
cusparseDnMatDescr_t matB,
const void* beta,
cusparseSpMatDescr_t matC,
cudaDataType computeType,
void* externalBuffer);
CUSPARSE_DEPRECATED(cusparseSDDMM)
cusparseStatus_t CUSPARSEAPI
cusparseConstrainedGeMM_bufferSize(cusparseHandle_t handle,
cusparseOperation_t opA,
cusparseOperation_t opB,
const void* alpha,
cusparseDnMatDescr_t matA,
cusparseDnMatDescr_t matB,
const void* beta,
cusparseSpMatDescr_t matC,
cudaDataType computeType,
size_t* bufferSize);
typedef enum {
CUSPARSE_SDDMM_ALG_DEFAULT = 0
} cusparseSDDMMAlg_t;
cusparseStatus_t CUSPARSEAPI
cusparseSDDMM_bufferSize(cusparseHandle_t handle,
cusparseOperation_t opA,
cusparseOperation_t opB,
const void* alpha,
cusparseDnMatDescr_t matA,
cusparseDnMatDescr_t matB,
const void* beta,
cusparseSpMatDescr_t matC,
cudaDataType computeType,
cusparseSDDMMAlg_t alg,
size_t* bufferSize);
cusparseStatus_t CUSPARSEAPI
cusparseSDDMM_preprocess(cusparseHandle_t handle,
cusparseOperation_t opA,
cusparseOperation_t opB,
const void* alpha,
cusparseDnMatDescr_t matA,
cusparseDnMatDescr_t matB,
const void* beta,
cusparseSpMatDescr_t matC,
cudaDataType computeType,
cusparseSDDMMAlg_t alg,
void* externalBuffer);
cusparseStatus_t CUSPARSEAPI
cusparseSDDMM(cusparseHandle_t handle,
cusparseOperation_t opA,
cusparseOperation_t opB,
const void* alpha,
cusparseDnMatDescr_t matA,
cusparseDnMatDescr_t matB,
const void* beta,
cusparseSpMatDescr_t matC,
cudaDataType computeType,
cusparseSDDMMAlg_t alg,
void* externalBuffer);
#if defined(__cplusplus)
} // extern "C"
#endif // defined(__cplusplus)
#undef CUSPARSE_DEPRECATED
#endif // !defined(CUSPARSE_H_)
| 49.052743 | 84 | 0.385879 | [
"vector"
] |
9f0a61d6f66bb08e5c8985e15c3b7a7d60b86e91 | 5,999 | c | C | VideoServer/libs/libg722_1/src/dct4.c | zengfanmao/mpds | c2bba464eaddc9ec70604a8614d84c5334461e8e | [
"MIT"
] | null | null | null | VideoServer/libs/libg722_1/src/dct4.c | zengfanmao/mpds | c2bba464eaddc9ec70604a8614d84c5334461e8e | [
"MIT"
] | null | null | null | VideoServer/libs/libg722_1/src/dct4.c | zengfanmao/mpds | c2bba464eaddc9ec70604a8614d84c5334461e8e | [
"MIT"
] | null | null | null | /*
* g722_1 - a library for the G.722.1 and Annex C codecs
*
* dct4.c
*
* Adapted by Steve Underwood <steveu@coppice.org> from the reference
* code supplied with ITU G.722.1, which is:
*
* (C)2004 Polycom, Inc.
* All rights reserved.
*
* 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.
*/
#if defined(HAVE_CONFIG_H)
#include <config.h>
#endif
#include <inttypes.h>
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <memory.h>
#include "g722_1/g722_1.h"
#include "defs.h"
#include "utilities.h"
#if !defined(G722_1_USE_FIXED_POINT)
typedef struct
{
float cosine;
float minus_sine;
} cos_msin_t;
#include "dct4.h"
static const cos_msin_t *cos_msin_table[] =
{
cos_msin_5,
cos_msin_10,
cos_msin_20,
cos_msin_40,
cos_msin_80,
cos_msin_160,
cos_msin_320,
cos_msin_640
};
/* Discrete Cosine Transform, Type IV */
void dct_type_iv(float input[], float output[], int dct_length)
{
float buffer_a[MAX_DCT_LENGTH];
float buffer_b[MAX_DCT_LENGTH];
float buffer_c[MAX_DCT_LENGTH];
float *in_ptr;
float *in_ptr_low;
float *in_ptr_high;
float *next_in_base;
float *out_ptr;
float *next_out_base;
float *out_buffer;
float *in_buffer;
float *buffer_swap;
float *fptr0;
float in_val_low;
float in_val_high;
float cos_even;
float cos_odd;
float msin_even;
float msin_odd;
const float *fptr2;
const float *core_a;
const cos_msin_t **table_ptr_ptr;
const cos_msin_t *cos_msin_ptr;
int set_span;
int set_count;
int set_count_log;
int pairs_left;
int sets_left;
int i;
int k;
int dct_length_log;
if (dct_length == MAX_DCT_LENGTH)
{
core_a = max_dct_core_a;
dct_length_log = MAX_DCT_LENGTH_LOG;
}
else
{
core_a = dct_core_a;
dct_length_log = DCT_LENGTH_LOG;
}
/* Do the sum/difference butterflies, the first part of
converting one N-point transform into N/2 two-point
transforms, where N = 1 << dct_length_log. */
in_buffer = input;
out_buffer = buffer_a;
for (set_count_log = 0; set_count_log <= dct_length_log - 2; set_count_log++)
{
/* Initialization for the loop over sets at the current size */
set_span = dct_length >> set_count_log;
set_count = 1 << set_count_log;
in_ptr = in_buffer;
next_out_base = out_buffer;
/* Loop over all the sets of this size */
for (sets_left = set_count; sets_left > 0; sets_left--)
{
/* Set up output pointers for the current set */
out_ptr = next_out_base;
next_out_base += set_span;
/* Loop over all the butterflies in the current set */
for (i = 0; i < (set_span >> 1); i++)
{
in_val_low = *in_ptr++;
in_val_high = *in_ptr++;
out_ptr[i] = in_val_low + in_val_high;
out_ptr[set_span - 1 - i] = in_val_low - in_val_high;
}
}
/* Decide which buffers to use as input and output next time.
Except for the first time (when the input buffer is the
subroutine input) we just alternate the local buffers. */
in_buffer = out_buffer;
out_buffer = (out_buffer == buffer_a) ? buffer_b : buffer_a;
}
/* Do dct_size/10 ten-point transforms */
fptr0 = in_buffer;
buffer_swap = buffer_c;
for (pairs_left = 1 << (dct_length_log - 1); pairs_left > 0; pairs_left--)
{
fptr2 = core_a;
for (k = 0; k < CORE_SIZE; k++)
{
buffer_swap[k] = vec_dot_prodf(fptr0, fptr2, CORE_SIZE);
fptr2 += CORE_SIZE;
}
fptr0 += CORE_SIZE;
buffer_swap += CORE_SIZE;
}
memcpy(in_buffer, buffer_c, dct_length*sizeof(float));
table_ptr_ptr = cos_msin_table;
/* Perform rotation butterflies */
for (set_count_log = dct_length_log - 2; set_count_log >= 0; set_count_log--)
{
/* Initialization for the loop over sets at the current size */
set_span = dct_length >> set_count_log;
set_count = 1 << set_count_log;
next_in_base = in_buffer;
next_out_base = (set_count_log == 0) ? output : out_buffer;
table_ptr_ptr++;
/* Loop over all the sets of this size */
for (sets_left = set_count; sets_left > 0; sets_left--)
{
/* Set up the pointers for the current set */
in_ptr_low = next_in_base;
in_ptr_high = in_ptr_low + (set_span >> 1);
out_ptr = next_out_base;
cos_msin_ptr = *table_ptr_ptr;
/* Loop over all the butterfly pairs in the current set */
for (i = 0; i < (set_span >> 1); i += 2)
{
cos_even = cos_msin_ptr[i].cosine;
msin_even = cos_msin_ptr[i].minus_sine;
cos_odd = cos_msin_ptr[i + 1].cosine;
msin_odd = cos_msin_ptr[i + 1].minus_sine;
out_ptr[i] = cos_even*in_ptr_low[i] - msin_even*in_ptr_high[i];
out_ptr[set_span - 1 - i] = msin_even*in_ptr_low[i] + cos_even*in_ptr_high[i];
out_ptr[i + 1] = cos_odd*in_ptr_low[i + 1] + msin_odd*in_ptr_high[i + 1];
out_ptr[set_span - 2 - i] = msin_odd*in_ptr_low[i + 1] - cos_odd*in_ptr_high[i + 1];
}
next_in_base += set_span;
next_out_base += set_span;
}
/* Swap input and output buffers for next time */
buffer_swap = in_buffer;
in_buffer = out_buffer;
out_buffer = buffer_swap;
}
}
/*- End of function --------------------------------------------------------*/
#endif
/*- End of file ------------------------------------------------------------*/
| 29.845771 | 100 | 0.589265 | [
"transform"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.