hexsha stringlengths 40 40 | size int64 5 2.72M | ext stringclasses 5
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 3 976 | max_stars_repo_name stringlengths 5 113 | max_stars_repo_head_hexsha stringlengths 40 78 | max_stars_repo_licenses listlengths 1 10 | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringdate 2015-01-01 00:01:43 2022-03-31 23:59:48 ⌀ | max_stars_repo_stars_event_max_datetime stringdate 2015-01-01 00:06:24 2022-03-31 23:59:53 ⌀ | max_issues_repo_path stringlengths 3 976 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 10 | max_issues_count float64 1 134k ⌀ | 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 976 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 10 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringdate 2015-01-01 00:01:19 2022-03-31 23:59:49 ⌀ | max_forks_repo_forks_event_max_datetime stringdate 2015-01-03 12:00:57 2022-03-31 23:59:49 ⌀ | content stringlengths 5 2.72M | avg_line_length float64 1.38 573k | max_line_length int64 2 1.01M | alphanum_fraction float64 0 1 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
034d06323f5d19a55e9659183724eba9e66caaeb | 424 | h | C | exemplos/07-TADs/complexo/complexo.h | flaviovdf/estruturas-de-dados | 328b591f3a1b74cc6db2c1210f74d69fb2df225a | [
"BSD-3-Clause"
] | 4 | 2018-12-17T17:00:18.000Z | 2021-06-25T12:49:45.000Z | exemplos/07-TADs/complexo/complexo.h | flaviovdf/estruturas-de-dados | 328b591f3a1b74cc6db2c1210f74d69fb2df225a | [
"BSD-3-Clause"
] | 1 | 2018-03-30T21:37:35.000Z | 2018-03-30T21:37:35.000Z | exemplos/07-TADs/complexo/complexo.h | flaviovdf/estruturas-de-dados | 328b591f3a1b74cc6db2c1210f74d69fb2df225a | [
"BSD-3-Clause"
] | 2 | 2018-03-30T18:57:02.000Z | 2019-04-02T03:14:35.000Z | #ifndef COMPLEXO_H
#define COMPLEXO_H
typedef struct {
double real;
double imaginario;
} complexo_t;
/*
* Adiciona 2 números complexos.
* Definido como a soma do real e a soma do imag.
*/
complexo_t add(complexo_t x, complexo_t y);
/*
* Multiplicação 2 números complexos
* usando: (rx + ix) * (ry + iy) =
* rx * ry + rx * ix + ix * ry + ix * iy
*/
complexo_t mult(complexo_t x, complexo_t y);
#endif
| 18.434783 | 49 | 0.653302 |
034d66934ed77a258ed002291f36f7fabe7ebf32 | 3,080 | c | C | src/backend/optimizer/path/hashutils.c | sfqtsh/postgres1.09 | 8c0099dc11299ca2ed31a0e567eaa7b173369594 | [
"BSD-4-Clause-UC"
] | 3 | 2019-05-28T18:32:49.000Z | 2022-01-25T11:41:26.000Z | src/backend/optimizer/path/hashutils.c | sfqtsh/postgres1.09 | 8c0099dc11299ca2ed31a0e567eaa7b173369594 | [
"BSD-4-Clause-UC"
] | 1 | 2018-08-10T09:41:03.000Z | 2018-08-10T09:41:03.000Z | src/backend/optimizer/path/hashutils.c | sfqtsh/postgres1.09 | 8c0099dc11299ca2ed31a0e567eaa7b173369594 | [
"BSD-4-Clause-UC"
] | 3 | 2016-07-20T03:54:09.000Z | 2022-02-05T16:05:30.000Z | /*-------------------------------------------------------------------------
*
* hashutils.c--
* Utilities for finding applicable merge clauses and pathkeys
*
* Copyright (c) 1994, Regents of the University of California
*
*
* IDENTIFICATION
* $Header: /usr/local/cvsroot/postgres95/src/backend/optimizer/path/hashutils.c,v 1.1.1.1 1996/07/09 06:21:35 scrappy Exp $
*
*-------------------------------------------------------------------------
*/
#include "postgres.h"
#include "nodes/pg_list.h"
#include "nodes/relation.h"
#include "optimizer/internal.h"
#include "optimizer/paths.h"
#include "optimizer/clauses.h"
static HInfo *match_hashop_hashinfo(Oid hashop, List *hashinfo_list);
/*
* group-clauses-by-hashop--
* If a join clause node in 'clauseinfo-list' is hashjoinable, store
* it within a hashinfo node containing other clause nodes with the same
* hash operator.
*
* 'clauseinfo-list' is the list of clauseinfo nodes
* 'inner-relid' is the relid of the inner join relation
*
* Returns the new list of hashinfo nodes.
*
*/
List *
group_clauses_by_hashop(List *clauseinfo_list,
int inner_relid)
{
List *hashinfo_list = NIL;
CInfo *clauseinfo = (CInfo*)NULL;
List *i = NIL;
Oid hashjoinop = 0;
foreach (i,clauseinfo_list) {
clauseinfo = (CInfo*)lfirst(i);
hashjoinop = clauseinfo->hashjoinoperator;
/*
* Create a new hashinfo node and add it to 'hashinfo-list' if one
* does not yet exist for this hash operator.
*/
if (hashjoinop ) {
HInfo *xhashinfo = (HInfo*)NULL;
Expr *clause = clauseinfo->clause;
Var *leftop = get_leftop(clause);
Var *rightop = get_rightop(clause);
JoinKey *keys = (JoinKey*)NULL;
xhashinfo =
match_hashop_hashinfo(hashjoinop,hashinfo_list);
if (inner_relid == leftop->varno){
keys = makeNode(JoinKey);
keys->outer = rightop;
keys->inner = leftop;
} else {
keys = makeNode(JoinKey);
keys->outer = leftop;
keys->inner = rightop;
}
if (xhashinfo==NULL) {
xhashinfo = makeNode(HInfo);
xhashinfo->hashop = hashjoinop;
xhashinfo->jmethod.jmkeys = NIL;
xhashinfo->jmethod.clauses = NIL;
/* XXX was push */
hashinfo_list = lappend(hashinfo_list,xhashinfo);
hashinfo_list = nreverse(hashinfo_list);
}
xhashinfo->jmethod.clauses =
lcons(clause, xhashinfo->jmethod.clauses);
xhashinfo->jmethod.jmkeys =
lcons(keys, xhashinfo->jmethod.jmkeys);
}
}
return(hashinfo_list);
}
/*
* match-hashop-hashinfo--
* Searches the list 'hashinfo-list' for a hashinfo node whose hash op
* field equals 'hashop'.
*
* Returns the node if it exists.
*
*/
static HInfo *
match_hashop_hashinfo(Oid hashop, List *hashinfo_list)
{
Oid key = 0;
HInfo *xhashinfo = (HInfo*)NULL;
List *i = NIL;
foreach( i, hashinfo_list) {
xhashinfo = (HInfo*)lfirst(i);
key = xhashinfo->hashop;
if (hashop == key) { /* found */
return(xhashinfo); /* should be a hashinfo node ! */
}
}
return((HInfo*)NIL);
}
| 25.454545 | 127 | 0.626299 |
034d83055c3d01de26da13978aba49cae4c2042f | 6,764 | h | C | Source/ThirdParty/Photon/Include/Common-cpp/inc/KeyObject.h | Brain-Vision/Unreal-SharedSpaces | 262153c5c52c4e15fed5ece901e0e1c8502bb030 | [
"MIT"
] | 33 | 2021-11-12T14:17:49.000Z | 2022-03-31T05:28:48.000Z | Source/ThirdParty/Photon/Include/Common-cpp/inc/KeyObject.h | Williero/Unreal-SharedSpaces | 90afcdd19b8628e53881ebdf847d88a5a181f286 | [
"MIT"
] | 7 | 2021-12-11T14:45:48.000Z | 2022-03-15T19:07:22.000Z | Source/ThirdParty/Photon/Include/Common-cpp/inc/KeyObject.h | Williero/Unreal-SharedSpaces | 90afcdd19b8628e53881ebdf847d88a5a181f286 | [
"MIT"
] | 14 | 2021-11-24T15:10:51.000Z | 2022-03-26T02:26:49.000Z | /* Exit Games Common - C++ Client Lib
* Copyright (C) 2004-2021 by Exit Games GmbH. All rights reserved.
* http://www.photonengine.com
* mailto:developer@photonengine.com
*/
#pragma once
#include "Common-cpp/inc/Helpers/ConfirmAllowedKey.h"
namespace ExitGames
{
namespace Common
{
/**
Container class template for objects to be stored as keys in a Hashtable or Dictionary.
@remarks
In most cases the library will do the work of storing a key in a KeyObject for you, so for example you don't have to explicitly
create an instance of this class, when storing a key-value pair in a Dictionary or Hashtable instance. However there are some
situations, where you will receive instances of class Object or want to create them (for example Hashtable::getKeys() will
return a JVector<Object>) and in that case casting those instances into KeyObject-instances can be a convenient way of assuring
a type-safe access to their payloads. */
template<typename Etype>
class KeyObject : public Object
{
public:
KeyObject(const KeyObject<Etype>& toCopy);
KeyObject(const Object& obj);
KeyObject(const Object* obj);
KeyObject(const typename Helpers::ConfirmAllowedKey<Etype>::type& data);
virtual ~KeyObject(void);
virtual KeyObject<Etype>& operator=(const KeyObject<Etype>& toCopy);
virtual KeyObject<Etype>& operator=(const Object& toCopy);
Etype getDataCopy(void) const;
Etype* getDataAddress(void) const;
protected:
virtual KeyObject<Etype>& assign(const Object& toCopy);
private:
typedef Object super;
void convert(const Object* obj, nByte type);
};
/** @file */
/**
Copy-Constructor.
Creates an object out of a deep copy of its parameter.
The parameter has to be of the same template instantiation as the
object, you want to create.
@param toCopy The object to copy. */
template<typename Etype>
KeyObject<Etype>::KeyObject(const KeyObject<Etype>& toCopy) : Object(toCopy)
{
}
/**
Constructor.
Creates an object out of a deep copy of the passed Object&.
If the type of the content of the passed object does not
match the template instantiation of the object to create, an empty
object is created instead of a copy of the passed object,
which leads to getDataCopy()
and getDataAddress() return
0.
@param obj The Object& to copy. */
template<typename Etype>
KeyObject<Etype>::KeyObject(const Object& obj)
{
convert(&obj, Helpers::ConfirmAllowedKey<Etype>::typeName);
}
/**
Constructor.
Creates an object out of a deep copy of the passed Object*.
If the type of the content of the passed object does not
match the template instantiation of the object to create, an empty
object is created instead of a copy of the passed object,
which leads to getDataCopy()
and getDataAddress() return
0.
@param obj The Object* to copy. */
template<typename Etype>
KeyObject<Etype>::KeyObject(const Object* const obj)
{
convert(obj, Helpers::ConfirmAllowedKey<Etype>::typeName);
}
/**
Constructor.
Creates an object out of a deep copy of the passed Etype.
@param data The value to copy. Has to be of a supported type. */
template<typename Etype>
KeyObject<Etype>::KeyObject(const typename Helpers::ConfirmAllowedKey<Etype>::type& data) : Object(&data, Helpers::ConfirmAllowedKey<Etype>::typeName, 0, true)
{
}
/**
Destructor. */
template<typename Etype>
KeyObject<Etype>::~KeyObject(void)
{
}
/**
operator= : Makes a deep copy of its right operand into its
left operand. This overwrites old data in the left operand. */
template<typename Etype>
KeyObject<Etype>& KeyObject<Etype>::operator=(const KeyObject<Etype>& toCopy)
{
return assign(toCopy);
}
/**
operator= : Makes a deep copy of its right operand into its
left operand. This overwrites old data in the left operand.
If the type of the content of the right operand does not
match the template instantiation of the left operand, then the left
operand stays unchanged. */
template<typename Etype>
KeyObject<Etype>& KeyObject<Etype>::operator=(const Object& toCopy)
{
return assign(toCopy);
}
template<typename Etype>
KeyObject<Etype>& KeyObject<Etype>::assign(const Object& toCopy)
{
if(Helpers::ConfirmAllowedKey<Etype>::typeName == toCopy.getType())
super::assign(toCopy);
return *this;
}
/**
Returns a deep copy of the content of the object. If you
only need access to the content, while the object still
exists, you can use getDataAddress()
instead to avoid the deep copy. That is especially
interesting for large content, of course.
If successful, the template instantiations for array types of this
function allocate the data for the copy, so you have to free
(for arrays of primitive types) or delete (for arrays of
class objects) it, as soon, as you do not need the array
anymore. All non-array copies free there memory
automatically, as soon as they leave their scope, same as the
single indices of the array, as soon, as the array is freed.
In case of an error this function returns 0 for primitive
return types and empty objects for classes.
@returns
a deep copy of the content of the object if successful, 0 or
an empty object otherwise. */
template<typename Etype>
inline Etype KeyObject<Etype>::getDataCopy(void) const
{
if(getType() == Helpers::ConfirmAllowedKey<Etype>::typeName)
return *(Etype*)getData();
else
return Etype();
}
/**
Returns the address of the original content of the object.
If you need access to the data above lifetime of the object,
call getDataCopy().
The return type is a pointer to the data, so it is a
double-pointer, of course, for template instantiations, which data
already is a pointer.
In case of an error, this function returns 0.
@returns
the address of the original content of the object, if
successful, 0 otherwise. */
template<typename Etype>
inline Etype* KeyObject<Etype>::getDataAddress(void) const
{
if(getType() == Helpers::ConfirmAllowedKey<Etype>::typeName)
return (Etype*)getData();
else
return 0;
}
template<typename Etype>
void KeyObject<Etype>::convert(const Object* const obj, nByte type)
{
super::assign((obj && type == obj->getType())?*obj:Object());
}
}
} | 33.156863 | 161 | 0.676079 |
034d91076ea6cf38f5f5c22fc1fc8bed44968c58 | 3,598 | c | C | framework/src/jshardware_common.c | leeeastwood/Haiway | 153b6861f864966c454f97febe03ae191a9a8657 | [
"MIT"
] | 162 | 2019-01-04T14:23:52.000Z | 2021-12-26T05:51:34.000Z | framework/src/jshardware_common.c | leeeastwood/Haiway | 153b6861f864966c454f97febe03ae191a9a8657 | [
"MIT"
] | 6 | 2019-01-04T14:32:15.000Z | 2020-08-07T06:47:34.000Z | framework/src/jshardware_common.c | leeeastwood/Haiway | 153b6861f864966c454f97febe03ae191a9a8657 | [
"MIT"
] | 130 | 2019-01-04T14:24:33.000Z | 2021-06-25T16:48:56.000Z | /*
* This file is part of Espruino, a JavaScript interpreter for Microcontrollers
*
* Copyright (C) 2013 Gordon Williams <gw@pur3.co.uk>
*
* 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/.
*
* ----------------------------------------------------------------------------
* Hardware interface Layer common functions
* ----------------------------------------------------------------------------
*/
#include "jshardware.h"
#include "jsinteractive.h"
#include "platform_config.h"
void jshUSARTInitInfo(JshUSARTInfo *inf) {
inf->baudRate = DEFAULT_BAUD_RATE;
inf->pinRX = PIN_UNDEFINED;
inf->pinTX = PIN_UNDEFINED;
inf->pinCK = PIN_UNDEFINED;
inf->pinCTS = PIN_UNDEFINED;
inf->bytesize = DEFAULT_BYTESIZE;
inf->parity = DEFAULT_PARITY; // PARITY_NONE = 0, PARITY_ODD = 1, PARITY_EVEN = 2 FIXME: enum?
inf->stopbits = DEFAULT_STOPBITS;
inf->xOnXOff = false;
inf->errorHandling = false;
}
void jshSPIInitInfo(JshSPIInfo *inf) {
inf->baudRate = 100000;
inf->baudRateSpec = SPIB_DEFAULT;
inf->pinSCK = PIN_UNDEFINED;
inf->pinMISO = PIN_UNDEFINED;
inf->pinMOSI = PIN_UNDEFINED;
inf->spiMode = SPIF_SPI_MODE_0;
inf->spiMSB = true; // MSB first is default
inf->numBits = 8;
}
void jshI2CInitInfo(JshI2CInfo *inf) {
inf->pinSCL = PIN_UNDEFINED;
inf->pinSDA = PIN_UNDEFINED;
inf->bitrate = 100000;
inf->started = false;
}
void jshFlashWriteAligned(void *buf, uint32_t addr, uint32_t len) {
#ifdef SPIFLASH_BASE
if (addr >= SPIFLASH_BASE) {
// If using external flash it doesn't care about alignment, so don't bother
jshFlashWrite(buf, addr, len);
return;
}
#endif
unsigned char *dPtr = (unsigned char *)buf;
uint32_t alignOffset = addr & (JSF_ALIGNMENT-1);
if (alignOffset) {
char buf[JSF_ALIGNMENT];
jshFlashRead(buf, addr-alignOffset, JSF_ALIGNMENT);
uint32_t alignRemainder = JSF_ALIGNMENT-alignOffset;
if (alignRemainder > len)
alignRemainder = len;
memcpy(&buf[alignOffset], dPtr, alignRemainder);
dPtr += alignRemainder;
jshFlashWrite(buf, addr-alignOffset, JSF_ALIGNMENT);
addr += alignRemainder;
if (alignRemainder >= len)
return; // we're done!
len -= alignRemainder;
}
// Do aligned write
alignOffset = len & (JSF_ALIGNMENT-1);
len -= alignOffset;
if (len)
jshFlashWrite(dPtr, addr, len);
addr += len;
dPtr += len;
// Do final unaligned write
if (alignOffset) {
char buf[JSF_ALIGNMENT];
jshFlashRead(buf, addr, JSF_ALIGNMENT);
memcpy(buf, dPtr, alignOffset);
jshFlashWrite(buf, addr, JSF_ALIGNMENT);
}
}
/** Send data in tx through the given SPI device and return the response in
* rx (if supplied). Returns true on success */
__attribute__((weak)) bool jshSPISendMany(IOEventFlags device, unsigned char *tx, unsigned char *rx, size_t count, void (*callback)()) {
size_t txPtr = 0;
size_t rxPtr = 0;
// transmit the data
while (txPtr<count && !jspIsInterrupted()) {
int data = jshSPISend(device, tx[txPtr++]);
if (data>=0) {
if (rx) rx[rxPtr] = (char)data;
rxPtr++;
}
}
// clear the rx buffer
while (rxPtr<count && !jspIsInterrupted()) {
int data = jshSPISend(device, -1);
if (rx) rx[rxPtr] = (char)data;
rxPtr++;
}
// call the callback
if (callback) callback();
return true;
}
// Only define this if it's not used elsewhere
__attribute__((weak)) void jshBusyIdle() {
}
| 31.286957 | 136 | 0.643691 |
0351552660af383b5887242fc634222b4fde687e | 1,372 | h | C | testing/test_gl_surface.h | shyndman/engine | 8a068a1bd7d55d3e90561e8a1576d5668bf17fe5 | [
"BSD-3-Clause"
] | 2 | 2018-12-16T04:00:07.000Z | 2019-05-24T04:05:50.000Z | testing/test_gl_surface.h | WangLuofan/engine | fcbb079921c58280d2a78589a9439fd36f7e4beb | [
"BSD-3-Clause"
] | null | null | null | testing/test_gl_surface.h | WangLuofan/engine | fcbb079921c58280d2a78589a9439fd36f7e4beb | [
"BSD-3-Clause"
] | 1 | 2019-03-24T09:33:27.000Z | 2019-03-24T09:33:27.000Z | // Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_TESTING_TEST_GL_SURFACE_H_
#define FLUTTER_TESTING_TEST_GL_SURFACE_H_
#include <cstdint>
#include "flutter/fml/macros.h"
#include "third_party/skia/include/gpu/GrContext.h"
namespace flutter {
namespace testing {
class TestGLSurface {
public:
TestGLSurface();
~TestGLSurface();
bool MakeCurrent();
bool ClearCurrent();
bool Present();
uint32_t GetFramebuffer() const;
bool MakeResourceCurrent();
void* GetProcAddress(const char* name) const;
sk_sp<GrContext> CreateContext();
private:
// Importing the EGL.h pulls in platform headers which are problematic
// (especially X11 which #defineds types like Bool). Any TUs importing
// this header then become susceptible to failures because of platform
// specific craziness. Don't expose EGL internals via this header.
using EGLDisplay = void*;
using EGLContext = void*;
using EGLSurface = void*;
EGLDisplay display_;
EGLContext onscreen_context_;
EGLContext offscreen_context_;
EGLSurface onscreen_surface_;
EGLSurface offscreen_surface_;
FML_DISALLOW_COPY_AND_ASSIGN(TestGLSurface);
};
} // namespace testing
} // namespace flutter
#endif // FLUTTER_TESTING_TEST_GL_SURFACE_H_
| 23.655172 | 73 | 0.762391 |
03526f6cf46eb8a9908b2363770412b03b57eeda | 152,096 | c | C | src/kernel/memory/malloc.c | GrieferAtWork/KOSmk2 | 446a982c7930eeb48710bcb234c4e4b15446b869 | [
"Zlib"
] | 1 | 2021-01-02T22:15:14.000Z | 2021-01-02T22:15:14.000Z | src/kernel/memory/malloc.c | GrieferAtWork/KOSmk2 | 446a982c7930eeb48710bcb234c4e4b15446b869 | [
"Zlib"
] | null | null | null | src/kernel/memory/malloc.c | GrieferAtWork/KOSmk2 | 446a982c7930eeb48710bcb234c4e4b15446b869 | [
"Zlib"
] | 1 | 2019-10-21T17:39:46.000Z | 2019-10-21T17:39:46.000Z | /* Copyright (c) 2017 Griefer@Work *
* *
* 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, subject to the following restrictions: *
* *
* 1. The origin of this software must not be misrepresented; you must not *
* claim that you wrote the original software. If you use this software *
* in a product, an acknowledgement in the product documentation would be *
* appreciated but is not required. *
* 2. Altered source versions must be plainly marked as such, and must not be *
* misrepresented as being the original software. *
* 3. This notice may not be removed or altered from any source distribution. *
*/
#ifndef GUARD_KERNEL_MEMORY_MALLOC_C
#define GUARD_KERNEL_MEMORY_MALLOC_C 1
#define _KOS_SOURCE 1
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wmaybe-uninitialized"
#include "../debug-config.h"
#include <assert.h>
#include <format-printer.h>
#include <hybrid/asm.h>
#include <hybrid/align.h>
#include <hybrid/check.h>
#include <hybrid/compiler.h>
#include <hybrid/debuginfo.h>
#include <hybrid/list/atree.h>
#include <hybrid/list/list.h>
#include <hybrid/minmax.h>
#include <hybrid/debug.h>
#include <hybrid/section.h>
#include <hybrid/sync/atomic-owner-rwlock.h>
#include <hybrid/sync/atomic-rwlock.h>
#include <hybrid/traceback.h>
#include <hybrid/typecore.h>
#include <kernel/interrupt.h>
#include <kernel/malloc.h>
#include <kernel/memory.h>
#include <kernel/mman.h>
#include <kernel/paging-util.h>
#include <kernel/paging.h>
#include <sys/syslog.h>
#include <linker/module.h>
#include <sched/cpu.h>
#include <sched/paging.h>
#include <sched/task.h>
#include <stdarg.h>
#include <stdio.h>
#include <string.h>
#include <string.h>
#include <arch/hints.h>
#include <sys/mman.h>
#if defined(__i386__) || defined(__x86_64__)
#include <asm/instx.h>
#include <arch/hints.h>
#endif
#define MALIGNED /* Annotation for an integral/pointer aligned by `HEAP_ALIGNMENT' */
DECL_BEGIN
#if 0 /* Disable all debug functionality. */
#define CONFIG_MALLOC_NO_DEBUG_INIT
#undef CONFIG_TRACE_LEAKS
#define CONFIG_MALLOC_HEADSIZE 0
#define CONFIG_MALLOC_FOOTSIZE 0
#define CONFIG_MALLOC_TRACEBACK 0
#endif
/* MALLOC configuration options:
*
* >> #define CONFIG_DEBUG_HEAP <BOOL>
* Enable all debug functionality, as well as additional
* internal integrity checks for heap-based kernel allocations.
* This option is enabled by default when the kernel core is
* being compiled in debug mode (CONFIG_DEBUG).
* Define as 0 to disable in every context.
*
* >> [GLOBAL] #define CONFIG_TRACE_LEAKS
* When defined, track all dynamically allocated pointers,
* based on which `struct instance' allocated them.
* This option must be defined in `.sources', as it affects
* the layout of data structures elsewhere, too.
* NOTE: In addition, this option enables validation of a
* 16-bit checksum whenever an mall-pointer is loaded,
* essentially enabling additional safety constraints
* whenever operating on dynamically allocated memory.
*
* >> #define CONFIG_MALLOC_HEADSIZE <SIZE>
* DEFAULT: IFDEF(CONFIG_DEBUG_HEAP): HEAP_ALIGNMENT
* DEFAULT: ELSE: 0
* Set the size of a small area of memory to-be allocated
* before all heap pointers.
* During (re-)allocation, this area is filled with random,
* but consistent values that are later re-checked for
* validity, thus allowing for early detection of most
* buffer underflow attacks.
*
* >> #define CONFIG_MALLOC_FOOTSIZE <SIZE>
* DEFAULT: IFDEF(CONFIG_DEBUG_HEAP): HEAP_ALIGNMENT
* DEFAULT: ELSE: 0
* Similar to `CONFIG_MALLOC_HEADSIZE', but located at
* the other end, this option is useful for detecting
* buffer overflow attacks.
* WARNING: Enabling this option guaranties 1-byte alignment
* in `kmalloc_usable_size()', disallowing any
* access to trailing data during allocations.
*
* >> #define CONFIG_MALLOC_NO_DEBUG_INIT <BOOL>
* DEFAULT: != DEFINED(CONFIG_DEBUG_HEAP)
* >> #define CONFIG_MALLOC_DEBUG_INIT <BYTE>
* DEFAULT: IFNDEF(CONFIG_MALLOC_NO_DEBUG_INIT)
* IFDEF (CONFIG_DEBUG_HEAP): 0xc3
* Define the default initialization of heap-allocated memory
* to always allocate data pre-initialized to `CONFIG_DEBUG_HEAP'
* This option only affects memory not allocated with `GFP_CALLOC',
* and is internally implemented by making use of mregion
* initialization, meaning that enabling this option will not
* increase memory allocation overhead/waste when allocating
* virtual (GFP_KERNEL or GFP_SHARED/GFP_NORMAL) memory.
* NOTE: `0xc3' was chosen because of its unique binary layout: `0b11000011'
*
* >> #define CONFIG_MALLOC_TRACEBACK <BOOL>
* DEFAULT: IFDEF(CONFIG_TRACE_LEAKS): 1
* REQUIRES: IFDEF(CONFIG_TRACE_LEAKS)
* >> #define CONFIG_MALLOC_TRACEBACK_MINSIZE <SIZE>
* DEFAULT: IFDEF(CONFIG_MALLOC_TRACEBACK): 4
* Store a short traceback of at least `CONFIG_MALLOC_TRACEBACK_MINSIZE'
* entries within the trailing memory located after every allocated pointer.
*
* >> #define CONFIG_MALLOC_NO_FREQUENCY <BOOL>
* DEFAULT: != DEFINED(CONFIG_DEBUG_HEAP)
* >> #define CONFIG_MALLOC_FREQUENCY <UNSIGNED INT>
* DEFAULT: IFNDEF(CONFIG_MALLOC_NO_FREQUENCY)
* IFDEF (CONFIG_DEBUG_HEAP): 1024
* The frequency on which the global state of all kernel heaps
* are checked for errors, such as access-after-free, among others.
* The frequency is automatically triggered once for every call to
* any allocating, or free-ing function.
* Note that is operation is very costly and the frequency (when available)
* can be re-configured using mallopt(M_MALL_CHECK_FREQUENCY) at runtime.
*/
#ifndef CONFIG_DEBUG_HEAP
#ifdef CONFIG_DEBUG
# define CONFIG_DEBUG_HEAP 1
#endif
#elif (CONFIG_DEBUG_HEAP+0) == 0
# undef CONFIG_DEBUG_HEAP
#endif
#ifdef CONFIG_MALLOC_NO_DEBUG_INIT
#if (CONFIG_MALLOC_NO_DEBUG_INIT+0) == 0
# undef CONFIG_MALLOC_NO_DEBUG_INIT
#endif
#endif
#ifndef CONFIG_MALLOC_DEBUG_INIT
#if !defined(CONFIG_MALLOC_NO_DEBUG_INIT) && \
defined(CONFIG_DEBUG_HEAP)
# define CONFIG_MALLOC_DEBUG_INIT KERNEL_DEBUG_MEMPAT_KMALLOC
#endif
#elif defined(CONFIG_MALLOC_NO_DEBUG_INIT)
# undef CONFIG_MALLOC_DEBUG_INIT
#endif
#if !defined(CONFIG_MALLOC_DEBUG_INIT) && \
!defined(CONFIG_MALLOC_NO_DEBUG_INIT)
#define CONFIG_MALLOC_NO_DEBUG_INIT
#endif
/* The min amount of traceback entries to track for any allocation. */
#ifdef CONFIG_TRACE_LEAKS
#ifndef CONFIG_MALLOC_TRACEBACK
# define CONFIG_MALLOC_TRACEBACK 1
#elif (CONFIG_MALLOC_TRACEBACK+0) == 0
# undef CONFIG_MALLOC_TRACEBACK
#endif
#elif defined(CONFIG_MALLOC_TRACEBACK)
# undef CONFIG_MALLOC_TRACEBACK
#endif
#ifdef CONFIG_MALLOC_TRACEBACK
#ifndef CONFIG_MALLOC_TRACEBACK_MINSIZE
# define CONFIG_MALLOC_TRACEBACK_MINSIZE 4
#endif
#else
# undef CONFIG_MALLOC_TRACEBACK_MINSIZE
#endif
#ifndef CONFIG_MALLOC_HEADSIZE
#ifdef CONFIG_DEBUG_HEAP
# define CONFIG_MALLOC_HEADSIZE HEAP_ALIGNMENT
#endif
#elif (CONFIG_MALLOC_HEADSIZE+0) == 0
# undef CONFIG_MALLOC_HEADSIZE
#endif
#ifndef CONFIG_MALLOC_FOOTSIZE
#ifdef CONFIG_DEBUG_HEAP
# define CONFIG_MALLOC_FOOTSIZE HEAP_ALIGNMENT
#endif
#elif (CONFIG_MALLOC_FOOTSIZE+0) == 0
# undef CONFIG_MALLOC_FOOTSIZE
#endif
#ifdef CONFIG_MALLOC_NO_FREQUENCY
#if (CONFIG_MALLOC_NO_FREQUENCY+0) == 0
# undef CONFIG_MALLOC_NO_FREQUENCY
#endif
#endif
#ifndef CONFIG_MALLOC_FREQUENCY
#if !defined(CONFIG_MALLOC_NO_FREQUENCY) && \
defined(CONFIG_DEBUG_HEAP)
# define CONFIG_MALLOC_FREQUENCY 1024
#endif
#elif (CONFIG_MALLOC_FREQUENCY+0) == 0
# undef CONFIG_MALLOC_FREQUENCY
#endif
/* Enable the debug-API when any functionality that
* requires additional tracking to-be done was activated. */
#if defined(CONFIG_TRACE_LEAKS) || \
defined(CONFIG_MALLOC_HEADSIZE) || \
defined(CONFIG_MALLOC_FOOTSIZE)
#define MALLOC_DEBUG_API
#endif
/* Enable/Disable some of the ~fancy~ strdup-style function in kernel-space:
* - strdup
* - strndup
* - strdupf
* - vstrdupf
* - memcdup // Not really part of the group, but never used since `memdup' also exists. */
#undef CONFIG_HAVE_STRDUP_IN_KERNEL
/* #define CONFIG_HAVE_STRDUP_IN_KERNEL 1 */
/* Memory zone used for physical allocations. */
#define MEMORY_PHYS_ZONE MZONE_ANY
/* Address ranges used by virtual kernel/shared memory allocations. */
#ifdef CONFIG_HIGH_KERNEL
#define KERNEL_VIRT_BEGIN __UINTPTR_C(0x00000000) /* 0x00000000...0xbfffffff */
#define KERNEL_VIRT_END (VM_USER_MAX+1) /* 0x00000000...0xbfffffff */
#define SHARED_VIRT_BEGIN VM_HOST_BASE /* 0xc0000000...0xffffffff */
#if (__SIZEOF_POINTER__ == 4 && VM_HOST_MAX == __UINTPTR_C(0xffffffff)) || \
(__SIZEOF_POINTER__ == 8 && VM_HOST_MAX == __UINTPTR_C(0xffffffffffffffff))
#define SHARED_VIRT_END __UINTPTR_C(0x00000000) /* 0xc0000000...0xffffffff */
#else
#define SHARED_VIRT_END (VM_HOST_MAX+1) /* 0xc0000000...0xffffffff */
#endif
#elif defined(CONFIG_LOW_KERNEL)
#define KERNEL_VIRT_BEGIN VM_USER_BASE /* 0x40000000...0xffffffff */
#if (__SIZEOF_POINTER__ == 4 && VM_USER_MAX == __UINTPTR_C(0xffffffff)) || \
(__SIZEOF_POINTER__ == 8 && VM_USER_MAX == __UINTPTR_C(0xffffffffffffffff))
#define KERNEL_VIRT_END __UINTPTR_C(0x00000000) /* 0x40000000...0xffffffff */
#else
#define KERNEL_VIRT_END (VM_USER_MAX+1) /* 0x40000000...0xffffffff */
#endif
#if VM_HOST_BASE == 0
#define SHARED_VIRT_BEGIN __UINTPTR_C(0x00000000) /* 0x00000000...0x3fffffff */
#define SHARED_VIRT_END VM_HOST_SIZE /* 0x00000000...0x3fffffff */
#else
#define SHARED_VIRT_BEGIN VM_HOST_BASE /* 0x00000000...0x3fffffff */
#define SHARED_VIRT_END (VM_HOST_MAX+1) /* 0x00000000...0x3fffffff */
#endif
#endif
#define BAD_ALLOC(n_bytes,flags) (void)0
#define M_ISNONNULL(p) likely((p) != NULL)
#define __GFP_NULL GFP_NORMAL /* GFP flags for pointers not matching `M_ISNONNULL' */
#if 1 /* Use shared memory for malloc()! */
#define __GFP_MALLOC GFP_SHARED /* GFP flags for malloc()-allocated memory. */
#else
#define __GFP_MALLOC GFP_MEMORY /* GFP flags for malloc()-allocated memory. */
#endif
/* Define to non-zero to add syslog entries for managed memory allocation. */
#ifndef LOG_MANAGED_ALLOCATIONS
#define LOG_MANAGED_ALLOCATIONS 0
#endif
#ifdef MALLOC_DEBUG_API
struct PACKED dinfo {
char const *i_file;
char const *i_func;
struct instance *i_inst;
int i_line;
};
struct PACKED stored_dinfo {
char const *i_file;
char const *i_func;
struct instance *i_inst;
};
#endif /* MALLOC_DEBUG_API */
#if defined(CONFIG_MALLOC_FOOTSIZE) || \
defined(CONFIG_MALLOC_TRACEBACK)
#define MPTR_HAVE_TAIL
struct PACKED mptr_tail {
#ifdef CONFIG_MALLOC_FOOTSIZE
byte_t t_foot[CONFIG_MALLOC_FOOTSIZE];
#endif
#ifdef CONFIG_MALLOC_TRACEBACK
#define MPTR_TAIL_TB_EOF ((void *)-1)
void *t_tb[1]; /*< [0..1|null(MPTR_TAIL_TB_EOF)][EOF(MPTR_TAIL_TB_EOF)]
* [0..MPTR_TRACEBACK_SIZE(^self)][const] Malloc traceback instruction pointers.
* NOTE: May prematurely terminate upon hitting `MPTR_TAIL_TB_EOF'. */
#endif
};
#endif
struct PACKED mptr {
/* Trace header */
#ifdef CONFIG_TRACE_LEAKS
#define MPTR_FILE(x) ((x)->m_info.i_file)
#define MPTR_FUNC(x) ((x)->m_info.i_func)
#define MPTR_INST(x) ((x)->m_info.i_inst)
#define MPTR_LINE(x) ((x)->m_line)
LIST_NODE(struct mptr)
m_chain; /*< [lock(MALLTRACE_LOCK(self))][null(KINSTANCE_TRACE_NULL)]
* Chain of all other MALL headers. */
struct stored_dinfo m_info; /*< [const] Basic debug information for tracking. */
s32 m_line; /*< [const] Source line where this pointer was allocated at. */
u16 m_chksum; /*< [const] Checksum of m_flag...:m_data + mt_tb. */
u8 m_refcnt; /*< [lock(MPTR_TRACE_LOCK(self))] Reference counter (required for handling free() while enumerating). */
#define MPTRFLAG_NONE 0x00
#define MPTRFLAG_UNTRACKED 0x01 /*< The pointer was untracked. */
#define MPTRFLAG_NOFREE 0x02 /*< The pointer must not be freed or reallocated. */
#define MPTRFLAG_GLOBAL 0x04 /*< The pointer is intended for global usage. */
#define MPTRFLAG_MASK 0x07 /*< Mask of recognized flags. */
u8 m_flag; /*< [lock(MALLTRACE_LOCK(self))] Mall flags (Set of `MPTRFLAG_*'). */
#define __1_MPTR_SIZEOF (5*__SIZEOF_POINTER__+8)
#else /* CONFIG_TRACE_LEAKS */
#define __1_MPTR_SIZEOF 0
#endif /* !CONFIG_TRACE_LEAKS */
/* Tail pointer header */
#ifdef MPTR_HAVE_TAIL
struct mptr_tail *m_tail; /*< [const][1..1][>= self] Pointer to the end of user-data. */
#define __2_MPTR_SIZEOF (__1_MPTR_SIZEOF+__SIZEOF_POINTER__)
#else
#define __2_MPTR_SIZEOF __1_MPTR_SIZEOF
#endif
/* Underflow safe-area header. */
#ifdef CONFIG_MALLOC_HEADSIZE
#define __3_MPTR_SIZEOF (CONFIG_MALLOC_HEADSIZE+__2_MPTR_SIZEOF)
#else
#define __3_MPTR_SIZEOF __2_MPTR_SIZEOF
#endif
#if (HEAP_ALIGNMENT & GFP_MASK_MPTR) != 0
/* Use a unique field for the pointer type. */
#define MPTR_HAVE_TYPE
#if GFP_MASK_MPTR > 0xff
# define __4_MPTR_SIZEOF (2+__3_MPTR_SIZEOF)
u16 m_type;
#else
# define __4_MPTR_SIZEOF (1+__3_MPTR_SIZEOF)
u8 m_type;
#endif
#else
#define __4_MPTR_SIZEOF __3_MPTR_SIZEOF
#endif
#define MPTR_UNALIGNED_SIZE (__4_MPTR_SIZEOF+__SIZEOF_SIZE_T__)
#if (MPTR_UNALIGNED_SIZE % HEAP_ALIGNMENT) != 0
#define MPTR_HAVE_PAD
byte_t m_pad[HEAP_ALIGNMENT-(MPTR_UNALIGNED_SIZE % HEAP_ALIGNMENT)];
#endif
#ifdef MPTR_HAVE_TYPE
size_t m_size; /*< [const][mask(~GFP_MASK_MPTR)][>= HEAP_MIN_MALLOC] Total memory size (including this header). */
#else
union{ size_t m_size; /*< [const][mask(~GFP_MASK_MPTR)][>= HEAP_MIN_MALLOC] Total memory size (including this header). */
size_t m_type; /*< [const][mask(GFP_MASK_MPTR)][!= 3] Flags used to create the pointer. */
size_t m_data; /*< [const] Malloc-pointer information. */
};
#endif
#ifdef CONFIG_MALLOC_HEADSIZE
byte_t m_head[CONFIG_MALLOC_HEADSIZE];
#endif
};
#ifdef CONFIG_TRACE_LEAKS
/* Lock that must be held when reading/writing the `m_info.i_inst' field of any mptr. */
PRIVATE DEFINE_ATOMIC_RWLOCK(mptr_inst_lock);
#define MPTR_TRACE_LOCK(self) ((self)->m_info.i_inst->i_driver.k_tlock)
#endif
#ifdef MPTR_HAVE_TAIL
#ifdef CONFIG_MALLOC_TRACEBACK
# define MPTR_TRACEBACK_ADDR(self) ((self)->m_tail->t_tb)
# define MPTR_TRACEBACK_SIZE(self) ((MPTR_TAILSIZE(self)-offsetof(struct mptr_tail,t_tb))/sizeof(void *))
#endif
# define MPTR_TAILADDR(self) ((self)->m_tail)
# define MPTR_TAILSIZE(self) (((uintptr_t)(self)+MPTR_SIZE(self))-(uintptr_t)MPTR_TAILADDR(self))
# define MPTR_USERADDR(self) ((struct mptr *)(self)+1)
# define MPTR_USERSIZE(self) ((uintptr_t)MPTR_TAILADDR(self)-(uintptr_t)MPTR_USERADDR(self))
#else
# define MPTR_USERADDR(self) ((struct mptr *)(self)+1)
# define MPTR_USERSIZE(self) (MPTR_SIZE(self)-sizeof(struct mptr))
#endif
#if defined(CONFIG_MALLOC_FOOTSIZE) && CONFIG_MALLOC_TRACEBACK
# define MPTR_MINTAILSIZE (CONFIG_MALLOC_FOOTSIZE+CONFIG_MALLOC_TRACEBACK_MINSIZE*sizeof(void *))
# define MPTR_SIZEOF(s) (sizeof(struct mptr)+(s)+CONFIG_MALLOC_FOOTSIZE+CONFIG_MALLOC_TRACEBACK_MINSIZE*sizeof(void *))
#elif defined(CONFIG_MALLOC_FOOTSIZE)
# define MPTR_MINTAILSIZE (CONFIG_MALLOC_FOOTSIZE)
# define MPTR_SIZEOF(s) (sizeof(struct mptr)+(s)+CONFIG_MALLOC_FOOTSIZE)
#elif CONFIG_MALLOC_TRACEBACK
# define MPTR_MINTAILSIZE (CONFIG_MALLOC_TRACEBACK_MINSIZE*sizeof(void *))
# define MPTR_SIZEOF(s) (sizeof(struct mptr)+(s)+CONFIG_MALLOC_TRACEBACK_MINSIZE*sizeof(void *))
#else
# define MPTR_SIZEOF(s) (sizeof(struct mptr)+(s))
#endif
#define MPTR_OF(p) ((struct mptr *)(p)-1)
#ifdef MPTR_HAVE_TYPE
# define MPTR_FLAGS(p) (p)->m_type
# define MPTR_TYPE(p) ((p)->m_type&GFP_MASK_TYPE)
# define MPTR_SIZE(p) (p)->m_size
# define MPTR_SETUP(self,type,size) (void)((self)->m_type = (type),(self)->m_size = (size))
#else
# define MPTR_FLAGS(p) ((p)->m_type&GFP_MASK_MPTR)
# define MPTR_TYPE(p) ((p)->m_type&GFP_MASK_TYPE)
# define MPTR_SIZE(p) ((p)->m_size&~GFP_MASK_MPTR)
# define MPTR_SETUP(self,type,size) (void)((self)->m_data = (type)|(size))
#endif
#define MPTR_HEAP(p) (&mheaps[MPTR_TYPE(p)])
#define MPTR_ISOK(p) (MPTR_TYPE(p) < __GFP_HEAPCOUNT && MPTR_SIZE(p) >= HEAP_MIN_MALLOC)
#define MPTR_VALIDATE(p) assertf(MPTR_ISOK(p),"Invalid m-pointer %p",p)
#ifdef MALLOC_DEBUG_API
struct dsetup {
struct dinfo s_info; /*< Basic debug information for tracking. */
void *s_tbebp; /*< EBP used in tracebacks. */
};
PRIVATE struct mptr *KCALL mptr_safeload(struct dsetup *__restrict setup, void *__restrict p);
#define MPTR_GET(p) mptr_safeload(setup,p)
/* Setup debug informations within a given mptr. */
PRIVATE void KCALL mptr_setup(struct mptr *__restrict self,
struct dsetup *__restrict setup,
size_t user_size);
#ifdef MPTR_HAVE_TAIL
PRIVATE void KCALL mptr_mvtail(struct mptr *__restrict self,
size_t old_size, size_t old_user_size,
size_t new_size, size_t new_user_size,
gfp_t flags);
#elif defined(CONFIG_TRACE_LEAKS)
#define mptr_mvtail(self,...) (void)(self->m_chksum = mptr_chksum(self))
#else
#define mptr_mvtail(self,...) (void)0
#endif
#ifdef CONFIG_TRACE_LEAKS
PRIVATE u16 KCALL mptr_chksum(struct mptr *__restrict self);
PRIVATE void KCALL mptr_unlink(struct dsetup *setup, struct mptr *__restrict self);
PRIVATE void KCALL mptr_relink(struct dsetup *setup, struct mptr *__restrict self);
#else
#define mptr_unlink(...) (void)0
#define mptr_relink(...) (void)0
#endif
#else
#define MPTR_GET(p) (MPTR_VALIDATE(MPTR_OF(p)),MPTR_OF(p))
#endif
#ifdef CONFIG_MALLOC_HEADSIZE
PRIVATE byte_t mall_header_seed[4] = {0x65,0xB6,0xBD,0x5A};
#define MALL_HEADERBYTE(i) (mall_header_seed[(i) % 4]^(byte_t)((0xff >> (i) % 8)*(i))) /* Returns the i-th control byte for mall-headers. */
#endif
#ifdef CONFIG_MALLOC_FOOTSIZE
PRIVATE byte_t mall_footer_seed[4] = {0xCF,0x6A,0xB7,0x97};
#define MALL_FOOTERBYTE(i) (mall_footer_seed[(i) % 4]^(byte_t)((0xff >> (i) % 7)*((i)+1))) /* Returns the i-th control byte for mall-footers. */
#endif
STATIC_ASSERT(IS_ALIGNED(MPTR_SIZEOF(0),HEAP_ALIGNMENT));
STATIC_ASSERT(IS_ALIGNED(sizeof(struct mptr),HEAP_ALIGNMENT));
STATIC_ASSERT(GFP_GTPAGEATTR(GFP_CALLOC) == PAGEATTR_ZERO);
/* unsigned int FFS(size_t x); */
/* unsigned int CLZ(size_t x); */
#if __SIZEOF_SIZE_T__ == __SIZEOF_INT__
# define FFS(x) ((unsigned int)__builtin_ffs((int)(x)))
# define CLZ(x) ((unsigned int)__builtin_clz((int)(x)))
# define CTZ(x) ((unsigned int)__builtin_ctz((int)(x)))
#elif __SIZEOF_SIZE_T__ == __SIZEOF_LONG__
# define FFS(x) ((unsigned int)__builtin_ffsl((long)(x)))
# define CLZ(x) ((unsigned int)__builtin_clzl((long)(x)))
# define CTZ(x) ((unsigned int)__builtin_ctzl((long)(x)))
#else
# define FFS(x) ((unsigned int)__builtin_ffsll((long long)(x)))
# define CLZ(x) ((unsigned int)__builtin_clzll((long long)(x)))
# define CTZ(x) ((unsigned int)__builtin_ctzll((long long)(x)))
#endif
/* Heap configuration:
* Index offset for the first bucket that should be search for a given size. */
#if HEAP_ALIGNMENT == 8
# define HEAP_BUCKET_OFFSET 4 /* FFS(HEAP_ALIGNMENT) */
#elif HEAP_ALIGNMENT == 16
# define HEAP_BUCKET_OFFSET 5 /* FFS(HEAP_ALIGNMENT) */
#else
# define HEAP_BUCKET_OFFSET FFS(HEAP_ALIGNMENT)
#endif
#define HEAP_BUCKET_OF(size) (((__SIZEOF_SIZE_T__*8)-CLZ(size))-HEAP_BUCKET_OFFSET)
#define HEAP_BUCKET_MINSIZE(i) (1 << ((i)+HEAP_BUCKET_OFFSET-1))
#define HEAP_BUCKET_COUNT ((__SIZEOF_SIZE_T__*8)-HEAP_BUCKET_OFFSET-1)
/* The min amount of bytes that can be allocated at once.
* NOTE: Technically, this is the min amount that can be freed at once, but eh... */
#define HEAP_MIN_MALLOC CEIL_ALIGN(sizeof(struct mfree),HEAP_ALIGNMENT)
#define MFREE_ATTRMASK 0x1
#define MFREE_SIZEMASK ~(MFREE_ATTRMASK)
/* Descriptor for a free portion of memory. */
struct mfree {
#ifdef __INTELLISENSE__
struct { struct mfree *le_next,**le_pself; }
mf_lsize; /*< [lock(:mh_lock)][sort(ASCENDING(mf_size))] List of free entries ordered by size. */
#else
LIST_NODE(struct mfree) mf_lsize; /*< [lock(:mh_lock)][sort(ASCENDING(mf_size))] List of free entries ordered by size. */
#endif
ATREE_XNODE(struct mfree) mf_laddr; /*< [lock(:mh_lock)][sort(ASCENDING(self))] List of free entries ordered by address. */
#if (HEAP_ALIGNMENT & MFREE_ATTRMASK) != 0
#define MFREE_HAVE_ATTR
#undef MFREE_ATTRMASK
#undef MFREE_SIZEMASK
MALIGNED size_t mf_size; /*< [lock(:mh_lock)][mask(MFREE_SIZEMASK)][>= HEAP_MIN_MALLOC]
* Size of this free range in bytes (Including this header). */
pgattr_t mf_attr; /*< [lock(:mh_lock)]
* Page-attributes for data within this free region.
* NOTE: When `CONFIG_MALLOC_DEBUG_INIT' is defined,
* and the `PAGEATTR_ZERO' flag isn't set, the
* memory described within this free range is
* fully initialized to `CONFIG_MALLOC_DEBUG_INIT'
* (Excluding this header of course)
* >> This behavior mirrors that of `PAGEATTR_ZERO'-initialized
* memory, in that free data is known to be in a specific state.
*/
#else
union{
size_t mf_info;
MALIGNED size_t mf_size; /*< [lock(:mh_lock)][mask(MFREE_SIZEMASK)][>= HEAP_MIN_MALLOC]
* Size of this free range in bytes (Including this header). */
pgattr_t mf_attr; /*< [lock(:mh_lock)][mask(MFREE_ATTRMASK)]
* Page-attributes for data within this free region.
* NOTE: When `CONFIG_MALLOC_DEBUG_INIT' is defined,
* and the `PAGEATTR_ZERO' flag isn't set, the
* memory described within this free range is
* fully initialized to `CONFIG_MALLOC_DEBUG_INIT'
* (Excluding this header of course)
* >> This behavior mirrors that of `PAGEATTR_ZERO'-initialized
* memory, in that free data is known to be in a specific state.
*/
};
#endif
};
#define MFREE_MIN(self) ((uintptr_t)(self))
#define MFREE_BEGIN(self) ((uintptr_t)(self))
#ifdef MFREE_HAVE_ATTR
#define MFREE_MAX(self) ((uintptr_t)(self)+(self)->mf_size-1)
#define MFREE_END(self) ((uintptr_t)(self)+(self)->mf_size)
#define MFREE_SIZE(self) (self)->mf_size
#define MFREE_ATTR(self) (self)->mf_attr
#define MFREE_SETUP(self,size,pg_attr) (assert(IS_ALIGNED(size,HEAP_ALIGNMENT)),\
assert((size) >= HEAP_MIN_MALLOC),\
(self)->mf_attr = (pg_attr),\
(self)->mf_size = (size))
#else
#define MFREE_MAX(self) ((uintptr_t)(self)+((self)->mf_size&MFREE_SIZEMASK)-1)
#define MFREE_END(self) ((uintptr_t)(self)+((self)->mf_size&MFREE_SIZEMASK))
#define MFREE_SIZE(self) ((self)->mf_size&MFREE_SIZEMASK)
#define MFREE_ATTR(self) ((self)->mf_attr&MFREE_ATTRMASK)
#define MFREE_SETUP(self,size,pg_attr) (assert(IS_ALIGNED(size,HEAP_ALIGNMENT)),\
assert((size) >= HEAP_MIN_MALLOC),\
assert(((pg_attr)&MFREE_ATTRMASK) == (pg_attr)),\
(self)->mf_info = (size)|(pg_attr))
#endif
/* TO-DO: Disable me. NOTE: When disabled, replace start with `TO-DO' */
#define MHEAP_USING_INTERNAL_VALIDATION 0
#if MHEAP_USING_INTERNAL_VALIDATION
#define MHEAP_RECURSIVE_LOCK 1
#define MHEAP_INTERNAL_VALIDATE(flags) (((flags)&GFP_NOFREQ) ? (void)0 : _mall_validate(NULL))
#else
#define MHEAP_RECURSIVE_LOCK 0
#define MHEAP_INTERNAL_VALIDATE(flags) (void)0
#endif
/* Memory heaps must always use recursive locks to prevent deadlocks such as the following:
../src/kernel/sched/task.c(650) : task_yield : [0] : C0169AD3
../include/hybrid/sync/atomic-rwlock.h(138) : atomic_rwlock_write : [0] : C01387DB : EFFFB898
../src/kernel/memory/malloc.c(1612) : mheap_free : [1] : C013DDF5 : EFFFB8A8
../src/kernel/memory/malloc.c(2256) : debug_free : [2] : C014032B : EFFFB8E8
../src/kernel/memory/malloc.c(3087) : _kfree_d : [3] : C01435EC : EFFFB938
../src/kernel/memory/memory.c(608) : mscatter_split_lo : [4] : C0146245 : EFFFB988
../src/kernel/mman/part.c(73) : mregion_part_split_lo : [5] : C0158ABB : EFFFB9C8
../src/kernel/mman/part.c(162) : mregion_part_action : [6] : C0159077 : EFFFB9F8
../src/kernel/mman/part.c(317) : mregion_part_decref : [7] : C0159692 : EFFFBA48
../src/kernel/mman/part.c(389) : mregion_decref : [8] : C01599D2 : EFFFBA78
../src/kernel/mman/mman.c(1473) : mman_munmap_impl : [9] : C0150297 : EFFFBAA8
../src/kernel/mman/mman.c(1532) : mman_munmap_unlocked : [a] : C01505AE : EFFFBAD8
../src/kernel/memory/malloc.c(786) : kernel_munmap : [b] : C013AC07 : EFFFBB18
../src/kernel/memory/malloc.c(970) : core_page_free : [c] : C013B7BC : EFFFBB48
../src/kernel/memory/malloc.c(1448) : mheap_unmapfree : [d] : C013D41F : EFFFBB88
../src/kernel/memory/malloc.c(1383) : mheap_release : [e] : C013D04A : EFFFBBD8
../src/kernel/memory/malloc.c(1613) : mheap_free : [f] : C013DE0B : EFFFBC38
../src/kernel/memory/malloc.c(2256) : debug_free : [10] : C014032B : EFFFBC78
../src/kernel/memory/malloc.c(3087) : _kfree_d : [11] : C01435EC : EFFFBCC8
../src/kernel/mman/mman.c(370) : mman_destroy : [12] : C014CA94 : EFFFBD18
../src/kernel/sched/task.c(633) : task_destroy : [13] : C0169819 : EFFFBD58
../src/kernel/sched/task.c(1982) : __task_destroy2 : [14] : C016D98F : EFFFBD88
../src/kernel/sched/task.c(2073) : task_terminate_self_unlock_cpu : [15] : C016DDBD : EFFFBDA8
../src/kernel/sched/task-util.c(594) : sig_vtimedrecv_endwrite : [16] : C01661DE : EFFFBE40
../src/kernel/sched/task-util.c(575) : sig_timedrecv_endwrite : [17] : C0166147 : EFFFBE70
../src/kernel/fs/iobuffer.c(222) : iobuffer_read : [18] : C0127D87 : EFFFBE90
../src/kernel/fs/pty.c(409) : master_read : [19] : C012CAD9 : EFFFBF20
../src/kernel/fs/file.c(148) : file_read : [1a] : C011DD7C : EFFFBF50
../src/kernel/fs/fd.c(815) : SYSC_read : [1b] : C0119577 : EFFFBF80
../syscall.c() : sys_ccall : [1c] : C01010D9 : EFFFBFC0
../??(0) : ?? : [1d] : 0000001B : EFFFBFDC
>> Basically: `free()' might call `munmap()', which could call another `free()'
of the same magnitude when the kernel memory manager inherited
a region, or a region part allocated as `MMAN_UNIGFP', or for
another manager, meaning that free()-ing that branch as the
result of unmapping unused memory will in turn call free() again.
*/
#undef MHEAP_RECURSIVE_LOCK
#define MHEAP_RECURSIVE_LOCK 1
struct mheap {
#if MHEAP_RECURSIVE_LOCK
#define __MHEAP_LOCK_INIT ATOMIC_OWNER_RWLOCK_INIT
atomic_owner_rwlock_t mh_lock; /*< Lock for this heap. */
#else
#define __MHEAP_LOCK_INIT ATOMIC_RWLOCK_INIT
atomic_rwlock_t mh_lock; /*< Lock for this heap. */
#endif
ATREE_HEAD(struct mfree) mh_addr; /*< [lock(mh_lock)][0..1|null(PAGE_ERROR)] Heap sorted by address. */
LIST_HEAD(struct mfree) mh_size[HEAP_BUCKET_COUNT];
/*< [lock(mh_lock)][0..1|null(PAGE_ERROR)][*] Heap sorted by free range size. */
size_t mh_overalloc; /*< [lock(mh_lock)] Amount (in bytes) by which to over-allocate memory in heaps.
* NOTE: Set to ZERO(0) to disable overallocation. */
size_t mh_freethresh;/*< [lock(mh_lock)] Threshold that must be reached before any continuous block
* of free data is split to free memory. (Should always be `>= PAGESIZE') */
};
#if MHEAP_RECURSIVE_LOCK
#define mheap_reading(x) atomic_owner_rwlock_reading(&(x)->mh_lock)
#define mheap_writing(x) atomic_owner_rwlock_writing(&(x)->mh_lock)
#define mheap_tryread(x) atomic_owner_rwlock_tryread(&(x)->mh_lock)
#define mheap_trywrite(x) atomic_owner_rwlock_trywrite(&(x)->mh_lock)
#define mheap_tryupgrade(x) atomic_owner_rwlock_tryupgrade(&(x)->mh_lock)
#define mheap_read(x) atomic_owner_rwlock_read(&(x)->mh_lock)
#define mheap_write(x) atomic_owner_rwlock_write(&(x)->mh_lock)
#define mheap_upgrade(x) atomic_owner_rwlock_upgrade(&(x)->mh_lock)
#define mheap_downgrade(x) atomic_owner_rwlock_downgrade(&(x)->mh_lock)
#define mheap_endread(x) atomic_owner_rwlock_endread(&(x)->mh_lock)
#define mheap_endwrite(x) atomic_owner_rwlock_endwrite(&(x)->mh_lock)
#else
#define mheap_reading(x) atomic_rwlock_reading(&(x)->mh_lock)
#define mheap_writing(x) atomic_rwlock_writing(&(x)->mh_lock)
#define mheap_tryread(x) atomic_rwlock_tryread(&(x)->mh_lock)
#define mheap_trywrite(x) atomic_rwlock_trywrite(&(x)->mh_lock)
#define mheap_tryupgrade(x) atomic_rwlock_tryupgrade(&(x)->mh_lock)
#define mheap_read(x) atomic_rwlock_read(&(x)->mh_lock)
#define mheap_write(x) atomic_rwlock_write(&(x)->mh_lock)
#define mheap_upgrade(x) atomic_rwlock_upgrade(&(x)->mh_lock)
#define mheap_downgrade(x) atomic_rwlock_downgrade(&(x)->mh_lock)
#define mheap_endread(x) atomic_rwlock_endread(&(x)->mh_lock)
#define mheap_endwrite(x) atomic_rwlock_endwrite(&(x)->mh_lock)
#endif
#ifdef MALLOC_DEBUG_API
PRIVATE SAFE MALIGNED bool KCALL mheap_isfree_l(struct mheap *__restrict self, void *p);
#endif /* MALLOC_DEBUG_API */
PRIVATE SAFE MALIGNED void *KCALL mheap_acquire(struct mheap *__restrict self, MALIGNED size_t n_bytes, MALIGNED size_t *__restrict alloc_bytes, gfp_t flags, bool unlock_heap);
PRIVATE SAFE MALIGNED void *KCALL mheap_acquire_al(struct mheap *__restrict self, MALIGNED size_t alignment, size_t offset, MALIGNED size_t n_bytes, MALIGNED size_t *__restrict alloc_bytes, gfp_t flags, bool unlock_heap);
PRIVATE SAFE MALIGNED void *KCALL mheap_acquire_at(struct mheap *__restrict self, MALIGNED void *p, MALIGNED size_t n_bytes, MALIGNED size_t *__restrict alloc_bytes, gfp_t flags);
PRIVATE SAFE bool KCALL mheap_release(struct mheap *__restrict self, MALIGNED void *p, MALIGNED size_t n_bytes, gfp_t flags, bool unlock_heap);
PRIVATE SAFE void KCALL mheap_release_nomerge(struct mheap *__restrict self, MALIGNED void *p, MALIGNED size_t n_bytes, gfp_t flags);
PRIVATE SAFE void KCALL mheap_unmapfree(struct mheap *__restrict self, struct mfree **__restrict pslot, ATREE_SEMI_T(uintptr_t) addr_semi, ATREE_LEVEL_T addr_level, gfp_t flags, bool unlock_heap);
#ifdef CONFIG_DEBUG_HEAP
PRIVATE SAFE void KCALL mheap_validate(struct dsetup *setup, struct mheap *__restrict self);
#endif
#if defined(CONFIG_DEBUG_HEAP) || defined(MALLOC_DEBUG_API)
PRIVATE SAFE ATTR_NORETURN void KCALL malloc_panic(struct dsetup *setup, struct mptr *info_header, char const *__restrict format, ...);
#endif
PRIVATE SAFE struct mptr *KCALL mheap_malloc(struct mheap *__restrict self, size_t size, gfp_t flags);
PRIVATE SAFE struct mptr *KCALL mheap_memalign(struct mheap *__restrict self, size_t alignment, size_t size, gfp_t flags);
PRIVATE SAFE void KCALL mheap_free(struct mheap *__restrict self, struct mptr *ptr, gfp_t flags);
#ifdef CONFIG_TRACE_LEAKS
PRIVATE SAFE struct mptr *KCALL mheap_realloc(struct dsetup *setup, struct mheap *__restrict self, struct mptr *ptr, size_t new_size, gfp_t flags);
PRIVATE SAFE struct mptr *KCALL mheap_realign(struct dsetup *setup, struct mheap *__restrict self, struct mptr *ptr, size_t alignment, size_t new_size, gfp_t flags);
#else
PRIVATE SAFE struct mptr *KCALL mheap_realloc(struct mheap *__restrict self, struct mptr *ptr, size_t new_size, gfp_t flags);
PRIVATE SAFE struct mptr *KCALL mheap_realign(struct mheap *__restrict self, struct mptr *ptr, size_t alignment, size_t new_size, gfp_t flags);
#endif
#if __SIZEOF_POINTER__ == 8
# define MEMSETX memsetq
# define MEMCPYX memcpyq
# define MEMPATX mempatq
#elif __SIZEOF_POINTER__ == 4
# define MEMSETX memsetl
# define MEMCPYX memcpyl
# define MEMPATX mempatl
#elif __SIZEOF_POINTER__ == 2
# define MEMSETX memsetw
# define MEMCPYX memcpyw
# define MEMPATX mempatw
#elif __SIZEOF_POINTER__ == 1
# define MEMSETX memsetb
# define MEMCPYX memcpyb
# define MEMPATX mempatb
#else
# error "Unsupported sizeof(void *)"
#endif
#define MHEAP_INIT(name) \
{ \
.mh_lock = __MHEAP_LOCK_INIT, \
.mh_addr = PAGE_ERROR, \
.mh_size = { \
[0 ... HEAP_BUCKET_COUNT-1] = PAGE_ERROR, \
}, \
.mh_overalloc = HEAP_DEFAULT_OVERALLOC(name), \
.mh_freethresh = HEAP_DEFAULT_FREETHRESH(name), \
}
/* The different memory heaps used by the kernel. */
PRIVATE struct mheap mheaps[__GFP_HEAPCOUNT] = {
[GFP_SHARED] = MHEAP_INIT(GFP_SHARED),
[GFP_SHARED|GFP_LOCKED] = MHEAP_INIT(GFP_SHARED|GFP_LOCKED),
[GFP_KERNEL] = MHEAP_INIT(GFP_KERNEL),
[GFP_KERNEL|GFP_LOCKED] = MHEAP_INIT(GFP_KERNEL|GFP_LOCKED),
[GFP_MEMORY] = MHEAP_INIT(GFP_MEMORY),
#ifdef MZONE_FAST
/* TODO: Make use the permanent mapping of 0-2Gib at -2Gib.
* >> Allocating physical memory from `MZONE_FAST'
* doesn't require memory to be re-mapped! */
#endif
};
#define MHEAP_GET(flags) \
(assertf(((flags)&GFP_MASK_TYPE) < __GFP_HEAPCOUNT,\
"Invalid heap id #%d",(int)((flags)&GFP_MASK_TYPE)),\
&mheaps[(flags)&GFP_MASK_TYPE])
#undef MHEAP_INIT
DECL_END
/* Define the ABI for the address tree used by mman. */
#define ATREE(x) mfree_tree_##x
#define ATREE_NULL PAGE_ERROR
#define ATREE_NODE_MIN MFREE_MIN
#define ATREE_NODE_MAX MFREE_MAX
#define Tkey uintptr_t
#define T struct mfree
#define path mf_laddr
#include <hybrid/list/atree-abi.h>
/* Mall public interface implementation. */
DECL_BEGIN
/* Page-level physical/virtual memory allocators. */
LOCAL SAFE PAGE_ALIGNED void *KCALL core_page_alloc(size_t n_bytes, gfp_t flags);
LOCAL SAFE PAGE_ALIGNED void *KCALL core_page_allocat(PAGE_ALIGNED void *start, size_t n_bytes, gfp_t flags);
LOCAL SAFE void KCALL core_page_free(PAGE_ALIGNED void *ptr, size_t n_bytes, gfp_t flags);
/* Kernel-level virtual mmap()/munmap() for anonymous memory. */
PRIVATE KPD VIRT void *KCALL
kernel_mmap_anon(VIRT PAGE_ALIGNED void *start,
PAGE_ALIGNED size_t n_bytes,
gfp_t flags) {
PHYS struct mregion *region;
errno_t error;
assert(PDIR_ISKPD());
assert(n_bytes != 0);
assert(IS_ALIGNED((uintptr_t)start,PAGESIZE));
assert(IS_ALIGNED(n_bytes,PAGESIZE));
assert((uintptr_t)start+n_bytes > (uintptr_t)start);
again:
region = mregion_new(GFP_NOFREQ|GFP_MEMORY);
if unlikely(!_mall_untrack(region)) return PAGE_ERROR;
region->mr_size = n_bytes;
if (flags&GFP_CALLOC)
region->mr_init = MREGION_INIT_ZERO;
#ifdef CONFIG_MALLOC_DEBUG_INIT
else {
/* Pre-initialize virtual kernel heap memory with a debug filler byte.
* >> Doing so here allows for pre-initialization of data. */
#if CONFIG_MALLOC_DEBUG_INIT == 0
region->mr_init = MREGION_INIT_ZERO;
#else
region->mr_init = MREGION_INIT_BYTE;
region->mr_setup.mri_byte = CONFIG_MALLOC_DEBUG_INIT;
#endif
}
#endif
#if GFP_LOCKED == 1
region->mr_part0.mt_locked = flags&GFP_LOCKED;
#else
region->mr_part0.mt_locked = !!(flags&GFP_LOCKED);
#endif
if (flags&GFP_INCORE) {
/* Preallocate core memory for the region. */
if (!page_malloc_scatter(®ion->mr_part0.mt_memory,n_bytes,
PAGESIZE,GFP_GTPAGEATTR(flags),
MZONE_ANY,GFP_MEMORY)) {
kfree(region);
goto swapmem;
}
assert(region->mr_part0.mt_memory.m_size <= region->mr_size);
#ifdef CONFIG_MALLOC_DEBUG_INIT
if (!(flags&GFP_CALLOC)) {
struct mscatter *iter = ®ion->mr_part0.mt_memory;
while (iter) {
MEMPATX(iter->m_start,
CONFIG_MALLOC_DEBUG_INIT,
iter->m_size);
iter = iter->m_next;
}
}
#endif
region->mr_part0.mt_state = MPART_STATE_INCORE;
}
mregion_setup(region);
error = mman_mmap_unlocked(&mman_kernel,(ppage_t)start,n_bytes,0,region,
PROT_READ|PROT_WRITE|PROT_NOUSER,NULL,NULL);
MREGION_DECREF(region);
if (E_ISERR(error)) {
swapmem:
/* Try to swap out memory. */
if (MMAN_SWAPOK(mman_swapmem(n_bytes,flags))) goto again;
BAD_ALLOC(n_bytes,flags);
return PAGE_ERROR;
}
MHEAP_INTERNAL_VALIDATE(flags);
return start;
}
LOCAL KPD VIRT void KCALL
kernel_munmap(VIRT PAGE_ALIGNED void *start,
PAGE_ALIGNED size_t n_bytes,
pgattr_t flags) {
assert(PDIR_ISKPD());
assert(n_bytes != 0);
assert(IS_ALIGNED((uintptr_t)start,PAGESIZE));
assert(IS_ALIGNED(n_bytes,PAGESIZE));
assert((uintptr_t)start+n_bytes > (uintptr_t)start);
mman_munmap_unlocked(&mman_kernel,(ppage_t)start,n_bytes,
#if PAGEATTR_ZERO == MMAN_MUNMAP_CLEAR
MMAN_MUNMAP_ALL|(flags&PAGEATTR_ZERO),
#else
MMAN_MUNMAP_ALL|(flags&PAGEATTR_ZERO ? MMAN_MUNMAP_CLEAR : 0),
#endif
NULL);
}
LOCAL SAFE PAGE_ALIGNED void *KCALL
core_page_alloc(size_t n_bytes, gfp_t flags) {
void *result;
if (flags&GFP_MEMORY) {
do result = page_malloc(n_bytes,GFP_GTPAGEATTR(flags),MEMORY_PHYS_ZONE);
while (result == PAGE_ERROR && MMAN_SWAPOK(mman_swapmem(n_bytes,flags)));
#ifdef CONFIG_MALLOC_DEBUG_INIT
if (result != PAGE_ERROR && !(flags&GFP_CALLOC))
MEMPATX(result,CONFIG_MALLOC_DEBUG_INIT,n_bytes);
#endif
} else {
PHYS struct mman *old_mman; bool has_write_lock = false;
#define HEAPEND_MASK (GFP_SHARED|GFP_KERNEL|GFP_LOCKED)
/* Make sure that default heap addresses are in valid ranges. */
PRIVATE VIRT uintptr_t heap_end[HEAPEND_MASK+1] = {
[GFP_SHARED] = HOST_HEAPEND_SHARED, /* 0xd4000000 / 0xffffd10000000000 */
[GFP_SHARED|GFP_LOCKED] = HOST_HEAPEND_SHARED_LOCKED, /* 0xd0000000 / 0xffffd00000000000 */
[GFP_KERNEL] = HOST_HEAPEND_KERNEL, /* 0x14000000 / 0x0000510000000000 */
[GFP_KERNEL|GFP_LOCKED] = HOST_HEAPEND_KERNEL_LOCKED, /* 0x10000000 / 0x0000500000000000 */
};
task_nointr();
if (!(flags&GFP_KERNEL)) TASK_PDIR_KERNEL_BEGIN(old_mman);
assert(PDIR_ISKPD());
/* Only need a read-lock to search for free space. */
if (!(flags&GFP_ATOMIC)) mman_read(&mman_kernel);
else if (mman_tryread(&mman_kernel) == -EAGAIN) {
result = PAGE_ERROR;
goto end;
}
check_again:
result = mman_findspace_unlocked(&mman_kernel,
(ppage_t)heap_end[flags&HEAPEND_MASK],n_bytes,PAGESIZE,
0,MMAN_FINDSPACE_ABOVE|MMAN_FINDSPACE_PRIVATE);
/* Make sure that we're not allocating out-of-bounds. */
if unlikely(flags&GFP_KERNEL) {
if (result == PAGE_ERROR) {
/* Try to re-scan the heap for a free gap. */
result = mman_findspace_unlocked(&mman_kernel,(ppage_t)(flags&GFP_LOCKED ? HOST_HEAPEND_KERNEL_LOCKED
: HOST_HEAPEND_KERNEL),
n_bytes,PAGESIZE,0,MMAN_FINDSPACE_ABOVE|MMAN_FINDSPACE_PRIVATE);
if unlikely(result == PAGE_ERROR) {
/* Try to scan an extended address range. */
#if HOST_HEAPEND_KERNEL_LOCKED < HOST_HEAPEND_KERNEL
if (!(flags&GFP_LOCKED))
result = mman_findspace_unlocked(&mman_kernel,(ppage_t)HOST_HEAPEND_KERNEL_LOCKED,n_bytes,
PAGESIZE,0,MMAN_FINDSPACE_ABOVE|MMAN_FINDSPACE_PRIVATE);
#elif HOST_HEAPEND_KERNEL < HOST_HEAPEND_KERNEL_LOCKED
if (flags&GFP_LOCKED)
result = mman_findspace_unlocked(&mman_kernel,(ppage_t)HOST_HEAPEND_KERNEL,n_bytes,
PAGESIZE,0,MMAN_FINDSPACE_ABOVE|MMAN_FINDSPACE_PRIVATE);
#endif
/* Try to scan the entire virtual address range. */
if unlikely(result == PAGE_ERROR)
result = mman_findspace_unlocked(&mman_kernel,(ppage_t)(KERNEL_VIRT_BEGIN),n_bytes,
PAGESIZE,0,MMAN_FINDSPACE_ABOVE|MMAN_FINDSPACE_PRIVATE);
}
if unlikely(result == PAGE_ERROR) goto end2;
}
} else {
/* Make sure not to allocate dynamic memory above what is reserved for error-codes.
* >> Since the reserve is _always_ less than a page, it's impossible
* to encounter this problem in other allocators such as `page_malloc()'.
* But since `kmalloc()'s purpose is to get away from page-aligned
* allocations, we may actually run into the problem of allocating
* memory above `__ERRNO_THRESHOLD', which in turn may be interpreted
* incorrectly once allocated pointers are transformed, or passed
* through various different interfaces.
* >> So to prevent any of those problems, simply don't allow virtual
* address mapping of the last virtual address page, thereby preventing
* any collisions that might otherwise arise. */
#if defined(CONFIG_NO_PDIR_SELFMAP) || (__ERRNO_THRESHOLD < THIS_PDIR_BASE)
#define PAGE_ISOK(x) ((x) != PAGE_ERROR && (uintptr_t)(x)+(n_bytes) < FLOOR_ALIGN(__ERRNO_THRESHOLD,PAGESIZE))
#else
#define PAGE_ISOK(x) ((x) != PAGE_ERROR)
#endif
if unlikely(!PAGE_ISOK(result)) {
/* Try to stay inside the designated region of memory as long as possible. */
result = mman_findspace_unlocked(&mman_kernel,(ppage_t)(flags&GFP_LOCKED ? HOST_HEAPEND_SHARED_LOCKED
: HOST_HEAPEND_SHARED),
n_bytes,PAGESIZE,0,MMAN_FINDSPACE_ABOVE|MMAN_FINDSPACE_PRIVATE);
if unlikely(!PAGE_ISOK(result)) {
#if HOST_HEAPEND_SHARED_LOCKED < HOST_HEAPEND_SHARED
if (!(flags&GFP_LOCKED))
result = mman_findspace_unlocked(&mman_kernel,(ppage_t)HOST_HEAPEND_SHARED_LOCKED,n_bytes,
PAGESIZE,0,MMAN_FINDSPACE_ABOVE|MMAN_FINDSPACE_PRIVATE);
#elif HOST_HEAPEND_SHARED < HOST_HEAPEND_SHARED_LOCKED
if (flags&GFP_LOCKED)
result = mman_findspace_unlocked(&mman_kernel,(ppage_t)HOST_HEAPEND_SHARED,n_bytes,
PAGESIZE,0,MMAN_FINDSPACE_ABOVE|MMAN_FINDSPACE_PRIVATE);
#endif
/* re-scan the entire shared address space as a last resort. */
if unlikely(!PAGE_ISOK(result))
result = mman_findspace_unlocked(&mman_kernel,(ppage_t)SHARED_VIRT_BEGIN,n_bytes,
PAGESIZE,0,MMAN_FINDSPACE_ABOVE|MMAN_FINDSPACE_PRIVATE);
}
#if defined(CONFIG_NO_PDIR_SELFMAP) || (__ERRNO_THRESHOLD < THIS_PDIR_BASE)
#define NEED_END2_ERR
if unlikely(result == PAGE_ERROR ||
(uintptr_t)result >= FLOOR_ALIGN(__ERRNO_THRESHOLD,PAGESIZE))
goto end2_err;
#else
if unlikely(result == PAGE_ERROR)
goto end2;
#endif
}
#undef PAGE_ISOK
}
assert(result != PAGE_ERROR);
/* Upgrade to a write-lock before mapping the space we've discovered. */
if (!has_write_lock) {
has_write_lock = true;
if (!(flags&GFP_ATOMIC)) {
if (mman_upgrade(&mman_kernel) == -ERELOAD)
goto check_again;
} else if (mman_tryupgrade(&mman_kernel) == -EAGAIN) {
result = PAGE_ERROR;
goto end_read;
}
}
result = kernel_mmap_anon(result,n_bytes,flags);
if (result == PAGE_ERROR) goto end2;
assert(((uintptr_t)result+n_bytes) <= FLOOR_ALIGN(__ERRNO_THRESHOLD,PAGESIZE));
heap_end[flags&HEAPEND_MASK] = (uintptr_t)result+n_bytes;
end2: if (has_write_lock) mman_endwrite(&mman_kernel);
else end_read: mman_endread(&mman_kernel);
end: if (!(flags&GFP_KERNEL)) TASK_PDIR_KERNEL_END(old_mman);
task_endnointr();
}
if (result == PAGE_ERROR) BAD_ALLOC(n_bytes,flags);
return result;
#ifdef NEED_END2_ERR
#undef NEED_END2_ERR
end2_err: result = PAGE_ERROR; goto end2;
#endif
}
LOCAL PAGE_ALIGNED void *KCALL
core_page_allocat(PAGE_ALIGNED void *start,
size_t n_bytes, gfp_t flags) {
void *result;
assert(IS_ALIGNED((uintptr_t)start,PAGESIZE));
if (flags&GFP_MEMORY) {
result = page_malloc_at((ppage_t)start,n_bytes,GFP_GTPAGEATTR(flags));
#ifdef CONFIG_MALLOC_DEBUG_INIT
if (result != PAGE_ERROR && !(flags&GFP_CALLOC))
MEMPATX(result,CONFIG_MALLOC_DEBUG_INIT,PAGESIZE);
#endif
} else {
bool has_write_lock = false;
PHYS struct mman *old_mman;
assert(n_bytes != 0);
assert(IS_ALIGNED((uintptr_t)start,PAGESIZE));
assert(IS_ALIGNED(n_bytes,PAGESIZE));
if unlikely((uintptr_t)start+n_bytes < (uintptr_t)start) return PAGE_ERROR;
if (flags&GFP_KERNEL) {
if unlikely(!addr_ishost_r(start,n_bytes)) return PAGE_ERROR;
} else {
if unlikely(!addr_isuser_r(start,n_bytes)) return PAGE_ERROR;
}
task_nointr();
if (!(flags&GFP_KERNEL)) TASK_PDIR_KERNEL_BEGIN(old_mman);
if (!(flags&GFP_ATOMIC)) mman_read(&mman_kernel);
else if (mman_tryread(&mman_kernel) == -EAGAIN) {
result = PAGE_ERROR;
goto end;
}
check_again:
if unlikely(mman_inuse_unlocked(&mman_kernel,(ppage_t)start,n_bytes)) { result = PAGE_ERROR; goto end2; }
/* Upgrade to a write-lock before mapping the space. */
if (!has_write_lock) {
has_write_lock = true;
if (!(flags&GFP_ATOMIC)) {
if (mman_upgrade(&mman_kernel) == -ERELOAD) goto check_again;
} else if (mman_tryupgrade(&mman_kernel) == -EAGAIN) {
result = PAGE_ERROR;
goto end_read;
}
}
result = kernel_mmap_anon(start,n_bytes,flags);
end2:
if (has_write_lock) mman_endwrite(&mman_kernel);
else end_read: mman_endread(&mman_kernel);
end: if (!(flags&GFP_KERNEL)) TASK_PDIR_KERNEL_END(old_mman);
task_endnointr();
}
return result;
}
LOCAL void KCALL
core_page_free(PAGE_ALIGNED void *ptr,
size_t n_bytes, gfp_t flags) {
assert(IS_ALIGNED((uintptr_t)ptr,PAGESIZE));
assert((uintptr_t)ptr+CEIL_ALIGN(n_bytes,PAGESIZE) >= (uintptr_t)ptr);
if (flags&GFP_MEMORY) {
page_ffree((ppage_t)ptr,n_bytes,GFP_GTPAGEATTR(flags));
} else {
PHYS struct mman *old_mman;
assert((flags&GFP_KERNEL)
? addr_isuser_r(ptr,CEIL_ALIGN(n_bytes,PAGESIZE))
: addr_ishost_r(ptr,CEIL_ALIGN(n_bytes,PAGESIZE)));
task_nointr();
if (!(flags&GFP_KERNEL)) TASK_PDIR_KERNEL_BEGIN(old_mman);
mman_write(&mman_kernel);
kernel_munmap(ptr,n_bytes,flags);
mman_endwrite(&mman_kernel);
if (!(flags&GFP_KERNEL)) TASK_PDIR_KERNEL_END(old_mman);
task_endnointr();
}
}
/* Kernel heap implementation. */
#ifdef MALLOC_DEBUG_API
PRIVATE MALIGNED bool KCALL
mheap_isfree_l(struct mheap *__restrict self, void *p) {
struct mfree *free_slot;
CHECK_HOST_DOBJ(self);
#if !MHEAP_RECURSIVE_LOCK
if (!mheap_tryread(self)) return false;
#else
mheap_read(self);
#endif
free_slot = mfree_tree_locate(self->mh_addr,(uintptr_t)p);
mheap_endread(self);
return free_slot != PAGE_ERROR;
}
#endif /* MALLOC_DEBUG_API */
PRIVATE MALIGNED void *KCALL
mheap_acquire(struct mheap *__restrict self, MALIGNED size_t n_bytes,
MALIGNED size_t *__restrict alloc_bytes, gfp_t flags,
bool unlock_heap) {
MALIGNED void *result = PAGE_ERROR;
MALIGNED struct mfree **iter,**end;
MALIGNED struct mfree *chain;
size_t page_bytes;
CHECK_HOST_DOBJ(self);
CHECK_HOST_DOBJ(alloc_bytes);
assert(IS_ALIGNED(n_bytes,HEAP_ALIGNMENT));
assert(mheap_writing(self));
if unlikely(n_bytes < HEAP_MIN_MALLOC)
n_bytes = HEAP_MIN_MALLOC;
iter = &self->mh_size[HEAP_BUCKET_OF(n_bytes)];
end = COMPILER_ENDOF(self->mh_size);
MHEAP_INTERNAL_VALIDATE(flags);
for (; iter != end; ++iter) {
chain = *iter,assert(chain);
while (chain != PAGE_ERROR && MFREE_SIZE(chain) < n_bytes)
chain = chain->mf_lsize.le_next,assert(chain);
if (chain != PAGE_ERROR) {
size_t unused_size;
pgattr_t chain_attr = MFREE_ATTR(chain);
result = (void *)chain;
#ifdef CONFIG_DEBUG_HEAP
{
struct mfree *del_entry;
del_entry = mfree_tree_remove(&self->mh_addr,MFREE_BEGIN(chain));
assertf(del_entry == chain,
"Invalid tracking for %p...%p (%p != %p)",
MFREE_MIN(chain),MFREE_MAX(chain),
MFREE_BEGIN(del_entry),MFREE_BEGIN(chain));
}
#else
mfree_tree_remove(&self->mh_addr,MFREE_BEGIN(chain));
#endif
LIST_REMOVE_EX(chain,mf_lsize,PAGE_ERROR);
unused_size = MFREE_SIZE(chain)-n_bytes;
if (unused_size < HEAP_MIN_MALLOC) {
/* Remainder is too small. - Allocate it as well. */
n_bytes += unused_size;
} else {
MALIGNED void *unused_begin = (void *)((uintptr_t)chain+n_bytes);
/* Make sure the the remainder is properly aligned. */
assert(IS_ALIGNED((uintptr_t)unused_begin,HEAP_ALIGNMENT));
assert(IS_ALIGNED(unused_size,HEAP_ALIGNMENT));
assert(unused_size < MFREE_SIZE(chain));
mheap_release_nomerge(self,unused_begin,unused_size,
(flags&~(GFP_CALLOC))|
GFP_STPAGEATTR(chain_attr));
}
/* Initialize the result memory. */
if (flags&GFP_CALLOC) {
if (chain_attr&PAGEATTR_ZERO)
memset(result,0,MIN(sizeof(struct mfree),n_bytes));
else memset(result,0,n_bytes);
}
#ifdef CONFIG_MALLOC_DEBUG_INIT
else if (chain_attr&PAGEATTR_ZERO) {
MEMPATX(result,CONFIG_MALLOC_DEBUG_INIT,n_bytes);
}
#endif
*alloc_bytes = n_bytes;
assert(IS_ALIGNED((uintptr_t)result,HEAP_ALIGNMENT));
goto done;
}
}
MHEAP_INTERNAL_VALIDATE(flags);
/* Allocate whole pages. */
page_bytes = CEIL_ALIGN(n_bytes,PAGESIZE);
page_bytes += self->mh_overalloc; /* Overallocate a bit. */
core_again:
result = core_page_alloc(page_bytes,flags);
if (result == PAGE_ERROR) {
if (page_bytes == CEIL_ALIGN(n_bytes,PAGESIZE)) goto done;
/* Try again without overallocation. */
page_bytes = CEIL_ALIGN(n_bytes,PAGESIZE);
goto core_again;
}
if (page_bytes != n_bytes) {
/* Release all unused memory. */
if (!mheap_release(self,(void *)((uintptr_t)result+n_bytes),
page_bytes-n_bytes,flags,unlock_heap))
n_bytes = page_bytes;
unlock_heap = false;
}
*alloc_bytes = n_bytes;
done:
MHEAP_INTERNAL_VALIDATE(flags);
#if LOG_MANAGED_ALLOCATIONS
if (result != PAGE_ERROR) {
syslog(LOG_MEM|LOG_ERROR,"[MEM] ALLOC(%p...%p) (%Iu/%Iu)\n",
result,(uintptr_t)result+*alloc_bytes-1,*alloc_bytes,n_bytes);
}
#endif
if (unlock_heap)
mheap_endwrite(self);
return result;
}
PRIVATE MALIGNED void *KCALL
mheap_acquire_at(struct mheap *__restrict self, MALIGNED void *p,
MALIGNED size_t n_bytes, MALIGNED size_t *__restrict alloc_bytes,
gfp_t flags) {
struct mfree **pslot,*slot;
MALIGNED void *result = p;
ATREE_SEMI_T(uintptr_t) addr_semi;
ATREE_LEVEL_T addr_level;
size_t slot_avail;
size_t unused_before; gfp_t slot_flags;
CHECK_HOST_DOBJ(self);
CHECK_HOST_DOBJ(alloc_bytes);
assert(IS_ALIGNED((uintptr_t)p,HEAP_ALIGNMENT));
assert(IS_ALIGNED((uintptr_t)n_bytes,HEAP_ALIGNMENT));
assert(mheap_writing(self));
if unlikely(!n_bytes) return p;
addr_semi = ATREE_SEMI0(uintptr_t);
addr_level = ATREE_LEVEL0(uintptr_t);
/* Search for a free slot at the given address. */
pslot = mfree_tree_plocate_at(&self->mh_addr,(uintptr_t)p,
&addr_semi,&addr_level);
if unlikely(pslot == PAGE_ERROR) {
/* Easy enough: the slot doesn't exist, so allocate memory here. */
PAGE_ALIGNED void *ptr_page = (void *)FLOOR_ALIGN((uintptr_t)p,PAGESIZE);
PAGE_ALIGNED size_t ptr_size = CEIL_ALIGN(((uintptr_t)p-(uintptr_t)ptr_page)+n_bytes,PAGESIZE);
assertf(IS_ALIGNED(ptr_size,HEAP_ALIGNMENT),"ptr_size = %Iu",ptr_size);
slot = (struct mfree *)core_page_allocat(ptr_page,ptr_size,flags);
if unlikely(slot == PAGE_ERROR) return PAGE_ERROR;
assert(IS_ALIGNED(MFREE_BEGIN(slot),HEAP_ALIGNMENT));
slot_avail = ptr_size-((uintptr_t)p-(uintptr_t)slot);
assert(IS_ALIGNED(slot_avail,HEAP_ALIGNMENT));
slot_flags = flags;
} else {
pgattr_t slot_attr;
slot = *pslot;
CHECK_HOST_DOBJ(slot);
assert((uintptr_t)p >= MFREE_MIN(slot));
assert((uintptr_t)p <= MFREE_MAX(slot));
assert(MFREE_SIZE(slot) >= HEAP_MIN_MALLOC);
assert(MFREE_SIZE(slot) > ((uintptr_t)p-MFREE_BEGIN(slot)));
assert(IS_ALIGNED(MFREE_BEGIN(slot),HEAP_ALIGNMENT));
slot_avail = MFREE_SIZE(slot)-((uintptr_t)p-MFREE_BEGIN(slot));
slot_attr = MFREE_ATTR(slot);
assert(IS_ALIGNED(slot_avail,HEAP_ALIGNMENT));
if (slot_avail < n_bytes) {
MALIGNED void *missing_addr;
MALIGNED size_t missing_size;
MALIGNED size_t missing_alloc;
/* The slot is too small. - allocate more memory afterwards. */
missing_addr = (void *)MFREE_END(slot);
missing_size = n_bytes-slot_avail;
assert(IS_ALIGNED((uintptr_t)missing_addr,HEAP_ALIGNMENT));
assert(IS_ALIGNED(missing_size,HEAP_ALIGNMENT));
if (mheap_acquire_at(self,missing_addr,missing_size,&missing_alloc,flags) == PAGE_ERROR)
return PAGE_ERROR;
/* Find the slot again, now that the heap has changed. */
addr_semi = ATREE_SEMI0(uintptr_t);
addr_level = ATREE_LEVEL0(uintptr_t);
/* Search for a free slot at the given address. */
pslot = mfree_tree_plocate_at(&self->mh_addr,(uintptr_t)p,
&addr_semi,&addr_level);
assertf(pslot != NULL,"But we know it must exist! (%p...%p)");
assert(*pslot == slot);
assert(slot_attr == MFREE_ATTR(*pslot));
slot_avail += missing_size;
}
/* Remove the slot from the address-tree & size-chain. */
mfree_tree_pop_at(pslot,addr_semi,addr_level);
LIST_REMOVE_EX(slot,mf_lsize,PAGE_ERROR);
/* Clear out the slot header. */
if (slot_attr&PAGEATTR_ZERO)
memset(slot,0,sizeof(struct mfree));
#ifdef CONFIG_MALLOC_DEBUG_INIT
else MEMPATX(slot,CONFIG_MALLOC_DEBUG_INIT,sizeof(struct mfree));
#endif
slot_flags = (flags&~GFP_CALLOC)|GFP_STPAGEATTR(slot_attr);
}
unused_before = (uintptr_t)result-MFREE_BEGIN(slot);
assert(IS_ALIGNED(unused_before,HEAP_ALIGNMENT));
if (unused_before) {
/* Make sure that the sub-pre-range isn't too small. */
if (unused_before < HEAP_MIN_MALLOC) {
MALIGNED void *slot_before_addr;
size_t slot_before_size,slot_before_alloc;
slot_before_size = HEAP_MIN_MALLOC-unused_before;
assert(IS_ALIGNED(slot_before_size,HEAP_ALIGNMENT));
assert(slot_before_size != 0);
slot_before_addr = (void *)((uintptr_t)slot-slot_before_size);
if (mheap_acquire_at(self,slot_before_addr,slot_before_size,
&slot_before_alloc,slot_flags) == PAGE_ERROR) {
asserte(mheap_release(self,slot,slot_avail+
((uintptr_t)p-MFREE_BEGIN(slot)),
slot_flags,false));
return PAGE_ERROR;
}
/* Got some memory before the slot! */
assert(IS_ALIGNED(slot_before_alloc,HEAP_ALIGNMENT));
assert(slot_before_alloc == slot_before_size);
slot = (struct mfree *)slot_before_addr;
unused_before += slot_before_alloc;
}
/* Free the unused memory before the slot. */
mheap_release_nomerge(self,slot,unused_before,slot_flags);
}
/* At this point we've allocated `slot_avail' bytes at `p'
* >> Now we must simply try to free as much of the difference as possible. */
assertf(IS_ALIGNED(slot_avail,HEAP_ALIGNMENT),"slot_avail = %Iu\n",slot_avail);
assert(IS_ALIGNED(n_bytes,HEAP_ALIGNMENT));
assert(slot_avail >= n_bytes);
{
size_t unused_size = slot_avail-n_bytes;
/* Try to release high memory. */
if (unused_size && mheap_release(self,
(void *)((uintptr_t)p+n_bytes),
unused_size,slot_flags,false))
slot_avail -= unused_size;
}
/* Do final initialization of memory. */
if (flags&GFP_CALLOC) {
if (!(slot_flags&GFP_CALLOC))
memset(p,0,slot_avail);
}
#ifdef CONFIG_MALLOC_DEBUG_INIT
else if (slot_flags&GFP_CALLOC) {
MEMPATX(p,CONFIG_MALLOC_DEBUG_INIT,slot_avail);
}
#endif
*alloc_bytes = slot_avail;
return p;
}
PRIVATE void KCALL
mheap_release_nomerge(struct mheap *__restrict self, MALIGNED void *p,
MALIGNED size_t n_bytes, gfp_t flags) {
struct mfree **piter,*iter;
CHECK_HOST_DATA(p,n_bytes);
assert(IS_ALIGNED((uintptr_t)p,HEAP_ALIGNMENT));
assert(IS_ALIGNED((uintptr_t)n_bytes,HEAP_ALIGNMENT));
assert(n_bytes >= HEAP_MIN_MALLOC);
#define NEW_SLOT ((struct mfree *)p)
#ifdef CONFIG_RESERVE_NULL_PAGE
assert((uintptr_t)p >= PAGESIZE);
#endif
assert(mheap_writing(self));
MFREE_SETUP(NEW_SLOT,n_bytes,GFP_GTPAGEATTR(flags));
assert(MFREE_SIZE(NEW_SLOT) >= HEAP_MIN_MALLOC);
mfree_tree_insert(&self->mh_addr,NEW_SLOT);
/* Figure out where the free-slot should go in the chain of free ranges. */
piter = &self->mh_size[HEAP_BUCKET_OF(n_bytes)];
while ((iter = *piter) != PAGE_ERROR &&
MFREE_SIZE(iter) < n_bytes)
piter = &iter->mf_lsize.le_next;
// syslog(LOG_DEBUG,"HERE: %p...%p (%x)\n",p,(uintptr_t)p+n_bytes-1,flags);
NEW_SLOT->mf_lsize.le_pself = piter;
NEW_SLOT->mf_lsize.le_next = iter;
if (iter != PAGE_ERROR) iter->mf_lsize.le_pself = &NEW_SLOT->mf_lsize.le_next;
*piter = NEW_SLOT;
assert(NEW_SLOT->mf_lsize.le_next);
MHEAP_INTERNAL_VALIDATE(flags);
#undef NEW_SLOT
}
PRIVATE bool KCALL
mheap_release(struct mheap *__restrict self, MALIGNED void *p,
MALIGNED size_t n_bytes, gfp_t flags,
bool unlock_heap) {
struct mfree **pslot,*slot,*iter,*next;
struct mfree *free_slot;
ATREE_SEMI_T(uintptr_t) addr_semi;
ATREE_LEVEL_T addr_level;
CHECK_HOST_DATA(p,n_bytes);
assert(mheap_writing(self));
assert(IS_ALIGNED((uintptr_t)p,HEAP_ALIGNMENT));
assert(IS_ALIGNED(n_bytes,HEAP_ALIGNMENT));
if unlikely(!n_bytes) {
if (unlock_heap) mheap_endwrite(self);
return true;
}
#ifndef MFREE_HAVE_ATTR
assert(!(GFP_GTPAGEATTR(flags)&MFREE_SIZEMASK));
#endif
#if LOG_MANAGED_ALLOCATIONS
syslog(LOG_MEM|LOG_ERROR,"[MEM] FREE(%p...%p)\n",
p,(uintptr_t)p+n_bytes-1);
#endif
MHEAP_INTERNAL_VALIDATE(flags);
/* Check for extending a free range above. */
addr_semi = ATREE_SEMI0(uintptr_t);
addr_level = ATREE_LEVEL0(uintptr_t);
pslot = mfree_tree_plocate_at(&self->mh_addr,(uintptr_t)p-1,
&addr_semi,&addr_level);
if (pslot != PAGE_ERROR) {
/* Extend this slot above. */
slot = *pslot;
CHECK_HOST_DOBJ(slot);
assert(MFREE_END(slot) == (uintptr_t)p);
mfree_tree_pop_at(pslot,addr_semi,addr_level);
#ifdef CONFIG_MALLOC_DEBUG_INIT
if (slot->mf_attr&PAGEATTR_ZERO && !(flags&GFP_CALLOC))
MEMPATX(slot+1,CONFIG_MALLOC_DEBUG_INIT,
MFREE_SIZE(slot)-sizeof(struct mfree));
if (flags&GFP_CALLOC && !(slot->mf_attr&PAGEATTR_ZERO))
MEMPATX(p,CONFIG_MALLOC_DEBUG_INIT,n_bytes);
#endif
if (!(slot->mf_attr&PAGEATTR_ZERO)) flags &= ~(GFP_CALLOC);
#ifdef MFREE_HAVE_ATTR
slot->mf_attr = GFP_GTPAGEATTR(flags);
slot->mf_size += n_bytes;
#else
MFREE_SETUP(slot,MFREE_SIZE(slot)+n_bytes,GFP_GTPAGEATTR(flags));
#endif
addr_semi = ATREE_SEMI0(uintptr_t);
addr_level = ATREE_LEVEL0(uintptr_t);
pslot = mfree_tree_pinsert_at(&self->mh_addr,slot,&addr_semi,&addr_level);
iter = slot->mf_lsize.le_next;
if (iter != PAGE_ERROR && MFREE_SIZE(iter) < MFREE_SIZE(slot)) {
/* Fix the size position. */
LIST_REMOVE_EX(slot,mf_lsize,PAGE_ERROR);
while ((next = iter->mf_lsize.le_next) != PAGE_ERROR &&
MFREE_SIZE(next) < MFREE_SIZE(slot)) iter = next;
/* Re-insert the slot. */
LIST_INSERT_AFTER_EX(iter,slot,mf_lsize,PAGE_ERROR);
}
mheap_unmapfree(self,pslot,addr_semi,addr_level,flags,unlock_heap);
MHEAP_INTERNAL_VALIDATE(flags);
return true;
}
/* Check for extending a free range below. */
addr_semi = ATREE_SEMI0(uintptr_t);
addr_level = ATREE_LEVEL0(uintptr_t);
pslot = mfree_tree_plocate_at(&self->mh_addr,(uintptr_t)p+n_bytes,
&addr_semi,&addr_level);
if (pslot != PAGE_ERROR) {
/* Extend this slot below. */
slot = *pslot;
CHECK_HOST_DOBJ(slot);
assert(MFREE_BEGIN(slot) == (uintptr_t)p+n_bytes);
assertf(MFREE_SIZE(slot) >= HEAP_MIN_MALLOC,
"MFREE_SIZE(slot) = %Iu\n",MFREE_SIZE(slot));
mfree_tree_pop_at(pslot,addr_semi,addr_level);
free_slot = (struct mfree *)p;
*free_slot = *slot;
#ifdef CONFIG_MALLOC_DEBUG_INIT
if (free_slot->mf_attr&PAGEATTR_ZERO && !(flags&GFP_CALLOC))
MEMPATX(slot+1,CONFIG_MALLOC_DEBUG_INIT,
MFREE_SIZE(slot)-sizeof(struct mfree));
if (flags&GFP_CALLOC && !(free_slot->mf_attr&PAGEATTR_ZERO))
MEMPATX(free_slot+1,CONFIG_MALLOC_DEBUG_INIT,n_bytes);
#endif
if (!(free_slot->mf_attr&PAGEATTR_ZERO)) flags &= ~(GFP_CALLOC);
#ifdef MFREE_HAVE_ATTR
free_slot->mf_attr = GFP_GTPAGEATTR(flags);
free_slot->mf_size += n_bytes;
#else
MFREE_SETUP(free_slot,MFREE_SIZE(free_slot)+n_bytes,GFP_GTPAGEATTR(flags));
#endif
*free_slot->mf_lsize.le_pself = free_slot;
if (free_slot->mf_lsize.le_next != PAGE_ERROR)
free_slot->mf_lsize.le_next->mf_lsize.le_pself = &free_slot->mf_lsize.le_next;
assert(IS_ALIGNED(MFREE_SIZE(free_slot),HEAP_ALIGNMENT));
if (free_slot->mf_attr&PAGEATTR_ZERO) {
if (n_bytes < sizeof(struct mfree))
memset((void *)((uintptr_t)slot+(sizeof(struct mfree)-n_bytes)),0,n_bytes);
else memset(slot,0,sizeof(struct mfree));
}
#ifdef CONFIG_MALLOC_DEBUG_INIT
else {
if (n_bytes < sizeof(struct mfree))
MEMPATX((void *)((uintptr_t)slot+(sizeof(struct mfree)-n_bytes)),
CONFIG_MALLOC_DEBUG_INIT,n_bytes);
else MEMPATX(slot,CONFIG_MALLOC_DEBUG_INIT,sizeof(struct mfree));
}
#endif
assert(IS_ALIGNED(MFREE_SIZE(free_slot),HEAP_ALIGNMENT));
addr_semi = ATREE_SEMI0(uintptr_t);
addr_level = ATREE_LEVEL0(uintptr_t);
pslot = mfree_tree_pinsert_at(&self->mh_addr,free_slot,&addr_semi,&addr_level);
iter = free_slot->mf_lsize.le_next;
if (iter != PAGE_ERROR && MFREE_SIZE(iter) < MFREE_SIZE(free_slot)) {
/* Fix the size position. */
LIST_REMOVE_EX(free_slot,mf_lsize,PAGE_ERROR);
while ((next = iter->mf_lsize.le_next) != PAGE_ERROR &&
MFREE_SIZE(next) < MFREE_SIZE(free_slot)) iter = next;
/* Re-insert the slot. */
LIST_INSERT_AFTER_EX(iter,free_slot,mf_lsize,PAGE_ERROR);
}
mheap_unmapfree(self,pslot,addr_semi,
addr_level,flags,unlock_heap);
MHEAP_INTERNAL_VALIDATE(flags);
return true;
}
MHEAP_INTERNAL_VALIDATE(flags);
/* Make sure the heap part wouldn't shrink too small. */
if (n_bytes < HEAP_MIN_MALLOC) goto too_small;
mheap_release_nomerge(self,p,n_bytes,flags);
if (unlock_heap) mheap_endwrite(self);
MHEAP_INTERNAL_VALIDATE(flags);
return true;
too_small:
if (unlock_heap) mheap_endwrite(self);
return false;
}
PRIVATE void KCALL
mheap_unmapfree(struct mheap *__restrict self,
struct mfree **__restrict pslot,
ATREE_SEMI_T(uintptr_t) addr_semi,
ATREE_LEVEL_T addr_level, gfp_t flags,
bool unlock_heap) {
struct mfree *slot;
assert(mheap_writing(self));
CHECK_HOST_DOBJ(pslot);
slot = *pslot;
CHECK_HOST_DOBJ(slot);
assert(IS_ALIGNED(MFREE_BEGIN(slot),HEAP_ALIGNMENT));
assert(IS_ALIGNED(MFREE_SIZE(slot),HEAP_ALIGNMENT));
if (MFREE_SIZE(slot) >= self->mh_freethresh) {
/* Release full pages. */
PAGE_ALIGNED void *page_begin = (PAGE_ALIGNED void *)CEIL_ALIGN((uintptr_t)MFREE_BEGIN(slot),PAGESIZE);
PAGE_ALIGNED void *page_end = (PAGE_ALIGNED void *)FLOOR_ALIGN((uintptr_t)MFREE_END(slot),PAGESIZE);
assert(page_begin <= page_end);
assert((uintptr_t)page_begin >= MFREE_BEGIN(slot));
assert((uintptr_t)page_end <= MFREE_END(slot));
if (page_begin != page_end) {
/* Unlink the free portion. */
struct mfree *hi_slot;
gfp_t page_flags;
MALIGNED size_t lo_size = (uintptr_t)page_begin-MFREE_BEGIN(slot);
MALIGNED size_t hi_size = MFREE_END(slot)-(uintptr_t)page_end;
assertf(IS_ALIGNED(lo_size,HEAP_ALIGNMENT),"lo_size = %Iu\n",lo_size);
assertf(IS_ALIGNED(hi_size,HEAP_ALIGNMENT),"hi_size = %Iu\n",hi_size);
hi_slot = (struct mfree *)page_end;
if (lo_size && lo_size < HEAP_MIN_MALLOC) {
lo_size += PAGESIZE;
*(uintptr_t *)&page_begin += PAGESIZE;
if (page_begin == page_end) goto end;
}
if (hi_size && hi_size < HEAP_MIN_MALLOC) {
hi_size += PAGESIZE;
*(uintptr_t *)&page_end -= PAGESIZE;
*(uintptr_t *)&hi_slot -= PAGESIZE;
if (page_begin == page_end) goto end;
}
assert(page_begin <= page_end);
page_flags = GFP_STPAGEATTR(MFREE_ATTR(slot))|(flags&~GFP_CALLOC);
/* Remove the old slot from the heap. */
LIST_REMOVE_EX(slot,mf_lsize,PAGE_ERROR);
mfree_tree_pop_at(pslot,addr_semi,addr_level);
/* Clear the small amount of memory filled with the free-controller. */
if (page_flags&GFP_CALLOC)
memset(slot,0,sizeof(struct mfree));
/* Create the low & high parts. */
if (lo_size) mheap_release_nomerge(self,slot,lo_size,page_flags);
if (hi_size) mheap_release_nomerge(self,hi_slot,hi_size,page_flags);
if (unlock_heap) mheap_endwrite(self);
/* Release heap data back to the system. */
core_page_free(page_begin,
(PAGE_ALIGNED uintptr_t)page_end-
(PAGE_ALIGNED uintptr_t)page_begin,
page_flags);
return;
}
}
end:
if (unlock_heap)
mheap_endwrite(self);
}
PRIVATE MALIGNED void *KCALL
mheap_acquire_al(struct mheap *__restrict self,
MALIGNED size_t alignment, size_t offset, MALIGNED size_t n_bytes,
MALIGNED size_t *__restrict alloc_bytes, gfp_t flags, bool unlock_heap) {
void *alloc_base; void *result;
size_t alloc_size,nouse_size;
assert(alignment != 0);
assert((alignment&(alignment-1)) == 0);
assert(IS_ALIGNED(alignment,HEAP_ALIGNMENT));
assert(IS_ALIGNED(n_bytes,HEAP_ALIGNMENT));
if unlikely(n_bytes < HEAP_MIN_MALLOC)
n_bytes = HEAP_MIN_MALLOC;
/* Must overallocate by at least `HEAP_MIN_MALLOC',
* so we can _always_ free unused lower memory. */
alloc_base = mheap_acquire(self,n_bytes+alignment+HEAP_MIN_MALLOC,&alloc_size,flags,false);
if unlikely(alloc_base == PAGE_ERROR) {
if (unlock_heap) mheap_endwrite(self);
return PAGE_ERROR;
}
assert(alloc_size >= n_bytes+alignment+HEAP_MIN_MALLOC);
result = (void *)(CEIL_ALIGN((uintptr_t)alloc_base+HEAP_MIN_MALLOC+offset,alignment)-offset);
assert((uintptr_t)result+n_bytes <=
(uintptr_t)alloc_base+alloc_size);
nouse_size = (uintptr_t)result-(uintptr_t)alloc_base;
assert(nouse_size+n_bytes <= alloc_size);
assertf(nouse_size >= HEAP_MIN_MALLOC,"nouse_size = %Iu",nouse_size);
/* Release lower memory. */
asserte(mheap_release(self,alloc_base,nouse_size,flags,false));
alloc_size -= nouse_size;
/* Try to release upper memory. */
assert(alloc_size >= n_bytes);
nouse_size = alloc_size-n_bytes;
if (mheap_release(self,(void *)((uintptr_t)result+n_bytes),nouse_size,flags,unlock_heap))
alloc_size -= nouse_size;
assert(alloc_size >= n_bytes);
*alloc_bytes = alloc_size;
assert(IS_ALIGNED((uintptr_t)result+offset,alignment));
return result;
}
#ifdef CONFIG_MALLOC_DEBUG_INIT
PRIVATE void KCALL
priv_resetpage(PAGE_ALIGNED void *start, uintptr_t xword, size_t n_bytes) {
bool should_clear;
assert(IS_ALIGNED((uintptr_t)start,PAGESIZE));
assert(n_bytes != 0);
assert(n_bytes <= PAGESIZE);
assert((n_bytes%4) == 0);
/* Check if the page at `start' is really allocated. */
if (addr_isglob(start)) {
task_nointr();
mman_read(&mman_kernel);
should_clear = thispdir_test_writable(&pdir_kernel_v,start);
mman_endread(&mman_kernel);
task_endnointr();
} else {
should_clear = true;
}
/* Only reset the page when it has been allocated. */
if (should_clear) MEMSETX(start,xword,n_bytes/__SIZEOF_POINTER__);
}
/* Scan `n_bytes' of memory for any byte not matching `xword & 0xff',
* assuming that `xword == 0x01010101 * (xword & 0xff)'
* Return NULL when no such byte exists, or the non-matching byte if so.
* NOTE: Special handling is done to ensure that no new memory after any non-aligned
* memory between `begin...CEIL_ALIGN(begin,PAGESIZE)' is allocated due to
* access, meaning that system memory isn't strained by accessing unallocated
* data, but instead assuming that that data is always equal to `xword'. */
PRIVATE void KCALL
priv_memsetx_noalloc(void *__restrict begin, uintptr_t xword, size_t n_bytes) {
byte_t *iter,*end,*aligned;
size_t fill_bytes;
end = (iter = (byte_t *)begin)+n_bytes;
assert(iter <= end);
while (iter != end && (uintptr_t)iter&(__SIZEOF_POINTER__-1))
*iter = ((u8 *)&xword)[(uintptr_t)iter&(__SIZEOF_POINTER__-1)];
assert(((end-iter) % __SIZEOF_POINTER__) == 0);
aligned = (byte_t *)CEIL_ALIGN((uintptr_t)iter,PAGESIZE);
fill_bytes = (size_t)(aligned-iter);
n_bytes = (size_t)(end-iter);
if (fill_bytes > n_bytes)
fill_bytes = n_bytes;
if (fill_bytes) {
/* Set unaligned data in the first (allocated) page. */
MEMSETX(iter,xword,fill_bytes/__SIZEOF_POINTER__);
n_bytes -= fill_bytes;
}
/* TODO: Tell the memory manager to unload all full pages,
* so that they will be re-allocated next time. */
while (n_bytes) {
fill_bytes = n_bytes;
if (fill_bytes > PAGESIZE)
fill_bytes = PAGESIZE;
/* Set unaligned data in other (potentially unallocated) pages. */
priv_resetpage(aligned,xword,fill_bytes);
n_bytes -= fill_bytes;
aligned += fill_bytes;
}
}
/* Reset debug pre-initialization of the given memory. */
PRIVATE void KCALL mheap_resetdebug(MALIGNED void *__restrict begin,
MALIGNED size_t n_bytes, gfp_t flags) {
if (flags&GFP_CALLOC) return;
priv_memsetx_noalloc(begin,CONFIG_MALLOC_DEBUG_INIT,n_bytes);
}
#else
#define mheap_resetdebug(begin,n_bytes,flags) (void)0
#endif
PRIVATE struct mptr *KCALL
mheap_malloc(struct mheap *__restrict self, size_t size, gfp_t flags) {
struct mptr *result;
MALIGNED size_t alloc_size;
mheap_write(self);
result = (struct mptr *)mheap_acquire(self,CEIL_ALIGN(MPTR_SIZEOF(size),HEAP_ALIGNMENT),
&alloc_size,flags,true);
/*mheap_endwrite(self);*/
if unlikely(result == PAGE_ERROR) return MPTR_OF(NULL);
assert(alloc_size >= size);
MPTR_SETUP(result,flags&GFP_MASK_MPTR,alloc_size);
MPTR_VALIDATE(result);
return result;
}
PRIVATE struct mptr *KCALL
mheap_memalign(struct mheap *__restrict self,
size_t alignment, size_t size,
gfp_t flags) {
struct mptr *result;
MALIGNED size_t alloc_size;
mheap_write(self);
result = (struct mptr *)mheap_acquire_al(self,alignment,sizeof(struct mptr),
CEIL_ALIGN(MPTR_SIZEOF(size),HEAP_ALIGNMENT),
&alloc_size,flags,true);
/*mheap_endwrite(self);*/
if (result == PAGE_ERROR) return MPTR_OF(NULL);
assert(IS_ALIGNED((uintptr_t)result+sizeof(struct mptr),alignment));
MPTR_SETUP(result,flags&GFP_MASK_MPTR,alloc_size);
MPTR_VALIDATE(result);
return result;
}
PRIVATE void KCALL
mheap_free(struct mheap *__restrict self, struct mptr *ptr, gfp_t flags) {
MALIGNED size_t alloc_size = MPTR_SIZE(ptr);
assertf(alloc_size >= MPTR_SIZEOF(0),
"alloc_size = %Iu\n",alloc_size);
if (flags&GFP_CALLOC) {
/* Clear the header + tail. */
#ifdef MPTR_HAVE_TAIL
memset(MPTR_TAILADDR(ptr),0,MPTR_TAILSIZE(ptr));
#endif
memset(ptr,0,sizeof(struct mptr));
}
#ifdef CONFIG_MALLOC_DEBUG_INIT
else {
mheap_resetdebug(ptr,alloc_size,flags);
}
#endif
mheap_write(self);
asserte(mheap_release(self,ptr,alloc_size,flags,true));
/*mheap_endwrite(self);*/
}
#ifndef __INTELLISENSE__
DECL_END
#define HEAP_REALIGN
#include "malloc-realign.c.inl"
#include "malloc-realign.c.inl"
DECL_BEGIN
#endif
#ifdef CONFIG_DEBUG_HEAP
PRIVATE void KCALL
mheap_validate_addr(struct dsetup *setup, struct mfree *node) {
if (node == PAGE_ERROR) return;
if (!OK_HOST_DATA(node,sizeof(struct mfree)))
malloc_panic(setup,NULL,"Invalid heap address-space space node %p",node);
if (!IS_ALIGNED(MFREE_BEGIN(node),HEAP_ALIGNMENT) ||
!IS_ALIGNED(MFREE_END(node),HEAP_ALIGNMENT))
malloc_panic(setup,NULL,"Miss-aligned heap address-space node %p...%p (size %p)\n%$[hex]",
MFREE_MIN(node),MFREE_MAX(node),MFREE_SIZE(node),sizeof(struct mfree),node);
if (MFREE_BEGIN(node) >= MFREE_END(node))
malloc_panic(setup,NULL,"Unordered heap address-space node %p...%p\n%$[hex]",
MFREE_MIN(node),MFREE_MAX(node),sizeof(struct mfree),node);
if (MFREE_SIZE(node) < HEAP_MIN_MALLOC)
malloc_panic(setup,NULL,"Heap address-space node %p...%p is too small (%Iu < %Iu)\n%$[hex]",
MFREE_MIN(node),MFREE_MAX(node),MFREE_SIZE(node),HEAP_MIN_MALLOC,sizeof(struct mfree),node);
mheap_validate_addr(setup,node->mf_laddr.a_min);
mheap_validate_addr(setup,node->mf_laddr.a_max);
}
PRIVATE void *KCALL
priv_scandata(void *start, uintptr_t xword, size_t n_bytes) {
#if defined(__i386__) || defined(__x86_64__)
byte_t *iter,*end; bool is_ok;
assert(n_bytes);
end = (iter = (byte_t *)start)+n_bytes;
__asm__ __volatile__(
#if __SIZEOF_POINTER__ >= 8
"repe; scasq\n"
#else
"repe; scasl\n"
#endif
"sete %1\n"
: "+D" (iter)
, "=g" (is_ok)
: "a" (xword)
, "c" ((end-iter)/__SIZEOF_POINTER__)
, "m" (*(struct { __extension__ byte_t val[n_bytes]; } *)start)
: "cc");
if (!is_ok) {
iter -= __SIZEOF_POINTER__;
assert(*(uintptr_t *)iter != xword);
while ((assert(iter < end),
*iter == ((u8 *)&xword)[(uintptr_t)iter & (__SIZEOF_POINTER__-1)]))
++iter;
return iter;
}
return NULL;
#else
uintptr_t *iter,*end;
while ((uintptr_t)start & (__SIZEOF_POINTER__-1)) {
if (!n_bytes) return NULL;
if unlikely(*(byte_t *)start != ((byte_t *)&xword)[(uintptr_t)start & (__SIZEOF_POINTER__-1)])
return start;
--n_bytes;
++*(byte_t **)&start;
}
end = (iter = (uintptr_t *)start)+(n_bytes/__SIZEOF_POINTER__);
n_bytes %= __SIZEOF_POINTER__;
for (; iter != end; ++iter) {
if likely(*iter == xword) continue;
while ((assert(iter < end),
*iter == ((u8 *)&xword)[(uintptr_t)iter & (__SIZEOF_POINTER__-1)]))
++iter;
return iter;
}
while (n_bytes) {
if unlikely(*(byte_t *)iter != ((byte_t *)&xword)[(uintptr_t)iter & (__SIZEOF_POINTER__-1)])
return iter;
--n_bytes;
++*(byte_t **)&iter;
}
return NULL;
#endif
}
PRIVATE void *KCALL
priv_scanpage(PAGE_ALIGNED void *start, uintptr_t xword, size_t n_bytes) {
void *result = NULL; bool should_scan;
assert(IS_ALIGNED((uintptr_t)start,PAGESIZE));
assert(n_bytes != 0);
assert(n_bytes <= PAGESIZE);
/* Check if the page at `start' is really allocated. */
task_nointr();
mman_read(&mman_kernel);
should_scan = thispdir_test_writable(&pdir_kernel_v,start);
mman_endread(&mman_kernel);
task_endnointr();
/* Only scan the page when it has been allocated. */
if (should_scan) result = priv_scandata(start,xword,n_bytes);
return result;
}
/* Scan `n_bytes' of memory for any byte not matching `xword'.
* Return NULL when no such byte exists, or the non-matching byte if so.
* NOTE: Special handling is done to ensure that no new memory after any non-aligned
* memory between `begin...CEIL_ALIGN(begin,PAGESIZE)' is allocated due to
* access, meaning that system memory isn't strained by accessing unallocated
* data, but instead assuming that that data is always equal to `xword'. */
PRIVATE void *KCALL
priv_memnchr_noalloc(void *__restrict begin, uintptr_t xword, size_t n_bytes) {
byte_t *iter,*end,*aligned; void *result;
size_t scan_bytes;
end = (iter = (byte_t *)begin)+n_bytes;
//syslog(LOG_MEM|LOG_ERROR,"CHECK: %p...%p\n",iter,end-1);
assert(iter <= end);
while (iter != end && (uintptr_t)iter&(__SIZEOF_POINTER__-1)) {
if (*iter != ((u8 *)&xword)[(uintptr_t)iter&(__SIZEOF_POINTER__-1)]) return iter;
++iter;
}
assert(((end-iter) % __SIZEOF_POINTER__) == 0);
aligned = (byte_t *)CEIL_ALIGN((uintptr_t)iter,PAGESIZE);
scan_bytes = (size_t)(aligned-iter);
n_bytes = (size_t)(end-iter);
if (scan_bytes > n_bytes)
scan_bytes = n_bytes;
if (scan_bytes) {
/* Scan unaligned data in the first (allocated) page. */
result = priv_scandata(iter,xword,scan_bytes);
if (result) return result;
n_bytes -= scan_bytes;
}
while (n_bytes) {
//syslog(LOG_DEBUG,"SCAN_PAGE: %p\n",aligned);
scan_bytes = n_bytes;
if (scan_bytes > PAGESIZE)
scan_bytes = PAGESIZE;
/* Scan unaligned data in other (potentially unallocated) pages. */
result = priv_scanpage(aligned,xword,scan_bytes);
if (result) return result;
n_bytes -= scan_bytes;
aligned += scan_bytes;
}
return NULL;
}
PRIVATE void KCALL
mheap_validate(struct dsetup *setup,
struct mheap *__restrict self) {
struct mfree **iter,**end,**pnode,*node;
#if !MHEAP_RECURSIVE_LOCK
if (!mheap_tryread(self)) return;
#else
mheap_read(self);
#endif
mheap_validate_addr(setup,self->mh_addr);
end = (iter = self->mh_size)+COMPILER_LENOF(self->mh_size);
for (; iter != end; ++iter) {
size_t min_size = HEAP_BUCKET_MINSIZE(iter-self->mh_size);
pnode = iter;
while ((node = *pnode) != PAGE_ERROR) {
if (!OK_HOST_DATA(node,sizeof(struct mfree)))
malloc_panic(setup,NULL,"Invalid heap size node %p",node);
if (!IS_ALIGNED(MFREE_BEGIN(node),HEAP_ALIGNMENT) ||
!IS_ALIGNED(MFREE_END(node),HEAP_ALIGNMENT))
malloc_panic(setup,NULL,"Miss-aligned heap sized node %p...%p\n%$[hex]",
MFREE_MIN(node),MFREE_MAX(node),sizeof(struct mfree),node);
if (MFREE_BEGIN(node) >= MFREE_END(node))
malloc_panic(setup,NULL,"Unordered heap sized node %p...%p\n%$[hex]",
MFREE_MIN(node),MFREE_MAX(node),sizeof(struct mfree),node);
if (MFREE_SIZE(node) < min_size)
malloc_panic(setup,NULL,"Heap sized node %p...%p is too small (%Iu < %Iu)\n%$[hex]",
MFREE_MIN(node),MFREE_MAX(node),MFREE_SIZE(node),
min_size,sizeof(struct mfree),node);
if (node->mf_lsize.le_pself != pnode)
malloc_panic(setup,NULL,"Heap sized node %p...%p is incorrectly linked (%p != %p)\n%$[hex]",
MFREE_MIN(node),MFREE_MAX(node),node->mf_lsize.le_pself,
pnode,sizeof(struct mfree),node);
pnode = &node->mf_lsize.le_next;
if (*pnode != PAGE_ERROR && OK_HOST_DATA(*pnode,sizeof(struct mfree)) &&
MFREE_SIZE(*pnode) < MFREE_SIZE(node))
malloc_panic(setup,NULL,"Heap sized node %p...%p is incorrectly ordered (%Iu is larger than next node %p...%p with %Iu bytes)\n%$[hex]",
MFREE_MIN(node),MFREE_MAX(node),MFREE_SIZE(node),
MFREE_MIN(*pnode),MFREE_MAX(*pnode),MFREE_SIZE(*pnode),
sizeof(struct mfree),node);
#ifndef CONFIG_MALLOC_DEBUG_INIT
if (MFREE_ATTR(node)&PAGEATTR_ZERO)
#endif
{
/* Make sure that node data is really zero/debug-initialized. */
byte_t *begin,*error; size_t n_bytes;
#ifdef CONFIG_MALLOC_DEBUG_INIT
uintptr_t init_xword = CONFIG_MALLOC_DEBUG_INIT;
if (MFREE_ATTR(node)&PAGEATTR_ZERO) init_xword = 0;
#else
#define init_xword 0
#endif
#define HEX_OFFSET 32
#define HEX_SIZE (16+HEX_OFFSET*2)
begin = (byte_t *)MFREE_BEGIN(node);
n_bytes = MFREE_SIZE(node);
assert(n_bytes >= sizeof(struct mfree));
begin += sizeof(struct mfree);
n_bytes -= sizeof(struct mfree);
if (n_bytes &&
(error = (byte_t *)priv_memnchr_noalloc(begin,init_xword,n_bytes)) != NULL) {
size_t hex_size; byte_t *hex_begin;
hex_begin = error-HEX_OFFSET;
if (hex_begin < begin)
hex_begin = begin;
hex_size = (size_t)((begin+n_bytes)-hex_begin);
if (hex_size > HEX_SIZE) hex_size = HEX_SIZE;
malloc_panic(setup,NULL,
"Memory at %p modified after it was freed isn't %#.2I8x\n"
"> Offset %Id bytes into heap free range %p...%p\n"
"> Offset %Id bytes into heap data range %p...%p\n"
"%$[hex]",
error,((u8 *)&init_xword)[(uintptr_t)error & (__SIZEOF_POINTER__-1)],
(uintptr_t)error-MFREE_BEGIN(node),MFREE_MIN(node),MFREE_MAX(node),
(uintptr_t)error-(uintptr_t)begin,(uintptr_t)begin,MFREE_MAX(node),
hex_size,hex_begin);
}
#undef init_xword
}
}
}
mheap_endread(self);
}
#endif
/* TODO: Use `hptr_t' internally! */
/* Public kernel heap API. */
PUBLIC SAFE hptr_t KCALL
heap_malloc(size_t n_bytes, gfp_t flags) {
void *result; size_t heap_size = 0;
struct mheap *heap = MHEAP_GET(flags);
n_bytes = CEIL_ALIGN(n_bytes,HEAP_ALIGNMENT);
mheap_write(heap);
result = mheap_acquire(heap,n_bytes,&heap_size,flags,true);
return HPTR(result,heap_size);
}
PUBLIC SAFE hptr_t KCALL
heap_malloc_at(void *ptr, size_t n_bytes, gfp_t flags) {
void *result; size_t heap_size = 0;
struct mheap *heap = MHEAP_GET(flags);
n_bytes = CEIL_ALIGN(n_bytes,HEAP_ALIGNMENT);
mheap_write(heap);
result = mheap_acquire_at(heap,ptr,n_bytes,&heap_size,flags);
mheap_endwrite(heap);
return HPTR(result,heap_size);
}
PUBLIC SAFE hptr_t KCALL
heap_memalign(size_t alignment, size_t offset,
size_t n_bytes, gfp_t flags) {
void *result; size_t heap_size = 0;
struct mheap *heap = MHEAP_GET(flags);
if (alignment < HEAP_ALIGNMENT)
alignment = HEAP_ALIGNMENT;
else alignment = CEIL_ALIGN(alignment,HEAP_ALIGNMENT);
n_bytes = CEIL_ALIGN(n_bytes,HEAP_ALIGNMENT);
mheap_write(heap);
result = mheap_acquire_al(heap,alignment,offset,n_bytes,
&heap_size,flags,true);
return HPTR(result,heap_size);
}
/* Free heap memory previously allocated using `heap_*' functions. */
PUBLIC SAFE bool KCALL heap_ffree(hptr_t ptr, gfp_t flags) {
struct mheap *heap = MHEAP_GET(flags);
assert(IS_ALIGNED(HPTR_SIZE(ptr),HEAP_ALIGNMENT));
assert(!HPTR_SIZE(ptr) || IS_ALIGNED((uintptr_t)HPTR_ADDR(ptr),HEAP_ALIGNMENT));
/* Revert the contents of the given memory range to their defaults. */
mheap_resetdebug(HPTR_ADDR(ptr),HPTR_SIZE(ptr),flags);
mheap_write(heap);
return mheap_release(heap,HPTR_ADDR(ptr),HPTR_SIZE(ptr),flags,true);
}
#if defined(CONFIG_DEBUG_HEAP) || defined(MALLOC_DEBUG_API)
PRIVATE ATTR_NORETURN void KCALL
malloc_panic(struct dsetup *setup,
struct mptr *info_header,
char const *__restrict format, ...) {
va_list args;
PREEMPTION_DISABLE();
debug_printf("\n\n");
va_start(args,format);
debug_vprintf(format,args);
debug_printf("\n");
va_end(args);
if (setup) {
debug_printf("%s(%d) : %s : [%s] : See reference to caller location\n",
setup->s_info.i_file,setup->s_info.i_line,
setup->s_info.i_func,
setup->s_info.i_inst->i_module->m_name->dn_name);
debug_tbprint2(setup->s_tbebp,0);
}
if (info_header) {
bool ok_module;
#ifdef CONFIG_TRACE_LEAKS
atomic_rwlock_read(&mptr_inst_lock);
ok_module = (OK_HOST_TEXT(MPTR_INST(info_header),sizeof(struct instance)) &&
OK_HOST_TEXT(MPTR_INST(info_header)->i_module,sizeof(struct module)) &&
OK_HOST_TEXT(MPTR_INST(info_header)->i_module->m_name,sizeof(struct dentryname)) &&
OK_HOST_TEXT(MPTR_INST(info_header)->i_module->m_name->dn_name,
MPTR_INST(info_header)->i_module->m_name->dn_size));
debug_printf("%s(%d) : %s : [%.?s] : See reference to associated allocation\n",
OK_HOST_TEXT(MPTR_FILE(info_header),1) ? MPTR_FILE(info_header) : NULL,
MPTR_LINE(info_header),
OK_HOST_TEXT(MPTR_FUNC(info_header),1) ? MPTR_FUNC(info_header) : NULL,
ok_module ? MPTR_INST(info_header)->i_module->m_name->dn_size : 0,
ok_module ? MPTR_INST(info_header)->i_module->m_name->dn_name : NULL);
atomic_rwlock_endread(&mptr_inst_lock);
#endif
#ifdef CONFIG_MALLOC_TRACEBACK
{
void **iter,**end; size_t pos;
end = (iter = MPTR_TRACEBACK_ADDR(info_header))+
MPTR_TRACEBACK_SIZE(info_header);
pos = 0;
while (iter != end) {
if (*iter == MPTR_TAIL_TB_EOF) break;
#ifdef CONFIG_USE_EXTERNAL_ADDR2LINE
debug_printf("#!$ addr2line(%p) '{file}({line}) : {func} : [%Ix] : %p'\n",
(uintptr_t)*iter-1,pos,*iter);
#else
debug_printf("%[vinfo] : [%Ix] : %p\n",
(uintptr_t)*iter-1,pos,*iter);
#endif
++iter,++pos;
}
}
#endif
}
debug_printf("\n");
#if 1
__NAMESPACE_INT_SYM
__afail("MALL PANIC",__DEBUGINFO_NUL);
#else
PREEMPTION_FREEZE();
#endif
}
#endif
PRIVATE int (KCALL core_mallopt)(int parameter_number,
int parameter_value,
gfp_t flags) {
struct mheap *heap = MHEAP_GET(flags);
switch (parameter_number) {
case M_TRIM_THRESHOLD:
if (parameter_value < PAGESIZE) return 0;
heap->mh_freethresh = parameter_value;
break;
case M_GRANULARITY:
heap->mh_overalloc = parameter_value;
break;
default: return 0;
}
return 1;
}
PUBLIC SAFE size_t (KCALL kmalloc_trim)(size_t max_free) {
size_t result = 0;
/* TODO: Go through each of the kernel heaps and
* release any full pages kept for buffering. */
return result;
}
/* General purpose memory API. */
#define MPTR_KMALLOC(size,flags) mheap_malloc(MHEAP_GET(flags),size,flags)
#define MPTR_KMEMALIGN(alignment,size,flags) \
(unlikely(alignment <= HEAP_ALIGNMENT) ? MPTR_KMALLOC(size,flags) : \
mheap_memalign(MHEAP_GET(flags),alignment,size,flags))
#define MPTR_KFREE(ptr) mheap_free(MPTR_HEAP(ptr),ptr,MPTR_FLAGS(ptr))
#define MPTR_KZFREE(ptr) mheap_free(MPTR_HEAP(ptr),ptr,MPTR_FLAGS(ptr)|GFP_CALLOC)
#define MPTR_KFFREE(ptr,flags) mheap_free(MPTR_HEAP(ptr),ptr,MPTR_FLAGS(ptr)|((flags)&~GFP_MASK_MPTR))
#define MPTR_KMALLOC_USABLE_SIZE(ptr) MPTR_USERSIZE(ptr)
#define MPTR_KMALLOC_FLAGS(ptr) MPTR_FLAGS(ptr)
#ifdef CONFIG_TRACE_LEAKS
#define MPTR_KREALLOC(ptr,new_size,flags) mheap_realloc(setup,MPTR_HEAP(ptr),ptr,new_size,MPTR_FLAGS(ptr)|((flags)&~GFP_MASK_MPTR))
#define MPTR_KREALIGN(ptr,alignment,new_size,flags) \
(likely(alignment > HEAP_ALIGNMENT) \
? mheap_realign(setup,MPTR_HEAP(ptr),ptr,alignment,new_size,MPTR_FLAGS(ptr)|((flags)&~GFP_MASK_MPTR))\
: mheap_realloc(setup,MPTR_HEAP(ptr),ptr,new_size,MPTR_FLAGS(ptr)|((flags)&~GFP_MASK_MPTR)))
#else
#define MPTR_KREALLOC(ptr,new_size,flags) mheap_realloc(MPTR_HEAP(ptr),ptr,new_size,MPTR_FLAGS(ptr)|((flags)&~GFP_MASK_MPTR))
#define MPTR_KREALIGN(ptr,alignment,new_size,flags) \
(likely(alignment > HEAP_ALIGNMENT) \
? mheap_realign(MPTR_HEAP(ptr),ptr,alignment,new_size,MPTR_FLAGS(ptr)|((flags)&~GFP_MASK_MPTR))\
: mheap_realloc(MPTR_HEAP(ptr),ptr,new_size,MPTR_FLAGS(ptr)|((flags)&~GFP_MASK_MPTR)))
#endif
#define KMALLOC(size,flags) MPTR_USERADDR(MPTR_KMALLOC(size,flags))
#define KMEMALIGN(alignment,size,flags) MPTR_USERADDR(MPTR_KMEMALIGN(alignment,size,flags))
#define KFREE(ptr) (M_ISNONNULL(ptr) ? MPTR_KFREE(MPTR_GET(ptr)) : (void)0)
#define KFFREE(ptr,flags) (M_ISNONNULL(ptr) ? MPTR_KFFREE(MPTR_GET(ptr),flags) : (void)0)
#define KMALLOC_USABLE_SIZE(ptr) (M_ISNONNULL(ptr) ? MPTR_KMALLOC_USABLE_SIZE(MPTR_GET(ptr)) : 0)
#define KMALLOC_FLAGS(ptr) (M_ISNONNULL(ptr) ? MPTR_KMALLOC_FLAGS(MPTR_GET(ptr)) : __GFP_NULL)
#define KREALLOC(ptr,size,flags) MPTR_USERADDR(M_ISNONNULL(ptr) ? MPTR_KREALLOC(MPTR_GET(ptr),size,flags) : MPTR_KMALLOC(size,flags))
#define KREALIGN(ptr,alignment,size,flags) MPTR_USERADDR(M_ISNONNULL(ptr) ? MPTR_KREALIGN(MPTR_GET(ptr),alignment,size,flags) : MPTR_KMEMALIGN(alignment,size,flags))
/* Public malloc/kmalloc/mall Api implementations. */
#ifndef MALLOC_DEBUG_API
PUBLIC void *(KCALL kmalloc)(size_t size, gfp_t flags) { return KMALLOC(size,flags); }
PUBLIC void *(KCALL krealloc)(void *ptr, size_t size, gfp_t flags) { return KREALLOC(ptr,size,flags); }
PUBLIC void *(KCALL kmemalign)(size_t alignment, size_t size, gfp_t flags) { return KMEMALIGN(alignment,size,flags); }
PUBLIC void *(KCALL krealign)(void *ptr, size_t alignment, size_t size, gfp_t flags) { return KREALIGN(ptr,alignment,size,flags); }
PUBLIC void *(KCALL kmemdup)(void const *__restrict ptr, size_t size, gfp_t flags) { register void *result = kmalloc(size,flags); if (result) memcpy(result,ptr,size); return result; }
PUBLIC void *(KCALL kmemadup)(void const *__restrict ptr, size_t alignment, size_t size, gfp_t flags) { register void *result = kmemalign(alignment,size,flags); if (result) memcpy(result,ptr,size); return result; }
PUBLIC void (KCALL kfree)(void *ptr) { KFREE(ptr); }
PUBLIC void (KCALL kffree)(void *ptr, gfp_t flags) { KFFREE(ptr,flags); }
PUBLIC size_t (KCALL kmalloc_usable_size)(void *ptr) { return KMALLOC_USABLE_SIZE(ptr); }
PUBLIC gfp_t (KCALL kmalloc_flags)(void *ptr) { return KMALLOC_FLAGS(ptr); }
PUBLIC int (KCALL kmallopt)(int parameter_number, int parameter_value, gfp_t flags) { return core_mallopt(parameter_number,parameter_value,flags); }
PUBLIC void *(KCALL _kmalloc_d)(size_t size, gfp_t flags, DEBUGINFO_UNUSED) { return KMALLOC(size,flags); }
PUBLIC void *(KCALL _krealloc_d)(void *ptr, size_t size, gfp_t flags, DEBUGINFO_UNUSED) { return KREALLOC(ptr,size,flags); }
PUBLIC void *(KCALL _kmemalign_d)(size_t alignment, size_t size, gfp_t flags, DEBUGINFO_UNUSED) { return KMEMALIGN(alignment,size,flags); }
PUBLIC void *(KCALL _krealign_d)(void *ptr, size_t alignment, size_t size, gfp_t flags, DEBUGINFO_UNUSED) { return KREALIGN(ptr,alignment,size,flags); }
PUBLIC void *(KCALL _kmemdup_d)(void const *__restrict ptr, size_t size, gfp_t flags, DEBUGINFO_UNUSED) { return kmemdup(ptr,size,flags); }
PUBLIC void *(KCALL _kmemadup_d)(void const *__restrict ptr, size_t alignment, size_t size, gfp_t flags, DEBUGINFO_UNUSED) { return kmemadup(ptr,alignment,size,flags); }
PUBLIC void (KCALL _kfree_d)(void *ptr, DEBUGINFO_UNUSED) { KFREE(ptr); }
PUBLIC void (KCALL _kffree_d)(void *ptr, gfp_t flags, DEBUGINFO_UNUSED) { KFFREE(ptr,flags); }
PUBLIC size_t (KCALL _kmalloc_usable_size_d)(void *ptr, DEBUGINFO_UNUSED) { return KMALLOC_USABLE_SIZE(ptr); }
PUBLIC gfp_t (KCALL _kmalloc_flags_d)(void *ptr, DEBUGINFO_UNUSED) { return KMALLOC_FLAGS(ptr); }
PUBLIC int (KCALL _kmallopt_d)(int parameter_number, int parameter_value, gfp_t flags, DEBUGINFO_UNUSED) { return core_mallopt(parameter_number,parameter_value,flags); }
#ifndef __ptbwalker_defined
#define __ptbwalker_defined 1
typedef __SSIZE_TYPE__ (__LIBCCALL *__ptbwalker)(void const *__restrict __instruction_pointer,
void const *__restrict __frame_address,
size_t __frame_index, void *__closure);
#endif
/* MALL Api stubs. */
PUBLIC void *(KCALL _mall_getattrib)(void *__restrict UNUSED(mallptr), int UNUSED(attrib)) { return NULL; }
PUBLIC ssize_t (KCALL _mall_traceback)(void *__restrict UNUSED(mallptr), __ptbwalker UNUSED(callback), void *UNUSED(closure)) { return 0; }
PUBLIC ssize_t (KCALL _mall_enum)(struct instance *UNUSED(inst), void *UNUSED(checkpoint), ssize_t (*callback)(void *__restrict mallptr, void *closure), void *UNUSED(closure)) { (void)callback; return 0; }
PUBLIC void (KCALL _mall_printleaks)(struct instance *UNUSED(inst)) {}
PUBLIC void (KCALL _mall_validate)(struct instance *UNUSED(inst)) {}
PUBLIC void *(KCALL _mall_untrack)(void *mallptr) { return mallptr; }
PUBLIC void *(KCALL _mall_nofree)(void *mallptr) { return mallptr; }
PUBLIC void *(KCALL _mall_getattrib_d)(void *__restrict UNUSED(mallptr), int UNUSED(attrib), DEBUGINFO_UNUSED) { return NULL; }
PUBLIC ssize_t (KCALL _mall_traceback_d)(void *__restrict UNUSED(mallptr), __ptbwalker UNUSED(callback), void *UNUSED(closure), DEBUGINFO_UNUSED) { return 0; }
PUBLIC ssize_t (KCALL _mall_enum_d)(struct instance *UNUSED(inst), void *UNUSED(checkpoint), ssize_t (*callback)(void *__restrict mallptr, void *closure), void *UNUSED(closure), DEBUGINFO_UNUSED) { (void)callback; return 0; }
PUBLIC void (KCALL _mall_printleaks_d)(struct instance *UNUSED(inst), DEBUGINFO_UNUSED) {}
PUBLIC void (KCALL _mall_validate_d)(struct instance *UNUSED(inst), DEBUGINFO_UNUSED) {}
PUBLIC void *(KCALL _mall_untrack_d)(void *mallptr, DEBUGINFO_UNUSED) { return mallptr; }
PUBLIC void *(KCALL _mall_nofree_d)(void *mallptr, DEBUGINFO_UNUSED) { return mallptr; }
/* Public malloc Api implementation. */
PUBLIC void *(KCALL malloc)(size_t n_bytes) { return KMALLOC(n_bytes,__GFP_MALLOC); }
PUBLIC void *(KCALL calloc)(size_t count, size_t n_bytes) { return KMALLOC(count*n_bytes,__GFP_MALLOC|GFP_CALLOC); }
PUBLIC void *(KCALL memalign)(size_t alignment, size_t n_bytes) { return KMEMALIGN(alignment,n_bytes,__GFP_MALLOC); }
PUBLIC void *(KCALL realloc)(void *__restrict mallptr, size_t n_bytes) { return KREALLOC(mallptr,n_bytes,__GFP_MALLOC); }
PUBLIC void *(KCALL realloc_in_place)(void *__restrict mallptr, size_t n_bytes) { return KREALLOC(mallptr,n_bytes,__GFP_MALLOC|GFP_NOMOVE); }
PUBLIC void *(KCALL valloc)(size_t n_bytes) { return KMEMALIGN(PAGESIZE,n_bytes,__GFP_MALLOC); }
PUBLIC void *(KCALL pvalloc)(size_t n_bytes) { return KMEMALIGN(PAGESIZE,(n_bytes+PAGESIZE-1)&~(PAGESIZE-1),__GFP_MALLOC); }
PUBLIC int (KCALL mallopt)(int parameter_number, int parameter_value) { return core_mallopt(parameter_number,parameter_value,__GFP_MALLOC); }
PUBLIC int (KCALL _mallopt_d)(int parameter_number, int parameter_value, DEBUGINFO_UNUSED) { return core_mallopt(parameter_number,parameter_value,__GFP_MALLOC); }
PUBLIC void *(KCALL _malloc_d)(size_t n_bytes, DEBUGINFO_UNUSED) { return KMALLOC(n_bytes,__GFP_MALLOC); }
PUBLIC void *(KCALL _calloc_d)(size_t count, size_t n_bytes, DEBUGINFO_UNUSED) { return KMALLOC(count*n_bytes,__GFP_MALLOC|GFP_CALLOC); }
PUBLIC void *(KCALL _memalign_d)(size_t alignment, size_t n_bytes, DEBUGINFO_UNUSED) { return KMEMALIGN(alignment,n_bytes,__GFP_MALLOC); }
PUBLIC void *(KCALL _realloc_d)(void *__restrict mallptr, size_t n_bytes, DEBUGINFO_UNUSED) { return KREALLOC(mallptr,n_bytes,__GFP_MALLOC); }
PUBLIC void *(KCALL _realloc_in_place_d)(void *__restrict mallptr, size_t n_bytes, DEBUGINFO_UNUSED) { return KREALLOC(mallptr,n_bytes,__GFP_MALLOC|GFP_NOMOVE); }
PUBLIC void *(KCALL _valloc_d)(size_t n_bytes, DEBUGINFO_UNUSED) { return KMEMALIGN(PAGESIZE,n_bytes,__GFP_MALLOC); }
PUBLIC void *(KCALL _pvalloc_d)(size_t n_bytes, DEBUGINFO_UNUSED) { return KMEMALIGN(PAGESIZE,(n_bytes+PAGESIZE-1)&~(PAGESIZE-1),__GFP_MALLOC); }
PUBLIC int (KCALL _posix_memalign_d)(void **__restrict pp, size_t alignment, size_t n_bytes, DEBUGINFO_UNUSED) { return (posix_memalign)(pp,alignment,n_bytes); }
PUBLIC void *(KCALL _memdup_d)(void const *__restrict ptr, size_t n_bytes, DEBUGINFO_UNUSED) { return (memdup)(ptr,n_bytes); }
PUBLIC void *(KCALL memdup)(void const *__restrict ptr, size_t n_bytes) {
void *result = KMALLOC(n_bytes,__GFP_MALLOC);
if (result) memcpy(result,ptr,n_bytes);
return result;
}
PUBLIC int (KCALL posix_memalign)(void **__restrict pp,
size_t alignment,
size_t n_bytes) {
void *result = NULL;
CHECK_HOST_DOBJ(pp);
if (alignment == HEAP_ALIGNMENT)
result = KMEMALIGN(alignment,n_bytes,__GFP_MALLOC);
else {
size_t d = alignment / sizeof(void*);
size_t r = alignment % sizeof(void*);
if (r != 0 || d == 0 || (d & (d-1)) != 0)
return EINVAL;
result = KMEMALIGN(alignment,n_bytes,__GFP_MALLOC);
}
if (!result) return ENOMEM;
*pp = result;
return 0;
}
#ifdef CONFIG_HAVE_STRDUP_IN_KERNEL
PUBLIC char *(KCALL _strdup_d)(char const *__restrict str, DEBUGINFO_UNUSED) { return (strdup)(str); }
PUBLIC char *(KCALL _strndup_d)(char const *__restrict str, size_t max_chars, DEBUGINFO_UNUSED) { return (strndup)(str,max_chars); }
PUBLIC char *(ATTR_CDECL _strdupf_d)(DEBUGINFO_UNUSED, char const *__restrict format, ...) { char *result; va_list args; va_start(args,format); result = (vstrdupf)(format,args); va_end(args); return result; }
PUBLIC char *(KCALL _vstrdupf_d)(char const *__restrict format, va_list args, DEBUGINFO_UNUSED) { return (vstrdupf)(format,args); }
PUBLIC void *(KCALL _memcdup_d)(void const *__restrict ptr, int needle, size_t n_bytes, DEBUGINFO_UNUSED) { return (memcdup)(ptr,needle,n_bytes); }
/* Additional mall functions that require longer code. */
PUBLIC char *(KCALL strdup)(char const *__restrict str) {
char *result; size_t len = strlen(str)+1;
result = (char *)KMALLOC(len*sizeof(char),__GFP_MALLOC);
if (result) memcpy(result,str,len*sizeof(char));
return result;
}
PUBLIC char *(KCALL strndup)(char const *__restrict str, size_t max_chars) {
char *result;
max_chars = strnlen(str,max_chars);
result = (char *)KMALLOC((max_chars+1)*sizeof(char),__GFP_MALLOC);
if (result) {
memcpy(result,str,max_chars*sizeof(char));
result[max_chars] = '\0';
}
return result;
}
PUBLIC void *(KCALL memcdup)(void const *__restrict ptr,
int needle, size_t n_bytes) {
if (n_bytes) {
void const *endaddr = memchr(ptr,needle,n_bytes-1);
if (endaddr) n_bytes = ((uintptr_t)endaddr-(uintptr_t)ptr)+1;
}
return memdup(ptr,n_bytes);
}
struct strdup_formatdata { char *start,*iter,*end; };
static NONNULL((1,3)) ssize_t
(KCALL strdupf_printer)(char const *__restrict data, size_t datalen,
struct strdup_formatdata *__restrict fmt) {
char *newiter;
newiter = fmt->iter+datalen;
if (newiter > fmt->end) {
size_t newsize = (size_t)(fmt->end-fmt->start);
assert(newsize);
do newsize *= 2;
while (fmt->start+newsize < newiter);
/* Realloc the strdup string */
newiter = (char *)KREALLOC(fmt->start,
(newsize+1)*sizeof(char),
__GFP_MALLOC);
if unlikely(!newiter) {
/* If there isn't enough memory, retry
* with a smaller buffer before giving up. */
newsize = (fmt->end-fmt->start)+datalen;
newiter = (char *)KREALLOC(fmt->start,
(newsize+1)*sizeof(char),
__GFP_MALLOC);
if unlikely(!newiter) return -1; /* Nothing we can do (out of memory...) */
}
fmt->iter = newiter+(fmt->iter-fmt->start);
fmt->start = newiter;
fmt->end = newiter+newsize;
}
memcpy(fmt->iter,data,datalen);
fmt->iter += datalen;
return datalen;
}
PUBLIC char *(KCALL vstrdupf)(char const *__restrict format, va_list args) {
struct strdup_formatdata data;
/* Try to do a (admittedly very bad) prediction on the required size. */
size_t format_length = (strlen(format)*3)/2;
data.start = (char *)KMALLOC((format_length+1)*sizeof(char),__GFP_MALLOC);
if unlikely(!data.start) {
/* Failed to allocate initial buffer (try with a smaller one) */
format_length = 1;
data.start = (char *)KMALLOC(2*sizeof(char),__GFP_MALLOC);
if unlikely(!data.start) return NULL;
}
data.end = data.start+format_length;
data.iter = data.start;
if unlikely(format_vprintf((pformatprinter)&strdupf_printer,
&data,format,args) != 0) {
free(data.start); /* Out-of-memory */
return NULL;
}
*data.iter = '\0';
if likely(data.iter != data.end) {
/* Try to realloc the string one last time to save up on memory */
data.end = (char *)KREALLOC(data.start,
((data.iter-data.start)+1)*sizeof(char),
__GFP_MALLOC);
if likely(data.end) data.start = data.end;
}
return data.start;
}
PUBLIC char *(ATTR_CDECL strdupf)(char const *__restrict format, ...) {
char *result;
va_list args;
va_start(args,format);
result = vstrdupf(format,args);
va_end(args);
return result;
}
#endif /* CONFIG_HAVE_STRDUP_IN_KERNEL */
#else /* !MALLOC_DEBUG_API */
PRIVATE void *(KCALL debug_malloc)(struct dsetup *__restrict setup, size_t size, gfp_t flags);
PRIVATE void *(KCALL debug_realloc)(struct dsetup *__restrict setup, void *ptr, size_t size, gfp_t flags);
PRIVATE void *(KCALL debug_memalign)(struct dsetup *__restrict setup, size_t alignment, size_t size, gfp_t flags);
PRIVATE void *(KCALL debug_realign)(struct dsetup *__restrict setup, void *ptr, size_t alignment, size_t size, gfp_t flags);
PRIVATE void (KCALL debug_free)(struct dsetup *__restrict setup, void *ptr, gfp_t flags);
PRIVATE size_t (KCALL debug_malloc_usable_size)(struct dsetup *__restrict setup, void *ptr);
PRIVATE gfp_t (KCALL debug_malloc_flags)(struct dsetup *__restrict setup, void *ptr);
PRIVATE void *(KCALL debug_memdup)(struct dsetup *__restrict setup, void const *__restrict ptr, size_t size, gfp_t flags);
PRIVATE int (KCALL debug_mallopt)(struct dsetup *__restrict setup, int parameter_number, int parameter_value, gfp_t flags);
PRIVATE int (KCALL debug_posix_memalign)(struct dsetup *__restrict setup, void **__restrict pp, size_t alignment, size_t n_bytes, gfp_t flags);
PRIVATE void *(KCALL debug_getattrib)(struct dsetup *__restrict setup, void *mallptr, int attrib);
PRIVATE ssize_t (KCALL debug_traceback)(struct dsetup *__restrict setup, void *mallptr, __ptbwalker callback, void *closure);
PRIVATE ssize_t (KCALL debug_enum)(struct dsetup *__restrict setup, struct instance *inst, void *checkpoint, ssize_t (KCALL *callback)(void *__restrict mallptr, void *closure), void *closure);
PRIVATE void (KCALL debug_printleaks)(struct dsetup *__restrict setup, struct instance *inst);
PRIVATE void (KCALL debug_validate)(struct dsetup *__restrict setup, struct instance *inst);
PRIVATE void *(KCALL debug_setflag)(struct dsetup *__restrict setup, void *mallptr, u8 flags);
#ifdef CONFIG_HAVE_STRDUP_IN_KERNEL
PRIVATE void *(KCALL debug_memcdup)(struct dsetup *__restrict setup, void const *__restrict ptr, int needle, size_t size, gfp_t flags);
PRIVATE char *(KCALL debug_strdup)(struct dsetup *__restrict setup, char const *__restrict str, gfp_t flags);
PRIVATE char *(KCALL debug_strndup)(struct dsetup *__restrict setup, char const *__restrict str, size_t max_chars, gfp_t flags);
PRIVATE char *(KCALL debug_vstrdupf)(struct dsetup *__restrict setup, char const *__restrict format, va_list args, gfp_t flags);
#endif /* CONFIG_HAVE_STRDUP_IN_KERNEL */
#ifdef CONFIG_TRACE_LEAKS
/* Called for all tracked pointers when a driver is unloaded.
* >> Using this, all pointers not previously tagged with `_mall_untrack()' or
* `_mall_nofree()' will be inherited by the kernel, as well as printed as leaks. */
INTDEF SAFE void (KCALL debug_add2core)(struct instance *__restrict inst);
#endif
#ifdef CONFIG_MALLOC_FREQUENCY
#if CONFIG_MALLOC_FREQUENCY > 0xffff || 1
typedef u32 mfreq_t;
#elif CONFIG_MALLOC_FREQUENCY > 0xff
typedef u16 mfreq_t;
#else
typedef u8 mfreq_t;
#endif
PRIVATE ATOMIC_DATA mfreq_t mall_check = CONFIG_MALLOC_FREQUENCY; /*< Next time MALL is checked for inconsistencies. */
PRIVATE ATOMIC_DATA mfreq_t mall_checkfreq = CONFIG_MALLOC_FREQUENCY; /*< MALL consistency check frequency. */
PRIVATE ATTR_COLDTEXT void KCALL
mall_onfreq(struct dsetup *__restrict setup) {
#if 0
syslog(LOG_MEM|LOG_DEBUG,"[MEM] Performing periodic memory validation\n");
#endif
debug_validate(setup,NULL);
}
#define MALL_FREQ(setup,flags) \
do{ mfreq_t freq; \
if (flags&GFP_NOFREQ) break; \
do freq = ATOMIC_READ(mall_check); \
while (!ATOMIC_CMPXCH_WEAK(mall_check,freq, \
freq ? freq-1 : ATOMIC_READ(mall_checkfreq))); \
if unlikely(!freq) mall_onfreq(setup); \
}while(0)
#else
#define MALL_FREQ(setup,flags) do{}while(0)
#endif
#if 1
#define MALL_FREQ_AFTER(setup,flags) \
MALL_FREQ(setup,flags)
#else
#define MALL_FREQ_AFTER(setup,flags) do{}while(0)
#endif
PRIVATE void *(KCALL debug_malloc)(struct dsetup *__restrict setup,
size_t size, gfp_t flags) {
struct mptr *p;
MALL_FREQ(setup,flags);
p = MPTR_KMALLOC(size,flags);
if (p != MPTR_OF(NULL)) mptr_setup(p,setup,size);
MALL_FREQ_AFTER(setup,flags);
return MPTR_USERADDR(p);
}
PRIVATE void *(KCALL debug_memalign)(struct dsetup *__restrict setup,
size_t alignment, size_t size, gfp_t flags) {
struct mptr *p;
MALL_FREQ(setup,flags);
p = MPTR_KMEMALIGN(alignment,size,flags);
if (p != MPTR_OF(NULL)) mptr_setup(p,setup,size);
MALL_FREQ_AFTER(setup,flags);
return MPTR_USERADDR(p);
}
PRIVATE void *(KCALL debug_realloc)(struct dsetup *__restrict setup,
void *ptr, size_t size, gfp_t flags) {
struct mptr *p;
MALL_FREQ(setup,flags);
if (M_ISNONNULL(ptr))
p = MPTR_KREALLOC(MPTR_GET(ptr),size,flags);
else {
if ((p = MPTR_KMALLOC(size,flags)) != MPTR_OF(NULL))
mptr_setup(p,setup,size);
}
MALL_FREQ_AFTER(setup,flags);
return MPTR_USERADDR(p);
}
PRIVATE void *(KCALL debug_realign)(struct dsetup *__restrict setup,
void *ptr, size_t alignment,
size_t size, gfp_t flags) {
struct mptr *p;
MALL_FREQ(setup,flags);
if (M_ISNONNULL(ptr))
p = MPTR_KREALIGN(MPTR_GET(ptr),alignment,size,flags);
else {
if ((p = MPTR_KMEMALIGN(alignment,size,flags)) != MPTR_OF(NULL))
mptr_setup(p,setup,size);
}
MALL_FREQ_AFTER(setup,flags);
return MPTR_USERADDR(p);
}
PRIVATE void (KCALL debug_free)(struct dsetup *__restrict setup, void *ptr, gfp_t flags) {
if (M_ISNONNULL(ptr)) {
struct mptr *p;
MALL_FREQ(setup,flags);
p = MPTR_GET(ptr);
mptr_unlink(setup,p);
MPTR_KFFREE(p,flags);
MALL_FREQ_AFTER(setup,flags);
}
}
PRIVATE size_t (KCALL debug_malloc_usable_size)(struct dsetup *__restrict setup, void *ptr) { return KMALLOC_USABLE_SIZE(ptr); }
PRIVATE gfp_t (KCALL debug_malloc_flags)(struct dsetup *__restrict setup, void *ptr) { return KMALLOC_FLAGS(ptr); }
PRIVATE void *(KCALL debug_memdup)(struct dsetup *__restrict setup,
void const *__restrict ptr, size_t size,
gfp_t flags) {
void *result = debug_malloc(setup,size,flags);
if (result) memcpy(result,ptr,size);
return result;
}
PRIVATE void *(KCALL debug_memadup)(struct dsetup *__restrict setup,
void const *__restrict ptr,
size_t alignment, size_t size,
gfp_t flags) {
void *result = debug_memalign(setup,alignment,size,flags);
if (result) memcpy(result,ptr,size);
return result;
}
PRIVATE int (KCALL debug_mallopt)(struct dsetup *__restrict setup,
int parameter_number, int parameter_value,
gfp_t flags) {
(void)setup;
#ifdef CONFIG_MALLOC_FREQUENCY
if (parameter_number == M_MALL_CHECK_FREQUENCY) {
int result;
if (--parameter_value < 0) parameter_value = (int)-1;
result = (int)ATOMIC_XCH(mall_checkfreq,(u32)parameter_value);
ATOMIC_WRITE(mall_check,(u32)parameter_value);
if (result >= 0) ++result;
return result;
}
#endif
return core_mallopt(parameter_number,parameter_value,flags);
}
PRIVATE int (KCALL debug_posix_memalign)(struct dsetup *__restrict setup,
void **__restrict pp, size_t alignment,
size_t n_bytes, gfp_t flags) {
void *result = NULL;
CHECK_HOST_DOBJ(pp);
if (alignment == HEAP_ALIGNMENT)
result = debug_memalign(setup,alignment,n_bytes,flags);
else {
size_t d = alignment / sizeof(void*);
size_t r = alignment % sizeof(void*);
if (r != 0 || d == 0 || (d & (d-1)) != 0)
return EINVAL;
result = debug_memalign(setup,alignment,n_bytes,flags);
}
if (!result) return ENOMEM;
*pp = result;
return 0;
}
#ifdef CONFIG_HAVE_STRDUP_IN_KERNEL
PRIVATE void *(KCALL debug_memcdup)(struct dsetup *__restrict setup,
void const *__restrict ptr, int needle,
size_t size, gfp_t flags) {
if (size) {
void const *endaddr = memchr(ptr,needle,size-1);
if (endaddr) size = ((uintptr_t)endaddr-(uintptr_t)ptr)+1;
}
return debug_memdup(setup,ptr,size,flags);
}
PRIVATE char *(KCALL debug_strdup)(struct dsetup *__restrict setup,
char const *__restrict str, gfp_t flags) {
size_t size = (strlen(str)+1)*sizeof(char);
void *result = debug_malloc(setup,size,flags);
if (result) memcpy(result,str,size);
return (char *)result;
}
PRIVATE char *(KCALL debug_strndup)(struct dsetup *__restrict setup,
char const *__restrict str,
size_t max_chars, gfp_t flags) {
size_t size = strnlen(str,max_chars);
char *result = (char *)debug_malloc(setup,(size+1)*sizeof(char),flags);
if (result) memcpy(result,str,size*sizeof(char)),
result[size] = '\0';
return result;
}
PRIVATE char *(KCALL debug_vstrdupf)(struct dsetup *__restrict setup,
char const *__restrict format,
va_list args, gfp_t flags) {
/* Minimal implementation (Not meant for speed) */
va_list args_copy; size_t result_size; char *result;
va_copy(args_copy,args);
result_size = (vsnprintf(NULL,0,format,args_copy)+1)*sizeof(char);
va_end(args_copy);
result = (char *)debug_malloc(setup,result_size,flags);
if (result) vsnprintf(result,result_size,format,args);
return result;
}
#endif /* CONFIG_HAVE_STRDUP_IN_KERNEL */
PRIVATE SAFE struct mptr *KCALL
mptr_safeload(struct dsetup *__restrict setup,
void *__restrict p) {
ATTR_UNUSED size_t i;
struct mptr *head;
struct mman *m;
#ifdef MPTR_HAVE_TAIL
struct mptr_tail *tail;
#endif
assert(TASK_ISSAFE());
CHECK_HOST_DOBJ(setup);
head = MPTR_OF(p);
/* Validate generic constraints. */
if (!IS_ALIGNED((uintptr_t)head,HEAP_ALIGNMENT) ||
!OK_HOST_DATA(head,sizeof(struct mptr)))
goto invptr;
/* Check if the given pointer is already apart of a free heap. */
if (addr_isglob(head)) {
bool is_mapped,is_free = false;
TASK_PDIR_KERNEL_BEGIN(m);
is_mapped = mman_inuse(&mman_kernel,
(ppage_t)FLOOR_ALIGN((uintptr_t)head,PAGESIZE),
PAGESIZE);
if (is_mapped) is_free = (mheap_isfree_l(&mheaps[GFP_KERNEL],head) ||
mheap_isfree_l(&mheaps[GFP_KERNEL|GFP_LOCKED],head));
TASK_PDIR_KERNEL_END(m);
if (!is_mapped) goto invptr;
if (is_free) goto freeptr;
if (mheap_isfree_l(&mheaps[GFP_SHARED],head)) goto freeptr;
if (mheap_isfree_l(&mheaps[GFP_SHARED|GFP_LOCKED],head)) goto freeptr;
} else {
if (!PDIR_ISKPD()) goto invptr;
if (page_query(head,1) & PAGEATTR_FREE) goto freeptr;
if (mheap_isfree_l(&mheaps[GFP_MEMORY],head)) goto freeptr;
}
if (MPTR_TYPE(head) >= __GFP_HEAPCOUNT) malloc_panic(setup,NULL,"Invalid heap id #%d at %p, offset %Id in %p",MPTR_TYPE(head),&head->m_type,(intptr_t)&head->m_type-(intptr_t)p,p);
if (MPTR_SIZE(head) < MPTR_SIZEOF(0)) malloc_panic(setup,NULL,"Invalid pointer size %Iu < %Iu at %p, offset %Id in %p",MPTR_SIZE(head),MPTR_SIZEOF(0),&head->m_size,(intptr_t)&head->m_size-(intptr_t)p,p);
if (!ATOMIC_READ(head->m_refcnt)) malloc_panic(setup,NULL,"Invalid reference counter 0 at %p, offset %Id in %p",&head->m_refcnt,(intptr_t)&head->m_refcnt-(intptr_t)p,p);
#ifdef MPTR_HAVE_TAIL
if ((void *)(tail = head->m_tail) < p) malloc_panic(setup,NULL,"Invalid tail address %p < %p at %p, offset %Id in %p",tail,p,&head->m_tail,(intptr_t)&head->m_tail-(intptr_t)p,p);
if (MPTR_TAILSIZE(head) < MPTR_MINTAILSIZE) malloc_panic(setup,NULL,"Tail %p of %p is too small (%Iu < %Iu) in %p",tail,head,(size_t)MPTR_TAILSIZE(head),(size_t)MPTR_MINTAILSIZE,p);
#endif
#ifdef CONFIG_MALLOC_HEADSIZE
/* Validate header bytes */
i = CONFIG_MALLOC_HEADSIZE; while (i--) {
if (head->m_head[i] != MALL_HEADERBYTE(i)) {
malloc_panic(setup,head,"Header corruption (%#.2I8x != %#.2I8x) at %p of %p (at offset %Id; header index %d)\n"
"%$[hex]",
head->m_head[i],MALL_HEADERBYTE(i),&head->m_head[i],p,
(intptr_t)&head->m_head[i]-(intptr_t)p,i,
CONFIG_MALLOC_HEADSIZE,head->m_head);
}
}
#endif
#ifdef CONFIG_MALLOC_FOOTSIZE
/* Validate footer bytes */
for (i = 0; i < CONFIG_MALLOC_FOOTSIZE; ++i) {
if (tail->t_foot[i] != MALL_FOOTERBYTE(i)) {
malloc_panic(setup,head,"Footer corruption (%#.2I8x != %#.2I8x) at %p of %p (at offset %Id; footer index %d)\n"
"%$[hex]",
tail->t_foot[i],MALL_FOOTERBYTE(i),&tail->t_foot[i],p,
(intptr_t)&tail->t_foot[i]-(intptr_t)p,i,
CONFIG_MALLOC_FOOTSIZE,tail->t_foot);
}
}
#endif
#ifdef CONFIG_TRACE_LEAKS
{ u16 chksum = mptr_chksum(head);
if (chksum != head->m_chksum) {
malloc_panic(setup,head,"Invalid checksum (expected %I32x, got %I32x) at %p, offset %Id in %p",
chksum,head->m_chksum,&head->m_chksum,
(intptr_t)&head->m_chksum-(intptr_t)p,p);
}
}
{
REF struct instance *inst;
/* Validate mall linkage */
atomic_rwlock_read(&mptr_inst_lock);
inst = head->m_info.i_inst;
if (!OK_HOST_DATA(inst,sizeof(struct instance)) ||
!OK_HOST_DATA(inst->i_module,sizeof(struct module)) ||
!INSTANCE_INKERNEL(inst)) {
atomic_rwlock_endread(&mptr_inst_lock);
malloc_panic(setup,head,"Invalid associated instance %p at %p, offset %Id in %p",
inst,&head->m_info.i_inst,(intptr_t)&head->m_info.i_inst-(intptr_t)p,p);
}
if (!INSTANCE_TRYINCREF(inst)) inst = NULL;
atomic_rwlock_endread(&mptr_inst_lock);
if (inst) {
if (atomic_rwlock_tryread(&inst->i_driver.k_tlock)) {
if (head->m_flag&~MPTRFLAG_MASK) {
malloc_panic(setup,head,"Unknown flags %#.4I16x at %p, offset %Id in %p",
head->m_flag,&head->m_flag,(intptr_t)&head->m_flag-(intptr_t)p,p);
}
if (!(head->m_flag&MPTRFLAG_UNTRACKED)) {
struct mptr *linked_self;
struct mman *old_mm = NULL;
if (addr_ispriv(head->m_chain.le_pself))
TASK_PDIR_KERNEL_BEGIN(old_mm);
if (!OK_HOST_DATA(head->m_chain.le_pself,sizeof(void *))) {
malloc_panic(setup,head,"Broken chain self-pointer (%p at &p, offset %Id) in %p",
head->m_chain.le_pself,&head->m_chain.le_pself,
(intptr_t)&head->m_chain.le_pself-(intptr_t)p,p);
}
linked_self = *head->m_chain.le_pself;
if (head != linked_self) {
malloc_panic(setup,head,"Incorrect self-pointer (expected %p, got %p in at %p at offset %Id) in %p",
head,linked_self,head->m_chain.le_pself,
(intptr_t)&head->m_chain.le_pself-(intptr_t)p,p);
}
if (head->m_chain.le_next != KINSTANCE_TRACE_NULL) {
struct mptr *next = head->m_chain.le_next;
if (!old_mm && addr_ispriv(next)) TASK_PDIR_KERNEL_BEGIN(old_mm);
if (!OK_HOST_DATA(next,sizeof(struct mptr))) {
malloc_panic(setup,head,"Broken chain next-pointer (%p at %p, offset %Id) in %p",
next,&head->m_chain.le_next,
(intptr_t)&head->m_chain.le_next-(intptr_t)p,p);
}
if (&head->m_chain.le_next != next->m_chain.le_pself) {
malloc_panic(setup,head,"Broken chain next-self-pointer (expected %p, got %p) following %p",
&head->m_chain.le_next,next->m_chain.le_pself,p);
}
}
if (old_mm) TASK_PDIR_KERNEL_END(old_mm);
}
atomic_rwlock_endread(&inst->i_driver.k_tlock);
}
INSTANCE_DECREF(inst);
}
}
#endif
return head;
invptr: malloc_panic(setup,NULL,"Faulty malloc-pointer %p",p);
freeptr: malloc_panic(setup,NULL,"malloc-pointer %p has already been freed",p);
}
PRIVATE void KCALL
mptr_setup(struct mptr *__restrict self,
struct dsetup *__restrict setup,
size_t user_size) {
CHECK_HOST_DOBJ(self);
CHECK_HOST_DOBJ(setup);
MPTR_VALIDATE(self);
assert(MPTR_SIZEOF(user_size) <= MPTR_SIZE(self));
(void)user_size;
#ifdef CONFIG_TRACE_LEAKS
self->m_refcnt = 1;
self->m_flag = MPTRFLAG_NONE;
self->m_line = (s32)setup->s_info.i_line;
self->m_info.i_file = setup->s_info.i_file;
self->m_info.i_func = setup->s_info.i_func;
self->m_info.i_inst = setup->s_info.i_inst;
#endif /* !CONFIG_TRACE_LEAKS */
#ifdef MPTR_HAVE_PAD
memset(self->m_pad,0xaa,sizeof(self->m_pad));
#endif
#ifdef CONFIG_MALLOC_HEADSIZE
{ size_t i;
for (i = 0; i < CONFIG_MALLOC_HEADSIZE; ++i)
self->m_head[i] = MALL_HEADERBYTE(i);
}
#endif
/* Initialize the tail. */
#ifdef MPTR_HAVE_TAIL
{ struct mptr_tail *tail; size_t tail_size;
tail = (struct mptr_tail *)((uintptr_t)MPTR_USERADDR(self)+user_size);
tail_size = ((uintptr_t)self+MPTR_SIZE(self))-(uintptr_t)tail;
#if defined(CONFIG_MALLOC_FOOTSIZE) && defined(CONFIG_MALLOC_TRACEBACK)
assertf(tail_size >= CONFIG_MALLOC_FOOTSIZE+CONFIG_MALLOC_TRACEBACK_MINSIZE*sizeof(void *),"%Iu",tail_size);
#elif defined(CONFIG_MALLOC_FOOTSIZE)
assertf(tail_size >= CONFIG_MALLOC_FOOTSIZE,"%Iu",tail_size);
#else
assertf(tail_size >= CONFIG_MALLOC_TRACEBACK_MINSIZE*sizeof(void *),"%Iu",tail_size);
#endif
#ifdef CONFIG_MALLOC_FOOTSIZE
{ size_t i;
for (i = 0; i < CONFIG_MALLOC_FOOTSIZE; ++i)
tail->t_foot[i] = MALL_FOOTERBYTE(i);
}
#ifdef CONFIG_MALLOC_TRACEBACK
tail_size -= CONFIG_MALLOC_FOOTSIZE;
#endif
#endif
#ifdef CONFIG_MALLOC_TRACEBACK
{ void **iter; size_t tail_overflow;
assert(tail_size >= CONFIG_MALLOC_TRACEBACK_MINSIZE*sizeof(void *));
iter = tail->t_tb;
tail_overflow = tail_size % sizeof(void *);
tail_size /= sizeof(void *);
/* Fill the traceback portion. */
#if defined(__i386__) || defined(__x86_64__)
if (tail_size) {
register uintptr_t temp;
/* Implement in assembly to take advantage of local interrupt handlers.
* >> If a pagefault occurrs while accessing a frame pointer, stop creation
* of the traceback (it is either corrupted, was customized, or has terminated) */
__asm__ __volatile__(/* BEGIN_EXCEPTION_HANDLER(EXC_PAGE_FAULT) */
L( ipushx_sym(%[temp],3f) )
L( pushx $(EXC_PAGE_FAULT) )
L( pushx TASK_OFFSETOF_IC(%[task]) )
L( movx %%xsp, TASK_OFFSETOF_IC(%[task]) )
L( )
L(1: testx %[frame], %[frame] /* >> if (!frame) break; */ )
L( jz 2f )
L( movx XSZ(%[frame]), %[temp] /* >> *iter++ = frame->f_return; */)
L( movx %[temp], 0(%[iter]) )
L( addx $(XSZ), %[iter] )
L( subx $1, %[size] /* >> if (!--size) break; */ )
L( jz 2f )
L( movx 0(%[frame]), %[frame] /* >> frame = frame->f_return; */)
L( jmp 1b /* >> continue; */ )
/* END_EXCEPTION_HANDLER(EXC_PAGE_FAULT) */
L(2: popx TASK_OFFSETOF_IC(%[task]) )
L( addx $(2*XSZ), %%xsp )
L(3: /* This is where execution jumps when something went wrong. */)
: [iter] "+D" (iter)
, [size] "+c" (tail_size)
, [temp] "=a" (temp)
: [frame] "S" (setup->s_tbebp) /* struct frame */
, [task] "d" (THIS_TASK)
: "memory", "cc");
}
#else
#warning "FIXME: No local exception handler used for tracebacks."
/* TODO: Use `call_user_worker' */
{ struct frame { struct frame *f_caller; void *f_return; };
struct frame *frame = (struct frame *)setup->s_tbebp;
for (; tail_size; --tail_size, ++iter) {
if (!frame) break;
if (!OK_HOST_DATA(frame,sizeof(struct frame))) break;
*iter = frame->f_return;
frame = frame->f_caller;
}
}
#endif
/* XXX: Free unused trailing data? */
/* Fill the remainder with EOF entries. */
while (tail_size--) *iter++ = MPTR_TAIL_TB_EOF;
/* Final trailing bytes. */
while (tail_overflow--) *(*(byte_t **)&iter)++ = (byte_t)((uintptr_t)MPTR_TAIL_TB_EOF & 0xff);
}
#endif
self->m_tail = tail;
}
#endif
#ifdef CONFIG_TRACE_LEAKS
self->m_chksum = mptr_chksum(self);
/* Link the pointer for the first time. */
{ struct instance *inst = setup->s_info.i_inst;
struct mman *old_mm = NULL;
assert(inst);
assert(inst->i_module);
atomic_rwlock_write(&inst->i_driver.k_tlock);
if (addr_ispriv(inst->i_driver.k_trace) &&
inst->i_driver.k_trace != KINSTANCE_TRACE_NULL)
TASK_PDIR_KERNEL_BEGIN(old_mm);
LIST_INSERT_EX(inst->i_driver.k_trace,self,m_chain,
KINSTANCE_TRACE_NULL);
if (old_mm) TASK_PDIR_KERNEL_END(old_mm);
atomic_rwlock_endwrite(&inst->i_driver.k_tlock);
}
#endif
}
#ifdef CONFIG_TRACE_LEAKS
LOCAL u16 KCALL
gen_chksum(byte_t const *__restrict iter,
size_t n_bytes, u16 sum) {
while (n_bytes--) sum = (sum*9)+*iter++;
return sum;
}
PRIVATE u16 KCALL
mptr_chksum(struct mptr *__restrict self) {
#ifdef MPTR_HAVE_TAIL
struct mptr_tail *tail = self->m_tail;
#endif
u16 result = 0xc13f;
result = gen_chksum((byte_t *)&self->m_flag,
offsetafter(struct mptr,m_size)-
offsetof(struct mptr,m_flag),result);
#ifdef CONFIG_MALLOC_TRACEBACK
result = gen_chksum((byte_t *)&tail->t_tb[0],
MPTR_TAILSIZE(self)
#ifdef CONFIG_MALLOC_FOOTSIZE
-CONFIG_MALLOC_FOOTSIZE
#endif
,result);
#endif /* CONFIG_MALLOC_TRACEBACK */
result ^= (uintptr_t)self & 0xffff;
result ^= (uintptr_t)self >> 16;
#ifdef MPTR_HAVE_TAIL
result ^= (uintptr_t)tail & 0xffff;
result ^= (uintptr_t)tail >> 16;
#endif
return result;
}
#endif /* CONFIG_TRACE_LEAKS */
#ifdef MPTR_HAVE_TAIL
PRIVATE void KCALL
mptr_mvtail(struct mptr *__restrict self,
size_t old_size, size_t old_user_size,
size_t new_size, size_t new_user_size,
gfp_t flags) {
void *old_tail,*new_tail;
size_t tail_size,tail_unused;
CHECK_HOST_DOBJ(self);
assert(MPTR_SIZE(self) == new_size);
assert(new_size >= MPTR_SIZEOF(0));
assert(IS_ALIGNED(old_size,HEAP_ALIGNMENT));
assert(IS_ALIGNED(new_size,HEAP_ALIGNMENT));
assert(old_user_size <= old_size);
assert(new_user_size <= new_size);
old_tail = self->m_tail;
new_tail = (void *)(((uintptr_t)old_tail-old_user_size)+new_user_size);
tail_size = ((uintptr_t)self+old_size)-(uintptr_t)old_tail;
assert(((uintptr_t)self+old_size) >= (uintptr_t)old_tail);
{
uintptr_t new_end = (uintptr_t)self+new_size;
uintptr_t new_tail_end = (uintptr_t)new_tail+tail_size;
if (new_end >= new_tail_end)
tail_unused = new_end-new_tail_end;
else {
/* Truncate the tail. */
assert(tail_size >= (new_tail_end-new_end));
tail_size -= (new_tail_end-new_end);
tail_unused = 0;
}
}
assert((uintptr_t)self+new_size >= (uintptr_t)new_tail+tail_size);
#if 0
syslog(LOG_DEBUG,"MOVE_TAIL %Iu(%Iu) -> %Iu(%Iu) (%p -> %p)\n",
old_size-MPTR_SIZEOF(0),old_user_size-MPTR_SIZEOF(0),
new_size-MPTR_SIZEOF(0),new_user_size-MPTR_SIZEOF(0),
old_tail,new_tail);
#endif
assertf(tail_size < new_size,
"old_tail = %p\n"
"tail_size = %Iu\n"
"old_size = %Iu\n"
"new_size = %Iu\n"
"old_user_size = %Iu\n"
"new_user_size = %Iu\n",
old_tail,tail_size,old_size,new_size,
old_user_size,new_user_size);
self->m_tail = (struct mptr_tail *)new_tail;
memmove(new_tail,old_tail,tail_size);
(void)tail_unused;
#ifdef CONFIG_MALLOC_TRACEBACK
memset((void *)((uintptr_t)new_tail+tail_size),
(byte_t)((uintptr_t)MPTR_TAIL_TB_EOF & 0xff),
tail_unused);
#endif
#ifdef CONFIG_TRACE_LEAKS
/* Update the associated checksum. */
self->m_chksum = mptr_chksum(self);
#endif /* CONFIG_TRACE_LEAKS */
if (old_size > new_size) {
size_t release_size = old_size-new_size;
void *release_addr = (void *)((uintptr_t)self+new_size);
#ifdef CONFIG_MALLOC_DEBUG_INIT
if (flags&GFP_CALLOC)
memset(release_addr,0,release_size);
else MEMPATX(release_addr,CONFIG_MALLOC_DEBUG_INIT,release_size);
#else
if (flags&GFP_CALLOC)
memset(release_addr,0,release_size);
#endif
}
}
#endif /* MPTR_HAVE_TAIL */
#ifdef CONFIG_TRACE_LEAKS
PRIVATE void KCALL
mptr_unlink(struct dsetup *setup,
struct mptr *__restrict self) {
struct instance *inst;
CHECK_HOST_DOBJ(self);
atomic_rwlock_read(&mptr_inst_lock);
inst = self->m_info.i_inst;
atomic_rwlock_write(&inst->i_driver.k_tlock);
if (self->m_flag&MPTRFLAG_NOFREE) {
malloc_panic(setup,self,
"Cannot realloc/free pointer %p (%p...%p / %p...%p) marked as NOFREE",
self,MPTR_USERADDR(self),(uintptr_t)MPTR_USERADDR(self)+MPTR_USERSIZE(self),
self,(uintptr_t)self+MPTR_SIZE(self));
}
if (!(self->m_flag&MPTRFLAG_UNTRACKED)) {
struct mman *old_mm = NULL;
if (addr_ispriv(self->m_chain.le_pself) ||
(self->m_chain.le_next != KINSTANCE_TRACE_NULL &&
addr_ispriv(self->m_chain.le_next)))
TASK_PDIR_KERNEL_BEGIN(old_mm);
LIST_REMOVE_EX(self,m_chain,KINSTANCE_TRACE_NULL);
if (old_mm) TASK_PDIR_KERNEL_END(old_mm);
}
atomic_rwlock_endwrite(&inst->i_driver.k_tlock);
atomic_rwlock_endread(&mptr_inst_lock);
}
PRIVATE void KCALL
mptr_relink(struct dsetup *setup,
struct mptr *__restrict self) {
struct instance *inst;
CHECK_HOST_DOBJ(self);
atomic_rwlock_read(&mptr_inst_lock);
inst = self->m_info.i_inst;
atomic_rwlock_write(&inst->i_driver.k_tlock);
if (!(self->m_flag&MPTRFLAG_UNTRACKED)) {
struct mman *old_mm = NULL;
if (addr_ispriv(inst->i_driver.k_trace) &&
inst->i_driver.k_trace != KINSTANCE_TRACE_NULL)
TASK_PDIR_KERNEL_BEGIN(old_mm);
LIST_INSERT_EX(inst->i_driver.k_trace,self,m_chain,KINSTANCE_TRACE_NULL);
if (old_mm) TASK_PDIR_KERNEL_END(old_mm);
}
atomic_rwlock_endwrite(&inst->i_driver.k_tlock);
atomic_rwlock_endread(&mptr_inst_lock);
}
#endif /* CONFIG_TRACE_LEAKS */
PRIVATE void *(KCALL debug_getattrib)(struct dsetup *__restrict setup,
void *mallptr, int attrib) {
struct mptr *p; void *result;
if unlikely(!mallptr) return NULL;
p = mptr_safeload(setup,mallptr);
switch (attrib) {
#ifdef CONFIG_TRACE_LEAKS
case __MALL_ATTRIB_FILE: result = (void *)MPTR_FILE(p); break;
case __MALL_ATTRIB_LINE: result = (void *)(intptr_t)MPTR_LINE(p); break;
case __MALL_ATTRIB_FUNC: result = (void *)MPTR_FUNC(p); break;
case __MALL_ATTRIB_INST:
atomic_rwlock_read(&mptr_inst_lock);
result = (void *)MPTR_INST(p);
if (!INSTANCE_TRYINCREF((struct instance *)result)) {
assertef(INSTANCE_INCREF(THIS_INSTANCE),"But we're the core...");
result = THIS_INSTANCE;
}
atomic_rwlock_endread(&mptr_inst_lock);
break;
#else
case __MALL_ATTRIB_LINE: result = (void *)(intptr_t)(int)-1; break;
case __MALL_ATTRIB_FILE:
case __MALL_ATTRIB_FUNC: result = (void *)"??" "?"; break;
case __MALL_ATTRIB_INST:
result = (void *)THIS_INSTANCE;
if (!INSTANCE_INCREF(result)) result = NULL;
break;
#endif
case __MALL_ATTRIB_SIZE: result = (void *)(uintptr_t)MPTR_USERSIZE(p); break;
default: result = NULL; break;
}
return result;
}
PRIVATE ssize_t (KCALL debug_traceback)(struct dsetup *__restrict setup,
void *mallptr, __ptbwalker callback,
void *closure) {
if unlikely(!mallptr) return 0;
(void)setup;
(void)callback;
(void)closure;
/* TODO */
return 0;
}
PRIVATE ssize_t (KCALL debug_enum)(struct dsetup *__restrict setup, struct instance *inst,
void *checkpoint, ssize_t (KCALL *callback)(void *__restrict mallptr,
void *closure),
void *closure) {
#ifdef CONFIG_TRACE_LEAKS
struct mptr *chain,**piter,*iter;
struct mptr *next,*checkpoint_ptr;
ssize_t temp,result = 0;
struct mman *old_mm = NULL;
if unlikely(!callback) return 0;
if (!inst) {
/* TODO: Validate all drivers + the core when `inst' is NULL. */
inst = THIS_INSTANCE;
}
checkpoint_ptr = checkpoint ? mptr_safeload(setup,checkpoint) : KINSTANCE_TRACE_NULL;
atomic_rwlock_write(&inst->i_driver.k_tlock);
/* Pop the chain of traced pointers from the instance. */
chain = inst->i_driver.k_trace;
inst->i_driver.k_trace = KINSTANCE_TRACE_NULL;
atomic_rwlock_endwrite(&inst->i_driver.k_tlock);
if unlikely(chain == KINSTANCE_TRACE_NULL) return 0;
TASK_PDIR_KERNEL_BEGIN(old_mm);
assert(chain->m_chain.le_pself == &inst->i_driver.k_trace);
chain->m_chain.le_pself = &chain;
iter = chain;
while (iter != KINSTANCE_TRACE_NULL) {
if (checkpoint_ptr == iter) break;
next = iter->m_chain.le_next;
assert(iter != next);
temp = (*callback)(MPTR_USERADDR(iter),closure);
if (temp < 0) { result = temp; break; }
result += temp;
iter = next;
}
atomic_rwlock_write(&inst->i_driver.k_tlock);
assert(chain->m_chain.le_pself == &chain);
/* Re-append the chain to the instance. */
piter = &inst->i_driver.k_trace;
while ((iter = *piter) != KINSTANCE_TRACE_NULL)
piter = &iter->m_chain.le_next;
*piter = chain;
chain->m_chain.le_pself = piter;
atomic_rwlock_endwrite(&inst->i_driver.k_tlock);
TASK_PDIR_KERNEL_END(old_mm);
return result;
#else
(void)setup;
(void)inst;
(void)checkpoint;
(void)callback;
(void)closure;
return 0;
#endif
}
#ifdef CONFIG_TRACE_LEAKS
#define F_PRINTF(...) \
do{ if ((temp = format_printf(printer,closure,__VA_ARGS__)) < 0) return temp; \
result += temp; \
}while(0)
PRIVATE ssize_t (KCALL mptr_printleak)(struct mptr *__restrict self,
pformatprinter printer, void *closure) {
ssize_t temp,result = 0;
F_PRINTF("##################################################\n"
"%s(%d) : %s : Leaked %Iu bytes at %p\n",
MPTR_FILE(self),MPTR_LINE(self),
MPTR_FUNC(self),MPTR_USERSIZE(self),
MPTR_USERADDR(self));
#ifdef CONFIG_MALLOC_TRACEBACK
{ void **iter,**end; size_t pos = 0;
end = (iter = MPTR_TRACEBACK_ADDR(self))+MPTR_TRACEBACK_SIZE(self);
for (; iter != end; ++iter,++pos) {
#ifdef CONFIG_USE_EXTERNAL_ADDR2LINE
F_PRINTF("#!$ addr2line(%p) '{file}({line}) : {func} : [%Ix] : %p'\n",
(uintptr_t)*iter-1,pos,*iter);
#else
F_PRINTF("%[vinfo] : [%Ix] : %p\n",
(uintptr_t)*iter-1,pos,*iter);
#endif
}
}
#endif
return result;
}
#undef F_PRINTF
INTERN SAFE void (KCALL debug_add2core)(struct instance *__restrict inst) {
struct mptr *chain,*chain_end;
struct mman *old_mm;
TASK_PDIR_KERNEL_BEGIN(old_mm);
atomic_rwlock_write(&mptr_inst_lock);
/* Extract all pointers from this instance. */
atomic_rwlock_write(&inst->i_driver.k_tlock);
chain = inst->i_driver.k_trace;
inst->i_driver.k_trace = KINSTANCE_TRACE_NULL;
atomic_rwlock_endwrite(&inst->i_driver.k_tlock);
/* At this point, nobody is really tracking the pointers from this instance.
* Note tough, that someone may be attempting to access one of its pointers
* right now, which is why we must keep on holding a lock to `mptr_inst_lock'
* in order to prevent them from doing anything... */
if (chain != KINSTANCE_TRACE_NULL) {
chain_end = chain;
for (;;) {
/* Update instance pointers. */
assert(chain_end->m_info.i_inst == inst);
chain_end->m_info.i_inst = THIS_INSTANCE;
/* Make sure to delete the file & function pointers.
* (they _were_ part of the module now unloaded, meaning they are now dangling) */
chain_end->m_info.i_file = NULL;
chain_end->m_info.i_func = NULL;
#ifdef CONFIG_TRACE_LEAKS
/* Update the associated checksum. */
chain_end->m_chksum = mptr_chksum(chain_end);
#endif /* CONFIG_TRACE_LEAKS */
assert(!(chain_end->m_flag&MPTRFLAG_UNTRACKED));
if (!(chain_end->m_flag&(MPTRFLAG_NOFREE|MPTRFLAG_GLOBAL))) {
mptr_printleak(chain_end,&syslog_printer,
SYSLOG_PRINTER_CLOSURE(LOG_MEM|LOG_DEBUG));
}
if (chain_end->m_chain.le_next == KINSTANCE_TRACE_NULL) break;
chain_end = chain_end->m_chain.le_next;
}
/* Re-insert all pointers into the core module, so-as to keep tracking them! */
atomic_rwlock_write(&THIS_INSTANCE->i_driver.k_tlock);
chain_end->m_chain.le_next = THIS_INSTANCE->i_driver.k_trace;
if (THIS_INSTANCE->i_driver.k_trace != KINSTANCE_TRACE_NULL)
THIS_INSTANCE->i_driver.k_trace->m_chain.le_pself = &chain_end->m_chain.le_next;
/* Update the chain heap pointer. */
THIS_INSTANCE->i_driver.k_trace = chain;
assert(chain->m_chain.le_pself == &inst->i_driver.k_trace);
chain->m_chain.le_pself = &THIS_INSTANCE->i_driver.k_trace;
atomic_rwlock_endwrite(&THIS_INSTANCE->i_driver.k_tlock);
}
atomic_rwlock_endwrite(&mptr_inst_lock);
TASK_PDIR_KERNEL_END(old_mm);
}
#endif
PRIVATE ssize_t KCALL
debug_printleaks_callback(void *__restrict mallptr,
void *closure) {
struct mptr *p = mptr_safeload((struct dsetup *)closure,mallptr);
#ifdef CONFIG_TRACE_LEAKS
if (p->m_flag&MPTRFLAG_NOFREE) return 0;
#endif
return mptr_printleak(p,&syslog_printer,
SYSLOG_PRINTER_CLOSURE(LOG_MEM|LOG_DEBUG));
}
PRIVATE ATTR_UNUSED ssize_t KCALL
debug_validate_callback(void *__restrict mallptr,
void *closure) {
mptr_safeload((struct dsetup *)closure,mallptr);
return 0;
}
PRIVATE void (KCALL debug_printleaks)(struct dsetup *__restrict setup, struct instance *inst) {
task_crit();
debug_enum(setup,inst,NULL,&debug_printleaks_callback,setup);
task_endcrit();
}
PRIVATE void (KCALL debug_validate)(struct dsetup *__restrict setup, struct instance *inst) {
struct mman *old_mm;
task_crit();
TASK_PDIR_KERNEL_BEGIN(old_mm);
#ifdef CONFIG_DEBUG_HEAP
mheap_validate(setup,&mheaps[GFP_SHARED]);
mheap_validate(setup,&mheaps[GFP_SHARED|GFP_LOCKED]);
mheap_validate(setup,&mheaps[GFP_KERNEL]);
mheap_validate(setup,&mheaps[GFP_KERNEL|GFP_LOCKED]);
mheap_validate(setup,&mheaps[GFP_MEMORY]);
#endif
#if !MHEAP_USING_INTERNAL_VALIDATION
debug_enum(setup,inst,NULL,&debug_validate_callback,setup);
#endif
TASK_PDIR_KERNEL_END(old_mm);
task_endcrit();
}
PRIVATE void *(KCALL debug_setflag)(struct dsetup *__restrict setup,
void *mallptr, u8 flags) {
struct instance *inst;
struct mptr *p = mptr_safeload(setup,mallptr);
atomic_rwlock_read(&mptr_inst_lock);
inst = p->m_info.i_inst;
atomic_rwlock_write(&inst->i_driver.k_tlock);
if (flags&MPTRFLAG_UNTRACKED &&
!(p->m_flag&MPTRFLAG_UNTRACKED)) {
struct mman *old_mm = NULL;
if (addr_ispriv(p->m_chain.le_pself) ||
(p->m_chain.le_next != KINSTANCE_TRACE_NULL &&
addr_ispriv(p->m_chain.le_next)))
TASK_PDIR_KERNEL_BEGIN(old_mm);
LIST_REMOVE_EX(p,m_chain,KINSTANCE_TRACE_NULL);
if (old_mm) TASK_PDIR_KERNEL_END(old_mm);
}
p->m_flag |= flags;
p->m_chksum = mptr_chksum(p);
atomic_rwlock_endwrite(&inst->i_driver.k_tlock);
atomic_rwlock_endread(&mptr_inst_lock);
return mallptr;
}
#ifdef __x86_64__
#define GET_EBP(r) __asm__ __volatile__("movq %%rbp, %0" : "=g" (r))
#elif defined(__i386__)
#define GET_EBP(r) __asm__ __volatile__("movl %%ebp, %0" : "=g" (r))
#elif defined(__arm__)
#define GET_EBP(r) __asm__ __volatile__("mov %0, lr" : "=r" (r))
#else
#define GET_EBP(r) (void)((r) = NULL)
#endif
#define DEF_SETUP(name) \
struct dsetup name; \
memset(&name.s_info,0,sizeof(struct dinfo)); \
name.s_info.i_inst = THIS_INSTANCE; \
GET_EBP(name.s_tbebp)
PUBLIC ATTR_NOINLINE void *(KCALL kmalloc)(size_t size, gfp_t flags) { DEF_SETUP(setup); return debug_malloc(&setup,size,flags); }
PUBLIC ATTR_NOINLINE void *(KCALL krealloc)(void *ptr, size_t size, gfp_t flags) { DEF_SETUP(setup); return debug_realloc(&setup,ptr,size,flags); }
PUBLIC ATTR_NOINLINE void *(KCALL kmemalign)(size_t alignment, size_t size, gfp_t flags) { DEF_SETUP(setup); return debug_memalign(&setup,alignment,size,flags); }
PUBLIC ATTR_NOINLINE void *(KCALL krealign)(void *ptr, size_t alignment, size_t size, gfp_t flags) { DEF_SETUP(setup); return debug_realign(&setup,ptr,alignment,size,flags); }
PUBLIC ATTR_NOINLINE void (KCALL kfree)(void *ptr) { DEF_SETUP(setup); debug_free(&setup,ptr,GFP_NORMAL); }
PUBLIC ATTR_NOINLINE void (KCALL kffree)(void *ptr, gfp_t flags) { DEF_SETUP(setup); debug_free(&setup,ptr,flags); }
PUBLIC ATTR_NOINLINE size_t (KCALL kmalloc_usable_size)(void *ptr) { DEF_SETUP(setup); return debug_malloc_usable_size(&setup,ptr); }
PUBLIC ATTR_NOINLINE gfp_t (KCALL kmalloc_flags)(void *ptr) { DEF_SETUP(setup); return debug_malloc_flags(&setup,ptr); }
PUBLIC ATTR_NOINLINE void *(KCALL kmemdup)(void const *__restrict ptr, size_t size, gfp_t flags) { DEF_SETUP(setup); return debug_memdup(&setup,ptr,size,flags); }
PUBLIC ATTR_NOINLINE void *(KCALL kmemadup)(void const *__restrict ptr, size_t alignment, size_t size, gfp_t flags) { DEF_SETUP(setup); return debug_memadup(&setup,ptr,alignment,size,flags); }
PUBLIC ATTR_NOINLINE int (KCALL kmallopt)(int parameter_number, int parameter_value, gfp_t flags) { DEF_SETUP(setup); return debug_mallopt(&setup,parameter_number,parameter_value,flags); }
PUBLIC ATTR_NOINLINE int (KCALL mallopt)(int parameter_number, int parameter_value) { DEF_SETUP(setup); return debug_mallopt(&setup,parameter_number,parameter_value,__GFP_MALLOC); }
PUBLIC ATTR_NOINLINE void *(KCALL malloc)(size_t n_bytes) { DEF_SETUP(setup); return debug_malloc(&setup,n_bytes,__GFP_MALLOC); }
PUBLIC ATTR_NOINLINE void *(KCALL calloc)(size_t count, size_t n_bytes) { DEF_SETUP(setup); return debug_malloc(&setup,count*n_bytes,__GFP_MALLOC|GFP_CALLOC); }
PUBLIC ATTR_NOINLINE void *(KCALL memalign)(size_t alignment, size_t n_bytes) { DEF_SETUP(setup); return debug_memalign(&setup,alignment,n_bytes,__GFP_MALLOC); }
PUBLIC ATTR_NOINLINE void *(KCALL realloc)(void *__restrict mallptr, size_t n_bytes) { DEF_SETUP(setup); return debug_realloc(&setup,mallptr,n_bytes,__GFP_MALLOC); }
PUBLIC ATTR_NOINLINE void *(KCALL realloc_in_place)(void *__restrict mallptr, size_t n_bytes) { DEF_SETUP(setup); return debug_realloc(&setup,mallptr,n_bytes,__GFP_MALLOC|GFP_NOMOVE); }
PUBLIC ATTR_NOINLINE void *(KCALL valloc)(size_t n_bytes) { DEF_SETUP(setup); return debug_memalign(&setup,PAGESIZE,n_bytes,__GFP_MALLOC); }
PUBLIC ATTR_NOINLINE void *(KCALL pvalloc)(size_t n_bytes) { DEF_SETUP(setup); return debug_memalign(&setup,PAGESIZE,(n_bytes+PAGESIZE-1)&~(PAGESIZE-1),__GFP_MALLOC); }
PUBLIC ATTR_NOINLINE void *(KCALL memdup)(void const *__restrict ptr, size_t n_bytes) { DEF_SETUP(setup); return debug_memdup(&setup,ptr,n_bytes,__GFP_MALLOC); }
PUBLIC ATTR_NOINLINE int (KCALL posix_memalign)(void **__restrict pp, size_t alignment, size_t n_bytes) { DEF_SETUP(setup); return debug_posix_memalign(&setup,pp,alignment,n_bytes,__GFP_MALLOC); }
#ifdef CONFIG_HAVE_STRDUP_IN_KERNEL
PUBLIC ATTR_NOINLINE char *(KCALL strdup)(char const *__restrict str) { DEF_SETUP(setup); return debug_strdup(&setup,str,__GFP_MALLOC); }
PUBLIC ATTR_NOINLINE char *(KCALL strndup)(char const *__restrict str, size_t max_chars) { DEF_SETUP(setup); return debug_strndup(&setup,str,max_chars,__GFP_MALLOC); }
PUBLIC ATTR_NOINLINE void *(KCALL memcdup)(void const *__restrict ptr, int needle, size_t n_bytes) { DEF_SETUP(setup); return debug_memcdup(&setup,ptr,needle,n_bytes,__GFP_MALLOC); }
PUBLIC ATTR_NOINLINE char *(KCALL vstrdupf)(char const *__restrict format, va_list args) { DEF_SETUP(setup); return debug_vstrdupf(&setup,format,args,__GFP_MALLOC); }
PUBLIC ATTR_NOINLINE char *(ATTR_CDECL strdupf)(char const *__restrict format, ...) { va_list args; char *result; DEF_SETUP(setup); va_start(args,format); result = debug_vstrdupf(&setup,format,args,__GFP_MALLOC); va_end(args); return result; }
#endif /* CONFIG_HAVE_STRDUP_IN_KERNEL */
PUBLIC ATTR_NOINLINE void *(KCALL _mall_getattrib)(void *mallptr, int attrib) { DEF_SETUP(setup); return debug_getattrib(&setup,mallptr,attrib); }
PUBLIC ATTR_NOINLINE ssize_t (KCALL _mall_traceback)(void *mallptr, __ptbwalker callback,
void *closure) { DEF_SETUP(setup); return debug_traceback(&setup,mallptr,callback,closure); }
PUBLIC ATTR_NOINLINE ssize_t (KCALL _mall_enum)(struct instance *inst, void *checkpoint, ssize_t (KCALL *callback)(void *__restrict mallptr, void *closure),
void *closure) { DEF_SETUP(setup); return debug_enum(&setup,inst,checkpoint,callback,closure); }
PUBLIC ATTR_NOINLINE void (KCALL _mall_printleaks)(struct instance *inst) { DEF_SETUP(setup); debug_printleaks(&setup,inst); }
PUBLIC ATTR_NOINLINE void (KCALL _mall_validate)(struct instance *inst) { DEF_SETUP(setup); debug_validate(&setup,inst); }
PUBLIC ATTR_NOINLINE void *(KCALL _mall_untrack)(void *mallptr) { DEF_SETUP(setup); return debug_setflag(&setup,mallptr,MPTRFLAG_UNTRACKED); }
PUBLIC ATTR_NOINLINE void *(KCALL _mall_nofree)(void *mallptr) { DEF_SETUP(setup); return debug_setflag(&setup,mallptr,MPTRFLAG_NOFREE); }
PUBLIC ATTR_NOINLINE void *(KCALL _mall_global)(void *mallptr) { DEF_SETUP(setup); return debug_setflag(&setup,mallptr,MPTRFLAG_GLOBAL); }
#undef DEF_SETUP
#define DEF_SETUP(name) \
struct dsetup name; \
name.s_info.i_file = __file; \
name.s_info.i_line = __line; \
name.s_info.i_func = __func; \
name.s_info.i_inst = __inst; \
GET_EBP(name.s_tbebp)
PUBLIC ATTR_NOINLINE void *(KCALL _kmalloc_d)(size_t size, gfp_t flags, DEBUGINFO) { DEF_SETUP(setup); return debug_malloc(&setup,size,flags); }
PUBLIC ATTR_NOINLINE void *(KCALL _krealloc_d)(void *ptr, size_t size, gfp_t flags, DEBUGINFO) { DEF_SETUP(setup); return debug_realloc(&setup,ptr,size,flags); }
PUBLIC ATTR_NOINLINE void *(KCALL _kmemalign_d)(size_t alignment, size_t size, gfp_t flags, DEBUGINFO) { DEF_SETUP(setup); return debug_memalign(&setup,alignment,size,flags); }
PUBLIC ATTR_NOINLINE void *(KCALL _krealign_d)(void *ptr, size_t alignment, size_t size, gfp_t flags, DEBUGINFO) { DEF_SETUP(setup); return debug_realign(&setup,ptr,alignment,size,flags); }
PUBLIC ATTR_NOINLINE void (KCALL _kfree_d)(void *ptr, DEBUGINFO) { DEF_SETUP(setup); debug_free(&setup,ptr,GFP_NORMAL); }
PUBLIC ATTR_NOINLINE void (KCALL _kffree_d)(void *ptr, gfp_t flags, DEBUGINFO) { DEF_SETUP(setup); debug_free(&setup,ptr,flags); }
PUBLIC ATTR_NOINLINE size_t (KCALL _kmalloc_usable_size_d)(void *ptr, DEBUGINFO) { DEF_SETUP(setup); return debug_malloc_usable_size(&setup,ptr); }
PUBLIC ATTR_NOINLINE gfp_t (KCALL _kmalloc_flags_d)(void *ptr, DEBUGINFO) { DEF_SETUP(setup); return debug_malloc_flags(&setup,ptr); }
PUBLIC ATTR_NOINLINE void *(KCALL _kmemdup_d)(void const *__restrict ptr, size_t size, gfp_t flags, DEBUGINFO) { DEF_SETUP(setup); return debug_memdup(&setup,ptr,size,flags); }
PUBLIC ATTR_NOINLINE void *(KCALL _kmemadup_d)(void const *__restrict ptr, size_t alignment, size_t size, gfp_t flags, DEBUGINFO) { DEF_SETUP(setup); return debug_memadup(&setup,ptr,alignment,size,flags); }
PUBLIC ATTR_NOINLINE int (KCALL _kmallopt_d)(int parameter_number, int parameter_value, gfp_t flags, DEBUGINFO) { DEF_SETUP(setup); return debug_mallopt(&setup,parameter_number,parameter_value,flags); }
PUBLIC ATTR_NOINLINE int (KCALL _mallopt_d)(int parameter_number, int parameter_value, DEBUGINFO) { DEF_SETUP(setup); return debug_mallopt(&setup,parameter_number,parameter_value,__GFP_MALLOC); }
PUBLIC ATTR_NOINLINE void *(KCALL _malloc_d)(size_t n_bytes, DEBUGINFO) { DEF_SETUP(setup); return debug_malloc(&setup,n_bytes,__GFP_MALLOC); }
PUBLIC ATTR_NOINLINE void *(KCALL _calloc_d)(size_t count, size_t n_bytes, DEBUGINFO) { DEF_SETUP(setup); return debug_malloc(&setup,count*n_bytes,__GFP_MALLOC|GFP_CALLOC); }
PUBLIC ATTR_NOINLINE void *(KCALL _memalign_d)(size_t alignment, size_t n_bytes, DEBUGINFO) { DEF_SETUP(setup); return debug_memalign(&setup,alignment,n_bytes,__GFP_MALLOC); }
PUBLIC ATTR_NOINLINE void *(KCALL _realloc_d)(void *__restrict mallptr, size_t n_bytes, DEBUGINFO) { DEF_SETUP(setup); return debug_realloc(&setup,mallptr,n_bytes,__GFP_MALLOC); }
PUBLIC ATTR_NOINLINE void *(KCALL _realloc_in_place_d)(void *__restrict mallptr, size_t n_bytes, DEBUGINFO) { DEF_SETUP(setup); return debug_realloc(&setup,mallptr,n_bytes,__GFP_MALLOC|GFP_NOMOVE); }
PUBLIC ATTR_NOINLINE void *(KCALL _valloc_d)(size_t n_bytes, DEBUGINFO) { DEF_SETUP(setup); return debug_memalign(&setup,PAGESIZE,n_bytes,__GFP_MALLOC); }
PUBLIC ATTR_NOINLINE void *(KCALL _pvalloc_d)(size_t n_bytes, DEBUGINFO) { DEF_SETUP(setup); return debug_memalign(&setup,PAGESIZE,(n_bytes+PAGESIZE-1)&~(PAGESIZE-1),__GFP_MALLOC); }
PUBLIC ATTR_NOINLINE void *(KCALL _memdup_d)(void const *__restrict ptr, size_t n_bytes, DEBUGINFO) { DEF_SETUP(setup); return debug_memdup(&setup,ptr,n_bytes,__GFP_MALLOC); }
PUBLIC ATTR_NOINLINE int (KCALL _posix_memalign_d)(void **__restrict pp, size_t alignment, size_t n_bytes, DEBUGINFO) { DEF_SETUP(setup); return debug_posix_memalign(&setup,pp,alignment,n_bytes,__GFP_MALLOC); }
#ifdef CONFIG_HAVE_STRDUP_IN_KERNEL
PUBLIC ATTR_NOINLINE char *(KCALL _strdup_d)(char const *__restrict str, DEBUGINFO) { DEF_SETUP(setup); return debug_strdup(&setup,str,__GFP_MALLOC); }
PUBLIC ATTR_NOINLINE char *(KCALL _strndup_d)(char const *__restrict str, size_t max_chars, DEBUGINFO) { DEF_SETUP(setup); return debug_strndup(&setup,str,max_chars,__GFP_MALLOC); }
PUBLIC ATTR_NOINLINE void *(KCALL _memcdup_d)(void const *__restrict ptr, int needle, size_t n_bytes, DEBUGINFO) { DEF_SETUP(setup); return debug_memcdup(&setup,ptr,needle,n_bytes,__GFP_MALLOC); }
PUBLIC ATTR_NOINLINE char *(KCALL _vstrdupf_d)(char const *__restrict format, va_list args, DEBUGINFO) { DEF_SETUP(setup); return debug_vstrdupf(&setup,format,args,__GFP_MALLOC); }
PUBLIC ATTR_NOINLINE char *(ATTR_CDECL _strdupf_d)(DEBUGINFO, char const *__restrict format, ...) { va_list args; char *result; DEF_SETUP(setup); va_start(args,format); result = debug_vstrdupf(&setup,format,args,__GFP_MALLOC); va_end(args); return result; }
#endif /* CONFIG_HAVE_STRDUP_IN_KERNEL */
PUBLIC ATTR_NOINLINE void *(KCALL _mall_getattrib_d)(void *mallptr, int attrib, DEBUGINFO) { DEF_SETUP(setup); return debug_getattrib(&setup,mallptr,attrib); }
PUBLIC ATTR_NOINLINE ssize_t (KCALL _mall_traceback_d)(void *mallptr, __ptbwalker callback,
void *closure, DEBUGINFO) { DEF_SETUP(setup); return debug_traceback(&setup,mallptr,callback,closure); }
PUBLIC ATTR_NOINLINE ssize_t (KCALL _mall_enum_d)(struct instance *inst, void *checkpoint, ssize_t (KCALL *callback)(void *__restrict mallptr, void *closure),
void *closure, DEBUGINFO) { DEF_SETUP(setup); return debug_enum(&setup,inst,checkpoint,callback,closure); }
PUBLIC ATTR_NOINLINE void (KCALL _mall_printleaks_d)(struct instance *inst, DEBUGINFO) { DEF_SETUP(setup); debug_printleaks(&setup,inst); }
PUBLIC ATTR_NOINLINE void (KCALL _mall_validate_d)(struct instance *inst, DEBUGINFO) { DEF_SETUP(setup); debug_validate(&setup,inst); }
PUBLIC ATTR_NOINLINE void *(KCALL _mall_untrack_d)(void *mallptr, DEBUGINFO) { DEF_SETUP(setup); return debug_setflag(&setup,mallptr,MPTRFLAG_UNTRACKED); }
PUBLIC ATTR_NOINLINE void *(KCALL _mall_nofree_d)(void *mallptr, DEBUGINFO) { DEF_SETUP(setup); return debug_setflag(&setup,mallptr,MPTRFLAG_NOFREE); }
PUBLIC ATTR_NOINLINE void *(KCALL _mall_global_d)(void *mallptr, DEBUGINFO) { DEF_SETUP(setup); return debug_setflag(&setup,mallptr,MPTRFLAG_GLOBAL); }
#undef DEF_SETUP
#endif /* MALLOC_DEBUG_API */
DECL_END
#pragma GCC diagnostic pop
#endif /* !GUARD_KERNEL_MEMORY_MALLOC_C */
| 44.734118 | 277 | 0.68418 |
0352d342a4e5e5a1b5005bacf5795a0c18d09207 | 1,692 | h | C | cmake-2.8.10.1/Source/cmDocumentationFormatterDocbook.h | vidkidz/crossbridge | ba0bf94aee0ce6cf7eb5be882382e52bc57ba396 | [
"MIT"
] | 1 | 2016-04-09T02:58:13.000Z | 2016-04-09T02:58:13.000Z | cmake-2.8.10.1/Source/cmDocumentationFormatterDocbook.h | vidkidz/crossbridge | ba0bf94aee0ce6cf7eb5be882382e52bc57ba396 | [
"MIT"
] | null | null | null | cmake-2.8.10.1/Source/cmDocumentationFormatterDocbook.h | vidkidz/crossbridge | ba0bf94aee0ce6cf7eb5be882382e52bc57ba396 | [
"MIT"
] | null | null | null | /*============================================================================
CMake - Cross Platform Makefile Generator
Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
Distributed under the OSI-approved BSD License (the "License");
see accompanying file Copyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even the
implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the License for more information.
============================================================================*/
#ifndef _cmDocumentationFormatterDocbook_h
#define _cmDocumentationFormatterDocbook_h
#include "cmStandardIncludes.h"
#include "cmDocumentationFormatter.h"
/** Class to print the documentation as Docbook.
http://www.oasis-open.org/docbook/xml/4.2/ */
class cmDocumentationFormatterDocbook : public cmDocumentationFormatter
{
public:
cmDocumentationFormatterDocbook();
virtual cmDocumentationEnums::Form GetForm() const
{ return cmDocumentationEnums::DocbookForm;}
virtual void PrintHeader(const char* docname, const char* appname,
std::ostream& os);
virtual void PrintFooter(std::ostream& os);
virtual void PrintSection(std::ostream& os,
const cmDocumentationSection& section,
const char* name);
virtual void PrintPreformatted(std::ostream& os, const char* text);
virtual void PrintParagraph(std::ostream& os, const char* text);
private:
void PrintId(std::ostream& os, const char* prefix, std::string id);
std::set<std::string> EmittedLinkIds;
std::string Docname;
};
#endif
| 38.454545 | 78 | 0.654846 |
035390003ba76bed0549d34335a209fc17c721fb | 3,740 | h | C | iPhoneOS15.2.sdk/System/Library/Frameworks/EventKitUI.framework/Headers/EKEventViewController.h | bakedpotato191/sdks | 7b5c8c299a8afcb6d68b356668b4949a946734d9 | [
"MIT"
] | 6 | 2021-12-13T03:09:30.000Z | 2022-03-09T15:18:16.000Z | iPhoneOS15.0.sdk/System/Library/Frameworks/EventKitUI.framework/Headers/EKEventViewController.h | chrisharper22/sdks | 9b2f79c4a48fd5ca9a602044e617231d639a3f57 | [
"MIT"
] | null | null | null | iPhoneOS15.0.sdk/System/Library/Frameworks/EventKitUI.framework/Headers/EKEventViewController.h | chrisharper22/sdks | 9b2f79c4a48fd5ca9a602044e617231d639a3f57 | [
"MIT"
] | null | null | null | //
// EKEventViewController.h
// EventKitUI
//
// Copyright 2009-2010 Apple Inc. All rights reserved.
//
#import <UIKit/UIKit.h>
#import <EventKitUI/EventKitUIDefines.h>
#import <EventKitUI/EventKitUIBundle.h>
NS_ASSUME_NONNULL_BEGIN
@class EKEvent, EKEventStore;
typedef NS_ENUM(NSInteger, EKEventViewAction) {
EKEventViewActionDone, // simply closed
EKEventViewActionResponded, // event invitation was responded to and saved
EKEventViewActionDeleted, // event was deleted
};
/*!
@class EKEventViewController
@abstract View controller to view event detail.
@discussion You can use this view controller to display the details of an event. You
can also optionally choose to allow the user to edit the event by displaying
an edit button. While you can use this view controller to display events that
have not been saved, the edit button will not appear in this situation. If
you have pushed this view controller onto a navigation controller stack, and
the underlying event gets deleted, this controller will remove itself from
the stack and clear its event property.
*/
@protocol EKEventViewDelegate;
NS_EXTENSION_UNAVAILABLE_IOS("EventKitUI is not supported in extensions")
EVENTKITUI_CLASS_AVAILABLE(4_0)
@interface EKEventViewController : UIViewController
@property(nonatomic, weak, nullable) id<EKEventViewDelegate> delegate __OSX_AVAILABLE_STARTING(__MAC_NA,__IPHONE_4_2);
/*!
@property event
@abstract Specifies the event to view.
@discussion You must set this prior to displaying the view controller.
*/
@property(nonatomic, retain, null_unspecified) EKEvent *event;
/*!
@property allowsEditing
@abstract Determines whether Edit button can be shown.
@discussion Note that even if this is enabled, the edit button may not appear if this event
is in a read-only calendar, such as a subscribed calendar. It may also not appear
if the event was not created by the current user (i.e. it's an event they were
invited to). And lastly, if the event was never saved, the edit button will not
appear.
*/
@property(nonatomic) BOOL allowsEditing;
/*!
@property allowsCalendarPreview
@abstract Determines whether event can be shown in calendar day view preview.
@discussion This option only affects calendar invites at present. If the event is an invite,
and this option is set, a table cell will appear that allows the user to preview
the event along with their other events for the day.
*/
@property(nonatomic) BOOL allowsCalendarPreview;
@end
NS_EXTENSION_UNAVAILABLE_IOS("EventKitUI is not supported in extensions")
@protocol EKEventViewDelegate <NSObject>
@required
/*!
@method eventViewController:didCompleteWithAction:
@abstract Called to let delegate know that an action has occurred that should cause the
controller to be dismissed.
@discussion If the user taps a button which deletes the event, or responds to an invite, this
method is called on the delegate so that the delegate can decide to dismiss
the view controller. When presented in a popover, it also reports when the Done
button is pressed.
@param controller the controller in question
@param action the action that is triggering the dismissal
*/
- (void)eventViewController:(EKEventViewController *)controller didCompleteWithAction:(EKEventViewAction)action __OSX_AVAILABLE_STARTING(__MAC_NA,__IPHONE_4_2);
@end
NS_ASSUME_NONNULL_END
| 41.098901 | 160 | 0.715241 |
0357ae48a64f9539068c5ef0b5f22af958b29fe9 | 884 | h | C | Pods/Headers/Public/ComponentKit/CKDataSourceStateInternal.h | zyfu0000/AsyncApplicationKit | 4af50fad6bd9d88709c85efc8ca14113d4fc9117 | [
"MIT"
] | null | null | null | Pods/Headers/Public/ComponentKit/CKDataSourceStateInternal.h | zyfu0000/AsyncApplicationKit | 4af50fad6bd9d88709c85efc8ca14113d4fc9117 | [
"MIT"
] | null | null | null | Pods/Headers/Public/ComponentKit/CKDataSourceStateInternal.h | zyfu0000/AsyncApplicationKit | 4af50fad6bd9d88709c85efc8ca14113d4fc9117 | [
"MIT"
] | null | null | null | /*
* Copyright (c) 2014-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
#import <ComponentKit/CKDefines.h>
#if CK_NOT_SWIFT
#import <ComponentKit/CKDataSourceState.h>
/** Internal interface since this class is usually only created internally. */
@interface CKDataSourceState ()
/**
@param configuration The configuration used to generate this state object.
@param sections An NSArray of NSArrays of CKDataSourceItem.
*/
- (instancetype)initWithConfiguration:(CKDataSourceConfiguration *)configuration
sections:(NSArray *)sections;
@property (nonatomic, copy, readonly) NSArray *sections;
@end
#endif
| 27.625 | 80 | 0.735294 |
03598d1fade2cc3b83adbecf1a8dc25293d2b816 | 9,425 | h | C | openanalytics/include/alibabacloud/openanalytics/OpenanalyticsClient.h | iamzken/aliyun-openapi-cpp-sdk | 3c991c9ca949b6003c8f498ce7a672ea88162bf1 | [
"Apache-2.0"
] | 89 | 2018-02-02T03:54:39.000Z | 2021-12-13T01:32:55.000Z | openanalytics/include/alibabacloud/openanalytics/OpenanalyticsClient.h | iamzken/aliyun-openapi-cpp-sdk | 3c991c9ca949b6003c8f498ce7a672ea88162bf1 | [
"Apache-2.0"
] | 89 | 2018-03-14T07:44:54.000Z | 2021-11-26T07:43:25.000Z | openanalytics/include/alibabacloud/openanalytics/OpenanalyticsClient.h | aliyun/aliyun-openapi-cpp-sdk | 0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36 | [
"Apache-2.0"
] | 69 | 2018-01-22T09:45:52.000Z | 2022-03-28T07:58:38.000Z | /*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef ALIBABACLOUD_OPENANALYTICS_OPENANALYTICSCLIENT_H_
#define ALIBABACLOUD_OPENANALYTICS_OPENANALYTICSCLIENT_H_
#include <future>
#include <alibabacloud/core/AsyncCallerContext.h>
#include <alibabacloud/core/EndpointProvider.h>
#include <alibabacloud/core/RpcServiceClient.h>
#include "OpenanalyticsExport.h"
#include "model/CloseProductAccountRequest.h"
#include "model/CloseProductAccountResult.h"
#include "model/DescribeRegionListRequest.h"
#include "model/DescribeRegionListResult.h"
#include "model/GetAllowIPRequest.h"
#include "model/GetAllowIPResult.h"
#include "model/GetEndPointByDomainRequest.h"
#include "model/GetEndPointByDomainResult.h"
#include "model/GetProductStatusRequest.h"
#include "model/GetProductStatusResult.h"
#include "model/GetRegionStatusRequest.h"
#include "model/GetRegionStatusResult.h"
#include "model/OpenProductAccountRequest.h"
#include "model/OpenProductAccountResult.h"
#include "model/QueryEndPointListRequest.h"
#include "model/QueryEndPointListResult.h"
#include "model/SetAllowIPRequest.h"
#include "model/SetAllowIPResult.h"
namespace AlibabaCloud
{
namespace Openanalytics
{
class ALIBABACLOUD_OPENANALYTICS_EXPORT OpenanalyticsClient : public RpcServiceClient
{
public:
typedef Outcome<Error, Model::CloseProductAccountResult> CloseProductAccountOutcome;
typedef std::future<CloseProductAccountOutcome> CloseProductAccountOutcomeCallable;
typedef std::function<void(const OpenanalyticsClient*, const Model::CloseProductAccountRequest&, const CloseProductAccountOutcome&, const std::shared_ptr<const AsyncCallerContext>&)> CloseProductAccountAsyncHandler;
typedef Outcome<Error, Model::DescribeRegionListResult> DescribeRegionListOutcome;
typedef std::future<DescribeRegionListOutcome> DescribeRegionListOutcomeCallable;
typedef std::function<void(const OpenanalyticsClient*, const Model::DescribeRegionListRequest&, const DescribeRegionListOutcome&, const std::shared_ptr<const AsyncCallerContext>&)> DescribeRegionListAsyncHandler;
typedef Outcome<Error, Model::GetAllowIPResult> GetAllowIPOutcome;
typedef std::future<GetAllowIPOutcome> GetAllowIPOutcomeCallable;
typedef std::function<void(const OpenanalyticsClient*, const Model::GetAllowIPRequest&, const GetAllowIPOutcome&, const std::shared_ptr<const AsyncCallerContext>&)> GetAllowIPAsyncHandler;
typedef Outcome<Error, Model::GetEndPointByDomainResult> GetEndPointByDomainOutcome;
typedef std::future<GetEndPointByDomainOutcome> GetEndPointByDomainOutcomeCallable;
typedef std::function<void(const OpenanalyticsClient*, const Model::GetEndPointByDomainRequest&, const GetEndPointByDomainOutcome&, const std::shared_ptr<const AsyncCallerContext>&)> GetEndPointByDomainAsyncHandler;
typedef Outcome<Error, Model::GetProductStatusResult> GetProductStatusOutcome;
typedef std::future<GetProductStatusOutcome> GetProductStatusOutcomeCallable;
typedef std::function<void(const OpenanalyticsClient*, const Model::GetProductStatusRequest&, const GetProductStatusOutcome&, const std::shared_ptr<const AsyncCallerContext>&)> GetProductStatusAsyncHandler;
typedef Outcome<Error, Model::GetRegionStatusResult> GetRegionStatusOutcome;
typedef std::future<GetRegionStatusOutcome> GetRegionStatusOutcomeCallable;
typedef std::function<void(const OpenanalyticsClient*, const Model::GetRegionStatusRequest&, const GetRegionStatusOutcome&, const std::shared_ptr<const AsyncCallerContext>&)> GetRegionStatusAsyncHandler;
typedef Outcome<Error, Model::OpenProductAccountResult> OpenProductAccountOutcome;
typedef std::future<OpenProductAccountOutcome> OpenProductAccountOutcomeCallable;
typedef std::function<void(const OpenanalyticsClient*, const Model::OpenProductAccountRequest&, const OpenProductAccountOutcome&, const std::shared_ptr<const AsyncCallerContext>&)> OpenProductAccountAsyncHandler;
typedef Outcome<Error, Model::QueryEndPointListResult> QueryEndPointListOutcome;
typedef std::future<QueryEndPointListOutcome> QueryEndPointListOutcomeCallable;
typedef std::function<void(const OpenanalyticsClient*, const Model::QueryEndPointListRequest&, const QueryEndPointListOutcome&, const std::shared_ptr<const AsyncCallerContext>&)> QueryEndPointListAsyncHandler;
typedef Outcome<Error, Model::SetAllowIPResult> SetAllowIPOutcome;
typedef std::future<SetAllowIPOutcome> SetAllowIPOutcomeCallable;
typedef std::function<void(const OpenanalyticsClient*, const Model::SetAllowIPRequest&, const SetAllowIPOutcome&, const std::shared_ptr<const AsyncCallerContext>&)> SetAllowIPAsyncHandler;
OpenanalyticsClient(const Credentials &credentials, const ClientConfiguration &configuration);
OpenanalyticsClient(const std::shared_ptr<CredentialsProvider> &credentialsProvider, const ClientConfiguration &configuration);
OpenanalyticsClient(const std::string &accessKeyId, const std::string &accessKeySecret, const ClientConfiguration &configuration);
~OpenanalyticsClient();
CloseProductAccountOutcome closeProductAccount(const Model::CloseProductAccountRequest &request)const;
void closeProductAccountAsync(const Model::CloseProductAccountRequest& request, const CloseProductAccountAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr) const;
CloseProductAccountOutcomeCallable closeProductAccountCallable(const Model::CloseProductAccountRequest& request) const;
DescribeRegionListOutcome describeRegionList(const Model::DescribeRegionListRequest &request)const;
void describeRegionListAsync(const Model::DescribeRegionListRequest& request, const DescribeRegionListAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr) const;
DescribeRegionListOutcomeCallable describeRegionListCallable(const Model::DescribeRegionListRequest& request) const;
GetAllowIPOutcome getAllowIP(const Model::GetAllowIPRequest &request)const;
void getAllowIPAsync(const Model::GetAllowIPRequest& request, const GetAllowIPAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr) const;
GetAllowIPOutcomeCallable getAllowIPCallable(const Model::GetAllowIPRequest& request) const;
GetEndPointByDomainOutcome getEndPointByDomain(const Model::GetEndPointByDomainRequest &request)const;
void getEndPointByDomainAsync(const Model::GetEndPointByDomainRequest& request, const GetEndPointByDomainAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr) const;
GetEndPointByDomainOutcomeCallable getEndPointByDomainCallable(const Model::GetEndPointByDomainRequest& request) const;
GetProductStatusOutcome getProductStatus(const Model::GetProductStatusRequest &request)const;
void getProductStatusAsync(const Model::GetProductStatusRequest& request, const GetProductStatusAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr) const;
GetProductStatusOutcomeCallable getProductStatusCallable(const Model::GetProductStatusRequest& request) const;
GetRegionStatusOutcome getRegionStatus(const Model::GetRegionStatusRequest &request)const;
void getRegionStatusAsync(const Model::GetRegionStatusRequest& request, const GetRegionStatusAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr) const;
GetRegionStatusOutcomeCallable getRegionStatusCallable(const Model::GetRegionStatusRequest& request) const;
OpenProductAccountOutcome openProductAccount(const Model::OpenProductAccountRequest &request)const;
void openProductAccountAsync(const Model::OpenProductAccountRequest& request, const OpenProductAccountAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr) const;
OpenProductAccountOutcomeCallable openProductAccountCallable(const Model::OpenProductAccountRequest& request) const;
QueryEndPointListOutcome queryEndPointList(const Model::QueryEndPointListRequest &request)const;
void queryEndPointListAsync(const Model::QueryEndPointListRequest& request, const QueryEndPointListAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr) const;
QueryEndPointListOutcomeCallable queryEndPointListCallable(const Model::QueryEndPointListRequest& request) const;
SetAllowIPOutcome setAllowIP(const Model::SetAllowIPRequest &request)const;
void setAllowIPAsync(const Model::SetAllowIPRequest& request, const SetAllowIPAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr) const;
SetAllowIPOutcomeCallable setAllowIPCallable(const Model::SetAllowIPRequest& request) const;
private:
std::shared_ptr<EndpointProvider> endpointProvider_;
};
}
}
#endif // !ALIBABACLOUD_OPENANALYTICS_OPENANALYTICSCLIENT_H_
| 79.201681 | 219 | 0.835225 |
0359b3f9bc510a181def89a52ab2f592069463c0 | 521 | c | C | unused/develop/data/src/data/scene_5_triggers.c | um3k/gbvm | dce728c5fd0d40c3f75b773660f475b4911d8121 | [
"MIT"
] | 33 | 2020-12-27T11:53:23.000Z | 2022-02-19T23:05:12.000Z | unused/develop/data/src/data/scene_5_triggers.c | um3k/gbvm | dce728c5fd0d40c3f75b773660f475b4911d8121 | [
"MIT"
] | 2 | 2020-12-10T16:53:53.000Z | 2022-01-31T21:42:01.000Z | unused/develop/data/src/data/scene_5_triggers.c | um3k/gbvm | dce728c5fd0d40c3f75b773660f475b4911d8121 | [
"MIT"
] | 6 | 2021-04-18T08:09:16.000Z | 2022-01-31T21:52:24.000Z | #pragma bank 255
// Scene: Parallax Test
// Triggers
#include "gbs_types.h"
#include "data/script_s5t0_interact.h"
#include "data/script_s5t1_interact.h"
const void __at(255) __bank_scene_5_triggers;
const struct trigger_t scene_5_triggers[] = {
{
// Trigger 1,
.x = 79,
.y = 13,
.width = 1,
.height = 1,
.script = TO_FAR_PTR_T(script_s5t0_interact)
},
{
// Trigger 2,
.x = 0,
.y = 13,
.width = 1,
.height = 1,
.script = TO_FAR_PTR_T(script_s5t1_interact)
}
};
| 17.366667 | 48 | 0.619962 |
035b0d76268e577cb4bbc2170d3e07217fc9b15b | 4,141 | h | C | Source/SynthVoice.h | cjsuth/Signal-O | 9618911b66c2f7193c77979e372272fb4796e55d | [
"MIT"
] | 1 | 2020-12-13T04:33:00.000Z | 2020-12-13T04:33:00.000Z | Source/SynthVoice.h | cjsuth/Signal-O | 9618911b66c2f7193c77979e372272fb4796e55d | [
"MIT"
] | null | null | null | Source/SynthVoice.h | cjsuth/Signal-O | 9618911b66c2f7193c77979e372272fb4796e55d | [
"MIT"
] | null | null | null | /*
==============================================================================
SynthVoice.h
Created: 22 May 2020 10:13:09am
Author: Chad Sutherland
==============================================================================
*/
#pragma once
#include <JuceHeader.h>
#include "SynthSound.h"
#include "maximilian.h"
class SynthVoice : public SynthesiserVoice
{
public:
bool canPlaySound (SynthesiserSound *sound)
{
return dynamic_cast<SynthSound*>(sound) != nullptr;
}
void getEnvelopeParams (std::atomic<float>* attack, std::atomic<float>* decay, std::atomic<float>* sustain, std::atomic<float>* release)
{
env1.setAttack(*attack);
env1.setDecay(*decay);
env1.setSustain(*sustain);
env1.setRelease(*release);
}
void getWavetypeParams(std::atomic<float>* wave1,
std::atomic<float>* wave2,
std::atomic<float>* l1,
std::atomic<float>* l2,
std::atomic<float>* o1,
std::atomic<float>* o2)
{
wavetype1 = (int)*wave1;
wavetype2 = (int)*wave2;
level1 = *l1;
level2 = *l2;
octave1 = *o1;
octave2 = *o2;
}
void getFilterParams (std::atomic<float>* filterType, std::atomic<float>* filterCutoff, std::atomic<float>* filterRes)
{
filterChoice = (int)*filterType;
cutoff = (int)*filterCutoff;
res = (int)*filterRes;
}
void startNote (int midiNoteNumber, float velocity, SynthesiserSound *sound, int currentPitchWheelPosition) override
{
env1.trigger = 1;
level = velocity * .8;
frequency = MidiMessage::getMidiNoteInHertz(midiNoteNumber);
}
void stopNote (float velocity, bool allowTailOff) override
{
env1.trigger = 0;
allowTailOff = true;
if (velocity == 0)
clearCurrentNote();
}
double setOscType()
{
double sample1, sample2;
double shiftedFreq1 = frequency * pow(2, octave1);
double shiftedFreq2 = frequency * pow(2, octave2);
switch (wavetype1)
{
case 1: sample1 = osc1.sinewave(shiftedFreq1); break;
case 2: sample1 = osc1.triangle(shiftedFreq1); break;
case 3: sample1 = osc1.saw(shiftedFreq1); break;
case 4: sample1 = osc1.square(shiftedFreq1); break;
default: sample1 = osc1.sinewave(shiftedFreq1);
}
switch (wavetype2)
{
case 1: sample2 = osc2.sinewave(shiftedFreq2); break;
case 2: sample2 = osc2.triangle(shiftedFreq2); break;
case 3: sample2 = osc2.saw(shiftedFreq2); break;
case 4: sample2 = osc2.square(shiftedFreq2); break;
default: sample2 = osc2.sinewave(shiftedFreq2);
}
return (sample1 * level1) + (sample2 * level2);
}
double setEnvelope()
{
return env1.adsr(setOscType(), env1.trigger);
}
// like processBlock, DSP stuff here
void renderNextBlock (AudioBuffer<float> &outputBuffer, int startSample, int numSamples) override
{
for (int sample = 0; sample < numSamples; ++sample)
{
for (int channel = 0; channel < outputBuffer.getNumChannels(); ++channel)
{
outputBuffer.addSample(channel, startSample, setEnvelope() * level); // change to gain
}
++startSample;
}
}
void pitchWheelMoved (int newPitchWheelValue)
{
}
void controllerMoved (int controllerNumber, int newControllerValue)
{
}
private:
double level, frequency;
int wavetype1, wavetype2;
float level1, level2, octave1, octave2;
int filterChoice;
float cutoff, res;
maxiOsc osc1, osc2;
maxiEnv env1;
maxiFilter filter1;
};
| 29.791367 | 141 | 0.528375 |
035c07101a885fb90ba5a2098bf4f5714fb55d67 | 2,844 | h | C | runtime/debug.h | stelleg/cheetah | 3315410fd863dfbdbd723f22e6c9fb6aff82ee3f | [
"MIT"
] | null | null | null | runtime/debug.h | stelleg/cheetah | 3315410fd863dfbdbd723f22e6c9fb6aff82ee3f | [
"MIT"
] | null | null | null | runtime/debug.h | stelleg/cheetah | 3315410fd863dfbdbd723f22e6c9fb6aff82ee3f | [
"MIT"
] | null | null | null | #ifndef _DEBUG_H
#define _DEBUG_H
#include <stdarg.h>
#include "rts-config.h"
// forward declaration for using struct global_stat
struct global_state;
struct __cilkrts_worker;
#define CILK_CHECK(g, cond, complain) \
((cond) ? (void)0 : cilk_die_internal(g, complain))
#ifndef ALERT_LVL
#define ALERT_LVL 0
#endif
#define ALERT_NONE 0x0
#define ALERT_FIBER 0x1
#define ALERT_SYNC 0x2
#define ALERT_SCHED 0x4
#define ALERT_STEAL 0x8
#define ALERT_EXCEPT 0x10
#define ALERT_RETURN 0x20
#define ALERT_BOOT 0x40
#define ALERT_CFRAME 0x80
#define ALERT_REDUCE 0x100
#define ALERT_START 0x200
#define ALERT_REDUCE_ID 0x400
extern CHEETAH_INTERNAL unsigned int alert_level;
// Unused: compiler inlines the stack frame creation
// #define CILK_STACKFRAME_MAGIC 0xCAFEBABE
CHEETAH_INTERNAL_NORETURN
void cilkrts_bug(struct __cilkrts_worker *w, const char *fmt, ...);
CHEETAH_INTERNAL_NORETURN
void cilk_die_internal(struct global_state *const g, const char *complain);
#if CILK_DEBUG
void cilkrts_alert(int lvl, struct __cilkrts_worker *w, const char *fmt, ...);
#define cilkrts_alert(LVL, W, FMT, ...) \
(alert_level & (LVL)&ALERT_LVL) \
? cilkrts_alert(LVL, W, FMT, ##__VA_ARGS__) \
: (void)0
#define WHEN_CILK_DEBUG(ex) ex
/** Standard text for failed assertion */
CHEETAH_INTERNAL extern const char *const __cilkrts_assertion_failed;
#define CILK_ASSERT(w, ex) \
(__builtin_expect((ex) != 0, 1) \
? (void)0 \
: cilkrts_bug(w, __cilkrts_assertion_failed, __FILE__, __LINE__, \
#ex))
#define CILK_ASSERT_G(ex) \
(__builtin_expect((ex) != 0, 1) \
? (void)0 \
: cilkrts_bug(NULL, __cilkrts_assertion_failed, __FILE__, __LINE__, \
#ex))
#define CILK_ABORT(w, msg) \
cilkrts_bug(w, __cilkrts_assertion_failed, __FILE__, __LINE__, msg)
#define CILK_ABORT_G(msg) \
cilkrts_bug(NULL, __cilkrts_assertion_failed_g, __FILE__, __LINE__, msg)
#else
#define cilkrts_alert(lvl, fmt, ...)
#define CILK_ASSERT(w, ex)
#define CILK_ASSERT_G(ex)
#define CILK_ABORT(w, msg)
#define CILK_ABORT_G(msg)
#define WHEN_CILK_DEBUG(ex)
#endif // CILK_DEBUG
// to silence compiler warning for vars only used during debugging
#define USE_UNUSED(var) (void)(var)
#endif
| 34.26506 | 80 | 0.581575 |
035c43f8c95e573cb21dddfe588d99bb17803649 | 11,150 | h | C | sys/dev/netmap/if_re_netmap.h | jinxuan/netmap | 32e06f9d18bf82e40a7c5b6e769c0ca7607913fc | [
"Linux-OpenIB"
] | 1 | 2017-02-14T14:04:44.000Z | 2017-02-14T14:04:44.000Z | sys/dev/netmap/if_re_netmap.h | djwmarks/netmap | 32e06f9d18bf82e40a7c5b6e769c0ca7607913fc | [
"Linux-OpenIB"
] | null | null | null | sys/dev/netmap/if_re_netmap.h | djwmarks/netmap | 32e06f9d18bf82e40a7c5b6e769c0ca7607913fc | [
"Linux-OpenIB"
] | null | null | null | /*
* Copyright (C) 2011-2014 Luigi Rizzo. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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.
*/
/*
* $FreeBSD: head/sys/dev/netmap/if_re_netmap.h 234225 2012-04-13 15:33:12Z luigi $
*
* netmap support for: re
*
* For more details on netmap support please see ixgbe_netmap.h
*/
#include <net/netmap.h>
#include <sys/selinfo.h>
#include <vm/vm.h>
#include <vm/pmap.h> /* vtophys ? */
#include <dev/netmap/netmap_kern.h>
/*
* Register/unregister. We are already under netmap lock.
*/
static int
re_netmap_reg(struct netmap_adapter *na, int onoff)
{
struct ifnet *ifp = na->ifp;
struct rl_softc *adapter = ifp->if_softc;
RL_LOCK(adapter);
re_stop(adapter); /* also clears IFF_DRV_RUNNING */
if (onoff) {
nm_set_native_flags(na);
} else {
nm_clear_native_flags(na);
}
re_init_locked(adapter); /* also enables intr */
RL_UNLOCK(adapter);
return (ifp->if_drv_flags & IFF_DRV_RUNNING ? 0 : 1);
}
/*
* Reconcile kernel and user view of the transmit ring.
*/
static int
re_netmap_txsync(struct netmap_kring *kring, int flags)
{
struct netmap_adapter *na = kring->na;
struct ifnet *ifp = na->ifp;
struct netmap_ring *ring = kring->ring;
u_int nm_i; /* index into the netmap ring */
u_int nic_i; /* index into the NIC ring */
u_int n;
u_int const lim = kring->nkr_num_slots - 1;
u_int const head = kring->rhead;
/* device-specific */
struct rl_softc *sc = ifp->if_softc;
struct rl_txdesc *txd = sc->rl_ldata.rl_tx_desc;
bus_dmamap_sync(sc->rl_ldata.rl_tx_list_tag,
sc->rl_ldata.rl_tx_list_map,
BUS_DMASYNC_POSTREAD | BUS_DMASYNC_POSTWRITE); // XXX extra postwrite ?
/*
* First part: process new packets to send.
*/
nm_i = kring->nr_hwcur;
if (nm_i != head) { /* we have new packets to send */
nic_i = sc->rl_ldata.rl_tx_prodidx;
// XXX or netmap_idx_k2n(kring, nm_i);
for (n = 0; nm_i != head; n++) {
struct netmap_slot *slot = &ring->slot[nm_i];
u_int len = slot->len;
uint64_t paddr;
void *addr = PNMB(na, slot, &paddr);
/* device-specific */
struct rl_desc *desc = &sc->rl_ldata.rl_tx_list[nic_i];
int cmd = slot->len | RL_TDESC_CMD_EOF |
RL_TDESC_CMD_OWN | RL_TDESC_CMD_SOF ;
NM_CHECK_ADDR_LEN(na, addr, len);
if (nic_i == lim) /* mark end of ring */
cmd |= RL_TDESC_CMD_EOR;
if (slot->flags & NS_BUF_CHANGED) {
/* buffer has changed, reload map */
desc->rl_bufaddr_lo = htole32(RL_ADDR_LO(paddr));
desc->rl_bufaddr_hi = htole32(RL_ADDR_HI(paddr));
netmap_reload_map(na, sc->rl_ldata.rl_tx_mtag,
txd[nic_i].tx_dmamap, addr);
}
slot->flags &= ~(NS_REPORT | NS_BUF_CHANGED);
/* Fill the slot in the NIC ring. */
desc->rl_cmdstat = htole32(cmd);
/* make sure changes to the buffer are synced */
bus_dmamap_sync(sc->rl_ldata.rl_tx_mtag,
txd[nic_i].tx_dmamap,
BUS_DMASYNC_PREWRITE);
nm_i = nm_next(nm_i, lim);
nic_i = nm_next(nic_i, lim);
}
sc->rl_ldata.rl_tx_prodidx = nic_i;
kring->nr_hwcur = head;
/* synchronize the NIC ring */
bus_dmamap_sync(sc->rl_ldata.rl_tx_list_tag,
sc->rl_ldata.rl_tx_list_map,
BUS_DMASYNC_PREREAD|BUS_DMASYNC_PREWRITE);
/* start ? */
CSR_WRITE_1(sc, sc->rl_txstart, RL_TXSTART_START);
}
/*
* Second part: reclaim buffers for completed transmissions.
*/
if (flags & NAF_FORCE_RECLAIM || nm_kr_txempty(kring)) {
nic_i = sc->rl_ldata.rl_tx_considx;
for (n = 0; nic_i != sc->rl_ldata.rl_tx_prodidx;
n++, nic_i = RL_TX_DESC_NXT(sc, nic_i)) {
uint32_t cmdstat =
le32toh(sc->rl_ldata.rl_tx_list[nic_i].rl_cmdstat);
if (cmdstat & RL_TDESC_STAT_OWN)
break;
}
if (n > 0) {
sc->rl_ldata.rl_tx_considx = nic_i;
sc->rl_ldata.rl_tx_free += n;
kring->nr_hwtail = nm_prev(netmap_idx_n2k(kring, nic_i), lim);
}
}
nm_txsync_finalize(kring);
return 0;
}
/*
* Reconcile kernel and user view of the receive ring.
*/
static int
re_netmap_rxsync(struct netmap_kring *kring, int flags)
{
struct netmap_adapter *na = kring->na;
struct ifnet *ifp = na->ifp;
struct netmap_ring *ring = kring->ring;
u_int nm_i; /* index into the netmap ring */
u_int nic_i; /* index into the NIC ring */
u_int n;
u_int const lim = kring->nkr_num_slots - 1;
u_int const head = nm_rxsync_prologue(kring);
int force_update = (flags & NAF_FORCE_READ) || kring->nr_kflags & NKR_PENDINTR;
/* device-specific */
struct rl_softc *sc = ifp->if_softc;
struct rl_rxdesc *rxd = sc->rl_ldata.rl_rx_desc;
if (head > lim)
return netmap_ring_reinit(kring);
bus_dmamap_sync(sc->rl_ldata.rl_rx_list_tag,
sc->rl_ldata.rl_rx_list_map,
BUS_DMASYNC_POSTREAD | BUS_DMASYNC_POSTWRITE);
/*
* First part: import newly received packets.
*
* This device uses all the buffers in the ring, so we need
* another termination condition in addition to RL_RDESC_STAT_OWN
* cleared (all buffers could have it cleared). The easiest one
* is to stop right before nm_hwcur.
*/
if (netmap_no_pendintr || force_update) {
uint16_t slot_flags = kring->nkr_slot_flags;
uint32_t stop_i = nm_prev(kring->nr_hwcur, lim);
nic_i = sc->rl_ldata.rl_rx_prodidx; /* next pkt to check */
nm_i = netmap_idx_n2k(kring, nic_i);
while (nm_i != stop_i) {
struct rl_desc *cur_rx = &sc->rl_ldata.rl_rx_list[nic_i];
uint32_t rxstat = le32toh(cur_rx->rl_cmdstat);
uint32_t total_len;
if ((rxstat & RL_RDESC_STAT_OWN) != 0)
break;
total_len = rxstat & sc->rl_rxlenmask;
/* XXX subtract crc */
total_len = (total_len < 4) ? 0 : total_len - 4;
ring->slot[nm_i].len = total_len;
ring->slot[nm_i].flags = slot_flags;
/* sync was in re_newbuf() */
bus_dmamap_sync(sc->rl_ldata.rl_rx_mtag,
rxd[nic_i].rx_dmamap, BUS_DMASYNC_POSTREAD);
// if_inc_counter(sc->rl_ifp, IFCOUNTER_IPACKETS, 1);
nm_i = nm_next(nm_i, lim);
nic_i = nm_next(nic_i, lim);
}
sc->rl_ldata.rl_rx_prodidx = nic_i;
kring->nr_hwtail = nm_i;
kring->nr_kflags &= ~NKR_PENDINTR;
}
/*
* Second part: skip past packets that userspace has released.
*/
nm_i = kring->nr_hwcur;
if (nm_i != head) {
nic_i = netmap_idx_k2n(kring, nm_i);
for (n = 0; nm_i != head; n++) {
struct netmap_slot *slot = &ring->slot[nm_i];
uint64_t paddr;
void *addr = PNMB(na, slot, &paddr);
struct rl_desc *desc = &sc->rl_ldata.rl_rx_list[nic_i];
int cmd = NETMAP_BUF_SIZE(na) | RL_RDESC_CMD_OWN;
if (addr == NETMAP_BUF_BASE(na)) /* bad buf */
goto ring_reset;
if (nic_i == lim) /* mark end of ring */
cmd |= RL_RDESC_CMD_EOR;
if (slot->flags & NS_BUF_CHANGED) {
/* buffer has changed, reload map */
desc->rl_bufaddr_lo = htole32(RL_ADDR_LO(paddr));
desc->rl_bufaddr_hi = htole32(RL_ADDR_HI(paddr));
netmap_reload_map(na, sc->rl_ldata.rl_rx_mtag,
rxd[nic_i].rx_dmamap, addr);
slot->flags &= ~NS_BUF_CHANGED;
}
desc->rl_cmdstat = htole32(cmd);
bus_dmamap_sync(sc->rl_ldata.rl_rx_mtag,
rxd[nic_i].rx_dmamap,
BUS_DMASYNC_PREREAD);
nm_i = nm_next(nm_i, lim);
nic_i = nm_next(nic_i, lim);
}
kring->nr_hwcur = head;
bus_dmamap_sync(sc->rl_ldata.rl_rx_list_tag,
sc->rl_ldata.rl_rx_list_map,
BUS_DMASYNC_PREREAD | BUS_DMASYNC_PREWRITE);
}
/* tell userspace that there might be new packets */
nm_rxsync_finalize(kring);
return 0;
ring_reset:
return netmap_ring_reinit(kring);
}
/*
* Additional routines to init the tx and rx rings.
* In other drivers we do that inline in the main code.
*/
static void
re_netmap_tx_init(struct rl_softc *sc)
{
struct rl_txdesc *txd;
struct rl_desc *desc;
int i, n;
struct netmap_adapter *na = NA(sc->rl_ifp);
struct netmap_slot *slot;
slot = netmap_reset(na, NR_TX, 0, 0);
/* slot is NULL if we are not in native netmap mode */
if (!slot)
return;
/* in netmap mode, overwrite addresses and maps */
txd = sc->rl_ldata.rl_tx_desc;
desc = sc->rl_ldata.rl_tx_list;
n = sc->rl_ldata.rl_tx_desc_cnt;
/* l points in the netmap ring, i points in the NIC ring */
for (i = 0; i < n; i++) {
uint64_t paddr;
int l = netmap_idx_n2k(&na->tx_rings[0], i);
void *addr = PNMB(na, slot + l, &paddr);
desc[i].rl_bufaddr_lo = htole32(RL_ADDR_LO(paddr));
desc[i].rl_bufaddr_hi = htole32(RL_ADDR_HI(paddr));
netmap_load_map(na, sc->rl_ldata.rl_tx_mtag,
txd[i].tx_dmamap, addr);
}
}
static void
re_netmap_rx_init(struct rl_softc *sc)
{
struct netmap_adapter *na = NA(sc->rl_ifp);
struct netmap_slot *slot = netmap_reset(na, NR_RX, 0, 0);
struct rl_desc *desc = sc->rl_ldata.rl_rx_list;
uint32_t cmdstat;
uint32_t nic_i, max_avail;
uint32_t const n = sc->rl_ldata.rl_rx_desc_cnt;
if (!slot)
return;
/*
* Do not release the slots owned by userspace,
* and also keep one empty.
*/
max_avail = n - 1 - nm_kr_rxspace(&na->rx_rings[0]);
for (nic_i = 0; nic_i < n; nic_i++) {
void *addr;
uint64_t paddr;
uint32_t nm_i = netmap_idx_n2k(&na->rx_rings[0], nic_i);
addr = PNMB(na, slot + nm_i, &paddr);
netmap_reload_map(na, sc->rl_ldata.rl_rx_mtag,
sc->rl_ldata.rl_rx_desc[nic_i].rx_dmamap, addr);
bus_dmamap_sync(sc->rl_ldata.rl_rx_mtag,
sc->rl_ldata.rl_rx_desc[nic_i].rx_dmamap, BUS_DMASYNC_PREREAD);
desc[nic_i].rl_bufaddr_lo = htole32(RL_ADDR_LO(paddr));
desc[nic_i].rl_bufaddr_hi = htole32(RL_ADDR_HI(paddr));
cmdstat = NETMAP_BUF_SIZE(na);
if (nic_i == n - 1) /* mark the end of ring */
cmdstat |= RL_RDESC_CMD_EOR;
if (nic_i < max_avail)
cmdstat |= RL_RDESC_CMD_OWN;
desc[nic_i].rl_cmdstat = htole32(cmdstat);
}
}
static void
re_netmap_attach(struct rl_softc *sc)
{
struct netmap_adapter na;
bzero(&na, sizeof(na));
na.ifp = sc->rl_ifp;
na.na_flags = NAF_BDG_MAYSLEEP;
na.num_tx_desc = sc->rl_ldata.rl_tx_desc_cnt;
na.num_rx_desc = sc->rl_ldata.rl_rx_desc_cnt;
na.nm_txsync = re_netmap_txsync;
na.nm_rxsync = re_netmap_rxsync;
na.nm_register = re_netmap_reg;
na.num_tx_rings = na.num_rx_rings = 1;
netmap_attach(&na);
}
/* end of file */
| 29.342105 | 83 | 0.69722 |
035c82a8eca6238bbc7e9ea12084de8f459a5505 | 650 | h | C | CondFormats/L1TObjects/interface/L1TGlobalPrescalesVetos.h | nistefan/cmssw | ea13af97f7f2117a4f590a5e654e06ecd9825a5b | [
"Apache-2.0"
] | 3 | 2018-08-24T19:10:26.000Z | 2019-02-19T11:45:32.000Z | CondFormats/L1TObjects/interface/L1TGlobalPrescalesVetos.h | nistefan/cmssw | ea13af97f7f2117a4f590a5e654e06ecd9825a5b | [
"Apache-2.0"
] | 3 | 2018-08-23T13:40:24.000Z | 2019-12-05T21:16:03.000Z | CondFormats/L1TObjects/interface/L1TGlobalPrescalesVetos.h | nistefan/cmssw | ea13af97f7f2117a4f590a5e654e06ecd9825a5b | [
"Apache-2.0"
] | 5 | 2018-08-21T16:37:52.000Z | 2020-01-09T13:33:17.000Z | // L1TGlobalPrescalesVetos
//
// Table containing the entire set of prescales and masks for each L1T algorithm bit
//
#ifndef L1TGlobalPrescalesVetos_h
#define L1TGlobalPrescalesVetos_h
#include <vector>
#include "CondFormats/Serialization/interface/Serializable.h"
class L1TGlobalPrescalesVetos {
public:
L1TGlobalPrescalesVetos(){ version_ = 0; bxmask_default_=0; }
unsigned int version_;
std::vector<std::vector<int> > prescale_table_;
int bxmask_default_;
std::map<int, std::vector<int> > bxmask_map_;
std::vector<int> veto_;
std::vector<int> exp_ints_;
std::vector<double> exp_doubles_;
COND_SERIALIZABLE;
};
#endif
| 22.413793 | 85 | 0.758462 |
0361612908604208163bbf05e8f8edae5e10c1c1 | 736 | c | C | lista_de_atividades_3/a.8.c | Douglasbm040/PROGRAMACAO-1- | 3f77aa45f44ed75ba0bf3a647444869e959d7591 | [
"MIT"
] | null | null | null | lista_de_atividades_3/a.8.c | Douglasbm040/PROGRAMACAO-1- | 3f77aa45f44ed75ba0bf3a647444869e959d7591 | [
"MIT"
] | null | null | null | lista_de_atividades_3/a.8.c | Douglasbm040/PROGRAMACAO-1- | 3f77aa45f44ed75ba0bf3a647444869e959d7591 | [
"MIT"
] | null | null | null | #include <stdio.h>
int main(){
int x,in, out, total, final = 0;
printf("Andares: ");
scanf("%d",&x);
printf("--------------\n");
for ( int i = 0 ; i < x ; i++){
printf("Entrada[%d]: ",i+1);
scanf("%d",&in );
printf("Saida[%d]: ",i+1);
scanf("%d",&out );
total = in + out ;
printf("TOTAL[%d] %d\n",i+1,total );
if (total >15){
printf("Excesso de Passageiros!\n");
printf("Deve(m) Sair: %d\n", total -15);
final += 15 - in ;
}
else{
final+=in ;
}
printf("--------------\n");
}
printf("Desceram: %d\n", final);
return 0;
} | 16.727273 | 55 | 0.368207 |
03617725dd5bc63fd145e8cf279c57d4d86e0a95 | 355 | h | C | Code/ZTranslate/ZTranslateViewController.h | StoneStoneStoneWang/ZStoreKit | 2c42aa3602ab240d4b428ebb20ade2da2b47c2c7 | [
"MIT"
] | null | null | null | Code/ZTranslate/ZTranslateViewController.h | StoneStoneStoneWang/ZStoreKit | 2c42aa3602ab240d4b428ebb20ade2da2b47c2c7 | [
"MIT"
] | null | null | null | Code/ZTranslate/ZTranslateViewController.h | StoneStoneStoneWang/ZStoreKit | 2c42aa3602ab240d4b428ebb20ade2da2b47c2c7 | [
"MIT"
] | null | null | null | //
// ZTranslateViewController.h
// ZFragment
//
// Created by three stone 王 on 2020/3/16.
// Copyright © 2020 three stone 王. All rights reserved.
//
#import <ZTransition/ZTransition.h>
#import "ZFragmentConfig.h"
#import "ZFragmentMix.h"
NS_ASSUME_NONNULL_BEGIN
@interface ZTranslateViewController : ZTViewController
@end
NS_ASSUME_NONNULL_END
| 16.904762 | 56 | 0.760563 |
036b21c0f7201e1398eed6acc12cbb9f380d845d | 891 | h | C | Aplicacion Movil/generated/bundles/login-transition/build/Android/Preview/app/src/main/include/Fuse.Animations.Easin-e748cec3.h | marferfer/SpinOff-LoL | a9dba8ac9dd476ec1ef94712d9a8e76d3b45aca8 | [
"Apache-2.0"
] | null | null | null | Aplicacion Movil/generated/bundles/login-transition/build/Android/Preview/app/src/main/include/Fuse.Animations.Easin-e748cec3.h | marferfer/SpinOff-LoL | a9dba8ac9dd476ec1ef94712d9a8e76d3b45aca8 | [
"Apache-2.0"
] | null | null | null | Aplicacion Movil/generated/bundles/login-transition/build/Android/Preview/app/src/main/include/Fuse.Animations.Easin-e748cec3.h | marferfer/SpinOff-LoL | a9dba8ac9dd476ec1ef94712d9a8e76d3b45aca8 | [
"Apache-2.0"
] | null | null | null | // This file was generated based on C:/Users/JuanJose/AppData/Local/Fusetools/Packages/Fuse.Common/1.9.0/Easing.uno.
// WARNING: Changes might be lost if you edit this file directly.
#pragma once
#include <Fuse.Animations.Easing.h>
namespace g{namespace Fuse{namespace Animations{struct Easing__ElasticInImpl;}}}
namespace g{
namespace Fuse{
namespace Animations{
// internal sealed class Easing.ElasticInImpl :275
// {
::g::Fuse::Animations::Easing_type* Easing__ElasticInImpl_typeof();
void Easing__ElasticInImpl__ctor_1_fn(Easing__ElasticInImpl* __this);
void Easing__ElasticInImpl__Map_fn(Easing__ElasticInImpl* __this, double* k, double* __retval);
void Easing__ElasticInImpl__New1_fn(Easing__ElasticInImpl** __retval);
struct Easing__ElasticInImpl : ::g::Fuse::Animations::Easing
{
void ctor_1();
static Easing__ElasticInImpl* New1();
};
// }
}}} // ::g::Fuse::Animations
| 33 | 116 | 0.782267 |
036b81306d18d8c5c52fbfc01acbf3c15ff04539 | 95 | h | C | ios/Classes/FlutterAndroidPipPlugin.h | App2Sales/flutter_android_pip | 801268be978a5884a9ef6e7542ef68cc5590a85f | [
"MIT"
] | 14 | 2019-01-29T02:33:03.000Z | 2022-03-10T02:33:35.000Z | ios/Classes/FlutterAndroidPipPlugin.h | App2Sales/flutter_android_pip | 801268be978a5884a9ef6e7542ef68cc5590a85f | [
"MIT"
] | 8 | 2018-10-04T12:40:35.000Z | 2021-11-10T12:08:30.000Z | ios/Classes/FlutterAndroidPipPlugin.h | App2Sales/flutter_android_pip | 801268be978a5884a9ef6e7542ef68cc5590a85f | [
"MIT"
] | 12 | 2019-02-15T00:37:12.000Z | 2022-03-17T04:10:40.000Z | #import <Flutter/Flutter.h>
@interface FlutterAndroidPipPlugin : NSObject<FlutterPlugin>
@end
| 19 | 60 | 0.810526 |
036c618a17653ce543fe8ba4c7b8559efa3d2500 | 6,364 | c | C | main/main.c | gkcity/-homekit-accessory-sample-esp8266 | 29d7161961836d1fbafdf27e9c080d34d03b65f9 | [
"MIT"
] | 1 | 2019-01-31T19:03:13.000Z | 2019-01-31T19:03:13.000Z | main/main.c | gkcity/-homekit-accessory-sample-esp8266 | 29d7161961836d1fbafdf27e9c080d34d03b65f9 | [
"MIT"
] | 1 | 2019-04-08T04:59:05.000Z | 2019-04-08T04:59:05.000Z | main/main.c | gkcity/-homekit-accessory-sample-esp8266 | 29d7161961836d1fbafdf27e9c080d34d03b65f9 | [
"MIT"
] | 1 | 2018-12-05T07:38:21.000Z | 2018-12-05T07:38:21.000Z | #include <string.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/event_groups.h"
#include "esp_system.h"
#include "esp_wifi.h"
#include "esp_event_loop.h"
#include "esp_log.h"
#include "nvs_flash.h"
#include "lwip/err.h"
#include "lwip/sys.h"
#include "device/definition/Lightbulb.h"
#include "HomeKitStack.h"
#include "CaptivePortal.h"
#define EXAMPLE_ESP_WIFI_SSID "gkct"
#define EXAMPLE_ESP_WIFI_PASS "hellogkct"
#define EXAMPLE_MAX_STA_CONN 10
/* FreeRTOS event group to signal when we are connected*/
static EventGroupHandle_t wifi_event_group;
/* The event group allows multiple bits for each event,
but we only care about one event - are we connected
to the AP with an IP? */
const int WIFI_CONNECTED_BIT = BIT0;
static const char *TAG = "homekit-accessory";
#define DID "1C:BE:EE:01:01:08"
#define NAME "demo"
#define SETUP_CODE "031-45-154"
static void runIotStack(void *param)
{
const char *ip = (const char *)param;
Device *device = NULL;
uint16_t port = 60006;
/**
* 1. 初始化设备
*/
device = Lightbulb(DID, NAME, ip, SETUP_CODE);
if (device == NULL)
{
return;
}
/**
* 2. 线程1: 启动协议栈,连接到服务器,等待控制指令并执行。
*/
StartHomeKit(device, &port);
/**
* 3. 线程2: 监控设备数据,如果发生变化,则通过ipc端口通知服务器。
*/
// StartDeviceMonitor(device->did, port);
/**
* 4. 线程3: 主线程,阻塞在这里,等待用户输入命令
*/
// WaitingForUserCommand(port);
/**
* 5. 停止数据监控
*/
//StopDeviceMonitor();
/**
* 6. 停止协议栈
*/
StopHomeKit();
/**
* 7. 删除设备,准备退出
*/
Device_Delete(device);
}
void startIoTStack(const char *ip)
{
wifi_ap_record_t ap;
memset(&ap, 0, sizeof(wifi_ap_record_t));
if (esp_wifi_sta_get_ap_info(&ap) == ESP_OK)
{
ESP_LOGI(TAG, "ap.ssid: %s", ap.ssid);
ESP_LOGI(TAG, "ap.bssid: %s", ap.bssid);
}
xTaskCreate(runIotStack, "iot", 1024 * 6, (void *)ip, 5, NULL);
}
static void runCaptivePortal(void *param)
{
tcpip_adapter_ip_info_t info;
if (tcpip_adapter_get_ip_info(TCPIP_ADAPTER_IF_AP, &info) != ESP_OK)
{
ESP_LOGI(TAG, "tcpip_adapter_get_ip_info failed");
return;
}
CaptivePortal * cp = CaptivePortal_New(NULL, NULL);
if (cp == NULL)
{
ESP_LOGI(TAG, "CaptivePortal_New failed");
return;
}
char s[32];
uint8_t *a = (uint8_t *) &info.ip.addr;
snprintf(s, 32, "%d.%d.%d.%d", a[0], a[1], a[2], a[3]);
printf("runCaptivePortal ip: %s\n", s);
CaptivePortal_Run(cp, info.ip.addr);
}
void startCaptivePortal(void)
{
ESP_LOGI(TAG, "startCaptivePortal");
xTaskCreate(runCaptivePortal, "cp", 1024 * 6, NULL, 5, NULL);
}
void stopCaptivePortal(void)
{
ESP_LOGI(TAG, "stopCaptivePortal");
}
static esp_err_t event_handler(void *ctx, system_event_t *event)
{
switch(event->event_id) {
case SYSTEM_EVENT_STA_START:
esp_wifi_connect();
break;
case SYSTEM_EVENT_STA_GOT_IP:
ESP_LOGI(TAG, "got ip:%s", ip4addr_ntoa(&event->event_info.got_ip.ip_info.ip));
xEventGroupSetBits(wifi_event_group, WIFI_CONNECTED_BIT);
startIoTStack(ip4addr_ntoa(&event->event_info.got_ip.ip_info.ip));
break;
case SYSTEM_EVENT_AP_STACONNECTED:
ESP_LOGI(TAG, "station:"MACSTR" join, AID=%d",
MAC2STR(event->event_info.sta_connected.mac), event->event_info.sta_connected.aid);
break;
case SYSTEM_EVENT_AP_STADISCONNECTED:
ESP_LOGI(TAG, "station:"MACSTR"leave, AID=%d",
MAC2STR(event->event_info.sta_disconnected.mac), event->event_info.sta_disconnected.aid);
break;
case SYSTEM_EVENT_STA_DISCONNECTED:
esp_wifi_connect();
xEventGroupClearBits(wifi_event_group, WIFI_CONNECTED_BIT);
break;
case SYSTEM_EVENT_AP_START:
startCaptivePortal();
break;
case SYSTEM_EVENT_AP_STOP:
stopCaptivePortal();
break;
default:
break;
}
return ESP_OK;
}
void wifi_init_softap()
{
wifi_event_group = xEventGroupCreate();
tcpip_adapter_init();
ESP_ERROR_CHECK(esp_event_loop_init(event_handler, NULL));
wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
ESP_ERROR_CHECK(esp_wifi_init(&cfg));
wifi_config_t wifi_config = {
.ap = {
.ssid = EXAMPLE_ESP_WIFI_SSID,
.ssid_len = strlen(EXAMPLE_ESP_WIFI_SSID),
.max_connection = EXAMPLE_MAX_STA_CONN,
.authmode = WIFI_AUTH_OPEN
},
};
if (strlen(EXAMPLE_ESP_WIFI_PASS) == 0) {
wifi_config.ap.authmode = WIFI_AUTH_OPEN;
}
ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_AP));
ESP_ERROR_CHECK(esp_wifi_set_config(ESP_IF_WIFI_AP, &wifi_config));
ESP_ERROR_CHECK(esp_wifi_start());
ESP_LOGI(TAG, "wifi_init_softap finished, SSID: %s", EXAMPLE_ESP_WIFI_SSID);
}
void wifi_init_sta()
{
wifi_event_group = xEventGroupCreate();
tcpip_adapter_init();
ESP_ERROR_CHECK(esp_event_loop_init(event_handler, NULL) );
wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
ESP_ERROR_CHECK(esp_wifi_init(&cfg));
wifi_config_t wifi_config = {
.sta = {
.ssid = EXAMPLE_ESP_WIFI_SSID,
.password = EXAMPLE_ESP_WIFI_PASS
},
};
ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA) );
ESP_ERROR_CHECK(esp_wifi_set_config(ESP_IF_WIFI_STA, &wifi_config) );
ESP_ERROR_CHECK(esp_wifi_start() );
ESP_LOGI(TAG, "wifi_init_sta finished.");
ESP_LOGI(TAG, "connect to ap SSID:%s password:%s",
EXAMPLE_ESP_WIFI_SSID, EXAMPLE_ESP_WIFI_PASS);
}
void app_main()
{
printf("app started, free heap size: %d\n", esp_get_free_heap_size());
printf("SDK version:%s\n", esp_get_idf_version());
//Initialize NVS
esp_err_t ret = nvs_flash_init();
if (ret == ESP_ERR_NVS_NO_FREE_PAGES) {
ESP_ERROR_CHECK(nvs_flash_erase());
ret = nvs_flash_init();
}
ESP_ERROR_CHECK(ret);
#if 0
ESP_LOGI(TAG, "ESP_WIFI_MODE_AP");
wifi_init_softap();
#else
ESP_LOGI(TAG, "ESP_WIFI_MODE_STA");
wifi_init_sta();
#endif
}
| 25.869919 | 110 | 0.634978 |
036c9a1f858028956c3b6d1261276c185cf376c7 | 220 | h | C | MapDemo/MapDemo/ViewController.h | 0Stars0/Test | 3185092996ea9fad73dd6d37a67427983b86fc9d | [
"MIT"
] | null | null | null | MapDemo/MapDemo/ViewController.h | 0Stars0/Test | 3185092996ea9fad73dd6d37a67427983b86fc9d | [
"MIT"
] | null | null | null | MapDemo/MapDemo/ViewController.h | 0Stars0/Test | 3185092996ea9fad73dd6d37a67427983b86fc9d | [
"MIT"
] | null | null | null | //
// ViewController.h
// MapDemo
//
// Created by zhouzhongmao on 2019/10/18.
// Copyright © 2019 zhouzhongmao. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
@end
| 13.75 | 55 | 0.7 |
036d2a5fb01d6854affe6e4feb92997dd8978084 | 4,515 | h | C | x_track/Vendor/hisilicon/hi3559v200/prebuilt_libs/amp/a7_liteos/mpp/include/hi_errno.h | liushiwei/lv_port_linux_frame_buffer | 17b822a68f8390df1e3b2c09319899c9c61dd72d | [
"MIT"
] | 158 | 2020-06-30T17:58:10.000Z | 2022-03-10T09:27:31.000Z | x_track/Vendor/hisilicon/hi3559v200/prebuilt_libs/amp/a7_liteos/mpp/include/hi_errno.h | liushiwei/lv_port_linux_frame_buffer | 17b822a68f8390df1e3b2c09319899c9c61dd72d | [
"MIT"
] | 13 | 2020-10-10T01:06:39.000Z | 2021-11-09T01:03:09.000Z | x_track/Vendor/hisilicon/hi3559v200/prebuilt_libs/amp/a7_liteos/mpp/include/hi_errno.h | liushiwei/lv_port_linux_frame_buffer | 17b822a68f8390df1e3b2c09319899c9c61dd72d | [
"MIT"
] | 41 | 2020-07-03T00:36:17.000Z | 2022-02-28T06:11:46.000Z | /******************************************************************************
Copyright (C), 2016, Hisilicon Tech. Co., Ltd.
******************************************************************************
File Name : hi_errno.h
Version : Initial Draft
Author : Hisilicon multimedia software group
Created : 2016/07/15
Last Modified :
Description : define the format of error code
Function List :
******************************************************************************/
#ifndef __HI_ERRNO_H__
#define __HI_ERRNO_H__
#include "hi_debug.h"
#ifdef __cplusplus
#if __cplusplus
extern "C" {
#endif
#endif /* End of #ifdef __cplusplus */
/* 1010 0000b
* VTOP use APPID from 0~31
* so, hisilicon use APPID based on 32
*/
#define HI_ERR_APPID (0x80000000L + 0x20000000L)
typedef enum hiERR_LEVEL_E {
EN_ERR_LEVEL_DEBUG = 0, /* debug-level */
EN_ERR_LEVEL_INFO, /* informational */
EN_ERR_LEVEL_NOTICE, /* normal but significant condition */
EN_ERR_LEVEL_WARNING, /* warning conditions */
EN_ERR_LEVEL_ERROR, /* error conditions */
EN_ERR_LEVEL_CRIT, /* critical conditions */
EN_ERR_LEVEL_ALERT, /* action must be taken immediately */
EN_ERR_LEVEL_FATAL, /* just for compatibility with previous version */
EN_ERR_LEVEL_BUTT
} ERR_LEVEL_E;
/******************************************************************************
|----------------------------------------------------------------|
| 1 | APP_ID | MOD_ID | ERR_LEVEL | ERR_ID |
|----------------------------------------------------------------|
|<--><--7bits----><----8bits---><--3bits---><------13bits------->|
******************************************************************************/
#define HI_DEF_ERR(module, level, errid) \
((HI_S32)((HI_ERR_APPID) | ((module) << 16) | ((level) << 13) | (errid)))
/* NOTE! the following defined all common error code,
** all module must reserved 0~63 for their common error code
*/
typedef enum hiEN_ERR_CODE_E {
EN_ERR_INVALID_DEVID = 1, /* invlalid device ID */
EN_ERR_INVALID_CHNID = 2, /* invlalid channel ID */
EN_ERR_ILLEGAL_PARAM = 3, /* at lease one parameter is illagal
* eg, an illegal enumeration value */
EN_ERR_EXIST = 4, /* resource exists */
EN_ERR_UNEXIST = 5, /* resource unexists */
EN_ERR_NULL_PTR = 6, /* using a NULL point */
EN_ERR_NOT_CONFIG = 7, /* try to enable or initialize system, device
** or channel, before configing attribute */
EN_ERR_NOT_SUPPORT = 8, /* operation or type is not supported by NOW */
EN_ERR_NOT_PERM = 9, /* operation is not permitted
** eg, try to change static attribute */
EN_ERR_INVALID_PIPEID = 10, /* invlalid pipe ID */
EN_ERR_INVALID_STITCHGRPID = 11, /* invlalid stitch group ID */
EN_ERR_NOMEM = 12,/* failure caused by malloc memory */
EN_ERR_NOBUF = 13,/* failure caused by malloc buffer */
EN_ERR_BUF_EMPTY = 14,/* no data in buffer */
EN_ERR_BUF_FULL = 15,/* no buffer for new data */
EN_ERR_SYS_NOTREADY = 16,/* System is not ready,maybe not initialed or
** loaded. Returning the error code when opening
** a device file failed. */
EN_ERR_BADADDR = 17,/* bad address,
** eg. used for copy_from_user & copy_to_user */
EN_ERR_BUSY = 18,/* resource is busy,
** eg. destroy a venc chn without unregister it */
EN_ERR_SIZE_NOT_ENOUGH = 19, /* buffer size is smaller than the actual size required */
EN_ERR_BUTT = 63,/* maxium code, private error code of all modules
** must be greater than it */
} EN_ERR_CODE_E;
#ifdef __cplusplus
#if __cplusplus
}
#endif
#endif /* __cplusplus */
#endif /* __HI_ERRNO_H__ */
| 44.264706 | 94 | 0.473311 |
036f5c65963dc0bfd4a45dabf61704a1a6c6570d | 6,275 | h | C | Code/Framework/AzCore/AzCore/Settings/SettingsRegistryImpl.h | cypherdotXd/o3de | bb90c4ddfe2d495e9c00ebf1e2650c6d603a5676 | [
"Apache-2.0",
"MIT"
] | 1 | 2021-07-17T23:46:31.000Z | 2021-07-17T23:46:31.000Z | Code/Framework/AzCore/AzCore/Settings/SettingsRegistryImpl.h | cypherdotXd/o3de | bb90c4ddfe2d495e9c00ebf1e2650c6d603a5676 | [
"Apache-2.0",
"MIT"
] | 3 | 2021-09-08T03:41:27.000Z | 2022-03-12T01:01:29.000Z | Code/Framework/AzCore/AzCore/Settings/SettingsRegistryImpl.h | cypherdotXd/o3de | bb90c4ddfe2d495e9c00ebf1e2650c6d603a5676 | [
"Apache-2.0",
"MIT"
] | null | null | null | /*
* Copyright (c) Contributors to the Open 3D Engine Project.
* For complete copyright and license terms please see the LICENSE at the root of this distribution.
*
* SPDX-License-Identifier: Apache-2.0 OR MIT
*
*/
#pragma once
#include <AzCore/JSON/document.h>
#include <AzCore/JSON/pointer.h>
#include <AzCore/IO/Path/Path_fwd.h>
#include <AzCore/Interface/Interface.h>
#include <AzCore/Serialization/Json/JsonSerialization.h>
#include <AzCore/Settings/SettingsRegistry.h>
#include <AzCore/std/containers/fixed_vector.h>
#include <AzCore/std/containers/vector.h>
#include <AzCore/std/parallel/mutex.h>
// Using a define instead of a static string to avoid the need for temporary buffers to composite the full paths.
#define AZ_SETTINGS_REGISTRY_HISTORY_KEY "/Amazon/AzCore/Runtime/Registry/FileHistory"
namespace AZ
{
class StackedString;
class SettingsRegistryImpl final
: public SettingsRegistryInterface
{
public:
AZ_CLASS_ALLOCATOR(SettingsRegistryImpl, AZ::OSAllocator, 0);
AZ_RTTI(AZ::SettingsRegistryImpl, "{E9C34190-F888-48CA-83C9-9F24B4E21D72}", AZ::SettingsRegistryInterface);
static constexpr size_t MaxRegistryFolderEntries = 128;
SettingsRegistryImpl();
AZ_DISABLE_COPY_MOVE(SettingsRegistryImpl);
~SettingsRegistryImpl() override = default;
void SetContext(SerializeContext* context);
void SetContext(JsonRegistrationContext* context);
Type GetType(AZStd::string_view path) const override;
bool Visit(Visitor& visitor, AZStd::string_view path) const override;
bool Visit(const VisitorCallback& callback, AZStd::string_view path) const override;
[[nodiscard]] NotifyEventHandler RegisterNotifier(const NotifyCallback& callback) override;
[[nodiscard]] NotifyEventHandler RegisterNotifier(NotifyCallback&& callback) override;
void ClearNotifiers();
[[nodiscard]] PreMergeEventHandler RegisterPreMergeEvent(const PreMergeEventCallback& callback) override;
[[nodiscard]] PreMergeEventHandler RegisterPreMergeEvent(PreMergeEventCallback&& callback) override;
[[nodiscard]] PostMergeEventHandler RegisterPostMergeEvent(const PostMergeEventCallback& callback) override;
[[nodiscard]] PostMergeEventHandler RegisterPostMergeEvent(PostMergeEventCallback&& callback) override;
void ClearMergeEvents();
bool Get(bool& result, AZStd::string_view path) const override;
bool Get(s64& result, AZStd::string_view path) const override;
bool Get(u64& result, AZStd::string_view path) const override;
bool Get(double& result, AZStd::string_view path) const override;
bool Get(AZStd::string& result, AZStd::string_view path) const override;
bool Get(SettingsRegistryInterface::FixedValueString& result, AZStd::string_view path) const override;
bool GetObject(void* result, Uuid resultTypeID, AZStd::string_view path) const override;
bool Set(AZStd::string_view path, bool value) override;
bool Set(AZStd::string_view path, s64 value) override;
bool Set(AZStd::string_view path, u64 value) override;
bool Set(AZStd::string_view path, double value) override;
bool Set(AZStd::string_view path, AZStd::string_view value) override;
bool Set(AZStd::string_view path, const char* value) override;
bool SetObject(AZStd::string_view path, const void* value, Uuid valueTypeID) override;
bool Remove(AZStd::string_view path) override;
bool MergeCommandLineArgument(AZStd::string_view argument, AZStd::string_view rootKey,
const CommandLineArgumentSettings& commandLineSettings) override;
bool MergeSettings(AZStd::string_view data, Format format) override;
bool MergeSettingsFile(AZStd::string_view path, Format format, AZStd::string_view rootKey,
AZStd::vector<char>* scratchBuffer = nullptr) override;
bool MergeSettingsFolder(AZStd::string_view path, const Specializations& specializations,
AZStd::string_view platform, AZStd::string_view rootKey = "", AZStd::vector<char>* scratchBuffer = nullptr) override;
void SetApplyPatchSettings(const AZ::JsonApplyPatchSettings& applyPatchSettings) override;
void GetApplyPatchSettings(AZ::JsonApplyPatchSettings& applyPatchSettings) override;
private:
using TagList = AZStd::fixed_vector<size_t, Specializations::MaxCount + 1>;
struct RegistryFile
{
AZ::IO::FixedMaxPathString m_relativePath;
TagList m_tags;
bool m_isPatch{ false };
bool m_isPlatformFile{ false };
};
using RegistryFileList = AZStd::fixed_vector<RegistryFile, MaxRegistryFolderEntries>;
template<typename T>
bool SetValueInternal(AZStd::string_view path, T value);
template<typename T>
bool GetValueInternal(T& result, AZStd::string_view path) const;
VisitResponse Visit(Visitor& visitor, StackedString& path, AZStd::string_view valueName,
const rapidjson::Value& value) const;
// Compares if lhs is less than rhs in terms of processing order. This can also detect and report conflicts.
bool IsLessThan(bool& collisionFound, const RegistryFile& lhs, const RegistryFile& rhs, const Specializations& specializations,
const rapidjson::Pointer& historyPointer, AZStd::string_view folderPath);
bool ExtractFileDescription(RegistryFile& output, const char* filename, const Specializations& specializations);
bool MergeSettingsFileInternal(const char* path, Format format, AZStd::string_view rootKey, AZStd::vector<char>& scratchBuffer);
void SignalNotifier(AZStd::string_view jsonPath, Type type);
mutable AZStd::recursive_mutex m_settingMutex;
mutable AZStd::recursive_mutex m_notifierMutex;
NotifyEvent m_notifiers;
PreMergeEvent m_preMergeEvent;
PostMergeEvent m_postMergeEvent;
rapidjson::Document m_settings;
JsonSerializerSettings m_serializationSettings;
JsonDeserializerSettings m_deserializationSettings;
JsonApplyPatchSettings m_applyPatchSettings;
};
} // namespace AZ
| 50.604839 | 136 | 0.730359 |
0371413b3ec6e6d553c9e839ddc098efbd1ae937 | 3,811 | h | C | Three/include/CGAL/Three/Three.h | baumhaus-project/cgal | f6f405009cbb8e682b088138d894429879d31d91 | [
"CC0-1.0"
] | 1 | 2019-04-08T23:06:26.000Z | 2019-04-08T23:06:26.000Z | Three/include/CGAL/Three/Three.h | baumhaus-project/cgal | f6f405009cbb8e682b088138d894429879d31d91 | [
"CC0-1.0"
] | 17 | 2018-01-10T13:32:24.000Z | 2021-07-30T12:23:20.000Z | Three/include/CGAL/Three/Three.h | baumhaus-project/cgal | f6f405009cbb8e682b088138d894429879d31d91 | [
"CC0-1.0"
] | 1 | 2019-02-21T15:26:25.000Z | 2019-02-21T15:26:25.000Z | // Copyright (c) 2018 GeometryFactory Sarl (France)
// All rights reserved.
//
// This file is part of CGAL (www.cgal.org).
//
// $URL$
// $Id$
// SPDX-License-Identifier: GPL-3.0-or-later OR LicenseRef-Commercial
//
//
// Author(s) : Maxime GIMENO
#ifndef THREE_H
#define THREE_H
#include <CGAL/license/Three.h>
#include <QString>
#include <QObject>
#include <QDockWidget>
#include <CGAL/Three/Scene_interface.h>
#include <CGAL/Three/Viewer_interface.h>
#include <QMainWindow>
#include <QApplication>
#ifdef three_EXPORTS
# define THREE_EXPORT Q_DECL_EXPORT
#else
# define THREE_EXPORT Q_DECL_IMPORT
#endif
#if QT_VERSION < QT_VERSION_CHECK(5, 15, 0)
#define CGAL_QT_SKIP_EMPTY_PARTS QString::SkipEmptyParts
#else
#define CGAL_QT_SKIP_EMPTY_PARTS ::Qt::SkipEmptyParts
#endif
namespace CGAL{
namespace Three{
//define enum depending on Qt version
class Polyhedron_demo_plugin_interface;
class THREE_EXPORT Three{
public:
Three();
virtual ~Three(){}
static QMainWindow* mainWindow();
static Viewer_interface* mainViewer();
static Viewer_interface* currentViewer();
static void setCurrentViewer(CGAL::Three::Viewer_interface* viewer);
static Viewer_interface* activeViewer();
static Scene_interface* scene();
static QObject* connectableScene();
static RenderingMode defaultSurfaceMeshRenderingMode();
static RenderingMode defaultPointSetRenderingMode();
static QString modeName(RenderingMode mode);
static RenderingMode modeFromName(QString name);
static int getDefaultPointSize();
static int getDefaultNormalLength();
static int getDefaultLinesWidth();
/*! \brief Adds a dock widget to the interface
*
* Adds a dock widget in the left section of the MainWindow. If the slot is already
* taken, the dock widgets will be tabified.
*/
void addDockWidget(QDockWidget* dock_widget);
/*! \brief gets an item of the templated type.
* \returns the first `SceneType` item found in the scene's list of currently selected
* items;
* \returns nullptr if there is no `SceneType` in the list.
*/
template<class SceneType>
static SceneType* getSelectedItem();
/*! \brief Automatically connects each action of `plugin` to the corresponding slot.
*
* \attention Each action named `ActionName` in the plugin's `actions()` list must have
* a corresponding slot named `on_ActionsName_triggered()`
* in the plugin.
*/
static void autoConnectActions(CGAL::Three::Polyhedron_demo_plugin_interface* plugin);
/*!
* Displays in the console a blue text preceded by the mention
* "INFO: ".
*/
static void information(QString);
/*!
* Displays in the console an orange text preceded by the mention "WARNING: ".
*/
static void warning(QString);
/*!
* Displays in the console a red text preceded by the mention "ERROR: ".
*/
static void error(QString);
/*!
* Displays an information popup.
*/
static void information(QString title, QString message);
/*!
* Displays a warning popup.
*/
static void warning(QString title, QString message);
/*!
* Displays an error popup.
*/
static void error(QString title, QString message);
protected:
static QMainWindow* s_mainwindow;
static Viewer_interface* s_mainviewer;
static Viewer_interface* s_currentviewer;
static Scene_interface* s_scene;
static QObject* s_connectable_scene;
static Three* s_three;
static RenderingMode s_defaultSMRM;
static RenderingMode s_defaultPSRM;
static int default_point_size;
static int default_normal_length;
static int default_lines_width;
public:
struct CursorScopeGuard
{
CursorScopeGuard(QCursor cursor)
{
QApplication::setOverrideCursor(cursor);
}
~CursorScopeGuard()
{
QApplication::restoreOverrideCursor();
}
};
};
}
}
#endif // THREE_H
| 27.615942 | 89 | 0.733141 |
0374aea5f1b3bf825f921fa2dea02e1f90815d2f | 4,260 | h | C | src/parser/minc/MincValue.h | MichelVazirani/RTcmix | cfe24ba27154b000393005df9aa00d2b3a17282c | [
"Apache-2.0"
] | null | null | null | src/parser/minc/MincValue.h | MichelVazirani/RTcmix | cfe24ba27154b000393005df9aa00d2b3a17282c | [
"Apache-2.0"
] | null | null | null | src/parser/minc/MincValue.h | MichelVazirani/RTcmix | cfe24ba27154b000393005df9aa00d2b3a17282c | [
"Apache-2.0"
] | null | null | null | //
// MincValue.h
// RTcmix
//
// Created by Douglas Scott on 12/30/19.
//
#ifndef MincValue_h
#define MincValue_h
#include "minc_internal.h"
#include <stddef.h>
#include <map>
/* A MincList contains an array of MincValues, whose underlying data
type is flexible. So a MincList is an array of arbitrarily mixed types
(any of the types represented in the MincDataType enum), and it can
support nested lists.
*/
class MincValue;
class MincList : public MincObject, public RefCounted
{
public:
MincList(int len=0);
void resize(int newLen);
int len; /* number of MincValue's in <data> array */
MincValue *data;
protected:
virtual ~MincList();
};
/* A MincMap is a set of MincValues, like a MincList, except they can be
set and retrieved via MincValue "keys". Like lists, they support mixed
types.
*/
class MincMap : public MincObject, public RefCounted
{
private:
struct MincValueCmp {
bool operator()(const MincValue& lhs, const MincValue& rhs) const;
};
public:
MincMap();
int len() const { return (int) map.size(); }
std::map<MincValue, MincValue, MincValueCmp> map;
void print();
protected:
virtual ~MincMap();
};
// A MincStruct contains a Symbol pointer which points to a linked list of Symbols
// which represent the elements of a particular MinC-defined struct.
class Symbol;
class MincStruct : public MincObject, public RefCounted
{
public:
MincStruct() : _memberList(NULL) {}
~MincStruct();
Symbol * addMember(const char *name, MincDataType type, int scope);
Symbol * lookupMember(const char *name);
Symbol * members() { return _memberList; }
void print();
protected:
Symbol * _memberList;
};
class MincValue {
public:
MincValue() : type(MincVoidType) { _u.list = NULL; }
MincValue(MincFloat f) : type(MincFloatType) { _u.number = f; }
MincValue(MincString s) : type(MincStringType) { _u.string = s; }
MincValue(MincHandle h);
MincValue(MincList *l);
MincValue(MincMap *m);
MincValue(MincStruct *str);
MincValue(MincDataType type);
MincValue(const MincValue &rhs);
~MincValue();
const MincValue& operator = (const MincValue &rhs);
const MincValue& operator = (MincFloat f);
const MincValue& operator = (MincString s);
const MincValue& operator = (MincHandle h);
const MincValue& operator = (MincList *l);
const MincValue& operator = (MincMap *m);
const MincValue& operator += (const MincValue &rhs);
const MincValue& operator -= (const MincValue &rhs);
const MincValue& operator *= (const MincValue &rhs);
const MincValue& operator /= (const MincValue &rhs);
const MincValue& operator[] (const MincValue &index) const; // for MincList,MincMap access
MincValue& operator[] (const MincValue &index); // for MincList, MincMap access
operator MincFloat() const { return _u.number; }
operator MincString() const { return _u.string; }
operator MincHandle() const { return _u.handle; }
operator MincList *() const { return _u.list; }
operator MincMap *() const { return _u.map; }
operator MincStruct *() const { return _u.mstruct; }
operator bool() const { return (type == MincFloatType) ? _u.number != 0.0 : _u.string != NULL; }
unsigned long long rawValue() const { return _u.raw; }
bool operator == (const MincValue &rhs) const;
bool operator != (const MincValue &rhs) const;
bool operator < (const MincValue &rhs) const;
bool operator > (const MincValue &rhs) const;
bool operator <= (const MincValue &rhs) const;
bool operator >= (const MincValue &rhs) const;
MincDataType dataType() const { return type; }
void zero() { _u.list = NULL; } // zeroes without changing type
void print();
private:
void doClear();
void doCopy(const MincValue &rhs);
bool validType(unsigned allowedTypes) const;
MincDataType type;
union {
MincFloat number;
MincString string;
MincHandle handle;
MincList *list;
MincMap *map;
MincStruct *mstruct;
unsigned long long raw; // used for raw comparison
} _u;
};
#endif /* MincValue_h */
| 31.555556 | 100 | 0.660094 |
03781f4e1af2d1e95f3c1d3c1fe971a0a2046af1 | 31,127 | h | C | src/include/carmi.h | J-Y2020/CARMI | 17c18dc5d615fdcf2d9e3086f9cc476a721a4d9b | [
"MIT"
] | null | null | null | src/include/carmi.h | J-Y2020/CARMI | 17c18dc5d615fdcf2d9e3086f9cc476a721a4d9b | [
"MIT"
] | null | null | null | src/include/carmi.h | J-Y2020/CARMI | 17c18dc5d615fdcf2d9e3086f9cc476a721a4d9b | [
"MIT"
] | null | null | null | /**
* @file carmi.h
* @author Jiaoyi
* @brief
* @version 0.1
* @date 2021-03-11
*
* @copyright Copyright (c) 2021
*
*/
#ifndef SRC_INCLUDE_CARMI_H_
#define SRC_INCLUDE_CARMI_H_
#include <float.h>
#include <algorithm>
#include <map>
#include <utility>
#include <vector>
#include "./params.h"
#include "baseNode.h"
#include "construct/structures.h"
#include "dataManager/empty_block.h"
#define log2(value) log(value) / log(2)
template <typename KeyType, typename ValueType>
class CARMI {
public:
typedef std::pair<KeyType, ValueType> DataType;
typedef std::vector<DataType> DataVectorType;
public:
CARMI();
/**
* @brief Construct a new CARMI object for carmi_common
*
* @param initData the dataset used to initialize carmi
* @param findData the read query
* @param insertData the write query
* @param insertIndex the index of each write query
* @param lambda lambda
*/
CARMI(DataVectorType &initData, DataVectorType &findData,
DataVectorType &insertData, std::vector<int> &insertIndex,
double lambda);
/**
* @brief Construct a new CARMI object for carmi_external
*
* @param dataset the pointer of the dataset
* @param initData the dataset used to initialize carmi
* @param findData the read query
* @param insertData the write query
* @param insertIndex the index of each write query
* @param lambda lambda
* @param record_number the number of the records
* @param record_len the length of a record (byte)
*/
CARMI(const void *dataset, DataVectorType &initData, DataVectorType &findData,
DataVectorType &insertData, std::vector<int> &insertIndex,
double lambda, int record_number, int record_len);
// main functions
public:
/**
* @brief find a record of the given key
*
* @param key
* @param currunion the index of the second layer of the leaf node
* @param currslot the index of the slot in a leaf node
* @return BaseNode<KeyType>*
*/
BaseNode<KeyType> *Find(KeyType key, int *currunion, int *currslot);
/**
* @brief insert a data point
*
* @param data
* @return true if the insertion is successful
* @return false if the operation fails
*/
bool Insert(DataType data);
/**
* @brief update a record of the given key
*
* @param data
* @return true if the operation succeeds
* @return false if the operation fails
*/
bool Update(DataType data);
/**
* @brief delete the record of the given key
*
* @param key
* @return true deletion is successful
* @return false the operation fails
*/
bool Delete(KeyType key);
/**
* @brief calculate the space of CARMI
*
* @return long double the space
*/
long double CalculateSpace() const;
/**
* @brief print the structure of CARMI
*
* @param level the current level
* @param type the type of root node
* @param idx the index of the node
* @param levelVec used to record the level of CARMI
* @param nodeVec used to record the number of each type of CARMI's node
*/
void PrintStructure(int level, NodeType type, int dataSize, int idx,
std::vector<int> *levelVec, std::vector<int> *nodeVec);
// construction algorithms
// main function
/**
* @brief main function of construction
*/
void Construction();
public:
/**
* @brief initialize entireData
*
* @param size the size of data points
*/
void InitEntireData(int size);
/**
* @brief initialize entireChild
*
*/
void InitEntireChild();
private:
// root
/**
* @brief determine whether the current setting is
* better than the previous optimal setting (more details)
*
* @tparam TYPE the typename of this node
* @tparam ModelType the typename of the model in this node
* @param c the child number of this node
* @param type the type of this node
* @param time_cost the time cost of this node
* @param optimalCost the previous optimal setting
* @param rootStruct used to record the optimal setting
*/
template <typename TYPE, typename ModelType>
void IsBetterRoot(int c, NodeType type, double time_cost, double *optimalCost,
RootStruct *rootStruct);
/**
* @brief traverse all possible settings to find the optimal root
*
* @return the type and childNumber of the optimal root
*/
RootStruct ChooseRoot();
/**
* @brief construct the root
*
* @tparam TYPE the type of the constructed root node
* @tparam ModelType the type of the model in the root node
* @param rootStruct the optimal setting of root
* @param range the range of data points in this node (root:0-size)
* @param subDataset the start index and size of data points in each child
* node
* @param childLeft the start index of child nodes
*
* @return TYPE return the constructed root
*/
template <typename TYPE, typename ModelType>
TYPE ConstructRoot(const RootStruct &rootStruct, const DataRange &range,
SubDataset *subDataset);
/**
* @brief store the optimal root into CARMI
*
* @param rootStruct the optimal setting of root
* @param nodeCost the cost of the index
* @return SubDataset: the range of all child node of the root node
*/
SubDataset StoreRoot(const RootStruct &rootStruct, NodeCost *nodeCost);
/**
* @brief construct each subtree using dp/greedy
*
* @param rootStruct the type and childNumber of root
* @param subDataset the left and size of data points in each child node
* @param nodeCost the space, time, cost of the index (is added ...)
*/
void ConstructSubTree(const RootStruct &rootStruct,
const SubDataset &subDataset, NodeCost *nodeCost);
private:
/**
* @brief the dynamic programming algorithm
*
* @param range the range of data points
* @return NodeCost the cost of the subtree
*/
NodeCost DP(const DataRange &range);
/**
* @brief traverse all possible settings to find the optimal inner node
*
* @param dataRange the range of data points in this node
* @return NodeCost the optimal cost of this subtree
*/
NodeCost DPInner(const DataRange &dataRange);
/**
* @brief traverse all possible settings to find the optimal leaf node
*
* @param dataRange the range of data points in this node
* @return NodeCost the optimal cost of this subtree
*/
NodeCost DPLeaf(const DataRange &dataRange);
/**
* @brief determine whether the current inner node's setting is
* better than the previous optimal setting
*
* @tparam TYPE the type of this inner node
* @param c the child number of this inner node
* @param frequency_weight the frequency weight of these queries
* @param time_cost the time cost of this inner node
* @param dataRange the range of data points in this node
* @param optimalCost the optimal cost of the previous setting
* @param optimal_node_struct the optimal setting
*/
template <typename TYPE>
void ChooseBetterInner(int c, double frequency_weight, double time_cost,
const DataRange &dataRange, NodeCost *optimalCost,
TYPE *optimal_node_struct);
private:
// greedy algorithm
/**
* @brief choose the optimal setting
*
* @tparam TYPE the type of this node
* @param c the number of child nodes
* @param frequency_weight the frequency weight of these queries
* @param time_cost the time cost of this node
* @param range the range of queries
* @param optimal_node_struct the optimal setting
* @param optimalCost the optimal cost
*/
template <typename TYPE>
void IsBetterGreedy(int c, double frequency_weight, double time_cost,
const IndexPair &range, TYPE *optimal_node_struct,
NodeCost *optimalCost);
/**
* @brief the greedy algorithm
*
* @param dataRange the range of these queries
* @return NodeCost the optimal cost of the subtree
*/
NodeCost GreedyAlgorithm(const DataRange &range);
private:
// store nodes
/**
* @brief store an inner node
*
* @tparam TYPE the type of this node
* @param range the left and size of the data points in initDataset
* @return TYPE trained node
*/
template <typename TYPE>
TYPE StoreInnerNode(const IndexPair &range, TYPE *node);
/**
* @brief store nodes
*
* @param storeIdx the index of this node being stored in entireChild
* @param optimalType the type of this node
* @param range the left and size of the data points in initDataset
*/
void StoreOptimalNode(int storeIdx, const DataRange &range);
private:
// manage entireData and entireChild
/**
* @brief allocate a block to the current leaf node
*
* @param size the size of the leaf node needs to be allocated
* @return int return idx (if it fails, return -1)
*/
int AllocateMemory(int size);
/**
* @brief release the specified space
*
* @param left the left index
* @param size the size
*/
void ReleaseMemory(int left, int size);
public:
/**
* @brief find the actual size in emptyBlocks
*
* @param size the size of the data points
* @return int the index in emptyBlocks
*/
int GetActualSize(int size);
/**
* @brief allocate empty blocks into emptyBlocks[i]
*
* @param left the beginning idx of empty blocks
* @param len the length of the blocks
* @return true allocation is successful
* @return false fails to allocate all blocks
*/
bool AllocateEmptyBlock(int left, int len);
/**
* @brief allocate a block to this leaf node
*
* @param idx the idx in emptyBlocks
* @return int return idx (if it fails, return -1)
*/
int AllocateSingleMemory(int *idx);
/**
* @brief allocate a block to the current inner node
*
* @param size the size of the inner node needs to be allocated
* @return int the starting position of the allocation, return -1, if it fails
*/
int AllocateChildMemory(int size);
private:
// minor functions
/**
* @brief calculate the frequency weight
*
* @param dataRange the left and size of data points
* @return double frequency weight
*/
double CalculateFrequencyWeight(const DataRange &dataRange);
/**
* @brief calculate the entropy of this node
*
* @param size the size of the entire data points
* @param childNum the child number of this node
* @param perSize the size of each child
* @return double entropy
*/
double CalculateEntropy(int size, int childNum,
const std::vector<IndexPair> &perSize) const;
/**
* @brief use this node to split the data points
*
* @tparam TYPE the type of this node
* @param node used to split dataset
* @param range the left and size of these data points
* @param dataset partitioned dataset
* @param subData the left and size of each sub dataset after being split
*/
template <typename TYPE>
void NodePartition(const TYPE &node, const IndexPair &range,
const DataVectorType &dataset,
std::vector<IndexPair> *subData) const;
/**
* @brief train the given node and use it to divide initDataset,
* trainFindQuery and trainTestQuery
*
* @tparam TYPE the type of this node
* @param c the child number of this node
* @param range the left and size of the data points
* @param subDataset the left and size of each sub dataset after being split
* @return TYPE node
*/
template <typename TYPE>
TYPE InnerDivideAll(int c, const DataRange &range, SubDataset *subDataset);
/**
* @brief construct the empty node and insert it into map
*
* @param range the left and size of data points
*/
void ConstructEmptyNode(const DataRange &range);
/**
* @brief update the previousLeaf and nextLeaf of each leaf nodes
*
*/
void UpdateLeaf();
/**
* @brief train the parameters of linear regression model
*
* @param left the start index of data points
* @param size the size of data points
* @param dataset
* @param a parameter A of LR model
* @param b parameter B of LR model
*/
void LRTrain(const int left, const int size, const DataVectorType &dataset,
float *a, float *b);
/**
* @brief extract data points (delete useless gaps and deleted data points)
*
* @param left the left index of the data points
* @param size the size of the entire data points
* @param dataset
* @param actual the actual size of these data points
* @return DataVectorType pure data points
*/
DataVectorType ExtractData(const int left, const int size,
const DataVectorType &dataset, int *actual);
/**
* @brief extract data points (delete useless gaps and deleted data points)
*
* @param unionleft the left index of the union structure in the leaf node
* @param unionright the right index of the union structure in the leaf node
* @param actual the actual size of these data points
* @return DataVectorType: pure data points
*/
DataVectorType ExtractData(const int unionleft, const int unionright,
int *actual);
/**
* @brief set the y of each data point as a precentage of
* the entire dataset size (index / size),
* prepare for the linear regression
*
* @param left the left index of the data points
* @param size the size of the entire data points
* @param dataset
* @return DataVectorType dataset used for training
*/
DataVectorType SetY(const int left, const int size,
const DataVectorType &dataset);
/**
* @brief find the optimal error value from 0 to size
*
* @tparam TYPE the typename of this node
* @param start_idx the start index of the data points
* @param size the size of the data points
* @param dataset
* @param node used to predict the position of each data point
*/
template <typename TYPE>
void FindOptError(int start_idx, int size, const DataVectorType &dataset,
TYPE *node);
// inline float log2(double value) const { return log(value) / log(2); }
public:
// inner nodes
/**
* @brief train LR model
*
* @param left the start index of data points
* @param size the size of data points
* @param dataset
* @param lr model
*/
void Train(int left, int size, const DataVectorType &dataset, LRModel *lr);
/**
* @brief train PLR model
*
* @param left the start index of data points
* @param size the size of data points
* @param dataset
* @param plr model
*/
void Train(int left, int size, const DataVectorType &dataset, PLRModel *plr);
/**
* @brief train the histogram model
*
* @param left the start index of data points
* @param size the size of data points
* @param dataset
* @param his model
*/
void Train(int left, int size, const DataVectorType &dataset, HisModel *his);
/**
* @brief train the bs model
*
* @param left the start index of data points
* @param size the size of data points
* @param dataset
* @param bs model
*/
void Train(int left, int size, const DataVectorType &dataset, BSModel *bs);
private:
// leaf nodes
/**
* @brief initialize array node
*
* @param left the start index of data points
* @param size the size of data points
* @param dataset
* @param arr leaf node
*/
void Init(int left, int size, const DataVectorType &dataset,
ArrayType<KeyType> *arr);
/**
* @brief initialize external array node
*
* @param start_idx the start index of data points
* @param size the size of data points
* @param dataset
* @param ext leaf node
*/
void Init(int start_idx, int size, const DataVectorType &dataset,
ExternalArray *ext);
/**
* @brief insert a data point into the next structure in the leaf node
*
* @param data the data points needed to be inserted
* @param nowDataIdx the index of this structure in entireData
* @param currunion the index of the current structure in the leaf node
* @param node the leaf node
* @return true INSERT succeeds
* @return false INSERT fails (the next structure is full)
*/
inline bool ArrayInsertNext(const DataType &data, int nowDataIdx,
int currunion, BaseNode<KeyType> *node);
/**
* @brief if the structure and the sibling nodes are all full, this leaf node
* needs to be rebalanced
*
* @param unionleft the left index of the structure
* @param unionright the right index of the structure
* @param arr the leaf node
*/
inline void Rebalance(const int unionleft, const int unionright,
ArrayType<KeyType> *arr);
/**
* @brief if the leaf node is full but has not reached KMaxLeafNUm, this leaf
* node needs to be expanded
*
* @param unionleft the left index of the structure
* @param unionright the right index of the structure
* @param arr the leaf node
*/
inline void Expand(const int unionleft, const int unionright,
ArrayType<KeyType> *arr);
/**
* @brief Get the number of data points in entireData[unionleft, unionright)
*
* @param unionleft
* @param unionright
* @return int
*/
inline int GetDataNum(const int unionleft, const int unionright);
/**
* @brief train the external array node
*
* @param start_idx the start index of data points
* @param size the size of data points
* @param dataset
* @param ext leaf node
*/
void Train(int start_idx, int size, const DataVectorType &dataset,
ExternalArray *ext);
/**
* @brief store data points in such a way that extra data points are filled
* with the previous blocks first
*
* @param dataset the dataset to be stored
* @param neededBlockNum the number of needed blocks to store all the data
* points
* @param tmpBlockVec blocks to store data points
* @param actualBlockNum the actual number of used data blocks
* @param missNumber the number of data points which are not stored as the
* prefetching index
* @return true
* @return false
*/
inline bool StorePrevious(
const DataVectorType &dataset, int neededLeafNum,
std::vector<LeafSlots<KeyType, ValueType>> *tmpBlockVec,
int *actualBlockNum, int *missNumber);
/**
* @brief store data points in such a way that extra data points are filled
* with the subsequent blocks first
*
* @param dataset the dataset to be stored
* @param neededBlockNum the number of needed blocks to store all the data
* points
* @param tmpBlockVec blocks to store data points
* @param actualBlockNum the actual number of used data blocks
* @param missNumber the number of data points which are not stored as the
* prefetching index
* @return true
* @return false
*/
inline bool StoreSubsequent(
const DataVectorType &dataset, int neededLeafNum,
std::vector<LeafSlots<KeyType, ValueType>> *tmpBlockVec,
int *actualBlockNum, int *missNumber);
/**
* @brief calculate the cost of the array node
*
* @param size the size of the data points
* @param givenBlockNum the allocated number of data blocks
* @return cost = time + kRate * space
*/
double CalculateArrayCost(int size, int totalSize, int givenBlockNum);
/**
* @brief check whether this array node can be prefetched
*
* @param neededBlockNum the needed number of leaf nodes
* @param start_idx the start index of data points
* @param size the size of data points
* @param dataset
*/
bool CheckIsPrefetch(int neededLeafNum, int left, int size,
const DataVectorType &dataset);
public:
/**
* @brief store data points into the entireData
*
* @param neededBlockNum the needed number of leaf nodes
* @param start_idx the start index of data points
* @param size the size of data points
* @param dataset
* @param arr leaf node
*/
bool StoreData(int needLeafNum, int start_idx, int size,
const DataVectorType &dataset, ArrayType<KeyType> *arr);
private:
// for public functions
/**
* @brief search a key-value through binary search
*
* @param key
* @param start
* @param end
* @return int the index of the key
*/
int ArrayBinarySearch(double key, int start, int end) const;
/**
* @brief search a key-value through binary search in the external leaf node
*
* @param key
* @param start
* @param end
* @return int the idx of the first element >= key
*/
int ExternalBinarySearch(double key, int start, int end) const;
public:
/**
* @brief binary search within a structure
*
* @param node the current node
* @param key
* @return int: the index of the given key
*/
int SlotsUnionSearch(const LeafSlots<KeyType, ValueType> &node, KeyType key);
/**
* @brief insert the given data into a leaf node
*
* @param data
* @param currunion the index of current structure
* @param node the structure where the data will be inserted
* @param arr the leaf node
* @return true
* @return false
*/
bool SlotsUnionInsert(const DataType &data, int currunion,
LeafSlots<KeyType, ValueType> *node,
BaseNode<KeyType> *arr);
/**
* @brief the main function of search a record in array
*
* @param key the key value
* @param preIdx the predicted index of this node
* @param error the error bound of this node
* @param left the left index of this node in the entireData
* @param size the size of this node
* @return int the index of the record
*/
int ArraySearch(double key, int preIdx, int error, int left, int size) const;
/**
* @brief the main function of search a record in external array
*
* @param key the key value
* @param preIdx the predicted index of this node
* @param error the error bound of this node
* @param left the left index of this node in the entireData
* @param size the size of this node
* @return int the index of the record
*/
int ExternalSearch(double key, int preIdx, int error, int left,
int size) const;
/**
* @brief split the current leaf node into an inner node and several leaf
* nodes
*
* @tparam TYPE the type of the current leaf node
* @param isExternal check whether the current node is the external array
* @param left the left index of this node in the entireData
* @param size the size of this node
* @param previousIdx the index of the previous leaf node
* @param idx the index of the current leaf node
*/
template <typename TYPE>
void Split(bool isExternal, int left, int size, int previousIdx, int idx);
/**
* @brief print the root node
*
* @param level the current level
* @param levelVec used to record the level of CARMI
* @param nodeVec used to record the number of each type of CARMI's node
*/
void PrintRoot(int level, int dataSize, std::vector<int> *levelVec,
std::vector<int> *nodeVec);
/**
* @brief print the inner node
*
* @param level the current level
* @param idx the index of the node
* @param levelVec used to record the level of CARMI
* @param nodeVec used to record the number of each type of CARMI's node
*/
void PrintInner(int level, int dataSize, int idx, std::vector<int> *levelVec,
std::vector<int> *nodeVec);
public:
std::vector<BaseNode<KeyType>> entireChild;
// for carmi_common
std::vector<LeafSlots<KeyType, ValueType>> entireData;
// int nowBlockTail;
int nowDataSize; // the used size of entireData to store data points
// for carmi_tree
const void *external_data;
int prefetchEnd;
int recordLength;
double sumDepth;
unsigned int nowChildNumber; // the number of inner nodes and leaf nodes
static const int kMaxLeafNum; // the number of union in a leaf node
static const int kMaxSlotNum; // the maximum number of slots in a union
static const int kLeafMaxCapacity; // the max capacity of a leaf node
private:
CARMIRoot<DataVectorType, KeyType> root; // the root node
int rootType; // the type of the root node
double lambda; // cost = time + lambda * space
int querySize; // the total frequency of queries
int reservedSpace; // the space needed to be reserved
bool isPrimary; // whether this carmi is a primary inde
bool isInitMode;
// for carmi_common
unsigned int entireDataSize; // the size of the entireData
int firstLeaf; // the index of the first leaf node in entireChild
std::vector<EmptyBlock> emptyBlocks; // store the index of all empty
// blocks(size: 1,2^i, 3*2^i, 4096)
// for carmi_external
int curr; // the current insert index for external array
float readRate;
DataVectorType initDataset;
DataVectorType findQuery;
DataVectorType insertQuery;
std::vector<int> insertQueryIndex;
std::map<IndexPair, NodeCost> COST;
std::map<IndexPair, BaseNode<KeyType>> structMap;
std::vector<int> scanLeaf;
std::vector<std::pair<double, double>>
prefetchData; // <leaf node id, block number>
std::vector<int> remainingNode;
std::vector<DataRange> remainingRange;
std::vector<int> prefetchNode;
std::vector<DataRange> prefetchRange;
// std::map<IndexPair, BaseNode<KeyType>> remainingStruct;
BaseNode<KeyType> emptyNode;
static const IndexPair emptyRange;
static const NodeCost emptyCost;
static const int kPrefetchRange;
static const int kThreshold; // used to initialize a leaf node
static const float kDataPointSize;
static const int kHisMaxChildNumber; // the max number of children in his
static const int kBSMaxChildNumber; // the max number of children in bs
static const int kMinChildNumber; // the min child number of inner nodes
static const int kInsertNewChildNumber; // the child number of when splitting
static const double kBaseNodeSpace; // MB, the size of a node
static const double kPLRRootSpace; // the space cost of lr root
public:
friend class PLRType<DataVectorType, KeyType>;
friend class LRModel;
friend class PLRModel;
friend class HisModel;
friend class BSModel;
friend class ArrayType<KeyType>;
friend class GappedArrayType;
friend class ExternalArray;
};
template <typename KeyType, typename ValueType>
const int CARMI<KeyType, ValueType>::kPrefetchRange = 2;
template <typename KeyType, typename ValueType>
const int CARMI<KeyType, ValueType>::kThreshold = 2;
template <typename KeyType, typename ValueType>
const int CARMI<KeyType, ValueType>::kHisMaxChildNumber = 256;
template <typename KeyType, typename ValueType>
const int CARMI<KeyType, ValueType>::kBSMaxChildNumber = 16;
template <typename KeyType, typename ValueType>
const int CARMI<KeyType, ValueType>::kMinChildNumber = 16;
template <typename KeyType, typename ValueType>
const int CARMI<KeyType, ValueType>::kInsertNewChildNumber = 16;
template <typename KeyType, typename ValueType>
const int CARMI<KeyType, ValueType>::kMaxLeafNum = 48 / sizeof(KeyType) + 1;
template <typename KeyType, typename ValueType>
const int CARMI<KeyType, ValueType>::kMaxSlotNum =
carmi_params::kMaxLeafNodeSize / sizeof(DataType);
template <typename KeyType, typename ValueType>
const int CARMI<KeyType, ValueType>::kLeafMaxCapacity =
CARMI<KeyType, ValueType>::kMaxSlotNum
*CARMI<KeyType, ValueType>::kMaxLeafNum;
template <typename KeyType, typename ValueType>
const IndexPair CARMI<KeyType, ValueType>::emptyRange = IndexPair(-1, 0);
template <typename KeyType, typename ValueType>
const NodeCost CARMI<KeyType, ValueType>::emptyCost = {0, 0, 0};
template <typename KeyType, typename ValueType>
const float CARMI<KeyType, ValueType>::kDataPointSize = sizeof(DataType) * 1.0 /
1024 / 1024;
template <typename KeyType, typename ValueType>
const double CARMI<KeyType, ValueType>::kBaseNodeSpace = 64.0 / 1024 / 1024;
template <typename KeyType, typename ValueType>
const double CARMI<KeyType, ValueType>::kPLRRootSpace =
sizeof(PLRType<DataVectorType, KeyType>) / 1024.0 / 1024.0;
template <typename KeyType, typename ValueType>
CARMI<KeyType, ValueType>::CARMI() {
isPrimary = false;
firstLeaf = -1;
nowDataSize = 0;
sumDepth = 0;
isInitMode = true;
prefetchEnd = -1;
emptyNode.array = ArrayType<KeyType>();
reservedSpace = 0;
readRate = 1.0;
InitEntireData(1000);
}
template <typename KeyType, typename ValueType>
CARMI<KeyType, ValueType>::CARMI(DataVectorType &initData,
DataVectorType &findData,
DataVectorType &insertData,
std::vector<int> &insertIndex, double l)
{
isPrimary = false;
lambda = l;
firstLeaf = -1;
nowDataSize = 0;
sumDepth = 0;
isInitMode = true;
prefetchEnd = -1;
initDataset = std::move(initData);
findQuery = std::move(findData);
insertQuery = std::move(insertData);
insertQueryIndex = std::move(insertIndex);
emptyNode.array = ArrayType<KeyType>();
reservedSpace = insertQuery.size() * 1.0 / initDataset.size() * 4096 * 16;
readRate = 1.0 - insertQuery.size() * 1.0 / initDataset.size();
#ifdef DEBUG
std::cout << "readRate:" << readRate << std::endl;
#endif // DEBUG
if (readRate < 1) {
readRate = std::max(readRate * 1.0, 0.95);
}
querySize = 0;
for (int i = 0; i < static_cast<int>(findQuery.size()); i++) {
querySize += findQuery[i].second;
}
for (int i = 0; i < static_cast<int>(insertQuery.size()); i++) {
querySize += insertQuery[i].second;
}
InitEntireData(initDataset.size());
InitEntireChild();
}
template <typename KeyType, typename ValueType>
CARMI<KeyType, ValueType>::CARMI(const void *dataset, DataVectorType &initData,
DataVectorType &findData,
DataVectorType &insertData,
std::vector<int> &insertIndex, double l,
int record_number, int record_len)
{
external_data = dataset;
recordLength = record_len;
curr = record_number;
sumDepth = 0;
isInitMode = true;
prefetchEnd = -1;
isPrimary = true;
lambda = l;
emptyNode.externalArray = ExternalArray(kThreshold);
nowDataSize = 0;
readRate = 1;
initDataset = std::move(initData);
findQuery = std::move(findData);
insertQuery = std::move(insertData);
insertQueryIndex = std::move(insertIndex);
reservedSpace =
static_cast<float>(insertQuery.size()) / initDataset.size() * 4096 * 16;
querySize = 0;
for (int i = 0; i < static_cast<int>(findQuery.size()); i++) {
querySize += findQuery[i].second;
}
for (int i = 0; i < static_cast<int>(insertQuery.size()); i++) {
querySize += insertQuery[i].second;
}
InitEntireChild();
}
#endif // SRC_INCLUDE_CARMI_H_
| 30.941352 | 80 | 0.675009 |
03788b270ee4f6752ac0c774cc274bdfa1fb6527 | 9,798 | h | C | src/include/access/double_write.h | opengauss-mirror/openGauss-graph | 6beb138fd00abdbfddc999919f90371522118008 | [
"MulanPSL-1.0"
] | 1 | 2021-11-05T10:14:39.000Z | 2021-11-05T10:14:39.000Z | src/include/access/double_write.h | opengauss-mirror/openGauss-graph | 6beb138fd00abdbfddc999919f90371522118008 | [
"MulanPSL-1.0"
] | null | null | null | src/include/access/double_write.h | opengauss-mirror/openGauss-graph | 6beb138fd00abdbfddc999919f90371522118008 | [
"MulanPSL-1.0"
] | null | null | null | /*
* Copyright (c) 2020 Huawei Technologies Co.,Ltd.
*
* openGauss is licensed under Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
* ---------------------------------------------------------------------------------------
*
* double_write.h
* Define some inline function of double write and export some interfaces.
*
*
* IDENTIFICATION
* src/include/access/double_write.h
*
* ---------------------------------------------------------------------------------------
*/
#ifndef DOUBLE_WRITE_H
#define DOUBLE_WRITE_H
#include "double_write_basic.h"
#include "storage/buf/buf_internals.h"
#include "storage/checksum_impl.h"
typedef enum BufTagVer {
ORIGIN_TAG = 0,
HASHBUCKET_TAG
} BufTagVer;
typedef struct st_dw_batch {
dw_page_head_t head;
uint16 page_num; /* for batch head, number of data pages */
uint16 buftag_ver;
BufferTag buf_tag[0]; /* to locate the data pages in batch */
} dw_batch_t;
typedef struct st_dw_batch_nohbkt {
dw_page_head_t head;
uint16 page_num; /* for batch head, number of data pages */
uint16 buftag_ver;
BufferTagFirstVer buf_tag[0]; /* to locate the data pages in batch */
} dw_batch_first_ver;
typedef struct dw_single_flush_item {
uint16 data_page_idx; /* from zero start, indicates the slot of the data page. */
uint16 dwn; /* double write number, updated when file header changed */
BufferTag buf_tag;
pg_crc32c crc; /* CRC of all above ... MUST BE LAST! */
}dw_single_flush_item;
/* Used by double_write to mark the buffers which are not flushed in the given buf_id array. */
static const int DW_INVALID_BUFFER_ID = -1;
/* steal high bit from pagenum as the flag of hashbucket */
#define IS_HASH_BKT_MASK (0x8000)
#define GET_REL_PGAENUM(pagenum) (pagenum & ~IS_HASH_BKT_MASK)
/**
* Dirty data pages in one batch
* The number of data pages depends on the number of BufferTag one page can hold
*/
static const uint16 DW_BATCH_DATA_PAGE_MAX =
(uint16)((BLCKSZ - sizeof(dw_batch_t) - sizeof(dw_page_tail_t)) / sizeof(BufferTag));
static const uint16 DW_BATCH_DATA_PAGE_MAX_FOR_NOHBK =
(uint16)((BLCKSZ - sizeof(dw_batch_first_ver) - sizeof(dw_page_tail_t)) / sizeof(BufferTagFirstVer));
/* 1 head + data + 1 tail */
static const uint16 DW_EXTRA_FOR_ONE_BATCH = 2;
/* 1 head + data + [1 tail, 2 head] + data + 2 tail */
static const uint16 DW_EXTRA_FOR_TWO_BATCH = 3;
static const uint16 DW_BATCH_MIN = (1 + DW_EXTRA_FOR_ONE_BATCH);
static const uint16 DW_BATCH_MAX = (DW_BATCH_DATA_PAGE_MAX + DW_EXTRA_FOR_ONE_BATCH);
/* 2 batches at most for one perform */
static const uint16 DW_DIRTY_PAGE_MAX = (DW_BATCH_DATA_PAGE_MAX + DW_BATCH_DATA_PAGE_MAX);
static const uint16 DW_BUF_MAX = (DW_DIRTY_PAGE_MAX + DW_EXTRA_FOR_TWO_BATCH);
static const uint16 DW_BATCH_MAX_FOR_NOHBK = (DW_BATCH_DATA_PAGE_MAX_FOR_NOHBK + DW_EXTRA_FOR_ONE_BATCH);
/* 2 batches at most for one perform */
static const uint16 DW_DIRTY_PAGE_MAX_FOR_NOHBK = (DW_BATCH_DATA_PAGE_MAX_FOR_NOHBK + DW_BATCH_DATA_PAGE_MAX_FOR_NOHBK);
static const uint16 DW_BUF_MAX_FOR_NOHBK = (DW_DIRTY_PAGE_MAX_FOR_NOHBK + DW_EXTRA_FOR_TWO_BATCH);
#define GET_DW_BATCH_DATA_PAGE_MAX(contain_hashbucket) (!contain_hashbucket ? DW_BATCH_DATA_PAGE_MAX_FOR_NOHBK : DW_BATCH_DATA_PAGE_MAX)
#define GET_DW_BATCH_MAX(contain_hashbucket) (!contain_hashbucket ? DW_BATCH_MAX_FOR_NOHBK : DW_BATCH_MAX)
#define GET_DW_DIRTY_PAGE_MAX(contain_hashbucket) (!contain_hashbucket ? DW_DIRTY_PAGE_MAX_FOR_NOHBK : DW_DIRTY_PAGE_MAX)
#define GET_DW_MEM_CTX_MAX_BLOCK_SIZE(contain_hashbucket) (!contain_hashbucket ? DW_MEM_CTX_MAX_BLOCK_SIZE_FOR_NOHBK : DW_MEM_CTX_MAX_BLOCK_SIZE)
/*
* 1 block for alignment, 1 for file_head, 1 for reading data_page during recovery
* and DW_BUF_MAX for double_write buffer.
*/
static const uint32 DW_MEM_CTX_MAX_BLOCK_SIZE = ((1 + 1 + 1 + DW_BUF_MAX) * BLCKSZ);
static const uint32 DW_MEM_CTX_MAX_BLOCK_SIZE_FOR_NOHBK = ((1 + 1 + 1 + DW_BUF_MAX_FOR_NOHBK) * BLCKSZ);
const uint16 SINGLE_BLOCK_TAG_NUM = BLCKSZ / sizeof(dw_single_flush_item);
static const uint32 DW_BOOTSTRAP_VERSION = 91261;
const uint32 DW_SUPPORT_SINGLE_FLUSH_VERSION = 92266;
/* dw single flush file information */
/* file head + storage buffer tag page + data page */
const int DW_SINGLE_FILE_SIZE = (1 + 161 + 32768) * 8192;
/* Reserve 8 bytes for bufferTag upgrade. now usepage num is 32768 * sizeof(dw_single_flush_item) / 8192 */
const int DW_SINGLE_BUFTAG_PAGE_NUM = 161;
const int DW_SINGLE_DIRTY_PAGE_NUM = 32768;
inline bool dw_buf_valid_dirty(uint32 buf_state)
{
return ((buf_state & (BM_VALID | BM_DIRTY)) == (BM_VALID | BM_DIRTY));
}
inline bool dw_buf_ckpt_needed(uint32 buf_state)
{
return ((buf_state & (BM_VALID | BM_DIRTY | BM_CHECKPOINT_NEEDED)) == (BM_VALID | BM_DIRTY | BM_CHECKPOINT_NEEDED));
}
inline bool dw_verify_file_head_checksum(dw_file_head_t* file_head)
{
uint32 checksum;
uint16 org_cks = file_head->tail.checksum;
file_head->tail.checksum = 0;
checksum = pg_checksum_block((char*)file_head, sizeof(dw_file_head_t));
file_head->tail.checksum = org_cks;
return (org_cks == REDUCE_CKS2UINT16(checksum));
}
inline bool dw_verify_file_head(dw_file_head_t* file_head)
{
return file_head->head.dwn == file_head->tail.dwn && dw_verify_file_head_checksum(file_head);
}
inline void dw_calc_file_head_checksum(dw_file_head_t* file_head)
{
uint32 checksum;
file_head->tail.checksum = 0;
checksum = pg_checksum_block((char*)file_head, sizeof(dw_file_head_t));
file_head->tail.checksum = REDUCE_CKS2UINT16(checksum);
}
inline bool dw_verify_batch_checksum(dw_batch_t* batch)
{
uint32 checksum;
uint16 org_cks = DW_PAGE_CHECKSUM(batch);
DW_PAGE_CHECKSUM(batch) = 0;
checksum = pg_checksum_block((char*)batch, BLCKSZ);
DW_PAGE_CHECKSUM(batch) = org_cks;
return (org_cks == REDUCE_CKS2UINT16(checksum));
}
inline bool dw_verify_page(dw_batch_t* page)
{
return (page)->head.dwn == DW_PAGE_TAIL(page)->dwn && dw_verify_batch_checksum(page);
}
inline void dw_calc_batch_checksum(dw_batch_t* batch)
{
uint32 checksum;
DW_PAGE_CHECKSUM(batch) = 0;
checksum = pg_checksum_block((char*)batch, BLCKSZ);
DW_PAGE_CHECKSUM(batch) = REDUCE_CKS2UINT16(checksum);
}
inline dw_batch_t* dw_batch_tail_page(dw_batch_t* head_page)
{
return (dw_batch_t*)((char*)head_page + BLCKSZ * (GET_REL_PGAENUM(head_page->page_num) + 1));
}
/**
* verify the batch head and tail page, including dwn and checksum
* @param head_page batch head
* @param dwn double write number
* @return true dwn and checksum match
*/
inline bool dw_verify_batch(dw_batch_t* head_page, uint16 dwn)
{
if (head_page->head.dwn == dwn && dw_verify_page(head_page)) {
dw_batch_t* tail_page = dw_batch_tail_page(head_page);
return tail_page->head.dwn == dwn && dw_verify_page(tail_page);
}
return false;
}
inline uint64 dw_page_distance(void* left, void* right)
{
return ((char*)right - (char*)left) / BLCKSZ;
}
int64 dw_seek_file(int fd, int64 offset, int32 origin);
void dw_pread_file(int fd, void* buf, int size, int64 offset);
void dw_pwrite_file(int fd, const void* buf, int size, int64 offset);
/**
* generate the file for the database first boot
*/
void dw_bootstrap();
/**
* do the memory allocate, spin_lock init, LWLock assign and double write recovery
* all the half-written pages should be recovered after this
* it should be finished before XLOG module start which may replay redo log
*/
void dw_init(bool shutdown);
/**
* double write only work when incremental checkpoint enabled and double write enabled
* @return true if both enabled
*/
inline bool dw_enabled()
{
return (
g_instance.attr.attr_storage.enableIncrementalCheckpoint && g_instance.attr.attr_storage.enable_double_write);
}
/**
* flush the buffers identified by the buf_id in buf_id_arr to double write file
* a token_id is returned, thus double write wish the caller to return it after the
* caller finish flushing the buffers to data file and forwarding the fsync request
* @param buf_id_arr the buffer id array which is used to get page from global buffer
* @param size the array size
*/
void dw_perform_batch_flush(uint32 size, CkptSortItem *dirty_buf_list, ThrdDwCxt* thrd_dw_cxt);
/**
* truncate the pages in double write file after ckpt or before exit
* wait for tokens, thus all the relative data file flush and fsync request forwarded
* then its safe to call fsync to make sure pages on data file
* and then safe to discard those pages on double write file
*/
void dw_truncate();
/**
* double write exit after XLOG exit.
* data file flushing, page writer and checkpointer thread may still running. wait for them.
*/
void dw_exit(bool single);
/**
* If double write is enabled and pagewriter is running,
* the dirty pages should only be flushed by pagewriter.
*/
inline bool dw_page_writer_running()
{
return (dw_enabled() && pg_atomic_read_u32(&g_instance.ckpt_cxt_ctl->current_page_writer_count) > 0);
}
extern uint16 dw_single_flush(BufferDesc *buf_desc);
extern bool dw_single_file_recycle(bool trunc_file);
extern bool backend_can_flush_dirty_page();
extern void dw_force_reset_single_file();
extern void reset_dw_pos_flag();
extern void clean_proc_dw_buf();
extern void init_proc_dw_buf();
#endif /* DOUBLE_WRITE_H */
| 34.621908 | 145 | 0.739743 |
03793a3a20c59b23a6386b615cecabace8bfead4 | 723 | c | C | gcc-gcc-7_3_0-release/gcc/testsuite/gcc.target/i386/avx512dq-vpmovd2m-1.c | best08618/asylo | 5a520a9f5c461ede0f32acc284017b737a43898c | [
"Apache-2.0"
] | 7 | 2020-05-02T17:34:05.000Z | 2021-10-17T10:15:18.000Z | gcc-gcc-7_3_0-release/gcc/testsuite/gcc.target/i386/avx512dq-vpmovd2m-1.c | best08618/asylo | 5a520a9f5c461ede0f32acc284017b737a43898c | [
"Apache-2.0"
] | null | null | null | gcc-gcc-7_3_0-release/gcc/testsuite/gcc.target/i386/avx512dq-vpmovd2m-1.c | best08618/asylo | 5a520a9f5c461ede0f32acc284017b737a43898c | [
"Apache-2.0"
] | 2 | 2020-07-27T00:22:36.000Z | 2021-04-01T09:41:02.000Z | /* { dg-do compile } */
/* { dg-options "-mavx512dq -mavx512vl -O2" } */
/* { dg-final { scan-assembler-times "vpmovd2m\[ \\t\]+\[^\{\n\]*%xmm\[0-9\]+\[^\n\]*%k\[1-7\](?:\n|\[ \\t\]+#)" 1 } } */
/* { dg-final { scan-assembler-times "vpmovd2m\[ \\t\]+\[^\{\n\]*%ymm\[0-9\]+\[^\n\]*%k\[1-7\](?:\n|\[ \\t\]+#)" 1 } } */
/* { dg-final { scan-assembler-times "vpmovd2m\[ \\t\]+\[^\{\n\]*%zmm\[0-9\]+\[^\n\]*%k\[1-7\](?:\n|\[ \\t\]+#)" 1 } } */
#include <immintrin.h>
volatile __m512i x512;
volatile __m256i x256;
volatile __m128i x128;
volatile __mmask8 m8;
volatile __mmask16 m16;
void extern
avx512dq_test (void)
{
m8 = _mm_movepi32_mask (x128);
m8 = _mm256_movepi32_mask (x256);
m16 = _mm512_movepi32_mask (x512);
}
| 32.863636 | 121 | 0.547718 |
037be7d37f6eb9f9762466c7817fc22562e4ddf6 | 499 | h | C | SDK/GUI/FontStyle.h | victor-timoshin/SWAY-GameFramework | 9c775354b313d00f6e4a83072aa5cf33a424a804 | [
"MIT"
] | null | null | null | SDK/GUI/FontStyle.h | victor-timoshin/SWAY-GameFramework | 9c775354b313d00f6e4a83072aa5cf33a424a804 | [
"MIT"
] | null | null | null | SDK/GUI/FontStyle.h | victor-timoshin/SWAY-GameFramework | 9c775354b313d00f6e4a83072aa5cf33a424a804 | [
"MIT"
] | null | null | null | #ifndef FONTSTYLE_H
#define FONTSTYLE_H
#include "HorizontalAlign.h"
#include "VerticalAlign.h"
namespace GUI
{
typedef struct FontStyle
{
Math::Color textColor; // Цвет текста.
Math::Color outlineColor; // Цвет обводки.
int outlineThickness; // Толщина обводки.
Math::Color shadowColor; // Цвет тени.
HORIZONTAL_ALIGN horizontalAlign; // Горизонтальное выравнивание.
VERTICAL_ALIGN verticalAlign; // Вертикальное выравнивание.
} LFONT_STYLE, *PFONT_STYLE;
}
#endif // FONTSTYLE_H | 24.95 | 67 | 0.759519 |
037d72f1bbf97ccf60a003403791d20ae502002e | 1,323 | h | C | searchlib/src/vespa/searchlib/queryeval/irequestcontext.h | renedlog/vespa | 81b982b28d6f00586d621602bd867834ec150419 | [
"Apache-2.0"
] | 1 | 2020-06-02T13:28:29.000Z | 2020-06-02T13:28:29.000Z | searchlib/src/vespa/searchlib/queryeval/irequestcontext.h | renedlog/vespa | 81b982b28d6f00586d621602bd867834ec150419 | [
"Apache-2.0"
] | null | null | null | searchlib/src/vespa/searchlib/queryeval/irequestcontext.h | renedlog/vespa | 81b982b28d6f00586d621602bd867834ec150419 | [
"Apache-2.0"
] | null | null | null | // Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#pragma once
#include <vespa/vespalib/stllike/string.h>
namespace search::attribute { class IAttributeVector; }
namespace vespalib::eval { struct Value; }
namespace vespalib { class Doom; }
namespace search::queryeval {
/**
* Provides a context that follows the life of a query.
*/
class IRequestContext
{
public:
virtual ~IRequestContext() { }
/**
* Provides the time of soft doom for the query. Now it is time to start cleaning up and return what you have.
* @return time of soft doom.
*/
virtual const vespalib::Doom & getDoom() const = 0;
/**
* Provide access to attributevectors
* @return AttributeVector or nullptr if it does not exist.
*/
virtual const attribute::IAttributeVector *getAttribute(const vespalib::string &name) const = 0;
virtual const attribute::IAttributeVector *getAttributeStableEnum(const vespalib::string &name) const = 0;
/**
* Returns the tensor of the given name that was passed with the query.
* Returns nullptr if the tensor is not found or if it is not a tensor.
*/
virtual std::unique_ptr<vespalib::eval::Value> get_query_tensor(const vespalib::string& tensor_name) const = 0;
};
}
| 31.5 | 118 | 0.706727 |
037eea231c38a168c0ac7833aacc6d127866dbcf | 526 | h | C | AliPayForDebug/AliPayForDebug/AlipayWallet_Headers/TNPageOptionMenuButtonLogic.h | ceekay1991/AliPayForDebug | 5795e5db31e5b649d4758469b752585e63e84d94 | [
"MIT"
] | 5 | 2020-03-29T12:08:37.000Z | 2021-05-26T05:20:11.000Z | AliPayForDebug/AliPayForDebug/AlipayWallet_Headers/TNPageOptionMenuButtonLogic.h | ceekay1991/AliPayForDebug | 5795e5db31e5b649d4758469b752585e63e84d94 | [
"MIT"
] | null | null | null | AliPayForDebug/AliPayForDebug/AlipayWallet_Headers/TNPageOptionMenuButtonLogic.h | ceekay1991/AliPayForDebug | 5795e5db31e5b649d4758469b752585e63e84d94 | [
"MIT"
] | 5 | 2020-04-17T03:24:04.000Z | 2022-03-30T05:42:17.000Z | //
// Generated by class-dump 3.5 (64 bit) (Debug version compiled Sep 17 2017 16:24:48).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by Steve Nygard.
//
#import <objc/NSObject.h>
@class TNPageViewController;
@interface TNPageOptionMenuButtonLogic : NSObject
{
TNPageViewController *_viewController;
}
@property(nonatomic) __weak TNPageViewController *viewController; // @synthesize viewController=_viewController;
- (void).cxx_destruct;
- (void)onOptionMenuClick:(long long)arg1;
@end
| 23.909091 | 112 | 0.743346 |
037f24366a89b6c093a9e261255ba0fc2a3a2f22 | 6,196 | c | C | Core/GUIX/common/src/gxe_text_button_create.c | xiaofei558008/STM32F407_Explorer_ThreadX | 3990aaae4aa5444dc5a494c063f137995f6ed1fe | [
"MIT"
] | 13 | 2020-06-25T15:47:11.000Z | 2022-01-13T06:41:50.000Z | Core/GUIX/common/src/gxe_text_button_create.c | wangyuew/STM32F407_Explorer_ThreadX | 3990aaae4aa5444dc5a494c063f137995f6ed1fe | [
"MIT"
] | null | null | null | Core/GUIX/common/src/gxe_text_button_create.c | wangyuew/STM32F407_Explorer_ThreadX | 3990aaae4aa5444dc5a494c063f137995f6ed1fe | [
"MIT"
] | 6 | 2020-07-16T06:00:05.000Z | 2022-01-23T00:05:08.000Z | /**************************************************************************/
/* */
/* Copyright (c) Microsoft Corporation. All rights reserved. */
/* */
/* This software is licensed under the Microsoft Software License */
/* Terms for Microsoft Azure RTOS. Full text of the license can be */
/* found in the LICENSE file at https://aka.ms/AzureRTOS_EULA */
/* and in the root directory of this software. */
/* */
/**************************************************************************/
/**************************************************************************/
/**************************************************************************/
/** */
/** GUIX Component */
/** */
/** Text Button Management (Button) */
/** */
/**************************************************************************/
#define GX_SOURCE_CODE
/* Include necessary system files. */
#include "gx_api.h"
#include "gx_button.h"
GX_CALLER_CHECKING_EXTERNS
/**************************************************************************/
/* */
/* FUNCTION RELEASE */
/* */
/* _gxe_text_button_create PORTABLE C */
/* 6.0 */
/* AUTHOR */
/* */
/* Kenneth Maxwell, Microsoft Corporation */
/* */
/* DESCRIPTION */
/* */
/* This function checks for errors in the text button create function */
/* call. */
/* */
/* INPUT */
/* */
/* button Button control block */
/* name Name of button */
/* parent Parent widget control block */
/* text_id text resource id */
/* style Style of button */
/* size Button size */
/* text_button_control_block_size Size of the text button */
/* control block */
/* */
/* OUTPUT */
/* */
/* status Completion status */
/* */
/* CALLS */
/* */
/* _gx_text_button_create Actual text button create */
/* function */
/* */
/* CALLED BY */
/* */
/* Application Code */
/* */
/* RELEASE HISTORY */
/* */
/* DATE NAME DESCRIPTION */
/* */
/* 05-19-2020 Kenneth Maxwell Initial Version 6.0 */
/* */
/**************************************************************************/
UINT _gxe_text_button_create(GX_TEXT_BUTTON *button, GX_CONST GX_CHAR *name, GX_WIDGET *parent,
GX_RESOURCE_ID text_id, ULONG style, USHORT Id,
GX_CONST GX_RECTANGLE *size, UINT text_button_control_block_size)
{
UINT status;
/* Check for appropriate caller. */
GX_INIT_AND_THREADS_CALLER_CHECKING
/* Check for invalid input pointers. */
if ((button == GX_NULL) || (size == GX_NULL))
{
return(GX_PTR_ERROR);
}
/* Check for invalid control block size. */
if (text_button_control_block_size != sizeof(GX_TEXT_BUTTON))
{
return(GX_INVALID_SIZE);
}
/* Check for id is created. */
if (button -> gx_widget_type != 0)
{
return(GX_ALREADY_CREATED);
}
/* Check for invalid widget. */
if (parent && (parent -> gx_widget_type == 0))
{
return(GX_INVALID_WIDGET);
}
/* Call the actual text button create function. */
status = _gx_text_button_create(button, name, parent, text_id, style, Id, size);
/* Return completion status. */
return status;
}
| 52.067227 | 96 | 0.258393 |
03810cd7e15c50d9c808d2fda7a699c37debec15 | 87 | c | C | llvm-gcc-4.2-2.9/gcc/testsuite/gcc.dg/pr27150-1.c | vidkidz/crossbridge | ba0bf94aee0ce6cf7eb5be882382e52bc57ba396 | [
"MIT"
] | 1 | 2016-04-09T02:58:13.000Z | 2016-04-09T02:58:13.000Z | llvm-gcc-4.2-2.9/gcc/testsuite/gcc.dg/pr27150-1.c | vidkidz/crossbridge | ba0bf94aee0ce6cf7eb5be882382e52bc57ba396 | [
"MIT"
] | null | null | null | llvm-gcc-4.2-2.9/gcc/testsuite/gcc.dg/pr27150-1.c | vidkidz/crossbridge | ba0bf94aee0ce6cf7eb5be882382e52bc57ba396 | [
"MIT"
] | null | null | null | /* { dg-do compile } */
/* { dg-options "-O2" } */
int g(int f)
{
return (&f)!=0;
}
| 10.875 | 26 | 0.436782 |
038483475e9937d6274bca839f90500f8370ed29 | 707 | h | C | ProatomicSubclasses/Frameworks/ProatomicSubclasses-Release-iphoneuniversal/ProatomicSubclasses.xcframework/ios-arm64_x86_64-simulator/ProatomicSubclasses.framework/Headers/ProatomicSubclasses.h | ProAtomic/ProatomicSubclasses | 346fe5272a2ee79d4f142aac35ff4ab8bac84e5e | [
"MIT"
] | null | null | null | ProatomicSubclasses/Frameworks/ProatomicSubclasses-Release-iphoneuniversal/ProatomicSubclasses.xcframework/ios-arm64_x86_64-simulator/ProatomicSubclasses.framework/Headers/ProatomicSubclasses.h | ProAtomic/ProatomicSubclasses | 346fe5272a2ee79d4f142aac35ff4ab8bac84e5e | [
"MIT"
] | null | null | null | ProatomicSubclasses/Frameworks/ProatomicSubclasses-Release-iphoneuniversal/ProatomicSubclasses.xcframework/ios-arm64_x86_64-simulator/ProatomicSubclasses.framework/Headers/ProatomicSubclasses.h | ProAtomic/ProatomicSubclasses | 346fe5272a2ee79d4f142aac35ff4ab8bac84e5e | [
"MIT"
] | null | null | null | //
// ProatomicSubclasses.h
// ProatomicSubclasses
//
// Created by Guillermo Saenz on 7/23/16.
// Copyright © 2016 Property Atomic Strong SAC. All rights reserved.
//
@import UIKit;
//! Project version number for ProatomicSubclasses.
FOUNDATION_EXPORT double ProatomicSubclassesVersionNumber;
//! Project version string for ProatomicSubclasses.
FOUNDATION_EXPORT const unsigned char ProatomicSubclassesVersionString[];
#import <ProatomicSubclasses/PASAutoLabel.h>
#import <ProatomicSubclasses/PASCountryPickerView.h>
#import <ProatomicSubclasses/PASGradientView.h>
#import <ProatomicSubclasses/PASScrollViewInnerShadowContainerView.h>
#import <ProatomicSubclasses/PASSecureCodingBaseModelObject.h>
| 32.136364 | 73 | 0.823197 |
0386169f05f08c6bec045be31daf8746e0c3161c | 1,516 | h | C | softbody/engine/geometry/geocore.h | legsonwings/softbody | 4a989c15214326672e19a482246cda617c203afd | [
"MIT"
] | null | null | null | softbody/engine/geometry/geocore.h | legsonwings/softbody | 4a989c15214326672e19a482246cda617c203afd | [
"MIT"
] | 2 | 2021-09-18T19:50:32.000Z | 2021-09-20T20:42:01.000Z | softbody/engine/geometry/geocore.h | legsonwings/softbody | 4a989c15214326672e19a482246cda617c203afd | [
"MIT"
] | null | null | null | #pragma once
#include "engine/core.h"
#include "stdx/stdx.h"
#include "engine/simplemath.h"
#include <vector>
#include <optional>
namespace geometry
{
struct nullshape {};
struct vertex
{
vector3 position = {};
vector3 normal = {};
vector2 texcoord = {};
constexpr vertex() = default;
constexpr vertex(vector3 const& pos, vector3 const& norm, vector2 txcoord = {}) : position(pos), normal(norm), texcoord(txcoord) {}
};
struct box
{
box() = default;
box(vector3 const& _center, vector3 const& _extents) : center(_center), extents(_extents) {}
std::vector<vector3> vertices();
vector3 center, extents;
};
struct aabb
{
aabb() : min_pt(vector3::Zero), max_pt(vector3::Zero) {}
aabb(vector3 const (&tri)[3]);
aabb(std::vector<vector3> const& points);
aabb(vector3 const* points, uint len);
aabb(vector3 const& _min, vector3 const& _max) : min_pt(_min), max_pt(_max) {}
vector3 center() const { return (max_pt + min_pt) / 2.f; }
vector3 span() const { return max_pt - min_pt; }
operator box() const { return { center(), span() }; }
aabb move(vector3 const& off) const { return aabb(min_pt + off, max_pt + off); }
aabb& operator+=(vector3 const& pt);
std::optional<aabb> intersect(aabb const& r) const;
// top left front = min, bot right back = max
vector3 min_pt;
vector3 max_pt;
};
} | 28.074074 | 139 | 0.593008 |
03886f1c4d0705eb15b7387b0bb089a5fa394c5b | 1,501 | c | C | handc/loadboot/loadboot.c | bitwize/rscheme | 1c933d3418205038df0f90e7bffdcfa2bff75951 | [
"TCL"
] | 21 | 2015-07-27T06:14:35.000Z | 2022-01-27T01:50:27.000Z | stage0/loadboot/loadboot.c | ecraven/rscheme | f7de3a1e2367b1828135d3c613877865f57f04da | [
"TCL"
] | 1 | 2019-08-21T12:47:11.000Z | 2019-08-21T12:47:11.000Z | stage0/loadboot/loadboot.c | ecraven/rscheme | f7de3a1e2367b1828135d3c613877865f57f04da | [
"TCL"
] | 7 | 2016-06-03T02:03:17.000Z | 2021-05-06T15:05:39.000Z | /*-----------------------------------------------------------------*-C-*---
* File: handc/loadboot/loadboot.c
*
* Copyright (C)1997 Donovan Kolbly <d.kolbly@rscheme.org>
* as part of the RScheme project, licensed for free use.
* See <http://www.rscheme.org/> for the latest information.
*
* File version: 1.8
* File mod date: 1998-01-13 11:38:09
* System build: v0.7.3.4-b7u, 2007-05-30
*
* Purpose: load the boot image
*------------------------------------------------------------------------*
* Notes:
* the function here is designed to be replaced by alternate
* boot image loaders, like FASL
*------------------------------------------------------------------------*/
#include <rscheme/smemory.h>
#include <rscheme/scheme.h>
#include <rscheme/heapi.h>
obj load_initial_heap( const char *path, rs_bool verbose )
{
char *gc_argv[3];
int vers;
obj r;
gc_argv[0] = "rs";
gc_argv[1] = verbose ? (char *)NULL : "-q";
gc_argv[2] = NULL;
init_gc( verbose ? 1 : 2, (const char **)gc_argv );
/* make room for it... */
gc_safe_point( 1024*1024 );
r = load_image_file( path, FALSE_OBJ, FALSE_OBJ, &vers );
if (EQ(r,FALSE_OBJ))
return FALSE_OBJ;
switch (vers)
{
case FMTV_RSCHEME_0_5: /* assume it's bootable */
case FMTV_RSCHEME_0_6_BOOT:
return r;
default:
fprintf( stderr, "%s: image version %d -- not bootable\n",
path, vers );
return FALSE_OBJ;
}
}
| 28.320755 | 76 | 0.523651 |
0388893330fa4d0610007649332c6a29a9301f13 | 23,161 | c | C | ccchacha20poly1305/crypto_test/crypto_test_chacha.c | holyswordman/apple_corecrypto_mirror | 7f67b02ab1fe07817b818c4e6f0d65ac39999d06 | [
"AML"
] | 20 | 2018-07-11T17:56:35.000Z | 2021-11-03T06:49:13.000Z | ccchacha20poly1305/crypto_test/crypto_test_chacha.c | holyswordman/apple_corecrypto_mirror | 7f67b02ab1fe07817b818c4e6f0d65ac39999d06 | [
"AML"
] | null | null | null | ccchacha20poly1305/crypto_test/crypto_test_chacha.c | holyswordman/apple_corecrypto_mirror | 7f67b02ab1fe07817b818c4e6f0d65ac39999d06 | [
"AML"
] | null | null | null | /*
* Copyright (c) 2016,2017,2018 Apple Inc. All rights reserved.
*
* corecrypto Internal Use License Agreement
*
* IMPORTANT: This Apple corecrypto software is supplied to you by Apple Inc. ("Apple")
* in consideration of your agreement to the following terms, and your download or use
* of this Apple software constitutes acceptance of these terms. If you do not agree
* with these terms, please do not download or use this Apple software.
*
* 1. As used in this Agreement, the term "Apple Software" collectively means and
* includes all of the Apple corecrypto materials provided by Apple here, including
* but not limited to the Apple corecrypto software, frameworks, libraries, documentation
* and other Apple-created materials. In consideration of your agreement to abide by the
* following terms, conditioned upon your compliance with these terms and subject to
* these terms, Apple grants you, for a period of ninety (90) days from the date you
* download the Apple Software, a limited, non-exclusive, non-sublicensable license
* under Apple’s copyrights in the Apple Software to make a reasonable number of copies
* of, compile, and run the Apple Software internally within your organization only on
* devices and computers you own or control, for the sole purpose of verifying the
* security characteristics and correct functioning of the Apple Software; provided
* that you must retain this notice and the following text and disclaimers in all
* copies of the Apple Software that you make. You may not, directly or indirectly,
* redistribute the Apple Software or any portions thereof. The Apple Software is only
* licensed and intended for use as expressly stated above and may not be used for other
* purposes or in other contexts without Apple's prior written permission. Except as
* expressly stated in this notice, no other rights or licenses, express or implied, are
* granted by Apple herein.
*
* 2. The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO
* WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES
* OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING
* THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS,
* SYSTEMS, OR SERVICES. APPLE DOES NOT WARRANT THAT THE APPLE SOFTWARE WILL MEET YOUR
* REQUIREMENTS, THAT THE OPERATION OF THE APPLE SOFTWARE WILL BE UNINTERRUPTED OR
* ERROR-FREE, THAT DEFECTS IN THE APPLE SOFTWARE WILL BE CORRECTED, OR THAT THE APPLE
* SOFTWARE WILL BE COMPATIBLE WITH FUTURE APPLE PRODUCTS, SOFTWARE OR SERVICES. NO ORAL
* OR WRITTEN INFORMATION OR ADVICE GIVEN BY APPLE OR AN APPLE AUTHORIZED REPRESENTATIVE
* WILL CREATE A WARRANTY.
*
* 3. IN NO EVENT SHALL APPLE BE LIABLE FOR ANY DIRECT, SPECIAL, INDIRECT, INCIDENTAL
* OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING
* IN ANY WAY OUT OF THE USE, REPRODUCTION, COMPILATION OR OPERATION OF THE APPLE
* SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING
* NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* 4. This Agreement is effective until terminated. Your rights under this Agreement will
* terminate automatically without notice from Apple if you fail to comply with any term(s)
* of this Agreement. Upon termination, you agree to cease all use of the Apple Software
* and destroy all copies, full or partial, of the Apple Software. This Agreement will be
* governed and construed in accordance with the laws of the State of California, without
* regard to its choice of law rules.
*
* You may report security issues about Apple products to product-security@apple.com,
* as described here: https://www.apple.com/support/security/. Non-security bugs and
* enhancement requests can be made via https://bugreport.apple.com as described
* here: https://developer.apple.com/bug-reporting/
*
* EA1350
* 10/5/15
*/
#include "testmore.h"
#include "testbyteBuffer.h"
#include "testccnBuffer.h"
#if (CCCHACHATEST == 0)
entryPoint(ccchacha_test,"ccchacha test")
#else
#include <corecrypto/ccchacha20poly1305.h>
#include <corecrypto/ccchacha20poly1305_priv.h>
static int verbose = 0;
typedef struct {
const char * key;
const char * nonce;
uint32_t counter;
const char * input;
const char * output;
} chacha20_test_vector;
static const chacha20_test_vector chacha20TestVectors[] = {
// Test 1 from "RFC 7539"
{
/* key */ "0000000000000000000000000000000000000000000000000000000000000000",
/* nonce */ "000000000000000000000000",
0,
/* input */ "00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
/* output */ "76b8e0ada0f13d90405d6ae55386bd28bdd219b8a08ded1aa836efcc8b770dc7da41597c5157488d7724e03fb8d84a376a43b8f41518a11cc387b669b2ee6586"
},
// Test 2 from "RFC 7539"
{
/* key */ "0000000000000000000000000000000000000000000000000000000000000001",
/* nonce */ "000000000000000000000002",
1,
/* input */ "416e79207375626d697373696f6e20746f20746865204945544620696e74656e6465642062792074686520436f6e7472696275746f7220666f72207075626c69636174696f6e20617320616c6c206f722070617274206f6620616e204945544620496e7465726e65742d4472616674206f722052464320616e6420616e792073746174656d656e74206d6164652077697468696e2074686520636f6e74657874206f6620616e204945544620616374697669747920697320636f6e7369646572656420616e20224945544620436f6e747269627574696f6e222e20537563682073746174656d656e747320696e636c756465206f72616c2073746174656d656e747320696e20494554462073657373696f6e732c2061732077656c6c206173207772697474656e20616e6420656c656374726f6e696320636f6d6d756e69636174696f6e73206d61646520617420616e792074696d65206f7220706c6163652c207768696368206172652061646472657373656420746f",
/* output */ "a3fbf07df3fa2fde4f376ca23e82737041605d9f4f4f57bd8cff2c1d4b7955ec2a97948bd3722915c8f3d337f7d370050e9e96d647b7c39f56e031ca5eb6250d4042e02785ececfa4b4bb5e8ead0440e20b6e8db09d881a7c6132f420e52795042bdfa7773d8a9051447b3291ce1411c680465552aa6c405b7764d5e87bea85ad00f8449ed8f72d0d662ab052691ca66424bc86d2df80ea41f43abf937d3259dc4b2d0dfb48a6c9139ddd7f76966e928e635553ba76c5c879d7b35d49eb2e62b0871cdac638939e25e8a1e0ef9d5280fa8ca328b351c3c765989cbcf3daa8b6ccc3aaf9f3979c92b3720fc88dc95ed84a1be059c6499b9fda236e7e818b04b0bc39c1e876b193bfe5569753f88128cc08aaa9b63d1a16f80ef2554d7189c411f5869ca52c5b83fa36ff216b9c1d30062bebcfd2dc5bce0911934fda79a86f6e698ced759c3ff9b6477338f3da4f9cd8514ea9982ccafb341b2384dd902f3d1ab7ac61dd29c6f21ba5b862f3730e37cfdc4fd806c22f221"
},
// Test 3 from "RFC 7539"
{
/* key */ "1c9240a5eb55d38af333888604f6b5f0473917c1402b80099dca5cbc207075c0",
/* nonce */ "000000000000000000000002",
42,
/* input */ "2754776173206272696c6c69672c20616e642074686520736c6974687920746f7665730a446964206779726520616e642067696d626c6520696e2074686520776162653a0a416c6c206d696d737920776572652074686520626f726f676f7665732c0a416e6420746865206d6f6d65207261746873206f757467726162652e",
/* output */ "62e6347f95ed87a45ffae7426f27a1df5fb69110044c0d73118effa95b01e5cf166d3df2d721caf9b21e5fb14c616871fd84c54f9d65b283196c7fe4f60553ebf39c6402c42234e32a356b3e764312a61a5532055716ead6962568f87d3f3f7704c6a8d1bcd1bf4d50d6154b6da731b187b58dfd728afa36757a797ac188d1"
},
};
static void test_chacha20(void) {
size_t i, n;
n = sizeof(chacha20TestVectors) / sizeof(*chacha20TestVectors);
for(i = 0; i < n; ++i) {
const chacha20_test_vector * const tv = &chacha20TestVectors[i];
byteBuffer key = hexStringToBytes(tv->key);
byteBuffer nonce = hexStringToBytes(tv->nonce);
uint32_t counter = tv->counter;
byteBuffer input = hexStringToBytes(tv->input);
byteBuffer outputExpected = hexStringToBytes(tv->output);
byteBuffer outputActual = mallocByteBuffer(outputExpected->len);
ccchacha20(key->bytes, nonce->bytes, counter, input->len, input->bytes, outputActual->bytes);
ok_memcmp(outputActual->bytes, outputExpected->bytes, outputExpected->len, "Check chacha20 test vector %zu", i + 1);
free(key);
free(nonce);
free(input);
free(outputExpected);
free(outputActual);
}
}
typedef struct {
const char * key;
const char * input;
const char * tag;
} poly1305_test_vector;
static const poly1305_test_vector poly1305TestVectors[] = {
// Test 1 from RFC 7539.
{
/* key */ "0000000000000000000000000000000000000000000000000000000000000000",
/* input */ "00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
/* tag */ "00000000000000000000000000000000"
},
// Test 2 from RFC 7539.
{
/* key */ "0000000000000000000000000000000036e5f6b5c5e06070f0efca96227a863e",
/* input */ "416e79207375626d697373696f6e20746f20746865204945544620696e74656e6465642062792074686520436f6e7472696275746f7220666f72207075626c69636174696f6e20617320616c6c206f722070617274206f6620616e204945544620496e7465726e65742d4472616674206f722052464320616e6420616e792073746174656d656e74206d6164652077697468696e2074686520636f6e74657874206f6620616e204945544620616374697669747920697320636f6e7369646572656420616e20224945544620436f6e747269627574696f6e222e20537563682073746174656d656e747320696e636c756465206f72616c2073746174656d656e747320696e20494554462073657373696f6e732c2061732077656c6c206173207772697474656e20616e6420656c656374726f6e696320636f6d6d756e69636174696f6e73206d61646520617420616e792074696d65206f7220706c6163652c207768696368206172652061646472657373656420746f",
/* tag */ "36e5f6b5c5e06070f0efca96227a863e"
},
// Test 3 from RFC 7539.
{
/* key */ "36e5f6b5c5e06070f0efca96227a863e00000000000000000000000000000000",
/* input */ "416e79207375626d697373696f6e20746f20746865204945544620696e74656e6465642062792074686520436f6e7472696275746f7220666f72207075626c69636174696f6e20617320616c6c206f722070617274206f6620616e204945544620496e7465726e65742d4472616674206f722052464320616e6420616e792073746174656d656e74206d6164652077697468696e2074686520636f6e74657874206f6620616e204945544620616374697669747920697320636f6e7369646572656420616e20224945544620436f6e747269627574696f6e222e20537563682073746174656d656e747320696e636c756465206f72616c2073746174656d656e747320696e20494554462073657373696f6e732c2061732077656c6c206173207772697474656e20616e6420656c656374726f6e696320636f6d6d756e69636174696f6e73206d61646520617420616e792074696d65206f7220706c6163652c207768696368206172652061646472657373656420746f",
/* tag */ "f3477e7cd95417af89a6b8794c310cf0"
},
// Test 4 from RFC 7539.
{
"1c9240a5eb55d38af333888604f6b5f0473917c1402b80099dca5cbc207075c0",
"2754776173206272696c6c69672c20616e642074686520736c6974687920746f7665730a446964206779726520616e642067696d626c6520696e2074686520776162653a0a416c6c206d696d737920776572652074686520626f726f676f7665732c0a416e6420746865206d6f6d65207261746873206f757467726162652e",
"4541669a7eaaee61e708dc7cbcc5eb62"
}
};
static void test_poly1305(void) {
size_t i, n;
n = sizeof(poly1305TestVectors) / sizeof(*poly1305TestVectors);
for(i = 0; i < n; ++i) {
const poly1305_test_vector * const tv = &poly1305TestVectors[i];
byteBuffer key = hexStringToBytes(tv->key);
byteBuffer input = hexStringToBytes(tv->input);
byteBuffer tagExpected = hexStringToBytes(tv->tag);
byteBuffer tagActual = mallocByteBuffer(tagExpected->len);
ccpoly1305(key->bytes, input->len, input->bytes, tagActual->bytes);
ok_memcmp(tagActual->bytes, tagExpected->bytes, tagExpected->len, "Check poly1305 test vector %zu", i + 1);
free(key);
free(input);
free(tagExpected);
free(tagActual);
}
}
typedef struct {
const char * key;
const char * nonce;
const char * aad;
const char * pt;
const char * ct;
const char * tag;
} chacha20_poly1305_test_vector;
static const chacha20_poly1305_test_vector chacha20_poly1305TestVectors[] =
{
// Test vector 1 from RFC 7539.
{
/* key */ "1c9240a5eb55d38af333888604f6b5f0473917c1402b80099dca5cbc207075c0",
/* nonce */ "000000000102030405060708",
/* aad */ "f33388860000000000004e91",
/* pt */ "496e7465726e65742d4472616674732061726520647261667420646f63756d656e74732076616c696420666f722061206d6178696d756d206f6620736978206d6f6e74687320616e64206d617920626520757064617465642c207265706c616365642c206f72206f62736f6c65746564206279206f7468657220646f63756d656e747320617420616e792074696d652e20497420697320696e617070726f70726961746520746f2075736520496e7465726e65742d447261667473206173207265666572656e6365206d6174657269616c206f7220746f2063697465207468656d206f74686572207468616e206173202fe2809c776f726b20696e2070726f67726573732e2fe2809d",
/* ct */ "64a0861575861af460f062c79be643bd5e805cfd345cf389f108670ac76c8cb24c6cfc18755d43eea09ee94e382d26b0bdb7b73c321b0100d4f03b7f355894cf332f830e710b97ce98c8a84abd0b948114ad176e008d33bd60f982b1ff37c8559797a06ef4f0ef61c186324e2b3506383606907b6a7c02b0f9f6157b53c867e4b9166c767b804d46a59b5216cde7a4e99040c5a40433225ee282a1b0a06c523eaf4534d7f83fa1155b0047718cbc546a0d072b04b3564eea1b422273f548271a0bb2316053fa76991955ebd63159434ecebb4e466dae5a1073a6727627097a1049e617d91d361094fa68f0ff77987130305beaba2eda04df997b714d6c6f2c29a6ad5cb4022b02709b",
/* tag */ "eead9d67890cbb22392336fea1851f38"
},
};
static void test_chacha20_poly1305(void) {
size_t testIndex, testCount;
testCount = sizeof(chacha20_poly1305TestVectors) / sizeof(*chacha20_poly1305TestVectors);
for(testIndex = 0; testIndex < testCount; ++testIndex) {
const chacha20_poly1305_test_vector * const tv = &chacha20_poly1305TestVectors[testIndex];
byteBuffer key = hexStringToBytes(tv->key);
byteBuffer nonce = hexStringToBytes(tv->nonce);
byteBuffer aad = hexStringToBytes(tv->aad);
byteBuffer pt = hexStringToBytes(tv->pt);
byteBuffer ptActual = mallocByteBuffer(pt->len);
byteBuffer ct = hexStringToBytes(tv->ct);
byteBuffer ctActual = mallocByteBuffer(ct->len);
byteBuffer tag = hexStringToBytes(tv->tag);
byteBuffer tagActual = mallocByteBuffer(tag->len);
const struct ccchacha20poly1305_info *info;
ccchacha20poly1305_ctx state;
size_t i;
int err;
info = ccchacha20poly1305_info();
// All-at-once test using the update API.
ccchacha20poly1305_init(info, &state, key->bytes);
ccchacha20poly1305_setnonce(info, &state, nonce->bytes);
ccchacha20poly1305_aad(info, &state, aad->len, aad->bytes);
ccchacha20poly1305_encrypt(info, &state, pt->len, pt->bytes, ctActual->bytes);
ccchacha20poly1305_finalize(info, &state, tagActual->bytes);
ok_memcmp(ctActual->bytes, ct->bytes, ct->len, "Check chacha20-poly1305 init ciphertext all-at-once via update encrypt test vector %zu", testIndex + 1);
ok_memcmp(tagActual->bytes, tag->bytes, tag->len, "Check chacha20-poly1305 init tag all-at-once via update encrypt test vector %zu", testIndex + 1);
ccchacha20poly1305_reset(info, &state);
ccchacha20poly1305_setnonce(info, &state, nonce->bytes);
ccchacha20poly1305_aad(info, &state, aad->len, aad->bytes);
ccchacha20poly1305_encrypt(info, &state, pt->len, pt->bytes, ctActual->bytes);
ccchacha20poly1305_finalize(info, &state, tagActual->bytes);
ok_memcmp(ctActual->bytes, ct->bytes, ct->len, "Check chacha20-poly1305 reset ciphertext all-at-once via update encrypt test vector %zu", testIndex + 1);
ok_memcmp(tagActual->bytes, tag->bytes, tag->len, "Check chacha20-poly1305 reset tag all-at-once via update encrypt test vector %zu", testIndex + 1);
ccchacha20poly1305_init(info, &state, key->bytes);
ccchacha20poly1305_setnonce(info, &state, nonce->bytes);
ccchacha20poly1305_aad(info, &state, aad->len, aad->bytes);
ccchacha20poly1305_decrypt(info, &state, ct->len, ct->bytes, ptActual->bytes);
err = ccchacha20poly1305_verify(info, &state, tag->bytes);
ok(err == 0, "Check chacha20-poly1305 init tag all-at-once via update decrypt test vector %zu", testIndex + 1);
ok_memcmp(ptActual->bytes, pt->bytes, pt->len, "Check chacha20-poly1305 init plaintext all-at-once via update decrypt test vector %zu", testIndex + 1);
ccchacha20poly1305_reset(info, &state);
ccchacha20poly1305_setnonce(info, &state, nonce->bytes);
ccchacha20poly1305_aad(info, &state, aad->len, aad->bytes);
ccchacha20poly1305_decrypt(info, &state, ct->len, ct->bytes, ptActual->bytes);
err = ccchacha20poly1305_verify(info, &state, tag->bytes);
ok(err == 0, "Check chacha20-poly1305 reset tag all-at-once via update decrypt test vector %zu", testIndex + 1);
ok_memcmp(ptActual->bytes, pt->bytes, pt->len, "Check chacha20-poly1305 reset plaintext all-at-once via update decrypt test vector %zu", testIndex + 1);
// Byte-by-byte test using the update API.
ccchacha20poly1305_init(info, &state, key->bytes);
ccchacha20poly1305_setnonce(info, &state, nonce->bytes);
for(i = 0; i < aad->len; ++i) ccchacha20poly1305_aad(info, &state, 1, &aad->bytes[i]);
for(i = 0; i < pt->len; ++i) ccchacha20poly1305_encrypt(info, &state, 1, &pt->bytes[i], &ctActual->bytes[i]);
ccchacha20poly1305_finalize(info, &state, tagActual->bytes);
ok_memcmp(ctActual->bytes, ct->bytes, ct->len, "Check chacha20-poly1305 init ciphertext byte-by-byte via update encrypt test vector %zu", testIndex + 1);
ok_memcmp(tagActual->bytes, tag->bytes, tag->len, "Check chacha20-poly1305 init tag byte-by-byte via update encrypt test vector %zu", testIndex + 1);
ccchacha20poly1305_reset(info, &state);
ccchacha20poly1305_setnonce(info, &state, nonce->bytes);
for(i = 0; i < aad->len; ++i) ccchacha20poly1305_aad(info, &state, 1, &aad->bytes[i]);
for(i = 0; i < pt->len; ++i) ccchacha20poly1305_encrypt(info, &state, 1, &pt->bytes[i], &ctActual->bytes[i]);
ccchacha20poly1305_finalize(info, &state, tagActual->bytes);
ok_memcmp(ctActual->bytes, ct->bytes, ct->len, "Check chacha20-poly1305 reset ciphertext byte-by-byte via update encrypt test vector %zu", testIndex + 1);
ok_memcmp(tagActual->bytes, tag->bytes, tag->len, "Check chacha20-poly1305 reset tag byte-by-byte via update encrypt test vector %zu", testIndex + 1);
ccchacha20poly1305_init(info, &state, key->bytes);
ccchacha20poly1305_setnonce(info, &state, nonce->bytes);
for(i = 0; i < aad->len; ++i) ccchacha20poly1305_aad(info, &state, 1, &aad->bytes[i]);
for(i = 0; i < ct->len; ++i) ccchacha20poly1305_decrypt(info, &state, 1, &ct->bytes[i], &ptActual->bytes[i]);
err = ccchacha20poly1305_verify(info, &state, tag->bytes);
ok(err == 0, "Check chacha20-poly1305 init byte-by-byte tag via update decrypt test vector %zu", testIndex + 1);
ok_memcmp(ptActual->bytes, pt->bytes, pt->len, "Check chacha20-poly1305 init byte-by-byte plaintext via update decrypt test vector %zu", testIndex + 1);
ccchacha20poly1305_reset(info, &state);
ccchacha20poly1305_setnonce(info, &state, nonce->bytes);
for(i = 0; i < aad->len; ++i) ccchacha20poly1305_aad(info, &state, 1, &aad->bytes[i]);
for(i = 0; i < ct->len; ++i) ccchacha20poly1305_decrypt(info, &state, 1, &ct->bytes[i], &ptActual->bytes[i]);
err = ccchacha20poly1305_verify(info, &state, tag->bytes);
ok(err == 0, "Check chacha20-poly1305 reset byte-by-byte tag via update decrypt test vector %zu", testIndex + 1);
ok_memcmp(ptActual->bytes, pt->bytes, pt->len, "Check chacha20-poly1305 reset byte-by-byte plaintext via update decrypt test vector %zu", testIndex + 1);
// All-at-once test using the one-shot API.
ccchacha20poly1305_encrypt_oneshot(info, key->bytes, nonce->bytes, aad->len, aad->bytes, pt->len, pt->bytes, ctActual->bytes, tagActual->bytes);
ok_memcmp(ctActual->bytes, ct->bytes, ct->len, "Check chacha20-poly1305 ciphertext all-at-once via one-shot encrypt test vector %zu", testIndex + 1);
ok_memcmp(tagActual->bytes, tag->bytes, tag->len, "Check chacha20-poly1305 tag all-at-once via one-shot encrypt test vector %zu", testIndex + 1);
err = ccchacha20poly1305_decrypt_oneshot(info, key->bytes, nonce->bytes, aad->len, aad->bytes, ct->len, ct->bytes, ptActual->bytes, tag->bytes);
ok(err == 0, "Check chacha20-poly1305 tag all-at-once via one-shot decrypt test vector %zu", testIndex + 1);
ok_memcmp(ptActual->bytes, pt->bytes, pt->len, "Check chacha20-poly1305 plaintext all-at-once via one-shot decrypt test vector %zu", testIndex + 1);
free(key);
free(nonce);
free(aad);
free(pt);
free(ptActual);
free(ct);
free(ctActual);
free(tag);
free(tagActual);
}
}
/* In this test we reach into the internal state to trigger the validation error on long messages. */
static int test_chacha20poly1305_counter_wrap(void)
{
uint8_t buf[CCCHACHA20_BLOCK_NBYTES] = { 0 };
const struct ccchacha20poly1305_info *info;
ccchacha20poly1305_ctx ctx;
info = ccchacha20poly1305_info();
ok_or_fail(ccchacha20poly1305_init(info, &ctx, buf) == 0, "ccchacha20poly1305_init encrypt counter wrap");
ok_or_fail(ccchacha20poly1305_setnonce(info, &ctx, buf) == 0, "ccchacha20poly1305_setnonce encrypt counter wrap");
ok_or_fail(ccchacha20poly1305_encrypt(info, &ctx, sizeof (buf), buf, buf) == 0, "ccchacha20poly1305_encrypt (begin) encrypt counter wrap");
ctx.text_nbytes = CCCHACHA20POLY1305_TEXT_MAX_NBYTES - CCCHACHA20_BLOCK_NBYTES;
ok_or_fail(ccchacha20poly1305_encrypt(info, &ctx, sizeof (buf), buf, buf) == 0, "ccchacha20poly1305_encrypt (end) encrypt counter wrap");
ok_or_fail(ccchacha20poly1305_encrypt(info, &ctx, 1, buf, buf) != 0, "ccchacha20poly1305_encrypt (overflow) encrypt counter wrap");
ok_or_fail(ccchacha20poly1305_init(info, &ctx, buf) == 0, "ccchacha20poly1305_init decrypt counter wrap");
ok_or_fail(ccchacha20poly1305_setnonce(info, &ctx, buf) == 0, "ccchacha20poly1305_setnonce decrypt counter wrap");
ok_or_fail(ccchacha20poly1305_decrypt(info, &ctx, sizeof (buf), buf, buf) == 0, "ccchacha20poly1305_decrypt (begin) decrypt counter wrap");
ctx.text_nbytes = CCCHACHA20POLY1305_TEXT_MAX_NBYTES - CCCHACHA20_BLOCK_NBYTES;
ok_or_fail(ccchacha20poly1305_decrypt(info, &ctx, sizeof (buf), buf, buf) == 0, "ccchacha20poly1305_decrypt (end) decrypt counter wrap");
ok_or_fail(ccchacha20poly1305_decrypt(info, &ctx, 1, buf, buf) != 0, "ccchacha20poly1305_decrypt (overflow) decrypt counter wrap");
return 1;
}
int ccchacha_tests(TM_UNUSED int argc, TM_UNUSED char *const *argv) {
plan_tests(37);
if(verbose) diag("Starting chacha tests\n");
test_chacha20();
test_poly1305();
test_chacha20_poly1305();
test_chacha20poly1305_counter_wrap();
return 0;
}
#endif // CCCHACHATEST
| 64.695531 | 767 | 0.774233 |
038a446d89dfa10a53f010d9a8be41b91790edd0 | 224 | h | C | slave/source/dropper/source/ntapi/ntapi.h | Aekras1a/Angie-Ransomware | b1933c3e5fb3b2df7154c892db9c4e3b4620c7e3 | [
"MIT"
] | 6 | 2020-04-16T08:35:16.000Z | 2022-02-09T21:36:29.000Z | slave/source/dropper/source/ntapi/ntapi.h | x1234xx/Angie-Ransomware | b1933c3e5fb3b2df7154c892db9c4e3b4620c7e3 | [
"MIT"
] | null | null | null | slave/source/dropper/source/ntapi/ntapi.h | x1234xx/Angie-Ransomware | b1933c3e5fb3b2df7154c892db9c4e3b4620c7e3 | [
"MIT"
] | 4 | 2019-05-25T20:26:59.000Z | 2021-03-22T16:47:06.000Z | #ifndef __NTAPI_NTAPI__
#define __NTAPI_NTAPI__
#define NtapiSyscallsFunctionsCount 13
extern DWORD NtapiSyscallsNamesHash[];
extern FARPROC NtapiSyscallsAddressStorage[];
extern CONST ULONG NtapiSyscallsOffset[];
#endif
| 20.363636 | 45 | 0.848214 |
038b37b182a77f3d63b8c1a18703504d731bb11d | 6,387 | h | C | arcane/src/arcane/anyitem/AnyItemGroup.h | cedricga91/framework | 143eeccb5bf375df4a3f11b888681f84f60380c6 | [
"Apache-2.0"
] | 16 | 2021-09-20T12:37:01.000Z | 2022-03-18T09:19:14.000Z | arcane/src/arcane/anyitem/AnyItemGroup.h | cedricga91/framework | 143eeccb5bf375df4a3f11b888681f84f60380c6 | [
"Apache-2.0"
] | 66 | 2021-09-17T13:49:39.000Z | 2022-03-30T16:24:07.000Z | arcane/src/arcane/anyitem/AnyItemGroup.h | cedricga91/framework | 143eeccb5bf375df4a3f11b888681f84f60380c6 | [
"Apache-2.0"
] | 11 | 2021-09-27T16:48:55.000Z | 2022-03-23T19:06:56.000Z | // -*- tab-width: 2; indent-tabs-mode: nil; coding: utf-8-with-signature -*-
//-----------------------------------------------------------------------------
// Copyright 2000-2022 CEA (www.cea.fr) IFPEN (www.ifpenergiesnouvelles.com)
// See the top-level COPYRIGHT file for details.
// SPDX-License-Identifier: Apache-2.0
//-----------------------------------------------------------------------------
/*---------------------------------------------------------------------------*/
/* AnyItemGroup.h (C) 2000-2012 */
/* */
/* Groupe aggrégée de types quelconques. */
/*---------------------------------------------------------------------------*/
#ifndef ARCANE_ANYITEM_ANYITEMGROUP_H
#define ARCANE_ANYITEM_ANYITEMGROUP_H
#include <map>
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
#include "arcane/ItemGroup.h"
#include "arcane/anyitem/AnyItemGlobal.h"
#include "arcane/anyitem/AnyItemPrivate.h"
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
ARCANE_BEGIN_NAMESPACE
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
ANYITEM_BEGIN_NAMESPACE
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
/*
* NB: Il faut savoir très tôt si on va itérer pour une variable ou une variable partielle
*
*/
/*!
* \brief Outil pour construire un groupe
*/
class GroupBuilder
{
public:
GroupBuilder(ItemGroup g)
: m_group(g)
, m_is_partial(false) {}
ItemGroup group() const { return m_group; }
bool isPartial() const { return m_is_partial; }
protected:
ItemGroup m_group;
bool m_is_partial;
};
/*!
* \brief Outil pour construire un groupe pour une variable partielle
*/
class PartialGroupBuilder
: public GroupBuilder
{
public:
PartialGroupBuilder(ItemGroup g) : GroupBuilder(g) {
this->m_is_partial = true;
}
};
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
/*!
* \brief Groupe AnyItem
* Agglomération de groupe Arcane + informations {partiel ou non} pour les variables
* Construction dans les familles AnyItem
*/
class Group
{
public:
/*!
* \brief Enumérateur d'un bloc d'items
*
* Enumérateur Arcane enrichi de la position dans la famille
*
*/
class BlockItemEnumerator
{
private:
typedef ItemInternal* ItemInternalPtr;
public:
BlockItemEnumerator(const Private::GroupIndexInfo & info)
: m_info(info)
, m_items(m_info.group->itemsInternal().data()), m_local_ids(m_info.group->itemsLocalId().data())
, m_index(0), m_count(m_info.group->size()), m_is_partial(info.is_partial) { }
BlockItemEnumerator(const BlockItemEnumerator& e)
: m_info(e.m_info)
, m_items(e.m_items), m_local_ids(e.m_local_ids)
, m_index(e.m_index), m_count(e.m_count), m_is_partial(e.m_is_partial) {}
//! Déréférencement vers l'item Arcane associé
Item operator*() const { return m_items[ m_local_ids[m_index] ]; }
//! Déréférencement indirect vers l'item Arcane associé
ItemInternal* operator->() const { return (ItemInternal*)m_items[ m_local_ids[m_index] ]; }
//! Avancement de l'énumérateur
inline void operator++() { ++m_index; }
//! Test de fin de l'énumérateur
inline bool hasNext() { return m_index<m_count; }
//! Nombre d'éléments de l'énumérateur
inline Integer count() const { return m_count; }
//! localId() de l'entité courante.
inline Integer varIndex() const { return (m_is_partial)?m_index:m_local_ids[m_index]; }
//! localId() de l'entité courante.
inline Integer localId() const { return m_info.local_id_offset+m_index; }
//! Index dans la AnyItem::Family du groupe en cours
inline Integer groupIndex() const { return m_info.group_index; }
//! Groupe sous-jacent courant
inline ItemGroup group() const { return ItemGroup(m_info.group); }
private:
const Private::GroupIndexInfo & m_info;
const ItemInternalPtr* m_items;
const Int32* ARCANE_RESTRICT m_local_ids;
Integer m_index;
Integer m_count;
bool m_is_partial;
};
/*!
* \brief Enumérateur des blocs d'items
*/
class Enumerator
{
public:
Enumerator(const Private::GroupIndexMapping& groups)
: m_current(std::begin(groups))
, m_end(std::end(groups)) {}
Enumerator(const Enumerator& e)
: m_current(e.m_current)
, m_end(e.m_end) {}
inline bool hasNext() const { return m_current != m_end; }
inline void operator++() { m_current++; }
//! Enumérateur d'un bloc d'items
inline BlockItemEnumerator enumerator() {
return BlockItemEnumerator(*m_current);
}
inline Integer groupIndex() const { return m_current->group_index; }
ItemGroup group() const { return ItemGroup(m_current->group); }
private:
Private::GroupIndexMapping::const_iterator m_current;
Private::GroupIndexMapping::const_iterator m_end;
};
public:
//! Construction à partir d'une table Groupe - offset (issue de la famille)
Group(const Private::GroupIndexMapping& groups)
: m_groups(groups) {}
//! Enumérateur du groupe
inline Enumerator enumerator() const {
return Enumerator(m_groups);
}
//! Nombre de groupes aggrégés
inline Integer size() const {
return m_groups.size();
}
//private:
public:
//! Table Groupe - offset
const Private::GroupIndexMapping& m_groups;
};
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
ANYITEM_END_NAMESPACE
ARCANE_END_NAMESPACE
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
#endif /* ARCANE_ANYITEM_ANYITEMGROUP_H */
| 32.586735 | 103 | 0.519806 |
038dc48200a9a70b30daf2290a8bc9fff8e2256f | 484 | h | C | SampleCode/NuMaker-PFM-M487/BLE_AB1602/Trsp/trspx_typedef.h | MDK-Packs/Nuvoton_M480BSP | 4a973aac620920f42c04bd8e01cf294fca6e737d | [
"Apache-2.0"
] | null | null | null | SampleCode/NuMaker-PFM-M487/BLE_AB1602/Trsp/trspx_typedef.h | MDK-Packs/Nuvoton_M480BSP | 4a973aac620920f42c04bd8e01cf294fca6e737d | [
"Apache-2.0"
] | null | null | null | SampleCode/NuMaker-PFM-M487/BLE_AB1602/Trsp/trspx_typedef.h | MDK-Packs/Nuvoton_M480BSP | 4a973aac620920f42c04bd8e01cf294fca6e737d | [
"Apache-2.0"
] | null | null | null | /******************************************************************************
Copyright (c) Airoha 2016 - All rights reserved
FILE NAME
trspx_typedef.h
DESCRIPTION
NOTES
********************************************************************************/
#ifndef __TRSPX_TYPEDEF_HH_
#define __TRSPX_TYPEDEF_HH_
typedef enum
{
BLE_IDLE,
//BLE_ACTIVATED,
BLE_ADVERTISING,
//BLE_WOBLE,
BLE_CONNECTED,
BLE_SET_INDICATION_ENABLED,
} TRSPX_BLE_STATUS;
#endif
| 20.166667 | 81 | 0.497934 |
038dcde0fdf0fb855683764815e3f5866fd3629d | 1,704 | h | C | blamlib/math/real_math.h | forksnd/blamlib | 5a97b36911cb40ad88a018d1f04c0a5fc58295e4 | [
"MIT"
] | 1 | 2020-04-09T04:34:54.000Z | 2020-04-09T04:34:54.000Z | blamlib/math/real_math.h | forksnd/blamlib | 5a97b36911cb40ad88a018d1f04c0a5fc58295e4 | [
"MIT"
] | null | null | null | blamlib/math/real_math.h | forksnd/blamlib | 5a97b36911cb40ad88a018d1f04c0a5fc58295e4 | [
"MIT"
] | 1 | 2020-11-03T13:31:36.000Z | 2020-11-03T13:31:36.000Z | #pragma once
#include <blamlib/cseries/cseries.h>
/* ---------- types */
using real = float;
using angle = real;
using real_fraction = real;
struct real_bounds
{
real lower;
real upper;
};
struct angle_bounds
{
angle lower;
angle upper;
};
struct real_fraction_bounds
{
real_fraction lower;
real_fraction upper;
};
struct real_point2d
{
real x;
real y;
};
struct real_point3d
{
real x;
real y;
real z;
};
struct real_vector2d
{
real i;
real j;
};
struct real_vector3d
{
real i;
real j;
real k;
};
struct real_vector4d
{
real i;
real j;
real k;
real w;
};
struct real_quaternion
{
real i;
real j;
real k;
real w;
};
struct real_euler_angles2d
{
real yaw;
real pitch;
};
struct real_euler_angles3d
{
real yaw;
real pitch;
real roll;
};
struct real_plane2d
{
real_vector2d normal;
real distance;
};
struct real_plane3d
{
real_vector3d normal;
real distance;
};
struct s_real_matrix3x3
{
real_vector3d forward;
real_vector3d left;
real_vector3d up;
};
struct s_real_matrix4x3
{
real_vector3d forward;
real_vector3d left;
real_vector3d up;
real_point3d position;
real scale;
};
struct s_real_orientation
{
real_quaternion rotation;
real_point3d translation;
real scale;
};
struct s_real_rectangle2d
{
real_bounds x;
real_bounds y;
};
struct s_real_rectangle3d
{
real_bounds x;
real_bounds y;
real_bounds z;
};
struct rgb_color
{
real red;
real green;
real blue;
};
struct argb_color
{
real alpha;
real red;
real green;
real blue;
};
struct real_hsv_color
{
real hue;
real saturation;
real value;
};
struct real_ahsv_color
{
real alpha;
real hue;
real saturation;
real value;
};
/* ---------- prototypes/REAL_MATH.CPP */
| 10.453988 | 41 | 0.70716 |
0391a97a067c3f6b4b8464e1240d5cb0fb7c4b91 | 2,379 | h | C | release/src-rt-6.x.4708/linux/linux-2.6.36/drivers/media/dvb/frontends/au8522.h | afeng11/tomato-arm | 1ca18a88480b34fd495e683d849f46c2d47bb572 | [
"FSFAP"
] | 4 | 2017-05-17T11:27:04.000Z | 2020-05-24T07:23:26.000Z | release/src-rt-6.x.4708/linux/linux-2.6.36/drivers/media/dvb/frontends/au8522.h | afeng11/tomato-arm | 1ca18a88480b34fd495e683d849f46c2d47bb572 | [
"FSFAP"
] | 1 | 2018-08-21T03:43:09.000Z | 2018-08-21T03:43:09.000Z | release/src-rt-6.x.4708/linux/linux-2.6.36/drivers/media/dvb/frontends/au8522.h | afeng11/tomato-arm | 1ca18a88480b34fd495e683d849f46c2d47bb572 | [
"FSFAP"
] | 5 | 2017-10-11T08:09:11.000Z | 2020-10-14T04:10:13.000Z | /*
Auvitek AU8522 QAM/8VSB demodulator driver
Copyright (C) 2008 Steven Toth <stoth@linuxtv.org>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#ifndef __AU8522_H__
#define __AU8522_H__
#include <linux/dvb/frontend.h>
enum au8522_if_freq {
AU8522_IF_6MHZ = 0,
AU8522_IF_4MHZ,
AU8522_IF_3_25MHZ,
};
struct au8522_led_config {
u16 vsb8_strong;
u16 qam64_strong;
u16 qam256_strong;
u16 gpio_output;
/* unset hi bits, set low bits */
u16 gpio_output_enable;
u16 gpio_output_disable;
u16 gpio_leds;
u8 *led_states;
unsigned int num_led_states;
};
struct au8522_config {
/* the demodulator's i2c address */
u8 demod_address;
/* Return lock status based on tuner lock, or demod lock */
#define AU8522_TUNERLOCKING 0
#define AU8522_DEMODLOCKING 1
u8 status_mode;
struct au8522_led_config *led_cfg;
enum au8522_if_freq vsb_if;
enum au8522_if_freq qam_if;
};
#if defined(CONFIG_DVB_AU8522) || (defined(CONFIG_DVB_AU8522_MODULE) && \
defined(MODULE))
extern struct dvb_frontend *au8522_attach(const struct au8522_config *config,
struct i2c_adapter *i2c);
#else
static inline
struct dvb_frontend *au8522_attach(const struct au8522_config *config,
struct i2c_adapter *i2c)
{
printk(KERN_WARNING "%s: driver disabled by Kconfig\n", __func__);
return NULL;
}
#endif /* CONFIG_DVB_AU8522 */
/* Other modes may need to be added later */
enum au8522_video_input {
AU8522_COMPOSITE_CH1 = 1,
AU8522_COMPOSITE_CH2,
AU8522_COMPOSITE_CH3,
AU8522_COMPOSITE_CH4,
AU8522_COMPOSITE_CH4_SIF,
AU8522_SVIDEO_CH13,
AU8522_SVIDEO_CH24,
};
enum au8522_audio_input {
AU8522_AUDIO_NONE,
AU8522_AUDIO_SIF,
};
#endif /* __AU8522_H__ */
/*
* Local variables:
* c-basic-offset: 8
*/
| 24.030303 | 77 | 0.754939 |
03935b1e4f85bb7beba7596f1952930936c54f4f | 86 | h | C | src/client/signals.h | divinity76/hhbd | 99b6c1ebca0044ec6530b821167f936c8d056e21 | [
"Unlicense"
] | null | null | null | src/client/signals.h | divinity76/hhbd | 99b6c1ebca0044ec6530b821167f936c8d056e21 | [
"Unlicense"
] | null | null | null | src/client/signals.h | divinity76/hhbd | 99b6c1ebca0044ec6530b821167f936c8d056e21 | [
"Unlicense"
] | null | null | null | #ifndef CLIENT_SIGNALS_H_
#define CLIENT_SIGNALS_H_
#endif /* CLIENT_SIGNALS_H_ */
| 12.285714 | 30 | 0.790698 |
0393b02650a6e475cd8224c799bc68106ef462a7 | 177 | c | C | packages/PIPS/validation/Scilab/COLD-1.0.5.sub/stubs/src/scilab_rt_isascii_s0_i2.c | DVSR1966/par4all | 86b33ca9da736e832b568c5637a2381f360f1996 | [
"MIT"
] | 51 | 2015-01-31T01:51:39.000Z | 2022-02-18T02:01:50.000Z | packages/PIPS/validation/Scilab/COLD-1.0.5.sub/stubs/src/scilab_rt_isascii_s0_i2.c | DVSR1966/par4all | 86b33ca9da736e832b568c5637a2381f360f1996 | [
"MIT"
] | 7 | 2017-05-29T09:29:00.000Z | 2019-03-11T16:01:39.000Z | packages/PIPS/validation/Scilab/COLD-1.0.5.sub/stubs/src/scilab_rt_isascii_s0_i2.c | DVSR1966/par4all | 86b33ca9da736e832b568c5637a2381f360f1996 | [
"MIT"
] | 12 | 2015-03-26T08:05:38.000Z | 2022-02-18T02:01:51.000Z |
void scilab_rt_isascii_s0_i2(char* s, int n, int m, int res[n][m])
{
int i,j;
for (i = 0; i < n; ++i) {
for (j = 0; j < m; ++j) {
res[i][j] = *s;
}
}
}
| 12.642857 | 67 | 0.423729 |
03956b599c4123468fcc4944c01da25d2ba7416d | 1,645 | h | C | PhotoLibraryServices.framework/PLMediaAnalysisAssetAttributes.h | reels-research/iOS-Private-Frameworks | 9a4f4534939310a51fdbf5a439dd22487efb0f01 | [
"MIT"
] | 4 | 2021-10-06T12:15:26.000Z | 2022-02-21T02:26:00.000Z | PhotoLibraryServices.framework/PLMediaAnalysisAssetAttributes.h | reels-research/iOS-Private-Frameworks | 9a4f4534939310a51fdbf5a439dd22487efb0f01 | [
"MIT"
] | null | null | null | PhotoLibraryServices.framework/PLMediaAnalysisAssetAttributes.h | reels-research/iOS-Private-Frameworks | 9a4f4534939310a51fdbf5a439dd22487efb0f01 | [
"MIT"
] | 1 | 2021-10-08T07:40:53.000Z | 2021-10-08T07:40:53.000Z | /* Generated by RuntimeBrowser
Image: /System/Library/PrivateFrameworks/PhotoLibraryServices.framework/PhotoLibraryServices
*/
@interface PLMediaAnalysisAssetAttributes : PLManagedObject
@property (nonatomic) float activityScore;
@property (nonatomic, retain) PLManagedAsset *asset;
@property (nonatomic) float autoplaySuggestionScore;
@property (nonatomic) int bestKeyFrameTimeScale;
@property (nonatomic) long long bestKeyFrameValue;
@property (nonatomic) int bestVideoRangeDurationTimeScale;
@property (nonatomic) long long bestVideoRangeDurationValue;
@property (nonatomic) int bestVideoRangeStartTimeScale;
@property (nonatomic) long long bestVideoRangeStartValue;
@property (nonatomic) float blurrinessScore;
@property (nonatomic) float exposureScore;
@property (nonatomic) unsigned long long faceCount;
@property (nonatomic, retain) NSDate *mediaAnalysisTimeStamp;
@property (nonatomic) unsigned long long mediaAnalysisVersion;
@property (nonatomic) float videoScore;
+ (id)entityName;
+ (id)fetchRequest;
- (struct { long long x1; int x2; unsigned int x3; long long x4; })bestKeyFrameTime;
- (struct { struct { long long x_1_1_1; int x_1_1_2; unsigned int x_1_1_3; long long x_1_1_4; } x1; struct { long long x_2_1_1; int x_2_1_2; unsigned int x_2_1_3; long long x_2_1_4; } x2; })bestVideoTimeRange;
- (void)setBestKeyFrameTime:(struct { long long x1; int x2; unsigned int x3; long long x4; })arg1;
- (void)setBestVideoTimeRange:(struct { struct { long long x_1_1_1; int x_1_1_2; unsigned int x_1_1_3; long long x_1_1_4; } x1; struct { long long x_2_1_1; int x_2_1_2; unsigned int x_2_1_3; long long x_2_1_4; } x2; })arg1;
@end
| 51.40625 | 223 | 0.790881 |
0395b00a1f72d10ff2207dc38f4a6e9bbaf32c67 | 1,206 | h | C | src/libraries/fs3/sg_fs3__private.h | samboy/veracity | 01935bf71cb04aec0ae6982ee163030710d60be8 | [
"Apache-2.0"
] | null | null | null | src/libraries/fs3/sg_fs3__private.h | samboy/veracity | 01935bf71cb04aec0ae6982ee163030710d60be8 | [
"Apache-2.0"
] | 3 | 2015-05-15T18:56:54.000Z | 2015-05-15T20:58:57.000Z | src/libraries/fs3/sg_fs3__private.h | samboy/veracity | 01935bf71cb04aec0ae6982ee163030710d60be8 | [
"Apache-2.0"
] | null | null | null | /*
Copyright 2010-2013 SourceGear, LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#ifndef H_SG_FS3_PRIVATE_H
#define H_SG_FS3_PRIVATE_H
#include <sg.h>
#include "sg_treendx_typedefs.h"
#include "sg_treendx_prototypes.h"
#include "sg_dbndx_typedefs.h"
#include "sg_dbndx_prototypes.h"
#include "sg_dag_sqlite3_typedefs.h"
#include "sg_dag_sqlite3_prototypes.h"
#include "sg_repo_vtable__fs3.h"
#define SG_DBNDX_QUERY_NULLFREE(pCtx,p) _sg_generic_nullfree(pCtx,p,SG_dbndx_query__free)
#define SG_DBNDX_UPDATE_NULLFREE(pCtx,p) _sg_generic_nullfree(pCtx,p,SG_dbndx_update__free)
#define SG_TREENDX_NULLFREE(pCtx,p) _sg_generic_nullfree(pCtx,p,SG_treendx__free)
#endif//H_SG_FS3_PRIVATE_H
| 33.5 | 92 | 0.793532 |
0396781c60ab73aa7dcd2461d216ab852ed883cd | 1,841 | h | C | Third party/EasySoap++-0.6.1/src/SOAPEnvelopeHandler.h | Jeanmilost/Visual-Mercutio | f079730005b6ce93d5e184bb7c0893ccced3e3ab | [
"MIT"
] | 1 | 2022-01-31T06:24:24.000Z | 2022-01-31T06:24:24.000Z | Third party/EasySoap++-0.6.1/src/SOAPEnvelopeHandler.h | Jeanmilost/Visual-Mercutio | f079730005b6ce93d5e184bb7c0893ccced3e3ab | [
"MIT"
] | 2 | 2021-04-11T15:50:42.000Z | 2021-06-05T08:23:04.000Z | Third party/EasySoap++-0.6.1/src/SOAPEnvelopeHandler.h | Jeanmilost/Visual-Mercutio | f079730005b6ce93d5e184bb7c0893ccced3e3ab | [
"MIT"
] | 2 | 2021-01-08T00:55:18.000Z | 2022-01-31T06:24:18.000Z | /*
* EasySoap++ - A C++ library for SOAP (Simple Object Access Protocol)
* Copyright (C) 2001 David Crowley; SciTegic, Inc.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 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
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the Free
* Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
* SOAPEnvelopeHandler.h,v 1.8 2001/11/21 06:00:47 dcrowley Exp
*/
#if !defined(AFX_SOAPENVELOPEHANDLER_H__DD7D4800_3A07_4FF2_943F_E7364E9278E7__INCLUDED_)
#define AFX_SOAPENVELOPEHANDLER_H__DD7D4800_3A07_4FF2_943F_E7364E9278E7__INCLUDED_
#include "SOAPBodyHandler.h"
#include "SOAPHeaderHandler.h"
BEGIN_EASYSOAP_NAMESPACE
class SOAPEnvelope;
class SOAPEnvelopeHandler : public SOAPParseEventHandler
{
public:
SOAPEnvelopeHandler();
virtual ~SOAPEnvelopeHandler();
void SetEnvelope(SOAPEnvelope& env);
virtual SOAPParseEventHandler* start(SOAPParser& parser, const XML_Char *name, const XML_Char **attrs);
virtual SOAPParseEventHandler* startElement(SOAPParser& parser, const XML_Char *name, const XML_Char **attrs);
private:
bool m_done;
SOAPEnvelope *m_envelope;
SOAPBodyHandler m_bodyHandler;
SOAPHeaderHandler m_headerHandler;
};
END_EASYSOAP_NAMESPACE
#endif // !defined(AFX_SOAPENVELOPEHANDLER_H__DD7D4800_3A07_4FF2_943F_E7364E9278E7__INCLUDED_)
| 30.683333 | 111 | 0.786529 |
039a1c3029e275d32c517456615071a88bb49e70 | 449 | h | C | vbcc_win/targets/ppc-warpos/include/proto/bevel.h | paulscottrobson/f68-emulator-old | c123676bb2356d66d1d0606859e38c8375ed0632 | [
"MIT"
] | 2 | 2022-02-28T15:57:45.000Z | 2022-03-12T16:20:22.000Z | vbcc_win/targets/ppc-warpos/include/proto/bevel.h | paulscottrobson/f68-emulator-old | c123676bb2356d66d1d0606859e38c8375ed0632 | [
"MIT"
] | 7 | 2022-02-23T19:48:27.000Z | 2022-02-25T10:14:03.000Z | vbcc_win/targets/ppc-warpos/include/proto/bevel.h | paulscottrobson/f68-emulator-old | c123676bb2356d66d1d0606859e38c8375ed0632 | [
"MIT"
] | 1 | 2022-03-07T07:41:56.000Z | 2022-03-07T07:41:56.000Z | #ifndef _PROTO_BEVEL_H
#define _PROTO_BEVEL_H
#ifndef EXEC_TYPES_H
#include <exec/types.h>
#endif
#if !defined(CLIB_BEVEL_PROTOS_H) && !defined(__GNUC__)
#include <clib/bevel_protos.h>
#endif
#ifndef __NOLIBBASE__
extern struct Library *BevelBase;
#endif
#ifdef __GNUC__
#ifdef __AROS__
#include <defines/bevel.h>
#else
#include <inline/bevel.h>
#endif
#elif !defined(__VBCC__)
#include <pragma/bevel_lib.h>
#endif
#endif /* _PROTO_BEVEL_H */
| 17.269231 | 55 | 0.766147 |
039b14754bb2cfd8b0d9fa95e44d253e8b13d072 | 4,497 | c | C | Linux/CNLab/CO3/2/Noiseless/receiver.c | codeSatan/4th-Sem-Lab | daedbf4693291dfb28148b74d72f0f56b8038b8d | [
"MIT"
] | null | null | null | Linux/CNLab/CO3/2/Noiseless/receiver.c | codeSatan/4th-Sem-Lab | daedbf4693291dfb28148b74d72f0f56b8038b8d | [
"MIT"
] | null | null | null | Linux/CNLab/CO3/2/Noiseless/receiver.c | codeSatan/4th-Sem-Lab | daedbf4693291dfb28148b74d72f0f56b8038b8d | [
"MIT"
] | null | null | null | /*Receiver side implementation of stop and wait protocol noiseless*/
//header files
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <unistd.h>
#define ERROR -1
#define MAX_QUEUE 1
#define PORT 11111
#define LOCALHOST "127.0.0.1"
#define MAX_PKT 1024
#define FRAME_SIZE sizeof(frame)
typedef unsigned int seq_nr; // sequence or ack numebr
typedef struct {
char data[MAX_PKT];
} packet; // packet definition
typedef enum { data, ack, nak } frame_kind; // frame kind definition
typedef struct {
frame_kind kind; // what kind of frame
seq_nr seq; // sequence number
seq_nr ack; // acknowledgement number
packet info; // the network layer packet
} frame; // frame definition
typedef enum { frame_arrival } event_type; // event type definition
char buffer[FRAME_SIZE]; // buffer to receive frame into
int sockfd; // server socket file descriptor
int client_sockfd; // client socket file descriptor
// function prototypes
void waitForEvent(event_type* event);
void getData(packet* pkt);
void makeFrame(frame* frm, packet* pkt);
void sendFrame(frame* frm);
void receiveFrame(frame* frm);
void extractData(frame* frm, packet* pkt);
void deliverData(packet* pkt);
void sender(void);
void receiver(void);
void receiver(void) {
packet p;
frame f, ackf;
ackf.kind = ack;
event_type event;
while (1) {
waitForEvent(&event); // wait for an event to occur
if (event == frame_arrival) {
receiveFrame(&f); // receive a frame
extractData(&f, &p); // extract the packet from the frame
deliverData(&p); // send the packet to network layer
sendFrame(&ackf); // send acknowledgement frame
}
}
}
/**
* Wait for frame arrival
*/
void waitForEvent(event_type* event) {
if (recv(client_sockfd, buffer, FRAME_SIZE, 0) == FRAME_SIZE) {
*event = frame_arrival;
} else {
printf("No more frames received!\n");
close(sockfd);
exit(EXIT_SUCCESS);
}
}
/**
* Receieve the frame that has been written into the buffer
*/
void receiveFrame(frame* frm) {
frame* fbuffer = (frame*)buffer;
*frm = *fbuffer;
memset(buffer, 0, FRAME_SIZE); // clear the buffer
}
/**
* Send frame to the destination machine
*/
void sendFrame(frame* f) {
frame* fbuffer = (frame*)buffer;
*fbuffer = *f;
if (write(client_sockfd, buffer, FRAME_SIZE) == ERROR) {
printf("Error in sending frame!\n");
close(sockfd);
exit(EXIT_FAILURE);
}
memset(buffer, 0, FRAME_SIZE); // clear the buffer
}
/**
* Extract the packet from the frame
*/
void extractData(frame* frm, packet* pkt) {
*pkt = frm->info;
}
//print the data
void deliverData(packet* pkt) { printf("Received message: %s", pkt->data); }
//driver code
int main() {
// Creating a socket of TCP/IP type
if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == ERROR) {
perror("socket() error ");
return EXIT_FAILURE;
}
// port to which we will bind the socket
unsigned short port = PORT;
// create a sockaddr_in for server
struct sockaddr_in server_addr;
server_addr.sin_family = AF_INET; // AF_INET implies IPv4
server_addr.sin_port = htons(port); // converting host BO to network BO
server_addr.sin_addr.s_addr = INADDR_ANY; // listen on all interfaces
bzero(&server_addr.sin_zero, 8); // set padding to zeroes
// binding the socket
if (bind(sockfd, (struct sockaddr*)&server_addr, sizeof(server_addr)) ==
ERROR) {
perror("bind failed");
close(sockfd);
return EXIT_FAILURE;
}
//listening for clients
if (listen(sockfd, MAX_QUEUE) == ERROR) {
perror("listen failed");
close(sockfd);
return EXIT_FAILURE;
}
struct sockaddr_in client_addr; // a sockaddr_in for client
unsigned int addrlen = sizeof(client_addr);
printf("Server listening!\n");
//accepting clients
client_sockfd = accept(sockfd, (struct sockaddr*)&client_addr, &addrlen);
if (client_sockfd == ERROR) {
perror("accept() failed ");
close(sockfd);
return EXIT_FAILURE;
}
printf("Connected successfully Waiting for packets!\n");
//receiver communications
receiver();
printf("No more frames received!\n");
close(sockfd); //close socket
} | 27.588957 | 77 | 0.642428 |
039cf2d26dde2b01a7d928bc4d0274d5f0c8e4bb | 2,460 | h | C | src/csapex_core/include/csapex/signal/slot.h | ICRA-2018/csapex | 8ee83b9166d0281a4923184cce67b4a55f273ea2 | [
"BSD-3-Clause"
] | null | null | null | src/csapex_core/include/csapex/signal/slot.h | ICRA-2018/csapex | 8ee83b9166d0281a4923184cce67b4a55f273ea2 | [
"BSD-3-Clause"
] | null | null | null | src/csapex_core/include/csapex/signal/slot.h | ICRA-2018/csapex | 8ee83b9166d0281a4923184cce67b4a55f273ea2 | [
"BSD-3-Clause"
] | null | null | null | #ifndef SLOT_H
#define SLOT_H
/// COMPONENT
#include <csapex/signal/signal_fwd.h>
#include <csapex/msg/input.h>
#include <csapex/model/token.h>
/// SYSTEM
#include <mutex>
#include <condition_variable>
#include <deque>
namespace csapex
{
class CSAPEX_CORE_EXPORT Slot : public Input
{
friend class Event;
public:
Slot(std::function<void()> callback, const UUID& uuid, bool active, bool blocking = true, ConnectableOwnerWeakPtr owner = ConnectableOwnerWeakPtr());
Slot(std::function<void(const TokenPtr&)> callback, const UUID& uuid, bool active, bool blocking = true, ConnectableOwnerWeakPtr owner = ConnectableOwnerWeakPtr());
Slot(std::function<void(Slot*, const TokenPtr&)> callback, const UUID& uuid, bool active, bool blocking = true, ConnectableOwnerWeakPtr owner = ConnectableOwnerWeakPtr());
template <typename TokenType>
Slot(std::function<void(const std::shared_ptr<TokenType const>&)> callback, const UUID& uuid, bool active)
: Slot(
[callback](const TokenPtr& token) {
auto t = std::dynamic_pointer_cast<TokenType const>(token->getTokenData());
apex_assert_hard(t);
callback(t);
},
uuid, active)
{
}
virtual ~Slot();
virtual void setToken(TokenPtr message) override;
int maxConnectionCount() const override;
virtual ConnectorType getConnectorType() const override
{
return ConnectorType::SLOT_T;
}
bool isActive() const;
bool isBlocking() const;
bool isEnabled() const override;
bool isSynchronous() const override;
void removeConnection(Connectable* connection) override;
void notifyMessageAvailable(Connection* connection) override;
void notifyMessageProcessed() override;
virtual void enable() override;
virtual void disable() override;
void reset();
void handleEvent();
void notifyEventHandled();
public:
slim_signal::Signal<void(const TokenPtr&)> token_set;
slim_signal::Signal<void()> triggered;
protected:
void addStatusInformation(std::stringstream& status_stream) const override;
private:
void tryNextToken();
protected:
std::function<void(Slot*, const TokenPtr&)> callback_;
bool active_;
bool blocking_;
long guard_;
private:
std::deque<Connection*> available_connections_;
std::recursive_mutex available_connections_mutex_;
};
} // namespace csapex
#endif // SLOT_H
| 26.170213 | 175 | 0.698374 |
039edc972a57edda8c9e673f57e1bee32c8dd821 | 513 | c | C | 2020/intro_pub/main.c | codaishin/sort-algorithms | 902aed79a76c50765fad821839fc2aebdc3947dc | [
"MIT"
] | null | null | null | 2020/intro_pub/main.c | codaishin/sort-algorithms | 902aed79a76c50765fad821839fc2aebdc3947dc | [
"MIT"
] | null | null | null | 2020/intro_pub/main.c | codaishin/sort-algorithms | 902aed79a76c50765fad821839fc2aebdc3947dc | [
"MIT"
] | null | null | null | #include <stdio.h>
void array_print(int* array, size_t size)
{
for (int i = 0; i < size; ++i) {
printf("%i ", array[i]);
}
printf("\n");
}
void array_sort(int* array, size_t size)
{
for (int h = 0; h < size; ++h) {
for (int i = 1; i < size - h; ++i) {
if (array[i-1] > array[i]) {
int tmp = array[i-1];
array[i-1] = array[i];
array[i] = tmp;
}
}
}
}
int main()
{
int array[10] = {2, 3, 1, 4, 6, 10, -4, 9, 0, -100};
array_sort(array, 10);
array_print(array, 10);
return 0;
}
| 15.545455 | 53 | 0.512671 |
039f44397fddd33185446b38bf45b31cd1a7c3d8 | 5,311 | h | C | logger.h | yihan1998/memcached | 56dc81db316a0b957415e371d20c683fea9d7d2f | [
"BSD-2-Clause",
"BSD-3-Clause"
] | 9,700 | 2015-01-01T16:19:51.000Z | 2022-03-31T14:32:18.000Z | logger.h | yihan1998/memcached | 56dc81db316a0b957415e371d20c683fea9d7d2f | [
"BSD-2-Clause",
"BSD-3-Clause"
] | 771 | 2015-01-01T06:59:05.000Z | 2022-03-30T05:53:00.000Z | logger.h | yihan1998/memcached | 56dc81db316a0b957415e371d20c683fea9d7d2f | [
"BSD-2-Clause",
"BSD-3-Clause"
] | 2,909 | 2015-01-01T01:07:46.000Z | 2022-03-24T15:31:27.000Z | /* logging functions */
#ifndef LOGGER_H
#define LOGGER_H
#include "bipbuffer.h"
/* TODO: starttime tunable */
#define LOGGER_BUF_SIZE 1024 * 64
#define LOGGER_WATCHER_BUF_SIZE 1024 * 256
#define LOGGER_ENTRY_MAX_SIZE 2048
#define GET_LOGGER() ((logger *) pthread_getspecific(logger_key));
/* Inlined from memcached.h - should go into sub header */
typedef unsigned int rel_time_t;
enum log_entry_type {
LOGGER_ASCII_CMD = 0,
LOGGER_EVICTION,
LOGGER_ITEM_GET,
LOGGER_ITEM_STORE,
LOGGER_CRAWLER_STATUS,
LOGGER_SLAB_MOVE,
LOGGER_CONNECTION_NEW,
LOGGER_CONNECTION_CLOSE,
#ifdef EXTSTORE
LOGGER_EXTSTORE_WRITE,
LOGGER_COMPACT_START,
LOGGER_COMPACT_ABORT,
LOGGER_COMPACT_READ_START,
LOGGER_COMPACT_READ_END,
LOGGER_COMPACT_END,
LOGGER_COMPACT_FRAGINFO,
#endif
};
enum logger_ret_type {
LOGGER_RET_OK = 0,
LOGGER_RET_NOSPACE,
LOGGER_RET_ERR
};
enum logger_parse_entry_ret {
LOGGER_PARSE_ENTRY_OK = 0,
LOGGER_PARSE_ENTRY_FULLBUF,
LOGGER_PARSE_ENTRY_FAILED
};
typedef struct _logentry logentry;
typedef struct _entry_details entry_details;
typedef void (*entry_log_cb)(logentry *e, const entry_details *d, const void *entry, va_list ap);
typedef int (*entry_parse_cb)(logentry *e, char *scratch);
struct _entry_details {
int reqlen;
uint16_t eflags;
entry_log_cb log_cb;
entry_parse_cb parse_cb;
char *format;
};
/* log entry intermediary structures */
struct logentry_eviction {
long long int exptime;
int nbytes;
uint32_t latime;
uint16_t it_flags;
uint8_t nkey;
uint8_t clsid;
char key[];
};
#ifdef EXTSTORE
struct logentry_ext_write {
long long int exptime;
uint32_t latime;
uint16_t it_flags;
uint8_t nkey;
uint8_t clsid;
uint8_t bucket;
char key[];
};
#endif
struct logentry_item_get {
uint8_t was_found;
uint8_t nkey;
uint8_t clsid;
int nbytes;
int sfd;
char key[];
};
struct logentry_item_store {
int status;
int cmd;
rel_time_t ttl;
uint8_t nkey;
uint8_t clsid;
int nbytes;
int sfd;
char key[];
};
struct logentry_conn_event {
int transport;
int reason;
int sfd;
struct sockaddr_in6 addr;
};
/* end intermediary structures */
/* WARNING: cuddled items aren't compatible with warm restart. more code
* necessary to ensure log streams are all flushed/processed before stopping
*/
struct _logentry {
enum log_entry_type event;
uint8_t pad;
uint16_t eflags;
uint64_t gid;
struct timeval tv; /* not monotonic! */
int size;
union {
char end;
} data[];
};
#define LOG_SYSEVENTS (1<<1) /* threads start/stop/working */
#define LOG_FETCHERS (1<<2) /* get/gets/etc */
#define LOG_MUTATIONS (1<<3) /* set/append/incr/etc */
#define LOG_SYSERRORS (1<<4) /* malloc/etc errors */
#define LOG_CONNEVENTS (1<<5) /* new client, closed, etc */
#define LOG_EVICTIONS (1<<6) /* details of evicted items */
#define LOG_STRICT (1<<7) /* block worker instead of drop */
#define LOG_RAWCMDS (1<<9) /* raw ascii commands */
typedef struct _logger {
struct _logger *prev;
struct _logger *next;
pthread_mutex_t mutex; /* guard for this + *buf */
uint64_t written; /* entries written to the buffer */
uint64_t dropped; /* entries dropped */
uint64_t blocked; /* times blocked instead of dropped */
uint16_t fetcher_ratio; /* log one out of every N fetches */
uint16_t mutation_ratio; /* log one out of every N mutations */
uint16_t eflags; /* flags this logger should log */
bipbuf_t *buf;
const entry_details *entry_map;
} logger;
enum logger_watcher_type {
LOGGER_WATCHER_STDERR = 0,
LOGGER_WATCHER_CLIENT = 1
};
typedef struct {
void *c; /* original connection structure. still with source thread attached */
int sfd; /* client fd */
int id; /* id number for watcher list */
uint64_t skipped; /* lines skipped since last successful print */
uint64_t min_gid; /* don't show log entries older than this GID */
bool failed_flush; /* recently failed to write out (EAGAIN), wait before retry */
enum logger_watcher_type t; /* stderr, client, syslog, etc */
uint16_t eflags; /* flags we are interested in */
bipbuf_t *buf; /* per-watcher output buffer */
} logger_watcher;
struct logger_stats {
uint64_t worker_dropped;
uint64_t worker_written;
uint64_t watcher_skipped;
uint64_t watcher_sent;
uint64_t watcher_count;
};
extern pthread_key_t logger_key;
/* public functions */
void logger_init(void);
void logger_stop(void);
logger *logger_create(void);
#define LOGGER_LOG(l, flag, type, ...) \
do { \
logger *myl = l; \
if (l == NULL) \
myl = GET_LOGGER(); \
if (myl->eflags & flag) \
logger_log(myl, type, __VA_ARGS__); \
} while (0)
enum logger_ret_type logger_log(logger *l, const enum log_entry_type event, const void *entry, ...);
enum logger_add_watcher_ret {
LOGGER_ADD_WATCHER_TOO_MANY = 0,
LOGGER_ADD_WATCHER_OK,
LOGGER_ADD_WATCHER_FAILED
};
enum logger_add_watcher_ret logger_add_watcher(void *c, const int sfd, uint16_t f);
/* functions used by restart system */
uint64_t logger_get_gid(void);
void logger_set_gid(uint64_t gid);
#endif
| 25.533654 | 100 | 0.695538 |
039fb5a70c4789997f644cb6cce1f1d55f29f314 | 477 | h | C | Init.h | xstater/XRange | 27af6b9100385c90923a42f1ac1419f383f3e678 | [
"MIT"
] | 1 | 2018-12-14T03:11:21.000Z | 2018-12-14T03:11:21.000Z | Init.h | xstater/XRange | 27af6b9100385c90923a42f1ac1419f383f3e678 | [
"MIT"
] | null | null | null | Init.h | xstater/XRange | 27af6b9100385c90923a42f1ac1419f383f3e678 | [
"MIT"
] | null | null | null | #ifndef _XRANGE_INIT_H_
#define _XRANGE_INIT_H_
#include "Init.h"
namespace xrange{
class InitRange{
public:
InitRange() = default;
~InitRange() = default;
template <class RangeType>
friend RangeType operator>>(RangeType range,InitRange Init){
return RangeType(range.begin(),range.end() - 1);
}
protected:
private:
};
InitRange init(){
return InitRange();
}
}
#endif //_XRANGE_INIT_H_ | 19.08 | 68 | 0.610063 |
039fe24944fb3eaab2117dc2d7a5a33609ef4f32 | 2,789 | h | C | src/game/shared/tf/tf_weapon_parse.h | cstom4994/SourceEngineRebuild | edfd7f8ce8af13e9d23586318350319a2e193c08 | [
"MIT"
] | 6 | 2022-01-23T09:40:33.000Z | 2022-03-20T20:53:25.000Z | src/game/shared/tf/tf_weapon_parse.h | cstom4994/SourceEngineRebuild | edfd7f8ce8af13e9d23586318350319a2e193c08 | [
"MIT"
] | null | null | null | src/game/shared/tf/tf_weapon_parse.h | cstom4994/SourceEngineRebuild | edfd7f8ce8af13e9d23586318350319a2e193c08 | [
"MIT"
] | 1 | 2022-02-06T21:05:23.000Z | 2022-02-06T21:05:23.000Z | //========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
//=============================================================================
#ifndef TF_WEAPON_PARSE_H
#define TF_WEAPON_PARSE_H
#ifdef _WIN32
#pragma once
#endif
#include "weapon_parse.h"
#include "networkvar.h"
#include "tf_shareddefs.h"
//=============================================================================
//
// TF Weapon Info
//
struct WeaponData_t
{
int m_nDamage;
int m_nBulletsPerShot;
float m_flRange;
float m_flSpread;
float m_flPunchAngle;
float m_flTimeFireDelay; // Time to delay between firing
float m_flTimeIdle; // Time to idle after firing
float m_flTimeIdleEmpty; // Time to idle after firing last bullet in clip
float m_flTimeReloadStart; // Time to start into a reload (ie. shotgun)
float m_flTimeReload; // Time to reload
bool m_bDrawCrosshair; // Should the weapon draw a crosshair
int m_iProjectile; // The type of projectile this mode fires
int m_iAmmoPerShot; // How much ammo each shot consumes
float m_flProjectileSpeed; // Start speed for projectiles (nail, etc.); NOTE: union with something non-projectile
float m_flSmackDelay; // how long after swing should damage happen for melee weapons
bool m_bUseRapidFireCrits;
void Init( void )
{
m_nDamage = 0;
m_nBulletsPerShot = 0;
m_flRange = 0.0f;
m_flSpread = 0.0f;
m_flPunchAngle = 0.0f;
m_flTimeFireDelay = 0.0f;
m_flTimeIdle = 0.0f;
m_flTimeIdleEmpty = 0.0f;
m_flTimeReloadStart = 0.0f;
m_flTimeReload = 0.0f;
m_iProjectile = TF_PROJECTILE_NONE;
m_iAmmoPerShot = 0;
m_flProjectileSpeed = 0.0f;
m_flSmackDelay = 0.0f;
m_bUseRapidFireCrits = false;
};
};
class CTFWeaponInfo : public FileWeaponInfo_t
{
public:
DECLARE_CLASS_GAMEROOT( CTFWeaponInfo, FileWeaponInfo_t );
CTFWeaponInfo();
~CTFWeaponInfo();
virtual void Parse( ::KeyValues *pKeyValuesData, const char *szWeaponName );
WeaponData_t const &GetWeaponData( int iWeapon ) const { return m_WeaponData[iWeapon]; }
public:
WeaponData_t m_WeaponData[2];
int m_iWeaponType;
// Grenade.
bool m_bGrenade;
float m_flDamageRadius;
float m_flPrimerTime;
bool m_bLowerWeapon;
bool m_bSuppressGrenTimer;
// Skins
bool m_bHasTeamSkins_Viewmodel;
bool m_bHasTeamSkins_Worldmodel;
// Muzzle flash
char m_szMuzzleFlashModel[128];
float m_flMuzzleFlashModelDuration;
char m_szMuzzleFlashParticleEffect[128];
// Tracer
char m_szTracerEffect[128];
// Eject Brass
bool m_bDoInstantEjectBrass;
char m_szBrassModel[128];
// Explosion Effect
char m_szExplosionSound[128];
char m_szExplosionEffect[128];
char m_szExplosionPlayerEffect[128];
char m_szExplosionWaterEffect[128];
bool m_bDontDrop;
};
#endif // TF_WEAPON_PARSE_H
| 24.901786 | 116 | 0.700968 |
03a0f441f0cdfa6c93df56d6870cb64b7ef50a9a | 6,304 | h | C | abcddraw.h | beatwise/abcdgui | 5e2b03421481c671c97afff52d4554a040c67c64 | [
"MIT"
] | null | null | null | abcddraw.h | beatwise/abcdgui | 5e2b03421481c671c97afff52d4554a040c67c64 | [
"MIT"
] | null | null | null | abcddraw.h | beatwise/abcdgui | 5e2b03421481c671c97afff52d4554a040c67c64 | [
"MIT"
] | null | null | null | /*
* Copyright (c) 2021 Alessandro De Santis
*
* 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.
*/
#pragma once
#include <cairomm/cairomm.h>
#include <cairomm/enums.h>
namespace abcd {
struct point
{
int x, y;
};
struct size
{
int width, height;
};
struct rect
{
int x1, y1, x2, y2;
int width() {return x2 - x1;}
int height() {return y2 - y1;}
rect()
{
x1 = y1 = x2 = y2 = 0;
}
rect(int x1, int y1, int x2, int y2)
{
this->x1 = x1; this->y1 = y1;
this->x2 = x2; this->y2 = y2;
}
};
struct color
{
uint8_t r, g, b, a;
};
class Draw
{
::Cairo::RefPtr<::Cairo::Context> m_cr;
::Cairo::RefPtr<::Cairo::ImageSurface> m_surface;
void prepare()
{
m_cr->translate(0.5, 0.5);
}
void create_rounded_rectangle(rect r, int rx, int ry)
{
double s = ry / double(rx);
rect ri;
ri.x1 = r.x1 + rx;
ri.y1 = r.y1 + ry;
ri.x2 = r.x2 - rx;
ri.y2 = r.y2 - ry;
m_cr->begin_new_sub_path();
m_cr->save();
m_cr->translate(ri.x2, ri.y1);
m_cr->scale(1, s);
m_cr->arc(0, 0, rx, -M_PI / 2, 0);
m_cr->restore();
m_cr->save();
m_cr->translate(ri.x2, ri.y2);
m_cr->scale(1, s);
m_cr->arc(0, 0, rx, 0, M_PI / 2);
m_cr->restore();
m_cr->save();
m_cr->translate(ri.x1, ri.y2);
m_cr->scale(1, s);
m_cr->arc(0, 0, ry/s, M_PI / 2, M_PI);
m_cr->restore();
m_cr->save();
m_cr->translate(ri.x1, ri.y1);
m_cr->scale(1, s);
m_cr->arc(0, 0, ry/s, M_PI, 3 * M_PI / 2);
m_cr->restore();
m_cr->close_path();
}
public:
Draw(uint8_t *pixels, int w, int h)
{
m_surface = ::Cairo::ImageSurface::create(
pixels, ::Cairo::Format::FORMAT_ARGB32, w, h, w * 4) ;
m_cr = ::Cairo::Context::create(m_surface);
prepare();
}
void set_stroke_width(float width)
{
m_cr->set_line_width(width);
}
void set_solid_paint(color c)
{
m_cr->set_source_rgba(c.r / 255.0, c.g / 255.0, c.b / 255.0, c.a / 255.0);
}
void clear()
{
m_cr->paint();
}
void stroke_rectangle(rect r)
{
m_cr->rectangle(r.x1, r.y1, r.width(), r.height());
m_cr->stroke();
}
void fill_rectangle(rect r)
{
m_cr->rectangle(r.x1, r.y1, r.width(), r.height());
m_cr->fill();
}
void stroke_rounded_rectangle(rect r, int rx, int ry)
{
create_rounded_rectangle(r, rx, ry);
m_cr->stroke();
}
void fill_rounded_rectangle(rect r, int rx, int ry)
{
create_rounded_rectangle(r, rx, ry);
m_cr->fill();
}
void stroke_arc(rect r, int sa, int ea)
{
float xc = (r.x1 + r.x2) / 2;
float yc = (r.y1 + r.y2) / 2;
float w = r.width();
float h = r.height();
float radius = w / 2;
if (w != h)
{
m_cr->save();
m_cr->scale(1, h / w);
}
m_cr->begin_new_path();
m_cr->arc(xc, yc * w / h, radius, sa * M_PI / 180, ea * M_PI / 180);
m_cr->stroke();
if (w != h)
{
m_cr->restore();
}
}
void fill_arc(rect r, int sa, int ea)
{
float xc = (r.x1 + r.x2) / 2;
float yc = (r.y1 + r.y2) / 2;
float w = r.width();
float h = r.height();
float radius = w / 2;
if (w != h)
{
m_cr->save();
m_cr->scale(1, h / w);
}
m_cr->begin_new_path();
m_cr->arc(xc, yc * w / h, radius, sa * M_PI / 180, ea * M_PI / 180);
m_cr->fill();
if (w != h)
{
m_cr->restore();
}
}
float set_font(const char *family, float size)
{
m_cr->select_font_face (family, ::Cairo::FONT_SLANT_NORMAL, ::Cairo::FONT_WEIGHT_NORMAL);
m_cr->set_font_size(size);
::Cairo::FontExtents fe;
m_cr->get_font_extents(fe);
float ratio = fe.height / size;
return ratio;
}
float get_font_height()
{
::Cairo::FontExtents fe;
m_cr->get_font_extents(fe);
return fe.height;
}
void text(const char *text, rect r, int xalign, int yalign)
{
::Cairo::FontExtents fe;
m_cr->get_font_extents(fe);
::Cairo::TextExtents te;
m_cr->get_text_extents(text, te);
::Cairo::TextExtents tex;
float xh = 0;
for (char c = 33; c < 127; ++c)
{
char s[] = " ";
s[0] = c;
m_cr->get_text_extents(s, tex);
xh = xh + tex.height;
}
xh = xh / (127-33.f);
float x, y;
switch (xalign)
{
case -1: x = r.x1; break;
case 1: x = r.x2 - te.width; break;
default: x = r.x1 + r.width() / 2 - te.width / 2; break;
}
x = x - te.x_bearing;
switch (yalign)
{
case -1: y = r.y1 + fe.ascent; break;
case 1: y = r.y2 - fe.descent; break;
default: y = r.y1 + r.height() / 2 - xh / 2 + xh; break;
}
m_cr->move_to(x, y);
m_cr->show_text(text);
}
void draw_textline(const char *text, point pt)
{
::Cairo::FontExtents fe;
m_cr->get_font_extents(fe);
::Cairo::TextExtents te;
m_cr->get_text_extents(text, te);
float x = pt.x /*+ te.x_bearing*/;
float y = pt.y + fe.ascent;
m_cr->move_to(x, y);
m_cr->show_text(text);
}
size get_textline_size(const char *text)
{
::Cairo::FontExtents fe;
m_cr->get_font_extents(fe);
::Cairo::TextExtents te;
m_cr->get_text_extents(text, te);
return {int(te.x_bearing + te.x_advance), int(fe.ascent + fe.descent)};
}
void push()
{
m_cr->save();
}
void pop()
{
m_cr->restore();
}
void clip(rect r)
{
m_cr->rectangle(r.x1, r.y1, r.width(), r.height());
m_cr->clip();
}
void translate(point pt)
{
m_cr->translate(pt.x, pt.y);
}
void rotate(float degree)
{
m_cr->rotate(degree * M_PI / 180);
}
};
} // abcd
| 18.59587 | 91 | 0.608503 |
03a1769b4c0bec48f5dc0dee322df6bb9130209f | 18,189 | c | C | sysfiles.c | arthursc98/zip_simulator | bd271a56d653f846a96871b7bc7b5aff526cc285 | [
"MIT"
] | null | null | null | sysfiles.c | arthursc98/zip_simulator | bd271a56d653f846a96871b7bc7b5aff526cc285 | [
"MIT"
] | null | null | null | sysfiles.c | arthursc98/zip_simulator | bd271a56d653f846a96871b7bc7b5aff526cc285 | [
"MIT"
] | null | null | null | /*
* sysfiles.c
* Implementing main functions of simulation
*
* Arthur Silveira Chaves (Sistemas de Informação)
* Beatriz Jonas Justino (Sistemas de Informação)
* Nicholas Meirinho Perez (Sistemas de Informação)
* Rafael Oliveira(Sistemas de Informação)
*
* Class/Subject: Operating Systems
*
* 10/11/2020
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include "gui.h"
#include "helpers.h"
#include "sysfiles.h"
// region [Main Operations]
void createFiles() {
char * files [2][1] = {
{"sofilesystem.chk"},
{"sofilesystem.sfs"},
};
for(int i = 0; i < 2; i++){
if (!fileExists(files[i][0])){
FILE * f;
if((f = fopen(files[i][0], "w+b")) == NULL) {
char error[100] = "Erro: Won't be able to create the file";
strcat(error, files[i][0]);
logError(error);
} else {
if (strcasecmp("sofilesystem.chk", files[i][0]) == 0) {
header h;
if ((h = (header) malloc(sizeof(struct headerInfo))) == NULL) {
fprintf(stderr, "Unable to alloc memory for header!\n");
exit(1);
}
fseek(f, 0, SEEK_SET);
fprintf(stdout, "Version\n>>> ");
fscanf(stdin, " %d", &h->version);
if (h->version < 10000000){
time_t now;
time(&now);
struct tm* now_tm;
now_tm = localtime(&now);
char today[12];
strftime(today, 12, "%Y%m%d", now_tm);
h->createDate = atoi(today);
h->modifiedDate = h->createDate;
h->nFiles = 0;
h->headerSize = sizeof(h);
fwrite(&h, sizeof(header), 1, f);
free(h);
clearscr();
} else {
char error[100] = "Erro: Invalid version";
logError(error);
}
}
}
fclose(f);
} else {
fprintf(stdout, "The S.O ");
fprintf(stdout, "%s ", files[i][0]);
fprintf(stdout, "already exists\n");
pauseSys();
clearscr();
}
}
}
void appendFiles() {
file newFile;
header headerMod;
int modifiedDate, creationDate;
bool exists, recoverable;
if ((newFile = (file) malloc(sizeof(struct fileInfo))) == NULL){
fprintf(stderr, "Unable to alloc memory for new file!\n");
exit(1);
}
if ((headerMod = (header) malloc(sizeof(struct headerInfo))) == NULL){
fprintf(stderr, "Unable to alloc memory for modified header!\n");
exit(1);
}
FILE * sfs, * currentFile, * chk;
if((chk = fopen("sofilesystem.chk", "r+b")) == NULL) {
char error[100] = "Erro: Won't be able to create the file";
strcat(error, "sofilesystem.chk");
logError(error);
}
if((sfs = fopen("sofilesystem.sfs", "a+b")) == NULL) {
char error[100] = "Erro: Won't be able to create the file";
strcat(error, "sofilesystem.sfs");
logError(error);
} else {
// region [Adding new file]
char * aux = inputFilename();
strcpy(newFile->filename, aux);
aux = inputOriginPath();
strcpy(newFile->originPath, aux);
checkExistingFile(newFile, &exists, &recoverable);
if(exists){
if(recoverable){
fprintf(stdout, "+=================================================================================================+\n");
fprintf(stdout, "+ Hey, you already add this file, if you want to recover it, go to the menu and choose the option +\n");
fprintf(stdout, "+=================================================================================================+\n");
} else {
fprintf(stdout, "+===========================================================+\n");
fprintf(stdout, "| The requested file already exists on your compressed file |\n");
fprintf(stdout, "+===========================================================+\n");
}
pauseSys();
clearscr();
fclose(sfs);
} else {
newFile->type = getExtension(&newFile);
newFile->bytesSize = getFileSize(&newFile);
getDates(&newFile, &modifiedDate, &creationDate);
newFile->modifiedDate = modifiedDate;
newFile->creationDate = creationDate;
newFile->deleted = false;
free(aux);
char * filePath = (char *)malloc(512 * sizeof(char));
strcpy(filePath, newFile->originPath);
strcat(filePath, newFile->filename);
currentFile = fopen(filePath, "rb");
free(filePath);
fseek(currentFile, 0, SEEK_END);
long filelen = ftell(currentFile);
fseek(currentFile, 0, SEEK_SET);
char * buffer = (char *)malloc(filelen * sizeof(char));
fread(buffer, filelen, 1 , currentFile);
fwrite(buffer, sizeof(char), filelen, sfs);
free(buffer);
unsigned char c[1];
fseek(currentFile, 0, SEEK_SET);
fread(&c, sizeof(char), 1, currentFile);
newFile->initialByte = c[0];
fclose(currentFile);
fseek(chk, 0, SEEK_END);
fwrite(&newFile, sizeof(file), 1, chk);
// endregion [Adding new file]
// region [Updating header]
fseek(chk, 0, SEEK_SET);
fread(&headerMod, sizeof(header), 1, chk);
time_t now;
time(&now);
struct tm* now_tm;
now_tm = localtime(&now);
char today[12];
strftime(today, 12, "%Y%m%d", now_tm);
headerMod->modifiedDate = atoi(today);
headerMod->nFiles = headerMod->nFiles + 1;
headerMod->headerSize = sizeof(headerMod);
fseek(chk, 0, SEEK_SET);
fwrite(&headerMod, sizeof(header), 1, chk);
// endregion [Updating header]
clearscr();
fclose(sfs);
}
}
fclose(chk);
}
void delete(){
FILE * chk, * sfs;
bool exist = false;
if((chk = fopen("sofilesystem.chk", "r+b")) == NULL) {
char error[100] = "Erro: Won't be able to create the file";
strcat(error, "sofilesystem.chk");
logError(error);
} else {
fseek(chk, 0, SEEK_END);
if (ftell(chk) != 0){
int skipBytes = 0, fileBytesSize;
char * filename = inputDeleteFilename();
fseek(chk, 0, SEEK_SET);
header headerReader = (header) malloc(sizeof(struct headerInfo));
fread(&headerReader, sizeof(header), 1, chk);
file fileRead[headerReader->nFiles];
fread(&fileRead, sizeof(file), headerReader->nFiles, chk);
for (int i = 0; i < headerReader->nFiles; i++){
if(strcasecmp(fileRead[i]->filename, filename) == 0){
exist = true;
fileRead[i]->deleted = true;
fileBytesSize = fileRead[i]->bytesSize;
break;
} else {
skipBytes = skipBytes + fileRead[i]->bytesSize;
}
}
if(!exist) {
printFileDoesntExists();
} else {
fseek(chk, 0, SEEK_SET);
fread(&headerReader, sizeof(header), 1, chk);
fwrite(&fileRead, sizeof(file), headerReader->nFiles, chk);
if((sfs = fopen("sofilesystem.sfs", "r+b")) == NULL) {
char error[100] = "Erro: Won't be able to create the file";
strcat(error, "sofilesystem.sfs");
logError(error);
} else {
fseek(sfs, skipBytes, SEEK_SET);
for(int i = 0; i < fileBytesSize; i++){
fputs(" ", sfs);
}
fclose(sfs);
clearscr();
printDeletedFile();
}
fclose(chk);
}
} else {
fprintf(stdout, "Your simulation file is empty. Append some files on it\n");
}
}
pauseSys();
clearscr();
}
void listFiles() {
FILE * f;
if((f = fopen("sofilesystem.chk", "r+b")) == NULL) {
char error[100] = "Erro: Won't be able to read the file";
strcat(error, "sofilesystem.chk");
logError(error);
} else {
fseek(f, 0 , SEEK_END);
if (ftell(f) != 0){
fseek(f, 0, SEEK_SET);
header headerReader = (header) malloc(sizeof(struct headerInfo));
fread(&headerReader, sizeof(header), 1, f);
file fileRead[headerReader->nFiles];
fread(&fileRead, sizeof(file), headerReader->nFiles, f);
for (int i = 0; i < headerReader->nFiles; i++){
if (!fileRead[i]->deleted){
fprintf(stdout, "+==========================================+\n");
fprintf(stdout, "Filename: %s\n", fileRead[i]->filename);
fprintf(stdout, "Origin Path: %s\n", fileRead[i]->originPath);
fprintf(stdout, "Directory: %s\n", fileRead[i]->originPath);
fprintf(stdout, "Creation Date: %d\n", fileRead[i]->creationDate);
fprintf(stdout, "Modified Date: %d\n", fileRead[i]->modifiedDate);
fprintf(stdout, "Initial Bytes: %08x\n", fileRead[i]->initialByte);
fprintf(stdout, "File Bytes Size: %d\n", fileRead[i]->bytesSize);
fprintf(stdout, "+==========================================+\n");
}
}
pauseSys();
}
}
clearscr();
fclose(f);
}
void showFile() {
file fileRead;
if ((fileRead = (file) malloc(sizeof(struct fileInfo))) == NULL){
fprintf(stderr, "Unable to alloc memory for file struct!\n");
exit(1);
}
bool exists = false;
char * externalFilename = inputFilenameReadContent();
strcpy(fileRead->filename, externalFilename);
char * extension = getExtension(&fileRead);
if (strcasecmp(extension, "txt") == 0){
FILE * f, * textFile;
if((f = fopen("sofilesystem.chk", "rb")) == NULL) {
char error[100] = "Erro: Won't be able to read the file";
strcat(error, "sofilesystem.chk");
logError(error);
} else {
fseek(f, 0, SEEK_END);
int nFiles = (ftell(f) / sizeof(file));
file fileRead[nFiles];
fseek(f, 0, SEEK_SET);
fread(&fileRead, sizeof(file), nFiles, f);
for (int i = 0; i < nFiles; i++){
if (!fileRead[i]->deleted){
if (strcasecmp(externalFilename, fileRead[i]->filename) == 0) {
exists = true;
char * fullfile = malloc(512);
strcpy(fullfile, fileRead[i]->originPath);
strcat(fullfile, fileRead[i]->filename);
if((textFile = fopen(fullfile, "r")) == NULL) {
char error[100] = "Erro: Won't be able to read the file ";
strcat(error, fullfile);
logError(error);
} else {
clearscr();
fprintf(stdout, "+==============+\n");
fprintf(stdout, "| File Content |\n");
fprintf(stdout, "+==============+\n");
char c;
while ((c = getc(textFile)) != EOF){
putchar(c);
}
fclose(textFile);
}
break;
}
}
}
if(!exists){
printFileDoesntExists();
}
}
fclose(f);
}
else {
fprintf(stdout, "+======================================+\n");
fprintf(stdout, "| The requested file isn't a text file |\n");
fprintf(stdout, "+======================================+\n");
}
free(externalFilename);
free(fileRead);
printf("\n");
pauseSys();
clearscr();
}
void unpack() {
FILE * f, * unpack_file, * sfs;
if((f = fopen("sofilesystem.chk", "r+b")) == NULL) {
char error[100] = "Erro: Won't be able to read the file";
strcat(error, "sofilesystem.chk");
logError(error);
} else {
fseek(f, 0 , SEEK_END);
if (ftell(f) != 0){
fseek(f, 0, SEEK_SET);
header headerReader = (header) malloc(sizeof(struct headerInfo));
fread(&headerReader, sizeof(header), 1, f);
file fileRead[headerReader->nFiles];
fread(&fileRead, sizeof(file), headerReader->nFiles, f);
struct stat st = {0};
if (stat("./unpacked_files", &st) == -1) {
createDir();
}
char fullpath[300];
int skipBytes = 0;
for (int i = 0; i < headerReader->nFiles; i++) {
if(!fileRead[i]->deleted) {
strcpy(fullpath, "./unpacked_files/");
strcat(fullpath, fileRead[i]->filename);
if((unpack_file = fopen(fullpath, "w+b")) == NULL) {
char error[100] = "Erro: Won't be able to read the file";
strcat(error, fullpath);
logError(error);
} else {
if((sfs = fopen("sofilesystem.sfs", "r+b")) == NULL) {
char error[100] = "Erro: Won't be able to read the file";
strcat(error, "sofilesystem.sfs");
logError(error);
} else {
if (i != 0){
skipBytes = 0;
for(int j = 0; j < i; j++){
skipBytes = skipBytes + fileRead[j]->bytesSize;
}
fseek(sfs, skipBytes, SEEK_SET);
}
char * buffer = (char *)malloc(fileRead[i]->bytesSize * sizeof(char));
fread(buffer, fileRead[i]->bytesSize, 1 , sfs);
fwrite(buffer, sizeof(char), fileRead[i]->bytesSize, unpack_file);
free(buffer);
}
fclose(sfs);
}
fclose(unpack_file);
}
}
printUnpackedFiles();
}
else {
fprintf(stdout, "+=================================================================+\n");
fprintf(stdout, "| The currently file can't be unpacked, there's nothing to unpack |\n");
fprintf(stdout, "+=================================================================+\n");
}
pauseSys();
clearscr();
fclose(f);
}
}
void recover(){
char * filename = inputRecoverFilename();
char * currentFileFullname = (char * ) malloc(sizeof(char) * 512);
int skipBytes = 0, fileBytesSize;
FILE * chk, * sfs, * currentFile;
if((chk = fopen("sofilesystem.chk", "r+b")) == NULL) {
char error[100] = "Erro: Won't be able to read the file";
strcat(error, "sofilesystem.chk");
logError(error);
} else {
fseek(chk, 0 , SEEK_END);
if (ftell(chk) != 0){
fseek(chk, 0, SEEK_SET);
header headerReader = (header) malloc(sizeof(struct headerInfo));
fread(&headerReader, sizeof(header), 1, chk);
file fileRead[headerReader->nFiles];
fread(&fileRead, sizeof(file), headerReader->nFiles, chk);
for (int i = 0; i < headerReader->nFiles; i++) {
if(strcasecmp(filename, fileRead[i]->filename) == 0){
strcpy(currentFileFullname, fileRead[i]->originPath);
strcat(currentFileFullname, fileRead[i]->filename);
fileBytesSize = fileRead[i]->bytesSize;
file rewriteFile = (file) malloc(sizeof(struct fileInfo));
rewriteFile = fileRead[i];
rewriteFile->deleted = false;
fseek(chk, sizeof(header) + (i * sizeof(file)), SEEK_SET);
fwrite(&rewriteFile, sizeof(file), 1, chk);
break;
} else {
skipBytes = skipBytes + fileRead[i]->bytesSize;
}
}
if((sfs = fopen("sofilesystem.sfs", "r+b")) == NULL) {
char error[100] = "Erro: Won't be able to read the file";
strcat(error, "sofilesystem.sfs");
logError(error);
} else {
fseek(sfs, skipBytes, SEEK_SET);
if((currentFile = fopen(currentFileFullname, "r+b")) == NULL) {
char error[100] = "Erro: Won't be able to read the file";
strcat(error, currentFileFullname);
logError(error);
} else {
char * buffer = (char *)malloc(fileBytesSize * sizeof(char));
fread(buffer, fileBytesSize, 1 , currentFile);
fwrite(buffer, sizeof(char), fileBytesSize, sfs);
free(buffer);
fprintf(stdout, "+==========================+\n");
fprintf(stdout, "| Completed recovered file |\n");
fprintf(stdout, "+==========================+\n");
}
fclose(currentFile);
}
fclose(sfs);
} else {
fprintf(stdout, "+===================================================================+\n");
fprintf(stdout, "| Your compressed file doesn't have any trace of the requested file |\n");
fprintf(stdout, "+===================================================================+\n");
}
pauseSys();
clearscr();
}
fclose(chk);
}
// endregion [Main Operations]
// region [File Attributes]
char * inputFilename() {
char * filename = malloc(256);
printInputFilename();
fscanf(stdin, " %[^\n]", filename);
return filename;
}
char * inputRecoverFilename() {
char * filename = malloc(256);
printInputRecoverFilename();
fscanf(stdin, " %[^\n]", filename);
return filename;
}
char * inputDeleteFilename() {
char * filename = malloc(256);
printInputDeleteFilename();
fscanf(stdin, " %[^\n]", filename);
return filename;
}
char * inputFilenameReadContent() {
char * filename = malloc(256);
printInputFilenameContent();
fscanf(stdin, " %[^\n]", filename);
return filename;
}
char * inputOriginPath() {
char * filePath = malloc(256);
printInputOriginPath();
fscanf(stdin, " %[^\n]", filePath);
#if defined(unix) || defined(__unix__) || defined(__unix) || (defined(__APPLE__) && defined(__MACH__))
char * currentDir = realpath(filePath, NULL);
if (currentDir == NULL){
char error[100] = "Erro: The requested path doesn't exists";
logError(error);
exit(1);
} else {
free(currentDir);
return filePath;
}
#elif _WIN32
struct stat buffer;
int exists = stat(filePath, &buffer);
if (exists == 0){
char error[100] = "Erro: The requested path doesn't exists";
logError(error);
exit(1);
} else {
return filePath;
}
#endif
}
char * getExtension(file * newFile) {
char * filename = (char *) malloc(sizeof(char) * 256);
strcpy(filename, (*newFile)->filename);
char * extension;
extension = strtok(filename, ".");
extension = strtok(NULL, ".");
return extension;
}
int getFileSize(file * newFile) {
struct stat attrib;
char * filename = (char *) malloc(sizeof(char) * 256);
strcpy(filename, (*newFile)->originPath);
strcat(filename, (*newFile)->filename);
stat(filename, &attrib);
return (int) attrib.st_size;
}
void getDates(file * newFile, int * modifiedDate, int * creationDate) {
struct stat attrib;
char * filename = (char *) malloc(sizeof(char) * 256);
strcpy(filename, (*newFile)->originPath);
strcat(filename, (*newFile)->filename);
stat(filename, &attrib);
char modifiedDateString[50];
char creationDateString[50];
strftime(modifiedDateString, 50, "%Y%m%d", localtime(&attrib.st_mtime));
strftime(creationDateString, 50, "%Y%m%d", localtime(&attrib.st_ctime));
*modifiedDate = atoi(modifiedDateString);
*creationDate = atoi(creationDateString);
}
// endregion [File Attributes]
// region [Check File]
void checkExistingFile(file newFile, bool * exists, bool * recoverable){
*exists = false;
*recoverable = false;
FILE * f;
if((f = fopen("sofilesystem.chk", "r+b")) == NULL) {
char error[100] = "Erro: Won't be able to read the file";
strcat(error, "sofilesystem.chk");
logError(error);
} else {
fseek(f, 0 , SEEK_END);
if (ftell(f) != 0){
char * filename = malloc(512);
char * fileInside = malloc(512);
strcpy(filename, newFile->originPath);
strcat(filename, newFile->filename);
fseek(f, 0, SEEK_SET);
header headerReader = (header) malloc(sizeof(struct headerInfo));
fread(&headerReader, sizeof(header), 1, f);
file fileRead[headerReader->nFiles];
fread(&fileRead, sizeof(file), headerReader->nFiles, f);
for (int i = 0; i < headerReader->nFiles; i++) {
strcpy(fileInside, fileRead[i]->originPath);
strcat(fileInside, fileRead[i]->filename);
if(strcasecmp(filename, fileInside) == 0){
*exists = true;
if(fileRead[i]->deleted){
*recoverable = true;
}
}
}
}
}
}
// endregion [Check File] | 30.264559 | 125 | 0.59382 |
03a37e958c9e41b16f068da7e9fdb53b141c3ba9 | 2,716 | h | C | include/parser.h | FragLand/concoct | 5dc9b8c05a1f89e50cdba69e4f2d5934444f78ed | [
"BSD-2-Clause"
] | 4 | 2020-06-10T01:39:43.000Z | 2020-06-10T23:14:13.000Z | include/parser.h | FragLand/concoct | 5dc9b8c05a1f89e50cdba69e4f2d5934444f78ed | [
"BSD-2-Clause"
] | 5 | 2020-06-11T01:01:56.000Z | 2020-06-12T12:48:30.000Z | include/parser.h | FragLand/concoct | 5dc9b8c05a1f89e50cdba69e4f2d5934444f78ed | [
"BSD-2-Clause"
] | null | null | null | /*
* Concoct - An imperative, dynamically-typed, interpreted, general-purpose programming language
* Copyright (c) 2020-2022 BlakeTheBlock and Lloyd Dilley
* http://concoct.dev/
*
* 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 OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef PARSER_H
#define PARSER_H
#include "lexer.h"
static const int CCT_NODE_COUNT_PER_BLOCK = 256;
typedef struct ConcoctNode
{
ConcoctToken token;
char* text;
struct ConcoctNode* parent;
int child_count;
struct ConcoctNode** children;
} ConcoctNode;
typedef struct concoct_node_tree
{
ConcoctNode** nodes;
int node_count;
int node_max;
ConcoctNode* root;
} ConcoctNodeTree;
typedef struct concoct_parser
{
ConcoctLexer* lexer;
ConcoctNodeTree* tree;
ConcoctToken current_token;
int error_line;
const char* error;
} ConcoctParser;
ConcoctNode* cct_new_node(ConcoctNodeTree* tree, ConcoctToken token, const char* text);
ConcoctParser* cct_new_parser(ConcoctLexer* lexer);
ConcoctParser* cct_new_parser_str(const char* str);
void cct_delete_parser(ConcoctParser* parser);
void cct_delete_node_tree(ConcoctNodeTree* tree);
ConcoctNode* cct_node_add_child(ConcoctNode* node, ConcoctNode* child);
ConcoctNodeTree* cct_parse_program(ConcoctParser* parser);
ConcoctNode* cct_parse_stat(ConcoctParser* parser);
ConcoctNode* cct_parse_expr(ConcoctParser* parser);
ConcoctToken cct_next_parser_token(ConcoctParser* parser);
void cct_print_node(ConcoctNode* node, int tab_level);
#endif // PARSER_H
| 36.702703 | 96 | 0.784978 |
03a3e6459b83ead0717d9d6eb2151593ee875cac | 7,420 | h | C | Sources/secp256k1/recovery_impl.h | rathishubham7/secp256k1_2 | bf852b6f02d15e1cb4bf89433c71a770d737a908 | [
"MIT"
] | null | null | null | Sources/secp256k1/recovery_impl.h | rathishubham7/secp256k1_2 | bf852b6f02d15e1cb4bf89433c71a770d737a908 | [
"MIT"
] | null | null | null | Sources/secp256k1/recovery_impl.h | rathishubham7/secp256k1_2 | bf852b6f02d15e1cb4bf89433c71a770d737a908 | [
"MIT"
] | null | null | null | /**********************************************************************
* Copyright (c) 2013-2015 Pieter Wuille *
* Distributed under the MIT software license, see the accompanying *
* file COPYING or http://www.opensource.org/licenses/mit-license.php.*
**********************************************************************/
#ifndef SECP256K1_2_MODULE_RECOVERY_MAIN_H
#define SECP256K1_2_MODULE_RECOVERY_MAIN_H
#include "secp256k1.h"
static void secp256k1_2_ecdsa_recoverable_signature_load(const secp256k1_2_context* ctx, secp256k1_2_scalar* r, secp256k1_2_scalar* s, int* recid, const secp256k1_2_ecdsa_recoverable_signature* sig) {
(void)ctx;
if (sizeof(secp256k1_2_scalar) == 32) {
/* When the secp256k1_2_scalar type is exactly 32 byte, use its
* representation inside secp256k1_2_ecdsa_signature, as conversion is very fast.
* Note that secp256k1_2_ecdsa_signature_save must use the same representation. */
memcpy(r, &sig->data[0], 32);
memcpy(s, &sig->data[32], 32);
} else {
secp256k1_2_scalar_set_b32(r, &sig->data[0], NULL);
secp256k1_2_scalar_set_b32(s, &sig->data[32], NULL);
}
*recid = sig->data[64];
}
static void secp256k1_2_ecdsa_recoverable_signature_save(secp256k1_2_ecdsa_recoverable_signature* sig, const secp256k1_2_scalar* r, const secp256k1_2_scalar* s, int recid) {
if (sizeof(secp256k1_2_scalar) == 32) {
memcpy(&sig->data[0], r, 32);
memcpy(&sig->data[32], s, 32);
} else {
secp256k1_2_scalar_get_b32(&sig->data[0], r);
secp256k1_2_scalar_get_b32(&sig->data[32], s);
}
sig->data[64] = recid;
}
int secp256k1_2_ecdsa_recoverable_signature_parse_compact(const secp256k1_2_context* ctx, secp256k1_2_ecdsa_recoverable_signature* sig, const unsigned char *input64, int recid) {
secp256k1_2_scalar r, s;
int ret = 1;
int overflow = 0;
(void)ctx;
ARG_CHECK(sig != NULL);
ARG_CHECK(input64 != NULL);
ARG_CHECK(recid >= 0 && recid <= 3);
secp256k1_2_scalar_set_b32(&r, &input64[0], &overflow);
ret &= !overflow;
secp256k1_2_scalar_set_b32(&s, &input64[32], &overflow);
ret &= !overflow;
if (ret) {
secp256k1_2_ecdsa_recoverable_signature_save(sig, &r, &s, recid);
} else {
memset(sig, 0, sizeof(*sig));
}
return ret;
}
int secp256k1_2_ecdsa_recoverable_signature_serialize_compact(const secp256k1_2_context* ctx, unsigned char *output64, int *recid, const secp256k1_2_ecdsa_recoverable_signature* sig) {
secp256k1_2_scalar r, s;
(void)ctx;
ARG_CHECK(output64 != NULL);
ARG_CHECK(sig != NULL);
ARG_CHECK(recid != NULL);
secp256k1_2_ecdsa_recoverable_signature_load(ctx, &r, &s, recid, sig);
secp256k1_2_scalar_get_b32(&output64[0], &r);
secp256k1_2_scalar_get_b32(&output64[32], &s);
return 1;
}
int secp256k1_2_ecdsa_recoverable_signature_convert(const secp256k1_2_context* ctx, secp256k1_2_ecdsa_signature* sig, const secp256k1_2_ecdsa_recoverable_signature* sigin) {
secp256k1_2_scalar r, s;
int recid;
(void)ctx;
ARG_CHECK(sig != NULL);
ARG_CHECK(sigin != NULL);
secp256k1_2_ecdsa_recoverable_signature_load(ctx, &r, &s, &recid, sigin);
secp256k1_2_ecdsa_signature_save(sig, &r, &s);
return 1;
}
static int secp256k1_2_ecdsa_sig_recover(const secp256k1_2_ecmult_context *ctx, const secp256k1_2_scalar *sigr, const secp256k1_2_scalar* sigs, secp256k1_2_ge *pubkey, const secp256k1_2_scalar *message, int recid) {
unsigned char brx[32];
secp256k1_2_fe fx;
secp256k1_2_ge x;
secp256k1_2_gej xj;
secp256k1_2_scalar rn, u1, u2;
secp256k1_2_gej qj;
int r;
if (secp256k1_2_scalar_is_zero(sigr) || secp256k1_2_scalar_is_zero(sigs)) {
return 0;
}
secp256k1_2_scalar_get_b32(brx, sigr);
r = secp256k1_2_fe_set_b32(&fx, brx);
(void)r;
VERIFY_CHECK(r); /* brx comes from a scalar, so is less than the order; certainly less than p */
if (recid & 2) {
if (secp256k1_2_fe_cmp_var(&fx, &secp256k1_2_ecdsa_const_p_minus_order) >= 0) {
return 0;
}
secp256k1_2_fe_add(&fx, &secp256k1_2_ecdsa_const_order_as_fe);
}
if (!secp256k1_2_ge_set_xo_var(&x, &fx, recid & 1)) {
return 0;
}
secp256k1_2_gej_set_ge(&xj, &x);
secp256k1_2_scalar_inverse_var(&rn, sigr);
secp256k1_2_scalar_mul(&u1, &rn, message);
secp256k1_2_scalar_negate(&u1, &u1);
secp256k1_2_scalar_mul(&u2, &rn, sigs);
secp256k1_2_ecmult(ctx, &qj, &xj, &u2, &u1);
secp256k1_2_ge_set_gej_var(pubkey, &qj);
return !secp256k1_2_gej_is_infinity(&qj);
}
int secp256k1_2_ecdsa_sign_recoverable(const secp256k1_2_context* ctx, secp256k1_2_ecdsa_recoverable_signature *signature, const unsigned char *msg32, const unsigned char *seckey, secp256k1_2_nonce_function noncefp, const void* noncedata) {
secp256k1_2_scalar r, s;
secp256k1_2_scalar sec, non, msg;
int recid = 0;
int ret = 0;
int overflow = 0;
VERIFY_CHECK(ctx != NULL);
ARG_CHECK(secp256k1_2_ecmult_gen_context_is_built(&ctx->ecmult_gen_ctx));
ARG_CHECK(msg32 != NULL);
ARG_CHECK(signature != NULL);
ARG_CHECK(seckey != NULL);
if (noncefp == NULL) {
noncefp = secp256k1_2_nonce_function_default;
}
secp256k1_2_scalar_set_b32(&sec, seckey, &overflow);
/* Fail if the secret key is invalid. */
if (!overflow && !secp256k1_2_scalar_is_zero(&sec)) {
unsigned char nonce32[32];
unsigned int count = 0;
secp256k1_2_scalar_set_b32(&msg, msg32, NULL);
while (1) {
ret = noncefp(nonce32, msg32, seckey, NULL, (void*)noncedata, count);
if (!ret) {
break;
}
secp256k1_2_scalar_set_b32(&non, nonce32, &overflow);
if (!secp256k1_2_scalar_is_zero(&non) && !overflow) {
if (secp256k1_2_ecdsa_sig_sign(&ctx->ecmult_gen_ctx, &r, &s, &sec, &msg, &non, &recid)) {
break;
}
}
count++;
}
memset(nonce32, 0, 32);
secp256k1_2_scalar_clear(&msg);
secp256k1_2_scalar_clear(&non);
secp256k1_2_scalar_clear(&sec);
}
if (ret) {
secp256k1_2_ecdsa_recoverable_signature_save(signature, &r, &s, recid);
} else {
memset(signature, 0, sizeof(*signature));
}
return ret;
}
int secp256k1_2_ecdsa_recover(const secp256k1_2_context* ctx, secp256k1_2_pubkey *pubkey, const secp256k1_2_ecdsa_recoverable_signature *signature, const unsigned char *msg32) {
secp256k1_2_ge q;
secp256k1_2_scalar r, s;
secp256k1_2_scalar m;
int recid;
VERIFY_CHECK(ctx != NULL);
ARG_CHECK(secp256k1_2_ecmult_context_is_built(&ctx->ecmult_ctx));
ARG_CHECK(msg32 != NULL);
ARG_CHECK(signature != NULL);
ARG_CHECK(pubkey != NULL);
secp256k1_2_ecdsa_recoverable_signature_load(ctx, &r, &s, &recid, signature);
VERIFY_CHECK(recid >= 0 && recid < 4); /* should have been caught in parse_compact */
secp256k1_2_scalar_set_b32(&m, msg32, NULL);
if (secp256k1_2_ecdsa_sig_recover(&ctx->ecmult_ctx, &r, &s, &q, &m, recid)) {
secp256k1_2_pubkey_save(pubkey, &q);
return 1;
} else {
memset(pubkey, 0, sizeof(*pubkey));
return 0;
}
}
#endif /* SECP256K1_2_MODULE_RECOVERY_MAIN_H */
| 38.247423 | 240 | 0.664286 |
03a46c4d9fa1c46f79750186db548c624b6da3fd | 1,094 | h | C | systemhelpers.h | egaebel/debug-server-client | a210dad4e434287de6b696ba761dad9ade7fccd5 | [
"MIT",
"Unlicense"
] | null | null | null | systemhelpers.h | egaebel/debug-server-client | a210dad4e434287de6b696ba761dad9ade7fccd5 | [
"MIT",
"Unlicense"
] | null | null | null | systemhelpers.h | egaebel/debug-server-client | a210dad4e434287de6b696ba761dad9ade7fccd5 | [
"MIT",
"Unlicense"
] | null | null | null | #ifndef SYSTEM_HELPERS_H_
#define SYSTEM_HELPERS_H_
#include <errno.h>
#include <unistd.h>
#include <stdbool.h>
#include <assert.h>
#include <fcntl.h>
#include <stdio.h>
#include <sys/socket.h>
#include <sys/mman.h>
#include <stdlib.h>
#include <string.h>
#include <netinet/in.h>
#include <netdb.h>
#include <signal.h>
//Socket related
void Setsockopt(int fd, int level, int optname);
int Socket(int domain, int type, int protocol);
void Listen (int sock_fd, int queue_length);
void Bind(int sock_fd, struct sockaddr * addr, int addr_len);
int Accept(int sockfd, struct sockaddr * addr, unsigned int * addrlen);
void Connect(int sockfd, const struct sockaddr * addr, socklen_t addrlen);
void Getaddrinfo(const char * node, const char * service, const struct addrinfo * hints, struct addrinfo ** res);
//general system
int Dup2(int fd, int fd2);
void Execve(char *filename, char * argv[], char * envp[]);
//files/fds open/close
int Close(int fd);
void Fclose(FILE * file);
FILE * Fopen(const char * filename, const char * mode);
int Open(const char *pathname, int flags, mode_t mode);
#endif
| 30.388889 | 113 | 0.732176 |
03a4db5eb65a088480472a64c483643aebec1147 | 34,372 | c | C | external/pmrrr/src/plarre.c | pjt1988/Elemental | 71d3e2b98829594e9f52980a8b1ef7c1e99c724b | [
"Apache-2.0"
] | 473 | 2015-01-11T03:22:11.000Z | 2022-03-31T05:28:39.000Z | external/pmrrr/src/plarre.c | pjt1988/Elemental | 71d3e2b98829594e9f52980a8b1ef7c1e99c724b | [
"Apache-2.0"
] | 205 | 2015-01-10T20:33:45.000Z | 2021-07-25T14:53:25.000Z | external/pmrrr/src/plarre.c | pjt1988/Elemental | 71d3e2b98829594e9f52980a8b1ef7c1e99c724b | [
"Apache-2.0"
] | 109 | 2015-02-16T14:06:42.000Z | 2022-03-23T21:34:26.000Z | /* Parallel computation of eigenvalues and symmetric tridiagonal
* matrix T, given by its diagonal elements D and its super-/sub-
* diagonal elements E.
*
* Copyright (c) 2010, RWTH Aachen University
* All rights reserved.
*
* Copyright (c) 2015, Jack Poulson
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
* * Redistributions of source code must retain the above
* copyright notice, this list of conditions and the following
* disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
* * Neither the name of the RWTH Aachen 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 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 RWTH
* AACHEN UNIVERSITY 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.
*
* Coded by Matthias Petschow (petschow@aices.rwth-aachen.de),
* August 2010, Version 0.7
*
* This code was the result of a collaboration between
* Matthias Petschow and Paolo Bientinesi. When you use this
* code, kindly reference a paper related to this work.
*
*/
#include "pmrrr.h"
#include "pmrrr/plarre.h"
#include "pmrrr/structs.h"
#define ONE 1.0
#define HUNDRED 100.0
#define HALF 0.5
#define FOURTH 0.25
static void *eigval_subset_thread_a(void *argin);
static void *eigval_subset_thread_r(void *argin);
static void clean_up_plarre(double*, double*, int*, int*, int*);
static
int eigval_approx_proc(proc_t *procinfo, int ifirst, int ilast,
int n, double *D, double *E, double *E2,
int *Windex, int *iblock, double *gersch, tol_t *tolstruct,
double *W, double *Werr, double *Wgap, double *work,
int *iwork);
static
int eigval_root_proc(proc_t *procinfo, int ifirst, int ilast,
int n, double *D, double *E, double *E2,
int *Windex, int *iblock, double *gersch, tol_t *tolstruct,
double *W, double *Werr, double *Wgap, double *work,
int *iwork);
static
int eigval_refine_proc(proc_t *procinfo, int ifirst, int ilast,
int n, double *D, double *E, double *E2,
int *Windex, int *iblock, double *gersch, tol_t *tolstruct,
double *W, double *Werr, double *Wgap, double *work,
int *iwork);
static
auxarg1_t *create_auxarg1(int, double*, double*, double*, int, int,
int, int, int, int*, double, double,
double*, double*, double*, int*, int*);
static
void retrieve_auxarg1(auxarg1_t*, int*, double**, double**, double**,
int*, int*, int*, int*, int*, int**, double*,
double*, double**, double**, double**, int**,
int**);
static
auxarg2_t *create_auxarg2(int, double*, double*, int, int, double*,
double*,double*,int*,double, double, double, double);
static
void retrieve_auxarg2(auxarg2_t*, int*, double**, double**, int*,
int*, double**, double**, double**, int**, double*, double*, double*,
double*);
static int cmp(const void*, const void*);
/* Routine to compute eigenvalues */
int plarre(proc_t *procinfo, char *jobz, char *range, in_t *Dstruct,
val_t *Wstruct, tol_t *tolstruct, int *nzp, int *offsetp)
{
/* input variables */
int nproc = procinfo->nproc;
bool wantZ = (jobz[0] == 'V' || jobz[0] == 'v');
bool cntval = (jobz[0] == 'C' || jobz[0] == 'c');
int n = Dstruct->n;
double *restrict D = Dstruct->D;
double *restrict E = Dstruct->E;
int *restrict isplit = Dstruct->isplit;
double *vl = Wstruct->vl;
double *vu = Wstruct->vu;
int *il = Wstruct->il;
int *iu = Wstruct->iu;
double *restrict W = Wstruct->W;
double *restrict Werr = Wstruct->Werr;
double *restrict Wgap = Wstruct->Wgap;
int *restrict Windex = Wstruct->Windex;
int *restrict iblock = Wstruct->iblock;
double *restrict gersch = Wstruct->gersch;
/* constants */
int IZERO = 0, IONE = 1;
double DZERO = 0.0;
/* work space */
double *E2;
double *work;
int *iwork;
/* compute geschgorin disks and spectral diameter */
double gl, gu, eold, emax, eabs;
/* compute splitting points */
int bl_begin, bl_end, bl_size;
/* distribute work among processes */
int ifirst, ilast, ifirst_tmp, ilast_tmp;
int chunk, isize, iil, iiu;
/* gather results */
int *rcount, *rdispl;
/* others */
int info, i, j, jbl, idummy;
double tmp1, dummy;
bool sorted;
enum range_enum {allrng=1, valrng=2, indrng=3} irange;
double intervals[2];
int negcounts[2];
double sigma;
if (range[0] == 'A' || range[0] == 'a') {
irange = allrng;
} else if (range[0] == 'V' || range[0] == 'v') {
irange = valrng;
} else if (range[0] == 'I' || range[0] == 'i') {
irange = indrng;
} else {
return 1;
}
/* allocate work space */
E2 = (double *) malloc( n * sizeof(double) );
assert(E2 != NULL);
work = (double *) malloc( 4*n * sizeof(double) );
assert(work != NULL);
iwork = (int *) malloc( 3*n * sizeof(int) );
assert(iwork != NULL);
rcount = (int *) malloc( nproc * sizeof(int) );
assert(rcount != NULL);
rdispl = (int *) malloc( nproc * sizeof(int) );
assert(rdispl != NULL);
/* Compute square of off-diagonal elements */
for (i=0; i<n-1; i++) {
E2[i] = E[i]*E[i];
}
/* compute geschgorin disks and spectral diameter */
gl = D[0];
gu = D[0];
eold = 0.0;
emax = 0.0;
E[n-1] = 0.0;
for (i=0; i<n; i++) {
eabs = fabs(E[i]);
if (eabs >= emax) emax = eabs;
tmp1 = eabs + eold;
gersch[2*i] = D[i] - tmp1;
gl = fmin(gl, gersch[2*i]);
gersch[2*i+1] = D[i] + tmp1;
gu = fmax(gu, gersch[2*i+1]);
eold = eabs;
}
/* min. pivot allowed in the Sturm sequence of T */
tolstruct->pivmin = DBL_MIN * fmax(1.0, emax*emax);
/* estimate of spectral diameter */
Dstruct->spdiam = gu - gl;
/* compute splitting points with threshold "split" */
odrra(&n, D, E, E2, &tolstruct->split, &Dstruct->spdiam,
&Dstruct->nsplit, isplit, &info);
assert(info == 0);
if (irange == allrng || irange == indrng) {
*vl = gl;
*vu = gu;
}
/* set eigenvalue indices in case of all or subset by value has
* to be computed; thereby convert all problem to subset by index
* computation */
if (irange == allrng) {
*il = 1;
*iu = n;
} else if (irange == valrng) {
intervals[0] = *vl; intervals[1] = *vu;
/* find negcount at boundaries 'vl' and 'vu';
* needs work of dim(n) and iwork of dim(n) */
odebz(&IONE, &IZERO, &n, &IONE, &IONE, &IZERO,
&DZERO, &DZERO, &tolstruct->pivmin, D, E, E2, &idummy,
intervals, &dummy, &idummy, negcounts, work, iwork, &info);
assert(info == 0);
/* update negcounts of whole matrix with negcounts found for block */
*il = negcounts[0] + 1;
*iu = negcounts[1];
}
if (cntval && irange == valrng) {
/* clean up and return */
*nzp = iceil(*iu-*il+1, nproc);
clean_up_plarre(E2, work, iwork, rcount, rdispl);
return 0;
}
/* loop over unreduced blocks */
bl_begin = 0;
for (jbl=0; jbl<Dstruct->nsplit; jbl++) {
bl_end = isplit[jbl] - 1;
bl_size = bl_end - bl_begin + 1;
/* deal with 1x1 block immediately */
if (bl_size == 1) {
E[bl_end] = 0.0;
W[bl_begin] = D[bl_begin];
Werr[bl_begin] = 0.0;
Werr[bl_begin] = 0.0;
iblock[bl_begin] = jbl + 1;
Windex[bl_begin] = 1;
bl_begin = bl_end + 1;
continue;
}
/* Indix range of block */
iil = 1;
iiu = bl_size;
/* each process computes a subset of the eigenvalues of the block */
ifirst_tmp = iil;
for (i=0; i<nproc; i++) {
chunk = (iiu-iil+1)/nproc + (i < (iiu-iil+1)%nproc);
if (i == nproc-1) {
ilast_tmp = iiu;
} else {
ilast_tmp = ifirst_tmp + chunk - 1;
ilast_tmp = imin(ilast_tmp, iiu);
}
if (i == procinfo->pid) {
ifirst = ifirst_tmp;
ilast = ilast_tmp;
isize = ilast - ifirst + 1;
*offsetp = ifirst - iil;
*nzp = isize;
}
rcount[i] = ilast_tmp - ifirst_tmp + 1;
rdispl[i] = ifirst_tmp - iil;
ifirst_tmp = ilast_tmp + 1;
ifirst_tmp = imin(ifirst_tmp, iiu + 1);
}
/* approximate eigenvalues of input assigned to process */
if (isize != 0) {
info = eigval_approx_proc(procinfo, ifirst, ilast,
bl_size, &D[bl_begin], &E[bl_begin], &E2[bl_begin],
&Windex[bl_begin], &iblock[bl_begin], &gersch[2*bl_begin],
tolstruct, &W[bl_begin], &Werr[bl_begin], &Wgap[bl_begin],
work, iwork);
assert(info == 0);
}
/* compute root representation of block */
info = eigval_root_proc(procinfo, ifirst, ilast,
bl_size, &D[bl_begin], &E[bl_begin], &E2[bl_begin],
&Windex[bl_begin], &iblock[bl_begin], &gersch[2*bl_begin],
tolstruct, &W[bl_begin], &Werr[bl_begin], &Wgap[bl_begin],
work, iwork);
assert(info == 0);
/* refine eigenvalues assigned to process w.r.t root */
if (isize != 0) {
info = eigval_refine_proc(procinfo, ifirst, ilast,
bl_size, &D[bl_begin], &E[bl_begin], &E2[bl_begin],
&Windex[bl_begin], &iblock[bl_begin], &gersch[2*bl_begin],
tolstruct, &W[bl_begin], &Werr[bl_begin], &Wgap[bl_begin],
work, iwork);
assert(info == 0);
}
memcpy(work, &W[bl_begin], isize * sizeof(double) );
MPI_Allgatherv(work, isize, MPI_DOUBLE, &W[bl_begin], rcount, rdispl,
MPI_DOUBLE, procinfo->comm);
memcpy(work, &Werr[bl_begin], isize * sizeof(double) );
MPI_Allgatherv(work, isize, MPI_DOUBLE, &Werr[bl_begin], rcount, rdispl,
MPI_DOUBLE, procinfo->comm);
memcpy(iwork, &Windex[bl_begin], isize * sizeof(int) );
MPI_Allgatherv(iwork, isize, MPI_INT, &Windex[bl_begin], rcount, rdispl,
MPI_INT, procinfo->comm);
/* Ensure that within block eigenvalues sorted */
sorted = false;
while (sorted == false) {
sorted = true;
for (j=bl_begin; j < bl_end; j++) {
if (W[j+1] < W[j]) {
sorted = false;
tmp1 = W[j];
W[j] = W[j+1];
W[j+1] = tmp1;
tmp1 = Werr[j];
Werr[j] = Werr[j+1];
Werr[j+1] = tmp1;
}
}
}
/* Set indices index correctly */
for (j=bl_begin; j <= bl_end; j++)
iblock[j] = jbl + 1;
/* Recompute gaps within the blocks */
for (j = bl_begin; j < bl_end; j++) {
Wgap[j] = fmax(0.0, (W[j+1] - Werr[j+1]) - (W[j] + Werr[j]) );
}
sigma = E[bl_end];
Wgap[bl_end] = fmax(0.0, (gu - sigma) - (W[bl_end] + Werr[bl_end]) );
/* Compute UNSHIFTED eigenvalues */
if (!wantZ) {
sigma = E[bl_end];
for (i=bl_begin; i<=bl_end; i++) {
W[i] += sigma;
}
}
/* Proceed with next block */
bl_begin = bl_end + 1;
}
/* end of loop over unreduced blocks */
/* free memory */
clean_up_plarre(E2, work, iwork, rcount, rdispl);
return 0;
}
/*
* Free's on allocated memory of plarre routine
*/
static
void clean_up_plarre(double *E2, double *work, int *iwork,
int *rcount, int *rdispl)
{
free(E2);
free(work);
free(iwork);
free(rcount);
free(rdispl);
}
#ifndef DISABLE_PTHREADS
static
int eigval_approx_proc
(proc_t *procinfo, int ifirst, int ilast,
int n, double *D, double *E, double *E2,
int *Windex, int *iblock, double *gersch, tol_t *tolstruct,
double *W, double *Werr, double *Wgap, double *work, int *iwork)
{
/* Input parameter */
int isize = ilast-ifirst+1;
double pivmin = tolstruct->pivmin;
/* /\* Multithreading *\/ */
int max_nthreads = procinfo->nthreads;
int iifirst, iilast, chunk;
pthread_t *threads;
pthread_attr_t attr;
auxarg1_t *auxarg1;
/* Others */
int info, m, i, j;
double dummy;
/* Allocate workspace */
int *isplit = (int *) malloc( n * sizeof(int) );
assert(isplit != NULL);
threads = (pthread_t *) malloc( max_nthreads * sizeof(pthread_t) );
assert(threads != NULL);
/* This is an unreduced block */
int nsplit = 1;
isplit[0] = n;
if (max_nthreads > 1) {
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM);
}
/* Set tolerance parameters */
double bsrtol = sqrt(DBL_EPSILON);
/* APPROXIMATE EIGENVALUES */
/* compute approximations of the eigenvalues with muliple threads */
/* equivalent to: */
/* dlarrd("I", "B", &n, &dummy, &dummy, &ifirst, &ilast, gersch, */
/* &bsrtol, D, E, E2, &pivmin, &nsplit, isplit, &m, W, Werr, */
/* &wl, &wu, iblock, Windex, work, iwork, &info); */
/* assert(info == 0); */
/* assert(m == ilast-ifirst+1); */
int nthreads = max_nthreads;
while (nthreads > 1 && isize / nthreads < 2)
nthreads--;
if (nthreads > 1) {
/* each threads computes W[iifirst:iilast] and places them in
* work[0:n-1]; the corresponding errors in work[n:2*n-1];
* the blocks they belong in iwork[0:n-1]; and their indices in
* iwork[n:2*n-1]; */
iifirst = ifirst;
chunk = isize / nthreads;
for (i=1; i<nthreads; i++) {
iilast = iifirst + chunk - 1;
auxarg1 = create_auxarg1(n, D, E, E2, ifirst, ilast, iifirst, iilast,
nsplit, isplit, bsrtol, pivmin, gersch,
&work[0], &work[n], &iwork[n], &iwork[0]);
info = pthread_create(&threads[i], &attr,
eigval_subset_thread_a,
(void *) auxarg1);
assert(info == 0);
iifirst = iilast + 1;
}
iilast = ilast;
auxarg1 = create_auxarg1(n, D, E, E2, ifirst, ilast, iifirst, iilast,
nsplit, isplit, bsrtol, pivmin, gersch,
&work[0], &work[n], &iwork[n], &iwork[0]);
void *status = eigval_subset_thread_a( (void *) auxarg1 );
assert(status == NULL);
/* join threads */
for (i=1; i<nthreads; i++) {
info = pthread_join(threads[i], &status);
assert(info == 0 && status == NULL);
}
/* m counts the numbers of eigenvalues computed by process */
m = isize;
for (j=0; j<isize; j++) {
W[j] = work[j];
Werr[j] = work[j+n];
iblock[j] = iwork[j];
Windex[j] = iwork[j+n];
}
} else {
/* no multithreaded computation */
double wl, wu;
odrrd("I", "B", &n, &dummy, &dummy, &ifirst, &ilast, gersch,
&bsrtol, D, E, E2, &pivmin, &nsplit, isplit, &m, W, Werr,
&wl, &wu, iblock, Windex, work, iwork, &info);
assert(info == 0);
assert(m == ilast-ifirst+1);
}
/* clean up */
free(threads);
free(isplit);
if (max_nthreads > 1) {
pthread_attr_destroy(&attr);
}
return 0;
}
#else
static
int eigval_approx_proc
(proc_t *procinfo, int ifirst, int ilast,
int n, double *D, double *E, double *E2,
int *Windex, int *iblock, double *gersch, tol_t *tolstruct,
double *W, double *Werr, double *Wgap, double *work,
int *iwork)
{
/* Input parameter */
double pivmin = tolstruct->pivmin;
/* Allocate workspace */
int *isplit = (int *) malloc( n * sizeof(int) );
assert(isplit != NULL);
/* This is an unreduced block */
int nsplit = 1;
isplit[0] = n;
/* Set tolerance parameters */
double bsrtol = sqrt(DBL_EPSILON);
/* APPROXIMATE EIGENVALUES */
int m, info;
double wl, wu, dummy;
odrrd("I", "B", &n, &dummy, &dummy, &ifirst, &ilast, gersch,
&bsrtol, D, E, E2, &pivmin, &nsplit, isplit, &m, W, Werr,
&wl, &wu, iblock, Windex, work, iwork, &info);
assert(info == 0);
assert(m == ilast-ifirst+1);
/* clean up */
free(isplit);
return 0;
}
#endif
static
int eigval_root_proc
(proc_t *procinfo, int ifirst, int ilast,
int n, double *D, double *E, double *E2,
int *Windex, int *iblock, double *gersch, tol_t *tolstruct,
double *W, double *Werr, double *Wgap, double *work, int *iwork)
{
/* Input parameter */
double pivmin = tolstruct->pivmin;
/* Create random vector to perturb rrr, same seed */
int two_n = 2*n;
int iseed[4] = {1,1,1,1};
double Dpivot, Dmax;
bool noREP;
int info, i, j;
int IONE = 1, ITWO = 2;
double tmp, tmp1, tmp2;
/* Set tolerance parameters (need to be same as in refine function) */
double rtl = sqrt(DBL_EPSILON);
/* Allocate workspace */
double *randvec = (double *) malloc( 2*n * sizeof(double) );
assert(randvec != NULL);
/* create random vector to perturb rrr and broadcast it */
odrnv(&ITWO, iseed, &two_n, randvec);
/* store shift of initial RRR, here set to zero */
E[n-1] = 0.0;
/* find outer bounds GL, GU for block and spectral diameter */
double gl = D[0];
double gu = D[0];
for (i = 0; i < n; i++) {
gl = fmin(gl, gersch[2*i] );
gu = fmax(gu, gersch[2*i+1]);
}
double spdiam = gu - gl;
/* find approximation of extremal eigenvalues of the block
* odrrk computes one eigenvalue of tridiagonal matrix T
* tmp1 and tmp2 one hold the eigenvalue and error, respectively */
odrrk(&n, &IONE, &gl, &gu, D, E2,
&pivmin, &rtl, &tmp1, &tmp2, &info);
assert(info == 0); /* if info=-1 => eigenvalue did not converge */
double isleft = fmax(gl, tmp1-tmp2 - HUNDRED*DBL_EPSILON*fabs(tmp1-tmp2) );
odrrk(&n, &n, &gl, &gu, D, E2, &pivmin, &rtl, &tmp1, &tmp2, &info);
assert(info == 0); /* if info=-1 => eigenvalue did not converge */
double isright = fmin(gu, tmp1+tmp2 + HUNDRED*DBL_EPSILON*fabs(tmp1+tmp2) );
spdiam = isright - isleft;
/* compute negcount at points s1 and s2 */
double s1 = isleft + HALF * spdiam;
double s2 = isright - FOURTH * spdiam; /* not needed currently */
/* compute negcount at points s1 and s2 */
/* cnt = number of eigenvalues in (s1,s2] = count_right - count_left
* negcnt_lft = number of eigenvalues smaller equals than s1
* negcnt_rgt = number of eigenvalues smaller equals than s2 */
int cnt, negcnt_lft, negcnt_rgt;
odrrc("T", &n, &s1, &s2, D, E, &pivmin,
&cnt, &negcnt_lft, &negcnt_rgt, &info);
assert(info == 0);
/* if more of the desired eigenvectors are in the left part shift left
* and the other way around */
int sgndef;
double sigma;
if ( negcnt_lft >= n - negcnt_lft ) {
/* shift left */
sigma = isleft;
sgndef = ONE;
} else {
/* shift right */
sigma = isright;
sgndef = -ONE;
}
/* define increment to perturb initial shift to find RRR
* with not too much element growth */
double tau = spdiam*DBL_EPSILON*n + 2.0*pivmin;
/* try to find initial RRR of block:
* need work space of 3*n here to store D, L, D^-1 of possible
* representation:
* D_try = work[0 : n-1]
* L_try = work[n :2*n-1]
* inv(D_try) = work[2*n:3*n-1] */
int off_L = n;
int off_invD = 2*n;
int jtry;
for (jtry = 0; jtry < MAX_TRY_RRR; jtry++) {
Dpivot = D[0] - sigma;
work[0] = Dpivot;
Dmax = fabs( work[0] );
j = 0;
for (i = 0; i < n-1; i++) {
work[i+off_invD] = 1.0 / work[i];
tmp = E[j] * work[i+off_invD];
work[i+off_L] = tmp;
Dpivot = (D[j+1] - sigma) - tmp*E[j];
work[i+1] = Dpivot;
Dmax = fmax(Dmax, fabs(Dpivot) );
j++;
}
/* except representation only if not too much element growth */
if (Dmax > MAX_GROWTH*spdiam) {
noREP = true;
} else {
noREP = false;
}
if (noREP == true) {
/* if all eigenvalues are desired shift is made definite to use DQDS
* so we should not end here */
if (jtry == MAX_TRY_RRR-2) {
if (sgndef == ONE) { /* floating point comparison okay here */
sigma = gl - FUDGE_FACTOR*spdiam*DBL_EPSILON*n
- FUDGE_FACTOR*2.0*pivmin;
} else {
sigma = gu + FUDGE_FACTOR*spdiam*DBL_EPSILON*n
+ FUDGE_FACTOR*2.0*pivmin;
}
} else if (jtry == MAX_TRY_RRR-1) {
fprintf(stderr,"No initial representation could be found.\n");
return 3;
} else {
sigma -= sgndef*tau;
tau *= 2.0;
continue;
}
} else { /* found representation */
break;
}
}
/* end trying to find initial RRR of block */
/* save initial RRR and corresponding shift */
memcpy(D, &work[0], n * sizeof(double) );
memcpy(E, &work[n], (n-1) * sizeof(double) );
E[n-1] = sigma;
/* work[0:4*n-1] can now be used again for anything */
/* perturb root rrr by small relative amount, first make sure
* that at least two values are actually disturbed enough,
* which might not be necessary */
while( fabs(randvec[0])*RAND_FACTOR < 1.0 )
randvec[0] *= 2.0;
while( fabs(randvec[n-1]) *RAND_FACTOR < 1.0 )
randvec[n-1] *= 2.0;
for (i=0; i<n-1; i++) {
D[i] *= 1.0 + DBL_EPSILON*RAND_FACTOR*randvec[i];
E[i] *= 1.0 + DBL_EPSILON*RAND_FACTOR*randvec[i+n];
}
D[n-1] *= 1.0 + DBL_EPSILON*RAND_FACTOR*randvec[n-1];
/* clean up */
free(randvec);
return 0;
}
#ifndef DISABLE_PTHREADS
static
int eigval_refine_proc
(proc_t *procinfo, int ifirst, int ilast,
int n, double *D, double *E, double *E2,
int *Windex, int *iblock, double *gersch, tol_t *tolstruct,
double *W, double *Werr, double *Wgap, double *work, int *iwork)
{
/* Input parameter */
int isize = ilast-ifirst+1;
double pivmin = tolstruct->pivmin;
/* Multithreading */
int nthreads;
int max_nthreads = procinfo->nthreads;
int chunk;
pthread_t *threads;
pthread_attr_t attr;
auxarg2_t *auxarg2;
int info, i;
/* Allocate space */
threads = (pthread_t *) malloc( max_nthreads * sizeof(pthread_t) );
assert(threads != NULL);
int *isplit = (int *) malloc( n * sizeof(int) );
assert(isplit != NULL);
/* This is an unreduced block (nsplit=1) */
isplit[0] = n;
/* Prepare multi-threading */
if (max_nthreads > 1) {
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM);
}
/* find outer bounds GL, GU for block and spectral diameter */
double gl = D[0];
double gu = D[0];
for (i = 0; i < n; i++) {
gl = fmin(gl, gersch[2*i] );
gu = fmax(gu, gersch[2*i+1]);
}
double spdiam = gu - gl;
/* REFINE EIGENVALUES i_low:i_upp WITH REPECT TO RRR */
int i_low = Windex[0];
int i_upp = Windex[isize-1];
double sigma = E[n-1];
/* calculate gaps */
for (i=0; i<isize-1; i++) {
Wgap[i] = fmax(0.0, (W[i+1] - Werr[i+1]) - (W[i] + Werr[i]) );
}
Wgap[isize-1] = fmax(0.0, gu - (W[isize-1] + Werr[isize-1]) );
/* shift eigenvalues to be consistent with dqds
* and compute eigenvalues of SHIFTED matrix */
for (i=0; i<isize; i++) {
W[i] -= sigma;
Werr[i] += fabs(W[i])*DBL_EPSILON;
}
/* work for sequential odrrb = work[0:2*n-1]
* iwork for sequential odrrb = iwork[0:2*n-1]
* DE2 = work[2*n:3*n-1] strting at bl_begin */
int off_DE2 = 2*n;
/* compute DE2 at store it in work[bl_begin+2*n:bl_end-1+2*n] */
for (i=0; i<n; i++) {
work[i+off_DE2] = D[i]*E[i]*E[i];
}
nthreads = max_nthreads;
while (nthreads > 1 && isize/nthreads < 2) {
nthreads--;
}
if (nthreads > 1) {
int rf_begin=0, rf_end;
chunk = isize / nthreads;
for (i=1; i<nthreads; i++) {
rf_end = rf_begin + chunk - 1;
auxarg2 = create_auxarg2(n, D,
&work[off_DE2],
rf_begin, rf_end, W, Werr, Wgap, Windex,
tolstruct->rtol1, tolstruct->rtol2,
pivmin, spdiam);
info = pthread_create(&threads[i], &attr,
eigval_subset_thread_r,
(void *) auxarg2);
assert(info == 0);
rf_begin = rf_end + 1;
}
rf_end = isize-1;
auxarg2 = create_auxarg2(n, D,
&work[off_DE2],
rf_begin, rf_end, W, Werr, Wgap, Windex,
tolstruct->rtol1, tolstruct->rtol2,
pivmin, spdiam);
void *status = eigval_subset_thread_r( (void *) auxarg2 );
assert(status == NULL);
/* join threads */
for (i=1; i<nthreads; i++) {
info = pthread_join(threads[i], &status);
assert(info == 0 && status == NULL);
}
/* should update gaps at splitting points here, but the gaps
* will be recomputed anyway */
} else {
int offset = i_low-1;
/* refine eigenvalues found by odrrb for i_low:i_upp */
odrrb(&n, D, &work[off_DE2], &i_low,
&i_upp, &tolstruct->rtol1, &tolstruct->rtol2, &offset, W, Wgap,
Werr, work, iwork, &pivmin, &spdiam, &n, &info);
assert(info == 0);
/* needs work of dim(2*n) and iwork of dim(2*n) */
}
/* odrrb computes gaps correctly, but not last one;
* this is ignored since the gaps are recomputed anyway */
/* clean up */
free(threads);
free(isplit);
if (max_nthreads > 1) {
pthread_attr_destroy(&attr);
}
return 0;
}
#else
static
int eigval_refine_proc
(proc_t *procinfo, int ifirst, int ilast,
int n, double *D, double *E, double *E2,
int *Windex, int *iblock, double *gersch, tol_t *tolstruct,
double *W, double *Werr, double *Wgap, double *work, int *iwork)
{
/* Input parameter */
int isize = ilast-ifirst+1;
double pivmin = tolstruct->pivmin;
/* Allocate space */
int *isplit = (int *) malloc( n * sizeof(int) );
assert(isplit != NULL);
/* This is an unreduced block (nsplit=1) */
isplit[0] = n;
/* find outer bounds GL, GU for block and spectral diameter */
double gl = D[0];
double gu = D[0];
int i;
for (i = 0; i < n; i++) {
gl = fmin(gl, gersch[2*i] );
gu = fmax(gu, gersch[2*i+1]);
}
double spdiam = gu - gl;
/* REFINE EIGENVALUES i_low:i_upp WITH REPECT TO RRR */
int i_low = Windex[0];
int i_upp = Windex[isize-1];
double sigma = E[n-1];
/* calculate gaps */
for (i=0; i<isize-1; i++) {
Wgap[i] = fmax(0.0, (W[i+1] - Werr[i+1]) - (W[i] + Werr[i]) );
}
Wgap[isize-1] = fmax(0.0, gu - (W[isize-1] + Werr[isize-1]) );
/* shift eigenvalues to be consistent with dqds
* and compute eigenvalues of SHIFTED matrix */
for (i=0; i<isize; i++) {
W[i] -= sigma;
Werr[i] += fabs(W[i])*DBL_EPSILON;
}
/* work for sequential odrrb = work[0:2*n-1]
* iwork for sequential odrrb = iwork[0:2*n-1]
* DE2 = work[2*n:3*n-1] strting at bl_begin */
int off_DE2 = 2*n;
/* compute DE2 at store it in work[bl_begin+2*n:bl_end-1+2*n] */
for (i=0; i<n; i++) {
work[i+off_DE2] = D[i]*E[i]*E[i];
}
int offset = i_low-1;
/* refine eigenvalues found by odrrb for i_low:i_upp */
int info;
odrrb
(&n, D, &work[off_DE2], &i_low,
&i_upp, &tolstruct->rtol1, &tolstruct->rtol2, &offset, W, Wgap,
Werr, work, iwork, &pivmin, &spdiam, &n, &info);
assert(info == 0);
/* needs work of dim(2*n) and iwork of dim(2*n) */
/* odrrb computes gaps correctly, but not last one;
* this is ignored since the gaps are recomputed anyway */
/* clean up */
free(isplit);
return 0;
}
#endif
static
void *eigval_subset_thread_a(void *argin)
{
/* from input argument */
int n, il, iu, my_il, my_iu;
double *D, *E, *E2, *gersch;
double bsrtol, pivmin;
int nsplit, *isplit;
/* others */
int info;
double dummy1, dummy2;
int num_vals;
double *W_tmp, *Werr_tmp, *W, *Werr;
int *iblock_tmp, *Windex_tmp, *iblock, *Windex;
double *work;
int *iwork;
retrieve_auxarg1((auxarg1_t *) argin, &n, &D, &E, &E2,
&il, &iu, &my_il, &my_iu, &nsplit,
&isplit, &bsrtol, &pivmin, &gersch,
&W, &Werr, &Windex, &iblock);
/* allocate memory */
W_tmp = (double *) malloc( n * sizeof(double) );
assert(W_tmp != NULL);
Werr_tmp = (double *) malloc( n * sizeof(double) );
assert(Werr_tmp != NULL);
Windex_tmp = (int *) malloc( n * sizeof(int) );
assert(Windex_tmp != NULL);
iblock_tmp = (int *) malloc( n * sizeof(int) );
assert(iblock_tmp != NULL);
work = (double *) malloc( 4*n * sizeof(double) );
assert (work != NULL);
iwork = (int *) malloc( 3*n * sizeof(int) );
assert (iwork != NULL);
/* compute eigenvalues 'my_il' to 'my_iu', put into temporary arrays */
odrrd("I", "B", &n, &dummy1, &dummy2, &my_il, &my_iu, gersch,
&bsrtol, D, E, E2, &pivmin, &nsplit, isplit, &num_vals,
W_tmp, Werr_tmp, &dummy1, &dummy2, iblock_tmp, Windex_tmp,
work, iwork, &info);
assert(info == 0);
/* copy computed values in W, Werr, Windex, iblock (which are work space) */
memcpy(&W[my_il-il], W_tmp, num_vals * sizeof(double) );
memcpy(&Werr[my_il-il], Werr_tmp, num_vals * sizeof(double) );
memcpy(&Windex[my_il-il], Windex_tmp, num_vals * sizeof(int) );
memcpy(&iblock[my_il-il], iblock_tmp, num_vals * sizeof(int) );
free(W_tmp);
free(Werr_tmp);
free(Windex_tmp);
free(iblock_tmp);
free(work);
free(iwork);
return NULL;
}
static
auxarg1_t *create_auxarg1(int n, double *D, double *E, double *E2,
int il, int iu, int my_il, int my_iu,
int nsplit, int *isplit, double bsrtol,
double pivmin, double *gersch, double *W,
double *Werr, int *Windex, int *iblock)
{
auxarg1_t *arg;
arg = (auxarg1_t *) malloc( sizeof(auxarg1_t) );
assert(arg != NULL);
arg->n = n;
arg->D = D;
arg->E = E;
arg->E2 = E2;
arg->il = il;
arg->iu = iu;
arg->my_il = my_il;
arg->my_iu = my_iu;
arg->nsplit = nsplit;
arg->isplit = isplit;
arg->bsrtol = bsrtol;
arg->pivmin = pivmin;
arg->gersch = gersch;
arg->W = W;
arg->Werr = Werr;
arg->Windex = Windex;
arg->iblock = iblock;
return arg;
}
static
void retrieve_auxarg1(auxarg1_t *arg, int *n, double **D, double **E,
double **E2, int *il, int *iu, int *my_il,
int *my_iu, int *nsplit, int **isplit,
double *bsrtol, double *pivmin, double **gersch,
double **W, double **Werr, int **Windex,
int **iblock)
{
*n = arg->n;
*D = arg->D;
*E = arg->E;
*E2 = arg->E2;
*il = arg->il;
*iu = arg->iu;
*my_il = arg->my_il;
*my_iu = arg->my_iu;
*nsplit = arg->nsplit;
*isplit = arg->isplit;
*bsrtol = arg->bsrtol;
*pivmin = arg->pivmin;
*gersch = arg->gersch;
*W = arg->W;
*Werr = arg->Werr;
*Windex = arg->Windex;
*iblock = arg->iblock;
free(arg);
}
static
void *eigval_subset_thread_r(void *argin)
{
/* from input argument */
int bl_size, rf_begin, rf_end;
double *D, *DE2;
double rtol1, rtol2, pivmin;
double bl_spdiam;
/* others */
int info, offset;
double *W, *Werr, *Wgap;
int *Windex;
double *work;
int *iwork;
retrieve_auxarg2((auxarg2_t *) argin, &bl_size, &D, &DE2,
&rf_begin, &rf_end, &W, &Werr, &Wgap, &Windex, &rtol1, &rtol2,
&pivmin, &bl_spdiam);
/* malloc work space */
work = (double *) malloc( 2*bl_size * sizeof(double) );
assert(work != NULL);
iwork = (int *) malloc( 2*bl_size * sizeof(int) );
assert(iwork != NULL);
/* special case of only one eigenvalue */
if (rf_begin == rf_end)
Wgap[rf_begin] = 0.0;
offset = Windex[rf_begin] - 1;
/* call bisection routine to refine the eigenvalues */
odrrb(&bl_size, D, DE2, &Windex[rf_begin], &Windex[rf_end],
&rtol1, &rtol2, &offset, &W[rf_begin], &Wgap[rf_begin],
&Werr[rf_begin], work, iwork, &pivmin, &bl_spdiam,
&bl_size, &info);
assert(info == 0);
/* clean up */
free(work);
free(iwork);
return NULL;
}
static
auxarg2_t *create_auxarg2(int bl_size, double *D, double *DE2,
int rf_begin, int rf_end, double *W, double *Werr,
double *Wgap, int *Windex,
double rtol1, double rtol2, double pivmin,
double bl_spdiam)
{
auxarg2_t *arg;
arg = (auxarg2_t *) malloc( sizeof(auxarg2_t) );
assert(arg != NULL);
arg->bl_size = bl_size;
arg->D = D;
arg->DE2 = DE2;
arg->rf_begin = rf_begin;
arg->rf_end = rf_end;
arg->W = W;
arg->Werr = Werr;
arg->Wgap = Wgap;
arg->Windex = Windex;
arg->rtol1 = rtol1;
arg->rtol2 = rtol2;
arg->pivmin = pivmin;
arg->bl_spdiam = bl_spdiam;
return arg;
}
static
void retrieve_auxarg2(auxarg2_t *arg, int *bl_size, double **D,
double **DE2, int *rf_begin, int *rf_end,
double **W, double **Werr, double **Wgap, int **Windex,
double *rtol1, double *rtol2,
double *pivmin, double *bl_spdiam)
{
*bl_size = arg->bl_size;
*D = arg->D;
*DE2 = arg->DE2;
*rf_begin = arg->rf_begin;
*rf_end = arg->rf_end;
*W = arg->W;
*Werr = arg->Werr;
*Wgap = arg->Wgap;
*Windex = arg->Windex;
*rtol1 = arg->rtol1;
*rtol2 = arg->rtol2;
*pivmin = arg->pivmin;
*bl_spdiam = arg->bl_spdiam;
free(arg);
}
/*
* Compare function for using qsort() on an array
* of doubles
*/
static
int cmp(const void *a1, const void *a2)
{
double arg1 = *(double *)a1;
double arg2 = *(double *)a2;
if (arg1 < arg2)
return -1;
else
return 1;
}
| 28.548173 | 78 | 0.586524 |
03a577f4c85b841c31d91d98555c188f83218992 | 12,160 | h | C | include/hfta/groupby_operator_oop.h | o-ran-sc/com-gs-lite | 2bc6bde491e4ae54fb54302c052f23a98482eb92 | [
"Apache-2.0"
] | 105 | 2015-01-02T03:41:13.000Z | 2018-10-13T01:32:02.000Z | include/hfta/groupby_operator_oop.h | o-ran-sc/com-gs-lite | 2bc6bde491e4ae54fb54302c052f23a98482eb92 | [
"Apache-2.0"
] | 1 | 2015-03-09T17:00:38.000Z | 2015-03-16T20:27:34.000Z | include/hfta/groupby_operator_oop.h | o-ran-sc/com-gs-lite | 2bc6bde491e4ae54fb54302c052f23a98482eb92 | [
"Apache-2.0"
] | 28 | 2015-02-23T18:59:03.000Z | 2017-12-20T01:04:57.000Z | /* ------------------------------------------------
Copyright 2014 AT&T Intellectual Property
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 GROUPBY_OPERATOR_OOP_H
#define GROUPBY_OPERATOR_OOP_H
#include "host_tuple.h"
#include "base_operator.h"
#include <list>
#include <vector>
#include "hash_table.h"
#include <cassert>
// TED: should be supplied by the groupby_func
#define _GB_FLUSH_PER_TUPLE_ 1
/* max allowed disorder -- Jin */
// TED: should be supplied by the groupby_func
#define DISORDER_LEVEL 2
//#define NDEBUG
using namespace std;
// ASSUME temporal_type is one of int, uint, llong, ullong
template <class groupby_func, class group, class aggregate, class hasher_func, class equal_func, class temporal_type>
class groupby_operator_oop : public base_operator {
private :
groupby_func func;
/* a list of hash tables, which maintains aggregates for current window and also k previous ones -- Jin */
vector<hash_table<group*, aggregate*, hasher_func, equal_func>* > group_tables;
/* the minimum and maximum window id of the hash tables -- Jin */
temporal_type min_wid, max_wid;
bool flush_finished;
temporal_type curr_table;
typename hash_table<group*, aggregate*, hasher_func, equal_func>::iterator flush_pos;
temporal_type last_flushed_temporal_gb;
temporal_type last_temporal_gb;
int n_slow_flush;
int n_patterns;
public:
groupby_operator_oop(int schema_handle, const char* name) : base_operator(name), func(schema_handle) {
flush_finished = true;
min_wid = 0;
max_wid = 0;
n_slow_flush = 0;
n_patterns = func.n_groupby_patterns();
}
~groupby_operator_oop() {
hash_table<group*, aggregate*, hasher_func, equal_func>* table;
// delete all the elements in the group_tables list;
while (!group_tables.empty()) {
table = group_tables.back();
group_tables.pop_back();
table->clear();
//fprintf(stderr,"Deleting group table (c) at %lx\n",(gs_uint64_t)(table));
delete (table);
}
}
int accept_tuple(host_tuple& tup, list<host_tuple>& result) {
// Push out completed groups
if(!flush_finished) partial_flush(result);
// create buffer on the stack to store key object
char buffer[sizeof(group)];
// extract the key information from the tuple and
// copy it into buffer
group* grp = func.create_group(tup, buffer);
if (!grp) {
//printf("grp==NULL recieved ");
if (func.temp_status_received()) {
//printf("temp status record ");
last_flushed_temporal_gb = func.get_last_flushed_gb ();
last_temporal_gb = func.get_last_gb ();
}
//printf("\n");
//fprintf(stderr,"min_wid=%d, max_wid=%d, last_temporal_gb=%d, last_flushed_temporal_gb=%d, flush_finished=%d\n",min_wid, max_wid, last_temporal_gb, last_flushed_temporal_gb, flush_finished);
/* no data has arrived, and so we ignore the temp tuples -- Jin */
if (group_tables.size()>0) {
gs_int64_t index;
if(last_flushed_temporal_gb >= min_wid){
index = last_flushed_temporal_gb - min_wid;
}else{
index = -(min_wid - last_flushed_temporal_gb); // unsigned arithmetic
}
if (func.flush_needed() && index>=0) {
#ifdef NDEBUG
//fprintf(stderr, "flush needed: last_flushed_gb %u , min_wid %u \n", last_flushed_temporal_gb, min_wid);
#endif
// Init flush on first temp tuple -- Jin
if ( !flush_finished) {
#ifdef NDEBUG
//fprintf(stderr, "last_flushed_gb is %u, min_wid is %u \n", last_flushed_temporal_gb, min_wid);
#endif
flush_old(result);
}
if (last_temporal_gb > min_wid && group_tables.size()>0) {
flush_finished = false;
}
// we start to flush from the head of the group tables -- Jin
if(group_tables.size()>0){
flush_pos = group_tables[0]->begin();
}
#ifdef NDEBUG
//fprintf(stderr, "after flush old \n");
#endif
}
}
host_tuple temp_tup;
if (!func.create_temp_status_tuple(temp_tup, flush_finished)) {
temp_tup.channel = output_channel;
result.push_back(temp_tup);
}
tup.free_tuple();
return 0;
}
//fprintf (stderr, "after create group grp=%lx, curr_table = %d\n",(gs_uint64_t)grp, grp->get_curr_gb());
/* This is a regular tuple -- Jin */
typename hash_table<group*, aggregate*, hasher_func, equal_func>::iterator iter;
/* first, decide which hash table we need to work at */
curr_table = grp->get_curr_gb();
if (max_wid == 0 && min_wid == 0) {
group_tables.push_back((new hash_table<group*, aggregate*, hasher_func, equal_func>()));
//fprintf(stderr,"Added (1) hash tbl at %lx, pos=%d\n",(gs_uint64_t)(group_tables.back()),group_tables.size());
max_wid = min_wid = curr_table;
}
if (curr_table < min_wid) {
for (temporal_type i = curr_table; i < min_wid; i++){
group_tables.insert(group_tables.begin(), new hash_table<group*, aggregate*, hasher_func, equal_func>());
//fprintf(stderr,"Added (2) hash tbl at %lx, pos=%d\n",(gs_uint64_t)(group_tables.back()),group_tables.size());
}
min_wid = curr_table;
}
if (curr_table > max_wid) {
hash_table<group*, aggregate*, hasher_func, equal_func>* pt;
for (temporal_type i = max_wid; i < curr_table; i++) {
pt =new hash_table<group*, aggregate*, hasher_func, equal_func>();
group_tables.push_back(pt);
//fprintf(stderr,"Added (3) hash tbl at %lx, pos=%d\n",(gs_uint64_t)(group_tables.back()),group_tables.size());
}
max_wid = curr_table;
}
gs_int64_t index = curr_table - min_wid;
if ((iter = group_tables[index]->find(grp)) != group_tables[index]->end()) {
aggregate* old_aggr = (*iter).second;
func.update_aggregate(tup, grp, old_aggr);
}else{
/* We only flush when a temp tuple is received, so we only check on temp tuple -- Jin */
// create a copy of the group on the heap
if(n_patterns <= 1){
group* new_grp = new group(grp); // need a copy constructor for groups
aggregate* aggr = new aggregate();
// create an aggregate in preallocated buffer
aggr = func.create_aggregate(tup, (char*)aggr);
// hash_table<group*, aggregate*, hasher_func, equal_func>* pt;
group_tables[index]->insert(new_grp, aggr);
}else{
int p;
for(p=0;p<n_patterns;++p){
group* new_grp = new group(grp, func.get_pattern(p));
aggregate* aggr = new aggregate();
aggr = func.create_aggregate(tup, (char*)aggr);
group_tables[index]->insert(new_grp, aggr);
}
}
}
tup.free_tuple();
return 0;
}
int partial_flush(list<host_tuple>& result) {
host_tuple tup;
/* the hash table we should flush is func->last_flushed_gb_0 -- Jin */
/* should we guarantee that everything before func->last_flushed_gb_0 also flushed ??? */
gs_int64_t i;
//fprintf(stderr, "partial_flush size of group_tables = %u, min_wid is %u, max_wid is %u last_temporal_gb=%d \n", group_tables.size(), min_wid, max_wid, last_temporal_gb);
if(group_tables.size()==0){
flush_finished = true;
//fprintf(stderr, "out of partial flush early \n");
return 0;
}
// emit up to _GB_FLUSH_PER_TABLE_ output tuples.
if (!group_tables[0]->empty()) {
for (i=0; flush_pos!=group_tables[0]->end() && i < _GB_FLUSH_PER_TUPLE_; ++flush_pos, ++i) {
n_slow_flush++;
bool failed = false;
tup = func.create_output_tuple((*flush_pos).first,(*flush_pos).second, failed);
if (!failed) {
tup.channel = output_channel;
result.push_back(tup);
}
//fprintf(stderr,"partial_flush Deleting at Flush_pos=%lx \n",(gs_uint64_t)((*flush_pos).first));
delete ((*flush_pos).first);
delete ((*flush_pos).second);
}
}
// Finalize processing if empty.
if (flush_pos == group_tables[0]->end()) {
/* one window is completely flushed, so recycle the hash table -- Jin */
hash_table<group*, aggregate*, hasher_func, equal_func>* table = group_tables[0];
//fprintf(stderr,"partial_flush Delelting group table %lx\n",(gs_uint64_t)(group_tables[0]));
group_tables[0]->clear();
delete (group_tables[0]);
group_tables.erase(group_tables.begin());
min_wid++;
if (last_temporal_gb > min_wid && group_tables.size()>0) {
flush_pos = group_tables[0]->begin();
} else {
flush_finished = true;
}
}
//fprintf(stderr, "out of partial flush \n");
return 0;
}
/* Where is this function called ??? */ /* externally */
int flush(list<host_tuple>& result) {
host_tuple tup;
typename hash_table<group*, aggregate*, hasher_func, equal_func>::iterator iter;
/* the hash table we should flush is func->last_flushed_gb_0 -- Jin */
/* should we guarantee that everything before func->last_flushed_gb_0 also flushed ??? */
while ( group_tables.size() > 0) {
if (!group_tables[0]->empty()) {
if (flush_finished)
flush_pos = group_tables[0]->begin();
for (; flush_pos != group_tables[0]->end(); ++flush_pos) {
bool failed = false;
tup = func.create_output_tuple((*flush_pos).first,(*flush_pos).second, failed);
if (!failed) {
tup.channel = output_channel;
result.push_back(tup);
}
//fprintf(stderr,"flush_old Deleting at Flush_pos=%lx \n",(gs_uint64_t)((*flush_pos).first));
delete ((*flush_pos).first);
delete ((*flush_pos).second);
}
}
min_wid++;
// remove the hashtable from group_tables
hash_table<group*, aggregate*, hasher_func, equal_func>* table = group_tables[0];
table->clear();
//fprintf(stderr,"flush_old Delelting group table %lx\n",(gs_uint64_t)(group_tables[0]));
delete (table);
group_tables.erase(group_tables.begin());
if(group_tables.size()>0){
flush_pos = group_tables[0]->begin();
}
}
flush_finished = true;
return 0;
}
/* flushes every hash table before last_flush_gb, and get ready to flush the next window -- Jin */
int flush_old(list<host_tuple>& result) {
host_tuple tup;
typename hash_table<group*, aggregate*, hasher_func, equal_func>::iterator iter;
gs_int64_t num, i;
//fprintf(stderr, "flush_old size of group_tables = %u, min_wid is %u, max_wid is %u last_temporal_gb=%d, num=%d\n", group_tables.size(), min_wid, max_wid, last_temporal_gb, num);
num = last_temporal_gb - min_wid;
//If the old table isn't empty, flush it now.
for (i = 0; i < num && group_tables.size() > 0; i++) {
if (!group_tables[0]->empty()) {
for (; flush_pos != group_tables[0]->end(); ++flush_pos) {
bool failed = false;
tup = func.create_output_tuple((*flush_pos).first,(*flush_pos).second, failed);
if (!failed) {
tup.channel = output_channel;
result.push_back(tup);
}
//fprintf(stderr,"flush_old Deleting at Flush_pos=%lx \n",(gs_uint64_t)((*flush_pos).first));
delete ((*flush_pos).first);
delete ((*flush_pos).second);
}
}
min_wid++;
// remove the hashtable from group_tables
hash_table<group*, aggregate*, hasher_func, equal_func>* table = group_tables[0];
table->clear();
//fprintf(stderr,"flush_old Delelting group table %lx\n",(gs_uint64_t)(group_tables[0]));
delete (table);
group_tables.erase(group_tables.begin());
if(group_tables.size()>0){
flush_pos = group_tables[0]->begin();
}
}
flush_finished = true;
//fprintf(stderr, "end of flush_old \n");
return 0;
}
int set_param_block(int sz, void * value) {
func.set_param_block(sz, value);
return 0;
}
int get_temp_status(host_tuple& result) {
result.channel = output_channel;
return func.create_temp_status_tuple(result, flush_finished);
}
int get_blocked_status () {
return -1;
}
unsigned int get_mem_footprint() {
unsigned int ret;
unsigned int i;
for(i=0;i<group_tables.size();++i)
ret += group_tables[i]->get_mem_footprint() ;
return ret;
}
};
#endif // GROUPBY_OPERATOR_OOP_H
| 30.4 | 191 | 0.68125 |
03a5bd6e92a3dca512ccb8c854129b3e1504ad1f | 1,890 | h | C | include/libsxg/internal/sxg_cbor.h | rgs1/libsxg | 5bfaf438eb1ecb57112c419fb5d7d396dea593a2 | [
"Apache-2.0"
] | null | null | null | include/libsxg/internal/sxg_cbor.h | rgs1/libsxg | 5bfaf438eb1ecb57112c419fb5d7d396dea593a2 | [
"Apache-2.0"
] | null | null | null | include/libsxg/internal/sxg_cbor.h | rgs1/libsxg | 5bfaf438eb1ecb57112c419fb5d7d396dea593a2 | [
"Apache-2.0"
] | null | null | null | // Copyright 2019 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
///////////////////////////////////////////////////////////////////////////////
#ifndef LIBSXG_INTERNAL_SXG_CBOR_H_
#define LIBSXG_INTERNAL_SXG_CBOR_H_
#include "libsxg/sxg_buffer.h"
#ifdef __cplusplus
extern "C" {
#endif
// Appends the initial bytes for a byte string (for internal use).
// Returns true on success.
bool sxg_write_bytes_cbor_header(uint64_t length, sxg_buffer_t* target);
// Appends the initial bytes for a utf-8 string (for internal use).
// Returns true on success.
bool sxg_write_utf8_cbor_header(uint64_t length, sxg_buffer_t* target);
// Appends the header for a map (visible for testing).
// Returns true on success.
bool sxg_write_map_cbor_header(size_t size, sxg_buffer_t* target);
// Appends the initial bytes for a array.
// Returns true on success.
bool sxg_write_array_cbor_header(uint64_t length, sxg_buffer_t* target);
// Appends utf-8 encoded string to the buffer. `string` must be null terminated.
// Returns true on success.
bool sxg_write_utf8string_cbor(const char* string, sxg_buffer_t* target);
// Appends a byte string encoded in CBOR. Returns true on success.
bool sxg_write_bytes_cbor(const uint8_t* bytes, size_t length,
sxg_buffer_t* target);
#ifdef __cplusplus
} // extern "C"
#endif
#endif // LIBSXG_INTERNAL_SXG_
| 34.363636 | 80 | 0.724868 |
03a7189e556885c1a60b66b5c4ecb2b556d80ca4 | 309 | h | C | Sources/Kore/Graphics5/VertexStructure.h | foundry2D/Kinc | 890baf38d0be53444ebfdeac8662479b23d169ea | [
"Zlib"
] | 203 | 2019-05-30T22:40:19.000Z | 2022-03-16T22:01:09.000Z | Sources/Kore/Graphics5/VertexStructure.h | foundry2D/Kinc | 890baf38d0be53444ebfdeac8662479b23d169ea | [
"Zlib"
] | 136 | 2019-06-01T04:39:33.000Z | 2022-03-14T12:38:03.000Z | Sources/Kore/Graphics5/VertexStructure.h | foundry2D/Kinc | 890baf38d0be53444ebfdeac8662479b23d169ea | [
"Zlib"
] | 211 | 2019-06-05T12:22:57.000Z | 2022-03-24T08:44:18.000Z | #pragma once
#include <Kore/Graphics4/VertexStructure.h>
namespace Kore {
namespace Graphics5 {
typedef Graphics4::VertexData VertexData;
typedef Graphics4::VertexAttribute VertexAttribute;
typedef Graphics4::VertexElement VertexElement;
typedef Graphics4::VertexStructure VertexStructure;
}
}
| 19.3125 | 53 | 0.799353 |
03a76c3b258ee33660384d834e35fd0f412ba115 | 951 | h | C | 111-meiju/meiju/AdViewSDK-3.5.2/AdNetworks/Mopan/lib/MopSplashOfbusecation.h | P79N6A/demo | 0286a294b8f9f83b316e75e8d996e94fb6ab6a53 | [
"Apache-2.0"
] | 4 | 2019-08-14T03:06:51.000Z | 2021-11-15T03:02:09.000Z | 111-meiju/meiju/AdViewSDK-3.5.2/AdNetworks/Mopan/lib/MopSplashOfbusecation.h | P79N6A/demo | 0286a294b8f9f83b316e75e8d996e94fb6ab6a53 | [
"Apache-2.0"
] | null | null | null | 111-meiju/meiju/AdViewSDK-3.5.2/AdNetworks/Mopan/lib/MopSplashOfbusecation.h | P79N6A/demo | 0286a294b8f9f83b316e75e8d996e94fb6ab6a53 | [
"Apache-2.0"
] | 2 | 2019-09-17T06:50:12.000Z | 2021-11-15T03:02:11.000Z | //
// MopSplashOfbusecation.h
// MopSplashSdk
//
// Created by xo on 15/6/15.
// Copyright (c) 2015年 Lijunpeng. All rights reserved.
//
#ifndef MopSplashSdk_MopSplashOfbusecation_h
#define MopSplashSdk_MopSplashOfbusecation_h
#define MopSpotController SAsdNgrWhjADFASd5FWsddEr //Class
#define initWithProductId mfeiSFIFasfg3wSFmksffDS
#define ProductSecret dmSDFosf3msSDowAdsfpLew // param
#define loadDataWithReloadSwitch OPWsnnWKN3SqfdfsAASD
#define andScreenOrientation NDFSs2fnaeASmdfdsfhSD// param
#define showMopPlaque SDiownge1reNsUTRvNBca
#define clickCloseButton KSm3dSAOFmseFskBwmSMFlk
#define MopBannerController SDquoaoao3242D7 //class
#define setBannerWithSize Owehf30jSD29l23r //param
#define AndRootView LSlqdpsfnFDS2Uuiaa
#define showMopBanner KSoqpWNSDWQ2221133Ss
#define removeBannerView PSWQPSPSSdjwnfislakwer
#define addLocation sdkfwiSDPJW23940Md
#endif
| 26.416667 | 74 | 0.794953 |
03aa3bd74e9cbc5a903260bfe91a20c6f16014f6 | 46,099 | h | C | third_party/omr/include_core/unix/zos/edcwccwi.h | xiacijie/omr-wala-linkage | a1aff7aef9ed131a45555451abde4615a04412c1 | [
"Apache-2.0"
] | null | null | null | third_party/omr/include_core/unix/zos/edcwccwi.h | xiacijie/omr-wala-linkage | a1aff7aef9ed131a45555451abde4615a04412c1 | [
"Apache-2.0"
] | null | null | null | third_party/omr/include_core/unix/zos/edcwccwi.h | xiacijie/omr-wala-linkage | a1aff7aef9ed131a45555451abde4615a04412c1 | [
"Apache-2.0"
] | null | null | null | /*******************************************************************************
* Copyright (c) 1988, 2014 IBM Corp. and others
*
* This program and the accompanying materials are made available under
* the terms of the Eclipse Public License 2.0 which accompanies this
* distribution and is available at https://www.eclipse.org/legal/epl-2.0/
* or the Apache License, Version 2.0 which accompanies this distribution and
* is available at https://www.apache.org/licenses/LICENSE-2.0.
*
* This Source Code may also be made available under the following
* Secondary Licenses when the conditions for such availability set
* forth in the Eclipse Public License, v. 2.0 are satisfied: GNU
* General Public License, version 2 with the GNU Classpath
* Exception [1] and GNU General Public License, version 2 with the
* OpenJDK Assembly Exception [2].
*
* [1] https://www.gnu.org/software/classpath/license.html
* [2] http://openjdk.java.net/legal/assembly-exception.html
*
* SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 OR LicenseRef-GPL-2.0 WITH Assembly-exception
*******************************************************************************/
/*
* @ddr_namespace: default
*/
??=ifndef __edcwccwi
??=ifdef __COMPILER_VER__
??=pragma filetag("IBM-1047")
??=endif
#define __edcwccwi 1
#pragma nomargins nosequence
#pragma checkout(suspend)
#if defined(__IBM_METAL__)
#error Language Environment standard C headers \
cannot be used when METAL option is used. \
Correct your header search path.
#endif /* __IBM_METAL__ */
#ifdef __cplusplus
extern "C" {
#endif
#ifndef __EDC_LE
#define __EDC_LE 0x10000000
#endif
#if __TARGET_LIB__ >= __EDC_LE
#pragma map (__dsa_prev, "\174\174DSAPRV")
#pragma map (__ep_find, "\174\174EPFIND")
#pragma map (__fnwsa, "\174\174FNWSA")
#if !defined(_LP64)
#pragma map (__stack_info, "\174\174STACK\174")
#endif
#if defined(__XPLINK__) && !defined(_LP64)
#pragma map (__bldxfd, "\174\174BLDXFD")
#endif
#ifdef _LP64
#pragma map (__set_laa_for_jit, "\174\174SETJIT")
#define __bldxfd(fd) fd
#endif
#if !defined(__features_h) || defined(__inc_features)
#include <features.h>
#endif
#ifndef __types
#include <sys/types.h>
#endif
#if __EDC_TARGET >= 0x41080000
#pragma map (__static_reinit, "\174\174STATRE")
#define __STATIC_REINIT_FULL 1
#endif
/*
* =============================================================
* Function definitions for Language Environment C-Language CWIs
* =============================================================
*/
#ifdef _NO_PROTO
void * __dsa_prev();
void * __ep_find();
void * __fnwsa();
#if defined(__XPLINK__) && !defined(_LP64)
void * __bldxfd();
#endif
#else
/*
* __dsa_prev() -- Do logical or physical DSA backchaining
* ============ ------------------------------------------
*
* note: This routine may ABEND. Caller may need to use CEE3SRP,
* CEEMRCE, etc. to handle ABENDs in this routine.
* (or use signal catcher, sigsetjmp(), and siglongjmp())
*/
void * /* pointer to prior DSA */
__dsa_prev
(
const void * /* pointer to current DSA */
, int /* backchaining request type:
1 = physical
2 = logical */
, int /* starting DSA format:
0 = up
1 = down */
, void * /* called function returns a pointer
to the fetched data (perhaps
moved into this A/S)
note: if callback function cannot
return the requested data, it must
not return -- i.e. it should
longjump back to the user program
that called __dsa_prev() */
(*) /* optional ptr to user-provided
callback function that fetches
data, possibly from other
address space -- NULL = fetch
data from current A/S */
(
void * /* 1st input parm for callback fcn --
starting address of data to be
fetched (perhaps from other A/S) */
, size_t /* 2nd input parm or callback fcn --
length of data to be fetched
(will not exceed 16 bytes) */
)
, const void * /* pointer to LE CAA -- required if
4th argument is non-NULL.
Note: this may be the address of
CAA in the other A/S */
, int * /* optional ptr to output field
where previous DSA stack format
will be returned -- NULL = don't
pass back stack format */
, void ** /* optional pointer to output field
where address of physical callee
DSA will be placed -- NULL =
don't pass back physical callee
address */
, int * /* optional ptr to output field
where physical callee stack format
will be returned -- NULL = don't
pass back stack format */
);
/*
* __ep_find() -- find entry point of owner of passed-in DSA
* =========== ------------------------------------------
*/
void * /* pointer to entry point -- NULL =
could not find */
__ep_find
(
const void * /* pointer to DSA */
, int /* DSA format:
0 = up
1 = down */
, void * /* called function returns a pointer
to the fetched data (perhaps
moved into this A/S)
note: if callback function cannot
return the requested data, it must
not return -- i.e. it should
longjump back to the user program
that called __dsa_prev() */
(*) /* optional ptr to user-provided
callback function that fetches
data, possibly from other
address space -- NULL = fetch
data from current A/S */
(
void * /* 1st input parm for callback fcn --
starting address of data to be
fetched (perhaps from other A/S) */
, size_t /* 2nd input parm or callback fcn --
length of data to be fetched
(will not exceed 16 bytes) */
)
);
/*
* __fnwsa() -- find the WSA associated with an executable module
* ========= containing the specified entry point
*
*/
void * /* address of WSA (or NULL if
module doesn't have a WSA) --
-1 == executable module could
not be found from ep */
__fnwsa
(
const void * /* pointer to entry point */
, void * /* called function returns a pointer
to the fetched data (perhaps
moved into this A/S)
note: if callback function cannot
return the requested data, it must
not return -- i.e. it should
longjump back to the user program
that called __fnwsa() */
(*) /* optional ptr to user-provided
callback function that fetches
data, possibly from other
address space -- NULL = fetch
data from current A/S */
(
void * /* 1st input parm for callback fcn --
starting address of data to be
fetched (perhaps from other A/S) */
, size_t /* 2nd input parm or callback fcn --
length of data to be fetched
(will not exceed 1K bytes) */
)
, const void * /* pointer to LE CAA -- required if
2nd argument is non-NULL.
Note: this may be the address of
CAA in the other A/S */
);
#if defined(__XPLINK__) && !defined(_LP64)
/*
* __bldxfd() -- build an XPLINK Compatibility Descriptor out of a
* ========= "function pointer" of unknown origin
*
*/
char * /* address of storage contain
XPLINK Compatibility Descriptor */
__bldxfd
(
void * /* pointer to entry point */
);
#endif /* __XPLINK__ && !LP64 */
typedef
struct __jumpinfo_vr_ext
{
short __ji_ve_version;
char __ji_ve_u[14];
U_128 __ji_ve_savearea[32];
} __jumpinfo_vr_ext_t_;
#if ((!defined(_LP64) && defined(__XPLINK__)) || \
(defined(_LP64) && (__EDC_TARGET >= __EDC_LE4107)))
typedef
struct __jumpinfo
{
/*Note - offsets are for 31-bit expansion*/
char __ji_u1[68]; /* +0 Reserved */
char __ji_mask_saved; /* +44 when non-zero
indicates signal mask
saved in __ji_sigmask*/
char __ji_u2[3]; /* +45 Reserved */
#ifdef __DOT1
sigset_t __ji_sigmask; /* +48 signal mask */
#else
unsigned int __ji_u2a; /* +48 Filler for non-posix*/
unsigned int __ji_u2b; /* +4C Filler for non-posix*/
#endif
char __ji_u3[11]; /* +50 Reserved */
unsigned __ji_fl_fp4 :1; /* +5B.0 4 FPRs valid */
unsigned __ji_fl_fp16 :1; /* +5B.1 16 FPRs valid */
unsigned __ji_fl_fpc :1; /* +5B.2 FPC valid */
unsigned __ji_fl_res1a :1; /* +5B.3 reserved */
#ifndef _LP64
unsigned __ji_fl_hr :1; /* +5B.4 Hi regs valid */
#else
unsigned __ji_fl_res3 :1; /* +5B.4 Reserved */
#endif
unsigned __ji_fl_res2 :1; /* +5B.5 Reserved */
unsigned __ji_fl_exp :1; /* +5B.6 explicit backchain */
unsigned __ji_fl_res2a :1; /* +5B.7 Reserved */
char __ji_u4[12]; /* +5C Reserved @D4C*/
__jumpinfo_vr_ext_t_ *__ji_vr_ext; /* +68 Pointer to VRs
save area @D4A*/
#ifndef _LP64 /* @D4A*/
char __ji_u7[4]; /* +6C Reserved @D4A*/
#endif /* @D4A*/
char __ji_u8[16]; /* +70 Reserved @D4A*/
long __ji_gr[16]; /* +80 resume registers */
#ifndef _LP64
long __ji_hr[16]; /* +C0 hi regs */
#endif
int __ji_u5[16]; /* +100 Reserved */
double __ji_fpr[16]; /* +140 FP registers 0-15 */
int __ji_fpc; /* +1C0 Floating pt cntl reg*/
char __ji_u6[60]; /* +1C4 Reserved */
/* +200 End of Resume area */
} __jumpinfo_t;
/**********************************************************************
* __far_jump() -- perform far jump *
**********************************************************************
*/
void
__far_jump
(
struct __jumpinfo * /* pointer to jump info buffer */
);
#endif
#if !defined(_LP64)
#if defined(__XPLINK__)
/*******************************************************************
* __set_stack_softlimit() -- Set stack softlimit *
*******************************************************************
*/
unsigned long /* returns the previous value of the
softlimit (ULONG_MAX returned if
first call) */
__set_stack_softlimit
(
unsigned long /* soft limit stack size in bytes */
);
#endif /* __XPLINK__ */
#else
#define __set_stack_softlimit(a) \
struct __no64bitSupport __set_stack_softlimit
#endif /* ! _LP64 */
#ifdef _LP64
typedef
struct __laa_jit_s {
void * user_data1;
void * user_data2;
} __laa_jit_t;
/**********************************************************************
* __set_laa_for_jit() -- set 2 reserved fields in the LAA for JAVA *
**********************************************************************
*/
int __set_laa_for_jit ( __laa_jit_t *laa_jit);
#endif /* _LP64 */
#if defined(__XPLINK__)
typedef
struct __mcontext
{
/*Note - offsets are for 31-bit expansion*/
char __mc__1[68]; /* +0 Reserved */
char __mc_mask_saved; /* +44 when non-zero
indicates signal mask
saved in __mc_sigmask*/
char __mc__2[2]; /* +45 Reserved */
unsigned __mc__3 :3; /* +47 Reserved */
unsigned __mc_psw_flag :1; /* +47.3 __mc_psw PSW valid */
#if __EDC_TARGET >= __EDC_LE4107 /* was '__EDC_LE410A' Modified for jit_freeSystemStackPointer */
unsigned __mc_int_dsa_flag :1; /* +47.4 __mc_int_dsa
is valid @D2A*/
unsigned __mc_savstack_flag :1; /* +47.5 __mc_int_dsa was
saved from (must be
restored to)
CEECAA_SAVSTACK
(31-bit) or
CEELCA_SAVSTACK
(64-bit) @D2A*/
unsigned __mc_savstack_async_flag:1;/*+47.6 __mc_int_dsa was
saved from (must be
restored to) the
field pointed to by
CEECAA_SAVSTACK_ASYNC
(31-bit) or
CEELCA_SAVSTACK_ASYNC
(64-bit) @D2A*/
unsigned __mc__4 :1; /* +47.7 Reserved @D2A*/
#else
unsigned __mc__4 :4; /* +47 Reserved */
#endif /* __EDC_TARGET >= __EDC_LE410A */
#ifdef __DOT1
sigset_t __mc_sigmask; /* +48 signal mask for posix*/
#else
unsigned int __mc__4a; /* +48 Filler for non-posix*/
unsigned int __mc__4b; /* +4C Filler for non-posix*/
#endif
char __mc__5[11]; /* +50 Reserved */
unsigned __mc_fl_fp4 :1; /* +5B.0 4 FPRs valid */
unsigned __mc_fl_fp16 :1; /* +5B.1 16 FPRs valid */
unsigned __mc_fl_fpc :1; /* +5B.2 FPC valid */
unsigned __mc_fl_res1a :1; /* +5B.3 Reserved */
unsigned __mc_fl_hr :1; /* +5B.4 Hi regs valid */
unsigned __mc_fl_res2 :1; /* +5B.5 Reserved */
unsigned __mc_fl_exp :1; /* +5B.6 Explicit backchain */
unsigned __mc_fl_res2a :1; /* +5B.7 Reserved */
/*#@ BEGIN @D5A*/
unsigned __mc_fl_res2b :2; /* +5C.0 Reserved */
unsigned __mc_fl_vr :1; /* +5C.2 Vector savearea valid*/
unsigned __mc_fl_res2c :5; /* +5C.x Reserved */
char __mc__6a[11]; /* +5D Reserved */
void *__mc_vr_ext; /* +68 ptr to vrs save area */
__pad31 (__mc__6b,4) /* +6C 31-bit reserved */
char __mc__6c[16]; /* +70 Reserved */
/*#@ END @D5A*/
long __mc_gr[16]; /* +80 resume register */
#ifndef _LP64
long __mc_hr_[16]; /* +C0 hi regs */
#endif
int __mc__7[16]; /* +100 Reserved */
double __mc_fpr[16]; /* +140 FP registers 0-15 */
int __mc_fpc; /* +1C0 Floating pt cntl reg*/
char __mc__8[60]; /* +1C4 Reserved */
__pad31 (__mc__9,16) /* reserved 31-bit */
__pad64 (__mc__9,8) /* reserved 64-bit */
struct __mcontext *__mc_aux_mcontext_ptr;/* +210 ptr __mcontext */
__pad31 (__mc__10,12) /* +214 reserved 31-bit */
__pad64 (__mc__10,24) /* +218 reserved 64-bit */
__pad31 (__mc_psw,8 ) /* 8-byte PSW for 31-bit */
__pad64 (__mc_psw,16) /* 16-byte PSW for 64-bit */
/* Note- __mc_psw is valid only if __mc_psw_flag is set */
#if __EDC_TARGET >= __EDC_LE410A
void *__mc_int_dsa; /* +228 interrupt DSA @D2A*/
/* Note- __mc_int_dsa is only valid if __mc_int_dsa_flag is set */
__pad31 (__mc__11,84) /* reserved 31-bit @D2A*/
__pad64 (__mc__11,104) /* reserved 64-bit @D2A*/
#else
__pad31 (__mc__11,88) /* reserved 31-bit */
__pad64 (__mc__11,112) /* reserved 64-bit */
#endif /* __EDC_TARGET >= __EDC_LE410A */
/* +280 End of Resume area */
} __mcontext_t_;
#endif /* __XPLINK__ */
__new4108(int,__static_reinit,(int,void *));
#endif /* _NO_PROTO */
/*
* Constants for __dsa_prev() and __ep_find() and __stack_info()
* -------------------------------------------------------------
*/
#define __EDCWCCWI_PHYSICAL 1 /* do physical backchain */
#define __EDCWCCWI_LOGICAL 2 /* do logical backchain */
#define __EDCWCCWI_UP 0 /* stack format = UP */
#define __EDCWCCWI_DOWN 1 /* stack format = DOWN */
/******************************************************************/
/* define's for VHM events and structure required as input to the */
/* VHM event calls */
/******************************************************************/
#if __EDC_TARGET >= __EDC_LE4103
#ifdef __cplusplus
#ifndef _LP64
#ifdef __XPLINK__
extern "OS_UPSTACK" void __cee_heap_manager(int, void *);
#else
extern "OS" void __cee_heap_manager(int, void *);
#endif
#endif
#else
void __cee_heap_manager(int ,void *);
#ifndef _LP64
#ifdef __XPLINK__
#pragma linkage(__cee_heap_manager, OS_UPSTACK)
#else
#pragma linkage(__cee_heap_manager, OS)
#endif
#endif
#endif
#define _VHM_INIT 1
#define _VHM_TERM 2
#define _VHM_CEEDUMP 3
#define _VHM_REPORT 4
/****** struct __event1_s ******/
struct __event1_s {
void * __ev1_free;
void * __ev1_malloc;
void * __ev1_realloc;
void * __ev1_calloc;
void * __ev1_xp_free;
void * __ev1_xp_malloc;
void * __ev1_xp_realloc;
void * __ev1_xp_calloc;
unsigned int __ev1_le_xplink : 1,
__ev1_le_reserved : 31;
unsigned int __ev1_vhm_xplink : 1,
__ev1_vhm_reserved : 31;
};
#if __EDC_TARGET >= __EDC_LE4106
/*****************************************************************/
/* __vhm_event() PROTOTYPE */
/*****************************************************************/
#pragma map (__vhm_event, "\174\174VHMEVT")
/*****************************************************************/
/* NOTE !!! At this moment this API is just supporting to drive */
/* the _VHM_REPORT as the event argument with VHM_CLEAR as */
/* the optional argument in MEMCHECK VHM. It could support */
/* more events and more event options in the future. */
/*****************************************************************/
void __vhm_event(int, ...);
/*****************************************************************/
/* __vhm_event() EVENT OPTIONS. Used in the optional argument. */
/*****************************************************************/
#define _VHM_REPORT_CLEAR 0x01 /* Used by _VHM_REPORT event to */
/* free the resources previously */
/* logged by MEMCHECK. */
#endif /* __EDC_TARGET >= __EDC_LE4106 */
#endif /* __EDC_TARGET >= __EDC_LE4103 */
#if !defined(_LP64)
#ifdef _OPEN_THREADS
#include <pthread.h>
typedef struct __segaddrs{
void * __startaddr;
void * __endaddr;
int __segtype;
int padding;
}SegmentAddresses;
typedef struct __stackinfo {
int __structsize;
int __numsegs;
void * __stacktop;
void * resrv;
SegmentAddresses __segaddr[1];
}STACKINFO;
__new4102(int, __stack_info, (STACKINFO *, struct __thdq_ *));
#endif
#else
#define __stack_info(a,b) \
struct __no64bitSupport __stack_info
#endif
#if __EDC_TARGET >= __EDC_LE4107 /* was '__EDC_LE410A' Modified for jit_freeSystemStackPointer */
#ifndef _LP64
#define __LE_SAVSTACK_ADDR ((void**)__gtca()+250)
#define __LE_SAVSTACK_ASYNC_ADDR ((void**)__gtca()+253)
#else
#ifndef __LAA_P
#define __LAA_P ((void *)*((void * __ptr32 *)0x04B8ul))
#endif
#define __LE_SAVSTACK_ADDR \
(((void**)(*(((void**)(__LAA_P))+11)))+4)
#define __LE_SAVSTACK_ASYNC_ADDR \
(((void**)(*(((void**)(__LAA_P))+11)))+42)
#endif
#endif /* __EDC_TARGET >= __EDC_LE410A */
#endif /* __TARGET_LIB__ >= __EDC_LE */
#ifdef __cplusplus
}
#endif
#pragma checkout(resume)
??=endif /* __edcwccwi */
| 75.079805 | 135 | 0.231198 |
03ac3b15fba74f3b083aab6ee0e64365706437da | 623 | c | C | collegeProjects/C-Study/C - List/LC_021_01.c | Lucas-Dalamarta/My-Studies | a86157a5009f746faf6b1084f4c71c37aabe050f | [
"MIT"
] | null | null | null | collegeProjects/C-Study/C - List/LC_021_01.c | Lucas-Dalamarta/My-Studies | a86157a5009f746faf6b1084f4c71c37aabe050f | [
"MIT"
] | null | null | null | collegeProjects/C-Study/C - List/LC_021_01.c | Lucas-Dalamarta/My-Studies | a86157a5009f746faf6b1084f4c71c37aabe050f | [
"MIT"
] | null | null | null | int main()
{
int i , id , qrp=0 , qro=0 , qrr=0 , mir=0 , mip=0 , pp=0;
char op;
for(i=0;i<100;i++){
printf("Digite a idade :\n");scanf("%d",&id);
getchar();
printf("Escolha a nota [otimo=o],[bom=b],[regular=e],[ruim=r],[pessimo=p]\n");scanf("%c",&op);
switch(op){
case 'o':qro++;break;
case 'r':qrr++;mir=id+mir;break;
case 'p':{if(id>mip){mip=id;}qrp++;break;
default : printf("\n");break;
}
getchar();
}}
pp=qrp*100/i;
mir=mir/qrr;
printf("Quantidade otimo %d\n",qro);
printf("Media id ruim %d\n",mir);
printf("Porcent %d\n",pp);
printf("Maior idade pes%d\n",mip);
return 0;
}
| 23.961538 | 96 | 0.563403 |
03aeb6d1fdb9b344c13ed0ff962b2a113034bab2 | 1,101 | h | C | Libraries/TWRefresh/Base/TWRefreshView.h | mumabinggan/JHKit_Static | fa3e8b462e51ba96b7ebf35a9eb8fabb6d188987 | [
"Apache-2.0"
] | null | null | null | Libraries/TWRefresh/Base/TWRefreshView.h | mumabinggan/JHKit_Static | fa3e8b462e51ba96b7ebf35a9eb8fabb6d188987 | [
"Apache-2.0"
] | null | null | null | Libraries/TWRefresh/Base/TWRefreshView.h | mumabinggan/JHKit_Static | fa3e8b462e51ba96b7ebf35a9eb8fabb6d188987 | [
"Apache-2.0"
] | null | null | null | //
// TWRefreshView.h
// EasyBaking
//
// Created by Chris on 9/6/15.
// Copyright (c) 2015 iEasyNote. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "TWRefreshIndicator.h"
typedef NS_ENUM(NSInteger, TWRefreshState) {
TWRefreshStateNormal,
TWRefreshStateReadyToRefresh,
TWRefreshStateRefreshing,
};
@interface TWRefreshView : UIView
{
// Scroll view to be pulling refresh
__weak UIScrollView *_scrollView;
// Indicator
__unsafe_unretained id<TWRefreshIndicator> _indicator;
// Refresh state
TWRefreshState _state;
// Scroll view original content inset
UIEdgeInsets _originalContentInset;
// Refresh inset height added when refreshing
CGFloat _refreshInsetHeight;
}
@property (nonatomic, assign) TWRefreshState state;
// Pulling refresh view
@property (nonatomic, assign, readonly) UIScrollView *scrollView;
// Refresh indicator view
@property (nonatomic, assign) id<TWRefreshIndicator> indicator;
@end
@interface TWRefreshHeaderView : TWRefreshView
@end
@interface TWRefreshFooterView : TWRefreshView
@end | 21.173077 | 65 | 0.737511 |
03b014b5121305e2a39bf21c9dbb56e7060a00c3 | 1,555 | h | C | src/jitlibs/softfloat/softfloat.h | aguynameddhia/etiss_dhia | 06e70cc7b1ca041fe0d6ed48d38df6138cda0fec | [
"BSD-3-Clause"
] | null | null | null | src/jitlibs/softfloat/softfloat.h | aguynameddhia/etiss_dhia | 06e70cc7b1ca041fe0d6ed48d38df6138cda0fec | [
"BSD-3-Clause"
] | null | null | null | src/jitlibs/softfloat/softfloat.h | aguynameddhia/etiss_dhia | 06e70cc7b1ca041fe0d6ed48d38df6138cda0fec | [
"BSD-3-Clause"
] | null | null | null | #ifndef JITLIB_FPFUNCS_H
#define JITLIB_FPFUNCS_H
#include <stdint.h>
/*header file for the static library dbtrise_fp_funcs*/
uint32_t fget_flags();
uint32_t fadd_s(uint32_t v1, uint32_t v2, uint8_t mode);
uint32_t fsub_s(uint32_t v1, uint32_t v2, uint8_t mode);
uint32_t fmul_s(uint32_t v1, uint32_t v2, uint8_t mode);
uint32_t fdiv_s(uint32_t v1, uint32_t v2, uint8_t mode);
uint32_t fsqrt_s(uint32_t v1, uint8_t mode);
uint32_t fcmp_s(uint32_t v1, uint32_t v2, uint32_t op);
uint32_t fcvt_s(uint32_t v1, uint32_t op, uint8_t mode);
uint32_t fmadd_s(uint32_t v1, uint32_t v2, uint32_t v3, uint32_t op, uint8_t mode);
uint32_t fsel_s(uint32_t v1, uint32_t v2, uint32_t op);
uint32_t fclass_s(uint32_t v1);
uint32_t fconv_d2f(uint64_t v1, uint8_t mode);
uint64_t fconv_f2d(uint32_t v1, uint8_t mode);
uint64_t fadd_d(uint64_t v1, uint64_t v2, uint8_t mode);
uint64_t fsub_d(uint64_t v1, uint64_t v2, uint8_t mode);
uint64_t fmul_d(uint64_t v1, uint64_t v2, uint8_t mode);
uint64_t fdiv_d(uint64_t v1, uint64_t v2, uint8_t mode);
uint64_t fsqrt_d(uint64_t v1, uint8_t mode);
uint64_t fcmp_d(uint64_t v1, uint64_t v2, uint32_t op);
uint64_t fcvt_d(uint64_t v1, uint32_t op, uint8_t mode);
uint64_t fmadd_d(uint64_t v1, uint64_t v2, uint64_t v3, uint32_t op, uint8_t mode);
uint64_t fsel_d(uint64_t v1, uint64_t v2, uint32_t op);
uint64_t fclass_d(uint64_t v1);
uint64_t fcvt_32_64(uint32_t v1, uint32_t op, uint8_t mode);
uint32_t fcvt_64_32(uint64_t v1, uint32_t op, uint8_t mode);
uint32_t unbox_s(uint64_t v);
#endif
| 44.428571 | 84 | 0.775563 |
03b3055899492feb0a2829844b0d69548487d0de | 849 | c | C | src/main.c | SIC-RENIC/rutasc | afdea1a53ee2a821411f72af8368ce1737d2603b | [
"BSD-2-Clause"
] | null | null | null | src/main.c | SIC-RENIC/rutasc | afdea1a53ee2a821411f72af8368ce1737d2603b | [
"BSD-2-Clause"
] | null | null | null | src/main.c | SIC-RENIC/rutasc | afdea1a53ee2a821411f72af8368ce1737d2603b | [
"BSD-2-Clause"
] | null | null | null | //
// Created by alfonso on 15/02/20.
//
/**
* Código que busca y genera rutas
*/
#include "rutasc.h"
PLoc ploc_base;
extern void cargaArchivoLocs(char * archlocs, PLoc ploc);
/**
*
* @param cargs
* @param args
* @return
*/
int main(int cargs, char **args){
int cantiloc=0;
int cantieve=0;
if (cargs < 8) {
fprintf(stderr, "No estan completos los parámetros:\n");
fprintf(stderr, "\nrutasc CantiLocs CantiEventos ArchivoLoc ArchivoREve ArchivoSal\n\n");
fprintf(stderr, "\t CantiLocs:\tCantidad de localidades\n");
return 1;
}
cantiloc = atoi(*(args + 1));
cantieve=atoi(*(args + 2));
char *archlocs = *(args + 3);
ploc_base =(PLoc) malloc(sizeof(struct LOCALIDAD) * cantiloc);
cargaArchivoLocs(archlocs,ploc_base);
free(ploc_base);
return 0;
}
| 15.722222 | 97 | 0.618375 |
03b545be885489400375ece2248871758a09ddc8 | 2,051 | h | C | awkcc20/awkcc/tokens.h | chipnetics/awkcc | ade60c877f161a436ace9ab77576d8cf271a9a04 | [
"BSD-2-Clause"
] | 1 | 2022-01-11T10:14:55.000Z | 2022-01-11T10:14:55.000Z | awkcc20/awkcc/tokens.h | chipnetics/awkcc | ade60c877f161a436ace9ab77576d8cf271a9a04 | [
"BSD-2-Clause"
] | null | null | null | awkcc20/awkcc/tokens.h | chipnetics/awkcc | ade60c877f161a436ace9ab77576d8cf271a9a04 | [
"BSD-2-Clause"
] | null | null | null | /***
* Copyright 1987 by AT&T Bell Laboratories.
* All rights reserved.
* Note: Lucent Technologies is now Alcatel-Lucent; some copyrights
* may have been assigned by AT&T to Alcatel-Lucent.
***/
/* Regular expression possibilities */
#define RCARAT 1
#define RREGEXP 2
#define RREGEX 4
#define RNORMAL 8
/* Functions */
#define FATAN 1001
#define FEXP 1002
#define FLENGTH 1003
#define FSYSTEM 1004
#define FCOS 1005
#define FINT 1006
#define FLOG 1007
#define FRAND 1008
#define FSIN 1009
#define FSQRT 1010
#define FSRAND 1011
#define FTOUPPER 1012
#define FTOLOWER 1013
/* Superstatements */
#define COMPSTMT 1500
#define INWHILE 1501
/* constant types */
#define REGEXP 1503
#define FLOAT 1504
#define INT 1505
#define EXTERN 1506
#define UVAR 1507
/* Variable types */
#define SYSVAR 1601
#define SYSARRAY 1602
#define FLOATVAR 1603
#define INTVAR 1604
#define PARAMETER 1605
#define VARPARAM 1606
#define ARRPARAM 1607
/* Functions */
#define USEDCALL 1608
/* Redirection */
#define PIPE 1611
/* Type information */
#define YNUM 0
#define YINT 1
#define YSTR 2
#define YBTH 3
#define YSTRUNK 4
#define YNUMUNK 5
#define YUNK 6
#define YDEP 7
#define YBOOL 8
#define ENDIT 9
/* BOOLEAN */
#define TRUE 1
#define FALSE 0
/* FLAGS */
#define FIXORD 1 /* order of evaluation fix */
#define HASRET 2 /* function has a return? */
#define PRECONV 4 /* +=, -=, etc: pre-conv lval to num? */
#define FELEM 8 /* flag for within IN loops */
#define FREGEXP 1 /* regexp type, flag in varinfo */
#define FGLOBL 2 /* used globally in function, varinfo */
/* For symbols which have not been set as functions, arrays, etc. */
#define SYM 2048
/* STACK OPERATIONS */
#define INVERT 1
#define POP 2
#define PUSH 3
#define POPR 4
#define NULLIFY 5
#define FIND 6
#define CHECKOK 7
#define AFFECT 8
#define AFFECTF 9
#define CSTACK 0
#define CBSTACK 1
#define CBFSTACK 2
/* Garbage that needs to get into the yacc */
#define NIL ((Node *) NULL)
#define makearr(a) a
#define ER sprintf(errbuf,
#define SX ), yyerror(errbuf)
| 17.681034 | 68 | 0.719161 |
03b638c0b3026851c81068ae0aca7d4f5703eb50 | 995 | c | C | json_state_arr_end.c | RhinoDevel/MtJson | ba9bae4a9f05e3f70cb247c88088ce55a1e9a0a3 | [
"0BSD"
] | null | null | null | json_state_arr_end.c | RhinoDevel/MtJson | ba9bae4a9f05e3f70cb247c88088ce55a1e9a0a3 | [
"0BSD"
] | null | null | null | json_state_arr_end.c | RhinoDevel/MtJson | ba9bae4a9f05e3f70cb247c88088ce55a1e9a0a3 | [
"0BSD"
] | null | null | null |
// MT, 2016feb29
#include <assert.h>
#include "Obj.h"
#include "Deb.h"
#include "Stack.h"
#include "json_state_arr_end.h"
enum JsonState json_state_arr_end(struct JsonStateInput * const inObj)
{
enum JsonState retVal = JsonState_err;
assert(inObj!=NULL);
assert(inObj->i<inObj->len);
assert(inObj->str[inObj->i]==']');
++inObj->i;
//Deb_line("]");
void const * const pop = Stack_pop(inObj->stack);
if(pop!=NULL)
{
struct JsonEle * const container = (struct JsonEle *)pop;
if(container->val->type==JsonType_arr)
{
if(inObj->i<inObj->len)
{
inObj->pos = &(container->next);
retVal = JsonState_val_end;
}
else
{
if(Stack_isEmpty(inObj->stack))
{
retVal = JsonState_done;
}
}
}
}
return retVal;
}
| 21.630435 | 71 | 0.489447 |
03b68aea182344c5d760cb1f8f3c061354fc503a | 1,189 | h | C | xiosim/uop_cracker.h | s-kanev/XIOSim | 9673bbd15ba72c9cce15243a462bffb5d9ded9ae | [
"BSD-3-Clause"
] | 55 | 2015-05-29T19:59:33.000Z | 2022-02-08T03:08:15.000Z | xiosim/uop_cracker.h | s-kanev/XIOSim | 9673bbd15ba72c9cce15243a462bffb5d9ded9ae | [
"BSD-3-Clause"
] | 1 | 2015-04-03T04:40:26.000Z | 2015-04-03T04:40:26.000Z | xiosim/uop_cracker.h | s-kanev/XIOSim | 9673bbd15ba72c9cce15243a462bffb5d9ded9ae | [
"BSD-3-Clause"
] | 7 | 2015-04-03T00:28:32.000Z | 2018-09-01T20:53:58.000Z | #ifndef __UOP_CRACKER_H__
#define __UOP_CRACKER_H__
struct Mop_t;
struct uop_t;
namespace xiosim {
namespace x86 {
/* Takes a decoded Mop and fills in the uop flow. */
void crack(struct Mop_t * Mop);
/* Allocate a (properly aligned) array of uops. */
struct uop_t* get_uop_array(const size_t num_uops);
/* Deallocates the uops for a Mop */
void return_uop_array(struct uop_t* p, const size_t num_uops);
/* Max number of uops per Mop */
const size_t MAX_NUM_UOPS = 64;
const size_t UOP_SEQ_SHIFT = 6; // log2(MAX_NUM_UOPS)
/* Max number of input registers per uop. */
const size_t MAX_IDEPS = 3;
/* Max numbder of output registers per uop (1+flags). */
const size_t MAX_ODEPS = 2;
/* Flags for allowing different types of uop fusion. */
struct fusion_flags_t {
bool LOAD_OP:1;
bool STA_STD:1;
bool LOAD_OP_ST:1; /* for atomic Mop execution */
bool FP_LOAD_OP:1; /* same as load op, but for fp ops */
bool matches(fusion_flags_t& rhs) {
return (LOAD_OP && rhs.LOAD_OP) || (STA_STD && rhs.STA_STD) ||
(LOAD_OP_ST && rhs.LOAD_OP_ST) || (FP_LOAD_OP && rhs.FP_LOAD_OP);
}
};
} // xiosim::x86
} // xiosim
#endif /* __UOP_CRACKER_H__ */
| 26.422222 | 80 | 0.687132 |
03b9de20930ecedf298015a33ea2df364e8cfd1f | 1,804 | h | C | plugins/dali-feedback.h | dalihub/dali-adaptor | b7943ae5aeb7ddd069be7496a1c1cee186b740c5 | [
"Apache-2.0",
"BSD-3-Clause"
] | 6 | 2016-11-18T10:26:46.000Z | 2021-11-01T12:29:05.000Z | plugins/dali-feedback.h | dalihub/dali-adaptor | b7943ae5aeb7ddd069be7496a1c1cee186b740c5 | [
"Apache-2.0",
"BSD-3-Clause"
] | 5 | 2020-07-15T11:30:49.000Z | 2020-12-11T19:13:46.000Z | plugins/dali-feedback.h | dalihub/dali-adaptor | b7943ae5aeb7ddd069be7496a1c1cee186b740c5 | [
"Apache-2.0",
"BSD-3-Clause"
] | 7 | 2019-05-17T07:14:40.000Z | 2021-05-24T07:25:26.000Z | #ifndef FEEDBACK_PLUGIN_H
#define FEEDBACK_PLUGIN_H
/*
* Copyright (c) 2021 Samsung Electronics 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.
*
*/
// INTERNAL INCLUDES
#include <dali/devel-api/adaptor-framework/feedback-plugin.h>
namespace Dali
{
namespace Plugin
{
/**
* Plays feedback effects for Dali-Toolkit UI Controls.
*/
class DaliFeedback : public Dali::FeedbackPlugin
{
public: // Construction & Destruction
/**
* Constructor
*/
DaliFeedback();
/**
* Destructor
*/
virtual ~DaliFeedback();
public: // FeedbackPlugin overrides
/**
* @copydoc Dali::Integration::FeedbackPlugin::PlayHaptic()
*/
void PlayHaptic(const std::string& filePath);
/**
* @copydoc Dali::FeedbackPlugin::PlayHapticMonotone()
*/
void PlayHapticMonotone(unsigned int duration);
/**
* @copydoc Dali::FeedbackPlugin::StopHaptic()
*/
void StopHaptic();
/**
* @copydoc Dali::FeedbackPlugin::PlaySound()
*/
int PlaySound(const std::string& fileName);
/**
* @copydoc Dali::FeedbackPlugin::StopSound()
*/
void StopSound(int handle);
/**
* @copydoc Dali::FeedbackPlugin::PlayFeedbackPattern()
*/
void PlayFeedbackPattern(int type, int pattern);
};
} // namespace Plugin
} // namespace Dali
#endif // FEEDBACK_PLUGIN_H
| 22.271605 | 75 | 0.699002 |
03ba35c84ace99e23f02f567b7b78227821bdaa5 | 1,196 | h | C | windows/VC++/DLL/RegularDLL/1096.h | liangjisheng/C-Cpp | 8b33ba1f43580a7bdded8bb4ce3d92983ccedb81 | [
"MIT"
] | 5 | 2019-09-17T09:12:15.000Z | 2021-05-29T10:54:39.000Z | windows/VC++/DLL/RegularDLL/1096.h | liangjisheng/C-Cpp | 8b33ba1f43580a7bdded8bb4ce3d92983ccedb81 | [
"MIT"
] | null | null | null | windows/VC++/DLL/RegularDLL/1096.h | liangjisheng/C-Cpp | 8b33ba1f43580a7bdded8bb4ce3d92983ccedb81 | [
"MIT"
] | 2 | 2021-07-26T06:36:12.000Z | 2022-01-23T15:20:30.000Z | // 1096.h : main header file for the 1096 DLL
//
#if !defined(AFX_1096_H__32553375_58D1_4721_ACE5_4A59A671E0AC__INCLUDED_)
#define AFX_1096_H__32553375_58D1_4721_ACE5_4A59A671E0AC__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#ifndef __AFXWIN_H__
#error include 'stdafx.h' before including this file for PCH
#endif
#include "resource.h" // main symbols
/////////////////////////////////////////////////////////////////////////////
// CMy1096App
// See 1096.cpp for the implementation of this class
//
class CMy1096App : public CWinApp
{
public:
CMy1096App();
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CMy1096App)
//}}AFX_VIRTUAL
//{{AFX_MSG(CMy1096App)
// NOTE - the ClassWizard will add and remove member functions here.
// DO NOT EDIT what you see in these blocks of generated code !
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
/////////////////////////////////////////////////////////////////////////////
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_1096_H__32553375_58D1_4721_ACE5_4A59A671E0AC__INCLUDED_)
| 26 | 97 | 0.666388 |
03bc155f7472778f9d369e5d09abd4294e44bbeb | 728 | h | C | ash/shelf/shelf_navigator.h | nagineni/chromium-crosswalk | 5725642f1c67d0f97e8613ec1c3e8107ab53fdf8 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 4 | 2017-04-05T01:51:34.000Z | 2018-02-15T03:11:54.000Z | ash/shelf/shelf_navigator.h | nagineni/chromium-crosswalk | 5725642f1c67d0f97e8613ec1c3e8107ab53fdf8 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2021-12-13T19:44:12.000Z | 2021-12-13T19:44:12.000Z | ash/shelf/shelf_navigator.h | nagineni/chromium-crosswalk | 5725642f1c67d0f97e8613ec1c3e8107ab53fdf8 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 4 | 2017-04-05T01:52:03.000Z | 2022-02-13T17:58:45.000Z | // Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef ASH_SHELF_SHELF_NAVIGATOR_H_
#define ASH_SHELF_SHELF_NAVIGATOR_H_
#include "ash/ash_export.h"
#include "ash/launcher/launcher_types.h"
namespace ash {
class LauncherModel;
// Scans the current shelf item and returns the index of the shelf item which
// should be activated next for the specified |direction|. Returns -1 if fails
// to find such item.
ASH_EXPORT int GetNextActivatedItemIndex(const LauncherModel& model,
CycleDirection direction);
} // namespace ash
#endif // ASH_SHELF_SHELF_NAVIGATOR_H_
| 30.333333 | 78 | 0.743132 |
03bc27bf03f188155970d587b72cff789d6eb6fe | 31,550 | h | C | game/state/battle/battleunit.h | Skin36/OpenApoc | ab333c6fe8d0dcfc96f044482a38ef81c10442a5 | [
"MIT"
] | null | null | null | game/state/battle/battleunit.h | Skin36/OpenApoc | ab333c6fe8d0dcfc96f044482a38ef81c10442a5 | [
"MIT"
] | null | null | null | game/state/battle/battleunit.h | Skin36/OpenApoc | ab333c6fe8d0dcfc96f044482a38ef81c10442a5 | [
"MIT"
] | null | null | null | #pragma once
#ifndef _USE_MATH_DEFINES
#define _USE_MATH_DEFINES
#endif
#include "game/state/battle/ai/unitai.h"
#include "game/state/battle/battle.h"
#include "game/state/battle/battleunitmission.h"
#include "game/state/gametime.h"
#include "game/state/rules/agenttype.h"
#include "library/sp.h"
#include "library/strings.h"
#include "library/vec.h"
#include <list>
#include <map>
#include <vector>
// How many in-game ticks are required to travel one in-game unit for battleunits
#define TICKS_PER_UNIT_TRAVELLED_BATTLEUNIT 32
// How many in-game ticks are required to pass 1 animation frame
#define TICKS_PER_FRAME_UNIT 8
// Every this amount of units travelled, unit will emit an appropriate sound
#define UNITS_TRAVELLED_PER_SOUND 12
// If running, unit will only emit sound every this number of times it normally would
#define UNITS_TRAVELLED_PER_SOUND_RUNNING_DIVISOR 2
// This defines how fast a flying unit accelerates to full speed
#define FLYING_ACCELERATION_DIVISOR 2
// A bit faster than items
#define FALLING_ACCELERATION_UNIT 0.16666667f // 1/6th
// How far should unit spread information about seeing an enemy
#define DISTANCE_TO_RELAY_VISIBLE_ENEMY_INFORMATION 5
// How far does unit see
#define VIEW_DISTANCE 20
// Base movement ticks consumption rate, this allows us to divide by 2,3,4,5,6,8,9,10,12,15,18,20..
#define BASE_MOVETICKS_CONSUMPTION_RATE 360
// Movement cost in TUs for walking movement to adjacent (non-diagonal) tile
#define STANDART_MOVE_TU_COST 4
namespace OpenApoc
{
static const unsigned TICKS_REGEN_PER_TURN = TICKS_PER_TURN * 3;
static const unsigned TICKS_PER_PSI_CHECK = TICKS_PER_SECOND / 2;
// FIXME: Seems to correspond to vanilla behavior, but ensure it's right
static const unsigned TICKS_PER_WOUND_EFFECT = TICKS_PER_TURN;
static const unsigned TICKS_PER_ENZYME_EFFECT = TICKS_PER_SECOND / 9;
static const unsigned TICKS_PER_FIRE_EFFECT = TICKS_PER_SECOND;
// FIXME: Ensure correct
static const unsigned TICKS_PER_LOWMORALE_STATE = TICKS_PER_TURN;
// FIXME: Ensure correct
static const unsigned LOWMORALE_CHECK_INTERVAL = TICKS_PER_TURN;
// How frequently unit tracks its target
static const unsigned LOS_CHECK_INTERVAL_TRACKING = TICKS_PER_SECOND / 4;
// How many ticks to skip after weapon that was ready to fire could not fire
static const unsigned WEAPON_MISFIRE_DELAY_TICKS = TICKS_PER_SECOND / 16;
// How many times to wait for MIA target to come back before giving up
static const unsigned TIMES_TO_WAIT_FOR_MIA_TARGET =
2 * TICKS_PER_SECOND / LOS_CHECK_INTERVAL_TRACKING;
// How many ticks are required to brainsuck a unit
static const unsigned TICKS_TO_BRAINSUCK = TICKS_PER_SECOND * 2;
// Chance out of 100 to be brainsucked
static const int BRAINSUCK_CHANCE = 66;
static const unsigned TICKS_SUPPRESS_SPOTTED_MESSAGES = TICKS_PER_TURN;
// As per Yataka Shimaoka on forums, cloaking effect returns after 2 seconds of inaction
static const unsigned CLOAK_TICKS_REQUIRED_UNIT = TICKS_PER_SECOND * 2;
class TileObjectBattleUnit;
class TileObjectShadow;
class Battle;
class DamageType;
class AIDecision;
class AIAction;
class AIMovement;
enum class GameEventType;
enum class DamageSource;
class Agent;
enum class MovementMode
{
Running,
Walking,
Prone
};
enum class KneelingMode
{
None,
Kneeling
};
enum class WeaponAimingMode
{
Aimed = 1,
Snap = 2,
Auto = 4
};
enum class ReserveShotMode
{
Aimed = 1,
Snap = 2,
Auto = 4,
None = 0
};
// Unit's general type, used in pathfinding
enum class BattleUnitType
{
SmallWalker,
SmallFlyer,
LargeWalker,
LargeFlyer
};
// Enum for tracking unit's weapon state
enum class WeaponStatus
{
NotFiring,
FiringLeftHand,
FiringRightHand,
FiringBothHands
};
enum class PsiStatus
{
NotEngaged,
Control,
Panic,
Stun,
Probe
};
enum class MoraleState
{
Normal,
PanicFreeze,
PanicRun,
Berserk
};
static const std::list<BattleUnitType> BattleUnitTypeList = {
BattleUnitType::LargeFlyer, BattleUnitType::LargeWalker, BattleUnitType::SmallFlyer,
BattleUnitType::SmallWalker};
class BattleUnit : public StateObject, public std::enable_shared_from_this<BattleUnit>
{
STATE_OBJECT(BattleUnit)
public:
// [Enums]
enum class BehaviorMode
{
Aggressive,
Normal,
Evasive
};
enum class FirePermissionMode
{
AtWill,
CeaseFire
};
// Enum for tracking unit's targeting mode
enum class TargetingMode
{
NoTarget,
Unit,
TileCenter,
TileGround
};
// [Properties]
UString id;
// Unit ownership
StateRef<Agent> agent;
StateRef<Organisation> owner;
// Squad
// Squad number, -1 = not assigned to any squad
int squadNumber = 0;
// Squad position, has no meaning if not in squad
unsigned int squadPosition = 0;
// Attacking and turning to hostiles
WeaponStatus weaponStatus = WeaponStatus::NotFiring;
// What are we targeting - unit or tile
TargetingMode targetingMode = TargetingMode::NoTarget;
// Tile we're targeting right now (or tile with unit we're targeting, if targeting unit)
Vec3<int> targetTile;
// How many times we checked and target we are ready to fire on was MIA
unsigned int timesTargetMIA = 0;
// Unit we're targeting right now
StateRef<BattleUnit> targetUnit;
// Unit we're ordered to focus on (in real time)
StateRef<BattleUnit> focusUnit;
// Units focusing this unit
std::list<StateRef<BattleUnit>> focusedByUnits;
// Ticks until we check if target is still valid, turn to it etc.
unsigned int ticksUntillNextTargetCheck = 0;
// Psi
PsiStatus psiStatus = PsiStatus::NotEngaged;
// Unit in process of being psi attacked by this
StateRef<BattleUnit> psiTarget;
// Item used for psi attack
StateRef<AEquipmentType> psiItem;
// Ticks accumulated towards next psi check
unsigned int ticksAccumulatedToNextPsiCheck = 0;
// Map of units and attacks in progress against this unit
std::map<UString, PsiStatus> psiAttackers;
// Brainsucking
StateRef<BattleUnit> brainSucker;
// Stats
// Accumulated xp points for each stat
AgentStats experiencePoints;
// Points earned for kills
int combatRating = 0;
// Fatal wounds for each body part
std::map<BodyPart, int> fatalWounds;
// Which body part is medikit used on
BodyPart healingBodyPart = BodyPart::Body;
// Is using a medikit
bool isHealing = false;
// Ticks towards next wound damage or medikit heal application
unsigned int woundTicksAccumulated = 0;
// Ticks towards next regeneration of stats (psi, stamina, stun)
unsigned int regenTicksAccumulated = 0;
// Stun damage acquired
int stunDamage = 0;
// Ticks accumulated towards next enzyme hit
unsigned int enzymeDebuffTicksAccumulated = 0;
// Enzyme debuff intensity remaining
int enzymeDebuffIntensity = 0;
// Ticks accumulated towards next fire hit
unsigned int fireDebuffTicksAccumulated = 0;
// Fire debuff intensity remaining
unsigned int fireDebuffTicksRemaining = 0;
// State of unit's morale
MoraleState moraleState = MoraleState::Normal;
// How much time unit has to spend in low morale state
unsigned int moraleStateTicksRemaining = 0;
// Ticks accumulated towards next morale check
unsigned int moraleTicksAccumulated = 0;
// TU at turn start (used to calculate percentage of TU)
int initialTU = 0;
// TU to reserve for shot
int reserveShotCost = 0;
// Stealth, increases each turn, set to 0 when taking action or no stealth in hand
// Unit is cloaked when this is >= CLOAK_TICKS_REQUIRED_UNIT
unsigned int cloakTicksAccumulated = 0;
// Ticks until spound is emmited
int ticksUntillNextCry = 0;
// User set modes
BehaviorMode behavior_mode = BehaviorMode::Normal;
WeaponAimingMode fire_aiming_mode = WeaponAimingMode::Snap;
FirePermissionMode fire_permission_mode = FirePermissionMode::AtWill;
MovementMode movement_mode = MovementMode::Walking;
KneelingMode kneeling_mode = KneelingMode::None;
ReserveShotMode reserve_shot_mode = ReserveShotMode::None;
KneelingMode reserve_kneel_mode = KneelingMode::None;
// Body
// Time, in game ticks, until body animation is finished
unsigned int body_animation_ticks_remaining = 0;
// Required for transition of derived params, like muzzle location
unsigned int body_animation_ticks_total = 0;
// Animations ticks for static body state (no body state change is in progress)
unsigned int body_animation_ticks_static = 0;
BodyState current_body_state = BodyState::Standing;
BodyState target_body_state = BodyState::Standing;
// Hands
// Time, in game ticks, until hands animation is finished
unsigned int hand_animation_ticks_remaining = 0;
// Time, in game ticks, until unit will lower it's weapon
unsigned int residual_aiming_ticks_remaining = 0;
// Time, in game ticks, until firing animation is finished
unsigned int firing_animation_ticks_remaining = 0;
HandState current_hand_state = HandState::AtEase;
HandState target_hand_state = HandState::AtEase;
// Movement
// Distance, in movement ticks, spent since starting to move
unsigned int movement_ticks_passed = 0;
// Movement sounds played
unsigned int movement_sounds_played = 0;
MovementState current_movement_state = MovementState::None;
Vec3<float> position;
Vec3<float> goalPosition;
bool atGoal = false;
bool usingLift = false;
// Value 0 - 100, Simulates slow takeoff, when starting to use flight this slowly rises to 1
unsigned int flyingSpeedModifier = 0;
// Freefalling
bool falling = false;
// Launched (will check launch goal if falling, will travel by parabola if moving)
bool launched = false;
// Goal we launched for, after reaching this will set xy velocity to 0
Vec3<float> launchGoal;
// Bounced after falling
bool bounced = false;
// Ticks to ignore collision when launching
unsigned int collisionIgnoredTicks = 0;
// Current falling/jumping speed
Vec3<float> velocity;
// Movement counter for TB motion scanner
unsigned int tilesMoved = 0;
// Turning
// Time, in game ticks, until unit can turn by 1/8th of a circle
unsigned int turning_animation_ticks_remaining = 0;
Vec2<int> facing;
Vec2<int> goalFacing;
// Missions
// Mission list
std::list<up<BattleUnitMission>> missions;
// Vision
// Item shown in unit's hands
// Units without inventory never show items in hands
StateRef<AEquipmentType> displayedItem;
// Visible units from other orgs
std::set<StateRef<BattleUnit>> visibleUnits;
// Visible units that are hostile to us
std::set<StateRef<BattleUnit>> visibleEnemies;
// Miscellaneous
// Unit successfully retreated from combat
bool retreated = false;
// Unit died and corpse was destroyed in an explosion
bool destroyed = false;
// If unit is asked to give way, this list will be filled with facings
// in order of priority that should be tried by it
std::list<Vec2<int>> giveWayRequestData;
// AI list
AIBlockUnit aiList;
// [Methods]
// Misc methods
// Called before unit is added to the map itself
void init(GameState &state);
// Clears all possible cases of circular refs
void destroy() override;
// Squad
// Remove unit from squad in battle's forces
void removeFromSquad(Battle &b);
// Assign unit to squad (optinally specify squad number and position)
bool assignToSquad(Battle &b, int squadNumber = -1, int squadPosition = -1);
// Fatal wounds
// Wether unit is fatally wounded
bool isFatallyWounded();
// Add fatal wound to a body part
void addFatalWound(BodyPart fatalWoundPart);
// Attacking and turning to hostiles
// Get full cost of attacking (including turn and pose change)
int getAttackCost(GameState &state, AEquipment &item, Vec3<int> tile);
// Set unit's focus (RT)
void setFocus(GameState &state, StateRef<BattleUnit> unit);
// Start attacking a unit
bool startAttacking(GameState &state, StateRef<BattleUnit> unit,
WeaponStatus status = WeaponStatus::FiringBothHands);
// Start attacking a tile
bool startAttacking(GameState &state, Vec3<int> tile,
WeaponStatus status = WeaponStatus::FiringBothHands, bool atGround = false);
// Cease attacking
void stopAttacking();
// Returns which hands can be used for an attack (or none if attack cannot be made)
// Checks wether target unit is in range, and clear LOF exists to it
WeaponStatus canAttackUnit(GameState &state, sp<BattleUnit> unit);
// Returns wether unit can be attacked by one of the two supplied weapons
// Checks wether target unit is in range, and clear LOF exists to it
WeaponStatus canAttackUnit(GameState &state, sp<BattleUnit> unit, sp<AEquipment> rightHand,
sp<AEquipment> leftHand = nullptr);
// Clear LOF means no friendly fire and no map part in between
// Clear LOS means nothing in between
bool hasLineToUnit(const sp<BattleUnit> unit, bool useLOS = false) const;
// Clear LOF means no friendly fire and no map part in between
// Clear LOS means nothing in between
bool hasLineToPosition(Vec3<float> targetPosition, bool useLOS = false) const;
// Psi
// Get cost of psi attack or upkeep
int getPsiCost(PsiStatus status, bool attack = true);
// Get chance of psi attack to succeed
int getPsiChance(StateRef<BattleUnit> target, PsiStatus status, StateRef<AEquipmentType> item);
// Starts attacking taget, returns if attack successful
bool startAttackPsi(GameState &state, StateRef<BattleUnit> target, PsiStatus status,
StateRef<AEquipmentType> item);
// Stop / break psi attack
void stopAttackPsi(GameState &state);
// Applies psi attack effects to this unit, returns false if attack must be terminated because
// of some failure
void applyPsiAttack(GameState &state, BattleUnit &attacker, PsiStatus status,
StateRef<AEquipmentType> item, bool impact);
// Cange unit's owner (mind control)
void changeOwner(GameState &state, StateRef<Organisation> newOwner);
// Items
// Attempts to use item, returns if success
bool useItem(GameState &state, sp<AEquipment> item);
// Use medikit on bodypart
bool useMedikit(GameState &state, BodyPart part);
// Use brainsucker ability
bool useBrainsucker(GameState &state);
// Use unit spawner (suicide)
bool useSpawner(GameState &state, sp<AEquipmentType> item);
// Body
// Get body animation frame to be drawn
unsigned int getBodyAnimationFrame() const;
// Set unit's body state
void setBodyState(GameState &state, BodyState bodyState);
// Begin unit's body change towards target body state
void beginBodyStateChange(GameState &state, BodyState bodyState);
// Hands
// Get hand animation frame to be drawn
unsigned int getHandAnimationFrame() const;
// Set unit's hand state
void setHandState(HandState state);
// Begin unit's hand state change towards target state
void beginHandStateChange(HandState state);
// Wether unit is allowed to change handState to target state
bool canHandStateChange(HandState state);
// Movement
// Set unit's movement state
void setMovementState(MovementState state);
// Get distance that unit has travelled (used in drawing and footstep sounds)
unsigned int getDistanceTravelled() const;
// User set modes
// Set unit preferred movement mode
void setMovementMode(MovementMode mode);
// Set unit preferred kneeling mode
void setKneelingMode(KneelingMode mode);
// Set unit preferred weapon aiming mode
void setWeaponAimingMode(WeaponAimingMode mode);
// Set unit fire permission mode
void setFirePermissionMode(FirePermissionMode mode);
// Set unit behavior mode
void setBehaviorMode(BehaviorMode mode);
// Set unit's reserve TU for fire mode
void setReserveShotMode(GameState &state, ReserveShotMode mode);
// Set unit's reserve TU for kneeling mode
void setReserveKneelMode(KneelingMode mode);
// Sound
// Should the unit play walk step sound now
bool shouldPlaySoundNow();
// Current sound index for the unit
unsigned int getWalkSoundIndex();
// Play walking sound
void playWalkSound(GameState &state);
// Play sound adjusting gain by distance to closest player unit
void playDistantSound(GameState &state, sp<Sample> sfx, float gainMult = 1.0f);
// Init the delay before first time unit emits a cry in combat
void initCryTimer(GameState &state);
// Reest the delay before unit emits a cry next time in combat
void resetCryTimer(GameState &state);
// Movement and position
// Set unit's goal to unit's position
void resetGoal();
// Get new goal for unit position, returns true if goal acquired
bool getNewGoal(GameState &state);
// Updates to do when unit reached goal
void onReachGoal(GameState &state);
// Calculate velocity for jumping (manually) towards target,
// returning fastest allowed velocity that makes unit drop on top of the tile.
// Returns true if successful, false if not
// For explanation how it works look @ AEquipment::calculateNextVelocityForThrow
bool calculateVelocityForLaunch(float distanceXY, float diffZ, float &velocityXY,
float &velocityZ, float initialXY = 0.5f);
// Calculates velocity for jumping (during movement, auto-jump over tile gap)
// For explanation how it works look @ AEquipment::calculateNextVelocityForThrow
void calculateVelocityForJump(float distanceXY, float diffZ, float &velocityXY,
float &velocityZ, bool diagonAlley);
// Returns wether unit can launch towards target position
bool canLaunch(Vec3<float> targetPosition);
// Returns wether unit can launch, and calculates all vectors and velocities if yes
bool canLaunch(Vec3<float> targetPosition, Vec3<float> &targetVectorXY, float &velocityXY,
float &velocityZ);
// Launch unit towards target position
void launch(GameState &state, Vec3<float> targetPosition,
BodyState bodyState = BodyState::Standing);
// Start unit's falling routine
void startFalling(GameState &state);
// Make unit move
void startMoving(GameState &state);
// Set unit's position
void setPosition(GameState &state, const Vec3<float> &pos, bool goal = false);
// Get unit's velocity (for purpose of leading the unit
Vec3<float> getVelocity() const;
// Turning
// Set unit's facing
void setFacing(GameState &state, Vec2<int> newFacing);
// Begin turning unit towards new facing
void beginTurning(GameState &state, Vec2<int> newFacing);
// Missions
// Pops all finished missions, returns true if popped
bool popFinishedMissions(GameState &state);
// Returns wether unit has a mission queued that will make it move
bool hasMovementQueued();
// Gets next destination from current mission, returns true if got one
bool getNextDestination(GameState &state, Vec3<float> &dest);
// Gets next facing from current mission, returns true if got one
bool getNextFacing(GameState &state, Vec2<int> &dest);
// Gets next body state from current mission, returns true if got one
bool getNextBodyState(GameState &state, BodyState &dest);
// Add mission, if possible to the front, otherwise to the back
// (or, if toBack = true, then always to the back)
// Returns true if succeeded in adding
bool addMission(GameState &state, BattleUnitMission *mission, bool toBack = false);
// Add parameterless mission by type, if possible to front, otherwise to the back
// Returns true if succeeded in adding
bool addMission(GameState &state, BattleUnitMission::Type type);
// Attempt to cancel all unit missions, returns true if successful
bool cancelMissions(GameState &state, bool forced = false);
// Attempt to give unit a new mission, replacing all others, returns true if successful
bool setMission(GameState &state, BattleUnitMission *mission);
// TB / TU functions
// Refresh unit's reserve cost
void refreshReserveCost(GameState &state);
// Returns wether unit can afford action
bool canAfford(GameState &state, int cost, bool ignoreKneelReserve = false,
bool ignoreShootReserve = false) const;
// Returns if unit did spend (false if unsufficient TUs)
bool spendTU(GameState &state, int cost, bool ignoreKneelReserve = false,
bool ignoreShootReserve = false, bool allowInterrupt = false);
// Spend all remaining TUs for the unit
void spendRemainingTU(GameState &state, bool allowInterrupt = false);
// Do routine that must be done at unit's turn start
// Called after updateTB was called
void beginTurn(GameState &state);
// TU costs
// Get cost to pick up item from ground
int getPickupCost() const;
// Get cost to throw item
int getThrowCost() const;
// Get cost to use medikit
int getMedikitCost() const;
// Get cost to use motion scanner
int getMotionScannerCost() const;
// Get cost to use teleporter
int getTeleporterCost() const;
// Get cost to turn 1 frame
int getTurnCost() const;
// Get cost to change body state
int getBodyStateChangeCost(BodyState from, BodyState to) const;
// AI execution
// Execute group decision made by AI
static void executeGroupAIDecision(GameState &state, AIDecision &decision,
std::list<StateRef<BattleUnit>> &units);
// Execute decision
void executeAIDecision(GameState &state, AIDecision &decision);
// Execute action
void executeAIAction(GameState &state, AIAction &action);
// Execute movement
void executeAIMovement(GameState &state, AIMovement &movement);
// Notifications
// Called to notify unit he's under fire
void notifyUnderFire(GameState &state, Vec3<int> position, bool visible);
// Called to notify unit he's hit
void notifyHit(Vec3<int> position);
// Experience
// Returns a roll for primary state increase based on how much experience was acquired
int rollForPrimaryStat(GameState &state, int experience);
// Process unit experience into stat increases
void processExperience(GameState &state);
// Unit state queries
// Returns true if the unit is dead
bool isDead() const;
// Returns true if the unit is unconscious and not dead
bool isUnconscious() const;
// Return true if the unit is conscious
// and not currently in the dropped state (curent and target)
bool isConscious() const;
// So we can stop going ->isLarge() all the time
bool isLarge() const { return agent->type->bodyType->large; }
// Wether unit is static - not moving, not falling, not changing body state
bool isStatic() const;
// Wether unit is busy - with aiming or firing or otherwise involved
bool isBusy() const;
// Wether unit is firing its weapon (or aiming in preparation of firing)
bool isAttacking() const;
// Wether unit is throwing an item
bool isThrowing() const;
// Wether unit is moving (has Goto Location queued)
bool isMoving() const;
// Wether unit is doing a specific mission (has it queued)
bool isDoing(BattleUnitMission::Type missionType) const;
// Return unit's general type
BattleUnitType getType() const;
// Wether unit is AI controlled
bool isAIControlled(GameState &state) const;
// Cloaked status
bool isCloaked() const;
// Unit's current AI type (can be modified by panic etc.)
AIType getAIType() const;
// Returns true if the unit is conscious and can fly
bool canFly() const;
// Returns true if the unit is conscious and can fly
bool canMove() const;
// Wether unit can go prone in position and facing
bool canProne(Vec3<int> pos, Vec2<int> fac) const;
// Wether unit can kneel in current position and facing
bool canKneel() const;
// Get unit's height in current situation
int getCurrentHeight() const { return agent->type->bodyType->height.at(current_body_state); }
// Get unit's gun muzzle location (where shots come from)
Vec3<float> getMuzzleLocation() const;
// Get unit's eyes (where vision rays come from)
// FIXME: This likely won't work properly for large units
// Idea here is to LOS from the center of the occupied tile
Vec3<float> getEyeLocation() const;
// Get thrown item's departure location
Vec3<float> getThrownItemLocation() const;
// Determine body part hit
BodyPart determineBodyPartHit(StateRef<DamageType> damageType, Vec3<float> cposition,
Vec3<float> direction);
// Returns true if sound and doodad were handled by it
bool applyDamage(GameState &state, int power, StateRef<DamageType> damageType,
BodyPart bodyPart, DamageSource source,
StateRef<BattleUnit> attacker = nullptr);
// Apply damage directly (after all calculations)
void applyDamageDirect(GameState &state, int damage, bool generateFatalWounds,
BodyPart fatalWoundPart, int stunPower,
StateRef<BattleUnit> attacker = nullptr, bool violent = true);
// Returns true if sound and doodad were handled by it
bool handleCollision(GameState &state, Collision &c);
// Get unit's position
const Vec3<float> &getPosition() const { return this->position; }
// Misc
// Request this unit give way to other unit
void requestGiveWay(const BattleUnit &requestor, const std::list<Vec3<int>> &plannedPath,
Vec3<int> pos);
// Appply enzyme to this unit
void applyEnzymeEffect(GameState &state);
// Spawn enzyme smoke on this unit
void spawnEnzymeSmoke(GameState &state);
// Send AgentEvent of specified type
// checkOwnership means event not set unless agent owned by player
// checkVisibility means event not sent unless agent seen by player
void sendAgentEvent(GameState &state, GameEventType type, bool checkOwnership = false,
bool checkVisibility = false) const;
// Trigger proximity mines around unit
void triggerProximity(GameState &state);
// Trigger brainsucker pods around unit
void triggerBrainsuckers(GameState &state);
// Retreat unit
void retreat(GameState &state);
// Drop unit to the ground
void dropDown(GameState &state);
// Try to make unit rise (may fail if other unit stands on top)
void tryToRiseUp(GameState &state);
// Process unit becoming unconscious
void fallUnconscious(GameState &state, StateRef<BattleUnit> attacker = nullptr);
// Process unit dying
void die(GameState &state, StateRef<BattleUnit> attacker = nullptr, bool violently = true);
// Update
// Main update function
void update(GameState &state, unsigned int ticks);
// Update function for TB (called when unit's turn begins
void updateTB(GameState &state);
// Updates unit's cloak status
void updateCloak(GameState &state, unsigned int ticks);
// Updates unit bleeding, debuffs and morale states
void updateStateAndStats(GameState &state, unsigned int ticks);
// Updates unit's morale
void updateMorale(GameState &state, unsigned int ticks);
// Updates unit's wounds and healing
void updateWoundsAndHealing(GameState &state, unsigned int ticks);
// Updates unit's regeneration
void updateRegen(GameState &state, unsigned int ticks);
// Updates unit give way request and events
void updateEvents(GameState &state);
// Updates unit's give way (give way if requested)
void updateGiveWay(GameState &state);
// Updates unit that is idle
void updateIdling(GameState &state);
// Update crying
void updateCrying(GameState &state);
// Checks if unit should begin falling
void updateCheckBeginFalling(GameState &state);
// Updates unit's body trainsition and acquires new target body state
void updateBody(GameState &state, unsigned int &bodyTicksRemaining);
// Updates unit's hands trainsition
void updateHands(GameState &state, unsigned int &handsTicksRemaining);
// Updates unit's movement if unit is falling
void updateMovementFalling(GameState &state, unsigned int &moveTicksRemaining,
bool &wasUsingLift);
// Update unit falling into another unit
void updateFallingIntoUnit(GameState &state, BattleUnit &unit);
// Updates unit's movement if unit is sucking brain
void updateMovementBrainsucker(GameState &state, unsigned int &moveTicksRemaining,
bool &wasUsingLift);
// Updates unit's movement if unit is jumping (over one tile gap)
void updateMovementJumping(GameState &state, unsigned int &moveTicksRemaining,
bool &wasUsingLift);
// Updates unit's movement if unit is moving normally
void updateMovementNormal(GameState &state, unsigned int &moveTicksRemaining,
bool &wasUsingLift);
// Updates unit's movement
// Return true if retreated or destroyed and we must halt immediately
void updateMovement(GameState &state, unsigned int &moveTicksRemaining, bool &wasUsingLift);
// Updates unit's trainsition and acquires new target
void updateTurning(GameState &state, unsigned int &turnTicksRemaining,
unsigned int const handsTicksRemaining);
// Updates unit's displayed item (which one will draw in unit's hands on screen)
void updateDisplayedItem(GameState &state);
// Runs all fire checks and returns false if we must stop attacking
bool updateAttackingRunCanFireChecks(GameState &state, unsigned int ticks,
sp<AEquipment> &weaponRight, sp<AEquipment> &weaponLeft,
Vec3<float> &targetPosition);
// Updates unit's attacking parameters (gun cooldown, hand states, aiming etc)
void updateAttacking(GameState &state, unsigned int ticks);
// Updates unit firing weapons
void updateFiring(GameState &state, sp<AEquipment> &weaponLeft, sp<AEquipment> &weaponRight,
Vec3<float> &targetPosition);
// Updates unit's psi attack (sustain payment, effect application etc.)
void updatePsi(GameState &state, unsigned int ticks);
// Updates unit's AI list
void updateAI(GameState &state, unsigned int ticks);
// Following members are not serialized, but rather are set in initBattle method
sp<std::vector<sp<Image>>> strategyImages;
StateRef<DoodadType> burningDoodad;
sp<std::list<sp<Sample>>> genericHitSounds;
sp<std::list<sp<Sample>>> psiSuccessSounds;
sp<std::list<sp<Sample>>> psiFailSounds;
sp<TileObjectBattleUnit> tileObject;
sp<TileObjectShadow> shadowObject;
/*
- curr. mind state (controlled/berserk/)
- ref. to psi attacker (who is controlling it/...)
*/
private:
friend class Battle;
// Start attacking (inner function which initialises everything regardles of target)
bool startAttacking(GameState &state, WeaponStatus status);
// Start psi (internal function which actually does the attack)
bool startAttackPsiInternal(GameState &state, StateRef<BattleUnit> target, PsiStatus status,
StateRef<AEquipmentType> item);
// Calculate unit's vision to terrain
void calculateVisionToTerrain(GameState &state);
// Calculate unit's vision to LBs checking every one independently
// Figure out a center tile of a block and check if it's visible (no collision)
void calculateVisionToLosBlocks(GameState &state, std::set<int> &discoveredBlocks,
std::set<int> &blocksToCheck);
// Calculate unit's vision to LBs using "shotgun" approach:
// Shoot 25 beams and include everything that was passed through into list of visible blocks
void calculateVisionToLosBlocksLazy(GameState &state, std::set<int> &discoveredBlocks);
// Calculate vision to every other unit
void calculateVisionToUnits(GameState &state);
// Return if unit sees unit
bool calculateVisionToUnit(GameState &state, BattleUnit &u);
// Return if target is within vision cone
bool isWithinVision(Vec3<int> pos);
// Update unit's vision of other units and terrain
void refreshUnitVisibility(GameState &state);
// Update other units's vision of this unit
void refreshUnitVision(GameState &state, bool forceBlind = false,
StateRef<BattleUnit> targetUnit = StateRef<BattleUnit>());
// Update both this unit's vision and other unit's vision of this unit
void refreshUnitVisibilityAndVision(GameState &state);
};
}
| 37.784431 | 99 | 0.751125 |
03bd5331671d4aff50432cfc91ce74f9070a4a39 | 843 | c | C | src/Weapons.c | chtprojects/sdlgame1 | 77c9ae3be60e4e6d86a8053a5d2e7bc055300b3c | [
"BSD-2-Clause"
] | null | null | null | src/Weapons.c | chtprojects/sdlgame1 | 77c9ae3be60e4e6d86a8053a5d2e7bc055300b3c | [
"BSD-2-Clause"
] | null | null | null | src/Weapons.c | chtprojects/sdlgame1 | 77c9ae3be60e4e6d86a8053a5d2e7bc055300b3c | [
"BSD-2-Clause"
] | null | null | null | #include "Weapons.h"
void Weapon_get(Weapon *weapon, WeaponType type) {
switch (type) {
case BASIC:
weapon->bulletSpeed = 1;
weapon->bulletSize = 2;
weapon->delay = 300;
weapon->lastShoot = 0;
weapon->damage = 1;
weapon->type = BASIC;
break;
case HEAVY:
weapon->bulletSpeed = 4;
weapon->bulletSize = 5;
weapon->delay = 100;
weapon->lastShoot = 0;
weapon->damage = 2;
weapon->type = HEAVY;
break;
case SHOOTGUN:
weapon->bulletSpeed = 3;
weapon->bulletSize = 5;
weapon->delay = 500;
weapon->lastShoot = 0;
weapon->damage = 2;
weapon->type = SHOOTGUN;
break;
case ROCKET:
weapon->bulletSpeed = 4;
weapon->bulletSize = 20;
weapon->delay = 2000;
weapon->lastShoot = 0;
weapon->damage = 5;
weapon->type = ROCKET;
break;
}
}
| 21.615385 | 50 | 0.596679 |
03bdd92fb41c24b4756c582413ac7bc66e015061 | 4,923 | h | C | RenderMan-master/JuceLibraryCode/modules/juce_video/native/juce_mac_Video.h | ethman/slakh-generation | e6454eb57a3683b99cdd16695fe652f83b75bb14 | [
"MIT"
] | 33 | 2020-02-04T20:05:14.000Z | 2022-03-26T16:32:11.000Z | RenderMan-master/JuceLibraryCode/modules/juce_video/native/juce_mac_Video.h | ethman/slakh_generation_scripts | e6454eb57a3683b99cdd16695fe652f83b75bb14 | [
"MIT"
] | 5 | 2020-02-03T18:30:05.000Z | 2022-03-30T01:22:21.000Z | RenderMan-master/JuceLibraryCode/modules/juce_video/native/juce_mac_Video.h | ethman/slakh_generation_scripts | e6454eb57a3683b99cdd16695fe652f83b75bb14 | [
"MIT"
] | 2 | 2020-12-13T18:15:06.000Z | 2021-03-31T17:39:34.000Z | /*
==============================================================================
This file is part of the JUCE library.
Copyright (c) 2015 - ROLI Ltd.
Permission is granted to use this software under the terms of either:
a) the GPL v2 (or any later version)
b) the Affero GPL v3
Details of these licenses can be found at: www.gnu.org/licenses
JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE. See the GNU General Public License for more details.
------------------------------------------------------------------------------
To release a closed-source product which uses JUCE, commercial licenses are
available: visit www.juce.com for more information.
==============================================================================
*/
#if JUCE_IOS
using BaseClass = UIViewComponent;
#else
using BaseClass = NSViewComponent;
#endif
struct VideoComponent::Pimpl : public BaseClass
{
Pimpl()
{
setVisible (true);
#if JUCE_MAC && JUCE_32BIT
auto view = [[NSView alloc] init]; // 32-bit builds don't have AVPlayerView, so need to use a layer
controller = [[AVPlayerLayer alloc] init];
setView (view);
[view setNextResponder: [view superview]];
[view setWantsLayer: YES];
[view setLayer: controller];
[view release];
#elif JUCE_MAC
controller = [[AVPlayerView alloc] init];
setView (controller);
[controller setNextResponder: [controller superview]];
[controller setWantsLayer: YES];
#else
controller = [[AVPlayerViewController alloc] init];
setView ([controller view]);
#endif
}
~Pimpl()
{
close();
setView (nil);
[controller release];
}
Result load (const File& file)
{
auto r = load (createNSURLFromFile (file));
if (r.wasOk())
currentFile = file;
return r;
}
Result load (const URL& url)
{
auto r = load ([NSURL URLWithString: juceStringToNS (url.toString (true))]);
if (r.wasOk())
currentURL = url;
return r;
}
Result load (NSURL* url)
{
if (url != nil)
{
close();
if (auto* player = [AVPlayer playerWithURL: url])
{
[controller setPlayer: player];
return Result::ok();
}
}
return Result::fail ("Couldn't open movie");
}
void close()
{
stop();
[controller setPlayer: nil];
currentFile = File();
currentURL = {};
}
bool isOpen() const noexcept { return getAVPlayer() != nil; }
bool isPlaying() const noexcept { return getSpeed() != 0; }
void play() noexcept { [getAVPlayer() play]; }
void stop() noexcept { [getAVPlayer() pause]; }
void setPosition (double newPosition)
{
if (auto* p = getAVPlayer())
{
CMTime t = { (CMTimeValue) (100000.0 * newPosition),
(CMTimeScale) 100000, kCMTimeFlags_Valid };
[p seekToTime: t
toleranceBefore: kCMTimeZero
toleranceAfter: kCMTimeZero];
}
}
double getPosition() const
{
if (auto* p = getAVPlayer())
return toSeconds ([p currentTime]);
return 0.0;
}
void setSpeed (double newSpeed)
{
[getAVPlayer() setRate: (float) newSpeed];
}
double getSpeed() const
{
if (auto* p = getAVPlayer())
return [p rate];
return 0.0;
}
Rectangle<int> getNativeSize() const
{
if (auto* player = getAVPlayer())
{
auto s = [[player currentItem] presentationSize];
return { (int) s.width, (int) s.height };
}
return {};
}
double getDuration() const
{
if (auto* player = getAVPlayer())
return toSeconds ([[player currentItem] duration]);
return 0.0;
}
void setVolume (float newVolume)
{
[getAVPlayer() setVolume: newVolume];
}
float getVolume() const
{
if (auto* p = getAVPlayer())
return [p volume];
return 0.0f;
}
File currentFile;
URL currentURL;
private:
#if JUCE_IOS
AVPlayerViewController* controller = nil;
#elif JUCE_32BIT
AVPlayerLayer* controller = nil;
#else
AVPlayerView* controller = nil;
#endif
AVPlayer* getAVPlayer() const noexcept { return [controller player]; }
static double toSeconds (const CMTime& t) noexcept
{
return t.timescale != 0 ? (t.value / (double) t.timescale) : 0.0;
}
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Pimpl)
};
| 24.615 | 108 | 0.540321 |
03bf6594875ce4ceec4346a76664aa646d7fde5f | 254 | h | C | iOS/DoraemonKit/Src/Core/Plugin/Common/ume/UmeDoraemonMMKVViewController.h | bravegogo/DoraemonKit | b3a155386d06cc132288b28efc044c6849919f7b | [
"Apache-2.0"
] | null | null | null | iOS/DoraemonKit/Src/Core/Plugin/Common/ume/UmeDoraemonMMKVViewController.h | bravegogo/DoraemonKit | b3a155386d06cc132288b28efc044c6849919f7b | [
"Apache-2.0"
] | 1 | 2020-07-29T08:52:54.000Z | 2020-07-29T08:52:54.000Z | iOS/DoraemonKit/Src/Core/Plugin/Common/ume/UmeDoraemonMMKVViewController.h | bravegogo/DoraemonKit | b3a155386d06cc132288b28efc044c6849919f7b | [
"Apache-2.0"
] | 3 | 2020-07-28T12:31:50.000Z | 2020-07-30T08:31:41.000Z | //
// UmeDoraemonMMKVViewController.h
// Pods
//
// Created by hyhan on 2020/7/27.
//
#import "DoraemonBaseViewController.h"
NS_ASSUME_NONNULL_BEGIN
@interface UmeDoraemonMMKVViewController : DoraemonBaseViewController
@end
NS_ASSUME_NONNULL_END
| 14.941176 | 69 | 0.791339 |
03c2d79e59c3b6d7b29383bcd72869356e0362f1 | 1,067 | h | C | admin/wmi/wbem/providers/win32provider/providers/w2kenum.h | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | admin/wmi/wbem/providers/win32provider/providers/w2kenum.h | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | admin/wmi/wbem/providers/win32provider/providers/w2kenum.h | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | //=================================================================
//
// W2kEnum.h -- W2k enumeration support
//
//
// Copyright (c) 1996-2001 Microsoft Corporation, All Rights Reserved
//
// Revisions: 07/28/99 Created
//
//=================================================================
#ifndef _W2KENUM_H_
#define _W2KENUM_H_
class CW2kAdapterInstance
{
public:
DWORD dwIndex ;
CHString chsPrimaryKey ;
CHString chsCaption ;
CHString chsDescription ;
CHString chsCompleteKey ;
CHString chsService ;
CHString chsNetCfgInstanceID ;
CHString chsRootdevice ;
CHString chsIpInterfaceKey ;
};
class CW2kAdapterEnum : public CHPtrArray
{
private:
BOOL GetW2kInstances() ;
BOOL IsIpPresent( CRegistry &a_RegIpInterface ) ;
public:
//=================================================
// Constructors/destructor
//=================================================
CW2kAdapterEnum() ;
~CW2kAdapterEnum() ;
};
#endif | 21.77551 | 71 | 0.488285 |
03c3f3266e3737ede9e770d65a083ffa95a60a11 | 1,431 | c | C | src/ft_init_image.c | BimManager/fdf | 05a5b3432f7f2d717f840f31dd8a9488dc9959d1 | [
"MIT"
] | null | null | null | src/ft_init_image.c | BimManager/fdf | 05a5b3432f7f2d717f840f31dd8a9488dc9959d1 | [
"MIT"
] | null | null | null | src/ft_init_image.c | BimManager/fdf | 05a5b3432f7f2d717f840f31dd8a9488dc9959d1 | [
"MIT"
] | null | null | null | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_init_image.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: kkozlov <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/12/25 11:34:42 by kkozlov #+# #+# */
/* Updated: 2020/01/11 13:51:10 by kkozlov ### ########.fr */
/* */
/* ************************************************************************** */
#include "fdf.h"
t_imgdata *ft_init_image(t_windata *windata, int width, int height)
{
t_imgdata *imgdt;
imgdt = malloc(sizeof(t_imgdata));
ft_bzero(imgdt, sizeof(t_imgdata));
imgdt->img_ptr = mlx_new_image(windata->mlx_ptr, width, height);
imgdt->buffer = mlx_get_data_addr(imgdt->img_ptr,
&imgdt->bits_per_pixel, &imgdt->size_line, &imgdt->endian);
imgdt->mapped = ft_queuenew(NULL, 0);
imgdt->origin = ft_rvecnew(0, 0, 0, 1);
imgdt->x_dir = ft_rvecnew(1, 0, 0, 0);
imgdt->y_dir = ft_rvecnew(1, 1, 0, 0);
return (imgdt);
}
| 47.7 | 80 | 0.331237 |
03c4682c1ef3481d8545b288af477447a2f1d205 | 8,692 | c | C | thtk/thdat.c | I-Tom-I/thtk | 374aee6e37d6c925f002a2ae7f415f344a5a755b | [
"Libpng",
"BSD-2-Clause"
] | null | null | null | thtk/thdat.c | I-Tom-I/thtk | 374aee6e37d6c925f002a2ae7f415f344a5a755b | [
"Libpng",
"BSD-2-Clause"
] | null | null | null | thtk/thdat.c | I-Tom-I/thtk | 374aee6e37d6c925f002a2ae7f415f344a5a755b | [
"Libpng",
"BSD-2-Clause"
] | null | null | null | /*
* 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 this list
* of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce this
* list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*/
#include <config.h>
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
#include <thtk/thtk.h>
#include "thdat.h"
#include "thrle.h"
#include "program.h"
extern const thdat_module_t archive_th02;
extern const thdat_module_t archive_th06;
extern const thdat_module_t archive_th08;
extern const thdat_module_t archive_th95;
extern const thdat_module_t archive_th105;
static const thdat_module_t*
thdat_version_to_module(
unsigned int version,
thtk_error_t** error)
{
switch (version) {
case 1:
case 2:
case 3:
case 4:
case 5:
return &archive_th02;
case 6:
case 7:
return &archive_th06;
case 8:
case 9:
return &archive_th08;
case 95:
case 10:
case 103:
case 11:
case 12:
case 125:
case 128:
case 13:
case 14:
case 143:
case 15:
case 16:
case 165:
case 17:
/* NEWHU: */
return &archive_th95;
case 105:
case 123:
return &archive_th105;
}
thtk_error_new(error, "no module found for version %u", version);
return NULL;
}
void
thdat_entry_init(
thdat_entry_t* entry)
{
if (entry) {
memset(entry->name, 0, sizeof(entry->name));
entry->extra = 0;
entry->offset = entry->zsize = entry->size = -1;
}
}
static thdat_t*
thdat_new(
unsigned int version,
thtk_io_t* stream,
thtk_error_t** error)
{
thdat_t* thdat;
if (!stream) {
thtk_error_new(error, "invalid parameter passed");
return 0;
}
thdat = malloc(sizeof(*thdat));
thdat->version = version;
if (!(thdat->module = thdat_version_to_module(version, error))) {
free(thdat);
return NULL;
}
thdat->stream = stream;
thdat->entry_count = 0;
thdat->entries = NULL;
thdat->offset = 0;
return thdat;
}
thdat_t*
thdat_open(
unsigned int version,
thtk_io_t* input,
thtk_error_t** error)
{
thdat_t* thdat;
if (!input) {
thtk_error_new(error, "invalid parameter passed");
return 0;
}
if (thtk_io_seek(input, 0, SEEK_SET, error) == -1)
return NULL;
if (!(thdat = thdat_new(version, input, error)))
return NULL;
if (!thdat->module->open(thdat, error)) {
thdat_free(thdat);
return NULL;
}
return thdat;
}
int
thdat_init(
thdat_t* thdat,
thtk_error_t** error)
{
if (!thdat->module->create(thdat, error)) {
thdat_free(thdat);
return 0;
}
return 1;
}
thdat_t*
thdat_create(
unsigned int version,
thtk_io_t* output,
size_t entry_count,
thtk_error_t** error)
{
thdat_t* thdat;
if (!output) {
thtk_error_new(error, "invalid parameter passed");
return 0;
}
if (thtk_io_seek(output, 0, SEEK_SET, error) == -1)
return NULL;
if (!(thdat = thdat_new(version, output, error)))
return NULL;
thdat->entry_count = entry_count;
thdat->entries = calloc(entry_count, sizeof(thdat_entry_t));
if (version != 105 && version != 123) {
if (!thdat_init(thdat, error))
return NULL;
}
return thdat;
}
static int
thdat_entry_compar(
const void* a,
const void* b)
{
const thdat_entry_t* ea = a;
const thdat_entry_t* eb = b;
return (int)ea->offset - eb->offset;
}
int
thdat_close(
thdat_t* thdat,
thtk_error_t** error)
{
if (!thdat) {
thtk_error_new(error, "invalid parameter passed");
return 0;
}
qsort(thdat->entries, thdat->entry_count, sizeof(thdat_entry_t), thdat_entry_compar);
return thdat->module->close(thdat, error);
}
void
thdat_free(
thdat_t* thdat)
{
if (thdat) {
free(thdat->entries);
free(thdat);
}
}
ssize_t
thdat_entry_count(
thdat_t* thdat,
thtk_error_t** error)
{
if (!thdat) {
thtk_error_new(error, "invalid parameter passed");
return -1;
}
return thdat->entry_count;
}
ssize_t
thdat_entry_by_name(
thdat_t* thdat,
const char* name,
thtk_error_t** error)
{
if (!thdat || !name) {
thtk_error_new(error, "invalid parameter passed");
return -1;
}
for (size_t e = 0; e < thdat->entry_count; ++e) {
if (strcmp(name, thdat->entries[e].name) == 0)
return e;
}
return -1;
}
int
thdat_entry_set_name(
thdat_t* thdat,
int entry_index,
const char* name,
thtk_error_t** error)
{
if (thdat && name && entry_index >= 0 && entry_index < (int)thdat->entry_count) {
char temp_name[256];
strncpy(temp_name, name, 255);
if (thdat->module->flags & THDAT_BASENAME) {
/* Borrow this function from detect */
extern const char *detect_basename(const char *path);
char temp_name2[256];
strncpy(temp_name2, temp_name, 255);
strncpy(temp_name, detect_basename(temp_name2), 255);
}
if (thdat->module->flags & THDAT_UPPERCASE) {
for (unsigned int i = 0; i < 255 && temp_name[i]; ++i) {
temp_name[i] = toupper(temp_name[i]);
}
}
if (thdat->module->flags & THDAT_8_3) {
const char* dotpos = strchr(temp_name, '.');
size_t name_len = dotpos ? strlen(temp_name) - strlen(dotpos) : strlen(temp_name);
size_t ext_len = dotpos ? strlen(dotpos + 1) : 0;
if (name_len > 8 || ext_len > 3) {
thtk_error_new(error, "name is not 8.3");
return 0;
}
}
strcpy(thdat->entries[entry_index].name, temp_name);
return 1;
}
thtk_error_new(error, "invalid parameter passed");
return 0;
}
const char*
thdat_entry_get_name(
thdat_t* thdat,
int entry_index,
thtk_error_t** error)
{
if (!thdat || entry_index < 0 || entry_index >= (int)thdat->entry_count) {
thtk_error_new(error, "invalid parameter passed");
return NULL;
}
return thdat->entries[entry_index].name;
}
ssize_t
thdat_entry_get_size(
thdat_t* thdat,
int entry_index,
thtk_error_t** error)
{
if (!thdat || entry_index < 0 || entry_index >= (int)thdat->entry_count) {
thtk_error_new(error, "invalid parameter passed");
return -1;
}
return thdat->entries[entry_index].size;
}
ssize_t
thdat_entry_get_zsize(
thdat_t* thdat,
int entry_index,
thtk_error_t** error)
{
if (!thdat || entry_index < 0 || entry_index >= (int)thdat->entry_count) {
thtk_error_new(error, "invalid parameter passed");
return -1;
}
return thdat->entries[entry_index].zsize;
}
ssize_t
thdat_entry_write_data(
thdat_t* thdat,
int entry_index,
thtk_io_t* input,
size_t input_length,
thtk_error_t** error)
{
if (!thdat || entry_index < 0 || entry_index >= (int)thdat->entry_count || !input) {
thtk_error_new(error, "invalid parameter passed");
return -1;
}
return thdat->module->write(thdat, entry_index, input, input_length, error);
}
ssize_t
thdat_entry_read_data(
thdat_t* thdat,
int entry_index,
thtk_io_t* output,
thtk_error_t** error)
{
if (!thdat || entry_index < 0 || entry_index >= (int)thdat->entry_count || !output) {
thtk_error_new(error, "invalid parameter passed");
return -1;
}
return thdat->module->read(thdat, entry_index, output, error);
}
| 24.41573 | 94 | 0.625863 |
03c4afd8ad6b6b928f7cf4832e38b506284838dc | 7,392 | c | C | stencil/C/IMCI/total_energy.c | shunsuke-sato/ARTED | 608e503c75076ac912a8a997910faf72e81f63f0 | [
"Apache-2.0"
] | 4 | 2016-11-20T12:56:04.000Z | 2018-03-02T02:00:18.000Z | stencil/C/IMCI/total_energy.c | shunsuke-sato/ARTED | 608e503c75076ac912a8a997910faf72e81f63f0 | [
"Apache-2.0"
] | 20 | 2016-07-10T05:34:15.000Z | 2017-04-09T02:51:54.000Z | stencil/C/IMCI/total_energy.c | shunsuke-sato/ARTED | 608e503c75076ac912a8a997910faf72e81f63f0 | [
"Apache-2.0"
] | 11 | 2016-06-29T20:52:16.000Z | 2018-05-25T07:03:49.000Z | /*
* Copyright 2016 ARTED developers
*
* 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.
*/
/* Hand-Code Vector processing for Knights Corner */
#include <complex.h>
#include "../interop.h"
extern int NLx, NLy, NLz;
#ifndef ARTED_DOMAIN_POWER_OF_TWO
extern int *modx, *mody, *modz;
#endif
#ifdef ARTED_STENCIL_LOOP_BLOCKING
extern int BX, BY;
#endif
void total_energy_stencil_( double const* restrict A_
, double const C[restrict 12]
, double const D[restrict 12]
, double complex const E[restrict NLx][NLy][NLz]
, double complex * restrict F
) {
const double A = *A_;
double complex const* e;
int ix, iy, iz, n;
#ifdef ARTED_STENCIL_LOOP_BLOCKING
int bx, by;
#endif
__m512d at = _mm512_set1_pd(A);
__m512i INV = _mm512_set4_epi64(1LL << 63, 0, 1LL << 63, 0);
__declspec(align(64)) double G[12];
for(n = 0 ; n < 12 ; ++n)
G[n] = C[n] * -0.5;
__m512i nly = _mm512_set1_epi32(NLy);
__m512i nlz = _mm512_set1_epi32(NLz);
__m512i nyx = _mm512_mask_blend_epi32(0xFF00, _mm512_set1_epi32(NLy ), _mm512_set1_epi32(NLx ));
#ifdef ARTED_DOMAIN_POWER_OF_TWO
__m512i myx = _mm512_mask_blend_epi32(0xFF00, _mm512_set1_epi32(NLy - 1), _mm512_set1_epi32(NLx - 1));
#endif
__declspec(align(64)) int yx_table[16];
__m512i yx_org = _mm512_setr_epi32(-4, -3, -2, -1, 1, 2, 3, 4, -4, -3, -2, -1, 1, 2, 3, 4);
__m512i *yx = (__m512i*) yx_table;
__m512i dnyx = _mm512_add_epi32(nyx, yx_org);
__m512i nlyz = _mm512_mask_mullo_epi32(nlz, 0xFF00, nlz, nly);
__m512d zr = _mm512_setzero_pd();
__m512d zi = _mm512_setzero_pd();
#pragma noprefetch
#pragma novector
#ifdef ARTED_STENCIL_LOOP_BLOCKING
for(bx = 0 ; bx < NLx ; bx += BX)
for(by = 0 ; by < NLy ; by += BY)
for(ix = bx ; ix < MIN(bx+BX,NLx) ; ++ix)
#else
for(ix = 0 ; ix < NLx ; ++ix)
#endif
{
__m512i tix = _mm512_set1_epi32(ix);
#ifndef ARTED_DOMAIN_POWER_OF_TWO
__m512i mxm = _mm512_loadu_prefetch_epi32(modx + (ix - 4 + NLx));
__m512i mxp = _mm512_alignr_epi32(mxm, mxm, 1);
__m512i xmp = _mm512_mask_blend_epi32(0xF0F0, mxm, mxp);
xmp = _mm512_permute4f128_epi32(xmp, _MM_PERM_BADC);
#endif
#ifdef ARTED_STENCIL_LOOP_BLOCKING
for(iy = by ; iy < MIN(by+BY,NLy) ; ++iy)
#else
for(iy = 0 ; iy < NLy ; ++iy)
#endif
{
__m512i tiy = _mm512_set1_epi32(iy);
#ifndef ARTED_DOMAIN_POWER_OF_TWO
__m512i mym = _mm512_loadu_prefetch_epi32(mody + (iy - 4 + NLy));
__m512i myp = _mm512_alignr_epi32(mym, mym, 1);
__m512i ymp = _mm512_mask_blend_epi32(0xF0F0, mym, myp);
__m512i uyx = _mm512_mask_blend_epi32(0xFF00, ymp, xmp);
#endif
__m512i tyx = _mm512_mask_blend_epi32(0xFF00, tiy, tix);
e = &E[ix][iy][0];
for(iz = 0 ; iz < NLz ; iz += 4)
{
__m512i tiz = _mm512_set1_epi32(iz);
#ifdef ARTED_DOMAIN_POWER_OF_TWO
__m512i mm = _mm512_sub_epi32(tyx, _mm512_and_epi32(_mm512_add_epi32(dnyx, tyx), myx));
#else
__m512i mm = _mm512_sub_epi32(tyx, uyx);
#endif
*yx = _mm512_sub_epi32(tiz, _mm512_mullo_epi32(mm, nlyz));
// conj(e[iz])
__m512d ez = _mm512_load_prefetch_pd(e + iz);
__m512d w = (__m512d) _mm512_xor_si512((__m512i) ez, INV);
__m512d tt = _mm512_setzero_pd();
__m512d ut = _mm512_setzero_pd();
__m512d wm[4];
__m512d wp[4];
__m512d v1, v2, v3, v4;
/* z-dimension (unit stride) */
{
__m512i z0, z2;
#ifdef ARTED_DOMAIN_POWER_OF_TWO
z0 = _mm512_load_prefetch_epi64(e + ((iz - 4 + NLz) & (NLz - 1)));
z2 = _mm512_load_prefetch_epi64(e + ((iz + 4 + NLz) & (NLz - 1)));
#else
z0 = _mm512_load_prefetch_epi64(e + modz[iz - 4 + NLz]);
z2 = _mm512_load_prefetch_epi64(e + modz[iz + 4 + NLz]);
#endif
wm[3] = (__m512d) z0;
wm[2] = (__m512d) _mm512_alignr_epi32((__m512i) ez, z0, 4);
wm[1] = (__m512d) _mm512_alignr_epi32((__m512i) ez, z0, 8);
wm[0] = (__m512d) _mm512_alignr_epi32((__m512i) ez, z0, 12);
wp[0] = (__m512d) _mm512_alignr_epi32(z2, (__m512i) ez, 4);
wp[1] = (__m512d) _mm512_alignr_epi32(z2, (__m512i) ez, 8);
wp[2] = (__m512d) _mm512_alignr_epi32(z2, (__m512i) ez, 12);
wp[3] = (__m512d) z2;
#pragma unroll(4)
for(n = 0 ; n < 4 ; ++n) {
v4 = _mm512_sub_pd(wp[n], wm[n]);
v3 = _mm512_add_pd(wp[n], wm[n]);
ut = _mm512_fmadd_pd(_mm512_set1_pd(D[n+8]), v4, ut);
tt = _mm512_fmadd_pd(_mm512_set1_pd(G[n+8]), v3, tt);
}
}
/* y-dimension (NLz stride) */
{
wm[3] = _mm512_load_prefetch_pd(e + yx_table[0]);
wm[2] = _mm512_load_prefetch_pd(e + yx_table[1]);
wm[1] = _mm512_load_prefetch_pd(e + yx_table[2]);
wm[0] = _mm512_load_prefetch_pd(e + yx_table[3]);
wp[0] = _mm512_load_prefetch_pd(e + yx_table[4]);
wp[1] = _mm512_load_prefetch_pd(e + yx_table[5]);
wp[2] = _mm512_load_prefetch_pd(e + yx_table[6]);
wp[3] = _mm512_load_prefetch_pd(e + yx_table[7]);
#pragma unroll(4)
for(n = 0 ; n < 4 ; ++n) {
v4 = _mm512_sub_pd(wp[n], wm[n]);
v3 = _mm512_add_pd(wp[n], wm[n]);
ut = _mm512_fmadd_pd(_mm512_set1_pd(D[n+4]), v4, ut);
tt = _mm512_fmadd_pd(_mm512_set1_pd(G[n+4]), v3, tt);
}
}
/* x-dimension (NLy*NLz stride) */
{
wm[3] = _mm512_load_prefetch_pd(e + yx_table[ 8]);
wm[2] = _mm512_load_prefetch_pd(e + yx_table[ 9]);
wm[1] = _mm512_load_prefetch_pd(e + yx_table[10]);
wm[0] = _mm512_load_prefetch_pd(e + yx_table[11]);
wp[0] = _mm512_load_prefetch_pd(e + yx_table[12]);
wp[1] = _mm512_load_prefetch_pd(e + yx_table[13]);
wp[2] = _mm512_load_prefetch_pd(e + yx_table[14]);
wp[3] = _mm512_load_prefetch_pd(e + yx_table[15]);
#pragma unroll(4)
for(n = 0 ; n < 4 ; ++n) {
v4 = _mm512_sub_pd(wp[n], wm[n]);
v3 = _mm512_add_pd(wp[n], wm[n]);
ut = _mm512_fmadd_pd(_mm512_set1_pd(D[n]), v4, ut);
tt = _mm512_fmadd_pd(_mm512_set1_pd(G[n]), v3, tt);
}
}
// z = - 0.5d0*v - zI*w
v4 = (__m512d) _mm512_shuffle_epi32((__m512i) ut, _MM_PERM_BADC);
v3 = (__m512d) _mm512_xor_si512((__m512i) v4, INV);
v2 = _mm512_add_pd(tt, v3);
// z = A * e[iz] + z
tt = _mm512_fmadd_pd(at, ez, v2);
// conj(e[iz]) * z
v1 = _mm512_mul_pd(w, tt);
v2 = (__m512d) _mm512_xor_si512((__m512i) v1, INV);
v3 = (__m512d) _mm512_shuffle_epi32((__m512i) w, _MM_PERM_BADC);
zr = _mm512_add_pd(v2, zr);
zi = _mm512_fmadd_pd(v3, tt, zi);
} /* NLz */
} /* NLy */
} /* NLx */
*F = _mm512_reduce_add_pd(zr) + _mm512_reduce_add_pd(zi) * I;
}
| 34.381395 | 104 | 0.608496 |
03c4e0fe994ce772679557bc0d4f7536713139fa | 26,816 | h | C | cbmex/cbmex.h | jsdpag/CereLink | a4294914ade9e1a0415536ba1163d76b6a73fa1e | [
"BSD-2-Clause"
] | 34 | 2015-01-02T19:34:17.000Z | 2022-03-22T20:29:09.000Z | cbmex/cbmex.h | jsdpag/CereLink | a4294914ade9e1a0415536ba1163d76b6a73fa1e | [
"BSD-2-Clause"
] | 77 | 2015-02-06T10:14:35.000Z | 2021-02-23T14:53:56.000Z | cbmex/cbmex.h | jsdpag/CereLink | a4294914ade9e1a0415536ba1163d76b6a73fa1e | [
"BSD-2-Clause"
] | 24 | 2015-09-15T14:37:55.000Z | 2021-09-02T15:30:38.000Z | /* =STS=> cbmex.h[4257].aa10 open SMID:10 */
//////////////////////////////////////////////////////////////////////////////
//
// (c) Copyright 2010 - 2011 Blackrock Microsystems
//
// $Workfile: cbmex.h $
// $Archive: /Cerebus/Human/WindowsApps/cbmex/cbmex.h $
// $Revision: 1 $
// $Date: 2/17/11 3:15p $
// $Author: Ehsan $
//
// $NoKeywords: $
//
//////////////////////////////////////////////////////////////////////////////
/*! \file cbmex.h
\brief MATLAB executable (MEX) interface for cbsdk.
*/
#ifndef CBMEX_H_INCLUDED
#define CBMEX_H_INCLUDED
#if defined(WIN32)
#include "pstdint.h"
#else
#include "stdint.h"
#endif
#include "mex.h"
#include "mex_compat.h"
///////////////////////////// Prototypes for all of the Matlab events ////////
void OnHelp (int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] );
void OnOpen (int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] );
void OnClose (int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] );
void OnTime (int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] );
void OnTrialConfig (int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] );
void OnChanLabel (int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] );
void OnTrialData (int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] );
void OnTrialComment (int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] );
void OnTrialTracking (int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] );
void OnFileConfig (int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] );
void OnDigitalOut (int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] );
void OnAnalogOut (int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] );
void OnMask (int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] );
void OnComment (int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] );
void OnConfig (int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] );
void OnCCF (int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] );
void OnSystem (int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] );
void OnSynchOut (int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] );
void OnExtCmd (int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] );
////////////////////// end of Prototypes for all of the Matlab events ////////
#define CBMEX_USAGE_CBMEX \
"cbmex is the live MATLAB interface for Cerebus system\n" \
"Format: cbmex(<command>, [arg1], ...)\n" \
"Inputs:\n" \
"<command> is a string and can be any of:\n" \
"'help', 'open', 'close', 'time', 'trialconfig', 'chanlabel',\n" \
"'trialdata', 'fileconfig', 'digitalout', 'mask', 'comment', 'config',\n" \
"'analogout', 'trialcomment', 'trialtracking', 'ccf', 'system', 'synchout', 'ext'\n" \
"Use cbmex('help', <command>) for each command usage\n" \
#define CBMEX_USAGE_HELP \
"Prints usage information about cbmex functions\n" \
"Format: cbmex('help', [command])\n" \
"Inputs:\n" \
"command: is the command name\n" \
"Use cbmex('help') to get the list of commands\n" \
#define CBMEX_USAGE_OPEN \
"Opens the live MATLAB interface for Cerebus system\n" \
"Format: [connection instrument] = cbmex('open', [interface = 0], [<parameter>[, value]])\n" \
"Inputs:\n" \
" interface (optional): 0 (Default), 1 (Central), 2 (UDP)\n" \
"<parameter>[, value] pairs are optional, some parameters do not have values.\n" \
" from left to right parameters will override previous ones or combine with them if possible.\n" \
"<parameter>[, value] can be any of:\n" \
"'instance', value: value is the library instance to open (default is 0)\n" \
"'inst-addr', value: value is string containing instrument ipv4 address\n" \
"'inst-port', value: value is the instrument port number\n" \
"'central-addr', value: value is string containing central ipv4 address\n" \
"'central-port', value: value is the central port number\n" \
"'receive-buffer-size', value: override default network buffer size (low value may result in drops)\n" \
"\n" \
"Outputs:\n" \
" connection (optional): 1 (Central), 2 (UDP)\n" \
" instrument (optional): 0 (NSP), 1 (Local nPlay), 2 (Local NSP), 3 (Remote nPlay)\n" \
#define CBMEX_USAGE_CLOSE \
"Closes the live MATLAB interface for Cerebus system\n" \
"Format: cbmex('close', [<parameter>[, value]])\n" \
"Inputs:\n" \
"<parameter>[, value] pairs are optional, some parameters do not have values.\n" \
" from left to right parameters will override previous ones or combine with them if possible.\n" \
"<parameter>[, value] can be any of:\n" \
"'instance', value: value is the library instance to close (default is 0)\n" \
#define CBMEX_USAGE_TIME \
"Get the latest Cerebus time past last reset\n" \
"Format: cbmex('time', [<parameter>[, value]])\n" \
"Inputs:\n" \
"<parameter>[, value] pairs are optional, some parameters do not have values.\n" \
" from left to right parameters will override previous ones or combine with them if possible.\n" \
"<parameter>[, value] can be any of:\n" \
"'instance', value: value is the library instance to use (default is 0)\n" \
"'samples': if specified sample number is returned otherwise seconds\n" \
#define CBMEX_USAGE_CHANLABEL \
"Get current channel labbels and optionally set new labels\n" \
"Format: [label_cell_array] = cbmex('chanlabel', [channels_vector], [new_label_cell_array], [<parameter>[, value]])\n" \
"Inputs:\n" \
"channels_vector (optional): a vector of all the channel numbers to change their label\n" \
" if not specified all the 156 channels are considered\n" \
"new_label_cell_array (optional): cell array of new labels (each cell a string of maximum 16 characters)\n" \
" number of labels must match number of channels\n" \
"<parameter>[, value] pairs are optional, some parameters do not have values.\n" \
" from left to right parameters will override previous ones or combine with them if possible.\n" \
"<parameter>[, value] can be any of:\n" \
"'instance', value: value is the library instance to use (default is 0)\n" \
"\n" \
"Outputs:\n" \
" label_cell_array (optional): If specified previous labels are returned\n" \
"Each row in label_cell_array looks like:\n" \
" For spike channels:\n" \
" 'channel label' [spike_enabled] [unit0_valid] [unit1_valid] [unit2_valid] [unit3_valid] [unit4_valid]\n" \
" For digital input channels:\n" \
" 'channel label' [digin_enabled] ...remaining columns are empty...\n" \
#define CBMEX_USAGE_TRIALCONFIG \
"Configures a trial to grab data with 'trialdata'\n" \
"Format: [ active_state, [config_vector_out] ]\n" \
" = cbmex('trialconfig', active, [config_vector_in], [<parameter>[, value]])\n" \
"Inputs:\n" \
"active: set 1 to flush data cache and start collecting data immediately,\n" \
" set 0 to stop collecting data immediately\n" \
"config_vector_in (optional):\n" \
" vector [begchan begmask begval endchan endmask endval] specifying start and stop channels, default is zero all\n" \
"<parameter>[, value] pairs are optional, some parameters do not have values.\n" \
" from left to right parameters will override previous ones or combine with them if possible.\n" \
"<parameter>[, value] can be any of:\n" \
"'double': if specified, the data is in double precision format (old behaviour)\n" \
"'absolute': if specified event timing is absolute (active will not reset time for events)\n" \
"'nocontinuous': if specified, continuous data cache is not created nor configured (same as 'continuous',0)\n" \
"'noevent': if specified, event data cache is not created nor configured (same as 'event',0)\n" \
"'waveform', value: set the number of waveforms to be cached (internal cache if less than 400)\n" \
"'continuous', value: set the number of continuous data to be cached\n" \
"'event', value: set the number of evnets to be cached\n" \
"'comment', value: set number of comments to be cached\n" \
"'tracking', value: set the number of video tracking evnets to be cached" \
"'instance', value: value is the library instance to use (default is 0)\n" \
"\n" \
"Outputs:\n" \
"active_state: return 1 if data collection is active, 0 otherwise\n" \
"config_vector_out:\n" \
" vector [begchan begmask begval endchan endmask endval double waveform continuous event comment tracking]\n" \
" specifying the configuration state\n" \
#define CBMEX_USAGE_TRIALDATA \
"Grab continuous and even data configured by 'trialconfig'\n" \
"Format:\n" \
" [timestamps_cell_array[, time, continuous_cell_array]] = cbmex('trialdata', [active = 0], [<parameter>[, value]])\n" \
" [time, continuous_cell_array] = cbmex('trialdata', [active = 0], [<parameter>[, value]])\n" \
"Note: above format means:\n" \
" if one output requested it will be timestamps_cell_array\n" \
" if two outputs requested it will be time and continuous_cell_array\n" \
"Inputs:\n" \
"active (optional):\n" \
" set 0 (default) to leave buffer intact\n" \
" set 1 to clear all the data and reset the trial time to the current time\n" \
"<parameter>[, value] pairs are optional, some parameters do not have values.\n" \
" from left to right parameters will override previous ones or combine with them if possible.\n" \
"<parameter>[, value] can be any of:\n" \
"'instance', value: value is the library instance to use (default is 0)\n" \
"\n" \
"Outputs:\n" \
"timestamps_cell_array: Timestamps for events of 152 channels (152 rows). Each row in this matrix looks like:\n" \
" For spike channels:\n" \
" 'channel name' [unclassified timestamps_vector] [u1_timestamps_vector] [u2_timestamps_vector] [u3_timestamps_vector] [u4_timestamps_vector] [u5_timestamps_vector]\n" \
" For digital input channels:\n" \
" 'channel name' [timestamps_vector] [values_vector] ...remaining columns are empty...\n" \
"time: Time (in seconds) that the data buffer was most recently cleared.\n" \
"continuous_cell_array: Continuous sample data, variable number of rows. Each row in this matrix looks like:\n" \
" [channel number] [sample rate (in samples / s)] [values_vector]\n" \
#define CBMEX_USAGE_TRIALCOMMENT \
"Grab comments configured by 'trialconfig'\n" \
"Format:\n" \
" [comments_cell_array, [timestamps_vector], [rgba_vector], [charset_vector]] \n" \
" = cbmex('trialcomment', [active = 0], [<parameter>[, value]])\n" \
"Inputs:\n" \
"active (optional):\n" \
" set 0 (default) to leave buffer intact\n" \
" set 1 to clear all the data and reset the trial time to the current time\n" \
"<parameter>[, value] pairs are optional, some parameters do not have values.\n" \
" from left to right parameters will override previous ones or combine with them if possible.\n" \
"<parameter>[, value] can be any of:\n" \
"'instance', value: value is the library instance to use (default is 0)\n" \
"\n" \
"Outputs:\n" \
"comments_cell_array: cell-array of comments (strings of possibly different sizes)\n" \
"timestamps_vector (optional): timastamps of the comments\n" \
"rgba_vector (optional): comments colors\n" \
"charset_vector (optional): characterset vector for comments\n" \
#define CBMEX_USAGE_TRIALTRACKING \
"Grab tracking data configured by 'trialconfig'\n" \
"Format:\n" \
" [tracking_cell_array] = cbmex('trialtracking', [active = 0], [<parameter>[, value]])\n" \
"Inputs:\n" \
"active (optional):\n" \
" set 0 (default) to leave buffer intact\n" \
" set 1 to clear all the data and reset the trial time to the current time\n" \
"<parameter>[, value] pairs are optional, some parameters do not have values.\n" \
" from left to right parameters will override previous ones or combine with them if possible.\n" \
"<parameter>[, value] can be any of:\n" \
"'instance', value: value is the library instance to use (default is 0)\n" \
"\n" \
"Outputs:\n" \
"tracking_cell_array: Each row in this matrix looks like:\n" \
" 'trackable_name' desc_vector timestamps_vector synch_timestamps_vector synch_frame_numbers_vector rb_cell_array\n" \
" Here is the description of output:\n" \
" desc_vector: column vector [type id max_point_count]\n" \
" type: 1 (2DMARKERS), 2 (2DBLOB), 3 (3DMARKERS), 4 (2DBOUNDARY)\n" \
" id: node unique ID\n" \
" max_point_count: maximum number of points for this trackable\n" \
" timestamps_vector: the timestamps of the tracking packets\n" \
" synch_timestamps_vector: synchronized timestamps of the tracking (in milliseconds)\n" \
" synch_frame_numbers_vector: synchronized frame numbers of tracking\n" \
" rb_cell_array: each cell is a matrix of rigid-body, the rows are points, columns are coordinates\n"\
#define CBMEX_USAGE_FILECONFIG \
"Configures file recording\n" \
"Format: [recording filename username] = cbmex('fileconfig', [filename, comments, action, [<parameter>[, value]]])\n" \
"Inputs:\n" \
"filename: file name string (255 character maximum)\n" \
"comments: file comment string (255 character maximum)\n" \
"action: set 1 to start recording, 0 to stop recording" \
"<parameter>[, value] pairs are optional, some parameters do not have values.\n" \
" from left to right parameters will override previous ones or combine with them if possible.\n" \
"<parameter>[, value] can be any of:\n" \
"'instance', value: value is the library instance to use (default is 0)\n" \
"'option', value: value is can be any of the 'open', 'close', 'none' (default)\n" \
" 'close' - closes the File dialog if open\n" \
" 'open' - opens the File dialog if closed, ignoring other parameters\n" \
" 'none' - opens the File dialog if closed, sets parameters given, starts or stops recording\n" \
"Outputs:\n" \
"recording: 1 if recording is in progress, 0 if not\n" \
"filename: recording file name\n" \
"username: recording user name\n" \
#define CBMEX_USAGE_DIGITALOUT \
"Set digital output properties for given channel\n" \
"Format: cbmex('digitalout', channel, default_value, [<parameter>[, value]])\n" \
"Inputs:\n" \
"channel: 153 (dout1), 154 (dout2), 155 (dout3), 156 (dout4)\n" \
"default_value: 1 sets dout default to ttl high and 0 sets dout default to ttl low" \
"<parameter>[, value] pairs are optional, some parameters do not have values.\n" \
" from left to right parameters will override previous ones or combine with them if possible.\n" \
"<parameter>[, value] can be any of:\n" \
"'instance', value: value is the library instance to use (default is 0)\n" \
#define CBMEX_USAGE_ANALOGOUT \
"Set analog output properties for given channel\n" \
"Format: cbmex('analogout', channel, [<parameter>[, value]])\n" \
"Inputs:\n" \
"channel: 145 (aout1), 146 (aout2), 147 (aout3), 148 (aout4)\n" \
" 149 (audout1), 150 (audout2)\n" \
"Each analog output can exclusivlely monitor a channel, generate custom waveform or be disabled\n" \
"<parameter>, <value> pairs are optional, Some parameters do not have values.\n" \
" from left to right parameters will override previous ones or combine with them if possible.\n" \
"<parameter>[, value] can be any of:\n" \
"'pulses', waveform: waveform is vector \n" \
" [nPhase1Duration nPhase1Amplitude nInterPhaseDelay nPhase2Duration nPhase2Amplitude nInterPulseDelay]\n" \
"'sequence', waveform: waveform is variable length vector of duration and amplitude\n" \
" Waveform format is [nDuration1 nAmplitude1 nDuration2 nAmplitude2 ...]\n" \
" Waveform must be a nonempty even-numbered vector of double-precision numbers\n" \
" Each duration must be followed by amplitude for that duration\n" \
" Durations must be positive\n" \
" Each duration-amplitude pair is a phase in the waveform\n" \
"'sinusoid', waveform: waveform is vector [nFrequency nAmplitude]\n" \
"'monitor', type: type can be any of 'spike', 'continuous'\n" \
" 'spike' means spikes on 'input' channel are monitored\n" \
" 'continuous' means continuous 'input' channel is monitored\n" \
"'track': monitor the last tracked channel\n" \
"'disable': disable analog output\n" \
"'offset', offset: amplitude offset\n" \
"'repeats', repeats: number of repeats. 0 (default) means non-stop\n" \
"'index', index: trigger index (0 to 4) is the per-channel trigger index (default is 0)\n" \
"'trigger', trigger: trigger can be any of 'instant' (default), 'off', 'dinrise', 'dinfall', 'spike', 'cmtcolor', 'softreset'\n" \
" 'off' means this trigger is not used\n" \
" 'instant' means immediate trigger (immediate analog output waveform)\n" \
" 'dinrise' is for digital input rising edge, 'dinfall' is for digital input falling edge\n" \
" 'spike' is the spike event on given input channel\n" \
" 'cmtcolor' is the trigger based on colored comment\n" \
" 'softreset' is the trigger based on software reset (e.g. result of file recording)\n" \
" 'extension' is the trigger based on extension\n" \
"'input', input: input depends on 'trigger' or 'monitor'\n" \
" If trigger is 'dinrise' or 'dinfall' then 'input' is bit number of 1 to 16 for first digital input\n" \
" If trigger is 'spike' then 'input' is input channel with spike data\n" \
" If trigger is 'cmtcolor' then 'input' is the high word (two bytes) of the comment color\n" \
" If monitor is 'spike' then 'input' is input channel with spike processing\n" \
" If monitor is 'continuous' then 'input' is input channel with continuous data\n" \
"'value', value: trigger value depends on 'trigger'\n" \
" If trigger is 'cmtcolor' then 'value' is the low word (two bytes) of the comment color\n" \
" If trigger is 'spike' then 'value' is spike unit number\n" \
" (0 for unclassified, 1-5 for first to fifth unit and 254 for any unit)\n" \
"'mv': if specified, voltages are considered in milli volts instead of raw integer value\n" \
"'ms': if specified, intervals are considered in milli seconds instead of samples\n" \
"'instance', value: value is the library instance to use (default is 0)\n" \
#define CBMEX_USAGE_MASK \
"Masks or unmasks given channels from trials\n" \
"Format: cbmex('mask', channel, [active = 1], [<parameter>[, value]])\n" \
"Inputs:\n" \
"channel: The channel number to mask\n" \
" channel 0 means all of the channels\n" \
"active (optional): set 1 (default) to activate, 0 to deactivate (mask out)\n" \
"<parameter>[, value] pairs are optional, some parameters do not have values.\n" \
" from left to right parameters will override previous ones or combine with them if possible.\n" \
"<parameter>[, value] can be any of:\n" \
"'instance', value: value is the library instance to use (default is 0)\n" \
#define CBMEX_USAGE_COMMENT \
"Send comment or user event\n" \
"Format: cbmex('comment', rgba, charset, comment, [<parameter>[, value]])\n" \
"Inputs:\n" \
"rgba: color coding or custom event number\n" \
"charset: character-set 0 for ASCII or 1 for UTF16 or any user-defined\n" \
"comment: comment string (maximum 127 characters)\n" \
"<parameter>[, value] pairs are optional, some parameters do not have values.\n" \
" from left to right parameters will override previous ones or combine with them if possible.\n" \
"<parameter>[, value] can be any of:\n" \
"'instance', value: value is the library instance to use (default is 0)\n" \
#define CBMEX_USAGE_CONFIG \
"Get channel config and optionally change some channel parameters\n" \
"Format: [config_cell_aray] = cbmex('config', channel, [<parameter>[, value]])\n" \
"Note: \n" \
" if new configuration is given and config_cell_aray is not present, nothing will be returned\n" \
"Inputs:\n" \
"channel: The channel number\n" \
"<parameter>[, value] pairs are optional, some parameters do not have values.\n" \
"<parameter>[, value] can be any of:\n" \
"'instance', value: value is the library instance to use (default is 0)\n" \
"'userflags', value: a user-defind value for the channel\n" \
"'smpfilter', value: continuous filter number\n" \
"'smpgroup', value: continuous sampling group number\n" \
"'spkfilter', value: spike filter number\n" \
"'spkgroup', value: NTrode group number\n" \
"'spkthrlevel', value: spike threshold level (can be raw integer, or string such as '-65mV')\n" \
"'amplrejpos', value: amplitude rejection positive range (can be raw integer, or string such as '5V')\n" \
"'amplrejneg', value: amplitude rejection negative range (can be raw integer, or string such as '-5V')\n" \
"'refelecchan', value: reference electrode number\n" \
"\n" \
"Outputs:\n" \
"config_cell_array (optional): if specified previous parameters are returned\n" \
"Each row in this matrix looks like:" \
" <parameter>, <value>" \
" <parameter> can be anything that is also specified in the Inputs section (plus the additional parameters below)\n" \
" <value> will be the configuration value for the channel\n" \
" additional <parameter>\n" \
"'analog_unit': unit of analog value\n" \
"'max_analog': maximum analog value\n" \
"'max_digital': maximum digital value\n" \
"'min_analog': minimum analog value\n" \
"'min_digital': minimum digital value\n" \
#define CBMEX_USAGE_CCF \
"Read, write and send CCF configuration file\n" \
"Format: cbmex('ccf', [<parameter>[, value]])\n" \
"Inputs:\n" \
"<parameter>[, value] pairs are optional, some parameters do not have values.\n" \
" from left to right parameters will override previous ones or combine with them if possible.\n" \
"<parameter>[, value] can be any of:\n" \
"'threaded': Use threaded operation when possible\n" \
"'send', filename: read CCF file and send it to NSP\n" \
"'save', destination_file: Save active configuration to CCF file\n" \
"'load', source_file, 'convert', destination_file: convert source file to new CCF file (in latest format)\n" \
"'instance', value: value is the library instance to use (default is 0)\n" \
#define CBMEX_USAGE_SYSTEM \
"Perform given cbmex system command\n" \
"Format: cbmex('system', <command>, [<parameter>[, value]])\n" \
"Inputs:\n" \
"<command> can be any of the following\n" \
" 'reset' : resets instrument\n" \
" 'shutdown' : shuts down instrument\n" \
" 'standby' : sends instrument to standby mode" \
"<parameter>[, value] pairs are optional, some parameters do not have values.\n" \
" from left to right parameters will override previous ones or combine with them if possible.\n" \
"<parameter>[, value] can be any of:\n" \
"'instance', value: value is the library instance to use (default is 0)\n" \
#define CBMEX_USAGE_SYNCHOUT \
"Set synch output clock\n" \
"Format: cbmex('synchout', [<parameter>[, value]])\n" \
"Inputs:\n" \
"<parameter>[, value] pairs are optional, some parameters do not have values.\n" \
" from left to right parameters will override previous ones or combine with them if possible.\n" \
"<parameter>[, value] can be any of:\n" \
"'freq', value: value is the frequency in Hz, 0 to stop (closest supported frequency will be used)\n" \
"'repeats', repeats: number of repeats. 0 (default) means non-stop\n" \
"'instance', value: value is the library instance to use (default is 0)\n" \
#define CBMEX_USAGE_EXTENSION \
"Extension control\n" \
"Format: cbmex('ext', [<parameter>[, value]])\n" \
"Inputs:\n" \
"<parameter>[, value] pairs are optional, some parameters do not have values.\n" \
" from left to right parameters will override previous ones or combine with them if possible.\n" \
"<parameter>[, value] can be any of:\n" \
"'upload', filepath: upload given file to extension root (blocks until upload finish)\n" \
"'command', cmd: cmd is string command to run on extension root\n" \
"'input', line: line is input to the previous command (if running)\n" \
"'terminate': to signal last running command to terminate (if running)\n" \
"'instance', value: value is the library instance to use (default is 0)\n" \
#endif /* CBMEX_H_INCLUDED */
| 63.096471 | 180 | 0.611687 |
03c6dbf988d89216f616fd104d904a06c42c6020 | 2,682 | h | C | system/lib/libc/musl/arch/js/bits/signal.h | Nitrillo/emscripten | b3efd9328f940034e1cab45af23bf29541e0d8ff | [
"MIT"
] | 6 | 2015-07-27T13:03:22.000Z | 2020-02-20T18:30:29.000Z | system/lib/libc/musl/arch/js/bits/signal.h | Nitrillo/emscripten | b3efd9328f940034e1cab45af23bf29541e0d8ff | [
"MIT"
] | 2 | 2015-06-21T17:38:11.000Z | 2015-06-22T20:54:42.000Z | system/lib/libc/musl/arch/js/bits/signal.h | Nitrillo/emscripten | b3efd9328f940034e1cab45af23bf29541e0d8ff | [
"MIT"
] | 1 | 2019-02-22T00:06:43.000Z | 2019-02-22T00:06:43.000Z | #if defined(_POSIX_SOURCE) || defined(_POSIX_C_SOURCE) \
|| defined(_XOPEN_SOURCE) || defined(_GNU_SOURCE) || defined(_BSD_SOURCE)
#ifdef _GNU_SOURCE
#define REG_GS 0
#define REG_FS 1
#define REG_ES 2
#define REG_DS 3
#define REG_EDI 4
#define REG_ESI 5
#define REG_EBP 6
#define REG_ESP 7
#define REG_EBX 8
#define REG_EDX 9
#define REG_ECX 10
#define REG_EAX 11
#define REG_TRAPNO 12
#define REG_ERR 13
#define REG_EIP 14
#define REG_CS 15
#define REG_EFL 16
#define REG_UESP 17
#define REG_SS 18
#endif
typedef struct sigaltstack {
void *ss_sp;
int ss_flags;
size_t ss_size;
} stack_t;
#if defined(_GNU_SOURCE) || defined(_BSD_SOURCE)
typedef int greg_t, gregset_t[19];
typedef struct _fpstate {
unsigned long cw, sw, tag, ipoff, cssel, dataoff, datasel;
struct {
unsigned short significand[4], exponent;
} _st[8];
unsigned long status;
} *fpregset_t;
struct sigcontext {
unsigned short gs, __gsh, fs, __fsh, es, __esh, ds, __dsh;
unsigned long edi, esi, ebp, esp, ebx, edx, ecx, eax;
unsigned long trapno, err, eip;
unsigned short cs, __csh;
unsigned long eflags, esp_at_signal;
unsigned short ss, __ssh;
struct _fpstate *fpstate;
unsigned long oldmask, cr2;
};
typedef struct {
gregset_t gregs;
fpregset_t fpregs;
unsigned long oldmask, cr2;
} mcontext_t;
#else
typedef struct {
unsigned __space[22];
} mcontext_t;
#endif
typedef struct __ucontext {
unsigned long uc_flags;
struct __ucontext *uc_link;
stack_t uc_stack;
mcontext_t uc_mcontext;
sigset_t uc_sigmask;
unsigned long __fpregs_mem[28];
} ucontext_t;
#define SA_NOCLDSTOP 1
#define SA_NOCLDWAIT 2
#define SA_SIGINFO 4
#define SA_ONSTACK 0x08000000
#define SA_RESTART 0x10000000
#define SA_NODEFER 0x40000000
#define SA_RESETHAND 0x80000000
#define SA_RESTORER 0x04000000
#endif
#define SIGHUP 1
#define SIGINT 2
#define SIGQUIT 3
#define SIGILL 4
#define SIGTRAP 5
#define SIGABRT 6
#define SIGIOT SIGABRT
#define SIGBUS 7
#define SIGFPE 8
#define SIGKILL 9
#define SIGUSR1 10
#define SIGSEGV 11
#define SIGUSR2 12
#define SIGPIPE 13
#define SIGALRM 14
#define SIGTERM 15
#define SIGSTKFLT 16
#define SIGCHLD 17
#define SIGCONT 18
#define SIGSTOP 19
#define SIGTSTP 20
#define SIGTTIN 21
#define SIGTTOU 22
#define SIGURG 23
#define SIGXCPU 24
#define SIGXFSZ 25
#define SIGVTALRM 26
#define SIGPROF 27
#define SIGWINCH 28
#define SIGIO 29
#define SIGPOLL 29
#define SIGPWR 30
#define SIGSYS 31
#define SIGUNUSED SIGSYS
#define _NSIG 65
| 22.537815 | 74 | 0.701342 |
03c7322e6b1295d49bf9aade0427bed1d57c4244 | 1,866 | h | C | System/Library/CoreServices/SpringBoard/PrivateHeaders/SBCompoundIdleTimer.h | lechium/iPhoneOS_12.1.1_Headers | aac688b174273dfcbade13bab104461f463db772 | [
"MIT"
] | 12 | 2019-06-02T02:42:41.000Z | 2021-04-13T07:22:20.000Z | System/Library/CoreServices/SpringBoard/PrivateHeaders/SBCompoundIdleTimer.h | lechium/iPhoneOS_12.1.1_Headers | aac688b174273dfcbade13bab104461f463db772 | [
"MIT"
] | null | null | null | System/Library/CoreServices/SpringBoard/PrivateHeaders/SBCompoundIdleTimer.h | lechium/iPhoneOS_12.1.1_Headers | aac688b174273dfcbade13bab104461f463db772 | [
"MIT"
] | 3 | 2019-06-11T02:46:10.000Z | 2019-12-21T14:58:16.000Z | //
// Generated by class-dump 3.5 (64 bit).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by Steve Nygard.
//
#import "NSObject.h"
#import "SBIdleTimer.h"
#import "SBIdleTimerDelegate.h"
@class NSArray, NSString;
@interface SBCompoundIdleTimer : NSObject <SBIdleTimerDelegate, SBIdleTimer>
{
id <SBIdleTimerDelegate> _delegate; // 8 = 0x8
NSArray *_timers; // 16 = 0x10
unsigned long long _currentTimerIdx; // 24 = 0x18
}
@property(nonatomic) __weak id <SBIdleTimerDelegate> delegate; // @synthesize delegate=_delegate;
- (void).cxx_destruct; // IMP=0x000000010026e384
- (_Bool)isTimerCurrent:(id)arg1; // IMP=0x000000010026e2cc
- (void)idleTimerDidWarn:(id)arg1; // IMP=0x000000010026e234
- (void)idleTimerDidReceiveUserEvent:(id)arg1; // IMP=0x000000010026e19c
- (void)idleTimerDidExpire:(id)arg1; // IMP=0x000000010026dfcc
- (void)idleTimerDidRefresh:(id)arg1; // IMP=0x000000010026df38
- (id)idleTimerForExtension; // IMP=0x000000010026dd28
- (_Bool)isEqualToTimer:(id)arg1; // IMP=0x000000010026dbc8
- (void)reset; // IMP=0x000000010026da8c
- (id)descriptionBuilderWithMultilinePrefix:(id)arg1; // IMP=0x000000010026da80
- (id)descriptionWithMultilinePrefix:(id)arg1; // IMP=0x000000010026da2c
- (id)succinctDescriptionBuilder; // IMP=0x000000010026d878
- (id)succinctDescription; // IMP=0x000000010026d824
- (id)copyWithZone:(struct _NSZone *)arg1; // IMP=0x000000010026d7dc
@property(readonly, copy) NSString *description;
- (_Bool)isEqual:(id)arg1; // IMP=0x000000010026d7c0
- (id)initWithTimers:(id)arg1 copy:(_Bool)arg2; // IMP=0x000000010026d618
- (id)initWithTimers:(id)arg1; // IMP=0x000000010026d608
- (id)init; // IMP=0x000000010026d5f8
// Remaining properties
@property(readonly, copy) NSString *debugDescription;
@property(readonly) unsigned long long hash;
@property(readonly) Class superclass;
@end
| 38.081633 | 97 | 0.757771 |
03c77a561b785cec6cfa50fb27ca1981220295b8 | 9,859 | c | C | main.c | MyLegGuy/commandRepeatScript | aadc6197dc748866a7422ff068c7f9bb9bdf3a86 | [
"CC0-1.0"
] | null | null | null | main.c | MyLegGuy/commandRepeatScript | aadc6197dc748866a7422ff068c7f9bb9bdf3a86 | [
"CC0-1.0"
] | null | null | null | main.c | MyLegGuy/commandRepeatScript | aadc6197dc748866a7422ff068c7f9bb9bdf3a86 | [
"CC0-1.0"
] | null | null | null | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <signal.h>
#include <errno.h>
// Set these to 0 to disable useless output to stdout
#define NEWLINESEPARATE 0
#define NULLDELIMFLAG "--nullDelim"
#define NEWLINEDELIMFLAG "--newlineDelim"
#define VERBOSETOGGLE "-v"
#define SUPERVERBOSETOGGLE "-V"
#define STARTDEFINEFLAG "-s"
#define PROP_SKIP_COMMAND_FORMAT_INDEX 1
#define PROP_CAN_FAIL 2
// #define 4
volatile sig_atomic_t shouldHappyExit=0;
int lineDelim='\n';
char uselessInfo=0;
char reallyUselessInfo=0;
int curProperties=0;
// Catch SIGUSR1
static void happyExitCatch(const int signo){
(void)signo;
shouldHappyExit=1;
}
char rmNewline(char* _target, size_t _len){ // _len includes the newline character
--_len;
if (_target[_len]=='\n'){
_target[_len]='\0';
return 1;
}
return 0;
}
// returns 1 if irregular exit
char getExitStatus(int _exitInfo){
if (WIFEXITED(_exitInfo)){
if (WEXITSTATUS(_exitInfo)!=0){
return 1;
}else{
return 0;
}
}else{
return 1;
}
}
char runProgram(char* const _args[], char _showOutput){
if (reallyUselessInfo){
char** _tempArgs=(char**)_args;
while(_tempArgs[0]){
printf("%s ",_tempArgs[0]);
_tempArgs++;
}
putchar('\n');
}
pid_t _newProcess;
if ((_newProcess=fork())==0) {
if (!_showOutput){
int _nullFile = open("/dev/null", O_WRONLY);
dup2(_nullFile,STDOUT_FILENO);
dup2(_nullFile,STDERR_FILENO);
close(_nullFile);
}
execv(_args[0],_args);
exit(1);
}
char _happySeen=0;
while(1){
int _exitInfo;
if (waitpid(_newProcess,&_exitInfo,0)==-1){
if (_happySeen){ // only allow shouldHappyExit to repeat waitpid once
return 1;
}
if (errno==EINTR && shouldHappyExit){ // if we caught SIGUSR1, don't interrupt. repeat.
_happySeen=1;
continue;
}
}
return getExitStatus(_exitInfo);
}
}
int readNumberLineOrEOF(FILE* fp, char** _tempLineBuff, size_t* _tempLineBuffSize, char* _didEOF){
size_t _numRead = getdelim(_tempLineBuff,_tempLineBuffSize,lineDelim,fp);
if (_numRead==-1){
if (_didEOF!=NULL && feof(fp)){
*_didEOF=1;
return -1;
}else{
fputs("failed to read number line\n",stderr);
exit(1);
}
}
// verify that all these characters are numbers
int i;
for (i=0;i<_numRead-1;++i){ // don't check the last character, that should be the deliminator character. if it's not the deliminator character, that means we're at EOF. this function is never used as the last line.
if (!((*_tempLineBuff)[i]>='0' && (*_tempLineBuff)[i]<='9')){
fprintf(stderr,"expected a number line, got %s\n",*_tempLineBuff);
exit(1);
}
}
if (_didEOF!=NULL){
*_didEOF=0;
}
return atoi(*_tempLineBuff);
}
int readNumberLine(FILE* fp, char** _tempLineBuff, size_t* _tempLineBuffSize){
return readNumberLineOrEOF(fp,_tempLineBuff,_tempLineBuffSize,NULL);
}
char runScript(FILE* fp, int _startIndex){
char _ret=0;
char* _tempLineBuff=NULL;
size_t _tempLineBuffSize=0;
// skip the first line by just reading and ignoring its contents
if (getdelim(&_tempLineBuff,&_tempLineBuffSize,lineDelim,fp)==-1){
fputs("error reading the ignored line!\n",stderr);
exit(1);
}
// second line, script properties line
curProperties = readNumberLine(fp,&_tempLineBuff,&_tempLineBuffSize);
// third line, command format count
int _totalCommandFormats = (curProperties & PROP_SKIP_COMMAND_FORMAT_INDEX) ? 1 : readNumberLine(fp,&_tempLineBuff,&_tempLineBuffSize);
// Read command formats
int* _commandSizes = malloc(sizeof(int)*_totalCommandFormats);
char*** _commandLists = malloc(sizeof(char**)*_totalCommandFormats);
int** _argMaps = malloc(sizeof(int*)*_totalCommandFormats);
int* _argCounts = malloc(sizeof(int)*_totalCommandFormats);
int _mostArgs=0; // most args out of any command format
int c;
for (c=0;c<_totalCommandFormats;++c){
// Read initial command
int _mainCommandSize = readNumberLine(fp,&_tempLineBuff,&_tempLineBuffSize);
_commandSizes[c]=_mainCommandSize;
char** _commandList = malloc(sizeof(char*)*(_mainCommandSize+1));
_commandLists[c]=_commandList;
int* _argMap = malloc(sizeof(int)*_mainCommandSize*2); // pattern with two byte info: <int destination index to put in _commandList> <int source index from _lastReadArgs>
_argMaps[c]=_argMap;
int _numInsertions=0; // use this to find how much of _argMap to read
int _maxMapDigit=-1;
int i;
for (i=0;i<_mainCommandSize;++i){
size_t _readChars = getdelim(&_tempLineBuff,&_tempLineBuffSize,lineDelim,fp);
if (_readChars==-1){
fputs("Failed to read line when parsing command\n",stderr);
exit(1);
}
if (_tempLineBuff[0]=='$'){
int _insertSource = atoi(&_tempLineBuff[1]);
if (_insertSource>_maxMapDigit){
_maxMapDigit=_insertSource;
}
_argMap[_numInsertions*2]=i;
_argMap[_numInsertions*2+1]=_insertSource;
_numInsertions++;
}else{
rmNewline(_tempLineBuff,_readChars);
_commandList[i]=strdup(_tempLineBuff);
}
}
_commandList[_mainCommandSize]=NULL; // null terminated array
if (access(_commandList[0],F_OK|X_OK)!=0){
fprintf(stderr,"%s permission denied\n",_commandList[0]);
exit(1);
}
_argCounts[c]=_maxMapDigit+1;
if (_argCounts[c]>_mostArgs){
_mostArgs=_argCounts[c];
}
}
// fast forward to start index of requested
int _curCommandIndex=0;
for (;_curCommandIndex<_startIndex;++_curCommandIndex){
int _thisIndex = (curProperties & PROP_SKIP_COMMAND_FORMAT_INDEX) ? 0 : readNumberLine(fp,&_tempLineBuff,&_tempLineBuffSize);
if (_thisIndex<0 || _thisIndex>=_totalCommandFormats){
printf("out of range index\n");
exit(1);
}
int i;
for (i=0;i<_argCounts[_thisIndex];++i){
while(1){
int _gottenChar = fgetc(fp);
if (_gottenChar==EOF){
puts("read error when trying to find start index. is index too far?");
exit(1);
}else if (_gottenChar==lineDelim){
break;
}
}
}
}
// Read and do command sets
char** _lastReadArgs = malloc(sizeof(char*)*_mostArgs);
while(!feof(fp)){
char _isScriptDone=0;
int _cIndex;
if (curProperties & PROP_SKIP_COMMAND_FORMAT_INDEX){
_cIndex=0;
}else{
char _didEOF;
_cIndex=readNumberLineOrEOF(fp,&_tempLineBuff,&_tempLineBuffSize,&_didEOF);
if (_didEOF){
_isScriptDone=1;
}
}
// Read arguments into the _lastReadArgs array
if (!_isScriptDone){
int i;
for (i=0;i<_argCounts[_cIndex];++i){
size_t _readChars = getdelim(&_tempLineBuff,&_tempLineBuffSize,lineDelim,fp);
if (_readChars==-1){
if (feof(fp)){
_isScriptDone=1;
break;
}else{
fprintf(stderr,"error reading at set index %d\n",_curCommandIndex);
exit(1);
}
}
rmNewline(_tempLineBuff,_readChars);
_lastReadArgs[i] = strdup(_tempLineBuff);
}
}
if (_isScriptDone){
break;
}
// insert read special arguments into usual arguments array
int i;
for (i=0;i<_argCounts[_cIndex];++i){
_commandLists[_cIndex][_argMaps[_cIndex][i*2]]=_lastReadArgs[_argMaps[_cIndex][i*2+1]];
}
// execute
if (runProgram(_commandLists[_cIndex],1)){
if (!(curProperties & PROP_CAN_FAIL)){
fprintf(stderr,"program failed at set index %d\n",_curCommandIndex);
exit(1);
}else{
if (reallyUselessInfo){
printf("Warning: failed.\n");
}
}
}
// free
for (i=0;i<_argCounts[_cIndex];++i){
free(_lastReadArgs[i]);
}
//
#if NEWLINESEPARATE==1
putchar('\n');
#endif
if (shouldHappyExit){
if (uselessInfo){
printf("happy exit at index %d\n",_curCommandIndex);
_ret=1;
}
break;
}
++_curCommandIndex;
}
free(_lastReadArgs);
if (uselessInfo){
puts("happy single script end!");
}
free:
// free the command list
for (c=0;c<_totalCommandFormats;++c){
int i;
// first set the already freed dynamic argument strings that are still inside _commandList to NULL
for (i=0;i<_argCounts[c];++i){
_commandLists[c][_argMaps[c][i*2]]=NULL;
}
for (i=0;i<_commandSizes[c];++i){
free(_commandLists[c][i]);
}
free(_commandLists[c]);
}
free(_commandLists);
for (c=0;c<_totalCommandFormats;++c){
free(_argMaps[c]);
}
free(_argMaps);
free(_commandSizes);
free(_argCounts);
free(_tempLineBuff);
return _ret;
}
int main(int argc, char** args){
if (argc<2){
fprintf(stderr,"Usage: %s [-V/-v] [-s <num>] ["NULLDELIMFLAG" / "NEWLINEDELIMFLAG"] <script 1> [script ...]\n",argc>=1 ? args[0] : "<program>");
return 1;
}
// Catch SIGUSR1. Use it as a signal to finish up before exiting
struct sigaction exitCatchSig;
memset(&exitCatchSig, 0, sizeof(struct sigaction));
exitCatchSig.sa_handler = happyExitCatch;
sigaction(SIGUSR1, &exitCatchSig, NULL);
// Run passed scripts
int _nonScriptArgs=0;
int i;
int _startIndex=0;
for (i=1;i<argc;++i){
if (strcmp(args[i],NULLDELIMFLAG)==0){
lineDelim='\0';
++_nonScriptArgs;
continue;
}else if (strcmp(args[i],NEWLINEDELIMFLAG)==0){
lineDelim='\n';
++_nonScriptArgs;
continue;
}else if (strcmp(args[i],VERBOSETOGGLE)==0){
uselessInfo=!uselessInfo;
reallyUselessInfo=0;
++_nonScriptArgs;
continue;
}else if (strcmp(args[i],SUPERVERBOSETOGGLE)==0){
reallyUselessInfo=!reallyUselessInfo;
uselessInfo=reallyUselessInfo;
++_nonScriptArgs;
continue;
}else if (strcmp(args[i],STARTDEFINEFLAG)==0){
if (i!=argc-1){
++i;
_nonScriptArgs+=2;
_startIndex=atoi(args[i]);
continue;
}else{
puts(STARTDEFINEFLAG" needs an arg.");
exit(1);
}
}
if (uselessInfo){
printf("Running script: %s (%d/%d)\n",args[i],i-_nonScriptArgs,argc-1-_nonScriptArgs);
}
FILE* fp = fopen(args[i],"rb");
if (fp){
if (runScript(fp,_startIndex)){
i=argc;
}
_startIndex=0;
}else{
fprintf(stderr,"Could not open %s\n",args[i]);
return 1;
}
fclose(fp);
}
return 0;
}
| 27.462396 | 215 | 0.683741 |
03c7993e7cc46196db9d7fafb6d04186f78243d4 | 2,272 | c | C | tests/mla_bench/test_mla.c | ArmstrongYang/Tengine | 69c610b7a38e3022e69ccaf9119901f3402af567 | [
"Apache-2.0"
] | 3 | 2019-12-27T02:31:59.000Z | 2021-08-04T05:59:03.000Z | tests/mla_bench/test_mla.c | houzh/Tengine | 423aaaf7e9008679f64a78ee93c8ebf7dbd58dc9 | [
"Apache-2.0"
] | null | null | null | tests/mla_bench/test_mla.c | houzh/Tengine | 423aaaf7e9008679f64a78ee93c8ebf7dbd58dc9 | [
"Apache-2.0"
] | null | null | null | #include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <malloc.h>
#include <unistd.h>
#include <sys/time.h>
#include <time.h>
unsigned long get_cur_time(void)
{
struct timeval tv;
gettimeofday(&tv, NULL);
return (tv.tv_sec * 1000000 + tv.tv_usec);
}
void run_test(int reptition, int warm_up, void (*test_func)(void*), void* arg)
{
if(warm_up)
test_func(arg);
for(int i = 0; i < reptition; i++)
{
test_func(arg);
}
}
extern void test_mla_4s(long n);
extern void test_mla_16b(long n);
extern void test_fmla_4s(long n);
extern void test_mla_8h(long n);
#define TESTBED_WRAP(inst, a, b) \
void testbed_wrap_##inst##_##a##b(void* arg) \
{ \
long n = ( long )arg; \
test_##inst##_##a##b(n); \
}
TESTBED_WRAP(mla, 4, s)
TESTBED_WRAP(mla, 8, h)
TESTBED_WRAP(mla, 16, b)
TESTBED_WRAP(fmla, 4, s)
int main(int argc, char* argv[])
{
long n = 1024 * 16;
unsigned long start;
unsigned long end;
float fops;
start = get_cur_time();
run_test(16, 0, testbed_wrap_mla_4s, ( void* )n);
end = get_cur_time();
fops = n * 16 * 1020 * 8;
printf("MLA_4S: reptition %ld, used %lu us, calculate %.2f Mops\n", n, end - start,
fops * (1000000.0 / (end - start)) / 1000000);
start = get_cur_time();
run_test(16, 0, testbed_wrap_mla_8h, ( void* )n);
end = get_cur_time();
fops = n * 16 * 1020 * 16;
printf("MLA_8H: reptition %ld, used %lu us, calculate %.2f Mops\n", n, end - start,
fops * (1000000.0 / (end - start)) / 1000000);
start = get_cur_time();
run_test(16, 0, testbed_wrap_mla_16b, ( void* )n);
end = get_cur_time();
fops = n * 16 * 1020 * 32;
printf("MLA_16B: reptition %ld, used %lu us, calculate %.2f Mops\n", n, end - start,
fops * (1000000.0 / (end - start)) / 1000000);
start = get_cur_time();
run_test(16, 0, testbed_wrap_fmla_4s, ( void* )n);
end = get_cur_time();
fops = n * 16 * 1020 * 8;
printf("FMLA_4S: reptition %ld, used %lu us, calculated %.2f Mfops\n", n, end - start,
fops * (1000000.0 / (end - start)) / 1000000);
return 0;
}
| 24.695652 | 90 | 0.567782 |
03c9e15bd203ed97126a65d17a9b2930d3d1030b | 379 | c | C | packages/PIPS/validation/Bootstrap/getopt01.c | DVSR1966/par4all | 86b33ca9da736e832b568c5637a2381f360f1996 | [
"MIT"
] | 51 | 2015-01-31T01:51:39.000Z | 2022-02-18T02:01:50.000Z | packages/PIPS/validation/Bootstrap/getopt01.c | DVSR1966/par4all | 86b33ca9da736e832b568c5637a2381f360f1996 | [
"MIT"
] | 7 | 2017-05-29T09:29:00.000Z | 2019-03-11T16:01:39.000Z | packages/PIPS/validation/Bootstrap/getopt01.c | DVSR1966/par4all | 86b33ca9da736e832b568c5637a2381f360f1996 | [
"MIT"
] | 12 | 2015-03-26T08:05:38.000Z | 2022-02-18T02:01:51.000Z | // Intrinsics linked to getopt
#include "unistd.h"
#include "getopt.h"
int main(int argc, char* argv[])
{
char *optstring = "fo";
int i1 = getopt(argc, argv, optstring);
struct option * longopts;
int * longindex;
int i2 = getopt_long(argc, argv, optstring, longopts, longindex);
int i3 = getopt_long_only(argc, argv, optstring, longopts, longindex);
return 0;
}
| 22.294118 | 72 | 0.688654 |
03cae1ae06c4d9b8cf6976e4a9de56cb10b213ce | 463 | h | C | cognitics/include/CoordinateSystems/WGS84Transform.h | mikedig/cdb-productivity-api | e2bedaa550a8afa780c01f864d72e0aebd87dd5a | [
"MIT"
] | null | null | null | cognitics/include/CoordinateSystems/WGS84Transform.h | mikedig/cdb-productivity-api | e2bedaa550a8afa780c01f864d72e0aebd87dd5a | [
"MIT"
] | null | null | null | cognitics/include/CoordinateSystems/WGS84Transform.h | mikedig/cdb-productivity-api | e2bedaa550a8afa780c01f864d72e0aebd87dd5a | [
"MIT"
] | null | null | null | #pragma once
#include "IGeodeticTransform.h"
namespace Cognitics
{
namespace CoordinateSystems
{
class WGS84Transform : public IGeodeticTransform
{
public:
virtual void GeodeticToECEF(double latitude, double longitude, double altitude, double& x, double& y, double& z);
virtual void ECEFtoGeodetic(double x, double y, double z, double& latitude, double& longitude, double& altitude);
};
}
}
| 24.368421 | 125 | 0.663067 |
03cbe3e59d49c7219cd9c6fcecccfc5e6582a0eb | 384 | h | C | src/Lethe/Script/Ast/Types/AstTypeDelegate.h | killvxk/lethe | c1a9bb45063f5148dc6cf681ce907dcbb468f5e6 | [
"BSL-1.0"
] | 9 | 2020-03-08T14:54:49.000Z | 2021-12-22T22:52:04.000Z | src/Lethe/Script/Ast/Types/AstTypeDelegate.h | kmar/lethe | 78259f56e7eb887dcd470bd7d988df0b153bca43 | [
"BSL-1.0"
] | null | null | null | src/Lethe/Script/Ast/Types/AstTypeDelegate.h | kmar/lethe | 78259f56e7eb887dcd470bd7d988df0b153bca43 | [
"BSL-1.0"
] | 3 | 2020-03-09T08:24:40.000Z | 2020-03-09T14:04:23.000Z | #pragma once
#include "AstTypeFuncPtr.h"
namespace lethe
{
class LETHE_API AstTypeDelegate : public AstTypeFuncPtr
{
public:
LETHE_AST_NODE(AstTypeDelegate)
typedef AstTypeFuncPtr Super;
AstTypeDelegate(const TokenLocation &nloc) : Super(nloc)
{
type = AST_TYPE_DELEGATE;
}
bool TypeGen(CompiledProgram &p) override;
const AstNode *GetTypeNode() const override;
};
}
| 14.769231 | 57 | 0.765625 |
03cc9d3e438747a7ac5468a92b5ac0b47c0b17fa | 922 | h | C | Speecher/SynchronousOperation.h | William500/Speecher | 2a57e3d200acb5cc7a8f3a744a46ea31d7362824 | [
"MIT"
] | null | null | null | Speecher/SynchronousOperation.h | William500/Speecher | 2a57e3d200acb5cc7a8f3a744a46ea31d7362824 | [
"MIT"
] | null | null | null | Speecher/SynchronousOperation.h | William500/Speecher | 2a57e3d200acb5cc7a8f3a744a46ea31d7362824 | [
"MIT"
] | null | null | null | #pragma once
#include "AsyncOperationHandler.h"
template <typename T>
class SynchronousOperation
{
private:
typedef typename AsyncOperationHandler<T>::T_Interface T_Result;
Microsoft::WRL::ComPtr<AsyncOperationHandler<T>> m_Handler;
T_Result m_Result;
HANDLE m_Event;
public:
SynchronousOperation(ABI::Windows::Foundation::IAsyncOperation<T>* operation)
{
m_Event = CreateEventW(nullptr, FALSE, FALSE, nullptr);
Assert(m_Event != nullptr);
m_Handler = Make<AsyncOperationHandler<T>>([this](T_Result result)
{
m_Result = result;
auto setResult = SetEvent(m_Event);
Assert(setResult != FALSE);
});
auto hr = operation->put_Completed(m_Handler.Get());
Assert(SUCCEEDED(hr));
}
~SynchronousOperation()
{
CloseHandle(m_Event);
}
T_Result Wait()
{
auto waitResult = WaitForSingleObjectEx(m_Event, INFINITE, FALSE);
Assert(waitResult == WAIT_OBJECT_0);
return m_Result;
}
}; | 20.488889 | 78 | 0.733189 |
03ceaeb191f2f12ae4149c6f97c5f206ac61e5a7 | 1,330 | h | C | build/source/pcraster_python/utils/pcraster_python_utils_export.h | openearth/hydro-model-builder-generator-wflow | 6f689859d0a9a307324db3dbe3f03c51884a42a8 | [
"MIT"
] | null | null | null | build/source/pcraster_python/utils/pcraster_python_utils_export.h | openearth/hydro-model-builder-generator-wflow | 6f689859d0a9a307324db3dbe3f03c51884a42a8 | [
"MIT"
] | 2 | 2018-07-05T14:36:18.000Z | 2020-03-19T21:16:37.000Z | build/source/pcraster_python/utils/pcraster_python_utils_export.h | openearth/hydro-model-generator-wflow | 6f689859d0a9a307324db3dbe3f03c51884a42a8 | [
"MIT"
] | null | null | null |
#ifndef PCRASTER_PYTHON_UTILS_EXPORT_H
#define PCRASTER_PYTHON_UTILS_EXPORT_H
#ifdef PCRASTER_PYTHON_UTILS_STATIC_DEFINE
# define PCRASTER_PYTHON_UTILS_EXPORT
# define PCRASTER_PYTHON_UTILS_NO_EXPORT
#else
# ifndef PCRASTER_PYTHON_UTILS_EXPORT
# ifdef pcraster_python_utils_EXPORTS
/* We are building this library */
# define PCRASTER_PYTHON_UTILS_EXPORT __attribute__((visibility("default")))
# else
/* We are using this library */
# define PCRASTER_PYTHON_UTILS_EXPORT __attribute__((visibility("default")))
# endif
# endif
# ifndef PCRASTER_PYTHON_UTILS_NO_EXPORT
# define PCRASTER_PYTHON_UTILS_NO_EXPORT __attribute__((visibility("hidden")))
# endif
#endif
#ifndef PCRASTER_PYTHON_UTILS_DEPRECATED
# define PCRASTER_PYTHON_UTILS_DEPRECATED __attribute__ ((__deprecated__))
#endif
#ifndef PCRASTER_PYTHON_UTILS_DEPRECATED_EXPORT
# define PCRASTER_PYTHON_UTILS_DEPRECATED_EXPORT PCRASTER_PYTHON_UTILS_EXPORT PCRASTER_PYTHON_UTILS_DEPRECATED
#endif
#ifndef PCRASTER_PYTHON_UTILS_DEPRECATED_NO_EXPORT
# define PCRASTER_PYTHON_UTILS_DEPRECATED_NO_EXPORT PCRASTER_PYTHON_UTILS_NO_EXPORT PCRASTER_PYTHON_UTILS_DEPRECATED
#endif
#if 0 /* DEFINE_NO_DEPRECATED */
# ifndef PCRASTER_PYTHON_UTILS_NO_DEPRECATED
# define PCRASTER_PYTHON_UTILS_NO_DEPRECATED
# endif
#endif
#endif
| 30.930233 | 117 | 0.828571 |
03cf90d6915cd3bc0c40ea01625b986713df4d16 | 902 | h | C | ptconfig.h | EarthenSky/C-AutoCompile | 3345c4b100c64803e199f4e461c6bcb6b2ceb655 | [
"MIT"
] | null | null | null | ptconfig.h | EarthenSky/C-AutoCompile | 3345c4b100c64803e199f4e461c6bcb6b2ceb655 | [
"MIT"
] | null | null | null | ptconfig.h | EarthenSky/C-AutoCompile | 3345c4b100c64803e199f4e461c6bcb6b2ceb655 | [
"MIT"
] | null | null | null | #ifndef PTCONFIG
#define PTCONFIG
//#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct ItemContents {
char contentIdentifier; // 's' == string, 'a' == array.
char* itemString;
char** rowArray; // This is an array containing the values of each item.
//char stringArray[arrayLength][maxStringSize+1];
} ItemContents_t;
const char g_configFileName[] = ".ptconfig"; // The filename of the program's data file.
int getFileString(const char*, char*&); // Read file and output string ptr.
ItemContents_t ReadItem(char*, char*, int, int);
void DealocateItemContents(ItemContents_t);
char* WriteRow(char* fileStringIn, char* keyString, int rowIndex, char* rowString); // Write to file.
int FormatConfig(char*);
char* ConfigAddRow(char*, char*, char*);
#endif //PTCONFIG
| 32.214286 | 106 | 0.660754 |
03cfc60f127e4f26675936d824519b486058f37b | 4,269 | h | C | include/orion/net/http/Session.h | entuerto/liborion | 35b97594bbea3a6d89dc9261e5fd4e92717e9d71 | [
"MIT"
] | null | null | null | include/orion/net/http/Session.h | entuerto/liborion | 35b97594bbea3a6d89dc9261e5fd4e92717e9d71 | [
"MIT"
] | null | null | null | include/orion/net/http/Session.h | entuerto/liborion | 35b97594bbea3a6d89dc9261e5fd4e92717e9d71 | [
"MIT"
] | null | null | null | //
// Session.h
//
// Copyright (c) 2013-2017 Tomas Palazuelos
//
// Distributed under the MIT Software License. (See accompanying file LICENSE.md)
//
#ifndef ORION_NET_HTTP_SESSION_H
#define ORION_NET_HTTP_SESSION_H
#include <orion/Common.h>
#include <orion/net/EndPoint.h>
#include <orion/net/Options.h>
#include <orion/net/Url.h>
#include <orion/net/Utils.h>
#include <orion/net/http/Request.h>
#include <orion/net/http/Response.h>
#include <orion/net/http/Utils.h>
#include <asio.hpp>
#include <string>
namespace orion
{
namespace net
{
namespace http
{
///
/// Base session class
///
class API_EXPORT BaseSession
{
public:
NO_COPY(BaseSession);
BaseSession(asio::io_context& io_context);
// Move constructor
BaseSession(BaseSession&& rhs) noexcept;
/// Default destructor
virtual ~BaseSession();
/// Move assignment
BaseSession& operator=(BaseSession&& rhs) noexcept;
void set_option(const Parameters& parameters);
void set_option(Parameters&& parameters);
void set_option(const Timeout& timeout);
bool connected() const;
void connected(bool value);
std::error_code close();
asio::io_context& io_context();
asio::ip::tcp::socket& socket();
private:
/// The io_context used to perform asynchronous operations.
asio::io_context& _io_context;
/// Socket for the connection.
asio::ip::tcp::socket _socket;
Parameters _params;
Timeout _timeout;
bool _connected;
};
///
/// Synchronous session
///
class API_EXPORT SyncSession
: public BaseSession
, public std::enable_shared_from_this<SyncSession>
{
public:
NO_COPY(SyncSession);
SyncSession(asio::io_context& io_context);
template<typename... Ts>
SyncSession(asio::io_context& io_context, Ts&&... ts)
: SyncSession(io_context)
{
set_option(std::forward<Ts>(ts)...);
}
// Move constructor
SyncSession(SyncSession&& rhs) noexcept;
/// Default destructor
~SyncSession() override;
/// Move assignment
SyncSession& operator=(SyncSession&& rhs) noexcept;
template<typename T, typename... Ts>
void set_option(SyncSession& session, T&& t, Ts&&... ts)
{
set_option(std::forward<T>(t));
set_option(std::forward<Ts>(ts)...);
}
Response submit(Request&& req);
Response submit(const Method& m, const Url& url);
private:
bool connect(const std::string& host, int port, std::error_code& ec);
};
///
/// Asynchronous session
///
class API_EXPORT AsyncSession
: public BaseSession
, public std::enable_shared_from_this<AsyncSession>
{
public:
NO_COPY(AsyncSession);
AsyncSession(asio::io_context& io_context);
template<typename... Ts>
AsyncSession(asio::io_context& io_context, Ts&&... ts)
: AsyncSession(io_context)
{
set_option(std::forward<Ts>(ts)...);
}
// Move constructor
AsyncSession(AsyncSession&& rhs) noexcept;
/// Default destructor
~AsyncSession() override;
/// Move assignment
AsyncSession& operator=(AsyncSession&& rhs) noexcept;
template <typename T, typename... Ts>
void set_option(AsyncSession& session, T&& t, Ts&&... ts)
{
set_option(std::forward<T>(t));
set_option(std::forward<Ts>(ts)...);
}
void on_close(CloseHandler h);
void on_error(ErrorHandler h);
void on_response(ResponseHandler h);
void submit(Request&& req);
void submit(const Method& m, const Url& url);
private:
void connect(const std::string& host, int port);
void do_read();
void do_write();
void do_on_close();
void do_on_error(const std::error_code& ec);
void do_on_response(const Response& res);
CloseHandler _close_handler;
ErrorHandler _error_handler;
ResponseHandler _response_handler;
/// Buffer for incoming data.
asio::streambuf _in_buffer;
Request _request;
Response _response;
};
template <typename T>
void set_option(BaseSession& session, T&& t)
{
session.set_option(std::forward<T>(t));
}
template <typename T, typename... Ts>
void set_option(BaseSession& session, T&& t, Ts&&... ts)
{
set_option(session, std::forward<T>(t));
set_option(session, std::forward<Ts>(ts)...);
}
} // namespace http
} // namespace net
} // namespace orion
#endif // ORION_NET_HTTP_SESSION_H
| 20.926471 | 81 | 0.68283 |
03cfc74ca0b159108993aa5d4049e50dad5a4910 | 441 | h | C | packages/expo-dev-menu/vendored/react-native-reanimated/ios/native/REAIOSScheduler.h | AMSTKO/expo | 5290f1e1bce92297678578d33e7971e2ea9b7497 | [
"Apache-2.0",
"MIT"
] | 1 | 2022-03-04T17:41:50.000Z | 2022-03-04T17:41:50.000Z | packages/expo-dev-menu/vendored/react-native-reanimated/ios/native/REAIOSScheduler.h | AMSTKO/expo | 5290f1e1bce92297678578d33e7971e2ea9b7497 | [
"Apache-2.0",
"MIT"
] | 1 | 2021-11-15T17:39:36.000Z | 2021-11-15T17:39:36.000Z | packages/expo-dev-menu/vendored/react-native-reanimated/ios/native/REAIOSScheduler.h | AMSTKO/expo | 5290f1e1bce92297678578d33e7971e2ea9b7497 | [
"Apache-2.0",
"MIT"
] | 3 | 2021-11-11T12:26:42.000Z | 2022-03-16T17:48:58.000Z | #pragma once
#include <stdio.h>
#include "Scheduler.h"
#import <ReactCommon/CallInvoker.h>
#import <React/RCTUIManager.h>
namespace devmenureanimated
{
using namespace facebook;
using namespace react;
class REAIOSScheduler : public Scheduler {
public:
REAIOSScheduler(std::shared_ptr<CallInvoker> jsInvoker);
void scheduleOnUI(std::function<void()> job) override;
virtual ~REAIOSScheduler();
};
} // namespace devmenureanimated
| 20.045455 | 58 | 0.768707 |
03d01b880443d92443a77006e9cf90e9cd482aed | 42 | c | C | vis/tests/performance/uninitialized_variables/all_uninit.c | flix-/phasar | 85b30c329be1766136c8cbc6f925cb4fd1bafd27 | [
"BSL-1.0"
] | 581 | 2018-06-10T10:37:55.000Z | 2022-03-30T14:56:53.000Z | vis/tests/performance/uninitialized_variables/all_uninit.c | flix-/phasar | 85b30c329be1766136c8cbc6f925cb4fd1bafd27 | [
"BSL-1.0"
] | 172 | 2018-06-13T12:33:26.000Z | 2022-03-26T07:21:41.000Z | vis/tests/performance/uninitialized_variables/all_uninit.c | flix-/phasar | 85b30c329be1766136c8cbc6f925cb4fd1bafd27 | [
"BSL-1.0"
] | 137 | 2018-06-10T10:31:14.000Z | 2022-03-06T11:53:56.000Z | int main()
{
int a;
int b;
return 0;
}
| 6 | 10 | 0.52381 |
03d08800e61d11e889515b94889a2367fb4646a4 | 1,295 | h | C | System/Library/PrivateFrameworks/PrototypeToolsUI.framework/PTUISettingsController.h | zhangkn/iOS14Header | 4323e9459ed6f6f5504ecbea2710bfd6c3d7c946 | [
"MIT"
] | 1 | 2020-11-04T15:43:01.000Z | 2020-11-04T15:43:01.000Z | System/Library/PrivateFrameworks/PrototypeToolsUI.framework/PTUISettingsController.h | zhangkn/iOS14Header | 4323e9459ed6f6f5504ecbea2710bfd6c3d7c946 | [
"MIT"
] | null | null | null | System/Library/PrivateFrameworks/PrototypeToolsUI.framework/PTUISettingsController.h | zhangkn/iOS14Header | 4323e9459ed6f6f5504ecbea2710bfd6c3d7c946 | [
"MIT"
] | null | null | null | /*
* This header is generated by classdump-dyld 1.0
* on Sunday, September 27, 2020 at 12:26:03 PM Mountain Standard Time
* Operating System: Version 14.0 (Build 18A373)
* Image Source: /System/Library/PrivateFrameworks/PrototypeToolsUI.framework/PrototypeToolsUI
* classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by Elias Limneos.
*/
#import <UIKitCore/UINavigationController.h>
@class UIBarButtonItem;
@interface PTUISettingsController : UINavigationController {
UIBarButtonItem* _dismissButton;
}
@property (nonatomic,retain) UIBarButtonItem * dismissButton; //@synthesize dismissButton=_dismissButton - In the implementation block
-(void)px_performWithoutAnimations:(/*^block*/id)arg1 completionHandler:(/*^block*/id)arg2 ;
-(void)_pxswizzled_pushViewController:(id)arg1 animated:(BOOL)arg2 ;
-(BOOL)px_shouldPreventAnimations;
-(void)px_setShouldPreventAnimations:(BOOL)arg1 ;
-(id)initWithRootSettings:(id)arg1 ;
-(void)_dismiss;
-(UIBarButtonItem *)dismissButton;
-(void)setDismissButton:(UIBarButtonItem *)arg1 ;
-(void)pushViewController:(id)arg1 animated:(BOOL)arg2 ;
-(BOOL)_canShowWhileLocked;
-(id)initWithRootModuleController:(id)arg1 ;
-(id)_defaultDismissButton;
-(id)_initWithRootModule:(id)arg1 ;
-(void)_reloadWithRootModule:(id)arg1 ;
@end
| 35.972222 | 147 | 0.784556 |
03d3e1371e21489e3f48d6f1534eb3ca67410ad0 | 808 | h | C | headers/envz.h | mwichmann/lsb-buildenv | 7a7eb64b5960172e0032e7202aeb454e076880fa | [
"BSD-3-Clause"
] | null | null | null | headers/envz.h | mwichmann/lsb-buildenv | 7a7eb64b5960172e0032e7202aeb454e076880fa | [
"BSD-3-Clause"
] | null | null | null | headers/envz.h | mwichmann/lsb-buildenv | 7a7eb64b5960172e0032e7202aeb454e076880fa | [
"BSD-3-Clause"
] | null | null | null | #if (__LSB_VERSION__ >= 50 )
#ifndef _ENVZ_H_
#define _ENVZ_H_
#include <stddef.h>
#include <argz.h>
#ifdef __cplusplus
extern "C" {
#endif
/* Function prototypes */
extern error_t envz_add(char **envz, size_t * envz_len,
const char *name, const char *value);
extern char envz_entry(const char *envz, size_t envz_len,
const char *name);
extern char envz_get(const char *envz, size_t envz_len,
const char *name);
extern error_t envz_merge(char **envz, size_t * envz_len,
const char *envz2, size_t envz2_len,
int override);
extern void envz_remove(char **envz, size_t * envz_len,
const char *name);
extern void envz_strip(char **envz, size_t * envz_len);
#ifdef __cplusplus
}
#endif
#endif /* protection */
#endif /* LSB version */
| 24.484848 | 61 | 0.669554 |
03d427969743e40cd1ab8c8ab32c863d53188feb | 274 | h | C | Ptt/User/Member.h | winter901017/Ptt | 8a823362cca11cc794443dce9739cd3141c72989 | [
"FTL"
] | 1 | 2021-07-01T14:02:59.000Z | 2021-07-01T14:02:59.000Z | Ptt/User/Member.h | winter901017/Ptt | 8a823362cca11cc794443dce9739cd3141c72989 | [
"FTL"
] | null | null | null | Ptt/User/Member.h | winter901017/Ptt | 8a823362cca11cc794443dce9739cd3141c72989 | [
"FTL"
] | null | null | null | #pragma once
#ifndef MEMBER_H
#define MEMBER_H
#include "User.h"
#include <iostream>
#include <string>
#include <fstream>
#include <vector>
using namespace std;
class Member:public User
{
public:
Member(void)
{
Permission_level = 1;
}
};
#endif // !MEMBER_H
| 10.148148 | 24 | 0.689781 |