hexsha stringlengths 40 40 | size int64 5 1.05M | ext stringclasses 588
values | lang stringclasses 305
values | max_stars_repo_path stringlengths 3 363 | max_stars_repo_name stringlengths 5 118 | max_stars_repo_head_hexsha stringlengths 40 40 | 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:00:35 2022-03-31 23:43:49 ⌀ | max_stars_repo_stars_event_max_datetime stringdate 2015-01-01 12:37:38 2022-03-31 23:59:52 ⌀ | max_issues_repo_path stringlengths 3 363 | max_issues_repo_name stringlengths 5 118 | max_issues_repo_head_hexsha stringlengths 40 40 | 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 363 | max_forks_repo_name stringlengths 5 135 | max_forks_repo_head_hexsha stringlengths 40 40 | 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:02 2022-03-31 23:27:27 ⌀ | max_forks_repo_forks_event_max_datetime stringdate 2015-01-03 08:55:07 2022-03-31 23:59:24 ⌀ | content stringlengths 5 1.05M | avg_line_length float64 1.13 1.04M | max_line_length int64 1 1.05M | alphanum_fraction float64 0 1 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
4e9fd1b5ef88c06060b7406ae453d0c5fd19324a | 4,234 | h | C | qemu/include/qemu/fifo32.h | hyunjoy/scripts | 01114d3627730d695b5ebe61093c719744432ffa | [
"Apache-2.0"
] | 60 | 2020-10-14T07:11:48.000Z | 2022-02-14T23:00:51.000Z | qemu/include/qemu/fifo32.h | hyunjoy/scripts | 01114d3627730d695b5ebe61093c719744432ffa | [
"Apache-2.0"
] | 8 | 2020-10-19T02:17:19.000Z | 2022-01-15T05:52:46.000Z | qemu/include/qemu/fifo32.h | hyunjoy/scripts | 01114d3627730d695b5ebe61093c719744432ffa | [
"Apache-2.0"
] | 18 | 2022-03-19T04:41:04.000Z | 2022-03-31T03:32:12.000Z | /*
* Generic FIFO32 component, based on FIFO8.
*
* Copyright (c) 2016 Jean-Christophe Dubois
*
* 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.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see <http://www.gnu.org/licenses/>.
*/
#ifndef FIFO32_H
#define FIFO32_H
#include "qemu/fifo8.h"
typedef struct {
Fifo8 fifo;
} Fifo32;
/**
* fifo32_create:
* @fifo: struct Fifo32 to initialise with new FIFO
* @capacity: capacity of the newly created FIFO expressed in 32 bit words
*
* Create a FIFO of the specified size. Clients should call fifo32_destroy()
* when finished using the fifo. The FIFO is initially empty.
*/
static inline void fifo32_create(Fifo32 *fifo, uint32_t capacity)
{
fifo8_create(&fifo->fifo, capacity * sizeof(uint32_t));
}
/**
* fifo32_destroy:
* @fifo: FIFO to cleanup
*
* Cleanup a FIFO created with fifo32_create(). Frees memory created for FIFO
* storage. The FIFO is no longer usable after this has been called.
*/
static inline void fifo32_destroy(Fifo32 *fifo)
{
fifo8_destroy(&fifo->fifo);
}
/**
* fifo32_num_free:
* @fifo: FIFO to check
*
* Return the number of free uint32_t slots in the FIFO.
*
* Returns: Number of free 32 bit words.
*/
static inline uint32_t fifo32_num_free(Fifo32 *fifo)
{
return DIV_ROUND_UP(fifo8_num_free(&fifo->fifo), sizeof(uint32_t));
}
/**
* fifo32_num_used:
* @fifo: FIFO to check
*
* Return the number of used uint32_t slots in the FIFO.
*
* Returns: Number of used 32 bit words.
*/
static inline uint32_t fifo32_num_used(Fifo32 *fifo)
{
return DIV_ROUND_UP(fifo8_num_used(&fifo->fifo), sizeof(uint32_t));
}
/**
* fifo32_push:
* @fifo: FIFO to push to
* @data: 32 bits data word to push
*
* Push a 32 bits data word to the FIFO. Behaviour is undefined if the FIFO
* is full. Clients are responsible for checking for fullness using
* fifo32_is_full().
*/
static inline void fifo32_push(Fifo32 *fifo, uint32_t data)
{
int i;
for (i = 0; i < sizeof(data); i++) {
fifo8_push(&fifo->fifo, data & 0xff);
data >>= 8;
}
}
/**
* fifo32_push_all:
* @fifo: FIFO to push to
* @data: data to push
* @size: number of 32 bit words to push
*
* Push a 32 bit word array to the FIFO. Behaviour is undefined if the FIFO
* is full. Clients are responsible for checking the space left in the FIFO
* using fifo32_num_free().
*/
static inline void fifo32_push_all(Fifo32 *fifo, const uint32_t *data,
uint32_t num)
{
int i;
for (i = 0; i < num; i++) {
fifo32_push(fifo, data[i]);
}
}
/**
* fifo32_pop:
* @fifo: fifo to pop from
*
* Pop a 32 bits data word from the FIFO. Behaviour is undefined if the FIFO
* is empty. Clients are responsible for checking for emptiness using
* fifo32_is_empty().
*
* Returns: The popped 32 bits data word.
*/
static inline uint32_t fifo32_pop(Fifo32 *fifo)
{
uint32_t ret = 0;
int i;
for (i = 0; i < sizeof(uint32_t); i++) {
ret |= (fifo8_pop(&fifo->fifo) << (i * 8));
}
return ret;
}
/**
* There is no fifo32_pop_buf() because the data is not stored in the buffer
* as a set of native-order words.
*/
/**
* fifo32_reset:
* @fifo: FIFO to reset
*
* Reset a FIFO. All data is discarded and the FIFO is emptied.
*/
static inline void fifo32_reset(Fifo32 *fifo)
{
fifo8_reset(&fifo->fifo);
}
/**
* fifo32_is_empty:
* @fifo: FIFO to check
*
* Check if a FIFO is empty.
*
* Returns: True if the fifo is empty, false otherwise.
*/
static inline bool fifo32_is_empty(Fifo32 *fifo)
{
return fifo8_is_empty(&fifo->fifo);
}
/**
* fifo32_is_full:
* @fifo: FIFO to check
*
* Check if a FIFO is full.
*
* Returns: True if the fifo is full, false otherwise.
*/
static inline bool fifo32_is_full(Fifo32 *fifo)
{
return fifo8_num_free(&fifo->fifo) < sizeof(uint32_t);
}
#define VMSTATE_FIFO32(_field, _state) VMSTATE_FIFO8(_field.fifo, _state)
#endif /* FIFO32_H */
| 22.167539 | 77 | 0.674539 |
19a76847f3ed2f09505d96402d7bc21cfdd30771 | 3,613 | h | C | llbc/include/llbc/core/algo/RingBuffer.h | joe1545134/llbc | db460e4a35ba8c63190bf2376bbba68453b4ecc0 | [
"MIT"
] | 83 | 2015-11-10T09:52:56.000Z | 2022-01-12T11:53:01.000Z | llbc/include/llbc/core/algo/RingBuffer.h | joe1545134/llbc | db460e4a35ba8c63190bf2376bbba68453b4ecc0 | [
"MIT"
] | 30 | 2017-09-30T07:43:20.000Z | 2022-01-23T13:18:48.000Z | llbc/include/llbc/core/algo/RingBuffer.h | caochunxi/llbc | 2ff4af937f1635be67a7e24602d0a3e87c708ba7 | [
"MIT"
] | 34 | 2015-11-14T12:37:44.000Z | 2021-12-16T02:38:36.000Z | // The MIT License (MIT)
// Copyright (c) 2013 lailongwei<lailongwei@126.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#ifndef __LLBC_CORE_ALGO_RING_BUFFER_H__
#define __LLBC_CORE_ALGO_RING_BUFFER_H__
#include "llbc/common/Common.h"
__LLBC_NS_BEGIN
/**
* \brief The basic ring buffer data structure implement.
*/
template <typename ElemType>
class LLBC_RingBuffer
{
public:
/**
* Constructor.
* @param[in] cap - default capacity.
*/
explicit LLBC_RingBuffer(size_t cap = LLBC_CFG_CORE_ALGO_RING_BUFFER_DEFAULT_CAP);
~LLBC_RingBuffer();
public:
/**
* Push element to ring buffer.
* Note: If ring buffer reach to limit, will auto recapacity.
* @param[in] elem - the element.
*/
void Push(const ElemType &elem);
/**
* Pop element from ring buffer.
* Warning: Do not pop empty ring buffer, the behavior is not defined!
* @return ElemType - the element.
*/
ElemType Pop();
/**
* Get front element.
* @return ElemType & - the front element reference.
*/
ElemType &Front();
/**
* Get front element.
* @return const ElemType & - the front element const reference.
*/
const ElemType &Front() const;
/**
* Get front element.
* @return ElemType & - the front element reference.
*/
ElemType &Tail();
/**
* Get front element.
* @return const ElemType & - the front element const reference.
*/
const ElemType &Tail() const;
/**
* Get ring buffer size(used capacity).
* @return size_t - the buffer size.
*/
size_t GetSize() const;
/**
* Get ring buffer capacity.
* @return size_t - the ring bufer capacity.
*/
size_t GetCapacity() const;
/**
* Adjust ring buffer capacity.
* @param[in] newCap - the new capacity.
*/
void ReCapacity(size_t newCap);
public:
/**
* Check ring buffer is full or not.
* @return bool - return true if full, otherwise return false.
*/
bool IsFull() const;
/**
* Check ring buffer is empty or not.
* @return bool - return true if empty, otherwise return false.
*/
bool IsEmpty() const;
/**
* Clear ring buffer.
*/
void Clear();
/**
* Disable assignment.
*/
LLBC_DISABLE_ASSIGNMENT(LLBC_RingBuffer);
private:
ElemType *_elems;
size_t _capacity;
size_t _front;
size_t _tail;
bool _full;
};
__LLBC_NS_END
#include "llbc/core/algo/RingBufferImpl.h"
#endif // !__LLBC_CORE_ALGO_RING_BUFFER_H__
| 26.762963 | 86 | 0.6615 |
d7a1d3e69ee37bb588c922da65db4f211a487d13 | 567 | h | C | include/tile/Layout.h | rbtnn/tile | 8b0b896b6e69128e68a4b134d7b0fbf617894fb1 | [
"MIT"
] | 1 | 2015-01-08T21:58:32.000Z | 2015-01-08T21:58:32.000Z | include/tile/Layout.h | rbtnn/tile | 8b0b896b6e69128e68a4b134d7b0fbf617894fb1 | [
"MIT"
] | null | null | null | include/tile/Layout.h | rbtnn/tile | 8b0b896b6e69128e68a4b134d7b0fbf617894fb1 | [
"MIT"
] | null | null | null |
#ifndef TILE_LAYOUT_H
#define TILE_LAYOUT_H
#include "./common_headers.h"
namespace Tile{
class Layout{
public:
typedef std::function<void(std::deque<HWND> const& hwnds_, long const& width_, long const& height_)> ArrangeFunctionSTL;
typedef void (* ArrangeFuncRef)(std::deque<HWND> const&, long const&, long const&);
Layout(std::string, ArrangeFunctionSTL);
std::string get_layout_name() const;
void arrange(std::deque<HWND> const&);
private:
std::string m_layout_name;
ArrangeFunctionSTL m_f;
};
}
#endif
| 22.68 | 126 | 0.686067 |
c758ca1244d76372fc4a84867ed011a371795522 | 302 | h | C | src/Log.h | abhishekkumarXD/Cherno-CPP | 15742c32ba0b65de5c616d261eeb0d2c084a68ec | [
"Apache-2.0"
] | 1 | 2022-02-07T13:25:18.000Z | 2022-02-07T13:25:18.000Z | src/Log.h | abhishekkumarXD/Cherno-CPP | 15742c32ba0b65de5c616d261eeb0d2c084a68ec | [
"Apache-2.0"
] | null | null | null | src/Log.h | abhishekkumarXD/Cherno-CPP | 15742c32ba0b65de5c616d261eeb0d2c084a68ec | [
"Apache-2.0"
] | null | null | null |
// pragma once is a non-standard but widely supported preprocessor directive
// designed to cause the current source file to be included only once in a
// single compilation.
#include <iostream>
void InitLog();
void Log(const char* message)
{
std::cout << message << std::endl;
}
| 21.571429 | 77 | 0.688742 |
67b451b18f103588405c1e707f2337bd10f696ee | 295 | h | C | vpr7_x2p/vpr/SRC/place/place_stats.h | ganeshgore/OpenFPGA | e2e4a9287ddd3f88ee6d436fa4b7e616bcd20390 | [
"MIT"
] | 31 | 2016-02-15T02:57:28.000Z | 2021-06-02T10:40:25.000Z | vpr7_x2p/vpr/SRC/place/place_stats.h | ganeshgore/OpenFPGA | e2e4a9287ddd3f88ee6d436fa4b7e616bcd20390 | [
"MIT"
] | null | null | null | vpr7_x2p/vpr/SRC/place/place_stats.h | ganeshgore/OpenFPGA | e2e4a9287ddd3f88ee6d436fa4b7e616bcd20390 | [
"MIT"
] | 6 | 2017-02-08T21:51:51.000Z | 2021-06-02T10:40:40.000Z | #ifdef PRINT_REL_POS_DISTR
void print_relative_pos_distr(void);
/* Prints out the probability distribution of the relative locations of *
* input pins on a net -- i.e. simulates 2-point net length probability *
* distribution. */
#endif
| 36.875 | 74 | 0.623729 |
c531164e5ab541e81dc612ad05ae1556f4adfb98 | 1,667 | h | C | src/libsgm_wrapper.h | michaelnguyen11/libSGM | f966b79f0653ea54faf8704b50cef39586c7a3ae | [
"Apache-2.0"
] | null | null | null | src/libsgm_wrapper.h | michaelnguyen11/libSGM | f966b79f0653ea54faf8704b50cef39586c7a3ae | [
"Apache-2.0"
] | null | null | null | src/libsgm_wrapper.h | michaelnguyen11/libSGM | f966b79f0653ea54faf8704b50cef39586c7a3ae | [
"Apache-2.0"
] | null | null | null | #ifndef __LIBSGM_WRAPPER_H__
#define __LIBSGM_WRAPPER_H__
#include "libsgm.h"
#include <memory>
namespace sgm {
/**
* @brief LibSGMWrapper class which is wrapper for sgm::StereoSGM.
*/
class LibSGMWrapper {
public:
/**
* @param numDisparity Maximum disparity minus minimum disparity.
* @param P1 Penalty on the disparity change by plus or minus 1 between nieghbor pixels.
* @param P2 Penalty on the disparity change by more than 1 between neighbor pixels.
* @param uniquenessRatio Margin in ratio by which the best cost function value should be at least second one.
* @param subpixel Disparity value has 4 fractional bits if subpixel option is enabled.
* @param pathType Number of scanlines used in cost aggregation.
* @param minDisparity Minimum possible disparity value.
* @param lrMaxDiff Acceptable difference pixels which is used in LR check consistency. LR check consistency will be disabled if this value is set to negative.
*/
LibSGMWrapper(int numDisparity = 128, int P1 = 10, int P2 = 120, float uniquenessRatio = 0.95f,
bool subpixel = false, PathType pathType = PathType::SCAN_8PATH, int minDisparity = 0, int lrMaxDiff = 1);
~LibSGMWrapper();
int getNumDisparities() const;
int getP1() const;
int getP2() const;
float getUniquenessRatio() const;
bool hasSubpixel() const;
PathType getPathType() const;
int getMinDisparity() const;
int getLrMaxDiff() const;
int getInvalidDisparity() const;
private:
struct Creator;
std::unique_ptr<sgm::StereoSGM> sgm_;
int numDisparity_;
sgm::StereoSGM::Parameters param_;
std::unique_ptr<Creator> prev_;
};
}
#endif // __LIBSGM_WRAPPER_H__
| 35.468085 | 161 | 0.743251 |
41b6ee5459ab35c6502c7819078a686c28da9310 | 3,365 | h | C | unit.h | YAost/Nature-simulator | 3c48a0268f758b0e66105ba5a58a1c85d7af77ac | [
"MIT"
] | null | null | null | unit.h | YAost/Nature-simulator | 3c48a0268f758b0e66105ba5a58a1c85d7af77ac | [
"MIT"
] | null | null | null | unit.h | YAost/Nature-simulator | 3c48a0268f758b0e66105ba5a58a1c85d7af77ac | [
"MIT"
] | null | null | null | #ifndef UNIT_H
#define UNIT_H
#include <SFML/Graphics.hpp>
#include <math.h>
const double pi = atan(1.0)*4;
class Unit {
public:
Unit();
bool is_alive();
void draw(sf::RenderWindow &w); // отрисовка объекта и его поведения
void calculate(); // расчёт unitVector, deg
void angle(); // поворот объекта
void coll(); // коллизия
void gen(int, float, float, float); // генерация начальных данных извне (ТАК КАК НЕ РАБОТАЕТ РАНДОМ)
sf::Vector2f pos(); // возвращает текущее положение объекта
void food(int , sf::Vector2f); // устанавливает параметры
bool search_food(); // возвращает инфу, ищет ли объект еду в данный момент
bool search_over(); // возвращает инфу, съел ли объект еду и "закончил" поиск
void set_over(); // сбрасывает флаг окончания поедания
float f_lenght(sf::Vector2f, sf::Vector2f);
int retFoodId(); // возвращает ID съедаемого
int retUnitHp(); // возвращает HP объекта
void setUnitHp(int); // устанавливает HP объекта на основе HP еды
bool retUnitParent(); // является ли объект родителем
void setParentTrue(); // делает объект родителем
int retUnitId(); // возвращает ID объекта
bool retMakeChild(); // создаётся ли ребенок
bool retMakeChildOver(); // закончилось ли создание
void setMakeChildOver(); // сбрасывает флаг процесса рождения
void child(int , sf::Vector2f);
int getPartnerId();
bool isUnitOld();
void RollBack(float, float, bool);
private:
sf::CircleShape col;
int id; // идентификатор
bool life; // жив ли вообще
bool parent; // является ли родителем
int partner_id; // id мужа / жены
bool mkchld; // флаг создания ребенка
bool mkvr; // флаг окончания создания ребенка
int hp; // текущее значение здоровья
int max_hp; // максимальное значение здоровья
float w, h; // размеры объекта (нужно для коллизии)
sf::RectangleShape obj; // объект из библиотеки SFML прямоугольной формы
sf::Texture texture; // текстура
float tx, ty; // координаты целевой точки
float ox, oy; // предыдущая координата
float max_speed;// максимальная скорость
sf::Vector2f direction; // вектор до целевой точки
float lenght; // расстояние до точки
sf::Vector2f unitVector; // единичный вектор для перемещения до точки в секунду, есть direction / lenght
float odeg, deg; // угол поворота объекта (старый и новый)
bool crsz; // флаг, обозначающий переход градуса поворота через ноль (угол поворота от 0 до 360)
float unitd; // градус поворота в секунду, постоянный
sf::Clock global_clock; // инициализация SFML часов
float passed_time; // учет пройденного времени
int food_id; // идентификатор цели "покушать"
bool srchfd; // флаг поиска еды (нацеливание)
bool srchvr; // флаг окончания поиска еды
float food_lenght; // возможное расстояние до цели "покушать"
sf::Vector2f food_xy; // координаты еды
sf::Vector2f partner_xy;
bool rlbck;
};
#endif
| 47.394366 | 117 | 0.616642 |
5105edb4eef53f9e4546cd2172c53d7344b51dfb | 2,646 | c | C | src/util.c | freedan42x/resources-game | 5db35e1e23dbc17310caf9f125533fccd1fb2e5c | [
"MIT"
] | null | null | null | src/util.c | freedan42x/resources-game | 5db35e1e23dbc17310caf9f125533fccd1fb2e5c | [
"MIT"
] | null | null | null | src/util.c | freedan42x/resources-game | 5db35e1e23dbc17310caf9f125533fccd1fb2e5c | [
"MIT"
] | null | null | null | #include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <termios.h>
#include <unistd.h>
#include <math.h>
#include <sys/ioctl.h>
#include "util.h"
void clear(void)
{
printf("\e[1;1H\e[2J");
}
int rand_range(int min, int max)
{
return rand() % (max + 1 - min) + min;
}
char *progress_bar(int width, double cur, double total)
{
char *buf = malloc(1024);
char *bar_buf = malloc(1024);
int prog_width = cur * width / total;
for (int i = 0; i < width; i++) {
strcat(bar_buf, (i < prog_width) ? "█" : "░");
}
sprintf(buf, "%s", bar_buf);
return buf;
}
static struct winsize w;
int term_width(void)
{
ioctl(STDOUT_FILENO, TIOCGWINSZ, &w);
return w.ws_col;
}
int term_height(void)
{
ioctl(STDOUT_FILENO, TIOCGWINSZ, &w);
return w.ws_row;
}
void gotoxy(int x, int y)
{
printf("\033[%d;%dH", y, x);
}
char *center(int len)
{
char *buf = malloc(1024);
sprintf(buf, "%*s", (term_width() - len) / 2, "");
return buf;
}
int parse_reward(Reward reward)
{
if (!reward.present) {
return 0;
}
switch (reward.type) {
case REWARD_VALUE:
return reward.value;
case REWARD_RANGE:
return rand_range(reward.range.min, reward.range.max);
default:
fprintf(stderr, "parse_reward: Unreachable");
exit(1);
}
}
void update_level(Game_State *game)
{
while (game->cur_exp >= game->need_exp) {
game->cur_exp -= game->need_exp;
game->lvl++;
game->need_exp = game->need_exp + pow(game->need_exp, 3.0 / 4.0) + log2(game->need_exp) + game->lvl;
}
}
void init_term(struct termios *term)
{
srand(time(NULL));
printf(HIDE_CURSOR);
tcgetattr(STDIN_FILENO, term);
struct termios new_term;
memcpy(&new_term, term, sizeof new_term);
new_term.c_lflag &= ~ICANON;
tcsetattr(STDIN_FILENO, TCSANOW, &new_term);
}
void exit_term(struct termios *term)
{
printf(SHOW_CURSOR);
tcsetattr(STDIN_FILENO, TCSANOW, term);
}
void unreachable(struct termios *term, char *msg)
{
fprintf(stderr, "%s", msg);
exit_term(term);
exit(1);
}
int kbhit() {
setbuf(stdin, NULL);
int bytes;
ioctl(STDIN_FILENO, FIONREAD, &bytes);
return bytes;
}
int getch(void) {
int c = 0;
struct termios org_opts, new_opts;
tcgetattr(STDIN_FILENO, &org_opts);
memcpy(&new_opts, &org_opts, sizeof new_opts);
new_opts.c_lflag &= ~(ICANON | ECHO | ECHOE | ECHOK | ECHONL | ECHOPRT | ECHOKE | ICRNL);
tcsetattr(STDIN_FILENO, TCSANOW, &new_opts);
if (kbhit()) {
c = getchar();
if (c == 27) {
int d = getchar();
int e = getchar();
c = c * 10000 + d * 100 + e;
}
tcsetattr(STDIN_FILENO, TCSANOW, &org_opts);
}
return c;
}
| 18.375 | 104 | 0.633409 |
5f4d403b48aac19a72793cda2d97d94fe13ecaef | 1,729 | h | C | Pseudo-Drifter/SystemManager.h | WerenskjoldH/Pseudo-Drifter | e9b09baa540372276608270dbfa14d5dd7e72639 | [
"Unlicense"
] | 1 | 2019-11-22T15:56:56.000Z | 2019-11-22T15:56:56.000Z | Pseudo-Drifter/SystemManager.h | WerenskjoldH/Pseudo-Drifter | e9b09baa540372276608270dbfa14d5dd7e72639 | [
"Unlicense"
] | null | null | null | Pseudo-Drifter/SystemManager.h | WerenskjoldH/Pseudo-Drifter | e9b09baa540372276608270dbfa14d5dd7e72639 | [
"Unlicense"
] | null | null | null | #ifndef SYSTEM_MANAGER_H
#define SYSTEM_MANAGER_H
/*
Description: This file contains all declarations and definitions pertaining to the system manager class
This class manages all systems
To-Do:
* Refactoring
* Storing entities with the systems in a vector and using entity signatures is probably a good idea, this current implementation is sloppy
*/
#include <memory>
#include <unordered_map>
#include <SDL.h>
#include "ConsoleColorer.h"
#include "System.h"
class SystemManager
{
private:
std::unordered_map<const char*, std::shared_ptr<System>> systems;
EntityManager* entityManager = nullptr;
public:
SystemManager(EntityManager* entityManager) : entityManager{ entityManager } {};
template <class T>
std::shared_ptr<T> AddSystem()
{
const char* systemName = typeid(T).name();
if (systems.find(systemName) != systems.end())
{
WRITE_CONSOLE_WARNING("SYSTEM MANAGER", "WARNING", "Attempted to add system a second time");
return nullptr;
}
auto system = std::make_shared<T>();
system->AssignEntityManager(entityManager);
systems[systemName] = std::static_pointer_cast<System>(system);
return system;
}
template <class T>
std::shared_ptr<System> GetSystem()
{
const char* systemName = typeid(T).name();
if (systems.find(systemName) == systems.end())
{
WRITE_CONSOLE_WARNING("SYSTEM MANAGER", "WARNING", "Attempted to get system that hasn't been added");
return nullptr;
}
return systems[systemName];
}
void Update(float dt)
{
for (auto& kvPair : systems)
{
kvPair.second->Update(dt);
}
}
void Draw(SDL_Renderer* renderer, const Camera& camera)
{
for (auto& kvPair : systems)
{
kvPair.second->Draw(renderer, camera);
}
}
};
#endif | 21.6125 | 140 | 0.714864 |
247e5fab095c686ed65b257afea1523be93897f8 | 2,561 | h | C | applications/physbam/physbam-lib/Public_Library/PhysBAM_Fluids/PhysBAM_Incompressible/Boundaries/BOUNDARY_MAC_GRID_SOLID_WALL_SLIP.h | schinmayee/nimbus | 170cd15e24a7a88243a6ea80aabadc0fc0e6e177 | [
"BSD-3-Clause"
] | 20 | 2017-07-03T19:09:09.000Z | 2021-09-10T02:53:56.000Z | applications/physbam/physbam-lib/Public_Library/PhysBAM_Fluids/PhysBAM_Incompressible/Boundaries/BOUNDARY_MAC_GRID_SOLID_WALL_SLIP.h | schinmayee/nimbus | 170cd15e24a7a88243a6ea80aabadc0fc0e6e177 | [
"BSD-3-Clause"
] | null | null | null | applications/physbam/physbam-lib/Public_Library/PhysBAM_Fluids/PhysBAM_Incompressible/Boundaries/BOUNDARY_MAC_GRID_SOLID_WALL_SLIP.h | schinmayee/nimbus | 170cd15e24a7a88243a6ea80aabadc0fc0e6e177 | [
"BSD-3-Clause"
] | 9 | 2017-09-17T02:05:06.000Z | 2020-01-31T00:12:01.000Z | //#####################################################################
// Copyright 2005-2006, Eran Guendelman, Geoffrey Irving.
// This file is part of PhysBAM whose distribution is governed by the license contained in the accompanying file PHYSBAM_COPYRIGHT.txt.
//#####################################################################
// Class BOUNDARY_MAC_GRID_SOLID_WALL_SLIP
//#####################################################################
#ifndef __BOUNDARY_MAC_GRID_SOLID_WALL_SLIP__
#define __BOUNDARY_MAC_GRID_SOLID_WALL_SLIP__
#include <PhysBAM_Tools/Grids_Uniform/UNIFORM_GRID_ITERATOR_FACE.h>
#include <PhysBAM_Tools/Grids_Uniform/UNIFORM_GRID_ITERATOR_NODE.h>
#include <PhysBAM_Tools/Grids_Uniform_Boundaries/BOUNDARY_UNIFORM.h>
#include <PhysBAM_Tools/Log/DEBUG_UTILITIES.h>
namespace PhysBAM{
template<class T_GRID>
class BOUNDARY_MAC_GRID_SOLID_WALL_SLIP:public BOUNDARY_UNIFORM<T_GRID,typename T_GRID::SCALAR>
{
typedef typename T_GRID::VECTOR_T TV;typedef typename TV::SCALAR T;typedef typename T_GRID::VECTOR_INT TV_INT;
typedef VECTOR<bool,2> TV_BOOL2;typedef VECTOR<TV_BOOL2,T_GRID::dimension> TV_SIDES;typedef typename GRID_ARRAYS_POLICY<T_GRID>::ARRAYS_SCALAR T_ARRAYS_SCALAR;
typedef typename GRID_ARRAYS_POLICY<T_GRID>::FACE_ARRAYS T_FACE_ARRAYS_SCALAR;typedef typename T_GRID::NODE_ITERATOR NODE_ITERATOR;typedef typename T_GRID::FACE_ITERATOR FACE_ITERATOR;
typedef typename GRID_ARRAYS_POLICY<T_GRID>::ARRAYS_BASE T_ARRAYS_BASE;
public:
typedef BOUNDARY_UNIFORM<T_GRID,T> BASE;
using BASE::Set_Constant_Extrapolation;using BASE::Constant_Extrapolation;
const T_ARRAYS_SCALAR* phi;
BOUNDARY_MAC_GRID_SOLID_WALL_SLIP(const TV_SIDES& constant_extrapolation=TV_SIDES());
~BOUNDARY_MAC_GRID_SOLID_WALL_SLIP();
void Set_Phi(T_ARRAYS_SCALAR& phi_input)
{phi=&phi_input;}
//#####################################################################
void Fill_Ghost_Cells_Face(const T_GRID& grid,const T_FACE_ARRAYS_SCALAR& u,T_FACE_ARRAYS_SCALAR& u_ghost,const T time,const int number_of_ghost_cells=3) PHYSBAM_OVERRIDE;
void Apply_Boundary_Condition_Face(const T_GRID& grid,T_FACE_ARRAYS_SCALAR& u,const T time) PHYSBAM_OVERRIDE;
void Reflect_Single_Ghost_Region(const int face_axis,const T_GRID& face_grid,T_ARRAYS_BASE& u_ghost_component,const int side,const RANGE<TV_INT>& region);
protected:
void Zero_Single_Boundary_Side(const T_GRID& grid,T_FACE_ARRAYS_SCALAR& u,const int side);
//#####################################################################
};
}
#endif
| 56.911111 | 188 | 0.714565 |
9a0a0602f42f90f62eac00436a6e638d2b04b3d9 | 969 | h | C | include/MazeImage++/MazeImage++.h | joshuainovero/Maze-Image-Generator | b913c97fa92a80c29befae32cd1cbcc350acb12a | [
"MIT"
] | null | null | null | include/MazeImage++/MazeImage++.h | joshuainovero/Maze-Image-Generator | b913c97fa92a80c29befae32cd1cbcc350acb12a | [
"MIT"
] | null | null | null | include/MazeImage++/MazeImage++.h | joshuainovero/Maze-Image-Generator | b913c97fa92a80c29befae32cd1cbcc350acb12a | [
"MIT"
] | null | null | null | /*****************************************************************************
*
* MazeImage++ - A library that generates maze images
* Copyright (C) - 2021 Joshua Inovero (joshinovero@gmail.com)
*
* File: MazeImage++.h
* This file is the main include header of the library
*
* ou may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the LICENSE file.
*
* 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 acknowledgment
* in the product documentation would be appreciated but is not required.
*
*****************************************************************************/
#ifndef MAZEIMAGEPLUSPLUS_H
#define MAZEIMAGEPLUSPLUS_H
#include <MazeImage++/utils/MazeImgGenerator.h>
#endif // MAZEIMAGEPLUSPLUS_H | 38.76 | 79 | 0.622291 |
7ad878957e553ec94dff6fd9a6938a009cb3d85a | 1,454 | c | C | src/hashmap.c | ryanisaacg/data-structures | 70e16715ec5bdd8f90709f7aacd0911a4c3626c7 | [
"MIT"
] | null | null | null | src/hashmap.c | ryanisaacg/data-structures | 70e16715ec5bdd8f90709f7aacd0911a4c3626c7 | [
"MIT"
] | null | null | null | src/hashmap.c | ryanisaacg/data-structures | 70e16715ec5bdd8f90709f7aacd0911a4c3626c7 | [
"MIT"
] | null | null | null | #include "hashmap.h"
#include <stdbool.h>
#include "linked_list.h"
#include "util.h"
static int get_hash(int key);
static bool void_ptr_equals(void *a, void *b);
static bool void_ptr_equals(void *a, void *b) {
return a == b;
}
HashMap *hm_new() {
HashMap *map = new(map);
map->eq = &void_ptr_equals;
map->keys = al_new(sizeof(void*));
for(int i = 0; i < HASHMAP_ENTRY_LENGTH; i++)
map->entries[i].head = map->entries[i].tail = NULL;
return map;
}
HashMap *hm_new_eqfunc(bool (*eq)(void*, void*)) {
HashMap *map = hm_new();
map->eq = eq;
return map;
}
void hm_put(HashMap *map, int hash, void *key, void *value) {
int index = get_hash(hash);
HashEntry *entry = new(entry);
entry->hash = hash;
entry->key = key;
entry->value = value;
al_add(&map->keys, key);
ll_add_last(&(map->entries[index]), entry);
}
void *hm_get(HashMap *map, int hash, void *key) {
int index = get_hash(hash);
LinkedList data = map->entries[index];
LinkedIterator iterator = ll_iter_head(&data);
while(ll_iter_has_next(&iterator)) {
HashEntry *entry = ll_iter_next(&iterator);
if(entry->hash == hash && map->eq(entry->key, key)) {
return entry->value;
}
}
return NULL;
}
ArrayList hm_get_keys(HashMap *map) {
return map->keys;
}
bool hm_has(HashMap *map, int hash, void *key){
return hm_get(map, hash, key) != NULL;
}
static int get_hash(int key) {
return abs(key) % HASHMAP_ENTRY_LENGTH;
}
void hm_destroy(HashMap *map) {
free(map);
}
| 22.030303 | 61 | 0.669876 |
a3ec874dd70e6ac1c965974469412a70890d23bb | 628 | h | C | src/multiprocessing/util.h | AvivShabtay/Linux-OS-Development | 4aa0c776670aee92c1f0e633950446f027557760 | [
"MIT"
] | 1 | 2020-01-25T13:14:41.000Z | 2020-01-25T13:14:41.000Z | src/multiprocessing/util.h | AvivShabtay/Linux-OS-Development | 4aa0c776670aee92c1f0e633950446f027557760 | [
"MIT"
] | null | null | null | src/multiprocessing/util.h | AvivShabtay/Linux-OS-Development | 4aa0c776670aee92c1f0e633950446f027557760 | [
"MIT"
] | null | null | null | /*
* util.h
*
* Created on: May 14, 2019
* Author: aviv
*/
#ifndef UTIL_H_
#define UTIL_H_
#include <string.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include "matrix.h"
#define NUM_OF_CHILDREN 3
#define CHILD_PROGRAM "./child"
#define READ_FROM_PIPE 0
#define WRITE_TO_PIPE 1
#define CORRECT_RESULT 3
char** createFilesFromArgs(int argc, char* argv[]);
int writeToChildren(int* childrenPipes[], matrix_t* data, size_t size);
int readFromChildren(int* parentPipe, int* result, char* buffer, size_t size);
void readMatrixFromTerminal(matrix_t* mat);
void cleanTerminal();
#endif /* UTIL_H_ */
| 20.933333 | 78 | 0.727707 |
435d6e340b5fc424534abed8819a802116be6484 | 1,206 | h | C | include/ncine/AudioStreamPlayer.h | ValtoGameEngines/nCine-Engine | 27869d762cd7cd668c2045bde99e743452444cb3 | [
"MIT"
] | 1 | 2020-10-01T16:05:11.000Z | 2020-10-01T16:05:11.000Z | include/ncine/AudioStreamPlayer.h | mat3019/nCine | 27869d762cd7cd668c2045bde99e743452444cb3 | [
"MIT"
] | null | null | null | include/ncine/AudioStreamPlayer.h | mat3019/nCine | 27869d762cd7cd668c2045bde99e743452444cb3 | [
"MIT"
] | 1 | 2020-06-29T08:06:11.000Z | 2020-06-29T08:06:11.000Z | #ifndef CLASS_NCINE_AUDIOSTREAMPLAYER
#define CLASS_NCINE_AUDIOSTREAMPLAYER
#include "common_defines.h"
#include "IAudioPlayer.h"
#include "AudioStream.h"
namespace ncine {
/// Audio stream player class
class DLL_PUBLIC AudioStreamPlayer : public IAudioPlayer
{
public:
/// A constructor creating a player from a file
explicit AudioStreamPlayer(const char *filename);
~AudioStreamPlayer() override;
inline unsigned int bufferId() const override { return audioStream_.bufferId(); }
inline int numChannels() const override { return audioStream_.numChannels(); }
inline int frequency() const override { return audioStream_.frequency(); }
unsigned long bufferSize() const override { return audioStream_.bufferSize(); }
void play() override;
void pause() override;
void stop() override;
/// Updates the player state and the stream buffer queue
void updateState() override;
inline static ObjectType sType() { return ObjectType::AUDIOSTREAM_PLAYER; }
private:
AudioStream audioStream_;
/// Deleted copy constructor
AudioStreamPlayer(const AudioStreamPlayer &) = delete;
/// Deleted assignment operator
AudioStreamPlayer &operator=(const AudioStreamPlayer &) = delete;
};
}
#endif
| 27.409091 | 82 | 0.771144 |
9e2c1d274804848a4ba687ceb30bd42d542aeb01 | 245 | h | C | Extern/CAESolver/CAE_h/mem4nodecrosssection.h | weikm/sandcarSimulation2 | fe499d0a3289c0ac1acce69c7dc78d8ce1b2708a | [
"Apache-2.0"
] | null | null | null | Extern/CAESolver/CAE_h/mem4nodecrosssection.h | weikm/sandcarSimulation2 | fe499d0a3289c0ac1acce69c7dc78d8ce1b2708a | [
"Apache-2.0"
] | null | null | null | Extern/CAESolver/CAE_h/mem4nodecrosssection.h | weikm/sandcarSimulation2 | fe499d0a3289c0ac1acce69c7dc78d8ce1b2708a | [
"Apache-2.0"
] | null | null | null | #pragma once
#include"baseshellsection.h"
class Membrance4NodeCrossSection:public BaseShellCrossSection
{
__host__ __device__ virtual void computeHourglassForce() override;
__host__ __device__ virtual void computeInternalForce() override;
}; | 27.222222 | 67 | 0.844898 |
7f3a5474ea94892598e11a90b3e0b97c13e21d2e | 12,597 | h | C | external/highway/hwy/highway.h | geenen124/iresearch | f89902a156619429f9e8df94bd7eea5a78579dbc | [
"Apache-2.0"
] | 12,278 | 2015-01-29T17:11:33.000Z | 2022-03-31T21:12:00.000Z | external/highway/hwy/highway.h | geenen124/iresearch | f89902a156619429f9e8df94bd7eea5a78579dbc | [
"Apache-2.0"
] | 9,469 | 2015-01-30T05:33:07.000Z | 2022-03-31T16:17:21.000Z | external/highway/hwy/highway.h | geenen124/iresearch | f89902a156619429f9e8df94bd7eea5a78579dbc | [
"Apache-2.0"
] | 892 | 2015-01-29T16:26:19.000Z | 2022-03-20T07:44:30.000Z | // Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// This include guard is checked by foreach_target, so avoid the usual _H_
// suffix to prevent copybara from renaming it. NOTE: ops/*-inl.h are included
// after/outside this include guard.
#ifndef HWY_HIGHWAY_INCLUDED
#define HWY_HIGHWAY_INCLUDED
// Main header required before using vector types.
#include "hwy/base.h"
#include "hwy/targets.h"
namespace hwy {
// API version (https://semver.org/)
#define HWY_MAJOR 0
#define HWY_MINOR 11
#define HWY_PATCH 1
//------------------------------------------------------------------------------
// Shorthand for descriptors (defined in shared-inl.h) used to select overloads.
// Because Highway functions take descriptor and/or vector arguments, ADL finds
// these functions without requiring users in project::HWY_NAMESPACE to
// qualify Highway functions with hwy::HWY_NAMESPACE. However, ADL rules for
// templates require `using hwy::HWY_NAMESPACE::ShiftLeft;` etc. declarations.
// HWY_FULL(T[,LMUL=1]) is a native vector/group. LMUL is the number of
// registers in the group, and is ignored on targets that do not support groups.
#define HWY_FULL1(T) hwy::HWY_NAMESPACE::Simd<T, HWY_LANES(T)>
#define HWY_3TH_ARG(arg1, arg2, arg3, ...) arg3
// Workaround for MSVC grouping __VA_ARGS__ into a single argument
#define HWY_FULL_RECOMPOSER(args_with_paren) HWY_3TH_ARG args_with_paren
// Trailing comma avoids -pedantic false alarm
#define HWY_CHOOSE_FULL(...) \
HWY_FULL_RECOMPOSER((__VA_ARGS__, HWY_FULL2, HWY_FULL1, ))
#define HWY_FULL(...) HWY_CHOOSE_FULL(__VA_ARGS__())(__VA_ARGS__)
// Vector of up to MAX_N lanes.
#define HWY_CAPPED(T, MAX_N) \
hwy::HWY_NAMESPACE::Simd<T, HWY_MIN(MAX_N, HWY_LANES(T))>
//------------------------------------------------------------------------------
// Export user functions for static/dynamic dispatch
// Evaluates to 0 inside a translation unit if it is generating anything but the
// static target (the last one if multiple targets are enabled). Used to prevent
// redefinitions of HWY_EXPORT. Unless foreach_target.h is included, we only
// compile once anyway, so this is 1 unless it is or has been included.
#ifndef HWY_ONCE
#define HWY_ONCE 1
#endif
// HWY_STATIC_DISPATCH(FUNC_NAME) is the namespace-qualified FUNC_NAME for
// HWY_STATIC_TARGET (the only defined namespace unless HWY_TARGET_INCLUDE is
// defined), and can be used to deduce the return type of Choose*.
#if HWY_STATIC_TARGET == HWY_SCALAR
#define HWY_STATIC_DISPATCH(FUNC_NAME) N_SCALAR::FUNC_NAME
#elif HWY_STATIC_TARGET == HWY_RVV
#define HWY_STATIC_DISPATCH(FUNC_NAME) N_RVV::FUNC_NAME
#elif HWY_STATIC_TARGET == HWY_WASM
#define HWY_STATIC_DISPATCH(FUNC_NAME) N_WASM::FUNC_NAME
#elif HWY_STATIC_TARGET == HWY_NEON
#define HWY_STATIC_DISPATCH(FUNC_NAME) N_NEON::FUNC_NAME
#elif HWY_STATIC_TARGET == HWY_PPC8
#define HWY_STATIC_DISPATCH(FUNC_NAME) N_PPC8::FUNC_NAME
#elif HWY_STATIC_TARGET == HWY_SSE4
#define HWY_STATIC_DISPATCH(FUNC_NAME) N_SSE4::FUNC_NAME
#elif HWY_STATIC_TARGET == HWY_AVX2
#define HWY_STATIC_DISPATCH(FUNC_NAME) N_AVX2::FUNC_NAME
#elif HWY_STATIC_TARGET == HWY_AVX3
#define HWY_STATIC_DISPATCH(FUNC_NAME) N_AVX3::FUNC_NAME
#endif
// Dynamic dispatch declarations.
template <typename RetType, typename... Args>
struct FunctionCache {
public:
typedef RetType(FunctionType)(Args...);
// A template function that when instantiated has the same signature as the
// function being called. This function initializes the global cache of the
// current supported targets mask used for dynamic dispatch and calls the
// appropriate function. Since this mask used for dynamic dispatch is a
// global cache, all the highway exported functions, even those exposed by
// different modules, will be initialized after this function runs for any one
// of those exported functions.
template <FunctionType* const table[]>
static RetType ChooseAndCall(Args... args) {
// If we are running here it means we need to update the chosen target.
chosen_target.Update();
return (table[chosen_target.GetIndex()])(args...);
}
};
// Factory function only used to infer the template parameters RetType and Args
// from a function passed to the factory.
template <typename RetType, typename... Args>
FunctionCache<RetType, Args...> FunctionCacheFactory(RetType (*)(Args...)) {
return FunctionCache<RetType, Args...>();
}
// HWY_CHOOSE_*(FUNC_NAME) expands to the function pointer for that target or
// nullptr is that target was not compiled.
#if HWY_TARGETS & HWY_SCALAR
#define HWY_CHOOSE_SCALAR(FUNC_NAME) &N_SCALAR::FUNC_NAME
#else
// When scalar is not present and we try to use scalar because other targets
// were disabled at runtime we fall back to the baseline with
// HWY_STATIC_DISPATCH()
#define HWY_CHOOSE_SCALAR(FUNC_NAME) &HWY_STATIC_DISPATCH(FUNC_NAME)
#endif
#if HWY_TARGETS & HWY_WASM
#define HWY_CHOOSE_WASM(FUNC_NAME) &N_WASM::FUNC_NAME
#else
#define HWY_CHOOSE_WASM(FUNC_NAME) nullptr
#endif
#if HWY_TARGETS & HWY_RVV
#define HWY_CHOOSE_RVV(FUNC_NAME) &N_RVV::FUNC_NAME
#else
#define HWY_CHOOSE_RVV(FUNC_NAME) nullptr
#endif
#if HWY_TARGETS & HWY_NEON
#define HWY_CHOOSE_NEON(FUNC_NAME) &N_NEON::FUNC_NAME
#else
#define HWY_CHOOSE_NEON(FUNC_NAME) nullptr
#endif
#if HWY_TARGETS & HWY_PPC8
#define HWY_CHOOSE_PCC8(FUNC_NAME) &N_PPC8::FUNC_NAME
#else
#define HWY_CHOOSE_PPC8(FUNC_NAME) nullptr
#endif
#if HWY_TARGETS & HWY_SSE4
#define HWY_CHOOSE_SSE4(FUNC_NAME) &N_SSE4::FUNC_NAME
#else
#define HWY_CHOOSE_SSE4(FUNC_NAME) nullptr
#endif
#if HWY_TARGETS & HWY_AVX2
#define HWY_CHOOSE_AVX2(FUNC_NAME) &N_AVX2::FUNC_NAME
#else
#define HWY_CHOOSE_AVX2(FUNC_NAME) nullptr
#endif
#if HWY_TARGETS & HWY_AVX3
#define HWY_CHOOSE_AVX3(FUNC_NAME) &N_AVX3::FUNC_NAME
#else
#define HWY_CHOOSE_AVX3(FUNC_NAME) nullptr
#endif
#define HWY_DISPATCH_TABLE(FUNC_NAME) \
HWY_CONCAT(FUNC_NAME, HighwayDispatchTable)
// HWY_EXPORT(FUNC_NAME); expands to a static array that is used by
// HWY_DYNAMIC_DISPATCH() to call the appropriate function at runtime. This
// static array must be defined at the same namespace level as the function
// it is exporting.
// After being exported, it can be called from other parts of the same source
// file using HWY_DYNAMIC_DISTPATCH(), in particular from a function wrapper
// like in the following example:
//
// #include "hwy/highway.h"
// HWY_BEFORE_NAMESPACE();
// namespace skeleton {
// namespace HWY_NAMESPACE {
//
// void MyFunction(int a, char b, const char* c) { ... }
//
// // NOLINTNEXTLINE(google-readability-namespace-comments)
// } // namespace HWY_NAMESPACE
// } // namespace skeleton
// HWY_AFTER_NAMESPACE();
//
// namespace skeleton {
// HWY_EXPORT(MyFunction); // Defines the dispatch table in this scope.
//
// void MyFunction(int a, char b, const char* c) {
// return HWY_DYNAMIC_DISPATCH(MyFunction)(a, b, c);
// }
// } // namespace skeleton
//
#if HWY_IDE || ((HWY_TARGETS & (HWY_TARGETS - 1)) == 0)
// Simplified version for IDE or the dynamic dispatch case with only one target.
// This case still uses a table, although of a single element, to provide the
// same compile error conditions as with the dynamic dispatch case when multiple
// targets are being compiled.
#define HWY_EXPORT(FUNC_NAME) \
HWY_MAYBE_UNUSED static decltype(&HWY_STATIC_DISPATCH(FUNC_NAME)) \
const HWY_DISPATCH_TABLE(FUNC_NAME)[1] = { \
&HWY_STATIC_DISPATCH(FUNC_NAME)}
#define HWY_DYNAMIC_DISPATCH(FUNC_NAME) HWY_STATIC_DISPATCH(FUNC_NAME)
#else
// Dynamic dispatch case with one entry per dynamic target plus the scalar
// mode and the initialization wrapper.
#define HWY_EXPORT(FUNC_NAME) \
static decltype(&HWY_STATIC_DISPATCH(FUNC_NAME)) \
const HWY_DISPATCH_TABLE(FUNC_NAME)[HWY_MAX_DYNAMIC_TARGETS + 2] = { \
/* The first entry in the table initializes the global cache and \
* calls the appropriate function. */ \
&decltype(hwy::FunctionCacheFactory(&HWY_STATIC_DISPATCH( \
FUNC_NAME)))::ChooseAndCall<HWY_DISPATCH_TABLE(FUNC_NAME)>, \
HWY_CHOOSE_TARGET_LIST(FUNC_NAME), \
HWY_CHOOSE_SCALAR(FUNC_NAME), \
}
#define HWY_DYNAMIC_DISPATCH(FUNC_NAME) \
(*(HWY_DISPATCH_TABLE(FUNC_NAME)[hwy::chosen_target.GetIndex()]))
#endif // HWY_IDE || ((HWY_TARGETS & (HWY_TARGETS - 1)) == 0)
} // namespace hwy
#endif // HWY_HIGHWAY_INCLUDED
//------------------------------------------------------------------------------
// NOTE: the following definitions and ops/*.h depend on HWY_TARGET, so we want
// to include them once per target, which is ensured by the toggle check.
// Because ops/*.h are included under it, they do not need their own guard.
#if defined(HWY_HIGHWAY_PER_TARGET) == defined(HWY_TARGET_TOGGLE)
#ifdef HWY_HIGHWAY_PER_TARGET
#undef HWY_HIGHWAY_PER_TARGET
#else
#define HWY_HIGHWAY_PER_TARGET
#endif
#undef HWY_FULL2
#if HWY_TARGET == HWY_RVV
#define HWY_FULL2(T, LMUL) hwy::HWY_NAMESPACE::Simd<T, HWY_LANES(T) * (LMUL)>
#else
#define HWY_FULL2(T, LMUL) hwy::HWY_NAMESPACE::Simd<T, HWY_LANES(T)>
#endif
// These define ops inside namespace hwy::HWY_NAMESPACE.
#if HWY_TARGET == HWY_SSE4
#include "hwy/ops/x86_128-inl.h"
#elif HWY_TARGET == HWY_AVX2
#include "hwy/ops/x86_256-inl.h"
#elif HWY_TARGET == HWY_AVX3
#include "hwy/ops/x86_512-inl.h"
#elif HWY_TARGET == HWY_PPC8
#elif HWY_TARGET == HWY_NEON
#include "hwy/ops/arm_neon-inl.h"
#elif HWY_TARGET == HWY_WASM
#include "hwy/ops/wasm_128-inl.h"
#elif HWY_TARGET == HWY_RVV
#include "hwy/ops/rvv-inl.h"
#elif HWY_TARGET == HWY_SCALAR
#include "hwy/ops/scalar-inl.h"
#else
#pragma message("HWY_TARGET does not match any known target")
#endif // HWY_TARGET
// Commonly used functions/types that must come after ops are defined.
HWY_BEFORE_NAMESPACE();
namespace hwy {
namespace HWY_NAMESPACE {
// The lane type of a vector type, e.g. float for Vec<Simd<float, 4>>.
template <class V>
using LaneType = decltype(GetLane(V()));
// Vector type, e.g. Vec128<float> for Simd<float, 4>. Useful as the return type
// of functions that do not take a vector argument, or as an argument type if
// the function only has a template argument for D, or for explicit type names
// instead of auto. This may be a built-in type.
template <class D>
using Vec = decltype(Zero(D()));
// Mask type. Useful as the return type of functions that do not take a mask
// argument, or as an argument type if the function only has a template argument
// for D, or for explicit type names instead of auto.
template <class D>
using Mask = decltype(MaskFromVec(Zero(D())));
// Returns the closest value to v within [lo, hi].
template <class V>
HWY_API V Clamp(const V v, const V lo, const V hi) {
return Min(Max(lo, v), hi);
}
// CombineShiftRightBytes (and ..Lanes) are not available for the scalar target.
// TODO(janwas): implement for RVV
#if HWY_TARGET != HWY_SCALAR && HWY_TARGET != HWY_RVV
template <size_t kLanes, class V>
HWY_API V CombineShiftRightLanes(const V hi, const V lo) {
return CombineShiftRightBytes<kLanes * sizeof(LaneType<V>)>(hi, lo);
}
#endif
// Returns lanes with the most significant bit set and all other bits zero.
template <class D>
HWY_API Vec<D> SignBit(D d) {
using Unsigned = MakeUnsigned<TFromD<D>>;
const Unsigned bit = Unsigned(1) << (sizeof(Unsigned) * 8 - 1);
return BitCast(d, Set(Rebind<Unsigned, D>(), bit));
}
// Returns quiet NaN.
template <class D>
HWY_API Vec<D> NaN(D d) {
const RebindToSigned<D> di;
// LimitsMax sets all exponent and mantissa bits to 1. The exponent plus
// mantissa MSB (to indicate quiet) would be sufficient.
return BitCast(d, Set(di, LimitsMax<TFromD<decltype(di)>>()));
}
// NOLINTNEXTLINE(google-readability-namespace-comments)
} // namespace HWY_NAMESPACE
} // namespace hwy
HWY_AFTER_NAMESPACE();
#endif // HWY_HIGHWAY_PER_TARGET
| 37.269231 | 80 | 0.725014 |
fa23ff9512b74f3d69fe3428e615cea95fa86d2e | 623 | h | C | src/lcthw/tstree.h | shantanu69/liblcthw | fb54bed9b8b7205f1c278a28a468ff57bbbc55eb | [
"MIT"
] | 2 | 2015-12-10T11:48:46.000Z | 2016-05-24T11:27:40.000Z | src/lcthw/tstree.h | shantanu69/liblcthw | fb54bed9b8b7205f1c278a28a468ff57bbbc55eb | [
"MIT"
] | null | null | null | src/lcthw/tstree.h | shantanu69/liblcthw | fb54bed9b8b7205f1c278a28a468ff57bbbc55eb | [
"MIT"
] | null | null | null | #ifndef _lcthw_TSTree_h
#define _lcthw_TSTree_h
#include <stdlib.h>
#include <lcthw/darray.h>
typedef struct TSTree {
char splitchar;
struct TSTree *low;
struct TSTree *equal;
struct TSTree *high;
void *value;
} TSTree;
void *TSTree_search(TSTree *root, const char *key, size_t len);
void *TSTree_search_prefix(TSTree *root, const char *key, size_t len);
typedef void (*TSTree_traverse_cb)(void *value, void *data);
TSTree *TSTree_insert(TSTree *node, const char *key, size_t len, void *value);
void TSTree_traverse(TSTree *node, TSTree_traverse_cb cb, void *data);
void TSTree_destroy(TSTree *root);
#endif
| 21.482759 | 78 | 0.751204 |
d21fa023bbff5045fff7060da78f6da2c69385d5 | 956 | h | C | include/il2cpp/System/Runtime/Serialization/Formatters/Binary/ObjectProgress.h | martmists-gh/BDSP | d6326c5d3ad9697ea65269ed47aa0b63abac2a0a | [
"MIT"
] | 1 | 2022-01-15T20:20:27.000Z | 2022-01-15T20:20:27.000Z | include/il2cpp/System/Runtime/Serialization/Formatters/Binary/ObjectProgress.h | martmists-gh/BDSP | d6326c5d3ad9697ea65269ed47aa0b63abac2a0a | [
"MIT"
] | null | null | null | include/il2cpp/System/Runtime/Serialization/Formatters/Binary/ObjectProgress.h | martmists-gh/BDSP | d6326c5d3ad9697ea65269ed47aa0b63abac2a0a | [
"MIT"
] | null | null | null | #pragma once
#include "il2cpp.h"
void System_Runtime_Serialization_Formatters_Binary_ObjectProgress___ctor (System_Runtime_Serialization_Formatters_Binary_ObjectProgress_o* __this, const MethodInfo* method_info);
void System_Runtime_Serialization_Formatters_Binary_ObjectProgress__Init (System_Runtime_Serialization_Formatters_Binary_ObjectProgress_o* __this, const MethodInfo* method_info);
void System_Runtime_Serialization_Formatters_Binary_ObjectProgress__ArrayCountIncrement (System_Runtime_Serialization_Formatters_Binary_ObjectProgress_o* __this, int32_t value, const MethodInfo* method_info);
bool System_Runtime_Serialization_Formatters_Binary_ObjectProgress__GetNext (System_Runtime_Serialization_Formatters_Binary_ObjectProgress_o* __this, int32_t* outBinaryTypeEnum, Il2CppObject** outTypeInformation, const MethodInfo* method_info);
void System_Runtime_Serialization_Formatters_Binary_ObjectProgress___cctor (const MethodInfo* method_info);
| 95.6 | 244 | 0.912134 |
cfa996b9566e754f00c094c2659d9ec45bd22020 | 3,416 | h | C | sources/drivers/misc/mediatek/ssusb/mu3d/musb_gadget.h | fuldaros/paperplane_kernel_wileyfox-spark | bea244880d2de50f4ad14bb6fa5777652232c033 | [
"Apache-2.0"
] | 2 | 2018-03-09T23:59:27.000Z | 2018-04-01T07:58:39.000Z | sources/drivers/misc/mediatek/ssusb/mu3d/musb_gadget.h | fuldaros/paperplane_kernel_wileyfox-spark | bea244880d2de50f4ad14bb6fa5777652232c033 | [
"Apache-2.0"
] | null | null | null | sources/drivers/misc/mediatek/ssusb/mu3d/musb_gadget.h | fuldaros/paperplane_kernel_wileyfox-spark | bea244880d2de50f4ad14bb6fa5777652232c033 | [
"Apache-2.0"
] | 3 | 2017-06-24T20:23:09.000Z | 2018-03-25T04:30:11.000Z | /*
* MUSB OTG driver peripheral defines
*
* Copyright 2005 Mentor Graphics Corporation
* Copyright (C) 2005-2006 by Texas Instruments
* Copyright (C) 2006-2007 Nokia Corporation
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
* THIS SOFTWARE IS PROVIDED "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 AUTHORS 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 __MUSB_GADGET_H
#define __MUSB_GADGET_H
#include <linux/list.h>
enum buffer_map_state {
UN_MAPPED = 0,
PRE_MAPPED,
MUSB_MAPPED
};
struct musb_request {
struct usb_request request;
struct list_head list;
struct musb_ep *ep;
struct musb *musb;
u8 tx; /* endpoint direction */
u8 epnum;
enum buffer_map_state map_state;
};
static inline struct musb_request *to_musb_request(struct usb_request *req)
{
return req ? container_of(req, struct musb_request, request) : NULL;
}
extern struct usb_request *musb_alloc_request(struct usb_ep *ep, gfp_t gfp_flags);
extern void musb_free_request(struct usb_ep *ep, struct usb_request *req);
/*
* struct musb_ep - peripheral side view of endpoint rx or tx side
*/
struct musb_ep {
/* stuff towards the head is basically write-once. */
struct usb_ep end_point;
char name[12];
struct musb_hw_ep *hw_ep;
struct musb *musb;
u8 current_epnum;
/* ... when enabled/disabled ... */
u8 type;
u8 is_in;
u16 packet_sz;
const struct usb_endpoint_descriptor *desc;
/* struct dma_channel *dma; */
/* later things are modified based on usage */
struct list_head req_list;
u8 wedged;
/* true if lock must be dropped but req_list may not be advanced */
u8 busy;
/* u8 hb_mult; */
};
static inline struct musb_ep *to_musb_ep(struct usb_ep *ep)
{
return ep ? container_of(ep, struct musb_ep, end_point) : NULL;
}
static inline struct musb_request *next_request(struct musb_ep *ep)
{
struct list_head *queue = &ep->req_list;
if (list_empty(queue))
return NULL;
return container_of(queue->next, struct musb_request, list);
}
void musb_conifg_ep0(struct musb *musb);
extern void musb_g_tx(struct musb *musb, u8 epnum);
extern void musb_g_rx(struct musb *musb, u8 epnum);
extern const struct usb_ep_ops musb_g_ep0_ops;
extern int musb_gadget_setup(struct musb *);
extern void musb_gadget_cleanup(struct musb *);
extern void musb_g_giveback(struct musb_ep *, struct usb_request *, int);
extern void musb_ep_restart(struct musb *, struct musb_request *);
#endif /* __MUSB_GADGET_H */
| 29.196581 | 82 | 0.752635 |
5cda0bdb7bf06f00701fb8c144c0fce25136ab4d | 767 | h | C | src/trunk/libs/3rd-party/spread/libspread-util/include/spu_system_defs_windows.h | yannikbehr/seiscomp3 | ebb44c77092555eef7786493d00ac4efc679055f | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | null | null | null | src/trunk/libs/3rd-party/spread/libspread-util/include/spu_system_defs_windows.h | yannikbehr/seiscomp3 | ebb44c77092555eef7786493d00ac4efc679055f | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | null | null | null | src/trunk/libs/3rd-party/spread/libspread-util/include/spu_system_defs_windows.h | yannikbehr/seiscomp3 | ebb44c77092555eef7786493d00ac4efc679055f | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | 1 | 2021-09-15T08:13:27.000Z | 2021-09-15T08:13:27.000Z | #ifndef SYSTEM_DEFS_WINDOWS_H
#define SYSTEM_DEFS_WINDOWS_H
#ifndef SYSTEM_DEFS_H
#error "system_defs_windows.h should never be directly included. Include system_defs.h."
#endif
#define LOC_INLINE __inline__
#ifndef int16
#define int16 short
#endif
#ifndef int16u
#define int16u unsigned short
#endif
#ifndef int32
#define int32 int
#endif
#ifndef int32u
#define int32u unsigned int
#endif
#ifndef UINT32_MAX
#define UINT32_MAX UINT_MAX
#endif
#ifndef INT32_MAX
#define INT32_MAX INT_MAX
#endif
#ifndef int64_t
#define int64_t __int64
#endif
#ifdef MSG_MAXIOVLEN
#define SPU_ARCH_SCATTER_SIZE MSG_MAXIOVLEN
#else
#define SPU_ARCH_SCATTER_SIZE 64
#endif
#endif /* SYSTEM_DEFS_WINDOWS_H */
| 17.044444 | 88 | 0.740548 |
d09be1ed938ff09e4d0de8d2e1d39afe6c4a3720 | 4,740 | h | C | include/tubeConvertTubesToDensityImage.h | thewtex/TubeTK | 7536c6c112e1785cead4d008e8fae5ca8f527f20 | [
"Apache-2.0"
] | null | null | null | include/tubeConvertTubesToDensityImage.h | thewtex/TubeTK | 7536c6c112e1785cead4d008e8fae5ca8f527f20 | [
"Apache-2.0"
] | null | null | null | include/tubeConvertTubesToDensityImage.h | thewtex/TubeTK | 7536c6c112e1785cead4d008e8fae5ca8f527f20 | [
"Apache-2.0"
] | null | null | null | /*=========================================================================
Library: TubeTK
Copyright 2010 Kitware Inc. 28 Corporate Drive,
Clifton Park, NY, 12065, USA.
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
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
=========================================================================*/
#ifndef __tubeConvertTubesToDensityImage_h
#define __tubeConvertTubesToDensityImage_h
// ITK includes
#include <itkGroupSpatialObject.h>
#include <itkMacro.h>
#include <itkProcessObject.h>
// TubeTK includes
#include "itktubeTubeSpatialObjectToDensityImageFilter.h"
#include "tubeWrappingMacros.h"
namespace tube
{
/** \class ConvertTubesToDensityImage
*
* \ingroup TubeTK
*/
template< class TOutputPixel, unsigned int Dimension >
class ConvertTubesToDensityImage:
public itk::ProcessObject
{
public:
/** Standard class typedefs. */
typedef ConvertTubesToDensityImage Self;
typedef itk::ProcessObject Superclass;
typedef itk::SmartPointer< Self > Pointer;
typedef itk::SmartPointer< const Self > ConstPointer;
/** Typdefs */
typedef itk::Image< TOutputPixel, Dimension > DensityImageType;
typedef typename DensityImageType::PixelType DensityPixelType;
typedef typename DensityImageType::Pointer DensityImagePointer;
typedef typename DensityImageType::SizeType SizeType;
typedef typename DensityImageType::SpacingType SpacingType;
/** Method for creation through the object factory. */
itkNewMacro( Self );
/** Run-time type information ( and related methods ). */
itkTypeMacro( ConvertTubesToDensityImage, Object );
typedef itk::Image< TOutputPixel, Dimension > RadiusImageType;
typedef typename RadiusImageType::Pointer RadiusImagePointer;
typedef itk::Vector< TOutputPixel, Dimension > TangentPixelType;
typedef itk::Image< TangentPixelType, Dimension > TangentImageType;
typedef typename TangentImageType::Pointer TangentImagePointer;
typedef itk::GroupSpatialObject< Dimension > TubeGroupType;
typedef typename TubeGroupType::Pointer TubeGroupPointer;
typedef itk::tube::TubeSpatialObjectToDensityImageFilter<
DensityImageType, RadiusImageType, TangentImageType > FilterType;
/** Set maximum density intensity value. Its a constant */
tubeWrapSetMacro( MaxDensityIntensity, DensityPixelType, Filter );
tubeWrapGetMacro( MaxDensityIntensity, DensityPixelType, Filter );
/** Set the size of the output image volumes */
tubeWrapSetMacro( Size, SizeType, Filter );
tubeWrapGetMacro( Size, SizeType, Filter );
/** Set whether to use squared or actual distances in calculations. */
tubeWrapSetMacro( UseSquaredDistance, bool, Filter );
tubeWrapGetMacro( UseSquaredDistance, bool, Filter );
/** Set the input tubes */
tubeWrapSetMacro( InputTubeGroup, TubeGroupPointer, Filter );
tubeWrapGetMacro( InputTubeGroup, TubeGroupPointer, Filter );
/* Runs tubes to density image conversion */
tubeWrapUpdateMacro( Filter );
/* Get the generated density image */
tubeWrapGetMacro( DensityMapImage, DensityImagePointer, Filter );
/* Get the generated radius image */
tubeWrapGetMacro( RadiusMapImage, RadiusImagePointer, Filter );
/* Get the generated tangent map image */
tubeWrapGetMacro( TangentMapImage, TangentImagePointer, Filter );
/** Sets the element spacing */
tubeWrapSetMacro( Spacing, SpacingType, Filter );
tubeWrapGetMacro( Spacing, SpacingType, Filter );
protected:
ConvertTubesToDensityImage( void );
~ConvertTubesToDensityImage() {}
void PrintSelf( std::ostream & os, itk::Indent indent ) const override;
private:
/** itkConvertTubesToImageFilter parameters **/
ConvertTubesToDensityImage( const Self & );
void operator=( const Self & );
// To remove warning "was hidden [-Woverloaded-virtual]"
void SetInput( const DataObjectIdentifierType &, itk::DataObject * ) override
{};
typename FilterType::Pointer m_Filter;
};
} // End namespace tube
#ifndef ITK_MANUAL_INSTANTIATION
#include "tubeConvertTubesToDensityImage.hxx"
#endif
#endif // End !defined( __tubeConvertTubesToDensityImage_h )
| 34.852941 | 79 | 0.717511 |
d0adf08ae8ee7bb703706cae0adcb79f9c8316c7 | 2,589 | c | C | app/src/main/c/bluez-android-3.35/utils/sdpd/cstate.c | IllusionMan1212/ShockPair | 0ad1fbd7edfcbf51e4b677d10ab3e137efec0b88 | [
"MIT"
] | 1 | 2021-07-12T00:34:11.000Z | 2021-07-12T00:34:11.000Z | app/src/main/c/bluez-android-3.35/utils/sdpd/cstate.c | IllusionMan1212/ShockPair | 0ad1fbd7edfcbf51e4b677d10ab3e137efec0b88 | [
"MIT"
] | null | null | null | app/src/main/c/bluez-android-3.35/utils/sdpd/cstate.c | IllusionMan1212/ShockPair | 0ad1fbd7edfcbf51e4b677d10ab3e137efec0b88 | [
"MIT"
] | null | null | null | /*
*
* BlueZ - Bluetooth protocol stack for Linux
*
* Copyright (C) 2001-2002 Nokia Corporation
* Copyright (C) 2002-2003 Maxim Krasnyansky <maxk@qualcomm.com>
* Copyright (C) 2002-2008 Marcel Holtmann <marcel@holtmann.org>
* Copyright (C) 2002-2003 Stephen Crane <steve.crane@rococosoft.com>
*
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <sys/time.h>
#include <sys/socket.h>
#include <bluetooth/bluetooth.h>
#include <bluetooth/sdp.h>
#include <bluetooth/sdp_lib.h>
#include "sdpd.h"
typedef struct _sdp_cstate_list sdp_cstate_list_t;
struct _sdp_cstate_list {
sdp_cstate_list_t *next;
uint32_t timestamp;
sdp_buf_t buf;
};
static sdp_cstate_list_t *cstates;
// FIXME: should probably remove it when it's found
sdp_buf_t *sdp_get_cached_rsp(sdp_cont_state_t *cstate)
{
sdp_cstate_list_t *p;
for (p = cstates; p; p = p->next)
if (p->timestamp == cstate->timestamp)
return &p->buf;
return 0;
}
uint32_t sdp_cstate_alloc_buf(sdp_buf_t *buf)
{
sdp_cstate_list_t *cstate = malloc(sizeof(sdp_cstate_list_t));
uint8_t *data = malloc(buf->data_size);
memcpy(data, buf->data, buf->data_size);
memset((char *)cstate, 0, sizeof(sdp_cstate_list_t));
cstate->buf.data = data;
cstate->buf.data_size = buf->data_size;
cstate->buf.buf_size = buf->data_size;
cstate->timestamp = sdp_get_time();
cstate->next = cstates;
cstates = cstate;
return cstate->timestamp;
}
/*
* A simple function which returns the time of day in
* seconds. Used for updating the service db state
* attribute of the service record of the SDP server
*/
uint32_t sdp_get_time()
{
/*
* To handle failure in gettimeofday, so an old
* value is returned and service does not fail
*/
static struct timeval tm;
gettimeofday(&tm, NULL);
return (uint32_t) tm.tv_sec;
}
| 26.96875 | 78 | 0.727694 |
04c934ee72be4d127e214fa11d059695047477ab | 235,223 | c | C | src/x509-parser.c | evdenis/x509-parser | 1cc65867a651311a0885cc66e448f49457fff2df | [
"BSD-2-Clause"
] | null | null | null | src/x509-parser.c | evdenis/x509-parser | 1cc65867a651311a0885cc66e448f49457fff2df | [
"BSD-2-Clause"
] | null | null | null | src/x509-parser.c | evdenis/x509-parser | 1cc65867a651311a0885cc66e448f49457fff2df | [
"BSD-2-Clause"
] | null | null | null | /*
* Copyright (C) 2019 - This file is part of x509-parser project
*
* Author:
* Arnaud EBALARD <arnaud.ebalard@ssi.gouv.fr>
*
* This software is licensed under a dual GPLv2/BSD license. See
* LICENSE file at the root folder of the project.
*/
#include "x509-parser.h"
/*
* Some implementation notes:
*
* The implementation is based on X.690 and X.680 (both 07/2002). It is
* voluntarily limited to parsing a buffer of small size (no more than
* ASN1_MAX_BUFFER_SIZE bytes long) containing a DER encoded ASN.1
* structure.
*
*/
#ifdef ERROR_TRACE_ENABLE
#define ERROR_TRACE_APPEND(x) do { \
extern int printf(const char *format, ...); \
printf("%05d", (x)); \
} while (0);
#else
#define ERROR_TRACE_APPEND(x)
#endif
typedef enum {
CLASS_UNIVERSAL = 0x00,
CLASS_APPLICATION = 0x01,
CLASS_CONTEXT_SPECIFIC = 0x02,
CLASS_PRIVATE = 0x03
} tag_class;
/*@
@ predicate bmatch(u8 *b1, u8 *b2, u16 n) =
@ \forall integer i; 0 <= i < n ==> b1[i] == b2[i];
@
@ predicate bdiffer(u8 *b1, u8 *b2, u16 n) =
@ ! bmatch(b1, b2, n);
@*/
/*@
@
@ requires \valid_read(b1 + (0 .. n-1));
@ requires \valid_read(b2 + (0 .. n-1));
@ assigns \nothing;
@*/
static int bufs_differ(const u8 *b1, const u8 *b2, u16 n)
{
int ret = 0;
u16 i = 0;
/*@
@ loop invariant 0 <= i <= n;
@ loop invariant bmatch(b1, b2, i);
@ loop assigns i;
@*/
for (i = 0; i < n; i++) {
if(b1[i] != b2[i]) {
ret = 1;
break;
}
}
return ret;
}
/*
* Helper for ASN.1 DER identifier field parsing, which extracts the tag number
* when it is not encoded on a single byte, i.e. when the first encountered byte
* for the field is 0x1f. The function takes as parameter the buffer following
* this 0x1f byte and, upon success, extracts the tag value.
*
* In our implementation, tag numbers are limited by the return type used for
* the parameter (32 bit unsigned integers). In practice we allow tag encoded
* on 4 bytes, i.e. with a final value of 4 * 7 bits, i.e. 28 bits. This is
* considered largely sufficient in the context of X.509 certificates (which is
* validated by our tests).
*
* Note that the function does verify that extracted tag is indeed >= 0x1f.
*/
/*@
@ requires len >= 0;
@ requires ((len > 0) && (buf != \null)) ==>
\valid_read(buf + (0 .. (len - 1)));
@ requires \separated(tag_num, eaten, buf+(..));
@ requires \valid(tag_num);
@ requires \valid(eaten);
@ ensures \result < 0 || \result == 0;
@ ensures (len == 0) ==> \result < 0;
@ ensures (buf == \null) ==> \result < 0;
@ ensures (\result == 0) ==> 1 <= *eaten <= len;
@ ensures (\result == 0) ==> (*eaten <= len);
@ ensures (\result == 0) ==> (*eaten > 0);
@ assigns *tag_num, *eaten;
@*/
static int _extract_complex_tag(const u8 *buf, u16 len, u32 *tag_num, u16 *eaten)
{
u16 rbytes;
u32 t = 0;
int ret;
if ((len == 0) || (buf == NULL)) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
if (len > 4) {
len = 4;
}
/*@
@ loop invariant 0 <= rbytes <= len;
@ loop invariant t <= (((u32)1 << (u32)(7*(rbytes))) - 1);
@ loop invariant \forall integer x ; 0 <= x < rbytes ==>
((buf[x] & 0x80) != 0);
@ loop assigns rbytes, t;
@ loop variant (len - rbytes);
@ */
for (rbytes = 0; rbytes < len; rbytes++) {
u32 tmp1, tmp2;
/*@ assert rbytes <= 3; */
/*@ assert t <= (((u32)1 << (u32)(7*(rbytes))) - 1); */
/*@ assert t <= (u32)0x1fffff; */
tmp1 = (t << (u32)7);
tmp2 = ((u32)buf[rbytes] & (u32)0x7f);
/*@ assert tmp1 <= (u32)0xfffff80; */
/*@ assert tmp2 <= (u32)0x7f; */
t = tmp1 + tmp2;
/*@ assert t <= (((u32)1 << (u32)(7*(rbytes + 1))) - 1); */
/*@ assert t <= 0xfffffff; */
if ((buf[rbytes] & 0x80) == 0) {
break;
}
}
/* Check if we left the loop w/o finding tag's end */
if (rbytes == len) {
/*@ assert ((buf[len - 1] & 0x80) != 0); */
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
if (t < 0x1f) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
*tag_num = t;
*eaten = rbytes + 1;
ret = 0;
out:
return ret;
}
/*
* Parse beginning of current buffer to get the identifier parameters (class,
* P/C flag and tag number). On success, the amount of bytes eaten to extract
* those information is returned in 'eaten' parameter, which is guaranteed to
* be lower or equal than 'len' parameter. On error, a non-zero negative value
* is returned.
*
* Note: tags numbers are limited by the return type used for the parameter
* (32 bit unsigned integer). In practice, this allows tag encoded on 4 bytes,
* i.e. 4 x 7 bits, i.e. 28 bits. This is considered largely sufficient in
* the context of X.509 certificates. An error is returned if a tag number
* higher than that is found.
*/
/*@
@ requires len >= 0;
@ requires ((len > 0) && (buf != \null)) ==>
\valid_read(buf + (0 .. (len - 1)));
@ requires \separated(cls, prim, tag_num, eaten, buf+(..));
@ requires \valid(cls);
@ requires \valid(prim);
@ requires \valid(tag_num);
@ requires \valid(eaten);
@ ensures \result < 0 || \result == 0;
@ ensures (\result == 0) ==> (0 < *eaten <= len);
@ ensures (\result == 0) ==> (*cls <= 0x3);
@ ensures (\result == 0) ==> (*prim <= 0x1);
@ ensures (len == 0) ==> \result < 0;
@ ensures (buf == \null) ==> \result < 0;
@ assigns *tag_num, *eaten, *prim, *cls;
@*/
static int get_identifier(const u8 *buf, u16 len,
tag_class *cls, u8 *prim, u32 *tag_num, u16 *eaten)
{
int ret;
u32 t;
u16 rbytes = 0;
u8 p;
tag_class c;
if (buf == NULL) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/*
* First byte (if available) will give us the class and P/C, and also
* tells us (based on the value of the 6 LSB of the bytes) if the tag
* number is stored on additional bytes.
*/
if (len == 0) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/* See 8.1.2.3 */
c = (buf[0] >> 6) & 0x03; /* Extract class from 2 MSB */
p = (buf[0] >> 5) & 0x01; /* Extract P/C bit */
t = buf[0] & 0x1f; /* Extract tag number from 6 LSB */
rbytes = 1;
/*
* Check if we know given class (see Table 1 from 8.1.2.2). In practice,
* there is no way to end up in default case, because 'c' has at most
* its two MSB set (see above).
*/
switch (c) {
case CLASS_UNIVERSAL:
case CLASS_APPLICATION:
case CLASS_CONTEXT_SPECIFIC:
case CLASS_PRIVATE:
break;
default:
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
break;
}
/*
* If the tag number (6 LSB of first byte) we already extracted is less
* than 0x1f, then it directly represents the tag number (which is <=
* 30) and our work is over. Otherwise (t == 0x1f) the real tag number
* is encoded on multiple bytes following the first byte. Note that we
* limit ourselves to tag encoded on less than 28 bits, i.e. only accept
* at most 4 bytes (only 7 LSB of each byte will count because MSB tells
* if this is the last).
*/
if (t == 0x1f) {
u16 tag_len = 0;
/*@
@ assert (len >= rbytes) && (len - rbytes <= 65535) &&
\valid_read(buf + (rbytes .. len - 1));
@*/
ret = _extract_complex_tag(buf + rbytes, len - rbytes,
&t, &tag_len);
if (ret) {
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
rbytes += tag_len;
}
/* Export what we extracted to caller */
*cls = c;
*prim = p;
*tag_num = t;
*eaten = rbytes;
ret = 0;
out:
return ret;
}
/*
* Parse beginning of current buffer to get the length parameter. Input buffer
* 'buf' has size 'len'. On success, 0 is returned, advertised length is
* returned in 'adv_len' and the number of bytes used for the encoding of the
* length is returned in 'eaten'.
*/
/*@
@ requires len >= 0;
@ requires ((len > 0) && (buf != \null)) ==> \valid_read(buf + (0 .. (len - 1)));
@ requires \separated(adv_len, eaten, buf+(..));
@ requires \valid(adv_len);
@ requires \valid(eaten);
@ ensures \result < 0 || \result == 0;
@ ensures (\result == 0) ==> (0 < *eaten <= len);
@ ensures (\result == 0) ==> (*adv_len <= len);
@ ensures (\result == 0) ==> ((*adv_len + *eaten) <= len);
@ ensures (len == 0) ==> \result < 0;
@ ensures (buf == \null) ==> \result < 0;
@ assigns *adv_len, *eaten;
@*/
static int get_length(const u8 *buf, u16 len, u16 *adv_len, u16 *eaten)
{
u16 l, rbytes = 0;
u8 len_len, b0;
int ret;
if (buf == NULL) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
if (len == 0) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/*@ assert \valid_read(buf + 0); */
b0 = buf[0];
/* Single byte length (i.e. definitive form, on one byte)? */
if ((b0 & 0x80) == 0) {
l = b0 & 0x7f;
/*@ assert l <= 0x7f ; */
/*
* Adding 1 below to take into account the byte that
* encode the length is possible because l does not
* have its MSB set, i.e. is less than or equal to
* 127.
*/
if ((l + 1) > len) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/* Advertised length looks ok */
*eaten = 1;
*adv_len = l;
/*@ assert (*eaten + *adv_len) <= len ; */
ret = 0;
goto out;
}
/*
* DER requires the definitive form for the length, i.e. that
* first byte of the length field is not 0x80. At that point,
* we already know that MSB of the byte is 1.
*/
if (b0 == 0x80) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/*
* We now know that the long form of the length is used. Let's
* extract how many bytes are used to encode the length.
*/
len_len = b0 & 0x7f;
/*@ assert len_len <= 0x7f ; */
rbytes += 1;
/*@ assert rbytes > 0 ; */
/*
* We first check that given length for the length field is not
* more than the size of the buffer (including the first byte
* encoding the length of that length). Note that we can do
* the addition below because MSB of len_len is 0.
*/
if ((len_len + 1) > len) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/* Now that we have length's length, let's now extract its value */
switch (len_len) {
case 0: /* Not acceptable */
/* Length's length cannot be 0 */
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
break;
case 1: /* Length values in [ 128, 255 ] */
/* assert \valid_read(buf + 1); */
l = buf[1];
if (l <= 127) {
/*
* For such a length value, the compact encoding
* (definitive form) should have been used.
*/
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/*@ assert 127 < l ; */
rbytes += 1;
break;
case 2: /* Length values in [ 256, 65535 ] */
/* assert \valid_read(buf + (1 .. 2)); */
l = (((u16)buf[1]) * 256) + buf[2];
if (l <= 0xff) {
/* Why 2 bytes if most significant is 0? */
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/*@ assert 0xff < l <= 0xffff ; */
rbytes += 2;
break;
default: /* Not acceptable */
/*
* Length cannot be encoded on more than two bytes (we
* have an *intentional* internal limitation for
* all ASN.1 DER structures set to 65535 bytes (all
* our lengths are u16)
*/
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
break;
}
/*@ assert l > 127 ; */
/*@ assert len >= rbytes ; */
if ((len - rbytes) < l) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/*@ assert (rbytes + l) <= len ; */
/*@ assert rbytes > 0 ; */
*eaten = rbytes;
*adv_len = l;
ret = 0;
out:
return ret;
}
typedef enum {
ASN1_TYPE_INTEGER = 0x02,
ASN1_TYPE_BIT_STRING = 0x03,
ASN1_TYPE_OCTET_STRING = 0x04,
ASN1_TYPE_NULL = 0x05,
ASN1_TYPE_OID = 0x06,
ASN1_TYPE_SEQUENCE = 0x10,
ASN1_TYPE_SET = 0x11,
ASN1_TYPE_PrintableString = 0x13,
ASN1_TYPE_T61String = 0x14,
ASN1_TYPE_IA5String = 0x16,
ASN1_TYPE_UTCTime = 0x17,
ASN1_TYPE_GeneralizedTime = 0x18,
} asn1_type;
/*
* All DER-encoded elements are basically TLV structures (or identifier octets,
* length octets, contents octets). This function parses the T and L elements
* from given buffer and verifies the advertised length for the value (content
* octets) does not overflow outside of the buffer. Additionally, the expected
* class and type for the tag are verified. On success, the size of parsed
* elements (class, type and length) are returned in 'parsed' and the size of
* content octets are returned in 'content_len'.
*
* Note that the function does not parse the content of the encoded value, i.e.
* the 'content_len' bytes in the buffer after the 'parsed' (TL header) ones. It
* only guarantees that they are in the buffer.
*
* This function is critical for the security of the module.
*/
/*@
@ requires len >= 0;
@ requires ((len > 0) && (buf != \null)) ==> \valid_read(buf + (0 .. (len - 1)));
@ requires \valid(parsed);
@ requires \valid(content_len);
@ requires \separated(parsed, content_len, buf+(..));
@ ensures \result < 0 || \result == 0;
@ ensures (\result == 0) ==> (1 < *parsed <= len);
@ ensures (\result == 0) ==> (*content_len <= len);
@ ensures (\result == 0) ==> ((*content_len + *parsed) <= len);
@ ensures (len == 0) ==> \result < 0;
@ ensures (buf == \null) ==> \result < 0;
@ assigns *parsed, *content_len;
@*/
static int parse_id_len(const u8 *buf, u16 len, tag_class exp_class,
u32 exp_type, u16 *parsed, u16 *content_len)
{
tag_class c = 0;
u8 p;
u32 t = 0;
u16 cur_parsed = 0;
u16 grabbed;
u16 adv_len = 0;
int ret;
if (buf == NULL) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/* We voluntarily limit the size of the buffers we accept */
if (len > ASN1_MAX_BUFFER_SIZE) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/* Get the first part of the encoding, i.e. the identifier */
ret = get_identifier(buf, len, &c, &p, &t, &cur_parsed);
if (ret) {
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/*@ assert cur_parsed > 0; */
/*
* Now, verify we are indeed dealing with an element of
* given type ...
*/
if (t != exp_type) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/* ... and class. */
if (c != exp_class) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
grabbed = cur_parsed;
/*@ assert grabbed > 0; */
len -= cur_parsed;
buf += cur_parsed;
/* Get the second part of the encoding, i.e. the length */
ret = get_length(buf, len, &adv_len, &cur_parsed);
if (ret) {
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/*@ assert cur_parsed > 0; */
grabbed += cur_parsed;
/*@ assert grabbed > 1; */
len -= cur_parsed;
buf += cur_parsed;
/* Verify advertised length is smaller than remaining buffer length */
if (adv_len > len) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
*parsed = grabbed;
/*@ assert *parsed > 1; */
*content_len = adv_len;
ret = 0;
out:
return ret;
}
/*
* Here, we have to deal with a wrapper around our a usual ASN.1 TLV.
* The id of that wrapper has a given type and a context specific
* class (CLASS_CONTEXT_SPECIFIC), i.e. a T1L1T2L2V where
* T1 has exp_ext_type and class CLASS_CONTEXT_SPECIFIC
* L1 provides the length of T2L2V
* T2 has exp_int_type and exp_int_class
* L2 provides the length of V
*/
/*@
@ requires len >= 0;
@ requires ((len > 0) && (buf != \null)) ==> \valid_read(buf + (0 .. (len - 1)));
@ requires \valid(parsed);
@ requires \valid(data_len);
@ requires \separated(parsed, data_len, buf+(..));
@ ensures \result < 0 || \result == 0;
@ ensures (\result == 0) ==> (*parsed <= len);
@ ensures (\result == 0) ==> (*data_len <= len);
@ ensures (\result == 0) ==> ((*data_len + *parsed) <= len);
@ ensures (len == 0) ==> \result < 0;
@ ensures (buf == \null) ==> \result < 0;
@ assigns *parsed, *data_len;
@*/
static int parse_explicit_id_len(const u8 *buf, u16 len,
u32 exp_ext_type,
tag_class exp_int_class, u32 exp_int_type,
u16 *parsed, u16 *data_len)
{
u16 hdr_len = 0;
u16 val_len = 0;
int ret;
if ((buf == NULL) || (len == 0)) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/* Work on external packaging */
ret = parse_id_len(buf, len, CLASS_CONTEXT_SPECIFIC,
exp_ext_type, &hdr_len, &val_len);
if (ret) {
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
buf += hdr_len;
len -= hdr_len;
*parsed = hdr_len;
/* Work on internal packaging */
ret = parse_id_len(buf, len, exp_int_class, exp_int_type,
&hdr_len, &val_len);
if (ret) {
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
len -= hdr_len;
*parsed += hdr_len;
if (len < val_len) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/* Export the size of data */
*data_len = val_len;
ret = 0;
out:
return ret;
}
/*@
@ requires len >= 0;
@ requires ((len > 0) && (buf != \null)) ==> \valid_read(buf + (0 .. (len - 1)));
@ requires \valid(arc_val);
@ requires \valid(eaten);
@ requires \separated(arc_val, eaten, buf+(..));
@ ensures \result < 0 || \result == 0;
@ ensures (\result == 0) ==> (*eaten <= len);
@ ensures (\result == 0) ==> (*eaten > 0);
@ ensures ((len > 0) && (buf != \null) && (\result != 0)) ==>
\forall integer x ; 0 <= x < \min(len, 4) ==>
((buf[x] & 0x80) != 0);
@ ensures (len == 0) ==> \result < 0;
@ assigns *arc_val, *eaten;
@*/
static int _parse_arc(const u8 *buf, u16 len, u32 *arc_val, u16 *eaten)
{
u16 rbytes;
u32 av = 0;
int ret;
if ((len == 0) || (buf == NULL)) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/*
* RFC 5280 has "There is no maximum size for OIDs. This specification
* mandates support for OIDs that have arc elements with values that
* are less than 2^28, that is, they MUST be between 0 and 268,435,455,
* inclusive. This allows each arc element to be represented within a
* single 32-bit word." For that reason, we just leave if we end up
* encountering more than 4 bytes here.
*/
if (len > 4) {
len = 4;
}
/*@
@ loop invariant 0 <= rbytes <= len;
@ loop invariant av <= (((u32)1 << (u32)(7*(rbytes))) - 1);
@ loop invariant \forall integer x ; 0 <= x < rbytes ==>
((buf[x] & 0x80) != 0);
@ loop assigns rbytes, av;
@ loop variant (len - rbytes);
@ */
for (rbytes = 0; rbytes < len; rbytes++) {
u32 tmp1, tmp2;
/*@ assert rbytes <= 3; */
/*@ assert av <= (((u32)1 << (u32)(7*(rbytes))) - 1); */
/*@ assert av <= (u32)0x1fffff; */
tmp1 = (av << (u32)7);
/*@ assert tmp1 <= (u32)0xfffff80; */
tmp2 = ((u32)buf[rbytes] & (u32)0x7f);
/*@ assert tmp2 <= (u32)0x7f; */
av = tmp1 + tmp2;
/*@ assert av <= (((u32)1 << (u32)(7*(rbytes + 1))) - 1); */
/*@ assert av <= 0xfffffff; */
if ((buf[rbytes] & 0x80) == 0) {
break;
}
}
if (rbytes >= len) {
/*@ assert ((buf[len - 1] & 0x80) != 0); */
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
*arc_val = av;
*eaten = rbytes + 1;
ret = 0;
out:
return ret;
}
/*
* Implements a function for parsing OID as described in section 8.19
* of X.690. On success, the function returns 0 and set 'parsed'
* parameters to the amount of bytes on which the OID is encoded
* (header and content bytes).
*/
/*@
@ requires len >= 0;
@ requires ((len > 0) && (buf != \null)) ==> \valid_read(buf + (0 .. (len - 1)));
@ requires \valid(parsed);
@ requires \separated(parsed,buf+(..));
@ ensures \result < 0 || \result == 0;
@ ensures (\result == 0) ==> (2 < *parsed <= len);
@ ensures (len == 0) ==> \result < 0;
@ ensures (buf == \null) ==> \result < 0;
@ assigns *parsed;
@*/
static int parse_OID(const u8 *buf, u16 len, u16 *parsed)
{
u16 data_len = 0;
u16 hdr_len = 0;
u16 remain = 0;
u16 num;
int ret;
if ((buf == NULL) || (len == 0)) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
ret = parse_id_len(buf, len, CLASS_UNIVERSAL, ASN1_TYPE_OID,
&hdr_len, &data_len);
if (ret) {
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
len -= hdr_len;
buf += hdr_len;
if (data_len < 1) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/*@ assert \valid_read(buf + (0 .. (data_len - 1))); */
remain = data_len;
num = 0;
/*@
@ loop assigns ret, num, buf, remain;
@ loop invariant \valid_read(buf + (0 .. (remain - 1)));
@ loop variant remain;
@ */
while (remain) {
u32 arc_val = 0;
u16 rbytes = 0;
/*
* RFC 5280 has "Implementations MUST be able to handle
* OIDs with up to 20 elements (inclusive)".
*/
if (num > 20) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
ret = _parse_arc(buf, remain, &arc_val, &rbytes);
if (ret) {
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/*@ assert rbytes <= remain ; */
num += 1;
buf += rbytes;
remain -= rbytes;
}
/*
* Let's check the OID had at least the first initial
* subidentifier (the one derived from the two first
* components) as described in section 8.19 of X.690.
*/
if (num < 1) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
*parsed = hdr_len + data_len;
ret = 0;
out:
return ret;
}
/*
* Implements a function for parsing integers as described in section 8.3
* of X.690. As integers may be used in a context specific way, we allow
* passing the expected class and type values which are to be found.
*/
/*@
@ requires len >= 0;
@ requires ((len > 0) && (buf != \null)) ==> \valid_read(buf + (0 .. (len - 1)));
@ requires \valid(eaten);
@ requires \separated(eaten, buf+(..));
@ ensures \result < 0 || \result == 0;
@ ensures (\result == 0) ==> (2 < *eaten <= len);
@ ensures (len == 0) ==> \result < 0;
@ ensures (buf == \null) ==> \result < 0;
@ assigns *eaten;
@*/
static int parse_integer(const u8 *buf, u16 len,
tag_class exp_class, u32 exp_type,
u16 *eaten)
{
u16 hdr_len = 0;
u16 data_len = 0;
int ret;
if ((buf == NULL) || (len == 0)) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
ret = parse_id_len(buf, len, exp_class, exp_type, &hdr_len, &data_len);
if (ret) {
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
buf += hdr_len;
/*
* Regarding integer encoding, 8.3.1 of X.690 has "The contents octets
* shall consist of one or more octets".
*/
if (data_len == 0) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/*
* On integer encoding, 8.3.2 of x.690 has "If the contents octets of
* an integer value encoding consist of more than one octet, then the
* bits of the first octet and bit 8 of the second octet:
*
* a) shall not all be ones; and
* b) shall not all be zero.
*/
if (data_len > 1) {
if ((buf[0] == 0) && ((buf[1] & 0x80) == 0)) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
if ((buf[0] == 0xff) && (buf[1] & 0x80)) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
}
*eaten = hdr_len + data_len;
ret = 0;
out:
return ret;
}
/*
* Implements a function for parsing booleans as described in section 8.2
* of X.690. When encoded in DER, a boolean is a 3 bytes elements which
* can take a value of:
*
* FALSE : { 0x01, 0x01, 0x00 }
* TRUE : { 0x01, 0x01, 0xff }
*
*/
/*@
@ requires len >= 0;
@ requires ((len > 0) && (buf != \null)) ==> \valid_read(buf + (0 .. (len - 1)));
@ requires \separated(eaten, buf+(..));
@ requires \valid(eaten);
@ ensures \result < 0 || \result == 0;
@ ensures (\result == 0) ==> (*eaten <= len);
@ ensures (len == 0) ==> \result < 0;
@ ensures (buf == \null) ==> \result < 0;
@ assigns *eaten;
@*/
static int parse_boolean(const u8 *buf, u16 len, u16 *eaten)
{
int ret;
if ((buf == NULL) || (len == 0)) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
if (len < 3) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
if ((buf[0] != 0x01) || (buf[1] != 0x01)) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
switch (buf[2]) {
case 0x00: /* FALSE */
case 0xff: /* TRUE */
break;
default:
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
break;
}
*eaten = 3;
ret = 0;
out:
return ret;
}
/*
* The implementation is based on 4.1 and 4.1.2.1 of RFC5280 + Section
* 8.3 of X.690. The version field is mandatory and it is encoded as
* an integer. As we only limit ourselves to version 3 certificates
* (i.e. a value of 0x02 for the integer encoding the version) and the
* version field is marked EXPLICIT in the definition, this makes things
* pretty simple.
*
* version [0] EXPLICIT Version DEFAULT v1,
*/
/*@
@ requires len >= 0;
@ requires ((len > 0) && (buf != \null)) ==> \valid_read(buf + (0 .. (len - 1)));
@ requires \valid(eaten);
@ requires \separated(eaten, buf+(..));
@ ensures \result < 0 || \result == 0;
@ ensures (\result == 0) ==> (*eaten <= len);
@ ensures (len == 0) ==> \result < 0;
@ ensures (buf == \null) ==> \result < 0;
@ assigns *eaten;
@*/
static int parse_x509_Version(const u8 *buf, u16 len, u16 *eaten)
{
u16 data_len = 0;
u16 hdr_len = 0;
int ret;
if ((buf == NULL) || (len == 0)) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
ret = parse_explicit_id_len(buf, len, 0,
CLASS_UNIVERSAL, ASN1_TYPE_INTEGER,
&hdr_len, &data_len);
if (ret) {
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
buf += hdr_len;
/*
* As the value we expect for the integer is 0x02 (version 3),
* data_len must be 1.
*/
if (data_len != 1) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
if (buf[0] != 0x02) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
*eaten = hdr_len + data_len;
ret = 0;
out:
return ret;
}
/*
* used for CertificateSerialNumber (in tbsCertificate, AKI, etc). As the
* underlying integer might be used with context specific class and types,
* those two elements are passed to the function and verified to match in
* given encoding.
*
* CertificateSerialNumber ::= INTEGER
*
*/
#define MAX_SERIAL_NUM_LEN 22 /* w/ header */
/*@
@ requires len >= 0;
@ requires ((len > 0) && (buf != \null)) ==> \valid_read(buf + (0 .. (len - 1)));
@ requires \valid(eaten);
@ requires \separated(eaten, buf+(..));
@ ensures \result < 0 || \result == 0;
@ ensures (\result == 0) ==> (*eaten <= len);
@ ensures (len == 0) ==> \result < 0;
@ ensures (buf == \null) ==> \result < 0;
@ assigns *eaten;
@*/
static int parse_CertificateSerialNumber(const u8 *buf, u16 len,
tag_class exp_class, u32 exp_type,
u16 *eaten)
{
u16 parsed = 0;
int ret;
if ((buf == NULL) || (len == 0)) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/* Verify the integer is DER-encoded as it should */
ret = parse_integer(buf, len, exp_class, exp_type, &parsed);
if (ret) {
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/*
* We now have the guarantee the integer has the following format:
* [2 bytes for t/c and len][(parsed - 2) bytes for encoded value]
*/
/*
* Serial is expected not to be 0. Because we are guaranteed with the
* check above to deal with a DER encoded integer, 0 would be encoded
* on exactly 3 bytes (2 for header and 1 for the value), the last one
* being 0.
*/
if ((parsed == 3) && (buf[2] == 0)) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/*
* serialNumber value is expected to be at most 20 bytes long, which
* makes 22 bytes for the whole structure (if we include the associated
* two bytes header (a length of 20 is encoded on a single byte of
* header following the type/class byte.
*/
if (parsed > MAX_SERIAL_NUM_LEN) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/* ... and be positive */
if (buf[2] & 0x80) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
*eaten = parsed;
ret = 0;
out:
return ret;
}
typedef struct {
const u8 *crv_name;
const u8 *crv_printable_oid;
const u8 *crv_der_oid;
const u8 crv_der_oid_len;
const u16 crv_order_bit_len;
} _curve;
typedef struct {
const _curve *curve_param; /* pointer to specific curve structure */
const u8 *null_param; /* pointer to null_encoded_val */
int ecdsa_no_param; /* 1 when ECDSA has no param */
int unparsed_param; /* 1 when generic param was left unparsed */
} alg_param;
static int parse_sig_ecdsa(const u8 *buf, u16 len, u16 *eaten);
static int parse_algoid_params_ecdsa_with(const u8 *buf, u16 len, alg_param *param);
static int parse_algoid_params_ecPublicKey(const u8 *buf, u16 len, alg_param *param);
static int parse_subjectpubkey_ec(const u8 *buf, u16 len, alg_param *param);
static int parse_subjectpubkey_rsa(const u8 *buf, u16 len, alg_param *param);
#ifdef TEMPORARY_BADALGS
static int parse_sig_generic(const u8 *buf, u16 len, u16 *eaten);
static int parse_algoid_params_generic(const u8 *buf, u16 len, alg_param *param);
static int parse_algoid_params_rsa(const u8 *buf, u16 len, alg_param *param);
#endif
typedef struct {
const u8 *alg_name;
const u8 *alg_printable_oid;
const u8 *alg_der_oid;
const u8 alg_der_oid_len;
const u8 alg_type;
int (*parse_sig)(const u8 *buf, u16 len, u16 *eaten);
int (*parse_subjectpubkey)(const u8 *buf, u16 len, alg_param *param);
int (*parse_algoid_params)(const u8 *buf, u16 len, alg_param *param);
} _alg_id;
/*
* The algorithmIdentifier structure is used at different location
* in a certificate for different kind of algorithms:
*
* - in signature and signatureAlgorithm fields, it describes a
* signature algorithm.
* - in subjectPublicKeyInfo, it describes a public key
* algorithm.
*
* For that reason, we need to be able to tell for a known algorithm
* if it is either a signature or public key algorithm.
*/
typedef enum {
ALG_INVALID = 0x00, /* neither sig nor pubkey */
ALG_SIG = 0x01,
ALG_PUBKEY = 0x02,
} alg_types;
static const u8 _ecdsa_sha1_name[] = "ecdsa-with-SHA1";
static const u8 _ecdsa_sha1_printable_oid[] = "1.2.840.10045.4.1";
static const u8 _ecdsa_sha1_der_oid[] = {0x06, 0x07, 0x2a, 0x86, 0x48,
0xce, 0x3d, 0x04, 0x01 };
static const _alg_id _ecdsa_sha1_alg = {
.alg_name = _ecdsa_sha1_name,
.alg_printable_oid = _ecdsa_sha1_printable_oid,
.alg_der_oid = _ecdsa_sha1_der_oid,
.alg_der_oid_len = sizeof(_ecdsa_sha1_der_oid),
.alg_type = ALG_SIG,
.parse_sig = parse_sig_ecdsa,
.parse_subjectpubkey = NULL,
.parse_algoid_params = parse_algoid_params_ecdsa_with,
};
static const u8 _ecdsa_sha224_name[] = "ecdsa-with-SHA224";
static const u8 _ecdsa_sha224_printable_oid[] = "1.2.840.10045.4.3.1";
static const u8 _ecdsa_sha224_der_oid[] = {0x06, 0x08, 0x2a, 0x86, 0x48,
0xce, 0x3d, 0x04, 0x03, 0x01 };
static const _alg_id _ecdsa_sha224_alg = {
.alg_name = _ecdsa_sha224_name,
.alg_printable_oid = _ecdsa_sha224_printable_oid,
.alg_der_oid = _ecdsa_sha224_der_oid,
.alg_der_oid_len = sizeof(_ecdsa_sha224_der_oid),
.alg_type = ALG_SIG,
.parse_sig = parse_sig_ecdsa,
.parse_subjectpubkey = NULL,
.parse_algoid_params = parse_algoid_params_ecdsa_with,
};
static const u8 _ecdsa_sha256_name[] = "ecdsa-with-SHA256";
static const u8 _ecdsa_sha256_printable_oid[] = "1.2.840.10045.4.3.2";
static const u8 _ecdsa_sha256_der_oid[] = {0x06, 0x08, 0x2a, 0x86, 0x48,
0xce, 0x3d, 0x04, 0x03, 0x02 };
static const _alg_id _ecdsa_sha256_alg = {
.alg_name = _ecdsa_sha256_name,
.alg_printable_oid = _ecdsa_sha256_printable_oid,
.alg_der_oid = _ecdsa_sha256_der_oid,
.alg_der_oid_len = sizeof(_ecdsa_sha256_der_oid),
.alg_type = ALG_SIG,
.parse_sig = parse_sig_ecdsa,
.parse_subjectpubkey = NULL,
.parse_algoid_params = parse_algoid_params_ecdsa_with,
};
static const u8 _ecdsa_sha384_name[] = "ecdsa-with-SHA384";
static const u8 _ecdsa_sha384_printable_oid[] = "1.2.840.10045.4.3.3";
static const u8 _ecdsa_sha384_der_oid[] = {0x06, 0x08, 0x2a, 0x86, 0x48,
0xce, 0x3d, 0x04, 0x03, 0x03 };
static const _alg_id _ecdsa_sha384_alg = {
.alg_name = _ecdsa_sha384_name,
.alg_printable_oid = _ecdsa_sha384_printable_oid,
.alg_der_oid = _ecdsa_sha384_der_oid,
.alg_der_oid_len = sizeof(_ecdsa_sha384_der_oid),
.alg_type = ALG_SIG,
.parse_sig = parse_sig_ecdsa,
.parse_subjectpubkey = NULL,
.parse_algoid_params = parse_algoid_params_ecdsa_with,
};
static const u8 _ecdsa_sha512_name[] = "ecdsa-with-SHA512";
static const u8 _ecdsa_sha512_printable_oid[] = "1.2.840.10045.4.3.4";
static const u8 _ecdsa_sha512_der_oid[] = {0x06, 0x08, 0x2a, 0x86, 0x48,
0xce, 0x3d, 0x04, 0x03, 0x04 };
static const _alg_id _ecdsa_sha512_alg = {
.alg_name = _ecdsa_sha512_name,
.alg_printable_oid = _ecdsa_sha512_printable_oid,
.alg_der_oid = _ecdsa_sha512_der_oid,
.alg_der_oid_len = sizeof(_ecdsa_sha512_der_oid),
.alg_type = ALG_SIG,
.parse_sig = parse_sig_ecdsa,
.parse_subjectpubkey = NULL,
.parse_algoid_params = parse_algoid_params_ecdsa_with,
};
static const u8 _ecpublickey_name[] = "ecPublicKey";
static const u8 _ecpublickey_printable_oid[] = "1.2.840.10045.2.1";
static const u8 _ecpublickey_der_oid[] = { 0x06, 0x07, 0x2a, 0x86, 0x48,
0xce, 0x3d, 0x02, 0x01 };
static const _alg_id _ecpublickey_alg = {
.alg_name = _ecpublickey_name,
.alg_printable_oid = _ecpublickey_printable_oid,
.alg_der_oid = _ecpublickey_der_oid,
.alg_der_oid_len = sizeof(_ecpublickey_der_oid),
.alg_type = ALG_PUBKEY,
.parse_sig = NULL,
.parse_subjectpubkey = parse_subjectpubkey_ec,
.parse_algoid_params = parse_algoid_params_ecPublicKey,
};
#ifdef TEMPORARY_BADALGS
static const u8 _rsa_md2_name[] = "md2WithRSAEncryption";
static const u8 _rsa_md2_printable_oid[] = "1.2.840.113549.1.1.2";
static const u8 _rsa_md2_der_oid[] = {0x06, 0x09, 0x2a, 0x86, 0x48, 0x86,
0xf7, 0x0d, 0x01, 0x01, 0x02 };
static const _alg_id _rsa_md2_alg = {
.alg_name = _rsa_md2_name,
.alg_printable_oid = _rsa_md2_printable_oid,
.alg_der_oid = _rsa_md2_der_oid,
.alg_der_oid_len = sizeof(_rsa_md2_der_oid),
.alg_type = ALG_SIG,
.parse_sig = parse_sig_generic,
.parse_subjectpubkey = NULL,
.parse_algoid_params = parse_algoid_params_generic,
};
static const u8 _rsa_md4_name[] = "md4WithRSAEncryption";
static const u8 _rsa_md4_printable_oid[] = "1.2.840.113549.1.1.3";
static const u8 _rsa_md4_der_oid[] = {0x06, 0x09, 0x2a, 0x86, 0x48, 0x86,
0xf7, 0x0d, 0x01, 0x01, 0x03 };
static const _alg_id _rsa_md4_alg = {
.alg_name = _rsa_md4_name,
.alg_printable_oid = _rsa_md4_printable_oid,
.alg_der_oid = _rsa_md4_der_oid,
.alg_der_oid_len = sizeof(_rsa_md4_der_oid),
.alg_type = ALG_SIG,
.parse_sig = parse_sig_generic,
.parse_subjectpubkey = NULL,
.parse_algoid_params = parse_algoid_params_generic,
};
static const u8 _rsa_md5_name[] = "md5WithRSAEncryption";
static const u8 _rsa_md5_printable_oid[] = "1.2.840.113549.1.1.4";
static const u8 _rsa_md5_der_oid[] = {0x06, 0x09, 0x2a, 0x86, 0x48, 0x86,
0xf7, 0x0d, 0x01, 0x01, 0x04 };
static const _alg_id _rsa_md5_alg = {
.alg_name = _rsa_md5_name,
.alg_printable_oid = _rsa_md5_printable_oid,
.alg_der_oid = _rsa_md5_der_oid,
.alg_der_oid_len = sizeof(_rsa_md5_der_oid),
.alg_type = ALG_SIG,
.parse_sig = parse_sig_generic,
.parse_subjectpubkey = NULL,
.parse_algoid_params = parse_algoid_params_rsa,
};
static const u8 _rsa_sha1_name[] = "sha1WithRSAEncryption";
static const u8 _rsa_sha1_printable_oid[] = "1.2.840.113549.1.1.5";
static const u8 _rsa_sha1_der_oid[] = {0x06, 0x09, 0x2a, 0x86, 0x48, 0x86,
0xf7, 0x0d, 0x01, 0x01, 0x05 };
static const _alg_id _rsa_sha1_alg = {
.alg_name = _rsa_sha1_name,
.alg_printable_oid = _rsa_sha1_printable_oid,
.alg_der_oid = _rsa_sha1_der_oid,
.alg_der_oid_len = sizeof(_rsa_sha1_der_oid),
.alg_type = ALG_SIG,
.parse_sig = parse_sig_generic,
.parse_subjectpubkey = NULL,
.parse_algoid_params = parse_algoid_params_rsa,
};
static const u8 _rsa_sha256_name[] = "sha256WithRSAEncryption";
static const u8 _rsa_sha256_printable_oid[] = "1.2.840.113549.1.1.11";
static const u8 _rsa_sha256_der_oid[] = {0x06, 0x09, 0x2a, 0x86, 0x48, 0x86,
0xf7, 0x0d, 0x01, 0x01, 0x0b };
static const _alg_id _rsa_sha256_alg = {
.alg_name = _rsa_sha256_name,
.alg_printable_oid = _rsa_sha256_printable_oid,
.alg_der_oid = _rsa_sha256_der_oid,
.alg_der_oid_len = sizeof(_rsa_sha256_der_oid),
.alg_type = ALG_SIG,
.parse_sig = parse_sig_generic,
.parse_subjectpubkey = NULL,
.parse_algoid_params = parse_algoid_params_generic,
};
static const u8 _rsa_sha224_name[] = "sha224WithRSAEncryption";
static const u8 _rsa_sha224_printable_oid[] = "1.2.840.113549.1.1.14";
static const u8 _rsa_sha224_der_oid[] = {0x06, 0x09, 0x2a, 0x86, 0x48, 0x86,
0xf7, 0x0d, 0x01, 0x01, 0x0e };
static const _alg_id _rsa_sha224_alg = {
.alg_name = _rsa_sha224_name,
.alg_printable_oid = _rsa_sha224_printable_oid,
.alg_der_oid = _rsa_sha224_der_oid,
.alg_der_oid_len = sizeof(_rsa_sha224_der_oid),
.alg_type = ALG_SIG,
.parse_sig = parse_sig_generic,
.parse_subjectpubkey = NULL,
.parse_algoid_params = parse_algoid_params_generic,
};
static const u8 _rsa_sha384_name[] = "sha384WithRSAEncryption";
static const u8 _rsa_sha384_printable_oid[] = "1.2.840.113549.1.1.12";
static const u8 _rsa_sha384_der_oid[] = {0x06, 0x09, 0x2a, 0x86, 0x48, 0x86,
0xf7, 0x0d, 0x01, 0x01, 0x0c };
static const _alg_id _rsa_sha384_alg = {
.alg_name = _rsa_sha384_name,
.alg_printable_oid = _rsa_sha384_printable_oid,
.alg_der_oid = _rsa_sha384_der_oid,
.alg_der_oid_len = sizeof(_rsa_sha384_der_oid),
.alg_type = ALG_SIG,
.parse_sig = parse_sig_generic,
.parse_subjectpubkey = NULL,
.parse_algoid_params = parse_algoid_params_generic,
};
static const u8 _rsa_sha512_name[] = "sha512WithRSAEncryption";
static const u8 _rsa_sha512_printable_oid[] = "1.2.840.113549.1.1.13";
static const u8 _rsa_sha512_der_oid[] = {0x06, 0x09, 0x2a, 0x86, 0x48, 0x86,
0xf7, 0x0d, 0x01, 0x01, 0x0d };
static const _alg_id _rsa_sha512_alg = {
.alg_name = _rsa_sha512_name,
.alg_printable_oid = _rsa_sha512_printable_oid,
.alg_der_oid = _rsa_sha512_der_oid,
.alg_der_oid_len = sizeof(_rsa_sha512_der_oid),
.alg_type = ALG_SIG,
.parse_sig = parse_sig_generic,
.parse_subjectpubkey = NULL,
.parse_algoid_params = parse_algoid_params_generic,
};
static const u8 _dsa_sha1_name[] = "dsaWithSHA1";
static const u8 _dsa_sha1_printable_oid[] = "1.3.14.3.2.27";
static const u8 _dsa_sha1_der_oid[] = {0x06, 0x07, 0x2a, 0x86, 0x48,
0xce, 0x38, 0x04, 0x03 };
static const _alg_id _dsa_sha1_alg = {
.alg_name = _dsa_sha1_name,
.alg_printable_oid = _dsa_sha1_printable_oid,
.alg_der_oid = _dsa_sha1_der_oid,
.alg_der_oid_len = sizeof(_dsa_sha1_der_oid),
.alg_type = ALG_SIG,
.parse_sig = parse_sig_generic,
.parse_subjectpubkey = NULL,
.parse_algoid_params = parse_algoid_params_generic,
};
static const u8 _pkcs1_rsaEncryption_name[] = "PKCS-1 rsaEncryption";
static const u8 _pkcs1_rsaEncryption_printable_oid[] = "1.2.840.113549.1.1.1";
static const u8 _pkcs1_rsaEncryption_der_oid[] = { 0x06, 0x09, 0x2a, 0x86,
0x48, 0x86, 0xf7, 0x0d,
0x01, 0x01, 0x01 };
static const _alg_id _pkcs1_rsaEncryption_alg = {
.alg_name = _pkcs1_rsaEncryption_name,
.alg_printable_oid = _pkcs1_rsaEncryption_printable_oid,
.alg_der_oid = _pkcs1_rsaEncryption_der_oid,
.alg_der_oid_len = sizeof(_pkcs1_rsaEncryption_der_oid),
.alg_type = ALG_PUBKEY,
.parse_sig = NULL,
.parse_subjectpubkey = parse_subjectpubkey_rsa,
.parse_algoid_params = parse_algoid_params_rsa,
};
static const u8 _rsassapss_name[] = "RSASSA-PSS";
static const u8 _rsassapss_printable_oid[] = "1.2.840.113549.1.1.10";
static const u8 _rsassapss_der_oid[] = { 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86,
0xf7, 0x0d, 0x01, 0x01, 0x0a };
static const _alg_id _rsassapss_alg = {
.alg_name = _rsassapss_name,
.alg_printable_oid = _rsassapss_printable_oid,
.alg_der_oid = _rsassapss_der_oid,
.alg_der_oid_len = sizeof(_rsassapss_der_oid),
.alg_type = ALG_SIG,
.parse_sig = parse_sig_generic,
.parse_subjectpubkey = NULL,
.parse_algoid_params = parse_algoid_params_generic,
};
static const u8 _odd1_name[] = "oiw-sha-1WithRSAEncryption";
static const u8 _odd1_printable_oid[] = "1.3.14.3.2.29";
static const u8 _odd1_der_oid[] = { 0x06, 0x05, 0x2b, 0x0e,
0x03, 0x02, 0x1d };
static const _alg_id _odd1_alg = {
.alg_name = _odd1_name,
.alg_printable_oid = _odd1_printable_oid,
.alg_der_oid = _odd1_der_oid,
.alg_der_oid_len = sizeof(_odd1_der_oid),
.alg_type = ALG_SIG,
.parse_sig = parse_sig_generic,
.parse_subjectpubkey = NULL,
.parse_algoid_params = parse_algoid_params_generic,
};
static const u8 _odd2_name[] = "oiw-shaWithRSASignature";
static const u8 _odd2_printable_oid[] = "1.3.14.3.2.15";
static const u8 _odd2_der_oid[] = { 0x06, 0x05, 0x2b, 0x0e,
0x03, 0x02, 0x0f };
static const _alg_id _odd2_alg = {
.alg_name = _odd2_name,
.alg_printable_oid = _odd2_printable_oid,
.alg_der_oid = _odd2_der_oid,
.alg_der_oid_len = sizeof(_odd2_der_oid),
.alg_type = ALG_SIG,
.parse_sig = parse_sig_generic,
.parse_subjectpubkey = NULL,
.parse_algoid_params = parse_algoid_params_generic,
};
static const u8 _odd3_name[] = "oiw-SHA-1";
static const u8 _odd3_printable_oid[] = "1.3.14.3.2.26";
static const u8 _odd3_der_oid[] = { 0x06, 0x05, 0x2b, 0x0e,
0x03, 0x02, 0x1a };
static const _alg_id _odd3_alg = {
.alg_name = _odd3_name,
.alg_printable_oid = _odd3_printable_oid,
.alg_der_oid = _odd3_der_oid,
.alg_der_oid_len = sizeof(_odd3_der_oid),
.alg_type = ALG_INVALID,
.parse_sig = parse_sig_generic,
.parse_subjectpubkey = NULL,
.parse_algoid_params = parse_algoid_params_generic,
};
static const u8 _odd4_name[] = "oiw-dsaWithSHA1";
static const u8 _odd4_printable_oid[] = "1.3.14.3.2.27";
static const u8 _odd4_der_oid[] = { 0x06, 0x05, 0x2b, 0x0e,
0x03, 0x02, 0x1b };
static const _alg_id _odd4_alg = {
.alg_name = _odd4_name,
.alg_printable_oid = _odd4_printable_oid,
.alg_der_oid = _odd4_der_oid,
.alg_der_oid_len = sizeof(_odd4_der_oid),
.alg_type = ALG_SIG,
.parse_sig = parse_sig_generic,
.parse_subjectpubkey = NULL,
.parse_algoid_params = parse_algoid_params_generic,
};
static const u8 _gost1_name[] = "gostR3411-94-with-gostR3410-2001";
static const u8 _gost1_printable_oid[] = "1.2.643.2.2.3";
static const u8 _gost1_der_oid[] = { 0x06, 0x06, 0x2a, 0x85,
0x03, 0x02, 0x02, 0x03 };
static const _alg_id _gost1_alg = {
.alg_name = _gost1_name,
.alg_printable_oid = _gost1_printable_oid,
.alg_der_oid = _gost1_der_oid,
.alg_der_oid_len = sizeof(_gost1_der_oid),
.alg_type = ALG_SIG,
.parse_sig = parse_sig_generic,
.parse_subjectpubkey = NULL,
.parse_algoid_params = parse_algoid_params_generic,
};
static const u8 _gost2_name[] = "gostR3411-94-with-gostR3410-94";
static const u8 _gost2_printable_oid[] = "1.2.643.2.2.4";
static const u8 _gost2_der_oid[] = { 0x06, 0x06, 0x2a, 0x85,
0x03, 0x02, 0x02, 0x04 };
static const _alg_id _gost2_alg = {
.alg_name = _gost2_name,
.alg_printable_oid = _gost2_printable_oid,
.alg_der_oid = _gost2_der_oid,
.alg_der_oid_len = sizeof(_gost2_der_oid),
.alg_type = ALG_SIG,
.parse_sig = parse_sig_generic,
.parse_subjectpubkey = NULL,
.parse_algoid_params = parse_algoid_params_generic,
};
static const u8 _rsa_ripemd160_name[] = "rsaSignatureWithripemd160";
static const u8 _rsa_ripemd160_printable_oid[] = "1.3.36.3.3.1.2";
static const u8 _rsa_ripemd160_der_oid[] = { 0x06, 0x06, 0x2b, 0x24,
0x03, 0x03, 0x01, 0x02 };
static const _alg_id _rsa_ripemd160_alg = {
.alg_name = _rsa_ripemd160_name,
.alg_printable_oid = _rsa_ripemd160_printable_oid,
.alg_der_oid = _rsa_ripemd160_der_oid,
.alg_der_oid_len = sizeof(_rsa_ripemd160_der_oid),
.alg_type = ALG_SIG,
.parse_sig = parse_sig_generic,
.parse_subjectpubkey = NULL,
.parse_algoid_params = parse_algoid_params_generic,
};
static const u8 _weird1_name[] = "weird1-avest-plc";
static const u8 _weird1_printable_oid[] = "1.3.6.1.4.1.12656.1.36";
static const u8 _weird1_der_oid[] = { 0x06, 0x09, 0x2b, 0x06, 0x01, 0x04,
0x01, 0xe2, 0x70, 0x01, 0x24 };
static const _alg_id _weird1_alg = {
.alg_name = _weird1_name,
.alg_printable_oid = _weird1_printable_oid,
.alg_der_oid = _weird1_der_oid,
.alg_der_oid_len = sizeof(_weird1_der_oid),
.alg_type = ALG_SIG,
.parse_sig = parse_sig_generic,
.parse_subjectpubkey = NULL,
.parse_algoid_params = parse_algoid_params_generic,
};
static const u8 _weird2_name[] = "weird2-avest-plc";
static const u8 _weird2_printable_oid[] = "1.3.6.1.4.1.12656.1.40";
static const u8 _weird2_der_oid[] = { 0x06, 0x09, 0x2b, 0x06, 0x01, 0x04,
0x01, 0xe2, 0x70, 0x01, 0x28 };
static const _alg_id _weird2_alg = {
.alg_name = _weird2_name,
.alg_printable_oid = _weird2_printable_oid,
.alg_der_oid = _weird2_der_oid,
.alg_der_oid_len = sizeof(_weird2_der_oid),
.alg_type = ALG_SIG,
.parse_sig = parse_sig_generic,
.parse_subjectpubkey = NULL,
.parse_algoid_params = parse_algoid_params_generic,
};
static const u8 _weird3_name[] = "weird3-avest-plc";
static const u8 _weird3_printable_oid[] = "1.3.6.1.4.1.12656.1.43";
static const u8 _weird3_der_oid[] = { 0x06, 0x09, 0x2b, 0x06, 0x01, 0x04,
0x01, 0xe2, 0x70, 0x01, 0x2b };
static const _alg_id _weird3_alg = {
.alg_name = _weird3_name,
.alg_printable_oid = _weird3_printable_oid,
.alg_der_oid = _weird3_der_oid,
.alg_der_oid_len = sizeof(_weird3_der_oid),
.alg_type = ALG_SIG,
.parse_sig = parse_sig_generic,
.parse_subjectpubkey = NULL,
.parse_algoid_params = parse_algoid_params_generic,
};
#endif
static const _alg_id *known_algs[] = {
&_ecdsa_sha1_alg,
&_ecdsa_sha224_alg,
&_ecdsa_sha256_alg,
&_ecdsa_sha384_alg,
&_ecdsa_sha512_alg,
&_ecpublickey_alg,
#ifdef TEMPORARY_BADALGS
&_rsa_md2_alg,
&_rsa_md4_alg,
&_rsa_md5_alg,
&_rsa_sha1_alg,
&_rsa_sha224_alg,
&_rsa_sha256_alg,
&_rsa_sha384_alg,
&_rsa_sha512_alg,
&_dsa_sha1_alg,
&_pkcs1_rsaEncryption_alg,
&_rsassapss_alg,
&_odd1_alg,
&_odd2_alg,
&_odd3_alg,
&_odd4_alg,
&_gost1_alg,
&_gost2_alg,
&_rsa_ripemd160_alg,
&_weird1_alg,
&_weird2_alg,
&_weird3_alg,
#endif
};
#define NUM_KNOWN_ALGS (sizeof(known_algs) / sizeof(known_algs[0]))
/*@
@ requires len >= 0;
@ requires ((len > 0) && (buf != \null)) ==> \valid_read(buf + (0 .. (len - 1)));
@ requires \valid(param);
@ requires \separated(param,buf+(..));
@ ensures \result < 0 || \result == 0;
@ ensures ((buf != \null) && (len == 0)) ==> \result == 0;
@ ensures (len != 0) ==> \result < 0;
@ ensures (buf == \null) ==> \result < 0;
@ ensures \result == 0 ==> param->ecdsa_no_param == 1;
@ assigns param->ecdsa_no_param;
@*/
static int parse_algoid_params_ecdsa_with(const u8 *buf, u16 len, alg_param *param)
{
int ret;
/*
* Based on the OID, specific parameters may follow. As we currently
* only support ECDSA-based signature algorithms and RFC5758 specifies
* those come w/o any additional parameters, we expect data_len to
* exactly match oid_len.
*
* Section 3.2 of RFC 5758 reads:
*
* When the ecdsa-with-SHA224, ecdsa-with-SHA256, ecdsa-with-SHA384,
* or ecdsa-with-SHA512 algorithm identifier appears in the algorithm
* field as an AlgorithmIdentifier, the encoding MUST omit the
* parameters field. That is, the AlgorithmIdentifier SHALL be a
* SEQUENCE of one component, the OID ecdsa-with-SHA224,
* ecdsa-with-SHA256, ecdsa-with-SHA384, or ecdsa-with-SHA512.
*/
if ((buf == NULL) || (len != 0)) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
} else {
param->ecdsa_no_param = 1;
ret = 0;
}
return ret;
}
static const u8 _curve_secp256r1_name[] = "secp256r1";
static const u8 _curve_secp256r1_printable_oid[] = "1.2.840.10045.3.1.7";
static const u8 _curve_secp256r1_der_oid[] = { 0x06, 0x08, 0x2a, 0x86, 0x48,
0xce, 0x3d, 0x03, 0x01, 0x07 };
static const _curve _curve_secp256r1 = {
.crv_name = _curve_secp256r1_name,
.crv_printable_oid = _curve_secp256r1_printable_oid,
.crv_der_oid = _curve_secp256r1_der_oid,
.crv_der_oid_len = sizeof(_curve_secp256r1_der_oid),
.crv_order_bit_len = 256,
};
static const u8 _curve_secp384r1_name[] = "secp384r1";
static const u8 _curve_secp384r1_printable_oid[] = "1.3.132.0.34";
static const u8 _curve_secp384r1_der_oid[] = { 0x06, 0x05, 0x2b, 0x81,
0x04, 0x00, 0x22 };
static const _curve _curve_secp384r1 = {
.crv_name = _curve_secp384r1_name,
.crv_printable_oid = _curve_secp384r1_printable_oid,
.crv_der_oid = _curve_secp384r1_der_oid,
.crv_der_oid_len = sizeof(_curve_secp384r1_der_oid),
.crv_order_bit_len = 384,
};
static const u8 _curve_secp521r1_name[] = "secp521r1";
static const u8 _curve_secp521r1_printable_oid[] = "1.3.132.0.35";
static const u8 _curve_secp521r1_der_oid[] = { 0x06, 0x05, 0x2b, 0x81,
0x04, 0x00, 0x23 };
static const _curve _curve_secp521r1 = {
.crv_name = _curve_secp521r1_name,
.crv_printable_oid = _curve_secp521r1_printable_oid,
.crv_der_oid = _curve_secp521r1_der_oid,
.crv_der_oid_len = sizeof(_curve_secp521r1_der_oid),
.crv_order_bit_len = 521,
};
static const u8 _curve_brainpoolP256R1_name[] = "brainpoolP256R1";
static const u8 _curve_brainpoolP256R1_printable_oid[] = "1.3.36.3.3.2.8.1.1.7";
static const u8 _curve_brainpoolP256R1_der_oid[] = { 0x06, 0x05, 0x2b, 0x24,
0x03, 0x03, 0x02, 0x08,
0x01, 0x01, 0x07 };
static const _curve _curve_brainpoolP256R1 = {
.crv_name = _curve_brainpoolP256R1_name,
.crv_printable_oid = _curve_brainpoolP256R1_printable_oid,
.crv_der_oid = _curve_brainpoolP256R1_der_oid,
.crv_der_oid_len = sizeof(_curve_brainpoolP256R1_der_oid),
.crv_order_bit_len = 256,
};
static const u8 _curve_brainpoolP384R1_name[] = "brainpoolP384R1";
static const u8 _curve_brainpoolP384R1_printable_oid[] = "1.3.36.3.3.2.8.1.1.11";
static const u8 _curve_brainpoolP384R1_der_oid[] = { 0x06, 0x05, 0x2b, 0x24,
0x03, 0x03, 0x02, 0x08,
0x01, 0x01, 0x0b };
static const _curve _curve_brainpoolP384R1 = {
.crv_name = _curve_brainpoolP384R1_name,
.crv_printable_oid = _curve_brainpoolP384R1_printable_oid,
.crv_der_oid = _curve_brainpoolP384R1_der_oid,
.crv_der_oid_len = sizeof(_curve_brainpoolP384R1_der_oid),
.crv_order_bit_len = 384,
};
static const u8 _curve_brainpoolP512R1_name[] = "brainpoolP512R1";
static const u8 _curve_brainpoolP512R1_printable_oid[] = "1.3.36.3.3.2.8.1.1.13";
static const u8 _curve_brainpoolP512R1_der_oid[] = { 0x06, 0x05, 0x2b, 0x24,
0x03, 0x03, 0x02, 0x08,
0x01, 0x01, 0x0d };
static const _curve _curve_brainpoolP512R1 = {
.crv_name = _curve_brainpoolP512R1_name,
.crv_printable_oid = _curve_brainpoolP512R1_printable_oid,
.crv_der_oid = _curve_brainpoolP512R1_der_oid,
.crv_der_oid_len = sizeof(_curve_brainpoolP512R1_der_oid),
.crv_order_bit_len = 512,
};
static const _curve *known_curves[] = {
&_curve_secp256r1,
&_curve_secp384r1,
&_curve_secp521r1,
&_curve_brainpoolP256R1,
&_curve_brainpoolP384R1,
&_curve_brainpoolP512R1,
};
#define NUM_KNOWN_CURVES (sizeof(known_curves) / sizeof(known_curves[0]))
/*@
@ requires len >= 0;
@ requires ((len > 0) && (buf != NULL)) ==> \valid_read(buf + (0 .. (len - 1)));
@ ensures (\result != NULL) ==> \exists integer i ; 0 <= i < NUM_KNOWN_CURVES && \result == known_curves[i];
@ ensures (len == 0) ==> \result == NULL;
@ ensures (buf == NULL) ==> \result == NULL;
@ assigns \nothing;
@*/
static _curve const * find_curve_by_oid(const u8 *buf, u16 len)
{
const _curve *found = NULL;
const _curve *cur = NULL;
u8 k;
if ((buf == NULL) || (len == 0)) {
goto out;
}
/*@
@ loop invariant 0 <= k <= NUM_KNOWN_CURVES;
@ loop invariant found == NULL;
@ loop assigns cur, found, k;
@ loop variant (NUM_KNOWN_CURVES - k);
@*/
for (k = 0; k < NUM_KNOWN_CURVES; k++) {
int ret;
cur = known_curves[k];
/*@ assert cur == known_curves[k];*/
if (cur->crv_der_oid_len != len) {
continue;
}
/*@ assert \valid_read(buf + (0 .. (len - 1))); @*/
ret = !bufs_differ(cur->crv_der_oid, buf, cur->crv_der_oid_len);
if (ret) {
found = cur;
break;
}
}
out:
return found;
}
static const u8 null_encoded_val[] = { 0x05, 0x00 };
/*@
@ requires len >= 0;
@ requires ((len > 0) && (buf != \null)) ==> \valid_read(buf + (0 .. (len - 1)));
@ requires \valid(param);
@ requires \separated(param,buf+(..));
@ ensures (len == 0) ==> \result < 0;
@ ensures \result < 0 || \result == 0;
@ ensures (\result == 0) ==> \exists integer i ; 0 <= i < NUM_KNOWN_CURVES && param->curve_param == known_curves[i];
@ assigns param->curve_param;
@*/
static int parse_algoid_params_ecPublicKey(const u8 *buf, u16 len, alg_param *param)
{
const _curve *curve = NULL;
u16 oid_len = 0;
int ret;
if ((buf == NULL) || (len == 0)) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/*
* Section 2.3.5 of RFC 3279 specifically describe the expected
* content of the parameters for ECDSA or ECDH public key embedded
* in the subjectPublicKeyInfo of a certificate. Those parameters
* follow the OID describing the algotithm in the AlgorithmIdentifier
* sequence:
*
* AlgorithmIdentifier ::= SEQUENCE {
* algorithm OBJECT IDENTIFIER,
* parameters ANY DEFINED BY algorithm OPTIONAL
* }
*
* Usually, when an AlgorithmIdentifier is used to describe the
* signature algorithm in the certificate or the signature
* itself, the OID comes with a NULL parameter. But for the
* specific OID 1.2.840.10045.2.1 described in Section 2.3.5 of
* RFC 3279 to support ECDSA and ECDH public keys in
* subjectPublicKeyInfo field, the associated parameters are
* expected to be of the following form:
*
* EcpkParameters ::= CHOICE {
* ecParameters ECParameters,
* namedCurve OBJECT IDENTIFIER,
* implicitlyCA NULL }
*
* In practice, to simplify things a lot w/o real lack of
* support, we only accept namedCurves (ECParameters is
* quite complex and never used in practice), i.e. we
* expect to find an OID for a curve we support.
*/
/* The first thing we should find in the sequence is an OID */
ret = parse_OID(buf, len, &oid_len);
if (ret) {
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/* We do not expected anything after the parameters */
if (oid_len != len) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/* Let's now see if that OID is one associated w/ a curve we support */
curve = find_curve_by_oid(buf, oid_len);
if (curve == NULL) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
param->curve_param = curve;
ret = 0;
out:
return ret;
}
/*
* From RFC 3279:
*
* The elliptic curve public key (an ECPoint which is an
* OCTET STRING) is mapped to a subjectPublicKey (a BIT
* STRING) as follows: the most significant bit of the
* OCTET STRING becomes the most significant bit of the
* BIT STRING, and the least significant bit of the OCTET
* STRING becomes the least significant bit of the BIT
* STRING.
*
* ECPoint ::= OCTET STRING
*
* The value of FieldElement SHALL be the octet string
* representation of a field element following the
* conversion routine in [X9.62], Section 4.3.3.
* The value of ECPoint SHALL be the octet string
* representation of an elliptic curve point following
* the conversion routine in [X9.62], Section 4.3.6.
* Note that this octet string may represent an elliptic
* curve point in compressed or uncompressed form.
*
*/
/*@
@ requires len >= 0;
@ requires ((len > 0) && (buf != \null)) ==> \valid_read(buf + (0 .. (len - 1)));
@ requires \initialized(¶m->curve_param);
@ ensures \result < 0 || \result == 0;
@ ensures (len == 0) ==> \result < 0;
@ ensures (buf == \null) ==> \result < 0;
@ assigns \nothing;
@*/
static int parse_subjectpubkey_ec(const u8 *buf, u16 len, alg_param *param)
{
u16 remain;
u16 hdr_len = 0;
u16 data_len = 0;
u16 order_ceil_len;
int ret;
u8 pc;
if ((buf == NULL) || (len == 0)) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/* subjectPublicKey field of SubjectPublicKeyInfo is a BIT STRING */
ret = parse_id_len(buf, len, CLASS_UNIVERSAL, ASN1_TYPE_BIT_STRING,
&hdr_len, &data_len);
if (ret) {
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/*
* We expect the bitstring data to contain at least the initial
* octet encoding the number of unused bits in the final
* subsequent octet of the bistring.
* */
if (data_len == 0) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
buf += hdr_len;
/*
* We expect the initial octet to encode a value of 0
* indicating that there are no unused bits in the final
* subsequent octet of the bitstring.
*/
if (buf[0] != 0) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
buf += 1;
remain = data_len - 1;
/*
* From that point on, the parsing of the public key is done as
* described in section 4.3.7 of X9.62 version 1998.
*/
/*
* The first thing we should find is the PC byte, which means
* at least one byte should remain at that point.
*/
if (remain == 0) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
pc = buf[0];
remain -= 1;
buf += 1;
/*
* At that point, Frama-C knows param->curve_param is either
* NULL or point to a static curve structure. That test is currently
* here to help Frama-C when using Typed memory model.
*/
if (param->curve_param == NULL) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/*
* We expect a specific length for the remaining data based on
* pc byte value.
*/
order_ceil_len = (param->curve_param->crv_order_bit_len + 7) / 8;
switch (pc) {
case 0x04: /* uncompressed */
if (remain != (order_ceil_len * 2)) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
break;
case 0x02: /* compressed */
case 0x03: /* compressed */
if (remain != order_ceil_len) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
break;
default: /* hybrid or other forms: no support */
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
break;
}
ret = 0;
out:
return ret;
}
#ifdef TEMPORARY_BADALGS
/*
* The function below just skips the parameters it should parse.
* It s just here as a helper for bad algs we do not intend to
* support and should not be used for real purposes.
*/
/*@
@ requires len >= 0;
@ requires ((len > 0) && (buf != \null)) ==> \valid_read(buf + (0 .. (len - 1)));
@ requires (param != \null) ==> \valid_read(param);
@ ensures (len == 0) ==> \result < 0;
@ ensures (buf == \null) ==> \result < 0;
@ ensures (param == \null) ==> \result < 0;
@ ensures \result < 0 || \result == 0;
@ ensures \result == 0 ==> param->unparsed_param == 1;
@ assigns param->unparsed_param;
@*/
static int parse_algoid_params_generic(const u8 *buf, u16 len, alg_param *param)
{
int ret;
if ((len == 0) || (buf == NULL) || (param == NULL)) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
param->unparsed_param = 1;
ret = 0;
out:
return ret;
}
/*@
@ requires len >= 0;
@ requires ((len > 0) && (buf != \null)) ==> \valid_read(buf + (0 .. (len - 1)));
@ requires (param != \null) ==> \valid_read(param);
@ ensures (len == 0) ==> \result < 0;
@ ensures (buf == \null) ==> \result < 0;
@ ensures (param == \null) ==> \result < 0;
@ ensures \result < 0 || \result == 0;
@ ensures \result == 0 ==> (param->null_param == null_encoded_val);
@ assigns param->null_param;
@*/
static int parse_algoid_params_rsa(const u8 *buf, u16 len, alg_param *param)
{
int ret;
if ((len == 0) || (buf == NULL) || (param == NULL)) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/*
* Section 3.2 of RFC 3370 explicitly states that
* "When the rsaEncryption, sha1WithRSAEncryption, or
* md5WithRSAEncryption signature value algorithm
* identifiers are used, the AlgorithmIdentifier parameters
* field MUST be NULL.", i.e. contain { 0x05, 0x00 }
*
*/
if (len != sizeof(null_encoded_val)) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
ret = bufs_differ(buf, null_encoded_val, sizeof(null_encoded_val));
if (ret) {
ret = -__LINE__;
goto out;
}
param->null_param = null_encoded_val;
ret = 0;
out:
return ret;
}
/*
* From RFC 3279:
*
* The RSA public key MUST be encoded using the ASN.1
* type RSAPublicKey:
*
* RSAPublicKey ::= SEQUENCE {
* modulus INTEGER, -- n
* publicExponent INTEGER } -- e
*
* where modulus is the modulus n, and publicExponent
* is the public exponent e. The DER encoded
* RSAPublicKey is the value of the BIT STRING
* subjectPublicKey.
*/
/*@
@ requires len >= 0;
@ requires ((len > 0) && (buf != \null)) ==> \valid_read(buf + (0 .. (len - 1)));
@ requires \initialized(¶m->null_param);
@ ensures \result < 0 || \result == 0;
@ ensures (len == 0) ==> \result < 0;
@ ensures (buf == \null) ==> \result < 0;
@ assigns \nothing;
@*/
static int parse_subjectpubkey_rsa(const u8 *buf, u16 len, alg_param *param)
{
u16 remain;
u16 hdr_len = 0;
u16 data_len = 0;
u16 eaten = 0;
int ret;
if ((buf == NULL) || (len == 0)) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
if (param->null_param != null_encoded_val) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/* subjectPublicKey field of SubjectPublicKeyInfo is a BIT STRING */
ret = parse_id_len(buf, len, CLASS_UNIVERSAL, ASN1_TYPE_BIT_STRING,
&hdr_len, &data_len);
if (ret) {
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/*
* We expect the bitstring data to contain at least the initial
* octet encoding the number of unused bits in the final
* subsequent octet of the bistring.
* */
if (data_len == 0) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
buf += hdr_len;
/*
* We expect the initial octet to encode a value of 0
* indicating that there are no unused bits in the final
* subsequent octet of the bitstring.
*/
if (buf[0] != 0) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
buf += 1;
remain = data_len - 1;
/*
* Now, in the case of a RSA public key, we expect the content of
* the BIT STRING to contain a SEQUENCE of two INTEGERS
*/
ret = parse_id_len(buf, remain, CLASS_UNIVERSAL, ASN1_TYPE_SEQUENCE,
&hdr_len, &data_len);
if (ret) {
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
buf += hdr_len;
remain = data_len;
/* Now, we should find the first integer, n (modulus) */
ret = parse_integer(buf, remain, CLASS_UNIVERSAL, ASN1_TYPE_INTEGER,
&eaten);
if (ret) {
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
remain -= eaten;
buf += eaten;
/* An then, the second one, e (publicExponent) */
ret = parse_integer(buf, remain, CLASS_UNIVERSAL, ASN1_TYPE_INTEGER,
&eaten);
if (ret) {
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
remain -= eaten;
if (remain != 0) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
ret = 0;
out:
return ret;
}
#endif
/*@
@ requires len >= 0;
@ requires ((len > 0) && (buf != NULL)) ==> \valid_read(buf + (0 .. (len - 1)));
@ ensures (\result != NULL) ==> \exists integer i ; 0 <= i < NUM_KNOWN_ALGS && \result == known_algs[i];
@ ensures (len == 0) ==> \result == NULL;
@ ensures (buf == NULL) ==> \result == NULL;
@ assigns \nothing;
@*/
static const _alg_id * find_alg_by_oid(const u8 *buf, u16 len)
{
const _alg_id *found = NULL;
const _alg_id *cur = NULL;
u8 k;
if ((buf == NULL) || (len == 0)) {
goto out;
}
/*@
@ loop invariant 0 <= k <= NUM_KNOWN_ALGS;
@ loop invariant found == NULL;
@ loop assigns cur, found, k;
@ loop variant (NUM_KNOWN_ALGS - k);
@*/
for (k = 0; k < NUM_KNOWN_ALGS; k++) {
int ret;
cur = known_algs[k];
/*@ assert cur == known_algs[k]; */
if (cur->alg_der_oid_len != len) {
continue;
}
/*@ assert \valid_read(buf + (0 .. (len - 1))); @*/
ret = !bufs_differ(cur->alg_der_oid, buf, cur->alg_der_oid_len);
if (ret) {
found = cur;
break;
}
}
out:
return found;
}
/*
* AlgorithmIdentifier. Used for signature field.
*
* AlgorithmIdentifier ::= SEQUENCE {
* algorithm OBJECT IDENTIFIER,
* parameters ANY DEFINED BY algorithm OPTIONAL }
*
*/
/*@
@ requires len >= 0;
@ requires ((len > 0) && (buf != \null)) ==> \valid_read(buf + (0 .. (len - 1)));
@ requires \valid(param);
@ requires \valid(alg);
@ requires \separated(buf,alg,param,eaten);
@ ensures \result < 0 || \result == 0;
@ ensures (\result == 0) ==> \exists u8 x; *alg == known_algs[x];
@ ensures (\result == 0) ==> (1 < *eaten <= len);
@ ensures (len == 0) ==> \result < 0;
@ ensures (buf == \null) ==> \result < 0;
@ ensures (\result == 0) ==> \valid_read(*alg);
@ assigns *alg, *eaten, *param;
@*/
static int parse_x509_AlgorithmIdentifier(const u8 *buf, u16 len,
const _alg_id **alg, alg_param *param,
u16 *eaten)
{
const _alg_id *talg = NULL;
u16 hdr_len = 0;
u16 data_len = 0;
u16 param_len;
u16 oid_len = 0;
int ret;
if ((buf == NULL) || (len == 0)) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/* Check we are dealing with a valid sequence */
ret = parse_id_len(buf, len, CLASS_UNIVERSAL, ASN1_TYPE_SEQUENCE,
&hdr_len, &data_len);
if (ret) {
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
buf += hdr_len;
/* The first thing we should find in the sequence is an OID */
ret = parse_OID(buf, data_len, &oid_len);
if (ret) {
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/* Let's now see if that OID is one associated w/ an alg we support */
talg = find_alg_by_oid(buf, oid_len);
if (talg == NULL) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/*@ assert \valid_read(talg); */
buf += oid_len;
param_len = data_len - oid_len;
/*@ calls parse_algoid_params_generic, parse_algoid_params_ecdsa_with, parse_algoid_params_ecPublicKey, parse_algoid_params_rsa; @*/
ret = talg->parse_algoid_params(buf, param_len, param);
if (ret) {
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
*alg = talg;
*eaten = hdr_len + data_len;
ret = 0;
out:
return ret;
}
static const u8 _dn_oid_cn[] = { 0x06, 0x03, 0x55, 0x04, 0x03 };
static const u8 _dn_oid_surname[] = { 0x06, 0x03, 0x55, 0x04, 0x04 };
static const u8 _dn_oid_serial[] = { 0x06, 0x03, 0x55, 0x04, 0x05 };
static const u8 _dn_oid_country[] = { 0x06, 0x03, 0x55, 0x04, 0x06 };
static const u8 _dn_oid_locality[] = { 0x06, 0x03, 0x55, 0x04, 0x07 };
static const u8 _dn_oid_state[] = { 0x06, 0x03, 0x55, 0x04, 0x08 };
static const u8 _dn_oid_org[] = { 0x06, 0x03, 0x55, 0x04, 0x0a };
static const u8 _dn_oid_org_unit[] = { 0x06, 0x03, 0x55, 0x04, 0x0b };
static const u8 _dn_oid_title[] = { 0x06, 0x03, 0x55, 0x04, 0x0c };
static const u8 _dn_oid_name[] = { 0x06, 0x03, 0x55, 0x04, 0x29 };
static const u8 _dn_oid_given_name[] = { 0x06, 0x03, 0x55, 0x04, 0x2a };
static const u8 _dn_oid_initials[] = { 0x06, 0x03, 0x55, 0x04, 0x2b };
static const u8 _dn_oid_gen_qual[] = { 0x06, 0x03, 0x55, 0x04, 0x2c };
static const u8 _dn_oid_dn_qual[] = { 0x06, 0x03, 0x55, 0x04, 0x2e };
static const u8 _dn_oid_pseudo[] = { 0x06, 0x03, 0x55, 0x04, 0x41 };
static const u8 _dn_oid_dc[] = { 0x06, 0x0a, 0x09, 0x92, 0x26,
0x89, 0x93, 0xf2, 0x2c, 0x64,
0x01, 0x19 };
/*
* This function verify given buffer contains a valid UTF-8 string
* -1 is returned on error, 0 on success.
*/
/*@
@ requires len >= 0;
@ requires ((len > 0) && (buf != \null)) ==> \valid_read(buf + (0 .. (len - 1)));
@ ensures \result < 0 || \result == 0;
@ ensures (len == 0) ==> \result < 0;
@ ensures (buf == \null) ==> \result < 0;
@ assigns \nothing;
@*/
static int check_utf8_string(const u8 *buf, u16 len)
{
int ret;
u8 b0;
if ((buf == NULL) || (len == 0)) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/*@
@ loop invariant \valid_read(buf + (0 .. (len - 1)));
@ loop assigns b0, len, buf, ret;
@ loop variant len;
@ */
while (len) {
b0 = buf[0];
/*
* CP encoded on a single byte, coding from 1 to 7 bits,
* U+000 to U+07FF.
*/
if (b0 <= 0x7f) { /* 0x00 to 0x7f */
len -= 1;
buf += 1;
continue;
}
/*
* CP encoded on 2 bytes, coding from 8 to 11 bits,
* U+0080 to U+07FF
*/
if ((b0 >= 0xc2) && (b0 <= 0xdf)) { /* 0xc2 to 0xdf */
if (len < 2) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/*@ assert \valid_read(buf + (0 .. 1)); */
if ((buf[1] & 0xc0) != 0x80) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
len -= 2;
buf += 2;
continue;
}
/*
* CP encoded on 3 bytes, coding 12 to 16 bits,
* U+0800 to U+FFFF.
*/
if ((b0 >= 0xe0) && (b0 <= 0xef)) { /* 0xe0 to 0xef */
if (len < 3) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/*@ assert \valid_read(buf + (0 .. 2)); */
if (((buf[1] & 0xc0) != 0x80) ||
((buf[2] & 0xc0) != 0x80)) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/*
* 1rst byte is 0xe0 => 2nd byte in [0xa0, 0xbf]
* 1rst byte is 0xed => 2nd byte in [0x80, 0x9f]
*/
if ((b0 == 0xe0) &&
((buf[1] < 0xa0) || (buf[1] > 0xbf))) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
} else if ((b0 == 0xed) &&
((buf[1] < 0x80) || (buf[1] > 0x9f))) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
len -= 3;
buf += 3;
continue;
}
/*
* CP encoded on 4 bytes, coding 17 to 21 bits,
* U+10000 to U+10FFFF.
*/
if ((b0 >= 0xf0) && (b0 <= 0xf4)) { /* 0xf0 to 0xf4 */
if (len < 4) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/*
* 1rst byte is 0xe0 => 2nd byte in [0xa0, 0xbf]
* 1rst byte is 0xed => 2nd byte in [0x80, 0x9f]
*/
/*@ assert \valid_read(buf + (0 .. 3)); */
if ((b0 == 0xf0) &&
((buf[1] < 0x90) || (buf[1] > 0xbf))) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
} else if ((b0 == 0xf4) &&
((buf[1] < 0x80) || (buf[1] > 0x8f))) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
if (((buf[1] & 0xc0) != 0x80) ||
((buf[2] & 0xc0) != 0x80) ||
((buf[3] & 0xc0) != 0x80)) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
len -= 4;
buf += 4;
continue;
}
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
ret = 0;
out:
return ret;
}
/*
* Verify given buffer contains only printable characters. -1 is
* returned on error, 0 on success.
*
* RFC 5280 has: "The character string type PrintableString supports a
* very basic Latin character set: the lowercase letters 'a' through 'z',
* uppercase letters 'A' through 'Z', the digits '0' through '9',
* eleven special characters ' = ( ) + , - . / : ? and space."
*
*/
/*@
@ requires len >= 0;
@ requires ((len > 0) && (buf != \null)) ==> \valid_read(buf + (0 .. (len - 1)));
@ ensures \result < 0 || \result == 0;
@ ensures (len == 0) ==> \result < 0;
@ ensures (buf == \null) ==> \result < 0;
@ assigns \nothing;
@*/
static int check_printable_string(const u8 *buf, u16 len)
{
int ret;
u16 rbytes;
u8 c;
if ((buf == NULL) || (len == 0)) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/*@
@ loop invariant 0 <= rbytes <= len;
@ loop assigns rbytes, c, ret;
@ loop variant (len - rbytes);
@ */
for (rbytes = 0; rbytes < len; rbytes++) {
c = buf[rbytes];
if ((c >= 'a' && c <= 'z') ||
(c >= 'A' && c <= 'Z') ||
(c >= '0' && c <= '9')) {
continue;
}
switch (c) {
case 39: /* ' */
case '=':
case '(':
case ')':
case '+':
case ',':
case '-':
case '.':
case '/':
case ':':
case '?':
case ' ':
continue;
default:
break;
}
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
ret = 0;
out:
return ret;
}
/*
* VisibleString == ISO646String == ASCII
*/
/*@
@ requires len >= 0;
@ requires ((len > 0) && (buf != \null)) ==> \valid_read(buf + (0 .. (len - 1)));
@ ensures \result < 0 || \result == 0;
@ ensures (len == 0) ==> \result < 0;
@ ensures (buf == \null) ==> \result < 0;
@ assigns \nothing;
@*/
static int check_visible_string(const u8 *buf, u16 len)
{
int ret;
u16 rbytes = 0;
u8 c;
if ((buf == NULL) || (len == 0)) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/*@
@ loop assigns rbytes, c, ret;
@ loop variant (len - rbytes);
@ */
while (rbytes < len) {
c = buf[rbytes];
if ((c >= 'a' && c <= 'z') ||
(c >= 'A' && c <= 'Z') ||
(c >= '0' && c <= '9')) {
rbytes += 1;
continue;
}
switch (c) {
case 39: /* ' */
case '=':
case '(':
case ')':
case '+':
case ',':
case '-':
case '.':
case '/':
case ':':
case '?':
case ' ':
case '!':
case '"':
case '#':
case '$':
case '%':
case '&':
case '*':
case ';':
case '<':
case '>':
case '[':
case '\\':
case ']':
case '^':
case '_':
case '`':
case '{':
case '|':
case '}':
case '~':
rbytes += 1;
continue;
default:
break;
}
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
ret = 0;
out:
return ret;
}
/*@
@ requires len >= 0;
@ requires ((len > 0) && (buf != \null)) ==> \valid_read(buf + (0 .. (len - 1)));
@ ensures \result < 0 || \result == 0;
@ ensures (len == 0) ==> \result < 0;
@ ensures (buf == \null) ==> \result < 0;
@ assigns \nothing;
@*/
static int check_teletex_string(const u8 ATTRIBUTE_UNUSED *buf,
u16 ATTRIBUTE_UNUSED len)
{
/* Support is OPTIONAL */
return -__LINE__;
}
/*@
@ requires len >= 0;
@ requires ((len > 0) && (buf != \null)) ==> \valid_read(buf + (0 .. (len - 1)));
@ ensures \result < 0 || \result == 0;
@ ensures (len == 0) ==> \result < 0;
@ ensures (buf == \null) ==> \result < 0;
@ assigns \nothing;
@*/
static int check_universal_string(const u8 ATTRIBUTE_UNUSED *buf,
u16 ATTRIBUTE_UNUSED len)
{
/* Support is OPTIONAL */
return -__LINE__;
}
/*@
@ requires len >= 0;
@ requires ((len > 0) && (buf != \null)) ==> \valid_read(buf + (0 .. (len - 1)));
@ ensures \result < 0 || \result == 0;
@ ensures (len == 0) ==> \result < 0;
@ ensures (buf == \null) ==> \result < 0;
@ assigns \nothing;
@*/
static int check_bmp_string(const u8 ATTRIBUTE_UNUSED *buf,
u16 ATTRIBUTE_UNUSED len)
{
/* Support is OPTIONAL */
return -__LINE__;
}
/*
* Most RDN values are encoded using the directory string type
* defined below. This function performs the required check to
* verify the given string is a valid DirectoryString. The
* function returns 0 on success and -1 on error.
*
* This is an error if the length does not match that of the
* string, if buffer is too short or too long for the encoded
* string.
*
* DirectoryString ::= CHOICE {
* teletexString TeletexString (SIZE (1..MAX)),
* printableString PrintableString (SIZE (1..MAX)),
* universalString UniversalString (SIZE (1..MAX)),
* utf8String UTF8String (SIZE (1..MAX)),
* bmpString BMPString (SIZE (1..MAX)) }
*
*
* 'len' is the size of given buffer, including string type
* and string length. 'lb' and 'ub' are respectively lower and
* upper bounds for the effective string.
*/
#define STR_TYPE_UTF8_STRING 12
#define STR_TYPE_PRINTABLE_STRING 19
#define STR_TYPE_TELETEX_STRING 20
#define STR_TYPE_IA5_STRING 22
#define STR_TYPE_VISIBLE_STRING 26
#define STR_TYPE_UNIVERSAL_STRING 28
#define STR_TYPE_BMP_STRING 30
/*@
@ requires len >= 0;
@ requires ((len > 0) && (buf != \null)) ==> \valid_read(buf + (0 .. (len - 1)));
@ ensures \result < 0 || \result == 0;
@ ensures \result == 0 ==> ((len >= 2) && (lb <= len - 2 <= ub));
@ ensures (len == 0) ==> \result < 0;
@ ensures (buf == \null) ==> \result < 0;
@ assigns \nothing;
@*/
static int parse_directory_string(const u8 *buf, u16 len, u16 lb, u16 ub)
{
int ret = -__LINE__;
u8 str_type;
if ((buf == NULL) || (len == 0)) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
if (len < 2) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
str_type = buf[0];
len -= 2;
if (buf[1] != len) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
buf += 2;
if ((len < lb) || (len > ub)) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
switch (str_type) {
case STR_TYPE_PRINTABLE_STRING:
ret = check_printable_string(buf, len);
if (ret) {
ERROR_TRACE_APPEND(__LINE__);
}
break;
case STR_TYPE_UTF8_STRING:
ret = check_utf8_string(buf, len);
if (ret) {
ERROR_TRACE_APPEND(__LINE__);
}
break;
#ifdef TEMPORARY_LAXIST_DIRECTORY_STRING
/*
* Section 4.1.2.4 of RFC 5280 has "CAs conforming to this
* profile MUST use either the PrintableString or UTF8String
* encoding of DirectoryString, with two exceptions
*/
case STR_TYPE_TELETEX_STRING:
ret = check_teletex_string(buf, len);
if (ret) {
ERROR_TRACE_APPEND(__LINE__);
}
break;
case STR_TYPE_UNIVERSAL_STRING:
ret = check_universal_string(buf, len);
if (ret) {
ERROR_TRACE_APPEND(__LINE__);
}
break;
case STR_TYPE_BMP_STRING:
ret = check_bmp_string(buf, len);
if (ret) {
ERROR_TRACE_APPEND(__LINE__);
}
break;
#endif
default:
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
break;
}
if (ret) {
goto out;
}
ret = 0;
out:
return ret;
}
/*
* Some RDN values are specifically encoded as PrintableString and the usual
* directoryString. The function verifies that. It returns -1 on error, 0
* on success.
*/
/*@
@ requires len >= 0;
@ requires ((len > 0) && (buf != \null)) ==> \valid_read(buf + (0 .. (len - 1)));
@ ensures \result < 0 || \result == 0;
@ ensures \result == 0 ==> ((len >= 2) && (lb <= len - 2 <= ub));
@ ensures (len == 0) ==> \result < 0;
@ ensures (buf == \null) ==> \result < 0;
@ assigns \nothing;
@*/
static int parse_printable_string(const u8 *buf, u16 len, u16 lb, u16 ub)
{
int ret = -__LINE__;
u8 str_type;
if ((buf == NULL) || (len == 0)) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
if (len < 2) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
str_type = buf[0];
if (str_type != STR_TYPE_PRINTABLE_STRING) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
len -= 2;
if (buf[1] != len) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
buf += 2;
if ((len < lb) || (len > ub)) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
ret = check_printable_string(buf, len);
if (ret) {
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
ret = 0;
out:
return ret;
}
/*@
@ requires len >= 0;
@ requires ((len > 0) && (buf != \null)) ==> \valid_read(buf + (0 .. (len - 1)));
@ ensures \result < 0 || \result == 0;
@ ensures (len == 0) ==> \result < 0;
@ ensures (buf == \null) ==> \result < 0;
@ assigns \nothing;
@*/
static int check_ia5_string(const u8 *buf, u16 len)
{
int ret;
u16 i;
if ((buf == NULL) || (len == 0)) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/*@
@ loop invariant \forall integer x ; 0 <= x < i ==>
((buf[x] <= 0x7f));
@ loop assigns i;
@ loop variant (len - i);
@ */
for (i = 0; i < len; i++) {
if (buf[i] > 0x7f) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
}
ret = 0;
out:
return ret;
}
/*
* As pointed by RFC 4519 and described by RFC 4517, IA5String
* is defined in ABNF form as *(%x00-7F).
*/
/*@
@ requires len >= 0;
@ requires ((len > 0) && (buf != \null)) ==> \valid_read(buf + (0 .. (len - 1)));
@ ensures \result < 0 || \result == 0;
@ ensures \result == 0 ==> ((len >= 2) && (lb <= len - 2 <= ub));
@ ensures (len == 0) ==> \result < 0;
@ ensures (buf == \null) ==> \result < 0;
@ assigns \nothing;
@*/
static int parse_ia5_string(const u8 *buf, u16 len, u16 lb, u16 ub)
{
int ret = -__LINE__;
u8 str_type;
if ((buf == NULL) || (len == 0)) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
if (len < 2) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
str_type = buf[0];
if (str_type != STR_TYPE_IA5_STRING) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
len -= 2;
if (buf[1] != len) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
buf += 2;
if ((len < lb) || (len > ub)) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
ret = check_ia5_string(buf, len);
if (ret) {
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
ret = 0;
out:
return ret;
}
/*
*
* -- Naming attributes of type X520CommonName:
* -- X520CommonName ::= DirectoryName (SIZE (1..ub-common-name))
* --
* -- Expanded to avoid parameterized type:
* X520CommonName ::= CHOICE {
* teletexString TeletexString (SIZE (1..ub-common-name)),
* printableString PrintableString (SIZE (1..ub-common-name)),
* universalString UniversalString (SIZE (1..ub-common-name)),
* utf8String UTF8String (SIZE (1..ub-common-name)),
* bmpString BMPString (SIZE (1..ub-common-name)) }
*/
#define UB_COMMON_NAME 64
/*@
@ requires len >= 0;
@ requires ((len > 0) && (buf != \null)) ==> \valid_read(buf + (0 .. (len - 1)));
@ ensures \result < 0 || \result == 0;
@ ensures (len == 0) ==> \result < 0;
@ ensures (buf == \null) ==> \result < 0;
@ assigns \nothing;
@*/
static int parse_rdn_val_cn(const u8 *buf, u16 len)
{
return parse_directory_string(buf, len, 1, UB_COMMON_NAME);
}
#define UB_NAME 32768
/*@
@ requires len >= 0;
@ requires ((len > 0) && (buf != \null)) ==> \valid_read(buf + (0 .. (len - 1)));
@ ensures \result < 0 || \result == 0;
@ ensures (len == 0) ==> \result < 0;
@ ensures (buf == \null) ==> \result < 0;
@ assigns \nothing;
@*/
static int parse_rdn_val_x520name(const u8 *buf, u16 len)
{
return parse_directory_string(buf, len, 1, UB_NAME);
}
#define UB_SERIAL_NUMBER 64
/*@
@ requires len >= 0;
@ requires ((len > 0) && (buf != \null)) ==> \valid_read(buf + (0 .. (len - 1)));
@ ensures \result < 0 || \result == 0;
@ ensures (len == 0) ==> \result < 0;
@ ensures (buf == \null) ==> \result < 0;
@ assigns \nothing;
@*/
static int parse_rdn_val_serial(const u8 *buf, u16 len)
{
return parse_printable_string(buf, len, 1, UB_SERIAL_NUMBER);
}
#define UB_COUNTRY 2
/*@
@ requires len >= 0;
@ requires ((len > 0) && (buf != \null)) ==> \valid_read(buf + (0 .. (len - 1)));
@ ensures \result < 0 || \result == 0;
@ ensures (len == 0) ==> \result < 0;
@ ensures (buf == \null) ==> \result < 0;
@ assigns \nothing;
@*/
static int parse_rdn_val_country(const u8 *buf, u16 len)
{
return parse_directory_string(buf, len, UB_COUNTRY, UB_COUNTRY);
}
#define UB_LOCALITY_NAME 128
/*@
@ requires len >= 0;
@ requires ((len > 0) && (buf != \null)) ==> \valid_read(buf + (0 .. (len - 1)));
@ ensures \result < 0 || \result == 0;
@ ensures (len == 0) ==> \result < 0;
@ ensures (buf == \null) ==> \result < 0;
@ assigns \nothing;
@*/
static int parse_rdn_val_locality(const u8 *buf, u16 len)
{
return parse_directory_string(buf, len, 1, UB_LOCALITY_NAME);
}
#define UB_STATE_NAME 128
/*@
@ requires len >= 0;
@ requires ((len > 0) && (buf != \null)) ==> \valid_read(buf + (0 .. (len - 1)));
@ ensures \result < 0 || \result == 0;
@ ensures (len == 0) ==> \result < 0;
@ ensures (buf == \null) ==> \result < 0;
@ assigns \nothing;
@*/
static int parse_rdn_val_state(const u8 *buf, u16 len)
{
return parse_directory_string(buf, len, 1, UB_STATE_NAME);
}
#define UB_ORGANIZATION_NAME 64
/*@
@ requires len >= 0;
@ requires ((len > 0) && (buf != \null)) ==> \valid_read(buf + (0 .. (len - 1)));
@ ensures \result < 0 || \result == 0;
@ ensures (len == 0) ==> \result < 0;
@ ensures (buf == \null) ==> \result < 0;
@ assigns \nothing;
@*/
static int parse_rdn_val_org(const u8 *buf, u16 len)
{
return parse_directory_string(buf, len, 1, UB_ORGANIZATION_NAME);
}
#define UB_ORGANIZATION_UNIT_NAME 64
/*@
@ requires len >= 0;
@ requires ((len > 0) && (buf != \null)) ==> \valid_read(buf + (0 .. (len - 1)));
@ ensures \result < 0 || \result == 0;
@ ensures (len == 0) ==> \result < 0;
@ ensures (buf == \null) ==> \result < 0;
@ assigns \nothing;
@*/
static int parse_rdn_val_org_unit(const u8 *buf, u16 len)
{
return parse_directory_string(buf, len, 1, UB_ORGANIZATION_UNIT_NAME);
}
#define UB_TITLE_NAME 64
/*@
@ requires len >= 0;
@ requires ((len > 0) && (buf != \null)) ==> \valid_read(buf + (0 .. (len - 1)));
@ ensures \result < 0 || \result == 0;
@ ensures (len == 0) ==> \result < 0;
@ ensures (buf == \null) ==> \result < 0;
@ assigns \nothing;
@*/
static int parse_rdn_val_title(const u8 *buf, u16 len)
{
return parse_directory_string(buf, len, 1, UB_TITLE_NAME);
}
/*@
@ requires len >= 0;
@ requires ((len > 0) && (buf != \null)) ==> \valid_read(buf + (0 .. (len - 1)));
@ ensures \result < 0 || \result == 0;
@ ensures (len == 0) ==> \result < 0;
@ ensures (buf == \null) ==> \result < 0;
@ assigns \nothing;
@*/
static int parse_rdn_val_dn_qual(const u8 *buf, u16 len)
{
/*
* There is no specific limit on that one, so giving the maximum
* buffer size we support will do the job.
*/
return parse_printable_string(buf, len, 1, ASN1_MAX_BUFFER_SIZE);
}
/*@
@ assigns \nothing;
@*/
static inline int _is_digit(u8 c)
{
return ((c >= '0') && (c <= '9'));
}
/*@
@ assigns \nothing;
@*/
static inline int _is_alpha(u8 c)
{
return (((c >= 'a') && (c <= 'z')) || ((c >= 'A') && (c <= 'Z')));
}
/*
* As point in RFC 5280 and defined in section 2.4 of RFC 4519,
* 'dc' (domainComponent) is a string attribute type holding a
* DNS label. It is encoded as an IA5String. The ABNF for the
* label is the following:
*
* label = (ALPHA / DIGIT) [*61(ALPHA / DIGIT / HYPHEN) (ALPHA / DIGIT)]
* ALPHA = %x41-5A / %x61-7A ; "A"-"Z" / "a"-"z"
* DIGIT = %x30-39 ; "0"-"9"
* HYPHEN = %x2D ; hyphen ("-")
*
* To simplify things, we first verify this is a valid IA5string and then
* verify the additional restrictions given above for the label.
*
* Note that RFC 2181 (Clarifications on DNS) has the following: "The DNS
* itself places only one restriction on the particular labels that can
* be used to identify resource records. That one restriction relates
* to the length of the label and the full name...". In the case of dc
* attributes, limitations are imposed by the use of IA5String for
* encoding and by the ABNF above.
*/
#define UB_DC 63
/*@
@ requires len >= 0;
@ requires ((len > 0) && (buf != \null)) ==> \valid_read(buf + (0 .. (len - 1)));
@ ensures \result < 0 || \result == 0;
@ ensures (len == 0) ==> \result < 0;
@ ensures (buf == \null) ==> \result < 0;
@ assigns \nothing;
@*/
static int parse_rdn_val_dc(const u8 *buf, u16 len)
{
int ret;
u16 i;
u8 c;
if ((buf == NULL) || (len == 0)) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/* We expect an IA5String */
ret = parse_ia5_string(buf, len, 1, UB_DC);
if (ret) {
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
buf += 2;
len -= 2;
/* Restriction on first byte */
c = buf[0];
ret = _is_alpha(c) || _is_digit(c);
if (!ret) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
buf += 1;
len -= 1;
if (!len) { /* over ? */
ret = 0;
goto out;
}
/* Restriction on last byte if any */
c = buf[len - 1];
ret = _is_alpha(c) || _is_digit(c);
if (!ret) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
buf += 1;
len -= 1;
/* Restriction on middle bytes */
/*@
@ loop invariant 0 <= i <= len;
@ loop assigns c, ret, i;
@ loop variant (len - i);
@ */
for (i = 0; i < len; i++) {
c = buf[i];
ret = _is_digit(c) || _is_alpha(c) || (c == '-');
if (!ret) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
}
ret = 0;
out:
return ret;
}
#define UB_PSEUDONYM 128
/*@
@ requires len >= 0;
@ requires ((len > 0) && (buf != \null)) ==> \valid_read(buf + (0 .. (len - 1)));
@ ensures \result < 0 || \result == 0;
@ ensures (len == 0) ==> \result < 0;
@ ensures (buf == \null) ==> \result < 0;
@ assigns \nothing;
@*/
static int parse_rdn_val_pseudo(const u8 *buf, u16 len)
{
return parse_directory_string(buf, len, 1, UB_PSEUDONYM);
}
typedef struct {
const u8 *oid;
u8 oid_len;
int (*parse_rdn_val)(const u8 *buf, u16 len);
} _name_oid;
static const _name_oid known_dn_oids[] = {
{ .oid = _dn_oid_cn,
.oid_len = sizeof(_dn_oid_cn),
.parse_rdn_val = parse_rdn_val_cn
},
{ .oid = _dn_oid_surname,
.oid_len = sizeof(_dn_oid_surname),
.parse_rdn_val = parse_rdn_val_x520name
},
{ .oid = _dn_oid_serial,
.oid_len = sizeof(_dn_oid_serial),
.parse_rdn_val = parse_rdn_val_serial
},
{ .oid = _dn_oid_country,
.oid_len = sizeof(_dn_oid_country),
.parse_rdn_val = parse_rdn_val_country
},
{ .oid = _dn_oid_locality,
.oid_len = sizeof(_dn_oid_locality),
.parse_rdn_val = parse_rdn_val_locality
},
{ .oid = _dn_oid_state,
.oid_len = sizeof(_dn_oid_state),
.parse_rdn_val = parse_rdn_val_state
},
{ .oid = _dn_oid_org,
.oid_len = sizeof(_dn_oid_org),
.parse_rdn_val = parse_rdn_val_org
},
{ .oid = _dn_oid_org_unit,
.oid_len = sizeof(_dn_oid_org_unit),
.parse_rdn_val = parse_rdn_val_org_unit
},
{ .oid = _dn_oid_title,
.oid_len = sizeof(_dn_oid_title),
.parse_rdn_val = parse_rdn_val_title
},
{ .oid = _dn_oid_name,
.oid_len = sizeof(_dn_oid_name),
.parse_rdn_val = parse_rdn_val_x520name
},
{ .oid = _dn_oid_given_name,
.oid_len = sizeof(_dn_oid_given_name),
.parse_rdn_val = parse_rdn_val_x520name
},
{ .oid = _dn_oid_initials,
.oid_len = sizeof(_dn_oid_initials),
.parse_rdn_val = parse_rdn_val_x520name
},
{ .oid = _dn_oid_gen_qual,
.oid_len = sizeof(_dn_oid_gen_qual),
.parse_rdn_val = parse_rdn_val_x520name
},
{ .oid = _dn_oid_dn_qual,
.oid_len = sizeof(_dn_oid_dn_qual),
.parse_rdn_val = parse_rdn_val_dn_qual
},
{ .oid = _dn_oid_pseudo,
.oid_len = sizeof(_dn_oid_pseudo),
.parse_rdn_val = parse_rdn_val_pseudo
},
{ .oid = _dn_oid_dc,
.oid_len = sizeof(_dn_oid_dc),
.parse_rdn_val = parse_rdn_val_dc
},
};
#define NUM_KNOWN_DN_OIDS (sizeof(known_dn_oids) / sizeof(known_dn_oids[0]))
/*@
@ requires len >= 0;
@ requires ((len > 0) && (buf != NULL)) ==> \valid_read(buf + (0 .. (len - 1)));
@ ensures (\result != NULL) ==> \exists integer i ; 0 <= i < NUM_KNOWN_DN_OIDS && \result == &known_dn_oids[i];
@ ensures (len == 0) ==> \result == NULL;
@ ensures (buf == NULL) ==> \result == NULL;
@ assigns \nothing;
@*/
static const _name_oid * find_dn_by_oid(const u8 *buf, u16 len)
{
const _name_oid *found = NULL;
const _name_oid *cur = NULL;
u8 k;
if ((buf == NULL) || (len == 0)) {
goto out;
}
/*@
@ loop invariant 0 <= k <= NUM_KNOWN_DN_OIDS;
@ loop invariant found == NULL;
@ loop assigns cur, found, k;
@ loop variant (NUM_KNOWN_DN_OIDS - k);
@*/
for (k = 0; k < NUM_KNOWN_DN_OIDS; k++) {
int ret;
cur = &known_dn_oids[k];
/*@ assert cur == &known_dn_oids[k];*/
if (cur->oid_len != len) {
continue;
}
/*@ assert \valid_read(buf + (0 .. (len - 1))); @*/
ret = !bufs_differ(cur->oid, buf, cur->oid_len);
if (ret) {
found = cur;
break;
}
}
out:
return found;
}
/*
* AttributeTypeAndValue ::= SEQUENCE {
* type AttributeType,
* value AttributeValue }
*
* AttributeType ::= OBJECT IDENTIFIER
*
* AttributeValue ::= ANY -- DEFINED BY AttributeType
*/
/*@
@ requires len >= 0;
@ requires ((len > 0) && (buf != \null)) ==> \valid_read(buf + (0 .. (len - 1)));
@ requires \valid(eaten);
@ ensures \result < 0 || \result == 0;
@ ensures (\result == 0) ==> (1 < *eaten <= len);
@ ensures (len == 0) ==> \result < 0;
@ ensures (buf == \null) ==> \result < 0;
@ assigns *eaten;
@*/
static int parse_AttributeTypeAndValue(const u8 *buf, u16 len, u16 *eaten)
{
u16 hdr_len = 0;
u16 data_len = 0;
u16 oid_len = 0;
u16 parsed;
const _name_oid *cur = NULL;
int ret;
if ((buf == NULL) || (len == 0)) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/* ... of SEQUENCEs ... */
ret = parse_id_len(buf, len, CLASS_UNIVERSAL, ASN1_TYPE_SEQUENCE,
&hdr_len, &data_len);
if (ret) {
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
parsed = hdr_len + data_len;
/*@ assert parsed <= len ; */
buf += hdr_len;
len -= hdr_len;
/* ... Containing an OID ... */
ret = parse_OID(buf, data_len, &oid_len);
if (ret) {
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
cur = find_dn_by_oid(buf, oid_len);
if (cur == NULL) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
data_len -= oid_len;
buf += oid_len;
/*
* Let's now check the value associated w/ and
* following the OID has a valid format.
*/
/*@ calls parse_rdn_val_cn, parse_rdn_val_x520name,
parse_rdn_val_serial, parse_rdn_val_country,
parse_rdn_val_locality, parse_rdn_val_state,
parse_rdn_val_org, parse_rdn_val_org_unit,
parse_rdn_val_title, parse_rdn_val_dn_qual,
parse_rdn_val_pseudo, parse_rdn_val_dc;
@*/
ret = cur->parse_rdn_val(buf, data_len);
if (ret) {
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
*eaten = parsed;
/*@ assert *eaten <= \at(len,Pre) ; */
ret = 0;
out:
return ret;
}
/*
* RelativeDistinguishedName ::=
* SET SIZE (1..MAX) OF AttributeTypeAndValue
*
*/
/*@
@ requires len >= 0;
@ requires ((len > 0) && (buf != \null)) ==> \valid_read(buf + (0 .. (len - 1)));
@ requires \valid(eaten);
@ requires \separated(eaten,buf+(..));
@ ensures \result < 0 || \result == 0;
@ ensures (\result == 0) ==> (1 < *eaten <= len);
@ ensures (len == 0) ==> \result < 0;
@ ensures (buf == \null) ==> \result < 0;
@ assigns *eaten;
@*/
static int parse_RelativeDistinguishedName(const u8 *buf, u16 len, u16 *eaten)
{
u16 hdr_len = 0;
u16 data_len = 0;
u16 rdn_remain, saved_rdn_len;
int ret;
if ((buf == NULL) || (len == 0)) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/* Each RDN is a SET ... */
ret = parse_id_len(buf, len, CLASS_UNIVERSAL, ASN1_TYPE_SET,
&hdr_len, &data_len);
if (ret) {
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
saved_rdn_len = hdr_len + data_len;
buf += hdr_len;
rdn_remain = data_len;
/*@
@ loop assigns ret, buf, rdn_remain;
@ loop invariant \valid_read(buf + (0 .. (rdn_remain - 1)));
@ loop variant rdn_remain;
@ */
while (rdn_remain) {
u16 parsed = 0;
ret = parse_AttributeTypeAndValue(buf, rdn_remain, &parsed);
if (ret) {
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/*
* FIXME! we should check the amount of AttributeTypeAndValue
* elements is between 1 and MAX
*/
rdn_remain -= parsed;
buf += parsed;
}
*eaten = saved_rdn_len;
ret = 0;
out:
return ret;
}
/*
* Used for Issuer and subject
*
* Name ::= CHOICE { -- only one possibility for now --
* rdnSequence RDNSequence }
*
* RDNSequence ::= SEQUENCE OF RelativeDistinguishedName
*
* RelativeDistinguishedName ::=
* SET SIZE (1..MAX) OF AttributeTypeAndValue
*
* AttributeTypeAndValue ::= SEQUENCE {
* type AttributeType,
* value AttributeValue }
*
* AttributeType ::= OBJECT IDENTIFIER
*
* AttributeValue ::= ANY -- DEFINED BY AttributeType
*
* Here is what section 4.1.2.4 of RFC 5280 has:
*
* As noted above, distinguished names are composed of attributes. This
* specification does not restrict the set of attribute types that may
* appear in names. However, conforming implementations MUST be
* prepared to receive certificates with issuer names containing the set
* of attribute types defined below. This specification RECOMMENDS
* support for additional attribute types.
*
* Standard sets of attributes have been defined in the X.500 series of
* specifications [X.520]. Implementations of this specification MUST
* be prepared to receive the following standard attribute types in
* issuer and subject (Section 4.1.2.6) names:
*
* * country,
* * organization,
* * organizational unit,
* * distinguished name qualifier,
* * state or province name,
* * common name (e.g., "Susan Housley"), and
* * serial number.
*
* In addition, implementations of this specification SHOULD be prepared
* to receive the following standard attribute types in issuer and
* subject names:
*
* * locality,
* * title,
* * surname,
* * given name,
* * initials,
* * pseudonym, and
* * generation qualifier (e.g., "Jr.", "3rd", or "IV").
*
* The syntax and associated object identifiers (OIDs) for these
* attribute types are provided in the ASN.1 modules in Appendix A.
*
* In addition, implementations of this specification MUST be prepared
* to receive the domainComponent attribute, as defined in [RFC4519].
* The Domain Name System (DNS) provides a hierarchical resource
* labeling system. This attribute provides a convenient mechanism for
* organizations that wish to use DNs that parallel their DNS names.
* This is not a replacement for the dNSName component of the
* alternative name extensions. Implementations are not required to
* convert such names into DNS names.
*/
/*@
@ requires len >= 0;
@ requires ((len > 0) && (buf != \null)) ==> \valid_read(buf + (0 .. (len - 1)));
@ requires \valid(eaten);
@ requires \separated(eaten, empty, buf+(..));
@ ensures \result < 0 || \result == 0;
@ ensures (\result == 0) ==> (1 < *eaten <= len);
@ ensures (\result == 0) ==> ((*empty == 0) || (*empty == 1));
@ ensures (len == 0) ==> \result < 0;
@ ensures (buf == \null) ==> \result < 0;
@ assigns *eaten, *empty;
@*/
static int parse_x509_Name(const u8 *buf, u16 len, u16 *eaten, int *empty)
{
u16 name_hdr_len = 0;
u16 name_data_len = 0;
u16 remain = 0;
int ret;
if ((buf == NULL) || (len == 0)) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/* Check we are dealing with a valid sequence */
ret = parse_id_len(buf, len, CLASS_UNIVERSAL, ASN1_TYPE_SEQUENCE,
&name_hdr_len, &name_data_len);
if (ret) {
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
buf += name_hdr_len;
remain = name_data_len;
/*@
@ loop assigns ret, buf, remain;
@ loop invariant \valid_read(buf + (0 .. (remain - 1)));
@ loop variant remain;
@ */
while (remain) {
u16 parsed = 0;
ret = parse_RelativeDistinguishedName(buf, remain, &parsed);
if (ret) {
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
buf += parsed;
remain -= parsed;
}
*eaten = name_hdr_len + name_data_len;
*empty = !name_data_len;
/*@ assert (*empty == 0) || (*empty == 1); */
ret = 0;
out:
return ret;
}
/*@
@ requires 0x30 <= d <= 0x39;
@ requires 0x30 <= u <= 0x39;
@ ensures 0 <= \result <= 99;
@ assigns \nothing;
@*/
u8 compute_decimal(u8 d, u8 u)
{
return (d - 0x30) * 10 + (u - 0x30);
}
/* Validate UTCTime (including the constraints from RFC 5280) */
/*@
@ requires len >= 0;
@ requires ((len > 0) && (buf != \null)) ==> \valid_read(buf + (0 .. (len - 1)));
@ requires \valid(eaten);
@ requires \valid(eaten);
@ requires \valid(year);
@ requires \valid(month);
@ requires \valid(day);
@ requires \valid(hour);
@ requires \valid(min);
@ requires \valid(sec);
@ requires \separated(eaten, year, month, day, hour, min, sec, buf + (0 .. (len - 1)));
@ ensures \result < 0 || \result == 0;
@ ensures (\result == 0) ==> (*eaten <= len);
@ ensures (\result == 0) ==> (*eaten == 15);
@ ensures (len < 15) ==> \result < 0;
@ ensures (buf == \null) ==> \result < 0;
@ assigns *eaten, *year, *month, *day, *hour, *min, *sec;
@*/
static int parse_UTCTime(const u8 *buf, u16 len, u16 *eaten,
u16 *year, u8 *month, u8 *day,
u8 *hour, u8 *min, u8 *sec)
{
u16 yyyy;
u8 mo, dd, hh, mm, ss;
const u8 c_zero = '0';
u8 time_type;
u16 time_len;
int ret = -__LINE__;
u8 i, tmp;
if (buf == NULL) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/*
* As described in section 4.1.2.5.1 of RFC 5280, we do
* expect the following encoding: YYMMDDHHMMSSZ, i.e.
* a length of at least 15 bytes for the buffer, i.e.
* an advertised length of 13 bytes for the string
* it contains.
*/
if (len < 15) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
time_type = buf[0];
if (time_type != ASN1_TYPE_UTCTime) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
time_len = buf[1];
if (time_len != (u8)13) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
buf += 2;
/*
* Check all first 12 characters are decimal digits and
* last one is character 'Z'
*/
/*@
@ loop invariant \valid_read(buf + i);
@ loop invariant \forall integer x ; 0 <= x < i ==>
0x30 <= buf[x] <= 0x39;
@ loop assigns i;
@ loop variant (12 - i);
@ */
for (i = 0; i < 12; i++) {
if (c_zero > buf[i]) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
if ((buf[i] - c_zero) > 9) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/*@ assert 0 <= buf[i] - c_zero <= 9; */
}
if (buf[12] != 'Z') {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/*@ assert c_zero == 0x30; */
/*@ assert \forall integer x ; 0 <= x < 12 ==> 0x30 <= buf[x] <= 0x39; */
yyyy = compute_decimal(buf[ 0], buf[1]);
if (yyyy >= 50) {
yyyy += 1900;
} else {
yyyy += 2000;
}
mo = compute_decimal(buf[ 2], buf[ 3]);
dd = compute_decimal(buf[ 4], buf[ 5]);
hh = compute_decimal(buf[ 6], buf[ 7]);
mm = compute_decimal(buf[ 8], buf[ 9]);
ss = compute_decimal(buf[10], buf[11]);
/*
* Check values are valid (n.b.: no specific check required on
* the year, because UTC Time is guaranteed to be less than
* )
*/
tmp = 0;
tmp |= mo > 12; /* month */
tmp |= dd > 31; /* day */
tmp |= hh > 23; /* hour */
tmp |= mm > 59; /* min */
tmp |= ss > 59; /* sec */
if (tmp) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/* Export what we extracted */
*year = yyyy;
*month = mo;
*day = dd;
*hour = hh;
*min = mm;
*sec = ss;
ret = 0;
out:
if (!ret) {
*eaten = 15;
}
return ret;
}
/*@
@ requires 0x30 <= d1 <= 0x39;
@ requires 0x30 <= d2 <= 0x39;
@ requires 0x30 <= d3 <= 0x39;
@ requires 0x30 <= d4 <= 0x39;
@ ensures 0 <= \result <= 9999;
@ assigns \nothing;
@*/
u16 compute_year(u8 d1, u8 d2, u8 d3, u8 d4)
{
return ((u16)d1 - (u16)0x30) * 1000 +
((u16)d2 - (u16)0x30) * 100 +
((u16)d3 - (u16)0x30) * 10 +
((u16)d4 - (u16)0x30);
}
/*
* Validate generalizedTime (including the constraints from RFC 5280). Note that
* the code is very similar to the one above developed for UTCTime. It
* could be possible to merge the functions into a unique helper
* but this would impact readibility.
*/
/*@
@ requires len >= 0;
@ requires ((len > 0) && (buf != \null)) ==> \valid_read(buf + (0 .. (len - 1)));
@ requires \valid(eaten);
@ requires \valid(year);
@ requires \valid(month);
@ requires \valid(day);
@ requires \valid(hour);
@ requires \valid(min);
@ requires \valid(sec);
@ requires \separated(eaten, year, month, day, hour, min, sec, buf + (0 .. (len - 1)));
@ ensures \result < 0 || \result == 0;
@ ensures (\result == 0) ==> (*eaten <= len);
@ ensures (\result == 0) ==> (*eaten == 17);
@ ensures (len < 17) ==> \result < 0;
@ ensures (buf == \null) ==> \result < 0;
@ assigns *eaten, *year, *month, *day, *hour, *min, *sec;
@*/
static int parse_generalizedTime(const u8 *buf, u16 len, u16 *eaten,
u16 *year, u8 *month, u8 *day,
u8 *hour, u8 *min, u8 *sec)
{
u16 yyyy;
u8 mo, dd, hh, mm, ss;
const u8 c_zero = '0';
u8 time_type;
u16 time_len;
int ret = -__LINE__;
u8 i, tmp;
if (buf == NULL) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/*
* As described in section 4.1.2.5.2 of RFC 5280, we do
* expect the following encoding: YYYYMMDDHHMMSSZ, i.e.
* a length of at least 17 bytes for the buffer, i.e.
* an advertised length of 15 bytes for the string
* it contains.
*/
if (len < 17) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
time_type = buf[0];
if (time_type != ASN1_TYPE_GeneralizedTime) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
time_len = buf[1];
if (time_len != 15) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
buf += 2;
/*
* Check all first 14 characters are decimal digits and
* last one is character 'Z'
*/
/*@
@ loop invariant \valid_read(buf + i);
@ loop invariant \forall integer x ; 0 <= x < i ==>
0x30 <= buf[x] <= 0x39;
@ loop assigns i;
@ loop variant (14 - i);
@ */
for (i = 0; i < 14; i++) {
if (c_zero > buf[i]) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
if ((buf[i] - c_zero) > 9) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
}
if (buf[14] != 'Z') {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/*@ assert c_zero == 0x30; */
/*@ assert \forall integer x ; 0 <= x < 12 ==> 0x30 <= buf[x] <= 0x39; */
yyyy = compute_year(buf[0], buf[1], buf[2], buf[3]);
mo = compute_decimal(buf[ 4], buf[ 5]);
dd = compute_decimal(buf[ 6], buf[ 7]);
hh = compute_decimal(buf[ 8], buf[ 9]);
mm = compute_decimal(buf[10], buf[11]);
ss = compute_decimal(buf[12], buf[13]);
/*
* Check values are valid (n.b.: RFC 5280 requires the use of
* UTCTime for dates through the year 2049. Dates in 2050 or
* later MUST be encoded as GeneralizedTime.
*/
tmp = 0;
tmp |= yyyy <= 2049; /* year */
tmp |= mo > 12; /* month */
tmp |= dd > 31; /* day */
tmp |= hh > 23; /* hour */
tmp |= mm > 59; /* min */
tmp |= ss > 59; /* sec */
if (tmp) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/* Export what we extracted */
*year = yyyy;
*month = mo;
*day = dd;
*hour = hh;
*min = mm;
*sec = ss;
ret = 0;
out:
if (!ret) {
*eaten = 17;
}
return ret;
}
/*
* Time ::= CHOICE {
* utcTime UTCTime,
* generalTime GeneralizedTime }
*
*/
/*@
@ requires len >= 0;
@ requires ((len > 0) && (buf != \null)) ==> \valid_read(buf + (0 .. (len - 1)));
@ requires \valid(eaten);
@ requires \valid(eaten);
@ requires \valid(year);
@ requires \valid(month);
@ requires \valid(day);
@ requires \valid(hour);
@ requires \valid(min);
@ requires \valid(sec);
@ requires \separated(t_type,eaten,year,month,day,hour,min,sec,buf+(..));
@ ensures \result < 0 || \result == 0;
@ ensures (\result == 0) ==> (*eaten <= len);
@ ensures (len == 0) ==> \result < 0;
@ ensures (buf == \null) ==> \result < 0;
@ assigns *t_type, *eaten, *year, *month, *day, *hour, *min, *sec;
@*/
static int parse_Time(const u8 *buf, u16 len, u8 *t_type, u16 *eaten,
u16 *year, u8 *month, u8 *day,
u8 *hour, u8 *min, u8 *sec)
{
u8 time_type;
int ret = -__LINE__;
if ((buf == NULL) || (len == 0)) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
if (len < 2) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
time_type = buf[0];
switch (time_type) {
case ASN1_TYPE_UTCTime:
ret = parse_UTCTime(buf, len, eaten, year, month,
day, hour, min, sec);
if (ret) {
ERROR_TRACE_APPEND(__LINE__);
}
break;
case ASN1_TYPE_GeneralizedTime:
ret = parse_generalizedTime(buf, len, eaten, year, month,
day, hour, min, sec);
if (ret) {
ERROR_TRACE_APPEND(__LINE__);
}
break;
default:
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
break;
}
*t_type = time_type;
out:
if (ret) {
*eaten = 0;
}
return ret;
}
/*
* RFC 5280 has "CAs conforming to this profile MUST always encode certificate
* validity dates through the year 2049 as UTCTime; certificate validity dates
* in 2050 or later MUST be encoded as GeneralizedTime."
*
* This function performs that simple check. It returns 0 on success, a non
* zero value on error.
*/
/*@ ensures \result < 0 || \result == 0;
@ assigns \nothing;
@*/
static int _verify_correct_time_use(u8 time_type, u16 yyyy)
{
int ret;
switch (time_type) {
case ASN1_TYPE_UTCTime:
ret = (yyyy <= 2049) ? 0 : -__LINE__;
break;
case ASN1_TYPE_GeneralizedTime:
ret = (yyyy >= 2050) ? 0 : -__LINE__;
break;
default:
ret = -1;
break;
}
return ret;
}
/*
* Verify Validity by checking it is indeed a sequence of two
* valid UTCTime elements. Note that the function only perform
* syntaxic checks on each element individually and does not
* compare the two values together (e.g. to verify notBefore
* is indeed before notAfter, etc).
*/
/*@
@ requires len >= 0;
@ requires ((len > 0) && (buf != \null)) ==> \valid_read(buf + (0 .. (len - 1)));
@ requires \valid(eaten);
@ requires \separated(eaten, buf+(..));
@ ensures \result < 0 || \result == 0;
@ ensures (\result == 0) ==> (*eaten <= len);
@ ensures (len == 0) ==> \result < 0;
@ ensures (buf == \null) ==> \result < 0;
@ assigns *eaten;
@*/
static int parse_x509_Validity(const u8 *buf, u16 len, u16 *eaten)
{
int ret;
u16 hdr_len = 0;
u16 remain = 0;
u16 data_len = 0;
u16 nb_len = 0, na_len = 0, na_year = 0, nb_year = 0;
u8 na_month = 0, na_day = 0, na_hour = 0, na_min = 0, na_sec = 0;
u8 nb_month = 0, nb_day = 0, nb_hour = 0, nb_min = 0, nb_sec = 0;
u8 t_type = 0;
if ((buf == NULL) || (len == 0)) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/* Check we are dealing with a valid sequence */
ret = parse_id_len(buf, len, CLASS_UNIVERSAL, ASN1_TYPE_SEQUENCE,
&hdr_len, &data_len);
if (ret) {
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
buf += hdr_len;
remain = data_len;
/* Parse notBefore */
ret = parse_Time(buf, remain, &t_type, &nb_len, &nb_year, &nb_month,
&nb_day, &nb_hour, &nb_min, &nb_sec);
if (ret) {
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/* Check valid time type was used for year value */
ret = _verify_correct_time_use(t_type, nb_year);
if (ret) {
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
remain -= nb_len;
buf += nb_len;
/* Parse notAfter */
ret = parse_Time(buf, remain, &t_type, &na_len, &na_year, &na_month,
&na_day, &na_hour, &na_min, &na_sec);
if (ret) {
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/* Check valid time type was used for year value */
ret = _verify_correct_time_use(t_type, na_year);
if (ret) {
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
remain -= na_len;
if (remain) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/* Compare value to verify notAfter is indeed after notBefore */
if (na_year < nb_year) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
} else if (na_year == nb_year) { /* Same year, check difference */
u32 na_rem_secs, nb_rem_secs; /* sec in a year fit on u32 */
#define SEC_PER_MIN 60
#define SEC_PER_HOUR (60 * SEC_PER_MIN)
#define SEC_PER_DAY (24 * SEC_PER_HOUR)
#define SEC_PER_MONTH (31 * SEC_PER_DAY)
na_rem_secs = 0;
na_rem_secs += na_month * SEC_PER_MONTH;
na_rem_secs += na_day * SEC_PER_DAY;
na_rem_secs += na_hour * SEC_PER_HOUR;
na_rem_secs += na_min * SEC_PER_MIN;
na_rem_secs += na_sec;
nb_rem_secs = 0;
nb_rem_secs += nb_month * SEC_PER_MONTH;
nb_rem_secs += nb_day * SEC_PER_DAY;
nb_rem_secs += nb_hour * SEC_PER_HOUR;
nb_rem_secs += nb_min * SEC_PER_MIN;
nb_rem_secs += nb_sec;
if (na_rem_secs <= nb_rem_secs) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
}
*eaten = hdr_len + data_len;
ret = 0;
out:
return ret;
}
/* SubjectPublicKeyInfo,
*
* SubjectPublicKeyInfo ::= SEQUENCE {
* algorithm AlgorithmIdentifier,
* subjectPublicKey BIT STRING }
*
*/
/*@
@ requires len >= 0;
@ requires ((len > 0) && (buf != \null)) ==> \valid_read(buf + (0 .. (len - 1)));
@ requires \valid(eaten);
@ requires \separated(eaten, buf+(..));
@ ensures \result < 0 || \result == 0;
@ ensures (\result == 0) ==> (*eaten <= len);
@ ensures (len == 0) ==> \result < 0;
@ ensures (buf == \null) ==> \result < 0;
@ assigns *eaten;
@*/
static int parse_x509_subjectPublicKeyInfo(const u8 *buf, u16 len, u16 *eaten)
{
u16 hdr_len = 0, data_len = 0, parsed = 0, remain = 0;
const _alg_id *alg = NULL;
alg_param param;
int ret;
if ((buf == NULL) || (len == 0)) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/* Check we are dealing with a valid sequence */
ret = parse_id_len(buf, len, CLASS_UNIVERSAL, ASN1_TYPE_SEQUENCE,
&hdr_len, &data_len);
if (ret) {
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
buf += hdr_len;
remain = data_len;
// memset(¶m, 0, sizeof(param));
param.curve_param = NULL;
param.null_param = NULL;
param.ecdsa_no_param = 0;
param.unparsed_param = 0;
ret = parse_x509_AlgorithmIdentifier(buf, remain,
&alg, ¶m, &parsed);
if (ret) {
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
if (alg->alg_type != ALG_PUBKEY) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
buf += parsed;
remain -= parsed;
/*
* Let's now check if subjectPublicKey is ok based on the
* algorithm and parameters we found.
*/
if (!alg->parse_subjectpubkey) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/*@ calls parse_subjectpubkey_ec, parse_subjectpubkey_rsa ; @*/
ret = alg->parse_subjectpubkey(buf, remain, ¶m);
if (ret) {
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
*eaten = hdr_len + data_len;
ret = 0;
out:
return ret;
}
/*
* Extensions -- optional
*/
#if 0
/* WIP! */
/*
* RFC 5280 has "When the subjectAltName extension contains a domain name
* system label, the domain name MUST be stored in the dNSName (an
* IA5String). The name MUST be in the "preferred name syntax", as
* specified by Section 3.5 of [RFC1034] and as modified by Section 2.1
* of [RFC1123]. In addition, while the string " " is a legal domain name,
* subjectAltName extensions with a dNSName of " " MUST NOT be used."
* |
* This function implements that checks, namely: |
* |
* From 3.5 of RFC 1034: |
* |
* <domain> ::= <subdomain> | " " " " not allowed --+
*
* <subdomain> ::= <label> | <subdomain> "." <label>
*
* <label> ::= <letter> [ [ <ldh-str> ] <let-dig> ]
*
* <ldh-str> ::= <let-dig-hyp> | <let-dig-hyp> <ldh-str>
*
* <let-dig-hyp> ::= <let-dig> | "-"
*
* <let-dig> ::= <letter> | <digit>
*
* <letter> ::= any one of the 52 alphabetic characters A through Z in
* upper case and a through z in lower case
*
* <digit> ::= any one of the ten digits 0 through 9
*
* Note that while upper and lower case letters are allowed in domain
* names, no significance is attached to the case. That is, two names with
* the same spelling but different case are to be treated as if identical.
*
* The labels must follow the rules for ARPANET host names. They must
* start with a letter, end with a letter or digit, and have as interior
* characters only letters, digits, and hyphen. There are also some
* restrictions on the length. Labels must be 63 characters or less.
*
* From 2.1 of RFC 1123:
*
* The syntax of a legal Internet host name was specified in RFC-952
* [DNS:4]. One aspect of host name syntax is hereby changed: the
* restriction on the first character is relaxed to allow either a
* letter or a digit. Host software MUST support this more liberal
* syntax.
*
* Host software MUST handle host names of up to 63 characters and
* SHOULD handle host names of up to 255 characters.
*
* Whenever a user inputs the identity of an Internet host, it SHOULD
* be possible to enter either (1) a host domain name or (2) an IP
* address in dotted-decimal ("#.#.#.#") form. The host SHOULD check
* the string syntactically for a dotted-decimal number before
* looking it up in the Domain Name System.
*
*/
static int check_prefered_name_syntax(const u8 *buf, u16 len)
{
/* FIXME! */
ret = 0;
out:
return ret;
}
#endif
/*
* Parse GeneralName (used in SAN and AIA extensions)
*
* GeneralName ::= CHOICE {
* otherName [0] AnotherName,
* rfc822Name [1] IA5String,
* dNSName [2] IA5String,
* x400Address [3] ORAddress,
* directoryName [4] Name,
* ediPartyName [5] EDIPartyName,
* uniformResourceIdentifier [6] IA5String,
* iPAddress [7] OCTET STRING,
* registeredID [8] OBJECT IDENTIFIER }
*
* OtherName ::= SEQUENCE {
* type-id OBJECT IDENTIFIER,
* value [0] EXPLICIT ANY DEFINED BY type-id }
*
* EDIPartyName ::= SEQUENCE {
* nameAssigner [0] DirectoryString OPTIONAL,
* partyName [1] DirectoryString }
*
*/
#define NAME_TYPE_rfc822Name 0x81
#define NAME_TYPE_dNSName 0x82
#define NAME_TYPE_URI 0x86
#define NAME_TYPE_iPAddress 0x87
#define NAME_TYPE_registeredID 0x88
#define NAME_TYPE_otherName 0xa0
#define NAME_TYPE_x400Address 0xa3
#define NAME_TYPE_directoryName 0xa4
#define NAME_TYPE_ediPartyName 0xa5
/*@
@ requires len >= 0;
@ requires ((len > 0) && (buf != \null)) ==> \valid_read(buf + (0 .. (len - 1)));
@ requires \valid(eaten);
@ requires \separated(eaten, empty, buf+(..));
@ ensures \result < 0 || \result == 0;
@ ensures (\result == 0) ==> (1 < *eaten <= len);
@ ensures (\result == 0) ==> (0 <= *empty <= 1);
@ ensures (len == 0) ==> \result < 0;
@ ensures (buf == \null) ==> \result < 0;
@ assigns *eaten, *empty;
@*/
static int parse_GeneralName(const u8 *buf, u16 len, u16 *eaten, int *empty)
{
u16 remain = 0, name_len = 0, name_hdr_len = 0, grabbed = 0;
u8 name_type;
int ret;
if ((buf == NULL) || (len == 0)) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
if (len < 2) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
remain = len;
/*
* We expect the id for current name to be encoded on
* a single byte, i.e. we expect its MSB to be set.
*/
name_type = buf[0];
if (!(name_type & 0x80)) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
switch (name_type) {
case NAME_TYPE_rfc822Name: /* 0x81 - rfc822Name - IA5String */
case NAME_TYPE_dNSName: /* 0x82 - dNSName - IA5String */
case NAME_TYPE_URI: /* 0x86 - uniformResourceIdentifier - IA5String */
buf += 1;
remain -= 1;
ret = get_length(buf, remain, &name_len, &grabbed);
if (ret) {
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
buf += grabbed;
remain -= grabbed;
if (name_len > remain) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
ret = check_ia5_string(buf, name_len);
if (ret) {
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/* Now, do some more specific checks */
switch (name_type) {
case NAME_TYPE_rfc822Name: /* rfc822Name - IA5String */
/* FIXME! We should do more parsing on that one */
break;
case NAME_TYPE_dNSName: /* dNSName - IA5String */
/* FIXME! We should do more parsing on that one */
/*
* From section 4.2.1.6 of RFC5280:
* The name MUST be in the "preferred name syntax",
* as specified by Section 3.5 of [RFC1034] and as
* modified by Section 2.1 of [RFC1123].
*/
break;
case NAME_TYPE_URI: /* uniformResourceIdentifier - IA5String */
/* FIXME! We should do more parsing on that one */
break;
default:
break;
}
remain -= name_len;
buf += name_len;
*eaten = name_len + grabbed + 1;
*empty = !name_len;
/*@ assert *eaten > 1; */
break;
case NAME_TYPE_iPAddress: /* 0x87 - iPaddress - OCTET STRING */
buf += 1;
remain -= 1;
ret = get_length(buf, remain, &name_len, &grabbed);
if (ret) {
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
buf += grabbed;
remain -= grabbed;
if (name_len > remain) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/* FIXME! Check size is 4, resp. 16, for IPv4, resp. IPv6. */
remain -= name_len;
buf += name_len;
*eaten = name_len + grabbed + 1;
*empty = !name_len;
/*@ assert *eaten > 1; */
break;
case NAME_TYPE_otherName: /* 0xa0 - otherName - OtherName */
/* FIXME! unsupported */
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
break;
case NAME_TYPE_x400Address: /* 0xa3 - x400Address - ORAddress */
/* FIXME! unsupported */
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
break;
case NAME_TYPE_directoryName: /* 0xa4 - directoryName - Name */
ret = parse_id_len(buf, remain, CLASS_CONTEXT_SPECIFIC, 4,
&name_hdr_len, &name_len);
if (ret) {
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
buf += name_hdr_len;
remain = name_len;
ret = parse_x509_Name(buf, remain, &grabbed, empty);
if (ret) {
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
buf += grabbed;
remain -= grabbed;
if (remain) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
*eaten = name_hdr_len + name_len;
/*@ assert *eaten > 1; */
break;
case NAME_TYPE_ediPartyName: /* 0xa5 - ediPartyName - EDIPartyName */
/* FIXME! unsupported */
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
break;
case NAME_TYPE_registeredID: /* 0x88 - registeredID - OBJECT IDENTIFIER */
/* FIXME! unsupported */
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
break;
default:
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
break;
}
/*@ assert *eaten > 1; */
ret = 0;
out:
return ret;
}
/* GeneralNames ::= SEQUENCE SIZE (1..MAX) OF GeneralName */
/*@
@ requires len >= 0;
@ requires ((len > 0) && (buf != \null)) ==> \valid_read(buf + (0 .. (len - 1)));
@ requires \valid(eaten);
@ requires \separated(eaten, buf+(..));
@ ensures \result < 0 || \result == 0;
@ ensures (\result == 0) ==> (1 < *eaten <= len);
@ ensures (len == 0) ==> \result < 0;
@ ensures (buf == \null) ==> \result < 0;
@ assigns *eaten;
@*/
static int parse_GeneralNames(const u8 *buf, u16 len, tag_class exp_class,
u32 exp_type, u16 *eaten)
{
u16 remain, parsed = 0, hdr_len = 0, data_len = 0;
int ret, unused = 0;
if ((buf == NULL) || (len == 0)) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
ret = parse_id_len(buf, len, exp_class, exp_type,
&hdr_len, &data_len);
if (ret) {
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
buf += hdr_len;
remain = data_len;
/*@
@ loop assigns ret, buf, remain, parsed, unused;
@ loop invariant \valid_read(buf + (0 .. (remain - 1)));
@ loop variant remain;
@ */
while (remain) {
ret = parse_GeneralName(buf, remain, &parsed, &unused);
if (ret) {
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
remain -= parsed;
buf += parsed;
}
*eaten = hdr_len + data_len;
ret = 0;
out:
return ret;
}
/*@
@ requires len >= 0;
@ requires ((len > 0) && (buf != \null)) ==> \valid_read(buf + (0 .. (len - 1)));
@ requires \separated(eaten, buf+(..));
@ ensures \result < 0 || \result == 0;
@ ensures (\result == 0) ==> (1 < *eaten <= len);
@ ensures (len == 0) ==> \result < 0;
@ ensures (buf == \null) ==> \result < 0;
@ assigns *eaten;
@*/
static int parse_AccessDescription(const u8 *buf, u16 len, u16 *eaten)
{
const u8 id_ad_caIssuers_oid[] = { 0x06, 0x08, 0x2b, 0x06, 0x01, 0x05,
0x05, 0x07, 0x30, 0x01 };
const u8 id_ad_ocsp_oid[] = { 0x06, 0x08, 0x2b, 0x06, 0x01, 0x05,
0x05, 0x07, 0x30, 0x02 };
u16 remain, hdr_len = 0, data_len = 0, oid_len = 0;
u16 al_len = 0, saved_ad_len = 0;
int ret, found, unused;
if ((buf == NULL) || (len == 0)) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
remain = len;
ret = parse_id_len(buf, remain,
CLASS_UNIVERSAL, ASN1_TYPE_SEQUENCE,
&hdr_len, &data_len);
if (ret) {
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
saved_ad_len = hdr_len + data_len;
/*@ assert saved_ad_len <= len ; */
remain -= hdr_len;
/*@ assert remain >= data_len ; */
buf += hdr_len;
/* accessMethod is an OID */
ret = parse_OID(buf, data_len, &oid_len);
if (ret) {
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/*
* We only support the two OID that are reference in the RFC,
* i.e. id-ad-caIssuers and id-ad-ocsp.
*/
found = 0;
if (oid_len == sizeof(id_ad_caIssuers_oid)) {
found = !bufs_differ(buf, id_ad_caIssuers_oid, oid_len);
}
if ((!found) && (oid_len == sizeof(id_ad_ocsp_oid))) {
found = !bufs_differ(buf, id_ad_ocsp_oid, oid_len);
}
if (!found) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
buf += oid_len;
remain -= oid_len;
data_len -= oid_len;
/*@ assert remain >= data_len ; */
/* accessLocation is a GeneralName */
ret = parse_GeneralName(buf, data_len, &al_len, &unused);
if (ret) {
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/*
* FIXME! I guess we could do some specific parsing on the
* content of the generalName based on what is described
* in section 4.2.2.1 of RFC 5280.
*/
buf += al_len;
/*@ assert remain >= data_len >= al_len; */
remain -= al_len;
data_len -= al_len;
if (data_len) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
*eaten = saved_ad_len;
/*@ assert *eaten <= len ; */
ret = 0;
out:
return ret;
}
typedef struct {
int empty_subject;
int san_empty;
int san_critical;
int ca_true;
int bc_critical;
int has_ski;
int has_keyUsage;
int keyCertSign_set;
int cRLSign_set;
int pathLenConstraint_set;
int has_name_constraints;
int has_crldp;
int one_crldp_has_all_reasons;
int aki_has_keyIdentifier;
int self_signed;
} cert_parsing_ctx;
/*
* 4.2.2.1 - Certificate Authority Information Access
*
* id-pe-authorityInfoAccess OBJECT IDENTIFIER ::= { id-pe 1 }
*
* AuthorityInfoAccessSyntax ::=
* SEQUENCE SIZE (1..MAX) OF AccessDescription
*
* AccessDescription ::= SEQUENCE {
* accessMethod OBJECT IDENTIFIER,
* accessLocation GeneralName }
*
* id-ad OBJECT IDENTIFIER ::= { id-pkix 48 }
*
* id-ad-caIssuers OBJECT IDENTIFIER ::= { id-ad 2 }
*
* id-ad-ocsp OBJECT IDENTIFIER ::= { id-ad 1 }
*
* GeneralName ::= CHOICE {
* otherName [0] AnotherName,
* rfc822Name [1] IA5String,
* dNSName [2] IA5String,
* x400Address [3] ORAddress,
* directoryName [4] Name,
* ediPartyName [5] EDIPartyName,
* uniformResourceIdentifier [6] IA5String,
* iPAddress [7] OCTET STRING,
* registeredID [8] OBJECT IDENTIFIER }
*/
/*@
@ requires len >= 0;
@ requires ((len > 0) && (buf != \null)) ==> \valid_read(buf + (0 .. (len - 1)));
@ requires \valid(ctx);
@ requires \separated(ctx, buf+(..));
@ ensures \result <= 0;
@ ensures (len == 0) ==> \result < 0;
@ ensures (critical != 0) ==> \result < 0;
@ ensures (buf == \null) ==> \result < 0;
@ assigns \nothing;
@*/
static int parse_ext_AIA(const u8 *buf, u16 len, int critical, cert_parsing_ctx ATTRIBUTE_UNUSED *ctx)
{
u16 hdr_len = 0, data_len = 0, remain;
int ret;
if ((buf == NULL) || (len == 0)) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/*
* 4.2.2.1 of RFC5280 has "Conforming CAs MUST mark this
* extension as non-critical
*/
if (critical) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
remain = len;
/* Check we are dealing with a valid sequence */
ret = parse_id_len(buf, remain, CLASS_UNIVERSAL, ASN1_TYPE_SEQUENCE,
&hdr_len, &data_len);
if (ret) {
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
buf += hdr_len;
remain -= hdr_len;
/* We do expect sequence to exactly match the length */
if (remain != data_len) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/*
* Empty AIA extensions are not authorized (AIA is a non empty sequence
* of AccessDescription structures.
*/
if (!remain) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/*
* Iterate on AccessDescription structures: each is
* a sequence containing an accessMethod (an OID)
* and an accessLocation (a GeneralName).
*/
/*@
@ loop assigns ret, buf, remain;
@ loop invariant \valid_read(buf + (0 .. (remain - 1)));
@ loop variant remain;
@ */
while (remain) {
u16 parsed = 0;
ret = parse_AccessDescription(buf, remain, &parsed);
if (ret) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
remain -= parsed;
buf += parsed;
}
ret = 0;
out:
return ret;
}
/* 4.2.1.1. Authority Key Identifier
*
* id-ce-authorityKeyIdentifier OBJECT IDENTIFIER ::= { id-ce 35 }
*
* AuthorityKeyIdentifier ::= SEQUENCE {
* keyIdentifier [0] KeyIdentifier OPTIONAL,
* authorityCertIssuer [1] GeneralNames OPTIONAL,
* authorityCertSerialNumber [2] CertificateSerialNumber OPTIONAL }
* -- authorityCertIssuer and authorityCertSerialNumber MUST both
* -- be present or both be absent
*
* KeyIdentifier ::= OCTET STRING
*
*/
/*@
@ requires len >= 0;
@ requires ((len > 0) && (buf != \null)) ==> \valid_read(buf + (0 .. (len - 1)));
@ requires \valid(ctx);
@ requires \separated(ctx, buf+(..));
@ ensures \result <= 0;
@ ensures (len == 0) ==> \result < 0;
@ ensures (buf == \null) ==> \result < 0;
@ assigns *ctx;
@*/
static int parse_ext_AKI(const u8 *buf, u16 len, int critical, cert_parsing_ctx *ctx)
{
u16 hdr_len = 0, data_len = 0;
u16 key_id_hdr_len = 0, key_id_data_len = 0;
u16 remain;
u16 parsed = 0;
int ret, has_keyIdentifier = 0;
if ((buf == NULL) || (len == 0)) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/*
* As specified in section 4.2.1.1. of RFC 5280, it is recommended
* for conforming CA not to set the critical bit for AKI extension
*/
if (critical) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/* Check we are indeed dealing w/ a sequence */
ret = parse_id_len(buf, len, CLASS_UNIVERSAL, ASN1_TYPE_SEQUENCE,
&hdr_len, &data_len);
if (ret) {
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
buf += hdr_len;
remain = data_len;
if (len != (hdr_len + data_len)) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/*
* We should now find a KeyIdentifier or/and a couple of
* (GeneralNames, and CertificateSerialNumber).
*/
/*
* First, the KeyIdentifier if present (KeyIdentifier ::= OCTET STRING)
*/
ret = parse_id_len(buf, remain, CLASS_CONTEXT_SPECIFIC, 0,
&key_id_hdr_len, &key_id_data_len);
if (!ret) {
/* An empty KeyIdentifier does not make any sense. Drop it! */
if (!key_id_data_len) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
buf += key_id_hdr_len + key_id_data_len;
remain -= key_id_hdr_len + key_id_data_len;
has_keyIdentifier = 1;
}
/*
* See if a (GeneralNames, CertificateSerialNumber) couple follows.
* GeneralNames ::= SEQUENCE SIZE (1..MAX) OF GeneralName. We do
* not accept one w/o the other.
*/
ret = parse_GeneralNames(buf, remain, CLASS_CONTEXT_SPECIFIC, 1,
&parsed);
if (!ret) {
u16 cert_serial_len = 0;
buf += parsed;
remain -= parsed;
/* CertificateSerialNumber ::= INTEGER */
ret = parse_CertificateSerialNumber(buf, remain,
CLASS_CONTEXT_SPECIFIC, 2,
&cert_serial_len);
if (ret) {
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
buf += cert_serial_len;
remain -= cert_serial_len;
}
/* Nothing should remain behind */
if (remain) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
ctx->aki_has_keyIdentifier = has_keyIdentifier;
ret = 0;
out:
return ret;
}
/*
* 4.2.1.2. Subject Key Identifier
*
* SubjectKeyIdentifier ::= KeyIdentifier
* KeyIdentifier ::= OCTET STRING
*/
/*@
@ requires len >= 0;
@ requires ((len > 0) && (buf != \null)) ==> \valid_read(buf + (0 .. (len - 1)));
@ requires \valid(ctx);
@ requires \separated(ctx,buf+(..));
@ ensures \result <= 0;
@ ensures (len == 0) ==> \result < 0;
@ ensures (buf == \null) ==> \result < 0;
@ assigns *ctx;
@*/
static int parse_ext_SKI(const u8 *buf, u16 len, int critical, cert_parsing_ctx *ctx)
{
u16 key_id_hdr_len = 0, key_id_data_len = 0;
u16 remain;
int ret;
if ((buf == NULL) || (len == 0)) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
remain = len;
/*
* As specified in section 4.2.1.1. of RFC 5280, conforming CA
* must mark this extension as non-critical.
*/
if (critical) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
ret = parse_id_len(buf, remain, CLASS_UNIVERSAL, ASN1_TYPE_OCTET_STRING,
&key_id_hdr_len, &key_id_data_len);
if (ret) {
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
if (len != (key_id_hdr_len + key_id_data_len)) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/* An empty KeyIdentifier does not make any sense. Drop it! */
if (!key_id_data_len) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
remain -= key_id_hdr_len + key_id_data_len;
if (remain) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
ctx->has_ski = 1;
ret = 0;
out:
return ret;
}
/*
* X.509 certificates includes 2 definitions of named bit list which
* both define 9 flags: KeyUsage and ReasonFlags. For that reason, most
* of the decoding logic for the instances of this types (keyUsage
* extension, CRLDP and FreshestCRL) can be done in a single location.
*
* Note that the function enforces that at least one bit is set in the
* nit named bit list, as explicitly required at least for Key Usage.
* This is in sync with what is given in Appendix B of RFC 5280:
* "When DER encoding a named bit list, trailing zeros MUST be omitted.
* That is, the encoded value ends with the last named bit that is set
* to one."
*/
/*@
@ requires len >= 0;
@ requires ((len > 0) && (buf != \null)) ==> \valid_read(buf + (0 .. (len - 1)));
@ requires \separated(val, buf+(..));
@ ensures \result <= 0;
@ ensures (len == 0) ==> \result < 0;
@ ensures (buf == \null) ==> \result < 0;
@ assigns *val;
@*/
static int parse_nine_bit_named_bit_list(const u8 *buf, u16 len, u16 *val)
{
u8 k, non_signif;
int ret;
/*
* Initial content octet is required. It provides the number of
* non-significative bits at the end of the last bytes carrying
* the bitstring value.
*/
if ((buf == NULL) || (len == 0)) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/* ... and it must be in the range [0,7]. */
if (buf[0] & 0xf8) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/*
* We encode 9 bits of information in a named bit list bitstring.
* With the initial octet of the content octets (encoding the number
* of unused bits in the final octet), the whole content octets
* should be made of 1, 2 or 3 bytes.
*/
switch (len) {
case 1: /* 1 byte giving number of unused bits - no following bytes */
if (buf[0] != 0) {
/*
* The number of non-significative bits is non-zero
* but no bits are following. This is invalid.
*/
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
} else {
/*
* Last paragraph of section 4.2.1.3 of RFC 5280 has
* "When the keyUsage extension appears in a
* certificate, at least one of the bits
* MUST be set to 1.". Regarding ReasonFlags, this
* is not explictly stated but would not make sense
* either.
*/
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
break;
case 2: /* 1 byte giving number of unused bits - 1 following byte */
/*
* Last paragraph of section 4.2.1.3 of RFC 5280 has
* "When the keyUsage extension appears in a
* certificate, at least one of the bits
* MUST be set to 1". Regarding ReasonFlags, this would
* not make sense either to have an empty list.
*/
if (buf[1] == 0) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/*
* Now that we are sure at least one bit is set, we can see
* which one is the last one set to verify it matches what
* the byte giving the number of unused bits tells us. When
* we are dealing w/ non-significative bits, they should be
* set to 0 in the byte (11.2.1 of X.690).
* Additionally, keyUsage type is a NamedBitList-based
* bitstring, and for that reason X.680 clause 11.2.2 requires
* "the bitstring shall have all trailing 0 bits removed
* before it is encoded". This is also the conclusion of
* http://www.ietf.org/mail-archive/web/pkix/current/
* msg10424.html. This is also explicitly stated in Appendix B
* of RFC5280: "When DER encoding a named bit list, trailing
* zeros MUST be omitted. That is, the encoded value ends with
* the last named bit that is set to one."
*/
non_signif = 0;
/*@
@ loop assigns k, non_signif;
@ loop variant (8 - k);
@*/
for (k = 0; k < 8; k++) {
if ((buf[1] >> k) & 0x1) {
non_signif = k;
break;
}
}
if (buf[0] != non_signif) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/* Revert bits to provide a usable value to caller */
*val = 0;
/*@
@ loop invariant 0 <= k <= 8;
@ loop assigns k, *val;
@ loop variant (8 - k);
@*/
for (k = 0; k < 8; k++) {
*val |= ((buf[1] >> k) & 0x1) << (7 - k);
}
break;
case 3: /* 1 byte for unused bits - 2 following bytes */
/*
* keyUsage and ReasonFlags support at most 9 bits. When the
* named bit list bitstring is made of 1 byte giving unused
* bits and 2 following bytes, this means the 9th bit (i.e.
* bit 8, decipherOnly) is asserted.
* Because of that, the value of the byte giving the number
* of unused bits is necessarily set to 7.
*/
if ((buf[0] != 7) || (buf[2] != 0x80)) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/*
* Revert bits to provide a usable value to caller,
* working on first byte's bits and then on single
* MSB from second byte.
*/
*val = 0;
/*@
@ loop invariant 0 <= k <= 8;
@ loop assigns k, *val;
@ loop variant (8 - k);
@*/
for (k = 0; k < 8; k++) {
*val |= ((buf[1] >> k) & 0x1) << (7 - k);
}
*val |= buf[2] >> 7;
break;
default: /* too many bytes for encoding 9 poor bits */
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
ret = 0;
out:
return ret;
}
/* 4.2.1.3. Key Usage
*
* id-ce-keyUsage OBJECT IDENTIFIER ::= { id-ce 15 }
*
* KeyUsage ::= BIT STRING {
* digitalSignature (0),
* nonRepudiation (1), -- recent editions of X.509 have
* -- renamed this bit to contentCommitment
* keyEncipherment (2),
* dataEncipherment (3),
* keyAgreement (4),
* keyCertSign (5),
* cRLSign (6),
* encipherOnly (7),
* decipherOnly (8) }
*
*/
/*
* Masks for keyusage bits. Those masks are only usable on values
* returned by parse_nine_bit_named_bit_list(), i.e. reversed
* bits. Those not already used in the code are commented to avoid
* unused macros and make clang compiler happy.
*/
//#define KU_digitalSignature 0x0001
//#define KU_nonRepudiation 0x0002
//#define KU_keyEncipherment 0x0004
//#define KU_dataEncipherment 0x0008
#define KU_keyAgreement 0x0010
#define KU_keyCertSign 0x0020
#define KU_cRLSign 0x0040
#define KU_encipherOnly 0x0080
#define KU_decipherOnly 0x0100
/*@
@ requires len >= 0;
@ requires ((len > 0) && (buf != \null)) ==> \valid_read(buf + (0 .. (len - 1)));
@ requires \valid(ctx);
@ requires \separated(ctx,buf+(..));
@ ensures \result <= 0;
@ ensures (len == 0) ==> \result < 0;
@ ensures (buf == \null) ==> \result < 0;
@ assigns *ctx;
@*/
static int parse_ext_keyUsage(const u8 *buf, u16 len,
int ATTRIBUTE_UNUSED critical,
cert_parsing_ctx *ctx)
{
u16 val = 0, hdr_len = 0, data_len = 0;
int ret;
if ((buf == NULL) || (len == 0)) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/*
* As specified in section 4.2.1.3 of RFC 5280, when the extension
* is present, "conforming CAs SHOULD mark this extension as
* critical." For that reason, and because various CA emit certificates
* with critical bit not set, we do not enforce critical bit value.
*/
/* Check we are indeed dealing w/ a bit string */
ret = parse_id_len(buf, len, CLASS_UNIVERSAL, ASN1_TYPE_BIT_STRING,
&hdr_len, &data_len);
if (ret) {
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
if (len != (hdr_len + data_len)) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
buf += hdr_len;
len -= hdr_len;
/*
* As expected in section 4.2.1.3 of RFC 5280, the function will
* enforce that at least one bit is set : "When the keyUsage extension
* appears in a certificate, at least one of the bits MUST be set to 1"
*/
ret = parse_nine_bit_named_bit_list(buf, data_len, &val);
if (ret) {
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/*
* Section 4.2.1.3 of RFC 5280 has: "The meaning of the decipherOnly
* bit is undefined in the absence of the keyAgreement bit". We
* consider it invalid to have the former but not the latter.
*/
if ((val & KU_decipherOnly) && !(val & KU_keyAgreement)) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/*
* Section 4.2.1.3 of RFC 5280 has: "The meaning of the decipherOnly
* bit is undefined in the absence of the keyAgreement bit". We
* consider it invalid to have the former but not the latter.
*/
if ((val & KU_encipherOnly) && !(val & KU_keyAgreement)) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
ctx->has_keyUsage = 1;
ctx->keyCertSign_set = !!(val & KU_keyCertSign);
ctx->cRLSign_set = !!(val & KU_cRLSign);
ret = 0;
out:
return ret;
}
/* CPSuri ::= IA5String */
/*@
@ requires len >= 0;
@ requires ((len > 0) && (buf != \null)) ==> \valid_read(buf + (0 .. (len - 1)));
@ requires \valid(eaten);
@ requires \separated(eaten,buf+(..));
@ ensures \result <= 0;
@ ensures (\result == 0) ==> (*eaten <= len);
@ ensures (len == 0) ==> \result < 0;
@ ensures (buf == \null) ==> \result < 0;
@ assigns *eaten;
@*/
static int parse_CPSuri(const u8 *buf, u16 len, u16 *eaten)
{
int ret;
if ((buf == NULL) || (len == 0)) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
ret = parse_ia5_string(buf, len, 1, 65534);
if (ret) {
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
*eaten = len;
ret = 0;
out:
return ret;
}
/*
* DisplayText ::= CHOICE {
* ia5String IA5String (SIZE (1..200)),
* visibleString VisibleString (SIZE (1..200)),
* bmpString BMPString (SIZE (1..200)),
* utf8String UTF8String (SIZE (1..200)) }
*/
/*@
@ requires len >= 0;
@ requires ((len > 0) && (buf != \null)) ==> \valid_read(buf + (0 .. (len - 1)));
@ requires \valid(eaten);
@ requires \separated(eaten, buf+(..));
@ ensures \result <= 0;
@ ensures (\result == 0) ==> (*eaten <= len);
@ ensures (len == 0) ==> \result < 0;
@ ensures (buf == \null) ==> \result < 0;
@ assigns *eaten;
@*/
static int parse_DisplayText(const u8 *buf, u16 len, u16 *eaten)
{
u16 hdr_len = 0, data_len = 0;
u8 str_type;
int ret = -1;
if ((buf == NULL) || (len == 0)) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
str_type = buf[0];
switch (str_type) {
case STR_TYPE_UTF8_STRING: /* UTF8String */
case STR_TYPE_IA5_STRING: /* IA5String */
case STR_TYPE_VISIBLE_STRING: /* VisibileString */
case STR_TYPE_BMP_STRING: /* BMPString */
ret = parse_id_len(buf, len, CLASS_UNIVERSAL, str_type,
&hdr_len, &data_len);
if (ret) {
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
buf += hdr_len;
switch (str_type) {
case STR_TYPE_UTF8_STRING:
ret = check_utf8_string(buf, data_len);
if (ret) {
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
break;
case STR_TYPE_IA5_STRING:
ret = check_ia5_string(buf, data_len);
if (ret) {
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
break;
case STR_TYPE_VISIBLE_STRING:
ret = check_visible_string(buf, data_len);
if (ret) {
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
break;
case STR_TYPE_BMP_STRING:
ret = check_bmp_string(buf, data_len);
if (ret) {
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
break;
default:
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
break;
}
*eaten = hdr_len + data_len;
break;
default:
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
break;
}
out:
return ret;
}
/*
* NoticeReference ::= SEQUENCE {
* organization DisplayText,
* noticeNumbers SEQUENCE OF INTEGER }
*
* DisplayText ::= CHOICE {
* ia5String IA5String (SIZE (1..200)),
* visibleString VisibleString (SIZE (1..200)),
* bmpString BMPString (SIZE (1..200)),
* utf8String UTF8String (SIZE (1..200)) }
*
*/
/*@
@ requires len >= 0;
@ requires ((len > 0) && (buf != \null)) ==> \valid_read(buf + (0 .. (len - 1)));
@ requires \valid(eaten);
@ requires \separated(eaten, buf+(..));
@ ensures \result <= 0;
@ ensures (\result == 0) ==> (1 < *eaten <= len);
@ ensures (len == 0) ==> \result < 0;
@ ensures (buf == \null) ==> \result < 0;
@ assigns *eaten;
@*/
static int parse_NoticeReference(const u8 *buf, u16 len, u16 *eaten)
{
u16 remain, parsed = 0, saved_len = 0, hdr_len = 0, data_len = 0;
int ret;
if ((buf == NULL) || (len == 0)) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
remain = len;
/* NoticeReference is a sequence */
ret = parse_id_len(buf, remain, CLASS_UNIVERSAL, ASN1_TYPE_SEQUENCE,
&hdr_len, &data_len);
if (ret) {
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
saved_len = hdr_len + data_len;
remain = data_len;
buf += hdr_len;
/*
* First element of the sequence is the organization (of type
* DisplayText)
*/
ret = parse_DisplayText(buf, remain, &parsed);
if (ret) {
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
remain -= parsed;
buf += parsed;
/*
* Second element is the noticeNumbers, i.e. a sequence of
* integers.
*/
ret = parse_id_len(buf, remain, CLASS_UNIVERSAL, ASN1_TYPE_SEQUENCE,
&hdr_len, &data_len);
if (ret) {
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
remain -= hdr_len;
buf += hdr_len;
/* Advertised data in the sequence must exactly match what remains */
if (remain != data_len) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/* The sequence contains integers */
/*@
@ loop assigns ret, buf, remain, parsed;
@ loop invariant \valid_read(buf + (0 .. (remain - 1)));
@ loop variant remain;
@ */
while (remain) {
/* Verify the integer is encoded as it should */
ret = parse_integer(buf, remain,
CLASS_UNIVERSAL, ASN1_TYPE_INTEGER,
&parsed);
if (ret) {
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
remain -= parsed;
buf += parsed;
}
*eaten = saved_len;
ret = 0;
out:
return ret;
}
/*
* UserNotice ::= SEQUENCE {
* noticeRef NoticeReference OPTIONAL,
* explicitText DisplayText OPTIONAL }
*
* NoticeReference ::= SEQUENCE {
* organization DisplayText,
* noticeNumbers SEQUENCE OF INTEGER }
*
* DisplayText ::= CHOICE {
* ia5String IA5String (SIZE (1..200)),
* visibleString VisibleString (SIZE (1..200)),
* bmpString BMPString (SIZE (1..200)),
* utf8String UTF8String (SIZE (1..200)) }
*
*/
/*@
@ requires len >= 0;
@ requires ((len > 0) && (buf != \null)) ==> \valid_read(buf + (0 .. (len - 1)));
@ requires \valid(eaten);
@ requires \separated(eaten, buf+(..));
@ ensures \result <= 0;
@ ensures (\result == 0) ==> (*eaten <= len);
@ ensures (len == 0) ==> \result < 0;
@ ensures (buf == \null) ==> \result < 0;
@ assigns *eaten;
@*/
static int parse_UserNotice(const u8 *buf, u16 len, u16 *eaten)
{
u16 hdr_len = 0, data_len = 0, remain = 0, parsed = 0;
int ret;
if ((buf == NULL) || (len == 0)) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
remain = len;
/* USerNotice is a sequence */
ret = parse_id_len(buf, remain, CLASS_UNIVERSAL, ASN1_TYPE_SEQUENCE,
&hdr_len, &data_len);
if (ret) {
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
remain -= hdr_len;
buf += hdr_len;
/* Having an empty sequence is considered invalid */
if (!data_len) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/* First element (if present) is a noticeRef of type NoticeReference */
ret = parse_NoticeReference(buf, remain, &parsed);
if (!ret) {
remain -= parsed;
buf += parsed;
}
/* Second element (if present) is an explicitText of type DisplayText */
ret = parse_DisplayText(buf, remain, &parsed);
if (!ret) {
remain -= parsed;
buf += parsed;
}
if (remain) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
*eaten = hdr_len + data_len;
ret = 0;
out:
return ret;
}
/*
* PolicyQualifierInfo ::= SEQUENCE {
* policyQualifierId PolicyQualifierId,
* qualifier ANY DEFINED BY policyQualifierId }
*
* -- policyQualifierIds for Internet policy qualifiers
*
* id-qt OBJECT IDENTIFIER ::= { id-pkix 2 }
* id-qt-cps OBJECT IDENTIFIER ::= { id-qt 1 }
* id-qt-unotice OBJECT IDENTIFIER ::= { id-qt 2 }
*
* PolicyQualifierId ::= OBJECT IDENTIFIER ( id-qt-cps | id-qt-unotice )
*/
/*@
@ requires len >= 0;
@ requires ((len > 0) && (buf != \null)) ==> \valid_read(buf + (0 .. (len - 1)));
@ requires \valid(eaten);
@ requires \separated(eaten, buf+(..));
@ ensures \result <= 0;
@ ensures (\result == 0) ==> (1 < *eaten <= len);
@ ensures (len == 0) ==> \result < 0;
@ ensures (buf == \null) ==> \result < 0;
@ assigns *eaten;
@*/
static int parse_policyQualifierInfo(const u8 *buf, u16 len, u16 *eaten)
{
u16 hdr_len = 0, data_len = 0, oid_len = 0, remain = 0;
u8 id_qt_cps_oid[] = { 0x06, 0x08, 0x2b, 0x06, 0x01, 0x05, 0x05,
0x07, 0x02, 0x01 };
u8 id_qt_unotice_oid[] = { 0x06, 0x08, 0x2b, 0x06, 0x01, 0x05, 0x05,
0x07, 0x02, 0x02 };
int ret;
if ((buf == NULL) || (len == 0)) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/* It's a sequence */
ret = parse_id_len(buf, len, CLASS_UNIVERSAL, ASN1_TYPE_SEQUENCE,
&hdr_len, &data_len);
if (ret) {
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
remain = data_len;
buf += hdr_len;
/*
* First element of the sequence (policyQualifierId) is an OID
* which can either take a value of id-qt-cps or id-qt-unotice.
*/
ret = parse_OID(buf, remain, &oid_len);
if (ret) {
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
if ((oid_len == sizeof(id_qt_cps_oid)) &&
!bufs_differ(buf, id_qt_cps_oid, oid_len)) { /* id-qt-cps */
u16 cpsuri_len = 0;
buf += oid_len;
remain -= oid_len;
ret = parse_CPSuri(buf, remain, &cpsuri_len);
if (ret) {
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
remain -= cpsuri_len;
buf += cpsuri_len;
} else if ((oid_len == sizeof(id_qt_unotice_oid)) &&
!bufs_differ(buf, id_qt_unotice_oid, oid_len)) { /* id-qt-unotice */
u16 cpsunotice_len = 0;
buf += oid_len;
remain -= oid_len;
ret = parse_UserNotice(buf, remain, &cpsunotice_len);
if (ret) {
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
remain -= cpsunotice_len;
buf += cpsunotice_len;
} else { /* unsupported! */
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
*eaten = hdr_len + data_len;
ret = 0;
out:
return ret;
}
/*
* PolicyInformation ::= SEQUENCE {
* policyIdentifier CertPolicyId,
* policyQualifiers SEQUENCE SIZE (1..MAX) OF
* PolicyQualifierInfo OPTIONAL }
*/
/*@
@ requires len >= 0;
@ requires ((len > 0) && (buf != \null)) ==> \valid_read(buf + (0 .. (len - 1)));
@ requires \valid(eaten);
@ requires \separated(eaten,buf+(..));
@ ensures \result <= 0;
@ ensures (\result == 0) ==> (1 < *eaten <= len);
@ ensures (len == 0) ==> \result < 0;
@ ensures (buf == \null) ==> \result < 0;
@ assigns *eaten;
@*/
static int parse_PolicyInformation(const u8 *buf, u16 len, u16 *eaten)
{
u16 hdr_len = 0, data_len = 0, oid_len = 0, saved_pi_len, remain;
int ret;
if ((buf == NULL) || (len == 0)) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
ret = parse_id_len(buf, len, CLASS_UNIVERSAL, ASN1_TYPE_SEQUENCE,
&hdr_len, &data_len);
if (ret) {
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
saved_pi_len = hdr_len + data_len;
remain = data_len;
buf += hdr_len;
/* policyIdentifier is a CertPolicyId, i.e. an OID */
ret = parse_OID(buf, remain, &oid_len);
if (ret) {
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
remain -= oid_len;
buf += oid_len;
/* policyQualifiers is optional */
if (remain) {
/* policyQualifiers is a sequence */
ret = parse_id_len(buf, remain,
CLASS_UNIVERSAL, ASN1_TYPE_SEQUENCE,
&hdr_len, &data_len);
if (ret) {
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
remain -= hdr_len;
buf += hdr_len;
/* Nothing should remain after policyQualifiers */
if (remain != data_len) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/*
* Let's parse each PolicyQualifierInfo in the
* policyQualifiers sequence
*/
/*@
@ loop assigns ret, buf, remain;
@ loop invariant \valid_read(buf + (0 .. (remain - 1)));
@ loop variant remain;
@ */
while (remain) {
u16 pqi_len = 0;
ret = parse_policyQualifierInfo(buf, remain, &pqi_len);
if (ret) {
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
remain -= pqi_len;
buf += pqi_len;
}
}
*eaten = saved_pi_len;
/*
* FIXME! At that point, we should verify we know the OID
* (policyIdentifier) and the associated optional
* content is indeed valid.
*/
ret = 0;
out:
return ret;
}
/* 4.2.1.4. Certificate Policies
*
* id-ce-certificatePolicies OBJECT IDENTIFIER ::= { id-ce 32 }
*
* anyPolicy OBJECT IDENTIFIER ::= { id-ce-certificatePolicies 0 }
*
* certificatePolicies ::= SEQUENCE SIZE (1..MAX) OF PolicyInformation
*
* PolicyInformation ::= SEQUENCE {
* policyIdentifier CertPolicyId,
* policyQualifiers SEQUENCE SIZE (1..MAX) OF
* PolicyQualifierInfo OPTIONAL }
*
* CertPolicyId ::= OBJECT IDENTIFIER
*
* PolicyQualifierInfo ::= SEQUENCE {
* policyQualifierId PolicyQualifierId,
* qualifier ANY DEFINED BY policyQualifierId }
*
* -- policyQualifierIds for Internet policy qualifiers
*
* id-qt OBJECT IDENTIFIER ::= { id-pkix 2 }
* id-qt-cps OBJECT IDENTIFIER ::= { id-qt 1 }
* id-qt-unotice OBJECT IDENTIFIER ::= { id-qt 2 }
*
* PolicyQualifierId ::= OBJECT IDENTIFIER ( id-qt-cps | id-qt-unotice )
*
* Qualifier ::= CHOICE {
* cPSuri CPSuri,
* userNotice UserNotice }
*
* CPSuri ::= IA5String
*
* UserNotice ::= SEQUENCE {
* noticeRef NoticeReference OPTIONAL,
* explicitText DisplayText OPTIONAL }
*
* NoticeReference ::= SEQUENCE {
* organization DisplayText,
* noticeNumbers SEQUENCE OF INTEGER }
*
* DisplayText ::= CHOICE {
* ia5String IA5String (SIZE (1..200)),
* visibleString VisibleString (SIZE (1..200)),
* bmpString BMPString (SIZE (1..200)),
* utf8String UTF8String (SIZE (1..200)) }
*
*/
/*@
@ requires len >= 0;
@ requires ((len > 0) && (buf != \null)) ==> \valid_read(buf + (0 .. (len - 1)));
@ requires \valid(ctx);
@ requires \separated(ctx, buf+(..));
@ ensures \result <= 0;
@ ensures (len == 0) ==> \result < 0;
@ ensures (buf == \null) ==> \result < 0;
@ assigns \nothing;
@*/
static int parse_ext_certPolicies(const u8 *buf, u16 len,
int ATTRIBUTE_UNUSED critical,
cert_parsing_ctx ATTRIBUTE_UNUSED *ctx)
{
u16 remain = 0, data_len = 0, hdr_len = 0, eaten = 0;
int ret;
if ((buf == NULL) || (len == 0)) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/*
* FIXME!
*
* This one will be a pain to deal with if we decide
* to support the full version, i.e. non empty sequence
* for policyQualifiersOID. RFC 5280 has:
*
* To promote interoperability, this profile RECOMMENDS that policy
* information terms consist of only an OID. Where an OID alone is
* insufficient, this profile strongly recommends that the use of
* qualifiers be limited to those identified in this section. When
* qualifiers are used with the special policy anyPolicy, they MUST be
* limited to the qualifiers identified in this section. Only those
* qualifiers returned as a result of path validation are considered.
*
*/
ret = parse_id_len(buf, len, CLASS_UNIVERSAL, ASN1_TYPE_SEQUENCE,
&hdr_len, &data_len);
if (ret) {
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
buf += hdr_len;
remain = data_len;
if (len != (hdr_len + data_len)) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/* Let's now check each individual PolicyInformation sequence */
/*@
@ loop assigns ret, buf, remain, eaten;
@ loop invariant \valid_read(buf + (0 .. (remain - 1)));
@ loop variant remain;
@ */
while (remain) {
ret = parse_PolicyInformation(buf, remain, &eaten);
if (ret) {
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
remain -= eaten;
buf += eaten;
}
ret = 0;
out:
return ret;
}
/*
* 4.2.1.5. Policy Mappings
*
* id-ce-policyMappings OBJECT IDENTIFIER ::= { id-ce 33 }
*
* PolicyMappings ::= SEQUENCE SIZE (1..MAX) OF SEQUENCE {
* issuerDomainPolicy CertPolicyId,
* subjectDomainPolicy CertPolicyId }
*
* CertPolicyId ::= OBJECT IDENTIFIER
*
*/
/*@
@ requires len >= 0;
@ requires ((len > 0) && (buf != \null)) ==> \valid_read(buf + (0 .. (len - 1)));
@ requires \valid(ctx);
@ requires \separated(ctx,buf+(..));
@ ensures \result <= 0;
@ ensures (len == 0) ==> \result < 0;
@ ensures (buf == \null) ==> \result < 0;
@ assigns \nothing;
@*/
static int parse_ext_policyMapping(const u8 *buf, u16 len, int critical,
cert_parsing_ctx ATTRIBUTE_UNUSED *ctx)
{
u16 remain = 0, data_len = 0, hdr_len = 0, eaten = 0;
int ret;
if ((buf == NULL) || (len == 0)) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/*
* As specified in section 4.2.1.5. of RFC 5280, "conforming CAs
* SHOULD mark this extension as critical".
*/
if (!critical) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/* Let's first check we are dealing with a valid sequence */
ret = parse_id_len(buf, len, CLASS_UNIVERSAL, ASN1_TYPE_SEQUENCE,
&hdr_len, &data_len);
if (ret) {
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
buf += hdr_len;
remain = data_len;
if (len != (hdr_len + data_len)) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/* Let's now check each sequence of {issuer,subject}DomainPolicy pair */
/*@
@ loop assigns ret, buf, remain, hdr_len, data_len, eaten;
@ loop invariant \valid_read(buf + (0 .. (remain - 1)));
@ loop variant remain;
@ */
while (remain) {
ret = parse_id_len(buf, remain,
CLASS_UNIVERSAL, ASN1_TYPE_SEQUENCE,
&hdr_len, &data_len);
if (ret) {
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
buf += hdr_len;
remain -= hdr_len;
/* issuerDomainPolicy (an OID)*/
ret = parse_OID(buf, data_len, &eaten);
if (ret) {
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
buf += eaten;
remain -= eaten;
data_len -= eaten;
/* subjectDomainPolicy (an OID) */
ret = parse_OID(buf, data_len, &eaten);
if (ret) {
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
data_len -= eaten;
if (data_len) {
/*
* Nothing should follow the two OIDs
* in the sequence.
*/
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
buf += eaten;
remain -= eaten;
}
ret = 0;
out:
return ret;
}
/* 4.2.1.6. Subject Alternative Name
*
* id-ce-subjectAltName OBJECT IDENTIFIER ::= { id-ce 17 }
*
* SubjectAltName ::= GeneralNames
*
* GeneralNames ::= SEQUENCE SIZE (1..MAX) OF GeneralName
*
* GeneralName ::= CHOICE {
* otherName [0] OtherName,
* rfc822Name [1] IA5String,
* dNSName [2] IA5String,
* x400Address [3] ORAddress,
* directoryName [4] Name,
* ediPartyName [5] EDIPartyName,
* uniformResourceIdentifier [6] IA5String,
* iPAddress [7] OCTET STRING,
* registeredID [8] OBJECT IDENTIFIER }
*
* OtherName ::= SEQUENCE {
* type-id OBJECT IDENTIFIER,
* value [0] EXPLICIT ANY DEFINED BY type-id }
*
* EDIPartyName ::= SEQUENCE {
* nameAssigner [0] DirectoryString OPTIONAL,
* partyName [1] DirectoryString }
*
*/
/*@
@ requires len >= 0;
@ requires ((len > 0) && (buf != \null)) ==> \valid_read(buf + (0 .. (len - 1)));
@ requires \valid(ctx);
@ requires \separated(ctx, buf+(..));
@ ensures \result <= 0;
@ ensures (len == 0) ==> \result < 0;
@ ensures (buf == \null) ==> \result < 0;
@ assigns *ctx;
@*/
static int parse_ext_SAN(const u8 *buf, u16 len, int critical, cert_parsing_ctx *ctx)
{
u16 data_len = 0, hdr_len = 0, remain = 0, eaten = 0;
int ret, san_empty, empty_gen_name;
if ((buf == NULL) || (len == 0)) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/* Let's first check we are dealing with a valid sequence */
ret = parse_id_len(buf, len, CLASS_UNIVERSAL, ASN1_TYPE_SEQUENCE,
&hdr_len, &data_len);
if (ret) {
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/*
* As specified in section 4.2.1.6. of RFC 5280, "if the subjectAltName
* extension is present, the sequence MUST contain at least one entry.
*/
if (!data_len) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
buf += hdr_len;
remain = data_len;
if (len != (hdr_len + data_len)) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
san_empty = (remain == 0);
/*@
@ loop assigns ret, buf, remain, eaten, empty_gen_name;
@ loop invariant \valid_read(buf + (0 .. (remain - 1)));
@ loop variant remain;
@ */
while (remain) {
empty_gen_name = 0;
ret = parse_GeneralName(buf, remain, &eaten, &empty_gen_name);
if (ret) {
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/*
* Section 4.2.16 of RFC 5280 has "Unlike the subject field,
* conforming CAs MUST NOT issue certificates with
* subjectAltNames containing empty GeneralName fields.
*/
if (empty_gen_name) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/*
* RFC5280 has: "When the subjectAltName extension contains an
* iPAddress, the address MUST be stored in the octet string in
* "network byte order", as specified in [RFC791]. The least
* significant bit (LSB) of each octet is the LSB of the
* corresponding byte in the network address. For IP version
* 4, as specified in [RFC791], the octet string MUST contain
* exactly four octets. For IP version 6, as specified in
* [RFC2460], the octet string MUST contain exactly sixteen
* octets.
*/
if (buf[0] == NAME_TYPE_iPAddress) {
switch (eaten) {
case 6: /* id/len/IPv4(4 bytes) */
break;
case 18: /* id/len/IPv6(16 bytes) */
break;
default: /* invalid */
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
break;
}
}
remain -= eaten;
buf += eaten;
}
/*
* Now that we know the extension is valid, let's record some
* useful info.
*/
ctx->san_empty = san_empty;
ctx->san_critical = critical;
ret = 0;
out:
return ret;
}
/* 4.2.1.7. Issuer Alternative Name */
/*@
@ requires len >= 0;
@ requires ((len > 0) && (buf != \null)) ==> \valid_read(buf + (0 .. (len - 1)));
@ requires \valid(ctx);
@ requires \separated(ctx, buf+(..));
@ ensures \result <= 0;
@ ensures (len == 0) ==> \result < 0;
@ ensures (buf == \null) ==> \result < 0;
@ assigns \nothing;
@*/
static int parse_ext_IAN(const u8 *buf, u16 len, int ATTRIBUTE_UNUSED critical,
cert_parsing_ctx ATTRIBUTE_UNUSED *ctx)
{
u16 data_len = 0, hdr_len = 0, remain = 0, eaten = 0;
int ret, unused = 0;
if ((buf == NULL) || (len == 0)) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/*
* Section 4.2.1.7 of RFC 5280 has "Where present, conforming CAs
* SHOULD mark this extension as non-critical."
*
* FIXME! add a check?
*/
/* Let's first check we are dealing with a valid sequence */
ret = parse_id_len(buf, len, CLASS_UNIVERSAL, ASN1_TYPE_SEQUENCE,
&hdr_len, &data_len);
if (ret) {
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/*
* As specified in section 4.2.1.6. of RFC 5280, "if the subjectAltName
* extension is present, the sequence MUST contain at least one entry.
* Unlike the subject field, conforming CAs MUST NOT issue certificates
* with subjectAltNames containing empty GeneralName fields.
*
* The first check is done here.
*
* FIXME! second check remains to be done. Possibly in adding an additional
* out parameter to parse_GeneralName(), to tell if an empty one is
* empty. This is because
*/
if (!data_len) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
buf += hdr_len;
remain = data_len;
if (len != (hdr_len + data_len)) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/*@
@ loop assigns ret, buf, remain, eaten, unused;
@ loop invariant \valid_read(buf + (0 .. (remain - 1)));
@ loop variant remain;
@ */
while (remain) {
ret = parse_GeneralName(buf, remain, &eaten, &unused);
if (ret) {
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
remain -= eaten;
buf += eaten;
}
ret = 0;
out:
return ret;
}
/*
* 4.2.1.8. Subject Directory Attributes
*
* id-ce-subjectDirectoryAttributes OBJECT IDENTIFIER ::= { id-ce 9 }
*
* SubjectDirectoryAttributes ::= SEQUENCE SIZE (1..MAX) OF Attribute
*
* Attribute ::= SEQUENCE {
* type AttributeType,
* values SET OF AttributeValue
* -- at least one value is required --
* }
*
* AttributeType ::= OBJECT IDENTIFIER
*
* AttributeValue ::= ANY -- DEFINED BY AttributeType
*
*/
/*@
@ requires len >= 0;
@ requires ((len > 0) && (buf != \null)) ==> \valid_read(buf + (0 .. (len - 1)));
@ requires \valid(ctx);
@ requires \separated(ctx, buf+(..));
@ ensures \result <= 0;
@ ensures (len == 0) ==> \result < 0;
@ ensures (buf == \null) ==> \result < 0;
@ assigns \nothing;
@*/
static int parse_ext_subjectDirAttr(const u8 *buf, u16 len, int critical,
cert_parsing_ctx ATTRIBUTE_UNUSED *ctx)
{
u16 hdr_len = 0, data_len = 0, oid_len = 0, remain = 0;
int ret;
if ((buf == NULL) || (len == 0)) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/*
* As specified in section 4.2.1.8. of RFC 5280, conforming CAs
* MUST mark this extension as non-critical.
*/
if (critical) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/* Let's first check we are dealing with a valid sequence */
ret = parse_id_len(buf, len, CLASS_UNIVERSAL, ASN1_TYPE_SEQUENCE,
&hdr_len, &data_len);
if (ret) {
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
buf += hdr_len;
remain = data_len;
if (len != (hdr_len + data_len)) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/*@
@ loop assigns ret, buf, remain, hdr_len, data_len, oid_len;
@ loop invariant \valid_read(buf + (0 .. (remain - 1)));
@ loop variant remain;
@ */
while (remain) {
/* Parse current attribute. Each one is a sequence ... */
ret = parse_id_len(buf, remain,
CLASS_UNIVERSAL, ASN1_TYPE_SEQUENCE,
&hdr_len, &data_len);
if (ret) {
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
buf += hdr_len;
remain -= hdr_len;
/* ... containing an OID (AttributeType) */
ret = parse_OID(buf, data_len, &oid_len);
if (ret) {
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/* FIXME! check the value depanding on the OID */
remain -= data_len;
buf += data_len;
}
ret = 0;
out:
return ret;
}
/* 4.2.1.9. Basic Constraints
*
* id-ce-basicConstraints OBJECT IDENTIFIER ::= { id-ce 19 }
*
* BasicConstraints ::= SEQUENCE {
* cA BOOLEAN DEFAULT FALSE,
* pathLenConstraint INTEGER (0..MAX) OPTIONAL }
*
*/
/*@
@ requires len >= 0;
@ requires ((len > 0) && (buf != \null)) ==> \valid_read(buf + (0 .. (len - 1)));
@ requires \valid(ctx);
@ requires \separated(ctx, buf+(..));
@ ensures \result <= 0;
@ ensures (len == 0) ==> \result < 0;
@ ensures (buf == \null) ==> \result < 0;
@ assigns *ctx;
@*/
static int parse_ext_basicConstraints(const u8 *buf, u16 len, int critical,
cert_parsing_ctx *ctx)
{
u16 hdr_len = 0, data_len = 0;
const u8 ca_true_wo_plc[] = { 0x01, 0x01, 0xff };
const u8 ca_true_w_plc[] = { 0x01, 0x01, 0xff, 0x02, 0x01 };
int ret;
if ((buf == NULL) || (len == 0)) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/* Record if basicConstraints extension was mared critical */
ctx->bc_critical = critical;
/* Let's first check we are dealing with a valid sequence */
ret = parse_id_len(buf, len, CLASS_UNIVERSAL, ASN1_TYPE_SEQUENCE,
&hdr_len, &data_len);
if (ret) {
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
buf += hdr_len;
if (len != (hdr_len + data_len)) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/*
* Only the following cases are valid/reasonable:
*
* 1) an empty sequence (cA default to false, resulting in
* no pathLenConstraint): { }
* 2) cA is explicitly set to TRUE and no pathLenConstraint
* is enforced. { 0x01, 0x01, 0xff }
* 3) cA is explicitly set to TRUE and a pathLenConstraint
* is enforced, in which case it is reasonable to limit
* allowed pathLenConstraint values to [0, 255]:
* { 0x01, 0x01, 0xff, 0x02, 0x01, 0xXX }
*
* Note:
*
* - encoding an explicit FALSE value for cA is invalid
* because this is the default value.
* - providing a pathLenConstraint w/o setting cA boolean
* does not make sense
*/
switch (data_len) {
case 0: /* empty sequence */
ret = 0;
break;
case 3: /* cA set, no pathLenConstraint */
ret = bufs_differ(buf, ca_true_wo_plc, 3);
if (ret) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
ctx->ca_true = 1;
break;
case 6: /* cA set, pathLenConstraint given ([0,127] allowed) */
ret = bufs_differ(buf, ca_true_w_plc, 5);
if (ret) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/*
* Section 4.2.1.9 of RFC 5280 has "Where it appears, the
* pathLenConstraint field MUST be greater than or equal
* to zero". We check MSB is not set, indicating it is
* positive.
*/
if (buf[5] & 0x80) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
ctx->ca_true = 1;
ctx->pathLenConstraint_set = 1;
break;
default: /* crap */
ret = -__LINE__;
break;
}
out:
return ret;
}
/* 4.2.1.10. Name Constraints */
/*
* Parse GeneralSubtrees structure.
*
* GeneralSubtree ::= SEQUENCE {
* base GeneralName,
* minimum [0] BaseDistance DEFAULT 0,
* maximum [1] BaseDistance OPTIONAL }
*
* BaseDistance ::= INTEGER (0..MAX)
*
*/
/*@
@ requires len >= 0;
@ requires ((len > 0) && (buf != \null)) ==> \valid_read(buf + (0 .. (len - 1)));
@ ensures \result <= 0;
@ ensures (len == 0) ==> \result < 0;
@ ensures (buf == \null) ==> \result < 0;
@ assigns \nothing;
@*/
static int parse_GeneralSubtrees(const u8 *buf, u16 len)
{
u16 hdr_len = 0, remain = 0, grabbed = 0, data_len = 0;
int ret, unused = 0;
if ((buf == NULL) || (len == 0)) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
ret = parse_id_len(buf, len, CLASS_UNIVERSAL, ASN1_TYPE_SEQUENCE,
&hdr_len, &data_len);
if (ret) {
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
buf += hdr_len;
remain = data_len;
/* base is a GeneralName */
ret = parse_GeneralName(buf, remain, &grabbed, &unused);
if (ret) {
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
buf += grabbed;
remain -= grabbed;
/*
* Section 4.2.1.10 of RFC5280 has "Within this profile, the minimum
* and maximum fields are not used with any name forms, thus, the
* minimum MUST be zero, ...
*
* Note: as the minum defaults to 0 in its definition, the field
* must be absent (i.e. cannot be present with a value of 0),
* as expected in DER encoding (11.5 of X.690 has: "the encoding of
* a set value or sequence value shall not include an encoding for
* any component value which is equal to its default value.)"
*/
ret = parse_id_len(buf, remain, CLASS_CONTEXT_SPECIFIC, 0,
&hdr_len, &data_len);
if (!ret) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/* ... and maximum MUST be absent." */
ret = parse_id_len(buf, remain, CLASS_CONTEXT_SPECIFIC, 1,
&hdr_len, &data_len);
if (!ret) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/* Nothing should remain behind */
if (remain) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
ret = 0;
out:
return ret;
}
/*@
@ requires len >= 0;
@ requires ((len > 0) && (buf != \null)) ==> \valid_read(buf + (0 .. (len - 1)));
@ requires \valid(ctx);
@ requires \separated(ctx, buf+(..));
@ ensures \result < 0 || \result == 0;
@ ensures (len == 0) ==> \result < 0;
@ ensures (buf == \null) ==> \result < 0;
@ assigns *ctx;
@*/
static int parse_ext_nameConstraints(const u8 *buf, u16 len, int critical,
cert_parsing_ctx *ctx)
{
u16 remain = 0, hdr_len = 0, data_len = 0;
int ret;
if ((buf == NULL) || (len == 0)) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/*
* Section 4.2.1.10 of RFC 5280 has "Conforming CAs MUST mark
* this extension as critical.
*/
if (!critical) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/* Let's first check we are dealing with a valid sequence */
ret = parse_id_len(buf, len, CLASS_UNIVERSAL, ASN1_TYPE_SEQUENCE,
&hdr_len, &remain);
if (ret) {
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
buf += hdr_len;
/*
* 4.2.1.10 has: "Conforming CAs MUST NOT issue certificates
* where name constraints is an empty sequence
*/
if (!remain) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/* Check if we have a permittedSubtrees structure */
ret = parse_id_len(buf, remain, CLASS_CONTEXT_SPECIFIC, 0,
&hdr_len, &data_len);
if (!ret) {
buf += hdr_len;
remain -= hdr_len;
ret = parse_GeneralSubtrees(buf, data_len);
if (ret) {
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
buf += data_len;
remain -= data_len;
}
/* Check if we have an excludedSubtrees structure */
ret = parse_id_len(buf, remain, CLASS_CONTEXT_SPECIFIC, 1,
&hdr_len, &data_len);
if (!ret) {
buf += hdr_len;
remain -= hdr_len;
ret = parse_GeneralSubtrees(buf, data_len);
if (ret) {
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
buf += data_len;
remain -= data_len;
}
if (remain) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
ctx->has_name_constraints = 1;
ret = 0;
out:
return ret;
}
/*
* 4.2.1.11. Policy Constraints
*
* id-ce-policyConstraints OBJECT IDENTIFIER ::= { id-ce 36 }
*
* PolicyConstraints ::= SEQUENCE {
* requireExplicitPolicy [0] SkipCerts OPTIONAL,
* inhibitPolicyMapping [1] SkipCerts OPTIONAL }
*
* SkipCerts ::= INTEGER (0..MAX)
*
*/
/*@
@ requires len >= 0;
@ requires ((len > 0) && (buf != \null)) ==> \valid_read(buf + (0 .. (len - 1)));
@ requires \valid(ctx);
@ requires \separated(ctx, buf+(..));
@ ensures \result <= 0;
@ ensures (len == 0) ==> \result < 0;
@ ensures (buf == \null) ==> \result < 0;
@ assigns \nothing;
@*/
static int parse_ext_policyConstraints(const u8 *buf, u16 len, int critical,
cert_parsing_ctx ATTRIBUTE_UNUSED *ctx)
{
u16 data_len = 0, hdr_len = 0, remain = 0, parsed = 0;
int ret;
if ((buf == NULL) || (len == 0)) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/*
* Section 4.2.1.11 of RFC 5280 has "Conforming CAs MUST mark this
* extension as critical".
*/
if (!critical) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/* Let's first check we are dealing with a valid sequence */
ret = parse_id_len(buf, len, CLASS_UNIVERSAL, ASN1_TYPE_SEQUENCE,
&hdr_len, &data_len);
if (ret) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/*
* Section 4.2.1.11 of RFC 5280 has "Conforming CAs MUST NOT issue
* certificates where policy constraints is an empty sequence".
*/
if (data_len == 0) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
buf += hdr_len;
remain = data_len;
/* Check if we have a requireExplicitPolicy */
ret = parse_integer(buf, remain, CLASS_CONTEXT_SPECIFIC, 0,
&parsed);
if (!ret) {
/*
* As the value is expected to be a very small integer,
* content should be encoded on at most 1 byte, i.e.
* 'parsed' value should be 3 (w/ 2 bytes header).
*/
if (parsed != 3) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
buf += parsed;
remain -= parsed;
}
/* Check if we have an inhibitPolicyMapping */
ret = parse_integer(buf, remain, CLASS_CONTEXT_SPECIFIC, 1,
&parsed);
if (!ret) {
/*
* As the value is expected to be a very small integer,
* content should be encoded on at most 1 byte, i.e.
* 'parsed' value should be 3 (w/ 2 bytes header).
*/
if (parsed != 3) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
buf += parsed;
remain -= parsed;
}
if (remain) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
ret = 0;
out:
return ret;
}
static const u8 _id_kp_anyEKU[] = { 0x06, 0x08, 0x2b, 0x06,
0x01, 0x05, 0x05, 0x07,
0x03, 0x00 };
static const u8 _id_kp_serverAuth[] = { 0x06, 0x08, 0x2b, 0x06,
0x01, 0x05, 0x05, 0x07,
0x03, 0x01 };
static const u8 _id_kp_clientAuth[] = { 0x06, 0x08, 0x2b, 0x06,
0x01, 0x05, 0x05, 0x07,
0x03, 0x02 };
static const u8 _id_kp_codeSigning[] = { 0x06, 0x08, 0x2b, 0x06,
0x01, 0x05, 0x05, 0x07,
0x03, 0x03 };
static const u8 _id_kp_emailProt[] = { 0x06, 0x08, 0x2b, 0x06,
0x01, 0x05, 0x05, 0x07,
0x03, 0x04 };
static const u8 _id_kp_timeStamping[] = { 0x06, 0x08, 0x2b, 0x06,
0x01, 0x05, 0x05, 0x07,
0x03, 0x08 };
static const u8 _id_kp_OCSPSigning[] = { 0x06, 0x08, 0x2b, 0x06,
0x01, 0x05, 0x05, 0x07,
0x03, 0x09 };
typedef struct {
const u8 *oid;
u8 oid_len;
} _kp_oid;
static const _kp_oid known_kp_oids[] = {
{ .oid = _id_kp_anyEKU,
.oid_len = sizeof(_id_kp_anyEKU),
},
{ .oid = _id_kp_serverAuth,
.oid_len = sizeof(_id_kp_serverAuth),
},
{ .oid = _id_kp_clientAuth,
.oid_len = sizeof(_id_kp_clientAuth),
},
{ .oid = _id_kp_codeSigning,
.oid_len = sizeof(_id_kp_codeSigning),
},
{ .oid = _id_kp_emailProt,
.oid_len = sizeof(_id_kp_emailProt),
},
{ .oid = _id_kp_timeStamping,
.oid_len = sizeof(_id_kp_timeStamping),
},
{ .oid = _id_kp_OCSPSigning,
.oid_len = sizeof(_id_kp_OCSPSigning),
},
};
#define NUM_KNOWN_KP_OIDS (sizeof(known_kp_oids) / sizeof(known_kp_oids[0]))
/*@
@ requires len >= 0;
@ requires ((len > 0) && (buf != NULL)) ==> \valid_read(buf + (0 .. (len - 1)));
@ ensures (\result != NULL) ==> \exists integer i ; 0 <= i < NUM_KNOWN_KP_OIDS && \result == &known_kp_oids[i];
@ ensures (len == 0) ==> \result == NULL;
@ ensures (buf == NULL) ==> \result == NULL;
@ assigns \nothing;
@*/
static const _kp_oid * find_kp_by_oid(const u8 *buf, u16 len)
{
const _kp_oid *found = NULL;
const _kp_oid *cur = NULL;
u8 k;
if ((buf == NULL) || (len == 0)) {
goto out;
}
/*@
@ loop invariant 0 <= k <= NUM_KNOWN_KP_OIDS;
@ loop invariant found == NULL;
@ loop assigns cur, found, k;
@ loop variant (NUM_KNOWN_KP_OIDS - k);
@*/
for (k = 0; k < NUM_KNOWN_KP_OIDS; k++) {
int ret;
cur = &known_kp_oids[k];
/*@ assert cur == &known_kp_oids[k];*/
if (cur->oid_len != len) {
continue;
}
/*@ assert \valid_read(buf + (0 .. (len - 1))); @*/
ret = !bufs_differ(cur->oid, buf, cur->oid_len);
if (ret) {
found = cur;
break;
}
}
out:
return found;
}
/*
* 4.2.1.12. Extended Key Usage
*
* id-ce-extKeyUsage OBJECT IDENTIFIER ::= { id-ce 37 }
*
* ExtKeyUsageSyntax ::= SEQUENCE SIZE (1..MAX) OF KeyPurposeId
*
* KeyPurposeId ::= OBJECT IDENTIFIER
*
*/
/*@
@ requires len >= 0;
@ requires ((len > 0) && (buf != \null)) ==> \valid_read(buf + (0 .. (len - 1)));
@ requires \valid(ctx);
@ requires \separated(ctx, buf+(..));
@ ensures \result <= 0;
@ ensures (len == 0) ==> \result < 0;
@ ensures (buf == \null) ==> \result < 0;
@ assigns \nothing;
@*/
static int parse_ext_EKU(const u8 *buf, u16 len, int critical,
cert_parsing_ctx ATTRIBUTE_UNUSED *ctx)
{
u16 remain = 0, data_len = 0, hdr_len = 0, oid_len = 0;
const _kp_oid *kp = NULL;
int ret;
if ((buf == NULL) || (len == 0)) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
ret = parse_id_len(buf, len, CLASS_UNIVERSAL, ASN1_TYPE_SEQUENCE,
&hdr_len, &data_len);
if (ret || (data_len == 0)) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
buf += hdr_len;
remain = data_len;
if (len != (hdr_len + data_len)) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/* Let's now check each individual KeyPurposeId in the sequence */
/*@
@ loop assigns ret, oid_len, kp, buf, remain;
@ loop invariant \valid_read(buf + (0 .. (remain - 1)));
@ loop variant remain;
@ */
while (remain) {
ret = parse_OID(buf, remain, &oid_len);
if (ret) {
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
kp = find_kp_by_oid(buf, oid_len);
if (kp == NULL) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/*
* RFC5280 sect 4.2.1.12 contains "Conforming CAs SHOULD NOT
* mark this extension as critical if the anyExtendedKeyUsage
* KeyPurposeId is present." We enforce this expected behavior."
*/
if ((kp->oid == _id_kp_anyEKU) && critical) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
buf += oid_len;
remain -= oid_len;
}
ret = 0;
out:
return ret;
}
/*
* ReasonFlags ::= BIT STRING {
* unused (0),
* keyCompromise (1),
* cACompromise (2),
* affiliationChanged (3),
* superseded (4),
* cessationOfOperation (5),
* certificateHold (6),
* privilegeWithdrawn (7),
* aACompromise (8) }
*
*/
/*@
@ requires len >= 0;
@ requires ((len > 0) && (buf != \null)) ==> \valid_read(buf + (0 .. (len - 1)));
@ requires \valid(eaten);
@ requires \separated(eaten, buf+(..));
@ ensures \result <= 0;
@ ensures (\result == 0) ==> (*eaten <= len);
@ ensures (len == 0) ==> \result < 0;
@ ensures (buf == \null) ==> \result < 0;
@ assigns *eaten;
@*/
static int parse_crldp_reasons(const u8 *buf, u16 len, u16 *eaten)
{
u16 val, hdr_len = 0, data_len = 0;
int ret;
if ((buf == NULL) || (len == 0)) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
ret = parse_id_len(buf, len, CLASS_CONTEXT_SPECIFIC, 1,
&hdr_len, &data_len);
if (ret) {
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
buf += hdr_len;
len -= hdr_len;
ret = parse_nine_bit_named_bit_list(buf, data_len, &val);
if (ret) {
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
*eaten = hdr_len + data_len;
ret = 0;
out:
return ret;
}
/*
* DistributionPoint ::= SEQUENCE {
* distributionPoint [0] DistributionPointName OPTIONAL,
* reasons [1] ReasonFlags OPTIONAL,
* cRLIssuer [2] GeneralNames OPTIONAL }
*
* DistributionPointName ::= CHOICE {
* fullName [0] GeneralNames,
* nameRelativeToCRLIssuer [1] RelativeDistinguishedName }
*
* ReasonFlags ::= BIT STRING {
* unused (0),
* keyCompromise (1),
* cACompromise (2),
* affiliationChanged (3),
* superseded (4),
* cessationOfOperation (5),
* certificateHold (6),
* privilegeWithdrawn (7),
* aACompromise (8) }
*/
/*@
@ requires len >= 0;
@ requires ((len > 0) && (buf != \null)) ==> \valid_read(buf + (0 .. (len - 1)));
@ requires \valid(eaten);
@ requires \valid(ctx);
@ requires \separated(eaten, ctx, buf+(..));
@ ensures \result <= 0;
@ ensures (\result == 0) ==> (0 < *eaten <= len);
@ ensures (len == 0) ==> \result < 0;
@ ensures (buf == \null) ==> \result < 0;
@ assigns *eaten, *ctx;
@*/
static int parse_DistributionPoint(const u8 *buf, u16 len, u16 *eaten,
cert_parsing_ctx *ctx)
{
u16 hdr_len = 0, data_len = 0, remain = 0, total_len = 0;
int dp_or_issuer_present = 0;
u16 parsed = 0;
int ret, has_all_reasons = 0;
if ((buf == NULL) || (len == 0)) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/* DistributionPoint is a sequence */
ret = parse_id_len(buf, len,
CLASS_UNIVERSAL, ASN1_TYPE_SEQUENCE,
&hdr_len, &data_len);
if (ret) {
ret = -__LINE__;
goto out;
}
total_len = hdr_len + data_len;
/*@ assert total_len > 0; */
remain = data_len;
buf += hdr_len;
/*
* Check if we have a (optional) distributionPoint field
* (of type DistributionPointName)
*/
ret = parse_id_len(buf, remain, CLASS_CONTEXT_SPECIFIC, 0,
&hdr_len, &data_len);
if (!ret) {
u16 dpn_remain = 0, dpn_eaten = 0;
u8 dpn_type;
buf += hdr_len;
remain -= hdr_len;
dpn_remain = data_len;
if (data_len == 0) {
ret = -__LINE__;
goto out;
}
dpn_type = buf[0];
/*
* distributionPoint field of type DistributionPointName
* can be either a fullName or a nameRelativeToCRLIssuer.
*/
switch (dpn_type) {
case 0xa0: /* fullName (i.e. a GeneralNames) */
ret = parse_GeneralNames(buf, dpn_remain,
CLASS_CONTEXT_SPECIFIC, 0,
&dpn_eaten);
if (ret) {
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
dpn_remain -= dpn_eaten;
buf += dpn_eaten;
break;
case 0xa1: /* nameRelativeToCRLIssuer (RDN) */
/*
* This form of distributionPoint is never used
* in practice in real X.509 certs, so not
* supported here. Note that RFC5280 has the
* following: "Conforming CAs SHOULD NOT use
* nameRelativeToCRLIssuer to specify distribution
* point names."
*/
ret = -__LINE__;
goto out;
break;
default:
ret = -__LINE__;
goto out;
break;
}
if (dpn_remain) {
ret = -__LINE__;
goto out;
}
/* Record the fact we found a DP */
dp_or_issuer_present |= 1;
remain -= data_len;
}
/* Check if we have a (optional) ReasonFlags */
ret = parse_id_len(buf, remain, CLASS_CONTEXT_SPECIFIC, 1,
&hdr_len, &data_len);
if (!ret) {
ret = parse_crldp_reasons(buf, remain, &parsed);
if (ret) {
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
buf += parsed;
remain -= parsed;
} else {
/*
* RFC 5280 has "If the DistributionPoint omits the reasons
* field, the CRL MUST include revocation information for all
* reasons", i.e. no reasonFlags means all reasons.
*/
has_all_reasons = 1;
}
/* Check if we have a (optional) cRLIssuer (GeneralNames) */
ret = parse_GeneralNames(buf, remain, CLASS_CONTEXT_SPECIFIC, 2,
&parsed);
if (!ret) {
/* Record the fact we found a cRLIssuer */
dp_or_issuer_present |= 1;
buf += parsed;
remain -= parsed;
}
if (remain) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/*
* RFC580 has (about DP and cRLIssuer): "While each of these fields is
* optional, a DistributionPoint MUST NOT consist of only the reasons
* field; either distributionPoint or cRLIssuer MUST be present."
*/
if (!dp_or_issuer_present) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
*eaten = total_len;
ctx->one_crldp_has_all_reasons |= has_all_reasons;
/*@ assert *eaten > 0; */
ret = 0;
out:
return ret;
}
/*
* 4.2.1.13. CRL Distribution Points
* 4.2.1.15. Freshet CRL (a.k.a Delta CRL Distribution Point)
*
* CRLDistributionPoints ::= SEQUENCE SIZE (1..MAX) OF DistributionPoint
*
* Note that the Freshest CRL extension uses the exact same syntax and
* convention as CRLDP extension. The only minor difference is that section
* 4.2.1.13 has that "The extension SHOULD be non-critical" and section
* 4.2.1.15 has that "The extension MUST be marked as non-critical by
* conforming CAs". We handle that by requiring that both extensions
* be marked as non-critical.
*/
/*@
@ requires len >= 0;
@ requires ((len > 0) && (buf != \null)) ==> \valid_read(buf + (0 .. (len - 1)));
@ requires \valid(ctx);
@ requires \separated(ctx, buf+(..));
@ ensures \result <= 0;
@ ensures (len == 0) ==> \result < 0;
@ ensures (buf == \null) ==> \result < 0;
@ assigns *ctx;
@*/
static int parse_ext_CRLDP(const u8 *buf, u16 len, int critical,
cert_parsing_ctx *ctx)
{
u16 hdr_len = 0, data_len = 0, remain;
int ret;
if ((buf == NULL) || (len == 0)) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/* See comment above */
if (critical) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/* Check we are dealing with a valid sequence */
ret = parse_id_len(buf, len,
CLASS_UNIVERSAL, ASN1_TYPE_SEQUENCE,
&hdr_len, &data_len);
if (ret) {
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
buf += hdr_len;
remain = data_len;
if (len != (hdr_len + data_len)) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
ctx->has_crldp = 1;
ctx->one_crldp_has_all_reasons = 0;
/* Iterate on DistributionPoint */
/*@
@ loop assigns ret, buf, remain, *ctx;
@ loop invariant \valid_read(buf + (0 .. (remain - 1)));
@ loop variant remain;
@ */
while (remain) {
u16 eaten = 0;
ret = parse_DistributionPoint(buf, remain, &eaten, ctx);
if (ret) {
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
remain -= eaten;
buf += eaten;
}
ret = 0;
out:
return ret;
}
/*
* 4.2.1.14. Inhibit anyPolicy
*
* InhibitAnyPolicy ::= SkipCerts
*
* SkipCerts ::= INTEGER (0..MAX)
*/
/*@
@ requires len >= 0;
@ requires ((len > 0) && (buf != \null)) ==> \valid_read(buf + (0 .. (len - 1)));
@ requires \valid(ctx);
@ requires \separated(ctx, buf+(..));
@ ensures \result <= 0;
@ ensures (len == 0) ==> \result < 0;
@ ensures (buf == \null) ==> \result < 0;
@ assigns \nothing;
@*/
#define MAX_INHIBITANYPOLICY 64
static int parse_ext_inhibitAnyPolicy(const u8 *buf, u16 len, int critical,
cert_parsing_ctx ATTRIBUTE_UNUSED *ctx)
{
u16 eaten = 0;
int ret;
if ((buf == NULL) || (len == 0)) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/*
* 4.2.1.14 of RFC5280 has "Conforming CAs MUST mark this
* extension as critical".
*/
if (!critical) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
ret = parse_integer(buf, len, CLASS_UNIVERSAL, ASN1_TYPE_INTEGER,
&eaten);
if (ret) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/*
* We limit SkipCerts values to integers between 0 and
* MAX_INHIBITANYPOLICY. This implies an encoding on 3 bytes.
*/
if (eaten != 3) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
if ((buf[2] & 0x80) || (buf[2] > MAX_INHIBITANYPOLICY)) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
if (eaten != len) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
ret = 0;
out:
return ret;
}
/* The OID we will support in final implementation */
static const u8 _ext_oid_AIA[] = { 0x06, 0x08, 0x2b, 0x06, 0x01,
0x05, 0x05, 0x07, 0x01, 0x01 };
static const u8 _ext_oid_subjectDirAttr[] = { 0x06, 0x03, 0x55, 0x1d, 0x09 };
static const u8 _ext_oid_SKI[] = { 0x06, 0x03, 0x55, 0x1d, 0x0e };
static const u8 _ext_oid_keyUsage[] = { 0x06, 0x03, 0x55, 0x1d, 0x0f };
static const u8 _ext_oid_SAN[] = { 0x06, 0x03, 0x55, 0x1d, 0x11 };
static const u8 _ext_oid_IAN[] = { 0x06, 0x03, 0x55, 0x1d, 0x12 };
static const u8 _ext_oid_basicConstraints[] = { 0x06, 0x03, 0x55, 0x1d, 0x13 };
static const u8 _ext_oid_nameConstraints[] = { 0x06, 0x03, 0x55, 0x1d, 0x1e };
static const u8 _ext_oid_CRLDP[] = { 0x06, 0x03, 0x55, 0x1d, 0x1f };
static const u8 _ext_oid_certPolicies[] = { 0x06, 0x03, 0x55, 0x1d, 0x20 };
static const u8 _ext_oid_policyMapping[] = { 0x06, 0x03, 0x55, 0x1d, 0x21 };
static const u8 _ext_oid_AKI[] = { 0x06, 0x03, 0x55, 0x1d, 0x23 };
static const u8 _ext_oid_policyConstraints[] = { 0x06, 0x03, 0x55, 0x1d, 0x24 };
static const u8 _ext_oid_EKU[] = { 0x06, 0x03, 0x55, 0x1d, 0x25 };
static const u8 _ext_oid_FreshestCRL[] = { 0x06, 0x03, 0x55, 0x1d, 0x2e };
static const u8 _ext_oid_inhibitAnyPolicy[] = { 0x06, 0x03, 0x55, 0x1d, 0x36 };
#ifdef TEMPORARY_BAD_EXT_OIDS
/*@
@ requires len >= 0;
@ requires ((len > 0) && (buf != \null)) ==> \valid_read(buf + (0 .. (len - 1)));
@ requires \valid(ctx);
@ requires \separated(ctx, buf+(..));
@ ensures \result <= 0;
@ assigns \nothing;
@*/
static int parse_ext_bad_oid(const u8 *buf, u16 len, int ATTRIBUTE_UNUSED critical,
cert_parsing_ctx ATTRIBUTE_UNUSED *ctx)
{
int ret;
if ((buf == NULL) || (len == 0)) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
ret = 0;
out:
return ret;
}
/* The OID we temporarily support in order to improve code coverage */
static const u8 _ext_oid_bad_ct1[] = { 0x06, 0x08, 0x2b, 0x06,
0x01, 0x05, 0x05, 0x07,
0x01, 0x01 };
static const u8 _ext_oid_bad_ct_poison[] = { 0x06, 0x0a, 0x2b, 0x06,
0x01, 0x04, 0x01, 0xd6,
0x79, 0x02, 0x04, 0x03 };
static const u8 _ext_oid_bad_ct_enabled[] = { 0x06, 0x0a, 0x2b, 0x06,
0x01, 0x04, 0x01, 0xd6,
0x79, 0x02, 0x04, 0x02 };
static const u8 _ext_oid_bad_ns_cert_type[] = { 0x06, 0x09, 0x60, 0x86,
0x48, 0x01, 0x86, 0xf8,
0x42, 0x01, 0x01 };
static const u8 _ext_oid_bad_szOID_ENROLL[] = { 0x06, 0x09, 0x2b, 0x06,
0x01, 0x04, 0x01, 0x82,
0x37, 0x14, 0x02 };
static const u8 _ext_oid_bad_smime_cap[] = { 0x06, 0x09, 0x2a, 0x86,
0x48, 0x86, 0xf7, 0x0d,
0x01, 0x09, 0x0f };
static const u8 _ext_oid_bad_ns_comment[] = { 0x06, 0x09, 0x60, 0x86,
0x48, 0x01, 0x86, 0xf8,
0x42, 0x01, 0x0d };
static const u8 _ext_oid_bad_deprecated_AKI[] = { 0x06, 0x03, 0x55, 0x1d,
0x01 };
static const u8 _ext_oid_bad_szOID_CERT_TEMPLATE[] = { 0x06, 0x09, 0x2b, 0x06,
0x01, 0x04, 0x01, 0x82,
0x37, 0x15, 0x07 };
static const u8 _ext_oid_bad_pkixFixes[] = { 0x06, 0x0a, 0x2b, 0x06,
0x01, 0x04, 0x01, 0x97,
0x55, 0x03, 0x01, 0x05 };
static const u8 _ext_oid_bad_ns_ca_policy_url[] = { 0x06, 0x09, 0x60, 0x86,
0x48, 0x01, 0x86, 0xf8,
0x42, 0x01, 0x08 };
static const u8 _ext_oid_bad_szOID_CERTSRV_CA_VERS[] = { 0x06, 0x09, 0x2b, 0x06,
0x01, 0x04, 0x01, 0x82,
0x37, 0x15, 0x01 };
static const u8 _ext_oid_bad_szOID_APP_CERT_POL[] = { 0x06, 0x03, 0x55, 0x1d,
0x10 };
#endif
/*
* Some OIDs we do not support yet (not meaning we will implement them):
*
* 6063 06092b060104018237150a
* 4424 06096086480186f842010c
* 1503 0603551d2e
* 1048 06032b654d
* 954 06082b06010505070103
* 905 06092a864886f67d074100
* 552 06092b0601050507300105
* 521 06092b0601040182371502
* 261 060a2b06010401823702011b
* 261 06096086480186f8420103
* 261 06082b0601050507010b
* 241 06096086480186f8420104
* 184 0603551d04
* 179 060a2b060104019a49080101
* 158 06096086480186f8420102
* 88 06072a28000a010101
* 81 06082b06010505070118
* 69 0603551d0a
* 64 06072a28000a010102
* 48 060a2b0601040182370a0b0b
* 48 06082b0601050507010c
* 30 06056038010801
* 25 060a6086480186fd69010102
* 18 06082b06010401bb6201
* 16 0603551d63
* 15 060b6086480186f83701090401
* 15 060b60857405040201020d0202
* 15 06096086480186fa6b1e01
* 14 060a6086480186f845011003
* 14 06092b060104018b770a01
* 8 06086085540102020401
* 7 06072b060104a16421
* 6 060b2a864886f76364061b0b02
* 6 060b2a864886f76364061b0402
* 6 06062a8570220201
* 5 060a2b06010401823702010a
* 5 060a2a864886f76364061b02
* 5 06092b0601040182371516
* 5 0603551d07
* 4 060b2a864886f76364061b0802
* 4 06092a864886f70d010901
* 4 0605551d876701
* 4 06032a0304
* 3 060b2b0601040181ed40010601
* 3 060b2a864886f76364061b0602
* 3 060a2b06010401818f1c1301
* 3 060a2a864886f72f01010902
* 3 0609551d0f0186f842010d
* 3 06086086480186f84201
* 3 06082b06010387670101
* 2 060a6086480186f845010609
* 2 060a2b06010401bf6d020306
* 2 060a2b0601040181b8480403
* 2 060a2a864886f7636406020c
* 2 060a2a864886f76364060203
* 2 060a2a864886f76364060201
* 2 060a2a864886f72f01010901
* 2 06092b06010401c06d0305
* 2 06072a280024040103
* 2 0604672a0700
* 2 0603551d40
* 2 0603550403
* 1 060b2b0601040181981c020306
* 1 060b2b06010401819248030101
* 1 060b2a864886f76364061b1102
* 1 060b2a864886f76364061b0f02
* 1 060b2a864886f76364061b0702
* 1 060b2a864886f76364061b0302
* 1 060a6086480186fd69010105
* 1 060a6086480186f845011004
* 1 060a2b06010401f7340a0201
* 1 060a2b0601040182370d0203
* 1 060a2b0601040181f4076402
* 1 060a2b0601040181f4076401
* 1 060a2a864886f76364061b10
* 1 060a2a864886f76364061b09
* 1 060a2a864886f76364060210
* 1 060a2a864886f7636406020b
* 1 060a2a864886f76364060209
* 1 060a2a864886f76364060206
* 1 060a2a864886f76364060109
* 1 06096086480186f843050b
* 1 06092b0601040181b84805
* 1 06092a864886f763640616
* 1 06092a24a390951701ce19
* 1 06082a817a0147010205
* 1 06072a280024040100
* 1 0606550101010101
* 1 0605551d876702
* 1 06052b0601037b
* 1 0603551d19
* 1 0603551d03
* 1 06032a2137
*/
typedef struct {
const u8 *oid;
u8 oid_len;
int (*parse_ext_params)(const u8 *buf, u16 len, int critical,
cert_parsing_ctx *ctx);
} _ext_oid;
static const _ext_oid known_ext_oids[] = {
{ .oid = _ext_oid_AIA,
.oid_len = sizeof(_ext_oid_AIA),
.parse_ext_params = parse_ext_AIA,
},
{ .oid = _ext_oid_AKI,
.oid_len = sizeof(_ext_oid_AKI),
.parse_ext_params = parse_ext_AKI,
},
{ .oid = _ext_oid_SKI,
.oid_len = sizeof(_ext_oid_SKI),
.parse_ext_params = parse_ext_SKI,
},
{ .oid = _ext_oid_keyUsage,
.oid_len = sizeof(_ext_oid_keyUsage),
.parse_ext_params = parse_ext_keyUsage,
},
{ .oid = _ext_oid_certPolicies,
.oid_len = sizeof(_ext_oid_certPolicies),
.parse_ext_params = parse_ext_certPolicies,
},
{ .oid = _ext_oid_policyMapping,
.oid_len = sizeof(_ext_oid_policyMapping),
.parse_ext_params = parse_ext_policyMapping,
},
{ .oid = _ext_oid_SAN,
.oid_len = sizeof(_ext_oid_SAN),
.parse_ext_params = parse_ext_SAN,
},
{ .oid = _ext_oid_IAN,
.oid_len = sizeof(_ext_oid_IAN),
.parse_ext_params = parse_ext_IAN,
},
{ .oid = _ext_oid_subjectDirAttr,
.oid_len = sizeof(_ext_oid_subjectDirAttr),
.parse_ext_params = parse_ext_subjectDirAttr,
},
{ .oid = _ext_oid_basicConstraints,
.oid_len = sizeof(_ext_oid_basicConstraints),
.parse_ext_params = parse_ext_basicConstraints,
},
{ .oid = _ext_oid_nameConstraints,
.oid_len = sizeof(_ext_oid_nameConstraints),
.parse_ext_params = parse_ext_nameConstraints,
},
{ .oid = _ext_oid_policyConstraints,
.oid_len = sizeof(_ext_oid_policyConstraints),
.parse_ext_params = parse_ext_policyConstraints,
},
{ .oid = _ext_oid_EKU,
.oid_len = sizeof(_ext_oid_EKU),
.parse_ext_params = parse_ext_EKU,
},
{ .oid = _ext_oid_CRLDP,
.oid_len = sizeof(_ext_oid_CRLDP),
.parse_ext_params = parse_ext_CRLDP,
},
{ .oid = _ext_oid_inhibitAnyPolicy,
.oid_len = sizeof(_ext_oid_inhibitAnyPolicy),
.parse_ext_params = parse_ext_inhibitAnyPolicy,
},
{ .oid = _ext_oid_FreshestCRL,
.oid_len = sizeof(_ext_oid_FreshestCRL),
.parse_ext_params = parse_ext_CRLDP,
},
#ifdef TEMPORARY_BAD_EXT_OIDS
{ .oid = _ext_oid_bad_ct1,
.oid_len = sizeof(_ext_oid_bad_ct1),
.parse_ext_params = parse_ext_bad_oid,
},
{ .oid = _ext_oid_bad_ct_poison,
.oid_len = sizeof(_ext_oid_bad_ct_poison),
.parse_ext_params = parse_ext_bad_oid,
},
{ .oid = _ext_oid_bad_ct_enabled,
.oid_len = sizeof(_ext_oid_bad_ct_enabled),
.parse_ext_params = parse_ext_bad_oid,
},
{ .oid = _ext_oid_bad_ns_cert_type,
.oid_len = sizeof(_ext_oid_bad_ns_cert_type),
.parse_ext_params = parse_ext_bad_oid,
},
{ .oid = _ext_oid_bad_szOID_ENROLL,
.oid_len = sizeof(_ext_oid_bad_szOID_ENROLL),
.parse_ext_params = parse_ext_bad_oid,
},
{ .oid = _ext_oid_bad_smime_cap,
.oid_len = sizeof(_ext_oid_bad_smime_cap),
.parse_ext_params = parse_ext_bad_oid,
},
{ .oid = _ext_oid_bad_ns_comment,
.oid_len = sizeof(_ext_oid_bad_ns_comment),
.parse_ext_params = parse_ext_bad_oid,
},
{ .oid = _ext_oid_bad_deprecated_AKI,
.oid_len = sizeof(_ext_oid_bad_deprecated_AKI),
.parse_ext_params = parse_ext_bad_oid,
},
{ .oid = _ext_oid_bad_szOID_CERT_TEMPLATE,
.oid_len = sizeof(_ext_oid_bad_szOID_CERT_TEMPLATE),
.parse_ext_params = parse_ext_bad_oid,
},
{ .oid = _ext_oid_bad_pkixFixes,
.oid_len = sizeof(_ext_oid_bad_pkixFixes),
.parse_ext_params = parse_ext_bad_oid,
},
{ .oid = _ext_oid_bad_ns_ca_policy_url,
.oid_len = sizeof(_ext_oid_bad_ns_ca_policy_url),
.parse_ext_params = parse_ext_bad_oid,
},
{ .oid = _ext_oid_bad_szOID_CERTSRV_CA_VERS,
.oid_len = sizeof(_ext_oid_bad_szOID_CERTSRV_CA_VERS),
.parse_ext_params = parse_ext_bad_oid,
},
{ .oid = _ext_oid_bad_szOID_APP_CERT_POL,
.oid_len = sizeof(_ext_oid_bad_szOID_APP_CERT_POL),
.parse_ext_params = parse_ext_bad_oid,
},
#endif
};
#define NUM_KNOWN_EXT_OIDS (sizeof(known_ext_oids) / sizeof(known_ext_oids[0]))
/*
* We limit the amount of extensions we accept per certificate. This can be
* done because each kind of extension is allowed to appear only once in a
* given certificate. Note that it is logical to allow
*/
#define MAX_EXT_NUM_PER_CERT NUM_KNOWN_EXT_OIDS
/*@
@ requires len >= 0;
@ requires ((len > 0) && (buf != NULL)) ==> \valid_read(buf + (0 .. (len - 1)));
@ ensures (\result != NULL) ==> \exists integer i ; 0 <= i < NUM_KNOWN_EXT_OIDS && \result == &known_ext_oids[i];
@ ensures (len == 0) ==> \result == NULL;
@ ensures (buf == NULL) ==> \result == NULL;
@ assigns \nothing;
@*/
static _ext_oid const * find_ext_by_oid(const u8 *buf, u16 len)
{
const _ext_oid *found = NULL;
const _ext_oid *cur = NULL;
u8 k;
if ((buf == NULL) || (len == 0)) {
goto out;
}
/*@
@ loop invariant 0 <= k <= NUM_KNOWN_EXT_OIDS;
@ loop invariant found == NULL;
@ loop assigns cur, found, k;
@ loop variant (NUM_KNOWN_EXT_OIDS - k);
@*/
for (k = 0; k < NUM_KNOWN_EXT_OIDS; k++) {
int ret;
cur = &known_ext_oids[k];
/*@ assert cur == &known_ext_oids[k];*/
if (cur->oid_len != len) {
continue;
}
/*@ assert \valid_read(buf + (0 .. (len - 1))); @*/
ret = !bufs_differ(cur->oid, buf, cur->oid_len);
if (ret) {
found = cur;
break;
}
}
out:
return found;
}
/*@
@ requires ext != \null;
@ requires \valid(parsed_oid_list + (0 .. (MAX_EXT_NUM_PER_CERT - 1)));
@ requires \initialized(parsed_oid_list + (0 .. (MAX_EXT_NUM_PER_CERT - 1)));
@ ensures \result <= 0;
@ assigns parsed_oid_list[0 .. (MAX_EXT_NUM_PER_CERT - 1)];
@*/
static int check_record_ext_unknown(const _ext_oid *ext,
const _ext_oid **parsed_oid_list)
{
u16 pos = 0;
int ret;
/*@
@ loop invariant pos <= MAX_EXT_NUM_PER_CERT;
@ loop assigns ret, pos, parsed_oid_list[0 .. (MAX_EXT_NUM_PER_CERT - 1)];
@ loop variant MAX_EXT_NUM_PER_CERT - pos;
@*/
while (pos < MAX_EXT_NUM_PER_CERT) {
/*
* Check if we are at the end of already seen extensions. In
* that case, record the extension as a new one.
*/
if (parsed_oid_list[pos] == NULL) {
parsed_oid_list[pos] = ext;
break;
}
if (ext == parsed_oid_list[pos]) {
ret = -__LINE__;
goto out;
}
pos += 1;
}
/*
* If we went to the end of our array, this means there are too many
* extensions in the certificate.
*/
if (pos >= MAX_EXT_NUM_PER_CERT) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
ret = 0;
out:
return ret;
}
/*
* Parse one extension.
*
* Extension ::= SEQUENCE {
* extnID OBJECT IDENTIFIER,
* critical BOOLEAN DEFAULT FALSE,
* extnValue OCTET STRING
* -- contains the DER encoding of an ASN.1 value
* -- corresponding to the extension type identified
* -- by extnID
* }
*/
/*@
@ requires len >= 0;
@ requires ((len > 0) && (buf != \null)) ==> \valid_read(buf + (0 .. (len - 1)));
@ requires \valid(eaten);
@ requires \valid(ctx);
@ requires \valid(parsed_oid_list);
@ requires \initialized(parsed_oid_list + (0 .. (MAX_EXT_NUM_PER_CERT - 1)));
@ ensures \result <= 0;
@ ensures (\result == 0) ==> (1 <= *eaten <= len);
@ ensures (len == 0) ==> \result < 0;
@ ensures (buf == \null) ==> \result < 0;
@ assigns parsed_oid_list[0 .. (MAX_EXT_NUM_PER_CERT - 1)], *eaten, *ctx;
@*/
static int parse_x509_Extension(const u8 *buf, u16 len,
const _ext_oid **parsed_oid_list,
u16 *eaten, cert_parsing_ctx *ctx)
{
u16 data_len = 0, hdr_len = 0, remain = 0;
u16 ext_hdr_len = 0, ext_data_len = 0, oid_len = 0;
u16 saved_ext_len = 0, parsed = 0;
const _ext_oid *ext = NULL;
int critical = 0;
int ret;
/*@ assert \initialized(parsed_oid_list + (0 .. (MAX_EXT_NUM_PER_CERT - 1))); */
remain = len;
/* Check we are dealing with a valid sequence */
ret = parse_id_len(buf, remain,
CLASS_UNIVERSAL, ASN1_TYPE_SEQUENCE,
&ext_hdr_len, &ext_data_len);
if (ret) {
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
buf += ext_hdr_len;
remain -= ext_hdr_len;
saved_ext_len = ext_hdr_len + ext_data_len;
/*@ assert \initialized(parsed_oid_list + (0 .. (MAX_EXT_NUM_PER_CERT - 1))); */
/*
* Let's parse the OID and then check if we have
* an associated handler for that extension.
*/
ret = parse_OID(buf, ext_data_len, &oid_len);
if (ret) {
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/*@ assert \initialized(parsed_oid_list + (0 .. (MAX_EXT_NUM_PER_CERT - 1))); */
ext = find_ext_by_oid(buf, oid_len);
if (ext == NULL) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/*@ assert \initialized(parsed_oid_list + (0 .. (MAX_EXT_NUM_PER_CERT - 1))); */
/*
* Now that we know the OID is one we support, we verify
* this is the first time we handle an instance of this
* type. Having multiple instances of a given extension
* in a certificate is forbidden by both section 4.2 of
* RFC5280 and section 8 of X.509, w/ respectively
*
* - "A certificate MUST NOT include more than one
* instance of a particular extension."
* - "For all certificate extensions, CRL extensions,
* and CRL entry extensions defined in this Directory
* Specification, there shall be no more than one
* instance of each extension type in any certificate,
* CRL, or CRL entry, respectively."
*
* This is done by recording for each extension we
* processed the pointer to its vtable and compare
* it with current one.
*/
ret = check_record_ext_unknown(ext, parsed_oid_list);
if (ret) {
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
buf += oid_len;
ext_data_len -= oid_len;
/*
* Now that we got the OID, let's check critical
* field value if present. It's a boolean
* defaulting to FALSE (in which case, it is absent).
* We could parse it as an integer but that
* would be a lot of work for three simple bytes.
*/
ret = parse_boolean(buf, ext_data_len, &parsed);
if (!ret) {
/*
* We now know it's a valid BOOLEAN, *but* in our
* case (DER), the DEFAULT FALSE means we cannot
* accept an encoded value of FALSE. Note that we
* sanity check the value we expect for the length
*/
if ((parsed != 3) || (buf[2] == 0x00)) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/*
* We now know the BOOLEAN is present and has
* a value of TRUE. Record that.
*/
critical = 1;
buf += parsed;
ext_data_len -= parsed;
}
/*
* We should now be in front of the octet string
* containing the extnValue.
*/
ret = parse_id_len(buf, ext_data_len,
CLASS_UNIVERSAL, ASN1_TYPE_OCTET_STRING,
&hdr_len, &data_len);
if (ret) {
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
buf += hdr_len;
ext_data_len -= hdr_len;
/* Check nothing remains behind the extnValue */
if (data_len != ext_data_len) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/* Parse the parameters for that extension */
/*@ calls parse_ext_AIA, parse_ext_AKI, parse_ext_SKI, parse_ext_keyUsage, parse_ext_certPolicies, parse_ext_policyMapping, parse_ext_SAN, parse_ext_IAN, parse_ext_subjectDirAttr, parse_ext_basicConstraints, parse_ext_nameConstraints, parse_ext_policyConstraints, parse_ext_EKU, parse_ext_CRLDP, parse_ext_inhibitAnyPolicy, parse_ext_bad_oid ; @*/
ret = ext->parse_ext_params(buf, ext_data_len, critical, ctx);
if (ret) {
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
*eaten = saved_ext_len;
ret = 0;
out:
return ret;
}
/*
* Parse X.509 extensions.
*
* TBSCertificate ::= SEQUENCE {
*
* ...
*
* extensions [3] EXPLICIT Extensions OPTIONAL
* }
*
* Extensions ::= SEQUENCE SIZE (1..MAX) OF Extension
*
*
*/
/*@
@ requires len >= 0;
@ requires ((len > 0) && (buf != \null)) ==> \valid_read(buf + (0 .. (len - 1)));
@ requires \valid(eaten);
@ requires \valid(ctx);
@ requires \separated(eaten, ctx, buf+(..));
@ ensures \result <= 0;
@ ensures (\result == 0) ==> (1 <= *eaten <= len);
@ ensures (len == 0) ==> \result < 0;
@ ensures (buf == \null) ==> \result < 0;
@ assigns *eaten, *ctx;
@*/
static int parse_x509_Extensions(const u8 *buf, u16 len, u16 *eaten,
cert_parsing_ctx *ctx)
{
u16 data_len = 0, hdr_len = 0, remain = 0;
u16 saved_len = 0;
const _ext_oid *parsed_oid_list[MAX_EXT_NUM_PER_CERT];
int ret;
u16 i;
if ((buf == NULL) || (len == 0)) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/*
* Extensions in X.509 v3 certificates is an EXPLICITLY tagged
* sequence.
*/
ret = parse_explicit_id_len(buf, len, 3,
CLASS_UNIVERSAL, ASN1_TYPE_SEQUENCE,
&hdr_len, &data_len);
if (ret) {
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
remain = data_len;
buf += hdr_len;
/*@ assert \valid_read(buf + (0 .. (remain - 1))); */
saved_len = hdr_len + data_len;
/*@ assert saved_len <= len; */
/*@ assert data_len <= saved_len; */
/* If present, it must contain at least one extension */
if (data_len == 0) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/* Initialize list of already seen extensions */
/*@
@ loop assigns i, parsed_oid_list[0 .. (MAX_EXT_NUM_PER_CERT - 1)];
@ loop invariant (i < MAX_EXT_NUM_PER_CERT) ==> \valid(&parsed_oid_list[i]);
@ loop variant (MAX_EXT_NUM_PER_CERT - i);
@*/
for (i = 0; i < MAX_EXT_NUM_PER_CERT; i++) {
parsed_oid_list[i] = NULL;
}
/*@ assert \initialized(parsed_oid_list + (0 .. (MAX_EXT_NUM_PER_CERT - 1))); */
/* Now, let's work on each extension in the sequence */
/*@
@ loop assigns ret, buf, remain, parsed_oid_list[0 .. (MAX_EXT_NUM_PER_CERT - 1)], *ctx;
@ loop invariant (remain != 0) ==> \valid_read(buf + (0 .. (remain - 1)));
@ loop variant remain;
@*/
while (remain) {
u16 ext_len = 0;
ret = parse_x509_Extension(buf, remain, parsed_oid_list,
&ext_len, ctx);
if (ret) {
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
remain -= ext_len;
buf += ext_len;
}
/*
* RFC5280 has "If the subject field contains an empty sequence,
* then the issuing CA MUST include a subjectAltName extension
* that is marked as critical."
*/
if (ctx->empty_subject) {
if (ctx->san_empty) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
if (!ctx->san_critical) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
}
/*@ assert 1 <= saved_len <= len; */
*eaten = saved_len;
ret = 0;
out:
return ret;
}
/*
*
* TBSCertificate ::= SEQUENCE {
* version [0] EXPLICIT Version DEFAULT v1,
* serialNumber CertificateSerialNumber,
* signature AlgorithmIdentifier,
* issuer Name,
* validity Validity,
* subject Name,
* subjectPublicKeyInfo SubjectPublicKeyInfo,
* issuerUniqueID [1] IMPLICIT UniqueIdentifier OPTIONAL,
* -- If present, version MUST be v2 or v3
* subjectUniqueID [2] IMPLICIT UniqueIdentifier OPTIONAL,
* -- If present, version MUST be v2 or v3
* extensions [3] EXPLICIT Extensions OPTIONAL
* -- If present, version MUST be v3
* }
*
* On success, the function returns the size of the tbsCertificate
* structure in 'eaten' parameter. It also provides in 'sig_alg'
* a pointer to the signature algorithm found in the signature field.
* This one is provided to be able to check later against the signature
* algorithm found in the signatureAlgorithm field of the certificate.
*/
/*@
@ requires len >= 0;
@ requires ((len > 0) && (buf != \null)) ==> \valid_read(buf + (0 .. (len - 1)));
@ requires \valid(eaten);
@ requires \separated(sig_alg, eaten, buf+(..));
@ ensures \result <= 0;
@ ensures (len == 0) ==> \result < 0;
@ ensures (buf == \null) ==> \result < 0;
@ ensures (\result == 0) ==> (1 < *eaten <= len);
@ assigns *eaten, *sig_alg;
@*/
static int parse_x509_tbsCertificate(const u8 *buf, u16 len,
const _alg_id **sig_alg, u16 *eaten)
{
u16 tbs_data_len = 0;
u16 tbs_hdr_len = 0;
u16 remain = 0;
u16 parsed = 0;
const u8 *subject_ptr, *issuer_ptr;
u16 subject_len, issuer_len;
alg_param param;
const _alg_id *alg = NULL;
cert_parsing_ctx ctx;
int ret, empty_issuer = 1;
if ((buf == NULL) || (len == 0)) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/*
* FIXME! At the moment, when using Frama-C with Typed memory model
* the use of memset() prevents to validate assigns clause for the
* function. At the moment, we workaround that problem by
* initializing the structure field by field. Yes, this is sad.
*/
/* memset(&ctx, 0, sizeof(ctx)); */
ctx.empty_subject = 0;
ctx.san_empty = 0;
ctx.san_critical = 0;
ctx.ca_true = 0;
ctx.bc_critical = 0;
ctx.has_ski = 0;
ctx.has_keyUsage = 0;
ctx.keyCertSign_set = 0;
ctx.cRLSign_set = 0;
ctx.pathLenConstraint_set = 0;
ctx.has_name_constraints = 0;
ctx.has_crldp = 0;
ctx.one_crldp_has_all_reasons = 0;
ctx.aki_has_keyIdentifier = 0;
ctx.self_signed = 0;
/*
* Let's first check we are dealing with a valid sequence containing
* all the elements of the certificate.
*/
ret = parse_id_len(buf, len, CLASS_UNIVERSAL, ASN1_TYPE_SEQUENCE,
&tbs_hdr_len, &tbs_data_len);
if (ret) {
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
buf += tbs_hdr_len;
remain = tbs_data_len;
/*
* Now, we can start and parse all the elements in the sequence
* one by one.
*/
/* version */
ret = parse_x509_Version(buf, remain, &parsed);
if (ret) {
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
buf += parsed;
remain -= parsed;
/* serialNumber */
ret = parse_CertificateSerialNumber(buf, remain,
CLASS_UNIVERSAL, ASN1_TYPE_INTEGER,
&parsed);
if (ret) {
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
buf += parsed;
remain -= parsed;
/* signature */
ret = parse_x509_AlgorithmIdentifier(buf, remain,
&alg, ¶m, &parsed);
if (ret) {
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
if (alg->alg_type != ALG_SIG) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
buf += parsed;
remain -= parsed;
/* issuer */
ret = parse_x509_Name(buf, remain, &parsed, &empty_issuer);
if (ret) {
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/*
* As described in section 4.1.2.4 of RFC 5280, "The issuer field MUST
* contain a non-empty distinguished name (DN)".
*/
/*@ assert (empty_issuer == 0) || (empty_issuer == 1); */
if (empty_issuer) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
issuer_ptr = buf;
issuer_len = parsed;
buf += parsed;
remain -= parsed;
/* validity */
ret = parse_x509_Validity(buf, remain, &parsed);
if (ret) {
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
buf += parsed;
remain -= parsed;
/* subject */
ret = parse_x509_Name(buf, remain, &parsed, &ctx.empty_subject);
if (ret) {
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
subject_ptr = buf;
subject_len = parsed;
buf += parsed;
remain -= parsed;
/*
* We can now check if certificate is self-signed, i.e. if subject and
* issuer fields are identical
*/
ctx.self_signed = 0;
if (subject_len == issuer_len) {
ctx.self_signed = !bufs_differ(subject_ptr, issuer_ptr, issuer_len);
}
/* subjectPublicKeyInfo */
ret = parse_x509_subjectPublicKeyInfo(buf, remain, &parsed);
if (ret) {
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
buf += parsed;
remain -= parsed;
/*
* At that point, the remainder of the tbsCertificate part
* is made of 3 *optional* elements:
*
* issuerUniqueID [1] IMPLICIT UniqueIdentifier OPTIONAL,
* subjectUniqueID [2] IMPLICIT UniqueIdentifier OPTIONAL,
* extensions [3] EXPLICIT Extensions OPTIONAL
*
* w/ UniqueIdentifier ::= BIT STRING
* Extensions ::= SEQUENCE SIZE (1..MAX) OF Extension
*
* Section 4.1.2.8 of RFC 5280 explicitly states that "CAs
* conforming to this profile MUST NOT generate certificates
* with unique identifier" but "Applications conforming to
* this profile SHOULD be capable of parsing certificates
* that include unique identifiers, but there are no processing
* requirements associated with the unique identifiers."
*
* Additionnally, some tests performed on 9826768 (of 18822321)
* certificates that validate in a 2011 TLS campaign, we do not
* have any certificate w/ either a subjectUniqueID or
* issuerUniqueID.
*
* For that reason, in order to simplify parsing, we expect NOT
* to find either a subject or issuer unique identifier and to
* directly find extensions, if any. This is done by checking if
* data remain at that point. If that is the case, we perform
* a full parsing of the Extensions.
*/
if (remain) {
ret = parse_x509_Extensions(buf, remain, &parsed, &ctx);
if (ret) {
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
buf += parsed;
remain -= parsed;
}
if (remain != 0) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/*
* RFC 5280 requires that SKI extension "MUST appear in all conforming
* CA certificates, that is, all certificates including the basic
* constraints extension (Section 4.2.1.9) where the value of cA is
* TRUE"
*/
if (ctx.ca_true && !ctx.has_ski) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/*
* RFC 5280 has "If the keyCertSign bit is asserted, then the cA bit in
* the basic constraints extension (Section 4.2.1.9) MUST also be
* asserted.
*
* It also has the following regarding basicConstraints extension:
* "Conforming CAs MUST include this extension in all CA certificates
* that contain public keys used to validate digital signatures on
* certificates and MUST mark the extension as critical in such
* certificates."
*
* Note that we do not enforce basicConstraints criticality otherwise
* as required by "This extension MAY appear as a critical or
* non-critical extension in CA certificates that contain public keys
* used exclusively for purposes other than validating digital
* signatures on certificates. This extension MAY appear as a critical
* or non-critical extension in end entity certificates."
*/
if (ctx.keyCertSign_set && (!ctx.ca_true || !ctx.bc_critical)) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/*
* If the subject is a CRL issuer (e.g., the key usage extension, as
* discussed in Section 4.2.1.3, is present and the value of cRLSign is
* TRUE), then the subject field MUST be populated with a non-empty
* distinguished name matching the contents of the issuer field (Section
* 5.1.2.3) in all CRLs issued by the subject CRL issuer.
*/
if (ctx.cRLSign_set && ctx.empty_subject) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/*
* RFC5280 has "CAs MUST NOT include the pathLenConstraint field
* unless the cA boolean is asserted and the key usage extension
* asserts the keyCertSign bit."
*/
if (ctx.pathLenConstraint_set &&
(!ctx.ca_true || !ctx.keyCertSign_set)) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/*
* RFC5280 has "The name constraints extension, which MUST be used only
* in a CA certificate, ..."
*/
if (ctx.has_name_constraints && !ctx.ca_true) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/*
* RFC5280 has "When a conforming CA includes a cRLDistributionPoints
* extension in a certificate, it MUST include at least one
* DistributionPoint that points to a CRL that covers the certificate
* for all reasons."
*/
if (ctx.ca_true && ctx.has_crldp && !ctx.one_crldp_has_all_reasons) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/*
* Section 4.2.1.1 of RFC 5280 has "The keyIdentifier field of the
* authorityKeyIdentifier extension MUST be included in all
* certificates generated by conforming CAs to facilitate certification
* path construction. There is one exception; where a CA distributes
* its public key in the form of a "self-signed" certificate, the
* authority key identifier MAY be omitted.
*/
if (!ctx.self_signed && !ctx.aki_has_keyIdentifier) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/*@ assert 1 < (tbs_hdr_len + tbs_data_len) <= len; */
*eaten = tbs_hdr_len + tbs_data_len;
*sig_alg = alg;
ret = 0;
out:
return ret;
}
/*@
@ requires len >= 0;
@ requires ((len > 0) && (buf != \null)) ==> \valid_read(buf + (0 .. (len - 1)));
@ requires \valid(eaten);
@ requires \separated(eaten, buf+(..), exp_sig_alg);
@ ensures \result <= 0;
@ ensures (\result == 0) ==> (1 < *eaten <= len);
@ ensures (len == 0) ==> \result < 0;
@ ensures (buf == \null) ==> \result < 0;
@ assigns *eaten;
@*/
static int parse_x509_signatureAlgorithm(const u8 *buf, u16 len,
const _alg_id *exp_sig_alg, u16 *eaten)
{
const _alg_id *alg = NULL;
alg_param param;
u16 parsed = 0;
int ret;
if ((buf == NULL) || (len == 0)) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/* signature */
ret = parse_x509_AlgorithmIdentifier(buf, len, &alg, ¶m, &parsed);
if (ret) {
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
if (alg->alg_type != ALG_SIG) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
buf += parsed;
len -= parsed;
/*
* As specified in section 4.1.1.2 of RFC 5280, the signatureAlgorithm
* field "MUST contain the same algorithm identifier as the signature
* field in the sequence tbsCertificate (Section 4.1.2.3)."
*/
if (alg != exp_sig_alg) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
*eaten = parsed;
ret = 0;
out:
return ret;
}
#ifdef TEMPORARY_BADALGS
/*@
@ requires len >= 0;
@ requires ((len > 0) && (buf != \null)) ==> \valid_read(buf + (0 .. (len - 1)));
@ requires \valid(eaten);
@ requires \separated(eaten, buf+(..));
@ ensures \result <= 0;
@ ensures (\result == 0) ==> (*eaten <= len);
@ ensures (len == 0) ==> \result < 0;
@ ensures (buf == \null) ==> \result < 0;
@ assigns *eaten;
@*/
static int parse_sig_generic(const u8 *buf, u16 len, u16 *eaten)
{
u16 bs_hdr_len = 0, bs_data_len = 0;
int ret;
ret = parse_id_len(buf, len, CLASS_UNIVERSAL, ASN1_TYPE_BIT_STRING,
&bs_hdr_len, &bs_data_len);
if (ret) {
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/*
* We expect the bitstring data to contain at least the initial
* octet encoding the number of unused bits in the final
* subsequent octet of the bistring.
* */
if (bs_data_len == 0) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
*eaten = bs_hdr_len + bs_data_len;
ret = 0;
out:
return ret;
}
#endif
/*@
@ requires len >= 0;
@ requires ((len > 0) && (buf != \null)) ==> \valid_read(buf + (0 .. (len - 1)));
@ requires \valid(eaten);
@ requires \separated(eaten, buf+(..));
@ ensures \result <= 0;
@ ensures (\result == 0) ==> (*eaten <= len);
@ ensures (len == 0) ==> \result < 0;
@ ensures (buf == \null) ==> \result < 0;
@ assigns *eaten;
@*/
static int parse_sig_ecdsa(const u8 *buf, u16 len, u16 *eaten)
{
u16 bs_hdr_len = 0, bs_data_len = 0, sig_len = 0, hdr_len = 0;
u16 data_len = 0, remain = 0, saved_sig_len = 0;
int ret;
if ((buf == NULL) || (len == 0)) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
ret = parse_id_len(buf, len, CLASS_UNIVERSAL, ASN1_TYPE_BIT_STRING,
&bs_hdr_len, &bs_data_len);
if (ret) {
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
saved_sig_len = bs_hdr_len + bs_data_len;
/*@ assert saved_sig_len <= len; */
buf += bs_hdr_len;
/*
* We expect the bitstring data to contain at least the initial
* octet encoding the number of unused bits in the final
* subsequent octet of the bistring.
* */
if (bs_data_len == 0) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/*
* The signature field is always a bitstring whose content
* may then be interpreted depending on the signature
* algorithm. At the moment, we only support ECDSA signature
* mechanisms. In that case, the content of the bitstring
* is parsed as defined in RFC5480, i.e. as a sequence of
* two integers:
*
* ECDSA-Sig-Value ::= SEQUENCE {
* r INTEGER,
* s INTEGER
* }
*
* As we only structural checks here, we do not verify
* the values stored in the integer are valid r and s
* values for the specific alg/curve.
*/
/*
* We expect the initial octet to encode a value of 0
* indicating that there are no unused bits in the final
* subsequent octet of the bitstring.
*/
if (buf[0] != 0) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
buf += 1;
sig_len = bs_data_len - 1;
/*
* Now that we know we are indeed dealing w/ an ECDSA sig mechanism,
* let's check we have a sequence of two integers.
*/
ret = parse_id_len(buf, sig_len,
CLASS_UNIVERSAL, ASN1_TYPE_SEQUENCE,
&hdr_len, &data_len);
if (ret) {
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
remain = sig_len - hdr_len;
buf += hdr_len;
/* Now, we should find the first integer, r */
ret = parse_id_len(buf, remain, CLASS_UNIVERSAL, ASN1_TYPE_INTEGER,
&hdr_len, &data_len);
if (ret) {
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
remain -= hdr_len + data_len;
buf += hdr_len + data_len;
/* An then, the second one, s */
ret = parse_id_len(buf, remain, CLASS_UNIVERSAL, ASN1_TYPE_INTEGER,
&hdr_len, &data_len);
if (ret) {
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
remain -= hdr_len + data_len;
buf += hdr_len + data_len;
/*
* Check there is nothing remaining in the bitstring
* after the two integers
*/
if (remain != 0) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/*@ assert saved_sig_len <= len; */
*eaten = saved_sig_len;
ret = 0;
out:
return ret;
}
/*@
@ requires len >= 0;
@ requires ((len > 0) && (buf != \null)) ==> \valid_read(buf + (0 .. (len - 1)));
@ requires (sig_alg != \null) ==> \valid_read(sig_alg) && \valid_function(sig_alg->parse_sig);
@ requires \valid(eaten);
@ ensures \result <= 0;
@ ensures (\result == 0) ==> (*eaten <= len);
@ ensures (len == 0) ==> \result < 0;
@ ensures (buf == \null) ==> \result < 0;
@ assigns *eaten;
@*/
static int parse_x509_signatureValue(const u8 *buf, u16 len,
const _alg_id *sig_alg, u16 *eaten)
{
int ret;
if ((buf == NULL) || (len == 0)) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
if (!sig_alg) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
if (!sig_alg->parse_sig) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/*@ calls parse_sig_ecdsa, parse_sig_generic; @*/
ret = sig_alg->parse_sig(buf, len, eaten);
if (ret) {
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
ret = 0;
out:
return ret;
}
/*@
@ requires len >= 0;
@ requires ((len > 0) && (buf != \null)) ==> \valid_read(buf + (0 .. (len - 1)));
@ ensures \result <= 0;
@ ensures (len == 0) ==> \result < 0;
@ ensures (buf == \null) ==> \result < 0;
@ assigns \nothing;
@*/
int parse_x509_cert(const u8 *buf, u16 len) {
u16 seq_data_len = 0;
u16 eaten = 0;
const _alg_id *sig_alg = NULL;
int ret;
if ((buf == NULL) || (len == 0)) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/*
* Parse beginning of buffer to verify it's a sequence and get
* the length of the data it contains.
*/
ret = parse_id_len(buf, len, CLASS_UNIVERSAL, ASN1_TYPE_SEQUENCE,
&eaten, &seq_data_len);
if (ret) {
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
len -= eaten;
buf += eaten;
/*
* We do expect advertised length to match what now remains in buffer
* after the sequence header we just parsed.
*/
if (seq_data_len != len) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/* Parse first element of the sequence: tbsCertificate */
ret = parse_x509_tbsCertificate(buf, len, &sig_alg, &eaten);
if (ret) {
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
len -= eaten;
buf += eaten;
/* Parse second element of the sequence: signatureAlgorithm */
ret = parse_x509_signatureAlgorithm(buf, len, sig_alg, &eaten);
if (ret) {
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
len -= eaten;
buf += eaten;
/* Parse second element of the sequence: signatureValue */
ret = parse_x509_signatureValue(buf, len, sig_alg, &eaten);
if (ret) {
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/* Check there is nothing left behind */
if (len != eaten) {
ret = -__LINE__;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
ret = 0;
out:
return ret;
}
/*@
@ requires len >= 0;
@ requires ((len > 0) && (buf != \null)) ==> \valid_read(buf + (0 .. (len - 1)));
@ requires \separated(eaten, buf+(..));
@ requires \valid(eaten);
@ ensures \result <= 1;
@ ensures (\result == 0) ==> (*eaten <= len);
@ ensures (\result == 0) ==> (*eaten > 0);
@ ensures (\result < 0) ==> (*eaten <= len);
@ ensures (\result < 0) ==> (*eaten > 0);
@ assigns *eaten;
*/
int parse_x509_cert_relaxed(const u8 *buf, u16 len, u16 *eaten)
{
u16 seq_data_len = 0;
u16 rbytes = 0;
int ret;
/*
* Parse beginning of buffer to verify it's a sequence and get
* the length of the data it contains.
*/
ret = parse_id_len(buf, len, CLASS_UNIVERSAL, ASN1_TYPE_SEQUENCE,
&rbytes, &seq_data_len);
if (ret) {
ret = 1;
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
/* Certificate has that exact length */
*eaten = rbytes + seq_data_len;
/* Parse it */
ret = parse_x509_cert(buf, rbytes + seq_data_len);
if (ret) {
ERROR_TRACE_APPEND(__LINE__);
goto out;
}
ret = 0;
out:
return ret;
}
#ifdef __FRAMAC__
/* This dummy main allows testing */
#include "__fc_builtin.h"
#define RAND_BUF_SIZE 65535
int main(int argc, char *argv[]) {
u8 buf[RAND_BUF_SIZE];
u16 len;
int ret;
/*@ assert \valid(buf + (0 .. (RAND_BUF_SIZE - 1))); */
Frama_C_make_unknown(buf, RAND_BUF_SIZE);
len = Frama_C_interval(0, RAND_BUF_SIZE);
/*@ assert 0 <= len <= RAND_BUF_SIZE; */
ret = parse_x509_cert(buf, len);
return ret;
}
#endif
| 25.432263 | 348 | 0.629747 |
a611644293f2ac804ba03f39a4911d6ce20d8cdb | 1,697 | h | C | src/tests/kits/support/barchivable/common.h | Kirishikesan/haiku | 835565c55830f2dab01e6e332cc7e2d9c015b51e | [
"MIT"
] | 1,338 | 2015-01-03T20:06:56.000Z | 2022-03-26T13:49:54.000Z | src/tests/kits/support/barchivable/common.h | Kirishikesan/haiku | 835565c55830f2dab01e6e332cc7e2d9c015b51e | [
"MIT"
] | 15 | 2015-01-17T22:19:32.000Z | 2021-12-20T12:35:00.000Z | src/tests/kits/support/barchivable/common.h | Kirishikesan/haiku | 835565c55830f2dab01e6e332cc7e2d9c015b51e | [
"MIT"
] | 350 | 2015-01-08T14:15:27.000Z | 2022-03-21T18:14:35.000Z | //------------------------------------------------------------------------------
#ifndef COMMON_H
#define COMMON_H
// Standard Includes -----------------------------------------------------------
#include <posix/string.h>
#include <errno.h>
// System Includes -------------------------------------------------------------
// Project Includes ------------------------------------------------------------
#include "cppunit/TestCaller.h"
#include "TestCase.h"
//#include "TestResult.h"
#include "cppunit/TestSuite.h"
// Local Includes --------------------------------------------------------------
// Local Defines ---------------------------------------------------------------
#define assert_err(condition) \
(this->assertImplementation ((condition), std::string((#condition)) + \
strerror(condition),\
__LINE__, __FILE__))
#define ADD_TEST(suitename, classname, funcname) \
(suitename)->addTest(new CppUnit::TestCaller<classname>(std::string("BArchivable::") + \
std::string((#funcname)), &classname::funcname));
#define ADD_TEST4(classbeingtested, suitename, classname, funcname) \
(suitename)->addTest(new TestCaller<classname>((#classbeingtested "::" #funcname), \
&classname::funcname));
#define CHECK_ERRNO \
cout << endl << "errno == \"" << strerror(errno) << "\" (" << errno \
<< ") in " << __PRETTY_FUNCTION__ << endl
#define CHECK_STATUS(status__) \
cout << endl << "status_t == \"" << strerror((status__)) << "\" (" \
<< (status__) << ") in " << __PRETTY_FUNCTION__ << endl
// Globals ---------------------------------------------------------------------
#endif //COMMON_H
/*
* $Log $
*
* $Id $
*
*/
| 32.018868 | 89 | 0.46317 |
10b33ad11a12e8ade3637d641256936fd2eef5cb | 2,446 | h | C | core/usbcdc/usbuser.h | Shifter1/lpc1343codebase | 0b056aa80ce15acc756f0b5f12982741afef0995 | [
"BSD-3-Clause"
] | 1 | 2019-12-19T20:21:24.000Z | 2019-12-19T20:21:24.000Z | core/usbcdc/usbuser.h | Shifter1/lpc1343codebase | 0b056aa80ce15acc756f0b5f12982741afef0995 | [
"BSD-3-Clause"
] | null | null | null | core/usbcdc/usbuser.h | Shifter1/lpc1343codebase | 0b056aa80ce15acc756f0b5f12982741afef0995 | [
"BSD-3-Clause"
] | 1 | 2019-12-19T20:21:37.000Z | 2019-12-19T20:21:37.000Z | /*----------------------------------------------------------------------------
* U S B - K e r n e l
*----------------------------------------------------------------------------
* Name: USBUSER.H
* Purpose: USB Custom User Definitions
* Version: V1.10
*----------------------------------------------------------------------------
* This software is supplied "AS IS" without any warranties, express,
* implied or statutory, including but not limited to the implied
* warranties of fitness for purpose, satisfactory quality and
* noninfringement. Keil extends you a royalty-free right to reproduce
* and distribute executable files created using this software for use
* on NXP Semiconductors LPC microcontroller devices only. Nothing else
* gives you the right to use this software.
*
* Copyright (c) 2005-2009 Keil Software.
*---------------------------------------------------------------------------*/
#ifndef __USBUSER_H__
#define __USBUSER_H__
/* USB Device Events Callback Functions */
extern void USB_Power_Event (uint32_t power);
extern void USB_Reset_Event (void);
extern void USB_Suspend_Event (void);
extern void USB_Resume_Event (void);
extern void USB_WakeUp_Event (void);
extern void USB_SOF_Event (void);
extern void USB_Error_Event (uint32_t error);
/* USB Endpoint Callback Events */
#define USB_EVT_SETUP 1 /* Setup Packet */
#define USB_EVT_OUT 2 /* OUT Packet */
#define USB_EVT_IN 3 /* IN Packet */
#define USB_EVT_OUT_NAK 4 /* OUT Packet - Not Acknowledged */
#define USB_EVT_IN_NAK 5 /* IN Packet - Not Acknowledged */
#define USB_EVT_OUT_STALL 6 /* OUT Packet - Stalled */
#define USB_EVT_IN_STALL 7 /* IN Packet - Stalled */
/* USB Endpoint Events Callback Pointers */
extern void (* const USB_P_EP[USB_LOGIC_EP_NUM])(uint32_t event);
/* USB Endpoint Events Callback Functions */
extern void USB_EndPoint0 (uint32_t event);
extern void USB_EndPoint1 (uint32_t event);
extern void USB_EndPoint2 (uint32_t event);
extern void USB_EndPoint3 (uint32_t event);
extern void USB_EndPoint4 (uint32_t event);
/* USB Core Events Callback Functions */
extern void USB_Configure_Event (void);
extern void USB_Interface_Event (void);
extern void USB_Feature_Event (void);
#endif /* __USBUSER_H__ */
| 42.172414 | 80 | 0.600572 |
0802020c5b121d0481fc0b1265526be9467ec8a7 | 1,067 | h | C | swift/Project/Pods/OneKit/OneKit/ByteDanceKit/UIKit/UILabel+BTDAdditions.h | jfsong1122/iostest | d9cf8156d8a0b6fa4a8aa383d40ac5ff9ba2a7d9 | [
"MIT"
] | null | null | null | swift/Project/Pods/OneKit/OneKit/ByteDanceKit/UIKit/UILabel+BTDAdditions.h | jfsong1122/iostest | d9cf8156d8a0b6fa4a8aa383d40ac5ff9ba2a7d9 | [
"MIT"
] | null | null | null | swift/Project/Pods/OneKit/OneKit/ByteDanceKit/UIKit/UILabel+BTDAdditions.h | jfsong1122/iostest | d9cf8156d8a0b6fa4a8aa383d40ac5ff9ba2a7d9 | [
"MIT"
] | null | null | null | //
// UILabel+BTDAdditions.h
// Essay
//
// Created by Tianhang Yu on 12-7-3.
// Copyright (c) 2012 Bytedance. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface UILabel (BTDAdditions)
/**
Return the height according to he maxWidth.
@param maxWidth The max width.
@return The height.
*/
- (CGFloat)btd_heightWithWidth:(CGFloat)maxWidth;
/**
Return the width according to he maxHeight.
@param maxHeight The max height.
@return The width.
*/
- (CGFloat)btd_widthWithHeight:(CGFloat)maxHeight;
/**
Set the label's text and the text's line height.
@param text The text.
@param lineHeight The line height of the text.
*/
- (void)btd_SetText:(nonnull NSString *)text lineHeight:(CGFloat)lineHeight;
/**
Set the label's text and highlight the partial text.
@param originText The text.
@param needHighlightText The highlighting text.
@param color The highlighting color.
*/
- (void)btd_setText:(nonnull NSString *)originText withNeedHighlightedText:(nonnull NSString *)needHighlightText highlightedColor:(nonnull UIColor *)color;
@end
| 22.702128 | 155 | 0.738519 |
bd73ec77d41a2cd668af6d102bd3bcd680f1b722 | 4,118 | c | C | jerry-core/ecma/builtin-objects/ecma-builtin-intrinsic.c | mmatyas/jerryscript | 6ff299c8314afbca083b60cf1d23000b1808f2b5 | [
"Apache-2.0"
] | null | null | null | jerry-core/ecma/builtin-objects/ecma-builtin-intrinsic.c | mmatyas/jerryscript | 6ff299c8314afbca083b60cf1d23000b1808f2b5 | [
"Apache-2.0"
] | null | null | null | jerry-core/ecma/builtin-objects/ecma-builtin-intrinsic.c | mmatyas/jerryscript | 6ff299c8314afbca083b60cf1d23000b1808f2b5 | [
"Apache-2.0"
] | 1 | 2021-09-13T12:04:01.000Z | 2021-09-13T12:04:01.000Z | /* Copyright JS Foundation and other contributors, http://js.foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "ecma-builtins.h"
#include "ecma-array-object.h"
#include "ecma-gc.h"
#include "lit-char-helpers.h"
#if ENABLED (JERRY_ES2015)
#define ECMA_BUILTINS_INTERNAL
#include "ecma-builtins-internal.h"
/**
* This object has a custom dispatch function.
*/
#define BUILTIN_CUSTOM_DISPATCH
/**
* List of built-in routine identifiers.
*/
enum
{
ECMA_INTRINSIC_ROUTINE_START = ECMA_BUILTIN_ID__COUNT - 1,
ECMA_INTRINSIC_PARSE_FLOAT,
ECMA_INTRINSIC_PARSE_INT,
ECMA_INTRINSIC_ARRAY_PROTOTYPE_VALUES
};
#define BUILTIN_INC_HEADER_NAME "ecma-builtin-intrinsic.inc.h"
#define BUILTIN_UNDERSCORED_ID intrinsic
#include "ecma-builtin-internal-routines-template.inc.h"
/** \addtogroup ecma ECMA
* @{
*
* \addtogroup ecmabuiltins
* @{
*
* \addtogroup intrinsic ECMA Intrinsic object built-in
* @{
*/
/**
* The %ArrayProto_values% intrinsic routine
*
* See also:
* ECMA-262 v5, 15.4.4.4
*
* @return ecma value
* Returned value must be freed with ecma_free_value.
*/
static ecma_value_t
ecma_builtin_intrinsic_array_prototype_values (ecma_value_t this_value) /**< this argument */
{
ecma_value_t this_obj = ecma_op_to_object (this_value);
if (ECMA_IS_VALUE_ERROR (this_obj))
{
return this_obj;
}
ecma_object_t *this_obj_p = ecma_get_object_from_value (this_obj);
ecma_value_t ret_value = ecma_op_create_array_iterator (this_obj_p, ECMA_ITERATOR_VALUES);
ecma_deref_object (this_obj_p);
return ret_value;
} /* ecma_builtin_intrinsic_array_prototype_values */
/**
* Dispatcher of the built-in's routines
*
* @return ecma value
* Returned value must be freed with ecma_free_value.
*/
ecma_value_t
ecma_builtin_intrinsic_dispatch_routine (uint16_t builtin_routine_id, /**< built-in wide routine identifier */
ecma_value_t this_arg, /**< 'this' argument value */
const ecma_value_t arguments_list_p[], /**< list of arguments
* passed to routine */
ecma_length_t arguments_number) /**< length of arguments' list */
{
JERRY_UNUSED (arguments_number);
ecma_value_t routine_arg_1 = arguments_list_p[0];
ecma_value_t routine_arg_2 = arguments_list_p[1];
if (builtin_routine_id == ECMA_INTRINSIC_ARRAY_PROTOTYPE_VALUES)
{
return ecma_builtin_intrinsic_array_prototype_values (this_arg);
}
ecma_value_t ret_value = ECMA_VALUE_EMPTY;
if (builtin_routine_id <= ECMA_INTRINSIC_PARSE_INT)
{
ecma_string_t *str_p = ecma_op_to_string (routine_arg_1);
if (JERRY_UNLIKELY (str_p == NULL))
{
return ECMA_VALUE_ERROR;
}
ECMA_STRING_TO_UTF8_STRING (str_p, string_buff, string_buff_size);
if (builtin_routine_id == ECMA_INTRINSIC_PARSE_INT)
{
ret_value = ecma_number_parse_int (string_buff,
string_buff_size,
routine_arg_2);
}
else
{
JERRY_ASSERT (builtin_routine_id == ECMA_INTRINSIC_PARSE_FLOAT);
ret_value = ecma_number_parse_float (string_buff,
string_buff_size);
}
ECMA_FINALIZE_UTF8_STRING (string_buff, string_buff_size);
ecma_deref_ecma_string (str_p);
}
return ret_value;
} /* ecma_builtin_intrinsic_dispatch_routine */
/**
* @}
* @}
* @}
*/
#endif /* ENABLED (JERRY_ES2015) */
| 28.597222 | 110 | 0.68237 |
ebee4e8980193fa5247586f5ebfda55b9d272142 | 2,365 | h | C | Validation/DTRecHits/plugins/DTSegment4DQuality.h | nistefan/cmssw | ea13af97f7f2117a4f590a5e654e06ecd9825a5b | [
"Apache-2.0"
] | 1 | 2019-08-09T08:42:11.000Z | 2019-08-09T08:42:11.000Z | Validation/DTRecHits/plugins/DTSegment4DQuality.h | nistefan/cmssw | ea13af97f7f2117a4f590a5e654e06ecd9825a5b | [
"Apache-2.0"
] | null | null | null | Validation/DTRecHits/plugins/DTSegment4DQuality.h | nistefan/cmssw | ea13af97f7f2117a4f590a5e654e06ecd9825a5b | [
"Apache-2.0"
] | 1 | 2019-03-19T13:44:54.000Z | 2019-03-19T13:44:54.000Z | #ifndef Validation_DTRecHits_DTSegment4DQuality_h
#define Validation_DTRecHits_DTSegment4DQuality_h
/** \class DTSegment4DQuality
* Basic analyzer class which accesses 4D DTSegments
* and plots resolution comparing reconstructed and simulated quantities
*
* Only true 4D segments are considered.
* Station 4 segments are not looked at.
* FIXME: Add flag to consider also
* segments with only phi view? Possible bias?
*
* Residual/pull plots are filled for the reco segment with alpha closest
* to the simulated muon direction (defined from muon simhits in the chamber).
*
* Efficiencies are defined as reconstructed 4D segments with alpha, beta, x, y,
* within 5 sigma relative to the sim muon, with sigmas specified in the config.
* Note that loss of even only one of the two views is considered as inefficiency!
*
* \author S. Bolognesi and G. Cerminara - INFN Torino
*/
#include <map>
#include <string>
#include <vector>
#include "DQMServices/Core/interface/ConcurrentMonitorElement.h"
#include "DQMServices/Core/interface/DQMGlobalEDAnalyzer.h"
#include "DataFormats/DTRecHit/interface/DTRecSegment4DCollection.h"
#include "FWCore/Utilities/interface/InputTag.h"
#include "SimDataFormats/TrackingHit/interface/PSimHitContainer.h"
namespace edm {
class ParameterSet;
class Event;
class EventSetup;
}
class HRes4DHit;
class HEff4DHit;
namespace dtsegment4d {
struct Histograms;
}
class DTSegment4DQuality : public DQMGlobalEDAnalyzer<dtsegment4d::Histograms> {
public:
/// Constructor
DTSegment4DQuality(const edm::ParameterSet& pset);
private:
/// Book the DQM plots
void bookHistograms(DQMStore::ConcurrentBooker &, edm::Run const&, edm::EventSetup const&, dtsegment4d::Histograms &) const override;
/// Perform the real analysis
void dqmAnalyze(edm::Event const&, edm::EventSetup const&, dtsegment4d::Histograms const&) const override;
private:
// Labels to read from event
edm::InputTag simHitLabel_;
edm::InputTag segment4DLabel_;
edm::EDGetTokenT<edm::PSimHitContainer> simHitToken_;
edm::EDGetTokenT<DTRecSegment4DCollection> segment4DToken_;
// Sigma resolution on position
double sigmaResX_;
double sigmaResY_;
// Sigma resolution on angle
double sigmaResAlpha_;
double sigmaResBeta_;
bool doall_;
bool local_;
// Switch for debug output
bool debug_;
};
#endif
| 29.5625 | 135 | 0.769133 |
d6fad691617ee5e582749bff7710f5d5ede1be01 | 1,208 | h | C | src/EventListView.h | JadedCtrl/Calendar | 12e1362b7b1261e3d233c11c1096462e4cb8b15a | [
"MIT"
] | 20 | 2017-08-29T09:01:26.000Z | 2021-12-14T13:43:18.000Z | src/EventListView.h | JadedCtrl/Calendar | 12e1362b7b1261e3d233c11c1096462e4cb8b15a | [
"MIT"
] | 78 | 2017-08-29T18:08:24.000Z | 2022-01-17T17:45:23.000Z | src/EventListView.h | JadedCtrl/Calendar | 12e1362b7b1261e3d233c11c1096462e4cb8b15a | [
"MIT"
] | 25 | 2017-09-03T07:03:18.000Z | 2022-03-11T06:29:32.000Z | /*
* Copyright 2017 Akshay Agarwal, agarwal.akshay.akshay8@gmail.com
* Copyright 2010-2017 Humdinger, humdingerb@gmail.com
* All rights reserved. Distributed under the terms of the MIT license.
*/
#ifndef EVENTLISTVIEW_H
#define EVENTLISTVIEW_H
#include <ListView.h>
class Event;
static const uint32 kPopClosed = 'kpop';
class EventListView : public BListView {
public:
EventListView(const char* name);
~EventListView();
virtual void Draw(BRect rect);
virtual void FrameResized(float w, float h);
virtual void MessageReceived(BMessage* message);
virtual void MouseDown(BPoint position);
virtual void MouseUp(BPoint position);
virtual void SelectionChanged();
virtual void MakeEmpty();
Event* SelectedEvent();
void SetPopUpMenuEnabled(bool enable);
private:
static const int32 kEditActionInvoked = 1000;
static const int32 kDeleteActionInvoked = 1001;
static const int32 kCancelActionInvoked = 1002;
static const int32 kHideActionInvoked = 1003;
void _ShowPopUpMenu(BPoint screen);
void _ShowEmptyPopUpMenu(BPoint screen);
bool fShowingPopUpMenu;
bool fPopUpMenuEnabled;
bool fPrimaryButton;
int32 fCurrentItemIndex;
};
#endif // EVENTLISTVIEW_H
| 23.686275 | 71 | 0.765728 |
83fbeb96461fe9264e0372af3cd1cb2724da8fc1 | 2,000 | h | C | include/ndm/pool.h | keenetic/libndm | 519175d2e4d288f09924f1409cb0c87e654ee090 | [
"MIT"
] | 2 | 2018-06-10T19:42:37.000Z | 2019-07-03T14:11:44.000Z | include/ndm/pool.h | keenetic/libndm | 519175d2e4d288f09924f1409cb0c87e654ee090 | [
"MIT"
] | null | null | null | include/ndm/pool.h | keenetic/libndm | 519175d2e4d288f09924f1409cb0c87e654ee090 | [
"MIT"
] | 1 | 2020-05-29T13:03:34.000Z | 2020-05-29T13:03:34.000Z | #ifndef __NDM_POOL__
#define __NDM_POOL__
#include <stddef.h>
#include <stdbool.h>
#include "attr.h"
struct ndm_pool_t
{
void *const __static_block;
const size_t __static_block_size;
void *__dynamic_block;
const size_t __dynamic_block_size;
size_t __available;
size_t __total_allocated;
size_t __total_dynamic_size;
bool __is_valid;
};
#define NDM_POOL_INITIALIZER( \
static_block, \
static_block_size, \
dynamic_block_size) \
{ \
.__static_block = static_block, \
.__static_block_size = static_block_size, \
.__dynamic_block = NULL, \
.__dynamic_block_size = dynamic_block_size, \
.__available = static_block_size, \
.__total_allocated = 0, \
.__total_dynamic_size = 0, \
.__is_valid = true \
}
void ndm_pool_init(
struct ndm_pool_t *pool,
void *static_block,
const size_t static_block_size,
const size_t dynamic_block_size);
static bool ndm_pool_is_valid(
const struct ndm_pool_t *pool) NDM_ATTR_WUR;
static inline bool ndm_pool_is_valid(
const struct ndm_pool_t *pool)
{
return pool->__is_valid;
}
void *ndm_pool_malloc(
struct ndm_pool_t *pool,
const size_t size) NDM_ATTR_WUR;
void *ndm_pool_calloc(
struct ndm_pool_t *pool,
const size_t nmemb,
const size_t size) NDM_ATTR_WUR;
char *ndm_pool_strdup(
struct ndm_pool_t *pool,
const char *const s) NDM_ATTR_WUR;
char *ndm_pool_strndup(
struct ndm_pool_t *pool,
const char *const s,
const size_t size) NDM_ATTR_WUR;
void ndm_pool_clear(
struct ndm_pool_t *pool);
static size_t ndm_pool_allocated(
const struct ndm_pool_t *pool) NDM_ATTR_WUR;
static inline size_t ndm_pool_allocated(
const struct ndm_pool_t *pool)
{
return pool->__total_allocated;
}
static size_t ndm_pool_total_dynamic_size(
const struct ndm_pool_t *pool) NDM_ATTR_WUR;
static inline size_t ndm_pool_total_dynamic_size(
const struct ndm_pool_t *pool)
{
return pool->__total_dynamic_size;
}
#endif /* __NDM_POOL__ */
| 22.727273 | 49 | 0.7415 |
d8040938869f183119e394fa0bd0189f72ff1553 | 475 | h | C | SimCalorimetry/EcalSimAlgos/interface/APDShape.h | nistefan/cmssw | ea13af97f7f2117a4f590a5e654e06ecd9825a5b | [
"Apache-2.0"
] | null | null | null | SimCalorimetry/EcalSimAlgos/interface/APDShape.h | nistefan/cmssw | ea13af97f7f2117a4f590a5e654e06ecd9825a5b | [
"Apache-2.0"
] | null | null | null | SimCalorimetry/EcalSimAlgos/interface/APDShape.h | nistefan/cmssw | ea13af97f7f2117a4f590a5e654e06ecd9825a5b | [
"Apache-2.0"
] | null | null | null | #ifndef EcalSimAlgos_APDShape_h
#define EcalSimAlgos_APDShape_h
#include "SimCalorimetry/EcalSimAlgos/interface/EcalShapeBase.h"
class APDShape : public EcalShapeBase
{
public:
APDShape( double tStart,
double tau ) ;
~APDShape() override ;
double threshold() const override ;
protected:
void fillShape( EcalShapeBase::DVec& aVec ) const override ;
private:
double m_tStart ;
double m_tau ;
};
#endif
| 15.322581 | 66 | 0.669474 |
1423f34f0dd9909869d9d5a847eba78ea7daa4d2 | 7,390 | c | C | shell/task/word.c | Koshroy/mrsh | 8660d8d07139359b278eb9cc6a36bfee03786a34 | [
"MIT"
] | 1 | 2019-04-14T20:18:28.000Z | 2019-04-14T20:18:28.000Z | shell/task/word.c | sahwar/mrsh | a0141f7e954bf69dcc6827a5b07e82ffb20b5bd7 | [
"MIT"
] | null | null | null | shell/task/word.c | sahwar/mrsh | a0141f7e954bf69dcc6827a5b07e82ffb20b5bd7 | [
"MIT"
] | null | null | null | #define _POSIX_C_SOURCE 200809L
#include <assert.h>
#include <errno.h>
#include <mrsh/buffer.h>
#include <mrsh/parser.h>
#include <stdio.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "builtin.h"
#include "shell/process.h"
#include "shell/task.h"
#define READ_SIZE 1024
struct task_word {
struct task task;
struct mrsh_word **word_ptr;
enum tilde_expansion tilde_expansion;
// only if it's a command
bool started;
struct process process;
int fd;
};
static bool buffer_read_from(struct mrsh_buffer *buf, int fd) {
while (true) {
char *dst = mrsh_buffer_reserve(buf, READ_SIZE);
ssize_t n = read(fd, dst, READ_SIZE);
if (n < 0 && errno == EINTR) {
continue;
} else if (n < 0) {
fprintf(stderr, "read() failed: %s\n", strerror(errno));
return false;
} else if (n == 0) {
break;
}
buf->len += n;
}
return true;
}
static void task_word_swap(struct task_word *tw,
struct mrsh_word *new_word) {
mrsh_word_destroy(*tw->word_ptr);
*tw->word_ptr = new_word;
}
static void task_word_destroy(struct task *task) {
struct task_word *tw = (struct task_word *)task;
if (tw->started) {
process_finish(&tw->process);
}
free(tw);
}
static bool task_word_command_start(struct task_word *tw,
struct context *ctx) {
struct mrsh_word *word = *tw->word_ptr;
struct mrsh_word_command *wc = mrsh_word_get_command(word);
int fds[2];
if (pipe(fds) != 0) {
fprintf(stderr, "pipe() failed: %s\n", strerror(errno));
return false;
}
pid_t pid = fork();
if (pid < 0) {
close(fds[0]);
close(fds[1]);
fprintf(stderr, "failed to fork(): %s\n", strerror(errno));
return false;
} else if (pid == 0) {
close(fds[0]);
dup2(fds[1], STDOUT_FILENO);
close(fds[1]);
if (wc->program != NULL) {
mrsh_run_program(ctx->state, wc->program);
}
exit(ctx->state->exit >= 0 ? ctx->state->exit : EXIT_SUCCESS);
}
close(fds[1]);
process_init(&tw->process, pid);
tw->fd = fds[0];
return true;
}
static const char *parameter_get_value(struct mrsh_state *state, char *name) {
static char value[16];
char *end;
long lvalue = strtol(name, &end, 10);
// Special cases
if (strcmp(name, "@") == 0) {
// TODO
} else if (strcmp(name, "*") == 0) {
// TODO
} else if (strcmp(name, "#") == 0) {
sprintf(value, "%d", state->args->argc - 1);
return value;
} else if (strcmp(name, "?") == 0) {
sprintf(value, "%d", state->last_status);
return value;
} else if (strcmp(name, "-") == 0) {
return print_options(state);
} else if (strcmp(name, "$") == 0) {
sprintf(value, "%d", (int)getpid());
return value;
} else if (strcmp(name, "!") == 0) {
// TODO
} else if (end[0] == '\0') {
if (lvalue >= state->args->argc) {
return NULL;
}
return state->args->argv[lvalue];
}
// User-set cases
return mrsh_env_get(state, name, NULL);
}
static int task_word_poll(struct task *task, struct context *ctx) {
struct task_word *tw = (struct task_word *)task;
struct mrsh_word *word = *tw->word_ptr;
int ret;
switch (word->type) {
case MRSH_WORD_STRING:;
struct mrsh_word_string *ws = mrsh_word_get_string(word);
if (!ws->single_quoted && tw->tilde_expansion != TILDE_EXPANSION_NONE) {
// TODO: TILDE_EXPANSION_ASSIGNMENT
expand_tilde(ctx->state, &ws->str);
}
return 0;
case MRSH_WORD_PARAMETER:;
struct mrsh_word_parameter *wp = mrsh_word_get_parameter(word);
const char *value = parameter_get_value(ctx->state, wp->name);
if (value == NULL && strcmp(wp->name, "LINENO") == 0) {
struct mrsh_position pos;
mrsh_word_range(word, &pos, NULL);
char lineno[16];
snprintf(lineno, sizeof(lineno), "%d", pos.line);
value = lineno;
}
if (value == NULL) {
if ((ctx->state->options & MRSH_OPT_NOUNSET)) {
fprintf(stderr, "%s: %s: unbound variable\n",
ctx->state->args->argv[0], wp->name);
return TASK_STATUS_ERROR;
}
value = "";
}
struct mrsh_word_string *replacement =
mrsh_word_string_create(strdup(value), false);
task_word_swap(tw, &replacement->word);
return 0;
case MRSH_WORD_COMMAND:
if (!tw->started) {
if (!task_word_command_start(tw, ctx)) {
return TASK_STATUS_ERROR;
}
tw->started = true;
// TODO: reading from the pipe blocks the whole shell
struct mrsh_buffer buf = {0};
if (!buffer_read_from(&buf, tw->fd)) {
mrsh_buffer_finish(&buf);
close(tw->fd);
return TASK_STATUS_ERROR;
}
mrsh_buffer_append_char(&buf, '\0');
close(tw->fd);
tw->fd = -1;
// Trim newlines at the end
ssize_t i = buf.len - 2;
while (i >= 0 && buf.data[i] == '\n') {
buf.data[i] = '\0';
--i;
}
struct mrsh_word_string *ws =
mrsh_word_string_create(mrsh_buffer_steal(&buf), false);
task_word_swap(tw, &ws->word);
}
return process_poll(&tw->process);
case MRSH_WORD_ARITHMETIC:;
struct mrsh_word_arithmetic *wa = mrsh_word_get_arithmetic(word);
char *body_str = mrsh_word_str(wa->body);
struct mrsh_parser *parser =
mrsh_parser_with_data(body_str, strlen(body_str));
free(body_str);
struct mrsh_arithm_expr *expr = mrsh_parse_arithm_expr(parser);
if (expr == NULL) {
struct mrsh_position err_pos;
const char *err_msg = mrsh_parser_error(parser, &err_pos);
if (err_msg != NULL) {
// TODO: improve error line/column
fprintf(stderr, "%s (arithmetic %d:%d): %s\n",
ctx->state->args->argv[0], err_pos.line,
err_pos.column, err_msg);
} else {
fprintf(stderr, "expected an arithmetic expression\n");
}
ret = TASK_STATUS_ERROR;
} else {
long result;
if (!mrsh_run_arithm_expr(expr, &result)) {
ret = TASK_STATUS_ERROR;
} else {
char buf[32];
snprintf(buf, sizeof(buf), "%ld", result);
struct mrsh_word_string *ws =
mrsh_word_string_create(strdup(buf), false);
task_word_swap(tw, &ws->word);
ret = EXIT_SUCCESS;
}
}
mrsh_arithm_expr_destroy(expr);
mrsh_parser_destroy(parser);
return ret;
case MRSH_WORD_LIST:
assert(false);
}
assert(false);
}
static const struct task_interface task_word_impl = {
.destroy = task_word_destroy,
.poll = task_word_poll,
};
struct task *task_word_create(struct mrsh_word **word_ptr,
enum tilde_expansion tilde_expansion) {
struct mrsh_word *word = *word_ptr;
if (word->type == MRSH_WORD_LIST) {
// For word lists, we just need to expand each word
struct mrsh_word_list *wl = mrsh_word_get_list(word);
struct task *task_list = task_list_create();
for (size_t i = 0; i < wl->children.len; ++i) {
struct mrsh_word **child_ptr =
(struct mrsh_word **)&wl->children.data[i];
if (i > 0 || wl->double_quoted) {
tilde_expansion = TILDE_EXPANSION_NONE;
}
task_list_add(task_list,
task_word_create(child_ptr, tilde_expansion));
}
return task_list;
}
struct task_word *tw = calloc(1, sizeof(struct task_word));
task_init(&tw->task, &task_word_impl);
tw->word_ptr = word_ptr;
tw->tilde_expansion = tilde_expansion;
struct task *task = &tw->task;
if (word->type == MRSH_WORD_ARITHMETIC) {
// For arithmetic words, we need to expand the arithmetic expression
// before parsing and evaluating it
struct mrsh_word_arithmetic *wa = mrsh_word_get_arithmetic(word);
struct task *task_list = task_list_create();
task_list_add(task_list,
task_word_create(&wa->body, TILDE_EXPANSION_NONE));
task_list_add(task_list, task);
return task_list;
}
return task;
}
| 25.839161 | 78 | 0.665223 |
147be280830a5d051a6812a315c5f238d7396f4f | 3,862 | h | C | Engine/Source/Runtime/Slate/Private/Framework/Text/TextEditHelper.h | PopCap/GameIdea | 201e1df50b2bc99afc079ce326aa0a44b178a391 | [
"BSD-2-Clause"
] | null | null | null | Engine/Source/Runtime/Slate/Private/Framework/Text/TextEditHelper.h | PopCap/GameIdea | 201e1df50b2bc99afc079ce326aa0a44b178a391 | [
"BSD-2-Clause"
] | 2 | 2015-06-21T17:38:11.000Z | 2015-06-22T20:54:42.000Z | Engine/Source/Runtime/Slate/Private/Framework/Text/TextEditHelper.h | PopCap/GameIdea | 201e1df50b2bc99afc079ce326aa0a44b178a391 | [
"BSD-2-Clause"
] | null | null | null | // Copyright 1998-2015 Epic Games, Inc. All Rights Reserved.
#pragma once
/**
* Design constraints
*/
namespace EditableTextDefs
{
/** Maximum number of undo levels to store */
static const int32 MaxUndoLevels = 99;
/** Vertical text offset from top of widget, as a scalar percentage of maximum character height */
static const float TextVertOffsetPercent = 0.0f;
/** How quickly the cursor's spring will pull the cursor around. Larger is faster. */
static const float CaretSpringConstant = 65.0f;
/** Vertical offset of caret from text location, in pixels */
static const float CaretVertOffset = 1.0f;
/** Width of the caret, as a scalar percentage of the font's maximum character height */
static const float CaretWidthPercent = 0.08f;
/** Height of the caret, as a scalar percentage of the font's maximum character height */
static const float CaretHeightPercent = 0.95f;
/** How long after the user last interacted with the keyboard should we keep the caret at full opacity? */
static const float CaretBlinkPauseTime = 0.1f;
/** How many times should the caret blink per second (full on/off cycles) */
static const float BlinksPerSecond = 1.0f;
/** How many pixels to extend the selection rectangle's left side horizontally */
static const float SelectionRectLeftOffset = 0.0f;
/** How many pixels to extend the selection rectangle's right side horizontally */
static const float SelectionRectRightOffset = 0.0f;
/** How quickly the selection 'targeting' rectangle will slide around. Larger is faster. */
static const float SelectionTargetSpringConstant = 25.0f;
/** Duration of animation selection target effects */
static const float SelectionTargetEffectDuration = 0.25f;
/** Opacity of the selection target effect overlay */
static const float SelectionTargetOpacity = 0.8f;
/** How large the selection target effect will be when selecting text, as a scalar percentage of font height */
static const float SelectingAnimOffsetPercent = 0.15f;
/** How large the selection target effect will be when deselecting text, as a scalar percentage of font height */
static const float DeselectingAnimOffsetPercent = 0.25f;
}
/**
* Contains helper routines that translate input into actions for an ITextEditorWidget.
* Used to share code between SEditableText and SMultiLineEditableText
*/
class FTextEditHelper
{
public:
/** Someone typed a character, translate the input event into a call to a ITextEditorWidget action */
static FReply OnKeyChar( const FCharacterEvent& InCharacterEvent, const TSharedRef< class ITextEditorWidget >& TextEditor );
/** Someone pressed a key, translate the input event into a call to a ITextEditorWidget action */
static FReply OnKeyDown( const FKeyEvent& InKeyEvent, const TSharedRef< ITextEditorWidget >& TextEditor );
static FReply OnMouseButtonDown( const FGeometry& MyGeometry, const FPointerEvent& InMouseEvent, const TSharedRef< ITextEditorWidget >& TextEditor );
static FReply OnMouseMove( const FGeometry& InMyGeometry, const FPointerEvent& InMouseEvent, const TSharedRef< ITextEditorWidget >& TextEditor );
static FReply OnMouseButtonUp( const FGeometry& MyGeometry, const FPointerEvent& InMouseEvent, const TSharedRef< ITextEditorWidget >& TextEditor );
static FReply OnMouseButtonDoubleClick(const FGeometry& InMyGeometry, const FPointerEvent& InMouseEvent, const TSharedRef< ITextEditorWidget >& TextEditor);
/**
* Gets the height of the largest character in the font
*
* @return The fonts height
*/
static float GetFontHeight(const FSlateFontInfo& FontInfo);
/**
* Calculate the width of the caret
* @param FontMaxCharHeight The height of the font to calculate the caret width for
* @return The width of the caret (might be clamped for very small fonts)
*/
static float CalculateCaretWidth(const float FontMaxCharHeight);
};
| 41.978261 | 157 | 0.769032 |
37b27ffccf64ba2923deb577a83e53492abf698e | 4,612 | h | C | TAO/CIAO/connectors/ami4ccm/tests/InterInArgs/Sender/InterInArgsT_Sender_exec.h | cflowe/ACE | 5ff60b41adbe1772372d1a43bcc1f2726ff8f810 | [
"DOC"
] | 36 | 2015-01-10T07:27:33.000Z | 2022-03-07T03:32:08.000Z | TAO/CIAO/connectors/ami4ccm/tests/InterInArgs/Sender/InterInArgsT_Sender_exec.h | cflowe/ACE | 5ff60b41adbe1772372d1a43bcc1f2726ff8f810 | [
"DOC"
] | 2 | 2018-08-13T07:30:51.000Z | 2019-02-25T03:04:31.000Z | TAO/CIAO/connectors/ami4ccm/tests/InterInArgs/Sender/InterInArgsT_Sender_exec.h | cflowe/ACE | 5ff60b41adbe1772372d1a43bcc1f2726ff8f810 | [
"DOC"
] | 38 | 2015-01-08T14:12:06.000Z | 2022-01-19T08:33:00.000Z | // -*- C++ -*-
// $Id: InterInArgsT_Sender_exec.h 92902 2010-12-17 15:09:42Z mcorino $
/**
* Code generated by the The ACE ORB (TAO) IDL Compiler v1.8.3
* TAO and the TAO IDL Compiler have been developed by:
* Center for Distributed Object Computing
* Washington University
* St. Louis, MO
* USA
* http://www.cs.wustl.edu/~schmidt/doc-center.html
* and
* Distributed Object Computing Laboratory
* University of California at Irvine
* Irvine, CA
* USA
* and
* Institute for Software Integrated Systems
* Vanderbilt University
* Nashville, TN
* USA
* http://www.isis.vanderbilt.edu/
*
* Information about TAO is available at:
* http://www.cs.wustl.edu/~schmidt/TAO.html
**/
#ifndef CIAO_INTERINARGST_SENDER_EXEC_XOE8WS_H_
#define CIAO_INTERINARGST_SENDER_EXEC_XOE8WS_H_
#include /**/ "ace/pre.h"
#include "ace/Task.h"
#include "InterInArgsT_SenderEC.h"
#if !defined (ACE_LACKS_PRAGMA_ONCE)
# pragma once
#endif /* ACE_LACKS_PRAGMA_ONCE */
#include /**/ "InterInArgsT_Sender_exec_export.h"
#include "tao/LocalObject.h"
namespace CIAO_InterInArgsT_Sender_Impl
{
typedef ACE_Atomic_Op <TAO_SYNCH_MUTEX, CORBA::UShort > Atomic_UShort;
/// Common exception handlers
void HandleException (
long id,
long expect_id,
const char* error_string,
const char* func);
/// Worker thread for asynchronous invocations
class asynch_foo_generator : public virtual ACE_Task_Base
{
public:
asynch_foo_generator (::InterInArgsT::CCM_Sender_Context_ptr context,
Atomic_UShort &nr_of_received_);
virtual int svc (void);
private:
::InterInArgsT::CCM_Sender_Context_var context_;
Atomic_UShort &nr_of_received_;
};
/// Worker thread for synchronous invocations
class synch_foo_generator : public virtual ACE_Task_Base
{
public:
synch_foo_generator (::InterInArgsT::CCM_Sender_Context_ptr context,
Atomic_UShort &nr_of_received_);
virtual int svc (void);
private:
::InterInArgsT::CCM_Sender_Context_var context_;
Atomic_UShort &nr_of_received_;
};
/**
* Component Executor Implementation Class: Sender_exec_i
*/
class Sender_exec_i
: public virtual Sender_Exec,
public virtual ::CORBA::LocalObject
{
public:
Sender_exec_i (void);
virtual ~Sender_exec_i (void);
//@{
/** Supported operations and attributes. */
//@}
//@{
/** Component attributes and port operations. */
//@}
//@{
/** Operations from Components::SessionComponent. */
virtual void set_session_context (::Components::SessionContext_ptr ctx);
virtual void configuration_complete (void);
virtual void ccm_activate (void);
virtual void ccm_passivate (void);
virtual void ccm_remove (void);
//@}
//@{
/** User defined public operations. */
//@}
private:
::InterInArgsT::CCM_Sender_Context_var ciao_context_;
asynch_foo_generator* asynch_foo_gen;
synch_foo_generator* synch_foo_gen;
//@{
/** Component attributes. */
//@}
//@{
/** User defined members. */
Atomic_UShort nr_of_received_;
//@}
//@{
/** User defined private operations. */
//@}
};
class AMI4CCM_MyFooReplyHandler_run_my_foo_i
: public ::InterInArgsT::CCM_AMI4CCM_MyFooReplyHandler,
public virtual ::CORBA::LocalObject
{
public:
AMI4CCM_MyFooReplyHandler_run_my_foo_i (Atomic_UShort &nr_of_received_);
virtual ~AMI4CCM_MyFooReplyHandler_run_my_foo_i (void);
virtual
void foo (::CORBA::Long ami_return_val,
const char * answer);
virtual
void foo_excep (::CCM_AMI::ExceptionHolder_ptr excep_holder);
virtual
void var_ins (const char * answer);
virtual
void var_ins_excep (::CCM_AMI::ExceptionHolder_ptr excep_holder);
virtual
void var_div_ins (const char * answer);
virtual
void var_div_ins_excep (::CCM_AMI::ExceptionHolder_ptr excep_holder);
virtual
void var_div2_ins (const char * answer);
virtual
void var_div2_ins_excep (::CCM_AMI::ExceptionHolder_ptr excep_holder);
virtual
void enum_in (const char * answer);
virtual
void enum_in_excep (::CCM_AMI::ExceptionHolder_ptr excep_holder);
private:
Atomic_UShort &nr_of_received_;
};
extern "C" INTERINARGS_T_SENDER_EXEC_Export ::Components::EnterpriseComponent_ptr
create_InterInArgsT_Sender_Impl (void);
}
#include /**/ "ace/post.h"
#endif /* ifndef */
| 25.910112 | 83 | 0.675629 |
23dfe055afb0126d233448fc702569905f9a5866 | 28,866 | c | C | sdk-6.5.20/libs/sdklt/bcmlrd/chip/bcm56880_a0/dna_4_6_6/bcm56880_a0_dna_4_6_6_lrd_r_ing_outer_tpid_2_map.c | copslock/broadcom_cpri | 8e2767676e26faae270cf485591902a4c50cf0c5 | [
"Spencer-94"
] | null | null | null | sdk-6.5.20/libs/sdklt/bcmlrd/chip/bcm56880_a0/dna_4_6_6/bcm56880_a0_dna_4_6_6_lrd_r_ing_outer_tpid_2_map.c | copslock/broadcom_cpri | 8e2767676e26faae270cf485591902a4c50cf0c5 | [
"Spencer-94"
] | null | null | null | sdk-6.5.20/libs/sdklt/bcmlrd/chip/bcm56880_a0/dna_4_6_6/bcm56880_a0_dna_4_6_6_lrd_r_ing_outer_tpid_2_map.c | copslock/broadcom_cpri | 8e2767676e26faae270cf485591902a4c50cf0c5 | [
"Spencer-94"
] | null | null | null | /*******************************************************************************
*
* DO NOT EDIT THIS FILE!
* This file is auto-generated by fltg from
* INTERNAL/fltg/xgs/npl/bcm56880_a0/dna_4_6_6/bcm56880_a0_dna_4_6_6_R_ING_OUTER_TPID_2.map.ltl for
* bcm56880_a0 variant dna_4_6_6
*
* Tool: $SDK/INTERNAL/fltg/bin/fltg
*
* Edits to this file will be lost when it is regenerated.
*
* This license is set out in https://raw.githubusercontent.com/Broadcom-Network-Switching-Software/OpenBCM/master/Legal/LICENSE file.
*
* Copyright 2007-2020 Broadcom Inc. All rights reserved.
*/
#include <bcmlrd/bcmlrd_internal.h>
#include <bcmlrd/chip/bcmlrd_id.h>
#include <bcmlrd/chip/bcm56880_a0/dna_4_6_6/bcm56880_a0_dna_4_6_6_lrd_field_data.h>
#include <bcmlrd/chip/bcm56880_a0/bcm56880_a0_lrd_ltm_intf.h>
#include <bcmlrd/chip/bcm56880_a0/dna_4_6_6/bcm56880_a0_dna_4_6_6_lrd_ltm_intf.h>
#include <bcmlrd/chip/bcm56880_a0/dna_4_6_6/bcm56880_a0_dna_4_6_6_lrd_xfrm_field_desc.h>
#include <bcmdrd/chip/bcm56880_a0_enum.h>
#include "bcmltd/chip/bcmltd_common_enumpool.h"
#include "../bcm56880_a0_lrd_enumpool.h"
#include "bcm56880_a0_dna_4_6_6_lrd_enumpool.h"
#include <bcmltd/bcmltd_handler.h>
/* R_ING_OUTER_TPID_2 field init */
static const bcmlrd_field_data_t bcm56880_a0_dna_4_6_6_lrd_r_ing_outer_tpid_2_map_field_data_mmd[] = {
{ /* 0 TPID */
.flags = 0,
.min = &bcm56880_a0_dna_4_6_6_lrd_ifd_u16_0x0,
.def = &bcm56880_a0_dna_4_6_6_lrd_ifd_u16_0x0,
.max = &bcm56880_a0_dna_4_6_6_lrd_ifd_u16_0xffff,
.depth = 0,
.width = 16,
.edata = NULL,
},
};
const bcmlrd_map_field_data_t bcm56880_a0_dna_4_6_6_lrd_r_ing_outer_tpid_2_map_field_data = {
.fields = 1,
.field = bcm56880_a0_dna_4_6_6_lrd_r_ing_outer_tpid_2_map_field_data_mmd
};
static const bcmlrd_map_table_attr_t bcm56880_a0_dna_4_6_6_lrd_r_ing_outer_tpid_2t_attr_entry[] = {
{ /* 0 */
.key = BCMLRD_MAP_TABLE_ATTRIBUTE_INTERACTIVE,
.value = FALSE,
},
};
static const bcmlrd_map_attr_t bcm56880_a0_dna_4_6_6_lrd_r_ing_outer_tpid_2t_attr_group = {
.attributes = 1,
.attr = bcm56880_a0_dna_4_6_6_lrd_r_ing_outer_tpid_2t_attr_entry,
};
const bcmltd_field_desc_t
bcm56880_a0_dna_4_6_6_lrd_field_demux_r_ing_outer_tpid_2t_tpidf_0_src_field_desc_s0[18] = {
{
.field_id = BCM56880_A0_DNA_4_6_6_R_ING_OUTER_TPID_2t_TPIDf,
.field_idx = 0,
.minbit = 8,
.maxbit = 15,
.entry_idx = 0,
.reserved = 0
},
{
.field_id = BCM56880_A0_DNA_4_6_6_R_ING_OUTER_TPID_2t_TPIDf,
.field_idx = 0,
.minbit = 0,
.maxbit = 7,
.entry_idx = 0,
.reserved = 0
},
{
.field_id = BCM56880_A0_DNA_4_6_6_R_ING_OUTER_TPID_2t_TPIDf,
.field_idx = 0,
.minbit = 8,
.maxbit = 15,
.entry_idx = 0,
.reserved = 0
},
{
.field_id = BCM56880_A0_DNA_4_6_6_R_ING_OUTER_TPID_2t_TPIDf,
.field_idx = 0,
.minbit = 0,
.maxbit = 7,
.entry_idx = 0,
.reserved = 0
},
{
.field_id = BCM56880_A0_DNA_4_6_6_R_ING_OUTER_TPID_2t_TPIDf,
.field_idx = 0,
.minbit = 8,
.maxbit = 15,
.entry_idx = 0,
.reserved = 0
},
{
.field_id = BCM56880_A0_DNA_4_6_6_R_ING_OUTER_TPID_2t_TPIDf,
.field_idx = 0,
.minbit = 0,
.maxbit = 7,
.entry_idx = 0,
.reserved = 0
},
{
.field_id = BCM56880_A0_DNA_4_6_6_R_ING_OUTER_TPID_2t_TPIDf,
.field_idx = 0,
.minbit = 8,
.maxbit = 15,
.entry_idx = 0,
.reserved = 0
},
{
.field_id = BCM56880_A0_DNA_4_6_6_R_ING_OUTER_TPID_2t_TPIDf,
.field_idx = 0,
.minbit = 0,
.maxbit = 7,
.entry_idx = 0,
.reserved = 0
},
{
.field_id = BCM56880_A0_DNA_4_6_6_R_ING_OUTER_TPID_2t_TPIDf,
.field_idx = 0,
.minbit = 8,
.maxbit = 15,
.entry_idx = 0,
.reserved = 0
},
{
.field_id = BCM56880_A0_DNA_4_6_6_R_ING_OUTER_TPID_2t_TPIDf,
.field_idx = 0,
.minbit = 0,
.maxbit = 7,
.entry_idx = 0,
.reserved = 0
},
{
.field_id = BCM56880_A0_DNA_4_6_6_R_ING_OUTER_TPID_2t_TPIDf,
.field_idx = 0,
.minbit = 8,
.maxbit = 15,
.entry_idx = 0,
.reserved = 0
},
{
.field_id = BCM56880_A0_DNA_4_6_6_R_ING_OUTER_TPID_2t_TPIDf,
.field_idx = 0,
.minbit = 0,
.maxbit = 7,
.entry_idx = 0,
.reserved = 0
},
{
.field_id = BCM56880_A0_DNA_4_6_6_R_ING_OUTER_TPID_2t_TPIDf,
.field_idx = 0,
.minbit = 8,
.maxbit = 15,
.entry_idx = 0,
.reserved = 0
},
{
.field_id = BCM56880_A0_DNA_4_6_6_R_ING_OUTER_TPID_2t_TPIDf,
.field_idx = 0,
.minbit = 0,
.maxbit = 7,
.entry_idx = 0,
.reserved = 0
},
{
.field_id = BCM56880_A0_DNA_4_6_6_R_ING_OUTER_TPID_2t_TPIDf,
.field_idx = 0,
.minbit = 8,
.maxbit = 15,
.entry_idx = 0,
.reserved = 0
},
{
.field_id = BCM56880_A0_DNA_4_6_6_R_ING_OUTER_TPID_2t_TPIDf,
.field_idx = 0,
.minbit = 0,
.maxbit = 7,
.entry_idx = 0,
.reserved = 0
},
{
.field_id = BCM56880_A0_DNA_4_6_6_R_ING_OUTER_TPID_2t_TPIDf,
.field_idx = 0,
.minbit = 8,
.maxbit = 15,
.entry_idx = 0,
.reserved = 0
},
{
.field_id = BCM56880_A0_DNA_4_6_6_R_ING_OUTER_TPID_2t_TPIDf,
.field_idx = 0,
.minbit = 0,
.maxbit = 7,
.entry_idx = 0,
.reserved = 0
},
};
static const bcmltd_field_desc_t
bcm56880_a0_dna_4_6_6_lrd_field_demux_r_ing_outer_tpid_2t_tpidf_0_dst_field_desc[18] = {
{
.field_id = KEYf,
.field_idx = 0,
.minbit = 138,
.maxbit = 145,
.entry_idx = 0,
.reserved = 0,
},
{
.field_id = KEYf,
.field_idx = 0,
.minbit = 130,
.maxbit = 137,
.entry_idx = 0,
.reserved = 0,
},
{
.field_id = KEYf,
.field_idx = 0,
.minbit = 138,
.maxbit = 145,
.entry_idx = 0,
.reserved = 0,
},
{
.field_id = KEYf,
.field_idx = 0,
.minbit = 130,
.maxbit = 137,
.entry_idx = 0,
.reserved = 0,
},
{
.field_id = KEYf,
.field_idx = 0,
.minbit = 138,
.maxbit = 145,
.entry_idx = 0,
.reserved = 0,
},
{
.field_id = KEYf,
.field_idx = 0,
.minbit = 130,
.maxbit = 137,
.entry_idx = 0,
.reserved = 0,
},
{
.field_id = KEYf,
.field_idx = 0,
.minbit = 122,
.maxbit = 129,
.entry_idx = 0,
.reserved = 0,
},
{
.field_id = KEYf,
.field_idx = 0,
.minbit = 114,
.maxbit = 121,
.entry_idx = 0,
.reserved = 0,
},
{
.field_id = KEYf,
.field_idx = 0,
.minbit = 122,
.maxbit = 129,
.entry_idx = 0,
.reserved = 0,
},
{
.field_id = KEYf,
.field_idx = 0,
.minbit = 114,
.maxbit = 121,
.entry_idx = 0,
.reserved = 0,
},
{
.field_id = KEYf,
.field_idx = 0,
.minbit = 122,
.maxbit = 129,
.entry_idx = 0,
.reserved = 0,
},
{
.field_id = KEYf,
.field_idx = 0,
.minbit = 114,
.maxbit = 121,
.entry_idx = 0,
.reserved = 0,
},
{
.field_id = KEYf,
.field_idx = 0,
.minbit = 186,
.maxbit = 193,
.entry_idx = 0,
.reserved = 0,
},
{
.field_id = KEYf,
.field_idx = 0,
.minbit = 178,
.maxbit = 185,
.entry_idx = 0,
.reserved = 0,
},
{
.field_id = KEYf,
.field_idx = 0,
.minbit = 186,
.maxbit = 193,
.entry_idx = 0,
.reserved = 0,
},
{
.field_id = KEYf,
.field_idx = 0,
.minbit = 178,
.maxbit = 185,
.entry_idx = 0,
.reserved = 0,
},
{
.field_id = KEYf,
.field_idx = 0,
.minbit = 186,
.maxbit = 193,
.entry_idx = 0,
.reserved = 0,
},
{
.field_id = KEYf,
.field_idx = 0,
.minbit = 178,
.maxbit = 185,
.entry_idx = 0,
.reserved = 0,
},
};
const bcmltd_field_desc_t
bcm56880_a0_dna_4_6_6_lrd_field_demux_r_ing_outer_tpid_2t_tpidf_1_src_field_desc_s1[18] = {
{
.field_id = BCM56880_A0_DNA_4_6_6_R_ING_OUTER_TPID_2t_TPIDf,
.field_idx = 0,
.minbit = 8,
.maxbit = 15,
.entry_idx = 0,
.reserved = 0
},
{
.field_id = BCM56880_A0_DNA_4_6_6_R_ING_OUTER_TPID_2t_TPIDf,
.field_idx = 0,
.minbit = 0,
.maxbit = 7,
.entry_idx = 0,
.reserved = 0
},
{
.field_id = BCM56880_A0_DNA_4_6_6_R_ING_OUTER_TPID_2t_TPIDf,
.field_idx = 0,
.minbit = 8,
.maxbit = 15,
.entry_idx = 0,
.reserved = 0
},
{
.field_id = BCM56880_A0_DNA_4_6_6_R_ING_OUTER_TPID_2t_TPIDf,
.field_idx = 0,
.minbit = 0,
.maxbit = 7,
.entry_idx = 0,
.reserved = 0
},
{
.field_id = BCM56880_A0_DNA_4_6_6_R_ING_OUTER_TPID_2t_TPIDf,
.field_idx = 0,
.minbit = 8,
.maxbit = 15,
.entry_idx = 0,
.reserved = 0
},
{
.field_id = BCM56880_A0_DNA_4_6_6_R_ING_OUTER_TPID_2t_TPIDf,
.field_idx = 0,
.minbit = 0,
.maxbit = 7,
.entry_idx = 0,
.reserved = 0
},
{
.field_id = BCM56880_A0_DNA_4_6_6_R_ING_OUTER_TPID_2t_TPIDf,
.field_idx = 0,
.minbit = 8,
.maxbit = 15,
.entry_idx = 0,
.reserved = 0
},
{
.field_id = BCM56880_A0_DNA_4_6_6_R_ING_OUTER_TPID_2t_TPIDf,
.field_idx = 0,
.minbit = 0,
.maxbit = 7,
.entry_idx = 0,
.reserved = 0
},
{
.field_id = BCM56880_A0_DNA_4_6_6_R_ING_OUTER_TPID_2t_TPIDf,
.field_idx = 0,
.minbit = 8,
.maxbit = 15,
.entry_idx = 0,
.reserved = 0
},
{
.field_id = BCM56880_A0_DNA_4_6_6_R_ING_OUTER_TPID_2t_TPIDf,
.field_idx = 0,
.minbit = 0,
.maxbit = 7,
.entry_idx = 0,
.reserved = 0
},
{
.field_id = BCM56880_A0_DNA_4_6_6_R_ING_OUTER_TPID_2t_TPIDf,
.field_idx = 0,
.minbit = 8,
.maxbit = 15,
.entry_idx = 0,
.reserved = 0
},
{
.field_id = BCM56880_A0_DNA_4_6_6_R_ING_OUTER_TPID_2t_TPIDf,
.field_idx = 0,
.minbit = 0,
.maxbit = 7,
.entry_idx = 0,
.reserved = 0
},
{
.field_id = BCM56880_A0_DNA_4_6_6_R_ING_OUTER_TPID_2t_TPIDf,
.field_idx = 0,
.minbit = 8,
.maxbit = 15,
.entry_idx = 0,
.reserved = 0
},
{
.field_id = BCM56880_A0_DNA_4_6_6_R_ING_OUTER_TPID_2t_TPIDf,
.field_idx = 0,
.minbit = 0,
.maxbit = 7,
.entry_idx = 0,
.reserved = 0
},
{
.field_id = BCM56880_A0_DNA_4_6_6_R_ING_OUTER_TPID_2t_TPIDf,
.field_idx = 0,
.minbit = 8,
.maxbit = 15,
.entry_idx = 0,
.reserved = 0
},
{
.field_id = BCM56880_A0_DNA_4_6_6_R_ING_OUTER_TPID_2t_TPIDf,
.field_idx = 0,
.minbit = 0,
.maxbit = 7,
.entry_idx = 0,
.reserved = 0
},
{
.field_id = BCM56880_A0_DNA_4_6_6_R_ING_OUTER_TPID_2t_TPIDf,
.field_idx = 0,
.minbit = 8,
.maxbit = 15,
.entry_idx = 0,
.reserved = 0
},
{
.field_id = BCM56880_A0_DNA_4_6_6_R_ING_OUTER_TPID_2t_TPIDf,
.field_idx = 0,
.minbit = 0,
.maxbit = 7,
.entry_idx = 0,
.reserved = 0
},
};
static const bcmltd_field_desc_t
bcm56880_a0_dna_4_6_6_lrd_field_demux_r_ing_outer_tpid_2t_tpidf_1_dst_field_desc[18] = {
{
.field_id = KEYf,
.field_idx = 0,
.minbit = 138,
.maxbit = 145,
.entry_idx = 0,
.reserved = 0,
},
{
.field_id = KEYf,
.field_idx = 0,
.minbit = 130,
.maxbit = 137,
.entry_idx = 0,
.reserved = 0,
},
{
.field_id = KEYf,
.field_idx = 0,
.minbit = 138,
.maxbit = 145,
.entry_idx = 0,
.reserved = 0,
},
{
.field_id = KEYf,
.field_idx = 0,
.minbit = 130,
.maxbit = 137,
.entry_idx = 0,
.reserved = 0,
},
{
.field_id = KEYf,
.field_idx = 0,
.minbit = 138,
.maxbit = 145,
.entry_idx = 0,
.reserved = 0,
},
{
.field_id = KEYf,
.field_idx = 0,
.minbit = 130,
.maxbit = 137,
.entry_idx = 0,
.reserved = 0,
},
{
.field_id = KEYf,
.field_idx = 0,
.minbit = 122,
.maxbit = 129,
.entry_idx = 0,
.reserved = 0,
},
{
.field_id = KEYf,
.field_idx = 0,
.minbit = 114,
.maxbit = 121,
.entry_idx = 0,
.reserved = 0,
},
{
.field_id = KEYf,
.field_idx = 0,
.minbit = 122,
.maxbit = 129,
.entry_idx = 0,
.reserved = 0,
},
{
.field_id = KEYf,
.field_idx = 0,
.minbit = 114,
.maxbit = 121,
.entry_idx = 0,
.reserved = 0,
},
{
.field_id = KEYf,
.field_idx = 0,
.minbit = 122,
.maxbit = 129,
.entry_idx = 0,
.reserved = 0,
},
{
.field_id = KEYf,
.field_idx = 0,
.minbit = 114,
.maxbit = 121,
.entry_idx = 0,
.reserved = 0,
},
{
.field_id = KEYf,
.field_idx = 0,
.minbit = 186,
.maxbit = 193,
.entry_idx = 0,
.reserved = 0,
},
{
.field_id = KEYf,
.field_idx = 0,
.minbit = 178,
.maxbit = 185,
.entry_idx = 0,
.reserved = 0,
},
{
.field_id = KEYf,
.field_idx = 0,
.minbit = 186,
.maxbit = 193,
.entry_idx = 0,
.reserved = 0,
},
{
.field_id = KEYf,
.field_idx = 0,
.minbit = 178,
.maxbit = 185,
.entry_idx = 0,
.reserved = 0,
},
{
.field_id = KEYf,
.field_idx = 0,
.minbit = 186,
.maxbit = 193,
.entry_idx = 0,
.reserved = 0,
},
{
.field_id = KEYf,
.field_idx = 0,
.minbit = 178,
.maxbit = 185,
.entry_idx = 0,
.reserved = 0,
},
};
const bcmlrd_field_xfrm_desc_t
bcm56880_a0_dna_4_6_6_lta_bcmltx_field_demux_r_ing_outer_tpid_2t_tpidf_0_xfrm_handler_fwd_s0_d0_desc = {
.handler_id = BCMLTD_TRANSFORM_BCM56880_A0_DNA_4_6_6_LTA_BCMLTX_FIELD_DEMUX_R_ING_OUTER_TPID_2T_TPIDF_0_XFRM_HANDLER_FWD_S0_D0_ID,
.src_fields = 18,
.src = bcm56880_a0_dna_4_6_6_lrd_field_demux_r_ing_outer_tpid_2t_tpidf_0_src_field_desc_s0,
.dst_fields = 18,
.dst = bcm56880_a0_dna_4_6_6_lrd_field_demux_r_ing_outer_tpid_2t_tpidf_0_dst_field_desc,
};
const bcmlrd_field_xfrm_desc_t
bcm56880_a0_dna_4_6_6_lta_bcmltx_field_demux_r_ing_outer_tpid_2t_tpidf_0_xfrm_handler_rev_s0_d0_desc = {
.handler_id = BCMLTD_TRANSFORM_BCM56880_A0_DNA_4_6_6_LTA_BCMLTX_FIELD_DEMUX_R_ING_OUTER_TPID_2T_TPIDF_0_XFRM_HANDLER_REV_S0_D0_ID,
.src_fields = 18,
.src = bcm56880_a0_dna_4_6_6_lrd_field_demux_r_ing_outer_tpid_2t_tpidf_0_dst_field_desc,
.dst_fields = 18,
.dst = bcm56880_a0_dna_4_6_6_lrd_field_demux_r_ing_outer_tpid_2t_tpidf_0_src_field_desc_s0,
};
const bcmlrd_field_xfrm_desc_t
bcm56880_a0_dna_4_6_6_lta_bcmltx_field_demux_r_ing_outer_tpid_2t_tpidf_1_xfrm_handler_fwd_s0_d0_desc = {
.handler_id = BCMLTD_TRANSFORM_BCM56880_A0_DNA_4_6_6_LTA_BCMLTX_FIELD_DEMUX_R_ING_OUTER_TPID_2T_TPIDF_1_XFRM_HANDLER_FWD_S0_D0_ID,
.src_fields = 18,
.src = bcm56880_a0_dna_4_6_6_lrd_field_demux_r_ing_outer_tpid_2t_tpidf_1_src_field_desc_s1,
.dst_fields = 18,
.dst = bcm56880_a0_dna_4_6_6_lrd_field_demux_r_ing_outer_tpid_2t_tpidf_1_dst_field_desc,
};
static const bcmlrd_map_entry_t bcm56880_a0_dna_4_6_6_lrd_r_ing_outer_tpid_2t_flex_hve_iparser1_scc_profile2_6_map_entry[] = {
{ /* 0 */
.entry_type = BCMLRD_MAP_ENTRY_MAPPED_VALUE,
.desc = {
.field_id = DATAf,
.field_idx = 0,
.minbit = 32,
.maxbit = 47,
.entry_idx = 0,
.reserved = 0
},
.u = {
.mapped = {
.src = {
.field_id = BCM56880_A0_DNA_4_6_6_R_ING_OUTER_TPID_2t_TPIDf,
.field_idx = 0,
.minbit = 0,
.maxbit = 15,
.entry_idx = 0,
.reserved = 0
}
}
},
},
{ /* 1 */
.entry_type = BCMLRD_MAP_ENTRY_FIXED_KEY,
.desc = {
.field_id = BCMLRD_FIELD_INDEX,
.field_idx = 0,
.minbit = 0,
.maxbit = 1,
.entry_idx = 0,
.reserved = 0
},
.u = {
.fixed = {
.value = 0,
}
},
},
};
static const bcmlrd_map_entry_t bcm56880_a0_dna_4_6_6_lrd_r_ing_outer_tpid_2t_iparser1_hme_stage0_tcam_only_map_entry[] = {
{ /* 0 */
.entry_type = BCMLRD_MAP_ENTRY_FIXED_KEY,
.desc = {
.field_id = BCMLRD_FIELD_INDEX,
.field_idx = 0,
.minbit = 0,
.maxbit = 5,
.entry_idx = 0,
.reserved = 0
},
.u = {
.fixed = {
.value = 18,
}
},
},
{ /* 1 */
.entry_type = BCMLRD_MAP_ENTRY_FIXED_KEY,
.desc = {
.field_id = BCMLRD_FIELD_INDEX,
.field_idx = 0,
.minbit = 0,
.maxbit = 5,
.entry_idx = 1,
.reserved = 0
},
.u = {
.fixed = {
.value = 19,
}
},
},
{ /* 2 */
.entry_type = BCMLRD_MAP_ENTRY_FIXED_KEY,
.desc = {
.field_id = BCMLRD_FIELD_INDEX,
.field_idx = 0,
.minbit = 0,
.maxbit = 5,
.entry_idx = 2,
.reserved = 0
},
.u = {
.fixed = {
.value = 20,
}
},
},
{ /* 3 */
.entry_type = BCMLRD_MAP_ENTRY_FIXED_KEY,
.desc = {
.field_id = BCMLRD_FIELD_INDEX,
.field_idx = 0,
.minbit = 0,
.maxbit = 5,
.entry_idx = 3,
.reserved = 0
},
.u = {
.fixed = {
.value = 36,
}
},
},
{ /* 4 */
.entry_type = BCMLRD_MAP_ENTRY_FIXED_KEY,
.desc = {
.field_id = BCMLRD_FIELD_INDEX,
.field_idx = 0,
.minbit = 0,
.maxbit = 5,
.entry_idx = 4,
.reserved = 0
},
.u = {
.fixed = {
.value = 37,
}
},
},
{ /* 5 */
.entry_type = BCMLRD_MAP_ENTRY_FIXED_KEY,
.desc = {
.field_id = BCMLRD_FIELD_INDEX,
.field_idx = 0,
.minbit = 0,
.maxbit = 5,
.entry_idx = 5,
.reserved = 0
},
.u = {
.fixed = {
.value = 38,
}
},
},
{ /* 6 */
.entry_type = BCMLRD_MAP_ENTRY_FIXED_KEY,
.desc = {
.field_id = BCMLRD_FIELD_INDEX,
.field_idx = 0,
.minbit = 0,
.maxbit = 5,
.entry_idx = 6,
.reserved = 0
},
.u = {
.fixed = {
.value = 6,
}
},
},
{ /* 7 */
.entry_type = BCMLRD_MAP_ENTRY_FIXED_KEY,
.desc = {
.field_id = BCMLRD_FIELD_INDEX,
.field_idx = 0,
.minbit = 0,
.maxbit = 5,
.entry_idx = 7,
.reserved = 0
},
.u = {
.fixed = {
.value = 7,
}
},
},
{ /* 8 */
.entry_type = BCMLRD_MAP_ENTRY_FIXED_KEY,
.desc = {
.field_id = BCMLRD_FIELD_INDEX,
.field_idx = 0,
.minbit = 0,
.maxbit = 5,
.entry_idx = 8,
.reserved = 0
},
.u = {
.fixed = {
.value = 8,
}
},
},
{ /* 9 */
.entry_type = BCMLRD_MAP_ENTRY_FWD_VALUE_FIELD_XFRM_HANDLER,
.desc = {
.field_id = 0,
.field_idx = 0,
.minbit = 0,
.maxbit = 0,
.entry_idx = 0,
.reserved = 0
},
.u = {
.xfrm = {
/* handler: bcm56880_a0_dna_4_6_6_lta_bcmltx_field_demux_r_ing_outer_tpid_2t_tpidf_0_xfrm_handler_fwd_s0_d0 */
.desc = &bcm56880_a0_dna_4_6_6_lta_bcmltx_field_demux_r_ing_outer_tpid_2t_tpidf_0_xfrm_handler_fwd_s0_d0_desc,
},
},
},
{ /* 10 */
.entry_type = BCMLRD_MAP_ENTRY_REV_VALUE_FIELD_XFRM_HANDLER,
.desc = {
.field_id = 0,
.field_idx = 0,
.minbit = 0,
.maxbit = 0,
.entry_idx = 0,
.reserved = 0
},
.u = {
.xfrm = {
/* handler: bcm56880_a0_dna_4_6_6_lta_bcmltx_field_demux_r_ing_outer_tpid_2t_tpidf_0_xfrm_handler_rev_s0_d0 */
.desc = &bcm56880_a0_dna_4_6_6_lta_bcmltx_field_demux_r_ing_outer_tpid_2t_tpidf_0_xfrm_handler_rev_s0_d0_desc,
},
},
},
};
static const bcmlrd_map_entry_t bcm56880_a0_dna_4_6_6_lrd_r_ing_outer_tpid_2t_iparser2_hme_stage0_tcam_only_map_entry[] = {
{ /* 0 */
.entry_type = BCMLRD_MAP_ENTRY_FIXED_KEY,
.desc = {
.field_id = BCMLRD_FIELD_INDEX,
.field_idx = 0,
.minbit = 0,
.maxbit = 5,
.entry_idx = 0,
.reserved = 0
},
.u = {
.fixed = {
.value = 18,
}
},
},
{ /* 1 */
.entry_type = BCMLRD_MAP_ENTRY_FIXED_KEY,
.desc = {
.field_id = BCMLRD_FIELD_INDEX,
.field_idx = 0,
.minbit = 0,
.maxbit = 5,
.entry_idx = 1,
.reserved = 0
},
.u = {
.fixed = {
.value = 19,
}
},
},
{ /* 2 */
.entry_type = BCMLRD_MAP_ENTRY_FIXED_KEY,
.desc = {
.field_id = BCMLRD_FIELD_INDEX,
.field_idx = 0,
.minbit = 0,
.maxbit = 5,
.entry_idx = 2,
.reserved = 0
},
.u = {
.fixed = {
.value = 20,
}
},
},
{ /* 3 */
.entry_type = BCMLRD_MAP_ENTRY_FIXED_KEY,
.desc = {
.field_id = BCMLRD_FIELD_INDEX,
.field_idx = 0,
.minbit = 0,
.maxbit = 5,
.entry_idx = 3,
.reserved = 0
},
.u = {
.fixed = {
.value = 36,
}
},
},
{ /* 4 */
.entry_type = BCMLRD_MAP_ENTRY_FIXED_KEY,
.desc = {
.field_id = BCMLRD_FIELD_INDEX,
.field_idx = 0,
.minbit = 0,
.maxbit = 5,
.entry_idx = 4,
.reserved = 0
},
.u = {
.fixed = {
.value = 37,
}
},
},
{ /* 5 */
.entry_type = BCMLRD_MAP_ENTRY_FIXED_KEY,
.desc = {
.field_id = BCMLRD_FIELD_INDEX,
.field_idx = 0,
.minbit = 0,
.maxbit = 5,
.entry_idx = 5,
.reserved = 0
},
.u = {
.fixed = {
.value = 38,
}
},
},
{ /* 6 */
.entry_type = BCMLRD_MAP_ENTRY_FIXED_KEY,
.desc = {
.field_id = BCMLRD_FIELD_INDEX,
.field_idx = 0,
.minbit = 0,
.maxbit = 5,
.entry_idx = 6,
.reserved = 0
},
.u = {
.fixed = {
.value = 6,
}
},
},
{ /* 7 */
.entry_type = BCMLRD_MAP_ENTRY_FIXED_KEY,
.desc = {
.field_id = BCMLRD_FIELD_INDEX,
.field_idx = 0,
.minbit = 0,
.maxbit = 5,
.entry_idx = 7,
.reserved = 0
},
.u = {
.fixed = {
.value = 7,
}
},
},
{ /* 8 */
.entry_type = BCMLRD_MAP_ENTRY_FIXED_KEY,
.desc = {
.field_id = BCMLRD_FIELD_INDEX,
.field_idx = 0,
.minbit = 0,
.maxbit = 5,
.entry_idx = 8,
.reserved = 0
},
.u = {
.fixed = {
.value = 8,
}
},
},
{ /* 9 */
.entry_type = BCMLRD_MAP_ENTRY_FWD_VALUE_FIELD_XFRM_HANDLER,
.desc = {
.field_id = 0,
.field_idx = 0,
.minbit = 0,
.maxbit = 0,
.entry_idx = 0,
.reserved = 0
},
.u = {
.xfrm = {
/* handler: bcm56880_a0_dna_4_6_6_lta_bcmltx_field_demux_r_ing_outer_tpid_2t_tpidf_1_xfrm_handler_fwd_s0_d0 */
.desc = &bcm56880_a0_dna_4_6_6_lta_bcmltx_field_demux_r_ing_outer_tpid_2t_tpidf_1_xfrm_handler_fwd_s0_d0_desc,
},
},
},
};
static const bcmlrd_map_group_t bcm56880_a0_dna_4_6_6_lrd_r_ing_outer_tpid_2_map_group[] = {
{
.dest = {
.kind = BCMLRD_MAP_PHYSICAL,
.id = FLEX_HVE_IPARSER1_SCC_PROFILE2_6m,
},
.entries = 2,
.entry = bcm56880_a0_dna_4_6_6_lrd_r_ing_outer_tpid_2t_flex_hve_iparser1_scc_profile2_6_map_entry
},
{
.dest = {
.kind = BCMLRD_MAP_PHYSICAL,
.id = IPARSER1_HME_STAGE0_TCAM_ONLYm,
},
.entries = 11,
.entry = bcm56880_a0_dna_4_6_6_lrd_r_ing_outer_tpid_2t_iparser1_hme_stage0_tcam_only_map_entry
},
{
.dest = {
.kind = BCMLRD_MAP_PHYSICAL,
.id = IPARSER2_HME_STAGE0_TCAM_ONLYm,
},
.entries = 10,
.entry = bcm56880_a0_dna_4_6_6_lrd_r_ing_outer_tpid_2t_iparser2_hme_stage0_tcam_only_map_entry
},
};
const bcmlrd_map_t bcm56880_a0_dna_4_6_6_lrd_r_ing_outer_tpid_2_map = {
.src_id = BCM56880_A0_DNA_4_6_6_R_ING_OUTER_TPID_2t,
.field_data = &bcm56880_a0_dna_4_6_6_lrd_r_ing_outer_tpid_2_map_field_data,
.groups = 3,
.group = bcm56880_a0_dna_4_6_6_lrd_r_ing_outer_tpid_2_map_group,
.table_attr = &bcm56880_a0_dna_4_6_6_lrd_r_ing_outer_tpid_2t_attr_group,
.entry_ops = BCMLRD_MAP_TABLE_ENTRY_OPERATION_LOOKUP | BCMLRD_MAP_TABLE_ENTRY_OPERATION_TRAVERSE | BCMLRD_MAP_TABLE_ENTRY_OPERATION_INSERT | BCMLRD_MAP_TABLE_ENTRY_OPERATION_UPDATE | BCMLRD_MAP_TABLE_ENTRY_OPERATION_DELETE
};
| 26.361644 | 226 | 0.485831 |
1812baec48aaf68bea8dab015c1d7e7cce111936 | 4,012 | h | C | Grafo/Camino al cole/GrafoValorado.h | Yule1223/Algorithmic-Techniques-in-Software-Engineering | 602e3d823cfc86d68a5b3f9435faef4e5c7dc788 | [
"MIT"
] | null | null | null | Grafo/Camino al cole/GrafoValorado.h | Yule1223/Algorithmic-Techniques-in-Software-Engineering | 602e3d823cfc86d68a5b3f9435faef4e5c7dc788 | [
"MIT"
] | null | null | null | Grafo/Camino al cole/GrafoValorado.h | Yule1223/Algorithmic-Techniques-in-Software-Engineering | 602e3d823cfc86d68a5b3f9435faef4e5c7dc788 | [
"MIT"
] | null | null | null | //
// GrafoValorado.h
//
// Implementación de grafos no dirigidos valorados
//
// Facultad de Informática
// Universidad Complutense de Madrid
//
// Copyright (c) 2020 Alberto Verdejo
//
#ifndef GRAFOVALORADO_H_
#define GRAFOVALORADO_H_
#include <iostream>
#include <memory>
#include <stdexcept>
#include <vector>
template <typename Valor>
class Arista {
public:
Arista() : pimpl(nullptr) {}
Arista(int v, int w, Valor valor) : pimpl(std::make_shared<Arista_impl>(v, w, valor)) {}
int uno() const { return pimpl->v; }
int otro(int u) const { return (u == pimpl->v) ? pimpl->w : pimpl->v; }
Valor valor() const { return pimpl->valor; }
void print(std::ostream & o = std::cout) const {
o << "(" << pimpl->v << ", " << pimpl->w << ", " << pimpl->valor << ")";
}
bool operator<(Arista<Valor> const& b) const {
return valor() < b.valor();
}
bool operator>(Arista<Valor> const& b) const {
return b.valor() < valor();
}
private:
struct Arista_impl {
int v, w;
Valor valor;
Arista_impl(int v, int w, Valor valor) : v(v), w(w), valor(valor) {}
};
std::shared_ptr<Arista_impl> pimpl; // puntero a la arista "de verdad"
};
template <typename Valor>
inline std::ostream& operator<<(std::ostream & o, Arista<Valor> const& ar) {
ar.print(o);
return o;
}
template <typename Valor>
using AdysVal = std::vector<Arista<Valor>>; // lista de adyacentes a un vértice
template <typename Valor>
class GrafoValorado {
public:
/**
* Crea un grafo valorado con V vértices, sin aristas.
*/
GrafoValorado(int V) : _V(V), _A(0), _ady(_V) { }
/**
* Crea un grafo valorado a partir de los datos en el flujo de entrada (si puede).
* primer es el índice del primer vértice del grafo en el entrada.
*/
GrafoValorado(std::istream & flujo, int primer = 0) : _A(0) {
flujo >> _V;
if (!flujo) return;
_ady.resize(_V);
int E, v, w;
Valor c;
flujo >> E;
while (E--) {
flujo >> v >> w >> c;
ponArista({v - primer, w - primer, c});
}
}
/**
* Devuelve el número de vértices del grafo.
*/
int V() const { return _V; }
/**
* Devuelve el número de aristas del grafo.
*/
int A() const { return _A; }
/**
* Añade una arista al grafo.
* @throws invalid_argument si algún vértice no existe
*/
void ponArista(Arista<Valor> arista) {
int v = arista.uno(), w = arista.otro(v);
if (v < 0 || v >= _V || w < 0 || w >= _V)
throw std::invalid_argument("Vertice inexistente");
++_A;
_ady[v].push_back(arista);
_ady[w].push_back(arista);
}
/**
* Devuelve la lista de adyacentes de v.
* @throws invalid_argument si v no existe
*/
AdysVal<Valor> const& ady(int v) const {
if (v < 0 || v >= _V)
throw std::invalid_argument("Vertice inexistente");
return _ady[v];
}
/**
* Devuelve las aristas del grafo.
*/
std::vector<Arista<Valor>> aristas() const {
std::vector<Arista<Valor>> ars;
for (int v = 0; v < V(); ++v)
for (auto arista : ady(v))
if (v < arista.otro(v))
ars.push_back(arista);
return ars;
}
/**
* Muestra el grafo en el stream de salida o
*/
void print(std::ostream& o = std::cout) const {
o << _V << " vértices, " << _A << " aristas\n";
for (auto v = 0; v < _V; ++v) {
o << v << ": ";
for (auto const& w : _ady[v]) {
o << w << " ";
}
o << "\n";
}
}
private:
int _V; // número de vértices
int _A; // número de aristas
std::vector<AdysVal<Valor>> _ady; // vector de listas de adyacentes
};
/**
* Para mostrar grafos por la salida estándar.
*/
template <typename Valor>
inline std::ostream& operator<<(std::ostream & o, GrafoValorado<Valor> const& g) {
g.print(o);
return o;
}
#endif /* GRAFOVALORADO_H_ */
| 24.463415 | 91 | 0.562562 |
af6db1e5816e83c9559121760b69465983d45616 | 705 | h | C | XVim2/XcodeHeader/DVTKit/DVTGradientImageButton.h | jsuo/XVim2 | f0126ed41be3d04f237e81c240c5f1f36443fcbc | [
"MIT"
] | null | null | null | XVim2/XcodeHeader/DVTKit/DVTGradientImageButton.h | jsuo/XVim2 | f0126ed41be3d04f237e81c240c5f1f36443fcbc | [
"MIT"
] | null | null | null | XVim2/XcodeHeader/DVTKit/DVTGradientImageButton.h | jsuo/XVim2 | f0126ed41be3d04f237e81c240c5f1f36443fcbc | [
"MIT"
] | null | null | null | //
// Generated by class-dump 3.5 (64 bit) (Debug version compiled Mar 30 2018 09:30:25).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by Steve Nygard.
//
#import <AppKit/NSButton.h>
#import <DVTKit/DVTGradientStyleButton-Protocol.h>
@class NSString;
@interface DVTGradientImageButton : NSButton <DVTGradientStyleButton>
{
}
+ (Class)cellClass;
- (BOOL)allowsVibrancy;
@property unsigned long long borderSides;
@property int gradientStyle;
- (id)_cell;
// Remaining properties
@property(readonly, copy) NSString *debugDescription;
@property(readonly, copy) NSString *description;
@property(readonly) unsigned long long hash;
@property(readonly) Class superclass;
@end
| 22.741935 | 90 | 0.748936 |
49ec257e70cb1ca2b93b97d7a9a4496a7aaef651 | 1,512 | c | C | eglibc-2.15/sysdeps/unix/sysv/linux/prof-freq.c | huhong789/shortcut | bce8a64c4d99b3dca72ffa0a04c9f3485cbab13a | [
"BSD-2-Clause"
] | 47 | 2015-03-10T23:21:52.000Z | 2022-02-17T01:04:14.000Z | eglibc-2.15/sysdeps/unix/sysv/linux/prof-freq.c | shortcut-sosp19/shortcut | f0ff3d9170dbc6de38e0d8c200db056aa26b9c48 | [
"BSD-2-Clause"
] | 1 | 2020-06-30T18:01:37.000Z | 2020-06-30T18:01:37.000Z | eglibc-2.15/sysdeps/unix/sysv/linux/prof-freq.c | shortcut-sosp19/shortcut | f0ff3d9170dbc6de38e0d8c200db056aa26b9c48 | [
"BSD-2-Clause"
] | 19 | 2015-02-25T19:50:05.000Z | 2021-10-05T14:35:54.000Z | /* Determine realtime clock frequency.
Copyright (C) 2003, 2004, 2006 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, write to the Free
Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
02111-1307 USA. */
#include <sys/time.h>
#include <libc-internal.h>
#include <kernel-features.h>
#include <ldsodefs.h>
int
__profile_frequency (void)
{
#ifdef __ASSUME_AT_CLKTCK
return GLRO(dl_clktck);
#else
if (GLRO(dl_clktck) != 0)
return GLRO(dl_clktck);
struct itimerval tim;
tim.it_interval.tv_sec = 0;
tim.it_interval.tv_usec = 1;
tim.it_value.tv_sec = 0;
tim.it_value.tv_usec = 0;
__setitimer (ITIMER_REAL, &tim, 0);
__setitimer (ITIMER_REAL, 0, &tim);
if (tim.it_interval.tv_usec < 2)
return 0;
return 1000000 / tim.it_interval.tv_usec;
#endif
}
libc_hidden_def (__profile_frequency)
| 29.076923 | 71 | 0.732804 |
0ad00325e494bb232208bd87ce2156cf3cd86019 | 445 | h | C | LKProject/LKProject/Class/System/Base/BaseViewController/UIViewController+BackButtonHandler.h | Yuri-Zhang/ProjectStructure | de7178ffbc328ba96bd603a339bbe8601fee8568 | [
"MIT"
] | 3 | 2017-03-17T10:08:47.000Z | 2020-03-06T06:12:11.000Z | MBBaseProject/MBBaseProject/Class/Extend/Category/UIKit/UIViewController/UIViewController+BackButtonHandler.h | MarioBiuuuu/MBProject | 7f7ff1c3f3f2718de74ed55b2d419ae5b5d4a6fa | [
"MIT"
] | null | null | null | MBBaseProject/MBBaseProject/Class/Extend/Category/UIKit/UIViewController/UIViewController+BackButtonHandler.h | MarioBiuuuu/MBProject | 7f7ff1c3f3f2718de74ed55b2d419ae5b5d4a6fa | [
"MIT"
] | null | null | null | //
// UIViewController+BackButtonHandler.h
// Dangdang
//
// Created by Yuri on 16/6/27.
// Copyright © 2016年 Eric MiAo. All rights reserved.
//
#import <UIKit/UIKit.h>
@protocol BackButtonHandlerProtocol <NSObject>
@optional
// Override this method in UIViewController derived class to handle 'Back' button click
-(BOOL)navigationShouldPopOnBackButton;
@end
@interface UIViewController (BackButtonHandler) <BackButtonHandlerProtocol>
@end
| 26.176471 | 87 | 0.777528 |
0ae4886cd628660dfe460cd94de8306d977d30d2 | 7,234 | h | C | FWCore/MessageLogger/interface/ELseverityLevel.h | NTrevisani/cmssw | a212a27526f34eb9507cf8b875c93896e6544781 | [
"Apache-2.0"
] | 3 | 2018-08-24T19:10:26.000Z | 2019-02-19T11:45:32.000Z | FWCore/MessageLogger/interface/ELseverityLevel.h | NTrevisani/cmssw | a212a27526f34eb9507cf8b875c93896e6544781 | [
"Apache-2.0"
] | 26 | 2018-10-30T12:47:58.000Z | 2022-03-29T08:39:00.000Z | FWCore/MessageLogger/interface/ELseverityLevel.h | NTrevisani/cmssw | a212a27526f34eb9507cf8b875c93896e6544781 | [
"Apache-2.0"
] | 5 | 2018-08-21T16:37:52.000Z | 2020-01-09T13:33:17.000Z | #ifndef MessageLogger_ELseverityLevel_h
#define MessageLogger_ELseverityLevel_h
// ----------------------------------------------------------------------
//
// ELseverityLevel.h - declare objects that encode a message's urgency
//
// Both frameworker and user will often pass one of the
// instantiated severity levels to logger methods.
//
// The only other methods of ELseverityLevel a frameworker
// might use is to check the relative level of two severities
// using operator< or the like.
//
// 30-Jun-1998 mf Created file.
// 26-Aug-1998 WEB Made ELseverityLevel object less weighty.
// 16-Jun-1999 mf Added constructor from string.
// 23-Jun-1999 mf Additional ELsev_noValueAssigned to allow constructor
// from string to give ELunspecified when not found, while
// still allowing finding zero severity.
// 23-Jun-1999 mf Corrections for subtleties in initialization of
// global symbols:
// Added ELsevLevGlobals array
// Changed extern consts of SLseverityLevels into
// const ELseverityLevel & 's
// Inserted class ELinitializeGlobalSeverityObjects
// in place of the
// initializeGlobalSeverityObjects() function.
// Changed globalSeverityObjectsGuarantor to an
// ELinitializeGlobalSeverityObjects instance.
// 30-Jun-1999 mf Modifications to eliminate problems with order of
// globals initializations:
// translate(), getInputStr(), getVarName()
// 12-Jun-2000 web Final fix to global static initialization problem
// 14-Jun-2000 web Declare classes before granting friendship.
// 27-Jun-2000 web Fix order-of-static-destruction problem
//
// ----------------------------------------------------------------------
#ifndef ELSTRING_H
#include "FWCore/MessageLogger/interface/ELstring.h"
#endif
namespace edm {
// ----------------------------------------------------------------------
// Forward declaration:
// ----------------------------------------------------------------------
class ELseverityLevel;
#ifndef __ROOTCLING__
// ----------------------------------------------------------------------
// Synonym for type of ELseverityLevel-generating function:
// ----------------------------------------------------------------------
typedef ELseverityLevel const ELslGen();
// ----------------------------------------------------------------------
// ELslProxy class template:
// ----------------------------------------------------------------------
template <ELslGen ELgen>
struct ELslProxy {
// --- birth/death:
//
ELslProxy();
~ELslProxy();
// --- copying:
//
ELslProxy(ELslProxy const&);
ELslProxy const& operator=(ELslProxy const&);
// --- conversion::
//
operator ELseverityLevel const() const;
// --- forwarding:
//
int getLevel() const;
const ELstring getSymbol() const;
const ELstring getName() const;
const ELstring getInputStr() const;
const ELstring getVarName() const;
}; // ELslProxy<ELslGen>
#endif
// ----------------------------------------------------------------------
// ----------------------------------------------------------------------
// ELseverityLevel:
// ----------------------------------------------------------------------
class ELseverityLevel {
public:
// --- One ELseverityLevel is globally instantiated (see below)
// --- for each of the following levels:
//
enum ELsev_ {
ELsev_noValueAssigned = 0 // default returned by map when not found
,
ELsev_zeroSeverity // threshold use only
,
ELsev_success // report reaching a milestone
,
ELsev_info // information
,
ELsev_warning // warning
,
ELsev_error // error detected
,
ELsev_unspecified // severity was not specified
,
ELsev_severe // future results are suspect
,
ELsev_highestSeverity // threshold use only
// -----
,
nLevels // how many levels?
}; // ELsev_
// ----- Birth/death:
//
ELseverityLevel(ELsev_ lev = ELsev_unspecified);
ELseverityLevel(ELstring const& str);
// str may match getSymbol, getName, getInputStr,
// or getVarName -- see accessors
~ELseverityLevel();
// ----- Comparator:
//
int cmp(ELseverityLevel const& e) const;
// ----- Accessors:
//
int getLevel() const;
const ELstring getSymbol() const; // example: "-e"
const ELstring getName() const; // example: "Error"
const ELstring getInputStr() const; // example: "ERROR"
const ELstring getVarName() const; // example: "ELerror"
// ----- Emitter:
//
friend std::ostream& operator<<(std::ostream& os, const ELseverityLevel& sev);
private:
// Data per ELseverityLevel object:
//
int myLevel;
}; // ELseverityLevel
#ifndef __ROOTCLING__
// ----------------------------------------------------------------------
// Declare the globally available severity objects,
// one generator function and one proxy per non-default ELsev_:
// ----------------------------------------------------------------------
extern ELslGen ELzeroSeverityGen;
extern ELslProxy<ELzeroSeverityGen> const ELzeroSeverity;
extern ELslGen ELdebugGen;
extern ELslProxy<ELdebugGen> const ELdebug;
extern ELslGen ELinfoGen;
extern ELslProxy<ELinfoGen> const ELinfo;
extern ELslGen ELwarningGen;
extern ELslProxy<ELwarningGen> const ELwarning;
extern ELslGen ELerrorGen;
extern ELslProxy<ELerrorGen> const ELerror;
extern ELslGen ELunspecifiedGen;
extern ELslProxy<ELunspecifiedGen> const ELunspecified;
extern ELslGen ELsevereGen;
extern ELslProxy<ELsevereGen> const ELsevere;
extern ELslGen ELhighestSeverityGen;
extern ELslProxy<ELhighestSeverityGen> const ELhighestSeverity;
#else
ELseverityLevel const ELzeroSeverity;
ELseverityLevel const ELdebug;
ELseverityLevel const ELinfo;
ELseverityLevel const ELwarning;
ELseverityLevel const ELerror;
ELseverityLevel const ELunspecified;
ELseverityLevel const ELsevere;
ELseverityLevel const ELhighestSeverity;
#endif
// ----------------------------------------------------------------------
// Comparators:
// ----------------------------------------------------------------------
extern bool operator==(ELseverityLevel const& e1, ELseverityLevel const& e2);
extern bool operator!=(ELseverityLevel const& e1, ELseverityLevel const& e2);
extern bool operator<(ELseverityLevel const& e1, ELseverityLevel const& e2);
extern bool operator<=(ELseverityLevel const& e1, ELseverityLevel const& e2);
extern bool operator>(ELseverityLevel const& e1, ELseverityLevel const& e2);
extern bool operator>=(ELseverityLevel const& e1, ELseverityLevel const& e2);
// ----------------------------------------------------------------------
} // end of namespace edm
// ----------------------------------------------------------------------
#ifndef __ROOTCLING__
#define ELSEVERITYLEVEL_ICC
#include "FWCore/MessageLogger/interface/ELseverityLevel.icc"
#undef ELSEVERITYLEVEL_ICC
#endif
// ----------------------------------------------------------------------
#endif // MessageLogger_ELseverityLevel_h
| 32.733032 | 82 | 0.576721 |
17ed51c67fed781ab86dc58022c76c99839d8a6a | 298 | h | C | SLToolObjCKit/Classes/Thread/SLProxy.h | CoderSLZeng/SLToolObjCKit | 636a07da4c4488b2b90f39edb4dec77d096f54bc | [
"MIT"
] | 3 | 2019-02-28T01:20:51.000Z | 2019-11-16T03:56:37.000Z | SLToolObjCKit/Classes/Thread/SLProxy.h | CoderSLZeng/SLToolObjCKit | 636a07da4c4488b2b90f39edb4dec77d096f54bc | [
"MIT"
] | null | null | null | SLToolObjCKit/Classes/Thread/SLProxy.h | CoderSLZeng/SLToolObjCKit | 636a07da4c4488b2b90f39edb4dec77d096f54bc | [
"MIT"
] | null | null | null | //
// SLProxy.h
// SLToolObjCKit
//
// Created by CoderSLZeng on 2019/3/8.
//
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface SLProxy : NSProxy
/** target */
@property (weak, nonatomic) id target;
+ (instancetype)proxyWithTarget:(id)targe;
@end
NS_ASSUME_NONNULL_END
| 13.545455 | 42 | 0.721477 |
778cb5b38ccfe9bc97fdd6f477edd6894bc5c25b | 20 | h | C | wb/t20190421/t0001/t0001/t0001/Test0001.h | stackprobe/Fairy | 55bee24922e28b5740be7aa861f7c3a9d6c7b61d | [
"MIT"
] | null | null | null | wb/t20190421/t0001/t0001/t0001/Test0001.h | stackprobe/Fairy | 55bee24922e28b5740be7aa861f7c3a9d6c7b61d | [
"MIT"
] | null | null | null | wb/t20190421/t0001/t0001/t0001/Test0001.h | stackprobe/Fairy | 55bee24922e28b5740be7aa861f7c3a9d6c7b61d | [
"MIT"
] | null | null | null | void XXXMain(void);
| 10 | 19 | 0.75 |
4fb39bf13656c7bd746f0a24c6c8028db6e8b765 | 4,175 | h | C | src/xr_3da/xrGame/stalker_movement_manager_space.h | acidicMercury8/xray-1.0 | 65e85c0e31e82d612c793d980dc4b73fa186c76c | [
"Linux-OpenIB"
] | 10 | 2021-05-04T06:40:27.000Z | 2022-01-20T20:24:28.000Z | src/xr_3da/xrGame/stalker_movement_manager_space.h | acidicMercury8/xray-1.0 | 65e85c0e31e82d612c793d980dc4b73fa186c76c | [
"Linux-OpenIB"
] | null | null | null | src/xr_3da/xrGame/stalker_movement_manager_space.h | acidicMercury8/xray-1.0 | 65e85c0e31e82d612c793d980dc4b73fa186c76c | [
"Linux-OpenIB"
] | 2 | 2021-11-07T16:57:19.000Z | 2021-12-05T13:17:12.000Z | ////////////////////////////////////////////////////////////////////////////
// Module : stalker_movement_manager_space.h
// Created : 10.06.2004
// Modified : 10.06.2004
// Author : Dmitriy Iassenev
// Description : Stalker movement manager space
////////////////////////////////////////////////////////////////////////////
#pragma once
namespace StalkerMovement {
enum eVelocities {
eVelocityStanding = u32(1) << 0,
eVelocityWalk = u32(1) << 1,
eVelocityRun = u32(1) << 2,
eVelocityMovementType = eVelocityStanding | eVelocityWalk | eVelocityRun,
eVelocityStand = u32(1) << 3,
eVelocityCrouch = u32(1) << 4,
eVelocityBodyState = eVelocityStand | eVelocityCrouch,
eVelocityDanger = u32(1) << 6,
eVelocityFree = u32(1) << 7,
eVelocityPanic = u32(1) << 8,
eVelocityMentalState = eVelocityDanger | eVelocityFree | eVelocityPanic,
eVelocityPositiveVelocity = u32(1) << 31,
eVelocityNegativeVelocity = u32(1) << 30,
eVelocityStandingFreeStand = eVelocityStanding | eVelocityFree | eVelocityStand,
eVelocityStandingPanicStand = eVelocityStanding | eVelocityPanic | eVelocityStand,
eVelocityStandingDangerStand = eVelocityStanding | eVelocityDanger | eVelocityStand,
eVelocityStandingFreeCrouch = eVelocityStanding | eVelocityFree | eVelocityCrouch,
eVelocityStandingPanicCrouch = eVelocityStanding | eVelocityPanic | eVelocityCrouch,
eVelocityStandingDangerCrouch = eVelocityStanding | eVelocityDanger | eVelocityCrouch,
eVelocityWalkFree = eVelocityWalk | eVelocityFree | eVelocityStand,
eVelocityWalkDangerStand = eVelocityWalk | eVelocityDanger | eVelocityStand,
eVelocityWalkDangerCrouch = eVelocityWalk | eVelocityDanger | eVelocityCrouch,
eVelocityRunFree = eVelocityRun | eVelocityFree | eVelocityStand,
eVelocityRunDangerStand = eVelocityRun | eVelocityDanger | eVelocityStand,
eVelocityRunDangerCrouch = eVelocityRun | eVelocityDanger | eVelocityCrouch,
eVelocityRunPanicStand = eVelocityRun | eVelocityPanic | eVelocityStand,
eVelocityStandingFreeCrouchPositive = eVelocityStandingFreeCrouch | eVelocityPositiveVelocity,
eVelocityStandingPanicCrouchPositive = eVelocityStandingPanicCrouch | eVelocityPositiveVelocity,
eVelocityStandingDangerCrouchPositive = eVelocityStandingDangerCrouch | eVelocityPositiveVelocity,
eVelocityWalkFreePositive = eVelocityWalkFree | eVelocityPositiveVelocity,
eVelocityWalkDangerStandPositive = eVelocityWalkDangerStand | eVelocityPositiveVelocity,
eVelocityWalkDangerCrouchPositive = eVelocityWalkDangerCrouch | eVelocityPositiveVelocity,
eVelocityRunFreePositive = eVelocityRunFree | eVelocityPositiveVelocity,
eVelocityRunDangerStandPositive = eVelocityRunDangerStand | eVelocityPositiveVelocity,
eVelocityRunDangerCrouchPositive = eVelocityRunDangerCrouch | eVelocityPositiveVelocity,
eVelocityRunPanicStandPositive = eVelocityRunPanicStand | eVelocityPositiveVelocity,
eVelocityStandingFreeCrouchNegative = eVelocityStandingFreeCrouch | eVelocityNegativeVelocity,
eVelocityStandingPanicCrouchNegative = eVelocityStandingPanicCrouch | eVelocityNegativeVelocity,
eVelocityStandingDangerCrouchNegative = eVelocityStandingDangerCrouch | eVelocityNegativeVelocity,
eVelocityWalkFreeNegative = eVelocityWalkFree | eVelocityNegativeVelocity,
eVelocityWalkDangerStandNegative = eVelocityWalkDangerStand | eVelocityNegativeVelocity,
eVelocityWalkDangerCrouchNegative = eVelocityWalkDangerCrouch | eVelocityNegativeVelocity,
eVelocityRunFreeNegative = eVelocityRunFree | eVelocityNegativeVelocity,
eVelocityRunDangerStandNegative = eVelocityRunDangerStand | eVelocityNegativeVelocity,
eVelocityRunDangerCrouchNegative = eVelocityRunDangerCrouch | eVelocityNegativeVelocity,
eVelocityRunPanicStandNegative = eVelocityRunPanicStand | eVelocityNegativeVelocity,
};
}; | 59.642857 | 105 | 0.727904 |
85fa15aa03e665c9a6d5ce65c463728ee7f62d10 | 31,672 | c | C | src/front-end/codegen/zir.c | lbrugnara/zenit | 72cf091e8c392c895adaa7ac623320af92a8b452 | [
"MIT"
] | 4 | 2019-04-27T21:09:56.000Z | 2022-02-03T21:22:14.000Z | src/front-end/codegen/zir.c | lbrugnara/zenit | 72cf091e8c392c895adaa7ac623320af92a8b452 | [
"MIT"
] | null | null | null | src/front-end/codegen/zir.c | lbrugnara/zenit | 72cf091e8c392c895adaa7ac623320af92a8b452 | [
"MIT"
] | null | null | null | #include "zir.h"
#include "../utils.h"
#include "../program.h"
#include "../symbol.h"
#include "../../zir/program.h"
#include "../../zir/instructions/operands/pool.h"
#define assert_or_return(ctx, condition, location, message) \
if (!(condition)) \
{ \
if (message != NULL) \
zenit_context_error(ctx, location, \
ZENIT_ERROR_INTERNAL, message); \
return NULL; \
}
static inline ZirType* new_zir_type_from_zenit_type(ZirProgram *program, ZenitType *zenit_type);
ZirAttributeMap* zenit_attr_map_to_zir_attr_map(ZenitContext *ctx, ZirProgram *program, ZenitAttributeNodeMap *zenit_attrs);
typedef ZirOperand*(*ZirGenerator)(ZenitContext *ctx, ZirProgram *program, ZenitNode *node);
// Visitor functions
static ZirOperand* visit_node(ZenitContext *ctx, ZirProgram *program, ZenitNode *node);
static ZirOperand* visit_uint_node(ZenitContext *ctx, ZirProgram *program, ZenitUintNode *uint_node);
static ZirOperand* visit_bool_node(ZenitContext *ctx, ZirProgram *program, ZenitBoolNode *bool_node);
static ZirOperand* visit_variable_node(ZenitContext *ctx, ZirProgram *program, ZenitVariableNode *variable_node);
static ZirOperand* visit_array_node(ZenitContext *ctx, ZirProgram *program, ZenitArrayNode *array_node);
static ZirOperand* visit_identifier_node(ZenitContext *ctx, ZirProgram *program, ZenitIdentifierNode *id_node);
static ZirOperand* visit_reference_node(ZenitContext *ctx, ZirProgram *program, ZenitReferenceNode *ref_node);
static ZirOperand* visit_cast_node(ZenitContext *ctx, ZirProgram *program, ZenitCastNode *cast_node);
static ZirOperand* visit_field_decl_node(ZenitContext *ctx, ZirProgram *program, ZenitStructFieldDeclNode *field_node);
static ZirOperand* visit_struct_decl_node(ZenitContext *ctx, ZirProgram *program, ZenitStructDeclNode *struct_node);
static ZirOperand* visit_struct_node(ZenitContext *ctx, ZirProgram *program, ZenitStructNode *struct_node);
static ZirOperand* visit_if_node(ZenitContext *ctx, ZirProgram *program, ZenitIfNode *if_node);
static ZirOperand* visit_block_node(ZenitContext *ctx, ZirProgram *program, ZenitBlockNode *block_node);
/*
* Variable: generators
* An array indexed with a <ZenitNodeKind> to get a <ZirGenerator> function
*/
static const ZirGenerator generators[] = {
[ZENIT_AST_NODE_UINT] = (ZirGenerator) &visit_uint_node,
[ZENIT_AST_NODE_BOOL] = (ZirGenerator) &visit_bool_node,
[ZENIT_AST_NODE_VARIABLE] = (ZirGenerator) &visit_variable_node,
[ZENIT_AST_NODE_ARRAY] = (ZirGenerator) &visit_array_node,
[ZENIT_AST_NODE_IDENTIFIER] = (ZirGenerator) &visit_identifier_node,
[ZENIT_AST_NODE_REFERENCE] = (ZirGenerator) &visit_reference_node,
[ZENIT_AST_NODE_CAST] = (ZirGenerator) &visit_cast_node,
[ZENIT_AST_NODE_FIELD_DECL] = (ZirGenerator) &visit_field_decl_node,
[ZENIT_AST_NODE_STRUCT_DECL] = (ZirGenerator) &visit_struct_decl_node,
[ZENIT_AST_NODE_STRUCT] = (ZirGenerator) &visit_struct_node,
[ZENIT_AST_NODE_IF] = (ZirGenerator) &visit_if_node,
[ZENIT_AST_NODE_BLOCK] = (ZirGenerator) &visit_block_node,
};
/*
* Function: new_temp_symbol
* Creates a new temporal ZIR symbol and adds it to the current program's block
*
* Parameters:
* <ZirProgram> *program: The ZIR program
* <ZirType> *type: The type of the temporal symbol
*
* Returns:
* ZirSymbol*: The new temporal symbol
*
* Notes:
* Temporal symbols are symbols which name starts with a '%'
*/
static ZirSymbol* new_temp_symbol(ZirProgram *program, ZirType *type)
{
char name[1024] = { 0 };
snprintf(name, 1024, "%%tmp%llu", program->current->temp_counter++);
ZirSymbol *zir_symbol = zir_symbol_new(name, type);
zir_program_add_symbol(program, zir_symbol);
return zir_symbol;
}
static ZirSymbol* import_zir_symbol_from_zenit_symbol(ZirProgram *program, ZenitSymbol *zenit_symbol, ZenitSourceLocation *loc)
{
ZirSymbol *zir_symbol = NULL;
if (zir_block_has_symbol(program->current, zenit_symbol->name))
{
// Because ZIR does not have use block for Zenit nested blocks (ZENIT_SCOPE_BLOCK), there can be
// clash of names, in that case we resolve it using the line and column number of the Zenit symbol
zir_symbol = zir_symbol_new(zenit_symbol->mangled_name, new_zir_type_from_zenit_type(program, zenit_symbol->type));
}
else
{
zir_symbol = zir_symbol_new(zenit_symbol->name, new_zir_type_from_zenit_type(program, zenit_symbol->type));
}
if (zir_symbol == NULL)
return NULL;
zir_symbol = zir_program_add_symbol(program, zir_symbol);
return zir_symbol;
}
/*
* Function: new_zir_type_from_zenit_type
* Converts a Zenit type object to its counterpart's ZIR type
*
* Parameters:
* <ZirProgram> *program: ZIR program
* <ZenitType> *zenit_type: The Zenit type object to convert
*
* Returns:
* ZirType*: The ZIR type object
*/
static inline ZirType* new_zir_type_from_zenit_type(ZirProgram *program, ZenitType *zenit_type)
{
if (zenit_type->typekind == ZENIT_TYPE_UINT)
{
ZenitUintType *zenit_uint = (ZenitUintType*) zenit_type;
ZirUintTypeSize size;
switch (zenit_uint->size)
{
case ZENIT_UINT_8:
size = ZIR_UINT_8;
break;
case ZENIT_UINT_16:
size = ZIR_UINT_16;
break;
default:
size = ZIR_UINT_UNK;
break;
}
return (ZirType*) zir_uint_type_new(size);
}
if (zenit_type->typekind == ZENIT_TYPE_BOOL)
{
return (ZirType*) zir_bool_type_new();
}
if (zenit_type->typekind == ZENIT_TYPE_REFERENCE)
{
ZenitReferenceType *zenit_ref = (ZenitReferenceType*) zenit_type;
ZirType *zir_element_type = new_zir_type_from_zenit_type(program, zenit_ref->element);
return (ZirType*) zir_reference_type_new(zir_element_type);
}
if (zenit_type->typekind == ZENIT_TYPE_STRUCT)
{
ZenitStructType *zenit_struct = (ZenitStructType*) zenit_type;
ZirStructType *zir_struct_type = zir_struct_type_new(zenit_struct->name);
struct FlListNode *zenit_node = fl_list_head(zenit_struct->members);
while (zenit_node)
{
ZenitStructTypeMember *zenit_member = (ZenitStructTypeMember*) zenit_node->value;
zir_struct_type_add_member(zir_struct_type, zenit_member->name, new_zir_type_from_zenit_type(program, zenit_member->type));
zenit_node = zenit_node->next;
}
return (ZirType*) zir_struct_type;
}
if (zenit_type->typekind == ZENIT_TYPE_ARRAY)
{
ZenitArrayType *zenit_array = (ZenitArrayType*) zenit_type;
ZirArrayType *zir_array = zir_array_type_new(new_zir_type_from_zenit_type(program, zenit_array->member_type));
zir_array->length = zenit_array->length;
return (ZirType*) zir_array;
}
if (zenit_type->typekind == ZENIT_TYPE_NONE)
return zir_none_type_new();
return NULL;
}
/*
* Function: zenit_attr_map_to_zir_attr_map
* Converts a map of Zenit attributes to a map of ZIR attributes
*
* Parameters:
* <ZenitContext> *ctx: Context object
* <ZirProgram> *program: The ZIR program
* <ZenitAttributeNodeMap> *zenit_attrs: The Zenit attribute map
*
* Returns:
* ZirAttributeMap: The map of ZIR attributes converted from the Zenit attribute map
*/
ZirAttributeMap* zenit_attr_map_to_zir_attr_map(ZenitContext *ctx, ZirProgram *program, ZenitAttributeNodeMap *zenit_attrs)
{
// We always initialize the ZIR attributes map
ZirAttributeMap *zir_attrs = zir_attribute_map_new();
// Get the Zenit attributes
const char **zenit_attr_names = zenit_attribute_node_map_keys(zenit_attrs);
size_t zenit_attr_count = fl_array_length(zenit_attr_names);
for (size_t i=0; i < zenit_attr_count; i++)
{
// Get the Zenit attribute
ZenitAttributeNode *zenit_attr = zenit_attribute_node_map_get(zenit_attrs, zenit_attr_names[i]);
// Get the Zenit properties
const char **zenit_prop_names = zenit_property_node_map_keys(zenit_attr->properties);
size_t zenit_prop_count = fl_array_length(zenit_prop_names);
// Create the ZIR attribute
ZirAttribute *zir_attr = zir_attribute_new(zenit_attr->name);
// Create the ZIR properties (if any)
for (size_t j=0; j < zenit_prop_count; j++)
{
// Get the Zenit property
ZenitPropertyNode *zenit_prop = zenit_property_node_map_get(zenit_attr->properties, zenit_prop_names[j]);
// Create the ZIR property with the operand obtained from visiting the property's value
ZirProperty *zir_prop = zir_property_new(zenit_prop->name, visit_node(ctx, program, zenit_prop->value));
// We add the parsed property to the attribute's properties map
zir_property_map_add(zir_attr->properties, zir_prop);
}
fl_array_free(zenit_prop_names);
// Add the ZIR attribute to the map
zir_attribute_map_add(zir_attrs, zir_attr);
}
fl_array_free(zenit_attr_names);
return zir_attrs;
}
/*
* Function: visit_cast_node
* Adds a cast instruction to the program using a temporal ZIR symbol to hold the intermediate
* result of the cast expression
*
* Parameters:
* <ZenitContext> *ctx: Context object
* <ZirProgram> *program: Program object
* <ZenitCastNode> *zenit_cast - The cast node
*
* Returns:
* ZirOperand - The cast operand object
*
*/
static ZirOperand* visit_cast_node(ZenitContext *ctx, ZirProgram *program, ZenitCastNode *zenit_cast)
{
// If it is an implicit cast (up cast), we let the back end manage it, so we directly return the operand
// that comes up from the casted expression
if (zenit_cast->implicit)
return visit_node(ctx, program, zenit_cast->expression);
ZenitSymbol *zenit_cast_symbol = zenit_utils_get_tmp_symbol(ctx->program, (ZenitNode*) zenit_cast);
// We use a temporal symbol for the cast's destination. We copy the type informaton from the Zenit cast's object type information
ZirSymbol *temp_symbol = new_temp_symbol(program, new_zir_type_from_zenit_type(program, zenit_cast_symbol->type));
// The destination operand is the temporal symbol created above
ZirOperand *destination = (ZirOperand*) zir_operand_pool_new_symbol(program->operands, temp_symbol);
// Now, we need to get the source operand of the cast, and for that we need to visit the casted expression
ZirOperand *source = visit_node(ctx, program, zenit_cast->expression);
// We create the cast instruction and we add it to the program. Finally, we return the destination operand.
return zir_program_emit(program, (ZirInstr*) zir_cast_instr_new(destination, source))->destination;
}
/*
* Function: visit_uint_node
* Returns a uint operand
*
* Parameters:
* <ZenitContext> *ctx: Context object
* <ZirProgram> *program: Program object
* <ZenitUintNode> *zenit_uint - Uint literal node
*
* Returns:
* ZirOperand - The uint operand object
*
*/
static ZirOperand* visit_uint_node(ZenitContext *ctx, ZirProgram *program, ZenitUintNode *zenit_uint)
{
ZenitSymbol *zenit_uint_symbol = zenit_utils_get_tmp_symbol(ctx->program, (ZenitNode*) zenit_uint);
// First, we need to map the types and values between Zenit and ZIR
ZirUintValue zir_value;
switch (((ZenitUintType*) zenit_uint_symbol->type)->size)
{
case ZENIT_UINT_8:
zir_value.uint8 = zenit_uint->value.uint8;
break;
case ZENIT_UINT_16:
zir_value.uint16 = zenit_uint->value.uint16;
break;
default:
return NULL;
}
// Then, we create a uint operand, and we copy the type information from the Zenit node
ZirUintOperand *zir_uint_source = zir_operand_pool_new_uint(program->operands, (ZirUintType*) new_zir_type_from_zenit_type(program, zenit_uint_symbol->type), zir_value);
return (ZirOperand*) zir_uint_source;
}
/*
* Function: visit_bool_node
* Returns a boolean operand
*
* Parameters:
* <ZenitContext> *ctx: Context object
* <ZirProgram> *program: Program object
* <ZenitBoolNode> *zenit_bool - Boolean literal node
*
* Returns:
* ZirOperand - The boolean operand object
*
*/
static ZirOperand* visit_bool_node(ZenitContext *ctx, ZirProgram *program, ZenitBoolNode *zenit_bool)
{
ZenitSymbol *zenit_bool_symbol = zenit_utils_get_tmp_symbol(ctx->program, (ZenitNode*) zenit_bool);
// Then, we create a boolean operand, and we copy the type information from the Zenit node
ZirBoolType *bool_type = (ZirBoolType*) new_zir_type_from_zenit_type(program, zenit_bool_symbol->type);
ZirBoolOperand *zir_bool_operand = zir_operand_pool_new_bool(program->operands, bool_type, zenit_bool->value);
return (ZirOperand*) zir_bool_operand;
}
/*
* Function: visit_reference_node
* Returns a reference operand for the referenced expression
*
* Parameters:
* <ZenitContext> *ctx: Context object
* <ZirProgram> *program: Program object
* <ZenitReferenceNode> *zenit_ref - The reference node
*
* Returns:
* ZirOperand - The reference operand object
*
*/
static ZirOperand* visit_reference_node(ZenitContext *ctx, ZirProgram *program, ZenitReferenceNode *zenit_ref)
{
// We need to visit the referenced expression to get the operand
ZirOperand *operand = visit_node(ctx, program, zenit_ref->expression);
if (operand->type != ZIR_OPERAND_SYMBOL)
{
zenit_context_error(ctx, zenit_ref->base.location, ZENIT_ERROR_INVALID_REFERENCE, "Invalid usage of the reference operator");
return NULL;
}
ZenitSymbol *zenit_ref_symbol = zenit_utils_get_tmp_symbol(ctx->program, (ZenitNode*) zenit_ref);
// We convert from the Zenit type to the ZIR type
ZirReferenceType *ref_zir_type = (ZirReferenceType*) new_zir_type_from_zenit_type(program, zenit_ref_symbol->type);
// We return a reference operand with the symbol operand we received from the visit to the referenced expression
return (ZirOperand*) zir_operand_pool_new_reference(program->operands, ref_zir_type, (ZirSymbolOperand*) operand);
}
/*
* Function: visit_identifier_node
* Returns a symbol operand for the identifier. The symbol must exist
*
* Parameters:
* <ZenitContext> *ctx: Context object
* <ZirProgram> *program: Program object
* <ZenitIdentifierNode> *zenit_id - Literal node
*
* Returns:
* ZirOperand - The symbol operand object
*
*/
static ZirOperand* visit_identifier_node(ZenitContext *ctx, ZirProgram *program, ZenitIdentifierNode *zenit_id)
{
ZenitSymbol *zenit_symbol = zenit_program_get_symbol(ctx->program, zenit_id->name);
// We retrieve the symbol from the symbol table
ZirSymbol *zir_symbol = NULL;
if (zir_symtable_has(&program->current->symtable, zenit_symbol->mangled_name))
{
zir_symbol = zir_symtable_get(&program->current->symtable, zenit_symbol->mangled_name);
}
else
{
zir_symbol = zir_symtable_get(&program->current->symtable, zenit_symbol->name);
}
assert_or_return(ctx, zir_symbol != NULL, zenit_id->base.location, "ZIR symbol does not exist");
return (ZirOperand*) zir_operand_pool_new_symbol(program->operands, zir_symbol);
}
/*
* Function: visit_array_node
* Creates an array operand for the array literal
*
* Parameters:
* <ZenitContext> *ctx: Context object
* <ZirProgram> *program: Program object
* <ZenitArrayNode> *zenit_array - Array initializer node
*
* Returns:
* ZirOperand - They array operand
*
*/
static ZirOperand* visit_array_node(ZenitContext *ctx, ZirProgram *program, ZenitArrayNode *zenit_array)
{
ZenitSymbol *zenit_array_symbol = zenit_utils_get_tmp_symbol(ctx->program, (ZenitNode*) zenit_array);
// We create an array operand for the array literal
ZirArrayType *zir_array_type = (ZirArrayType*) new_zir_type_from_zenit_type(program, zenit_array_symbol->type);
ZirArrayOperand *zir_array = zir_operand_pool_new_array(program->operands, zir_array_type);
// Visit the array's elements to get the operands
for (size_t i=0; i < fl_array_length(zenit_array->elements); i++)
{
ZirOperand *zir_operand = visit_node(ctx, program, zenit_array->elements[i]);
zir_array_operand_add_element(zir_array, zir_operand);
}
return (ZirOperand*) zir_array;
}
/*
* Function: visit_struct_node
* This function creates an struct operand.
*
* Parameters:
* <ZenitContext> *ctx: Context object
* <ZirProgram> *program: ZIR program
* <ZenitStructFieldDeclNode> *zenit_struct: The struct literal node
*
* Returns:
* ZirOperand*: The struct operand
*/
static ZirOperand* visit_struct_node(ZenitContext *ctx, ZirProgram *program, ZenitStructNode *zenit_struct)
{
ZenitSymbol *zenit_struct_symbol = zenit_utils_get_tmp_symbol(ctx->program, (ZenitNode*) zenit_struct);
// Create struct operand
ZirStructType *zir_struct_type = (ZirStructType*) new_zir_type_from_zenit_type(program, zenit_struct_symbol->type);
ZirStructOperand *struct_operand = zir_operand_pool_new_struct(program->operands, zir_struct_type);
for (size_t i=0; i < fl_array_length(zenit_struct->members); i++)
{
ZenitNode *member_node = zenit_struct->members[i];
if (member_node->nodekind == ZENIT_AST_NODE_FIELD)
{
ZenitStructFieldNode *field_node = (ZenitStructFieldNode*) member_node;
ZirOperand *field_operand = visit_node(ctx, program, field_node->value);
zir_struct_operand_add_member(struct_operand, field_node->name, field_operand);
}
}
// Return struct operand
return (ZirOperand*) struct_operand;
}
/*
* Function: visit_field_decl_node
* The field declaration visitor adds the ZIR symbols to the current block
*
* Parameters:
* <ZenitContext> *ctx: Context object
* <ZirProgram> *program: ZIR program
* <ZenitStructFieldDeclNode> *zenit_field: The field declaration node
*
* Returns:
* ZirOperand*: This function returns <NULL> as the field declaration does not add an instruction to the program
*/
static ZirOperand* visit_field_decl_node(ZenitContext *ctx, ZirProgram *program, ZenitStructFieldDeclNode *zenit_field)
{
ZenitSymbol *zenit_symbol = zenit_program_get_symbol(ctx->program, zenit_field->name);
// We add a new symbol in the current block.
ZirSymbol *zir_symbol = import_zir_symbol_from_zenit_symbol(program, zenit_symbol, &zenit_field->base.location);
assert_or_return(ctx, zir_symbol != NULL, zenit_field->base.location, "Could not create ZIR symbol");
return NULL;
}
/*
* Function: visit_struct_decl_node
* This function checks if the <convert_zenit_scope_to_zir_block> function has added the ZIR block that identifies
* the struct declaration, and after that it visits all the members to populate the block with their information
*
* Parameters:
* <ZenitContext> *ctx: Context object
* <ZirProgram> *program: Program object
* <ZenitStructDeclNode> *struct_node - Struct declaration node
*
* Returns:
* ZirOperand - <NULL>, because the struct declaration does not add an instruction
*/
static ZirOperand* visit_struct_decl_node(ZenitContext *ctx, ZirProgram *program, ZenitStructDeclNode *struct_node)
{
ZirBlock *struct_block = zir_program_get_block(program, ZIR_BLOCK_STRUCT, struct_node->name);
if (struct_block == NULL)
{
zenit_context_error(ctx, struct_node->base.location, ZENIT_ERROR_INTERNAL, "Missing ZIR block for struct '%s'", struct_node->name);
return NULL;
}
zenit_program_push_scope(ctx->program, ZENIT_SCOPE_STRUCT, struct_node->name);
zir_program_enter_block(program, struct_block);
for (size_t i=0; i < fl_array_length(struct_node->members); i++)
visit_node(ctx, program, struct_node->members[i]);
zir_program_pop_block(program);
zenit_program_pop_scope(ctx->program);
return NULL;
}
/*
* Function: visit_variable_node
* This function creates a new instruction that declares a named variable in the current
* block scope.
*
* Parameters:
* <ZenitContext> *ctx: Context object
* <ZirProgram> *program: Program object
* <ZenitVariableNode> *zenit_variable - Variable declaration node
*
* Returns:
* ZirOperand - The symbol operand that identifies the variable
*/
static ZirOperand* visit_variable_node(ZenitContext *ctx, ZirProgram *program, ZenitVariableNode *zenit_variable)
{
ZenitSymbol *zenit_symbol = zenit_program_get_symbol(ctx->program, zenit_variable->name);
ZirSymbol *zir_symbol = import_zir_symbol_from_zenit_symbol(program, zenit_symbol, &zenit_variable->base.location);
assert_or_return(ctx, zir_symbol != NULL, zenit_variable->base.location, "Could not create ZIR symbol");
// The destination operand is a symbol operand (the created ZIR symbol)
ZirOperand *lhs = (ZirOperand*) zir_operand_pool_new_symbol(program->operands, zir_symbol);
// The source operand is the one we get from the visit to the <ZenitVariableNode>'s value
ZirOperand *rhs = visit_node(ctx, program, zenit_variable->rvalue);
// Create the variable declaration instruction with the source and destination operands
ZirVariableInstr *var_instr = zir_variable_instr_new(lhs, rhs);
// Convert the Zenit attributes to ZIR attributes
var_instr->attributes = zenit_attr_map_to_zir_attr_map(ctx, program, zenit_variable->attributes);
// Add the variable instruction to the program and finally return the destination operand
return zir_program_emit(program, (ZirInstr*) var_instr)->destination;
}
static ZirOperand* visit_if_node(ZenitContext *ctx, ZirProgram *program, ZenitIfNode *if_node)
{
zenit_program_push_scope(ctx->program, ZENIT_SCOPE_BLOCK, if_node->id);
// We need to visit the condition expression to emit it. We get the operand because it
// is the *source* condition of the if-false instruction
ZirOperand *source_operand = visit_node(ctx, program, if_node->condition);
// TODO: WE ARE USING UINT FOR THE JUMP, WE SHOULD UPDATE THIS TO SIGNED INT AS THE TYPES IN ZIR CHANGE
// TO ALLOW JUMPING BACKWARDS
// Create a uint operand for the jump offset with a value of 0 symbolizing a jump that needs to be backpatched
ZirOperand *if_jump_destination = (ZirOperand*) zir_operand_pool_new_uint(program->operands, zir_uint_type_new(ZIR_UINT_16), (ZirUintValue){ .uint16 = 0 });
// Emit the if-false instruction. We keep a reference to it to backpatch the jump destination
ZirInstr *if_false_instr = zir_program_emit(program, (ZirInstr*) zir_if_false_instr_new(if_jump_destination, source_operand));
// Get the IP at the if-false instruction to calculate the jump
size_t if_instr_ip = zir_block_get_ip(program->current);
if (if_instr_ip > (size_t) UINT16_MAX)
{
zenit_context_error(ctx, if_node->base.location, ZENIT_ERROR_INTERNAL, "Unaddressable jump of %zu instructions", if_instr_ip);
goto unaddressable_jump;
}
// Visit the "then" branch to emit the ZIR instructions when the if-false instruction is not satisfied
visit_node(ctx, program, if_node->then_branch);
// At this point, the value of the IP of the block is 'k' which is placed in the last instruction that belongs to
// the "then" branch. We say we are 'q' instructions ahead of the IP 'n' we saved before (the if_instr_ip variable):
//
// if_false <condition> jump <unknown> <-- IP: 'n' ---.
// ... | Difference of 'k' - 'n' instructions => 'q'
// <last instruction within "then" branch> <-- IP: 'k' ---´
// <first instruction outside of the "then" branch> <-- IP: 'k' + 1
//
// Depending on the existence of an else branch, we need to calculate the offset of the jump from the if-false instruction
if (if_node->else_branch == NULL)
{
// If there is no "else" branch, the jump destination is the instruction placed at 'k' + 1
// The following line retrieves the current IP ('k')
size_t current_ip = zir_block_get_ip(program->current);
// Because the if-false instruction works with offsets, we need to calculate it:
// target offset = 'k' + 1 - 'n'
if (fl_std_uint_add_overflow(current_ip, 1, UINT16_MAX))
{
zenit_context_error(ctx, if_node->base.location, ZENIT_ERROR_INTERNAL, "Unaddressable jump of %zu + 1 instructions", current_ip);
goto unaddressable_jump;
}
((ZirUintOperand*) if_false_instr->destination)->value.uint16 = current_ip - if_instr_ip + 1;
}
else
{
// If there is an "else" branch, the jump destination of the if-false instruction is the first instruction within the "else" branch,
// but to not fall from the "then" branch to the "else" branch when the if-false instruction is not met, we need to add an instruction
// to "exit" the "then" branch. That instruction is an unconditional jump, and the destination of that jump needs to be backpatched to jump
// to the next instruction following the "else" branch:
//
// if_false <condition> jump <unknown> <-- IP: 'n' ------.
// ... |
// <last instruction within "then" branch> <-- IP: 'k' | Difference of 'j' + 1 - 'n' instructions
// jump ?? <-- IP: 'j' |
// <first instruction of the "else" branch> <-- IP: 'j' + 1 --´
// ...
// <last instruction within "else" branch> <-- IP: 'm'
// <first instruction outside of the "else" branch> <-- IP: 'm' + 1 (the target of the jump instruction)
//
ZirOperand *jump_destination = (ZirOperand*) zir_operand_pool_new_uint(program->operands, zir_uint_type_new(ZIR_UINT_16), (ZirUintValue){ .uint16 = 0 });
ZirInstr *jump_instr = zir_program_emit(program, (ZirInstr*) zir_jump_instr_new(jump_destination));
// Similar to what we did with the if-false instruction, we save the IP ('j') at the jump place to calculate the offset
size_t jump_inst_ip = zir_block_get_ip(program->current);
// As mentioned above, the entry point of the "else" branch is the instruction 'j' + 1, which means that the if-false instruction
// needs to jump 'j' + 1 - 'n' instruction forward:
if (fl_std_uint_add_overflow(jump_inst_ip, 1, UINT16_MAX))
{
zenit_context_error(ctx, if_node->base.location, ZENIT_ERROR_INTERNAL, "Unaddressable jump of %zu + 1 instructions", jump_inst_ip);
goto unaddressable_jump;
}
((ZirUintOperand*) if_false_instr->destination)->value.uint16 = jump_inst_ip + 1 - if_instr_ip;
// We visit the "else" branch
visit_node(ctx, program, if_node->else_branch);
// We retrieve the current IP ('m')
size_t last_else_ip = zir_block_get_ip(program->current);
// Finally, the destination of the unconditional jump is the instruction 'm' + 1, and the offset from the jump instruction
// is: 'm' + 1 - 'j'
if (fl_std_uint_add_overflow(last_else_ip, 1, UINT16_MAX))
{
zenit_context_error(ctx, if_node->base.location, ZENIT_ERROR_INTERNAL, "Unaddressable jump of %zu + 1 instructions", last_else_ip);
goto unaddressable_jump;
}
((ZirUintOperand*) jump_instr->destination)->value.uint16 = last_else_ip + 1 - jump_inst_ip;
}
unaddressable_jump:
// Jump out of the Zenit block
zenit_program_pop_scope(ctx->program);
// No need to return anything
return NULL;
}
static ZirOperand* visit_block_node(ZenitContext *ctx, ZirProgram *program, ZenitBlockNode *block_node)
{
// Enter to the Zenit scope
zenit_program_push_scope(ctx->program, ZENIT_SCOPE_BLOCK, block_node->id);
// Generate ZIR instructions for each Zenit statement
for (size_t i=0; i < fl_array_length(block_node->statements); i++)
visit_node(ctx, program, block_node->statements[i]);
// Jump out of the Zenit block
zenit_program_pop_scope(ctx->program);
// No need to return anything
return NULL;
}
/*
* Function: visit_node
* This function selects the visitor function based on the node's type
* and calls the function.
*
* Parameters:
* <ZenitContext> *ctx: Context object
* <ZirProgram> *program: Program object
* <ZenitNode> *node - Node to visit
*
* Returns:
* ZirOperand - A pointer to a an operand object
*
*/
static ZirOperand* visit_node(ZenitContext *ctx, ZirProgram *program, ZenitNode *node)
{
return generators[node->nodekind](ctx, program, node);
}
/*
* Function: convert_zenit_scope_to_zir_block
* For every type or function defined in Zenit (which is represented as a scope object) this function
* creates a ZIR block to contain the type or function definition.
*
* Parameters:
* <ZenitScope> *scope: The Zenit scope object used as the root for the conversion
* <ZirBlock> *block: The ZIR root block that will hold all the new ZIR blocks
*
* Returns:
* void: This function does not return a value
*/
static void convert_zenit_scope_to_zir_block(ZenitScope *scope, ZirBlock *block)
{
for (size_t i=0; i < fl_array_length(scope->children); i++)
{
ZenitScope *zenit_child = scope->children[i];
ZirBlockType block_type;
switch (zenit_child->type)
{
case ZENIT_SCOPE_STRUCT:
block_type = ZIR_BLOCK_STRUCT;
break;
case ZENIT_SCOPE_FUNCTION:
block_type = ZIR_BLOCK_FUNCTION;
break;
case ZENIT_SCOPE_GLOBAL:
block_type = ZIR_BLOCK_GLOBAL;
break;
case ZENIT_SCOPE_BLOCK: // We don't create ZIR blocks for Zenit nested scopes
continue;
}
ZirBlock *zir_child = zir_block_new(zenit_child->id, block_type, block);
block->children = fl_array_append(block->children, &zir_child);
convert_zenit_scope_to_zir_block(zenit_child, zir_child);
}
}
/*
* Function: zenit_generate_zir
* We just iterate over the declarations visiting each node to populate the <ZirProgram>
* with <ZirInstr>s
*/
ZirProgram* zenit_generate_zir(ZenitContext *ctx)
{
if (!ctx || !ctx->ast || !ctx->ast->decls)
return NULL;
ZirProgram *program = zir_program_new();
size_t errors = zenit_context_error_count(ctx);
// We make sure all the functions, structs, etc are "declared" in ZIR
convert_zenit_scope_to_zir_block(ctx->program->global_scope, program->global);
for (size_t i=0; i < fl_array_length(ctx->ast->decls); i++)
visit_node(ctx, program, ctx->ast->decls[i]);
if (errors == zenit_context_error_count(ctx))
return program;
zir_program_free(program);
return NULL;
}
| 40.709512 | 173 | 0.695283 |
27750532d39c6e0f47f12a34819750cbc5a18943 | 1,171 | h | C | allrichstore/Tools/CommonLibrary/Category/CommonCatetory.h | 754340156/NQ_quanfu | c885cfd9d4aa95c5b2f519008b3d1a60055638b8 | [
"MIT"
] | 1 | 2021-05-13T05:24:18.000Z | 2021-05-13T05:24:18.000Z | allrichstore/Tools/CommonLibrary/Category/CommonCatetory.h | 754340156/NQ_quanfu | c885cfd9d4aa95c5b2f519008b3d1a60055638b8 | [
"MIT"
] | null | null | null | allrichstore/Tools/CommonLibrary/Category/CommonCatetory.h | 754340156/NQ_quanfu | c885cfd9d4aa95c5b2f519008b3d1a60055638b8 | [
"MIT"
] | null | null | null | //
// CommonCatetory.h
// CommonLibrary
//
// Created by Alexi on 13-11-6.
// Copyright (c) 2013年 ywchen. All rights reserved.
//
#ifndef CommonLibrary_CommonCatetory_h
#define CommonLibrary_CommonCatetory_h
#import "UIImage+TintColor.h"
#import "UIImage+Alpha.h"
#import "UIImage+Common.h"
#import "NSDate+Common.h"
#if kSupportNSDataCommon
#import "NSData+Common.h"
#import "NSData+CRC.h"
#endif
#import "NSString+Common.h"
#if kSupportGTM64
#import "GTMDefines.h"
#import "GTMBase64.h"
#endif
#import "UILabel+Common.h"
#import "UIView+CustomAutoLayout.h"
#if kSupportModifyFrame
#import "UIView+ModifyFrame.h"
#endif
#import "NSString+RegexCheck.h"
#if kSupportKeyChainHelper
#import "KeyChainHelper.h"
#endif
#import "UIViewController+ChildViewController.h"
#import "NSObject+CommonBlock.h"
#if kSupportNSObjectKVOCategory
#import "NSObject+KVOCategory.h"
#endif
#import "UIView+RelativeCoordinate.h"
#if kSupportMKMapViewZoomLevel
#import "MKMapView+ZoomLevel.h"
#endif
#import "UITextField+UITextField_Tip.h"
#import "CLSafeMutableArray.h"
#import "UIView+Glow.h"
#if kSupportUIViewEffect
#import "UIView+Effect.h"
#endif
#endif
| 14.822785 | 52 | 0.762596 |
27822f6d70b52d8679f02d5906aded7e7740e699 | 245 | h | C | ScrollViewNest/ScrollViewNest/menuManager/HZMenuManagerReusableView.h | hmx101607/ScrollViewNest | a33ec6da2e2e39f6bcd80cc2f3c111543131a30e | [
"MIT"
] | 3 | 2019-04-26T02:22:24.000Z | 2019-10-08T01:37:42.000Z | ScrollViewNest/ScrollViewNest/menuManager/HZMenuManagerReusableView.h | hmx101607/ScrollViewNest | a33ec6da2e2e39f6bcd80cc2f3c111543131a30e | [
"MIT"
] | null | null | null | ScrollViewNest/ScrollViewNest/menuManager/HZMenuManagerReusableView.h | hmx101607/ScrollViewNest | a33ec6da2e2e39f6bcd80cc2f3c111543131a30e | [
"MIT"
] | null | null | null | //
// HZMenuManagerReusableView.h
// Pods
//
// Created by mason on 2018/5/16.
//
//
#import <UIKit/UIKit.h>
@interface HZMenuManagerReusableView : UICollectionReusableView
/** <##> */
@property (strong, nonatomic) NSString *title;
@end
| 13.611111 | 63 | 0.681633 |
6b358a3f1b9d425b4a83c5da5744cbbdd62d3ff4 | 12,239 | h | C | tinyfx.h | MilkTool/tinyfx | e67ef7f5d7d41f717683b30ec3644d3ba26dff23 | [
"MIT"
] | 60 | 2017-10-19T19:10:34.000Z | 2022-03-03T15:13:25.000Z | tinyfx.h | MilkTool/tinyfx | e67ef7f5d7d41f717683b30ec3644d3ba26dff23 | [
"MIT"
] | 38 | 2017-10-31T12:46:47.000Z | 2020-11-03T06:16:47.000Z | tinyfx.h | MilkTool/tinyfx | e67ef7f5d7d41f717683b30ec3644d3ba26dff23 | [
"MIT"
] | 6 | 2017-10-20T11:45:56.000Z | 2020-10-11T02:01:11.000Z | #pragma once
#ifdef __cplusplus
extern "C" {
#endif
#include <stddef.h>
#include <stdint.h>
#include <stdbool.h>
typedef enum tfx_buffer_flags {
TFX_BUFFER_NONE = 0,
// for index buffers: use 32-bit instead of 16-bit indices.
TFX_BUFFER_INDEX_32 = 1 << 0,
// updated regularly (once per game tick)
TFX_BUFFER_MUTABLE = 1 << 1,
// temporary (updated many times per frame)
// TFX_BUFFER_STREAM = 1 << 2
} tfx_buffer_flags;
typedef enum tfx_depth_test {
TFX_DEPTH_TEST_NONE = 0,
TFX_DEPTH_TEST_LT,
TFX_DEPTH_TEST_GT,
TFX_DEPTH_TEST_EQ
} tfx_depth_test;
#define TFX_INVALID_BUFFER tfx_buffer { 0 }
#define TFX_INVALID_TRANSIENT_BUFFER tfx_transient_buffer { 0 }
// draw state
enum {
// cull modes
TFX_STATE_CULL_CW = 1 << 0,
TFX_STATE_CULL_CCW = 1 << 1,
// depth write
TFX_STATE_DEPTH_WRITE = 1 << 2,
TFX_STATE_RGB_WRITE = 1 << 3,
TFX_STATE_ALPHA_WRITE = 1 << 4,
// blending
TFX_STATE_BLEND_ALPHA = 1 << 5,
// primitive modes
TFX_STATE_DRAW_POINTS = 1 << 6,
TFX_STATE_DRAW_LINES = 1 << 7,
TFX_STATE_DRAW_LINE_STRIP = 1 << 8,
TFX_STATE_DRAW_LINE_LOOP = 1 << 9,
TFX_STATE_DRAW_TRI_STRIP = 1 << 10,
TFX_STATE_DRAW_TRI_FAN = 1 << 11,
// misc state
TFX_STATE_MSAA = 1 << 12,
TFX_STATE_WIREFRAME = 1 << 13,
TFX_STATE_DEFAULT = 0
| TFX_STATE_CULL_CCW
| TFX_STATE_MSAA
| TFX_STATE_DEPTH_WRITE
| TFX_STATE_RGB_WRITE
| TFX_STATE_ALPHA_WRITE
| TFX_STATE_BLEND_ALPHA
};
enum {
TFX_CUBE_MAP_POSITIVE_X = 0,
TFX_CUBE_MAP_NEGATIVE_X = 1,
TFX_CUBE_MAP_POSITIVE_Y = 2,
TFX_CUBE_MAP_NEGATIVE_Y = 3,
TFX_CUBE_MAP_POSITIVE_Z = 4,
TFX_CUBE_MAP_NEGATIVE_Z = 5
};
enum {
TFX_TEXTURE_FILTER_POINT = 1 << 0,
TFX_TEXTURE_FILTER_LINEAR = 1 << 1,
//TFX_TEXTURE_FILTER_ANISOTROPIC = 1 << 2,
TFX_TEXTURE_CPU_WRITABLE = 1 << 3,
// TFX_TEXTURE_GPU_WRITABLE = 1 << 4,
TFX_TEXTURE_GEN_MIPS = 1 << 5,
TFX_TEXTURE_RESERVE_MIPS = 1 << 6,
TFX_TEXTURE_CUBE = 1 << 7,
TFX_TEXTURE_MSAA_SAMPLE = 1 << 8,
TFX_TEXTURE_MSAA_X2 = 1 << 9,
TFX_TEXTURE_MSAA_X4 = 1 << 10,
TFX_TEXTURE_EXTERNAL = 1 << 11
};
typedef enum tfx_reset_flags {
TFX_RESET_NONE = 0,
TFX_RESET_MAX_ANISOTROPY = 1 << 0,
TFX_RESET_REPORT_GPU_TIMINGS = 1 << 1,
// a basic text/image overlay for debugging.
// be aware that it's pretty slow, since it just plots pixels on cpu.
// you probably don't want to leave this on if you're not using it!
TFX_RESET_DEBUG_OVERLAY = 1 << 2,
TFX_RESET_DEBUG_OVERLAY_STATS = 1 << 3
// TFX_RESET_VR
} tfx_reset_flags;
typedef enum tfx_view_flags {
TFX_VIEW_NONE = 0,
TFX_VIEW_INVALIDATE = 1 << 0,
TFX_VIEW_FLUSH = 1 << 1,
TFX_VIEW_SORT_SEQUENTIAL = 1 << 2,
TFX_VIEW_DEFAULT = TFX_VIEW_SORT_SEQUENTIAL
} tfx_view_flags;
typedef enum tfx_format {
// color only
TFX_FORMAT_RGB565 = 0,
TFX_FORMAT_RGBA8,
TFX_FORMAT_SRGB8,
TFX_FORMAT_SRGB8_A8,
TFX_FORMAT_RGB10A2,
TFX_FORMAT_RG11B10F,
TFX_FORMAT_RGB16F,
TFX_FORMAT_RGBA16F,
// color + depth
TFX_FORMAT_RGB565_D16,
TFX_FORMAT_RGBA8_D16,
TFX_FORMAT_RGBA8_D24,
// TFX_FORMAT_RGB10A2_D16,
// TFX_FORMAT_RG11B10F_D16,
// TFX_FORMAT_RGBA16F_D16,
// single channel
TFX_FORMAT_R16F,
TFX_FORMAT_R32UI,
TFX_FORMAT_R32F,
// two channels
TFX_FORMAT_RG16F,
TFX_FORMAT_RG32F,
// depth only
TFX_FORMAT_D16,
TFX_FORMAT_D24,
TFX_FORMAT_D32,
TFX_FORMAT_D32F,
//TFX_FORMAT_D24_S8
} tfx_format;
typedef unsigned tfx_program;
typedef enum tfx_uniform_type {
TFX_UNIFORM_INT = 0,
TFX_UNIFORM_FLOAT,
TFX_UNIFORM_VEC2,
TFX_UNIFORM_VEC3,
TFX_UNIFORM_VEC4,
TFX_UNIFORM_MAT2,
TFX_UNIFORM_MAT3,
TFX_UNIFORM_MAT4
} tfx_uniform_type;
typedef enum tfx_severity {
TFX_SEVERITY_INFO,
TFX_SEVERITY_WARNING,
TFX_SEVERITY_ERROR,
TFX_SEVERITY_FATAL
} tfx_severity;
typedef struct tfx_platform_data {
bool use_gles;
int context_version;
void* (*gl_get_proc_address)(const char*);
void(*info_log)(const char* msg, tfx_severity level);
} tfx_platform_data;
typedef struct tfx_uniform {
union {
float *fdata;
int *idata;
uint8_t *data;
};
const char *name;
tfx_uniform_type type;
int count;
int last_count;
size_t size;
} tfx_uniform;
typedef struct tfx_texture {
unsigned gl_ids[2];
unsigned gl_msaa_id;
unsigned gl_idx, gl_count;
uint16_t width;
uint16_t height;
uint16_t depth;
uint16_t mip_count;
tfx_format format;
bool is_depth;
bool is_stencil;
bool dirty;
uint16_t flags, _pad0;
void *internal;
} tfx_texture;
typedef struct tfx_canvas {
// 0 = normal, 1 = msaa
unsigned gl_fbo[2];
tfx_texture attachments[8];
uint32_t allocated;
uint16_t width;
uint16_t height;
uint16_t current_width;
uint16_t current_height;
int current_mip;
//bool mipmaps;
bool msaa;
bool cube;
bool own_attachments;
bool reconfigure;
} tfx_canvas;
typedef enum tfx_component_type {
TFX_TYPE_FLOAT = 0,
TFX_TYPE_BYTE,
TFX_TYPE_UBYTE,
TFX_TYPE_SHORT,
TFX_TYPE_USHORT,
TFX_TYPE_SKIP,
} tfx_component_type;
typedef struct tfx_vertex_component {
size_t offset;
size_t size;
bool normalized;
tfx_component_type type;
} tfx_vertex_component;
typedef struct tfx_vertex_format {
// limit to 8, since we only have an 8 bit mask
tfx_vertex_component components[8];
uint8_t count, component_mask, _pad0[2];
size_t stride;
} tfx_vertex_format;
typedef struct tfx_buffer {
unsigned gl_id;
bool dirty;
bool has_format;
tfx_buffer_flags flags;
tfx_vertex_format format;
void *internal;
} tfx_buffer;
typedef struct tfx_transient_buffer {
bool has_format;
tfx_vertex_format format;
void *data;
uint16_t num;
uint32_t offset;
} tfx_transient_buffer;
typedef void (*tfx_draw_callback)(void);
typedef struct tfx_timing_info {
uint64_t time;
uint8_t id, _pad0[3];
const char *name;
} tfx_timing_info;
typedef struct tfx_stats {
uint32_t draws;
uint32_t blits;
uint32_t num_timings;
tfx_timing_info *timings;
} tfx_stats;
typedef struct tfx_caps {
bool compute;
bool float_canvas;
bool multisample;
bool debug_marker;
bool debug_output;
bool memory_info;
bool instancing;
bool seamless_cubemap;
bool anisotropic_filtering;
bool multibind;
} tfx_caps;
// TODO
// #define TFX_API __attribute__ ((visibility("default")))
#define TFX_API
// bg_fg: 2x 8 bit palette colors. standard palette matches vga.
// bg_fg = (bg << 8) | fg, assuming little endian
TFX_API void tfx_debug_print(const int baserow, const int basecol, const uint16_t bg_fg, const int auto_wrap, const char *str);
TFX_API void tfx_debug_blit_rgba(const int x, const int y, const int w, const int h, const uint32_t *pixels);
// each pixel is an 8-bit palette index (standard palette matches vga, shared with text)
TFX_API void tfx_debug_blit_pal(const int x, const int y, const int w, const int h, const uint8_t *pixels);
// note: doesn't copy! make sure to keep this palette in memory yourself.
// pass NULL to reset to default palette. expects ABGR input.
TFX_API void tfx_debug_set_palette(const uint32_t *palette);
TFX_API void tfx_set_platform_data(tfx_platform_data pd);
TFX_API tfx_caps tfx_get_caps();
TFX_API void tfx_dump_caps();
TFX_API void tfx_reset(uint16_t width, uint16_t height, tfx_reset_flags flags);
TFX_API void tfx_shutdown();
TFX_API tfx_vertex_format tfx_vertex_format_start();
TFX_API void tfx_vertex_format_add(tfx_vertex_format *fmt, uint8_t slot, size_t count, bool normalized, tfx_component_type type);
TFX_API void tfx_vertex_format_end(tfx_vertex_format *fmt);
TFX_API size_t tfx_vertex_format_offset(tfx_vertex_format *fmt, uint8_t slot);
TFX_API uint32_t tfx_transient_buffer_get_available(tfx_vertex_format *fmt);
TFX_API tfx_transient_buffer tfx_transient_buffer_new(tfx_vertex_format *fmt, uint16_t num_verts);
TFX_API tfx_buffer tfx_buffer_new(const void *data, size_t size, tfx_vertex_format *format, tfx_buffer_flags flags);
TFX_API void tfx_buffer_update(tfx_buffer *buf, const void *data, uint32_t offset, uint32_t size);
TFX_API void tfx_buffer_free(tfx_buffer *buf);
TFX_API tfx_texture tfx_texture_new(uint16_t w, uint16_t h, uint16_t layers, const void *data, tfx_format format, uint16_t flags);
TFX_API void tfx_texture_update(tfx_texture *tex, const void *data);
TFX_API void tfx_texture_free(tfx_texture *tex);
TFX_API tfx_texture tfx_get_texture(tfx_canvas *canvas, uint8_t index);
TFX_API tfx_canvas tfx_canvas_new(uint16_t w, uint16_t h, tfx_format format, uint16_t flags);
TFX_API void tfx_canvas_free(tfx_canvas *c);
TFX_API tfx_canvas tfx_canvas_attachments_new(bool claim_attachments, int count, tfx_texture *attachments);
TFX_API void tfx_view_set_name(uint8_t id, const char *name);
TFX_API void tfx_view_set_canvas(uint8_t id, tfx_canvas *canvas, int layer);
TFX_API void tfx_view_set_flags(uint8_t id, tfx_view_flags flags);
TFX_API void tfx_view_set_clear_color(uint8_t id, unsigned color);
TFX_API void tfx_view_set_clear_depth(uint8_t id, float depth);
TFX_API void tfx_view_set_depth_test(uint8_t id, tfx_depth_test mode);
TFX_API void tfx_view_set_scissor(uint8_t id, uint16_t x, uint16_t y, uint16_t w, uint16_t h);
// order: xywh, in pixels
TFX_API void tfx_view_set_viewports(uint8_t id, int count, uint16_t **viewports);
TFX_API void tfx_view_set_instance_mul(uint8_t id, unsigned factor);
TFX_API tfx_canvas *tfx_view_get_canvas(uint8_t id);
TFX_API uint16_t tfx_view_get_width(uint8_t id);
TFX_API uint16_t tfx_view_get_height(uint8_t id);
TFX_API void tfx_view_get_dimensions(uint8_t id, uint16_t *w, uint16_t *h);
// TFX_API void tfx_view_set_transform(uint8_t id, float *view, float *proj_l, float *proj_r);
// you may pass -1 for attrib_count to use a null-terminated list for attribs
TFX_API tfx_program tfx_program_new(const char *vss, const char *fss, const char *attribs[], const int attrib_count);
// you may pass -1 for attrib_count to use a null-terminated list for attribs
TFX_API tfx_program tfx_program_len_new(const char *vss, const int _vs_len, const char *fss, const int _fs_len, const char *attribs[], const int attrib_count);
// you may pass -1 for attrib_count to use a null-terminated list for attribs
TFX_API tfx_program tfx_program_gs_len_new(const char *_gss, const int _gs_len, const char *_vss, const int _vs_len, const char *_fss, const int _fs_len, const char *attribs[], const int attrib_count);
// you may pass -1 for attrib_count to use a null-terminated list for attribs
TFX_API tfx_program tfx_program_gs_new(const char *gss, const char *vss, const char *fss, const char *attribs[], const int attrib_count);
TFX_API tfx_program tfx_program_cs_len_new(const char *css, const int _cs_len);
TFX_API tfx_program tfx_program_cs_new(const char *css);
// TODO: add tfx_program_free(tfx_program). they are currently cleaned up with tfx_shutdown.
TFX_API tfx_uniform tfx_uniform_new(const char *name, tfx_uniform_type type, int count);
// TFX_API void tfx_set_transform(float *mtx, uint8_t count);
TFX_API void tfx_set_transient_buffer(tfx_transient_buffer tb);
// pass -1 to update maximum uniform size
TFX_API void tfx_set_uniform(tfx_uniform *uniform, const float *data, const int count);
// pass -1 to update maximum uniform size
TFX_API void tfx_set_uniform_int(tfx_uniform *uniform, const int *data, const int count);
TFX_API void tfx_set_callback(tfx_draw_callback cb);
TFX_API void tfx_set_state(uint64_t flags);
TFX_API void tfx_set_scissor(uint16_t x, uint16_t y, uint16_t w, uint16_t h);
TFX_API void tfx_set_texture(tfx_uniform *uniform, tfx_texture *tex, uint8_t slot);
TFX_API void tfx_set_buffer(tfx_buffer *buf, uint8_t slot, bool write);
TFX_API void tfx_set_image(tfx_uniform *uniform, tfx_texture *tex, uint8_t slot, uint8_t mip, bool write);
TFX_API void tfx_set_vertices(tfx_buffer *vbo, int count);
TFX_API void tfx_set_indices(tfx_buffer *ibo, int count, int offset);
TFX_API void tfx_dispatch(uint8_t id, tfx_program program, uint32_t x, uint32_t y, uint32_t z);
// TFX_API void tfx_submit_ordered(uint8_t id, tfx_program program, uint32_t depth, bool retain);
TFX_API void tfx_submit(uint8_t id, tfx_program program, bool retain);
// submit an empty draw. useful for using draw callbacks and ensuring views are processed.
TFX_API void tfx_touch(uint8_t id);
TFX_API void tfx_blit(uint8_t src, uint8_t dst, uint16_t x, uint16_t y, uint16_t w, uint16_t h, int mip);
TFX_API tfx_stats tfx_frame();
#undef TFX_API
#ifdef __cplusplus
}
#endif
| 31.30179 | 201 | 0.779802 |
5fd99190e0a0f1a86673f910aea685ec8001efff | 7,244 | h | C | vendor/intel/avcstreamoutdemo.h | lindongw/libva-utils | 3bbb0cc7a24d6cdcdc8f92f2a556cdaf985ee1df | [
"MIT"
] | 88 | 2018-01-26T21:07:17.000Z | 2022-03-25T08:12:42.000Z | vendor/intel/avcstreamoutdemo.h | lindongw/libva-utils | 3bbb0cc7a24d6cdcdc8f92f2a556cdaf985ee1df | [
"MIT"
] | 109 | 2018-01-25T05:18:06.000Z | 2022-03-28T04:56:49.000Z | vendor/intel/avcstreamoutdemo.h | lindongw/libva-utils | 3bbb0cc7a24d6cdcdc8f92f2a556cdaf985ee1df | [
"MIT"
] | 85 | 2018-02-09T15:05:16.000Z | 2022-03-17T04:06:12.000Z | /*
* Copyright (c) 2018 Intel Corporation. All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sub license, 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 (including the
* next paragraph) 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 NON-INFRINGEMENT.
* IN NO EVENT SHALL PRECISION INSIGHT AND/OR ITS SUPPLIERS BE LIABLE FOR
* ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/**
* \file avcstreamoutdemo.h
*
* This file contains the decode streamout layout.
*/
#ifndef _AVC_STREAMOUT_DEMO_H_
#define _AVC_STREAMOUT_DEMO_H_
typedef signed dw;
/*
* avc streamout layout
*/
typedef struct {
// dw 0
union {
struct {
dw InterMbMode : 2; // Valid only if IntraMbFlag is inter.
dw MbSkipFlag : 1; // Cuurently always set to 0
dw : 1; // MBZ
dw IntraMbMode : 2; // Valid for Inter MB, Used in conjunction with MbType
dw : 1; // MBZ
dw MbPolarity : 1; // FieldMB polarity
dw MbType5Bits : 5; // Matches best MB mode. In H.264 spec: Table 7-11 for Intra; Table 7-14 for Inter.
dw IntraMbFlag : 1; // Set if MB is intra, unset if MB is inter
dw MbFieldFlag : 1; // Set if field MB, unset if frame MB
dw Transform8x8Flag : 1; // Set if current MB uses 8x8 transforms
dw : 1; // MBZ
dw CodedPatternDC : 3; // AVC Only. Indicates whether DC coeffs are sent. Y is most significant bit.
dw EdgeFilterFlag : 3; // AVC.
dw : 1; // MBZ
dw PackedMvNum : 8; // Debug only. Specifies number of MVs in packed motion vector form
};
struct {
dw Value;
};
} DW0;
// dw 1
union {
struct {
dw MbXCnt : 16; // Horizontal Origin of MB in dest piture in units of MBs
dw MbYCnt : 16; // Vertical Origin of MB in dest piture in units of MBs
};
struct {
dw Value;
};
} DW1;
// dw 2
union {
struct {
dw CbpAcY : 16; // Coded block pattern for Y.
dw CbpAcU : 4; // Coded block pattern for U
dw CbpAcV : 4; // Coded block pattern for V
dw : 6; // Reserved
dw LastMBOfSliceFlag : 1; // Indicates current MB is last in slice. Data not right
dw ConcealMBFlag : 1; // Specifies in MB is a conceal MB.
};
struct {
dw Value;
};
} DW2;
// dw 3
union {
struct {
dw QpPrimeY : 7; // AVC: Per-MB QP for luma.
dw QScaleType : 1; // MPEG2 only
dw MbClock16 : 8; // MB compute clocks in 16-clock units
dw NzCoefCountMB : 9; // All coded coefficients in MB
dw : 3; // Reserved
dw Skip8x8Pattern : 4; // AVC Only. Indicates which of the 8x8 sub-blocks uses predicted MVs
};
struct {
dw Value;
};
} DW3;
// dw 4
union {
struct {
dw LumaIntraPredModes0 : 16; // AVC only
dw LumaIntraPredModes1 : 16; // AVC only
} Intra;
struct {
dw SubMbShape : 8; // Indicates sub-block partitioning for each 8x8 sub-block
dw SubMbPredModes : 8; // Indicates prediction mode for each 8x8 sub-block
dw : 16; // Reserved
} Inter;
struct {
dw Value;
};
} DW4;
// dw 5
union {
struct {
dw LumaIntraPredModes2 : 16; // AVC only
dw LumaIntraPredModes3 : 16; // AVC only
} Intra;
struct {
dw FrameStorIDL0_0 : 8;
dw FrameStorIDL0_1 : 8;
dw FrameStorIDL0_2 : 8;
dw FrameStorIDL0_3 : 8;
} Inter;
struct {
dw Value;
};
} DW5;
// dw 6
union {
struct {
dw MbIntraStruct : 8; // Indicates which neighbours can be used for intra-prediction
dw : 24; // Reserved
} Intra;
struct {
dw FrameStorIDL1_0 : 8;
dw FrameStorIDL1_1 : 8;
dw FrameStorIDL1_2 : 8;
dw FrameStorIDL1_3 : 8;
} Inter;
struct {
dw Value;
};
} DW6;
// dw 7
union {
struct {
dw SubBlockCodeTypeY0 : 2; // VC-1. Specifies if 8x8, 8x4, 4x8, 4x4
dw SubBlockCodeTypeY1 : 2; // VC-1. Specifies if 8x8, 8x4, 4x8, 4x4
dw SubBlockCodeTypeY2 : 2; // VC-1. Specifies if 8x8, 8x4, 4x8, 4x4
dw SubBlockCodeTypeY3 : 2; // VC-1. Specifies if 8x8, 8x4, 4x8, 4x4
dw SubBlockCodeTypeU : 2; // VC-1. Specifies if 8x8, 8x4, 4x8, 4x4
dw SubBlockCodeTypeV : 2; // VC-1. Specifies if 8x8, 8x4, 4x8, 4x4
dw : 8;
dw MvFieldSelect : 4; // Field polatity for VC-1 and MPEG2
dw : 8;
};
struct {
dw Value;
};
} DW7;
// dw 8-15 for inter MBs only
union {
struct {
dw MvFwd_x : 16; // x-component of fwd MV for 8x8 or 4x4 sub-block
dw MvFwd_y : 16; // y-component of fwd MV for 8x8 or 4x4 sub-block
dw MvBwd_x : 16; // x-component of bwd MV for 8x8 or 4x4 sub-block
dw MvBwd_y : 16; // y-component of bwd MV for 8x8 or 4x4 sub-block
};
struct {
dw Value[2];
};
} QW8[4];
} VADecStreamOutData;
#endif /*_AVC_STREAMOUT_DEMO_H_*/
| 38.328042 | 132 | 0.485643 |
7584b079299e7eebcaaf7950dc82b037731c9721 | 988 | h | C | ert/tests/tests_ex.h | thomasten/edgelessrt | 2b42deefdaaa75dbc6568ff4f8152b6ae74862bf | [
"MIT"
] | 101 | 2020-06-19T09:14:41.000Z | 2022-03-28T03:14:09.000Z | ert/tests/tests_ex.h | thomasten/edgelessrt | 2b42deefdaaa75dbc6568ff4f8152b6ae74862bf | [
"MIT"
] | 24 | 2020-07-20T09:45:44.000Z | 2022-01-10T09:56:46.000Z | ert/tests/tests_ex.h | thomasten/edgelessrt | 2b42deefdaaa75dbc6568ff4f8152b6ae74862bf | [
"MIT"
] | 14 | 2020-07-18T17:17:35.000Z | 2022-01-06T03:29:06.000Z | #pragma once
#include <openenclave/internal/tests.h>
#define ASSERT_THROW(exp, exc) \
try \
{ \
exp; \
OE_TEST(false && "did not throw"); \
} \
catch (exc) \
{ \
} \
catch (...) \
{ \
OE_TEST(false && "threw different type"); \
}
#define ASSERT_NO_THROW(exp) \
try \
{ \
exp; \
} \
catch (...) \
{ \
OE_TEST(false && "threw"); \
}
| 35.285714 | 51 | 0.192308 |
559ff112b24bfb5c3e780b5cf9f1f31d967f7b73 | 300 | h | C | WVRProgram/WVRProgram/Classes/Home/BrandZone/WVRBrandZoneViewCProtocol.h | portal-io/portal-ios-business | e8c3776b5a2e81c152c41fbf78fe33f48ed64d07 | [
"MIT"
] | null | null | null | WVRProgram/WVRProgram/Classes/Home/BrandZone/WVRBrandZoneViewCProtocol.h | portal-io/portal-ios-business | e8c3776b5a2e81c152c41fbf78fe33f48ed64d07 | [
"MIT"
] | null | null | null | WVRProgram/WVRProgram/Classes/Home/BrandZone/WVRBrandZoneViewCProtocol.h | portal-io/portal-ios-business | e8c3776b5a2e81c152c41fbf78fe33f48ed64d07 | [
"MIT"
] | null | null | null | //
// WVRBrandZoneViewCProtocol.h
// WhaleyVR
//
// Created by qbshen on 2017/7/25.
// Copyright © 2017年 Snailvr. All rights reserved.
//
#import "WVRCollectionViewProtocol.h"
@protocol WVRBrandZoneViewCProtocol <WVRCollectionViewProtocol>
- (void) updateWithDataSource:(id)originData;
@end
| 17.647059 | 63 | 0.75 |
1d90b461ff10231a84dc589d9fafe7d03e746f93 | 5,457 | h | C | src/net/ws_cli/ws_types.h | panda-factory/cpp-improvement-tutorial | 6e9256d5cdab46e320a9aab0a29ccd1af4ec5079 | [
"BSD-2-Clause"
] | null | null | null | src/net/ws_cli/ws_types.h | panda-factory/cpp-improvement-tutorial | 6e9256d5cdab46e320a9aab0a29ccd1af4ec5079 | [
"BSD-2-Clause"
] | null | null | null | src/net/ws_cli/ws_types.h | panda-factory/cpp-improvement-tutorial | 6e9256d5cdab46e320a9aab0a29ccd1af4ec5079 | [
"BSD-2-Clause"
] | null | null | null | //
// Created by admin on 2021/2/6.
//
#ifndef TEST_WS_TYPES_H
#define TEST_WS_TYPES_H
#include <functional>
#include "net/ws_cli/ws_state.h"
namespace net {
namespace ws {
constexpr int WS_DEFAULT_CONNECT_TIMEOUT = 60;
constexpr int HTTP_STATUS_SWITCHING_PROTOCOLS_101 = 101;
constexpr int WS_HDR_BASE_SIZE = 2;
constexpr int WS_HDR_PAYLOAD_LEN_SIZE = 8;
constexpr int WS_HDR_MASK_SIZE = 4;
constexpr int WS_HDR_MIN_SIZE = WS_HDR_BASE_SIZE;
constexpr int WS_HDR_MAX_SIZE = (WS_HDR_BASE_SIZE + WS_HDR_PAYLOAD_LEN_SIZE + WS_HDR_MASK_SIZE);
enum WSOpcode {
CONTINUATION_0X0 = 0x0,
TEXT_0X1 = 0x1,
BINARY_0X2 = 0x2,
// 0x3 - 0x7 Reserved for further non-control frames.
NON_CONTROL_RSV_0X3 = 0x3,
NON_CONTROL_RSV_0X4 = 0x4,
NON_CONTROL_RSV_0X5 = 0x5,
NON_CONTROL_RSV_0X6 = 0x6,
NON_CONTROL_RSV_0X7 = 0x7,
CLOSE_0X8 = 0x8,
PING_0X9 = 0x9,
PONG_0XA = 0xA,
// 0xB - 0xF are reserved for further control frames.
CONTROL_RSV_0XB = 0xB,
CONTROL_RSV_0XC = 0xC,
CONTROL_RSV_0XD = 0xD,
CONTROL_RSV_0XE = 0xE,
CONTROL_RSV_0XF = 0xF
};
///
/// Websocket header structure.
///
///
/// Websocket protocol RFC 6455: http://tools.ietf.org/html/rfc6455
///
/// 0 1 2 3
/// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
/// +-+-+-+-+-------+-+-------------+-------------------------------+
/// |F|R|R|R| opcode|M| Payload len | Extended payload length |
/// |I|S|S|S| (4) |A| (7) | (16/64) |
/// |N|V|V|V| |S| | (if payload len==126/127) |
/// | |1|2|3| |K| | |
/// +-+-+-+-+-------+-+-------------+ - - - - - - - - - - - - - - - +
/// | Extended payload length continued, if payload len == 127 |
/// + - - - - - - - - - - - - - - - +-------------------------------+
/// | |Masking-key, if MASK set to 1 |
/// +-------------------------------+-------------------------------+
/// | Masking-key (continued) | Payload Data |
/// +-------------------------------- - - - - - - - - - - - - - - - +
/// : Payload Data continued ... :
/// + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +
/// | Payload Data continued ... |
/// +---------------------------------------------------------------+
///
#pragma pack(push,1)
struct WSHeader {
uint8_t fin : 1; //! Indicates that this is the final fragment in a message.
uint8_t rsv1 : 1; ///< Reserved bit 1 for extensions.
uint8_t rsv2 : 1; ///< Reserved bit 2 for extensions.
uint8_t rsv3 : 1; ///< Reserved bit 3 for extensions.
uint8_t opcode : 4; ///< Operation code.
uint8_t maskBit : 1; ///< If this frame is masked this bit is set.
uint8_t payloadLen : 7; ///< Length of the payload.
uint64_t exPayloadLen; ///< Length of the payload.
uint32_t mask; ///< Masking key for the payload.
};
#pragma pack(pop)
#define WS_IS_CLOSE_STATUS_NOT_USED(code) \
(((int)code < 1000) || ((int)code > 4999))
#define WS_MAX_PAYLOAD_LEN 0x7FFFFFFFFFFFFFFF
#define WS_CONTROL_MAX_PAYLOAD_LEN 125
/// Status codes in the range 3000-3999 are reserved for use by
/// libraries, frameworks, and applications. These status codes are
/// registered directly with IANA. The interpretation of these codes
/// is undefined by this protocol.
#define WS_IS_CLOSE_STATUS_IANA_RESERVED(code) \
(((int)code >= 3000) && ((int)code <= 3999))
/// Status codes in the range 4000-4999 are reserved for private use
/// and thus can't be registered. Such codes can be used by prior
/// agreements between WebSocket applications. The interpretation of
/// these codes is undefined by this protocol.
#define WS_IS_CLOSE_STATUS_PRIVATE_USE(code) \
(((int)code >= 4000) && ((int)code <= 4999))
/// Has the peer sent a valid close code?
#define WS_IS_PEER_CLOSE_STATUS_VALID(code) \
(WS_IS_CLOSE_STATUS_IANA_RESERVED(code) \
|| (WS_IS_CLOSE_STATUS_PRIVATE_USE(code)) \
|| (code == WSCloseStatus::NORMAL_1000) \
|| (code == WSCloseStatus::GOING_AWAY_1001) \
|| (code == WSCloseStatus::PROTOCOL_ERR_1002) \
|| (code == WSCloseStatus::UNSUPPORTED_DATA_1003) \
|| (code == WSCloseStatus::INCONSISTENT_DATA_1007) \
|| (code == WSCloseStatus::POLICY_VIOLATION_1008) \
|| (code == WSCloseStatus::MESSAGE_TOO_BIG_1009) \
|| (code == WSCloseStatus::EXTENSION_NOT_NEGOTIATED_1010) \
|| (code == WSCloseStatus::UNEXPECTED_CONDITION_1011))
using NoCopyCleanup = void (*)(const void *data, uint64_t datalen, void *extra);
using CloseCallback = void (*)(WSCloseStatus status, const char *reason, size_t reason_len, void *arg);
using MsgBeginCallback = void (*)(void *arg);
using MsgEndCallback = void (*)(void *arg);
using MsgFrameBeginCallback = void (*)(void *arg);
using MsgFrameDataCallback = void (*)(char *payload,
uint64_t len, void *arg);
using MsgCallback = void (*)(char *msg, uint64_t len,
int binary, void *arg);
using MsgFrameEndCallback = void (*)(void *arg);
using ConnectHandle = std::function<void(void *arg)>;
} // namespace ws
} // namespace net
#endif //TEST_WS_TYPES_H
| 41.030075 | 103 | 0.568261 |
8a64c87b4828bd0ca8a9e2bef8a5be347c62e236 | 1,075 | h | C | src/qt/creditaddressvalidator.h | Ankh-Trust/credit-core | fa6fd67bdc9846cc40ee24f9a64e610e634b9356 | [
"MIT"
] | 2 | 2019-10-31T11:56:31.000Z | 2019-11-02T08:48:45.000Z | src/qt/creditaddressvalidator.h | Ankh-fdn/credit-core | fa6fd67bdc9846cc40ee24f9a64e610e634b9356 | [
"MIT"
] | 2 | 2019-11-22T18:49:20.000Z | 2020-10-06T11:44:46.000Z | src/qt/creditaddressvalidator.h | Ankh-fdn/credit-core | fa6fd67bdc9846cc40ee24f9a64e610e634b9356 | [
"MIT"
] | 1 | 2020-06-09T16:15:27.000Z | 2020-06-09T16:15:27.000Z | // Copyright (c) 2016-2019 Duality Blockchain Solutions Developers
// Copyright (c) 2014-2019 The Dash Core Developers
// Copyright (c) 2009-2019 The Bitcoin Developers
// Copyright (c) 2009-2019 Satoshi Nakamoto
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef CREDIT_QT_CREDITADDRESSVALIDATOR_H
#define CREDIT_QT_CREDITADDRESSVALIDATOR_H
#include <QValidator>
/** Base58 entry widget validator, checks for valid characters and
* removes some whitespace.
*/
class CreditAddressEntryValidator : public QValidator
{
Q_OBJECT
public:
explicit CreditAddressEntryValidator(QObject* parent);
State validate(QString& input, int& pos) const;
};
/** Credit address widget validator, checks for a valid Credit address.
*/
class CreditAddressCheckValidator : public QValidator
{
Q_OBJECT
public:
explicit CreditAddressCheckValidator(QObject* parent);
State validate(QString& input, int& pos) const;
};
#endif // CREDIT_QT_CREDITADDRESSVALIDATOR_H
| 27.564103 | 71 | 0.775814 |
ce8492c26f8f08f3072ad089633ad1da0dafe4e8 | 1,647 | h | C | usr/libexec/appstored/Migrator.h | lechium/tvOS145Headers | 9940da19adb0017f8037853e9cfccbe01b290dd5 | [
"MIT"
] | 5 | 2021-04-29T04:31:43.000Z | 2021-08-19T18:59:58.000Z | usr/libexec/appstored/Migrator.h | lechium/tvOS145Headers | 9940da19adb0017f8037853e9cfccbe01b290dd5 | [
"MIT"
] | null | null | null | usr/libexec/appstored/Migrator.h | lechium/tvOS145Headers | 9940da19adb0017f8037853e9cfccbe01b290dd5 | [
"MIT"
] | 1 | 2022-03-19T11:16:23.000Z | 2022-03-19T11:16:23.000Z | //
// Generated by classdumpios 1.0.1 (64 bit) (iOS port by DreamDevLost)(Debug version compiled Sep 26 2020 13:48:20).
//
// Copyright (C) 1997-2019 Steve Nygard.
//
#import <objc/NSObject.h>
@class MigratorConfigurationStore, NSMutableArray;
@protocol OS_dispatch_queue;
@interface Migrator : NSObject
{
MigratorConfigurationStore *_configurationStore; // 8 = 0x8
NSObject<OS_dispatch_queue> *_dispatchQueue; // 16 = 0x10
NSMutableArray *_migrations; // 24 = 0x18
}
+ (_Bool)needsMigration; // IMP=0x0000000100171618
+ (_Bool)needsInitialMigration; // IMP=0x0000000100171580
+ (id)migrationsNeeded; // IMP=0x0000000100171534
+ (id)sharedInstance; // IMP=0x0000000100171140
- (void).cxx_destruct; // IMP=0x0000000100172d38
- (void)_runMigrationsWhenReady; // IMP=0x0000000100172bd8
- (void)_queueMigrationWithConfiguration:(id)arg1; // IMP=0x0000000100172a28
- (void)_queueMigration:(id)arg1 persist:(_Bool)arg2; // IMP=0x00000001001728c8
- (void)_queueMigration:(id)arg1; // IMP=0x00000001001728b8
- (_Bool)_setupMigrationFollowingMigratorComplete:(unsigned long long)arg1; // IMP=0x000000010017242c
- (void)_performMigration; // IMP=0x0000000100172014
- (void)_loadBagAndPerformMigration; // IMP=0x0000000100171e4c
- (void)_boostrapWhenReady; // IMP=0x0000000100171c2c
- (void)_handleMonitorStateDidChangeNotification:(id)arg1; // IMP=0x00000001001719fc
- (void)_handleNetworkStateDidChangeNotification:(id)arg1; // IMP=0x00000001001717ec
- (_Bool)performMigration:(unsigned long long)arg1 clientID:(id)arg2; // IMP=0x0000000100171684
- (void)dealloc; // IMP=0x0000000100171478
- (id)init; // IMP=0x00000001001711ac
@end
| 41.175 | 120 | 0.775349 |
ef2cd1abf56db16472cea32e80d39f159050f81e | 12,122 | c | C | cryptl30/lib_skip.c | ab300819/applied-cryptography | 3fddc4cda2e1874e978608259034d36c60a4dbba | [
"MIT",
"Unlicense"
] | 1 | 2021-04-17T05:01:00.000Z | 2021-04-17T05:01:00.000Z | cryptl30/lib_skip.c | ab300819/applied-cryptography | 3fddc4cda2e1874e978608259034d36c60a4dbba | [
"MIT",
"Unlicense"
] | null | null | null | cryptl30/lib_skip.c | ab300819/applied-cryptography | 3fddc4cda2e1874e978608259034d36c60a4dbba | [
"MIT",
"Unlicense"
] | null | null | null | /****************************************************************************
* *
* cryptlib Skipjack Encryption Routines *
* Copyright Peter Gutmann 1992-1998 *
* *
****************************************************************************/
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include "crypt.h"
#include "cryptctx.h"
/* Size of the Skipjack block and key size */
#define SKIPJACK_KEYSIZE 10
#define SKIPJACK_BLOCKSIZE 8
/* Prototypes for functions in crypt/skipjack.c */
void skipjackMakeKey( BYTE key[ SKIPJACK_KEYSIZE ],
BYTE tab[ SKIPJACK_KEYSIZE ][ 256 ]);
void skipjackEncrypt( BYTE tab[ SKIPJACK_KEYSIZE ][ 256 ],
BYTE in[ SKIPJACK_BLOCKSIZE ],
BYTE out[ SKIPJACK_BLOCKSIZE ] );
void skipjackDecrypt( BYTE tab[ SKIPJACK_KEYSIZE ][ 256 ],
BYTE in[ SKIPJACK_BLOCKSIZE ],
BYTE out[ SKIPJACK_BLOCKSIZE ] );
/****************************************************************************
* *
* Skipjack Self-test Routines *
* *
****************************************************************************/
/* Skipjack test vectors from the NSA Skipjack specification */
static const struct SKIPJACK_TEST {
const BYTE key[ 10 ];
const BYTE plainText[ 8 ];
const BYTE cipherText[ 8 ];
} testSkipjack[] = {
{ { 0x00, 0x99, 0x88, 0x77, 0x66, 0x55, 0x44, 0x33, 0x22, 0x11 },
{ 0x33, 0x22, 0x11, 0x00, 0xDD, 0xCC, 0xBB, 0xAA },
{ 0x25, 0x87, 0xCA, 0xE2, 0x7A, 0x12, 0xD3, 0x00 } }
};
/* Test the Skipjack code against the Skipjack test vectors */
int skipjackSelfTest( void )
{
BYTE temp[ SKIPJACK_BLOCKSIZE ];
BYTE sjKey[ 10 ][ 256 ];
int i;
for( i = 0; i < sizeof( testSkipjack ) / sizeof( struct SKIPJACK_TEST ); i++ )
{
memcpy( temp, testSkipjack[ i ].plainText, SKIPJACK_BLOCKSIZE );
skipjackMakeKey( ( BYTE * ) testSkipjack[ i ].key, sjKey );
skipjackEncrypt( sjKey, temp, temp );
if( memcmp( testSkipjack[ i ].cipherText, temp, SKIPJACK_BLOCKSIZE ) )
return( CRYPT_ERROR );
}
return( CRYPT_OK );
}
/****************************************************************************
* *
* Init/Shutdown Routines *
* *
****************************************************************************/
/* Perform init and shutdown actions on an encryption context */
int skipjackInit( CRYPT_INFO *cryptInfo )
{
int status;
/* Allocate memory for the key within the crypt context and set up any
pointers we need */
if( ( status = krnlMemalloc( &cryptInfo->ctxConv.key, SKIPJACK_KEYSIZE * 256 ) ) != CRYPT_OK )
return( status );
cryptInfo->ctxConv.keyLength = SKIPJACK_KEYSIZE * 256;
return( CRYPT_OK );
}
int skipjackEnd( CRYPT_INFO *cryptInfo )
{
/* Free any allocated memory */
krnlMemfree( &cryptInfo->ctxConv.key );
return( CRYPT_OK );
}
/****************************************************************************
* *
* Skipjack En/Decryption Routines *
* *
****************************************************************************/
/* Encrypt/decrypt data in ECB mode */
int skipjackEncryptECB( CRYPT_INFO *cryptInfo, BYTE *buffer, int noBytes )
{
int blockCount = noBytes / SKIPJACK_BLOCKSIZE;
while( blockCount-- )
{
/* Encrypt a block of data */
skipjackEncrypt( cryptInfo->ctxConv.key, buffer, buffer );
/* Move on to next block of data */
buffer += SKIPJACK_BLOCKSIZE;
}
return( CRYPT_OK );
}
int skipjackDecryptECB( CRYPT_INFO *cryptInfo, BYTE *buffer, int noBytes )
{
int blockCount = noBytes / SKIPJACK_BLOCKSIZE;
while( blockCount-- )
{
/* Decrypt a block of data */
skipjackDecrypt( cryptInfo->ctxConv.key, buffer, buffer );
/* Move on to next block of data */
buffer += SKIPJACK_BLOCKSIZE;
}
return( CRYPT_OK );
}
/* Encrypt/decrypt data in CBC mode */
int skipjackEncryptCBC( CRYPT_INFO *cryptInfo, BYTE *buffer, int noBytes )
{
int blockCount = noBytes / SKIPJACK_BLOCKSIZE;
while( blockCount-- )
{
int i;
/* XOR the buffer contents with the IV */
for( i = 0; i < SKIPJACK_BLOCKSIZE; i++ )
buffer[ i ] ^= cryptInfo->ctxConv.currentIV[ i ];
/* Encrypt a block of data */
skipjackEncrypt( cryptInfo->ctxConv.key, buffer, buffer );
/* Shift ciphertext into IV */
memcpy( cryptInfo->ctxConv.currentIV, buffer, SKIPJACK_BLOCKSIZE );
/* Move on to next block of data */
buffer += SKIPJACK_BLOCKSIZE;
}
return( CRYPT_OK );
}
int skipjackDecryptCBC( CRYPT_INFO *cryptInfo, BYTE *buffer, int noBytes )
{
BYTE temp[ SKIPJACK_BLOCKSIZE ];
int blockCount = noBytes / SKIPJACK_BLOCKSIZE;
while( blockCount-- )
{
int i;
/* Save the ciphertext */
memcpy( temp, buffer, SKIPJACK_BLOCKSIZE );
/* Decrypt a block of data */
skipjackDecrypt( cryptInfo->ctxConv.key, buffer, buffer );
/* XOR the buffer contents with the IV */
for( i = 0; i < SKIPJACK_BLOCKSIZE; i++ )
buffer[ i ] ^= cryptInfo->ctxConv.currentIV[ i ];
/* Shift the ciphertext into the IV */
memcpy( cryptInfo->ctxConv.currentIV, temp, SKIPJACK_BLOCKSIZE );
/* Move on to next block of data */
buffer += SKIPJACK_BLOCKSIZE;
}
/* Clear the temporary buffer */
zeroise( temp, SKIPJACK_BLOCKSIZE );
return( CRYPT_OK );
}
/* Encrypt/decrypt data in CFB mode */
int skipjackEncryptCFB( CRYPT_INFO *cryptInfo, BYTE *buffer, int noBytes )
{
int i, ivCount = cryptInfo->ctxConv.ivCount;
/* If there's any encrypted material left in the IV, use it now */
if( ivCount )
{
int bytesToUse;
/* Find out how much material left in the encrypted IV we can use */
bytesToUse = SKIPJACK_BLOCKSIZE - ivCount;
if( noBytes < bytesToUse )
bytesToUse = noBytes;
/* Encrypt the data */
for( i = 0; i < bytesToUse; i++ )
buffer[ i ] ^= cryptInfo->ctxConv.currentIV[ i + ivCount ];
memcpy( cryptInfo->ctxConv.currentIV + ivCount, buffer, bytesToUse );
/* Adjust the byte count and buffer position */
noBytes -= bytesToUse;
buffer += bytesToUse;
ivCount += bytesToUse;
}
while( noBytes )
{
ivCount = ( noBytes > SKIPJACK_BLOCKSIZE ) ? SKIPJACK_BLOCKSIZE : noBytes;
/* Encrypt the IV */
skipjackEncrypt( cryptInfo->ctxConv.key, cryptInfo->ctxConv.currentIV,
cryptInfo->ctxConv.currentIV );
/* XOR the buffer contents with the encrypted IV */
for( i = 0; i < ivCount; i++ )
buffer[ i ] ^= cryptInfo->ctxConv.currentIV[ i ];
/* Shift the ciphertext into the IV */
memcpy( cryptInfo->ctxConv.currentIV, buffer, ivCount );
/* Move on to next block of data */
noBytes -= ivCount;
buffer += ivCount;
}
/* Remember how much of the IV is still available for use */
cryptInfo->ctxConv.ivCount = ( ivCount % SKIPJACK_BLOCKSIZE );
return( CRYPT_OK );
}
/* Decrypt data in CFB mode. Note that the transformation can be made
faster (but less clear) with temp = buffer, buffer ^= iv, iv = temp
all in one loop */
int skipjackDecryptCFB( CRYPT_INFO *cryptInfo, BYTE *buffer, int noBytes )
{
BYTE temp[ SKIPJACK_BLOCKSIZE ];
int i, ivCount = cryptInfo->ctxConv.ivCount;
/* If there's any encrypted material left in the IV, use it now */
if( ivCount )
{
int bytesToUse;
/* Find out how much material left in the encrypted IV we can use */
bytesToUse = SKIPJACK_BLOCKSIZE - ivCount;
if( noBytes < bytesToUse )
bytesToUse = noBytes;
/* Decrypt the data */
memcpy( temp, buffer, bytesToUse );
for( i = 0; i < bytesToUse; i++ )
buffer[ i ] ^= cryptInfo->ctxConv.currentIV[ i + ivCount ];
memcpy( cryptInfo->ctxConv.currentIV + ivCount, temp, bytesToUse );
/* Adjust the byte count and buffer position */
noBytes -= bytesToUse;
buffer += bytesToUse;
ivCount += bytesToUse;
}
while( noBytes )
{
ivCount = ( noBytes > SKIPJACK_BLOCKSIZE ) ? SKIPJACK_BLOCKSIZE : noBytes;
/* Encrypt the IV */
skipjackEncrypt( cryptInfo->ctxConv.key, cryptInfo->ctxConv.currentIV,
cryptInfo->ctxConv.currentIV );
/* Save the ciphertext */
memcpy( temp, buffer, ivCount );
/* XOR the buffer contents with the encrypted IV */
for( i = 0; i < ivCount; i++ )
buffer[ i ] ^= cryptInfo->ctxConv.currentIV[ i ];
/* Shift the ciphertext into the IV */
memcpy( cryptInfo->ctxConv.currentIV, temp, ivCount );
/* Move on to next block of data */
noBytes -= ivCount;
buffer += ivCount;
}
/* Remember how much of the IV is still available for use */
cryptInfo->ctxConv.ivCount = ( ivCount % SKIPJACK_BLOCKSIZE );
/* Clear the temporary buffer */
zeroise( temp, SKIPJACK_BLOCKSIZE );
return( CRYPT_OK );
}
/* Encrypt/decrypt data in OFB mode */
int skipjackEncryptOFB( CRYPT_INFO *cryptInfo, BYTE *buffer, int noBytes )
{
int i, ivCount = cryptInfo->ctxConv.ivCount;
/* If there's any encrypted material left in the IV, use it now */
if( ivCount )
{
int bytesToUse;
/* Find out how much material left in the encrypted IV we can use */
bytesToUse = SKIPJACK_BLOCKSIZE - ivCount;
if( noBytes < bytesToUse )
bytesToUse = noBytes;
/* Encrypt the data */
for( i = 0; i < bytesToUse; i++ )
buffer[ i ] ^= cryptInfo->ctxConv.currentIV[ i + ivCount ];
/* Adjust the byte count and buffer position */
noBytes -= bytesToUse;
buffer += bytesToUse;
ivCount += bytesToUse;
}
while( noBytes )
{
ivCount = ( noBytes > SKIPJACK_BLOCKSIZE ) ? SKIPJACK_BLOCKSIZE : noBytes;
/* Encrypt the IV */
skipjackEncrypt( cryptInfo->ctxConv.key, cryptInfo->ctxConv.currentIV,
cryptInfo->ctxConv.currentIV );
/* XOR the buffer contents with the encrypted IV */
for( i = 0; i < ivCount; i++ )
buffer[ i ] ^= cryptInfo->ctxConv.currentIV[ i ];
/* Move on to next block of data */
noBytes -= ivCount;
buffer += ivCount;
}
/* Remember how much of the IV is still available for use */
cryptInfo->ctxConv.ivCount = ( ivCount % SKIPJACK_BLOCKSIZE );
return( CRYPT_OK );
}
/* Decrypt data in OFB mode */
int skipjackDecryptOFB( CRYPT_INFO *cryptInfo, BYTE *buffer, int noBytes )
{
int i, ivCount = cryptInfo->ctxConv.ivCount;
/* If there's any encrypted material left in the IV, use it now */
if( ivCount )
{
int bytesToUse;
/* Find out how much material left in the encrypted IV we can use */
bytesToUse = SKIPJACK_BLOCKSIZE - ivCount;
if( noBytes < bytesToUse )
bytesToUse = noBytes;
/* Decrypt the data */
for( i = 0; i < bytesToUse; i++ )
buffer[ i ] ^= cryptInfo->ctxConv.currentIV[ i + ivCount ];
/* Adjust the byte count and buffer position */
noBytes -= bytesToUse;
buffer += bytesToUse;
ivCount += bytesToUse;
}
while( noBytes )
{
ivCount = ( noBytes > SKIPJACK_BLOCKSIZE ) ? SKIPJACK_BLOCKSIZE : noBytes;
/* Encrypt the IV */
skipjackEncrypt( cryptInfo->ctxConv.key, cryptInfo->ctxConv.currentIV,
cryptInfo->ctxConv.currentIV );
/* XOR the buffer contents with the encrypted IV */
for( i = 0; i < ivCount; i++ )
buffer[ i ] ^= cryptInfo->ctxConv.currentIV[ i ];
/* Move on to next block of data */
noBytes -= ivCount;
buffer += ivCount;
}
/* Remember how much of the IV is still available for use */
cryptInfo->ctxConv.ivCount = ( ivCount % SKIPJACK_BLOCKSIZE );
return( CRYPT_OK );
}
/****************************************************************************
* *
* Skipjack Key Management Routines *
* *
****************************************************************************/
/* Key schedule a Skipjack key */
int skipjackInitKey( CRYPT_INFO *cryptInfo, const void *key, const int keyLength )
{
/* Copy the key to internal storage */
if( cryptInfo->ctxConv.userKey != key )
memcpy( cryptInfo->ctxConv.userKey, key, keyLength );
cryptInfo->ctxConv.userKeyLength = keyLength;
/* In theory Skipjack doesn't require a key schedule so we could just
copy the user key across, however the optimised version preprocesses
the keying data to save an XOR on each F-table access */
skipjackMakeKey( ( BYTE * ) key, cryptInfo->ctxConv.key );
return( CRYPT_OK );
}
| 27.995381 | 95 | 0.62003 |
8907d19a571a9b5aa9f5d8fc692ac9a04495eed1 | 571 | h | C | src/player_deterministic.h | tczajka/flippo-veoveo | 6ebd612c4b85cb910264169164f1cdb1a2252a3d | [
"MIT"
] | 5 | 2019-01-19T14:18:20.000Z | 2022-01-23T16:58:45.000Z | src/player_deterministic.h | tczajka/flippo-veoveo | 6ebd612c4b85cb910264169164f1cdb1a2252a3d | [
"MIT"
] | null | null | null | src/player_deterministic.h | tczajka/flippo-veoveo | 6ebd612c4b85cb910264169164f1cdb1a2252a3d | [
"MIT"
] | null | null | null | #ifndef PLAYER_DETERMINISTIC_H
#define PLAYER_DETERMINISTIC_H
#include "player.h"
class PlayerFirst : public Player {
public:
PlayerFirst(const int _symmetry) : symmetry{_symmetry} {}
Move choose_move(const Position &position,
const PlaySettings &settings) override;
private:
int symmetry;
};
class PlayerGreedy : public Player {
public:
PlayerGreedy(const int _symmetry) : symmetry{_symmetry} {}
Move choose_move(const Position &position,
const PlaySettings &settings) override;
private:
int symmetry;
};
#endif
| 19.689655 | 60 | 0.716287 |
81aada61a777226f8730aefe541655a0900654b1 | 133 | h | C | example.h | Mego/ExampleCPP | fb7671a14d8a8ce262f5400e7a110b826978d9c4 | [
"MIT"
] | 1 | 2016-12-11T20:35:53.000Z | 2016-12-11T20:35:53.000Z | example.h | Mego/ExampleCPP | fb7671a14d8a8ce262f5400e7a110b826978d9c4 | [
"MIT"
] | null | null | null | example.h | Mego/ExampleCPP | fb7671a14d8a8ce262f5400e7a110b826978d9c4 | [
"MIT"
] | null | null | null | #ifndef EXAMPLE_H_INCLUDED
#define EXAMPLE_H_INCLUDED
#include <string>
std::string example();
#endif // EXAMPLE_H_INCLUDED | 16.625 | 28 | 0.75188 |
32e2b74ff80b1838f4320b1fa701874132a869a8 | 3,936 | h | C | SurgSim/Devices/DeviceFilters/PoseIntegrator.h | dbungert/opensurgsim | bd30629f2fd83f823632293959b7654275552fa9 | [
"Apache-2.0"
] | 24 | 2015-01-19T16:18:59.000Z | 2022-03-13T03:29:11.000Z | SurgSim/Devices/DeviceFilters/PoseIntegrator.h | dbungert/opensurgsim | bd30629f2fd83f823632293959b7654275552fa9 | [
"Apache-2.0"
] | 3 | 2018-12-21T14:54:08.000Z | 2022-03-14T12:38:07.000Z | SurgSim/Devices/DeviceFilters/PoseIntegrator.h | dbungert/opensurgsim | bd30629f2fd83f823632293959b7654275552fa9 | [
"Apache-2.0"
] | 8 | 2015-04-10T19:45:36.000Z | 2022-02-02T17:00:59.000Z | // This file is a part of the OpenSurgSim project.
// Copyright 2013-2015, SimQuest Solutions 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 SURGSIM_DEVICES_DEVICEFILTERS_POSEINTEGRATOR_H
#define SURGSIM_DEVICES_DEVICEFILTERS_POSEINTEGRATOR_H
#include <memory>
#include <string>
#include "SurgSim/DataStructures/OptionalValue.h"
#include "SurgSim/Devices/DeviceFilters/DeviceFilter.h"
#include "SurgSim/Framework/Timer.h"
#include "SurgSim/Math/RigidTransform.h"
namespace SurgSim
{
namespace DataStructures
{
class DataGroupCopier;
};
namespace Devices
{
SURGSIM_STATIC_REGISTRATION(PoseIntegrator);
/// A device filter that integrates the pose, turning a relative device into an absolute one.
/// Also provides the instantaneous linear and angular velocities.
/// \sa SurgSim::Input::CommonDevice
/// \sa SurgSim::Input::InputConsumerInterface
/// \sa SurgSim::Input::OutputProducerInterface
class PoseIntegrator : public DeviceFilter
{
public:
/// The type used for poses.
typedef Math::RigidTransform3d PoseType;
/// Constructor.
/// \param name Name of this device filter.
explicit PoseIntegrator(const std::string& name);
SURGSIM_CLASSNAME(SurgSim::Devices::PoseIntegrator);
/// Integrates the pose.
/// \param pose The latest differential pose.
/// \return The integrated pose.
const PoseType& integrate(const PoseType& pose);
void initializeInput(const std::string& device, const DataStructures::DataGroup& inputData) override;
/// Notifies the consumer that the application input coming from the device has been updated.
/// Treats the pose coming from the input device as a delta pose and integrates it to get the output pose.
/// \param device The name of the device that is producing the input. This should only be used to identify
/// the device (e.g. if the consumer is listening to several devices at once).
/// \param inputData The application input state coming from the device.
void handleInput(const std::string& device, const DataStructures::DataGroup& inputData) override;
/// Sets the string name of the boolean entry that will reset the pose to its initial value. Such a reset can be
/// useful if the integrated pose is used to position an object and the integration takes the object out of view.
/// \param name The name of the NamedData<bool> entry.
/// \warning A pose reset may generate high velocities, and if the pose is the input to a VirtualToolCoupler then
/// large forces will likely be generated.
/// \exception Asserts if called after initialize.
void setReset(const std::string& name);
protected:
/// Overridden from DeviceFilter
/// tries to see if "pose" was sent and resets itself to that pose
void filterOutput(const std::string& device,
const SurgSim::DataStructures::DataGroup& dataToFilter,
SurgSim::DataStructures::DataGroup* result) override;
private:
/// The result of integrating the input poses.
PoseType m_poseResult;
/// A timer for the update rate needed for calculating velocity.
Framework::Timer m_timer;
/// A copier into the input DataGroup, if needed.
std::shared_ptr<DataStructures::DataGroupCopier> m_copier;
/// The name of the reset boolean (if any).
std::string m_resetName;
SurgSim::DataStructures::OptionalValue<SurgSim::Math::RigidTransform3d> m_resetPose;
};
}; // namespace Devices
}; // namespace SurgSim
#endif // SURGSIM_DEVICES_DEVICEFILTERS_POSEINTEGRATOR_H
| 37.132075 | 114 | 0.763465 |
0a555cfde8b14ba6506ad34eed61927f4cd0d740 | 3,575 | h | C | headers/structs.h | BlankWheein/P1 | ec8c18a958323189818165053027b756337115b5 | [
"Apache-2.0"
] | null | null | null | headers/structs.h | BlankWheein/P1 | ec8c18a958323189818165053027b756337115b5 | [
"Apache-2.0"
] | null | null | null | headers/structs.h | BlankWheein/P1 | ec8c18a958323189818165053027b756337115b5 | [
"Apache-2.0"
] | null | null | null | #ifndef STRUCTS
#define STRUCTS
/*
The Enumeration of Light Color
*/
typedef enum {green, /**< When the light is Green */
red, /**< When the light is Red */
dummy /**< When the light is a mock light. This means the Vehicles will ignore this light (This is used to Check for the nearest Traffic light) */
} Light_color;
/*
The Enumeration of Lane_type
*/
typedef enum {PlusBus, /**< When the Vehicle is a Plusbus */
Car, /**< When the Vehicle is a Car */
Bus /**< When the Vehicle is a Bus */
} Lane_type;
/*
The Enumeration of State
*/
typedef enum {Waiting, /**< The state of the Vehicle if it is waiting to get on the bridge */
Driving, /**< The state of the Vehicle if it is driving on the bridge */
Done, /**< The state of the Vehicle if it is done driving on the bridge */
HoldingForRed, /**< The state of the Vehicle if it is holding for red on the bridge */
Mock /**< This is a mock Vehicle. This means the Vehicles will ignore this Vehicle (This is used for getting the nearest Vehicle)*/
} State;
/*
A structure to represent Traffic lights
*/
typedef struct {
/*@{*/
Light_color color; /**< The color of the Traffic light */
double position; /**< The position of the traffic light on the road */
int timer; /**< The current Traffic light timer (This counts from 0 to either timer_green or timer_red) */
int timer_green; /**< How long the Traffic light should stay Green (In seconds) */
int timer_red; /**< How long the Traffic light should stay Red (In seconds) */
} Traffic_light;
/*
A structure to represent A Vehicle
*/
typedef struct {
double speed; /**< The current speed of the Vehicle (In M/s)*/
double position; /**< The current position of the Vehicle (This goes from 0 to the distance of the road) */
double speed_limit; /**< The Speed limit of the Vehicle (In Km/h)*/
double speed_limit_time; /**< How long it takes for the Vehicle to reach its speed speed_limit (In Seconds)*/
double time_driving; /**< This is used for calculating the acceleration (this is a constant) */
double acceleration; /**< The Vehicles acceleration in meter per second squared */
double safe_distance; /**< The distance the vehicle tries to keep from the car infront (In Meters) */
int ID; /**< The ID of the car */
int lane; /**< The lane the Vehicle is driving in */
int secs_on_bridge; /**< The amount of seconds the Vehicle has been on the bridge */
State state; /**< The State the Vehicle is in (This is of Type State) */
Lane_type type; /**< The Type of lanes the Vehicle can drive in (This is of Type Lane_type) */
double avg_speed; /**< The Average speed of the Vehicle across the bridge */
double avg_speed_total; /**< This is used to calculate the average speed of the Vehicle */
int time_waited_for_green_light; /**< The amount of seconds the Vehicle has waited for a green light */
} Vehicle;
/*
A structure to represent Roads
*/
typedef struct {
double speed_limit; /**< The speed limit on the road (In m/s)*/
Lane_type lane_type; /**< The type of lane the road is (This is of Type Lane_type) */
double length; /**< The length of the road (In Meters) */
} Road;
#endif
| 47.039474 | 161 | 0.615385 |
0aaf4bea3208dfbbef50a7925cbf235052a8ce9f | 2,098 | c | C | src/minimal_classifier.bpf.c | netgroup/hike-public | 5cf9e18c837d25e21f403f9b4676f11e397cc6bb | [
"BSD-3-Clause"
] | null | null | null | src/minimal_classifier.bpf.c | netgroup/hike-public | 5cf9e18c837d25e21f403f9b4676f11e397cc6bb | [
"BSD-3-Clause"
] | null | null | null | src/minimal_classifier.bpf.c | netgroup/hike-public | 5cf9e18c837d25e21f403f9b4676f11e397cc6bb | [
"BSD-3-Clause"
] | null | null | null |
#include <stddef.h>
#include <linux/in.h>
#include <linux/if_ether.h>
#include <linux/if_packet.h>
#include <linux/ipv6.h>
#include <linux/seg6.h>
#include <linux/errno.h>
/* HIKe Chain IDs and XDP eBPF/HIKe programs IDs */
#include "minimal.h"
#include "hike_vm.h"
#include "parse_helpers.h"
#define MAP_IPV6_SIZE 64
bpf_map(map_ipv6, HASH, struct in6_addr, __u32, MAP_IPV6_SIZE);
static __always_inline
int __hvxdp_handle_ipv6(struct xdp_md *ctx, struct hdr_cursor *cur)
{
struct in6_addr *key;
struct ipv6hdr *ip6h;
__u32 *chain_id;
int nexthdr;
int rc;
nexthdr = parse_ip6hdr(ctx, cur, &ip6h);
if (!ip6h || nexthdr < 0)
return XDP_PASS;
cur_reset_transport_header(cur);
/* let's find out the chain id associated with the IPv6 DA */
key = &ip6h->daddr;
chain_id = bpf_map_lookup_elem(&map_ipv6, key);
if (!chain_id)
/* value not found, deliver the packet to the kernel */
return XDP_PASS;
DEBUG_PRINT("HIKe VM invoking Chain ID=0x%x", *chain_id);
rc = hike_chain_boostrap(ctx, *chain_id);
/* the fallback behavior of this classifier consists in dropping any
* packet that has not been delivered by any of the selected HIKe
* Chains in an explicit way.
*/
if (rc < 0)
DEBUG_PRINT("HIKe VM returned error code=%d", rc);
return XDP_ABORTED;
}
__section("hike_classifier")
int __hike_classifier(struct xdp_md *ctx)
{
struct pkt_info *info = hike_pcpu_shmem();
struct hdr_cursor *cur;
struct ethhdr *eth;
__be16 eth_type;
__u16 proto;
if (!info)
return XDP_ABORTED;
cur = pkt_info_cur(info);
cur_init(cur);
eth_type = parse_ethhdr(ctx, cur, ð);
if (!eth || eth_type < 0)
return XDP_ABORTED;
/* set the network header */
cur_reset_network_header(cur);
proto = bpf_htons(eth_type);
switch (proto) {
case ETH_P_IPV6:
return __hvxdp_handle_ipv6(ctx, cur);
case ETH_P_IP:
/* fallthrough */
default:
DEBUG_PRINT("HIKe VM Classifier passthrough for proto=%x",
bpf_htons(eth_type));
break;
}
/* default policy allows any unrecognized packed... */
return XDP_PASS;
}
char LICENSE[] SEC("license") = "Dual BSD/GPL";
| 22.319149 | 69 | 0.714967 |
61eaa4f6d9965c3e22fe3503e32b3b44243fc594 | 350 | h | C | Oto.h | CrossPlatUtauDG/stage2 | be505a3f69a38f3ebed83c7c61b43ec54e2d216a | [
"MIT"
] | 2 | 2017-07-26T03:01:39.000Z | 2017-07-26T04:20:33.000Z | Oto.h | CrossPlatUtauDG/stage2 | be505a3f69a38f3ebed83c7c61b43ec54e2d216a | [
"MIT"
] | null | null | null | Oto.h | CrossPlatUtauDG/stage2 | be505a3f69a38f3ebed83c7c61b43ec54e2d216a | [
"MIT"
] | null | null | null | #ifndef OTO_H
#define OTO_H
#include <string>
#include <map>
#include "VoiceProp.h"
class Oto {
public:
Oto(std::string path);
~Oto();
VoiceProp getVPfromName(std::string sampleName);
private:
std::string fileDir;
std::string otoText;
int lines;
std::map<std::string, VoiceProp*> otoEntries;
void openFile();
};
#endif
| 14 | 50 | 0.668571 |
76d701941e931619541676b277f14893dbd922f4 | 1,376 | c | C | test.c | littlstar/uri.c | c33b9b767606b7edc1edcb095ff256c4b6bf4cef | [
"MIT"
] | 13 | 2015-01-31T05:02:07.000Z | 2022-03-27T17:10:37.000Z | test.c | littlstar/uri.c | c33b9b767606b7edc1edcb095ff256c4b6bf4cef | [
"MIT"
] | 1 | 2015-02-27T20:01:53.000Z | 2015-02-27T20:12:16.000Z | test.c | littlstar/uri.c | c33b9b767606b7edc1edcb095ff256c4b6bf4cef | [
"MIT"
] | 1 | 2019-09-21T09:36:02.000Z | 2019-09-21T09:36:02.000Z |
/**
* `test.c' - uri
*
* copyright (c) 2014 joseph werle
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <ok/ok.h>
#include "uri.h"
#define S(x) # x
#define t(m, a, b) ({ \
char tmp[1024]; \
sprintf(tmp, "%s(%s) = %s", S(m), S(a), S(b)); \
char *result = m(a); \
assert(0 == strcmp(b, result)); \
ok(tmp); \
free(result); \
})
int
main (void) {
// encode
{
t(uri_encode,
"Betty's favorite language is Français",
"Betty%27s%20favorite%20language%20is%20Fran%C3%A7ais");
t(uri_encode, "(45 * 2) + 90", "(45%20*%202)%20%2B%2090");
t(uri_encode,
"`console.log(value); if (!foo) { _bar(): }`",
"%60console.log(value)%3B%20if%20(!foo)%20%7B%20_bar()%3A%20%7D%60");
t(uri_encode,
"\"it will all be alright !\", he said.",
"%22it%20will%20all%20be%20alright%20!%22%2C%20he%20said.");
}
// decode
{
t(uri_decode,
"a%C3%A7%C3%BAcar",
"açúcar");
t(uri_decode,
"tor%C3%A7ut",
"torçut");
t(uri_decode,
"JavaScript_%D1%88%D0%B5%D0%BB%D0%BB%D1%8B",
"JavaScript_шеллы");
}
ok_done();
return 0;
}
| 21.5 | 77 | 0.462209 |
ddae2693af99143a6927a271c2b69819c5cde9f3 | 4,749 | h | C | inc/dg/backend/vector_categories.h | RaulGerru/FELTOR_Raul | a566f8a9003ade437e093334877f839f3dfd0260 | [
"MIT"
] | 18 | 2016-06-28T14:34:29.000Z | 2022-01-06T08:50:48.000Z | inc/dg/backend/vector_categories.h | RaulGerru/FELTOR_Raul | a566f8a9003ade437e093334877f839f3dfd0260 | [
"MIT"
] | 11 | 2017-01-18T16:06:15.000Z | 2021-02-22T19:11:42.000Z | inc/dg/backend/vector_categories.h | mrheld/feltor | c70bc6bb43f39261f6236df88e16610d08cb98ca | [
"MIT"
] | 12 | 2016-06-27T13:18:11.000Z | 2021-09-03T08:12:25.000Z | #ifndef _DG_VECTOR_CATEGORIES_
#define _DG_VECTOR_CATEGORIES_
#include "matrix_categories.h"
namespace dg{
//here we introduce the concept of data access
///@addtogroup dispatch
///@{
/**
* @brief Vector Tag base class, indicates the basic Vector/container concept
*
* The vector tag has three functions.
First, it indicates the fundamental datatype a vector class contains (typically a double).
Second, it describes how the data in a Vector type is layed out in memory. We distinguish between a simple, contiguous chunk of data in a shared memory system (dg::SharedVectorTag), a dataset that is
part of a larger dataset on a distributed memory system (dg::MPIVectorTag), and
a dataset that consists of a number of subsets (dg::RecursiveVectorTag).
Both the MPIVectorTag and the RecursiveVectorTag allow recursion, that is
for example a RecursiveVector can consist itself of many shared vectors or of many
RecursiveVector again. The innermost type must always be a shared vector however.
The third function of the Vector tag is to describe how the data in the vector has to be accessed.For example
* how do we get the pointer to the first element, the size, or how to access the MPI communicator? This is described in Derived Tags from the fundamental
Tags, e.g. the \c ThrustVectorTag.
* @note in any case we assume that the class has a default constructor, is copyable/assignable and has a \c size and a \c swap member function
* @note <tt> dg::TensorTraits<Vector> </tt>has member typedefs \c value_type, \c execution_policy, \c tensor_category
* @note any vector can serve as a diagonal matrix
* @see \ref dispatch
*/
struct AnyVectorTag : public AnyMatrixTag{};
///@}
/**
* @brief Indicate a contiguous chunk of shared memory
*
* With this tag a class promises that the data it holds lies in a contiguous chunk that
* can be traversed knowing the pointer to its first element. Sub-Tags
* indicate addtional functionality like data resize.
* @note We assume a class with this Tag has the following methods
* - \c size() returns the size (in number of elements) of the contiguous data
* - \c data() returns a pointer (or something for which the \c thrust::pointer_traits are specialized) to the first element of the contiguous data.
* The return type must be convertible to <tt> (const) value_type* </tt>
*/
struct SharedVectorTag : public AnyVectorTag {};
/**
* @brief A distributed vector contains a data container and a MPI communicator
*
* This tag indicates that data is distributed among one or several processes.
* An MPI Vector is assumed to be composed of a data container together with an MPI Communicator.
* In fact, the currently only class with this tag is the \c MPI_Vector class.
*
* @note This is a recursive tag in the sense that classes must provide a typedef \c container_type, for which the \c dg::TensorTraits must be specialized
* @see dg::MPI_Vector, mpi_structures
*/
struct MPIVectorTag : public AnyVectorTag {};
/**
* @brief This tag indicates composition/recursion.
*
* This Tag indicates that a class is composed of an array of containers, i.e. a container of containers.
* We assume that the bracket \c operator[] is defined to access the inner elements and the \c size() function returns the number of elements.
* @note The class must typedef \c value_type (the "inner" type that is returned by the bracket operator) and \c dg::TensorTraits<value_type> must be specialized for this type.
* @note Examples are \c std::vector<T> and \c std::array<T,N> where T is the inner type and N is the size of the array
*/
struct RecursiveVectorTag : public AnyVectorTag {};
struct ArrayVectorTag : public RecursiveVectorTag{}; //!< \c std::array of containers
/**
* @brief Indicate thrust/std - like behaviour
*
* There must be the typedefs
* - \c iterator
* - \c const_iterator
* - \c pointer
* - \c const_pointer
* An instance can be constructed by
* - iterators \c (begin, end)
* The member functions contan at least
* - \c resize() resize the vector
* - \c size() returns the number of elements
* - \c data() returns \c pointer to the underlying array
* - \c begin() returns \c iterator to the beginning
* - \c cbegin() returns \c const_iterator to the beginning
* - \c end() return an \c iterator to the end
* - \c cend() returns a \c const_iterator to the end
* @note \c thrust::host_vector and \c thrust::device_vector meet these requirements
*/
struct ThrustVectorTag : public SharedVectorTag {};
struct CuspVectorTag : public ThrustVectorTag {}; //!< special tag for cusp arrays
struct StdArrayTag : public ThrustVectorTag {}; //!< <tt> std::array< primitive_type, N> </tt>
}//namespace dg
#endif //_DG_VECTOR_CATEGORIES_
| 48.958763 | 200 | 0.743314 |
50d2011d06cc23ba8ffa0674a2cb53f68f87c4cf | 718 | h | C | ios/Pods/Headers/Public/ViroReact/VRTLog.h | atlance01/ViroVRapp | aee8e46049ba39bef00150d38b9711896e08c4cb | [
"BSD-3-Clause"
] | 5 | 2017-08-08T06:01:54.000Z | 2022-03-28T17:17:11.000Z | ios/Pods/Headers/Public/ViroReact/VRTLog.h | atlance01/ViroVRapp | aee8e46049ba39bef00150d38b9711896e08c4cb | [
"BSD-3-Clause"
] | 2 | 2019-11-22T22:03:24.000Z | 2020-04-21T19:10:47.000Z | ios/Pods/Headers/Public/ViroReact/VRTLog.h | atlance01/ViroVRapp | aee8e46049ba39bef00150d38b9711896e08c4cb | [
"BSD-3-Clause"
] | 3 | 2019-11-22T17:11:03.000Z | 2019-11-24T19:11:30.000Z | //
// VROLog.h
// React
//
// Copyright © 2016 Viro Media. All rights reserved.
//
#import <Foundation/Foundation.h>
/**
* Used only for logging out information within VRT components.
* NOTE: This has no relation to VROLog.
*/
@interface VRTLog : NSObject
/**
* Static Flag used to enable / disable VRT debug information
* logged out onto the console in debug builds (data is not
* logged in release builds).
*/
+ (BOOL)debugEnabled;
+ (void)setdebugEnabled:(BOOL)debugEnabled;
/**
* Prints out logs into the console. This is only
* enabled in debug builds and if debugEnabled is True (Enabled
* true RCTMenu).
*/
+ (void)debug:(NSString *)log;
@end | 24.758621 | 67 | 0.650418 |
20821904aa6395f094a2a2433547c7699af07b57 | 6,712 | h | C | src/interfaces/builtins_spidermonkey.h | Samsung/Fluff | d8c95b67d390156e24b45cf61b066930f2d783e4 | [
"MIT"
] | 58 | 2019-04-02T04:50:47.000Z | 2021-12-28T02:09:36.000Z | src/interfaces/builtins_spidermonkey.h | Samsung/Fluff | d8c95b67d390156e24b45cf61b066930f2d783e4 | [
"MIT"
] | 3 | 2019-05-25T08:12:18.000Z | 2019-06-08T11:47:05.000Z | src/interfaces/builtins_spidermonkey.h | Samsung/Fluff | d8c95b67d390156e24b45cf61b066930f2d783e4 | [
"MIT"
] | 10 | 2019-04-24T18:46:24.000Z | 2020-06-27T17:56:58.000Z | #ifndef BUILTINS_H_
#define BUILTINS_H_
#include <string>
namespace builtins {
const std::string variables[] = {
"Reflect",
"timesAccessed",
"console",
"os",
"performance",
"scriptArgs",
"scriptPath",
"variables",
"functions",
"methods",
"top",
"undefined",
"JSON",
"Math",
"NaN",
"StopIteration",
"Intl",
"__proto__",
"file",
"path",
"mozMemory",
"gc",
"gcBytes",
"gcMaxBytes",
"mallocBytesRemaining",
"maxMalloc",
"gcIsHighFrequencyMode",
"gcNumber",
"majorGCCount",
"minorGCCount",
"zone",
"gcTriggerBytes",
"gcAllocTrigger",
"delayBytes",
"heapGrowthFactor",
"length",
"E",
"LOG2E",
"LOG10E",
"LN2",
"LN10",
"PI",
"SQRT2",
"SQRT1_2",
};
const std::string functions[] = {
"Function",
"Object",
"eval",
"Debugger",
"PerfMeasurement",
"version",
"options",
"load",
"loadRelativeToScript",
"evaluate",
"run",
"readline",
"print",
"printErr",
"putstr",
"dateNow",
"help",
"quit",
"assertEq",
"startTimingMutator",
"stopTimingMutator",
"throwError",
"intern",
"getslx",
"evalcx",
"evalInWorker",
"getSharedArrayBuffer",
"setSharedArrayBuffer",
"shapeOf",
"sleep",
"compile",
"parseModule",
"setModuleResolveHook",
"getModuleLoadPath",
"parse",
"syntaxParse",
"offThreadCompileScript",
"runOffThreadScript",
"timeout",
"interruptIf",
"invokeInterruptCallback",
"setInterruptCallback",
"enableLastWarning",
"disableLastWarning",
"getLastWarning",
"clearLastWarning",
"elapsed",
"decompileFunction",
"decompileThis",
"thisFilename",
"newGlobal",
"createMappedArrayBuffer",
"getMaxArgs",
"objectEmulatingUndefined",
"isCachingEnabled",
"setCachingEnabled",
"cacheEntry",
"printProfilerEvents",
"enableSingleStepProfiling",
"disableSingleStepProfiling",
"isLatin1",
"stackPointerInfo",
"entryPoints",
"gc",
"minorgc",
"gcparam",
"relazifyFunctions",
"getBuildConfiguration",
"hasChild",
"setSavedStacksRNGState",
"getSavedFrameCount",
"saveStack",
"callFunctionFromNativeFrame",
"callFunctionWithAsyncStack",
"enableTrackAllocations",
"disableTrackAllocations",
"makeFakePromise",
"settleFakePromise",
"makeFinalizeObserver",
"finalizeCount",
"gcPreserveCode",
"startgc",
"gcslice",
"abortgc",
"validategc",
"fullcompartmentchecks",
"nondeterministicGetWeakMapKeys",
"internalConst",
"isProxy",
"dumpHeap",
"terminate",
"enableSPSProfiling",
"enableSPSProfilingWithSlowAssertions",
"disableSPSProfiling",
"readSPSProfilingStack",
"enableOsiPointRegisterChecks",
"displayName",
"isAsmJSCompilationAvailable",
"isSimdAvailable",
"getJitCompilerOptions",
"isAsmJSModule",
"isAsmJSModuleLoadedFromCache",
"isAsmJSFunction",
"isLazyFunction",
"isRelazifiableFunction",
"enableShellObjectMetadataCallback",
"getObjectMetadata",
"bailout",
"inJit",
"inIon",
"assertJitStackInvariants",
"setJitCompilerOption",
"setIonCheckGraphCoherency",
"serialize",
"deserialize",
"neuter",
"helperThreadCount",
"startTraceLogger",
"stopTraceLogger",
"reportOutOfMemory",
"reportLargeAllocationFailure",
"findPath",
"evalReturningScope",
"cloneAndExecuteScript",
"backtrace",
"getBacktrace",
"byteSize",
"byteSizeOfScript",
"immutablePrototypesEnabled",
"setImmutablePrototype",
"setLazyParsingDisabled",
"setDiscardSource",
"getConstructorName",
"allocationMarker",
"setGCCallback",
"setARMHwCapFlags",
"getLcovInfo",
"getModuleEnvironmentNames",
"getModuleEnvironmentValue",
"clone",
"getSelfHostedValue",
"line2pc",
"pc2line",
"nestedShell",
"assertFloat32",
"assertRecoveredOnBailout",
"withSourceHook",
"wrapWithProto",
"trackedOpts",
"read",
"snarf",
"readRelativeToScript",
"redirect",
"FakeDOMObject",
"Array",
"extractBuiltins",
"Set",
"Boolean",
"Date",
"isNaN",
"isFinite",
"parseInt",
"parseFloat",
"Number",
"String",
"escape",
"unescape",
"uneval",
"decodeURI",
"encodeURI",
"decodeURIComponent",
"encodeURIComponent",
"RegExp",
"Error",
"InternalError",
"EvalError",
"RangeError",
"ReferenceError",
"SyntaxError",
"TypeError",
"URIError",
"Iterator",
"ArrayBuffer",
"Int8Array",
"Uint8Array",
"Int16Array",
"Uint16Array",
"Int32Array",
"Uint32Array",
"Float32Array",
"Float64Array",
"Uint8ClampedArray",
"Proxy",
"WeakMap",
"Map",
"DataView",
"Symbol",
"WeakSet",
};
const std::string methods[] = {
"apply",
"construct",
"defineProperty",
"deleteProperty",
"get",
"getOwnPropertyDescriptor",
"getPrototypeOf",
"has",
"isExtensible",
"ownKeys",
"preventExtensions",
"set",
"setPrototypeOf",
"parse",
"toSource",
"toString",
"valueOf",
"watch",
"unwatch",
"hasOwnProperty",
"isPrototypeOf",
"propertyIsEnumerable",
"constructor",
"toLocaleString",
"__defineGetter__",
"__defineSetter__",
"__lookupGetter__",
"__lookupSetter__",
"log",
"getenv",
"getpid",
"system",
"spawn",
"kill",
"waitpid",
"readFile",
"readRelativeToScript",
"writeTypedArrayToFile",
"redirect",
"isAbsolute",
"join",
"reverse",
"sort",
"push",
"pop",
"shift",
"unshift",
"splice",
"concat",
"slice",
"lastIndexOf",
"indexOf",
"forEach",
"map",
"filter",
"reduce",
"reduceRight",
"some",
"every",
"find",
"findIndex",
"copyWithin",
"fill",
"entries",
"keys",
"includes",
"stringify",
"abs",
"acos",
"asin",
"atan",
"atan2",
"ceil",
"clz32",
"cos",
"exp",
"floor",
"imul",
"fround",
"max",
"min",
"pow",
"random",
"round",
"sin",
"sqrt",
"tan",
"log10",
"log2",
"log1p",
"expm1",
"cosh",
"sinh",
"tanh",
"acosh",
"asinh",
"atanh",
"hypot",
"trunc",
"sign",
"cbrt",
"Collator",
"NumberFormat",
"DateTimeFormat",
};
}; // namespace builtins
#endif // ifndef BUILTINS_H_ | 18.490358 | 43 | 0.575983 |
e3e7a4a93212b6593f9f07533ec3b1ef407d2581 | 13,044 | h | C | src/sigfunctions.h | rettopnivek/seqmodels | 2fc1456074b030898f964f93d1edfb04191f198c | [
"MIT"
] | 1 | 2021-05-28T02:50:23.000Z | 2021-05-28T02:50:23.000Z | src/sigfunctions.h | rettopnivek/seqmodels | 2fc1456074b030898f964f93d1edfb04191f198c | [
"MIT"
] | 3 | 2020-04-07T10:02:49.000Z | 2020-04-28T15:46:21.000Z | src/sigfunctions.h | rettopnivek/seqmodels | 2fc1456074b030898f964f93d1edfb04191f198c | [
"MIT"
] | null | null | null | // Include guard to protect against multiple definitions error
#ifndef __SIGFUNCTIONS__
#define __SIGFUNCTIONS__
#include <Rcpp.h> // Includes certain libraries of functions
#include "levyfunctions.h" // For drift of 0
#include "miscfunctions.h" // Linear interpolation
/*
Purpose:
Scalar functions for the random generation, density, distribution,
quantile, and moments functions of the shifted inverse Gaussian
(Wald) distribution.
References:
Dagpunar, J. (1988). Principles of Random Variate Generation.
Oxford: Clarendon Press.
Heathcote, A. (2004a). Fitting Wald and ex-Wald distributions to
response time data: An example using functions for the S-PLUS
package. Behavior Research Methods Instruments & Computers, 36,
678 - 694.
Heathcote, A. (2004b). rtfit.ssc. Retrieved May 5, 2017 from
Psychonomic Society Web Archive: http://www.psychonomic.org/ARCHIVE/.
Index
Lookup - 01: sig_param_verify
Lookup - 02: rinvgauss_scl
Lookup - 03: dinvgauss_scl
Lookup - 04: pinvgauss_scl
Lookup - 05: qinvgauss_scl
Lookup - 06: minvgauss_scl
Lookup - 07: sig_to_ig
*/
// Lookup - 01
inline bool sig_param_verify( std::vector<double> prm,
std::vector<int> index ) {
/*
Purpose:
Function to verify whether inputs are admissable for the
shifted inverse Gaussian distribution.
Arguments:
prm - A vector of parameters
index - The type of parameter being inputted, where...
0 = skip
1 = time
2 = kappa (Threshold)
3 = xi (Drift rate)
4 = tau (Shift)
5 = sigma (Coefficient of drift)
6 = probability
Returns:
TRUE if the inputs are admissable, FALSE otherwise.
*/
// Initialize output
bool out;
// Determine size of vector
int sz = index.size();
// Initialize variable for checks
int chk = 0;
// Variable for number of checks that need to be passed
int n_pass = 0;
// Variable for whether a time is present
double t_yes = 0.0;
for ( int i = 0; i < sz; i++ ) {
if ( index[i] > 0 ) n_pass += 1;
// Check whether inputted time is a real number and
// greater than 0
if ( index[i] == 1 ) {
if ( ( !Rcpp::NumericVector::is_na( prm[i] ) ) &&
( prm[i] > 0.0 ) ) {
chk += 1;
t_yes += prm[i];
}
}
// Check whether threshold is a real number and whether it
// is greater than 0
if ( index[i] == 2 ) {
if ( ( !Rcpp::NumericVector::is_na( prm[i] ) ) &&
( prm[i] > 0.0 ) ) chk += 1;
}
// Check whether drift rate is a real number and whether it
// is greater than or equal to 0
if ( index[i] == 3 ) {
if ( ( !Rcpp::NumericVector::is_na( prm[i] ) ) &&
( prm[i] >= 0.0 ) ) chk += 1;
}
// Check whether shift parameter is a real number and whether it
// is greater than or equal to 0 and, if applicable, whether it
// is less than the inputted response time
if ( index[i] == 4 ) {
if ( ( !Rcpp::NumericVector::is_na( prm[i] ) ) &&
( prm[i] >= 0.0 ) ) {
// Check whether shift parameter is less than the
// given time
if ( t_yes > 0.0 ) {
if ( t_yes > prm[i] ) chk += 1;
} else {
chk += 1;
}
}
}
// Check whether coefficient of drift is a real number and whether
// it is greater than 0
if ( index[i] == 5 ) {
if ( ( !Rcpp::NumericVector::is_na( prm[i] ) ) &&
( prm[i] > 0.0 ) ) chk += 1;
}
// Check whether probability is a real number and whether it
// is appropriately bounded
if ( index[i] == 6 ) {
if ( ( !Rcpp::NumericVector::is_na( prm[i] ) ) &&
( (prm[i] >= 0.0) | (prm[i] <= 1.0) ) ) chk += 1;
}
}
// Test how many checks were passed
out = chk == n_pass;
return( out );
}
// Lookup - 02
inline double rinvgauss_scl( std::vector<double> prm ) {
/*
Purpose:
Scalar function to generate random draws from the inverse
Gaussian distribution.
Arguments:
prm - A vector of parameters, where...
prm[0] = A threshold
prm[1] = A drift rate
prm[2] = A shift parameter
prm[3] = The coefficient of drift
prm[4] = A chi-square random deviate with 1 degree of freedom
prm[5] = A unit uniform deviate
Returns:
A random deviate.
*/
// Initialize output
double out = NA_REAL;
// Define index
std::vector<int> index = create_range( 2, 5 );
// Check for valid inputs
if ( sig_param_verify( prm, index ) ) {
// Extract parameters
double kappa = prm[0];
double xi = prm[1];
double tau = prm[2];
double sigma = prm[3];
// Rescale base on sigma
xi = xi / sigma; kappa = kappa / sigma; sigma = 1.0;
// Generate values from standard inverse Gaussian
// Special case when drift rate is 0
// Finishing times follow a Levy distribution
if ( xi == 0.0 ) {
out = levy_to_ig( prm[5], kappa, sigma, 3 );
} else {
// Extract random deviates
double y2 = prm[4]; double u = prm[5];
// Compute random deviates using script adapted from Heathcote
// (2004b) which was in turn adapted from pp. 79 - 80 of
// Dagpuner (1988)
double y2onm = y2/xi;
double r1 = ( 2.0 * kappa + y2onm -
sqrt( y2onm * ( 4.0 * kappa + y2onm ) ) ) /
( 2.0 * xi );
double r2 = pow( kappa/xi, 2.0 )/r1;
if ( u < kappa/( kappa + xi*r1 ) ) {
out = r1;
}
else {
out = r2;
}
}
// Apply shift parameter
out = out + tau;
}
return(out);
}
// Lookup - 03
inline double dinvgauss_scl( std::vector<double> prm ) {
/*
Purpose:
Scalar version for the density of the shifted inverse
Gaussian distribution. Code is adapted from Smyth et al.
(2017).
Arguments:
prm - A vector of parameters, where...
prm[0] = An observed time
prm[1] = A threshold
prm[2] = A drift rate
prm[3] = A shift parameter
prm[4] = The coefficient of drift
prm[5] = An indicator for the log-likelihood
Returns:
The likelihood or log-likelihood.
*/
// Initialize output
double out = log( 0.0 );
// Determine if log-density should be returned
int ln = prm[5];
// Define index
std::vector<int> index = create_range( 1, 5 );
// Check for valid inputs
if ( sig_param_verify( prm, index ) ) {
// Extract parameters
double rt = prm[0];
double kappa = prm[1];
double xi = prm[2];
double tau = prm[3];
double sigma = prm[4];
// Rescale base on sigma
xi = xi / sigma; kappa = kappa / sigma; sigma = 1.0;
// Shift observed time
double t = rt - tau;
// Special case when drift rate is 0
// Finishing times follow a Levy distribution
if ( xi == 0.0 ) {
out = levy_to_ig( t, kappa, sigma, 1 );
} else {
// Calculate log of density (Heathcote, 2004b)
out = log( kappa ) - pow( kappa - xi*t, 2.0)/( 2.0 * t );
out -= log( sqrt( 2.0 * M_PI * pow( t, 3.0 ) ) );
}
}
// If specified return the density
if (ln==0.0) out = exp(out);
return( out );
}
// Lookup - 04
inline double pinvgauss_scl( std::vector<double> prm ) {
/*
Purpose:
Scalar version for the distribution function of the
shifted inverse Gaussian distribution.
Arguments:
prm - A vector of parameters, where...
prm[0] = An observed time
prm[1] = A threshold
prm[2] = A drift rate
prm[3] = A shift parameter
prm[4] = The coefficient of drift
Returns:
The cumulative probability.
*/
// Initialize output
double out = 0.0;
// Define index
std::vector<int> index = create_range( 1, 5 );
// Check for valid inputs
if ( sig_param_verify( prm, index ) ) {
// Extract parameters
double rt = prm[0];
double kappa = prm[1];
double xi = prm[2];
double tau = prm[3];
double sigma = prm[4];
// Rescale base on sigma
xi = xi / sigma; kappa = kappa / sigma; sigma = 1.0;
// For positive infinity
if ( rt == R_PosInf ) {
out = 1.0;
} else {
// Shift observed time
double t = rt - tau;
// Special case when drift rate is 0
// Finishing times follow a Levy distribution
if ( xi == 0.0 ) {
out = levy_to_ig( t, kappa, sigma, 2 );
} else {
// Compute distribution function (Heathcote, 2004b)
double sqrtt = sqrt( t );
double term1 = ( xi*t - kappa )/sqrtt; // k1
double term2 = ( xi*t + kappa)/sqrtt; // k2
double term3 = exp( 2.0 * kappa * xi );
double Phi1 = R::pnorm( term1, 0.0, 1.0, 1, 0 );
double Phi2 = R::pnorm( -term2, 0.0, 1.0, 1, 0 );
// Protection against numerical error
if ( ( std::isinf( term3 ) ) || ( Phi2 == 0.0 ) ) {
out = -pow( term1, 2.0 )/2.0 - 0.94/pow( term2, 2.0 );
out = exp( out ) / ( term2*pow( 2.0 * M_PI, 0.5 ) );
out += Phi1;
} else {
out = Phi1 + term3 * Phi2;
}
}
}
}
return( out );
}
// Lookup - 05
inline double qinvgauss_scl( std::vector<double> prm ) {
/*
Purpose:
Scalar function for quantile function of the shifted
inverse Gaussian distribution.
Arguments:
prm - A vector of parameters, where...
prm[0] = p (Probability)
prm[1] = A threshold
prm[2] = A drift rate
prm[3] = A shift parameter
prm[4] = The coefficient of drift
prm[5] = mx (Uppermost quantile to examine)
prm[6] = em_stop (Max number of possible iterations)
prm[7] = err (Desired level of accuracy in estimate)
Returns:
The quantile associated with the inputted cumulative probability.
*/
// Initialize output
double out = NA_REAL;
// Define index
std::vector<int> index = create_range( 1, 5 );
index[0] = 6; // For probability
// Check for inadmissable values
if ( sig_param_verify( prm, index ) ) {
cdf cur_cdf = pinvgauss_scl;
// Extract values governing linear interpolation
double mx = prm[5];
int em_stop = prm[6];
double err = prm[7];
out = lin_interp_quantile( prm, cur_cdf,
0.0, mx, em_stop, err,
0.0, R_PosInf );
}
return( out );
}
// Lookup - 06
inline std::vector<double> minvgauss_scl( std::vector<double> prm ) {
/*
Purpose:
Scalar function to compute the moments (mean, variance,
standard deviation, skewness, and exces kurtosis) for the
shifted inverse Gaussian.
Arguments:
prm - A vector of parameters, where...
prm[1] = A threshold
prm[2] = A drift rate
prm[3] = A shift parameter
prm[4] = The coefficient of drift
Returns:
A vector with the mean, variance, standard deviation,
skewness, and excess kurtosis.
*/
// Initialize output
std::vector<double> out(5);
for ( int i = 0; i < 5; i++ ) out[i] = NA_REAL;
// Define index
std::vector<int> index = create_range( 2, 5 );
// Check for inadmissable values
if ( sig_param_verify( prm, index ) ) {
// Extract parameters
double kappa = prm[0];
double xi = prm[1];
double tau = prm[2];
double sigma = prm[3];
// Rescale base on sigma
xi = xi / sigma; kappa = kappa / sigma; sigma = 1.0;
// Convert from Brownian transformation
double mu = kappa/xi;
double lambda = pow( kappa, 2.0 )/pow( sigma, 2.0 );
// Mean
out[0] = mu + tau;
// Variance
out[1] = pow( mu, 3.0 )/lambda;
// Standard deviation
out[2] = pow( out[1], 0.5 );
// Skewness
out[3] = 3.0 * pow( mu/lambda, 0.5 );
// Exces kurtosis
out[4] = 15.0 * mu / lambda;
}
return( out );
}
// Lookup - 07
inline double sig_to_ig( double t, double kappa,
double xi, double sigma,
double u, int ver ) {
/*
Purpose:
A convenience function that computes the density,
distribution, or random generation functions given
subset of parameters for the inverse Gaussian.
Arguments:
t - An observed time or a chi-square deviate
kappa - A threshold
xi - A drift rate
sigma - The coefficient of drift
u - A unit uniform deviate
ver - If 1, computes the density; if 2, computes the
distribution function; if 3, generates a
random deviate.
Returns:
A continuous value.
*/
// Initialize output
double out = NA_REAL;
// Density function
if ( ver == 1 ) {
std::vector<double> ig_prm(6);
ig_prm[0] = t;
ig_prm[1] = kappa;
ig_prm[2] = xi;
ig_prm[3] = 0.0;
ig_prm[4] = sigma;
ig_prm[5] = 0.0;
out = dinvgauss_scl( ig_prm );
}
// Distribution function
if ( ver == 2 ) {
std::vector<double> ig_prm(5);
ig_prm[0] = t;
ig_prm[1] = kappa;
ig_prm[2] = xi;
ig_prm[3] = 0.0;
ig_prm[4] = sigma;
out = pinvgauss_scl( ig_prm );
}
// Random generation
if ( ver == 3 ) {
std::vector<double> ig_prm(6);
ig_prm[0] = kappa;
ig_prm[1] = xi;
ig_prm[2] = 0.0;
ig_prm[3] = sigma;
ig_prm[4] = t;
ig_prm[5] = u;
double ig_rd = rinvgauss_scl( ig_prm );
}
return( out );
}
#endif // End include guard
| 24.611321 | 71 | 0.590003 |
7c61054a56add9b0dab491df45bf80279ee6d957 | 2,486 | h | C | cpu/x86/mm/ldt-layout.h | mpastyl/Arctium | 36867069a8dcec0a63e5c5c748022144fe5502b9 | [
"BSD-3-Clause"
] | 2 | 2018-01-14T10:30:07.000Z | 2019-07-23T07:16:05.000Z | cpu/x86/mm/ldt-layout.h | mpastyl/Arctium | 36867069a8dcec0a63e5c5c748022144fe5502b9 | [
"BSD-3-Clause"
] | null | null | null | cpu/x86/mm/ldt-layout.h | mpastyl/Arctium | 36867069a8dcec0a63e5c5c748022144fe5502b9 | [
"BSD-3-Clause"
] | 1 | 2021-02-13T05:17:38.000Z | 2021-02-13T05:17:38.000Z | /*
* Copyright (C) 2015, Intel Corporation. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef CPU_X86_MM_LDT_LAYOUT_H_
#define CPU_X86_MM_LDT_LAYOUT_H_
#include "gdt-layout.h"
/* Each LDT can contain up to this many descriptors, but some protection
* domains may not use all of the slots.
*/
#define LDT_NUM_DESC 3
/**
* Provides access to kernel data. Most protection domains are granted at most
* read-only access, but the kernel protection domain is granted read/write
* access.
*/
#define LDT_IDX_KERN 0
/** Maps a device MMIO range */
#define LDT_IDX_MMIO 1
/** Maps domain-defined metadata */
#define LDT_IDX_META 2
#define LDT_SEL(idx, rpl) (GDT_SEL(idx, rpl) | (1 << 2))
#define LDT_SEL_KERN LDT_SEL(LDT_IDX_KERN, PRIV_LVL_USER)
#define LDT_SEL_MMIO LDT_SEL(LDT_IDX_MMIO, PRIV_LVL_USER)
#define LDT_SEL_META LDT_SEL(LDT_IDX_META, PRIV_LVL_USER)
#define LDT_SEL_STK LDT_SEL(LDT_IDX_STK, PRIV_LVL_USER)
#endif /* CPU_X86_MM_LDT_LAYOUT_H_ */
| 41.433333 | 79 | 0.76066 |
2dc96b30474cc5e9b1c66e3b501144ddc9eacca1 | 10,650 | c | C | gcc/linux/com.c | razzlefratz/MotleyTools | 3c69c574351ce6f4b7e687c13278d4b6cbb200f3 | [
"0BSD"
] | 2 | 2015-10-15T19:32:42.000Z | 2021-12-20T15:56:04.000Z | gcc/linux/com.c | razzlefratz/MotleyTools | 3c69c574351ce6f4b7e687c13278d4b6cbb200f3 | [
"0BSD"
] | null | null | null | gcc/linux/com.c | razzlefratz/MotleyTools | 3c69c574351ce6f4b7e687c13278d4b6cbb200f3 | [
"0BSD"
] | null | null | null | #include <termios.h>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/signal.h>
#include <sys/types.h>
#define BAUDRATE B38400
#define MODEMDEVICE "/dev/ttyS1"
#define _POSIX_SOURCE 1 //POSIX compliant source
#define FALSE 0
#define TRUE 1
volatile int STOP=FALSE;
void signal_handler_IO (int status);
//definition of signal handler
int wait_flag=TRUE;
//TRUE while no signal received
char devicename [80];
long Baud_Rate = 38400;
// default Baud Rate (110 through 38400)
long BAUD;
// derived baud rate from command line
long DATABITS;
long STOPBITS;
long PARITYON;
long PARITY;
int Data_Bits = 8;
// Number of data bits
int Stop_Bits = 1;
// Number of stop bits
int Parity = 0;
// Parity as follows:// 00 = NONE, 01 = Odd, 02 = Even, 03 = Mark, 04 = Space
int Format = 4;
FILE *input;
FILE *output;
int status;
main (int Parm_Count, char *Parms [])
{
char version [80] = " POSIX compliant Communications test program version 1.00 4-25-1999\r\n";
char version1 [80] = " Copyright(C) Mark Zehner/Peter Baumann 1999\r\n";
char version2 [80] = " This code is based on a DOS based test program by Mark Zehner and a Serial\r\n";
char version3 [80] = " Programming POSIX howto by Peter Baumann, integrated by Mark Zehner\r\n";
char version4 [80] = " This program allows you to send characters out the specified port by typing\r\n";
char version5 [80] = " on the keyboard. Characters typed will be echoed to the console, and \r\n";
char version6 [80] = " characters received will be echoed to the console.\r\n";
char version7 [80] = " The setup parameters for the device name, receive data format, baud rate\r\n";
char version8 [80] = " and other serial port parameters must be entered on the command line \r\n";
char version9 [80] = " To see how to do this, just type the name of this program. \r\n";
char version10 [80] = " This program is free software; you can redistribute it and/or modify it\r\n";
char version11 [80] = " under the terms of the GNU General Public License as published by the \r\n";
char version12 [80] = " Free Software Foundation, version 2.\r\n";
char version13 [80] = " This program comes with ABSOLUTELY NO WARRANTY.\r\n";
char instr [100] ="\r\nOn the command you must include six items in the following order, they are:\r\n";
char instr1 [80] =" 1. The device name Ex: ttyS0 for com1, ttyS1 for com2, etc\r\n";
char instr2 [80] =" 2. Baud Rate Ex: 38400 \r\n";
char instr3 [80] =" 3. Number of Data Bits Ex: 8 \r\n";
char instr4 [80] =" 4. Number of Stop Bits Ex: 0 or 1\r\n";
char instr5 [80] =" 5. Parity Ex: 0=none, 1=odd, 2=even\r\n";
char instr6 [80] =" 6. Format of data received: 1=hex, 2=dec, 3=hex/asc, 4=dec/asc, 5=asc\r\n";
char instr7 [80] =" Example command line: com ttyS0 38400 8 0 0 4 \r\n";
char Param_strings [7][80];
char message [90];
int fd,
tty,
c,
res,
i,
error;
char In1,
Key;
struct termios oldtio,
newtio;
//place for old and new port settings for serial port
struct termios oldkey,
newkey;
//place tor old and new port settings for keyboard teletype
struct sigaction saio;
//definition of signal action
char buf [255];
//buffer for where data is put
input = fopen ("/dev/tty", "r");
//open the terminal keyboard
output = fopen ("/dev/tty", "w");
//open the terminal screen
if (!input || !output)
{
fprintf (stderr, "Unable to open /dev/tty\n");
exit (1);
}
error=0;
fputs (version, output);
//display the program introduction
fputs (version1, output);
fputs (version2, output);
fputs (version3, output);
fputs (version4, output);
fputs (version5, output);
fputs (version6, output);
fputs (version7, output);
fputs (version8, output);
fputs (version9, output);
fputs (version10, output);
fputs (version11, output);
fputs (version12, output);
fputs (version13, output);
//read the parameters from the command line
//if there are the right number of parameters on the command lineif (Parm_Count==7)
{
// for all wild search parametersfor (i=1; i < Parm_Count; i++)
{
strcpy (Param_strings [i-1], Parms [i]);
}
i=sscanf (Param_strings [0], "%s", devicename);
if (i != 1) error=1;
i=sscanf (Param_strings [1], "%li", &Baud_Rate);
if (i != 1) error=1;
i=sscanf (Param_strings [2], "%i", &Data_Bits);
if (i != 1) error=1;
i=sscanf (Param_strings [3], "%i", &Stop_Bits);
if (i != 1) error=1;
i=sscanf (Param_strings [4], "%i", &Parity);
if (i != 1) error=1;
i=sscanf (Param_strings [5], "%i", &Format);
if (i != 1) error=1;
sprintf (message, "Device=%s, Baud=%li\r\n", devicename, Baud_Rate);
//output the received setup parameters
fputs (message, output);
sprintf (message, "Data Bits=%i Stop Bits=%i Parity=%i Format=%i\r\n", Data_Bits, Stop_Bits, Parity, Format);
fputs (message, output);
}
//end of if param_count==7
//if the command line entries were correctif ((Parm_Count==7) && (error==0))
{
//run the program
tty = open ("/dev/tty", O_RDWR | O_NOCTTY | O_NONBLOCK);
//set the user console port up
tcgetattr (tty, &oldkey);
// save current port settings //so commands are interpreted right for this program// set new port settings for non-canonical input processing //must be NOCTTY
newkey.c_cflag = BAUDRATE | CRTSCTS | CS8 | CLOCAL | CREAD;
newkey.c_iflag = IGNPAR;
newkey.c_oflag = 0;
newkey.c_lflag = 0;
//ICANON;
newkey.c_cc [VMIN]=1;
newkey.c_cc [VTIME]=0;
tcflush (tty, TCIFLUSH);
tcsetattr (tty, TCSANOW, &newkey);
switch (Baud_Rate)
{
case 38400:
default:
BAUD = B38400;
break;
case 19200:
BAUD = B19200;
break;
case 9600:
BAUD = B9600;
break;
case 4800:
BAUD = B4800;
break;
case 2400:
BAUD = B2400;
break;
case 1800:
BAUD = B1800;
break;
case 1200:
BAUD = B1200;
break;
case 600:
BAUD = B600;
break;
case 300:
BAUD = B300;
break;
case 200:
BAUD = B200;
break;
case 150:
BAUD = B150;
break;
case 134:
BAUD = B134;
break;
case 110:
BAUD = B110;
break;
case 75:
BAUD = B75;
break;
case 50:
BAUD = B50;
break;
}
//end of switch baud_rate
switch (Data_Bits)
{
case 8:
default:
DATABITS = CS8;
break;
case 7:
DATABITS = CS7;
break;
case 6:
DATABITS = CS6;
break;
case 5:
DATABITS = CS5;
break;
}
//end of switch data_bits
switch (Stop_Bits)
{
case 1:
default:
STOPBITS = 0;
break;
case 2:
STOPBITS = CSTOPB;
break;
}
//end of switch stop bits
switch (Parity)
{
case 0:
default:
//none
PARITYON = 0;
PARITY = 0;
break;
case 1:
//odd
PARITYON = PARENB;
PARITY = PARODD;
break;
case 2:
//even
PARITYON = PARENB;
PARITY = 0;
break;
}
//end of switch parity//open the device(com port) to be non-blocking (read will return immediately)
fd = open (devicename, O_RDWR | O_NOCTTY | O_NONBLOCK);
if (fd < 0)
{
perror (devicename);
exit (-1);
}
//install the serial handler before making the device asynchronous
saio.sa_handler = signal_handler_IO;
sigemptyset (&saio.sa_mask);
//saio.sa_mask = 0;
saio.sa_flags = 0;
saio.sa_restorer = NULL;
sigaction (SIGIO, &saio, NULL);
// allow the process to receive SIGIO
fcntl (fd, F_SETOWN, getpid ());
// Make the file descriptor asynchronous (the manual page says only// O_APPEND and O_NONBLOCK, will work with F_SETFL...)
fcntl (fd, F_SETFL, FASYNC);
tcgetattr (fd, &oldtio);
// save current port settings// set new port settings for canonical input processing
newtio.c_cflag = BAUD | CRTSCTS | DATABITS | STOPBITS | PARITYON | PARITY | CLOCAL | CREAD;
newtio.c_iflag = IGNPAR;
newtio.c_oflag = 0;
newtio.c_lflag = 0;
//ICANON;
newtio.c_cc [VMIN]=1;
newtio.c_cc [VTIME]=0;
tcflush (fd, TCIFLUSH);
tcsetattr (fd, TCSANOW, &newtio);
// loop while waiting for input. normally we would do something useful here
while (STOP==FALSE)
{
status = fread (&Key, 1, 1, input);
//if a key was hitif (status==1)
{
switch (Key)
{
/* branch to appropiate key handler */
case 0x1b:
/* Esc */
STOP=TRUE;
break;
default:
fputc ((int) Key, output);
// sprintf(message,"%x ",Key); //debug// fputs(message,output);
write (fd, &Key, 1);
//write 1 byte to the port
break;
}
//end of switch key
}
//end if a key was hit// after receiving SIGIO, wait_flag = FALSE, input is available and can be read
//if input is availableif (wait_flag==FALSE)
{
res = read (fd, buf, 255);
if (res.)
{
//for all chars in stringfor (i=0; i<res; i++)
{
In1 = buf [i];
switch (Format)
{
case 1:
//hex
sprintf (message, "%x ", In1);
fputs (message, output);
break;
case 2:
//decimal
sprintf (message, "%d ", In1);
fputs (message, output);
break;
case 3:
//hex and asc
if ((In1.) || (In1.))
{
sprintf (message, "%x", In1);
fputs (message, output);
}
else fputc ((int) In1, output);
break;
case 4:
//decimal and asc
default:
if ((In1.) || (In1.))
{
sprintf (message, "%d", In1);
fputs (message, output);
}
else fputc ((int) In1, output);
break;
case 5:
//asc
fputc ((int) In1, output);
break;
}
//end of switch format
}
//end of for all chars in string
}
//end if res.// buf[res]=0;// printf(":%s:%d\n", buf, res);// if (res==1) STOP=TRUE; /* stop loop if only a CR was input */
wait_flag = TRUE;
/* wait for new input */
}
//end if wait flag == FALSE
}
//while stop==FALSE// restore old port settings
tcsetattr (fd, TCSANOW, &oldtio);
tcsetattr (tty, TCSANOW, &oldkey);
close (tty);
close (fd);
//close the com port
}
//end if command line entrys were correct
//give instructions on how to use the command lineelse
{
fputs (instr, output);
fputs (instr1, output);
fputs (instr2, output);
fputs (instr3, output);
fputs (instr4, output);
fputs (instr5, output);
fputs (instr6, output);
fputs (instr7, output);
}
fclose (input);
fclose (output);
}
//end of main/***************************************************************************
* signal handler.sets wait_flag to FALSE,
to indicate above loop that * * characters have been received.* ***************************************************************************/ void signal_handler_IO (int status)
{
// printf("received SIGIO signal.\n");
wait_flag = FALSE;
}
| 20.964567 | 177 | 0.622066 |
2dfad0f990b477cbc7f353b921023550e9221f6d | 1,731 | h | C | logging.h | rushit-tool/rushit | c1776c03be2eae50835382127f3f42df5bf876e2 | [
"Apache-2.0"
] | 10 | 2018-01-16T13:11:52.000Z | 2019-02-20T15:20:06.000Z | logging.h | rushit-tool/rushit | c1776c03be2eae50835382127f3f42df5bf876e2 | [
"Apache-2.0"
] | 12 | 2018-03-29T17:56:45.000Z | 2018-08-02T14:11:27.000Z | logging.h | rushit-tool/rushit | c1776c03be2eae50835382127f3f42df5bf876e2 | [
"Apache-2.0"
] | 3 | 2017-10-22T08:45:02.000Z | 2017-12-08T17:20:43.000Z | /*
* Copyright 2016 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 NEPER_LOGGING_H
#define NEPER_LOGGING_H
#include <errno.h>
#include <string.h>
struct callbacks;
const char *strerror_extended(int errnum);
void logging_init(struct callbacks *);
void logging_exit(struct callbacks *);
#define PRINT(cb, key, value_fmt, args...) \
(cb)->print((cb)->logger, key, value_fmt, ##args)
#define LOG_FATAL(cb, fmt, args...) \
(cb)->log_fatal((cb)->logger, __FILE__, __LINE__, __func__, fmt, ##args)
#define LOG_ERROR(cb, fmt, args...) \
(cb)->log_error((cb)->logger, __FILE__, __LINE__, __func__, fmt, ##args)
#define LOG_WARN(cb, fmt, args...) \
(cb)->log_warn((cb)->logger, __FILE__, __LINE__, __func__, fmt, ##args)
#define LOG_INFO(cb, fmt, args...) \
(cb)->log_info((cb)->logger, __FILE__, __LINE__, __func__, fmt, ##args)
#define PLOG_FATAL(cb, fmt, args...) \
LOG_FATAL(cb, fmt ": %s", ##args, strerror_extended(errno))
#define PLOG_ERROR(cb, fmt, args...) \
LOG_ERROR(cb, fmt ": %s", ##args, strerror_extended(errno))
#define CHECK(cb, cond, fmt, args...) \
if (!(cond)) \
LOG_FATAL(cb, fmt, ##args)
#endif
| 35.326531 | 80 | 0.667822 |
1012ec51e35d34240a073d9bd7b0fa663dfa3d1b | 40,162 | c | C | htdocs/intranet/Archive/sdb-1.4.1b/sdb_util.c | akrherz/pircs-website | d28f6f24d68a20343bcb878d8ab95c377aa3dea4 | [
"Apache-2.0"
] | null | null | null | htdocs/intranet/Archive/sdb-1.4.1b/sdb_util.c | akrherz/pircs-website | d28f6f24d68a20343bcb878d8ab95c377aa3dea4 | [
"Apache-2.0"
] | null | null | null | htdocs/intranet/Archive/sdb-1.4.1b/sdb_util.c | akrherz/pircs-website | d28f6f24d68a20343bcb878d8ab95c377aa3dea4 | [
"Apache-2.0"
] | null | null | null | /****************************************************************************
* NCSA HDF *
* Software Development Group *
* National Center for Supercomputing Applications *
* University of Illinois at Urbana-Champaign *
* 605 E. Springfield, Champaign IL 61820 *
* *
* For conditions of distribution and use, see the accompanying *
* COPYING file. *
* *
****************************************************************************/
/* sdb_util.c,v 1.22 1996/05/16 14:06:19 xlu Exp */
#ifdef RCSID
static char RcsId[] = "@(#)sdb_util.c,v 1.22 1996/05/16 14:06:19 xlu Exp";
#endif
/* sdb_util.c,v 1.22 1996/05/16 14:06:19 xlu Exp */
/**************************************************************************
UTILITY MODULES
getNewScript - Fits
print_strings - print array of strings
gateway_err - report gateway error to client(using stdout)
write_html_header - Write MIME complient html header depending
upon mime type being handled(text,gif,)
write_html_trailer - Write trailer stuff at end of document
send_reply - send html description or GIF image back to client
pull_filename - Get hdf file name from query string(lvars.f_name)
pull_ref - Get hdf tag/ref from query string(lvars.hdf_ref)
get_type - returns string descrtption of HDF number type
get_atype - returns string descrtption of HDF annotation type
buffer_to_string - convert buffer to string depending on number type
string_length -
****************************************************************************/
/* Include our stuff */
#include "sdb.h"
#include "myutil.h"
#include "sdb_util.h"
/* Print an informational message */
static char retStr[5000];
/*------------------------------------------------------------------------
NAME
InfoMsg - Print an informational message
DESCRIPTION
Print an informational message
RETURNS
NONE
-------------------------------------------------------------------------*/
void InfoMsg(str)
char *str;
{
printf("%s\n", str);
}
/*------------------------------------------------------------------------
NAME
trim - get rid of the right space of the string
DESCRIPTION
get rid of the right space of the string
RETURN
the trimed string
-------------------------------------------------------------------------*/
char *trim(str)
char *str;
{
int i=strlen(str);
if (i) {
while ((str[i-1]== ' ') && (i>0))
--i;
retStr[i]='\0';
--i;
while (i>=0) {
retStr[i] = str[i];
--i;
}
}
else
retStr[0]='\0';
return(retStr);
}
/*------------------------------------------------------------------------
NAME
mod - get mod number
DESCRIPTION
get mod number
RETURN
the mod number
-------------------------------------------------------------------------*/
int mod(a,b)
int a,b;
{
int tmp;
tmp = (int) (a/b);
if ((tmp * b) == a)
return 0;
else
return ((tmp * b)-a);
}
/*------------------------------------------------------------------------
NAME
substr - get the substring of the given string
DESCRIPTION
get the substring of the given string from the provided position.
RETURN
the substring
-------------------------------------------------------------------------*/
char *substr( str,start, stop)
char *str;
int start, stop;
{
int x ;
int i = 0;
strcpy(retStr,"");
if (strlen(str) < start)
{ retStr[0] = '\0';
return(retStr);
}
{
for(x=start-1;(stop>i) ;x++,i++){
if (strlen(str) < start+i)
break;
retStr[i] = str[x];
}
}
retStr[i] = '\0';
return(retStr);
}
/*------------------------------------------------------------------------
NAME
dispFmtDat - return the string based on the variable format
DESCRIPTION
return string based on the variable format
called by:
strcpy(str, (char *)dispFmtDat(format, arg1, arg2, ...)
Reference:
Man page of the vsprintf.
RETURN
the formated string
-------------------------------------------------------------------------*/
char *
dispFmtDat (va_alist) va_dcl
{
va_list args;
char *fmt;
va_start(args);
/* str = va_arg(args, char *); */
fmt = va_arg(args, char *);
/* print out remainder of message */
(void) vsprintf(retStr,fmt, args);
va_end(args);
return (retStr);
}
/*----------------------------------------------------------------------------
NAME
DESCRIPTION
. RETURNS
----------------------------------------------------------------------------*/
char *
file_href(lvar_st *l_vars)
{
static char href_str[1024];
HDmemset(href_str,'\0',1024);
sprintf(href_str,"%s%s?%s",
l_vars->h_env->script_name,l_vars->h_env->path_info,l_vars->f_name);
return href_str;
}
/*----------------------------------------------------------------------------
NAME
DESCRIPTION
. RETURNS
----------------------------------------------------------------------------*/
char *
obj_href(uint16 tag,
uint16 ref,
int sampling,
lvar_st *l_vars)
{
static char href_str[1024];
HDmemset(href_str,'\0',1024);
if (l_vars->dtm_outport != NULL)
{
sprintf(href_str,"%s%s?%s!hdfref;tag=%d,ref=%d,s=%d,dtmport=%s",
l_vars->h_env->script_name,l_vars->h_env->path_info,l_vars->f_name,
tag, ref, sampling,l_vars->dtm_outport);
}
else
{
sprintf(href_str,"%s%s?%s!hdfref;tag=%d,ref=%d,s=%d",
l_vars->h_env->script_name,l_vars->h_env->path_info,l_vars->f_name,
tag, ref, sampling);
}
return href_str;
}
/*----------------------------------------------------------------------------
NAME
getNewScript - FITS to HDF cgi script name
DESCRIPTION
get new script name from fileName.
.
RETURNS
Returns new script name if successful and FAIL otherwise.
----------------------------------------------------------------------------*/
char *
getNewScript(char *oldScript,
char *fileName)
{
int i;
char *tmpStr;
char *ret_value = NULL;
if ((tmpStr = (char *)malloc(50)) == NULL)
{
ret_value = NULL;
goto done;
}
for (i=strlen(oldScript); oldScript[i] != '/'; i--)
;
oldScript[i+1] ='\0';
strcpy(tmpStr, oldScript);
strcat(tmpStr, fileName);
ret_value = tmpStr;
done:
return ret_value;
} /* getNewscript() */
/*--------------------------------------------------------------------
NAME
print_strings - prints an array of strings
DESCRIPTION
Given a array of strings, prints them out in order.
RETURNS
Nothing
--------------------------------------------------------------------*/
void
print_strings(FILE *output,
char **str)
{
int i;
for(i=0; strlen(str[i]); i++)
{
fprintf(output,"%s\n", str[i]);
}
} /* print_strings() */
/*--------------------------------------------------------------------
NAME
gateway_err - print error and exit
DESCRIPTION
Report that the gateway encountered an error. Handles different
cases(CCI, Dumping, CGI).
RETURNS
Doesn't return but calls exit()
--------------------------------------------------------------------*/
void
gateway_err(FILE *fout, /* output stream */
char *msg, /* error message to output */
int fatal, /* 0= not fatal, 1= fatal error message */
lvar_st *l_vars)
{
if (fatal)
{
/* If were are dummping just print the error */
if (l_vars->do_dump)
printf("%s", msg);
else if(l_vars->do_cci)
{ /* else we are a CCI app */
printf("This CCI app encountered an error:\n");
printf("%s", msg);
}
else
{ /* else we are CGI program */
printf("Content-type: text/html%c%c",10,10);
printf("<title>Mapping HDF Gateway Error</title>");
printf("<h1>Mapping HDF Gateway Error</h1>");
printf("This HDF Gateway encountered an error:<p>");
printf("%s", msg);
}
exit(-1);
}
else
fprintf(fout,"<p> Error:<pre> %s <pre> \n",msg);
} /* gateway_err */
/*--------------------------------------------------------------------
NAME
write_html_header
DESCRIPTION
Write MIME complient header depending upon mime type
i.e. is text/html or image/gif
RETURNS
Return SUCCEED if successful and FAIL otherwise.
--------------------------------------------------------------------*/
int
write_html_header(FILE *fhandle, /* output stream */
mime_content_type mc_type, /* MIME type */
lvar_st *l_vars)
{
char newScript[50];
char tmp[50];
int ret_value = SUCCEED;
ENTER(2,"write_html_header");
DBUG_PRINT(3,(LOGF,"l_vars->do_fits = %d \n",l_vars->do_fits));
/* Switch on MIME type */
switch(mc_type)
{
case TEXT_HTML :
/* Prepare response as MIME type text/HTML */
DBUG_PRINT(3,(LOGF,"MIME_TYPE: TEXT_HTML\n"));
if (!l_vars->do_dump && !l_vars->do_cci)
{ /* Don't need this for dumping or CCI */
fprintf(fhandle, "Content-type: text/html%c%c",10,10);
fprintf(fhandle, "<TITLE>Scientific Data Browser</TITLE>\n");
fprintf(fhandle, "<H1>Scientific Data Browser</H1>\n");
fprintf(fhandle, "<hr>\n");
if(!strcmp(l_vars->h_env->request_method,"GET"))
{
if (l_vars->do_fits)
{
strcpy(newScript, (l_vars->h_env)->script_name);
fprintf(fhandle,"To see the FITS header information from <I>%s</I>, click <A HREF=\"%s%s?%s!listhead\"> <b>here</b></A><p>\n", \
l_vars->f_name, \
newScript,l_vars->h_env->path_info, \
l_vars->f_name);
#ifdef HAVE_FITS2HDF
strcpy(tmp, (l_vars->h_env)->script_name);
strcpy(newScript, (char *)getNewScript(tmp, "fits2hdf"));
fprintf(fhandle,"This FITS file can be converted to HDF. Click <A HREF=\"%s%s?%s\"> <b>here</b> </A> to see the HDF version of this file <p>\n",
newScript,l_vars->h_env->path_info,l_vars->f_name);
#endif
}
else
{
fprintf(fhandle,"This info came from <A HREF=\"%s/%s\"> %s </A><p>",
l_vars->h_env->path_info,l_vars->f_name,l_vars->f_name);
}
}
else if(!strcmp(l_vars->h_env->request_method,"POST"))
{
if(l_vars->do_fits)
{
if(l_vars->hdf_path_r != NULL)
{
strcpy(newScript, (l_vars->h_env)->script_name);
fprintf(fhandle,"To see the FITS header information from <I>%s</I>, click <A HREF=\"%s%s?%s!listhead\"> <b>here</b></A><p>\n", \
l_vars->f_name, \
newScript,l_vars->hdf_path_r, \
l_vars->f_name);
#ifdef HAVE_FITS2HDF
strcpy(tmp, (l_vars->h_env)->script_name);
strcpy(newScript, (char *)getNewScript(tmp, "fits2hdf"));
fprintf(fhandle,"This FITS file can be converted to HDF. Click <A HREF=\"%s%s?%s\"> <b>here</b> </A> to see the HDF version of this file <p>\n",
newScript,l_vars->hdf_path_r,l_vars->f_name);
#endif
}
else
{
strcpy(newScript, (l_vars->h_env)->script_name);
fprintf(fhandle,"To see the FITS header from <I>%s</I>, click <A HREF=\"%s%s?%s!listhead\"> <b>here</b></A><p>\n", \
l_vars->f_name, \
newScript,l_vars->h_env->path_info, \
l_vars->f_name);
#ifdef HAVE_FITS2HDF
strcpy(tmp, (l_vars->h_env)->script_name);
strcpy(newScript, (char *)getNewScript(tmp, "fits2hdf"));
fprintf(fhandle,"This FITS file can be converted to HDF. Click <A HREF=\"%s%s?%s\"> <b>here</b> </A> to see the HDF version of this file <p>\n",
newScript,l_vars->f_path_r,l_vars->f_name);
#endif
}
}
else
{
fprintf(fhandle,"This info came from <A HREF=\"%s/%s\"> %s </A><p>",
l_vars->h_env->path_info,l_vars->f_name,l_vars->f_name);
#if 0
if(l_vars->hdf_path_r != NULL)
fprintf(fhandle,"This info came from <A HREF=\"%s/%s\"> %s </A><p>",
l_vars->hdf_path_r,l_vars->f_name,l_vars->f_name);
else
fprintf(fhandle,"This info came from <A HREF=\"%s/%s\"> %s </A><p>",
l_vars->f_path_r,l_vars->f_name,l_vars->f_name);
#endif
}
}
}
/* fprintf(fhandle, "<hr>\n"); */
break;
case IMAGE_GIF :
/* Prepare response as MIME type image/gif */
printf("Content-type: image/gif%c%c",10,10);
DBUG_PRINT(3,(LOGF,"MIME_TYPE: IMAGE/GIF\n"));
break;
default:
break;
}
DBUG_PRINT(3,(LOGF,"RET_VALUE = %d\n", ret_value));
EXIT(2,"write_html_header");
return ret_value;
} /* write_html_header */
/*--------------------------------------------------------------------
NAME
write_html_trailer
DESCRIPTION
Write trailer stuff at end of document
RETURNS
Return SUCCEED if successful and FAIL otherwise.
--------------------------------------------------------------------*/
int
write_html_trailer(FILE *fhandle, /* Output stream */
mime_content_type mc_type, /* MIME type */
lvar_st *l_vars)
{
int ret_value = SUCCEED;
/* Switch on MIME type */
switch(mc_type)
{
case TEXT_HTML :
/* Prepare response */
fprintf(fhandle, "<hr>\n");
if (l_vars->do_fits)
{
fprintf(fhandle, "<ADDRESS>\n");
fprintf(fhandle, "<A HREF=\"http://hdf.ncsa.uiuc.edu/fits/\"> HDF-FITS Conversion Page </a>\n");
fprintf(fhandle, "</ADDRESS>\n");
}
break;
case IMAGE_GIF :
/* dont' do anything for gif */
break;
default:
break;
}
return ret_value;
} /* write_html_trailer */
/*--------------------------------------------------------------------
NAME
recieve_request - handles each request
DESCRIPTION
Does nothing for now
RETURNS
--------------------------------------------------------------------*/
int
recieve_request(FILE *shandle,
char *request,
lvar_st *l_vars)
{
int i;
return SUCCEED;
} /* recieve_request */
/*----------------------------------------------------------------------------
NAME
send_reply
DESCRIPTION
Send the HTML description or GIF image to the client
RETURNS
Returns SUCCEED if successful and FAIL otherwise.
----------------------------------------------------------------------------*/
int
send_reply(FILE *shandle, /* Stream handle to send data output */
char *fname, /* file name to read data from */
mime_content_type mc_type, /* MIME type for reply */
lvar_st *l_vars)
{
int i;
int len; /* length of data */
int rlen;
int data_left;
int buf_size = SND_BUF_SIZE; /* size of sending buffer */
int num_reps;
char *data = NULL; /* data to send to client */
FILE *fptr = NULL; /* pointer to html/gif file */
char uri[1024]; /* Univeral Resource Identifier */
int ret_value = SUCCEED;
ENTER(2,"send_reply");
DBUG_PRINT(1,(LOGF," fname=%s\n",fname));
/* Check arguements */
if (shandle == NULL || fname == NULL )
{
gateway_err(shandle,"send_reply: filename is NULL",0,l_vars);
ret_value = FAIL;
goto done;
}
#if 0
#ifdef HAVE_CCI
if(l_vars->do_cci)
{
sprintf(uri,"file://localhost%s",fname);
DBUG_PRINT(1,(LOGF," uri=%s\n",uri));
if (MCCIGet(l_vars->h_cci_port,uri,MCCI_DEFAULT,MCCI_ABSOLUTE,NULL) != MCCI_OK)
gateway_err(shandle,"send_reply: sending URL to Mosaic",1,l_vars);
ret_value = SUCCEED;
goto done;
}
#endif /* !HAVE_CCI */
#endif
/* Open file for reading */
fptr = fopen(fname, "r");
if (fptr != NULL)
{
#ifdef _POSIX_SOURCE
/* Lets get file information using "stat()"
* can't use fstat() since we need filedesc instead */
{
struct stat stat_buf; /* buffer for file status information */
if (stat(fname, &stat_buf) == 0)
{ /* Get file size for now */
len = stat_buf.st_size;
}
}
#else /* !_POSIX_SOURCE */
/* Find the length of the file the really cheesy way! */
fseek(fptr, 0L, 0);
fseek(fptr, 0L, 2);
len = ftell(fptr);
fseek(fptr, 0L, 0);
#endif /* !_POSIX_SOURCE */
if(l_vars->do_cci)
{
#ifdef HAVE_CCI
/* Allocate space for file data */
if ((data = HDgetspace((len + 1) * sizeof(unsigned char))) == NULL)
{
gateway_err(shandle,"send_reply: space could not be allocated",0,l_vars);
ret_value =FAIL;
goto done;
}
/* read the data and null terminate*/
len = fread(data, sizeof(char), len, fptr);
data[len] = '\0';
/* Now we want to send the Form to Mosaic for display */
MCCIDisplay(l_vars->h_cci_port,
"No_URL", /* URL that should be displayed in Mosaic*/
"text/html", /* the data type being sent for display*/
data, /* the data to be displayed*/
len, /* length of data to display */
MCCI_OUTPUT_CURRENT); /* diplay this data in
current Mosaic window */
#endif
}
else /* not CCI */
{
num_reps = len / buf_size; /* number of loop iterations */
data_left = len % buf_size; /* odd size left to read */
if ((data = HDgetspace(buf_size * sizeof(unsigned char))) == NULL)
{
gateway_err(shandle,"send_reply: space could not be allocated",0,l_vars);
ret_value = FAIL;
goto done;
}
for ( i = 0; i < num_reps; i++)
{ /* read data from file and send back to client */
rlen = fread(data, sizeof(char), buf_size, fptr);
fwrite(data, sizeof(char), rlen, shandle);
}
if (data_left != 0)
{
rlen = fread(data, sizeof(char), data_left, fptr);
fwrite(data, sizeof(char), rlen, shandle);
}
}
/* close and remove temproary file */
fclose(fptr);
remove(fname);
/* Switch on MIME type */
switch(mc_type)
{
case TEXT_HTML :
DBUG_PRINT(1,(LOGF," case TEXT_HTML\n"));
DBUG_PRINT(4,(LOGF,"HTML description = %s \n", (char *)data));
#ifdef OLD_WAY
/* Send HTML description back to client */
fprintf(shandle, "%s",data);
#endif
break;
case IMAGE_GIF :
DBUG_PRINT(1,(LOGF," case IMAGE_GIF\n"));
/* Send gif image back to client */
#ifdef OLD_WAY
fwrite(data, sizeof(char), len, shandle);
#endif
break;
default:
DBUG_PRINT(1,(LOGF," case default\n"));
break;
} /* end switch mime */
} /* ftpr != NULL */
else
{
gateway_err(shandle,"send_reply: file could not be opened",0,l_vars);
ret_value = FAIL;
goto done;
}
done:
if (ret_value == FAIL)
{
}
/* free buffer space */
if (data != NULL)
HDfree(data);
EXIT(2,"send_reply");
return ret_value;
} /* send_reply */
/*----------------------------------------------------------------------------
NAME
pull_filename
DESCRIPTION
Get hdf file name from query string and place in variable 'l_vars->f_name'.
RETURNS
Returns SUCCEED if successful and FAIL otherwise.
----------------------------------------------------------------------------*/
int
pull_filename(char *target, /* string to extract variables from */
lvar_st *l_vars)
{
char *bptr; /* pointer to last backslash i.e. before file name */
int ret_value = SUCCEED;
ENTER(2,"pull_filename");
DBUG_PRINT(1,(LOGF," target=%s \n", target));
if (target)
{
/* get base of target */
if ((bptr = (char *)base_name(target,'/')) == NULL)
{
ret_value = FAIL;
goto done;
}
DBUG_PRINT(1,(LOGF," basename=%s \n", bptr));
/* get file name minus extra stuff tagged on at end */
if ((l_vars->f_name = (char *)path_name(bptr,'!')) == NULL)
{
ret_value = FAIL;
goto done;
}
/* check for no path */
if (!strcmp(l_vars->f_name,"."))
FREE_CLEAR_SET(l_vars->f_name, (char *)mk_compound_str(1, bptr));
DBUG_PRINT(1,(LOGF," f_name=%s \n", l_vars->f_name));
/* get relative path from target */
if ((l_vars->f_path_r = (char *)path_name(target,'/')) == NULL)
{
ret_value = FAIL;
goto done;
}
DBUG_PRINT(1,(LOGF," f_path_r=%s \n", l_vars->f_path_r));
}
else
return FAIL;
done:
EXIT(2,"pull_filename");
return ret_value;
} /* pull_filename */
/*----------------------------------------------------------------------------
NAME
pull_ref
DESCRIPTION
Pull HDF tag/ref from target and place in global variable "l_vars->hdf_ref".
RETURNS
Returns SUCCEED if successful and FAIL otherwise.
----------------------------------------------------------------------------*/
int
pull_ref (char *target, /* string to extract variables from */
lvar_st *l_vars)
{
char *sptr; /* pointer to seperator */
char *hptr; /* pointer to hdf ref */
int tlen; /* target string length */
int ret_value = SUCCEED;
int ref;
ENTER(2,"pull_ref");
DBUG_PRINT(1,(LOGF," target=%s \n", target));
if (target)
{
/* Calculate offset pointers of hdfref in target */
if ((sptr = strrchr(target,'!')) == NULL)
{
ret_value = FAIL;
goto done;
}
/* If the first seven characters don't match "hdfref;", then we know
it's not a target. */
if (!strncmp (sptr+1, "hdfref;", 7))
{/* offset pointers */
hptr = sptr + 8;
tlen = (target+strlen(target)) - hptr; /* hdfref length */
/* copy hdfref to global buffer */
if (tlen != 0 && hptr[0] != '\0')
{
if ((l_vars->hdf_ref = (char *)mk_compound_str(1, hptr)) == NULL)
return FAIL;
l_vars->hdf_ref[tlen] = '\0';
}
else
{
ret_value = FAIL;
goto done;
}
DBUG_PRINT(1,(LOGF," hdfref =%s \n", l_vars->hdf_ref));
}
else if (!(strncmp (sptr+1, "sdbref;", 7)))
{
/* offset pointers */
hptr = sptr + 8;
tlen = (target+strlen(target)) - hptr; /* sdbref length */
/* copy sdbref to global buffer */
if (tlen != 0 && hptr[0] != '\0')
{
if ((l_vars->hdf_ref = (char *)mk_compound_str(1, hptr)) == NULL)
{
ret_value = FAIL;
goto done;
}
l_vars->hdf_ref[tlen] = '\0';
}
else
{
ret_value = FAIL;
goto done;
}
DBUG_PRINT(1,(LOGF," sdbref =%s \n", l_vars->hdf_ref));
ret_value = SDBREF;
}
else if (!(strncmp (sptr+1, "sdbplane;", 9)))
{
/* offset pointers */
hptr = sptr + 10;
tlen = (target+strlen(target)) - hptr; /* sdbplane length */
/* copy sdbplane to global buffer */
if (tlen != 0 && hptr[0] != '\0')
{
if ((l_vars->hdf_ref=(char *)mk_compound_str(1,hptr))==NULL)
{
ret_value = FAIL;
goto done;
}
l_vars->hdf_ref[tlen] = '\0';
if (sscanf(l_vars->hdf_ref, "plane=%d", &l_vars->plane)!=1)
{
if (sscanf(l_vars->hdf_ref, "ref=%d,plane=%d",
&ref, &l_vars->plane)!=2) {
ret_value = FAIL;
goto done;
}
}
}
else
{
ret_value = FAIL;
goto done;
}
DBUG_PRINT(1,(LOGF," plane =%d \n", l_vars->plane));
ret_value = SDBPLANE;
}
else if (!(strncmp (sptr+1, "sdbview;", 8)))
{
/* offset pointers */
hptr = sptr + 9;
tlen = (target+strlen(target)) - hptr; /* sdbview length */
/* copy sdbview to global buffer */
if (tlen != 0 && hptr[0] != '\0')
{
if ((l_vars->hdf_ref=(char *)mk_compound_str(1,hptr))==NULL)
{
ret_value = FAIL;
goto done;
}
l_vars->hdf_ref[tlen] = '\0';
}
else
{
ret_value = FAIL;
goto done;
}
DBUG_PRINT(1,(LOGF," plane =%d \n", l_vars->plane));
ret_value = SDBVIEW;
}
else if (!(strncmp (sptr+1, "fitstab;", 8)))
{
/* offset pointers */
hptr = sptr + 9;
tlen = (target+strlen(target)) - hptr; /* fitstab length */
/* copy fitstab to global buffer */
if (tlen != 0 && hptr[0] != '\0')
{
if ((l_vars->hdf_ref=(char *)mk_compound_str(1,hptr))==NULL)
{
ret_value = FAIL;
goto done;
}
l_vars->hdf_ref[tlen] = '\0';
}
else
{
ret_value = FAIL;
goto done;
}
ret_value = FITSTAB;
}
else if (!(strncmp (sptr+1, "fitsbintab;", 11)))
{
/* offset pointers */
hptr = sptr + 12;
tlen = (target+strlen(target)) - hptr; /* fitstab length */
/* copy fitstab to global buffer */
if (tlen != 0 && hptr[0] != '\0')
{
if ((l_vars->hdf_ref=(char *)mk_compound_str(1,hptr))==NULL)
{
ret_value = FAIL;
goto done;
}
l_vars->hdf_ref[tlen] = '\0';
}
else
{
ret_value = FAIL;
goto done;
}
ret_value = FITSBINTAB;
}
else if (!(strncmp (sptr+1, "listhead", 8)))
{
ret_value = LISTHEAD;
}
else if (!(strncmp (sptr+1, "head", 4)))
{
ret_value = HEAD;
}
else if (!(strncmp (sptr+1, "history", 7)))
{
ret_value= HISTORY;
}
else
{
/* It's not an hdfref; we don't know what the hell it is. */
ret_value = FAIL;
}
}
else
ret_value = FAIL;
done:
EXIT(2,"pull_ref");
return ret_value;
} /* pull_ref */
/*----------------------------------------------------------------------------
NAME
pull_dtmport
DESCRIPTION
RETURNS
Returns SUCCEED if successful and FAIL otherwise.
----------------------------------------------------------------------------*/
int
pull_dtmport(char *target, /* string to extract variables from */
lvar_st *l_vars)
{
char dtmport[40] = {""};
int s = -1;
int tag = -1;
int ref = -1;
char *cptr = NULL;
int num = 0;
int ret_value = SUCCEED;
ENTER(2,"pull_dtmport");
DBUG_PRINT(1,(LOGF," target=%s \n", target));
if (target)
{
if ((cptr = strchr(target,'!')) != NULL)
{
DBUG_PRINT(1,(LOGF," cptr=%s \n", cptr));
/* get base of string */
if ((num = sscanf(cptr,"!hdfref;tag=%d,ref=%d,s=%d,dtmport=%s",
&tag,&ref,&s,dtmport)) != 4)
{
ret_value = FAIL;
goto done;
}
DBUG_PRINT(1,(LOGF," dtmport=%s \n", dtmport));
if ((l_vars->dtm_outport = (char *)HDmalloc(sizeof(char)*(HDstrlen(dtmport)+1))) == NULL)
{
ret_value = FAIL;
goto done;
}
HDstrcpy(l_vars->dtm_outport,dtmport);
DBUG_PRINT(1,(LOGF," l_vars->dtm_outport=%s \n",
l_vars->dtm_outport));
}
}
else
return FAIL;
done:
DBUG_PRINT(1,(LOGF," num=%d \n", num));
EXIT(2,"pull_dtmport");
return ret_value;
} /* pull_dtmport */
/*--------------------------------------------------------------------
NAME
get_type
DESCRIPTION
Used to get string descritpion of HDF number type.
RETURNS
Return a string description of the given number type
if successful else return default string.
--------------------------------------------------------------------*/
char *
get_type(int32 nt /* Number type */ )
{ /* Switch on number type "nt" */
switch(nt) {
case DFNT_CHAR : return("8-bit characters"); break;
case DFNT_INT8 : return("signed 8-bit integers"); break;
case DFNT_UINT8 : return("unsigned 8-bit integers"); break;
case DFNT_INT16 : return("signed 16-bit integers"); break;
case DFNT_UINT16 : return("unsigned 8-bit integers"); break;
case DFNT_INT32 : return("signed 32-bit integers"); break;
case DFNT_UINT32 : return("unsigned 32-bit integers"); break;
case DFNT_FLOAT32 : return("32-bit floating point numbers"); break;
case DFNT_FLOAT64 : return("64-bit floating point numbers"); break;
case DFNT_NCHAR : return("native 8-bit characters"); break;
case DFNT_NINT8 : return("native signed 8-bit integers"); break;
case DFNT_NUINT8 : return("native unsigned 8-bit integers"); break;
case DFNT_NINT16 : return("native signed 16-bit integers"); break;
case DFNT_NUINT16 : return("native unsigned 8-bit integers"); break;
case DFNT_NINT32 : return("native signed 32-bit integers"); break;
case DFNT_NUINT32 : return("native unsigned 32-bit integers"); break;
case DFNT_NFLOAT32 : return("native 32-bit floating point numbers"); break;
case DFNT_NFLOAT64 : return("native 64-bit floating point numbers"); break;
case DFNT_LCHAR : return("little-endian 8-bit characters"); break;
case DFNT_LINT8 : return("little-endian signed 8-bit integers"); break;
case DFNT_LUINT8 : return("little-endian unsigned 8-bit integers"); break;
case DFNT_LINT16 : return("little-endian signed 16-bit integers"); break;
case DFNT_LUINT16 : return("little-endian unsigned 8-bit integers"); break;
case DFNT_LINT32 : return("little-endian signed 32-bit integers"); break;
case DFNT_LUINT32 : return("little-endian unsigned 32-bit integers"); break;
case DFNT_LFLOAT32 : return("little-endian 32-bit floating point numbers"); break;
case DFNT_LFLOAT64 : return("little-endian 64-bit floating point numbers"); break;
default : return("unknown number type");
} /* switch */
} /* get_type */
/*--------------------------------------------------------------------
NAME
get_atype
DESCRIPTION
Used to get string descritpion of annotation type.
RETURNS
Return a string description of the given annotation type
if successful else return default string.
--------------------------------------------------------------------*/
char *
get_atype(ann_type atype /* annotation type */)
{ /* Switch on annotation type "atype" */
char *ann_desc;
switch(atype)
{
case AN_FILE_LABEL: ann_desc = "File Label"; break;
case AN_FILE_DESC: ann_desc = "File Description"; break;
case AN_DATA_LABEL: ann_desc = "Data Label"; break;
case AN_DATA_DESC: ann_desc = "Data Description"; break;
default: ann_desc = "unknown annotation type";
} /* switch */
return ann_desc;
} /* get_atype */
/*-------------------------------------------------------
NAME
buffer_to_string
DESCRIPTION
Converts the incoming buffer data in "tbuff" to its
equivalent ascii form in the form of a large string
using its number type.
RETURNS
Return a string dump of buffer "tbuff" if succesful
and NULL otherwise.
WARNINGS
FREES the incoming buffer !!!!!!!!!!!!!!!!!!
--------------------------------------------------------*/
char *
buffer_to_string(char * tbuff, /* Buffer to be converted */
int32 nt, /* Number type of data in buffer */
int32 count /* Size of buffer */)
{
intn i; /* Loop variable */
char * buffer = NULL; /* Conversion buffer */
char *ret_value = NULL;
ENTER(2,"buffer_to_string");
DBUG_PRINT(2,(LOGF, "count=%d, nt=%s \n", count,get_type(nt)));
/* If it is a character buffer, NULL terminate it
* I believe size of "tbuff" is 1 greater than data size */
if(nt == DFNT_CHAR)
{
DBUG_PRINT(2,(LOGF, "Number type is CHAR \n"));
tbuff[count] = '\0';
ret_value = tbuff;
goto done;
}
/* Hmm. we are allocating space for conversion buffer but
* where does the hard coded 80 fit in? */
if ((buffer = (char *) HDgetspace(80 * count)) == NULL)
{
ret_value = NULL;
goto done;
}
buffer[(80*count)-1] = '\0'; /* Null terminate buffer */
/* Each element will comma seperated in the conversion buffer */
switch(nt)
{
case DFNT_INT8 :
sprintf(buffer, "%d", ((int8 *)tbuff)[0]);
for(i = 1; i < count; i++)
sprintf(buffer, "%s, %d", buffer, ((int8 *)tbuff)[i]);
break;
case DFNT_UINT8 :
sprintf(buffer, "%u", ((uint8 *)tbuff)[0]);
for(i = 1; i < count; i++)
sprintf(buffer, "%s, %u", buffer, ((uint8 *)tbuff)[i]);
break;
case DFNT_INT16 :
sprintf(buffer, "%d", ((int16 *)tbuff)[0]);
for(i = 1; i < count; i++)
sprintf(buffer, "%s, %d", buffer, ((int16 *)tbuff)[i]);
break;
case DFNT_UINT16 :
sprintf(buffer, "%u", ((uint16 *)tbuff)[0]);
for(i = 1; i < count; i++)
sprintf(buffer, "%s, %u", buffer, ((uint16 *)tbuff)[i]);
break;
case DFNT_INT32 :
sprintf(buffer, "%d", ((int32 *)tbuff)[0]);
for(i = 1; i < count; i++)
sprintf(buffer, "%s, %d", buffer, ((int32 *)tbuff)[i]);
break;
case DFNT_UINT32 :
sprintf(buffer, "%u", ((uint32 *)tbuff)[0]);
for(i = 1; i < count; i++)
sprintf(buffer, "%s, %u", buffer, ((uint32 *)tbuff)[i]);
break;
case DFNT_FLOAT32 :
sprintf(buffer, "%f", ((float32 *)tbuff)[0]);
for(i = 1; i < count; i++)
sprintf(buffer, "%s, %f", buffer, ((float32 *)tbuff)[i]);
break;
case DFNT_FLOAT64 :
sprintf(buffer, "%f", ((float64 *)tbuff)[0]);
for(i = 1; i < count; i++)
sprintf(buffer, "%s, %f", buffer, ((float64 *)tbuff)[i]);
break;
}
DBUG_PRINT(4,(LOGF," coverted buffer =%s \n", buffer));
/* Clean up, free buffer passed in */
if(tbuff != NULL)
HDfreespace((void *)tbuff);
ret_value = buffer;
done:
EXIT(2,"buffer_to_string");
return ret_value;
} /* buffer_to_string */
/*--------------------------------------------------------------------
NAME
string_length
DESCRIPTION
RETURNS
--------------------------------------------------------------------*/
int32
string_length(char *name)
{
char t_name[120], *ptr1, *ptr2;
strcpy(t_name, name);
ptr1 = (char *) strrchr(t_name, '"');
ptr2 = (char *) strrchr(t_name, '<');
ptr1 = ptr1 + 2;
*ptr2 = '\0';
return(strlen(ptr1));
} /* string_length() */
| 33.440466 | 179 | 0.44191 |
679d268048f5a08808de931908348fc8030248e1 | 1,612 | c | C | src/ckb-ext.c | keroro520/mruby-ckb-ext | a97463f688f8e44fefeb0182a953985ab9107884 | [
"MIT"
] | 1 | 2019-04-20T13:17:54.000Z | 2019-04-20T13:17:54.000Z | src/ckb-ext.c | keroro520/mruby-ckb-ext | a97463f688f8e44fefeb0182a953985ab9107884 | [
"MIT"
] | null | null | null | src/ckb-ext.c | keroro520/mruby-ckb-ext | a97463f688f8e44fefeb0182a953985ab9107884 | [
"MIT"
] | null | null | null | #include "mruby.h"
#include "mruby/string.h"
#include "mruby/compile.h"
#include "ckb_consts.h"
#include "protocol_reader.h"
#undef ns
#define ns(x) FLATBUFFERS_WRAP_NAMESPACE(Ckb_Protocol, x)
extern int ckb_load_tx(void* addr, uint64_t* len, size_t offset);
extern int ckb_load_cell(void* addr, uint64_t* len, size_t offset,
size_t index, size_t source);
extern int ckb_load_cell_by_field(void* addr, uint64_t* len, size_t offset,
size_t index, size_t source, size_t field);
extern int ckb_load_input_by_field(void* addr, uint64_t* len, size_t offset,
size_t index, size_t source, size_t field);
extern int ckb_debug(const char* message);
static mrb_value
ckb_mrb_eval(mrb_state *mrb, mrb_value self)
{
mrb_int index, source;
mrb_get_args(mrb, "ii", &index, &source);
uint64_t len = 0;
if (ckb_load_cell_by_field(NULL, &len, 0, index, source, CKB_CELL_FIELD_DATA) != CKB_SUCCESS) {
mrb_raise(mrb, E_ARGUMENT_ERROR, "missing target cell");
}
void* addr = malloc(len);
if (addr == NULL) {
free(addr);
mrb_raise(mrb, E_ARGUMENT_ERROR, "not enough memory");
}
if (ckb_load_cell_by_field(addr, &len, 0, index, source, CKB_CELL_FIELD_DATA) != CKB_SUCCESS) {
free(addr);
mrb_raise(mrb, E_ARGUMENT_ERROR, "loading cell data");
}
mrb_value v = mrb_load_string(mrb, addr);
free(addr);
return v;
}
void
mrb_mruby_ckb_ext_gem_init(mrb_state* mrb)
{
struct RClass *class__;
class__ = mrb_define_module(mrb, "CKB");
mrb_define_module_function(mrb, class__, "eval", ckb_mrb_eval, MRB_ARGS_REQ(2));
}
void mrb_mruby_ckb_ext_gem_final(mrb_state* mrb)
{
}
| 28.280702 | 97 | 0.730769 |
bccbaaed8c83ec4c0117e9e639ea84f3979d8d71 | 401 | h | C | Queue.h | linuxartisan/generic-list-in-c | 75b22b83edf29296e463c25c43fda87c84626dd1 | [
"MIT"
] | 1 | 2022-02-24T00:55:51.000Z | 2022-02-24T00:55:51.000Z | Queue.h | xinbin818/generic-list-in-c | 75b22b83edf29296e463c25c43fda87c84626dd1 | [
"MIT"
] | null | null | null | Queue.h | xinbin818/generic-list-in-c | 75b22b83edf29296e463c25c43fda87c84626dd1 | [
"MIT"
] | 1 | 2022-02-24T00:55:40.000Z | 2022-02-24T00:55:40.000Z | #ifndef LINUXARTISAN_QUEUE_H
#define LINUXARTISAN_QUEUE_H
#include "List.h"
typedef struct Queue
{
List* list;
}Queue;
Queue* queue_create();
void queue_destroy(Queue*);
/* capacity */
bool queue_empty(Queue*);
int queue_size(Queue*);
/* element access */
void* queue_front(Queue*);
void* queue_back(Queue*);
/* modifiers */
void enqueue(Queue*, void* elem);
void* dequeue(Queue*);
#endif
| 14.321429 | 33 | 0.713217 |
4c50816ae887e5046ea1d66413df4593559d43b8 | 3,655 | h | C | 111-meiju/meiju/AdViewSDK-3.5.2/AdNetworks/Chance/lib/CSInterstitial.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/Chance/lib/CSInterstitial.h | P79N6A/demo | 0286a294b8f9f83b316e75e8d996e94fb6ab6a53 | [
"Apache-2.0"
] | null | null | null | 111-meiju/meiju/AdViewSDK-3.5.2/AdNetworks/Chance/lib/CSInterstitial.h | P79N6A/demo | 0286a294b8f9f83b316e75e8d996e94fb6ab6a53 | [
"Apache-2.0"
] | 2 | 2019-09-17T06:50:12.000Z | 2021-11-15T03:02:11.000Z | //
// CSInterstitial.h
// ChanceAdSDK
//
// Created by Chance_yangjh on 13-10-28.
// Copyright (c) 2013年 Chance. All rights reserved.
//
#ifndef CSInterstitial_h
#define CSInterstitial_h
#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>
#import "CSError.h"
typedef NS_ENUM(unsigned int, CSInterstitialStatus) {
CSInterstitialStatus_Hide,
CSInterstitialStatus_Showing,
CSInterstitialStatus_Show,
CSInterstitialStatus_Hiding,
};
// 插屏广告加载完成
typedef void (^CSInterstitialDidLoadAD)();
// 插屏广告加载出错
typedef void (^CSInterstitialLoadFailure)(CSError *error);
// 插屏广告打开完成
typedef void (^CSInterstitialDidPresent)();
// 插屏广告倒计时结束
typedef void (^CSInterstitialCountDownFinished)();
// 插屏广告将要关闭
typedef void (^CSInterstitialWillDismiss)();
// 插屏广告关闭完成
typedef void (^CSInterstitialDidDismiss)();
@protocol CSInterstitialDelegate;
@interface CSInterstitial : NSObject
// 广告位ID
@property (nonatomic, copy) NSString *placementID;
// 关闭按钮显示前的倒计时时长(秒)
@property (nonatomic, assign) unsigned int countdown;
// 倒计时后是否自动关闭,默认为NO
@property (nonatomic, assign) BOOL autoCloseAfterCountDown;
// 是否显示关闭按钮,默认为YES
@property (nonatomic, assign) BOOL showCloseButton;
// 广告是否准备好。准备好则show或fill马上就能展现,否则可能需要等待
@property (nonatomic, readonly) BOOL isReady;
// 关闭时是否加载下一个广告,默认为YES
@property (nonatomic, assign) BOOL loadNextWhenClose;
// 点击广告后是否关闭广告
@property (nonatomic, assign) BOOL closeWhenClick;
// 插屏广告当前状态
@property (nonatomic, readonly) CSInterstitialStatus status;
// 插屏广告尺寸
@property (nonatomic, readonly) CGSize interstitialSize;
@property (nonatomic, weak) UIViewController *rootViewController;
// 插屏广告回调代理
@property (nonatomic, weak) id <CSInterstitialDelegate> delegate;
// 插屏广告加载完成的block
@property (nonatomic, copy) CSInterstitialDidLoadAD didLoadAD;
// 插屏广告加载出错的block
@property (nonatomic, copy) CSInterstitialLoadFailure loadADFailure;
// 插屏广告打开完成的block
@property (nonatomic, copy) CSInterstitialDidPresent didPresent;
// 插屏广告倒计时结束的block
@property (nonatomic, copy) CSInterstitialCountDownFinished countdownFinished;
// 插屏广告将要关闭的block
@property (nonatomic, copy) CSInterstitialWillDismiss willDismiss;
// 插屏广告关闭完成的block
@property (nonatomic, copy) CSInterstitialDidDismiss didDismiss;
// 插屏广告只有一个
+ (CSInterstitial *)sharedInterstitial;
/**
* @brief 加载插屏广告数据
*/
- (void)loadInterstitial;
/**
* @brief 显示插屏广告
*/
- (void)showInterstitial;
/**
* @brief 显示插屏广告 from 6.4.3
*
* @param viewController 显示插屏广告用的UIViewController
*/
- (void)showInterstitial:(UIViewController *)viewController;
/**
* @brief 显示插屏广告
*
* @param rootView 插屏广告的父视图
*/
- (void)showInterstitialOnRootView:(UIView *)rootView;
/**
* @brief 用插屏广告填充view
*
* @param view 插屏广告的展现容器
*/
- (void)fillInterstitialInView:(UIView *)view;
/**
* @brief 关闭插屏广告
*/
- (void)closeInterstitial;
@end
@protocol CSInterstitialDelegate <NSObject>
@optional
// 插屏广告发出请求
- (void)csInterstitialRequestAD:(CSInterstitial *)csInterstitial;
// 插屏广告加载完成
- (void)csInterstitialDidLoadAd:(CSInterstitial *)csInterstitial;
// 插屏广告加载错误
- (void)csInterstitial:(CSInterstitial *)csInterstitial
loadAdFailureWithError:(CSError *)csError;
// 插屏广告打开完成
- (void)csInterstitialDidPresentScreen:(CSInterstitial *)csInterstitial;
// 倒计时结束
- (void)csInterstitialCountDownFinished:(CSInterstitial *)csInterstitial;
// 插屏广告将要关闭
- (void)csInterstitialWillDismissScreen:(CSInterstitial *)csInterstitial;
// 插屏广告关闭完成
- (void)csInterstitialDidDismissScreen:(CSInterstitial *)csInterstitial;
// 互动页展示
- (void)csInterstitialInteractPageShow:(CSInterstitial *)csInterstitial;
// 互动页关闭
- (void)csInterstitialInteractPageClose:(CSInterstitial *)csInterstitial;
@end
#endif
| 23.733766 | 78 | 0.775376 |
2907a49ca99931e17b521e0b6b5cc0055ca7f799 | 1,915 | h | C | MSTypes.h | MihaelShevchuk/MSSocketLibrary | 6ec75fea90221026a5a5ec302b56b93b83bfbf01 | [
"BSD-2-Clause"
] | null | null | null | MSTypes.h | MihaelShevchuk/MSSocketLibrary | 6ec75fea90221026a5a5ec302b56b93b83bfbf01 | [
"BSD-2-Clause"
] | null | null | null | MSTypes.h | MihaelShevchuk/MSSocketLibrary | 6ec75fea90221026a5a5ec302b56b93b83bfbf01 | [
"BSD-2-Clause"
] | null | null | null | //
// MSTypes.h
// MSSocketLibrary
//
// Created by Mihail Shevchuk on 25.01.18.
// Copyright © 2018 Mihail Shevchuk. All rights reserved.
//
#ifndef MSTypes_h
#define MSTypes_h
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <arpa/inet.h>
#include <pthread.h>
#include <map>
const int MAX_SERVER_PATH_LEN = 30;
class MSSocket;
class MSServer;
enum MSEventType {
LOCAL_SERVER,
LOCAL_SOCKET,
NETWORK_SOCKET,
NETWORK_SERVER
};
enum MSEvent {
ALREADY_CONNECT = 1,
ALREADY_DISCONNECT = 2,
ALREADY_LAUNCH = 3,
ALREADY_SHUTDOWN = 4,
NOT_SETUP = 6,
NOT_READ = 8,
NOT_SEND = 9,
IS_CONNECT = 11,
IS_DISCONNECT = 12
};
struct MSEventMessage {
MSEventMessage(MSEventType sType,
MSEvent sEvent,
int sPort,
char* sPath) : type(sType), event(sEvent), port(sPort) {
strcpy(serverPath, sPath);
}
MSEventType type;
MSEvent event;
int port;
char serverPath[MAX_SERVER_PATH_LEN];
};
typedef char* pChar;
typedef void* pVoid;
typedef void (*pFuncThrowEvent)(MSEventMessage*, pVoid);
typedef void (*pFuncCallBack)(void *message, size_t size, void *manager);
struct ServersCreateMaps {
std::map<uint32_t, MSServer*> networkMap;
std::map<pChar, MSServer*> localMap;
};
struct SocketsCreateMaps {
std::map<uint32_t, MSSocket*> networMap;
std::map<pChar, MSSocket*> localMap;
};
struct LaunchMaps {
std::map<uint32_t, bool> networkMap;
std::map<pChar, bool> localMap;
};
struct ServersMaps {
ServersCreateMaps createMaps;
LaunchMaps launchMaps;
};
struct SocketsMaps {
SocketsCreateMaps createMaps;
LaunchMaps launchMaps;
};
struct Maps {
SocketsMaps socketsMaps;
ServersMaps serversMaps;
};
#endif /* MSTypes_h */
| 20.157895 | 75 | 0.653264 |
ada5e051fc8b5a6931e96dd188ec1e92e419a324 | 782 | h | C | include/types.h | CraftSpider/AlphaUtils | 70ff9cd4ec4184f67d7e8b779538ef88f1e88682 | [
"MIT"
] | 1 | 2019-06-23T14:03:16.000Z | 2019-06-23T14:03:16.000Z | include/types.h | CraftSpider/AlphaUtils | 70ff9cd4ec4184f67d7e8b779538ef88f1e88682 | [
"MIT"
] | null | null | null | include/types.h | CraftSpider/AlphaUtils | 70ff9cd4ec4184f67d7e8b779538ef88f1e88682 | [
"MIT"
] | 2 | 2019-06-23T14:03:17.000Z | 2020-11-19T02:16:51.000Z | #pragma once
#include <cstdint>
/**
* \file types.h
* \brief Defines AlphaTools global type shorthands
* \TODO: Move whole project into a namespace
*
* \author CraftSpider
*/
/**
* Unsigned 1 byte integer
*/
typedef std::uint8_t uchar;
/**
* Unsigned 2 byte integer
*/
typedef std::uint16_t ushort;
/**
* Unsigned 4 byte integer
*/
typedef std::uint32_t uint;
/**
* Unsigned 8 byte integer
*/
typedef std::uint64_t ulong;
/**
* Signed 1 byte integer
*/
typedef std::int8_t schar;
/**
* Signed 2 byte integer
*/
typedef std::int16_t sshort;
/**
* Signed 4 byte integer
*/
typedef std::int32_t sint;
/**
* Signed 8 byte integer
*/
typedef std::int64_t slong;
/**
* Types of endianness a computer might have
*/
enum class Endian {
BIG, LITTLE
};
| 13.254237 | 51 | 0.659847 |
422667e688c4c1d38c81c70aece057e0de4cc203 | 21,285 | h | C | base/tools/kdexts2/precomp.h | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | base/tools/kdexts2/precomp.h | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | base/tools/kdexts2/precomp.h | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | /*++
Copyright (c) 1993-1999 Microsoft Corporation
Module Name:
precomp.h
Abstract:
This header file is used to cause the correct machine/platform specific
data structures to be used when compiling for a non-hosted platform.
--*/
#include <nt.h>
#include <ntrtl.h>
#include <nturtl.h>
#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define STRSAFE_NO_DEPRECATE
#include <strsafe.h>
// This is a 64 bit aware debugger extension
#define KDEXT_64BIT
#include <wdbgexts.h>
#include <dbgeng.h>
#include "extsfns.h"
#include "session.h"
#ifdef __cplusplus
extern "C" {
#endif
//
// undef the wdbgexts
//
#undef DECLARE_API
#define DECLARE_API(extension) \
CPPMOD HRESULT CALLBACK extension(PDEBUG_CLIENT Client, PCSTR args)
#ifndef EXTENSION_API
#define EXTENSION_API( name ) \
HRESULT _EFN_##name
#endif // EXTENSION_API
#define INIT_API() \
HRESULT Status; \
if ((Status = ExtQuery(Client)) != S_OK) return Status;
#define EXIT_API ExtRelease
// Safe release and NULL.
#define EXT_RELEASE(Unk) \
((Unk) != NULL ? ((Unk)->Release(), (Unk) = NULL) : NULL)
// Global variables initialized by query.
extern PDEBUG_ADVANCED g_ExtAdvanced;
extern PDEBUG_CLIENT g_ExtClient;
extern PDEBUG_CONTROL2 g_ExtControl;
extern PDEBUG_DATA_SPACES g_ExtData;
extern PDEBUG_REGISTERS g_ExtRegisters;
extern PDEBUG_SYMBOLS2 g_ExtSymbols;
extern PDEBUG_SYSTEM_OBJECTS g_ExtSystem;
extern ULONG64 STeip;
extern ULONG64 STebp;
extern ULONG64 STesp;
extern ULONG64 EXPRLastDump;
HRESULT
ExtQuery(PDEBUG_CLIENT Client);
void
ExtRelease(void);
#ifdef DEFINE_GUID
#undef DEFINE_GUID
#endif
#define DEFINE_GUID(name, l, w1, w2, b1, b2, b3, b4, b5, b6, b7, b8) \
EXTERN_C const GUID DECLSPEC_SELECTANY name \
= { l, w1, w2, { b1, b2, b3, b4, b5, b6, b7, b8 } }
//
// Flag definitions used by extensions
//
#include "extflags.h"
#define ADDRESS_NOT_VALID 0
#define ADDRESS_VALID 1
#define ADDRESS_TRANSITION 2
//#define POOL_TYPE_AND_QUOTA_MASK (15)
#define MAXULONG64_PTR (~((ULONG64)0))
#define MAXLONG64_PTR ((LONG64)(MAXULONG64_PTR >> 1))
#define MINLONG64_PTR (~MAXLONG64_PTR)
#define POOL_BIG_TABLE_ENTRY_FREE 0x1
//
// macros to crack the ControllerId field of the socket info structure
//
#define PcmciaClassFromControllerType(type) (((type) & 0xff))
#define PcmciaModelFromControllerType(type) (((type) >> 8) & 0x3ffff)
#define PcmciaRevisionFromControllerType(type) ((type) >> 26)
#ifdef PAGE_SIZE
#undef PAGE_SIZE
#endif
#define DBG_PTR_SIZE (IsPtr64() ? 8 : 4)
#define UNEXTEND64(p) (IsPtr64() ? p : (ULONG64) (ULONG) p)
extern ULONG PageSize;
extern ULONG PageShift;
extern ULONG BuildNo;
extern ULONG PoolBlockShift;
extern BOOL NewPool;
#define _KB (PageSize/1024)
#define POOL_BLOCK_SHIFT_OLD ((PageSize == 0x4000) ? 6 : (((PageSize == 0x2000) || ((BuildNo < 2257) && (PageSize == 0x1000))) ? 5 : 4))
#define POOL_BLOCK_SHIFT_LAB1_2402 ((PageSize == 0x4000) ? 5 : (((PageSize == 0x2000)) ? 4 : (IsPtr64() ? 4 : 3)))
#define POOL_BLOCK_SHIFT PoolBlockShift
#define PAGE_ALIGN64(Va) ((ULONG64)((Va) & ~((ULONG64) (PageSize - 1))))
#define GetBits(from, pos, num) ((from >> pos) & (((ULONG64) ~0) >> (sizeof(ULONG64)*8 - num)))
extern ULONG64 PaeEnabled;
extern ULONG TargetMachine;
extern ULONG TargetIsDump;
extern BOOL IsLocalKd;
typedef struct _MMPFNENTRY {
ULONG Modified : 1;
ULONG ReadInProgress : 1;
ULONG WriteInProgress : 1;
ULONG PrototypePte: 1;
ULONG PageColor : 3;
ULONG ParityError : 1;
ULONG PageLocation : 3;
ULONG RemovalRequested : 1;
ULONG CacheAttribute : 2;
ULONG Rom : 1;
ULONG LockCharged : 1;
ULONG DontUse : 16; //overlays USHORT for reference count field.
} MMPFNENTRY;
typedef struct {
BOOL Valid;
CHAR Type[MAX_PATH];
ULONG64 Module;
ULONG TypeId;
ULONG Size;
} CachedType;
//-----------------------------------------------------------------------------------------
//
// api declaration macros & api access macros
//
//-----------------------------------------------------------------------------------------
extern WINDBG_EXTENSION_APIS ExtensionApis;
__inline
ULONG64
KD_OBJECT_TO_OBJECT_HEADER(
ULONG64 o
)
{
static ULONG Off=0, GotOff=0;
if (!GotOff &&
!GetFieldOffset("nt!_OBJECT_HEADER", "Body", &Off)) {
GotOff = TRUE;
} else if (!GotOff){
return 0;
}
return o - Off;
}
__inline
ULONG64
KD_OBJECT_HEADER_TO_OBJECT(
ULONG64 o
)
{
static ULONG Off=0, GotOff=0;
if (!GotOff &&
!GetFieldOffset("nt!_OBJECT_HEADER", "Body", &Off)) {
GotOff = TRUE;
} else if (!GotOff){
return 0;
}
return o + Off;
}
__inline
VOID
KD_OBJECT_HEADER_TO_QUOTA_INFO(
ULONG64 oh,
PULONG64 pOutH
)
{
ULONG QuotaInfoOffset=0;
GetFieldValue(oh, "nt!_OBJECT_HEADER", "QuotaInfoOffset", QuotaInfoOffset);
*pOutH = (QuotaInfoOffset == 0 ? 0 : ((oh) - QuotaInfoOffset));
}
__inline
VOID
KD_OBJECT_HEADER_TO_HANDLE_INFO (
ULONG64 oh,
PULONG64 pOutH
)
{
ULONG HandleInfoOffset=0;
GetFieldValue(oh, "nt!_OBJECT_HEADER", "HandleInfoOffset", HandleInfoOffset);
*pOutH = (HandleInfoOffset == 0 ? 0 : ((oh) - HandleInfoOffset));
}
__inline
VOID
KD_OBJECT_HEADER_TO_NAME_INFO(
ULONG64 oh,
PULONG64 pOutH
)
{
ULONG NameInfoOffset=0;
GetFieldValue(oh, "nt!_OBJECT_HEADER", "NameInfoOffset", NameInfoOffset);
*pOutH = (NameInfoOffset == 0 ? 0 : ((oh) - NameInfoOffset));
}
__inline
VOID
KD_OBJECT_HEADER_TO_CREATOR_INFO(
ULONG64 oh,
PULONG64 pOutH
)
{
ULONG Flags=0;
GetFieldValue(oh, "_OBJECT_HEADER", "Flags", Flags);
*pOutH = ((Flags & OB_FLAG_CREATOR_INFO) == 0 ? 0 : ((oh) - GetTypeSize("_OBJECT_HEADER_CREATOR_INFO")));
}
//-----------------------------------------------------------------------------------------
//
// prototypes for internal non-exported support functions
//
//-----------------------------------------------------------------------------------------
//
// get data from DebuggerData or GetExpression as appropriate
//
char ___SillyString[];
extern KDDEBUGGER_DATA64 KdDebuggerData;
#define GetNtDebuggerData(NAME) \
(HaveDebuggerData()? (GetDebuggerData(KDBG_TAG, \
&KdDebuggerData, \
sizeof(KdDebuggerData)), \
KdDebuggerData.NAME): \
GetExpression( "nt!" #NAME ))
#define GetNtDebuggerDataValue(NAME) \
(HaveDebuggerData()? \
GetUlongFromAddress((GetDebuggerData(KDBG_TAG, \
&KdDebuggerData, \
sizeof(KdDebuggerData)), \
KdDebuggerData.NAME) \
): \
GetUlongValue( "nt!" #NAME ))
//
// This is used to read pointer values from address.
//
#define GetNtDebuggerDataPtrValue(NAME) \
(HaveDebuggerData()? \
GetPointerFromAddress((GetDebuggerData(KDBG_TAG, \
&KdDebuggerData, \
sizeof(KdDebuggerData)), \
KdDebuggerData.NAME) \
): \
GetPointerValue( "nt!" #NAME ))
typedef enum _MODE {
KernelMode,
UserMode,
MaximumMode
} MODE;
extern BOOL
HaveDebuggerData(
VOID
);
BOOL
ReadPcr(
USHORT Processor,
PVOID Pcr,
PULONG AddressOfPcr,
HANDLE hThread
);
ULONG
GetUlongFromAddress (
ULONG64 Location
);
BYTE
GetByteFromAddress (
ULONG64 Location
);
ULONG
GetUlongValue (
PCHAR String
);
BYTE
GetByteValue (
PCHAR String
);
ULONG64
GetGlobalFromAddress (
ULONG64 Location,
ULONG Size
);
ULONG64
GetGlobalValue (
PCHAR String
);
HRESULT
GetGlobalEx(
PCHAR String,
PVOID OutValue,
ULONG OutSize
);
#define GetGlobal( _String, _OutValue ) \
GetGlobalEx( (_String), &(_OutValue), sizeof(_OutValue) )
BOOLEAN
ReadMemoryUncached (
ULONG64 Offset,
PVOID Buffer,
ULONG BufferSize,
PULONG BytesRead
);
BOOLEAN
WriteMemoryUncached (
ULONG64 Offset,
PVOID Buffer,
ULONG BufferSize,
PULONG BytesWritten
);
/////////////////////////////////////////////
//
// KdExts.c
//
/////////////////////////////////////////////
BOOL
GetCurrentProcessor(
IN PDEBUG_CLIENT Client,
OPTIONAL OUT PULONG pProcessor,
OPTIONAL OUT PHANDLE phCurrentThread
);
HRESULT
ExecuteCommand(
IN PDEBUG_CLIENT Client,
IN PSTR Command
);
HRESULT
GetExtensionFunction(
IN PCSTR FunctionName,
IN FARPROC *Function
);
void ExtOut(PCSTR Format, ...);
void ExtErr(PCSTR Format, ...);
void ExtWarn(PCSTR Format, ...);
void ExtVerb(PCSTR Format, ...);
/////////////////////////////////////////////
//
// CritSec.c
//
/////////////////////////////////////////////
PLIST_ENTRY
DumpCritSec(
HANDLE hCurrentProcess,
DWORD dwAddrCritSec,
BOOLEAN bDumpIfUnowned
);
/////////////////////////////////////////////
//
// Device.c
//
/////////////////////////////////////////////
VOID
DumpDevice(
ULONG64 DeviceAddress,
ULONG FieldWidth,
BOOLEAN FullDetail
);
HRESULT
GetDevObjInfo(
IN ULONG64 DeviceObject,
OUT PDEBUG_DEVICE_OBJECT_INFO pDevObjInfo
);
/////////////////////////////////////////////
//
// Devnode.c
//
/////////////////////////////////////////////
typedef struct _FLAG_NAME {
ULONG Flag;
PUCHAR Name;
} FLAG_NAME, *PFLAG_NAME;
VOID
DumpDeviceCapabilities(
ULONG64 caps
);
VOID
DumpFlags(
ULONG Depth,
LPSTR FlagDescription,
ULONG Flags,
PFLAG_NAME FlagTable
);
VOID
xdprintf(
ULONG Depth,
PCHAR S,
...
);
BOOLEAN
xReadMemory (
ULONG64 S,
PVOID D,
ULONG Len
);
/////////////////////////////////////////////
//
// Driver.c
//
/////////////////////////////////////////////
VOID
DumpDriver(
ULONG64 DriverAddress,
ULONG FieldWidth,
ULONG Flags
);
HRESULT
GetDrvObjInfo(
IN ULONG64 DriverObject,
OUT PDEBUG_DRIVER_OBJECT_INFO pDrvObjInfo);
/////////////////////////////////////////////
//
// irp.c
//
/////////////////////////////////////////////
HRESULT
GetIrpInfo(
ULONG64 Irp,
PDEBUG_IRP_INFO pIrp
);
/////////////////////////////////////////////
//
// lock.c
//
/////////////////////////////////////////////
VOID
DumpStaticFastMutex (
IN PCHAR Name
);
/////////////////////////////////////////////
//
// memory.c
//
/////////////////////////////////////////////
VOID
MemoryUsage (
IN ULONG64 PfnStart,
IN ULONG64 LowPage,
IN ULONG64 HighPage,
IN ULONG IgnoreInvalidFrames
);
/////////////////////////////////////////////
//
// Object.c
//
/////////////////////////////////////////////
extern ULONG64 EXPRLastDump;
typedef enum _POOL_TYPE {
NonPagedPool,
PagedPool,
NonPagedPoolMustSucceed,
DontUseThisType,
NonPagedPoolCacheAligned,
PagedPoolCacheAligned,
NonPagedPoolCacheAlignedMustS,
MaxPoolType
// end_wdm
,
//
// Note these per session types are carefully chosen so that the appropriate
// masking still applies as well as MaxPoolType above.
//
NonPagedPoolSession = 32,
PagedPoolSession = NonPagedPoolSession + 1,
NonPagedPoolMustSucceedSession = PagedPoolSession + 1,
DontUseThisTypeSession = NonPagedPoolMustSucceedSession + 1,
NonPagedPoolCacheAlignedSession = DontUseThisTypeSession + 1,
PagedPoolCacheAlignedSession = NonPagedPoolCacheAlignedSession + 1,
NonPagedPoolCacheAlignedMustSSession = PagedPoolCacheAlignedSession + 1,
// begin_wdm
} POOL_TYPE;
typedef BOOLEAN (*ENUM_TYPE_ROUTINE)(
IN ULONG64 pObjectHeader,
IN PVOID Parameter
);
//
// Object Table Entry Structure
//
typedef struct _OBJECT_TABLE_ENTRY {
ULONG NonPagedObjectHeader;
ACCESS_MASK GrantedAccess;
} OBJECT_TABLE_ENTRY, *POBJECT_TABLE_ENTRY;
#define LOG_OBJECT_TABLE_ENTRY_SIZE 1
BOOLEAN
FetchObjectManagerVariables(
BOOLEAN ForceReload
);
ULONG64
FindObjectByName(
IN PUCHAR Path,
IN ULONG64 RootObject
);
ULONG64
FindObjectType(
IN PUCHAR TypeName
);
BOOLEAN
DumpObject(
IN char *Pad,
IN ULONG64 Object,
// IN POBJECT_HEADER OptObjectHeader OPTIONAL,
IN ULONG Flags
);
BOOLEAN
WalkObjectsByType(
IN PUCHAR ObjectTypeName,
IN ENUM_TYPE_ROUTINE EnumRoutine,
IN PVOID Parameter
);
BOOLEAN
CaptureObjectName(
IN ULONG64 pObjectHeader,
// IN POBJECT_HEADER ObjectHeader,
IN PWSTR Buffer,
IN ULONG BufferSize
);
VOID
DumpObjectName(
ULONG64 ObjectAddress
);
/////////////////////////////////////////////
//
// pcr.c
//
/////////////////////////////////////////////
BOOL
ReadTargetPcr (
OUT PULONG64 PPcr,
IN ULONG Processor
);
/////////////////////////////////////////////
//
// Pool.c
//
/////////////////////////////////////////////
typedef
BOOLEAN
(WINAPI *POOLFILTER) (
PCHAR Tag,
PCHAR Filter,
ULONG Flags,
ULONG64 PoolHeader,
ULONG64 BlockSize,
ULONG64 Data,
PVOID Context
);
void SearchPool(
ULONG TagName,
ULONG Flags,
ULONG64 RestartAddr,
POOLFILTER Filter,
PVOID Context
);
BOOLEAN
CheckSingleFilter (
PCHAR Tag,
PCHAR Filter
);
LOGICAL
PoolInitializeGlobals(void);
HRESULT
ListPoolPage(
ULONG64 PoolPageToDump,
ULONG Flags,
PDEBUG_POOL_DATA PoolData
);
PSTR
GetPoolTagDescription(
IN ULONG PoolTag
);
void
PrintPoolRegion(
ULONG64 Pool
);
PRTL_BITMAP
GetBitmap(
ULONG64 pBitmap
);
ULONG64
GetNextResidentAddress (
ULONG64 VirtualAddress,
ULONG64 MaximumVirtualAddress
);
/////////////////////////////////////////////
//
// Process.c
//
/////////////////////////////////////////////
extern CHAR *WaitReasonList[];
BOOL
DumpProcess(
IN char * pad,
IN ULONG64 RealProcessBase,
IN ULONG Flags,
IN OPTIONAL PCHAR ImageFileName
);
BOOL
DumpThread (
IN ULONG Processor,
IN char *Pad,
IN ULONG64 RealThreadBase,
IN ULONG64 Flags
);
BOOL
DumpThreadEx (
IN ULONG Processor,
IN char *Pad,
IN ULONG64 RealThreadBase,
IN ULONG Flags,
IN PDEBUG_CLIENT pDbgClient
);
VOID
dumpSymbolicAddress(
ULONG64 Address,
PCHAR Buffer,
BOOL AlwaysShowHex
);
BOOLEAN
FetchProcessStructureVariables(
VOID
);
BOOL
GetProcessSessionId(
ULONG64 Process,
PULONG SessionId
);
BOOL
GetProcessHead(
PULONG64 Head,
PULONG64 First
);
ULONG
GetAddressState(
IN ULONG64 VirtualAddress
);
typedef struct _PROCESS_COMMIT_USAGE {
UCHAR ImageFileName[ 16 ];
ULONG64 ClientId;
ULONG64 ProcessAddress;
ULONG64 CommitCharge;
ULONG64 NumberOfPrivatePages;
ULONG64 NumberOfLockedPages;
} PROCESS_COMMIT_USAGE, *PPROCESS_COMMIT_USAGE;
PPROCESS_COMMIT_USAGE
GetProcessCommit (
PULONG64 TotalCommitCharge,
PULONG NumberOfProcesses
);
VOID
DumpMmThreads (
VOID
);
PSTR
GetThreadWaitReasonName(
ULONG dwWatiReason
);
/////////////////////////////////////////////
//
// pte.c
//
/////////////////////////////////////////////
ULONG
DbgGetValid(
ULONG64 Pte
);
ULONG64
DbgGetPdeAddress(
IN ULONG64 VirtualAddress
);
ULONG64
DbgGetPteAddress(
IN ULONG64 VirtualAddress
);
ULONG64
DbgGetFrameNumber(
ULONG64 Pte
);
ULONG64
DbgGetSubsectionAddress(
IN ULONG64 Pte
);
ULONG64
DbgGetVirtualAddressMappedByPte(
IN ULONG64 Pte
);
ULONG
MiGetSysPteListDelimiter (
VOID
);
BOOL
Mi_Is_Physical_Address (
ULONG64 VirtualAddress
);
ULONG
MiConvertPhysicalToPfn (
IN ULONG64 VirtualAddress
);
/////////////////////////////////////////////
//
// Registry.c
//
/////////////////////////////////////////////
USHORT
GetKcbName(
ULONG64 KcbAddr,
PWCHAR NameBuffer,
ULONG BufferSize
);
/////////////////////////////////////////////
//
// sel.c
//
/////////////////////////////////////////////
// X86 only
//
// LDT descriptor entry
//
typedef struct _LDT_ENTRY_X86 {
USHORT LimitLow;
USHORT BaseLow;
union {
struct {
UCHAR BaseMid;
UCHAR Flags1; // Declare as bytes to avoid alignment
UCHAR Flags2; // Problems.
UCHAR BaseHi;
} Bytes;
struct {
ULONG BaseMid : 8;
ULONG Type : 5;
ULONG Dpl : 2;
ULONG Pres : 1;
ULONG LimitHi : 4;
ULONG Sys : 1;
ULONG Reserved_0 : 1;
ULONG Default_Big : 1;
ULONG Granularity : 1;
ULONG BaseHi : 8;
} Bits;
} HighWord;
} LDT_ENTRY_X86, *PLDT_ENTRY_X86;
typedef struct _DESCRIPTOR_TABLE_ENTRY_X86 {
ULONG Selector;
LDT_ENTRY_X86 Descriptor;
} DESCRIPTOR_TABLE_ENTRY_X86, *PDESCRIPTOR_TABLE_ENTRY_X86;
NTSTATUS
LookupSelector(
IN USHORT Processor,
IN OUT PDESCRIPTOR_TABLE_ENTRY_X86 pDescriptorTableEntry
);
/////////////////////////////////////////////
//
// trap.cpp
//
/////////////////////////////////////////////
// IA64 only
typedef enum _DISPLAY_MODE {
DISPLAY_MIN = 0,
DISPLAY_DEFAULT = DISPLAY_MIN,
DISPLAY_MED = 1,
DISPLAY_MAX = 2,
DISPLAY_FULL = DISPLAY_MAX
} DISPLAY_MODE;
typedef struct _EM_REG_FIELD {
const char *SubName;
const char *Name;
unsigned long Length;
unsigned long Shift;
} EM_REG_FIELD, *PEM_REG_FIELD;
VOID
DisplayFullEmRegField(
ULONG64 EmRegValue,
EM_REG_FIELD EmRegFields[],
ULONG Field
);
VOID
DisplayFullEmReg(
IN ULONG64 Val,
IN EM_REG_FIELD EmRegFields[],
IN DISPLAY_MODE DisplayMode
);
/////////////////////////////////////////////
//
// Util.c
//
/////////////////////////////////////////////
typedef VOID
(*PDUMP_SPLAY_NODE_FN)(
ULONG64 RemoteAddress,
ULONG Level
);
ULONG
DumpSplayTree(
IN ULONG64 pSplayLinks,
IN PDUMP_SPLAY_NODE_FN DumpNodeFn
);
BOOLEAN
DbgRtlIsRightChild(
ULONG64 pLinks,
ULONG64 Parent
);
BOOLEAN
DbgRtlIsLeftChild(
ULONG64 pLinks,
ULONG64 Parent
);
ULONG
GetBitFieldOffset (
IN LPSTR Type,
IN LPSTR Field,
OUT PULONG pOffset,
OUT PULONG pSize
);
ULONG
GetFieldOffsetEx ( // returns Offset and Size...
IN LPSTR Type,
IN LPSTR Field,
OUT PULONG pOffset,
OUT PULONG pSize
);
ULONG64
GetPointerFromAddress (
ULONG64 Location
);
VOID
DumpUnicode(
UNICODE_STRING u
);
VOID
DumpUnicode64(
UNICODE_STRING64 u
);
ULONG64
GetPointerValue (
PCHAR String
);
BOOLEAN
IsHexNumber(
const char *szExpression
);
BOOLEAN
IsDecNumber(
const char *szExpression
);
BOOLEAN
CheckSingleFilter (
PCHAR Tag,
PCHAR Filter
);
ULONG64
UtilStringToUlong64 (
UCHAR *String
);
#define ENUM_NAME(val) {val, #val}
typedef struct _ENUM_NAME {
ULONG EnumVal;
const char * Name;
} ENUM_NAME, *PENUM_NAME;
const char *
getEnumName(
ULONG EnumVal,
PENUM_NAME EnumTable
);
#ifdef __cplusplus
}
#endif
| 20.118147 | 138 | 0.540334 |
422fa81d837820710f5275f0a054cb821b799c1a | 65 | h | C | src/bustools_predict.h | Yenaled/bustools | 6fa0731f7f32c68645f0f60b1c1c89771b1c8061 | [
"BSD-2-Clause"
] | null | null | null | src/bustools_predict.h | Yenaled/bustools | 6fa0731f7f32c68645f0f60b1c1c89771b1c8061 | [
"BSD-2-Clause"
] | null | null | null | src/bustools_predict.h | Yenaled/bustools | 6fa0731f7f32c68645f0f60b1c1c89771b1c8061 | [
"BSD-2-Clause"
] | null | null | null | #include "Common.hpp"
void bustools_predict(Bustools_opt &opt);
| 16.25 | 41 | 0.784615 |
4ec7951a317cf80a89278bc97d440f1299e140de | 6,524 | h | C | orcm/mca/analytics/analytics.h | benmcclelland/orcm-zht | d09813ac2e26c4c7bf2196aa7b385326567f3dbf | [
"BSD-3-Clause-Open-MPI"
] | null | null | null | orcm/mca/analytics/analytics.h | benmcclelland/orcm-zht | d09813ac2e26c4c7bf2196aa7b385326567f3dbf | [
"BSD-3-Clause-Open-MPI"
] | null | null | null | orcm/mca/analytics/analytics.h | benmcclelland/orcm-zht | d09813ac2e26c4c7bf2196aa7b385326567f3dbf | [
"BSD-3-Clause-Open-MPI"
] | null | null | null | /*
* Copyright (c) 2014 Intel, Inc. All rights reserved.
* $COPYRIGHT$
*
* Additional copyrights may follow
*
* $HEADER$
*/
#ifndef MCA_ANALYTICS_H
#define MCA_ANALYTICS_H
/*
* includes
*/
#include "orcm_config.h"
#include "orcm/constants.h"
#include "opal/mca/mca.h"
#include "orcm/mca/analytics/analytics_types.h"
BEGIN_C_DECLS
/* Maybe following goes in activate_analytics_workflow_step() */
/* If tap_output in attributes, send data
* If opal_list_get_next(steps) == opal_list_get_end(steps)
* OBJ_RELEASE(data)
* else
*/
#define ORCM_ACTIVATE_WORKFLOW_STEP(a, b) \
do { \
opal_list_item_t *list_item = opal_list_get_next(&(a)->steps); \
orcm_workflow_step_t *wf_step_item = (orcm_workflow_step_t *)list_item; \
if (list_item == opal_list_get_end(&(a)->steps)) { \
opal_output_verbose(1, orcm_analytics_base_framework.framework_output, \
"%s TRIED TO ACTIVATE EMPTY WORKFLOW %d AT %s:%d", \
ORTE_NAME_PRINT(ORTE_PROC_MY_NAME), \
(a)->workflow_id, \
__FILE__, __LINE__); \
} else { \
opal_output_verbose(1, orcm_analytics_base_framework.framework_output, \
"%s ACTIVATE WORKFLOW %d MODULE %s AT %s:%d", \
ORTE_NAME_PRINT(ORTE_PROC_MY_NAME), \
(a)->workflow_id, wf_step_item->analytic, \
__FILE__, __LINE__); \
orcm_analytics.activate_analytics_workflow_step((a), \
wf_step_item, \
(b)); \
} \
}while(0);
#define ORCM_ACTIVATE_NEXT_WORKFLOW_STEP(a, b) \
do { \
opal_list_item_t *list_item = opal_list_get_next(&(a)->steps); \
orcm_workflow_step_t *wf_step_item = (orcm_workflow_step_t *)list_item; \
if (list_item == opal_list_get_end(&(a)->steps)) { \
opal_output_verbose(1, orcm_analytics_base_framework.framework_output, \
"%s END OF WORKFLOW %d AT %s:%d", \
ORTE_NAME_PRINT(ORTE_PROC_MY_NAME), \
(a)->workflow_id, \
__FILE__, __LINE__); \
} else { \
opal_output_verbose(1, orcm_analytics_base_framework.framework_output, \
"%s ACTIVATE NEXT WORKFLOW %d MODULE %s AT %s:%d", \
ORTE_NAME_PRINT(ORTE_PROC_MY_NAME), \
(a)->workflow_id, wf_step_item->analytic, \
__FILE__, __LINE__); \
orcm_analytics.activate_analytics_workflow_step((a), \
wf_step_item, \
(b)); \
} \
}while(0);
/* Module functions */
/* initialize the module */
typedef int (*orcm_analytics_base_module_init_fn_t)(struct orcm_analytics_base_module_t *mod);
/* finalize the selected module */
typedef void (*orcm_analytics_base_module_finalize_fn_t)(struct orcm_analytics_base_module_t *mod);
/* do the real work in the selected module */
typedef void (*orcm_analytics_base_module_analyze_fn_t)(int fd, short args, void* cb);
/*
* Ver 1.0
*/
typedef struct {
orcm_analytics_base_module_init_fn_t init;
orcm_analytics_base_module_finalize_fn_t finalize;
orcm_analytics_base_module_analyze_fn_t analyze;
} orcm_analytics_base_module_t;
/*
* the component data structure
*/
/* function to determine if this component is available for use.
* Note that we do not use the standard component open
* function as we do not want/need return of a module.
*/
typedef bool (*mca_analytics_base_component_avail_fn_t)(void);
/* create and return an analytics module */
typedef struct orcm_analytics_base_module_t* (*mca_analytics_base_component_create_hdl_fn_t)(void);
/* provide a chance for the component to finalize */
typedef void (*mca_analytics_base_component_finalize_fn_t)(void);
typedef struct {
mca_base_component_t base_version;
mca_base_component_data_t base_data;
int priority;
mca_analytics_base_component_avail_fn_t available;
mca_analytics_base_component_create_hdl_fn_t create_handle;
mca_analytics_base_component_finalize_fn_t finalize;
} orcm_analytics_base_component_t;
/* define an API module */
typedef void (*orcm_analytics_API_module_activate_analytics_workflow_step_fn_t)(orcm_workflow_t *wf,
orcm_workflow_step_t *wf_step,
opal_value_array_t *data);
typedef struct {
orcm_analytics_API_module_activate_analytics_workflow_step_fn_t activate_analytics_workflow_step;
} orcm_analytics_API_module_t;
/*
* Macro for use in components that are of type analytics v1.0.0
*/
#define ORCM_ANALYTICS_BASE_VERSION_1_0_0 \
/* analytics v1.0 is chained to MCA v2.0 */ \
MCA_BASE_VERSION_2_0_0, \
/* analytics v1.0 */ \
"analytics", 1, 0, 0
/* Global structure for accessing name server functions
*/
/* holds API function pointers */
ORCM_DECLSPEC extern orcm_analytics_API_module_t orcm_analytics;
END_C_DECLS
#endif
| 44.380952 | 110 | 0.517014 |
866c6e44c445639797b7b9f718a3c836ab66a9ad | 1,955 | h | C | Protector/Protector.h | AvivShabtay/Protector | 97b2f1a80a4cd87b15ec21f34069edf9de2bb835 | [
"MIT"
] | 3 | 2020-10-03T10:45:24.000Z | 2022-01-18T10:34:30.000Z | Protector/Protector.h | AvivShabtay/Protector | 97b2f1a80a4cd87b15ec21f34069edf9de2bb835 | [
"MIT"
] | 3 | 2021-04-17T13:11:44.000Z | 2021-05-01T17:40:54.000Z | Protector/Protector.h | AvivShabtay/Protector | 97b2f1a80a4cd87b15ec21f34069edf9de2bb835 | [
"MIT"
] | 1 | 2021-02-07T11:27:58.000Z | 2021-02-07T11:27:58.000Z | #pragma once
#include "FastMutex.h"
#include "Vector.h"
#include "String.h"
#include <ntddk.h>
#define DRIVER_PREFIX "Protector: "
#define DRIVER_TAG 'Prtc'
using ProtectorString = String<DRIVER_TAG, PagedPool>;
using ProtectorVector = Vector<ProtectorString*, DRIVER_TAG>;
/* The Driver's unload function called whenever the kernel unloads the driver. */
DRIVER_UNLOAD ProtectorUnload;
/* The Driver's default dispatch to all the unimplemented dispatch. */
DRIVER_DISPATCH DefaultDispatch;
/* The Driver's default dispatch for create and close dispatch. */
DRIVER_DISPATCH CreateCloseDispatch;
/* Dispatch function for device control I\O requests. */
DRIVER_DISPATCH ProtectorDeviceControl;
/* Helper function to return the IRP to the caller. */
NTSTATUS CompleteIrp(PIRP Irp, NTSTATUS status = STATUS_SUCCESS, ULONG_PTR info = 0);
/* The Driver's callback function for Process Notifications. */
void OnProcessNotify(_Inout_ PEPROCESS Process, _In_ HANDLE ProcessId, _Inout_opt_ PPS_CREATE_NOTIFY_INFO CreateInfo);
/* Check if given path include in the black-listed list. */
bool IsPathInBlackList(const ProtectorString& imagePath);
/* Handler for add path requests. */
NTSTATUS AddPathHandler(_In_ PIRP Irp, _In_ PIO_STACK_LOCATION StackLocation);
/* Handler for remove path requests. */
NTSTATUS RemovePathHandler(_In_ PIRP Irp, _In_ PIO_STACK_LOCATION StackLocation);
/* Handler for path list length requests. */
NTSTATUS GetPathListLengthHandler(_In_ PIRP Irp, _In_ PIO_STACK_LOCATION StackLocation);
/* Handler for get paths requests. */
NTSTATUS GetPathsHandler(_In_ PIRP Irp, _In_ PIO_STACK_LOCATION StackLocation);
/* Check if the input buffer size is not smaller than required. */
bool IsValidInputBuffer(_In_ PIO_STACK_LOCATION StackLocation, _In_ ULONGLONG validSize);
/* Check if the output buffer size is not smaller than required. */
bool IsValidOutputBuffer(_In_ PIO_STACK_LOCATION StackLocation, _In_ ULONGLONG validSize); | 38.333333 | 118 | 0.796931 |
e50ff1223619443665476539d18920c988a4308a | 2,744 | h | C | Extends/NSObject+NSObject_File.h | netcosportsanatoly/NS-Categories | 448e2c65d09706c3eef3e4a777d098fb7d61a346 | [
"MIT"
] | null | null | null | Extends/NSObject+NSObject_File.h | netcosportsanatoly/NS-Categories | 448e2c65d09706c3eef3e4a777d098fb7d61a346 | [
"MIT"
] | 2 | 2015-03-09T14:23:32.000Z | 2015-07-23T00:25:57.000Z | Extends/NSObject+NSObject_File.h | netcosportsanatoly/NS-Categories | 448e2c65d09706c3eef3e4a777d098fb7d61a346 | [
"MIT"
] | 5 | 2015-07-16T09:42:42.000Z | 2017-11-03T09:45:13.000Z | //
// NSObject+NSObject_File.h
// Extends
//
// Created by bigmac on 25/09/12.
// Copyright (c) 2012 Jean Alexandre Iragne. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface NSObject (NSObject_File)
/**
* Retrieve application useful folders (Document, Document/tmp, Cache)
*
* @return Path for the current application
*/
#pragma mark - Folder paths access
+(NSString *)getApplicationDocumentPath;
+(NSString *)getApplicationCachePath;
+(NSString *)getApplicationTempPath;
/**
* Retrieve application useful folders associated with a file name.
*
* @return Entire path of the given fileName.
*/
#pragma mark - File paths access
+(NSString *)getApplicationDocumentPathForFile:(NSString *)fileName;
+(NSString *)getApplicationCachePathForFile:(NSString *)fileName;
+(NSString *)getApplicationTempPathForFile:(NSString *)fileName;
/**
* Check if a file exists
*
* @param filePath Full path of the file
*
* @return YES if the NSFileManager found it, Not if not.
*/
+(BOOL)isFileExistingAtPath:(NSString *)filePath;
/**
* Create an object from the given file name using the given TTL.
* If file is older than the ttl, the object created will be empty.
*
* @return Created object
*/
#pragma mark - Get objects from files
+(id)getObjectFromDocumentFile:(NSString *)fileName withTTL:(NSUInteger)ttl;
+(id)getObjectFromCacheFile:(NSString *)fileName withTTL:(NSUInteger)ttl;
+(id)getObjectFromTempFile:(NSString *)fileName withTTL:(NSUInteger)ttl;
/**
* Save an object into a file given with fileName
*
* @return (/)
*/
#pragma mark - Save objects in files
-(void)saveObjectInDocumentFile:(NSString *)fileName;
-(void)saveObjectInCacheFile:(NSString*)fileName;
-(void)saveObjectInTempFile:(NSString*)fileName;
/**
* Remove the content of a file given with fileName
*
* @return (/)
*/
#pragma mark - File cleaning
+(void)emptyContentOfDocumentFile:(NSString *)fileName;
+(void)emptyContentOfCacheFile:(NSString *)fileName;
+(void)emptyContentOfTempFile:(NSString *)fileName;
/**
* Remove file given with fileName
*
* @return (/)
*/
#pragma mark - File removing
+(void)removeDocumentFile:(NSString *)fileName;
+(void)removeCacheFile:(NSString *)fileName;
+(void)removeCacheFiles;
+(void)removeTempFile:(NSString *)fileName;
+(void)removeTempFiles;
/**
* Check if the file is older than the TTL.
* If it is older than the TTL, it removes it.
*
* @param NSInteger TTL to comapre with.
*
* @return 1 if the file has been removed, 0 if not.
*/
#pragma mark - TTL Checking
+(NSInteger)dateModifiedSortFile:(NSString *)filePath withTTL:(NSUInteger)ttl andRemove:(BOOL)shouldRemove;
+(BOOL)file:(NSString *)filePath hasBeenModifiedBeforeNowMinusTTL:(NSUInteger)ttl;
@end
| 27.717172 | 107 | 0.735423 |
af2228e7a08eb63addf68c245a5751d09c2431a4 | 349 | h | C | source/MBKit/View/Refresh/MBRefreshKit+MBKit.h | pgbo/matchbook | 3311fa54309b471b3cba896f2254cb5088b3cdfc | [
"MIT"
] | 9 | 2019-05-17T02:47:46.000Z | 2019-11-05T11:22:56.000Z | source/MBKit/View/Refresh/MBRefreshKit+MBKit.h | pgbo/matchbook | 3311fa54309b471b3cba896f2254cb5088b3cdfc | [
"MIT"
] | 2 | 2019-07-20T16:17:03.000Z | 2019-10-30T09:22:35.000Z | source/MBKit/View/Refresh/MBRefreshKit+MBKit.h | pgbo/matchbook | 3311fa54309b471b3cba896f2254cb5088b3cdfc | [
"MIT"
] | 2 | 2019-10-11T14:50:12.000Z | 2020-06-12T04:11:36.000Z | //
// MBRefreshKit+MBKit.h
// matchbook
//
// Created by guangbool on 2017/6/30.
// Copyright © 2017年 devbool. All rights reserved.
//
#import <MBKit/MBKit.h>
@interface MBRefreshKit (MBKit)
/**
上翻套件
@param actionBlock 满足上翻条件时的程序调用
@return 实例
*/
+ (MBRefreshKit *)PageupKitWithActionBlock:(void(^)(MBRefreshKit *kit))actionBlock;
@end
| 15.863636 | 83 | 0.69914 |
791670bd98cf671cbf8f8a9d5fbf123bc14e5d32 | 514 | h | C | src/cc1/fopt.h | bocke/ucc | d95c0014dfc555c3eb6e9fdf909e0460bf2a0060 | [
"MIT"
] | 55 | 2015-02-07T12:31:13.000Z | 2022-02-19T15:25:02.000Z | src/cc1/fopt.h | bocke/ucc | d95c0014dfc555c3eb6e9fdf909e0460bf2a0060 | [
"MIT"
] | null | null | null | src/cc1/fopt.h | bocke/ucc | d95c0014dfc555c3eb6e9fdf909e0460bf2a0060 | [
"MIT"
] | 9 | 2015-08-06T21:26:33.000Z | 2022-01-14T03:44:40.000Z | #ifndef FOPT_H
#define FOPT_H
struct cc1_fopt
{
#define X(flag, name) unsigned char name;
#define INVERT(flag, name)
#define ALIAS(flag, name)
#define EXCLUSIVE(flag, name, excl) X(flag, name)
#define ALIAS_EXCLUSIVE(flag, name, excl)
#include "fopts.h"
#undef X
#undef INVERT
#undef ALIAS
#undef EXCLUSIVE
#undef ALIAS_EXCLUSIVE
};
void fopt_default(struct cc1_fopt *);
unsigned char *fopt_on(struct cc1_fopt *, const char *argument, int invert);
#define FOPT_PIC(fopt) ((fopt)->pic || (fopt)->pie)
#endif
| 18.357143 | 76 | 0.733463 |
b2aacae4ebc82206bf16bd5aa0a1212d0dc1ca37 | 7,087 | c | C | putty/halibut/in_afm.c | OneIdentity/rc-legacy | 6e247f55b7df6b1022819810ba3363a2db401f08 | [
"Apache-2.0"
] | null | null | null | putty/halibut/in_afm.c | OneIdentity/rc-legacy | 6e247f55b7df6b1022819810ba3363a2db401f08 | [
"Apache-2.0"
] | null | null | null | putty/halibut/in_afm.c | OneIdentity/rc-legacy | 6e247f55b7df6b1022819810ba3363a2db401f08 | [
"Apache-2.0"
] | null | null | null | #include <stdio.h>
#include <stdlib.h>
#include "halibut.h"
#include "paper.h"
char *afm_read_line(input *in) {
int i, len = 256;
int c;
char *line;
do {
i = 0;
in->pos.line++;
c = getc(in->currfp);
if (c == EOF) {
error(err_afmeof, &in->pos);
return NULL;
}
line = snewn(len, char);
while (c != EOF && c != '\r' && c != '\n') {
if (i >= len - 1) {
len += 256;
line = sresize(line, len, char);
}
line[i++] = c;
c = getc(in->currfp);
}
if (c == '\r') {
/* Cope with CRLF terminated lines */
c = getc(in->currfp);
if (c != '\n' && c != EOF)
ungetc(c, in->currfp);
}
line[i] = 0;
} while (line[(strspn(line, " \t"))] == 0 ||
strncmp(line, "Comment ", 8) == 0 ||
strncmp(line, "Comment\t", 8) == 0);
return line;
}
static int afm_require_key(char *line, char const *expected, input *in) {
char *key = strtok(line, " \t");
if (strcmp(key, expected) == 0)
return TRUE;
error(err_afmkey, &in->pos, expected);
return FALSE;
}
void read_afm_file(input *in) {
char *line, *key, *val;
font_info *fi;
size_t i;
fi = snew(font_info);
fi->name = NULL;
fi->widths = newtree234(width_cmp);
fi->fontfile = NULL;
fi->kerns = newtree234(kern_cmp);
fi->ligs = newtree234(lig_cmp);
fi->fontbbox[0] = fi->fontbbox[1] = fi->fontbbox[2] = fi->fontbbox[3] = 0;
fi->capheight = fi->xheight = fi->ascent = fi->descent = 0;
fi->stemh = fi->stemv = fi->italicangle = 0;
for (i = 0; i < lenof(fi->bmp); i++)
fi->bmp[i] = 0xFFFF;
in->pos.line = 0;
line = afm_read_line(in);
if (!line || !afm_require_key(line, "StartFontMetrics", in))
goto giveup;
if (!(val = strtok(NULL, " \t"))) {
error(err_afmval, in->pos, "StartFontMetrics", 1);
goto giveup;
}
if (atof(val) >= 5.0) {
error(err_afmvers, &in->pos);
goto giveup;
}
sfree(line);
for (;;) {
line = afm_read_line(in);
if (line == NULL)
goto giveup;
key = strtok(line, " \t");
if (strcmp(key, "EndFontMetrics") == 0) {
fi->next = all_fonts;
all_fonts = fi;
fclose(in->currfp);
return;
} else if (strcmp(key, "FontName") == 0) {
if (!(val = strtok(NULL, " \t"))) {
error(err_afmval, &in->pos, key, 1);
goto giveup;
}
fi->name = dupstr(val);
} else if (strcmp(key, "FontBBox") == 0) {
int i;
for (i = 0; i < 3; i++) {
if (!(val = strtok(NULL, " \t"))) {
error(err_afmval, &in->pos, key, 4);
goto giveup;
}
fi->fontbbox[i] = atof(val);
}
} else if (strcmp(key, "CapHeight") == 0) {
if (!(val = strtok(NULL, " \t"))) {
error(err_afmval, &in->pos, key, 1);
goto giveup;
}
fi->capheight = atof(val);
} else if (strcmp(key, "XHeight") == 0) {
if (!(val = strtok(NULL, " \t"))) {
error(err_afmval, &in->pos, key, 1);
goto giveup;
}
fi->xheight = atof(val);
} else if (strcmp(key, "Ascender") == 0) {
if (!(val = strtok(NULL, " \t"))) {
error(err_afmval, &in->pos, key, 1);
goto giveup;
}
fi->ascent = atof(val);
} else if (strcmp(key, "Descender") == 0) {
if (!(val = strtok(NULL, " \t"))) {
error(err_afmval, &in->pos, key, 1);
goto giveup;
}
fi->descent = atof(val);
} else if (strcmp(key, "CapHeight") == 0) {
if (!(val = strtok(NULL, " \t"))) {
error(err_afmval, &in->pos, key, 1);
goto giveup;
}
fi->capheight = atof(val);
} else if (strcmp(key, "StdHW") == 0) {
if (!(val = strtok(NULL, " \t"))) {
error(err_afmval, &in->pos, key, 1);
goto giveup;
}
fi->stemh = atof(val);
} else if (strcmp(key, "StdVW") == 0) {
if (!(val = strtok(NULL, " \t"))) {
error(err_afmval, &in->pos, key, 1);
goto giveup;
}
fi->stemv = atof(val);
} else if (strcmp(key, "ItalicAngle") == 0) {
if (!(val = strtok(NULL, " \t"))) {
error(err_afmval, &in->pos, key, 1);
goto giveup;
}
fi->italicangle = atof(val);
} else if (strcmp(key, "StartCharMetrics") == 0) {
int nglyphs, i;
if (!(val = strtok(NULL, " \t"))) {
error(err_afmval, &in->pos, key, 1);
goto giveup;
}
nglyphs = atoi(val);
sfree(line);
for (i = 0; i < nglyphs; i++) {
int width = 0;
glyph g = NOGLYPH;
line = afm_read_line(in);
if (line == NULL)
goto giveup;
key = strtok(line, " \t");
while (key != NULL) {
if (strcmp(key, "WX") == 0 || strcmp(key, "W0X") == 0) {
if (!(val = strtok(NULL, " \t")) ||
!strcmp(val, ";")) {
error(err_afmval, &in->pos, key, 1);
goto giveup;
}
width = atoi(val);
} else if (strcmp(key, "N") == 0) {
if (!(val = strtok(NULL, " \t")) ||
!strcmp(val, ";")) {
error(err_afmval, &in->pos, key, 1);
goto giveup;
}
g = glyph_intern(val);
} else if (strcmp(key, "L") == 0) {
glyph succ, lig;
if (!(val = strtok(NULL, " \t")) ||
!strcmp(val, ";")) {
error(err_afmval, &in->pos, key, 1);
goto giveup;
}
succ = glyph_intern(val);
if (!(val = strtok(NULL, " \t")) ||
!strcmp(val, ";")) {
error(err_afmval, &in->pos, key, 1);
goto giveup;
}
lig = glyph_intern(val);
if (g != NOGLYPH && succ != NOGLYPH &&
lig != NOGLYPH) {
ligature *l = snew(ligature);
l->left = g;
l->right = succ;
l->lig = lig;
add234(fi->ligs, l);
}
}
do {
key = strtok(NULL, " \t");
} while (key && strcmp(key, ";"));
key = strtok(NULL, " \t");
}
sfree(line);
if (width != 0 && g != NOGLYPH) {
wchar_t ucs;
glyph_width *w = snew(glyph_width);
w->glyph = g;
w->width = width;
add234(fi->widths, w);
ucs = ps_glyph_to_unicode(g);
if (ucs < 0xFFFF)
fi->bmp[ucs] = g;
}
}
line = afm_read_line(in);
if (!line || !afm_require_key(line, "EndCharMetrics", in))
goto giveup;
sfree(line);
} else if (strcmp(key, "StartKernPairs") == 0 ||
strcmp(key, "StartKernPairs0") == 0) {
int nkerns, i;
kern_pair *kerns;
if (!(val = strtok(NULL, " \t"))) {
error(err_afmval, &in->pos, key, 1);
goto giveup;
}
nkerns = atoi(val);
sfree(line);
kerns = snewn(nkerns, kern_pair);
for (i = 0; i < nkerns; i++) {
line = afm_read_line(in);
if (line == NULL)
goto giveup;
key = strtok(line, " \t");
if (strcmp(key, "KPX") == 0) {
char *nl, *nr;
int l, r;
kern_pair *kp;
nl = strtok(NULL, " \t");
nr = strtok(NULL, " \t");
val = strtok(NULL, " \t");
if (!val) {
error(err_afmval, &in->pos, key, 3);
goto giveup;
}
l = glyph_intern(nl);
r = glyph_intern(nr);
if (l == -1 || r == -1) continue;
kp = snew(kern_pair);
kp->left = l;
kp->right = r;
kp->kern = atoi(val);
add234(fi->kerns, kp);
}
}
line = afm_read_line(in);
if (!line || !afm_require_key(line, "EndKernPairs", in))
goto giveup;
sfree(line);
}
}
giveup:
sfree(fi);
fclose(in->currfp);
return;
}
| 25.584838 | 78 | 0.50769 |
f953776d80fd83a97bdb62e38b90cc0bdd07bdaa | 291 | h | C | Analysis/Util/armadillo_utils.h | konradotto/TS | bf088bd8432b1e3f4b8c8c083650a30d9ef2ae2e | [
"Apache-2.0"
] | 125 | 2015-01-22T05:43:23.000Z | 2022-03-22T17:15:59.000Z | Analysis/Util/armadillo_utils.h | konradotto/TS | bf088bd8432b1e3f4b8c8c083650a30d9ef2ae2e | [
"Apache-2.0"
] | 59 | 2015-02-10T09:13:06.000Z | 2021-11-11T02:32:38.000Z | Analysis/Util/armadillo_utils.h | konradotto/TS | bf088bd8432b1e3f4b8c8c083650a30d9ef2ae2e | [
"Apache-2.0"
] | 98 | 2015-01-17T01:25:10.000Z | 2022-03-18T17:29:42.000Z | /* Copyright (C) 2011 Ion Torrent Systems, Inc. All Rights Reserved */
#ifndef ARMADILLO_UTILS_H
#define ARMADILLO_UTILS_H
#include <armadillo>
inline bool is_pos_def(const arma::mat22& M)
{
// Sylvester's test:
return M.at(0,0) > 0 and arma::det(M) > 0;
}
#endif // ARMADILLO_UTILS_H
| 19.4 | 70 | 0.714777 |
7f0c40b32bb6980c7c54038478493c1fb369a575 | 351 | h | C | waifu2xconvertercppoptions.h | rossomah/waifu2x-converter-qt | 1e203ad160f6e69874f1dd391cec534abdc36324 | [
"MIT"
] | 31 | 2015-08-27T17:03:11.000Z | 2022-01-31T03:25:09.000Z | waifu2xconvertercppoptions.h | rossomah/waifu2x-converter-qt | 1e203ad160f6e69874f1dd391cec534abdc36324 | [
"MIT"
] | null | null | null | waifu2xconvertercppoptions.h | rossomah/waifu2x-converter-qt | 1e203ad160f6e69874f1dd391cec534abdc36324 | [
"MIT"
] | 9 | 2015-05-31T12:43:18.000Z | 2022-01-24T16:09:35.000Z | #ifndef WAIFU2XCONVERTERCPPOPTIONS_H
#define WAIFU2XCONVERTERCPPOPTIONS_H
#include <QList>
namespace Waifu2xConverterQt {
enum Option {
Jobs,
ModelDir,
ScaleRatio,
NoiseLevel,
Mode,
OutputFile,
InputFile,
};
QString optionToString(const Option opt);
QList<Option> optionList();
}
#endif // WAIFU2XCONVERTERCPPOPTIONS_H
| 15.954545 | 41 | 0.74359 |
c32a17ce51c1490e80089876b8beefff26afb2de | 1,487 | c | C | USACO/C/1.1.5.c | lxdlam/ACM | cde519ef9732ff9e4e9e3f53c00fb30d07bdb306 | [
"MIT"
] | 1 | 2019-11-12T15:08:16.000Z | 2019-11-12T15:08:16.000Z | USACO/C/1.1.5.c | lxdlam/ACM | cde519ef9732ff9e4e9e3f53c00fb30d07bdb306 | [
"MIT"
] | null | null | null | USACO/C/1.1.5.c | lxdlam/ACM | cde519ef9732ff9e4e9e3f53c00fb30d07bdb306 | [
"MIT"
] | 1 | 2018-01-22T08:06:11.000Z | 2018-01-22T08:06:11.000Z | /*
ID: lxdlam1
LANG: C
TASK: beads
*/
#include <stdio.h>
#include <string.h>
#define MAX_LENGTH 351
int main()
{
FILE* fin = fopen("beads.in", "r");
FILE* fout = fopen("beads.out", "w");
int length, numMaxbeads = 0, i, left, right, j, flag = 1, m;
char necklace[2 * MAX_LENGTH] = {0}, temp[MAX_LENGTH] = {0};
fscanf(fin, "%d", &length);
fscanf(fin, "%s", temp);
strcpy(necklace, temp);
strcat(necklace, temp);
for (i = 0; i < 2 * length; i++)
{
numMaxbeads++;
if (necklace[i] != necklace[i + 1] && necklace[i + 1] != 0)
{
numMaxbeads = flag = 0;
break;
}
}
for (i = 0; i < 2 * length; i++)
{
if (necklace[i] == necklace[i + 1])
continue;
else if (necklace[i + 1] == '\0')
break;
else if (flag)
break;
left = right = 0;
m = i;
while (necklace[m] == 'w' && m > 0)
{
m--;
}
for (j = i; ; j--)
{
if (necklace[j] == necklace[m])
left++;
else if (necklace[j] == 'w')
left++;
else
break;
}
m = i + 1;
while (necklace[m] == 'w' && m < length)
{
m++;
}
for (j = i + 1; ; j++)
{
if (necklace[j] == necklace[m])
right++;
else if (necklace[j] == 'w')
right++;
else
break;
}
numMaxbeads = (left + right) > numMaxbeads ? (left + right) : numMaxbeads;
}
if (numMaxbeads >= length)
fprintf(fout, "%d\n", length);
else
fprintf(fout, "%d\n", numMaxbeads);
fclose(fin);
fclose(fout);
return 0;
}
| 19.311688 | 77 | 0.496974 |
c3a1b342714d8306689cf78ead0b1c278ba60b73 | 8,656 | c | C | sdk-6.5.20/libs/sdklt/bcmlrd/chip/bcm56996_a0/bcm56996_a0_lrd_table_info_map.c | copslock/broadcom_cpri | 8e2767676e26faae270cf485591902a4c50cf0c5 | [
"Spencer-94"
] | null | null | null | sdk-6.5.20/libs/sdklt/bcmlrd/chip/bcm56996_a0/bcm56996_a0_lrd_table_info_map.c | copslock/broadcom_cpri | 8e2767676e26faae270cf485591902a4c50cf0c5 | [
"Spencer-94"
] | null | null | null | sdk-6.5.20/libs/sdklt/bcmlrd/chip/bcm56996_a0/bcm56996_a0_lrd_table_info_map.c | copslock/broadcom_cpri | 8e2767676e26faae270cf485591902a4c50cf0c5 | [
"Spencer-94"
] | null | null | null | /*******************************************************************************
*
* DO NOT EDIT THIS FILE!
* This file is auto-generated by fltg from
* INTERNAL/fltg/xgs/table/common/common_TABLE_INFO.map.ltl for
* bcm56996_a0
*
* Tool: $SDK/INTERNAL/fltg/bin/fltg
*
* Edits to this file will be lost when it is regenerated.
*
* This license is set out in https://raw.githubusercontent.com/Broadcom-Network-Switching-Software/OpenBCM/master/Legal/LICENSE file.
*
* Copyright 2007-2020 Broadcom Inc. All rights reserved.
*/
#include <bcmlrd/bcmlrd_internal.h>
#include <bcmlrd/chip/bcmlrd_id.h>
#include <bcmlrd/chip/bcm56996_a0/bcm56996_a0_lrd_field_data.h>
#include <bcmlrd/chip/bcm56996_a0/bcm56996_a0_lrd_ltm_intf.h>
#include <bcmlrd/chip/bcm56996_a0/bcm56996_a0_lrd_xfrm_field_desc.h>
#include <bcmdrd/chip/bcm56996_a0_enum.h>
#include "bcmltd/chip/bcmltd_common_enumpool.h"
#include "bcm56996_a0_lrd_enumpool.h"
#include <bcmltd/id/bcmltd_common_id.h> /* LTID_T */
/* TABLE_INFO field init */
static const bcmlrd_field_data_t bcm56996_a0_lrd_table_info_map_field_data_mmd[] = {
{ /* 0 TABLE_ID */
.flags = BCMLRD_FIELD_F_READ_ONLY | BCMLTD_FIELD_F_KEY | BCMLTD_FIELD_F_ENUM,
.min = &bcm56996_a0_lrd_ifd_u32_0x0,
.def = &bcm56996_a0_lrd_ifd_u32_0x0,
.max = &bcm56996_a0_lrd_ifd_u32_0xffffffff,
.depth = 0,
.width = 32,
.edata = BCM56996_A0_LRD_LTID_T_DATA,
},
{ /* 1 TYPE */
.flags = BCMLRD_FIELD_F_READ_ONLY | BCMLTD_FIELD_F_ENUM,
.min = &bcm56996_a0_lrd_ifd_u32_0x0,
.def = &bcm56996_a0_lrd_ifd_u32_0x0,
.max = &bcm56996_a0_lrd_ifd_u32_0x4,
.depth = 0,
.width = 3,
.edata = BCMLTD_COMMON_TABLE_TYPE_T_DATA,
},
{ /* 2 MAP */
.flags = BCMLRD_FIELD_F_READ_ONLY | BCMLTD_FIELD_F_ENUM,
.min = &bcm56996_a0_lrd_ifd_u32_0x0,
.def = &bcm56996_a0_lrd_ifd_u32_0x0,
.max = &bcm56996_a0_lrd_ifd_u32_0x2,
.depth = 0,
.width = 2,
.edata = BCMLTD_COMMON_TABLE_MAP_T_DATA,
},
{ /* 3 MODELED */
.flags = BCMLRD_FIELD_F_READ_ONLY,
.min = &bcm56996_a0_lrd_ifd_is_true_0x0,
.def = &bcm56996_a0_lrd_ifd_is_true_0x0,
.max = &bcm56996_a0_lrd_ifd_is_true_0x1,
.depth = 0,
.width = 1,
.edata = NULL,
},
{ /* 4 READ_ONLY */
.flags = BCMLRD_FIELD_F_READ_ONLY,
.min = &bcm56996_a0_lrd_ifd_is_true_0x0,
.def = &bcm56996_a0_lrd_ifd_is_true_0x0,
.max = &bcm56996_a0_lrd_ifd_is_true_0x1,
.depth = 0,
.width = 1,
.edata = NULL,
},
{ /* 5 NUM_KEYS */
.flags = BCMLRD_FIELD_F_READ_ONLY,
.min = &bcm56996_a0_lrd_ifd_u32_0x0,
.def = &bcm56996_a0_lrd_ifd_u32_0x0,
.max = &bcm56996_a0_lrd_ifd_u32_0xffffffff,
.depth = 0,
.width = 32,
.edata = NULL,
},
{ /* 6 NUM_FIELDS */
.flags = BCMLRD_FIELD_F_READ_ONLY,
.min = &bcm56996_a0_lrd_ifd_u32_0x0,
.def = &bcm56996_a0_lrd_ifd_u32_0x0,
.max = &bcm56996_a0_lrd_ifd_u32_0xffffffff,
.depth = 0,
.width = 32,
.edata = NULL,
},
{ /* 7 ENTRY_INUSE_CNT */
.flags = BCMLRD_FIELD_F_READ_ONLY,
.min = &bcm56996_a0_lrd_ifd_u32_0x0,
.def = &bcm56996_a0_lrd_ifd_u32_0x0,
.max = &bcm56996_a0_lrd_ifd_u32_0xffffffff,
.depth = 0,
.width = 32,
.edata = NULL,
},
{ /* 8 ENTRY_MAXIMUM */
.flags = BCMLRD_FIELD_F_READ_ONLY,
.min = &bcm56996_a0_lrd_ifd_u32_0x0,
.def = &bcm56996_a0_lrd_ifd_u32_0x0,
.max = &bcm56996_a0_lrd_ifd_u32_0xffffffff,
.depth = 0,
.width = 32,
.edata = NULL,
},
{ /* 9 ENTRY_LIMIT */
.flags = BCMLRD_FIELD_F_READ_ONLY,
.min = &bcm56996_a0_lrd_ifd_u32_0x0,
.def = &bcm56996_a0_lrd_ifd_u32_0x0,
.max = &bcm56996_a0_lrd_ifd_u32_0xffffffff,
.depth = 0,
.width = 32,
.edata = NULL,
},
{ /* 10 NUM_RESOURCE_INFO */
.flags = BCMLRD_FIELD_F_READ_ONLY,
.min = &bcm56996_a0_lrd_ifd_u32_0x0,
.def = &bcm56996_a0_lrd_ifd_u32_0x0,
.max = &bcm56996_a0_lrd_ifd_u32_0xffffffff,
.depth = 0,
.width = 32,
.edata = NULL,
},
{ /* 11 INSERT_OPCODE */
.flags = BCMLRD_FIELD_F_READ_ONLY,
.min = &bcm56996_a0_lrd_ifd_is_true_0x0,
.def = &bcm56996_a0_lrd_ifd_is_true_0x0,
.max = &bcm56996_a0_lrd_ifd_is_true_0x1,
.depth = 0,
.width = 1,
.edata = NULL,
},
{ /* 12 DELETE_OPCODE */
.flags = BCMLRD_FIELD_F_READ_ONLY,
.min = &bcm56996_a0_lrd_ifd_is_true_0x0,
.def = &bcm56996_a0_lrd_ifd_is_true_0x0,
.max = &bcm56996_a0_lrd_ifd_is_true_0x1,
.depth = 0,
.width = 1,
.edata = NULL,
},
{ /* 13 LOOKUP_OPCODE */
.flags = BCMLRD_FIELD_F_READ_ONLY,
.min = &bcm56996_a0_lrd_ifd_is_true_0x0,
.def = &bcm56996_a0_lrd_ifd_is_true_0x0,
.max = &bcm56996_a0_lrd_ifd_is_true_0x1,
.depth = 0,
.width = 1,
.edata = NULL,
},
{ /* 14 UPDATE_OPCODE */
.flags = BCMLRD_FIELD_F_READ_ONLY,
.min = &bcm56996_a0_lrd_ifd_is_true_0x0,
.def = &bcm56996_a0_lrd_ifd_is_true_0x0,
.max = &bcm56996_a0_lrd_ifd_is_true_0x1,
.depth = 0,
.width = 1,
.edata = NULL,
},
{ /* 15 TRAVERSE_OPCODE */
.flags = BCMLRD_FIELD_F_READ_ONLY,
.min = &bcm56996_a0_lrd_ifd_is_true_0x0,
.def = &bcm56996_a0_lrd_ifd_is_true_0x0,
.max = &bcm56996_a0_lrd_ifd_is_true_0x1,
.depth = 0,
.width = 1,
.edata = NULL,
},
};
const bcmlrd_map_field_data_t bcm56996_a0_lrd_table_info_map_field_data = {
.fields = 16,
.field = bcm56996_a0_lrd_table_info_map_field_data_mmd
};
static const bcmlrd_map_table_attr_t bcm56996_a0_lrd_table_infot_attr_entry[] = {
{ /* 0 */
.key = BCMLRD_MAP_TABLE_ATTRIBUTE_INTERACTIVE,
.value = FALSE,
},
};
static const bcmlrd_map_attr_t bcm56996_a0_lrd_table_infot_attr_group = {
.attributes = 1,
.attr = bcm56996_a0_lrd_table_infot_attr_entry,
};
const bcmlrd_field_selector_t bcm56996_a0_lrd_table_info_map_select[] = {
{ /* Node:0, Type:ROOT, TYPE */
.selector_type = BCMLRD_FIELD_SELECTOR_TYPE_ROOT,
.field_id = TABLE_INFOt_TYPEf,
.group_index = BCMLRD_INVALID_SELECTOR_INDEX,
.entry_index = BCMLRD_INVALID_SELECTOR_INDEX,
.selection_parent = BCMLRD_INVALID_SELECTOR_INDEX,
.group = BCMLRD_INVALID_SELECTOR_INDEX,
.selector_id = BCMLRD_INVALID_SELECTOR_INDEX,
.selector_value = BCMLRD_INVALID_SELECTOR_INDEX
},
{ /* Node:1, Type:FIELD, ENTRY_MAXIMUM */
.selector_type = BCMLRD_FIELD_SELECTOR_TYPE_FIELD,
.field_id = TABLE_INFOt_ENTRY_MAXIMUMf,
.group_index = BCMLRD_INVALID_SELECTOR_INDEX,
.entry_index = BCMLRD_INVALID_SELECTOR_INDEX,
.selection_parent = 0,
.group = 0,
.selector_id = TABLE_INFOt_TYPEf,
.selector_value = 0 /* INDEX */
},
{ /* Node:2, Type:FIELD, ENTRY_MAXIMUM */
.selector_type = BCMLRD_FIELD_SELECTOR_TYPE_FIELD,
.field_id = TABLE_INFOt_ENTRY_MAXIMUMf,
.group_index = BCMLRD_INVALID_SELECTOR_INDEX,
.entry_index = BCMLRD_INVALID_SELECTOR_INDEX,
.selection_parent = 0,
.group = 1,
.selector_id = TABLE_INFOt_TYPEf,
.selector_value = 1 /* INDEX_ALLOCATE */
},
{ /* Node:3, Type:FIELD, ENTRY_MAXIMUM */
.selector_type = BCMLRD_FIELD_SELECTOR_TYPE_FIELD,
.field_id = TABLE_INFOt_ENTRY_MAXIMUMf,
.group_index = BCMLRD_INVALID_SELECTOR_INDEX,
.entry_index = BCMLRD_INVALID_SELECTOR_INDEX,
.selection_parent = 0,
.group = 2,
.selector_id = TABLE_INFOt_TYPEf,
.selector_value = 4 /* CONFIG */
},
};
const bcmlrd_field_selector_data_t bcm56996_a0_lrd_table_info_map_select_data = {
.num_field_selector = 4,
.field_selector = bcm56996_a0_lrd_table_info_map_select,
};
static const bcmlrd_map_group_t bcm56996_a0_lrd_table_info_map_group[] = {
{
.dest = {
.kind = BCMLRD_MAP_LTM,
.id = 0,
},
.entries = 0,
.entry = NULL
},
};
const bcmlrd_map_t bcm56996_a0_lrd_table_info_map = {
.src_id = TABLE_INFOt,
.field_data = &bcm56996_a0_lrd_table_info_map_field_data,
.groups = 1,
.group = bcm56996_a0_lrd_table_info_map_group,
.table_attr = &bcm56996_a0_lrd_table_infot_attr_group,
.entry_ops = BCMLRD_MAP_TABLE_ENTRY_OPERATION_LOOKUP | BCMLRD_MAP_TABLE_ENTRY_OPERATION_TRAVERSE,
.sel = &bcm56996_a0_lrd_table_info_map_select_data,
};
| 33.8125 | 134 | 0.654575 |
bf980fd1f7855564ce0e462f4fed6ebf4901ba6a | 2,733 | h | C | CondFormats/L1TObjects/interface/L1TriggerKeyListExt.h | nistefan/cmssw | ea13af97f7f2117a4f590a5e654e06ecd9825a5b | [
"Apache-2.0"
] | 3 | 2018-08-24T19:10:26.000Z | 2019-02-19T11:45:32.000Z | CondFormats/L1TObjects/interface/L1TriggerKeyListExt.h | nistefan/cmssw | ea13af97f7f2117a4f590a5e654e06ecd9825a5b | [
"Apache-2.0"
] | 3 | 2018-08-23T13:40:24.000Z | 2019-12-05T21:16:03.000Z | CondFormats/L1TObjects/interface/L1TriggerKeyListExt.h | nistefan/cmssw | ea13af97f7f2117a4f590a5e654e06ecd9825a5b | [
"Apache-2.0"
] | 5 | 2018-08-21T16:37:52.000Z | 2020-01-09T13:33:17.000Z | #ifndef CondFormats_L1TObjects_L1TriggerKeyListExt_h
#define CondFormats_L1TObjects_L1TriggerKeyListExt_h
// system include files
#include "CondFormats/Serialization/interface/Serializable.h"
#include <string>
#include <map>
class L1TriggerKeyListExt
{
public:
L1TriggerKeyListExt();
virtual ~L1TriggerKeyListExt();
typedef std::map< std::string, std::string > KeyToToken ;
typedef std::map< std::string, KeyToToken > RecordToKeyToToken ;
// ---------- const member functions ---------------------
// Get payload token for L1TriggerKeyExt
std::string token( const std::string& tscKey ) const ;
// Get payload token for configuration data
std::string token( const std::string& recordName,
const std::string& dataType,
const std::string& key ) const ;
// Get payload token for configuration data
std::string token( const std::string& recordType, // "record@type"
const std::string& key ) const ;
const KeyToToken& tscKeyToTokenMap() const
{ return m_tscKeyToToken ; }
const RecordToKeyToToken& recordTypeToKeyToTokenMap() const
{ return m_recordKeyToken ; }
// Get object key for a given payload token. In practice, each
// record in the CondDB has only one object, so there is no need to
// specify the data type.
std::string objectKey( const std::string& recordName,
const std::string& payloadToken ) const ;
// Get TSC key for a given L1TriggerKeyExt payload token
std::string tscKey( const std::string& triggerKeyPayloadToken ) const ;
// ---------- static member functions --------------------
// ---------- member functions ---------------------------
// Store payload token for L1TriggerKey, return true if successful
bool addKey( const std::string& tscKey,
const std::string& payloadToken,
bool overwriteKey = false ) ;
// Store payload token for configuration data, return true if successful
bool addKey( const std::string& recordType, // "record@type"
const std::string& key,
const std::string& payloadToken,
bool overwriteKey = false ) ;
private:
//L1TriggerKeyListExt(const L1TriggerKeyListExt&); // stop default
//const L1TriggerKeyListExt& operator=(const L1TriggerKeyListExt&); // stop default
// ---------- member data --------------------------------
// map of TSC key (first) to L1TriggerKeyExt payload token (second)
KeyToToken m_tscKeyToToken ;
// map of subsystem key (second/first) to configuration data payload
// token (second/second), keyed by record@type (first)
RecordToKeyToToken m_recordKeyToken ;
COND_SERIALIZABLE;
};
#endif
| 32.927711 | 89 | 0.65569 |
c73e16a2803086b76f37f15c285ea94a5d5b2c18 | 310 | h | C | dbms/src/DataStreams/copyData.h | 189569400/ClickHouse | 0b8683c8c9f0e17446bef5498403c39e9cb483b8 | [
"Apache-2.0"
] | 3 | 2016-12-30T14:19:47.000Z | 2021-11-13T06:58:32.000Z | dbms/src/DataStreams/copyData.h | 189569400/ClickHouse | 0b8683c8c9f0e17446bef5498403c39e9cb483b8 | [
"Apache-2.0"
] | 1 | 2017-01-13T21:29:36.000Z | 2017-01-16T18:29:08.000Z | dbms/src/DataStreams/copyData.h | 189569400/ClickHouse | 0b8683c8c9f0e17446bef5498403c39e9cb483b8 | [
"Apache-2.0"
] | 1 | 2021-02-07T16:00:54.000Z | 2021-02-07T16:00:54.000Z | #pragma once
#include <atomic>
namespace DB
{
class IBlockInputStream;
class IBlockOutputStream;
/** Копирует данные из InputStream в OutputStream
* (например, из БД в консоль и т. п.)
*/
void copyData(IBlockInputStream & from, IBlockOutputStream & to, std::atomic<bool> * is_cancelled = nullptr);
}
| 17.222222 | 109 | 0.732258 |
67b20b3943cc65047de5ccaa4a1e9263fe5b04ec | 2,544 | c | C | 1001/1001.c | zs1621/cstudy | 4e1d1e479723f2ba9033c75fb5b1050fe291cf09 | [
"MIT"
] | null | null | null | 1001/1001.c | zs1621/cstudy | 4e1d1e479723f2ba9033c75fb5b1050fe291cf09 | [
"MIT"
] | null | null | null | 1001/1001.c | zs1621/cstudy | 4e1d1e479723f2ba9033c75fb5b1050fe291cf09 | [
"MIT"
] | null | null | null | #include <math.h>
#include <stdlib.h>
int mnum = 0;
int lena = 1;
int lenb = 1;
int len = 2;
int x,y,z;
int i,j,k;
int result[6][125];
/************************
* *
* @param s1 乘数 *
* @param s2 乘数 *
* @param s 结果 *
* *
************************/
void muls(int *s1, int *s2, int *s)
{
for (i=0; i < lena; i++) {
for (j=0; j < lenb; j++) {
s[i+j] += s1[i] * s2[j];
}
}
int k = len;
while (!s[k])
--k;
for(i=0,j=0; i <= k; i++)
{
s[i+1] += s[i] / 10;
s[i] %= 10;
}
}
/************************
* *
* @param s 求方的值 *
* @param res 结果 *
* @param num 求方次数 *
* *
************************/
void mul(int *s, int *res, int num) {
for (mnum = 0; mnum < num; mnum++) {
if (mnum == 0) {
muls(s, s, res);
while (!res[len]) {
--len;
}
lena = len;
lenb = 5;
len = lena + lenb;
} else {
muls(res, s, res);
while (!res[len]) {
--len;
}
lena = len;
lenb = 5;
len = lena + lenb;
}
}
}
void main () {
char a[6][6];
char kill[6][5];
int live[6][5];
int b[6];
int c[6];
for ( i = 0; i < 6; i++ ) {
scanf("%6s %3d", a[i], &b[i]);
}
for ( i = 0; i < 6; i++ ) {
k = 5;
for (j = 0; j < 6; j++) {
k -= 1;
if ( a[i][j] == '.' ) {
c[i] = j;
k = k + 1;
} else {
kill[i][k] = a[i][j];
}
}
}
for ( i = 0; i < 6; i++) {
for ( j = 0; j < 5; j++) {
//printf("%c--", kill[i][j]);
}
}
for ( x= 0; x < 6; x++) {
for (i = 0; i < 5; i++) {
live[x][i] = (kill[x][i] - '0');
// printf("%d ppp %d zz", live[x][i], i);
}
}
for ( x=0; x < 6; x++ ) {
int s[5] = {0};
int res[125] = {0};
for (y = 0; y < 5; y++) {
s[y] = live[x][y];
printf("%d\n", s[y]);
}
printf("--%d--", b[x]);
printf("------------------------------------------");
mul(s, res, b[x]);
for ( y = 0; y < 125; y++) {
if (y == 124) {
printf("\n");
} else {
printf("%d", res[y]);
}
}
}
}
| 21.024793 | 61 | 0.26533 |
68f46366d8cf0e7d328d1c7c216e27e8c88a4965 | 3,015 | h | C | Compressonator/Applications/_Plugins/C3DModel_Loaders/obj/gltf/GltfCommon.h | gauravgarg17/Compressonator | 5cbc5cf4383da4bceeb1d2d2781421f63c48c6aa | [
"MIT"
] | 29 | 2018-08-07T17:19:22.000Z | 2022-03-25T13:53:57.000Z | Compressonator/Applications/_Plugins/C3DModel_Loaders/obj/gltf/GltfCommon.h | gauravgarg17/Compressonator | 5cbc5cf4383da4bceeb1d2d2781421f63c48c6aa | [
"MIT"
] | 19 | 2019-07-08T09:03:06.000Z | 2019-08-09T10:58:48.000Z | Compressonator/Applications/_Plugins/C3DModel_Loaders/obj/gltf/GltfCommon.h | gauravgarg17/Compressonator | 5cbc5cf4383da4bceeb1d2d2781421f63c48c6aa | [
"MIT"
] | 7 | 2019-03-19T01:08:52.000Z | 2020-09-08T14:42:39.000Z | // AMD AMDUtils code
//
// Copyright(c) 2017 Advanced Micro Devices, Inc.All rights reserved.
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files(the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions :
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#pragma once
#include "../json/json.h"
#include "GltfFeatures.h"
#include "MIPS.h"
#include "GltfStructures.h"
// The GlTF file is loaded in 2 steps
// 1) loading the GPU agnostic data (This is done in the GLTFCommon class you can see here below)
// - nodes
// - scenes
// - animations
// - binary buffers
// - GPU specific data
//
//2) Loading the GPU specific data and rendering it with a specific technique, this is done in the GltfPbr class (see GltfPbr.h)
// This split allows us to have different techniques to render a same model.
// In the future we'll have different techniques to render the scene:
// - depth only
// - shadow maps
// - motion vectors
// - transparent pass
// - ...
struct tfPrimitives
{
XMVECTOR m_center;
XMVECTOR m_radius;
};
struct tfMesh
{
std::vector<tfPrimitives> m_pPrimitives;
};
struct NodeMatrixPostTransform
{
tfNode *pN; XMMATRIX m;
};
class GLTFCommon
{
public:
nlohmann::json j3;
std::string m_path = "";
std::string m_filename = ""; // *1*
std::vector<tfScene> m_scenes;
std::vector<char *> buffersData;
int Load(std::string path, std::string filename, CMIPS *cmips = NULL);
void Unload();
void SetAnimationTime(int animationIndex, float time);
void TransformNodes(NodeMatrixPostTransform *pNodesOut, DWORD *pCount);
DWORD GetNodeCount() { return (DWORD)m_nodes.size(); }
std::vector<tfMesh> m_meshes;
float m_distance = 4.0f; // calc from mesh atrribes what the max value in ether x or y direction is going to be
private:
std::vector<tfNode> m_nodes;
std::vector<tfAnimation> m_animations;
};
void GetBufferDetails(nlohmann::json::object_t accessor, nlohmann::json::array_t bufferViews, std::vector<char *> buffers, tfAccessor *pAccessor); | 35.892857 | 146 | 0.709121 |
6e7f70c39729654ed79c9d3896e598142f9e648c | 3,210 | c | C | mwc/romana/relic/e/lib/ncurses/lib_erase.c | gspu/Coherent | 299bea1bb52a4dcc42a06eabd5b476fce77013ef | [
"BSD-3-Clause"
] | 20 | 2019-10-10T14:14:56.000Z | 2022-02-24T02:54:38.000Z | mwc/romana/relic/g/usr/lib/ncurses/lib_erase.c | gspu/Coherent | 299bea1bb52a4dcc42a06eabd5b476fce77013ef | [
"BSD-3-Clause"
] | null | null | null | mwc/romana/relic/g/usr/lib/ncurses/lib_erase.c | gspu/Coherent | 299bea1bb52a4dcc42a06eabd5b476fce77013ef | [
"BSD-3-Clause"
] | 1 | 2022-03-25T18:38:37.000Z | 2022-03-25T18:38:37.000Z | /*********************************************************************
* COPYRIGHT NOTICE *
**********************************************************************
* This software is copyright (C) 1982 by Pavel Curtis *
* *
* Permission is granted to reproduce and distribute *
* this file by any means so long as no fee is charged *
* above a nominal handling fee and so long as this *
* notice is always included in the copies. *
* *
* Other rights are reserved except as explicitly granted *
* by written permission of the author. *
* Pavel Curtis *
* Computer Science Dept. *
* 405 Upson Hall *
* Cornell University *
* Ithaca, NY 14853 *
* *
* Ph- (607) 256-4934 *
* *
* Pavel.Cornell@Udel-Relay (ARPAnet) *
* decvax!cornell!pavel (UUCPnet) *
*********************************************************************/
/*
** lib_erase.c
**
** The routine werase().
**
** $Log: lib_erase.c,v $
* Revision 1.8 93/04/12 14:13:38 bin
* Udo: third color update
*
* Revision 1.2 92/04/13 14:37:27 bin
* update by vlad
*
* Revision 2.3 91/04/20 18:32:50 munk
* Usage of register variables
*
* Revision 2.2 82/11/03 12:27:41 pavel
* Fixed off-by-one error... If only I had used an invariant...
*
* Revision 2.1 82/10/25 14:47:17 pavel
* Added Copyright Notice
*
* Revision 2.0 82/10/25 13:45:12 pavel
* Beta-one Test Release
*
**
*/
#ifdef RCSHDR
static char RCSid[] =
"$Header: /src386/usr/lib/ncurses/RCS/lib_erase.c,v 1.8 93/04/12 14:13:38 bin Exp Locker: bin $";
#endif
#include "curses.h"
#include "curses.priv.h"
werase(win)
register WINDOW *win;
{
register int y;
chtype *sp, *end, *start, *maxx;
int minx;
chtype blank = ' ' | win->_attrs;
#ifdef TRACE
if (_tracing)
_tracef("werase(%o) called", win);
#endif
for (y = win->_regtop; y <= win->_regbottom; y++)
{
minx = _NOCHANGE;
start = win->_line[y];
end = &start[win->_maxx];
for (sp = start; sp <= end; sp++)
{
if (*sp != blank)
{
maxx = sp;
if (minx == _NOCHANGE)
minx = sp - start;
*sp = blank;
win->_numchngd[y] += 1;
}
}
if (minx != _NOCHANGE)
{
if (win->_firstchar[y] > minx
|| win->_firstchar[y] == _NOCHANGE)
win->_firstchar[y] = minx;
if (win->_lastchar[y] < maxx - win->_line[y])
win->_lastchar[y] = maxx - win->_line[y];
}
}
win->_curx = win->_cury = 0;
}
| 30 | 98 | 0.411215 |
f50109befdd3c10b593b6201eed6e1056d7c4c3e | 242 | c | C | crt/sched.c | asvrada/mystikos | eee9b1d1fc0a5b621b42c6dafdb709de8e8b09c5 | [
"MIT"
] | 87 | 2021-02-19T05:22:29.000Z | 2022-03-31T12:40:50.000Z | crt/sched.c | asvrada/mystikos | eee9b1d1fc0a5b621b42c6dafdb709de8e8b09c5 | [
"MIT"
] | 519 | 2021-02-19T18:26:41.000Z | 2022-03-31T23:26:55.000Z | crt/sched.c | asvrada/mystikos | eee9b1d1fc0a5b621b42c6dafdb709de8e8b09c5 | [
"MIT"
] | 69 | 2021-02-19T00:20:08.000Z | 2022-02-16T22:47:18.000Z | #include <myst/syscallext.h>
#include <sched.h>
#include <stdio.h>
#include <string.h>
#include <syscall.h>
#include <unistd.h>
int sched_getparam(pid_t pid, struct sched_param* param)
{
return syscall(SYS_sched_getparam, pid, param);
}
| 20.166667 | 56 | 0.731405 |
91d96187c02ab9b9fb81c921bb39dbf9171ac6ed | 1,560 | h | C | lib/usual/crypto/hmac.h | yummyliu/pgbouncers | 15357f8d4cec51707e41708cfb1adee5923c3cda | [
"0BSD",
"MIT"
] | null | null | null | lib/usual/crypto/hmac.h | yummyliu/pgbouncers | 15357f8d4cec51707e41708cfb1adee5923c3cda | [
"0BSD",
"MIT"
] | null | null | null | lib/usual/crypto/hmac.h | yummyliu/pgbouncers | 15357f8d4cec51707e41708cfb1adee5923c3cda | [
"0BSD",
"MIT"
] | null | null | null | /*
* HMAC implementation based on OpenBSD
*
* Copyright (c) 2012 Daniel Farina
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
/**
* @file
* HMAC-SHA1 implementation (RFC2104).
*/
#ifndef _USUAL_CRYPTO_HMAC_H_
#define _USUAL_CRYPTO_HMAC_H_
#include <usual/crypto/digest.h>
/** HMAC Context */
struct HMAC;
/** Create context with key */
struct HMAC *hmac_new(const struct DigestInfo *impl,
const void *key, unsigned int key_len,
CxMem *cx);
/** Free context */
void hmac_free(struct HMAC *ctx);
/** Initialize context */
void hmac_reset(struct HMAC *ctx);
/** Hash more data */
void hmac_update(struct HMAC *ctx, const void *data, unsigned int len);
/** Get final result */
void hmac_final(struct HMAC *ctx, uint8_t *dst);
unsigned hmac_block_len(struct HMAC *ctx);
unsigned hmac_result_len(struct HMAC *ctx);
#endif /* _USUAL_HMAC_H_ */
| 29.433962 | 75 | 0.735897 |
8cb933e0be9730cc7ed288175994afb20a090751 | 3,232 | h | C | basic_programming/zebra/rtadv.h | shan3275/c | 481bdac8c3e852703b5a78859edf5148732a4452 | [
"BSD-2-Clause"
] | null | null | null | basic_programming/zebra/rtadv.h | shan3275/c | 481bdac8c3e852703b5a78859edf5148732a4452 | [
"BSD-2-Clause"
] | null | null | null | basic_programming/zebra/rtadv.h | shan3275/c | 481bdac8c3e852703b5a78859edf5148732a4452 | [
"BSD-2-Clause"
] | null | null | null | /* Router advertisement
* Copyright (C) 2005 6WIND <jean-mickael.guerin@6wind.com>
* Copyright (C) 1999 Kunihiro Ishiguro
*
* This file is part of GNU Zebra.
*
* GNU Zebra 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, or (at your option) any
* later version.
*
* GNU Zebra 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 GNU Zebra; see the file COPYING. If not, write to the Free
* Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*/
#ifndef _ZEBRA_RTADV_H
#define _ZEBRA_RTADV_H
#include "vty.h"
#include "zebra/interface.h"
/* NB: RTADV is defined in zebra/interface.h above */
#ifdef RTADV
/* Router advertisement prefix. */
struct rtadv_prefix
{
/* Prefix to be advertised. */
struct prefix_ipv6 prefix;
/* The value to be placed in the Valid Lifetime in the Prefix */
u_int32_t AdvValidLifetime;
#define RTADV_VALID_LIFETIME 2592000
/* The value to be placed in the on-link flag */
int AdvOnLinkFlag;
/* The value to be placed in the Preferred Lifetime in the Prefix
Information option, in seconds.*/
u_int32_t AdvPreferredLifetime;
#define RTADV_PREFERRED_LIFETIME 604800
/* The value to be placed in the Autonomous Flag. */
int AdvAutonomousFlag;
/* The value to be placed in the Router Address Flag [RFC6275 7.2]. */
int AdvRouterAddressFlag;
#ifndef ND_OPT_PI_FLAG_RADDR
#define ND_OPT_PI_FLAG_RADDR 0x20
#endif
};
extern void rtadv_config_write (struct vty *, struct interface *);
extern void rtadv_init (void);
/* RFC4584 Extension to Sockets API for Mobile IPv6 */
#ifndef ND_OPT_ADV_INTERVAL
#define ND_OPT_ADV_INTERVAL 7 /* Adv Interval Option */
#endif
#ifndef ND_OPT_HA_INFORMATION
#define ND_OPT_HA_INFORMATION 8 /* HA Information Option */
#endif
#ifndef HAVE_STRUCT_ND_OPT_ADV_INTERVAL
struct nd_opt_adv_interval { /* Advertisement interval option */
uint8_t nd_opt_ai_type;
uint8_t nd_opt_ai_len;
uint16_t nd_opt_ai_reserved;
uint32_t nd_opt_ai_interval;
} __attribute__((__packed__));
#else
#ifndef HAVE_STRUCT_ND_OPT_ADV_INTERVAL_ND_OPT_AI_TYPE
/* fields may have to be renamed */
#define nd_opt_ai_type nd_opt_adv_interval_type
#define nd_opt_ai_len nd_opt_adv_interval_len
#define nd_opt_ai_reserved nd_opt_adv_interval_reserved
#define nd_opt_ai_interval nd_opt_adv_interval_ival
#endif
#endif
#ifndef HAVE_STRUCT_ND_OPT_HOMEAGENT_INFO
struct nd_opt_homeagent_info { /* Home Agent info */
u_int8_t nd_opt_hai_type;
u_int8_t nd_opt_hai_len;
u_int16_t nd_opt_hai_reserved;
u_int16_t nd_opt_hai_preference;
u_int16_t nd_opt_hai_lifetime;
} __attribute__((__packed__));
#endif
extern const char *rtadv_pref_strs[];
#endif /* RTADV */
#endif /* _ZEBRA_RTADV_H */
| 30.780952 | 73 | 0.73979 |
1bab153d45994796ddb7436af2419c64117f69fa | 1,132 | h | C | src/xray/render/base/engine_renderer.h | ixray-team/ixray-2.0 | 85c3a544175842323fc82f42efd96c66f0fc5abb | [
"Linux-OpenIB"
] | 3 | 2021-10-30T09:36:14.000Z | 2022-03-26T17:00:06.000Z | src/xray/render/base/engine_renderer.h | acidicMercury8/ixray-2.0 | 85c3a544175842323fc82f42efd96c66f0fc5abb | [
"Linux-OpenIB"
] | null | null | null | src/xray/render/base/engine_renderer.h | acidicMercury8/ixray-2.0 | 85c3a544175842323fc82f42efd96c66f0fc5abb | [
"Linux-OpenIB"
] | 1 | 2022-03-26T17:00:08.000Z | 2022-03-26T17:00:08.000Z | ////////////////////////////////////////////////////////////////////////////
// Created : 28.10.2008
// Author : Dmitriy Iassenev
// Copyright (C) GSC Game World - 2009
////////////////////////////////////////////////////////////////////////////
#ifndef XRAY_RENDER_BASE_ENGINE_RENDERER_H_INCLUDED
#define XRAY_RENDER_BASE_ENGINE_RENDERER_H_INCLUDED
namespace xray {
namespace render {
namespace engine {
struct XRAY_NOVTABLE renderer {
virtual bool run ( bool wait_for_command ) = 0;
virtual bool run_editor_commands ( bool wait_for_command ) = 0;
virtual u32 frame_id ( ) = 0;
virtual void set_view_matrix ( float4x4 const& view_matrix ) = 0;
virtual void set_projection_matrix ( float4x4 const& view_matrix ) = 0;
virtual void draw_frame ( ) = 0;
virtual void purge_orders ( ) = 0;
virtual void flush_debug_commands ( ) = 0;
virtual void test_cooperative_level ( ) = 0;
XRAY_DECLARE_PURE_VIRTUAL_DESTRUCTOR( renderer )
}; // class world
} // namespace engine
} // namespace render
} // namespace xray
#endif // #ifndef XRAY_RENDER_BASE_ENGINE_RENDERER_H_INCLUDED | 35.375 | 77 | 0.623675 |
1ef31a8ab608dbbe566eb886d2d9ac7f437bef3d | 1,301 | h | C | ch8_VO2/include/EdgeSE3ProjectDirect.h | ClovisChen/slam14 | 35fad23a491f2dd7666edab55ae849ac937d44c2 | [
"MIT"
] | null | null | null | ch8_VO2/include/EdgeSE3ProjectDirect.h | ClovisChen/slam14 | 35fad23a491f2dd7666edab55ae849ac937d44c2 | [
"MIT"
] | null | null | null | ch8_VO2/include/EdgeSE3ProjectDirect.h | ClovisChen/slam14 | 35fad23a491f2dd7666edab55ae849ac937d44c2 | [
"MIT"
] | null | null | null | //
// Created by chen-tian on 7/26/17.
//
#ifndef CH8_VO2_EDGESE3PROJECTDIRECT_H
#define CH8_VO2_EDGESE3PROJECTDIRECT_H
#include <g2o/core/base_unary_edge.h>
#include <g2o/types/sba/types_sba.h>
#include <g2o/types/sba/types_six_dof_expmap.h>
#include <iostream>
#include <opencv2/core/core.hpp>
using namespace cv;
//project a 3d point into an image plane, the error is photometric error
//an unary edge with one vertex SE3Expmap (the pose of camera)
class EdgeSE3ProjectDirect: public g2o::BaseUnaryEdge<1, double, g2o::VertexSE3Expmap >
{
public:
EIGEN_MAKE_ALIGNED_OPERATOR_NEW;
EdgeSE3ProjectDirect(){};
EdgeSE3ProjectDirect( Eigen::Vector3d point, float fx, float fy, float cx, float cy, Mat* image );
virtual void computeError();
//plus in manifold
virtual void linearizeOplus();
//dummy read and write functions because we don't care...
virtual bool read (std::istream& in){};
virtual bool write (std::ostream& out )const {};
protected:
//get a gray scale value from reference image (bilinear interpolated)
inline float getPixelValue ( float x, float y );
public:
Eigen::Vector3d x_world_;
float cx_=0, cy_=0, fx_=0, fy_=0;//Camera intrinsics
Mat* image_= nullptr;//reference image
};
#endif //CH8_VO2_EDGESE3PROJECTDIRECT_H
| 27.680851 | 102 | 0.732513 |
518f4178dd44ad5e1ad19d643d10f09e1f71f223 | 919 | h | C | protocols/GEOTileServerProxyDelegate.h | shaojiankui/iOS10-Runtime-Headers | 6b0d842bed0c52c2a7c1464087b3081af7e10c43 | [
"MIT"
] | 36 | 2016-04-20T04:19:04.000Z | 2018-10-08T04:12:25.000Z | protocols/GEOTileServerProxyDelegate.h | shaojiankui/iOS10-Runtime-Headers | 6b0d842bed0c52c2a7c1464087b3081af7e10c43 | [
"MIT"
] | null | null | null | protocols/GEOTileServerProxyDelegate.h | shaojiankui/iOS10-Runtime-Headers | 6b0d842bed0c52c2a7c1464087b3081af7e10c43 | [
"MIT"
] | 10 | 2016-06-16T02:40:44.000Z | 2019-01-15T03:31:45.000Z | /* Generated by RuntimeBrowser.
*/
@protocol GEOTileServerProxyDelegate
@required
- (void)proxy:(GEOTileServerProxy *)arg1 canShrinkDiskCacheByAmount:(unsigned long long)arg2;
- (void)proxy:(GEOTileServerProxy *)arg1 didShrinkDiskCacheByAmount:(unsigned long long)arg2;
- (void)proxy:(GEOTileServerProxy *)arg1 failedToLoadAllPendingTilesWithError:(NSError *)arg2;
- (void)proxy:(GEOTileServerProxy *)arg1 failedToLoadTiles:(GEOTileKeyList *)arg2 error:(NSError *)arg3;
- (void)proxy:(GEOTileServerProxy *)arg1 loadedTile:(NSData *)arg2 forKey:(const struct _GEOTileKey { unsigned int x1 : 6; unsigned int x2 : 26; unsigned int x3 : 26; unsigned int x4 : 6; unsigned int x5 : 8; unsigned int x6 : 8; unsigned int x7 : 8; unsigned int x8 : 1; unsigned int x9 : 7; unsigned char x10[4]; }*)arg3 info:(NSDictionary *)arg4;
- (void)proxy:(GEOTileServerProxy *)arg1 willGoToNetworkForTiles:(GEOTileKeyList *)arg2;
@end
| 57.4375 | 349 | 0.764962 |
b6434caff01a196c151730c9c292ef1e5830134c | 586 | c | C | src/utils/files.c | LuckyMagpie/lonely-tennis | c163b384adb96a197c1f3622c915f8f02324e9a7 | [
"MIT"
] | 2 | 2018-07-10T21:55:13.000Z | 2021-08-08T08:15:24.000Z | src/utils/files.c | LuckyMagpie/lonely-tennis | c163b384adb96a197c1f3622c915f8f02324e9a7 | [
"MIT"
] | null | null | null | src/utils/files.c | LuckyMagpie/lonely-tennis | c163b384adb96a197c1f3622c915f8f02324e9a7 | [
"MIT"
] | null | null | null | #include <stdio.h>
#include <stdlib.h>
#include "files.h"
#include "vector.h"
char* file_to_str(const char* path)
{
FILE* file = fopen(path, "rb");
if (!file) {
fprintf(stderr, "%s:File not found %s\n", __func__, path);
char* error = malloc(1);
error[0] = '\0';
return error;
}
fseek(file, 0, SEEK_END);
unsigned long file_size = (unsigned long)ftell(file);
rewind(file);
char* string = malloc(file_size + 1);
fread(string, file_size, 1, file);
fclose(file);
string[file_size] = '\0';
return string;
}
| 18.903226 | 66 | 0.580205 |
2287c6d9ee162c66293a0a178f566d0156dd7786 | 1,309 | h | C | include/slog/appender/appender.h | suemi994/slog | 720dfd8301ca31ac321d87053cfce65ae9aeb719 | [
"MIT"
] | null | null | null | include/slog/appender/appender.h | suemi994/slog | 720dfd8301ca31ac321d87053cfce65ae9aeb719 | [
"MIT"
] | null | null | null | include/slog/appender/appender.h | suemi994/slog | 720dfd8301ca31ac321d87053cfce65ae9aeb719 | [
"MIT"
] | null | null | null | /*
* Created by suemi on 2016/12/7.
*/
#ifndef SLOG_APPENDER_H
#define SLOG_APPENDER_H
#include <string>
#include <memory>
#include "slog/utils/no_copyable.h"
#include "slog/base/fixed_buffer.h"
namespace slog {
class ErrorHandler;
class Properties;
class Appender : public NoCopyable {
public:
struct Result {
bool is_success;
std::string message;
const char* data;
int written;
int len;
Result();
Result(bool success, const char* start, int length, int write_size = 0, const std::string& msg=std::string());
};
Appender(const std::string& name);
Appender(const Properties &prop);
virtual ~Appender();
static std::shared_ptr<Appender> DefaultInstance();
/**
* 关闭所持有的资源比如文件句柄、网络socket
*/
virtual void Close();
bool IsClosed() const;
template<size_t SIZE>
void Append(const FixedBuffer<SIZE> &buffer);
virtual void Append(const char *data, size_t len);
const std::string& name() const;
virtual bool is_immediate() const = 0;
const std::unique_ptr<ErrorHandler> &error_handler() const;
void set_error_handler(std::unique_ptr<ErrorHandler> &handler);
protected:
virtual Result DoAppend(const char* data, int len) = 0;
std::string name_;
std::unique_ptr<ErrorHandler> error_handler_;
bool is_closed_;
};
}
#endif
| 17.931507 | 114 | 0.700535 |
39333579200f2057abd3a6dc33c6dacdd6cb338b | 11,705 | c | C | fteqtv/bsp.c | BryanHaley/fteqw-applesilicon | 06714d400c13c3f50bcd03e3d2184648a71ddb29 | [
"Intel"
] | 1 | 2022-03-20T01:14:23.000Z | 2022-03-20T01:14:23.000Z | fteqtv/bsp.c | BryanHaley/fteqw-applesilicon | 06714d400c13c3f50bcd03e3d2184648a71ddb29 | [
"Intel"
] | null | null | null | fteqtv/bsp.c | BryanHaley/fteqw-applesilicon | 06714d400c13c3f50bcd03e3d2184648a71ddb29 | [
"Intel"
] | null | null | null | /*
Copyright (C) 1996-1997 Id Software, Inc.
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#include "qtv.h"
#define MAX_MAP_LEAFS 32767
typedef struct {
float planen[3];
float planedist;
int child[2];
} node_t;
struct bsp_s {
unsigned int fullchecksum;
unsigned int visedchecksum;
node_t *nodes;
unsigned char *pvslump;
unsigned char **pvsofs;
unsigned char decpvs[(MAX_MAP_LEAFS+7)/8]; //decompressed pvs
int pvsbytecount;
int numintermissionspots;
intermission_t intermissionspot[8];
};
static const intermission_t nullintermissionspot = {{0}};
typedef struct
{
int contents;
int visofs; // -1 = no visibility info
short mins[3]; // for frustum culling
short maxs[3];
unsigned short firstmarksurface;
unsigned short nummarksurfaces;
#define NUM_AMBIENTS 4
unsigned char ambient_level[NUM_AMBIENTS];
} dleaf_t;
typedef struct
{
unsigned int planenum;
short children[2]; // negative numbers are -(leafs+1), not nodes
short mins[3]; // for sphere culling
short maxs[3];
unsigned short firstface;
unsigned short numfaces; // counting both sides
} dnode_t;
typedef struct
{
float normal[3];
float dist;
unsigned int type; // PLANE_X - PLANE_ANYZ ?remove? trivial to regenerate
} dplane_t;
typedef struct
{
int fileofs, filelen;
} lump_t;
#define LUMP_ENTITIES 0
#define LUMP_PLANES 1
#define LUMP_VISIBILITY 4
#define LUMP_NODES 5
#define LUMP_LEAFS 10
#define HEADER_LUMPS 15
typedef struct
{
int version;
lump_t lumps[HEADER_LUMPS];
} dheader_t;
void DecompressVis(unsigned char *in, unsigned char *out, int bytecount)
{
int c;
unsigned char *end;
for (end = out + bytecount; out < end; )
{
c = *in;
if (!c)
{ //a 0 is always followed by the count of 0s.
c = in[1];
in += 2;
for (; c > 4; c-=4)
{
*(unsigned int*)out = 0;
out+=4;
}
for (; c; c--)
*out++ = 0;
}
else
{
in++;
*out++ = c;
}
}
}
void BSP_LoadEntities(bsp_t *bsp, char *entitydata)
{
char *v;
char key[2048];
char value[2048];
enum {et_random, et_startspot, et_primarystart, et_intermission} etype;
float org[3];
float angles[3];
qboolean foundstartspot = false;
float startspotorg[3];
float startspotangles[3];
//char *COM_ParseToken (char *data, char *out, int outsize, const char *punctuation)
while (entitydata)
{
entitydata = COM_ParseToken(entitydata, key, sizeof(key), NULL);
if (!entitydata)
break;
if (!strcmp(key, "{"))
{
org[0] = 0;
org[1] = 0;
org[2] = 0;
angles[0] = 0;
angles[1] = 0;
angles[2] = 0;
etype = et_random;
for(;;)
{
if(!entitydata)
{
printf("unexpected eof in bsp entities section\n");
return;
}
entitydata = COM_ParseToken(entitydata, key, sizeof(key), NULL);
if (!strcmp(key, "}"))
break;
entitydata = COM_ParseToken(entitydata, value, sizeof(value), NULL);
if (!strcmp(key, "origin"))
{
v = value;
v = COM_ParseToken(v, key, sizeof(key), NULL);
org[0] = atof(key);
v = COM_ParseToken(v, key, sizeof(key), NULL);
org[1] = atof(key);
v = COM_ParseToken(v, key, sizeof(key), NULL);
org[2] = atof(key);
}
if (!strcmp(key, "angles") || !strcmp(key, "angle") || !strcmp(key, "mangle"))
{
v = value;
v = COM_ParseToken(v, key, sizeof(key), NULL);
angles[0] = atof(key);
v = COM_ParseToken(v, key, sizeof(key), NULL);
if (v)
{
angles[1] = atof(key);
v = COM_ParseToken(v, key, sizeof(key), NULL);
angles[2] = atof(key);
}
else
{
angles[1] = angles[0];
angles[0] = 0;
angles[2] = 0;
}
}
if (!strcmp(key, "classname"))
{
if (!strcmp(value, "info_player_start"))
etype = et_primarystart;
if (!strcmp(value, "info_deathmatch_start"))
etype = et_startspot;
if (!strcmp(value, "info_intermission"))
etype = et_intermission;
}
}
switch (etype)
{
case et_random: //a random (unknown) entity
break;
case et_primarystart: //a single player start
memcpy(startspotorg, org, sizeof(startspotorg));
memcpy(startspotangles, angles, sizeof(startspotangles));
foundstartspot = true;
break;
case et_startspot:
if (!foundstartspot)
{
memcpy(startspotorg, org, sizeof(startspotorg));
memcpy(startspotangles, angles, sizeof(startspotangles));
foundstartspot = true;
}
break;
case et_intermission:
if (bsp->numintermissionspots < sizeof(bsp->intermissionspot)/sizeof(bsp->intermissionspot[0]))
{
bsp->intermissionspot[bsp->numintermissionspots].pos[0] = org[0];
bsp->intermissionspot[bsp->numintermissionspots].pos[1] = org[1];
bsp->intermissionspot[bsp->numintermissionspots].pos[2] = org[2];
bsp->intermissionspot[bsp->numintermissionspots].angle[0] = angles[0];
bsp->intermissionspot[bsp->numintermissionspots].angle[1] = angles[1];
bsp->intermissionspot[bsp->numintermissionspots].angle[2] = angles[2];
bsp->numintermissionspots++;
}
break;
}
}
else
{
printf("data not expected here\n");
return;
}
}
if (foundstartspot && !bsp->numintermissionspots)
{
bsp->intermissionspot[bsp->numintermissionspots].pos[0] = startspotorg[0];
bsp->intermissionspot[bsp->numintermissionspots].pos[1] = startspotorg[1];
bsp->intermissionspot[bsp->numintermissionspots].pos[2] = startspotorg[2];
bsp->intermissionspot[bsp->numintermissionspots].angle[0] = startspotangles[0];
bsp->intermissionspot[bsp->numintermissionspots].angle[1] = startspotangles[1];
bsp->intermissionspot[bsp->numintermissionspots].angle[2] = startspotangles[2];
bsp->numintermissionspots++;
}
}
bsp_t *BSP_LoadModel(cluster_t *cluster, char *gamedir, char *bspname)
{
unsigned char *data;
unsigned int size;
char *entdata;
dheader_t *header;
dplane_t *planes;
dnode_t *nodes;
dleaf_t *leaf;
int numnodes, i;
int numleafs;
unsigned int chksum;
bsp_t *bsp;
data = FS_ReadFile(gamedir, bspname, &size);
if (!data)
{
Sys_Printf(cluster, "Couldn't open bsp file \"%s\" (gamedir \"%s\")\n", bspname, gamedir);
return NULL;
}
header = (dheader_t*)data;
if (size < sizeof(dheader_t) || data[0] != 29)
{
free(data);
Sys_Printf(cluster, "BSP not version 29 (%s in %s)\n", bspname, gamedir);
return NULL;
}
for (i = 0; i < HEADER_LUMPS; i++)
{
if (LittleLong(header->lumps[i].fileofs) + LittleLong(header->lumps[i].filelen) > size)
{
free(data);
Sys_Printf(cluster, "BSP appears truncated (%s in gamedir %s)\n", bspname, gamedir);
return NULL;
}
}
planes = (dplane_t*)(data+LittleLong(header->lumps[LUMP_PLANES].fileofs));
nodes = (dnode_t*)(data+LittleLong(header->lumps[LUMP_NODES].fileofs));
leaf = (dleaf_t*)(data+LittleLong(header->lumps[LUMP_LEAFS].fileofs));
entdata = (char*)(data+LittleLong(header->lumps[LUMP_ENTITIES].fileofs));
numnodes = LittleLong(header->lumps[LUMP_NODES].filelen)/sizeof(dnode_t);
numleafs = LittleLong(header->lumps[LUMP_LEAFS].filelen)/sizeof(dleaf_t);
bsp = malloc(sizeof(bsp_t) + sizeof(node_t)*numnodes + LittleLong(header->lumps[LUMP_VISIBILITY].filelen) + sizeof(unsigned char *)*numleafs);
bsp->numintermissionspots = 0;
if (bsp)
{
bsp->fullchecksum = 0;
bsp->visedchecksum = 0;
for (i = 0; i < HEADER_LUMPS; i++)
{
if (i == LUMP_ENTITIES)
continue; //entities never appear in any checksums
chksum = Com_BlockChecksum(data + LittleLong(header->lumps[i].fileofs), LittleLong(header->lumps[i].filelen));
bsp->fullchecksum ^= chksum;
if (i == LUMP_VISIBILITY || i == LUMP_LEAFS || i == LUMP_NODES)
continue;
bsp->visedchecksum ^= chksum;
}
bsp->nodes = (node_t*)(bsp+1);
bsp->pvsofs = (unsigned char**)(bsp->nodes+numnodes);
bsp->pvslump = (unsigned char*)(bsp->pvsofs+numleafs);
bsp->pvsbytecount = (numleafs+7)/8;
for (i = 0; i < numnodes; i++)
{
bsp->nodes[i].child[0] = LittleShort(nodes[i].children[0]);
bsp->nodes[i].child[1] = LittleShort(nodes[i].children[1]);
bsp->nodes[i].planedist = planes[LittleLong(nodes[i].planenum)].dist;
bsp->nodes[i].planen[0] = planes[LittleLong(nodes[i].planenum)].normal[0];
bsp->nodes[i].planen[1] = planes[LittleLong(nodes[i].planenum)].normal[1];
bsp->nodes[i].planen[2] = planes[LittleLong(nodes[i].planenum)].normal[2];
}
memcpy(bsp->pvslump, data+LittleLong(header->lumps[LUMP_VISIBILITY].fileofs), LittleLong(header->lumps[LUMP_VISIBILITY].filelen));
for (i = 0; i < numleafs; i++)
{
if (leaf[i].visofs < 0)
bsp->pvsofs[i] = NULL;
else
bsp->pvsofs[i] = bsp->pvslump+leaf[i].visofs;
}
}
BSP_LoadEntities(bsp, entdata);
free(data);
return bsp;
}
void BSP_Free(bsp_t *bsp)
{
free(bsp);
}
int BSP_SphereLeafNums_r(bsp_t *bsp, int first, int maxleafs, unsigned short *list, float *pos, float radius)
{
node_t *node;
float dot;
int rn;
int numleafs = 0;
if (!bsp)
return 0;
for(rn = first;rn >= 0;)
{
node = &bsp->nodes[rn];
dot = (node->planen[0]*pos[0] + node->planen[1]*pos[1] + node->planen[2]*pos[2]) - node->planedist;
if (dot < -radius)
rn = node->child[1];
else if (dot > radius)
rn = node->child[0];
else
{
rn = BSP_SphereLeafNums_r(bsp, node->child[0], maxleafs-numleafs, list+numleafs, pos, radius);
if (rn < 0)
return -1; //ran out, so don't use pvs for this entity.
else
numleafs += rn;
rn = node->child[1]; //both sides
}
}
rn = -1-rn;
if (rn <= 0)
; //leaf 0 has no pvs info, so don't add it.
else if (maxleafs>numleafs)
{
list[numleafs] = rn-1;
numleafs++;
}
else
return -1; //there are just too many
return numleafs;
}
unsigned int BSP_Checksum(bsp_t *bsp)
{
if (!bsp)
return 0;
return bsp->visedchecksum;
}
int BSP_SphereLeafNums(bsp_t *bsp, int maxleafs, unsigned short *list, float x, float y, float z, float radius)
{
float pos[3];
pos[0] = x;
pos[1] = y;
pos[2] = z;
return BSP_SphereLeafNums_r(bsp, 0, maxleafs, list, pos, radius);
}
int BSP_LeafNum(bsp_t *bsp, float x, float y, float z)
{
node_t *node;
float dot;
int rn;
if (!bsp)
return 0;
for(rn = 0;rn >= 0;)
{
node = &bsp->nodes[rn];
dot = node->planen[0]*x + node->planen[1]*y + node->planen[2]*z;
rn = node->child[(dot-node->planedist) <= 0];
}
return -1-rn;
}
qboolean BSP_Visible(bsp_t *bsp, int leafcount, unsigned short *list)
{
int i;
if (!bsp)
return true;
if (leafcount < 0) //too many, so pvs was switched off.
return true;
for (i = 0; i < leafcount; i++)
{
if (bsp->decpvs[list[i]>>3] & (1<<(list[i]&7)))
return true;
}
return false;
}
void BSP_SetupForPosition(bsp_t *bsp, float x, float y, float z)
{
int leafnum;
if (!bsp)
return;
leafnum = BSP_LeafNum(bsp, x, y, z);
DecompressVis(bsp->pvsofs[leafnum], bsp->decpvs, bsp->pvsbytecount);
}
const intermission_t *BSP_IntermissionSpot(bsp_t *bsp)
{
int spotnum;
if (bsp)
{
if (bsp->numintermissionspots>0)
{
spotnum = rand()%bsp->numintermissionspots;
return &bsp->intermissionspot[spotnum];
}
}
return &nullintermissionspot;
}
| 23.742394 | 143 | 0.658095 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.