blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 4
721
| content_id
stringlengths 40
40
| detected_licenses
listlengths 0
57
| license_type
stringclasses 2
values | repo_name
stringlengths 5
91
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringclasses 321
values | visit_date
timestamp[ns]date 2016-08-12 09:31:09
2023-09-06 10:45:07
| revision_date
timestamp[ns]date 2010-09-28 14:01:40
2023-09-06 06:22:19
| committer_date
timestamp[ns]date 2010-09-28 14:01:40
2023-09-06 06:22:19
| github_id
int64 426
681M
| star_events_count
int64 101
243k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 23
values | gha_event_created_at
timestamp[ns]date 2012-06-28 18:51:49
2023-09-14 21:59:16
⌀ | gha_created_at
timestamp[ns]date 2008-02-11 22:55:26
2023-08-10 11:14:58
⌀ | gha_language
stringclasses 147
values | src_encoding
stringclasses 26
values | language
stringclasses 2
values | is_vendor
bool 2
classes | is_generated
bool 2
classes | length_bytes
int64 6
10.2M
| extension
stringclasses 115
values | filename
stringlengths 3
113
| content
stringlengths 6
10.2M
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
aeae81e7188660483b0a4a7428bf4f1e126b0ad1
|
5ab69c8644a936a3d9dec1669a86c7369c911bf8
|
/os/storage/antelope/lvm.c
|
7abed8d278375299d358e8dc7c1f88c446068e91
|
[
"BSD-3-Clause"
] |
permissive
|
contiki-ng/contiki-ng
|
393d36f68b98f5ee3544ea32502cf662ffb2fe9f
|
31fcaadf7a0dc8ceea07f438cd69db73174879e6
|
refs/heads/develop
| 2023-09-01T20:10:30.000765
| 2023-09-01T14:37:12
| 2023-09-01T14:37:12
| 91,191,972
| 1,242
| 788
|
BSD-3-Clause
| 2023-09-14T19:08:35
| 2017-05-13T17:37:59
|
C
|
UTF-8
|
C
| false
| false
| 22,794
|
c
|
lvm.c
|
/*
* Copyright (c) 2010, Swedish Institute of Computer Science
* 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 Institute 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 INSTITUTE 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 INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
/**
* \file
* Logic engine used for quickly evaluating data constraints in relations.
* \author
* Nicolas Tsiftes <nvt@sics.se>
*/
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "aql.h"
#include "lvm.h"
#define DEBUG DEBUG_NONE
#include "debug.h"
/*
* The logic engine determines whether a logical predicate is true for
* each tuple in a relation. It uses a stack-based execution model of
* operations that are arranged in prefix (Polish) notation.
*/
/* Default option values. */
#ifndef LVM_MAX_NAME_LENGTH
#define LVM_MAX_NAME_LENGTH 16
#endif
#ifndef LVM_MAX_VARIABLE_ID
#define LVM_MAX_VARIABLE_ID 8
#endif
#ifndef LVM_USE_FLOATS
#define LVM_USE_FLOATS 0
#endif
#define IS_CONNECTIVE(op) ((op) & LVM_CONNECTIVE)
struct variable {
operand_type_t type;
operand_value_t value;
char name[LVM_MAX_NAME_LENGTH + 1];
};
typedef struct variable variable_t;
struct derivation {
operand_value_t max;
operand_value_t min;
uint8_t derived;
};
typedef struct derivation derivation_t;
/* Registered variables for a LVM expression. Their values may be
changed between executions of the expression. */
static variable_t variables[LVM_MAX_VARIABLE_ID];
/* Range derivations of variables that are used for index searches. */
static derivation_t derivations[LVM_MAX_VARIABLE_ID];
#if DEBUG
static void
print_derivations(derivation_t *d)
{
int i;
for(i = 0; i < LVM_MAX_VARIABLE_ID; i++) {
if(d[i].derived) {
printf("%s is constrained to (%ld,%ld)\n", variables[i].name,
d[i].min.l, d[i].max.l);
}
}
}
#endif /* DEBUG */
static variable_id_t
lookup(char *name)
{
variable_t *var;
for(var = variables; var <= &variables[LVM_MAX_VARIABLE_ID - 1] && var->name[0] != '\0'; var++) {
if(strcmp(var->name, name) == 0) {
break;
}
}
return (variable_id_t)(var - &variables[0]);
}
static operator_t *
get_operator(lvm_instance_t *p)
{
operator_t *operator;
operator = (operator_t *)&p->code[p->ip];
p->ip += sizeof(operator_t);
return operator;
}
static void
get_operand(lvm_instance_t *p, operand_t *operand)
{
memcpy(operand, &p->code[p->ip], sizeof(*operand));
p->ip += sizeof(*operand);
}
static node_type_t
get_type(lvm_instance_t *p)
{
node_type_t node_type;
node_type = *(node_type_t *)(p->code + p->ip);
p->ip += sizeof(node_type);
return node_type;
}
static long
operand_to_long(operand_t *operand)
{
switch(operand->type) {
case LVM_LONG:
return operand->value.l;
#if LVM_USE_FLOATS
case LVM_FLOAT:
return (long)operand->value.f;
break;
#endif /* LVM_USE_FLOATS */
case LVM_VARIABLE:
return variables[operand->value.id].value.l;
default:
return 0;
}
}
static lvm_status_t
eval_expr(lvm_instance_t *p, operator_t op, operand_t *result)
{
int i;
node_type_t type;
operator_t *operator;
operand_t operand[2];
long value[2];
long result_value;
lvm_status_t r;
for(i = 0; i < 2; i++) {
type = get_type(p);
switch(type) {
case LVM_ARITH_OP:
operator = get_operator(p);
r = eval_expr(p, *operator, &operand[i]);
if(LVM_ERROR(r)) {
return r;
}
break;
case LVM_OPERAND:
get_operand(p, &operand[i]);
break;
default:
return LVM_SEMANTIC_ERROR;
}
value[i] = operand_to_long(&operand[i]);
}
switch(op) {
case LVM_ADD:
result_value = value[0] + value[1];
break;
case LVM_SUB:
result_value = value[0] - value[1];
break;
case LVM_MUL:
result_value = value[0] * value[1];
break;
case LVM_DIV:
if(value[1] == 0) {
return LVM_MATH_ERROR;
}
result_value = value[0] / value[1];
break;
default:
return LVM_EXECUTION_ERROR;
}
result->type = LVM_LONG;
result->value.l = result_value;
return LVM_TRUE;
}
static int
eval_logic(lvm_instance_t *p, operator_t *op)
{
int i;
int r;
operand_t operand;
long result[2];
node_type_t type;
operator_t *operator;
long l1, l2;
int logic_result[2];
unsigned arguments;
if(IS_CONNECTIVE(*op)) {
arguments = *op == LVM_NOT ? 1 : 2;
for(i = 0; i < arguments; i++) {
type = get_type(p);
if(type != LVM_CMP_OP) {
return LVM_SEMANTIC_ERROR;
}
operator = get_operator(p);
logic_result[i] = eval_logic(p, operator);
if(LVM_ERROR(logic_result[i])) {
return logic_result[i];
}
}
if(*op == LVM_NOT) {
return !logic_result[0];
} else if(*op == LVM_AND) {
return logic_result[0] == LVM_TRUE && logic_result[1] == LVM_TRUE;
} else {
return logic_result[0] == LVM_TRUE || logic_result[1] == LVM_TRUE;
}
}
for(i = 0; i < 2; i++) {
type = get_type(p);
switch(type) {
case LVM_ARITH_OP:
operator = get_operator(p);
r = eval_expr(p, *operator, &operand);
if(LVM_ERROR(r)) {
return r;
}
break;
case LVM_OPERAND:
get_operand(p, &operand);
break;
default:
return LVM_SEMANTIC_ERROR;
}
result[i] = operand_to_long(&operand);
}
l1 = result[0];
l2 = result[1];
PRINTF("Result1: %ld\nResult2: %ld\n", l1, l2);
switch(*op) {
case LVM_EQ:
return l1 == l2;
case LVM_NEQ:
return l1 != l2;
case LVM_GE:
return l1 > l2;
case LVM_GEQ:
return l1 >= l2;
case LVM_LE:
return l1 < l2;
case LVM_LEQ:
return l1 <= l2;
default:
break;
}
return LVM_EXECUTION_ERROR;
}
void
lvm_reset(lvm_instance_t *p, unsigned char *code, lvm_ip_t size)
{
memset(code, 0, size);
p->code = code;
p->size = size;
p->end = 0;
p->ip = 0;
p->error = 0;
memset(variables, 0, sizeof(variables));
memset(derivations, 0, sizeof(derivations));
}
lvm_ip_t
lvm_jump_to_operand(lvm_instance_t *p)
{
lvm_ip_t old_end;
old_end = p->end;
p->end += sizeof(operator_t) + sizeof(node_type_t);
if(p->end >= p->size) {
p->error = __LINE__;
p->end = old_end;
}
return old_end;
}
lvm_ip_t
lvm_shift_for_operator(lvm_instance_t *p, lvm_ip_t end)
{
unsigned char *ptr;
lvm_ip_t old_end;
old_end = p->end;
if(p->end + sizeof(operator_t) + sizeof(node_type_t) > p->size ||
end >= old_end) {
p->error = __LINE__;
return 0;
}
ptr = p->code + end;
memmove(ptr + sizeof(operator_t) + sizeof(node_type_t), ptr, old_end - end);
p->end = end;
return old_end + sizeof(operator_t) + sizeof(node_type_t);
}
lvm_ip_t
lvm_get_end(lvm_instance_t *p)
{
return p->end;
}
lvm_ip_t
lvm_set_end(lvm_instance_t *p, lvm_ip_t end)
{
lvm_ip_t old_end;
if(end >= p->size) {
p->error = __LINE__;
return p->end;
}
old_end = p->end;
p->end = end;
return old_end;
}
lvm_status_t
lvm_execute(lvm_instance_t *p)
{
node_type_t type;
operator_t *operator;
lvm_status_t status;
p->ip = 0;
status = LVM_EXECUTION_ERROR;
type = get_type(p);
switch(type) {
case LVM_CMP_OP:
operator = get_operator(p);
status = eval_logic(p, operator);
if(!LVM_ERROR(status)) {
PRINTF("The statement is %s\n", status == LVM_TRUE ? "true" : "false");
} else {
PRINTF("Execution error: %d\n", (int)status);
}
break;
default:
PRINTF("Error: The code must start with a relational operator\n");
}
return status;
}
lvm_status_t
lvm_set_type(lvm_instance_t *p, node_type_t type)
{
if(p->end + sizeof(node_type_t) >= DB_VM_BYTECODE_SIZE) {
PRINTF("Error: overflow in lvm_set_type\n");
return LVM_STACK_OVERFLOW;
}
*(node_type_t *)(p->code + p->end) = type;
p->end += sizeof(type);
return LVM_TRUE;
}
lvm_status_t
lvm_set_op(lvm_instance_t *p, operator_t op)
{
lvm_status_t status;
status = lvm_set_type(p, LVM_ARITH_OP);
if(status != LVM_TRUE) {
return status;
}
if(p->end + sizeof(op) >= DB_VM_BYTECODE_SIZE) {
PRINTF("Error: overflow in lvm_set_op\n");
return LVM_STACK_OVERFLOW;
}
memcpy(&p->code[p->end], &op, sizeof(op));
p->end += sizeof(op);
return LVM_TRUE;
}
lvm_status_t
lvm_set_relation(lvm_instance_t *p, operator_t op)
{
lvm_status_t status;
status = lvm_set_type(p, LVM_CMP_OP);
if(status != LVM_TRUE) {
return status;
}
if(p->end + sizeof(op) >= DB_VM_BYTECODE_SIZE) {
PRINTF("Error: overflow in lvm_set_relation\n");
return LVM_STACK_OVERFLOW;
}
memcpy(&p->code[p->end], &op, sizeof(op));
p->end += sizeof(op);
return LVM_TRUE;
}
lvm_status_t
lvm_set_operand(lvm_instance_t *p, operand_t *op)
{
lvm_status_t status;
status = lvm_set_type(p, LVM_OPERAND);
if(status != LVM_TRUE) {
return status;
}
if(p->end + sizeof(*op) >= DB_VM_BYTECODE_SIZE) {
PRINTF("Error: overflow in lvm_set_operand\n");
return LVM_STACK_OVERFLOW;
}
memcpy(&p->code[p->end], op, sizeof(*op));
p->end += sizeof(*op);
return LVM_TRUE;
}
lvm_status_t
lvm_set_long(lvm_instance_t *p, long l)
{
operand_t op;
op.type = LVM_LONG;
op.value.l = l;
return lvm_set_operand(p, &op);
}
lvm_status_t
lvm_register_variable(char *name, operand_type_t type)
{
variable_id_t id;
variable_t *var;
id = lookup(name);
if(id == LVM_MAX_VARIABLE_ID) {
return LVM_VARIABLE_LIMIT_REACHED;
}
var = &variables[id];
if(var->name[0] == '\0') {
strncpy(var->name, name, sizeof(var->name) - 1);
var->name[sizeof(var->name) - 1] = '\0';
var->type = type;
}
return LVM_TRUE;
}
lvm_status_t
lvm_set_variable_value(char *name, operand_value_t value)
{
variable_id_t id;
id = lookup(name);
if(id == LVM_MAX_VARIABLE_ID) {
return LVM_INVALID_IDENTIFIER;
}
variables[id].value = value;
return LVM_TRUE;
}
lvm_status_t
lvm_set_variable(lvm_instance_t *p, char *name)
{
operand_t op;
variable_id_t id;
id = lookup(name);
if(id == LVM_MAX_VARIABLE_ID) {
return LVM_INVALID_IDENTIFIER;
}
PRINTF("var id = %d\n", id);
op.type = LVM_VARIABLE;
op.value.id = id;
return lvm_set_operand(p, &op);
}
void
lvm_clone(lvm_instance_t *dst, lvm_instance_t *src)
{
memcpy(dst, src, sizeof(*dst));
}
static void
create_intersection(derivation_t *result, derivation_t *d1, derivation_t *d2)
{
int i;
for(i = 0; i < LVM_MAX_VARIABLE_ID; i++) {
if(!d1[i].derived && !d2[i].derived) {
continue;
} else if(d1[i].derived && !d2[i].derived) {
result[i].min.l = d1[i].min.l;
result[i].max.l = d1[i].max.l;
} else if(!d1[i].derived && d2[i].derived) {
result[i].min.l = d2[i].min.l;
result[i].max.l = d2[i].max.l;
} else {
/* Both derivations have been made; create an
intersection of the ranges. */
if(d1[i].min.l > d2[i].min.l) {
result[i].min.l = d1[i].min.l;
} else {
result[i].min.l = d2[i].min.l;
}
if(d1[i].max.l < d2[i].max.l) {
result[i].max.l = d1[i].max.l;
} else {
result[i].max.l = d2[i].max.l;
}
}
result[i].derived = 1;
}
#if DEBUG
PRINTF("Created an intersection of D1 and D2\n");
PRINTF("D1: \n");
print_derivations(d1);
PRINTF("D2: \n");
print_derivations(d2);
PRINTF("Result: \n");
print_derivations(result);
#endif /* DEBUG */
}
static void
create_union(derivation_t *result, derivation_t *d1, derivation_t *d2)
{
int i;
for(i = 0; i < LVM_MAX_VARIABLE_ID; i++) {
if(!d1[i].derived && !d2[i].derived) {
continue;
} else if(d1[i].derived && !d2[i].derived) {
result[i].min.l = d1[i].min.l;
result[i].max.l = d1[i].max.l;
} else if(!d1[i].derived && d2[i].derived) {
result[i].min.l = d2[i].min.l;
result[i].max.l = d2[i].max.l;
} else {
/* Both derivations have been made; create a
union of the ranges. */
if(d1[i].min.l > d2[i].min.l) {
result[i].min.l = d2[i].min.l;
} else {
result[i].min.l = d1[i].min.l;
}
if(d1[i].max.l < d2[i].max.l) {
result[i].max.l = d2[i].max.l;
} else {
result[i].max.l = d1[i].max.l;
}
}
result[i].derived = 1;
}
#if DEBUG
PRINTF("Created a union of D1 and D2\n");
PRINTF("D1: \n");
print_derivations(d1);
PRINTF("D2: \n");
print_derivations(d2);
PRINTF("Result: \n");
print_derivations(result);
#endif /* DEBUG */
}
static int
derive_relation(lvm_instance_t *p, derivation_t *local_derivations)
{
operator_t *operator;
node_type_t type;
operand_t operand[2];
int i;
int variable_id;
operand_value_t *value;
derivation_t *derivation;
type = get_type(p);
operator = get_operator(p);
if(IS_CONNECTIVE(*operator)) {
derivation_t d1[LVM_MAX_VARIABLE_ID];
derivation_t d2[LVM_MAX_VARIABLE_ID];
if(*operator != LVM_AND && *operator != LVM_OR) {
return LVM_DERIVATION_ERROR;
}
PRINTF("Attempting to infer ranges from a logical connective\n");
memset(d1, 0, sizeof(d1));
memset(d2, 0, sizeof(d2));
if(LVM_ERROR(derive_relation(p, d1)) ||
LVM_ERROR(derive_relation(p, d2))) {
return LVM_DERIVATION_ERROR;
}
if(*operator == LVM_AND) {
create_intersection(local_derivations, d1, d2);
} else if(*operator == LVM_OR) {
create_union(local_derivations, d1, d2);
}
return LVM_TRUE;
}
for(i = 0; i < 2; i++) {
type = get_type(p);
switch(type) {
case LVM_OPERAND:
get_operand(p, &operand[i]);
break;
default:
return LVM_DERIVATION_ERROR;
}
}
if(operand[0].type == LVM_VARIABLE && operand[1].type == LVM_VARIABLE) {
return LVM_DERIVATION_ERROR;
}
/* Determine which of the operands that is the variable. */
if(operand[0].type == LVM_VARIABLE) {
if(operand[1].type == LVM_VARIABLE) {
return LVM_DERIVATION_ERROR;
}
variable_id = operand[0].value.id;
value = &operand[1].value;
} else {
variable_id = operand[1].value.id;
value = &operand[0].value;
}
if(variable_id >= LVM_MAX_VARIABLE_ID) {
return LVM_DERIVATION_ERROR;
}
PRINTF("variable id %d, value %ld\n", variable_id, *(long *)value);
derivation = local_derivations + variable_id;
/* Default values. */
derivation->max.l = LONG_MAX;
derivation->min.l = LONG_MIN;
switch(*operator) {
case LVM_EQ:
derivation->max = *value;
derivation->min = *value;
break;
case LVM_GE:
derivation->min.l = value->l + 1;
break;
case LVM_GEQ:
derivation->min.l = value->l;
break;
case LVM_LE:
derivation->max.l = value->l - 1;
break;
case LVM_LEQ:
derivation->max.l = value->l;
break;
default:
return LVM_DERIVATION_ERROR;
}
derivation->derived = 1;
return LVM_TRUE;
}
lvm_status_t
lvm_derive(lvm_instance_t *p)
{
return derive_relation(p, derivations);
}
lvm_status_t
lvm_get_derived_range(lvm_instance_t *p, char *name,
operand_value_t *min, operand_value_t *max)
{
int i;
for(i = 0; i < LVM_MAX_VARIABLE_ID; i++) {
if(strcmp(name, variables[i].name) == 0) {
if(derivations[i].derived) {
*min = derivations[i].min;
*max = derivations[i].max;
return LVM_TRUE;
}
return LVM_DERIVATION_ERROR;
}
}
return LVM_INVALID_IDENTIFIER;
}
#if DEBUG
static lvm_ip_t
print_operator(lvm_instance_t *p, lvm_ip_t index)
{
operator_t operator;
struct operator_map {
operator_t op;
char *representation;
};
struct operator_map operator_map[] = {
{LVM_ADD, "+"},
{LVM_SUB, "-"},
{LVM_MUL, "*"},
{LVM_DIV, "/"},
{LVM_GE, ">"},
{LVM_GEQ, ">="},
{LVM_LE, "<"},
{LVM_LEQ, "<="},
{LVM_EQ, "="},
{LVM_NEQ, "<>"},
{LVM_AND, "/\\"},
{LVM_OR, "\\/"},
{LVM_NOT, "!"}
};
int i;
memcpy(&operator, p->code + index, sizeof(operator));
for(i = 0; i < sizeof(operator_map) / sizeof(operator_map[0]); i++) {
if(operator_map[i].op == operator) {
PRINTF("%s ", operator_map[i].representation);
break;
}
}
return index + sizeof(operator_t);
}
static lvm_ip_t
print_operand(lvm_instance_t *p, lvm_ip_t index)
{
operand_t operand;
memcpy(&operand, p->code + index, sizeof(operand));
switch(operand.type) {
case LVM_VARIABLE:
if(operand.value.id >= LVM_MAX_VARIABLE_ID ||
variables[operand.value.id].name == NULL) {
PRINTF("var(id:%d):?? ", operand.value.id);
} else {
PRINTF("var(%s):%ld ", variables[operand.value.id].name,
variables[operand.value.id].value.l);
}
break;
case LVM_LONG:
PRINTF("long:%ld ", operand.value.l);
break;
default:
PRINTF("?? ");
break;
}
return index + sizeof(operand_t);
}
static lvm_ip_t
print_relation(lvm_instance_t *p, lvm_ip_t index)
{
/* Relational operators are stored as ordinary operators. */
return print_operator(p, index);
}
#endif /* DEBUG */
void
lvm_print_code(lvm_instance_t *p)
{
#if DEBUG
lvm_ip_t ip;
PRINTF("Code: ");
for(ip = 0; ip < p->end;) {
switch(*(node_type_t *)(p->code + ip)) {
case LVM_CMP_OP:
ip = print_relation(p, ip + sizeof(node_type_t));
break;
case LVM_ARITH_OP:
ip = print_operator(p, ip + sizeof(node_type_t));
break;
case LVM_OPERAND:
ip = print_operand(p, ip + sizeof(node_type_t));
break;
default:
PRINTF("Invalid opcode: 0x%x ", p->code[ip]);
ip = p->end;
break;
}
}
putchar('\n');
#endif
}
void
lvm_print_derivations(lvm_instance_t *p)
{
#if DEBUG
print_derivations(derivations);
#endif /* DEBUG */
}
#ifdef TEST
int
main(void)
{
lvm_instance_t p;
unsigned char code[256];
lvm_reset(&p, code, sizeof(code));
lvm_register_variable("z", LVM_LONG);
lvm_set_variable_value("z", (operand_value_t)15L);
lvm_register_variable("y", LVM_LONG);
lvm_set_variable_value("y", (operand_value_t)109L);
/* Infix: 109 = y /\ 20 > 70 - (6 + z * 3) => 109 = 109 /\ 20 > 19 => true */
lvm_set_relation(&p, LVM_AND);
lvm_set_relation(&p, LVM_EQ);
lvm_set_long(&p, 109);
lvm_set_variable(&p, "y");
lvm_set_relation(&p, LVM_GE);
lvm_set_long(&p, 20);
lvm_set_op(&p, LVM_SUB);
lvm_set_long(&p, 70);
lvm_set_op(&p, LVM_ADD);
lvm_set_long(&p, 6);
lvm_set_op(&p, LVM_MUL);
lvm_set_variable(&p, "z");
lvm_set_long(&p, 3);
lvm_print_code(&p);
lvm_execute(&p);
/* Infix: !(9999 + 1 < -1 + 10001) => !(10000 < 10000) => true */
lvm_reset(&p, code, sizeof(code));
lvm_set_relation(&p, LVM_NOT);
lvm_set_relation(&p, LVM_LE);
lvm_set_op(&p, LVM_ADD);
lvm_set_long(&p, 9999);
lvm_set_long(&p, 1);
lvm_set_op(&p, LVM_ADD);
lvm_set_long(&p, -1);
lvm_set_long(&p, 10001);
lvm_print_code(&p);
lvm_execute(&p);
/* Derivation tests */
/* Infix: a = 5 => a:(5,5) */
lvm_reset(&p, code, sizeof(code));
lvm_register_variable("a", LVM_LONG);
lvm_set_relation(&p, LVM_EQ);
lvm_set_variable(&p, "a");
lvm_set_long(&p, 5);
lvm_derive(&p);
lvm_print_derivations(&p);
/* Infix: a < 10 => a:(-oo,9) */
lvm_reset(&p, code, sizeof(code));
lvm_register_variable("a", LVM_LONG);
lvm_set_relation(&p, LVM_LE);
lvm_set_variable(&p, "a");
lvm_set_long(&p, 10);
lvm_derive(&p);
lvm_print_derivations(&p);
/* Infix: a < 100 /\ 10 < a => a:(11,99) */
lvm_reset(&p, code, sizeof(code));
lvm_register_variable("a", LVM_LONG);
lvm_set_relation(&p, LVM_AND);
lvm_set_relation(&p, LVM_LE);
lvm_set_variable(&p, "a");
lvm_set_long(&p, 100);
lvm_set_relation(&p, LVM_GE);
lvm_set_long(&p, 10);
lvm_set_variable(&p, "a");
lvm_derive(&p);
lvm_print_derivations(&p);
/* Infix: a < 100 /\ b > 100 => a:(-oo,99), b:(101,oo) */
lvm_reset(&p, code, sizeof(code));
lvm_register_variable("a", LVM_LONG);
lvm_register_variable("b", LVM_LONG);
lvm_set_relation(&p, LVM_AND);
lvm_set_relation(&p, LVM_LE);
lvm_set_variable(&p, "a");
lvm_set_long(&p, 100);
lvm_set_relation(&p, LVM_GE);
lvm_set_variable(&p, "b");
lvm_set_long(&p, 100);
lvm_derive(&p);
lvm_print_derivations(&p);
/* Infix: a < 100 \/ a < 1000 \/ a < 1902 => a:(-oo,1901) */
lvm_reset(&p, code, sizeof(code));
lvm_register_variable("a", LVM_LONG);
lvm_set_relation(&p, LVM_OR);
lvm_set_relation(&p, LVM_LE);
lvm_set_variable(&p, "a");
lvm_set_long(&p, 100);
lvm_set_relation(&p, LVM_OR);
lvm_set_relation(&p, LVM_LE);
lvm_set_long(&p, 1000);
lvm_set_variable(&p, "a");
lvm_set_relation(&p, LVM_LE);
lvm_set_variable(&p, "a");
lvm_set_long(&p, 1902);
lvm_derive(&p);
lvm_print_derivations(&p);
/* Infix: (a < 100 /\ a < 90 /\ a > 80 /\ a < 105) \/ b > 10000 =>
a:(81,89), b:(10001:oo) */
lvm_reset(&p, code, sizeof(code));
lvm_register_variable("a", LVM_LONG);
lvm_register_variable("b", LVM_LONG);
lvm_set_relation(&p, LVM_OR);
lvm_set_relation(&p, LVM_GE);
lvm_set_variable(&p, "b");
lvm_set_long(&p, 10000);
lvm_set_relation(&p, LVM_AND);
lvm_set_relation(&p, LVM_LE);
lvm_set_variable(&p, "a");
lvm_set_long(&p, 100);
lvm_set_relation(&p, LVM_AND);
lvm_set_relation(&p, LVM_LE);
lvm_set_variable(&p, "a");
lvm_set_long(&p, 90);
lvm_set_relation(&p, LVM_AND);
lvm_set_relation(&p, LVM_GE);
lvm_set_variable(&p, "a");
lvm_set_long(&p, 80);
lvm_set_relation(&p, LVM_LE);
lvm_set_variable(&p, "a");
lvm_set_long(&p, 105);
lvm_derive(&p);
lvm_print_derivations(&p);
printf("Done\n");
return 0;
}
#endif
|
ac8d9934f0084afcb080a381a4c24fde696b7784
|
e73547787354afd9b717ea57fe8dd0695d161821
|
/src/entity/model/Hammer3Block.c
|
60d9deb4941202602261995f5fb02d3e67dd3066
|
[] |
no_license
|
pmret/papermario
|
8b514b19653cef8d6145e47499b3636b8c474a37
|
9774b26d93f1045dd2a67e502b6efc9599fb6c31
|
refs/heads/main
| 2023-08-31T07:09:48.951514
| 2023-08-21T18:07:08
| 2023-08-21T18:07:08
| 287,151,133
| 904
| 139
| null | 2023-09-14T02:44:23
| 2020-08-13T01:22:57
|
C
|
UTF-8
|
C
| false
| false
| 1,741
|
c
|
Hammer3Block.c
|
#include "common.h"
#include "entity/model/Hammer3Block.vtx.inc.c"
#include "entity/model/Hammer3Block_face.png.inc.c"
#include "entity/model/Hammer3Block_face.pal.inc.c"
Gfx Entity_Hammer3Block_LoadTexture[] = {
gsDPSetTextureLUT(G_TT_RGBA16),
gsDPLoadTLUT_pal16(0, D_0A000380_E322B0),
gsSPTexture(0xFFFF, 0xFFFF, 0, G_TX_RENDERTILE, G_ON),
gsDPSetTextureDetail(G_TD_CLAMP),
gsDPSetTextureLOD(G_TL_TILE),
gsDPLoadTextureBlock_4b(D_0A000280_E321B0, G_IM_FMT_CI, 16, 32, 0, G_TX_MIRROR | G_TX_WRAP, G_TX_NOMIRROR | G_TX_CLAMP, 4, 5, G_TX_NOLOD, G_TX_NOLOD),
gsDPSetTexturePersp(G_TP_PERSP),
gsDPSetTextureFilter(G_TF_BILERP),
gsSPEndDisplayList(),
};
Gfx Entity_Hammer3Block_RenderBlock[] = {
gsDPPipeSync(),
gsSPDisplayList(Entity_Hammer3Block_LoadTexture),
gsSPClearGeometryMode(G_LIGHTING),
gsSPVertex(D_0A000000_E31F30, 30, 0),
gsSP2Triangles(0, 1, 2, 0, 0, 2, 3, 0),
gsSP2Triangles(4, 0, 3, 0, 4, 3, 5, 0),
gsSP2Triangles(6, 7, 8, 0, 6, 8, 9, 0),
gsSP2Triangles(10, 11, 12, 0, 10, 12, 13, 0),
gsSP2Triangles(14, 15, 16, 0, 14, 16, 17, 0),
gsSP2Triangles(16, 18, 19, 0, 16, 19, 17, 0),
gsSP2Triangles(18, 20, 21, 0, 18, 21, 19, 0),
gsSP2Triangles(22, 23, 4, 0, 22, 4, 5, 0),
gsSP2Triangles(24, 25, 26, 0, 24, 26, 27, 0),
gsSP2Triangles(26, 28, 29, 0, 26, 29, 27, 0),
gsSPVertex(&D_0A000000_E31F30[28], 12, 0),
gsSP2Triangles(0, 2, 6, 0, 0, 6, 1, 0),
gsSP2Triangles(3, 7, 4, 0, 3, 4, 8, 0),
gsSP2Triangles(4, 5, 9, 0, 4, 9, 8, 0),
gsSP2Triangles(5, 10, 11, 0, 5, 11, 9, 0),
gsSPEndDisplayList(),
};
Gfx Entity_Hammer3Block_Render[] = {
gsSPDisplayList(Entity_Hammer3Block_RenderBlock),
gsSPEndDisplayList(),
};
|
18681e81b45d3deb2eb3d610c819186c369fa8c2
|
2898fa4f2ad766afa0495a837f59fe95daa081a7
|
/tests/unit-pass/brace-init-7.C
|
a5c37fb4ced7cb20775e6f974f00a98597c4eed0
|
[
"NCSA"
] |
permissive
|
kframework/c-semantics
|
12fcc1b1bf1f7792636d1c37f6f7bb1b89a392b5
|
e6879d14455771aa0cb3e3d201131d4d763a73a2
|
refs/heads/master
| 2023-07-31T23:57:03.316456
| 2022-02-01T17:50:31
| 2022-02-01T17:50:31
| 11,747,541
| 312
| 52
|
NOASSERTION
| 2022-02-01T17:50:33
| 2013-07-29T19:13:25
|
C
|
UTF-8
|
C
| false
| false
| 73
|
c
|
brace-init-7.C
|
struct Y {int x, y; };
Y x = {1, 2};
int main() {
return x.y - 2*x.x;
}
|
93fb4d62a8887733feee6ddaf9d9ea80961b21d4
|
a3cf3ed7895b6168fe0864770f944d0a25d5ad74
|
/src/libre/class/utf8_Arabic.c
|
360564ea38c348793c5bfb40405554423ac1f2ff
|
[
"BSD-2-Clause"
] |
permissive
|
katef/libfsm
|
32269415d8ab61778bef9bfdb3c14c61117216d4
|
479d103357f4e1a8596437895bbc6ddf237a1da0
|
refs/heads/main
| 2023-08-12T06:21:35.611111
| 2023-06-03T22:17:25
| 2023-06-15T20:40:54
| 80,573,145
| 918
| 66
|
BSD-2-Clause
| 2023-09-12T13:31:36
| 2017-01-31T23:31:36
|
C
|
UTF-8
|
C
| false
| false
| 1,681
|
c
|
utf8_Arabic.c
|
/* generated */
#include "class.h"
static const struct range ranges[] = {
{ 0x0600UL, 0x0604UL },
{ 0x0606UL, 0x060BUL },
{ 0x060DUL, 0x061AUL },
{ 0x061CUL, 0x061EUL },
{ 0x0620UL, 0x063FUL },
{ 0x0641UL, 0x064AUL },
{ 0x0656UL, 0x066FUL },
{ 0x0671UL, 0x06DCUL },
{ 0x06DEUL, 0x06FFUL },
{ 0x0750UL, 0x077FUL },
{ 0x0870UL, 0x088EUL },
{ 0x0890UL, 0x0891UL },
{ 0x0898UL, 0x08E1UL },
{ 0x08E3UL, 0x08FFUL },
{ 0xFB50UL, 0xFBC2UL },
{ 0xFBD3UL, 0xFD3DUL },
{ 0xFD40UL, 0xFD8FUL },
{ 0xFD92UL, 0xFDC7UL },
{ 0xFDCFUL, 0xFDCFUL },
{ 0xFDF0UL, 0xFDFFUL },
{ 0xFE70UL, 0xFE74UL },
{ 0xFE76UL, 0xFEFCUL },
{ 0x10E60UL, 0x10E7EUL },
{ 0x10EFDUL, 0x10EFFUL },
{ 0x1EE00UL, 0x1EE03UL },
{ 0x1EE05UL, 0x1EE1FUL },
{ 0x1EE21UL, 0x1EE22UL },
{ 0x1EE24UL, 0x1EE24UL },
{ 0x1EE27UL, 0x1EE27UL },
{ 0x1EE29UL, 0x1EE32UL },
{ 0x1EE34UL, 0x1EE37UL },
{ 0x1EE39UL, 0x1EE39UL },
{ 0x1EE3BUL, 0x1EE3BUL },
{ 0x1EE42UL, 0x1EE42UL },
{ 0x1EE47UL, 0x1EE47UL },
{ 0x1EE49UL, 0x1EE49UL },
{ 0x1EE4BUL, 0x1EE4BUL },
{ 0x1EE4DUL, 0x1EE4FUL },
{ 0x1EE51UL, 0x1EE52UL },
{ 0x1EE54UL, 0x1EE54UL },
{ 0x1EE57UL, 0x1EE57UL },
{ 0x1EE59UL, 0x1EE59UL },
{ 0x1EE5BUL, 0x1EE5BUL },
{ 0x1EE5DUL, 0x1EE5DUL },
{ 0x1EE5FUL, 0x1EE5FUL },
{ 0x1EE61UL, 0x1EE62UL },
{ 0x1EE64UL, 0x1EE64UL },
{ 0x1EE67UL, 0x1EE6AUL },
{ 0x1EE6CUL, 0x1EE72UL },
{ 0x1EE74UL, 0x1EE77UL },
{ 0x1EE79UL, 0x1EE7CUL },
{ 0x1EE7EUL, 0x1EE7EUL },
{ 0x1EE80UL, 0x1EE89UL },
{ 0x1EE8BUL, 0x1EE9BUL },
{ 0x1EEA1UL, 0x1EEA3UL },
{ 0x1EEA5UL, 0x1EEA9UL },
{ 0x1EEABUL, 0x1EEBBUL },
{ 0x1EEF0UL, 0x1EEF1UL }
};
const struct class utf8_Arabic = {
ranges,
sizeof ranges / sizeof *ranges
};
|
8c90830be33ea7a6f3edcb9deea40cfaec53dd06
|
d9b749e8a4982b8bcd66a19d4ee189fc607ab79e
|
/winrc/unbound-service-remove.c
|
2a285b09a2d1d22436147419eeaee7098edef2ac
|
[
"LicenseRef-scancode-free-unknown",
"GPL-3.0-or-later",
"LicenseRef-scancode-autoconf-simple-exception",
"BSD-3-Clause"
] |
permissive
|
NLnetLabs/unbound
|
26312ae0b3b963f2ab700c4be3d9c45587bcf45e
|
10843805ac37002f1d9293c9835a3e68e41d392d
|
refs/heads/master
| 2023-08-31T23:34:52.610625
| 2023-08-31T11:54:03
| 2023-08-31T11:54:03
| 94,195,301
| 2,526
| 395
|
BSD-3-Clause
| 2023-09-07T14:37:56
| 2017-06-13T09:27:49
|
C
|
UTF-8
|
C
| false
| false
| 2,519
|
c
|
unbound-service-remove.c
|
/*
* winrc/unbound-service-remove.c - windows services installation util
*
* Copyright (c) 2009, NLnet Labs. All rights reserved.
*
* This software is open source.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* Neither the name of the NLNET LABS nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
* TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* \file
*
* This file contains functions to integrate with the windows services API.
* This means it handles the commandline switches to install and remove
* the service (via CreateService and DeleteService), it handles
* the ServiceMain() main service entry point when started as a service,
* and it handles the Handler[_ex]() to process requests to the service
* (such as start and stop and status).
*/
#include "config.h"
#include "winrc/w_inst.h"
/** Remove service main */
int main(int argc, char** argv)
{
FILE* out = stdout;
/* out = fopen("unbound-service-remove.log", "w");*/
if(argc == 2 && strcmp(argv[1], "stop")==0) {
wsvc_rc_stop(out);
return 0;
}
if(argc != 1) {
if(out) fprintf(out, "Usage: %s [stop]\n", argv[0]);
else printf("Usage: %s [stop]\n", argv[0]);
return 1;
}
wsvc_remove(NULL);
return 0;
}
|
8b56115abb575f6f466ed5b67bbb631d3a8ec28f
|
ae31542273a142210a1ff30fb76ed9d45d38eba9
|
/src/backend/libpq/test/auth_test.c
|
8ea9a4804bae995aafaf75ca7ea51054c7c6ae1c
|
[
"Apache-2.0",
"LicenseRef-scancode-generic-cla",
"PostgreSQL",
"OpenSSL",
"LicenseRef-scancode-stream-benchmark",
"ISC",
"LicenseRef-scancode-openssl",
"LicenseRef-scancode-other-copyleft",
"LicenseRef-scancode-ssleay-windows",
"BSD-2-Clause",
"Python-2.0"
] |
permissive
|
greenplum-db/gpdb
|
8334837bceb2d5d51a684500793d11b190117c6a
|
2c0f8f0fb24a2d7a7da114dc80f5f5a2712fca50
|
refs/heads/main
| 2023-08-22T02:03:03.806269
| 2023-08-21T22:59:53
| 2023-08-22T01:17:10
| 44,781,140
| 6,417
| 2,082
|
Apache-2.0
| 2023-09-14T20:33:42
| 2015-10-23T00:25:17
|
C
|
UTF-8
|
C
| false
| false
| 3,466
|
c
|
auth_test.c
|
#include <stdarg.h>
#include <stddef.h>
#include <setjmp.h>
#include "cmockery.h"
#include "postgres.h"
#include "utils/memutils.h"
#include "../auth.c"
#ifdef ENABLE_GSS
static void
pg_authid_search_will_return(const char *user_name, HeapTuple retval)
{
expect_value(SearchSysCache1, cacheId, AUTHNAME);
expect_string(SearchSysCache1, key1, user_name);
will_return(SearchSysCache1, retval);
if (retval != NULL)
{
expect_value(ReleaseSysCache, tuple, retval);
will_be_called(ReleaseSysCache);
}
}
static void
pg_authid_tuple_attribute_will_be(HeapTuple tuple, AttrNumber attr, Datum retval)
{
expect_value(SysCacheGetAttr, cacheId, AUTHNAME);
expect_value(SysCacheGetAttr, tup, tuple);
expect_value(SysCacheGetAttr, attributeNumber, attr);
expect_any(SysCacheGetAttr, isNull);
/*
* The cast to bool here is required; otherwise will_assign_value assumes it
* has an int's worth of space to set and we smash the stack.
*/
will_assign_value(SysCacheGetAttr, isNull, (bool) (retval == 0));
will_return(SysCacheGetAttr, retval);
}
/* Unit tests for check_valid_until_for_gssapi() function */
static void
test_checkValidUntilForGssapi_returns_error_for_nonexistent_user(void **state)
{
int result;
Port *port = (Port *) malloc(sizeof(Port));
port->user_name = "foo";
pg_authid_search_will_return(port->user_name, NULL);
result = check_valid_until_for_gssapi(port);
assert_true(result == STATUS_ERROR);
}
static void
test_checkValidUntilForGssapi_returns_ok_for_user_with_null_validuntil(void **state)
{
int result;
Port *port = (Port *) malloc(sizeof(Port));
HeapTuple tuple = malloc(sizeof(*tuple));
port->user_name = "foo";
pg_authid_search_will_return(port->user_name, tuple);
pg_authid_tuple_attribute_will_be(tuple, Anum_pg_authid_rolvaliduntil, (Datum) 0);
result = check_valid_until_for_gssapi(port);
assert_true(result == STATUS_OK);
}
static void
test_checkValidUntilForGssapi_returns_error_for_user_with_expired_validuntil(void **state)
{
int result;
Port *port = (Port *) malloc(sizeof(Port));
HeapTuple tuple = malloc(sizeof(*tuple));
port->user_name = "foo";
pg_authid_search_will_return(port->user_name, tuple);
pg_authid_tuple_attribute_will_be(tuple, Anum_pg_authid_rolvaliduntil, (Datum) 10293842);
will_return(GetCurrentTimestamp, 10293843);
result = check_valid_until_for_gssapi(port);
assert_true(result == STATUS_ERROR);
}
static void
test_checkValidUntilForGssapi_returns_ok_for_user_with_unexpired_validuntil(void **state)
{
int result;
Port *port = (Port *) malloc(sizeof(Port));
HeapTuple tuple = malloc(sizeof(*tuple));
port->user_name = "foo";
pg_authid_search_will_return(port->user_name, tuple);
pg_authid_tuple_attribute_will_be(tuple, Anum_pg_authid_rolvaliduntil, (Datum) 10293844);
will_return(GetCurrentTimestamp, 10293843);
result = check_valid_until_for_gssapi(port);
assert_true(result == STATUS_OK);
}
#endif
int
main(int argc, char* argv[])
{
cmockery_parse_arguments(argc, argv);
const UnitTest tests[] = {
#ifdef ENABLE_GSS
unit_test(test_checkValidUntilForGssapi_returns_error_for_nonexistent_user),
unit_test(test_checkValidUntilForGssapi_returns_ok_for_user_with_null_validuntil),
unit_test(test_checkValidUntilForGssapi_returns_error_for_user_with_expired_validuntil),
unit_test(test_checkValidUntilForGssapi_returns_ok_for_user_with_unexpired_validuntil),
#endif
};
MemoryContextInit();
return run_tests(tests);
}
|
5479ca67de20861136095a913ce099f70ee10842
|
79d343002bb63a44f8ab0dbac0c9f4ec54078c3a
|
/lib/libc/musl/src/process/posix_spawnattr_init.c
|
0dcd868f3c61450a84f94e86fa3261e4c5230469
|
[
"BSD-3-Clause",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause",
"LicenseRef-scancode-other-permissive",
"LicenseRef-scancode-musl-exception",
"MIT"
] |
permissive
|
ziglang/zig
|
4aa75d8d3bcc9e39bf61d265fd84b7f005623fc5
|
f4c9e19bc3213c2bc7e03d7b06d7129882f39f6c
|
refs/heads/master
| 2023-08-31T13:16:45.980913
| 2023-08-31T05:50:29
| 2023-08-31T05:50:29
| 40,276,274
| 25,560
| 2,399
|
MIT
| 2023-09-14T21:09:50
| 2015-08-06T00:51:28
|
Zig
|
UTF-8
|
C
| false
| false
| 120
|
c
|
posix_spawnattr_init.c
|
#include <spawn.h>
int posix_spawnattr_init(posix_spawnattr_t *attr)
{
*attr = (posix_spawnattr_t){ 0 };
return 0;
}
|
7564d914128f44a3fc92c1166140d8a152a5aa0e
|
693bd39eb66eade67997bc608fe84e76e66eeec2
|
/inc/mpp_meta.h
|
5aea91dad6d1b89754086ba77d6ca7f00df58d10
|
[] |
permissive
|
HermanChen/mpp
|
6a1751777b120b764f86e0f34975231054a3c262
|
0af9b5becc76c4685831214808e124e65543297b
|
refs/heads/develop
| 2023-08-17T07:17:49.489974
| 2023-07-31T08:26:14
| 2023-08-11T07:38:17
| 71,088,248
| 139
| 79
|
Apache-2.0
| 2023-03-08T09:44:01
| 2016-10-17T01:13:37
|
C
|
UTF-8
|
C
| false
| false
| 7,775
|
h
|
mpp_meta.h
|
/*
* Copyright 2015 Rockchip Electronics Co. LTD
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef __MPP_META_H__
#define __MPP_META_H__
#include <stdint.h>
#include "rk_type.h"
#define FOURCC_META(a, b, c, d) ((RK_U32)(a) << 24 | \
((RK_U32)(b) << 16) | \
((RK_U32)(c) << 8) | \
((RK_U32)(d) << 0))
/*
* Mpp Metadata definition
*
* Metadata is for information transmision in mpp.
* Mpp task will contain two meta data:
*
* 1. Data flow metadata
* This metadata contains information of input / output data flow. For example
* A. decoder input side task the input packet must be defined and output frame
* may not be defined. Then decoder will try malloc or use committed buffer to
* complete decoding.
* B. decoder output side task
*
*
* 2. Flow control metadata
*
*/
typedef enum MppMetaDataType_e {
/*
* mpp meta data of data flow
* reference counter will be used for these meta data type
*/
TYPE_FRAME = FOURCC_META('m', 'f', 'r', 'm'),
TYPE_PACKET = FOURCC_META('m', 'p', 'k', 't'),
TYPE_BUFFER = FOURCC_META('m', 'b', 'u', 'f'),
/* mpp meta data of normal data type */
TYPE_S32 = FOURCC_META('s', '3', '2', ' '),
TYPE_S64 = FOURCC_META('s', '6', '4', ' '),
TYPE_PTR = FOURCC_META('p', 't', 'r', ' '),
} MppMetaType;
typedef enum MppMetaKey_e {
/* data flow key */
KEY_INPUT_FRAME = FOURCC_META('i', 'f', 'r', 'm'),
KEY_INPUT_PACKET = FOURCC_META('i', 'p', 'k', 't'),
KEY_OUTPUT_FRAME = FOURCC_META('o', 'f', 'r', 'm'),
KEY_OUTPUT_PACKET = FOURCC_META('o', 'p', 'k', 't'),
/* output motion information for motion detection */
KEY_MOTION_INFO = FOURCC_META('m', 'v', 'i', 'f'),
KEY_HDR_INFO = FOURCC_META('h', 'd', 'r', ' '),
KEY_HDR_META_OFFSET = FOURCC_META('h', 'd', 'r', 'o'),
KEY_HDR_META_SIZE = FOURCC_META('h', 'd', 'r', 'l'),
/* flow control key */
KEY_INPUT_BLOCK = FOURCC_META('i', 'b', 'l', 'k'),
KEY_OUTPUT_BLOCK = FOURCC_META('o', 'b', 'l', 'k'),
KEY_INPUT_IDR_REQ = FOURCC_META('i', 'i', 'd', 'r'), /* input idr frame request flag */
KEY_OUTPUT_INTRA = FOURCC_META('o', 'i', 'd', 'r'), /* output intra frame indicator */
/* mpp_frame / mpp_packet meta data info key */
KEY_TEMPORAL_ID = FOURCC_META('t', 'l', 'i', 'd'),
KEY_LONG_REF_IDX = FOURCC_META('l', 't', 'i', 'd'),
KEY_ENC_AVERAGE_QP = FOURCC_META('a', 'v', 'g', 'q'),
KEY_ROI_DATA = FOURCC_META('r', 'o', 'i', ' '),
KEY_OSD_DATA = FOURCC_META('o', 's', 'd', ' '),
KEY_OSD_DATA2 = FOURCC_META('o', 's', 'd', '2'),
KEY_USER_DATA = FOURCC_META('u', 's', 'r', 'd'),
KEY_USER_DATAS = FOURCC_META('u', 'r', 'd', 's'),
/*
* For vepu580 roi buffer config mode
* The encoder roi structure is so complex that we should provide a buffer
* tunnel for externl user to config encoder hardware by direct sending
* roi data buffer.
* This way can reduce the config parsing and roi buffer data generating
* overhead in mpp.
*/
KEY_ROI_DATA2 = FOURCC_META('r', 'o', 'i', '2'),
/*
* qpmap for rv1109/1126 encoder qpmap config
* Input data is a MppBuffer which contains an array of 16bit Vepu541RoiCfg.
* And each 16bit represents a 16x16 block qp info.
*
* H.264 - 16x16 block qp is arranged in raster order:
* each value is a 16bit data
* 00 01 02 03 04 05 06 07 -> 00 01 02 03 04 05 06 07
* 10 11 12 13 14 15 16 17 10 11 12 13 14 15 16 17
* 20 21 22 23 24 25 26 27 20 21 22 23 24 25 26 27
* 30 31 32 33 34 35 36 37 30 31 32 33 34 35 36 37
*
* H.265 - 16x16 block qp is reorder to 64x64/32x32 ctu order then 64x64 / 32x32 ctu raster order
* 64x64 ctu
* 00 01 02 03 04 05 06 07 -> 00 01 02 03 10 11 12 13 20 21 22 23 30 31 32 33 04 05 06 07 14 15 16 17 24 25 26 27 34 35 36 37
* 10 11 12 13 14 15 16 17
* 20 21 22 23 24 25 26 27
* 30 31 32 33 34 35 36 37
* 32x32 ctu
* 00 01 02 03 04 05 06 07 -> 00 01 10 11 02 03 12 13 04 05 14 15 06 07 16 17
* 10 11 12 13 14 15 16 17 20 21 30 31 22 23 32 33 24 25 34 35 26 27 36 37
* 20 21 22 23 24 25 26 27
* 30 31 32 33 34 35 36 37
*/
KEY_QPMAP0 = FOURCC_META('e', 'q', 'm', '0'),
/* input motion list for smart p rate control */
KEY_MV_LIST = FOURCC_META('m', 'v', 'l', 't'),
/* frame long-term reference frame operation */
KEY_ENC_MARK_LTR = FOURCC_META('m', 'l', 't', 'r'),
KEY_ENC_USE_LTR = FOURCC_META('u', 'l', 't', 'r'),
/* MLVEC specified encoder feature */
KEY_ENC_FRAME_QP = FOURCC_META('f', 'r', 'm', 'q'),
KEY_ENC_BASE_LAYER_PID = FOURCC_META('b', 'p', 'i', 'd'),
/* Thumbnail info for decoder output frame */
KEY_DEC_TBN_EN = FOURCC_META('t', 'b', 'e', 'n'),
KEY_DEC_TBN_Y_OFFSET = FOURCC_META('t', 'b', 'y', 'o'),
KEY_DEC_TBN_UV_OFFSET = FOURCC_META('t', 'b', 'c', 'o'),
} MppMetaKey;
#define mpp_meta_get(meta) mpp_meta_get_with_tag(meta, MODULE_TAG, __FUNCTION__)
#include "mpp_frame.h"
#include "mpp_packet.h"
#ifdef __cplusplus
extern "C" {
#endif
MPP_RET mpp_meta_get_with_tag(MppMeta *meta, const char *tag, const char *caller);
MPP_RET mpp_meta_put(MppMeta meta);
RK_S32 mpp_meta_size(MppMeta meta);
MPP_RET mpp_meta_set_s32(MppMeta meta, MppMetaKey key, RK_S32 val);
MPP_RET mpp_meta_set_s64(MppMeta meta, MppMetaKey key, RK_S64 val);
MPP_RET mpp_meta_set_ptr(MppMeta meta, MppMetaKey key, void *val);
MPP_RET mpp_meta_get_s32(MppMeta meta, MppMetaKey key, RK_S32 *val);
MPP_RET mpp_meta_get_s64(MppMeta meta, MppMetaKey key, RK_S64 *val);
MPP_RET mpp_meta_get_ptr(MppMeta meta, MppMetaKey key, void **val);
MPP_RET mpp_meta_set_frame (MppMeta meta, MppMetaKey key, MppFrame frame);
MPP_RET mpp_meta_set_packet(MppMeta meta, MppMetaKey key, MppPacket packet);
MPP_RET mpp_meta_set_buffer(MppMeta meta, MppMetaKey key, MppBuffer buffer);
MPP_RET mpp_meta_get_frame (MppMeta meta, MppMetaKey key, MppFrame *frame);
MPP_RET mpp_meta_get_packet(MppMeta meta, MppMetaKey key, MppPacket *packet);
MPP_RET mpp_meta_get_buffer(MppMeta meta, MppMetaKey key, MppBuffer *buffer);
MPP_RET mpp_meta_get_s32_d(MppMeta meta, MppMetaKey key, RK_S32 *val, RK_S32 def);
MPP_RET mpp_meta_get_s64_d(MppMeta meta, MppMetaKey key, RK_S64 *val, RK_S64 def);
MPP_RET mpp_meta_get_ptr_d(MppMeta meta, MppMetaKey key, void **val, void *def);
MPP_RET mpp_meta_get_frame_d(MppMeta meta, MppMetaKey key, MppFrame *frame, MppFrame def);
MPP_RET mpp_meta_get_packet_d(MppMeta meta, MppMetaKey key, MppPacket *packet, MppPacket def);
MPP_RET mpp_meta_get_buffer_d(MppMeta meta, MppMetaKey key, MppBuffer *buffer, MppBuffer def);
#ifdef __cplusplus
}
#endif
#endif /*__MPP_META_H__*/
|
df9b10d6ad652b4af3d84b5f86461921f5de2549
|
fcad0847f36caed70c6823a7fa93f64309d75597
|
/modules/PReLU.c
|
5f666388ef85503bed33d6b407ba1825f917a832
|
[
"BSD-3-Clause"
] |
permissive
|
mvitez/thnets
|
923e7c76ee9b275e17d83da80eaad3dd273333eb
|
ac3ad6d98e7cce17ecd3e44de1311eb27935e00e
|
refs/heads/master
| 2020-12-15T01:29:11.491275
| 2019-04-30T09:48:32
| 2019-04-30T09:49:23
| 48,061,703
| 202
| 34
| null | 2017-01-20T13:57:46
| 2015-12-15T18:36:33
|
C
|
UTF-8
|
C
| false
| false
| 2,146
|
c
|
PReLU.c
|
#include "../thnets.h"
static void nnfree_PReLU(struct module *mod)
{
THFloatTensor_free(mod->PReLU.weight);
}
int nnload_PReLU(struct module *mod, struct nnmodule *n)
{
struct table *t = n->table;
mod->type = MT_PReLU;
mod->updateOutput = nn_PReLU_updateOutput;
mod->nnfree = nnfree_PReLU;
struct PReLU *m = &mod->PReLU;
m->nOutputPlane = TableGetNumber(t, "nOutputPlane");
m->weight = TableGetTensor(t, "weight");
return 0;
}
#ifdef ONNX
void onnxload_PReLU(const void *graph, struct module *m, int nodeidx)
{
m->type = MT_PReLU;
m->updateOutput = nn_PReLU_updateOutput;
m->nnfree = nnfree_PReLU;
struct PReLU *p = &m->PReLU;
p->weight = onnx_gettensor(graph, nodeidx, 1);
p->nOutputPlane = (int)p->weight->size[0];
}
#endif
THFloatTensor *nn_PReLU_updateOutput(struct module *module, THFloatTensor *input)
{
THFloatTensor *output = module->output;
THFloatTensor *weight = module->PReLU.weight;
THFloatTensor_resizeAs(output, input);
float *in = THFloatTensor_data(input);
float *out = THFloatTensor_data(output);
float *w = THFloatTensor_data(weight);
long bs, ks, nOutputPlane = module->PReLU.nOutputPlane;
if(nOutputPlane == 0)
{
long i, n = THFloatTensor_nElement(input);
for(i = 0; i < n; i++)
out[i] = in[i] > 0 ? in[i] : *w*in[i];
return output;
}
int input_ndim = input->nDimension;
switch (input_ndim)
{
case 1:
bs = 1;
ks = 1;
break;
case 2:
bs = input->size[0];
ks = 1;
break;
case 3:
bs = 1;
ks = input->size[1] * input->size[2];
break;
case 4:
bs = input->size[0];
ks = input->size[2] * input->size[3];
break;
default:
ks = 0;
bs = 0;
break;
}
if (input->size[(input_ndim + 1) % 2] != nOutputPlane)
THError("wrong number of input planes");
int i, j, k;
#pragma omp parallel for private(j,k)
for(i = 0; i < bs; ++i)
{
float *n_input_data = in + i*nOutputPlane*ks;
float *n_output_data = out + i*nOutputPlane*ks;
for (j = 0; j < nOutputPlane; ++j)
{
for (k = 0; k < ks; ++k)
n_output_data[k] = (n_input_data[k] > 0) ? n_input_data[k] : w[j] * n_input_data[k];
n_input_data += ks;
n_output_data += ks;
}
}
return output;
}
|
756175a542c470f09744e341049059c7cf69677f
|
d2253070a3a64b14dee5ca0b3d311919178e590c
|
/include/battle_dome.h
|
900508c4bf3e304771ad4f422b5caab1ccd62eb8
|
[] |
no_license
|
pret/pokeemerald
|
ce232eccdde78502f3c251d672b26af3e1d7e508
|
d67914e114c937c4c80ce128ddc5523d4dc2cd40
|
refs/heads/master
| 2023-08-31T11:23:13.877932
| 2023-08-27T23:40:59
| 2023-08-27T23:40:59
| 43,677,244
| 1,944
| 1,903
| null | 2023-09-12T22:48:06
| 2015-10-05T10:09:22
|
C
|
UTF-8
|
C
| false
| false
| 225
|
h
|
battle_dome.h
|
#ifndef GUARD_BATTLE_DOME_H
#define GUARD_BATTLE_DOME_H
extern u32 gPlayerPartyLostHP;
int GetDomeTrainerSelectedMons(u16 tournamentTrainerId);
int TrainerIdToDomeTournamentId(u16 trainerId);
#endif // GUARD_BATTLE_DOME_H
|
838513c532e5368242e5ac2312656e193113b6d1
|
0cc343d927d5db6693006018986715c43acab961
|
/examples/linking/include_paths/main.c
|
bcf326eebf6ae3e89c54756fe511d79497ca806f
|
[
"MIT"
] |
permissive
|
verifast/verifast
|
ec0101fc4a69bd33c5f66be4444169c4e060ead8
|
d152da790c7ebf72ce616533a6c83082629adbdb
|
refs/heads/master
| 2023-08-25T00:13:51.464802
| 2023-08-13T10:00:00
| 2023-08-13T10:00:00
| 14,519,163
| 325
| 64
|
NOASSERTION
| 2023-08-10T21:16:08
| 2013-11-19T08:57:02
|
OCaml
|
UTF-8
|
C
| false
| false
| 194
|
c
|
main.c
|
#include "header.h"
int main() //@ : main
//@ requires true;
//@ ensures true;
{
func();
//@ open unsound();
*((int*) 0) = 5; //~allow_dead_code
return 0; //~allow_dead_code
}
|
e62d71191655c36837dc99483e45997ee3127409
|
79d343002bb63a44f8ab0dbac0c9f4ec54078c3a
|
/lib/libc/include/any-windows-any/winresrc.h
|
3e6dda7d8d7db2f39129319a9254cce66fe65def
|
[
"MIT",
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-public-domain"
] |
permissive
|
ziglang/zig
|
4aa75d8d3bcc9e39bf61d265fd84b7f005623fc5
|
f4c9e19bc3213c2bc7e03d7b06d7129882f39f6c
|
refs/heads/master
| 2023-08-31T13:16:45.980913
| 2023-08-31T05:50:29
| 2023-08-31T05:50:29
| 40,276,274
| 25,560
| 2,399
|
MIT
| 2023-09-14T21:09:50
| 2015-08-06T00:51:28
|
Zig
|
UTF-8
|
C
| false
| false
| 597
|
h
|
winresrc.h
|
/**
* This file has no copyright assigned and is placed in the Public Domain.
* This file is part of the mingw-w64 runtime package.
* No warranty is given; refer to the file DISCLAIMER.PD within this package.
*/
#ifndef _WINRESRC_
#define _WINRESRC_
#ifndef WINVER
#define WINVER 0x0502
#endif
#ifndef _WIN32_IE
#define _WIN32_IE 0x0501
#endif
#ifndef _WIN32_WINDOWS
#define _WIN32_WINDOWS 0x0502
#endif
#ifndef _WIN32_WINNT
#define _WIN32_WINNT 0x0502
#endif
#include <winuser.rh>
#include <commctrl.rh>
#include <dde.rh>
#include <winnt.rh>
#include <dlgs.h>
#include <winver.h>
#endif
|
886fdc4b9787bdb3ae88b9913eaf86b1dc34d5c9
|
1efb2283837c9b70bc6449cec877799e4efa3268
|
/src/mpid/ch4/netmod/ofi/ofi_probe.h
|
a1267133975510ce3b1873765ef8eae2f5b58392
|
[
"mpich2"
] |
permissive
|
pmodels/mpich
|
d2392e8e30536cad3e500c16aa1e71211101d83f
|
2d265f9f5f93ebdd07ad547423bc6212868262a4
|
refs/heads/main
| 2023-09-04T05:50:15.041823
| 2023-09-01T23:07:33
| 2023-09-01T23:07:33
| 70,918,679
| 506
| 313
|
NOASSERTION
| 2023-09-14T14:38:36
| 2016-10-14T14:39:42
|
C
|
UTF-8
|
C
| false
| false
| 6,709
|
h
|
ofi_probe.h
|
/*
* Copyright (C) by Argonne National Laboratory
* See COPYRIGHT in top-level directory
*/
#ifndef OFI_PROBE_H_INCLUDED
#define OFI_PROBE_H_INCLUDED
#include "ofi_impl.h"
MPL_STATIC_INLINE_PREFIX int MPIDI_OFI_do_iprobe(int source,
int tag,
MPIR_Comm * comm,
int context_offset,
MPIDI_av_entry_t * addr, int vci_src, int vci_dst,
int *flag,
MPI_Status * status, MPIR_Request ** message)
{
int mpi_errno = MPI_SUCCESS;
fi_addr_t remote_proc;
uint64_t match_bits, mask_bits;
MPIR_Request r, *rreq; /* don't need to init request, output only */
struct fi_msg_tagged msg;
int ofi_err;
int receiver_nic, ctx_idx;
receiver_nic = MPIDI_OFI_multx_receiver_nic_index(comm, comm->recvcontext_id,
source, comm->rank, tag);
ctx_idx = MPIDI_OFI_get_ctx_index(vci_dst, receiver_nic);
MPIR_FUNC_ENTER;
if (unlikely(MPI_ANY_SOURCE == source)) {
remote_proc = FI_ADDR_UNSPEC;
} else {
int sender_nic = MPIDI_OFI_multx_sender_nic_index(comm, comm->recvcontext_id,
source, comm->rank, tag);
remote_proc = MPIDI_OFI_av_to_phys(addr, sender_nic, vci_src);
}
if (message) {
MPIDI_CH4_REQUEST_CREATE(rreq, MPIR_REQUEST_KIND__MPROBE, vci_dst, 1);
MPIR_ERR_CHKANDSTMT((rreq) == NULL, mpi_errno, MPIX_ERR_NOREQ, goto fn_fail, "**nomemreq");
} else {
rreq = &r;
}
if (message) {
MPIDI_OFI_REQUEST(rreq, kind) = MPIDI_OFI_req_kind__mprobe;
} else {
MPIDI_OFI_REQUEST(rreq, kind) = MPIDI_OFI_req_kind__probe;
}
MPIDI_OFI_REQUEST(rreq, huge.remote_info) = NULL;
rreq->comm = comm;
MPIR_Comm_add_ref(comm);
match_bits =
MPIDI_OFI_init_recvtag(&mask_bits, comm->recvcontext_id + context_offset, source, tag);
MPIDI_OFI_REQUEST(rreq, event_id) = MPIDI_OFI_EVENT_PEEK;
MPL_atomic_release_store_int(&(MPIDI_OFI_REQUEST(rreq, util_id)), MPIDI_OFI_PEEK_START);
msg.msg_iov = NULL;
msg.desc = NULL;
msg.iov_count = 0;
msg.addr = remote_proc;
msg.tag = match_bits;
msg.ignore = mask_bits;
msg.context = (void *) &(MPIDI_OFI_REQUEST(rreq, context));
msg.data = 0;
uint64_t recv_flags = FI_PEEK | FI_COMPLETION;
if (message) {
recv_flags |= FI_CLAIM;
}
ofi_err = 0;
MPIDI_OFI_CALL_RETRY_RETURN(fi_trecvmsg(MPIDI_OFI_global.ctx[ctx_idx].rx, &msg, recv_flags),
vci_dst, ofi_err);
if (ofi_err == -FI_ENOMSG) {
*flag = 0;
if (message)
MPIDI_CH4_REQUEST_FREE(rreq);
goto fn_exit;
}
MPIDI_OFI_CALL(ofi_err, trecvmsg);
MPIDI_OFI_PROGRESS_WHILE(MPL_atomic_acquire_load_int(&(MPIDI_OFI_REQUEST(rreq, util_id))) ==
MPIDI_OFI_PEEK_START, vci_dst);
/* Ordering constraint for util_id is unnecessary after the thread unblocks */
switch (MPL_atomic_relaxed_load_int(&(MPIDI_OFI_REQUEST(rreq, util_id)))) {
case MPIDI_OFI_PEEK_NOT_FOUND:
*flag = 0;
if (message)
MPIDI_CH4_REQUEST_FREE(rreq);
goto fn_exit;
case MPIDI_OFI_PEEK_FOUND:
MPIR_Request_extract_status(rreq, status);
*flag = 1;
if (message) {
MPIR_Request_add_ref(rreq);
*message = rreq;
}
break;
default:
MPIR_Assert(0);
}
fn_exit:
if (message == NULL) {
MPIR_Comm_release(comm);
}
MPIR_FUNC_EXIT;
return mpi_errno;
fn_fail:
goto fn_exit;
}
/* Common macro used by all MPIDI_NM_mpi_probe routines to facilitate tuning */
#define MPIDI_OFI_PROBE_VNIS(vci_src_, vci_dst_) \
do { \
/* NOTE: hashing is based on target rank */ \
MPIDI_EXPLICIT_VCIS(comm, attr, source, comm->rank, vci_src_, vci_dst_); \
if (vci_src_ == 0 && vci_dst_ == 0) { \
vci_src_ = MPIDI_get_vci(SRC_VCI_FROM_RECVER, comm, source, comm->rank, tag); \
vci_dst_ = MPIDI_get_vci(DST_VCI_FROM_RECVER, comm, source, comm->rank, tag); \
} \
} while (0)
MPL_STATIC_INLINE_PREFIX int MPIDI_NM_mpi_improbe(int source,
int tag,
MPIR_Comm * comm,
int attr, MPIDI_av_entry_t * addr,
int *flag, MPIR_Request ** message,
MPI_Status * status)
{
int mpi_errno = MPI_SUCCESS;
MPIR_FUNC_ENTER;
int context_offset = MPIR_PT2PT_ATTR_CONTEXT_OFFSET(attr);
int vci_src, vci_dst;
MPIDI_OFI_PROBE_VNIS(vci_src, vci_dst);
MPIDI_OFI_THREAD_CS_ENTER_VCI_OPTIONAL(vci_dst);
if (!MPIDI_OFI_ENABLE_TAGGED) {
mpi_errno = MPIDIG_mpi_improbe(source, tag, comm, context_offset, vci_dst, flag, message,
status);
} else {
/* Set flags for mprobe peek, when ready */
mpi_errno = MPIDI_OFI_do_iprobe(source, tag, comm, context_offset, addr, vci_src, vci_dst,
flag, status, message);
}
MPIDI_OFI_THREAD_CS_EXIT_VCI_OPTIONAL(vci_dst);
MPIR_FUNC_EXIT;
return mpi_errno;
}
MPL_STATIC_INLINE_PREFIX int MPIDI_NM_mpi_iprobe(int source,
int tag,
MPIR_Comm * comm,
int attr, MPIDI_av_entry_t * addr,
int *flag, MPI_Status * status)
{
int mpi_errno;
MPIR_FUNC_ENTER;
int context_offset = MPIR_PT2PT_ATTR_CONTEXT_OFFSET(attr);
int vci_src, vci_dst;
MPIDI_OFI_PROBE_VNIS(vci_src, vci_dst);
MPIDI_OFI_THREAD_CS_ENTER_VCI_OPTIONAL(vci_dst);
if (!MPIDI_OFI_ENABLE_TAGGED) {
mpi_errno = MPIDIG_mpi_iprobe(source, tag, comm, context_offset, vci_dst, flag, status);
} else {
mpi_errno = MPIDI_OFI_do_iprobe(source, tag, comm, context_offset, addr,
vci_src, vci_dst, flag, status, NULL);
}
MPIDI_OFI_THREAD_CS_EXIT_VCI_OPTIONAL(vci_dst);
MPIR_FUNC_EXIT;
return mpi_errno;
}
#endif /* OFI_PROBE_H_INCLUDED */
|
0bdd813c753d13efe9ff37941e83575d0be97fa9
|
4e32ea5b4a215f427af04630e01b1312ffd31a55
|
/test/programs/fault_localization/factorization_paper_example.c
|
97b4140b3e631deb51285279a08820fcc762b9a6
|
[
"Apache-2.0",
"GPL-1.0-or-later"
] |
permissive
|
sosy-lab/cpachecker
|
1add74cb774316dd6e1aea3fb1f352c8141466b7
|
1822761867d106301bda0bc99ed3cc0a25c529aa
|
refs/heads/trunk
| 2023-08-31T14:47:22.284597
| 2023-08-31T14:20:58
| 2023-08-31T14:20:58
| 20,107,238
| 186
| 90
|
Apache-2.0
| 2021-07-27T14:24:30
| 2014-05-23T16:57:37
|
SWIG
|
UTF-8
|
C
| false
| false
| 242
|
c
|
factorization_paper_example.c
|
int __VERIFIER_nondet_int();
int main(){
int num = __VERIFIER_nondet_int();
if (num < 1) return 0;
for (int i = 2; i <= num; i++) {
if (num % i == 0) {
num /=(i + 1);
i--;
}
}
if(num != 1) {
ERROR: return 1;
}
}
|
538daa46ebb7993d57f54d3af1c9ac1e28afcbe9
|
7eaf54a78c9e2117247cb2ab6d3a0c20719ba700
|
/SOFTWARE/A64-TERES/linux-a64/arch/alpha/kernel/binfmt_loader.c
|
9525660c93c0f1808c9180cb382d142e88ae3bb2
|
[
"Linux-syscall-note",
"GPL-2.0-only",
"GPL-1.0-or-later",
"LicenseRef-scancode-free-unknown",
"Apache-2.0"
] |
permissive
|
OLIMEX/DIY-LAPTOP
|
ae82f4ee79c641d9aee444db9a75f3f6709afa92
|
a3fafd1309135650bab27f5eafc0c32bc3ca74ee
|
refs/heads/rel3
| 2023-08-04T01:54:19.483792
| 2023-04-03T07:18:12
| 2023-04-03T07:18:12
| 80,094,055
| 507
| 92
|
Apache-2.0
| 2023-04-03T07:05:59
| 2017-01-26T07:25:50
|
C
|
UTF-8
|
C
| false
| false
| 1,093
|
c
|
binfmt_loader.c
|
#include <linux/init.h>
#include <linux/fs.h>
#include <linux/file.h>
#include <linux/mm_types.h>
#include <linux/binfmts.h>
#include <linux/a.out.h>
static int load_binary(struct linux_binprm *bprm)
{
struct exec *eh = (struct exec *)bprm->buf;
unsigned long loader;
struct file *file;
int retval;
if (eh->fh.f_magic != 0x183 || (eh->fh.f_flags & 0x3000) != 0x3000)
return -ENOEXEC;
if (bprm->loader)
return -ENOEXEC;
allow_write_access(bprm->file);
fput(bprm->file);
bprm->file = NULL;
loader = bprm->vma->vm_end - sizeof(void *);
file = open_exec("/sbin/loader");
retval = PTR_ERR(file);
if (IS_ERR(file))
return retval;
/* Remember if the application is TASO. */
bprm->taso = eh->ah.entry < 0x100000000UL;
bprm->file = file;
bprm->loader = loader;
retval = prepare_binprm(bprm);
if (retval < 0)
return retval;
return search_binary_handler(bprm);
}
static struct linux_binfmt loader_format = {
.load_binary = load_binary,
};
static int __init init_loader_binfmt(void)
{
insert_binfmt(&loader_format);
return 0;
}
arch_initcall(init_loader_binfmt);
|
03f3fd1a038ee4d85b079607764b97dca2b76bb9
|
98f272704d0a3849acd1a2eec8a99285308633dc
|
/sandbox-capsicum.c
|
21fc6fd6d98b477196090787141ef54a72be8360
|
[
"ISC"
] |
permissive
|
kristapsdz/kcgi
|
35a6f8c86a3816be222c8f2bd44d0683c5595318
|
575e9267f73ab575a0082242a41a6b77c487914e
|
refs/heads/master
| 2023-06-08T08:47:47.785495
| 2022-04-02T19:17:13
| 2022-04-02T19:17:13
| 50,068,029
| 285
| 77
|
ISC
| 2023-07-16T20:03:48
| 2016-01-20T23:30:58
|
C
|
UTF-8
|
C
| false
| false
| 5,085
|
c
|
sandbox-capsicum.c
|
/* $Id$ */
/*
* Copyright (c) 2014 Baptiste Daroussin <bapt@freebsd.org>
* Copyright (c) 2015--2016 Kristaps Dzonsons <kristaps@bsd.lv>
*
* Permission to use, copy, modify, and 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.
*/
#include "config.h"
#if HAVE_CAPSICUM
#include <sys/resource.h>
#include <sys/capsicum.h>
#include <assert.h>
#include <unistd.h>
#include <errno.h>
#include <stdarg.h>
#include <stdlib.h>
#include "kcgi.h"
#include "extern.h"
static int
ksandbox_capsicum_init_control(int worker, int fdfiled, int fdaccept)
{
int rc;
struct rlimit rl_zero;
cap_rights_t rights;
cap_rights_init(&rights);
/*
* If we have old-style accept FastCGI sockets, then mark us as
* accepting on it.
* XXX: the CAP_READ and CAP_WRITE are necessary because they're
* required by descriptors we create from the accept().
* The new-style passing of descriptors is easier.
*/
if (fdaccept != -1) {
cap_rights_init(&rights,
CAP_EVENT, CAP_FCNTL, CAP_ACCEPT,
CAP_READ, CAP_WRITE);
if (cap_rights_limit(fdaccept, &rights) < 0 &&
errno != ENOSYS) {
kutil_warn(NULL, NULL, "cap_rights_limit");
return 0;
}
} else {
assert(fdfiled != -1);
cap_rights_init(&rights, CAP_EVENT,
CAP_FCNTL, CAP_READ, CAP_WRITE);
if (cap_rights_limit(fdfiled, &rights) < 0 &&
errno != ENOSYS) {
kutil_warn(NULL, NULL, "cap_rights_limit");
return 0;
}
}
/* Always pass through write-only stderr. */
cap_rights_init(&rights, CAP_WRITE, CAP_FSTAT);
if (cap_rights_limit(STDERR_FILENO, &rights) < 0 &&
errno != ENOSYS) {
kutil_warn(NULL, NULL, "cap_rights_limit");
return 0;
}
/* Interface to worker. */
cap_rights_init(&rights, CAP_EVENT,
CAP_FCNTL, CAP_READ, CAP_WRITE);
if (cap_rights_limit(worker, &rights) < 0 &&
errno != ENOSYS) {
kutil_warn(NULL, NULL, "cap_rights_limit");
return 0;
}
rl_zero.rlim_cur = rl_zero.rlim_max = 0;
if (setrlimit(RLIMIT_FSIZE, &rl_zero) == -1) {
kutil_warn(NULL, NULL, "setrlimit");
return 0;
} else if (setrlimit(RLIMIT_NPROC, &rl_zero) == -1) {
kutil_warn(NULL, NULL, "setrlimit");
return 0;
}
rc = cap_enter();
if (rc && errno != ENOSYS) {
kutil_warn(NULL, NULL, "cap_enter");
rc = 0;
} else
rc = 1;
return rc;
}
static int
ksandbox_capsicum_init_worker(int fd1, int fd2)
{
int rc;
struct rlimit rl_zero;
cap_rights_t rights;
cap_rights_init(&rights);
/*
* Test for EBADF because STDIN_FILENO is usually closed by the
* caller.
*/
cap_rights_init(&rights, CAP_EVENT, CAP_READ, CAP_FSTAT);
if (cap_rights_limit(STDIN_FILENO, &rights) < 0 &&
errno != ENOSYS && errno != EBADF) {
kutil_warn(NULL, NULL, "cap_rights_limit");
return 0;
}
cap_rights_init(&rights, CAP_EVENT, CAP_WRITE, CAP_FSTAT);
if (cap_rights_limit(STDERR_FILENO, &rights) < 0 &&
errno != ENOSYS) {
kutil_warn(NULL, NULL, "cap_rights_limit");
return 0;
}
/* Only do thesee if the descriptors are valid. */
cap_rights_init(&rights, CAP_EVENT, CAP_READ, CAP_WRITE, CAP_FSTAT);
if (fd1 != -1 && cap_rights_limit(fd1, &rights) < 0 &&
errno != ENOSYS) {
kutil_warn(NULL, NULL, "cap_rights_limit");
return 0;
}
if (fd2 != -1 && cap_rights_limit(fd2, &rights) < 0 &&
errno != ENOSYS) {
kutil_warn(NULL, NULL, "cap_rights_limit");
return 0;
}
rl_zero.rlim_cur = rl_zero.rlim_max = 0;
#if 0
/* Don't run this: if we use openlog, it will fail. */
if (setrlimit(RLIMIT_FSIZE, &rl_zero) == -1) {
kutil_warn(NULL, NULL, "setrlimit");
return 0;
}
#endif
if (setrlimit(RLIMIT_NOFILE, &rl_zero) == -1) {
kutil_warn(NULL, NULL, "setrlimit");
return 0;
} else if (setrlimit(RLIMIT_NPROC, &rl_zero) == -1) {
kutil_warn(NULL, NULL, "setrlimit");
return 0;
}
rc = cap_enter();
if (rc && errno != ENOSYS) {
kutil_warn(NULL, NULL, "cap_enter");
rc = 0;
} else
rc = 1;
return rc;
}
int
ksandbox_capsicum_init_child(enum sandtype type,
int fd1, int fd2, int fdfiled, int fdaccept)
{
int rc;
switch (type) {
case SAND_WORKER:
rc = ksandbox_capsicum_init_worker(fd1, fd2);
break;
case SAND_CONTROL_OLD:
assert(fd2 == -1);
rc = ksandbox_capsicum_init_control
(fd1, fdfiled, fdaccept);
break;
case SAND_CONTROL_NEW:
assert(fd2 == -1);
rc = ksandbox_capsicum_init_control
(fd1, fdfiled, fdaccept);
break;
default:
abort();
}
if (!rc)
kutil_warnx(NULL, NULL, "capsicum sandbox failure");
return rc;
}
#else
int dummy;
#endif
|
d12d01a2f4e7630a2fe8226f3bfa027a80a857d4
|
7c857119fe1505b1d80d6e62969661c06dc1a2f4
|
/rEFIt_UEFI/libeg/BmLib.h
|
67eb7e53c62356e881fcd0d190ca9468d6764222
|
[
"BSD-2-Clause"
] |
permissive
|
CloverHackyColor/CloverBootloader
|
7042ca7dd6b513d22be591a295e49071ae1482ee
|
2711170df4f60b2ae5aa20add3e00f35cf57b7e5
|
refs/heads/master
| 2023-08-30T22:14:34.590134
| 2023-08-27T19:14:02
| 2023-08-27T19:14:02
| 205,810,121
| 4,734
| 770
|
BSD-2-Clause
| 2023-09-03T12:41:33
| 2019-09-02T08:22:14
|
C
|
UTF-8
|
C
| false
| false
| 4,898
|
h
|
BmLib.h
|
/*
* BmLib.h
*
* Created on: 10 Apr 2020
* Author: jief
*/
#ifndef LIBEG_BMLIB_H_
#define LIBEG_BMLIB_H_
extern "C" {
#include <Protocol/DevicePath.h>
#include <Guid/FileSystemVolumeLabelInfo.h>
#include <Guid/FileInfo.h>
#include <Guid/FileSystemInfo.h>
}
/**
Find the first instance of this Protocol
in the system and return it's interface.
@param ProtocolGuid Provides the protocol to search for
@param Interface On return, a pointer to the first interface
that matches ProtocolGuid
@retval EFI_SUCCESS A protocol instance matching ProtocolGuid was found
@retval EFI_NOT_FOUND No protocol instances were found that match ProtocolGuid
**/
EFI_STATUS
EfiLibLocateProtocol (
const EFI_GUID& ProtocolGuid,
OUT void **Interface
);
/**
Function opens and returns a file handle to the root directory of a volume.
@param DeviceHandle A handle for a device
@return A valid file handle or NULL is returned
**/
EFI_FILE*
EfiLibOpenRoot (
IN EFI_HANDLE DeviceHandle
);
/**
Function gets the file system information from an open file descriptor,
and stores it in a buffer allocated from pool.
@param FHand The file handle.
@return A pointer to a buffer with file information.
@retval NULL is returned if failed to get Volume Label Info.
**/
XStringW
EfiLibFileSystemVolumeLabelInfo (
const EFI_FILE* FHand
);
//Compare strings case insensitive
// return 0 if strings are equal not accounting match case
INTN
StriCmp (
IN CONST CHAR16 *FirstS,
IN CONST CHAR16 *SecondS
);
// If Null-terminated strings are case insensitive equal or its sSize symbols are equal then true
XBool
AsciiStriNCmp(
IN CONST CHAR8 *FirstS,
IN CONST CHAR8 *SecondS,
IN CONST UINTN sSize
);
// Case insensitive search of WhatString in WhereString
XBool
AsciiStrStriN (
IN CONST CHAR8 *WhatString,
IN CONST UINTN sWhatSize,
IN CONST CHAR8 *WhereString,
IN CONST UINTN sWhereSize
);
/**
Function gets the file information from an open file descriptor, and stores it
in a buffer allocated from pool.
@param FHand File Handle.
@return A pointer to a buffer with file information or NULL is returned
**/
EFI_FILE_INFO *
EfiLibFileInfo (
const EFI_FILE* FHand
);
EFI_FILE_SYSTEM_INFO *
EfiLibFileSystemInfo (
const EFI_FILE* FHand
);
/**
Function is used to determine the number of device path instances
that exist in a device path.
@param DevicePath A pointer to a device path data structure.
@return This function counts and returns the number of device path instances
in DevicePath.
**/
UINTN
EfiDevicePathInstanceCount (
IN EFI_DEVICE_PATH_PROTOCOL *DevicePath
);
/**
Adjusts the size of a previously allocated buffer.
@param OldPool - A pointer to the buffer whose size is being adjusted.
@param OldSize - The size of the current buffer.
@param NewSize - The size of the new buffer.
@return The newly allocated buffer.
@retval NULL Allocation failed.
**/
void *
EfiReallocatePool (
IN void *OldPool,
IN UINTN OldSize,
IN UINTN NewSize
);
/**
Compare two EFI_TIME data.
@param FirstTime - A pointer to the first EFI_TIME data.
@param SecondTime - A pointer to the second EFI_TIME data.
@retval true The FirstTime is not later than the SecondTime.
@retval false The FirstTime is later than the SecondTime.
**/
XBool
TimeCompare (
IN EFI_TIME *FirstTime,
IN EFI_TIME *SecondTime
);
/*
Translate VT-UTF8 characters into one Unicode character.
UTF8 Encoding Table
Bits per Character | Unicode Character Range | Unicode Binary Encoding | UTF8 Binary Encoding
0-7 | 0x0000 - 0x007F | 00000000 0xxxxxxx | 0xxxxxxx
8-11 | 0x0080 - 0x07FF | 00000xxx xxxxxxxx | 110xxxxx 10xxxxxx
12-16 | 0x0800 - 0xFFFF | xxxxxxxx xxxxxxxx | 1110xxxx 10xxxxxx 10xxxxxx
$ U+0024 10 0100 00100100 24
¢ U+00A2 1010 0010 11000010 10100010 C2 A2
€ U+20AC 0010 0000 1010 1100 11100010 10000010 10101100 E2 82 AC
𐍈 U+10348 1 0000 0011 0100 1000 11110000 10010000 10001101 10001000 F0 90 8D 88
*/
CHAR8* GetUnicodeChar(CHAR8 *s, CHAR16* UnicodeChar);
#endif /* LIBEG_BMLIB_H_ */
|
130de92d025c17764d4cdc5431f57e4044977081
|
64f63e6468d7d1a8239ca8a60cb3a57671d7026e
|
/include/modulemgr_nids.h
|
3e909aa18bc02fbf8915c04753d05953069aafc9
|
[
"BSD-3-Clause",
"MIT"
] |
permissive
|
uofw/uofw
|
511c6877af464a4c18cd62405805ed92b15b39c3
|
c517e4cee6679cf2c0ecb24afaa50a86c6460cf1
|
refs/heads/master
| 2023-02-09T17:10:03.719610
| 2023-02-03T13:11:50
| 2023-02-03T13:11:50
| 6,622,246
| 312
| 93
|
NOASSERTION
| 2023-09-05T19:54:15
| 2012-11-09T23:39:19
|
C
|
UTF-8
|
C
| false
| false
| 1,177
|
h
|
modulemgr_nids.h
|
/* Copyright (C) 2011 - 2015 The uOFW team
See the file COPYING for copying permission.
*/
#ifndef MODULEMGR_NIDS_H
#define MODULEMGR_NIDS_H
#ifdef __cplusplus
extern "C" {
#endif
/* function NIDs */
#define NID_MODULE_BOOTSTART 0xD3744BE0
#define NID_MODULE_REBOOT_PHASE 0xADF12745
#define NID_MODULE_REBOOT_BEFORE 0x2F064FA6
#define NID_MODULE_START 0xD632ACDB
#define NID_MODULE_STOP 0xCEE8593C
#define NID_592743D8 0x592743D8
/* variable NIDs*/
#define NID_MODULE_REBOOT_BEFORE_THREAD_PARAM 0xF4F4299D
#define NID_MODULE_START_THREAD_PARAM 0x0F7C276C
#define NID_MODULE_STOP_THREAD_PARAM 0xCF0CC697
#define NID_MODULE_INFO 0xF01D73A7
#define NID_MODULE_SDK_VERSION 0x11B97506
#define NID_1D4042A5 0x1D4042A5
#ifdef __cplusplus
}
#endif
#endif /* MODULEMGR_NIDS_H */
|
0916a17ac82e7b05319377831aea1f6457be1e7a
|
7eaf54a78c9e2117247cb2ab6d3a0c20719ba700
|
/SOFTWARE/A64-TERES/linux-a64/drivers/media/platform/s5p-mfc/s5p_mfc_pm.c
|
11d5f1dada32b1d593b53b0555f4ebcdb371b9d2
|
[
"LicenseRef-scancode-free-unknown",
"Apache-2.0",
"Linux-syscall-note",
"GPL-2.0-only",
"GPL-1.0-or-later"
] |
permissive
|
OLIMEX/DIY-LAPTOP
|
ae82f4ee79c641d9aee444db9a75f3f6709afa92
|
a3fafd1309135650bab27f5eafc0c32bc3ca74ee
|
refs/heads/rel3
| 2023-08-04T01:54:19.483792
| 2023-04-03T07:18:12
| 2023-04-03T07:18:12
| 80,094,055
| 507
| 92
|
Apache-2.0
| 2023-04-03T07:05:59
| 2017-01-26T07:25:50
|
C
|
UTF-8
|
C
| false
| false
| 2,295
|
c
|
s5p_mfc_pm.c
|
/*
* linux/drivers/media/platform/s5p-mfc/s5p_mfc_pm.c
*
* Copyright (c) 2010 Samsung Electronics Co., Ltd.
* http://www.samsung.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.
*/
#include <linux/clk.h>
#include <linux/err.h>
#include <linux/platform_device.h>
#ifdef CONFIG_PM_RUNTIME
#include <linux/pm_runtime.h>
#endif
#include "s5p_mfc_common.h"
#include "s5p_mfc_debug.h"
#include "s5p_mfc_pm.h"
#define MFC_GATE_CLK_NAME "mfc"
#define CLK_DEBUG
static struct s5p_mfc_pm *pm;
static struct s5p_mfc_dev *p_dev;
#ifdef CLK_DEBUG
static atomic_t clk_ref;
#endif
int s5p_mfc_init_pm(struct s5p_mfc_dev *dev)
{
int ret = 0;
pm = &dev->pm;
p_dev = dev;
pm->clock_gate = clk_get(&dev->plat_dev->dev, MFC_GATE_CLK_NAME);
if (IS_ERR(pm->clock_gate)) {
mfc_err("Failed to get clock-gating control\n");
ret = PTR_ERR(pm->clock_gate);
goto err_g_ip_clk;
}
ret = clk_prepare(pm->clock_gate);
if (ret) {
mfc_err("Failed to prepare clock-gating control\n");
goto err_p_ip_clk;
}
atomic_set(&pm->power, 0);
#ifdef CONFIG_PM_RUNTIME
pm->device = &dev->plat_dev->dev;
pm_runtime_enable(pm->device);
#endif
#ifdef CLK_DEBUG
atomic_set(&clk_ref, 0);
#endif
return 0;
err_p_ip_clk:
clk_put(pm->clock_gate);
err_g_ip_clk:
return ret;
}
void s5p_mfc_final_pm(struct s5p_mfc_dev *dev)
{
clk_unprepare(pm->clock_gate);
clk_put(pm->clock_gate);
#ifdef CONFIG_PM_RUNTIME
pm_runtime_disable(pm->device);
#endif
}
int s5p_mfc_clock_on(void)
{
int ret;
#ifdef CLK_DEBUG
atomic_inc(&clk_ref);
mfc_debug(3, "+ %d\n", atomic_read(&clk_ref));
#endif
ret = clk_enable(pm->clock_gate);
return ret;
}
void s5p_mfc_clock_off(void)
{
#ifdef CLK_DEBUG
atomic_dec(&clk_ref);
mfc_debug(3, "- %d\n", atomic_read(&clk_ref));
#endif
clk_disable(pm->clock_gate);
}
int s5p_mfc_power_on(void)
{
#ifdef CONFIG_PM_RUNTIME
return pm_runtime_get_sync(pm->device);
#else
atomic_set(&pm->power, 1);
return 0;
#endif
}
int s5p_mfc_power_off(void)
{
#ifdef CONFIG_PM_RUNTIME
return pm_runtime_put_sync(pm->device);
#else
atomic_set(&pm->power, 0);
return 0;
#endif
}
|
af07b95904e6a96ef8b1529e010a8d8787ebff2e
|
419fda15ef43c0e1bccfe4475ed782e318e5aee5
|
/zealbooter/lib/strlen.h
|
859589bd77ea901a11cf8b5f37eb08f6e9a4a889
|
[
"LicenseRef-scancode-public-domain",
"Unlicense"
] |
permissive
|
Zeal-Operating-System/ZealOS
|
a4390856d8c83705639f9231ab4dc5fe759765dd
|
b32f9cea7788a04012ea50b5cd501ba36746862e
|
refs/heads/master
| 2023-09-01T11:39:12.664185
| 2023-07-15T21:02:08
| 2023-07-15T21:02:08
| 381,741,497
| 941
| 74
|
Unlicense
| 2023-09-04T06:14:24
| 2021-06-30T15:05:22
|
HolyC
|
UTF-8
|
C
| false
| false
| 97
|
h
|
strlen.h
|
#ifndef __STRLEN_H__
#define __STRLEN_H__
size_t strlen(const char *s);
#endif // __STRLEN_H__
|
6ce058deffb68a85d484ea15171a8d6df568594f
|
722c0a166c811e66a4a77f6cd985e0ecf5140123
|
/src/str/vsprintf_s.c
|
69095c4b2c715d309b3be3ec8c3e11f7fac7f667
|
[
"MIT"
] |
permissive
|
rurban/safeclib
|
0fcb1f505cff4c4ff0a765e4ea9ff6b9082dfa72
|
3e943f7317448ab98046ed99d86d45e300224d12
|
refs/heads/master
| 2023-08-23T22:30:47.117025
| 2023-02-23T13:08:52
| 2023-02-23T13:08:52
| 88,128,310
| 282
| 69
|
NOASSERTION
| 2022-10-06T11:44:57
| 2017-04-13T05:29:04
|
C
|
UTF-8
|
C
| false
| false
| 4,778
|
c
|
vsprintf_s.c
|
/*------------------------------------------------------------------
* vsprintf_s.c
*
* August 2017, Reini Urban
* February 2018, Reini Urban
* November 2021, Reini Urban
*
* Copyright (c) 2017,2018,2021 by Reini Urban
* 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.
*------------------------------------------------------------------
*/
#ifdef FOR_DOXYGEN
#include "safe_str_lib.h"
#else
#include "safeclib_private.h"
#endif
/**
* @def vsprintf_s(dest,dmax,fmt,va_args)
* @brief
* The \b vsprintf_s function composes a string with the same content that
* would be printed if format was used on \c printf. Instead of being
* printed, the content is stored in dest.
* If dmax is zero, nothing is written and dest may be a null pointer,
* however the return value (number of bytes that would be written) is
* still calculated and returned.
*
* @remark SPECIFIED IN
* * C11 standard (ISO/IEC 9899:2011):
* K.3.5.3.13 The vsprintf_s function (p: 601)
* http://en.cppreference.com/w/c/io/vfprintf
*
* @param[out] dest pointer to string that will be written into.
* @param[in] dmax restricted maximum length of dest
* @param[in] fmt format-control string.
* @param[in] ap optional arguments
*
* @pre fmt shall not be a null pointer.
* @pre dmax shall not be greater than RSIZE_MAX_STR or the size of dest.
* @pre dmax shall not equal zero if dest is not null.
* @pre fmt shall not contain the conversion specifier %n
* @pre None of the arguments corresponding to %s is a null pointer (not yet)
* @pre No encoding error shall occur.
*
* @note C11 uses RSIZE_MAX, not RSIZE_MAX_STR.
*
* @return On success the total number of characters without the terminating
* \0 is returned.
* @return On failure a negative number is returned (deviating from C11).
* @return If dest is valid and too small for the formatted text,
* including the terminating null, then the buffer is cleared, and the
* invalid parameter handler is invoked.
*
* @retval -ESNULLP when \c fmt is NULL pointer, or
* when \c dest is NULL and dmax > 0, or
* when a \c %s argument is NULL
* @retval -ESZEROL when \c dmax = 0 and dest is not NULL
* @retval -ESLEMAX when \c dmax > \c RSIZE_MAX_STR
* @retval -EOVERFLOW when \c dmax > size of dest
* @retval -ESNOSPC when return value exceeds dmax unless dmax is zero and dest
* is NULL
* @retval -EINVAL when \c fmt contains \c %n
*
* @note The C11 standard was most likely wrong with changing the return value
* 0 on errors. All other functions and existing C11 implementations do return
* -1, so we return negative error codes. See the
* http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1141.pdf revision for their
* rationale. vsprintf_s does not set \c errno.
*
* @see
* sprintf_s(), vsnprintf_s()
*/
#ifdef FOR_DOXYGEN
int vsprintf_s(char *restrict dest, const rsize_t dmax,
const char *restrict fmt, va_list ap)
#else
EXPORT int _vsprintf_s_chk(char *restrict dest, const rsize_t dmax,
const size_t destbos, const char *restrict fmt,
va_list ap)
#endif
{
int ret;
ret = _vsnprintf_s_chk(dest, dmax, destbos, fmt, ap);
if (unlikely(dmax && ret >= (int)dmax)
#ifdef HAVE_MINGW32
|| (ret == -1 && errno == ERANGE)
#endif
) {
handle_error(dest, dmax, "vsprintf_s: len exceeds dmax", ESNOSPC);
#ifdef HAVE_MINGW32
errno = 0;
#endif
return -ESNOSPC; /* different to the standard (=0),
but like all other implementations */
}
return ret;
}
|
725e54eb9b0aca36aca0c0d0d1cb3bee91447025
|
e6da5a3210800cdfde59f3bbb7986ff3fc878598
|
/src/interfaces/ecpg/ecpglib/pg_type.h
|
1ffacf02c82101b108a414c8cb890a2b8ddafbde
|
[
"BSD-3-Clause",
"PostgreSQL",
"LicenseRef-scancode-unknown-license-reference",
"BSD-2-Clause"
] |
permissive
|
Tencent/TBase
|
b66f13583ce6cd02ee5d453e2ce5a3a61e8b8f13
|
7cf7f8afbcab7290538ad5e65893561710be3dfa
|
refs/heads/master
| 2023-09-04T03:27:38.289238
| 2023-03-09T12:02:41
| 2023-03-09T12:18:46
| 220,177,733
| 1,433
| 283
|
NOASSERTION
| 2023-07-31T07:31:58
| 2019-11-07T07:34:03
|
C
|
UTF-8
|
C
| false
| false
| 2,293
|
h
|
pg_type.h
|
/*-------------------------------------------------------------------------
*
* pg_type.h
* Hard-wired knowledge about some standard type OIDs.
*
* XXX keep this in sync with src/include/catalog/pg_type.h
*
* Portions Copyright (c) 1996-2017, PostgreSQL Global Development Group
* Portions Copyright (c) 1994, Regents of the University of California
*
* src/interfaces/ecpg/ecpglib/pg_type.h
*
*-------------------------------------------------------------------------
*/
#ifndef PG_TYPE_H
#define PG_TYPE_H
#define BOOLOID 16
#define BYTEAOID 17
#define CHAROID 18
#define NAMEOID 19
#define INT8OID 20
#define INT2OID 21
#define INT2VECTOROID 22
#define INT4OID 23
#define REGPROCOID 24
#define TEXTOID 25
#define OIDOID 26
#define TIDOID 27
#define XIDOID 28
#define CIDOID 29
#define OIDVECTOROID 30
#define POINTOID 600
#define LSEGOID 601
#define PATHOID 602
#define BOXOID 603
#define POLYGONOID 604
#define LINEOID 628
#define FLOAT4OID 700
#define FLOAT8OID 701
#define ABSTIMEOID 702
#define RELTIMEOID 703
#define TINTERVALOID 704
#define UNKNOWNOID 705
#define CIRCLEOID 718
#define CASHOID 790
#define INETOID 869
#define CIDROID 650
#define BPCHAROID 1042
#define VARCHAROID 1043
#define DATEOID 1082
#define TIMEOID 1083
#define TIMESTAMPOID 1114
#define TIMESTAMPTZOID 1184
#define INTERVALOID 1186
#define TIMETZOID 1266
#define ZPBITOID 1560
#define VARBITOID 1562
#define NUMERICOID 1700
#define REFCURSOROID 1790
#define REGPROCEDUREOID 2202
#define REGOPEROID 2203
#define REGOPERATOROID 2204
#define REGCLASSOID 2205
#define REGTYPEOID 2206
#define REGROLEOID 4096
#define REGNAMESPACEOID 4089
#define REGTYPEARRAYOID 2211
#define UUIDOID 2950
#define LSNOID 3220
#define TSVECTOROID 3614
#define GTSVECTOROID 3642
#define TSQUERYOID 3615
#define REGCONFIGOID 3734
#define REGDICTIONARYOID 3769
#define JSONBOID 3802
#define INT4RANGEOID 3904
#endif /* PG_TYPE_H */
|
793c536d73497f57f78cdda82e4581136f386b00
|
c26d7b0ed875357278e61627da2da0650da77986
|
/src/games/trek/attack.c
|
4323e6a4e4b53e46c45849827683f8205420436c
|
[
"BSD-3-Clause"
] |
permissive
|
RetroBSD/retrobsd
|
5343d9e3c424637fc3ad5b03fe720b2744490025
|
486f81f6abff01c7dcc207235cd2979b226a95ff
|
refs/heads/master
| 2023-09-02T23:12:05.110883
| 2023-07-07T18:41:40
| 2023-07-07T18:41:40
| 18,598,087
| 282
| 59
|
BSD-3-Clause
| 2023-07-18T07:35:36
| 2014-04-09T13:25:46
|
C
|
UTF-8
|
C
| false
| false
| 4,217
|
c
|
attack.c
|
/*
* Copyright (c) 1980 Regents of the University of California.
* All rights reserved. The Berkeley software License Agreement
* specifies the terms and conditions for redistribution.
*/
# include "trek.h"
/*
** Klingon Attack Routine
**
** This routine performs the Klingon attack provided that
** (1) Something happened this move (i.e., not free), and
** (2) You are not cloaked. Note that if you issue the
** cloak command, you are not considered cloaked until you
** expend some time.
**
** Klingons are permitted to move both before and after the
** attack. They will tend to move toward you before the
** attack and away from you after the attack.
**
** Under certain conditions you can get a critical hit. This
** sort of hit damages devices. The probability that a given
** device is damaged depends on the device. Well protected
** devices (such as the computer, which is in the core of the
** ship and has considerable redundancy) almost never get
** damaged, whereas devices which are exposed (such as the
** warp engines) or which are particularly delicate (such as
** the transporter) have a much higher probability of being
** damaged.
**
** The actual amount of damage (i.e., how long it takes to fix
** it) depends on the amount of the hit and the "damfac[]"
** entry for the particular device.
**
** Casualties can also occur.
*/
void
attack(resting)
int resting; /* set if attack while resting */
{
register int hit, i, l;
int maxhit, tothit, shldabsb;
double chgfac, propor, extradm;
double dustfac, tothe;
int cas;
int hitflag;
if (Move.free)
return;
if (Etc.nkling <= 0 || Quad[Ship.quadx][Ship.quady].stars < 0)
return;
if (Ship.cloaked && Ship.cloakgood)
return;
/* move before attack */
klmove(0);
if (Ship.cond == DOCKED)
{
if (!resting)
printf("Starbase shields protect the %s\n", Ship.shipname);
return;
}
/* setup shield effectiveness */
chgfac = 1.0;
if (Move.shldchg)
chgfac = 0.25 + 0.50 * franf();
maxhit = tothit = 0;
hitflag = 0;
/* let each Klingon do his damndest */
for (i = 0; i < Etc.nkling; i++)
{
/* if he's low on power he won't attack */
if (Etc.klingon[i].power < 20)
continue;
if (!hitflag)
{
printf("\nStardate %.2f: Klingon attack:\n",
Now.date);
hitflag++;
}
/* complete the hit */
dustfac = 0.90 + 0.01 * franf();
tothe = Etc.klingon[i].avgdist;
hit = Etc.klingon[i].power * pow(dustfac, tothe) * Param.hitfac;
/* deplete his energy */
dustfac = Etc.klingon[i].power;
Etc.klingon[i].power = dustfac * Param.phasfac * (1.0 + (franf() - 0.5) * 0.2);
/* see how much of hit shields will absorb */
shldabsb = 0;
if (Ship.shldup || Move.shldchg)
{
propor = Ship.shield;
propor /= Param.shield;
shldabsb = propor * chgfac * hit;
if (shldabsb > Ship.shield)
shldabsb = Ship.shield;
Ship.shield -= shldabsb;
}
/* actually do the hit */
printf("HIT: %d units", hit);
if (!damaged(SRSCAN))
printf(" from %d,%d", Etc.klingon[i].x, Etc.klingon[i].y);
cas = (shldabsb * 100) / hit;
hit -= shldabsb;
if (shldabsb > 0)
printf(", shields absorb %d%%, effective hit %d\n",
cas, hit);
else
printf("\n");
tothit += hit;
if (hit > maxhit)
maxhit = hit;
Ship.energy -= hit;
/* see if damages occurred */
if (hit >= (15 - Game.skill) * (25 - ranf(12)))
{
printf("CRITICAL HIT!!!\n");
/* select a device from probability vector */
cas = ranf(1000);
for (l = 0; cas >= 0; l++)
cas -= Param.damprob[l];
l -= 1;
/* compute amount of damage */
extradm = (hit * Param.damfac[l]) / (75 + ranf(25)) + 0.5;
/* damage the device */
damage(l, extradm);
if (damaged(SHIELD))
{
if (Ship.shldup)
printf("Sulu: Shields knocked down, captain.\n");
Ship.shldup = 0;
Move.shldchg = 0;
}
}
if (Ship.energy <= 0)
lose(L_DSTRYD);
}
/* see what our casualities are like */
if (maxhit >= 200 || tothit >= 500)
{
cas = tothit * 0.015 * franf();
if (cas >= 2)
{
printf("McCoy: we suffered %d casualties in that attack.\n",
cas);
Game.deaths += cas;
Ship.crew -= cas;
}
}
/* allow Klingons to move after attacking */
klmove(1);
return;
}
|
84da3186bf7ac88936e96fd3091597fc336f6d26
|
79d343002bb63a44f8ab0dbac0c9f4ec54078c3a
|
/lib/libc/wasi/libc-top-half/musl/src/stdio/vswprintf.c
|
bf9bcaf3a2a162a3f1939834f9288a694a758be9
|
[
"BSD-3-Clause",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause",
"LicenseRef-scancode-other-permissive",
"LicenseRef-scancode-musl-exception",
"MIT",
"LLVM-exception",
"Apache-2.0",
"NCSA"
] |
permissive
|
ziglang/zig
|
4aa75d8d3bcc9e39bf61d265fd84b7f005623fc5
|
f4c9e19bc3213c2bc7e03d7b06d7129882f39f6c
|
refs/heads/master
| 2023-08-31T13:16:45.980913
| 2023-08-31T05:50:29
| 2023-08-31T05:50:29
| 40,276,274
| 25,560
| 2,399
|
MIT
| 2023-09-14T21:09:50
| 2015-08-06T00:51:28
|
Zig
|
UTF-8
|
C
| false
| false
| 1,160
|
c
|
vswprintf.c
|
#include "stdio_impl.h"
#include <limits.h>
#include <errno.h>
#include <stdint.h>
#include <stdlib.h>
#include <wchar.h>
struct cookie {
wchar_t *ws;
size_t l;
};
static size_t sw_write(FILE *f, const unsigned char *s, size_t l)
{
size_t l0 = l;
int i = 0;
struct cookie *c = f->cookie;
if (s!=f->wbase && sw_write(f, f->wbase, f->wpos-f->wbase)==-1)
return -1;
while (c->l && l && (i=mbtowc(c->ws, (void *)s, l))>=0) {
s+=i;
l-=i;
c->l--;
c->ws++;
}
*c->ws = 0;
if (i < 0) {
f->wpos = f->wbase = f->wend = 0;
f->flags |= F_ERR;
return i;
}
f->wend = f->buf + f->buf_size;
f->wpos = f->wbase = f->buf;
return l0;
}
int vswprintf(wchar_t *restrict s, size_t n, const wchar_t *restrict fmt, va_list ap)
{
int r;
unsigned char buf[256];
struct cookie c = { s, n-1 };
FILE f = {
.lbf = EOF,
.write = sw_write,
#if defined(__wasilibc_unmodified_upstream) || defined(_REENTRANT)
.lock = -1,
#endif
.buf = buf,
.buf_size = sizeof buf,
.cookie = &c,
};
if (!n) {
return -1;
} else if (n > INT_MAX) {
errno = EOVERFLOW;
return -1;
}
r = vfwprintf(&f, fmt, ap);
sw_write(&f, 0, 0);
return r>=n ? -1 : r;
}
|
9d4c90c86146caf3a106417ee817206e817344ac
|
4c690b473a2fd8baa53377195933c2b996a01244
|
/net.c
|
57d4dff24dbe1d7776570adfef8a58204a91d984
|
[
"BSD-3-Clause"
] |
permissive
|
NLnetLabs/ldns
|
77bdf4bf6f814fe8d7e274a1754e9bbf23ae0a4a
|
67b9f0ae98910df882ca77f503673929a9e1db9b
|
refs/heads/develop
| 2023-08-28T07:19:23.088018
| 2023-06-03T13:08:41
| 2023-06-03T13:09:04
| 72,740,793
| 248
| 103
|
BSD-3-Clause
| 2023-09-14T14:40:58
| 2016-11-03T11:57:12
|
C
|
UTF-8
|
C
| false
| false
| 24,586
|
c
|
net.c
|
/*
* net.c
*
* Network implementation
* All network related functions are grouped here
*
* a Net::DNS like library for C
*
* (c) NLnet Labs, 2004-2006
*
* See the file LICENSE for the license
*/
#include <ldns/config.h>
#include <ldns/ldns.h>
#ifdef HAVE_NETINET_IN_H
#include <netinet/in.h>
#endif
#ifdef HAVE_SYS_SOCKET_H
#include <sys/socket.h>
#endif
#ifdef HAVE_NETDB_H
#include <netdb.h>
#endif
#ifdef HAVE_ARPA_INET_H
#include <arpa/inet.h>
#endif
#include <sys/time.h>
#include <errno.h>
#include <fcntl.h>
#ifdef HAVE_POLL
#include <poll.h>
#endif
ldns_status
ldns_send(ldns_pkt **result_packet, ldns_resolver *r, const ldns_pkt *query_pkt)
{
ldns_buffer *qb;
ldns_status result;
ldns_rdf *tsig_mac = NULL;
qb = ldns_buffer_new(LDNS_MIN_BUFLEN);
if (query_pkt && ldns_pkt_tsig(query_pkt)) {
tsig_mac = ldns_rr_rdf(ldns_pkt_tsig(query_pkt), 3);
}
if (!query_pkt ||
ldns_pkt2buffer_wire(qb, query_pkt) != LDNS_STATUS_OK) {
result = LDNS_STATUS_ERR;
} else {
result = ldns_send_buffer(result_packet, r, qb, tsig_mac);
}
ldns_buffer_free(qb);
return result;
}
/* code from rdata.c */
static struct sockaddr_storage *
ldns_rdf2native_sockaddr_storage_port(
const ldns_rdf *rd, uint16_t port, size_t *size)
{
struct sockaddr_storage *data;
struct sockaddr_in *data_in;
struct sockaddr_in6 *data_in6;
data = LDNS_MALLOC(struct sockaddr_storage);
if (!data) {
return NULL;
}
/* zero the structure for portability */
memset(data, 0, sizeof(struct sockaddr_storage));
switch(ldns_rdf_get_type(rd)) {
case LDNS_RDF_TYPE_A:
#ifndef S_SPLINT_S
data->ss_family = AF_INET;
#endif
data_in = (struct sockaddr_in*) data;
data_in->sin_port = (in_port_t)htons(port);
memcpy(&(data_in->sin_addr), ldns_rdf_data(rd), ldns_rdf_size(rd));
*size = sizeof(struct sockaddr_in);
return data;
case LDNS_RDF_TYPE_AAAA:
#ifndef S_SPLINT_S
data->ss_family = AF_INET6;
#endif
data_in6 = (struct sockaddr_in6*) data;
data_in6->sin6_port = (in_port_t)htons(port);
memcpy(&data_in6->sin6_addr, ldns_rdf_data(rd), ldns_rdf_size(rd));
*size = sizeof(struct sockaddr_in6);
return data;
default:
LDNS_FREE(data);
return NULL;
}
}
struct sockaddr_storage *
ldns_rdf2native_sockaddr_storage(
const ldns_rdf *rd, uint16_t port, size_t *size)
{
return ldns_rdf2native_sockaddr_storage_port(
rd, (port == 0 ? (uint16_t)LDNS_PORT : port), size);
}
/** best effort to set nonblocking */
static void
ldns_sock_nonblock(int sockfd)
{
#ifdef HAVE_FCNTL
int flag;
if((flag = fcntl(sockfd, F_GETFL)) != -1) {
flag |= O_NONBLOCK;
if(fcntl(sockfd, F_SETFL, flag) == -1) {
/* ignore error, continue blockingly */
}
}
#elif defined(HAVE_IOCTLSOCKET)
unsigned long on = 1;
if(ioctlsocket(sockfd, FIONBIO, &on) != 0) {
/* ignore error, continue blockingly */
}
#endif
}
/** best effort to set blocking */
static void
ldns_sock_block(int sockfd)
{
#ifdef HAVE_FCNTL
int flag;
if((flag = fcntl(sockfd, F_GETFL)) != -1) {
flag &= ~O_NONBLOCK;
if(fcntl(sockfd, F_SETFL, flag) == -1) {
/* ignore error, continue */
}
}
#elif defined(HAVE_IOCTLSOCKET)
unsigned long off = 0;
if(ioctlsocket(sockfd, FIONBIO, &off) != 0) {
/* ignore error, continue */
}
#endif
}
/** wait for a socket to become ready */
static int
ldns_sock_wait(int sockfd, struct timeval timeout, int write)
{
int ret;
#ifndef HAVE_POLL
#ifndef S_SPLINT_S
fd_set fds;
FD_ZERO(&fds);
FD_SET(FD_SET_T sockfd, &fds);
if(write)
ret = select(sockfd+1, NULL, &fds, NULL, &timeout);
else
ret = select(sockfd+1, &fds, NULL, NULL, &timeout);
#endif
#else
struct pollfd pfds[2];
memset(&pfds[0], 0, sizeof(pfds[0]) * 2);
pfds[0].fd = sockfd;
pfds[0].events = POLLIN|POLLERR;
if (write) {
pfds[0].events |= POLLOUT;
}
ret = poll(pfds, 1, (int)(timeout.tv_sec * 1000
+ timeout.tv_usec / 1000));
#endif
if(ret == 0)
/* timeout expired */
return 0;
else if(ret == -1)
/* error */
return 0;
return 1;
}
static int
ldns_tcp_connect_from(const struct sockaddr_storage *to, socklen_t tolen,
const struct sockaddr_storage *from, socklen_t fromlen,
struct timeval timeout)
{
int sockfd;
#ifndef S_SPLINT_S
if ((sockfd = socket((int)((struct sockaddr*)to)->sa_family, SOCK_STREAM,
IPPROTO_TCP)) == SOCK_INVALID) {
return -1;
}
#endif
if (from && bind(sockfd, (const struct sockaddr*)from, fromlen) == SOCK_INVALID){
close_socket(sockfd);
return -1;
}
/* perform nonblocking connect, to be able to wait with select() */
ldns_sock_nonblock(sockfd);
if (connect(sockfd, (struct sockaddr*)to, tolen) == SOCK_INVALID) {
#ifndef USE_WINSOCK
#ifdef EINPROGRESS
if(errno != EINPROGRESS) {
#else
if(1) {
#endif
close_socket(sockfd);
return -1;
}
#else /* USE_WINSOCK */
if(WSAGetLastError() != WSAEINPROGRESS &&
WSAGetLastError() != WSAEWOULDBLOCK) {
close_socket(sockfd);
return -1;
}
#endif
/* error was only telling us that it would block */
}
/* wait(write) until connected or error */
while(1) {
int error = 0;
socklen_t len = (socklen_t)sizeof(error);
if(!ldns_sock_wait(sockfd, timeout, 1)) {
close_socket(sockfd);
return -1;
}
/* check if there is a pending error for nonblocking connect */
if(getsockopt(sockfd, SOL_SOCKET, SO_ERROR, (void*)&error,
&len) < 0) {
#ifndef USE_WINSOCK
error = errno; /* on solaris errno is error */
#else
error = WSAGetLastError();
#endif
}
#ifndef USE_WINSOCK
#if defined(EINPROGRESS) && defined(EWOULDBLOCK)
if(error == EINPROGRESS || error == EWOULDBLOCK)
continue; /* try again */
#endif
else if(error != 0) {
close_socket(sockfd);
/* error in errno for our user */
errno = error;
return -1;
}
#else /* USE_WINSOCK */
if(error == WSAEINPROGRESS)
continue;
else if(error == WSAEWOULDBLOCK)
continue;
else if(error != 0) {
close_socket(sockfd);
errno = error;
return -1;
}
#endif /* USE_WINSOCK */
/* connected */
break;
}
/* set the socket blocking again */
ldns_sock_block(sockfd);
return sockfd;
}
int
ldns_tcp_connect(const struct sockaddr_storage *to, socklen_t tolen,
struct timeval timeout)
{
int s = ldns_tcp_connect_from(to, tolen, NULL, 0, timeout);
return s > 0 ? s : 0;
}
int
ldns_tcp_connect2(const struct sockaddr_storage *to, socklen_t tolen,
struct timeval timeout)
{
return ldns_tcp_connect_from(to, tolen, NULL, 0, timeout);
}
static int
ldns_tcp_bgsend_from(ldns_buffer *qbin,
const struct sockaddr_storage *to, socklen_t tolen,
const struct sockaddr_storage *from, socklen_t fromlen,
struct timeval timeout)
{
int sockfd;
sockfd = ldns_tcp_connect_from(to, tolen, from, fromlen, timeout);
if (sockfd >= 0 && ldns_tcp_send_query(qbin, sockfd, to, tolen) == 0) {
close_socket(sockfd);
return -1;
}
return sockfd;
}
int
ldns_tcp_bgsend(ldns_buffer *qbin,
const struct sockaddr_storage *to, socklen_t tolen,
struct timeval timeout)
{
int s = ldns_tcp_bgsend_from(qbin, to, tolen, NULL, 0, timeout);
return s > 0 ? s : 0;
}
int
ldns_tcp_bgsend2(ldns_buffer *qbin,
const struct sockaddr_storage *to, socklen_t tolen,
struct timeval timeout)
{
return ldns_tcp_bgsend_from(qbin, to, tolen, NULL, 0, timeout);
}
/* keep in mind that in DNS tcp messages the first 2 bytes signal the
* amount data to expect
*/
static ldns_status
ldns_tcp_send_from(uint8_t **result, ldns_buffer *qbin,
const struct sockaddr_storage *to, socklen_t tolen,
const struct sockaddr_storage *from, socklen_t fromlen,
struct timeval timeout, size_t *answer_size)
{
int sockfd;
uint8_t *answer;
sockfd = ldns_tcp_bgsend_from(qbin, to, tolen, from, fromlen, timeout);
if (sockfd == -1) {
return LDNS_STATUS_ERR;
}
answer = ldns_tcp_read_wire_timeout(sockfd, answer_size, timeout);
close_socket(sockfd);
if (!answer) {
/* oops */
return LDNS_STATUS_NETWORK_ERR;
}
*result = answer;
return LDNS_STATUS_OK;
}
ldns_status
ldns_tcp_send(uint8_t **result, ldns_buffer *qbin,
const struct sockaddr_storage *to, socklen_t tolen,
struct timeval timeout, size_t *answer_size)
{
return ldns_tcp_send_from(result, qbin,
to, tolen, NULL, 0, timeout, answer_size);
}
int
ldns_udp_connect(const struct sockaddr_storage *to, struct timeval ATTR_UNUSED(timeout))
{
int sockfd;
#ifndef S_SPLINT_S
if ((sockfd = socket((int)((struct sockaddr*)to)->sa_family, SOCK_DGRAM,
IPPROTO_UDP))
== SOCK_INVALID) {
return 0;
}
#endif
return sockfd;
}
int
ldns_udp_connect2(const struct sockaddr_storage *to, struct timeval ATTR_UNUSED(timeout))
{
int sockfd;
#ifndef S_SPLINT_S
if ((sockfd = socket((int)((struct sockaddr*)to)->sa_family, SOCK_DGRAM,
IPPROTO_UDP))
== SOCK_INVALID) {
return -1;
}
#endif
return sockfd;
}
static int
ldns_udp_bgsend_from(ldns_buffer *qbin,
const struct sockaddr_storage *to , socklen_t tolen,
const struct sockaddr_storage *from, socklen_t fromlen,
struct timeval timeout)
{
int sockfd;
sockfd = ldns_udp_connect2(to, timeout);
if (sockfd == -1) {
return -1;
}
if (from && bind(sockfd, (const struct sockaddr*)from, fromlen) == -1){
close_socket(sockfd);
return -1;
}
if (ldns_udp_send_query(qbin, sockfd, to, tolen) == 0) {
close_socket(sockfd);
return -1;
}
return sockfd;
}
int
ldns_udp_bgsend(ldns_buffer *qbin,
const struct sockaddr_storage *to , socklen_t tolen,
struct timeval timeout)
{
int s = ldns_udp_bgsend_from(qbin, to, tolen, NULL, 0, timeout);
return s > 0 ? s : 0;
}
int
ldns_udp_bgsend2(ldns_buffer *qbin,
const struct sockaddr_storage *to , socklen_t tolen,
struct timeval timeout)
{
return ldns_udp_bgsend_from(qbin, to, tolen, NULL, 0, timeout);
}
static ldns_status
ldns_udp_send_from(uint8_t **result, ldns_buffer *qbin,
const struct sockaddr_storage *to , socklen_t tolen,
const struct sockaddr_storage *from, socklen_t fromlen,
struct timeval timeout, size_t *answer_size)
{
int sockfd;
uint8_t *answer;
sockfd = ldns_udp_bgsend_from(qbin, to, tolen, from, fromlen, timeout);
if (sockfd == -1) {
return LDNS_STATUS_SOCKET_ERROR;
}
/* wait for an response*/
if(!ldns_sock_wait(sockfd, timeout, 0)) {
close_socket(sockfd);
return LDNS_STATUS_NETWORK_ERR;
}
/* set to nonblocking, so if the checksum is bad, it becomes
* an EAGAIN error and the ldns_udp_send function does not block,
* but returns a 'NETWORK_ERROR' much like a timeout. */
ldns_sock_nonblock(sockfd);
answer = ldns_udp_read_wire(sockfd, answer_size, NULL, NULL);
close_socket(sockfd);
if (!answer) {
/* oops */
return LDNS_STATUS_NETWORK_ERR;
}
*result = answer;
return LDNS_STATUS_OK;
}
ldns_status
ldns_udp_send(uint8_t **result, ldns_buffer *qbin,
const struct sockaddr_storage *to , socklen_t tolen,
struct timeval timeout, size_t *answer_size)
{
return ldns_udp_send_from(result, qbin, to, tolen, NULL, 0,
timeout, answer_size);
}
ldns_status
ldns_send_buffer(ldns_pkt **result, ldns_resolver *r, ldns_buffer *qb, ldns_rdf *tsig_mac)
{
uint8_t i;
struct sockaddr_storage *src = NULL;
size_t src_len = 0;
struct sockaddr_storage *ns;
size_t ns_len;
struct timeval tv_s;
struct timeval tv_e;
ldns_rdf **ns_array;
size_t *rtt;
ldns_pkt *reply;
bool all_servers_rtt_inf;
uint8_t retries;
uint8_t *reply_bytes = NULL;
size_t reply_size = 0;
ldns_status status, send_status;
assert(r != NULL);
status = LDNS_STATUS_OK;
rtt = ldns_resolver_rtt(r);
ns_array = ldns_resolver_nameservers(r);
reply = NULL;
ns_len = 0;
all_servers_rtt_inf = true;
if (ldns_resolver_random(r)) {
ldns_resolver_nameservers_randomize(r);
}
if(ldns_resolver_source(r)) {
src = ldns_rdf2native_sockaddr_storage_port(
ldns_resolver_source(r), 0, &src_len);
}
/* loop through all defined nameservers */
for (i = 0; i < ldns_resolver_nameserver_count(r); i++) {
if (rtt[i] == LDNS_RESOLV_RTT_INF) {
/* not reachable nameserver! */
continue;
}
/* maybe verbosity setting?
printf("Sending to ");
ldns_rdf_print(stdout, ns_array[i]);
printf("\n");
*/
ns = ldns_rdf2native_sockaddr_storage(ns_array[i],
ldns_resolver_port(r), &ns_len);
#ifndef S_SPLINT_S
if ((ns->ss_family == AF_INET) &&
(ldns_resolver_ip6(r) == LDNS_RESOLV_INET6)) {
/* not reachable */
LDNS_FREE(ns);
continue;
}
if ((ns->ss_family == AF_INET6) &&
(ldns_resolver_ip6(r) == LDNS_RESOLV_INET)) {
/* not reachable */
LDNS_FREE(ns);
continue;
}
#endif
all_servers_rtt_inf = false;
gettimeofday(&tv_s, NULL);
send_status = LDNS_STATUS_ERR;
/* reply_bytes implicitly handles our error */
if (ldns_resolver_usevc(r)) {
for (retries = ldns_resolver_retry(r); retries > 0; retries--) {
send_status =
ldns_tcp_send_from(&reply_bytes, qb,
ns, (socklen_t)ns_len,
src, (socklen_t)src_len,
ldns_resolver_timeout(r),
&reply_size);
if (send_status == LDNS_STATUS_OK) {
break;
}
}
} else {
for (retries = ldns_resolver_retry(r); retries > 0; retries--) {
/* ldns_rdf_print(stdout, ns_array[i]); */
send_status =
ldns_udp_send_from(&reply_bytes, qb,
ns, (socklen_t)ns_len,
src, (socklen_t)src_len,
ldns_resolver_timeout(r),
&reply_size);
if (send_status == LDNS_STATUS_OK) {
break;
}
}
}
if (send_status != LDNS_STATUS_OK) {
ldns_resolver_set_nameserver_rtt(r, i, LDNS_RESOLV_RTT_INF);
status = send_status;
}
/* obey the fail directive */
if (!reply_bytes) {
/* the current nameserver seems to have a problem, blacklist it */
if (ldns_resolver_fail(r)) {
if(src) {
LDNS_FREE(src);
}
LDNS_FREE(ns);
return LDNS_STATUS_ERR;
} else {
LDNS_FREE(ns);
continue;
}
}
status = ldns_wire2pkt(&reply, reply_bytes, reply_size);
if (status != LDNS_STATUS_OK) {
if(src) LDNS_FREE(src);
LDNS_FREE(reply_bytes);
LDNS_FREE(ns);
return status;
}
assert(reply);
LDNS_FREE(ns);
gettimeofday(&tv_e, NULL);
if (reply) {
ldns_pkt_set_querytime(reply, (uint32_t)
((tv_e.tv_sec - tv_s.tv_sec) * 1000) +
(tv_e.tv_usec - tv_s.tv_usec) / 1000);
ldns_pkt_set_answerfrom(reply,
ldns_rdf_clone(ns_array[i]));
ldns_pkt_set_timestamp(reply, tv_s);
ldns_pkt_set_size(reply, reply_size);
break;
} else {
if (ldns_resolver_fail(r)) {
/* if fail is set bail out, after the first
* one */
break;
}
}
/* wait retrans seconds... */
sleep((unsigned int) ldns_resolver_retrans(r));
}
if(src) {
LDNS_FREE(src);
}
if (all_servers_rtt_inf) {
LDNS_FREE(reply_bytes);
return LDNS_STATUS_RES_NO_NS;
}
#ifdef HAVE_SSL
if (tsig_mac && reply && reply_bytes) {
if (!ldns_pkt_tsig_verify(reply,
reply_bytes,
reply_size,
ldns_resolver_tsig_keyname(r),
ldns_resolver_tsig_keydata(r), tsig_mac)) {
status = LDNS_STATUS_CRYPTO_TSIG_BOGUS;
}
}
#else
(void)tsig_mac;
#endif /* HAVE_SSL */
LDNS_FREE(reply_bytes);
if (result) {
*result = reply;
}
return status;
}
ssize_t
ldns_tcp_send_query(ldns_buffer *qbin, int sockfd,
const struct sockaddr_storage *to, socklen_t tolen)
{
uint8_t *sendbuf;
ssize_t bytes;
/* add length of packet */
sendbuf = LDNS_XMALLOC(uint8_t, ldns_buffer_position(qbin) + 2);
if(!sendbuf) return 0;
ldns_write_uint16(sendbuf, ldns_buffer_position(qbin));
memcpy(sendbuf + 2, ldns_buffer_begin(qbin), ldns_buffer_position(qbin));
bytes = sendto(sockfd, (void*)sendbuf,
ldns_buffer_position(qbin) + 2, 0, (struct sockaddr *)to, tolen);
LDNS_FREE(sendbuf);
if (bytes == -1 || (size_t) bytes != ldns_buffer_position(qbin) + 2 ) {
return 0;
}
return bytes;
}
/* don't wait for an answer */
ssize_t
ldns_udp_send_query(ldns_buffer *qbin, int sockfd, const struct sockaddr_storage *to,
socklen_t tolen)
{
ssize_t bytes;
bytes = sendto(sockfd, (void*)ldns_buffer_begin(qbin),
ldns_buffer_position(qbin), 0, (struct sockaddr *)to, tolen);
if (bytes == -1 || (size_t)bytes != ldns_buffer_position(qbin)) {
return 0;
}
return bytes;
}
uint8_t *
ldns_udp_read_wire(int sockfd, size_t *size, struct sockaddr_storage *from,
socklen_t *fromlen)
{
uint8_t *wire, *wireout;
ssize_t wire_size;
wire = LDNS_XMALLOC(uint8_t, LDNS_MAX_PACKETLEN);
if (!wire) {
*size = 0;
return NULL;
}
wire_size = recvfrom(sockfd, (void*)wire, LDNS_MAX_PACKETLEN, 0,
(struct sockaddr *)from, fromlen);
/* recvfrom can also return 0 */
if (wire_size == -1 || wire_size == 0) {
*size = 0;
LDNS_FREE(wire);
return NULL;
}
*size = (size_t)wire_size;
wireout = LDNS_XREALLOC(wire, uint8_t, (size_t)wire_size);
if(!wireout) LDNS_FREE(wire);
return wireout;
}
uint8_t *
ldns_tcp_read_wire_timeout(int sockfd, size_t *size, struct timeval timeout)
{
uint8_t *wire;
uint16_t wire_size;
ssize_t bytes = 0, rc = 0;
wire = LDNS_XMALLOC(uint8_t, 2);
if (!wire) {
*size = 0;
return NULL;
}
while (bytes < 2) {
if(!ldns_sock_wait(sockfd, timeout, 0)) {
*size = 0;
LDNS_FREE(wire);
return NULL;
}
rc = recv(sockfd, (void*) (wire + bytes),
(size_t) (2 - bytes), 0);
if (rc == -1 || rc == 0) {
*size = 0;
LDNS_FREE(wire);
return NULL;
}
bytes += rc;
}
wire_size = ldns_read_uint16(wire);
LDNS_FREE(wire);
wire = LDNS_XMALLOC(uint8_t, wire_size);
if (!wire) {
*size = 0;
return NULL;
}
bytes = 0;
while (bytes < (ssize_t) wire_size) {
if(!ldns_sock_wait(sockfd, timeout, 0)) {
*size = 0;
LDNS_FREE(wire);
return NULL;
}
rc = recv(sockfd, (void*) (wire + bytes),
(size_t) (wire_size - bytes), 0);
if (rc == -1 || rc == 0) {
LDNS_FREE(wire);
*size = 0;
return NULL;
}
bytes += rc;
}
*size = (size_t) bytes;
return wire;
}
uint8_t *
ldns_tcp_read_wire(int sockfd, size_t *size)
{
uint8_t *wire;
uint16_t wire_size;
ssize_t bytes = 0, rc = 0;
wire = LDNS_XMALLOC(uint8_t, 2);
if (!wire) {
*size = 0;
return NULL;
}
while (bytes < 2) {
rc = recv(sockfd, (void*) (wire + bytes),
(size_t) (2 - bytes), 0);
if (rc == -1 || rc == 0) {
*size = 0;
LDNS_FREE(wire);
return NULL;
}
bytes += rc;
}
wire_size = ldns_read_uint16(wire);
LDNS_FREE(wire);
wire = LDNS_XMALLOC(uint8_t, wire_size);
if (!wire) {
*size = 0;
return NULL;
}
bytes = 0;
while (bytes < (ssize_t) wire_size) {
rc = recv(sockfd, (void*) (wire + bytes),
(size_t) (wire_size - bytes), 0);
if (rc == -1 || rc == 0) {
LDNS_FREE(wire);
*size = 0;
return NULL;
}
bytes += rc;
}
*size = (size_t) bytes;
return wire;
}
#ifndef S_SPLINT_S
ldns_rdf *
ldns_sockaddr_storage2rdf(const struct sockaddr_storage *sock, uint16_t *port)
{
ldns_rdf *addr;
struct sockaddr_in *data_in;
struct sockaddr_in6 *data_in6;
switch(sock->ss_family) {
case AF_INET:
data_in = (struct sockaddr_in*)sock;
if (port) {
*port = ntohs((uint16_t)data_in->sin_port);
}
addr = ldns_rdf_new_frm_data(LDNS_RDF_TYPE_A,
LDNS_IP4ADDRLEN, &data_in->sin_addr);
break;
case AF_INET6:
data_in6 = (struct sockaddr_in6*)sock;
if (port) {
*port = ntohs((uint16_t)data_in6->sin6_port);
}
addr = ldns_rdf_new_frm_data(LDNS_RDF_TYPE_AAAA,
LDNS_IP6ADDRLEN, &data_in6->sin6_addr);
break;
default:
if (port) {
*port = 0;
}
return NULL;
}
return addr;
}
#endif
/* code from resolver.c */
ldns_status
ldns_axfr_start(ldns_resolver *resolver, const ldns_rdf *domain, ldns_rr_class class)
{
ldns_pkt *query;
ldns_buffer *query_wire;
struct sockaddr_storage *src = NULL;
size_t src_len = 0;
struct sockaddr_storage *ns = NULL;
size_t ns_len = 0;
size_t ns_i;
ldns_status status;
if (!resolver || ldns_resolver_nameserver_count(resolver) < 1) {
return LDNS_STATUS_ERR;
}
query = ldns_pkt_query_new(ldns_rdf_clone(domain), LDNS_RR_TYPE_AXFR, class, 0);
if (!query) {
return LDNS_STATUS_ADDRESS_ERR;
}
if(ldns_resolver_source(resolver)) {
src = ldns_rdf2native_sockaddr_storage_port(
ldns_resolver_source(resolver), 0, &src_len);
}
/* For AXFR, we have to make the connection ourselves */
/* try all nameservers (which usually would mean v4 fallback if
* @hostname is used */
for (ns_i = 0;
ns_i < ldns_resolver_nameserver_count(resolver) &&
resolver->_socket == SOCK_INVALID;
ns_i++) {
if (ns != NULL) {
LDNS_FREE(ns);
}
ns = ldns_rdf2native_sockaddr_storage(
resolver->_nameservers[ns_i],
ldns_resolver_port(resolver), &ns_len);
#ifndef S_SPLINT_S
if ((ns->ss_family == AF_INET) &&
(ldns_resolver_ip6(resolver) == LDNS_RESOLV_INET6)) {
/* not reachable */
LDNS_FREE(ns);
ns = NULL;
continue;
}
if ((ns->ss_family == AF_INET6) &&
(ldns_resolver_ip6(resolver) == LDNS_RESOLV_INET)) {
/* not reachable */
LDNS_FREE(ns);
ns = NULL;
continue;
}
#endif
resolver->_socket = ldns_tcp_connect_from(
ns, (socklen_t)ns_len,
src, (socklen_t)src_len,
ldns_resolver_timeout(resolver));
}
if (src) {
LDNS_FREE(src);
}
if (resolver->_socket == SOCK_INVALID) {
ldns_pkt_free(query);
LDNS_FREE(ns);
return LDNS_STATUS_NETWORK_ERR;
}
#ifdef HAVE_SSL
if (ldns_resolver_tsig_keyname(resolver) && ldns_resolver_tsig_keydata(resolver)) {
status = ldns_pkt_tsig_sign(query,
ldns_resolver_tsig_keyname(resolver),
ldns_resolver_tsig_keydata(resolver),
300, ldns_resolver_tsig_algorithm(resolver), NULL);
if (status != LDNS_STATUS_OK) {
/* to prevent problems on subsequent calls to
* ldns_axfr_start we have to close the socket here! */
close_socket(resolver->_socket);
resolver->_socket = 0;
ldns_pkt_free(query);
LDNS_FREE(ns);
return LDNS_STATUS_CRYPTO_TSIG_ERR;
}
}
#endif /* HAVE_SSL */
/* Convert the query to a buffer
* Is this necessary?
*/
query_wire = ldns_buffer_new(LDNS_MAX_PACKETLEN);
if(!query_wire) {
ldns_pkt_free(query);
LDNS_FREE(ns);
close_socket(resolver->_socket);
return LDNS_STATUS_MEM_ERR;
}
status = ldns_pkt2buffer_wire(query_wire, query);
if (status != LDNS_STATUS_OK) {
ldns_pkt_free(query);
ldns_buffer_free(query_wire);
LDNS_FREE(ns);
/* to prevent problems on subsequent calls to ldns_axfr_start
* we have to close the socket here! */
close_socket(resolver->_socket);
resolver->_socket = 0;
return status;
}
/* Send the query */
if (ldns_tcp_send_query(query_wire, resolver->_socket, ns,
(socklen_t)ns_len) == 0) {
ldns_pkt_free(query);
ldns_buffer_free(query_wire);
LDNS_FREE(ns);
/* to prevent problems on subsequent calls to ldns_axfr_start
* we have to close the socket here! */
close_socket(resolver->_socket);
return LDNS_STATUS_NETWORK_ERR;
}
ldns_pkt_free(query);
ldns_buffer_free(query_wire);
LDNS_FREE(ns);
/*
* The AXFR is done once the second SOA record is sent
*/
resolver->_axfr_soa_count = 0;
return LDNS_STATUS_OK;
}
|
ecb41a205aae034b94d4e20b3d1925013eaeea2c
|
58fe7cb3949dd1930e709696659a0296500b64a6
|
/tests/cbmc/include/cbmc_proof/endian.h
|
e735463d6221d3689abb16163b12879ddc60f64e
|
[
"Apache-2.0",
"MIT"
] |
permissive
|
aws/s2n-tls
|
3344638a6a69c6f20665cf6847e1bc4b85f2e558
|
62dc7a6d4876e5eee0dea3690d528a4c7080a1d5
|
refs/heads/main
| 2023-08-31T23:26:33.780048
| 2023-08-31T05:17:33
| 2023-08-31T05:17:33
| 21,287,076
| 513
| 213
|
Apache-2.0
| 2023-09-13T23:52:29
| 2014-06-27T19:37:59
|
C
|
UTF-8
|
C
| false
| false
| 1,834
|
h
|
endian.h
|
/*
* Copyright Amazon.com, Inc. or its affiliates. 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. A copy of the License is
* located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing permissions and
* limitations under the License.
*/
#if __BYTE_ORDER == __LITTLE_ENDIAN
# define __LONG_LONG_PAIR(HI, LO) LO, HI
#elif __BYTE_ORDER == __BIG_ENDIAN
# define __LONG_LONG_PAIR(HI, LO) HI, LO
#endif
#undef htobe16
#undef htole16
#undef htobe32
#undef htole32
#undef htobe64
#undef htole64
#undef be16toh
#undef le16toh
#undef be32toh
#undef le32toh
#undef be64toh
#undef le64toh
#if __BYTE_ORDER == __LITTLE_ENDIAN
# define htobe16(x) __builtin_bswap16(x)
# define htole16(x) (x)
# define be16toh(x) __builtin_bswap16(x)
# define le16toh(x) (x)
# define htobe32(x) __builtin_bswap32(x)
# define htole32(x) (x)
# define be32toh(x) __builtin_bswap32(x)
# define le32toh(x) (x)
# define htobe64(x) __builtin_bswap64(x)
# define htole64(x) (x)
# define be64toh(x) __builtin_bswap64(x)
# define le64toh(x) (x)
#else
# define htobe16(x) (x)
# define htole16(x) __builtin_bswap16(x)
# define be16toh(x) (x)
# define le16toh(x) __builtin_bswap16(x)
# define htobe32(x) (x)
# define htole32(x) __builtin_bswap32(x)
# define be32toh(x) (x)
# define le32toh(x) __builtin_bswap32(x)
# define htobe64(x) (x)
# define htole64(x) __builtin_bswap64(x)
# define be64toh(x) (x)
# define le64toh(x) __builtin_bswap64(x)
#endif
|
f7157dcebd789e525a6b5f50e45f31571962cd2e
|
7744859512f027ef0da8b1bde0f8518e631b98eb
|
/soh/assets/objects/object_haka_door/object_haka_door.h
|
93e489e2d378cd0bf4394ef071e11c14abb0af03
|
[] |
no_license
|
HarbourMasters/Shipwright
|
7f70b9470e4f9a117f3fe2d6e4deb776b8742182
|
0e7c6585239c0d7ea2c039b8b8cb7eaedf8928a9
|
refs/heads/develop
| 2023-08-31T20:50:56.253521
| 2023-08-30T17:34:06
| 2023-08-30T17:34:06
| 472,575,717
| 2,104
| 459
| null | 2023-09-14T20:29:01
| 2022-03-22T01:42:52
|
C
|
UTF-8
|
C
| false
| false
| 1,516
|
h
|
object_haka_door.h
|
#pragma once
#include "align_asset_macro.h"
#define dobject_haka_door_Tex_000000 "__OTR__objects/object_haka_door/object_haka_door_Tex_000000"
static const ALIGN_ASSET(2) char object_haka_door_Tex_000000[] = dobject_haka_door_Tex_000000;
#define dobject_haka_door_DL_001310 "__OTR__objects/object_haka_door/object_haka_door_DL_001310"
static const ALIGN_ASSET(2) char object_haka_door_DL_001310[] = dobject_haka_door_DL_001310;
#define dgShadowDoorLeftDL "__OTR__objects/object_haka_door/gShadowDoorLeftDL"
static const ALIGN_ASSET(2) char gShadowDoorLeftDL[] = dgShadowDoorLeftDL;
#define dgShadowDoorRightDL "__OTR__objects/object_haka_door/gShadowDoorRightDL"
static const ALIGN_ASSET(2) char gShadowDoorRightDL[] = dgShadowDoorRightDL;
#define dobject_haka_door_Tex_001490 "__OTR__objects/object_haka_door/object_haka_door_Tex_001490"
static const ALIGN_ASSET(2) char object_haka_door_Tex_001490[] = dobject_haka_door_Tex_001490;
#define dobject_haka_door_DL_002620 "__OTR__objects/object_haka_door/object_haka_door_DL_002620"
static const ALIGN_ASSET(2) char object_haka_door_DL_002620[] = dobject_haka_door_DL_002620;
#define dobject_haka_door_Tex_002700 "__OTR__objects/object_haka_door/object_haka_door_Tex_002700"
static const ALIGN_ASSET(2) char object_haka_door_Tex_002700[] = dobject_haka_door_Tex_002700;
#define dobject_haka_door_DL_003890 "__OTR__objects/object_haka_door/object_haka_door_DL_003890"
static const ALIGN_ASSET(2) char object_haka_door_DL_003890[] = dobject_haka_door_DL_003890;
|
9dc133e9b8c8d58fd66ec1beead88ec8fbbf743f
|
9ceacf33fd96913cac7ef15492c126d96cae6911
|
/sys/dev/cardbus/if_rl_cardbus.c
|
2d4eb393a6781aa2b770f18022439a63bfaf49fc
|
[] |
no_license
|
openbsd/src
|
ab97ef834fd2d5a7f6729814665e9782b586c130
|
9e79f3a0ebd11a25b4bff61e900cb6de9e7795e9
|
refs/heads/master
| 2023-09-02T18:54:56.624627
| 2023-09-02T15:16:12
| 2023-09-02T15:16:12
| 66,966,208
| 3,394
| 1,235
| null | 2023-08-08T02:42:25
| 2016-08-30T18:18:25
|
C
|
UTF-8
|
C
| false
| false
| 8,917
|
c
|
if_rl_cardbus.c
|
/* $OpenBSD: if_rl_cardbus.c,v 1.32 2022/04/06 18:59:28 naddy Exp $ */
/* $NetBSD: if_rl_cardbus.c,v 1.3.8.3 2001/11/14 19:14:02 nathanw Exp $ */
/*
* Copyright (c) 2000 Masanori Kanaoka
* 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. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR 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.
*/
/*
* if_rl_cardbus.c:
* Cardbus specific routines for Realtek 8139 ethernet adapter.
* Tested for
* - elecom-Laneed LD-10/100CBA (Accton MPX5030)
* - MELCO LPC3-TX-CB (Realtek 8139)
*/
#include "bpfilter.h"
#include <sys/param.h>
#include <sys/systm.h>
#include <sys/mbuf.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <sys/errno.h>
#include <sys/malloc.h>
#include <sys/kernel.h>
#include <sys/timeout.h>
#include <sys/device.h>
#include <sys/endian.h>
#include <net/if.h>
#include <net/if_media.h>
#if NBPFILTER > 0
#include <net/bpf.h>
#endif
#include <netinet/in.h>
#include <netinet/if_ether.h>
#include <machine/bus.h>
#include <machine/intr.h>
#include <dev/mii/miivar.h>
#include <dev/pci/pcivar.h>
#include <dev/pci/pcireg.h>
#include <dev/pci/pcidevs.h>
#include <dev/cardbus/cardbusvar.h>
/*
* Default to using PIO access for this driver. On SMP systems,
* there appear to be problems with memory mapped mode: it looks like
* doing too many memory mapped access back to back in rapid succession
* can hang the bus. I'm inclined to blame this on crummy design/construction
* on the part of Realtek. Memory mapped mode does appear to work on
* uniprocessor systems though.
*/
#define RL_USEIOSPACE
#include <dev/ic/rtl81x9reg.h>
/*
* Various supported device vendors/types and their names.
*/
const struct pci_matchid rl_cardbus_devices[] = {
{ PCI_VENDOR_ABOCOM, PCI_PRODUCT_ABOCOM_FE2000VX },
{ PCI_VENDOR_ACCTON, PCI_PRODUCT_ACCTON_5030 },
{ PCI_VENDOR_COREGA, PCI_PRODUCT_COREGA_2CB_TXD },
{ PCI_VENDOR_COREGA, PCI_PRODUCT_COREGA_CB_TXD },
{ PCI_VENDOR_DLINK, PCI_PRODUCT_DLINK_DFE690TXD },
{ PCI_VENDOR_PLANEX, PCI_PRODUCT_PLANEX_FNW_3603_TX },
{ PCI_VENDOR_PLANEX, PCI_PRODUCT_PLANEX_FNW_3800_TX },
{ PCI_VENDOR_REALTEK, PCI_PRODUCT_REALTEK_RT8138 },
{ PCI_VENDOR_REALTEK, PCI_PRODUCT_REALTEK_RT8139 },
};
struct rl_cardbus_softc {
struct rl_softc sc_rl; /* real rtk softc */
/* CardBus-specific goo. */
cardbus_devfunc_t sc_ct;
pci_chipset_tag_t sc_pc;
pcitag_t sc_tag;
int sc_csr;
int sc_cben;
int sc_bar_reg;
pcireg_t sc_bar_val;
bus_size_t sc_mapsize;
int sc_intrline;
};
static int rl_cardbus_match(struct device *, void *, void *);
static void rl_cardbus_attach(struct device *, struct device *, void *);
static int rl_cardbus_detach(struct device *, int);
void rl_cardbus_setup(struct rl_cardbus_softc *);
const struct cfattach rl_cardbus_ca = {
sizeof(struct rl_cardbus_softc), rl_cardbus_match, rl_cardbus_attach,
rl_cardbus_detach
};
int
rl_cardbus_match(struct device *parent, void *match, void *aux)
{
return (cardbus_matchbyid((struct cardbus_attach_args *)aux,
rl_cardbus_devices, nitems(rl_cardbus_devices)));
}
void
rl_cardbus_attach(struct device *parent, struct device *self, void *aux)
{
struct rl_cardbus_softc *csc =
(struct rl_cardbus_softc *)self;
struct rl_softc *sc = &csc->sc_rl;
struct cardbus_attach_args *ca = aux;
struct cardbus_softc *psc =
(struct cardbus_softc *)sc->sc_dev.dv_parent;
cardbus_chipset_tag_t cc = psc->sc_cc;
cardbus_function_tag_t cf = psc->sc_cf;
cardbus_devfunc_t ct = ca->ca_ct;
bus_addr_t adr;
sc->sc_dmat = ca->ca_dmat;
csc->sc_ct = ct;
csc->sc_tag = ca->ca_tag;
csc->sc_intrline = ca->ca_intrline;
csc->sc_pc = ca->ca_pc;
/*
* Map control/status registers.
*/
csc->sc_csr = PCI_COMMAND_MASTER_ENABLE;
#ifdef RL_USEIOSPACE
if (Cardbus_mapreg_map(ct, RL_PCI_LOIO, PCI_MAPREG_TYPE_IO, 0,
&sc->rl_btag, &sc->rl_bhandle, &adr, &csc->sc_mapsize) == 0) {
csc->sc_cben = CARDBUS_IO_ENABLE;
csc->sc_csr |= PCI_COMMAND_IO_ENABLE;
csc->sc_bar_reg = RL_PCI_LOIO;
csc->sc_bar_val = adr | PCI_MAPREG_TYPE_IO;
}
#else
if (Cardbus_mapreg_map(ct, RL_PCI_LOMEM, PCI_MAPREG_TYPE_MEM, 0,
&sc->rl_btag, &sc->rl_bhandle, &adr, &csc->sc_mapsize) == 0) {
csc->sc_cben = CARDBUS_MEM_ENABLE;
csc->sc_csr |= PCI_COMMAND_MEM_ENABLE;
csc->sc_bar_reg = RL_PCI_LOMEM;
csc->sc_bar_val = adr | PCI_MAPREG_TYPE_MEM;
}
#endif
else {
printf("%s: unable to map deviceregisters\n",
sc->sc_dev.dv_xname);
return;
}
Cardbus_function_enable(ct);
rl_cardbus_setup(csc);
/*
* Map and establish the interrupt.
*/
sc->sc_ih = cardbus_intr_establish(cc, cf, csc->sc_intrline, IPL_NET,
rl_intr, sc, sc->sc_dev.dv_xname);
if (sc->sc_ih == NULL) {
printf(": couldn't establish interrupt\n");
Cardbus_function_disable(csc->sc_ct);
return;
}
printf(": irq %d", csc->sc_intrline);
sc->rl_type = RL_8139;
rl_attach(sc);
}
int
rl_cardbus_detach(struct device *self, int flags)
{
struct rl_cardbus_softc *csc = (void *) self;
struct rl_softc *sc = &csc->sc_rl;
struct cardbus_devfunc *ct = csc->sc_ct;
int rv;
#ifdef DIAGNOSTIC
if (ct == NULL)
panic("%s: data structure lacks", sc->sc_dev.dv_xname);
#endif
rv = rl_detach(sc);
if (rv)
return (rv);
/*
* Unhook the interrupt handler.
*/
if (sc->sc_ih != NULL)
cardbus_intr_disestablish(ct->ct_cc, ct->ct_cf, sc->sc_ih);
/*
* Release bus space and close window.
*/
if (csc->sc_bar_reg != 0)
Cardbus_mapreg_unmap(ct, csc->sc_bar_reg,
sc->rl_btag, sc->rl_bhandle, csc->sc_mapsize);
return (0);
}
void
rl_cardbus_setup(struct rl_cardbus_softc *csc)
{
struct rl_softc *sc = &csc->sc_rl;
cardbus_devfunc_t ct = csc->sc_ct;
cardbus_chipset_tag_t cc = ct->ct_cc;
pci_chipset_tag_t pc = csc->sc_pc;
pcireg_t reg, command;
int pmreg;
/*
* Handle power management nonsense.
*/
if (pci_get_capability(pc, csc->sc_tag,
PCI_CAP_PWRMGMT, &pmreg, 0)) {
command = pci_conf_read(pc, csc->sc_tag, pmreg + 4);
if (command & RL_PSTATE_MASK) {
pcireg_t iobase, membase, irq;
/* Save important PCI config data. */
iobase = pci_conf_read(pc, csc->sc_tag,
RL_PCI_LOIO);
membase = pci_conf_read(pc, csc->sc_tag,
RL_PCI_LOMEM);
irq = pci_conf_read(pc, csc->sc_tag,
PCI_PRODUCT_DELTA_8139);
/* Reset the power state. */
printf("%s: chip is in D%d power mode "
"-- setting to D0\n", sc->sc_dev.dv_xname,
command & RL_PSTATE_MASK);
command &= 0xFFFFFFFC;
pci_conf_write(pc, csc->sc_tag,
pmreg + 4, command);
/* Restore PCI config data. */
pci_conf_write(pc, csc->sc_tag,
RL_PCI_LOIO, iobase);
pci_conf_write(pc, csc->sc_tag,
RL_PCI_LOMEM, membase);
pci_conf_write(pc, csc->sc_tag,
PCI_PRODUCT_DELTA_8139, irq);
}
}
/* Make sure the right access type is on the CardBus bridge. */
(*ct->ct_cf->cardbus_ctrl)(cc, csc->sc_cben);
(*ct->ct_cf->cardbus_ctrl)(cc, CARDBUS_BM_ENABLE);
/* Program the BAR */
pci_conf_write(pc, csc->sc_tag,
csc->sc_bar_reg, csc->sc_bar_val);
/* Enable the appropriate bits in the CARDBUS CSR. */
reg = pci_conf_read(pc, csc->sc_tag,
PCI_COMMAND_STATUS_REG);
reg &= ~(PCI_COMMAND_IO_ENABLE|PCI_COMMAND_MEM_ENABLE);
reg |= csc->sc_csr;
pci_conf_write(pc, csc->sc_tag,
PCI_COMMAND_STATUS_REG, reg);
/*
* Make sure the latency timer is set to some reasonable
* value.
*/
reg = pci_conf_read(pc, csc->sc_tag, PCI_BHLC_REG);
if (PCI_LATTIMER(reg) < 0x20) {
reg &= ~(PCI_LATTIMER_MASK << PCI_LATTIMER_SHIFT);
reg |= (0x20 << PCI_LATTIMER_SHIFT);
pci_conf_write(pc, csc->sc_tag, PCI_BHLC_REG, reg);
}
}
|
c77e31cc7ed73b8daf691315d0bd65034578f9ce
|
6923f79f1eaaba0ab28b25337ba6cb56be97d32d
|
/Algorithmic_Trading_Chan/jplv7/Ucsd_garch/MEX Source/egarchXcore.c
|
6b9c95295833349e00e4af6e2180b4dbec056314
|
[] |
no_license
|
burakbayramli/books
|
9fe7ba0cabf06e113eb125d62fe16d4946f4a4f0
|
5e9a0e03aa7ddf5e5ddf89943ccc68d94b539e95
|
refs/heads/master
| 2023-08-17T05:31:08.885134
| 2023-08-14T10:05:37
| 2023-08-14T10:05:37
| 72,460,321
| 223
| 174
| null | 2022-10-24T12:15:06
| 2016-10-31T17:24:00
|
Jupyter Notebook
|
UTF-8
|
C
| false
| false
| 2,135
|
c
|
egarchXcore.c
|
/* Change this to reflect the apropriate header file */
#include <math.h>
#include "mex.h"
/*
* egarchcore.c -
* This is a helper function and is part of the UCSD_GARCH toolbox
* You can compile it and should work on any platform.
*
* Author: Kevin Sheppard
* kevin.sheppard@economics.ox.ac.uk
* Revision: 2 Date: 12/31/2001
*/
void egarchcore(double *data, double *parameters, int p, int o, int q, int m, int T, double *covEst, double *Ht, double *X)
{
int i, j, p2=2*p;
const double covEst2= *covEst * *covEst;
for (j=0; j<m; j++) {
*(Ht+j)=covEst2;
}
for (i=m; i<(T); i++) {
*(Ht+i)=parameters[0]+*(X+i);
for (j=0; j<p; j++) {
*(Ht+i)+=parameters[j+1]* *(data+(i-(j+1)))/ *(Ht+i-(j+1));
}
for (j=0; j<o; j++) {
*(Ht+i)+=parameters[j+p+1]* fabs(*(data+(i-(j+1)))/ *(Ht+i-(j+1)));
}
for (j=0; j<q; j++) {
*(Ht+i)+=parameters[j+p2+1]* log(*(Ht+(i-(j+1))));
}
*(Ht+i)= exp(*(Ht+i));
}
}
/* The gateway routine */
void mexFunction( int nlhs, mxArray *plhs[],
int nrhs, const mxArray *prhs[])
{
double *data, *parameters, *Ht, *covEst, *X;
int p, o, q, m, T;
int mrows,ncols;
/* Check for proper number of arguments. */
if(nrhs!=9)
mexErrMsgTxt("Nine inputs required.");
if(nlhs!=1)
mexErrMsgTxt("One output required.");
/* Get the scalar inputs */
p = mxGetScalar(prhs[3]);
o = mxGetScalar(prhs[4]);
q = mxGetScalar(prhs[5]);
m = mxGetScalar(prhs[6]);
T = mxGetScalar(prhs[7]);
/* Create a pointer to the input matrices . */
data = mxGetPr(prhs[0]);
parameters = mxGetPr(prhs[1]);
covEst = mxGetPr(prhs[2]);
X = mxGetPr(prhs[8]);
/* Get the dimensions of the matrix input ht to make an output matrix. */
mrows = mxGetM(prhs[0]);
ncols = mxGetN(prhs[0]);
/* Set the output pointer to the output matrix. */
plhs[0] = mxCreateDoubleMatrix(mrows,ncols, mxREAL);
/* Create a C pointer to a copy of the output matrix. */
Ht = mxGetPr(plhs[0]);
/* Call the C subroutine. */
egarchcore(data,parameters,p,o, q, m, T, covEst, Ht, X);
}
|
93c9fe39f533ad9db77f120b527a5bc9a415d841
|
2247493654c160426c1655281aa7f1dca2bc98dd
|
/src/property_evaluator/SpecificHeatPropertyEvaluator.C
|
ea133a0b26e6f396348fe6d94f0b675276d1bd97
|
[
"BSD-2-Clause"
] |
permissive
|
NaluCFD/Nalu
|
12999b0e3b76dbeab8fc184f38b65a13b1180bce
|
3286651e494894ac5948c41bf985f987d20c2370
|
refs/heads/master
| 2023-08-10T02:48:04.179859
| 2023-08-02T19:02:46
| 2023-08-02T19:02:46
| 69,712,764
| 138
| 185
|
NOASSERTION
| 2023-09-14T16:42:19
| 2016-10-01T01:25:20
|
C
|
UTF-8
|
C
| false
| false
| 8,854
|
c
|
SpecificHeatPropertyEvaluator.C
|
/*------------------------------------------------------------------------*/
/* Copyright 2014 Sandia Corporation. */
/* This software is released under the license detailed */
/* in the file, LICENSE, which is located in the top-level Nalu */
/* directory structure */
/*------------------------------------------------------------------------*/
#include <property_evaluator/SpecificHeatPropertyEvaluator.h>
#include <property_evaluator/PolynomialPropertyEvaluator.h>
#include <property_evaluator/ReferencePropertyData.h>
#include <FieldTypeDef.h>
#include <stk_mesh/base/MetaData.hpp>
#include <stk_mesh/base/BulkData.hpp>
#include <stk_mesh/base/Field.hpp>
#include <stdexcept>
namespace sierra{
namespace nalu{
//==========================================================================
// Class Definition
//==========================================================================
// SpecificHeatPropertyEvaluator - evaluates Cp (5 coeff) based on T
//==========================================================================
//--------------------------------------------------------------------------
//-------- constructor -----------------------------------------------------
//--------------------------------------------------------------------------
SpecificHeatPropertyEvaluator::SpecificHeatPropertyEvaluator(
const std::map<std::string, ReferencePropertyData*> &referencePropertyDataMap,
const std::map<std::string, std::vector<double> > &lowPolynomialCoeffsMap,
const std::map<std::string, std::vector<double> > &highPolynomialCoeffsMap,
double universalR)
: PolynomialPropertyEvaluator(referencePropertyDataMap, lowPolynomialCoeffsMap, highPolynomialCoeffsMap, universalR)
{
// resize reference mass fraction and polynomial size
refMassFraction_.resize(ykVecSize_);
// save off reference values for yk
size_t k = 0;
std::map<std::string, ReferencePropertyData*>::const_iterator itrp;
for ( itrp = referencePropertyDataMap.begin();
itrp!= referencePropertyDataMap.end(); ++itrp, ++k) {
ReferencePropertyData *propData = (*itrp).second;
refMassFraction_[k] = propData->massFraction_;
}
}
//--------------------------------------------------------------------------
//-------- destructor ------------------------------------------------------
//--------------------------------------------------------------------------
SpecificHeatPropertyEvaluator::~SpecificHeatPropertyEvaluator()
{
// nothing
}
//--------------------------------------------------------------------------
//-------- execute ---------------------------------------------------------
//--------------------------------------------------------------------------
double
SpecificHeatPropertyEvaluator::execute(
double *indVarList,
stk::mesh::Entity /*node*/)
{
// hard coded to expect temperature only
const double T = indVarList[0];
// process sum
double sum_cp_r = 0.0;
if ( T < TlowHigh_ ) {
for ( size_t k = 0; k < ykVecSize_; ++k ) {
sum_cp_r += refMassFraction_[k]*compute_cp_r(T, &lowPolynomialCoeffs_[k][0])/mw_[k];
}
}
else {
for ( size_t k = 0; k < ykVecSize_; ++k ) {
sum_cp_r += refMassFraction_[k]*compute_cp_r(T, &highPolynomialCoeffs_[k][0])/mw_[k];
}
}
return sum_cp_r*universalR_;
}
//--------------------------------------------------------------------------
//-------- compute_cp_r ----------------------------------------------------
//--------------------------------------------------------------------------
double
SpecificHeatPropertyEvaluator::compute_cp_r(
const double &T,
const double *pt_poly)
{
double cp_r = pt_poly[0]
+ pt_poly[1]*T
+ pt_poly[2]*T*T
+ pt_poly[3]*T*T*T
+ pt_poly[4]*T*T*T*T;
return cp_r;
}
//==========================================================================
// Class Definition
//==========================================================================
// SpecificHeatTYkPropertyEvaluator - evaluates Cp (5 coeff) based on T and Yk
//==========================================================================
//--------------------------------------------------------------------------
//-------- constructor -----------------------------------------------------
//--------------------------------------------------------------------------
SpecificHeatTYkPropertyEvaluator::SpecificHeatTYkPropertyEvaluator(
const std::map<std::string, ReferencePropertyData*> &referencePropertyDataMap,
const std::map<std::string, std::vector<double> > &lowPolynomialCoeffsMap,
const std::map<std::string, std::vector<double> > &highPolynomialCoeffsMap,
double universalR,
stk::mesh::MetaData &metaData)
: PolynomialPropertyEvaluator(referencePropertyDataMap, lowPolynomialCoeffsMap, highPolynomialCoeffsMap, universalR),
massFraction_(NULL)
{
// save off mass fraction field
massFraction_ = metaData.get_field<double>(stk::topology::NODE_RANK, "mass_fraction");
}
//--------------------------------------------------------------------------
//-------- destructor ------------------------------------------------------
//--------------------------------------------------------------------------
SpecificHeatTYkPropertyEvaluator::~SpecificHeatTYkPropertyEvaluator()
{
// nothing
}
//--------------------------------------------------------------------------
//-------- execute ---------------------------------------------------------
//--------------------------------------------------------------------------
double
SpecificHeatTYkPropertyEvaluator::execute(
double *indVarList,
stk::mesh::Entity node)
{
const double T = indVarList[0];
const double *massFraction = stk::mesh::field_data(*massFraction_, node);
// process sum
double sum_cp_r = 0.0;
if ( T < TlowHigh_ ) {
for ( size_t k = 0; k < ykVecSize_; ++k ) {
sum_cp_r += massFraction[k]*compute_cp_r(T, &lowPolynomialCoeffs_[k][0])/mw_[k];
}
}
else {
for ( size_t k = 0; k < ykVecSize_; ++k ) {
sum_cp_r += massFraction[k]*compute_cp_r(T, &highPolynomialCoeffs_[k][0])/mw_[k];
}
}
return sum_cp_r*universalR_;
}
//--------------------------------------------------------------------------
//-------- compute_cp_r ----------------------------------------------------
//--------------------------------------------------------------------------
double
SpecificHeatTYkPropertyEvaluator::compute_cp_r(
const double &T,
const double *pt_poly)
{
double cp_r = pt_poly[0]
+ pt_poly[1]*T
+ pt_poly[2]*T*T
+ pt_poly[3]*T*T*T
+ pt_poly[4]*T*T*T*T;
return cp_r;
}
//==========================================================================
// Class Definition
//==========================================================================
// SpecificHeatConstCpkPropertyEvaluator - evaluates Cp \bar Cp_k and Yk
//==========================================================================
//--------------------------------------------------------------------------
//-------- constructor -----------------------------------------------------
//--------------------------------------------------------------------------
SpecificHeatConstCpkPropertyEvaluator::SpecificHeatConstCpkPropertyEvaluator(
const std::map<std::string, double> &cpConstMap,
stk::mesh::MetaData &metaData)
: PropertyEvaluator(),
cpVecSize_(cpConstMap.size()),
massFraction_(NULL)
{
// save off mass fraction field
massFraction_ = metaData.get_field<double>(stk::topology::NODE_RANK, "mass_fraction");
// save off Cp_k as vector
cpVec_.resize(cpVecSize_);
size_t k = 0;
std::map<std::string, double>::const_iterator it;
for ( it = cpConstMap.begin();
it!= cpConstMap.end(); ++it, ++k) {
double theValue = (*it).second;
cpVec_[k] = theValue;
}
}
//--------------------------------------------------------------------------
//-------- destructor ------------------------------------------------------
//--------------------------------------------------------------------------
SpecificHeatConstCpkPropertyEvaluator::~SpecificHeatConstCpkPropertyEvaluator()
{
// nothing
}
//--------------------------------------------------------------------------
//-------- execute ---------------------------------------------------------
//--------------------------------------------------------------------------
double
SpecificHeatConstCpkPropertyEvaluator::execute(
double */*indVarList*/,
stk::mesh::Entity node)
{
const double *massFraction = stk::mesh::field_data(*massFraction_, node);
// process sum
double sum_cp = 0.0;
for ( size_t k = 0; k < cpVecSize_; ++k ) {
sum_cp += massFraction[k]*cpVec_[k];
}
return sum_cp;
}
} // namespace nalu
} // namespace Sierra
|
b0cd782287b8fc82b45fcc657bcb30d14bd64c6e
|
89db60818afeb3dc7c3b7abe9ceae155f074f7f2
|
/src/libhttpd/checkcontent.c
|
1b535ec917373f8a754f89230aa9a9be2bf1af3c
|
[
"bzip2-1.0.6",
"LPL-1.02",
"MIT"
] |
permissive
|
9fans/plan9port
|
63c3d01928c6f8a8617d3ea6ecc05bac72391132
|
65c090346a38a8c30cb242d345aa71060116340c
|
refs/heads/master
| 2023-08-25T17:14:26.233105
| 2023-08-23T13:21:37
| 2023-08-23T18:47:08
| 26,095,474
| 1,645
| 468
|
NOASSERTION
| 2023-09-05T16:55:41
| 2014-11-02T22:40:13
|
C
|
UTF-8
|
C
| false
| false
| 771
|
c
|
checkcontent.c
|
#include <u.h>
#include <libc.h>
#include <bin.h>
#include <httpd.h>
int
hcheckcontent(HContent *me, HContent *oks, char *list, int size)
{
HContent *ok;
if(oks == nil || me == nil)
return 1;
for(ok = oks; ok != nil; ok = ok->next){
if((cistrcmp(ok->generic, me->generic) == 0 || strcmp(ok->generic, "*") == 0)
&& (me->specific == nil || cistrcmp(ok->specific, me->specific) == 0 || strcmp(ok->specific, "*") == 0)){
if(ok->mxb > 0 && size > ok->mxb)
return 0;
return 1;
}
}
USED(list);
if(0){
fprint(2, "list: %s/%s not found\n", me->generic, me->specific);
for(; oks != nil; oks = oks->next){
if(oks->specific)
fprint(2, "\t%s/%s\n", oks->generic, oks->specific);
else
fprint(2, "\t%s\n", oks->generic);
}
}
return 0;
}
|
210bb255b577bbf806c7abba31905a251a174368
|
5eff7a36d9a9917dce9111f0c3074375fe6f7656
|
/app/xlockmore/modes/eyes.c
|
9c5b8d44b5646a50178a25d6a70ed55ad87dc044
|
[] |
no_license
|
openbsd/xenocara
|
cb392d02ebba06f6ff7d826fd8a89aa3b8401779
|
a012b5de33ea0b977095d77316a521195b26cc6b
|
refs/heads/master
| 2023-08-25T12:16:58.862008
| 2023-08-12T16:16:25
| 2023-08-12T16:16:25
| 66,967,384
| 177
| 66
| null | 2023-07-22T18:12:37
| 2016-08-30T18:36:01
|
C
|
UTF-8
|
C
| false
| false
| 31,239
|
c
|
eyes.c
|
/* -*- Mode: C; tab-width: 4 -*- */
/* eyes --- follow the bouncing Grelb */
#if !defined( lint ) && !defined( SABER )
static const char sccsid[] = "@(#)eyes.c 5.00 2000/11/01 xlockmore";
#endif
/*-
* Copyright 1996 by Ron Hitchens <ron@idiom.com>
*
* Adapted from the ubiquitous xeyes demo supplied by MIT with the
* X Window System.
* That code is Copyright 1991 Massachusetts Institute of Technology.
*
* Permission to use, copy, modify, and distribute this software and its
* documentation for any purpose and without fee is hereby granted,
* provided that the above copyright notice appear in all copies and that
* both that copyright notice and this permission notice appear in
* supporting documentation.
*
* This file is provided AS IS with no warranties of any kind. The author
* shall have no liability with respect to the infringement of copyrights,
* trade secrets or any patents by this file or any part thereof. In no
* event will the author be liable for any lost revenue or profits or
* other special, indirect and consequential damages.
*
* Revision History:
* 01-Nov-2000: Allocation checks
* 04-Sep-1997: Added interactive frobbing with mouse (copied from julia.c)
* 10-May-1997: Compatible with xscreensaver
* 18-Mar-1996: Changes for new hook calling conventions. Keep per-screen
* state information. Remove global accesses.
* 21-Feb-1996: Recoded to keep an off-screen image for each pair of eyes,
* and to only paint the changed parts to the screen.
* Allow the Grelb to enter from either side.
* 18-Feb-1996: Got the code into mostly working condition.
* 15-Feb-1996: Had a brainwave, started hacking the xeyes code.
*
* Put "random rotations and horizontal shifts in.
* At first try make the shifts "random" with a weighting scheme favouring
* shifts towards the most empty region.
*/
#ifdef STANDALONE
#define MODE_eyes
#define PROGCLASS "Eyes"
#define HACK_INIT init_eyes
#define HACK_DRAW draw_eyes
#define eyes_opts xlockmore_opts
#define DEFAULTS "*delay: 20000 \n" \
"*count: -8 \n" \
"*cycles: 5 \n" \
"*ncolors: 200 \n" \
"*bitmap: \n" \
"*trackmouse: False \n"
#include "xlockmore.h" /* in xscreensaver distribution */
#else /* STANDALONE */
#include "xlock.h" /* in xlockmore distribution */
#endif /* STANDALONE */
#include "iostuff.h"
#ifdef MODE_eyes
#define DEF_TRACKMOUSE "False"
static Bool trackmouse;
static XrmOptionDescRec opts[] =
{
{(char *) "-trackmouse", (char *) ".eyes.trackmouse", XrmoptionNoArg, (caddr_t) "on"},
{(char *) "+trackmouse", (char *) ".eyes.trackmouse", XrmoptionNoArg, (caddr_t) "off"}
};
static argtype vars[] =
{
{(void *) & trackmouse, (char *) "trackmouse", (char *) "TrackMouse", (char *) DEF_TRACKMOUSE, t_Bool}
};
static OptionStruct desc[] =
{
{(char *) "-/+trackmouse", (char *) "turn on/off the tracking of the mouse"}
};
ModeSpecOpt eyes_opts =
{sizeof opts / sizeof opts[0], opts, sizeof vars / sizeof vars[0], vars, desc};
#ifdef USE_MODULES
ModStruct eyes_description =
{"eyes", "init_eyes", "draw_eyes", "release_eyes",
"refresh_eyes", "init_eyes", (char *) NULL, &eyes_opts,
20000, -8, 5, 1, 64, 1.0, "",
"Shows eyes following a bouncing grelb", 0, NULL};
#endif
/* definitions for the xlock version of xeyes */
#define MAX_EYES 200 /* limit or uses too much memory */
#define MIN_EYE_SIZE 50 /* smallest size eyes can be */
#define FLY_ICON_SIZE 5 /* the size of a fly when iconic */
#define FLY_MAX_SPEED 10 /* max (slowest) delay between steps */
#define FLY_SIDE_LEFT 0 /* enter and leave by left side */
#define FLY_SIDE_RIGHT 1 /* enter and leave by right side */
#define LIFE_MIN 100 /* shortest life, cycles */
#define LIFE_RANGE 1000 /* range of possible lifetimes */
#define MAX_CYCLES 10 /* max value of cycles */
#define FRICTION 24 /* affects bounciness */
/* definitions from the original MIT xeyes code */
#define NUM_EYES 2
#define EYE_X(n) ((n) * 2.0)
#define EYE_Y(n) (0.0)
#define EYE_OFFSET (0.1) /* padding between eyes */
#define EYE_THICK (0.175) /* thickness of eye rim */
#define BALL_WIDTH (0.3)
#define BALL_PAD (0.05)
#define EYE_WIDTH (2.0 - (EYE_THICK + EYE_OFFSET) * 2)
#define EYE_HEIGHT EYE_WIDTH
#define EYE_HWIDTH (EYE_WIDTH / 2.0)
#define EYE_HHEIGHT (EYE_HEIGHT / 2.0)
#define BALL_HEIGHT BALL_WIDTH
#define BALL_DIST ((EYE_WIDTH - BALL_WIDTH) / 2.0 - BALL_PAD)
#define W_MIN_X (-1.0 + EYE_OFFSET)
#define W_MAX_X (3.0 - EYE_OFFSET)
#define W_MIN_Y (-1.0 + EYE_OFFSET)
#define W_MAX_Y (1.0 - EYE_OFFSET)
/* ---------------------------------------------------------------------- */
/* definitions of matrix math code used by xeyes */
#define TPointEqual(a, b) ((a).x == (b).x && (a).y == (b).y)
#define XPointEqual(a, b) ((a).x == (b).x && (a).y == (b).y)
typedef struct _transform {
double mx, bx;
double my, by;
} Transform;
typedef struct _TPoint {
double x, y;
} TPoint;
#define Xx(x,y,t) ((int)((t)->mx * (x) + (t)->bx + 0.5))
#define Xy(x,y,t) ((int)((t)->my * (y) + (t)->by + 0.5))
#define Xwidth(w,h,t) ((int)((t)->mx * (w) + 0.5))
#define Xheight(w,h,t) ((int)((t)->my * (h) + 0.5))
#define Tx(x,y,t) ((((double) (x)) - (t)->bx) / (t)->mx)
#define Ty(x,y,t) ((((double) (y)) - (t)->by) / (t)->my)
#define Twidth(w,h,t) (((double) (w)) / (t)->mx)
#define Theight(w,h,t) (((double) (h)) / (t)->my)
/* ---------------------------------------------------------------------- */
/* aliases for vars defined in the bitmap file */
#define FLY_WIDTH image_width
#define FLY_HEIGHT image_height
#define FLY_BITS image_bits
#include "eyes.xbm"
#ifdef XBM_GRELB
#include "eyes2.xbm"
#define FLY2_WIDTH image2_width
#define FLY2_HEIGHT image2_height
#define FLY2_BITS image2_bits
#endif
typedef struct { /* info about a "fly" */
int x, y;
int oldx, oldy;
int width, height;
int vx, vy;
int side;
unsigned long pixel;
int zero_y;
} Fly;
typedef struct { /* info about a pair of eyes */
int x, y;
int width;
int height;
int rectw, recth;
int painted;
unsigned long time_to_die;
unsigned long eyelid_pixel, eyeball_pixel, pupil_pixel;
Pixmap pixmap;
XRectangle bbox;
Transform transform;
TPoint pupil[2];
TPoint last_pupil[2];
} Eyes;
typedef struct { /* per-screen info */
Pixmap flypix;
int flywidth, flyheight;
#ifdef XBM_GRELB
Pixmap fly2pix;
int fly2width, fly2height;
#endif
int graphics_format;
GC eyeGC;
GC flyGC;
int num_eyes;
Eyes *eyes;
Fly fly;
Cursor cursor;
unsigned long time;
} EyeScrInfo;
/* ---------------------------------------------------------------------- */
static EyeScrInfo *eye_info = (EyeScrInfo *) NULL;
/* ---------------------------------------------------------------------- */
/*-
* Fill an arc, using a tranformation matrix. Lifted from xeyes.
* The code to return the bounding box is a local addition.
*/
static void
TFillArc(register Display * dpy, Drawable d, GC gc, Transform * t, double x, double y, double width, double height, int angle1, int angle2, XRectangle * rect)
{
int xx, xy, xw, xh;
xx = Xx(x, y, t);
xy = Xy(x, y, t);
xw = Xwidth(width, height, t);
xh = Xheight(width, height, t);
if (xw < 0) {
xx += xw;
xw = -xw;
}
if (xh < 0) {
xy += xh;
xh = -xh;
}
XFillArc(dpy, d, gc, xx, xy, xw, xh, angle1, angle2);
if (rect != NULL) {
rect->x = xx;
rect->y = xy;
rect->width = xw;
rect->height = xh;
}
}
/*-
* Set a tranform matrix from the given arguments. Lifted from xeyes.
*/
static void
SetTransform(Transform * t, int xx1, int xx2, int xy1, int xy2, double tx1, double tx2, double ty1, double ty2)
{
t->mx = ((double) xx2 - xx1) / (tx2 - tx1);
t->bx = ((double) xx1) - t->mx * tx1;
t->my = ((double) xy2 - xy1) / (ty2 - ty1);
t->by = ((double) xy1) - t->my * ty1;
}
/* ---------------------------------------------------------------------- */
/*-
* Given two rectangles, return the rectangle which encloses both.
* Used to clculate "damage" when the pupil moves, to minimize the
* number of pixels which must be copied out to the screen.
*/
static void
join_rects(XRectangle * r1, XRectangle * r2, XRectangle * ret)
{
XRectangle tmp;
int n1, n2;
/* find min x and min y */
tmp.x = (r1->x <= r2->x) ? r1->x : r2->x;
tmp.y = (r1->y <= r2->y) ? r1->y : r2->y;
/* find max x, plus one (just past the right side) */
n1 = r1->x + r1->width;
n2 = r2->x + r2->width;
/* compute width, relative to min x (left side) */
tmp.width = ((n1 > n2) ? n1 : n2) - tmp.x;
/* same for y */
n1 = r1->y + r1->height;
n2 = r2->y + r2->height;
tmp.height = ((n1 > n2) ? n1 : n2) - tmp.y;
*ret = tmp; /* copy out result rectangle */
}
/* ---------------------------------------------------------------------- */
/*-
* Do the math to figure out where the pupil should be drawn.
* This code lifted intact from the xeyes widget.
*/
#if defined( SVR4 ) || defined( SYSV ) && defined( SYSV386 )
extern double hypot(double, double);
#endif
static void
computePupil(int num, TPoint mouse, TPoint *ret)
{
double cx, cy;
double dist;
double angle;
double x, y;
double h;
double dx, dy;
double cosa, sina;
dx = mouse.x - EYE_X(num);
dy = mouse.y - EYE_Y(num);
if (dx == 0 && dy == 0) {
cx = EYE_X(num);
cy = EYE_Y(num);
} else {
/* Avoid atan2: DOMAIN error message */
if (dx == 0.0 && dy == 0.0)
angle = 0.0;
else
angle = atan2((double) dy, (double) dx);
cosa = cos(angle);
sina = sin(angle);
h = hypot(EYE_HHEIGHT * cosa, EYE_HWIDTH * sina);
x = (EYE_HWIDTH * EYE_HHEIGHT) * cosa / h;
y = (EYE_HWIDTH * EYE_HHEIGHT) * sina / h;
dist = BALL_DIST * hypot(x, y);
if (dist > hypot((double) dx, (double) dy)) {
cx = dx + EYE_X(num);
cy = dy + EYE_Y(num);
} else {
cx = dist * cosa + EYE_X(num);
cy = dist * sina + EYE_Y(num);
}
}
(*ret).x = cx;
(*ret).y = cy;
}
/* ---------------------------------------------------------------------- */
/*-
* Create the eye image, using the data in the structure pointed
* to by "e", in the Drawable "d". The "full" flag indicates
* whether to create the full eye image, or to just paint the
* pupil in a new position.
*/
static void
make_eye(ModeInfo * mi, Drawable d, Eyes * e, int n, int full)
{
EyeScrInfo *ep = &eye_info[MI_SCREEN(mi)];
Display *display = MI_DISPLAY(mi);
GC gc = ep->eyeGC;
XRectangle *bbox = &e->bbox;
XRectangle tmp1, tmp2;
if (full) {
/* draw the outer (eyelid) oval */
XSetForeground(display, gc, e->eyelid_pixel);
TFillArc(display, d, gc, &e->transform,
EYE_X(n) - EYE_HWIDTH - EYE_THICK,
EYE_Y(n) - EYE_HHEIGHT - EYE_THICK,
EYE_WIDTH + EYE_THICK * 2.0,
EYE_HEIGHT + EYE_THICK * 2.0,
90 * 64, 360 * 64, &tmp1);
/* draw the inner (eyeball) oval */
XSetForeground(display, gc, e->eyeball_pixel);
TFillArc(display, d, gc, &e->transform,
EYE_X(n) - EYE_HWIDTH, EYE_Y(n) - EYE_HHEIGHT,
EYE_WIDTH, EYE_HEIGHT, 90 * 64, 360 * 64, &tmp2);
join_rects(&tmp1, &tmp2, &tmp1);
/* draw the pupil on top of the eyeball oval */
XSetForeground(display, gc, e->pupil_pixel);
TFillArc(display, d, gc, &e->transform,
e->pupil[n].x - BALL_WIDTH / 2.0,
e->pupil[n].y - BALL_HEIGHT / 2.0,
BALL_WIDTH, BALL_HEIGHT, 90 * 64, 360 * 64, &tmp2);
join_rects(&tmp1, &tmp2, bbox);
} else {
/* undraw the pupil */
XSetForeground(display, gc, e->eyeball_pixel);
TFillArc(display, d, gc, &e->transform,
e->last_pupil[n].x - BALL_WIDTH / 2.0,
e->last_pupil[n].y - BALL_HEIGHT / 2.0,
BALL_WIDTH, BALL_HEIGHT, 90 * 64, 360 * 64, &tmp1);
/* draw the pupil on top of the eyeball oval */
XSetForeground(display, gc, e->pupil_pixel);
TFillArc(display, d, gc, &e->transform,
e->pupil[n].x - BALL_WIDTH / 2.0,
e->pupil[n].y - BALL_HEIGHT / 2.0,
BALL_WIDTH, BALL_HEIGHT, 90 * 64, 360 * 64, &tmp2);
join_rects(&tmp1, &tmp2, bbox);
}
}
/* ---------------------------------------------------------------------- */
/*-
* Check to see if the flyer touches this pair of eyes.
*/
static Bool
fly_touches(Fly * f, Eyes * e, int old)
{
int x = (old) ? f->oldx : f->x;
int y = (old) ? f->oldy : f->y;
if ((x + f->width) <= e->x)
return (False);
if (x >= (e->x + e->width))
return (False);
if ((y + f->height) <= e->y)
return (False);
if (y >= (e->y + e->height))
return (False);
return (True);
}
static Bool
fly_touches_eye(Fly * f, Eyes * e)
{
if (fly_touches(f, e, True) || fly_touches(f, e, False)) {
return (True);
}
return (False);
}
/*-
* Check to see if two pairs of eyes overlap.
*/
static Bool
eyes_overlap(Eyes * e1, Eyes * e2)
{
if ((e1->x + e1->width) < e2->x)
return (False);
if (e1->x >= (e2->x + e2->width))
return (False);
if ((e1->y + e1->height) < e2->y)
return (False);
if (e1->y >= (e2->y + e2->height))
return (False);
return (True);
}
/* ---------------------------------------------------------------------- */
/*-
* Initialize the flyer. Called when the window changes, and
* whenever she bounces off the screen.
* In the first version, the eyes followed a "fly", which was
* just a flickering spot that moved at random. That didn't
* work so well. It was replaced with a bouncing gelb, but the
* name "fly" has yet to be purged.
*/
static void
init_fly(ModeInfo * mi, Fly * f)
{
EyeScrInfo *ep = &eye_info[MI_SCREEN(mi)];
int win_width = MI_WIDTH(mi);
int win_height = MI_HEIGHT(mi);
(void) memset((char *) f, 0, sizeof (Fly)); /* clear everything to zero */
f->side = FLY_SIDE_LEFT;
if (!MI_IS_ICONIC(mi))
{
f->width = ep->flywidth;
f->height = ep->flyheight;
f->vx = NRAND(15) + 1; /* random horiz velocity */
} else
{
/* image is just a dot when iconic */
f->width = f->height = FLY_ICON_SIZE;
f->vx = NRAND(4) + 1; /* slower when iconic */
}
f->y = NRAND(win_height);
if (f->y > (win_height / 2)) {
f->side = FLY_SIDE_RIGHT; /* change to right side */
f->y -= win_height / 2; /* start in top half */
f->x = win_width - f->width; /* move to right of screen */
f->vx = -(f->vx); /* flip direction */
}
f->oldx = -(f->width); /* prevent undraw 1st time */
if (MI_NPIXELS(mi) <= 2) {
f->pixel = MI_WHITE_PIXEL(mi); /* always white when mono */
} else {
f->pixel = MI_PIXEL(mi, NRAND(MI_NPIXELS(mi)));
}
}
/*-
* Unpaint the flyer by painting the image in black.
*/
static void
unpaint_fly(ModeInfo * mi, Fly * f)
{
Display *display = MI_DISPLAY(mi);
Window window = MI_WINDOW(mi);
GC gc = MI_GC(mi);
if (MI_IS_ICONIC(mi)) {
XSetForeground(display, gc, MI_BLACK_PIXEL(mi));
XFillArc(display, window, gc, f->oldx, f->oldy,
f->width, f->height, 90 * 64, 360 * 64);
} else {
XSetForeground(display, gc, MI_BLACK_PIXEL(mi));
#ifdef FLASH
XFillRectangle(display, window, gc,
f->oldx, f->oldy, f->width, f->height);
#else
ERASE_IMAGE(display, window, gc, f->x, f->y,
f->oldx, f->oldy, f->width, f->height);
#endif
}
}
/*-
* Paint the bouncing grelb on the screen. If not in iconic
* mode, unpaint the previous image. When iconic, the fly
* doesn't need to be undrawn, because it will always be on top
* of the eyes, which are repainted before the fly is painted.
*/
static void
paint_fly(ModeInfo * mi, Fly * f)
{
EyeScrInfo *ep = &eye_info[MI_SCREEN(mi)];
Display *display = MI_DISPLAY(mi);
Window window = MI_WINDOW(mi);
int x = f->x, y = f->y;
if (MI_IS_ICONIC(mi)) {
/* don't need to unpaint when iconic
* ep->flyGC has stipple set, don't use when iconic
*/
XSetForeground(display, MI_GC(mi), f->pixel);
XFillArc(display, window, MI_GC(mi), x, y,
f->width, f->height, 90 * 64, 360 * 64);
} else {
unpaint_fly(mi, f);
XSetForeground(display, ep->flyGC, f->pixel);
#ifdef XBM_GRELB
if (ep->fly2pix != None) {
XSetStipple(display, ep->flyGC, (f->vy <= 0) ? ep->flypix : ep->fly2pix);
} else
#endif
XSetStipple(display, ep->flyGC, ep->flypix);
XSetTSOrigin(display, ep->flyGC, x, y);
#ifdef FLASH
XSetFillStyle(display, ep->flyGC, FillStippled);
#else
XSetFillStyle(display, ep->flyGC, FillOpaqueStippled);
#endif
XFillRectangle(display, window, ep->flyGC,
x, y, f->width, f->height);
XFlush(display);
}
}
/*-
* Compute the new position of the fly. The bouncy-boinginess
* algorithm is borrowed from the "bounce" (soccer ball) mode.
*/
static void
move_fly(ModeInfo * mi, Fly * f)
{
int win_width = MI_WIDTH(mi);
int win_height = MI_HEIGHT(mi);
int left = (f->side == FLY_SIDE_LEFT) ? -(f->width) : 0;
int right = (f->side == FLY_SIDE_RIGHT) ? win_width :
win_width - f->width;
Bool track_p = trackmouse;
int cx, cy;
f->oldx = f->x; /* remember position before moving, */
f->oldy = f->y; /* for unpainting previous image */
if (track_p) {
Window r, c;
int rx, ry;
unsigned int m;
(void) XQueryPointer(MI_DISPLAY(mi), MI_WINDOW(mi),
&r, &c, &rx, &ry, &cx, &cy, &m);
if (cx <= 0 || cy <= 0 ||
cx >= MI_WIDTH(mi) - f->width - 1 ||
cy >= MI_HEIGHT(mi) - f->width - 1) {
track_p = False;
}
}
if (track_p) {
f->x = cx;
f->y = cy;
return;
}
f->x += f->vx; /* apply x velocity */
if (f->x > right) {
if (f->side == FLY_SIDE_RIGHT) {
unpaint_fly(mi, f); /* went off the edge, reset */
init_fly(mi, f);
} else {
/* Bounce off the right edge */
f->x = 2 * (win_width - f->width) - f->x;
f->vx = -f->vx + f->vx / FRICTION;
}
} else if (f->x < left) {
if (f->side == FLY_SIDE_LEFT) {
unpaint_fly(mi, f); /* went off the edge, reset */
init_fly(mi, f);
} else {
/* Bounce off the left edge */
f->x = -f->x;
f->vx = -f->vx + f->vx / FRICTION;
}
}
f->vy++; /* gravity, accelerate in y direction */
f->y += f->vy; /* apply y velocity */
if (f->y >= (win_height - f->height)) {
/* Bounce off the bottom edge */
f->y = (win_height - f->height);
f->vy = -f->vy + f->vy / FRICTION;
/* every once in a while, go apeshit to clean "high lurkers" */
if (NRAND(50) == 0) {
f->vy *= 4;
}
} else if (f->y < 0) {
/* Bounce off the top edge */
f->y = -f->y;
f->vy = -f->vy + f->vy / FRICTION;
}
/* if he settles to the bottom, move him off quick */
if (abs(f->vy) < 2) {
if ((f->zero_y++) > 10) {
f->vx += (f->side == FLY_SIDE_LEFT) ? -1 : 1;
}
} else {
f->zero_y = 0; /* still bouncing */
}
}
/* ---------------------------------------------------------------------- */
/*-
* Initialize one pair of eyes
*/
static void
create_eyes(ModeInfo * mi, Eyes * e, Eyes * eyes, int num_eyes)
{
EyeScrInfo *ep = &eye_info[MI_SCREEN(mi)];
Display *display = MI_DISPLAY(mi);
Window window = MI_WINDOW(mi);
int win_width = MI_WIDTH(mi);
int win_height = MI_HEIGHT(mi);
unsigned long black_pixel = MI_BLACK_PIXEL(mi);
unsigned long white_pixel = MI_WHITE_PIXEL(mi);
Bool iconic = MI_IS_ICONIC(mi);
Pixmap pix = e->pixmap; /* preserve pixmap handle */
int w = e->width; /* remember last w/h */
int h = e->height;
int npixels = MI_NPIXELS(mi); /* num colors in colormap */
int cycs = MI_CYCLES(mi); /* affects eye lifetime */
int maxw = win_width / 2; /* widest eyes can be */
int color, lid_color;
int i;
(void) memset((char *) e, 0, sizeof (Eyes)); /* wipe everything */
e->pixmap = pix; /* remember Pixmap handle */
/* sanity check the cycles value */
if (cycs < 1)
cycs = 1;
if (cycs > MAX_CYCLES)
cycs = MAX_CYCLES;
e->time_to_die = (unsigned long) LIFE_MIN + NRAND(LIFE_RANGE);
e->time_to_die *= (unsigned long) cycs; /* multiply life by cycles */
e->time_to_die += ep->time;
e->pupil_pixel = black_pixel; /* pupil is always black */
if (MI_NPIXELS(mi) <= 2) {
/* TODO: stipple the eyelid? */
e->eyelid_pixel = black_pixel;
e->eyeball_pixel = white_pixel;
} else {
lid_color = NRAND(npixels);
e->eyelid_pixel = MI_PIXEL(mi, lid_color);
while ((color = NRAND(npixels + 5)) == lid_color) {
/* empty */
}
if (color >= npixels) {
/* give white a little better chance */
e->eyeball_pixel = white_pixel;
} else {
e->eyeball_pixel = MI_PIXEL(mi, color);
}
}
if (iconic) {
/* only one pair of eyes, fills entire window */
e->width = win_width;
e->height = win_height;
} else {
if (maxw - MIN_EYE_SIZE > MIN_EYE_SIZE)
e->width = NRAND(maxw - MIN_EYE_SIZE) + MIN_EYE_SIZE;
else
e->width = NRAND(MIN_EYE_SIZE) + MIN_EYE_SIZE;
e->x = (win_width - e->width > 0) ? NRAND(win_width - e->width) : 0;
e->height = NRAND(e->width * 3 / 4) + (e->width / 4);
e->y = (win_height - e->height > 0) ? NRAND(win_height - e->height) : 0;
/* check for overlap with other eyes */
for (i = 0; i < num_eyes; i++) {
if (&eyes[i] == e) { /* that's me */
continue;
}
if (eyes_overlap(e, &eyes[i])) {
/* collision, force retry on next cycle */
e->time_to_die = 0;
break;
}
}
}
/* If the Pixmap is smaller than the new size, make it bigger */
if ((e->width > w) || (e->height > h)) {
if (e->pixmap != None) {
XFreePixmap(display, e->pixmap);
}
if ((e->pixmap = XCreatePixmap(display, window,
e->width, e->height, MI_DEPTH(mi))) == None) {
e->width = e->height = 0;
return;
}
}
/* Set the transformation matrix for this set of eyes
* If iconic, make the eyes image one pixel shorter and
* skinnier, they seem to fit in the icon box better that way.
*/
SetTransform(&e->transform, 0, (iconic) ? e->width - 1 : e->width,
(iconic) ? e->height - 1 : e->height, 0,
W_MIN_X, W_MAX_X, W_MIN_Y, W_MAX_Y);
/* clear the offscreen pixmap to background color */
XSetForeground(display, ep->eyeGC, black_pixel);
XFillRectangle(display, (Drawable) e->pixmap, ep->eyeGC, 0, 0, e->width, e->height);
/* make the full eye images in the offscreen Pixmap */
make_eye(mi, e->pixmap, e, 0, True);
make_eye(mi, e->pixmap, e, 1, True);
}
/*-
* Paint an eye pair onto the screen.
* This is normally only the change rectangles for each pupil,
* unless in iconic mode, which always repaints the full image.
*/
static void
paint_eyes(ModeInfo * mi, Eyes * e, Fly * f, Eyes * eyes, int num_eyes)
{
EyeScrInfo *ep = &eye_info[MI_SCREEN(mi)];
Display *display = MI_DISPLAY(mi);
Window window = MI_WINDOW(mi);
GC gc = ep->eyeGC;
Bool iconic = MI_IS_ICONIC(mi);
int focusx = (f->x + (f->width / 2)) - e->x;
int focusy = (f->y + (f->height / 2)) - e->y;
Pixmap pix = e->pixmap;
TPoint point;
int i;
if (pix == None) {
e->time_to_die = 0; /* "should not happen" */
}
if (ep->time >= e->time_to_die) {
/* Sorry Bud, your time is up */
if (e->painted) {
/* only unpaint it if previously painted */
XSetForeground(display, gc, MI_BLACK_PIXEL(mi));
XFillRectangle(display, window, gc, e->x, e->y, e->width, e->height);
}
/* randomly place the eyes elsewhere */
create_eyes(mi, e, eyes, num_eyes);
pix = e->pixmap; /* pixmap may have changed */
}
/* If the bouncer would intersect this pair of eyes, force the
* eyes to move. This simplifies the code, because we do not
* have to deal with drawing the bouncer on top of the eyes.
* When trying to do so, there was too much annoying flashing
* and ghost images from the undraw. I decided to observe the
* KISS principle and keep it simple. I think the effect is
* better also.
* We must draw the flyer on the eyes when iconic, but that is
* easy because the eyes repaint the whole box each time.
*/
if ((!iconic) && (fly_touches_eye(f, e))) {
e->time_to_die = 0;
}
if (e->time_to_die == 0) {
return; /* collides with something */
}
/* set the point to look at and compute the pupil position */
point.x = Tx(focusx, focusy, &e->transform);
point.y = Ty(focusx, focusy, &e->transform);
computePupil(0, point, &(e->pupil[0]));
computePupil(1, point, &(e->pupil[1]));
if (e->painted) {
/* if still looking at the same point, do nothing further */
if (TPointEqual(e->pupil[0], e->last_pupil[0]) &&
TPointEqual(e->pupil[1], e->last_pupil[1])) {
return;
}
}
for (i = 0; i < 2; i++) {
/* update the eye, calculates the changed rectangle */
make_eye(mi, pix, e, i, False);
/* Only blit the change if the full image has been painted */
if (e->painted) {
/* copy the changed rectangle out to the screen */
XCopyArea(display, pix, window, gc,
e->bbox.x, e->bbox.y,
(int) e->bbox.width, (int) e->bbox.height,
e->x + e->bbox.x, e->y + e->bbox.y);
}
/* remember where we're looking, for the next time around */
e->last_pupil[i] = e->pupil[i];
}
/* always do full paint when iconic, eliminates need to track fly */
if (iconic || (!e->painted)) {
XCopyArea(display, pix, window, gc, 0, 0,
e->width, e->height, e->x, e->y);
}
/* when iconic, pretend to never paint, causes full paint each time */
if (!iconic) {
e->painted++; /* note that a paint has been done */
}
}
/* ---------------------------------------------------------------------- */
static void
freePairsOfEyes(Display * display, EyeScrInfo * ep)
{
int en;
if (ep->eyes) {
for (en = 0; en < ep->num_eyes; en++)
if (ep->eyes[en].pixmap != None)
XFreePixmap(display, ep->eyes[en].pixmap);
free(ep->eyes);
ep->eyes = (Eyes *) NULL;
}
}
static void
free_eyes(Display * display, EyeScrInfo * ep)
{
if (ep->flyGC != None) {
XFreeGC(display, ep->flyGC);
ep->flyGC = None;
}
if (ep->eyeGC != None) {
XFreeGC(display, ep->eyeGC);
ep->eyeGC = None;
}
if (ep->flypix != None) {
XFreePixmap(display, ep->flypix);
ep->flypix = None;
}
#ifdef XBM_GRELB
if (ep->fly2pix != None) {
XFreePixmap(display, ep->fly2pix);
ep->fly2pix = None;
}
#endif
freePairsOfEyes(display, ep);
if (ep->cursor != None) {
XFreeCursor(display, ep->cursor);
ep->cursor = None;
}
}
/*-
* Initialize them eyes. Called each time the window changes.
*/
void
init_eyes(ModeInfo * mi)
{
Display *display = MI_DISPLAY(mi);
Window window = MI_WINDOW(mi);
EyeScrInfo *ep;
int i;
/*-
* Initialization that only needs to be done once. If the
* release hook is called, this stuff may be freed and this
* function will have to allocate it again next time the
* init hook is called.
*/
if (eye_info == NULL) {
if ((eye_info = (EyeScrInfo *) calloc(MI_NUM_SCREENS(mi),
sizeof (EyeScrInfo))) == NULL)
return;
}
ep = &eye_info[MI_SCREEN(mi)];
if (ep->flypix == None) {
getPixmap(mi, window, FLY_WIDTH, FLY_HEIGHT, FLY_BITS,
&(ep->flywidth), &(ep->flyheight), &(ep->flypix),
&(ep->graphics_format));
if (ep->flypix == None) {
free_eyes(display, ep);
return;
}
#ifdef XBM_GRELB
if (ep->graphics_format == IS_XBM) {
ep->graphics_format =0;
getPixmap(mi, window,
FLY2_WIDTH, FLY2_HEIGHT, FLY2_BITS,
&(ep->fly2width), &(ep->fly2height), &(ep->fly2pix),
&(ep->graphics_format));
if (ep->fly2pix == None) {
free_eyes(display, ep);
return;
}
}
#endif
}
if (ep->flyGC == None) {
XGCValues gcv;
gcv.foreground = MI_BLACK_PIXEL(mi);
gcv.background = MI_BLACK_PIXEL(mi);
if ((ep->flyGC = XCreateGC(display, window,
GCForeground | GCBackground, &gcv)) == None) {
free_eyes(display, ep);
return;
}
}
if (ep->eyeGC == None) {
if ((ep->eyeGC = XCreateGC(display, window,
(unsigned long) 0, (XGCValues *) NULL)) == None) {
free_eyes(display, ep);
return;
}
}
ep->time = 0;
/* don't want any exposure events from XCopyArea */
XSetGraphicsExposures(display, ep->eyeGC, False);
freePairsOfEyes(display, ep);
if (MI_IS_ICONIC(mi))
ep->num_eyes = 1;
else {
ep->num_eyes = MI_COUNT(mi);
/* MAX_EYES is used or one may quickly run out of memory */
if (ep->num_eyes > MAX_EYES)
ep->num_eyes = MAX_EYES;
if (ep->num_eyes < 0) {
if (ep->num_eyes < -MAX_EYES)
ep->num_eyes = NRAND(MAX_EYES) + 1;
else
ep->num_eyes = NRAND(-ep->num_eyes) + 1; /* Add 1 so its not too boring */
}
}
if (!ep->eyes) {
if ((ep->eyes = (Eyes *) calloc(ep->num_eyes, sizeof (Eyes))) == NULL) {
free_eyes(display, ep);
return;
}
}
for (i = 0; i < ep->num_eyes; i++) { /* place each eye pair */
/* don't assume None == 0 */
ep->eyes[i].pixmap = None;
create_eyes(mi, &(ep->eyes[i]), ep->eyes, ep->num_eyes);
}
init_fly(mi, &(ep->fly)); /* init the bouncer */
if (trackmouse && !ep->cursor) { /* Create an invisible cursor */
Pixmap bit;
XColor black;
black.red = 0;
black.green = 0;
black.blue = 0;
black.flags = DoRed | DoGreen | DoBlue;
if ((bit = XCreatePixmapFromBitmapData(display, window,
(char *) "\000", 1, 1, MI_BLACK_PIXEL(mi),
MI_BLACK_PIXEL(mi), 1)) == None) {
free_eyes(display, ep);
return;
}
if ((ep->cursor = XCreatePixmapCursor(display, bit, bit,
&black, &black, 0, 0)) == None) {
free_eyes(display, ep);
return;
}
XFreePixmap(display, bit);
}
XDefineCursor(display, window, ep->cursor);
MI_CLEARWINDOW(mi);
}
/* ---------------------------------------------------------------------- */
/*-
* Called by the mainline code periodically to update the display.
*/
void
draw_eyes(ModeInfo * mi)
{
int i;
EyeScrInfo *ep;
if (eye_info == NULL)
return;
ep = &eye_info[MI_SCREEN(mi)];
if (ep->flypix == None)
return;
MI_IS_DRAWN(mi) = True;
move_fly(mi, &(ep->fly));
ep->time++;
for (i = 0; i < ep->num_eyes; i++) {
paint_eyes(mi, &(ep->eyes[i]), &(ep->fly), ep->eyes, ep->num_eyes);
}
paint_fly(mi, &(ep->fly));
}
/* ---------------------------------------------------------------------- */
/*-
* The display is being taken away from us. Free up malloc'ed
* memory and X resources that we've alloc'ed. Only called
* once, we must zap everything for every screen.
*/
void
release_eyes(ModeInfo * mi)
{
if (eye_info != NULL) {
int screen;
for (screen = 0; screen < MI_NUM_SCREENS(mi); screen++)
free_eyes(MI_DISPLAY(mi), &eye_info[screen]);
free(eye_info);
}
eye_info = (EyeScrInfo *) NULL;
}
/* ---------------------------------------------------------------------- */
/*-
* Called when the mainline xlock code notices possible window
* damage. This hook should take steps to repaint the entire
* window (no specific damage area information is provided).
*/
void
refresh_eyes(ModeInfo * mi)
{
int i;
EyeScrInfo *ep;
if (eye_info == NULL)
return;
ep = &eye_info[MI_SCREEN(mi)];
if (ep->eyeGC == None)
return;
MI_CLEARWINDOW(mi);
/* simply flag all the eyes as not painted, will repaint next time */
for (i = 0; i < ep->num_eyes; i++) {
ep->eyes[i].painted = False;
}
}
#endif /* MODE_eyes */
|
4708d4bb4a5e7e5fa64a61f73cafb4df9054095b
|
f9e7d65cb784c01a0200145ba8d289afe41d4a56
|
/board/jacuzzi/battery.c
|
443bf1e98a3af72540896de2912d0d1d1ce36cdd
|
[
"BSD-3-Clause"
] |
permissive
|
FrameworkComputer/EmbeddedController
|
ad7086769e87d0a4179eae96a7c9ff5e383ff54e
|
f6d6b927eed71550d3475411cfc3e59abe5cef2a
|
refs/heads/hx20-hx30
| 2023-08-08T20:45:10.621169
| 2023-05-26T07:03:59
| 2023-05-26T07:03:59
| 447,021,040
| 846
| 48
|
BSD-3-Clause
| 2023-05-26T07:04:59
| 2022-01-12T00:11:14
|
C
|
UTF-8
|
C
| false
| false
| 3,495
|
c
|
battery.c
|
/* Copyright 2019 The Chromium OS Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "battery.h"
#include "battery_fuel_gauge.h"
#include "gpio.h"
const struct board_batt_params board_battery_info[] = {
[BATTERY_PANASONIC_AC15A3J] = {
.fuel_gauge = {
.manuf_name = "PANASONIC",
.device_name = "AC15A3J",
.ship_mode = {
.reg_addr = 0x3A,
.reg_data = { 0xC574, 0xC574 },
},
.fet = {
.reg_addr = 0x0,
.reg_mask = 0x4000,
.disconnect_val = 0x0,
}
},
.batt_info = {
.voltage_max = 13200,
.voltage_normal = 11580,
.voltage_min = 9000,
.precharge_current = 256,
.start_charging_min_c = 0,
.start_charging_max_c = 45,
.charging_min_c = 0,
.charging_max_c = 60,
.discharging_min_c = -20,
.discharging_max_c = 60,
},
},
[BATTERY_PANASONIC_AC16L5J] = {
.fuel_gauge = {
.manuf_name = "PANASONIC",
.device_name = "AP16L5J",
.ship_mode = {
.reg_addr = 0x3A,
.reg_data = { 0xC574, 0xC574 },
},
.fet = {
.reg_addr = 0x0,
.reg_mask = 0x4000,
.disconnect_val = 0x0,
}
},
.batt_info = {
.voltage_max = 8800,
.voltage_normal = 7700,
.voltage_min = 6000,
.precharge_current = 256,
.start_charging_min_c = 0,
.start_charging_max_c = 50,
.charging_min_c = 0,
.charging_max_c = 60,
.discharging_min_c = -20,
.discharging_max_c = 75,
},
},
[BATTERY_LGC_AC16L8J] = {
.fuel_gauge = {
.manuf_name = "LGC KT0020G010",
.device_name = "AP16L8J",
.ship_mode = {
.reg_addr = 0x3A,
.reg_data = { 0xC574, 0xC574 },
},
.fet = {
.mfgacc_support = 1,
.reg_addr = 0x0,
.reg_mask = 0x0002,
.disconnect_val = 0x0,
}
},
.batt_info = {
.voltage_max = 8700,
.voltage_normal = 7500,
.voltage_min = 6000,
.precharge_current = 256,
.start_charging_min_c = 0,
.start_charging_max_c = 50,
.charging_min_c = 0,
.charging_max_c = 60,
.discharging_min_c = -20,
.discharging_max_c = 75,
},
},
[BATTERY_PANASONIC_AC16L5J_KT00205009] = {
.fuel_gauge = {
.manuf_name = "PANASONIC KT00205009",
.device_name = "AP16L5J",
.ship_mode = {
.reg_addr = 0x3A,
.reg_data = { 0xC574, 0xC574 },
},
.fet = {
.reg_addr = 0x0,
.reg_mask = 0x4000,
.disconnect_val = 0x0,
}
},
.batt_info = {
.voltage_max = 8800,
.voltage_normal = 7700,
.voltage_min = 6000,
.precharge_current = 256,
.start_charging_min_c = 0,
.start_charging_max_c = 50,
.charging_min_c = 0,
.charging_max_c = 60,
.discharging_min_c = -20,
.discharging_max_c = 75,
},
},
};
BUILD_ASSERT(ARRAY_SIZE(board_battery_info) == BATTERY_TYPE_COUNT);
const enum battery_type DEFAULT_BATTERY_TYPE = BATTERY_PANASONIC_AC16L5J_KT00205009;
enum battery_present battery_hw_present(void)
{
return gpio_get_level(GPIO_EC_BATT_PRES_ODL) ? BP_NO : BP_YES;
}
|
571a30135ba0b05fdddada65ecbc9cc058a5df34
|
0ab34cafb4fce823bdb64588375a5e0320c4d5da
|
/src/platform/win32/time.c
|
44cbc8ebfd858074d562f843750fd52cd906b190
|
[
"Artistic-2.0",
"MIT",
"BSD-3-Clause",
"LicenseRef-scancode-public-domain"
] |
permissive
|
MoarVM/MoarVM
|
00eb8de04ef3eb43d8dd108a016a5fbd644f7cb7
|
2f8234c222dea886da28a9e369e34f3cff18ad8a
|
refs/heads/main
| 2023-08-24T03:30:58.906341
| 2023-08-23T03:28:20
| 2023-08-23T03:28:20
| 10,411,154
| 616
| 228
|
NOASSERTION
| 2023-08-23T03:28:33
| 2013-05-31T19:02:30
|
C
|
UTF-8
|
C
| false
| false
| 1,382
|
c
|
time.c
|
#include "moar.h"
#include "platform/time.h"
#include <windows.h>
#include <time.h>
/* see http://support.microsoft.com/kb/167296 */
#define OFFSET 116444736000000000
#define E6 1000000
MVMuint64 MVM_platform_now(void)
{
union { FILETIME ft; MVMuint64 u; } now;
GetSystemTimeAsFileTime(&now.ft);
return (now.u - OFFSET) * 100;
}
void MVM_platform_sleep(MVMnum64 second)
{
DWORD millis = (DWORD)(second * 1000);
Sleep(millis);
}
void MVM_platform_nanosleep(MVMuint64 nanos)
{
MVMuint64 now;
DWORD millis;
const MVMuint64 end = MVM_platform_now() + nanos;
millis = (DWORD)((nanos + E6 - 1) / E6);
while(1) {
Sleep(millis);
now = MVM_platform_now();
if (now >= end)
break;
millis = (DWORD)((end - now) / E6);
}
}
void MVM_platform_decodelocaltime(MVMThreadContext *tc, MVMint64 time, MVMint64 decoded[]) {
const time_t t = (time_t)time;
struct tm tm;
errno_t error = localtime_s(&tm, &t);
if (error != 0)
MVM_exception_throw_adhoc(tc, "Could not decode localtime: %s", strerror(error));
decoded[0] = tm.tm_sec;
decoded[1] = tm.tm_min;
decoded[2] = tm.tm_hour;
decoded[3] = tm.tm_mday;
decoded[4] = tm.tm_mon + 1;
decoded[5] = tm.tm_year + 1900;
decoded[6] = tm.tm_wday;
decoded[7] = tm.tm_yday;
decoded[8] = tm.tm_isdst;
}
|
f279f1ccad640b11952cf827215b69ea6444696d
|
d38ed5f31d74a79a054ed55dd9123a8d615283b9
|
/third_party/libgit2/src/patch_parse.c
|
d7311157f3c77d94983c562902210b70b9c27c6d
|
[
"GPL-2.0-only",
"LicenseRef-scancode-public-domain",
"GCC-exception-2.0",
"LGPL-2.0-or-later",
"Zlib",
"LGPL-2.1-or-later",
"LGPL-2.1-only",
"ISC",
"MIT",
"Apache-2.0"
] |
permissive
|
chigraph/chigraph
|
8ff76a14337da29fa2b2a84d5c35f2eac4156c6e
|
6981bdd6763db54edfe284c1f7d223193584c69a
|
refs/heads/master
| 2022-12-21T13:46:57.273039
| 2022-12-17T18:41:19
| 2022-12-17T18:41:19
| 60,776,831
| 364
| 65
|
Apache-2.0
| 2019-12-13T14:46:43
| 2016-06-09T13:27:37
|
C++
|
UTF-8
|
C
| false
| false
| 29,667
|
c
|
patch_parse.c
|
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#include "patch_parse.h"
#include "git2/patch.h"
#include "patch.h"
#include "diff_parse.h"
#include "path.h"
typedef struct {
git_patch base;
git_patch_parse_ctx *ctx;
/* the paths from the `diff --git` header, these will be used if this is not
* a rename (and rename paths are specified) or if no `+++`/`---` line specify
* the paths.
*/
char *header_old_path, *header_new_path;
/* renamed paths are precise and are not prefixed */
char *rename_old_path, *rename_new_path;
/* the paths given in `---` and `+++` lines */
char *old_path, *new_path;
/* the prefixes from the old/new paths */
char *old_prefix, *new_prefix;
} git_patch_parsed;
static int header_path_len(git_patch_parse_ctx *ctx)
{
bool inquote = 0;
bool quoted = git_parse_ctx_contains_s(&ctx->parse_ctx, "\"");
size_t len;
for (len = quoted; len < ctx->parse_ctx.line_len; len++) {
if (!quoted && git__isspace(ctx->parse_ctx.line[len]))
break;
else if (quoted && !inquote && ctx->parse_ctx.line[len] == '"') {
len++;
break;
}
inquote = (!inquote && ctx->parse_ctx.line[len] == '\\');
}
return len;
}
static int parse_header_path_buf(git_buf *path, git_patch_parse_ctx *ctx, size_t path_len)
{
int error;
if ((error = git_buf_put(path, ctx->parse_ctx.line, path_len)) < 0)
goto done;
git_parse_advance_chars(&ctx->parse_ctx, path_len);
git_buf_rtrim(path);
if (path->size > 0 && path->ptr[0] == '"')
error = git_buf_unquote(path);
if (error < 0)
goto done;
git_path_squash_slashes(path);
done:
return error;
}
static int parse_header_path(char **out, git_patch_parse_ctx *ctx)
{
git_buf path = GIT_BUF_INIT;
int error = parse_header_path_buf(&path, ctx, header_path_len(ctx));
*out = git_buf_detach(&path);
return error;
}
static int parse_header_git_oldpath(
git_patch_parsed *patch, git_patch_parse_ctx *ctx)
{
git_buf old_path = GIT_BUF_INIT;
int error;
if ((error = parse_header_path_buf(&old_path, ctx, ctx->parse_ctx.line_len - 1)) < 0)
goto out;
patch->old_path = git_buf_detach(&old_path);
out:
git_buf_dispose(&old_path);
return error;
}
static int parse_header_git_newpath(
git_patch_parsed *patch, git_patch_parse_ctx *ctx)
{
git_buf new_path = GIT_BUF_INIT;
int error;
if ((error = parse_header_path_buf(&new_path, ctx, ctx->parse_ctx.line_len - 1)) < 0)
goto out;
patch->new_path = git_buf_detach(&new_path);
out:
git_buf_dispose(&new_path);
return error;
}
static int parse_header_mode(uint16_t *mode, git_patch_parse_ctx *ctx)
{
int64_t m;
if ((git_parse_advance_digit(&m, &ctx->parse_ctx, 8)) < 0)
return git_parse_err("invalid file mode at line %"PRIuZ, ctx->parse_ctx.line_num);
if (m > UINT16_MAX)
return -1;
*mode = (uint16_t)m;
return 0;
}
static int parse_header_oid(
git_oid *oid,
uint16_t *oid_len,
git_patch_parse_ctx *ctx)
{
size_t len;
for (len = 0; len < ctx->parse_ctx.line_len && len < GIT_OID_HEXSZ; len++) {
if (!git__isxdigit(ctx->parse_ctx.line[len]))
break;
}
if (len < GIT_OID_MINPREFIXLEN || len > GIT_OID_HEXSZ ||
git_oid_fromstrn(oid, ctx->parse_ctx.line, len) < 0)
return git_parse_err("invalid hex formatted object id at line %"PRIuZ,
ctx->parse_ctx.line_num);
git_parse_advance_chars(&ctx->parse_ctx, len);
*oid_len = (uint16_t)len;
return 0;
}
static int parse_header_git_index(
git_patch_parsed *patch, git_patch_parse_ctx *ctx)
{
char c;
if (parse_header_oid(&patch->base.delta->old_file.id,
&patch->base.delta->old_file.id_abbrev, ctx) < 0 ||
git_parse_advance_expected_str(&ctx->parse_ctx, "..") < 0 ||
parse_header_oid(&patch->base.delta->new_file.id,
&patch->base.delta->new_file.id_abbrev, ctx) < 0)
return -1;
if (git_parse_peek(&c, &ctx->parse_ctx, 0) == 0 && c == ' ') {
uint16_t mode;
git_parse_advance_chars(&ctx->parse_ctx, 1);
if (parse_header_mode(&mode, ctx) < 0)
return -1;
if (!patch->base.delta->new_file.mode)
patch->base.delta->new_file.mode = mode;
if (!patch->base.delta->old_file.mode)
patch->base.delta->old_file.mode = mode;
}
return 0;
}
static int parse_header_git_oldmode(
git_patch_parsed *patch, git_patch_parse_ctx *ctx)
{
return parse_header_mode(&patch->base.delta->old_file.mode, ctx);
}
static int parse_header_git_newmode(
git_patch_parsed *patch, git_patch_parse_ctx *ctx)
{
return parse_header_mode(&patch->base.delta->new_file.mode, ctx);
}
static int parse_header_git_deletedfilemode(
git_patch_parsed *patch,
git_patch_parse_ctx *ctx)
{
git__free((char *)patch->base.delta->old_file.path);
patch->base.delta->old_file.path = NULL;
patch->base.delta->status = GIT_DELTA_DELETED;
patch->base.delta->nfiles = 1;
return parse_header_mode(&patch->base.delta->old_file.mode, ctx);
}
static int parse_header_git_newfilemode(
git_patch_parsed *patch,
git_patch_parse_ctx *ctx)
{
git__free((char *)patch->base.delta->new_file.path);
patch->base.delta->new_file.path = NULL;
patch->base.delta->status = GIT_DELTA_ADDED;
patch->base.delta->nfiles = 1;
return parse_header_mode(&patch->base.delta->new_file.mode, ctx);
}
static int parse_header_rename(
char **out,
git_patch_parse_ctx *ctx)
{
git_buf path = GIT_BUF_INIT;
if (parse_header_path_buf(&path, ctx, header_path_len(ctx)) < 0)
return -1;
/* Note: the `rename from` and `rename to` lines include the literal
* filename. They do *not* include the prefix. (Who needs consistency?)
*/
*out = git_buf_detach(&path);
return 0;
}
static int parse_header_renamefrom(
git_patch_parsed *patch, git_patch_parse_ctx *ctx)
{
patch->base.delta->status = GIT_DELTA_RENAMED;
return parse_header_rename(&patch->rename_old_path, ctx);
}
static int parse_header_renameto(
git_patch_parsed *patch, git_patch_parse_ctx *ctx)
{
patch->base.delta->status = GIT_DELTA_RENAMED;
return parse_header_rename(&patch->rename_new_path, ctx);
}
static int parse_header_copyfrom(
git_patch_parsed *patch, git_patch_parse_ctx *ctx)
{
patch->base.delta->status = GIT_DELTA_COPIED;
return parse_header_rename(&patch->rename_old_path, ctx);
}
static int parse_header_copyto(
git_patch_parsed *patch, git_patch_parse_ctx *ctx)
{
patch->base.delta->status = GIT_DELTA_COPIED;
return parse_header_rename(&patch->rename_new_path, ctx);
}
static int parse_header_percent(uint16_t *out, git_patch_parse_ctx *ctx)
{
int64_t val;
if (git_parse_advance_digit(&val, &ctx->parse_ctx, 10) < 0)
return -1;
if (git_parse_advance_expected_str(&ctx->parse_ctx, "%") < 0)
return -1;
if (val < 0 || val > 100)
return -1;
*out = (uint16_t)val;
return 0;
}
static int parse_header_similarity(
git_patch_parsed *patch, git_patch_parse_ctx *ctx)
{
if (parse_header_percent(&patch->base.delta->similarity, ctx) < 0)
return git_parse_err("invalid similarity percentage at line %"PRIuZ,
ctx->parse_ctx.line_num);
return 0;
}
static int parse_header_dissimilarity(
git_patch_parsed *patch, git_patch_parse_ctx *ctx)
{
uint16_t dissimilarity;
if (parse_header_percent(&dissimilarity, ctx) < 0)
return git_parse_err("invalid similarity percentage at line %"PRIuZ,
ctx->parse_ctx.line_num);
patch->base.delta->similarity = 100 - dissimilarity;
return 0;
}
static int parse_header_start(git_patch_parsed *patch, git_patch_parse_ctx *ctx)
{
if (parse_header_path(&patch->header_old_path, ctx) < 0)
return git_parse_err("corrupt old path in git diff header at line %"PRIuZ,
ctx->parse_ctx.line_num);
if (git_parse_advance_ws(&ctx->parse_ctx) < 0 ||
parse_header_path(&patch->header_new_path, ctx) < 0)
return git_parse_err("corrupt new path in git diff header at line %"PRIuZ,
ctx->parse_ctx.line_num);
/*
* We cannot expect to be able to always parse paths correctly at this
* point. Due to the possibility of unquoted names, whitespaces in
* filenames and custom prefixes we have to allow that, though, and just
* proceeed here. We then hope for the "---" and "+++" lines to fix that
* for us.
*/
if (!git_parse_ctx_contains(&ctx->parse_ctx, "\n", 1) &&
!git_parse_ctx_contains(&ctx->parse_ctx, "\r\n", 2)) {
git_parse_advance_chars(&ctx->parse_ctx, ctx->parse_ctx.line_len - 1);
git__free(patch->header_old_path);
patch->header_old_path = NULL;
git__free(patch->header_new_path);
patch->header_new_path = NULL;
}
return 0;
}
typedef enum {
STATE_START,
STATE_DIFF,
STATE_FILEMODE,
STATE_MODE,
STATE_INDEX,
STATE_PATH,
STATE_SIMILARITY,
STATE_RENAME,
STATE_COPY,
STATE_END,
} parse_header_state;
typedef struct {
const char *str;
parse_header_state expected_state;
parse_header_state next_state;
int(*fn)(git_patch_parsed *, git_patch_parse_ctx *);
} parse_header_transition;
static const parse_header_transition transitions[] = {
/* Start */
{ "diff --git " , STATE_START, STATE_DIFF, parse_header_start },
{ "deleted file mode " , STATE_DIFF, STATE_FILEMODE, parse_header_git_deletedfilemode },
{ "new file mode " , STATE_DIFF, STATE_FILEMODE, parse_header_git_newfilemode },
{ "old mode " , STATE_DIFF, STATE_MODE, parse_header_git_oldmode },
{ "new mode " , STATE_MODE, STATE_END, parse_header_git_newmode },
{ "index " , STATE_FILEMODE, STATE_INDEX, parse_header_git_index },
{ "index " , STATE_DIFF, STATE_INDEX, parse_header_git_index },
{ "index " , STATE_END, STATE_INDEX, parse_header_git_index },
{ "--- " , STATE_INDEX, STATE_PATH, parse_header_git_oldpath },
{ "+++ " , STATE_PATH, STATE_END, parse_header_git_newpath },
{ "GIT binary patch" , STATE_INDEX, STATE_END, NULL },
{ "Binary files " , STATE_INDEX, STATE_END, NULL },
{ "similarity index " , STATE_DIFF, STATE_SIMILARITY, parse_header_similarity },
{ "dissimilarity index ", STATE_DIFF, STATE_SIMILARITY, parse_header_dissimilarity },
{ "rename from " , STATE_SIMILARITY, STATE_RENAME, parse_header_renamefrom },
{ "rename old " , STATE_SIMILARITY, STATE_RENAME, parse_header_renamefrom },
{ "copy from " , STATE_SIMILARITY, STATE_COPY, parse_header_copyfrom },
{ "rename to " , STATE_RENAME, STATE_END, parse_header_renameto },
{ "rename new " , STATE_RENAME, STATE_END, parse_header_renameto },
{ "copy to " , STATE_COPY, STATE_END, parse_header_copyto },
/* Next patch */
{ "diff --git " , STATE_END, 0, NULL },
{ "@@ -" , STATE_END, 0, NULL },
{ "-- " , STATE_END, 0, NULL },
};
static int parse_header_git(
git_patch_parsed *patch,
git_patch_parse_ctx *ctx)
{
size_t i;
int error = 0;
parse_header_state state = STATE_START;
/* Parse remaining header lines */
for (; ctx->parse_ctx.remain_len > 0; git_parse_advance_line(&ctx->parse_ctx)) {
bool found = false;
if (ctx->parse_ctx.line_len == 0 || ctx->parse_ctx.line[ctx->parse_ctx.line_len - 1] != '\n')
break;
for (i = 0; i < ARRAY_SIZE(transitions); i++) {
const parse_header_transition *transition = &transitions[i];
size_t op_len = strlen(transition->str);
if (transition->expected_state != state ||
git__prefixcmp(ctx->parse_ctx.line, transition->str) != 0)
continue;
state = transition->next_state;
/* Do not advance if this is the patch separator */
if (transition->fn == NULL)
goto done;
git_parse_advance_chars(&ctx->parse_ctx, op_len);
if ((error = transition->fn(patch, ctx)) < 0)
goto done;
git_parse_advance_ws(&ctx->parse_ctx);
if (git_parse_advance_expected_str(&ctx->parse_ctx, "\n") < 0 ||
ctx->parse_ctx.line_len > 0) {
error = git_parse_err("trailing data at line %"PRIuZ, ctx->parse_ctx.line_num);
goto done;
}
found = true;
break;
}
if (!found) {
error = git_parse_err("invalid patch header at line %"PRIuZ,
ctx->parse_ctx.line_num);
goto done;
}
}
if (state != STATE_END) {
error = git_parse_err("unexpected header line %"PRIuZ, ctx->parse_ctx.line_num);
goto done;
}
done:
return error;
}
static int parse_int(int *out, git_patch_parse_ctx *ctx)
{
git_off_t num;
if (git_parse_advance_digit(&num, &ctx->parse_ctx, 10) < 0 || !git__is_int(num))
return -1;
*out = (int)num;
return 0;
}
static int parse_hunk_header(
git_patch_hunk *hunk,
git_patch_parse_ctx *ctx)
{
const char *header_start = ctx->parse_ctx.line;
char c;
hunk->hunk.old_lines = 1;
hunk->hunk.new_lines = 1;
if (git_parse_advance_expected_str(&ctx->parse_ctx, "@@ -") < 0 ||
parse_int(&hunk->hunk.old_start, ctx) < 0)
goto fail;
if (git_parse_peek(&c, &ctx->parse_ctx, 0) == 0 && c == ',') {
if (git_parse_advance_expected_str(&ctx->parse_ctx, ",") < 0 ||
parse_int(&hunk->hunk.old_lines, ctx) < 0)
goto fail;
}
if (git_parse_advance_expected_str(&ctx->parse_ctx, " +") < 0 ||
parse_int(&hunk->hunk.new_start, ctx) < 0)
goto fail;
if (git_parse_peek(&c, &ctx->parse_ctx, 0) == 0 && c == ',') {
if (git_parse_advance_expected_str(&ctx->parse_ctx, ",") < 0 ||
parse_int(&hunk->hunk.new_lines, ctx) < 0)
goto fail;
}
if (git_parse_advance_expected_str(&ctx->parse_ctx, " @@") < 0)
goto fail;
git_parse_advance_line(&ctx->parse_ctx);
if (!hunk->hunk.old_lines && !hunk->hunk.new_lines)
goto fail;
hunk->hunk.header_len = ctx->parse_ctx.line - header_start;
if (hunk->hunk.header_len > (GIT_DIFF_HUNK_HEADER_SIZE - 1))
return git_parse_err("oversized patch hunk header at line %"PRIuZ,
ctx->parse_ctx.line_num);
memcpy(hunk->hunk.header, header_start, hunk->hunk.header_len);
hunk->hunk.header[hunk->hunk.header_len] = '\0';
return 0;
fail:
git_error_set(GIT_ERROR_PATCH, "invalid patch hunk header at line %"PRIuZ,
ctx->parse_ctx.line_num);
return -1;
}
static int parse_hunk_body(
git_patch_parsed *patch,
git_patch_hunk *hunk,
git_patch_parse_ctx *ctx)
{
git_diff_line *line;
int error = 0;
int oldlines = hunk->hunk.old_lines;
int newlines = hunk->hunk.new_lines;
for (;
ctx->parse_ctx.remain_len > 1 &&
(oldlines || newlines) &&
!git_parse_ctx_contains_s(&ctx->parse_ctx, "@@ -");
git_parse_advance_line(&ctx->parse_ctx)) {
char c;
int origin;
int prefix = 1;
int old_lineno = hunk->hunk.old_start + (hunk->hunk.old_lines - oldlines);
int new_lineno = hunk->hunk.new_start + (hunk->hunk.new_lines - newlines);
if (ctx->parse_ctx.line_len == 0 || ctx->parse_ctx.line[ctx->parse_ctx.line_len - 1] != '\n') {
error = git_parse_err("invalid patch instruction at line %"PRIuZ,
ctx->parse_ctx.line_num);
goto done;
}
git_parse_peek(&c, &ctx->parse_ctx, 0);
switch (c) {
case '\n':
prefix = 0;
/* fall through */
case ' ':
origin = GIT_DIFF_LINE_CONTEXT;
oldlines--;
newlines--;
break;
case '-':
origin = GIT_DIFF_LINE_DELETION;
oldlines--;
new_lineno = -1;
break;
case '+':
origin = GIT_DIFF_LINE_ADDITION;
newlines--;
old_lineno = -1;
break;
default:
error = git_parse_err("invalid patch hunk at line %"PRIuZ, ctx->parse_ctx.line_num);
goto done;
}
line = git_array_alloc(patch->base.lines);
GIT_ERROR_CHECK_ALLOC(line);
memset(line, 0x0, sizeof(git_diff_line));
line->content = ctx->parse_ctx.line + prefix;
line->content_len = ctx->parse_ctx.line_len - prefix;
line->content_offset = ctx->parse_ctx.content_len - ctx->parse_ctx.remain_len;
line->origin = origin;
line->num_lines = 1;
line->old_lineno = old_lineno;
line->new_lineno = new_lineno;
hunk->line_count++;
}
if (oldlines || newlines) {
error = git_parse_err(
"invalid patch hunk, expected %d old lines and %d new lines",
hunk->hunk.old_lines, hunk->hunk.new_lines);
goto done;
}
/* Handle "\ No newline at end of file". Only expect the leading
* backslash, though, because the rest of the string could be
* localized. Because `diff` optimizes for the case where you
* want to apply the patch by hand.
*/
if (git_parse_ctx_contains_s(&ctx->parse_ctx, "\\ ") &&
git_array_size(patch->base.lines) > 0) {
line = git_array_get(patch->base.lines, git_array_size(patch->base.lines) - 1);
if (line->content_len < 1) {
error = git_parse_err("cannot trim trailing newline of empty line");
goto done;
}
line->content_len--;
git_parse_advance_line(&ctx->parse_ctx);
}
done:
return error;
}
static int parse_patch_header(
git_patch_parsed *patch,
git_patch_parse_ctx *ctx)
{
int error = 0;
for (; ctx->parse_ctx.remain_len > 0; git_parse_advance_line(&ctx->parse_ctx)) {
/* This line is too short to be a patch header. */
if (ctx->parse_ctx.line_len < 6)
continue;
/* This might be a hunk header without a patch header, provide a
* sensible error message. */
if (git_parse_ctx_contains_s(&ctx->parse_ctx, "@@ -")) {
size_t line_num = ctx->parse_ctx.line_num;
git_patch_hunk hunk;
/* If this cannot be parsed as a hunk header, it's just leading
* noise, continue.
*/
if (parse_hunk_header(&hunk, ctx) < 0) {
git_error_clear();
continue;
}
error = git_parse_err("invalid hunk header outside patch at line %"PRIuZ,
line_num);
goto done;
}
/* This buffer is too short to contain a patch. */
if (ctx->parse_ctx.remain_len < ctx->parse_ctx.line_len + 6)
break;
/* A proper git patch */
if (git_parse_ctx_contains_s(&ctx->parse_ctx, "diff --git ")) {
error = parse_header_git(patch, ctx);
goto done;
}
error = 0;
continue;
}
git_error_set(GIT_ERROR_PATCH, "no patch found");
error = GIT_ENOTFOUND;
done:
return error;
}
static int parse_patch_binary_side(
git_diff_binary_file *binary,
git_patch_parse_ctx *ctx)
{
git_diff_binary_t type = GIT_DIFF_BINARY_NONE;
git_buf base85 = GIT_BUF_INIT, decoded = GIT_BUF_INIT;
git_off_t len;
int error = 0;
if (git_parse_ctx_contains_s(&ctx->parse_ctx, "literal ")) {
type = GIT_DIFF_BINARY_LITERAL;
git_parse_advance_chars(&ctx->parse_ctx, 8);
} else if (git_parse_ctx_contains_s(&ctx->parse_ctx, "delta ")) {
type = GIT_DIFF_BINARY_DELTA;
git_parse_advance_chars(&ctx->parse_ctx, 6);
} else {
error = git_parse_err(
"unknown binary delta type at line %"PRIuZ, ctx->parse_ctx.line_num);
goto done;
}
if (git_parse_advance_digit(&len, &ctx->parse_ctx, 10) < 0 ||
git_parse_advance_nl(&ctx->parse_ctx) < 0 || len < 0) {
error = git_parse_err("invalid binary size at line %"PRIuZ, ctx->parse_ctx.line_num);
goto done;
}
while (ctx->parse_ctx.line_len) {
char c;
size_t encoded_len, decoded_len = 0, decoded_orig = decoded.size;
git_parse_peek(&c, &ctx->parse_ctx, 0);
if (c == '\n')
break;
else if (c >= 'A' && c <= 'Z')
decoded_len = c - 'A' + 1;
else if (c >= 'a' && c <= 'z')
decoded_len = c - 'a' + (('z' - 'a') + 1) + 1;
if (!decoded_len) {
error = git_parse_err("invalid binary length at line %"PRIuZ, ctx->parse_ctx.line_num);
goto done;
}
git_parse_advance_chars(&ctx->parse_ctx, 1);
encoded_len = ((decoded_len / 4) + !!(decoded_len % 4)) * 5;
if (encoded_len > ctx->parse_ctx.line_len - 1) {
error = git_parse_err("truncated binary data at line %"PRIuZ, ctx->parse_ctx.line_num);
goto done;
}
if ((error = git_buf_decode_base85(
&decoded, ctx->parse_ctx.line, encoded_len, decoded_len)) < 0)
goto done;
if (decoded.size - decoded_orig != decoded_len) {
error = git_parse_err("truncated binary data at line %"PRIuZ, ctx->parse_ctx.line_num);
goto done;
}
git_parse_advance_chars(&ctx->parse_ctx, encoded_len);
if (git_parse_advance_nl(&ctx->parse_ctx) < 0) {
error = git_parse_err("trailing data at line %"PRIuZ, ctx->parse_ctx.line_num);
goto done;
}
}
binary->type = type;
binary->inflatedlen = (size_t)len;
binary->datalen = decoded.size;
binary->data = git_buf_detach(&decoded);
done:
git_buf_dispose(&base85);
git_buf_dispose(&decoded);
return error;
}
static int parse_patch_binary(
git_patch_parsed *patch,
git_patch_parse_ctx *ctx)
{
int error;
if (git_parse_advance_expected_str(&ctx->parse_ctx, "GIT binary patch") < 0 ||
git_parse_advance_nl(&ctx->parse_ctx) < 0)
return git_parse_err("corrupt git binary header at line %"PRIuZ, ctx->parse_ctx.line_num);
/* parse old->new binary diff */
if ((error = parse_patch_binary_side(
&patch->base.binary.new_file, ctx)) < 0)
return error;
if (git_parse_advance_nl(&ctx->parse_ctx) < 0)
return git_parse_err("corrupt git binary separator at line %"PRIuZ,
ctx->parse_ctx.line_num);
/* parse new->old binary diff */
if ((error = parse_patch_binary_side(
&patch->base.binary.old_file, ctx)) < 0)
return error;
if (git_parse_advance_nl(&ctx->parse_ctx) < 0)
return git_parse_err("corrupt git binary patch separator at line %"PRIuZ,
ctx->parse_ctx.line_num);
patch->base.binary.contains_data = 1;
patch->base.delta->flags |= GIT_DIFF_FLAG_BINARY;
return 0;
}
static int parse_patch_binary_nodata(
git_patch_parsed *patch,
git_patch_parse_ctx *ctx)
{
if (git_parse_advance_expected_str(&ctx->parse_ctx, "Binary files ") < 0 ||
git_parse_advance_expected_str(&ctx->parse_ctx, patch->header_old_path) < 0 ||
git_parse_advance_expected_str(&ctx->parse_ctx, " and ") < 0 ||
git_parse_advance_expected_str(&ctx->parse_ctx, patch->header_new_path) < 0 ||
git_parse_advance_expected_str(&ctx->parse_ctx, " differ") < 0 ||
git_parse_advance_nl(&ctx->parse_ctx) < 0)
return git_parse_err("corrupt git binary header at line %"PRIuZ, ctx->parse_ctx.line_num);
patch->base.binary.contains_data = 0;
patch->base.delta->flags |= GIT_DIFF_FLAG_BINARY;
return 0;
}
static int parse_patch_hunks(
git_patch_parsed *patch,
git_patch_parse_ctx *ctx)
{
git_patch_hunk *hunk;
int error = 0;
while (git_parse_ctx_contains_s(&ctx->parse_ctx, "@@ -")) {
hunk = git_array_alloc(patch->base.hunks);
GIT_ERROR_CHECK_ALLOC(hunk);
memset(hunk, 0, sizeof(git_patch_hunk));
hunk->line_start = git_array_size(patch->base.lines);
hunk->line_count = 0;
if ((error = parse_hunk_header(hunk, ctx)) < 0 ||
(error = parse_hunk_body(patch, hunk, ctx)) < 0)
goto done;
}
patch->base.delta->flags |= GIT_DIFF_FLAG_NOT_BINARY;
done:
return error;
}
static int parse_patch_body(
git_patch_parsed *patch, git_patch_parse_ctx *ctx)
{
if (git_parse_ctx_contains_s(&ctx->parse_ctx, "GIT binary patch"))
return parse_patch_binary(patch, ctx);
else if (git_parse_ctx_contains_s(&ctx->parse_ctx, "Binary files "))
return parse_patch_binary_nodata(patch, ctx);
else
return parse_patch_hunks(patch, ctx);
}
int check_header_names(
const char *one,
const char *two,
const char *old_or_new,
bool two_null)
{
if (!one || !two)
return 0;
if (two_null && strcmp(two, "/dev/null") != 0)
return git_parse_err("expected %s path of '/dev/null'", old_or_new);
else if (!two_null && strcmp(one, two) != 0)
return git_parse_err("mismatched %s path names", old_or_new);
return 0;
}
static int check_prefix(
char **out,
size_t *out_len,
git_patch_parsed *patch,
const char *path_start)
{
const char *path = path_start;
size_t prefix_len = patch->ctx->opts.prefix_len;
size_t remain_len = prefix_len;
*out = NULL;
*out_len = 0;
if (prefix_len == 0)
goto done;
/* leading slashes do not count as part of the prefix in git apply */
while (*path == '/')
path++;
while (*path && remain_len) {
if (*path == '/')
remain_len--;
path++;
}
if (remain_len || !*path)
return git_parse_err(
"header filename does not contain %"PRIuZ" path components",
prefix_len);
done:
*out_len = (path - path_start);
*out = git__strndup(path_start, *out_len);
return (*out == NULL) ? -1 : 0;
}
static int check_filenames(git_patch_parsed *patch)
{
const char *prefixed_new, *prefixed_old;
size_t old_prefixlen = 0, new_prefixlen = 0;
bool added = (patch->base.delta->status == GIT_DELTA_ADDED);
bool deleted = (patch->base.delta->status == GIT_DELTA_DELETED);
if (patch->old_path && !patch->new_path)
return git_parse_err("missing new path");
if (!patch->old_path && patch->new_path)
return git_parse_err("missing old path");
/* Ensure (non-renamed) paths match */
if (check_header_names(patch->header_old_path, patch->old_path, "old", added) < 0 ||
check_header_names(patch->header_new_path, patch->new_path, "new", deleted) < 0)
return -1;
prefixed_old = (!added && patch->old_path) ? patch->old_path : patch->header_old_path;
prefixed_new = (!deleted && patch->new_path) ? patch->new_path : patch->header_new_path;
if ((prefixed_old && check_prefix(&patch->old_prefix, &old_prefixlen, patch, prefixed_old) < 0) ||
(prefixed_new && check_prefix(&patch->new_prefix, &new_prefixlen, patch, prefixed_new) < 0))
return -1;
/* Prefer the rename filenames as they are unambiguous and unprefixed */
if (patch->rename_old_path)
patch->base.delta->old_file.path = patch->rename_old_path;
else
patch->base.delta->old_file.path = prefixed_old + old_prefixlen;
if (patch->rename_new_path)
patch->base.delta->new_file.path = patch->rename_new_path;
else
patch->base.delta->new_file.path = prefixed_new + new_prefixlen;
if (!patch->base.delta->old_file.path &&
!patch->base.delta->new_file.path)
return git_parse_err("git diff header lacks old / new paths");
return 0;
}
static int check_patch(git_patch_parsed *patch)
{
git_diff_delta *delta = patch->base.delta;
if (check_filenames(patch) < 0)
return -1;
if (delta->old_file.path &&
delta->status != GIT_DELTA_DELETED &&
!delta->new_file.mode)
delta->new_file.mode = delta->old_file.mode;
if (delta->status == GIT_DELTA_MODIFIED &&
!(delta->flags & GIT_DIFF_FLAG_BINARY) &&
delta->new_file.mode == delta->old_file.mode &&
git_array_size(patch->base.hunks) == 0)
return git_parse_err("patch with no hunks");
if (delta->status == GIT_DELTA_ADDED) {
memset(&delta->old_file.id, 0x0, sizeof(git_oid));
delta->old_file.id_abbrev = 0;
}
if (delta->status == GIT_DELTA_DELETED) {
memset(&delta->new_file.id, 0x0, sizeof(git_oid));
delta->new_file.id_abbrev = 0;
}
return 0;
}
git_patch_parse_ctx *git_patch_parse_ctx_init(
const char *content,
size_t content_len,
const git_patch_options *opts)
{
git_patch_parse_ctx *ctx;
git_patch_options default_opts = GIT_PATCH_OPTIONS_INIT;
if ((ctx = git__calloc(1, sizeof(git_patch_parse_ctx))) == NULL)
return NULL;
if ((git_parse_ctx_init(&ctx->parse_ctx, content, content_len)) < 0) {
git__free(ctx);
return NULL;
}
if (opts)
memcpy(&ctx->opts, opts, sizeof(git_patch_options));
else
memcpy(&ctx->opts, &default_opts, sizeof(git_patch_options));
GIT_REFCOUNT_INC(ctx);
return ctx;
}
static void patch_parse_ctx_free(git_patch_parse_ctx *ctx)
{
if (!ctx)
return;
git_parse_ctx_clear(&ctx->parse_ctx);
git__free(ctx);
}
void git_patch_parse_ctx_free(git_patch_parse_ctx *ctx)
{
GIT_REFCOUNT_DEC(ctx, patch_parse_ctx_free);
}
int git_patch_parsed_from_diff(git_patch **out, git_diff *d, size_t idx)
{
git_diff_parsed *diff = (git_diff_parsed *)d;
git_patch *p;
if ((p = git_vector_get(&diff->patches, idx)) == NULL)
return -1;
GIT_REFCOUNT_INC(p);
*out = p;
return 0;
}
static void patch_parsed__free(git_patch *p)
{
git_patch_parsed *patch = (git_patch_parsed *)p;
if (!patch)
return;
git_patch_parse_ctx_free(patch->ctx);
git__free((char *)patch->base.binary.old_file.data);
git__free((char *)patch->base.binary.new_file.data);
git_array_clear(patch->base.hunks);
git_array_clear(patch->base.lines);
git__free(patch->base.delta);
git__free(patch->old_prefix);
git__free(patch->new_prefix);
git__free(patch->header_old_path);
git__free(patch->header_new_path);
git__free(patch->rename_old_path);
git__free(patch->rename_new_path);
git__free(patch->old_path);
git__free(patch->new_path);
git__free(patch);
}
int git_patch_parse(
git_patch **out,
git_patch_parse_ctx *ctx)
{
git_patch_parsed *patch;
size_t start, used;
int error = 0;
assert(out && ctx);
*out = NULL;
patch = git__calloc(1, sizeof(git_patch_parsed));
GIT_ERROR_CHECK_ALLOC(patch);
patch->ctx = ctx;
GIT_REFCOUNT_INC(patch->ctx);
patch->base.free_fn = patch_parsed__free;
patch->base.delta = git__calloc(1, sizeof(git_diff_delta));
GIT_ERROR_CHECK_ALLOC(patch->base.delta);
patch->base.delta->status = GIT_DELTA_MODIFIED;
patch->base.delta->nfiles = 2;
start = ctx->parse_ctx.remain_len;
if ((error = parse_patch_header(patch, ctx)) < 0 ||
(error = parse_patch_body(patch, ctx)) < 0 ||
(error = check_patch(patch)) < 0)
goto done;
used = start - ctx->parse_ctx.remain_len;
ctx->parse_ctx.remain += used;
patch->base.diff_opts.old_prefix = patch->old_prefix;
patch->base.diff_opts.new_prefix = patch->new_prefix;
patch->base.diff_opts.flags |= GIT_DIFF_SHOW_BINARY;
GIT_REFCOUNT_INC(&patch->base);
*out = &patch->base;
done:
if (error < 0)
patch_parsed__free(&patch->base);
return error;
}
int git_patch_from_buffer(
git_patch **out,
const char *content,
size_t content_len,
const git_patch_options *opts)
{
git_patch_parse_ctx *ctx;
int error;
ctx = git_patch_parse_ctx_init(content, content_len, opts);
GIT_ERROR_CHECK_ALLOC(ctx);
error = git_patch_parse(out, ctx);
git_patch_parse_ctx_free(ctx);
return error;
}
|
f7b093417107cfddfacbad7debe929282da712c9
|
0317ceaef72e61fb06061ab27d887c04c071e147
|
/firmware/apps/words.h
|
2cd7785ce5218df8543ef5c7e335e084f21347df
|
[
"LicenseRef-scancode-warranty-disclaimer"
] |
no_license
|
travisgoodspeed/goodwatch
|
16df7f55768d775a12898719360663315a215162
|
60673a72eaed8878cf79b56a9efcb623a1e7d2f4
|
refs/heads/master
| 2023-07-05T19:08:51.138235
| 2022-11-22T00:55:09
| 2022-11-22T00:55:09
| 87,991,182
| 468
| 60
| null | 2022-11-22T00:55:10
| 2017-04-12T00:21:21
|
C
|
UTF-8
|
C
| false
| false
| 10,296
|
h
|
words.h
|
/*! \file words.h
\brief Table of words. From EFF short list: https://www.eff.org/deeplinks/2016/07/new-wordlists-random-passphrases
*/
#define NUMWORDS 950
// a rather limited dictionary, use at least 6 words
const char * const word_array[] = {
"aardvark",
"abdomen",
"abiding",
"abnormal",
"abrasion",
"abundant",
"abyss",
"academy",
"acetone",
"achiness",
"acid",
"acquire",
"acrobat",
"actress",
"aerosol",
"afloat",
"afraid",
"again",
"agency",
"aghast",
"agitate",
"agnostic",
"agreeing",
"aidless",
"ajar",
"alchemy",
"alfalfa",
"algae",
"aliens",
"alkaline",
"almanac",
"alphabet",
"already",
"also",
"altitude",
"aluminum",
"always",
"amiable",
"amnesty",
"amoeba",
"amuser",
"anagram",
"anchor",
"android",
"animal",
"anklet",
"answer",
"antelope",
"anxiety",
"anyplace",
"aorta",
"apnea",
"apple",
"apricot",
"arachnid",
"ardently",
"arena",
"argument",
"armchair",
"aromatic",
"arsonist",
"asbestos",
"ascend",
"aseptic",
"ashamed",
"asinine",
"asleep",
"asocial",
"atlas",
"atom",
"attic",
"atypical",
"avenue",
"aviator",
"avocado",
"awhile",
"awkward",
"awning",
"awoke",
"axially",
"azalea",
"babbling",
"backpack",
"badass",
"bagpipe",
"bakery",
"bamboo",
"banana",
"basket",
"bathrobe",
"bazooka",
"blade",
"blender",
"blimp",
"blouse",
"blurred",
"boatyard",
"bobcat",
"body",
"bohemian",
"boiler",
"bonnet",
"boots",
"borough",
"bottle",
"bouquet",
"boxlike",
"breath",
"broom",
"brushes",
"buckle",
"buddhist",
"buffalo",
"bullfrog",
"bunny",
"busboy",
"buzzard",
"cabin",
"cactus",
"cadillac",
"cage",
"cahoots",
"cajoling",
"cakewalk",
"camera",
"canister",
"capsule",
"carrot",
"cashew",
"caviar",
"cedar",
"celery",
"cement",
"census",
"ceramics",
"cesspool",
"chimney",
"chlorine",
"chrome",
"chute",
"cilantro",
"cinnamon",
"circle",
"civilian",
"clay",
"clock",
"cobweb",
"coconut",
"codeword",
"computer",
"confetti",
"copier",
"cornea",
"cotton",
"couch",
"coyote",
"coziness",
"crawfish",
"crib",
"crumble",
"crystal",
"cubical",
"cucumber",
"cuddly",
"cufflink",
"cuisine",
"culprit",
"cup",
"curry",
"cushion",
"cuticle",
"cyclist",
"cylinder",
"cymbal",
"cynicism",
"cypress",
"daffodil",
"dagger",
"dairy",
"datebook",
"daughter",
"dawn",
"daytime",
"dazzler",
"dealer",
"debris",
"decal",
"dedicate",
"deepness",
"defrost",
"degree",
"democrat",
"dentist",
"depot",
"deranged",
"desktop",
"device",
"diamond",
"dibs",
"diffuser",
"digit",
"dilated",
"dimple",
"dioxide",
"diploma",
"ditto",
"dividers",
"doctor",
"dodge",
"doll",
"dominoes",
"donut",
"doorstep",
"dorsal",
"double",
"dozed",
"dresser",
"drum",
"dryer",
"duckling",
"duffel",
"dugout",
"dumpster",
"duplex",
"durable",
"dustpan",
"dutiful",
"duvet",
"dwarfism",
"dwelling",
"dynamite",
"dyslexia",
"earlobe",
"easel",
"ebook",
"echoless",
"eclipse",
"ecstasy",
"edged",
"editor",
"educator",
"eelworm",
"eerie",
"effects",
"eggnog",
"ejection",
"elastic",
"elbow",
"elderly",
"elephant",
"elfishly",
"elk",
"elusive",
"elves",
"emcee",
"emerald",
"emission",
"emoticon",
"emperor",
"emulate",
"energy",
"enforcer",
"engine",
"enhance",
"enlarged",
"enormous",
"enquirer",
"ensemble",
"entryway",
"envoy",
"enzyme",
"epidemic",
"erasable",
"erratic",
"eruption",
"eskimo",
"espresso",
"essay",
"estrogen",
"etching",
"eternal",
"ethics",
"eulogy",
"evidence",
"exam",
"excerpt",
"exhale",
"exist",
"exorcist",
"explode",
"exterior",
"fabric",
"factory",
"faded",
"failsafe",
"falcon",
"family",
"fanfare",
"fasten",
"faucet",
"favorite",
"feasibly",
"february",
"federal",
"feedback",
"feigned",
"feline",
"femur",
"fence",
"ferret",
"festival",
"feverish",
"fiddle",
"figurine",
"fillet",
"finalist",
"fiscally",
"fixture",
"flight",
"florist",
"flypaper",
"foamless",
"focus",
"foggy",
"folksong",
"fondue",
"footpath",
"fossil",
"fountain",
"fox",
"fragment",
"freeway",
"fridge",
"frosting",
"fruit",
"gadget",
"gangway",
"garlic",
"gaslight",
"gauntlet",
"gearbox",
"gecko",
"gem",
"gerbil",
"gesture",
"getaway",
"geyser",
"giftshop",
"gigabyte",
"gimmick",
"giraffe",
"giveaway",
"gizmo",
"glasses",
"gleeful",
"glisten",
"glove",
"glucose",
"glycerin",
"gnarly",
"gnomish",
"goatskin",
"goggles",
"goldfish",
"gong",
"gooey",
"gorgeous",
"gosling",
"gothic",
"gourmet",
"governor",
"grape",
"grill",
"guitar",
"gullible",
"gumdrop",
"gurgling",
"gusto",
"gutless",
"gymnast",
"gyration",
"habitat",
"hacking",
"haggard",
"haiku",
"halogen",
"handgun",
"hardhat",
"hastily",
"haughty",
"hazelnut",
"headband",
"hedgehog",
"hefty",
"helmet",
"herbs",
"hexagon",
"hubcap",
"huddling",
"huff",
"hugeness",
"human",
"hunter",
"hushing",
"hyacinth",
"hybrid",
"hydrant",
"icepack",
"icing",
"iconic",
"idiocy",
"idly",
"igloo",
"ignition",
"iguana",
"imaging",
"imbecile",
"imitator",
"imprint",
"iodine",
"ipad",
"iphone",
"irksome",
"iron",
"island",
"isotope",
"itemizer",
"itunes",
"ivory",
"jaguar",
"jalapeno",
"jamboree",
"janitor",
"jarring",
"jasmine",
"jaundice",
"jazz",
"jealous",
"jeep",
"jelly",
"jersey",
"jetski",
"jezebel",
"jiffy",
"jigsaw",
"jingling",
"jogging",
"john",
"joinable",
"jokingly",
"journal",
"jovial",
"joystick",
"jubilant",
"juggle",
"juice",
"jujitsu",
"jukebox",
"junkyard",
"juror",
"juvenile",
"kabob",
"kamikaze",
"kangaroo",
"karate",
"kayak",
"keepsake",
"kennel",
"kerosene",
"ketchup",
"khaki",
"kilogram",
"kimono",
"kingdom",
"kiosk",
"kissing",
"kite",
"kleenex",
"knapsack",
"kneecap",
"knickers",
"koala",
"krypton",
"ladder",
"lantern",
"laptop",
"lasagna",
"latch",
"laundry",
"lavender",
"laxative",
"lecturer",
"leftover",
"leggings",
"leisure",
"lemon",
"length",
"leopard",
"lettuce",
"leukemia",
"levers",
"lewdness",
"library",
"licorice",
"lifeboat",
"likewise",
"lilac",
"lint",
"lioness",
"lipstick",
"liquid",
"listless",
"litter",
"lizard",
"llama",
"luau",
"lucidity",
"luggage",
"lukewarm",
"lullaby",
"lunchbox",
"luscious",
"lyrics",
"macaroni",
"maestro",
"magazine",
"mahogany",
"maimed",
"majority",
"makeover",
"mammal",
"mango",
"mapmaker",
"marbles",
"massager",
"maverick",
"maximum",
"moaning",
"mobilize",
"moccasin",
"modify",
"moisture",
"molecule",
"momentum",
"mortuary",
"mosquito",
"movie",
"mower",
"mudflow",
"mugshot",
"mule",
"mummy",
"mundane",
"muppet",
"mural",
"mustard",
"mutation",
"myriad",
"myspace",
"myth",
"nail",
"namesake",
"napkin",
"narrator",
"natives",
"navigate",
"nearest",
"nebula",
"nectar",
"neither",
"nemesis",
"nephew",
"nest",
"netting",
"neuron",
"nextdoor",
"nicotine",
"niece",
"nintendo",
"nirvana",
"nuclear",
"nugget",
"nuisance",
"nullify",
"numbing",
"nuptials",
"nursery",
"nylon",
"oasis",
"oat",
"obituary",
"object",
"observer",
"obtain",
"obvious",
"oceanic",
"octopus",
"ocular",
"office",
"oiliness",
"ointment",
"older",
"olympics",
"oncoming",
"onion",
"onlooker",
"onstage",
"onward",
"onyx",
"oomph",
"opaquely",
"opera",
"opium",
"opossum",
"opponent",
"optical",
"osmosis",
"ostrich",
"ought",
"outhouse",
"ovation",
"oven",
"owlish",
"oxford",
"oxidize",
"oxygen",
"oyster",
"ozone",
"padlock",
"pageant",
"pajamas",
"palm",
"pamphlet",
"paprika",
"parakeet",
"passport",
"patio",
"pauper",
"pavement",
"payphone",
"pebble",
"pegboard",
"pelican",
"penguin",
"peony",
"peroxide",
"pewter",
"pharmacy",
"pheasant",
"phrasing",
"plank",
"pledge",
"plotted",
"plug",
"plywood",
"poetic",
"pogo",
"poison",
"poking",
"poncho",
"popcorn",
"postcard",
"poultry",
"prairie",
"pretzel",
"princess",
"prune",
"pry",
"pseudo",
"pucker",
"pueblo",
"pulley",
"pumpkin",
"puppy",
"purse",
"pushup",
"putt",
"puzzle",
"pyramid",
"python",
"quarters",
"quilt",
"quote",
"racoon",
"radish",
"ragweed",
"railroad",
"rarity",
"rebuilt",
"receipt",
"reentry",
"refinery",
"register",
"rekindle",
"relic",
"remote",
"reopen",
"reporter",
"request",
"rerun",
"reunion",
"revolver",
"rewrite",
"rhapsody",
"rhetoric",
"rhino",
"rhubarb",
"rhyme",
"ribbon",
"riches",
"ridden",
"rimmed",
"riptide",
"riskily",
"ritzy",
"roamer",
"robe",
"rocket",
"romancer",
"ropelike",
"royal",
"rubber",
"rugby",
"ruined",
"rulebook",
"rummage",
"running",
"rupture",
"sabotage",
"saffron",
"samurai",
"sandworm",
"sapphire",
"sardine",
"sassy",
"satchel",
"sauna",
"savage",
"scarf",
"scenario",
"scooter",
"scythe",
"sedative",
"selected",
"senator",
"septum",
"sequence",
"serpent",
"sesame",
"settler",
"severely",
"shack",
"shelf",
"shirt",
"shovel",
"shrimp",
"shuttle",
"shyness",
"siamese",
"sibling",
"siesta",
"silicon",
"singles",
"sitcom",
"sixfold",
"sizable",
"skeleton",
"skies",
"skulk",
"skylight",
"slapping",
"sled",
"sloth",
"smitten",
"smudge",
"snapshot",
"sneezing",
"sniff",
"snowsuit",
"snugness",
"speakers",
"sphinx",
"spider",
"sponge",
"sprout",
"spur",
"spyglass",
"squirrel",
"statue",
"stingray",
"student",
"stylus",
"suave",
"subway",
"suction",
"suds",
"sugar",
"suitcase",
"sulphur",
"surfer",
"sushi",
"swan",
"swimwear",
"sword",
"sycamore",
"syllable",
"symphony",
"syringes",
"taco",
"tadpole",
"tagalong",
"takeout",
"tallness",
"tamale",
"tanned",
"tapestry",
"tastebud",
"tattoo",
"tavern",
"thaw",
"theater",
"thimble",
"thorn",
"throat",
"thumb",
"tiara",
"tidbit",
"tiger",
"timid",
"tinsel",
"tirade",
"tissue",
"tractor",
"tree",
"tripod",
"trousers",
"trucks",
"tryout",
"tubeless",
"tuesday",
"tugboat",
"tulip",
"turtle",
"tusk",
"tutorial",
"tuxedo",
"tweezers",
"twins",
"umbrella",
"umpire",
"uncle",
"ungloved",
"unhinge",
"unicycle",
"unjustly",
"unknown",
"unmarked",
"unopened",
"unpaved",
"unroll",
"untied",
"unusual",
"unveiled",
"unzip",
"upbeat",
"update",
"upfront",
"upgrade",
"upkeep",
"upload",
"uppercut",
"upright",
"upstairs",
"uptown",
"upwind",
"uranium",
"urban",
"urchin",
"urethane",
"urgent",
"username",
"usher",
"utensil",
"utility",
"utmost",
"utopia",
"vacuum",
"vagrancy",
"varied",
"vaseline",
"vehicle",
"velcro",
"vendor",
"veteran",
"vexingly",
"vicinity",
"village",
"vinegar",
"violin",
"virus",
"visor",
"vitamins",
"vixen",
"vocalist",
"vogue",
"voucher",
"voyage",
"waffle",
"wagon",
"wakeup",
"walrus",
"wanderer",
"wasp",
"water",
"waving",
"wheat",
"whisper",
"wick",
"widow",
"wielder",
"wifeless",
"wildcat",
"windmill",
"wipeout",
"wired",
"wishbone",
"wizardry",
"womb",
"wound",
"wrangle",
"wreckage",
"xerox",
"yacht",
"yahoo",
"yard",
"yearbook",
"yiddish",
"yield",
"yo-yo",
"yodel",
"yogurt",
"yuppie",
"zealot",
"zebra",
"zeppelin",
"zillion",
"zipping",
"zodiac",
"zombie",
"zucchini"
};
|
fe547cd10ca078e7e967cdaaaff20295d28a8f40
|
69db0de8c61c7cba691193edd3f087fdb54351c2
|
/src/data/pokemon/trainer_class_lookups.h
|
e7611d7582dd9d6f1bf1ea64821300d24bcd9af8
|
[] |
no_license
|
pret/pokefirered
|
5363c332321c7650d4c85be6aa2e8baf3acda162
|
f8741615bfa0123e38680f30103f217c269ec96a
|
refs/heads/master
| 2023-08-31T15:22:19.498797
| 2023-08-31T15:15:29
| 2023-08-31T15:15:29
| 115,841,713
| 847
| 709
| null | 2023-09-12T22:48:38
| 2017-12-31T04:07:51
|
C
|
UTF-8
|
C
| false
| false
| 21,759
|
h
|
trainer_class_lookups.h
|
const u8 gFacilityClassToPicIndex[] =
{
[FACILITY_CLASS_AQUA_LEADER_ARCHIE] = TRAINER_PIC_AQUA_LEADER_ARCHIE,
[FACILITY_CLASS_AQUA_GRUNT_M] = TRAINER_PIC_AQUA_GRUNT_M,
[FACILITY_CLASS_AQUA_GRUNT_F] = TRAINER_PIC_AQUA_GRUNT_F,
[FACILITY_CLASS_RS_AROMA_LADY] = TRAINER_PIC_RS_AROMA_LADY,
[FACILITY_CLASS_RS_RUIN_MANIAC] = TRAINER_PIC_RS_RUIN_MANIAC,
[FACILITY_CLASS_INTERVIEWER] = TRAINER_PIC_INTERVIEWER,
[FACILITY_CLASS_RS_TUBER_F] = TRAINER_PIC_RS_TUBER_F,
[FACILITY_CLASS_RS_TUBER_M] = TRAINER_PIC_RS_TUBER_M,
[FACILITY_CLASS_RS_COOLTRAINER_M] = TRAINER_PIC_RS_COOLTRAINER_M,
[FACILITY_CLASS_RS_COOLTRAINER_F] = TRAINER_PIC_RS_COOLTRAINER_F,
[FACILITY_CLASS_HEX_MANIAC] = TRAINER_PIC_HEX_MANIAC,
[FACILITY_CLASS_RS_LADY] = TRAINER_PIC_RS_LADY,
[FACILITY_CLASS_RS_BEAUTY] = TRAINER_PIC_RS_BEAUTY,
[FACILITY_CLASS_RICH_BOY] = TRAINER_PIC_RICH_BOY,
[FACILITY_CLASS_RS_POKEMANIAC] = TRAINER_PIC_RS_POKEMANIAC,
[FACILITY_CLASS_RS_SWIMMER_M] = TRAINER_PIC_RS_SWIMMER_M,
[FACILITY_CLASS_RS_BLACK_BELT] = TRAINER_PIC_RS_BLACK_BELT,
[FACILITY_CLASS_GUITARIST] = TRAINER_PIC_GUITARIST,
[FACILITY_CLASS_KINDLER] = TRAINER_PIC_KINDLER,
[FACILITY_CLASS_RS_CAMPER] = TRAINER_PIC_RS_CAMPER,
[FACILITY_CLASS_BUG_MANIAC] = TRAINER_PIC_BUG_MANIAC,
[FACILITY_CLASS_RS_PSYCHIC_M] = TRAINER_PIC_RS_PSYCHIC_M,
[FACILITY_CLASS_RS_PSYCHIC_F] = TRAINER_PIC_RS_PSYCHIC_F,
[FACILITY_CLASS_RS_GENTLEMAN] = TRAINER_PIC_RS_GENTLEMAN,
[FACILITY_CLASS_ELITE_FOUR_SIDNEY] = TRAINER_PIC_ELITE_FOUR_SIDNEY,
[FACILITY_CLASS_ELITE_FOUR_PHOEBE] = TRAINER_PIC_ELITE_FOUR_PHOEBE,
[FACILITY_CLASS_LEADER_ROXANNE] = TRAINER_PIC_LEADER_ROXANNE,
[FACILITY_CLASS_LEADER_BRAWLY] = TRAINER_PIC_LEADER_BRAWLY,
[FACILITY_CLASS_LEADER_TATE_AND_LIZA] = TRAINER_PIC_LEADER_TATE_AND_LIZA,
[FACILITY_CLASS_SCHOOL_KID_M] = TRAINER_PIC_SCHOOL_KID_M,
[FACILITY_CLASS_SCHOOL_KID_F] = TRAINER_PIC_SCHOOL_KID_F,
[FACILITY_CLASS_SR_AND_JR] = TRAINER_PIC_SR_AND_JR,
[FACILITY_CLASS_POKEFAN_M] = TRAINER_PIC_POKEFAN_M,
[FACILITY_CLASS_POKEFAN_F] = TRAINER_PIC_POKEFAN_F,
[FACILITY_CLASS_EXPERT_M] = TRAINER_PIC_EXPERT_M,
[FACILITY_CLASS_EXPERT_F] = TRAINER_PIC_EXPERT_F,
[FACILITY_CLASS_RS_YOUNGSTER] = TRAINER_PIC_RS_YOUNGSTER,
[FACILITY_CLASS_CHAMPION_STEVEN] = TRAINER_PIC_CHAMPION_STEVEN,
[FACILITY_CLASS_RS_FISHERMAN] = TRAINER_PIC_RS_FISHERMAN,
[FACILITY_CLASS_CYCLING_TRIATHLETE_M] = TRAINER_PIC_CYCLING_TRIATHLETE_M,
[FACILITY_CLASS_CYCLING_TRIATHLETE_F] = TRAINER_PIC_CYCLING_TRIATHLETE_F,
[FACILITY_CLASS_RUNNING_TRIATHLETE_M] = TRAINER_PIC_RUNNING_TRIATHLETE_M,
[FACILITY_CLASS_RUNNING_TRIATHLETE_F] = TRAINER_PIC_RUNNING_TRIATHLETE_F,
[FACILITY_CLASS_SWIMMING_TRIATHLETE_M] = TRAINER_PIC_SWIMMING_TRIATHLETE_M,
[FACILITY_CLASS_SWIMMING_TRIATHLETE_F] = TRAINER_PIC_SWIMMING_TRIATHLETE_F,
[FACILITY_CLASS_DRAGON_TAMER] = TRAINER_PIC_DRAGON_TAMER,
[FACILITY_CLASS_RS_BIRD_KEEPER] = TRAINER_PIC_RS_BIRD_KEEPER,
[FACILITY_CLASS_NINJA_BOY] = TRAINER_PIC_NINJA_BOY,
[FACILITY_CLASS_BATTLE_GIRL] = TRAINER_PIC_BATTLE_GIRL,
[FACILITY_CLASS_PARASOL_LADY] = TRAINER_PIC_PARASOL_LADY,
[FACILITY_CLASS_RS_SWIMMER_F] = TRAINER_PIC_RS_SWIMMER_F,
[FACILITY_CLASS_RS_PICNICKER] = TRAINER_PIC_RS_PICNICKER,
[FACILITY_CLASS_RS_TWINS] = TRAINER_PIC_RS_TWINS,
[FACILITY_CLASS_RS_SAILOR] = TRAINER_PIC_RS_SAILOR,
[FACILITY_CLASS_BOARDER_M] = TRAINER_PIC_RS_YOUNGSTER,
[FACILITY_CLASS_BOARDER_F] = TRAINER_PIC_RS_YOUNGSTER,
[FACILITY_CLASS_COLLECTOR] = TRAINER_PIC_COLLECTOR,
[FACILITY_CLASS_PKMN_TRAINER_WALLY] = TRAINER_PIC_WALLY,
[FACILITY_CLASS_PKMN_TRAINER_BRENDAN] = TRAINER_PIC_RS_BRENDAN_1,
[FACILITY_CLASS_PKMN_TRAINER_BRENDAN_2] = TRAINER_PIC_RS_BRENDAN_1,
[FACILITY_CLASS_PKMN_TRAINER_BRENDAN_3] = TRAINER_PIC_RS_BRENDAN_1,
[FACILITY_CLASS_PKMN_TRAINER_MAY] = TRAINER_PIC_RS_MAY_1,
[FACILITY_CLASS_PKMN_TRAINER_MAY_2] = TRAINER_PIC_RS_MAY_1,
[FACILITY_CLASS_PKMN_TRAINER_MAY_3] = TRAINER_PIC_RS_MAY_1,
[FACILITY_CLASS_RS_PKMN_BREEDER_M] = TRAINER_PIC_RS_POKEMON_BREEDER_M,
[FACILITY_CLASS_RS_PKMN_BREEDER_F] = TRAINER_PIC_RS_POKEMON_BREEDER_F,
[FACILITY_CLASS_RS_PKMN_RANGER_M] = TRAINER_PIC_RS_POKEMON_RANGER_M,
[FACILITY_CLASS_RS_PKMN_RANGER_F] = TRAINER_PIC_RS_POKEMON_RANGER_F,
[FACILITY_CLASS_MAGMA_LEADER_MAXIE] = TRAINER_PIC_MAGMA_LEADER_MAXIE,
[FACILITY_CLASS_MAGMA_GRUNT_M] = TRAINER_PIC_MAGMA_GRUNT_M,
[FACILITY_CLASS_MAGMA_GRUNT_F] = TRAINER_PIC_MAGMA_GRUNT_F,
[FACILITY_CLASS_RS_LASS] = TRAINER_PIC_RS_LASS,
[FACILITY_CLASS_RS_BUG_CATCHER] = TRAINER_PIC_RS_BUG_CATCHER,
[FACILITY_CLASS_RS_HIKER] = TRAINER_PIC_RS_HIKER,
[FACILITY_CLASS_RS_YOUNG_COUPLE] = TRAINER_PIC_RS_YOUNG_COUPLE,
[FACILITY_CLASS_OLD_COUPLE] = TRAINER_PIC_OLD_COUPLE,
[FACILITY_CLASS_RS_SIS_AND_BRO] = TRAINER_PIC_RS_SIS_AND_BRO,
[FACILITY_CLASS_AQUA_ADMIN_M] = TRAINER_PIC_AQUA_ADMIN_M,
[FACILITY_CLASS_AQUA_ADMIN_F] = TRAINER_PIC_AQUA_ADMIN_F,
[FACILITY_CLASS_MAGMA_ADMIN_M] = TRAINER_PIC_MAGMA_ADMIN_M,
[FACILITY_CLASS_MAGMA_ADMIN_F] = TRAINER_PIC_MAGMA_ADMIN_F,
[FACILITY_CLASS_LEADER_WATTSON] = TRAINER_PIC_LEADER_WATTSON,
[FACILITY_CLASS_LEADER_FLANNERY] = TRAINER_PIC_LEADER_FLANNERY,
[FACILITY_CLASS_LEADER_NORMAN] = TRAINER_PIC_LEADER_NORMAN,
[FACILITY_CLASS_LEADER_WINONA] = TRAINER_PIC_LEADER_WINONA,
[FACILITY_CLASS_LEADER_WALLACE] = TRAINER_PIC_LEADER_WALLACE,
[FACILITY_CLASS_ELITE_FOUR_GLACIA] = TRAINER_PIC_ELITE_FOUR_GLACIA,
[FACILITY_CLASS_ELITE_FOUR_DRAKE] = TRAINER_PIC_ELITE_FOUR_DRAKE,
[FACILITY_CLASS_YOUNGSTER] = TRAINER_PIC_YOUNGSTER,
[FACILITY_CLASS_BUG_CATCHER] = TRAINER_PIC_BUG_CATCHER,
[FACILITY_CLASS_LASS] = TRAINER_PIC_LASS,
[FACILITY_CLASS_SAILOR] = TRAINER_PIC_SAILOR,
[FACILITY_CLASS_CAMPER] = TRAINER_PIC_CAMPER,
[FACILITY_CLASS_PICNICKER] = TRAINER_PIC_PICNICKER,
[FACILITY_CLASS_POKEMANIAC] = TRAINER_PIC_POKEMANIAC,
[FACILITY_CLASS_SUPER_NERD] = TRAINER_PIC_SUPER_NERD,
[FACILITY_CLASS_HIKER] = TRAINER_PIC_HIKER,
[FACILITY_CLASS_BIKER] = TRAINER_PIC_BIKER,
[FACILITY_CLASS_BURGLAR] = TRAINER_PIC_BURGLAR,
[FACILITY_CLASS_ENGINEER] = TRAINER_PIC_ENGINEER,
[FACILITY_CLASS_FISHERMAN] = TRAINER_PIC_FISHERMAN,
[FACILITY_CLASS_SWIMMER_M] = TRAINER_PIC_SWIMMER_M,
[FACILITY_CLASS_CUE_BALL] = TRAINER_PIC_CUE_BALL,
[FACILITY_CLASS_GAMER] = TRAINER_PIC_GAMER,
[FACILITY_CLASS_BEAUTY] = TRAINER_PIC_BEAUTY,
[FACILITY_CLASS_SWIMMER_F] = TRAINER_PIC_SWIMMER_F,
[FACILITY_CLASS_PSYCHIC_M] = TRAINER_PIC_PSYCHIC_M,
[FACILITY_CLASS_ROCKER] = TRAINER_PIC_ROCKER,
[FACILITY_CLASS_JUGGLER] = TRAINER_PIC_JUGGLER,
[FACILITY_CLASS_TAMER] = TRAINER_PIC_TAMER,
[FACILITY_CLASS_BIRD_KEEPER] = TRAINER_PIC_BIRD_KEEPER,
[FACILITY_CLASS_BLACK_BELT] = TRAINER_PIC_BLACK_BELT,
[FACILITY_CLASS_RIVAL_EARLY] = TRAINER_PIC_RIVAL_EARLY,
[FACILITY_CLASS_SCIENTIST] = TRAINER_PIC_SCIENTIST,
[FACILITY_CLASS_BOSS] = TRAINER_PIC_LEADER_GIOVANNI,
[FACILITY_CLASS_ROCKET_GRUNT_M] = TRAINER_PIC_ROCKET_GRUNT_M,
[FACILITY_CLASS_COOLTRAINER_M] = TRAINER_PIC_COOLTRAINER_M,
[FACILITY_CLASS_COOLTRAINER_F] = TRAINER_PIC_COOLTRAINER_F,
[FACILITY_CLASS_ELITE_FOUR_LORELEI] = TRAINER_PIC_ELITE_FOUR_LORELEI,
[FACILITY_CLASS_ELITE_FOUR_BRUNO] = TRAINER_PIC_ELITE_FOUR_BRUNO,
[FACILITY_CLASS_LEADER_M] = TRAINER_PIC_LEADER_BROCK,
[FACILITY_CLASS_LEADER_F] = TRAINER_PIC_LEADER_MISTY,
[FACILITY_CLASS_GENTLEMAN] = TRAINER_PIC_GENTLEMAN,
[FACILITY_CLASS_RIVAL_LATE] = TRAINER_PIC_RIVAL_LATE,
[FACILITY_CLASS_CHAMPION_RIVAL] = TRAINER_PIC_CHAMPION_RIVAL,
[FACILITY_CLASS_CHANNELER] = TRAINER_PIC_CHANNELER,
[FACILITY_CLASS_TWINS] = TRAINER_PIC_TWINS,
[FACILITY_CLASS_COOL_COUPLE] = TRAINER_PIC_COOL_COUPLE,
[FACILITY_CLASS_YOUNG_COUPLE] = TRAINER_PIC_YOUNG_COUPLE,
[FACILITY_CLASS_CRUSH_KIN] = TRAINER_PIC_CRUSH_KIN,
[FACILITY_CLASS_SIS_AND_BRO] = TRAINER_PIC_SIS_AND_BRO,
[FACILITY_CLASS_PKMN_PROF] = TRAINER_PIC_PROFESSOR_OAK,
[FACILITY_CLASS_BRENDAN] = TRAINER_PIC_RS_BRENDAN_2,
[FACILITY_CLASS_MAY] = TRAINER_PIC_RS_MAY_2,
[FACILITY_CLASS_RED] = TRAINER_PIC_RED,
[FACILITY_CLASS_LEAF] = TRAINER_PIC_LEAF,
[FACILITY_CLASS_ROCKET_GRUNT_F] = TRAINER_PIC_ROCKET_GRUNT_F,
[FACILITY_CLASS_PSYCHIC_F] = TRAINER_PIC_PSYCHIC_F,
[FACILITY_CLASS_CRUSH_GIRL] = TRAINER_PIC_CRUSH_GIRL,
[FACILITY_CLASS_TUBER] = TRAINER_PIC_TUBER_F,
[FACILITY_CLASS_PKMN_BREEDER] = TRAINER_PIC_POKEMON_BREEDER,
[FACILITY_CLASS_PKMN_RANGER_M] = TRAINER_PIC_POKEMON_RANGER_M,
[FACILITY_CLASS_PKMN_RANGER_F] = TRAINER_PIC_POKEMON_RANGER_F,
[FACILITY_CLASS_AROMA_LADY] = TRAINER_PIC_AROMA_LADY,
[FACILITY_CLASS_RUIN_MANIAC] = TRAINER_PIC_RUIN_MANIAC,
[FACILITY_CLASS_LADY] = TRAINER_PIC_LADY,
[FACILITY_CLASS_PAINTER] = TRAINER_PIC_PAINTER,
#ifdef BUGFIX
[FACILITY_CLASS_ELITE_FOUR_AGATHA] = TRAINER_PIC_ELITE_FOUR_AGATHA,
[FACILITY_CLASS_ELITE_FOUR_LANCE] = TRAINER_PIC_ELITE_FOUR_LANCE,
#else
[FACILITY_CLASS_ELITE_FOUR_AGATHA] = TRAINER_PIC_ELITE_FOUR_LORELEI,
[FACILITY_CLASS_ELITE_FOUR_LANCE] = TRAINER_PIC_ELITE_FOUR_BRUNO,
#endif
[FACILITY_CLASS_CHAMPION_RIVAL_2] = TRAINER_PIC_CHAMPION_RIVAL,
};
const u8 gFacilityClassToTrainerClass[] =
{
[FACILITY_CLASS_AQUA_LEADER_ARCHIE] = TRAINER_CLASS_AQUA_LEADER,
[FACILITY_CLASS_AQUA_GRUNT_M] = TRAINER_CLASS_TEAM_AQUA,
[FACILITY_CLASS_AQUA_GRUNT_F] = TRAINER_CLASS_TEAM_AQUA,
[FACILITY_CLASS_RS_AROMA_LADY] = TRAINER_CLASS_RS_AROMA_LADY,
[FACILITY_CLASS_RS_RUIN_MANIAC] = TRAINER_CLASS_RS_RUIN_MANIAC,
[FACILITY_CLASS_INTERVIEWER] = TRAINER_CLASS_INTERVIEWER,
[FACILITY_CLASS_RS_TUBER_F] = TRAINER_CLASS_RS_TUBER_F,
[FACILITY_CLASS_RS_TUBER_M] = TRAINER_CLASS_RS_TUBER_M,
[FACILITY_CLASS_RS_COOLTRAINER_M] = TRAINER_CLASS_RS_COOLTRAINER,
[FACILITY_CLASS_RS_COOLTRAINER_F] = TRAINER_CLASS_RS_COOLTRAINER,
[FACILITY_CLASS_HEX_MANIAC] = TRAINER_CLASS_HEX_MANIAC,
[FACILITY_CLASS_RS_LADY] = TRAINER_CLASS_RS_LADY,
[FACILITY_CLASS_RS_BEAUTY] = TRAINER_CLASS_RS_BEAUTY,
[FACILITY_CLASS_RICH_BOY] = TRAINER_CLASS_RICH_BOY,
[FACILITY_CLASS_RS_POKEMANIAC] = TRAINER_CLASS_RS_POKEMANIAC,
[FACILITY_CLASS_RS_SWIMMER_M] = TRAINER_CLASS_RS_SWIMMER_M,
[FACILITY_CLASS_RS_BLACK_BELT] = TRAINER_CLASS_RS_BLACK_BELT,
[FACILITY_CLASS_GUITARIST] = TRAINER_CLASS_GUITARIST,
[FACILITY_CLASS_KINDLER] = TRAINER_CLASS_KINDLER,
[FACILITY_CLASS_RS_CAMPER] = TRAINER_CLASS_RS_CAMPER,
[FACILITY_CLASS_BUG_MANIAC] = TRAINER_CLASS_BUG_MANIAC,
[FACILITY_CLASS_RS_PSYCHIC_M] = TRAINER_CLASS_RS_PSYCHIC,
[FACILITY_CLASS_RS_PSYCHIC_F] = TRAINER_CLASS_RS_PSYCHIC,
[FACILITY_CLASS_RS_GENTLEMAN] = TRAINER_CLASS_RS_GENTLEMAN,
[FACILITY_CLASS_ELITE_FOUR_SIDNEY] = TRAINER_CLASS_RS_ELITE_FOUR,
[FACILITY_CLASS_ELITE_FOUR_PHOEBE] = TRAINER_CLASS_RS_ELITE_FOUR,
[FACILITY_CLASS_LEADER_ROXANNE] = TRAINER_CLASS_RS_LEADER,
[FACILITY_CLASS_LEADER_BRAWLY] = TRAINER_CLASS_RS_LEADER,
[FACILITY_CLASS_LEADER_TATE_AND_LIZA] = TRAINER_CLASS_RS_LEADER,
[FACILITY_CLASS_SCHOOL_KID_M] = TRAINER_CLASS_SCHOOL_KID,
[FACILITY_CLASS_SCHOOL_KID_F] = TRAINER_CLASS_SCHOOL_KID,
[FACILITY_CLASS_SR_AND_JR] = TRAINER_CLASS_SR_AND_JR,
[FACILITY_CLASS_POKEFAN_M] = TRAINER_CLASS_POKEFAN,
[FACILITY_CLASS_POKEFAN_F] = TRAINER_CLASS_POKEFAN,
[FACILITY_CLASS_EXPERT_M] = TRAINER_CLASS_EXPERT,
[FACILITY_CLASS_EXPERT_F] = TRAINER_CLASS_EXPERT,
[FACILITY_CLASS_RS_YOUNGSTER] = TRAINER_CLASS_RS_YOUNGSTER,
[FACILITY_CLASS_CHAMPION_STEVEN] = TRAINER_CLASS_RS_CHAMPION,
[FACILITY_CLASS_RS_FISHERMAN] = TRAINER_CLASS_RS_FISHERMAN,
[FACILITY_CLASS_CYCLING_TRIATHLETE_M] = TRAINER_CLASS_TRIATHLETE,
[FACILITY_CLASS_CYCLING_TRIATHLETE_F] = TRAINER_CLASS_TRIATHLETE,
[FACILITY_CLASS_RUNNING_TRIATHLETE_M] = TRAINER_CLASS_TRIATHLETE,
[FACILITY_CLASS_RUNNING_TRIATHLETE_F] = TRAINER_CLASS_TRIATHLETE,
[FACILITY_CLASS_SWIMMING_TRIATHLETE_M] = TRAINER_CLASS_TRIATHLETE,
[FACILITY_CLASS_SWIMMING_TRIATHLETE_F] = TRAINER_CLASS_TRIATHLETE,
[FACILITY_CLASS_DRAGON_TAMER] = TRAINER_CLASS_DRAGON_TAMER,
[FACILITY_CLASS_RS_BIRD_KEEPER] = TRAINER_CLASS_RS_BIRD_KEEPER,
[FACILITY_CLASS_NINJA_BOY] = TRAINER_CLASS_NINJA_BOY,
[FACILITY_CLASS_BATTLE_GIRL] = TRAINER_CLASS_BATTLE_GIRL,
[FACILITY_CLASS_PARASOL_LADY] = TRAINER_CLASS_PARASOL_LADY,
[FACILITY_CLASS_RS_SWIMMER_F] = TRAINER_CLASS_RS_SWIMMER_F,
[FACILITY_CLASS_RS_PICNICKER] = TRAINER_CLASS_RS_PICNICKER,
[FACILITY_CLASS_RS_TWINS] = TRAINER_CLASS_RS_TWINS,
[FACILITY_CLASS_RS_SAILOR] = TRAINER_CLASS_RS_SAILOR,
[FACILITY_CLASS_BOARDER_M] = TRAINER_CLASS_BOARDER,
[FACILITY_CLASS_BOARDER_F] = TRAINER_CLASS_BOARDER,
[FACILITY_CLASS_COLLECTOR] = TRAINER_CLASS_COLLECTOR,
[FACILITY_CLASS_PKMN_TRAINER_WALLY] = TRAINER_CLASS_PKMN_TRAINER,
[FACILITY_CLASS_PKMN_TRAINER_BRENDAN] = TRAINER_CLASS_PKMN_TRAINER,
[FACILITY_CLASS_PKMN_TRAINER_BRENDAN_2] = TRAINER_CLASS_PKMN_TRAINER,
[FACILITY_CLASS_PKMN_TRAINER_BRENDAN_3] = TRAINER_CLASS_PKMN_TRAINER,
[FACILITY_CLASS_PKMN_TRAINER_MAY] = TRAINER_CLASS_PKMN_TRAINER,
[FACILITY_CLASS_PKMN_TRAINER_MAY_2] = TRAINER_CLASS_PKMN_TRAINER,
[FACILITY_CLASS_PKMN_TRAINER_MAY_3] = TRAINER_CLASS_PKMN_TRAINER,
[FACILITY_CLASS_RS_PKMN_BREEDER_M] = TRAINER_CLASS_RS_PKMN_BREEDER,
[FACILITY_CLASS_RS_PKMN_BREEDER_F] = TRAINER_CLASS_RS_PKMN_BREEDER,
[FACILITY_CLASS_RS_PKMN_RANGER_M] = TRAINER_CLASS_RS_PKMN_RANGER,
[FACILITY_CLASS_RS_PKMN_RANGER_F] = TRAINER_CLASS_RS_PKMN_RANGER,
[FACILITY_CLASS_MAGMA_LEADER_MAXIE] = TRAINER_CLASS_MAGMA_LEADER,
[FACILITY_CLASS_MAGMA_GRUNT_M] = TRAINER_CLASS_TEAM_MAGMA,
[FACILITY_CLASS_MAGMA_GRUNT_F] = TRAINER_CLASS_TEAM_MAGMA,
[FACILITY_CLASS_RS_LASS] = TRAINER_CLASS_RS_LASS,
[FACILITY_CLASS_RS_BUG_CATCHER] = TRAINER_CLASS_RS_BUG_CATCHER,
[FACILITY_CLASS_RS_HIKER] = TRAINER_CLASS_RS_HIKER,
[FACILITY_CLASS_RS_YOUNG_COUPLE] = TRAINER_CLASS_RS_YOUNG_COUPLE,
[FACILITY_CLASS_OLD_COUPLE] = TRAINER_CLASS_OLD_COUPLE,
[FACILITY_CLASS_RS_SIS_AND_BRO] = TRAINER_CLASS_RS_SIS_AND_BRO,
[FACILITY_CLASS_AQUA_ADMIN_M] = TRAINER_CLASS_AQUA_ADMIN,
[FACILITY_CLASS_AQUA_ADMIN_F] = TRAINER_CLASS_AQUA_ADMIN,
[FACILITY_CLASS_MAGMA_ADMIN_M] = TRAINER_CLASS_MAGMA_ADMIN,
[FACILITY_CLASS_MAGMA_ADMIN_F] = TRAINER_CLASS_MAGMA_ADMIN,
[FACILITY_CLASS_LEADER_WATTSON] = TRAINER_CLASS_RS_LEADER,
[FACILITY_CLASS_LEADER_FLANNERY] = TRAINER_CLASS_RS_LEADER,
[FACILITY_CLASS_LEADER_NORMAN] = TRAINER_CLASS_RS_LEADER,
[FACILITY_CLASS_LEADER_WINONA] = TRAINER_CLASS_RS_LEADER,
[FACILITY_CLASS_LEADER_WALLACE] = TRAINER_CLASS_RS_LEADER,
[FACILITY_CLASS_ELITE_FOUR_GLACIA] = TRAINER_CLASS_RS_ELITE_FOUR,
[FACILITY_CLASS_ELITE_FOUR_DRAKE] = TRAINER_CLASS_RS_ELITE_FOUR,
[FACILITY_CLASS_YOUNGSTER] = TRAINER_CLASS_YOUNGSTER,
[FACILITY_CLASS_BUG_CATCHER] = TRAINER_CLASS_BUG_CATCHER,
[FACILITY_CLASS_LASS] = TRAINER_CLASS_LASS,
[FACILITY_CLASS_SAILOR] = TRAINER_CLASS_SAILOR,
[FACILITY_CLASS_CAMPER] = TRAINER_CLASS_CAMPER,
[FACILITY_CLASS_PICNICKER] = TRAINER_CLASS_PICNICKER,
[FACILITY_CLASS_POKEMANIAC] = TRAINER_CLASS_POKEMANIAC,
[FACILITY_CLASS_SUPER_NERD] = TRAINER_CLASS_SUPER_NERD,
[FACILITY_CLASS_HIKER] = TRAINER_CLASS_HIKER,
[FACILITY_CLASS_BIKER] = TRAINER_CLASS_BIKER,
[FACILITY_CLASS_BURGLAR] = TRAINER_CLASS_BURGLAR,
[FACILITY_CLASS_ENGINEER] = TRAINER_CLASS_ENGINEER,
[FACILITY_CLASS_FISHERMAN] = TRAINER_CLASS_FISHERMAN,
[FACILITY_CLASS_SWIMMER_M] = TRAINER_CLASS_SWIMMER_M,
[FACILITY_CLASS_CUE_BALL] = TRAINER_CLASS_CUE_BALL,
[FACILITY_CLASS_GAMER] = TRAINER_CLASS_GAMER,
[FACILITY_CLASS_BEAUTY] = TRAINER_CLASS_BEAUTY,
[FACILITY_CLASS_SWIMMER_F] = TRAINER_CLASS_SWIMMER_F,
[FACILITY_CLASS_PSYCHIC_M] = TRAINER_CLASS_PSYCHIC,
[FACILITY_CLASS_ROCKER] = TRAINER_CLASS_ROCKER,
[FACILITY_CLASS_JUGGLER] = TRAINER_CLASS_JUGGLER,
[FACILITY_CLASS_TAMER] = TRAINER_CLASS_TAMER,
[FACILITY_CLASS_BIRD_KEEPER] = TRAINER_CLASS_BIRD_KEEPER,
[FACILITY_CLASS_BLACK_BELT] = TRAINER_CLASS_BLACK_BELT,
[FACILITY_CLASS_RIVAL_EARLY] = TRAINER_CLASS_RIVAL_EARLY,
[FACILITY_CLASS_SCIENTIST] = TRAINER_CLASS_SCIENTIST,
[FACILITY_CLASS_BOSS] = TRAINER_CLASS_BOSS,
[FACILITY_CLASS_ROCKET_GRUNT_M] = TRAINER_CLASS_TEAM_ROCKET,
[FACILITY_CLASS_COOLTRAINER_M] = TRAINER_CLASS_COOLTRAINER,
[FACILITY_CLASS_COOLTRAINER_F] = TRAINER_CLASS_COOLTRAINER,
[FACILITY_CLASS_ELITE_FOUR_LORELEI] = TRAINER_CLASS_ELITE_FOUR,
[FACILITY_CLASS_ELITE_FOUR_BRUNO] = TRAINER_CLASS_ELITE_FOUR,
[FACILITY_CLASS_LEADER_M] = TRAINER_CLASS_LEADER,
[FACILITY_CLASS_LEADER_F] = TRAINER_CLASS_LEADER,
[FACILITY_CLASS_GENTLEMAN] = TRAINER_CLASS_GENTLEMAN,
[FACILITY_CLASS_RIVAL_LATE] = TRAINER_CLASS_RIVAL_LATE,
[FACILITY_CLASS_CHAMPION_RIVAL] = TRAINER_CLASS_CHAMPION,
[FACILITY_CLASS_CHANNELER] = TRAINER_CLASS_CHANNELER,
[FACILITY_CLASS_TWINS] = TRAINER_CLASS_TWINS,
[FACILITY_CLASS_COOL_COUPLE] = TRAINER_CLASS_COOL_COUPLE,
[FACILITY_CLASS_YOUNG_COUPLE] = TRAINER_CLASS_YOUNG_COUPLE,
[FACILITY_CLASS_CRUSH_KIN] = TRAINER_CLASS_CRUSH_KIN,
[FACILITY_CLASS_SIS_AND_BRO] = TRAINER_CLASS_SIS_AND_BRO,
[FACILITY_CLASS_PKMN_PROF] = TRAINER_CLASS_PKMN_PROF,
[FACILITY_CLASS_BRENDAN] = TRAINER_CLASS_PLAYER,
[FACILITY_CLASS_MAY] = TRAINER_CLASS_PLAYER,
[FACILITY_CLASS_RED] = TRAINER_CLASS_PLAYER,
[FACILITY_CLASS_LEAF] = TRAINER_CLASS_PLAYER,
[FACILITY_CLASS_ROCKET_GRUNT_F] = TRAINER_CLASS_TEAM_ROCKET,
[FACILITY_CLASS_PSYCHIC_F] = TRAINER_CLASS_PSYCHIC,
[FACILITY_CLASS_CRUSH_GIRL] = TRAINER_CLASS_CRUSH_GIRL,
[FACILITY_CLASS_TUBER] = TRAINER_CLASS_TUBER,
[FACILITY_CLASS_PKMN_BREEDER] = TRAINER_CLASS_PKMN_BREEDER,
[FACILITY_CLASS_PKMN_RANGER_M] = TRAINER_CLASS_PKMN_RANGER,
[FACILITY_CLASS_PKMN_RANGER_F] = TRAINER_CLASS_PKMN_RANGER,
[FACILITY_CLASS_AROMA_LADY] = TRAINER_CLASS_AROMA_LADY,
[FACILITY_CLASS_RUIN_MANIAC] = TRAINER_CLASS_RUIN_MANIAC,
[FACILITY_CLASS_LADY] = TRAINER_CLASS_LADY,
[FACILITY_CLASS_PAINTER] = TRAINER_CLASS_PAINTER,
[FACILITY_CLASS_ELITE_FOUR_AGATHA] = TRAINER_CLASS_ELITE_FOUR,
[FACILITY_CLASS_ELITE_FOUR_LANCE] = TRAINER_CLASS_ELITE_FOUR,
[FACILITY_CLASS_CHAMPION_RIVAL_2] = TRAINER_CLASS_CHAMPION,
};
|
482a1fe6e7e565e1b3c29fa76fd3d96a24006f72
|
77c5962bd8fa9494b7847a07bdd9eea4e5f6c0da
|
/src/c/opus_helper.h
|
03d1f38eebb0515e312ec4de8edc1083fe8f8df2
|
[
"MIT"
] |
permissive
|
brion/ogv.js
|
a07892bf6cb397faf236903724a8f92ac344a0da
|
5ce404a6aa8f53b7cef220916b89e613ac58fd17
|
refs/heads/main
| 2023-09-03T22:10:55.300560
| 2023-01-03T17:00:06
| 2023-01-03T17:00:06
| 13,348,747
| 1,063
| 129
|
NOASSERTION
| 2023-03-04T02:46:35
| 2013-10-05T16:52:51
|
JavaScript
|
UTF-8
|
C
| false
| false
| 182
|
h
|
opus_helper.h
|
#ifndef OPUS_HELPER_H
#define OPUS_HELPER_H
OpusMSDecoder *opus_process_header(ogg_packet *op, int *mapping_family, int *channels, int *preskip, float *gain, int *streams);
#endif
|
147d8b2e894ae3870649ad6d6d548957360952b6
|
022a5b48798b391a28e58ef4ad1b762c1b3d0d9c
|
/lib/bap_ghidra/ghidra_stubs.c
|
044b1219ea6e8811755fae7e99db3cf3af4b76a6
|
[
"MIT"
] |
permissive
|
BinaryAnalysisPlatform/bap
|
b96e8ee63e59af67c70e4d90d46b10785767fa65
|
511b64ce7fcf619eae373a6a11c50c668a0cf311
|
refs/heads/master
| 2023-08-17T16:39:11.865744
| 2023-06-09T15:02:19
| 2023-06-09T15:02:19
| 25,968,851
| 2,002
| 332
|
MIT
| 2023-09-08T16:30:56
| 2014-10-30T11:59:43
|
OCaml
|
UTF-8
|
C
| false
| false
| 374
|
c
|
ghidra_stubs.c
|
#include <caml/mlvalues.h>
#include <caml/memory.h>
#include <caml/alloc.h>
#include <string.h>
#include "ghidra_disasm.h"
value disasm_ghidra_init_stub(value paths, value print_targets) {
CAMLparam2(paths, print_targets);
char *s = strdup(String_val(paths));
int r = Val_int(disasm_ghidra_init(s, Bool_val(print_targets)));
free(s);
CAMLreturn(r);
}
|
335aaf64370958c18a3b3be9438d03fb4ef4d8aa
|
28d0f8c01599f8f6c711bdde0b59f9c2cd221203
|
/sys/arch/hpcmips/dev/ucbsnd.c
|
f12916871d3cafe5b640495d584537ca31ec28bc
|
[] |
no_license
|
NetBSD/src
|
1a9cbc22ed778be638b37869ed4fb5c8dd616166
|
23ee83f7c0aea0777bd89d8ebd7f0cde9880d13c
|
refs/heads/trunk
| 2023-08-31T13:24:58.105962
| 2023-08-27T15:50:47
| 2023-08-27T15:50:47
| 88,439,547
| 656
| 348
| null | 2023-07-20T20:07:24
| 2017-04-16T20:03:43
| null |
UTF-8
|
C
| false
| false
| 17,806
|
c
|
ucbsnd.c
|
/* $NetBSD: ucbsnd.c,v 1.26 2020/11/21 21:23:48 thorpej Exp $ */
/*-
* Copyright (c) 2000 The NetBSD Foundation, Inc.
* All rights reserved.
*
* This code is derived from software contributed to The NetBSD Foundation
* by UCHIYAMA Yasushi.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
*/
/*
* Device driver for PHILIPS UCB1200 Advanced modem/audio analog front-end
* Audio codec part.
*
* /dev/ucbsnd0 : sampling rate 22.154kHz monoral 16bit straight PCM device.
*/
#include <sys/cdefs.h>
__KERNEL_RCSID(0, "$NetBSD: ucbsnd.c,v 1.26 2020/11/21 21:23:48 thorpej Exp $");
#include "opt_use_poll.h"
#include <sys/param.h>
#include <sys/systm.h>
#include <sys/conf.h>
#include <sys/kmem.h>
#include <sys/device.h>
#include <sys/proc.h>
#include <sys/endian.h>
#include <sys/bus.h>
#include <sys/intr.h>
#include <mips/locore.h>
#include <mips/cache.h>
#include <hpcmips/tx/tx39var.h>
#include <hpcmips/tx/tx39sibvar.h>
#include <hpcmips/tx/tx39sibreg.h>
#include <hpcmips/tx/tx39icureg.h>
#include <hpcmips/tx/txsnd.h>
#include <hpcmips/dev/ucb1200var.h>
#include <hpcmips/dev/ucb1200reg.h>
#define AUDIOUNIT(x) (minor(x)&0x0f)
#define AUDIODEV(x) (minor(x)&0xf0)
#ifdef UCBSNDDEBUG
int ucbsnd_debug = 1;
#define DPRINTF(arg) if (ucbsnd_debug) printf arg;
#define DPRINTFN(n, arg) if (ucbsnd_debug > (n)) printf arg;
#else
#define DPRINTF(arg)
#define DPRINTFN(n, arg)
#endif
#define UCBSND_BUFBLOCK 5
/*
* XXX temporary DMA buffer
*/
static u_int8_t dmabuf_static[TX39_SIBDMA_SIZE * UCBSND_BUFBLOCK] __attribute__((__aligned__(16))); /* XXX */
static size_t dmabufcnt_static[UCBSND_BUFBLOCK]; /* XXX */
enum ucbsnd_state {
/* 0 */ UCBSND_IDLE,
/* 1 */ UCBSND_INIT,
/* 2 */ UCBSND_ENABLE_SAMPLERATE,
/* 3 */ UCBSND_ENABLE_OUTPUTPATH,
/* 4 */ UCBSND_ENABLE_SETVOLUME,
/* 5 */ UCBSND_ENABLE_SPEAKER0,
/* 6 */ UCBSND_ENABLE_SPEAKER1,
/* 7 */ UCBSND_TRANSITION_PIO,
/* 8 */ UCBSND_PIO,
/* 9 */ UCBSND_TRANSITION_DISABLE,
/*10 */ UCBSND_DISABLE_OUTPUTPATH,
/*11 */ UCBSND_DISABLE_SPEAKER0,
/*12 */ UCBSND_DISABLE_SPEAKER1,
/*13 */ UCBSND_DISABLE_SIB,
/*14 */ UCBSND_DMASTART,
/*15 */ UCBSND_DMAEND,
};
struct ring_buf {
u_int32_t rb_buf; /* buffer start address */
size_t *rb_bufcnt; /* effective data count (max rb_blksize)*/
size_t rb_bufsize; /* total amount of buffer */
int rb_blksize; /* DMA block size */
int rb_maxblks; /* # of blocks in ring */
int rb_inp; /* start of input (to buffer) */
int rb_outp; /* output pointer */
};
struct ucbsnd_softc {
device_t sc_dev;
device_t sc_sib; /* parent (TX39 SIB module) */
device_t sc_ucb; /* parent (UCB1200 module) */
tx_chipset_tag_t sc_tc;
struct tx_sound_tag sc_tag;
int sc_mute;
/*
* audio codec state machine
*/
int sa_transfer_mode;
#define UCBSND_TRANSFERMODE_DMA 0
#define UCBSND_TRANSFERMODE_PIO 1
enum ucbsnd_state sa_state;
int sa_snd_attenuation;
#define UCBSND_DEFAULT_ATTENUATION 0 /* Full volume */
int sa_snd_rate; /* passed down from SIB module */
int sa_tel_rate;
void* sa_sf0ih;
void* sa_sndih;
int sa_retry;
int sa_cnt; /* misc counter */
/*
* input buffer
*/
size_t sa_dmacnt;
struct ring_buf sc_rb;
};
int ucbsnd_match(device_t, cfdata_t, void *);
void ucbsnd_attach(device_t, device_t, void *);
int ucbsnd_exec_output(void *);
int ucbsnd_busy(void *);
void ucbsnd_sound_init(struct ucbsnd_softc *);
void __ucbsnd_sound_click(tx_sound_tag_t);
void __ucbsnd_sound_mute(tx_sound_tag_t, int);
int ucbsndwrite_subr(struct ucbsnd_softc *, u_int32_t *, size_t,
struct uio *);
int ringbuf_allocate(struct ring_buf *, size_t, int);
void ringbuf_deallocate(struct ring_buf *);
void ringbuf_reset(struct ring_buf *);
int ringbuf_full(struct ring_buf *);
void *ringbuf_producer_get(struct ring_buf *);
void ringbuf_producer_return(struct ring_buf *, size_t);
void *ringbuf_consumer_get(struct ring_buf *, size_t *);
void ringbuf_consumer_return(struct ring_buf *);
CFATTACH_DECL_NEW(ucbsnd, sizeof(struct ucbsnd_softc),
ucbsnd_match, ucbsnd_attach, NULL, NULL);
dev_type_open(ucbsndopen);
dev_type_close(ucbsndclose);
dev_type_read(ucbsndread);
dev_type_write(ucbsndwrite);
const struct cdevsw ucbsnd_cdevsw = {
.d_open = ucbsndopen,
.d_close = ucbsndclose,
.d_read = ucbsndread,
.d_write = ucbsndwrite,
.d_ioctl = nullioctl,
.d_stop = nostop,
.d_tty = notty,
.d_poll = nopoll,
.d_mmap = nommap,
.d_kqfilter = nokqfilter,
.d_discard = nodiscard,
.d_flag = 0
};
int
ucbsnd_match(device_t parent, cfdata_t cf, void *aux)
{
return (1);
}
void
ucbsnd_attach(device_t parent, device_t self, void *aux)
{
struct ucb1200_attach_args *ucba = aux;
struct ucbsnd_softc *sc = device_private(self);
tx_chipset_tag_t tc;
sc->sc_dev = self;
tc = sc->sc_tc = ucba->ucba_tc;
sc->sc_sib = ucba->ucba_sib;
sc->sc_ucb = ucba->ucba_ucb;
/* register sound functions */
ucbsnd_sound_init(sc);
sc->sa_snd_rate = ucba->ucba_snd_rate;
sc->sa_tel_rate = ucba->ucba_tel_rate;
sc->sa_snd_attenuation = UCBSND_DEFAULT_ATTENUATION;
#define KHZ(a) ((a) / 1000), (((a) % 1000))
printf(": audio %d.%03d kHz telecom %d.%03d kHz",
KHZ((tx39sib_clock(sc->sc_sib) * 2) /
(sc->sa_snd_rate * 64)),
KHZ((tx39sib_clock(sc->sc_sib) * 2) /
(sc->sa_tel_rate * 64)));
ucb1200_state_install(parent, ucbsnd_busy, self,
UCB1200_SND_MODULE);
ringbuf_allocate(&sc->sc_rb, TX39_SIBDMA_SIZE, UCBSND_BUFBLOCK);
printf("\n");
}
int
ucbsnd_busy(void *arg)
{
struct ucbsnd_softc *sc = arg;
return (sc->sa_state != UCBSND_IDLE);
}
int
ucbsnd_exec_output(void *arg)
{
struct ucbsnd_softc *sc = arg;
tx_chipset_tag_t tc = sc->sc_tc;
txreg_t reg;
u_int32_t *buf;
size_t bufcnt;
switch (sc->sa_state) {
default:
panic("ucbsnd_exec_output: invalid state %d", sc->sa_state);
/* NOTREACHED */
break;
case UCBSND_IDLE:
/* nothing to do */
return (0);
case UCBSND_INIT:
sc->sa_sf0ih = tx_intr_establish(
tc, MAKEINTR(1, TX39_INTRSTATUS1_SIBSF0INT),
IST_EDGE, IPL_TTY, ucbsnd_exec_output, sc);
sc->sa_state = UCBSND_ENABLE_SAMPLERATE;
return (0);
case UCBSND_ENABLE_SAMPLERATE:
/* Enable UCB1200 side sample rate */
reg = TX39_SIBSF0_WRITE;
reg = TX39_SIBSF0_REGADDR_SET(reg, UCB1200_AUDIOCTRLA_REG);
reg = TX39_SIBSF0_REGDATA_SET(reg, sc->sa_snd_rate);
tx_conf_write(tc, TX39_SIBSF0CTRL_REG, reg);
sc->sa_state = UCBSND_ENABLE_OUTPUTPATH;
return (0);
case UCBSND_ENABLE_OUTPUTPATH:
/* Enable UCB1200 side */
reg = TX39_SIBSF0_WRITE;
reg = TX39_SIBSF0_REGADDR_SET(reg, UCB1200_AUDIOCTRLB_REG);
reg = TX39_SIBSF0_REGDATA_SET(reg, sc->sa_snd_attenuation |
UCB1200_AUDIOCTRLB_OUTEN);
tx_conf_write(tc, TX39_SIBSF0CTRL_REG, reg);
/* Enable SIB side */
reg = tx_conf_read(tc, TX39_SIBCTRL_REG);
tx_conf_write(tc, TX39_SIBCTRL_REG,
reg | TX39_SIBCTRL_ENSND);
sc->sa_state = UCBSND_ENABLE_SPEAKER0;
sc->sa_retry = 10;
return (0);
case UCBSND_ENABLE_SPEAKER0:
/* Speaker on */
reg = TX39_SIBSF0_REGADDR_SET(0, UCB1200_IO_DATA_REG);
tx_conf_write(tc, TX39_SIBSF0CTRL_REG, reg);
sc->sa_state = UCBSND_ENABLE_SPEAKER1;
return (0);
case UCBSND_ENABLE_SPEAKER1:
reg = tx_conf_read(tc, TX39_SIBSF0STAT_REG);
if ((TX39_SIBSF0_REGADDR(reg) != UCB1200_IO_DATA_REG) &&
--sc->sa_retry > 0) {
sc->sa_state = UCBSND_ENABLE_SPEAKER0;
return (0);
}
if (sc->sa_retry <= 0) {
printf("ucbsnd_exec_output: subframe0 busy\n");
sc->sa_state = UCBSND_IDLE;
return (0);
}
reg |= TX39_SIBSF0_WRITE;
reg |= UCB1200_IO_DATA_SPEAKER;
tx_conf_write(tc, TX39_SIBSF0CTRL_REG, reg);
/*
* Begin to transfer.
*/
switch (sc->sa_transfer_mode) {
case UCBSND_TRANSFERMODE_DMA:
sc->sa_state = UCBSND_DMASTART;
sc->sa_dmacnt = 0;
break;
case UCBSND_TRANSFERMODE_PIO:
sc->sa_state = UCBSND_TRANSITION_PIO;
break;
}
return (0);
case UCBSND_DMASTART:
/* get data */
if (sc->sa_dmacnt) /* return previous buffer */
ringbuf_consumer_return(&sc->sc_rb);
buf = ringbuf_consumer_get(&sc->sc_rb, &bufcnt);
if (buf == 0) {
sc->sa_state = UCBSND_DMAEND;
return (0);
}
if (sc->sa_dmacnt == 0) {
/* change interrupt source */
if (sc->sa_sf0ih) {
tx_intr_disestablish(tc, sc->sa_sf0ih);
sc->sa_sf0ih = 0;
}
sc->sa_sndih = tx_intr_establish(
tc, MAKEINTR(1, TX39_INTRSTATUS1_SND1_0INT),
IST_EDGE, IPL_TTY, ucbsnd_exec_output, sc);
} else {
wakeup(&sc->sc_rb);
}
/* set DMA buffer address */
tx_conf_write(tc, TX39_SIBSNDTXSTART_REG,
MIPS_KSEG0_TO_PHYS(buf));
/* set DMA buffer size */
tx_conf_write(tc, TX39_SIBSIZE_REG,
TX39_SIBSIZE_SNDSIZE_SET(0, bufcnt));
tx_conf_write(tc, TX39_SIBSF0CTRL_REG, TX39_SIBSF0_SNDVALID);
/* kick DMA */
reg = tx_conf_read(tc, TX39_SIBDMACTRL_REG);
reg |= TX39_SIBDMACTRL_ENDMATXSND;
tx_conf_write(tc, TX39_SIBDMACTRL_REG, reg);
/* set next */
sc->sa_dmacnt += bufcnt;
break;
case UCBSND_DMAEND:
sc->sa_state = UCBSND_TRANSITION_DISABLE;
break;
case UCBSND_TRANSITION_PIO:
/* change interrupt source */
if (sc->sa_sf0ih) {
tx_intr_disestablish(tc, sc->sa_sf0ih);
sc->sa_sf0ih = 0;
}
sc->sa_sndih = tx_intr_establish(
tc, MAKEINTR(1, TX39_INTRSTATUS1_SNDININT),
IST_EDGE, IPL_TTY, ucbsnd_exec_output, sc);
sc->sa_state = UCBSND_PIO;
sc->sa_cnt = 0;
return (0);
case UCBSND_PIO:
{
/* PIO test routine */
int dummy_data = sc->sa_cnt * 3;
tx_conf_write(tc, TX39_SIBSNDHOLD_REG,
dummy_data << 16 | dummy_data);
tx_conf_write(tc, TX39_SIBSF0CTRL_REG, TX39_SIBSF0_SNDVALID);
if (sc->sa_cnt++ > 50) {
sc->sa_state = UCBSND_TRANSITION_DISABLE;
}
return (0);
}
case UCBSND_TRANSITION_DISABLE:
/* change interrupt source */
if (sc->sa_sndih) {
tx_intr_disestablish(tc, sc->sa_sndih);
sc->sa_sndih = 0;
}
sc->sa_sf0ih = tx_intr_establish(
tc, MAKEINTR(1, TX39_INTRSTATUS1_SIBSF0INT),
IST_EDGE, IPL_TTY, ucbsnd_exec_output, sc);
sc->sa_state = UCBSND_DISABLE_OUTPUTPATH;
return (0);
case UCBSND_DISABLE_OUTPUTPATH:
/* disable codec output path and mute */
reg = TX39_SIBSF0_WRITE;
reg = TX39_SIBSF0_REGADDR_SET(reg, UCB1200_AUDIOCTRLB_REG);
reg = TX39_SIBSF0_REGDATA_SET(reg, UCB1200_AUDIOCTRLB_MUTE);
tx_conf_write(tc, TX39_SIBSF0CTRL_REG, reg);
sc->sa_state = UCBSND_DISABLE_SPEAKER0;
sc->sa_retry = 10;
return (0);
case UCBSND_DISABLE_SPEAKER0:
/* Speaker off */
reg = TX39_SIBSF0_REGADDR_SET(0, UCB1200_IO_DATA_REG);
tx_conf_write(tc, TX39_SIBSF0CTRL_REG, reg);
sc->sa_state = UCBSND_DISABLE_SPEAKER1;
return (0);
case UCBSND_DISABLE_SPEAKER1:
reg = tx_conf_read(tc, TX39_SIBSF0STAT_REG);
if ((TX39_SIBSF0_REGADDR(reg) != UCB1200_IO_DATA_REG) &&
--sc->sa_retry > 0) {
sc->sa_state = UCBSND_DISABLE_SPEAKER0;
return (0);
}
if (sc->sa_retry <= 0) {
printf("ucbsnd_exec_output: subframe0 busy\n");
sc->sa_state = UCBSND_IDLE;
return (0);
}
reg |= TX39_SIBSF0_WRITE;
reg &= ~UCB1200_IO_DATA_SPEAKER;
tx_conf_write(tc, TX39_SIBSF0CTRL_REG, reg);
sc->sa_state = UCBSND_DISABLE_SIB;
return (0);
case UCBSND_DISABLE_SIB:
/* Disable SIB side */
reg = tx_conf_read(tc, TX39_SIBCTRL_REG);
reg &= ~TX39_SIBCTRL_ENSND;
tx_conf_write(tc, TX39_SIBCTRL_REG, reg);
/* end audio disable sequence */
if (sc->sa_sf0ih) {
tx_intr_disestablish(tc, sc->sa_sf0ih);
sc->sa_sf0ih = 0;
}
sc->sa_state = UCBSND_IDLE;
return (0);
}
return (0);
}
/*
* global sound interface.
*/
void
ucbsnd_sound_init(struct ucbsnd_softc *sc)
{
tx_sound_tag_t ts = &sc->sc_tag;
tx_chipset_tag_t tc = sc->sc_tc;
ts->ts_v = sc;
ts->ts_click = __ucbsnd_sound_click;
ts->ts_mute = __ucbsnd_sound_mute;
tx_conf_register_sound(tc, ts);
}
void
__ucbsnd_sound_click(tx_sound_tag_t arg)
{
struct ucbsnd_softc *sc = (void*)arg;
if (!sc->sc_mute && sc->sa_state == UCBSND_IDLE) {
sc->sa_transfer_mode = UCBSND_TRANSFERMODE_PIO;
sc->sa_state = UCBSND_INIT;
ucbsnd_exec_output((void*)sc);
}
}
void
__ucbsnd_sound_mute(tx_sound_tag_t arg, int onoff)
{
struct ucbsnd_softc *sc = (void*)arg;
sc->sc_mute = onoff;
}
/*
* device access
*/
extern struct cfdriver ucbsnd_cd;
int
ucbsndopen(dev_t dev, int flags, int ifmt, struct lwp *l)
{
int unit = AUDIOUNIT(dev);
struct ucbsnd_softc *sc;
int s;
sc = device_lookup_private(&ucbsnd_cd, unit);
if (sc == NULL)
return (ENXIO);
s = splvm();
ringbuf_reset(&sc->sc_rb);
splx(s);
return (0);
}
int
ucbsndclose(dev_t dev, int flags, int ifmt, struct lwp *l)
{
int unit = AUDIOUNIT(dev);
struct ucbsnd_softc *sc;
sc = device_lookup_private(&ucbsnd_cd, unit);
if (sc == NULL)
return (ENXIO);
return (0);
}
int
ucbsndread(dev_t dev, struct uio *uio, int ioflag)
{
int unit = AUDIOUNIT(dev);
struct ucbsnd_softc *sc;
int error = 0;
sc = device_lookup_private(&ucbsnd_cd, unit);
if (sc == NULL)
return (ENXIO);
/* not supported yet */
return (error);
}
int
ucbsndwrite_subr(struct ucbsnd_softc *sc, u_int32_t *buf, size_t bufsize,
struct uio *uio)
{
int i, s, error;
error = uiomove(buf, bufsize, uio);
/*
* inverse endian for UCB1200
*/
for (i = 0; i < bufsize / sizeof(int); i++)
buf[i] = htobe32(buf[i]);
mips_dcache_wbinv_range((vaddr_t)buf, bufsize);
ringbuf_producer_return(&sc->sc_rb, bufsize);
s = splvm();
if (sc->sa_state == UCBSND_IDLE && ringbuf_full(&sc->sc_rb)) {
sc->sa_transfer_mode = UCBSND_TRANSFERMODE_DMA;
sc->sa_state = UCBSND_INIT;
ucbsnd_exec_output((void*)sc);
}
splx(s);
return (error);
}
int
ucbsndwrite(dev_t dev, struct uio *uio, int ioflag)
{
int unit = AUDIOUNIT(dev);
struct ucbsnd_softc *sc;
int len, error = 0;
int i, n, s, rest;
void *buf;
sc = device_lookup_private(&ucbsnd_cd, unit);
if (sc == NULL)
return (ENXIO);
len = uio->uio_resid;
n = (len + TX39_SIBDMA_SIZE - 1) / TX39_SIBDMA_SIZE;
rest = len % TX39_SIBDMA_SIZE;
if (rest)
--n;
for (i = 0; i < n; i++) {
while (!(buf = ringbuf_producer_get(&sc->sc_rb))) {
error = tsleep(&sc->sc_rb, PRIBIO, "ucbsnd", 1000);
if (error)
goto errout;
}
error = ucbsndwrite_subr(sc, buf, TX39_SIBDMA_SIZE, uio);
if (error)
goto out;
}
if (rest) {
while (!(buf = ringbuf_producer_get(&sc->sc_rb))) {
error = tsleep(&sc->sc_rb, PRIBIO, "ucbsnd", 1000);
if (error)
goto errout;
}
error = ucbsndwrite_subr(sc, buf, rest, uio);
}
out:
return (error);
errout:
printf("%s: timeout. reset ring-buffer.\n", device_xname(sc->sc_dev));
s = splvm();
ringbuf_reset(&sc->sc_rb);
splx(s);
return (error);
}
/*
* Ring buffer.
*/
int
ringbuf_allocate(struct ring_buf *rb, size_t blksize, int maxblk)
{
rb->rb_bufsize = blksize * maxblk;
rb->rb_blksize = blksize;
rb->rb_maxblks = maxblk;
#if notyet
rb->rb_buf = (u_int32_t)kmem_alloc(rb->rb_bufsize, KM_SLEEP);
#else
rb->rb_buf = (u_int32_t)dmabuf_static;
#endif
if (rb->rb_buf == 0) {
printf("ringbuf_allocate: can't allocate buffer\n");
return (1);
}
memset((char*)rb->rb_buf, 0, rb->rb_bufsize);
#if notyet
rb->rb_bufcnt = kmem_alloc(rb->rb_maxblks * sizeof(size_t), KM_SLEEP);
#else
rb->rb_bufcnt = dmabufcnt_static;
#endif
if (rb->rb_bufcnt == 0) {
printf("ringbuf_allocate: can't allocate buffer\n");
return (1);
}
memset((char*)rb->rb_bufcnt, 0, rb->rb_maxblks * sizeof(size_t));
ringbuf_reset(rb);
return (0);
}
void
ringbuf_deallocate(struct ring_buf *rb)
{
#if notyet
kmem_free((void*)rb->rb_buf, rb->rb_bufsize);
kmem_free(rb->rb_bufcnt, rb->rb_maxblks * sizeof(size_t));
#endif
}
void
ringbuf_reset(struct ring_buf *rb)
{
rb->rb_outp = 0;
rb->rb_inp = 0;
}
int
ringbuf_full(struct ring_buf *rb)
{
int ret;
ret = rb->rb_outp == rb->rb_maxblks;
return (ret);
}
void*
ringbuf_producer_get(struct ring_buf *rb)
{
u_int32_t ret;
int s;
s = splvm();
ret = ringbuf_full(rb) ? 0 :
rb->rb_buf + rb->rb_inp * rb->rb_blksize;
splx(s);
return (void *)ret;
}
void
ringbuf_producer_return(struct ring_buf *rb, size_t cnt)
{
int s;
assert(cnt <= rb->rb_blksize);
s = splvm();
rb->rb_outp++;
rb->rb_bufcnt[rb->rb_inp] = cnt;
rb->rb_inp = (rb->rb_inp + 1) % rb->rb_maxblks;
splx(s);
}
void*
ringbuf_consumer_get(struct ring_buf *rb, size_t *cntp)
{
u_int32_t p;
int idx;
if (rb->rb_outp == 0)
return (0);
idx = (rb->rb_inp - rb->rb_outp + rb->rb_maxblks) % rb->rb_maxblks;
p = rb->rb_buf + idx * rb->rb_blksize;
*cntp = rb->rb_bufcnt[idx];
return (void *)p;
}
void
ringbuf_consumer_return(struct ring_buf *rb)
{
if (rb->rb_outp > 0)
rb->rb_outp--;
}
|
295312b8a8ca3e7ed5ebb72297556843fea4c8ff
|
eecd5e4c50d8b78a769bcc2675250576bed34066
|
/src/snes/tutorials/ex2.c
|
f143c9f43d2742afece8d22f9fb7dc354ee82dd0
|
[
"BSD-2-Clause"
] |
permissive
|
petsc/petsc
|
3b1a04fea71858e0292f9fd4d04ea11618c50969
|
9c5460f9064ca60dd71a234a1f6faf93e7a6b0c9
|
refs/heads/main
| 2023-08-17T20:51:16.507070
| 2023-08-17T16:08:06
| 2023-08-17T16:08:06
| 8,691,401
| 341
| 169
|
NOASSERTION
| 2023-03-29T11:02:58
| 2013-03-10T20:55:21
|
C
|
UTF-8
|
C
| false
| false
| 12,667
|
c
|
ex2.c
|
static char help[] = "Newton method to solve u'' + u^{2} = f, sequentially.\n\
This example employs a user-defined monitoring routine.\n\n";
/*
Include "petscdraw.h" so that we can use PETSc drawing routines.
Include "petscsnes.h" so that we can use SNES solvers. Note that this
file automatically includes:
petscsys.h - base PETSc routines petscvec.h - vectors
petscmat.h - matrices
petscis.h - index sets petscksp.h - Krylov subspace methods
petscviewer.h - viewers petscpc.h - preconditioners
petscksp.h - linear solvers
*/
#include <petscsnes.h>
/*
User-defined routines
*/
extern PetscErrorCode FormJacobian(SNES, Vec, Mat, Mat, void *);
extern PetscErrorCode FormFunction(SNES, Vec, Vec, void *);
extern PetscErrorCode FormInitialGuess(Vec);
extern PetscErrorCode Monitor(SNES, PetscInt, PetscReal, void *);
/*
User-defined context for monitoring
*/
typedef struct {
PetscViewer viewer;
} MonitorCtx;
int main(int argc, char **argv)
{
SNES snes; /* SNES context */
Vec x, r, F, U; /* vectors */
Mat J; /* Jacobian matrix */
MonitorCtx monP; /* monitoring context */
PetscInt its, n = 5, i, maxit, maxf;
PetscMPIInt size;
PetscScalar h, xp, v, none = -1.0;
PetscReal abstol, rtol, stol, norm;
PetscFunctionBeginUser;
PetscCall(PetscInitialize(&argc, &argv, (char *)0, help));
PetscCallMPI(MPI_Comm_size(PETSC_COMM_WORLD, &size));
PetscCheck(size == 1, PETSC_COMM_SELF, PETSC_ERR_WRONG_MPI_SIZE, "This is a uniprocessor example only!");
PetscCall(PetscOptionsGetInt(NULL, NULL, "-n", &n, NULL));
h = 1.0 / (n - 1);
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Create nonlinear solver context
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
PetscCall(SNESCreate(PETSC_COMM_WORLD, &snes));
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Create vector data structures; set function evaluation routine
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
/*
Note that we form 1 vector from scratch and then duplicate as needed.
*/
PetscCall(VecCreate(PETSC_COMM_WORLD, &x));
PetscCall(VecSetSizes(x, PETSC_DECIDE, n));
PetscCall(VecSetFromOptions(x));
PetscCall(VecDuplicate(x, &r));
PetscCall(VecDuplicate(x, &F));
PetscCall(VecDuplicate(x, &U));
/*
Set function evaluation routine and vector
*/
PetscCall(SNESSetFunction(snes, r, FormFunction, (void *)F));
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Create matrix data structure; set Jacobian evaluation routine
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
PetscCall(MatCreate(PETSC_COMM_WORLD, &J));
PetscCall(MatSetSizes(J, PETSC_DECIDE, PETSC_DECIDE, n, n));
PetscCall(MatSetFromOptions(J));
PetscCall(MatSeqAIJSetPreallocation(J, 3, NULL));
/*
Set Jacobian matrix data structure and default Jacobian evaluation
routine. User can override with:
-snes_fd : default finite differencing approximation of Jacobian
-snes_mf : matrix-free Newton-Krylov method with no preconditioning
(unless user explicitly sets preconditioner)
-snes_mf_operator : form preconditioning matrix as set by the user,
but use matrix-free approx for Jacobian-vector
products within Newton-Krylov method
*/
PetscCall(SNESSetJacobian(snes, J, J, FormJacobian, NULL));
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Customize nonlinear solver; set runtime options
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
/*
Set an optional user-defined monitoring routine
*/
PetscCall(PetscViewerDrawOpen(PETSC_COMM_WORLD, 0, 0, 0, 0, 400, 400, &monP.viewer));
PetscCall(SNESMonitorSet(snes, Monitor, &monP, 0));
/*
Set names for some vectors to facilitate monitoring (optional)
*/
PetscCall(PetscObjectSetName((PetscObject)x, "Approximate Solution"));
PetscCall(PetscObjectSetName((PetscObject)U, "Exact Solution"));
/*
Set SNES/KSP/KSP/PC runtime options, e.g.,
-snes_view -snes_monitor -ksp_type <ksp> -pc_type <pc>
*/
PetscCall(SNESSetFromOptions(snes));
/*
Print parameters used for convergence testing (optional) ... just
to demonstrate this routine; this information is also printed with
the option -snes_view
*/
PetscCall(SNESGetTolerances(snes, &abstol, &rtol, &stol, &maxit, &maxf));
PetscCall(PetscPrintf(PETSC_COMM_WORLD, "atol=%g, rtol=%g, stol=%g, maxit=%" PetscInt_FMT ", maxf=%" PetscInt_FMT "\n", (double)abstol, (double)rtol, (double)stol, maxit, maxf));
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Initialize application:
Store right-hand-side of PDE and exact solution
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
xp = 0.0;
for (i = 0; i < n; i++) {
v = 6.0 * xp + PetscPowScalar(xp + 1.e-12, 6.0); /* +1.e-12 is to prevent 0^6 */
PetscCall(VecSetValues(F, 1, &i, &v, INSERT_VALUES));
v = xp * xp * xp;
PetscCall(VecSetValues(U, 1, &i, &v, INSERT_VALUES));
xp += h;
}
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Evaluate initial guess; then solve nonlinear system
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
/*
Note: The user should initialize the vector, x, with the initial guess
for the nonlinear solver prior to calling SNESSolve(). In particular,
to employ an initial guess of zero, the user should explicitly set
this vector to zero by calling VecSet().
*/
PetscCall(FormInitialGuess(x));
PetscCall(SNESSolve(snes, NULL, x));
PetscCall(SNESGetIterationNumber(snes, &its));
PetscCall(PetscPrintf(PETSC_COMM_WORLD, "number of SNES iterations = %" PetscInt_FMT "\n\n", its));
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Check solution and clean up
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
/*
Check the error
*/
PetscCall(VecAXPY(x, none, U));
PetscCall(VecNorm(x, NORM_2, &norm));
PetscCall(PetscPrintf(PETSC_COMM_WORLD, "Norm of error %g, Iterations %" PetscInt_FMT "\n", (double)norm, its));
/*
Free work space. All PETSc objects should be destroyed when they
are no longer needed.
*/
PetscCall(VecDestroy(&x));
PetscCall(VecDestroy(&r));
PetscCall(VecDestroy(&U));
PetscCall(VecDestroy(&F));
PetscCall(MatDestroy(&J));
PetscCall(SNESDestroy(&snes));
PetscCall(PetscViewerDestroy(&monP.viewer));
PetscCall(PetscFinalize());
return 0;
}
/* ------------------------------------------------------------------- */
/*
FormInitialGuess - Computes initial guess.
Input/Output Parameter:
. x - the solution vector
*/
PetscErrorCode FormInitialGuess(Vec x)
{
PetscScalar pfive = .50;
PetscFunctionBeginUser;
PetscCall(VecSet(x, pfive));
PetscFunctionReturn(PETSC_SUCCESS);
}
/* ------------------------------------------------------------------- */
/*
FormFunction - Evaluates nonlinear function, F(x).
Input Parameters:
. snes - the SNES context
. x - input vector
. ctx - optional user-defined context, as set by SNESSetFunction()
Output Parameter:
. f - function vector
Note:
The user-defined context can contain any application-specific data
needed for the function evaluation (such as various parameters, work
vectors, and grid information). In this program the context is just
a vector containing the right-hand-side of the discretized PDE.
*/
PetscErrorCode FormFunction(SNES snes, Vec x, Vec f, void *ctx)
{
Vec g = (Vec)ctx;
const PetscScalar *xx, *gg;
PetscScalar *ff, d;
PetscInt i, n;
PetscFunctionBeginUser;
/*
Get pointers to vector data.
- For default PETSc vectors, VecGetArray() returns a pointer to
the data array. Otherwise, the routine is implementation dependent.
- You MUST call VecRestoreArray() when you no longer need access to
the array.
*/
PetscCall(VecGetArrayRead(x, &xx));
PetscCall(VecGetArray(f, &ff));
PetscCall(VecGetArrayRead(g, &gg));
/*
Compute function
*/
PetscCall(VecGetSize(x, &n));
d = (PetscReal)(n - 1);
d = d * d;
ff[0] = xx[0];
for (i = 1; i < n - 1; i++) ff[i] = d * (xx[i - 1] - 2.0 * xx[i] + xx[i + 1]) + xx[i] * xx[i] - gg[i];
ff[n - 1] = xx[n - 1] - 1.0;
/*
Restore vectors
*/
PetscCall(VecRestoreArrayRead(x, &xx));
PetscCall(VecRestoreArray(f, &ff));
PetscCall(VecRestoreArrayRead(g, &gg));
PetscFunctionReturn(PETSC_SUCCESS);
}
/* ------------------------------------------------------------------- */
/*
FormJacobian - Evaluates Jacobian matrix.
Input Parameters:
. snes - the SNES context
. x - input vector
. dummy - optional user-defined context (not used here)
Output Parameters:
. jac - Jacobian matrix
. B - optionally different preconditioning matrix
*/
PetscErrorCode FormJacobian(SNES snes, Vec x, Mat jac, Mat B, void *dummy)
{
const PetscScalar *xx;
PetscScalar A[3], d;
PetscInt i, n, j[3];
PetscFunctionBeginUser;
/*
Get pointer to vector data
*/
PetscCall(VecGetArrayRead(x, &xx));
/*
Compute Jacobian entries and insert into matrix.
- Note that in this case we set all elements for a particular
row at once.
*/
PetscCall(VecGetSize(x, &n));
d = (PetscReal)(n - 1);
d = d * d;
/*
Interior grid points
*/
for (i = 1; i < n - 1; i++) {
j[0] = i - 1;
j[1] = i;
j[2] = i + 1;
A[0] = A[2] = d;
A[1] = -2.0 * d + 2.0 * xx[i];
PetscCall(MatSetValues(B, 1, &i, 3, j, A, INSERT_VALUES));
}
/*
Boundary points
*/
i = 0;
A[0] = 1.0;
PetscCall(MatSetValues(B, 1, &i, 1, &i, A, INSERT_VALUES));
i = n - 1;
A[0] = 1.0;
PetscCall(MatSetValues(B, 1, &i, 1, &i, A, INSERT_VALUES));
/*
Restore vector
*/
PetscCall(VecRestoreArrayRead(x, &xx));
/*
Assemble matrix
*/
PetscCall(MatAssemblyBegin(B, MAT_FINAL_ASSEMBLY));
PetscCall(MatAssemblyEnd(B, MAT_FINAL_ASSEMBLY));
if (jac != B) {
PetscCall(MatAssemblyBegin(jac, MAT_FINAL_ASSEMBLY));
PetscCall(MatAssemblyEnd(jac, MAT_FINAL_ASSEMBLY));
}
PetscFunctionReturn(PETSC_SUCCESS);
}
/* ------------------------------------------------------------------- */
/*
Monitor - User-defined monitoring routine that views the
current iterate with an x-window plot.
Input Parameters:
snes - the SNES context
its - iteration number
norm - 2-norm function value (may be estimated)
ctx - optional user-defined context for private data for the
monitor routine, as set by SNESMonitorSet()
Note:
See the manpage for PetscViewerDrawOpen() for useful runtime options,
such as -nox to deactivate all x-window output.
*/
PetscErrorCode Monitor(SNES snes, PetscInt its, PetscReal fnorm, void *ctx)
{
MonitorCtx *monP = (MonitorCtx *)ctx;
Vec x;
SNESConvergedReason reason;
PetscFunctionBeginUser;
PetscCall(PetscPrintf(PETSC_COMM_WORLD, "iter = %" PetscInt_FMT ", SNES Function norm %g\n", its, (double)fnorm));
PetscCall(SNESGetConvergedReason(snes, &reason));
PetscCall(SNESGetSolution(snes, &x));
PetscCall(VecView(x, monP->viewer));
PetscCall(PetscPrintf(PETSC_COMM_WORLD, " converged = %s\n", SNESConvergedReasons[reason]));
PetscFunctionReturn(PETSC_SUCCESS);
}
/*TEST
test:
args: -nox -snes_monitor_cancel -snes_monitor_short -snes_view -pc_type jacobi -ksp_gmres_cgs_refinement_type refine_always
test:
suffix: 2
args: -nox -snes_monitor_cancel -snes_monitor_short -snes_type newtontr -snes_view
requires: !single
test:
suffix: 3
args: -nox -malloc no -options_left no -snes_monitor_cancel -snes_monitor_short -snes_view -pc_type jacobi -ksp_gmres_cgs_refinement_type refine_always
test:
suffix: 4
args: -nox -snes_monitor_cancel -snes_monitor_short -snes_type newtontrdc -snes_view
requires: !single
test:
suffix: 5
filter: grep -v atol | sed -e "s/CONVERGED_ITS/DIVERGED_MAX_IT/g" | sed -e "s/CONVERGED_FNORM_RELATIVE/DIVERGED_MAX_IT/g"
args: -nox -snes_type {{newtonls newtontr ncg ngmres qn anderson nrichardson ms ksponly ksptransposeonly vinewtonrsls vinewtonssls fas ms}} -snes_max_it 1
requires: !single
TEST*/
|
411ef8c27696586420eb344e37069f29026ba97f
|
a0cda7f4000a8ea36d82c7e5e46cc7548f60b3b7
|
/Chapter 08/ch8/tip2/EmbedAppComm/EmbedRN/Pods/Headers/Public/React/RCTViewControllerProtocol.h
|
8835c154efe1342c835f312ee7caba4a741aa60d
|
[
"MIT"
] |
permissive
|
PacktPublishing/React-Native-Cookbook
|
1d7f054c0847c684787cd3b35f3f8d2f1d26309f
|
de4d1d903adcc3c4a4a98bbfa362e670c0d94d59
|
refs/heads/master
| 2023-01-27T16:41:30.416840
| 2023-01-18T09:58:26
| 2023-01-18T09:58:26
| 76,628,573
| 105
| 46
| null | null | null | null |
UTF-8
|
C
| false
| false
| 80
|
h
|
RCTViewControllerProtocol.h
|
../../../../../node_modules/react-native/React/Views/RCTViewControllerProtocol.h
|
8ecf7c3aed3bb1d95e6c4e33c260de8c7f3723de
|
79d343002bb63a44f8ab0dbac0c9f4ec54078c3a
|
/test/standalone/cmakedefine/expected.h
|
d71f070678d4d27dd85261ca096282abe75f4dd2
|
[
"MIT"
] |
permissive
|
ziglang/zig
|
4aa75d8d3bcc9e39bf61d265fd84b7f005623fc5
|
f4c9e19bc3213c2bc7e03d7b06d7129882f39f6c
|
refs/heads/master
| 2023-08-31T13:16:45.980913
| 2023-08-31T05:50:29
| 2023-08-31T05:50:29
| 40,276,274
| 25,560
| 2,399
|
MIT
| 2023-09-14T21:09:50
| 2015-08-06T00:51:28
|
Zig
|
UTF-8
|
C
| false
| false
| 649
|
h
|
expected.h
|
// cmakedefine
// undefined
/* #undef noval */
// 1
#define trueval 1
// undefined
/* #undef falseval */
// undefined
/* #undef zeroval */
// 1
#define oneval 1
// 1
#define tenval 1
// 1
#define stringval 1
// cmakedefine01
// 0
#define boolnoval 0
// 1
#define booltrueval 1
// 0
#define boolfalseval 0
// 0
#define boolzeroval 0
// 1
#define booloneval 1
// 1
#define booltenval 1
// 1
#define boolstringval 1
// @ substition
// no substition
//
// 1
// 1
// 0
// 0
// 0
// 0
// 1
// 1
// 10
// 10
// test
// test
// substition
// removal
//
// 1
// 1
// 0
// 0
// 0
// 0
// 1
// 1
// 10
// 10
// test
// test
|
7810265cdb587f052d9ffbdb68957cd68cf704dc
|
db229415713a206a848429321e19006b212d20d5
|
/simde/arm/neon/subl_high.h
|
d45f4989bea314cf51361173132a8b894b135d27
|
[
"MIT",
"Apache-2.0",
"LicenseRef-scancode-free-unknown"
] |
permissive
|
simd-everywhere/simde
|
66dd029cbd0b3814b0377c72d953f223d38e7e53
|
4d55fc25bcfddc0e2f0c744448557a070dd310c9
|
refs/heads/master
| 2023-09-04T12:55:25.455223
| 2023-08-18T12:46:56
| 2023-08-18T14:53:06
| 86,497,800
| 1,570
| 173
|
MIT
| 2023-09-07T13:41:28
| 2017-03-28T19:14:32
|
C
|
UTF-8
|
C
| false
| false
| 4,068
|
h
|
subl_high.h
|
/* SPDX-License-Identifier: MIT
*
* 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.
*
* Copyright:
* 2021 Décio Luiz Gazzoni Filho <decio@decpp.net>
*/
#if !defined(SIMDE_ARM_NEON_SUBL_HIGH_H)
#define SIMDE_ARM_NEON_SUBL_HIGH_H
#include "sub.h"
#include "movl.h"
#include "movl_high.h"
#include "types.h"
HEDLEY_DIAGNOSTIC_PUSH
SIMDE_DISABLE_UNWANTED_DIAGNOSTICS
SIMDE_BEGIN_DECLS_
SIMDE_FUNCTION_ATTRIBUTES
simde_int16x8_t
simde_vsubl_high_s8(simde_int8x16_t a, simde_int8x16_t b) {
#if defined(SIMDE_ARM_NEON_A64V8_NATIVE)
return vsubl_high_s8(a, b);
#else
return simde_vsubq_s16(simde_vmovl_high_s8(a), simde_vmovl_high_s8(b));
#endif
}
#if defined(SIMDE_ARM_NEON_A64V8_ENABLE_NATIVE_ALIASES)
#undef vsubl_high_s8
#define vsubl_high_s8(a, b) simde_vsubl_high_s8((a), (b))
#endif
SIMDE_FUNCTION_ATTRIBUTES
simde_int32x4_t
simde_vsubl_high_s16(simde_int16x8_t a, simde_int16x8_t b) {
#if defined(SIMDE_ARM_NEON_A64V8_NATIVE)
return vsubl_high_s16(a, b);
#else
return simde_vsubq_s32(simde_vmovl_high_s16(a), simde_vmovl_high_s16(b));
#endif
}
#if defined(SIMDE_ARM_NEON_A64V8_ENABLE_NATIVE_ALIASES)
#undef vsubl_high_s16
#define vsubl_high_s16(a, b) simde_vsubl_high_s16((a), (b))
#endif
SIMDE_FUNCTION_ATTRIBUTES
simde_int64x2_t
simde_vsubl_high_s32(simde_int32x4_t a, simde_int32x4_t b) {
#if defined(SIMDE_ARM_NEON_A64V8_NATIVE)
return vsubl_high_s32(a, b);
#else
return simde_vsubq_s64(simde_vmovl_high_s32(a), simde_vmovl_high_s32(b));
#endif
}
#if defined(SIMDE_ARM_NEON_A64V8_ENABLE_NATIVE_ALIASES)
#undef vsubl_high_s32
#define vsubl_high_s32(a, b) simde_vsubl_high_s32((a), (b))
#endif
SIMDE_FUNCTION_ATTRIBUTES
simde_uint16x8_t
simde_vsubl_high_u8(simde_uint8x16_t a, simde_uint8x16_t b) {
#if defined(SIMDE_ARM_NEON_A64V8_NATIVE)
return vsubl_high_u8(a, b);
#else
return simde_vsubq_u16(simde_vmovl_high_u8(a), simde_vmovl_high_u8(b));
#endif
}
#if defined(SIMDE_ARM_NEON_A64V8_ENABLE_NATIVE_ALIASES)
#undef vsubl_high_u8
#define vsubl_high_u8(a, b) simde_vsubl_high_u8((a), (b))
#endif
SIMDE_FUNCTION_ATTRIBUTES
simde_uint32x4_t
simde_vsubl_high_u16(simde_uint16x8_t a, simde_uint16x8_t b) {
#if defined(SIMDE_ARM_NEON_A64V8_NATIVE)
return vsubl_high_u16(a, b);
#else
return simde_vsubq_u32(simde_vmovl_high_u16(a), simde_vmovl_high_u16(b));
#endif
}
#if defined(SIMDE_ARM_NEON_A64V8_ENABLE_NATIVE_ALIASES)
#undef vsubl_high_u16
#define vsubl_high_u16(a, b) simde_vsubl_high_u16((a), (b))
#endif
SIMDE_FUNCTION_ATTRIBUTES
simde_uint64x2_t
simde_vsubl_high_u32(simde_uint32x4_t a, simde_uint32x4_t b) {
#if defined(SIMDE_ARM_NEON_A64V8_NATIVE)
return vsubl_high_u32(a, b);
#else
return simde_vsubq_u64(simde_vmovl_high_u32(a), simde_vmovl_high_u32(b));
#endif
}
#if defined(SIMDE_ARM_NEON_A64V8_ENABLE_NATIVE_ALIASES)
#undef vsubl_high_u32
#define vsubl_high_u32(a, b) simde_vsubl_high_u32((a), (b))
#endif
SIMDE_END_DECLS_
HEDLEY_DIAGNOSTIC_POP
#endif /* !defined(SIMDE_ARM_NEON_SUBL_HIGH_H) */
|
fdfc6d541a4db67f17987cb2180f133bb55bea1e
|
9ceacf33fd96913cac7ef15492c126d96cae6911
|
/usr.sbin/mopd/common/pf.c
|
df8766d6818c0400f580be23aecd6879441f4818
|
[
"BSD-2-Clause"
] |
permissive
|
openbsd/src
|
ab97ef834fd2d5a7f6729814665e9782b586c130
|
9e79f3a0ebd11a25b4bff61e900cb6de9e7795e9
|
refs/heads/master
| 2023-09-02T18:54:56.624627
| 2023-09-02T15:16:12
| 2023-09-02T15:16:12
| 66,966,208
| 3,394
| 1,235
| null | 2023-08-08T02:42:25
| 2016-08-30T18:18:25
|
C
|
UTF-8
|
C
| false
| false
| 6,158
|
c
|
pf.c
|
/* $OpenBSD: pf.c,v 1.19 2023/03/08 04:43:13 guenther Exp $ */
/*
* Copyright (c) 1993-95 Mats O Jansson. All rights reserved.
* Copyright (c) 1990 The Regents of the University of California.
* All rights reserved.
*
* This code is partly derived from rarpd.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <sys/types.h>
#include <sys/time.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <sys/uio.h>
#include <net/if.h>
#include <net/bpf.h>
#include <netinet/in.h>
#include <netinet/if_ether.h>
#include <netdb.h>
#include <ctype.h>
#include <string.h>
#include <err.h>
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <syslog.h>
#include <unistd.h>
#include "common/mopdef.h"
/*
* Variables
*/
extern int promisc;
/*
* Return information to device.c how to open device.
* In this case the driver can handle both Ethernet type II and
* IEEE 802.3 frames (SNAP) in a single pfOpen.
*/
int
pfTrans(char *interface)
{
return (TRANS_ETHER + TRANS_8023 + TRANS_AND);
}
/*
* Open and initialize packet filter.
*/
int
pfInit(char *interface, int mode, u_short protocol, int typ)
{
int fd;
struct ifreq ifr;
u_int dlt;
int immediate;
static struct bpf_insn insns[] = {
BPF_STMT(BPF_LD | BPF_H | BPF_ABS, 12),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0x4711, 4, 0),
BPF_STMT(BPF_LD | BPF_H | BPF_ABS, 20),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0x4711, 0, 3),
BPF_STMT(BPF_LD | BPF_H | BPF_ABS, 14),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0xaaaa, 0, 1),
BPF_STMT(BPF_RET | BPF_K, 1520),
BPF_STMT(BPF_RET | BPF_K, 0),
};
static struct bpf_program filter = {
sizeof insns / sizeof(insns[0]),
insns
};
if ((fd = open("/dev/bpf", mode)) == -1) {
syslog(LOG_ERR,"pfInit: open bpf %m");
return (-1);
}
/* Set immediate mode so packets are processed as they arrive. */
immediate = 1;
if (ioctl(fd, BIOCIMMEDIATE, &immediate) < 0) {
syslog(LOG_ERR,"pfInit: BIOCIMMEDIATE: %m");
return (-1);
}
strncpy(ifr.ifr_name, interface, sizeof ifr.ifr_name);
if (ioctl(fd, BIOCSETIF, &ifr) < 0) {
syslog(LOG_ERR,"pfInit: BIOCSETIF: %m");
return (-1);
}
/* Check that the data link layer is an Ethernet; this code won't work
* with anything else. */
if (ioctl(fd, BIOCGDLT, &dlt) < 0) {
syslog(LOG_ERR,"pfInit: BIOCGDLT: %m");
return (-1);
}
if (dlt != DLT_EN10MB) {
syslog(LOG_ERR,"pfInit: %s is not ethernet", interface);
return (-1);
}
if (promisc)
/* Set promiscuous mode. */
if (ioctl(fd, BIOCPROMISC, 0) < 0) {
syslog(LOG_ERR,"pfInit: BIOCPROMISC: %m");
return (-1);
}
/* Set filter program. */
insns[1].k = protocol;
insns[3].k = protocol;
if (ioctl(fd, BIOCSETF, &filter) < 0) {
syslog(LOG_ERR,"pfInit: BIOCSETF: %m");
return (-1);
}
/* XXX set the same write filter (for protocol only) */
if (ioctl(fd, BIOCSETWF, &filter) < 0) {
syslog(LOG_ERR,"pfInit: BIOCSETWF: %m");
return (-1);
}
/* Lock the interface to prevent further changes */
if (ioctl(fd, BIOCLOCK) < 0) {
syslog(LOG_ERR,"pfInit: BIOCLOCK: %m");
return (-1);
}
return (fd);
}
/*
* Add a Multicast address to the interface
*/
int
pfAddMulti(int s, char *interface, char *addr)
{
struct ifreq ifr;
int fd;
strncpy(ifr.ifr_name, interface, sizeof(ifr.ifr_name) - 1);
ifr.ifr_name[sizeof(ifr.ifr_name) - 1] = 0;
ifr.ifr_addr.sa_family = AF_UNSPEC;
bcopy(addr, ifr.ifr_addr.sa_data, 6);
/*
* open a socket, temporarily, to use for SIOC* ioctls
*/
if ((fd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
syslog(LOG_ERR, "pfAddMulti: socket: %m");
return (-1);
}
if (ioctl(fd, SIOCADDMULTI, &ifr) < 0) {
syslog(LOG_ERR, "pfAddMulti: SIOCADDMULTI: %m");
close(fd);
return (-1);
}
close(fd);
return (0);
}
/*
* Delete a Multicast address from the interface
*/
int
pfDelMulti(int s, char *interface, char *addr)
{
struct ifreq ifr;
int fd;
strncpy(ifr.ifr_name, interface, sizeof (ifr.ifr_name) - 1);
ifr.ifr_name[sizeof(ifr.ifr_name)-1] = 0;
ifr.ifr_addr.sa_family = AF_UNSPEC;
bcopy(addr, ifr.ifr_addr.sa_data, 6);
/*
* open a socket, temporarily, to use for SIOC* ioctls
*
*/
if ((fd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
syslog(LOG_ERR, "pfDelMulti: socket: %m");
return (-1);
}
if (ioctl(fd, SIOCDELMULTI, &ifr) < 0) {
syslog(LOG_ERR, "pfAddMulti: SIOCDELMULTI: %m");
close(fd);
return (-1);
}
close(fd);
return (0);
}
/*
* read a packet
*/
int
pfRead(int fd, u_char *buf, int len)
{
return (read(fd, buf, len));
}
/*
* write a packet
*/
int
pfWrite(int fd, u_char *buf, int len, int trans)
{
struct iovec iov[2];
/* XXX */
switch (trans) {
case TRANS_8023:
iov[0].iov_base = buf;
iov[0].iov_len = 22;
iov[1].iov_base = buf + 22;
iov[1].iov_len = len - 22;
break;
default:
iov[0].iov_base = buf;
iov[0].iov_len = 14;
iov[1].iov_base = buf + 14;
iov[1].iov_len = len - 14;
break;
}
if (writev(fd, iov, 2) == len)
return (len);
return (-1);
}
|
39535d225b91ef8579fe8766e93ef4b91497e45a
|
060bc5ba9a8f707bdac927f30842febf9a4676a1
|
/sys/mips/include/trap.h
|
70270f9a04d0cc3a0d3b95a5644a738cbf477e5e
|
[
"BSD-4-Clause-UC",
"LicenseRef-scancode-other-permissive"
] |
permissive
|
sergev/LiteBSD
|
14ae93caa709d4707c3b122c243641c8214583c3
|
6f89c18880065a83d3d18661c80f72fb3397a888
|
refs/heads/master
| 2023-01-10T02:20:05.357875
| 2022-07-19T16:41:32
| 2022-07-19T16:41:32
| 19,167,171
| 318
| 58
|
NOASSERTION
| 2022-12-28T16:23:01
| 2014-04-26T02:55:34
|
C
|
UTF-8
|
C
| false
| false
| 2,209
|
h
|
trap.h
|
/*
* MIPS exception codes.
*
* Copyright (c) 2014 Serge Vakulenko
*
* Permission to use, copy, modify, and distribute this software
* and its documentation for any purpose and without fee is hereby
* granted, provided that the above copyright notice appear in all
* copies and that both that the copyright notice and this
* permission notice and warranty disclaimer appear in supporting
* documentation, and that the name of the author not be used in
* advertising or publicity pertaining to distribution of the
* software without specific, written prior permission.
*
* The author disclaim 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, 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.
*/
/*
* See MIPS achitecture docs for description of Cause.ExcCode field.
*/
#define TRAP_Int 0 /* Interrupt */
#define TRAP_MOD 1 /* TLB modified */
#define TRAP_TLBL 2 /* TLB refill (load or fetch) */
#define TRAP_TLBS 3 /* TLB refill (store) */
#define TRAP_AdEL 4 /* Address error (load or fetch) */
#define TRAP_AdES 5 /* Address error (store) */
#define TRAP_IBE 6 /* Bus error (instruction fetch) */
#define TRAP_DBE 7 /* Bus error (data load or store) */
#define TRAP_Sys 8 /* Syscall */
#define TRAP_Bp 9 /* Breakpoint */
#define TRAP_RI 10 /* Reserved instruction */
#define TRAP_CPU 11 /* Coprocessor Unusable */
#define TRAP_Ov 12 /* Arithmetic Overflow */
#define TRAP_Tr 13 /* Trap */
#define TRAP_TLBRI 19 /* TLB read-inhibit */
#define TRAP_TLBEI 20 /* TLB execute-inhibit */
#define TRAP_WATCH 23 /* Reference to WatchHi/WatchLo address */
#define TRAP_MCheck 24 /* Machine check */
#define TRAP_DSPDis 26 /* DSP disabled */
#define TRAP_USER 0x20 /* user-mode flag or'ed with type */
|
8f03c591a2ad56c516ae814405124f79c78f08a1
|
3b1223e5259c580cbf107d1f45960d9f08aff27f
|
/tools/ltools/group.c
|
374a5200d28111c47c6c07f588540881b4c52a79
|
[] |
no_license
|
osfree-project/osfree
|
6be0fe3e2fb5ef577650b7a3a9eee1f38fb2eb8b
|
04ba405e346948ef0ae1a1b483aeb76f044c50a0
|
refs/heads/master
| 2023-09-02T21:38:29.849765
| 2023-08-30T05:21:33
| 2023-08-30T05:21:33
| 122,781,887
| 105
| 11
| null | 2023-01-24T08:36:57
| 2018-02-24T21:36:31
|
C
|
UTF-8
|
C
| false
| false
| 5,220
|
c
|
group.c
|
/* LTOOLS
Programs to read, write, delete and change Linux extended 2 filesystems under DOS
Module group.c
This file contains routines for handling the ext2 groups
Copyright information and copying policy see file README.TXT
History see file MAIN.C
*/
#include <stdio.h>
#include <stdlib.h>
#include "ext2.h"
#include "proto.h"
#include "ldir.h"
extern int isDebug;
extern int DebugOut(int level, const char *fmt,...);
extern void *MALLOC(size_t size);
extern void FREE(void *block);
/*
* Group Global Variables
*/
group_desc *gt;
int num_groups;
extern super_block sb;
extern unsigned short BLOCK_SIZE;
#ifdef UNIX
#define STDOUT stdout
#define STDERR stdout
#else
extern FILE *STDOUT, *STDERR;
#endif
extern super_block sb;
/* load_groups
* Load the group descriptors into memory and set some
* global variables.
*
* returns -1 for failure
* 1 for success
*/
int load_groups(void)
{
unsigned long lba, size;
unsigned short offset;
#ifdef UNIX
int i;
#endif
DebugOut(16,"------------------Executing 'load_groups'---------------------\n");
/* How many groups are there? */
/* Funky math insures integer divide will round up */
if (sb.s_blocks_per_group == 0)
return -1; /* error checking */
num_groups = (sb.s_blocks_count - sb.s_first_data_block +
sb.s_blocks_per_group - 1) / sb.s_blocks_per_group;
size = sizeof(group_desc) * num_groups;
if (BLOCK_SIZE==1024)
{ lba=(2 * BLOCK_SIZE / DISK_BLOCK_SIZE);
offset=0;
} else
{ lba=BLOCK_SIZE / DISK_BLOCK_SIZE;
offset=0;
}
if ((gt = (group_desc *) MALLOC(size)) == NULL)
{
fprintf(STDERR, "Memory problem in load_groups.\n");
return (-1); /* Memory problem, signal failure */
}
if (readdisk((byte *) gt, lba, offset, size) != size)
{ fprintf(STDERR, "Disk problem in load_groups.\n");
return (-1); /* Disk problem, signal failure */
}
#ifdef UNIX
/* fix byteorder: */
for (i = 0; i < num_groups; i++)
{
gt[i].bg_block_bitmap = le32_to_cpu(gt[i].bg_block_bitmap);
gt[i].bg_inode_bitmap = le32_to_cpu(gt[i].bg_inode_bitmap);
gt[i].bg_inode_table = le32_to_cpu(gt[i].bg_inode_table);
gt[i].bg_free_blocks_count = le16_to_cpu(gt[i].bg_free_blocks_count);
gt[i].bg_free_inodes_count = le16_to_cpu(gt[i].bg_free_inodes_count);
gt[i].bg_used_dirs_count = le16_to_cpu(gt[i].bg_used_dirs_count);
}
#endif
return (1); /* Otherwise everything is OK */
}
void store_groups(void)
{
unsigned long lba, size;
unsigned short offset;
#ifdef UNIX
group_desc *gx;
long i;
#endif
DebugOut(16,"------------------Executing 'store_groups'---------------------\n");
/* How many groups are there? */
/* Funky math insures integer divide will round up */
if (sb.s_blocks_per_group == 0)
exit(-1); /* error checking */
num_groups = (sb.s_blocks_count - sb.s_first_data_block +
sb.s_blocks_per_group - 1) / sb.s_blocks_per_group;
size = sizeof(group_desc) * num_groups;
if (BLOCK_SIZE==1024)
{ lba=(2 * BLOCK_SIZE / DISK_BLOCK_SIZE);
offset=0;
} else
{ lba=BLOCK_SIZE / DISK_BLOCK_SIZE;
offset=0;
}
//printf("store_groups: lba=%lu offset=%u size=%lu\n",lba,offset,size);
#ifdef UNIX
/* fix byteorder: */
if ((gx = MALLOC (size)) == NULL)
{
fprintf (STDERR, "Memory problem in store_groups.\n");
exit (-1); /* Memory problem, signal failure */
}
for (i = 0; i < num_groups; i++)
{
gx[i].bg_block_bitmap = cpu_to_le32(gt[i].bg_block_bitmap);
gx[i].bg_inode_bitmap = cpu_to_le32(gt[i].bg_inode_bitmap);
gx[i].bg_inode_table = cpu_to_le32(gt[i].bg_inode_table);
gx[i].bg_free_blocks_count = cpu_to_le16(gt[i].bg_free_blocks_count);
gx[i].bg_free_inodes_count = cpu_to_le16(gt[i].bg_free_inodes_count);
gx[i].bg_used_dirs_count = cpu_to_le16(gt[i].bg_used_dirs_count);
}
if (writedisk((byte *) gx, lba, offset , size) != size)
#else
if (writedisk((byte *) gt, lba, offset, size) != size)
#endif
{
fprintf(STDERR, "Disk problem in load_groups.\n");
exit(-1); /* Disk problem, signal failure */
}
#ifdef UNIX
FREE(gx);
#endif
}
/* print_groups
* print out group information (useful for debugging)
*/
void print_groups(void)
{
int i;
unsigned long first_block, last_block, first_inode, last_inode;
for (i = 0; i < num_groups; i++)
{
first_block = i * sb.s_blocks_per_group + sb.s_first_data_block;
last_block = (i + 1) * sb.s_blocks_per_group - (1 - sb.s_first_data_block);
first_inode = i * sb.s_inodes_per_group + 1;
last_inode = (i + 1) * sb.s_inodes_per_group;
printf("----------------------------\n");
printf("Group Number: %d Blocks: %ld-%ld Inodes:%ld-%ld\n", i,
first_block, last_block, first_inode, last_inode);
printf("Blocks Bitmap Block: %lu\n", gt[i].bg_block_bitmap);
printf("Inodes Bitmap Block: %lu\n", gt[i].bg_inode_bitmap);
printf("Inodes Table Block: %lu\n", gt[i].bg_inode_table);
printf("Free Blocks: %u\n", gt[i].bg_free_blocks_count);
printf("Free Inodes: %u\n", gt[i].bg_free_inodes_count);
printf("Used Directories: %u\n", gt[i].bg_used_dirs_count);
}
}
|
84c0e11d4a849f583fdfc8d573ec70f89ab0f64b
|
7eaf54a78c9e2117247cb2ab6d3a0c20719ba700
|
/SOFTWARE/A64-TERES/u-boot_new/arch/arm/include/asm/arch-at91/at91sam9g45_matrix.h
|
80e49e343016eef16b53b3fb501db0097a818585
|
[
"GPL-2.0-or-later",
"LicenseRef-scancode-free-unknown",
"Apache-2.0"
] |
permissive
|
OLIMEX/DIY-LAPTOP
|
ae82f4ee79c641d9aee444db9a75f3f6709afa92
|
a3fafd1309135650bab27f5eafc0c32bc3ca74ee
|
refs/heads/rel3
| 2023-08-04T01:54:19.483792
| 2023-04-03T07:18:12
| 2023-04-03T07:18:12
| 80,094,055
| 507
| 92
|
Apache-2.0
| 2023-04-03T07:05:59
| 2017-01-26T07:25:50
|
C
|
UTF-8
|
C
| false
| false
| 3,202
|
h
|
at91sam9g45_matrix.h
|
/*
* Matrix-centric header file for the AT91SAM9M1x family
*
* Copyright (C) 2008 Atmel Corporation.
*
* Memory Controllers (MATRIX, EBI) - System peripherals registers.
* Based on AT91SAM9G45 preliminary datasheet.
*
* SPDX-License-Identifier: GPL-2.0+
*/
#ifndef AT91SAM9G45_MATRIX_H
#define AT91SAM9G45_MATRIX_H
#ifndef __ASSEMBLY__
struct at91_matrix {
u32 mcfg[16];
u32 scfg[16];
u32 pras[16][2];
u32 mrcr; /* 0x100 Master Remap Control */
u32 filler[3];
u32 tcmr;
u32 filler2;
u32 ddrmpr;
u32 filler3[3];
u32 ebicsa;
u32 filler4[47];
u32 wpmr;
u32 wpsr;
};
#endif /* __ASSEMBLY__ */
#define AT91_MATRIX_ULBT_INFINITE (0 << 0)
#define AT91_MATRIX_ULBT_SINGLE (1 << 0)
#define AT91_MATRIX_ULBT_FOUR (2 << 0)
#define AT91_MATRIX_ULBT_EIGHT (3 << 0)
#define AT91_MATRIX_ULBT_SIXTEEN (4 << 0)
#define AT91_MATRIX_ULBT_THIRTYTWO (5 << 0)
#define AT91_MATRIX_ULBT_SIXTYFOUR (6 << 0)
#define AT91_MATRIX_ULBT_128 (7 << 0)
#define AT91_MATRIX_DEFMSTR_TYPE_NONE (0 << 16)
#define AT91_MATRIX_DEFMSTR_TYPE_LAST (1 << 16)
#define AT91_MATRIX_DEFMSTR_TYPE_FIXED (2 << 16)
#define AT91_MATRIX_FIXED_DEFMSTR_SHIFT 18
#define AT91_MATRIX_M0PR_SHIFT 0
#define AT91_MATRIX_M1PR_SHIFT 4
#define AT91_MATRIX_M2PR_SHIFT 8
#define AT91_MATRIX_M3PR_SHIFT 12
#define AT91_MATRIX_M4PR_SHIFT 16
#define AT91_MATRIX_M5PR_SHIFT 20
#define AT91_MATRIX_M6PR_SHIFT 24
#define AT91_MATRIX_M7PR_SHIFT 28
#define AT91_MATRIX_M8PR_SHIFT 0 /* register B */
#define AT91_MATRIX_M9PR_SHIFT 4 /* register B */
#define AT91_MATRIX_M10PR_SHIFT 8 /* register B */
#define AT91_MATRIX_M11PR_SHIFT 12 /* register B */
#define AT91_MATRIX_RCB0 (1 << 0)
#define AT91_MATRIX_RCB1 (1 << 1)
#define AT91_MATRIX_RCB2 (1 << 2)
#define AT91_MATRIX_RCB3 (1 << 3)
#define AT91_MATRIX_RCB4 (1 << 4)
#define AT91_MATRIX_RCB5 (1 << 5)
#define AT91_MATRIX_RCB6 (1 << 6)
#define AT91_MATRIX_RCB7 (1 << 7)
#define AT91_MATRIX_RCB8 (1 << 8)
#define AT91_MATRIX_RCB9 (1 << 9)
#define AT91_MATRIX_RCB10 (1 << 10)
#define AT91_MATRIX_EBI_CS1A_SMC (0 << 1)
#define AT91_MATRIX_EBI_CS1A_SDRAMC (1 << 1)
#define AT91_MATRIX_EBI_CS3A_SMC (0 << 3)
#define AT91_MATRIX_EBI_CS3A_SMC_SMARTMEDIA (1 << 3)
#define AT91_MATRIX_EBI_CS4A_SMC (0 << 4)
#define AT91_MATRIX_EBI_CS4A_SMC_CF0 (1 << 4)
#define AT91_MATRIX_EBI_CS5A_SMC (0 << 5)
#define AT91_MATRIX_EBI_CS5A_SMC_CF1 (1 << 5)
#define AT91_MATRIX_EBI_DBPU_ON (0 << 8)
#define AT91_MATRIX_EBI_DBPU_OFF (1 << 8)
#define AT91_MATRIX_EBI_VDDIOMSEL_1_8V (0 << 16)
#define AT91_MATRIX_EBI_VDDIOMSEL_3_3V (1 << 16)
#define AT91_MATRIX_EBI_EBI_IOSR_REDUCED (0 << 17)
#define AT91_MATRIX_EBI_EBI_IOSR_NORMAL (1 << 17)
#define AT91_MATRIX_EBI_DDR_IOSR_REDUCED (0 << 18)
#define AT91_MATRIX_EBI_DDR_IOSR_NORMAL (1 << 18)
#endif
|
82c549ada05703a357ece4acb4f6a41eab2f81ea
|
131b6d5381fc3bb4403682135b77f9bce91e79f1
|
/nx/source/runtime/alloc.c
|
ec8821805695c1b3e7d837e20640dac696ff0cf3
|
[
"ISC"
] |
permissive
|
switchbrew/libnx
|
53deb695b9ee6f3981c559125e8fce3bce6852b7
|
4fcdb6eb34b20f1f65eb9791fe513a710a001bea
|
refs/heads/master
| 2023-08-28T17:00:22.025929
| 2023-08-11T04:11:38
| 2023-08-12T14:51:58
| 103,794,142
| 1,286
| 299
|
ISC
| 2023-09-09T12:08:36
| 2017-09-17T01:12:38
|
C
|
UTF-8
|
C
| false
| false
| 374
|
c
|
alloc.c
|
#include "alloc.h"
#include <stdlib.h>
void* __attribute__((weak)) __libnx_alloc(size_t size) {
return malloc(size);
}
void* __attribute__((weak)) __libnx_aligned_alloc(size_t alignment, size_t size) {
size = (size + alignment - 1) &~ (alignment - 1);
return aligned_alloc(alignment, size);
}
void __attribute__((weak)) __libnx_free(void* p) {
free(p);
}
|
a58695491ee127f8d5d5ecafe9abd8138da93b2b
|
aa3befea459382dc5c01c925653d54f435b3fb0f
|
/net/neighbor/neighbor_snapshot.c
|
a35fb5434700a2e22e68065f3cb3db1df5528c70
|
[
"MIT-open-group",
"BSD-3-Clause",
"HPND-sell-variant",
"BSD-4-Clause-UC",
"LicenseRef-scancode-warranty-disclaimer",
"MIT-0",
"LicenseRef-scancode-bsd-atmel",
"LicenseRef-scancode-gary-s-brown",
"LicenseRef-scancode-proprietary-license",
"SunPro",
"MIT",
"LicenseRef-scancode-public-domain-disclaimer",
"LicenseRef-scancode-other-permissive",
"HPND",
"ISC",
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause",
"GPL-1.0-or-later",
"CC-BY-2.0",
"CC-BY-4.0"
] |
permissive
|
apache/nuttx
|
14519a7bff4a87935d94fb8fb2b19edb501c7cec
|
606b6d9310fb25c7d92c6f95bf61737e3c79fa0f
|
refs/heads/master
| 2023-08-25T06:55:45.822534
| 2023-08-23T16:03:31
| 2023-08-24T21:25:47
| 228,103,273
| 407
| 241
|
Apache-2.0
| 2023-09-14T18:26:05
| 2019-12-14T23:27:55
|
C
|
UTF-8
|
C
| false
| false
| 3,139
|
c
|
neighbor_snapshot.c
|
/****************************************************************************
* net/neighbor/neighbor_snapshot.c
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership. The
* ASF licenses this file to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*
****************************************************************************/
/****************************************************************************
* Included Files
****************************************************************************/
#include <nuttx/config.h>
#include <string.h>
#include <debug.h>
#include <nuttx/net/ip.h>
#include "inet/inet.h"
#include "neighbor/neighbor.h"
#ifdef CONFIG_NETLINK_ROUTE
/****************************************************************************
* Public Functions
****************************************************************************/
/****************************************************************************
* Name: neighbor_snapshot
*
* Description:
* Take a snapshot of the current state of the Neighbor table.
*
* Input Parameters:
* snapshot - Location to return the Neighbor table copy
* nentries - The size of the user provided 'dest' in entries, each of
* size sizeof(struct neighbor_entry_s)
*
* Returned Value:
* On success, the number of entries actually copied is returned. Unused
* entries are not returned.
*
* Assumptions
* The network is locked to assure exclusive access to the ARP table
*
****************************************************************************/
unsigned int neighbor_snapshot(FAR struct neighbor_entry_s *snapshot,
unsigned int nentries)
{
unsigned int ncopied;
int i;
/* Copy all non-empty entries in the Neighbor table. */
for (i = 0, ncopied = 0;
nentries > ncopied && i < CONFIG_NET_IPv6_NCONF_ENTRIES;
i++)
{
FAR struct neighbor_entry_s *neighbor = &g_neighbors[i];
/* An unused entry table entry will be nullified. In particularly,
* the Neighbor IP address will be all zero (i.e., the unspecified
* IPv6 address).
*/
if (!net_ipv6addr_cmp(neighbor->ne_ipaddr, g_ipv6_unspecaddr))
{
memcpy(&snapshot[ncopied], neighbor,
sizeof(struct neighbor_entry_s));
ncopied++;
}
}
/* Return the number of entries copied into the user buffer */
return ncopied;
}
#endif /* CONFIG_NETLINK_ROUTE */
|
0042792886ad512fdda6857ce25a976ed58d5761
|
41db6c672362ccafdd28af40ecf7df51ffa90a15
|
/src/heapy/hv_cli_user.c
|
0c449bcb5b8ee2ba4accd788d91704ee89f52001
|
[
"LicenseRef-scancode-warranty-disclaimer",
"MIT"
] |
permissive
|
zhuyifei1999/guppy3
|
e5649a066199a92dc3bf8e77bdd6ffb44e790449
|
1b2db87af36388e43afd6ce5774b869bcc4a9452
|
refs/heads/master
| 2023-06-24T23:03:52.612921
| 2023-06-17T01:18:06
| 2023-06-17T01:54:06
| 202,611,372
| 371
| 24
|
MIT
| 2023-06-17T01:54:09
| 2019-08-15T21:05:15
|
Python
|
UTF-8
|
C
| false
| false
| 2,351
|
c
|
hv_cli_user.c
|
/* Implementation of user defined classifiers. */
PyDoc_STRVAR(hv_cli_user_defined_doc,
"\n"
);
typedef struct {
/* Mimics a tuple */
PyObject_VAR_HEAD
NyObjectClassifierObject *cond_cli;
PyObject *cond_kind;
PyObject *classify;
PyObject *memoized_kind;
NyNodeGraphObject *rg;
NyNodeSetObject *norefer;
PyObject *dict;
} UserObject;
static PyObject *
hv_cli_user_memoized_kind(UserObject * self, PyObject *kind)
{
if (self->memoized_kind != Py_None && kind != Py_None) {
kind = PyObject_CallFunctionObjArgs(self->memoized_kind, kind, 0);
} else {
Py_INCREF(kind);
}
return kind;
}
static PyObject *
hv_cli_user_classify(UserObject * self, PyObject *obj)
{
PyObject *kind;
kind = self->cond_cli->def->classify(self->cond_cli->self, obj);
if (!kind)
return 0;
if (kind != self->cond_kind) {
Py_DECREF(kind);
kind = Py_None;
Py_INCREF(kind);
return kind;
} else {
Py_DECREF(kind);
return PyObject_CallFunctionObjArgs(self->classify, obj, 0);
}
}
static NyObjectClassifierDef hv_cli_user_def = {
0,
sizeof(NyObjectClassifierDef),
"cli_user_defined",
"user defined classifier",
(binaryfunc)hv_cli_user_classify,
(binaryfunc)hv_cli_user_memoized_kind,
};
static PyObject *
hv_cli_user_defined(NyHeapViewObject *self, PyObject *args, PyObject *kwds)
{
static char *kwlist[] = {"cond_cli", "cond_kind", "classify", "memoized_kind", 0};
UserObject *s, tmp;
PyObject *r;
if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!OOO:user_defined", kwlist,
&NyObjectClassifier_Type, &tmp.cond_cli,
&tmp.cond_kind,
&tmp.classify,
&tmp.memoized_kind
))
return 0;
s = NYTUPLELIKE_NEW(UserObject);
if (!s)
return 0;
s->cond_cli = tmp.cond_cli;
Py_INCREF(s->cond_cli);
s->cond_kind = tmp.cond_kind;
Py_INCREF(s->cond_kind);
s->classify = tmp.classify;
Py_INCREF(s->classify);
s->memoized_kind = tmp.memoized_kind;
Py_INCREF(s->memoized_kind);
r = NyObjectClassifier_New((PyObject *)s, &hv_cli_user_def);
Py_DECREF(s);
return r;
}
|
65ce85addcae05ec18aa624e1c82baa2b7ea7798
|
ea71454e71004ddc1f2d5e2e460f5640de07b511
|
/hw/xquartz/darwinEvents.c
|
3438da116213cda2aa611faa69ed82bc9fc671a7
|
[
"LicenseRef-scancode-warranty-disclaimer",
"MIT",
"MIT-open-group",
"BSD-3-Clause",
"LicenseRef-scancode-x11-adobe",
"HPND-sell-variant",
"ICU",
"LicenseRef-scancode-mit-old-style",
"SGI-B-2.0",
"ISC",
"LicenseRef-scancode-xfree86-1.0",
"X11-distribute-modifications-variant",
"LicenseRef-scancode-other-permissive",
"X11",
"HPND"
] |
permissive
|
pelya/xserver-xsdl
|
039b289a5835b57aed609e6368f38ae1519e3672
|
6ea1ce707be8ae1b5260bf7c5e36db568c7431c9
|
refs/heads/xsdl2
| 2021-12-28T16:24:31.176024
| 2016-06-26T19:35:39
| 2016-06-26T19:35:39
| 4,112,984
| 278
| 54
| null | 2016-03-31T18:44:36
| 2012-04-23T12:49:38
|
C
|
UTF-8
|
C
| false
| false
| 20,583
|
c
|
darwinEvents.c
|
/*
Darwin event queue and event handling
Copyright 2007-2008 Apple Inc.
Copyright 2004 Kaleb S. KEITHLEY. All Rights Reserved.
Copyright (c) 2002-2004 Torrey T. Lyons. All Rights Reserved.
This file is based on mieq.c by Keith Packard,
which contains the following copyright:
Copyright 1990, 1998 The Open Group
Permission to use, copy, modify, distribute, and sell this software and its
documentation for any purpose is hereby granted without fee, provided that
the above copyright notice appear in all copies and that both that
copyright notice and this permission notice appear in supporting
documentation.
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
OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Except as contained in this notice, the name of The Open Group shall not be
used in advertising or otherwise to promote the sale, use or other dealings
in this Software without prior written authorization from The Open Group.
*/
#include "sanitizedCarbon.h"
#ifdef HAVE_DIX_CONFIG_H
#include <dix-config.h>
#endif
#include <X11/X.h>
#include <X11/Xmd.h>
#include <X11/Xproto.h>
#include "misc.h"
#include "windowstr.h"
#include "pixmapstr.h"
#include "inputstr.h"
#include "inpututils.h"
#include "eventstr.h"
#include "mi.h"
#include "scrnintstr.h"
#include "mipointer.h"
#include "os.h"
#include "darwin.h"
#include "quartz.h"
#include "quartzKeyboard.h"
#include "quartzRandR.h"
#include "darwinEvents.h"
#include <sys/types.h>
#include <sys/uio.h>
#include <unistd.h>
#include <pthread.h>
#include <errno.h>
#include <time.h>
#include <IOKit/hidsystem/IOLLEvent.h>
/* Fake button press/release for scroll wheel move. */
#define SCROLLWHEELUPFAKE 4
#define SCROLLWHEELDOWNFAKE 5
#define SCROLLWHEELLEFTFAKE 6
#define SCROLLWHEELRIGHTFAKE 7
#include <X11/extensions/applewmconst.h>
#include "applewmExt.h"
/* FIXME: Abstract this better */
extern Bool QuartzModeEventHandler(int screenNum, XQuartzEvent *e, DeviceIntPtr dev);
int darwin_all_modifier_flags = 0; // last known modifier state
int darwin_all_modifier_mask = 0;
int darwin_x11_modifier_mask = 0;
#define FD_ADD_MAX 128
static int fd_add[FD_ADD_MAX];
int fd_add_count = 0;
static pthread_mutex_t fd_add_lock = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t fd_add_ready_cond = PTHREAD_COND_INITIALIZER;
static pthread_t fd_add_tid = NULL;
static InternalEvent* darwinEvents = NULL;
static pthread_mutex_t mieq_lock = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t mieq_ready_cond = PTHREAD_COND_INITIALIZER;
/*** Pthread Magics ***/
static pthread_t create_thread(void *(*func)(void *), void *arg) {
pthread_attr_t attr;
pthread_t tid;
pthread_attr_init (&attr);
pthread_attr_setscope (&attr, PTHREAD_SCOPE_SYSTEM);
pthread_attr_setdetachstate (&attr, PTHREAD_CREATE_DETACHED);
pthread_create (&tid, &attr, func, arg);
pthread_attr_destroy (&attr);
return tid;
}
void darwinEvents_lock(void);
void darwinEvents_lock(void) {
int err;
if((err = pthread_mutex_lock(&mieq_lock))) {
ErrorF("%s:%s:%d: Failed to lock mieq_lock: %d\n",
__FILE__, __FUNCTION__, __LINE__, err);
xorg_backtrace();
}
if(darwinEvents == NULL) {
pthread_cond_wait(&mieq_ready_cond, &mieq_lock);
}
}
void darwinEvents_unlock(void);
void darwinEvents_unlock(void) {
int err;
if((err = pthread_mutex_unlock(&mieq_lock))) {
ErrorF("%s:%s:%d: Failed to unlock mieq_lock: %d\n",
__FILE__, __FUNCTION__, __LINE__, err);
xorg_backtrace();
}
}
/*
* DarwinPressModifierKey
* Press or release the given modifier key (one of NX_MODIFIERKEY_* constants)
*/
static void DarwinPressModifierKey(int pressed, int key) {
int keycode = DarwinModifierNXKeyToNXKeycode(key, 0);
if (keycode == 0) {
ErrorF("DarwinPressModifierKey bad keycode: key=%d\n", key);
return;
}
DarwinSendKeyboardEvents(pressed, keycode);
}
/*
* DarwinUpdateModifiers
* Send events to update the modifier state.
*/
static int darwin_x11_modifier_mask_list[] = {
#ifdef NX_DEVICELCMDKEYMASK
NX_DEVICELCTLKEYMASK, NX_DEVICERCTLKEYMASK,
NX_DEVICELSHIFTKEYMASK, NX_DEVICERSHIFTKEYMASK,
NX_DEVICELCMDKEYMASK, NX_DEVICERCMDKEYMASK,
NX_DEVICELALTKEYMASK, NX_DEVICERALTKEYMASK,
#else
NX_CONTROLMASK, NX_SHIFTMASK, NX_COMMANDMASK, NX_ALTERNATEMASK,
#endif
NX_ALPHASHIFTMASK,
0
};
static int darwin_all_modifier_mask_additions[] = { NX_SECONDARYFNMASK, };
static void DarwinUpdateModifiers(
int pressed, // KeyPress or KeyRelease
int flags ) // modifier flags that have changed
{
int *f;
int key;
/* Capslock is special. This mask is the state of capslock (on/off),
* not the state of the button. Hopefully we can find a better solution.
*/
if(NX_ALPHASHIFTMASK & flags) {
DarwinPressModifierKey(KeyPress, NX_MODIFIERKEY_ALPHALOCK);
DarwinPressModifierKey(KeyRelease, NX_MODIFIERKEY_ALPHALOCK);
}
for(f=darwin_x11_modifier_mask_list; *f; f++)
if(*f & flags && *f != NX_ALPHASHIFTMASK) {
key = DarwinModifierNXMaskToNXKey(*f);
if(key == -1)
ErrorF("DarwinUpdateModifiers: Unsupported NXMask: 0x%x\n", *f);
else
DarwinPressModifierKey(pressed, key);
}
}
/* Generic handler for Xquartz-specifc events. When possible, these should
be moved into their own individual functions and set as handlers using
mieqSetHandler. */
static void DarwinEventHandler(int screenNum, InternalEvent *ie, DeviceIntPtr dev) {
XQuartzEvent *e = &(ie->xquartz_event);
switch(e->subtype) {
case kXquartzControllerNotify:
DEBUG_LOG("kXquartzControllerNotify\n");
AppleWMSendEvent(AppleWMControllerNotify,
AppleWMControllerNotifyMask,
e->data[0],
e->data[1]);
break;
case kXquartzPasteboardNotify:
DEBUG_LOG("kXquartzPasteboardNotify\n");
AppleWMSendEvent(AppleWMPasteboardNotify,
AppleWMPasteboardNotifyMask,
e->data[0],
e->data[1]);
break;
case kXquartzActivate:
DEBUG_LOG("kXquartzActivate\n");
QuartzShow();
AppleWMSendEvent(AppleWMActivationNotify,
AppleWMActivationNotifyMask,
AppleWMIsActive, 0);
break;
case kXquartzDeactivate:
DEBUG_LOG("kXquartzDeactivate\n");
AppleWMSendEvent(AppleWMActivationNotify,
AppleWMActivationNotifyMask,
AppleWMIsInactive, 0);
QuartzHide();
break;
case kXquartzReloadPreferences:
DEBUG_LOG("kXquartzReloadPreferences\n");
AppleWMSendEvent(AppleWMActivationNotify,
AppleWMActivationNotifyMask,
AppleWMReloadPreferences, 0);
break;
case kXquartzToggleFullscreen:
DEBUG_LOG("kXquartzToggleFullscreen\n");
if(XQuartzIsRootless)
ErrorF("Ignoring kXquartzToggleFullscreen because of rootless mode.");
else
QuartzRandRToggleFullscreen();
break;
case kXquartzSetRootless:
DEBUG_LOG("kXquartzSetRootless\n");
if(e->data[0]) {
QuartzRandRSetFakeRootless();
} else {
QuartzRandRSetFakeFullscreen(FALSE);
}
break;
case kXquartzSetRootClip:
QuartzSetRootClip((Bool)e->data[0]);
break;
case kXquartzQuit:
GiveUp(0);
break;
case kXquartzSpaceChanged:
DEBUG_LOG("kXquartzSpaceChanged\n");
QuartzSpaceChanged(e->data[0]);
break;
case kXquartzListenOnOpenFD:
ErrorF("Calling ListenOnOpenFD() for new fd: %d\n", (int)e->data[0]);
ListenOnOpenFD((int)e->data[0], 1);
break;
case kXquartzReloadKeymap:
DarwinKeyboardReloadHandler();
break;
case kXquartzDisplayChanged:
DEBUG_LOG("kXquartzDisplayChanged\n");
QuartzUpdateScreens();
/* Update our RandR info */
QuartzRandRUpdateFakeModes(TRUE);
break;
default:
if(!QuartzModeEventHandler(screenNum, e, dev))
ErrorF("Unknown application defined event type %d.\n", e->subtype);
}
}
void DarwinListenOnOpenFD(int fd) {
ErrorF("DarwinListenOnOpenFD: %d\n", fd);
pthread_mutex_lock(&fd_add_lock);
if(fd_add_count < FD_ADD_MAX)
fd_add[fd_add_count++] = fd;
else
ErrorF("FD Addition buffer at max. Dropping fd addition request.\n");
pthread_cond_broadcast(&fd_add_ready_cond);
pthread_mutex_unlock(&fd_add_lock);
}
static void *DarwinProcessFDAdditionQueue_thread(void *args) {
/* TODO: Possibly adjust this to no longer be a race... maybe trigger this
* once a client connects and claims to be the WM.
*
* From ajax:
* There's already an internal callback chain for setting selection [in 1.5]
* ownership. See the CallSelectionCallback at the bottom of
* ProcSetSelectionOwner, and xfixes/select.c for an example of how to hook
* into it.
*/
struct timespec sleep_for;
struct timespec sleep_remaining;
sleep_for.tv_sec = 3;
sleep_for.tv_nsec = 0;
ErrorF("X11.app: DarwinProcessFDAdditionQueue_thread: Sleeping to allow xinitrc to catchup.\n");
while(nanosleep(&sleep_for, &sleep_remaining) != 0) {
sleep_for = sleep_remaining;
}
pthread_mutex_lock(&fd_add_lock);
while(true) {
while(fd_add_count) {
DarwinSendDDXEvent(kXquartzListenOnOpenFD, 1, fd_add[--fd_add_count]);
}
pthread_cond_wait(&fd_add_ready_cond, &fd_add_lock);
}
return NULL;
}
Bool DarwinEQInit(void) {
int *p;
for(p=darwin_x11_modifier_mask_list, darwin_all_modifier_mask=0; *p; p++) {
darwin_x11_modifier_mask |= *p;
}
for(p=darwin_all_modifier_mask_additions, darwin_all_modifier_mask= darwin_x11_modifier_mask; *p; p++) {
darwin_all_modifier_mask |= *p;
}
mieqInit();
mieqSetHandler(ET_XQuartz, DarwinEventHandler);
/* Note that this *could* cause a potential async issue, since we're checking
* darwinEvents without holding the lock, but darwinEvents is only ever set
* here, so I don't bother.
*/
if (!darwinEvents) {
darwinEvents = InitEventList(GetMaximumEventsNum());;
if (!darwinEvents)
FatalError("Couldn't allocate event buffer\n");
darwinEvents_lock();
pthread_cond_broadcast(&mieq_ready_cond);
darwinEvents_unlock();
}
if(!fd_add_tid)
fd_add_tid = create_thread(DarwinProcessFDAdditionQueue_thread, NULL);
return TRUE;
}
void DarwinEQFini(void) {
mieqFini();
}
/*
* ProcessInputEvents
* Read and process events from the event queue until it is empty.
*/
void ProcessInputEvents(void) {
char nullbyte;
int x = sizeof(nullbyte);
mieqProcessInputEvents();
// Empty the signaling pipe
while (x == sizeof(nullbyte)) {
x = read(darwinEventReadFD, &nullbyte, sizeof(nullbyte));
}
}
/* Sends a null byte down darwinEventWriteFD, which will cause the
Dispatch() event loop to check out event queue */
static void DarwinPokeEQ(void) {
char nullbyte=0;
// <daniels> oh, i ... er ... christ.
write(darwinEventWriteFD, &nullbyte, sizeof(nullbyte));
}
/* Convert from Appkit pointer input values to X input values:
* Note: pointer_x and pointer_y are relative to the upper-left of primary
* display.
*/
static void DarwinPrepareValuators(DeviceIntPtr pDev, int *valuators, ScreenPtr screen,
float pointer_x, float pointer_y,
float pressure, float tilt_x, float tilt_y) {
/* Fix offset between darwin and X screens */
pointer_x -= darwinMainScreenX + screen->x;
pointer_y -= darwinMainScreenY + screen->y;
if(pointer_x < 0.0)
pointer_x = 0.0;
if(pointer_y < 0.0)
pointer_y = 0.0;
if(pDev == darwinPointer) {
valuators[0] = pointer_x;
valuators[1] = pointer_y;
valuators[2] = 0;
valuators[3] = 0;
valuators[4] = 0;
} else {
/* Setup our array of values */
valuators[0] = XQUARTZ_VALUATOR_LIMIT * (pointer_x / (float)screenInfo.screens[0]->width);
valuators[1] = XQUARTZ_VALUATOR_LIMIT * (pointer_y / (float)screenInfo.screens[0]->height);
valuators[2] = XQUARTZ_VALUATOR_LIMIT * pressure;
valuators[3] = XQUARTZ_VALUATOR_LIMIT * tilt_x;
valuators[4] = XQUARTZ_VALUATOR_LIMIT * tilt_y;
}
//DEBUG_LOG("Pointer (%f, %f), Valuators: {%d,%d,%d,%d,%d}\n", pointer_x, pointer_y,
// valuators[0], valuators[1], valuators[2], valuators[3], valuators[4]);
}
void DarwinInputReleaseButtonsAndKeys(DeviceIntPtr pDev) {
darwinEvents_lock(); {
int i;
if (pDev->button) {
for (i = 0; i < pDev->button->numButtons; i++) {
if (BitIsOn(pDev->button->down, i)) {
QueuePointerEvents(pDev, ButtonRelease, i, POINTER_ABSOLUTE, NULL);
}
}
}
if (pDev->key) {
for (i = 0; i < NUM_KEYCODES; i++) {
if (BitIsOn(pDev->key->down, i + MIN_KEYCODE)) {
QueueKeyboardEvents(pDev, KeyRelease, i + MIN_KEYCODE, NULL);
}
}
}
DarwinPokeEQ();
} darwinEvents_unlock();
}
void DarwinSendPointerEvents(DeviceIntPtr pDev, int ev_type, int ev_button, float pointer_x, float pointer_y,
float pressure, float tilt_x, float tilt_y) {
static int darwinFakeMouseButtonDown = 0;
ScreenPtr screen;
int valuators[5];
//DEBUG_LOG("x=%f, y=%f, p=%f, tx=%f, ty=%f\n", pointer_x, pointer_y, pressure, tilt_x, tilt_y);
if(!darwinEvents) {
DEBUG_LOG("DarwinSendPointerEvents called before darwinEvents was initialized\n");
return;
}
screen = miPointerGetScreen(pDev);
if(!screen) {
DEBUG_LOG("DarwinSendPointerEvents called before screen was initialized\n");
return;
}
/* Handle fake click */
if (ev_type == ButtonPress && darwinFakeButtons && ev_button == 1) {
if(darwinFakeMouseButtonDown != 0) {
/* We're currently "down" with another button, so release it first */
DarwinSendPointerEvents(pDev, ButtonRelease, darwinFakeMouseButtonDown, pointer_x, pointer_y, pressure, tilt_x, tilt_y);
darwinFakeMouseButtonDown=0;
}
if (darwin_all_modifier_flags & darwinFakeMouse2Mask) {
ev_button = 2;
darwinFakeMouseButtonDown = 2;
DarwinUpdateModKeys(darwin_all_modifier_flags & ~darwinFakeMouse2Mask);
} else if (darwin_all_modifier_flags & darwinFakeMouse3Mask) {
ev_button = 3;
darwinFakeMouseButtonDown = 3;
DarwinUpdateModKeys(darwin_all_modifier_flags & ~darwinFakeMouse3Mask);
}
}
if (ev_type == ButtonRelease && ev_button == 1) {
if(darwinFakeMouseButtonDown) {
ev_button = darwinFakeMouseButtonDown;
}
if(darwinFakeMouseButtonDown == 2) {
DarwinUpdateModKeys(darwin_all_modifier_flags & ~darwinFakeMouse2Mask);
} else if(darwinFakeMouseButtonDown == 3) {
DarwinUpdateModKeys(darwin_all_modifier_flags & ~darwinFakeMouse3Mask);
}
darwinFakeMouseButtonDown = 0;
}
DarwinPrepareValuators(pDev, valuators, screen, pointer_x, pointer_y, pressure, tilt_x, tilt_y);
darwinEvents_lock(); {
ValuatorMask mask;
valuator_mask_set_range(&mask, 0, (pDev == darwinPointer) ? 2 : 5, valuators);
QueuePointerEvents(pDev, ev_type, ev_button, POINTER_ABSOLUTE, &mask);
DarwinPokeEQ();
} darwinEvents_unlock();
}
void DarwinSendKeyboardEvents(int ev_type, int keycode) {
if(!darwinEvents) {
DEBUG_LOG("DarwinSendKeyboardEvents called before darwinEvents was initialized\n");
return;
}
darwinEvents_lock(); {
QueueKeyboardEvents(darwinKeyboard, ev_type, keycode + MIN_KEYCODE, NULL);
DarwinPokeEQ();
} darwinEvents_unlock();
}
void DarwinSendProximityEvents(DeviceIntPtr pDev, int ev_type, float pointer_x, float pointer_y,
float pressure, float tilt_x, float tilt_y) {
ScreenPtr screen;
int valuators[5];
DEBUG_LOG("DarwinSendProximityEvents: %d l:%f,%f p:%f t:%f,%f\n", ev_type, pointer_x, pointer_y, pressure, tilt_x, tilt_y);
if(!darwinEvents) {
DEBUG_LOG("DarwinSendProximityEvents called before darwinEvents was initialized\n");
return;
}
screen = miPointerGetScreen(pDev);
if(!screen) {
DEBUG_LOG("DarwinSendPointerEvents called before screen was initialized\n");
return;
}
DarwinPrepareValuators(pDev, valuators, screen, pointer_x, pointer_y, pressure, tilt_x, tilt_y);
darwinEvents_lock(); {
ValuatorMask mask;
valuator_mask_set_range(&mask, 0, 5, valuators);
QueueProximityEvents(pDev, ev_type, &mask);
DarwinPokeEQ();
} darwinEvents_unlock();
}
/* Send the appropriate number of button clicks to emulate scroll wheel */
void DarwinSendScrollEvents(float count_x, float count_y,
float pointer_x, float pointer_y,
float pressure, float tilt_x, float tilt_y) {
int sign_x, sign_y;
if(!darwinEvents) {
DEBUG_LOG("DarwinSendScrollEvents called before darwinEvents was initialized\n");
return;
}
sign_x = count_x > 0.0f ? SCROLLWHEELLEFTFAKE : SCROLLWHEELRIGHTFAKE;
sign_y = count_y > 0.0f ? SCROLLWHEELUPFAKE : SCROLLWHEELDOWNFAKE;
count_x = fabs(count_x);
count_y = fabs(count_y);
while ((count_x > 0.0f) || (count_y > 0.0f)) {
if (count_x > 0.0f) {
DarwinSendPointerEvents(darwinPointer, ButtonPress, sign_x, pointer_x, pointer_y, pressure, tilt_x, tilt_y);
DarwinSendPointerEvents(darwinPointer, ButtonRelease, sign_x, pointer_x, pointer_y, pressure, tilt_x, tilt_y);
count_x = count_x - 1.0f;
}
if (count_y > 0.0f) {
DarwinSendPointerEvents(darwinPointer, ButtonPress, sign_y, pointer_x, pointer_y, pressure, tilt_x, tilt_y);
DarwinSendPointerEvents(darwinPointer, ButtonRelease, sign_y, pointer_x, pointer_y, pressure, tilt_x, tilt_y);
count_y = count_y - 1.0f;
}
}
}
/* Send the appropriate KeyPress/KeyRelease events to GetKeyboardEvents to
reflect changing modifier flags (alt, control, meta, etc) */
void DarwinUpdateModKeys(int flags) {
DarwinUpdateModifiers(KeyRelease, darwin_all_modifier_flags & ~flags & darwin_x11_modifier_mask);
DarwinUpdateModifiers(KeyPress, ~darwin_all_modifier_flags & flags & darwin_x11_modifier_mask);
darwin_all_modifier_flags = flags;
}
/*
* DarwinSendDDXEvent
* Send the X server thread a message by placing it on the event queue.
*/
void DarwinSendDDXEvent(int type, int argc, ...) {
XQuartzEvent e;
int i;
va_list args;
memset(&e, 0, sizeof(e));
e.header = ET_Internal;
e.type = ET_XQuartz;
e.length = sizeof(e);
e.time = GetTimeInMillis();
e.subtype = type;
if (argc > 0 && argc < XQUARTZ_EVENT_MAXARGS) {
va_start (args, argc);
for (i = 0; i < argc; i++)
e.data[i] = (uint32_t) va_arg (args, uint32_t);
va_end (args);
}
darwinEvents_lock(); {
mieqEnqueue(NULL, (InternalEvent*)&e);
DarwinPokeEQ();
} darwinEvents_unlock();
}
|
92c08a1b0f867bf5c46ac2961bf7dfdef1cbf070
|
f367e4b66a1ee42e85830b31df88f63723c36a47
|
/plugins/out_influxdb/influxdb_bulk.c
|
2542ee3c428bdbf0d6d1148346ea357d530650a5
|
[
"Apache-2.0"
] |
permissive
|
fluent/fluent-bit
|
06873e441162b92941024e9a7e9e8fc934150bf7
|
1a41f49dc2f3ae31a780caa9ffd6137b1d703065
|
refs/heads/master
| 2023-09-05T13:44:55.347372
| 2023-09-05T10:14:33
| 2023-09-05T10:14:33
| 29,933,948
| 4,907
| 1,565
|
Apache-2.0
| 2023-09-14T10:17:02
| 2015-01-27T20:41:52
|
C
|
UTF-8
|
C
| false
| false
| 5,760
|
c
|
influxdb_bulk.c
|
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/* Fluent Bit
* ==========
* Copyright (C) 2015-2022 The Fluent Bit Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <fluent-bit.h>
#include "influxdb.h"
#include "influxdb_bulk.h"
static const uint64_t ONE_BILLION = 1000000000;
static int influxdb_escape(char *out, const char *str, int size, bool quote) {
int out_size = 0;
int i;
for (i = 0; i < size; ++i) {
char ch = str[i];
if (quote ? (ch == '"' || ch == '\\') : (isspace(ch) || ch == ',' || ch == '=')) {
out[out_size++] = '\\';
} else if (ch == '\\') {
out[out_size++] = '\\';
}
out[out_size++] = ch;
}
return out_size;
}
static int influxdb_bulk_buffer(struct influxdb_bulk *bulk, int required)
{
int new_size;
int available;
char *ptr;
available = (bulk->size - bulk->len);
if (available < required) {
new_size = bulk->size + available + required + INFLUXDB_BULK_CHUNK;
ptr = flb_realloc(bulk->ptr, new_size);
if (!ptr) {
flb_errno();
return -1;
}
bulk->ptr = ptr;
bulk->size = new_size;
}
return 0;
}
struct influxdb_bulk *influxdb_bulk_create()
{
struct influxdb_bulk *b;
b = flb_malloc(sizeof(struct influxdb_bulk));
if (!b) {
perror("calloc");
return NULL;
}
b->ptr = flb_malloc(INFLUXDB_BULK_CHUNK);
if (!b->ptr) {
perror("malloc");
flb_free(b);
return NULL;
}
b->size = INFLUXDB_BULK_CHUNK;
b->len = 0;
return b;
}
void influxdb_bulk_destroy(struct influxdb_bulk *bulk)
{
if (bulk->size > 0) {
flb_free(bulk->ptr);
}
flb_free(bulk);
}
int influxdb_bulk_append_header(struct influxdb_bulk *bulk,
const char *tag, int tag_len,
uint64_t seq_n, const char *seq, int seq_len)
{
int ret;
int required;
required = tag_len + 1 + seq_len + 1 + 32;
/* Make sure we have enough space */
ret = influxdb_bulk_buffer(bulk, required);
if (ret != 0) {
return -1;
}
/* Tag, sequence and final space */
memcpy(bulk->ptr + bulk->len, tag, tag_len);
bulk->len += tag_len;
if (seq_len != 0) {
bulk->ptr[bulk->len] = ',';
bulk->len++;
/* Sequence number */
memcpy(bulk->ptr + bulk->len, seq, seq_len);
bulk->len += seq_len;
bulk->ptr[bulk->len] = '=';
bulk->len++;
ret = snprintf(bulk->ptr + bulk->len, 32, "%" PRIu64, seq_n);
bulk->len += ret;
}
/* Add a NULL byte for debugging purposes */
bulk->ptr[bulk->len] = '\0';
return 0;
}
int influxdb_bulk_append_kv(struct influxdb_bulk *bulk,
const char *key, int k_len,
const char *val, int v_len,
int quote)
{
int ret;
int required;
/* Reserve double space for keys and values in case of escaping */
required = k_len * 2 + 1 + v_len * 2 + 1 + 1;
if (quote) {
required += 2;
}
/* Make sure we have enough space */
ret = influxdb_bulk_buffer(bulk, required);
if (ret != 0) {
return -1;
}
if (bulk->len > 0) {
bulk->ptr[bulk->len] = ',';
bulk->len++;
}
/* key */
bulk->len += influxdb_escape(bulk->ptr + bulk->len, key, k_len, false);
/* separator */
bulk->ptr[bulk->len] = '=';
bulk->len++;
/* value */
if (quote) {
bulk->ptr[bulk->len] = '"';
bulk->len++;
}
bulk->len += influxdb_escape(bulk->ptr + bulk->len, val, v_len, quote);
if (quote) {
bulk->ptr[bulk->len] = '"';
bulk->len++;
}
/* Add a NULL byte for debugging purposes */
bulk->ptr[bulk->len] = '\0';
return 0;
};
int influxdb_bulk_append_timestamp(struct influxdb_bulk *bulk,
struct flb_time *t)
{
int ret;
int len;
uint64_t timestamp;
/* Make sure we have enough space */
ret = influxdb_bulk_buffer(bulk, 128);
if (ret != 0) {
return -1;
}
/* Timestamp is in Nanoseconds */
timestamp = (t->tm.tv_sec * ONE_BILLION) + t->tm.tv_nsec;
len = snprintf(bulk->ptr + bulk->len, 127, " %" PRIu64, timestamp);
if (len == -1) {
return -1;
}
bulk->len += len;
bulk->ptr[bulk->len] = '\0';
return 0;
};
int influxdb_bulk_append_bulk(struct influxdb_bulk *bulk_to,
struct influxdb_bulk *bulk_from,
char separator)
{
if (influxdb_bulk_buffer(bulk_to, bulk_from->len + 2) != 0) {
return -1;
}
if (bulk_to->len > 0) {
bulk_to->ptr[bulk_to->len] = separator;
bulk_to->len += 1;
}
memcpy(bulk_to->ptr + bulk_to->len,
bulk_from->ptr, bulk_from->len * sizeof(char));
bulk_to->len += bulk_from->len;
/* Add a NULL byte for always terminating with NULL */
bulk_to->ptr[bulk_to->len] = '\0';
return 0;
};
|
ece2a2f5642ab2ace01f19df6a8d5a3f16cd311a
|
f367e4b66a1ee42e85830b31df88f63723c36a47
|
/src/aws/flb_aws_credentials_log.h
|
6e9f0806dee81958382802a80b583569a5cab364
|
[
"Apache-2.0"
] |
permissive
|
fluent/fluent-bit
|
06873e441162b92941024e9a7e9e8fc934150bf7
|
1a41f49dc2f3ae31a780caa9ffd6137b1d703065
|
refs/heads/master
| 2023-09-05T13:44:55.347372
| 2023-09-05T10:14:33
| 2023-09-05T10:14:33
| 29,933,948
| 4,907
| 1,565
|
Apache-2.0
| 2023-09-14T10:17:02
| 2015-01-27T20:41:52
|
C
|
UTF-8
|
C
| false
| false
| 1,350
|
h
|
flb_aws_credentials_log.h
|
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/* Fluent Bit
* ==========
* Copyright (C) 2021 The Fluent Bit Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef FLB_AWS_CREDENTIALS_LOG_H
#define FLB_AWS_CREDENTIALS_LOG_H
#include <fluent-bit/flb_log.h>
#define AWS_CREDS_ERROR(format, ...) flb_error("[aws_credentials] " format, ##__VA_ARGS__)
#define AWS_CREDS_WARN(format, ...) flb_warn("[aws_credentials] " format, ##__VA_ARGS__)
#define AWS_CREDS_DEBUG(format, ...) flb_debug("[aws_credentials] " format, ##__VA_ARGS__)
#define AWS_CREDS_ERROR_OR_DEBUG(debug_only, format, ...) do {\
if (debug_only == FLB_TRUE) {\
AWS_CREDS_DEBUG(format, ##__VA_ARGS__);\
}\
else {\
AWS_CREDS_ERROR(format, ##__VA_ARGS__);\
}\
} while (0)
#endif
|
0a9f5517db5dca8b0524f5acaaa9b8f110f6f229
|
50dd46b8ece33f3cdd174284b15d1d51f89669d4
|
/2018/beginners/pwn-motd/src/motd.c
|
f9d1e67409f7875d6904bd0807457d4ba35bd830
|
[
"LicenseRef-scancode-generic-cla",
"Apache-2.0"
] |
permissive
|
google/google-ctf
|
f99da1ee07729bbccb869fff1cbaed6a80e43bcc
|
df02323eaf945d15e124801c74abaadca2749dc7
|
refs/heads/master
| 2023-08-31T14:30:27.548081
| 2023-08-29T13:04:20
| 2023-08-29T13:04:20
| 131,317,137
| 4,136
| 607
|
Apache-2.0
| 2023-08-30T22:17:02
| 2018-04-27T15:56:03
|
Go
|
UTF-8
|
C
| false
| false
| 2,552
|
c
|
motd.c
|
/*
Copyright 2018 Google LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MOTD_LEN 256
char MOTD[MOTD_LEN];
char *DEFAULT_MOTD = "MOTD: Welcome back friend!";
void set_motd(){
char buf[MOTD_LEN];
printf("Enter new message of the day\n");
printf("New msg: ");
// Uh oh!
gets(buf);
strncpy(MOTD, buf, MOTD_LEN);
MOTD[MOTD_LEN - 1] = '\0';
printf("New message of the day saved!\n");
return;
}
void get_motd(){
printf(MOTD);
printf("\n");
return;
}
void set_admin_motd(){
printf("TODO: Allow admin MOTD to be set\n");
return;
}
void read_flag();
void get_admin_motd(){
uid_t uid = getuid();
if(uid != 0) {
printf("You're not root!\n");
}
else {
read_flag();
}
return;
}
void print_menu(){
printf("Choose functionality to test:\n");
printf("1 - Get user MOTD\n");
printf("2 - Set user MOTD\n");
printf("3 - Set admin MOTD (TODO)\n");
printf("4 - Get admin MOTD\n");
printf("5 - Exit\n");
}
int main(int argc, char* argv[]){
void *cmd;
char *input;
size_t input_len;
int choice, nitems = 0;
setbuf(stdout, NULL);
setbuf(stderr, NULL);
fflush(stdin);
strcpy(MOTD, DEFAULT_MOTD);
while(choice != 5){
print_menu();
printf("choice: ");
getline(&input, &input_len, stdin);
choice = atoi(input);
if(choice == 0){
printf("Unrecognized input!\n");
continue;
}
else if (choice < 1 || choice > 5){
printf("Not an option!\n");
continue;
}
else {
switch (choice){
case 1:
get_motd();
break;
case 2:
set_motd();
break;
case 3:
set_admin_motd();
break;
case 4:
get_admin_motd();
break;
case 5:
return 0;
}
}
}
}
void read_flag(){
FILE *fd;
char flag[256] = {0};
fd = fopen("./flag.txt", "r");
fscanf(fd,"%s", &flag);
printf("Admin MOTD is: %s\n", flag);
return;
}
|
fc17cef4f54d9e7768f0bc5cc9d5b57685369830
|
89db60818afeb3dc7c3b7abe9ceae155f074f7f2
|
/src/cmd/troff/n3.c
|
1c7c574f62fb49bce7838576435f6eb2e2c8fac2
|
[
"bzip2-1.0.6",
"LPL-1.02",
"MIT"
] |
permissive
|
9fans/plan9port
|
63c3d01928c6f8a8617d3ea6ecc05bac72391132
|
65c090346a38a8c30cb242d345aa71060116340c
|
refs/heads/master
| 2023-08-25T17:14:26.233105
| 2023-08-23T13:21:37
| 2023-08-23T18:47:08
| 26,095,474
| 1,645
| 468
|
NOASSERTION
| 2023-09-05T16:55:41
| 2014-11-02T22:40:13
|
C
|
UTF-8
|
C
| false
| false
| 16,249
|
c
|
n3.c
|
/*
* troff3.c
*
* macro and string routines, storage allocation
*/
#include "tdef.h"
#include "fns.h"
#include "ext.h"
Tchar *argtop;
int pagech = '%';
int strflg;
#define MHASHSIZE 128 /* must be 2**n */
#define MHASH(x) ((x>>6)^x) & (MHASHSIZE-1)
Contab *mhash[MHASHSIZE];
Blockp *blist; /* allocated blocks for macros and strings */
int nblist; /* how many there are */
int bfree = -1; /* first (possible) free block in the list */
Contab *contabp = NULL;
#define MDELTA 500
int nm = 0;
int savname; /* name of macro/string being defined */
int savslot; /* place in Contab of savname */
int freeslot = -1; /* first (possible) free slot in contab */
void prcontab(Contab *p)
{
int i;
for (i = 0; i < nm; i++)
if (p)
if (p[i].rq != 0)
fprintf(stderr, "slot %d, %-2.2s\n", i, unpair(p[i].rq));
else
fprintf(stderr, "slot %d empty\n", i);
else
fprintf(stderr, "slot %d empty\n", i);
}
void blockinit(void)
{
blist = (Blockp *) calloc(NBLIST, sizeof(Blockp));
if (blist == NULL) {
ERROR "not enough room for %d blocks", NBLIST WARN;
done2(1);
}
nblist = NBLIST;
blist[0].nextoff = blist[1].nextoff = -1;
blist[0].bp = (Tchar *) calloc(BLK, sizeof(Tchar));
blist[1].bp = (Tchar *) calloc(BLK, sizeof(Tchar));
/* -1 prevents blist[0] from being used; temporary fix */
/* for a design botch: offset==0 is overloaded. */
/* blist[1] reserved for .rd indicator -- also unused. */
/* but someone unwittingly looks at these, so allocate something */
bfree = 2;
}
char *grow(char *ptr, int num, int size) /* make array bigger */
{
char *p;
if (ptr == NULL)
p = (char *) calloc(num, size);
else
p = (char *) realloc(ptr, num * size);
return p;
}
void mnspace(void)
{
nm = sizeof(contab)/sizeof(Contab) + MDELTA;
freeslot = sizeof(contab)/sizeof(Contab) + 1;
contabp = (Contab *) grow((char *) contabp, nm, sizeof(Contab));
if (contabp == NULL) {
ERROR "not enough memory for namespace of %d marcos", nm WARN;
exit(1);
}
contabp = (Contab *) memcpy((char *) contabp, (char *)contab,
sizeof(contab));
if (contabp == NULL) {
ERROR "Cannot reinitialize macro/request name list" WARN;
exit(1);
}
}
void caseig(void)
{
int i;
Offset oldoff = offset;
offset = 0;
i = copyb();
offset = oldoff;
if (i != '.')
control(i, 1);
}
void casern(void)
{
int i, j, k;
lgf++;
skip();
if ((i = getrq()) == 0 || (oldmn = findmn(i)) < 0)
return;
skip();
clrmn(findmn(j = getrq()));
if (j) {
munhash(&contabp[oldmn]);
contabp[oldmn].rq = j;
maddhash(&contabp[oldmn]);
if (dip != d )
for (k = dilev; k; k--)
if (d[k].curd == i)
d[k].curd = j;
}
}
void maddhash(Contab *rp)
{
Contab **hp;
if (rp->rq == 0)
return;
hp = &mhash[MHASH(rp->rq)];
rp->link = *hp;
*hp = rp;
}
void munhash(Contab *mp)
{
Contab *p;
Contab **lp;
if (mp->rq == 0)
return;
lp = &mhash[MHASH(mp->rq)];
p = *lp;
while (p) {
if (p == mp) {
*lp = p->link;
p->link = 0;
return;
}
lp = &p->link;
p = p->link;
}
}
void mrehash(void)
{
Contab *p;
int i;
for (i=0; i < MHASHSIZE; i++)
mhash[i] = 0;
for (p=contabp; p < &contabp[nm]; p++)
p->link = 0;
for (p=contabp; p < &contabp[nm]; p++) {
if (p->rq == 0)
continue;
i = MHASH(p->rq);
p->link = mhash[i];
mhash[i] = p;
}
}
void caserm(void)
{
int j;
int k = 0;
lgf++;
g0:
while (!skip() && (j = getrq()) != 0) {
if (dip != d)
for (k = dilev; k; k--)
if (d[k].curd == j) {
ERROR "cannot remove diversion %s during definition",
unpair(j) WARN;
goto g0;
}
clrmn(findmn(j));
}
lgf--;
}
void caseas(void)
{
app++;
caseds();
}
void caseds(void)
{
ds++;
casede();
}
void caseam(void)
{
app++;
casede();
}
void casede(void)
{
int i, req;
Offset savoff;
req = '.';
lgf++;
skip();
if ((i = getrq()) == 0)
goto de1;
if ((offset = finds(i)) == 0)
goto de1;
if (newmn)
savslot = newmn;
else
savslot = findmn(i);
savname = i;
if (ds)
copys();
else
req = copyb();
clrmn(oldmn);
if (newmn) {
if (contabp[newmn].rq)
munhash(&contabp[newmn]);
contabp[newmn].rq = i;
maddhash(&contabp[newmn]);
}
if (apptr) {
savoff = offset;
offset = apptr;
wbf((Tchar) IMP);
offset = savoff;
}
offset = dip->op;
if (req != '.')
control(req, 1);
de1:
ds = app = 0;
}
int findmn(int i)
{
Contab *p;
for (p = mhash[MHASH(i)]; p; p = p->link)
if (i == p->rq)
return(p - contabp);
return(-1);
}
void clrmn(int i)
{
if (i >= 0) {
if (contabp[i].mx)
ffree(contabp[i].mx);
munhash(&contabp[i]);
contabp[i].rq = 0;
contabp[i].mx = 0;
contabp[i].emx = 0;
contabp[i].f = 0;
if (contabp[i].divsiz != NULL) {
free(contabp[i].divsiz);
contabp[i].divsiz = NULL;
}
if (freeslot > i)
freeslot = i;
}
}
void growcontab(void)
{
nm += MDELTA;
contabp = (Contab *) grow((char *) contabp , nm, sizeof(Contab));
if (contabp == NULL) {
ERROR "Too many (%d) string/macro names", nm WARN;
done2(02);
} else {
memset((char *)(contabp) + (nm - MDELTA) * sizeof(Contab),
0, MDELTA * sizeof(Contab));
mrehash();
}
}
Offset finds(int mn)
{
int i;
Offset savip;
oldmn = findmn(mn);
newmn = 0;
apptr = 0;
if (app && oldmn >= 0 && contabp[oldmn].mx) {
savip = ip;
ip = contabp[oldmn].emx;
oldmn = -1;
apptr = ip;
if (!diflg)
ip = incoff(ip);
nextb = ip;
ip = savip;
} else {
for (i = freeslot; i < nm; i++) {
if (contabp[i].rq == 0)
break;
}
if (i == nm)
growcontab();
freeslot = i + 1;
if ((nextb = alloc()) == -1) {
app = 0;
if (macerr++ > 1)
done2(02);
if (nextb == 0)
ERROR "Not enough space for string/macro names" WARN;
edone(04);
return(offset = 0);
}
contabp[i].mx = nextb;
if (!diflg) {
newmn = i;
if (oldmn == -1)
contabp[i].rq = -1;
} else {
contabp[i].rq = mn;
maddhash(&contabp[i]);
}
}
app = 0;
return(offset = nextb);
}
int skip(void)
{
Tchar i;
while (cbits(i = getch()) == ' ' || ismot(i))
;
ch = i;
return(nlflg);
}
int copyb(void)
{
int i, j, state;
Tchar ii;
int req, k;
Offset savoff;
Uchar *p;
savoff = 0;
if (skip() || !(j = getrq()))
j = '.';
req = j;
p = unpair(j);
/* was: k = j >> BYTE; j &= BYTEMASK; */
j = p[0];
k = p[1];
copyf++;
flushi();
nlflg = 0;
state = 1;
/* state 0 eat up
* state 1 look for .
* state 2 look for first char of end macro
* state 3 look for second char of end macro
*/
while (1) {
i = cbits(ii = getch());
if (state == 3) {
if (i == k)
break;
if (!k) {
ch = ii;
i = getach();
ch = ii;
if (!i)
break;
}
state = 0;
goto c0;
}
if (i == '\n') {
state = 1;
nlflg = 0;
goto c0;
}
if (state == 1 && i == '.') {
state++;
savoff = offset;
goto c0;
}
if (state == 2 && i == j) {
state++;
goto c0;
}
state = 0;
c0:
if (offset)
wbf(ii);
}
if (offset) {
offset = savoff;
wbf((Tchar)0);
}
copyf--;
return(req);
}
void copys(void)
{
Tchar i;
copyf++;
if (skip())
goto c0;
if (cbits(i = getch()) != '"')
wbf(i);
while (cbits(i = getch()) != '\n')
wbf(i);
c0:
wbf((Tchar)0);
copyf--;
}
Offset alloc(void) /* return free Offset in nextb */
{
int i, j;
for (i = bfree; i < nblist; i++)
if (blist[i].nextoff == 0)
break;
if (i == nblist) {
blist = (Blockp *) realloc((char *) blist, 2 * nblist * sizeof(Blockp));
if (blist == NULL) {
ERROR "can't grow blist for string/macro defns" WARN;
done2(2);
}
nblist *= 2;
for (j = i; j < nblist; j++) {
blist[j].nextoff = 0;
blist[j].bp = 0;
}
}
blist[i].nextoff = -1; /* this block is the end */
bfree = i + 1;
if (blist[i].bp == 0)
blist[i].bp = (Tchar *) calloc(BLK, sizeof(Tchar));
if (blist[i].bp == NULL) {
ERROR "can't allocate memory for string/macro definitions" WARN;
done2(2);
}
nextb = (Offset) i * BLK;
return nextb;
}
void ffree(Offset i) /* free list of blocks starting at blist(o) */
{ /* (doesn't actually free the blocks, just the pointers) */
int j;
for ( ; blist[j = bindex(i)].nextoff != -1; ) {
if (bfree > j)
bfree = j;
i = blist[j].nextoff;
blist[j].nextoff = 0;
}
blist[j].nextoff = 0;
}
void wbf(Tchar i) /* store i into offset, get ready for next one */
{
int j, off;
if (!offset)
return;
j = bindex(offset);
if (i == 0)
contabp[savslot].emx = offset;
off = boffset(offset);
blist[j].bp[off++] = i;
offset++;
if (pastend(offset)) { /* off the end of this block */
if (blist[j].nextoff == -1) {
if ((nextb = alloc()) == -1) {
ERROR "Out of temp file space" WARN;
done2(01);
}
blist[j].nextoff = nextb;
}
offset = blist[j].nextoff;
}
}
Tchar rbf(void) /* return next char from blist[] block */
{
Tchar i, j;
if (ip == RD_OFFSET) { /* for rdtty */
if (j = rdtty())
return(j);
else
return(popi());
}
i = rbf0(ip);
if (i == 0) {
if (!app)
i = popi();
return(i);
}
ip = incoff(ip);
return(i);
}
Offset xxxincoff(Offset p) /* get next blist[] block */
{
p++;
if (pastend(p)) { /* off the end of this block */
if ((p = blist[bindex(p-1)].nextoff) == -1) { /* and nothing was allocated after it */
ERROR "Bad storage allocation" WARN;
done2(-5);
}
}
return(p);
}
Tchar popi(void)
{
Stack *p;
if (frame == stk)
return(0);
if (strflg)
strflg--;
p = nxf = frame;
p->nargs = 0;
frame = p->pframe;
ip = p->pip;
pendt = p->ppendt;
lastpbp = p->lastpbp;
return(p->pch);
}
/*
* test that the end of the allocation is above a certain location
* in memory
*/
#define SPACETEST(base, size) \
if ((char*)base + size >= (char*)stk+STACKSIZE) \
ERROR "Stacksize overflow in n3" WARN
Offset pushi(Offset newip, int mname)
{
Stack *p;
SPACETEST(nxf, sizeof(Stack));
p = nxf;
p->pframe = frame;
p->pip = ip;
p->ppendt = pendt;
p->pch = ch;
p->lastpbp = lastpbp;
p->mname = mname;
lastpbp = pbp;
pendt = ch = 0;
frame = nxf;
if (nxf->nargs == 0)
nxf += 1;
else
nxf = (Stack *)argtop;
return(ip = newip);
}
void *setbrk(int x)
{
char *i;
if ((i = (char *) calloc(x, 1)) == 0) {
ERROR "Core limit reached" WARN;
edone(0100);
}
return(i);
}
int getsn(void)
{
int i;
if ((i = getach()) == 0)
return(0);
if (i == '(')
return(getrq());
else
return(i);
}
Offset setstr(void)
{
int i, j;
lgf++;
if ((i = getsn()) == 0 || (j = findmn(i)) == -1 || !contabp[j].mx) {
lgf--;
return(0);
} else {
SPACETEST(nxf, sizeof(Stack));
nxf->nargs = 0;
strflg++;
lgf--;
return pushi(contabp[j].mx, i);
}
}
void collect(void)
{
int j;
Tchar i, *strp, *lim, **argpp, **argppend;
int quote;
Stack *savnxf;
copyf++;
nxf->nargs = 0;
savnxf = nxf;
if (skip())
goto rtn;
{
char *memp;
memp = (char *)savnxf;
/*
* 1 s structure for the macro descriptor
* APERMAC Tchar *'s for pointers into the strings
* space for the Tchar's themselves
*/
memp += sizeof(Stack);
/*
* CPERMAC = the total # of characters for ALL arguments
*/
#define CPERMAC 200
#define APERMAC 9
memp += APERMAC * sizeof(Tchar *);
memp += CPERMAC * sizeof(Tchar);
nxf = (Stack *)memp;
}
lim = (Tchar *)nxf;
argpp = (Tchar **)(savnxf + 1);
argppend = &argpp[APERMAC];
SPACETEST(argppend, sizeof(Tchar *));
strp = (Tchar *)argppend;
/*
* Zero out all the string pointers before filling them in.
*/
for (j = 0; j < APERMAC; j++)
argpp[j] = 0;
/* ERROR "savnxf=0x%x,nxf=0x%x,argpp=0x%x,strp=argppend=0x%x, lim=0x%x",
* savnxf, nxf, argpp, strp, lim WARN;
*/
strflg = 0;
while (argpp != argppend && !skip()) {
*argpp++ = strp;
quote = 0;
if (cbits(i = getch()) == '"')
quote++;
else
ch = i;
while (1) {
i = getch();
/* fprintf(stderr, "collect %c %d\n", cbits(i), cbits(i)); */
if (nlflg || (!quote && argpp != argppend && cbits(i) == ' '))
break; /* collects rest into $9 */
if ( quote
&& cbits(i) == '"'
&& cbits(i = getch()) != '"') {
ch = i;
break;
}
*strp++ = i;
if (strflg && strp >= lim) {
/* ERROR "strp=0x%x, lim = 0x%x", strp, lim WARN; */
ERROR "Macro argument too long" WARN;
copyf--;
edone(004);
}
SPACETEST(strp, 3 * sizeof(Tchar));
}
*strp++ = 0;
}
nxf = savnxf;
nxf->nargs = argpp - (Tchar **)(savnxf + 1);
argtop = strp;
rtn:
copyf--;
}
void seta(void)
{
int i;
i = cbits(getch()) - '0';
if (i > 0 && i <= APERMAC && i <= frame->nargs)
pushback(*(((Tchar **)(frame + 1)) + i - 1));
}
void caseda(void)
{
app++;
casedi();
}
void casegd(void)
{
int i, j;
skip();
if ((i = getrq()) == 0)
return;
if ((j = findmn(i)) >= 0) {
if (contabp[j].divsiz != NULL) {
numtabp[DN].val = contabp[j].divsiz->dix;
numtabp[DL].val = contabp[j].divsiz->diy;
}
}
}
#define FINDDIV(o) if ((o = findmn(dip->curd)) < 0) \
ERROR "lost diversion %s", unpair(dip->curd) WARN
void casedi(void)
{
int i, j, *k;
lgf++;
if (skip() || (i = getrq()) == 0) {
if (dip != d) {
FINDDIV(savslot);
wbf((Tchar)0);
}
if (dilev > 0) {
numtabp[DN].val = dip->dnl;
numtabp[DL].val = dip->maxl;
FINDDIV(j);
if ((contabp[j].divsiz = (Divsiz *) malloc(sizeof(Divsiz))) == NULL) {
ERROR "Cannot alloc diversion size" WARN;
done2(1);
} else {
contabp[j].divsiz->dix = numtabp[DN].val;
contabp[j].divsiz->diy = numtabp[DL].val;
}
dip = &d[--dilev];
offset = dip->op;
}
goto rtn;
}
if (++dilev == NDI) {
--dilev;
ERROR "Diversions nested too deep" WARN;
edone(02);
}
if (dip != d) {
FINDDIV(j);
savslot = j;
wbf((Tchar)0);
}
diflg++;
dip = &d[dilev];
dip->op = finds(i);
dip->curd = i;
clrmn(oldmn);
k = (int *) & dip->dnl;
for (j = 0; j < 10; j++)
k[j] = 0; /*not op and curd*/
rtn:
app = 0;
diflg = 0;
}
void casedt(void)
{
lgf++;
dip->dimac = dip->ditrap = dip->ditf = 0;
skip();
dip->ditrap = vnumb((int *)0);
if (nonumb)
return;
skip();
dip->dimac = getrq();
}
#define LNSIZE 4000
void casetl(void)
{
int j;
int w[3];
Tchar buf[LNSIZE];
Tchar *tp;
Tchar i, delim;
/*
* bug fix
*
* if .tl is the first thing in the file, the p1
* doesn't come out, also the pagenumber will be 0
*
* tends too confuse the device filter (and the user as well)
*/
if (dip == d && numtabp[NL].val == -1)
newline(1);
dip->nls = 0;
skip();
if (ismot(delim = getch())) {
ch = delim;
delim = '\'';
} else
delim = cbits(delim);
tp = buf;
numtabp[HP].val = 0;
w[0] = w[1] = w[2] = 0;
j = 0;
while (cbits(i = getch()) != '\n') {
if (cbits(i) == cbits(delim)) {
if (j < 3)
w[j] = numtabp[HP].val;
numtabp[HP].val = 0;
if (w[j] != 0)
*tp++ = WORDSP;
j++;
*tp++ = 0;
} else {
if (cbits(i) == pagech) {
setn1(numtabp[PN].val, numtabp[findr('%')].fmt,
i&SFMASK);
continue;
}
numtabp[HP].val += width(i);
if (tp < &buf[LNSIZE-10]) {
if (cbits(i) == ' ' && *tp != WORDSP)
*tp++ = WORDSP;
*tp++ = i;
} else {
ERROR "Overflow in casetl" WARN;
}
}
}
if (j<3)
w[j] = numtabp[HP].val;
*tp++ = 0;
*tp++ = 0;
*tp = 0;
tp = buf;
if (NROFF)
horiz(po);
while (i = *tp++)
pchar(i);
if (w[1] || w[2])
horiz(j = quant((lt - w[1]) / 2 - w[0], HOR));
while (i = *tp++)
pchar(i);
if (w[2]) {
horiz(lt - w[0] - w[1] - w[2] - j);
while (i = *tp++)
pchar(i);
}
newline(0);
if (dip != d) {
if (dip->dnl > dip->hnl)
dip->hnl = dip->dnl;
} else {
if (numtabp[NL].val > dip->hnl)
dip->hnl = numtabp[NL].val;
}
}
void casepc(void)
{
pagech = chget(IMP);
}
void casepm(void)
{
int i, k;
int xx, cnt, tcnt, kk, tot;
Offset j;
kk = cnt = tcnt = 0;
tot = !skip();
stackdump();
for (i = 0; i < nm; i++) {
if ((xx = contabp[i].rq) == 0 || contabp[i].mx == 0)
continue;
tcnt++;
j = contabp[i].mx;
for (k = 1; (j = blist[bindex(j)].nextoff) != -1; )
k++;
cnt++;
kk += k;
if (!tot)
fprintf(stderr, "%-2.2s %d\n", unpair(xx), k);
}
fprintf(stderr, "pm: total %d, macros %d, space %d\n", tcnt, cnt, kk);
}
void stackdump(void) /* dumps stack of macros in process */
{
Stack *p;
if (frame != stk) {
fprintf(stderr, "stack: ");
for (p = frame; p != stk; p = p->pframe)
fprintf(stderr, "%s ", unpair(p->mname));
fprintf(stderr, "\n");
}
}
|
b3ef3b1b44556ac0c22e9009f6189596d7bbe4d2
|
83372fce92c9088ee5c1e1c13bc67385a3b02a36
|
/test/val/div-char-char.c
|
aa86bcd198e05de91959114c6807bc4c767ad44e
|
[
"Zlib",
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-proprietary-license"
] |
permissive
|
cc65/cc65
|
2cd1b20b61ddd0691cd4601b4da37a9200a50afb
|
16e90187e8e80c6e2fcfcc04f068ac865d2290e5
|
refs/heads/master
| 2023-09-03T17:16:46.027934
| 2023-09-02T22:30:44
| 2023-09-02T22:30:44
| 8,932,489
| 2,103
| 526
|
Zlib
| 2023-09-13T06:19:01
| 2013-03-21T15:56:48
|
C
|
UTF-8
|
C
| false
| false
| 1,581
|
c
|
div-char-char.c
|
#include <stdint.h>
#include <stdio.h>
#include "div-common.h"
int res = 0;
/* we check A_8 and B_8 signed */
#define TEST(_n,_a,_b,_r) TEST_AB_8(_n,_a,_b,_r)
#define DO_TEST_A(_n) res += test##_n##a()
#define DO_TEST_B(_n) res += test##_n##b()
/* arbitrary values */
TEST(1, 1, 8, 0)
TEST(2, -1, 8, 0)
TEST(3, 1, -8, 0)
TEST(4, -1, -8, 0)
TEST(5, 8, 1, 8)
TEST(6, -8, 1, -8)
TEST(7, 8, -1, -8)
TEST(8, -8, -1, 8)
TEST(11, 32, 64, 0)
TEST(12, -32, 64, 0)
TEST(13, 32, -64, 0)
TEST(14, -32, -64, 0)
TEST(15, 64, 32, 2)
TEST(16, -64, 32, -2)
TEST(17, 64, -32, -2)
TEST(18, -64, -32, 2)
/* +128 can't be tested for 8-bit signed char */
TEST(101, 127, -128, 0)
TEST(102, -127, -128, 0)
TEST(103, -128, -128, 1)
int main(void)
{
/* check if the result is correct */
DO_TEST_A(1);
DO_TEST_A(2);
DO_TEST_A(3);
DO_TEST_A(4);
DO_TEST_A(5);
DO_TEST_A(6);
DO_TEST_A(7);
DO_TEST_A(8);
DO_TEST_A(11);
DO_TEST_A(12);
DO_TEST_A(13);
DO_TEST_A(14);
DO_TEST_A(15);
DO_TEST_A(16);
DO_TEST_A(17);
DO_TEST_A(18);
DO_TEST_A(101);
DO_TEST_A(102);
DO_TEST_A(103);
/* check if the results are equal */
DO_TEST_B(1);
DO_TEST_B(2);
DO_TEST_B(3);
DO_TEST_B(4);
DO_TEST_B(5);
DO_TEST_B(6);
DO_TEST_B(7);
DO_TEST_B(8);
DO_TEST_B(11);
DO_TEST_B(12);
DO_TEST_B(13);
DO_TEST_B(14);
DO_TEST_B(15);
DO_TEST_B(16);
DO_TEST_B(17);
DO_TEST_B(18);
DO_TEST_B(101);
DO_TEST_B(102);
DO_TEST_B(103);
return res;
}
|
c825c930e7ffe8f9bd18a3418d2084f6bb62cc89
|
96df46515663aee49a753171fb3b07d74c8ef72f
|
/bindgen-tests/tests/headers/union_with_big_member.h
|
e8a3fe0a9cdff826b9dd5b30476ea4740676f97d
|
[
"BSD-3-Clause"
] |
permissive
|
rust-lang/rust-bindgen
|
05273ad4d385ce0b5a2315859f8c7c453c150db6
|
820ca42982fe77d5504f7a0534a3de6db6a1d703
|
refs/heads/main
| 2023-08-30T19:59:33.017994
| 2023-08-15T18:01:02
| 2023-08-15T18:01:02
| 61,728,459
| 2,874
| 391
|
BSD-3-Clause
| 2023-09-12T20:32:46
| 2016-06-22T15:05:51
|
Rust
|
UTF-8
|
C
| false
| false
| 235
|
h
|
union_with_big_member.h
|
// bindgen-flags: --with-derive-hash --with-derive-partialeq --with-derive-eq
//
union WithBigArray {
int a;
int b[33];
};
union WithBigArray2 {
int a;
char b[33];
};
union WithBigMember {
int a;
union WithBigArray b;
};
|
d4edff8e2e424251b7f7ba29207f6029bf45571d
|
eecd5e4c50d8b78a769bcc2675250576bed34066
|
/src/mat/tests/ex232.c
|
99a56edf23f3eb145b127093de4d73d20d4e6b71
|
[
"BSD-2-Clause"
] |
permissive
|
petsc/petsc
|
3b1a04fea71858e0292f9fd4d04ea11618c50969
|
9c5460f9064ca60dd71a234a1f6faf93e7a6b0c9
|
refs/heads/main
| 2023-08-17T20:51:16.507070
| 2023-08-17T16:08:06
| 2023-08-17T16:08:06
| 8,691,401
| 341
| 169
|
NOASSERTION
| 2023-03-29T11:02:58
| 2013-03-10T20:55:21
|
C
|
UTF-8
|
C
| false
| false
| 1,612
|
c
|
ex232.c
|
/* tests MatSeqSBAIJSetPreallocationCSR() and MatMPISBAIJSetPreallocationCSR() */
#include <petsc.h>
int main(int argc, char **args)
{
PetscInt ia[3] = {0, 2, 4};
PetscInt ja[4] = {0, 1, 0, 1};
PetscScalar c[16] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
Mat ssbaij, msbaij;
PetscBool v2 = PETSC_FALSE;
PetscFunctionBeginUser;
PetscCall(PetscInitialize(&argc, &args, (char *)0, (char *)0));
PetscCall(PetscOptionsGetBool(NULL, NULL, "-v2", &v2, NULL));
PetscCall(MatCreate(PETSC_COMM_SELF, &ssbaij));
PetscCall(MatCreate(PETSC_COMM_SELF, &msbaij));
if (!v2) {
PetscCall(MatSetType(ssbaij, MATSEQSBAIJ));
PetscCall(MatSetType(msbaij, MATMPISBAIJ));
}
PetscCall(MatSetBlockSize(ssbaij, 2));
PetscCall(MatSetSizes(ssbaij, 4, 4, 4, 4));
PetscCall(MatSetBlockSize(msbaij, 2));
PetscCall(MatSetSizes(msbaij, 4, 4, 4, 4));
if (v2) {
PetscCall(MatSetUp(ssbaij));
PetscCall(MatSetUp(msbaij));
PetscCall(MatSetType(ssbaij, MATSEQSBAIJ));
PetscCall(MatSetType(msbaij, MATMPISBAIJ));
}
PetscCall(MatSeqSBAIJSetPreallocationCSR(ssbaij, 2, ia, ja, c));
PetscCall(MatMPISBAIJSetPreallocationCSR(msbaij, 2, ia, ja, c));
PetscCall(MatView(ssbaij, PETSC_VIEWER_STDOUT_(PETSC_COMM_SELF)));
PetscCall(MatView(msbaij, PETSC_VIEWER_STDOUT_(PETSC_COMM_SELF)));
PetscCall(MatDestroy(&ssbaij));
PetscCall(MatDestroy(&msbaij));
PetscCall(PetscFinalize());
return 0;
}
/*TEST
test:
filter: sed "s?\.??g"
test:
suffix: 2
filter: sed "s?\.??g"
args : -v2
output_file: output/ex232_1.out
TEST*/
|
be929bd9e41cdffb6e740b3b739e9f88cacc0132
|
e73547787354afd9b717ea57fe8dd0695d161821
|
/include/mapfs/tik_04_hit.h
|
072c2d376746d0b1e17f1994bda704db29b164c1
|
[] |
no_license
|
pmret/papermario
|
8b514b19653cef8d6145e47499b3636b8c474a37
|
9774b26d93f1045dd2a67e502b6efc9599fb6c31
|
refs/heads/main
| 2023-08-31T07:09:48.951514
| 2023-08-21T18:07:08
| 2023-08-21T18:07:08
| 287,151,133
| 904
| 139
| null | 2023-09-14T02:44:23
| 2020-08-13T01:22:57
|
C
|
UTF-8
|
C
| false
| false
| 1,313
|
h
|
tik_04_hit.h
|
#define COLLIDER_Root 0x1D
#define COLLIDER_exitd2 0x1C
#define COLLIDER_ttd2 0x1B
#define COLLIDER_nd2 0x1A
#define COLLIDER_exitd 0x19
#define COLLIDER_ttd 0x18
#define COLLIDER_nd 0x17
#define COLLIDER_exite 0x16
#define COLLIDER_tte 0x15
#define COLLIDER_deilite 0x14
#define COLLIDER_deilie 0x13
#define COLLIDER_ne 0x12
#define COLLIDER_exitw 0x11
#define COLLIDER_ttw 0x10
#define COLLIDER_nw 0xF
#define COLLIDER_deiliw 0xE
#define COLLIDER_deilitw 0xD
#define COLLIDER_g9 0xC
#define COLLIDER_erb2 0xB
#define COLLIDER_erb 0xA
#define COLLIDER_erb1 0x9
#define COLLIDER_Default 0x8
#define COLLIDER_o23 0x7
#define COLLIDER_o22 0x6
#define COLLIDER_o53 0x5
#define COLLIDER_o52 0x4
#define COLLIDER_kabe 0x3
#define COLLIDER_o51 0x2
#define COLLIDER_o50 0x1
#define COLLIDER_yuka 0x0
#define ZONE_Root 0x4
#define ZONE_Default 0x3
#define ZONE_o36 0x2
#define ZONE_o37 0x1
#define ZONE_o39 0x0
|
31e2123dd1ac051b84bf6d2867d7409463de29e1
|
8a51a96f61699f0318315ccc89cef39f6866f2b5
|
/src/backend/statistics/mvdistinct.c
|
6d25c14644a951fdd55805922028f550ba629205
|
[
"PostgreSQL"
] |
permissive
|
postgres/postgres
|
979febf2b41c00090d1256228f768f33e7ef3b6f
|
b5934bfd6071fed3a38cea0cfaa93afda63d9c0c
|
refs/heads/master
| 2023-08-31T00:10:01.373472
| 2023-08-30T23:07:48
| 2023-08-30T23:07:48
| 927,442
| 13,691
| 4,807
|
NOASSERTION
| 2023-09-09T13:59:15
| 2010-09-21T11:35:45
|
C
|
UTF-8
|
C
| false
| false
| 18,117
|
c
|
mvdistinct.c
|
/*-------------------------------------------------------------------------
*
* mvdistinct.c
* POSTGRES multivariate ndistinct coefficients
*
* Estimating number of groups in a combination of columns (e.g. for GROUP BY)
* is tricky, and the estimation error is often significant.
* The multivariate ndistinct coefficients address this by storing ndistinct
* estimates for combinations of the user-specified columns. So for example
* given a statistics object on three columns (a,b,c), this module estimates
* and stores n-distinct for (a,b), (a,c), (b,c) and (a,b,c). The per-column
* estimates are already available in pg_statistic.
*
*
* Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
* Portions Copyright (c) 1994, Regents of the University of California
*
* IDENTIFICATION
* src/backend/statistics/mvdistinct.c
*
*-------------------------------------------------------------------------
*/
#include "postgres.h"
#include <math.h>
#include "access/htup_details.h"
#include "catalog/pg_statistic_ext.h"
#include "catalog/pg_statistic_ext_data.h"
#include "lib/stringinfo.h"
#include "statistics/extended_stats_internal.h"
#include "statistics/statistics.h"
#include "utils/fmgrprotos.h"
#include "utils/lsyscache.h"
#include "utils/syscache.h"
#include "utils/typcache.h"
static double ndistinct_for_combination(double totalrows, StatsBuildData *data,
int k, int *combination);
static double estimate_ndistinct(double totalrows, int numrows, int d, int f1);
static int n_choose_k(int n, int k);
static int num_combinations(int n);
/* size of the struct header fields (magic, type, nitems) */
#define SizeOfHeader (3 * sizeof(uint32))
/* size of a serialized ndistinct item (coefficient, natts, atts) */
#define SizeOfItem(natts) \
(sizeof(double) + sizeof(int) + (natts) * sizeof(AttrNumber))
/* minimal size of a ndistinct item (with two attributes) */
#define MinSizeOfItem SizeOfItem(2)
/* minimal size of mvndistinct, when all items are minimal */
#define MinSizeOfItems(nitems) \
(SizeOfHeader + (nitems) * MinSizeOfItem)
/* Combination generator API */
/* internal state for generator of k-combinations of n elements */
typedef struct CombinationGenerator
{
int k; /* size of the combination */
int n; /* total number of elements */
int current; /* index of the next combination to return */
int ncombinations; /* number of combinations (size of array) */
int *combinations; /* array of pre-built combinations */
} CombinationGenerator;
static CombinationGenerator *generator_init(int n, int k);
static void generator_free(CombinationGenerator *state);
static int *generator_next(CombinationGenerator *state);
static void generate_combinations(CombinationGenerator *state);
/*
* statext_ndistinct_build
* Compute ndistinct coefficient for the combination of attributes.
*
* This computes the ndistinct estimate using the same estimator used
* in analyze.c and then computes the coefficient.
*
* To handle expressions easily, we treat them as system attributes with
* negative attnums, and offset everything by number of expressions to
* allow using Bitmapsets.
*/
MVNDistinct *
statext_ndistinct_build(double totalrows, StatsBuildData *data)
{
MVNDistinct *result;
int k;
int itemcnt;
int numattrs = data->nattnums;
int numcombs = num_combinations(numattrs);
result = palloc(offsetof(MVNDistinct, items) +
numcombs * sizeof(MVNDistinctItem));
result->magic = STATS_NDISTINCT_MAGIC;
result->type = STATS_NDISTINCT_TYPE_BASIC;
result->nitems = numcombs;
itemcnt = 0;
for (k = 2; k <= numattrs; k++)
{
int *combination;
CombinationGenerator *generator;
/* generate combinations of K out of N elements */
generator = generator_init(numattrs, k);
while ((combination = generator_next(generator)))
{
MVNDistinctItem *item = &result->items[itemcnt];
int j;
item->attributes = palloc(sizeof(AttrNumber) * k);
item->nattributes = k;
/* translate the indexes to attnums */
for (j = 0; j < k; j++)
{
item->attributes[j] = data->attnums[combination[j]];
Assert(AttributeNumberIsValid(item->attributes[j]));
}
item->ndistinct =
ndistinct_for_combination(totalrows, data, k, combination);
itemcnt++;
Assert(itemcnt <= result->nitems);
}
generator_free(generator);
}
/* must consume exactly the whole output array */
Assert(itemcnt == result->nitems);
return result;
}
/*
* statext_ndistinct_load
* Load the ndistinct value for the indicated pg_statistic_ext tuple
*/
MVNDistinct *
statext_ndistinct_load(Oid mvoid, bool inh)
{
MVNDistinct *result;
bool isnull;
Datum ndist;
HeapTuple htup;
htup = SearchSysCache2(STATEXTDATASTXOID,
ObjectIdGetDatum(mvoid), BoolGetDatum(inh));
if (!HeapTupleIsValid(htup))
elog(ERROR, "cache lookup failed for statistics object %u", mvoid);
ndist = SysCacheGetAttr(STATEXTDATASTXOID, htup,
Anum_pg_statistic_ext_data_stxdndistinct, &isnull);
if (isnull)
elog(ERROR,
"requested statistics kind \"%c\" is not yet built for statistics object %u",
STATS_EXT_NDISTINCT, mvoid);
result = statext_ndistinct_deserialize(DatumGetByteaPP(ndist));
ReleaseSysCache(htup);
return result;
}
/*
* statext_ndistinct_serialize
* serialize ndistinct to the on-disk bytea format
*/
bytea *
statext_ndistinct_serialize(MVNDistinct *ndistinct)
{
int i;
bytea *output;
char *tmp;
Size len;
Assert(ndistinct->magic == STATS_NDISTINCT_MAGIC);
Assert(ndistinct->type == STATS_NDISTINCT_TYPE_BASIC);
/*
* Base size is size of scalar fields in the struct, plus one base struct
* for each item, including number of items for each.
*/
len = VARHDRSZ + SizeOfHeader;
/* and also include space for the actual attribute numbers */
for (i = 0; i < ndistinct->nitems; i++)
{
int nmembers;
nmembers = ndistinct->items[i].nattributes;
Assert(nmembers >= 2);
len += SizeOfItem(nmembers);
}
output = (bytea *) palloc(len);
SET_VARSIZE(output, len);
tmp = VARDATA(output);
/* Store the base struct values (magic, type, nitems) */
memcpy(tmp, &ndistinct->magic, sizeof(uint32));
tmp += sizeof(uint32);
memcpy(tmp, &ndistinct->type, sizeof(uint32));
tmp += sizeof(uint32);
memcpy(tmp, &ndistinct->nitems, sizeof(uint32));
tmp += sizeof(uint32);
/*
* store number of attributes and attribute numbers for each entry
*/
for (i = 0; i < ndistinct->nitems; i++)
{
MVNDistinctItem item = ndistinct->items[i];
int nmembers = item.nattributes;
memcpy(tmp, &item.ndistinct, sizeof(double));
tmp += sizeof(double);
memcpy(tmp, &nmembers, sizeof(int));
tmp += sizeof(int);
memcpy(tmp, item.attributes, sizeof(AttrNumber) * nmembers);
tmp += nmembers * sizeof(AttrNumber);
/* protect against overflows */
Assert(tmp <= ((char *) output + len));
}
/* check we used exactly the expected space */
Assert(tmp == ((char *) output + len));
return output;
}
/*
* statext_ndistinct_deserialize
* Read an on-disk bytea format MVNDistinct to in-memory format
*/
MVNDistinct *
statext_ndistinct_deserialize(bytea *data)
{
int i;
Size minimum_size;
MVNDistinct ndist;
MVNDistinct *ndistinct;
char *tmp;
if (data == NULL)
return NULL;
/* we expect at least the basic fields of MVNDistinct struct */
if (VARSIZE_ANY_EXHDR(data) < SizeOfHeader)
elog(ERROR, "invalid MVNDistinct size %zu (expected at least %zu)",
VARSIZE_ANY_EXHDR(data), SizeOfHeader);
/* initialize pointer to the data part (skip the varlena header) */
tmp = VARDATA_ANY(data);
/* read the header fields and perform basic sanity checks */
memcpy(&ndist.magic, tmp, sizeof(uint32));
tmp += sizeof(uint32);
memcpy(&ndist.type, tmp, sizeof(uint32));
tmp += sizeof(uint32);
memcpy(&ndist.nitems, tmp, sizeof(uint32));
tmp += sizeof(uint32);
if (ndist.magic != STATS_NDISTINCT_MAGIC)
elog(ERROR, "invalid ndistinct magic %08x (expected %08x)",
ndist.magic, STATS_NDISTINCT_MAGIC);
if (ndist.type != STATS_NDISTINCT_TYPE_BASIC)
elog(ERROR, "invalid ndistinct type %d (expected %d)",
ndist.type, STATS_NDISTINCT_TYPE_BASIC);
if (ndist.nitems == 0)
elog(ERROR, "invalid zero-length item array in MVNDistinct");
/* what minimum bytea size do we expect for those parameters */
minimum_size = MinSizeOfItems(ndist.nitems);
if (VARSIZE_ANY_EXHDR(data) < minimum_size)
elog(ERROR, "invalid MVNDistinct size %zu (expected at least %zu)",
VARSIZE_ANY_EXHDR(data), minimum_size);
/*
* Allocate space for the ndistinct items (no space for each item's
* attnos: those live in bitmapsets allocated separately)
*/
ndistinct = palloc0(MAXALIGN(offsetof(MVNDistinct, items)) +
(ndist.nitems * sizeof(MVNDistinctItem)));
ndistinct->magic = ndist.magic;
ndistinct->type = ndist.type;
ndistinct->nitems = ndist.nitems;
for (i = 0; i < ndistinct->nitems; i++)
{
MVNDistinctItem *item = &ndistinct->items[i];
/* ndistinct value */
memcpy(&item->ndistinct, tmp, sizeof(double));
tmp += sizeof(double);
/* number of attributes */
memcpy(&item->nattributes, tmp, sizeof(int));
tmp += sizeof(int);
Assert((item->nattributes >= 2) && (item->nattributes <= STATS_MAX_DIMENSIONS));
item->attributes
= (AttrNumber *) palloc(item->nattributes * sizeof(AttrNumber));
memcpy(item->attributes, tmp, sizeof(AttrNumber) * item->nattributes);
tmp += sizeof(AttrNumber) * item->nattributes;
/* still within the bytea */
Assert(tmp <= ((char *) data + VARSIZE_ANY(data)));
}
/* we should have consumed the whole bytea exactly */
Assert(tmp == ((char *) data + VARSIZE_ANY(data)));
return ndistinct;
}
/*
* pg_ndistinct_in
* input routine for type pg_ndistinct
*
* pg_ndistinct is real enough to be a table column, but it has no
* operations of its own, and disallows input (just like pg_node_tree).
*/
Datum
pg_ndistinct_in(PG_FUNCTION_ARGS)
{
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("cannot accept a value of type %s", "pg_ndistinct")));
PG_RETURN_VOID(); /* keep compiler quiet */
}
/*
* pg_ndistinct
* output routine for type pg_ndistinct
*
* Produces a human-readable representation of the value.
*/
Datum
pg_ndistinct_out(PG_FUNCTION_ARGS)
{
bytea *data = PG_GETARG_BYTEA_PP(0);
MVNDistinct *ndist = statext_ndistinct_deserialize(data);
int i;
StringInfoData str;
initStringInfo(&str);
appendStringInfoChar(&str, '{');
for (i = 0; i < ndist->nitems; i++)
{
int j;
MVNDistinctItem item = ndist->items[i];
if (i > 0)
appendStringInfoString(&str, ", ");
for (j = 0; j < item.nattributes; j++)
{
AttrNumber attnum = item.attributes[j];
appendStringInfo(&str, "%s%d", (j == 0) ? "\"" : ", ", attnum);
}
appendStringInfo(&str, "\": %d", (int) item.ndistinct);
}
appendStringInfoChar(&str, '}');
PG_RETURN_CSTRING(str.data);
}
/*
* pg_ndistinct_recv
* binary input routine for type pg_ndistinct
*/
Datum
pg_ndistinct_recv(PG_FUNCTION_ARGS)
{
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("cannot accept a value of type %s", "pg_ndistinct")));
PG_RETURN_VOID(); /* keep compiler quiet */
}
/*
* pg_ndistinct_send
* binary output routine for type pg_ndistinct
*
* n-distinct is serialized into a bytea value, so let's send that.
*/
Datum
pg_ndistinct_send(PG_FUNCTION_ARGS)
{
return byteasend(fcinfo);
}
/*
* ndistinct_for_combination
* Estimates number of distinct values in a combination of columns.
*
* This uses the same ndistinct estimator as compute_scalar_stats() in
* ANALYZE, i.e.,
* n*d / (n - f1 + f1*n/N)
*
* except that instead of values in a single column we are dealing with
* combination of multiple columns.
*/
static double
ndistinct_for_combination(double totalrows, StatsBuildData *data,
int k, int *combination)
{
int i,
j;
int f1,
cnt,
d;
bool *isnull;
Datum *values;
SortItem *items;
MultiSortSupport mss;
int numrows = data->numrows;
mss = multi_sort_init(k);
/*
* In order to determine the number of distinct elements, create separate
* values[]/isnull[] arrays with all the data we have, then sort them
* using the specified column combination as dimensions. We could try to
* sort in place, but it'd probably be more complex and bug-prone.
*/
items = (SortItem *) palloc(numrows * sizeof(SortItem));
values = (Datum *) palloc0(sizeof(Datum) * numrows * k);
isnull = (bool *) palloc0(sizeof(bool) * numrows * k);
for (i = 0; i < numrows; i++)
{
items[i].values = &values[i * k];
items[i].isnull = &isnull[i * k];
}
/*
* For each dimension, set up sort-support and fill in the values from the
* sample data.
*
* We use the column data types' default sort operators and collations;
* perhaps at some point it'd be worth using column-specific collations?
*/
for (i = 0; i < k; i++)
{
Oid typid;
TypeCacheEntry *type;
Oid collid = InvalidOid;
VacAttrStats *colstat = data->stats[combination[i]];
typid = colstat->attrtypid;
collid = colstat->attrcollid;
type = lookup_type_cache(typid, TYPECACHE_LT_OPR);
if (type->lt_opr == InvalidOid) /* shouldn't happen */
elog(ERROR, "cache lookup failed for ordering operator for type %u",
typid);
/* prepare the sort function for this dimension */
multi_sort_add_dimension(mss, i, type->lt_opr, collid);
/* accumulate all the data for this dimension into the arrays */
for (j = 0; j < numrows; j++)
{
items[j].values[i] = data->values[combination[i]][j];
items[j].isnull[i] = data->nulls[combination[i]][j];
}
}
/* We can sort the array now ... */
qsort_interruptible(items, numrows, sizeof(SortItem),
multi_sort_compare, mss);
/* ... and count the number of distinct combinations */
f1 = 0;
cnt = 1;
d = 1;
for (i = 1; i < numrows; i++)
{
if (multi_sort_compare(&items[i], &items[i - 1], mss) != 0)
{
if (cnt == 1)
f1 += 1;
d++;
cnt = 0;
}
cnt += 1;
}
if (cnt == 1)
f1 += 1;
return estimate_ndistinct(totalrows, numrows, d, f1);
}
/* The Duj1 estimator (already used in analyze.c). */
static double
estimate_ndistinct(double totalrows, int numrows, int d, int f1)
{
double numer,
denom,
ndistinct;
numer = (double) numrows * (double) d;
denom = (double) (numrows - f1) +
(double) f1 * (double) numrows / totalrows;
ndistinct = numer / denom;
/* Clamp to sane range in case of roundoff error */
if (ndistinct < (double) d)
ndistinct = (double) d;
if (ndistinct > totalrows)
ndistinct = totalrows;
return floor(ndistinct + 0.5);
}
/*
* n_choose_k
* computes binomial coefficients using an algorithm that is both
* efficient and prevents overflows
*/
static int
n_choose_k(int n, int k)
{
int d,
r;
Assert((k > 0) && (n >= k));
/* use symmetry of the binomial coefficients */
k = Min(k, n - k);
r = 1;
for (d = 1; d <= k; ++d)
{
r *= n--;
r /= d;
}
return r;
}
/*
* num_combinations
* number of combinations, excluding single-value combinations
*/
static int
num_combinations(int n)
{
return (1 << n) - (n + 1);
}
/*
* generator_init
* initialize the generator of combinations
*
* The generator produces combinations of K elements in the interval (0..N).
* We prebuild all the combinations in this method, which is simpler than
* generating them on the fly.
*/
static CombinationGenerator *
generator_init(int n, int k)
{
CombinationGenerator *state;
Assert((n >= k) && (k > 0));
/* allocate the generator state as a single chunk of memory */
state = (CombinationGenerator *) palloc(sizeof(CombinationGenerator));
state->ncombinations = n_choose_k(n, k);
/* pre-allocate space for all combinations */
state->combinations = (int *) palloc(sizeof(int) * k * state->ncombinations);
state->current = 0;
state->k = k;
state->n = n;
/* now actually pre-generate all the combinations of K elements */
generate_combinations(state);
/* make sure we got the expected number of combinations */
Assert(state->current == state->ncombinations);
/* reset the number, so we start with the first one */
state->current = 0;
return state;
}
/*
* generator_next
* returns the next combination from the prebuilt list
*
* Returns a combination of K array indexes (0 .. N), as specified to
* generator_init), or NULL when there are no more combination.
*/
static int *
generator_next(CombinationGenerator *state)
{
if (state->current == state->ncombinations)
return NULL;
return &state->combinations[state->k * state->current++];
}
/*
* generator_free
* free the internal state of the generator
*
* Releases the generator internal state (pre-built combinations).
*/
static void
generator_free(CombinationGenerator *state)
{
pfree(state->combinations);
pfree(state);
}
/*
* generate_combinations_recurse
* given a prefix, generate all possible combinations
*
* Given a prefix (first few elements of the combination), generate following
* elements recursively. We generate the combinations in lexicographic order,
* which eliminates permutations of the same combination.
*/
static void
generate_combinations_recurse(CombinationGenerator *state,
int index, int start, int *current)
{
/* If we haven't filled all the elements, simply recurse. */
if (index < state->k)
{
int i;
/*
* The values have to be in ascending order, so make sure we start
* with the value passed by parameter.
*/
for (i = start; i < state->n; i++)
{
current[index] = i;
generate_combinations_recurse(state, (index + 1), (i + 1), current);
}
return;
}
else
{
/* we got a valid combination, add it to the array */
memcpy(&state->combinations[(state->k * state->current)],
current, state->k * sizeof(int));
state->current++;
}
}
/*
* generate_combinations
* generate all k-combinations of N elements
*/
static void
generate_combinations(CombinationGenerator *state)
{
int *current = (int *) palloc0(sizeof(int) * state->k);
generate_combinations_recurse(state, 0, 0, current);
pfree(current);
}
|
744ddb6725e2a9f6a23da50101c71b65acdae8c2
|
fdbb74a95924e2677466614f6ab6e2bb13b2a95a
|
/tool/plinko/lib/char.c
|
893cb7e69856e7f6b97e0f194a29914bac8f4c09
|
[
"ISC"
] |
permissive
|
jart/cosmopolitan
|
fb11b5658939023977060a7c6c71a74093d9cb44
|
0d748ad58e1063dd1f8560f18a0c75293b9415b7
|
refs/heads/master
| 2023-09-06T09:17:29.303607
| 2023-09-02T03:49:13
| 2023-09-02T03:50:18
| 272,457,606
| 11,887
| 435
|
ISC
| 2023-09-14T17:47:58
| 2020-06-15T14:16:13
|
C
|
UTF-8
|
C
| false
| false
| 2,567
|
c
|
char.c
|
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│
│vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│
╞══════════════════════════════════════════════════════════════════════════════╡
│ Copyright 2022 Justine Alexandra Roberts Tunney │
│ │
│ 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. │
╚─────────────────────────────────────────────────────────────────────────────*/
#include "tool/plinko/lib/char.h"
pureconst bool IsHex(int c) {
return ((L'0' <= c && c <= L'9') || (L'A' <= c && c <= L'F') ||
(L'a' <= c && c <= L'f'));
}
pureconst int GetDiglet(int c) {
if (IsDigit(c)) return c - L'0';
if (IsUpper(c)) return c - L'A' + 10;
if (IsLower(c)) return c - L'a' + 10;
return -1;
}
pureconst bool IsSpace(int c) {
switch (c) {
case L' ':
case L'\t':
case L'\n':
case L'\f':
case L'\v':
case L'\r':
return true;
default:
return false;
}
}
pureconst bool IsParen(int c) {
switch (c) {
case L'(':
case L')':
case L'[':
case L']':
case L'{':
case L'}':
return true;
default:
return false;
}
}
|
87eda9563189b490f2fc25bd23dc7530373d7917
|
b91a6cc4c7ee18d33d92d171c4473a5df66b6d9b
|
/exercises/practice/sublist/sublist.h
|
62980d14d065cdc2c734c20925ee9795259768a3
|
[
"MIT"
] |
permissive
|
exercism/c
|
b26171da41cf032fcee9ddf3736c6ed571bf3ad5
|
c76ccd0a34b8ebfcf448fb95d7b90e9f040461de
|
refs/heads/main
| 2023-07-25T18:04:49.202518
| 2023-07-22T19:39:08
| 2023-07-22T19:39:08
| 24,443,186
| 305
| 242
|
MIT
| 2023-09-05T11:33:28
| 2014-09-25T04:07:05
|
C
|
UTF-8
|
C
| false
| false
| 345
|
h
|
sublist.h
|
#ifndef SUBLIST_H
#define SUBLIST_H
#include <stddef.h>
typedef enum { EQUAL, UNEQUAL, SUBLIST, SUPERLIST } comparison_result_t;
comparison_result_t check_lists(int *list_to_compare, int *base_list,
size_t list_to_compare_element_count,
size_t base_list_element_count);
#endif
|
09f5449b974081d19c8694137d73fa0ff43efe9b
|
0f5244a66dd11060f9c35d49f22ca026d171e29c
|
/src/portable/nxp/lpc_ip3511/dcd_lpc_ip3511.c
|
f4ed09d83c383afce71ea9d9f02f7cd1a32dfa67
|
[
"MIT"
] |
permissive
|
hathach/tinyusb
|
b5557037f1cb1763b280f308829ceea94d31f3ae
|
1fdf29075d4e613eacfa881166015263797db0f6
|
refs/heads/master
| 2023-08-22T10:14:47.526256
| 2023-08-16T09:01:16
| 2023-08-16T09:01:16
| 6,860,771
| 4,096
| 918
|
MIT
| 2023-09-14T07:22:16
| 2012-11-26T06:24:00
|
C
|
UTF-8
|
C
| false
| false
| 21,232
|
c
|
dcd_lpc_ip3511.c
|
/*
* The MIT License (MIT)
*
* Copyright (c) 2019 Ha Thach (tinyusb.org)
*
* 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.
*
* This file is part of the TinyUSB stack.
*/
#include "tusb_option.h"
/* Since 2012 starting with LPC11uxx, NXP start to use common USB Device Controller with code name LPC IP3511
* for almost their new MCUs. Currently supported and tested families are
* - LPC11U68, LPC11U37
* - LPC1347
* - LPC51U68
* - LPC54114
* - LPC55s69
*/
#if CFG_TUD_ENABLED && defined(TUP_USBIP_IP3511)
//--------------------------------------------------------------------+
// INCLUDE
//--------------------------------------------------------------------+
#if TU_CHECK_MCU(OPT_MCU_LPC11UXX, OPT_MCU_LPC13XX, OPT_MCU_LPC15XX)
// LPCOpen
#include "chip.h"
#else
// SDK
#include "fsl_device_registers.h"
#define INCLUDE_FSL_DEVICE_REGISTERS
#endif
#include "device/dcd.h"
//--------------------------------------------------------------------+
// IP3511 Registers
//--------------------------------------------------------------------+
typedef struct {
__IO uint32_t DEVCMDSTAT; // Device Command/Status register, offset: 0x0
__I uint32_t INFO; // Info register, offset: 0x4
__IO uint32_t EPLISTSTART; // EP Command/Status List start address, offset: 0x8
__IO uint32_t DATABUFSTART; // Data buffer start address, offset: 0xC
__IO uint32_t LPM; // Link Power Management register, offset: 0x10
__IO uint32_t EPSKIP; // Endpoint skip, offset: 0x14
__IO uint32_t EPINUSE; // Endpoint Buffer in use, offset: 0x18
__IO uint32_t EPBUFCFG; // Endpoint Buffer Configuration register, offset: 0x1C
__IO uint32_t INTSTAT; // interrupt status register, offset: 0x20
__IO uint32_t INTEN; // interrupt enable register, offset: 0x24
__IO uint32_t INTSETSTAT; // set interrupt status register, offset: 0x28
uint8_t RESERVED_0[8];
__I uint32_t EPTOGGLE; // Endpoint toggle register, offset: 0x34
} dcd_registers_t;
// Max nbytes for each control/bulk/interrupt transfer
enum {
NBYTES_ISO_FS_MAX = 1023, // FS ISO
NBYTES_ISO_HS_MAX = 1024, // HS ISO
NBYTES_CBI_FS_MAX = 64, // FS control/bulk/interrupt. TODO some FS can do burst with higher size e.g 1024. Need to test
NBYTES_CBI_HS_MAX = 32767 // can be up to all 15-bit, but only tested with 4096
};
enum {
INT_SOF_MASK = TU_BIT(30),
INT_DEVICE_STATUS_MASK = TU_BIT(31)
};
enum {
DEVCMDSTAT_DEVICE_ADDR_MASK = TU_BIT(7 )-1,
DEVCMDSTAT_DEVICE_ENABLE_MASK = TU_BIT(7 ),
DEVCMDSTAT_SETUP_RECEIVED_MASK = TU_BIT(8 ),
DEVCMDSTAT_DEVICE_CONNECT_MASK = TU_BIT(16), // reflect the soft-connect only, does not reflect the actual attached state
DEVCMDSTAT_DEVICE_SUSPEND_MASK = TU_BIT(17),
// 23-22 is link speed (only available for HighSpeed port)
DEVCMDSTAT_CONNECT_CHANGE_MASK = TU_BIT(24),
DEVCMDSTAT_SUSPEND_CHANGE_MASK = TU_BIT(25),
DEVCMDSTAT_RESET_CHANGE_MASK = TU_BIT(26),
DEVCMDSTAT_VBUS_DEBOUNCED_MASK = TU_BIT(28),
};
enum {
DEVCMDSTAT_SPEED_SHIFT = 22
};
//--------------------------------------------------------------------+
// Endpoint Command/Status List
//--------------------------------------------------------------------+
// EP Command/Status field definition
enum {
EPCS_TYPE = TU_BIT(26),
EPCS_RF_TV = TU_BIT(27),
EPCS_TOGGLE_RESET = TU_BIT(28),
EPCS_STALL = TU_BIT(29),
EPCS_DISABLED = TU_BIT(30),
EPCS_ACTIVE = TU_BIT(31),
};
// Endpoint Command/Status
typedef union TU_ATTR_PACKED
{
// Full and High speed has different bit layout for buffer_offset and nbytes
// TODO FS/HS layout depends on the max speed of controller e.g
// lpc55s69 PORT0 is only FS but actually has the same layout as HS on port1
// Buffer (aligned 64) = DATABUFSTART [31:22] | buffer_offset [21:6]
volatile struct {
uint32_t offset : 16;
uint32_t nbytes : 10;
uint32_t TU_RESERVED : 6;
} buffer_fs;
// Buffer (aligned 64) = USB_RAM [31:17] | buffer_offset [16:6]
volatile struct {
uint32_t offset : 11 ;
uint32_t nbytes : 15 ;
uint32_t TU_RESERVED : 6 ;
} buffer_hs;
volatile struct {
uint32_t TU_RESERVED : 26;
uint32_t type : 1 ;
uint32_t rf_tv : 1 ; // rate feedback or toggle value
uint32_t toggle_reset : 1 ;
uint32_t stall : 1 ;
uint32_t disable : 1 ;
uint32_t active : 1 ;
} cmd_sts;
}ep_cmd_sts_t;
TU_VERIFY_STATIC( sizeof(ep_cmd_sts_t) == 4, "size is not correct" );
// Software transfer management
typedef struct
{
uint16_t total_bytes;
uint16_t xferred_bytes;
uint16_t nbytes;
// prevent unaligned access on Highspeed port on USB_SRAM
uint16_t TU_RESERVED;
}xfer_dma_t;
// Absolute max of endpoints pairs for all port
// - 11 13 15 51 54 has 5x2 endpoints
// - 55 usb0 (FS) has 5x2 endpoints, usb1 (HS) has 6x2 endpoints
#define MAX_EP_PAIRS 6
// NOTE data will be transferred as soon as dcd get request by dcd_pipe(_queue)_xfer using double buffering.
// current_td is used to keep track of number of remaining & xferred bytes of the current request.
typedef struct
{
// 256 byte aligned, 2 for double buffer (not used)
// Each cmd_sts can only transfer up to DMA_NBYTES_MAX bytes each
ep_cmd_sts_t ep[2*MAX_EP_PAIRS][2];
xfer_dma_t dma[2*MAX_EP_PAIRS];
TU_ATTR_ALIGNED(64) uint8_t setup_packet[8];
}dcd_data_t;
// EP list must be 256-byte aligned
// Some MCU controller may require this variable to be placed in specific SRAM region.
// For example: LPC55s69 port1 Highspeed must be USB_RAM (0x40100000)
// Use CFG_TUD_MEM_SECTION to place it accordingly.
CFG_TUD_MEM_SECTION TU_ATTR_ALIGNED(256) static dcd_data_t _dcd;
// Dummy buffer to fix ZLPs overwriting the buffer (probably an USB/DMA controller bug)
// TODO find way to save memory
CFG_TUD_MEM_SECTION TU_ATTR_ALIGNED(64) static uint8_t dummy[8];
//--------------------------------------------------------------------+
// Multiple Controllers
//--------------------------------------------------------------------+
typedef struct
{
dcd_registers_t* regs; // registers
const bool is_highspeed; // max link speed
const IRQn_Type irqnum; // IRQ number
const uint8_t ep_pairs; // Max bi-directional Endpoints
}dcd_controller_t;
#ifdef INCLUDE_FSL_DEVICE_REGISTERS
static const dcd_controller_t _dcd_controller[] = {
{ .regs = (dcd_registers_t*) USB0_BASE , .is_highspeed = false, .irqnum = USB0_IRQn, .ep_pairs = FSL_FEATURE_USB_EP_NUM },
#if defined(FSL_FEATURE_SOC_USBHSD_COUNT) && FSL_FEATURE_SOC_USBHSD_COUNT
{ .regs = (dcd_registers_t*) USBHSD_BASE, .is_highspeed = true, .irqnum = USB1_IRQn, .ep_pairs = FSL_FEATURE_USBHSD_EP_NUM }
#endif
};
#else
static const dcd_controller_t _dcd_controller[] = {
{ .regs = (dcd_registers_t*) LPC_USB0_BASE, .is_highspeed = false, .irqnum = USB0_IRQn, .ep_pairs = 5 },
};
#endif
#if defined(FSL_FEATURE_SOC_USBHSD_COUNT) && FSL_FEATURE_SOC_USBHSD_COUNT
#define IP3511_HAS_HIGHSPEED
#endif
//--------------------------------------------------------------------+
// INTERNAL OBJECT & FUNCTION DECLARATION
//--------------------------------------------------------------------+
TU_ATTR_ALWAYS_INLINE static inline uint16_t get_buf_offset(void const * buffer) {
uint32_t addr = (uint32_t) buffer;
TU_ASSERT( (addr & 0x3f) == 0, 0 );
return ( (addr >> 6) & 0xFFFFUL ) ;
}
TU_ATTR_ALWAYS_INLINE static inline uint8_t ep_addr2id(uint8_t ep_addr) {
return 2*(ep_addr & 0x0F) + ((ep_addr & TUSB_DIR_IN_MASK) ? 1 : 0);
}
TU_ATTR_ALWAYS_INLINE static inline bool ep_is_iso(ep_cmd_sts_t* ep_cs, bool is_highspeed) {
return is_highspeed ? (ep_cs[0].cmd_sts.type && !ep_cs[0].cmd_sts.rf_tv) : ep_cs->cmd_sts.type;
}
TU_ATTR_ALWAYS_INLINE static inline bool ep_is_bulk(ep_cmd_sts_t* ep_cs) {
return (ep_cs[0].cmd_sts.type == 0) && (ep_cs[0].cmd_sts.rf_tv == 0);
}
TU_ATTR_ALWAYS_INLINE static inline ep_cmd_sts_t* get_ep_cs(uint8_t ep_id) {
return _dcd.ep[ep_id];
}
TU_ATTR_ALWAYS_INLINE static inline bool rhport_is_highspeed(uint8_t rhport) {
return _dcd_controller[rhport].is_highspeed;
}
//--------------------------------------------------------------------+
// CONTROLLER API
//--------------------------------------------------------------------+
static void prepare_setup_packet(uint8_t rhport) {
uint16_t const buf_offset = get_buf_offset(_dcd.setup_packet);
if ( _dcd_controller[rhport].is_highspeed ) {
_dcd.ep[0][1].buffer_hs.offset = buf_offset;
} else {
_dcd.ep[0][1].buffer_fs.offset = buf_offset;
}
}
static void edpt_reset(uint8_t rhport, uint8_t ep_id)
{
(void) rhport;
tu_memclr(&_dcd.ep[ep_id], sizeof(_dcd.ep[ep_id]));
}
static void edpt_reset_all(uint8_t rhport)
{
for (uint8_t ep_id = 0; ep_id < 2*_dcd_controller[rhport].ep_pairs; ++ep_id)
{
edpt_reset(rhport, ep_id);
}
prepare_setup_packet(rhport);
}
void dcd_init(uint8_t rhport)
{
edpt_reset_all(rhport);
dcd_registers_t* dcd_reg = _dcd_controller[rhport].regs;
dcd_reg->EPLISTSTART = (uint32_t) _dcd.ep;
dcd_reg->DATABUFSTART = tu_align((uint32_t) &_dcd, TU_BIT(22)); // 22-bit alignment
dcd_reg->INTSTAT |= dcd_reg->INTSTAT; // clear all pending interrupt
dcd_reg->INTEN = INT_DEVICE_STATUS_MASK;
dcd_reg->DEVCMDSTAT |= DEVCMDSTAT_DEVICE_ENABLE_MASK | DEVCMDSTAT_DEVICE_CONNECT_MASK |
DEVCMDSTAT_RESET_CHANGE_MASK | DEVCMDSTAT_CONNECT_CHANGE_MASK | DEVCMDSTAT_SUSPEND_CHANGE_MASK;
NVIC_ClearPendingIRQ(_dcd_controller[rhport].irqnum);
}
void dcd_int_enable(uint8_t rhport)
{
NVIC_EnableIRQ(_dcd_controller[rhport].irqnum);
}
void dcd_int_disable(uint8_t rhport)
{
NVIC_DisableIRQ(_dcd_controller[rhport].irqnum);
}
void dcd_set_address(uint8_t rhport, uint8_t dev_addr)
{
dcd_registers_t* dcd_reg = _dcd_controller[rhport].regs;
// Response with status first before changing device address
dcd_edpt_xfer(rhport, tu_edpt_addr(0, TUSB_DIR_IN), NULL, 0);
dcd_reg->DEVCMDSTAT &= ~DEVCMDSTAT_DEVICE_ADDR_MASK;
dcd_reg->DEVCMDSTAT |= dev_addr;
}
void dcd_remote_wakeup(uint8_t rhport)
{
(void) rhport;
}
void dcd_connect(uint8_t rhport)
{
dcd_registers_t* dcd_reg = _dcd_controller[rhport].regs;
dcd_reg->DEVCMDSTAT |= DEVCMDSTAT_DEVICE_CONNECT_MASK;
}
void dcd_disconnect(uint8_t rhport)
{
dcd_registers_t* dcd_reg = _dcd_controller[rhport].regs;
dcd_reg->DEVCMDSTAT &= ~DEVCMDSTAT_DEVICE_CONNECT_MASK;
}
void dcd_sof_enable(uint8_t rhport, bool en)
{
(void) rhport;
(void) en;
// TODO implement later
}
//--------------------------------------------------------------------+
// DCD Endpoint Port
//--------------------------------------------------------------------+
void dcd_edpt_stall(uint8_t rhport, uint8_t ep_addr)
{
(void) rhport;
// TODO cannot able to STALL Control OUT endpoint !!!!! FIXME try some walk-around
uint8_t const ep_id = ep_addr2id(ep_addr);
_dcd.ep[ep_id][0].cmd_sts.stall = 1;
}
void dcd_edpt_clear_stall(uint8_t rhport, uint8_t ep_addr)
{
(void) rhport;
uint8_t const ep_id = ep_addr2id(ep_addr);
_dcd.ep[ep_id][0].cmd_sts.stall = 0;
_dcd.ep[ep_id][0].cmd_sts.toggle_reset = 1;
_dcd.ep[ep_id][0].cmd_sts.rf_tv = 0;
}
bool dcd_edpt_open(uint8_t rhport, tusb_desc_endpoint_t const * p_endpoint_desc)
{
//------------- Prepare Queue Head -------------//
uint8_t ep_id = ep_addr2id(p_endpoint_desc->bEndpointAddress);
ep_cmd_sts_t* ep_cs = get_ep_cs(ep_id);
// Check if endpoint is available
TU_ASSERT( ep_cs[0].cmd_sts.disable && ep_cs[1].cmd_sts.disable );
edpt_reset(rhport, ep_id);
switch (p_endpoint_desc->bmAttributes.xfer) {
case TUSB_XFER_ISOCHRONOUS:
ep_cs[0].cmd_sts.type = 1;
break;
case TUSB_XFER_INTERRUPT:
// What is interrupt endpoint in rate feedback mode ?
if ( rhport_is_highspeed(rhport) ) {
ep_cs[0].cmd_sts.type = 1;
ep_cs[0].cmd_sts.rf_tv = 1;
}
break;
case TUSB_XFER_BULK:
// nothing to do both type and rf_tv are 0
break;
default: break;
}
// Enable EP interrupt
dcd_registers_t* dcd_reg = _dcd_controller[rhport].regs;
dcd_reg->INTEN |= TU_BIT(ep_id);
return true;
}
void dcd_edpt_close_all (uint8_t rhport)
{
for (uint8_t ep_id = 0; ep_id < 2*_dcd_controller[rhport].ep_pairs; ++ep_id)
{
_dcd.ep[ep_id][0].cmd_sts.active = _dcd.ep[ep_id][0].cmd_sts.active = 0; // TODO proper way is to EPSKIP then wait ep[][].active then write ep[][].disable (see table 778 in LPC55S69 Use Manual)
_dcd.ep[ep_id][0].cmd_sts.disable = _dcd.ep[ep_id][1].cmd_sts.disable = 1;
}
}
void dcd_edpt_close(uint8_t rhport, uint8_t ep_addr)
{
(void) rhport;
uint8_t ep_id = ep_addr2id(ep_addr);
_dcd.ep[ep_id][0].cmd_sts.active = _dcd.ep[ep_id][0].cmd_sts.active = 0; // TODO proper way is to EPSKIP then wait ep[][].active then write ep[][].disable (see table 778 in LPC55S69 Use Manual)
_dcd.ep[ep_id][0].cmd_sts.disable = _dcd.ep[ep_id][1].cmd_sts.disable = 1;
}
static void prepare_ep_xfer(uint8_t rhport, uint8_t ep_id, uint16_t buf_offset, uint16_t total_bytes) {
uint16_t nbytes;
ep_cmd_sts_t* ep_cs = get_ep_cs(ep_id);
const bool is_iso = ep_is_iso(ep_cs, _dcd_controller[rhport].is_highspeed);
if ( rhport_is_highspeed(rhport) ) {
nbytes = tu_min16(total_bytes, is_iso ? NBYTES_ISO_HS_MAX : NBYTES_CBI_HS_MAX);
#if TU_CHECK_MCU(OPT_MCU_LPC54)
// LPC54 Errata USB.1: In USB high-speed device mode, the NBytes field does not decrement after BULK OUT transfer.
// Suggested Work-around: Program the NByte to the max packet size (512)
// Actual Work-around: round up NByte to multiple of 4.
// Note: this can cause buffer overflowed and corrupt data if host send more data than total_bytes
if ( (ep_id > 1) && (ep_id & 0x01) == 0 && ep_is_bulk(ep_cs) ) {
if ( nbytes & 0x03 ) {
nbytes = tu_align4(nbytes) + 4;
}
}
#endif
ep_cs[0].buffer_hs.offset = buf_offset;
ep_cs[0].buffer_hs.nbytes = nbytes;
}else {
nbytes = tu_min16(total_bytes, is_iso ? NBYTES_ISO_FS_MAX : NBYTES_CBI_FS_MAX);
ep_cs[0].buffer_fs.offset = buf_offset;
ep_cs[0].buffer_fs.nbytes = nbytes;
}
_dcd.dma[ep_id].nbytes = nbytes;
ep_cs[0].cmd_sts.active = 1;
}
bool dcd_edpt_xfer(uint8_t rhport, uint8_t ep_addr, uint8_t* buffer, uint16_t total_bytes) {
uint8_t const ep_id = ep_addr2id(ep_addr);
if (!buffer || total_bytes == 0) {
// Although having no data, ZLPs can cause buffer overwritten to zeroes. Probably due to USB/DMA controller side
// effect/bug. Assigned buffer offset to (valid) dummy to prevent overwriting to DATABUFSTART
buffer = (uint8_t *) (uint32_t) dummy;
}
tu_memclr(&_dcd.dma[ep_id], sizeof(xfer_dma_t));
_dcd.dma[ep_id].total_bytes = total_bytes;
prepare_ep_xfer(rhport, ep_id, get_buf_offset(buffer), total_bytes);
return true;
}
//--------------------------------------------------------------------+
// IRQ
//--------------------------------------------------------------------+
static void bus_reset(uint8_t rhport)
{
tu_memclr(&_dcd, sizeof(dcd_data_t));
edpt_reset_all(rhport);
// disable all endpoints as specified by LPC55S69 UM Table 778
for(uint8_t ep_id = 0; ep_id < 2*MAX_EP_PAIRS; ep_id++)
{
_dcd.ep[ep_id][0].cmd_sts.disable = _dcd.ep[ep_id][1].cmd_sts.disable = 1;
}
dcd_registers_t* dcd_reg = _dcd_controller[rhport].regs;
dcd_reg->EPINUSE = 0;
dcd_reg->EPBUFCFG = 0;
dcd_reg->EPSKIP = 0xFFFFFFFF;
dcd_reg->INTSTAT = dcd_reg->INTSTAT; // clear all pending interrupt
dcd_reg->DEVCMDSTAT |= DEVCMDSTAT_SETUP_RECEIVED_MASK; // clear setup received interrupt
dcd_reg->INTEN = INT_DEVICE_STATUS_MASK | TU_BIT(0) | TU_BIT(1); // enable device status & control endpoints
}
static void process_xfer_isr(uint8_t rhport, uint32_t int_status) {
uint8_t const max_ep = 2*_dcd_controller[rhport].ep_pairs;
for(uint8_t ep_id = 0; ep_id < max_ep; ep_id++ ) {
if ( tu_bit_test(int_status, ep_id) ) {
ep_cmd_sts_t * ep_cs = &_dcd.ep[ep_id][0];
xfer_dma_t* xfer_dma = &_dcd.dma[ep_id];
if ( ep_id <= 1 ) {
// For control endpoint, we need to manually clear Active bit
ep_cs->cmd_sts.active = 0;
}
uint16_t buf_offset;
uint16_t buf_nbytes;
if ( rhport_is_highspeed(rhport) ) {
buf_offset = ep_cs->buffer_hs.offset;
buf_nbytes = ep_cs->buffer_hs.nbytes;
#if TU_CHECK_MCU(OPT_MCU_LPC54)
// LPC54 Errata USB.2: In USB high-speed device mode, the NBytes field is not correct after BULK IN transfer
// There is no work-around. For EP in transfer, the NByte value can be ignored after a packet is transmitted.
if ( (ep_id > 1) && (ep_id & 0x01) == 1 && ep_is_bulk(ep_cs) ) {
buf_nbytes = 0;
}
#endif
} else {
buf_offset = ep_cs->buffer_fs.offset;
buf_nbytes = ep_cs->buffer_fs.nbytes;
}
xfer_dma->xferred_bytes += xfer_dma->nbytes - buf_nbytes;
if ( (buf_nbytes == 0) && (xfer_dma->total_bytes > xfer_dma->xferred_bytes) ) {
// There is more data to transfer
// buff_offset has been already increased by hw to correct value for next transfer
prepare_ep_xfer(rhport, ep_id, buf_offset, xfer_dma->total_bytes - xfer_dma->xferred_bytes);
} else {
// for detecting ZLP
xfer_dma->total_bytes = xfer_dma->xferred_bytes;
uint8_t const ep_addr = tu_edpt_addr(ep_id / 2, ep_id & 0x01);
// TODO no way determine if the transfer is failed or not
dcd_event_xfer_complete(rhport, ep_addr, xfer_dma->xferred_bytes, XFER_RESULT_SUCCESS, true);
}
}
}
}
void dcd_int_handler(uint8_t rhport)
{
dcd_registers_t* dcd_reg = _dcd_controller[rhport].regs;
uint32_t const cmd_stat = dcd_reg->DEVCMDSTAT;
uint32_t int_status = dcd_reg->INTSTAT & dcd_reg->INTEN;
dcd_reg->INTSTAT = int_status; // Acknowledge handled interrupt
if (int_status == 0) return;
//------------- Device Status -------------//
if ( int_status & INT_DEVICE_STATUS_MASK )
{
dcd_reg->DEVCMDSTAT |= DEVCMDSTAT_RESET_CHANGE_MASK | DEVCMDSTAT_CONNECT_CHANGE_MASK | DEVCMDSTAT_SUSPEND_CHANGE_MASK;
if ( cmd_stat & DEVCMDSTAT_RESET_CHANGE_MASK) // bus reset
{
bus_reset(rhport);
tusb_speed_t speed = TUSB_SPEED_FULL;
if ( _dcd_controller[rhport].is_highspeed ) {
// 0 : reserved, 1 : full, 2 : high, 3: super
if ( 2 == ((cmd_stat >> DEVCMDSTAT_SPEED_SHIFT) & 0x3UL) ) {
speed= TUSB_SPEED_HIGH;
}
}
dcd_event_bus_reset(rhport, speed, true);
}
if (cmd_stat & DEVCMDSTAT_CONNECT_CHANGE_MASK)
{
// device disconnect
if (cmd_stat & DEVCMDSTAT_DEVICE_ADDR_MASK)
{
// debouncing as this can be set when device is powering
dcd_event_bus_signal(rhport, DCD_EVENT_UNPLUGGED, true);
}
}
if (cmd_stat & DEVCMDSTAT_SUSPEND_CHANGE_MASK)
{
// suspend signal, bus idle for more than 3ms
// Note: Host may delay more than 3 ms before and/or after bus reset before doing enumeration.
if (cmd_stat & DEVCMDSTAT_DEVICE_ADDR_MASK)
{
dcd_event_bus_signal(rhport, (cmd_stat & DEVCMDSTAT_DEVICE_SUSPEND_MASK) ? DCD_EVENT_SUSPEND : DCD_EVENT_RESUME, true);
}
}
}
// Setup Receive
if ( tu_bit_test(int_status, 0) && (cmd_stat & DEVCMDSTAT_SETUP_RECEIVED_MASK) )
{
// Follow UM flowchart to clear Active & Stall on both Control IN/OUT endpoints
_dcd.ep[0][0].cmd_sts.active = _dcd.ep[1][0].cmd_sts.active = 0;
_dcd.ep[0][0].cmd_sts.stall = _dcd.ep[1][0].cmd_sts.stall = 0;
dcd_reg->DEVCMDSTAT |= DEVCMDSTAT_SETUP_RECEIVED_MASK;
dcd_event_setup_received(rhport, _dcd.setup_packet, true);
// keep waiting for next setup
prepare_setup_packet(rhport);
// clear bit0
int_status = tu_bit_clear(int_status, 0);
}
// Endpoint transfer complete interrupt
process_xfer_isr(rhport, int_status);
}
#endif
|
bfac2ab8b6e8f8617af7cee3fa6013e17c0d4967
|
9907672fcd81ab73ac63b2a83422a82bf31eadde
|
/tyama_icpc2003dC(PKU2030-TJU2678-ZJU1717-aizu1126)_shorter.c
|
46b16d22cd0f5ded4b8a3e837179726e39f66702
|
[
"0BSD"
] |
permissive
|
cielavenir/procon
|
bbe1974b9bddb51b76d58722a0686a5b477c4456
|
746e1a91f574f20647e8aaaac0d9e6173f741176
|
refs/heads/master
| 2023-06-21T23:11:24.562546
| 2023-06-11T13:15:15
| 2023-06-11T13:15:15
| 7,557,464
| 137
| 136
| null | 2020-10-20T09:35:52
| 2013-01-11T09:40:26
|
C++
|
UTF-8
|
C
| false
| false
| 595
|
c
|
tyama_icpc2003dC(PKU2030-TJU2678-ZJU1717-aizu1126)_shorter.c
|
#define M 100
char m[M][M],s[M][M][M],r[M],*z;
cmp(char *p,char *q){
for(;*p=='0';p++);for(;*q=='0';q++);
return (z=strlen(p)-strlen(q))?z:strcmp(p,q);
}
main(w,h,i,j,k,l){
for(;scanf("%d%d",&w,&h),w;puts(z)){
for(memset(s,0,sizeof(s)),*r=0,j=1;j<=h;j++)scanf("%s",m[j]+1);
for(i=1;i<=w;i++)for(j=1;j<=h;j++){
if(!isdigit(m[j][i]))continue;
if(cmp(s[j][i-1],s[j-1][i])>0)strcpy(s[j][i],s[j][i-1]),s[j][i][strlen(s[j][i])]=m[j][i];
else strcpy(s[j][i],s[j-1][i]),s[j][i][strlen(s[j][i])]=m[j][i];
if(cmp(s[j][i],r)>0)strcpy(r,s[j][i]);
}
for(z=r;*z=='0';z++);
}
return 0;}
|
fb7d54ce922968b300dc42d655aad44973f8aff5
|
7eaf54a78c9e2117247cb2ab6d3a0c20719ba700
|
/SOFTWARE/A64-TERES/linux-a64/arch/sh/kernel/cpu/sh2/setup-sh7619.c
|
e0b740c831c7e172f42beb3c8ce957d9a22bb032
|
[
"LicenseRef-scancode-free-unknown",
"Apache-2.0",
"Linux-syscall-note",
"GPL-2.0-only",
"GPL-1.0-or-later"
] |
permissive
|
OLIMEX/DIY-LAPTOP
|
ae82f4ee79c641d9aee444db9a75f3f6709afa92
|
a3fafd1309135650bab27f5eafc0c32bc3ca74ee
|
refs/heads/rel3
| 2023-08-04T01:54:19.483792
| 2023-04-03T07:18:12
| 2023-04-03T07:18:12
| 80,094,055
| 507
| 92
|
Apache-2.0
| 2023-04-03T07:05:59
| 2017-01-26T07:25:50
|
C
|
UTF-8
|
C
| false
| false
| 5,479
|
c
|
setup-sh7619.c
|
/*
* SH7619 Setup
*
* Copyright (C) 2006 Yoshinori Sato
* Copyright (C) 2009 Paul Mundt
*
* This file is subject to the terms and conditions of the GNU General Public
* License. See the file "COPYING" in the main directory of this archive
* for more details.
*/
#include <linux/platform_device.h>
#include <linux/init.h>
#include <linux/serial.h>
#include <linux/serial_sci.h>
#include <linux/sh_timer.h>
#include <linux/io.h>
enum {
UNUSED = 0,
/* interrupt sources */
IRQ0, IRQ1, IRQ2, IRQ3, IRQ4, IRQ5, IRQ6, IRQ7,
WDT, EDMAC, CMT0, CMT1,
SCIF0, SCIF1, SCIF2,
HIF_HIFI, HIF_HIFBI,
DMAC0, DMAC1, DMAC2, DMAC3,
SIOF,
};
static struct intc_vect vectors[] __initdata = {
INTC_IRQ(IRQ0, 64), INTC_IRQ(IRQ1, 65),
INTC_IRQ(IRQ2, 66), INTC_IRQ(IRQ3, 67),
INTC_IRQ(IRQ4, 80), INTC_IRQ(IRQ5, 81),
INTC_IRQ(IRQ6, 82), INTC_IRQ(IRQ7, 83),
INTC_IRQ(WDT, 84), INTC_IRQ(EDMAC, 85),
INTC_IRQ(CMT0, 86), INTC_IRQ(CMT1, 87),
INTC_IRQ(SCIF0, 88), INTC_IRQ(SCIF0, 89),
INTC_IRQ(SCIF0, 90), INTC_IRQ(SCIF0, 91),
INTC_IRQ(SCIF1, 92), INTC_IRQ(SCIF1, 93),
INTC_IRQ(SCIF1, 94), INTC_IRQ(SCIF1, 95),
INTC_IRQ(SCIF2, 96), INTC_IRQ(SCIF2, 97),
INTC_IRQ(SCIF2, 98), INTC_IRQ(SCIF2, 99),
INTC_IRQ(HIF_HIFI, 100), INTC_IRQ(HIF_HIFBI, 101),
INTC_IRQ(DMAC0, 104), INTC_IRQ(DMAC1, 105),
INTC_IRQ(DMAC2, 106), INTC_IRQ(DMAC3, 107),
INTC_IRQ(SIOF, 108),
};
static struct intc_prio_reg prio_registers[] __initdata = {
{ 0xf8140006, 0, 16, 4, /* IPRA */ { IRQ0, IRQ1, IRQ2, IRQ3 } },
{ 0xf8140008, 0, 16, 4, /* IPRB */ { IRQ4, IRQ5, IRQ6, IRQ7 } },
{ 0xf8080000, 0, 16, 4, /* IPRC */ { WDT, EDMAC, CMT0, CMT1 } },
{ 0xf8080002, 0, 16, 4, /* IPRD */ { SCIF0, SCIF1, SCIF2 } },
{ 0xf8080004, 0, 16, 4, /* IPRE */ { HIF_HIFI, HIF_HIFBI } },
{ 0xf8080006, 0, 16, 4, /* IPRF */ { DMAC0, DMAC1, DMAC2, DMAC3 } },
{ 0xf8080008, 0, 16, 4, /* IPRG */ { SIOF } },
};
static DECLARE_INTC_DESC(intc_desc, "sh7619", vectors, NULL,
NULL, prio_registers, NULL);
static struct plat_sci_port scif0_platform_data = {
.mapbase = 0xf8400000,
.flags = UPF_BOOT_AUTOCONF,
.scscr = SCSCR_RE | SCSCR_TE | SCSCR_REIE,
.scbrr_algo_id = SCBRR_ALGO_2,
.type = PORT_SCIF,
.irqs = SCIx_IRQ_MUXED(88),
};
static struct platform_device scif0_device = {
.name = "sh-sci",
.id = 0,
.dev = {
.platform_data = &scif0_platform_data,
},
};
static struct plat_sci_port scif1_platform_data = {
.mapbase = 0xf8410000,
.flags = UPF_BOOT_AUTOCONF,
.scscr = SCSCR_RE | SCSCR_TE | SCSCR_REIE,
.scbrr_algo_id = SCBRR_ALGO_2,
.type = PORT_SCIF,
.irqs = SCIx_IRQ_MUXED(92),
};
static struct platform_device scif1_device = {
.name = "sh-sci",
.id = 1,
.dev = {
.platform_data = &scif1_platform_data,
},
};
static struct plat_sci_port scif2_platform_data = {
.mapbase = 0xf8420000,
.flags = UPF_BOOT_AUTOCONF,
.scscr = SCSCR_RE | SCSCR_TE | SCSCR_REIE,
.scbrr_algo_id = SCBRR_ALGO_2,
.type = PORT_SCIF,
.irqs = SCIx_IRQ_MUXED(96),
};
static struct platform_device scif2_device = {
.name = "sh-sci",
.id = 2,
.dev = {
.platform_data = &scif2_platform_data,
},
};
static struct resource eth_resources[] = {
[0] = {
.start = 0xfb000000,
.end = 0xfb0001c8,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = 85,
.end = 85,
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device eth_device = {
.name = "sh-eth",
.id = -1,
.dev = {
.platform_data = (void *)1,
},
.num_resources = ARRAY_SIZE(eth_resources),
.resource = eth_resources,
};
static struct sh_timer_config cmt0_platform_data = {
.channel_offset = 0x02,
.timer_bit = 0,
.clockevent_rating = 125,
.clocksource_rating = 0, /* disabled due to code generation issues */
};
static struct resource cmt0_resources[] = {
[0] = {
.start = 0xf84a0072,
.end = 0xf84a0077,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = 86,
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device cmt0_device = {
.name = "sh_cmt",
.id = 0,
.dev = {
.platform_data = &cmt0_platform_data,
},
.resource = cmt0_resources,
.num_resources = ARRAY_SIZE(cmt0_resources),
};
static struct sh_timer_config cmt1_platform_data = {
.channel_offset = 0x08,
.timer_bit = 1,
.clockevent_rating = 125,
.clocksource_rating = 0, /* disabled due to code generation issues */
};
static struct resource cmt1_resources[] = {
[0] = {
.start = 0xf84a0078,
.end = 0xf84a007d,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = 87,
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device cmt1_device = {
.name = "sh_cmt",
.id = 1,
.dev = {
.platform_data = &cmt1_platform_data,
},
.resource = cmt1_resources,
.num_resources = ARRAY_SIZE(cmt1_resources),
};
static struct platform_device *sh7619_devices[] __initdata = {
&scif0_device,
&scif1_device,
&scif2_device,
ð_device,
&cmt0_device,
&cmt1_device,
};
static int __init sh7619_devices_setup(void)
{
return platform_add_devices(sh7619_devices,
ARRAY_SIZE(sh7619_devices));
}
arch_initcall(sh7619_devices_setup);
void __init plat_irq_setup(void)
{
register_intc_controller(&intc_desc);
}
static struct platform_device *sh7619_early_devices[] __initdata = {
&scif0_device,
&scif1_device,
&scif2_device,
&cmt0_device,
&cmt1_device,
};
#define STBCR3 0xf80a0000
void __init plat_early_device_setup(void)
{
/* enable CMT clock */
__raw_writeb(__raw_readb(STBCR3) & ~0x10, STBCR3);
early_platform_add_devices(sh7619_early_devices,
ARRAY_SIZE(sh7619_early_devices));
}
|
cb8226b89ca19feb78e253358c0004cc83e8b84f
|
e683a0b8dbb87c7ceb99e0d06896174a559d2c67
|
/Library/Trans/Graphics/Bitmap/Tif/ExportC/cpt4.c
|
431ab317bc24154a99e987a836e411c21e973880
|
[
"Apache-2.0"
] |
permissive
|
bluewaysw/pcgeos
|
f093d79567d977d992f47065056d14d5a04b9f14
|
c6ae4c8e77b54b9ff654c3916f2191f8b1a1b65d
|
refs/heads/master
| 2023-08-31T00:17:54.481175
| 2023-08-29T19:00:49
| 2023-08-29T19:00:49
| 157,968,410
| 603
| 88
|
Apache-2.0
| 2023-09-13T07:44:06
| 2018-11-17T09:09:55
|
Assembly
|
UTF-8
|
C
| false
| false
| 4,138
|
c
|
cpt4.c
|
/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Copyright (c) GeoWorks 1992 -- All Rights Reserved
PROJECT: PC GEOS
MODULE:
FILE: cpt4.c
AUTHOR: Maryann Simmons, Feb 13, 1992
METHODS:
Name Description
---- -----------
FUNCTIONS:
Scope Name Description
----- ---- -----------
REVISION HISTORY:
Name Date Description
---- ---- -----------
MS 2/13/92 Initial version.
DESCRIPTION:
$Id: cpt4.c,v 1.1 97/04/07 11:27:35 newdeal Exp $
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
/*
----- Copyright(c), 1990-91 Halcyon Software -----
cpt4.c
Description
Compression algorithm according to CCITT group 3 table T4
*/
#include "hsimem.h"
#include "hsierror.h"
#include <Ansi/stdio.h>
#include "hsidib.h"
#include <Ansi/string.h>
#define BLACK 1
#define WHITE 0;
#define FLUSH 1
#define NOFLUSH 0
#include "ccitt.h"
/* function prototypes */
int FAR _NextBlack (LPSTR, int, int);
int FAR _NextWhite (LPSTR, int, int);
int cPutBits (LPSTR dst, int pos, T4 FAR *codeptr);
int cEncodeT4 (LPSTR dst, int bitpos, int bitcnt, T4 FAR *table);
/*
Put the byte value in the buffer according to bit offset
and number of bits.
*/
WORD WORDPatternAND[]=
{
0x8000, 0x4000, 0x2000, 0x1000,
0x0800, 0x0400, 0x0200, 0x0100,
0x0080, 0x0040, 0x0020, 0x0010,
0x0008, 0x0004, 0x0002, 0x0001
};
int cPutBits( LPSTR dst, int pos, T4 FAR *codeptr )
{
int i;
int j;
j = 16 - codeptr->bc;
for ( i=0; i < codeptr->bc ; i++ )
{
if ( codeptr->cd & (WORD)WORDPatternAND[ j + i ] )
dst[(pos+i)/8] |= BitPatternOr[(pos+i)%8];
}
return (pos+codeptr->bc);
}
int
cEncodeT4( LPSTR dst, int bitpos, int bitcnt, T4 FAR *table)
{
T4 FAR *ptr;
int terminator, makeup;
// Encoding the scan line
terminator = bitcnt & 0x3f;
makeup = 0;
if ( bitcnt >= 64 )
makeup = bitcnt/64 + 63;
// encode the makeup code first if any
if ( makeup )
{
ptr = table + makeup;
bitpos = cPutBits( dst, bitpos, ptr );
}
// then the terminator code which is a must
ptr = table + terminator;
bitpos = cPutBits( dst, bitpos, ptr );
return( bitpos );
}
/*
Compress one scanline data to CCITT G3 format. Make sure the dst
is zapped before coming to this routine, since it might contain
left over from previous run.
*/
int
cpt4 (
LPSTR dst, // output buffer
LPSTR src, // input buffer
WORD maxbits ) // image width in pixel
{
int crnsrc, nxtsrc/*, last*/;
int nxtdst=0, i;
/*BYTE zero=0x00;*/
crnsrc = nxtsrc = 0;
for (i=0; i < (maxbits+7)/8;i++) // invert the input string, since
src[i] = ~src[i]; // ccitt treat 1 as black, 0 as
// white
while ( 1 )
{
if ( nxtsrc < maxbits )
{
// get the WHITE run
nxtsrc = _NextBlack( src, crnsrc, maxbits );
// write out the WHITE run code word
nxtdst = cEncodeT4( dst, nxtdst, nxtsrc-crnsrc,(T4 FAR*)wht );
crnsrc = nxtsrc;
}
else
{
// no more bit to process
/*last = WHITE;*/
break;
}
if ( nxtsrc < maxbits )
{
// do the BLACK run
nxtsrc = _NextWhite( src, crnsrc, maxbits );
// write out the BLACK run code word
nxtdst = cEncodeT4( dst, nxtdst, nxtsrc-crnsrc,(T4 FAR *)blk );
crnsrc = nxtsrc;
}
else
{
/*last = BLACK;*/
break;
}
}
/* donot append EOL if maxbits has reached
if ( nxtsrc != maxbits )
nxtdst = cPutBits( dst, nxtdst, (wht+whtcnt-1) );
*/
return( nxtdst );
}
|
b06fcc8795ce5e64fb3bf2a0500ede2bcf776509
|
d2253070a3a64b14dee5ca0b3d311919178e590c
|
/include/constants/battle.h
|
ac83feb3a0567142a4ebcd4ed10192694102535a
|
[] |
no_license
|
pret/pokeemerald
|
ce232eccdde78502f3c251d672b26af3e1d7e508
|
d67914e114c937c4c80ce128ddc5523d4dc2cd40
|
refs/heads/master
| 2023-08-31T11:23:13.877932
| 2023-08-27T23:40:59
| 2023-08-27T23:40:59
| 43,677,244
| 1,944
| 1,903
| null | 2023-09-12T22:48:06
| 2015-10-05T10:09:22
|
C
|
UTF-8
|
C
| false
| false
| 17,708
|
h
|
battle.h
|
#ifndef GUARD_CONSTANTS_BATTLE_H
#define GUARD_CONSTANTS_BATTLE_H
/*
* A battler may be in one of four positions on the field. The first bit determines
* what side the battler is on, either the player's side or the opponent's side.
* The second bit determines what flank the battler is on, either the left or right.
* Note that the opponent's flanks are drawn corresponding to their perspective, so
* their right mon appears on the left, and their left mon appears on the right.
* The battler ID is usually the same as the position, except in the case of link battles.
*
* + ------------------------- +
* | Opponent's side |
* | Right Left |
* | 3 1 |
* | |
* | Player's side |
* | Left Right |
* | 0 2 |
* ----------------------------+
* | |
* | |
* +---------------------------+
*/
#define MAX_BATTLERS_COUNT 4
#define B_POSITION_PLAYER_LEFT 0
#define B_POSITION_OPPONENT_LEFT 1
#define B_POSITION_PLAYER_RIGHT 2
#define B_POSITION_OPPONENT_RIGHT 3
// These macros can be used with either battler ID or positions to get the partner or the opposite mon
#define BATTLE_OPPOSITE(id) ((id) ^ BIT_SIDE)
#define BATTLE_PARTNER(id) ((id) ^ BIT_FLANK)
#define B_SIDE_PLAYER 0
#define B_SIDE_OPPONENT 1
#define NUM_BATTLE_SIDES 2
#define B_FLANK_LEFT 0
#define B_FLANK_RIGHT 1
#define BIT_SIDE 1
#define BIT_FLANK 2
// Battle Type Flags
#define BATTLE_TYPE_DOUBLE (1 << 0)
#define BATTLE_TYPE_LINK (1 << 1)
#define BATTLE_TYPE_IS_MASTER (1 << 2) // In not-link battles, it's always set.
#define BATTLE_TYPE_TRAINER (1 << 3)
#define BATTLE_TYPE_FIRST_BATTLE (1 << 4)
#define BATTLE_TYPE_LINK_IN_BATTLE (1 << 5) // Set on battle entry, cleared on exit. Checked rarely
#define BATTLE_TYPE_MULTI (1 << 6)
#define BATTLE_TYPE_SAFARI (1 << 7)
#define BATTLE_TYPE_BATTLE_TOWER (1 << 8)
#define BATTLE_TYPE_WALLY_TUTORIAL (1 << 9) // Used in pokefirered as BATTLE_TYPE_OLD_MAN_TUTORIAL.
#define BATTLE_TYPE_ROAMER (1 << 10)
#define BATTLE_TYPE_EREADER_TRAINER (1 << 11)
#define BATTLE_TYPE_KYOGRE_GROUDON (1 << 12)
#define BATTLE_TYPE_LEGENDARY (1 << 13)
#define BATTLE_TYPE_REGI (1 << 14)
#define BATTLE_TYPE_TWO_OPPONENTS (1 << 15) // Used in pokefirered as BATTLE_TYPE_GHOST.
#define BATTLE_TYPE_DOME (1 << 16) // Used in pokefirered as BATTLE_TYPE_POKEDUDE.
#define BATTLE_TYPE_PALACE (1 << 17) // Used in pokefirered as BATTLE_TYPE_WILD_SCRIPTED.
#define BATTLE_TYPE_ARENA (1 << 18) // Used in pokefirered as BATTLE_TYPE_LEGENDARY_FRLG.
#define BATTLE_TYPE_FACTORY (1 << 19) // Used in pokefirered as BATTLE_TYPE_TRAINER_TOWER.
#define BATTLE_TYPE_PIKE (1 << 20)
#define BATTLE_TYPE_PYRAMID (1 << 21)
#define BATTLE_TYPE_INGAME_PARTNER (1 << 22)
#define BATTLE_TYPE_TOWER_LINK_MULTI (1 << 23)
#define BATTLE_TYPE_RECORDED (1 << 24)
#define BATTLE_TYPE_RECORDED_LINK (1 << 25)
#define BATTLE_TYPE_TRAINER_HILL (1 << 26)
#define BATTLE_TYPE_SECRET_BASE (1 << 27)
#define BATTLE_TYPE_GROUDON (1 << 28)
#define BATTLE_TYPE_KYOGRE (1 << 29)
#define BATTLE_TYPE_RAYQUAZA (1 << 30)
#define BATTLE_TYPE_RECORDED_IS_MASTER (1 << 31)
#define BATTLE_TYPE_FRONTIER (BATTLE_TYPE_BATTLE_TOWER | BATTLE_TYPE_DOME | BATTLE_TYPE_PALACE | BATTLE_TYPE_ARENA | BATTLE_TYPE_FACTORY | BATTLE_TYPE_PIKE | BATTLE_TYPE_PYRAMID)
#define BATTLE_TYPE_FRONTIER_NO_PYRAMID (BATTLE_TYPE_BATTLE_TOWER | BATTLE_TYPE_DOME | BATTLE_TYPE_PALACE | BATTLE_TYPE_ARENA | BATTLE_TYPE_FACTORY | BATTLE_TYPE_PIKE)
#define BATTLE_TYPE_RECORDED_INVALID ((BATTLE_TYPE_LINK | BATTLE_TYPE_SAFARI | BATTLE_TYPE_FIRST_BATTLE \
| BATTLE_TYPE_WALLY_TUTORIAL | BATTLE_TYPE_ROAMER | BATTLE_TYPE_EREADER_TRAINER \
| BATTLE_TYPE_KYOGRE_GROUDON | BATTLE_TYPE_LEGENDARY | BATTLE_TYPE_REGI \
| BATTLE_TYPE_RECORDED | BATTLE_TYPE_TRAINER_HILL | BATTLE_TYPE_SECRET_BASE \
| BATTLE_TYPE_GROUDON | BATTLE_TYPE_KYOGRE | BATTLE_TYPE_RAYQUAZA))
// Battle Outcome defines
#define B_OUTCOME_WON 1
#define B_OUTCOME_LOST 2
#define B_OUTCOME_DREW 3
#define B_OUTCOME_RAN 4
#define B_OUTCOME_PLAYER_TELEPORTED 5
#define B_OUTCOME_MON_FLED 6
#define B_OUTCOME_CAUGHT 7
#define B_OUTCOME_NO_SAFARI_BALLS 8
#define B_OUTCOME_FORFEITED 9
#define B_OUTCOME_MON_TELEPORTED 10
#define B_OUTCOME_LINK_BATTLE_RAN (1 << 7) // 128
// Non-volatile status conditions
// These persist remain outside of battle and after switching out
#define STATUS1_NONE 0
#define STATUS1_SLEEP (1 << 0 | 1 << 1 | 1 << 2) // First 3 bits (Number of turns to sleep)
#define STATUS1_SLEEP_TURN(num) ((num) << 0) // Just for readability (or if rearranging statuses)
#define STATUS1_POISON (1 << 3)
#define STATUS1_BURN (1 << 4)
#define STATUS1_FREEZE (1 << 5)
#define STATUS1_PARALYSIS (1 << 6)
#define STATUS1_TOXIC_POISON (1 << 7)
#define STATUS1_TOXIC_COUNTER (1 << 8 | 1 << 9 | 1 << 10 | 1 << 11)
#define STATUS1_TOXIC_TURN(num) ((num) << 8)
#define STATUS1_PSN_ANY (STATUS1_POISON | STATUS1_TOXIC_POISON)
#define STATUS1_ANY (STATUS1_SLEEP | STATUS1_POISON | STATUS1_BURN | STATUS1_FREEZE | STATUS1_PARALYSIS | STATUS1_TOXIC_POISON)
// Volatile status ailments
// These are removed after exiting the battle or switching out
#define STATUS2_CONFUSION (1 << 0 | 1 << 1 | 1 << 2)
#define STATUS2_CONFUSION_TURN(num) ((num) << 0)
#define STATUS2_FLINCHED (1 << 3)
#define STATUS2_UPROAR (1 << 4 | 1 << 5 | 1 << 6)
#define STATUS2_UPROAR_TURN(num) ((num) << 4)
#define STATUS2_UNUSED (1 << 7)
#define STATUS2_BIDE (1 << 8 | 1 << 9)
#define STATUS2_BIDE_TURN(num) (((num) << 8) & STATUS2_BIDE)
#define STATUS2_LOCK_CONFUSE (1 << 10 | 1 << 11) // e.g. Thrash
#define STATUS2_LOCK_CONFUSE_TURN(num)((num) << 10)
#define STATUS2_MULTIPLETURNS (1 << 12)
#define STATUS2_WRAPPED (1 << 13 | 1 << 14 | 1 << 15)
#define STATUS2_WRAPPED_TURN(num) ((num) << 13)
#define STATUS2_INFATUATION (1 << 16 | 1 << 17 | 1 << 18 | 1 << 19) // 4 bits, one for every battler
#define STATUS2_INFATUATED_WITH(battler) (gBitTable[battler] << 16)
#define STATUS2_FOCUS_ENERGY (1 << 20)
#define STATUS2_TRANSFORMED (1 << 21)
#define STATUS2_RECHARGE (1 << 22)
#define STATUS2_RAGE (1 << 23)
#define STATUS2_SUBSTITUTE (1 << 24)
#define STATUS2_DESTINY_BOND (1 << 25)
#define STATUS2_ESCAPE_PREVENTION (1 << 26)
#define STATUS2_NIGHTMARE (1 << 27)
#define STATUS2_CURSED (1 << 28)
#define STATUS2_FORESIGHT (1 << 29)
#define STATUS2_DEFENSE_CURL (1 << 30)
#define STATUS2_TORMENT (1 << 31)
// Seems like per-battler statuses. Not quite sure how to categorize these
#define STATUS3_LEECHSEED_BATTLER (1 << 0 | 1 << 1) // The battler to receive HP from Leech Seed
#define STATUS3_LEECHSEED (1 << 2)
#define STATUS3_ALWAYS_HITS (1 << 3 | 1 << 4)
#define STATUS3_ALWAYS_HITS_TURN(num) (((num) << 3) & STATUS3_ALWAYS_HITS) // "Always Hits" is set as a 2 turn timer, i.e. next turn is the last turn when it's active
#define STATUS3_PERISH_SONG (1 << 5)
#define STATUS3_ON_AIR (1 << 6)
#define STATUS3_UNDERGROUND (1 << 7)
#define STATUS3_MINIMIZED (1 << 8)
#define STATUS3_CHARGED_UP (1 << 9)
#define STATUS3_ROOTED (1 << 10)
#define STATUS3_YAWN (1 << 11 | 1 << 12) // Number of turns to sleep
#define STATUS3_YAWN_TURN(num) (((num) << 11) & STATUS3_YAWN)
#define STATUS3_IMPRISONED_OTHERS (1 << 13)
#define STATUS3_GRUDGE (1 << 14)
#define STATUS3_CANT_SCORE_A_CRIT (1 << 15)
#define STATUS3_MUDSPORT (1 << 16)
#define STATUS3_WATERSPORT (1 << 17)
#define STATUS3_UNDERWATER (1 << 18)
#define STATUS3_INTIMIDATE_POKES (1 << 19)
#define STATUS3_TRACE (1 << 20)
#define STATUS3_SEMI_INVULNERABLE (STATUS3_UNDERGROUND | STATUS3_ON_AIR | STATUS3_UNDERWATER)
// Not really sure what a "hitmarker" is.
#define HITMARKER_WAKE_UP_CLEAR (1 << 4) // Cleared when waking up. Never set or checked.
#define HITMARKER_SKIP_DMG_TRACK (1 << 5)
#define HITMARKER_DESTINYBOND (1 << 6)
#define HITMARKER_NO_ANIMATIONS (1 << 7)
#define HITMARKER_IGNORE_SUBSTITUTE (1 << 8)
#define HITMARKER_NO_ATTACKSTRING (1 << 9)
#define HITMARKER_ATTACKSTRING_PRINTED (1 << 10)
#define HITMARKER_NO_PPDEDUCT (1 << 11)
#define HITMARKER_SWAP_ATTACKER_TARGET (1 << 12)
#define HITMARKER_IGNORE_SAFEGUARD (1 << 13)
#define HITMARKER_SYNCHRONISE_EFFECT (1 << 14)
#define HITMARKER_RUN (1 << 15)
#define HITMARKER_IGNORE_ON_AIR (1 << 16)
#define HITMARKER_IGNORE_UNDERGROUND (1 << 17)
#define HITMARKER_IGNORE_UNDERWATER (1 << 18)
#define HITMARKER_UNABLE_TO_USE_MOVE (1 << 19)
#define HITMARKER_PASSIVE_DAMAGE (1 << 20)
#define HITMARKER_DISOBEDIENT_MOVE (1 << 21)
#define HITMARKER_PLAYER_FAINTED (1 << 22)
#define HITMARKER_ALLOW_NO_PP (1 << 23)
#define HITMARKER_GRUDGE (1 << 24)
#define HITMARKER_OBEYS (1 << 25)
#define HITMARKER_NEVER_SET (1 << 26) // Cleared as part of a large group. Never set or checked
#define HITMARKER_CHARGING (1 << 27)
#define HITMARKER_FAINTED(battler) (gBitTable[battler] << 28)
#define HITMARKER_FAINTED2(battler) ((1 << 28) << battler)
// Per-side statuses that affect an entire party
#define SIDE_STATUS_REFLECT (1 << 0)
#define SIDE_STATUS_LIGHTSCREEN (1 << 1)
#define SIDE_STATUS_X4 (1 << 2)
#define SIDE_STATUS_SPIKES (1 << 4)
#define SIDE_STATUS_SAFEGUARD (1 << 5)
#define SIDE_STATUS_FUTUREATTACK (1 << 6)
#define SIDE_STATUS_MIST (1 << 8)
#define SIDE_STATUS_SPIKES_DAMAGED (1 << 9)
// Flags describing move's result
#define MOVE_RESULT_MISSED (1 << 0)
#define MOVE_RESULT_SUPER_EFFECTIVE (1 << 1)
#define MOVE_RESULT_NOT_VERY_EFFECTIVE (1 << 2)
#define MOVE_RESULT_DOESNT_AFFECT_FOE (1 << 3)
#define MOVE_RESULT_ONE_HIT_KO (1 << 4)
#define MOVE_RESULT_FAILED (1 << 5)
#define MOVE_RESULT_FOE_ENDURED (1 << 6)
#define MOVE_RESULT_FOE_HUNG_ON (1 << 7)
#define MOVE_RESULT_NO_EFFECT (MOVE_RESULT_MISSED | MOVE_RESULT_DOESNT_AFFECT_FOE | MOVE_RESULT_FAILED)
// Battle Weather flags
#define B_WEATHER_RAIN_TEMPORARY (1 << 0)
#define B_WEATHER_RAIN_DOWNPOUR (1 << 1) // unused
#define B_WEATHER_RAIN_PERMANENT (1 << 2)
#define B_WEATHER_RAIN (B_WEATHER_RAIN_TEMPORARY | B_WEATHER_RAIN_DOWNPOUR | B_WEATHER_RAIN_PERMANENT)
#define B_WEATHER_SANDSTORM_TEMPORARY (1 << 3)
#define B_WEATHER_SANDSTORM_PERMANENT (1 << 4)
#define B_WEATHER_SANDSTORM (B_WEATHER_SANDSTORM_TEMPORARY | B_WEATHER_SANDSTORM_PERMANENT)
#define B_WEATHER_SUN_TEMPORARY (1 << 5)
#define B_WEATHER_SUN_PERMANENT (1 << 6)
#define B_WEATHER_SUN (B_WEATHER_SUN_TEMPORARY | B_WEATHER_SUN_PERMANENT)
#define B_WEATHER_HAIL_TEMPORARY (1 << 7)
#define B_WEATHER_HAIL (B_WEATHER_HAIL_TEMPORARY)
#define B_WEATHER_ANY (B_WEATHER_RAIN | B_WEATHER_SANDSTORM | B_WEATHER_SUN | B_WEATHER_HAIL)
// Move Effects
#define MOVE_EFFECT_SLEEP 1
#define MOVE_EFFECT_POISON 2
#define MOVE_EFFECT_BURN 3
#define MOVE_EFFECT_FREEZE 4
#define MOVE_EFFECT_PARALYSIS 5
#define MOVE_EFFECT_TOXIC 6
#define PRIMARY_STATUS_MOVE_EFFECT MOVE_EFFECT_TOXIC // All above move effects apply primary status
#define MOVE_EFFECT_CONFUSION 7
#define MOVE_EFFECT_FLINCH 8
#define MOVE_EFFECT_TRI_ATTACK 9
#define MOVE_EFFECT_UPROAR 10
#define MOVE_EFFECT_PAYDAY 11
#define MOVE_EFFECT_CHARGING 12
#define MOVE_EFFECT_WRAP 13
#define MOVE_EFFECT_RECOIL_25 14
#define MOVE_EFFECT_ATK_PLUS_1 15
#define MOVE_EFFECT_DEF_PLUS_1 16
#define MOVE_EFFECT_SPD_PLUS_1 17
#define MOVE_EFFECT_SP_ATK_PLUS_1 18
#define MOVE_EFFECT_SP_DEF_PLUS_1 19
#define MOVE_EFFECT_ACC_PLUS_1 20
#define MOVE_EFFECT_EVS_PLUS_1 21
#define MOVE_EFFECT_ATK_MINUS_1 22
#define MOVE_EFFECT_DEF_MINUS_1 23
#define MOVE_EFFECT_SPD_MINUS_1 24
#define MOVE_EFFECT_SP_ATK_MINUS_1 25
#define MOVE_EFFECT_SP_DEF_MINUS_1 26
#define MOVE_EFFECT_ACC_MINUS_1 27
#define MOVE_EFFECT_EVS_MINUS_1 28
#define MOVE_EFFECT_RECHARGE 29
#define MOVE_EFFECT_RAGE 30
#define MOVE_EFFECT_STEAL_ITEM 31
#define MOVE_EFFECT_PREVENT_ESCAPE 32
#define MOVE_EFFECT_NIGHTMARE 33
#define MOVE_EFFECT_ALL_STATS_UP 34
#define MOVE_EFFECT_RAPIDSPIN 35
#define MOVE_EFFECT_REMOVE_PARALYSIS 36
#define MOVE_EFFECT_ATK_DEF_DOWN 37
#define MOVE_EFFECT_RECOIL_33 38
#define MOVE_EFFECT_ATK_PLUS_2 39
#define MOVE_EFFECT_DEF_PLUS_2 40
#define MOVE_EFFECT_SPD_PLUS_2 41
#define MOVE_EFFECT_SP_ATK_PLUS_2 42
#define MOVE_EFFECT_SP_DEF_PLUS_2 43
#define MOVE_EFFECT_ACC_PLUS_2 44
#define MOVE_EFFECT_EVS_PLUS_2 45
#define MOVE_EFFECT_ATK_MINUS_2 46
#define MOVE_EFFECT_DEF_MINUS_2 47
#define MOVE_EFFECT_SPD_MINUS_2 48
#define MOVE_EFFECT_SP_ATK_MINUS_2 49
#define MOVE_EFFECT_SP_DEF_MINUS_2 50
#define MOVE_EFFECT_ACC_MINUS_2 51
#define MOVE_EFFECT_EVS_MINUS_2 52
#define MOVE_EFFECT_THRASH 53
#define MOVE_EFFECT_KNOCK_OFF 54
#define MOVE_EFFECT_NOTHING_37 55
#define MOVE_EFFECT_NOTHING_38 56
#define MOVE_EFFECT_NOTHING_39 57
#define MOVE_EFFECT_NOTHING_3A 58
#define MOVE_EFFECT_SP_ATK_TWO_DOWN 59
#define NUM_MOVE_EFFECTS 60
#define MOVE_EFFECT_AFFECTS_USER (1 << 6) // 64
#define MOVE_EFFECT_CERTAIN (1 << 7) // 128
// Battle terrain defines for gBattleTerrain.
#define BATTLE_TERRAIN_GRASS 0
#define BATTLE_TERRAIN_LONG_GRASS 1
#define BATTLE_TERRAIN_SAND 2
#define BATTLE_TERRAIN_UNDERWATER 3
#define BATTLE_TERRAIN_WATER 4
#define BATTLE_TERRAIN_POND 5
#define BATTLE_TERRAIN_MOUNTAIN 6
#define BATTLE_TERRAIN_CAVE 7
#define BATTLE_TERRAIN_BUILDING 8
#define BATTLE_TERRAIN_PLAIN 9
#define B_WAIT_TIME_LONG 64
#define B_WAIT_TIME_MED 48
#define B_WAIT_TIME_SHORT 32
#define CASTFORM_NORMAL 0
#define CASTFORM_FIRE 1
#define CASTFORM_WATER 2
#define CASTFORM_ICE 3
#define NUM_CASTFORM_FORMS 4
#define CASTFORM_SUBSTITUTE (1 << 7)
#define FLEE_ITEM 1
#define FLEE_ABILITY 2
// Return value for IsRunningFromBattleImpossible.
#define BATTLE_RUN_SUCCESS 0
#define BATTLE_RUN_FORBIDDEN 1
#define BATTLE_RUN_FAILURE 2
#define B_WIN_TYPE_NORMAL 0
#define B_WIN_TYPE_ARENA 1
// Window Ids for sStandardBattleWindowTemplates / sBattleArenaWindowTemplates
#define B_WIN_MSG 0
#define B_WIN_ACTION_PROMPT 1 // "What will {x} do?"
#define B_WIN_ACTION_MENU 2 // "Fight/Pokémon/Bag/Run" menu
#define B_WIN_MOVE_NAME_1 3 // Top left
#define B_WIN_MOVE_NAME_2 4 // Top right
#define B_WIN_MOVE_NAME_3 5 // Bottom left
#define B_WIN_MOVE_NAME_4 6 // Bottom right
#define B_WIN_PP 7
#define B_WIN_DUMMY 8
#define B_WIN_PP_REMAINING 9
#define B_WIN_MOVE_TYPE 10
#define B_WIN_SWITCH_PROMPT 11 // "Switch which?"
#define B_WIN_YESNO 12
#define B_WIN_LEVEL_UP_BOX 13
#define B_WIN_LEVEL_UP_BANNER 14
#define B_WIN_VS_PLAYER 15
#define B_WIN_VS_OPPONENT 16
#define B_WIN_VS_MULTI_PLAYER_1 17
#define B_WIN_VS_MULTI_PLAYER_2 18
#define B_WIN_VS_MULTI_PLAYER_3 19
#define B_WIN_VS_MULTI_PLAYER_4 20
#define B_WIN_VS_OUTCOME_DRAW 21
#define B_WIN_VS_OUTCOME_LEFT 22
#define B_WIN_VS_OUTCOME_RIGHT 23
// The following are duplicate id values for windows that Battle Arena uses differently.
#define ARENA_WIN_PLAYER_NAME 15
#define ARENA_WIN_VS 16
#define ARENA_WIN_OPPONENT_NAME 17
#define ARENA_WIN_MIND 18
#define ARENA_WIN_SKILL 19
#define ARENA_WIN_BODY 20
#define ARENA_WIN_JUDGMENT_TITLE 21
#define ARENA_WIN_JUDGMENT_TEXT 22
// Flag for BattlePutTextOnWindow. Never set
#define B_WIN_COPYTOVRAM (1 << 7)
// Indicator for the party summary bar to display an empty slot.
#define HP_EMPTY_SLOT 0xFFFF
#endif // GUARD_CONSTANTS_BATTLE_H
|
e068bc2db5f3dfa2ec71d69eea3689b2fe3bd184
|
28d0f8c01599f8f6c711bdde0b59f9c2cd221203
|
/sys/arch/acorn32/include/irqhandler.h
|
50d996392655c904eb8094e55aac2506f9d016ae
|
[] |
no_license
|
NetBSD/src
|
1a9cbc22ed778be638b37869ed4fb5c8dd616166
|
23ee83f7c0aea0777bd89d8ebd7f0cde9880d13c
|
refs/heads/trunk
| 2023-08-31T13:24:58.105962
| 2023-08-27T15:50:47
| 2023-08-27T15:50:47
| 88,439,547
| 656
| 348
| null | 2023-07-20T20:07:24
| 2017-04-16T20:03:43
| null |
UTF-8
|
C
| false
| false
| 5,878
|
h
|
irqhandler.h
|
/* $NetBSD: irqhandler.h,v 1.9 2009/03/14 14:45:51 dsl Exp $ */
/*
* Copyright (c) 1994-1996 Mark Brinicombe.
* Copyright (c) 1994 Brini.
* All rights reserved.
*
* This code is derived from software written for Brini by Mark Brinicombe
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by Mark Brinicombe
* for the NetBSD Project.
* 4. The name of the company nor the name of the author may be used to
* endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* IRQ related stuff (defines + structures)
*
* Created : 30/09/94
*/
#ifndef _ARM32_IRQHANDLER_H_
#define _ARM32_IRQHANDLER_H_
#if defined(_KERNEL_OPT)
#include "iomd.h"
#endif
#ifndef _LOCORE
#include <sys/types.h>
#endif /* _LOCORE */
/* Define the IRQ bits */
/*
* XXX this is really getting rather horrible.
* Shortly to be replaced with system specific interrupt tables and handling
*/
#if NIOMD > 0
/* Only for ARM7500 : */
/*#define IRQ_PRINTER 0x00*/
#define IRQ_INT2 0x00
/*#define IRQ_RESERVED0 0x01*/
#define IRQ_BUTTON 0x02
#define IRQ_NINT1 0x02
#define IRQ_FLYBACK 0x03
#define IRQ_NPOR 0x04
#define IRQ_TIMER0 0x05
#define IRQ_TIMER1 0x06
#define IRQ_SOFTINT 0x07
#define IRQ_DREQ3 0x08
#define IRQ_NINT8 0x08
/*#define IRQ_HD1 0x09*/
#define IRQ_INT7 0x09
/*#define IRQ_HD IRQ_HD1*/
#define IRQ_DREQ2 0x0A
#define IRQ_NINT6 0x0A
#define IRQ_INT5 0x0B
/*#define IRQ_FLOPPY 0x0C*/
#define IRQ_NINT4 0x0C
/*#define IRQ_SERIAL 0x0D*/
#define IRQ_NINT3 0x0D
#define IRQ_KBDTX 0x0E
#define IRQ_KBDRX 0x0F
#define IRQ_IRQ3 0x10
#define IRQ_IRQ4 0x11
#define IRQ_IRQ5 0x12
#define IRQ_IRQ6 0x13
#define IRQ_IRQ7 0x14
#define IRQ_IRQ9 0x15
#define IRQ_IRQ10 0x16
#define IRQ_IRQ11 0x17
#define IRQ_IOP0 0x10
#define IRQ_IOP1 0x11
#define IRQ_IOP2 0x12
#define IRQ_IOP3 0x13
#define IRQ_IOP4 0x14
#define IRQ_IOP5 0x15
#define IRQ_IOP6 0x16
#define IRQ_IOP7 0x17
#define IRQ_MSDRX 0x18
#define IRQ_MSDTX 0x19
#define IRQ_ATOD 0x1A
#define IRQ_NEVENT1 0x1B
#define IRQ_CLOCK 0x1B
#define IRQ_NEVENT2 0x1C
#define IRQ_PANIC 0x1C
/*#define IRQ_RESERVED2 0x1D*/
/*#define IRQ_RESERVED3 0x1E*/
/*
* Note that Sound DMA IRQ is on the 31st vector.
* It's not part of the IRQD.
*/
#define IRQ_SDMA 0x1F
/* Several interrupts are different between the A7000 and RC7500 */
#ifdef RC7500
#define IRQ_FIQDOWN 0x07
#define IRQ_ETHERNET 0x0B
#define IRQ_HD2 IRQ_IRQ11
#else /* RC7500 */
/*#define IRQ_RESERVED1 0x07 */
#define IRQ_EXTENDED 0x0B
#define IRQ_PODULE 0x0D
#endif /* RC7500 */
/* for non ARM7500 machines : */
/*#define IRQ_PRINTER 0x00*/
/*#define IRQ_RESERVED0 0x01*/
/*#define IRQ_FLOPPYIDX 0x02*/
#define IRQ_FLYBACK 0x03
#define IRQ_POR 0x04
#define IRQ_TIMER0 0x05
#define IRQ_TIMER1 0x06
/*#define IRQ_RESERVED1 0x07*/
/*#define IRQ_RESERVED2 0x08*/
/*#define IRQ_HD 0x09*/
/*#define IRQ_SERIAL 0x0A*/
#define IRQ_EXTENDED 0x0B
/*#define IRQ_FLOPPY 0x0C*/
#define IRQ_PODULE 0x0D
#define IRQ_KBDTX 0x0E
#define IRQ_KBDRX 0x0F
#define IRQ_DMACH0 0x10
#define IRQ_DMACH1 0x11
#define IRQ_DMACH2 0x12
#define IRQ_DMACH3 0x13
#define IRQ_DMASCH0 0x14
#define IRQ_DMASCH1 0x15
/*#define IRQ_RESERVED3 0x16*/
/*#define IRQ_RESERVED4 0x17*/
#endif /* NIOMD > 0 */
#define IRQ_VSYNC IRQ_FLYBACK /* Aliased */
#define IRQ_NETSLOT IRQ_EXTENDED
#define IRQ_INSTRUCT -1
#define NIRQS 0x20
#include <machine/intr.h>
#ifndef _LOCORE
typedef struct irqhandler {
int (*ih_func)(void *arg);/* handler function */
void *ih_arg; /* Argument to handler */
int ih_level; /* Interrupt level */
int ih_num; /* Interrupt number (for accounting) */
const char *ih_name; /* Name of interrupt (for vmstat -i) */
u_int ih_flags; /* Interrupt flags */
u_int ih_maskaddr; /* mask address for expansion cards */
u_int ih_maskbits; /* interrupt bit for expansion cards */
struct irqhandler *ih_next; /* next handler */
} irqhandler_t;
#ifdef _KERNEL
extern u_int irqmasks[NIPL];
extern irqhandler_t *irqhandlers[NIRQS];
void irq_init(void);
int irq_claim(int, irqhandler_t *);
int irq_release(int, irqhandler_t *);
void *intr_claim(int irq, int level, const char *name, int (*func)(void *), void *arg);
int intr_release(void *ih);
void irq_setmasks(void);
void disable_irq(int);
void enable_irq(int);
void stray_irqhandler(u_int);
#endif /* _KERNEL */
#endif /* _LOCORE */
#define IRQ_FLAG_ACTIVE 0x00000001 /* This is the active handler in list */
#endif /* _ARM32_IRQHANDLER_H_ */
/* End of irqhandler.h */
|
eddc78d7ec79af4c6a2c940401dc3f7fa957f7ed
|
cb80ffbfe6b12be3f42322537aff3552fd9239f2
|
/examples/models/models_animation.c
|
ffe2d01248a8c22fcdedc31a40ad291135231d28
|
[
"Zlib",
"LicenseRef-scancode-other-permissive",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
raysan5/raylib
|
afe80387401361d6f35f9831978b0b379d2d9971
|
a86c93ebc0095f6c2ffc14656bfc9e1e37070f72
|
refs/heads/master
| 2023-08-16T20:49:02.921768
| 2023-08-14T22:09:27
| 2023-08-14T22:09:27
| 13,836,499
| 15,971
| 2,825
|
Zlib
| 2023-09-14T21:19:02
| 2013-10-24T15:46:04
|
C
|
UTF-8
|
C
| false
| false
| 5,011
|
c
|
models_animation.c
|
/*******************************************************************************************
*
* raylib [models] example - Load 3d model with animations and play them
*
* Example originally created with raylib 2.5, last time updated with raylib 3.5
*
* Example contributed by Culacant (@culacant) and reviewed by Ramon Santamaria (@raysan5)
*
* Example licensed under an unmodified zlib/libpng license, which is an OSI-certified,
* BSD-like license that allows static linking with closed source software
*
* Copyright (c) 2019-2023 Culacant (@culacant) and Ramon Santamaria (@raysan5)
*
********************************************************************************************
*
* NOTE: To export a model from blender, make sure it is not posed, the vertices need to be
* in the same position as they would be in edit mode and the scale of your models is
* set to 0. Scaling can be done from the export menu.
*
********************************************************************************************/
#include "raylib.h"
//------------------------------------------------------------------------------------
// Program main entry point
//------------------------------------------------------------------------------------
int main(void)
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [models] example - model animation");
// Define the camera to look into our 3d world
Camera camera = { 0 };
camera.position = (Vector3){ 10.0f, 10.0f, 10.0f }; // Camera position
camera.target = (Vector3){ 0.0f, 0.0f, 0.0f }; // Camera looking at point
camera.up = (Vector3){ 0.0f, 1.0f, 0.0f }; // Camera up vector (rotation towards target)
camera.fovy = 45.0f; // Camera field-of-view Y
camera.projection = CAMERA_PERSPECTIVE; // Camera mode type
Model model = LoadModel("resources/models/iqm/guy.iqm"); // Load the animated model mesh and basic data
Texture2D texture = LoadTexture("resources/models/iqm/guytex.png"); // Load model texture and set material
SetMaterialTexture(&model.materials[0], MATERIAL_MAP_DIFFUSE, texture); // Set model material map texture
Vector3 position = { 0.0f, 0.0f, 0.0f }; // Set model position
// Load animation data
unsigned int animsCount = 0;
ModelAnimation *anims = LoadModelAnimations("resources/models/iqm/guyanim.iqm", &animsCount);
int animFrameCounter = 0;
DisableCursor(); // Catch cursor
SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose()) // Detect window close button or ESC key
{
// Update
//----------------------------------------------------------------------------------
UpdateCamera(&camera, CAMERA_FIRST_PERSON);
// Play animation when spacebar is held down
if (IsKeyDown(KEY_SPACE))
{
animFrameCounter++;
UpdateModelAnimation(model, anims[0], animFrameCounter);
if (animFrameCounter >= anims[0].frameCount) animFrameCounter = 0;
}
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
ClearBackground(RAYWHITE);
BeginMode3D(camera);
DrawModelEx(model, position, (Vector3){ 1.0f, 0.0f, 0.0f }, -90.0f, (Vector3){ 1.0f, 1.0f, 1.0f }, WHITE);
for (int i = 0; i < model.boneCount; i++)
{
DrawCube(anims[0].framePoses[animFrameCounter][i].translation, 0.2f, 0.2f, 0.2f, RED);
}
DrawGrid(10, 1.0f); // Draw a grid
EndMode3D();
DrawText("PRESS SPACE to PLAY MODEL ANIMATION", 10, 10, 20, MAROON);
DrawText("(c) Guy IQM 3D model by @culacant", screenWidth - 200, screenHeight - 20, 10, GRAY);
EndDrawing();
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
UnloadTexture(texture); // Unload texture
UnloadModelAnimations(anims, animsCount); // Unload model animations data
UnloadModel(model); // Unload model
CloseWindow(); // Close window and OpenGL context
//--------------------------------------------------------------------------------------
return 0;
}
|
6d3998b2d9cc02505c24b328f24f47892ca1f76f
|
67775026f2d078a07c5d27ace5405035e89c6ee7
|
/contrib/MSR Driver/Kernel/TmpRdr.c
|
842dab25ad8dce0cce124db98689c5355560c586
|
[
"BSD-2-Clause"
] |
permissive
|
anrieff/libcpuid
|
759b4789568560dd36b8f5af6ce2e0c7cb4e3588
|
0ded44bb0cf5e249b37a4e3f68e7c413f3e6fb51
|
refs/heads/master
| 2023-09-02T06:28:23.853266
| 2023-08-06T10:13:48
| 2023-08-06T10:14:04
| 19,618,386
| 414
| 128
|
NOASSERTION
| 2023-07-16T09:35:50
| 2014-05-09T16:50:29
|
C
|
UTF-8
|
C
| false
| false
| 4,189
|
c
|
TmpRdr.c
|
#include <ntddk.h>
#define FILE_DEVICE_UNKNOWN 0x00000022
#define IOCTL_UNKNOWN_BASE FILE_DEVICE_UNKNOWN
#define IOCTL_PROCVIEW_RDMSR CTL_CODE(IOCTL_UNKNOWN_BASE, 0x0803, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS)
#define FLAG_HANDLE_OPENED 1
void UnloadDriver(PDRIVER_OBJECT DriverObject);
NTSTATUS DispatchCreateClose(IN PDEVICE_OBJECT DeviceObject, IN PIRP Irp);
NTSTATUS DispatchIoctl(IN PDEVICE_OBJECT DeviceObject, IN PIRP Irp);
NTSTATUS DriverEntry(IN PDRIVER_OBJECT DriverObject, IN PUNICODE_STRING RegistryPath);
typedef struct _DEVICE_EXTENSION{
PDEVICE_OBJECT DeviceObject;
} DEVICE_EXTENSION, *PDEVICE_EXTENSION;
PDEVICE_OBJECT g_pDeviceObject;
#pragma alloc_text(PAGE0DEF, DriverEntry)
//
NTSTATUS DriverEntry(IN PDRIVER_OBJECT DriverObject, IN PUNICODE_STRING RegistryPath){
NTSTATUS ntStatus;
UNICODE_STRING uszDriverString;
UNICODE_STRING uszDeviceString;
PDEVICE_OBJECT pDeviceObject;
PDEVICE_EXTENSION extension;
// Point uszDriverString at the driver name
RtlInitUnicodeString(&uszDriverString, L"\\Device\\TmpRdr");
// Create and initialize device object
ntStatus = IoCreateDevice(DriverObject, sizeof(DEVICE_EXTENSION), &uszDriverString, FILE_DEVICE_UNKNOWN, 0, FALSE, &pDeviceObject);
if(ntStatus != STATUS_SUCCESS)
return ntStatus;
// Assign extension variable
extension = pDeviceObject->DeviceExtension;
// Point uszDeviceString at the device name
RtlInitUnicodeString(&uszDeviceString, L"\\DosDevices\\TmpRdr");
// Create symbolic link to the user-visible name
ntStatus = IoCreateSymbolicLink(&uszDeviceString, &uszDriverString);
if(ntStatus != STATUS_SUCCESS){
// Delete device object if not successful
IoDeleteDevice(pDeviceObject);
return ntStatus;
}
// Assign global pointer to the device object for use by the callback functions
g_pDeviceObject = pDeviceObject;
// Load structure to point to IRP handlers
DriverObject->DriverUnload = UnloadDriver;
DriverObject->MajorFunction[IRP_MJ_CREATE] = DispatchCreateClose;
DriverObject->MajorFunction[IRP_MJ_CLOSE] = DispatchCreateClose;
DriverObject->MajorFunction[IRP_MJ_DEVICE_CONTROL] = DispatchIoctl;
// Return success
return ntStatus;
}
//
NTSTATUS DispatchCreateClose(IN PDEVICE_OBJECT DeviceObject, IN PIRP Irp){
PDEVICE_EXTENSION extension = DeviceObject->DeviceExtension;
Irp->IoStatus.Status = STATUS_SUCCESS;
Irp->IoStatus.Information = 0;
IoCompleteRequest(Irp, IO_NO_INCREMENT);
return STATUS_SUCCESS;
}
//
NTSTATUS DispatchIoctl(IN PDEVICE_OBJECT DeviceObject, IN PIRP Irp){
NTSTATUS ntStatus = STATUS_UNSUCCESSFUL;
PIO_STACK_LOCATION irpStack = IoGetCurrentIrpStackLocation(Irp);
PDEVICE_EXTENSION extension = DeviceObject->DeviceExtension;
__int64 *p__int64;
int iMSRregister;
switch(irpStack->Parameters.DeviceIoControl.IoControlCode){
case IOCTL_PROCVIEW_RDMSR:
if(irpStack->Parameters.DeviceIoControl.OutputBufferLength >= sizeof(__int64)){
if(irpStack->Parameters.DeviceIoControl.InputBufferLength == sizeof(int))
iMSRregister = *((int *)Irp->AssociatedIrp.SystemBuffer);
else
iMSRregister = 0x19c;
p__int64 = Irp->AssociatedIrp.SystemBuffer;
*p__int64 = __readmsr(iMSRregister);
ntStatus = STATUS_SUCCESS;
Irp->IoStatus.Information = sizeof(__int64);
IoCompleteRequest(Irp, IO_NO_INCREMENT);
return ntStatus;
}
break;
default:
break;
}
Irp->IoStatus.Status = ntStatus;
if(ntStatus == STATUS_SUCCESS)
Irp->IoStatus.Information = irpStack->Parameters.DeviceIoControl.OutputBufferLength;
else
Irp->IoStatus.Information = 0;
IoCompleteRequest(Irp, IO_NO_INCREMENT);
return ntStatus;
}
//
void UnloadDriver(IN PDRIVER_OBJECT DriverObject){
UNICODE_STRING uszDeviceString;
IoDeleteDevice(DriverObject->DeviceObject);
RtlInitUnicodeString(&uszDeviceString, L"\\DosDevices\\TmpRdr");
IoDeleteSymbolicLink(&uszDeviceString);
}
|
762a3219d613a48b1f906cf72dc3d88232b75f78
|
89db60818afeb3dc7c3b7abe9ceae155f074f7f2
|
/src/libauth/httpauth.c
|
9d1b0d26ff0a33313f0721d92c6ac3337606c9c7
|
[
"bzip2-1.0.6",
"LPL-1.02",
"MIT"
] |
permissive
|
9fans/plan9port
|
63c3d01928c6f8a8617d3ea6ecc05bac72391132
|
65c090346a38a8c30cb242d345aa71060116340c
|
refs/heads/master
| 2023-08-25T17:14:26.233105
| 2023-08-23T13:21:37
| 2023-08-23T18:47:08
| 26,095,474
| 1,645
| 468
|
NOASSERTION
| 2023-09-05T16:55:41
| 2014-11-02T22:40:13
|
C
|
UTF-8
|
C
| false
| false
| 1,059
|
c
|
httpauth.c
|
#include <u.h>
#include <libc.h>
#include <auth.h>
#include <authsrv.h>
/* deprecated.
This is the mechanism that put entries in /sys/lib/httpd.rewrite
and passwords on the authserver in /sys/lib/httppasswords, which
was awkward to administer. Instead, use local .httplogin files,
which are implemented in sys/src/cmd/ip/httpd/authorize.c */
int
httpauth(char *name, char *password)
{
int afd;
Ticketreq tr;
Ticket t;
char key[DESKEYLEN];
char buf[512];
afd = authdial(nil, nil);
if(afd < 0)
return -1;
/* send ticket request to AS */
memset(&tr, 0, sizeof(tr));
strcpy(tr.uid, name);
tr.type = AuthHttp;
convTR2M(&tr, buf);
if(write(afd, buf, TICKREQLEN) != TICKREQLEN){
close(afd);
return -1;
}
if(_asrdresp(afd, buf, TICKETLEN) < 0){
close(afd);
return -1;
}
close(afd);
/*
* use password and try to decrypt the
* ticket. If it doesn't work we've got a bad password,
* give up.
*/
passtokey(key, password);
convM2T(buf, &t, key);
if(t.num != AuthHr || strcmp(t.cuid, tr.uid))
return -1;
return 0;
}
|
ef63bd94cfc881b46bc7130a99227613dd080bf0
|
0744dcc5394cebf57ebcba343747af6871b67017
|
/os/drivers/wireless/scsc/mbulk.h
|
9f8394413799c3073653045e63417acc48b95dfc
|
[
"GPL-1.0-or-later",
"BSD-3-Clause",
"ISC",
"MIT",
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-other-permissive",
"Apache-2.0"
] |
permissive
|
Samsung/TizenRT
|
96abf62f1853f61fcf91ff14671a5e0c6ca48fdb
|
1a5c2e00a4b1bbf4c505bbf5cc6a8259e926f686
|
refs/heads/master
| 2023-08-31T08:59:33.327998
| 2023-08-08T06:09:20
| 2023-08-31T04:38:20
| 82,517,252
| 590
| 719
|
Apache-2.0
| 2023-09-14T06:54:49
| 2017-02-20T04:38:30
|
C
|
UTF-8
|
C
| false
| false
| 11,692
|
h
|
mbulk.h
|
/*****************************************************************************
*
* Copyright 2017 Samsung Electronics All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific
* language governing permissions and limitations under the License.
*
****************************************************************************/
#ifndef __MBULK_H__
#define __MBULK_H__
/**
* mbulk(bulk memory) API
*
* This header file describes APIs of the bulk memory management.
* The diagram below is an example of a mbulk buffer with one
* segment (i.e. not a chained mbulk).
*
* sig_bufsz
* |<-------->|
* | |<--------- dat_bufsz ---------->|
* +--------------------------------------------------+
* | mbulk| signal | bulk buffer |
* +-------------------------+---------------+--------+
* | | | valid data | |
* | | |<--------+---->| |
* | | | mbulk_tlen(m) | |
* | |<----->| | |<------>|
* | mbulk_headroom(m)| | mbulk_tailroom(m)
* | | |
* | |-- off -->|
* v v |
* mbulk_get_sig(m) mbulk_dat(m) |
* v
* mbulk_dat_at(m,off)
*
* In general, all clients are supposed to use only mbulk_xxx() APIs (but not
* mbulk_seg_xxx() APIs), as they can handle S/G chained mbulk as well.
* But as of now, specially in Condor, S/G chained mbulk is not supported,
* which means the most of mbulk_xxx() would be wrappers of mbulk_seg_xxx().
*
* An in-lined signal buffer can be allocated along with a mbulk buffer.
* There is no direct life-cycle relationship between the signal and the
* associated mbulk in this case, which means that the signal buffer should be
* de-allocated independently of the mbulk buffer.
*
*/
/**
* bulk buffer descriptor
*/
struct mbulk;
/**
* mbulk pool ID
*/
#define MBULK_POOL_ID_MIN (0)
#define MBULK_POOL_ID_MAX_FW (4) /* 0 ~ 3 used for firmware pools */
#define MBULK_POOL_ID_MAX (MBULK_POOL_ID_MAX_FW)
/* Max number of mbulk to be freed by the Host */
#define MBULK_MAX_HOST_TO_FREE 2
/**
* mbulk buffer classification
*
* Note that PACKED attribute is added to enum definition so that
* compiler assigns the smallest integral type (u8).
*/
enum mbulk_class {
MBULK_CLASS_FROM_HOST_DAT = 0,
MBULK_CLASS_FROM_HOST_CTL = 1,
MBULK_CLASS_FROM_RADIO = 2,
MBULK_CLASS_CONTRL = 3,
MBULK_CLASS_DEBUG = 4,
MBULK_CLASS_OTHERS = 5,
MBULK_CLASS_MAX
} STRUCT_PACKED;
/**
* The private definition of mbulk structure is included here
* so that its members can be directly accessed, and the access
* codes can be in-lined by the compiler.
* But client codes are not supposed to directly refer to mbulk
* members, nor use mbulk_seg_xxx() functions. Only modules handling
* mbulk scatter/gather chain would directly use mulk_seg_xxx() APIs.
*/
#include "mbulk_def.h"
/**
* Get the bulk data reference counter
*
* After a bulk buffer with non-zero data buffer size is created,
* the reference counter is set to one. Each time it is duplicated,
* its reference counter would be increased.
*
* Note that the reference counter is initialized to zero if a signal
* is created from mbulk pool but with zero data buffer size, as there
* is no data buffer.
*/
static inline int mbulk_refcnt(const struct mbulk *m)
{
return MBULK_SEG_REFCNT(m);
}
/**
* Get the bulk data buffer size
*
*/
static inline int mbulk_buffer_size(const struct mbulk *m)
{
return MBULK_SEG_DAT_BUFSIZE(m);
}
/**
* Check if mbulk has an in-lined signal buffer
*
*/
static inline bool mbulk_has_signal(const struct mbulk *m)
{
return MBULK_SEG_HAS_SIGNAL(m);
}
/**
* Set mbulk to be read-only
*/
static inline void mbulk_set_readonly(struct mbulk *m)
{
MBULK_SEG_SET_READONLY(m);
}
/**
* is mbulk read-only
*/
static inline bool mbulk_is_readonly(const struct mbulk *m)
{
return MBULK_SEG_IS_READONLY(m);
}
/**
* check if mbulk is a scatter/gather chained buffer
*
*/
static inline bool mbulk_is_sg(const struct mbulk *m)
{
return MBULK_SEG_IS_CHAIN_HEAD(m);
}
/**
* check if mbulk is a part of scatter/gather chained buffer
*
*/
static inline bool mbulk_is_chained(const struct mbulk *m)
{
return MBULK_SEG_IS_CHAINED(m);
}
/**
* Allocate a bulk buffer with an in-lined signal buffer
*
* Only one mbulk segment is used for allocation starting from the
* mbulk pool with the smallest segment size. If no segment fitting
* the requested size, then return NULL without trying to create
* a chained buffer.
*
*/
struct mbulk *mbulk_with_signal_alloc(enum mbulk_class clas, size_t sig_bufsz, size_t dat_bufsz);
/**
* Allocate a bulk buffer with an in-lined signal buffer
*
* A mbulk segment is allocated from the given the pool, if its size
* meeting the requested size.
*
*/
struct mbulk *mbulk_with_signal_alloc_by_pool(u8 pool_id, u16 colour, enum mbulk_class clas, size_t sig_bufsz, size_t dat_bufsz);
/**
* Get a signal buffer address
*
* Given a mbulk buffer, returns a signal buffer address.
*
* @param m mbulk
* @return in-lined signal buffer
*/
static inline void *mbulk_get_seg(const struct mbulk *m)
{
return (void *)MBULK_SEG_B(m);
}
/**
* Get a signal buffer address
*
* Given a mbulk buffer, returns a signal buffer address if any in-lined
* signal buffer.
*
*/
static inline void *mbulk_get_signal(const struct mbulk *m)
{
bool ret = false;
ret = mbulk_has_signal(m);
return ret ? mbulk_get_seg(m) : NULL;
}
/**
* Allocate a bulk buffer
*
* Only one mbulk segment is used for allocation starting from the
* mbulk pool with the smallest segment size. If no segment fitting
* the requested size, then return NULL without trying to create
* a chained buffer.
*
*/
static inline struct mbulk *mbulk_alloc(enum mbulk_class clas, size_t dat_bufsz)
{
return mbulk_with_signal_alloc(clas, 0, dat_bufsz);
}
/**
* free mbulk buffer
*
* After checking the bulk reference counter, this function return the buffer
* to the mbulk pool if it is zero. Note that this doesn't free the in-lined
* signal buffer.
*/
static inline void mbulk_free(struct mbulk *m)
{
mbulk_seg_free(m);
}
/**
* get bulk buffer address for read or write access
*
* The address is the buffer address after the headroom in the mbulk segment.
* Note that this function can only be used to access the data in the same
* segment, including a segment in the mbulk chain (for example, to access
* the 802.11 header of A-MSDU).
*
*/
static inline void *mbulk_dat_rw(const struct mbulk *m)
{
//BUG_ON(MBULK_SEG_IS_READONLY(m));
return MBULK_SEG_DAT(m);
}
/**
* get bulk buffer address for read-only
*
* The address is the buffer address after the headroom in the mbulk segment.
* Note that this function can only be used to access the data in the same
* segment, including a segment in the mbulk chain (for example, to access
* the 802.11 header of A-MSDU).
*
*/
static inline const void *mbulk_dat_r(const struct mbulk *m)
{
return (const void *)MBULK_SEG_DAT(m);
}
/**
* get bulk buffer address at the offset for read or write access
*
*/
static inline void *mbulk_dat_at_rw(const struct mbulk *m, size_t off)
{
//BUG_ON(MBULK_SEG_IS_READONLY(m));
return MBULK_SEG_DAT_AT(m, off);
}
/**
* get bulk buffer address at the offset for read access
*
*/
static inline /*const */ void *mbulk_dat_at_r(const struct mbulk *m, size_t off)
{
return (/*const */ void *)MBULK_SEG_DAT_AT(m, off);
}
/**
* get valid data length
*
*/
static inline size_t mbulk_tlen(const struct mbulk *m)
{
return MBULK_SEG_LEN(m);
}
/**
* get headroom
*
*/
static inline size_t mbulk_headroom(const struct mbulk *m)
{
return MBULK_SEG_HEADROOM(m);
}
static inline size_t mbulk_tailroom(const struct mbulk *m)
{
return MBULK_SEG_TAILROOM(m);
}
/**
* reserve headroom
*
* Note this API should be called right after mbulk is created or the valid
* data length is zero.
*
*/
static inline bool mbulk_reserve_head(struct mbulk *m, size_t headroom)
{
return mbulk_seg_reserve_head(m, headroom);
}
/**
* adjust the valid data range
*
* headroom would be placed after the signal buffer (or mbuf descriptor if
* no in-lined signal), and the valid data length is set to \len.
*
*/
static inline bool mbulk_adjust_range(struct mbulk *m, size_t headroom, size_t len)
{
return mbulk_seg_adjust_range(m, headroom, len);
}
/**
* extend the data range at the head
*
* The headroom would be reduced, and the data range is extended.
* To prepend data in the head, the headroom should have been reserved before.
*
*/
static inline bool mbulk_prepend_head(struct mbulk *m, size_t more)
{
return mbulk_seg_prepend_head(m, more);
}
/**
* extend the data at the tail
*
* Data range is expanded towards the tail.
*
*/
static inline bool mbulk_append_tail(struct mbulk *m, size_t more)
{
return mbulk_seg_append_tail(m, more);
}
/**
* trim data at the head
*
* The headroom would be increased, and the valid data range is reduced
* accordingly.
*
*/
static inline bool mbulk_trim_head(struct mbulk *m, size_t less)
{
return mbulk_seg_trim_head(m, less);
}
/**
* trim data at the tail
*
* The data length would be reduced.
*
*/
static inline bool mbulk_trim_tail(struct mbulk *m, size_t less)
{
return mbulk_seg_trim_tail(m, less);
}
/**
* duplicate a mbulk
*
* There is no data copy. but the referece counter of the orignal mbulk is
* increased by one.
*
*/
static inline struct mbulk *mbulk_duplicate(struct mbulk *m)
{
return mbulk_seg_duplicate(m);
}
/**
* clone a mbulk
*
* New mbulk buffer is created, and contents are copied. The signal is copied
* only when \copy_sig is TRUE.
*
*/
static inline struct mbulk *mbulk_clone(const struct mbulk *m, enum mbulk_class clas, bool copy_sig)
{
return mbulk_seg_clone(m, clas, copy_sig);
}
/**
* allocate a signal buffer from mbulk pool
*
*/
void *msignal_alloc(size_t sig_sz);
/**
* free a signal buffer created from mbulk pool
*
*/
void msignal_free(void *sig);
/**
* get mbulk descriptor given a signal buffer address
*
*/
struct mbulk *msignal_to_mbulk(void *sig);
/**
* get next chained mbulk in a scatter/gathered list
*/
static inline scsc_mifram_ref mbulk_chain_next(struct mbulk *m)
{
return MBULK_SEG_CHAIN_NEXT(m);
}
/**
* init mbulk library
*/
/*extern void init_mbulk(void);*/
void init_mbulk(void *mem, size_t pool_size);
/**
* add a memory zone to a mbulk pool list
*
*/
int mbulk_pool_add(u8 pool_id, char *base, char *end, size_t buf_size, u8 guard);
/**
* check sanity of a mbulk pool
*/
void mbulk_pool_check_sanity(u8 pool_id);
/**
* configure the handler which returning the buffer to the host
*/
void mbulk_set_handler_return_host_mbulk(void (*free_host_buf)(struct mbulk *m));
/**
* free a mbulk in the virtual host
*/
void mbulk_free_virt_host(struct mbulk *m);
void mbulk_pool_dump(u8 pool_id, int max_cnt);
void mbulk_pool_init(void);
#endif /*__MBULK_H__*/
|
2ac5c14dfbccf8032161dd3ef953b96ceca0360e
|
8023a4ffb780d18f77766744668e05a246ed7f8e
|
/windows/project/part11/common/luatable.h
|
dad0b52a2c75cb299b27f32f2a7879725a61a40a
|
[
"MIT"
] |
permissive
|
Manistein/dummylua-tutorial
|
e6768ac28c525b0a9ef7523d18f4dd1768e96572
|
c8158625ac5665f9726515ccb3a835f6474641b3
|
refs/heads/master
| 2023-05-12T22:14:49.160230
| 2023-04-26T07:31:29
| 2023-04-26T07:31:29
| 153,052,447
| 395
| 59
|
MIT
| 2022-06-08T01:58:02
| 2018-10-15T04:17:50
|
C
|
UTF-8
|
C
| false
| false
| 2,750
|
h
|
luatable.h
|
/* Copyright (c) 2018 Manistein,https://manistein.github.io/blog/
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 luatable_h
#define luatable_h
#include "luastate.h"
#define isdummy(t) ((t)->lastfree == NULL)
#define getkey(n) (cast(const TValue*, &n->key.tvk))
#define getwkey(n) (cast(TValue*, &n->key.tvk))
#define getval(n) (cast(TValue*, &n->value))
#define getnode(t, i) (&(t)->node[i])
#define hashint(key, t) getnode(t, lmod(key, twoto(t->lsizenode)))
#define hashstr(ts, t) getnode(t, lmod(ts->hash, twoto(t->lsizenode)))
#define hashboolean(key, t) getnode(t, lmod(key, twoto(t->lsizenode)))
#define hashpointer(p, t) getnode(t, lmod(point2uint(p), twoto(t->lsizenode)))
struct Table* luaH_new(struct lua_State* L);
void luaH_free(struct lua_State* L, struct Table* t);
// if luaH_getint return luaO_nilobject, that means key is not exist
const TValue* luaH_getint(struct lua_State* L, struct Table* t, lua_Integer key);
int luaH_setint(struct lua_State* L, struct Table* t, int key, const TValue* value);
const TValue* luaH_getshrstr(struct lua_State* L, struct Table* t, struct TString* key);
const TValue* luaH_getstr(struct lua_State* L, struct Table* t, struct TString* key);
const TValue* luaH_get(struct lua_State* L, struct Table* t, const TValue* key);
TValue* luaH_set(struct lua_State* L, struct Table* t, const TValue* key);
int luaH_resize(struct lua_State* L, struct Table* t, unsigned int asize, unsigned int hsize);
TValue* luaH_newkey(struct lua_State* L, struct Table* t, const TValue* key);
// 传入一个key,获得下一个key的key值和对应的value值,并且入栈
int luaH_next(struct lua_State* L, struct Table* t, TValue* key);
int luaH_getn(struct lua_State* L, struct Table* t);
#endif
|
5f04194f8bc19150a914ed685d20bda8922924c7
|
7eaf54a78c9e2117247cb2ab6d3a0c20719ba700
|
/SOFTWARE/A64-TERES/linux-a64/drivers/staging/csr/csr_wifi_sme_sef.h
|
78b88c067236f0b74b471c0e13e5c8eda55d940f
|
[
"Linux-syscall-note",
"GPL-2.0-only",
"GPL-1.0-or-later",
"eCos-exception-2.0",
"MIT",
"LicenseRef-scancode-free-unknown",
"Apache-2.0"
] |
permissive
|
OLIMEX/DIY-LAPTOP
|
ae82f4ee79c641d9aee444db9a75f3f6709afa92
|
a3fafd1309135650bab27f5eafc0c32bc3ca74ee
|
refs/heads/rel3
| 2023-08-04T01:54:19.483792
| 2023-04-03T07:18:12
| 2023-04-03T07:18:12
| 80,094,055
| 507
| 92
|
Apache-2.0
| 2023-04-03T07:05:59
| 2017-01-26T07:25:50
|
C
|
UTF-8
|
C
| false
| false
| 6,668
|
h
|
csr_wifi_sme_sef.h
|
/*****************************************************************************
(c) Cambridge Silicon Radio Limited 2010
Confidential information of CSR
Refer to LICENSE.txt included with this source for details
on the license terms.
*****************************************************************************/
#ifndef CSR_WIFI_ROUTER_SEF_CSR_WIFI_SME_H__
#define CSR_WIFI_ROUTER_SEF_CSR_WIFI_SME_H__
#include "csr_wifi_sme_prim.h"
typedef void (*CsrWifiSmeStateHandlerType)(void *drvpriv, CsrWifiFsmEvent *msg);
extern const CsrWifiSmeStateHandlerType
CsrWifiSmeUpstreamStateHandlers[CSR_WIFI_SME_PRIM_UPSTREAM_COUNT];
extern void CsrWifiSmeActivateCfmHandler(void *drvpriv, CsrWifiFsmEvent *msg);
extern void CsrWifiSmeAdhocConfigGetCfmHandler(void *drvpriv,
CsrWifiFsmEvent *msg);
extern void CsrWifiSmeAdhocConfigSetCfmHandler(void *drvpriv,
CsrWifiFsmEvent *msg);
extern void CsrWifiSmeAssociationCompleteIndHandler(void *drvpriv,
CsrWifiFsmEvent *msg);
extern void CsrWifiSmeAssociationStartIndHandler(void *drvpriv,
CsrWifiFsmEvent *msg);
extern void CsrWifiSmeBlacklistCfmHandler(void *drvpriv,
CsrWifiFsmEvent *msg);
extern void CsrWifiSmeCalibrationDataGetCfmHandler(void *drvpriv,
CsrWifiFsmEvent *msg);
extern void CsrWifiSmeCalibrationDataSetCfmHandler(void *drvpriv,
CsrWifiFsmEvent *msg);
extern void CsrWifiSmeCcxConfigGetCfmHandler(void *drvpriv,
CsrWifiFsmEvent *msg);
extern void CsrWifiSmeCcxConfigSetCfmHandler(void *drvpriv,
CsrWifiFsmEvent *msg);
extern void CsrWifiSmeCoexConfigGetCfmHandler(void *drvpriv,
CsrWifiFsmEvent *msg);
extern void CsrWifiSmeCoexConfigSetCfmHandler(void *drvpriv,
CsrWifiFsmEvent *msg);
extern void CsrWifiSmeCoexInfoGetCfmHandler(void *drvpriv,
CsrWifiFsmEvent *msg);
extern void CsrWifiSmeConnectCfmHandler(void *drvpriv, CsrWifiFsmEvent *msg);
extern void CsrWifiSmeConnectionConfigGetCfmHandler(void *drvpriv,
CsrWifiFsmEvent *msg);
extern void CsrWifiSmeConnectionInfoGetCfmHandler(void *drvpriv,
CsrWifiFsmEvent *msg);
extern void CsrWifiSmeConnectionQualityIndHandler(void *drvpriv,
CsrWifiFsmEvent *msg);
extern void CsrWifiSmeConnectionStatsGetCfmHandler(void *drvpriv,
CsrWifiFsmEvent *msg);
extern void CsrWifiSmeDeactivateCfmHandler(void *drvpriv, CsrWifiFsmEvent *msg);
extern void CsrWifiSmeDisconnectCfmHandler(void *drvpriv, CsrWifiFsmEvent *msg);
extern void CsrWifiSmeEventMaskSetCfmHandler(void *drvpriv,
CsrWifiFsmEvent *msg);
extern void CsrWifiSmeHostConfigGetCfmHandler(void *drvpriv,
CsrWifiFsmEvent *msg);
extern void CsrWifiSmeHostConfigSetCfmHandler(void *drvpriv,
CsrWifiFsmEvent *msg);
extern void CsrWifiSmeIbssStationIndHandler(void *drvpriv,
CsrWifiFsmEvent *msg);
extern void CsrWifiSmeKeyCfmHandler(void *drvpriv, CsrWifiFsmEvent *msg);
extern void CsrWifiSmeLinkQualityGetCfmHandler(void *drvpriv,
CsrWifiFsmEvent *msg);
extern void CsrWifiSmeMediaStatusIndHandler(void *drvpriv,
CsrWifiFsmEvent *msg);
extern void CsrWifiSmeMibConfigGetCfmHandler(void *drvpriv,
CsrWifiFsmEvent *msg);
extern void CsrWifiSmeMibConfigSetCfmHandler(void *drvpriv,
CsrWifiFsmEvent *msg);
extern void CsrWifiSmeMibGetCfmHandler(void *drvpriv, CsrWifiFsmEvent *msg);
extern void CsrWifiSmeMibGetNextCfmHandler(void *drvpriv, CsrWifiFsmEvent *msg);
extern void CsrWifiSmeMibSetCfmHandler(void *drvpriv, CsrWifiFsmEvent *msg);
extern void CsrWifiSmeMicFailureIndHandler(void *drvpriv, CsrWifiFsmEvent *msg);
extern void CsrWifiSmeMulticastAddressCfmHandler(void *drvpriv,
CsrWifiFsmEvent *msg);
extern void CsrWifiSmePacketFilterSetCfmHandler(void *drvpriv,
CsrWifiFsmEvent *msg);
extern void CsrWifiSmePermanentMacAddressGetCfmHandler(void *drvpriv,
CsrWifiFsmEvent *msg);
extern void CsrWifiSmePmkidCandidateListIndHandler(void *drvpriv,
CsrWifiFsmEvent *msg);
extern void CsrWifiSmePmkidCfmHandler(void *drvpriv, CsrWifiFsmEvent *msg);
extern void CsrWifiSmePowerConfigGetCfmHandler(void *drvpriv,
CsrWifiFsmEvent *msg);
extern void CsrWifiSmePowerConfigSetCfmHandler(void *drvpriv,
CsrWifiFsmEvent *msg);
extern void CsrWifiSmeRegulatoryDomainInfoGetCfmHandler(void *drvpriv,
CsrWifiFsmEvent *msg);
extern void CsrWifiSmeRoamCompleteIndHandler(void *drvpriv,
CsrWifiFsmEvent *msg);
extern void CsrWifiSmeRoamStartIndHandler(void *drvpriv, CsrWifiFsmEvent *msg);
extern void CsrWifiSmeRoamingConfigGetCfmHandler(void *drvpriv,
CsrWifiFsmEvent *msg);
extern void CsrWifiSmeRoamingConfigSetCfmHandler(void *drvpriv,
CsrWifiFsmEvent *msg);
extern void CsrWifiSmeScanConfigGetCfmHandler(void *drvpriv,
CsrWifiFsmEvent *msg);
extern void CsrWifiSmeScanConfigSetCfmHandler(void *drvpriv,
CsrWifiFsmEvent *msg);
extern void CsrWifiSmeScanFullCfmHandler(void *drvpriv, CsrWifiFsmEvent *msg);
extern void CsrWifiSmeScanResultIndHandler(void *drvpriv, CsrWifiFsmEvent *msg);
extern void CsrWifiSmeScanResultsFlushCfmHandler(void *drvpriv,
CsrWifiFsmEvent *msg);
extern void CsrWifiSmeScanResultsGetCfmHandler(void *drvpriv,
CsrWifiFsmEvent *msg);
extern void CsrWifiSmeSmeStaConfigGetCfmHandler(void *drvpriv,
CsrWifiFsmEvent *msg);
extern void CsrWifiSmeSmeStaConfigSetCfmHandler(void *drvpriv,
CsrWifiFsmEvent *msg);
extern void CsrWifiSmeStationMacAddressGetCfmHandler(void *drvpriv,
CsrWifiFsmEvent *msg);
extern void CsrWifiSmeTspecIndHandler(void *drvpriv, CsrWifiFsmEvent *msg);
extern void CsrWifiSmeTspecCfmHandler(void *drvpriv, CsrWifiFsmEvent *msg);
extern void CsrWifiSmeVersionsGetCfmHandler(void *drvpriv,
CsrWifiFsmEvent *msg);
extern void CsrWifiSmeWifiFlightmodeCfmHandler(void *drvpriv,
CsrWifiFsmEvent *msg);
extern void CsrWifiSmeWifiOffIndHandler(void *drvpriv, CsrWifiFsmEvent *msg);
extern void CsrWifiSmeWifiOffCfmHandler(void *drvpriv, CsrWifiFsmEvent *msg);
extern void CsrWifiSmeWifiOnCfmHandler(void *drvpriv, CsrWifiFsmEvent *msg);
extern void CsrWifiSmeCloakedSsidsSetCfmHandler(void *drvpriv,
CsrWifiFsmEvent *msg);
extern void CsrWifiSmeCloakedSsidsGetCfmHandler(void *drvpriv,
CsrWifiFsmEvent *msg);
extern void CsrWifiSmeWifiOnIndHandler(void *drvpriv, CsrWifiFsmEvent *msg);
extern void CsrWifiSmeSmeCommonConfigGetCfmHandler(void *drvpriv,
CsrWifiFsmEvent *msg);
extern void CsrWifiSmeSmeCommonConfigSetCfmHandler(void *drvpriv,
CsrWifiFsmEvent *msg);
extern void CsrWifiSmeGetInterfaceCapabilityCfmHandler(void *drvpriv,
CsrWifiFsmEvent *msg);
extern void CsrWifiSmeErrorIndHandler(void *drvpriv, CsrWifiFsmEvent *msg);
extern void CsrWifiSmeInfoIndHandler(void *drvpriv, CsrWifiFsmEvent *msg);
extern void CsrWifiSmeCoreDumpIndHandler(void *drvpriv, CsrWifiFsmEvent *msg);
extern void CsrWifiSmeAmpStatusChangeIndHandler(void *drvpriv,
CsrWifiFsmEvent *msg);
#endif /* CSR_WIFI_ROUTER_SEF_CSR_WIFI_SME_H__ */
|
b342c26a943ee91a3835795bc64372a7f697853f
|
f367e4b66a1ee42e85830b31df88f63723c36a47
|
/lib/c-ares-1.19.1/src/lib/ares_process.c
|
6cac0a99fdf90d46fa57623ca67bdc52ffb9c4e8
|
[
"MIT",
"NTP",
"Apache-2.0"
] |
permissive
|
fluent/fluent-bit
|
06873e441162b92941024e9a7e9e8fc934150bf7
|
1a41f49dc2f3ae31a780caa9ffd6137b1d703065
|
refs/heads/master
| 2023-09-05T13:44:55.347372
| 2023-09-05T10:14:33
| 2023-09-05T10:14:33
| 29,933,948
| 4,907
| 1,565
|
Apache-2.0
| 2023-09-14T10:17:02
| 2015-01-27T20:41:52
|
C
|
UTF-8
|
C
| false
| false
| 50,122
|
c
|
ares_process.c
|
/* Copyright 1998 by the Massachusetts Institute of Technology.
* Copyright (C) 2004-2017 by Daniel Stenberg
*
* Permission to use, copy, modify, and distribute this
* software and its documentation for any purpose and without
* fee is hereby granted, provided that the above copyright
* notice appear in all copies and that both that copyright
* notice and this permission notice appear in supporting
* documentation, and that the name of M.I.T. not be used in
* advertising or publicity pertaining to distribution of the
* software without specific, written prior permission.
* M.I.T. makes no representations about the suitability of
* this software for any purpose. It is provided "as is"
* without express or implied warranty.
*/
#include "ares_setup.h"
#ifdef HAVE_SYS_UIO_H
# include <sys/uio.h>
#endif
#ifdef HAVE_NETINET_IN_H
# include <netinet/in.h>
#endif
#ifdef HAVE_NETINET_TCP_H
# include <netinet/tcp.h>
#endif
#ifdef HAVE_NETDB_H
# include <netdb.h>
#endif
#ifdef HAVE_ARPA_INET_H
# include <arpa/inet.h>
#endif
#include "ares_nameser.h"
#ifdef HAVE_STRINGS_H
# include <strings.h>
#endif
#ifdef HAVE_SYS_IOCTL_H
# include <sys/ioctl.h>
#endif
#ifdef NETWARE
# include <sys/filio.h>
#endif
#include <assert.h>
#include <fcntl.h>
#include <limits.h>
#include "ares.h"
#include "ares_dns.h"
#include "ares_nowarn.h"
#include "ares_private.h"
static int try_again(int errnum);
static void write_tcp_data(ares_channel channel, fd_set *write_fds,
ares_socket_t write_fd, struct timeval *now);
static void read_tcp_data(ares_channel channel, fd_set *read_fds,
ares_socket_t read_fd, struct timeval *now);
static void read_udp_packets(ares_channel channel, fd_set *read_fds,
ares_socket_t read_fd, struct timeval *now);
static void advance_tcp_send_queue(ares_channel channel, int whichserver,
ares_ssize_t num_bytes);
static void process_timeouts(ares_channel channel, struct timeval *now);
static void process_broken_connections(ares_channel channel,
struct timeval *now);
static void process_answer(ares_channel channel, unsigned char *abuf,
int alen, int whichserver, int tcp,
struct timeval *now);
static void handle_error(ares_channel channel, int whichserver,
struct timeval *now);
static void skip_server(ares_channel channel, struct query *query,
int whichserver);
static void next_server(ares_channel channel, struct query *query,
struct timeval *now);
static int open_tcp_socket(ares_channel channel, struct server_state *server);
static int open_udp_socket(ares_channel channel, struct server_state *server);
static int same_questions(const unsigned char *qbuf, int qlen,
const unsigned char *abuf, int alen);
static int same_address(struct sockaddr *sa, struct ares_addr *aa);
static int has_opt_rr(const unsigned char *abuf, int alen);
static void end_query(ares_channel channel, struct query *query, int status,
unsigned char *abuf, int alen);
/* return true if now is exactly check time or later */
int ares__timedout(struct timeval *now,
struct timeval *check)
{
long secs = (now->tv_sec - check->tv_sec);
if(secs > 0)
return 1; /* yes, timed out */
if(secs < 0)
return 0; /* nope, not timed out */
/* if the full seconds were identical, check the sub second parts */
return (now->tv_usec - check->tv_usec >= 0);
}
/* add the specific number of milliseconds to the time in the first argument */
static void timeadd(struct timeval *now, int millisecs)
{
now->tv_sec += millisecs/1000;
now->tv_usec += (millisecs%1000)*1000;
if(now->tv_usec >= 1000000) {
++(now->tv_sec);
now->tv_usec -= 1000000;
}
}
/*
* generic process function
*/
static void processfds(ares_channel channel,
fd_set *read_fds, ares_socket_t read_fd,
fd_set *write_fds, ares_socket_t write_fd)
{
struct timeval now = ares__tvnow();
write_tcp_data(channel, write_fds, write_fd, &now);
read_tcp_data(channel, read_fds, read_fd, &now);
read_udp_packets(channel, read_fds, read_fd, &now);
process_timeouts(channel, &now);
process_broken_connections(channel, &now);
}
/* Something interesting happened on the wire, or there was a timeout.
* See what's up and respond accordingly.
*/
void ares_process(ares_channel channel, fd_set *read_fds, fd_set *write_fds)
{
processfds(channel, read_fds, ARES_SOCKET_BAD, write_fds, ARES_SOCKET_BAD);
}
/* Something interesting happened on the wire, or there was a timeout.
* See what's up and respond accordingly.
*/
void ares_process_fd(ares_channel channel,
ares_socket_t read_fd, /* use ARES_SOCKET_BAD or valid
file descriptors */
ares_socket_t write_fd)
{
processfds(channel, NULL, read_fd, NULL, write_fd);
}
/* Return 1 if the specified error number describes a readiness error, or 0
* otherwise. This is mostly for HP-UX, which could return EAGAIN or
* EWOULDBLOCK. See this man page
*
* http://devrsrc1.external.hp.com/STKS/cgi-bin/man2html?
* manpage=/usr/share/man/man2.Z/send.2
*/
static int try_again(int errnum)
{
#if !defined EWOULDBLOCK && !defined EAGAIN
#error "Neither EWOULDBLOCK nor EAGAIN defined"
#endif
switch (errnum)
{
#ifdef EWOULDBLOCK
case EWOULDBLOCK:
return 1;
#endif
#if defined EAGAIN && EAGAIN != EWOULDBLOCK
case EAGAIN:
return 1;
#endif
}
return 0;
}
static ares_ssize_t socket_writev(ares_channel channel, ares_socket_t s, const struct iovec * vec, int len)
{
if (channel->sock_funcs)
return channel->sock_funcs->asendv(s, vec, len, channel->sock_func_cb_data);
return writev(s, vec, len);
}
static ares_ssize_t socket_write(ares_channel channel, ares_socket_t s, const void * data, size_t len)
{
if (channel->sock_funcs)
{
struct iovec vec;
vec.iov_base = (void*)data;
vec.iov_len = len;
return channel->sock_funcs->asendv(s, &vec, 1, channel->sock_func_cb_data);
}
return swrite(s, data, len);
}
/* If any TCP sockets select true for writing, write out queued data
* we have for them.
*/
static void write_tcp_data(ares_channel channel,
fd_set *write_fds,
ares_socket_t write_fd,
struct timeval *now)
{
struct server_state *server;
struct send_request *sendreq;
struct iovec *vec;
int i;
ares_ssize_t scount;
ares_ssize_t wcount;
size_t n;
/* From writev manpage: An implementation can advertise its limit by defining
IOV_MAX in <limits.h> or at run time via the return value from
sysconf(_SC_IOV_MAX). On modern Linux systems, the limit is 1024. Back in
Linux 2.0 days, this limit was 16. */
#if defined(IOV_MAX)
const size_t maxn = IOV_MAX; /* FreeBSD */
#elif defined(_SC_IOV_MAX)
const size_t maxn = sysconf(_SC_IOV_MAX); /* Linux */
#else
const size_t maxn = 16; /* Safe default */
#endif
if(!write_fds && (write_fd == ARES_SOCKET_BAD))
/* no possible action */
return;
for (i = 0; i < channel->nservers; i++)
{
/* Make sure server has data to send and is selected in write_fds or
write_fd. */
server = &channel->servers[i];
if (!server->qhead || server->tcp_socket == ARES_SOCKET_BAD ||
server->is_broken)
continue;
if(write_fds) {
if(!FD_ISSET(server->tcp_socket, write_fds))
continue;
}
else {
if(server->tcp_socket != write_fd)
continue;
}
if(write_fds)
/* If there's an error and we close this socket, then open
* another with the same fd to talk to another server, then we
* don't want to think that it was the new socket that was
* ready. This is not disastrous, but is likely to result in
* extra system calls and confusion. */
FD_CLR(server->tcp_socket, write_fds);
/* Count the number of send queue items. */
n = 0;
for (sendreq = server->qhead; sendreq; sendreq = sendreq->next)
n++;
/* Allocate iovecs so we can send all our data at once. */
vec = ares_malloc(n * sizeof(struct iovec));
if (vec)
{
/* Fill in the iovecs and send. */
n = 0;
for (sendreq = server->qhead; sendreq; sendreq = sendreq->next)
{
vec[n].iov_base = (char *) sendreq->data;
vec[n].iov_len = sendreq->len;
n++;
if(n >= maxn)
break;
}
wcount = socket_writev(channel, server->tcp_socket, vec, (int)n);
ares_free(vec);
if (wcount < 0)
{
if (!try_again(SOCKERRNO))
handle_error(channel, i, now);
continue;
}
/* Advance the send queue by as many bytes as we sent. */
advance_tcp_send_queue(channel, i, wcount);
}
else
{
/* Can't allocate iovecs; just send the first request. */
sendreq = server->qhead;
scount = socket_write(channel, server->tcp_socket, sendreq->data, sendreq->len);
if (scount < 0)
{
if (!try_again(SOCKERRNO))
handle_error(channel, i, now);
continue;
}
/* Advance the send queue by as many bytes as we sent. */
advance_tcp_send_queue(channel, i, scount);
}
}
}
/* Consume the given number of bytes from the head of the TCP send queue. */
static void advance_tcp_send_queue(ares_channel channel, int whichserver,
ares_ssize_t num_bytes)
{
struct send_request *sendreq;
struct server_state *server = &channel->servers[whichserver];
while (num_bytes > 0) {
sendreq = server->qhead;
if ((size_t)num_bytes >= sendreq->len) {
num_bytes -= sendreq->len;
server->qhead = sendreq->next;
if (sendreq->data_storage)
ares_free(sendreq->data_storage);
ares_free(sendreq);
if (server->qhead == NULL) {
SOCK_STATE_CALLBACK(channel, server->tcp_socket, 1, 0);
server->qtail = NULL;
/* qhead is NULL so we cannot continue this loop */
break;
}
}
else {
sendreq->data += num_bytes;
sendreq->len -= num_bytes;
num_bytes = 0;
}
}
}
static ares_ssize_t socket_recvfrom(ares_channel channel,
ares_socket_t s,
void * data,
size_t data_len,
int flags,
struct sockaddr *from,
ares_socklen_t *from_len)
{
if (channel->sock_funcs)
return channel->sock_funcs->arecvfrom(s, data, data_len,
flags, from, from_len,
channel->sock_func_cb_data);
#ifdef HAVE_RECVFROM
return recvfrom(s, data, data_len, flags, from, from_len);
#else
return sread(s, data, data_len);
#endif
}
static ares_ssize_t socket_recv(ares_channel channel,
ares_socket_t s,
void * data,
size_t data_len)
{
if (channel->sock_funcs)
return channel->sock_funcs->arecvfrom(s, data, data_len, 0, 0, 0,
channel->sock_func_cb_data);
return sread(s, data, data_len);
}
/* If any TCP socket selects true for reading, read some data,
* allocate a buffer if we finish reading the length word, and process
* a packet if we finish reading one.
*/
static void read_tcp_data(ares_channel channel, fd_set *read_fds,
ares_socket_t read_fd, struct timeval *now)
{
struct server_state *server;
int i;
ares_ssize_t count;
if(!read_fds && (read_fd == ARES_SOCKET_BAD))
/* no possible action */
return;
for (i = 0; i < channel->nservers; i++)
{
/* Make sure the server has a socket and is selected in read_fds. */
server = &channel->servers[i];
if (server->tcp_socket == ARES_SOCKET_BAD || server->is_broken)
continue;
if(read_fds) {
if(!FD_ISSET(server->tcp_socket, read_fds))
continue;
}
else {
if(server->tcp_socket != read_fd)
continue;
}
if(read_fds)
/* If there's an error and we close this socket, then open another
* with the same fd to talk to another server, then we don't want to
* think that it was the new socket that was ready. This is not
* disastrous, but is likely to result in extra system calls and
* confusion. */
FD_CLR(server->tcp_socket, read_fds);
if (server->tcp_lenbuf_pos != 2)
{
/* We haven't yet read a length word, so read that (or
* what's left to read of it).
*/
count = socket_recv(channel, server->tcp_socket,
server->tcp_lenbuf + server->tcp_lenbuf_pos,
2 - server->tcp_lenbuf_pos);
if (count <= 0)
{
if (!(count == -1 && try_again(SOCKERRNO)))
handle_error(channel, i, now);
continue;
}
server->tcp_lenbuf_pos += (int)count;
if (server->tcp_lenbuf_pos == 2)
{
/* We finished reading the length word. Decode the
* length and allocate a buffer for the data.
*/
server->tcp_length = server->tcp_lenbuf[0] << 8
| server->tcp_lenbuf[1];
server->tcp_buffer = ares_malloc(server->tcp_length);
if (!server->tcp_buffer) {
handle_error(channel, i, now);
return; /* bail out on malloc failure. TODO: make this
function return error codes */
}
server->tcp_buffer_pos = 0;
}
}
else
{
/* Read data into the allocated buffer. */
count = socket_recv(channel, server->tcp_socket,
server->tcp_buffer + server->tcp_buffer_pos,
server->tcp_length - server->tcp_buffer_pos);
if (count <= 0)
{
if (!(count == -1 && try_again(SOCKERRNO)))
handle_error(channel, i, now);
continue;
}
server->tcp_buffer_pos += (int)count;
if (server->tcp_buffer_pos == server->tcp_length)
{
/* We finished reading this answer; process it and
* prepare to read another length word.
*/
process_answer(channel, server->tcp_buffer, server->tcp_length,
i, 1, now);
ares_free(server->tcp_buffer);
server->tcp_buffer = NULL;
server->tcp_lenbuf_pos = 0;
server->tcp_buffer_pos = 0;
}
}
}
}
/* If any UDP sockets select true for reading, process them. */
static void read_udp_packets(ares_channel channel, fd_set *read_fds,
ares_socket_t read_fd, struct timeval *now)
{
struct server_state *server;
int i;
ares_ssize_t read_len;
unsigned char buf[MAXENDSSZ + 1];
#ifdef HAVE_RECVFROM
ares_socklen_t fromlen;
union {
struct sockaddr sa;
struct sockaddr_in sa4;
struct sockaddr_in6 sa6;
} from;
#endif
if(!read_fds && (read_fd == ARES_SOCKET_BAD))
/* no possible action */
return;
for (i = 0; i < channel->nservers; i++)
{
/* Make sure the server has a socket and is selected in read_fds. */
server = &channel->servers[i];
if (server->udp_socket == ARES_SOCKET_BAD || server->is_broken)
continue;
if(read_fds) {
if(!FD_ISSET(server->udp_socket, read_fds))
continue;
}
else {
if(server->udp_socket != read_fd)
continue;
}
if(read_fds)
/* If there's an error and we close this socket, then open
* another with the same fd to talk to another server, then we
* don't want to think that it was the new socket that was
* ready. This is not disastrous, but is likely to result in
* extra system calls and confusion. */
FD_CLR(server->udp_socket, read_fds);
/* To reduce event loop overhead, read and process as many
* packets as we can. */
do {
if (server->udp_socket == ARES_SOCKET_BAD) {
read_len = -1;
} else {
if (server->addr.family == AF_INET) {
fromlen = sizeof(from.sa4);
} else {
fromlen = sizeof(from.sa6);
}
read_len = socket_recvfrom(channel, server->udp_socket, (void *)buf,
sizeof(buf), 0, &from.sa, &fromlen);
}
if (read_len == 0) {
/* UDP is connectionless, so result code of 0 is a 0-length UDP
* packet, and not an indication the connection is closed like on
* tcp */
continue;
} else if (read_len < 0) {
if (try_again(SOCKERRNO))
continue;
handle_error(channel, i, now);
#ifdef HAVE_RECVFROM
} else if (!same_address(&from.sa, &server->addr)) {
/* The address the response comes from does not match the address we
* sent the request to. Someone may be attempting to perform a cache
* poisoning attack. */
continue;
#endif
} else {
process_answer(channel, buf, (int)read_len, i, 0, now);
}
} while (read_len >= 0);
}
}
/* If any queries have timed out, note the timeout and move them on. */
static void process_timeouts(ares_channel channel, struct timeval *now)
{
time_t t; /* the time of the timeouts we're processing */
struct query *query;
struct list_node* list_head;
struct list_node* list_node;
/* Process all the timeouts that have fired since the last time we processed
* timeouts. If things are going well, then we'll have hundreds/thousands of
* queries that fall into future buckets, and only a handful of requests
* that fall into the "now" bucket, so this should be quite quick.
*/
for (t = channel->last_timeout_processed; t <= now->tv_sec; t++)
{
list_head = &(channel->queries_by_timeout[t % ARES_TIMEOUT_TABLE_SIZE]);
for (list_node = list_head->next; list_node != list_head; )
{
query = list_node->data;
list_node = list_node->next; /* in case the query gets deleted */
if (query->timeout.tv_sec && ares__timedout(now, &query->timeout))
{
query->error_status = ARES_ETIMEOUT;
++query->timeouts;
next_server(channel, query, now);
}
}
}
channel->last_timeout_processed = now->tv_sec;
}
/* Handle an answer from a server. */
static void process_answer(ares_channel channel, unsigned char *abuf,
int alen, int whichserver, int tcp,
struct timeval *now)
{
int tc, rcode, packetsz;
unsigned short id;
struct query *query;
struct list_node* list_head;
struct list_node* list_node;
/* If there's no room in the answer for a header, we can't do much
* with it. */
if (alen < HFIXEDSZ)
return;
/* Grab the query ID, truncate bit, and response code from the packet. */
id = DNS_HEADER_QID(abuf);
tc = DNS_HEADER_TC(abuf);
rcode = DNS_HEADER_RCODE(abuf);
/* Find the query corresponding to this packet. The queries are
* hashed/bucketed by query id, so this lookup should be quick. Note that
* both the query id and the questions must be the same; when the query id
* wraps around we can have multiple outstanding queries with the same query
* id, so we need to check both the id and question.
*/
query = NULL;
list_head = &(channel->queries_by_qid[id % ARES_QID_TABLE_SIZE]);
for (list_node = list_head->next; list_node != list_head;
list_node = list_node->next)
{
struct query *q = list_node->data;
if ((q->qid == id) && same_questions(q->qbuf, q->qlen, abuf, alen))
{
query = q;
break;
}
}
if (!query)
return;
packetsz = PACKETSZ;
/* If we use EDNS and server answers with FORMERR without an OPT RR, the protocol
* extension is not understood by the responder. We must retry the query
* without EDNS enabled. */
if (channel->flags & ARES_FLAG_EDNS)
{
packetsz = channel->ednspsz;
if (rcode == FORMERR && has_opt_rr(abuf, alen) != 1)
{
int qlen = (query->tcplen - 2) - EDNSFIXEDSZ;
channel->flags ^= ARES_FLAG_EDNS;
query->tcplen -= EDNSFIXEDSZ;
query->qlen -= EDNSFIXEDSZ;
query->tcpbuf[0] = (unsigned char)((qlen >> 8) & 0xff);
query->tcpbuf[1] = (unsigned char)(qlen & 0xff);
DNS_HEADER_SET_ARCOUNT(query->tcpbuf + 2, 0);
query->tcpbuf = ares_realloc(query->tcpbuf, query->tcplen);
query->qbuf = query->tcpbuf + 2;
ares__send_query(channel, query, now);
return;
}
}
/* If we got a truncated UDP packet and are not ignoring truncation,
* don't accept the packet, and switch the query to TCP if we hadn't
* done so already.
*/
if ((tc || alen > packetsz) && !tcp && !(channel->flags & ARES_FLAG_IGNTC))
{
if (!query->using_tcp)
{
query->using_tcp = 1;
ares__send_query(channel, query, now);
}
return;
}
/* Limit alen to PACKETSZ if we aren't using TCP (only relevant if we
* are ignoring truncation.
*/
if (alen > packetsz && !tcp)
alen = packetsz;
/* If we aren't passing through all error packets, discard packets
* with SERVFAIL, NOTIMP, or REFUSED response codes.
*/
if (!(channel->flags & ARES_FLAG_NOCHECKRESP))
{
if (rcode == SERVFAIL || rcode == NOTIMP || rcode == REFUSED)
{
skip_server(channel, query, whichserver);
if (query->server == whichserver)
next_server(channel, query, now);
return;
}
}
end_query(channel, query, ARES_SUCCESS, abuf, alen);
}
/* Close all the connections that are no longer usable. */
static void process_broken_connections(ares_channel channel,
struct timeval *now)
{
int i;
for (i = 0; i < channel->nservers; i++)
{
struct server_state *server = &channel->servers[i];
if (server->is_broken)
{
handle_error(channel, i, now);
}
}
}
/* Swap the contents of two lists */
static void swap_lists(struct list_node* head_a,
struct list_node* head_b)
{
int is_a_empty = ares__is_list_empty(head_a);
int is_b_empty = ares__is_list_empty(head_b);
struct list_node old_a = *head_a;
struct list_node old_b = *head_b;
if (is_a_empty) {
ares__init_list_head(head_b);
} else {
*head_b = old_a;
old_a.next->prev = head_b;
old_a.prev->next = head_b;
}
if (is_b_empty) {
ares__init_list_head(head_a);
} else {
*head_a = old_b;
old_b.next->prev = head_a;
old_b.prev->next = head_a;
}
}
static void handle_error(ares_channel channel, int whichserver,
struct timeval *now)
{
struct server_state *server;
struct query *query;
struct list_node list_head;
struct list_node* list_node;
server = &channel->servers[whichserver];
/* Reset communications with this server. */
ares__close_sockets(channel, server);
/* Tell all queries talking to this server to move on and not try this
* server again. We steal the current list of queries that were in-flight to
* this server, since when we call next_server this can cause the queries to
* be re-sent to this server, which will re-insert these queries in that
* same server->queries_to_server list.
*/
ares__init_list_head(&list_head);
swap_lists(&list_head, &(server->queries_to_server));
for (list_node = list_head.next; list_node != &list_head; )
{
query = list_node->data;
list_node = list_node->next; /* in case the query gets deleted */
assert(query->server == whichserver);
skip_server(channel, query, whichserver);
next_server(channel, query, now);
}
/* Each query should have removed itself from our temporary list as
* it re-sent itself or finished up...
*/
assert(ares__is_list_empty(&list_head));
}
static void skip_server(ares_channel channel, struct query *query,
int whichserver)
{
/* The given server gave us problems with this query, so if we have the
* luxury of using other servers, then let's skip the potentially broken
* server and just use the others. If we only have one server and we need to
* retry then we should just go ahead and re-use that server, since it's our
* only hope; perhaps we just got unlucky, and retrying will work (eg, the
* server timed out our TCP connection just as we were sending another
* request).
*/
if (channel->nservers > 1)
{
query->server_info[whichserver].skip_server = 1;
}
}
static void next_server(ares_channel channel, struct query *query,
struct timeval *now)
{
/* We need to try each server channel->tries times. We have channel->nservers
* servers to try. In total, we need to do channel->nservers * channel->tries
* attempts. Use query->try to remember how many times we already attempted
* this query. Use modular arithmetic to find the next server to try. */
while (++(query->try_count) < (channel->nservers * channel->tries))
{
struct server_state *server;
/* Move on to the next server. */
query->server = (query->server + 1) % channel->nservers;
server = &channel->servers[query->server];
/* We don't want to use this server if (1) we decided this connection is
* broken, and thus about to be closed, (2) we've decided to skip this
* server because of earlier errors we encountered, or (3) we already
* sent this query over this exact connection.
*/
if (!server->is_broken &&
!query->server_info[query->server].skip_server &&
!(query->using_tcp &&
(query->server_info[query->server].tcp_connection_generation ==
server->tcp_connection_generation)))
{
ares__send_query(channel, query, now);
return;
}
/* You might think that with TCP we only need one try. However, even
* when using TCP, servers can time-out our connection just as we're
* sending a request, or close our connection because they die, or never
* send us a reply because they get wedged or tickle a bug that drops
* our request.
*/
}
/* If we are here, all attempts to perform query failed. */
end_query(channel, query, query->error_status, NULL, 0);
}
void ares__send_query(ares_channel channel, struct query *query,
struct timeval *now)
{
struct send_request *sendreq;
struct server_state *server;
int timeplus;
server = &channel->servers[query->server];
if (query->using_tcp)
{
/* Make sure the TCP socket for this server is set up and queue
* a send request.
*/
if (server->tcp_socket == ARES_SOCKET_BAD)
{
if (open_tcp_socket(channel, server) == -1)
{
skip_server(channel, query, query->server);
next_server(channel, query, now);
return;
}
}
sendreq = ares_malloc(sizeof(struct send_request));
if (!sendreq)
{
end_query(channel, query, ARES_ENOMEM, NULL, 0);
return;
}
memset(sendreq, 0, sizeof(struct send_request));
/* To make the common case fast, we avoid copies by using the query's
* tcpbuf for as long as the query is alive. In the rare case where the
* query ends while it's queued for transmission, then we give the
* sendreq its own copy of the request packet and put it in
* sendreq->data_storage.
*/
sendreq->data_storage = NULL;
sendreq->data = query->tcpbuf;
sendreq->len = query->tcplen;
sendreq->owner_query = query;
sendreq->next = NULL;
if (server->qtail)
server->qtail->next = sendreq;
else
{
SOCK_STATE_CALLBACK(channel, server->tcp_socket, 1, 1);
server->qhead = sendreq;
}
server->qtail = sendreq;
query->server_info[query->server].tcp_connection_generation =
server->tcp_connection_generation;
}
else
{
if (server->udp_socket == ARES_SOCKET_BAD)
{
if (open_udp_socket(channel, server) == -1)
{
skip_server(channel, query, query->server);
next_server(channel, query, now);
return;
}
}
if (socket_write(channel, server->udp_socket, query->qbuf, query->qlen) == -1)
{
/* FIXME: Handle EAGAIN here since it likely can happen. */
skip_server(channel, query, query->server);
next_server(channel, query, now);
return;
}
}
/* For each trip through the entire server list, double the channel's
* assigned timeout, avoiding overflow. If channel->timeout is negative,
* leave it as-is, even though that should be impossible here.
*/
timeplus = channel->timeout;
{
/* How many times do we want to double it? Presume sane values here. */
const int shift = query->try_count / channel->nservers;
/* Is there enough room to shift timeplus left that many times?
*
* To find out, confirm that all of the bits we'll shift away are zero.
* Stop considering a shift if we get to the point where we could shift
* a 1 into the sign bit (i.e. when shift is within two of the bit
* count).
*
* This has the side benefit of leaving negative numbers unchanged.
*/
if(shift <= (int)(sizeof(int) * CHAR_BIT - 1)
&& (timeplus >> (sizeof(int) * CHAR_BIT - 1 - shift)) == 0)
{
timeplus <<= shift;
}
}
query->timeout = *now;
timeadd(&query->timeout, timeplus);
/* Keep track of queries bucketed by timeout, so we can process
* timeout events quickly.
*/
ares__remove_from_list(&(query->queries_by_timeout));
ares__insert_in_list(
&(query->queries_by_timeout),
&(channel->queries_by_timeout[query->timeout.tv_sec %
ARES_TIMEOUT_TABLE_SIZE]));
/* Keep track of queries bucketed by server, so we can process server
* errors quickly.
*/
ares__remove_from_list(&(query->queries_to_server));
ares__insert_in_list(&(query->queries_to_server),
&(server->queries_to_server));
}
/*
* setsocknonblock sets the given socket to either blocking or non-blocking
* mode based on the 'nonblock' boolean argument. This function is highly
* portable.
*/
static int setsocknonblock(ares_socket_t sockfd, /* operate on this */
int nonblock /* TRUE or FALSE */)
{
#if defined(USE_BLOCKING_SOCKETS)
return 0; /* returns success */
#elif defined(HAVE_FCNTL_O_NONBLOCK)
/* most recent unix versions */
int flags;
flags = fcntl(sockfd, F_GETFL, 0);
if (FALSE != nonblock)
return fcntl(sockfd, F_SETFL, flags | O_NONBLOCK);
else
return fcntl(sockfd, F_SETFL, flags & (~O_NONBLOCK)); /* LCOV_EXCL_LINE */
#elif defined(HAVE_IOCTL_FIONBIO)
/* older unix versions */
int flags = nonblock ? 1 : 0;
return ioctl(sockfd, FIONBIO, &flags);
#elif defined(HAVE_IOCTLSOCKET_FIONBIO)
#ifdef WATT32
char flags = nonblock ? 1 : 0;
#else
/* Windows */
unsigned long flags = nonblock ? 1UL : 0UL;
#endif
return ioctlsocket(sockfd, FIONBIO, &flags);
#elif defined(HAVE_IOCTLSOCKET_CAMEL_FIONBIO)
/* Amiga */
long flags = nonblock ? 1L : 0L;
return IoctlSocket(sockfd, FIONBIO, flags);
#elif defined(HAVE_SETSOCKOPT_SO_NONBLOCK)
/* BeOS */
long b = nonblock ? 1L : 0L;
return setsockopt(sockfd, SOL_SOCKET, SO_NONBLOCK, &b, sizeof(b));
#else
# error "no non-blocking method was found/used/set"
#endif
}
#if defined(IPV6_V6ONLY) && defined(WIN32)
/* It makes support for IPv4-mapped IPv6 addresses.
* Linux kernel, NetBSD, FreeBSD and Darwin: default is off;
* Windows Vista and later: default is on;
* DragonFly BSD: acts like off, and dummy setting;
* OpenBSD and earlier Windows: unsupported.
* Linux: controlled by /proc/sys/net/ipv6/bindv6only.
*/
static void set_ipv6_v6only(ares_socket_t sockfd, int on)
{
(void)setsockopt(sockfd, IPPROTO_IPV6, IPV6_V6ONLY, (void *)&on, sizeof(on));
}
#else
#define set_ipv6_v6only(s,v)
#endif
static int configure_socket(ares_socket_t s, int family, ares_channel channel)
{
union {
struct sockaddr sa;
struct sockaddr_in sa4;
struct sockaddr_in6 sa6;
} local;
/* do not set options for user-managed sockets */
if (channel->sock_funcs)
return 0;
(void)setsocknonblock(s, TRUE);
#if defined(FD_CLOEXEC) && !defined(MSDOS)
/* Configure the socket fd as close-on-exec. */
if (fcntl(s, F_SETFD, FD_CLOEXEC) == -1)
return -1; /* LCOV_EXCL_LINE */
#endif
/* Set the socket's send and receive buffer sizes. */
if ((channel->socket_send_buffer_size > 0) &&
setsockopt(s, SOL_SOCKET, SO_SNDBUF,
(void *)&channel->socket_send_buffer_size,
sizeof(channel->socket_send_buffer_size)) == -1)
return -1;
if ((channel->socket_receive_buffer_size > 0) &&
setsockopt(s, SOL_SOCKET, SO_RCVBUF,
(void *)&channel->socket_receive_buffer_size,
sizeof(channel->socket_receive_buffer_size)) == -1)
return -1;
#ifdef SO_BINDTODEVICE
if (channel->local_dev_name[0]) {
if (setsockopt(s, SOL_SOCKET, SO_BINDTODEVICE,
channel->local_dev_name, sizeof(channel->local_dev_name))) {
/* Only root can do this, and usually not fatal if it doesn't work, so */
/* just continue on. */
}
}
#endif
if (family == AF_INET) {
if (channel->local_ip4) {
memset(&local.sa4, 0, sizeof(local.sa4));
local.sa4.sin_family = AF_INET;
local.sa4.sin_addr.s_addr = htonl(channel->local_ip4);
if (bind(s, &local.sa, sizeof(local.sa4)) < 0)
return -1;
}
}
else if (family == AF_INET6) {
if (memcmp(channel->local_ip6, &ares_in6addr_any,
sizeof(channel->local_ip6)) != 0) {
memset(&local.sa6, 0, sizeof(local.sa6));
local.sa6.sin6_family = AF_INET6;
memcpy(&local.sa6.sin6_addr, channel->local_ip6,
sizeof(channel->local_ip6));
if (bind(s, &local.sa, sizeof(local.sa6)) < 0)
return -1;
}
set_ipv6_v6only(s, 0);
}
return 0;
}
static int open_tcp_socket(ares_channel channel, struct server_state *server)
{
ares_socket_t s;
int opt;
ares_socklen_t salen;
union {
struct sockaddr_in sa4;
struct sockaddr_in6 sa6;
} saddr;
struct sockaddr *sa;
switch (server->addr.family)
{
case AF_INET:
sa = (void *)&saddr.sa4;
salen = sizeof(saddr.sa4);
memset(sa, 0, salen);
saddr.sa4.sin_family = AF_INET;
if (server->addr.tcp_port) {
saddr.sa4.sin_port = aresx_sitous(server->addr.tcp_port);
} else {
saddr.sa4.sin_port = aresx_sitous(channel->tcp_port);
}
memcpy(&saddr.sa4.sin_addr, &server->addr.addrV4,
sizeof(server->addr.addrV4));
break;
case AF_INET6:
sa = (void *)&saddr.sa6;
salen = sizeof(saddr.sa6);
memset(sa, 0, salen);
saddr.sa6.sin6_family = AF_INET6;
if (server->addr.tcp_port) {
saddr.sa6.sin6_port = aresx_sitous(server->addr.tcp_port);
} else {
saddr.sa6.sin6_port = aresx_sitous(channel->tcp_port);
}
memcpy(&saddr.sa6.sin6_addr, &server->addr.addrV6,
sizeof(server->addr.addrV6));
break;
default:
return -1; /* LCOV_EXCL_LINE */
}
/* Acquire a socket. */
s = ares__open_socket(channel, server->addr.family, SOCK_STREAM, 0);
if (s == ARES_SOCKET_BAD)
return -1;
/* Configure it. */
if (configure_socket(s, server->addr.family, channel) < 0)
{
ares__close_socket(channel, s);
return -1;
}
#ifdef TCP_NODELAY
/*
* Disable the Nagle algorithm (only relevant for TCP sockets, and thus not
* in configure_socket). In general, in DNS lookups we're pretty much
* interested in firing off a single request and then waiting for a reply,
* so batching isn't very interesting.
*/
opt = 1;
if (channel->sock_funcs == 0
&&
setsockopt(s, IPPROTO_TCP, TCP_NODELAY,
(void *)&opt, sizeof(opt)) == -1)
{
ares__close_socket(channel, s);
return -1;
}
#endif
if (channel->sock_config_cb)
{
int err = channel->sock_config_cb(s, SOCK_STREAM,
channel->sock_config_cb_data);
if (err < 0)
{
ares__close_socket(channel, s);
return err;
}
}
/* Connect to the server. */
if (ares__connect_socket(channel, s, sa, salen) == -1)
{
int err = SOCKERRNO;
if (err != EINPROGRESS && err != EWOULDBLOCK)
{
ares__close_socket(channel, s);
return -1;
}
}
if (channel->sock_create_cb)
{
int err = channel->sock_create_cb(s, SOCK_STREAM,
channel->sock_create_cb_data);
if (err < 0)
{
ares__close_socket(channel, s);
return err;
}
}
SOCK_STATE_CALLBACK(channel, s, 1, 0);
server->tcp_buffer_pos = 0;
server->tcp_socket = s;
server->tcp_connection_generation = ++channel->tcp_connection_generation;
return 0;
}
static int open_udp_socket(ares_channel channel, struct server_state *server)
{
ares_socket_t s;
ares_socklen_t salen;
union {
struct sockaddr_in sa4;
struct sockaddr_in6 sa6;
} saddr;
struct sockaddr *sa;
switch (server->addr.family)
{
case AF_INET:
sa = (void *)&saddr.sa4;
salen = sizeof(saddr.sa4);
memset(sa, 0, salen);
saddr.sa4.sin_family = AF_INET;
if (server->addr.udp_port) {
saddr.sa4.sin_port = aresx_sitous(server->addr.udp_port);
} else {
saddr.sa4.sin_port = aresx_sitous(channel->udp_port);
}
memcpy(&saddr.sa4.sin_addr, &server->addr.addrV4,
sizeof(server->addr.addrV4));
break;
case AF_INET6:
sa = (void *)&saddr.sa6;
salen = sizeof(saddr.sa6);
memset(sa, 0, salen);
saddr.sa6.sin6_family = AF_INET6;
if (server->addr.udp_port) {
saddr.sa6.sin6_port = aresx_sitous(server->addr.udp_port);
} else {
saddr.sa6.sin6_port = aresx_sitous(channel->udp_port);
}
memcpy(&saddr.sa6.sin6_addr, &server->addr.addrV6,
sizeof(server->addr.addrV6));
break;
default:
return -1; /* LCOV_EXCL_LINE */
}
/* Acquire a socket. */
s = ares__open_socket(channel, server->addr.family, SOCK_DGRAM, 0);
if (s == ARES_SOCKET_BAD)
return -1;
/* Set the socket non-blocking. */
if (configure_socket(s, server->addr.family, channel) < 0)
{
ares__close_socket(channel, s);
return -1;
}
if (channel->sock_config_cb)
{
int err = channel->sock_config_cb(s, SOCK_DGRAM,
channel->sock_config_cb_data);
if (err < 0)
{
ares__close_socket(channel, s);
return err;
}
}
/* Connect to the server. */
if (ares__connect_socket(channel, s, sa, salen) == -1)
{
int err = SOCKERRNO;
if (err != EINPROGRESS && err != EWOULDBLOCK)
{
ares__close_socket(channel, s);
return -1;
}
}
if (channel->sock_create_cb)
{
int err = channel->sock_create_cb(s, SOCK_DGRAM,
channel->sock_create_cb_data);
if (err < 0)
{
ares__close_socket(channel, s);
return err;
}
}
SOCK_STATE_CALLBACK(channel, s, 1, 0);
server->udp_socket = s;
return 0;
}
static int same_questions(const unsigned char *qbuf, int qlen,
const unsigned char *abuf, int alen)
{
struct {
const unsigned char *p;
int qdcount;
char *name;
long namelen;
int type;
int dnsclass;
} q, a;
int i, j;
if (qlen < HFIXEDSZ || alen < HFIXEDSZ)
return 0;
/* Extract qdcount from the request and reply buffers and compare them. */
q.qdcount = DNS_HEADER_QDCOUNT(qbuf);
a.qdcount = DNS_HEADER_QDCOUNT(abuf);
if (q.qdcount != a.qdcount)
return 0;
/* For each question in qbuf, find it in abuf. */
q.p = qbuf + HFIXEDSZ;
for (i = 0; i < q.qdcount; i++)
{
/* Decode the question in the query. */
if (ares_expand_name(q.p, qbuf, qlen, &q.name, &q.namelen)
!= ARES_SUCCESS)
return 0;
q.p += q.namelen;
if (q.p + QFIXEDSZ > qbuf + qlen)
{
ares_free(q.name);
return 0;
}
q.type = DNS_QUESTION_TYPE(q.p);
q.dnsclass = DNS_QUESTION_CLASS(q.p);
q.p += QFIXEDSZ;
/* Search for this question in the answer. */
a.p = abuf + HFIXEDSZ;
for (j = 0; j < a.qdcount; j++)
{
/* Decode the question in the answer. */
if (ares_expand_name(a.p, abuf, alen, &a.name, &a.namelen)
!= ARES_SUCCESS)
{
ares_free(q.name);
return 0;
}
a.p += a.namelen;
if (a.p + QFIXEDSZ > abuf + alen)
{
ares_free(q.name);
ares_free(a.name);
return 0;
}
a.type = DNS_QUESTION_TYPE(a.p);
a.dnsclass = DNS_QUESTION_CLASS(a.p);
a.p += QFIXEDSZ;
/* Compare the decoded questions. */
if (strcasecmp(q.name, a.name) == 0 && q.type == a.type
&& q.dnsclass == a.dnsclass)
{
ares_free(a.name);
break;
}
ares_free(a.name);
}
ares_free(q.name);
if (j == a.qdcount)
return 0;
}
return 1;
}
static int same_address(struct sockaddr *sa, struct ares_addr *aa)
{
void *addr1;
void *addr2;
if (sa->sa_family == aa->family)
{
switch (aa->family)
{
case AF_INET:
addr1 = &aa->addrV4;
addr2 = &(CARES_INADDR_CAST(struct sockaddr_in *, sa))->sin_addr;
if (memcmp(addr1, addr2, sizeof(aa->addrV4)) == 0)
return 1; /* match */
break;
case AF_INET6:
addr1 = &aa->addrV6;
addr2 = &(CARES_INADDR_CAST(struct sockaddr_in6 *, sa))->sin6_addr;
if (memcmp(addr1, addr2, sizeof(aa->addrV6)) == 0)
return 1; /* match */
break;
default:
break; /* LCOV_EXCL_LINE */
}
}
return 0; /* different */
}
/* search for an OPT RR in the response */
static int has_opt_rr(const unsigned char *abuf, int alen)
{
unsigned int qdcount, ancount, nscount, arcount, i;
const unsigned char *aptr;
int status;
if (alen < HFIXEDSZ)
return -1;
/* Parse the answer header. */
qdcount = DNS_HEADER_QDCOUNT(abuf);
ancount = DNS_HEADER_ANCOUNT(abuf);
nscount = DNS_HEADER_NSCOUNT(abuf);
arcount = DNS_HEADER_ARCOUNT(abuf);
aptr = abuf + HFIXEDSZ;
/* skip the questions */
for (i = 0; i < qdcount; i++)
{
char* name;
long len;
status = ares_expand_name(aptr, abuf, alen, &name, &len);
if (status != ARES_SUCCESS)
return -1;
ares_free_string(name);
if (aptr + len + QFIXEDSZ > abuf + alen)
return -1;
aptr += len + QFIXEDSZ;
}
/* skip the ancount and nscount */
for (i = 0; i < ancount + nscount; i++)
{
char* name;
long len;
int dlen;
status = ares_expand_name(aptr, abuf, alen, &name, &len);
if (status != ARES_SUCCESS)
return -1;
ares_free_string(name);
if (aptr + len + RRFIXEDSZ > abuf + alen)
return -1;
aptr += len;
dlen = DNS_RR_LEN(aptr);
aptr += RRFIXEDSZ;
if (aptr + dlen > abuf + alen)
return -1;
aptr += dlen;
}
/* search for rr type (41) - opt */
for (i = 0; i < arcount; i++)
{
char* name;
long len;
int dlen;
status = ares_expand_name(aptr, abuf, alen, &name, &len);
if (status != ARES_SUCCESS)
return -1;
ares_free_string(name);
if (aptr + len + RRFIXEDSZ > abuf + alen)
return -1;
aptr += len;
if (DNS_RR_TYPE(aptr) == T_OPT)
return 1;
dlen = DNS_RR_LEN(aptr);
aptr += RRFIXEDSZ;
if (aptr + dlen > abuf + alen)
return -1;
aptr += dlen;
}
return 0;
}
static void end_query (ares_channel channel, struct query *query, int status,
unsigned char *abuf, int alen)
{
int i;
/* First we check to see if this query ended while one of our send
* queues still has pointers to it.
*/
for (i = 0; i < channel->nservers; i++)
{
struct server_state *server = &channel->servers[i];
struct send_request *sendreq;
for (sendreq = server->qhead; sendreq; sendreq = sendreq->next)
if (sendreq->owner_query == query)
{
sendreq->owner_query = NULL;
assert(sendreq->data_storage == NULL);
if (status == ARES_SUCCESS)
{
/* We got a reply for this query, but this queued sendreq
* points into this soon-to-be-gone query's tcpbuf. Probably
* this means we timed out and queued the query for
* retransmission, then received a response before actually
* retransmitting. This is perfectly fine, so we want to keep
* the connection running smoothly if we can. But in the worst
* case we may have sent only some prefix of the query, with
* some suffix of the query left to send. Also, the buffer may
* be queued on multiple queues. To prevent dangling pointers
* to the query's tcpbuf and handle these cases, we just give
* such sendreqs their own copy of the query packet.
*/
sendreq->data_storage = ares_malloc(sendreq->len);
if (sendreq->data_storage != NULL)
{
memcpy(sendreq->data_storage, sendreq->data, sendreq->len);
sendreq->data = sendreq->data_storage;
}
}
if ((status != ARES_SUCCESS) || (sendreq->data_storage == NULL))
{
/* We encountered an error (probably a timeout, suggesting the
* DNS server we're talking to is probably unreachable,
* wedged, or severely overloaded) or we couldn't copy the
* request, so mark the connection as broken. When we get to
* process_broken_connections() we'll close the connection and
* try to re-send requests to another server.
*/
server->is_broken = 1;
/* Just to be paranoid, zero out this sendreq... */
sendreq->data = NULL;
sendreq->len = 0;
}
}
}
/* Invoke the callback */
query->callback(query->arg, status, query->timeouts, abuf, alen);
ares__free_query(query);
/* Simple cleanup policy: if no queries are remaining, close all network
* sockets unless STAYOPEN is set.
*/
if (!(channel->flags & ARES_FLAG_STAYOPEN) &&
ares__is_list_empty(&(channel->all_queries)))
{
for (i = 0; i < channel->nservers; i++)
ares__close_sockets(channel, &channel->servers[i]);
}
}
void ares__free_query(struct query *query)
{
/* Remove the query from all the lists in which it is linked */
ares__remove_from_list(&(query->queries_by_qid));
ares__remove_from_list(&(query->queries_by_timeout));
ares__remove_from_list(&(query->queries_to_server));
ares__remove_from_list(&(query->all_queries));
/* Zero out some important stuff, to help catch bugs */
query->callback = NULL;
query->arg = NULL;
/* Deallocate the memory associated with the query */
ares_free(query->tcpbuf);
ares_free(query->server_info);
ares_free(query);
}
ares_socket_t ares__open_socket(ares_channel channel,
int af, int type, int protocol)
{
if (channel->sock_funcs)
return channel->sock_funcs->asocket(af,
type,
protocol,
channel->sock_func_cb_data);
else
return socket(af, type, protocol);
}
int ares__connect_socket(ares_channel channel,
ares_socket_t sockfd,
const struct sockaddr *addr,
ares_socklen_t addrlen)
{
if (channel->sock_funcs)
return channel->sock_funcs->aconnect(sockfd,
addr,
addrlen,
channel->sock_func_cb_data);
else
return connect(sockfd, addr, addrlen);
}
void ares__close_socket(ares_channel channel, ares_socket_t s)
{
if (channel->sock_funcs)
channel->sock_funcs->aclose(s, channel->sock_func_cb_data);
else
sclose(s);
}
|
57764e02a84c5fa163d0fb273bb4966ff8f30605
|
e7aad0b1c5d8907dbb52000c482c396d1b801751
|
/casadm/vt100codes.h
|
76df5472a8ec7136dcf25a8e3a30dea51f3315d8
|
[
"BSD-3-Clause",
"MIT"
] |
permissive
|
Open-CAS/open-cas-linux
|
c57d60f860702d7bc380c5d85cf502c0bf5e1bae
|
93334b4675afee8815f8ea12bb7297e0fd2a4195
|
refs/heads/master
| 2023-07-12T10:32:26.921455
| 2023-07-03T12:24:47
| 2023-07-03T12:24:47
| 178,356,155
| 202
| 84
|
BSD-3-Clause
| 2023-07-03T12:24:49
| 2019-03-29T07:37:15
|
Python
|
UTF-8
|
C
| false
| false
| 4,192
|
h
|
vt100codes.h
|
/*
* Copyright(c) 2012-2021 Intel Corporation
* SPDX-License-Identifier: BSD-3-Clause
*/
/* General setup */
#define RESET_DEVICE "\033c"
//! enable line wrapping
#define ENABLE_LINE_WRAP "\x1b[7h"
//! disable it
#define DISABLE_LINE_WRAP "\x1b[7l"
/* Scrolling options. Note: there is no way to disable scrolling */
//! Whole screen is scrolled on SCROLL_UP/SCROLL_DOWN
#define SCROLL_ENTIRE_SCREEN "\x1b[r"
//! Only rows from A to B are scrolled on SCROLL_UP/SCROLL_DOWN, anything above A or below B is not scrolled
#define SCROLL_SCREEN_REGION(A,B) "\x1b[" (A) ";" (B) "r"
//! scroll up
#define SCROLL_UP "\x1b[M"
//! scroll down
#define SCROLL_DOWN "\x1b[D"
//! make cursor invisible - xterm
#define HIDE_CURSOR "\x1b[?25l"
//! restore it -xterm
#define SHOW_CURSOR "\x1b[?25h"
/* Absolute cursor positioning. */
//! Set cursor position to left-top position
#define CURSOR_HOME "\x1b[H"
//! Set cursor position to specific y/x (note: y = 1..height, x = 1..width)
#define CURSOR_YX "\x1b[%d;%dH"
/* Relative cursor positioning. */
//! move cursor one position up
#define CURSOR_UP "\x1b[A"
//! move cursor n positions up
#define CURSOR_UP_N "\x1b[%dA"
//! move cursor one position down
#define CURSOR_DOWN "\x1b[B"
//! move cursor n positions down
#define CURSOR_DOWN_N "\x1b[%dB"
//! move cursor one position forward
#define CURSOR_FORWARD "\x1b[C"
//! move cursor n positions forward
#define CURSOR_FORWARD_N "\x1b[%dC"
//! move cursor one position backward
#define CURSOR_BACKWARD "\x1b[D"
//! move cursor n positions backward
#define CURSOR_BACKWARD_N "\x1b[%dD"
/* Unsave restores position after last save. */
//! One cursor position may be saved
#define SAVE_CURSOR "\x1b[s"
//! and restored
#define UNSAVE_CURSOR "\x1b[u"
/* Erase screen. */
//! Erase whole screen
#define ERASE "\x1b[2J"
//! same as above
#define ERASE_SCREEN ERASE
//! erase above cursor
#define ERASE_UP "\x1b[1J"
//! erase below cursor
#define ERASE_DOWN "\x1b[J"
#define INSERT_MODE "\x1b[4h"
#define REPLACE_MODE "\x1b[4l"
/* Erase line. */
//! erase current line
#define ERASE_LINE "\x1b[K"
//! erase current line left from the cursor
#define ERASE_START_OF_LINE "\x1b[1K"
//! erase current line right from the cursor
#define ERASE_END_OF_LINE "\x1b[K"
/* a = one of following 23 attributes*/
//! set specific attribute
#define SET_ATTR "\x1b[%dm"
//! if you have to set more attributes, separate them by ";"
#define AND_ATTR ";"
/*generalattributes (0-8 without 3 and 6) */
//!resets terminal defaults
#define ATTR_RESET 0
//!sets brighter fg color
#define ATTR_BRIGHT 1
//!turns off bright (sets darker fg color) note: not supported by most of platforms
#define ATTR_DIM 2
//!turns on text underline (not supported by MS Windows)
#define ATTR_UNDERSCORE 4
//!turns on blink (Not supported by MS Windows, most of other implementations incompatible)
#define ATTR_BLINK 5
//! Inverts bg and fg color (incompatible implementation on MS windows)*/
#define ATTR_REVERSE 7
#define ATTR_HIDDEN 8 /*???*/
/*Foreground (text) colours*/
#define FG_COLOR_BLACK 30
#define FG_COLOR_RED 31
#define FG_COLOR_GREEN 32
#define FG_COLOR_YELLOW 33
#define FG_COLOR_BLUE 34
#define FG_COLOR_MAGENTA 35
#define FG_COLOR_CYAN 36
#define FG_COLOR_WHITE 37
/*Background colors*/
#define BG_COLOR_BLACK 40
#define BG_COLOR_RED 41
#define BG_COLOR_GREEN 42
#define BG_COLOR_YELLOW 43
#define BG_COLOR_BLUE 44
#define BG_COLOR_MAGENTA 45
#define BG_COLOR_CYAN 46
#define BG_COLOR_WHITE 47
|
c21637d7eb2a802f8c6a91204fb97bf21a728a71
|
f42190636add23ead6a5022d706a124032d66f92
|
/src/Microsoft.DotNet.Wpf/src/WpfGfx/core/common/RectUtils.h
|
b09228282d5440b05da30ca08b6aa634046417cd
|
[
"MIT"
] |
permissive
|
dotnet/wpf
|
b8f73a99e03f87b4dee5db643e38e2c0704f707a
|
2ff355a607d79eef5fea7796de1f29cf9ea4fbed
|
refs/heads/main
| 2023-09-04T09:35:19.355384
| 2023-09-03T02:30:37
| 2023-09-03T02:30:37
| 153,711,945
| 6,927
| 1,397
|
MIT
| 2023-09-14T17:22:06
| 2018-10-19T01:55:23
|
C#
|
UTF-8
|
C
| false
| false
| 816
|
h
|
RectUtils.h
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//+----------------------------------------------------------------------------
//
//
// Abstract:
// Miscellaneous rectangle utility routines
//
//-----------------------------------------------------------------------------
#pragma once
BOOL
AreTransformedRectanglesClose(
__in_ecount(1) const CMilRectF *pFirstRect,
__in_ecount(1) const CMilRectF *pSecondRect,
__in_ecount_opt(1) const CMILMatrix *pTransform,
__in float closeTolerance
);
BOOL
RectF_RBFromParallelogramPointsF(
__in_ecount(4) const MilPoint2F *pPoints,
__out_ecount_opt(1) MilRectF *pRectF_RB
);
|
7f25e75aafff4dcf53a5672f863a4d89f4353b8a
|
9e0c8c8d8bafa73d133e41f201badc756c92978a
|
/tests/unit/misc_fake.c
|
650b5360592086854bc23e8b4ba14cd0cac45152
|
[
"BSD-2-Clause",
"MIT",
"CC0-1.0",
"BSD-3-Clause",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause-Views"
] |
permissive
|
vvaltchev/tilck
|
ccf8d9933be1269b85388e5b21645b831ecf5412
|
e9c27da4dd15f5f8a927b11f31484aec3f1429f0
|
refs/heads/master
| 2023-08-16T00:07:42.593483
| 2023-07-04T21:00:31
| 2023-07-19T23:25:42
| 53,845,595
| 2,142
| 115
|
BSD-2-Clause
| 2023-09-03T05:36:46
| 2016-03-14T10:02:41
|
C
|
UTF-8
|
C
| false
| false
| 3,135
|
c
|
misc_fake.c
|
/* SPDX-License-Identifier: BSD-2-Clause */
#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
#include <string.h>
#include <tilck/common/basic_defs.h>
#include <tilck/kernel/datetime.h>
#include <tilck/kernel/sync.h>
#include <tilck/kernel/sched.h>
#include <tilck_gen_headers/config_kmalloc.h>
#include <tilck/kernel/kmalloc.h>
#include <kernel/kmalloc/kmalloc_heap_struct.h> // kmalloc private header
#include <kernel/kmalloc/kmalloc_block_node.h> // kmalloc private header
u32 spur_irq_count;
u32 unhandled_irq_count[256];
bool suppress_printk;
volatile bool __in_panic;
volatile bool __in_kernel_shutdown;
volatile bool __in_panic_debugger;
void *__kernel_pdir;
bool mock_kmalloc = false; /* see the comments above __wrap_general_kmalloc() */
void *__real_general_kmalloc(size_t *size, u32 flags);
void __real_general_kfree(void *ptr, size_t *size, u32 flags);
void panic(const char *fmt, ...)
{
printf("\n--- KERNEL PANIC ---\n");
va_list args;
va_start(args, fmt);
vprintf(fmt, args);
va_end(args);
printf("\n--- END PANIC MESSAGE ---\n");
abort();
}
void __wrap_tilck_vprintk(u32 flags, const char *fmt, va_list args)
{
if (suppress_printk)
return;
vprintf(fmt, args);
}
void __wrap_assert_failed(const char *expr, const char *file, int line)
{
printf("Kernel assertion '%s' FAILED in %s:%d\n", expr, file, line);
abort();
}
void __wrap_not_reached(const char *file, int line)
{
printf("Kernel NOT_REACHED statement in %s:%d\n", file, line);
abort();
}
void __wrap_not_implemented(const char *file, int line)
{
printf("Kernel NOT_IMPLEMENTED at %s:%d\n", file, line);
abort();
}
int __wrap_fat_ramdisk_prepare_for_mmap(void *hdr, size_t rd_size)
{
return -1;
}
int __wrap_wth_create_thread_for(void *t) { return 0; }
void __wrap_wth_wakeup() { /* do nothing */ }
void __wrap_check_in_irq_handler() { /* do nothing */ }
void __wrap_kmutex_lock(struct kmutex *m) {
ASSERT(m->owner_task == NULL);
m->owner_task = get_curr_task();
}
void __wrap_kmutex_unlock(struct kmutex *m) {
ASSERT(m->owner_task == get_curr_task());
m->owner_task = NULL;
}
/*
* Decide with just a global flag whether to use glibc's malloc() or Tilck's
* kmalloc() implementation, instead of using a proper GMock in kmalloc_test.cpp
* with ON_CALL(mock, general_kmalloc).WillByDefault([&mock](...) { ... }),
* simply because that is too slow for performance measurements. Otherwise, the
* mocking mechanism with GMock is great.
*/
void *__wrap_general_kmalloc(size_t *size, u32 flags)
{
if (mock_kmalloc)
return malloc(*size);
return __real_general_kmalloc(size, 0);
}
void __wrap_general_kfree(void *ptr, size_t *size, u32 flags)
{
if (mock_kmalloc)
return free(ptr);
return __real_general_kfree(ptr, size, 0);
}
void *__wrap_kmalloc_get_first_heap(size_t *size)
{
static void *buf;
if (!buf) {
buf = aligned_alloc(KMALLOC_MAX_ALIGN, KMALLOC_FIRST_HEAP_SIZE);
VERIFY(buf);
VERIFY( ((ulong)buf & (KMALLOC_MAX_ALIGN - 1)) == 0 );
}
if (size)
*size = KMALLOC_FIRST_HEAP_SIZE;
return buf;
}
|
bed02348ca38a06c5afed5895a7e728f087374e7
|
f6e5f3c038fb15cb1bfd2e0a6e8038324656bd28
|
/3rdparty/openssl-win32/openssl/engine.h
|
55eef84d361ee3a6a6466f6395b53a09b4518d58
|
[
"OpenSSL",
"MIT"
] |
permissive
|
vslavik/winsparkle
|
c838830255f0fc0d0d1c4c6251e450ebf0eb9a45
|
415acf557e8c15a12d8168d298b3b577fdbc6d54
|
refs/heads/master
| 2023-09-01T13:39:55.053989
| 2023-08-31T16:20:45
| 2023-08-31T17:17:37
| 467,582
| 1,105
| 279
|
NOASSERTION
| 2023-09-13T21:46:13
| 2010-01-11T16:13:10
|
C++
|
UTF-8
|
C
| false
| false
| 48
|
h
|
engine.h
|
#include "../../openssl/crypto/engine/engine.h"
|
c62ffd7fc734ad16096c968c7c74611243ab6b6d
|
59864cbd213b5da6f50d6255b0a021564b3d5bd4
|
/challenges/Kaprica_Go/src/main.c
|
a37a9d43f50a8445d66223df5f2f8882cb34eb5e
|
[
"MIT",
"BSD-3-Clause",
"LicenseRef-scancode-unknown",
"BSD-2-Clause"
] |
permissive
|
trailofbits/cb-multios
|
8af96a4fbc3b34644367faa135347f88e0e0d0a3
|
810d7b24b1f62f56ef49b148fe155b0d0629cad2
|
refs/heads/master
| 2023-09-05T03:56:20.229403
| 2022-12-27T15:47:54
| 2022-12-27T15:47:54
| 41,688,943
| 522
| 133
|
MIT
| 2023-06-29T02:47:13
| 2015-08-31T17:04:31
|
C
|
UTF-8
|
C
| false
| false
| 16,253
|
c
|
main.c
|
/*
* Copyright (c) 2015 Kaprica Security, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
#include "libcgc.h"
#include "cgc_ctype.h"
#include "cgc_stdint.h"
#include "cgc_stdlib.h"
#include "cgc_string.h"
typedef int8_t s8;
typedef int16_t s16;
typedef int32_t s32;
typedef int64_t s64;
typedef uint8_t u8;
typedef uint16_t u16;
typedef uint32_t u32;
typedef uint64_t u64;
typedef enum action_t action_t;
enum action_t {
AUNUSED = 0,
PLAY,
PASS
};
typedef enum color_t color_t;
enum color_t {
CUNUSED = 0,
BLACK,
WHITE,
EMPTY,
OFF_BOARD
};
#define error(__status) cgc_exit(__status)
#define BOARD_DIM 19
#define NUM_PLAYERS 2
#define NUM_HISTORIES 16
#define SET_BOARD(board, x, y, pt) (board[y][x] = pt)
#define COLOR_STRING(c) (c == WHITE ? "White" : "Black")
#define OTHER_PLAYER(c) (c == WHITE ? BLACK : WHITE)
typedef color_t board_t[BOARD_DIM][BOARD_DIM];
typedef u8 sboard_t[BOARD_DIM][BOARD_DIM];
typedef u64 hash_t;
static u32 pcnt = 0;
static u64 prng_s = 0;
u64 cgc_prand(void)
{
pcnt++;
prng_s = prng_s * 1103515245 + 12345;
return (u32)(prng_s / (2 << 15));
}
typedef struct hashl_t hashl_t;
struct hashl_t {
hash_t hash;
hashl_t* next;
};
static inline void INIT_LIST(hashl_t** list, hash_t hash)
{
*list = cgc_calloc(1, sizeof(hashl_t));
if (!list) error(1);
(*list)->hash = hash;
(*list)->next = *list;
}
static inline void EXTD_LIST(hashl_t* list, hash_t hash)
{
hashl_t* new = cgc_calloc(1, sizeof(hashl_t));
if (!new)
error(1);
for (; list->next != list; list = list->next)
if (list->hash == hash)
return;
new->next = new;
new->hash = hash;
list->next = new;
}
static inline int CONT_LIST(hashl_t* list, hash_t hash)
{
u32 cnt = 1;
do {
if (list->hash == hash) {
return 1;
} else if (list->next != list) {
list = list->next;
cnt++;
} else {
break;
}
} while (1);
return 0;
}
typedef struct game_t game_t;
struct game_t {
board_t board;
u32 scores[NUM_PLAYERS];
u32 caps[NUM_PLAYERS];
u32 used[NUM_PLAYERS];
u64 ticks;
u8 passes;
color_t current;
hashl_t* history;
};
static hash_t ztable[BOARD_DIM * BOARD_DIM][NUM_PLAYERS];
int cgc_init_zobrist(void)
{
for (u16 y = 0; y < BOARD_DIM * BOARD_DIM; y++) {
for (u16 x = 0; x < NUM_PLAYERS; x++) {
ztable[y][x] = cgc_prand();
}
}
return 0;
}
hash_t cgc_hash_zobrist(board_t board)
{
hash_t h = 0;
for (u16 y = 0; y < BOARD_DIM * BOARD_DIM; y++) {
if (board[y / BOARD_DIM][y % BOARD_DIM] != EMPTY) {
h ^= ztable[y][board[y / BOARD_DIM][y % BOARD_DIM] - 1];
}
}
return h;
}
void cgc_push_game_state(game_t* game) {
hash_t h = cgc_hash_zobrist(game->board);
EXTD_LIST(game->history, h);
}
static inline u64 abs(s32 x)
{
return (x < 0) ? -x : x;
}
u8 cgc_ndigits(int x)
{
if (x == 0)
return 1;
u8 n = 0;
while (x) {
x /= 10;
n++;
}
return n;
}
game_t* cgc_init_game(board_t board)
{
game_t* game = cgc_calloc(1, sizeof(game_t));
if (!game)
return NULL;
if (board) {
for (u32 y = 0; y < BOARD_DIM; y++) {
for (u32 x = 0; x < BOARD_DIM; x++) {
game->board[y][x] = board[y][x];
}
}
} else {
for (u32 y = 0; y < BOARD_DIM; y++) {
for (u32 x = 0; x < BOARD_DIM; x++) {
game->board[y][x] = EMPTY;
}
}
}
for (u32 i = 0; i < NUM_PLAYERS; i++) {
game->scores[i] = 0;
game->caps[i] = 0;
game->used[i] = 0;
}
game->history = NULL;
hash_t h = cgc_hash_zobrist(game->board);
INIT_LIST(&game->history, h);
game->ticks = 0;
game->passes = 0;
return game;
}
game_t* cgc_copy_game(game_t* game)
{
game_t* copy = cgc_calloc(1, sizeof(game_t));
if (!copy)
error(1);
cgc_memcpy(copy, game, sizeof(game_t));
return copy;
}
color_t cgc_get_color(board_t board, u8 x, u8 y)
{
if (x >= BOARD_DIM || x < 0 || y >= BOARD_DIM || y < 0)
return OFF_BOARD;
return board[y][x];
}
int cgc_has_liberty(game_t* game, sboard_t sboard, u8 x, u8 y, color_t color)
{
color_t c = cgc_get_color(game->board, x, y);
if (c == OFF_BOARD)
return 0;
if (sboard[y][x] == 1)
return 0;
color_t u = cgc_get_color(game->board, x, y + 1);
color_t d = cgc_get_color(game->board, x, y - 1);
color_t l = cgc_get_color(game->board, x - 1, y);
color_t r = cgc_get_color(game->board, x + 1, y);
sboard[y][x] = 1;
if (u == EMPTY || d == EMPTY || l == EMPTY || r == EMPTY) {
return 1;
}
if (u == color && cgc_has_liberty(game, sboard, x, y + 1, color)) {
return 1;
} else if (d == color && cgc_has_liberty(game, sboard, x, y - 1, color)) {
return 1;
} else if (l == color && cgc_has_liberty(game, sboard, x - 1, y, color)) {
return 1;
} else if (r == color && cgc_has_liberty(game, sboard, x + 1, y, color)) {
return 1;
}
return 0;
}
u8 cgc_surrounded_by(game_t* game, sboard_t sboard, u8 x, u8 y, color_t color)
{
if (!game || !sboard)
error(1);
color_t cur = cgc_get_color(game->board, x, y);
if (cur == OFF_BOARD || sboard[y][x] == 1)
return 1;
if (cur == color) {
sboard[y][x] = 1;
return 2;
} else if (cur == OTHER_PLAYER(color)) {
sboard[y][x] = 1;
return 0;
} else if (cur == EMPTY) {
sboard[y][x] = 1;
}
u8 u = cgc_surrounded_by(game, sboard, x, y + 1, color);
u8 d = cgc_surrounded_by(game, sboard, x, y - 1, color);
u8 l = cgc_surrounded_by(game, sboard, x + 1, y, color);
u8 r = cgc_surrounded_by(game, sboard, x - 1, y, color);
if (u + d + l + r > 4) {
return 2;
} else {
return 0;
}
}
int cgc_remove_captures(game_t* game, color_t color)
{
u32 cnt = 0;
sboard_t sboard;
game_t* frozen = cgc_copy_game(game);
for (u8 y = 0; y < BOARD_DIM; y++) {
for (u8 x = 0; x < BOARD_DIM; x++) {
cgc_memset(sboard, 0, sizeof(sboard));
if (cgc_get_color(frozen->board, x, y) == color && !cgc_has_liberty(frozen, sboard, x, y, color)) {
cnt++;
SET_BOARD(game->board, x, y, EMPTY);
}
}
}
cgc_free(frozen);
return cnt;
}
int cgc_has_happened(game_t* proposed, game_t* current)
{
hash_t h = cgc_hash_zobrist(proposed->board);
if (CONT_LIST(current->history, h)) {
return 1;
}
return 0;
}
int cgc_score(game_t* game, u32* black, u32* white)
{
sboard_t sboard;
*black = game->caps[BLACK - 1];
*white = game->caps[WHITE - 1];
for (u8 y = 0; y < BOARD_DIM; y++) {
for (u8 x = 0; x < BOARD_DIM; x++) {
cgc_memset(sboard, 0, sizeof(sboard));
color_t cur = cgc_get_color(game->board, x, y);
if (cur == WHITE) {
*white += 1;
continue;
} else if (cur == BLACK) {
*black += 1;
continue;
}
u8 s = cgc_surrounded_by(game, sboard, x, y, BLACK);
if (s > 1) {
*black += 1;
continue;
}
s = cgc_surrounded_by(game, sboard, x, y, WHITE);
if (s > 1) {
*white += 1;
continue;
}
}
}
return 0;
}
int cgc_check_and_play(game_t** game, u8 x, u8 y, color_t color, u8 play)
{
if (color != EMPTY && (*game)->board[y][x] != EMPTY) {
return -1;
}
game_t* simulated = cgc_copy_game(*game);
SET_BOARD(simulated->board, x, y, color);
u16 our_cap = cgc_remove_captures(simulated, OTHER_PLAYER(color));
u16 thr_cap = cgc_remove_captures(simulated, color);
if (cgc_has_happened(simulated, *game)) {
cgc_free(simulated);
return -1;
} else if (play) {
cgc_free(*game);
*game = simulated;
(*game)->used[color - 1]++;
(*game)->caps[color - 1] += our_cap;
(*game)->caps[OTHER_PLAYER(color) - 1] += thr_cap;
return 0;
} else {
cgc_free(simulated);
return 0;
}
}
#define SCREEN_WIDTH 80
#define SCREEN_HEIGHT 30
#define BOARD_WIDTH 37
static inline void clear_screen(void)
{
cgc_fdprintf(STDOUT, "\033[2J");
}
static inline void print_char(char color)
{
cgc_fdprintf(STDOUT, "%c", color);
}
void cgc_print_rchar(char c, u8 r)
{
for (u8 i = 0; i < r; i++)
print_char(c);
}
void cgc_print_player(game_t* game, color_t color)
{
#define OFFSET 7
cgc_fdprintf(STDOUT, "%s: %d", COLOR_STRING(color), game->scores[color - 1]);
cgc_print_rchar(' ', (((SCREEN_WIDTH - BOARD_WIDTH) / 2) - OFFSET) - cgc_ndigits(game->scores[color - 1]));
}
void cgc_print_point(game_t* game, u8 x, u8 y)
{
if (x != 0)
print_char(' ');
switch (cgc_get_color(game->board, x, y)) {
case EMPTY:
print_char('-');
break;
case WHITE:
print_char('W');
break;
case BLACK:
print_char('B');
break;
default:
return;
}
if (x != BOARD_DIM - 1)
print_char(' ');
else
print_char('\n');
}
void cgc_draw_game(game_t* game)
{
//clear_screen();
cgc_print_rchar('\n', (SCREEN_HEIGHT - BOARD_DIM) / 2);
for (u32 y = 0; y < BOARD_DIM; y++) {
if (abs(y - (BOARD_DIM / 2)) == 3) {
cgc_print_player(game, y < BOARD_DIM / 2 ? WHITE : BLACK);
} else if (y == BOARD_DIM / 2) {
cgc_fdprintf(STDOUT, "Ticks: %u", game->ticks);
cgc_print_rchar(' ', (((SCREEN_WIDTH - BOARD_WIDTH) / 2) - OFFSET)- cgc_ndigits(game->ticks));
} else {
cgc_print_rchar(' ', (SCREEN_WIDTH - BOARD_WIDTH) / 2);
}
for (u32 x = 0; x < BOARD_DIM; x++) {
cgc_print_point(game, x, y);
}
}
cgc_print_rchar('\n', (SCREEN_HEIGHT - BOARD_DIM) / 2);
}
void cgc_sleep(int s, int us)
{
struct cgc_timeval t;
t.tv_sec = s;
t.tv_usec = us;
cgc_fdwait(0, NULL, NULL, &t, NULL);
}
int cgc_read_n_bytes(int fd, cgc_size_t n, char *buf, int has_terminator, char terminator)
{
if (!n || !buf)
return -1;
cgc_size_t rx = 0, total_read = 0;
while (total_read < n) {
if (cgc_receive(fd, buf + total_read, 1, &rx) != 0) {
return -1;
} else if (rx == 0) {
break;
} else {
if (has_terminator && *(buf + total_read) == terminator) {
*(buf + total_read) = '\0';
break;
}
total_read += rx;
}
}
return total_read;
}
int cgc_read_move(u8* x, u8* y, u8* pass)
{
#define INPUT_MAX 8
int ret = -1;
char buf[INPUT_MAX + 1];
*pass = 0;
cgc_memset(buf, 0, INPUT_MAX);
cgc_read_n_bytes(STDIN, INPUT_MAX, buf, 1, '\n');
buf[INPUT_MAX] = '\0';
char* p = NULL;
if (!cgc_strncmp("pass", buf, cgc_strlen("pass"))) {
*pass = 1;
ret = 0; goto out;
}
long n1 = cgc_strtol(buf, &p, 10);
if (p == buf)
goto out;
if (p >= buf + INPUT_MAX)
goto out;
while (p && *p && p < buf + INPUT_MAX && !cgc_isdigit(*p))
p++;
long n2 = cgc_strtol(p, NULL, 10);
if (n1 >= 0 && n1 < BOARD_DIM && n2 >= 0 && n2 < BOARD_DIM) {
*x = n1;
*y = n2;
ret = 0; goto out;
}
out:
return ret;
}
void cgc_end_game(game_t* game, char *name, u8 reason)
{
cgc_free(game);
cgc_fdprintf(STDOUT, "Game Over ");
switch (reason) {
case 0:
cgc_fdprintf(STDOUT, "Both Passed\n");
break;
case 1:
cgc_fdprintf(STDOUT, "Game Time Exceeded\n");
break;
case 2:
cgc_fdprintf(STDOUT, "Stones Exhausted\n");
break;
}
cgc_fdprintf(STDOUT, "You are a ");
cgc_fdprintf(STDOUT, ((game->scores[BLACK - 1] > game->scores[WHITE - 1])) ? "Winner, " : "Loser, ");
#ifdef PATCHED
cgc_fdprintf(STDOUT, "%s", name);
#else
cgc_fdprintf(STDOUT, name);
#endif
cgc_exit(0);
return;
}
void cgc_prompt_move(game_t* game, color_t color)
{
cgc_fdprintf(STDOUT, "%d ", game->ticks);
if (color == BLACK)
cgc_fdprintf(STDOUT, "B >");
else if (color == WHITE)
cgc_fdprintf(STDOUT, "W >");
}
char* cgc_color_to_string(color_t c)
{
switch (c) {
case WHITE:
return "White";
case BLACK:
return "Black";
case EMPTY:
return "Empty";
case OFF_BOARD:
return "Off";
default:
error(1);
}
return NULL;
}
int cgc_pass_for(game_t* game, color_t color)
{
game->passes++;
if (color == WHITE && game->passes > 1)
return -1;
return 0;
}
int cgc_interact(game_t** game, color_t color)
{
u8 x, y, pass;
cgc_prompt_move(*game, color);
if (cgc_read_move(&x, &y, &pass) < 0) {
return -1;
}
if (pass) {
return cgc_pass_for(*game, color) < 0;
}
(*game)->passes = 0;
if (cgc_check_and_play(game, x, y, color, 1) < 0) {
return -1;
}
cgc_push_game_state(*game);
return 0;
}
action_t cgc_calculate_move(game_t** game, u8* ox, u8* oy, color_t color)
{
s32 vote, bvote = 0;
u8 bx, by;
sboard_t sboard;
u32 chance;
u8 gend = 0;
for (u8 y = 0; y < BOARD_DIM; y++) {
for (u8 x = 0; x < BOARD_DIM; x++) {
vote = 0;
cgc_memset(sboard, 0, sizeof(sboard));
u8 neigh_cnt = 0;
neigh_cnt += (cgc_get_color((*game)->board, x + 1, y) == color);
neigh_cnt += (cgc_get_color((*game)->board, x - 1, y) == color);
neigh_cnt += (cgc_get_color((*game)->board, x, y + 1) == color);
neigh_cnt += (cgc_get_color((*game)->board, x, y - 1) == color);
if (neigh_cnt == 4)
vote -= 3;
else if (neigh_cnt == 2)
vote += 1;
else if (neigh_cnt == 1)
vote += 2;
if (vote >= bvote) {
if (cgc_check_and_play(game, x, y, color, 0) < 0) {
continue;
}
chance = cgc_prand();
if (chance % 100 > (vote == bvote ? 90 : 75)) {
gend++;
bx = x;
by = y;
bvote = vote;
if (gend > 5)
goto done;
}
}
}
}
done:
if (!gend)
return PASS;
else {
*ox = bx, *oy = by;
return PLAY;
}
}
int cgc_ai(game_t** game, color_t color)
{
u8 x, y;
switch (cgc_calculate_move(game, &x, &y, color)) {
case PLAY:
cgc_check_and_play(game, x, y, color, 1);
cgc_push_game_state(*game);
break;
case PASS:
(*game)->passes++;
break;
default:
error(1);
}
return 0;
}
void cgc_pb(game_t* game)
{
cgc_fdprintf(STDERR, "@@");
for (u16 y = 0; y < BOARD_DIM; y++) {
for (u16 x = 0; x < BOARD_DIM; x++) {
cgc_fdprintf(STDERR, "%d", game->board[y][x]);
}
}
cgc_fdprintf(STDERR, "\n");
}
int main(int cgc_argc, char *cgc_argv[])
{
#define NAME_LEN 8
char name[NAME_LEN];
int iret = -1;
cgc_read_n_bytes(STDIN, sizeof(prng_s), (char *)&prng_s, 0, 0);
if (cgc_init_zobrist() != 0)
error(1);
game_t* game = cgc_init_game(NULL);
if (!game)
error(1);
cgc_fdprintf(STDOUT, "What is your name?\n");
if (cgc_read_n_bytes(STDIN, NAME_LEN, name, 1, '\n') < 0) {
cgc_printf("Need a name, bro\n");
cgc_exit(1);
}
cgc_printf("Hi, %s\n", name);
cgc_draw_game(game);
while (1) {
while (1) {
int r = cgc_interact(&game, BLACK);
if (r == -1) {
continue;
} else if (r == 0) {
break;
} else if (r == 1) {
cgc_end_game(game, name, 0);
}
}
cgc_score(game, &(game->scores[BLACK - 1]), &(game->scores[WHITE -1]));
cgc_draw_game(game);
cgc_ai(&game, WHITE);
cgc_score(game, &(game->scores[BLACK - 1]), &(game->scores[WHITE - 1]));
#define MAX_STONES 90
#define MAX_TICKS 150
game->ticks++;
if (game->ticks > MAX_TICKS)
cgc_end_game(game, name, 1);
if (game->used[BLACK - 1] > MAX_STONES || game->used[WHITE - 1] > MAX_STONES)
cgc_end_game(game, name, 2);
}
}
|
67d2bd1a53f5dc25e392976472d298848362e705
|
badb70a0b235c98ac034cfe5b4bfafda36647831
|
/Library/OcDeviceMiscLib/SetResizableBar.c
|
f95da1533e8a3caedf79876f569f96a444e2a1f5
|
[
"BSD-3-Clause"
] |
permissive
|
acidanthera/OpenCorePkg
|
f34a7d67b22c74fb5ab559e48519e5f5855b6751
|
1d5b1736fe5a5ef7662b5c076c6d11aac96fd5d6
|
refs/heads/master
| 2023-08-30T21:03:02.993659
| 2023-08-28T23:30:43
| 2023-08-28T23:30:43
| 179,354,282
| 13,212
| 2,999
|
BSD-3-Clause
| 2023-09-10T18:29:53
| 2019-04-03T19:14:29
|
C
|
UTF-8
|
C
| false
| false
| 27,866
|
c
|
SetResizableBar.c
|
/** @file
Copyright (C) 2021, vit9696. All rights reserved.
All rights reserved.
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
**/
#include <Uefi.h>
#include <IndustryStandard/Pci.h>
#include <Protocol/PciIo.h>
#include <Protocol/PciRootBridgeIo.h>
#include <Library/BaseLib.h>
#include <Library/BaseMemoryLib.h>
#include <Library/MemoryAllocationLib.h>
#include <Library/DebugLib.h>
#include <Library/IoLib.h>
#include <Library/UefiBootServicesTableLib.h>
#include <Library/OcDeviceMiscLib.h>
#include "PciExtInternal.h"
STATIC
EFI_STATUS
LocatePciCapabilityPciIo (
IN EFI_PCI_IO_PROTOCOL *PciIo,
IN UINT16 CapId,
OUT UINT32 *Offset
)
{
EFI_STATUS Status;
UINT32 CapabilityPtr;
UINT32 CapabilityEntry;
UINT16 CapabilityID;
CapabilityPtr = EFI_PCIE_CAPABILITY_BASE_OFFSET;
while (CapabilityPtr != 0) {
//
// Mask it to DWORD alignment per PCI spec
//
CapabilityPtr &= 0xFFC;
Status = PciIo->Pci.Read (
PciIo,
EfiPciIoWidthUint32,
CapabilityPtr,
1,
&CapabilityEntry
);
if (EFI_ERROR (Status)) {
DEBUG ((DEBUG_INFO, "OCDM: Capability I/O error - %r\n", Status));
return EFI_DEVICE_ERROR;
}
if (CapabilityEntry == MAX_UINT32) {
DEBUG ((DEBUG_INFO, "OCDM: Read from disabled device\n"));
return EFI_INVALID_PARAMETER;
}
CapabilityID = (UINT16)CapabilityEntry;
if (CapabilityID == CapId) {
DEBUG ((DEBUG_VERBOSE, "OCDM: Found CAP 0x%X at 0x%X\n", CapabilityID, CapabilityPtr));
*Offset = CapabilityPtr;
return EFI_SUCCESS;
}
CapabilityPtr = (CapabilityEntry >> 20) & 0xFFF;
}
return EFI_NOT_FOUND;
}
//
// Needed to access address larger than 256
//
STATIC
UINT64
PciAddrOffset (
UINT64 PciAddress,
INT32 Offset
)
{
UINT32 Reg = (UINT32)((PciAddress & 0xffffffff00000000) >> 32);
UINT8 Bus = (UINT8)((PciAddress & 0xff000000) >> 24);
UINT8 Dev = (UINT8)((PciAddress & 0xff0000) >> 16);
UINT8 Func = (UINT8)((PciAddress & 0xff00) >> 8);
return EFI_PCI_ADDRESS (Bus, Dev, Func, (Reg + Offset));
}
STATIC
EFI_STATUS
LocatePciCapabilityRbIo (
IN EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL *PciRootBridgeIo,
IN UINT64 PciAddress,
IN UINT16 CapId,
OUT UINT32 *Offset
)
{
EFI_STATUS Status;
UINT32 CapabilityPtr;
UINT32 CapabilityEntry;
UINT16 CapabilityID;
CapabilityPtr = EFI_PCIE_CAPABILITY_BASE_OFFSET;
while (CapabilityPtr != 0) {
//
// Mask it to DWORD alignment per PCI spec
//
CapabilityPtr &= 0xFFC;
Status = PciRootBridgeIo->Pci.Read (
PciRootBridgeIo,
EfiPciWidthUint32,
PciAddrOffset (PciAddress, CapabilityPtr),
1,
&CapabilityEntry
);
if (EFI_ERROR (Status)) {
DEBUG ((DEBUG_INFO, "OCDM: Capability I/O error - %r\n", Status));
return EFI_DEVICE_ERROR;
}
if (CapabilityEntry == MAX_UINT32) {
DEBUG ((DEBUG_INFO, "OCDM: Read from disabled device\n"));
return EFI_INVALID_PARAMETER;
}
CapabilityID = (UINT16)CapabilityEntry;
if (CapabilityID == CapId) {
DEBUG ((DEBUG_VERBOSE, "OCDM: Found CAP 0x%X at 0x%X\n", CapabilityID, CapabilityPtr));
*Offset = CapabilityPtr;
return EFI_SUCCESS;
}
CapabilityPtr = (CapabilityEntry >> 20) & 0xFFF;
}
return EFI_NOT_FOUND;
}
STATIC
EFI_STATUS
SetResizableBarOnDevicePciIo (
IN EFI_PCI_IO_PROTOCOL *PciIo,
IN PCI_BAR_SIZE Size,
IN BOOLEAN Increase
)
{
EFI_STATUS Status;
UINT32 ResizableBarOffset;
PCI_EXPRESS_EXTENDED_CAPABILITIES_RESIZABLE_BAR_ENTRY Entries[PCI_MAX_BAR];
PCI_EXPRESS_EXTENDED_CAPABILITIES_RESIZABLE_BAR_CONTROL ResizableBarControl;
UINT32 Offset;
UINT32 Index;
UINT32 ResizableBarNumber;
UINT64 Capabilities;
UINT64 NewCapabilities;
UINT32 OldBar[PCI_MAX_BAR];
UINT32 NewBar[PCI_MAX_BAR];
INTN Bit;
BOOLEAN ChangedBars;
ChangedBars = FALSE;
Status = LocatePciCapabilityPciIo (
PciIo,
PCI_EXPRESS_EXTENDED_CAPABILITY_RESIZABLE_BAR_ID,
&ResizableBarOffset
);
if (EFI_ERROR (Status)) {
DEBUG ((DEBUG_INFO, "OCDM: RBAR is unsupported by device - %r\n", Status));
return EFI_UNSUPPORTED;
}
ResizableBarControl.Uint32 = 0;
Offset = ResizableBarOffset + sizeof (PCI_EXPRESS_EXTENDED_CAPABILITIES_HEADER)
+ sizeof (PCI_EXPRESS_EXTENDED_CAPABILITIES_RESIZABLE_BAR_CAPABILITY);
Status = PciIo->Pci.Read (
PciIo,
EfiPciIoWidthUint8,
Offset,
sizeof (PCI_EXPRESS_EXTENDED_CAPABILITIES_RESIZABLE_BAR_CONTROL),
&ResizableBarControl
);
DEBUG ((
DEBUG_INFO,
"OCDM: RBAR control is %X, total %u - %r\n",
ResizableBarControl.Uint32,
MIN (ResizableBarControl.Bits.ResizableBarNumber, PCI_MAX_BAR),
Status
));
if (EFI_ERROR (Status)) {
return EFI_UNSUPPORTED;
}
ResizableBarNumber = MIN (ResizableBarControl.Bits.ResizableBarNumber, PCI_MAX_BAR);
Status = PciIo->Pci.Read (
PciIo,
EfiPciIoWidthUint8,
ResizableBarOffset + sizeof (PCI_EXPRESS_EXTENDED_CAPABILITIES_HEADER),
sizeof (PCI_EXPRESS_EXTENDED_CAPABILITIES_RESIZABLE_BAR_ENTRY) * ResizableBarNumber,
(VOID *)Entries
);
if (EFI_ERROR (Status)) {
DEBUG ((DEBUG_INFO, "OCDM: RBAR caps cannot be read - %r\n", Status));
return EFI_UNSUPPORTED;
}
Status = PciIo->Pci.Read (
PciIo,
EfiPciIoWidthUint32,
OFFSET_OF (PCI_TYPE00, Device.Bar),
PCI_MAX_BAR,
(VOID *)OldBar
);
if (EFI_ERROR (Status)) {
ZeroMem (OldBar, sizeof (OldBar));
}
DEBUG ((
DEBUG_INFO,
"OCDM: Old BAR %08X %08X %08X %08X %08X %08X - %r\n",
OldBar[0],
OldBar[1],
OldBar[2],
OldBar[3],
OldBar[4],
OldBar[5],
Status
));
for (Index = 0; Index < ResizableBarNumber; Index++) {
//
// When the bit of Capabilities Set, indicates that the Function supports
// operating with the BAR sized to (2^Bit) MB.
// Example:
// Bit 0 is set: supports operating with the BAR sized to 1 MB
// Bit 1 is set: supports operating with the BAR sized to 2 MB
// Bit n is set: supports operating with the BAR sized to (2^n) MB
//
// Reference values for RX 6900 with two resizable BARs.
// Disabled values:
// Resizeable Bar Capability [1]
// ResizableBarCapability 0007F000
// ResizableBarControl 0840
// Resizeable Bar Capability [2]
// ResizableBarCapability 00001FE0
// ResizableBarControl 0102
// Enabled values:
// Resizeable Bar Capability [1]
// ResizableBarCapability 0007F000
// ResizableBarControl 0E40
// Resizeable Bar Capability [2]
// ResizableBarCapability 00001FE0
// ResizableBarControl 0802
//
NewCapabilities = Capabilities = LShiftU64 (Entries[Index].ResizableBarControl.Bits.BarSizeCapability, 28)
| Entries[Index].ResizableBarCapability.Bits.BarSizeCapability;
//
// Restrict supported BARs to specified value.
//
NewCapabilities &= PCI_BAR_CAP_LIMIT (Size);
//
// Disable bits higher than current as we are not allowed to increase bar size
// more than we already have.
//
if (!Increase) {
NewCapabilities &= PCI_BAR_CAP_LIMIT (Entries[Index].ResizableBarControl.Bits.BarSize);
}
//
// If requested BAR size is too low, choose the lowest available BAR size.
//
if ( (NewCapabilities == 0)
&& (Entries[Index].ResizableBarControl.Bits.BarSize > (UINT32)Size))
{
Bit = LowBitSet64 (Capabilities);
} else {
Bit = HighBitSet64 (NewCapabilities);
}
DEBUG ((
DEBUG_INFO,
"OCDM: RBAR %u/%u supports 0x%Lx, sizing %u inc %d results setting from %u to %d\n",
Index + 1,
ResizableBarNumber,
Capabilities,
Size,
Increase,
Entries[Index].ResizableBarControl.Bits.BarSize,
(INT32)Bit
));
//
// If we have no supported configuration, just skip.
//
if ((Bit < 0) || (Entries[Index].ResizableBarControl.Bits.BarSize == (UINT32)Bit)) {
continue;
}
Offset = ResizableBarOffset + sizeof (PCI_EXPRESS_EXTENDED_CAPABILITIES_HEADER)
+ Index * sizeof (PCI_EXPRESS_EXTENDED_CAPABILITIES_RESIZABLE_BAR_ENTRY)
+ OFFSET_OF (PCI_EXPRESS_EXTENDED_CAPABILITIES_RESIZABLE_BAR_ENTRY, ResizableBarControl);
Entries[Index].ResizableBarControl.Bits.BarSize = (UINT32)Bit;
PciIo->Pci.Write (
PciIo,
EfiPciIoWidthUint32,
Offset,
1,
&Entries[Index].ResizableBarControl.Uint32
);
ChangedBars = TRUE;
}
if (ChangedBars) {
DEBUG_CODE_BEGIN ();
Status = PciIo->Pci.Read (
PciIo,
EfiPciIoWidthUint32,
OFFSET_OF (PCI_TYPE00, Device.Bar),
PCI_MAX_BAR,
(VOID *)NewBar
);
if (EFI_ERROR (Status)) {
ZeroMem (NewBar, sizeof (NewBar));
}
DEBUG ((
DEBUG_INFO,
"OCDM: New BAR %08X %08X %08X %08X %08X %08X - %r\n",
NewBar[0],
NewBar[1],
NewBar[2],
NewBar[3],
NewBar[4],
NewBar[5],
Status
));
DEBUG_CODE_END ();
//
// PCI BARs are reset after resizing, so we must restore them. This follows the spec:
// After writing the BAR Size field, the contents of the corresponding BAR are undefined.
// To ensure that it contains a valid address after resizing the BAR, system software must
// reprogram the BAR, and Set the Memory Space Enable bit (unless the resource is not allocated).
// TODO: We do not bother touching `Memory Space Enable` bit but strictly we should.
//
if (!IsZeroBuffer (OldBar, sizeof (OldBar))) {
Status = PciIo->Pci.Write (
PciIo,
EfiPciIoWidthUint32,
OFFSET_OF (PCI_TYPE00, Device.Bar),
PCI_MAX_BAR,
(VOID *)OldBar
);
DEBUG ((DEBUG_INFO, "OCDM: Reprogrammed BARs to original - %r\n", Status));
}
}
return EFI_SUCCESS;
}
STATIC
EFI_STATUS
SetResizableBarOnDeviceRbIo (
IN EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL *PciRootBridgeIo,
IN UINT64 PciAddress,
IN PCI_BAR_SIZE Size,
IN BOOLEAN Increase
)
{
EFI_STATUS Status;
UINT32 ResizableBarOffset;
PCI_EXPRESS_EXTENDED_CAPABILITIES_RESIZABLE_BAR_ENTRY Entries[PCI_MAX_BAR];
PCI_EXPRESS_EXTENDED_CAPABILITIES_RESIZABLE_BAR_CONTROL ResizableBarControl;
UINT32 Offset;
UINT32 Index;
UINT32 ResizableBarNumber;
UINT64 Capabilities;
UINT64 NewCapabilities;
UINT32 OldBar[PCI_MAX_BAR];
UINT32 NewBar[PCI_MAX_BAR];
INTN Bit;
Status = LocatePciCapabilityRbIo (
PciRootBridgeIo,
PciAddress,
PCI_EXPRESS_EXTENDED_CAPABILITY_RESIZABLE_BAR_ID,
&ResizableBarOffset
);
if (EFI_ERROR (Status)) {
DEBUG ((DEBUG_INFO, "OCDM: RBAR is unsupported by device - %r\n", Status));
return EFI_UNSUPPORTED;
}
ResizableBarControl.Uint32 = 0;
Offset = ResizableBarOffset + sizeof (PCI_EXPRESS_EXTENDED_CAPABILITIES_HEADER)
+ sizeof (PCI_EXPRESS_EXTENDED_CAPABILITIES_RESIZABLE_BAR_CAPABILITY);
Status = PciRootBridgeIo->Pci.Read (
PciRootBridgeIo,
EfiPciWidthUint8,
PciAddrOffset (PciAddress, Offset),
sizeof (PCI_EXPRESS_EXTENDED_CAPABILITIES_RESIZABLE_BAR_CONTROL),
&ResizableBarControl
);
DEBUG ((
DEBUG_INFO,
"OCDM: RBAR control is %X, total %u - %r\n",
ResizableBarControl.Uint32,
MIN (ResizableBarControl.Bits.ResizableBarNumber, PCI_MAX_BAR),
Status
));
if (EFI_ERROR (Status)) {
return EFI_UNSUPPORTED;
}
ResizableBarNumber = MIN (ResizableBarControl.Bits.ResizableBarNumber, PCI_MAX_BAR);
Status = PciRootBridgeIo->Pci.Read (
PciRootBridgeIo,
EfiPciWidthUint8,
PciAddrOffset (PciAddress, ResizableBarOffset + sizeof (PCI_EXPRESS_EXTENDED_CAPABILITIES_HEADER)),
sizeof (PCI_EXPRESS_EXTENDED_CAPABILITIES_RESIZABLE_BAR_ENTRY) * ResizableBarNumber,
Entries
);
if (EFI_ERROR (Status)) {
DEBUG ((DEBUG_INFO, "OCDM: RBAR caps cannot be read - %r\n", Status));
return EFI_UNSUPPORTED;
}
Status = PciRootBridgeIo->Pci.Read (
PciRootBridgeIo,
EfiPciWidthUint32,
PciAddrOffset (PciAddress, OFFSET_OF (PCI_TYPE00, Device.Bar)),
PCI_MAX_BAR,
OldBar
);
if (EFI_ERROR (Status)) {
ZeroMem (OldBar, sizeof (OldBar));
}
DEBUG ((
DEBUG_INFO,
"OCDM: Old BAR %08X %08X %08X %08X %08X %08X - %r\n",
OldBar[0],
OldBar[1],
OldBar[2],
OldBar[3],
OldBar[4],
OldBar[5],
Status
));
for (Index = 0; Index < ResizableBarNumber; Index++) {
//
// When the bit of Capabilities Set, indicates that the Function supports
// operating with the BAR sized to (2^Bit) MB.
// Example:
// Bit 0 is set: supports operating with the BAR sized to 1 MB
// Bit 1 is set: supports operating with the BAR sized to 2 MB
// Bit n is set: supports operating with the BAR sized to (2^n) MB
//
// Reference values for RX 6900 with two resizable BARs.
// Disabled values:
// Resizeable Bar Capability [1]
// ResizableBarCapability 0007F000
// ResizableBarControl 0840
// Resizeable Bar Capability [2]
// ResizableBarCapability 00001FE0
// ResizableBarControl 0102
// Enabled values:
// Resizeable Bar Capability [1]
// ResizableBarCapability 0007F000
// ResizableBarControl 0E40
// Resizeable Bar Capability [2]
// ResizableBarCapability 00001FE0
// ResizableBarControl 0802
//
NewCapabilities = Capabilities = LShiftU64 (Entries[Index].ResizableBarControl.Bits.BarSizeCapability, 28)
| Entries[Index].ResizableBarCapability.Bits.BarSizeCapability;
//
// Restrict supported BARs to specified value.
//
NewCapabilities &= PCI_BAR_CAP_LIMIT (Size);
//
// Disable bits higher than current as we are not allowed to increase bar size
// more than we already have.
//
if (!Increase) {
NewCapabilities &= PCI_BAR_CAP_LIMIT (Entries[Index].ResizableBarControl.Bits.BarSize);
}
//
// If requested BAR size is too low, choose the lowest available BAR size.
//
if ( (NewCapabilities == 0)
&& (Entries[Index].ResizableBarControl.Bits.BarSize > (UINT32)Size))
{
Bit = LowBitSet64 (Capabilities);
} else {
Bit = HighBitSet64 (NewCapabilities);
}
DEBUG ((
DEBUG_INFO,
"OCDM: RBAR %u/%u supports 0x%Lx, sizing %u inc %d results setting from %u to %d\n",
Index + 1,
ResizableBarNumber,
Capabilities,
Size,
Increase,
Entries[Index].ResizableBarControl.Bits.BarSize,
(INT32)Bit
));
//
// If we have no supported configuration, just skip.
//
if ((Bit < 0) || (Entries[Index].ResizableBarControl.Bits.BarSize == (UINT32)Bit)) {
continue;
}
Offset = ResizableBarOffset + sizeof (PCI_EXPRESS_EXTENDED_CAPABILITIES_HEADER)
+ Index * sizeof (PCI_EXPRESS_EXTENDED_CAPABILITIES_RESIZABLE_BAR_ENTRY)
+ OFFSET_OF (PCI_EXPRESS_EXTENDED_CAPABILITIES_RESIZABLE_BAR_ENTRY, ResizableBarControl);
Entries[Index].ResizableBarControl.Bits.BarSize = (UINT32)Bit;
PciRootBridgeIo->Pci.Write (
PciRootBridgeIo,
EfiPciWidthUint32,
PciAddrOffset (PciAddress, Offset),
1,
&Entries[Index].ResizableBarControl.Uint32
);
}
DEBUG_CODE_BEGIN ();
Status = PciRootBridgeIo->Pci.Read (
PciRootBridgeIo,
EfiPciWidthUint32,
PciAddrOffset (PciAddress, OFFSET_OF (PCI_TYPE00, Device.Bar)),
PCI_MAX_BAR,
NewBar
);
if (EFI_ERROR (Status)) {
ZeroMem (NewBar, sizeof (NewBar));
}
DEBUG ((
DEBUG_INFO,
"OCDM: New BAR %08X %08X %08X %08X %08X %08X - %r\n",
NewBar[0],
NewBar[1],
NewBar[2],
NewBar[3],
NewBar[4],
NewBar[5],
Status
));
DEBUG_CODE_END ();
//
// PCI BARs are reset after resizing, so we must restore them. This follows the spec:
// After writing the BAR Size field, the contents of the corresponding BAR are undefined.
// To ensure that it contains a valid address after resizing the BAR, system software must
// reprogram the BAR, and Set the Memory Space Enable bit (unless the resource is not allocated).
// TODO: We do not bother touching `Memory Space Enable` bit but strictly we should.
//
if (!IsZeroBuffer (OldBar, sizeof (OldBar))) {
Status = PciRootBridgeIo->Pci.Write (
PciRootBridgeIo,
EfiPciWidthUint32,
PciAddrOffset (PciAddress, OFFSET_OF (PCI_TYPE00, Device.Bar)),
PCI_MAX_BAR,
OldBar
);
DEBUG ((DEBUG_INFO, "OCDM: Reprogrammed BARs to original - %r\n", Status));
}
return EFI_SUCCESS;
}
EFI_STATUS
ResizeGpuBarsPciIo (
IN PCI_BAR_SIZE Size,
IN BOOLEAN Increase
)
{
EFI_STATUS Status;
UINTN HandleCount;
EFI_HANDLE *HandleBuffer;
UINTN Index;
EFI_PCI_IO_PROTOCOL *PciIo;
PCI_CLASSCODE ClassCode;
BOOLEAN HasSuccess;
ASSERT (Size < PciBarTotal);
HasSuccess = FALSE;
Status = gBS->LocateHandleBuffer (
ByProtocol,
&gEfiPciIoProtocolGuid,
NULL,
&HandleCount,
&HandleBuffer
);
if (EFI_ERROR (Status)) {
DEBUG ((DEBUG_INFO, "OCDM: No PCI devices for RBAR support - %r\n", Status));
return Status;
}
for (Index = 0; Index < HandleCount; ++Index) {
Status = gBS->HandleProtocol (
HandleBuffer[Index],
&gEfiPciIoProtocolGuid,
(VOID **)&PciIo
);
if (EFI_ERROR (Status)) {
continue;
}
Status = PciIo->Pci.Read (
PciIo,
EfiPciIoWidthUint8,
PCI_CLASSCODE_OFFSET,
sizeof (PCI_CLASSCODE) / sizeof (UINT8),
&ClassCode
);
if (EFI_ERROR (Status)) {
continue;
}
DEBUG ((DEBUG_VERBOSE, "OCDM: PCI device %u/%u has class %X\n", Index+1, HandleCount, ClassCode));
if (ClassCode.BaseCode != PCI_CLASS_DISPLAY) {
continue;
}
DEBUG ((
DEBUG_INFO,
"OCDM: Setting RBAR to %u inc %d on %u/%u\n",
Size,
Increase,
Index+1,
HandleCount
));
Status = SetResizableBarOnDevicePciIo (PciIo, Size, Increase);
if (!EFI_ERROR (Status)) {
HasSuccess = TRUE;
}
}
FreePool (HandleBuffer);
if (HasSuccess) {
return EFI_SUCCESS;
}
return EFI_NOT_FOUND;
}
STATIC
BOOLEAN
PciGetNextBusRange (
IN OUT EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR **Descriptors,
OUT UINT16 *MinBus,
OUT UINT16 *MaxBus
)
{
//
// When *Descriptors is NULL, Configuration() is not implemented, so assume
// range is 0~PCI_MAX_BUS
//
if ((*Descriptors) == NULL) {
*MinBus = 0;
*MaxBus = PCI_MAX_BUS;
return FALSE;
}
//
// *Descriptors points to one or more address space descriptors, which
// ends with a end tagged descriptor. Examine each of the descriptors,
// if a bus typed one is found and its bus range covers bus, this handle
// is the handle we are looking for.
//
while ((*Descriptors)->Desc != ACPI_END_TAG_DESCRIPTOR) {
if ((*Descriptors)->ResType == ACPI_ADDRESS_SPACE_TYPE_BUS) {
*MinBus = (UINT16)(*Descriptors)->AddrRangeMin;
*MaxBus = (UINT16)(*Descriptors)->AddrRangeMax;
(*Descriptors)++;
return FALSE;
}
(*Descriptors)++;
}
return TRUE;
}
STATIC
EFI_STATUS
ResizeGpuBarsRbIo (
IN PCI_BAR_SIZE Size,
IN BOOLEAN Increase
)
{
EFI_STATUS Status;
UINTN HandleCount;
EFI_HANDLE *HandleBuffer;
UINTN Index;
EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL *PciRootBridgeIo;
EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *Descriptors;
UINT8 HdrType;
UINT8 Bus;
UINT8 Dev;
UINT8 Func;
UINT16 MinBus;
UINT16 MaxBus;
BOOLEAN IsEnd;
BOOLEAN HasSuccess;
PCI_CLASSCODE ClassCode;
UINT64 PciAddress;
ASSERT (Size < PciBarTotal);
HasSuccess = FALSE;
Status = gBS->LocateHandleBuffer (
ByProtocol,
&gEfiPciRootBridgeIoProtocolGuid,
NULL,
&HandleCount,
&HandleBuffer
);
if (EFI_ERROR (Status)) {
DEBUG ((DEBUG_INFO, "OCDM: No PCI devices for RBAR support - %r\n", Status));
return Status;
}
for (Index = 0; Index < HandleCount; ++Index) {
Status = gBS->HandleProtocol (
HandleBuffer[Index],
&gEfiPciRootBridgeIoProtocolGuid,
(VOID **)&PciRootBridgeIo
);
if (EFI_ERROR (Status)) {
continue;
}
Status = PciRootBridgeIo->Configuration (PciRootBridgeIo, (VOID **)&Descriptors);
if (EFI_ERROR (Status)) {
continue;
}
//
// Not sure if multiple root bridge systems even exist but this should support them
//
while (TRUE) {
IsEnd = PciGetNextBusRange (&Descriptors, &MinBus, &MaxBus);
if (IsEnd || (Descriptors == NULL)) {
break;
}
for (Bus = 0; Bus <= MaxBus; Bus++) {
for (Dev = 0; Dev <= PCI_MAX_DEVICE; Dev++) {
for (Func = 0; Func <= PCI_MAX_FUNC; Func++) {
PciAddress = EFI_PCI_ADDRESS (Bus, Dev, Func, 0);
// PciAddrOffset doesnt need to be used below 256
Status = PciRootBridgeIo->Pci.Read (
PciRootBridgeIo,
EfiPciWidthUint8,
PciAddress + PCI_CLASSCODE_OFFSET,
sizeof (PCI_CLASSCODE) / sizeof (UINT8),
&ClassCode
);
if (EFI_ERROR (Status)) {
continue;
}
DEBUG ((DEBUG_VERBOSE, "OCDM: PCI device %u/%u/%u has class %X\n", Bus, Dev, Func, ClassCode));
if (ClassCode.BaseCode != PCI_CLASS_DISPLAY) {
continue;
}
DEBUG ((
DEBUG_INFO,
"OCDM: Setting RBAR to %u inc %d on %u/%u/%u\n",
Size,
Increase,
Bus,
Dev,
Func
));
Status = SetResizableBarOnDeviceRbIo (PciRootBridgeIo, PciAddress, Size, Increase);
if (!EFI_ERROR (Status)) {
HasSuccess = TRUE;
}
PciRootBridgeIo->Pci.Read (PciRootBridgeIo, EfiPciWidthUint8, PciAddress + PCI_HEADER_TYPE_OFFSET, 1, &HdrType);
if (!Func && ((HdrType & HEADER_TYPE_MULTI_FUNCTION) == 0)) {
break;
}
}
}
}
}
}
FreePool (HandleBuffer);
if (HasSuccess) {
return EFI_SUCCESS;
}
return EFI_NOT_FOUND;
}
EFI_STATUS
ResizeGpuBars (
IN PCI_BAR_SIZE Size,
IN BOOLEAN Increase,
IN BOOLEAN UseRbIo
)
{
if (UseRbIo) {
DEBUG ((DEBUG_INFO, "OCDM: RBAR using PciRootBridgeIo\n"));
return ResizeGpuBarsRbIo (Size, Increase);
}
DEBUG ((DEBUG_INFO, "OCDM: RBAR using PciIo\n"));
return ResizeGpuBarsPciIo (Size, Increase);
}
|
40470dec6fa0e0d60a03ca0b141094fb217db0bd
|
376e1818d427b5e4d32fa6dd6c7b71e9fd88afdb
|
/comms/lirc/patches/patch-daemons_config__file.h
|
63217739f46ebc0991f76b6394a901ffd0c5cf95
|
[] |
no_license
|
NetBSD/pkgsrc
|
a0732c023519650ef821ab89c23ab6ab59e25bdb
|
d042034ec4896cc5b47ed6f2e5b8802d9bc5c556
|
refs/heads/trunk
| 2023-09-01T07:40:12.138283
| 2023-09-01T05:25:19
| 2023-09-01T05:25:19
| 88,439,572
| 321
| 138
| null | 2023-07-12T22:34:14
| 2017-04-16T20:04:15
| null |
UTF-8
|
C
| false
| false
| 490
|
h
|
patch-daemons_config__file.h
|
$NetBSD: patch-daemons_config__file.h,v 1.1 2016/05/02 02:32:14 dholland Exp $
Patch up gcc inline mess.
--- daemons/config_file.h~ 2011-03-25 22:28:18.000000000 +0000
+++ daemons/config_file.h
@@ -67,7 +67,6 @@ struct void_array {
void **init_void_array(struct void_array *ar, size_t chunk_size, size_t item_size);
int add_void_array(struct void_array *ar, void *data);
-inline void *get_void_array(struct void_array *ar);
/* some safer functions */
void *s_malloc(size_t size);
|
5c4c85a32dc01540bbd38430fc8d026d10ec625d
|
0744dcc5394cebf57ebcba343747af6871b67017
|
/external/include/protocols/libcoap/subscribe.h
|
826ecec597f75dd453eafc99430ccc5e1165affd
|
[
"Apache-2.0",
"BSD-3-Clause",
"MIT"
] |
permissive
|
Samsung/TizenRT
|
96abf62f1853f61fcf91ff14671a5e0c6ca48fdb
|
1a5c2e00a4b1bbf4c505bbf5cc6a8259e926f686
|
refs/heads/master
| 2023-08-31T08:59:33.327998
| 2023-08-08T06:09:20
| 2023-08-31T04:38:20
| 82,517,252
| 590
| 719
|
Apache-2.0
| 2023-09-14T06:54:49
| 2017-02-20T04:38:30
|
C
|
UTF-8
|
C
| false
| false
| 8,340
|
h
|
subscribe.h
|
/****************************************************************************
*
* Copyright 2016 Samsung Electronics All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific
* language governing permissions and limitations under the License.
*
****************************************************************************/
/* subscribe.h -- subscription handling for CoAP
* see draft-hartke-coap-observe-03
*
* Copyright (C) 2010--2012 Olaf Bergmann <bergmann@tzi.org>
*
* This file is part of the CoAP library libcoap. Please see
* README for terms of use.
*/
#ifndef _COAP_SUBSCRIBE_H_
#define _COAP_SUBSCRIBE_H_
#include <protocols/libcoap/config.h>
#include <protocols/libcoap/address.h>
/**
* @defgroup observe Resource observation
* @{
*/
#ifndef COAP_OBS_MAX_NON
/**
* Number of notifications that may be sent non-confirmable before a
* confirmable message is sent to detect if observers are alive. The
* maximum allowed value here is @c 15.
*/
#define COAP_OBS_MAX_NON 5
#endif /* COAP_OBS_MAX_NON */
#ifndef COAP_OBS_MAX_FAIL
/**
* Number of confirmable notifications that may fail (i.e. time out
* without being ACKed) before an observer is removed. The maximum
* value for COAP_OBS_MAX_FAIL is @c 3.
*/
#define COAP_OBS_MAX_FAIL 3
#endif /* COAP_OBS_MAX_FAIL */
/** Subscriber information */
typedef struct coap_subscription_t {
struct coap_subscription_t *next;
/**< next element in linked list */
coap_address_t subscriber; /**< address and port of subscriber */
unsigned int non: 1; /**< send non-confirmable notifies if @c 1 */
unsigned int non_cnt: 4; /**< up to 15 non-confirmable notifies allowed */
unsigned int fail_cnt: 2; /**< up to 3 confirmable notifies can fail */
unsigned int dirty: 1; /**< set if the notification temporarily could not be sent (in that case, the resource's partiallydirty flag is set too) */
size_t token_length; /**< actual length of token */
unsigned char token[8]; /**< token used for subscription */
/* @todo CON/NON flag, block size */
} coap_subscription_t;
void coap_subscription_init(coap_subscription_t *);
#if 0
#include "uthash.h"
#include "uri.h"
#include "list.h"
#include "pdu.h"
#include "net.h"
#if 0
typedef unsigned long coap_key_t;
/** Used to indicate that a hashkey is invalid. */
#define COAP_INVALID_HASHKEY ((coap_key_t)-1)
typedef struct {
coap_uri_t *uri; /* unique identifier; memory is released by coap_delete_resource() */
UT_hash_handle hh; /**< hash handle (for internal use only) */
str *name; /* display name of the resource */
unsigned char mediatype; /* media type for resource representation */
unsigned int dirty: 1; /* set to 1 if resource has changed */
unsigned int writable: 1; /* set to 1 if resource can be changed using PUT */
/* cache-control */
unsigned char etag[4]; /* version identifier for this resource
* (zero terminated, first byte is zero if not set). */
unsigned int maxage; /* maximum cache time (zero means no Max-age option) */
/**
* Callback function that copies the resource representation into the provided data
* buffer (PDU payload). finished is set to 1 to indicate that this was the last block
* of buflen data for this resource representation, 0 means that data is not finished
* and a subsequent call with offset updated by buflen would yield more data (i.e.
* the M-bit of CoAP's block option must be set if offset and buflen are selected
* accordingly.
* When called, buflen must be set to the maximum length of buf that is to be filled
* with the mediatype representation of the resource identified by uri.
* The mediatype must be set to the requested mediatype of COAP_MEDIATYPE_ANY if
* none was given. On return, the mediatype will be set to the type that is
* actually used.
* The return value indicates the result code that should be used in a response to
* this function.
*/
int (*data)(coap_uri_t *uri, unsigned char *mediatype, unsigned int offset, unsigned char *buf, unsigned int *buflen, int *finished);
} coap_resource_t;
#endif
typedef struct {
coap_key_t resource; /* hash key for subscribed resource */
time_t expires; /* expiry time of subscription */
coap_address_t subscriber; /**< subscriber's address */
str token; /**< subscription token */
} coap_subscription_t;
#define COAP_RESOURCE(node) ((coap_resource_t *)(node)->data)
#define COAP_SUBSCRIPTION(node) ((coap_subscription_t *)(node)->data)
/** Checks subscribed resources for updates and notifies subscribers of changes. */
void coap_check_resource_list(coap_context_t *context);
/** Removes expired subscriptions. */
void coap_check_subscriptions(coap_context_t *context);
#if 0
/**
* Adds specified resource to the resource observation list. Returns a
* unique key for the resource. The alloceted memory is released when
* the resource is destroyed with coap_delete_resource().
*/
coap_key_t coap_add_resource(coap_context_t *context, coap_resource_t *);
/**
* Deletes the resource that is identified by key. Returns 1 if the resource was
* removed, 0 on error (e.g. if no such resource exists).
*/
int coap_delete_resource(coap_context_t *context, coap_key_t key);
#endif
/**
* Creates a new subscription object filled with the given data. The storage
* allocated for this object must be released using coap_free(). */
coap_subscription_t *coap_new_subscription(coap_context_t *context, const coap_uri_t *resource, const struct sockaddr *subscriber, socklen_t addrlen, time_t expiry);
/**
* Adds the given subsription object to the observer list.
* @param context The CoAP context
* @param subscription A new subscription oobject created with coap_new_subscription()
* @return A unique hash key for this resource or COAP_INVALID_HASHKEY on error.
* The storage allocated for the subscription object is released when it is
* removed from the subscription list, unless the function has returned
* COAP_INVALID_HASHKEY. In this case, the storage must be released by the
* caller of this function.
*/
coap_key_t coap_add_subscription(coap_context_t *context, coap_subscription_t *subscription);
/**
* Returns the subscription from subscriber for the resource identified
* by hashkey. When token is not NULL the subscription must have the
* same token.
* @param context The CoAP context
* @param hashkey The unique key that identifies the subscription
* @param subscriber The subscriber's transport address
* @param token If not NULL, this specifies a token given by the
* subscriber to identify its subscription.
* @return The requested subscription object or NULL when not found.
*/
coap_subscription_t *coap_find_subscription(coap_context_t *context, coap_key_t hashkey, struct sockaddr *subscriber, str *token);
/**
* Removes a subscription from the subscription list stored in context and
* releases the storage that was allocated for this subscription.
* @param context The CoAP context.
* @param haskey The unique key that identifies the subscription to remove.
* @return 1 if a subscription was removed, 0 otherwise.
*/
int coap_delete_subscription(coap_context_t *context, coap_key_t hashkey, struct sockaddr *subscriber);
/** Returns a unique hash for the specified URI or COAP_INVALID_HASHKEY on error. */
coap_key_t coap_uri_hash(const coap_uri_t *uri);
/** Returns a unique hash for the specified subscription or COAP_INVALID_HASHKEY on error. */
coap_key_t coap_subscription_hash(coap_subscription_t *subscription);
#if 0
/** Returns the resource identified by key or NULL if not found. */
coap_resource_t *coap_get_resource_from_key(coap_context_t *ctx, coap_key_t key);
/** Returns the resource identified by uri or NULL if not found. */
coap_resource_t *coap_get_resource(coap_context_t *ctx, coap_uri_t *uri);
#endif
#endif
/** @} */
#endif /* _COAP_SUBSCRIBE_H_ */
|
0b67ff0ea81b0be83523363f1986035c8a330d6f
|
167c6226bc77c5daaedab007dfdad4377f588ef4
|
/cpp/ql/test/library-tests/attributes/type_attributes/type_attributes.c
|
1111602430a511178aac325c9096b9876867e162
|
[
"LicenseRef-scancode-public-domain",
"MIT"
] |
permissive
|
github/codeql
|
1eebb449a34f774db9e881b52cb8f7a1b1a53612
|
d109637e2d7ab3b819812eb960c05cb31d9d2168
|
refs/heads/main
| 2023-08-20T11:32:39.162059
| 2023-08-18T14:33:32
| 2023-08-18T14:33:32
| 143,040,428
| 5,987
| 1,363
|
MIT
| 2023-09-14T19:36:50
| 2018-07-31T16:35:51
|
CodeQL
|
UTF-8
|
C
| false
| false
| 580
|
c
|
type_attributes.c
|
// Compilable with
// gcc -c type_attributes.c
// clang -c type_attributes.c
struct __attribute__((__packed__)) my_packed_struct {
char c;
int i;
};
typedef union __attribute__((__transparent_union__)) {
int i;
int j;
} tu;
// This union can't be made transparent, as the types aren't the same size
typedef union __attribute__((__transparent_union__)) {
char c;
long long int j;
} notTransparent;
typedef __attribute__((unused)) int unusedInt;
typedef int depInt __attribute__ ((deprecated));
typedef short __attribute__((__may_alias__)) short_a;
|
b3505c43c2ba8eed74af0997dbbc73f437e68273
|
aa3befea459382dc5c01c925653d54f435b3fb0f
|
/boards/arm/stm32wl5/nucleo-wl55jc/src/nucleo-wl55jc.h
|
c6118cd1cd3c360e33b9611eb9f4922e572f5778
|
[
"MIT-open-group",
"BSD-3-Clause",
"HPND-sell-variant",
"BSD-4-Clause-UC",
"LicenseRef-scancode-warranty-disclaimer",
"MIT-0",
"LicenseRef-scancode-bsd-atmel",
"LicenseRef-scancode-gary-s-brown",
"LicenseRef-scancode-proprietary-license",
"SunPro",
"MIT",
"LicenseRef-scancode-public-domain-disclaimer",
"LicenseRef-scancode-other-permissive",
"HPND",
"ISC",
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause",
"GPL-1.0-or-later",
"CC-BY-2.0",
"CC-BY-4.0"
] |
permissive
|
apache/nuttx
|
14519a7bff4a87935d94fb8fb2b19edb501c7cec
|
606b6d9310fb25c7d92c6f95bf61737e3c79fa0f
|
refs/heads/master
| 2023-08-25T06:55:45.822534
| 2023-08-23T16:03:31
| 2023-08-24T21:25:47
| 228,103,273
| 407
| 241
|
Apache-2.0
| 2023-09-14T18:26:05
| 2019-12-14T23:27:55
|
C
|
UTF-8
|
C
| false
| false
| 6,679
|
h
|
nucleo-wl55jc.h
|
/****************************************************************************
* boards/arm/stm32wl5/nucleo-wl55jc/src/nucleo-wl55jc.h
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership. The
* ASF licenses this file to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*
****************************************************************************/
#ifndef __BOARDS_ARM_STM32WL5_NUCLEO_WL55JC_SRC_NUCLEO_WL55JC_H
#define __BOARDS_ARM_STM32WL5_NUCLEO_WL55JC_SRC_NUCLEO_WL55JC_H
/****************************************************************************
* Included Files
****************************************************************************/
#include <nuttx/config.h>
#include <nuttx/compiler.h>
#include <stdint.h>
#include <stm32wl5.h>
/****************************************************************************
* Pre-processor Definitions
****************************************************************************/
/* Configuration ************************************************************/
#define HAVE_PROC 1
#if !defined(CONFIG_FS_PROCFS)
# undef HAVE_PROC
#endif
#if defined(HAVE_PROC) && defined(CONFIG_DISABLE_MOUNTPOINT)
# warning Mountpoints disabled. No procfs support
# undef HAVE_PROC
#endif
#if defined(CONFIG_LCD_SSD1680)
/* There is no E-ink display on a board.
* It can be connected on many different ways
* It is possible to configure pins using make menuconfig
*/
# if defined(CONFIG_SSD1680_GPIO_CS_PORTA)
# define CONFIG_SSD1680_CS_PORT GPIO_PORTA
# elif defined(CONFIG_SSD1680_GPIO_CS_PORTB)
# define CONFIG_SSD1680_CS_PORT GPIO_PORTB
# elif defined(CONFIG_SSD1680_GPIO_CS_PORTC)
# define CONFIG_SSD1680_CS_PORT GPIO_PORTC
# elif defined(CONFIG_SSD1680_GPIO_CS_PORTD)
# define CONFIG_SSD1680_CS_PORT GPIO_PORTD
# endif
# if defined(CONFIG_SSD1680_GPIO_DTA_CMD_PORTA)
# define CONFIG_SSD1680_DC_PORT GPIO_PORTA
# elif defined(CONFIG_SSD1680_GPIO_DTA_CMD_PORTB)
# define CONFIG_SSD1680_DC_PORT GPIO_PORTB
# elif defined(CONFIG_SSD1680_GPIO_DTA_CMD_PORTC)
# define CONFIG_SSD1680_DC_PORT GPIO_PORTC
# elif defined(CONFIG_SSD1680_GPIO_DTA_CMD_PORTD)
# define CONFIG_SSD1680_DC_PORT GPIO_PORTD
# endif
# if defined(CONFIG_SSD1680_GPIO_RST_PORTA)
# define CONFIG_SSD1680_RST_PORT GPIO_PORTA
# elif defined(CONFIG_SSD1680_GPIO_RST_PORTB)
# define CONFIG_SSD1680_RST_PORT GPIO_PORTB
# elif defined(CONFIG_SSD1680_GPIO_RST_PORTC)
# define CONFIG_SSD1680_RST_PORT GPIO_PORTC
# elif defined(CONFIG_SSD1680_GPIO_RST_PORTD)
# define CONFIG_SSD1680_RST_PORT GPIO_PORTD
# endif
# if defined(CONFIG_SSD1680_GPIO_BUSY_PORTA)
# define CONFIG_SSD1680_BUSY_PORT GPIO_PORTA
# elif defined(CONFIG_SSD1680_GPIO_BUSY_PORTB)
# define CONFIG_SSD1680_BUSY_PORT GPIO_PORTB
# elif defined(CONFIG_SSD1680_GPIO_BUSY_PORTC)
# define CONFIG_SSD1680_BUSY_PORT GPIO_PORTC
# elif defined(CONFIG_SSD1680_GPIO_BUSY_PORTD)
# define CONFIG_SSD1680_BUSY_PORT GPIO_PORTD
# endif
# define GPIO_SSD1680_CS (GPIO_OUTPUT|GPIO_OTYPER_PP(0)|GPIO_SPEED_2MHz|\
GPIO_OUTPUT_SET|\
CONFIG_SSD1680_CS_PORT|\
CONFIG_SSD1680_GPIO_PIN_CS)
# define GPIO_SSD1680_CMD (GPIO_OUTPUT|GPIO_OTYPER_PP(0)|GPIO_OSPEED_2MHz|\
GPIO_OUTPUT_SET|\
CONFIG_SSD1680_DC_PORT|\
CONFIG_SSD1680_GPIO_PIN_DTA_CMD)
# ifdef CONFIG_SSD1680_RST_PORT
# define GPIO_SSD1680_RST (GPIO_OUTPUT|GPIO_OTYPER_PP(0)|GPIO_SPEED_2MHz|\
GPIO_OUTPUT_SET|\
CONFIG_SSD1680_RST_PORT|\
CONFIG_SSD1680_GPIO_PIN_RST)
# endif
# ifdef CONFIG_SSD1680_BUSY_PORT
# define GPIO_SSD1680_BUSY (GPIO_INPUT|GPIO_PULLUP|GPIO_SPEED_2MHz|\
CONFIG_SSD1680_BUSY_PORT|\
CONFIG_SSD1680_GPIO_PIN_BUSY)
# endif
#endif
#define GPIO_LED_GREEN (GPIO_PORTB|GPIO_PIN9 |GPIO_OUTPUT|GPIO_PULLUP|GPIO_SPEED_50MHz)
#define GPIO_LED_RED (GPIO_PORTB|GPIO_PIN11|GPIO_OUTPUT|GPIO_PULLUP|GPIO_SPEED_50MHz)
#define GPIO_LED_BLUE (GPIO_PORTB|GPIO_PIN15|GPIO_OUTPUT|GPIO_PULLUP|GPIO_SPEED_50MHz)
#define GPIO_BUTTON1 (GPIO_PORTA|GPIO_PIN0|GPIO_INPUT|GPIO_PULLUP)
#define GPIO_BUTTON2 (GPIO_PORTA|GPIO_PIN1|GPIO_INPUT|GPIO_PULLUP)
#define GPIO_BUTTON3 (GPIO_PORTC|GPIO_PIN6|GPIO_INPUT|GPIO_PULLUP|GPIO_EXTI)
/****************************************************************************
* Public Data
****************************************************************************/
/****************************************************************************
* Public Functions Prototypes
****************************************************************************/
/****************************************************************************
* Name: board_leds_initialize
*
* Description:
* Initialize LEDs
*
****************************************************************************/
void board_leds_initialize(void);
/****************************************************************************
* Name: stm32wl5_flash_init
*
* Description:
* Initialize on-board FLASH partition table
*
****************************************************************************/
int stm32wl5_flash_init(void);
/****************************************************************************
* Name: stm32wl5_spidev_initialize
*
* Description:
* Initialize SPIs
*
****************************************************************************/
void stm32wl5_spidev_initialize(void);
/****************************************************************************
* Name: ipcc_init
*
* Description:
* Initializes configured IPCC channels.
*
****************************************************************************/
int ipcc_init(void);
#endif /* __BOARDS_ARM_STM32WL5_NUCLEO_WL55JC_SRC_NUCLEO_WL55JC_H */
|
0fbc7b7f9d5248a9033b4eebd511076e20333f37
|
aa3befea459382dc5c01c925653d54f435b3fb0f
|
/arch/arm/src/samd2l2/hardware/saml_pm.h
|
2d3ec88f2c17d41784ae6d3d6eeefbad3f69aa7c
|
[
"MIT-open-group",
"BSD-3-Clause",
"HPND-sell-variant",
"BSD-4-Clause-UC",
"LicenseRef-scancode-warranty-disclaimer",
"MIT-0",
"LicenseRef-scancode-bsd-atmel",
"LicenseRef-scancode-gary-s-brown",
"LicenseRef-scancode-proprietary-license",
"SunPro",
"MIT",
"LicenseRef-scancode-public-domain-disclaimer",
"LicenseRef-scancode-other-permissive",
"HPND",
"ISC",
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause",
"GPL-1.0-or-later",
"CC-BY-2.0",
"CC-BY-4.0"
] |
permissive
|
apache/nuttx
|
14519a7bff4a87935d94fb8fb2b19edb501c7cec
|
606b6d9310fb25c7d92c6f95bf61737e3c79fa0f
|
refs/heads/master
| 2023-08-25T06:55:45.822534
| 2023-08-23T16:03:31
| 2023-08-24T21:25:47
| 228,103,273
| 407
| 241
|
Apache-2.0
| 2023-09-14T18:26:05
| 2019-12-14T23:27:55
|
C
|
UTF-8
|
C
| false
| false
| 8,260
|
h
|
saml_pm.h
|
/****************************************************************************
* arch/arm/src/samd2l2/hardware/saml_pm.h
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership. The
* ASF licenses this file to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*
****************************************************************************/
/* References:
* "Atmel SAM L21E / SAM L21G / SAM L21J Smart ARM-Based Microcontroller
* Datasheet", Atmel-42385C-SAML21_Datasheet_Preliminary-03/20/15
*/
#ifndef __ARCH_ARM_SRC_SAMD2L2_HARDWARE_SAML_PM_H
#define __ARCH_ARM_SRC_SAMD2L2_HARDWARE_SAML_PM_H
/****************************************************************************
* Included Files
****************************************************************************/
#include <nuttx/config.h>
#include "chip.h"
#ifdef CONFIG_ARCH_FAMILY_SAML21
/****************************************************************************
* Pre-processor Definitions
****************************************************************************/
/* PM register offsets ******************************************************/
#define SAM_PM_CTRLA_OFFSET 0x0000 /* Control A */
#define SAM_PM_SLEEPCFG_OFFSET 0x0001 /* Sleep configuration */
#define SAM_PM_PLCFG_OFFSET 0x0002 /* Performance level configuration */
#define SAM_PM_INTENCLR_OFFSET 0x0004 /* Interrupt enable clear register */
#define SAM_PM_INTENSET_OFFSET 0x0005 /* Interrupt enable set register */
#define SAM_PM_INTFLAG_OFFSET 0x0006 /* Interrupt flag status and clear register */
#define SAM_PM_STDBYCFG_OFFSET 0x0008 /* Standby configuration */
/* PM register addresses ****************************************************/
#define SAM_PM_CTRLA (SAM_PM_BASE+SAM_PM_CTRLA_OFFSET)
#define SAM_PM_SLEEPCFG (SAM_PM_BASE+SAM_PM_SLEEPCFG_OFFSET)
#define SAM_PM_PLCFG (SAM_PM_BASE+SAM_PM_PLCFG_OFFSET)
#define SAM_PM_INTENCLR (SAM_PM_BASE+SAM_PM_INTENCLR_OFFSET)
#define SAM_PM_INTENSET (SAM_PM_BASE+SAM_PM_INTENSET_OFFSET)
#define SAM_PM_INTFLAG (SAM_PM_BASE+SAM_PM_INTFLAG_OFFSET)
#define SAM_PM_STDBYCFG (SAM_PM_BASE+SAM_PM_STDBYCFG_OFFSET)
/* PM register bit definitions **********************************************/
/* Control A register */
#define PM_CTRLA_IORET (1 << 2) /* Bit 2: I/O retention */
/* Sleep configuration register */
#define PM_SLEEPCFG_MODE_SHIFT (0) /* Bits 0-2: Idle Mode Configuration */
#define PM_SLEEPCFG_MODE_MASK (7 << PM_SLEEPCFG_MODE_SHIFT)
# define PM_SLEEPCFG_MODE_IDLE (2 << PM_SLEEPCFG_MODE_SHIFT) /* CPU, AHBx, APBx clocks OFF */
# define PM_SLEEPCFG_MODE_STANDBY (4 << PM_SLEEPCFG_MODE_SHIFT) /* All clocks OFF, except sleepwalking peripherals */
# define PM_SLEEPCFG_MODE_BACKUP (5 << PM_SLEEPCFG_MODE_SHIFT) /* Only backup domain is powered ON */
# define PM_SLEEPCFG_MODE_OFF (6 << PM_SLEEPCFG_MODE_SHIFT) /* All power domains are powered OFF */
/* Performance level configuration */
#define PM_PLCFG_PLSEL_SHIFT (0) /* Bits 0-1: Performance level select */
#define PM_PLCFG_PLSEL_MASK (3 << PM_PLCFG_PLSEL_SHIFT)
# define PM_PLCFG_PLSEL_PL0 (0 << PM_PLCFG_PLSEL_SHIFT) /* Performance level 0 */
# define PM_PLCFG_PLSEL_PL2 (2 << PM_PLCFG_PLSEL_SHIFT) /* Performance level 2 */
#define PM_PLCFG_PLDIS (1 << 7) /* Bit 7: Performance level disable */
/* Interrupt enable clear, Interrupt enable set,
* and Interrupt flag status and clear registers
*/
#define PM_INT_PLRDY (1 << 0) /* Bit 0: Performanc level ready */
/* Standby configuration */
#define PM_STDBYCFG_PDCFG_SHIFT (0) /* Bits 0-1: Power domain configuration */
#define PM_STDBYCFG_PDCFG_MASK (3 << PM_STDBYCFG_PDCFG_SHIFT)
# define PM_STDBYCFG_PDCFG_DEFAULT (0 << PM_STDBYCFG_PDCFG_SHIFT) /* All power domains handled by HW */
# define PM_STDBYCFG_PDCFG_PD01 (1 << PM_STDBYCFG_PDCFG_SHIFT) /* PD0 ACTIVE; PD1/2 handled by HW */
# define PM_STDBYCFG_PDCFG_PD12 (2 << PM_STDBYCFG_PDCFG_SHIFT) /* PD0/1 ACTIVE; PD2 handled by HW */
# define PM_STDBYCFG_PDCFG_PD012 (3 << PM_STDBYCFG_PDCFG_SHIFT) /* All power domains ACTIVE */
#define PM_STDBYCFG_DPGPD0 (1 << 4) /* Bit 4: Dynamic power gating for power domain 0 */
#define PM_STDBYCFG_DPGPD1 (1 << 5) /* Bit 5: Dynamic power gating for power domain 1 */
#define PM_STDBYCFG_VREGSMOD_SHIFT (6) /* Bits 6-7: Linked power domain */
#define PM_STDBYCFG_VREGSMOD_MASK (3 << PM_STDBYCFG_VREGSMOD_SHIFT)
# define PM_STDBYCFG_VREGSMOD_AUTO (0 << PM_STDBYCFG_VREGSMOD_SHIFT) /* Automatic mode */
# define PM_STDBYCFG_VREGSMOD_PERFORMANCE (1 << PM_STDBYCFG_VREGSMOD_SHIFT) /* Performance oriented */
# define PM_STDBYCFG_VREGSMOD_LP (2 << PM_STDBYCFG_VREGSMOD_SHIFT) /* Low power consumption oriented */
#define PM_STDBYCFG_LINKPD_SHIFT (8) /* Bits 8-9: */
#define PM_STDBYCFG_LINKPD_MASK (3 << PM_STDBYCFG_LINKPD_SHIFT)
# define PM_STDBYCFG_LINKPD_DEFAULT (0 << PM_STDBYCFG_LINKPD_SHIFT) /* Power domains not linked */
# define PM_STDBYCFG_LINKPD_PD01 (1 << PM_STDBYCFG_LINKPD_SHIFT) /* Power domains P0/1 linked */
# define PM_STDBYCFG_LINKPD_PD12 (2 << PM_STDBYCFG_LINKPD_SHIFT) /* Power domains P1/P2 linked */
# define PM_STDBYCFG_LINKPD_PD012 (3 << PM_STDBYCFG_LINKPD_SHIFT) /* All power domains linked */
#define PM_STDBYCFG_BBIASHS_SHIFT (10) /* Bits 10-11: Back bias for HMCRAMCHS */
#define PM_STDBYCFG_BBIASHS_MASK (3 << PM_STDBYCFG_BBIASHS_SHIFT)
# define PM_STDBYCFG_BBIASHS_RETBACK (0 << PM_STDBYCFG_BBIASHS_SHIFT) /* Retention back biasing mode */
# define PM_STDBYCFG_BBIASHS_STDBYBACK (1 << PM_STDBYCFG_BBIASHS_SHIFT) /* Standby back biasing mode */
# define PM_STDBYCFG_BBIASHS_STDBYOFF (2 << PM_STDBYCFG_BBIASHS_SHIFT) /* Standby OFF mode */
# define PM_STDBYCFG_BBIASHS_OFF (3 << PM_STDBYCFG_BBIASHS_SHIFT) /* Always OFF mode */
#define PM_STDBYCFG_BBIASLP_SHIFT (12) /* Bits 12-13: Back bias for HMCRAMCLP */
#define PM_STDBYCFG_BBIASLP_MASK (3 << PM_STDBYCFG_BBIASLP_SHIFT)
# define PM_STDBYCFG_BBIASLP_RETBACK (0 << PM_STDBYCFG_BBIASLP_SHIFT) /* Retention back biasing mode */
# define PM_STDBYCFG_BBIASLP_STDBYBACK (1 << PM_STDBYCFG_BBIASLP_SHIFT) /* Standby back biasing mode */
# define PM_STDBYCFG_BBIASLP_STDBYOFF (2 << PM_STDBYCFG_BBIASLP_SHIFT) /* Standby OFF mode */
# define PM_STDBYCFG_BBIASLP_OFF (3 << PM_STDBYCFG_BBIASLP_SHIFT) /* Always OFF mode */
/****************************************************************************
* Public Types
****************************************************************************/
/****************************************************************************
* Public Data
****************************************************************************/
/****************************************************************************
* Public Functions Prototypes
****************************************************************************/
#endif /* CONFIG_ARCH_FAMILY_SAML21 */
#endif /* __ARCH_ARM_SRC_SAMD2L2_HARDWARE_SAML_PM_H */
|
8a3d8bb806c00e1a99398483f693c1418e48d79e
|
ce99bd11ca505967277f4689c621479c1987698e
|
/src/game/chr_b.c
|
4ebdff43594924590812ecff027be1af741613a3
|
[] |
no_license
|
n64decomp/007
|
5951258890f15431f273e1503674c5e0402c66e0
|
c46751089ddc18b12ef7a45b6a3e03de2054c422
|
refs/heads/master
| 2022-11-08T23:34:54.021033
| 2022-10-29T14:41:01
| 2022-10-29T14:41:01
| 241,212,109
| 359
| 48
| null | 2020-11-21T23:30:31
| 2020-02-17T21:31:00
|
C
|
UTF-8
|
C
| false
| false
| 2,993
|
c
|
chr_b.c
|
#include <ultra64.h>
#include <bondtypes.h>
#include "cheat_buttons.h"
#include "chr.h"
#include "chr_b.h"
#include "chrobjdata.h"
#include "objecthandler.h"
s32 load_body_head_if_not_loaded(s32 model)
{
if (c_item_entries[model].header->RootNode == 0)
{
fileLoad(c_item_entries[model].header, c_item_entries[model].filename);
return 1;
}
return 0;
}
/**
* Address 0x7F0232E8 (VERSION_US)
* Address 0x7F0235D8 (other version)
*/
struct Model *makeonebody(s32 body, s32 head, struct ModelFileHeader *bodyHeader, struct ModelFileHeader *headHeader, s32 sunglasses, struct Model *model)
{
f32 scale;
f32 pov;
s32 opcode;
struct ModelRoData_HeaderRecord *node;
scale = c_item_entries[body].scale * 0.10000001f;
opcode = 0;
pov = c_item_entries[body].pov;
if (
#ifdef BUGFIX_R1
cheatIsActive(CHEAT_DK_MODE) && not_in_us_7F0209EC(body, head)
#else
cheatIsActive(CHEAT_DK_MODE)
#endif
)
{
scale *= 0.8f;
}
if (bodyHeader->RootNode == 0)
{
fileLoad(bodyHeader, c_item_entries[body].filename);
}
modelCalculateRwDataLen(bodyHeader);
if ((c_item_entries[body].hasHead == 0) && (head >= 0))
{
opcode = &bodyHeader->Switches[4]->Opcode;
if (opcode != 0)
{
if (headHeader->RootNode == 0)
{
fileLoad(headHeader, c_item_entries[head].filename);
#ifdef XBLADEBUG
#error fix XBLADEBUG
//sprintf("makeonebody: no head attachment for body number %d!\n",lVar3);
#endif
}
modelCalculateRwDataLen(headHeader);
bodyHeader->numRecords += headHeader->numRecords;
}
}
if (model == 0)
{
model = get_aircraft_obj_instance_controller(bodyHeader);
}
#ifdef XBLADEBUG
#error fix XBLADEBUG
//
// if (*&pMStack0000003c->field_0x2 < pMStack00000024->numRecords) {
// assertPrint_8291E690
// (".\\ported\\chrlv.cpp",0xc4,
// "Assertion failed: chrsub->inst.savesize>=bodyobj->savesize");
// }
//
//
#endif
if (model != 0)
{
modelSetScale(model, scale);
sub_GAME_7F06CE84(model, pov);
if ((headHeader != 0) && (c_item_entries[body].hasHead == 0))
{
bodyHeader->numRecords -= headHeader->numRecords;
sub_GAME_7F06C3B4(model, opcode, headHeader);
if ((sunglasses == 0) && ((s32) headHeader->numSwitches > 0))
{
if (headHeader->Switches[0] != 0)
{
node = modelGetNodeRwData(model, headHeader->Switches[0]);
node->ModelType = 0;
}
}
}
}
return model;
}
//sub_GAME_7F0234A8
Model *setup_chr_instance(int body,int head,ModelFileHeader *body_header, ModelFileHeader *head_header,int sunglasses)
{
return makeonebody(body,head,body_header,head_header,sunglasses,0x0);
}
|
0b6ec4ee66350c0a2e167f9ab003a1983130c521
|
76f9898ff7a555f4a729d725056a317af818375d
|
/assets/objects/object_link_boy/gSWLinkAdultFairyBowFPDL.c
|
c92c1d786aeb14cce81c3b69a2419c86431c71dd
|
[] |
no_license
|
z64proto/sw97
|
0b65837ab2f2a4073faca5670761d7fe0e74d29d
|
f571505ade2cefd4a5b5d19da06d33e7c6b02c60
|
refs/heads/master
| 2023-08-01T02:47:42.895871
| 2022-05-15T20:29:08
| 2022-05-15T20:29:08
| 430,216,978
| 208
| 29
| null | 2021-11-22T12:23:50
| 2021-11-20T21:52:59
|
C
|
UTF-8
|
C
| false
| false
| 10,594
|
c
|
gSWLinkAdultFairyBowFPDL.c
|
#include "ultra64.h"
#include "global.h"
u64 gSWLinkAdultFairyBowFPDL_bow_i8_png_i8[] = {
0xfffffefffffeffff, 0xfef7fcfefffaffff, 0xfcf2fcfdfff3fdff, 0xfff0f7f2f3edf8fd, 0xffeaeee2ede0eef9, 0xffeaeadee4c6e8e6, 0xfdd2cbd5bfa7d7bb, 0xdec6b5aba48c9c9d,
};
Vtx gSWLinkAdultFairyBowFPDL_gSWLinkAdultFairyBowFPDL_mesh_layer_Opaque_vtx_cull[8] = {
{{{-2009, -439, -78},0, {-16, -16},{0x0, 0x0, 0x0, 0x0}}},
{{{-2009, -439, 56},0, {-16, -16},{0x0, 0x0, 0x0, 0x0}}},
{{{-2009, 630, 56},0, {-16, -16},{0x0, 0x0, 0x0, 0x0}}},
{{{-2009, 630, -78},0, {-16, -16},{0x0, 0x0, 0x0, 0x0}}},
{{{2010, -439, -78},0, {-16, -16},{0x0, 0x0, 0x0, 0x0}}},
{{{2010, -439, 56},0, {-16, -16},{0x0, 0x0, 0x0, 0x0}}},
{{{2010, 630, 56},0, {-16, -16},{0x0, 0x0, 0x0, 0x0}}},
{{{2010, 630, -78},0, {-16, -16},{0x0, 0x0, 0x0, 0x0}}},
};
Vtx gSWLinkAdultFairyBowFPDL_gSWLinkAdultFairyBowFPDL_mesh_layer_Opaque_vtx_0[17] = {
{{{-106, 341, -19},0, {0, 256},{0x10, 0xA0, 0xAE, 0xFE}}},
{{{-489, 229, -44},0, {0, 256},{0x24, 0x90, 0xD1, 0xFE}}},
{{{-489, 325, -77},0, {0, 256},{0x6, 0xFB, 0x81, 0xFE}}},
{{{-106, 341, 10},0, {0, 256},{0x15, 0x97, 0x45, 0xFE}}},
{{{112, 338, 10},0, {0, 256},{0xF0, 0x9F, 0x51, 0xFE}}},
{{{112, 338, -19},0, {0, 256},{0xEB, 0x9D, 0xB3, 0xFE}}},
{{{2, 432, -16},0, {0, 256},{0xFE, 0xF7, 0x81, 0xFE}}},
{{{10, 486, -11},0, {0, 256},{0x2, 0x7F, 0xF6, 0xFE}}},
{{{-265, 630, -11},0, {0, 256},{0xEB, 0x7D, 0x0, 0xFE}}},
{{{-489, 325, 56},0, {0, 256},{0x2, 0x4, 0x7F, 0xFE}}},
{{{2, 432, 12},0, {0, 256},{0x2, 0x3, 0x7F, 0xFE}}},
{{{-489, 229, 23},0, {0, 256},{0x1C, 0xAC, 0x5B, 0xFE}}},
{{{504, 312, 56},0, {0, 256},{0xFD, 0x0, 0x7F, 0xFE}}},
{{{504, 216, 22},0, {0, 256},{0xD8, 0x8D, 0x23, 0xFE}}},
{{{542, 221, -36},0, {0, 256},{0xE1, 0xB0, 0xA2, 0xFE}}},
{{{503, 312, -78},0, {0, 256},{0xF9, 0xF7, 0x82, 0xFE}}},
{{{289, 623, -11},0, {0, 256},{0x17, 0x7D, 0x0, 0xFE}}},
};
Gfx gSWLinkAdultFairyBowFPDL_gSWLinkAdultFairyBowFPDL_mesh_layer_Opaque_tri_0[] = {
gsSPVertex(gSWLinkAdultFairyBowFPDL_gSWLinkAdultFairyBowFPDL_mesh_layer_Opaque_vtx_0 + 0, 17, 0),
gsSP2Triangles(0, 1, 2, 0, 3, 1, 0, 0),
gsSP2Triangles(4, 3, 0, 0, 4, 0, 5, 0),
gsSP2Triangles(5, 0, 6, 0, 0, 2, 6, 0),
gsSP2Triangles(6, 2, 7, 0, 8, 7, 2, 0),
gsSP2Triangles(8, 9, 7, 0, 7, 9, 10, 0),
gsSP2Triangles(10, 9, 11, 0, 10, 11, 3, 0),
gsSP2Triangles(3, 11, 1, 0, 10, 3, 4, 0),
gsSP2Triangles(4, 12, 10, 0, 4, 13, 12, 0),
gsSP2Triangles(5, 13, 4, 0, 5, 14, 13, 0),
gsSP2Triangles(6, 14, 5, 0, 6, 15, 14, 0),
gsSP2Triangles(7, 15, 6, 0, 7, 16, 15, 0),
gsSP2Triangles(12, 16, 7, 0, 10, 12, 7, 0),
gsSPEndDisplayList(),
};
Vtx gSWLinkAdultFairyBowFPDL_gSWLinkAdultFairyBowFPDL_mesh_layer_Opaque_vtx_1[10] = {
{{{2010, -309, -11},0, {0, 256},{0x6E, 0xC1, 0x0, 0xFE}}},
{{{1535, -363, 45},0, {0, 256},{0x7, 0xFD, 0x7F, 0xFE}}},
{{{1535, -439, -11},0, {0, 256},{0xD4, 0x89, 0x0, 0xFE}}},
{{{1463, -249, -11},0, {0, 256},{0x34, 0x74, 0x0, 0xFE}}},
{{{1535, -363, -67},0, {0, 256},{0x6, 0xFD, 0x81, 0xFE}}},
{{{-2009, -258, -9},0, {0, 256},{0xA6, 0xAC, 0x1F, 0xFE}}},
{{{-1537, -324, -65},0, {0, 256},{0xFD, 0xEB, 0x83, 0xFE}}},
{{{-1561, -376, 3},0, {0, 256},{0x28, 0x88, 0x9, 0xFE}}},
{{{-1460, -212, -9},0, {0, 256},{0xCF, 0x75, 0x0, 0xFE}}},
{{{-1537, -324, 47},0, {0, 256},{0xFC, 0xF8, 0x7F, 0xFE}}},
};
Gfx gSWLinkAdultFairyBowFPDL_gSWLinkAdultFairyBowFPDL_mesh_layer_Opaque_tri_1[] = {
gsSPVertex(gSWLinkAdultFairyBowFPDL_gSWLinkAdultFairyBowFPDL_mesh_layer_Opaque_vtx_1 + 0, 10, 0),
gsSP2Triangles(0, 1, 2, 0, 1, 0, 3, 0),
gsSP2Triangles(0, 4, 3, 0, 2, 4, 0, 0),
gsSP2Triangles(5, 6, 7, 0, 6, 5, 8, 0),
gsSP2Triangles(5, 9, 8, 0, 7, 9, 5, 0),
gsSPEndDisplayList(),
};
Vtx gSWLinkAdultFairyBowFPDL_gSWLinkAdultFairyBowFPDL_mesh_layer_Opaque_vtx_2[24] = {
{{{-911, 86, 15},0, {142, 145},{0x1F, 0xB7, 0x63, 0xFE}}},
{{{-1537, -324, 47},0, {38, 99},{0xFC, 0xF8, 0x7F, 0xFE}}},
{{{-1561, -376, 3},0, {35, 83},{0x28, 0x88, 0x9, 0xFE}}},
{{{-1460, -212, -9},0, {49, 129},{0xCF, 0x75, 0x0, 0xFE}}},
{{{-1248, 140, -10},0, {79, 228},{0xA9, 0x5D, 0x0, 0xFE}}},
{{{-489, 325, 56},0, {213, 162},{0x2, 0x4, 0x7F, 0xFE}}},
{{{-489, 229, 23},0, {215, 124},{0x1C, 0xAC, 0x5B, 0xFE}}},
{{{-489, 229, -44},0, {215, 124},{0x24, 0x90, 0xD1, 0xFE}}},
{{{-911, 85, -35},0, {142, 145},{0x1A, 0xC3, 0x94, 0xFE}}},
{{{-1537, -324, -65},0, {38, 99},{0xFD, 0xEB, 0x83, 0xFE}}},
{{{-489, 325, -77},0, {213, 162},{0x6, 0xFB, 0x81, 0xFE}}},
{{{-265, 630, -11},0, {246, 241},{0xEB, 0x7D, 0x0, 0xFE}}},
{{{504, 312, 56},0, {-14, 182},{0xFD, 0x0, 0x7F, 0xFE}}},
{{{1260, 108, -11},0, {157, 69},{0x59, 0x5B, 0x0, 0xFE}}},
{{{289, 623, -11},0, {-80, 126},{0x17, 0x7D, 0x0, 0xFE}}},
{{{922, 62, 14},0, {90, 167},{0xE7, 0xCD, 0x72, 0xFE}}},
{{{504, 216, 22},0, {-7, 215},{0xD8, 0x8D, 0x23, 0xFE}}},
{{{922, 62, -36},0, {90, 167},{0xE0, 0xBD, 0x99, 0xFE}}},
{{{542, 221, -36},0, {0, 204},{0xE1, 0xB0, 0xA2, 0xFE}}},
{{{503, 312, -78},0, {-14, 182},{0xF9, 0xF7, 0x82, 0xFE}}},
{{{1463, -249, -11},0, {224, 143},{0x34, 0x74, 0x0, 0xFE}}},
{{{1535, -363, 45},0, {247, 165},{0x7, 0xFD, 0x7F, 0xFE}}},
{{{1535, -439, -11},0, {252, 192},{0xD4, 0x89, 0x0, 0xFE}}},
{{{1535, -363, -67},0, {247, 165},{0x6, 0xFD, 0x81, 0xFE}}},
};
Gfx gSWLinkAdultFairyBowFPDL_gSWLinkAdultFairyBowFPDL_mesh_layer_Opaque_tri_2[] = {
gsSPVertex(gSWLinkAdultFairyBowFPDL_gSWLinkAdultFairyBowFPDL_mesh_layer_Opaque_vtx_2 + 0, 24, 0),
gsSP2Triangles(0, 1, 2, 0, 0, 3, 1, 0),
gsSP2Triangles(0, 4, 3, 0, 5, 4, 0, 0),
gsSP2Triangles(6, 5, 0, 0, 0, 7, 6, 0),
gsSP2Triangles(0, 8, 7, 0, 8, 0, 2, 0),
gsSP2Triangles(2, 9, 8, 0, 9, 3, 8, 0),
gsSP2Triangles(8, 3, 4, 0, 8, 4, 10, 0),
gsSP2Triangles(11, 10, 4, 0, 5, 11, 4, 0),
gsSP2Triangles(8, 10, 7, 0, 12, 13, 14, 0),
gsSP2Triangles(12, 15, 13, 0, 15, 12, 16, 0),
gsSP2Triangles(16, 17, 15, 0, 16, 18, 17, 0),
gsSP2Triangles(18, 19, 17, 0, 19, 13, 17, 0),
gsSP2Triangles(19, 14, 13, 0, 17, 13, 20, 0),
gsSP2Triangles(20, 13, 15, 0, 15, 21, 20, 0),
gsSP2Triangles(22, 21, 15, 0, 15, 17, 22, 0),
gsSP2Triangles(17, 23, 22, 0, 20, 23, 17, 0),
gsSPEndDisplayList(),
};
Gfx mat_gSWLinkAdultFairyBowFPDL_BowWoodBlue_layerOpaque[] = {
gsDPPipeSync(),
gsDPSetCombineLERP(TEXEL0, 0, SHADE, 0, 0, 0, 0, 1, COMBINED, 0, PRIMITIVE, 0, 0, 0, 0, COMBINED),
gsSPSetGeometryMode(G_ZBUFFER | G_SHADE | G_CULL_BACK | G_FOG | G_LIGHTING | G_SHADING_SMOOTH),
gsSPClearGeometryMode(G_CULL_FRONT | G_TEXTURE_GEN | G_TEXTURE_GEN_LINEAR),
gsSPSetOtherMode(G_SETOTHERMODE_H, 4, 20, G_AD_NOISE | G_CD_MAGICSQ | G_CK_NONE | G_TC_FILT | G_TF_BILERP | G_TL_TILE | G_TD_CLAMP | G_TP_PERSP | G_CYC_2CYCLE | G_PM_NPRIMITIVE),
gsSPSetOtherMode(G_SETOTHERMODE_L, 0, 32, G_AC_NONE | G_ZS_PIXEL | G_RM_FOG_SHADE_A | G_RM_AA_ZB_OPA_SURF2),
gsSPTexture(65535, 65535, 0, 0, 1),
gsDPSetTextureLUT(G_TT_NONE),
gsDPTileSync(),
gsDPSetTextureImage(G_IM_FMT_I, G_IM_SIZ_8b_LOAD_BLOCK, 1, gSWLinkAdultFairyBowFPDL_bow_i8_png_i8),
gsDPSetTile(G_IM_FMT_I, G_IM_SIZ_8b_LOAD_BLOCK, 0, 0, 7, 0, G_TX_WRAP | G_TX_NOMIRROR, 3, 0, G_TX_WRAP | G_TX_NOMIRROR, 3, 0),
gsDPLoadSync(),
gsDPLoadBlock(7, 0, 0, 31, 2048),
gsDPPipeSync(),
gsDPSetTile(G_IM_FMT_I, G_IM_SIZ_8b, 1, 0, 0, 0, G_TX_WRAP | G_TX_NOMIRROR, 3, 0, G_TX_WRAP | G_TX_NOMIRROR, 3, 0),
gsDPSetTileSize(0, 0, 0, 28, 28),
gsDPSetPrimColor(0, 0, 68, 68, 254, 255),
gsSPDisplayList(0xC000000),
gsSPEndDisplayList(),
};
Gfx mat_gSWLinkAdultFairyBowFPDL_BowWoodRed_layerOpaque[] = {
gsDPPipeSync(),
gsDPSetCombineLERP(TEXEL0, 0, SHADE, 0, 0, 0, 0, 1, COMBINED, 0, PRIMITIVE, 0, 0, 0, 0, COMBINED),
gsSPSetGeometryMode(G_ZBUFFER | G_SHADE | G_CULL_BACK | G_FOG | G_LIGHTING | G_SHADING_SMOOTH),
gsSPClearGeometryMode(G_CULL_FRONT | G_TEXTURE_GEN | G_TEXTURE_GEN_LINEAR),
gsSPSetOtherMode(G_SETOTHERMODE_H, 4, 20, G_AD_NOISE | G_CD_MAGICSQ | G_CK_NONE | G_TC_FILT | G_TF_BILERP | G_TL_TILE | G_TD_CLAMP | G_TP_PERSP | G_CYC_2CYCLE | G_PM_NPRIMITIVE),
gsSPSetOtherMode(G_SETOTHERMODE_L, 0, 32, G_AC_NONE | G_ZS_PIXEL | G_RM_FOG_SHADE_A | G_RM_AA_ZB_OPA_SURF2),
gsSPTexture(65535, 65535, 0, 0, 1),
gsDPSetTextureLUT(G_TT_NONE),
gsDPTileSync(),
gsDPSetTextureImage(G_IM_FMT_I, G_IM_SIZ_8b_LOAD_BLOCK, 1, gSWLinkAdultFairyBowFPDL_bow_i8_png_i8),
gsDPSetTile(G_IM_FMT_I, G_IM_SIZ_8b_LOAD_BLOCK, 0, 0, 7, 0, G_TX_WRAP | G_TX_NOMIRROR, 3, 0, G_TX_WRAP | G_TX_NOMIRROR, 3, 0),
gsDPLoadSync(),
gsDPLoadBlock(7, 0, 0, 31, 2048),
gsDPPipeSync(),
gsDPSetTile(G_IM_FMT_I, G_IM_SIZ_8b, 1, 0, 0, 0, G_TX_WRAP | G_TX_NOMIRROR, 3, 0, G_TX_WRAP | G_TX_NOMIRROR, 3, 0),
gsDPSetTileSize(0, 0, 0, 28, 28),
gsDPSetPrimColor(0, 0, 160, 0, 0, 255),
gsSPEndDisplayList(),
};
Gfx mat_gSWLinkAdultFairyBowFPDL_BowWood_layerOpaque[] = {
gsDPPipeSync(),
gsDPSetCombineLERP(TEXEL0, 0, SHADE, 0, 0, 0, 0, 1, COMBINED, 0, PRIMITIVE, 0, 0, 0, 0, COMBINED),
gsSPSetGeometryMode(G_ZBUFFER | G_SHADE | G_CULL_BACK | G_FOG | G_LIGHTING | G_SHADING_SMOOTH),
gsSPClearGeometryMode(G_CULL_FRONT | G_TEXTURE_GEN | G_TEXTURE_GEN_LINEAR),
gsSPSetOtherMode(G_SETOTHERMODE_H, 4, 20, G_AD_NOISE | G_CD_MAGICSQ | G_CK_NONE | G_TC_FILT | G_TF_BILERP | G_TL_TILE | G_TD_CLAMP | G_TP_PERSP | G_CYC_2CYCLE | G_PM_NPRIMITIVE),
gsSPSetOtherMode(G_SETOTHERMODE_L, 0, 32, G_AC_NONE | G_ZS_PIXEL | G_RM_FOG_SHADE_A | G_RM_AA_ZB_OPA_SURF2),
gsSPTexture(65535, 65535, 0, 0, 1),
gsDPSetTextureLUT(G_TT_NONE),
gsDPTileSync(),
gsDPSetTextureImage(G_IM_FMT_I, G_IM_SIZ_8b_LOAD_BLOCK, 1, gSWLinkAdultFairyBowFPDL_bow_i8_png_i8),
gsDPSetTile(G_IM_FMT_I, G_IM_SIZ_8b_LOAD_BLOCK, 0, 0, 7, 0, G_TX_WRAP | G_TX_NOMIRROR, 3, 0, G_TX_WRAP | G_TX_NOMIRROR, 3, 0),
gsDPLoadSync(),
gsDPLoadBlock(7, 0, 0, 31, 2048),
gsDPPipeSync(),
gsDPSetTile(G_IM_FMT_I, G_IM_SIZ_8b, 1, 0, 0, 0, G_TX_WRAP | G_TX_NOMIRROR, 3, 0, G_TX_WRAP | G_TX_NOMIRROR, 3, 0),
gsDPSetTileSize(0, 0, 0, 28, 28),
gsDPSetPrimColor(0, 0, 254, 254, 126, 255),
gsSPEndDisplayList(),
};
Gfx gSWLinkAdultFairyBowFPDL[] = {
gsSPClearGeometryMode(G_LIGHTING),
gsSPVertex(gSWLinkAdultFairyBowFPDL_gSWLinkAdultFairyBowFPDL_mesh_layer_Opaque_vtx_cull + 0, 8, 0),
gsSPCullDisplayList(0, 7),
gsSPDisplayList(mat_gSWLinkAdultFairyBowFPDL_BowWoodBlue_layerOpaque),
gsSPDisplayList(gSWLinkAdultFairyBowFPDL_gSWLinkAdultFairyBowFPDL_mesh_layer_Opaque_tri_0),
gsSPDisplayList(mat_gSWLinkAdultFairyBowFPDL_BowWoodRed_layerOpaque),
gsSPDisplayList(gSWLinkAdultFairyBowFPDL_gSWLinkAdultFairyBowFPDL_mesh_layer_Opaque_tri_1),
gsSPDisplayList(mat_gSWLinkAdultFairyBowFPDL_BowWood_layerOpaque),
gsSPDisplayList(gSWLinkAdultFairyBowFPDL_gSWLinkAdultFairyBowFPDL_mesh_layer_Opaque_tri_2),
gsSPEndDisplayList(),
};
|
a02b85d6aca24800a6847c07851cb96eb6152ef6
|
e1cddfd754d952134e72dfd03522c5ea4fb6008e
|
/src/vnet/adj/adj_nsh.c
|
00d945729d8b5df3e37a2c6940eca7665b8d4614
|
[
"Apache-2.0"
] |
permissive
|
FDio/vpp
|
0ad30fa1bec2975ffa6b66b45c9f4f32163123b6
|
f234b0d4626d7e686422cc9dfd25958584f4931e
|
refs/heads/master
| 2023-08-31T16:09:04.068646
| 2022-03-14T09:49:15
| 2023-08-31T09:50:00
| 96,556,718
| 1,048
| 630
|
Apache-2.0
| 2023-06-21T05:39:17
| 2017-07-07T16:29:40
|
C
|
UTF-8
|
C
| false
| false
| 6,623
|
c
|
adj_nsh.c
|
/*
* Copyright (c) 2017 Cisco and/or its affiliates.
* 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 <vnet/vnet.h>
#include <vnet/adj/adj_nsh.h>
#include <vnet/ip/ip.h>
#ifndef CLIB_MARCH_VARIANT
nsh_main_placeholder_t nsh_main_placeholder;
#endif /* CLIB_MARCH_VARIANT */
/**
* @brief Trace data for a NSH Midchain
*/
typedef struct adj_nsh_trace_t_ {
/** Adjacency index taken. */
u32 adj_index;
} adj_nsh_trace_t;
static u8 *
format_adj_nsh_trace (u8 * s, va_list * args)
{
CLIB_UNUSED (vlib_main_t * vm) = va_arg (*args, vlib_main_t *);
CLIB_UNUSED (vlib_node_t * node) = va_arg (*args, vlib_node_t *);
adj_nsh_trace_t * t = va_arg (*args, adj_nsh_trace_t *);
s = format (s, "adj-idx %d : %U",
t->adj_index,
format_ip_adjacency, t->adj_index, FORMAT_IP_ADJACENCY_NONE);
return s;
}
typedef enum adj_nsh_rewrite_next_t_
{
ADJ_NSH_REWRITE_NEXT_DROP,
} adj_gpe_rewrite_next_t;
always_inline uword
adj_nsh_rewrite_inline (vlib_main_t * vm,
vlib_node_runtime_t * node,
vlib_frame_t * frame,
int is_midchain)
{
u32 * from = vlib_frame_vector_args (frame);
u32 n_left_from, n_left_to_next, * to_next, next_index;
u32 thread_index = vlib_get_thread_index();
n_left_from = frame->n_vectors;
next_index = node->cached_next_index;
while (n_left_from > 0)
{
vlib_get_next_frame (vm, node, next_index, to_next, n_left_to_next);
while (n_left_from > 0 && n_left_to_next > 0)
{
ip_adjacency_t * adj0;
vlib_buffer_t * p0;
char *h0;
u32 pi0, rw_len0, adj_index0, next0 = 0;
u32 tx_sw_if_index0;
pi0 = to_next[0] = from[0];
from += 1;
n_left_from -= 1;
to_next += 1;
n_left_to_next -= 1;
p0 = vlib_get_buffer (vm, pi0);
h0 = vlib_buffer_get_current (p0);
adj_index0 = vnet_buffer (p0)->ip.adj_index[VLIB_TX];
/* We should never rewrite a pkt using the MISS adjacency */
ASSERT(adj_index0);
adj0 = adj_get (adj_index0);
/* Guess we are only writing on simple IP4 header. */
vnet_rewrite_one_header(adj0[0], h0, sizeof(ip4_header_t));
/* Update packet buffer attributes/set output interface. */
rw_len0 = adj0[0].rewrite_header.data_bytes;
vnet_buffer(p0)->ip.save_rewrite_length = rw_len0;
vlib_increment_combined_counter(&adjacency_counters,
thread_index,
adj_index0,
/* packet increment */ 0,
/* byte increment */ rw_len0);
/* Check MTU of outgoing interface. */
if (PREDICT_TRUE((vlib_buffer_length_in_chain (vm, p0) <=
adj0[0].rewrite_header.max_l3_packet_bytes)))
{
/* Don't adjust the buffer for ttl issue; icmp-error node wants
* to see the IP header */
p0->current_data -= rw_len0;
p0->current_length += rw_len0;
tx_sw_if_index0 = adj0[0].rewrite_header.sw_if_index;
if (is_midchain)
{
adj0->sub_type.midchain.fixup_func(
vm, adj0, p0,
adj0->sub_type.midchain.fixup_data);
}
vnet_buffer (p0)->sw_if_index[VLIB_TX] = tx_sw_if_index0;
/*
* Follow the feature ARC. this will result eventually in
* the midchain-tx node
*/
vnet_feature_arc_start (nsh_main_placeholder.output_feature_arc_index,
tx_sw_if_index0, &next0, p0);
}
else
{
/* can't fragment NSH */
next0 = ADJ_NSH_REWRITE_NEXT_DROP;
}
if (PREDICT_FALSE(p0->flags & VLIB_BUFFER_IS_TRACED))
{
adj_nsh_trace_t *tr = vlib_add_trace (vm, node,
p0, sizeof (*tr));
tr->adj_index = vnet_buffer(p0)->ip.adj_index[VLIB_TX];
}
vlib_validate_buffer_enqueue_x1 (vm, node, next_index,
to_next, n_left_to_next,
pi0, next0);
}
vlib_put_next_frame (vm, node, next_index, n_left_to_next);
}
return frame->n_vectors;
}
VLIB_NODE_FN (adj_nsh_rewrite_node) (vlib_main_t * vm,
vlib_node_runtime_t * node,
vlib_frame_t * frame)
{
return adj_nsh_rewrite_inline (vm, node, frame, 0);
}
VLIB_NODE_FN (adj_nsh_midchain_node) (vlib_main_t * vm,
vlib_node_runtime_t * node,
vlib_frame_t * frame)
{
return adj_nsh_rewrite_inline (vm, node, frame, 1);
}
VLIB_REGISTER_NODE (adj_nsh_rewrite_node) = {
.name = "adj-nsh-rewrite",
.vector_size = sizeof (u32),
.format_trace = format_adj_nsh_trace,
.n_next_nodes = 1,
.next_nodes = {
[ADJ_NSH_REWRITE_NEXT_DROP] = "error-drop",
},
};
VLIB_REGISTER_NODE (adj_nsh_midchain_node) = {
.name = "adj-nsh-midchain",
.vector_size = sizeof (u32),
.format_trace = format_adj_nsh_trace,
.n_next_nodes = 1,
.next_nodes = {
[ADJ_NSH_REWRITE_NEXT_DROP] = "error-drop",
},
};
/* Built-in ip4 tx feature path definition */
/* *INDENT-OFF* */
VNET_FEATURE_ARC_INIT (nsh_output, static) =
{
.arc_name = "nsh-output",
.start_nodes = VNET_FEATURES ("adj-nsh-midchain"),
.arc_index_ptr = &nsh_main_placeholder.output_feature_arc_index,
};
VNET_FEATURE_INIT (nsh_tx_drop, static) =
{
.arc_name = "nsh-output",
.node_name = "error-drop",
.runs_before = 0, /* not before any other features */
};
/* *INDENT-ON* */
|
6a7dba95ce6d6ad08449c7942f2391c7831542c5
|
b8cc7f50628eb2f6b4fdbd66eae5a1aa502cc309
|
/src/Edit.h
|
abf5342391ed7a9de5089d3f38c0ab688ba97064
|
[
"BSD-3-Clause",
"LicenseRef-scancode-scintilla",
"MIT",
"BSD-2-Clause",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
zufuliu/notepad2
|
ad82f2baaf60cd9efcbf3af57d2e2f381f961f0b
|
6296f4a8567d2c22690be0cafcdf91a0fea60cc7
|
refs/heads/main
| 2023-08-29T03:45:42.292846
| 2023-08-28T10:33:46
| 2023-08-28T10:33:46
| 79,987,996
| 2,154
| 227
|
NOASSERTION
| 2023-08-11T23:59:02
| 2017-01-25T06:07:49
|
C++
|
UTF-8
|
C
| false
| false
| 21,723
|
h
|
Edit.h
|
/******************************************************************************
*
*
* Notepad2
*
* Edit.h
* Text File Editing Helper Stuff
*
* See Readme.txt for more information about this source code.
* Please send me your comments to this work.
*
* See License.txt for details about distribution and modification.
*
* (c) Florian Balmer 1996-2011
* florian.balmer@gmail.com
* https://www.flos-freeware.ch
*
*
******************************************************************************/
#pragma once
// WideCharToMultiByte, UTF8 encoding of U+0800 to U+FFFF
#define kMaxMultiByteCount 3
#define NP2_FIND_REPLACE_LIMIT 2048
#define NP2_LONG_LINE_LIMIT 4096
#define NP2_InvalidSearchFlags (-1)
#define NP2_MarkAllMultiline 0x00001000
#define NP2_MarkAllBookmark 0x00002000
#define NP2_MarkAllSelectAll 0x00004000
#define NP2_FromFindAll 0x00008000
typedef struct EDITFINDREPLACE {
char szFind[512];
char szReplace[512];
char szFindUTF8[512 * kMaxMultiByteCount];
char szReplaceUTF8[512 * kMaxMultiByteCount];
HWND hwnd;
UINT fuFlags;
bool bTransformBS;
bool bFindClose;
bool bReplaceClose;
bool bNoFindWrap;
bool bWildcardSearch;
} EDITFINDREPLACE, *LPEDITFINDREPLACE;
typedef const EDITFINDREPLACE * LPCEDITFINDREPLACE;
typedef enum EditAlignMode {
EditAlignMode_Left = 0,
EditAlignMode_Right = 1,
EditAlignMode_Center = 2,
EditAlignMode_Justify = 3,
EditAlignMode_JustifyEx = 4,
} EditAlignMode;
typedef enum EditSortFlag {
EditSortFlag_Ascending = 0,
EditSortFlag_Descending = 1,
EditSortFlag_IgnoreCase = 2,
EditSortFlag_LogicalNumber = 4,
EditSortFlag_ColumnSort = 8,
EditSortFlag_GroupByFileType = 16,
EditSortFlag_DontSort = 32,
EditSortFlag_Shuffle = 64,
EditSortFlag_MergeDuplicate = 128,
EditSortFlag_RemoveDuplicate = 256,
EditSortFlag_RemoveUnique = 512,
} EditSortFlag;
// wrap indent
enum {
EditWrapIndent_None = 0,
EditWrapIndent_OneCharacter = 1,
EditWrapIndent_TwoCharacter = 2,
EditWrapIndent_OneLevel = 3,
EditWrapIndent_TwoLevel = 4,
EditWrapIndent_SameAsSubline = 5,
EditWrapIndent_OneLevelThanSubline = 6,
EditWrapIndent_TwoLevelThanSubline = 7,
EditWrapIndent_MaxValue = EditWrapIndent_TwoLevelThanSubline,
EditWrapIndent_DefaultValue = EditWrapIndent_None,
};
// wrap symbol
enum {
EditWrapSymbolBefore_None = 0,
EditWrapSymbolBefore_NearText = 1,
EditWrapSymbolBefore_NearBorder = 2,
EditWrapSymbolBefore_MaxValue = EditWrapSymbolBefore_NearBorder,
EditWrapSymbolAfter_None = 0,
EditWrapSymbolAfter_NearText = 1,
EditWrapSymbolAfter_NearBorder = 2,
EditWrapSymbolAfter_LineNumberMargin = 3,
EditWrapSymbolAfter_MaxValue = EditWrapSymbolAfter_LineNumberMargin,
EditWrapSymbol_MaxValue = EditWrapSymbolBefore_MaxValue + 10 * EditWrapSymbolAfter_MaxValue,
EditWrapSymbol_DefaultValue = EditWrapSymbolBefore_NearBorder,
};
void Edit_ReleaseResources(void);
void EditCreate(HWND hwndParent);
void EditSetNewText(LPCSTR lpstrText, DWORD cbText, Sci_Line lineCount);
static inline void EditSetEmptyText(void) {
EditSetNewText("", 0, 1);
}
bool EditConvertText(UINT cpSource, UINT cpDest, bool bSetSavePoint);
void EditConvertToLargeMode(void);
void EditReplaceDocument(HANDLE pdoc);
char* EditGetClipboardText(HWND hwnd); // LocalFree()
bool EditCopyAppend(HWND hwnd);
static inline int GetScintillaEOLMode(int mode) {
const UINT mask = (SC_EOL_CRLF << 2*0) | (SC_EOL_LF << 2*1) | (SC_EOL_CR << 2*2);
return (mask >> (mode << 1)) & 3;
}
static inline int GetSettingsEOLMode(int mode) {
const UINT mask = (0 << 2*SC_EOL_CRLF) | (1 << 2*SC_EOL_LF) | (2 << 2*SC_EOL_CR);
return (mask >> (mode << 1)) & 3;
}
struct EditFileIOStatus;
void EditDetectEOLMode(LPCSTR lpData, DWORD cbData, struct EditFileIOStatus *status);
bool EditLoadFile(LPWSTR pszFile, struct EditFileIOStatus *status);
bool EditSaveFile(HWND hwnd, LPCWSTR pszFile, int saveFlag, struct EditFileIOStatus *status);
void EditInvertCase(void);
void EditMapTextCase(int menu);
void EditSentenceCase(void);
void EditURLEncode(void);
void EditURLDecode(void);
void EditEscapeCChars(HWND hwnd);
void EditUnescapeCChars(HWND hwnd);
void EditEscapeXHTMLChars(HWND hwnd);
void EditUnescapeXHTMLChars(HWND hwnd);
void EditChar2Hex(void);
void EditHex2Char(void);
void EditShowHex(void);
typedef enum Base64EncodingFlag {
Base64EncodingFlag_Default,
Base64EncodingFlag_UrlSafe,
Base64EncodingFlag_HtmlEmbeddedImage,
} Base64EncodingFlag;
void EditBase64Encode(Base64EncodingFlag encodingFlag);
void EditBase64Decode(bool decodeAsHex);
void EditConvertNumRadix(int radix);
void EditModifyNumber(bool bIncrease);
void EditTabsToSpaces(int nTabWidth, bool bOnlyIndentingWS);
void EditSpacesToTabs(int nTabWidth, bool bOnlyIndentingWS);
void EditMoveUp(void);
void EditMoveDown(void);
void EditModifyLines(LPCWSTR pwszPrefix, LPCWSTR pwszAppend, bool skipEmptyLine);
void EditAlignText(EditAlignMode nMode);
void EditEncloseSelection(LPCWSTR pwszOpen, LPCWSTR pwszClose);
void EditToggleLineComments(LPCWSTR pwszComment, bool bInsertAtStart);
void EditPadWithSpaces(bool bSkipEmpty, bool bNoUndoGroup);
void EditStripFirstCharacter(void);
void EditStripLastCharacter(void);
void EditStripTrailingBlanks(HWND hwnd, bool bIgnoreSelection);
void EditStripLeadingBlanks(HWND hwnd, bool bIgnoreSelection);
void EditCompressSpaces(void);
void EditRemoveBlankLines(bool bMerge);
void EditWrapToColumn(int nColumn/*, int nTabWidth*/);
void EditJoinLinesEx(void);
void EditSortLines(EditSortFlag iSortFlags);
void EditJumpTo(Sci_Line iNewLine, Sci_Position iNewCol);
void EditSelectEx(Sci_Position iAnchorPos, Sci_Position iCurrentPos);
void EditFixPositions(void);
void EditEnsureSelectionVisible(void);
void EditEnsureConsistentLineEndings(void);
void EditGetExcerpt(LPWSTR lpszExcerpt, DWORD cchExcerpt);
void EditSelectWord(void);
void EditSelectLines(bool currentBlock, bool lineSelection);
HWND EditFindReplaceDlg(HWND hwnd, LPEDITFINDREPLACE lpefr, bool bReplace);
void EditFindNext(LPCEDITFINDREPLACE lpefr, bool fExtendSelection);
void EditFindPrev(LPCEDITFINDREPLACE lpefr, bool fExtendSelection);
void EditFindAll(LPCEDITFINDREPLACE lpefr, bool selectAll);
bool EditReplace(HWND hwnd, LPCEDITFINDREPLACE lpefr);
bool EditReplaceAll(HWND hwnd, LPCEDITFINDREPLACE lpefr, bool bShowInfo);
bool EditReplaceAllInSelection(HWND hwnd, LPCEDITFINDREPLACE lpefr, bool bShowInfo);
bool EditLineNumDlg(HWND hwnd);
void EditModifyLinesDlg(HWND hwnd);
void EditEncloseSelectionDlg(HWND hwnd);
void EditInsertTagDlg(HWND hwnd);
void EditInsertDateTime(bool bShort);
void EditUpdateTimestampMatchTemplate(HWND hwnd);
void EditInsertUnicodeControlCharacter(int menu);
void EditShowUnicodeControlCharacter(bool bShow);
bool EditSortDlg(HWND hwnd, EditSortFlag *piSortFlags);
bool EditAlignDlg(HWND hwnd, EditAlignMode *piAlignMode);
void EditSelectionAction(int action);
void TryBrowseFile(HWND hwnd, LPCWSTR pszFile, bool bWarn);
typedef enum OpenSelectionType {
OpenSelectionType_None,
OpenSelectionType_Link,
OpenSelectionType_File,
OpenSelectionType_Folder,
OpenSelectionType_ContainingFolder,
} OpenSelectionType;
void EditOpenSelection(OpenSelectionType type);
// in Bridge.cpp
#ifdef __cplusplus
extern "C" {
#endif
bool EditPrint(HWND hwnd, LPCWSTR pszDocTitle);
void EditPrintSetup(HWND hwnd);
void EditCopyAsRTF(HWND hwnd);
#ifdef __cplusplus
}
#endif
enum {
MarkerNumber_Bookmark = 0,
// [0, INDICATOR_CONTAINER) are reserved for lexer.
IndicatorNumber_MarkOccurrence = INDICATOR_CONTAINER + 0,
IndicatorNumber_MatchBrace = INDICATOR_CONTAINER + 1,
IndicatorNumber_MatchBraceError = INDICATOR_CONTAINER + 2,
// [INDICATOR_IME, INDICATOR_IME_MAX] are reserved for IME.
MarginNumber_LineNumber = 0,
MarginNumber_Bookmark = 1,
MarginNumber_CodeFolding = 2,
MarkerBitmask_Bookmark = 1 << MarkerNumber_Bookmark,
};
typedef struct EditMarkAllStatus {
bool pending;
bool ignoreSelectionUpdate;
bool bookmarkForFindAll;
int findFlag;
int incrementSize; // increment search size
Sci_Position iSelCount; // length for pszText
LPSTR pszText; // pattern or text to find
double duration; // search duration in milliseconds
Sci_Position matchCount; // total match count
Sci_Position lastMatchPos; // last matching position
Sci_Position iStartPos; // previous stop position
Sci_Line bookmarkLine; // previous bookmark line
StopWatch watch; // used to dynamic compute increment size
} EditMarkAllStatus;
void EditMarkAll_ClearEx(int findFlag, Sci_Position iSelCount, LPSTR pszText);
NP2_inline void EditMarkAll_Clear(void) {
EditMarkAll_ClearEx(0, 0, NULL);
}
void EditMarkAll_Start(BOOL bChanged, int findFlag, Sci_Position iSelCount, LPSTR pszText);
void EditMarkAll_Continue(EditMarkAllStatus *status, HANDLE timer);
void EditMarkAll(BOOL bChanged, bool matchCase, bool wholeWord, bool bookmark);
void EditToggleBookmarkAt(Sci_Position iPos);
void EditBookmarkSelectAll(void);
// auto completion fill-up characters
#define MAX_AUTO_COMPLETION_FILLUP_LENGTH 32 // Only 32 ASCII punctuation
#define AUTO_COMPLETION_FILLUP_DEFAULT L";,()[]{}\\/"
// timeout for scanning words in document
#define AUTOC_SCAN_WORDS_MIN_TIMEOUT 50
#define AUTOC_SCAN_WORDS_DEFAULT_TIMEOUT 500
enum {
AutoCompleteScope_None = 0,
AutoCompleteScope_Commont = 1,
AutoCompleteScope_String = 2,
AutoCompleteScope_PlainText = 4,
AutoCompleteScope_Other = 8,
AutoCompleteScope_Default = 0xff,
};
enum {
AutoCompleteFillUpMask_Enter = 1,
AutoCompleteFillUpMask_Tab = 2,
AutoCompleteFillUpMask_Space = 4,
AutoCompleteFillUpMask_Punctuation = 8,
// default settings
AutoCompleteFillUpMask_Default = 15,
};
// auto insert
typedef enum AutoInsertCharacter {
AutoInsertCharacter_Parenthesis,
AutoInsertCharacter_Brace,
AutoInsertCharacter_SquareBracket,
AutoInsertCharacter_AngleBracket,
AutoInsertCharacter_DoubleQuote,
AutoInsertCharacter_SingleQuote,
AutoInsertCharacter_Backtick,
AutoInsertCharacter_Comma,
} AutoInsertCharacter;
enum {
AutoInsertMask_Parenthesis = 1, // ()
AutoInsertMask_Brace = 2, // {}
AutoInsertMask_SquareBracket = 4, // []
AutoInsertMask_AngleBracket = 8, // <>
AutoInsertMask_DoubleQuote = 16, // ""
AutoInsertMask_SingleQuote = 32, // ''
AutoInsertMask_Backtick = 64, // ``
AutoInsertMask_SpaceAfterComma = 128, // ', '
// default settings
AutoInsertMask_Default = 255,
};
// asm line comment
enum {
AsmLineCommentChar_Semicolon = 0, // ';'
AsmLineCommentChar_Sharp = 1, // '#'
AsmLineCommentChar_Slash = 2, // '//'
AsmLineCommentChar_At = 3, // '@'
};
#define MIN_AUTO_COMPLETION_VISIBLE_ITEM_COUNT 8
#define MIN_AUTO_COMPLETION_WORD_LENGTH 1
#define MIN_AUTO_COMPLETION_NUMBER_LENGTH 0
typedef struct EditAutoCompletionConfig {
bool bIndentText;
bool bCloseTags;
bool bCompleteWord;
bool bScanWordsInDocument;
int fCompleteScope;
int fScanWordScope;
UINT dwScanWordsTimeout;
bool bEnglistIMEModeOnly;
bool bIgnoreCase;
bool bLaTeXInputMethod;
UINT iVisibleItemCount;
int iMinWordLength;
int iMinNumberLength;
int fAutoCompleteFillUpMask;
int fAutoInsertMask;
int iAsmLineCommentChar;
UINT iPreviousItemCount; // status
char szAutoCompleteFillUp[MAX_AUTO_COMPLETION_FILLUP_LENGTH + 4];
WCHAR wszAutoCompleteFillUp[MAX_AUTO_COMPLETION_FILLUP_LENGTH];
} EditAutoCompletionConfig;
enum {
AutoCompleteCondition_Normal = 0,
AutoCompleteCondition_OnCharAdded = 1,
AutoCompleteCondition_OnCharDeleted = 2,
};
// in EditAutoC.c
void EditCompleteUpdateConfig(void);
bool IsDocWordChar(uint32_t ch);
bool IsAutoCompletionWordCharacter(uint32_t ch);
void EditCompleteWord(int iCondition, bool autoInsert);
bool EditIsOpenBraceMatched(Sci_Position pos, Sci_Position startPos);
void EditAutoCloseBraceQuote(int ch, AutoInsertCharacter what);
void EditAutoCloseXMLTag(void);
void EditAutoIndent(void);
void EditToggleCommentLine(void);
void EditToggleCommentBlock(void);
void EditInsertScriptShebangLine(void);
typedef enum CallTipType {
CallTipType_None,
CallTipType_Notification,
CallTipType_ColorHex,
} CallTipType;
typedef enum ShowCallTip {
ShowCallTip_None,
ShowCallTip_ColorRGBA,
ShowCallTip_ColorARGB,
ShowCallTip_ColorBGRA,
ShowCallTip_ColorABGR,
} ShowCallTip;
struct CallTipInfo {
ShowCallTip showCallTip;
CallTipType type;
Sci_Position startPos;
Sci_Position endPos;
Sci_Position hexStart;
COLORREF currentColor;
//COLORREF backColor;
//COLORREF foreColor;
};
void EditShowCallTip(Sci_Position position);
void EditClickCallTip(HWND hwnd);
#define NCP_DEFAULT 1
#define NCP_UTF8 2
#define NCP_UTF8_SIGN 4
#define NCP_UNICODE 8
#define NCP_UNICODE_REVERSE 16
#define NCP_UNICODE_BOM 32
#define NCP_8BIT 64
#define NCP_INTERNAL (NCP_DEFAULT | NCP_UTF8 | NCP_UTF8_SIGN | NCP_UNICODE | NCP_UNICODE_REVERSE | NCP_UNICODE_BOM)
#define NCP_RECODE 128
#define NCP_7BIT 256 // encoded in ASCII with escapes: UTF-7, ISO-2022, HZ-GB-2312
#define CPI_NONE (-1)
#define CPI_FIRST 0
#define CPI_DEFAULT 0
#define CPI_OEM 1
#define CPI_UNICODEBOM 2
#define CPI_UNICODEBEBOM 3
#define CPI_UNICODE 4
#define CPI_UNICODEBE 5
#define CPI_UTF8 6
#define CPI_UTF8SIGN 7
#define CPI_UTF7 8
// global default encoding
#define CPI_GLOBAL_DEFAULT CPI_UTF8
#define MAX_ENCODING_LABEL_SIZE 32
// MultiByteToWideChar() and WideCharToMultiByte() uses int as length.
#define MAX_NON_UTF8_SIZE ((1U << 31) - 16)
// added 32 bytes padding as encoding detection may read beyond cbData.
#define NP2_ENCODING_DETECTION_PADDING 32
enum {
EncodingFlag_None = 0,
EncodingFlag_Binary = 1,
EncodingFlag_UTF7 = 2,
EncodingFlag_Reversed = 4,
EncodingFlag_Invalid = 8,
};
typedef struct NP2ENCODING {
const UINT uFlags;
/*const*/UINT uCodePage;
// string format: [normal name + ','] + [lower case parse name + ',']+
const char * const pszParseNames;
const UINT idsName;
LPWSTR wchLabel;
} NP2ENCODING;
// see UniConversion.h and https://www.unicode.org/faq/utf_bom.html
#define SURROGATE_LEAD_FIRST 0xD800
#define SURROGATE_TRAIL_FIRST 0xDC00
#define SUPPLEMENTAL_PLANE_FIRST 0x10000
#define MAX_UNICODE 0x10ffff
#define SURROGATE_OFFSET (0x10000 - (0xD800 << 10) - 0xDC00)
#define UTF16_TO_UTF32(lead, trail) (((lead) << 10) + (trail) + SURROGATE_OFFSET)
// https://docs.microsoft.com/en-us/windows/win32/intl/locale_iuseutf8legacyacp
#ifndef LOCALE_IUSEUTF8LEGACYACP
#define LOCALE_IUSEUTF8LEGACYACP 0x00000666 // NTDDI_VERSION >= NTDDI_WIN10_MN
#endif
// https://docs.microsoft.com/en-us/windows/win32/intl/locale_iuseutf8legacyoemcp
#ifndef LOCALE_IUSEUTF8LEGACYOEMCP
#define LOCALE_IUSEUTF8LEGACYOEMCP 0x00000999 // NTDDI_VERSION >= NTDDI_WIN10_MN
#endif
// https://docs.microsoft.com/en-us/windows/win32/intl/locale-sname
#ifndef LOCALE_SNAME
#define LOCALE_SNAME 0x0000005c // _WIN32_WINNT >= _WIN32_WINNT_VISTA
#endif
static inline BOOL GetLegacyACP(UINT *acp) {
#if _WIN32_WINNT >= _WIN32_WINNT_VISTA
return GetLocaleInfoEx(LOCALE_NAME_SYSTEM_DEFAULT, LOCALE_IUSEUTF8LEGACYACP | LOCALE_RETURN_NUMBER,
(LPWSTR)(acp), sizeof(UINT) / sizeof(WCHAR));
#else
return GetLocaleInfoW(LOCALE_SYSTEM_DEFAULT, LOCALE_IUSEUTF8LEGACYACP | LOCALE_RETURN_NUMBER,
(LPWSTR)(acp), sizeof(UINT) / sizeof(WCHAR));
#endif
}
static inline BOOL GetLegacyOEMCP(UINT *oemcp) {
#if _WIN32_WINNT >= _WIN32_WINNT_VISTA
return GetLocaleInfoEx(LOCALE_NAME_SYSTEM_DEFAULT, LOCALE_IUSEUTF8LEGACYOEMCP | LOCALE_RETURN_NUMBER,
(LPWSTR)(oemcp), sizeof(UINT) / sizeof(WCHAR));
#else
return GetLocaleInfoW(LOCALE_SYSTEM_DEFAULT, LOCALE_IUSEUTF8LEGACYOEMCP | LOCALE_RETURN_NUMBER,
(LPWSTR)(oemcp), sizeof(UINT) / sizeof(WCHAR));
#endif
}
// 932 Shift-JIS, 936 GBK, 949 UHC, 950 Big5, 1361 Johab
static inline bool IsDBCSCodePage(UINT page) {
return page == 932 || page == 936 || page == 949 || page == 950 || page == 1361;
}
// dwFlags must be 0 for MultiByteToWideChar() and WideCharToMultiByte()
static inline bool IsZeroFlagsCodePage(UINT page) {
return page == CP_UTF8
|| page == CP_UTF7
|| page == 54936 // GB18030
|| page == 50220 // ISO-2022-JP
|| page == 50221 // CS ISO-2022-JP
|| page == 50222 // ISO-2022-JP SO/SI
|| page == 50225 // ISO-2022-KR
|| page == 50227 // ISO-2022-CN Simplified
|| page == 50229 // ISO-2022-CN Traditional
//|| (page >= 57002 && page <= 57011) // ISCII
//|| page == 42 // Symbol
;
}
// in EditEncoding.c
extern NP2ENCODING mEncoding[];
static inline bool Encoding_IsUnicode(int iEncoding) {
return iEncoding == CPI_UNICODEBOM
|| iEncoding == CPI_UNICODEBEBOM
|| iEncoding == CPI_UNICODE
|| iEncoding == CPI_UNICODEBE;
}
static inline bool Encoding_IsUTF8(int iEncoding) {
return iEncoding == CPI_UTF8
|| iEncoding == CPI_UTF8SIGN;
}
void Encoding_ReleaseResources(void);
bool EditSetNewEncoding(int iEncoding, int iNewEncoding, BOOL bNoUI, bool bSetSavePoint);
void EditOnCodePageChanged(UINT oldCodePage, bool showControlCharacter, LPEDITFINDREPLACE lpefr);
const char* GetFoldDisplayEllipsis(UINT cpEdit, UINT acp);
void Encoding_InitDefaults(void);
int Encoding_MapIniSetting(bool bLoad, UINT iSetting);
void Encoding_GetLabel(int iEncoding);
int Encoding_Match(LPCWSTR pwszTest);
int Encoding_MatchA(LPCSTR pchTest);
bool Encoding_IsValid(int iEncoding);
int Encoding_GetIndex(UINT codePage);
int Encoding_GetAnsiIndex(void);
void Encoding_AddToTreeView(HWND hwnd, int idSel, bool bRecodeOnly);
bool Encoding_GetFromTreeView(HWND hwnd, int *pidEncoding, bool bQuiet);
#if 0
void Encoding_AddToListView(HWND hwnd, int idSel, bool bRecodeOnly);
bool Encoding_GetFromListView(HWND hwnd, int *pidEncoding);
void Encoding_AddToComboboxEx(HWND hwnd, int idSel, bool bRecodeOnly);
bool Encoding_GetFromComboboxEx(HWND hwnd, int *pidEncoding);
#endif
UINT CodePageFromCharSet(UINT uCharSet);
bool IsUTF8(const char *pTest, DWORD nLength);
bool IsUTF7(const char *pTest, DWORD nLength);
#define BOM_UTF8 0xBFBBEF
#define BOM_UTF16LE 0xFEFF
#define BOM_UTF16BE 0xFFFE
static inline bool IsUTF8Signature(const char *p) {
//return p[0] == '\xEF' && p[1] == '\xBB' && p[2] == '\xBF';
return (*((const UINT *)p) & 0xFFFFFF) == BOM_UTF8;
}
static inline BOOL Encoding_HasBOM(int iEncoding) {
return (iEncoding == CPI_UNICODEBOM
|| iEncoding == CPI_UNICODEBEBOM
|| iEncoding == CPI_UTF8SIGN) ? iEncoding : FALSE;
}
LPSTR RecodeAsUTF8(LPSTR lpData, DWORD *cbData, UINT codePage, DWORD flags);
int EditDetermineEncoding(LPCWSTR pszFile, char *lpData, DWORD cbData, int *encodingFlag);
bool IsStringCaseSensitiveW(LPCWSTR pszTextW);
bool IsStringCaseSensitiveA(LPCSTR pszText);
//void SciInitThemes(HWND hwnd);
#define FV_TABWIDTH 1
#define FV_INDENTWIDTH 2
#define FV_TABSASSPACES 4
#define FV_TABINDENTS 8
#define FV_WORDWRAP 16
#define FV_LONGLINESLIMIT 32
#define FV_ENCODING 64
#define FV_MODE 128
#define FV_MaskHasTabIndentWidth (FV_TABWIDTH | FV_INDENTWIDTH)
#define FV_MaskHasFileTabSettings (FV_TABWIDTH | FV_INDENTWIDTH | FV_TABSASSPACES)
typedef struct EditTabSettings {
int globalTabWidth;
int globalIndentWidth;
bool globalTabsAsSpaces;
bool bTabIndents;
uint8_t bBackspaceUnindents;
bool bDetectIndentation;
int schemeTabWidth;
int schemeIndentWidth;
bool schemeTabsAsSpaces;
bool schemeUseGlobalTabSettings;
} EditTabSettings;
typedef struct FILEVARS {
int mask;
int iTabWidth;
int iIndentWidth;
bool bTabsAsSpaces;
bool bTabIndents;
bool fWordWrap;
int iLongLinesLimit;
int iEncoding;
char tchEncoding[32];
char tchMode[32];
} FILEVARS, *LPFILEVARS;
typedef const FILEVARS * LPCFILEVARS;
extern EditTabSettings tabSettings;
extern FILEVARS fvCurFile;
void EditSetWrapStartIndent(int tabWidth, int indentWidth);
void EditSetWrapIndentMode(int tabWidth, int indentWidth);
void FileVars_Init(LPCSTR lpData, DWORD cbData, LPFILEVARS lpfv);
void FileVars_Apply(LPFILEVARS lpfv);
bool FileVars_ParseInt(LPCSTR pszData, LPCSTR pszName, int *piValue);
bool FileVars_ParseStr(LPCSTR pszData, LPCSTR pszName, char *pszValue, int cchValue);
static inline int FileVars_GetEncoding(LPCFILEVARS lpfv) {
return (lpfv->mask & FV_ENCODING) ? lpfv->iEncoding : CPI_NONE;
}
typedef enum {
FOLD_ACTION_FOLD = SC_FOLDACTION_CONTRACT,
FOLD_ACTION_EXPAND = SC_FOLDACTION_EXPAND,
FOLD_ACTION_SNIFF = SC_FOLDACTION_TOGGLE,
} FOLD_ACTION;
void FoldExpandRange(Sci_Line lineStart, Sci_Line lineEnd);
void FoldToggleAll(FOLD_ACTION action);
void FoldToggleLevel(int lev, FOLD_ACTION action);
void FoldToggleCurrentBlock(FOLD_ACTION action);
void FoldToggleCurrentLevel(FOLD_ACTION action);
void FoldToggleDefault(FOLD_ACTION action);
void FoldClickAt(Sci_Position pos, int mode);
void FoldAltArrow(int key, int mode);
void EditGotoBlock(int menu);
enum SelectOption {
SelectOption_None,
SelectOption_EnableMultipleSelection = 1,
SelectOption_CopySelectionAsFindText = 2,
SelectOption_CopyPasteBufferAsFindText = 4,
SelectOption_Default = 7,
};
enum LineSelectionMode {
LineSelectionMode_None,
LineSelectionMode_VisualStudio,
LineSelectionMode_Normal,
};
|
806c1649d7bef70525e8dcf901dce8d137357a9d
|
28d0f8c01599f8f6c711bdde0b59f9c2cd221203
|
/sys/kern/kern_ctf.c
|
c79cc48af90297081f2157db45d8264696d5496d
|
[] |
no_license
|
NetBSD/src
|
1a9cbc22ed778be638b37869ed4fb5c8dd616166
|
23ee83f7c0aea0777bd89d8ebd7f0cde9880d13c
|
refs/heads/trunk
| 2023-08-31T13:24:58.105962
| 2023-08-27T15:50:47
| 2023-08-27T15:50:47
| 88,439,547
| 656
| 348
| null | 2023-07-20T20:07:24
| 2017-04-16T20:03:43
| null |
UTF-8
|
C
| false
| false
| 5,952
|
c
|
kern_ctf.c
|
/* $NetBSD: kern_ctf.c,v 1.8 2021/04/06 07:57:03 simonb Exp $ */
/*-
* Copyright (c) 2008 John Birrell <jb@freebsd.org>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $FreeBSD: src/sys/kern/kern_ctf.c,v 1.1.4.1 2009/08/03 08:13:06 kensmith Exp $
*/
#define ELFSIZE ARCH_ELFSIZE
#include <sys/proc.h>
#include <sys/module.h>
#include <sys/exec.h>
#include <sys/exec_elf.h>
#include <sys/kmem.h>
#include <sys/malloc.h>
#include <sys/kobj_impl.h>
#include <sys/kobj.h>
#include <sys/kern_ctf.h>
#define _KSYMS_PRIVATE
#include <sys/ksyms.h>
#include <net/zlib.h>
/*
* Note this file is included by both link_elf.c and link_elf_obj.c.
*
* The CTF header structure definition can't be used here because it's
* (annoyingly) covered by the CDDL. We will just use a few bytes from
* it as an integer array where we 'know' what they mean.
*/
#define CTF_HDR_SIZE 36
#define CTF_HDR_STRTAB_U32 7
#define CTF_HDR_STRLEN_U32 8
static void *
z_alloc(void *nil, u_int items, u_int size)
{
void *ptr;
ptr = malloc(items * size, M_TEMP, M_NOWAIT);
return ptr;
}
static void
z_free(void *nil, void *ptr)
{
free(ptr, M_TEMP);
}
int
mod_ctf_get(struct module *mod, mod_ctf_t **mcp)
{
mod_ctf_t *mc;
struct ksyms_symtab *st;
void * ctftab = NULL;
size_t sz;
int error = 0;
int compressed = 0;
void *ctfbuf = NULL;
uint8_t *ctfaddr;
uint16_t ctfmagic;
size_t ctfsize;
/*
* Return the cached mc if there is one already.
*/
extern specificdata_key_t fbt_module_key;
mc = module_getspecific(mod, fbt_module_key);
if (mc != NULL) {
*mcp = mc;
return (0);
}
/*
* Allocate and initialize a new mc.
*/
mc = kmem_zalloc(sizeof(mod_ctf_t), KM_SLEEP);
st = ksyms_get_mod(module_name(mod));
if (st != NULL) {
mc->nmap = st->sd_nmap;
mc->nmapsize = st->sd_nmapsize;
}
if (mod->mod_kobj == NULL) {
/* no kobj entry, try building from ksyms list */
if (st == NULL) {
error = ENOENT;
goto out;
}
ctfaddr = st->sd_ctfstart;
ctfsize = st->sd_ctfsize;
mc->symtab = st->sd_symstart;
mc->strtab = st->sd_strstart;
mc->strcnt = 0; /* XXX TBD */
mc->nsym = st->sd_symsize / sizeof(Elf_Sym);
} else {
if (kobj_find_section(mod->mod_kobj, ".SUNW_ctf", (void **)&ctfaddr, &ctfsize)) {
error = ENOENT;
goto out;
}
mc->symtab = mod->mod_kobj->ko_symtab;
mc->strtab = mod->mod_kobj->ko_strtab;
mc->strcnt = 0; /* XXX TBD */
mc->nsym = mod->mod_kobj->ko_symcnt;
}
if (ctfaddr == NULL) {
error = ENOENT;
goto out;
}
/* Check the CTF magic number. */
memcpy(&ctfmagic, ctfaddr, sizeof ctfmagic);
if (ctfmagic != CTF_MAGIC) {
error = EINVAL;
goto out;
}
/* Check if version 2. */
if (ctfaddr[2] != 2) {
error = EINVAL;
goto out;
}
/* Check if the data is compressed. */
if ((ctfaddr[3] & 0x1) != 0) {
uint32_t *u32 = (uint32_t *) ctfaddr;
/*
* The last two fields in the CTF header are the offset
* from the end of the header to the start of the string
* data and the length of that string data. se this
* information to determine the decompressed CTF data
* buffer required.
*/
sz = u32[CTF_HDR_STRTAB_U32] + u32[CTF_HDR_STRLEN_U32] +
CTF_HDR_SIZE;
compressed = 1;
} else {
/*
* The CTF data is not compressed, so the ELF section
* size is the same as the buffer size required.
*/
sz = ctfsize;
}
/*
* Allocate memory to buffer the CTF data in its decompressed
* form.
*/
if (compressed) {
if ((ctfbuf = malloc(sz, M_TEMP, M_WAITOK)) == NULL) {
error = ENOMEM;
goto out;
}
ctftab = ctfbuf;
mc->ctfalloc = 1;
} else {
ctftab = (void *)ctfaddr;
}
/* Check if decompression is required. */
if (compressed) {
z_stream zs;
int ret;
/*
* The header isn't compressed, so copy that into the
* CTF buffer first.
*/
memcpy(ctftab, ctfaddr, CTF_HDR_SIZE);
/* Initialise the zlib structure. */
memset(&zs, 0, sizeof(zs));
zs.zalloc = z_alloc;
zs.zfree = z_free;
if (inflateInit2(&zs, MAX_WBITS) != Z_OK) {
error = EIO;
goto out;
}
zs.avail_in = ctfsize - CTF_HDR_SIZE;
zs.next_in = ctfaddr + CTF_HDR_SIZE;
zs.avail_out = sz - CTF_HDR_SIZE;
zs.next_out = ((uint8_t *) ctftab) + CTF_HDR_SIZE;
inflateReset(&zs);
if ((ret = inflate(&zs, Z_FINISH)) != Z_STREAM_END) {
printf("%s(%d): zlib inflate returned %d\n", __func__, __LINE__, ret);
error = EIO;
goto out;
}
}
/* Got the CTF data! */
mc->ctfcnt = ctfsize;
mc->ctftab = ctftab;
ctfbuf = NULL;
module_setspecific(mod, fbt_module_key, mc);
*mcp = mc;
mc = NULL;
out:
if (ctfbuf != NULL)
free(ctfbuf, M_TEMP);
if (mc != NULL)
kmem_free(mc, sizeof(*mc));
return (error);
}
|
3580e4d8224a05a63590e0443a10304f83222133
|
f3eed0234b4d0ad2bbb2abd700cf1e2c7a0e8a1d
|
/AKWF-c/AKWF_stereo/AKWF_stereo_0075.h
|
ca46b50fff1c7458f725acf94f3b7ab42371b0e4
|
[
"CC0-1.0"
] |
permissive
|
KristofferKarlAxelEkstrand/AKWF-FREE
|
b2defa1a2d389d309be6dd2e9f968923daf80d1b
|
cf8171df36e9fec25416b5f568b72a6e2cb69194
|
refs/heads/master
| 2023-07-23T18:22:36.939705
| 2023-07-10T17:14:40
| 2023-07-10T17:14:40
| 145,817,187
| 359
| 59
|
CC0-1.0
| 2023-07-10T17:14:41
| 2018-08-23T07:26:56
| null |
UTF-8
|
C
| false
| false
| 6,478
|
h
|
AKWF_stereo_0075.h
|
/* Adventure Kid Waveforms (AKWF) converted for use with Teensy Audio Library
*
* Adventure Kid Waveforms(AKWF) Open waveforms library
* https://www.adventurekid.se/akrt/waveforms/adventure-kid-waveforms/
*
* This code is in the public domain, CC0 1.0 Universal (CC0 1.0)
* https://creativecommons.org/publicdomain/zero/1.0/
*
* Converted by Brad Roy, https://github.com/prosper00
*/
/* AKWF_stereo_0075 256 samples
+-----------------------------------------------------------------------------------------------------------------+
| ****** ****** |
| **** **** |
| **** *** |
| **** **** |
| *** *** |
| **** **** |
|*** *** |
|* *** *|
| *** ***|
| *** **** |
| *** *** |
| **** *** |
| **** *** |
| **** **** |
| ****** ****** |
+-----------------------------------------------------------------------------------------------------------------+
*/
const uint16_t AKWF_stereo_0075 [] = {
32887, 33391, 33619, 34435, 34421, 35166, 35202, 36029, 35995, 36800, 36774, 37635, 37562, 38415, 38335, 39233,
39114, 40015, 39880, 40818, 40651, 41597, 41407, 42384, 42166, 43156, 42911, 43927, 43657, 44689, 44391, 45444,
45124, 46194, 45846, 46932, 46565, 47666, 47270, 48383, 47969, 49100, 48656, 49799, 49336, 50496, 50003, 51174,
50657, 51850, 51301, 52505, 51932, 53157, 52553, 53790, 53161, 54416, 53758, 55024, 54340, 55623, 54912, 56204,
55470, 56775, 56013, 57329, 56543, 57870, 57060, 58392, 57561, 58902, 58051, 59395, 58524, 59873, 58981, 60333,
59421, 60777, 59851, 61206, 60258, 61615, 60654, 62009, 61025, 62380, 61371, 62727, 61696, 63049, 62000, 63351,
62285, 63629, 62551, 63888, 62799, 64122, 63030, 64339, 63245, 64535, 63443, 64715, 63626, 64874, 63793, 65016,
63939, 65140, 64067, 65245, 64180, 65333, 64274, 65406, 64355, 65462, 64419, 65504, 64466, 65529, 64495, 65535,
64509, 65528, 64505, 65503, 64487, 65464, 64451, 65407, 64397, 65334, 64326, 65244, 64238, 65138, 64131, 65016,
64007, 64874, 63864, 64715, 63701, 64537, 63519, 64340, 63320, 64125, 63098, 63889, 62855, 63632, 62591, 63353,
62304, 63053, 61996, 62730, 61665, 62384, 61308, 62011, 60938, 61622, 60554, 61214, 60154, 60786, 59740, 60344,
59310, 59883, 58866, 59407, 58406, 58914, 57932, 58407, 57442, 57884, 56939, 57345, 56422, 56791, 55891, 56222,
55348, 55639, 54790, 55042, 54220, 54435, 53637, 53813, 53040, 53178, 52433, 52531, 51813, 51872, 51180, 51201,
50534, 50518, 49881, 49826, 49214, 49123, 48539, 48411, 47851, 47689, 47155, 46957, 46448, 46216, 45734, 45469,
45011, 44714, 44280, 43951, 43541, 43182, 42795, 42405, 42045, 41625, 41286, 40836, 40525, 40046, 39758, 39249,
38985, 38449, 38209, 37644, 37427, 36837, 36645, 36029, 35857, 35218, 35070, 34406, 34279, 33591, 33490, 32779,
32701, 31965, 31909, 31152, 31118, 30340, 30331, 29529, 29544, 28721, 28758, 27913, 27977, 27110, 27197, 26311,
26424, 25516, 25653, 24721, 24887, 23935, 24125, 23154, 23372, 22380, 22623, 21610, 21880, 20847, 21144, 20091,
20413, 19343, 19688, 18603, 18971, 17872, 18265, 17151, 17567, 16438, 16879, 15735, 16200, 15042, 15534, 14360,
14880, 13687, 14234, 13029, 13605, 12381, 12983, 11744, 12375, 11121, 11780, 10511, 11197, 9914, 10625, 9330,
10066, 8762, 9524, 8206, 8992, 7667, 8475, 7144, 7974, 6634, 7484, 6141, 7013, 5664, 6556, 5203,
6114, 4759, 5685, 4330, 5277, 3920, 4882, 3528, 4510, 3156, 4165, 2809, 3840, 2487, 3536, 2185,
3251, 1907, 2984, 1649, 2736, 1413, 2506, 1198, 2290, 1000, 2093, 822, 1910, 661, 1744, 519,
1598, 397, 1468, 292, 1356, 202, 1261, 130, 1181, 73, 1117, 31, 1070, 8, 1042, 1,
1026, 7, 1030, 33, 1050, 72, 1084, 129, 1139, 203, 1210, 291, 1298, 397, 1404, 521,
1529, 662, 1672, 821, 1835, 999, 2017, 1196, 2217, 1410, 2437, 1647, 2681, 1904, 2945, 2183,
3231, 2483, 3539, 2807, 3871, 3152, 4228, 3524, 4598, 3914, 4983, 4323, 5382, 4750, 5796, 5193,
6226, 5653, 6670, 6130, 7132, 6621, 7604, 7129, 8093, 7651, 8597, 8191, 9114, 8745, 9645, 9314,
10189, 9897, 10746, 10493, 11316, 11101, 11899, 11723, 12495, 12359, 13102, 13004, 13724, 13666, 14355, 14334,
15001, 15020, 15655, 15708, 16322, 16415, 16997, 17122, 17684, 17850, 18381, 18575, 19088, 19323, 19804, 20064,
20524, 20825, 21258, 21581, 21993, 22358, 22743, 23128, 23488, 23913, 24251, 24698, 25009, 25491, 25781, 26286,
26548, 27086, 27331, 27895, 28103, 28693, 28896, 29514, 29673, 30307, 30473, 31150, 31248, 31913, 32063, 32822,
};
|
72d31c5d02699e17cc0d84048819610fce06e30c
|
fbe68d84e97262d6d26dd65c704a7b50af2b3943
|
/third_party/virtualbox/src/VBox/RDP/client-1.8.4/iso.c
|
740b45f65ef4e626efa1c885959fca8f1b169a38
|
[
"GPL-3.0-only",
"GPL-1.0-or-later",
"GPL-3.0-or-later",
"GPL-2.0-only",
"LGPL-2.0-or-later",
"LicenseRef-scancode-unknown-license-reference",
"CDDL-1.0",
"LicenseRef-scancode-warranty-disclaimer",
"LGPL-2.1-or-later",
"GPL-2.0-or-later",
"MPL-1.0",
"LicenseRef-scancode-generic-exception",
"Apache-2.0",
"OpenSSL",
"MIT"
] |
permissive
|
thalium/icebox
|
c4e6573f2b4f0973b6c7bb0bf068fe9e795fdcfb
|
6f78952d58da52ea4f0e55b2ab297f28e80c1160
|
refs/heads/master
| 2022-08-14T00:19:36.984579
| 2022-02-22T13:10:31
| 2022-02-22T13:10:31
| 190,019,914
| 585
| 109
|
MIT
| 2022-01-13T20:58:15
| 2019-06-03T14:18:12
|
C++
|
UTF-8
|
C
| false
| false
| 8,500
|
c
|
iso.c
|
/* -*- c-basic-offset: 8 -*-
rdesktop: A Remote Desktop Protocol client.
Protocol services - ISO layer
Copyright (C) Matthew Chapman <matthewc.unsw.edu.au> 1999-2008
Copyright 2005-2011 Peter Astrand <astrand@cendio.se> for Cendio AB
Copyright 2012 Henrik Andersson <hean01@cendio.se> for Cendio AB
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 3 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, see <http://www.gnu.org/licenses/>.
*/
/*
* Oracle GPL Disclaimer: For the avoidance of doubt, except that if any license choice
* other than GPL or LGPL is available it will apply instead, Oracle elects to use only
* the General Public License version 2 (GPLv2) at this time for any software where
* a choice of GPL license versions is made available with the language indicating
* that GPLv2 or any later version may be used, or where a choice of which version
* of the GPL is applied is otherwise unspecified.
*/
#include "rdesktop.h"
extern RD_BOOL g_encryption;
extern RD_BOOL g_encryption_initial;
extern RDP_VERSION g_rdp_version;
extern RD_BOOL g_use_password_as_pin;
static RD_BOOL g_negotiate_rdp_protocol = True;
extern char *g_sc_csp_name;
extern char *g_sc_reader_name;
extern char *g_sc_card_name;
extern char *g_sc_container_name;
/* Send a self-contained ISO PDU */
static void
iso_send_msg(uint8 code)
{
STREAM s;
s = tcp_init(11);
out_uint8(s, 3); /* version */
out_uint8(s, 0); /* reserved */
out_uint16_be(s, 11); /* length */
out_uint8(s, 6); /* hdrlen */
out_uint8(s, code);
out_uint16(s, 0); /* dst_ref */
out_uint16(s, 0); /* src_ref */
out_uint8(s, 0); /* class */
s_mark_end(s);
tcp_send(s);
}
static void
iso_send_connection_request(char *username, uint32 neg_proto)
{
STREAM s;
int length = 30 + strlen(username);
if (g_rdp_version >= RDP_V5 && g_negotiate_rdp_protocol)
length += 8;
s = tcp_init(length);
out_uint8(s, 3); /* version */
out_uint8(s, 0); /* reserved */
out_uint16_be(s, length); /* length */
out_uint8(s, length - 5); /* hdrlen */
out_uint8(s, ISO_PDU_CR);
out_uint16(s, 0); /* dst_ref */
out_uint16(s, 0); /* src_ref */
out_uint8(s, 0); /* class */
out_uint8p(s, "Cookie: mstshash=", strlen("Cookie: mstshash="));
out_uint8p(s, username, strlen(username));
out_uint8(s, 0x0d); /* cookie termination string: CR+LF */
out_uint8(s, 0x0a);
if (g_rdp_version >= RDP_V5 && g_negotiate_rdp_protocol)
{
/* optional rdp protocol negotiation request for RDPv5 */
out_uint8(s, RDP_NEG_REQ);
out_uint8(s, 0);
out_uint16(s, 8);
out_uint32(s, neg_proto);
}
s_mark_end(s);
tcp_send(s);
}
/* Receive a message on the ISO layer, return code */
static STREAM
iso_recv_msg(uint8 * code, uint8 * rdpver)
{
STREAM s;
uint16 length;
uint8 version;
s = tcp_recv(NULL, 4);
if (s == NULL)
return NULL;
in_uint8(s, version);
if (rdpver != NULL)
*rdpver = version;
if (version == 3)
{
in_uint8s(s, 1); /* pad */
in_uint16_be(s, length);
}
else
{
in_uint8(s, length);
if (length & 0x80)
{
length &= ~0x80;
next_be(s, length);
}
}
if (length < 4)
{
error("Bad packet header\n");
return NULL;
}
s = tcp_recv(s, length - 4);
if (s == NULL)
return NULL;
if (version != 3)
return s;
in_uint8s(s, 1); /* hdrlen */
in_uint8(s, *code);
if (*code == ISO_PDU_DT)
{
in_uint8s(s, 1); /* eot */
return s;
}
in_uint8s(s, 5); /* dst_ref, src_ref, class */
return s;
}
/* Initialise ISO transport data packet */
STREAM
iso_init(int length)
{
STREAM s;
s = tcp_init(length + 7);
s_push_layer(s, iso_hdr, 7);
return s;
}
/* Send an ISO data PDU */
void
iso_send(STREAM s)
{
uint16 length;
s_pop_layer(s, iso_hdr);
length = s->end - s->p;
out_uint8(s, 3); /* version */
out_uint8(s, 0); /* reserved */
out_uint16_be(s, length);
out_uint8(s, 2); /* hdrlen */
out_uint8(s, ISO_PDU_DT); /* code */
out_uint8(s, 0x80); /* eot */
tcp_send(s);
}
/* Receive ISO transport data packet */
STREAM
iso_recv(uint8 * rdpver)
{
STREAM s;
uint8 code = 0;
s = iso_recv_msg(&code, rdpver);
if (s == NULL)
return NULL;
if (rdpver != NULL)
if (*rdpver != 3)
return s;
if (code != ISO_PDU_DT)
{
error("expected DT, got 0x%x\n", code);
return NULL;
}
return s;
}
/* Establish a connection up to the ISO layer */
RD_BOOL
iso_connect(char *server, char *username, char *domain, char *password,
RD_BOOL reconnect, uint32 * selected_protocol)
{
STREAM s;
uint8 code;
uint32 neg_proto;
g_negotiate_rdp_protocol = True;
neg_proto = PROTOCOL_SSL;
#ifdef WITH_CREDSSP
if (!g_use_password_as_pin)
neg_proto |= PROTOCOL_HYBRID;
else if (g_sc_csp_name || g_sc_reader_name || g_sc_card_name || g_sc_container_name)
neg_proto |= PROTOCOL_HYBRID;
else
warning("Disables CredSSP due to missing smartcard information for SSO.\n");
#endif
retry:
*selected_protocol = PROTOCOL_RDP;
code = 0;
if (!tcp_connect(server))
return False;
iso_send_connection_request(username, neg_proto);
s = iso_recv_msg(&code, NULL);
if (s == NULL)
return False;
if (code != ISO_PDU_CC)
{
error("expected CC, got 0x%x\n", code);
tcp_disconnect();
return False;
}
if (g_rdp_version >= RDP_V5 && s_check_rem(s, 8))
{
/* handle RDP_NEG_REQ response */
const char *reason = NULL;
uint8 type = 0, flags = 0;
uint16 length = 0;
uint32 data = 0;
in_uint8(s, type);
in_uint8(s, flags);
in_uint16(s, length);
in_uint32(s, data);
if (type == RDP_NEG_FAILURE)
{
RD_BOOL retry_without_neg = False;
switch (data)
{
case SSL_WITH_USER_AUTH_REQUIRED_BY_SERVER:
reason = "SSL with user authentication required by server";
break;
case SSL_NOT_ALLOWED_BY_SERVER:
reason = "SSL not allowed by server";
retry_without_neg = True;
break;
case SSL_CERT_NOT_ON_SERVER:
reason = "no valid authentication certificate on server";
retry_without_neg = True;
break;
case INCONSISTENT_FLAGS:
reason = "inconsistent negotiation flags";
break;
case SSL_REQUIRED_BY_SERVER:
reason = "SSL required by server";
break;
case HYBRID_REQUIRED_BY_SERVER:
reason = "CredSSP required by server";
break;
default:
reason = "unknown reason";
}
tcp_disconnect();
if (retry_without_neg)
{
fprintf(stderr,
"Failed to negotiate protocol, retrying with plain RDP.\n");
g_negotiate_rdp_protocol = False;
goto retry;
}
fprintf(stderr, "Failed to connect, %s.\n", reason);
return False;
}
if (type != RDP_NEG_RSP)
{
tcp_disconnect();
error("Expected RDP_NEG_RSP, got type = 0x%x\n", type);
return False;
}
/* handle negotiation response */
if (data == PROTOCOL_SSL)
{
if (!tcp_tls_connect())
{
/* failed to connect using cssp, let retry with plain TLS */
tcp_disconnect();
neg_proto = PROTOCOL_RDP;
goto retry;
}
/* do not use encryption when using TLS */
g_encryption = False;
fprintf(stderr, "Connection established using SSL.\n");
}
#ifdef WITH_CREDSSP
else if (data == PROTOCOL_HYBRID)
{
if (!cssp_connect(server, username, domain, password, s))
{
/* failed to connect using cssp, let retry with plain TLS */
tcp_disconnect();
neg_proto = PROTOCOL_SSL;
goto retry;
}
/* do not use encryption when using TLS */
fprintf(stderr, "Connection established using CredSSP.\n");
g_encryption = False;
}
#endif
else if (data == PROTOCOL_RDP)
{
fprintf(stderr, "Connection established using plain RDP.\n");
}
else if (data != PROTOCOL_RDP)
{
tcp_disconnect();
error("Unexpected protocol in negotiation response, got data = 0x%x.\n",
data);
return False;
}
*selected_protocol = data;
}
return True;
}
/* Disconnect from the ISO layer */
void
iso_disconnect(void)
{
iso_send_msg(ISO_PDU_DR);
tcp_disconnect();
}
/* reset the state to support reconnecting */
void
iso_reset_state(void)
{
g_encryption = g_encryption_initial;
tcp_reset_state();
}
|
6c8240cd7328ebb92363c3a7cfda28389d026359
|
bc3d6594ef6494153fe7006ab63bd5c51ebf5085
|
/libs/curl/docs/examples/cacertinmem.c
|
cf7c76e1445be48418029de1187e8507f18cbadb
|
[
"GPL-1.0-or-later",
"LGPL-2.1-or-later",
"Apache-2.0",
"LicenseRef-scancode-proprietary-license",
"LGPL-2.0-or-later",
"BSD-3-Clause",
"BSD-4-Clause",
"MIT",
"curl"
] |
permissive
|
PacktPublishing/The-Modern-Cpp-Challenge
|
c7b213a53d61fdb253dbc58c84d8c65740621af3
|
6a79f529c038a15c752acb67b4aef7c0d366f1a3
|
refs/heads/master
| 2023-02-02T14:49:38.309156
| 2023-01-30T10:22:25
| 2023-01-30T10:22:25
| 133,945,626
| 301
| 107
|
MIT
| 2021-12-11T18:51:48
| 2018-05-18T11:28:53
|
C
|
UTF-8
|
C
| false
| false
| 6,944
|
c
|
cacertinmem.c
|
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2017, Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.haxx.se/docs/copyright.html.
*
* You 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 COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
/* <DESC>
* CA cert in memory with OpenSSL to get a HTTPS page.
* </DESC>
*/
#include <openssl/err.h>
#include <openssl/ssl.h>
#include <curl/curl.h>
#include <stdio.h>
size_t writefunction(void *ptr, size_t size, size_t nmemb, void *stream)
{
fwrite(ptr, size, nmemb, (FILE *)stream);
return (nmemb*size);
}
static CURLcode sslctx_function(CURL *curl, void *sslctx, void *parm)
{
CURLcode rv = CURLE_ABORTED_BY_CALLBACK;
X509_STORE *store = NULL;
X509 *cert = NULL;
BIO *bio = NULL;
char *mypem =
/* CA for example.com. CN = DigiCert High Assurance EV Root CA */
"-----BEGIN CERTIFICATE-----\n"
"MIIDxTCCAq2gAwIBAgIQAqxcJmoLQJuPC3nyrkYldzANBgkqhkiG9w0BAQUFADBs\n"
"MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3\n"
"d3cuZGlnaWNlcnQuY29tMSswKQYDVQQDEyJEaWdpQ2VydCBIaWdoIEFzc3VyYW5j\n"
"ZSBFViBSb290IENBMB4XDTA2MTExMDAwMDAwMFoXDTMxMTExMDAwMDAwMFowbDEL\n"
"MAkGA1UEBhMCVVMxFTATBgNVBAoTDERpZ2lDZXJ0IEluYzEZMBcGA1UECxMQd3d3\n"
"LmRpZ2ljZXJ0LmNvbTErMCkGA1UEAxMiRGlnaUNlcnQgSGlnaCBBc3N1cmFuY2Ug\n"
"RVYgUm9vdCBDQTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAMbM5XPm\n"
"+9S75S0tMqbf5YE/yc0lSbZxKsPVlDRnogocsF9ppkCxxLeyj9CYpKlBWTrT3JTW\n"
"PNt0OKRKzE0lgvdKpVMSOO7zSW1xkX5jtqumX8OkhPhPYlG++MXs2ziS4wblCJEM\n"
"xChBVfvLWokVfnHoNb9Ncgk9vjo4UFt3MRuNs8ckRZqnrG0AFFoEt7oT61EKmEFB\n"
"Ik5lYYeBQVCmeVyJ3hlKV9Uu5l0cUyx+mM0aBhakaHPQNAQTXKFx01p8VdteZOE3\n"
"hzBWBOURtCmAEvF5OYiiAhF8J2a3iLd48soKqDirCmTCv2ZdlYTBoSUeh10aUAsg\n"
"EsxBu24LUTi4S8sCAwEAAaNjMGEwDgYDVR0PAQH/BAQDAgGGMA8GA1UdEwEB/wQF\n"
"MAMBAf8wHQYDVR0OBBYEFLE+w2kD+L9HAdSYJhoIAu9jZCvDMB8GA1UdIwQYMBaA\n"
"FLE+w2kD+L9HAdSYJhoIAu9jZCvDMA0GCSqGSIb3DQEBBQUAA4IBAQAcGgaX3Nec\n"
"nzyIZgYIVyHbIUf4KmeqvxgydkAQV8GK83rZEWWONfqe/EW1ntlMMUu4kehDLI6z\n"
"eM7b41N5cdblIZQB2lWHmiRk9opmzN6cN82oNLFpmyPInngiK3BD41VHMWEZ71jF\n"
"hS9OMPagMRYjyOfiZRYzy78aG6A9+MpeizGLYAiJLQwGXFK3xPkKmNEVX58Svnw2\n"
"Yzi9RKR/5CYrCsSXaQ3pjOLAEFe4yHYSkVXySGnYvCoCWw9E1CAx2/S6cCZdkGCe\n"
"vEsXCS+0yx5DaMkHJ8HSXPfqIbloEpw8nL+e/IBcm2PN7EeqJSdnoDfzAIJ9VNep\n"
"+OkuE6N36B9K\n"
"-----END CERTIFICATE-----\n";
/* clear the current thread's OpenSSL error queue */
ERR_clear_error();
/* get a BIO */
bio = BIO_new_mem_buf(mypem, -1);
if(!bio)
goto err;
/* use it to read the PEM formatted certificate from memory into an X509
* structure that SSL can use
*/
if(!PEM_read_bio_X509(bio, &cert, 0, NULL))
goto err;
/* get a pointer to the X509 certificate store (which may be empty!) */
store = SSL_CTX_get_cert_store((SSL_CTX *)sslctx);
if(!store)
goto err;
/* add our certificate to this store */
if(!X509_STORE_add_cert(store, cert)) {
unsigned long error = ERR_peek_last_error();
/* Ignore error X509_R_CERT_ALREADY_IN_HASH_TABLE which means the
* certificate is already in the store. That could happen if
* libcurl already loaded the certificate from a ca cert bundle
* set at libcurl build-time or runtime.
*/
if(ERR_GET_LIB(error) != ERR_LIB_X509 ||
ERR_GET_REASON(error) != X509_R_CERT_ALREADY_IN_HASH_TABLE)
goto err;
ERR_clear_error();
}
rv = CURLE_OK;
err:
if(rv != CURLE_OK) {
char errbuf[256];
unsigned long error = ERR_peek_last_error();
fprintf(stderr, "error adding certificate\n");
if(error) {
ERR_error_string_n(error, errbuf, sizeof errbuf);
fprintf(stderr, "%s\n", errbuf);
}
}
X509_free(cert);
BIO_free(bio);
ERR_clear_error();
return rv;
}
int main(void)
{
CURL *ch;
CURLcode rv;
rv = curl_global_init(CURL_GLOBAL_ALL);
ch = curl_easy_init();
rv = curl_easy_setopt(ch, CURLOPT_VERBOSE, 0L);
rv = curl_easy_setopt(ch, CURLOPT_HEADER, 0L);
rv = curl_easy_setopt(ch, CURLOPT_NOPROGRESS, 1L);
rv = curl_easy_setopt(ch, CURLOPT_NOSIGNAL, 1L);
rv = curl_easy_setopt(ch, CURLOPT_WRITEFUNCTION, *writefunction);
rv = curl_easy_setopt(ch, CURLOPT_WRITEDATA, stdout);
rv = curl_easy_setopt(ch, CURLOPT_HEADERFUNCTION, *writefunction);
rv = curl_easy_setopt(ch, CURLOPT_HEADERDATA, stderr);
rv = curl_easy_setopt(ch, CURLOPT_SSLCERTTYPE, "PEM");
rv = curl_easy_setopt(ch, CURLOPT_SSL_VERIFYPEER, 1L);
rv = curl_easy_setopt(ch, CURLOPT_URL, "https://www.example.com/");
/* turn off the default CA locations (optional)
* otherwise libcurl will load CA certificates from the locations that
* were detected/specified at build-time
*/
rv = curl_easy_setopt(ch, CURLOPT_CAINFO, NULL);
rv = curl_easy_setopt(ch, CURLOPT_CAPATH, NULL);
/* first try: retrieve page without ca certificates -> should fail
* unless libcurl was built --with-ca-fallback enabled at build-time
*/
rv = curl_easy_perform(ch);
if(rv == CURLE_OK)
printf("*** transfer succeeded ***\n");
else
printf("*** transfer failed ***\n");
/* use a fresh connection (optional)
* this option seriously impacts performance of multiple transfers but
* it is necessary order to demonstrate this example. recall that the
* ssl ctx callback is only called _before_ an SSL connection is
* established, therefore it will not affect existing verified SSL
* connections already in the connection cache associated with this
* handle. normally you would set the ssl ctx function before making
* any transfers, and not use this option.
*/
rv = curl_easy_setopt(ch, CURLOPT_FRESH_CONNECT, 1L);
/* second try: retrieve page using cacerts' certificate -> will succeed
* load the certificate by installing a function doing the necessary
* "modifications" to the SSL CONTEXT just before link init
*/
rv = curl_easy_setopt(ch, CURLOPT_SSL_CTX_FUNCTION, *sslctx_function);
rv = curl_easy_perform(ch);
if(rv == CURLE_OK)
printf("*** transfer succeeded ***\n");
else
printf("*** transfer failed ***\n");
curl_easy_cleanup(ch);
curl_global_cleanup();
return rv;
}
|
fb57f0af91630346243e9a4c76791cb80fcafdb5
|
59864cbd213b5da6f50d6255b0a021564b3d5bd4
|
/challenges/Filesystem_Command_Shell/src/service.c
|
cf37885ceec0ed9f61bc4d0a63321a0462514b61
|
[
"MIT",
"BSD-3-Clause",
"LicenseRef-scancode-unknown",
"BSD-2-Clause"
] |
permissive
|
trailofbits/cb-multios
|
8af96a4fbc3b34644367faa135347f88e0e0d0a3
|
810d7b24b1f62f56ef49b148fe155b0d0629cad2
|
refs/heads/master
| 2023-09-05T03:56:20.229403
| 2022-12-27T15:47:54
| 2022-12-27T15:47:54
| 41,688,943
| 522
| 133
|
MIT
| 2023-06-29T02:47:13
| 2015-08-31T17:04:31
|
C
|
UTF-8
|
C
| false
| false
| 5,022
|
c
|
service.c
|
/*
Author: Steve Wood <swood@cromulence.com>
Copyright (c) 2016 Cromulence LLC
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include "libcgc.h"
#include "cgc_stdlib.h"
#include "cgc_service.h"
#include "cgc_filesystem.h"
#include "cgc_stdio.h"
#include "cgc_string.h"
#include "cgc_input.h"
#include "cgc_malloc.h"
#define COMMAND_COUNT 10
securityIdType securityID = 0;
int main(int cgc_argc, char *cgc_argv[]) {
char command[1024];
char buffer[100];
char nameBuffer[10];
int retcode;
int unauth = 1;
unsigned int securityToken;
int i;
int argcount;
char **args;
fileHandleType fh;
commandsTableType commands[] = {
{"make", cgc_makeFile },
{"erase", cgc_eraseFile },
{"list", cgc_listFiles },
{"write", cgc_overwriteFile },
{"show", cgc_dumpFile },
{"last", cgc_readFromEnd },
{ "first", cgc_readFirstN },
{ "copy", cgc_copyFile },
{ "perms", cgc_setPermissions },
{ "makememfile", cgc_makeMemFile }
};
retcode = cgc_initFileSystem(4096, 8192, 8192*300);
if (retcode != 0) {
cgc_printf("Error making filesystem\n");
cgc__terminate(-1);
}
retcode = cgc_createFile("README.txt", REGULAR, ROOT_ID);
if ( retcode != 0 ) {
cgc_printf("error making README\n");
cgc__terminate(-1);
}
fh = cgc_openFile("README.txt", ROOT_ID);
if ( fh < 0 ) {
cgc_printf("error making README\n");
cgc__terminate(-1);
}
cgc_strcpy(buffer, "Welcome to the interactive filesystem shell. ");
retcode = cgc_writeFile(fh, buffer, cgc_strlen(buffer), ROOT_ID);
if (retcode < 0 ) {
cgc_printf("error making README\n");
cgc__terminate(-1);
}
cgc_strcpy(buffer, "Valid commands are make, makememfile, erase, list, copy, write, show, first, last, and perms.");
retcode = cgc_writeFile(fh, buffer, cgc_strlen(buffer), ROOT_ID);
if (retcode < 0 ) {
cgc_printf("error making Message of the Day\n");
cgc__terminate(-1);
}
// this should be cgc_read-only but needs to be writable so it can be deleted for the exploit
cgc_setPerms(fh, 3, ROOT_ID);
cgc_closeFile(fh);
cgc_makeMemoryFile("authentication.db", 0x4347C000, 4096, 1, 0 );
while (1) {
if (unauth) {
cgc_printf("login: ");
}
else {
cgc_printf("> ");
}
retcode = cgc_receive_until(command, '\n', sizeof(command));
if (cgc_strlen(command) == 0) {
continue;
}
argcount = cgc_tokenize(command, ' ', &args);
if (unauth) {
if (argcount != 2) {
cgc_free(args);
continue;
}
securityToken = cgc_atoi(args[1]);
securityID = cgc_authenticate(args[0], securityToken);
if (securityID == 0) {
cgc_printf("Invalid login\n");
cgc_free(args);
continue;
}
else {
cgc_printf("Access allowed\n");
cgc_lookupName(nameBuffer, securityID);
cgc_printf("Welcome $s\n", nameBuffer);
}
unauth = 0;
cgc_free(args);
continue;
}
if (cgc_strcmp(args[0], "logout") == 0) {
cgc_printf("bye felicia\n");
unauth = 1;
continue;
}
else if (cgc_strcmp(args[0], "exit") == 0 ) {
break;
}
else {
for ( i= 0; i < COMMAND_COUNT; ++i ) {
if ( cgc_strcmp(args[0], commands[i].command) == 0 ) {
retcode = commands[i].handler(argcount, args);
break;
}
}
if ( i == COMMAND_COUNT && cgc_strlen(args[0]) > 0 ) {
cgc_printf("unknown command $s\n", args[0]);
}
continue;
}
} //while
} // main
|
5451ea68a83dd891fdc3b90f84ae2e6aa310ad31
|
7eaf54a78c9e2117247cb2ab6d3a0c20719ba700
|
/SOFTWARE/A64-TERES/linux-a64/drivers/video/sh7760fb.c
|
5fbb0c7ab0c8e54071c3d463511882a146fb7034
|
[
"Linux-syscall-note",
"GPL-2.0-only",
"GPL-1.0-or-later",
"LicenseRef-scancode-free-unknown",
"Apache-2.0"
] |
permissive
|
OLIMEX/DIY-LAPTOP
|
ae82f4ee79c641d9aee444db9a75f3f6709afa92
|
a3fafd1309135650bab27f5eafc0c32bc3ca74ee
|
refs/heads/rel3
| 2023-08-04T01:54:19.483792
| 2023-04-03T07:18:12
| 2023-04-03T07:18:12
| 80,094,055
| 507
| 92
|
Apache-2.0
| 2023-04-03T07:05:59
| 2017-01-26T07:25:50
|
C
|
UTF-8
|
C
| false
| false
| 14,454
|
c
|
sh7760fb.c
|
/*
* SH7760/SH7763 LCDC Framebuffer driver.
*
* (c) 2006-2008 MSC Vertriebsges.m.b.H.,
* Manuel Lauss <mano@roarinelk.homelinux.net>
* (c) 2008 Nobuhiro Iwamatsu <iwamatsu.nobuhiro@renesas.com>
*
* This file is subject to the terms and conditions of the GNU General
* Public License. See the file COPYING in the main directory of this
* archive for more details.
*
* PLEASE HAVE A LOOK AT Documentation/fb/sh7760fb.txt!
*
* Thanks to Siegfried Schaefer <s.schaefer at schaefer-edv.de>
* for his original source and testing!
*
* sh7760_setcolreg get from drivers/video/sh_mobile_lcdcfb.c
*/
#include <linux/completion.h>
#include <linux/delay.h>
#include <linux/dma-mapping.h>
#include <linux/fb.h>
#include <linux/interrupt.h>
#include <linux/io.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/platform_device.h>
#include <linux/slab.h>
#include <asm/sh7760fb.h>
struct sh7760fb_par {
void __iomem *base;
int irq;
struct sh7760fb_platdata *pd; /* display information */
dma_addr_t fbdma; /* physical address */
int rot; /* rotation enabled? */
u32 pseudo_palette[16];
struct platform_device *dev;
struct resource *ioarea;
struct completion vsync; /* vsync irq event */
};
static irqreturn_t sh7760fb_irq(int irq, void *data)
{
struct completion *c = data;
complete(c);
return IRQ_HANDLED;
}
/* wait_for_lps - wait until power supply has reached a certain state. */
static int wait_for_lps(struct sh7760fb_par *par, int val)
{
int i = 100;
while (--i && ((ioread16(par->base + LDPMMR) & 3) != val))
msleep(1);
if (i <= 0)
return -ETIMEDOUT;
return 0;
}
/* en/disable the LCDC */
static int sh7760fb_blank(int blank, struct fb_info *info)
{
struct sh7760fb_par *par = info->par;
struct sh7760fb_platdata *pd = par->pd;
unsigned short cntr = ioread16(par->base + LDCNTR);
unsigned short intr = ioread16(par->base + LDINTR);
int lps;
if (blank == FB_BLANK_UNBLANK) {
intr |= VINT_START;
cntr = LDCNTR_DON2 | LDCNTR_DON;
lps = 3;
} else {
intr &= ~VINT_START;
cntr = LDCNTR_DON2;
lps = 0;
}
if (pd->blank)
pd->blank(blank);
iowrite16(intr, par->base + LDINTR);
iowrite16(cntr, par->base + LDCNTR);
return wait_for_lps(par, lps);
}
static int sh7760_setcolreg (u_int regno,
u_int red, u_int green, u_int blue,
u_int transp, struct fb_info *info)
{
u32 *palette = info->pseudo_palette;
if (regno >= 16)
return -EINVAL;
/* only FB_VISUAL_TRUECOLOR supported */
red >>= 16 - info->var.red.length;
green >>= 16 - info->var.green.length;
blue >>= 16 - info->var.blue.length;
transp >>= 16 - info->var.transp.length;
palette[regno] = (red << info->var.red.offset) |
(green << info->var.green.offset) |
(blue << info->var.blue.offset) |
(transp << info->var.transp.offset);
return 0;
}
static int sh7760fb_get_color_info(struct device *dev,
u16 lddfr, int *bpp, int *gray)
{
int lbpp, lgray;
lgray = lbpp = 0;
switch (lddfr & LDDFR_COLOR_MASK) {
case LDDFR_1BPP_MONO:
lgray = 1;
lbpp = 1;
break;
case LDDFR_2BPP_MONO:
lgray = 1;
lbpp = 2;
break;
case LDDFR_4BPP_MONO:
lgray = 1;
case LDDFR_4BPP:
lbpp = 4;
break;
case LDDFR_6BPP_MONO:
lgray = 1;
case LDDFR_8BPP:
lbpp = 8;
break;
case LDDFR_16BPP_RGB555:
case LDDFR_16BPP_RGB565:
lbpp = 16;
lgray = 0;
break;
default:
dev_dbg(dev, "unsupported LDDFR bit depth.\n");
return -EINVAL;
}
if (bpp)
*bpp = lbpp;
if (gray)
*gray = lgray;
return 0;
}
static int sh7760fb_check_var(struct fb_var_screeninfo *var,
struct fb_info *info)
{
struct fb_fix_screeninfo *fix = &info->fix;
struct sh7760fb_par *par = info->par;
int ret, bpp;
/* get color info from register value */
ret = sh7760fb_get_color_info(info->dev, par->pd->lddfr, &bpp, NULL);
if (ret)
return ret;
var->bits_per_pixel = bpp;
if ((var->grayscale) && (var->bits_per_pixel == 1))
fix->visual = FB_VISUAL_MONO10;
else if (var->bits_per_pixel >= 15)
fix->visual = FB_VISUAL_TRUECOLOR;
else
fix->visual = FB_VISUAL_PSEUDOCOLOR;
/* TODO: add some more validation here */
return 0;
}
/*
* sh7760fb_set_par - set videomode.
*
* NOTE: The rotation, grayscale and DSTN codepaths are
* totally untested!
*/
static int sh7760fb_set_par(struct fb_info *info)
{
struct sh7760fb_par *par = info->par;
struct fb_videomode *vm = par->pd->def_mode;
unsigned long sbase, dstn_off, ldsarl, stride;
unsigned short hsynp, hsynw, htcn, hdcn;
unsigned short vsynp, vsynw, vtln, vdln;
unsigned short lddfr, ldmtr;
int ret, bpp, gray;
par->rot = par->pd->rotate;
/* rotate only works with xres <= 320 */
if (par->rot && (vm->xres > 320)) {
dev_dbg(info->dev, "rotation disabled due to display size\n");
par->rot = 0;
}
/* calculate LCDC reg vals from display parameters */
hsynp = vm->right_margin + vm->xres;
hsynw = vm->hsync_len;
htcn = vm->left_margin + hsynp + hsynw;
hdcn = vm->xres;
vsynp = vm->lower_margin + vm->yres;
vsynw = vm->vsync_len;
vtln = vm->upper_margin + vsynp + vsynw;
vdln = vm->yres;
/* get color info from register value */
ret = sh7760fb_get_color_info(info->dev, par->pd->lddfr, &bpp, &gray);
if (ret)
return ret;
dev_dbg(info->dev, "%dx%d %dbpp %s (orientation %s)\n", hdcn,
vdln, bpp, gray ? "grayscale" : "color",
par->rot ? "rotated" : "normal");
#ifdef CONFIG_CPU_LITTLE_ENDIAN
lddfr = par->pd->lddfr | (1 << 8);
#else
lddfr = par->pd->lddfr & ~(1 << 8);
#endif
ldmtr = par->pd->ldmtr;
if (!(vm->sync & FB_SYNC_HOR_HIGH_ACT))
ldmtr |= LDMTR_CL1POL;
if (!(vm->sync & FB_SYNC_VERT_HIGH_ACT))
ldmtr |= LDMTR_FLMPOL;
/* shut down LCDC before changing display parameters */
sh7760fb_blank(FB_BLANK_POWERDOWN, info);
iowrite16(par->pd->ldickr, par->base + LDICKR); /* pixclock */
iowrite16(ldmtr, par->base + LDMTR); /* polarities */
iowrite16(lddfr, par->base + LDDFR); /* color/depth */
iowrite16((par->rot ? 1 << 13 : 0), par->base + LDSMR); /* rotate */
iowrite16(par->pd->ldpmmr, par->base + LDPMMR); /* Power Management */
iowrite16(par->pd->ldpspr, par->base + LDPSPR); /* Power Supply Ctrl */
/* display resolution */
iowrite16(((htcn >> 3) - 1) | (((hdcn >> 3) - 1) << 8),
par->base + LDHCNR);
iowrite16(vdln - 1, par->base + LDVDLNR);
iowrite16(vtln - 1, par->base + LDVTLNR);
/* h/v sync signals */
iowrite16((vsynp - 1) | ((vsynw - 1) << 12), par->base + LDVSYNR);
iowrite16(((hsynp >> 3) - 1) | (((hsynw >> 3) - 1) << 12),
par->base + LDHSYNR);
/* AC modulation sig */
iowrite16(par->pd->ldaclnr, par->base + LDACLNR);
stride = (par->rot) ? vtln : hdcn;
if (!gray)
stride *= (bpp + 7) >> 3;
else {
if (bpp == 1)
stride >>= 3;
else if (bpp == 2)
stride >>= 2;
else if (bpp == 4)
stride >>= 1;
/* 6 bpp == 8 bpp */
}
/* if rotated, stride must be power of 2 */
if (par->rot) {
unsigned long bit = 1 << 31;
while (bit) {
if (stride & bit)
break;
bit >>= 1;
}
if (stride & ~bit)
stride = bit << 1; /* not P-o-2, round up */
}
iowrite16(stride, par->base + LDLAOR);
/* set display mem start address */
sbase = (unsigned long)par->fbdma;
if (par->rot)
sbase += (hdcn - 1) * stride;
iowrite32(sbase, par->base + LDSARU);
/*
* for DSTN need to set address for lower half.
* I (mlau) don't know which address to set it to,
* so I guessed at (stride * yres/2).
*/
if (((ldmtr & 0x003f) >= LDMTR_DSTN_MONO_8) &&
((ldmtr & 0x003f) <= LDMTR_DSTN_COLOR_16)) {
dev_dbg(info->dev, " ***** DSTN untested! *****\n");
dstn_off = stride;
if (par->rot)
dstn_off *= hdcn >> 1;
else
dstn_off *= vdln >> 1;
ldsarl = sbase + dstn_off;
} else
ldsarl = 0;
iowrite32(ldsarl, par->base + LDSARL); /* mem for lower half of DSTN */
info->fix.line_length = stride;
sh7760fb_check_var(&info->var, info);
sh7760fb_blank(FB_BLANK_UNBLANK, info); /* panel on! */
dev_dbg(info->dev, "hdcn : %6d htcn : %6d\n", hdcn, htcn);
dev_dbg(info->dev, "hsynw : %6d hsynp : %6d\n", hsynw, hsynp);
dev_dbg(info->dev, "vdln : %6d vtln : %6d\n", vdln, vtln);
dev_dbg(info->dev, "vsynw : %6d vsynp : %6d\n", vsynw, vsynp);
dev_dbg(info->dev, "clksrc: %6d clkdiv: %6d\n",
(par->pd->ldickr >> 12) & 3, par->pd->ldickr & 0x1f);
dev_dbg(info->dev, "ldpmmr: 0x%04x ldpspr: 0x%04x\n", par->pd->ldpmmr,
par->pd->ldpspr);
dev_dbg(info->dev, "ldmtr : 0x%04x lddfr : 0x%04x\n", ldmtr, lddfr);
dev_dbg(info->dev, "ldlaor: %ld\n", stride);
dev_dbg(info->dev, "ldsaru: 0x%08lx ldsarl: 0x%08lx\n", sbase, ldsarl);
return 0;
}
static struct fb_ops sh7760fb_ops = {
.owner = THIS_MODULE,
.fb_blank = sh7760fb_blank,
.fb_check_var = sh7760fb_check_var,
.fb_setcolreg = sh7760_setcolreg,
.fb_set_par = sh7760fb_set_par,
.fb_fillrect = cfb_fillrect,
.fb_copyarea = cfb_copyarea,
.fb_imageblit = cfb_imageblit,
};
static void sh7760fb_free_mem(struct fb_info *info)
{
struct sh7760fb_par *par = info->par;
if (!info->screen_base)
return;
dma_free_coherent(info->dev, info->screen_size,
info->screen_base, par->fbdma);
par->fbdma = 0;
info->screen_base = NULL;
info->screen_size = 0;
}
/* allocate the framebuffer memory. This memory must be in Area3,
* (dictated by the DMA engine) and contiguous, at a 512 byte boundary.
*/
static int sh7760fb_alloc_mem(struct fb_info *info)
{
struct sh7760fb_par *par = info->par;
void *fbmem;
unsigned long vram;
int ret, bpp;
if (info->screen_base)
return 0;
/* get color info from register value */
ret = sh7760fb_get_color_info(info->dev, par->pd->lddfr, &bpp, NULL);
if (ret) {
printk(KERN_ERR "colinfo\n");
return ret;
}
/* min VRAM: xres_min = 16, yres_min = 1, bpp = 1: 2byte -> 1 page
max VRAM: xres_max = 1024, yres_max = 1024, bpp = 16: 2MB */
vram = info->var.xres * info->var.yres;
if (info->var.grayscale) {
if (bpp == 1)
vram >>= 3;
else if (bpp == 2)
vram >>= 2;
else if (bpp == 4)
vram >>= 1;
} else if (bpp > 8)
vram *= 2;
if ((vram < 1) || (vram > 1024 * 2048)) {
dev_dbg(info->dev, "too much VRAM required. Check settings\n");
return -ENODEV;
}
if (vram < PAGE_SIZE)
vram = PAGE_SIZE;
fbmem = dma_alloc_coherent(info->dev, vram, &par->fbdma, GFP_KERNEL);
if (!fbmem)
return -ENOMEM;
if ((par->fbdma & SH7760FB_DMA_MASK) != SH7760FB_DMA_MASK) {
sh7760fb_free_mem(info);
dev_err(info->dev, "kernel gave me memory at 0x%08lx, which is"
"unusable for the LCDC\n", (unsigned long)par->fbdma);
return -ENOMEM;
}
info->screen_base = fbmem;
info->screen_size = vram;
info->fix.smem_start = (unsigned long)info->screen_base;
info->fix.smem_len = info->screen_size;
return 0;
}
static int sh7760fb_probe(struct platform_device *pdev)
{
struct fb_info *info;
struct resource *res;
struct sh7760fb_par *par;
int ret;
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (unlikely(res == NULL)) {
dev_err(&pdev->dev, "invalid resource\n");
return -EINVAL;
}
info = framebuffer_alloc(sizeof(struct sh7760fb_par), &pdev->dev);
if (!info)
return -ENOMEM;
par = info->par;
par->dev = pdev;
par->pd = pdev->dev.platform_data;
if (!par->pd) {
dev_dbg(info->dev, "no display setup data!\n");
ret = -ENODEV;
goto out_fb;
}
par->ioarea = request_mem_region(res->start,
resource_size(res), pdev->name);
if (!par->ioarea) {
dev_err(&pdev->dev, "mmio area busy\n");
ret = -EBUSY;
goto out_fb;
}
par->base = ioremap_nocache(res->start, resource_size(res));
if (!par->base) {
dev_err(&pdev->dev, "cannot remap\n");
ret = -ENODEV;
goto out_res;
}
iowrite16(0, par->base + LDINTR); /* disable vsync irq */
par->irq = platform_get_irq(pdev, 0);
if (par->irq >= 0) {
ret = request_irq(par->irq, sh7760fb_irq, 0,
"sh7760-lcdc", &par->vsync);
if (ret) {
dev_err(&pdev->dev, "cannot grab IRQ\n");
par->irq = -ENXIO;
} else
disable_irq_nosync(par->irq);
}
fb_videomode_to_var(&info->var, par->pd->def_mode);
ret = sh7760fb_alloc_mem(info);
if (ret) {
dev_dbg(info->dev, "framebuffer memory allocation failed!\n");
goto out_unmap;
}
info->pseudo_palette = par->pseudo_palette;
/* fixup color register bitpositions. These are fixed by hardware */
info->var.red.offset = 11;
info->var.red.length = 5;
info->var.red.msb_right = 0;
info->var.green.offset = 5;
info->var.green.length = 6;
info->var.green.msb_right = 0;
info->var.blue.offset = 0;
info->var.blue.length = 5;
info->var.blue.msb_right = 0;
info->var.transp.offset = 0;
info->var.transp.length = 0;
info->var.transp.msb_right = 0;
strcpy(info->fix.id, "sh7760-lcdc");
/* set the DON2 bit now, before cmap allocation, as it will randomize
* palette memory.
*/
iowrite16(LDCNTR_DON2, par->base + LDCNTR);
info->fbops = &sh7760fb_ops;
ret = fb_alloc_cmap(&info->cmap, 256, 0);
if (ret) {
dev_dbg(info->dev, "Unable to allocate cmap memory\n");
goto out_mem;
}
ret = register_framebuffer(info);
if (ret < 0) {
dev_dbg(info->dev, "cannot register fb!\n");
goto out_cmap;
}
platform_set_drvdata(pdev, info);
printk(KERN_INFO "%s: memory at phys 0x%08lx-0x%08lx, size %ld KiB\n",
pdev->name,
(unsigned long)par->fbdma,
(unsigned long)(par->fbdma + info->screen_size - 1),
info->screen_size >> 10);
return 0;
out_cmap:
sh7760fb_blank(FB_BLANK_POWERDOWN, info);
fb_dealloc_cmap(&info->cmap);
out_mem:
sh7760fb_free_mem(info);
out_unmap:
if (par->irq >= 0)
free_irq(par->irq, &par->vsync);
iounmap(par->base);
out_res:
release_mem_region(res->start, resource_size(res));
out_fb:
framebuffer_release(info);
return ret;
}
static int sh7760fb_remove(struct platform_device *dev)
{
struct fb_info *info = platform_get_drvdata(dev);
struct sh7760fb_par *par = info->par;
sh7760fb_blank(FB_BLANK_POWERDOWN, info);
unregister_framebuffer(info);
fb_dealloc_cmap(&info->cmap);
sh7760fb_free_mem(info);
if (par->irq >= 0)
free_irq(par->irq, par);
iounmap(par->base);
release_mem_region(par->ioarea->start, resource_size(par->ioarea));
framebuffer_release(info);
platform_set_drvdata(dev, NULL);
return 0;
}
static struct platform_driver sh7760_lcdc_driver = {
.driver = {
.name = "sh7760-lcdc",
.owner = THIS_MODULE,
},
.probe = sh7760fb_probe,
.remove = sh7760fb_remove,
};
module_platform_driver(sh7760_lcdc_driver);
MODULE_AUTHOR("Nobuhiro Iwamatsu, Manuel Lauss");
MODULE_DESCRIPTION("FBdev for SH7760/63 integrated LCD Controller");
MODULE_LICENSE("GPL");
|
f78c392574585b952c322f5af8c75de96f0536ea
|
29a7a9691c51d070f39a4761d07bff4d9713a331
|
/crates/pdf_io/pdf_io/dpx-tt_glyf.h
|
c92fbd0a939211bd0fbfb9e6d6779c836955f876
|
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
tectonic-typesetting/tectonic
|
07596d8aa5122ead5bc845187c2a80fdeaab7ca3
|
63302695c0f59c6b0bdad2baade12b82a1d74c6d
|
refs/heads/master
| 2023-09-01T10:47:15.090008
| 2023-08-31T16:18:01
| 2023-08-31T16:18:01
| 74,936,681
| 3,648
| 177
|
NOASSERTION
| 2023-09-08T01:49:06
| 2016-11-28T04:17:33
|
C
|
UTF-8
|
C
| false
| false
| 1,883
|
h
|
dpx-tt_glyf.h
|
/* This is dvipdfmx, an eXtended version of dvipdfm by Mark A. Wicks.
Copyright (C) 2002-2016 by Jin-Hwan Cho and Shunsaku Hirata,
the dvipdfmx project team.
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.
*/
#ifndef _TT_GLYF_H_
#define _TT_GLYF_H_
#include "tectonic_bridge_core.h"
#include "dpx-sfnt.h"
struct tt_glyph_desc
{
USHORT gid;
USHORT ogid; /* GID in original font */
USHORT advw, advh;
SHORT lsb, tsb;
SHORT llx, lly, urx, ury;
ULONG length;
BYTE *data;
};
struct tt_glyphs
{
USHORT num_glyphs;
USHORT max_glyphs;
USHORT last_gid;
USHORT emsize;
USHORT dw; /* optimal value for DW */
USHORT default_advh; /* default value */
SHORT default_tsb; /* default value */
struct tt_glyph_desc *gd;
unsigned char *used_slot;
};
struct tt_glyphs *tt_build_init (void);
void tt_build_finish (struct tt_glyphs *g);
USHORT tt_add_glyph (struct tt_glyphs *g, USHORT gid, USHORT new_gid);
USHORT tt_get_index (struct tt_glyphs *g, USHORT gid);
USHORT tt_find_glyph (struct tt_glyphs *g, USHORT gid);
int tt_build_tables (sfnt *sfont, struct tt_glyphs *g);
int tt_get_metrics (sfnt *sfont, struct tt_glyphs *g);
#endif /* _TT_GLYF_H_ */
|
5f98d091665295013ea094cda1a663d6b976e146
|
d9b749e8a4982b8bcd66a19d4ee189fc607ab79e
|
/iterator/iter_donotq.c
|
40ffb45c49aada200d93caba0889a231ede6d4de
|
[
"LicenseRef-scancode-free-unknown",
"GPL-3.0-or-later",
"LicenseRef-scancode-autoconf-simple-exception",
"BSD-3-Clause"
] |
permissive
|
NLnetLabs/unbound
|
26312ae0b3b963f2ab700c4be3d9c45587bcf45e
|
10843805ac37002f1d9293c9835a3e68e41d392d
|
refs/heads/master
| 2023-08-31T23:34:52.610625
| 2023-08-31T11:54:03
| 2023-08-31T11:54:03
| 94,195,301
| 2,526
| 395
|
BSD-3-Clause
| 2023-09-07T14:37:56
| 2017-06-13T09:27:49
|
C
|
UTF-8
|
C
| false
| false
| 4,309
|
c
|
iter_donotq.c
|
/*
* iterator/iter_donotq.c - iterative resolver donotqueryaddresses storage.
*
* Copyright (c) 2007, NLnet Labs. All rights reserved.
*
* This software is open source.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* Neither the name of the NLNET LABS nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
* TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* \file
*
* This file contains functions to assist the iterator module.
* The donotqueryaddresses are stored and looked up. These addresses
* (like 127.0.0.1) must not be used to send queries to, and can be
* discarded immediately from the server selection.
*/
#include "config.h"
#include "iterator/iter_donotq.h"
#include "util/regional.h"
#include "util/log.h"
#include "util/config_file.h"
#include "util/net_help.h"
struct iter_donotq*
donotq_create(void)
{
struct iter_donotq* dq = (struct iter_donotq*)calloc(1,
sizeof(struct iter_donotq));
if(!dq)
return NULL;
dq->region = regional_create();
if(!dq->region) {
donotq_delete(dq);
return NULL;
}
return dq;
}
void
donotq_delete(struct iter_donotq* dq)
{
if(!dq)
return;
regional_destroy(dq->region);
free(dq);
}
/** insert new address into donotq structure */
static int
donotq_insert(struct iter_donotq* dq, struct sockaddr_storage* addr,
socklen_t addrlen, int net)
{
struct addr_tree_node* node = (struct addr_tree_node*)regional_alloc(
dq->region, sizeof(*node));
if(!node)
return 0;
if(!addr_tree_insert(&dq->tree, node, addr, addrlen, net)) {
verbose(VERB_QUERY, "duplicate donotquery address ignored.");
}
return 1;
}
/** apply donotq string */
static int
donotq_str_cfg(struct iter_donotq* dq, const char* str)
{
struct sockaddr_storage addr;
int net;
socklen_t addrlen;
verbose(VERB_ALGO, "donotq: %s", str);
if(!netblockstrtoaddr(str, UNBOUND_DNS_PORT, &addr, &addrlen, &net)) {
log_err("cannot parse donotquery netblock: %s", str);
return 0;
}
if(!donotq_insert(dq, &addr, addrlen, net)) {
log_err("out of memory");
return 0;
}
return 1;
}
/** read donotq config */
static int
read_donotq(struct iter_donotq* dq, struct config_file* cfg)
{
struct config_strlist* p;
for(p = cfg->donotqueryaddrs; p; p = p->next) {
log_assert(p->str);
if(!donotq_str_cfg(dq, p->str))
return 0;
}
return 1;
}
int
donotq_apply_cfg(struct iter_donotq* dq, struct config_file* cfg)
{
regional_free_all(dq->region);
addr_tree_init(&dq->tree);
if(!read_donotq(dq, cfg))
return 0;
if(cfg->donotquery_localhost) {
if(!donotq_str_cfg(dq, "127.0.0.0/8"))
return 0;
if(cfg->do_ip6) {
if(!donotq_str_cfg(dq, "::1"))
return 0;
}
}
addr_tree_init_parents(&dq->tree);
return 1;
}
int
donotq_lookup(struct iter_donotq* donotq, struct sockaddr_storage* addr,
socklen_t addrlen)
{
return addr_tree_lookup(&donotq->tree, addr, addrlen) != NULL;
}
size_t
donotq_get_mem(struct iter_donotq* donotq)
{
if(!donotq) return 0;
return sizeof(*donotq) + regional_get_mem(donotq->region);
}
|
0a69aa9cc88c927e8867e429fda5a5c287700db3
|
5aa8006a9a48e999fa5d5092fe893b16b84b7999
|
/src/main/core/support/config_handlers.h
|
8d6450195fcd8c85b0cd60ec5413a6c2ceb6d873
|
[
"LicenseRef-scancode-public-domain"
] |
permissive
|
shadow/shadow
|
5a18451ac5a288f82f199ea59bc5adb783de9d7d
|
021dbe7672dbfede4c8093ccd260c61cd3986731
|
refs/heads/main
| 2023-09-02T19:47:30.119593
| 2023-09-01T00:18:23
| 2023-09-01T00:18:23
| 1,759,835
| 1,309
| 252
|
NOASSERTION
| 2023-09-14T19:17:48
| 2011-05-17T08:18:57
|
Rust
|
UTF-8
|
C
| false
| false
| 1,079
|
h
|
config_handlers.h
|
#include "main/bindings/c/bindings-opaque.h"
typedef void (*ConfigHandlerFn)(const ConfigOptions*);
void addConfigHandler(ConfigHandlerFn fun_ptr);
void runConfigHandlers(const ConfigOptions* config);
// Used to generate unique symbol names. See
// https://stackoverflow.com/questions/1597007/creating-c-macro-with-and-line-token-concatenation-with-positioning-macr
#define OPTIONS_TOKENPASTE(x, y) x##y
#define OPTIONS_TOKENPASTE2(x, y) OPTIONS_TOKENPASTE(x, y)
#define ADD_CONFIG_HANDLER(config_fn, value) \
static void OPTIONS_TOKENPASTE2(_set_value_, __LINE__)(const ConfigOptions* config) { \
value = config_fn(config); \
} \
__attribute__((constructor)) static void OPTIONS_TOKENPASTE2(_add_entry_, __LINE__)() { \
addConfigHandler(OPTIONS_TOKENPASTE2(_set_value_, __LINE__)); \
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.